@arbol-ai/maximus 7.4.0 → 8.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 (135) hide show
  1. package/README.md +36 -38
  2. package/bin/maximus.js +4 -0
  3. package/config/oxfmt.mjs +1 -0
  4. package/config/oxlint.mjs +10 -0
  5. package/dist/analytics/analytics.d.ts +21 -9
  6. package/dist/analytics/analytics.js +19 -5
  7. package/dist/body.d.ts +1 -1
  8. package/dist/body.js +2 -2
  9. package/dist/chunks/agent-skills-Ef65jTf_.js +49 -0
  10. package/dist/chunks/agent-skills-m7y1EUch.js +3 -0
  11. package/dist/chunks/{body-6LichrQm.js → body-DOIHwIIl.js} +14 -7
  12. package/dist/chunks/{correlation-BEkcFFGT.js → correlation-4b23a-a4.js} +8 -5
  13. package/dist/chunks/define-app-CfVZBt7D.js +336 -0
  14. package/dist/chunks/{errors-D7zG9kx9.js → errors-WfyKhiyk.js} +9 -4
  15. package/dist/chunks/{execution-kVUJPy1A.js → execution-CfZEx_JP.js} +28 -15
  16. package/dist/chunks/generate-C-9FKW0o.js +197 -0
  17. package/dist/chunks/handler-DWTGoduQ.js +140 -0
  18. package/dist/chunks/http-layout-_h7xwgPC.js +128 -0
  19. package/dist/chunks/{http-paths-yKD6TSNJ.js → http-paths-DMBxwpp6.js} +50 -31
  20. package/dist/chunks/{json-Bu4BLT25.js → json-B14evE6-.js} +21 -5
  21. package/dist/chunks/names-ncD7A3DV.js +280 -0
  22. package/dist/chunks/openapi-CV0KmJpS.js +1588 -0
  23. package/dist/chunks/openapi-file-OjSs9mRv.js +83 -0
  24. package/dist/chunks/pages-DyC0m8Zb.js +14 -0
  25. package/dist/chunks/prepare-configured-BmRJLg6J.js +3 -0
  26. package/dist/chunks/prepare-configured-Cithjf80.js +52 -0
  27. package/dist/chunks/project-files-C0OX7MQQ.js +130 -0
  28. package/dist/chunks/query-kind-CWKAXEME.js +40 -0
  29. package/dist/chunks/record-DQUDTpEA.js +10 -0
  30. package/dist/chunks/result-CKgZHrnj.js +56 -0
  31. package/dist/chunks/{runtime-DlqA7J38.js → runtime-CVVf5hmp.js} +50 -26
  32. package/dist/chunks/scaffold-DGrcjR3h.js +3 -0
  33. package/dist/chunks/scaffold-DZD6dfoZ.js +138 -0
  34. package/dist/chunks/{schemas-CzTvbXb6.js → schemas-p_aRcMC1.js} +30 -14
  35. package/dist/chunks/server-CCc7fil4.js +410 -0
  36. package/dist/chunks/src--HZrH1U9.js +568 -0
  37. package/dist/chunks/{telemetry-BTwB68m5.js → telemetry-C3LfZcOB.js} +32 -11
  38. package/dist/chunks/{types-DQdfRF3f.d.ts → types-BQYB4Ads.d.ts} +993 -341
  39. package/dist/chunks/{validation-r-sgmsqb.js → validation-fTohBT6R.js} +69 -28
  40. package/dist/chunks/workers-types-iONp32T4.d.ts +143 -0
  41. package/dist/chunks/yaml-Dk2L24yQ.js +74 -0
  42. package/dist/diagnostics.d.ts +6 -4
  43. package/dist/diagnostics.js +2 -2
  44. package/dist/errors.d.ts +2 -2
  45. package/dist/errors.js +2 -2
  46. package/dist/http-paths.d.ts +1 -1
  47. package/dist/http-paths.js +1 -1
  48. package/dist/index.d.ts +2 -2
  49. package/dist/index.js +12 -11
  50. package/dist/internals.d.ts +1 -1
  51. package/dist/internals.js +5 -4
  52. package/dist/mcp/index.d.ts +3 -2
  53. package/dist/mcp/index.js +5 -387
  54. package/dist/postgres/index.d.ts +25 -8
  55. package/dist/postgres/index.js +17 -8
  56. package/dist/project/config.d.ts +110 -72
  57. package/dist/project/config.js +161 -45
  58. package/dist/project/index.d.ts +17 -4
  59. package/dist/project/index.js +44 -9
  60. package/dist/projection.d.ts +14 -13
  61. package/dist/projection.js +8 -32
  62. package/dist/schemas.d.ts +1 -1
  63. package/dist/schemas.js +2 -2
  64. package/dist/standard-failures.d.ts +2 -89
  65. package/dist/tooling/cli.js +149 -105
  66. package/dist/tooling/testing.js +2 -2
  67. package/dist/vite/cloudflare-workers.js +25 -0
  68. package/dist/vite/index.d.ts +157 -0
  69. package/dist/vite/index.js +1477 -0
  70. package/dist/webhooks.d.ts +12 -10
  71. package/dist/webhooks.js +26 -12
  72. package/dist/workers/runtime.d.ts +1 -1
  73. package/dist/workers/runtime.js +1 -1
  74. package/package.json +26 -22
  75. package/skills/maximus/SKILL.md +165 -68
  76. package/skills/maximus/references/deploying.md +73 -0
  77. package/skills/maximus/references/errors-and-results.md +114 -55
  78. package/skills/maximus/references/project.md +202 -0
  79. package/skills/maximus/references/routes-and-tools.md +256 -0
  80. package/skills/maximus/references/testing.md +137 -50
  81. package/skills/maximus/references/transports.md +113 -100
  82. package/skills/maximus/references/writing-code.md +84 -0
  83. package/templates/mcp/mcp/instructions.md.template +2 -0
  84. package/templates/mcp/routes/v1/greeting.get.ts.template +12 -0
  85. package/templates/mcp/tests/mcp.test.ts.template +36 -0
  86. package/templates/project/.agents/skills/project/SKILL.md.template +21 -12
  87. package/templates/project/.github/workflows/ci.yml.template +4 -1
  88. package/templates/project/CLAUDE.md.template +41 -25
  89. package/templates/project/README.md.template +54 -48
  90. package/templates/project/middleware/10-response.ts.template +5 -2
  91. package/templates/project/package.json.template +13 -9
  92. package/templates/project/pages/index.ts.template +2 -4
  93. package/templates/project/routes/v1/greeting.get.ts.template +10 -0
  94. package/templates/project/routes/v1/greeting.post.ts.template +12 -0
  95. package/templates/project/tests/greeting.test.ts.template +45 -0
  96. package/templates/project/tsconfig.json.template +8 -6
  97. package/templates/project/vite.config.ts.template +15 -7
  98. package/templates/web/app/main.tsx.template +16 -0
  99. package/templates/web/app/root.tsx.template +17 -0
  100. package/templates/web/app/routes/index.tsx.template +9 -0
  101. package/templates/web/index.html.template +12 -0
  102. package/templates/web/package.json.template +12 -0
  103. package/templates/web/tsconfig.json.template +7 -0
  104. package/templates/web/vite.config.ts.template +22 -0
  105. package/dist/chunks/builder-BiXv7d2v.js +0 -100
  106. package/dist/chunks/define-app-DvD_1jUE.js +0 -625
  107. package/dist/chunks/prepare-project-CMyGSEtI.js +0 -236
  108. package/dist/chunks/prepare-project-MtS0-W_n.js +0 -3
  109. package/dist/chunks/record-DY-lX9w1.js +0 -34
  110. package/dist/chunks/src-N3oyx5QF.js +0 -1091
  111. package/dist/client/client.d.ts +0 -129
  112. package/dist/client/client.js +0 -321
  113. package/dist/tooling/vite.d.ts +0 -3
  114. package/dist/tooling/vite.js +0 -57
  115. package/skills/maximus/references/adding-an-operation.md +0 -179
  116. package/skills/maximus/references/building-a-service.md +0 -167
  117. package/skills/maximus/references/migration-from-v2.md +0 -62
  118. package/skills/maximus/references/migration-to-v5.md +0 -37
  119. package/skills/maximus/references/publishing-and-verification.md +0 -42
  120. package/templates/project/cloudflare.config.ts.template +0 -24
  121. package/templates/project/maximus.config.ts.template +0 -20
  122. package/templates/project/routes/v1/greeting.ts.template +0 -38
  123. package/templates/service/.agents/skills/project/SKILL.md.template +0 -10
  124. package/templates/service/.github/workflows/ci.yml.template +0 -21
  125. package/templates/service/.gitignore.template +0 -9
  126. package/templates/service/CLAUDE.md.template +0 -5
  127. package/templates/service/README.md.template +0 -45
  128. package/templates/service/cloudflare.config.ts.template +0 -30
  129. package/templates/service/package.json.template +0 -36
  130. package/templates/service/src/app.ts.template +0 -30
  131. package/templates/service/src/index.ts.template +0 -13
  132. package/templates/service/tests/contract.test.ts.template +0 -12
  133. package/templates/service/tsconfig.json.template +0 -16
  134. package/templates/service/vite.config.ts.template +0 -13
  135. package/templates/service/vitest.config.ts.template +0 -10
