psionic 0.3.0 → 0.3.2
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 +321 -0
- package/__tests__/async-functions.ts +43 -0
- package/__tests__/async-generator-functions.ts +137 -0
- package/__tests__/convert-from-wire-format.ts +65 -0
- package/__tests__/convert-to-wire-format.ts +66 -0
- package/__tests__/describe.ts +26 -0
- package/__tests__/lib/adapter.ts +47 -0
- package/docs/extending.md +19 -0
- package/docs/protocol.md +154 -0
- package/examples/cli-chat/client.mjs +21 -0
- package/examples/cli-chat/package.json +17 -0
- package/examples/cli-chat/server.mjs +48 -0
- package/examples/cloudflare/README.md +37 -0
- package/examples/cloudflare/eslint.config.js +19 -0
- package/examples/cloudflare/index.html +13 -0
- package/examples/cloudflare/package.json +29 -0
- package/examples/cloudflare/public/vite.svg +1 -0
- package/examples/cloudflare/src/App.svelte +450 -0
- package/examples/cloudflare/src/api.ts +33 -0
- package/examples/cloudflare/src/main.ts +4 -0
- package/examples/cloudflare/tsconfig.app.json +27 -0
- package/examples/cloudflare/tsconfig.json +14 -0
- package/examples/cloudflare/tsconfig.node.json +26 -0
- package/examples/cloudflare/tsconfig.worker.json +8 -0
- package/examples/cloudflare/vite.config.ts +8 -0
- package/examples/cloudflare/worker/cloudflare.ts +115 -0
- package/examples/cloudflare/worker/index.ts +17 -0
- package/examples/cloudflare/worker/peer.ts +47 -0
- package/examples/cloudflare/worker-configuration.d.ts +10922 -0
- package/examples/cloudflare/wrangler.jsonc +58 -0
- package/examples/nodestreams/adapter.mjs +36 -0
- package/examples/nodestreams/child.mjs +20 -0
- package/examples/nodestreams/package.json +14 -0
- package/examples/nodestreams/parent.mjs +20 -0
- package/examples/reconnect/client.mjs +22 -0
- package/examples/reconnect/package.json +15 -0
- package/examples/reconnect/server.mjs +30 -0
- package/examples/tokens/client.mjs +26 -0
- package/examples/tokens/package.json +20 -0
- package/examples/tokens/server.mjs +46 -0
- package/make-package.js +23 -0
- package/package.json +24 -42
- package/src/adapters/reconnect.ts +54 -0
- package/src/adapters/resend.ts +34 -0
- package/src/adapters/socket.ts +183 -0
- package/src/adapters/websocket.ts +157 -0
- package/src/adapters/webworker.ts +48 -0
- package/src/codecs/cbor.ts +239 -0
- package/src/codecs/psionic.ts +75 -0
- package/src/psionic.ts +876 -0
- package/src/session.ts +164 -0
- package/src/utils/react-hooks.ts +48 -0
- package/tests +8 -0
- package/tsdown.config.ts +19 -0
- package/adapters/reconnect.d.mts +0 -10
- package/adapters/reconnect.mjs +0 -42
- package/adapters/reconnect.mjs.map +0 -1
- package/adapters/resend.d.mts +0 -13
- package/adapters/resend.mjs +0 -29
- package/adapters/resend.mjs.map +0 -1
- package/adapters/socket.d.mts +0 -14
- package/adapters/socket.mjs +0 -160
- package/adapters/socket.mjs.map +0 -1
- package/adapters/websocket.d.mts +0 -20
- package/adapters/websocket.mjs +0 -124
- package/adapters/websocket.mjs.map +0 -1
- package/adapters/webworker.d.mts +0 -8
- package/adapters/webworker.mjs +0 -42
- package/adapters/webworker.mjs.map +0 -1
- package/codecs/cbor.d.mts +0 -12
- package/codecs/cbor.mjs +0 -198
- package/codecs/cbor.mjs.map +0 -1
- package/codecs/psionic.d.mts +0 -12
- package/codecs/psionic.mjs +0 -57
- package/codecs/psionic.mjs.map +0 -1
- package/psionic.d.mts +0 -203
- package/psionic.mjs +0 -671
- package/psionic.mjs.map +0 -1
- package/session.d.mts +0 -63
- package/session.mjs +0 -92
- package/session.mjs.map +0 -1
- package/utils/react-hooks.d.mts +0 -24
- package/utils/react-hooks.mjs +0 -37
- package/utils/react-hooks.mjs.map +0 -1
package/psionic.mjs
DELETED
|
@@ -1,671 +0,0 @@
|
|
|
1
|
-
import { createSession } from "./session.mjs";
|
|
2
|
-
|
|
3
|
-
//#region src/psionic.ts
|
|
4
|
-
/**
|
|
5
|
-
* Psionic - Live-updating, cross-language, bidirectional RPC protocol.
|
|
6
|
-
*/
|
|
7
|
-
const MAX_ID_LENGTH = 64;
|
|
8
|
-
const Keyword = "@@psion";
|
|
9
|
-
let CallContextSymbol = Symbol("call-context");
|
|
10
|
-
const AsyncFnKey = "f";
|
|
11
|
-
const AsyncGenKey = "g";
|
|
12
|
-
const STATE_DISCONNECTED = 0;
|
|
13
|
-
const STATE_CONNECTING = 1;
|
|
14
|
-
const STATE_CONNECTED = 2;
|
|
15
|
-
const STATE_LOCAL_DESCRIBED = 3;
|
|
16
|
-
const STATE_REMOTE_DESCRIBED = 4;
|
|
17
|
-
const STATE_READY = 5;
|
|
18
|
-
const OpDescribe = "D";
|
|
19
|
-
const OpCall = "C";
|
|
20
|
-
const OpOK = "K";
|
|
21
|
-
const OpError = "E";
|
|
22
|
-
const OpIterNext = ".";
|
|
23
|
-
const OpIterReturn = "<";
|
|
24
|
-
const OpIterThrow = ">";
|
|
25
|
-
const Errors = [
|
|
26
|
-
{
|
|
27
|
-
code: 0,
|
|
28
|
-
error: `${Keyword}: Remote error`
|
|
29
|
-
},
|
|
30
|
-
{
|
|
31
|
-
code: 1,
|
|
32
|
-
error: `${Keyword}: No remote assigned`
|
|
33
|
-
},
|
|
34
|
-
{
|
|
35
|
-
code: 2,
|
|
36
|
-
error: `${Keyword}: Disconnected`
|
|
37
|
-
},
|
|
38
|
-
{
|
|
39
|
-
code: 3,
|
|
40
|
-
error: `${Keyword}: Protocol violation`
|
|
41
|
-
},
|
|
42
|
-
{
|
|
43
|
-
code: 4,
|
|
44
|
-
error: `${Keyword}: Function not found`
|
|
45
|
-
},
|
|
46
|
-
{
|
|
47
|
-
code: 5,
|
|
48
|
-
error: `${Keyword}: Expired or invalid`
|
|
49
|
-
},
|
|
50
|
-
{
|
|
51
|
-
code: 6,
|
|
52
|
-
error: `${Keyword}: Rejected`
|
|
53
|
-
}
|
|
54
|
-
];
|
|
55
|
-
const ErrorGeneric = Errors[0];
|
|
56
|
-
const ErrorNoRemote = Errors[1];
|
|
57
|
-
const ErrorDisconnected = Errors[2];
|
|
58
|
-
const ErrorProtocolViolation = Errors[3];
|
|
59
|
-
const ErrorFunctionNotFound = Errors[4];
|
|
60
|
-
const ErrorExpiredOrInvalid = Errors[5];
|
|
61
|
-
const ErrorRejected = Errors[6];
|
|
62
|
-
/** Create a new event emitter instance. */
|
|
63
|
-
function createEventEmitter() {
|
|
64
|
-
const events = {};
|
|
65
|
-
function on(key, listener) {
|
|
66
|
-
if (!events[key]) events[key] = /* @__PURE__ */ new Set();
|
|
67
|
-
events[key].add(listener);
|
|
68
|
-
return () => off(key, listener);
|
|
69
|
-
}
|
|
70
|
-
function emit(key, ...args) {
|
|
71
|
-
if (events[key]) {
|
|
72
|
-
const listeners = Array.from(events[key]);
|
|
73
|
-
for (const listener of listeners) try {
|
|
74
|
-
listener(...args);
|
|
75
|
-
} catch (ex) {
|
|
76
|
-
if (key !== "error") emit("error", ex instanceof Error ? ex : new Error(String(ex)));
|
|
77
|
-
}
|
|
78
|
-
return;
|
|
79
|
-
}
|
|
80
|
-
if (key === "error") console.error(`${Keyword} Unhandled error:`, ...args);
|
|
81
|
-
}
|
|
82
|
-
function off(key, listener) {
|
|
83
|
-
if (events[key]) {
|
|
84
|
-
events[key].delete(listener);
|
|
85
|
-
if (events[key].size === 0) delete events[key];
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
return {
|
|
89
|
-
on,
|
|
90
|
-
emit,
|
|
91
|
-
off
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
|
-
/** Create a new Describer instance, which holds state and emits events when state changes. */
|
|
95
|
-
function createDescription(initialState) {
|
|
96
|
-
let state = initialState;
|
|
97
|
-
const events = createEventEmitter();
|
|
98
|
-
return {
|
|
99
|
-
currentState() {
|
|
100
|
-
return state;
|
|
101
|
-
},
|
|
102
|
-
off: events.off,
|
|
103
|
-
on: events.on,
|
|
104
|
-
describe(stateChange) {
|
|
105
|
-
const prev = state;
|
|
106
|
-
let newState = prev;
|
|
107
|
-
let swapped = true;
|
|
108
|
-
if (typeof stateChange === "function") {
|
|
109
|
-
newState = stateChange(prev);
|
|
110
|
-
swapped = false;
|
|
111
|
-
} else newState = stateChange;
|
|
112
|
-
state = newState;
|
|
113
|
-
if (newState !== prev) events.emit("change", newState, prev, swapped);
|
|
114
|
-
return [
|
|
115
|
-
prev,
|
|
116
|
-
newState,
|
|
117
|
-
swapped
|
|
118
|
-
];
|
|
119
|
-
}
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
/** Create a new disconnected peer instance. */
|
|
123
|
-
function createPeer(opts) {
|
|
124
|
-
const publicEmitter = createEventEmitter();
|
|
125
|
-
const session = opts?.session ?? createSession();
|
|
126
|
-
const peer = {
|
|
127
|
-
readyState: STATE_DISCONNECTED,
|
|
128
|
-
session,
|
|
129
|
-
emit: publicEmitter.emit,
|
|
130
|
-
on: publicEmitter.on,
|
|
131
|
-
off: publicEmitter.off,
|
|
132
|
-
send: sendRawMessage,
|
|
133
|
-
get ready() {
|
|
134
|
-
return peer.readyState === STATE_READY;
|
|
135
|
-
},
|
|
136
|
-
close,
|
|
137
|
-
describe,
|
|
138
|
-
connect,
|
|
139
|
-
sendErrorMessages: opts?.sendErrorMessages ?? false,
|
|
140
|
-
receiveErrorMessages: opts?.receiveErrorMessages ?? false,
|
|
141
|
-
connection: void 0,
|
|
142
|
-
handleMessage
|
|
143
|
-
};
|
|
144
|
-
peer.remote = session.remoteDescription ? fromCodecDescription(peer, session.remoteDescription) : peer.remote;
|
|
145
|
-
if (opts?.description) peer.local = opts.description;
|
|
146
|
-
const describer = createDescription(peer.local);
|
|
147
|
-
async function describe(stateChange) {
|
|
148
|
-
const [prevState, newState, swap] = describer.describe(stateChange);
|
|
149
|
-
peer.local = newState;
|
|
150
|
-
if (peer.readyState < STATE_CONNECTED) return;
|
|
151
|
-
peer.session.localDescription = toCodecDescription(newState);
|
|
152
|
-
const diff = swap ? newState ?? {} : diffDescriptions(prevState ?? {}, newState ?? {});
|
|
153
|
-
if (diff === null) return;
|
|
154
|
-
const encoded = toCodecDescription(diff);
|
|
155
|
-
try {
|
|
156
|
-
await sendAndWait(peer, OpDescribe, encoded, swap || void 0);
|
|
157
|
-
} catch (ex) {
|
|
158
|
-
close(new OperationError(ErrorProtocolViolation));
|
|
159
|
-
throw ex;
|
|
160
|
-
}
|
|
161
|
-
if (peer.readyState === STATE_REMOTE_DESCRIBED) peer.readyState = STATE_READY;
|
|
162
|
-
else if (peer.readyState < STATE_LOCAL_DESCRIBED) peer.readyState = STATE_LOCAL_DESCRIBED;
|
|
163
|
-
peer.emit("readyStateChange", peer.readyState);
|
|
164
|
-
}
|
|
165
|
-
async function connect(newConnection, waitForRemoteDescribe = true) {
|
|
166
|
-
close(null);
|
|
167
|
-
let previousLocal = peer.local;
|
|
168
|
-
peer.readyState = STATE_CONNECTING;
|
|
169
|
-
let previousConnection = peer.connection;
|
|
170
|
-
const connection = await newConnection(peer);
|
|
171
|
-
if (peer.connection !== previousConnection || peer.readyState !== STATE_CONNECTING) {
|
|
172
|
-
connection.close();
|
|
173
|
-
return;
|
|
174
|
-
}
|
|
175
|
-
peer.connection = connection;
|
|
176
|
-
peer.local = previousLocal ?? opts?.description;
|
|
177
|
-
peer.readyState = STATE_CONNECTED;
|
|
178
|
-
peer.emit("readyStateChange", peer.readyState);
|
|
179
|
-
if (peer.local) await describe(peer.local);
|
|
180
|
-
if (waitForRemoteDescribe !== false) await waitUntilRemoteReady(peer);
|
|
181
|
-
}
|
|
182
|
-
function close(err) {
|
|
183
|
-
if (peer.readyState === STATE_DISCONNECTED) return;
|
|
184
|
-
peer.readyState = STATE_DISCONNECTED;
|
|
185
|
-
peer.emit("readyStateChange", peer.readyState);
|
|
186
|
-
if (peer.connection) peer.connection.close(err);
|
|
187
|
-
}
|
|
188
|
-
function sendRawMessage(type, ...message) {
|
|
189
|
-
if (!peer.connection) throw new OperationError(ErrorNoRemote);
|
|
190
|
-
const msg = [type, ...message];
|
|
191
|
-
peer.connection.send(msg);
|
|
192
|
-
peer.emit("send", msg);
|
|
193
|
-
}
|
|
194
|
-
function handleMessage(msg) {
|
|
195
|
-
peer.emit("message", msg);
|
|
196
|
-
handleIncomingMessage(peer, msg).catch((ex) => {
|
|
197
|
-
peer.emit("error", ex instanceof Error ? ex : new Error(String(ex)));
|
|
198
|
-
});
|
|
199
|
-
}
|
|
200
|
-
return peer;
|
|
201
|
-
}
|
|
202
|
-
/** Resolves when remote has described itself. Rejects on disconnect. */
|
|
203
|
-
function waitUntilRemoteReady(peer) {
|
|
204
|
-
return new Promise(function(resolve, reject) {
|
|
205
|
-
if (peer.readyState >= STATE_REMOTE_DESCRIBED) return resolve();
|
|
206
|
-
const cleanup = peer.on("readyStateChange", readyStateChange);
|
|
207
|
-
function readyStateChange(readyState) {
|
|
208
|
-
if (readyState >= STATE_REMOTE_DESCRIBED) {
|
|
209
|
-
cleanup();
|
|
210
|
-
resolve();
|
|
211
|
-
}
|
|
212
|
-
if (readyState === STATE_DISCONNECTED) {
|
|
213
|
-
cleanup();
|
|
214
|
-
reject(new OperationError(ErrorDisconnected));
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
});
|
|
218
|
-
}
|
|
219
|
-
/** Converts a local description to wire-safe codec format (functions → sentinel symbols). */
|
|
220
|
-
function toCodecDescription(description) {
|
|
221
|
-
const seen = /* @__PURE__ */ new WeakSet();
|
|
222
|
-
function replacer(v) {
|
|
223
|
-
const value = v?.[CallContextSymbol] ?? v;
|
|
224
|
-
if (isAsyncGeneratorLike(value)) return { [Keyword]: AsyncGenKey };
|
|
225
|
-
if (typeof value === "function") return { [Keyword]: AsyncFnKey };
|
|
226
|
-
if (value && typeof value === "object") {
|
|
227
|
-
if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) throw new OperationError(ErrorProtocolViolation);
|
|
228
|
-
const result = Array.isArray(value) ? [] : {};
|
|
229
|
-
if (seen.has(value)) throw new OperationError(ErrorProtocolViolation);
|
|
230
|
-
seen.add(value);
|
|
231
|
-
for (const key of Object.keys(value)) {
|
|
232
|
-
if (key === Keyword) throw new OperationError(ErrorProtocolViolation);
|
|
233
|
-
result[key] = replacer(value[key]);
|
|
234
|
-
}
|
|
235
|
-
return result;
|
|
236
|
-
}
|
|
237
|
-
return value;
|
|
238
|
-
}
|
|
239
|
-
return replacer(description ?? {});
|
|
240
|
-
}
|
|
241
|
-
/** Converts a wire-format description into a usable object (sentinel symbols → invoker functions). */
|
|
242
|
-
function fromCodecDescription(peer, description) {
|
|
243
|
-
const seen = /* @__PURE__ */ new WeakSet();
|
|
244
|
-
function replacer(value, currentPath = []) {
|
|
245
|
-
if (value?.[Keyword] === AsyncGenKey) return createAsyncGeneratorFunction(peer, currentPath);
|
|
246
|
-
if (value?.[Keyword] === AsyncFnKey) return createAsyncFunction(peer, currentPath);
|
|
247
|
-
if (typeof value === "function") throw new OperationError(ErrorProtocolViolation);
|
|
248
|
-
if (value && typeof value === "object") {
|
|
249
|
-
if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) throw new OperationError(ErrorProtocolViolation);
|
|
250
|
-
if (seen.has(value)) throw new OperationError(ErrorProtocolViolation);
|
|
251
|
-
seen.add(value);
|
|
252
|
-
const result = Array.isArray(value) ? [] : {};
|
|
253
|
-
for (const key of Object.keys(value)) result[key] = replacer(value[key], [...currentPath, key]);
|
|
254
|
-
return result;
|
|
255
|
-
}
|
|
256
|
-
return value;
|
|
257
|
-
}
|
|
258
|
-
return replacer(description ?? {});
|
|
259
|
-
}
|
|
260
|
-
const AsyncGeneratorFunction = (async function* () {});
|
|
261
|
-
/** Creates a local async generator that proxies iteration to the remote. */
|
|
262
|
-
function createAsyncGeneratorFunction(peer, name) {
|
|
263
|
-
function wrappedAsyncGeneratorFunction(...args) {
|
|
264
|
-
let _operationId = null;
|
|
265
|
-
let closed = false;
|
|
266
|
-
function wrapped(fn) {
|
|
267
|
-
return (value) => {
|
|
268
|
-
if (closed) return {
|
|
269
|
-
value: void 0,
|
|
270
|
-
done: true
|
|
271
|
-
};
|
|
272
|
-
try {
|
|
273
|
-
return fn(value).catch(handleError);
|
|
274
|
-
} catch (err) {
|
|
275
|
-
handleError(err);
|
|
276
|
-
throw err;
|
|
277
|
-
}
|
|
278
|
-
};
|
|
279
|
-
function handleError(err) {
|
|
280
|
-
if (_operationId && !closed) {
|
|
281
|
-
const error = safeSendError(peer, err);
|
|
282
|
-
sendAndWait(peer, OpIterThrow, _operationId, error.code, error.error).catch(() => {});
|
|
283
|
-
}
|
|
284
|
-
closed = true;
|
|
285
|
-
throw err;
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
const nexter = wrapped(async (sendValue) => {
|
|
289
|
-
const [value, done] = await sendAndWait(peer, OpIterNext, await operationId(), sendValue);
|
|
290
|
-
if (done) closed = true;
|
|
291
|
-
return {
|
|
292
|
-
value,
|
|
293
|
-
done: !!done
|
|
294
|
-
};
|
|
295
|
-
});
|
|
296
|
-
const thrower = wrapped(async (err) => {
|
|
297
|
-
const error = safeSendError(peer, err);
|
|
298
|
-
const [value, done] = await sendAndWait(peer, OpIterThrow, await operationId(), error.code, error.error);
|
|
299
|
-
if (done) closed = true;
|
|
300
|
-
return {
|
|
301
|
-
value,
|
|
302
|
-
done: !!done
|
|
303
|
-
};
|
|
304
|
-
});
|
|
305
|
-
const returner = wrapped(async (value) => {
|
|
306
|
-
closed = true;
|
|
307
|
-
await sendAndWait(peer, OpIterReturn, await operationId(), value).catch(() => {});
|
|
308
|
-
return {
|
|
309
|
-
value,
|
|
310
|
-
done: true
|
|
311
|
-
};
|
|
312
|
-
});
|
|
313
|
-
let iterator = {
|
|
314
|
-
[Symbol.asyncIterator]() {
|
|
315
|
-
return this;
|
|
316
|
-
},
|
|
317
|
-
next: nexter,
|
|
318
|
-
throw: thrower,
|
|
319
|
-
return: returner
|
|
320
|
-
};
|
|
321
|
-
async function operationId() {
|
|
322
|
-
if (_operationId || closed) return _operationId;
|
|
323
|
-
try {
|
|
324
|
-
return _operationId = await sendAndWait(peer, OpCall, name, args);
|
|
325
|
-
} catch (err) {
|
|
326
|
-
closed = true;
|
|
327
|
-
throw err;
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
return iterator;
|
|
331
|
-
}
|
|
332
|
-
return markAsAsyncGenerator(wrappedAsyncGeneratorFunction);
|
|
333
|
-
}
|
|
334
|
-
/** Marks a function as an async generator, setting the appropriate properties. */
|
|
335
|
-
function markAsAsyncGenerator(wrappedAsyncGeneratorFunction) {
|
|
336
|
-
Object.defineProperties(wrappedAsyncGeneratorFunction, {
|
|
337
|
-
[Symbol.toStringTag]: {
|
|
338
|
-
value: AsyncGeneratorFunction[Symbol.toStringTag],
|
|
339
|
-
writable: true
|
|
340
|
-
},
|
|
341
|
-
prototype: {
|
|
342
|
-
value: AsyncGeneratorFunction.prototype,
|
|
343
|
-
writable: true
|
|
344
|
-
},
|
|
345
|
-
constructor: {
|
|
346
|
-
value: AsyncGeneratorFunction.constructor,
|
|
347
|
-
writable: true
|
|
348
|
-
}
|
|
349
|
-
});
|
|
350
|
-
return wrappedAsyncGeneratorFunction;
|
|
351
|
-
}
|
|
352
|
-
/** Sanitizes an error for sending, respecting sendErrorMessages policy. */
|
|
353
|
-
function safeSendError(peer, error) {
|
|
354
|
-
const code = typeof error === "string" ? ErrorGeneric.code : error.code ?? ErrorGeneric.code;
|
|
355
|
-
if (!peer.sendErrorMessages) return {
|
|
356
|
-
code,
|
|
357
|
-
error: (Errors[code] ?? ErrorGeneric).error
|
|
358
|
-
};
|
|
359
|
-
if (typeof error === "object") return {
|
|
360
|
-
code: error.code ?? 0,
|
|
361
|
-
error: error.message
|
|
362
|
-
};
|
|
363
|
-
if (typeof error === "string") return {
|
|
364
|
-
code: ErrorGeneric.code,
|
|
365
|
-
error
|
|
366
|
-
};
|
|
367
|
-
return ErrorGeneric;
|
|
368
|
-
}
|
|
369
|
-
/** Sanitizes a received error, respecting receiveErrorMessages policy. */
|
|
370
|
-
function safeReceiveError(peer, error) {
|
|
371
|
-
let code = typeof error === "string" ? ErrorGeneric.code : error.code ?? ErrorGeneric.code;
|
|
372
|
-
if (peer.receiveErrorMessages) return new OperationError(typeof error === "string" ? error : error.message ?? Errors[code]?.error ?? ErrorGeneric.error, code);
|
|
373
|
-
return new OperationError((Errors[code] ?? ErrorGeneric).error, code);
|
|
374
|
-
}
|
|
375
|
-
/** Creates a local async function that proxies calls to the remote. */
|
|
376
|
-
function createAsyncFunction(peer, name, waitForPeer = true) {
|
|
377
|
-
return async function wrappedAsyncFunction(...args) {
|
|
378
|
-
if (waitForPeer) await waitUntilRemoteReady(peer);
|
|
379
|
-
return await sendAndWait(peer, OpCall, name, args);
|
|
380
|
-
};
|
|
381
|
-
}
|
|
382
|
-
/** Sends a frame and returns a promise that resolves when the remote responds. */
|
|
383
|
-
function sendAndWait(peer, type, ...message) {
|
|
384
|
-
return new Promise(function(resolve, reject) {
|
|
385
|
-
if (!peer.connection) return reject(new OperationError(ErrorNoRemote));
|
|
386
|
-
let operation;
|
|
387
|
-
try {
|
|
388
|
-
operation = peer.session.add("outbound-call", {
|
|
389
|
-
resolve,
|
|
390
|
-
reject
|
|
391
|
-
}, reject);
|
|
392
|
-
peer.send(type, operation.id, ...message);
|
|
393
|
-
} catch (ex) {
|
|
394
|
-
operation?.cleanup();
|
|
395
|
-
reject(ex);
|
|
396
|
-
}
|
|
397
|
-
});
|
|
398
|
-
}
|
|
399
|
-
const messageHandler = {
|
|
400
|
-
async [OpDescribe](peer, _session, id, description, swap) {
|
|
401
|
-
if (typeof description !== "object" || description === null || Array.isArray(description) || swap !== void 0 && swap !== null && typeof swap !== "boolean") throw new OperationError(ErrorProtocolViolation);
|
|
402
|
-
const mapped = fromCodecDescription(peer, description);
|
|
403
|
-
peer.remote = { ...swap ? mapped : mergeDescriptions(peer.remote, mapped) };
|
|
404
|
-
peer.session.remoteDescription = toCodecDescription(peer.remote);
|
|
405
|
-
let prevReadyState = peer.readyState;
|
|
406
|
-
if (peer.readyState === STATE_LOCAL_DESCRIBED) peer.readyState = STATE_READY;
|
|
407
|
-
else if (peer.readyState < STATE_REMOTE_DESCRIBED) peer.readyState = STATE_REMOTE_DESCRIBED;
|
|
408
|
-
if (prevReadyState !== peer.readyState) peer.emit("readyStateChange", peer.readyState);
|
|
409
|
-
peer.emit("describe", peer.remote);
|
|
410
|
-
peer.send(OpOK, id);
|
|
411
|
-
},
|
|
412
|
-
async [OpCall](peer, session, id, name, args) {
|
|
413
|
-
if (!Array.isArray(name) || !Array.isArray(args)) throw new OperationError(ErrorProtocolViolation);
|
|
414
|
-
await handleInvocation(peer, session, id, name, args);
|
|
415
|
-
},
|
|
416
|
-
[OpOK](_peer, session, id, result) {
|
|
417
|
-
const operation = session.use("outbound-call", id);
|
|
418
|
-
if (!operation) return;
|
|
419
|
-
operation.cleanup();
|
|
420
|
-
operation.context.resolve(result);
|
|
421
|
-
},
|
|
422
|
-
[OpError](peer, session, id, code, error) {
|
|
423
|
-
if (typeof code !== "number") {
|
|
424
|
-
peer.close();
|
|
425
|
-
return;
|
|
426
|
-
}
|
|
427
|
-
const errorObj = safeReceiveError(peer, {
|
|
428
|
-
code,
|
|
429
|
-
message: error
|
|
430
|
-
});
|
|
431
|
-
const operation = session.use(void 0, id);
|
|
432
|
-
if (!operation) return;
|
|
433
|
-
operation.reject(errorObj);
|
|
434
|
-
},
|
|
435
|
-
async [OpIterNext](peer, session, id, operationId, value) {
|
|
436
|
-
return await withGenerator(peer, session, id, operationId, async (operation) => {
|
|
437
|
-
const result = await operation.context.generator.next(value);
|
|
438
|
-
if (result.done) operation.cleanup();
|
|
439
|
-
return [result.value, result.done ? 1 : 0];
|
|
440
|
-
});
|
|
441
|
-
},
|
|
442
|
-
async [OpIterReturn](peer, session, id, operationId, value) {
|
|
443
|
-
return await withGenerator(peer, session, id, operationId, async (operation) => {
|
|
444
|
-
const asyncGenerator = operation.context.generator;
|
|
445
|
-
operation.cleanup();
|
|
446
|
-
const result = await asyncGenerator.return(value);
|
|
447
|
-
return [result.value, result.done ? 1 : 0];
|
|
448
|
-
}, false);
|
|
449
|
-
},
|
|
450
|
-
async [OpIterThrow](peer, session, id, operationId, code, error) {
|
|
451
|
-
if (typeof code !== "number" || error !== void 0 && typeof error !== "string") throw new OperationError(ErrorProtocolViolation);
|
|
452
|
-
return await withGenerator(peer, session, id, operationId, async (operation) => {
|
|
453
|
-
const err = safeReceiveError(peer, {
|
|
454
|
-
code,
|
|
455
|
-
message: error
|
|
456
|
-
});
|
|
457
|
-
const result = await operation.context.generator.throw(err);
|
|
458
|
-
if (result.done) operation.cleanup();
|
|
459
|
-
return [result.value, result.done ? 1 : 0];
|
|
460
|
-
});
|
|
461
|
-
}
|
|
462
|
-
};
|
|
463
|
-
/** Executes an operation on an in-flight generator with protocol validation. */
|
|
464
|
-
async function withGenerator(peer, session, id, operationId, fn, preventReentry = true) {
|
|
465
|
-
if (!isValidID(operationId)) throw new OperationError(ErrorProtocolViolation);
|
|
466
|
-
const operation = session.use("generator", operationId);
|
|
467
|
-
if (!operation) throw new OperationError(ErrorExpiredOrInvalid);
|
|
468
|
-
if (!exists()) {
|
|
469
|
-
const err = new OperationError(ErrorFunctionNotFound);
|
|
470
|
-
operation.reject(err);
|
|
471
|
-
throw err;
|
|
472
|
-
}
|
|
473
|
-
if (operation.context.busy && preventReentry) throw new OperationError(ErrorProtocolViolation);
|
|
474
|
-
try {
|
|
475
|
-
operation.context.busy = true;
|
|
476
|
-
const result = await fn(operation);
|
|
477
|
-
if (!exists()) {
|
|
478
|
-
operation.reject(new OperationError(ErrorFunctionNotFound));
|
|
479
|
-
return peer.send(OpOK, id, [void 0, 1]);
|
|
480
|
-
} else peer.send(OpOK, id, result);
|
|
481
|
-
} catch (ex) {
|
|
482
|
-
operation.cleanup();
|
|
483
|
-
sendError(peer, id, ex?.code, ex);
|
|
484
|
-
throw ex;
|
|
485
|
-
} finally {
|
|
486
|
-
operation.context.busy = false;
|
|
487
|
-
}
|
|
488
|
-
function exists() {
|
|
489
|
-
return lookupFunction(peer.local, operation.context.name) === operation?.context.target;
|
|
490
|
-
}
|
|
491
|
-
}
|
|
492
|
-
function sendError(peer, id, inCode, error) {
|
|
493
|
-
const str = error?.error ?? error?.message ?? error;
|
|
494
|
-
const code = (typeof error === "object" && typeof error.code === "number" ? error.code : inCode) ?? ErrorGeneric.code;
|
|
495
|
-
if (peer.readyState >= STATE_CONNECTED) {
|
|
496
|
-
const sanitized = safeSendError(peer, {
|
|
497
|
-
code,
|
|
498
|
-
message: str
|
|
499
|
-
});
|
|
500
|
-
peer.send(OpError, id, sanitized.code, sanitized.error);
|
|
501
|
-
return;
|
|
502
|
-
}
|
|
503
|
-
if (code !== ErrorNoRemote.code) peer.emit("error", new OperationError(String(str ?? Errors[code]?.error ?? ErrorGeneric.error), code));
|
|
504
|
-
}
|
|
505
|
-
/** Routes an incoming frame to the appropriate handler. */
|
|
506
|
-
async function handleIncomingMessage(peer, data) {
|
|
507
|
-
if (!Array.isArray(data) || typeof data[0] !== "string" || data[0].length !== 1) return;
|
|
508
|
-
if (!isValidID(data[1])) throw new OperationError(ErrorProtocolViolation);
|
|
509
|
-
const handler = messageHandler[data[0]];
|
|
510
|
-
if (!handler) return;
|
|
511
|
-
try {
|
|
512
|
-
return await handler(peer, peer.session, ...data.slice(1));
|
|
513
|
-
} catch (err) {
|
|
514
|
-
if (data[0] === OpError) {
|
|
515
|
-
peer.emit("error", err);
|
|
516
|
-
return;
|
|
517
|
-
}
|
|
518
|
-
const error = safeSendError(peer, err);
|
|
519
|
-
try {
|
|
520
|
-
peer.send(OpError, data[1], error.code, error.error);
|
|
521
|
-
} catch {}
|
|
522
|
-
throw err;
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
/** Resolves a dotted function path against a description object. */
|
|
526
|
-
function lookupFunction(origin, name) {
|
|
527
|
-
if (origin === void 0 || origin === null) return null;
|
|
528
|
-
let target = origin;
|
|
529
|
-
for (let i = 0; target && i < name.length; ++i) if (Object.prototype.hasOwnProperty.call(target, name[i])) target = target[name[i]];
|
|
530
|
-
else return null;
|
|
531
|
-
if (typeof target !== "function") return null;
|
|
532
|
-
return target;
|
|
533
|
-
}
|
|
534
|
-
/** Wraps a function to automatically provide a call context. */
|
|
535
|
-
function withContext(fn) {
|
|
536
|
-
const fail = () => {
|
|
537
|
-
throw new Error("withContext functions cannot be wrapped.");
|
|
538
|
-
};
|
|
539
|
-
fail[CallContextSymbol] = fn;
|
|
540
|
-
return fail;
|
|
541
|
-
}
|
|
542
|
-
/** Handles an incoming RPC call or generator creation. */
|
|
543
|
-
async function handleInvocation(peer, session, id, name, args) {
|
|
544
|
-
let operation = void 0;
|
|
545
|
-
try {
|
|
546
|
-
let target = lookupFunction(peer.local, name);
|
|
547
|
-
if (!target || typeof target !== "function") throw new OperationError(ErrorFunctionNotFound);
|
|
548
|
-
const cctx = {
|
|
549
|
-
peer,
|
|
550
|
-
id
|
|
551
|
-
};
|
|
552
|
-
let callArgs = args;
|
|
553
|
-
if (CallContextSymbol in target) {
|
|
554
|
-
callArgs = [cctx, ...args];
|
|
555
|
-
target = target[CallContextSymbol];
|
|
556
|
-
}
|
|
557
|
-
let complete = false;
|
|
558
|
-
if (isAsyncGeneratorLike(target)) {
|
|
559
|
-
let context = {
|
|
560
|
-
target,
|
|
561
|
-
name
|
|
562
|
-
};
|
|
563
|
-
operation = session.add("generator", context, function(_err) {
|
|
564
|
-
if (complete || !context.generator) return;
|
|
565
|
-
complete = true;
|
|
566
|
-
context.generator.return(void 0).catch(() => {});
|
|
567
|
-
});
|
|
568
|
-
cctx.operation = operation;
|
|
569
|
-
if (!operation) return peer.send(OpError, id, ErrorRejected.code, ErrorRejected.error);
|
|
570
|
-
context.generator = target(...callArgs);
|
|
571
|
-
peer.send(OpOK, id, operation.id);
|
|
572
|
-
} else {
|
|
573
|
-
operation = session.add("inbound-call", void 0, (err) => {
|
|
574
|
-
if (complete) return;
|
|
575
|
-
complete = true;
|
|
576
|
-
try {
|
|
577
|
-
sendError(peer, id, err?.code ?? ErrorGeneric.code, err);
|
|
578
|
-
} catch (ex) {}
|
|
579
|
-
});
|
|
580
|
-
cctx.operation = operation;
|
|
581
|
-
if (!operation) return peer.send(OpError, id, ErrorRejected.code, ErrorRejected.error);
|
|
582
|
-
const result = await Promise.resolve().then(() => target(...callArgs));
|
|
583
|
-
if (complete) return;
|
|
584
|
-
complete = true;
|
|
585
|
-
operation.cleanup();
|
|
586
|
-
peer.send(OpOK, id, result);
|
|
587
|
-
}
|
|
588
|
-
} catch (ex) {
|
|
589
|
-
if (operation) operation.cleanup();
|
|
590
|
-
sendError(peer, id, ex?.code ?? ErrorGeneric.code, ex);
|
|
591
|
-
throw ex;
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
var OperationError = class extends Error {
|
|
595
|
-
code;
|
|
596
|
-
constructor(ex, code) {
|
|
597
|
-
if (typeof ex === "string") {
|
|
598
|
-
super(ex);
|
|
599
|
-
this.code = code ?? ErrorGeneric.code;
|
|
600
|
-
} else {
|
|
601
|
-
super(ex.error);
|
|
602
|
-
this.code = code ?? ex.code;
|
|
603
|
-
}
|
|
604
|
-
}
|
|
605
|
-
};
|
|
606
|
-
function isAsyncGeneratorLike(value) {
|
|
607
|
-
if (typeof value !== "function") return false;
|
|
608
|
-
if (value.constructor?.name === "AsyncGeneratorFunction") return true;
|
|
609
|
-
if (value.prototype?.[Symbol.asyncIterator]) return true;
|
|
610
|
-
return false;
|
|
611
|
-
}
|
|
612
|
-
/** Returns a shallow diff of two descriptions, or null if unchanged. */
|
|
613
|
-
function diffDescriptions(prev, next) {
|
|
614
|
-
const stack = [{
|
|
615
|
-
prev,
|
|
616
|
-
next,
|
|
617
|
-
path: []
|
|
618
|
-
}];
|
|
619
|
-
const diffResult = {};
|
|
620
|
-
let changed = false;
|
|
621
|
-
while (stack.length > 0) {
|
|
622
|
-
const { prev, next, path } = stack.pop();
|
|
623
|
-
if (prev === next) continue;
|
|
624
|
-
if (typeof prev === "function" && typeof next === "function" && isAsyncGeneratorLike(prev) === isAsyncGeneratorLike(next)) continue;
|
|
625
|
-
else if (Array.isArray(prev) && Array.isArray(next)) {
|
|
626
|
-
if (prev.length !== next.length) {
|
|
627
|
-
changed = true;
|
|
628
|
-
addChange(next);
|
|
629
|
-
} else if (prev.some((item, index) => item !== next[index])) {
|
|
630
|
-
changed = true;
|
|
631
|
-
addChange(next);
|
|
632
|
-
}
|
|
633
|
-
} else if (typeof prev === "object" && typeof next === "object" && prev !== null && next !== null) {
|
|
634
|
-
const allKeys = new Set([...Object.keys(prev), ...Object.keys(next)]);
|
|
635
|
-
for (const key of allKeys) stack.push({
|
|
636
|
-
prev: prev[key],
|
|
637
|
-
next: next[key],
|
|
638
|
-
path: [...path, key]
|
|
639
|
-
});
|
|
640
|
-
} else {
|
|
641
|
-
changed = true;
|
|
642
|
-
addChange(next);
|
|
643
|
-
}
|
|
644
|
-
function addChange(next) {
|
|
645
|
-
let current = diffResult;
|
|
646
|
-
for (let i = 0; i < path.length - 1; ++i) {
|
|
647
|
-
if (!(path[i] in current)) current[path[i]] = {};
|
|
648
|
-
current = current[path[i]];
|
|
649
|
-
}
|
|
650
|
-
current[path[path.length - 1]] = next ?? null;
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
if (!changed) return null;
|
|
654
|
-
return diffResult;
|
|
655
|
-
}
|
|
656
|
-
/** Deep-merges a patch into a description. Null values delete keys. */
|
|
657
|
-
function mergeDescriptions(original, patch) {
|
|
658
|
-
const result = { ...original };
|
|
659
|
-
for (const [key, value] of Object.entries(patch)) if (value === null || value === void 0) delete result[key];
|
|
660
|
-
else if (Array.isArray(value) || Array.isArray(result[key])) result[key] = value;
|
|
661
|
-
else if (typeof value === "object" && value !== null && typeof result[key] === "object" && result[key] !== null) result[key] = mergeDescriptions(result[key], value);
|
|
662
|
-
else result[key] = value;
|
|
663
|
-
return result;
|
|
664
|
-
}
|
|
665
|
-
function isValidID(id) {
|
|
666
|
-
return typeof id === "string" && id.length > 0 && id.length < MAX_ID_LENGTH;
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
//#endregion
|
|
670
|
-
export { AsyncFnKey, AsyncGenKey, CallContextSymbol, ErrorDisconnected, ErrorExpiredOrInvalid, ErrorFunctionNotFound, ErrorGeneric, ErrorNoRemote, ErrorProtocolViolation, ErrorRejected, Errors, Keyword, OpCall, OpDescribe, OpError, OpIterNext, OpIterReturn, OpIterThrow, OpOK, OperationError, STATE_CONNECTED, STATE_CONNECTING, STATE_DISCONNECTED, STATE_LOCAL_DESCRIBED, STATE_READY, STATE_REMOTE_DESCRIBED, createAsyncFunction, createAsyncGeneratorFunction, createDescription, createEventEmitter, createPeer, fromCodecDescription, isAsyncGeneratorLike, markAsAsyncGenerator, mergeDescriptions, toCodecDescription, waitUntilRemoteReady, withContext };
|
|
671
|
-
//# sourceMappingURL=psionic.mjs.map
|