forked from nicojs/typed-html
-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
suspense.js
295 lines (253 loc) · 8.21 KB
/
suspense.js
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
const { contentsToString, contentToString } = require('./index');
const { Readable, PassThrough } = require('node:stream');
// Avoids double initialization in case this file is not cached by
// module bundlers.
if (!globalThis.SUSPENSE_ROOT) {
/* global SUSPENSE_ROOT */
globalThis.SUSPENSE_ROOT = {
requests: new Map(),
requestCounter: 1,
autoScript: true
};
}
function noop() {}
/**
* Simple IE11 compatible replace child scripts to replace the template streamed by the
* server.
*
* As this script is the only residue of this package that is actually sent to the client,
* it's important to keep it as small as possible and also include the license to avoid
* legal issues.
*/
// Pending data-sr elements are kept pending if their fallback has not yet been
// rendered, on each render a try to switch all pending data-sr is attempted until
// no elements are substituted.
const SuspenseScript = /* html */ `
<script id="kita-html-suspense">
/*! Apache-2.0 https://kita.js.org */
function $KITA_RC(i){
// simple aliases
var d=document,q=d.querySelector.bind(d),
// div sent as the fallback wrapper
v=q('div[id="B:'+i+'"][data-sf]'),
// template and script sent after promise finishes
t=q('template[id="N:'+i+'"][data-sr]'),s=q('script[id="S:'+i+'"][data-ss]'),
// fragment created to avoid inserting element one by one
f=d.createDocumentFragment(),
// used by iterators
c,j,
// all pending hydrations
r;
// if div or template is not found, let this hydration as pending
if(t&&v&&s){
// appends into the fragment
while(c=t.content.firstChild)
f.appendChild(c);
// replaces the div and removes the script and template
v.parentNode.replaceChild(f,v);
t.remove();
s.remove();
// looks for pending templates
r=d.querySelectorAll('template[id][data-sr]');
do{
// resets j from previous loop
j=0;
// loops over every found pending template and
for(c=0;c<r.length;c++)
if(r[c]!=t)
// let j as true while at least on $KITA_RC call returns true
j=$KITA_RC(r[c].id.slice(2))?!0:j;
}while(j)
// we know at least the original template was substituted
return!0;
}
}
</script>
`
// Removes comment lines
.replace(/^\s*\/\/.*/gm, '')
// Removes line breaks added for readability
.replace(/\n\s*/g, '');
/** @type {import('./suspense').Suspense} */
function Suspense(props) {
const children = Array.isArray(props.children)
? contentsToString(props.children)
: contentToString(props.children);
// Returns content if it's not a promise
if (typeof children === 'string') {
return children;
}
if (!props.rid) {
throw new Error('Suspense requires a `rid` to be specified.');
}
let data = SUSPENSE_ROOT.requests.get(props.rid);
if (!data) {
// Creating the request data lazily allows
// faster render() calls when no suspense
// components are used.
data = {
stream: new Readable({ read: noop }),
running: 0,
sent: false
};
SUSPENSE_ROOT.requests.set(props.rid, data);
}
// Gets the current run number for this request
// Increments first so we can differ 0 as no suspenses
// were used and 1 as the first suspense component
const run = ++data.running;
void children
.then(writeStreamTemplate)
.catch(function errorRecover(error) {
// No catch block was specified, so we can
// re-throw the error.
if (!props.catch) {
throw error;
}
let html;
// Unwraps error handler
if (typeof props.catch === 'function') {
html = props.catch(error);
} else {
html = props.catch;
}
// handles if catch block returns a string
if (typeof html === 'string') {
return writeStreamTemplate(html);
}
// must be a promise
return html.then(writeStreamTemplate);
})
.catch(function writeFatalError(error) {
data.stream.emit('error', error);
})
.finally(function clearRequestData() {
// reduces current suspense id
if (data && data.running > 1) {
data.running -= 1;
return;
}
// Last suspense component, runs cleanup
if (data && !data.stream.closed) {
data.stream.push(null);
}
// Removes the current state
SUSPENSE_ROOT.requests.delete(props.rid);
});
// Always will be a single children because multiple
// root tags aren't a valid JSX syntax
const fallback = contentToString(props.fallback);
// Keeps string return type
if (typeof fallback === 'string') {
return '<div id="B:' + run + '" data-sf>' + fallback + '</div>';
}
return fallback.then(function resolveCallback(resolved) {
return '<div id="B:' + run + '" data-sf>' + resolved + '</div>';
});
/**
* This function may be called by the catch handler in case the error could be handled.
*
* @param {string} result
*/
function writeStreamTemplate(result) {
if (
// Ensures the stream is still open (.closed may not be already defined at this point)
!SUSPENSE_ROOT.requests.has(props.rid) ||
// just to typecheck
!data ||
// Stream was already closed/cleared out.
data.stream.closed
) {
return;
}
// Writes the suspense script if its the first
// suspense component in this request data. This way following
// templates+scripts can be executed
if (SUSPENSE_ROOT.autoScript && data.sent === false) {
data.stream.push(SuspenseScript);
data.sent = true;
}
// Writes the chunk
data.stream.push(
// prettier-ignore
`<template id="N:${run}" data-sr>${result}</template><script id="S:${run}" data-ss>$KITA_RC(${run})</script>`
);
}
}
/** @type {import('./suspense').renderToStream} */
function renderToStream(html, rid) {
if (!rid) {
rid = SUSPENSE_ROOT.requestCounter++;
} else if (SUSPENSE_ROOT.requests.has(rid)) {
// Ensures the request id is unique within the current request
// error here to keep original stack trace
const error = new Error(`The provided Request Id is already in use: ${rid}.`);
// returns errored stream to avoid throws
return new Readable({
read() {
this.emit('error', error);
this.push(null);
}
});
}
if (typeof html === 'function') {
try {
html = html(rid);
} catch (error) {
// Avoids memory leaks by removing the request data
SUSPENSE_ROOT.requests.delete(rid);
// returns errored stream to avoid throws
return new Readable({
read() {
this.emit('error', error);
this.push(null);
}
});
}
}
// If no suspense component was used, this will not be defined.
const requestData = SUSPENSE_ROOT.requests.get(rid);
// No suspense was used, just return the HTML as a stream
if (!requestData) {
if (typeof html === 'string') {
return Readable.from([html]);
}
return new Readable({
read() {
void html
.then((result) => {
this.push(result);
this.push(null);
})
.catch((error) => {
this.emit('error', error);
});
}
});
}
return resolveHtmlStream(html, requestData);
}
/** @type {import('./suspense').resolveHtmlStream} */
function resolveHtmlStream(template, requestData) {
// Impossible to sync templates have their
// streams being written (sent = true) before the fallback
if (typeof template === 'string') {
requestData.stream.push(template);
return requestData.stream;
}
const prepended = new PassThrough();
void template.then(
(result) => {
prepended.push(result);
requestData.stream.pipe(prepended);
},
(error) => {
prepended.emit('error', error);
}
);
return prepended;
}
exports.Suspense = Suspense;
exports.renderToStream = renderToStream;
exports.resolveHtmlStream = resolveHtmlStream;
exports.SuspenseScript = SuspenseScript;