vite-plugin-vercel 0.0.2 → 0.0.5

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.js CHANGED
@@ -1,9 +1,7 @@
1
- var __create = Object.create;
2
1
  var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
5
4
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
9
7
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -18,309 +16,238 @@ var __spreadValues = (a, b) => {
18
16
  }
19
17
  return a;
20
18
  };
21
- var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
22
- var __export = (target, all) => {
23
- for (var name in all)
24
- __defProp(target, name, { get: all[name], enumerable: true });
25
- };
26
- var __reExport = (target, module2, copyDefault, desc) => {
27
- if (module2 && typeof module2 === "object" || typeof module2 === "function") {
28
- for (let key of __getOwnPropNames(module2))
29
- if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
30
- __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
31
- }
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __objRest = (source, exclude) => {
21
+ var target = {};
22
+ for (var prop in source)
23
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
+ target[prop] = source[prop];
25
+ if (source != null && __getOwnPropSymbols)
26
+ for (var prop of __getOwnPropSymbols(source)) {
27
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
+ target[prop] = source[prop];
29
+ }
32
30
  return target;
33
31
  };
34
- var __toESM = (module2, isNodeMode) => {
35
- return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", !isNodeMode && module2 && module2.__esModule ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
36
- };
37
- var __toCommonJS = /* @__PURE__ */ ((cache) => {
38
- return (module2, temp) => {
39
- return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp);
40
- };
41
- })(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0);
42
32
 
43
33
  // src/index.ts
44
- var src_exports = {};
45
- __export(src_exports, {
46
- default: () => allPlugins
47
- });
48
- var import_promises3 = __toESM(require("fs/promises"));
34
+ import fs5 from "fs/promises";
49
35
 
50
36
  // src/utils.ts
51
- var import_vite = require("vite");
52
- var import_path = __toESM(require("path"));
53
- var import_promises = __toESM(require("fs/promises"));
37
+ import { normalizePath } from "vite";
38
+ import path from "path";
39
+ import fs from "fs/promises";
54
40
  function getRoot(config) {
55
- return (0, import_vite.normalizePath)(config.root || process.cwd());
41
+ return normalizePath(config.root || process.cwd());
56
42
  }
57
43
  function getOutDir(config, force) {
58
- const p = (0, import_vite.normalizePath)(config.build.outDir);
44
+ const p = normalizePath(config.build.outDir);
59
45
  if (!force)
60
46
  return p;
61
- return import_path.default.join(import_path.default.dirname(p), force);
47
+ return path.join(path.dirname(p), force);
62
48
  }
63
49
  function getOutput(config, suffix) {
64
50
  var _a, _b;
65
- return import_path.default.join(((_a = config.vercel) == null ? void 0 : _a.outDir) ? "" : getRoot(config), ((_b = config.vercel) == null ? void 0 : _b.outDir) ?? ".output", suffix ?? "");
51
+ return path.join(((_a = config.vercel) == null ? void 0 : _a.outDir) ? "" : getRoot(config), ((_b = config.vercel) == null ? void 0 : _b.outDir) ?? ".vercel/output", suffix ?? "");
66
52
  }
67
53
  function pathRelativeToApi(filePath, config) {
68
54
  const root = getRoot(config);
69
- return (0, import_vite.normalizePath)(import_path.default.relative(import_path.default.join(root, "api"), filePath));
55
+ return normalizePath(path.relative(path.join(root, "api"), filePath));
70
56
  }
71
57
  async function copyDir(src, dest) {
72
- await import_promises.default.mkdir(dest, { recursive: true });
73
- const entries = await import_promises.default.readdir(src, { withFileTypes: true });
58
+ await fs.mkdir(dest, { recursive: true });
59
+ const entries = await fs.readdir(src, { withFileTypes: true });
74
60
  for (const entry of entries) {
75
- const srcPath = import_path.default.join(src, entry.name);
76
- const destPath = import_path.default.join(dest, entry.name);
77
- entry.isDirectory() ? await copyDir(srcPath, destPath) : await import_promises.default.copyFile(srcPath, destPath);
61
+ const srcPath = path.join(src, entry.name);
62
+ const destPath = path.join(dest, entry.name);
63
+ entry.isDirectory() ? await copyDir(srcPath, destPath) : await fs.copyFile(srcPath, destPath);
78
64
  }
79
65
  }
80
66
 
