/
index.js
651 lines (565 loc) · 18.5 KB
/
index.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
import { fork } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import colors from 'kleur';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import * as vite from 'vite';
import { mkdirp, posixify, resolve_entry, rimraf } from '../../utils/filesystem.js';
import * as sync from '../../core/sync/sync.js';
import { build_server } from './build/build_server.js';
import { build_service_worker } from './build/build_service_worker.js';
import { load_config } from '../../core/config/index.js';
import { dev } from './dev/index.js';
import { generate_manifest } from '../../core/generate_manifest/index.js';
import { runtime_directory, logger } from '../../core/utils.js';
import { find_deps, get_default_build_config } from './build/utils.js';
import { preview } from './preview/index.js';
import { get_config_aliases, get_app_aliases, get_env } from './utils.js';
import { fileURLToPath } from 'node:url';
import { create_static_module, create_dynamic_module } from '../../core/env.js';
import { is_illegal, module_guard, normalize_id } from './graph_analysis/index.js';
import { create_assets } from '../../core/sync/create_manifest_data/index.js';
const cwd = process.cwd();
/** @type {import('./types').EnforcedConfig} */
const enforced_config = {
appType: true,
base: true,
build: {
cssCodeSplit: true,
emptyOutDir: true,
lib: {
entry: true,
name: true,
formats: true
},
manifest: true,
modulePreload: {
polyfill: true
},
outDir: true,
rollupOptions: {
input: true,
output: {
format: true,
entryFileNames: true,
chunkFileNames: true,
assetFileNames: true
},
preserveEntrySignatures: true
},
ssr: true
},
publicDir: true,
resolve: {
alias: {
$app: true,
$lib: true,
'$service-worker': true
}
},
root: true
};
/** @return {import('vite').Plugin[]} */
export function sveltekit() {
return [...svelte({ prebundleSvelteLibraries: true }), kit()];
}
/**
* Returns the SvelteKit Vite plugin. Vite executes Rollup hooks as well as some of its own.
* Background reading is available at:
* - https://vitejs.dev/guide/api-plugin.html
* - https://rollupjs.org/guide/en/#plugin-development
*
* You can get an idea of the lifecycle by looking at the flow charts here:
* - https://rollupjs.org/guide/en/#build-hooks
* - https://rollupjs.org/guide/en/#output-generation-hooks
*
* @return {import('vite').Plugin}
*/
function kit() {
/** @type {import('types').ValidatedConfig} */
let svelte_config;
/** @type {import('vite').ResolvedConfig} */
let vite_config;
/** @type {import('vite').ConfigEnv} */
let vite_config_env;
/** @type {import('types').ManifestData} */
let manifest_data;
/** @type {boolean} */
let is_build;
/** @type {import('types').Logger} */
let log;
/** @type {import('types').Prerendered} */
let prerendered;
/** @type {import('types').PrerenderMap} */
let prerender_map;
/** @type {import('types').BuildData} */
let build_data;
/** @type {string | undefined} */
let deferred_warning;
/** @type {{ public: Record<string, string>; private: Record<string, string> }} */
let env;
/**
* @type {{
* build_dir: string;
* output_dir: string;
* client_out_dir: string;
* }}
*/
let paths;
let completed_build = false;
function vite_client_build_config() {
/** @type {Record<string, string>} */
const input = {
// Put unchanging assets in immutable directory. We don't set that in the
// outDir so that other plugins can add mutable assets to the bundle
start: `${runtime_directory}/client/start.js`
};
manifest_data.nodes.forEach((node) => {
if (node.component) {
const resolved = path.resolve(cwd, node.component);
const relative = decodeURIComponent(
path.relative(svelte_config.kit.files.routes, resolved)
);
const name = relative.startsWith('..')
? path.basename(node.component)
: posixify(path.join('pages', relative));
input[`components/${name}`] = resolved;
}
if (node.shared) {
const resolved = path.resolve(cwd, node.shared);
const relative = decodeURIComponent(
path.relative(svelte_config.kit.files.routes, resolved)
);
const name = relative.startsWith('..')
? path.basename(node.shared)
: posixify(path.join('pages', relative));
input[`modules/${name}`] = resolved;
}
});
return get_default_build_config({
config: svelte_config,
input,
ssr: false,
outDir: `${paths.client_out_dir}`
});
}
/**
* @param {import('rollup').OutputAsset[]} assets
* @param {import('rollup').OutputChunk[]} chunks
*/
function client_build_info(assets, chunks) {
/** @type {import('vite').Manifest} */
const vite_manifest = JSON.parse(
fs.readFileSync(`${paths.client_out_dir}/${vite_config.build.manifest}`, 'utf-8')
);
const entry_id = posixify(path.relative(cwd, `${runtime_directory}/client/start.js`));
return {
assets,
chunks,
entry: find_deps(vite_manifest, entry_id, false),
vite_manifest
};
}
// TODO remove this for 1.0
check_vite_version();
return {
name: 'vite-plugin-svelte-kit',
/**
* Build the SvelteKit-provided Vite config to be merged with the user's vite.config.js file.
* @see https://vitejs.dev/guide/api-plugin.html#config
*/
async config(config, config_env) {
vite_config_env = config_env;
svelte_config = await load_config();
env = get_env(svelte_config.kit.env, vite_config_env.mode);
// The config is created in build_server for SSR mode and passed inline
if (config.build?.ssr) return;
is_build = config_env.command === 'build';
paths = {
build_dir: `${svelte_config.kit.outDir}/build`,
output_dir: `${svelte_config.kit.outDir}/output`,
client_out_dir: `${svelte_config.kit.outDir}/output/client`
};
if (is_build) {
manifest_data = (await sync.all(svelte_config, config_env.mode)).manifest_data;
const new_config = vite_client_build_config();
const warning = warn_overridden_config(config, new_config);
if (warning) console.error(warning + '\n');
return new_config;
}
const allow = new Set([
svelte_config.kit.files.lib,
svelte_config.kit.files.routes,
svelte_config.kit.outDir,
path.resolve(cwd, 'src'), // TODO this isn't correct if user changed all his files to sth else than src (like in test/options)
path.resolve(cwd, 'node_modules'),
path.resolve(vite.searchForWorkspaceRoot(cwd), 'node_modules')
]);
// We can only add directories to the allow list, so we find out
// if there's a client hooks file and pass its directory
const client_hooks = resolve_entry(svelte_config.kit.files.hooks.client);
if (client_hooks) {
allow.add(path.dirname(client_hooks));
}
// dev and preview config can be shared
/** @type {import('vite').UserConfig} */
const result = {
appType: 'custom',
base: svelte_config.kit.paths.base,
build: {
rollupOptions: {
// Vite dependency crawler needs an explicit JS entry point
// eventhough server otherwise works without it
input: `${runtime_directory}/client/start.js`
}
},
define: {
__SVELTEKIT_APP_VERSION_POLL_INTERVAL__: '0',
__SVELTEKIT_BROWSER__: config_env.ssrBuild ? 'false' : 'true',
__SVELTEKIT_DEV__: 'true'
},
publicDir: svelte_config.kit.files.assets,
resolve: {
alias: [...get_app_aliases(svelte_config.kit), ...get_config_aliases(svelte_config.kit)]
},
root: cwd,
server: {
fs: {
allow: [...allow]
},
watch: {
ignored: [
// Ignore all siblings of config.kit.outDir/generated
`${posixify(svelte_config.kit.outDir)}/!(generated)`
]
}
},
ssr: {
// Without this, Vite will treat `@sveltejs/kit` as noExternal if it's
// a linked dependency, and that causes modules to be imported twice
// under different IDs, which breaks a bunch of stuff
// https://github.com/vitejs/vite/pull/9296
external: ['@sveltejs/kit']
},
optimizeDeps: {
exclude: ['@sveltejs/kit']
}
};
deferred_warning = warn_overridden_config(config, result);
return result;
},
async resolveId(id) {
// treat $env/static/[public|private] as virtual
if (id.startsWith('$env/') || id === '$service-worker') return `\0${id}`;
},
async load(id, options) {
if (options?.ssr === false) {
const normalized_cwd = vite.normalizePath(cwd);
const normalized_lib = vite.normalizePath(svelte_config.kit.files.lib);
if (
is_illegal(id, {
cwd: normalized_cwd,
node_modules: vite.normalizePath(path.join(cwd, 'node_modules')),
server: vite.normalizePath(path.join(normalized_lib, 'server'))
})
) {
const relative = normalize_id(id, normalized_lib, normalized_cwd);
throw new Error(`Cannot import ${relative} into client-side code`);
}
}
switch (id) {
case '\0$env/static/private':
return create_static_module('$env/static/private', env.private);
case '\0$env/static/public':
return create_static_module('$env/static/public', env.public);
case '\0$env/dynamic/private':
return create_dynamic_module(
'private',
vite_config_env.command === 'serve' ? env.private : undefined
);
case '\0$env/dynamic/public':
return create_dynamic_module(
'public',
vite_config_env.command === 'serve' ? env.public : undefined
);
case '\0$service-worker':
return create_service_worker_module(svelte_config);
}
},
/**
* Stores the final config.
*/
configResolved(config) {
vite_config = config;
},
/**
* Clears the output directories.
*/
buildStart() {
if (vite_config.build.ssr) {
return;
}
// Reset for new build. Goes here because `build --watch` calls buildStart but not config
completed_build = false;
if (is_build) {
if (!vite_config.build.watch) {
rimraf(paths.build_dir);
rimraf(paths.output_dir);
}
mkdirp(paths.build_dir);
mkdirp(paths.output_dir);
}
},
/**
* Vite builds a single bundle. We need three bundles: client, server, and service worker.
* The user's package.json scripts will invoke the Vite CLI to execute the client build. We
* then use this hook to kick off builds for the server and service worker.
*/
writeBundle: {
sequential: true,
async handler(_options, bundle) {
if (vite_config.build.ssr) {
return;
}
const guard = module_guard(this, {
cwd: vite.normalizePath(process.cwd()),
lib: vite.normalizePath(svelte_config.kit.files.lib)
});
manifest_data.nodes.forEach((_node, i) => {
const id = vite.normalizePath(
path.resolve(svelte_config.kit.outDir, `generated/nodes/${i}.js`)
);
guard.check(id);
});
const verbose = vite_config.logLevel === 'info';
log = logger({
verbose
});
fs.writeFileSync(
`${paths.client_out_dir}/${svelte_config.kit.appDir}/version.json`,
JSON.stringify({ version: svelte_config.kit.version.name })
);
const { assets, chunks } = collect_output(bundle);
log.info(
`Client build completed. Wrote ${chunks.length} chunks and ${assets.length} assets`
);
log.info('Building server');
const options = {
cwd,
config: svelte_config,
vite_config,
vite_config_env,
build_dir: paths.build_dir, // TODO just pass `paths`
manifest_data,
output_dir: paths.output_dir,
service_worker_entry_file: resolve_entry(svelte_config.kit.files.serviceWorker)
};
const client = client_build_info(assets, chunks);
const server = await build_server(options, client);
/** @type {import('types').BuildData} */
build_data = {
app_dir: svelte_config.kit.appDir,
app_path: `${svelte_config.kit.paths.base.slice(1)}${
svelte_config.kit.paths.base ? '/' : ''
}${svelte_config.kit.appDir}`,
manifest_data,
service_worker: options.service_worker_entry_file ? 'service-worker.js' : null, // TODO make file configurable?
client,
server
};
const manifest_path = `${paths.output_dir}/server/manifest-full.js`;
fs.writeFileSync(
manifest_path,
`export const manifest = ${generate_manifest({
build_data,
relative_path: '.',
routes: manifest_data.routes
})};\n`
);
log.info('Prerendering');
await new Promise((fulfil, reject) => {
const results_path = `${svelte_config.kit.outDir}/generated/prerendered.json`;
// do prerendering in a subprocess so any dangling stuff gets killed upon completion
const script = fileURLToPath(
new URL('../../core/prerender/prerender.js', import.meta.url)
);
const child = fork(
script,
[
vite_config.build.outDir,
manifest_path,
results_path,
'' + verbose,
JSON.stringify({ ...env.private, ...env.public })
],
{
stdio: 'inherit'
}
);
child.on('exit', (code) => {
if (code) {
reject(new Error(`Prerendering failed with code ${code}`));
} else {
const results = JSON.parse(fs.readFileSync(results_path, 'utf8'), (key, value) => {
if (key === 'pages' || key === 'assets' || key === 'redirects') {
return new Map(value);
}
return value;
});
prerendered = results.prerendered;
prerender_map = new Map(results.prerender_map);
fulfil(undefined);
}
});
});
// generate a new manifest that doesn't include prerendered pages
fs.writeFileSync(
`${paths.output_dir}/server/manifest.js`,
`export const manifest = ${generate_manifest({
build_data,
relative_path: '.',
routes: manifest_data.routes.filter((route) => prerender_map.get(route.id) !== true)
})};\n`
);
if (options.service_worker_entry_file) {
if (svelte_config.kit.paths.assets) {
throw new Error('Cannot use service worker alongside config.kit.paths.assets');
}
log.info('Building service worker');
await build_service_worker(options, prerendered, client.vite_manifest);
}
console.log(
`\nRun ${colors.bold().cyan('npm run preview')} to preview your production build locally.`
);
completed_build = true;
}
},
/**
* Runs the adapter.
*/
closeBundle: {
sequential: true,
async handler() {
// vite calls closeBundle when dev-server restarts, ignore that,
// and only adapt when build successfully completes.
const is_restart = !completed_build;
if (vite_config.build.ssr || is_restart) {
return;
}
if (svelte_config.kit.adapter) {
const { adapt } = await import('../../core/adapt/index.js');
await adapt(svelte_config, build_data, prerendered, prerender_map, { log });
} else {
console.log(colors.bold().yellow('\nNo adapter specified'));
const link = colors.bold().cyan('https://kit.svelte.dev/docs/adapters');
console.log(
`See ${link} to learn how to configure your app to run on the platform of your choosing`
);
}
// avoid making the manifest available to users
fs.unlinkSync(`${paths.output_dir}/client/${vite_config.build.manifest}`);
fs.unlinkSync(`${paths.output_dir}/server/${vite_config.build.manifest}`);
}
},
/**
* Adds the SvelteKit middleware to do SSR in dev mode.
* @see https://vitejs.dev/guide/api-plugin.html#configureserver
*/
async configureServer(vite) {
// This method is called by Vite after clearing the screen.
// This patch ensures we can log any important messages afterwards for the user to see.
const print_urls = vite.printUrls;
vite.printUrls = function () {
print_urls.apply(this);
if (deferred_warning) console.error('\n' + deferred_warning);
};
return await dev(vite, vite_config, svelte_config);
},
/**
* Adds the SvelteKit middleware to do SSR in preview mode.
* @see https://vitejs.dev/guide/api-plugin.html#configurepreviewserver
*/
configurePreviewServer(vite) {
return preview(vite, vite_config, svelte_config);
}
};
}
function check_vite_version() {
// TODO parse from kit peer deps and maybe do a full semver compare if we ever require feature releases a min
const min_required_vite_major = 3;
const vite_version = vite.version ?? '2.x'; // vite started exporting it's version in 3.0
const current_vite_major = parseInt(vite_version.split('.')[0], 10);
if (current_vite_major < min_required_vite_major) {
throw new Error(
`Vite version ${current_vite_major} is no longer supported. Please upgrade to version ${min_required_vite_major}`
);
}
}
/** @param {import('rollup').OutputBundle} bundle */
function collect_output(bundle) {
/** @type {import('rollup').OutputChunk[]} */
const chunks = [];
/** @type {import('rollup').OutputAsset[]} */
const assets = [];
for (const value of Object.values(bundle)) {
// collect asset and output chunks
if (value.type === 'asset') {
assets.push(value);
} else {
chunks.push(value);
}
}
return { assets, chunks };
}
/**
* @param {Record<string, any>} config
* @param {Record<string, any>} resolved_config
*/
function warn_overridden_config(config, resolved_config) {
const overridden = find_overridden_config(config, resolved_config, enforced_config, '', []);
if (overridden.length > 0) {
return (
colors.bold().red('The following Vite config options will be overridden by SvelteKit:') +
overridden.map((key) => `\n - ${key}`).join('')
);
}
}
/**
* @param {Record<string, any>} config
* @param {Record<string, any>} resolved_config
* @param {import('./types').EnforcedConfig} enforced_config
* @param {string} path
* @param {string[]} out used locally to compute the return value
*/
function find_overridden_config(config, resolved_config, enforced_config, path, out) {
for (const key in enforced_config) {
if (typeof config === 'object' && config !== null && key in config) {
const enforced = enforced_config[key];
if (enforced === true) {
if (config[key] !== resolved_config[key]) {
out.push(path + key);
}
} else {
find_overridden_config(config[key], resolved_config[key], enforced, path + key + '.', out);
}
}
}
return out;
}
/**
* @param {import('types').ValidatedConfig} config
*/
const create_service_worker_module = (config) => `
if (typeof self === 'undefined' || self instanceof ServiceWorkerGlobalScope === false) {
throw new Error('This module can only be imported inside a service worker');
}
export const build = [];
export const files = [
${create_assets(config)
.filter((asset) => config.kit.serviceWorker.files(asset.file))
.map((asset) => `${JSON.stringify(`${config.kit.paths.base}/${asset.file}`)}`)
.join(',\n\t\t\t\t')}
];
export const prerendered = [];
export const version = ${JSON.stringify(config.kit.version.name)};
`;