@arbol-ai/maximus 7.3.1 → 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.
- package/README.md +36 -38
- package/bin/maximus.js +4 -0
- package/config/oxfmt.mjs +1 -0
- package/config/oxlint.mjs +10 -0
- package/dist/analytics/analytics.d.ts +21 -9
- package/dist/analytics/analytics.js +19 -5
- package/dist/body.d.ts +1 -1
- package/dist/body.js +2 -2
- package/dist/chunks/agent-skills-Ef65jTf_.js +49 -0
- package/dist/chunks/agent-skills-m7y1EUch.js +3 -0
- package/dist/chunks/{body-6LichrQm.js → body-DOIHwIIl.js} +14 -7
- package/dist/chunks/{correlation-BEkcFFGT.js → correlation-4b23a-a4.js} +8 -5
- package/dist/chunks/define-app-CfVZBt7D.js +336 -0
- package/dist/chunks/errors-WfyKhiyk.js +131 -0
- package/dist/chunks/execution-CfZEx_JP.js +84 -0
- package/dist/chunks/generate-C-9FKW0o.js +197 -0
- package/dist/chunks/handler-DWTGoduQ.js +140 -0
- package/dist/chunks/http-layout-_h7xwgPC.js +128 -0
- package/dist/chunks/http-paths-DMBxwpp6.js +218 -0
- package/dist/chunks/{json-Bu4BLT25.js → json-B14evE6-.js} +21 -5
- package/dist/chunks/names-ncD7A3DV.js +280 -0
- package/dist/chunks/openapi-CV0KmJpS.js +1588 -0
- package/dist/chunks/openapi-file-OjSs9mRv.js +83 -0
- package/dist/chunks/pages-DyC0m8Zb.js +14 -0
- package/dist/chunks/prepare-configured-BmRJLg6J.js +3 -0
- package/dist/chunks/prepare-configured-Cithjf80.js +52 -0
- package/dist/chunks/project-files-C0OX7MQQ.js +130 -0
- package/dist/chunks/query-kind-CWKAXEME.js +40 -0
- package/dist/chunks/record-DQUDTpEA.js +10 -0
- package/dist/chunks/result-CKgZHrnj.js +56 -0
- package/dist/chunks/{runtime-BPnaa-NK.js → runtime-CVVf5hmp.js} +50 -25
- package/dist/chunks/scaffold-DGrcjR3h.js +3 -0
- package/dist/chunks/scaffold-DZD6dfoZ.js +138 -0
- package/dist/chunks/{schemas-CzTvbXb6.js → schemas-p_aRcMC1.js} +30 -14
- package/dist/chunks/server-CCc7fil4.js +410 -0
- package/dist/chunks/src--HZrH1U9.js +568 -0
- package/dist/chunks/standard-failures-CLjxS2ea.js +74 -0
- package/dist/chunks/{telemetry-BTwB68m5.js → telemetry-C3LfZcOB.js} +32 -11
- package/dist/chunks/{types-BWxDd3tY.d.ts → types-BQYB4Ads.d.ts} +998 -337
- package/dist/chunks/{validation-r-sgmsqb.js → validation-fTohBT6R.js} +69 -28
- package/dist/chunks/workers-types-iONp32T4.d.ts +143 -0
- package/dist/chunks/yaml-Dk2L24yQ.js +74 -0
- package/dist/diagnostics.d.ts +6 -4
- package/dist/diagnostics.js +2 -2
- package/dist/errors.d.ts +2 -2
- package/dist/errors.js +2 -125
- package/dist/http-paths.d.ts +1 -1
- package/dist/http-paths.js +1 -197
- package/dist/index.d.ts +2 -2
- package/dist/index.js +12 -10
- package/dist/internals.d.ts +1 -1
- package/dist/internals.js +5 -3
- package/dist/mcp/index.d.ts +3 -2
- package/dist/mcp/index.js +5 -387
- package/dist/postgres/index.d.ts +25 -8
- package/dist/postgres/index.js +17 -8
- package/dist/project/config.d.ts +139 -0
- package/dist/project/config.js +196 -0
- package/dist/project/index.d.ts +17 -4
- package/dist/project/index.js +44 -9
- package/dist/projection.d.ts +14 -13
- package/dist/projection.js +8 -32
- package/dist/schemas.d.ts +1 -1
- package/dist/schemas.js +2 -2
- package/dist/standard-failures.d.ts +2 -89
- package/dist/standard-failures.js +1 -72
- package/dist/tooling/cli.js +151 -107
- package/dist/tooling/testing.js +2 -2
- package/dist/vite/cloudflare-workers.js +25 -0
- package/dist/vite/index.d.ts +157 -0
- package/dist/vite/index.js +1477 -0
- package/dist/webhooks.d.ts +12 -10
- package/dist/webhooks.js +26 -12
- package/dist/workers/runtime.d.ts +1 -1
- package/dist/workers/runtime.js +1 -1
- package/package.json +30 -22
- package/skills/maximus/SKILL.md +165 -69
- package/skills/maximus/references/deploying.md +73 -0
- package/skills/maximus/references/errors-and-results.md +114 -55
- package/skills/maximus/references/project.md +202 -0
- package/skills/maximus/references/routes-and-tools.md +256 -0
- package/skills/maximus/references/testing.md +137 -50
- package/skills/maximus/references/transports.md +113 -100
- package/skills/maximus/references/writing-code.md +84 -0
- package/templates/mcp/mcp/instructions.md.template +2 -0
- package/templates/mcp/routes/v1/greeting.get.ts.template +12 -0
- package/templates/mcp/tests/mcp.test.ts.template +36 -0
- package/templates/project/.agents/skills/project/SKILL.md.template +21 -12
- package/templates/project/.github/workflows/ci.yml.template +4 -1
- package/templates/project/CLAUDE.md.template +41 -22
- package/templates/project/README.md.template +54 -47
- package/templates/project/middleware/10-response.ts.template +16 -0
- package/templates/project/package.json.template +16 -8
- package/templates/project/pages/index.ts.template +2 -4
- package/templates/project/routes/v1/greeting.get.ts.template +10 -0
- package/templates/project/routes/v1/greeting.post.ts.template +12 -0
- package/templates/project/tests/greeting.test.ts.template +45 -0
- package/templates/project/tsconfig.json.template +8 -5
- package/templates/project/vite.config.ts.template +15 -7
- package/templates/web/app/main.tsx.template +16 -0
- package/templates/web/app/root.tsx.template +17 -0
- package/templates/web/app/routes/index.tsx.template +9 -0
- package/templates/web/index.html.template +12 -0
- package/templates/web/package.json.template +12 -0
- package/templates/web/tsconfig.json.template +7 -0
- package/templates/web/vite.config.ts.template +22 -0
- package/dist/chunks/execution-B-yy4C7N.js +0 -691
- package/dist/chunks/prepare-project-zi106pWF.js +0 -146
- package/dist/chunks/record-DY-lX9w1.js +0 -34
- package/dist/chunks/src-DPSpGNnT.js +0 -1164
- package/dist/client/client.d.ts +0 -129
- package/dist/client/client.js +0 -321
- package/dist/tooling/vite.d.ts +0 -3
- package/dist/tooling/vite.js +0 -44
- package/skills/maximus/references/adding-an-operation.md +0 -179
- package/skills/maximus/references/building-a-service.md +0 -167
- package/skills/maximus/references/migration-from-v2.md +0 -62
- package/skills/maximus/references/migration-to-v5.md +0 -37
- package/skills/maximus/references/publishing-and-verification.md +0 -39
- package/templates/project/cloudflare.config.ts.template +0 -24
- package/templates/project/routes/v1/greeting.ts.template +0 -22
- package/templates/project/src/app.ts.template +0 -2
- package/templates/project/src/application.ts.template +0 -26
- package/templates/project/src/index.ts.template +0 -3
- package/templates/project/src/worker.ts.template +0 -6
- package/templates/service/.agents/skills/project/SKILL.md.template +0 -10
- package/templates/service/.github/workflows/ci.yml.template +0 -21
- package/templates/service/.gitignore.template +0 -9
- package/templates/service/CLAUDE.md.template +0 -5
- package/templates/service/README.md.template +0 -45
- package/templates/service/cloudflare.config.ts.template +0 -30
- package/templates/service/package.json.template +0 -36
- package/templates/service/src/app.ts.template +0 -30
- package/templates/service/src/index.ts.template +0 -13
- package/templates/service/tests/contract.test.ts.template +0 -12
- package/templates/service/tsconfig.json.template +0 -16
- package/templates/service/vite.config.ts.template +0 -13
- package/templates/service/vitest.config.ts.template +0 -10
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { a as operationPathParameters } from "./http-paths-DMBxwpp6.js";
|
|
2
|
+
import { a as projectPath, i as projectFiles, n as checkProjectFolder, s as routeShape } from "./project-files-C0OX7MQQ.js";
|
|
3
|
+
import { existsSync, lstatSync, mkdirSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
5
|
+
|
|
6
|
+
// src/tooling/internal/generate.ts
|
|
7
|
+
/**
|
|
8
|
+
* `maximus gen`: a new route or MCP tool file, named and placed by the conventions prepare reads, with a
|
|
9
|
+
* handler and a contract to fill in. An existing module is never overwritten, and neither is a route a file
|
|
10
|
+
* already answers.
|
|
11
|
+
*/
|
|
12
|
+
/** The methods a route file may answer, by the suffix its name takes. */
|
|
13
|
+
const METHODS = [
|
|
14
|
+
"get",
|
|
15
|
+
"post",
|
|
16
|
+
"put",
|
|
17
|
+
"patch",
|
|
18
|
+
"delete"
|
|
19
|
+
];
|
|
20
|
+
/** A tool's file name, which names it: lowercase words joined by single hyphens. */
|
|
21
|
+
const TOOL = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
22
|
+
/** An MCP tool name a route declares: lowercase words joined by single underscores. */
|
|
23
|
+
const TOOL_NAME = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
|
|
24
|
+
/** The widest line the project's formatter writes, in characters. */
|
|
25
|
+
const PRINT_WIDTH = 110;
|
|
26
|
+
/** The base path a project serves its API below unless its configuration moves it. */
|
|
27
|
+
const API_BASE_PATH = "/api";
|
|
28
|
+
/** A one-sentence JSDoc comment: on one line when it fits, otherwise wrapped at the formatter's width. */
|
|
29
|
+
function jsDoc(sentence) {
|
|
30
|
+
const line = `/** ${sentence} */`;
|
|
31
|
+
if (line.length <= PRINT_WIDTH) return [line];
|
|
32
|
+
const lines = [];
|
|
33
|
+
let current = " *";
|
|
34
|
+
for (const word of sentence.split(" ")) {
|
|
35
|
+
const fitsAlone = ` * ${word}`.length <= PRINT_WIDTH;
|
|
36
|
+
if (current !== " *" && fitsAlone && `${current} ${word}`.length > PRINT_WIDTH) {
|
|
37
|
+
lines.push(current);
|
|
38
|
+
current = " *";
|
|
39
|
+
}
|
|
40
|
+
current = `${current} ${word}`;
|
|
41
|
+
}
|
|
42
|
+
return [
|
|
43
|
+
"/**",
|
|
44
|
+
...lines,
|
|
45
|
+
current,
|
|
46
|
+
" */"
|
|
47
|
+
];
|
|
48
|
+
}
|
|
49
|
+
/** `head{ a, b }tail`, as the formatter writes it: on one line when it fits, otherwise one entry per line. */
|
|
50
|
+
function braces(indent, head, entries, tail) {
|
|
51
|
+
const line = `${indent}${head}{ ${entries.join(", ")} }${tail}`;
|
|
52
|
+
if (line.length <= PRINT_WIDTH) return [line];
|
|
53
|
+
return [
|
|
54
|
+
`${indent}${head}{`,
|
|
55
|
+
...entries.map((entry) => `${indent} ${entry},`),
|
|
56
|
+
`${indent}}${tail}`
|
|
57
|
+
];
|
|
58
|
+
}
|
|
59
|
+
/** `const { a, b } = input;` as the formatter writes it: it breaks after `=` before it breaks the braces. */
|
|
60
|
+
function destructureInput(indent, names) {
|
|
61
|
+
const pattern = `${indent}const { ${names.join(", ")} } =`;
|
|
62
|
+
if (`${pattern} input;`.length <= PRINT_WIDTH) return [`${pattern} input;`];
|
|
63
|
+
if (pattern.length <= PRINT_WIDTH) return [pattern, `${indent} input;`];
|
|
64
|
+
return braces(indent, "const ", names, " = input;");
|
|
65
|
+
}
|
|
66
|
+
/** A contract field whose value is text, as the formatter writes it: a long text on a line of its own. */
|
|
67
|
+
function textField(indent, name, text) {
|
|
68
|
+
const line = `${indent}${name}: '${text}',`;
|
|
69
|
+
if (line.length <= PRINT_WIDTH) return [line];
|
|
70
|
+
return [`${indent}${name}:`, `${indent} '${text}',`];
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* A placeholder handler that answers its input fields back, written as statements: it names the fields it
|
|
74
|
+
* takes, then answers them.
|
|
75
|
+
*/
|
|
76
|
+
function echoHandler(names) {
|
|
77
|
+
return [
|
|
78
|
+
" ({ input }) => {",
|
|
79
|
+
...destructureInput(" ", names),
|
|
80
|
+
...braces(" ", "return ", names, ";"),
|
|
81
|
+
" },"
|
|
82
|
+
];
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* A route's path as file segments: `/v1/tasks/{taskId}`, `/v1/tasks/:taskId` and `v1/tasks/[taskId]` are
|
|
86
|
+
* `v1`, `tasks` and `[taskId]`. A leading `/api` is the base path, not the route's.
|
|
87
|
+
*/
|
|
88
|
+
function routeSegments(path) {
|
|
89
|
+
const segments = path.replace(/^\/?api(?=\/v[1-9])/, "").split("/").filter(Boolean).map((segment) => {
|
|
90
|
+
const parameter = /^(?:\{([a-zA-Z][a-zA-Z0-9_]*)\}|:([a-zA-Z][a-zA-Z0-9_]*)|\[([a-zA-Z][a-zA-Z0-9_]*)\])$/.exec(segment);
|
|
91
|
+
if (parameter) return `[${parameter[1] ?? parameter[2] ?? parameter[3]}]`;
|
|
92
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(segment)) throw new TypeError(`Use letters, digits, _ and - in a fixed segment, and {name} for a parameter: ${segment}`);
|
|
93
|
+
return segment;
|
|
94
|
+
});
|
|
95
|
+
if (!/^v[1-9][0-9]*$/.test(segments[0] ?? "") || segments.length < 2) throw new TypeError(`A route lives below its API version, such as /v1/tasks: ${path}`);
|
|
96
|
+
return segments;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Writes a new file of the project, refusing an existing one, a path that leads outside the project and a
|
|
100
|
+
* folder on the way that is a symlink.
|
|
101
|
+
*/
|
|
102
|
+
function writeModule(root, path, text) {
|
|
103
|
+
const target = resolve(root, path);
|
|
104
|
+
if (relative(root, target).startsWith("..")) throw new TypeError(`${path} is outside the project.`);
|
|
105
|
+
checkProjectFolder(root, dirname(target));
|
|
106
|
+
if (existsSync(target) || lstatSync(target, { throwIfNoEntry: false })) throw new TypeError(`${path} exists; edit it instead.`);
|
|
107
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
108
|
+
writeFileSync(target, text, { flag: "wx" });
|
|
109
|
+
return target;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Writes `routes/<path>.<method>.ts`, or `routes/<path>/index.<method>.ts` when `<path>` is already a folder,
|
|
113
|
+
* declaring a route that takes its path parameters and answers them back, an MCP tool too when `tool` names
|
|
114
|
+
* it. Refuses a method and path a route file already answers.
|
|
115
|
+
*/
|
|
116
|
+
function generateRoute(directory, method, path, tool) {
|
|
117
|
+
const root = resolve(directory);
|
|
118
|
+
const verb = method.toLowerCase();
|
|
119
|
+
if (!METHODS.some((known) => known === verb)) throw new TypeError(`Choose a route method: ${METHODS.join(", ")}.`);
|
|
120
|
+
if (tool !== void 0 && !TOOL_NAME.test(tool)) throw new TypeError(`Name an MCP tool in snake_case, such as get_task: ${tool}`);
|
|
121
|
+
const segments = routeSegments(path);
|
|
122
|
+
const routePath = projectPath(segments.join("/"), "routes");
|
|
123
|
+
operationPathParameters(routePath);
|
|
124
|
+
for (const { name, file } of projectFiles(root, "routes", "development")) {
|
|
125
|
+
const suffix = /\.(get|post|put|patch|delete)$/.exec(name);
|
|
126
|
+
if (suffix?.[1] === verb && routeShape(projectPath(name.slice(0, -suffix[0].length), "routes")) === routeShape(routePath)) throw new TypeError(`${relative(root, file)} already answers ${verb.toUpperCase()} ${routePath}.`);
|
|
127
|
+
}
|
|
128
|
+
const folder = join("routes", ...segments);
|
|
129
|
+
const file = existsSync(join(root, folder)) ? join(folder, `index.${verb}.ts`) : `${folder}.${verb}.ts`;
|
|
130
|
+
const parameters = segments.flatMap((segment) => segment.startsWith("[") ? [segment.slice(1, -1)] : []);
|
|
131
|
+
const call = `${verb.toUpperCase()} ${API_BASE_PATH}${routePath}`;
|
|
132
|
+
const exposure = tool ? `${call}, also the MCP tool ${tool}` : call;
|
|
133
|
+
return {
|
|
134
|
+
file: writeModule(root, file, [
|
|
135
|
+
`import { defineHandler${parameters.length ? ", t" : ""} } from '@arbol-ai/maximus';`,
|
|
136
|
+
"",
|
|
137
|
+
...jsDoc(`${exposure}: what it answers, in a few words.`),
|
|
138
|
+
...routeDeclaration(call, parameters, tool),
|
|
139
|
+
""
|
|
140
|
+
].join("\n")),
|
|
141
|
+
method: verb.toUpperCase(),
|
|
142
|
+
path: routePath
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* A route's `defineHandler` call: a placeholder handler that answers its path parameters back, and a
|
|
147
|
+
* contract whose description says what to write there. A route without parameters takes and answers nothing.
|
|
148
|
+
*/
|
|
149
|
+
function routeDeclaration(call, parameters, tool) {
|
|
150
|
+
const indent = parameters.length ? " " : " ";
|
|
151
|
+
const fields = parameters.map((parameter) => `${parameter}: t.String()`);
|
|
152
|
+
const contract = [
|
|
153
|
+
...textField(indent, "description", `Write one sentence that tells callers what ${call} does.`),
|
|
154
|
+
...fields.length ? braces(indent, "input: ", fields, ",") : [],
|
|
155
|
+
...fields.length ? braces(indent, "output: ", fields, ",") : [],
|
|
156
|
+
...tool ? [`${indent}mcp: { name: '${tool}' },`] : []
|
|
157
|
+
];
|
|
158
|
+
if (!parameters.length) return [
|
|
159
|
+
"export default defineHandler(() => {}, {",
|
|
160
|
+
...contract,
|
|
161
|
+
"});"
|
|
162
|
+
];
|
|
163
|
+
return [
|
|
164
|
+
"export default defineHandler(",
|
|
165
|
+
...echoHandler(parameters),
|
|
166
|
+
" {",
|
|
167
|
+
...contract,
|
|
168
|
+
" }",
|
|
169
|
+
");"
|
|
170
|
+
];
|
|
171
|
+
}
|
|
172
|
+
/** Writes `mcp/tools/<name>.ts`, an MCP tool only agents call, named `<name>` in snake_case. */
|
|
173
|
+
function generateTool(directory, name) {
|
|
174
|
+
if (!TOOL.test(name)) throw new TypeError(`Name a tool file in kebab-case, such as summarize-tasks: ${name}`);
|
|
175
|
+
const tool = name.replaceAll("-", "_");
|
|
176
|
+
const text = [
|
|
177
|
+
"import { defineTool, t } from '@arbol-ai/maximus';",
|
|
178
|
+
"",
|
|
179
|
+
...jsDoc(`The MCP tool ${tool}, which no HTTP route serves: what it answers, in a few words.`),
|
|
180
|
+
"export default defineTool(",
|
|
181
|
+
...echoHandler(["text"]),
|
|
182
|
+
" {",
|
|
183
|
+
...textField(" ", "description", `Write one sentence that tells agents what ${tool} does.`),
|
|
184
|
+
" effect: 'read',",
|
|
185
|
+
" input: { text: t.String({ maxLength: 1000 }) },",
|
|
186
|
+
" output: { text: t.String() },",
|
|
187
|
+
" }",
|
|
188
|
+
");",
|
|
189
|
+
""
|
|
190
|
+
].join("\n");
|
|
191
|
+
return {
|
|
192
|
+
file: writeModule(resolve(directory), join("mcp", "tools", `${name}.ts`), text),
|
|
193
|
+
tool
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export { generateRoute, generateTool };
|
|
@@ -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 };
|