81
- // src/manifests.ts
82
- var import_path2 = __toESM(require("path"));
67
+ // src/config.ts
68
+ import path2 from "path";
69
+
70
+ // src/schemas/config/config.ts
71
+ import { z } from "zod";
72
+ var HasOrMissing = z.array(z.union([
73
+ z.object({
74
+ type: z.literal("host"),
75
+ value: z.string()
76
+ }).strict(),
77
+ z.object({
78
+ type: z.literal("header"),
79
+ key: z.string(),
80
+ value: z.string().optional()
81
+ }).strict(),
82
+ z.object({
83
+ type: z.literal("cookie"),
84
+ key: z.string(),
85
+ value: z.string().optional()
86
+ }).strict(),
87
+ z.object({
88
+ type: z.literal("query"),
89
+ key: z.string(),
90
+ value: z.string().optional()
91
+ }).strict()
92
+ ])).optional();
93
+ var vercelOutputConfigSchema = z.object({
94
+ version: z.literal(3),
95
+ routes: z.array(z.union([
96
+ z.object({
97
+ src: z.string(),
98
+ dest: z.string().optional(),
99
+ headers: z.record(z.string()).optional(),
100
+ methods: z.array(z.string()).optional(),
101
+ status: z.number().int().positive().optional(),
102
+ continue: z.boolean().optional(),
103
+ check: z.boolean().optional(),
104
+ missing: HasOrMissing,
105
+ has: HasOrMissing,
106
+ locale: z.object({
107
+ redirect: z.record(z.string()).optional(),
108
+ cookie: z.string().optional()
109
+ }).strict().optional(),
110
+ middlewarePath: z.string().optional()
111
+ }).strict(),
112
+ z.object({
113
+ handle: z.union([
114
+ z.literal("rewrite"),
115
+ z.literal("filesystem"),
116
+ z.literal("resource"),
117
+ z.literal("miss"),
118
+ z.literal("hit"),
119
+ z.literal("error")
120
+ ]),
121
+ src: z.string().optional(),
122
+ dest: z.string().optional(),
123
+ status: z.number().optional()
124
+ }).strict()
125
+ ])).optional(),
126
+ images: z.object({
127
+ sizes: z.tuple([
128
+ z.number().int().positive(),
129
+ z.number().int().positive()
130
+ ]),
131
+ domains: z.array(z.string()).nonempty().optional(),
132
+ minimumCacheTTL: z.number().int().positive().optional(),
133
+ formats: z.union([z.literal("image/avif"), z.literal("image/webp")]).array().nonempty().optional(),
134
+ dangerouslyAllowSVG: z.boolean().optional(),
135
+ contentSecurityPolicy: z.string().optional()
136
+ }).strict().optional(),
137
+ wildcard: z.array(z.object({
138
+ domain: z.string(),
139
+ value: z.string()
140
+ }).strict()).optional(),
141
+ overrides: z.record(z.object({
142
+ path: z.string().optional(),
143
+ contentType: z.string().optional()
144
+ }).strict()).optional(),
145
+ cache: z.array(z.string()).optional()
146
+ }).strict();
147
+
148
+ // src/config.ts
149
+ import fs2 from "fs/promises";
150
+ import { getTransformedRoutes } from "@vercel/routing-utils";
151
+ function getConfig(resolvedConfig, config) {
152
+ var _a, _b, _c, _d, _e;
153
+ const { routes } = getTransformedRoutes({
154
+ nowConfig: {
155
+ cleanUrls: true
156
+ }
157
+ });
158
+ return vercelOutputConfigSchema.parse(__spreadProps(__spreadValues({
159
+ version: 3
160
+ }, (_a = resolvedConfig.vercel) == null ? void 0 : _a.config), {
161
+ routes: [
162
+ ...routes ?? [],
163
+ ...(config == null ? void 0 : config.routes) ?? [],
164
+ ...((_c = (_b = resolvedConfig.vercel) == null ? void 0 : _b.config) == null ? void 0 : _c.routes) ?? []
165
+ ],
166
+ overrides: __spreadValues(__spreadValues({}, (_e = (_d = resolvedConfig.vercel) == null ? void 0 : _d.config) == null ? void 0 : _e.overrides), config == null ? void 0 : config.overrides)
167
+ }));
168
+ }
169
+ function getConfigDestination(resolvedConfig) {
170
+ return path2.join(getOutput(resolvedConfig), "config.json");
171
+ }
172
+ async function writeConfig(resolvedConfig, config) {
173
+ await fs2.writeFile(getConfigDestination(resolvedConfig), JSON.stringify(getConfig(resolvedConfig, config), void 0, 2), "utf-8");
174
+ }
175
+
176
+ // src/build.ts
177
+ import glob from "fast-glob";
178
+ import path3 from "path";
179
+ import { build } from "esbuild";
83
180
 
