@sveltejs/kit 1.0.0-next.391 → 1.0.0-next.394

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.js CHANGED
@@ -1,16 +1,23 @@
1
- import * as fs from 'fs';
2
- import fs__default, { readFileSync, writeFileSync, readdirSync, statSync } from 'fs';
3
- import path__default, { join, dirname, resolve as resolve$1, normalize } from 'path';
4
- import { a as load_template, $, c as coalesce_to_error, l as load_config } from './chunks/error.js';
1
+ import { fork } from 'node:child_process';
2
+ import fs$1 from 'node:fs';
3
+ import path from 'node:path';
4
+ import { a as load_template, $, l as load_config } from './chunks/index.js';
5
5
  import { svelte } from '@sveltejs/vite-plugin-svelte';
6
6
  import * as vite from 'vite';
7
7
  import { loadConfigFromFile } from 'vite';
8
- import { p as posixify, m as mkdirp, w as walk, r as rimraf } from './chunks/write_tsconfig.js';
9
- import { g as get_runtime_directory, s, i as init, a as get_runtime_prefix, u as update, b as get_mime_lookup, p as parse_route_id, c as all, l as logger } from './chunks/sync.js';
10
- import { URL as URL$1, pathToFileURL } from 'url';
11
- import { installPolyfills } from './node/polyfills.js';
8
+ import { p as posixify, m as mkdirp, r as rimraf } from './chunks/filesystem.js';
9
+ import { s, i as init, u as update, p as parse_route_id, a as all } from './chunks/sync.js';
10
+ import * as fs from 'fs';
11
+ import fs__default, { readdirSync, statSync } from 'fs';
12
+ import path__default, { resolve, join, normalize } from 'path';
13
+ import { g as get_runtime_directory, a as get_runtime_prefix, b as get_mime_lookup, l as logger } from './chunks/utils.js';
12
14
  import * as qs from 'querystring';
15
+ import { URL as URL$1, pathToFileURL } from 'url';
13
16
  import { getRequest, setResponse } from './node.js';
17
+ import { installPolyfills } from './node/polyfills.js';
18
+ import { c as coalesce_to_error } from './chunks/error.js';
19
+ import { fileURLToPath } from 'node:url';
20
+ import './chunks/write_tsconfig.js';
14
21
  import 'assert';
15
22
  import 'net';
16
23
  import 'http';
@@ -31,22 +38,26 @@ import 'node:zlib';
31
38
  import 'node:stream';
32
39
  import 'node:buffer';
33
40
  import 'node:util';
34
- import 'node:url';
35
41
  import 'node:net';
36
- import 'node:fs';
37
- import 'node:path';
38
42
  import 'crypto';
39
43
 
40
44
  /**
45
+ * @param {import('vite').ResolvedConfig} config
41
46
  * @param {import('vite').ConfigEnv} config_env
42
47
  * @return {Promise<import('vite').UserConfig>}
43
48
  */
