-
-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathstream.js
More file actions
66 lines (61 loc) · 1.53 KB
/
stream.js
File metadata and controls
66 lines (61 loc) · 1.53 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
import { Deferred } from './lib/util.js';
import { renderToChunks } from './lib/chunked.js';
/** @typedef {ReadableStream<Uint8Array> & { allReady: Promise<void>}} RenderStream */
/**
* @param {import('preact').VNode} vnode
* @param {any} [context]
* @returns {RenderStream}
*/
export function renderToReadableStream(vnode, context) {
/** @type {Deferred<void>} */
const allReady = new Deferred();
const encoder = new TextEncoder('utf-8');
const abortController = new AbortController();
let canceled = false;
/** @type {Deferred<void> | undefined} */
let pullReady;
/** @type {RenderStream} */
const stream = new ReadableStream({
start(controller) {
renderToChunks(vnode, {
context,
abortSignal: abortController.signal,
async onWrite(s) {
while (
!canceled &&
controller.desiredSize != null &&
controller.desiredSize <= 0
) {
pullReady = pullReady || new Deferred();
await pullReady.promise;
pullReady = undefined;
}
if (canceled) return;
controller.enqueue(encoder.encode(s));
}
})
.then(() => {
if (!canceled) controller.close();
allReady.resolve();
})
.catch((error) => {
if (canceled) {
allReady.resolve();
return;
}
controller.error(error);
allReady.reject(error);
});
},
pull() {
if (pullReady) pullReady.resolve();
},
cancel(reason) {
canceled = true;
if (pullReady) pullReady.resolve();
abortController.abort(reason);
}
});
stream.allReady = allReady.promise;
return stream;
}