84
181
  // src/assert.ts
85
- var import_libassert = require("@brillout/libassert");
182
+ import { newError } from "@brillout/libassert";
86
183
  var libName = "vite-plugin-vercel";
87
184
  function assert(condition, errorMessage) {
88
185
  if (condition) {
89
186
  return;
90
187
  }
91
- const err = (0, import_libassert.newError)(`[${libName}][Wrong Usage] ${errorMessage}`, 2);
188
+ const err = newError(`[${libName}][Wrong Usage] ${errorMessage}`, 2);
92
189
  throw err;
93
190
  }
94
191
 
95
- // src/schemas/manifests/routes.ts
96
- var myzod = __toESM(require("myzod"));
97
- function record(schema) {
98
- return myzod.object({
99
- [myzod.keySignature]: schema
100
- });
101
- }
102
- var routesManifestRedirectSchema = myzod.object({
103
- source: myzod.string(),
104
- destination: myzod.string(),
105
- statusCode: myzod.literals(301, 302, 307, 308),
106
- regex: myzod.string()
107
- });
108
- var routesManifestHeaderSchema = myzod.object({
109
- source: myzod.string(),
110
- headers: myzod.array(myzod.object({
111
- key: myzod.string(),
112
- value: myzod.string()
113
- })),
114
- regex: myzod.string()
115
- });
116
- var routesManifestRewriteSchema = myzod.object({
117
- source: myzod.string(),
118
- has: myzod.array(myzod.object({
119
- key: myzod.string(),
120
- value: myzod.string(),
121
- type: myzod.literals("header", "cookie", "host", "query")
122
- })).optional(),
123
- destination: myzod.string(),
124
- regex: myzod.string()
125
- });
126
- var routesManifestDynamicRouteSchema = myzod.object({
127
- page: myzod.string(),
128
- regex: myzod.string(),
129
- routeKeys: record(myzod.string()).optional(),
130
- namedRegex: myzod.string().optional()
131
- });
132
- var routesManifestSchema = myzod.object({
133
- version: myzod.literal(3),
134
- basePath: myzod.string().pattern(/^\/.*/),
135
- pages404: myzod.boolean(),
136
- redirects: myzod.array(routesManifestRedirectSchema).optional(),
137
- headers: myzod.array(routesManifestHeaderSchema).optional(),
138
- rewrites: myzod.array(routesManifestRewriteSchema).optional(),
139
- dynamicRoutes: myzod.array(routesManifestDynamicRouteSchema).optional()
140
- });
141
-
142
- // src/schemas/manifests/functions.ts
143
- var myzod2 = __toESM(require("myzod"));
144
- function record2(schema) {
145
- return myzod2.object({
146
- [myzod2.keySignature]: schema
147
- });
148
- }
149
- var functionsManifestSchemaPage = myzod2.object({
150
- runtime: myzod2.string().optional(),
151
- handler: myzod2.string().optional(),
152
- regions: myzod2.array(myzod2.string()).optional(),
153
- maxDuration: myzod2.number().min(1).max(900).optional(),
154
- memory: myzod2.number().min(128).max(3008).optional()
155
- });
156
- var functionsManifestSchemaPageWeb = myzod2.omit(functionsManifestSchemaPage, ["runtime"]).and(myzod2.object({
157
- runtime: myzod2.literal("web"),
158
- env: myzod2.array(myzod2.string()),
159
- files: myzod2.array(myzod2.string()),
160
- name: myzod2.string(),
161
- page: myzod2.string(),
162
- regexp: myzod2.string(),
163
- sortingIndex: myzod2.number()
164
- }));
165
- var functionsManifestSchema = myzod2.object({
166
- version: myzod2.literal(1),
167
- pages: myzod2.object({
168
- "_middleware.js": functionsManifestSchemaPageWeb.optional()
169
- }).and(record2(myzod2.intersection(myzod2.partial(myzod2.omit(functionsManifestSchemaPageWeb, ["runtime"])), functionsManifestSchemaPage)))
170
- });
171
-
172
- // src/schemas/manifests/prerender.ts
173
- var myzod3 = __toESM(require("myzod"));
174
- function record3(schema) {
175
- return myzod3.object({
176
- [myzod3.keySignature]: schema
177
- });
178
- }
179
- var prerenderManifestSchemaRoute = myzod3.object({
180
- initialRevalidateSeconds: myzod3.number(),
181
- srcRoute: myzod3.string(),
182
- dataRoute: myzod3.string()
183
- });
184
- var prerenderManifestSchemaDynamicRoute = myzod3.object({
185
- routeRegex: myzod3.string(),
186
- fallback: myzod3.string().or(myzod3.null()),
187
- dataRoute: myzod3.string(),
188
- dataRouteRegex: myzod3.string()
189
- });
190
- var prerenderManifestSchema = myzod3.object({
191
- version: myzod3.literal(3),
192
- routes: record3(prerenderManifestSchemaRoute),
193
- dynamicRoutes: record3(prerenderManifestSchemaDynamicRoute),
194
- preview: myzod3.object({
195
- previewModeId: myzod3.string().or(myzod3.null())
196
- })
197
- });
198
-
199
- // src/manifests.ts
200
- function getPrerenderManifest(resolvedConfig, isrPages) {
201
- var _a, _b;
202
- const prerenderManifestDefault = (_a = resolvedConfig.vercel) == null ? void 0 : _a.prerenderManifest;
203
- const routes = Object.entries((isrPages == null ? void 0 : isrPages.routes) ?? {}).reduce((acc, [key, val]) => {
204
- var _a2, _b2, _c, _d, _e, _f, _g;
205
- const srcRoute = (val == null ? void 0 : val.srcRoute) ?? ((_b2 = (_a2 = prerenderManifestDefault == null ? void 0 : prerenderManifestDefault.routes) == null ? void 0 : _a2[key]) == null ? void 0 : _b2.srcRoute);
206
- assert(typeof srcRoute === "string", `\`[prerender-manifest] { srcRoute }\` is required for route ${key}`);
207
- acc[key === "/" ? "/index" : key] = {
208
- initialRevalidateSeconds: (val == null ? void 0 : val.initialRevalidateSeconds) ?? ((_d = (_c = prerenderManifestDefault == null ? void 0 : prerenderManifestDefault.routes) == null ? void 0 : _c[key]) == null ? void 0 : _d.initialRevalidateSeconds) ?? ((_e = resolvedConfig.vercel) == null ? void 0 : _e.initialRevalidateSeconds) ?? 86400,
209
- srcRoute,
210
- dataRoute: (val == null ? void 0 : val.dataRoute) ?? ((_g = (_f = prerenderManifestDefault == null ? void 0 : prerenderManifestDefault.routes) == null ? void 0 : _f[key]) == null ? void 0 : _g.dataRoute) ?? ""
211
- };
212
- return acc;
213
- }, {});
214
- const uniqueRoutes = Array.from(new Set(Object.values(routes).map((r) => r.srcRoute)));
215
- const dynamicRoutes = uniqueRoutes.reduce((acc, cur) => {
216
- var _a2, _b2, _c, _d, _e, _f;
217
- acc[cur] = {
218
- routeRegex: "^" + cur + "$",
219
- dataRoute: ((_b2 = (_a2 = prerenderManifestDefault == null ? void 0 : prerenderManifestDefault.dynamicRoutes) == null ? void 0 : _a2[cur]) == null ? void 0 : _b2.dataRoute) ?? "",
220
- fallback: ((_d = (_c = prerenderManifestDefault == null ? void 0 : prerenderManifestDefault.dynamicRoutes) == null ? void 0 : _c[cur]) == null ? void 0 : _d.fallback) ?? null,
221
- dataRouteRegex: ((_f = (_e = prerenderManifestDefault == null ? void 0 : prerenderManifestDefault.dynamicRoutes) == null ? void 0 : _e[cur]) == null ? void 0 : _f.dataRouteRegex) ?? ""
222
- };
223
- return acc;
224
- }, {});
225
- return prerenderManifestSchema.parse({
226
- version: 3,
227
- routes,
228
- dynamicRoutes,
229
- preview: {
230
- previewModeId: ((_b = prerenderManifestDefault == null ? void 0 : prerenderManifestDefault.preview) == null ? void 0 : _b.previewModeId) ?? null
231
- }
232
- }, {
233
- collectErrors: true
234
- });
235
- }
236
- function getPrerenderManifestDestination(resolvedConfig) {
237
- return import_path2.default.join(getOutput(resolvedConfig), "prerender-manifest.json");
238
- }
239
- function getRoutesManifest(resolvedConfig, ssr) {
240
- var _a;
241
- const routesManifest = (_a = resolvedConfig.vercel) == null ? void 0 : _a.routesManifest;
242
- const allRewrites = [
243
- ...(ssr == null ? void 0 : ssr.rewrites) ?? [],
244
- ...(routesManifest == null ? void 0 : routesManifest.rewrites) ?? []
245
- ];
246
- const allDynamicRoutes = [
247
- ...(ssr == null ? void 0 : ssr.dynamicRoutes) ?? [],
248
- ...(routesManifest == null ? void 0 : routesManifest.dynamicRoutes) ?? []
249
- ];
250
- return routesManifestSchema.parse({
251
- version: 3,
252
- basePath: (routesManifest == null ? void 0 : routesManifest.basePath) ?? "/",
253
- pages404: (routesManifest == null ? void 0 : routesManifest.pages404) ?? true,
254
- dynamicRoutes: allDynamicRoutes.length > 0 ? allDynamicRoutes : void 0,
255
- rewrites: allRewrites.length > 0 ? allRewrites : void 0,
256
- redirects: routesManifest == null ? void 0 : routesManifest.redirects,
257
- headers: routesManifest == null ? void 0 : routesManifest.headers
258
- }, {
259
- collectErrors: true
260
- });
261
- }
262
- function getRoutesManifestDestination(resolvedConfig) {
263
- return import_path2.default.join(getOutput(resolvedConfig), "routes-manifest.json");
264
- }
265
- function getFunctionsManifest(pages) {
266
- return functionsManifestSchema.parse({
267
- version: 1,
268
- pages
269
- }, {
270
- collectErrors: true
271
- });
272
- }
273
- function getFunctionsManifestDestination(resolvedConfig) {
274
- return import_path2.default.join(getOutput(resolvedConfig), "functions-manifest.json");
275
- }
192
+ // src/schemas/config/vc-config.ts
193
+ import { z as z2 } from "zod";
194
+ var vercelOutputEdgeVcConfigSchema = z2.object({
195
+ runtime: z2.literal("edge"),
196
+ entrypoint: z2.string(),
197
+ envVarsInUse: z2.array(z2.string()).optional()
198
+ }).strict();
199
+ var vercelOutputServerlessVcConfigSchema = z2.object({
200
+ runtime: z2.string(),
201
+ handler: z2.string(),
202
+ memory: z2.number().int().min(128).max(3008).optional(),
203
+ maxDuration: z2.number().int().positive().optional(),
204
+ environment: z2.record(z2.string()).optional(),
205
+ regions: z2.array(z2.string()).optional()
206
+ }).strict();
207
+ var vercelOutputServerlessNodeVcConfigSchema = vercelOutputServerlessVcConfigSchema.extend({
208
+ launcherType: z2.literal("Nodejs"),
209
+ shouldAddHelpers: z2.boolean().optional(),
210
+ shouldAddSourcemapSupport: z2.boolean().optional(),
211
+ awsLambdaHandler: z2.string().optional()
212
+ }).strict();
213
+ var vercelOutputVcConfigSchema = z2.union([
214
+ vercelOutputEdgeVcConfigSchema,
215
+ vercelOutputServerlessVcConfigSchema,
216
+ vercelOutputServerlessNodeVcConfigSchema
217
+ ]);
276
218
 
