@arbol-ai/maximus 7.3.1 → 7.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 (55) hide show
  1. package/dist/analytics/analytics.d.ts +1 -1
  2. package/dist/body.d.ts +1 -1
  3. package/dist/chunks/builder-BiXv7d2v.js +100 -0
  4. package/dist/chunks/{execution-B-yy4C7N.js → define-app-DvD_1jUE.js} +5 -71
  5. package/dist/chunks/errors-D7zG9kx9.js +126 -0
  6. package/dist/chunks/execution-kVUJPy1A.js +71 -0
  7. package/dist/chunks/http-paths-yKD6TSNJ.js +199 -0
  8. package/dist/chunks/prepare-project-CMyGSEtI.js +236 -0
  9. package/dist/chunks/prepare-project-MtS0-W_n.js +3 -0
  10. package/dist/chunks/{runtime-BPnaa-NK.js → runtime-DlqA7J38.js} +4 -3
  11. package/dist/chunks/{src-DPSpGNnT.js → src-N3oyx5QF.js} +31 -104
  12. package/dist/chunks/standard-failures-CLjxS2ea.js +74 -0
  13. package/dist/chunks/{types-BWxDd3tY.d.ts → types-DQdfRF3f.d.ts} +13 -4
  14. package/dist/client/client.d.ts +1 -1
  15. package/dist/client/client.js +2 -2
  16. package/dist/diagnostics.d.ts +1 -1
  17. package/dist/errors.d.ts +1 -1
  18. package/dist/errors.js +1 -124
  19. package/dist/http-paths.d.ts +1 -1
  20. package/dist/http-paths.js +1 -197
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.js +5 -4
  23. package/dist/internals.d.ts +1 -1
  24. package/dist/internals.js +3 -2
  25. package/dist/mcp/index.d.ts +1 -1
  26. package/dist/mcp/index.js +3 -3
  27. package/dist/project/config.d.ts +101 -0
  28. package/dist/project/config.js +80 -0
  29. package/dist/project/index.d.ts +1 -1
  30. package/dist/project/index.js +3 -3
  31. package/dist/schemas.d.ts +1 -1
  32. package/dist/standard-failures.js +1 -72
  33. package/dist/tooling/cli.js +10 -10
  34. package/dist/tooling/vite.d.ts +1 -1
  35. package/dist/tooling/vite.js +38 -25
  36. package/dist/webhooks.d.ts +1 -1
  37. package/dist/workers/runtime.d.ts +1 -1
  38. package/dist/workers/runtime.js +1 -1
  39. package/package.json +5 -1
  40. package/skills/maximus/SKILL.md +4 -5
  41. package/skills/maximus/references/building-a-service.md +8 -8
  42. package/skills/maximus/references/publishing-and-verification.md +14 -11
  43. package/templates/project/.agents/skills/project/SKILL.md.template +7 -7
  44. package/templates/project/CLAUDE.md.template +10 -7
  45. package/templates/project/README.md.template +8 -7
  46. package/templates/project/cloudflare.config.ts.template +1 -1
  47. package/templates/project/{src/application.ts.template → maximus.config.ts.template} +4 -10
  48. package/templates/project/middleware/10-response.ts.template +13 -0
  49. package/templates/project/package.json.template +4 -0
  50. package/templates/project/routes/v1/greeting.ts.template +33 -17
  51. package/templates/project/tsconfig.json.template +1 -0
  52. package/dist/chunks/prepare-project-zi106pWF.js +0 -146
  53. package/templates/project/src/app.ts.template +0 -2
  54. package/templates/project/src/index.ts.template +0 -3
  55. package/templates/project/src/worker.ts.template +0 -6
