forked from kitajs/html
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsuspense.js
378 lines (317 loc) · 10.7 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
const { contentsToString } = require('./index');
const { PassThrough, Writable } = require('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,
enabled: false,
autoScript: true
};
}
/**
* 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) {
// There's no actual way of knowing if this component is being
// rendered inside a renderToString call, so we have to rely on
// this simple check: If the First Suspense render is called without
// `enabled` being true, it means no renderToString was called before.
// This is not 100% accurate, but it's the best estimation we can do.
if (!SUSPENSE_ROOT.enabled) {
throw new Error('Cannot use Suspense outside of a `renderToStream` call.');
}
if (!props.rid) {
throw new Error('Suspense requires a `rid` to be specified.');
}
// fallback may be async.
const fallback = contentsToString([props.fallback]);
if (!props.children) {
return '';
}
const children = contentsToString([props.children]);
// Returns content if it's not a promise
if (typeof children === 'string') {
return children;
}
let data = SUSPENSE_ROOT.requests.get(props.rid);
if (!data) {
throw new Error(
'Request data was deleted before all suspense components were resolved.'
);
}
// 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;
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) {
if (data) {
const stream = data.stream.deref();
// stream.emit returns true if there's a listener
// so we can safely ignore the error
if (stream && stream.emit('error', error)) {
return;
}
}
/* c8 ignore next 2 */
// Nothing else to do if no catch or listener was found
console.error(error);
})
.finally(function clearRequestData() {
// Reloads the request data as it may have been closed
data = SUSPENSE_ROOT.requests.get(props.rid);
if (!data) {
return;
}
// reduces current suspense id
if (data.running > 1) {
data.running -= 1;
// Last suspense component, runs cleanup
} else {
const stream = data.stream.deref();
if (stream && !stream.closed) {
stream.end();
}
// Removes the current state
SUSPENSE_ROOT.requests.delete(props.rid);
}
});
// 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) {
// Reloads the request data as it may have been closed
data = SUSPENSE_ROOT.requests.get(props.rid);
if (!data) {
return;
}
const stream = data.stream.deref();
// Stream was probably already closed/cleared out.
// We can safely ignore this.
if (!stream || 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) {
stream.write(SuspenseScript);
data.sent = true;
}
// Writes the chunk
stream.write(
// prettier-ignore
'<template id="N:' + run + '" data-sr>' + result + '</template><script id="S:' + run + '" data-ss>$KITA_RC(' + run + ')</script>'
);
}
}
// the real reason this is a extra function is because fastify-html-plugin and
// future plugins may want to reuse streams and this function avoids forcing
// them to reimplement the suspense logic.
/** @type {import('./suspense').pipeHtml} */
function pipeHtml(html, stream, rid) {
// When the HTML is a string, it means there were no other async components
// or async Suspense's fallbacks. We can just pipe the HTML to the stream
// and try to close it.
if (typeof html === 'string') {
stream.write(html);
const requestData = SUSPENSE_ROOT.requests.get(rid);
// This request data was already resolved or no suspenses were used.
if (!requestData || requestData.running === 0) {
stream.end();
SUSPENSE_ROOT.requests.delete(rid);
}
return;
}
html
.then(function writeStreamHtml(html) {
stream.write(html);
})
.catch(function catchError(error) {
// Emits the error down the stream or
// prints it to the console if there's no
// listener (default node impl always has a listener)
/* c8 ignore next 4 */
if (stream.emit('error', error) === false) {
console.error(error);
}
})
.finally(function endStream() {
const requestData = SUSPENSE_ROOT.requests.get(rid);
// This request data already resolved or no suspenses were used.
if (!requestData || requestData.running === 0) {
stream.end();
SUSPENSE_ROOT.requests.delete(rid);
}
});
}
/** @type {import('./suspense').renderToStream} */
function renderToStream(factory, rid) {
// Enables suspense if it's not enabled yet
if (SUSPENSE_ROOT.enabled === false) {
SUSPENSE_ROOT.enabled = true;
}
// Ensures the request id is unique
if (!rid) {
rid = SUSPENSE_ROOT.requestCounter++;
} else if (SUSPENSE_ROOT.requests.has(rid)) {
throw new Error(`The provided Request Id is already in use: ${rid}.`);
}
const stream = new PassThrough();
SUSPENSE_ROOT.requests.set(rid, {
stream: new WeakRef(stream),
running: 0,
sent: false
});
try {
// Loads the template
const html = factory(rid);
// Pipes the HTML to the stream
pipeHtml(html, stream, rid);
return stream;
} catch (renderError) {
// Could not generate even the loading template.
// This means a sync error was thrown and there's
// nothing we can do unless closing the stream
// and re-throwing the error.
stream.end();
SUSPENSE_ROOT.requests.delete(rid);
throw renderError;
}
}
/** @type {import('./suspense').renderToString} */
async function renderToString(factory, rid) {
// Enables suspense if it's not enabled yet
if (SUSPENSE_ROOT.enabled === false) {
SUSPENSE_ROOT.enabled = true;
}
// Ensures the request id is unique
if (!rid) {
rid = SUSPENSE_ROOT.requestCounter++;
} else if (SUSPENSE_ROOT.requests.has(rid)) {
throw new Error(`The provided Request Id is already in use: ${rid}.`);
}
let finalHtml = '';
const stream = new Writable({
write(chunk, _, callback) {
finalHtml += chunk.toString();
callback();
}
});
SUSPENSE_ROOT.requests.set(rid, {
stream: new WeakRef(stream),
running: 0,
sent: false
});
try {
// Loads the template
const html = factory(rid);
// Pipes the HTML to the stream
pipeHtml(html, stream, rid);
return new Promise((res, rej) => {
stream.once('finish', () => res(finalHtml));
stream.once('error', rej);
});
} catch (renderError) {
// Could not generate even the loading template.
// This means a sync error was thrown and there's
// nothing we can do unless closing the stream
// and re-throwing the error.
stream.end();
SUSPENSE_ROOT.requests.delete(rid);
throw renderError;
}
}
module.exports.Suspense = Suspense;
module.exports.pipeHtml = pipeHtml;
module.exports.renderToStream = renderToStream;
module.exports.renderToString = renderToString;
module.exports.SuspenseScript = SuspenseScript;