@barqjs/start 0.0.0-stage → 0.2.0-next.1

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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +817 -2
  3. package/dist/client-BsyxVCyu.js +1554 -0
  4. package/dist/client-BsyxVCyu.js.map +1 -0
  5. package/dist/client-DidH0F2e.d.ts +450 -0
  6. package/dist/client-DidH0F2e.d.ts.map +1 -0
  7. package/dist/client.d.ts +25 -0
  8. package/dist/client.js +4 -0
  9. package/dist/env-Bhk_aIkx.d.ts +47 -0
  10. package/dist/env-Bhk_aIkx.d.ts.map +1 -0
  11. package/dist/env.d.ts +2 -0
  12. package/dist/env.js +43 -0
  13. package/dist/env.js.map +1 -0
  14. package/dist/index-B4o7eyCr.d.ts +925 -0
  15. package/dist/index-B4o7eyCr.d.ts.map +1 -0
  16. package/dist/index.d.ts +18 -0
  17. package/dist/index.js +6 -0
  18. package/dist/middleware-B-tI8QHQ.d.ts +574 -0
  19. package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
  20. package/dist/middleware.d.ts +2 -0
  21. package/dist/middleware.js +281 -0
  22. package/dist/middleware.js.map +1 -0
  23. package/dist/prerender.d.ts +118 -0
  24. package/dist/prerender.d.ts.map +1 -0
  25. package/dist/prerender.js +289 -0
  26. package/dist/prerender.js.map +1 -0
  27. package/dist/protocol.d.ts +56 -0
  28. package/dist/protocol.d.ts.map +1 -0
  29. package/dist/protocol.js +25 -0
  30. package/dist/protocol.js.map +1 -0
  31. package/dist/serve.d.ts +144 -0
  32. package/dist/serve.d.ts.map +1 -0
  33. package/dist/serve.js +221 -0
  34. package/dist/serve.js.map +1 -0
  35. package/dist/server-DG6jb_NA.js +1253 -0
  36. package/dist/server-DG6jb_NA.js.map +1 -0
  37. package/dist/server.d.ts +159 -0
  38. package/dist/server.d.ts.map +1 -0
  39. package/dist/server.js +1 -0
  40. package/dist/src-odXG7kLA.js +1151 -0
  41. package/dist/src-odXG7kLA.js.map +1 -0
  42. package/dist/static-fn-CXjJi-It.js +122 -0
  43. package/dist/static-fn-CXjJi-It.js.map +1 -0
  44. package/package.json +106 -4
  45. package/src/client.ts +698 -0
  46. package/src/context.ts +699 -0
  47. package/src/cookies.ts +229 -0
  48. package/src/env.ts +86 -0
  49. package/src/fn-error.ts +121 -0
  50. package/src/frames-client.ts +1220 -0
  51. package/src/frames-server.ts +464 -0
  52. package/src/frames.ts +285 -0
  53. package/src/index.ts +740 -0
  54. package/src/live-client.ts +50 -0
  55. package/src/live-server.ts +292 -0
  56. package/src/middleware.ts +994 -0
  57. package/src/prerender.ts +477 -0
  58. package/src/protocol.ts +61 -0
  59. package/src/rate-limit.ts +202 -0
  60. package/src/serve.ts +153 -0
  61. package/src/server.ts +1026 -0
  62. package/src/session.ts +449 -0
  63. package/src/start-instance.ts +147 -0
  64. package/src/static-fn.ts +181 -0
  65. package/src/static.ts +302 -0
  66. package/src/stubs.ts +32 -0
  67. package/src/timing.ts +29 -0
  68. package/src/wire-types.ts +138 -0