@@ -0,0 +1,236 @@
1
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
2
+ import { join, relative, resolve, sep } from "node:path";
3
+ import { parseSync } from "vite";
4
+
5
+ // src/tooling/internal/project-exports.ts
6
+ /** Read public export names with Oxc, without importing or executing application modules. */
7
+ const ROUTE_METHODS = [
8
+ "GET",
9
+ "POST",
10
+ "PUT",
11
+ "PATCH",
12
+ "DELETE"
13
+ ];
14
+ /** Refuse direct runtime import cycles and workerd-only imports in application configuration. */
15
+ function readProjectModule(file, role) {
16
+ const parsed = parseSync(file, readFileSync(file, "utf-8"));
17
+ if (parsed.errors.length) throw new TypeError(`Cannot discover ${file}: ${parsed.errors[0]?.message}`);
18
+ for (const node of parsed.program.body) {
19
+ let source;
20
+ if (node.type === "ImportDeclaration" && node.importKind !== "type") {
21
+ if (node.specifiers.length === 0 || node.specifiers.some((specifier) => specifier.type !== "ImportSpecifier" || specifier.importKind !== "type")) source = node.source.value;
22
+ } else if ((node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") && node.exportKind !== "type") source = node.source?.value;
23
+ if (!source) continue;
24
+ const generated = /(?:\.maximus\/|#maximus\/)([^/.?#]+)/.exec(source)?.[1];
25
+ if (generated && (role === "config" || [
26
+ "app",
27
+ "worker",
28
+ "entry"
29
+ ].includes(generated) || role === "middleware" && ["base", "routes"].includes(generated))) throw new TypeError(`Runtime import ${source} creates a generated-module cycle in ${file}. Use a type-only import or shared domain module.`);
30
+ if (role === "config" && (source.startsWith("cloudflare:") || /^@arbol-ai\/maximus\/(?:workers|project)$/.test(source))) throw new TypeError(`Configuration must remain importable outside workerd: ${source} in ${file}. Import its types only.`);
31
+ }
32
+ return parsed;
33
+ }
34
+ /** Explicit exports make discovery reproducible; wildcard re-exports have no locally owned method set. */
35
+ function routeExports(file) {
36
+ const parsed = readProjectModule(file, "route");
37
+ const names = /* @__PURE__ */ new Set();
38
+ for (const statement of parsed.module.staticExports) for (const entry of statement.entries) {
39
+ if (entry.isType) continue;
40
+ const name = entry.exportName.kind === "Default" ? "default" : entry.exportName.name;
41
+ if (!name) throw new TypeError(`Route modules require explicit exports, not export *: ${file}`);
42
+ names.add(name);
43
+ }
44
+ const methods = ROUTE_METHODS.filter((method) => names.has(method));
45
+ if (names.has("default")) {
46
+ if (methods.length) throw new TypeError(`Choose a default route factory or named method exports, not both: ${file}`);
47
+ return {
48
+ legacy: true,
49
+ methods: []
50
+ };
51
+ }
52
+ const unsupported = [...names].filter((name) => !ROUTE_METHODS.some((method) => method === name));
53
+ if (!methods.length || unsupported.length) throw new TypeError(`Route ${file} must export GET, POST, PUT, PATCH or DELETE. Keep helpers private or in _files.`);
54
+ return {
55
+ legacy: false,
56
+ methods
57
+ };
58
+ }
59
+
60
+ // src/tooling/internal/project-files.ts
61
+ /** Deterministic source discovery. Only ordinary source files inside opted-in directories are loaded. */
62
+ /** Project-owned convention directories; infrastructure remains in cloudflare.config.ts. */
63
+ const PROJECT_DIRECTORIES = [
64
+ "routes",
65
+ "pages",
66
+ "middleware",
67
+ "crons",
68
+ "queues",
69
+ "email",
70
+ "durable-objects"
71
+ ];
72
+ /** Sort by code units so generated imports are identical on every locale and platform. */
73
+ function compareNames(a, b) {
74
+ return a < b ? -1 : Number(a > b);
75
+ }
76
+ /** Discover without following symlinks or importing user code into the build host. */
77
+ function projectFiles(root, directory, mode) {
78
+ const folder = resolve(root, directory);
79
+ if (!existsSync(folder)) return [];
80
+ if (lstatSync(folder).isSymbolicLink()) throw new TypeError(`Project directory cannot be a symlink: ${directory}`);
81
+ const files = [];
82
+ function visit(current) {
83
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
84
+ if (entry.name.startsWith(".") || entry.name.startsWith("_") && !(directory === "email" && entry.name.startsWith("_default."))) continue;
85
+ const file = join(current, entry.name);
86
+ if (entry.isSymbolicLink()) throw new TypeError(`Project modules cannot be symlinks: ${relative(root, file)}`);
87
+ if (entry.isDirectory()) visit(file);
88
+ else if (entry.isFile() && /\.(?:[cm]?ts|tsx|[cm]?js|jsx)$/.test(entry.name) && !/\.(?:d|test|spec)(?:\.(?:dev|prod))?\.[^.]+$/.test(entry.name)) {
89
+ const name = relative(folder, file).split(sep).join("/").replace(/\.[^.]+$/, "");
90
+ const environment = /\.(dev|prod)$/.exec(name)?.[1];
91
+ if (environment && (environment === "dev" ? mode !== "development" : mode !== "production")) continue;
92
+ files.push({
93
+ file,
94
+ name: name.replace(/\.(?:dev|prod)$/, "")
95
+ });
96
+ }
97
+ }
98
+ }
99
+ visit(folder);
100
+ files.sort((a, b) => compareNames(a.file, b.file));
101
+ return files;
102
+ }
103
+ /** Convert groups, index files and dynamic operation segments into a native Maximus path. */
104
+ function projectPath(name, kind) {
105
+ const segments = name.split("/").filter((segment) => !/^\([a-zA-Z0-9_-]+\)$/.test(segment));
106
+ if (segments.at(-1) === "index") segments.pop();
107
+ const path = `/${segments.map((segment) => {
108
+ const parameter = /^\[([a-zA-Z][a-zA-Z0-9_]*)\]$/.exec(segment)?.[1];
109
+ if (parameter && kind === "routes") return `{${parameter}}`;
110
+ if (!/^[a-zA-Z0-9_-]+$/.test(segment)) throw new TypeError(`Unsupported ${kind} segment: ${segment}. Pages use fixed paths; operations support [parameter].`);
111
+ return segment;
112
+ }).join("/")}`;
113
+ if (kind === "routes" && !/^\/v[1-9][0-9]*\/.+/.test(path)) throw new TypeError(`Operation file must live below routes/v1/ (or another version): ${name}`);
114
+ return path;
115
+ }
116
+
117
+ // src/tooling/internal/prepare-project.ts
118
+ /** Build-time source generation preserves each operation's literal type and keeps filesystem code out of Workers. */
119
+ /** Generate only owned modules; a failed discovery never replaces the previous output. */
120
+ function prepareProject(directory, mode = "production") {
121
+ const root = resolve(directory);
122
+ const configs = [
123
+ "maximus.config.ts",
124
+ "maximus.config.mts",
125
+ "maximus.config.js",
126
+ "maximus.config.mjs"
127
+ ].filter((name) => existsSync(join(root, name)));
128
+ if (configs.length > 1) throw new TypeError("Keep exactly one maximus.config module at the project root.");
129
+ const [config] = configs;
130
+ if (config && lstatSync(join(root, config)).isSymbolicLink()) throw new TypeError("The Maximus configuration cannot be a symlink.");
131
+ for (const required of config ? [] : ["src/application.ts", "src/worker.ts"]) if (!existsSync(join(root, required))) throw new TypeError(`Add maximus.config.ts, or keep the legacy ${required}. Create a project with maximus init --layout project.`);
132
+ const output = join(root, ".maximus");
133
+ if (existsSync(output) && lstatSync(output).isSymbolicLink()) throw new TypeError("The generated .maximus directory cannot be a symlink.");
134
+ const files = Object.fromEntries(PROJECT_DIRECTORIES.map((name) => [name, projectFiles(root, name, mode)]));
135
+ if (config) readProjectModule(join(root, config), "config");
136
+ for (const { file } of files.middleware ?? []) readProjectModule(file, "middleware");
137
+ const header = `// Generated by maximus prepare (${mode}). Edit the source modules, not this file.\n`;
138
+ const imports = [];
139
+ const source = (file) => JSON.stringify(relative(output, file).split(sep).join("/"));
140
+ const register = (kind) => (files[kind] ?? []).map((file, index) => {
141
+ const identifier = `${kind.replaceAll("-", "_")}_${index}`;
142
+ imports.push(`import ${identifier} from ${source(file.file)};`);
143
+ return {
144
+ ...file,
145
+ identifier
146
+ };
147
+ });
148
+ const occupied = /* @__PURE__ */ new Set();
149
+ const mounts = (files.routes ?? []).flatMap(({ name, file }, index) => {
150
+ const path = projectPath(name, "routes");
151
+ if (occupied.has(path)) throw new TypeError(`Multiple route files claim ${path}; put its methods in one module.`);
152
+ occupied.add(path);
153
+ const identifier = `routes_${index}`;
154
+ const exports = routeExports(file);
155
+ if (exports.legacy) {
156
+ imports.push(`import ${identifier} from ${source(file)};`);
157
+ return [`.mount(${identifier}(${JSON.stringify(path)}))`];
158
+ }
159
+ imports.push(`import * as ${identifier} from ${source(file)};`);
160
+ return exports.methods.map((method) => `.mount(${identifier}.${method}(${JSON.stringify(path)}, ${JSON.stringify(method)}))`);
161
+ });
162
+ const application = `${header}import { checkProjectPipeline } from '@arbol-ai/maximus/config';\nimport { base } from './base.ts';\n${imports.join("\n")}\nexport const app = checkProjectPipeline(base, base${mounts.join("")}.build());\n`;
163
+ imports.length = 0;
164
+ const middleware = register("middleware");
165
+ const middlewareSource = `${header}import { collectMiddleware } from '@arbol-ai/maximus/config';\n${imports.join("\n")}\nexport const { middleware, requestMiddleware } = collectMiddleware([${middleware.map(({ identifier }) => identifier).join(", ")}] as const);\n`;
166
+ const baseSource = config ? `${header}import config from '../${config}';\nimport { useProjectMiddleware } from '@arbol-ai/maximus/config';\nimport { middleware } from './middleware.ts';\nexport const base: typeof config.application = useProjectMiddleware(config.application, middleware);\n` : `${header}export { base } from '../src/application.ts';\n`;
167
+ const routeSource = `${header}import { createRoute } from '@arbol-ai/maximus/config';\nimport { base } from './base.ts';\nexport const defineRoute = createRoute(base);\n`;
168
+ imports.length = 0;
169
+ const pages = register("pages");
170
+ const pagePaths = /* @__PURE__ */ new Set();
171
+ const pageEntries = pages.map(({ name, identifier }) => {
172
+ const path = projectPath(name, "pages");
173
+ if (pagePaths.has(path)) throw new TypeError(`Multiple page files claim ${path}.`);
174
+ pagePaths.add(path);
175
+ return `${JSON.stringify(path)}: ${identifier}`;
176
+ });
177
+ const crons = (files.crons ?? []).map(({ file }, index) => {
178
+ imports.push(`import cron_${index}, { cron as schedule_${index} } from ${source(file)};`);
179
+ return `{ cron: schedule_${index}, handler: cron_${index} }`;
180
+ });
181
+ const eventEntries = (kind) => {
182
+ const keys = /* @__PURE__ */ new Set();
183
+ return register(kind).map(({ name, identifier }) => {
184
+ if (name.includes("/") || keys.has(name)) throw new TypeError(`${kind} modules require distinct top-level names: ${name}`);
185
+ keys.add(name);
186
+ return `${JSON.stringify(name)}: ${identifier}`;
187
+ });
188
+ };
189
+ const queues = eventEntries("queues");
190
+ const email = eventEntries("email");
191
+ const classes = /* @__PURE__ */ new Set(["Service"]);
192
+ const durableObjects = register("durable-objects").map(({ name, identifier }) => {
193
+ if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name)) throw new TypeError(`Durable Object filenames must be top-level kebab-case names: ${name}`);
194
+ const className = name.split("-").map((part) => part[0]?.toUpperCase() + part.slice(1)).join("");
195
+ if (classes.has(className)) throw new TypeError(`Duplicate Worker export: ${className}`);
196
+ classes.add(className);
197
+ return `export const ${className} = worker.durableObject(${identifier});`;
198
+ });
199
+ const worker = `${header}import { createProjectWorker } from '@arbol-ai/maximus/project';\nimport type { WorkerRuntime } from '@arbol-ai/maximus/workers';\nimport type { ProjectEnv } from '@arbol-ai/maximus/config';\nimport type { base } from './base.ts';\nimport { app } from './app.ts';\n${config ? `import config from '../${config}';\nconst options = config.worker;` : "import { options } from '../src/worker.ts';"}\nimport { requestMiddleware } from './middleware.ts';\n${imports.join("\n")}\nconst worker: WorkerRuntime<${config ? "ProjectEnv<typeof config>" : "Parameters<typeof base.definition.context>[0]['env']"}, typeof app.operations> = createProjectWorker(app, { pages: { ${pageEntries.join(", ")} }, crons: [${crons.join(", ")}], queues: { ${queues.join(", ")} }, email: { ${email.join(", ")} } }, { ...options, http: { ...options.http, middleware: [...(options.http?.middleware ?? []), ...requestMiddleware] } });\nexport default worker.handler;\nexport const Service = worker.entrypoint;\n${durableObjects.join("\n")}\n`;
200
+ mkdirSync(output, { recursive: true });
201
+ const generated = {
202
+ "middleware.ts": middlewareSource,
203
+ "base.ts": baseSource,
204
+ "routes.ts": routeSource,
205
+ "app.ts": application,
206
+ "worker.ts": worker,
207
+ "entry.ts": "// Generated by maximus prepare. Stable Cloudflare entrypoint.\nexport { default } from './worker.ts';\nexport * from './worker.ts';\n"
208
+ };
209
+ for (const name of Object.keys(generated)) {
210
+ const target = join(output, name);
211
+ if (existsSync(target) && (lstatSync(target).isSymbolicLink() || !lstatSync(target).isFile())) throw new TypeError(`Generated files must be ordinary files: ${name}`);
212
+ }
213
+ let changed = false;
214
+ for (const [name, content] of Object.entries(generated)) {
215
+ const target = join(output, name);
216
+ if (existsSync(target) && lstatSync(target).isSymbolicLink()) throw new TypeError(`Generated files cannot be symlinks: ${name}`);
217
+ if (!existsSync(target) || readFileSync(target, "utf-8") !== content) {
218
+ changed = true;
219
+ const temporary = `${target}.${process.pid}.tmp`;
220
+ writeFileSync(temporary, content, { flag: "wx" });
221
+ renameSync(temporary, target);
222
+ }
223
+ }
224
+ return {
225
+ directory: root,
226
+ mode,
227
+ layout: config ? "config" : "legacy",
228
+ changed,
229
+ config,
230
+ durableObjects: files["durable-objects"]?.map(({ file }) => file) ?? [],
231
+ files: Object.values(files).flat().map(({ file }) => file),
232
+ modules: Object.fromEntries(Object.entries(files).map(([kind, entries]) => [kind, entries.length]))
233
+ };
234
+ }
235
+
236
+ export { PROJECT_DIRECTORIES as n, prepareProject as t };
@@ -0,0 +1,3 @@
1
+ import { t as prepareProject } from "./prepare-project-CMyGSEtI.js";
2
+
3
+ export { prepareProject };
@@ -1,9 +1,10 @@
1
1
  import { r as parseInput } from "./validation-r-sgmsqb.js";
