@arbol-ai/maximus 8.0.1 → 8.4.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 (70) hide show
  1. package/dist/analytics/analytics.d.ts +16 -16
  2. package/dist/analytics/analytics.js +4 -4
  3. package/dist/body.d.ts +2 -2
  4. package/dist/body.js +2 -2
  5. package/dist/capture/index.d.ts +37 -0
  6. package/dist/capture/index.js +181 -0
  7. package/dist/chunks/{define-app-x7uY70_1.js → define-app-CQpWqqqE.js} +44 -14
  8. package/dist/chunks/delay-BsKQP_lF.js +12 -0
  9. package/dist/chunks/{json-B14evE6-.js → destination-DIkn8W6K.js} +65 -1
  10. package/dist/chunks/digest-C51F1bhA.js +12 -0
  11. package/dist/chunks/{errors-C5w9WY1l.js → errors-BoutSmiy.js} +2 -3
  12. package/dist/chunks/execution-Bpq6s4nA.js +265 -0
  13. package/dist/chunks/{generate-C-9FKW0o.js → generate-Dg88LzLU.js} +1 -1
  14. package/dist/chunks/{handler-iebR-urt.js → handler-DSpyrWc-.js} +6 -2
  15. package/dist/chunks/{http-layout-DS8DnPyu.js → http-layout-BcYH4I2w.js} +1 -1
  16. package/dist/chunks/{http-paths-DMBxwpp6.js → http-paths-D043DkJv.js} +50 -81
  17. package/dist/chunks/http-routes-B6tCsnxB.js +29 -0
  18. package/dist/chunks/{openapi-CeolxIqa.js → openapi-D2rds7vy.js} +32 -130
  19. package/dist/chunks/{openapi-file-Bz9FRaE6.js → openapi-file-BK8zET5U.js} +24 -6
  20. package/dist/chunks/{pages-iZTvFs5a.js → pages-B7ysoFAM.js} +1 -1
  21. package/dist/chunks/result-CF4OzG9O.js +29 -0
  22. package/dist/chunks/{runtime-D94vx21X.js → runtime-CGtS2rOb.js} +165 -11
  23. package/dist/chunks/schemas-_UJcx_uY.js +813 -0
  24. package/dist/chunks/{server-Bzf1Q1_4.js → server-CVhTLNj2.js} +38 -101
  25. package/dist/chunks/{src-CPrJpbOM.js → src-D67OfW9B.js} +94 -27
  26. package/dist/chunks/tasks-C873C3le.js +100 -0
  27. package/dist/chunks/tasks-DYdY-dBI.js +267 -0
  28. package/dist/chunks/{telemetry-C3LfZcOB.js → telemetry-BtxJh69Q.js} +4 -4
  29. package/dist/chunks/{types-DTIuIEJ-.d.ts → types-BfGa2aJT.d.ts} +537 -124
  30. package/dist/chunks/validation-CpzAxj2_.js +201 -0
  31. package/dist/chunks/{workers-types-BRk_Xa_5.d.ts → workers-types-Cxf-5cH7.d.ts} +6 -1
  32. package/dist/diagnostics.d.ts +1 -1
  33. package/dist/diagnostics.js +1 -1
  34. package/dist/errors.d.ts +1 -1
  35. package/dist/errors.js +1 -1
  36. package/dist/http-paths.d.ts +1 -1
  37. package/dist/http-paths.js +1 -1
  38. package/dist/index.d.ts +2 -2
  39. package/dist/index.js +12 -11
  40. package/dist/internals.d.ts +2 -2
  41. package/dist/internals.js +6 -6
  42. package/dist/mcp/index.d.ts +1 -1
  43. package/dist/mcp/index.js +1 -1
  44. package/dist/mcp/tasks.d.ts +33 -0
  45. package/dist/mcp/tasks.js +3 -0
  46. package/dist/project/config.d.ts +2 -2
  47. package/dist/project/config.js +3 -2
  48. package/dist/project/index.d.ts +2 -2
  49. package/dist/project/index.js +3 -3
  50. package/dist/schemas.d.ts +2 -2
  51. package/dist/schemas.js +3 -3
  52. package/dist/standard-failures.d.ts +1 -1
  53. package/dist/tooling/cli.js +2 -2
  54. package/dist/vite/index.d.ts +2 -2
  55. package/dist/vite/index.js +15 -9
  56. package/dist/webhooks.d.ts +13 -2
  57. package/dist/webhooks.js +38 -1
  58. package/dist/workers/runtime.d.ts +1 -1
  59. package/dist/workers/runtime.js +1 -1
  60. package/package.json +15 -3
  61. package/skills/maximus/SKILL.md +14 -4
  62. package/skills/maximus/references/project.md +4 -0
  63. package/skills/maximus/references/routes-and-tools.md +11 -1
  64. package/templates/project/CLAUDE.md.template +3 -3
  65. package/templates/project/README.md.template +1 -0
  66. package/templates/project/tsconfig.json.template +1 -0
  67. package/dist/chunks/execution-rOiLo8VG.js +0 -84
  68. package/dist/chunks/result-CKgZHrnj.js +0 -56
  69. package/dist/chunks/schemas-p_aRcMC1.js +0 -227
  70. package/dist/chunks/validation-fTohBT6R.js +0 -420