@@ -0,0 +1,50 @@
1
+ /**
2
+ * `live`: a server function's answer as a standing one, kept current for as
3
+ * long as the caller reads it, Solid 2.0's declaration.
4
+ *
5
+ * In the browser, calling a live function returns an async iterable that
6
+ * survives its connection. Each connection is a call at the live address,
7
+ * read as server-sent events: a value per event, or, for a frame, the region
8
+ * applied where it is mounted, the same component yielded once per connection
9
+ * so a `dynamic` over it never remounts. A body that ends without saying it
10
+ * is complete is a death, and the loop calls again, after a pause that grows
11
+ * with each failure in a row and resets on a healthy connection, naming the
12
+ * last event it applied. A failure on the first connection rejects as a call
13
+ * would, and so does a refusal the server will repeat.
14
+ *
15
+ * On the server, in process, there is no connection: the call is the call,
16
+ * and a frame it answers with is marked so the page connects once claimed.
17
+ */
18
+
19
+ import type { ServerFn } from "./client.ts";
20
+ import { type LiveIterable, type LiveStub, liveIterable } from "./frames-client.ts";
21
+ import { FRAME } from "./frames.ts";
22
+
23
+ export type { LiveIterable, LiveStatus } from "./frames-client.ts";
24
+
25
+ /** Whether a server function is the server half, which runs in this process. */
26
+ function inProcess(fn: unknown): boolean {
27
+ return typeof fn === "function" && "built" in fn;
28
+ }
29
+
30
+ /**
31
+ * Declare a server function's answer a standing one. In the browser, calling
32
+ * the result returns an iterable that stays connected; on the server it is the
33
+ * call itself, a frame it answers with marked for the page to connect.
34
+ */
35
+ export function live<In, Out>(
36
+ fn: ServerFn<In, Out, never>,
37
+ ): (...args: Parameters<ServerFn<In, Out, never>>) => LiveIterable<Awaited<Out>> {
38
+ if (inProcess(fn)) {
39
+ return ((...args: unknown[]) =>
40
+ (fn as unknown as (...given: unknown[]) => Promise<unknown>)(...args).then((answer) => {
41
+ const frame =
42
+ typeof answer === "function"
43
+ ? (answer as unknown as Record<symbol, { live?: boolean }>)[FRAME]
44
+ : undefined;
45
+ if (frame !== undefined) frame.live = true;
46
+ return answer;
47
+ })) as never;
48
+ }
49
+ return ((options?: unknown) => liveIterable(fn as unknown as LiveStub, options)) as never;
50
+ }
@@ -0,0 +1,292 @@
1
+ /**
2
+ * The server half of `live`: a call at the live address answered as server-sent
3
+ * events, for as long as the answer stands.
4
+ *
5
+ * A frame is rendered again each time an async source it reads moves, and each
6
+ * new rendering that differs from the last goes out as one event carrying the
7
+ * frame's markup. Any other answer goes out a value per event. An answer whose
8
+ * every source has ended says so with a `complete` event; a body that ends
9
+ * without one is a connection that died, which the page's loop reconnects.
10
+ *
11
+ * Each event's id is the digest of what it carried. A reconnect names the last
12
+ * one it applied in `Last-Event-ID`, and an answer that still matches it is not
13
+ * sent again.
14
+ */
15
+
16
+ import { SharedSources, shareSources, unshareSources } from "@barqjs/core/internal";
17
+ import { encodeWire } from "@barqjs/server/codec";
18
+ import { withoutRequestEvent } from "@barqjs/server/storage";
19
+
20
+ import { type ServerFrame, frameMarkup } from "./frames-server.ts";
21
+ import { isFrame } from "./frames.ts";
22
+
23
+ /** The `x-barq-rpc` value a live answer carries. */
24
+ export const RPC_LIVE = "live";
25
+
26
+ /** How often an idle connection says it is still there, against proxies that time one out. */
27
+ const HEARTBEAT_MS = 20_000;
28
+
29
+ function digest(text: string): string {
30
+ let hash = 0x811c9dc5;
31
+ for (let at = 0; at < text.length; at++) {
32
+ hash ^= text.charCodeAt(at);
33
+ hash = Math.imul(hash, 0x01000193);
34
+ }
35
+ return (hash >>> 0).toString(36);
36
+ }
37
+
38
+ function isIterable(value: unknown): value is AsyncIterable<unknown> {
39
+ return (
40
+ typeof value === "object" &&
41
+ value !== null &&
42
+ typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === "function"
43
+ );
44
+ }
45
+
46
+ /**
47
+ * One event: its kind, an id, and data that is JSON and so carries no line
48
+ * break of its own. A frame's markup is `frame`, a value the default kind.
49
+ */
50
+ function event(kind: "frame" | "message", id: string, data: string): string {
51
+ return `${kind === "frame" ? "event: frame\n" : ""}id: ${id}\ndata: ${data}\n\n`;
52
+ }
53
+
54
+ type Emit = (data: string, kind: "frame" | "message") => void;
55
+
56
+ /**
57
+ * Drive a live answer: each rendering of a frame, or each value of an
58
+ * iterable, through `emit` until it ends, then `finish(complete)`. Returns
59
+ * what stops it early.
60
+ */
61
+ function produce(result: unknown, emit: Emit, finish: (complete: boolean) => void): () => void {
62
+ let ended = false;
63
+ const stops: (() => void)[] = [];
64
+ const end = (complete: boolean): void => {
65
+ if (ended) return;
66
+ ended = true;
67
+ for (const stop of stops) stop();
68
+ finish(complete);
69
+ };
70
+
71
+ const frames = async (frame: ServerFrame): Promise<void> => {
72
+ const shared = new SharedSources();
73
+ stops.push(() => shared.close());
74
+ let rendering = false;
75
+ let again = false;
76
+ const render = async (): Promise<void> => {
77
+ if (rendering) {
78
+ again = true;
79
+ return;
80
+ }
81
+ rendering = true;
82
+ try {
83
+ for (;;) {
84
+ again = false;
85
+ const session = Symbol("live-frame");
86
+ shared.begin();
87
+ shareSources(session, shared);
88
+ let markup: string;
89
+ try {
90
+ markup = await frameMarkup(frame, { session });
91
+ } finally {
92
+ unshareSources(session);
93
+ }
94
+ shared.sweep();
95
+ if (ended) return;
96
+ emit(JSON.stringify(markup), "frame");
97
+ if (!again) break;
98
+ }
99
+ } catch (error) {
100
+ console.error(
101
+ "[barq] A live frame failed to render, so its connection ends and the page reconnects. The error:",
102
+ error,
103
+ );
104
+ end(false);
105
+ return;
106
+ } finally {
107
+ rendering = false;
108
+ }
109
+ if (shared.settled) end(true);
110
+ };
111
+ shared.onChange(() => void render());
112
+ await render();
113
+ };
114
+
115
+ const values = async (source: AsyncIterable<unknown>): Promise<void> => {
116
+ const iterator = source[Symbol.asyncIterator]();
117
+ stops.push(() => void iterator.return?.());
118
+ try {
119
+ for (;;) {
120
+ const step = await iterator.next();
121
+ if (ended) return;
122
+ if (step.done === true) break;
123
+ emit(JSON.stringify(encodeWire(step.value)), "message");
124
+ }
125
+ end(true);
126
+ } catch (error) {
127
+ console.error(
128
+ "[barq] A live answer failed while streaming, so its connection ends and the page reconnects. The error:",
129
+ error,
130
+ );
131
+ end(false);
132
+ }
133
+ };
134
+
135
+ if (isFrame(result)) void frames(result as ServerFrame);
136
+ else if (isIterable(result)) void values(result);
137
+ else {
138
+ emit(JSON.stringify(encodeWire(result)), "message");
139
+ end(true);
140
+ }
141
+ return () => {
142
+ if (ended) return;
143
+ ended = true;
144
+ for (const stop of stops) stop();
145
+ };
146
+ }
147
+
148
+ interface Connection {
149
+ readonly emit: Emit;
150
+ readonly end: (complete: boolean) => void;
151
+ }
152
+
153
+ /**
154
+ * One server-sent event stream. `attach` is handed the connection when the
155
+ * stream starts and answers with what to run when it ends, either way.
156
+ */
157
+ function connection(request: Request, attach: (connection: Connection) => () => void): Response {
158
+ const encoder = new TextEncoder();
159
+ let controller: ReadableStreamDefaultController<Uint8Array> | null = null;
160
+ let ended = false;
161
+ const stops: (() => void)[] = [];
162
+ const end = (complete: boolean): void => {
163
+ if (ended) return;
164
+ ended = true;
165
+ for (const stop of stops) stop();
166
+ if (controller === null) return;
167
+ try {
168
+ if (complete) controller.enqueue(encoder.encode("event: complete\ndata: \n\n"));
169
+ controller.close();
170
+ } catch {
171
+ // The reader has gone.
172
+ }
173
+ };
174
+ const send = (text: string): void => {
175
+ if (ended || controller === null) return;
176
+ try {
177
+ controller.enqueue(encoder.encode(text));
178
+ } catch {
179
+ end(false);
180
+ }
181
+ };
182
+ let sentId = request.headers.get("last-event-id");
183
+ const emit: Emit = (data, kind) => {
184
+ const id = digest(data);
185
+ if (id === sentId) return;
186
+ sentId = id;
187
+ send(event(kind, id, data));
188
+ };
189
+
190
+ const body = new ReadableStream<Uint8Array>({
191
+ start(given) {
192
+ controller = given;
193
+ const heartbeat = setInterval(() => send(": still here\n\n"), HEARTBEAT_MS);
194
+ (heartbeat as { unref?: () => void }).unref?.();
195
+ stops.push(() => clearInterval(heartbeat));
196
+ const abort = (): void => end(false);
197
+ request.signal.addEventListener("abort", abort, { once: true });
198
+ stops.push(() => request.signal.removeEventListener("abort", abort));
199
+ stops.push(attach({ emit, end }));
200
+ },
201
+ cancel() {
202
+ end(false);
203
+ },
204
+ });
205
+ const answer = new Response(body);
206
+ answer.headers.set("content-type", "text/event-stream; charset=utf-8");
207
+ answer.headers.set("cache-control", "no-store");
208
+ answer.headers.set("x-accel-buffering", "no");
209
+ answer.headers.set("x-barq-rpc", RPC_LIVE);
210
+ return answer;
211
+ }
212
+
213
+ /** The answer to a call at the live address. */
214
+ export function liveResponse(result: unknown, request: Request): Response {
215
+ return connection(request, (to) => produce(result, to.emit, to.end));
216
+ }
217
+
218
+ interface Broadcast {
219
+ readonly connections: Set<Connection>;
220
+ latest: { readonly data: string; readonly kind: "frame" | "message" } | null;
221
+ ended: boolean;
222
+ stop: () => void;
223
+ }
224
+
225
+ /** The running shared answers, by function and arguments. */
226
+ const BROADCASTS = new Map<string, Broadcast>();
227
+
228
+ /**
229
+ * A joiner's own answer, closed without reading it. Only an answer that is
230
+ * already an iterator, a generator object, holds anything: an iterable nobody
231
+ * has asked for an iterator has started nothing, and asking would start it.
232
+ */
233
+ function closeUnread(result: unknown): void {
234
+ const iterator = result as { return?: () => unknown } | null;
235
+ if (typeof iterator?.return !== "function") return;
236
+ try {
237
+ const closing = iterator.return();
238
+ if (closing instanceof Promise) void closing.catch(() => {});
239
+ } catch {
240
+ // Nothing read it, and nothing will.
241
+ }
242
+ }
243
+
244
+ /**
245
+ * The answer to a live call to a `broadcast` function: one rendering per
246
+ * `key`, every connection asking the same thing a reader of it. The first call
247
+ * starts it, outside its own request, and each later one joins it with the
248
+ * latest event and closes its own answer unread. It stops when its last
249
+ * connection goes.
250
+ */
251
+ export function broadcastResponse(key: string, result: unknown, request: Request): Response {
252
+ let shared = BROADCASTS.get(key);
253
+ if (shared !== undefined && !shared.ended) {
254
+ closeUnread(result);
255
+ } else {
256
+ const started: Broadcast = {
257
+ connections: new Set(),
258
+ latest: null,
259
+ ended: false,
260
+ stop: () => {},
261
+ };
262
+ BROADCASTS.set(key, started);
263
+ started.stop = withoutRequestEvent(() =>
264
+ produce(
265
+ result,
266
+ (data, kind) => {
267
+ started.latest = { data, kind };
268
+ for (const each of started.connections) each.emit(data, kind);
269
+ },
270
+ (complete) => {
271
+ started.ended = true;
272
+ if (BROADCASTS.get(key) === started) BROADCASTS.delete(key);
273
+ for (const each of started.connections) each.end(complete);
274
+ },
275
+ ),
276
+ );
277
+ shared = started;
278
+ }
279
+ const joined = shared;
280
+ return connection(request, (to) => {
281
+ joined.connections.add(to);
282
+ if (joined.latest !== null) to.emit(joined.latest.data, joined.latest.kind);
283
+ if (joined.ended) to.end(true);
284
+ return () => {
285
+ joined.connections.delete(to);
286
+ if (joined.connections.size > 0 || joined.ended) return;
287
+ joined.ended = true;
288
+ if (BROADCASTS.get(key) === joined) BROADCASTS.delete(key);
289
+ joined.stop();
290
+ };
291
+ });
292
+ }