@sveltejs/kit 1.0.0-next.47 → 1.0.0-next.472

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.
Files changed (117) hide show
  1. package/README.md +12 -9
  2. package/package.json +93 -64
  3. package/scripts/special-types/$env+dynamic+private.md +8 -0
  4. package/scripts/special-types/$env+dynamic+public.md +8 -0
  5. package/scripts/special-types/$env+static+private.md +19 -0
  6. package/scripts/special-types/$env+static+public.md +7 -0
  7. package/scripts/special-types/$lib.md +1 -0
  8. package/src/cli.js +112 -0
  9. package/src/constants.js +7 -0
  10. package/src/core/adapt/builder.js +207 -0
  11. package/src/core/adapt/index.js +31 -0
  12. package/src/core/config/default-error.html +56 -0
  13. package/src/core/config/index.js +105 -0
  14. package/src/core/config/options.js +492 -0
  15. package/src/core/config/types.d.ts +1 -0
  16. package/src/core/env.js +121 -0
  17. package/src/core/generate_manifest/index.js +92 -0
  18. package/src/core/prerender/crawl.js +194 -0
  19. package/src/core/prerender/prerender.js +431 -0
  20. package/src/core/prerender/queue.js +80 -0
  21. package/src/core/sync/create_manifest_data/index.js +472 -0
  22. package/src/core/sync/create_manifest_data/types.d.ts +37 -0
  23. package/src/core/sync/sync.js +59 -0
  24. package/src/core/sync/utils.js +33 -0
  25. package/src/core/sync/write_ambient.js +53 -0
  26. package/src/core/sync/write_client_manifest.js +94 -0
  27. package/src/core/sync/write_matchers.js +25 -0
  28. package/src/core/sync/write_root.js +91 -0
  29. package/src/core/sync/write_tsconfig.js +195 -0
  30. package/src/core/sync/write_types/index.js +673 -0
  31. package/src/core/utils.js +70 -0
  32. package/src/exports/hooks/index.js +1 -0
  33. package/src/exports/hooks/sequence.js +44 -0
  34. package/src/exports/index.js +54 -0
  35. package/src/exports/node/index.js +145 -0
  36. package/src/exports/node/polyfills.js +41 -0
  37. package/src/exports/vite/build/build_server.js +357 -0
  38. package/src/exports/vite/build/build_service_worker.js +90 -0
  39. package/src/exports/vite/build/utils.js +162 -0
  40. package/src/exports/vite/dev/index.js +554 -0
  41. package/src/exports/vite/index.js +591 -0
  42. package/src/exports/vite/preview/index.js +186 -0
  43. package/src/exports/vite/types.d.ts +3 -0
  44. package/src/exports/vite/utils.js +361 -0
  45. package/src/runtime/app/env.js +1 -0
  46. package/src/runtime/app/environment.js +11 -0
  47. package/src/runtime/app/forms.js +65 -0
  48. package/src/runtime/app/navigation.js +23 -0
  49. package/src/runtime/app/paths.js +1 -0
  50. package/src/runtime/app/stores.js +102 -0
  51. package/src/runtime/client/ambient.d.ts +24 -0
  52. package/src/runtime/client/client.js +1558 -0
  53. package/src/runtime/client/fetcher.js +107 -0
  54. package/src/runtime/client/parse.js +60 -0
  55. package/src/runtime/client/singletons.js +21 -0
  56. package/src/runtime/client/start.js +37 -0
  57. package/src/runtime/client/types.d.ts +87 -0
  58. package/src/runtime/client/utils.js +159 -0
  59. package/src/runtime/components/error.svelte +16 -0
  60. package/{assets → src/runtime}/components/layout.svelte +0 -0
  61. package/src/runtime/control.js +100 -0
  62. package/src/runtime/env/dynamic/private.js +1 -0
  63. package/src/runtime/env/dynamic/public.js +1 -0
  64. package/src/runtime/env-private.js +6 -0
  65. package/src/runtime/env-public.js +6 -0
  66. package/src/runtime/env.js +6 -0
  67. package/src/runtime/hash.js +16 -0
  68. package/src/runtime/paths.js +11 -0
  69. package/src/runtime/server/cookie.js +76 -0
  70. package/src/runtime/server/data/index.js +146 -0
  71. package/src/runtime/server/endpoint.js +66 -0
  72. package/src/runtime/server/index.js +339 -0
  73. package/src/runtime/server/page/actions.js +225 -0
  74. package/src/runtime/server/page/crypto.js +239 -0
  75. package/src/runtime/server/page/csp.js +249 -0
  76. package/src/runtime/server/page/fetch.js +286 -0
  77. package/src/runtime/server/page/index.js +308 -0
  78. package/src/runtime/server/page/load_data.js +124 -0
  79. package/src/runtime/server/page/render.js +359 -0
  80. package/src/runtime/server/page/respond_with_error.js +92 -0
  81. package/src/runtime/server/page/serialize_data.js +87 -0
  82. package/src/runtime/server/page/types.d.ts +41 -0
  83. package/src/runtime/server/utils.js +220 -0
  84. package/src/utils/array.js +9 -0
  85. package/src/utils/error.js +22 -0
  86. package/src/utils/escape.js +46 -0
  87. package/src/utils/filesystem.js +108 -0
  88. package/src/utils/functions.js +16 -0
  89. package/src/utils/http.js +55 -0
  90. package/src/utils/misc.js +1 -0
  91. package/src/utils/routing.js +117 -0
  92. package/src/utils/url.js +142 -0
  93. package/svelte-kit.js +1 -1
  94. package/types/ambient.d.ts +404 -0
  95. package/types/index.d.ts +396 -0
  96. package/types/internal.d.ts +377 -0
  97. package/types/private.d.ts +210 -0
  98. package/CHANGELOG.md +0 -463
  99. package/assets/components/error.svelte +0 -13
  100. package/assets/runtime/app/env.js +0 -5
  101. package/assets/runtime/app/navigation.js +0 -44
  102. package/assets/runtime/app/paths.js +0 -1
  103. package/assets/runtime/app/stores.js +0 -93
  104. package/assets/runtime/chunks/utils.js +0 -22
  105. package/assets/runtime/internal/singletons.js +0 -23
  106. package/assets/runtime/internal/start.js +0 -773
  107. package/assets/runtime/paths.js +0 -12
  108. package/dist/chunks/index.js +0 -3517
  109. package/dist/chunks/index2.js +0 -587
  110. package/dist/chunks/index3.js +0 -246
  111. package/dist/chunks/index4.js +0 -530
  112. package/dist/chunks/index5.js +0 -763
  113. package/dist/chunks/index6.js +0 -322
  114. package/dist/chunks/standard.js +0 -99
  115. package/dist/chunks/utils.js +0 -83
  116. package/dist/cli.js +0 -553
  117. package/dist/ssr.js +0 -2581