@@ -0,0 +1,265 @@
1
+ import { f as Value, t as admitInput } from "./validation-CpzAxj2_.js";
2
+ import { B as withoutSecrets, R as holdsSecrets } from "./schemas-_UJcx_uY.js";
3
+ import { i as standardErrors } from "./errors-BoutSmiy.js";
4
+ import { a as isAttachmentSchema, o as validAttachment } from "./define-app-CQpWqqqE.js";
5
+ import { b as operationScopes, c as ADMISSION_CODES, f as STANDARD_CODES, l as BODY_CODES, v as operationMatchesScopes, y as operationOutputLimit } from "./tasks-DYdY-dBI.js";
6
+ import { t as err } from "./result-CF4OzG9O.js";
7
+ import { t as sha256Hex } from "./digest-C51F1bhA.js";
8
+ import { t as delay } from "./delay-BsKQP_lF.js";
9
+ import { o as reportUnexpected, r as elapsedMicros, s as telemetryEnabled, t as activeTraceId } from "./telemetry-BtxJh69Q.js";
10
+
11
+ // src/capture.ts
12
+ /** The most entries a `dimensions` callback's answer keeps. */
13
+ const MAX_DIMENSIONS = 32;
14
+ /** The longest value of one entry a `dimensions` callback's answer keeps. */
15
+ const MAX_DIMENSION_LENGTH = 256;
16
+ /** Writes one line of capture's own diagnostics; they are best effort. */
17
+ function logCapture(line) {
18
+ try {
19
+ console.error(JSON.stringify(line));
20
+ } catch {}
21
+ }
22
+ /** Whether capture is on for this env: a switch that throws turns it off and says so. */
23
+ function captureEnabled(capture, env) {
24
+ if (typeof capture.enabled !== "function") return capture.enabled !== false;
25
+ try {
26
+ return capture.enabled(env);
27
+ } catch {
28
+ logCapture({ event: "maximus.capture.switch_failed" });
29
+ return false;
30
+ }
31
+ }
32
+ /** A UUIDv7 at this instant: its leading bits are the time, so ids sort by when their records happened. */
33
+ function timeOrderedId(instant) {
34
+ const time = instant.toString(16).padStart(12, "0");
35
+ const random = crypto.randomUUID().replaceAll("-", "");
36
+ return `${time.slice(0, 8)}-${time.slice(8)}-7${random.slice(13, 16)}-${random.slice(16, 20)}-${random.slice(20)}`;
37
+ }
38
+ /**
39
+ * The input a record carries. An input whose schema marks nothing is the decoded one, as plain JSON. One whose
40
+ * schema marks a field is what the schema checked, without that field: a codec may move a value to where no
41
+ * mark reaches, so only the checked value is known to have the shape the marks describe. Decoded values a
42
+ * record cannot carry, such as a `BigInt`, fall back to the checked one, which is plain JSON by admission. Read
43
+ * after the call: a handler that changes its input in place changes the record, and in a strict object nothing
44
+ * it adds to a marked schema's input can reach it.
45
+ */
46
+ function recordedInput(schema, admitted) {
47
+ if (!admitted) return null;
48
+ if (holdsSecrets(schema)) return withoutSecrets(schema, admitted.checked) ?? null;
49
+ if (admitted.decoded === admitted.checked) return admitted.checked;
50
+ try {
51
+ return JSON.parse(JSON.stringify(admitted.decoded));
52
+ } catch {
53
+ return admitted.checked;
54
+ }
55
+ }
56
+ /** The output a record carries: never an attachment's bytes, and never what its schema marks. */
57
+ function recordedOutput(schema, value) {
58
+ if (isAttachmentSchema(schema)) {
59
+ const { contentType, filename, byteLength } = value;
60
+ return {
61
+ contentType,
62
+ filename,
63
+ byteLength
64
+ };
65
+ }
66
+ return holdsSecrets(schema) ? withoutSecrets(schema, value) ?? null : value;
67
+ }
68
+ /** The failure's data a record carries, without what its code's schema marks. */
69
+ function recordedFailureData(errors, failure) {
70
+ const schema = Object.values(errors.definitions).find(({ code }) => code === failure.code)?.dataSchema;
71
+ return schema && holdsSecrets(schema) ? withoutSecrets(schema, failure.data) ?? null : failure.data ?? null;
72
+ }
73
+ /** What the `dimensions` callback names for this call: bounded identifiers, or nothing when it throws. */
74
+ function recordedDimensions(application, env, captured) {
75
+ const dimensions = application.capture?.dimensions;
76
+ if (!dimensions) return {};
77
+ try {
78
+ const { operation, surface, principal, verified, call } = captured;
79
+ const named = dimensions({
80
+ env,
81
+ operation,
82
+ surface,
83
+ principal,
84
+ ...verified?.client ? { authority: {
85
+ surface,
86
+ scopes: verified.scopes,
87
+ client: verified.client
88
+ } } : {},
89
+ ...call?.rpcCaller ? { rpcCaller: call.rpcCaller } : {},
90
+ ...call?.userAgent ? { userAgent: call.userAgent } : {},
91
+ context: call?.context ?? {},
92
+ ...call?.admitted ? { input: call.admitted.decoded } : {}
93
+ });
94
+ return Object.fromEntries(Object.entries(named).filter((entry) => typeof entry[1] === "string" && entry[1] !== "").slice(0, MAX_DIMENSIONS).map(([name, value]) => [name, value.slice(0, MAX_DIMENSION_LENGTH)]));
95
+ } catch {
96
+ logCapture({
97
+ event: "maximus.capture.dimensions_failed",
98
+ requestId: captured.requestId
99
+ });
100
+ return {};
101
+ }
102
+ }
103
+ /** The record of one call, as background work. */
104
+ async function buildRecord(application, capture, env, captured, moment) {
105
+ const { operation, surface, principal, verified, result, call } = captured;
106
+ const declared = operation !== null && Object.hasOwn(application.operations, operation) ? application.operations[operation] : void 0;
107
+ const http = surface === "http" ? declared?.http : void 0;
108
+ const payloads = capture.payloads === "all";
109
+ return {
110
+ id: timeOrderedId(moment.occurredAt),
111
+ service: application.name,
112
+ operation,
113
+ organizationId: principal?.organizationId ?? null,
114
+ actorId: principal?.actorId ?? null,
115
+ actorKind: principal?.actorKind ?? null,
116
+ requestId: captured.requestId,
117
+ traceId: moment.traceId,
118
+ surface,
119
+ occurredAt: moment.occurredAt,
120
+ durationMicros: moment.durationMicros,
121
+ outcome: result.ok ? "success" : "failure",
122
+ errorCode: result.ok ? null : result.error.code,
123
+ stage: captured.executionStarted === void 0 ? "admission" : "execution",
124
+ version: application.version,
125
+ effect: declared?.effect ?? null,
126
+ scopes: declared ? [...operationScopes(declared)] : [],
127
+ visibility: declared ? declared.visibility ?? "public" : null,
128
+ httpMethod: http?.method ?? null,
129
+ httpPath: http?.path ?? null,
130
+ mcpTool: surface === "mcp" ? declared?.mcp?.name ?? null : null,
131
+ rpcCaller: call?.rpcCaller ?? null,
132
+ clientId: verified?.client?.id ?? null,
133
+ clientClass: verified?.client?.class ?? null,
134
+ grantedScopes: verified ? [...verified.scopes] : null,
135
+ userAgent: call?.userAgent ?? null,
136
+ tokenSha256: verified?.token ? await sha256Hex(verified.token) : null,
137
+ dimensions: recordedDimensions(application, env, captured),
138
+ startedAt: moment.startedAt,
139
+ admissionMicros: moment.admissionMicros,
140
+ input: payloads && declared ? recordedInput(declared.input, call?.admitted) : null,
141
+ output: payloads && declared && result.ok ? recordedOutput(declared.output, result.value) : null,
142
+ failureData: payloads && !result.ok ? recordedFailureData(application.errors, result.error) : null,
143
+ payloadRef: null
144
+ };
145
+ }
146
+ /**
147
+ * Captures one call beside `recordExecution` or `recordAdmission`, as background work: it never throws, never
148
+ * delays or changes the response and never affects an observer. A failed delivery logs
149
+ * `maximus.capture.delivery_failed` with the request id alone. Nothing is recorded without a background context,
150
+ * or while capture is off, whether telemetry is on or not.
151
+ */
152
+ function recordCapture(application, env, background, captured) {
153
+ const { capture } = application;
154
+ if (!(capture && background)) return;
155
+ try {
156
+ if (!captureEnabled(capture, env) || capture.sink.available?.(env) === false) return;
157
+ const occurredAt = Date.now();
158
+ const admissionMicros = elapsedMicros(captured.requestStarted, captured.executionStarted);
159
+ const executionMicros = captured.executionStarted === void 0 ? 0 : elapsedMicros(captured.executionStarted);
160
+ const moment = {
161
+ occurredAt,
162
+ startedAt: Math.max(0, Math.round(occurredAt - (admissionMicros + executionMicros) / 1e3)),
163
+ durationMicros: captured.executionStarted === void 0 ? admissionMicros : executionMicros,
164
+ admissionMicros,
165
+ traceId: activeTraceId(application.telemetry)
166
+ };
167
+ background.waitUntil(delay(0).then(() => buildRecord(application, capture, env, captured, moment)).then((record) => capture.sink.send(record, env)).catch(() => {
168
+ logCapture({
169
+ event: "maximus.capture.delivery_failed",
170
+ requestId: captured.requestId
171
+ });
172
+ }));
173
+ } catch {
174
+ logCapture({
175
+ event: "maximus.capture.delivery_failed",
176
+ requestId: captured.requestId
177
+ });
178
+ }
179
+ }
180
+
181
+ // src/execution.ts
182
+ /**
183
+ * The one execution path every transport calls: the caller's eligibility, input decoding, context
184
+ * preparation, middleware, the handler, and the checks on what it returns.
185
+ */
186
+ /**
187
+ * The execution path every transport shares: checks that the caller may run the operation (its scopes when
188
+ * `authority` is given, its actor kind, and `authority` itself when the operation has conditional scopes),
189
+ * decodes the input, prepares the context, runs the middleware and the handler, then checks the result
190
+ * against the catalog, the declared failures, the output schema and the output limit. A refused caller
191
+ * answers `FORBIDDEN` and a refused input `INVALID_INPUT`. An unexpected error becomes `INTERNAL_ERROR`,
192
+ * reported while telemetry is on, and is never thrown. `call` hands the admitted input and the prepared context
193
+ * to the recording points, which only the Result would otherwise reach.
194
+ */
195
+ async function executeOperation(manifest, operation, env, principal, input, authority, background, body, call) {
196
+ if (operation.conditionalScopes?.length && !authority || authority && !operationMatchesScopes(operation, authority.scopes) || operation.actorKinds && !operation.actorKinds.includes(principal.actorKind)) return err(standardErrors.forbidden.create());
197
+ try {
198
+ const admitted = admitInput(operation.input, input);
199
+ if (!admitted.ok) return err(standardErrors.invalidInput.create(admitted.error.data));
200
+ if (call) call.admitted = {
201
+ checked: admitted.checked,
202
+ decoded: admitted.value
203
+ };
204
+ const trustedAuthority = authority ? Object.freeze({
205
+ surface: authority.surface,
206
+ scopes: Object.freeze([...authority.scopes]),
207
+ client: Object.freeze({ ...authority.client }),
208
+ ...authority.token ? { token: authority.token } : {}
209
+ }) : void 0;
210
+ const invocation = {
211
+ env,
212
+ principal,
213
+ input: admitted.value,
214
+ ...body ? { body } : {},
215
+ ...background ? { background } : {},
216
+ ...trustedAuthority ? { authority: trustedAuthority } : {},
217
+ ...call?.rpcCaller ? { rpcCaller: call.rpcCaller } : {},
218
+ ...call?.userAgent ? { userAgent: call.userAgent } : {},
219
+ ...call?.taskId ? { taskId: call.taskId } : {}
220
+ };
221
+ /**
222
+ * A failure the call answers, from its context, middleware or handler: one of the catalog and, when the
223
+ * operation declares its failures, a declared or standard one. A failure only admission answers, or a
224
+ * body's for an operation that reads no byte body, is never the operation's. Any other is the server's
225
+ * error.
226
+ */
227
+ const declared = (answered) => {
228
+ const failure = manifest.errors.validate(answered);
229
+ if (ADMISSION_CODES.has(failure.code) || BODY_CODES.has(failure.code) && operation.http?.body !== "bytes") throw new TypeError(`Failure ${failure.code} is answered before an operation runs, never by it`);
230
+ if (operation.failures && !STANDARD_CODES.has(failure.code) && !operation.failures.includes(failure.code)) throw new TypeError(`Undeclared failure ${failure.code}`);
231
+ return failure;
232
+ };
233
+ const context = operation.pipeline ? await operation.pipeline.context(invocation) : await manifest.context(invocation);
234
+ if (!context.ok) return err(declared(context.error));
235
+ if (call) call.context = context.value;
236
+ const chain = operation.pipeline?.middleware ?? manifest.middleware ?? [];
237
+ let latest = -1;
238
+ /**
239
+ * Runs the middleware at `index`, whose `next` runs the following one, until the handler; each `next`
240
+ * runs once.
241
+ */
242
+ const dispatch = async (index) => {
243
+ if (index <= latest) throw new Error("Middleware next() may be called only once.");
244
+ latest = index;
245
+ const middleware = chain[index];
246
+ return await (middleware ? middleware(context.value, () => dispatch(index + 1)) : operation.execute(context.value, admitted.value));
247
+ };
248
+ const result = await dispatch(0);
249
+ if (!result || typeof result.ok !== "boolean" || !Object.hasOwn(result, "ok") || Object.keys(result).length !== 2 || !Object.hasOwn(result, result.ok ? "value" : "error")) throw new TypeError("Invalid operation result");
250
+ if (!result.ok) return err(declared(result.error));
251
+ const maxOutputBytes = operationOutputLimit(manifest, operation);
252
+ if (isAttachmentSchema(operation.output)) {
253
+ if (!validAttachment(result.value, maxOutputBytes)) throw new TypeError("Invalid attachment output");
254
+ return result;
255
+ }
256
+ if (!Value.Check(operation.output, result.value)) throw new TypeError("Invalid operation output");
257
+ if (new TextEncoder().encode(JSON.stringify(result.value)).byteLength > maxOutputBytes) throw new TypeError("Operation output exceeds its limit");
258
+ return result;
259
+ } catch (error) {
260
+ if (telemetryEnabled(manifest.telemetry, env)) reportUnexpected(error, "operation", principal.requestId);
261
+ return err(standardErrors.internal.create());
262
+ }
263
+ }
264
+
265
+ export { recordCapture as n, executeOperation as t };
@@ -1,4 +1,4 @@
1
- import { a as operationPathParameters } from "./http-paths-DMBxwpp6.js";
1
+ import { a as operationPathParameters } from "./http-paths-D043DkJv.js";
2
2
  import { a as projectPath, i as projectFiles, n as checkProjectFolder, s as routeShape } from "./project-files-C0OX7MQQ.js";