2
2
  import { r as isRequestId } from "./correlation-BEkcFFGT.js";
3
- import { standardErrors } from "../errors.js";
4
- import { d as err, p as ok, r as PrincipalSchema, t as executeOperation } from "./execution-B-yy4C7N.js";
5
- import { r as createHttpHandler } from "./src-DPSpGNnT.js";
3
+ import { i as standardErrors } from "./errors-D7zG9kx9.js";
4
+ import { f as ok, n as PrincipalSchema, u as err } from "./define-app-DvD_1jUE.js";
5
+ import { r as createHttpHandler } from "./src-N3oyx5QF.js";
6
6
  import { a as telemetryEnabled, r as recordExecution, s as withTelemetry } from "./telemetry-BTwB68m5.js";
7
+ import { t as executeOperation } from "./execution-kVUJPy1A.js";
7
8
  import { DurableObject, WorkerEntrypoint, tracing } from "cloudflare:workers";
8
9
 
9
10
  // src/workers/assets.ts
@@ -1,110 +1,14 @@
1
- import { FailureSchema, standardErrors } from "../errors.js";
1
+ import { i as standardErrors, t as FailureSchema } from "./errors-D7zG9kx9.js";
2
2
  import { r as readBodyText } from "./body-6LichrQm.js";
3
3
  import { t as isRecord } from "./record-DY-lX9w1.js";
