hx-stream 0.2.0 → 0.2.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/global.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ declare namespace JSX {
2
+ interface Element {}
3
+ interface IntrinsicElements {
4
+ [elementName: string]: any;
5
+ }
6
+ interface Fragment {}
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hx-stream",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "keep htmx client state across page refreshes",
5
5
  "keywords": [ "htmx", "streaming" ],
6
6
  "homepage": "https://hx-stream.ajanibilby.com",
package/server.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ type Options<T extends boolean> = T extends true ? RenderOptions : DefaultOptions;
2
+ type DefaultOptions = {
3
+ abortSignal?: AbortSignal;
4
+ highWaterMark?: number;
5
+ keepAlive?: number;
6
+ };
7
+ type RenderOptions = {
8
+ render: (jsx: JSX.Element) => string;
9
+ } & DefaultOptions;
10
+ type HasRender<O> = O extends {
11
+ render: (jsx: JSX.Element) => string;
12
+ } ? true : false;
13
+ export declare class StreamResponse<JsxEnabled extends boolean> {
14
+ #private;
15
+ readonly response: Response;
16
+ get readyState(): number;
17
+ static CONNECTING: number;
18
+ static OPEN: number;
19
+ static CLOSED: number;
20
+ constructor(options: Options<JsxEnabled>);
21
+ bind(controller: ReadableByteStreamController): void;
22
+ private sendBytes;
23
+ private sendText;
24
+ private keepAlive;
25
+ send(target: string, swap: string, html: JsxEnabled extends true ? (JSX.Element | string) : string): boolean;
26
+ close(): boolean;
27
+ }
28
+ export declare function MakeStream<T extends Partial<RenderOptions>>(props: T, cb: (stream: StreamResponse<HasRender<T>>, props: T) => Promise<void> | void): Response;
29
+ export {};
package/server.js ADDED
@@ -0,0 +1,109 @@
1
+ const encoder = new TextEncoder();
2
+ const headers = {
3
+ // Chunked encoding with immediate forwarding by proxies (i.e. nginx)
4
+ "X-Content-Type-Options": "nosniff",
5
+ "X-Accel-Buffering": "no",
6
+ "Transfer-Encoding": "chunked",
7
+ "Content-Type": "text/event-stream",
8
+ // the maximum keep alive chrome shouldn't ignore
9
+ "Keep-Alive": "timeout=60",
10
+ "Connection": "keep-alive",
11
+ };
12
+ const SCALE = 36 ** 6;
13
+ function MakeBoundary() {
14
+ return "hx-" + Math.floor(Math.random() * SCALE).toString(36);
15
+ }
16
+ export class StreamResponse {
17
+ #controller;
18
+ #signal;
19
+ #timer;
20
+ #state;
21
+ #boundary;
22
+ #render;
23
+ response;
24
+ get readyState() { return this.#state; }
25
+ static CONNECTING = 0;
26
+ static OPEN = 1;
27
+ static CLOSED = 2;
28
+ constructor(options) {
29
+ this.#controller = null;
30
+ this.#state = StreamResponse.CONNECTING;
31
+ this.#render = options.render;
32
+ this.#boundary = MakeBoundary();
33
+ // immediate prepare for abortion
34
+ this.#signal = options.abortSignal;
35
+ const cancel = () => { this.close(); this.#signal?.removeEventListener("abort", cancel); };
36
+ this.#signal?.addEventListener('abort', cancel);
37
+ const start = (c) => { this.#controller = c; this.#state = StreamResponse.OPEN; };
38
+ const stream = new ReadableStream({ start, cancel }, { highWaterMark: options.highWaterMark });
39
+ this.response = new Response(stream, { headers });
40
+ this.response.headers.set("X-Chunk-Boundary", this.#boundary);
41
+ this.#timer = setInterval(() => this.keepAlive(), options.keepAlive || 30_000);
42
+ }
43
+ bind(controller) {
44
+ this.#controller = controller;
45
+ }
46
+ sendBytes(chunk) {
47
+ if (this.#state === StreamResponse.CLOSED) {
48
+ const err = new Error(`Warn: Attempted to send data on closed hx-stream`);
49
+ console.warn(err);
50
+ return false;
51
+ }
52
+ if (this.#signal?.aborted) {
53
+ this.close();
54
+ return false;
55
+ }
56
+ if (!this.#controller)
57
+ return false;
58
+ try {
59
+ this.#controller.enqueue(chunk);
60
+ }
61
+ catch (e) {
62
+ console.error(e);
63
+ this.close(); // unbind on failure
64
+ return false;
65
+ }
66
+ return true;
67
+ }
68
+ sendText(chunk) {
69
+ return this.sendBytes(encoder.encode(chunk));
70
+ }
71
+ keepAlive() { return this.sendText(" "); }
72
+ send(target, swap, html) {
73
+ if (typeof html !== "string") {
74
+ if (!this.#render)
75
+ throw new Error(`Cannot render to JSX when no renderer provided during class initialization`);
76
+ html = this.#render(html);
77
+ }
78
+ return this.sendText(`<${this.#boundary}>${target}|${swap}|${html}</${this.#boundary}>\n`);
79
+ }
80
+ close() {
81
+ if (this.#controller) {
82
+ try {
83
+ this.#controller.close();
84
+ }
85
+ catch (e) {
86
+ console.error(e);
87
+ }
88
+ this.#controller = null;
89
+ }
90
+ // Cleanup
91
+ if (this.#timer)
92
+ clearInterval(this.#timer);
93
+ // was already closed
94
+ if (this.#state === EventSource.CLOSED)
95
+ return false;
96
+ // Mark closed
97
+ this.#state = StreamResponse.CLOSED;
98
+ return true;
99
+ }
100
+ }
101
+ export function MakeStream(props, cb) {
102
+ const stream = new StreamResponse(props);
103
+ queueMicrotask(() => {
104
+ const p = cb(stream, props);
105
+ if (p instanceof Promise)
106
+ p.catch(console.error);
107
+ });
108
+ return stream.response;
109
+ }
File without changes
File without changes
File without changes