44
- async function get_vite_config(config_env) {
45
- const config = (await loadConfigFromFile(config_env))?.config;
46
- if (!config) {
49
+ async function get_vite_config(config, config_env) {
50
+ const loaded = await loadConfigFromFile(
51
+ config_env,
52
+ config.configFile,
53
+ undefined,
54
+ config.logLevel
55
+ );
56
+
57
+ if (!loaded) {
47
58
  throw new Error('Could not load Vite config');
48
59
  }
49
- return { ...config, mode: config_env.mode };
60
+ return { ...loaded.config, mode: config_env.mode };
50
61
  }
51
62
 
52
63
  /**
@@ -434,6 +445,7 @@ export class Server {
434
445
  * @param {{
435
446
  * cwd: string;
436
447
  * config: import('types').ValidatedConfig;
448
+ * vite_config: import('vite').ResolvedConfig;
437
449
  * vite_config_env: import('vite').ConfigEnv;
438
450
  * manifest_data: import('types').ManifestData;
439
451
  * build_dir: string;
@@ -446,6 +458,7 @@ async function build_server(options, client) {
446
458
  const {
447
459
  cwd,
448
460
  config,
461
+ vite_config,
449
462
  vite_config_env,
450
463
  manifest_data,
451
464
  build_dir,
@@ -510,11 +523,9 @@ async function build_server(options, client) {
510
523
  })
511
524
  );
512
525
 
513
- const vite_config = await get_vite_config(vite_config_env);
514
-
515
526
  const merged_config = merge_vite_configs(
516
527
  get_default_config({ config, input, ssr: true, outDir: `${output_dir}/server` }),
517
- vite_config
528
+ await get_vite_config(vite_config, vite_config_env)
518
529
  );
519
530
 
520
531
  remove_svelte_kit(merged_config);
@@ -611,6 +622,7 @@ function get_methods(cwd, output, manifest_data) {
611
622
  /**
612
623
  * @param {{
613
624
  * config: import('types').ValidatedConfig;
625
+ * vite_config: import('vite').ResolvedConfig;
614
626
  * vite_config_env: import('vite').ConfigEnv;
615
627
  * manifest_data: import('types').ManifestData;
616
628
  * output_dir: string;
@@ -620,7 +632,7 @@ function get_methods(cwd, output, manifest_data) {
620
632
  * @param {import('vite').Manifest} client_manifest
621
633
  */
622
634
  async function build_service_worker(
623
- { config, vite_config_env, manifest_data, output_dir, service_worker_entry_file },
635
+ { config, vite_config, vite_config_env, manifest_data, output_dir, service_worker_entry_file },
624
636
  prerendered,
625
637
  client_manifest
626
638
  ) {
@@ -667,8 +679,7 @@ async function build_service_worker(
667
679
  .trim()
668
680
  );
669
681
 
670
- const vite_config = await get_vite_config(vite_config_env);
671
- const merged_config = merge_vite_configs(vite_config, {
682
+ const merged_config = merge_vite_configs(await get_vite_config(vite_config, vite_config_env), {
672
683
  base: assets_base(config.kit),
673
684
  build: {
674
685
  lib: {
@@ -699,744 +710,8 @@ async function build_service_worker(
699
710
  await vite.build(merged_config);
700
711
  }
701
712
 
702
- const absolute = /^([a-z]+:)?\/?\//;
703
- const scheme = /^[a-z]+:/;
704
-
705
- /**
706
- * @param {string} base
707
- * @param {string} path
708
- */
709
- function resolve(base, path) {
710
- if (scheme.test(path)) return path;
711
-
712
- const base_match = absolute.exec(base);
713
- const path_match = absolute.exec(path);
714
-
715
- if (!base_match) {
716
- throw new Error(`bad base path: "${base}"`);
717
- }
718
-
719
- const baseparts = path_match ? [] : base.slice(base_match[0].length).split('/');
720
- const pathparts = path_match ? path.slice(path_match[0].length).split('/') : path.split('/');
721
-
722
- baseparts.pop();
723
-
724
- for (let i = 0; i < pathparts.length; i += 1) {
725
- const part = pathparts[i];
726
- if (part === '.') continue;
727
- else if (part === '..') baseparts.pop();
728
- else baseparts.push(part);
729
- }
730
-
731
- const prefix = (path_match && path_match[0]) || (base_match && base_match[0]) || '';
732
-
733
- return `${prefix}${baseparts.join('/')}`;
734
- }
735
-
736
- /** @param {string} path */
737
- function is_root_relative(path) {
738
- return path[0] === '/' && path[1] !== '/';
739
- }
740
-
741
- /**
742
- * @typedef {{
743
- * fn: () => Promise<any>,
744
- * fulfil: (value: any) => void,
745
- * reject: (error: Error) => void
746
- * }} Task
747
- */
748
-
749
- /** @param {number} concurrency */
750
- function queue(concurrency) {
751
- /** @type {Task[]} */
752
- const tasks = [];
753
-
754
- let current = 0;
755
-
756
- /** @type {(value?: any) => void} */
757
- let fulfil;
758
-
759
- /** @type {(error: Error) => void} */
760
- let reject;
761
-
762
- let closed = false;
763
-
764
- const done = new Promise((f, r) => {
765
- fulfil = f;
766
- reject = r;
767
- });
768
-
769
- done.catch(() => {
770
- // this is necessary in case a catch handler is never added
771
- // to the done promise by the user
772
- });
773
-
774
- function dequeue() {
775
- if (current < concurrency) {
776
- const task = tasks.shift();
777
-
778
- if (task) {
779
- current += 1;
780
- const promise = Promise.resolve(task.fn());
781
-
782
- promise
783
- .then(task.fulfil, (err) => {
784
- task.reject(err);
785
- reject(err);
786
- })
787
- .then(() => {
788
- current -= 1;
789
- dequeue();
790
- });
791
- } else if (current === 0) {
792
- closed = true;
793
- fulfil();
794
- }
795
- }
796
- }
797
-
798
- return {
799
- /** @param {() => any} fn */
800
- add: (fn) => {
801
- if (closed) throw new Error('Cannot add tasks to a queue that has ended');
802
-
803
- const promise = new Promise((fulfil, reject) => {
804
- tasks.push({ fn, fulfil, reject });
805
- });
806
-
807
- dequeue();
808
- return promise;
809
- },
810
-
811
- done: () => {
812
- if (current === 0) {
813
- closed = true;
814
- fulfil();
815
- }
816
-
817
- return done;
818
- }
819
- };
820
- }
821
-
822
- const DOCTYPE = 'DOCTYPE';
823
- const CDATA_OPEN = '[CDATA[';
824
- const CDATA_CLOSE = ']]>';
825
- const COMMENT_OPEN = '--';
826
- const COMMENT_CLOSE = '-->';
827
-
828
- const TAG_OPEN = /[a-zA-Z]/;
829
- const TAG_CHAR = /[a-zA-Z0-9]/;
830
- const ATTRIBUTE_NAME = /[^\t\n\f />"'=]/;
831
-
832
- const WHITESPACE = /[\s\n\r]/;
833
-
834
- /** @param {string} html */
835
- function crawl(html) {
836
- /** @type {string[]} */
837
- const hrefs = [];
838
-
839
- let i = 0;
840
- main: while (i < html.length) {
841
- const char = html[i];
842
-
843
- if (char === '<') {
844
- if (html[i + 1] === '!') {
845
- i += 2;
846
-
847
- if (html.slice(i, i + DOCTYPE.length).toUpperCase() === DOCTYPE) {
848
- i += DOCTYPE.length;
849
- while (i < html.length) {
850
- if (html[i++] === '>') {
851
- continue main;
852
- }
853
- }
854
- }
855
-
856
- // skip cdata
857
- if (html.slice(i, i + CDATA_OPEN.length) === CDATA_OPEN) {
858
- i += CDATA_OPEN.length;
859
- while (i < html.length) {
860
- if (html.slice(i, i + CDATA_CLOSE.length) === CDATA_CLOSE) {
861
- i += CDATA_CLOSE.length;
862
- continue main;
863
- }
864
-
865
- i += 1;
866
- }
867
- }
868
-
869
- // skip comments
870
- if (html.slice(i, i + COMMENT_OPEN.length) === COMMENT_OPEN) {
871
- i += COMMENT_OPEN.length;
872
- while (i < html.length) {
873
- if (html.slice(i, i + COMMENT_CLOSE.length) === COMMENT_CLOSE) {
874
- i += COMMENT_CLOSE.length;
875
- continue main;
876
- }
877
-
878
- i += 1;
879
- }
880
- }
881
- }
882
-
883
- // parse opening tags
884
- const start = ++i;
885
- if (TAG_OPEN.test(html[start])) {
886
- while (i < html.length) {
887
- if (!TAG_CHAR.test(html[i])) {
888
- break;
889
- }
890
-
891
- i += 1;
892
- }
893
-
894
- const tag = html.slice(start, i).toUpperCase();
895
-
896
- if (tag === 'SCRIPT' || tag === 'STYLE') {
897
- while (i < html.length) {
898
- if (
899
- html[i] === '<' &&
900
- html[i + 1] === '/' &&
901
- html.slice(i + 2, i + 2 + tag.length).toUpperCase() === tag
902
- ) {
903
- continue main;
904
- }
905
-
906
- i += 1;
907
- }
908
- }
909
-
910
- let href = '';
911
- let rel = '';
912
-
913
- while (i < html.length) {
914
- const start = i;
915
-
916
- const char = html[start];
917
- if (char === '>') break;
918
-
919
- if (ATTRIBUTE_NAME.test(char)) {
920
- i += 1;
921
-
922
- while (i < html.length) {
923
- if (!ATTRIBUTE_NAME.test(html[i])) {
924
- break;
925
- }
926
-
927
- i += 1;
928
- }
929
-
930
- const name = html.slice(start, i).toLowerCase();
931
-
932
- while (WHITESPACE.test(html[i])) i += 1;
933
-
934
- if (html[i] === '=') {
935
- i += 1;
936
- while (WHITESPACE.test(html[i])) i += 1;
937
-
938
- let value;
939
-
940
- if (html[i] === "'" || html[i] === '"') {
941
- const quote = html[i++];
942
-
943
- const start = i;
944
- let escaped = false;
945
-
946
- while (i < html.length) {
947
- if (!escaped) {
948
- const char = html[i];
949
-
950
- if (html[i] === quote) {
951
- break;
952
- }
953
-
954
- if (char === '\\') {
955
- escaped = true;
956
- }
957
- }
958
-
959
- i += 1;
960
- }
961
-
962
- value = html.slice(start, i);
963
- } else {
964
- const start = i;
965
- while (html[i] !== '>' && !WHITESPACE.test(html[i])) i += 1;
966
- value = html.slice(start, i);
967
-
968
- i -= 1;
969
- }
970
-
971
- if (name === 'href') {
972
- href = value;
973
- } else if (name === 'rel') {
974
- rel = value;
975
- } else if (name === 'src') {
976
- hrefs.push(value);
977
- } else if (name === 'srcset') {
978
- const candidates = [];
979
- let insideURL = true;
980
- value = value.trim();
981
- for (let i = 0; i < value.length; i++) {
982
- if (value[i] === ',' && (!insideURL || (insideURL && value[i + 1] === ' '))) {
983
- candidates.push(value.slice(0, i));
984
- value = value.substring(i + 1).trim();
985
- i = 0;
986
- insideURL = true;
987
- } else if (value[i] === ' ') {
988
- insideURL = false;
989
- }
990
- }
991
- candidates.push(value);
992
- for (const candidate of candidates) {
993
- const src = candidate.split(WHITESPACE)[0];
994
- hrefs.push(src);
995
- }
996
- }
997
- } else {
998
- i -= 1;
999
- }
1000
- }
1001
-
1002
- i += 1;
1003
- }
1004
-
1005
- if (href && !/\bexternal\b/i.test(rel)) {
1006
- hrefs.push(href);
1007
- }
1008
- }
1009
- }
1010
-
1011
- i += 1;
1012
- }
1013
-
1014
- return hrefs;
1015
- }
1016
-
1017
- /**
1018
- * Inside a script element, only `</script` and `<!--` hold special meaning to the HTML parser.
1019
- *
1020
- * The first closes the script element, so everything after is treated as raw HTML.
1021
- * The second disables further parsing until `-->`, so the script element might be unexpectedly
1022
- * kept open until until an unrelated HTML comment in the page.
1023
- *
1024
- * U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are escaped for the sake of pre-2018
1025
- * browsers.
1026
- *
1027
- * @see tests for unsafe parsing examples.
1028
- * @see https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements
1029
- * @see https://html.spec.whatwg.org/multipage/syntax.html#cdata-rcdata-restrictions
1030
- * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-state
1031
- * @see https://html.spec.whatwg.org/multipage/parsing.html#script-data-double-escaped-state
1032
- * @see https://github.com/tc39/proposal-json-superset
1033
- * @type {Record<string, string>}
1034
- */
1035
- const render_json_payload_script_dict = {
1036
- '<': '\\u003C',
1037
- '\u2028': '\\u2028',
1038
- '\u2029': '\\u2029'
1039
- };
1040
-
1041
- new RegExp(
1042
- `[${Object.keys(render_json_payload_script_dict).join('')}]`,
1043
- 'g'
1044
- );
1045
-
1046
- /**
1047
- * When inside a double-quoted attribute value, only `&` and `"` hold special meaning.
1048
- * @see https://html.spec.whatwg.org/multipage/parsing.html#attribute-value-(double-quoted)-state
1049
- * @type {Record<string, string>}
1050
- */
1051
- const escape_html_attr_dict = {
1052
- '&': '&amp;',
1053
- '"': '&quot;'
1054
- };
1055
-
1056
- const escape_html_attr_regex = new RegExp(
1057
- // special characters
1058
- `[${Object.keys(escape_html_attr_dict).join('')}]|` +
1059
- // high surrogate without paired low surrogate
1060
- '[\\ud800-\\udbff](?![\\udc00-\\udfff])|' +
1061
- // a valid surrogate pair, the only match with 2 code units
1062
- // we match it so that we can match unpaired low surrogates in the same pass
1063
- // TODO: use lookbehind assertions once they are widely supported: (?<![\ud800-udbff])[\udc00-\udfff]
1064
- '[\\ud800-\\udbff][\\udc00-\\udfff]|' +
1065
- // unpaired low surrogate (see previous match)
1066
- '[\\udc00-\\udfff]',
1067
- 'g'
1068
- );
1069
-
1070
- /**
1071
- * Formats a string to be used as an attribute's value in raw HTML.
1072
- *
1073
- * It escapes unpaired surrogates (which are allowed in js strings but invalid in HTML), escapes
1074
- * characters that are special in attributes, and surrounds the whole string in double-quotes.
1075
- *
1076
- * @param {string} str
1077
- * @returns {string} Escaped string surrounded by double-quotes.
1078
- * @example const html = `<tag data-value=${escape_html_attr('value')}>...</tag>`;
1079
- */
1080
- function escape_html_attr(str) {
1081
- const escaped_str = str.replace(escape_html_attr_regex, (match) => {
1082
- if (match.length === 2) {
1083
- // valid surrogate pair
1084
- return match;
1085
- }
1086
-
1087
- return escape_html_attr_dict[match] ?? `&#${match.charCodeAt(0)};`;
1088
- });
1089
-
1090
- return `"${escaped_str}"`;
1091
- }
1092
-
1093
- /**
1094
- * @typedef {import('types').PrerenderErrorHandler} PrerenderErrorHandler
1095
- * @typedef {import('types').Logger} Logger
1096
- */
1097
-
1098
- /**
1099
- * @param {Parameters<PrerenderErrorHandler>[0]} details
1100
- * @param {import('types').ValidatedKitConfig} config
1101
- */
1102
- function format_error({ status, path, referrer, referenceType }, config) {
1103
- const message =
1104
- status === 404 && !path.startsWith(config.paths.base)
1105
- ? `${path} does not begin with \`base\`, which is configured in \`paths.base\` and can be imported from \`$app/paths\``
1106
- : path;
1107
-
1108
- return `${status} ${message}${referrer ? ` (${referenceType} from ${referrer})` : ''}`;
1109
- }
1110
-
1111
- /**
1112
- * @param {Logger} log
1113
- * @param {import('types').ValidatedKitConfig} config
1114
- * @returns {PrerenderErrorHandler}
1115
- */
1116
- function normalise_error_handler(log, config) {
1117
- switch (config.prerender.onError) {
1118
- case 'continue':
1119
- return (details) => {
1120
- log.error(format_error(details, config));
1121
- };
1122
- case 'fail':
1123
- return (details) => {
1124
- throw new Error(format_error(details, config));
1125
- };
1126
- default:
1127
- return config.prerender.onError;
1128
- }
1129
- }
1130
-
1131
- const OK = 2;
1132
- const REDIRECT = 3;
1133
-
1134
- /**
1135
- * @param {{
1136
- * config: import('types').ValidatedKitConfig;
1137
- * client_out_dir: string;
1138
- * manifest_path: string;
1139
- * log: Logger;
1140
- * }} opts
1141
- */
1142
- async function prerender({ config, client_out_dir, manifest_path, log }) {
1143
- /** @type {import('types').Prerendered} */
1144
- const prerendered = {
1145
- pages: new Map(),
1146
- assets: new Map(),
1147
- redirects: new Map(),
1148
- paths: []
1149
- };
1150
-
1151
- if (!config.prerender.enabled) {
1152
- return prerendered;
1153
- }
1154
-
1155
- installPolyfills();
1156
- const { fetch } = globalThis;
1157
- globalThis.fetch = async (info, init) => {
1158
- /** @type {string} */
1159
- let url;
1160
-
1161
- /** @type {RequestInit} */
1162
- let opts = {};
1163
-
1164
- if (info instanceof Request) {
1165
- url = info.url;
1166
-
1167
- opts = {
1168
- method: info.method,
1169
- headers: info.headers,
1170
- body: info.body,
1171
- mode: info.mode,
1172
- credentials: info.credentials,
1173
- cache: info.cache,
1174
- redirect: info.redirect,
1175
- referrer: info.referrer,
1176
- integrity: info.integrity
1177
- };
1178
- } else {
1179
- url = info.toString();
1180
- }
1181
-
1182
- if (url.startsWith(config.prerender.origin + '/')) {
1183
- const request = new Request(url, opts);
1184
- const response = await server.respond(request, {
1185
- getClientAddress,
1186
- prerendering: {
1187
- dependencies: new Map()
1188
- }
1189
- });
1190
-
1191
- const decoded = new URL$1(url).pathname;
1192
-
1193
- save(
1194
- 'dependencies',
1195
- response,
1196
- Buffer.from(await response.clone().arrayBuffer()),
1197
- decoded,
1198
- encodeURI(decoded),
1199
- null,
1200
- 'fetched'
1201
- );
1202
-
1203
- return response;
1204
- }
1205
-
1206
- return fetch(info, init);
1207
- };
1208
-
1209
- const server_root = join(config.outDir, 'output');
1210
-
1211
- /** @type {import('types').ServerModule} */
1212
- const { Server, override } = await import(pathToFileURL(`${server_root}/server/index.js`).href);
1213
-
1214
- /** @type {import('types').SSRManifest} */
1215
- const manifest = (await import(pathToFileURL(`${server_root}/server/manifest.js`).href)).manifest;
1216
-
1217
- override({
1218
- paths: config.paths,
1219
- prerendering: true,
1220
- read: (file) => readFileSync(join(config.files.assets, file))
1221
- });
1222
-
1223
- const server = new Server(manifest);
1224
-
1225
- const error = normalise_error_handler(log, config);
1226
-
1227
- const q = queue(config.prerender.concurrency);
1228
-
1229
- /**
1230
- * @param {string} path
1231
- * @param {boolean} is_html
1232
- */
1233
- function output_filename(path, is_html) {
1234
- const file = path.slice(config.paths.base.length + 1) || 'index.html';
1235
-
1236
- if (is_html && !file.endsWith('.html')) {
1237
- return file + (file.endsWith('/') ? 'index.html' : '.html');
1238
- }
1239
-
1240
- return file;
1241
- }
1242
-
1243
- const files = new Set(walk(client_out_dir).map(posixify));
1244
- const seen = new Set();
1245
- const written = new Set();
1246
-
1247
- /**
1248
- * @param {string | null} referrer
1249
- * @param {string} decoded
1250
- * @param {string} [encoded]
1251
- */
1252
- function enqueue(referrer, decoded, encoded) {
1253
- if (seen.has(decoded)) return;
1254
- seen.add(decoded);
1255
-
1256
- const file = decoded.slice(config.paths.base.length + 1);
1257
- if (files.has(file)) return;
1258
-
1259
- return q.add(() => visit(decoded, encoded || encodeURI(decoded), referrer));
1260
- }
1261
-
1262
- /**
1263
- * @param {string} decoded
1264
- * @param {string} encoded
1265
- * @param {string?} referrer
1266
- */
1267
- async function visit(decoded, encoded, referrer) {
1268
- if (!decoded.startsWith(config.paths.base)) {
1269
- error({ status: 404, path: decoded, referrer, referenceType: 'linked' });
1270
- return;
1271
- }
1272
-
1273
- /** @type {Map<string, import('types').PrerenderDependency>} */
1274
- const dependencies = new Map();
1275
-
1276
- const response = await server.respond(new Request(config.prerender.origin + encoded), {
1277
- getClientAddress,
1278
- prerendering: {
1279
- dependencies
1280
- }
1281
- });
1282
-
1283
- const body = Buffer.from(await response.arrayBuffer());
1284
-
1285
- save('pages', response, body, decoded, encoded, referrer, 'linked');
1286
-
1287
- for (const [dependency_path, result] of dependencies) {
1288
- // this seems circuitous, but using new URL allows us to not care
1289
- // whether dependency_path is encoded or not
1290
- const encoded_dependency_path = new URL$1(dependency_path, 'http://localhost').pathname;
1291
- const decoded_dependency_path = decodeURI(encoded_dependency_path);
1292
-
1293
- const body = result.body ?? new Uint8Array(await result.response.arrayBuffer());
1294
- save(
1295
- 'dependencies',
1296
- result.response,
1297
- body,
1298
- decoded_dependency_path,
1299
- encoded_dependency_path,
1300
- decoded,
1301
- 'fetched'
1302
- );
1303
- }
1304
-
1305
- if (config.prerender.crawl && response.headers.get('content-type') === 'text/html') {
1306
- for (const href of crawl(body.toString())) {
1307
- if (href.startsWith('data:') || href.startsWith('#')) continue;
1308
-
1309
- const resolved = resolve(encoded, href);
1310
- if (!is_root_relative(resolved)) continue;
1311
-
1312
- const { pathname, search } = new URL$1(resolved, 'http://localhost');
1313
-
1314
- enqueue(decoded, decodeURI(pathname), pathname);
1315
- }
1316
- }
1317
- }
1318
-
1319
- /**
1320
- * @param {'pages' | 'dependencies'} category
1321
- * @param {Response} response
1322
- * @param {string | Uint8Array} body
1323
- * @param {string} decoded
1324
- * @param {string} encoded
1325
- * @param {string | null} referrer
1326
- * @param {'linked' | 'fetched'} referenceType
1327
- */
1328
- function save(category, response, body, decoded, encoded, referrer, referenceType) {
1329
- const response_type = Math.floor(response.status / 100);
1330
- const type = /** @type {string} */ (response.headers.get('content-type'));
1331
- const is_html = response_type === REDIRECT || type === 'text/html';
1332
-
1333
- const file = output_filename(decoded, is_html);
1334
- const dest = `${config.outDir}/output/prerendered/${category}/${file}`;
1335
-
1336
- if (written.has(file)) return;
1337
-
1338
- if (response_type === REDIRECT) {
1339
- const location = response.headers.get('location');
1340
-
1341
- if (location) {
1342
- const resolved = resolve(encoded, location);
1343
- if (is_root_relative(resolved)) {
1344
- enqueue(decoded, decodeURI(resolved), resolved);
1345
- }
1346
-
1347
- if (!response.headers.get('x-sveltekit-normalize')) {
1348
- mkdirp(dirname(dest));
1349
-
1350
- log.warn(`${response.status} ${decoded} -> ${location}`);
1351
-
1352
- writeFileSync(
1353
- dest,
1354
- `<meta http-equiv="refresh" content=${escape_html_attr(`0;url=${location}`)}>`
1355
- );
1356
-
1357
- written.add(file);
1358
-
1359
- if (!prerendered.redirects.has(decoded)) {
1360
- prerendered.redirects.set(decoded, {
1361
- status: response.status,
1362
- location: resolved
1363
- });
1364
-
1365
- prerendered.paths.push(decoded);
1366
- }
1367
- }
1368
- } else {
1369
- log.warn(`location header missing on redirect received from ${decoded}`);
1370
- }
1371
-
1372
- return;
1373
- }
1374
-
1375
- if (response.status === 200) {
1376
- mkdirp(dirname(dest));
1377
-
1378
- log.info(`${response.status} ${decoded}`);
1379
- writeFileSync(dest, body);
1380
- written.add(file);
1381
-
1382
- if (is_html) {
1383
- prerendered.pages.set(decoded, {
1384
- file
1385
- });
1386
- } else {
1387
- prerendered.assets.set(decoded, {
1388
- type
1389
- });
1390
- }
1391
-
1392
- prerendered.paths.push(decoded);
1393
- } else if (response_type !== OK) {
1394
- error({ status: response.status, path: decoded, referrer, referenceType });
1395
- }
1396
- }
1397
-
1398
- if (config.prerender.enabled) {
1399
- for (const entry of config.prerender.entries) {
1400
- if (entry === '*') {
1401
- /** @type {import('types').ManifestData} */
1402
- const { routes } = (await import(pathToFileURL(manifest_path).href)).manifest._;
1403
- const entries = routes
1404
- .map((route) => (route.type === 'page' ? route.path : ''))
1405
- .filter(Boolean);
1406
-
1407
- for (const entry of entries) {
1408
- enqueue(null, config.paths.base + entry); // TODO can we pre-normalize these?
1409
- }
1410
- } else {
1411
- enqueue(null, config.paths.base + entry);
1412
- }
1413
- }
1414
-
1415
- await q.done();
1416
- }
1417
-
1418
- const rendered = await server.respond(new Request(config.prerender.origin + '/[fallback]'), {
1419
- getClientAddress,
1420
- prerendering: {
1421
- fallback: true,
1422
- dependencies: new Map()
1423
- }
1424
- });
1425
-
1426
- const file = `${config.outDir}/output/prerendered/fallback.html`;
1427
- mkdirp(dirname(file));
1428
- writeFileSync(file, await rendered.text());
1429
-
1430
- return prerendered;
1431
- }
1432
-
1433
- /** @return {string} */
1434
- function getClientAddress() {
1435
- throw new Error('Cannot read clientAddress during prerendering');
1436
- }
1437
-
1438
713
  function totalist(dir, callback, pre='') {
1439
- dir = resolve$1('.', dir);
714
+ dir = resolve('.', dir);
1440
715
  let arr = readdirSync(dir);
1441
716
  let i=0, abs, stats;
1442
717
  for (; i < arr.length; i++) {
@@ -2010,7 +1285,7 @@ function toHeaders(name, stats, isEtag) {
2010
1285
  }
2011
1286
 
2012
1287
  function sirv (dir, opts={}) {
2013
- dir = resolve$1(dir || '.');
1288
+ dir = resolve(dir || '.');
2014
1289
 
2015
1290
  let isNotFound = opts.onNoMatch || is404;
2016
1291
  let setHeaders = opts.setHeaders || noop;
@@ -2257,6 +1532,35 @@ async function dev(vite, vite_config, svelte_config) {
2257
1532
  extensions: []
2258
1533
  });
2259
1534
 
1535
+ vite.middlewares.use(async (req, res, next) => {
1536
+ try {
1537
+ const base = `${vite.config.server.https ? 'https' : 'http'}://${
1538
+ req.headers[':authority'] || req.headers.host
1539
+ }`;
1540
+
1541
+ const decoded = decodeURI(new URL$1(base + req.url).pathname);
1542
+
1543
+ if (decoded.startsWith(assets)) {
1544
+ const pathname = decoded.slice(assets.length);
1545
+ const file = svelte_config.kit.files.assets + pathname;
1546
+
1547
+ if (fs__default.existsSync(file) && !fs__default.statSync(file).isDirectory()) {
1548
+ if (has_correct_case(file, svelte_config.kit.files.assets)) {
1549
+ req.url = encodeURI(pathname); // don't need query/hash
1550
+ asset_server(req, res);
1551
+ return;
1552
+ }
1553
+ }
1554
+ }
1555
+
1556
+ next();
1557
+ } catch (e) {
1558
+ const error = coalesce_to_error(e);
1559
+ res.statusCode = 500;
1560
+ res.end(fix_stack_trace(error));
1561
+ }
1562
+ });
1563
+
2260
1564
  return () => {
2261
1565
  const serve_static_middleware = vite.middlewares.stack.find(
2262
1566
  (middleware) =>
@@ -2267,27 +1571,11 @@ async function dev(vite, vite_config, svelte_config) {
2267
1571
 
2268
1572
  vite.middlewares.use(async (req, res) => {
2269
1573
  try {
2270
- if (!req.url || !req.method) throw new Error('Incomplete request');
2271
-
2272
1574
  const base = `${vite.config.server.https ? 'https' : 'http'}://${
2273
1575
  req.headers[':authority'] || req.headers.host
2274
1576
  }`;
2275
1577
 
2276
1578
  const decoded = decodeURI(new URL$1(base + req.url).pathname);
2277
-
2278
- if (decoded.startsWith(assets)) {
2279
- const pathname = decoded.slice(assets.length);
2280
- const file = svelte_config.kit.files.assets + pathname;
2281
-
2282
- if (fs__default.existsSync(file) && !fs__default.statSync(file).isDirectory()) {
2283
- if (has_correct_case(file, svelte_config.kit.files.assets)) {
2284
- req.url = encodeURI(pathname); // don't need query/hash
2285
- asset_server(req, res);
2286
- return;
2287
- }
2288
- }
2289
- }
2290
-
2291
1579
  const file = posixify(path__default.resolve(decoded.slice(1)));
2292
1580
  const is_file = fs__default.existsSync(file) && !fs__default.statSync(file).isDirectory();
2293
1581
  const allowed =
@@ -2943,12 +2231,12 @@ function kit() {
2943
2231
  // for everything regardless — but it means that entry chunks reflect
2944
2232
  // their location in the source code, which is helpful for debugging
2945
2233
  manifest_data.components.forEach((file) => {
2946
- const resolved = path__default.resolve(cwd, file);
2947
- const relative = decodeURIComponent(path__default.relative(svelte_config.kit.files.routes, resolved));
2234
+ const resolved = path.resolve(cwd, file);
2235
+ const relative = decodeURIComponent(path.relative(svelte_config.kit.files.routes, resolved));
2948
2236
 
2949
2237
  const name = relative.startsWith('..')
2950
- ? path__default.basename(file)
2951
- : posixify(path__default.join('pages', relative));
2238
+ ? path.basename(file)
2239
+ : posixify(path.join('pages', relative));
2952
2240
  input[name] = resolved;
2953
2241
  });
2954
2242
 
@@ -2967,11 +2255,11 @@ function kit() {
2967
2255
  function client_build_info(assets, chunks) {
2968
2256
  /** @type {import('vite').Manifest} */
2969
2257
  const vite_manifest = JSON.parse(
2970
- fs__default.readFileSync(`${paths.client_out_dir}/manifest.json`, 'utf-8')
2258
+ fs$1.readFileSync(`${paths.client_out_dir}/manifest.json`, 'utf-8')
2971
2259
  );
2972
2260
 
2973
2261
  const entry_id = posixify(
2974
- path__default.relative(cwd, `${get_runtime_directory(svelte_config.kit)}/client/start.js`)
2262
+ path.relative(cwd, `${get_runtime_directory(svelte_config.kit)}/client/start.js`)
2975
2263
  );
2976
2264
 
2977
2265
  return {
@@ -3042,9 +2330,9 @@ function kit() {
3042
2330
  svelte_config.kit.files.lib,
3043
2331
  svelte_config.kit.files.routes,
3044
2332
  svelte_config.kit.outDir,
3045
- path__default.resolve(cwd, 'src'),
3046
- path__default.resolve(cwd, 'node_modules'),
3047
- path__default.resolve(vite.searchForWorkspaceRoot(cwd), 'node_modules')
2333
+ path.resolve(cwd, 'src'),
2334
+ path.resolve(cwd, 'node_modules'),
2335
+ path.resolve(vite.searchForWorkspaceRoot(cwd), 'node_modules')
3048
2336
  ])
3049
2337
  ]
3050
2338
  },
@@ -3090,11 +2378,10 @@ function kit() {
3090
2378
  * then use this hook to kick off builds for the server and service worker.
3091
2379
  */
3092
2380
  async writeBundle(_options, bundle) {
3093
- log = logger({
3094
- verbose: vite_config.logLevel === 'info'
3095
- });
2381
+ const verbose = vite_config.logLevel === 'info';
2382
+ log = logger({ verbose });
3096
2383
 
3097
- fs__default.writeFileSync(
2384
+ fs$1.writeFileSync(
3098
2385
  `${paths.client_out_dir}/${svelte_config.kit.appDir}/version.json`,
3099
2386
  JSON.stringify({ version: svelte_config.kit.version.name })
3100
2387
  );
@@ -3106,6 +2393,7 @@ function kit() {
3106
2393
  const options = {
3107
2394
  cwd,
3108
2395
  config: svelte_config,
2396
+ vite_config,
3109
2397
  vite_config_env,
3110
2398
  build_dir: paths.build_dir, // TODO just pass `paths`
3111
2399
  manifest_data,
@@ -3125,7 +2413,7 @@ function kit() {
3125
2413
  };
3126
2414
 
3127
2415
  const manifest_path = `${paths.output_dir}/server/manifest.js`;
3128
- fs__default.writeFileSync(
2416
+ fs$1.writeFileSync(
3129
2417
  manifest_path,
3130
2418
  `export const manifest = ${generate_manifest({
3131
2419
  build_data,
@@ -3134,14 +2422,39 @@ function kit() {
3134
2422
  })};\n`
3135
2423
  );
3136
2424
 
3137
- process.env.SVELTEKIT_SERVER_BUILD_COMPLETED = 'true';
3138
2425
  log.info('Prerendering');
2426
+ await new Promise((fulfil, reject) => {
2427
+ const results_path = `${svelte_config.kit.outDir}/generated/prerendered.json`;
2428
+
2429
+ // do prerendering in a subprocess so any dangling stuff gets killed upon completion
2430
+ const script = fileURLToPath(
2431
+ new URL(
2432
+ './prerender.js' ,
2433
+ import.meta.url
2434
+ )
2435
+ );
3139
2436
 
3140
- prerendered = await prerender({
3141
- config: svelte_config.kit,
3142
- client_out_dir: vite_config.build.outDir,
3143
- manifest_path,
3144
- log
2437
+ const child = fork(
2438
+ script,
2439
+ [vite_config.build.outDir, results_path, manifest_path, '' + verbose],
2440
+ {
2441
+ stdio: 'inherit'
2442
+ }
2443
+ );
2444
+
2445
+ child.on('exit', (code) => {
2446
+ if (code) {
2447
+ reject(new Error(`Prerendering failed with code ${code}`));
2448
+ } else {
2449
+ prerendered = JSON.parse(fs$1.readFileSync(results_path, 'utf8'), (key, value) => {
2450
+ if (key === 'pages' || key === 'assets' || key === 'redirects') {
2451
+ return new Map(value);
2452
+ }
2453
+ return value;
2454
+ });
2455
+ fulfil(undefined);
2456
+ }
2457
+ });
3145
2458
  });
3146
2459
 
3147
2460
  if (options.service_worker_entry_file) {
@@ -3172,7 +2485,7 @@ function kit() {
3172
2485
  }
3173
2486
 
3174
2487
  if (svelte_config.kit.adapter) {
3175
- const { adapt } = await import('./chunks/index2.js');
2488
+ const { adapt } = await import('./chunks/index3.js');
3176
2489
  await adapt(svelte_config, build_data, prerendered, { log });
3177
2490
  } else {
3178
2491
  console.log($.bold().yellow('\nNo adapter specified'));
@@ -3181,13 +2494,6 @@ function kit() {
3181
2494
  `See ${$.bold().cyan('https://kit.svelte.dev/docs/adapters')} to learn how to configure your app to run on the platform of your choosing`
3182
2495
  );
3183
2496
  }
3184
-
3185
- if (svelte_config.kit.prerender.enabled) {
3186
- // this is necessary to close any open db connections, etc.
3187
- // TODO: prerender in a subprocess so we can exit in isolation and then remove this
3188
- // https://github.com/sveltejs/kit/issues/5306
3189
- process.exit(0);
3190
- }
3191
2497
  },
3192
2498
 
3193
2499
  /**