4
- import { C as operationMatchesScopes, D as pathParameterSchemas, O as attachmentResponse, S as operationBodyLimit, T as operationScopes, _ as STANDARD_CODES, b as mcpOpenWorld, c as tokenEndpoints, d as err, h as DEFAULT_MAX_BODY_BYTES, i as createTokenAuthorization, k as binaryBody, l as tokenIssuer, m as sha256Hex, n as defineApp, p as ok, s as tokenAudiences, t as executeOperation, u as usesOwnBearer, v as composeOperations, w as operationOutputLimit, y as isPublicOperation } from "./execution-B-yy4C7N.js";
5
- import { createHttpRouteResolver, operationPathParameters } from "../http-paths.js";
4
+ import { C as operationOutputLimit, D as attachmentResponse, E as pathParameterSchemas, O as binaryBody, S as operationMatchesScopes, c as tokenIssuer, f as ok, g as STANDARD_CODES, l as usesOwnBearer, m as DEFAULT_MAX_BODY_BYTES, o as tokenAudiences, p as sha256Hex, r as createTokenAuthorization, s as tokenEndpoints, u as err, v as isPublicOperation, w as operationScopes, x as operationBodyLimit, y as mcpOpenWorld } from "./define-app-DvD_1jUE.js";
5
+ import { a as operationPathParameters, t as createHttpRouteResolver } from "./http-paths-yKD6TSNJ.js";
6
6
  import { a as telemetryEnabled, i as reportUnexpected, n as recordAdmission, r as recordExecution, s as withTelemetry } from "./telemetry-BTwB68m5.js";
7
+ import { t as executeOperation } from "./execution-kVUJPy1A.js";
7
8
  import { n as mediaType } from "./json-Bu4BLT25.js";
8
9
  import { Type, Type as Type$1, Type as t } from "@sinclair/typebox";
9
10
  import { stringify } from "yaml";
10
11
 
