@builtbyfriends/edge 0.0.0-stage → 1.9.1
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/LICENSE +22 -0
- package/README.md +10 -2
- package/dist/index.d.mts +236 -0
- package/dist/index.mjs +849 -0
- package/package.json +38 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026-present, Built By Friends Company
|
|
4
|
+
Copyright (c) 2026-present, Cloudflare, Inc.
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @builtbyfriends/edge
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Routing and static asset helpers shared by bwf's direct Cloudflare deployments and platform runtime.
|
|
4
|
+
|
|
5
|
+
Configure redirects, rewrites, headers, and asset behavior through `bwf.config.ts`.
|
|
6
|
+
|
|
7
|
+
## Documentation
|
|
8
|
+
|
|
9
|
+
See Static Assets and the configuration reference.
|
|
10
|
+
|
|
11
|
+
Read the bwf documentation online or use the Markdown guides and references in `node_modules/@builtbyfriends/bwf/docs/`, included with the `bwf` package.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { AssetConfig, AssetConfig as AssetConfig$1, HeaderRule, HeaderRule as HeaderRule$1, RedirectRule, RedirectRule as RedirectRule$1 } from "@builtbyfriends/deploy-core";
|
|
2
|
+
type ProjectZeroTrustRouting = Readonly<{
|
|
3
|
+
teamDomain: string;
|
|
4
|
+
audiences: ReadonlyArray<Readonly<{
|
|
5
|
+
hostname: string;
|
|
6
|
+
audience: string;
|
|
7
|
+
}>>;
|
|
8
|
+
}>;
|
|
9
|
+
/** Upgrade public HTTP requests without involving assets or application code. */
|
|
10
|
+
export declare function redirectToHttps(request: Request): Response | undefined;
|
|
11
|
+
type HeaderRulePolicy = Readonly<{
|
|
12
|
+
/**
|
|
13
|
+
* Protect unrelated tenants that share one registrable domain. Direct
|
|
14
|
+
* deployments own their hostname and may safely use cookie header rules.
|
|
15
|
+
*/
|
|
16
|
+
cookieIsolation?: "shared-domain" | "origin";
|
|
17
|
+
}>;
|
|
18
|
+
/** A single member of a `Clear-Site-Data` list. */
|
|
19
|
+
type ClearSiteDataMember = Readonly<{
|
|
20
|
+
/** The member text, trimmed of surrounding whitespace; kept for re-serialization. */
|
|
21
|
+
raw: string;
|
|
22
|
+
/**
|
|
23
|
+
* The quoted-string content (original case) when the member is a well-formed
|
|
24
|
+
* quoted-string, else `null`. A browser ignores members that are not
|
|
25
|
+
* well-formed quoted-strings.
|
|
26
|
+
*/
|
|
27
|
+
directive: string | null;
|
|
28
|
+
}>;
|
|
29
|
+
/**
|
|
30
|
+
* Parse a `Clear-Site-Data` header value into its list members. The value is a
|
|
31
|
+
* comma-separated list of quoted-strings (W3C Clear-Site-Data); a comma inside a
|
|
32
|
+
* quoted-string does not split a member. Empty members are dropped.
|
|
33
|
+
*/
|
|
34
|
+
export declare function parseClearSiteData(value: string): Array<ClearSiteDataMember>;
|
|
35
|
+
/**
|
|
36
|
+
* Sanitize a `Clear-Site-Data` value so a tenant rule can't clear cookies across
|
|
37
|
+
* the shared *.void.app boundary, while still allowing the safe directives.
|
|
38
|
+
*
|
|
39
|
+
* Only `"cookies"` and `"*"` clear cookies for the registrable domain (and thus
|
|
40
|
+
* every tenant's subdomain). `"cache"`, `"storage"`, `"executionContexts"`, and
|
|
41
|
+
* any future quoted directive are origin-scoped — each subdomain is its own
|
|
42
|
+
* origin — so they are kept verbatim. Malformed members are dropped (a browser
|
|
43
|
+
* ignores them, and dropping forecloses a lenient parser honoring them).
|
|
44
|
+
*
|
|
45
|
+
* Returns the filtered value, or `null` when nothing safe remains: a `"*"`
|
|
46
|
+
* includes cookies and can't be expressed without them, and a value that is only
|
|
47
|
+
* `"cookies"` collapses to empty.
|
|
48
|
+
*/
|
|
49
|
+
export declare function sanitizeClearSiteData(value: string): string | null;
|
|
50
|
+
/**
|
|
51
|
+
* Apply matching header rules to a response.
|
|
52
|
+
* All matching rules merge; last match wins for same header name.
|
|
53
|
+
* Returns the original response unchanged when no rules or no matches.
|
|
54
|
+
*/
|
|
55
|
+
export declare function applyHeaderRules(response: Response, pathname: string, rules?: ReadonlyArray<HeaderRule$1>, policy?: HeaderRulePolicy): Response;
|
|
56
|
+
type CompiledPattern = Readonly<{
|
|
57
|
+
/**
|
|
58
|
+
* @deprecated Built on first read for older callers; bwf does not use it.
|
|
59
|
+
* It can backtrack and fails past engine size limits. Use `matchPattern` or
|
|
60
|
+
* `matchPatternCaptures`.
|
|
61
|
+
*/
|
|
62
|
+
regex: RegExp;
|
|
63
|
+
paramNames: ReadonlyArray<string>;
|
|
64
|
+
}>;
|
|
65
|
+
/**
|
|
66
|
+
* Parse a capture pattern. Throws a SyntaxError for a malformed one: a repeated
|
|
67
|
+
* name (`/:id/:id`, `/:splat/*`) or a name that starts with a digit (`/:1`).
|
|
68
|
+
*/
|
|
69
|
+
export declare function compilePattern(source: string): CompiledPattern;
|
|
70
|
+
/**
|
|
71
|
+
* Match a pattern against a pathname. Returns captured params, or null.
|
|
72
|
+
* A malformed pattern (e.g. a repeated name like `/:splat/*`) also returns
|
|
73
|
+
* null, so one bad rule cannot fail unrelated requests.
|
|
74
|
+
*/
|
|
75
|
+
export declare function matchPatternCaptures(pattern: string, pathname: string): Record<string, string> | null;
|
|
76
|
+
/**
|
|
77
|
+
* Match a pattern against a pathname (boolean form). Malformed patterns yield
|
|
78
|
+
* `false` rather than throwing (see `matchPatternCaptures`).
|
|
79
|
+
*/
|
|
80
|
+
export declare function matchPattern(pattern: string, pathname: string): boolean;
|
|
81
|
+
/**
|
|
82
|
+
* Match a pattern against a pathname using LITERAL semantics — no named
|
|
83
|
+
* captures. Only `*` is special (matches any characters including `/`); every
|
|
84
|
+
* other character (including `:`) is treated as a literal.
|
|
85
|
+
*
|
|
86
|
+
* Used for header rules, which never had `:name` capture syntax; existing tenant configs may include literal
|
|
87
|
+
* `:` (e.g. `/api/v1:health`, `:batchGet`-style URLs). Routing rules
|
|
88
|
+
* (`redirects`/`rewrites`/`fallbacks`) use the capture-aware `compilePattern`.
|
|
89
|
+
*/
|
|
90
|
+
export declare function matchLiteralPattern(pattern: string, pathname: string): boolean;
|
|
91
|
+
/**
|
|
92
|
+
* Substitute `:name` and `:name*` tokens in a destination string with the
|
|
93
|
+
* matching named captures from `params`. `:splat` works for legacy `*` patterns
|
|
94
|
+
* because `compilePattern` captures anonymous `*` as `splat`.
|
|
95
|
+
*/
|
|
96
|
+
export declare function substituteParams(destination: string, params: Record<string, string>): string;
|
|
97
|
+
type RoutingRuleResult = {
|
|
98
|
+
type: "redirect";
|
|
99
|
+
destination: string;
|
|
100
|
+
status: number;
|
|
101
|
+
} | {
|
|
102
|
+
type: "rewrite";
|
|
103
|
+
destination: string;
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* Check routing rules (redirects + rewrites) against a request pathname.
|
|
107
|
+
*
|
|
108
|
+
* **First match wins** — matches Netlify `_redirects` and Vercel `vercel.json`
|
|
109
|
+
* semantics: users put more-specific rules above more-general ones, and the
|
|
110
|
+
* first rule whose source matches takes effect. (Header rules in this same
|
|
111
|
+
* package use last-match-wins for compatibility with Netlify `_headers`,
|
|
112
|
+
* which is the opposite of `_redirects`. The asymmetry is intentional.)
|
|
113
|
+
*
|
|
114
|
+
* `requestHost` is the WHATWG `url.hostname` (lowercase, port-stripped).
|
|
115
|
+
* Rules with a `host` field are skipped when `rule.host !== requestHost`;
|
|
116
|
+
* path-only rules apply to every host bound to the project.
|
|
117
|
+
*
|
|
118
|
+
* Returns a discriminated result. The caller is responsible for building the
|
|
119
|
+
* actual `Response` for redirects (so it can merge the request's query string
|
|
120
|
+
* into the `Location` header).
|
|
121
|
+
*/
|
|
122
|
+
export declare function applyRoutingRules(pathname: string, rules?: ReadonlyArray<RedirectRule$1>, requestHost?: string): RoutingRuleResult | null;
|
|
123
|
+
/**
|
|
124
|
+
* Merge a request's query string into a redirect destination.
|
|
125
|
+
*
|
|
126
|
+
* If the destination already contains a `?`, its parameters take precedence
|
|
127
|
+
* over the request's. Otherwise the request's query is appended verbatim.
|
|
128
|
+
*
|
|
129
|
+
* A `#fragment` on the destination is stripped before the merge and
|
|
130
|
+
* re-appended afterwards, so `/new#faq` + `?utm=x` becomes `/new?utm=x#faq`
|
|
131
|
+
* rather than `/new#faq?utm=x` (which browsers treat as fragment text).
|
|
132
|
+
*/
|
|
133
|
+
export declare function mergeQueryIntoLocation(destination: string, requestSearch: string): string;
|
|
134
|
+
type EdgeAssetFetcher = Readonly<{
|
|
135
|
+
fetch(request: Request): Promise<Response>;
|
|
136
|
+
}>;
|
|
137
|
+
type StaticEdgeEnv = Readonly<{
|
|
138
|
+
ASSETS: EdgeAssetFetcher;
|
|
139
|
+
}>;
|
|
140
|
+
type StaticEdgeConfig = Readonly<{
|
|
141
|
+
alwaysUseHttps?: boolean;
|
|
142
|
+
/** Optional native Worker self-metadata used to identify the served version. */
|
|
143
|
+
versionMetadataBinding?: string;
|
|
144
|
+
/**
|
|
145
|
+
* @deprecated Ignored. Cloudflare applies asset handling from the Worker's
|
|
146
|
+
* `assets` config (`not_found_handling`, `html_handling`), which `bwf deploy`
|
|
147
|
+
* writes. Removed in the next major version.
|
|
148
|
+
*/
|
|
149
|
+
assetConfig?: AssetConfig$1;
|
|
150
|
+
headerRules?: ReadonlyArray<HeaderRule$1>;
|
|
151
|
+
redirectRules?: ReadonlyArray<RedirectRule$1>;
|
|
152
|
+
fallbackRules?: ReadonlyArray<RedirectRule$1>;
|
|
153
|
+
}>;
|
|
154
|
+
type StaticEdgeHandler = Readonly<{
|
|
155
|
+
fetch(request: Request, env: StaticEdgeEnv): Promise<Response>;
|
|
156
|
+
}>;
|
|
157
|
+
/**
|
|
158
|
+
* Create the thin Worker used by direct static, SPA, and SSG deployments.
|
|
159
|
+
* Routing semantics intentionally match the hosted dispatch Worker: redirects
|
|
160
|
+
* and rewrites run before assets, fallback rewrites run only after an asset
|
|
161
|
+
* miss, and response-header rules apply to the effective pathname.
|
|
162
|
+
*/
|
|
163
|
+
export declare function createStaticEdgeHandler(config: StaticEdgeConfig): StaticEdgeHandler;
|
|
164
|
+
type ResolvedAsset = Readonly<{
|
|
165
|
+
path: string;
|
|
166
|
+
hash: string;
|
|
167
|
+
redirect?: string;
|
|
168
|
+
notFound?: boolean;
|
|
169
|
+
spa?: boolean;
|
|
170
|
+
}>;
|
|
171
|
+
/**
|
|
172
|
+
* Percent-decode a request pathname for a manifest lookup, honoring required
|
|
173
|
+
* URL encodings and encoded square brackets. Returns the raw value unchanged
|
|
174
|
+
* on a malformed sequence (e.g. a lone `%`) or other over-encoded spellings.
|
|
175
|
+
*
|
|
176
|
+
* Request pathnames arrive percent-encoded — WHATWG `URL.pathname` never
|
|
177
|
+
* decodes — but manifest keys are the asset's decoded on-disk path (a file
|
|
178
|
+
* named `oxc masthead.riv` is stored under `/assets/oxc masthead.riv`, not
|
|
179
|
+
* `%20`). Callers try the raw key first, then this decoded form.
|
|
180
|
+
*
|
|
181
|
+
* The decoded form is accepted only when re-encoding it reproduces the request
|
|
182
|
+
* path (up to percent-escape letter case and square-bracket encoding). Next.js
|
|
183
|
+
* encodes brackets in dynamic-page chunk URLs even though URL.pathname leaves
|
|
184
|
+
* them literal. Other accepted escapes are characters a URL MUST encode
|
|
185
|
+
* (space, `#`, non-ASCII, …). This rejects
|
|
186
|
+
* over-encoded spellings of ordinary path text (`%2F`→`/`, `%61`→`a`, `%5F`→`_`,
|
|
187
|
+
* `%2e%2e`→`..`), which a browser would never send and which would otherwise let
|
|
188
|
+
* a request reconstruct a guarded path (`/assets%2Fx`, `/%61ssets/x`,
|
|
189
|
+
* `/%5F%5Fvoid/x`) and serve the manifest entry while the raw-`url.pathname`
|
|
190
|
+
* policy gates — the `/__nosam/*` reserved-route block, the hashed-asset prefix
|
|
191
|
+
* gate, and the header/redirect rules — never fire. The URL pathname setter
|
|
192
|
+
* applies exactly the WHATWG "path percent-encode set", making it the canonical
|
|
193
|
+
* re-encoder.
|
|
194
|
+
*
|
|
195
|
+
* Known limitation: a file whose name contains a literal `%` (e.g. `logo%20.svg`,
|
|
196
|
+
* requested as `logo%2520.svg`) is not resolved — the path encoder leaves `%`
|
|
197
|
+
* as-is, so the round-trip can't reproduce the double-escaped request.
|
|
198
|
+
*/
|
|
199
|
+
export declare function safeDecodePathname(pathname: string): string;
|
|
200
|
+
/**
|
|
201
|
+
* Resolve a request pathname to a manifest entry using AssetConfig rules.
|
|
202
|
+
* Replicates Cloudflare Workers Assets path resolution behavior.
|
|
203
|
+
*/
|
|
204
|
+
export declare function resolveStaticPath(pathname: string, manifest: Record<string, string>, config: AssetConfig$1): ResolvedAsset | null;
|
|
205
|
+
/**
|
|
206
|
+
* Get the Content-Type header value for a given file path based on its extension.
|
|
207
|
+
*/
|
|
208
|
+
export declare function getContentType(path: string): string;
|
|
209
|
+
/**
|
|
210
|
+
* Resolve the Content-Type to serve for a stored asset, reconciling the value
|
|
211
|
+
* persisted at upload time (R2 `httpMetadata.contentType` / KV `ct` metadata)
|
|
212
|
+
* with a fresh path-based lookup. Returns `undefined` when no Content-Type
|
|
213
|
+
* header should be emitted.
|
|
214
|
+
*
|
|
215
|
+
* `application/null` is a sentinel (matching Wrangler) meaning "omit the
|
|
216
|
+
* Content-Type header entirely".
|
|
217
|
+
*
|
|
218
|
+
* `application/octet-stream` is the uploader's no-information default: older
|
|
219
|
+
* CLI versions stamped it on any extension their MIME table did not recognize
|
|
220
|
+
* (e.g. `.md`). Because assets are content-addressed and never re-uploaded,
|
|
221
|
+
* those stale octet-stream values can't be corrected at the source, so we
|
|
222
|
+
* treat a stored octet-stream as "unknown" and re-derive from the path here.
|
|
223
|
+
* Any other stored value is authoritative and honored as-is.
|
|
224
|
+
*/
|
|
225
|
+
export declare function resolveAssetContentType(stored: string | null | undefined, path: string): string | undefined;
|
|
226
|
+
/** Shared between the SDK, edge admission and Pages clients. */
|
|
227
|
+
type UsageLimitData = {
|
|
228
|
+
code: "usage_limit";
|
|
229
|
+
resource: "ai" | "sandbox" | "requests" | "execution";
|
|
230
|
+
reason: "monthly_quota" | "rate_limit" | "concurrency" | "runtime_budget" | "cpu";
|
|
231
|
+
message: string;
|
|
232
|
+
retryAt?: string;
|
|
233
|
+
};
|
|
234
|
+
export declare function readUsageLimit(value: unknown): UsageLimitData | null;
|
|
235
|
+
export declare function usageLimitResponse(limit: UsageLimitData): Response;
|
|
236
|
+
export type { AssetConfig, ClearSiteDataMember, CompiledPattern, EdgeAssetFetcher, HeaderRule, HeaderRulePolicy, ProjectZeroTrustRouting, RedirectRule, ResolvedAsset, RoutingRuleResult, StaticEdgeConfig, StaticEdgeEnv, StaticEdgeHandler, UsageLimitData };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,849 @@
|
|
|
1
|
+
// src/https.ts
|
|
2
|
+
/** Upgrade public HTTP requests without involving assets or application code. */
|
|
3
|
+
function redirectToHttps(request) {
|
|
4
|
+
const url = new URL(request.url);
|
|
5
|
+
if (url.protocol !== "http:" || url.hostname === "localhost" || url.hostname.endsWith(".localhost") || isIpv4Loopback(url.hostname) || url.hostname === "[::1]" || url.pathname.startsWith("/.well-known/acme-challenge/") || url.pathname.startsWith("/.well-known/pki-validation/")) return;
|
|
6
|
+
url.protocol = "https:";
|
|
7
|
+
url.port = "";
|
|
8
|
+
return Response.redirect(url.href, 308);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* `URL` already rewrites every IPv4 form (`127.1`, `0x7f.0.0.1`) to four
|
|
12
|
+
* decimal parts and rejects parts above 255, so only the shape is checked.
|
|
13
|
+
*/
|
|
14
|
+
function isIpv4Loopback(hostname) {
|
|
15
|
+
const parts = hostname.split(".");
|
|
16
|
+
return parts.length === 4 && parts[0] === "127" && parts.every((part) => part !== "" && [...part].every((char) => char >= "0" && char <= "9"));
|
|
17
|
+
}
|
|
18
|
+
// src/pattern.ts
|
|
19
|
+
/**
|
|
20
|
+
* Path-pattern matchers shared by routing and header rules.
|
|
21
|
+
*
|
|
22
|
+
* Each pattern is parsed once into tokens, and matching walks those tokens
|
|
23
|
+
* over the pathname. No RegExp is built from pattern text, so a pattern cannot
|
|
24
|
+
* hit engine size limits or backtrack: a match costs at most
|
|
25
|
+
* (steps) x (path length - pattern minimum + 1).
|
|
26
|
+
*
|
|
27
|
+
* `compilePattern` syntax:
|
|
28
|
+
* `:name` — single path segment, captured as `name`
|
|
29
|
+
* `:name*` — zero or more path segments, captured as `name`
|
|
30
|
+
* `*` — zero or more path segments, captured as `splat` (legacy)
|
|
31
|
+
*
|
|
32
|
+
* When a legacy pattern contains multiple anonymous `*`, the first captures
|
|
33
|
+
* as `splat` and later wildcards are non-capturing.
|
|
34
|
+
*/
|
|
35
|
+
const MAX_CACHE = 256;
|
|
36
|
+
/** LRU read: re-inserting a hit moves it to the most-recently-used end of Map order. */
|
|
37
|
+
function lruGet(cache, key) {
|
|
38
|
+
const value = cache.get(key);
|
|
39
|
+
if (value !== void 0) {
|
|
40
|
+
cache.delete(key);
|
|
41
|
+
cache.set(key, value);
|
|
42
|
+
}
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
/** LRU write: evict the least-recently-used entry once the cache is full. */
|
|
46
|
+
function lruSet(cache, key, value) {
|
|
47
|
+
if (cache.size >= MAX_CACHE) {
|
|
48
|
+
const first = cache.keys().next();
|
|
49
|
+
if (!first.done) cache.delete(first.value);
|
|
50
|
+
}
|
|
51
|
+
cache.set(key, value);
|
|
52
|
+
}
|
|
53
|
+
/** `[A-Za-z0-9_]` */
|
|
54
|
+
function isNameChar(code) {
|
|
55
|
+
return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 95;
|
|
56
|
+
}
|
|
57
|
+
/** Whether a wildcard of this kind may take the code unit. */
|
|
58
|
+
function accepts(kind, code) {
|
|
59
|
+
if (kind === "seg") return code !== 47;
|
|
60
|
+
return code !== 10 && code !== 13 && code !== 8232 && code !== 8233;
|
|
61
|
+
}
|
|
62
|
+
function pushText(tokens, text) {
|
|
63
|
+
if (!text) return;
|
|
64
|
+
const last = tokens[tokens.length - 1];
|
|
65
|
+
if (last?.kind === "text") last.text += text;
|
|
66
|
+
else tokens.push({
|
|
67
|
+
kind: "text",
|
|
68
|
+
text
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
/** `compilePattern` syntax, read left to right. */
|
|
72
|
+
function parseCapture(source) {
|
|
73
|
+
const tokens = [];
|
|
74
|
+
const paramNames = [];
|
|
75
|
+
let splatTaken = false;
|
|
76
|
+
let index = 0;
|
|
77
|
+
while (index < source.length) {
|
|
78
|
+
const character = source[index];
|
|
79
|
+
if (character === ":") {
|
|
80
|
+
let end = index + 1;
|
|
81
|
+
while (end < source.length && isNameChar(source.charCodeAt(end))) end++;
|
|
82
|
+
if (end === index + 1) {
|
|
83
|
+
pushText(tokens, ":");
|
|
84
|
+
index++;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const name = source.slice(index + 1, end);
|
|
88
|
+
paramNames.push(name);
|
|
89
|
+
const rest = source[end] === "*";
|
|
90
|
+
tokens.push({
|
|
91
|
+
kind: rest ? "any" : "seg",
|
|
92
|
+
name
|
|
93
|
+
});
|
|
94
|
+
index = rest ? end + 1 : end;
|
|
95
|
+
} else if (character === "*") {
|
|
96
|
+
if (splatTaken) tokens.push({ kind: "any" });
|
|
97
|
+
else {
|
|
98
|
+
paramNames.push("splat");
|
|
99
|
+
tokens.push({
|
|
100
|
+
kind: "any",
|
|
101
|
+
name: "splat"
|
|
102
|
+
});
|
|
103
|
+
splatTaken = true;
|
|
104
|
+
}
|
|
105
|
+
index++;
|
|
106
|
+
} else {
|
|
107
|
+
let end = index + 1;
|
|
108
|
+
while (end < source.length && source[end] !== ":" && source[end] !== "*") end++;
|
|
109
|
+
pushText(tokens, source.slice(index, end));
|
|
110
|
+
index = end;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
tokens,
|
|
115
|
+
paramNames
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/** Text in which only `*` is special. */
|
|
119
|
+
function parseStars(tokens, text) {
|
|
120
|
+
const parts = text.split("*");
|
|
121
|
+
pushText(tokens, parts[0]);
|
|
122
|
+
for (let k = 1; k < parts.length; k++) {
|
|
123
|
+
tokens.push({ kind: "any" });
|
|
124
|
+
pushText(tokens, parts[k]);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Drop an `any` that directly follows another `any`: the first takes every
|
|
129
|
+
* unit the pair could take, so the second always matches ''. Every other step
|
|
130
|
+
* needs at least one unit, so a path of length m faces at most 2m + 1 steps.
|
|
131
|
+
*/
|
|
132
|
+
function prepare(tokens) {
|
|
133
|
+
const steps = [];
|
|
134
|
+
for (const token of tokens) if (!(token.kind === "any" && steps[steps.length - 1]?.kind === "any")) steps.push(token);
|
|
135
|
+
const starts = new Int32Array(steps.length + 1);
|
|
136
|
+
steps.forEach((step, i) => {
|
|
137
|
+
const shortest = step.kind === "text" ? step.text.length : step.kind === "any" ? 0 : 1;
|
|
138
|
+
starts[i + 1] = starts[i] + shortest;
|
|
139
|
+
});
|
|
140
|
+
return {
|
|
141
|
+
steps,
|
|
142
|
+
starts,
|
|
143
|
+
minLength: starts[steps.length]
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
function stepBack(step, path, start, next, row) {
|
|
147
|
+
let found = 0;
|
|
148
|
+
if (step.kind === "text") {
|
|
149
|
+
for (let d = row.length - 1; d >= 0; d--) {
|
|
150
|
+
const value = next[d] === 1 && path.startsWith(step.text, start + d) ? 1 : 0;
|
|
151
|
+
row[d] = value;
|
|
152
|
+
found |= value;
|
|
153
|
+
}
|
|
154
|
+
return found === 1;
|
|
155
|
+
}
|
|
156
|
+
const kind = step.kind;
|
|
157
|
+
let after = 0;
|
|
158
|
+
for (let d = row.length - 1; d >= 0; d--) {
|
|
159
|
+
const value = kind === "any" ? next[d] === 1 || after === 1 && accepts(kind, path.charCodeAt(start + d)) : (next[d] === 1 || after === 1) && accepts(kind, path.charCodeAt(start + d));
|
|
160
|
+
row[d] = value ? 1 : 0;
|
|
161
|
+
after = row[d];
|
|
162
|
+
found |= after;
|
|
163
|
+
}
|
|
164
|
+
return found === 1;
|
|
165
|
+
}
|
|
166
|
+
/** The row after the last step: only the end of the path (d = slack) finishes. */
|
|
167
|
+
function endRow(width) {
|
|
168
|
+
const row = new Uint8Array(width);
|
|
169
|
+
row[width - 1] = 1;
|
|
170
|
+
return row;
|
|
171
|
+
}
|
|
172
|
+
/** Checks that reject most paths before any row is built. */
|
|
173
|
+
function quickReject({ steps, minLength }, path) {
|
|
174
|
+
const first = steps[0];
|
|
175
|
+
const last = steps[steps.length - 1];
|
|
176
|
+
return path.length < minLength || first?.kind === "text" && !path.startsWith(first.text) || last?.kind === "text" && !path.endsWith(last.text);
|
|
177
|
+
}
|
|
178
|
+
/** Whether the steps match the whole path. Keeps two rows. */
|
|
179
|
+
function matches(prepared, path) {
|
|
180
|
+
if (quickReject(prepared, path)) return false;
|
|
181
|
+
const { steps, starts, minLength } = prepared;
|
|
182
|
+
let next = endRow(path.length - minLength + 1);
|
|
183
|
+
let row = new Uint8Array(next.length);
|
|
184
|
+
const first = steps[0]?.kind === "text" ? 1 : 0;
|
|
185
|
+
for (let i = steps.length - 1; i >= first; i--) {
|
|
186
|
+
if (!stepBack(steps[i], path, starts[i], next, row)) return false;
|
|
187
|
+
const done = next;
|
|
188
|
+
next = row;
|
|
189
|
+
row = done;
|
|
190
|
+
}
|
|
191
|
+
return next[0] === 1;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Where a step that begins at p (row index d) ends: the longest choice after
|
|
195
|
+
* which the rest still matches. `next` is the row of the following step.
|
|
196
|
+
*/
|
|
197
|
+
function greedyEnd(step, path, p, d, next) {
|
|
198
|
+
if (step.kind === "text") return p + step.text.length;
|
|
199
|
+
const shortest = step.kind === "any" ? 0 : 1;
|
|
200
|
+
const longest = next.length - 1 - d + shortest;
|
|
201
|
+
let k = 0;
|
|
202
|
+
while (k < longest && accepts(step.kind, path.charCodeAt(p + k))) k++;
|
|
203
|
+
while (k > shortest && next[d + k - shortest] !== 1) k--;
|
|
204
|
+
return p + k;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* End positions of steps 0..upTo in the match that JS backtracking returns
|
|
208
|
+
* (each wildcard, left to right, takes the longest run that still lets the
|
|
209
|
+
* rest match), or null. The backward pass keeps a copy of every `size`-th
|
|
210
|
+
* row; the forward pass rebuilds one block of rows at a time into a fixed
|
|
211
|
+
* pool. About 2 * sqrt(n) rows are alive at once, and each row is computed at
|
|
212
|
+
* most twice.
|
|
213
|
+
*/
|
|
214
|
+
function greedyEnds(prepared, path, upTo) {
|
|
215
|
+
if (quickReject(prepared, path)) return null;
|
|
216
|
+
const { steps, starts, minLength } = prepared;
|
|
217
|
+
const n = steps.length;
|
|
218
|
+
const width = path.length - minLength + 1;
|
|
219
|
+
const size = n * width <= 65536 ? 1 : Math.ceil(Math.sqrt(n));
|
|
220
|
+
const saved = /* @__PURE__ */ new Map([[n, endRow(width)]]);
|
|
221
|
+
let next = endRow(width);
|
|
222
|
+
let row = new Uint8Array(width);
|
|
223
|
+
const first = steps[0]?.kind === "text" ? 1 : 0;
|
|
224
|
+
for (let i = n - 1; i >= first; i--) {
|
|
225
|
+
if (!stepBack(steps[i], path, starts[i], next, row)) return null;
|
|
226
|
+
if (i % size === 0) saved.set(i, row.slice());
|
|
227
|
+
const done = next;
|
|
228
|
+
next = row;
|
|
229
|
+
row = done;
|
|
230
|
+
}
|
|
231
|
+
if (next[0] !== 1) return null;
|
|
232
|
+
const pool = Array.from({ length: size }, () => new Uint8Array(width));
|
|
233
|
+
let top = 0;
|
|
234
|
+
const rowAt = (r) => r === top ? saved.get(r) : pool[r % size];
|
|
235
|
+
const ends = new Int32Array(upTo + 1);
|
|
236
|
+
let p = 0;
|
|
237
|
+
for (let i = 0; i <= upTo; i++) {
|
|
238
|
+
if (i + 1 > top) {
|
|
239
|
+
top = Math.min(n, Math.ceil((i + 1) / size) * size);
|
|
240
|
+
for (let r = top - 1; r > i; r--) stepBack(steps[r], path, starts[r], rowAt(r + 1), pool[r % size]);
|
|
241
|
+
}
|
|
242
|
+
p = greedyEnd(steps[i], path, p, p - starts[i], rowAt(i + 1));
|
|
243
|
+
ends[i] = p;
|
|
244
|
+
}
|
|
245
|
+
return ends;
|
|
246
|
+
}
|
|
247
|
+
/** The regex the earlier string-building compiler produced, for the deprecated `regex` view. */
|
|
248
|
+
function toRegExp(tokens) {
|
|
249
|
+
let body = "";
|
|
250
|
+
for (const token of tokens) if (token.kind === "text") body += token.text.replace(/[.+?^${}()|[\]\\:]/g, "\\$&");
|
|
251
|
+
else if (token.kind === "seg") body += `(?<${token.name}>[^/]+)`;
|
|
252
|
+
else body += token.name ? `(?<${token.name}>.*)` : ".*";
|
|
253
|
+
return new RegExp(`^${body}$`);
|
|
254
|
+
}
|
|
255
|
+
const compileCache = /* @__PURE__ */ new Map();
|
|
256
|
+
function compile(source) {
|
|
257
|
+
const cached = lruGet(compileCache, source);
|
|
258
|
+
if (cached) return cached;
|
|
259
|
+
const { tokens, paramNames } = parseCapture(source);
|
|
260
|
+
let error;
|
|
261
|
+
const seen = /* @__PURE__ */ new Set();
|
|
262
|
+
for (const name of paramNames) {
|
|
263
|
+
if (seen.has(name)) error ??= `Duplicate capture group name "${name}"`;
|
|
264
|
+
else if (name.charCodeAt(0) >= 48 && name.charCodeAt(0) <= 57) error ??= `Invalid capture group name "${name}"`;
|
|
265
|
+
seen.add(name);
|
|
266
|
+
}
|
|
267
|
+
const prepared = prepare(tokens);
|
|
268
|
+
let lastNamed = -1;
|
|
269
|
+
prepared.steps.forEach((step, i) => {
|
|
270
|
+
if (step.kind !== "text" && step.name) lastNamed = i;
|
|
271
|
+
});
|
|
272
|
+
let regex;
|
|
273
|
+
const compiled = {
|
|
274
|
+
...prepared,
|
|
275
|
+
paramNames,
|
|
276
|
+
error,
|
|
277
|
+
lastNamed,
|
|
278
|
+
get regex() {
|
|
279
|
+
return regex ??= toRegExp(parseCapture(source).tokens);
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
lruSet(compileCache, source, compiled);
|
|
283
|
+
return compiled;
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Parse a capture pattern. Throws a SyntaxError for a malformed one: a repeated
|
|
287
|
+
* name (`/:id/:id`, `/:splat/*`) or a name that starts with a digit (`/:1`).
|
|
288
|
+
*/
|
|
289
|
+
function compilePattern(source) {
|
|
290
|
+
const compiled = compile(source);
|
|
291
|
+
if (compiled.error) throw new SyntaxError(compiled.error);
|
|
292
|
+
return compiled;
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Match a pattern against a pathname. Returns captured params, or null.
|
|
296
|
+
* A malformed pattern (e.g. a repeated name like `/:splat/*`) also returns
|
|
297
|
+
* null, so one bad rule cannot fail unrelated requests.
|
|
298
|
+
*/
|
|
299
|
+
function matchPatternCaptures(pattern, pathname) {
|
|
300
|
+
const compiled = compile(pattern);
|
|
301
|
+
if (compiled.error) return null;
|
|
302
|
+
const { steps, lastNamed } = compiled;
|
|
303
|
+
const ends = lastNamed === -1 ? void 0 : greedyEnds(compiled, pathname, lastNamed);
|
|
304
|
+
if (ends === null || ends === void 0 && !matches(compiled, pathname)) return null;
|
|
305
|
+
const params = Object.create(null);
|
|
306
|
+
for (const name of compiled.paramNames) params[name] = "";
|
|
307
|
+
for (let i = 0; ends && i <= lastNamed; i++) {
|
|
308
|
+
const step = steps[i];
|
|
309
|
+
if (step.kind !== "text" && step.name) params[step.name] = pathname.slice(i === 0 ? 0 : ends[i - 1], ends[i]);
|
|
310
|
+
}
|
|
311
|
+
return params;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Match a pattern against a pathname (boolean form). Malformed patterns yield
|
|
315
|
+
* `false` rather than throwing (see `matchPatternCaptures`).
|
|
316
|
+
*/
|
|
317
|
+
function matchPattern(pattern, pathname) {
|
|
318
|
+
const compiled = compile(pattern);
|
|
319
|
+
return compiled.error === void 0 && matches(compiled, pathname);
|
|
320
|
+
}
|
|
321
|
+
const literalCache = /* @__PURE__ */ new Map();
|
|
322
|
+
/**
|
|
323
|
+
* Match a pattern against a pathname using LITERAL semantics — no named
|
|
324
|
+
* captures. Only `*` is special (matches any characters including `/`); every
|
|
325
|
+
* other character (including `:`) is treated as a literal.
|
|
326
|
+
*
|
|
327
|
+
* Used for header rules, which never had `:name` capture syntax; existing tenant configs may include literal
|
|
328
|
+
* `:` (e.g. `/api/v1:health`, `:batchGet`-style URLs). Routing rules
|
|
329
|
+
* (`redirects`/`rewrites`/`fallbacks`) use the capture-aware `compilePattern`.
|
|
330
|
+
*/
|
|
331
|
+
function matchLiteralPattern(pattern, pathname) {
|
|
332
|
+
let prepared = lruGet(literalCache, pattern);
|
|
333
|
+
if (!prepared) {
|
|
334
|
+
const tokens = [];
|
|
335
|
+
parseStars(tokens, pattern);
|
|
336
|
+
prepared = prepare(tokens);
|
|
337
|
+
lruSet(literalCache, pattern, prepared);
|
|
338
|
+
}
|
|
339
|
+
return matches(prepared, pathname);
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Substitute `:name` and `:name*` tokens in a destination string with the
|
|
343
|
+
* matching named captures from `params`. `:splat` works for legacy `*` patterns
|
|
344
|
+
* because `compilePattern` captures anonymous `*` as `splat`.
|
|
345
|
+
*/
|
|
346
|
+
function substituteParams(destination, params) {
|
|
347
|
+
const result = destination.replace(/:([A-Za-z0-9_]+)\*?/g, (whole, name) => {
|
|
348
|
+
return params[name] ?? whole;
|
|
349
|
+
});
|
|
350
|
+
if (/^[/\\]{2}/.test(result) && !/^[/\\]{2}/.test(destination)) return "/" + result.replace(/^[/\\]+/, "");
|
|
351
|
+
return result;
|
|
352
|
+
}
|
|
353
|
+
// src/headers.ts
|
|
354
|
+
/**
|
|
355
|
+
* Headers that rules may never set on a shared domain. void.app is not on the
|
|
356
|
+
* Public Suffix List, so a `Set-Cookie` with `Domain=.void.app` reaches every
|
|
357
|
+
* tenant. `Clear-Site-Data` is filtered per directive by
|
|
358
|
+
* {@link sanitizeClearSiteData}; per-host headers such as HSTS stay allowed.
|
|
359
|
+
*/
|
|
360
|
+
const BLOCKED_HEADERS = /* @__PURE__ */ new Set(["set-cookie"]);
|
|
361
|
+
/**
|
|
362
|
+
* Parse one list member into its quoted-string content, or `null` when it is not
|
|
363
|
+
* a well-formed quoted-string. Implements RFC 7230's
|
|
364
|
+
* `quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE`: it must be wrapped
|
|
365
|
+
* in double quotes, a backslash escapes the next character, and an unescaped
|
|
366
|
+
* inner quote (or a dangling escape) is malformed.
|
|
367
|
+
*/
|
|
368
|
+
function parseQuotedString(member) {
|
|
369
|
+
if (member.length < 2 || member[0] !== "\"" || member[member.length - 1] !== "\"") return null;
|
|
370
|
+
let content = "";
|
|
371
|
+
for (let i = 1; i < member.length - 1; i += 1) {
|
|
372
|
+
const char = member[i];
|
|
373
|
+
if (char === "\\") {
|
|
374
|
+
i += 1;
|
|
375
|
+
if (i >= member.length - 1) return null;
|
|
376
|
+
content += member[i];
|
|
377
|
+
} else if (char === "\"") return null;
|
|
378
|
+
else content += char;
|
|
379
|
+
}
|
|
380
|
+
return content;
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Parse a `Clear-Site-Data` header value into its list members. The value is a
|
|
384
|
+
* comma-separated list of quoted-strings (W3C Clear-Site-Data); a comma inside a
|
|
385
|
+
* quoted-string does not split a member. Empty members are dropped.
|
|
386
|
+
*/
|
|
387
|
+
function parseClearSiteData(value) {
|
|
388
|
+
const members = [];
|
|
389
|
+
const pushMember = (slice) => {
|
|
390
|
+
const raw = slice.trim();
|
|
391
|
+
if (raw.length > 0) members.push({
|
|
392
|
+
raw,
|
|
393
|
+
directive: parseQuotedString(raw)
|
|
394
|
+
});
|
|
395
|
+
};
|
|
396
|
+
let start = 0;
|
|
397
|
+
let inQuotes = false;
|
|
398
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
399
|
+
const char = value[i];
|
|
400
|
+
if (inQuotes) {
|
|
401
|
+
if (char === "\\") i += 1;
|
|
402
|
+
else if (char === "\"") inQuotes = false;
|
|
403
|
+
} else if (char === "\"") inQuotes = true;
|
|
404
|
+
else if (char === ",") {
|
|
405
|
+
pushMember(value.slice(start, i));
|
|
406
|
+
start = i + 1;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
pushMember(value.slice(start));
|
|
410
|
+
return members;
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Sanitize a `Clear-Site-Data` value so a tenant rule can't clear cookies across
|
|
414
|
+
* the shared *.void.app boundary, while still allowing the safe directives.
|
|
415
|
+
*
|
|
416
|
+
* Only `"cookies"` and `"*"` clear cookies for the registrable domain (and thus
|
|
417
|
+
* every tenant's subdomain). `"cache"`, `"storage"`, `"executionContexts"`, and
|
|
418
|
+
* any future quoted directive are origin-scoped — each subdomain is its own
|
|
419
|
+
* origin — so they are kept verbatim. Malformed members are dropped (a browser
|
|
420
|
+
* ignores them, and dropping forecloses a lenient parser honoring them).
|
|
421
|
+
*
|
|
422
|
+
* Returns the filtered value, or `null` when nothing safe remains: a `"*"`
|
|
423
|
+
* includes cookies and can't be expressed without them, and a value that is only
|
|
424
|
+
* `"cookies"` collapses to empty.
|
|
425
|
+
*/
|
|
426
|
+
function sanitizeClearSiteData(value) {
|
|
427
|
+
const kept = [];
|
|
428
|
+
for (const { raw, directive } of parseClearSiteData(value)) {
|
|
429
|
+
const normalized = directive?.toLowerCase();
|
|
430
|
+
if (normalized === "*") return null;
|
|
431
|
+
if (directive === null || normalized === "cookies") continue;
|
|
432
|
+
kept.push(raw);
|
|
433
|
+
}
|
|
434
|
+
return kept.length > 0 ? kept.join(", ") : null;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Apply matching header rules to a response.
|
|
438
|
+
* All matching rules merge; last match wins for same header name.
|
|
439
|
+
* Returns the original response unchanged when no rules or no matches.
|
|
440
|
+
*/
|
|
441
|
+
function applyHeaderRules(response, pathname, rules, policy) {
|
|
442
|
+
if (!rules || rules.length === 0) return response;
|
|
443
|
+
const matched = [];
|
|
444
|
+
for (const rule of rules) if (matchLiteralPattern(rule.pattern, pathname)) matched.push(...rule.headers);
|
|
445
|
+
if (matched.length === 0) return response;
|
|
446
|
+
const newResponse = new Response(response.body, response);
|
|
447
|
+
const isolateSharedDomainCookies = policy?.cookieIsolation !== "origin";
|
|
448
|
+
const rawOriginClearSiteData = isolateSharedDomainCookies ? response.headers.get("clear-site-data") : null;
|
|
449
|
+
const originClearSiteData = rawOriginClearSiteData === null ? null : sanitizeClearSiteData(rawOriginClearSiteData);
|
|
450
|
+
for (const [name, value] of matched) {
|
|
451
|
+
const lowerName = name.toLowerCase();
|
|
452
|
+
if (isolateSharedDomainCookies && BLOCKED_HEADERS.has(lowerName)) continue;
|
|
453
|
+
if (isolateSharedDomainCookies && lowerName === "clear-site-data") {
|
|
454
|
+
const safe = sanitizeClearSiteData(value);
|
|
455
|
+
if (safe !== null) newResponse.headers.set(name, safe);
|
|
456
|
+
else if (originClearSiteData !== null) newResponse.headers.set(name, originClearSiteData);
|
|
457
|
+
else newResponse.headers.delete(name);
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
newResponse.headers.set(name, value);
|
|
461
|
+
}
|
|
462
|
+
return newResponse;
|
|
463
|
+
}
|
|
464
|
+
// src/routing-rules.ts
|
|
465
|
+
/**
|
|
466
|
+
* Check routing rules (redirects + rewrites) against a request pathname.
|
|
467
|
+
*
|
|
468
|
+
* **First match wins** — matches Netlify `_redirects` and Vercel `vercel.json`
|
|
469
|
+
* semantics: users put more-specific rules above more-general ones, and the
|
|
470
|
+
* first rule whose source matches takes effect. (Header rules in this same
|
|
471
|
+
* package use last-match-wins for compatibility with Netlify `_headers`,
|
|
472
|
+
* which is the opposite of `_redirects`. The asymmetry is intentional.)
|
|
473
|
+
*
|
|
474
|
+
* `requestHost` is the WHATWG `url.hostname` (lowercase, port-stripped).
|
|
475
|
+
* Rules with a `host` field are skipped when `rule.host !== requestHost`;
|
|
476
|
+
* path-only rules apply to every host bound to the project.
|
|
477
|
+
*
|
|
478
|
+
* Returns a discriminated result. The caller is responsible for building the
|
|
479
|
+
* actual `Response` for redirects (so it can merge the request's query string
|
|
480
|
+
* into the `Location` header).
|
|
481
|
+
*/
|
|
482
|
+
function applyRoutingRules(pathname, rules, requestHost) {
|
|
483
|
+
if (!rules?.length) return null;
|
|
484
|
+
for (const rule of rules) {
|
|
485
|
+
if (rule.host && rule.host !== requestHost) continue;
|
|
486
|
+
try {
|
|
487
|
+
compilePattern(rule.source);
|
|
488
|
+
} catch (err) {
|
|
489
|
+
console.warn(`[dispatch] skipping routing rule with invalid source ${JSON.stringify(rule.source)}: ${err instanceof Error ? err.message : String(err)}`);
|
|
490
|
+
continue;
|
|
491
|
+
}
|
|
492
|
+
const params = matchPatternCaptures(rule.source, pathname);
|
|
493
|
+
if (!params) continue;
|
|
494
|
+
const destination = substituteParams(rule.destination, params);
|
|
495
|
+
if (rule.status === 200) return {
|
|
496
|
+
type: "rewrite",
|
|
497
|
+
destination
|
|
498
|
+
};
|
|
499
|
+
return {
|
|
500
|
+
type: "redirect",
|
|
501
|
+
destination,
|
|
502
|
+
status: rule.status
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
return null;
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Merge a request's query string into a redirect destination.
|
|
509
|
+
*
|
|
510
|
+
* If the destination already contains a `?`, its parameters take precedence
|
|
511
|
+
* over the request's. Otherwise the request's query is appended verbatim.
|
|
512
|
+
*
|
|
513
|
+
* A `#fragment` on the destination is stripped before the merge and
|
|
514
|
+
* re-appended afterwards, so `/new#faq` + `?utm=x` becomes `/new?utm=x#faq`
|
|
515
|
+
* rather than `/new#faq?utm=x` (which browsers treat as fragment text).
|
|
516
|
+
*/
|
|
517
|
+
function mergeQueryIntoLocation(destination, requestSearch) {
|
|
518
|
+
if (!requestSearch || requestSearch === "?") return destination;
|
|
519
|
+
const fragIdx = destination.indexOf("#");
|
|
520
|
+
const base = fragIdx === -1 ? destination : destination.slice(0, fragIdx);
|
|
521
|
+
const fragment = fragIdx === -1 ? "" : destination.slice(fragIdx);
|
|
522
|
+
const destQueryIdx = base.indexOf("?");
|
|
523
|
+
if (destQueryIdx === -1) return base + requestSearch + fragment;
|
|
524
|
+
if (destQueryIdx === base.length - 1) return base.slice(0, destQueryIdx) + fragment;
|
|
525
|
+
const reqParams = new URLSearchParams(requestSearch);
|
|
526
|
+
const destParams = new URLSearchParams(base.slice(destQueryIdx + 1));
|
|
527
|
+
for (const [key, value] of reqParams) if (!destParams.has(key)) destParams.append(key, value);
|
|
528
|
+
return base.slice(0, destQueryIdx) + "?" + destParams.toString() + fragment;
|
|
529
|
+
}
|
|
530
|
+
// src/runtime.ts
|
|
531
|
+
/**
|
|
532
|
+
* Create the thin Worker used by direct static, SPA, and SSG deployments.
|
|
533
|
+
* Routing semantics intentionally match the hosted dispatch Worker: redirects
|
|
534
|
+
* and rewrites run before assets, fallback rewrites run only after an asset
|
|
535
|
+
* miss, and response-header rules apply to the effective pathname.
|
|
536
|
+
*/
|
|
537
|
+
function createStaticEdgeHandler(config) {
|
|
538
|
+
return { async fetch(request, env) {
|
|
539
|
+
const originalUrl = new URL(request.url);
|
|
540
|
+
if (request.method === "GET" && originalUrl.pathname === "/__nosam/ready") {
|
|
541
|
+
if (!config.versionMetadataBinding) return Response.json({ ready: true });
|
|
542
|
+
const metadata = env[config.versionMetadataBinding];
|
|
543
|
+
return Response.json({
|
|
544
|
+
ready: true,
|
|
545
|
+
versionId: metadata?.id
|
|
546
|
+
}, { headers: { "cache-control": "no-store" } });
|
|
547
|
+
}
|
|
548
|
+
if (config.alwaysUseHttps) {
|
|
549
|
+
const redirect = redirectToHttps(request);
|
|
550
|
+
if (redirect) return redirect;
|
|
551
|
+
}
|
|
552
|
+
let effectiveUrl = new URL(originalUrl);
|
|
553
|
+
let effectiveRequest = request;
|
|
554
|
+
const route = applyRoutingRules(effectiveUrl.pathname, config.redirectRules, effectiveUrl.hostname);
|
|
555
|
+
if (route?.type === "redirect") return applyHeaderRules(new Response(null, {
|
|
556
|
+
status: route.status,
|
|
557
|
+
headers: { location: mergeQueryIntoLocation(route.destination, effectiveUrl.search) }
|
|
558
|
+
}), effectiveUrl.pathname, config.headerRules, { cookieIsolation: "origin" });
|
|
559
|
+
if (route?.type === "rewrite") {
|
|
560
|
+
effectiveUrl = rewriteUrl(effectiveUrl, route.destination);
|
|
561
|
+
effectiveRequest = rewriteRequest(request, effectiveUrl, originalUrl.toString());
|
|
562
|
+
}
|
|
563
|
+
let response = await env.ASSETS.fetch(effectiveRequest);
|
|
564
|
+
if (response.status === 404) {
|
|
565
|
+
const fallback = applyRoutingRules(effectiveUrl.pathname, config.fallbackRules, effectiveUrl.hostname);
|
|
566
|
+
if (fallback?.type === "rewrite") {
|
|
567
|
+
effectiveUrl = rewriteUrl(effectiveUrl, fallback.destination);
|
|
568
|
+
effectiveRequest = rewriteRequest(request, effectiveUrl, originalUrl.toString());
|
|
569
|
+
response = await env.ASSETS.fetch(effectiveRequest);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
return applyHeaderRules(response, effectiveUrl.pathname, config.headerRules, { cookieIsolation: "origin" });
|
|
573
|
+
} };
|
|
574
|
+
}
|
|
575
|
+
function rewriteUrl(url, destination) {
|
|
576
|
+
const rewritten = new URL(url);
|
|
577
|
+
const destinationUrl = new URL(destination, url);
|
|
578
|
+
rewritten.pathname = destinationUrl.pathname;
|
|
579
|
+
rewritten.search = destinationUrl.search || url.search;
|
|
580
|
+
return rewritten;
|
|
581
|
+
}
|
|
582
|
+
function rewriteRequest(request, url, originalUrl) {
|
|
583
|
+
const rewritten = new Request(url.toString(), request);
|
|
584
|
+
rewritten.headers.set("X-Nosam-Original-URL", originalUrl);
|
|
585
|
+
return rewritten;
|
|
586
|
+
}
|
|
587
|
+
// src/static.ts
|
|
588
|
+
/**
|
|
589
|
+
* Percent-decode a request pathname for a manifest lookup, honoring required
|
|
590
|
+
* URL encodings and encoded square brackets. Returns the raw value unchanged
|
|
591
|
+
* on a malformed sequence (e.g. a lone `%`) or other over-encoded spellings.
|
|
592
|
+
*
|
|
593
|
+
* Request pathnames arrive percent-encoded — WHATWG `URL.pathname` never
|
|
594
|
+
* decodes — but manifest keys are the asset's decoded on-disk path (a file
|
|
595
|
+
* named `oxc masthead.riv` is stored under `/assets/oxc masthead.riv`, not
|
|
596
|
+
* `%20`). Callers try the raw key first, then this decoded form.
|
|
597
|
+
*
|
|
598
|
+
* The decoded form is accepted only when re-encoding it reproduces the request
|
|
599
|
+
* path (up to percent-escape letter case and square-bracket encoding). Next.js
|
|
600
|
+
* encodes brackets in dynamic-page chunk URLs even though URL.pathname leaves
|
|
601
|
+
* them literal. Other accepted escapes are characters a URL MUST encode
|
|
602
|
+
* (space, `#`, non-ASCII, …). This rejects
|
|
603
|
+
* over-encoded spellings of ordinary path text (`%2F`→`/`, `%61`→`a`, `%5F`→`_`,
|
|
604
|
+
* `%2e%2e`→`..`), which a browser would never send and which would otherwise let
|
|
605
|
+
* a request reconstruct a guarded path (`/assets%2Fx`, `/%61ssets/x`,
|
|
606
|
+
* `/%5F%5Fvoid/x`) and serve the manifest entry while the raw-`url.pathname`
|
|
607
|
+
* policy gates — the `/__nosam/*` reserved-route block, the hashed-asset prefix
|
|
608
|
+
* gate, and the header/redirect rules — never fire. The URL pathname setter
|
|
609
|
+
* applies exactly the WHATWG "path percent-encode set", making it the canonical
|
|
610
|
+
* re-encoder.
|
|
611
|
+
*
|
|
612
|
+
* Known limitation: a file whose name contains a literal `%` (e.g. `logo%20.svg`,
|
|
613
|
+
* requested as `logo%2520.svg`) is not resolved — the path encoder leaves `%`
|
|
614
|
+
* as-is, so the round-trip can't reproduce the double-escaped request.
|
|
615
|
+
*/
|
|
616
|
+
function safeDecodePathname(pathname) {
|
|
617
|
+
let decoded;
|
|
618
|
+
try {
|
|
619
|
+
decoded = decodeURIComponent(pathname);
|
|
620
|
+
} catch {
|
|
621
|
+
return pathname;
|
|
622
|
+
}
|
|
623
|
+
if (decoded === pathname) return pathname;
|
|
624
|
+
const canonical = reencodePathname(decoded);
|
|
625
|
+
if (canonical === null) return pathname;
|
|
626
|
+
const normalized = normalizePercentCase(pathname).replace(/%5B/g, "[").replace(/%5D/g, "]");
|
|
627
|
+
return normalizePercentCase(canonical) === normalized ? decoded : pathname;
|
|
628
|
+
}
|
|
629
|
+
/** Uppercase the hex digits of every `%xx` escape so encodings compare equal
|
|
630
|
+
* regardless of the letter case a client used. */
|
|
631
|
+
function normalizePercentCase(pathname) {
|
|
632
|
+
return pathname.replace(/%[0-9a-fA-F]{2}/g, (escape) => escape.toUpperCase());
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* Serialize a decoded path back to a safe URL pathname via the WHATWG "path
|
|
636
|
+
* percent-encode set" (the `URL.pathname` setter). Returns null if the value
|
|
637
|
+
* can't be encoded. Used to canonicalize the decoded lookup key and to make a
|
|
638
|
+
* redirect Location URL-safe.
|
|
639
|
+
*/
|
|
640
|
+
function reencodePathname(pathname) {
|
|
641
|
+
try {
|
|
642
|
+
const encoder = new URL("https://nosam.invalid/");
|
|
643
|
+
encoder.pathname = pathname;
|
|
644
|
+
return encoder.pathname;
|
|
645
|
+
} catch {
|
|
646
|
+
return null;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Match a pathname against the manifest via exact match + html_handling rules
|
|
651
|
+
* (no not-found fallback). Returns null when nothing matches.
|
|
652
|
+
*/
|
|
653
|
+
function matchManifestEntry(pathname, manifest, htmlHandling) {
|
|
654
|
+
if (manifest[pathname]) return {
|
|
655
|
+
path: pathname,
|
|
656
|
+
hash: manifest[pathname]
|
|
657
|
+
};
|
|
658
|
+
switch (htmlHandling) {
|
|
659
|
+
case "auto-trailing-slash": {
|
|
660
|
+
const withHtml = pathname + ".html";
|
|
661
|
+
if (manifest[withHtml]) return {
|
|
662
|
+
path: withHtml,
|
|
663
|
+
hash: manifest[withHtml]
|
|
664
|
+
};
|
|
665
|
+
const withIndex = (pathname.endsWith("/") ? pathname : pathname + "/") + "index.html";
|
|
666
|
+
if (manifest[withIndex]) return {
|
|
667
|
+
path: withIndex,
|
|
668
|
+
hash: manifest[withIndex]
|
|
669
|
+
};
|
|
670
|
+
break;
|
|
671
|
+
}
|
|
672
|
+
case "force-trailing-slash": {
|
|
673
|
+
if (!pathname.endsWith("/") && pathname !== "/") {
|
|
674
|
+
const withIndex = pathname + "/index.html";
|
|
675
|
+
if (manifest[withIndex]) return {
|
|
676
|
+
path: withIndex,
|
|
677
|
+
hash: manifest[withIndex],
|
|
678
|
+
redirect: pathname + "/"
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
const indexPath = pathname + "index.html";
|
|
682
|
+
if (manifest[indexPath]) return {
|
|
683
|
+
path: indexPath,
|
|
684
|
+
hash: manifest[indexPath]
|
|
685
|
+
};
|
|
686
|
+
break;
|
|
687
|
+
}
|
|
688
|
+
case "drop-trailing-slash": {
|
|
689
|
+
if (pathname === "/") {
|
|
690
|
+
if (manifest["/index.html"]) return {
|
|
691
|
+
path: "/index.html",
|
|
692
|
+
hash: manifest["/index.html"]
|
|
693
|
+
};
|
|
694
|
+
break;
|
|
695
|
+
}
|
|
696
|
+
if (pathname.endsWith("/")) {
|
|
697
|
+
const withoutSlash = pathname.slice(0, -1);
|
|
698
|
+
const withHtml = withoutSlash + ".html";
|
|
699
|
+
if (manifest[withHtml]) return {
|
|
700
|
+
path: withHtml,
|
|
701
|
+
hash: manifest[withHtml],
|
|
702
|
+
redirect: withoutSlash
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
const withHtml = pathname + ".html";
|
|
706
|
+
if (manifest[withHtml]) return {
|
|
707
|
+
path: withHtml,
|
|
708
|
+
hash: manifest[withHtml]
|
|
709
|
+
};
|
|
710
|
+
break;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
return null;
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* Resolve a request pathname to a manifest entry using AssetConfig rules.
|
|
717
|
+
* Replicates Cloudflare Workers Assets path resolution behavior.
|
|
718
|
+
*/
|
|
719
|
+
function resolveStaticPath(pathname, manifest, config) {
|
|
720
|
+
const htmlHandling = config.html_handling ?? "auto-trailing-slash";
|
|
721
|
+
let matched = matchManifestEntry(pathname, manifest, htmlHandling);
|
|
722
|
+
if (!matched) {
|
|
723
|
+
const decoded = safeDecodePathname(pathname);
|
|
724
|
+
if (decoded !== pathname) {
|
|
725
|
+
matched = matchManifestEntry(decoded, manifest, htmlHandling);
|
|
726
|
+
if (matched?.redirect !== void 0) {
|
|
727
|
+
const safeRedirect = reencodePathname(matched.redirect);
|
|
728
|
+
if (safeRedirect !== null) matched = {
|
|
729
|
+
...matched,
|
|
730
|
+
redirect: safeRedirect
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
if (matched) return matched;
|
|
736
|
+
switch (config.not_found_handling ?? "none") {
|
|
737
|
+
case "single-page-application":
|
|
738
|
+
if (manifest["/index.html"]) return {
|
|
739
|
+
path: "/index.html",
|
|
740
|
+
hash: manifest["/index.html"],
|
|
741
|
+
spa: true
|
|
742
|
+
};
|
|
743
|
+
break;
|
|
744
|
+
case "404-page": if (manifest["/404.html"]) return {
|
|
745
|
+
path: "/404.html",
|
|
746
|
+
hash: manifest["/404.html"],
|
|
747
|
+
notFound: true
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
return null;
|
|
751
|
+
}
|
|
752
|
+
const MIME_TYPES = {
|
|
753
|
+
html: "text/html; charset=utf-8",
|
|
754
|
+
htm: "text/html; charset=utf-8",
|
|
755
|
+
css: "text/css; charset=utf-8",
|
|
756
|
+
js: "text/javascript; charset=utf-8",
|
|
757
|
+
mjs: "text/javascript; charset=utf-8",
|
|
758
|
+
json: "application/json; charset=utf-8",
|
|
759
|
+
xml: "application/xml; charset=utf-8",
|
|
760
|
+
svg: "image/svg+xml; charset=utf-8",
|
|
761
|
+
txt: "text/plain; charset=utf-8",
|
|
762
|
+
csv: "text/csv; charset=utf-8",
|
|
763
|
+
md: "text/markdown; charset=utf-8",
|
|
764
|
+
markdown: "text/markdown; charset=utf-8",
|
|
765
|
+
yaml: "text/yaml; charset=utf-8",
|
|
766
|
+
yml: "text/yaml; charset=utf-8",
|
|
767
|
+
toml: "application/toml",
|
|
768
|
+
png: "image/png",
|
|
769
|
+
jpg: "image/jpeg",
|
|
770
|
+
jpeg: "image/jpeg",
|
|
771
|
+
gif: "image/gif",
|
|
772
|
+
ico: "image/x-icon",
|
|
773
|
+
webp: "image/webp",
|
|
774
|
+
avif: "image/avif",
|
|
775
|
+
woff: "font/woff",
|
|
776
|
+
woff2: "font/woff2",
|
|
777
|
+
ttf: "font/ttf",
|
|
778
|
+
otf: "font/otf",
|
|
779
|
+
eot: "application/vnd.ms-fontobject",
|
|
780
|
+
pdf: "application/pdf",
|
|
781
|
+
wasm: "application/wasm",
|
|
782
|
+
webmanifest: "application/manifest+json; charset=utf-8",
|
|
783
|
+
map: "application/json; charset=utf-8",
|
|
784
|
+
mp4: "video/mp4",
|
|
785
|
+
webm: "video/webm",
|
|
786
|
+
mp3: "audio/mpeg",
|
|
787
|
+
ogg: "audio/ogg"
|
|
788
|
+
};
|
|
789
|
+
/**
|
|
790
|
+
* Get the Content-Type header value for a given file path based on its extension.
|
|
791
|
+
*/
|
|
792
|
+
function getContentType(path) {
|
|
793
|
+
const ext = path.split(".").pop()?.toLowerCase() ?? "";
|
|
794
|
+
return MIME_TYPES[ext] ?? "application/octet-stream";
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* Resolve the Content-Type to serve for a stored asset, reconciling the value
|
|
798
|
+
* persisted at upload time (R2 `httpMetadata.contentType` / KV `ct` metadata)
|
|
799
|
+
* with a fresh path-based lookup. Returns `undefined` when no Content-Type
|
|
800
|
+
* header should be emitted.
|
|
801
|
+
*
|
|
802
|
+
* `application/null` is a sentinel (matching Wrangler) meaning "omit the
|
|
803
|
+
* Content-Type header entirely".
|
|
804
|
+
*
|
|
805
|
+
* `application/octet-stream` is the uploader's no-information default: older
|
|
806
|
+
* CLI versions stamped it on any extension their MIME table did not recognize
|
|
807
|
+
* (e.g. `.md`). Because assets are content-addressed and never re-uploaded,
|
|
808
|
+
* those stale octet-stream values can't be corrected at the source, so we
|
|
809
|
+
* treat a stored octet-stream as "unknown" and re-derive from the path here.
|
|
810
|
+
* Any other stored value is authoritative and honored as-is.
|
|
811
|
+
*/
|
|
812
|
+
function resolveAssetContentType(stored, path) {
|
|
813
|
+
if (stored === "application/null") return;
|
|
814
|
+
if (!stored || stored === "application/octet-stream") return getContentType(path);
|
|
815
|
+
return stored;
|
|
816
|
+
}
|
|
817
|
+
// src/limits.ts
|
|
818
|
+
function readUsageLimit(value) {
|
|
819
|
+
if (!value || typeof value !== "object") return null;
|
|
820
|
+
const v = value;
|
|
821
|
+
if (v.code !== "usage_limit" || typeof v.message !== "string" || ![
|
|
822
|
+
"ai",
|
|
823
|
+
"sandbox",
|
|
824
|
+
"requests",
|
|
825
|
+
"execution"
|
|
826
|
+
].includes(String(v.resource)) || ![
|
|
827
|
+
"monthly_quota",
|
|
828
|
+
"rate_limit",
|
|
829
|
+
"concurrency",
|
|
830
|
+
"runtime_budget",
|
|
831
|
+
"cpu"
|
|
832
|
+
].includes(String(v.reason))) return null;
|
|
833
|
+
return {
|
|
834
|
+
code: "usage_limit",
|
|
835
|
+
resource: v.resource,
|
|
836
|
+
reason: v.reason,
|
|
837
|
+
message: v.message,
|
|
838
|
+
...typeof v.retryAt === "string" && Number.isFinite(Date.parse(v.retryAt)) ? { retryAt: v.retryAt } : {}
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
function usageLimitResponse(limit) {
|
|
842
|
+
const headers = new Headers({ "Cache-Control": "no-store" });
|
|
843
|
+
if (limit.retryAt && Number.isFinite(Date.parse(limit.retryAt))) headers.set("Retry-After", String(Math.max(0, Math.ceil((Date.parse(limit.retryAt) - Date.now()) / 1e3))));
|
|
844
|
+
return Response.json(limit, {
|
|
845
|
+
status: 429,
|
|
846
|
+
headers
|
|
847
|
+
});
|
|
848
|
+
}
|
|
849
|
+
export { applyHeaderRules, applyRoutingRules, compilePattern, createStaticEdgeHandler, getContentType, matchLiteralPattern, matchPattern, matchPatternCaptures, mergeQueryIntoLocation, parseClearSiteData, readUsageLimit, redirectToHttps, resolveAssetContentType, resolveStaticPath, safeDecodePathname, sanitizeClearSiteData, substituteParams, usageLimitResponse };
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@builtbyfriends/edge",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.9.1",
|
|
4
|
+
"description": "Routing, headers, and static asset helpers for bwf runtimes.",
|
|
5
|
+
"homepage": "https://github.com/builtbyfriends/platform",
|
|
6
|
+
"bugs": {
|
|
7
|
+
"url": "https://github.com/builtbyfriends/platform/issues"
|
|
8
|
+
},
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/builtbyfriends/platform.git",
|
|
13
|
+
"directory": "packages/edge"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/index.d.mts",
|
|
22
|
+
"import": "./dist/index.mjs"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public"
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@builtbyfriends/deploy-core": "1.9.1"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@cloudflare/workers-types": "^5.20261110.1",
|
|
33
|
+
"typescript": "7.0.2",
|
|
34
|
+
"vite-plus": "1.6.0"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "vp pack",
|
|
38
|
+
"dev": "vp pack --watch",
|
|
39
|
+
"typecheck": "tsc --noEmit"
|
|
40
|
+
}
|
|
6
41
|
}
|