@vercel/build-utils 14.17.0 → 14.18.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/schedules.js CHANGED
@@ -25,6 +25,10 @@ __export(schedules_exports, {
25
25
  module.exports = __toCommonJS(schedules_exports);
26
26
  var import_crypto = require("crypto");
27
27
  const FLAT_TARGET_KEYS = ["path", "function", "topic", "entrypoint"];
28
+ const SCHEDULE_REQUEST_METHODS = [
29
+ "GET",
30
+ "POST"
31
+ ];
28
32
  const DEFAULT_NAME_HASH_LENGTH = 12;
29
33
  function defaultScheduleName(type, ref, expression) {
30
34
  return (0, import_crypto.createHash)("sha1").update(`${type}|${ref}|${expression}`).digest("hex").slice(0, DEFAULT_NAME_HASH_LENGTH);
@@ -40,11 +44,11 @@ function isFlatScheduleDefinition(obj) {
40
44
  }
41
45
  function assertNotMixedFields(obj) {
42
46
  const hasLegacy = "expression" in obj || "target" in obj;
43
- const hasFlatSchedule = "schedule" in obj;
47
+ const hasFlatSchedule = "schedule" in obj || "requestMethod" in obj;
44
48
  const flatTargetCount = FLAT_TARGET_KEYS.filter((key) => key in obj).length;
45
49
  if (hasLegacy && (hasFlatSchedule || flatTargetCount > 0)) {
46
50
  throw new Error(
47
- "Schedule cannot mix legacy fields (`expression`, `target`) with flat fields (`schedule`, `path`, `function`, `topic`, `entrypoint`)."
51
+ "Schedule cannot mix legacy fields (`expression`, `target`) with flat fields (`schedule`, `path`, `requestMethod`, `function`, `topic`, `entrypoint`)."
48
52
  );
49
53
  }
50
54
  }
@@ -92,7 +96,7 @@ function parseLegacySchedule(obj) {
92
96
  };
93
97
  }
94
98
  function parseFlatSchedule(obj) {
95
- const { name, schedule, timezone, jitter } = obj;
99
+ const { name, schedule, timezone, jitter, requestMethod } = obj;
96
100
  if (name !== void 0 && typeof name !== "string") {
97
101
  throw new Error("Schedule `name` must be a string.");
98
102
  }
@@ -110,8 +114,17 @@ function parseFlatSchedule(obj) {
110
114
  if (typeof targetValue !== "string") {
111
115
  throw new Error(`Schedule \`${targetKey}\` must be a string.`);
112
116
  }
117
+ if (requestMethod !== void 0) {
118
+ if (targetKey !== "path") {
119
+ throw new Error("Schedule `requestMethod` is only valid with `path`.");
120
+ }
121
+ if (!SCHEDULE_REQUEST_METHODS.includes(requestMethod)) {
122
+ throw new Error("Schedule `requestMethod` must be `GET` or `POST`.");
123
+ }
124
+ }
113
125
  const target = {
114
- [targetKey]: targetValue
126
+ [targetKey]: targetValue,
127
+ ...requestMethod !== void 0 ? { requestMethod } : {}
115
128
  };
116
129
  return {
117
130
  name: name ?? defaultScheduleName(targetKey, targetValue, schedule),
@@ -0,0 +1,11 @@
1
+ import type { StaticBundleExclusions, StaticMount } from './types';
2
+ /** Stub file that keeps an excluded mount directory present in the Lambda. */
3
+ export declare const STATIC_PLACEHOLDER_FILE = ".static-placeholder";
4
+ /**
5
+ * Lambda bundle trimming for promoted mounts: exclude each mount directory
6
+ * (inside `workPath`) from the bundle, and add a placeholder stub plus any
7
+ * `keepFiles` present in the directory so framework startup checks (directory
8
+ * exists, fallback file exists) still pass. Mounts outside `workPath` are
9
+ * skipped.
10
+ */
11
+ export declare function staticBundleExclusions(mounts: StaticMount[], workPath: string, keepFiles: string[]): StaticBundleExclusions;
@@ -0,0 +1,67 @@
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
+ var bundle_exports = {};
30
+ __export(bundle_exports, {
31
+ STATIC_PLACEHOLDER_FILE: () => STATIC_PLACEHOLDER_FILE,
32
+ staticBundleExclusions: () => staticBundleExclusions
33
+ });
34
+ module.exports = __toCommonJS(bundle_exports);
35
+ var import_fs = __toESM(require("fs"));
36
+ var import_path = require("path");
37
+ var import_file_blob = __toESM(require("../file-blob"));
38
+ var import_file_fs_ref = __toESM(require("../file-fs-ref"));
39
+ const STATIC_PLACEHOLDER_FILE = ".static-placeholder";
40
+ function staticBundleExclusions(mounts, workPath, keepFiles) {
41
+ const excludePatterns = [];
42
+ const directoryStubs = {};
43
+ for (const mount of mounts) {
44
+ const relDir = (0, import_path.relative)(workPath, mount.directory);
45
+ if (!relDir || relDir.startsWith("..") || (0, import_path.isAbsolute)(relDir))
46
+ continue;
47
+ const relDirUnix = relDir.split(import_path.sep).join("/");
48
+ excludePatterns.push(`${relDirUnix}/**`);
49
+ directoryStubs[`${relDirUnix}/${STATIC_PLACEHOLDER_FILE}`] = new import_file_blob.default({
50
+ data: ""
51
+ });
52
+ for (const keepFile of keepFiles) {
53
+ const fsPath = (0, import_path.join)(mount.directory, keepFile);
54
+ if (import_fs.default.existsSync(fsPath)) {
55
+ directoryStubs[`${relDirUnix}/${keepFile}`] = new import_file_fs_ref.default({
56
+ fsPath
57
+ });
58
+ }
59
+ }
60
+ }
61
+ return { excludePatterns, directoryStubs };
62
+ }
63
+ // Annotate the CommonJS export names for ESM import in node:
64
+ 0 && (module.exports = {
65
+ STATIC_PLACEHOLDER_FILE,
66
+ staticBundleExclusions
67
+ });
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Shared static-file CDN promotion for builders that deploy a web framework as
3
+ * one Lambda behind a catch-all route. Framework-specific discovery stays in
4
+ * each builder and emits a {@link StaticDiscovery}; this module copies the
5
+ * discovered directories into the build output's static dir and produces the
6
+ * routes that keep the framework's precedence.
7
+ */
8
+ export { EMPTY_DISCOVERY, type ShadowRoute, type StaticBundleExclusions, type StaticDiscovery, type StaticFallback, type StaticMount, type StaticPromotionResult, type StaticPromotionOptions, } from './types';
9
+ export { copyStaticMounts, promoteStaticFiles } from './promote';
10
+ export { MAX_ROUTE_SRC_LENGTH, NAVIGATION_ACCEPT_RE, staticDirectoryRedirects, staticFallbackRoutes, staticShadowRoutes, } from './routes';
11
+ export { STATIC_PLACEHOLDER_FILE, staticBundleExclusions } from './bundle';
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var static_files_exports = {};
20
+ __export(static_files_exports, {
21
+ EMPTY_DISCOVERY: () => import_types.EMPTY_DISCOVERY,
22
+ MAX_ROUTE_SRC_LENGTH: () => import_routes.MAX_ROUTE_SRC_LENGTH,
23
+ NAVIGATION_ACCEPT_RE: () => import_routes.NAVIGATION_ACCEPT_RE,
24
+ STATIC_PLACEHOLDER_FILE: () => import_bundle.STATIC_PLACEHOLDER_FILE,
25
+ copyStaticMounts: () => import_promote.copyStaticMounts,
26
+ promoteStaticFiles: () => import_promote.promoteStaticFiles,
27
+ staticBundleExclusions: () => import_bundle.staticBundleExclusions,
28
+ staticDirectoryRedirects: () => import_routes.staticDirectoryRedirects,
29
+ staticFallbackRoutes: () => import_routes.staticFallbackRoutes,
30
+ staticShadowRoutes: () => import_routes.staticShadowRoutes
31
+ });
32
+ module.exports = __toCommonJS(static_files_exports);
33
+ var import_types = require("./types");
34
+ var import_promote = require("./promote");
35
+ var import_routes = require("./routes");
36
+ var import_bundle = require("./bundle");
37
+ // Annotate the CommonJS export names for ESM import in node:
38
+ 0 && (module.exports = {
39
+ EMPTY_DISCOVERY,
40
+ MAX_ROUTE_SRC_LENGTH,
41
+ NAVIGATION_ACCEPT_RE,
42
+ STATIC_PLACEHOLDER_FILE,
43
+ copyStaticMounts,
44
+ promoteStaticFiles,
45
+ staticBundleExclusions,
46
+ staticDirectoryRedirects,
47
+ staticFallbackRoutes,
48
+ staticShadowRoutes
49
+ });
@@ -0,0 +1,19 @@
1
+ import type { StaticDiscovery, StaticMount, StaticPromotionOptions, StaticPromotionResult } from './types';
2
+ /**
3
+ * Copy each mount's directory into the CDN tree at its URL prefix.
4
+ *
5
+ * A path is filled only by the highest-priority source whose prefix covers it,
6
+ * so a lower-priority source never leaks a file that would 404 at runtime.
7
+ * Priority follows {@link byCopyPriority}; the per-file filter enforces it.
8
+ * Files listed in `excludedFiles` are skipped so the Lambda serves them.
9
+ *
10
+ * A failed mount is skipped (the Lambda still serves it), but it keeps its
11
+ * namespace so lower-priority sources cannot fill it. Returns the mounts that
12
+ * were copied, so a failed mount gets no fallback route (empty when all fail).
13
+ */
14
+ export declare function copyStaticMounts(discovery: Pick<StaticDiscovery, 'mounts' | 'excludedFiles'>, outputStaticDir: string, opts?: StaticPromotionOptions): Promise<StaticMount[]>;
15
+ /**
16
+ * Copy a discovery's mounts into `outputStaticDir`. Returns null when there
17
+ * is nothing to promote: no mounts discovered, or none could be copied.
18
+ */
19
+ export declare function promoteStaticFiles(discovery: StaticDiscovery, outputStaticDir: string, opts?: StaticPromotionOptions): Promise<StaticPromotionResult | null>;
@@ -0,0 +1,90 @@
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
+ var promote_exports = {};
30
+ __export(promote_exports, {
31
+ copyStaticMounts: () => copyStaticMounts,
32
+ promoteStaticFiles: () => promoteStaticFiles
33
+ });
34
+ module.exports = __toCommonJS(promote_exports);
35
+ var import_fs = __toESM(require("fs"));
36
+ var import_path = require("path");
37
+ var import_debug = __toESM(require("../debug"));
38
+ var import_utils = require("./utils");
39
+ function cdnUrlPath(outputStaticDir, destPath) {
40
+ const rel = (0, import_path.relative)(outputStaticDir, destPath);
41
+ return rel === "" ? "/" : "/" + rel.split(import_path.sep).join("/");
42
+ }
43
+ async function copyStaticMounts(discovery, outputStaticDir, opts) {
44
+ const excluded = new Set(discovery.excludedFiles);
45
+ const higherPriority = [];
46
+ const copied = [];
47
+ for (const mount of (0, import_utils.byCopyPriority)(discovery.mounts)) {
48
+ const dest = (0, import_path.join)(outputStaticDir, (0, import_utils.trimSlashes)(mount.urlPath));
49
+ try {
50
+ await import_fs.default.promises.mkdir(dest, { recursive: true });
51
+ await import_fs.default.promises.cp(mount.directory, dest, {
52
+ recursive: true,
53
+ force: false,
54
+ filter: (_src, destPath) => {
55
+ const urlPath = cdnUrlPath(outputStaticDir, destPath);
56
+ return !higherPriority.some((base) => (0, import_utils.mountCovers)(base, urlPath)) && !excluded.has(urlPath);
57
+ }
58
+ });
59
+ copied.push(mount);
60
+ (0, import_debug.default)(`copied ${mount.directory} -> ${dest}`);
61
+ } catch (err) {
62
+ (0, import_debug.default)(
63
+ `${(0, import_utils.logLabel)(opts)}: skipping ${mount.urlPath}: copy failed (${err})`
64
+ );
65
+ }
66
+ higherPriority.push((0, import_utils.trimTrailingSlashes)(mount.urlPath));
67
+ }
68
+ return copied;
69
+ }
70
+ async function promoteStaticFiles(discovery, outputStaticDir, opts) {
71
+ const label = (0, import_utils.logLabel)(opts);
72
+ const { mounts } = discovery;
73
+ if (mounts.length === 0) {
74
+ (0, import_debug.default)(`${label}: no static mounts found, skipping`);
75
+ return null;
76
+ }
77
+ (0, import_debug.default)(
78
+ `${label}: found ${mounts.length} static mount(s): ${mounts.map((m) => m.urlPath).join(", ")}`
79
+ );
80
+ const copiedMounts = await copyStaticMounts(discovery, outputStaticDir, opts);
81
+ if (copiedMounts.length === 0) {
82
+ return null;
83
+ }
84
+ return { discovery, copiedMounts, outputStaticDir };
85
+ }
86
+ // Annotate the CommonJS export names for ESM import in node:
87
+ 0 && (module.exports = {
88
+ copyStaticMounts,
89
+ promoteStaticFiles
90
+ });
@@ -0,0 +1,60 @@
1
+ import type { RouteWithSrc } from '@vercel/routing-utils';
2
+ import type { ShadowRoute, StaticMount, StaticPromotionOptions } from './types';
3
+ export declare const MAX_ROUTE_SRC_LENGTH = 4096;
4
+ /**
5
+ * Routes that send paths the app owns to the Lambda, emitted before
6
+ * `handle: 'filesystem'` so the app wins over a colliding CDN file.
7
+ *
8
+ * Each shadow body is a ready-made pattern from discovery, minus its leading
9
+ * slash and with no capturing groups. The bodies are OR'd into one capturing
10
+ * group whose match is copied back into `request.path` via `$1`. The group
11
+ * allows an optional trailing slash so a framework's slash redirect still
12
+ * reaches the app.
13
+ *
14
+ * Bodies are grouped by method set so a shadow only intercepts the methods
15
+ * the app handles, then split across as many routes as fit the 4096-char
16
+ * `src` cap; all route to the Lambda, so the split is order-independent. A
17
+ * body too long for a `src` even alone is dropped (and logged): its path stays
18
+ * unshadowed. Returns an empty list when nothing is shadowed.
19
+ */
20
+ export declare function staticShadowRoutes(shadowRoutes: ShadowRoute[], lambdaPath: string, opts?: StaticPromotionOptions): RouteWithSrc[];
21
+ /**
22
+ * Bare-directory → slash redirects, emitted after shadow routes and before
23
+ * `handle: 'filesystem'`.
24
+ *
25
+ * The CDN serves index.html as an implicit directory index for bare directory
26
+ * paths. For `html`/`frontend` mounts, redirect the bare form to the slash
27
+ * form so the CDN serves the file at the correct URL base. Directories covered
28
+ * by a higher-priority mount get their CDN content from that mount, so they
29
+ * emit no redirect (mounts are walked in copy-priority order). Only
30
+ * directories that contain an index.html get a redirect.
31
+ */
32
+ export declare function staticDirectoryRedirects(mounts: StaticMount[], opts?: StaticPromotionOptions): RouteWithSrc[];
33
+ /**
34
+ * Accept-header gate for navigation requests: an explicit text/html or
35
+ * application/xhtml+xml media type not rejected with q=0. The type is
36
+ * boundary-guarded so a longer token like `text/htmlx` never matches, and a
37
+ * wildcard `Accept` does not count. The router anchors `has` values with
38
+ * `^…$`, hence the `.*` wrapping.
39
+ */
40
+ export declare const NAVIGATION_ACCEPT_RE = ".*(?:^|[,\\s])(?:text/html|application/xhtml\\+xml)(?=[,;\\s]|$)(?![^,]*;\\s*q=0(?:\\.0+)?(?:[,;\\s]|$)).*";
41
+ /**
42
+ * `handle: 'miss'` routes that serve each copied mount's fallback file for a
43
+ * miss under its mount. `check: true` re-resolves the rewrite to the copied
44
+ * file so it stays a CDN hit. Routes are GET/HEAD only.
45
+ *
46
+ * `copied` supplies the fallbacks: only copied mounts get one, since a
47
+ * `check: true` destination that doesn't exist ends the request instead of
48
+ * reaching the Lambda. `discovered` (every discovered mount) supplies the
49
+ * nested-mount exclusions, since nested mounts own their own subtrees whether
50
+ * or not they were copied.
51
+ *
52
+ * A non-200 fallback (e.g. 404.html) is served for every miss. A 200 fallback
53
+ * (e.g. index.html) is served only for navigation requests: an explicit html
54
+ * `Accept` ({@link NAVIGATION_ACCEPT_RE}) plus, unless
55
+ * `useFallbackForExtensionedPaths` is true, an extension-less final path
56
+ * segment (so `/app/main.js` falls through). Anything the gate rejects falls
57
+ * through to the Lambda. A fallback whose nested-mount guard pushes its `src`
58
+ * over the cap is skipped.
59
+ */
60
+ export declare function staticFallbackRoutes(copied: Pick<StaticMount, 'urlPath' | 'fallback'>[], discovered: Pick<StaticMount, 'urlPath'>[], opts?: StaticPromotionOptions): RouteWithSrc[];
@@ -0,0 +1,205 @@
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
+ var routes_exports = {};
30
+ __export(routes_exports, {
31
+ MAX_ROUTE_SRC_LENGTH: () => MAX_ROUTE_SRC_LENGTH,
32
+ NAVIGATION_ACCEPT_RE: () => NAVIGATION_ACCEPT_RE,
33
+ staticDirectoryRedirects: () => staticDirectoryRedirects,
34
+ staticFallbackRoutes: () => staticFallbackRoutes,
35
+ staticShadowRoutes: () => staticShadowRoutes
36
+ });
37
+ module.exports = __toCommonJS(routes_exports);
38
+ var import_fs = __toESM(require("fs"));
39
+ var import_path = require("path");
40
+ var import_debug = __toESM(require("../debug"));
41
+ var import_utils = require("./utils");
42
+ const MAX_ROUTE_SRC_LENGTH = 4096;
43
+ function shadowSrc(bodies) {
44
+ return `^/((?:${bodies.join("|")})/?)$`;
45
+ }
46
+ function redirectSrc(bodies) {
47
+ return `^/((?:${bodies.join("|")}))$`;
48
+ }
49
+ const SHADOW_SRC_WRAPPER_LENGTH = shadowSrc([]).length;
50
+ const REDIRECT_SRC_WRAPPER_LENGTH = redirectSrc([]).length;
51
+ function chunkBodies(bodies, wrapperLength) {
52
+ const chunks = [];
53
+ let srcLen = 0;
54
+ let dropped = 0;
55
+ for (const body of bodies) {
56
+ if (wrapperLength + body.length > MAX_ROUTE_SRC_LENGTH) {
57
+ dropped += 1;
58
+ continue;
59
+ }
60
+ const current = chunks[chunks.length - 1];
61
+ if (current && srcLen + 1 + body.length <= MAX_ROUTE_SRC_LENGTH) {
62
+ current.push(body);
63
+ srcLen += 1 + body.length;
64
+ } else {
65
+ chunks.push([body]);
66
+ srcLen = wrapperLength + body.length;
67
+ }
68
+ }
69
+ return { chunks, dropped };
70
+ }
71
+ function staticShadowRoutes(shadowRoutes, lambdaPath, opts) {
72
+ const byMethods = /* @__PURE__ */ new Map();
73
+ for (const sr of shadowRoutes) {
74
+ const key = sr.methods === null ? "" : JSON.stringify([...sr.methods].sort());
75
+ const group = byMethods.get(key);
76
+ if (group) {
77
+ group.push(sr.body);
78
+ } else {
79
+ byMethods.set(key, [sr.body]);
80
+ }
81
+ }
82
+ const routes = [];
83
+ let dropped = 0;
84
+ for (const [methodsKey, bodies] of byMethods) {
85
+ const methods = methodsKey === "" ? void 0 : JSON.parse(methodsKey);
86
+ const { chunks, dropped: d } = chunkBodies(
87
+ bodies,
88
+ SHADOW_SRC_WRAPPER_LENGTH
89
+ );
90
+ dropped += d;
91
+ for (const chunk of chunks) {
92
+ routes.push({
93
+ src: shadowSrc(chunk),
94
+ dest: `/${lambdaPath}`,
95
+ ...methods ? { methods } : {},
96
+ transforms: [{ type: "request.path", op: "set", args: "/$1" }]
97
+ });
98
+ }
99
+ }
100
+ if (dropped > 0) {
101
+ (0, import_debug.default)(
102
+ `${(0, import_utils.logLabel)(opts)}: ${dropped} shadow route(s) over the ${MAX_ROUTE_SRC_LENGTH} char cap left unshadowed`
103
+ );
104
+ }
105
+ return routes;
106
+ }
107
+ function staticDirectoryRedirects(mounts, opts) {
108
+ const redirects = [];
109
+ let redirectDropped = 0;
110
+ const higherPriority = [];
111
+ for (const mount of (0, import_utils.byCopyPriority)(mounts)) {
112
+ if (!mount.html && !mount.frontend) {
113
+ higherPriority.push((0, import_utils.trimTrailingSlashes)(mount.urlPath));
114
+ continue;
115
+ }
116
+ const urlPrefix = (0, import_utils.trimSlashes)(mount.urlPath);
117
+ const bodies = [];
118
+ const collectBodies = (absDir, urlPath) => {
119
+ if (higherPriority.some((base) => (0, import_utils.mountCovers)(base, `/${urlPath}`))) {
120
+ return;
121
+ }
122
+ if (urlPath && import_fs.default.existsSync((0, import_path.join)(absDir, "index.html"))) {
123
+ bodies.push((0, import_utils.escapeRegex)(urlPath));
124
+ }
125
+ for (const entry of import_fs.default.readdirSync(absDir, { withFileTypes: true })) {
126
+ if (!entry.isDirectory())
127
+ continue;
128
+ collectBodies(
129
+ (0, import_path.join)(absDir, entry.name),
130
+ urlPath ? `${urlPath}/${entry.name}` : entry.name
131
+ );
132
+ }
133
+ };
134
+ try {
135
+ collectBodies(mount.directory, urlPrefix);
136
+ } catch (err) {
137
+ (0, import_debug.default)(
138
+ `${(0, import_utils.logLabel)(opts)}: skipping bare-dir redirects for ${mount.urlPath} (${err})`
139
+ );
140
+ }
141
+ higherPriority.push((0, import_utils.trimTrailingSlashes)(mount.urlPath));
142
+ const { chunks, dropped } = chunkBodies(
143
+ bodies,
144
+ REDIRECT_SRC_WRAPPER_LENGTH
145
+ );
146
+ redirectDropped += dropped;
147
+ for (const chunk of chunks) {
148
+ redirects.push({
149
+ src: redirectSrc(chunk),
150
+ dest: "/$1/",
151
+ status: 307,
152
+ methods: ["GET", "HEAD"]
153
+ });
154
+ }
155
+ }
156
+ if (redirectDropped > 0) {
157
+ (0, import_debug.default)(
158
+ `${(0, import_utils.logLabel)(opts)}: ${redirectDropped} redirect(s) over the ${MAX_ROUTE_SRC_LENGTH} char cap left unredirected`
159
+ );
160
+ }
161
+ return redirects;
162
+ }
163
+ const NAVIGATION_ACCEPT_RE = ".*(?:^|[,\\s])(?:text/html|application/xhtml\\+xml)(?=[,;\\s]|$)(?![^,]*;\\s*q=0(?:\\.0+)?(?:[,;\\s]|$)).*";
164
+ function staticFallbackRoutes(copied, discovered, opts) {
165
+ const mountPrefixes = discovered.map((m) => (0, import_utils.trimTrailingSlashes)(m.urlPath));
166
+ return copied.flatMap((mount) => {
167
+ const fb = mount.fallback;
168
+ if (!fb)
169
+ return [];
170
+ const isNavigation = fb.status === 200;
171
+ const prefix = (0, import_utils.trimTrailingSlashes)(mount.urlPath);
172
+ const nested = mountPrefixes.filter((urlPath) => urlPath.startsWith(`${prefix}/`)).map((urlPath) => urlPath.slice(prefix.length + 1));
173
+ const siblingGuard = nested.length ? `(?!(?:${nested.map(import_utils.escapeRegex).join("|")})(?:/|$))` : "";
174
+ const useExtensionGuard = isNavigation && !opts?.useFallbackForExtensionedPaths;
175
+ const extensionGuard = useExtensionGuard ? "(?!.*[^/.]\\.[^/]*$)" : "";
176
+ const src = `^${(0, import_utils.escapeRegex)(prefix)}/${siblingGuard}${extensionGuard}.*$`;
177
+ if (src.length > MAX_ROUTE_SRC_LENGTH) {
178
+ (0, import_debug.default)(
179
+ `${(0, import_utils.logLabel)(opts)}: fallback route for ${mount.urlPath} over the ${MAX_ROUTE_SRC_LENGTH} char cap, served by the Lambda`
180
+ );
181
+ return [];
182
+ }
183
+ const route = {
184
+ src,
185
+ dest: `${prefix}/${fb.file}`,
186
+ status: fb.status,
187
+ check: true,
188
+ methods: ["GET", "HEAD"],
189
+ ...isNavigation ? {
190
+ has: [
191
+ { type: "header", key: "accept", value: NAVIGATION_ACCEPT_RE }
192
+ ]
193
+ } : {}
194
+ };
195
+ return [route];
196
+ });
197
+ }
198
+ // Annotate the CommonJS export names for ESM import in node:
199
+ 0 && (module.exports = {
200
+ MAX_ROUTE_SRC_LENGTH,
201
+ NAVIGATION_ACCEPT_RE,
202
+ staticDirectoryRedirects,
203
+ staticFallbackRoutes,
204
+ staticShadowRoutes
205
+ });
@@ -0,0 +1,81 @@
1
+ import type { Files } from '../types';
2
+ /**
3
+ * Types for static-file promotion: the discovery contract a builder's
4
+ * framework-specific discovery step hands in, plus the options and results of
5
+ * the shared promotion steps.
6
+ */
7
+ /** A mount's miss fallback: which file to serve, and with what status. */
8
+ export interface StaticFallback {
9
+ /** File to serve for unmatched paths under the mount (e.g. "index.html"). */
10
+ file: string;
11
+ /** Status to serve it with (200 for index.html, 404 for 404.html). */
12
+ status: number;
13
+ }
14
+ /** One directory served by the app at a URL prefix. */
15
+ export interface StaticMount {
16
+ /** URL prefix, no trailing slash ("/" for root). */
17
+ urlPath: string;
18
+ /** Absolute source directory. */
19
+ directory: string;
20
+ /** Miss fallback for this mount, or null for none. */
21
+ fallback: StaticFallback | null;
22
+ /** Low-priority SPA-style mount, copied after all plain mounts. */
23
+ frontend: boolean;
24
+ /** Directory-index + bare-directory redirect mode. */
25
+ html: boolean;
26
+ }
27
+ /** A path the app owns ahead of the CDN. */
28
+ export interface ShadowRoute {
29
+ /** Regex body matched against the path minus its leading slash. */
30
+ body: string;
31
+ /** Sorted HTTP methods, or null for all methods. */
32
+ methods: string[] | null;
33
+ }
34
+ /** Discovery output: the contract between a builder and this module. */
35
+ export interface StaticDiscovery {
36
+ /** Mounts in declaration order. */
37
+ mounts: StaticMount[];
38
+ /** Paths the app owns, sorted by body. */
39
+ shadowRoutes: ShadowRoute[];
40
+ /** CDN URL paths (leading slash) the app owns; sorted and deduplicated. */
41
+ excludedFiles: string[];
42
+ }
43
+ /**
44
+ * The discovery result for "nothing to promote". Frozen (arrays included) so
45
+ * the shared instance can't be mutated by a caller.
46
+ */
47
+ export declare const EMPTY_DISCOVERY: StaticDiscovery;
48
+ /** Options shared by every promotion step. */
49
+ export interface StaticPromotionOptions {
50
+ /** Prefix for debug log lines (e.g. "FastAPI"). */
51
+ debugLabel?: string;
52
+ /**
53
+ * Serve fallback for navigation requests to extensioned paths
54
+ * like `/app/main.js`. Defaults to false.
55
+ */
56
+ useFallbackForExtensionedPaths?: boolean;
57
+ }
58
+ /** Outcome of promoting a discovery's mounts, for wiring routes and output. */
59
+ export interface StaticPromotionResult {
60
+ /**
61
+ * The full discovery. `discovery.mounts` (every discovered mount, copied or
62
+ * not) drives redirects, bundle exclusion and the fallback nested-mount
63
+ * guard, since a mount owns its namespace at runtime even if its copy failed.
64
+ */
65
+ discovery: StaticDiscovery;
66
+ /**
67
+ * Mounts actually copied, in copy-priority order. Only these get fallback
68
+ * routes: a `check: true` destination that doesn't exist ends the request
69
+ * instead of reaching the Lambda.
70
+ */
71
+ copiedMounts: StaticMount[];
72
+ /** Static output dir the mounts were copied into. */
73
+ outputStaticDir: string;
74
+ }
75
+ /** Lambda bundle adjustments for promoted mounts. */
76
+ export interface StaticBundleExclusions {
77
+ /** Glob patterns that exclude promoted mount directories from the Lambda. */
78
+ excludePatterns: string[];
79
+ /** Stub files that keep excluded mount directories present in the Lambda. */
80
+ directoryStubs: Files;
81
+ }