@hilbras/sdk 3.4.3 → 3.5.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 CHANGED
@@ -1,9 +1,9 @@
1
1
  <p align="center">
2
- <img src="https://img.shields.io/badge/version-3.4.3-blue" alt="version">
2
+ <img src="https://img.shields.io/badge/version-3.5.0-blue" alt="version">
3
3
  <img src="https://img.shields.io/badge/license-MIT-green" alt="license">
4
4
  <img src="https://img.shields.io/badge/node-%3E%3D18-brightgreen" alt="node">
5
5
  <img src="https://img.shields.io/badge/types-strict-blueviolet" alt="types">
6
- <img src="https://img.shields.io/badge/tests-1809%20passing-brightgreen" alt="tests">
6
+ <img src="https://img.shields.io/badge/tests-1932%20passing-brightgreen" alt="tests">
7
7
  <img src="https://img.shields.io/badge/runtime%20deps-zero-brightgreen" alt="zero deps">
8
8
  </p>
9
9
 
@@ -71,6 +71,18 @@ export declare class CircuitBreakerOpenError extends HilbrasSdkError {
71
71
  retryAfterMs?: number;
72
72
  });
73
73
  }
74
+ /**
75
+ * A request could not be accepted as written: malformed JSON, a missing or
76
+ * wrongly typed field, or a body that exceeds the configured limits.
77
+ *
78
+ * This is a caller error, so the default `status` is 400. Framework handlers
79
+ * map it to that status instead of surfacing a 200 with a failure buried in a
80
+ * stream.
81
+ */
82
+ export declare class RequestValidationError extends HilbrasSdkError {
83
+ readonly status: number;
84
+ constructor(message: string, hint?: string, status?: number);
85
+ }
74
86
  export declare class ValidationError extends HilbrasSdkError {
75
87
  readonly attempts: number;
76
88
  readonly lastError: unknown;
@@ -168,6 +168,22 @@ export class CircuitBreakerOpenError extends HilbrasSdkError {
168
168
  this.name = "CircuitBreakerOpenError";
169
169
  }
170
170
  }
