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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +791 -2
  3. package/dist/client-BHyIiYxt.js +1527 -0
  4. package/dist/client-BHyIiYxt.js.map +1 -0
  5. package/dist/client-DHCV7yvQ.d.ts +440 -0
  6. package/dist/client-DHCV7yvQ.d.ts.map +1 -0
  7. package/dist/client.d.ts +3 -0
  8. package/dist/client.js +4 -0
  9. package/dist/env-qA8EyOr1.d.ts +49 -0
  10. package/dist/env-qA8EyOr1.d.ts.map +1 -0
  11. package/dist/env.d.ts +2 -0
  12. package/dist/env.js +44 -0
  13. package/dist/env.js.map +1 -0
  14. package/dist/index-Bm_-MTj6.d.ts +915 -0
  15. package/dist/index-Bm_-MTj6.d.ts.map +1 -0
  16. package/dist/index.d.ts +5 -0
  17. package/dist/index.js +6 -0
  18. package/dist/middleware-BdVlE8qm.d.ts +576 -0
  19. package/dist/middleware-BdVlE8qm.d.ts.map +1 -0
  20. package/dist/middleware.d.ts +2 -0
  21. package/dist/middleware.js +282 -0
  22. package/dist/middleware.js.map +1 -0
  23. package/dist/prerender.d.ts +98 -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 +58 -0
  28. package/dist/protocol.d.ts.map +1 -0
  29. package/dist/protocol.js +26 -0
  30. package/dist/protocol.js.map +1 -0
  31. package/dist/serve.d.ts +135 -0
  32. package/dist/serve.d.ts.map +1 -0
  33. package/dist/serve.js +223 -0
  34. package/dist/serve.js.map +1 -0
  35. package/dist/server-BV3xKmLa.js +1148 -0
  36. package/dist/server-BV3xKmLa.js.map +1 -0
  37. package/dist/server.d.ts +142 -0
  38. package/dist/server.d.ts.map +1 -0
  39. package/dist/server.js +1 -0
  40. package/dist/src-ChnB_xug.js +1140 -0
  41. package/dist/src-ChnB_xug.js.map +1 -0
  42. package/dist/static-fn-DgjNArBe.js +123 -0
  43. package/dist/static-fn-DgjNArBe.js.map +1 -0
  44. package/package.json +106 -4
  45. package/src/client.ts +672 -0
  46. package/src/context.ts +666 -0
  47. package/src/cookies.ts +229 -0
  48. package/src/env.ts +86 -0
  49. package/src/fn-error.ts +97 -0
  50. package/src/frames-client.ts +1216 -0
  51. package/src/frames-server.ts +464 -0
  52. package/src/frames.ts +285 -0
  53. package/src/index.ts +714 -0
  54. package/src/live-client.ts +50 -0
  55. package/src/live-server.ts +182 -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 +990 -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 +139 -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,182 @@
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
+
19
+ import { type ServerFrame, frameMarkup } from "./frames-server.ts";
20
+ import { isFrame } from "./frames.ts";
21
+
22
+ /** The `x-barq-rpc` value a live answer carries. */
23
+ export const RPC_LIVE = "live";
24
+
25
+ /** How often an idle connection says it is still there, against proxies that time one out. */
26
+ const HEARTBEAT_MS = 20_000;
27
+
28
+ function digest(text: string): string {
29
+ let hash = 0x811c9dc5;
30
+ for (let at = 0; at < text.length; at++) {
31
+ hash ^= text.charCodeAt(at);
32
+ hash = Math.imul(hash, 0x01000193);
33
+ }
34
+ return (hash >>> 0).toString(36);
35
+ }
36
+
37
+ function isIterable(value: unknown): value is AsyncIterable<unknown> {
38
+ return (
39
+ typeof value === "object" &&
40
+ value !== null &&
41
+ typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === "function"
42
+ );
43
+ }
44
+
45
+ /**
46
+ * One event: its kind, an id, and data that is JSON and so carries no line
47
+ * break of its own. A frame's markup is `frame`, a value the default kind.
48
+ */
49
+ function event(kind: "frame" | "message", id: string, data: string): string {
50
+ return `${kind === "frame" ? "event: frame\n" : ""}id: ${id}\ndata: ${data}\n\n`;
51
+ }
52
+
53
+ /** The answer to a call at the live address. */
54
+ export function liveResponse(result: unknown, request: Request): Response {
55
+ const encoder = new TextEncoder();
56
+ const last = request.headers.get("last-event-id");
57
+ let controller: ReadableStreamDefaultController<Uint8Array> | null = null;
58
+ let ended = false;
59
+ const stops: (() => void)[] = [];
60
+ const end = (complete: boolean): void => {
61
+ if (ended) return;
62
+ ended = true;
63
+ for (const stop of stops) stop();
64
+ if (controller === null) return;
65
+ try {
66
+ if (complete) controller.enqueue(encoder.encode("event: complete\ndata: \n\n"));
67
+ controller.close();
68
+ } catch {
69
+ // The reader has gone.
70
+ }
71
+ };
72
+ const send = (text: string): void => {
73
+ if (ended || controller === null) return;
74
+ try {
75
+ controller.enqueue(encoder.encode(text));
76
+ } catch {
77
+ end(false);
78
+ }
79
+ };
80
+ let sentId = last;
81
+ const emit = (data: string, kind: "frame" | "message" = "message"): void => {
82
+ const id = digest(data);
83
+ if (id === sentId) return;
84
+ sentId = id;
85
+ send(event(kind, id, data));
86
+ };
87
+
88
+ const start = (): void => {
89
+ const heartbeat = setInterval(() => send(": still here\n\n"), HEARTBEAT_MS);
90
+ (heartbeat as { unref?: () => void }).unref?.();
91
+ stops.push(() => clearInterval(heartbeat));
92
+ const abort = (): void => end(false);
93
+ request.signal.addEventListener("abort", abort, { once: true });
94
+ stops.push(() => request.signal.removeEventListener("abort", abort));
95
+ if (isFrame(result)) void frames(result as ServerFrame);
96
+ else if (isIterable(result)) void values(result);
97
+ else {
98
+ emit(JSON.stringify(encodeWire(result)));
99
+ end(true);
100
+ }
101
+ };
102
+
103
+ const frames = async (frame: ServerFrame): Promise<void> => {
104
+ const shared = new SharedSources();
105
+ stops.push(() => shared.close());
106
+ let rendering = false;
107
+ let again = false;
108
+ const render = async (): Promise<void> => {
109
+ if (rendering) {
110
+ again = true;
111
+ return;
112
+ }
113
+ rendering = true;
114
+ try {
115
+ for (;;) {
116
+ again = false;
117
+ const session = Symbol("live-frame");
118
+ shared.begin();
119
+ shareSources(session, shared);
120
+ let markup: string;
121
+ try {
122
+ markup = await frameMarkup(frame, { session });
123
+ } finally {
124
+ unshareSources(session);
125
+ }
126
+ shared.sweep();
127
+ if (ended) return;
128
+ emit(JSON.stringify(markup), "frame");
129
+ if (!again) break;
130
+ }
131
+ } catch (error) {
132
+ console.error(
133
+ "[barq] A live frame failed to render, so its connection ends and the page reconnects. The error:",
134
+ error,
135
+ );
136
+ end(false);
137
+ return;
138
+ } finally {
139
+ rendering = false;
140
+ }
141
+ if (shared.settled) end(true);
142
+ };
143
+ shared.onChange(() => void render());
144
+ await render();
145
+ };
146
+
147
+ const values = async (source: AsyncIterable<unknown>): Promise<void> => {
148
+ const iterator = source[Symbol.asyncIterator]();
149
+ stops.push(() => void iterator.return?.());
150
+ try {
151
+ for (;;) {
152
+ const step = await iterator.next();
153
+ if (ended) return;
154
+ if (step.done === true) break;
155
+ emit(JSON.stringify(encodeWire(step.value)));
156
+ }
157
+ end(true);
158
+ } catch (error) {
159
+ console.error(
160
+ "[barq] A live answer failed while streaming, so its connection ends and the page reconnects. The error:",
161
+ error,
162
+ );
163
+ end(false);
164
+ }
165
+ };
166
+
167
+ const body = new ReadableStream<Uint8Array>({
168
+ start(given) {
169
+ controller = given;
170
+ start();
171
+ },
172
+ cancel() {
173
+ end(false);
174
+ },
175
+ });
176
+ const answer = new Response(body);
177
+ answer.headers.set("content-type", "text/event-stream; charset=utf-8");
178
+ answer.headers.set("cache-control", "no-store");
179
+ answer.headers.set("x-accel-buffering", "no");
180
+ answer.headers.set("x-barq-rpc", RPC_LIVE);
181
+ return answer;
182
+ }