@klnap/next-proxy-chain 1.2.0 → 2.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/dist/index.d.ts CHANGED
@@ -1,80 +1,109 @@
1
1
  import { NextRequest, NextFetchEvent, NextResponse } from 'next/server';
2
+ import { NextRequest as NextRequest$1, NextResponse as NextResponse$1 } from 'next/server.js';
2
3
 
3
4
  /**
4
5
  * Unique symbol identifying an explicit continue action in the proxy chain pipeline.
5
6
  */
6
7
  declare const NEXT: unique symbol;
8
+ /** Marks handlers created by defineHandler(). */
9
+ declare const DEFINED_HANDLER: unique symbol;
7
10
 
8
- type DebugLevel = false | true | 'compact' | 'detailed' | 'verbose';
9
- type SkipReason = 'include-mismatch' | 'exclude-match' | 'when-false';
11
+ type RequestMetadata = {
12
+ readonly requestId: string;
13
+ readonly startedAt: number;
14
+ readonly elapsedMs: number;
15
+ readonly originalUrl: string;
16
+ readonly originalPathname: string;
17
+ readonly originalHostname: string;
18
+ };
19
+ type ApplicationContext<TContext extends object> = string extends keyof TContext ? never : Omit<Partial<TContext>, keyof RequestMetadata | "signal">;
20
+ type HandlerContext<TContext extends object = object> = RequestMetadata & ApplicationContext<TContext> & {
21
+ readonly signal: AbortSignal;
22
+ };
23
+
24
+ type DebugLevel = false | true | "compact" | "detailed" | "verbose";
25
+ type SkipReason = "include-mismatch" | "exclude-match" | "when-false";
10
26
  type HandlerDiagnosticDetails = {
11
27
  include?: readonly string[];
12
- includeResult?: 'matched' | 'mismatch';
28
+ includeResult?: "matched" | "mismatch";
13
29
  exclude?: readonly string[];
14
- excludeResult?: 'not-matched' | 'matched';
15
- when?: 'matched' | 'false' | 'not-evaluated';
30
+ excludeResult?: "not-matched" | "matched";
31
+ when?: "matched" | "false" | "not-evaluated";
16
32
  timeoutMs?: number;
17
- timeoutSource?: 'handler' | 'chain';
33
+ timeoutSource?: "handler" | "chain";
18
34
  };
19
35
  type NamedHandler = {
20
36
  name: string;
21
37
  details?: HandlerDiagnosticDetails;
22
38
  };
23
39
  type HandlerTrace = (NamedHandler & {
24
- outcome: 'continue';
25
- source: 'undefined' | 'NextResponse.next()' | 'next()';
40
+ outcome: "continue";
41
+ source: "undefined" | "NextResponse.next()" | "next()";
26
42
  durationMs: number;
27
43
  }) | (NamedHandler & {
28
- outcome: 'rewrite';
44
+ outcome: "rewrite";
29
45
  durationMs: number;
30
46
  destination: string;
31
47
  final: boolean;
32
48
  }) | (NamedHandler & {
33
- outcome: 'redirect';
49
+ outcome: "redirect";
34
50
  durationMs: number;
35
51
  status: number;
36
52
  destination?: string;
37
53
  }) | (NamedHandler & {
38
- outcome: 'response';
54
+ outcome: "response";
39
55
  durationMs: number;
40
56
  status: number;
41
57
  }) | (NamedHandler & {
42
- outcome: 'skipped';
58
+ outcome: "skipped";
43
59
  reason: SkipReason;
44
60
  }) | (NamedHandler & {
45
- outcome: 'not-reached';
61
+ outcome: "not-reached";
62
+ }) | (NamedHandler & {
63
+ outcome: "recovered";
64
+ durationMs: number;
65
+ recovery: "continue" | "rewrite" | "redirect" | "response";
66
+ policy: "handler" | "chain";
46
67
  }) | (NamedHandler & {
47
- outcome: 'recovered';
68
+ outcome: "failed" | "timeout";
48
69
  durationMs: number;
49
- recovery: 'continue' | 'rewrite' | 'redirect' | 'response';
50
- policy: 'handler' | 'chain';
70
+ policy: "none" | "handler" | "chain";
71
+ phase?: "when" | "handler" | "result" | "recovery";
72
+ recovery?: "response";
73
+ timeoutMs?: number;
51
74
  }) | (NamedHandler & {
52
- outcome: 'failed' | 'timeout';
75
+ outcome: "request-cancelled";
53
76
  durationMs: number;
54
- policy: 'none' | 'handler' | 'chain';
77
+ phase: "before-handler" | "when" | "handler";
78
+ policy: "none" | "handler" | "chain";
79
+ recovery?: "response";
55
80
  });
