@arbol-ai/maximus 8.4.0 → 8.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/dist/body.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { n as readBodyBytes, r as readBodyText } from "./chunks/body-DOIHwIIl.js";
2
- import { a as readJsonResponse, i as readJsonBody, n as isJsonMediaType, o as retryAfterSeconds, t as publicDestination } from "./chunks/destination-DIkn8W6K.js";
2
+ import { a as retryAfterSeconds, i as readJsonResponse, r as readJsonBody, t as isJsonMediaType } from "./chunks/json-B14evE6-.js";
3
+ import { t as publicDestination } from "./chunks/destination-5xTX0b7E.js";
3
4
 
4
5
  export { isJsonMediaType, publicDestination, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, retryAfterSeconds };
@@ -0,0 +1,65 @@
1
+ // src/internal/destination.ts
2
+ /**
3
+ * Where a Worker may send a request for someone it does not control, such as a server an organization
4
+ * registered. A Worker cannot resolve a name before it fetches it, so the rules hold on the URL itself.
5
+ */
6
+ /**
7
+ * Top-level names reserved for special use or private networks (RFC 2606, 6761, 6762, 7686, 8375 and 9476),
8
+ * and the ones internal networks use.
9
+ */
10
+ const PRIVATE_TOP_LEVEL_NAMES = /* @__PURE__ */ new Set([
11
+ "alt",
12
+ "arpa",
13
+ "cloudflare",
14
+ "corp",
15
+ "example",
16
+ "home",
17
+ "internal",
18
+ "intranet",
19
+ "invalid",
20
+ "lan",
21
+ "local",
22
+ "localdomain",
23
+ "localhost",
24
+ "onion",
25
+ "private",
26
+ "test"
27
+ ]);
28
+ /**
29
+ * Cloudflare's own domains and Arbol's, subdomains included: Arbol's services are reached through the Gateway
30
+ * and native RPC, and neither ever stands for someone else's server.
31
+ */
32
+ const PLATFORM_DOMAINS = [
33
+ "cloudflare.com",
34
+ "cloudflareaccess.com",
35
+ "cloudflareclient.com",
36
+ "cloudflare-dns.com",
37
+ "cloudflare-gateway.com",
38
+ "getarbol.app",
39
+ "getarbol.com"
40
+ ];
41
+ /**
42
+ * A DNS name of two labels or more: letters, digits and inner hyphens, at most 63 characters a label and 253
43
+ * in all, under a top-level name of letters. An IP literal is none.
44
+ */
45
+ const DNS_NAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
46
+ /**
47
+ * The URL, when a Worker may send a request there for someone it does not control: https on its default port,
48
+ * with no credentials or fragment, to a public DNS name; never an IP literal, a special-use or private-network
49
+ * name, nor Cloudflare's or Arbol's own hosts. Undefined for anything else. Send the request with
50
+ * `redirect: 'manual'` and refuse a `3xx`, so no redirect takes it elsewhere.
51
+ */
52
+ function publicDestination(value) {
53
+ let url;
54
+ try {
55
+ url = new URL(value);
56
+ } catch {
57
+ return;
58
+ }
59
+ const host = url.hostname;
60
+ const topLevelName = host.slice(host.lastIndexOf(".") + 1);
61
+ if (url.protocol !== "https:" || url.port !== "" || url.username !== "" || url.password !== "" || url.hash !== "" || !DNS_NAME.test(host) || PRIVATE_TOP_LEVEL_NAMES.has(topLevelName) || PLATFORM_DOMAINS.some((domain) => host === domain || host.endsWith(`.${domain}`))) return;
62
+ return url;
63
+ }
64
+
65
+ export { publicDestination as t };
@@ -75,68 +75,4 @@ function retryAfterSeconds(value, nowMs, maximum = 3600) {
75
75
  return Number.isFinite(seconds) ? Math.min(maximum, Math.max(0, Math.ceil(seconds))) : void 0;
76
76
  }
77
77
 