3
3
  import { existsSync, lstatSync, mkdirSync, writeFileSync } from "node:fs";
4
4
  import { dirname, join, relative, resolve } from "node:path";
@@ -1,4 +1,4 @@
1
- import { KindGuard, Type } from "@sinclair/typebox";
1
+ import { Type } from "typebox";
2
2
 
3
3
  // src/handler.ts
4
4
  /**
@@ -24,10 +24,14 @@ var Failed = class Failed {
24
24
  return value instanceof Failed;
25
25
  }
26
26
  };
27
+ /** Whether a value is a TypeBox type rather than a record of fields. */
28
+ function isTypeBoxType(value) {
29
+ return "~kind" in value || "~unsafe" in value;
30
+ }
27
31
  /** The schema `input` or `output` stands for, as `SchemaOf` types it: no fields is an empty strict object. */
28
32
  function schemaOf(value) {
29
33
  if (value === void 0) return Type.Object({}, { additionalProperties: false });
30
- return KindGuard.IsSchema(value) ? value : Type.Object(value, { additionalProperties: false });
34
+ return isTypeBoxType(value) ? value : Type.Object(value, { additionalProperties: false });
31
35
  }
32
36
  /** Every declaration `defineHandler` returned, so binding refuses any other value. */
33
37
  const handlers = /* @__PURE__ */ new WeakSet();
