@arbol-ai/maximus 0.0.0-stage → 7.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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +51 -2
  3. package/config/oxfmt.d.mts +8 -0
  4. package/config/oxfmt.mjs +30 -0
  5. package/config/oxlint-plugin.mjs +41 -0
  6. package/config/oxlint.d.mts +8 -0
  7. package/config/oxlint.mjs +118 -0
  8. package/dist/analytics/analytics.d.ts +34 -0
  9. package/dist/analytics/analytics.js +62 -0
  10. package/dist/body.d.ts +2 -0
  11. package/dist/body.js +4 -0
  12. package/dist/chunks/body-BcMbreNd.js +106 -0
  13. package/dist/chunks/correlation-gaiEoMBr.js +45 -0
  14. package/dist/chunks/execution-qfZuMSIu.js +700 -0
  15. package/dist/chunks/json-Dwni3u4c.js +63 -0
  16. package/dist/chunks/record-D2H3cg8S.js +36 -0
  17. package/dist/chunks/schemas-q-51wBMQ.js +216 -0
  18. package/dist/chunks/src-Ph5KHCRP.js +1160 -0
  19. package/dist/chunks/telemetry-DvZgrzZn.js +220 -0
  20. package/dist/chunks/types-CGwAhnTE.d.ts +1630 -0
  21. package/dist/chunks/validation-DWxKk1Js.js +382 -0
  22. package/dist/client/client.d.ts +131 -0
  23. package/dist/client/client.js +325 -0
  24. package/dist/diagnostics.d.ts +41 -0
  25. package/dist/diagnostics.js +4 -0
  26. package/dist/errors.d.ts +2 -0
  27. package/dist/errors.js +128 -0
  28. package/dist/http-paths.d.ts +2 -0
  29. package/dist/http-paths.js +200 -0
  30. package/dist/index.d.ts +2 -0
  31. package/dist/index.js +11 -0
  32. package/dist/internals.d.ts +2 -0
  33. package/dist/internals.js +5 -0
  34. package/dist/mcp/index.d.ts +12 -0
  35. package/dist/mcp/index.js +406 -0
  36. package/dist/postgres/index.d.ts +81 -0
  37. package/dist/postgres/index.js +140 -0
  38. package/dist/schemas.d.ts +2 -0
  39. package/dist/schemas.js +4 -0
  40. package/dist/standard-failures.d.ts +91 -0
  41. package/dist/standard-failures.js +75 -0
  42. package/dist/tooling/cli.js +110 -0
  43. package/dist/tooling/testing.d.ts +7 -0
  44. package/dist/tooling/testing.js +21 -0
  45. package/dist/webhooks.d.ts +69 -0
  46. package/dist/webhooks.js +162 -0
  47. package/dist/workers/runtime.d.ts +112 -0
  48. package/dist/workers/runtime.js +228 -0
  49. package/package.json +153 -4
  50. package/skills/maximus/SKILL.md +89 -0
  51. package/skills/maximus/references/adding-an-operation.md +179 -0
  52. package/skills/maximus/references/building-a-service.md +158 -0
  53. package/skills/maximus/references/errors-and-results.md +77 -0
  54. package/skills/maximus/references/migration-from-v2.md +62 -0
  55. package/skills/maximus/references/migration-to-v5.md +37 -0
  56. package/skills/maximus/references/publishing-and-verification.md +39 -0
  57. package/skills/maximus/references/testing.md +73 -0
  58. package/skills/maximus/references/transports.md +119 -0
  59. package/templates/service/.agents/skills/project/SKILL.md.template +10 -0
  60. package/templates/service/.github/workflows/ci.yml.template +21 -0
  61. package/templates/service/.gitignore.template +8 -0
  62. package/templates/service/CLAUDE.md.template +3 -0
  63. package/templates/service/README.md.template +45 -0
  64. package/templates/service/cloudflare.config.ts.template +30 -0
  65. package/templates/service/oxfmt.config.ts.template +1 -0
  66. package/templates/service/oxlint.config.ts.template +1 -0
  67. package/templates/service/package.json.template +31 -0
  68. package/templates/service/src/app.ts.template +30 -0
  69. package/templates/service/src/index.ts.template +13 -0
  70. package/templates/service/tests/contract.test.ts.template +12 -0
  71. package/templates/service/tsconfig.json.template +16 -0
  72. package/templates/service/vite.config.ts.template +7 -0
  73. package/templates/service/vitest.config.ts.template +10 -0