78
- // src/internal/destination.ts
79
- /**
80
- * Where a Worker may send a request for someone it does not control, such as a server an organization
81
- * registered. A Worker cannot resolve a name before it fetches it, so the rules hold on the URL itself.
82
- */
83
- /**
84
- * Top-level names reserved for special use or private networks (RFC 2606, 6761, 6762, 7686, 8375 and 9476),
85
- * and the ones internal networks use.
86
- */
87
- const PRIVATE_TOP_LEVEL_NAMES = /* @__PURE__ */ new Set([
88
- "alt",
89
- "arpa",
90
- "cloudflare",
91
- "corp",
92
- "example",
93
- "home",
94
- "internal",
95
- "intranet",
96
- "invalid",
97
- "lan",
98
- "local",
99
- "localdomain",
100
- "localhost",
101
- "onion",
102
- "private",
103
- "test"
104
- ]);
105
- /**
106
- * Cloudflare's own domains and Arbol's, subdomains included: Arbol's services are reached through the Gateway
107
- * and native RPC, and neither ever stands for someone else's server.
108
- */
109
- const PLATFORM_DOMAINS = [
110
- "cloudflare.com",
111
- "cloudflareaccess.com",
112
- "cloudflareclient.com",
113
- "cloudflare-dns.com",
114
- "cloudflare-gateway.com",
115
- "getarbol.app",
116
- "getarbol.com"
117
- ];
118
- /**
119
- * A DNS name of two labels or more: letters, digits and inner hyphens, at most 63 characters a label and 253
120
- * in all, under a top-level name of letters. An IP literal is none.
121
- */
122
- const DNS_NAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
123
- /**
124
- * The URL, when a Worker may send a request there for someone it does not control: https on its default port,
125
- * with no credentials or fragment, to a public DNS name; never an IP literal, a special-use or private-network
126
- * name, nor Cloudflare's or Arbol's own hosts. Undefined for anything else. Send the request with
127
- * `redirect: 'manual'` and refuse a `3xx`, so no redirect takes it elsewhere.
128
- */
129
- function publicDestination(value) {
130
- let url;
131
- try {
132
- url = new URL(value);
133
- } catch {
134
- return;
135
- }
136
- const host = url.hostname;
137
- const topLevelName = host.slice(host.lastIndexOf(".") + 1);
138
- if (url.protocol !== "https:" || url.port !== "" || url.username !== "" || url.password !== "" || url.hash !== "" || !DNS_NAME.test(host) || PRIVATE_TOP_LEVEL_NAMES.has(topLevelName) || PLATFORM_DOMAINS.some((domain) => host === domain || host.endsWith(`.${domain}`))) return;
139
- return url;
140
- }
141
-
142
- export { readJsonResponse as a, readJsonBody as i, isJsonMediaType as n, retryAfterSeconds as o, mediaType as r, publicDestination as t };
78
+ export { retryAfterSeconds as a, readJsonResponse as i, mediaType as n, readJsonBody as r, isJsonMediaType as t };
@@ -3,7 +3,7 @@ import { r as isRequestId } from "./correlation-4b23a-a4.js";
3
3
  import { i as standardErrors } from "./errors-BoutSmiy.js";
4
4
  import { y as PrincipalSchema } from "./openapi-D2rds7vy.js";
5
5
  import { r as ok, t as err } from "./result-CF4OzG9O.js";
6
- import { r as createHttpHandler } from "./src-D67OfW9B.js";
6
+ import { r as createHttpHandler } from "./src-B_LthUVU.js";
7
7
  import { t as delay } from "./delay-BsKQP_lF.js";
8
8
  import { a as recordExecution, l as withTelemetry, o as reportUnexpected, s as telemetryEnabled } from "./telemetry-BtxJh69Q.js";
9
9
  import { n as recordCapture, t as executeOperation } from "./execution-Bpq6s4nA.js";
@@ -9,7 +9,7 @@ import { t as sha256Hex } from "./digest-C51F1bhA.js";
9
9
  import { a as recordExecution, i as recordAdmission, l as withTelemetry, o as reportUnexpected, s as telemetryEnabled } from "./telemetry-BtxJh69Q.js";
10
10
  import { n as recordCapture, t as executeOperation } from "./execution-Bpq6s4nA.js";
