-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
builder.js
237 lines (199 loc) · 6.04 KB
/
builder.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
import { existsSync, statSync, createReadStream, createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream';
import { promisify } from 'node:util';
import { fork } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import glob from 'tiny-glob';
import zlib from 'zlib';
import { copy, rimraf, mkdirp } from '../../utils/filesystem.js';
import { generate_manifest } from '../generate_manifest/index.js';
import { get_route_segments } from '../../utils/routing.js';
import { get_env } from '../../exports/vite/utils.js';
const pipe = promisify(pipeline);
/**
* Creates the Builder which is passed to adapters for building the application.
* @param {{
* config: import('types').ValidatedConfig;
* build_data: import('types').BuildData;
* routes: import('types').RouteData[];
* prerendered: import('types').Prerendered;
* log: import('types').Logger;
* }} opts
* @returns {import('types').Builder}
*/
export function create_builder({ config, build_data, routes, prerendered, log }) {
return {
log,
rimraf,
mkdirp,
copy,
config,
prerendered,
async createEntries(fn) {
/** @type {import('types').RouteDefinition[]} */
const facades = routes.map((route) => {
/** @type {Set<import('types').HttpMethod>} */
const methods = new Set();
if (route.page) {
methods.add('GET');
}
if (route.endpoint) {
for (const method of build_data.server.methods[route.endpoint.file]) {
methods.add(method);
}
}
return {
id: route.id,
segments: get_route_segments(route.id).map((segment) => ({
dynamic: segment.includes('['),
rest: segment.includes('[...'),
content: segment
})),
pattern: route.pattern,
methods: Array.from(methods)
};
});
const seen = new Set();
for (let i = 0; i < routes.length; i += 1) {
const route = routes[i];
const { id, filter, complete } = fn(facades[i]);
if (seen.has(id)) continue;
seen.add(id);
const group = [route];
// figure out which lower priority routes should be considered fallbacks
for (let j = i + 1; j < routes.length; j += 1) {
if (filter(facades[j])) {
group.push(routes[j]);
}
}
const filtered = new Set(group);
// heuristic: if /foo/[bar] is included, /foo/[bar].json should
// also be included, since the page likely needs the endpoint
// TODO is this still necessary, given the new way of doing things?
filtered.forEach((route) => {
if (route.page) {
const endpoint = routes.find((candidate) => candidate.id === route.id + '.json');
if (endpoint) {
filtered.add(endpoint);
}
}
});
if (filtered.size > 0) {
await complete({
generateManifest: ({ relativePath }) =>
generate_manifest({
build_data,
relative_path: relativePath,
routes: Array.from(filtered)
})
});
}
}
},
generateFallback(dest) {
// do prerendering in a subprocess so any dangling stuff gets killed upon completion
const script = fileURLToPath(new URL('../prerender/fallback.js', import.meta.url));
const manifest_path = `${config.kit.outDir}/output/server/manifest-full.js`;
const env = get_env(config.kit.env, 'production');
return new Promise((fulfil, reject) => {
const child = fork(
script,
[dest, manifest_path, JSON.stringify({ ...env.private, ...env.public })],
{
stdio: 'inherit'
}
);
child.on('exit', (code) => {
if (code) {
reject(new Error(`Could not create a fallback page — failed with code ${code}`));
} else {
fulfil(undefined);
}
});
});
},
generateManifest: ({ relativePath }) => {
return generate_manifest({
build_data,
relative_path: relativePath,
routes
});
},
getBuildDirectory(name) {
return `${config.kit.outDir}/${name}`;
},
getClientDirectory() {
return `${config.kit.outDir}/output/client`;
},
getServerDirectory() {
return `${config.kit.outDir}/output/server`;
},
getAppPath() {
return build_data.app_path;
},
writeClient(dest) {
return [...copy(`${config.kit.outDir}/output/client`, dest)];
},
// @ts-expect-error
writePrerendered(dest, opts) {
// TODO remove for 1.0
if (opts?.fallback) {
throw new Error(
'The fallback option no longer exists — use builder.generateFallback(fallback) instead'
);
}
const source = `${config.kit.outDir}/output/prerendered`;
return [...copy(`${source}/pages`, dest), ...copy(`${source}/dependencies`, dest)];
},
writeServer(dest) {
return copy(`${config.kit.outDir}/output/server`, dest);
},
// TODO remove these methods for 1.0
// @ts-expect-error
writeStatic() {
throw new Error(
`writeStatic has been removed. Please ensure you are using the latest version of ${
config.kit.adapter.name || 'your adapter'
}`
);
},
async compress(directory) {
if (!existsSync(directory)) {
return;
}
const files = await glob('**/*.{html,js,json,css,svg,xml,wasm}', {
cwd: directory,
dot: true,
absolute: true,
filesOnly: true
});
await Promise.all(
files.map((file) => Promise.all([compress_file(file, 'gz'), compress_file(file, 'br')]))
);
},
async prerender() {
throw new Error(
'builder.prerender() has been removed. Prerendering now takes place in the build phase — see builder.prerender and builder.writePrerendered'
);
}
};
}
/**
* @param {string} file
* @param {'gz' | 'br'} format
*/
async function compress_file(file, format = 'gz') {
const compress =
format == 'br'
? zlib.createBrotliCompress({
params: {
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
[zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: statSync(file).size
}
})
: zlib.createGzip({ level: zlib.constants.Z_BEST_COMPRESSION });
const source = createReadStream(file);
const destination = createWriteStream(`${file}.${format}`);
await pipe(source, compress, destination);
}