psionic 0.3.2 → 0.3.4
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/adapters/reconnect.d.mts +10 -0
- package/adapters/reconnect.mjs +42 -0
- package/adapters/reconnect.mjs.map +1 -0
- package/adapters/resend.d.mts +13 -0
- package/adapters/resend.mjs +26 -0
- package/adapters/resend.mjs.map +1 -0
- package/adapters/socket.d.mts +14 -0
- package/adapters/socket.mjs +160 -0
- package/adapters/socket.mjs.map +1 -0
- package/adapters/websocket.d.mts +21 -0
- package/adapters/websocket.mjs +135 -0
- package/adapters/websocket.mjs.map +1 -0
- package/adapters/webworker.d.mts +8 -0
- package/adapters/webworker.mjs +42 -0
- package/adapters/webworker.mjs.map +1 -0
- package/codecs/cbor.d.mts +12 -0
- package/codecs/cbor.mjs +198 -0
- package/codecs/cbor.mjs.map +1 -0
- package/codecs/psionic.d.mts +12 -0
- package/codecs/psionic.mjs +57 -0
- package/codecs/psionic.mjs.map +1 -0
- package/package.json +42 -24
- package/psionic.d.mts +203 -0
- package/psionic.mjs +671 -0
- package/psionic.mjs.map +1 -0
- package/session.d.mts +63 -0
- package/session.mjs +92 -0
- package/session.mjs.map +1 -0
- package/utils/react-hooks.d.mts +24 -0
- package/utils/react-hooks.mjs +37 -0
- package/utils/react-hooks.mjs.map +1 -0
- package/README.md +0 -321
- package/__tests__/async-functions.ts +0 -43
- package/__tests__/async-generator-functions.ts +0 -137
- package/__tests__/convert-from-wire-format.ts +0 -65
- package/__tests__/convert-to-wire-format.ts +0 -66
- package/__tests__/describe.ts +0 -26
- package/__tests__/lib/adapter.ts +0 -47
- package/docs/extending.md +0 -19
- package/docs/protocol.md +0 -154
- package/examples/cli-chat/client.mjs +0 -21
- package/examples/cli-chat/package.json +0 -17
- package/examples/cli-chat/server.mjs +0 -48
- package/examples/cloudflare/README.md +0 -37
- package/examples/cloudflare/eslint.config.js +0 -19
- package/examples/cloudflare/index.html +0 -13
- package/examples/cloudflare/package.json +0 -29
- package/examples/cloudflare/public/vite.svg +0 -1
- package/examples/cloudflare/src/App.svelte +0 -450
- package/examples/cloudflare/src/api.ts +0 -33
- package/examples/cloudflare/src/main.ts +0 -4
- package/examples/cloudflare/tsconfig.app.json +0 -27
- package/examples/cloudflare/tsconfig.json +0 -14
- package/examples/cloudflare/tsconfig.node.json +0 -26
- package/examples/cloudflare/tsconfig.worker.json +0 -8
- package/examples/cloudflare/vite.config.ts +0 -8
- package/examples/cloudflare/worker/cloudflare.ts +0 -115
- package/examples/cloudflare/worker/index.ts +0 -17
- package/examples/cloudflare/worker/peer.ts +0 -47
- package/examples/cloudflare/worker-configuration.d.ts +0 -10922
- package/examples/cloudflare/wrangler.jsonc +0 -58
- package/examples/nodestreams/adapter.mjs +0 -36
- package/examples/nodestreams/child.mjs +0 -20
- package/examples/nodestreams/package.json +0 -14
- package/examples/nodestreams/parent.mjs +0 -20
- package/examples/reconnect/client.mjs +0 -22
- package/examples/reconnect/package.json +0 -15
- package/examples/reconnect/server.mjs +0 -30
- package/examples/tokens/client.mjs +0 -26
- package/examples/tokens/package.json +0 -20
- package/examples/tokens/server.mjs +0 -46
- package/make-package.js +0 -23
- package/src/adapters/reconnect.ts +0 -54
- package/src/adapters/resend.ts +0 -34
- package/src/adapters/socket.ts +0 -183
- package/src/adapters/websocket.ts +0 -157
- package/src/adapters/webworker.ts +0 -48
- package/src/codecs/cbor.ts +0 -239
- package/src/codecs/psionic.ts +0 -75
- package/src/psionic.ts +0 -876
- package/src/session.ts +0 -164
- package/src/utils/react-hooks.ts +0 -48
- package/tests +0 -8
- package/tsdown.config.ts +0 -19
package/codecs/cbor.mjs
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { AsyncFnKey, AsyncGenKey } from "../psionic.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/codecs/cbor.ts
|
|
4
|
+
const TAG_ASYNC_FN = 32768;
|
|
5
|
+
const TAG_ASYNC_GEN = 32769;
|
|
6
|
+
const cborCodec = function(options) {
|
|
7
|
+
const maxEntities = options?.maxEntities ?? 4096;
|
|
8
|
+
function messageToWire(message) {
|
|
9
|
+
const scratch = new Uint8Array(16);
|
|
10
|
+
const scratchView = new DataView(scratch.buffer);
|
|
11
|
+
let output = new Uint8Array(512);
|
|
12
|
+
let at = 0;
|
|
13
|
+
function ensureSpace(bytes) {
|
|
14
|
+
if (at + bytes <= output.length) return;
|
|
15
|
+
let newsize = output.length * 2;
|
|
16
|
+
while (newsize < at + bytes) newsize *= 2;
|
|
17
|
+
if (newsize >= 50331648) throw new Error("Message too large to encode");
|
|
18
|
+
const newBuffer = new Uint8Array(newsize);
|
|
19
|
+
newBuffer.set(output);
|
|
20
|
+
output = newBuffer;
|
|
21
|
+
}
|
|
22
|
+
function append(bytes) {
|
|
23
|
+
ensureSpace(bytes.length);
|
|
24
|
+
output.set(bytes, at);
|
|
25
|
+
at += bytes.length;
|
|
26
|
+
}
|
|
27
|
+
const encoder = new TextEncoder();
|
|
28
|
+
function writeItem(item) {
|
|
29
|
+
if (typeof item === "number" && Number.isInteger(item) && item >= 0) writeUInt(0, item);
|
|
30
|
+
else if (typeof item === "number" && Number.isInteger(item) && item < 0) writeUInt(1, -1 - item);
|
|
31
|
+
else if (typeof item === "string") {
|
|
32
|
+
const bytes = encoder.encode(item);
|
|
33
|
+
writeUInt(3, bytes.length);
|
|
34
|
+
ensureSpace(bytes.length);
|
|
35
|
+
output.set(bytes, at);
|
|
36
|
+
at += bytes.length;
|
|
37
|
+
} else if (Array.isArray(item)) {
|
|
38
|
+
writeUInt(4, item.length);
|
|
39
|
+
for (const subitem of item) writeItem(subitem);
|
|
40
|
+
} else if (item === AsyncFnKey) {
|
|
41
|
+
writeUInt(6, TAG_ASYNC_FN);
|
|
42
|
+
append([246]);
|
|
43
|
+
} else if (item === AsyncGenKey) {
|
|
44
|
+
writeUInt(6, TAG_ASYNC_GEN);
|
|
45
|
+
append([246]);
|
|
46
|
+
} else if (item && typeof item === "object") {
|
|
47
|
+
const entries = Object.entries(item);
|
|
48
|
+
writeUInt(5, entries.length);
|
|
49
|
+
for (const [key, value] of entries) {
|
|
50
|
+
const keyBytes = encoder.encode(key);
|
|
51
|
+
writeUInt(3, keyBytes.length);
|
|
52
|
+
ensureSpace(keyBytes.length);
|
|
53
|
+
output.set(keyBytes, at);
|
|
54
|
+
at += keyBytes.length;
|
|
55
|
+
writeItem(value);
|
|
56
|
+
}
|
|
57
|
+
} else if (item === false) append([244]);
|
|
58
|
+
else if (item === true) append([245]);
|
|
59
|
+
else if (item === null) append([246]);
|
|
60
|
+
else if (item === void 0) append([247]);
|
|
61
|
+
else if (typeof item === "number") {
|
|
62
|
+
const f32 = Math.fround(item);
|
|
63
|
+
let bytes = 8;
|
|
64
|
+
if (Number.isFinite(f32) && f32 === item) bytes = 4;
|
|
65
|
+
ensureSpace(bytes + 1);
|
|
66
|
+
if (bytes === 4) scratchView.setFloat32(0, item, false);
|
|
67
|
+
else scratchView.setFloat64(0, item, false);
|
|
68
|
+
output[at++] = 224 | (bytes === 4 ? 26 : 27);
|
|
69
|
+
for (let i = 0; i < bytes; i++) output[at++] = scratch[i];
|
|
70
|
+
} else throw new Error("Unsupported type");
|
|
71
|
+
}
|
|
72
|
+
writeItem(message);
|
|
73
|
+
return output.subarray(0, at);
|
|
74
|
+
function writeUInt(majorTypeValue, num) {
|
|
75
|
+
const majorType = majorTypeValue << 5;
|
|
76
|
+
if (num < 24) {
|
|
77
|
+
append([majorType | num]);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
let length = 0;
|
|
81
|
+
if (num > 4294967295) length = 3;
|
|
82
|
+
else if (num > 65535) length = 2;
|
|
83
|
+
else if (num > 255) length = 1;
|
|
84
|
+
const bytesNeeded = [
|
|
85
|
+
1,
|
|
86
|
+
2,
|
|
87
|
+
4,
|
|
88
|
+
8
|
|
89
|
+
][length];
|
|
90
|
+
if (bytesNeeded === 1) scratchView.setUint8(0, num);
|
|
91
|
+
else if (bytesNeeded === 2) scratchView.setUint16(0, num, false);
|
|
92
|
+
else if (bytesNeeded === 4) scratchView.setUint32(0, num, false);
|
|
93
|
+
else if (bytesNeeded === 8) scratchView.setBigUint64(0, BigInt(num), false);
|
|
94
|
+
else throw new Error("Number too large for encoding");
|
|
95
|
+
ensureSpace(bytesNeeded + 1);
|
|
96
|
+
output[at++] = majorType | length + 24;
|
|
97
|
+
for (let i = 0; i < bytesNeeded; i++) output[at++] = scratch[i];
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function messageFromWire(data) {
|
|
101
|
+
function ensureBytes(bytes) {
|
|
102
|
+
if (i + bytes > wire.length) throw new Error("CBOR - Unexpected end of data");
|
|
103
|
+
}
|
|
104
|
+
const wire = typeof data === "string" ? new TextEncoder().encode(data) : data;
|
|
105
|
+
const view = new DataView(wire.buffer, wire.byteOffset, wire.byteLength);
|
|
106
|
+
const decoder = new TextDecoder();
|
|
107
|
+
let i = 0, entities = 0;
|
|
108
|
+
return takeNextValue();
|
|
109
|
+
function takeNextValue() {
|
|
110
|
+
if (entities > maxEntities) throw new Error("CBOR - Maximum entities exceeded");
|
|
111
|
+
entities += 1;
|
|
112
|
+
ensureBytes(1);
|
|
113
|
+
let value = null;
|
|
114
|
+
const majorType = (wire[i] & 224) >> 5;
|
|
115
|
+
const minorType = wire[i] & 31;
|
|
116
|
+
if (majorType === 0) value = takeUInt(minorType);
|
|
117
|
+
else if (majorType === 1) value = -1 - takeUInt(minorType);
|
|
118
|
+
else if (majorType === 3) {
|
|
119
|
+
let length = takeUInt(minorType);
|
|
120
|
+
ensureBytes(length);
|
|
121
|
+
value = decoder.decode(wire.subarray(i, i + length));
|
|
122
|
+
i += length;
|
|
123
|
+
} else if (majorType === 4) {
|
|
124
|
+
const length = takeUInt(minorType);
|
|
125
|
+
value = [];
|
|
126
|
+
for (let j = 0; j < length; j++) {
|
|
127
|
+
const item = takeNextValue();
|
|
128
|
+
value.push(item);
|
|
129
|
+
}
|
|
130
|
+
} else if (majorType === 5) {
|
|
131
|
+
const length = takeUInt(minorType);
|
|
132
|
+
value = {};
|
|
133
|
+
for (let j = 0; j < length; j++) {
|
|
134
|
+
const key = String(takeNextValue());
|
|
135
|
+
const val = takeNextValue();
|
|
136
|
+
value[key] = val;
|
|
137
|
+
}
|
|
138
|
+
} else if (majorType === 6) {
|
|
139
|
+
const tag = takeUInt(minorType);
|
|
140
|
+
const taggedvalue = takeNextValue();
|
|
141
|
+
if (tag === TAG_ASYNC_FN) return AsyncFnKey;
|
|
142
|
+
if (tag === TAG_ASYNC_GEN) return AsyncGenKey;
|
|
143
|
+
return taggedvalue;
|
|
144
|
+
} else if (majorType === 7) if (minorType === 20) value = false;
|
|
145
|
+
else if (minorType === 21) value = true;
|
|
146
|
+
else if (minorType === 22) value = null;
|
|
147
|
+
else if (minorType === 23) value = void 0;
|
|
148
|
+
else if (minorType === 26) {
|
|
149
|
+
ensureBytes(5);
|
|
150
|
+
i += 1;
|
|
151
|
+
value = view.getFloat32(i, false);
|
|
152
|
+
i += 4;
|
|
153
|
+
} else if (minorType === 27) {
|
|
154
|
+
ensureBytes(9);
|
|
155
|
+
i += 1;
|
|
156
|
+
value = view.getFloat64(i, false);
|
|
157
|
+
i += 8;
|
|
158
|
+
} else throw new Error("CBOR - Unsupported simple value");
|
|
159
|
+
else throw new Error("CBOR - Unsupported major type " + majorType.toString(2).padStart(3, "0"));
|
|
160
|
+
return value;
|
|
161
|
+
}
|
|
162
|
+
function takeUInt(minorType) {
|
|
163
|
+
if (minorType < 24) {
|
|
164
|
+
i += 1;
|
|
165
|
+
return minorType;
|
|
166
|
+
}
|
|
167
|
+
const bytes = [
|
|
168
|
+
1,
|
|
169
|
+
2,
|
|
170
|
+
4,
|
|
171
|
+
8
|
|
172
|
+
][minorType - 24];
|
|
173
|
+
if (bytes === void 0) throw new Error("CBOR - Integer too large to decode");
|
|
174
|
+
ensureBytes(bytes + 1);
|
|
175
|
+
let num;
|
|
176
|
+
i += 1;
|
|
177
|
+
if (bytes === 1) num = view.getUint8(i);
|
|
178
|
+
else if (bytes === 2) num = view.getUint16(i, false);
|
|
179
|
+
else if (bytes === 4) num = view.getUint32(i, false);
|
|
180
|
+
else if (bytes === 8) {
|
|
181
|
+
const bigNum = view.getBigUint64(i, false);
|
|
182
|
+
if (bigNum > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error("CBOR - Number too large to safely represent in JavaScript");
|
|
183
|
+
num = Number(bigNum);
|
|
184
|
+
} else throw new Error("CBOR - Unsupported integer byte length");
|
|
185
|
+
i += bytes;
|
|
186
|
+
return num;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return {
|
|
190
|
+
type: "binary",
|
|
191
|
+
messageFromWire,
|
|
192
|
+
messageToWire
|
|
193
|
+
};
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
//#endregion
|
|
197
|
+
export { cborCodec };
|
|
198
|
+
//# sourceMappingURL=cbor.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cbor.mjs","names":[],"sources":["../../src/codecs/cbor.ts"],"sourcesContent":["import { AsyncFnKey, AsyncGenKey } from \"../../src/psionic\";\n\nconst TAG_ASYNC_FN = 32768;\nconst TAG_ASYNC_GEN = 32769;\n\nexport type CborCodecOptions = {\n /** Max entities per message. Default: 4096. */\n maxEntities?: number;\n}\n\nexport const cborCodec = function (options?: CborCodecOptions) {\n const maxEntities = options?.maxEntities ?? 0x1000;\n\n function messageToWire(message: any[]): Uint8Array {\n const scratch = new Uint8Array(0x10);\n const scratchView = new DataView(scratch.buffer);\n let output = new Uint8Array(0x200);\n let at = 0;\n function ensureSpace(bytes: number) {\n if (at + bytes <= output.length) return;\n let newsize = output.length * 2;\n while (newsize < at + bytes) newsize *= 2;\n if (newsize >= 0x3000000) {\n throw new Error('Message too large to encode');\n }\n const newBuffer = new Uint8Array(newsize);\n newBuffer.set(output);\n output = newBuffer;\n }\n function append(bytes: number[]) {\n ensureSpace(bytes.length);\n output.set(bytes, at);\n at += bytes.length;\n }\n const encoder = new TextEncoder();\n function writeItem(item: any) {\n if (typeof item === 'number' && Number.isInteger(item) && item >= 0) {\n writeUInt(0b000, item);\n } else if (typeof item === 'number' && Number.isInteger(item) && item < 0) {\n writeUInt(0b001, -1 - item);\n } else if (typeof item === 'string') {\n const bytes = encoder.encode(item);\n writeUInt(0b011, bytes.length);\n ensureSpace(bytes.length);\n output.set(bytes, at);\n at += bytes.length;\n } else if (Array.isArray(item)) {\n writeUInt(0b100, item.length);\n for (const subitem of item) {\n writeItem(subitem);\n }\n } else if (item === AsyncFnKey) {\n writeUInt(0b110, TAG_ASYNC_FN);\n append([(0b111 << 5) | 22]); // null payload — only the tag matters\n } else if (item === AsyncGenKey) {\n writeUInt(0b110, TAG_ASYNC_GEN);\n append([(0b111 << 5) | 22]); // null payload — only the tag matters\n } else if (item && typeof item === 'object') {\n const entries = Object.entries(item);\n writeUInt(0b101, entries.length);\n for (const [key, value] of entries) {\n const keyBytes = encoder.encode(key);\n writeUInt(0b011, keyBytes.length);\n ensureSpace(keyBytes.length);\n output.set(keyBytes, at);\n at += keyBytes.length;\n writeItem(value);\n }\n } else if (item === false) {\n append([0b111 << 5 | 20]);\n } else if (item === true) {\n append([0b111 << 5 | 21]);\n } else if (item === null) {\n append([0b111 << 5 | 22]);\n } else if (item === undefined) {\n append([0b111 << 5 | 23]);\n } else if (typeof item === 'number') {\n const f32 = Math.fround(item);\n let bytes = 8;\n if (Number.isFinite(f32) && f32 === item) {\n bytes = 4;\n }\n ensureSpace(bytes + 1);\n if (bytes === 4) scratchView.setFloat32(0, item, false);\n else scratchView.setFloat64(0, item, false);\n output[at++] = (0b111 << 5) | (bytes === 4 ? 26 : 27);\n for (let i = 0; i < bytes; i++) output[at++] = scratch[i];\n } else {\n throw new Error('Unsupported type');\n }\n }\n writeItem(message);\n return output.subarray(0, at);\n\n function writeUInt(majorTypeValue: number, num: number) {\n const majorType = majorTypeValue << 5;\n if (num < 24) {\n append([majorType | num]);\n return;\n }\n\n let length = 0;\n if (num > 0xFFFFFFFF) {\n length = 3;\n } else if (num > 0xFFFF) {\n length = 2;\n } else if (num > 0xFF) {\n length = 1;\n }\n const bytesNeeded = [1,2,4,8][length];\n if (bytesNeeded === 1) {\n scratchView.setUint8(0, num);\n } else if (bytesNeeded === 2) {\n scratchView.setUint16(0, num, false);\n } else if (bytesNeeded === 4) {\n scratchView.setUint32(0, num, false);\n } else if (bytesNeeded === 8) {\n scratchView.setBigUint64(0, BigInt(num), false);\n } else {\n throw new Error('Number too large for encoding');\n }\n ensureSpace(bytesNeeded + 1);\n output[at++] = majorType | (length + 24);\n for (let i = 0; i < bytesNeeded; i++) output[at++] = scratch[i];\n }\n };\n\n function messageFromWire(data: string | Uint8Array): any {\n function ensureBytes(bytes: number) {\n if (i + bytes > wire.length) {\n throw new Error('CBOR - Unexpected end of data');\n }\n }\n const wire = typeof data === 'string' ? new TextEncoder().encode(data) : data;\n const view = new DataView(wire.buffer, wire.byteOffset, wire.byteLength);\n const decoder = new TextDecoder();\n let i = 0, entities = 0;\n const result = takeNextValue();\n return result;\n\n function takeNextValue(): any {\n if (entities > maxEntities) throw new Error('CBOR - Maximum entities exceeded');\n entities += 1;\n ensureBytes(1);\n let value: any = null;\n const majorType = (wire[i] & 0b11100000) >> 5;\n const minorType = (wire[i] & 0b00011111);\n if (majorType === 0b000) {\n value = takeUInt(minorType);\n } else if (majorType === 0b001) {\n value = -1 - takeUInt(minorType);\n } else if (majorType === 0b011) {\n let length = takeUInt(minorType);\n ensureBytes(length);\n value = decoder.decode(wire.subarray(i, i + length));\n i += length;\n } else if (majorType === 0b100) {\n const length = takeUInt(minorType);\n value = [];\n for (let j = 0; j < length; j++) {\n const item = takeNextValue();\n value.push(item);\n }\n } else if (majorType === 0b101) {\n const length = takeUInt(minorType);\n value = {};\n for (let j = 0; j < length; j++) {\n const key = String(takeNextValue());\n const val = takeNextValue();\n value[key] = val;\n }\n } else if (majorType === 0b110) {\n const tag = takeUInt(minorType);\n const taggedvalue = takeNextValue();\n if (tag === TAG_ASYNC_FN) return AsyncFnKey;\n if (tag === TAG_ASYNC_GEN) return AsyncGenKey;\n return taggedvalue;\n } else if (majorType === 0b111) {\n if (minorType === 20) value = false;\n else if (minorType === 21) value = true;\n else if (minorType === 22) value = null;\n else if (minorType === 23) value = undefined;\n else if (minorType === 26) {\n ensureBytes(5);\n i += 1;\n value = view.getFloat32(i, false);\n i += 4;\n } else if (minorType === 27) {\n ensureBytes(9);\n i += 1;\n value = view.getFloat64(i, false);\n i += 8;\n } else {\n throw new Error('CBOR - Unsupported simple value');\n }\n } else {\n throw new Error('CBOR - Unsupported major type ' + majorType.toString(2).padStart(3, '0'));\n }\n return value;\n }\n\n function takeUInt(minorType: number): number {\n if (minorType < 24) {\n i += 1;\n return minorType;\n }\n\n const addl = minorType - 24;\n const bytes = [1,2,4,8][addl];\n if (bytes === undefined) throw new Error('CBOR - Integer too large to decode');\n ensureBytes(bytes + 1);\n let num: number;\n i += 1;\n if (bytes === 1) {\n num = view.getUint8(i);\n } else if (bytes === 2) {\n num = view.getUint16(i, false);\n } else if (bytes === 4) {\n num = view.getUint32(i, false);\n } else if (bytes === 8) {\n const bigNum = view.getBigUint64(i, false);\n if (bigNum > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new Error('CBOR - Number too large to safely represent in JavaScript');\n }\n num = Number(bigNum);\n } else {\n throw new Error('CBOR - Unsupported integer byte length');\n }\n i += bytes;\n return num;\n }\n }\n\n return {\n type: 'binary' as const,\n messageFromWire,\n messageToWire\n };\n}\n"],"mappings":";;;AAEA,MAAM,eAAgB;AACtB,MAAM,gBAAgB;AAOtB,MAAa,YAAY,SAAU,SAA4B;CAC3D,MAAM,cAAc,SAAS,eAAe;CAE5C,SAAS,cAAc,SAA4B;EAC/C,MAAM,UAAU,IAAI,WAAW,GAAK;EACpC,MAAM,cAAc,IAAI,SAAS,QAAQ,OAAO;EAChD,IAAI,SAAS,IAAI,WAAW,IAAM;EAClC,IAA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;EACA;EACH"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
//#region src/codecs/psionic.d.ts
|
|
2
|
+
type PsionicCodecOptions = {
|
|
3
|
+
/** Max entities per message. Default: 4096. */maxEntities?: number;
|
|
4
|
+
};
|
|
5
|
+
declare const psionicCodec: (options?: PsionicCodecOptions) => {
|
|
6
|
+
type: "text";
|
|
7
|
+
messageFromWire: (data: Uint8Array | string) => any;
|
|
8
|
+
messageToWire: (message: any[]) => Uint8Array | string;
|
|
9
|
+
};
|
|
10
|
+
//#endregion
|
|
11
|
+
export { PsionicCodecOptions, psionicCodec };
|
|
12
|
+
//# sourceMappingURL=psionic.d.mts.map
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { ErrorProtocolViolation, Keyword, OperationError } from "../psionic.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/codecs/psionic.ts
|
|
4
|
+
const psionicCodec = (options = {}) => {
|
|
5
|
+
const maxEntities = options.maxEntities ?? 4096;
|
|
6
|
+
function messageToWire(message) {
|
|
7
|
+
let str = String(message[0]);
|
|
8
|
+
let j;
|
|
9
|
+
for (j = message.length - 1; j >= 0; --j) if (message[j] !== void 0) break;
|
|
10
|
+
for (let i = 1; i <= j; i++) str += " " + JSON.stringify(message[i]);
|
|
11
|
+
return str;
|
|
12
|
+
}
|
|
13
|
+
function messageFromWire(data) {
|
|
14
|
+
const wire = typeof data === "string" ? data : new TextDecoder().decode(data);
|
|
15
|
+
let braceStack = 0, arrayStack = 0, inString = 0, entityCount = 0;
|
|
16
|
+
let formatted = [];
|
|
17
|
+
let start = 0;
|
|
18
|
+
let escaping = false;
|
|
19
|
+
for (let i = 0; i <= wire.length; i++) if (wire[i] === " ") {
|
|
20
|
+
const value = wire.slice(0, i);
|
|
21
|
+
formatted.push(value);
|
|
22
|
+
start = i + 1;
|
|
23
|
+
break;
|
|
24
|
+
}
|
|
25
|
+
for (let i = start; i <= wire.length; i++) {
|
|
26
|
+
if (entityCount > maxEntities) throw new OperationError(`${Keyword}: Maximum entity count exceeded`, ErrorProtocolViolation.code);
|
|
27
|
+
if (wire[i] === "{" && !inString) {
|
|
28
|
+
braceStack++;
|
|
29
|
+
entityCount++;
|
|
30
|
+
} else if (wire[i] === "}" && !inString) braceStack--;
|
|
31
|
+
else if (wire[i] === "[" && !inString) {
|
|
32
|
+
arrayStack++;
|
|
33
|
+
entityCount++;
|
|
34
|
+
} else if (wire[i] === "]" && !inString) arrayStack--;
|
|
35
|
+
else if (wire[i] === "\\" && inString) escaping = !escaping;
|
|
36
|
+
else if (wire[i] === "\"") {
|
|
37
|
+
if (!escaping) inString = inString ? 0 : 1;
|
|
38
|
+
escaping = false;
|
|
39
|
+
} else if (i === wire.length && start < i || wire[i] === " " && braceStack === 0 && arrayStack === 0 && !inString) {
|
|
40
|
+
entityCount++;
|
|
41
|
+
const value = wire.slice(start, i);
|
|
42
|
+
formatted.push(JSON.parse(value));
|
|
43
|
+
start = i + 1;
|
|
44
|
+
} else escaping = false;
|
|
45
|
+
}
|
|
46
|
+
return formatted;
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
type: "text",
|
|
50
|
+
messageFromWire,
|
|
51
|
+
messageToWire
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
//#endregion
|
|
56
|
+
export { psionicCodec };
|
|
57
|
+
//# sourceMappingURL=psionic.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"psionic.mjs","names":[],"sources":["../../src/codecs/psionic.ts"],"sourcesContent":["import { ErrorProtocolViolation, Keyword, OperationError} from \"../psionic\";\n\nexport type PsionicCodecOptions = {\n /** Max entities per message. Default: 4096. */\n maxEntities?: number;\n}\n\nexport const psionicCodec = (options: PsionicCodecOptions = {}) => {\n const maxEntities = options.maxEntities ?? 0x1000;\n\n function messageToWire(message: any[]): Uint8Array | string {\n let str = String(message[0]);\n let j: number;\n for (j = message.length - 1; j >= 0; --j) {\n if (message[j] !== undefined) break;\n }\n for (let i = 1; i <= j; i++) {\n str += ' ' + JSON.stringify(message[i]);\n }\n return str;\n };\n\n function messageFromWire(data: Uint8Array | string): any {\n const wire = typeof data === 'string' ? data : new TextDecoder().decode(data);\n let braceStack = 0, arrayStack = 0, inString = 0, entityCount = 0;\n let formatted = [];\n let start = 0;\n let escaping = false;\n // Extract the op code (first space-delimited token).\n for (let i = 0; i <= wire.length; i++) {\n if (wire[i] === ' ') {\n const value = wire.slice(0, i);\n formatted.push(value);\n start = i + 1;\n break;\n }\n }\n // Parse remaining space-delimited values, respecting JSON nesting.\n for (let i = start; i <= wire.length; i++) {\n if (entityCount > maxEntities) {\n throw new OperationError(`${Keyword}: Maximum entity count exceeded`, ErrorProtocolViolation.code);\n }\n if (wire[i] === '{' && !inString) {\n braceStack++;\n entityCount++;\n } else if (wire[i] === '}' && !inString) {\n braceStack--;\n } else if (wire[i] === '[' && !inString) {\n arrayStack++;\n entityCount++;\n } else if (wire[i] === ']' && !inString) {\n arrayStack--;\n } else if (wire[i] === '\\\\' && inString) {\n escaping = !escaping;\n } else if (wire[i] === '\"') {\n if (!escaping) inString = inString ? 0 : 1;\n escaping = false;\n } else if ((i === wire.length && start < i) || (wire[i] === ' ' && braceStack === 0 && arrayStack === 0 && !inString)) {\n entityCount++;\n const value = wire.slice(start, i);\n formatted.push(JSON.parse(value));\n start = i + 1;\n } else {\n escaping = false;\n }\n }\n return formatted;\n }\n\n return {\n type: 'text' as const,\n messageFromWire,\n messageToWire\n };\n};\n"],"mappings":";;;AAOA,MAAa,gBAAgB,UAA+B,EAAE,KAAK;CAC/D,MAAM,cAAc,QAAQ,eAAe;CAE3C,SAAS,cAAc,SAAqC;EACxD,IAAI,MAAM,OAAO,QAAQ,GAAG;EAC5B,IAAI;AACJ,OAAK,IAAI,QAAQ,SAAS,GAAG,KAAK,GAAG,EAAE,EACnC,KAAI,QAAQ,OAAO,OAAW;AAElC,OAAK,IAAI,IAAI,GAAG,KAAK,GAAG,IACpB,QAAO,MA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
|
3
|
+
"version": "0.3.4",
|
|
4
4
|
"description": "Light-weight streaming RPC library for JavaScript",
|
|
5
5
|
"license": "ISC",
|
|
6
|
-
"author": "JDP",
|
|
7
|
-
"type": "module",
|
|
8
|
-
"scripts": {
|
|
9
|
-
"test": "./tests",
|
|
10
|
-
"build": "tsdown && node make-package.js"
|
|
11
|
-
},
|
|
12
|
-
"devDependencies": {
|
|
13
|
-
"@types/node": "^25.2.3",
|
|
14
|
-
"@types/react": "^19.2.14",
|
|
15
|
-
"tsdown": "^0.20.3",
|
|
16
|
-
"typescript": "^5.9.3"
|
|
17
|
-
},
|
|
18
6
|
"exports": {
|
|
19
|
-
"./utils/react-hooks":
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
"./adapters/
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
"./
|
|
28
|
-
|
|
7
|
+
"./utils/react-hooks": {
|
|
8
|
+
"default": "./utils/react-hooks.mjs",
|
|
9
|
+
"types": "./utils/react-hooks.d.ts"
|
|
10
|
+
},
|
|
11
|
+
"./adapters/webworker": {
|
|
12
|
+
"default": "./adapters/webworker.mjs",
|
|
13
|
+
"types": "./adapters/webworker.d.ts"
|
|
14
|
+
},
|
|
15
|
+
"./adapters/reconnect": {
|
|
16
|
+
"default": "./adapters/reconnect.mjs",
|
|
17
|
+
"types": "./adapters/reconnect.d.ts"
|
|
18
|
+
},
|
|
19
|
+
"./adapters/resend": {
|
|
20
|
+
"default": "./adapters/resend.mjs",
|
|
21
|
+
"types": "./adapters/resend.d.ts"
|
|
22
|
+
},
|
|
23
|
+
"./adapters/socket": {
|
|
24
|
+
"default": "./adapters/socket.mjs",
|
|
25
|
+
"types": "./adapters/socket.d.ts"
|
|
26
|
+
},
|
|
27
|
+
"./adapters/websocket": {
|
|
28
|
+
"default": "./adapters/websocket.mjs",
|
|
29
|
+
"types": "./adapters/websocket.d.ts"
|
|
30
|
+
},
|
|
31
|
+
"./codecs/cbor": {
|
|
32
|
+
"default": "./codecs/cbor.mjs",
|
|
33
|
+
"types": "./codecs/cbor.d.ts"
|
|
34
|
+
},
|
|
35
|
+
"./codecs/psionic": {
|
|
36
|
+
"default": "./codecs/psionic.mjs",
|
|
37
|
+
"types": "./codecs/psionic.d.ts"
|
|
38
|
+
},
|
|
39
|
+
"./session": {
|
|
40
|
+
"default": "./session.mjs",
|
|
41
|
+
"types": "./session.d.ts"
|
|
42
|
+
},
|
|
43
|
+
".": {
|
|
44
|
+
"default": "./psionic.mjs",
|
|
45
|
+
"types": "./psionic.d.ts"
|
|
46
|
+
}
|
|
29
47
|
}
|
|
30
|
-
}
|
|
48
|
+
}
|
package/psionic.d.mts
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { ID, OperationTypes, Session } from "./session.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/psionic.d.ts
|
|
4
|
+
declare const Keyword: "@@psion";
|
|
5
|
+
declare let CallContextSymbol: symbol;
|
|
6
|
+
declare const AsyncFnKey = "f";
|
|
7
|
+
declare const AsyncGenKey = "g";
|
|
8
|
+
declare const STATE_DISCONNECTED: 0;
|
|
9
|
+
declare const STATE_CONNECTING: 1;
|
|
10
|
+
declare const STATE_CONNECTED: 2;
|
|
11
|
+
declare const STATE_LOCAL_DESCRIBED: 3;
|
|
12
|
+
declare const STATE_REMOTE_DESCRIBED: 4;
|
|
13
|
+
declare const STATE_READY: 5;
|
|
14
|
+
type ReadyState = typeof STATE_DISCONNECTED | typeof STATE_CONNECTING | typeof STATE_CONNECTED | typeof STATE_LOCAL_DESCRIBED | typeof STATE_REMOTE_DESCRIBED | typeof STATE_READY;
|
|
15
|
+
declare const OpDescribe: "D";
|
|
16
|
+
declare const OpCall: "C";
|
|
17
|
+
declare const OpOK: "K";
|
|
18
|
+
declare const OpError: "E";
|
|
19
|
+
declare const OpIterNext: ".";
|
|
20
|
+
declare const OpIterReturn: "<";
|
|
21
|
+
declare const OpIterThrow: ">";
|
|
22
|
+
type CallFrame = [type: typeof OpCall, id: ID, name: string[], args: any[]];
|
|
23
|
+
type DescribeFrame = [type: typeof OpDescribe, id: ID, description: any, swap?: boolean];
|
|
24
|
+
type RespondFrame = [type: typeof OpOK, id: ID, result: any];
|
|
25
|
+
type ErrorFrame = [type: typeof OpError, id: ID, code: number, error?: string];
|
|
26
|
+
type IterNextFrame = [type: typeof OpIterNext, id: ID, operationId: ID, value: any];
|
|
27
|
+
type IterReturnFrame = [type: typeof OpIterReturn, id: ID, operationId: ID, value: any];
|
|
28
|
+
type IterThrowFrame = [type: typeof OpIterThrow, id: ID, operationId: ID, code: number, error?: string];
|
|
29
|
+
type Frame = DescribeFrame | CallFrame | RespondFrame | ErrorFrame | IterNextFrame | IterReturnFrame | IterThrowFrame;
|
|
30
|
+
type FrameOps = Frame[0];
|
|
31
|
+
declare const Errors: readonly [{
|
|
32
|
+
readonly code: 0;
|
|
33
|
+
readonly error: "@@psion: Remote error";
|
|
34
|
+
}, {
|
|
35
|
+
readonly code: 1;
|
|
36
|
+
readonly error: "@@psion: No remote assigned";
|
|
37
|
+
}, {
|
|
38
|
+
readonly code: 2;
|
|
39
|
+
readonly error: "@@psion: Disconnected";
|
|
40
|
+
}, {
|
|
41
|
+
readonly code: 3;
|
|
42
|
+
readonly error: "@@psion: Protocol violation";
|
|
43
|
+
}, {
|
|
44
|
+
readonly code: 4;
|
|
45
|
+
readonly error: "@@psion: Function not found";
|
|
46
|
+
}, {
|
|
47
|
+
readonly code: 5;
|
|
48
|
+
readonly error: "@@psion: Expired or invalid";
|
|
49
|
+
}, {
|
|
50
|
+
readonly code: 6;
|
|
51
|
+
readonly error: "@@psion: Rejected";
|
|
52
|
+
}];
|
|
53
|
+
declare const ErrorGeneric: {
|
|
54
|
+
readonly code: 0;
|
|
55
|
+
readonly error: "@@psion: Remote error";
|
|
56
|
+
};
|
|
57
|
+
declare const ErrorNoRemote: {
|
|
58
|
+
readonly code: 1;
|
|
59
|
+
readonly error: "@@psion: No remote assigned";
|
|
60
|
+
};
|
|
61
|
+
declare const ErrorDisconnected: {
|
|
62
|
+
readonly code: 2;
|
|
63
|
+
readonly error: "@@psion: Disconnected";
|
|
64
|
+
};
|
|
65
|
+
declare const ErrorProtocolViolation: {
|
|
66
|
+
readonly code: 3;
|
|
67
|
+
readonly error: "@@psion: Protocol violation";
|
|
68
|
+
};
|
|
69
|
+
declare const ErrorFunctionNotFound: {
|
|
70
|
+
readonly code: 4;
|
|
71
|
+
readonly error: "@@psion: Function not found";
|
|
72
|
+
};
|
|
73
|
+
declare const ErrorExpiredOrInvalid: {
|
|
74
|
+
readonly code: 5;
|
|
75
|
+
readonly error: "@@psion: Expired or invalid";
|
|
76
|
+
};
|
|
77
|
+
declare const ErrorRejected: {
|
|
78
|
+
readonly code: 6;
|
|
79
|
+
readonly error: "@@psion: Rejected";
|
|
80
|
+
};
|
|
81
|
+
type ErrorTypes = typeof Errors[number];
|
|
82
|
+
/** Codec for serializing frames to/from wire format. */
|
|
83
|
+
type WireCodec = {
|
|
84
|
+
type?: 'text' | 'binary';
|
|
85
|
+
messageToWire: (message: any[]) => string | Uint8Array;
|
|
86
|
+
messageFromWire: (wire: string | Uint8Array) => any[];
|
|
87
|
+
};
|
|
88
|
+
type BasicDescription = {
|
|
89
|
+
[key: string]: BasicValue;
|
|
90
|
+
};
|
|
91
|
+
type BasicValue = string | number | boolean | null | undefined | ((...args: any[]) => Promise<any>) | ((...args: any[]) => AsyncGenerator<any, any, any>) | BasicDescription | BasicValue[];
|
|
92
|
+
type DescriptionValue<T> = [T] extends [(string | number | boolean | null | undefined)] ? T : [T] extends [readonly (infer U)[]] ? DescriptionValue<U>[] : [T] extends [object] ? Description<T> : [T] extends [(...args: infer A extends any[]) => Promise<infer R>] ? (...args: A) => Promise<R> : [T] extends [(...args: infer A extends any[]) => AsyncGenerator<infer Y, infer R, infer N>] ? (...args: A) => AsyncGenerator<Y, R, N> : never;
|
|
93
|
+
/** Infers concrete types for functions within a description. */
|
|
94
|
+
type Description<T> = { [K in keyof T]: DescriptionValue<T[K]> };
|
|
95
|
+
type PeerEvents<RemoteAPI> = {
|
|
96
|
+
readyStateChange: (readyState: ReadyState) => void;
|
|
97
|
+
describe: (description: Description<RemoteAPI>) => void;
|
|
98
|
+
error: (err: Error) => void;
|
|
99
|
+
send: (frame: Frame) => void;
|
|
100
|
+
message: (frame: Frame) => void;
|
|
101
|
+
};
|
|
102
|
+
/** Transport-level connection to a remote peer. */
|
|
103
|
+
type Connection = {
|
|
104
|
+
/** Send a frame to the remote. */send: (frame: Frame) => void; /** Close the connection and clean up resources. */
|
|
105
|
+
close: (err?: any) => void;
|
|
106
|
+
};
|
|
107
|
+
/** Adapter interface for middleware or peers */
|
|
108
|
+
type AdapterNext = {
|
|
109
|
+
session: Session;
|
|
110
|
+
handleMessage: Peer["handleMessage"];
|
|
111
|
+
close: Peer["close"];
|
|
112
|
+
};
|
|
113
|
+
type Adapter = (peer: Peer) => Promise<Connection>;
|
|
114
|
+
type PeerOptions<LocalAPI extends BasicDescription> = {
|
|
115
|
+
/** Initial description sent to the remote on connect. */description?: LocalAPI; /** Send full error messages to remote. Default: false. */
|
|
116
|
+
sendErrorMessages?: boolean; /** Accept full error messages from remote. Default: false. */
|
|
117
|
+
receiveErrorMessages?: boolean;
|
|
118
|
+
session?: Session;
|
|
119
|
+
};
|
|
120
|
+
/** Represents a peer in the network. */
|
|
121
|
+
type Peer<RemoteAPI extends BasicDescription = any, LocalAPI extends BasicDescription = any> = {
|
|
122
|
+
session: Session; /** Send a frame to the remote peer. */
|
|
123
|
+
send(...frame: any[]): void; /** Emit an event to local listeners. */
|
|
124
|
+
emit(key: string, ...args: any[]): void; /** Handle an incoming message frame from the remote peer. */
|
|
125
|
+
handleMessage(frame: Frame): void; /** Whether to send full error messages to remote. */
|
|
126
|
+
sendErrorMessages?: boolean; /** Whether to accept full error messages from remote. */
|
|
127
|
+
receiveErrorMessages?: boolean; /** Register an event listener. */
|
|
128
|
+
on: <K extends keyof PeerEvents<RemoteAPI>>(key: K, listener: PeerEvents<RemoteAPI>[K]) => () => void; /** Remove an event listener. */
|
|
129
|
+
off: <K extends keyof PeerEvents<RemoteAPI>>(key: K, listener: PeerEvents<RemoteAPI>[K]) => void; /** Connect to remote, describe local state, optionally wait for remote description. */
|
|
130
|
+
connect(connect: Adapter, waitForRemoteDescribe?: boolean): Promise<void>; /** Remote's described state, with functions replaced by invokers. */
|
|
131
|
+
remote?: Description<RemoteAPI>; /** Describe local state to remote. Accepts an object or an updater function. */
|
|
132
|
+
describe: (stateChange: DescribeCallback<Description<LocalAPI>>) => Promise<void>; /** Close connection and clean up. Peer can reconnect after closing. */
|
|
133
|
+
close(ex?: any): void; /** Copy of the most recently described local state. */
|
|
134
|
+
local?: Description<LocalAPI>;
|
|
135
|
+
/**
|
|
136
|
+
* - `0` STATE_DISCONNECTED: The peer is not connected to any remote.
|
|
137
|
+
* - `1` STATE_CONNECTING: The peer is currently connecting to a new remote.
|
|
138
|
+
* - `2` STATE_CONNECTED: The peer is connected to a remote, but is not yet ready to use.
|
|
139
|
+
* - `3` STATE_LOCAL_DESCRIBED: The peer has described itself, but not received a description.
|
|
140
|
+
* - `4` STATE_REMOTE_DESCRIBED: The peer has received a description, but not described itself.
|
|
141
|
+
* - `5` STATE_READY: The peer is ready to both send and receive messages.
|
|
142
|
+
*/
|
|
143
|
+
readyState: ReadyState; /** Current remote connection, if any. */
|
|
144
|
+
connection?: Connection;
|
|
145
|
+
get ready(): boolean;
|
|
146
|
+
};
|
|
147
|
+
type EventEmitter<T> = {
|
|
148
|
+
on: <K extends keyof T>(key: K, listener: T[K]) => () => void;
|
|
149
|
+
off: <K extends keyof T>(key: K, listener: T[K]) => void;
|
|
150
|
+
};
|
|
151
|
+
/** Create a new event emitter instance. */
|
|
152
|
+
declare function createEventEmitter(): {
|
|
153
|
+
on: (key: string, listener: (...args: any[]) => void) => () => void;
|
|
154
|
+
emit: (key: string, ...args: any[]) => void;
|
|
155
|
+
off: (key: string, listener: (...args: any[]) => void) => void;
|
|
156
|
+
};
|
|
157
|
+
/** Either a full state object, or a state updater function. */
|
|
158
|
+
type DescribeCallback<T> = T | ((current: T) => T);
|
|
159
|
+
/** Events emitted by a Describer instance. */
|
|
160
|
+
type DescriberEvents<T> = {
|
|
161
|
+
/** Emitted when the state changes. */change: (description: Description<T>, previous: Description<T>, swap?: boolean) => void;
|
|
162
|
+
};
|
|
163
|
+
/** A Describer instance manages state and emits events when the state changes. */
|
|
164
|
+
type Describer<T> = EventEmitter<DescriberEvents<T>> & {
|
|
165
|
+
/** Get the complete current state. */currentState(): T; /** Describe a new state change. */
|
|
166
|
+
describe: (stateChange: DescribeCallback<T>) => [prevState: T, newState: T, swap: boolean];
|
|
167
|
+
};
|
|
168
|
+
/** Create a new Describer instance, which holds state and emits events when state changes. */
|
|
169
|
+
declare function createDescription<T>(initialState: T): Describer<T>;
|
|
170
|
+
/** Create a new disconnected peer instance. */
|
|
171
|
+
declare function createPeer<RemoteAPI extends BasicDescription = any, LocalAPI extends BasicDescription = any>(opts?: PeerOptions<LocalAPI>): Peer<RemoteAPI, LocalAPI>;
|
|
172
|
+
/** Resolves when remote has described itself. Rejects on disconnect. */
|
|
173
|
+
declare function waitUntilRemoteReady(peer: Peer): Promise<void>;
|
|
174
|
+
/** Converts a local description to wire-safe codec format (functions → sentinel symbols). */
|
|
175
|
+
declare function toCodecDescription(description: any): any;
|
|
176
|
+
/** Converts a wire-format description into a usable object (sentinel symbols → invoker functions). */
|
|
177
|
+
declare function fromCodecDescription(peer: Peer, description: any): any;
|
|
178
|
+
/** Creates a local async generator that proxies iteration to the remote. */
|
|
179
|
+
declare function createAsyncGeneratorFunction(peer: Peer, name: string[]): (...args: any[]) => AsyncGenerator<any, any, any>;
|
|
180
|
+
/** Marks a function as an async generator, setting the appropriate properties. */
|
|
181
|
+
declare function markAsAsyncGenerator<T>(wrappedAsyncGeneratorFunction: T): T;
|
|
182
|
+
/** Creates a local async function that proxies calls to the remote. */
|
|
183
|
+
declare function createAsyncFunction(peer: Peer, name: string[], waitForPeer?: boolean): (...args: any[]) => Promise<any>;
|
|
184
|
+
/** Context value that can be passed in to described functions */
|
|
185
|
+
type CallContext = {
|
|
186
|
+
peer: Peer;
|
|
187
|
+
id: ID;
|
|
188
|
+
operation: OperationTypes;
|
|
189
|
+
};
|
|
190
|
+
type HasContext<T> = {};
|
|
191
|
+
type RemoveFirstParameter<T> = T extends ((first: CallContext, ...args: infer U) => infer R) ? (...args: U) => R : never;
|
|
192
|
+
/** Wraps a function to automatically provide a call context. */
|
|
193
|
+
declare function withContext<T extends Function>(fn: T): RemoveFirstParameter<T> | HasContext<RemoveFirstParameter<T>>;
|
|
194
|
+
declare class OperationError extends Error {
|
|
195
|
+
code: number;
|
|
196
|
+
constructor(ex: ErrorTypes | string, code?: number);
|
|
197
|
+
}
|
|
198
|
+
declare function isAsyncGeneratorLike(value: any): boolean;
|
|
199
|
+
/** Deep-merges a patch into a description. Null values delete keys. */
|
|
200
|
+
declare function mergeDescriptions(original: any, patch: any): any;
|
|
201
|
+
//#endregion
|
|
202
|
+
export { Adapter, AdapterNext, AsyncFnKey, AsyncGenKey, BasicDescription, BasicValue, CallContext, CallContextSymbol, CallFrame, Connection, DescribeFrame, Description, DescriptionValue, ErrorDisconnected, ErrorExpiredOrInvalid, ErrorFrame, ErrorFunctionNotFound, ErrorGeneric, ErrorNoRemote, ErrorProtocolViolation, ErrorRejected, Errors, Frame, FrameOps, IterNextFrame, IterReturnFrame, IterThrowFrame, Keyword, OpCall, OpDescribe, OpError, OpIterNext, OpIterReturn, OpIterThrow, OpOK, OperationError, Peer, PeerEvents, PeerOptions, ReadyState, RespondFrame, STATE_CONNECTED, STATE_CONNECTING, STATE_DISCONNECTED, STATE_LOCAL_DESCRIBED, STATE_READY, STATE_REMOTE_DESCRIBED, WireCodec, createAsyncFunction, createAsyncGeneratorFunction, createDescription, createEventEmitter, createPeer, fromCodecDescription, isAsyncGeneratorLike, markAsAsyncGenerator, mergeDescriptions, toCodecDescription, waitUntilRemoteReady, withContext };
|
|
203
|
+
//# sourceMappingURL=psionic.d.mts.map
|