11
11
  import { a as ownsPrefix, i as nativePaths, n as composition, o as servesCloudflareAccess, r as httpTransports, s as servesOwnBearer, t as VERSIONED_PATH } from "./http-layout-BcYH4I2w.js";
12
- import { r as mediaType } from "./destination-DIkn8W6K.js";
12
+ import { n as mediaType } from "./json-B14evE6-.js";
13
13
  import { t as toYaml } from "./yaml-Dk2L24yQ.js";
14
14
  import { Type as Type$1, Type as t } from "typebox";
15
15
 
@@ -0,0 +1,92 @@
1
+ import { F as Static, jr as Failure, xn as OperationShape } from "./chunks/types-BfGa2aJT.js";
2
+ /** What every HTTP operation answers: its data on success, its failure otherwise, and the request id. */
3
+ export type Envelope<T> = {
4
+ success: true;
5
+ data: T;
6
+ error: null;
7
+ metadata: {
8
+ requestId: string;
9
+ };
10
+ } | {
11
+ success: false;
12
+ data: null;
13
+ error: Failure;
14
+ metadata: {
15
+ requestId: string;
16
+ };
17
+ };
18
+ /** The part of an application the client's types read: its operations. `typeof app` satisfies it. */
19
+ export interface ClientManifest {
20
+ operations: Record<string, OperationShape>;
21
+ }
22
+ /** The operations public over HTTP: those with a route that are not internal. */
23
+ export type OperationName<M extends ClientManifest> = Extract<{ [K in keyof M['operations']]: M['operations'][K] extends {
24
+ http: object;
25
+ } ? M['operations'][K] extends {
26
+ visibility: 'internal';
27
+ } ? never : K : never; }[keyof M['operations']], string>;
28
+ /** The operations that read, POST searches included: what a read cache may own, whatever the method. */
29
+ export type ReadOperationName<M extends ClientManifest> = { [K in OperationName<M>]: M['operations'][K] extends {
30
+ effect: 'read';
31
+ } ? K : never; }[OperationName<M>];
32
+ /** What an operation takes, as callers send it, path fields included. */
33
+ export type OperationInput<M extends ClientManifest, K extends OperationName<M>> = Static<M['operations'][K]['input']>;
34
+ /** What an operation answers: its output, or the Response of an attachment. */
35
+ export type OperationOutput<M extends ClientManifest, K extends OperationName<M>> = M['operations'][K] extends {
36
+ http: {
37
+ response: 'attachment';
38
+ };
39
+ } ? Response : Static<M['operations'][K]['output']>;
40
+ /** Options of one call: a signal that cancels it. */
41
+ export interface CallOptions {
42
+ signal?: AbortSignal;
43
+ }
44
+ /** Options of one call to a byte operation: the bytes and the transfer's two moments. */
45
+ export interface BinaryCallOptions extends CallOptions {
46
+ /** Sent with its own type, unless a header field of the input names the content type. */
47
+ body: Blob | Uint8Array<ArrayBuffer>;
48
+ /** 0 when sending begins, 1 after a success response; not byte progress. */
49
+ onUploadProgress?: (share: 0 | 1) => void;
50
+ }
51
+ /** A refusal the service answered: its status, its failure and the request's id (empty when invalid). */
52
+ export interface ClientFailure {
53
+ status: number;
54
+ failure: Failure;
55
+ requestId: string;
56
+ }
57
+ /** How the client answers and bounds what it reads, and the hooks around each request. */
58
+ export interface ClientOptions {
59
+ /** `data` answers each call's data and throws its refusal; the envelope is answered otherwise. */
60
+ response?: 'data' | 'envelope';
61
+ /** A signal taken at each call, before anything awaits. */
62
+ signal?: () => AbortSignal;
63
+ /** The Error a refusal throws in `data` mode. */
64
+ onFailure?: (refusal: ClientFailure) => Error;
65
+ /** The fetch every request goes through: the global one, or a test's Worker. */
66
+ fetch?: typeof fetch;
67
+ /** May add headers; the method, URL, body and bearer stay the client's. */
68
+ beforeRequest?: (request: Request) => void | Promise<void>;
69
+ afterResponse?: (response: Response, request: Request) => void | Promise<void>;
70
+ /** The largest operation response read: 1 MiB unless set. */
71
+ maxResponseBytes?: number;
72
+ }
73
+ type Answer<M extends ClientManifest, K extends OperationName<M>, Mode> = Mode extends 'data' ? OperationOutput<M, K> : Envelope<OperationOutput<M, K>>;
74
+ /** One method per public HTTP operation; a byte operation also takes its body in the call options. */
75
+ export type AppClientContract<M extends ClientManifest, Mode extends 'data' | 'envelope' = 'envelope'> = { [K in OperationName<M>]: M['operations'][K] extends {
76
+ http: {
77
+ body: 'bytes';
78
+ };
79
+ } ? (input: OperationInput<M, K>, options: BinaryCallOptions) => Promise<Answer<M, K, Mode>> : (input: OperationInput<M, K>, options?: CallOptions) => Promise<Answer<M, K, Mode>>; };
80
+ /**
81
+ * A typed client of an application, from its type alone (`createClient<typeof app>(…)`), for the service at
82
+ * `origin` (a base URL that may carry a path, such as `https://agenda.getarbol.com/api`). `token` is the
83
+ * bearer, or a function asked for it before every request, so a renewed token is always the one sent. With
84
+ * `response: 'data'`, a method answers the data and throws on a refusal; otherwise it answers the envelope.
85
+ */
86
+ export declare function createClient<M extends ClientManifest>(origin: string, token: string | (() => Promise<string>), options: ClientOptions & {
87
+ response: 'data';
88
+ }): AppClientContract<M, 'data'>;
89
+ export declare function createClient<M extends ClientManifest>(origin: string, token: string | (() => Promise<string>), options?: ClientOptions & {
90
+ response?: 'envelope';
91
+ }): AppClientContract<M>;
92
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,300 @@
1
+ import { a as operationPathParameters, i as isPathParameterValue, r as isInputHeaderName } from "./chunks/http-paths-D043DkJv.js";
2
+ import { i as readJsonResponse } from "./chunks/json-B14evE6-.js";
3
+
4
+ // src/client.ts
5
+ const TIMEOUT_MS = 3e4;
6
+ const MAX_CONTRACT_BYTES = 4194304;
7
+ const DEFAULT_MAX_RESPONSE_BYTES = 1048576;
8
+ const MAX_FAILURE_BYTES = 16384;
9
+ const MAX_ATTACHMENT_BYTES = 16777216;
10
+ const METHODS = /* @__PURE__ */ new Set([
11
+ "get",
12
+ "post",
13
+ "put",
14
+ "patch",
15
+ "delete"
16
+ ]);
17
+ /** Maximus's request ids: a UUID, or a Cloudflare ray. */
18
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
19
+ const RAY = /^[0-9a-f]{16}(?:-[A-Z]{3})?$/u;
20
+ /** What a malformed refusal reads as: the service's own failure, never its unchecked text. */
21
+ const INTERNAL_FAILURE = {
22
+ code: "INTERNAL_ERROR",
23
+ message: "The service could not complete the operation.",
24
+ retryable: false,
25
+ data: {}
26
+ };
27
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
28
+ const isRequestId = (value) => typeof value === "string" && (UUID.test(value) || RAY.test(value));
29
+ const isFailure = (value) => isRecord(value) && Object.keys(value).length === 4 && typeof value.code === "string" && /^[^\p{Cc}]{1,128}$/u.test(value.code) && typeof value.message === "string" && typeof value.retryable === "boolean" && isRecord(value.data);
30
+ /** What an abort listener is before it is listening. */
31
+ const ignore = () => {};
32
+ /** Waits for `pending` until `signal` aborts, then rejects with its reason; the work itself goes on. */
33
+ async function untilAborted(pending, signal) {
34
+ signal.throwIfAborted();
35
+ let abort = ignore;
36
+ const aborted = new Promise((_resolve, reject) => {
37
+ abort = () => reject(signal.reason);
38
+ signal.addEventListener("abort", abort, { once: true });
39
+ });
40
+ try {
41
+ return await Promise.race([pending, aborted]);
42
+ } finally {
43
+ signal.removeEventListener("abort", abort);
44
+ }
45
+ }
46
+ /** A GET input value as the service's query reads it back; null for one a query string cannot carry. */
47
+ function queryValue(value) {
48
+ if (typeof value === "string") return value;
49
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : null;
50
+ if (typeof value === "boolean") return String(value);
51
+ return Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string" && item !== "" && !item.includes(",")) ? value.join(",") : null;
52
+ }
53
+ /** One operation's route, or null for a method the client does not send. */
54
+ function readRoute(path, method, operation) {
55
+ if (!METHODS.has(method)) return null;
56
+ const headers = isRecord(operation) ? operation["x-input-headers"] ?? {} : null;
57
+ if (!isRecord(operation) || typeof operation.operationId !== "string" || !isRecord(headers) || Object.values(headers).some((header) => typeof header !== "string" || !isInputHeaderName(header))) throw new Error("Invalid service operation.");
58
+ return [operation.operationId, {
59
+ method: method.toUpperCase(),
60
+ path,
61
+ parameters: operationPathParameters(path),
62
+ headers,
63
+ bytes: operation["x-body"] === "bytes",
64
+ attachment: operation["x-response"] === "attachment"
65
+ }];
66
+ }
67
+ /** Every operation's route, method, header fields, byte body and attachment, from an OpenAPI document. */
68
+ function readRoutes(document) {
69
+ const paths = isRecord(document) ? document.paths : void 0;
70
+ if (!isRecord(paths)) throw new Error("Invalid service contract.");
71
+ const routes = /* @__PURE__ */ new Map();
72
+ for (const [path, methods] of Object.entries(paths)) for (const [method, operation] of Object.entries(isRecord(methods) ? methods : {})) {
73
+ const entry = readRoute(path, method, operation);
74
+ if (entry && routes.has(entry[0])) throw new Error("Invalid service operation.");
75
+ if (entry) routes.set(...entry);
76
+ }
77
+ return routes;
78
+ }
79
+ /** An operation's envelope, its shape and status checked before any data or failure reaches the caller. */
80
+ function readEnvelope(value, status) {
81
+ if (isRecord(value) && Object.keys(value).length === 4 && Object.hasOwn(value, "data") && isRecord(value.metadata) && Object.keys(value.metadata).length === 1 && isRequestId(value.metadata.requestId)) {
82
+ const metadata = { requestId: value.metadata.requestId };
83
+ if (value.success === true && value.error === null && status >= 200 && status < 300) return {
84
+ success: true,
85
+ data: value.data,
86
+ error: null,
87
+ metadata
88
+ };
89
+ if (value.success === false && value.data === null && isFailure(value.error) && status >= 400 && status < 600) return {
90
+ success: false,
91
+ data: null,
92
+ error: value.error,
93
+ metadata
94
+ };
95
+ }
96
+ throw new Error(`Invalid service response (${status}).`);
97
+ }
98
+ /** A byte operation's request: the bytes as its body, its string fields as headers or query. */
99
+ function prepareBytes(route, url, rest, options) {
100
+ const upload = options;
101
+ if (!(upload?.body instanceof Blob || upload?.body instanceof Uint8Array)) throw new TypeError("A binary body is required.");
102
+ const headers = new Headers();
103
+ for (const [field, value] of rest) {
104
+ if (value === void 0) continue;
105
+ if (typeof value !== "string") throw new TypeError("Header and query values of a byte operation must be strings.");
106
+ const header = route.headers[field];
107
+ if (header) headers.set(header, value);
108
+ else url.searchParams.set(field, value);
109
+ }
110
+ if (!headers.has("content-type")) {
111
+ const type = upload.body instanceof Blob ? upload.body.type : "";
112
+ headers.set("content-type", type || "application/octet-stream");
113
+ }
114
+ return {
115
+ url,
116
+ headers,
117
+ body: upload.body,
118
+ upload
119
+ };
120
+ }
121
+ /** A GET request: every field that is not in the path travels in the query. */
122
+ function prepareQuery(url, rest) {
123
+ for (const [field, value] of rest) {
124
+ if (value === void 0) continue;
125
+ const text = queryValue(value);
126
+ if (text === null) throw new TypeError("Query values must be strings, finite numbers, booleans or lists of strings.");
127
+ url.searchParams.set(field, text);
128
+ }
129
+ return {
130
+ url,
131
+ headers: new Headers(),
132
+ body: void 0,
133
+ upload: void 0
134
+ };
135
+ }
136
+ /** The service URL of one route, its path fields filled in and encoded. */
137
+ function routeUrl(route, input, serviceUrl) {
138
+ let { path } = route;
139
+ for (const parameter of route.parameters) {
140
+ const value = input[parameter];
141
+ if (!isPathParameterValue(value)) throw new TypeError("Path values must be nonempty strings without slashes, dot segments or controls.");
142
+ path = path.replace(`{${parameter}}`, encodeURIComponent(value));
143
+ }
144
+ return serviceUrl(path);
145
+ }
146
+ /** The call's URL, headers and body: path fields in the path, the rest in the query, headers or JSON body. */
147
+ function prepare(route, input, options, serviceUrl) {
148
+ const url = routeUrl(route, input, serviceUrl);
149
+ const rest = Object.entries(input).filter(([field]) => !route.parameters.includes(field));
150
+ if (route.bytes) return prepareBytes(route, url, rest, options);
151
+ if (route.method === "GET") return prepareQuery(url, rest);
152
+ return {
153
+ url,
154
+ headers: new Headers({ "content-type": "application/json" }),
155
+ body: JSON.stringify(Object.fromEntries(rest)),
156
+ upload: void 0
157
+ };
158
+ }
159
+ /** An attachment's answer: the Response itself, once its declared length is within bounds. */
160
+ function attachmentAnswer(response, dataMode) {
161
+ const length = Number(response.headers.get("content-length") ?? NaN);
162
+ if (!Number.isSafeInteger(length) || length < 0 || length > MAX_ATTACHMENT_BYTES) throw new Error("Invalid attachment length.");
163
+ if (dataMode) return response;
164
+ return {
165
+ success: true,
166
+ data: response,
167
+ error: null,
168
+ metadata: { requestId: response.headers.get("x-request-id") ?? "" }
169
+ };
170
+ }
171
+ /** The envelope a response carries; in data mode a malformed refusal reads as the internal failure. */
172
+ function answeredEnvelope(value, response, dataMode) {
173
+ try {
174
+ return readEnvelope(value, response.status);
175
+ } catch (error) {
176
+ if (!dataMode || response.ok) throw error;
177
+ const requestId = response.headers.get("x-request-id");
178
+ return {
179
+ success: false,
180
+ data: null,
181
+ error: INTERNAL_FAILURE,
182
+ metadata: { requestId: isRequestId(requestId) ? requestId : "" }
183
+ };
184
+ }
185
+ }
186
+ function createClient(origin, token, options = {}) {
187
+ const base = new URL(origin);
188
+ const prefix = base.pathname.replace(/\/$/u, "");
189
+ const serviceUrl = (path) => new URL(`${prefix}${path}`, base.origin);
190
+ const transport = options.fetch ?? fetch;
191
+ const dataMode = options.response === "data";
192
+ let routes;
193
+ /** The bearer of one request: the token, or the one its function answers now. */
194
+ async function bearer(signal) {
195
+ if (typeof token === "string") return token;
196
+ return await untilAborted(token(), signal);
197
+ }
198
+ /** Sends one request after the hooks: they add headers, never the bearer, method, body or deadline. */
199
+ async function send(url, init, authenticated = true) {
200
+ const { signal } = init;
201
+ const authorization = authenticated ? `Bearer ${await bearer(signal)}` : void 0;
202
+ const request = new Request(url, {
203
+ ...init,
204
+ redirect: "manual",
205
+ credentials: "omit",
206
+ cache: "no-store"
207
+ });
208
+ await untilAborted(Promise.resolve(options.beforeRequest?.(request)), signal);
209
+ for (const [header, value] of new Headers(init.headers)) request.headers.set(header, value);
210
+ if (authorization) request.headers.set("authorization", authorization);
211
+ else request.headers.delete("authorization");
212
+ const response = await untilAborted(transport(url, {
213
+ ...init,
214
+ headers: Object.fromEntries(request.headers),
215
+ redirect: "manual",
216
+ credentials: "omit",
217
+ cache: "no-store"
218
+ }), signal);
219
+ await untilAborted(Promise.resolve(options.afterResponse?.(response, request)), signal);
220
+ return response;
221
+ }
222
+ /** The routes, read once from the live contract. */
223
+ async function discover() {
224
+ const signal = AbortSignal.timeout(TIMEOUT_MS);
225
+ const response = await send(serviceUrl("/openapi.json"), {
226
+ method: "GET",
227
+ signal
228
+ }, false);
229
+ const document = await readJsonResponse(response, {
230
+ signal,
231
+ maxBytes: MAX_CONTRACT_BYTES
232
+ });
233
+ if (!response.ok || !document.ok) throw new Error("Invalid service contract.");
234
+ return readRoutes(document.value);
235
+ }
236
+ /** The route of an operation; a failed read of the contract is tried again by the next call. */
237
+ async function routeOf(name, signal) {
238
+ routes ??= discover();
239
+ let known;
240
+ try {
241
+ known = await untilAborted(routes, signal);
242
+ } catch (error) {
243
+ routes = void 0;
244
+ throw error;
245
+ }
246
+ const route = known.get(name);
247
+ if (!route) throw new Error("Operation is not exposed over HTTP.");
248
+ return route;
249
+ }
250
+ /** What a call answers in data mode: the data, or the Error its refusal throws. */
251
+ function dataOf(envelope, status) {
252
+ if (envelope.success) return envelope.data;
253
+ const refusal = {
254
+ status,
255
+ failure: envelope.error,
256
+ requestId: envelope.metadata.requestId
257
+ };
258
+ throw options.onFailure?.(refusal) ?? new Error("The service refused the request.", { cause: refusal });
259
+ }
260
+ /** One call: route, request, then the envelope, or the attachment, as the client's mode answers it. */
261
+ async function call(name, input, callOptions) {
262
+ const signals = [
263
+ AbortSignal.timeout(TIMEOUT_MS),
264
+ options.signal?.(),
265
+ callOptions?.signal
266
+ ];
267
+ const signal = AbortSignal.any(signals.filter((entry) => entry !== void 0));
268
+ signal.throwIfAborted();
269
+ const route = await routeOf(name, signal);
270
+ const { url, headers, body, upload } = prepare(route, input, callOptions, serviceUrl);
271
+ upload?.onUploadProgress?.(0);
272
+ const response = await send(url, {
273
+ method: route.method,
274
+ signal,
275
+ headers,
276
+ body
277
+ });
278
+ if (route.attachment && response.ok) {
279
+ const answer = attachmentAnswer(response, dataMode);
280
+ upload?.onUploadProgress?.(1);
281
+ return answer;
282
+ }
283
+ const maxBytes = options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
284
+ const limit = response.ok ? maxBytes : Math.min(maxBytes, MAX_FAILURE_BYTES);
285
+ const read = await readJsonResponse(response, {
286
+ signal,
287
+ maxBytes: limit
288
+ });
289
+ signal.throwIfAborted();
290
+ const envelope = answeredEnvelope(read.ok ? read.value : void 0, response, dataMode);
291
+ if (envelope.success) upload?.onUploadProgress?.(1);
292
+ return dataMode ? dataOf(envelope, response.status) : envelope;
293
+ }
294
+ return new Proxy(Object.create(null), { get(_target, name) {
295
+ if (typeof name !== "string" || name === "then") return;
296
+ return (input, callOptions) => call(name, input, callOptions);
297
+ } });
298
+ }
299
+
300
+ export { createClient };
package/dist/index.js CHANGED
@@ -6,9 +6,10 @@ import { t as createHttpRouteResolver } from "./chunks/http-paths-D043DkJv.js";
6
6
  import { S as matchesScopes, b as operationScopes, m as isPublicOperation, v as operationMatchesScopes } from "./chunks/tasks-DYdY-dBI.js";