277
219
  // src/build.ts
278
- var import_fast_glob = __toESM(require("fast-glob"));
279
- var import_path3 = __toESM(require("path"));
280
- var import_esbuild = require("esbuild");
281
- var import_promises2 = __toESM(require("fs/promises"));
282
- function getPagesEndpoints(resolvedConfig) {
220
+ import fs3 from "fs/promises";
221
+ function getAdditionalEndpoints(resolvedConfig) {
283
222
  var _a;
284
- const apiEndpoints = (((_a = resolvedConfig.vercel) == null ? void 0 : _a.pagesEndpoints) ?? []).map((p) => import_path3.default.isAbsolute(p) ? p : import_path3.default.resolve(getRoot(resolvedConfig), p));
285
- return new Set(apiEndpoints);
223
+ return (((_a = resolvedConfig.vercel) == null ? void 0 : _a.additionalEndpoints) ?? []).map((e) => __spreadProps(__spreadValues({}, e), {
224
+ destination: e.destination + ".func"
225
+ }));
286
226
  }
287
- function getApiEntries(resolvedConfig) {
288
- var _a;
289
- const pagesEndpoints = getPagesEndpoints(resolvedConfig);
290
- const apiEntries = import_fast_glob.default.sync(`${getRoot(resolvedConfig)}/api/**/*.*([a-zA-Z0-9])`).filter((filepath) => !import_path3.default.basename(filepath).startsWith("_"));
227
+ function getEntries(resolvedConfig) {
228
+ const apiEntries = glob.sync(`${getRoot(resolvedConfig)}/api/**/*.*([a-zA-Z0-9])`).filter((filepath) => !path3.basename(filepath).startsWith("_"));
291
229
  return apiEntries.reduce((entryPoints, filePath) => {
292
230
  const outFilePath = pathRelativeToApi(filePath, resolvedConfig);
293
- const parsed = import_path3.default.parse(outFilePath);
294
- const alsoPage = pagesEndpoints.has(filePath);
231
+ const parsed = path3.parse(outFilePath);
295
232
  const entry = {
296
233
  source: filePath,
297
- destination: [`api/${import_path3.default.join(parsed.dir, parsed.name)}`]
234
+ destination: `api/${path3.join(parsed.dir, parsed.name)}.func`
298
235
  };
299
- if (alsoPage) {
300
- entry.destination.push(`${import_path3.default.join(parsed.dir, parsed.name)}`);
301
- }
302
236
  entryPoints.push(entry);
303
237
  return entryPoints;
304
- }, ((_a = resolvedConfig.vercel) == null ? void 0 : _a.additionalEndpoints) ?? []);
238
+ }, getAdditionalEndpoints(resolvedConfig));
305
239
  }
