@klnap/next-proxy-chain 1.0.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/README.md ADDED
@@ -0,0 +1,126 @@
1
+ # `@repo/next-proxy-chain`
2
+
3
+ Composable Next.js Edge proxy pipeline with pure Web API core, pass-through detection, context threading, header/cookie accumulation, and zero external runtime dependencies.
4
+
5
+ ---
6
+
7
+ ## Key Features
8
+
9
+ - **Linear Pipeline Composition**: Order middleware steps clearly without nested wrapper hell.
10
+ - **Pass-through Interoperability**: Transparently supports `NextResponse.next()` from third-party middlewares via `x-middleware-next: 1` detection.
11
+ - **Per-request Context**: Type-safe, isolated `Map` context (`TContext`) threaded across all rules.
12
+ - **Header & Cookie Accumulation**: Collects and merges request headers, response headers, and cookies across rules before writing to the outgoing response.
13
+ - **Host & Path Scoping**: Declarative `include` / `exclude` routing rules with glob, RegExp, and next-intl locale support.
14
+ - **Header Injection & Leak Protection**: Automatically filters internal `x-middleware-*` transport headers from client responses.
15
+ - **100% Edge-Safe**: Built purely on standard Web APIs (`Headers`, `Map`, `Response`, `Request`).
16
+
17
+ ---
18
+
19
+ ## Quick Start
20
+
21
+ ### 1. Define Reusable Proxies
22
+
23
+ ```ts
24
+ import { defineProxy, next } from "@repo/next-proxy-chain"
25
+
26
+ // Request ID injector
27
+ export const requestIdProxy = defineProxy("requestId", (req) => {
28
+ const id = crypto.randomUUID()
29
+ return next({
30
+ request: { "x-request-id": id },
31
+ headers: { "x-request-id": id },
32
+ })
33
+ })
34
+
35
+ // Authentication guard
36
+ export const authProxy = defineProxy("auth", async (req, ctx) => {
37
+ const token = req.cookies.get("auth-token")?.value
38
+ if (!token) {
39
+ return NextResponse.redirect(new URL("/login", req.url))
40
+ }
41
+ ctx.set("userId", "user_123")
42
+ return next()
43
+ })
44
+ ```
45
+
46
+ ### 2. Assemble the Pipeline in `proxy.ts`
47
+
48
+ ```ts
49
+ import { proxyChain, path } from "@repo/next-proxy-chain"
50
+ import { requestIdProxy } from "./proxies/request-id"
51
+ import { authProxy } from "./proxies/auth"
52
+ import { i18nProxy } from "./proxies/i18n"
53
+
54
+ const isDev = process.env.NODE_ENV !== "production"
55
+
56
+ export default proxyChain({ debug: isDev }, [
57
+ requestIdProxy,
58
+ authProxy({
59
+ include: path("/dashboard/*"),
60
+ exclude: path("/dashboard/public"),
61
+ }),
62
+ i18nProxy,
63
+ ])
64
+
65
+ export const config = {
66
+ matcher: "/((?!api|_next|.*\\..*).*)",
67
+ }
68
+ ```
69
+
70
+ ---
71
+
72
+ ## Scope Matching Rules
73
+
74
+ Scoping supports globs, RegExps, host matching, and combinations:
75
+
76
+ ```ts
77
+ // Path on any host
78
+ include: path("/admin/*")
79
+
80
+ // Any path on a specific host
81
+ include: { host: "shop.localhost" }
82
+
83
+ // Specific path on a specific host
84
+ include: { host: "shop.localhost", path: "/checkout/*" }
85
+
86
+ // OR combinations
87
+ include: [
88
+ path("/health"),
89
+ { host: "shop.localhost", path: "/checkout/*" },
90
+ ]
91
+
92
+ // Exclude always wins
93
+ exclude: { host: "museum.localhost" }
94
+ ```
95
+
96
+ ---
97
+
98
+ ## Error Handling
99
+
100
+ By default, any unhandled error inside a rule logs safely and returns an HTTP 500 (`safeInternalError`). You can supply a custom `onError` handler:
101
+
102
+ ```ts
103
+ export default proxyChain(
104
+ {
105
+ onError: (err, ruleIndex, req, ctx) => {
106
+ return new NextResponse("Service Unavailable", { status: 503 })
107
+ },
108
+ },
109
+ [
110
+ // rules...
111
+ ]
112
+ )
113
+ ```
114
+
115
+ ---
116
+
117
+ ## API Reference
118
+
119
+ ### Core Functions
120
+
121
+ - `proxyChain(options?, rules)`: Combines rules into an Edge proxy handler.
122
+ - `defineProxy(name?, fn)`: Creates a proxy function that can be called with `{ include, exclude }` to scope.
123
+ - `withPaths(rule, filter)`: Scopes any rule function with path/host filters.
124
+ - `next(options?)`: Signals pipeline continuation with optional `{ request?, headers? }` mutations.
125
+ - `decodeOverriddenRequestHeaders(headers)`: Extracts Next.js middleware request header overrides.
126
+ - `createProxyContext()`: Instantiates a fresh `Map` for per-request context.
@@ -0,0 +1,412 @@
1
+ // src/core.ts
2
+ var NEXT = /* @__PURE__ */ Symbol.for("proxy-chain.next");
3
+ function next(options = {}) {
4
+ return { [NEXT]: true, ...options };
5
+ }
6
+ function isNextResult(value) {
7
+ return typeof value === "object" && value !== null && NEXT in value;
8
+ }
9
+ function createProxyContext() {
10
+ return /* @__PURE__ */ new Map();
11
+ }
12
+ var USELESS_FN_NAMES = /* @__PURE__ */ new Set(["", "proxy", "anonymous", "run", "next"]);
13
+ function usefulName(value) {
14
+ if (!value || USELESS_FN_NAMES.has(value)) return void 0;
15
+ return value;
16
+ }
17
+ function toStatelessRegExp(re) {
18
+ const flags = re.flags.replace(/[gy]/g, "");
19
+ return flags === re.flags ? re : new RegExp(re.source, flags);
20
+ }
21
+ function escapeRegex(value) {
22
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
23
+ }
24
+ function host(matcher) {
25
+ const list = Array.isArray(matcher) ? matcher : [matcher];
26
+ const parts = list.map((m) => {
27
+ if (m instanceof RegExp) return `(?:${toStatelessRegExp(m).source})`;
28
+ return `(?:${escapeRegex(m.toLowerCase())})`;
29
+ });
30
+ return toStatelessRegExp(new RegExp(`^(?:${parts.join("|")})$`, "i"));
31
+ }
32
+ function isScopeObject(value) {
33
+ return "host" in value || "path" in value;
34
+ }
35
+ function compileScopes(input, pathOptions) {
36
+ if (input == null) return void 0;
37
+ const list = Array.isArray(input) ? input : [input];
38
+ const compilePath = (matcher) => {
39
+ if (Array.isArray(matcher)) {
40
+ const parts = matcher.map(
41
+ (m) => typeof m === "string" ? path(m, pathOptions) : toStatelessRegExp(m)
42
+ );
43
+ if (parts.length === 1) return parts[0];
44
+ return toStatelessRegExp(new RegExp(`(?:${parts.map((r) => `(?:${r.source})`).join("|")})`));
45
+ }
46
+ return typeof matcher === "string" ? path(matcher, pathOptions) : toStatelessRegExp(matcher);
47
+ };
48
+ const compiled = [];
49
+ for (const item of list) {
50
+ if (typeof item === "string" || item instanceof RegExp) {
51
+ compiled.push({ path: compilePath(item) });
52
+ continue;
53
+ }
54
+ if (item && typeof item === "object" && isScopeObject(item)) {
55
+ if (item.host == null && item.path == null) {
56
+ throw new Error("[proxy-chain] scope needs at least `host` or `path`");
57
+ }
58
+ compiled.push({
59
+ host: item.host != null ? host(item.host) : void 0,
60
+ path: item.path != null ? compilePath(item.path) : void 0
61
+ });
62
+ continue;
63
+ }
64
+ throw new Error("[proxy-chain] invalid include/exclude scope");
65
+ }
66
+ return compiled;
67
+ }
68
+ function scopeMatches(pathname, hostname, scope) {
69
+ if (scope.host) {
70
+ if (!hostname || !scope.host.test(hostname)) return false;
71
+ }
72
+ if (scope.path) {
73
+ if (!scope.path.test(pathname)) return false;
74
+ }
75
+ return true;
76
+ }
77
+ function toRule(entry) {
78
+ if (typeof entry === "function") {
79
+ const name2 = usefulName(entry.name);
80
+ return name2 ? { run: entry, name: name2 } : { run: entry };
81
+ }
82
+ const rule = entry;
83
+ const runName = typeof rule.run === "function" ? usefulName(rule.run.name) : void 0;
84
+ const name = usefulName(rule.name) ?? runName;
85
+ const harden = (scopes) => scopes?.map((s) => ({
86
+ host: s.host ? toStatelessRegExp(s.host) : void 0,
87
+ path: s.path ? toStatelessRegExp(s.path) : void 0
88
+ }));
89
+ return {
90
+ ...rule,
91
+ name: name ?? void 0,
92
+ include: harden(rule.include),
93
+ exclude: harden(rule.exclude)
94
+ };
95
+ }
96
+ function ruleLabel(rule, index) {
97
+ const runName = typeof rule.run === "function" ? usefulName(rule.run.name) : void 0;
98
+ return usefulName(rule.name) ?? runName ?? `rule#${index}`;
99
+ }
100
+ function withPaths(entry, filter) {
101
+ const base = toRule(entry);
102
+ const opts = filter.pathOptions;
103
+ const include = compileScopes(filter.include, opts);
104
+ const exclude = compileScopes(filter.exclude, opts);
105
+ const name = filter.name ?? base.name;
106
+ assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
107
+ return { run: base.run, include, exclude, name };
108
+ }
109
+ function ruleMatches(pathname, hostname, rule) {
110
+ if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) return false;
111
+ if (rule.include && !rule.include.some((scope) => scopeMatches(pathname, hostname, scope))) {
112
+ return false;
113
+ }
114
+ return true;
115
+ }
116
+ function pathMatches(pathname, rule) {
117
+ return ruleMatches(pathname, null, rule);
118
+ }
119
+ function normalizeHost(raw) {
120
+ if (!raw) return null;
121
+ const first = raw.split(",")[0]?.trim().toLowerCase();
122
+ if (!first) return null;
123
+ if (first.startsWith("[")) {
124
+ const end = first.indexOf("]");
125
+ return end === -1 ? first : first.slice(1, end);
126
+ }
127
+ const withoutPort = first.replace(/:\d+$/, "");
128
+ return withoutPort || null;
129
+ }
130
+ function parseCookieName(setCookie) {
131
+ const eq = setCookie.indexOf("=");
132
+ return (eq === -1 ? setCookie : setCookie.slice(0, eq)).trim();
133
+ }
134
+ function listSetCookie(headers) {
135
+ const extended = headers;
136
+ if (typeof extended.getSetCookie === "function") return extended.getSetCookie();
137
+ const single = headers.get("set-cookie");
138
+ return single ? [single] : [];
139
+ }
140
+ function cookieItemsFromHeaders(headers) {
141
+ const map = /* @__PURE__ */ new Map();
142
+ for (const value of listSetCookie(headers)) {
143
+ map.set(parseCookieName(value), value);
144
+ }
145
+ return map;
146
+ }
147
+ function responseHeaderItems(headers) {
148
+ const map = /* @__PURE__ */ new Map();
149
+ headers.forEach((value, key) => {
150
+ const lower = key.toLowerCase();
151
+ if (lower === "set-cookie") return;
152
+ if (lower.startsWith("x-middleware-next") || lower.startsWith("x-middleware-rewrite") || lower.startsWith("x-middleware-override-headers") || lower.startsWith("x-middleware-request-")) {
153
+ return;
154
+ }
155
+ map.set(key, value);
156
+ });
157
+ return map;
158
+ }
159
+ function decodeOverriddenRequestHeaders(headers) {
160
+ const result = new Headers();
161
+ const overrideHeaderNames = headers.get("x-middleware-override-headers");
162
+ if (overrideHeaderNames) {
163
+ for (const name of overrideHeaderNames.split(",")) {
164
+ const trimmed = name.trim();
165
+ const val = headers.get(`x-middleware-request-${trimmed}`);
166
+ if (val !== null) {
167
+ result.set(trimmed, val);
168
+ }
169
+ }
170
+ }
171
+ return result;
172
+ }
173
+ function mergeWrites(writes, strategy, onConflict) {
174
+ const resolved = /* @__PURE__ */ new Map();
175
+ const setBy = /* @__PURE__ */ new Map();
176
+ for (const write of writes) {
177
+ for (const [key, value] of write.items) {
178
+ const existing = resolved.get(key);
179
+ if (existing === void 0) {
180
+ resolved.set(key, value);
181
+ setBy.set(key, write.ruleName);
182
+ continue;
183
+ }
184
+ const previousRule = setBy.get(key);
185
+ if (typeof strategy === "function") {
186
+ const result = strategy(key, existing, value);
187
+ if (result === null) resolved.delete(key);
188
+ else resolved.set(key, result);
189
+ setBy.set(key, write.ruleName);
190
+ continue;
191
+ }
192
+ if (strategy === "first-write-wins") {
193
+ onConflict?.(key, previousRule, write.ruleName);
194
+ continue;
195
+ }
196
+ onConflict?.(key, write.ruleName, previousRule);
197
+ resolved.set(key, value);
198
+ setBy.set(key, write.ruleName);
199
+ }
200
+ }
201
+ return resolved;
202
+ }
203
+ function applyMergedToResponse(res, headers, cookies) {
204
+ for (const [key, value] of headers) {
205
+ res.headers.set(key, value);
206
+ }
207
+ res.headers.delete("set-cookie");
208
+ for (const cookie of cookies.values()) {
209
+ res.headers.append("set-cookie", cookie);
210
+ }
211
+ }
212
+ var DEFAULT_BLOCKED_REQUEST_HEADERS = [
213
+ "host",
214
+ "connection",
215
+ "keep-alive",
216
+ "proxy-authenticate",
217
+ "proxy-authorization",
218
+ "te",
219
+ "trailer",
220
+ "transfer-encoding",
221
+ "upgrade",
222
+ "content-length",
223
+ "cookie",
224
+ "authorization",
225
+ "x-forwarded-host",
226
+ "x-forwarded-for",
227
+ "x-forwarded-proto",
228
+ "x-real-ip",
229
+ "x-middleware-next",
230
+ "x-middleware-override-headers"
231
+ ];
232
+ function normalizeHeaderName(name) {
233
+ return name.toLowerCase();
234
+ }
235
+ function isRequestHeaderAllowed(name, policy = {}) {
236
+ const key = normalizeHeaderName(name);
237
+ const allowed = new Set((policy.allowed ?? []).map(normalizeHeaderName));
238
+ if (allowed.has(key)) return true;
239
+ if (key.startsWith("x-middleware-")) return false;
240
+ const blocked = /* @__PURE__ */ new Set([
241
+ ...DEFAULT_BLOCKED_REQUEST_HEADERS.map(normalizeHeaderName),
242
+ ...(policy.blocked ?? []).map(normalizeHeaderName)
243
+ ]);
244
+ return !blocked.has(key);
245
+ }
246
+ function mergeRequestHeaderOverrides(target, overrides, policy = {}) {
247
+ const dropped = [];
248
+ let applied = 0;
249
+ overrides.forEach((value, key) => {
250
+ if (!isRequestHeaderAllowed(key, policy)) {
251
+ dropped.push(key);
252
+ return;
253
+ }
254
+ target.set(key, value);
255
+ applied++;
256
+ });
257
+ return { applied, dropped };
258
+ }
259
+ function headersInitToHeaders(init) {
260
+ return new Headers(init);
261
+ }
262
+ function headersDiffer(base, overrides) {
263
+ for (const [key, value] of overrides.entries()) {
264
+ if (base.get(key) !== value) return true;
265
+ }
266
+ return false;
267
+ }
268
+ function segmentToRegex(segment) {
269
+ if (segment === "**") return "(?:.*)";
270
+ if (segment === "*") return "[^/]+";
271
+ if (segment.startsWith(":")) return "[^/]+";
272
+ return escapeRegex(segment);
273
+ }
274
+ function path(pattern, options = {}) {
275
+ const { locales = [] } = options;
276
+ const localePrefix = locales.length > 0 ? `(?:(?:${locales.map(escapeRegex).join("|")})\\/)?` : "";
277
+ if (pattern instanceof RegExp) {
278
+ const body2 = pattern.source.replace(/^\^/, "").replace(/\$$/, "");
279
+ const needsStart = !pattern.source.startsWith("^");
280
+ const needsEnd = !pattern.source.endsWith("$");
281
+ return toStatelessRegExp(
282
+ new RegExp(
283
+ `${needsStart ? "^" : ""}${localePrefix ? `/${localePrefix}` : ""}${body2}${needsEnd ? "$" : ""}`,
284
+ pattern.flags
285
+ )
286
+ );
287
+ }
288
+ const normalized = (pattern.startsWith("/") ? pattern : `/${pattern}`).replace(/\/$/, "") || "/";
289
+ const segments = normalized.slice(1).split("/");
290
+ const trailingStar = segments.length > 0 && segments[segments.length - 1] === "*";
291
+ const suffix = trailingStar ? "(?:\\/.*)?$" : "$";
292
+ const body = trailingStar ? segments.slice(0, -1).map(segmentToRegex).concat("[^/]+").join("\\/") : segments.map(segmentToRegex).join("\\/");
293
+ return new RegExp(`^/${localePrefix}${body}${suffix}`);
294
+ }
295
+ function toPathRegex(matcher, options) {
296
+ const list = Array.isArray(matcher) ? matcher : [matcher];
297
+ const regexes = list.map((m) => path(m, options));
298
+ if (regexes.length === 1) return toStatelessRegExp(regexes[0]);
299
+ return toStatelessRegExp(new RegExp(`(?:${regexes.map((r) => `(?:${r.source})`).join("|")})`));
300
+ }
301
+ function scopeKey(scope) {
302
+ return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
303
+ }
304
+ function assertIncludeExcludeNoOverlap(include, exclude, label) {
305
+ if (!include?.length || !exclude?.length) return;
306
+ const excluded = new Set(exclude.map(scopeKey));
307
+ for (const scope of include) {
308
+ if (excluded.has(scopeKey(scope))) {
309
+ throw new Error(
310
+ `[proxy-chain] ${label}: include and exclude share an identical scope. Remove one.`
311
+ );
312
+ }
313
+ }
314
+ }
315
+ var LEVEL_RANK = {
316
+ debug: 10,
317
+ info: 20,
318
+ warn: 30,
319
+ error: 40
320
+ };
321
+ function createConsoleLogger(minLevel = "info") {
322
+ const min = LEVEL_RANK[minLevel];
323
+ const write = (level) => (obj, msg) => {
324
+ if (LEVEL_RANK[level] < min) return;
325
+ if (typeof obj === "string") {
326
+ console[level](obj);
327
+ return;
328
+ }
329
+ const message = msg ?? "";
330
+ if (message) console[level](`[proxy-chain] ${message}`, obj);
331
+ else console[level]("[proxy-chain]", obj);
332
+ };
333
+ return {
334
+ debug: write("debug"),
335
+ info: write("info"),
336
+ warn: write("warn"),
337
+ error: write("error")
338
+ };
339
+ }
340
+ function formatDuration(ms) {
341
+ return `${ms.toFixed(2)}ms`;
342
+ }
343
+ function formatPipelineLine(input) {
344
+ const trace = input.traceId ? ` [${input.traceId.slice(0, 8)}]` : "";
345
+ const req = `${input.method} ${input.path}${trace}`;
346
+ const { name, outcome } = input;
347
+ switch (outcome.kind) {
348
+ case "passed":
349
+ return `[proxy-chain] \xB7 ${req} | ${name} (${formatDuration(outcome.duration)}) -> passed`;
350
+ case "next":
351
+ return `[proxy-chain] ~ ${req} | ${name} (${formatDuration(outcome.duration)}) -> headers mutated (${outcome.headers})`;
352
+ case "stop":
353
+ return `[proxy-chain] \xD7 ${req} | ${name} (${formatDuration(outcome.duration)}) -> stop ${outcome.status}`;
354
+ }
355
+ }
356
+ var RuleTimeoutError = class extends Error {
357
+ ruleName;
358
+ timeoutMs;
359
+ constructor(ruleName, timeoutMs) {
360
+ super(`[proxy-chain] ${ruleName} timed out after ${timeoutMs}ms`);
361
+ this.name = "RuleTimeoutError";
362
+ this.ruleName = ruleName;
363
+ this.timeoutMs = timeoutMs;
364
+ }
365
+ };
366
+ async function withRuleTimeout(promise, timeoutMs, ruleName) {
367
+ if (!timeoutMs || timeoutMs <= 0) return promise;
368
+ let timer;
369
+ const timeout = new Promise((_, reject) => {
370
+ timer = setTimeout(() => reject(new RuleTimeoutError(ruleName, timeoutMs)), timeoutMs);
371
+ });
372
+ try {
373
+ return await Promise.race([promise, timeout]);
374
+ } finally {
375
+ if (timer !== void 0) clearTimeout(timer);
376
+ }
377
+ }
378
+
379
+ export {
380
+ NEXT,
381
+ next,
382
+ isNextResult,
383
+ createProxyContext,
384
+ toStatelessRegExp,
385
+ host,
386
+ compileScopes,
387
+ toRule,
388
+ ruleLabel,
389
+ withPaths,
390
+ ruleMatches,
391
+ pathMatches,
392
+ normalizeHost,
393
+ parseCookieName,
394
+ listSetCookie,
395
+ cookieItemsFromHeaders,
396
+ responseHeaderItems,
397
+ decodeOverriddenRequestHeaders,
398
+ mergeWrites,
399
+ applyMergedToResponse,
400
+ DEFAULT_BLOCKED_REQUEST_HEADERS,
401
+ isRequestHeaderAllowed,
402
+ mergeRequestHeaderOverrides,
403
+ headersInitToHeaders,
404
+ headersDiffer,
405
+ path,
406
+ toPathRegex,
407
+ assertIncludeExcludeNoOverlap,
408
+ createConsoleLogger,
409
+ formatPipelineLine,
410
+ RuleTimeoutError,
411
+ withRuleTimeout
412
+ };