7
7
  import { _ as projectAccessToken, a as createTokenVerifier, i as createTokenAuthorization, n as createRpcOpenApi, s as projectToken, t as createOpenApi, y as PrincipalSchema } from "./chunks/openapi-D2rds7vy.js";
8
8
  import { n as isResult, r as ok, t as err } from "./chunks/result-CF4OzG9O.js";
9
- import { a as maximus, i as protectedResourceMetadata, n as t, r as createHttpHandler, t as Type } from "./chunks/src-D67OfW9B.js";
9
+ import { a as maximus, i as protectedResourceMetadata, n as t, r as createHttpHandler, t as Type } from "./chunks/src-B_LthUVU.js";
10
10
  import { a as defineTelemetry, i as defineHandler, n as defineAuth, o as defineTool, r as defineContext } from "./chunks/handler-DSpyrWc-.js";
11
11
  import { o as reportUnexpected } from "./chunks/telemetry-BtxJh69Q.js";
12
- import { a as readJsonResponse, i as readJsonBody, n as isJsonMediaType, o as retryAfterSeconds, t as publicDestination } from "./chunks/destination-DIkn8W6K.js";
12
+ import { a as retryAfterSeconds, i as readJsonResponse, r as readJsonBody, t as isJsonMediaType } from "./chunks/json-B14evE6-.js";
13
+ import { t as publicDestination } from "./chunks/destination-5xTX0b7E.js";
13
14
 
