@sveltejs/kit 1.0.0-next.352 → 1.0.0-next.353

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.
@@ -0,0 +1,673 @@
1
+ import fs__default from 'fs';
2
+ import path__default, { join } from 'path';
3
+ import * as url from 'url';
4
+
5
+ let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true;
6
+ if (typeof process !== 'undefined') {
7
+ ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env);
8
+ isTTY = process.stdout && process.stdout.isTTY;
9
+ }
10
+
11
+ const $ = {
12
+ enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && (
13
+ FORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY
14
+ ),
15
+
16
+ // modifiers
17
+ reset: init(0, 0),
18
+ bold: init(1, 22),
19
+ dim: init(2, 22),
20
+ italic: init(3, 23),
21
+ underline: init(4, 24),
22
+ inverse: init(7, 27),
23
+ hidden: init(8, 28),
24
+ strikethrough: init(9, 29),
25
+
26
+ // colors
27
+ black: init(30, 39),
28
+ red: init(31, 39),
29
+ green: init(32, 39),
30
+ yellow: init(33, 39),
31
+ blue: init(34, 39),
32
+ magenta: init(35, 39),
33
+ cyan: init(36, 39),
34
+ white: init(37, 39),
35
+ gray: init(90, 39),
36
+ grey: init(90, 39),
37
+
38
+ // background colors
39
+ bgBlack: init(40, 49),
40
+ bgRed: init(41, 49),
41
+ bgGreen: init(42, 49),
42
+ bgYellow: init(43, 49),
43
+ bgBlue: init(44, 49),
44
+ bgMagenta: init(45, 49),
45
+ bgCyan: init(46, 49),
46
+ bgWhite: init(47, 49)
47
+ };
48
+
49
+ function run(arr, str) {
50
+ let i=0, tmp, beg='', end='';
51
+ for (; i < arr.length; i++) {
52
+ tmp = arr[i];
53
+ beg += tmp.open;
54
+ end += tmp.close;
55
+ if (!!~str.indexOf(tmp.close)) {
56
+ str = str.replace(tmp.rgx, tmp.close + tmp.open);
57
+ }
58
+ }
59
+ return beg + str + end;
60
+ }
61
+
62
+ function chain(has, keys) {
63
+ let ctx = { has, keys };
64
+
65
+ ctx.reset = $.reset.bind(ctx);
66
+ ctx.bold = $.bold.bind(ctx);
67
+ ctx.dim = $.dim.bind(ctx);
68
+ ctx.italic = $.italic.bind(ctx);
69
+ ctx.underline = $.underline.bind(ctx);
70
+ ctx.inverse = $.inverse.bind(ctx);
71
+ ctx.hidden = $.hidden.bind(ctx);
72
+ ctx.strikethrough = $.strikethrough.bind(ctx);
73
+
74
+ ctx.black = $.black.bind(ctx);
75
+ ctx.red = $.red.bind(ctx);
76
+ ctx.green = $.green.bind(ctx);
77
+ ctx.yellow = $.yellow.bind(ctx);
78
+ ctx.blue = $.blue.bind(ctx);
79
+ ctx.magenta = $.magenta.bind(ctx);
80
+ ctx.cyan = $.cyan.bind(ctx);
81
+ ctx.white = $.white.bind(ctx);
82
+ ctx.gray = $.gray.bind(ctx);
83
+ ctx.grey = $.grey.bind(ctx);
84
+
85
+ ctx.bgBlack = $.bgBlack.bind(ctx);
86
+ ctx.bgRed = $.bgRed.bind(ctx);
87
+ ctx.bgGreen = $.bgGreen.bind(ctx);
88
+ ctx.bgYellow = $.bgYellow.bind(ctx);
89
+ ctx.bgBlue = $.bgBlue.bind(ctx);
90
+ ctx.bgMagenta = $.bgMagenta.bind(ctx);
91
+ ctx.bgCyan = $.bgCyan.bind(ctx);
92
+ ctx.bgWhite = $.bgWhite.bind(ctx);
93
+
94
+ return ctx;
95
+ }
96
+
97
+ function init(open, close) {
98
+ let blk = {
99
+ open: `\x1b[${open}m`,
100
+ close: `\x1b[${close}m`,
101
+ rgx: new RegExp(`\\x1b\\[${close}m`, 'g')
102
+ };
103
+ return function (txt) {
104
+ if (this !== void 0 && this.has !== void 0) {
105
+ !!~this.has.indexOf(open) || (this.has.push(open),this.keys.push(blk));
106
+ return txt === void 0 ? this : $.enabled ? run(this.keys, txt+'') : txt+'';
107
+ }
108
+ return txt === void 0 ? chain([open], [blk]) : $.enabled ? run([blk], txt+'') : txt+'';
109
+ };
110
+ }
111
+
112
+ /** @typedef {import('./types').Validator} Validator */
113
+
114
+ /** @type {Validator} */
115
+ const options = object(
116
+ {
117
+ extensions: validate(['.svelte'], (input, keypath) => {
118
+ if (!Array.isArray(input) || !input.every((page) => typeof page === 'string')) {
119
+ throw new Error(`${keypath} must be an array of strings`);
120
+ }
121
+
122
+ input.forEach((extension) => {
123
+ if (extension[0] !== '.') {
124
+ throw new Error(`Each member of ${keypath} must start with '.' — saw '${extension}'`);
125
+ }
126
+
127
+ if (!/^(\.[a-z0-9]+)+$/i.test(extension)) {
128
+ throw new Error(`File extensions must be alphanumeric — saw '${extension}'`);
129
+ }
130
+ });
131
+
132
+ return input;
133
+ }),
134
+
135
+ kit: object({
136
+ adapter: validate(null, (input, keypath) => {
137
+ if (typeof input !== 'object' || !input.adapt) {
138
+ let message = `${keypath} should be an object with an "adapt" method`;
139
+
140
+ if (Array.isArray(input) || typeof input === 'string') {
141
+ // for the early adapter adopters
142
+ message += ', rather than the name of an adapter';
143
+ }
144
+
145
+ throw new Error(`${message}. See https://kit.svelte.dev/docs/adapters`);
146
+ }
147
+
148
+ return input;
149
+ }),
150
+
151
+ alias: validate({}, (input, keypath) => {
152
+ if (typeof input !== 'object') {
153
+ throw new Error(`${keypath} should be an object`);
154
+ }
155
+
156
+ for (const key in input) {
157
+ assert_string(input[key], `${keypath}.${key}`);
158
+ }
159
+
160
+ return input;
161
+ }),
162
+
163
+ // TODO: remove this for the 1.0 release
164
+ amp: error(
165
+ (keypath) =>
166
+ `${keypath} has been removed. See https://kit.svelte.dev/docs/seo#amp for details on how to support AMP`
167
+ ),
168
+
169
+ appDir: validate('_app', (input, keypath) => {
170
+ assert_string(input, keypath);
171
+
172
+ if (input) {
173
+ if (input.startsWith('/') || input.endsWith('/')) {
174
+ throw new Error(
175
+ "config.kit.appDir cannot start or end with '/'. See https://kit.svelte.dev/docs/configuration"
176
+ );
177
+ }
178
+ } else {
179
+ throw new Error(`${keypath} cannot be empty`);
180
+ }
181
+
182
+ return input;
183
+ }),
184
+
185
+ browser: object({
186
+ hydrate: boolean(true),
187
+ router: boolean(true)
188
+ }),
189
+
190
+ csp: object({
191
+ mode: list(['auto', 'hash', 'nonce']),
192
+ directives: object({
193
+ 'child-src': string_array(),
194
+ 'default-src': string_array(),
195
+ 'frame-src': string_array(),
196
+ 'worker-src': string_array(),
197
+ 'connect-src': string_array(),
198
+ 'font-src': string_array(),
199
+ 'img-src': string_array(),
200
+ 'manifest-src': string_array(),
201
+ 'media-src': string_array(),
202
+ 'object-src': string_array(),
203
+ 'prefetch-src': string_array(),
204
+ 'script-src': string_array(),
205
+ 'script-src-elem': string_array(),
206
+ 'script-src-attr': string_array(),
207
+ 'style-src': string_array(),
208
+ 'style-src-elem': string_array(),
209
+ 'style-src-attr': string_array(),
210
+ 'base-uri': string_array(),
211
+ sandbox: string_array(),
212
+ 'form-action': string_array(),
213
+ 'frame-ancestors': string_array(),
214
+ 'navigate-to': string_array(),
215
+ 'report-uri': string_array(),
216
+ 'report-to': string_array(),
217
+ 'require-trusted-types-for': string_array(),
218
+ 'trusted-types': string_array(),
219
+ 'upgrade-insecure-requests': boolean(false),
220
+ 'require-sri-for': string_array(),
221
+ 'block-all-mixed-content': boolean(false),
222
+ 'plugin-types': string_array(),
223
+ referrer: string_array()
224
+ })
225
+ }),
226
+
227
+ endpointExtensions: string_array(['.js', '.ts']),
228
+
229
+ files: object({
230
+ assets: string('static'),
231
+ hooks: string(join('src', 'hooks')),
232
+ lib: string(join('src', 'lib')),
233
+ params: string(join('src', 'params')),
234
+ routes: string(join('src', 'routes')),
235
+ serviceWorker: string(join('src', 'service-worker')),
236
+ template: string(join('src', 'app.html'))
237
+ }),
238
+
239
+ floc: boolean(false),
240
+
241
+ // TODO: remove this for the 1.0 release
242
+ headers: error(
243
+ (keypath) =>
244
+ `${keypath} has been removed. See https://github.com/sveltejs/kit/pull/3384 for details`
245
+ ),
246
+
247
+ // TODO: remove this for the 1.0 release
248
+ host: error(
249
+ (keypath) =>
250
+ `${keypath} has been removed. See https://github.com/sveltejs/kit/pull/3384 for details`
251
+ ),
252
+
253
+ // TODO remove for 1.0
254
+ hydrate: error((keypath) => `${keypath} has been moved to config.kit.browser.hydrate`),
255
+
256
+ inlineStyleThreshold: number(0),
257
+
258
+ methodOverride: object({
259
+ parameter: string('_method'),
260
+ allowed: validate([], (input, keypath) => {
261
+ if (!Array.isArray(input) || !input.every((method) => typeof method === 'string')) {
262
+ throw new Error(`${keypath} must be an array of strings`);
263
+ }
264
+
265
+ if (input.map((i) => i.toUpperCase()).includes('GET')) {
266
+ throw new Error(`${keypath} cannot contain "GET"`);
267
+ }
268
+
269
+ return input;
270
+ })
271
+ }),
272
+
273
+ outDir: string('.svelte-kit'),
274
+
275
+ package: object({
276
+ dir: string('package'),
277
+ // excludes all .d.ts and filename starting with _
278
+ exports: fun((filepath) => !/^_|\/_|\.d\.ts$/.test(filepath)),
279
+ files: fun(() => true),
280
+ emitTypes: boolean(true)
281
+ }),
282
+
283
+ paths: object({
284
+ base: validate('', (input, keypath) => {
285
+ assert_string(input, keypath);
286
+
287
+ if (input !== '' && (input.endsWith('/') || !input.startsWith('/'))) {
288
+ throw new Error(
289
+ `${keypath} option must either be the empty string or a root-relative path that starts but doesn't end with '/'. See https://kit.svelte.dev/docs/configuration#paths`
290
+ );
291
+ }
292
+
293
+ return input;
294
+ }),
295
+ assets: validate('', (input, keypath) => {
296
+ assert_string(input, keypath);
297
+
298
+ if (input) {
299
+ if (!/^[a-z]+:\/\//.test(input)) {
300
+ throw new Error(
301
+ `${keypath} option must be an absolute path, if specified. See https://kit.svelte.dev/docs/configuration#paths`
302
+ );
303
+ }
304
+
305
+ if (input.endsWith('/')) {
306
+ throw new Error(
307
+ `${keypath} option must not end with '/'. See https://kit.svelte.dev/docs/configuration#paths`
308
+ );
309
+ }
310
+ }
311
+
312
+ return input;
313
+ })
314
+ }),
315
+
316
+ prerender: object({
317
+ concurrency: number(1),
318
+ crawl: boolean(true),
319
+ createIndexFiles: error(
320
+ (keypath) =>
321
+ `${keypath} has been removed — it is now controlled by the trailingSlash option. See https://kit.svelte.dev/docs/configuration#trailingslash`
322
+ ),
323
+ default: boolean(false),
324
+ enabled: boolean(true),
325
+ entries: validate(['*'], (input, keypath) => {
326
+ if (!Array.isArray(input) || !input.every((page) => typeof page === 'string')) {
327
+ throw new Error(`${keypath} must be an array of strings`);
328
+ }
329
+
330
+ input.forEach((page) => {
331
+ if (page !== '*' && page[0] !== '/') {
332
+ throw new Error(
333
+ `Each member of ${keypath} must be either '*' or an absolute path beginning with '/' — saw '${page}'`
334
+ );
335
+ }
336
+ });
337
+
338
+ return input;
339
+ }),
340
+
341
+ // TODO: remove this for the 1.0 release
342
+ force: validate(undefined, (input, keypath) => {
343
+ if (typeof input !== 'undefined') {
344
+ const newSetting = input ? 'continue' : 'fail';
345
+ const needsSetting = newSetting === 'continue';
346
+ throw new Error(
347
+ `${keypath} has been removed in favor of \`onError\`. In your case, set \`onError\` to "${newSetting}"${
348
+ needsSetting ? '' : ' (or leave it undefined)'
349
+ } to get the same behavior as you would with \`force: ${JSON.stringify(input)}\``
350
+ );
351
+ }
352
+ }),
353
+
354
+ onError: validate('fail', (input, keypath) => {
355
+ if (typeof input === 'function') return input;
356
+ if (['continue', 'fail'].includes(input)) return input;
357
+ throw new Error(
358
+ `${keypath} should be either a custom function or one of "continue" or "fail"`
359
+ );
360
+ }),
361
+
362
+ // TODO: remove this for the 1.0 release
363
+ pages: error((keypath) => `${keypath} has been renamed to \`entries\`.`)
364
+ }),
365
+
366
+ // TODO: remove this for the 1.0 release
367
+ protocol: error(
368
+ (keypath) =>
369
+ `${keypath} has been removed. See https://github.com/sveltejs/kit/pull/3384 for details`
370
+ ),
371
+
372
+ // TODO remove for 1.0
373
+ router: error((keypath) => `${keypath} has been moved to config.kit.browser.router`),
374
+
375
+ routes: fun((filepath) => !/(?:(?:^_|\/_)|(?:^\.|\/\.)(?!well-known))/.test(filepath)),
376
+
377
+ serviceWorker: object({
378
+ register: boolean(true),
379
+ files: fun((filename) => !/\.DS_Store/.test(filename))
380
+ }),
381
+
382
+ // TODO remove this for 1.0
383
+ ssr: error(
384
+ (keypath) =>
385
+ `${keypath} has been removed — use the handle hook instead: https://kit.svelte.dev/docs/hooks#handle'`
386
+ ),
387
+
388
+ // TODO remove this for 1.0
389
+ target: error((keypath) => `${keypath} is no longer required, and should be removed`),
390
+
391
+ trailingSlash: list(['never', 'always', 'ignore']),
392
+
393
+ version: object({
394
+ name: string(Date.now().toString()),
395
+ pollInterval: number(0)
396
+ }),
397
+
398
+ vite: validate(
399
+ () => ({}),
400
+ (input, keypath) => {
401
+ if (typeof input === 'object') {
402
+ const config = input;
403
+ input = () => config;
404
+ }
405
+
406
+ if (typeof input !== 'function') {
407
+ throw new Error(
408
+ `${keypath} must be a Vite config object (https://vitejs.dev/config) or a function that returns one`
409
+ );
410
+ }
411
+
412
+ return input;
413
+ }
414
+ )
415
+ })
416
+ },
417
+ true
418
+ );
419
+
420
+ /**
421
+ * @param {Record<string, Validator>} children
422
+ * @param {boolean} [allow_unknown]
423
+ * @returns {Validator}
424
+ */
425
+ function object(children, allow_unknown) {
426
+ return (input, keypath) => {
427
+ /** @type {Record<string, any>} */
428
+ const output = {};
429
+
430
+ if ((input && typeof input !== 'object') || Array.isArray(input)) {
431
+ throw new Error(`${keypath} should be an object`);
432
+ }
433
+
434
+ for (const key in input) {
435
+ if (!(key in children)) {
436
+ if (allow_unknown) {
437
+ output[key] = input[key];
438
+ } else {
439
+ let message = `Unexpected option ${keypath}.${key}`;
440
+
441
+ // special case
442
+ if (keypath === 'config.kit' && key in options) {
443
+ message += ` (did you mean config.${key}?)`;
444
+ }
445
+
446
+ throw new Error(message);
447
+ }
448
+ }
449
+ }
450
+
451
+ for (const key in children) {
452
+ const validator = children[key];
453
+ output[key] = validator(input && input[key], `${keypath}.${key}`);
454
+ }
455
+
456
+ return output;
457
+ };
458
+ }
459
+
460
+ /**
461
+ * @param {any} fallback
462
+ * @param {(value: any, keypath: string) => any} fn
463
+ * @returns {Validator}
464
+ */
465
+ function validate(fallback, fn) {
466
+ return (input, keypath) => {
467
+ return input === undefined ? fallback : fn(input, keypath);
468
+ };
469
+ }
470
+
471
+ /**
472
+ * @param {string | null} fallback
473
+ * @param {boolean} allow_empty
474
+ * @returns {Validator}
475
+ */
476
+ function string(fallback, allow_empty = true) {
477
+ return validate(fallback, (input, keypath) => {
478
+ assert_string(input, keypath);
479
+
480
+ if (!allow_empty && input === '') {
481
+ throw new Error(`${keypath} cannot be empty`);
482
+ }
483
+
484
+ return input;
485
+ });
486
+ }
487
+
488
+ /**
489
+ * @param {string[] | undefined} [fallback]
490
+ * @returns {Validator}
491
+ */
492
+ function string_array(fallback) {
493
+ return validate(fallback, (input, keypath) => {
494
+ if (input === undefined) return input;
495
+
496
+ if (!Array.isArray(input) || input.some((value) => typeof value !== 'string')) {
497
+ throw new Error(`${keypath} must be an array of strings, if specified`);
498
+ }
499
+
500
+ return input;
501
+ });
502
+ }
503
+
504
+ /**
505
+ * @param {number} fallback
506
+ * @returns {Validator}
507
+ */
508
+ function number(fallback) {
509
+ return validate(fallback, (input, keypath) => {
510
+ if (typeof input !== 'number') {
511
+ throw new Error(`${keypath} should be a number, if specified`);
512
+ }
513
+ return input;
514
+ });
515
+ }
516
+
517
+ /**
518
+ * @param {boolean} fallback
519
+ * @returns {Validator}
520
+ */
521
+ function boolean(fallback) {
522
+ return validate(fallback, (input, keypath) => {
523
+ if (typeof input !== 'boolean') {
524
+ throw new Error(`${keypath} should be true or false, if specified`);
525
+ }
526
+ return input;
527
+ });
528
+ }
529
+
530
+ /**
531
+ * @param {string[]} options
532
+ * @returns {Validator}
533
+ */
534
+ function list(options, fallback = options[0]) {
535
+ return validate(fallback, (input, keypath) => {
536
+ if (!options.includes(input)) {
537
+ // prettier-ignore
538
+ const msg = options.length > 2
539
+ ? `${keypath} should be one of ${options.slice(0, -1).map(input => `"${input}"`).join(', ')} or "${options[options.length - 1]}"`
540
+ : `${keypath} should be either "${options[0]}" or "${options[1]}"`;
541
+
542
+ throw new Error(msg);
543
+ }
544
+ return input;
545
+ });
546
+ }
547
+
548
+ /**
549
+ * @param {(filename: string) => boolean} fallback
550
+ * @returns {Validator}
551
+ */
552
+ function fun(fallback) {
553
+ return validate(fallback, (input, keypath) => {
554
+ if (typeof input !== 'function') {
555
+ throw new Error(`${keypath} should be a function, if specified`);
556
+ }
557
+ return input;
558
+ });
559
+ }
560
+
561
+ /**
562
+ * @param {string} input
563
+ * @param {string} keypath
564
+ */
565
+ function assert_string(input, keypath) {
566
+ if (typeof input !== 'string') {
567
+ throw new Error(`${keypath} should be a string, if specified`);
568
+ }
569
+ }
570
+
571
+ /** @param {(keypath?: string) => string} fn */
572
+ function error(fn) {
573
+ return validate(undefined, (input, keypath) => {
574
+ if (input !== undefined) {
575
+ throw new Error(fn(keypath));
576
+ }
577
+ });
578
+ }
579
+
580
+ /**
581
+ * Loads the template (src/app.html by default) and validates that it has the
582
+ * required content.
583
+ * @param {string} cwd
584
+ * @param {import('types').ValidatedConfig} config
585
+ */
586
+ function load_template(cwd, config) {
587
+ const { template } = config.kit.files;
588
+ const relative = path__default.relative(cwd, template);
589
+
590
+ if (fs__default.existsSync(template)) {
591
+ const contents = fs__default.readFileSync(template, 'utf8');
592
+
593
+ // TODO remove this for 1.0
594
+ const match = /%svelte\.([a-z]+)%/.exec(contents);
595
+ if (match) {
596
+ throw new Error(
597
+ `%svelte.${match[1]}% in ${relative} should be replaced with %sveltekit.${match[1]}%`
598
+ );
599
+ }
600
+
601
+ const expected_tags = ['%sveltekit.head%', '%sveltekit.body%'];
602
+ expected_tags.forEach((tag) => {
603
+ if (contents.indexOf(tag) === -1) {
604
+ throw new Error(`${relative} is missing ${tag}`);
605
+ }
606
+ });
607
+ } else {
608
+ throw new Error(`${relative} does not exist`);
609
+ }
610
+
611
+ return fs__default.readFileSync(template, 'utf-8');
612
+ }
613
+
614
+ /**
615
+ * Loads and validates svelte.config.js
616
+ * @param {{ cwd?: string }} options
617
+ * @returns {Promise<import('types').ValidatedConfig>}
618
+ */
619
+ async function load_config({ cwd = process.cwd() } = {}) {
620
+ const config_file = path__default.join(cwd, 'svelte.config.js');
621
+
622
+ if (!fs__default.existsSync(config_file)) {
623
+ return process_config({}, { cwd });
624
+ }
625
+
626
+ const config = await import(`${url.pathToFileURL(config_file).href}?ts=${Date.now()}`);
627
+
628
+ return process_config(config.default, { cwd });
629
+ }
630
+
631
+ /**
632
+ * @param {import('types').Config} config
633
+ * @returns {import('types').ValidatedConfig}
634
+ */
635
+ function process_config(config, { cwd = process.cwd() }) {
636
+ const validated = validate_config(config);
637
+
638
+ validated.kit.outDir = path__default.resolve(cwd, validated.kit.outDir);
639
+
640
+ for (const key in validated.kit.files) {
641
+ // @ts-expect-error this is typescript at its stupidest
642
+ validated.kit.files[key] = path__default.resolve(cwd, validated.kit.files[key]);
643
+ }
644
+
645
+ return validated;
646
+ }
647
+
648
+ /**
649
+ * @param {import('types').Config} config
650
+ * @returns {import('types').ValidatedConfig}
651
+ */
652
+ function validate_config(config) {
653
+ if (typeof config !== 'object') {
654
+ throw new Error(
655
+ 'svelte.config.js must have a configuration object as its default export. See https://kit.svelte.dev/docs/configuration'
656
+ );
657
+ }
658
+
659
+ return options(config, 'config');
660
+ }
661
+
662
+ /**
663
+ * @param {unknown} err
664
+ * @return {Error}
665
+ */
666
+ function coalesce_to_error(err) {
667
+ return err instanceof Error ||
668
+ (err && /** @type {any} */ (err).name && /** @type {any} */ (err).message)
669
+ ? /** @type {Error} */ (err)
670
+ : new Error(JSON.stringify(err));
671
+ }
672
+
673
+ export { $, load_template as a, coalesce_to_error as c, load_config as l };