@@ -0,0 +1,325 @@
1
+ import { r as isRequestId } from "../chunks/correlation-gaiEoMBr.js";
2
+ import { standardErrors } from "../errors.js";
3
+ import { n as exactLength, t as isRecord } from "../chunks/record-D2H3cg8S.js";
4
+ import { isInputHeaderName, isPathParameterValue, operationPathParameters } from "../http-paths.js";
5
+ import { i as readJsonResponse } from "../chunks/json-Dwni3u4c.js";
6
+
7
+ //#region src/client/attachment-response.ts
8
+ /**
9
+ * An attachment as the typed client hands it out: a Response whose body is held to the length its headers
10
+ * declare.
11
+ */
12
+ /** Bound raw response streams without buffering or trusting an unbounded/chunked attachment. */
13
+ function boundedAttachment(response, maxBytes) {
14
+ const rawLength = response.headers.get("content-length");
15
+ if (!rawLength || !/^\d+$/u.test(rawLength) || !Number.isSafeInteger(Number(rawLength)) || Number(rawLength) > maxBytes) throw new Error("Invalid attachment length.");
16
+ const length = Number(rawLength);
17
+ if (!response.body) {
18
+ if (length !== 0) throw new Error("Missing attachment body.");
19
+ return response;
20
+ }
21
+ return new Response(exactLength(response.body, length), {
22
+ status: response.status,
23
+ statusText: response.statusText,
24
+ headers: response.headers
25
+ });
26
+ }
27
+
28
+ //#endregion
29
+ //#region src/client/operation-abort.ts
30
+ /**
31
+ * Lets a client call stop waiting when its caller aborts, without cancelling the work it waited for.
32
+ */
33
+ /**
34
+ * Waits for `pending` until the caller's `signal` aborts, then rejects with its reason. The pending work
35
+ * itself goes on, so a shared one, such as route discovery, still serves the other calls.
36
+ */
37
+ async function awaitWithSignal(pending, signal) {
38
+ signal?.throwIfAborted();
39
+ if (!signal) return pending;
40
+ let abort;
41
+ const aborted = new Promise((_resolve, reject) => {
42
+ abort = () => reject(signal.reason);
43
+ signal.addEventListener("abort", abort, { once: true });
44
+ });
45
+ try {
46
+ return await Promise.race([pending, aborted]);
47
+ } finally {
48
+ if (abort) signal.removeEventListener("abort", abort);
49
+ }
50
+ }
51
+
52
+ //#endregion
53
+ //#region src/client/response-envelope.ts
54
+ /**
55
+ * Reads an operation's response envelope as the typed client receives it, checking its shape and its
56
+ * status before any data or failure reaches the caller.
57
+ */
58
+ /**
59
+ * Whether a value is a well-formed failure: exactly code, message, retryable and data, with a printable code.
60
+ */
61
+ const failure = (value) => isRecord(value) && Object.keys(value).length === 4 && typeof value.code === "string" && value.code.length > 0 && value.code.length <= 128 && !/\p{Cc}/u.test(value.code) && typeof value.message === "string" && typeof value.retryable === "boolean" && isRecord(value.data);
62
+ /** Validate protocol discriminants and status consistency before data or refusal reaches a caller. */
63
+ function responseEnvelope(value, status) {
64
+ 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)) throw new Error(`Invalid service response (${status}).`);
65
+ const metadata = { requestId: value.metadata.requestId };
66
+ if (value.success === true && value.error === null && status >= 200 && status < 300) return {
67
+ success: true,
68
+ data: value.data,
69
+ error: null,
70
+ metadata
71
+ };
72
+ if (value.success === false && value.data === null && failure(value.error) && status >= 400 && status <= 599) return {
73
+ success: false,
74
+ data: null,
75
+ error: value.error,
76
+ metadata
77
+ };
78
+ throw new Error(`Invalid service response (${status}).`);
79
+ }
80
+ /** The largest refusal body the client reads, whatever its success limit. */
81
+ const MAX_FAILURE_BYTES = 16384;
82
+ /** Refusal decoding never grants a successful operation's larger body budget or exposes unvalidated server text. */
83
+ async function readOperationEnvelope(response, options) {
84
+ const result = await readJsonResponse(response, {
85
+ signal: options.signal,
86
+ maxBytes: response.ok ? options.maxBytes : Math.min(options.maxBytes, MAX_FAILURE_BYTES)
87
+ });
88
+ options.signal.throwIfAborted();
89
+ try {
90
+ if (!result.ok) throw new Error(`Invalid service response (${response.status}).`);
91
+ return responseEnvelope(result.value, response.status);
92
+ } catch (error) {
93
+ if (!options.dataMode || response.ok) throw error;
94
+ const requestId = response.headers.get("x-request-id");
95
+ return {
96
+ success: false,
97
+ data: null,
98
+ error: standardErrors.internal.create(),
99
+ metadata: { requestId: isRequestId(requestId) ? requestId : "" }
100
+ };
101
+ }
102
+ }
103
+
104
+ //#endregion
105
+ //#region src/client/client.ts
106
+ /**
107
+ * `@arbol-ai/maximus/client`: the typed HTTP client. Its methods are inferred from the application's type
108
+ * alone, and its routes come from the service's live OpenAPI document.
109
+ */
110
+ /** Progress observes validated transfer lifecycle; callback failure cannot replay or change a request. */
111
+ function notifyUploadTransfer(upload, share) {
112
+ try {
113
+ upload?.onUploadProgress?.(share);
114
+ } catch {}
115
+ }
116
+ /** The response body limit when the client sets none: 1 MiB. */
117
+ const DEFAULT_MAX_RESPONSE_BYTES = 1048576;
118
+ /** The largest response body limit a client may set: 16 MiB. */
119
+ const MAX_RESPONSE_BYTES = 16777216;
120
+ /**
121
+ * A GET input value as the service's query codec reads it back: a string as it is, a finite number, a
122
+ * boolean as `true` or `false`, and a list of nonempty strings without commas joined by commas. Null for a
123
+ * value a query string cannot carry.
124
+ */
125
+ function queryValue(value) {
126
+ if (typeof value === "string") return value;
127
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : null;
128
+ if (typeof value === "boolean") return String(value);
129
+ return Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string" && item !== "" && !item.includes(",")) ? value.join(",") : null;
130
+ }
131
+ function createClient(origin, token, options = {}) {
132
+ const maxResponseBytes = options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
133
+ if (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes < 1 || maxResponseBytes > MAX_RESPONSE_BYTES) throw new RangeError("maxResponseBytes must be an integer between 1 byte and 16 MiB.");
134
+ const maxAttachmentBytes = options.maxAttachmentBytes ?? MAX_RESPONSE_BYTES;
135
+ if (!Number.isSafeInteger(maxAttachmentBytes) || maxAttachmentBytes < 1 || maxAttachmentBytes > MAX_RESPONSE_BYTES) throw new RangeError("Invalid attachment byte limit.");
136
+ const base = new URL(origin);
137
+ const loopback = [
138
+ "localhost",
139
+ "127.0.0.1",
140
+ "[::1]"
141
+ ].includes(base.hostname);
142
+ if (!(base.protocol === "https:" || base.protocol === "http:" && loopback) || base.username || base.password || !/^\/(?:[a-zA-Z0-9_-]+\/)*[a-zA-Z0-9_-]*$/.test(base.pathname) || base.search || base.hash) throw new TypeError("Use an HTTPS origin (plain HTTP only on localhost).");
143
+ const prefix = base.pathname.replace(/\/$/, "");
144
+ /** A service path as a URL below the base URL's own path. */
145
+ const serviceUrl = (path) => new URL(`${prefix}${path}`, base.origin);
146
+ const transport = options.fetch ?? fetch;
147
+ let routes;
148
+ /**
149
+ * Reads every operation's route, method, byte body, attachment and header fields from the service's live
150
+ * OpenAPI document.
151
+ */
152
+ async function discover() {
153
+ const signal = AbortSignal.timeout(options.timeoutMs ?? 3e4);
154
+ const response = await send(serviceUrl("/openapi.json"), {
155
+ method: "GET",
156
+ signal
157
+ }, void 0, false);
158
+ const result = await readJsonResponse(response, {
159
+ signal,
160
+ maxBytes: 4194304
161
+ });
162
+ if (!response.ok || !result.ok || !result.value || typeof result.value !== "object" || !("paths" in result.value) || !result.value.paths || typeof result.value.paths !== "object") throw new Error("Invalid service contract.");
163
+ const found = /* @__PURE__ */ new Map();
164
+ for (const [path, methods] of Object.entries(result.value.paths)) {
165
+ if (!methods || typeof methods !== "object") throw new Error("Invalid service route.");
166
+ let parameters;
167
+ try {
168
+ parameters = operationPathParameters(path);
169
+ } catch {
170
+ throw new Error("Invalid service route.");
171
+ }
172
+ for (const [method, operation] of Object.entries(methods)) {
173
+ if (![
174
+ "get",
175
+ "post",
176
+ "put",
177
+ "patch",
178
+ "delete"
179
+ ].includes(method)) continue;
180
+ if (!operation || typeof operation !== "object" || !("operationId" in operation) || typeof operation.operationId !== "string" || found.has(operation.operationId)) throw new Error("Invalid service operation.");
181
+ const metadata = operation;
182
+ const body = metadata["x-body"];
183
+ const responseKind = metadata["x-response"];
184
+ if (body !== void 0 && body !== "bytes" || responseKind !== void 0 && responseKind !== "attachment") throw new Error("Invalid operation body contract.");
185
+ const headers = metadata["x-input-headers"] ?? {};
186
+ if (!headers || typeof headers !== "object" || Array.isArray(headers) || Object.entries(headers).some(([field, header]) => !field || typeof header !== "string" || !isInputHeaderName(header))) throw new Error("Invalid operation header contract.");
187
+ found.set(operation.operationId, {
188
+ path,
189
+ method: method.toUpperCase(),
190
+ parameters,
191
+ headers,
192
+ ...body === "bytes" ? { body } : {},
193
+ ...responseKind === "attachment" ? { response: responseKind } : {}
194
+ });
195
+ }
196
+ }
197
+ return found;
198
+ }
199
+ /**
200
+ * Sends one request with the bearer, no credentials and no cache, after the hooks: they may add headers,
201
+ * never replace the bearer, the method, the body or the deadline.
202
+ */
203
+ async function send(url, init, upload, authenticated = true) {
204
+ const { signal } = init;
205
+ signal?.throwIfAborted();
206
+ const bearer = authenticated ? `Bearer ${typeof token === "string" ? token : await awaitWithSignal(token(), signal)}` : void 0;
207
+ signal?.throwIfAborted();
208
+ const request = new Request(url, {
209
+ ...init,
210
+ redirect: "manual",
211
+ credentials: options.credentials ?? "omit",
212
+ cache: options.cache ?? "no-store"
213
+ });
214
+ await awaitWithSignal(Promise.resolve(options.beforeRequest?.(request)), signal);
215
+ signal?.throwIfAborted();
216
+ for (const [header, value] of new Headers(init.headers)) request.headers.set(header, value);
217
+ if (bearer) request.headers.set("authorization", bearer);
218
+ else request.headers.delete("authorization");
219
+ notifyUploadTransfer(upload, 0);
220
+ const response = await awaitWithSignal(transport(url, {
221
+ ...init,
222
+ headers: [...request.headers].length ? Object.fromEntries(request.headers) : void 0,
223
+ redirect: "manual",
224
+ credentials: request.credentials,
225
+ cache: request.cache
226
+ }), signal);
227
+ await awaitWithSignal(Promise.resolve(options.afterResponse?.(response, request)), signal);
228
+ return response;
229
+ }
230
+ return new Proxy(Object.create(null), { get(_target, name) {
231
+ if (typeof name !== "string" || name === "then") return;
232
+ return async (input, callOptions) => {
233
+ const capturedSignal = options.signal?.();
234
+ const signals = [
235
+ AbortSignal.timeout(options.timeoutMs ?? 3e4),
236
+ capturedSignal,
237
+ callOptions?.signal
238
+ ].filter((signal) => signal !== void 0);
239
+ const signal = AbortSignal.any(signals);
240
+ signal.throwIfAborted();
241
+ routes ??= discover().catch((error) => {
242
+ routes = void 0;
243
+ throw error;
244
+ });
245
+ const route = (await awaitWithSignal(routes, signal)).get(name);
246
+ if (!route) throw new Error("Operation is not exposed over HTTP.");
247
+ const { path: declaredPath } = route;
248
+ let path = declaredPath;
249
+ for (const parameter of route.parameters) {
250
+ const value = input[parameter];
251
+ if (!isPathParameterValue(value)) throw new TypeError("Path values must be nonempty strings without slashes, dot segments or controls.");
252
+ path = path.replace(`{${parameter}}`, encodeURIComponent(value));
253
+ }
254
+ const pathNames = new Set(route.parameters);
255
+ const remaining = Object.fromEntries(Object.entries(input).filter(([field]) => !pathNames.has(field)));
256
+ const url = serviceUrl(path);
257
+ const metadataHeaders = new Headers();
258
+ const query = route.body === "bytes" ? Object.fromEntries(Object.entries(remaining).filter(([field]) => !Object.hasOwn(route.headers, field))) : remaining;
259
+ if (route.body === "bytes") for (const [key, value] of Object.entries(query)) {
260
+ if (value === void 0) continue;
261
+ if (typeof value !== "string") throw new TypeError("Query values must be strings.");
262
+ url.searchParams.set(key, value);
263
+ }
264
+ else if (route.method === "GET") for (const [key, value] of Object.entries(query)) {
265
+ if (value === void 0) continue;
266
+ const text = queryValue(value);
267
+ if (text === null) throw new TypeError("Query values must be strings, finite numbers, booleans or lists of nonempty strings without commas.");
268
+ url.searchParams.set(key, text);
269
+ }
270
+ for (const [field, header] of Object.entries(route.headers)) {
271
+ const value = remaining[field];
272
+ if (value === void 0) continue;
273
+ if (typeof value !== "string") throw new TypeError("Header values must be strings.");
274
+ metadataHeaders.set(header, value);
275
+ }
276
+ let body;
277
+ let upload;
278
+ if (route.body === "bytes") {
279
+ if (!callOptions || !("body" in callOptions) || !(callOptions.body instanceof Blob || callOptions.body instanceof Uint8Array)) throw new TypeError("A binary body is required.");
280
+ upload = callOptions;
281
+ ({body} = upload);
282
+ if (!metadataHeaders.has("content-type")) metadataHeaders.set("content-type", upload.body instanceof Blob && upload.body.type ? upload.body.type : "application/octet-stream");
283
+ } else if (route.method !== "GET") {
284
+ if (callOptions && "body" in callOptions) throw new TypeError("A JSON operation cannot accept a binary body.");
285
+ metadataHeaders.set("content-type", "application/json");
286
+ body = JSON.stringify(remaining);
287
+ }
288
+ const response = await send(url, {
289
+ method: route.method,
290
+ signal,
291
+ headers: metadataHeaders,
292
+ ...body === void 0 ? {} : { body }
293
+ }, upload);
294
+ if (route.response === "attachment" && response.ok) {
295
+ const attachment = boundedAttachment(response, maxAttachmentBytes);
296
+ notifyUploadTransfer(upload, 1);
297
+ return options.response === "data" ? attachment : {
298
+ success: true,
299
+ data: attachment,
300
+ error: null,
301
+ metadata: { requestId: response.headers.get("x-request-id") ?? "" }
302
+ };
303
+ }
304
+ const envelope = await readOperationEnvelope(response, {
305
+ signal,
306
+ maxBytes: maxResponseBytes,
307
+ dataMode: options.response === "data"
308
+ });
309
+ if (envelope.success) notifyUploadTransfer(upload, 1);
310
+ if (options.response !== "data") return envelope;
311
+ if (!envelope.success) {
312
+ const refusal = {
313
+ status: response.status,
314
+ failure: envelope.error,
315
+ requestId: envelope.metadata.requestId
316
+ };
317
+ throw options.onFailure?.(refusal) ?? new Error("The service refused the request.", { cause: refusal });
318
+ }
319
+ return envelope.data;
320
+ };
321
+ } });
322
+ }
323
+
324
+ //#endregion
325
+ export { createClient };
@@ -0,0 +1,41 @@
1
+ import { $t as telemetryEnabled, Bn as parseTraceParent, Fn as DurableCorrelation, In as TraceParent, Jt as Observer, Kt as BackgroundContext, Ln as createRequestId, Qt as reportUnexpected, Rn as durableCorrelation, Xt as diagnosticsEnabled, Yt as TelemetryConfig, Zt as recordExecution, en as withDiagnostics, qt as ExecutionObservation, zn as isRequestId } from "./chunks/types-CGwAhnTE.js";
2
+ //#region src/internal/diagnostics.d.ts
3
+ /**
4
+ * What diagnostics may say about an error: its name, its causes' names, its issue count and its stack
5
+ * locations.
6
+ */
7
+ interface ErrorDescription {
8
+ /**
9
+ * The error's name when it is a built-in or supplied domain name, else `UnknownError`; `NonError` when the
10
+ * thrown value is not an `Error`.
11
+ */
12
+ name: string;
13
+ /**
14
+ * The names of up to three errors in its `cause` chain, nearest first, each a known name or `UnknownError`;
15
+ * absent without a cause.
16
+ */
17
+ causes?: string[];
18
+ /**
19
+ * How many entries the error's `issues` array holds, or its direct cause's; absent when neither has one.
20
+ */
21
+ issueCount?: number;
22
+ /**
23
+ * Line and column numbers of up to eight stack frames, from the top, without file names; absent when the
24
+ * stack yields none.
25
+ */
26
+ locations?: {
27
+ line: number;
28
+ column: number;
29
+ }[];
30
+ }
31
+ /**
32
+ * Create a pure projection for SDK events and owner-written log lines. Names are
33
+ * developer constants, never values taken from an upstream response. Messages,
34
+ * record keys, URLs and query parameters are never returned. No logging occurs.
35
+ */
36
+ export declare function createDiagnostics(errorNames?: readonly string[]): {
37
+ safeErrorName: (error: unknown) => string;
38
+ describeError: (error: unknown) => ErrorDescription;
39
+ };
40
+ //#endregion
41
+ export { type BackgroundContext, type DurableCorrelation, type ErrorDescription, type ExecutionObservation, type Observer, type TelemetryConfig, type TraceParent, createRequestId, diagnosticsEnabled, durableCorrelation, isRequestId, parseTraceParent, recordExecution, reportUnexpected, telemetryEnabled, withDiagnostics };
@@ -0,0 +1,4 @@
1
+ import { i as parseTraceParent, n as durableCorrelation, r as isRequestId, t as createRequestId } from "./chunks/correlation-gaiEoMBr.js";
2
+ import { a as telemetryEnabled, c as createDiagnostics, i as reportUnexpected, o as withDiagnostics, r as recordExecution, t as diagnosticsEnabled } from "./chunks/telemetry-DvZgrzZn.js";
3
+
4
+ export { createDiagnostics, createRequestId, diagnosticsEnabled, durableCorrelation, isRequestId, parseTraceParent, recordExecution, reportUnexpected, telemetryEnabled, withDiagnostics };
@@ -0,0 +1,2 @@
1
+ import { An as FailureData, Dn as ErrorDefinition, En as ErrorCatalog, Mn as defineErrors, Nn as resultSchema, On as ErrorFactory, Pn as standardErrors, Tn as DefinedErrors, jn as FailureSchema, kn as Failure, zn as isRequestId } from "./chunks/types-CGwAhnTE.js";
2
+ export { DefinedErrors, ErrorCatalog, ErrorDefinition, ErrorFactory, Failure, FailureData, FailureSchema, defineErrors, isRequestId, resultSchema, standardErrors };
package/dist/errors.js ADDED
@@ -0,0 +1,128 @@
1
+ import { STANDARD_FAILURES } from "./standard-failures.js";
2
+ import { i as parseSchema } from "./chunks/validation-DWxKk1Js.js";
3
+ import { r as isRequestId } from "./chunks/correlation-gaiEoMBr.js";
4
+ import { Type } from "@sinclair/typebox";
5
+ import { Value } from "@sinclair/typebox/value";
6
+
7
+ //#region src/errors.ts
8
+ /**
9
+ * `@arbol-ai/maximus/errors`: error catalogs. `defineErrors` joins the standard failures and an
10
+ * application's own into one catalog whose factories build each failure and whose schema validates every
11
+ * failure an operation returns.
12
+ */
13
+ /**
14
+ * Every failure, whatever its code: the base each catalog's failures narrow. The OpenAPI document
15
+ * names it `Failure`, so every service's errors share one type.
16
+ */
17
+ const FailureSchema = Type.Object({
18
+ code: Type.String({ description: "The failure code, stable across releases." }),
19
+ message: Type.String({ description: "What went wrong, for people; it never contains input values." }),
20
+ retryable: Type.Boolean({ description: "Whether repeating the same request may succeed." }),
21
+ data: Type.Object({}, { description: "Diagnostics the code declares; empty for most codes." })
22
+ }, {
23
+ $id: "Failure",
24
+ additionalProperties: false
25
+ });
26
+ /** The first field issues of a refused input: where, and what was expected. Never a value. */
27
+ const InputIssuesSchema = Type.Object({ issues: Type.Optional(Type.Array(Type.Object({
28
+ path: Type.String({
29
+ maxLength: 256,
30
+ description: "RFC 6901 JSON Pointer to the refused field; empty for the whole input."
31
+ }),
32
+ message: Type.String({ maxLength: 256 })
33
+ }, {
34
+ $id: "ValidationIssue",
35
+ additionalProperties: false
36
+ }), { maxItems: 10 })) }, { additionalProperties: false });
37
+ /** The standard failures as a catalog defines them; INVALID_INPUT carries its field issues. */
38
+ const STANDARD = {
39
+ ...STANDARD_FAILURES,
40
+ invalidInput: {
41
+ ...STANDARD_FAILURES.invalidInput,
42
+ dataSchema: InputIssuesSchema
43
+ }
44
+ };
45
+ /** One failure's schema, its `create()` and its `is()`, from its definition. */
46
+ function factory(definition) {
47
+ const dataSchema = definition.dataSchema ?? Type.Object({}, { additionalProperties: false });
48
+ const schema = Type.Object({
49
+ code: Type.Literal(definition.code),
50
+ message: Type.Literal(definition.message),
51
+ retryable: Type.Literal(definition.retryable ?? false),
52
+ data: dataSchema
53
+ }, { additionalProperties: false });
54
+ return {
55
+ schema,
56
+ create(...args) {
57
+ const data = parseSchema(dataSchema, args.at(0) ?? {});
58
+ return {
59
+ code: definition.code,
60
+ message: definition.message,
61
+ retryable: definition.retryable ?? false,
62
+ data
63
+ };
64
+ },
65
+ is(value) {
66
+ return Value.Check(schema, value);
67
+ }
68
+ };
69
+ }
70
+ /** The catalog's own members, which no failure may be named after. */
71
+ const CATALOG_MEMBERS = {
72
+ schema: true,
73
+ definitions: true,
74
+ status: true,
75
+ retryAfter: true,
76
+ validate: true
77
+ };
78
+ /**
79
+ * An error catalog: the standard failures and the application's own, each with a fixed code, status, message
80
+ * and retry semantics. `catalog.name.create(data?)` builds a failure; the application validates every failure
81
+ * an operation returns against the catalog.
82
+ */
83
+ function defineErrors(domain) {
84
+ const own = domain;
85
+ if (Object.keys(own).some((name) => Object.hasOwn(STANDARD, name) || Object.hasOwn(CATALOG_MEMBERS, name))) throw new TypeError("Domain errors cannot replace framework errors or catalog members.");
86
+ const definitions = {
87
+ ...STANDARD,
88
+ ...own
89
+ };
90
+ const byCode = /* @__PURE__ */ new Map();
91
+ for (const definition of Object.values(definitions)) {
92
+ if (byCode.has(definition.code) || definition.status < 400 || definition.status > 599) throw new TypeError("Error definitions require unique codes and failure statuses.");
93
+ if ("dataSchema" in definition && definition.dataSchema && (definition.dataSchema.type !== "object" || definition.dataSchema.additionalProperties !== false)) throw new TypeError("Domain error data must be a strict object schema.");
94
+ byCode.set(definition.code, definition);
95
+ }
96
+ const factories = Object.fromEntries(Object.entries(definitions).map(([name, value]) => [name, factory(value)]));
97
+ const schema = Type.Union(Object.values(factories).map((value) => value.schema));
98
+ return Object.assign(factories, {
99
+ schema,
100
+ definitions,
101
+ status(code) {
102
+ return byCode.get(code)?.status ?? 500;
103
+ },
104
+ retryAfter(code) {
105
+ return byCode.get(code)?.retryAfter;
106
+ },
107
+ validate(error) {
108
+ return parseSchema(schema, error);
109
+ }
110
+ });
111
+ }
112
+ /**
113
+ * The catalog of the framework's own failures (`INVALID_INPUT`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, …).
114
+ */
115
+ const standardErrors = defineErrors({});
116
+ /** The schema of a Result: `{ ok: true, value } | { ok: false, error }`. */
117
+ function resultSchema(value, error) {
118
+ return Type.Union([Type.Object({
119
+ ok: Type.Literal(true),
120
+ value
121
+ }, { additionalProperties: false }), Type.Object({
122
+ ok: Type.Literal(false),
123
+ error
124
+ }, { additionalProperties: false })]);
125
+ }
126
+
127
+ //#endregion
128
+ export { FailureSchema, defineErrors, isRequestId, resultSchema, standardErrors };
@@ -0,0 +1,2 @@
1
+ import { C as operationPathParameters, S as isPathParameterValue, _ as HttpRouteDefinition, b as decodePathParameter, v as HttpRouteMatch, x as isInputHeaderName, y as createHttpRouteResolver } from "./chunks/types-CGwAhnTE.js";
2
+ export { HttpRouteDefinition, HttpRouteMatch, createHttpRouteResolver, decodePathParameter, isInputHeaderName, isPathParameterValue, operationPathParameters };