vite-plugin-vercel 9.0.6 → 10.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs DELETED
@@ -1,829 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var src_exports = {};
32
- __export(src_exports, {
33
- default: () => allPlugins
34
- });
35
- module.exports = __toCommonJS(src_exports);
36
- var import_promises5 = __toESM(require("fs/promises"), 1);
37
- var import_node_path6 = __toESM(require("path"), 1);
38
-
39
- // src/build.ts
40
- var import_promises = __toESM(require("fs/promises"), 1);
41
- var import_node_module = require("module");
42
- var import_node_path2 = __toESM(require("path"), 1);
43
- var import_find_root = require("@manypkg/find-root");
44
- var import_build_utils = require("@vercel/build-utils");
45
- var import_nft = require("@vercel/nft");
46
- var import_esbuild = require("esbuild");
47
- var import_fast_glob = __toESM(require("fast-glob"), 1);
48
- var import_magicast = require("magicast");
49
-
50
- // src/assert.ts
51
- var import_libassert = require("@brillout/libassert");
52
- var libName = "vite-plugin-vercel";
53
- function assert(condition, errorMessage) {
54
- if (condition) {
55
- return;
56
- }
57
- const err = (0, import_libassert.newError)(`[${libName}][Wrong Usage] ${errorMessage}`, 2);
58
- throw err;
59
- }
60
-
61
- // src/schemas/config/vc-config.ts
62
- var import_zod = require("zod");
63
- var vercelOutputEdgeVcConfigSchema = import_zod.z.object({
64
- runtime: import_zod.z.literal("edge"),
65
- entrypoint: import_zod.z.string(),
66
- envVarsInUse: import_zod.z.array(import_zod.z.string()).optional()
67
- }).strict();
68
- var vercelOutputServerlessVcConfigSchema = import_zod.z.object({
69
- runtime: import_zod.z.string(),
70
- handler: import_zod.z.string(),
71
- memory: import_zod.z.number().int().min(128).max(3008).optional(),
72
- maxDuration: import_zod.z.number().int().positive().optional(),
73
- environment: import_zod.z.record(import_zod.z.string()).optional(),
74
- regions: import_zod.z.array(import_zod.z.string()).optional(),
75
- supportsWrapper: import_zod.z.boolean().optional(),
76
- supportsResponseStreaming: import_zod.z.boolean().optional()
77
- }).strict();
78
- var vercelOutputServerlessNodeVcConfigSchema = vercelOutputServerlessVcConfigSchema.extend({
79
- launcherType: import_zod.z.literal("Nodejs"),
80
- shouldAddHelpers: import_zod.z.boolean().optional(),
81
- shouldAddSourcemapSupport: import_zod.z.boolean().optional(),
82
- awsLambdaHandler: import_zod.z.string().optional()
83
- }).strict();
84
- var vercelOutputVcConfigSchema = import_zod.z.union([
85
- vercelOutputEdgeVcConfigSchema,
86
- vercelOutputServerlessVcConfigSchema,
87
- vercelOutputServerlessNodeVcConfigSchema
88
- ]);
89
-
90
- // src/schemas/exports.ts
91
- var import_zod2 = require("zod");
92
- var vercelEndpointExports = import_zod2.z.object({
93
- edge: import_zod2.z.boolean().optional(),
94
- headers: import_zod2.z.record(import_zod2.z.string()).optional(),
95
- streaming: import_zod2.z.boolean().optional(),
96
- isr: import_zod2.z.object({
97
- expiration: import_zod2.z.number().or(import_zod2.z.literal(false))
98
- }).optional()
99
- });
100
-
101
- // src/utils.ts
102
- var import_vite = require("vite");
103
- var import_node_path = __toESM(require("path"), 1);
104
- function getRoot(config) {
105
- return (0, import_vite.normalizePath)(config.root || process.cwd());
106
- }
107
- function getOutput(config, suffix) {
108
- return import_node_path.default.join(
109
- config.vercel?.outDir ? "" : getRoot(config),
110
- config.vercel?.outDir ?? ".vercel/output",
111
- suffix ?? ""
112
- );
113
- }
114
- function getPublic(config) {
115
- return import_node_path.default.join(getRoot(config), config.publicDir || "public");
116
- }
117
- function pathRelativeTo(filePath, config, rel) {
118
- const root = getRoot(config);
119
- return (0, import_vite.normalizePath)(import_node_path.default.relative((0, import_vite.normalizePath)(import_node_path.default.join(root, rel)), filePath));
120
- }
121
-
122
- // src/build.ts
123
- async function getAdditionalEndpoints(resolvedConfig) {
124
- const userEndpoints = [];
125
- if (Array.isArray(resolvedConfig.vercel?.additionalEndpoints)) {
126
- for (const endpoint of resolvedConfig.vercel.additionalEndpoints) {
127
- if (typeof endpoint === "function") {
128
- const res = await endpoint();
129
- if (Array.isArray(res)) {
130
- userEndpoints.push(...res);
131
- } else {
132
- userEndpoints.push(res);
133
- }
134
- } else {
135
- userEndpoints.push(endpoint);
136
- }
137
- }
138
- }
139
- return userEndpoints.map((e) => ({
140
- ...e,
141
- route: e.route ?? true,
142
- // path.resolve removes the trailing slash if any
143
- destination: `${import_node_path2.default.posix.resolve("/", e.destination)}.func`
144
- }));
145
- }
146
- async function getEntries(resolvedConfig) {
147
- const apiEntries = import_fast_glob.default.sync(`${getRoot(resolvedConfig)}/api/**/*.*([a-zA-Z0-9])`).filter((filepath) => !import_node_path2.default.basename(filepath).startsWith("_"));
148
- if (apiEntries.length > 0) {
149
- console.warn(
150
- "@vercel/build is currently force building /api files itself, with no way to disable it. In order to avoid double compilation, you should temporarily rename /api to /_api while using this plugin. /_api functions are compiled under .vercel/output/functions/api/*.func as if they were in /api."
151
- );
152
- }
153
- const otherApiEntries = import_fast_glob.default.sync(`${getRoot(resolvedConfig)}/_api/**/*.*([a-zA-Z0-9])`).filter((filepath) => !import_node_path2.default.basename(filepath).startsWith("_"));
154
- return [...apiEntries, ...otherApiEntries].reduce(
155
- (entryPoints, filePath) => {
156
- const outFilePath = pathRelativeTo(filePath, resolvedConfig, filePath.includes("/_api/") ? "_api" : "api");
157
- const parsed = import_node_path2.default.posix.parse(outFilePath);
158
- entryPoints.push({
159
- source: filePath,
160
- destination: `api/${import_node_path2.default.posix.join(parsed.dir, parsed.name)}.func`,
161
- route: true
162
- });
163
- return entryPoints;
164
- },
165
- await getAdditionalEndpoints(resolvedConfig)
166
- );
167
- }
168
- var edgeWasmPlugin = {
169
- name: "edge-wasm-vercel",
170
- setup(build2) {
171
- build2.onResolve({ filter: /\.wasm/ }, (args) => {
172
- return {
173
- path: args.path.replace(/\.wasm\?module$/i, ".wasm"),
174
- external: true
175
- };
176
- });
177
- }
178
- };
179
- var vercelOgPlugin = (ctx) => {
180
- return {
181
- name: "vercel-og",
182
- setup(build2) {
183
- build2.onResolve({ filter: /@vercel\/og/ }, () => {
184
- ctx.found = true;
185
- return void 0;
186
- });
187
- build2.onLoad({ filter: /@vercel\/og/ }, (args) => {
188
- ctx.index = args.path;
189
- return void 0;
190
- });
191
- }
192
- };
193
- };
194
- var standardBuildOptions = {
195
- bundle: true,
196
- target: "es2022",
197
- format: "esm",
198
- platform: "node",
199
- logLevel: "info",
200
- logOverride: {
201
- "ignored-bare-import": "verbose",
202
- "require-resolve-not-external": "verbose"
203
- },
204
- minify: false,
205
- plugins: [],
206
- define: {
207
- "process.env.NODE_ENV": '"production"',
208
- "import.meta.env.NODE_ENV": '"production"'
209
- }
210
- };
211
- async function buildFn(resolvedConfig, entry, buildOptions) {
212
- assert(
213
- entry.destination.length > 0,
214
- `Endpoint ${typeof entry.source === "string" ? entry.source : "-"} does not have build destination`
215
- );
216
- const options = Object.assign({}, standardBuildOptions);
217
- if (buildOptions) {
218
- Object.assign(options, buildOptions);
219
- }
220
- const filename = entry.edge || options.format === "cjs" ? "index.js" : "index.mjs";
221
- const outfile = import_node_path2.default.join(getOutput(resolvedConfig, "functions"), entry.destination, filename);
222
- Object.assign(options, { outfile });
223
- if (!options.stdin) {
224
- if (typeof entry.source === "string") {
225
- options.entryPoints = [entry.source];
226
- } else {
227
- assert(typeof entry.source === "object", "`{ source }` must be a string or an object");
228
- assert(typeof entry.source.contents === "string", "`{ contents }` must be a string");
229
- options.stdin = entry.source;
230
- }
231
- }
232
- if (entry.edge) {
233
- options.platform = void 0;
234
- options.external = [...import_node_module.builtinModules, ...import_node_module.builtinModules.map((m) => `node:${m}`)];
235
- options.conditions = ["edge-light", "worker", "browser", "module", "import", "require"];
236
- options.plugins?.push(edgeWasmPlugin);
237
- options.format = "esm";
238
- } else if (options.format === "esm") {
239
- options.banner = {
240
- js: `import { createRequire as VPV_createRequire } from "node:module";
241
- import { fileURLToPath as VPV_fileURLToPath } from "node:url";
242
- import { dirname as VPV_dirname } from "node:path";
243
- const require = VPV_createRequire(import.meta.url);
244
- const __filename = VPV_fileURLToPath(import.meta.url);
245
- const __dirname = VPV_dirname(__filename);
246
- `
247
- };
248
- }
249
- const ctx = { found: false, index: "" };
250
- options.plugins?.push(vercelOgPlugin(ctx));
251
- const output = await (0, import_esbuild.build)(options);
252
- if (typeof entry.source === "string") {
253
- let base = resolvedConfig.root;
254
- try {
255
- const dir = await (0, import_find_root.findRoot)(resolvedConfig.root);
256
- base = dir.rootDir;
257
- } catch (e) {
258
- }
259
- const { fileList, reasons } = await (0, import_nft.nodeFileTrace)([entry.source], {
260
- base,
261
- processCwd: resolvedConfig.root,
262
- mixedModules: true,
263
- ignore: [
264
- "**/node_modules/react{,-dom,-dom-server-turbopack}/**/*.development.js",
265
- "**/*.d.ts",
266
- "**/*.map",
267
- "**/node_modules/webpack5/**/*"
268
- ],
269
- async readFile(filepath) {
270
- if (filepath.endsWith(".ts") || filepath.endsWith(".tsx")) {
271
- const result = await (0, import_esbuild.build)({
272
- ...standardBuildOptions,
273
- entryPoints: [entry.source],
274
- bundle: false,
275
- write: false
276
- });
277
- return result.outputFiles[0].text;
278
- }
279
- return import_promises.default.readFile(filepath, "utf-8");
280
- }
281
- });
282
- for (const file of fileList) {
283
- if (reasons.has(file) && reasons.get(file)?.type.includes("asset") && !file.endsWith(".js") && !file.endsWith(".cjs") && !file.endsWith(".mjs") && !file.endsWith("package.json")) {
284
- await (0, import_promises.copyFile)(
285
- import_node_path2.default.join(base, file),
286
- import_node_path2.default.join(getOutput(resolvedConfig, "functions"), entry.destination, (0, import_node_path2.basename)(file))
287
- );
288
- }
289
- }
290
- }
291
- await writeVcConfig(resolvedConfig, entry.destination, filename, {
292
- edge: Boolean(entry.edge),
293
- streaming: entry.streaming
294
- });
295
- return output;
296
- }
297
- async function writeVcConfig(resolvedConfig, destination, filename, options) {
298
- const vcConfig = import_node_path2.default.join(getOutput(resolvedConfig, "functions"), destination, ".vc-config.json");
299
- const nodeVersion = await (0, import_build_utils.getNodeVersion)(getOutput(resolvedConfig));
300
- await import_promises.default.writeFile(
301
- vcConfig,
302
- JSON.stringify(
303
- vercelOutputVcConfigSchema.parse(
304
- options.edge ? {
305
- runtime: "edge",
306
- entrypoint: filename
307
- } : {
308
- runtime: nodeVersion.runtime,
309
- handler: filename,
310
- maxDuration: resolvedConfig.vercel?.defaultMaxDuration,
311
- launcherType: "Nodejs",
312
- shouldAddHelpers: true,
313
- supportsResponseStreaming: options.streaming ?? resolvedConfig.vercel?.defaultSupportsResponseStreaming
314
- }
315
- ),
316
- void 0,
317
- 2
318
- ),
319
- "utf-8"
320
- );
321
- }
322
- function getSourceAndDestination(destination) {
323
- if (destination.startsWith("api/")) {
324
- return import_node_path2.default.posix.resolve("/", destination);
325
- }
326
- return import_node_path2.default.posix.resolve("/", destination, ":match*");
327
- }
328
- var RE_BRACKETS = /^\[([^/]+)\]$/gm;
329
- function replaceBrackets(source) {
330
- return source.split("/").map((segment) => segment.replace(RE_BRACKETS, ":$1")).join("/");
331
- }
332
- function isPrimitive(test) {
333
- return test !== Object(test);
334
- }
335
- function _eval(code) {
336
- const func = new Function(`{ return function(){ return ${code} } };`);
337
- return func.call(null).call(null);
338
- }
339
- function evalExport(exp) {
340
- if (!exp) return;
341
- const code = isPrimitive(exp) ? exp : (0, import_magicast.generateCode)(exp).code;
342
- return _eval(code);
343
- }
344
- async function extractExports(filepath) {
345
- try {
346
- const mod = await (0, import_magicast.loadFile)(filepath);
347
- const subject = {
348
- edge: evalExport(mod.exports.edge),
349
- headers: evalExport(mod.exports.headers),
350
- streaming: evalExport(mod.exports.streaming),
351
- isr: evalExport(mod.exports.isr)
352
- };
353
- return vercelEndpointExports.parse(subject);
354
- } catch (e) {
355
- console.warn(`Warning: failed to read exports of '${filepath}'`, e);
356
- }
357
- }
358
- async function extractHeaders(resolvedConfig) {
359
- let headers = [];
360
- if (typeof resolvedConfig.vercel?.headers === "function") {
361
- headers = await resolvedConfig.vercel.headers();
362
- } else if (Array.isArray(resolvedConfig.vercel?.headers)) {
363
- headers = resolvedConfig.vercel.headers;
364
- }
365
- return headers;
366
- }
367
- async function buildEndpoints(resolvedConfig) {
368
- const entries = await getEntries(resolvedConfig);
369
- const headers = await extractHeaders(resolvedConfig);
370
- for (const entry of entries) {
371
- if (typeof entry.source === "string") {
372
- const exports2 = await extractExports(entry.source);
373
- if (exports2) {
374
- if (entry.headers || exports2.headers) {
375
- entry.headers = {
376
- ...exports2.headers,
377
- ...entry.headers
378
- };
379
- }
380
- if (entry.edge !== void 0 && exports2.edge !== void 0) {
381
- throw new Error(
382
- `edge configuration should be defined either in the endpoint itself or through Vite config, not both ('${entry.source}')`
383
- );
384
- }
385
- if (exports2.edge !== void 0) {
386
- entry.edge = exports2.edge;
387
- }
388
- if (entry.isr !== void 0 && exports2.isr !== void 0) {
389
- throw new Error(
390
- `isr configuration should be defined either in the endpoint itself or through Vite config, not both ('${entry.source}')`
391
- );
392
- }
393
- if ((entry.isr !== void 0 || exports2.isr !== void 0) && (entry.edge !== void 0 || exports2.edge !== void 0)) {
394
- throw new Error(`isr cannot be enabled for edge functions ('${entry.source}')`);
395
- }
396
- if (exports2.isr) {
397
- entry.isr = exports2.isr;
398
- }
399
- if (typeof exports2.streaming === "boolean") {
400
- entry.streaming = exports2.streaming;
401
- }
402
- }
403
- }
404
- await buildFn(resolvedConfig, entry, entry.buildOptions);
405
- }
406
- const isrEntries = entries.filter((e) => e.isr).map((e) => [e.destination.replace(/\.func$/, ""), { expiration: e.isr?.expiration }]);
407
- return {
408
- rewrites: entries.filter((e) => {
409
- if (e.addRoute === void 0 && e.route !== void 0) {
410
- return e.route !== false;
411
- }
412
- if (e.addRoute !== void 0 && e.route === void 0) {
413
- return e.addRoute !== false;
414
- }
415
- if (e.addRoute !== void 0 && e.route !== void 0) {
416
- throw new Error("Cannot use both `route` and `addRoute` in `additionalEndpoints`");
417
- }
418
- return true;
419
- }).map((e) => {
420
- const destination = e.destination.replace(/\.func$/, "");
421
- if (typeof e.route === "string") {
422
- return {
423
- source: `(${e.route})`,
424
- destination: `${destination}/?__original_path=$1`
425
- };
426
- }
427
- return {
428
- source: replaceBrackets(getSourceAndDestination(destination)),
429
- destination: getSourceAndDestination(destination)
430
- };
431
- }),
432
- isr: Object.fromEntries(isrEntries),
433
- headers: [
434
- ...entries.filter((e) => e.headers).map((e) => ({
435
- source: `/${e.destination.replace(/\.func$/, "")}`,
436
- headers: Object.entries(e.headers ?? {}).map(([key, value]) => ({
437
- key,
438
- value
439
- }))
440
- })),
441
- ...headers
442
- ]
443
- };
444
- }
445
-
446
- // src/config.ts
447
- var import_node_path3 = __toESM(require("path"), 1);
448
-
449
- // src/schemas/config/config.ts
450
- var import_zod3 = require("zod");
451
- var HasOrMissing = import_zod3.z.array(
452
- import_zod3.z.union([
453
- import_zod3.z.object({
454
- type: import_zod3.z.literal("host"),
455
- value: import_zod3.z.string()
456
- }).strict(),
457
- import_zod3.z.object({
458
- type: import_zod3.z.literal("header"),
459
- key: import_zod3.z.string(),
460
- value: import_zod3.z.string().optional()
461
- }).strict(),
462
- import_zod3.z.object({
463
- type: import_zod3.z.literal("cookie"),
464
- key: import_zod3.z.string(),
465
- value: import_zod3.z.string().optional()
466
- }).strict(),
467
- import_zod3.z.object({
468
- type: import_zod3.z.literal("query"),
469
- key: import_zod3.z.string(),
470
- value: import_zod3.z.string().optional()
471
- }).strict()
472
- ])
473
- ).optional();
474
- var vercelOutputConfigSchema = import_zod3.z.object({
475
- version: import_zod3.z.literal(3),
476
- routes: import_zod3.z.array(
477
- import_zod3.z.union([
478
- import_zod3.z.object({
479
- src: import_zod3.z.string(),
480
- dest: import_zod3.z.string().optional(),
481
- headers: import_zod3.z.record(import_zod3.z.string()).optional(),
482
- methods: import_zod3.z.array(import_zod3.z.string()).optional(),
483
- status: import_zod3.z.number().int().positive().optional(),
484
- continue: import_zod3.z.boolean().optional(),
485
- check: import_zod3.z.boolean().optional(),
486
- missing: HasOrMissing,
487
- has: HasOrMissing,
488
- locale: import_zod3.z.object({
489
- redirect: import_zod3.z.record(import_zod3.z.string()).optional(),
490
- cookie: import_zod3.z.string().optional()
491
- }).strict().optional(),
492
- middlewarePath: import_zod3.z.string().optional()
493
- }).strict(),
494
- import_zod3.z.object({
495
- handle: import_zod3.z.union([
496
- import_zod3.z.literal("rewrite"),
497
- import_zod3.z.literal("filesystem"),
498
- import_zod3.z.literal("resource"),
499
- import_zod3.z.literal("miss"),
500
- import_zod3.z.literal("hit"),
501
- import_zod3.z.literal("error")
502
- ]),
503
- src: import_zod3.z.string().optional(),
504
- dest: import_zod3.z.string().optional(),
505
- status: import_zod3.z.number().optional()
506
- }).strict()
507
- ])
508
- ).optional(),
509
- images: import_zod3.z.object({
510
- sizes: import_zod3.z.tuple([import_zod3.z.number().int().positive(), import_zod3.z.number().int().positive()]),
511
- domains: import_zod3.z.array(import_zod3.z.string()).nonempty().optional(),
512
- minimumCacheTTL: import_zod3.z.number().int().positive().optional(),
513
- formats: import_zod3.z.union([import_zod3.z.literal("image/avif"), import_zod3.z.literal("image/webp")]).array().nonempty().optional(),
514
- dangerouslyAllowSVG: import_zod3.z.boolean().optional(),
515
- contentSecurityPolicy: import_zod3.z.string().optional()
516
- }).strict().optional(),
517
- wildcard: import_zod3.z.array(
518
- import_zod3.z.object({
519
- domain: import_zod3.z.string(),
520
- value: import_zod3.z.string()
521
- }).strict()
522
- ).optional(),
523
- overrides: import_zod3.z.record(
524
- import_zod3.z.object({
525
- path: import_zod3.z.string().optional(),
526
- contentType: import_zod3.z.string().optional()
527
- }).strict()
528
- ).optional(),
529
- cache: import_zod3.z.array(import_zod3.z.string()).optional()
530
- }).strict();
531
-
532
- // src/config.ts
533
- var import_promises2 = __toESM(require("fs/promises"), 1);
534
- var import_routing_utils = require("@vercel/routing-utils");
535
- function reorderEnforce(arr) {
536
- return [
537
- ...arr.filter((r) => r.enforce === "pre"),
538
- ...arr.filter((r) => !r.enforce),
539
- ...arr.filter((r) => r.enforce === "post")
540
- ];
541
- }
542
- function getConfig(resolvedConfig, rewrites, overrides, headers) {
543
- const _rewrites = [
544
- // User provided config always comes first
545
- ...resolvedConfig.vercel?.rewrites ?? [],
546
- ...rewrites ?? []
547
- ];
548
- const _enforcedRewrites = reorderEnforce(_rewrites).map((r) => {
549
- r.source = r.source.replaceAll(/:\[(\.\.\.)(.*)\]/g, ":$2*");
550
- r.source = r.source.replaceAll(/:(\.\.\.)(.*)/g, ":$2+");
551
- return r;
552
- });
553
- const { routes, error } = (0, import_routing_utils.getTransformedRoutes)({
554
- cleanUrls: resolvedConfig.vercel?.cleanUrls ?? true,
555
- trailingSlash: resolvedConfig.vercel?.trailingSlash,
556
- rewrites: _enforcedRewrites,
557
- redirects: resolvedConfig.vercel?.redirects ? reorderEnforce(resolvedConfig.vercel?.redirects) : void 0,
558
- headers
559
- });
560
- if (error) {
561
- throw error;
562
- }
563
- if (resolvedConfig.vercel?.config?.routes && resolvedConfig.vercel.config.routes.length > 0 && !resolvedConfig.vercel.config.routes.every((r) => "continue" in r && r.continue)) {
564
- console.warn(
565
- 'Did you forget to add `"continue": true` to your routes? See https://vercel.com/docs/build-output-api/v3/configuration#source-route\nIf not, it is discouraged to use `vercel.config.routes` to override routes. Prefer using `vercel.rewrites` and `vercel.redirects`.'
566
- );
567
- }
568
- let userRoutes = [];
569
- let buildRoutes = [];
570
- if (resolvedConfig.vercel?.config?.routes) {
571
- const norm = (0, import_routing_utils.normalizeRoutes)(resolvedConfig.vercel.config.routes);
572
- if (norm.error) {
573
- throw norm.error;
574
- }
575
- userRoutes = norm.routes ?? [];
576
- }
577
- if (routes) {
578
- const norm = (0, import_routing_utils.normalizeRoutes)(routes);
579
- if (norm.error) {
580
- throw norm.error;
581
- }
582
- buildRoutes = norm.routes ?? [];
583
- }
584
- const cleanRoutes = (0, import_routing_utils.mergeRoutes)({
585
- userRoutes,
586
- builds: [
587
- {
588
- use: "@vercel/node",
589
- entrypoint: "index.js",
590
- routes: buildRoutes
591
- }
592
- ]
593
- });
594
- return vercelOutputConfigSchema.parse({
595
- version: 3,
596
- ...resolvedConfig.vercel?.config,
597
- routes: cleanRoutes,
598
- overrides: {
599
- ...resolvedConfig.vercel?.config?.overrides,
600
- ...overrides
601
- }
602
- });
603
- }
604
- function getConfigDestination(resolvedConfig) {
605
- return import_node_path3.default.join(getOutput(resolvedConfig), "config.json");
606
- }
607
- async function writeConfig(resolvedConfig, rewrites, overrides, headers) {
608
- await import_promises2.default.writeFile(
609
- getConfigDestination(resolvedConfig),
610
- JSON.stringify(getConfig(resolvedConfig, rewrites, overrides, headers), void 0, 2),
611
- "utf-8"
612
- );
613
- }
614
-
615
- // src/helpers.ts
616
- var import_promises3 = __toESM(require("fs/promises"), 1);
617
- var import_node_path4 = __toESM(require("path"), 1);
618
- async function copyDir(src, dest) {
619
- await import_promises3.default.mkdir(dest, { recursive: true });
620
- const entries = await import_promises3.default.readdir(src, { withFileTypes: true });
621
- for (const entry of entries) {
622
- const srcPath = import_node_path4.default.join(src, entry.name);
623
- const destPath = import_node_path4.default.join(dest, entry.name);
624
- entry.isDirectory() ? await copyDir(srcPath, destPath) : await import_promises3.default.copyFile(srcPath, destPath);
625
- }
626
- }
627
-
628
- // src/prerender.ts
629
- var import_node_path5 = __toESM(require("path"), 1);
630
-
631
- // src/schemas/config/prerender-config.ts
632
- var import_zod4 = require("zod");
633
- var vercelOutputPrerenderConfigSchema = import_zod4.z.object({
634
- expiration: import_zod4.z.union([import_zod4.z.number().int().positive(), import_zod4.z.literal(false)]),
635
- group: import_zod4.z.number().int().optional(),
636
- bypassToken: import_zod4.z.string().optional(),
637
- fallback: import_zod4.z.string().optional(),
638
- allowQuery: import_zod4.z.array(import_zod4.z.string()).optional()
639
- }).strict();
640
-
641
- // src/prerender.ts
642
- var import_promises4 = __toESM(require("fs/promises"), 1);
643
- function execPrerender(resolvedConfig) {
644
- const prerender = resolvedConfig.vercel?.prerender;
645
- if (prerender === false) {
646
- return;
647
- }
648
- return prerender?.(resolvedConfig);
649
- }
650
- var group = 1;
651
- async function writePrerenderConfig(resolvedConfig, destination, isr) {
652
- const parsed = import_node_path5.default.parse(destination);
653
- const outfile = import_node_path5.default.join(getOutput(resolvedConfig, "functions"), parsed.dir, `${parsed.name}.prerender-config.json`);
654
- await import_promises4.default.mkdir(import_node_path5.default.join(getOutput(resolvedConfig, "functions"), parsed.dir), { recursive: true });
655
- await import_promises4.default.writeFile(
656
- outfile,
657
- JSON.stringify(
658
- vercelOutputPrerenderConfigSchema.parse({
659
- group: group++,
660
- ...isr
661
- }),
662
- void 0,
663
- 2
664
- ),
665
- "utf-8"
666
- );
667
- }
668
- function getPrerenderSymlinkInfo(resolvedConfig, destination, target) {
669
- const parsed = import_node_path5.default.parse(destination);
670
- const targetParsed = import_node_path5.default.parse(target);
671
- return {
672
- target: import_node_path5.default.join(getOutput(resolvedConfig, "functions"), targetParsed.dir, `${targetParsed.name}.func`),
673
- link: import_node_path5.default.join(getOutput(resolvedConfig, "functions"), parsed.dir, `${parsed.name}.func`)
674
- };
675
- }
676
- async function buildPrerenderConfigs(resolvedConfig, extractedIsr) {
677
- const isr = Object.assign({}, extractedIsr, await getIsrConfig(resolvedConfig));
678
- const entries = Object.entries(isr);
679
- const rewrites = [];
680
- for (const [destination, { symlink, route, ...isr2 }] of entries) {
681
- await writePrerenderConfig(resolvedConfig, destination, isr2);
682
- if (symlink) {
683
- const info = getPrerenderSymlinkInfo(resolvedConfig, destination, symlink);
684
- await copyDir(info.target, info.link);
685
- }
686
- if (route) {
687
- rewrites.push({
688
- source: `(${route})`,
689
- destination: `${destination}/?__original_path=$1`
690
- });
691
- }
692
- }
693
- return rewrites;
694
- }
695
- async function getIsrConfig(resolvedConfig) {
696
- const isr = resolvedConfig.vercel?.isr ?? {};
697
- if (typeof isr === "function") {
698
- return await isr();
699
- }
700
- return isr;
701
- }
702
-
703
- // src/index.ts
704
- function vercelPluginCleanup() {
705
- let resolvedConfig;
706
- return {
707
- apply: "build",
708
- name: "vite-plugin-vercel:cleanup",
709
- enforce: "pre",
710
- configResolved(config) {
711
- resolvedConfig = config;
712
- },
713
- writeBundle: {
714
- order: "pre",
715
- sequential: true,
716
- async handler() {
717
- if (!resolvedConfig.build?.ssr) {
718
- await cleanOutputDirectory(resolvedConfig);
719
- }
720
- }
721
- }
722
- };
723
- }
724
- function vercelPlugin() {
725
- let resolvedConfig;
726
- let vikeFound = false;
727
- return {
728
- apply: "build",
729
- name: "vite-plugin-vercel",
730
- enforce: "post",
731
- configResolved(config) {
732
- resolvedConfig = config;
733
- vikeFound = resolvedConfig.plugins.some((p) => p.name.match("^vite-plugin-ssr:|^vike:"));
734
- if (typeof resolvedConfig.vercel?.distContainsOnlyStatic === "undefined") {
735
- resolvedConfig.vercel ??= {};
736
- resolvedConfig.vercel.distContainsOnlyStatic = !vikeFound;
737
- }
738
- },
739
- writeBundle: {
740
- order: "post",
741
- sequential: true,
742
- async handler() {
743
- if (!resolvedConfig.build?.ssr) {
744
- if (vikeFound) {
745
- return;
746
- }
747
- }
748
- const overrides = await execPrerender(resolvedConfig);
749
- const userOverrides = await computeStaticHtmlOverrides(resolvedConfig);
750
- const { rewrites, isr, headers } = await buildEndpoints(resolvedConfig);
751
- rewrites.push(...await buildPrerenderConfigs(resolvedConfig, isr));
752
- await writeConfig(
753
- resolvedConfig,
754
- rewrites,
755
- {
756
- ...userOverrides,
757
- ...overrides
758
- },
759
- headers
760
- );
761
- await copyDistToStatic(resolvedConfig);
762
- }
763
- }
764
- };
765
- }
766
- async function cleanOutputDirectory(resolvedConfig) {
767
- await import_promises5.default.rm(getOutput(resolvedConfig), {
768
- recursive: true,
769
- force: true
770
- });
771
- await import_promises5.default.mkdir(getOutput(resolvedConfig), { recursive: true });
772
- }
773
- async function copyDistToStatic(resolvedConfig) {
774
- if (resolvedConfig.vercel?.distContainsOnlyStatic) {
775
- await copyDir(resolvedConfig.build.outDir, getOutput(resolvedConfig, "static"));
776
- }
777
- }
778
- async function computeStaticHtmlOverrides(resolvedConfig) {
779
- const staticAbsolutePath = getOutput(resolvedConfig, "static");
780
- const files = await getStaticHtmlFiles(staticAbsolutePath);
781
- const publicDir = getPublic(resolvedConfig);
782
- const publicFiles = await getStaticHtmlFiles(publicDir);
783
- files.push(...publicFiles.map((f) => f.replace(publicDir, staticAbsolutePath)));
784
- return files.reduce(
785
- (acc, curr) => {
786
- const relPath = import_node_path6.default.relative(staticAbsolutePath, curr);
787
- const parsed = import_node_path6.default.parse(relPath);
788
- const pathJoined = import_node_path6.default.join(parsed.dir, parsed.name);
789
- acc[relPath] = {
790
- path: pathJoined
791
- };
792
- return acc;
793
- },
794
- {}
795
- );
796
- }
797
- async function getStaticHtmlFiles(src) {
798
- try {
799
- await import_promises5.default.stat(src);
800
- } catch (e) {
801
- return [];
802
- }
803
- const entries = await import_promises5.default.readdir(src, { withFileTypes: true });
804
- const htmlFiles = [];
805
- for (const entry of entries) {
806
- const srcPath = import_node_path6.default.join(src, entry.name);
807
- entry.isDirectory() ? htmlFiles.push(...await getStaticHtmlFiles(srcPath)) : srcPath.endsWith(".html") ? htmlFiles.push(srcPath) : void 0;
808
- }
809
- return htmlFiles;
810
- }
811
- async function tryImportVpvv(options) {
812
- try {
813
- await import("vike/plugin");
814
- const vpvv = await import("@vite-plugin-vercel/vike");
815
- return vpvv.default(options);
816
- } catch (e) {
817
- try {
818
- await import("vite-plugin-ssr/plugin");
819
- const vpvv = await import("@vite-plugin-vercel/vike");
820
- return vpvv.default(options);
821
- } catch (e2) {
822
- return null;
823
- }
824
- }
825
- }
826
- function allPlugins(options = {}) {
827
- const { smart, ...rest } = options;
828
- return [vercelPluginCleanup(), vercelPlugin(), smart !== false ? tryImportVpvv(rest) : null];
829
- }