14
15
  export { AttachmentOutputSchema, DeletedObjectSchema, EmailAddressSchema, EmptyInputSchema, FailureSchema, HexColorSchema, HttpsUrlSchema, NamedReferenceSchema, OrganizationIdSchema, Page, PageInfoSchema, PageQueryFields, PhoneNumberSchema, PostalAddressSchema, PrincipalSchema, SignedUrlSchema, Type, UuidSchema, createHttpHandler, createHttpRouteResolver, createOpenApi, createRpcOpenApi, createTokenAuthorization, createTokenVerifier, cursorKey, cutPage, defineAuth, defineContext, defineErrors, defineHandler, defineTelemetry, defineTool, err, isJsonMediaType, isPublicOperation, isResult, matchesScopes, maximus, ok, operationMatchesScopes, operationScopes, pageLimit, parseInput, parseSchema, projectAccessToken, projectToken, protectedResourceMetadata, publicDestination, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, reportUnexpected, resultSchema, retryAfterSeconds, standardErrors, t };
@@ -1,5 +1,5 @@
1
1
  import { i as standardErrors } from "../chunks/errors-BoutSmiy.js";
2
- import { r as createAssetHandler, t as createWorker } from "../chunks/runtime-CGtS2rOb.js";
2
+ import { r as createAssetHandler, t as createWorker } from "../chunks/runtime-8OpxAvsI.js";
3
3
  import { t as checkPagePaths } from "../chunks/pages-B7ysoFAM.js";
4
4
 
5
5
  // src/project/handlers.ts
@@ -1,3 +1,3 @@
1
- import { n as credentials, t as createWorker } from "../chunks/runtime-CGtS2rOb.js";
1
+ import { n as credentials, t as createWorker } from "../chunks/runtime-8OpxAvsI.js";
2
2
 
3
3
  export { createWorker, credentials };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arbol-ai/maximus",
3
- "version": "8.4.0",
3
+ "version": "8.5.0",
4
4
  "description": "Maximus: define a service once and serve it over HTTP, MCP and Worker RPC on Cloudflare Workers, configured in vite.config.ts, with its OpenAPI and CLI.",
5
5
  "keywords": [
6
6
  "api",
@@ -63,6 +63,10 @@
63
63
  "types": "./dist/body.d.ts",
64
64
  "import": "./dist/body.js"
65
65
  },
66
+ "./client": {
67
+ "types": "./dist/client.d.ts",
68
+ "import": "./dist/client.js"
69
+ },
66
70
  "./webhooks": {
67
71
  "types": "./dist/webhooks.d.ts",
68
72
  "import": "./dist/webhooks.js"