306
240
  var standardBuildOptions = {
307
241
  bundle: true,
308
242
  target: "es2020",
309
- format: "cjs",
243
+ format: "esm",
310
244
  platform: "node",
311
245
  logLevel: "info",
312
246
  minify: true
313
247
  };
314
248
  async function buildFn(resolvedConfig, entry, buildOptions) {
315
- var _a, _b, _c, _d;
316
- if (!Array.isArray(entry.destination)) {
317
- entry.destination = [entry.destination];
318
- }
319
249
  assert(entry.destination.length > 0, `Endpoint ${typeof entry.source === "string" ? entry.source : "-"} does not have build destination`);
320
- const [firstDestination, ...remainingDestinations] = entry.destination;
321
- const pages = ((_b = (_a = resolvedConfig.vercel) == null ? void 0 : _a.functionsManifest) == null ? void 0 : _b.pages) ?? {};
322
- const fnManifests = {};
323
- const outfile = import_path3.default.join(getOutput(resolvedConfig, "server/pages"), firstDestination + ".js");
250
+ const outfile = path3.join(getOutput(resolvedConfig, "functions"), entry.destination, "index.js");
324
251
  const options = Object.assign({}, standardBuildOptions, { outfile });
325
252
  if (buildOptions) {
326
253
  Object.assign(options, buildOptions);
@@ -334,31 +261,42 @@ async function buildFn(resolvedConfig, entry, buildOptions) {
334
261
  options.stdin = entry.source;
335
262
  }
336
263
  }
337
- await (0, import_esbuild.build)(options);
338
- fnManifests[firstDestination + ".js"] = __spreadValues({
339
- maxDuration: (_c = resolvedConfig.vercel) == null ? void 0 : _c.defaultMaxDuration
340
- }, pages[firstDestination + ".js"]);
341
- for (const dest of remainingDestinations) {
342
- await import_promises2.default.mkdir(import_path3.default.join(getOutput(resolvedConfig, "server/pages"), import_path3.default.dirname(dest)), {
343
- recursive: true
344
- });
345
- await import_promises2.default.copyFile(outfile, import_path3.default.join(getOutput(resolvedConfig, "server/pages"), dest + ".js"));
346
- fnManifests[dest + ".js"] = __spreadValues({
347
- maxDuration: (_d = resolvedConfig.vercel) == null ? void 0 : _d.defaultMaxDuration
348
- }, pages[dest + ".js"] ?? pages[firstDestination + ".js"]);
349
- }
350
- return fnManifests;
264
+ await build(options);
265
+ await writeVcConfig(resolvedConfig, entry.destination);
266
+ }
267
+ async function writeVcConfig(resolvedConfig, destination) {
268
+ var _a;
269
+ const vcConfig = path3.join(getOutput(resolvedConfig, "functions"), destination, ".vc-config.json");
270
+ await fs3.writeFile(vcConfig, JSON.stringify(vercelOutputVcConfigSchema.parse({
271
+ runtime: "nodejs16.x",
272
+ handler: "index.js",
273
+ maxDuration: (_a = resolvedConfig.vercel) == null ? void 0 : _a.defaultMaxDuration,
274
+ launcherType: "Nodejs",
275
+ shouldAddHelpers: true
276
+ }), void 0, 2), "utf-8");
351
277
  }
