@sveltejs/kit 1.0.0-next.243 → 1.0.0-next.247

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.
@@ -10,6 +10,7 @@ import { e as escape_html_attr, r as resolve, i as is_root_relative, a as escape
10
10
  import { s } from './misc.js';
11
11
  import { __fetch_polyfill } from '../install-fetch.js';
12
12
  import { getRequest, setResponse } from '../node.js';
13
+ import { sequence } from '../hooks.js';
13
14
  import 'sade';
14
15
  import 'child_process';
15
16
  import 'net';
@@ -206,7 +207,7 @@ function is_pojo(body) {
206
207
  return true;
207
208
  }
208
209
 
209
- var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
210
+ var chars$1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
210
211
  var unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
211
212
  var reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
212
213
  var escaped = {
@@ -366,8 +367,8 @@ function devalue(value) {
366
367
  function getName(num) {
367
368
  var name = '';
368
369
  do {
369
- name = chars[num % chars.length] + name;
370
- num = ~~(num / chars.length) - 1;
370
+ name = chars$1[num % chars$1.length] + name;
371
+ num = ~~(num / chars$1.length) - 1;
371
372
  } while (num >= 0);
372
373
  return reserved.test(name) ? name + "_" : name;
373
374
  }
@@ -497,6 +498,455 @@ function create_prerendering_url_proxy(url) {
497
498
  });
498
499
  }
499
500
 
501
+ const encoder = new TextEncoder();
502
+
503
+ /**
504
+ * SHA-256 hashing function adapted from https://bitwiseshiftleft.github.io/sjcl
505
+ * modified and redistributed under BSD license
506
+ * @param {string} data
507
+ */
508
+ function sha256(data) {
509
+ if (!key[0]) precompute();
510
+
511
+ const out = init.slice(0);
512
+ const array = encode(data);
513
+
514
+ for (let i = 0; i < array.length; i += 16) {
515
+ const w = array.subarray(i, i + 16);
516
+
517
+ let tmp;
518
+ let a;
519
+ let b;
520
+
521
+ let out0 = out[0];
522
+ let out1 = out[1];
523
+ let out2 = out[2];
524
+ let out3 = out[3];
525
+ let out4 = out[4];
526
+ let out5 = out[5];
527
+ let out6 = out[6];
528
+ let out7 = out[7];
529
+
530
+ /* Rationale for placement of |0 :
531
+ * If a value can overflow is original 32 bits by a factor of more than a few
532
+ * million (2^23 ish), there is a possibility that it might overflow the
533
+ * 53-bit mantissa and lose precision.
534
+ *
535
+ * To avoid this, we clamp back to 32 bits by |'ing with 0 on any value that
536
+ * propagates around the loop, and on the hash state out[]. I don't believe
537
+ * that the clamps on out4 and on out0 are strictly necessary, but it's close
538
+ * (for out4 anyway), and better safe than sorry.
539
+ *
540
+ * The clamps on out[] are necessary for the output to be correct even in the
541
+ * common case and for short inputs.
542
+ */
543
+
544
+ for (let i = 0; i < 64; i++) {
545
+ // load up the input word for this round
546
+
547
+ if (i < 16) {
548
+ tmp = w[i];
549
+ } else {
550
+ a = w[(i + 1) & 15];
551
+
552
+ b = w[(i + 14) & 15];
553
+
554
+ tmp = w[i & 15] =
555
+ (((a >>> 7) ^ (a >>> 18) ^ (a >>> 3) ^ (a << 25) ^ (a << 14)) +
556
+ ((b >>> 17) ^ (b >>> 19) ^ (b >>> 10) ^ (b << 15) ^ (b << 13)) +
557
+ w[i & 15] +
558
+ w[(i + 9) & 15]) |
559
+ 0;
560
+ }
561
+
562
+ tmp =
563
+ tmp +
564
+ out7 +
565
+ ((out4 >>> 6) ^ (out4 >>> 11) ^ (out4 >>> 25) ^ (out4 << 26) ^ (out4 << 21) ^ (out4 << 7)) +
566
+ (out6 ^ (out4 & (out5 ^ out6))) +
567
+ key[i]; // | 0;
568
+
569
+ // shift register
570
+ out7 = out6;
571
+ out6 = out5;
572
+ out5 = out4;
573
+
574
+ out4 = (out3 + tmp) | 0;
575
+
576
+ out3 = out2;
577
+ out2 = out1;
578
+ out1 = out0;
579
+
580
+ out0 =
581
+ (tmp +
582
+ ((out1 & out2) ^ (out3 & (out1 ^ out2))) +
583
+ ((out1 >>> 2) ^
584
+ (out1 >>> 13) ^
585
+ (out1 >>> 22) ^
586
+ (out1 << 30) ^
587
+ (out1 << 19) ^
588
+ (out1 << 10))) |
589
+ 0;
590
+ }
591
+
592
+ out[0] = (out[0] + out0) | 0;
593
+ out[1] = (out[1] + out1) | 0;
594
+ out[2] = (out[2] + out2) | 0;
595
+ out[3] = (out[3] + out3) | 0;
596
+ out[4] = (out[4] + out4) | 0;
597
+ out[5] = (out[5] + out5) | 0;
598
+ out[6] = (out[6] + out6) | 0;
599
+ out[7] = (out[7] + out7) | 0;
600
+ }
601
+
602
+ const bytes = new Uint8Array(out.buffer);
603
+ reverse_endianness(bytes);
604
+
605
+ return base64(bytes);
606
+ }
607
+
608
+ /** The SHA-256 initialization vector */
609
+ const init = new Uint32Array(8);
610
+
611
+ /** The SHA-256 hash key */
612
+ const key = new Uint32Array(64);
613
+
614
+ /** Function to precompute init and key. */
615
+ function precompute() {
616
+ /** @param {number} x */
617
+ function frac(x) {
618
+ return (x - Math.floor(x)) * 0x100000000;
619
+ }
620
+
621
+ let prime = 2;
622
+
623
+ for (let i = 0; i < 64; prime++) {
624
+ let is_prime = true;
625
+
626
+ for (let factor = 2; factor * factor <= prime; factor++) {
627
+ if (prime % factor === 0) {
628
+ is_prime = false;
629
+
630
+ break;
631
+ }
632
+ }
633
+
634
+ if (is_prime) {
635
+ if (i < 8) {
636
+ init[i] = frac(prime ** (1 / 2));
637
+ }
638
+
639
+ key[i] = frac(prime ** (1 / 3));
640
+
641
+ i++;
642
+ }
643
+ }
644
+ }
645
+
646
+ /** @param {Uint8Array} bytes */
647
+ function reverse_endianness(bytes) {
648
+ for (let i = 0; i < bytes.length; i += 4) {
649
+ const a = bytes[i + 0];
650
+ const b = bytes[i + 1];
651
+ const c = bytes[i + 2];
652
+ const d = bytes[i + 3];
653
+
654
+ bytes[i + 0] = d;
655
+ bytes[i + 1] = c;
656
+ bytes[i + 2] = b;
657
+ bytes[i + 3] = a;
658
+ }
659
+ }
660
+
661
+ /** @param {string} str */
662
+ function encode(str) {
663
+ const encoded = encoder.encode(str);
664
+ const length = encoded.length * 8;
665
+
666
+ // result should be a multiple of 512 bits in length,
667
+ // with room for a 1 (after the data) and two 32-bit
668
+ // words containing the original input bit length
669
+ const size = 512 * Math.ceil((length + 65) / 512);
670
+ const bytes = new Uint8Array(size / 8);
671
+ bytes.set(encoded);
672
+
673
+ // append a 1
674
+ bytes[encoded.length] = 0b10000000;
675
+
676
+ reverse_endianness(bytes);
677
+
678
+ // add the input bit length
679
+ const words = new Uint32Array(bytes.buffer);
680
+ words[words.length - 2] = Math.floor(length / 0x100000000); // this will always be zero for us
681
+ words[words.length - 1] = length;
682
+
683
+ return words;
684
+ }
685
+
686
+ /*
687
+ Based on https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727
688
+
689
+ MIT License
690
+ Copyright (c) 2020 Egor Nepomnyaschih
691
+ Permission is hereby granted, free of charge, to any person obtaining a copy
692
+ of this software and associated documentation files (the "Software"), to deal
693
+ in the Software without restriction, including without limitation the rights
694
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
695
+ copies of the Software, and to permit persons to whom the Software is
696
+ furnished to do so, subject to the following conditions:
697
+ The above copyright notice and this permission notice shall be included in all
698
+ copies or substantial portions of the Software.
699
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
700
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
701
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
702
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
703
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
704
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
705
+ SOFTWARE.
706
+ */
707
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
708
+
709
+ /** @param {Uint8Array} bytes */
710
+ function base64(bytes) {
711
+ const l = bytes.length;
712
+
713
+ let result = '';
714
+ let i;
715
+
716
+ for (i = 2; i < l; i += 3) {
717
+ result += chars[bytes[i - 2] >> 2];
718
+ result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
719
+ result += chars[((bytes[i - 1] & 0x0f) << 2) | (bytes[i] >> 6)];
720
+ result += chars[bytes[i] & 0x3f];
721
+ }
722
+
723
+ if (i === l + 1) {
724
+ // 1 octet yet to write
725
+ result += chars[bytes[i - 2] >> 2];
726
+ result += chars[(bytes[i - 2] & 0x03) << 4];
727
+ result += '==';
728
+ }
729
+
730
+ if (i === l) {
731
+ // 2 octets yet to write
732
+ result += chars[bytes[i - 2] >> 2];
733
+ result += chars[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)];
734
+ result += chars[(bytes[i - 1] & 0x0f) << 2];
735
+ result += '=';
736
+ }
737
+
738
+ return result;
739
+ }
740
+
741
+ /** @type {Promise<void>} */
742
+ let csp_ready;
743
+
744
+ /** @type {() => string} */
745
+ let generate_nonce;
746
+
747
+ /** @type {(input: string) => string} */
748
+ let generate_hash;
749
+
750
+ if (typeof crypto !== 'undefined') {
751
+ const array = new Uint8Array(16);
752
+
753
+ generate_nonce = () => {
754
+ crypto.getRandomValues(array);
755
+ return base64(array);
756
+ };
757
+
758
+ generate_hash = sha256;
759
+ } else {
760
+ // TODO: remove this in favor of web crypto API once we no longer support Node 14
761
+ const name = 'crypto'; // store in a variable to fool esbuild when adapters bundle kit
762
+ csp_ready = import(name).then((crypto) => {
763
+ generate_nonce = () => {
764
+ return crypto.randomBytes(16).toString('base64');
765
+ };
766
+
767
+ generate_hash = (input) => {
768
+ return crypto.createHash('sha256').update(input, 'utf-8').digest().toString('base64');
769
+ };
770
+ });
771
+ }
772
+
773
+ const quoted = new Set([
774
+ 'self',
775
+ 'unsafe-eval',
776
+ 'unsafe-hashes',
777
+ 'unsafe-inline',
778
+ 'none',
779
+ 'strict-dynamic',
780
+ 'report-sample'
781
+ ]);
782
+
783
+ const crypto_pattern = /^(nonce|sha\d\d\d)-/;
784
+
785
+ class Csp {
786
+ /** @type {boolean} */
787
+ #use_hashes;
788
+
789
+ /** @type {boolean} */
790
+ #dev;
791
+
792
+ /** @type {boolean} */
793
+ #script_needs_csp;
794
+
795
+ /** @type {boolean} */
796
+ #style_needs_csp;
797
+
798
+ /** @type {import('types/csp').CspDirectives} */
799
+ #directives;
800
+
801
+ /** @type {import('types/csp').Source[]} */
802
+ #script_src;
803
+
804
+ /** @type {import('types/csp').Source[]} */
805
+ #style_src;
806
+
807
+ /**
808
+ * @param {{
809
+ * mode: string,
810
+ * directives: import('types/csp').CspDirectives
811
+ * }} config
812
+ * @param {{
813
+ * dev: boolean;
814
+ * prerender: boolean;
815
+ * needs_nonce: boolean;
816
+ * }} opts
817
+ */
818
+ constructor({ mode, directives }, { dev, prerender, needs_nonce }) {
819
+ this.#use_hashes = mode === 'hash' || (mode === 'auto' && prerender);
820
+ this.#directives = dev ? { ...directives } : directives; // clone in dev so we can safely mutate
821
+ this.#dev = dev;
822
+
823
+ const d = this.#directives;
824
+
825
+ if (dev) {
826
+ // remove strict-dynamic in dev...
827
+ // TODO reinstate this if we can figure out how to make strict-dynamic work
828
+ // if (d['default-src']) {
829
+ // d['default-src'] = d['default-src'].filter((name) => name !== 'strict-dynamic');
830
+ // if (d['default-src'].length === 0) delete d['default-src'];
831
+ // }
832
+
833
+ // if (d['script-src']) {
834
+ // d['script-src'] = d['script-src'].filter((name) => name !== 'strict-dynamic');
835
+ // if (d['script-src'].length === 0) delete d['script-src'];
836
+ // }
837
+
838
+ const effective_style_src = d['style-src'] || d['default-src'];
839
+
840
+ // ...and add unsafe-inline so we can inject <style> elements
841
+ if (effective_style_src && !effective_style_src.includes('unsafe-inline')) {
842
+ d['style-src'] = [...effective_style_src, 'unsafe-inline'];
843
+ }
844
+ }
845
+
846
+ this.#script_src = [];
847
+ this.#style_src = [];
848
+
849
+ const effective_script_src = d['script-src'] || d['default-src'];
850
+ const effective_style_src = d['style-src'] || d['default-src'];
851
+
852
+ this.#script_needs_csp =
853
+ !!effective_script_src &&
854
+ effective_script_src.filter((value) => value !== 'unsafe-inline').length > 0;
855
+
856
+ this.#style_needs_csp =
857
+ !dev &&
858
+ !!effective_style_src &&
859
+ effective_style_src.filter((value) => value !== 'unsafe-inline').length > 0;
860
+
861
+ this.script_needs_nonce = this.#script_needs_csp && !this.#use_hashes;
862
+ this.style_needs_nonce = this.#style_needs_csp && !this.#use_hashes;
863
+
864
+ if (this.script_needs_nonce || this.style_needs_nonce || needs_nonce) {
865
+ this.nonce = generate_nonce();
866
+ }
867
+ }
868
+
869
+ /** @param {string} content */
870
+ add_script(content) {
871
+ if (this.#script_needs_csp) {
872
+ if (this.#use_hashes) {
873
+ this.#script_src.push(`sha256-${generate_hash(content)}`);
874
+ } else if (this.#script_src.length === 0) {
875
+ this.#script_src.push(`nonce-${this.nonce}`);
876
+ }
877
+ }
878
+ }
879
+
880
+ /** @param {string} content */
881
+ add_style(content) {
882
+ if (this.#style_needs_csp) {
883
+ if (this.#use_hashes) {
884
+ this.#style_src.push(`sha256-${generate_hash(content)}`);
885
+ } else if (this.#style_src.length === 0) {
886
+ this.#style_src.push(`nonce-${this.nonce}`);
887
+ }
888
+ }
889
+ }
890
+
891
+ /** @param {boolean} [is_meta] */
892
+ get_header(is_meta = false) {
893
+ const header = [];
894
+
895
+ // due to browser inconsistencies, we can't append sources to default-src
896
+ // (specifically, Firefox appears to not ignore nonce-{nonce} directives
897
+ // on default-src), so we ensure that script-src and style-src exist
898
+
899
+ const directives = { ...this.#directives };
900
+
901
+ if (this.#style_src.length > 0) {
902
+ directives['style-src'] = [
903
+ ...(directives['style-src'] || directives['default-src'] || []),
904
+ ...this.#style_src
905
+ ];
906
+ }
907
+
908
+ if (this.#script_src.length > 0) {
909
+ directives['script-src'] = [
910
+ ...(directives['script-src'] || directives['default-src'] || []),
911
+ ...this.#script_src
912
+ ];
913
+ }
914
+
915
+ for (const key in directives) {
916
+ if (is_meta && (key === 'frame-ancestors' || key === 'report-uri' || key === 'sandbox')) {
917
+ // these values cannot be used with a <meta> tag
918
+ // TODO warn?
919
+ continue;
920
+ }
921
+
922
+ // @ts-expect-error gimme a break typescript, `key` is obviously a member of directives
923
+ const value = /** @type {string[] | true} */ (directives[key]);
924
+
925
+ if (!value) continue;
926
+
927
+ const directive = [key];
928
+ if (Array.isArray(value)) {
929
+ value.forEach((value) => {
930
+ if (quoted.has(value) || crypto_pattern.test(value)) {
931
+ directive.push(`'${value}'`);
932
+ } else {
933
+ directive.push(value);
934
+ }
935
+ });
936
+ }
937
+
938
+ header.push(directive.join(' '));
939
+ }
940
+
941
+ return header.join('; ');
942
+ }
943
+
944
+ get_meta() {
945
+ const content = escape_html_attr(this.get_header(true));
946
+ return `<meta http-equiv="content-security-policy" content=${content}>`;
947
+ }
948
+ }
949
+
500
950
  // TODO rename this function/module
501
951
 
502
952
  /**
@@ -527,8 +977,18 @@ async function render_response({
527
977
  ssr,
528
978
  stuff
529
979
  }) {
530
- const css = new Set(options.manifest._.entry.css);
531
- const js = new Set(options.manifest._.entry.js);
980
+ if (state.prerender) {
981
+ if (options.csp.mode === 'nonce') {
982
+ throw new Error('Cannot use prerendering if config.kit.csp.mode === "nonce"');
983
+ }
984
+
985
+ if (options.template_contains_nonce) {
986
+ throw new Error('Cannot use prerendering if page template contains %svelte.nonce%');
987
+ }
988
+ }
989
+
990
+ const stylesheets = new Set(options.manifest._.entry.css);
991
+ const modulepreloads = new Set(options.manifest._.entry.js);
532
992
  /** @type {Map<string, string>} */
533
993
  const styles = new Map();
534
994
 
@@ -546,8 +1006,8 @@ async function render_response({
546
1006
 
547
1007
  if (ssr) {
548
1008
  branch.forEach(({ node, loaded, fetched, uses_credentials }) => {
549
- if (node.css) node.css.forEach((url) => css.add(url));
550
- if (node.js) node.js.forEach((url) => js.add(url));
1009
+ if (node.css) node.css.forEach((url) => stylesheets.add(url));
1010
+ if (node.js) node.js.forEach((url) => modulepreloads.add(url));
551
1011
  if (node.styles) Object.entries(node.styles).forEach(([k, v]) => styles.set(k, v));
552
1012
 
553
1013
  // TODO probably better if `fetched` wasn't populated unless `hydrate`
@@ -619,11 +1079,44 @@ async function render_response({
619
1079
 
620
1080
  const inlined_style = Array.from(styles.values()).join('\n');
621
1081
 
622
- if (state.prerender) {
623
- if (maxage) {
624
- head += `<meta http-equiv="cache-control" content="max-age=${maxage}">`;
1082
+ await csp_ready;
1083
+ const csp = new Csp(options.csp, {
1084
+ dev: options.dev,
1085
+ prerender: !!state.prerender,
1086
+ needs_nonce: options.template_contains_nonce
1087
+ });
1088
+
1089
+ // prettier-ignore
1090
+ const init_app = `
1091
+ import { start } from ${s(options.prefix + options.manifest._.entry.file)};
1092
+ start({
1093
+ target: ${options.target ? `document.querySelector(${s(options.target)})` : 'document.body'},
1094
+ paths: ${s(options.paths)},
1095
+ session: ${try_serialize($session, (error) => {
1096
+ throw new Error(`Failed to serialize session data: ${error.message}`);
1097
+ })},
1098
+ route: ${!!page_config.router},
1099
+ spa: ${!ssr},
1100
+ trailing_slash: ${s(options.trailing_slash)},
1101
+ hydrate: ${ssr && page_config.hydrate ? `{
1102
+ status: ${status},
1103
+ error: ${serialize_error(error)},
1104
+ nodes: [
1105
+ ${(branch || [])
1106
+ .map(({ node }) => `import(${s(options.prefix + node.entry)})`)
1107
+ .join(',\n\t\t\t\t\t\t')}
1108
+ ],
1109
+ url: new URL(${s(url.href)}),
1110
+ params: ${devalue(params)}
1111
+ }` : 'null'}
1112
+ });
1113
+ `;
1114
+
1115
+ const init_service_worker = `
1116
+ if ('serviceWorker' in navigator) {
1117
+ navigator.serviceWorker.register('${options.service_worker}');
625
1118
  }
626
- }
1119
+ `;
627
1120
 
628
1121
  if (options.amp) {
629
1122
  head += `
@@ -641,49 +1134,54 @@ async function render_response({
641
1134
  }
642
1135
  } else {
643
1136
  if (inlined_style) {
644
- head += `\n\t<style${options.dev ? ' data-svelte' : ''}>${inlined_style}</style>`;
1137
+ const attributes = [];
1138
+ if (options.dev) attributes.push(' data-svelte');
1139
+ if (csp.style_needs_nonce) attributes.push(` nonce="${csp.nonce}"`);
1140
+
1141
+ csp.add_style(inlined_style);
1142
+
1143
+ head += `\n\t<style${attributes.join('')}>${inlined_style}</style>`;
645
1144
  }
1145
+
646
1146
  // prettier-ignore
647
- head += Array.from(css)
648
- .map((dep) => `\n\t<link${styles.has(dep) ? ' disabled media="(max-width: 0)"' : ''} rel="stylesheet" href="${options.prefix + dep}">`)
1147
+ head += Array.from(stylesheets)
1148
+ .map((dep) => {
1149
+ const attributes = [
1150
+ 'rel="stylesheet"',
1151
+ `href="${options.prefix + dep}"`
1152
+ ];
1153
+
1154
+ if (csp.style_needs_nonce) {
1155
+ attributes.push(`nonce="${csp.nonce}"`);
1156
+ }
1157
+
1158
+ if (styles.has(dep)) {
1159
+ attributes.push('disabled', 'media="(max-width: 0)"');
1160
+ }
1161
+
1162
+ return `\n\t<link ${attributes.join(' ')}>`;
1163
+ })
649
1164
  .join('');
650
1165
 
651
1166
  if (page_config.router || page_config.hydrate) {
652
- head += Array.from(js)
1167
+ head += Array.from(modulepreloads)
653
1168
  .map((dep) => `\n\t<link rel="modulepreload" href="${options.prefix + dep}">`)
654
1169
  .join('');
655
- // prettier-ignore
656
- head += `
657
- <script type="module">
658
- import { start } from ${s(options.prefix + options.manifest._.entry.file)};
659
- start({
660
- target: ${options.target ? `document.querySelector(${s(options.target)})` : 'document.body'},
661
- paths: ${s(options.paths)},
662
- session: ${try_serialize($session, (error) => {
663
- throw new Error(`Failed to serialize session data: ${error.message}`);
664
- })},
665
- route: ${!!page_config.router},
666
- spa: ${!ssr},
667
- trailing_slash: ${s(options.trailing_slash)},
668
- hydrate: ${ssr && page_config.hydrate ? `{
669
- status: ${status},
670
- error: ${serialize_error(error)},
671
- nodes: [
672
- ${(branch || [])
673
- .map(({ node }) => `import(${s(options.prefix + node.entry)})`)
674
- .join(',\n\t\t\t\t\t\t')}
675
- ],
676
- url: new URL(${s(url.href)}),
677
- params: ${devalue(params)}
678
- }` : 'null'}
679
- });
680
- </script>`;
681
1170
 
1171
+ const attributes = ['type="module"'];
1172
+
1173
+ csp.add_script(init_app);
1174
+
1175
+ if (csp.script_needs_nonce) {
1176
+ attributes.push(`nonce="${csp.nonce}"`);
1177
+ }
1178
+
1179
+ head += `<script ${attributes.join(' ')}>${init_app}</script>`;
1180
+
1181
+ // prettier-ignore
682
1182
  body += serialized_data
683
1183
  .map(({ url, body, json }) => {
684
- let attributes = `type="application/json" data-type="svelte-data" data-url=${escape_html_attr(
685
- url
686
- )}`;
1184
+ let attributes = `type="application/json" data-type="svelte-data" data-url=${escape_html_attr(url)}`;
687
1185
  if (body) attributes += ` data-body="${hash(body)}"`;
688
1186
 
689
1187
  return `<script ${attributes}>${json}</script>`;
@@ -693,12 +1191,27 @@ async function render_response({
693
1191
 
694
1192
  if (options.service_worker) {
695
1193
  // always include service worker unless it's turned off explicitly
1194
+ csp.add_script(init_service_worker);
1195
+
696
1196
  head += `
697
- <script>
698
- if ('serviceWorker' in navigator) {
699
- navigator.serviceWorker.register('${options.service_worker}');
700
- }
701
- </script>`;
1197
+ <script${csp.script_needs_nonce ? ` nonce="${csp.nonce}"` : ''}>${init_service_worker}</script>`;
1198
+ }
1199
+ }
1200
+
1201
+ if (state.prerender) {
1202
+ const http_equiv = [];
1203
+
1204
+ const csp_headers = csp.get_meta();
1205
+ if (csp_headers) {
1206
+ http_equiv.push(csp_headers);
1207
+ }
1208
+
1209
+ if (maxage) {
1210
+ http_equiv.push(`<meta http-equiv="cache-control" content="max-age=${maxage}">`);
1211
+ }
1212
+
1213
+ if (http_equiv.length > 0) {
1214
+ head = http_equiv.join('\n') + head;
702
1215
  }
703
1216
  }
704
1217
 
@@ -706,7 +1219,7 @@ async function render_response({
706
1219
  const assets =
707
1220
  options.paths.assets || (segments.length > 0 ? segments.map(() => '..').join('/') : '.');
708
1221
 
709
- const html = options.template({ head, body, assets });
1222
+ const html = options.template({ head, body, assets, nonce: /** @type {string} */ (csp.nonce) });
710
1223
 
711
1224
  const headers = new Headers({
712
1225
  'content-type': 'text/html',
@@ -721,6 +1234,13 @@ async function render_response({
721
1234
  headers.set('permissions-policy', 'interest-cohort=()');
722
1235
  }
723
1236
 
1237
+ if (!state.prerender) {
1238
+ const csp_header = csp.get_header();
1239
+ if (csp_header) {
1240
+ headers.set('content-security-policy', csp_header);
1241
+ }
1242
+ }
1243
+
724
1244
  return new Response(html, {
725
1245
  status,
726
1246
  headers
@@ -915,6 +1435,9 @@ async function load_node({
915
1435
  /** @type {Response} */
916
1436
  let response;
917
1437
 
1438
+ /** @type {import('types/internal').PrerenderDependency} */
1439
+ let dependency;
1440
+
918
1441
  // handle fetch requests for static assets. e.g. prebaked data, etc.
919
1442
  // we need to support everything the browser's fetch supports
920
1443
  const prefix = options.paths.assets || options.paths.base;
@@ -941,8 +1464,6 @@ async function load_node({
941
1464
  response = await fetch(`${url.origin}/${file}`, /** @type {RequestInit} */ (opts));
942
1465
  }
943
1466
  } else if (is_root_relative(resolved)) {
944
- const relative = resolved;
945
-
946
1467
  if (opts.credentials !== 'omit') {
947
1468
  uses_credentials = true;
948
1469
 
@@ -966,28 +1487,14 @@ async function load_node({
966
1487
  throw new Error('Request body must be a string');
967
1488
  }
968
1489
 
969
- const rendered = await respond(
970
- new Request(new URL(requested, event.url).href, opts),
971
- options,
972
- {
973
- fetched: requested,
974
- initiator: route
975
- }
976
- );
977
-
978
- if (rendered) {
979
- if (state.prerender) {
980
- state.prerender.dependencies.set(relative, rendered);
981
- }
1490
+ response = await respond(new Request(new URL(requested, event.url).href, opts), options, {
1491
+ fetched: requested,
1492
+ initiator: route
1493
+ });
982
1494
 
983
- response = rendered;
984
- } else {
985
- // we can't load the endpoint from our own manifest,
986
- // so we need to make an actual HTTP request
987
- response = await fetch(new URL(requested, event.url).href, {
988
- method: opts.method || 'GET',
989
- headers: opts.headers
990
- });
1495
+ if (state.prerender) {
1496
+ dependency = { response, body: null };
1497
+ state.prerender.dependencies.set(resolved, dependency);
991
1498
  }
992
1499
  } else {
993
1500
  // external
@@ -1020,59 +1527,69 @@ async function load_node({
1020
1527
  response = await options.hooks.externalFetch.call(null, external_request);
1021
1528
  }
1022
1529
 
1023
- if (response) {
1024
- const proxy = new Proxy(response, {
1025
- get(response, key, _receiver) {
1026
- async function text() {
1027
- const body = await response.text();
1028
-
1029
- /** @type {import('types/helper').ResponseHeaders} */
1030
- const headers = {};
1031
- for (const [key, value] of response.headers) {
1032
- if (key === 'set-cookie') {
1033
- set_cookie_headers = set_cookie_headers.concat(value);
1034
- } else if (key !== 'etag') {
1035
- headers[key] = value;
1036
- }
1530
+ const proxy = new Proxy(response, {
1531
+ get(response, key, _receiver) {
1532
+ async function text() {
1533
+ const body = await response.text();
1534
+
1535
+ /** @type {import('types/helper').ResponseHeaders} */
1536
+ const headers = {};
1537
+ for (const [key, value] of response.headers) {
1538
+ if (key === 'set-cookie') {
1539
+ set_cookie_headers = set_cookie_headers.concat(value);
1540
+ } else if (key !== 'etag') {
1541
+ headers[key] = value;
1037
1542
  }
1543
+ }
1038
1544
 
1039
- if (!opts.body || typeof opts.body === 'string') {
1040
- // prettier-ignore
1041
- fetched.push({
1545
+ if (!opts.body || typeof opts.body === 'string') {
1546
+ // prettier-ignore
1547
+ fetched.push({
1042
1548
  url: requested,
1043
1549
  body: /** @type {string} */ (opts.body),
1044
1550
  json: `{"status":${response.status},"statusText":${s(response.statusText)},"headers":${s(headers)},"body":"${escape_json_string_in_html(body)}"}`
1045
1551
  });
1046
- }
1047
-
1048
- return body;
1049
1552
  }
1050
1553
 
1051
- if (key === 'text') {
1052
- return text;
1554
+ if (dependency) {
1555
+ dependency.body = body;
1053
1556
  }
1054
1557
 
1055
- if (key === 'json') {
1056
- return async () => {
1057
- return JSON.parse(await text());
1058
- };
1059
- }
1558
+ return body;
1559
+ }
1560
+
1561
+ if (key === 'arrayBuffer') {
1562
+ return async () => {
1563
+ const buffer = await response.arrayBuffer();
1564
+
1565
+ if (dependency) {
1566
+ dependency.body = new Uint8Array(buffer);
1567
+ }
1060
1568
 
1061
- // TODO arrayBuffer?
1569
+ // TODO should buffer be inlined into the page (albeit base64'd)?
1570
+ // any conditions in which it shouldn't be?
1062
1571
 
1063
- return Reflect.get(response, key, response);
1572
+ return buffer;
1573
+ };
1064
1574
  }
1065
- });
1066
1575
 
1067
- return proxy;
1068
- }
1576
+ if (key === 'text') {
1577
+ return text;
1578
+ }
1579
+
1580
+ if (key === 'json') {
1581
+ return async () => {
1582
+ return JSON.parse(await text());
1583
+ };
1584
+ }
1585
+
1586
+ // TODO arrayBuffer?
1587
+
1588
+ return Reflect.get(response, key, response);
1589
+ }
1590
+ });
1069
1591
 
1070
- return (
1071
- response ||
1072
- new Response('Not found', {
1073
- status: 404
1074
- })
1075
- );
1592
+ return proxy;
1076
1593
  },
1077
1594
  stuff: { ...stuff }
1078
1595
  };
@@ -1565,7 +2082,8 @@ async function respond(request, options, state = {}) {
1565
2082
  request,
1566
2083
  url,
1567
2084
  params: {},
1568
- locals: {}
2085
+ locals: {},
2086
+ platform: state.platform
1569
2087
  };
1570
2088
 
1571
2089
  // TODO remove this for 1.0
@@ -1627,7 +2145,9 @@ async function respond(request, options, state = {}) {
1627
2145
  let decoded = decodeURI(event.url.pathname);
1628
2146
 
1629
2147
  if (options.paths.base) {
1630
- if (!decoded.startsWith(options.paths.base)) return;
2148
+ if (!decoded.startsWith(options.paths.base)) {
2149
+ return new Response(undefined, { status: 404 });
2150
+ }
1631
2151
  decoded = decoded.slice(options.paths.base.length) || '/';
1632
2152
  }
1633
2153
 
@@ -1692,6 +2212,10 @@ async function respond(request, options, state = {}) {
1692
2212
  ssr
1693
2213
  });
1694
2214
  }
2215
+
2216
+ // we can't load the endpoint from our own manifest,
2217
+ // so we need to make an actual HTTP request
2218
+ return await fetch(request);
1695
2219
  },
1696
2220
 
1697
2221
  // TODO remove for 1.0
@@ -1739,12 +2263,12 @@ async function respond(request, options, state = {}) {
1739
2263
  * @returns {Promise<import('vite').Plugin>}
1740
2264
  */
1741
2265
  async function create_plugin(config, cwd) {
1742
- /** @type {import('amphtml-validator').Validator} */
2266
+ /** @type {import('types/hooks').Handle} */
1743
2267
  let amp;
1744
2268
 
1745
2269
  if (config.kit.amp) {
1746
2270
  process.env.VITE_SVELTEKIT_AMP = 'true';
1747
- amp = await (await import('./index8.js').then(function (n) { return n.i; })).getInstance();
2271
+ amp = (await import('./amp_hook.js')).handle;
1748
2272
  }
1749
2273
 
1750
2274
  return {
@@ -1861,7 +2385,6 @@ async function create_plugin(config, cwd) {
1861
2385
  vite.middlewares.use(async (req, res) => {
1862
2386
  try {
1863
2387
  if (!req.url || !req.method) throw new Error('Incomplete request');
1864
- if (req.url === '/favicon.ico') return not_found(res);
1865
2388
 
1866
2389
  const base = `${vite.config.server.https ? 'https' : 'http'}://${req.headers.host}`;
1867
2390
 
@@ -1878,6 +2401,8 @@ async function create_plugin(config, cwd) {
1878
2401
  }
1879
2402
  }
1880
2403
 
2404
+ if (req.url === '/favicon.ico') return not_found(res);
2405
+
1881
2406
  if (!decoded.startsWith(config.kit.paths.base)) return not_found(res);
1882
2407
 
1883
2408
  /** @type {Partial<import('types/internal').Hooks>} */
@@ -1885,10 +2410,12 @@ async function create_plugin(config, cwd) {
1885
2410
  ? await vite.ssrLoadModule(`/${config.kit.files.hooks}`)
1886
2411
  : {};
1887
2412
 
2413
+ const handle = user_hooks.handle || (({ event, resolve }) => resolve(event));
2414
+
1888
2415
  /** @type {import('types/internal').Hooks} */
1889
2416
  const hooks = {
1890
2417
  getSession: user_hooks.getSession || (() => ({})),
1891
- handle: user_hooks.handle || (({ event, resolve }) => resolve(event)),
2418
+ handle: amp ? sequence(amp, handle) : handle,
1892
2419
  handleError:
1893
2420
  user_hooks.handleError ||
1894
2421
  (({ /** @type {Error & { frame?: string }} */ error }) => {
@@ -1934,8 +2461,11 @@ async function create_plugin(config, cwd) {
1934
2461
  return res.end(err.reason || 'Invalid request body');
1935
2462
  }
1936
2463
 
2464
+ const template = load_template(cwd, config);
2465
+
1937
2466
  const rendered = await respond(request, {
1938
2467
  amp: config.kit.amp,
2468
+ csp: config.kit.csp,
1939
2469
  dev: true,
1940
2470
  floc: config.kit.floc,
1941
2471
  get_stack: (error) => {
@@ -1971,59 +2501,17 @@ async function create_plugin(config, cwd) {
1971
2501
  root,
1972
2502
  router: config.kit.router,
1973
2503
  target: config.kit.target,
1974
- template: ({ head, body, assets }) => {
1975
- let rendered = load_template(cwd, config)
1976
- .replace(/%svelte\.assets%/g, assets)
1977
- // head and body must be replaced last, in case someone tries to sneak in %svelte.assets% etc
1978
- .replace('%svelte.head%', () => head)
1979
- .replace('%svelte.body%', () => body);
1980
-
1981
- if (amp) {
1982
- const result = amp.validateString(rendered);
1983
-
1984
- if (result.status !== 'PASS') {
1985
- const lines = rendered.split('\n');
1986
-
1987
- /** @param {string} str */
1988
- const escape = (str) =>
1989
- str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
1990
-
1991
- rendered = `<!doctype html>
1992
- <head>
1993
- <meta charset="utf-8" />
1994
- <meta name="viewport" content="width=device-width, initial-scale=1" />
1995
- <style>
1996
- body {
1997
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
1998
- color: #333;
1999
- }
2000
-
2001
- pre {
2002
- background: #f4f4f4;
2003
- padding: 1em;
2004
- overflow-x: auto;
2005
- }
2006
- </style>
2007
- </head>
2008
- <h1>AMP validation failed</h1>
2009
-
2010
- ${result.errors
2011
- .map(
2012
- (error) => `
2013
- <h2>${error.severity}</h2>
2014
- <p>Line ${error.line}, column ${error.col}: ${error.message} (<a href="${error.specUrl}">${
2015
- error.code
2016
- }</a>)</p>
2017
- <pre>${escape(lines[error.line - 1])}</pre>
2018
- `
2019
- )
2020
- .join('\n\n')}
2021
- `;
2022
- }
2023
- }
2024
-
2025
- return rendered;
2504
+ template: ({ head, body, assets, nonce }) => {
2505
+ return (
2506
+ template
2507
+ .replace(/%svelte\.assets%/g, assets)
2508
+ .replace(/%svelte\.nonce%/g, nonce)
2509
+ // head and body must be replaced last, in case someone tries to sneak in %svelte.assets% etc
2510
+ .replace('%svelte.head%', () => head)
2511
+ .replace('%svelte.body%', () => body)
2512
+ );
2026
2513
  },
2514
+ template_contains_nonce: template.includes('%svelte.nonce%'),
2027
2515
  trailing_slash: config.kit.trailingSlash
2028
2516
  });
2029
2517