@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
package/dist/client/client.d.ts
DELETED
|
@@ -1,129 +0,0 @@
|
|
|
1
|
-
import { Fn as Failure, Wt as OperationShape, l as Static } from "../chunks/types-BWxDd3tY.js";
|
|
2
|
-
/** What every HTTP operation answers: its data on success, its failure otherwise, and the request id. */
|
|
3
|
-
export type Envelope<T> = {
|
|
4
|
-
success: true;
|
|
5
|
-
data: T;
|
|
6
|
-
error: null;
|
|
7
|
-
metadata: {
|
|
8
|
-
requestId: string;
|
|
9
|
-
};
|
|
10
|
-
} | {
|
|
11
|
-
success: false;
|
|
12
|
-
data: null;
|
|
13
|
-
error: Failure;
|
|
14
|
-
metadata: {
|
|
15
|
-
requestId: string;
|
|
16
|
-
};
|
|
17
|
-
};
|
|
18
|
-
/** The part of an application the client's types read: its operations. `typeof app` satisfies it. */
|
|
19
|
-
export type ClientManifest = {
|
|
20
|
-
/** The application's operations by name; each one public over HTTP becomes a client method of that name. */
|
|
21
|
-
operations: Record<string, OperationShape>;
|
|
22
|
-
};
|
|
23
|
-
/** Public HTTP operation identifiers derive from the service's native manifest. */
|
|
24
|
-
export type OperationName<M extends ClientManifest> = Extract<{ [K in keyof M['operations']]: M['operations'][K] extends {
|
|
25
|
-
http: object;
|
|
26
|
-
} ? M['operations'][K] extends {
|
|
27
|
-
visibility: 'internal';
|
|
28
|
-
} ? never : K : never; }[keyof M['operations']], string>;
|
|
29
|
-
/** Read effects include POST searches; transport method does not determine cache ownership. */
|
|
30
|
-
export type ReadOperationName<M extends ClientManifest> = { [K in OperationName<M>]: M['operations'][K] extends {
|
|
31
|
-
effect: 'read';
|
|
32
|
-
} ? K : never; }[OperationName<M>];
|
|
33
|
-
/** The complete declared input includes item path and mapped metadata-header fields. */
|
|
34
|
-
export type OperationInput<M extends ClientManifest, K extends OperationName<M>> = Static<M['operations'][K]['input']>;
|
|
35
|
-
/** JSON outputs retain their native schema type; validated attachments expose the Web Response API. */
|
|
36
|
-
export type OperationOutput<M extends ClientManifest, K extends OperationName<M>> = ClientOutput<M['operations'][K]>;
|
|
37
|
-
/** Whether a method answers the whole envelope or only its data. */
|
|
38
|
-
export type ResponseMode = 'envelope' | 'data';
|
|
39
|
-
/** What one method answers in a response mode. */
|
|
40
|
-
type ClientResponse<O extends OperationShape, Mode extends ResponseMode> = Mode extends 'data' ? ClientOutput<O> : Envelope<ClientOutput<O>>;
|
|
41
|
-
/**
|
|
42
|
-
* The typed client of an application: one method per public HTTP operation. A byte operation also takes its
|
|
43
|
-
* body in the call options.
|
|
44
|
-
*/
|
|
45
|
-
export type AppClientContract<M extends ClientManifest, Mode extends ResponseMode = 'envelope'> = { [K in OperationName<M>]: M['operations'][K] extends {
|
|
46
|
-
http: {
|
|
47
|
-
body: 'bytes';
|
|
48
|
-
};
|
|
49
|
-
} ? (input: OperationInput<M, K>, options: BinaryCallOptions) => Promise<ClientResponse<M['operations'][K], Mode>> : (input: OperationInput<M, K>, options?: CallOptions) => Promise<ClientResponse<M['operations'][K], Mode>>; };
|
|
50
|
-
/** An operation's output as the client returns it: its declared type, or a Response for an attachment. */
|
|
51
|
-
type ClientOutput<Operation extends OperationShape> = Operation extends {
|
|
52
|
-
http: {
|
|
53
|
-
response: 'attachment';
|
|
54
|
-
};
|
|
55
|
-
} ? Response : Static<Operation['output']>;
|
|
56
|
-
/** Options of one call: a signal that cancels it. */
|
|
57
|
-
export interface CallOptions {
|
|
58
|
-
/** Cancels this call when it aborts, as do the client's `timeoutMs` deadline and its `signal` option. */
|
|
59
|
-
signal?: AbortSignal;
|
|
60
|
-
}
|
|
61
|
-
/** Options of one call to a byte operation: its body and the transfer's progress. */
|
|
62
|
-
export interface BinaryCallOptions extends CallOptions {
|
|
63
|
-
/**
|
|
64
|
-
* The bytes to upload; without a mapped `content-type` input field, a `Blob`'s own type is sent, else
|
|
65
|
-
* `application/octet-stream`.
|
|
66
|
-
*/
|
|
67
|
-
body: Blob | Uint8Array<ArrayBuffer>;
|
|
68
|
-
/** Transfer lifecycle only: 0 when sending begins, 1 after a validated success response; not byte progress. */
|
|
69
|
-
onUploadProgress?: (share: 0 | 1) => void;
|
|
70
|
-
}
|
|
71
|
-
/** A validated native refusal; applications select finite, localized presentation without parsing responses. */
|
|
72
|
-
export interface ClientFailure {
|
|
73
|
-
/** Actual HTTP status, including a refusal whose protocol body could not be decoded. */
|
|
74
|
-
status: number;
|
|
75
|
-
/** Validated native failure, or the canonical internal failure for malformed refusal bodies. */
|
|
76
|
-
failure: Failure;
|
|
77
|
-
/** Technical UUID/edge-ray correlation; empty when the response provides no valid identifier. */
|
|
78
|
-
requestId: string;
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* How the client answers, authenticates, times out and bounds what it reads, and the hooks around each
|
|
82
|
-
* request.
|
|
83
|
-
*/
|
|
84
|
-
export interface ClientOptions {
|
|
85
|
-
/** Data mode rejects native refusals; omitted mode preserves typed success/failure envelopes. */
|
|
86
|
-
response?: ResponseMode;
|
|
87
|
-
/** Captured once at operation entry, before discovery or token acquisition can await. */
|
|
88
|
-
signal?: () => AbortSignal;
|
|
89
|
-
/** Optional application presentation of an already validated refusal, used only in data mode. */
|
|
90
|
-
onFailure?: (refusal: ClientFailure) => Error;
|
|
91
|
-
/**
|
|
92
|
-
* The fetch implementation every request goes through, the global `fetch` by default; for tests or a
|
|
93
|
-
* Service Binding's `fetch`.
|
|
94
|
-
*/
|
|
95
|
-
fetch?: typeof fetch;
|
|
96
|
-
/**
|
|
97
|
-
* The deadline of each call in milliseconds, discovery and token acquisition included; 30000 by default.
|
|
98
|
-
*/
|
|
99
|
-
timeoutMs?: number;
|
|
100
|
-
/** Headers may be augmented; method, URL, body, bearer and declared metadata remain client-owned. */
|
|
101
|
-
beforeRequest?: (request: Request) => void | Promise<void>;
|
|
102
|
-
/** Receives the same request object, including admitted request headers for consistency cursors. */
|
|
103
|
-
afterResponse?: (response: Response, request: Request) => void | Promise<void>;
|
|
104
|
-
/**
|
|
105
|
-
* The Fetch credentials mode, `'omit'` by default. Its values are written out because the Workers and
|
|
106
|
-
* Node type libraries declare no `RequestCredentials`.
|
|
107
|
-
*/
|
|
108
|
-
credentials?: 'omit' | 'same-origin' | 'include';
|
|
109
|
-
/** The Fetch cache mode, `'no-store'` by default; written out for the same reason (`RequestCache`). */
|
|
110
|
-
cache?: 'default' | 'no-store' | 'reload' | 'no-cache' | 'force-cache' | 'only-if-cached';
|
|
111
|
-
/** Raw attachments are bounded independently of small JSON metadata responses; defaults to 16 MiB. */
|
|
112
|
-
maxAttachmentBytes?: number;
|
|
113
|
-
/** Operation response byte limit, including chunked bodies; defaults to 1 MiB and cannot exceed 16 MiB. */
|
|
114
|
-
maxResponseBytes?: number;
|
|
115
|
-
}
|
|
116
|
-
/**
|
|
117
|
-
* A typed HTTP client for an application, from its type alone (`createClient<typeof app>(…)`): one
|
|
118
|
-
* method per public HTTP operation, named as the operation. On its first call it reads the routes
|
|
119
|
-
* from the service's live `/openapi.json` at `origin`, an HTTPS base URL that may carry a path.
|
|
120
|
-
* With `response: 'data'`, a method returns the data and throws on a refusal.
|
|
121
|
-
*/
|
|
122
|
-
export declare function createClient<M extends ClientManifest>(origin: string, token: string | (() => Promise<string>), options: ClientOptions & {
|
|
123
|
-
response: 'data';
|
|
124
|
-
}): AppClientContract<M, 'data'>;
|
|
125
|
-
/** The same, answering each call with its success or failure envelope. */
|
|
126
|
-
export declare function createClient<M extends ClientManifest>(origin: string, token: string | (() => Promise<string>), options?: ClientOptions & {
|
|
127
|
-
response?: 'envelope';
|
|
128
|
-
}): AppClientContract<M>;
|
|
129
|
-
export {};
|
package/dist/client/client.js
DELETED
|
@@ -1,321 +0,0 @@
|
|
|
1
|
-
import { r as isRequestId } from "../chunks/correlation-BEkcFFGT.js";
|
|
2
|
-
import { standardErrors } from "../errors.js";
|
|
3
|
-
import { n as exactLength, t as isRecord } from "../chunks/record-DY-lX9w1.js";
|
|
4
|
-
import { isInputHeaderName, isPathParameterValue, operationPathParameters } from "../http-paths.js";
|
|
5
|
-
import { i as readJsonResponse } from "../chunks/json-Bu4BLT25.js";
|
|
6
|
-
|
|
7
|
-
// src/client/attachment-response.ts
|
|
8
|
-
/**
|
|
9
|
-
* An attachment as the typed client hands it out: a Response whose body is held to the length its headers
|
|
10
|
-
* declare.
|
|
11
|
-
*/
|
|
12
|
-
/** Bound raw response streams without buffering or trusting an unbounded/chunked attachment. */
|
|
13
|
-
function boundedAttachment(response, maxBytes) {
|
|
14
|
-
const rawLength = response.headers.get("content-length");
|
|
15
|
-
if (!rawLength || !/^\d+$/u.test(rawLength) || !Number.isSafeInteger(Number(rawLength)) || Number(rawLength) > maxBytes) throw new Error("Invalid attachment length.");
|
|
16
|
-
const length = Number(rawLength);
|
|
17
|
-
if (!response.body) {
|
|
18
|
-
if (length !== 0) throw new Error("Missing attachment body.");
|
|
19
|
-
return response;
|
|
20
|
-
}
|
|
21
|
-
return new Response(exactLength(response.body, length), {
|
|
22
|
-
status: response.status,
|
|
23
|
-
statusText: response.statusText,
|
|
24
|
-
headers: response.headers
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// src/client/operation-abort.ts
|
|
29
|
-
/**
|
|
30
|
-
* Lets a client call stop waiting when its caller aborts, without cancelling the work it waited for.
|
|
31
|
-
*/
|
|
32
|
-
/**
|
|
33
|
-
* Waits for `pending` until the caller's `signal` aborts, then rejects with its reason. The pending work
|
|
34
|
-
* itself goes on, so a shared one, such as route discovery, still serves the other calls.
|
|
35
|
-
*/
|
|
36
|
-
async function awaitWithSignal(pending, signal) {
|
|
37
|
-
signal?.throwIfAborted();
|
|
38
|
-
if (!signal) return pending;
|
|
39
|
-
let abort;
|
|
40
|
-
const aborted = new Promise((_resolve, reject) => {
|
|
41
|
-
abort = () => reject(signal.reason);
|
|
42
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
43
|
-
});
|
|
44
|
-
try {
|
|
45
|
-
return await Promise.race([pending, aborted]);
|
|
46
|
-
} finally {
|
|
47
|
-
if (abort) signal.removeEventListener("abort", abort);
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// src/client/response-envelope.ts
|
|
52
|
-
/**
|
|
53
|
-
* Reads an operation's response envelope as the typed client receives it, checking its shape and its
|
|
54
|
-
* status before any data or failure reaches the caller.
|
|
55
|
-
*/
|
|
56
|
-
/**
|
|
57
|
-
* Whether a value is a well-formed failure: exactly code, message, retryable and data, with a printable code.
|
|
58
|
-
*/
|
|
59
|
-
const failure = (value) => isRecord(value) && Object.keys(value).length === 4 && typeof value.code === "string" && value.code.length > 0 && value.code.length <= 128 && !/\p{Cc}/u.test(value.code) && typeof value.message === "string" && typeof value.retryable === "boolean" && isRecord(value.data);
|
|
60
|
-
/** Validate protocol discriminants and status consistency before data or refusal reaches a caller. */
|
|
61
|
-
function responseEnvelope(value, status) {
|
|
62
|
-
if (!isRecord(value) || Object.keys(value).length !== 4 || !Object.hasOwn(value, "data") || !isRecord(value.metadata) || Object.keys(value.metadata).length !== 1 || !isRequestId(value.metadata.requestId)) throw new Error(`Invalid service response (${status}).`);
|
|
63
|
-
const metadata = { requestId: value.metadata.requestId };
|
|
64
|
-
if (value.success === true && value.error === null && status >= 200 && status < 300) return {
|
|
65
|
-
success: true,
|
|
66
|
-
data: value.data,
|
|
67
|
-
error: null,
|
|
68
|
-
metadata
|
|
69
|
-
};
|
|
70
|
-
if (value.success === false && value.data === null && failure(value.error) && status >= 400 && status <= 599) return {
|
|
71
|
-
success: false,
|
|
72
|
-
data: null,
|
|
73
|
-
error: value.error,
|
|
74
|
-
metadata
|
|
75
|
-
};
|
|
76
|
-
throw new Error(`Invalid service response (${status}).`);
|
|
77
|
-
}
|
|
78
|
-
/** The largest refusal body the client reads, whatever its success limit. */
|
|
79
|
-
const MAX_FAILURE_BYTES = 16384;
|
|
80
|
-
/** Refusal decoding never grants a successful operation's larger body budget or exposes unvalidated server text. */
|
|
81
|
-
async function readOperationEnvelope(response, options) {
|
|
82
|
-
const result = await readJsonResponse(response, {
|
|
83
|
-
signal: options.signal,
|
|
84
|
-
maxBytes: response.ok ? options.maxBytes : Math.min(options.maxBytes, MAX_FAILURE_BYTES)
|
|
85
|
-
});
|
|
86
|
-
options.signal.throwIfAborted();
|
|
87
|
-
try {
|
|
88
|
-
if (!result.ok) throw new Error(`Invalid service response (${response.status}).`);
|
|
89
|
-
return responseEnvelope(result.value, response.status);
|
|
90
|
-
} catch (error) {
|
|
91
|
-
if (!options.dataMode || response.ok) throw error;
|
|
92
|
-
const requestId = response.headers.get("x-request-id");
|
|
93
|
-
return {
|
|
94
|
-
success: false,
|
|
95
|
-
data: null,
|
|
96
|
-
error: standardErrors.internal.create(),
|
|
97
|
-
metadata: { requestId: isRequestId(requestId) ? requestId : "" }
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
// src/client/client.ts
|
|
103
|
-
/**
|
|
104
|
-
* `@arbol-ai/maximus/client`: the typed HTTP client. Its methods are inferred from the application's type
|
|
105
|
-
* alone, and its routes come from the service's live OpenAPI document.
|
|
106
|
-
*/
|
|
107
|
-
/** Progress observes validated transfer lifecycle; callback failure cannot replay or change a request. */
|
|
108
|
-
function notifyUploadTransfer(upload, share) {
|
|
109
|
-
try {
|
|
110
|
-
upload?.onUploadProgress?.(share);
|
|
111
|
-
} catch {}
|
|
112
|
-
}
|
|
113
|
-
/** The response body limit when the client sets none: 1 MiB. */
|
|
114
|
-
const DEFAULT_MAX_RESPONSE_BYTES = 1048576;
|
|
115
|
-
/** The largest response body limit a client may set: 16 MiB. */
|
|
116
|
-
const MAX_RESPONSE_BYTES = 16777216;
|
|
117
|
-
/**
|
|
118
|
-
* A GET input value as the service's query codec reads it back: a string as it is, a finite number, a
|
|
119
|
-
* boolean as `true` or `false`, and a list of nonempty strings without commas joined by commas. Null for a
|
|
120
|
-
* value a query string cannot carry.
|
|
121
|
-
*/
|
|
122
|
-
function queryValue(value) {
|
|
123
|
-
if (typeof value === "string") return value;
|
|
124
|
-
if (typeof value === "number") return Number.isFinite(value) ? String(value) : null;
|
|
125
|
-
if (typeof value === "boolean") return String(value);
|
|
126
|
-
return Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string" && item !== "" && !item.includes(",")) ? value.join(",") : null;
|
|
127
|
-
}
|
|
128
|
-
function createClient(origin, token, options = {}) {
|
|
129
|
-
const maxResponseBytes = options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;
|
|
130
|
-
if (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes < 1 || maxResponseBytes > MAX_RESPONSE_BYTES) throw new RangeError("maxResponseBytes must be an integer between 1 byte and 16 MiB.");
|
|
131
|
-
const maxAttachmentBytes = options.maxAttachmentBytes ?? MAX_RESPONSE_BYTES;
|
|
132
|
-
if (!Number.isSafeInteger(maxAttachmentBytes) || maxAttachmentBytes < 1 || maxAttachmentBytes > MAX_RESPONSE_BYTES) throw new RangeError("Invalid attachment byte limit.");
|
|
133
|
-
const base = new URL(origin);
|
|
134
|
-
const loopback = [
|
|
135
|
-
"localhost",
|
|
136
|
-
"127.0.0.1",
|
|
137
|
-
"[::1]"
|
|
138
|
-
].includes(base.hostname);
|
|
139
|
-
if (!(base.protocol === "https:" || base.protocol === "http:" && loopback) || base.username || base.password || !/^\/(?:[a-zA-Z0-9_-]+\/)*[a-zA-Z0-9_-]*$/.test(base.pathname) || base.search || base.hash) throw new TypeError("Use an HTTPS origin (plain HTTP only on localhost).");
|
|
140
|
-
const prefix = base.pathname.replace(/\/$/, "");
|
|
141
|
-
/** A service path as a URL below the base URL's own path. */
|
|
142
|
-
const serviceUrl = (path) => new URL(`${prefix}${path}`, base.origin);
|
|
143
|
-
const transport = options.fetch ?? fetch;
|
|
144
|
-
let routes;
|
|
145
|
-
/**
|
|
146
|
-
* Reads every operation's route, method, byte body, attachment and header fields from the service's live
|
|
147
|
-
* OpenAPI document.
|
|
148
|
-
*/
|
|
149
|
-
async function discover() {
|
|
150
|
-
const signal = AbortSignal.timeout(options.timeoutMs ?? 3e4);
|
|
151
|
-
const response = await send(serviceUrl("/openapi.json"), {
|
|
152
|
-
method: "GET",
|
|
153
|
-
signal
|
|
154
|
-
}, void 0, false);
|
|
155
|
-
const result = await readJsonResponse(response, {
|
|
156
|
-
signal,
|
|
157
|
-
maxBytes: 4194304
|
|
158
|
-
});
|
|
159
|
-
if (!response.ok || !result.ok || !result.value || typeof result.value !== "object" || !("paths" in result.value) || !result.value.paths || typeof result.value.paths !== "object") throw new Error("Invalid service contract.");
|
|
160
|
-
const found = /* @__PURE__ */ new Map();
|
|
161
|
-
for (const [path, methods] of Object.entries(result.value.paths)) {
|
|
162
|
-
if (!methods || typeof methods !== "object") throw new Error("Invalid service route.");
|
|
163
|
-
let parameters;
|
|
164
|
-
try {
|
|
165
|
-
parameters = operationPathParameters(path);
|
|
166
|
-
} catch {
|
|
167
|
-
throw new Error("Invalid service route.");
|
|
168
|
-
}
|
|
169
|
-
for (const [method, operation] of Object.entries(methods)) {
|
|
170
|
-
if (![
|
|
171
|
-
"get",
|
|
172
|
-
"post",
|
|
173
|
-
"put",
|
|
174
|
-
"patch",
|
|
175
|
-
"delete"
|
|
176
|
-
].includes(method)) continue;
|
|
177
|
-
if (!operation || typeof operation !== "object" || !("operationId" in operation) || typeof operation.operationId !== "string" || found.has(operation.operationId)) throw new Error("Invalid service operation.");
|
|
178
|
-
const metadata = operation;
|
|
179
|
-
const body = metadata["x-body"];
|
|
180
|
-
const responseKind = metadata["x-response"];
|
|
181
|
-
if (body !== void 0 && body !== "bytes" || responseKind !== void 0 && responseKind !== "attachment") throw new Error("Invalid operation body contract.");
|
|
182
|
-
const headers = metadata["x-input-headers"] ?? {};
|
|
183
|
-
if (!headers || typeof headers !== "object" || Array.isArray(headers) || Object.entries(headers).some(([field, header]) => !field || typeof header !== "string" || !isInputHeaderName(header))) throw new Error("Invalid operation header contract.");
|
|
184
|
-
found.set(operation.operationId, {
|
|
185
|
-
path,
|
|
186
|
-
method: method.toUpperCase(),
|
|
187
|
-
parameters,
|
|
188
|
-
headers,
|
|
189
|
-
...body === "bytes" ? { body } : {},
|
|
190
|
-
...responseKind === "attachment" ? { response: responseKind } : {}
|
|
191
|
-
});
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
return found;
|
|
195
|
-
}
|
|
196
|
-
/**
|
|
197
|
-
* Sends one request with the bearer, no credentials and no cache, after the hooks: they may add headers,
|
|
198
|
-
* never replace the bearer, the method, the body or the deadline.
|
|
199
|
-
*/
|
|
200
|
-
async function send(url, init, upload, authenticated = true) {
|
|
201
|
-
const { signal } = init;
|
|
202
|
-
signal?.throwIfAborted();
|
|
203
|
-
const bearer = authenticated ? `Bearer ${typeof token === "string" ? token : await awaitWithSignal(token(), signal)}` : void 0;
|
|
204
|
-
signal?.throwIfAborted();
|
|
205
|
-
const request = new Request(url, {
|
|
206
|
-
...init,
|
|
207
|
-
redirect: "manual",
|
|
208
|
-
credentials: options.credentials ?? "omit",
|
|
209
|
-
cache: options.cache ?? "no-store"
|
|
210
|
-
});
|
|
211
|
-
await awaitWithSignal(Promise.resolve(options.beforeRequest?.(request)), signal);
|
|
212
|
-
signal?.throwIfAborted();
|
|
213
|
-
for (const [header, value] of new Headers(init.headers)) request.headers.set(header, value);
|
|
214
|
-
if (bearer) request.headers.set("authorization", bearer);
|
|
215
|
-
else request.headers.delete("authorization");
|
|
216
|
-
notifyUploadTransfer(upload, 0);
|
|
217
|
-
const response = await awaitWithSignal(transport(url, {
|
|
218
|
-
...init,
|
|
219
|
-
headers: [...request.headers].length ? Object.fromEntries(request.headers) : void 0,
|
|
220
|
-
redirect: "manual",
|
|
221
|
-
credentials: request.credentials,
|
|
222
|
-
cache: request.cache
|
|
223
|
-
}), signal);
|
|
224
|
-
await awaitWithSignal(Promise.resolve(options.afterResponse?.(response, request)), signal);
|
|
225
|
-
return response;
|
|
226
|
-
}
|
|
227
|
-
return new Proxy(Object.create(null), { get(_target, name) {
|
|
228
|
-
if (typeof name !== "string" || name === "then") return;
|
|
229
|
-
return async (input, callOptions) => {
|
|
230
|
-
const capturedSignal = options.signal?.();
|
|
231
|
-
const signals = [
|
|
232
|
-
AbortSignal.timeout(options.timeoutMs ?? 3e4),
|
|
233
|
-
capturedSignal,
|
|
234
|
-
callOptions?.signal
|
|
235
|
-
].filter((signal) => signal !== void 0);
|
|
236
|
-
const signal = AbortSignal.any(signals);
|
|
237
|
-
signal.throwIfAborted();
|
|
238
|
-
routes ??= discover().catch((error) => {
|
|
239
|
-
routes = void 0;
|
|
240
|
-
throw error;
|
|
241
|
-
});
|
|
242
|
-
const route = (await awaitWithSignal(routes, signal)).get(name);
|
|
243
|
-
if (!route) throw new Error("Operation is not exposed over HTTP.");
|
|
244
|
-
const { path: declaredPath } = route;
|
|
245
|
-
let path = declaredPath;
|
|
246
|
-
for (const parameter of route.parameters) {
|
|
247
|
-
const value = input[parameter];
|
|
248
|
-
if (!isPathParameterValue(value)) throw new TypeError("Path values must be nonempty strings without slashes, dot segments or controls.");
|
|
249
|
-
path = path.replace(`{${parameter}}`, encodeURIComponent(value));
|
|
250
|
-
}
|
|
251
|
-
const pathNames = new Set(route.parameters);
|
|
252
|
-
const remaining = Object.fromEntries(Object.entries(input).filter(([field]) => !pathNames.has(field)));
|
|
253
|
-
const url = serviceUrl(path);
|
|
254
|
-
const metadataHeaders = new Headers();
|
|
255
|
-
const query = route.body === "bytes" ? Object.fromEntries(Object.entries(remaining).filter(([field]) => !Object.hasOwn(route.headers, field))) : remaining;
|
|
256
|
-
if (route.body === "bytes") for (const [key, value] of Object.entries(query)) {
|
|
257
|
-
if (value === void 0) continue;
|
|
258
|
-
if (typeof value !== "string") throw new TypeError("Query values must be strings.");
|
|
259
|
-
url.searchParams.set(key, value);
|
|
260
|
-
}
|
|
261
|
-
else if (route.method === "GET") for (const [key, value] of Object.entries(query)) {
|
|
262
|
-
if (value === void 0) continue;
|
|
263
|
-
const text = queryValue(value);
|
|
264
|
-
if (text === null) throw new TypeError("Query values must be strings, finite numbers, booleans or lists of nonempty strings without commas.");
|
|
265
|
-
url.searchParams.set(key, text);
|
|
266
|
-
}
|
|
267
|
-
for (const [field, header] of Object.entries(route.headers)) {
|
|
268
|
-
const value = remaining[field];
|
|
269
|
-
if (value === void 0) continue;
|
|
270
|
-
if (typeof value !== "string") throw new TypeError("Header values must be strings.");
|
|
271
|
-
metadataHeaders.set(header, value);
|
|
272
|
-
}
|
|
273
|
-
let body;
|
|
274
|
-
let upload;
|
|
275
|
-
if (route.body === "bytes") {
|
|
276
|
-
if (!callOptions || !("body" in callOptions) || !(callOptions.body instanceof Blob || callOptions.body instanceof Uint8Array)) throw new TypeError("A binary body is required.");
|
|
277
|
-
upload = callOptions;
|
|
278
|
-
({body} = upload);
|
|
279
|
-
if (!metadataHeaders.has("content-type")) metadataHeaders.set("content-type", upload.body instanceof Blob && upload.body.type ? upload.body.type : "application/octet-stream");
|
|
280
|
-
} else if (route.method !== "GET") {
|
|
281
|
-
if (callOptions && "body" in callOptions) throw new TypeError("A JSON operation cannot accept a binary body.");
|
|
282
|
-
metadataHeaders.set("content-type", "application/json");
|
|
283
|
-
body = JSON.stringify(remaining);
|
|
284
|
-
}
|
|
285
|
-
const response = await send(url, {
|
|
286
|
-
method: route.method,
|
|
287
|
-
signal,
|
|
288
|
-
headers: metadataHeaders,
|
|
289
|
-
...body === void 0 ? {} : { body }
|
|
290
|
-
}, upload);
|
|
291
|
-
if (route.response === "attachment" && response.ok) {
|
|
292
|
-
const attachment = boundedAttachment(response, maxAttachmentBytes);
|
|
293
|
-
notifyUploadTransfer(upload, 1);
|
|
294
|
-
return options.response === "data" ? attachment : {
|
|
295
|
-
success: true,
|
|
296
|
-
data: attachment,
|
|
297
|
-
error: null,
|
|
298
|
-
metadata: { requestId: response.headers.get("x-request-id") ?? "" }
|
|
299
|
-
};
|
|
300
|
-
}
|
|
301
|
-
const envelope = await readOperationEnvelope(response, {
|
|
302
|
-
signal,
|
|
303
|
-
maxBytes: maxResponseBytes,
|
|
304
|
-
dataMode: options.response === "data"
|
|
305
|
-
});
|
|
306
|
-
if (envelope.success) notifyUploadTransfer(upload, 1);
|
|
307
|
-
if (options.response !== "data") return envelope;
|
|
308
|
-
if (!envelope.success) {
|
|
309
|
-
const refusal = {
|
|
310
|
-
status: response.status,
|
|
311
|
-
failure: envelope.error,
|
|
312
|
-
requestId: envelope.metadata.requestId
|
|
313
|
-
};
|
|
314
|
-
throw options.onFailure?.(refusal) ?? new Error("The service refused the request.", { cause: refusal });
|
|
315
|
-
}
|
|
316
|
-
return envelope.data;
|
|
317
|
-
};
|
|
318
|
-
} });
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
export { createClient };
|
package/dist/tooling/vite.d.ts
DELETED
package/dist/tooling/vite.js
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { n as PROJECT_DIRECTORIES, t as prepareProject } from "../chunks/prepare-project-zi106pWF.js";
|
|
2
|
-
import { relative, resolve } from "node:path";
|
|
3
|
-
|
|
4
|
-
// src/tooling/vite.ts
|
|
5
|
-
/** Optional Vite integration. It generates static imports before Cloudflare reads the Worker. */
|
|
6
|
-
/** Prepare on startup/build and refresh discovery when convention files are added or removed. */
|
|
7
|
-
function maximusProject() {
|
|
8
|
-
let root = process.cwd();
|
|
9
|
-
let mode = "production";
|
|
10
|
-
return {
|
|
11
|
-
name: "maximus-project",
|
|
12
|
-
enforce: "pre",
|
|
13
|
-
config(config, environment) {
|
|
14
|
-
root = resolve(config.root ?? root);
|
|
15
|
-
({mode} = environment);
|
|
16
|
-
prepareProject(root, mode);
|
|
17
|
-
},
|
|
18
|
-
configureServer(server) {
|
|
19
|
-
const update = (file) => {
|
|
20
|
-
const [directory] = relative(root, file).split(/[\\/]/);
|
|
21
|
-
if (!PROJECT_DIRECTORIES.some((name) => name === directory)) return;
|
|
22
|
-
try {
|
|
23
|
-
prepareProject(root, mode);
|
|
24
|
-
server.ws.send({ type: "full-reload" });
|
|
25
|
-
} catch (error) {
|
|
26
|
-
server.config.logger.error(error instanceof Error ? error.message : String(error));
|
|
27
|
-
server.ws.send({
|
|
28
|
-
type: "error",
|
|
29
|
-
err: {
|
|
30
|
-
message: error instanceof Error ? error.message : String(error),
|
|
31
|
-
stack: ""
|
|
32
|
-
}
|
|
33
|
-
});
|
|
34
|
-
}
|
|
35
|
-
};
|
|
36
|
-
server.watcher.on("add", update).on("unlink", update);
|
|
37
|
-
server.httpServer?.once("close", () => {
|
|
38
|
-
server.watcher.off("add", update).off("unlink", update);
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export { maximusProject };
|
|
@@ -1,179 +0,0 @@
|
|
|
1
|
-
# Adding an operation
|
|
2
|
-
|
|
3
|
-
## Template
|
|
4
|
-
|
|
5
|
-
```ts
|
|
6
|
-
import { err, ok, t, UuidSchema } from '@arbol-ai/maximus';
|
|
7
|
-
|
|
8
|
-
import { base, errors } from '../../application';
|
|
9
|
-
|
|
10
|
-
export const notes = base.operation(
|
|
11
|
-
'getNote', // camelCase, unique; also the OpenAPI operationId and RPC method name
|
|
12
|
-
{
|
|
13
|
-
scope: ['notes:notes:read', 'notes:notes:write'], // any one admits; scopeMatch: 'all' for every one
|
|
14
|
-
effect: 'read', // 'read' | 'write' | 'delete' — truthful; only reads may use GET
|
|
15
|
-
group: 'Notes', // OpenAPI tag
|
|
16
|
-
title: 'Get a note',
|
|
17
|
-
description: 'Read one note by its identifier.', // written for people and models
|
|
18
|
-
input: t.Object({ noteId: UuidSchema }, { additionalProperties: false }),
|
|
19
|
-
output: NoteSchema,
|
|
20
|
-
http: { method: 'GET', path: '/v1/notes/{noteId}' },
|
|
21
|
-
mcp: { name: 'get_note', idempotent: true },
|
|
22
|
-
// rpc: true,
|
|
23
|
-
},
|
|
24
|
-
async ({ env, principal }, input) => {
|
|
25
|
-
const note = await readNote(env.NOTES, principal.organizationId, input.noteId);
|
|
26
|
-
return note ? ok(note) : err(errors.noteNotFound.create());
|
|
27
|
-
}
|
|
28
|
-
);
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
### Declared failures
|
|
32
|
-
|
|
33
|
-
Declare `failures` (the domain codes it may answer) so its documents list only those and any other
|
|
34
|
-
domain failure it returns becomes `INTERNAL_ERROR`, reported. Omitted, every failure of the catalog is
|
|
35
|
-
listed and allowed; standard failures are always allowed.
|
|
36
|
-
|
|
37
|
-
```ts
|
|
38
|
-
base.operation(
|
|
39
|
-
'archiveNote',
|
|
40
|
-
{
|
|
41
|
-
scope: 'notes:notes:write',
|
|
42
|
-
effect: 'write',
|
|
43
|
-
actorKinds: ['user'],
|
|
44
|
-
title: 'Archive a note',
|
|
45
|
-
description: 'Moves a note out of the active list; it stays readable.',
|
|
46
|
-
input: t.Object({ noteId: UuidSchema }, { additionalProperties: false }),
|
|
47
|
-
output: NoteSchema,
|
|
48
|
-
http: { method: 'POST', path: '/v1/notes/{noteId}/archive' },
|
|
49
|
-
mcp: { name: 'archive_note', idempotent: true },
|
|
50
|
-
failures: ['NOTE_NOT_FOUND'], // the only domain failure it may answer
|
|
51
|
-
},
|
|
52
|
-
async ({ env, principal }, input) => archiveNote(env.NOTES, principal.organizationId, input.noteId)
|
|
53
|
-
);
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
Reserved names: `fetch`, `connect`, `constructor`, `then`, `scheduled`, `queue`, `alarm`,
|
|
57
|
-
`__proto__`, `prototype`.
|
|
58
|
-
|
|
59
|
-
## Fields
|
|
60
|
-
|
|
61
|
-
An inline definition with a field no operation has (a misspelling, a retired `api` name) does not
|
|
62
|
-
compile.
|
|
63
|
-
|
|
64
|
-
| Field | Rule |
|
|
65
|
-
| --- | --- |
|
|
66
|
-
| `scope` | `<namespace>:<resource>:<action>` with the app's namespace; a list is any-of unless `scopeMatch: 'all'`. |
|
|
67
|
-
| `conditionalScopes` | Extra namespaced scopes the handler checks via `context.authority?.scopes`; calls without authority (ordinary RPC) are refused. |
|
|
68
|
-
| `actorKinds` | `['user']`, `['service']` or both; omitted, either is admitted. Required on every documented operation under the `oauth+bearer` token scheme. |
|
|
69
|
-
| `visibility` | `'internal'`: routed and scope-checked, hidden from OpenAPI, `scopes_supported` and the client. Give it a staff-only scope. |
|
|
70
|
-
| `maxBodyBytes` | Per-operation body limit, up to 16 MiB, never on GET. App default 32 KiB. |
|
|
71
|
-
| `maxOutputBytes` | Up to 16 MiB. Default 256 KiB. Over the limit → `INTERNAL_ERROR`. |
|
|
72
|
-
| `http.method`, `http.path` | `/v<n>/…`, static segments `[A-Za-z0-9_-]+`, whole-segment `{param}`; unique `METHOD path`. |
|
|
73
|
-
| `http.successStatus` | `200`, `201` or `202`. |
|
|
74
|
-
| `mcp.name` | `^[a-z][A-Za-z0-9_]{0,63}$`, unique; `idempotent` required; `openWorld` defaults to `true`. Served once the Worker mounts `transports: [mcp()]`. |
|
|
75
|
-
| `rpc` | `true` (all app callers) or `{ callers }` (a subset). |
|
|
76
|
-
|
|
77
|
-
## HTTP input rules
|
|
78
|
-
|
|
79
|
-
- GET input comes from the query string: each declared field is read as its kind (integer, number,
|
|
80
|
-
boolean, comma-separated string list, otherwise string); repeated keys are refused. The typed
|
|
81
|
-
client writes those values the same way.
|
|
82
|
-
- POST, PUT, PATCH and DELETE read a JSON body with `content-type: application/json` (415
|
|
83
|
-
otherwise); a DELETE with no body and no `content-type` is the empty input.
|
|
84
|
-
- A `{param}` must be a required `string` field of the input (of each union member). The query or
|
|
85
|
-
body may not repeat it.
|
|
86
|
-
- Unknown routes and methods are 404 before authentication; no trailing-slash normalization.
|
|
87
|
-
|
|
88
|
-
## Schemas
|
|
89
|
-
|
|
90
|
-
- Strict objects or unions of strict objects (discriminated by a field). A GET input is one object.
|
|
91
|
-
- Shared, each a named component: `OrganizationIdSchema`, `UuidSchema`, `EmailAddressSchema`,
|
|
92
|
-
`PhoneNumberSchema` (E.164), `HttpsUrlSchema`, `HexColorSchema`, `DeletedObjectSchema`,
|
|
93
|
-
`SignedUrlSchema`, `NamedReferenceSchema`, `PostalAddressSchema`; `EmptyInputSchema` (unnamed). Ids
|
|
94
|
-
are strings; use `organizationId` and `requestId`, never aliases. Name your own entities with a
|
|
95
|
-
PascalCase `$id`, one shape per name: it becomes a public SDK type.
|
|
96
|
-
- Lists: `input: inputSchema(t.Object({ ...PageQueryFields, ...filters }, { additionalProperties: false }))`
|
|
97
|
-
(`cursor`, `direction`, `limit`; `limit: pageLimit({ maximum })` to lower it) and
|
|
98
|
-
`output: Page(Item, { $id: 'ItemPage' })`, answering `{ object: 'list', data, pageInfo }`.
|
|
99
|
-
- Formats: `date`, `time`, `date-time` (time zone required), `email`, `uuid`, `uri`.
|
|
100
|
-
- Use `t.Union([X, t.Null()])` for absent values in outputs; present every field.
|
|
101
|
-
|
|
102
|
-
## Codecs (from `@arbol-ai/maximus/schemas`)
|
|
103
|
-
|
|
104
|
-
```ts
|
|
105
|
-
import { defaultSchema, inputSchema, normalizeSchema, refineSchema, t } from '@arbol-ai/maximus/schemas';
|
|
106
|
-
|
|
107
|
-
input: inputSchema(
|
|
108
|
-
refineSchema(
|
|
109
|
-
t.Object(
|
|
110
|
-
{
|
|
111
|
-
query: normalizeSchema(t.String({ minLength: 1, maxLength: 100 }), (value) => value.trim()),
|
|
112
|
-
limit: defaultSchema(t.Integer({ minimum: 1, maximum: 50 }), 20),
|
|
113
|
-
from: t.String({ format: 'date' }),
|
|
114
|
-
to: t.String({ format: 'date' }),
|
|
115
|
-
},
|
|
116
|
-
{ additionalProperties: false }
|
|
117
|
-
),
|
|
118
|
-
(value) => value.from <= value.to,
|
|
119
|
-
{ message: 'The range must not end before it starts.', path: ['to'] }
|
|
120
|
-
)
|
|
121
|
-
),
|
|
122
|
-
```
|
|
123
|
-
|
|
124
|
-
- Without `inputSchema(...)` around the input, normalizers, transforms, refinements and stripping do
|
|
125
|
-
not run.
|
|
126
|
-
- Handlers receive `StaticDecode<typeof input>`; clients and OpenAPI see `Static<typeof input>`.
|
|
127
|
-
- Refinement messages travel to callers in `INVALID_INPUT` issues: never include input values.
|
|
128
|
-
- Other helpers: `transformSchema`, `inspectSchema` (several issues via `addIssue`), `pipeSchema`,
|
|
129
|
-
`stripObject` / `strictObject` / `looseObject` / `extendObject`, `literalUnion`, `urlSchema`.
|
|
130
|
-
|
|
131
|
-
Numbers in a GET query need a wire schema:
|
|
132
|
-
|
|
133
|
-
```ts
|
|
134
|
-
const Query = t.Object(
|
|
135
|
-
{
|
|
136
|
-
limit: t.Optional(
|
|
137
|
-
t.Transform(t.String({ pattern: '^[1-9][0-9]{0,2}$' })).Decode((v) => Number(v)).Encode((v) => String(v))
|
|
138
|
-
),
|
|
139
|
-
},
|
|
140
|
-
{ additionalProperties: false }
|
|
141
|
-
);
|
|
142
|
-
const Canonical = t.Object({ limit: t.Optional(t.Integer({ minimum: 1, maximum: 100 })) }, { additionalProperties: false });
|
|
143
|
-
// input: inputSchema(Canonical, Query)
|
|
144
|
-
```
|
|
145
|
-
|
|
146
|
-
## Context, derive and use
|
|
147
|
-
|
|
148
|
-
Handler context: `env`, `principal` (`actorId`, `actorKind`, `organizationId`, `requestId`),
|
|
149
|
-
`authority` (`{ surface, scopes, client, token? }`, frozen; absent over ordinary RPC), `input`,
|
|
150
|
-
`operation`, `background` (`waitUntil`, best effort), and `body` for byte uploads.
|
|
151
|
-
|
|
152
|
-
```ts
|
|
153
|
-
const connected = base.derive(async ({ env, principal }) => {
|
|
154
|
-
const account = await loadAccount(env, principal.organizationId);
|
|
155
|
-
return account ? ok({ account }) : err(errors.accountNotConnected.create());
|
|
156
|
-
});
|
|
157
|
-
export const reports = connected.operation('listReports', definition, async ({ account }, input) => …);
|
|
158
|
-
```
|
|
159
|
-
|
|
160
|
-
- `.derive()` must precede `.operation()` on its chain (it throws otherwise); it runs after
|
|
161
|
-
admission and input validation; its failure ends the call.
|
|
162
|
-
- `.use(async (context, proceed) => …)`: call `proceed()` at most once and return its `Result`, or
|
|
163
|
-
return your own. Results are validated. Applies to operations declared after it.
|
|
164
|
-
- Operations that set something up (a connection) must not sit in the group that requires it.
|
|
165
|
-
- `mount` only builders from the same `maximus()` base.
|
|
166
|
-
|
|
167
|
-
## Files
|
|
168
|
-
|
|
169
|
-
Upload: `http: { method: 'PUT', path: '/v1/notes/{noteId}/attachment', body: 'bytes', headers: { contentType: 'content-type' } }`,
|
|
170
|
-
a `maxBodyBytes`, and `const bytes = await context.body.read()` (a `Result`, read once) after checking
|
|
171
|
-
the target resource. Download: `output: AttachmentOutputSchema`, `http: { …, response: 'attachment' }`,
|
|
172
|
-
return `ok({ body, contentType, filename, byteLength })`. Both are HTTP-only.
|
|
173
|
-
|
|
174
|
-
## Before you finish
|
|
175
|
-
|
|
176
|
-
- Scopes namespaced; effect truthful; strict schemas; every failure from the app's catalog.
|
|
177
|
-
- No organization in the input; tenant keys built from `principal.organizationId`.
|
|
178
|
-
- Provider and storage reads go through `checkSchema`/`readSchema`.
|
|
179
|
-
- Typecheck, tests and lint pass; `.build()` raises no `TypeError`.
|