352
- async function buildApiEndpoints(resolvedConfig) {
353
- const entries = getApiEntries(resolvedConfig);
354
- const fnManifests = {};
278
+ async function buildEndpoints(resolvedConfig) {
279
+ const entries = getEntries(resolvedConfig);
355
280
  for (const entry of entries) {
356
- Object.assign(fnManifests, await buildFn(resolvedConfig, entry));
281
+ await buildFn(resolvedConfig, entry);
357
282
  }
358
- return fnManifests;
359
283
  }
360
284
 
361
285
  // src/prerender.ts
286
+ import path4 from "path";
287
+
288
+ // src/schemas/config/prerender-config.ts
289
+ import { z as z3 } from "zod";
290
+ var vercelOutputPrerenderConfigSchema = z3.object({
291
+ expiration: z3.union([z3.number().int().positive(), z3.literal(false)]),
292
+ group: z3.number().int().optional(),
293
+ bypassToken: z3.string().optional(),
294
+ fallback: z3.string().optional(),
295
+ allowQuery: z3.array(z3.string()).optional()
296
+ }).strict();
297
+
298
+ // src/prerender.ts
299
+ import fs4 from "fs/promises";
362
300
  function execPrerender(resolvedConfig) {
363
301
  var _a;
364
302
  const prerender = (_a = resolvedConfig.vercel) == null ? void 0 : _a.prerender;
@@ -367,6 +305,51 @@ function execPrerender(resolvedConfig) {
367
305
  }
368
306
  return prerender == null ? void 0 : prerender(resolvedConfig);
369
307
  }
308
+ var group = 1;
309
+ async function writePrerenderConfig(resolvedConfig, destination, isr) {
310
+ const parsed = path4.parse(destination);
311
+ const outfile = path4.join(getOutput(resolvedConfig, "functions"), parsed.dir, parsed.name + ".prerender-config.json");
312
+ await fs4.mkdir(path4.join(getOutput(resolvedConfig, "functions"), parsed.dir), { recursive: true });
313
+ await fs4.writeFile(outfile, JSON.stringify(vercelOutputPrerenderConfigSchema.parse(__spreadValues({
314
+ group: group++
315
+ }, isr)), void 0, 2), "utf-8");
316
+ }
317
+ function getPrerenderSymlinkInfo(resolvedConfig, destination, target) {
318
+ const parsed = path4.parse(destination);
319
+ const targetParsed = path4.parse(target);
320
+ return {
321
+ target: path4.join(getOutput(resolvedConfig, "functions"), targetParsed.dir, targetParsed.name + ".func"),
322
+ link: path4.join(getOutput(resolvedConfig, "functions"), parsed.dir, parsed.name + ".func")
323
+ };
324
+ }
325
+ async function buildPrerenderConfigs(resolvedConfig) {
326
+ const isr = await getIsrConfig(resolvedConfig);
327
+ const entries = Object.entries(isr);
328
+ const rewrites = [];
329
+ for (const _a of entries) {
330
+ const [destination, _b] = _a, _c = _b, { symlink, route } = _c, isr2 = __objRest(_c, ["symlink", "route"]);
331
+ await writePrerenderConfig(resolvedConfig, destination, isr2);
332
+ if (symlink) {
333
+ const info = getPrerenderSymlinkInfo(resolvedConfig, destination, symlink);
334
+ await copyDir(info.target, info.link);
335
+ }
336
+ if (route) {
337
+ rewrites.push({
338
+ src: `(${route})`,
339
+ dest: `${destination}/?__original_path=$1`
340
+ });
341
+ }
342
+ }
343
+ return rewrites;
344
+ }
345
+ async function getIsrConfig(resolvedConfig) {
346
+ var _a;
347
+ const isr = ((_a = resolvedConfig.vercel) == null ? void 0 : _a.isr) ?? {};
348
+ if (typeof isr === "function") {
349
+ return await isr();
350
+ }
351
+ return isr;
352
+ }
370
353
 
371
354
  // src/index.ts
372
355
  function vercelPlugin() {
@@ -374,49 +357,46 @@ function vercelPlugin() {
374
357
  return {
375
358
  apply: "build",
376
359
  name: "vite-plugin-vercel",
360
+ enforce: "post",
377
361
  configResolved(config) {
378
362
  resolvedConfig = config;
379
363
  },
380
364
  async buildStart() {
381
- if (resolvedConfig.build.ssr)
382
- return;
383
- await cleanOutputDirectory(resolvedConfig);
365
+ if (process.env.VERCEL_ENV === "production" && !process.env.ENABLE_FILE_SYSTEM_API) {
366
+ throw new Error("Missing ENABLE_FILE_SYSTEM_API=1 to your environment variables in your project settings");
367
+ }
368
+ if (!resolvedConfig.build.ssr) {
369
+ await cleanOutputDirectory(resolvedConfig);
370
+ } else {
371
+ await copyDistClientToOutputStatic(resolvedConfig);
372
+ }
384
373
  },
385
374
  async writeBundle() {
386
375
  var _a;
387
- if (!((_a = resolvedConfig.build) == null ? void 0 : _a.ssr)) {
388
- await copyDistClientToOutputStatic(resolvedConfig);
376
+ if (!((_a = resolvedConfig.build) == null ? void 0 : _a.ssr))
389
377
  return;
390
- }
391
- const isrPages = await execPrerender(resolvedConfig);
392
- const fnManifests = await buildApiEndpoints(resolvedConfig);
393
- await generateFunctionsManifest(resolvedConfig, fnManifests);
394
- await generateRoutesManifest(resolvedConfig, isrPages == null ? void 0 : isrPages.ssr);
395
- await generatePrerenderManifest(resolvedConfig, isrPages == null ? void 0 : isrPages.isr);
378
+ const overrides = await execPrerender(resolvedConfig);
379
+ await buildEndpoints(resolvedConfig);
380
+ const rewrites = await buildPrerenderConfigs(resolvedConfig);
381
+ await writeConfig(resolvedConfig, {
382
+ routes: [{ handle: "filesystem" }, ...rewrites],
383
+ overrides
384
+ });
396
385
  }
397
386
  };
398
387
  }
399
388
  async function copyDistClientToOutputStatic(resolvedConfig) {
400
- await copyDir(getOutDir(resolvedConfig), getOutput(resolvedConfig, "static"));
389
+ await copyDir(getOutDir(resolvedConfig, "client"), getOutput(resolvedConfig, "static"));
401
390
  }
402
391
  async function cleanOutputDirectory(resolvedConfig) {
403
- await import_promises3.default.rm(getOutput(resolvedConfig), {
392
+ await fs5.rm(getOutput(resolvedConfig), {
404
393
  recursive: true,
405
394
  force: true
406
395
  });
407
396
  }
408
- async function generatePrerenderManifest(resolvedConfig, isrPages) {
409
- await import_promises3.default.writeFile(getPrerenderManifestDestination(resolvedConfig), JSON.stringify(getPrerenderManifest(resolvedConfig, isrPages), void 0, 2));
410
- }
411
- async function generateRoutesManifest(resolvedConfig, ssr) {
412
- await import_promises3.default.writeFile(getRoutesManifestDestination(resolvedConfig), JSON.stringify(getRoutesManifest(resolvedConfig, ssr), void 0, 2));
413
- }
414
- async function generateFunctionsManifest(resolvedConfig, fnManifests) {
415
- await import_promises3.default.writeFile(getFunctionsManifestDestination(resolvedConfig), JSON.stringify(getFunctionsManifest(fnManifests), void 0, 2));
416
- }
417
397
  function allPlugins() {
418
398
  return [vercelPlugin()];
419
399
  }
420
- module.exports = __toCommonJS(src_exports);
421
- // Annotate the CommonJS export names for ESM import in node:
422
- 0 && (module.exports = {});
400
+ export {
401
+ allPlugins as default
402
+ };