171
+ /**
172
+ * A request could not be accepted as written: malformed JSON, a missing or
173
+ * wrongly typed field, or a body that exceeds the configured limits.
174
+ *
175
+ * This is a caller error, so the default `status` is 400. Framework handlers
176
+ * map it to that status instead of surfacing a 200 with a failure buried in a
177
+ * stream.
178
+ */
179
+ export class RequestValidationError extends HilbrasSdkError {
180
+ status;
181
+ constructor(message, hint, status = 400) {
182
+ super(message, { hint });
183
+ this.name = "RequestValidationError";
184
+ this.status = status;
185
+ }
186
+ }
171
187
  export class ValidationError extends HilbrasSdkError {
172
188
  attempts;
173
189
  lastError;
@@ -5,14 +5,12 @@
5
5
  * Uses the HilbrasClient to generate streaming responses with full protocol support.
6
6
  */
7
7
  import type { Tool } from "../../types/tools.js";
8
+ import { type FrameworkHandlerBaseOptions } from "../shared/handler-core.js";
8
9
  export interface ChatMessage {
9
10
  role: "user" | "assistant" | "system";
10
11
  content: string;
11
12
  }
12
- export interface EndpointOptions {
13
- provider: string;
14
- model: string;
15
- systemPrompt?: string;
13
+ export interface EndpointOptions extends FrameworkHandlerBaseOptions {
16
14
  tools?: Tool[];
17
15
  maxSteps?: number;
18
16
  }
@@ -22,10 +20,10 @@ export interface EndpointOptions {
22
20
  * @example
23
21
  * ```ts
24
22
  * // src/pages/api/chat.ts
25
- * import { createChatEndpoint } from "@hilbras/astro";
23
+ * import { createChatEndpoint } from "@hilbras/sdk/astro";
26
24
  *
27
25
  * export const { POST } = createChatEndpoint({
28
- * provider: "OpenAI",
26
+ * provider: "openai",
29
27
  * model: "gpt-4o",
30
28
  * });
31
29
  * ```
@@ -34,6 +32,7 @@ export declare function createChatEndpoint(options: EndpointOptions): {
34
32
  POST: ({ request }: {
35
33
  request: Request;
36
34
  }) => Promise<Response>;
35
+ dispose: () => Promise<void>;
37
36
  };
38
37
  /**
39
38
  * Create a non-streaming completion endpoint for Astro.
@@ -42,4 +41,5 @@ export declare function createCompletionEndpoint(options: EndpointOptions): {
42
41
  POST: ({ request }: {
43
42
  request: Request;
44
43
  }) => Promise<Response>;
44
+ dispose: () => Promise<void>;
45
45
  };
@@ -4,74 +4,145 @@
4
4
  * Create API endpoints for streaming chat/completion in Astro.
5
5
  * Uses the HilbrasClient to generate streaming responses with full protocol support.
6
6
  */
7
- import { HilbrasClient } from "../../client/client.js";
8
7
  import { createSSEResponse } from "../../utils/sse-writer.js";
8
+ import { createFrameworkClientPool, errorResponse, isRequestPhaseError, readJsonBody, resolveChatFields, resolveCompletionFields, resolveLimits, } from "../shared/handler-core.js";
9
9
  /**
10
10
  * Create a streaming chat endpoint for Astro.
11
11
  *
12
12
  * @example
13
13
  * ```ts
14
14
  * // src/pages/api/chat.ts
15
- * import { createChatEndpoint } from "@hilbras/astro";
15
+ * import { createChatEndpoint } from "@hilbras/sdk/astro";
16
16
  *
17
17
  * export const { POST } = createChatEndpoint({
18
- * provider: "OpenAI",
18
+ * provider: "openai",
19
19
  * model: "gpt-4o",
20
20
  * });
21
21
  * ```
22
22
  */
23
23
  export function createChatEndpoint(options) {
24
+ const pool = createFrameworkClientPool({
25
+ provider: options.provider,
26
+ model: options.model,
27
+ apiKey: options.apiKey,
28
+ });
29
+ const limits = resolveLimits(options.limits);
30
+ // This adapter never read `model`/`tools`/`maxSteps` from the body in v3.4, so
31
+ // its default is `false`. Defaulting to `true` would have widened the
32
+ // caller's influence over a route that did not previously have any.
33
+ const trustClientFields = options.trustClientFields ?? false;
24
34
  async function POST({ request }) {
25
- const body = await request.json();
26
- const { messages, stream } = body;
27
- const client = new HilbrasClient();
28
- client.addProviderFromCatalog(options.provider, options.model, process.env.AI_API_KEY ?? "");
29
- const allMessages = options.systemPrompt
30
- ? [{ role: "system", content: options.systemPrompt }, ...messages]
31
- : messages;
32
- if (stream === false) {
33
- const result = await client.complete({
34
- provider: options.provider,
35
+ try {
36
+ const body = await readJsonBody(request, limits);
37
+ const fields = resolveChatFields(body, {
35
38
  model: options.model,
36
- messages: allMessages,
39
+ tools: options.tools,
40
+ maxSteps: options.maxSteps,
41
+ trustClientFields,
42
+ limits,
37
43
  });
38
- return new Response(JSON.stringify({
39
- id: `cmpl-${Date.now()}`,
40
- choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
41
- }), {
42
- headers: { "Content-Type": "application/json" },
44
+ const client = pool.get(fields.model);
45
+ const providerName = pool.providerName;
46
+ const effective = { ...fields, provider: providerName };
47
+ await options.onRequest?.({ request, body, effective });
48
+ const allMessages = options.systemPrompt
49
+ ? [{ role: "system", content: options.systemPrompt }, ...fields.messages]
50
+ : fields.messages;
51
+ if (!effective.stream) {
52
+ const result = await client.complete({
53
+ provider: providerName,
54
+ model: fields.model,
55
+ messages: allMessages,
56
+ temperature: fields.temperature,
57
+ maxTokens: fields.maxTokens,
58
+ signal: request.signal,
59
+ });
60
+ return new Response(JSON.stringify({
61
+ id: `cmpl-${Date.now()}`,
62
+ choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
63
+ }), {
64
+ headers: { "Content-Type": "application/json" },
65
+ });
66
+ }
67
+ const chunks = client.streamText({
68
+ provider: providerName,
69
+ model: fields.model,
70
+ messages: allMessages,
71
+ temperature: fields.temperature,
72
+ maxTokens: fields.maxTokens,
73
+ tools: fields.tools,
74
+ maxSteps: fields.maxSteps,
75
+ signal: request.signal,
43
76
  });
77
+ return createSSEResponse(chunks);
78
+ }
79
+ catch (error) {
80
+ if (options.onError) {
81
+ await options.onError(error, {
82
+ request,
83
+ phase: isRequestPhaseError(error) ? "request" : "provider",
84
+ });
85
+ }
86
+ return errorResponse(error);
44
87
  }
45
- const chunks = client.streamText({
46
- provider: options.provider,
47
- model: options.model,
48
- messages: allMessages,
49
- tools: options.tools,
50
- maxSteps: options.maxSteps,
51
- });
52
- return createSSEResponse(chunks);
53
88
  }
54
- return { POST };
89
+ async function dispose() {
90
+ await pool.dispose();
91
+ }
92
+ return { POST, dispose };
55
93
  }
56
94
  /**
57
95
  * Create a non-streaming completion endpoint for Astro.
58
96
  */
59
97
  export function createCompletionEndpoint(options) {
98
+ const pool = createFrameworkClientPool({
99
+ provider: options.provider,
100
+ model: options.model,
101
+ apiKey: options.apiKey,
102
+ });
103
+ const limits = resolveLimits(options.limits);
104
+ // This adapter never read `model`/`tools`/`maxSteps` from the body in v3.4, so
105
+ // its default is `false`. Defaulting to `true` would have widened the
106
+ // caller's influence over a route that did not previously have any.
107
+ const trustClientFields = options.trustClientFields ?? false;
60
108
  async function POST({ request }) {
61
- const body = await request.json();
62
- const client = new HilbrasClient();
63
- client.addProviderFromCatalog(options.provider, options.model, process.env.AI_API_KEY ?? "");
64
- const result = await client.complete({
65
- provider: options.provider,
66
- model: options.model,
67
- messages: [{ role: "user", content: body.prompt ?? "" }],
68
- });
69
- return new Response(JSON.stringify({
70
- id: `cmpl-${Date.now()}`,
71
- choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
72
- }), {
73
- headers: { "Content-Type": "application/json" },
74
- });
109
+ try {
110
+ const body = await readJsonBody(request, limits);
111
+ const fields = resolveCompletionFields(body, {
112
+ model: options.model,
113
+ trustClientFields,
114
+ limits,
115
+ });
116
+ const client = pool.get(fields.model);
117
+ const effective = { ...fields, provider: pool.providerName };
118
+ await options.onRequest?.({ request, body, effective });
119
+ const result = await client.complete({
120
+ provider: pool.providerName,
121
+ model: fields.model,
122
+ messages: [{ role: "user", content: fields.prompt }],
123
+ temperature: fields.temperature,
124
+ maxTokens: fields.maxTokens,
125
+ signal: request.signal,
126
+ });
127
+ return new Response(JSON.stringify({
128
+ id: `cmpl-${Date.now()}`,
129
+ choices: [{ message: { role: "assistant", content: result }, finishReason: "stop" }],
130
+ }), {
131
+ headers: { "Content-Type": "application/json" },
132
+ });
133
+ }
134
+ catch (error) {
135
+ if (options.onError) {
136
+ await options.onError(error, {
137
+ request,
138
+ phase: isRequestPhaseError(error) ? "request" : "provider",
139
+ });
140
+ }
141
+ return errorResponse(error);
142
+ }
143
+ }
144
+ async function dispose() {
145
+ await pool.dispose();
75
146
  }
76
- return { POST };
147
+ return { POST, dispose };
77
148
  }
@@ -4,4 +4,5 @@
4
4
  * API endpoints and client-side hooks for Astro.
5
5
  */
6
6
  export { createChatEndpoint, createCompletionEndpoint, type EndpointOptions, type ChatMessage } from "./endpoints.js";
7
+ export type { FrameworkErrorContext, FrameworkHandlerLimits, FrameworkRequestContext, } from "../shared/handler-core.js";
7
8
  export { createChatState, type UseChatOptions, type UseChatReturn, type Message } from "./hooks.js";
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @hilbras/sdk — Next.js API route helpers
3
+ *
4
+ * Subpath: `@hilbras/sdk/nextjs/api`
5
+ *
6
+ * These helpers import `next/server`, so they live under their own subpath
7
+ * rather than in `@hilbras/sdk/nextjs`. The `./nextjs` entry must keep working
8
+ * in a project with no `next` installed, and re-exporting these from there
9
+ * would make `next/server` a hard resolution requirement for every consumer.
10
+ *
11
+ * `createChatHandler` and friends — which take a plain `Request` and return a
12
+ * plain `Response` and need no Next types at all — remain in `@hilbras/sdk/nextjs`.
13
+ */
14
+ export { createStreamHandler, createStreamCompletionHandler } from "./stream.js";
15
+ export type { ChatMessage, StreamChatOptions, StreamCompletionOptions } from "./stream.js";
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @hilbras/sdk — Next.js API route helpers
3
+ *
4
+ * Subpath: `@hilbras/sdk/nextjs/api`
5
+ *
6
+ * These helpers import `next/server`, so they live under their own subpath
7
+ * rather than in `@hilbras/sdk/nextjs`. The `./nextjs` entry must keep working
8
+ * in a project with no `next` installed, and re-exporting these from there
9
+ * would make `next/server` a hard resolution requirement for every consumer.
10
+ *
11
+ * `createChatHandler` and friends — which take a plain `Request` and return a
12
+ * plain `Response` and need no Next types at all — remain in `@hilbras/sdk/nextjs`.
13
+ */
14
+ export { createStreamHandler, createStreamCompletionHandler } from "./stream.js";
@@ -0,0 +1,44 @@
1
+ import { HilbrasClient, type HilbrasClientConfig } from "../../../client/client.js";
2
+ import type { Message } from "../../../types/messages.js";
3
+ import { type NextRequestLike } from "../next-runtime.js";
4
+ export type ChatMessage = Message;
5
+ export interface StreamChatOptions {
6
+ /** HilbrasClient config (creates a new client if not provided) */
7
+ config?: HilbrasClientConfig;
8
+ /** Pre-existing client instance */
9
+ client?: HilbrasClient;
10
+ /** Catalog provider id used when this helper creates the client */
11
+ provider: string;
12
+ /** Default model */
13
+ model: string;
14
+ /** Credential for a newly created catalog-backed client */
15
+ apiKey?: string;
16
+ /** System prompt */
17
+ systemPrompt?: string;
18
+ /** Custom error handler */
19
+ onError?: (error: Error) => Response | Promise<Response>;
20
+ /** Called before streaming starts */
21
+ onRequest?: (messages: ChatMessage[]) => void | Promise<void>;
22
+ /** Called after streaming completes */
23
+ onComplete?: (messages: ChatMessage[], usage: {
24
+ inputTokens: number;
25
+ outputTokens: number;
26
+ }) => void | Promise<void>;
27
+ }
28
+ /** Create a streaming chat API route for Next.js App Router. */
29
+ export declare function createStreamHandler(options: StreamChatOptions): {
30
+ POST: (request: NextRequestLike) => Promise<import("../next-runtime.js").HilbrasNextResponse | Response>;
31
+ };
32
+ export interface StreamCompletionOptions {
33
+ config?: HilbrasClientConfig;
34
+ client?: HilbrasClient;
35
+ provider: string;
36
+ model: string;
37
+ apiKey?: string;
38
+ systemPrompt?: string;
39
+ onError?: (error: Error) => Response | Promise<Response>;
40
+ }
41
+ /** Create a streaming text-completion API route. */
42
+ export declare function createStreamCompletionHandler(options: StreamCompletionOptions): {
43
+ POST: (request: NextRequestLike) => Promise<import("../next-runtime.js").HilbrasNextResponse | Response>;
44
+ };
@@ -0,0 +1,150 @@
1
+ import { HilbrasClient, } from "../../../client/client.js";
2
+ import { createNextResponseShim, } from "../next-runtime.js";
3
+ const NextResponse = createNextResponseShim();
4
+ const ROLES = new Set(["system", "user", "assistant", "tool"]);
5
+ function parseMessages(value) {
6
+ if (!Array.isArray(value))
7
+ throw new Error("Request body must include a messages array");
8
+ return value.map((message) => {
9
+ if (typeof message !== "object" || message === null) {
10
+ throw new Error("Each message must be an object");
11
+ }
12
+ const candidate = message;
13
+ if (typeof candidate.role !== "string" || !ROLES.has(candidate.role)) {
14
+ throw new Error("Message role is invalid");
15
+ }
16
+ if (typeof candidate.content !== "string" && candidate.content !== null && !Array.isArray(candidate.content)) {
17
+ throw new Error("Message content is invalid");
18
+ }
19
+ return candidate;
20
+ });
21
+ }
22
+ function createRouteClient(options) {
23
+ if (options.client)
24
+ return { client: options.client, provider: options.provider };
25
+ const client = new HilbrasClient(options.config);
26
+ const provider = client.addProviderFromCatalog(options.provider, options.model, options.apiKey ?? process.env.HILBRAS_API_KEY ?? "");
27
+ return { client, provider };
28
+ }
29
+ /** Create a streaming chat API route for Next.js App Router. */
30
+ export function createStreamHandler(options) {
31
+ const { config, client: existingClient, provider, model, systemPrompt, apiKey, onError, onRequest, onComplete } = options;
32
+ const route = createRouteClient({ config, client: existingClient, apiKey, provider, model });
33
+ async function POST(request) {
34
+ try {
35
+ const body = await request.json();
36
+ const record = typeof body === "object" && body !== null ? body : {};
37
+ const messages = parseMessages(record.messages);
38
+ await onRequest?.(messages);
39
+ const apiMessages = [];
40
+ if (systemPrompt)
41
+ apiMessages.push({ role: "system", content: systemPrompt });
42
+ apiMessages.push(...messages);
43
+ const stream = new ReadableStream({
44
+ async start(controller) {
45
+ const encoder = new TextEncoder();
46
+ let inputTokens = 0;
47
+ let outputTokens = 0;
48
+ try {
49
+ for await (const chunk of route.client.stream({
50
+ messages: apiMessages,
51
+ model,
52
+ provider: route.provider,
53
+ signal: request.signal,
54
+ })) {
55
+ if (chunk.type === "text") {
56
+ controller.enqueue(encoder.encode(`0:${JSON.stringify(chunk.text)}\n`));
57
+ }
58
+ else if (chunk.type === "usage") {
59
+ inputTokens = chunk.inputTokens;
60
+ outputTokens = chunk.outputTokens;
61
+ controller.enqueue(encoder.encode(`1:${JSON.stringify({ inputTokens, outputTokens })}\n`));
62
+ }
63
+ else if (chunk.type === "finish") {
64
+ controller.enqueue(encoder.encode(`2:${JSON.stringify(chunk.reason)}\n`));
65
+ }
66
+ }
67
+ await onComplete?.(messages, { inputTokens, outputTokens });
68
+ }
69
+ catch (err) {
70
+ const error = err instanceof Error ? err : new Error(String(err));
71
+ await onError?.(error);
72
+ controller.enqueue(encoder.encode(`3:${JSON.stringify("stream_failed")}\n`));
73
+ }
74
+ finally {
75
+ controller.close();
76
+ }
77
+ },
78
+ });
79
+ return new Response(stream, {
80
+ headers: {
81
+ "Content-Type": "application/x-ndjson; charset=utf-8",
82
+ "Cache-Control": "no-cache, no-transform",
83
+ "Connection": "keep-alive",
84
+ },
85
+ });
86
+ }
87
+ catch (err) {
88
+ const error = err instanceof Error ? err : new Error(String(err));
89
+ if (onError)
90
+ return onError(error);
91
+ return NextResponse.json({ error: "Request failed" }, { status: 400 });
92
+ }
93
+ }
94
+ return { POST };
95
+ }
96
+ /** Create a streaming text-completion API route. */
97
+ export function createStreamCompletionHandler(options) {
98
+ const { config, client: existingClient, provider, model, systemPrompt, apiKey, onError } = options;
99
+ const route = createRouteClient({ config, client: existingClient, apiKey, provider, model });
100
+ async function POST(request) {
101
+ try {
102
+ const body = await request.json();
103
+ const record = typeof body === "object" && body !== null ? body : {};
104
+ if (typeof record.prompt !== "string" || !record.prompt.trim()) {
105
+ throw new Error("Request body must include a non-empty prompt");
106
+ }
107
+ const apiMessages = [];
108
+ if (systemPrompt)
109
+ apiMessages.push({ role: "system", content: systemPrompt });
110
+ apiMessages.push({ role: "user", content: record.prompt });
111
+ const stream = new ReadableStream({
112
+ async start(controller) {
113
+ const encoder = new TextEncoder();
114
+ try {
115
+ for await (const chunk of route.client.stream({
116
+ messages: apiMessages,
117
+ model,
118
+ provider: route.provider,
119
+ signal: request.signal,
120
+ })) {
121
+ if (chunk.type === "text")
122
+ controller.enqueue(encoder.encode(chunk.text));
123
+ }
124
+ }
125
+ catch (err) {
126
+ const error = err instanceof Error ? err : new Error(String(err));
127
+ await onError?.(error);
128
+ controller.enqueue(encoder.encode("stream_failed"));
129
+ }
130
+ finally {
131
+ controller.close();
132
+ }
133
+ },
134
+ });
135
+ return new Response(stream, {
136
+ headers: {
137
+ "Content-Type": "text/plain; charset=utf-8",
138
+ "Cache-Control": "no-cache, no-transform",
139
+ },
140
+ });
141
+ }
142
+ catch (err) {
143
+ const error = err instanceof Error ? err : new Error(String(err));
144
+ if (onError)
145
+ return onError(error);
146
+ return NextResponse.json({ error: "Request failed" }, { status: 400 });
147
+ }
148
+ }
149
+ return { POST };
150
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @hilbras/sdk — Next.js edge middleware
3
+ *
4
+ * Subpath: `@hilbras/sdk/nextjs/edge`
5
+ *
6
+ * `hilbrasMiddleware` implements the rate-limit bucket keying. It is typed
7
+ * structurally against the Next request surface rather than importing
8
+ * `next/server`, and it has its own subpath so that `@hilbras/sdk/nextjs` stays
9
+ * importable in a project with no Next dependency.
10
+ */
11
+ export { hilbrasMiddleware, forwardedClientIp } from "./middleware.js";
12
+ export type { HilbrasMiddlewareOptions, RateLimitStore } from "./middleware.js";
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @hilbras/sdk — Next.js edge middleware
3
+ *
4
+ * Subpath: `@hilbras/sdk/nextjs/edge`
5
+ *
6
+ * `hilbrasMiddleware` implements the rate-limit bucket keying. It is typed
7
+ * structurally against the Next request surface rather than importing
8
+ * `next/server`, and it has its own subpath so that `@hilbras/sdk/nextjs` stays
9
+ * importable in a project with no Next dependency.
10
+ */
11
+ export { hilbrasMiddleware, forwardedClientIp } from "./middleware.js";
@@ -0,0 +1,85 @@
1
+ import { type NextRequestLike } from "../next-runtime.js";
2
+ export interface HilbrasMiddlewareOptions {
3
+ /** Rate limit: max requests per window (default: 60) */
4
+ maxRequests?: number;
5
+ /** Rate limit: window duration in seconds (default: 60) */
6
+ windowSeconds?: number;
7
+ /** Paths to exclude from middleware (default: ["/_next", "/favicon.ico"]) */
8
+ excludePaths?: string[];
9
+ /** Custom error response */
10
+ onError?: (error: string) => Response;
11
+ /**
12
+ * How many trusted reverse proxies sit in front of the app.
13
+ *
14
+ * `x-forwarded-for` is a comma-separated list that each proxy appends to, so
15
+ * the real client address sits `trustProxy` entries from the **right**. Taking
16
+ * the leftmost entry — which is what this middleware did before 2.3.0 — reads
17
+ * the value the *client* supplied, because the common proxies (nginx
18
+ * `proxy_add_x_forwarded_for`, Vercel, Cloudflare) prepend the real address to
19
+ * whatever the client sent. An attacker who rotated the header therefore got a
20
+ * fresh rate-limit bucket per request.
21
+ *
22
+ * Defaults to `0`: trust the rightmost entry, i.e. the address added by the
23
+ * proxy directly in front of you. Correct for a single proxy, and safe for
24
+ * none — see `fallbackKey`.
25
+ *
26
+ * Set this to the number of proxies in your chain. With no proxy at all,
27
+ * leave it at `0` and supply `fallbackKey`.
28
+ */
29
+ trustProxy?: number;
30
+ /**
31
+ * Key derivation for the rate-limit bucket, used when no trustworthy forwarded
32
+ * address is available.
33
+ */
34
+ fallbackKey?: (request: NextRequestLike) => string;
35
+ /**
36
+ * Counter backend. The default is in-process `Map` state, which is correct
37
+ * for a single instance or a dev server. Behind more than one instance each
38
+ * keeps its own counter, so the effective limit becomes
39
+ * `maxRequests × instances`. Pass a shared store (Redis, KV, or anything with
40
+ * a `hit` method) to make the limit global; that store must expire its own
41
+ * keys.
42
+ */
43
+ store?: RateLimitStore;
44
+ }
45
+ /** A counter backend. Entries must expire themselves. */
46
+ export interface RateLimitStore {
47
+ /** Increment and return the counter for `key` within a `windowMs` window. */
48
+ hit(key: string, windowMs: number): Promise<{
49
+ count: number;
50
+ resetAt: number;
51
+ }>;
52
+ /** Drop expired entries. Optional — a shared store expires its own keys. */
53
+ cleanup?(): void | Promise<void>;
54
+ }
55
+ /**
56
+ * Extract the client address from a `x-forwarded-for` list.
57
+ *
58
+ * Each proxy *appends* the address it saw, so the list reads
59
+ * `client-supplied, …, nearest-hop`. With `trustProxy` trusted proxies the real
60
+ * client sits `trustProxy` entries from the right, which is index
61
+ * `entries.length - trustProxy`:
62
+ *
63
+ * - `trustProxy: 0` — index `length`, i.e. out of range. Nothing is trusted, so
64
+ * there is no entry we can attribute to the client rather than to a proxy.
65
+ * - `trustProxy: 1` — `"9.9.9.1, 1.1.1.1"` gives index 1, the real client, and
66
+ * `9.9.9.1` (the attacker's) is correctly ignored.
67
+ * - `trustProxy: 2` — `"9.9.9.1, 1.1.1.1, 10.0.0.1"` gives index 1 again.
68
+ *
69
+ * Returns `undefined` when the list is absent or shorter than the trust depth,
70
+ * because in that case every entry present was chosen by the client.
71
+ */
72
+ export declare function forwardedClientIp(headerValue: string | null | undefined, trustProxy: number): string | undefined;
73
+ /**
74
+ * Next.js middleware for rate limiting AI API routes.
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * // middleware.ts
79
+ * import { hilbrasMiddleware } from "@hilbras/sdk/nextjs/edge";
80
+ *
81
+ * export const config = { matcher: ["/api/:path*"] };
82
+ * export default hilbrasMiddleware({ maxRequests: 30, trustProxy: 1 });
83
+ * ```
84
+ */
85
+ export declare function hilbrasMiddleware(options?: HilbrasMiddlewareOptions): (request: NextRequestLike) => Promise<import("../next-runtime.js").HilbrasNextResponse | Response>;