@vercel/config 0.0.9

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,555 @@
1
+ /**
2
+ * Helper function to reference a path parameter in transforms.
3
+ * Path parameters are extracted from the route pattern (e.g., :userId).
4
+ *
5
+ * @example
6
+ * param('userId') // Returns '$userId'
7
+ */
8
+ export declare function param(name: string): string;
9
+ /**
10
+ * Helper function to reference a runtime environment variable in transforms.
11
+ * These are environment variables that get resolved at request time by Vercel's routing layer,
12
+ * not at build time.
13
+ *
14
+ * @example
15
+ * runtimeEnv('BEARER_TOKEN') // Returns '$BEARER_TOKEN'
16
+ */
17
+ export declare function runtimeEnv(name: string): string;
18
+ /**
19
+ * Template literal type for durations recognized by pretty-cache-header.
20
+ *
21
+ * Usage examples: '10s', '1week', '2months', '12hrs'
22
+ */
23
+ export type TimeUnit = 'ms' | 'milli' | 'millisecond' | 'milliseconds' | 's' | 'sec' | 'secs' | 'second' | 'seconds' | 'm' | 'min' | 'mins' | 'minute' | 'minutes' | 'h' | 'hr' | 'hrs' | 'hour' | 'hours' | 'd' | 'day' | 'days' | 'w' | 'week' | 'weeks' | 'mon' | 'mth' | 'mths' | 'month' | 'months' | 'y' | 'yr' | 'yrs' | 'year' | 'years';
24
+ export type TimeString = `${number}${TimeUnit}`;
25
+ /**
26
+ * Options for constructing the Cache-Control header.
27
+ * All fields are optional; set only what you need.
28
+ */
29
+ export interface CacheOptions {
30
+ /**
31
+ * Indicates that the response can be cached by any cache.
32
+ * Equivalent to "public" in Cache-Control.
33
+ */
34
+ public?: true;
35
+ /**
36
+ * Indicates that the response is intended for a single user
37
+ * and must not be stored by a shared cache.
38
+ */
39
+ private?: true;
40
+ /**
41
+ * Indicates that the resource will not be updated and,
42
+ * therefore, does not need revalidation.
43
+ */
44
+ immutable?: true;
45
+ /**
46
+ * Indicates that a response must not be stored in any cache.
47
+ */
48
+ noStore?: true;
49
+ /**
50
+ * Indicates that the response cannot be used to satisfy a subsequent request
51
+ * without validation on the origin server.
52
+ */
53
+ noCache?: true;
54
+ /**
55
+ * Indicates that the client must revalidate the response with the origin server
56
+ * before using it again.
57
+ */
58
+ mustRevalidate?: true;
59
+ /**
60
+ * Same as must-revalidate, but specifically for shared caches.
61
+ */
62
+ proxyRevalidate?: true;
63
+ /**
64
+ * The maximum amount of time a resource is considered fresh.
65
+ * e.g. '1week', '30s', '3days'.
66
+ */
67
+ maxAge?: TimeString;
68
+ /**
69
+ * If s-maxage is present in a response, it takes priority over max-age
70
+ * when a shared cache (e.g., CDN) is satisfied.
71
+ */
72
+ sMaxAge?: TimeString;
73
+ /**
74
+ * How long (in seconds) a resource remains fresh (beyond its max-age)
75
+ * while a background revalidation is attempted.
76
+ */
77
+ staleWhileRevalidate?: TimeString;
78
+ /**
79
+ * Allows clients to use stale data when an error is encountered
80
+ * while attempting to revalidate.
81
+ */
82
+ staleIfError?: TimeString;
83
+ }
84
+ /**
85
+ * Condition type for matching in redirects, headers, and rewrites.
86
+ * - 'header': Match if a specific HTTP header key/value is present (or missing).
87
+ * - 'cookie': Match if a specific cookie is present (or missing).
88
+ * - 'host': Match if the incoming host matches a given pattern.
89
+ * - 'query': Match if a query parameter is present (or missing).
90
+ */
91
+ export type ConditionType = 'header' | 'cookie' | 'host' | 'query';
92
+ /**
93
+ * Used to define "has" or "missing" conditions.
94
+ */
95
+ export interface Condition {
96
+ type: ConditionType;
97
+ key: string;
98
+ value?: string;
99
+ }
100
+ /**
101
+ * Transform type specifies the scope of what the transform will apply to.
102
+ * - 'request.query': Transform query parameters in the request
103
+ * - 'request.headers': Transform headers in the request
104
+ * - 'response.headers': Transform headers in the response
105
+ */
106
+ export type TransformType = 'request.query' | 'request.headers' | 'response.headers';
107
+ /**
108
+ * Transform operation type.
109
+ * - 'set': Sets the key and value if missing
110
+ * - 'append': Appends args to the value of the key, and will set if missing
111
+ * - 'delete': Deletes the key entirely if args is not provided; otherwise, it will delete the value of args from the matching key
112
+ */
113
+ export type TransformOp = 'set' | 'append' | 'delete';
114
+ /**
115
+ * Conditional matching properties for transform keys.
116
+ * When the key property is an object, it can contain one or more of these properties.
117
+ */
118
+ export interface TransformKeyConditions {
119
+ /** Check equality on a value */
120
+ eq?: string | number;
121
+ /** Check inequality on a value */
122
+ neq?: string;
123
+ /** Check inclusion in an array of values */
124
+ inc?: string[];
125
+ /** Check non-inclusion in an array of values */
126
+ ninc?: string[];
127
+ /** Check if value starts with a prefix */
128
+ pre?: string;
129
+ /** Check if value ends with a suffix */
130
+ suf?: string;
131
+ /** Check if value is greater than */
132
+ gt?: number;
133
+ /** Check if value is greater than or equal to */
134
+ gte?: number;
135
+ /** Check if value is less than */
136
+ lt?: number;
137
+ /** Check if value is less than or equal to */
138
+ lte?: number;
139
+ }
140
+ /**
141
+ * Transform target specifies what key to target for the transform.
142
+ * The key can be a string (exact match) or an object with conditional matching.
143
+ */
144
+ export interface TransformTarget {
145
+ key: string | TransformKeyConditions;
146
+ }
147
+ /**
148
+ * Transform defines a single transformation operation on request or response data.
149
+ * Supports environment variables (e.g., $BEARER_TOKEN) and path parameters (e.g., $userId).
150
+ */
151
+ export interface Transform {
152
+ /** The scope of what the transform will apply to */
153
+ type: TransformType;
154
+ /** The operation to perform */
155
+ op: TransformOp;
156
+ /** The target key to transform */
157
+ target: TransformTarget;
158
+ /** The value(s) to use for the operation. Can include environment variables ($VAR) and path parameters ($param) */
159
+ args?: string | string[];
160
+ /** List of environment variable names that are used in args (without the $ prefix) */
161
+ env?: string[];
162
+ }
163
+ /**
164
+ * Route defines a routing rule with transforms.
165
+ * This is the newer, more powerful route format that supports transforms.
166
+ *
167
+ * @example
168
+ * {
169
+ * src: "/users/:userId/posts/:postId",
170
+ * transforms: [
171
+ * {
172
+ * type: "request.headers",
173
+ * op: "set",
174
+ * target: { key: "x-user-id" },
175
+ * args: "$userId"
176
+ * },
177
+ * {
178
+ * type: "request.headers",
179
+ * op: "set",
180
+ * target: { key: "authorization" },
181
+ * args: "Bearer $BEARER_TOKEN"
182
+ * }
183
+ * ]
184
+ * }
185
+ */
186
+ export interface Route {
187
+ /** Pattern to match request paths using path-to-regexp syntax */
188
+ src: string;
189
+ /** Optional destination for rewrite/redirect */
190
+ dest?: string;
191
+ /** Array of transforms to apply */
192
+ transforms?: Transform[];
193
+ /** Optional conditions that must be present */
194
+ has?: Condition[];
195
+ /** Optional conditions that must be absent */
196
+ missing?: Condition[];
197
+ /** If true, this is a redirect (status defaults to 308 or specified) */
198
+ redirect?: boolean;
199
+ /** Status code for redirects */
200
+ status?: number;
201
+ /** Headers to set (alternative to using transforms) */
202
+ headers?: Record<string, string>;
203
+ }
204
+ /**
205
+ * Represents a single HTTP header key/value pair.
206
+ */
207
+ export interface Header {
208
+ key: string;
209
+ value: string;
210
+ }
211
+ /**
212
+ * Options for transform operations on headers and query parameters.
213
+ * These are converted internally to Vercel's transforms format.
214
+ */
215
+ export interface TransformOptions {
216
+ /**
217
+ * Headers to set/modify on the incoming request.
218
+ * Use param() for path parameters and runtimeEnv() for environment variables.
219
+ *
220
+ * @example
221
+ * requestHeaders: {
222
+ * 'x-user-id': param('userId'),
223
+ * 'authorization': `Bearer ${runtimeEnv('API_TOKEN')}`
224
+ * }
225
+ */
226
+ requestHeaders?: Record<string, string | string[]>;
227
+ /**
228
+ * Headers to set/modify on the outgoing response.
229
+ * Use param() for path parameters and runtimeEnv() for environment variables.
230
+ *
231
+ * @example
232
+ * responseHeaders: {
233
+ * 'x-post-id': param('postId')
234
+ * }
235
+ */
236
+ responseHeaders?: Record<string, string | string[]>;
237
+ /**
238
+ * Query parameters to set/modify on the request.
239
+ *
240
+ * @example
241
+ * requestQuery: {
242
+ * 'theme': 'dark'
243
+ * }
244
+ */
245
+ requestQuery?: Record<string, string | string[]>;
246
+ }
247
+ /**
248
+ * HeaderRule defines one or more headers to set for requests
249
+ * matching a given source pattern, plus optional "has" / "missing" conditions.
250
+ */
251
+ export interface HeaderRule {
252
+ /**
253
+ * Pattern to match request paths using path-to-regexp syntax.
254
+ * @example
255
+ * "/api/(.*)" // Basic capture group
256
+ * "/blog/:slug" // Named parameter
257
+ * "/feedback/((?!general).*)" // Negative lookahead in a group
258
+ */
259
+ source: string;
260
+ /** An array of key/value pairs to set as headers. */
261
+ headers: Header[];
262
+ /** Optional conditions that must be present. */
263
+ has?: Condition[];
264
+ /** Optional conditions that must be absent. */
265
+ missing?: Condition[];
266
+ }
267
+ /**
268
+ * RedirectRule defines a URL rewrite in which the user is redirected
269
+ * (3xx response) to a destination, with optional conditions.
270
+ */
271
+ export interface RedirectRule {
272
+ /**
273
+ * Pattern to match request paths using path-to-regexp syntax.
274
+ * @example
275
+ * "/api/(.*)" // Basic capture group
276
+ * "/blog/:slug" // Named parameter
277
+ * "/feedback/((?!general).*)" // Negative lookahead in a group
278
+ */
279
+ source: string;
280
+ destination: string;
281
+ /**
282
+ * If true, default status code is 308; if false, 307.
283
+ * Can be overridden by `statusCode`.
284
+ */
285
+ permanent?: boolean;
286
+ /**
287
+ * Allows specifying a custom HTTP status code instead of 307 or 308.
288
+ */
289
+ statusCode?: number;
290
+ has?: Condition[];
291
+ missing?: Condition[];
292
+ }
293
+ /**
294
+ * RewriteRule defines an internal rewrite from the source pattern
295
+ * to the specified destination, without exposing a redirect to the user.
296
+ */
297
+ export interface RewriteRule {
298
+ /**
299
+ * Pattern to match request paths using path-to-regexp syntax.
300
+ * @example
301
+ * "/api/(.*)" // Basic capture group
302
+ * "/blog/:slug" // Named parameter
303
+ * "/feedback/((?!general).*)" // Negative lookahead in a group
304
+ */
305
+ source: string;
306
+ destination: string;
307
+ has?: Condition[];
308
+ missing?: Condition[];
309
+ /** Internal field: transforms generated from requestHeaders/responseHeaders/requestQuery */
310
+ transforms?: Transform[];
311
+ }
312
+ /**
313
+ * CronRule defines a scheduled function invocation on Vercel.
314
+ */
315
+ export interface CronRule {
316
+ /**
317
+ * The URL path to invoke, must start with '/'.
318
+ */
319
+ path: string;
320
+ /**
321
+ * Cron expression string (e.g., '0 0 * * *' for daily midnight).
322
+ */
323
+ schedule: string;
324
+ }
325
+ /**
326
+ * Providers can be used to asynchronously load sets of rules.
327
+ */
328
+ export type RedirectProvider = () => Promise<RedirectRule[]>;
329
+ export type HeaderProvider = () => Promise<HeaderRule[]>;
330
+ export type RewriteProvider = () => Promise<RewriteRule[]>;
331
+ export type CronProvider = () => Promise<CronRule[]>;
332
+ /**
333
+ * The aggregated router configuration, suitable for exporting as
334
+ * a JSON or TypeScript object that can be consumed by Vercel.
335
+ */
336
+ export interface RouterConfig {
337
+ redirects?: RedirectRule[];
338
+ headers?: HeaderRule[];
339
+ rewrites?: RewriteRule[];
340
+ /**
341
+ * Array of routes with transforms support.
342
+ * This is the newer, more powerful routing format.
343
+ * When routes is present, other fields (redirects, headers, rewrites, crons) are excluded.
344
+ */
345
+ routes?: Route[];
346
+ /**
347
+ * When true, Vercel automatically removes file extensions and normalizes
348
+ * certain paths, serving HTML and serverless routes extension-free.
349
+ */
350
+ cleanUrls?: boolean;
351
+ /**
352
+ * When true, routes are normalized to include a trailing slash.
353
+ */
354
+ trailingSlash?: boolean;
355
+ /**
356
+ * Array of cron definitions for scheduled invocations.
357
+ */
358
+ crons?: CronRule[];
359
+ /**
360
+ * Custom build command to run during deployment.
361
+ */
362
+ buildCommand?: string;
363
+ /**
364
+ * Custom install command to run during deployment.
365
+ */
366
+ installCommand?: string;
367
+ }
368
+ /**
369
+ * The main Router class for building a Vercel configuration object in code.
370
+ * Supports synchronous or asynchronous addition of rewrites, redirects, headers,
371
+ * plus convenience methods for crons, caching, and more.
372
+ */
373
+ export declare class Router {
374
+ private redirectRules;
375
+ private headerRules;
376
+ private rewriteRules;
377
+ private routeRules;
378
+ private cronRules;
379
+ private cleanUrlsConfig;
380
+ private trailingSlashConfig;
381
+ private buildCommandConfig;
382
+ private installCommandConfig;
383
+ /**
384
+ * Helper to extract environment variable names from a string or string array.
385
+ * Environment variables are identified by the pattern $VAR_NAME where VAR_NAME
386
+ * is typically uppercase with underscores (e.g., $API_KEY, $BEARER_TOKEN).
387
+ */
388
+ private extractEnvVars;
389
+ /**
390
+ * Internal helper to convert TransformOptions to Transform array
391
+ */
392
+ private transformOptionsToTransforms;
393
+ /**
394
+ * Adds a single rewrite rule (synchronous).
395
+ * Automatically enables rewrite caching by adding the x-vercel-enable-rewrite-caching header.
396
+ *
397
+ * @example
398
+ * // This will automatically enable caching for the rewrite
399
+ * import { createRouter, param, runtimeEnv } from '@vercel/router-sdk';
400
+ * const router = createRouter();
401
+ * router.rewrite('/api/(.*)', 'https://old-on-prem.com/$1')
402
+ *
403
+ * // With transforms
404
+ * router.rewrite('/users/:userId', 'https://api.example.com/users/$1', {
405
+ * requestHeaders: {
406
+ * 'x-user-id': param('userId'),
407
+ * 'authorization': `Bearer ${runtimeEnv('API_TOKEN')}`
408
+ * }
409
+ * });
410
+ */
411
+ rewrite(source: string, destination: string, options?: {
412
+ has?: Condition[];
413
+ missing?: Condition[];
414
+ requestHeaders?: Record<string, string | string[]>;
415
+ responseHeaders?: Record<string, string | string[]>;
416
+ requestQuery?: Record<string, string | string[]>;
417
+ }): this;
418
+ /**
419
+ * Loads rewrite rules asynchronously and appends them.
420
+ * Automatically enables rewrite caching for all loaded rules by adding the x-vercel-enable-rewrite-caching header.
421
+ *
422
+ * @example
423
+ * // This will automatically enable caching for all rewrites
424
+ * await router.rewrites(() => fetchRewriteRulesFromDB());
425
+ */
426
+ rewrites(provider: RewriteProvider): Promise<this>;
427
+ /**
428
+ * Adds a single redirect rule (synchronous).
429
+ * @example
430
+ * router.redirect('/old-path', '/new-path', { permanent: true })
431
+ *
432
+ * // With transforms
433
+ * router.redirect('/users/:userId', '/new-users/$1', {
434
+ * permanent: true,
435
+ * requestHeaders: {
436
+ * 'x-user-id': param('userId')
437
+ * }
438
+ * })
439
+ */
440
+ redirect(source: string, destination: string, options?: {
441
+ permanent?: boolean;
442
+ statusCode?: number;
443
+ has?: Condition[];
444
+ missing?: Condition[];
445
+ requestHeaders?: Record<string, string | string[]>;
446
+ responseHeaders?: Record<string, string | string[]>;
447
+ requestQuery?: Record<string, string | string[]>;
448
+ }): this;
449
+ /**
450
+ * Loads redirect rules asynchronously and appends them.
451
+ */
452
+ redirects(provider: RedirectProvider): Promise<this>;
453
+ /**
454
+ * Adds a single header rule (synchronous).
455
+ * @example
456
+ * router.header('/api/(.*)', [{ key: 'X-Custom', value: 'HelloWorld' }])
457
+ */
458
+ header(source: string, headers: Header[], options?: {
459
+ has?: Condition[];
460
+ missing?: Condition[];
461
+ }): this;
462
+ /**
463
+ * Loads header rules asynchronously and appends them.
464
+ */
465
+ headers(provider: HeaderProvider): Promise<this>;
466
+ /**
467
+ * Adds a typed "Cache-Control" header, leveraging `pretty-cache-header`.
468
+ * This method is purely for convenience, so you can do:
469
+ *
470
+ * router.cacheControl('/my-page', {
471
+ * public: true,
472
+ * maxAge: '1week',
473
+ * staleWhileRevalidate: '1year'
474
+ * });
475
+ */
476
+ cacheControl(source: string, cacheOptions: CacheOptions, options?: {
477
+ has?: Condition[];
478
+ missing?: Condition[];
479
+ }): this;
480
+ /**
481
+ * Adds a route with transforms support.
482
+ * This is the newer, more powerful routing format that supports transforms.
483
+ *
484
+ * @example
485
+ * // Add a route with transforms for path parameters and environment variables
486
+ * router.route({
487
+ * src: '/users/:userId/posts/:postId',
488
+ * dest: 'https://api.example.com/users/$userId/posts/$postId',
489
+ * transforms: [
490
+ * {
491
+ * type: 'request.headers',
492
+ * op: 'set',
493
+ * target: { key: 'x-user-id' },
494
+ * args: '$userId'
495
+ * },
496
+ * {
497
+ * type: 'request.headers',
498
+ * op: 'set',
499
+ * target: { key: 'authorization' },
500
+ * args: 'Bearer $BEARER_TOKEN'
501
+ * }
502
+ * ]
503
+ * });
504
+ */
505
+ route(config: Route): this;
506
+ /**
507
+ * When true, automatically serve HTML files and serverless functions
508
+ * without the .html or .js extension. This is a built-in Vercel feature.
509
+ */
510
+ setCleanUrls(value: boolean): this;
511
+ /**
512
+ * When true, automatically normalize paths to include a trailing slash.
513
+ */
514
+ setTrailingSlash(value: boolean): this;
515
+ /**
516
+ * Sets a custom build command to run during deployment.
517
+ * @example
518
+ * router.setBuildCommand('pnpm run generate-config')
519
+ */
520
+ setBuildCommand(value: string): this;
521
+ /**
522
+ * Sets a custom install command to run during deployment.
523
+ * @example
524
+ * router.setInstallCommand('pnpm install --no-frozen-lockfile')
525
+ */
526
+ setInstallCommand(value: string): this;
527
+ /**
528
+ * Adds a single cron rule (synchronous).
529
+ */
530
+ cron(path: string, schedule: string): this;
531
+ /**
532
+ * Loads cron rules asynchronously and appends them.
533
+ */
534
+ crons(provider: CronProvider): Promise<this>;
535
+ /**
536
+ * Returns the complete router configuration.
537
+ * Typically, you'll export or return this in your build scripts,
538
+ * so that Vercel can pick it up.
539
+ */
540
+ getConfig(): RouterConfig;
541
+ /**
542
+ * Visualizes the routing tree in the order that Vercel applies routes.
543
+ * Returns a formatted string showing the routing hierarchy.
544
+ */
545
+ visualize(): string;
546
+ private validateSourcePattern;
547
+ private validateCronExpression;
548
+ }
549
+ /**
550
+ * A simple factory function for creating a new Router instance.
551
+ * @example
552
+ * import { createRouter } from '@vercel/router-sdk';
553
+ * const router = createRouter();
554
+ */
555
+ export declare function createRouter(): Router;