@@ -0,0 +1,105 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import * as url from 'url';
4
+ import options from './options.js';
5
+
6
+ /**
7
+ * Loads the template (src/app.html by default) and validates that it has the
8
+ * required content.
9
+ * @param {string} cwd
10
+ * @param {import('types').ValidatedConfig} config
11
+ */
12
+ export function load_template(cwd, config) {
13
+ const { appTemplate } = config.kit.files;
14
+ const relative = path.relative(cwd, appTemplate);
15
+
16
+ if (fs.existsSync(appTemplate)) {
17
+ const contents = fs.readFileSync(appTemplate, 'utf8');
18
+
19
+ // TODO remove this for 1.0
20
+ const match = /%svelte\.([a-z]+)%/.exec(contents);
21
+ if (match) {
22
+ throw new Error(
23
+ `%svelte.${match[1]}% in ${relative} should be replaced with %sveltekit.${match[1]}%`
24
+ );
25
+ }
26
+
27
+ const expected_tags = ['%sveltekit.head%', '%sveltekit.body%'];
28
+ expected_tags.forEach((tag) => {
29
+ if (contents.indexOf(tag) === -1) {
30
+ throw new Error(`${relative} is missing ${tag}`);
31
+ }
32
+ });
33
+ } else {
34
+ throw new Error(`${relative} does not exist`);
35
+ }
36
+
37
+ return fs.readFileSync(appTemplate, 'utf-8');
38
+ }
39
+
40
+ /**
41
+ * Loads the error page (src/error.html by default) if it exists.
42
+ * Falls back to a generic error page content.
43
+ * @param {import('types').ValidatedConfig} config
44
+ */
45
+ export function load_error_page(config) {
46
+ const { errorTemplate } = config.kit.files;
47
+ return fs.readFileSync(errorTemplate, 'utf-8');
48
+ }
49
+
50
+ /**
51
+ * Loads and validates svelte.config.js
52
+ * @param {{ cwd?: string }} options
53
+ * @returns {Promise<import('types').ValidatedConfig>}
54
+ */
55
+ export async function load_config({ cwd = process.cwd() } = {}) {
56
+ const config_file = path.join(cwd, 'svelte.config.js');
57
+
58
+ if (!fs.existsSync(config_file)) {
59
+ return process_config({}, { cwd });
60
+ }
61
+
62
+ const config = await import(`${url.pathToFileURL(config_file).href}?ts=${Date.now()}`);
63
+
64
+ return process_config(config.default, { cwd });
65
+ }
66
+
67
+ /**
68
+ * @param {import('types').Config} config
69
+ * @returns {import('types').ValidatedConfig}
70
+ */
71
+ function process_config(config, { cwd = process.cwd() } = {}) {
72
+ const validated = validate_config(config);
73
+
74
+ validated.kit.outDir = path.resolve(cwd, validated.kit.outDir);
75
+
76
+ for (const key in validated.kit.files) {
77
+ // TODO remove for 1.0
78
+ if (key === 'template') continue;
79
+
80
+ // @ts-expect-error this is typescript at its stupidest
81
+ validated.kit.files[key] = path.resolve(cwd, validated.kit.files[key]);
82
+ }
83
+
84
+ if (!fs.existsSync(validated.kit.files.errorTemplate)) {
85
+ validated.kit.files.errorTemplate = url.fileURLToPath(
86
+ new URL('./default-error.html', import.meta.url)
87
+ );
88
+ }
89
+
90
+ return validated;
91
+ }
92
+
93
+ /**
94
+ * @param {import('types').Config} config
95
+ * @returns {import('types').ValidatedConfig}
96
+ */
97
+ export function validate_config(config) {
98
+ if (typeof config !== 'object') {
99
+ throw new Error(
100
+ 'svelte.config.js must have a configuration object as its default export. See https://kit.svelte.dev/docs/configuration'
101
+ );
102
+ }
103
+
104
+ return options(config, 'config');
105
+ }
@@ -0,0 +1,492 @@
1
+ import { join } from 'path';
2
+
3
+ /** @typedef {import('./types').Validator} Validator */
4
+
5
+ const directives = object({
6
+ 'child-src': string_array(),
7
+ 'default-src': string_array(),
8
+ 'frame-src': string_array(),
9
+ 'worker-src': string_array(),
10
+ 'connect-src': string_array(),
11
+ 'font-src': string_array(),
12
+ 'img-src': string_array(),
13
+ 'manifest-src': string_array(),
14
+ 'media-src': string_array(),
15
+ 'object-src': string_array(),
16
+ 'prefetch-src': string_array(),
17
+ 'script-src': string_array(),
18
+ 'script-src-elem': string_array(),
19
+ 'script-src-attr': string_array(),
20
+ 'style-src': string_array(),
21
+ 'style-src-elem': string_array(),
22
+ 'style-src-attr': string_array(),
23
+ 'base-uri': string_array(),
24
+ sandbox: string_array(),
25
+ 'form-action': string_array(),
26
+ 'frame-ancestors': string_array(),
27
+ 'navigate-to': string_array(),
28
+ 'report-uri': string_array(),
29
+ 'report-to': string_array(),
30
+ 'require-trusted-types-for': string_array(),
31
+ 'trusted-types': string_array(),
32
+ 'upgrade-insecure-requests': boolean(false),
33
+ 'require-sri-for': string_array(),
34
+ 'block-all-mixed-content': boolean(false),
35
+ 'plugin-types': string_array(),
36
+ referrer: string_array()
37
+ });
38
+
39
+ /** @type {Validator} */
40
+ const options = object(
41
+ {
42
+ extensions: validate(['.svelte'], (input, keypath) => {
43
+ if (!Array.isArray(input) || !input.every((page) => typeof page === 'string')) {
44
+ throw new Error(`${keypath} must be an array of strings`);
45
+ }
46
+
47
+ input.forEach((extension) => {
48
+ if (extension[0] !== '.') {
49
+ throw new Error(`Each member of ${keypath} must start with '.' — saw '${extension}'`);
50
+ }
51
+
52
+ if (!/^(\.[a-z0-9]+)+$/i.test(extension)) {
53
+ throw new Error(`File extensions must be alphanumeric — saw '${extension}'`);
54
+ }
55
+ });
56
+
57
+ return input;
58
+ }),
59
+
60
+ kit: object({
61
+ adapter: validate(null, (input, keypath) => {
62
+ if (typeof input !== 'object' || !input.adapt) {
63
+ let message = `${keypath} should be an object with an "adapt" method`;
64
+
65
+ if (Array.isArray(input) || typeof input === 'string') {
66
+ // for the early adapter adopters
67
+ message += ', rather than the name of an adapter';
68
+ }
69
+
70
+ throw new Error(`${message}. See https://kit.svelte.dev/docs/adapters`);
71
+ }
72
+
73
+ return input;
74
+ }),
75
+
76
+ alias: validate({}, (input, keypath) => {
77
+ if (typeof input !== 'object') {
78
+ throw new Error(`${keypath} should be an object`);
79
+ }
80
+
81
+ for (const key in input) {
82
+ assert_string(input[key], `${keypath}.${key}`);
83
+ }
84
+
85
+ return input;
86
+ }),
87
+
88
+ // TODO: remove this for the 1.0 release
89
+ amp: error(
90
+ (keypath) =>
91
+ `${keypath} has been removed. See https://kit.svelte.dev/docs/seo#amp for details on how to support AMP`
92
+ ),
93
+
94
+ appDir: validate('_app', (input, keypath) => {
95
+ assert_string(input, keypath);
96
+
97
+ if (input) {
98
+ if (input.startsWith('/') || input.endsWith('/')) {
99
+ throw new Error(
100
+ "config.kit.appDir cannot start or end with '/'. See https://kit.svelte.dev/docs/configuration"
101
+ );
102
+ }
103
+ } else {
104
+ throw new Error(`${keypath} cannot be empty`);
105
+ }
106
+
107
+ return input;
108
+ }),
109
+
110
+ // TODO: remove this for the 1.0 release
111
+ browser: object({
112
+ hydrate: error(
113
+ (keypath) =>
114
+ `${keypath} has been removed. You can set it inside the top level +layout.js instead. See the PR for more information: https://github.com/sveltejs/kit/pull/6197`
115
+ ),
116
+ router: error(
117
+ (keypath) =>
118
+ `${keypath} has been removed. You can set it inside the top level +layout.js instead. See the PR for more information: https://github.com/sveltejs/kit/pull/6197`
119
+ )
120
+ }),
121
+
122
+ csp: object({
123
+ mode: list(['auto', 'hash', 'nonce']),
124
+ directives,
125
+ reportOnly: directives
126
+ }),
127
+
128
+ csrf: object({
129
+ checkOrigin: boolean(true)
130
+ }),
131
+
132
+ // TODO: remove this for the 1.0 release
133
+ endpointExtensions: error(
134
+ (keypath) => `${keypath} has been renamed to config.kit.moduleExtensions`
135
+ ),
136
+
137
+ env: object({
138
+ dir: string(process.cwd()),
139
+ publicPrefix: string('PUBLIC_')
140
+ }),
141
+
142
+ files: object({
143
+ assets: string('static'),
144
+ hooks: string(join('src', 'hooks')),
145
+ lib: string(join('src', 'lib')),
146
+ params: string(join('src', 'params')),
147
+ routes: string(join('src', 'routes')),
148
+ serviceWorker: string(join('src', 'service-worker')),
149
+ appTemplate: string(join('src', 'app.html')),
150
+ errorTemplate: string(join('src', 'error.html')),
151
+ // TODO: remove this for the 1.0 release
152
+ template: error(
153
+ () => 'config.kit.files.template has been renamed to config.kit.files.appTemplate'
154
+ )
155
+ }),
156
+
157
+ // TODO: remove this for the 1.0 release
158
+ headers: error(
159
+ (keypath) =>
160
+ `${keypath} has been removed. See https://github.com/sveltejs/kit/pull/3384 for details`
161
+ ),
162
+
163
+ // TODO: remove this for the 1.0 release
164
+ host: error(
165
+ (keypath) =>
166
+ `${keypath} has been removed. See https://github.com/sveltejs/kit/pull/3384 for details`
167
+ ),
168
+
169
+ // TODO remove for 1.0
170
+ hydrate: error((keypath) => `${keypath} has been moved to config.kit.browser.hydrate`),
171
+
172
+ inlineStyleThreshold: number(0),
173
+
174
+ methodOverride: error(
175
+ () =>
176
+ 'Method overrides have been removed in favor of actions. See the PR for more information: https://github.com/sveltejs/kit/pull/6469'
177
+ ),
178
+
179
+ moduleExtensions: string_array(['.js', '.ts']),
180
+
181
+ outDir: string('.svelte-kit'),
182
+
183
+ package: error((keypath) => `${keypath} has been removed — use @sveltejs/package instead`),
184
+
185
+ paths: object({
186
+ base: validate('', (input, keypath) => {
187
+ assert_string(input, keypath);
188
+
189
+ if (input !== '' && (input.endsWith('/') || !input.startsWith('/'))) {
190
+ throw new Error(
191
+ `${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`
192
+ );
193
+ }
194
+
195
+ return input;
196
+ }),
197
+ assets: validate('', (input, keypath) => {
198
+ assert_string(input, keypath);
199
+
200
+ if (input) {
201
+ if (!/^[a-z]+:\/\//.test(input)) {
202
+ throw new Error(
203
+ `${keypath} option must be an absolute path, if specified. See https://kit.svelte.dev/docs/configuration#paths`
204
+ );
205
+ }
206
+
207
+ if (input.endsWith('/')) {
208
+ throw new Error(
209
+ `${keypath} option must not end with '/'. See https://kit.svelte.dev/docs/configuration#paths`
210
+ );
211
+ }
212
+ }
213
+
214
+ return input;
215
+ })
216
+ }),
217
+
218
+ prerender: object({
219
+ concurrency: number(1),
220
+ crawl: boolean(true),
221
+ createIndexFiles: error(
222
+ (keypath) =>
223
+ `${keypath} has been removed — it is now controlled by the trailingSlash option. See https://kit.svelte.dev/docs/configuration#trailingslash`
224
+ ),
225
+ default: error(
226
+ (keypath) =>
227
+ `${keypath} has been removed. You can set it inside the top level +layout.js instead. See the PR for more information: https://github.com/sveltejs/kit/pull/6197`
228
+ ),
229
+ enabled: boolean(true),
230
+ entries: validate(['*'], (input, keypath) => {
231
+ if (!Array.isArray(input) || !input.every((page) => typeof page === 'string')) {
232
+ throw new Error(`${keypath} must be an array of strings`);
233
+ }
234
+
235
+ input.forEach((page) => {
236
+ if (page !== '*' && page[0] !== '/') {
237
+ throw new Error(
238
+ `Each member of ${keypath} must be either '*' or an absolute path beginning with '/' — saw '${page}'`
239
+ );
240
+ }
241
+ });
242
+
243
+ return input;
244
+ }),
245
+
246
+ // TODO: remove this for the 1.0 release
247
+ force: validate(undefined, (input, keypath) => {
248
+ if (typeof input !== 'undefined') {
249
+ const newSetting = input ? 'continue' : 'fail';
250
+ const needsSetting = newSetting === 'continue';
251
+ throw new Error(
252
+ `${keypath} has been removed in favor of \`onError\`. In your case, set \`onError\` to "${newSetting}"${
253
+ needsSetting ? '' : ' (or leave it undefined)'
254
+ } to get the same behavior as you would with \`force: ${JSON.stringify(input)}\``
255
+ );
256
+ }
257
+ }),
258
+
259
+ onError: validate('fail', (input, keypath) => {
260
+ if (typeof input === 'function') return input;
261
+ if (['continue', 'fail'].includes(input)) return input;
262
+ throw new Error(
263
+ `${keypath} should be either a custom function or one of "continue" or "fail"`
264
+ );
265
+ }),
266
+
267
+ origin: validate('http://sveltekit-prerender', (input, keypath) => {
268
+ assert_string(input, keypath);
269
+
270
+ let origin;
271
+
272
+ try {
273
+ origin = new URL(input).origin;
274
+ } catch (e) {
275
+ throw new Error(`${keypath} must be a valid origin`);
276
+ }
277
+
278
+ if (input !== origin) {
279
+ throw new Error(`${keypath} must be a valid origin (${origin} rather than ${input})`);
280
+ }
281
+
282
+ return origin;
283
+ }),
284
+
285
+ // TODO: remove this for the 1.0 release
286
+ pages: error((keypath) => `${keypath} has been renamed to \`entries\`.`)
287
+ }),
288
+
289
+ // TODO: remove this for the 1.0 release
290
+ protocol: error(
291
+ (keypath) =>
292
+ `${keypath} has been removed. See https://github.com/sveltejs/kit/pull/3384 for details`
293
+ ),
294
+
295
+ // TODO remove for 1.0
296
+ router: error((keypath) => `${keypath} has been moved to config.kit.browser.router`),
297
+
298
+ // TODO remove for 1.0
299
+ routes: error(
300
+ (keypath) =>
301
+ `${keypath} has been removed. See https://github.com/sveltejs/kit/discussions/5774 for details`
302
+ ),
303
+
304
+ serviceWorker: object({
305
+ register: boolean(true),
306
+ files: fun((filename) => !/\.DS_Store/.test(filename))
307
+ }),
308
+
309
+ // TODO remove this for 1.0
310
+ ssr: error(
311
+ (keypath) =>
312
+ `${keypath} has been removed — use the handle hook instead: https://kit.svelte.dev/docs/hooks#handle`
313
+ ),
314
+
315
+ // TODO remove this for 1.0
316
+ target: error((keypath) => `${keypath} is no longer required, and should be removed`),
317
+
318
+ trailingSlash: list(['never', 'always', 'ignore']),
319
+
320
+ version: object({
321
+ name: string(Date.now().toString()),
322
+ pollInterval: number(0)
323
+ }),
324
+
325
+ // TODO remove this for 1.0
326
+ vite: error((keypath) => `${keypath} has been removed — use vite.config.js instead`)
327
+ })
328
+ },
329
+ true
330
+ );
331
+
332
+ /**
333
+ * @param {Record<string, Validator>} children
334
+ * @param {boolean} [allow_unknown]
335
+ * @returns {Validator}
336
+ */
337
+ function object(children, allow_unknown = false) {
338
+ return (input, keypath) => {
339
+ /** @type {Record<string, any>} */
340
+ const output = {};
341
+
342
+ if ((input && typeof input !== 'object') || Array.isArray(input)) {
343
+ throw new Error(`${keypath} should be an object`);
344
+ }
345
+
346
+ for (const key in input) {
347
+ if (!(key in children)) {
348
+ if (allow_unknown) {
349
+ output[key] = input[key];
350
+ } else {
351
+ let message = `Unexpected option ${keypath}.${key}`;
352
+
353
+ // special case
354
+ if (keypath === 'config.kit' && key in options) {
355
+ message += ` (did you mean config.${key}?)`;
356
+ }
357
+
358
+ throw new Error(message);
359
+ }
360
+ }
361
+ }
362
+
363
+ for (const key in children) {
364
+ const validator = children[key];
365
+ output[key] = validator(input && input[key], `${keypath}.${key}`);
366
+ }
367
+
368
+ return output;
369
+ };
370
+ }
371
+
372
+ /**
373
+ * @param {any} fallback
374
+ * @param {(value: any, keypath: string) => any} fn
375
+ * @returns {Validator}
376
+ */
377
+ function validate(fallback, fn) {
378
+ return (input, keypath) => {
379
+ return input === undefined ? fallback : fn(input, keypath);
380
+ };
381
+ }
382
+
383
+ /**
384
+ * @param {string | null} fallback
385
+ * @param {boolean} allow_empty
386
+ * @returns {Validator}
387
+ */
388
+ function string(fallback, allow_empty = true) {
389
+ return validate(fallback, (input, keypath) => {
390
+ assert_string(input, keypath);
391
+
392
+ if (!allow_empty && input === '') {
393
+ throw new Error(`${keypath} cannot be empty`);
394
+ }
395
+
396
+ return input;
397
+ });
398
+ }
399
+
400
+ /**
401
+ * @param {string[] | undefined} [fallback]
402
+ * @returns {Validator}
403
+ */
404
+ function string_array(fallback) {
405
+ return validate(fallback, (input, keypath) => {
406
+ if (input === undefined) return input;
407
+
408
+ if (!Array.isArray(input) || input.some((value) => typeof value !== 'string')) {
409
+ throw new Error(`${keypath} must be an array of strings, if specified`);
410
+ }
411
+
412
+ return input;
413
+ });
414
+ }
415
+
416
+ /**
417
+ * @param {number} fallback
418
+ * @returns {Validator}
419
+ */
420
+ function number(fallback) {
421
+ return validate(fallback, (input, keypath) => {
422
+ if (typeof input !== 'number') {
423
+ throw new Error(`${keypath} should be a number, if specified`);
424
+ }
425
+ return input;
426
+ });
427
+ }
428
+
429
+ /**
430
+ * @param {boolean} fallback
431
+ * @returns {Validator}
432
+ */
433
+ function boolean(fallback) {
434
+ return validate(fallback, (input, keypath) => {
435
+ if (typeof input !== 'boolean') {
436
+ throw new Error(`${keypath} should be true or false, if specified`);
437
+ }
438
+ return input;
439
+ });
440
+ }
441
+
442
+ /**
443
+ * @param {string[]} options
444
+ * @returns {Validator}
445
+ */
446
+ function list(options, fallback = options[0]) {
447
+ return validate(fallback, (input, keypath) => {
448
+ if (!options.includes(input)) {
449
+ // prettier-ignore
450
+ const msg = options.length > 2
451
+ ? `${keypath} should be one of ${options.slice(0, -1).map(input => `"${input}"`).join(', ')} or "${options[options.length - 1]}"`
452
+ : `${keypath} should be either "${options[0]}" or "${options[1]}"`;
453
+
454
+ throw new Error(msg);
455
+ }
456
+ return input;
457
+ });
458
+ }
459
+
460
+ /**
461
+ * @param {(filename: string) => boolean} fallback
462
+ * @returns {Validator}
463
+ */
464
+ function fun(fallback) {
465
+ return validate(fallback, (input, keypath) => {
466
+ if (typeof input !== 'function') {
467
+ throw new Error(`${keypath} should be a function, if specified`);
468
+ }
469
+ return input;
470
+ });
471
+ }
472
+
473
+ /**
474
+ * @param {string} input
475
+ * @param {string} keypath
476
+ */
477
+ function assert_string(input, keypath) {
478
+ if (typeof input !== 'string') {
479
+ throw new Error(`${keypath} should be a string, if specified`);
480
+ }
481
+ }
482
+
483
+ /** @param {(keypath?: string) => string} fn */
484
+ function error(fn) {
485
+ return validate(undefined, (input, keypath) => {
486
+ if (input !== undefined) {
487
+ throw new Error(fn(keypath));
488
+ }
489
+ });
490
+ }
491
+
492
+ export default options;
@@ -0,0 +1 @@
1
+ export type Validator<T = any> = (input: T, keypath: string) => T;