56
81
  type ChainOutcome = {
57
- type: 'next';
82
+ type: "next";
58
83
  } | {
59
- type: 'rewrite';
84
+ type: "rewrite";
60
85
  destination: string;
61
86
  } | {
62
- type: 'redirect';
87
+ type: "redirect";
63
88
  status: number;
64
89
  destination?: string;
65
90
  } | {
66
- type: 'response';
91
+ type: "response";
67
92
  status: number;
68
93
  } | {
69
- type: 'error';
94
+ type: "error";
70
95
  status: number;
71
- classification: 'handler' | 'engine';
96
+ classification: "handler" | "engine";
72
97
  } | {
73
- type: 'timeout';
98
+ type: "timeout";
74
99
  status: number;
75
100
  timeoutMs: number;
101
+ } | {
102
+ type: "request-cancelled";
76
103
  };
77
104
  type ChainTrace = {
105
+ requestId: string;
106
+ startedAt: number;
78
107
  method: string;
79
108
  pathname?: string;
80
109
  durationMs: number;
@@ -82,8 +111,8 @@ type ChainTrace = {
82
111
  handlers: readonly HandlerTrace[];
83
112
  };
84
113
  type TraceCallback = (trace: ChainTrace) => void | Promise<void>;
85
- type HandlerWhen<TContext = ProxyContext> = (request: NextRequest, event: NextFetchEvent, context: TContext) => boolean | Promise<boolean>;
86
- type HandlerDebugOptions<TContext = ProxyContext> = {
114
+ type HandlerWhen<TContext extends object = object> = (request: NextRequest, event: NextFetchEvent, context: HandlerContext<TContext>) => boolean | Promise<boolean>;
115
+ type HandlerDebugOptions<TContext extends object = object> = {
87
116
  name?: string;
88
117
  debug?: DebugLevel;
89
118
  timeout?: number;
@@ -93,7 +122,7 @@ type HandlerDebugOptions<TContext = ProxyContext> = {
93
122
  exclude?: RouteScopeList;
94
123
  when?: HandlerWhen<TContext>;
95
124
  };
96
- handler: (request: NextRequest, event: NextFetchEvent, context: TContext) => Response | NextResult | undefined | void | Promise<Response | NextResult | undefined | void>;
125
+ handler: (request: NextRequest, event: NextFetchEvent, context: HandlerContext<TContext>) => Response | NextResult | undefined | void | Promise<Response | NextResult | undefined | void>;
97
126
  };
98
127
 
99
128
  /**
@@ -111,11 +140,6 @@ type NextOptions = {
111
140
  type NextResult = NextOptions & {
112
141
  readonly [NEXT]: true;
113
142
  };
114
- /**
115
- * Shared state for an individual request pipeline execution.
116
- * Backed by Map to eliminate prototype-pollution risks.
117
- */
118
- type ProxyContext = Map<string, unknown>;
119
143
  type PathMatcher = RegExp | string;
120
144
  type HostMatcher = string | RegExp | readonly (string | RegExp)[];
121
145
  /**
@@ -134,7 +158,7 @@ type CompiledScope = {
134
158
  host?: RegExp;
135
159
  path?: RegExp;
136
160
  };
137
- interface BaseProxyRule<TFn, TContext = ProxyContext> {
161
+ interface BaseHandlerRule<TFn, TContext extends object = object> {
138
162
  run: TFn;
139
163
  include?: CompiledScope[];
140
164
  exclude?: CompiledScope[];
@@ -148,34 +172,23 @@ interface BaseProxyRule<TFn, TContext = ProxyContext> {
148
172
  exclude?: RouteScopeList;
149
173
  };
150
174
  }
151
- type ProxyPathFilter = {
175
+ type HandlerFilter = {
152
176
  include?: RouteScopeList;
153
177
  exclude?: RouteScopeList;
154
178
  name?: string;
155
179
  };
156
- /**
157
- * Type-only brand carried by defineProxy() rules. It records the context type a rule expects.
158
- * Chain entries match on it as an object, which keeps handler parameters contextually typed.
159
- */
160
- declare const CONTEXT_BRAND: unique symbol;
161
- /** Entry type for a defineProxy() rule that expects context TContext. */
162
- type ContextRuleEntry<TContext = ProxyContext> = {
163
- readonly [CONTEXT_BRAND]: TContext;
164
- };
165
180
  /**
166
181
  * A native Next.js proxy handler: `(request, event)`. Use it in chain() without any wrapper.
167
182
  */
168
- type NativeProxy<TContext = ProxyContext> = (req: NextRequest, event: NextFetchEvent,
169
- /** Request context from createContext. Next.js never passes it; chain() does, as the third argument. */
170
- context: TContext) => NextResponse | Response | NextResult | undefined | void | Promise<NextResponse | Response | NextResult | undefined | void>;
183
+ type NativeProxy<TContext extends object = object> = (req: NextRequest, event: NextFetchEvent,
184
+ /** Request context added by chain(); Next.js continues to pass its native event unchanged. */
185
+ context: HandlerContext<TContext>) => NextResponse | Response | NextResult | undefined | void | Promise<NextResponse | Response | NextResult | undefined | void>;
171
186
  /**
172
187
  * A single proxy execution function.
173
188
  */
174
- type ProxyFn<TContext = ProxyContext> = (req: NextRequest, ctx: TContext, event: NextFetchEvent) => NextResponse | Response | NextResult | undefined | void | Promise<NextResponse | Response | NextResult | undefined | void>;
175
- type ProxyRule<TContext = ProxyContext> = BaseProxyRule<ProxyFn<TContext>, TContext>;
176
- type DefinedProxy<TContext = ProxyContext> = ProxyFn<TContext> & ((filter: ProxyPathFilter) => ProxyRule<TContext>) & ContextRuleEntry<TContext>;
177
- type Entry<TContext = ProxyContext> = ProxyFn<TContext> | ProxyRule<TContext>;
178
- type MergeStrategy = 'last-write-wins' | 'first-write-wins' | ((key: string, existing: string, incoming: string) => string | null);
189
+ type HandlerFn<TContext extends object = object> = (req: NextRequest, ctx: HandlerContext<TContext>, event: NextFetchEvent) => NextResponse | Response | NextResult | undefined | void | Promise<NextResponse | Response | NextResult | undefined | void>;
190
+ type HandlerRule<TContext extends object = object> = BaseHandlerRule<HandlerFn<TContext>, TContext>;
191
+ type MergeStrategy = "last-write-wins" | "first-write-wins" | ((key: string, existing: string, incoming: string) => string | null);
179
192
  interface ChainLogger {
180
193
  debug: (metaOrMsg: unknown, maybeMsg?: string) => void;
181
194
  info: (metaOrMsg: unknown, maybeMsg?: string) => void;
@@ -190,19 +203,18 @@ interface RequestHeaderPolicy {
190
203
  * Value returned from `onError`.
191
204
  *
192
205
  * - `Response` — stop the pipeline and return it
193
- * - `NextResult` (`next()`) — continue to the next rule (rule-level errors only)
206
+ * - `NextResult` (`next()`) — continue after an ordinary rule error only
194
207
  * - `undefined` / `void` / `null` — fail closed (`500`)
195
208
  */
196
209
  type OnErrorResult = NextResponse | Response | NextResult | undefined | void | null;
197
- type OnErrorHandler<TContext = ProxyContext> = (err: unknown,
210
+ type OnErrorHandler<TContext extends object = object> = (err: unknown,
198
211
  /**
199
212
  * 0-based index of the rule that threw.
200
- * `-1` means the error originated in the pipeline engine after context creation.
213
+ * `-1` means the error originated in the pipeline engine.
201
214
  * Engine-level errors cannot continue; only a `Response` is honored.
202
215
  */
203
- ruleIndex: number, req: NextRequest, ctx: TContext) => OnErrorResult | Promise<OnErrorResult>;
204
- interface ChainConfig<TContext = ProxyContext> {
205
- createContext: (req: NextRequest, event: NextFetchEvent) => TContext;
216
+ ruleIndex: number, req: NextRequest, ctx: HandlerContext<TContext>) => OnErrorResult | Promise<OnErrorResult>;
217
+ interface ChainConfig<TContext extends object = object> {
206
218
  cookieMergeStrategy: MergeStrategy;
207
219
  /**
208
220
  * How conflicting **response** headers from different rules are resolved.
@@ -214,18 +226,13 @@ interface ChainConfig<TContext = ProxyContext> {
214
226
  logger: ChainLogger;
215
227
  onTrace?: TraceCallback;
216
228
  tracePath?: boolean;
217
- /** Maximum wall-clock execution time per rule in milliseconds. 0 disables timeout. */
218
- ruleTimeoutMs: number;
229
+ /** Maximum execution time per handler, including its predicate, in milliseconds. 0 disables timeout. */
230
+ timeout: number;
219
231
  requestHeaderPolicy: RequestHeaderPolicy;
220
232
  /** Throw an error on startup if the runtime platform does not support request header overrides. */
221
233
  strictOverrideCheck?: boolean;
222
- /**
223
- * Request header name that prefixes rewrites with a physical host folder
224
- * (multi-tenant `app/(sites)/shop` layouts). Unset = disabled.
225
- */
226
- hostFolderHeader?: string;
227
234
  }
228
- type ProxyChainOptions<TContext = ProxyContext> = Partial<ChainConfig<TContext>>;
235
+ type ChainOptions<TContext extends object = object> = Partial<ChainConfig<TContext>>;
229
236
 
230
237
  /**
231
238
  * Creates a continuation action instructing the proxy chain to proceed to subsequent rules.
@@ -242,64 +249,33 @@ declare function next(options?: NextOptions): NextResult;
242
249
  */
243
250
  declare function isNextResult(value: unknown): value is NextResult;
244
251
 
252
+ type ProxyHandler = (req: NextRequest$1, event: NextFetchEvent) => Promise<NextResponse$1 | Response>;
253
+ /** Internal executor for the public chain() composition helper. */
254
+ declare function executeChain<TContext extends object = object>(options: ChainOptions<TContext>, entries: HandlerRule<TContext>[]): ProxyHandler;
255
+
256
+ type DefinedHandler<TContext extends object = object> = HandlerRule<TContext> & {
257
+ readonly [DEFINED_HANDLER]: true;
258
+ };
245
259
  /**
246
- * Creates a reusable, scope-aware proxy rule function.
247
- *
248
- * @example
249
- * const authRule = defineProxy("auth", async (req, ctx) => next())
250
- * const scopedAuthRule = authRule({ include: path("/admin/*") })
251
- */
252
- declare function defineProxy<TContext = ProxyContext>(run: ProxyFn<TContext>): DefinedProxy<TContext>;
253
- declare function defineProxy<TContext = ProxyContext>(name: string, run: ProxyFn<TContext>): DefinedProxy<TContext>;
254
- type ProxyHandler = (req: NextRequest, event: NextFetchEvent) => Promise<NextResponse | Response>;
255
- /**
256
- * Composes independent proxy rules into a single pipeline for Next.js 15 (middleware.ts) and Next.js 16 (proxy.ts).
257
- *
258
- * Custom `TContext` requires `createContext`. Without it, context is `ProxyContext` (`Map`).
259
- *
260
- * @example
261
- * export default proxyChain({ debug: true }, [
262
- * requestIdRule,
263
- * authRule({ include: path("/dashboard/*") }),
264
- * i18nRule,
265
- * ])
260
+ * Defines a native-signature handler with optional chain rules and local settings.
266
261
  */
267
- /** @deprecated Use chain(). Plain functions here receive (request, context, event). */
268
- declare function proxyChain(entries: Entry<ProxyContext>[]): ProxyHandler;
269
- declare function proxyChain(options: ProxyChainOptions<ProxyContext>, entries: Entry<ProxyContext>[]): ProxyHandler;
270
- declare function proxyChain<TContext>(options: ProxyChainOptions<TContext> & {
271
- createContext: (req: NextRequest, event: NextFetchEvent) => TContext;
272
- }, entries: Entry<TContext>[]): ProxyHandler;
262
+ declare function defineHandler<TContext extends object = object>(options: HandlerDebugOptions<TContext>): DefinedHandler<TContext>;
273
263
 
274
264
  /** Scope for a tuple entry: `[handler, scope]`. A string, RegExp, or array is shorthand for `include`. */
275
- type ChainScope = Omit<ProxyPathFilter, 'name'> | PathMatcher | readonly PathMatcher[];
276
- /** One entry of chain(): a native handler, a defineProxy() rule, a rule object, or a scoped tuple. */
277
- type ChainEntry<TContext = ProxyContext> = NativeProxy<TContext> | ContextRuleEntry<TContext> | ProxyRule<TContext> | readonly [NativeProxy<TContext> | ContextRuleEntry<TContext>, ChainScope];
265
+ type ChainScope = Omit<HandlerFilter, "name"> | PathMatcher | readonly PathMatcher[];
266
+ /** One entry of chain(): a native handler, a defineHandler() result, or a scoped tuple. */
267
+ type ChainEntry<TContext extends object = object> = NativeProxy<TContext> | DefinedHandler<TContext> | readonly [NativeProxy<TContext> | DefinedHandler<TContext>, ChainScope];
278
268
  /**
279
- * Composes native Next.js proxy handlers and optional rules into one proxy.
269
+ * Composes native Next.js proxy handlers and defineHandler() results into one proxy.
280
270
  *
281
- * - A plain function receives `(request, event)`, exactly like a native `proxy.ts` export.
282
- * - A `defineProxy()` rule receives `(request, context, event)`.
271
+ * - A plain function receives native `(request, event)` arguments plus context as a third argument.
272
+ * - A `defineHandler()` handler receives `(request, event, context)`.
283
273
  * - `[handler, scope]` runs the handler only for matching paths or hosts.
284
274
  *
285
275
  * @example
286
276
  * export default chain([intlProxy, [authProxy, { include: '/dashboard/**' }]])
287
277
  */
288
- declare function chain(entries: readonly ChainEntry<ProxyContext>[], options?: ProxyChainOptions<ProxyContext>): ReturnType<typeof proxyChain>;
289
- declare function chain<TContext>(entries: readonly ChainEntry<TContext>[], options: ProxyChainOptions<TContext> & {
290
- createContext: (req: NextRequest, event: NextFetchEvent) => TContext;
291
- }): ReturnType<typeof proxyChain>;
292
-
293
- /**
294
- * Defines a native-signature handler with optional chain rules and local settings.
295
- */
296
- declare function defineHandler<TContext = ProxyContext>(options: HandlerDebugOptions<TContext>): ProxyRule<TContext>;
297
-
298
- /**
299
- * Creates an isolated per-request context instance.
300
- * Backed by Map to eliminate prototype pollution risks.
301
- */
302
- declare function createProxyContext(): ProxyContext;
278
+ declare function chain<TContext extends object = object>(entries: readonly ChainEntry<TContext>[], options?: ChainOptions<TContext>): ReturnType<typeof executeChain>;
303
279
 
304
280
  /**
305
281
  * Builds a compiled Host matcher RegExp from domain names, `*.example.com` wildcards, or regex patterns.
@@ -319,4 +295,4 @@ declare class RuleTimeoutError extends Error {
319
295
  constructor(ruleName: string, timeoutMs: number);
320
296
  }
321
297
 
322
- export { type ChainEntry, type ChainLogger, type ChainOutcome, type ChainScope, type ChainTrace, type DebugLevel, type DefinedProxy, type Entry, type HandlerDebugOptions, type HandlerDiagnosticDetails, type HandlerTrace, type HandlerWhen, type HostMatcher, type MergeStrategy, type NativeProxy, type NextOptions, type NextResult, type OnErrorHandler, type OnErrorResult, type PathMatcher, type ProxyChainOptions, type ProxyContext, type ProxyFn, type ProxyPathFilter, type ProxyRule, type RequestHeaderPolicy, RuleTimeoutError, type SkipReason, type TraceCallback, chain, createProxyContext, defineHandler, defineProxy, host, isNextResult, next, path, proxyChain };
298
+ export { type ChainEntry, type ChainLogger, type ChainOptions, type ChainOutcome, type ChainScope, type ChainTrace, type DebugLevel, type DefinedHandler, type HandlerContext, type HandlerDebugOptions, type HandlerDiagnosticDetails, type HandlerTrace, type HandlerWhen, type HostMatcher, type MergeStrategy, type NativeProxy, type NextOptions, type NextResult, type OnErrorHandler, type OnErrorResult, type PathMatcher, type RequestHeaderPolicy, type RequestMetadata, RuleTimeoutError, type SkipReason, type TraceCallback, chain, defineHandler, host, isNextResult, next, path };