@@ -1,4 +1,4 @@
1
- import { l as usesOwnBearer, v as usesCloudflareAccess } from "./openapi-CeolxIqa.js";
1
+ import { u as usesOwnBearer, v as usesCloudflareAccess } from "./openapi-D2rds7vy.js";
2
2
 
3
3
  // src/internal/http-layout.ts
4
4
  /**
@@ -1,7 +1,9 @@
1
+ import { addRoute, createRouter, findRoute, routesOverlap } from "rou3";
2
+
1
3
  // src/http-paths.ts
2
4
  /**
3
5
  * `@arbol-ai/maximus/http-paths`: versioned route templates, path parameter decoding, and the router that
4
- * matches a request to exactly one operation.
6
+ * matches a request to exactly one operation, on rou3's route tree.
5
7
  */
6
8
  /** A fixed path segment of a route template. */
7
9
  const STATIC_SEGMENT = /^[a-zA-Z0-9_-]+$/;
@@ -80,30 +82,35 @@ function routeName(route) {
80
82
  return `${route.definition.http?.method} ${route.definition.http?.path}`;
81
83
  }
82
84
  /**
85
+ * Two templates of one method that match a common path, in the order a refusal names them: from the last
86
+ * segment where one is fixed and the other a parameter, the fixed one first.
87
+ */
88
+ function overlapping(left, right) {
89
+ if (left.segments.length !== right.segments.length || !routesOverlap(left.pattern, right.pattern)) return;
90
+ for (let index = left.segments.length - 1; index >= 0; index -= 1) {
91
+ const leftFixed = !left.segments[index]?.startsWith("{");
92
+ if (leftFixed !== !right.segments[index]?.startsWith("{")) return leftFixed ? [left, right] : [right, left];
93
+ }
94
+ return [left, right];
95
+ }
96
+ /**
83
97
  * The router for a set of definitions: `match(method, path)` finds the one route a request reaches, with its
84
98
  * decoded parameters, and `ownsPath(path)` says whether any route answers a path. A definition without `http`
85
99
  * is skipped. Construction throws a TypeError for an unsupported method, a malformed template, a duplicate
86
- * route, or two templates that could match the same path. A fixed route is one map lookup; templates compile
87
- * into states with one transition per segment, so matching never scans the routes.
100
+ * route, or two templates that could match the same path; a fixed route may share its path with a template,
101
+ * and wins it. Matching is rou3's route tree, fixed segments before parameters.
88
102
  */
