-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrender.ts
More file actions
229 lines (185 loc) · 6.03 KB
/
render.ts
File metadata and controls
229 lines (185 loc) · 6.03 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
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
import { Readable } from 'node:stream';
import {
type DarkElement,
type Callback,
type CallbackWithValue,
type Resource,
ROOT,
Fiber,
CREATE_EFFECT_TAG,
STATE_SCRIPT_TYPE,
TaskPriority,
platform,
flatten,
TagVirtualNode,
createReplacer,
unmountRoot,
setRootId,
getRootId,
$$scope,
nextTick,
dummyFn,
falseFn,
scheduler,
} from '@dark-engine/core';
import { type MetatagsBox, detectIsMetatagsBox } from '@dark-engine/platform-browser';
import { createNativeElement, commit, finishCommit, createChunk, createNativeChildrenNodes } from '../dom';
import { type NativeElement, TagNativeElement } from '../native-element';
import { DOCTYPE } from '../constants';
const spawn = nextTick; // !
let nextRootId = -1;
let isInjected = false;
function inject() {
platform.createElement = createNativeElement as typeof platform.createElement;
platform.raf = dummyFn as unknown as typeof platform.raf;
platform.caf = dummyFn;
platform.spawn = spawn;
platform.commit = commit;
platform.finishCommit = finishCommit;
platform.detectIsDynamic = falseFn;
isInjected = true;
}
type ScheduleRenderOptions = {
element: DarkElement;
onStart: Callback;
onError: CallbackWithValue<string>;
onCompleted: Callback;
};
function scheduleRender(options: ScheduleRenderOptions) {
!isInjected && inject();
const { element, onCompleted, onError, onStart } = options;
const rootId = getNextRootId();
const callback = () => {
setRootId(rootId);
const $scope = $$scope();
const fiber = new Fiber().mutate({
el: new TagNativeElement(ROOT),
inst: new TagVirtualNode(ROOT, {}, flatten([element || createReplacer()]) as TagVirtualNode['children']),
tag: CREATE_EFFECT_TAG,
});
const emitter = $scope.getEmitter();
$scope.setIsStream(true);
$scope.resetMount();
$scope.setWorkInProgress(fiber);
$scope.setUnitOfWork(fiber);
onStart();
emitter.on('finish', () => {
emitter.kill();
onCompleted();
});
emitter.on<string>('error', err => {
emitter.kill();
onError(err);
});
};
scheduler.schedule(callback, { priority: TaskPriority.NORMAL, forceAsync: true });
}
type RenderToStreamOptions = {
bootstrapScripts?: Array<string>;
bootstrapModules?: Array<string>;
chunkSize?: number;
awaitMetatags?: boolean;
};
function renderToReadableStream(element: DarkElement, options?: RenderToStreamOptions, fromStream?: boolean): Readable {
const { bootstrapScripts = [], bootstrapModules = [], chunkSize = 500, awaitMetatags = false } = options || {};
const stream = new Readable({ encoding: 'utf-8', read() {} });
let canSendChunks = true;
let hasMetatags = false;
let content = '';
let stash = '';
const onStart = () => {
const emitter = $$scope().getEmitter();
emitter.on<MetatagsBox>('box', box => {
if (!hasMetatags && detectIsMetatagsBox(box)) {
const data = createMetadata(box.vNodes);
hasMetatags = true;
if (awaitMetatags) {
canSendChunks = true;
content += data + stash;
stash = '';
} else if (!fromStream) {
content = content.replace(HEAD_CLOSED_CHUNK, data + HEAD_CLOSED_CHUNK);
}
}
});
emitter.on<Fiber<NativeElement>>('chunk', fiber => {
const chunk = createChunk(fiber);
if (chunk === HEAD_CLOSED_CHUNK && awaitMetatags && !hasMetatags) {
canSendChunks = false;
}
if (canSendChunks) {
if (chunk === BODY_CLOSED_CHUNK && (bootstrapScripts.length > 0 || bootstrapModules.length > 0)) {
content += addScripts(bootstrapScripts, false);
content += addScripts(bootstrapModules, true);
}
content += chunk;
if (content.length >= chunkSize) {
stream.push(content);
content = '';
}
} else {
stash += chunk;
}
});
};
const onCompleted = () => {
const rootId = getRootId();
if (content) {
stream.push(content);
content = '';
}
stream.push(withState());
stream.push(null);
unmountRoot(rootId);
};
const onError = (err: string) => {
const rootId = getRootId();
stream.emit('error', new Error(err));
stream.push(null);
unmountRoot(rootId);
};
scheduleRender({ element, onStart, onCompleted, onError });
return stream;
}
function renderToString(element: DarkElement): Promise<string> {
return convertStreamToPromise(renderToReadableStream(element));
}
function renderToStream(element: DarkElement, options?: RenderToStreamOptions): Readable {
const stream = renderToReadableStream(element, options, true);
stream.push(DOCTYPE);
return stream;
}
function convertStreamToPromise(stream: Readable) {
return new Promise<string>((resolve, reject) => {
let data = '';
stream.on('data', chunk => (data += chunk));
stream.on('end', () => resolve(data));
stream.on('error', reject);
});
}
function addScripts(scripts: Array<string>, isModule: boolean) {
if (scripts.length === 0) return '';
let content = '';
scripts.forEach(x => (content += isModule ? createModule(x) : createScript(x)));
return content;
}
function withState(content = '') {
const $scope = $$scope();
const state = $scope.getResources();
const resources: Record<string, Resource> = {};
if (state.size === 0) return content;
state.forEach((value, key) => (resources[key] = value));
const encoded = Buffer.from(JSON.stringify(resources)).toString('base64');
const $content = `${content}<script type="${STATE_SCRIPT_TYPE}">"${encoded}"</script>`;
return $content;
}
const createMetadata = (vNodes: Array<TagVirtualNode>) =>
createNativeChildrenNodes(vNodes)
.map(x => x.renderToString())
.join('');
const createModule = (src: string) => `<script type="module" src="${src}" defer></script>`;
const createScript = (src: string) => `<script src="${src}" defer></script>`;
const getNextRootId = () => ++nextRootId;
const HEAD_CLOSED_CHUNK = '</head>';
const BODY_CLOSED_CHUNK = '</body>';
export { renderToString, renderToStream, convertStreamToPromise, inject };