-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathclient.tsx
More file actions
246 lines (219 loc) · 6.58 KB
/
client.tsx
File metadata and controls
246 lines (219 loc) · 6.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import { from as rxFrom, Observable } from "rxjs";
import {
createSeriazliedMemo,
SerializedMemo,
SerializedProjection,
SerializedRef,
SerializedStoreAccessor,
SerializedThing,
WsMessage,
WsMessageDown,
WsMessageUp,
} from "./shared";
import {
Accessor,
createComputed,
createEffect,
createMemo,
createSignal,
from,
getListener,
onCleanup,
untrack,
} from "solid-js";
import { createAsync } from "@solidjs/router";
import { createLazyMemo } from "@solid-primitives/memo";
import { createCallback } from "@solid-primitives/rootless";
import { createWS } from "@solid-primitives/websocket";
const protocol = window.location.protocol === "https:" ? "wss" : "ws";
const wsUrl = `${protocol}://${window.location.hostname}:${window.location.port}/_ws`;
const getWs = createLazyMemo(() => createWS(wsUrl));
export type Listener = (ev: { data: any }) => any;
export type SimpleWs = {
removeEventListener(type: "message", listener: Listener): void;
addEventListener(type: "message", listener: Listener): void;
send(data: string): void;
};
function wsRpc<T>(message: WsMessageUp) {
const ws = getWs();
const id = crypto.randomUUID() as string;
return new Promise<{ value: T; dispose: () => void }>(async (res, rej) => {
function dispose() {
ws.send(
JSON.stringify({ type: "dispose", id } satisfies WsMessage<WsMessageUp>)
);
}
function handler(event: { data: string }) {
// console.log(`handler ${id}`, message, { data: event.data });
const data = JSON.parse(event.data) as WsMessage<WsMessageDown<T>>;
if (data.id === id && data.type === "value") {
res({ value: data.value, dispose });
ws.removeEventListener("message", handler);
}
}
ws.addEventListener("message", handler);
ws.send(
JSON.stringify({ ...message, id } satisfies WsMessage<WsMessageUp>)
);
});
}
function wsSub<T>(message: WsMessageUp) {
const ws = getWs();
const id = crypto.randomUUID();
return rxFrom(
new Observable<T>((obs) => {
// console.log(`attaching sub handler`);
function handler(event: { data: string }) {
const data = JSON.parse(event.data) as WsMessage<WsMessageDown<T>>;
// console.log(`data`, data, id);
if (data.id === id && data.type === "value") obs.next(data.value);
}
ws.addEventListener("message", handler);
ws.send(
JSON.stringify({ ...message, id } satisfies WsMessage<WsMessageUp>)
);
return () => {
// console.log(`detaching sub handler`);
ws.removeEventListener("message", handler);
};
})
);
}
export function createRef<I, O>(ref: SerializedRef) {
return (...input: any[]) =>
wsRpc<O>({
type: "invoke",
ref,
input,
}).then(({ value }) => value);
}
export function createSocketMemoConsumer<O>(ref: SerializedMemo) {
// console.log({ ref });
const memo = createLazyMemo(
() =>
from(
wsSub<O>({
type: "subscribe",
ref,
})
),
() => ref.initial
);
return () => {
const memoValue = memo()();
// console.log({ memoValue });
return memoValue;
};
}
export function createSocketProjectionConsumer<O extends object>(
ref: SerializedProjection<O> | SerializedStoreAccessor<O>
) {
const nodes = [] as { path: string; accessor: Accessor<any> }[];
function getNode(path: string) {
const node = nodes.find((node) => node.path === path);
if (node) return node;
const newNode = {
path,
accessor: from(wsSub<O>({ type: "subscribe", ref, path })),
};
nodes.push(newNode);
return newNode;
}
// @ts-expect-error
return new Proxy<O>(ref.initial || {}, {
get(target, path: string) {
return getListener()
? getNode(path).accessor()
: ((target as any)[path] as O);
},
});
}
type SerializedValue = SerializedThing | Record<string, SerializedThing>;
const deserializeValue = (value: SerializedValue) => {
if (value.__type === "ref") {
return createRef(value);
} else if (value.__type === "memo") {
return createSocketMemoConsumer(value);
} else if (value.__type === "projection") {
return createSocketProjectionConsumer(value);
} else {
return Object.entries(value).reduce((res, [name, value]) => {
return {
...res,
[name]:
value.__type === "ref"
? createRef(value)
: value.__type === "memo"
? createSocketMemoConsumer(value)
: value.__type === "projection"
? createSocketProjectionConsumer(value)
: value.__type === "store-accessor"
? createSocketProjectionConsumer(value)
: value,
};
}, {} as any);
}
};
export function createEndpoint(name: string, input?: any) {
const inputScope = crypto.randomUUID();
const serializedInput =
input?.type === "memo"
? createSeriazliedMemo({
name: `input`,
scope: inputScope,
initial: untrack(input),
})
: input;
// console.log({ serializedInput });
const scopePromise = wsRpc<SerializedValue>({
type: "create",
name,
input: serializedInput,
});
if (input?.type === "memo") {
const [inputSignal, setInput] = createSignal(input());
createComputed(() => setInput(input()));
const onSubscribe = createCallback(
(ws: SimpleWs, data: WsMessage<WsMessageDown<any>>) => {
createEffect(() => {
const value = inputSignal();
// console.log(`sending input update to server`, value, input);
ws.send(
JSON.stringify({
type: "value",
id: data.id,
value,
} satisfies WsMessage<WsMessageUp>)
);
});
}
);
const ws = getWs();
function handler(event: { data: string }) {
const data = JSON.parse(event.data) as WsMessage<WsMessageDown<any>>;
if (data.type === "subscribe" && data.ref.scope === inputScope) {
onSubscribe(ws, data);
}
}
ws.addEventListener("message", handler);
onCleanup(() => ws.removeEventListener("message", handler));
}
onCleanup(() => {
// console.log(`cleanup endpoint`);
scopePromise.then(({ dispose }) => dispose());
});
const scope = createAsync(() => scopePromise);
const deserializedScope = createMemo(
() => scope() && deserializeValue(scope()!.value)
);
return new Proxy((() => {}) as any, {
get(_, path) {
const res = deserializedScope()?.[path];
return res || (() => {});
},
apply(_, __, args) {
const res = deserializedScope()?.(...args);
return res;
},
});
}