11
- // src/builder.ts
12
- /** Immutable builders let independent resource modules share inferred context without overwriting routes. */
13
- var ApplicationBuilder = class ApplicationBuilder {
14
- /**
15
- * The application declared so far: its configuration, context preparation, middleware and operations, which
16
- * `.build()` checks.
17
- */
18
- definition;
19
- root;
20
- constructor(definition, root = definition) {
21
- this.definition = definition;
22
- this.root = root;
23
- }
24
- /**
25
- * Declares an operation: a camelCase name no other operation uses, its definition (scope, words, effect,
26
- * schemas and exposure) and its handler, which receives the prepared context and the decoded input and
27
- * returns a Result.
28
- */
29
- operation(name, definition, execute) {
30
- const operations = composeOperations(this.definition.operations, { [name]: {
31
- ...definition,
32
- execute,
33
- pipeline: {
34
- context: (invocation) => this.definition.context({
35
- ...invocation,
36
- operation: name
37
- }),
38
- middleware: this.definition.middleware ?? []
39
- }
40
- } });
41
- return new ApplicationBuilder({
42
- ...this.definition,
43
- operations
44
- }, this.root);
45
- }
46
- /**
47
- * Adds what `resolve` returns to the context of every operation declared after it. It runs after admission
48
- * and before the middleware; a failure it returns answers the call. Derive before declaring operations.
49
- */
50
- derive(resolve) {
51
- if (Object.keys(this.definition.operations).length) throw new TypeError("Derive context before declaring operations.");
52
- const previous = this.definition.context;
53
- return new ApplicationBuilder({
54
- ...this.definition,
55
- context: async (invocation) => {
56
- const context = await previous(invocation);
57
- if (!context.ok) return context;
58
- const derived = await resolve(context.value);
59
- return derived.ok ? ok({
60
- ...context.value,
61
- ...derived.value
62
- }) : derived;
63
- }
64
- }, this.root);
65
- }
66
- /**
67
- * Wraps every operation declared after it, once the caller is admitted and the context prepared. The
68
- * middleware calls `next` at most once.
69
- */
70
- use(middleware) {
71
- return new ApplicationBuilder({
72
- ...this.definition,
73
- middleware: [...this.definition.middleware ?? [], middleware]
74
- }, this.root);
75
- }
76
- /**
77
- * Adds the operations of a resource module built from the same application; each keeps the context and
78
- * middleware it was declared with.
79
- */
80
- mount(module) {
81
- if (this.root !== module.root) throw new TypeError("Resource groups must derive from the same application.");
82
- return new ApplicationBuilder({
83
- ...this.definition,
84
- operations: composeOperations(this.definition.operations, module.definition.operations)
85
- }, this.root);
86
- }
87
- /**
88
- * Checks every rule the application must keep and returns it. A refusal is a TypeError that names the rule
89
- * and the operation that breaks it.
90
- */
91
- build() {
92
- return defineApp()(this.definition);
93
- }
94
- };
95
- /**
96
- * Starts an application: its name, scope namespace, origin, token policy, error catalog and RPC callers.
97
- * Chain `.derive()` and `.use()` to prepare each call, `.operation()` to declare operations, `.mount()` to
98
- * compose resource modules that share this base, then `.build()`.
99
- */
100
- function maximus(configuration) {
101
- return new ApplicationBuilder({
102
- ...configuration,
103
- operations: {},
104
- context: (invocation) => Promise.resolve(ok(invocation))
105
- });
106
- }
107
-
108
12
  // src/oauth.ts
109
13
  /** A scope token as RFC 6749 defines it: printable ASCII without spaces, quotes or backslashes. */
110
14
  const SCOPE = /^[\u0021\u0023-\u005B\u005D-\u007E]+$/;
@@ -782,6 +686,7 @@ function createHttpHandler(manifest, hooks = {}) {
782
686
  const url = new URL(origin);
783
687
  return url.protocol !== "https:" || url.origin !== origin;
784
688
  }))) throw new TypeError("HTTP origins must be exact HTTPS origins.");
689
+ for (const middleware of hooks.middleware ?? []) if (typeof middleware !== "function") throw new TypeError("Every HTTP middleware entry must be a function.");
785
690
  const paths = nativePaths(manifest.tokens, hooks);
786
691
  const authorize = createTokenAuthorization(manifest.tokens, hooks.verify);
787
692
  const operations = Object.entries(manifest.operations);