@@ -0,0 +1,140 @@
1
+ import { KindGuard, Type } from "@sinclair/typebox";
2
+
3
+ // src/handler.ts
4
+ /**
5
+ * Declarations a project binds to its application: `defineHandler` for a route whose path and method come
6
+ * from its filename, `defineTool` for a tool only MCP serves, named by its file, and `defineContext` and
7
+ * `defineAuth` for the context every handler receives and the tokens the application verifies itself. A
8
+ * route or tool takes its handler first and its contract after it; each is a plain value, and binding
9
+ * derives what it leaves out (its name, scope, effect and title) and runs it through the same execution
10
+ * path as every other operation.
11
+ */
12
+ /**
13
+ * A failure a handler answers with, `return fail('TASK_NOT_FOUND')`: an expected outcome, never thrown.
14
+ * `fail` creates one, and so does a byte body's `read()` that cannot read the body.
15
+ */
16
+ var Failed = class Failed {
17
+ /** The catalog failure the call answers. */
18
+ failure;
19
+ constructor(failure) {
20
+ this.failure = failure;
21
+ }
22
+ /** Whether a handler's answer is a failure rather than its output. */
23
+ static is(value) {
24
+ return value instanceof Failed;
25
+ }
26
+ };
27
+ /** The schema `input` or `output` stands for, as `SchemaOf` types it: no fields is an empty strict object. */
28
+ function schemaOf(value) {
29
+ if (value === void 0) return Type.Object({}, { additionalProperties: false });
30
+ return KindGuard.IsSchema(value) ? value : Type.Object(value, { additionalProperties: false });
31
+ }
32
+ /** Every declaration `defineHandler` returned, so binding refuses any other value. */
33
+ const handlers = /* @__PURE__ */ new WeakSet();
34
+ /** Every declaration `defineTool` returned. */
35
+ const tools = /* @__PURE__ */ new WeakSet();
36
+ /** Every handler declaration takes its handler first: an object there is a contract written in its place. */
37
+ function requireHandler(handler, helper) {
38
+ if (typeof handler !== "function") throw new TypeError(`${helper} takes the handler first and its contract after it: ${helper}(async ({ input }) => …, { input, output }).`);
39
+ }
40
+ /**
41
+ * The declaration's schemas and handler. A contract without `output` answers the empty object, so its
42
+ * handler may return nothing.
43
+ */
44
+ function declare(handler, contract) {
45
+ const { input, output, ...options } = contract;
46
+ return Object.freeze({
47
+ options: Object.freeze(options),
48
+ input: schemaOf(input),
49
+ output: schemaOf(output),
50
+ handler: output === void 0 ? async (args) => await handler(args) ?? {} : handler
51
+ });
52
+ }
53
+ /**
54
+ * Declares a route as its file's default export: its handler, then its contract. The filename gives its path
55
+ * and method: `routes/v1/tasks/[taskId].delete.ts` answers `DELETE /v1/tasks/{taskId}` below the API's base
56
+ * path, `/api` by default. The handler receives one object, `{ input, principal, env, fail, …context }`, and
57
+ * returns its output or `fail(code)`. The contract's `input` and `output` are schemas or the fields of strict
58
+ * objects; without a contract, the route takes no input and answers the empty object.
59
+ */
60
+ function defineHandler(handler, contract) {
61
+ requireHandler(handler, "defineHandler");
62
+ const declaration = declare(handler, contract ?? {});
63
+ handlers.add(declaration);
64
+ return declaration;
65
+ }
66
+ /**
67
+ * Declares a tool only MCP serves, as its file's default export: its handler, then its contract.
68
+ * `mcp/tools/summarize-tasks.ts` is the tool `summarize_tasks`, the operation `summarizeTasks` and, by
69
+ * default, the title `Summarize tasks`. The contract states its description and effect; its handler works as
70
+ * a route's.
71
+ */
72
+ function defineTool(handler, contract) {
73
+ requireHandler(handler, "defineTool");
74
+ const declaration = declare(handler, contract);
75
+ tools.add(declaration);
76
+ return declaration;
77
+ }
78
+ /** Whether a module's default export came from `defineHandler`. */
79
+ function isHandlerDeclaration(value) {
80
+ return typeof value === "object" && value !== null && handlers.has(value);
81
+ }
82
+ /** Whether a module's default export came from `defineTool`. */
83
+ function isToolDeclaration(value) {
84
+ return typeof value === "object" && value !== null && tools.has(value);
85
+ }
86
+ /** Every declaration `defineContext` returned. */
87
+ const contexts = /* @__PURE__ */ new WeakSet();
88
+ /**
89
+ * Declares, as `context.ts`'s default export, what every handler receives besides the invocation: it runs
90
+ * once per call after admission and returns the values handlers destructure, such as a store scoped to
91
+ * `principal.organizationId`, or `fail(code)` to answer the call instead. A route that lists its `failures`
92
+ * answers a domain code of the context only when it lists that code too.
93
+ */
94
+ function defineContext(prepare) {
95
+ const declaration = Object.freeze({ prepare });
96
+ contexts.add(declaration);
97
+ return declaration;
98
+ }
99
+ /** Whether `context.ts`'s default export came from `defineContext`. */
100
+ function isContextDeclaration(value) {
101
+ return typeof value === "object" && value !== null && contexts.has(value);
102
+ }
103
+ /** The fields `auth.ts` states: code. The issuer, audience, scheme and every other field are configuration. */
104
+ const AUTH_FIELDS = /* @__PURE__ */ new Set([
105
+ "resolve",
106
+ "resourceMetadataUrl",
107
+ "resources"
108
+ ]);
109
+ /**
110
+ * Declares, as `auth.ts`'s default export, how the application verifies tokens itself: `resolve`, which
111
+ * replaces the default OAuth verification for every token but the development token (for credentials the
112
+ * configured issuer does not issue, such as an application session or a workload key), and its OAuth
113
+ * resources and their metadata URL. Verify every token cryptographically and parse its principal strictly.
114
+ * The issuer, audience, scheme and every other field stay in configuration: any of them here throws a
115
+ * TypeError rather than overriding it.
116
+ */
117
+ function defineAuth(auth) {
118
+ const configured = Object.keys(auth).filter((field) => !AUTH_FIELDS.has(field));
119
+ if (configured.length) throw new TypeError(`auth.ts states how tokens are verified in code; configure ${configured.join(", ")} in vite.config.ts.`);
120
+ return Object.freeze(auth);
121
+ }
122
+ /** The fields `telemetry.ts` states: whether diagnostics run, their observers and the active trace id. */
123
+ const TELEMETRY_FIELDS = /* @__PURE__ */ new Set([
124
+ "enabled",
125
+ "observers",
126
+ "traceId"
127
+ ]);
128
+ /**
129
+ * Declares, as `telemetry.ts`'s default export, what the application's diagnostics do: whether Maximus writes
130
+ * its log events, calls observers and annotates spans (`enabled`, on by default), the observers that receive
131
+ * each call's safe metadata, such as `analytics()` from `@arbol-ai/maximus/analytics`, and how to read the
132
+ * active trace id (`traceId`). Any other field throws a TypeError.
133
+ */
134
+ function defineTelemetry(telemetry) {
135
+ const unknown = Object.keys(telemetry).filter((field) => !TELEMETRY_FIELDS.has(field));
136
+ if (unknown.length) throw new TypeError(`telemetry.ts states only enabled, observers and traceId: remove ${unknown.join(", ")}.`);
137
+ return Object.freeze(telemetry);
138
+ }
139
+
140
+ export { defineTelemetry as a, isHandlerDeclaration as c, defineHandler as i, isToolDeclaration as l, defineAuth as n, defineTool as o, defineContext as r, isContextDeclaration as s, Failed as t };
@@ -0,0 +1,128 @@
1
+ import { l as usesOwnBearer, v as usesCloudflareAccess } from "./openapi-CV0KmJpS.js";
2
+
3
+ // src/internal/http-layout.ts
4
+ /**
5
+ * Where everything an HTTP handler serves lives, checked once at construction: the application's own
6
+ * paths below its base path, its transports, its plain routes and its mounts. No two of them may
7
+ * claim the same path, and none may claim an operation route's.
8
+ */
9
+ /** The paths an application answers itself, below its base path: discovery and liveness. */
10
+ const NATIVE_PATHS = [
11
+ "/",
12
+ "/health",
13
+ "/openapi.json",
14
+ "/openapi.yaml",
15
+ "/openapi.yml",
16
+ "/.well-known/oauth-protected-resource",
17
+ "/.well-known/oauth-protected-resource/mcp"
18
+ ];
19
+ /** An absolute path of slash-separated unreserved characters. */
20
+ const PLAIN_ROUTE_PATH = /^\/[a-zA-Z0-9._~-]+(?:\/[a-zA-Z0-9._~-]+)*$/;
21
+ /** `/v1`, `/v2/…`: the namespace of operation routes, which nothing else may claim. */
22
+ const VERSIONED_PATH = /^\/v[1-9][0-9]*(?:\/|$)/;
23
+ /** An absolute path of unreserved characters, without a trailing slash or dot segments. */
24
+ function validPath(path) {
25
+ return PLAIN_ROUTE_PATH.test(path) && !path.split("/").some((segment) => segment === "." || segment === "..");
26
+ }
27
+ /** Whether `prefix` owns `path`: the prefix itself, or any slash-delimited descendant. */
28
+ function ownsPrefix(prefix, path) {
29
+ return path === prefix || path.startsWith(`${prefix}/`);
30
+ }
31
+ /**
32
+ * Checks where the application's own paths live: its base path, its liveness path and its OAuth resources.
33
+ */
34
+ function nativePaths(tokens, hooks) {
35
+ const base = hooks.basePath === "/" ? "" : hooks.basePath ?? "";
36
+ if (base && !validPath(base)) throw new TypeError("HTTP basePath must be an absolute path without a trailing slash or dot segments.");
37
+ /** A native path as served below the base path. */
38
+ const mount = (path) => base ? `${base}${path === "/" ? "" : path}` : path;
39
+ /** A served path as the native path it is, or null outside the base path. */
40
+ const local = (path) => {
41
+ if (base === "") return path;
42
+ if (path === base) return "/";
43
+ return path.startsWith(`${base}/`) ? path.slice(base.length) : null;
44
+ };
45
+ const reserved = new Set(NATIVE_PATHS.map(mount));
46
+ const health = hooks.healthPath ?? mount("/health");
47
+ if (!validPath(health) || reserved.has(health) && health !== mount("/health") || VERSIONED_PATH.test(local(health) ?? "")) throw new TypeError("HTTP healthPath must be an unreserved absolute path.");
48
+ reserved.add(health);
49
+ const resources = new Map(Object.entries(tokens.resources ?? {}));
50
+ for (const path of resources.keys()) {
51
+ if (!validPath(path) || !ownsPrefix("/.well-known/oauth-protected-resource", path) || path === health) throw new TypeError("OAuth resources require distinct absolute protected-resource discovery paths.");
52
+ reserved.add(path);
53
+ }
54
+ return {
55
+ base,
56
+ mount,
57
+ local,
58
+ reserved,
59
+ health,
60
+ resources
61
+ };
62
+ }
63
+ /**
64
+ * Checks the transports: one per path, at most one MCP transport, and one whenever the application configures
65
+ * MCP.
66
+ */
67
+ function httpTransports(transports = [], mcpConfigured = false) {
68
+ const byPath = new Map(transports.map((transport) => [transport.path, transport]));
69
+ const mcpTransports = [...byPath.values()].filter((transport) => transport.protocol === "mcp" || transport.path === "/mcp");
70
+ if (mcpTransports.length > 1) throw new TypeError("An HTTP handler may mount only one MCP transport.");
71
+ const [mcp] = mcpTransports;
72
+ if (mcpConfigured && !mcp) throw new TypeError("MCP configuration requires the optional MCP transport.");
73
+ if (byPath.size !== transports.length) throw new TypeError("Duplicate transport path.");
74
+ return {
75
+ byPath,
76
+ mcp
77
+ };
78
+ }
79
+ /**
80
+ * Whether the application issues its own bearer tokens, refusing a token scheme the handler could
81
+ * never serve: own bearer tokens publish no OAuth discovery, need a resolver and cannot serve MCP.
82
+ */
83
+ function servesOwnBearer(tokens, mcp) {
84
+ const ownBearer = usesOwnBearer(tokens);
85
+ if (ownBearer && tokens.resources !== void 0) throw new TypeError("A bearer token scheme cannot publish OAuth resource discovery.");
86
+ if ((ownBearer || tokens.scheme?.type === "oauth+bearer") && !tokens.resolve) throw new TypeError("An application bearer token scheme requires tokens.resolve to verify the token.");
87
+ if (ownBearer && mcp) throw new TypeError("The MCP transport needs OAuth discovery; it cannot serve a bearer token scheme.");
88
+ return ownBearer;
89
+ }
90
+ /**
91
+ * Whether the application admits Cloudflare Access application tokens, refusing the MCP transport beside
92
+ * them: MCP clients find their authorization server through OAuth discovery and present its bearer tokens,
93
+ * neither of which Access serves.
94
+ */
95
+ function servesCloudflareAccess(tokens, mcp) {
96
+ const access = usesCloudflareAccess(tokens);
97
+ if (access && mcp) throw new TypeError("The MCP transport needs OAuth discovery and bearer tokens; it cannot serve Cloudflare Access application tokens.");
98
+ return access;
99
+ }
100
+ /**
101
+ * Checks that every transport, plain route and mount path is well formed and claims nothing the
102
+ * application, an operation route or another of them already owns.
103
+ */
104
+ function composition(paths, operations, transports, hooks) {
105
+ const transportPaths = [...transports.byPath.keys()];
106
+ for (const path of transportPaths) if (!(path === "/" && transports.mcp?.path === "/") && !validPath(path) || paths.reserved.has(path) || VERSIONED_PATH.test(paths.local(path) ?? "") || operations.ownsPath(paths.local(path) ?? "") || transportPaths.some((other) => other !== path && (ownsPrefix(other, path) || ownsPrefix(path, other)))) throw new TypeError(`Transport path is reserved: ${path}`);
107
+ const routes = new Map(Object.entries(hooks.routes ?? {}));
108
+ for (const path of routes.keys()) if (!validPath(path) || VERSIONED_PATH.test(paths.local(path) ?? "") || paths.reserved.has(path) || operations.ownsPath(paths.local(path) ?? "") || transports.byPath.has(path)) throw new TypeError(`Route path is reserved or malformed: ${path}`);
109
+ const mounts = new Map(Object.entries(hooks.mounts ?? {}));
110
+ for (const prefix of mounts.keys()) {
111
+ const local = paths.local(prefix);
112
+ if (!validPath(prefix) || VERSIONED_PATH.test(local ?? "") || [...paths.reserved].some((path) => ownsPrefix(prefix, path)) || [...transportPaths, ...routes.keys()].some((path) => ownsPrefix(prefix, path) || ownsPrefix(path, prefix)) || operations.ownsPath(local ?? "")) throw new TypeError(`Mount path is reserved or malformed: ${prefix}`);
113
+ }
114
+ return {
115
+ routes,
116
+ mounted(path) {
117
+ let route;
118
+ let prefix = "";
119
+ for (const segment of path.slice(1).split("/")) {
120
+ prefix += `/${segment}`;
121
+ route = mounts.get(prefix) ?? route;
122
+ }
123
+ return route;
124
+ }
125
+ };
126
+ }
127
+
128
+ export { ownsPrefix as a, nativePaths as i, composition as n, servesCloudflareAccess as o, httpTransports as r, servesOwnBearer as s, VERSIONED_PATH as t };
@@ -25,21 +25,28 @@ const RESERVED_HEADERS = /* @__PURE__ */ new Set([
25
25
  function isInputHeaderName(header) {
26
26
  return /^[A-Za-z0-9-]+$/u.test(header) && !RESERVED_HEADERS.has(header.toLowerCase());
27
27
  }
28
- /** Parse declared templates, never caller paths. Parameters occupy one complete path segment. */
28
+ /**
29
+ * The parameter names of a declared route template, in order. A template is versioned (`/v1/…`) with at least
30
+ * one segment after the version, each fixed or a complete `{parameter}` with a unique, safe name; anything
31
+ * else throws a TypeError. It reads declared templates, never a request's path.
32
+ */
29
33
  function operationPathParameters(path) {
30
34
  const segments = path.split("/");
31
- if (segments[0] !== "" || !/^v[1-9][0-9]*$/.test(segments[1] ?? "") || segments.length < 3) throw new TypeError("Operations require a versioned path.");
35
+ if (segments[0] !== "" || !/^v[1-9][0-9]*$/.test(segments[1] ?? "") || segments.length < 3) throw new TypeError(`Operations require a versioned path, such as /v1/tasks: ${path}`);
32
36
  const parameters = [];
33
37
  for (const segment of segments.slice(2)) {
34
38
  const parameter = PARAMETER_SEGMENT.exec(segment)?.[1];
35
39
  if (parameter) {
36
- if (UNSAFE_PARAMETERS.has(parameter) || parameters.includes(parameter)) throw new TypeError("Path parameter names must be unique and safe.");
40
+ if (UNSAFE_PARAMETERS.has(parameter) || parameters.includes(parameter)) throw new TypeError(`Path parameter names must be unique and safe: ${path}`);
37
41
  parameters.push(parameter);
38
- } else if (!STATIC_SEGMENT.test(segment)) throw new TypeError("Use fixed routes or complete {parameter} segments; empty and malformed segments are forbidden.");
42
+ } else if (!STATIC_SEGMENT.test(segment)) throw new TypeError(`Use fixed routes or complete {parameter} segments; empty and malformed segments are forbidden: ${path}`);
39
43
  }
40
44
  return parameters;
41
45
  }
42
- /** A decoded item key stays in one segment; dot segments and controls cannot alter URL ownership. */
46
+ /**
47
+ * One path segment, percent-decoded, or null when it does not decode or decodes to a value
48
+ * `isPathParameterValue` refuses, so decoding cannot change which route a path reaches.
49
+ */
43
50
  function decodePathParameter(segment) {
44
51
  try {
45
52
  const value = decodeURIComponent(segment);
@@ -48,12 +55,15 @@ function decodePathParameter(segment) {
48
55
  return null;
49
56
  }
50
57
  }
51
- /** Item keys are nonempty strings that cannot change URL path ownership when encoded. */
58
+ /**
59
+ * Whether a value can be a path parameter: a nonempty string other than `.` and `..`, without a slash, a
60
+ * backslash, a control character or a lone surrogate, so it stays one segment when encoded.
61
+ */
52
62
  function isPathParameterValue(value) {
53
63
  if (typeof value !== "string" || value.length === 0 || value === "." || value === ".." || /[\\/]/.test(value)) return false;
54
64
  for (const character of value) {
55
- const code = character.charCodeAt(0);
56
- if (code < 32 || code === 127) return false;
65
+ const code = character.codePointAt(0) ?? 0;
66
+ if (code < 32 || code === 127 || code >= 55296 && code <= 57343) return false;
57
67
  }
58
68
  return true;
59
69
  }
@@ -65,9 +75,16 @@ const HTTP_METHODS = /* @__PURE__ */ new Set([
65
75
  "PATCH",
66
76
  "DELETE"
67
77
  ]);
78
+ /** A route as a refusal names it: its method and path template, `GET /v1/notes/{noteId}`. */
79
+ function routeName(route) {
80
+ return `${route.definition.http?.method} ${route.definition.http?.path}`;
81
+ }
68
82
  /**
69
- * Exact routes use a Map. Template branches compile into deterministic states at construction:
70
- * one transition per segment, including overlapping fixed prefixes, with no per-request route scan.
83
+ * The router for a set of definitions: `match(method, path)` finds the one route a request reaches, with its
84
+ * decoded parameters, and `ownsPath(path)` says whether any route answers a path. A definition without `http`
85
+ * 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.
71
88
  */
72
89
  function createHttpRouteResolver(definitions) {
73
90
  const exact = /* @__PURE__ */ new Map();
@@ -84,7 +101,7 @@ function createHttpRouteResolver(definitions) {
84
101
  };
85
102
  for (const definition of definitions) {
86
103
  if (!definition.http) continue;
87
- if (!HTTP_METHODS.has(definition.http.method)) throw new TypeError("Operation routes require a supported HTTP method.");
104
+ if (!HTTP_METHODS.has(definition.http.method)) throw new TypeError(`Operation routes require a supported HTTP method: ${definition.http.method} ${definition.http.path}`);
88
105
  const names = operationPathParameters(definition.http.path);
89
106
  const segments = definition.http.path.slice(1).split("/");
90
107
  const route = {
@@ -99,7 +116,7 @@ function createHttpRouteResolver(definitions) {
99
116
  };
100
117
  if (names.length === 0) {
101
118
  const key = `${definition.http.method} ${definition.http.path}`;
102
- if (exact.has(key)) throw new TypeError("Duplicate operation route.");
119
+ if (exact.has(key)) throw new TypeError(`Duplicate operation route: ${key}`);
103
120
  exact.set(key, route);
104
121
  continue;
105
122
  }
@@ -119,7 +136,7 @@ function createHttpRouteResolver(definitions) {
119
136
  }
120
137
  node = child;
121
138
  }
122
- if (node.route) throw new TypeError("Ambiguous operation path templates.");
139
+ if (node.route) throw new TypeError(`Ambiguous operation path templates: ${routeName(node.route)} and ${routeName(route)}`);
123
140
  node.route = route;
124
141
  }
125
142
  const states = /* @__PURE__ */ new Map();
@@ -133,7 +150,7 @@ function createHttpRouteResolver(definitions) {
133
150
  const known = states.get(key);
134
151
  if (known) return known;
135
152
  const routes = distinct.flatMap((node) => node.route ? [node.route] : []);
136
- if (routes.length > 1) throw new TypeError("Ambiguous overlapping operation path templates.");
153
+ if (routes.length > 1) throw new TypeError(`Ambiguous overlapping operation path templates: ${routes.map(routeName).join(" and ")}`);
137
154
  const state = {
138
155
  fixed: /* @__PURE__ */ new Map(),
139
156
  route: routes[0]
@@ -153,14 +170,12 @@ function createHttpRouteResolver(definitions) {
153
170
  }
154
171
  const templates = new Map([...roots].map(([method, root]) => [method, compile([root])]));
155
172
  /**
156
- * The route for a method and path: an exact route first, then one transition per segment through the
157
- * compiled states.
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.
158
175
  */
159
- function findRoute(method, path) {
160
- const fixed = exact.get(`${method} ${path}`);
176
+ function findRoute(method, segments) {
177
+ const fixed = exact.get(`${method} /${segments.join("/")}`);
161
178
  if (fixed) return fixed;
162
- if (!path.startsWith("/") || path.endsWith("/")) return null;
163
- const segments = path.slice(1).split("/");
164
179
  let state = templates.get(method);
165
180
  for (const segment of segments) {
166
181
  if (!segment || !state) return null;
@@ -169,19 +184,22 @@ function createHttpRouteResolver(definitions) {
169
184
  return state?.route ?? null;
170
185
  }
171
186
  /**
172
- * The route a request reaches, with its path parameters decoded; null when none matches or a parameter
173
- * value is unsafe.
187
+ * The route a request reaches, with its path parameters: every segment is decoded before it is matched, so
188
+ * `/v1/notes/%61rchive` is `/v1/notes/archive` and reaches its route, never a sibling `{noteId}` as the
189
+ * value `archive`. Null when none matches, or a segment is empty or decodes to an unsafe value.
174
190
  */
175
191
  function match(method, path) {
176
- const route = findRoute(method, path);
192
+ if (!path.startsWith("/")) return null;
193
+ const segments = [];
194
+ for (const segment of path.slice(1).split("/")) {
195
+ const decoded = decodePathParameter(segment);
196
+ if (decoded === null) return null;
197
+ segments.push(decoded);
198
+ }
199
+ const route = findRoute(method, segments);
177
200
  if (!route) return null;
178
- const segments = path.slice(1).split("/");
179
201
  const parameters = {};
180
- for (const parameter of route.parameters) {
181
- const value = decodePathParameter(segments[parameter.position] ?? "");
182
- if (value === null) return null;
183
- parameters[parameter.name] = value;
184
- }
202
+ for (const parameter of route.parameters) parameters[parameter.name] = segments[parameter.position] ?? "";
185
203
  return {
186
204
  definition: route.definition,
187
205
  parameters
@@ -189,9 +207,10 @@ function createHttpRouteResolver(definitions) {
189
207
  }
190
208
  return {
191
209
  match,
192
- /** Used only at construction to prevent a transport from bypassing item-route authorization. */
210
+ /** Whether any route answers a declared path, so a transport cannot claim an operation's path. */
193
211
  ownsPath(path) {
194
- return [...HTTP_METHODS].some((method) => findRoute(method, path) !== null);
212
+ const segments = path.slice(1).split("/");
213
+ return [...HTTP_METHODS].some((method) => findRoute(method, segments) !== null);
195
214
  }
196
215
  };
197
216
  }
@@ -1,16 +1,24 @@
1
- import { r as readBodyText, t as httpBodyFailure } from "./body-6LichrQm.js";
1
+ import { r as readBodyText, t as httpBodyFailure } from "./body-DOIHwIIl.js";
2
2
 
3
3
  // src/internal/json.ts
4
4
  /** The media type of a Content-Type value, lowercased and without its parameters. */
5
5
  function mediaType(contentType) {
6
6
  return contentType?.split(";", 1)[0]?.trim().toLowerCase();
7
7
  }
8
- /** `application/json`, or a structured `+json` type such as `application/problem+json`. */
8
+ /**
9
+ * Whether a Content-Type value is `application/json` or a structured `+json` type such as
10
+ * `application/problem+json`, whatever its parameters and case.
11
+ */
9
12
  function isJsonMediaType(value) {
10
13
  const type = mediaType(value);
11
14
  return type === "application/json" || /^application\/[a-z0-9!#$&^_.+-]+\+json$/.test(type ?? "");
12
15
  }
13
- /** Decode bounded JSON into unknown for the owner's input/output validator. */
16
+ /**
17
+ * Reads a JSON body within `maxBytes` and parses it, as `unknown` for a schema to check. A Content-Type other
18
+ * than `application/json` (or any `+json` type, with `allowJsonSuffix`) fails as `unexpected_content_type`
19
+ * before anything is read, and text that does not parse as `invalid_json`; the other failures are
20
+ * `readBodyText`'s.
21
+ */
14
22
  async function readJsonBody(source, options) {
15
23
  const contentType = source.headers.get("content-type");
16
24
  if (!(options.allowJsonSuffix ? isJsonMediaType(contentType) : mediaType(contentType) === "application/json")) {
@@ -34,7 +42,11 @@ async function readJsonBody(source, options) {
34
42
  };
35
43
  }
36
44
  }
37
- /** Pass the same deadline to fetch; empty 204/205 responses have no JSON body. */
45
+ /**
46
+ * Reads a response's JSON body as `readJsonBody` does, accepting any `+json` type: a 204 or 205 reads as
47
+ * `null`, and a signal already aborted fails as `aborted` without reading. Pass the signal the `fetch` used,
48
+ * so one deadline covers the request and its body.
49
+ */
38
50
  async function readJsonResponse(response, options) {
39
51
  if (options.signal.aborted) {
40
52
  response.body?.cancel().catch(() => {});
@@ -52,7 +64,11 @@ async function readJsonResponse(response, options) {
52
64
  allowJsonSuffix: true
53
65
  });
54
66
  }
55
- /** Bounded Retry-After hint only. A hint never makes repeating a mutation safe. */
67
+ /**
68
+ * The seconds a `Retry-After` value asks a client to wait, as delta seconds or as an HTTP date relative to
69
+ * `nowMs`, rounded up and held between 0 and `maximum` (an hour by default); undefined when the value is
70
+ * absent or unreadable. It is a hint: it never makes repeating a write safe.
71
+ */
56
72
  function retryAfterSeconds(value, nowMs, maximum = 3600) {
57
73
  if (!value || !Number.isFinite(nowMs) || !Number.isSafeInteger(maximum) || maximum < 0) return;
58
74
  const seconds = /^\d+$/.test(value.trim()) ? Number(value.trim()) : (Date.parse(value) - nowMs) / 1e3;