89
103
  function createHttpRouteResolver(definitions) {
90
- const exact = /* @__PURE__ */ new Map();
91
- const roots = /* @__PURE__ */ new Map();
92
- let nextId = 0;
93
- /** A new tree node with the next id. */
94
- const branch = () => {
95
- const node = {
96
- id: nextId,
97
- fixed: /* @__PURE__ */ new Map()
98
- };
99
- nextId += 1;
100
- return node;
101
- };
104
+ const router = createRouter();
105
+ const fixed = /* @__PURE__ */ new Set();
106
+ const shapes = /* @__PURE__ */ new Map();
107
+ const templates = /* @__PURE__ */ new Map();
102
108
  for (const definition of definitions) {
103
109
  if (!definition.http) continue;
104
- if (!HTTP_METHODS.has(definition.http.method)) throw new TypeError(`Operation routes require a supported HTTP method: ${definition.http.method} ${definition.http.path}`);
105
- const names = operationPathParameters(definition.http.path);
106
- const segments = definition.http.path.slice(1).split("/");
110
+ const { method, path } = definition.http;
111
+ if (!HTTP_METHODS.has(method)) throw new TypeError(`Operation routes require a supported HTTP method: ${method} ${path}`);
112
+ const names = operationPathParameters(path);
113
+ const segments = path.slice(1).split("/");
107
114
  const route = {
108
115
  definition,
109
116
  parameters: segments.flatMap((segment, position) => {
@@ -115,73 +122,35 @@ function createHttpRouteResolver(definitions) {
115
122
  })
116
123
  };
117
124
  if (names.length === 0) {
118
- const key = `${definition.http.method} ${definition.http.path}`;
119
- if (exact.has(key)) throw new TypeError(`Duplicate operation route: ${key}`);
120
- exact.set(key, route);
125
+ const key = `${method} ${path}`;
126
+ if (fixed.has(key)) throw new TypeError(`Duplicate operation route: ${key}`);
127
+ fixed.add(key);
128
+ addRoute(router, method, path, route);
121
129
  continue;
122
130
  }
123
- let node = roots.get(definition.http.method);
124
- if (!node) {
125
- node = branch();
126
- roots.set(definition.http.method, node);
127
- }
128
- for (const segment of segments) if (segment.startsWith("{")) {
129
- node.parameter ??= branch();
130
- node = node.parameter;
131
- } else {
132
- let child = node.fixed.get(segment);
133
- if (!child) {
134
- child = branch();
135
- node.fixed.set(segment, child);
136
- }
137
- node = child;
138
- }
139
- if (node.route) throw new TypeError(`Ambiguous operation path templates: ${routeName(node.route)} and ${routeName(route)}`);
140
- node.route = route;
141
- }
142
- const states = /* @__PURE__ */ new Map();
143
- /**
144
- * The state for a set of tree nodes: their routes (at most one), and for each next segment the state of
145
- * every node it can lead to, compiled once per set.
146
- */
147
- function compile(nodes) {
148
- const distinct = [...new Map(nodes.map((node) => [node.id, node])).values()];
149
- const key = distinct.map((node) => node.id).toSorted((left, right) => left - right).join(",");
150
- const known = states.get(key);
151
- if (known) return known;
152
- const routes = distinct.flatMap((node) => node.route ? [node.route] : []);
153
- if (routes.length > 1) throw new TypeError(`Ambiguous overlapping operation path templates: ${routes.map(routeName).join(" and ")}`);
154
- const state = {
155
- fixed: /* @__PURE__ */ new Map(),
156
- route: routes[0]
131
+ const shape = `${method} ${path.replaceAll(/\{\w+\}/g, "{}")}`;
132
+ const same = shapes.get(shape);
133
+ if (same) throw new TypeError(`Ambiguous operation path templates: ${routeName(same)} and ${routeName(route)}`);
134
+ shapes.set(shape, route);
135
+ const template = {
136
+ route,
137
+ segments,
138
+ pattern: path.replaceAll(/\{(\w+)\}/g, ":$1")
157
139
  };
158
- states.set(key, state);
159
- const parameters = distinct.flatMap((node) => node.parameter ? [node.parameter] : []);
160
- if (parameters.length > 0) state.parameter = compile(parameters);
161
- const fixed = new Set(distinct.flatMap((node) => [...node.fixed.keys()]));
162
- for (const segment of fixed) {
163
- const children = distinct.flatMap((node) => {
164
- const child = node.fixed.get(segment);
165
- return child ? [child] : [];
166
- });
167
- state.fixed.set(segment, compile([...children, ...parameters]));
168
- }
169
- return state;
140
+ templates.set(method, [...templates.get(method) ?? [], template]);
141
+ addRoute(router, method, template.pattern, route);
142
+ }
143
+ for (const declared of templates.values()) for (const [index, template] of declared.entries()) for (const other of declared.slice(0, index)) {
144
+ const pair = overlapping(other, template);
145
+ if (pair) throw new TypeError(`Ambiguous overlapping operation path templates: ${routeName(pair[0].route)} and ${routeName(pair[1].route)}`);
170
146
  }
171
- const templates = new Map([...roots].map(([method, root]) => [method, compile([root])]));
172
147
  /**
173
- * The route for a method and the path's segments: an exact route first, then one transition per segment
174
- * through the compiled states.
148
+ * The route for a method and the path's segments. An empty segment matches none, where rou3 would ignore a
149
+ * trailing slash.
175
150
  */
176
- function findRoute(method, segments) {
177
- const fixed = exact.get(`${method} /${segments.join("/")}`);
178
- if (fixed) return fixed;
179
- let state = templates.get(method);
180
- for (const segment of segments) {
181
- if (!segment || !state) return null;
182
- state = state.fixed.get(segment) ?? state.parameter;
183
- }
184
- return state?.route ?? null;
151
+ function routeOf(method, segments) {
152
+ if (segments.some((segment) => !segment)) return null;
153
+ return findRoute(router, method, `/${segments.join("/")}`, { params: false })?.data ?? null;
185
154
  }
186
155
  /**
187
156
  * The route a request reaches, with its path parameters: every segment is decoded before it is matched, so
@@ -196,7 +165,7 @@ function createHttpRouteResolver(definitions) {
196
165
  if (decoded === null) return null;
197
166
  segments.push(decoded);
198
167
  }
199
- const route = findRoute(method, segments);
168
+ const route = routeOf(method, segments);
200
169
  if (!route) return null;
201
170
  const parameters = {};
202
171
  for (const parameter of route.parameters) parameters[parameter.name] = segments[parameter.position] ?? "";
@@ -210,7 +179,7 @@ function createHttpRouteResolver(definitions) {
210
179
  /** Whether any route answers a declared path, so a transport cannot claim an operation's path. */
211
180
  ownsPath(path) {
212
181
  const segments = path.slice(1).split("/");
213
- return [...HTTP_METHODS].some((method) => findRoute(method, segments) !== null);
182
+ return [...HTTP_METHODS].some((method) => routeOf(method, segments) !== null);
214
183
  }
215
184
  };
216
185
  }
@@ -0,0 +1,29 @@
1
+ // src/internal/http-routes.ts
2
+ /**
3
+ * The parameter's schema in an object input, or in each member of a union. Every one must declare the
4
+ * parameter as a required string field, or this throws a TypeError.
5
+ */
6
+ function pathParameterSchemas(input, parameter) {
7
+ const node = input;
8
+ if (node.type === "object") {
9
+ const schema = node.properties?.[parameter];
10
+ if (!schema || schema.type !== "string" || !node.required?.includes(parameter)) throw new TypeError(`Path parameter "${parameter}" must be a required string input field.`);
11
+ return [schema];
12
+ }
13
+ if (Array.isArray(node.anyOf) && node.anyOf.length > 0) return node.anyOf.flatMap((schema) => pathParameterSchemas(schema, parameter));
14
+ throw new TypeError("Path parameters require object input contracts.");
15
+ }
16
+ /**
17
+ * The group a route's path names, which OpenAPI publishes as its tag: its first fixed segment after the
18
+ * version, in words, such as `Notes` for `/v1/notes/{noteId}` and `Task lists` for `/v1/task-lists`;
19
+ * undefined when only parameters follow the version.
20
+ */
21
+ function routeGroup(path) {
22
+ const segments = path.split("/").filter(Boolean);
23
+ const segment = (/^v[1-9][0-9]*$/.test(segments[0] ?? "") ? segments.slice(1) : segments).find((part) => !part.startsWith("{"));
24
+ if (segment === void 0) return;
25
+ const words = segment.replaceAll(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[\s_-]+/).filter(Boolean).join(" ").toLowerCase();
26
+ return words.charAt(0).toUpperCase() + words.slice(1);
27
+ }
28
+
29
+ export { routeGroup as n, pathParameterSchemas as t };