@@ -931,9 +836,8 @@ function createHttpHandler(manifest, hooks = {}) {
931
836
  * Routes the request: origin pinning, the `before` hook, plain routes and mounts, liveness and discovery
932
837
  * documents, then an operation or a transport, else the fallback or NOT_FOUND.
933
838
  */
934
- async function dispatch() {
839
+ async function dispatchNative() {
935
840
  const url = new URL(incoming.url);
936
- if (hooks.origins && !hooks.origins.includes(url.origin)) return reject(standardErrors.notFound.create());
937
841
  if (hooks.before) {
938
842
  plain = true;
939
843
  const response = await hooks.before(incoming, env, context);
@@ -1099,7 +1003,30 @@ function createHttpHandler(manifest, hooks = {}) {
1099
1003
  }
1100
1004
  let response;
1101
1005
  try {
1102
- response = await dispatch();
1006
+ if (hooks.origins && !hooks.origins.includes(new URL(incoming.url).origin)) response = reject(standardErrors.notFound.create());
1007
+ else {
1008
+ const dispatch = async (index) => {
1009
+ const middleware = hooks.middleware?.[index];
1010
+ if (!middleware) return dispatchNative();
1011
+ let invoked = false;
1012
+ let active = true;
1013
+ const requestView = new Request(incoming.url, {
1014
+ method: incoming.method,
1015
+ headers: new Headers(incoming.headers),
1016
+ signal: incoming.signal
1017
+ });
1018
+ try {
1019
+ return await middleware(requestView, env, context, () => {
1020
+ if (invoked || !active) throw new TypeError("An HTTP middleware continuation may run only once before its wrapper settles.");
1021
+ invoked = true;
1022
+ return dispatch(index + 1);
1023
+ });
1024
+ } finally {
1025
+ active = false;
1026
+ }
1027
+ };
1028
+ response = await dispatch(0);
1029
+ }
1103
1030
  } catch (error) {
1104
1031
  reportUnexpected(error, plain ? "route" : "http", requestId);
1105
1032
  response = plain ? failure(standardErrors.internal.create(), requestId, resolutionContext()) : reject(standardErrors.internal.create());
@@ -1161,4 +1088,4 @@ function operationInput(route, request, url, bodyText) {
1161
1088
  });
1162
1089
  }
1163
1090
 
1164
- export { canonical as a, nativePaths as c, maximus as d, createOpenApi as i, ownsPrefix as l, t as n, standaloneSchema as o, createHttpHandler as r, VERSIONED_PATH as s, Type$1 as t, protectedResourceMetadata as u };
1091
+ export { canonical as a, nativePaths as c, createOpenApi as i, ownsPrefix as l, t as n, standaloneSchema as o, createHttpHandler as r, VERSIONED_PATH as s, Type$1 as t, protectedResourceMetadata as u };
@@ -0,0 +1,74 @@
1
+ // src/standard-failures.ts
2
+ /** The framework's own failures, by the name `standardErrors` gives each. */
3
+ const STANDARD_FAILURES = {
4
+ invalidInput: {
5
+ code: "INVALID_INPUT",
6
+ status: 400,
7
+ message: "The request does not match the published schema."
8
+ },
9
+ unauthorized: {
10
+ code: "UNAUTHORIZED",
11
+ status: 401,
12
+ message: "A valid access token is required."
13
+ },
14
+ forbidden: {
15
+ code: "FORBIDDEN",
16
+ status: 403,
17
+ message: "The token does not authorize this operation."
18
+ },
19
+ notFound: {
20
+ code: "NOT_FOUND",
21
+ status: 404,
22
+ message: "The requested operation does not exist."
23
+ },
24
+ methodNotAllowed: {
25
+ code: "HTTP_METHOD_NOT_ALLOWED",
26
+ status: 405,
27
+ message: "The HTTP method is not supported for this resource."
28
+ },
29
+ tooLarge: {
30
+ code: "REQUEST_TOO_LARGE",
31
+ status: 413,
32
+ message: "The request exceeds the allowed size."
33
+ },
34
+ unsupportedMedia: {
35
+ code: "UNSUPPORTED_MEDIA_TYPE",
36
+ status: 415,
37
+ message: "The request content type is not supported."
38
+ },
39
+ rateLimited: {
40
+ code: "RATE_LIMITED",
41
+ status: 429,
42
+ message: "The request rate limit was exceeded. Try again later.",
43
+ retryable: true,
44
+ retryAfter: 60
45
+ },
46
+ internal: {
47
+ code: "INTERNAL_ERROR",
48
+ status: 500,
49
+ message: "The service could not complete the operation."
50
+ },
51
+ upstreamUnavailable: {
52
+ code: "UPSTREAM_UNAVAILABLE",
53
+ status: 503,
54
+ message: "The upstream service could not complete the request.",
55
+ retryable: true
56
+ },
57
+ upstreamTimeout: {
58
+ code: "UPSTREAM_TIMEOUT",
59
+ status: 504,
60
+ message: "The upstream service did not respond before its deadline.",
61
+ retryable: true
62
+ },
63
+ /**
64
+ * A write may have been applied and its answer was lost. Never retried: the caller reconciles (reads
65
+ * the resource or polls the operation) before deciding to repeat anything.
66
+ */
67
+ outcomeUnknown: {
68
+ code: "OUTCOME_UNKNOWN",
69
+ status: 502,
70
+ message: "The operation may have been applied; check its result before repeating it."
71
+ }
72
+ };
73
+
74
+ export { STANDARD_FAILURES as t };
@@ -986,12 +986,13 @@ type DistinctOperations<Ops, M> = [Extract<keyof M, keyof Ops>] extends [never]
986
986
  readonly 'Operations declared twice': Extract<keyof M, keyof Ops>;
987
987
  };
988
988
  /** An operation's definition as `.operation()` takes it: its scope, exposure, words, schemas and limits. */
989
- type Definition<I extends TSchema, O extends TSchema, X extends Exposure> = X & Omit<OperationShape, keyof Exposure | 'input' | 'output' | 'execute' | 'pipeline'> & {
989
+ type OperationFields<I extends TSchema, O extends TSchema> = Omit<OperationShape, keyof Exposure | 'input' | 'output' | 'execute' | 'pipeline'> & {
990
990
  input: I;
991
991
  output: O;
992
992
  };
993
+ type Definition<I extends TSchema, O extends TSchema, X extends Exposure> = X & OperationFields<I, O>;
993
994
  /** Refuses a definition field no operation has, such as a misspelled one, which would otherwise do nothing. */
994
- type KnownFields<X> = Readonly<Record<Exclude<keyof X, keyof OperationShape>, never>>;
995
+ type KnownOperationFields<X> = Readonly<Record<Exclude<keyof X, keyof OperationShape>, never>>;
995
996
  /** Immutable builders let independent resource modules share inferred context without overwriting routes. */
996
997
  declare class ApplicationBuilder<E, C, Ops extends Record<string, OperationShape>> {
997
998
  /**
@@ -1006,7 +1007,7 @@ declare class ApplicationBuilder<E, C, Ops extends Record<string, OperationShape
1006
1007
  * schemas and exposure) and its handler, which receives the prepared context and the decoded input and
1007
1008
  * returns a Result.
1008
1009
  */
1009
- operation<const N extends string, I extends TSchema, O extends TSchema, const X extends Exposure>(name: N extends keyof Ops ? never : N, definition: Definition<I, O, X> & KnownFields<X>, execute: (context: C & (X extends {
1010
+ operation<const N extends string, I extends TSchema, O extends TSchema, const X extends Exposure>(name: N extends keyof Ops ? never : N, definition: Definition<I, O, X> & KnownOperationFields<X>, execute: (context: C & (X extends {
1010
1011
  http: {
1011
1012
  body: 'bytes';
1012
1013
  };
@@ -1432,11 +1433,19 @@ interface RouteContext {
1432
1433
  * receive a principal and are absent from OpenAPI.
1433
1434
  */
1434
1435
  type HttpRoute<E> = (request: Request, env: E, context: RouteContext) => Promise<Response>;
1436
+ /**
1437
+ * Wraps HTTP before token admission. The request is a bodyless metadata copy, so a wrapper cannot
1438
+ * consume unbounded input or mutate the headers native admission reads. No principal is available;
1439
+ * `next` keeps the existing pipeline and may run only once before the wrapper settles.
1440
+ */
1441
+ type HttpMiddleware<E> = (request: Request, env: E, context: RouteContext, next: () => Promise<Response>) => Promise<Response>;
1435
1442
  /**
1436
1443
  * How the HTTP handler composes the application with the rest of a Worker: exact origins, transports, plain
1437
1444
  * routes and mounts, a base path, a fallback and request hooks.
1438
1445
  */
1439
1446
  interface HttpOptions<E = unknown> {
1447
+ /** Ordered request wrappers, after origin admission and inside native error/security handling. */
1448
+ middleware?: readonly HttpMiddleware<E>[];
1440
1449
  /** Exact deployment origins; refusal precedes metadata, hooks and token admission. */
1441
1450
  origins?: readonly string[];
1442
1451
  /**
@@ -1691,4 +1700,4 @@ interface WorkerOptions<E> {
1691
1700
  * Workers whose Service Binding names an allowed `caller`.
1692
1701
  */
1693
1702
  declare function createWorker<E, C, O extends Record<string, OperationShape>>(application: AppManifest<E, C, O>, options?: WorkerOptions<E>): WorkerRuntime<E, O>;
1694
- export { SignedUrl as $, Observer as $t, HttpOptions as A, ok as An, parseInput as At, Type$2 as B, standardErrors as Bn, McpGuide as Bt, HttpRouteDefinition as C, StaticDecode$1 as Cn, strictObject as Ct, isInputHeaderName as D, Success as Dn, InputIssue as Dt, decodePathParameter as E, Result as En, urlSchema as Et, createHttpHandler as F, Failure as Fn, AppManifest as Ft, EmailAddressSchema as G, isRequestId as Gn, composeOperations as Gt, t$1 as H, TraceParent as Hn, OperationMiddleware as Ht, EmptyInputSchema as I, FailureData as In, Exposure as It, NamedReference as J, AttachmentOutputSchema as Jn, operationMatchesScopes as Jt, HexColorSchema as K, parseTraceParent as Kn, isPublicOperation as Kt, OrganizationIdSchema as L, FailureSchema as Ln, Invocation as Lt, HttpTransport as M, ErrorCatalog as Mn, ApplicationBuilder as Mt, RouteContext as N, ErrorDefinition as Nn, ApplicationConfiguration as Nt, isPathParameterValue as O, err as On, decodeInput as Ot, TransportContext as P, ErrorFactory as Pn, maximus as Pt, PostalAddressSchema as Q, ExecutionObservation as Qt, Static$2 as R, defineErrors as Rn, InvocationAuthority as Rt, readBodyText as S, matchesScopes as Sn, refineSchema as St, createHttpRouteResolver as T, FailureResult as Tn, transformSchema as Tt, DeletedObject as U, createRequestId as Un, OperationScope as Ut, UuidSchema as V, DurableCorrelation as Vn, McpSkill as Vt, DeletedObjectSchema as W, durableCorrelation as Wn, OperationShape as Wt, PhoneNumberSchema as X, AdmissionObservation as Xt, NamedReferenceSchema as Y, operationScopes as Yt, PostalAddress as Z, BackgroundContext as Zt, retryAfterSeconds as _, createTokenVerifier as _n, inspectSchema as _t, credentials as a, withDiagnostics as an, PageQueryFields as at, HttpBodyFailureReason as b, protectedResourceMetadata as bn, normalizeSchema as bt, executeOperation as c, TokenAlgorithm as cn, Checked as ct, Type$1 as d, TokenDevelopment as dn, SchemaInput as dt, TelemetryConfig as en, SignedUrlSchema as et, t as f, TokenPolicy as fn, SchemaIssue as ft, readJsonResponse as g, createTokenAuthorization as gn, inputSchema as gt, readJsonBody as h, TokenScheme as hn, extendObject as ht, createWorker as i, telemetryEnabled as in, PageQuery as it, HttpRoute as j, DefinedErrors as jn, parseSchema as jt, operationPathParameters as k, isResult as kn, decodeSchema as kt, Static$1 as l, TokenClaims as ln, checkSchema as lt, isJsonMediaType as m, TokenResolutionContext as mn, defaultSchema as mt, WorkerOptions as n, recordExecution as nn, PageInfo as nt, WorkerAssetsOptions as o, Principal as on, TPage as ot, createOpenApi as p, TokenPrincipal as pn, SchemaValidationError as pt, HttpsUrlSchema as q, Attachment as qn, operation as qt, WorkerRuntime as r, reportUnexpected as rn, PageInfoSchema as rt, defineApp as s, PrincipalSchema as sn, pageLimit as st, RpcMethods as t, diagnosticsEnabled as tn, Page as tt, TSchema$1 as u, TokenClient as un, readSchema as ut, BodyReadOptions as v, projectToken as vn, literalUnion as vt, HttpRouteMatch as w, BinaryBody as wn, stripObject as wt, readBodyBytes as x, ScopeMatch as xn, pipeSchema as xt, HttpBodyFailure as y, OAuthResource as yn, looseObject as yt, TSchema$2 as z, resultSchema as zn, McpConfiguration as zt };
1703
+ export { PostalAddressSchema as $, AdmissionObservation as $t, HttpMiddleware as A, Success as An, decodeSchema as At, TSchema$2 as B, FailureSchema as Bn, Invocation as Bt, HttpRouteDefinition as C, protectedResourceMetadata as Cn, refineSchema as Ct, isInputHeaderName as D, BinaryBody as Dn, urlSchema as Dt, decodePathParameter as E, StaticDecode$1 as En, transformSchema as Et, TransportContext as F, ErrorCatalog as Fn, KnownOperationFields as Ft, DeletedObjectSchema as G, TraceParent as Gn, OperationMiddleware as Gt, UuidSchema as H, resultSchema as Hn, McpConfiguration as Ht, createHttpHandler as I, ErrorDefinition as In, OperationFields as It, HttpsUrlSchema as J, isRequestId as Jn, composeOperations as Jt, EmailAddressSchema as K, createRequestId as Kn, OperationScope as Kt, EmptyInputSchema as L, ErrorFactory as Ln, maximus as Lt, HttpRoute as M, isResult as Mn, parseSchema as Mt, HttpTransport as N, ok as Nn, ApplicationBuilder as Nt, isPathParameterValue as O, FailureResult as On, InputIssue as Ot, RouteContext as P, DefinedErrors as Pn, ApplicationConfiguration as Pt, PostalAddress as Q, operationScopes as Qt, OrganizationIdSchema as R, Failure as Rn, AppManifest as Rt, readBodyText as S, OAuthResource as Sn, pipeSchema as St, createHttpRouteResolver as T, matchesScopes as Tn, stripObject as Tt, t$1 as U, standardErrors as Un, McpGuide as Ut, Type$2 as V, defineErrors as Vn, InvocationAuthority as Vt, DeletedObject as W, DurableCorrelation as Wn, McpSkill as Wt, NamedReferenceSchema as X, Attachment as Xn, operation as Xt, NamedReference as Y, parseTraceParent as Yn, isPublicOperation as Yt, PhoneNumberSchema as Z, AttachmentOutputSchema as Zn, operationMatchesScopes as Zt, retryAfterSeconds as _, TokenResolutionContext as _n, inputSchema as _t, credentials as a, recordExecution as an, PageQuery as at, HttpBodyFailureReason as b, createTokenVerifier as bn, looseObject as bt, executeOperation as c, withDiagnostics as cn, pageLimit as ct, Type$1 as d, TokenAlgorithm as dn, readSchema as dt, BackgroundContext as en, SignedUrl as et, t as f, TokenClaims as fn, SchemaInput as ft, readJsonResponse as g, TokenPrincipal as gn, extendObject as gt, readJsonBody as h, TokenPolicy as hn, defaultSchema as ht, createWorker as i, diagnosticsEnabled as in, PageInfoSchema as it, HttpOptions as j, err as jn, parseInput as jt, operationPathParameters as k, Result as kn, decodeInput as kt, Static$1 as l, Principal as ln, Checked as lt, isJsonMediaType as m, TokenDevelopment as mn, SchemaValidationError as mt, WorkerOptions as n, Observer as nn, Page as nt, WorkerAssetsOptions as o, reportUnexpected as on, PageQueryFields as ot, createOpenApi as p, TokenClient as pn, SchemaIssue as pt, HexColorSchema as q, durableCorrelation as qn, OperationShape as qt, WorkerRuntime as r, TelemetryConfig as rn, PageInfo as rt, defineApp as s, telemetryEnabled as sn, TPage as st, RpcMethods as t, ExecutionObservation as tn, SignedUrlSchema as tt, TSchema$1 as u, PrincipalSchema as un, checkSchema as ut, BodyReadOptions as v, TokenScheme as vn, inspectSchema as vt, HttpRouteMatch as w, ScopeMatch as wn, strictObject as wt, readBodyBytes as x, projectToken as xn, normalizeSchema as xt, HttpBodyFailure as y, createTokenAuthorization as yn, literalUnion as yt, Static$2 as z, FailureData as zn, Exposure as zt };
@@ -1,4 +1,4 @@
1
- import { Fn as Failure, Wt as OperationShape, l as Static } from "../chunks/types-BWxDd3tY.js";
1
+ import { Rn as Failure, l as Static, qt as OperationShape } from "../chunks/types-DQdfRF3f.js";
2
2
  /** What every HTTP operation answers: its data on success, its failure otherwise, and the request id. */
3
3
  export type Envelope<T> = {
4
4
  success: true;
@@ -1,7 +1,7 @@
1
1
  import { r as isRequestId } from "../chunks/correlation-BEkcFFGT.js";
2
- import { standardErrors } from "../errors.js";
2
+ import { i as standardErrors } from "../chunks/errors-D7zG9kx9.js";
3
3
  import { n as exactLength, t as isRecord } from "../chunks/record-DY-lX9w1.js";
4
- import { isInputHeaderName, isPathParameterValue, operationPathParameters } from "../http-paths.js";
4
+ import { a as operationPathParameters, i as isPathParameterValue, r as isInputHeaderName } from "../chunks/http-paths-yKD6TSNJ.js";
5
5
  import { i as readJsonResponse } from "../chunks/json-Bu4BLT25.js";
6
6
 
7
7
  // src/client/attachment-response.ts
@@ -1,4 +1,4 @@
1
- import { $t as Observer, Gn as isRequestId, Hn as TraceParent, Kn as parseTraceParent, Qt as ExecutionObservation, Un as createRequestId, Vn as DurableCorrelation, Wn as durableCorrelation, Zt as BackgroundContext, an as withDiagnostics, en as TelemetryConfig, in as telemetryEnabled, nn as recordExecution, rn as reportUnexpected, tn as diagnosticsEnabled } from "./chunks/types-BWxDd3tY.js";
1
+ import { Gn as TraceParent, Jn as isRequestId, Kn as createRequestId, Wn as DurableCorrelation, Yn as parseTraceParent, an as recordExecution, cn as withDiagnostics, en as BackgroundContext, in as diagnosticsEnabled, nn as Observer, on as reportUnexpected, qn as durableCorrelation, rn as TelemetryConfig, sn as telemetryEnabled, tn as ExecutionObservation } from "./chunks/types-DQdfRF3f.js";
2
2
  /**
3
3
  * What diagnostics may say about an error: its name, its causes' names, its issue count and its stack
4
4
  * locations.
package/dist/errors.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { Bn as standardErrors, Fn as Failure, Gn as isRequestId, In as FailureData, Ln as FailureSchema, Mn as ErrorCatalog, Nn as ErrorDefinition, Pn as ErrorFactory, Rn as defineErrors, jn as DefinedErrors, zn as resultSchema } from "./chunks/types-BWxDd3tY.js";
1
+ import { Bn as FailureSchema, Fn as ErrorCatalog, Hn as resultSchema, In as ErrorDefinition, Jn as isRequestId, Ln as ErrorFactory, Pn as DefinedErrors, Rn as Failure, Un as standardErrors, Vn as defineErrors, zn as FailureData } from "./chunks/types-DQdfRF3f.js";
2
2
  export { DefinedErrors, ErrorCatalog, ErrorDefinition, ErrorFactory, Failure, FailureData, FailureSchema, defineErrors, isRequestId, resultSchema, standardErrors };