@arbol-ai/maximus 0.0.0-stage → 7.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/LICENSE +21 -0
- package/README.md +51 -2
- package/config/oxfmt.d.mts +8 -0
- package/config/oxfmt.mjs +30 -0
- package/config/oxlint-plugin.mjs +41 -0
- package/config/oxlint.d.mts +8 -0
- package/config/oxlint.mjs +118 -0
- package/dist/analytics/analytics.d.ts +34 -0
- package/dist/analytics/analytics.js +62 -0
- package/dist/body.d.ts +2 -0
- package/dist/body.js +4 -0
- package/dist/chunks/body-BcMbreNd.js +106 -0
- package/dist/chunks/correlation-gaiEoMBr.js +45 -0
- package/dist/chunks/execution-qfZuMSIu.js +700 -0
- package/dist/chunks/json-Dwni3u4c.js +63 -0
- package/dist/chunks/record-D2H3cg8S.js +36 -0
- package/dist/chunks/schemas-q-51wBMQ.js +216 -0
- package/dist/chunks/src-Ph5KHCRP.js +1160 -0
- package/dist/chunks/telemetry-DvZgrzZn.js +220 -0
- package/dist/chunks/types-CGwAhnTE.d.ts +1630 -0
- package/dist/chunks/validation-DWxKk1Js.js +382 -0
- package/dist/client/client.d.ts +131 -0
- package/dist/client/client.js +325 -0
- package/dist/diagnostics.d.ts +41 -0
- package/dist/diagnostics.js +4 -0
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +128 -0
- package/dist/http-paths.d.ts +2 -0
- package/dist/http-paths.js +200 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +11 -0
- package/dist/internals.d.ts +2 -0
- package/dist/internals.js +5 -0
- package/dist/mcp/index.d.ts +12 -0
- package/dist/mcp/index.js +406 -0
- package/dist/postgres/index.d.ts +81 -0
- package/dist/postgres/index.js +140 -0
- package/dist/schemas.d.ts +2 -0
- package/dist/schemas.js +4 -0
- package/dist/standard-failures.d.ts +91 -0
- package/dist/standard-failures.js +75 -0
- package/dist/tooling/cli.js +110 -0
- package/dist/tooling/testing.d.ts +7 -0
- package/dist/tooling/testing.js +21 -0
- package/dist/webhooks.d.ts +69 -0
- package/dist/webhooks.js +162 -0
- package/dist/workers/runtime.d.ts +112 -0
- package/dist/workers/runtime.js +228 -0
- package/package.json +153 -4
- package/skills/maximus/SKILL.md +89 -0
- package/skills/maximus/references/adding-an-operation.md +179 -0
- package/skills/maximus/references/building-a-service.md +158 -0
- package/skills/maximus/references/errors-and-results.md +77 -0
- package/skills/maximus/references/migration-from-v2.md +62 -0
- package/skills/maximus/references/migration-to-v5.md +37 -0
- package/skills/maximus/references/publishing-and-verification.md +39 -0
- package/skills/maximus/references/testing.md +73 -0
- package/skills/maximus/references/transports.md +119 -0
- package/templates/service/.agents/skills/project/SKILL.md.template +10 -0
- package/templates/service/.github/workflows/ci.yml.template +21 -0
- package/templates/service/.gitignore.template +8 -0
- package/templates/service/CLAUDE.md.template +3 -0
- package/templates/service/README.md.template +45 -0
- package/templates/service/cloudflare.config.ts.template +30 -0
- package/templates/service/oxfmt.config.ts.template +1 -0
- package/templates/service/oxlint.config.ts.template +1 -0
- package/templates/service/package.json.template +31 -0
- package/templates/service/src/app.ts.template +30 -0
- package/templates/service/src/index.ts.template +13 -0
- package/templates/service/tests/contract.test.ts.template +12 -0
- package/templates/service/tsconfig.json.template +16 -0
- package/templates/service/vite.config.ts.template +7 -0
- package/templates/service/vitest.config.ts.template +10 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { Pool, PoolClient } from "pg";
|
|
2
|
+
//#region src/postgres/failures.d.ts
|
|
3
|
+
/** Where a transaction was when it failed. */
|
|
4
|
+
type TransactionStage = 'connect' | 'begin' | 'configure' | 'work' | 'commit';
|
|
5
|
+
/**
|
|
6
|
+
* A classified transaction failure: retryable only when the database says so, and never for a commit whose
|
|
7
|
+
* outcome is unknown.
|
|
8
|
+
*/
|
|
9
|
+
interface TransactionFailure {
|
|
10
|
+
/**
|
|
11
|
+
* The stable code callers branch on, such as `DATABASE_RETRY` for a serialization or deadlock abort, or
|
|
12
|
+
* `COMMIT_UNCERTAIN` when the commit's outcome is unknown.
|
|
13
|
+
*/
|
|
14
|
+
code: 'DATABASE_CONFLICT' | 'DATABASE_RETRY' | 'DATABASE_UNAVAILABLE' | 'COMMIT_UNCERTAIN' | 'DATABASE_FAILURE';
|
|
15
|
+
/** A fixed description of the failure, never the server's own message or the query text. */
|
|
16
|
+
message: string;
|
|
17
|
+
/** A database retry never authorizes replaying an external effect. */
|
|
18
|
+
retryable: boolean;
|
|
19
|
+
/** Where the transaction was when it failed, such as `work` while the callback ran, or `commit`. */
|
|
20
|
+
stage: TransactionStage;
|
|
21
|
+
/**
|
|
22
|
+
* The five-character SQLSTATE the server reported, such as `40001`; absent when the server reported none
|
|
23
|
+
* and for an uncertain commit.
|
|
24
|
+
*/
|
|
25
|
+
sqlState?: string;
|
|
26
|
+
}
|
|
27
|
+
/** Only server ErrorResponse instances establish a SQLSTATE; arbitrary error messages are never classified. */
|
|
28
|
+
export declare function classifyTransactionFailure(error: unknown, stage: TransactionStage): TransactionFailure;
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region src/postgres/transaction.d.ts
|
|
31
|
+
/** The organization a transaction works for, taken from the verified principal. */
|
|
32
|
+
interface TenantContext {
|
|
33
|
+
/**
|
|
34
|
+
* The trusted organization id (1 to 128 letters, digits, `_` and `-`, starting with a letter or digit) that
|
|
35
|
+
* every query in the callback must filter by; any other form is refused.
|
|
36
|
+
*/
|
|
37
|
+
readonly organizationId: string;
|
|
38
|
+
}
|
|
39
|
+
/** The time budgets, isolation level and opt-in database-only retries of a transaction. */
|
|
40
|
+
interface TransactionOptions {
|
|
41
|
+
/**
|
|
42
|
+
* How long one statement may run before Postgres aborts it (`statement_timeout`), in milliseconds from 1 to
|
|
43
|
+
* 60000.
|
|
44
|
+
*/
|
|
45
|
+
statementTimeoutMs: number;
|
|
46
|
+
/**
|
|
47
|
+
* How long a statement may wait for a lock before Postgres aborts it (`lock_timeout`), in milliseconds from
|
|
48
|
+
* 1 to 60000.
|
|
49
|
+
*/
|
|
50
|
+
lockTimeoutMs: number;
|
|
51
|
+
/**
|
|
52
|
+
* How long the transaction may wait idle for its next statement before Postgres ends the session
|
|
53
|
+
* (`idle_in_transaction_session_timeout`), in milliseconds from 1 to 60000.
|
|
54
|
+
*/
|
|
55
|
+
idleTimeoutMs: number;
|
|
56
|
+
/** The transaction's isolation level; `read committed` when absent. */
|
|
57
|
+
isolation?: 'read committed' | 'repeatable read' | 'serializable';
|
|
58
|
+
/** Opt in only when the callback performs database work exclusively. Defaults to one attempt. */
|
|
59
|
+
databaseOnlyRetry?: {
|
|
60
|
+
maxAttempts: number;
|
|
61
|
+
baseDelayMs: number;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** The work's value, or a classified failure. */
|
|
65
|
+
type TransactionResult<T> = {
|
|
66
|
+
ok: true;
|
|
67
|
+
value: T;
|
|
68
|
+
} | {
|
|
69
|
+
ok: false;
|
|
70
|
+
error: TransactionFailure;
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Run short owner SQL on one checked-out client, passing trusted tenant context explicitly.
|
|
74
|
+
* Owners enforce organization predicates and composite keys; this helper does not install RLS
|
|
75
|
+
* or pretend a session setting enforces isolation. The pool must use a restricted runtime role.
|
|
76
|
+
* Never perform provider/model/stream I/O in the callback. Unexpected callback errors retain their
|
|
77
|
+
* identity after rollback. Uncertain COMMIT never retries; reconcile by the owner's logical key.
|
|
78
|
+
*/
|
|
79
|
+
export declare function withTenantTransaction<T>(pool: Pick<Pool, 'connect'>, tenant: TenantContext, options: TransactionOptions, work: (client: PoolClient, tenant: TenantContext) => Promise<T>): Promise<TransactionResult<T>>;
|
|
80
|
+
//#endregion
|
|
81
|
+
export type { TenantContext, TransactionFailure, TransactionOptions, TransactionResult, TransactionStage };
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { setTimeout } from "node:timers/promises";
|
|
2
|
+
import { DatabaseError } from "pg";
|
|
3
|
+
|
|
4
|
+
//#region src/postgres/failures.ts
|
|
5
|
+
/**
|
|
6
|
+
* Classifies a Postgres transaction failure by the server's SQLSTATE and the stage it happened in, never
|
|
7
|
+
* by its message.
|
|
8
|
+
*/
|
|
9
|
+
/** Only server ErrorResponse instances establish a SQLSTATE; arbitrary error messages are never classified. */
|
|
10
|
+
function classifyTransactionFailure(error, stage) {
|
|
11
|
+
const sqlState = error instanceof DatabaseError && /^[0-9A-Z]{5}$/.test(error.code ?? "") ? error.code : void 0;
|
|
12
|
+
if (stage === "commit" && (!sqlState || sqlState.startsWith("08") || sqlState === "40003" || sqlState.startsWith("57"))) return {
|
|
13
|
+
code: "COMMIT_UNCERTAIN",
|
|
14
|
+
message: "Commit outcome must be reconciled before replay.",
|
|
15
|
+
retryable: false,
|
|
16
|
+
stage
|
|
17
|
+
};
|
|
18
|
+
if (sqlState === "40001" || sqlState === "40P01") return {
|
|
19
|
+
code: "DATABASE_RETRY",
|
|
20
|
+
message: "The database transaction was aborted.",
|
|
21
|
+
retryable: true,
|
|
22
|
+
stage,
|
|
23
|
+
sqlState
|
|
24
|
+
};
|
|
25
|
+
if (sqlState === "23505" || sqlState === "23503" || sqlState === "23514" || sqlState === "23P01") return {
|
|
26
|
+
code: "DATABASE_CONFLICT",
|
|
27
|
+
message: "The database constraint rejected the change.",
|
|
28
|
+
retryable: false,
|
|
29
|
+
stage,
|
|
30
|
+
sqlState
|
|
31
|
+
};
|
|
32
|
+
if (stage === "connect" || sqlState?.startsWith("08") || sqlState === "53300" || sqlState === "57P03") return {
|
|
33
|
+
code: "DATABASE_UNAVAILABLE",
|
|
34
|
+
message: "The database is unavailable.",
|
|
35
|
+
retryable: true,
|
|
36
|
+
stage,
|
|
37
|
+
...sqlState ? { sqlState } : {}
|
|
38
|
+
};
|
|
39
|
+
return {
|
|
40
|
+
code: "DATABASE_FAILURE",
|
|
41
|
+
message: "The database transaction failed.",
|
|
42
|
+
retryable: false,
|
|
43
|
+
stage,
|
|
44
|
+
...sqlState ? { sqlState } : {}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
//#endregion
|
|
49
|
+
//#region src/postgres/transaction.ts
|
|
50
|
+
/**
|
|
51
|
+
* Short tenant-scoped Postgres transactions on one checked-out client, with time budgets and opt-in
|
|
52
|
+
* database-only retries.
|
|
53
|
+
*/
|
|
54
|
+
/** A verified organization id; the same rule as the core's `OrganizationIdSchema`, which this entry does not import. */
|
|
55
|
+
const ORGANIZATION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
|
|
56
|
+
/**
|
|
57
|
+
* Refuses an organization id that is not one, time budgets outside 1 to 60000 ms, an unknown isolation level
|
|
58
|
+
* and unbounded retries.
|
|
59
|
+
*/
|
|
60
|
+
function validateOptions(tenant, options) {
|
|
61
|
+
if (!ORGANIZATION_ID.test(tenant.organizationId)) throw new TypeError("A trusted organization identifier is required.");
|
|
62
|
+
for (const value of [
|
|
63
|
+
options.statementTimeoutMs,
|
|
64
|
+
options.lockTimeoutMs,
|
|
65
|
+
options.idleTimeoutMs
|
|
66
|
+
]) if (!Number.isSafeInteger(value) || value < 1 || value > 6e4) throw new TypeError("Transaction time budgets must be between 1 and 60000 milliseconds.");
|
|
67
|
+
if (options.isolation && ![
|
|
68
|
+
"read committed",
|
|
69
|
+
"repeatable read",
|
|
70
|
+
"serializable"
|
|
71
|
+
].includes(options.isolation)) throw new TypeError("Unsupported isolation level.");
|
|
72
|
+
const retry = options.databaseOnlyRetry;
|
|
73
|
+
if (retry && (!Number.isSafeInteger(retry.maxAttempts) || retry.maxAttempts < 1 || retry.maxAttempts > 5 || !Number.isSafeInteger(retry.baseDelayMs) || retry.baseDelayMs < 1 || retry.baseDelayMs > 1e3)) throw new TypeError("Database retries require bounded attempts and delay.");
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Run short owner SQL on one checked-out client, passing trusted tenant context explicitly.
|
|
77
|
+
* Owners enforce organization predicates and composite keys; this helper does not install RLS
|
|
78
|
+
* or pretend a session setting enforces isolation. The pool must use a restricted runtime role.
|
|
79
|
+
* Never perform provider/model/stream I/O in the callback. Unexpected callback errors retain their
|
|
80
|
+
* identity after rollback. Uncertain COMMIT never retries; reconcile by the owner's logical key.
|
|
81
|
+
*/
|
|
82
|
+
async function withTenantTransaction(pool, tenant, options, work) {
|
|
83
|
+
validateOptions(tenant, options);
|
|
84
|
+
const attempts = options.databaseOnlyRetry?.maxAttempts ?? 1;
|
|
85
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
86
|
+
let client;
|
|
87
|
+
let stage = "connect";
|
|
88
|
+
let discard = false;
|
|
89
|
+
let failure;
|
|
90
|
+
try {
|
|
91
|
+
client = await pool.connect();
|
|
92
|
+
stage = "begin";
|
|
93
|
+
await client.query(`BEGIN ISOLATION LEVEL ${options.isolation ?? "read committed"}`);
|
|
94
|
+
stage = "configure";
|
|
95
|
+
await client.query("SELECT set_config('statement_timeout', $1, true), set_config('lock_timeout', $2, true), set_config('idle_in_transaction_session_timeout', $3, true)", [
|
|
96
|
+
`${options.statementTimeoutMs}ms`,
|
|
97
|
+
`${options.lockTimeoutMs}ms`,
|
|
98
|
+
`${options.idleTimeoutMs}ms`
|
|
99
|
+
]);
|
|
100
|
+
stage = "work";
|
|
101
|
+
const value = await work(client, Object.freeze({ organizationId: tenant.organizationId }));
|
|
102
|
+
stage = "commit";
|
|
103
|
+
if ((await client.query("COMMIT")).command !== "COMMIT") return {
|
|
104
|
+
ok: false,
|
|
105
|
+
error: {
|
|
106
|
+
code: "DATABASE_FAILURE",
|
|
107
|
+
message: "The database rolled back the transaction.",
|
|
108
|
+
retryable: false,
|
|
109
|
+
stage
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
return {
|
|
113
|
+
ok: true,
|
|
114
|
+
value
|
|
115
|
+
};
|
|
116
|
+
} catch (error) {
|
|
117
|
+
failure = classifyTransactionFailure(error, stage);
|
|
118
|
+
discard = failure.code === "COMMIT_UNCERTAIN" || failure.code === "DATABASE_UNAVAILABLE";
|
|
119
|
+
if (client && !discard) try {
|
|
120
|
+
await client.query("ROLLBACK");
|
|
121
|
+
} catch {
|
|
122
|
+
discard = true;
|
|
123
|
+
}
|
|
124
|
+
if (stage === "work" && failure.code === "DATABASE_FAILURE" && !failure.sqlState) throw error;
|
|
125
|
+
} finally {
|
|
126
|
+
client?.release(discard);
|
|
127
|
+
}
|
|
128
|
+
if (!failure) throw new Error("Missing transaction outcome.");
|
|
129
|
+
if (failure.code !== "DATABASE_RETRY" || discard || attempt === attempts) return {
|
|
130
|
+
ok: false,
|
|
131
|
+
error: failure
|
|
132
|
+
};
|
|
133
|
+
const base = options.databaseOnlyRetry?.baseDelayMs ?? 1;
|
|
134
|
+
await setTimeout(base * attempt + Math.floor(Math.random() * base));
|
|
135
|
+
}
|
|
136
|
+
throw new Error("Unreachable transaction attempt.");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
//#endregion
|
|
140
|
+
export { classifyTransactionFailure, withTenantTransaction };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { $ as PageQuery, A as EmptyInputSchema, B as EmailAddressSchema, Ct as decodeInput, Et as parseSchema, F as Type, G as PhoneNumberSchema, H as HttpsUrlSchema, Hn as AttachmentOutputSchema, I as UuidSchema, J as SignedUrl, K as PostalAddress, L as t, M as Static, N as StaticDecode, P as TSchema, Q as PageInfoSchema, R as DeletedObject, St as InputIssue, Tt as parseInput, U as NamedReference, V as HexColorSchema, Vn as Attachment, W as NamedReferenceSchema, X as Page, Y as SignedUrlSchema, Z as PageInfo, _t as refineSchema, at as readSchema, bt as transformSchema, ct as SchemaValidationError, dt as inputSchema, et as PageQueryFields, ft as inspectSchema, gt as pipeSchema, ht as normalizeSchema, it as checkSchema, j as OrganizationIdSchema, lt as defaultSchema, mt as looseObject, nt as pageLimit, ot as SchemaInput, pt as literalUnion, q as PostalAddressSchema, rt as Checked, st as SchemaIssue, tt as TPage, ut as extendObject, vt as strictObject, wt as decodeSchema, xt as urlSchema, yt as stripObject, z as DeletedObjectSchema } from "./chunks/types-CGwAhnTE.js";
|
|
2
|
+
export { type Attachment, AttachmentOutputSchema, type Checked, type DeletedObject, DeletedObjectSchema, EmailAddressSchema, EmptyInputSchema, HexColorSchema, HttpsUrlSchema, type InputIssue, type NamedReference, NamedReferenceSchema, OrganizationIdSchema, Page, type PageInfo, PageInfoSchema, type PageQuery, PageQueryFields, PhoneNumberSchema, type PostalAddress, PostalAddressSchema, type SchemaInput, type SchemaIssue, SchemaValidationError, type SignedUrl, SignedUrlSchema, type Static, type StaticDecode, type TPage, type TSchema, Type, UuidSchema, checkSchema, decodeInput, decodeSchema, defaultSchema, extendObject, inputSchema, inspectSchema, literalUnion, looseObject, normalizeSchema, pageLimit, parseInput, parseSchema, pipeSchema, readSchema, refineSchema, strictObject, stripObject, t, transformSchema, urlSchema };
|
package/dist/schemas.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { _ as strictObject, b as urlSchema, c as extendObject, d as inspectSchema, f as literalUnion, g as refineSchema, h as pipeSchema, i as parseSchema, m as normalizeSchema, n as decodeSchema, o as SchemaValidationError, p as looseObject, r as parseInput, s as defaultSchema, t as decodeInput, u as inputSchema, v as stripObject, y as transformSchema } from "./chunks/validation-DWxKk1Js.js";
|
|
2
|
+
import { _ as pageLimit, a as t, b as readSchema, c as HexColorSchema, d as PhoneNumberSchema, f as PostalAddressSchema, g as PageQueryFields, h as PageInfoSchema, i as UuidSchema, l as HttpsUrlSchema, m as Page, n as OrganizationIdSchema, o as DeletedObjectSchema, p as SignedUrlSchema, r as Type, s as EmailAddressSchema, t as EmptyInputSchema, u as NamedReferenceSchema, v as AttachmentOutputSchema, y as checkSchema } from "./chunks/schemas-q-51wBMQ.js";
|
|
3
|
+
|
|
4
|
+
export { AttachmentOutputSchema, DeletedObjectSchema, EmailAddressSchema, EmptyInputSchema, HexColorSchema, HttpsUrlSchema, NamedReferenceSchema, OrganizationIdSchema, Page, PageInfoSchema, PageQueryFields, PhoneNumberSchema, PostalAddressSchema, SchemaValidationError, SignedUrlSchema, Type, UuidSchema, checkSchema, decodeInput, decodeSchema, defaultSchema, extendObject, inputSchema, inspectSchema, literalUnion, looseObject, normalizeSchema, pageLimit, parseInput, parseSchema, pipeSchema, readSchema, refineSchema, strictObject, stripObject, t, transformSchema, urlSchema };
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
//#region src/standard-failures.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* `@arbol-ai/maximus/failures`: the framework's own failures as plain data: code, HTTP status,
|
|
4
|
+
* message, retryability and Retry-After. No runtime and no schema library, for a dispatcher that presents
|
|
5
|
+
* them, such as an API gateway. `defineErrors` builds their schemas from this same table.
|
|
6
|
+
*/
|
|
7
|
+
/** One of the framework's own failures. */
|
|
8
|
+
export interface StandardFailure {
|
|
9
|
+
/** The stable code clients branch on, such as `RATE_LIMITED`. */
|
|
10
|
+
readonly code: string;
|
|
11
|
+
/** The HTTP status that answers it. */
|
|
12
|
+
readonly status: number;
|
|
13
|
+
/** A fixed message for people; it never carries request data. */
|
|
14
|
+
readonly message: string;
|
|
15
|
+
/** Whether the same request may succeed later; false when absent. */
|
|
16
|
+
readonly retryable?: boolean;
|
|
17
|
+
/** The seconds a client waits before retrying, sent as `Retry-After`. */
|
|
18
|
+
readonly retryAfter?: number;
|
|
19
|
+
}
|
|
20
|
+
/** The framework's own failures, by the name `standardErrors` gives each. */
|
|
21
|
+
export declare const STANDARD_FAILURES: {
|
|
22
|
+
readonly invalidInput: {
|
|
23
|
+
readonly code: 'INVALID_INPUT';
|
|
24
|
+
readonly status: 400;
|
|
25
|
+
readonly message: 'The request does not match the published schema.';
|
|
26
|
+
};
|
|
27
|
+
readonly unauthorized: {
|
|
28
|
+
readonly code: 'UNAUTHORIZED';
|
|
29
|
+
readonly status: 401;
|
|
30
|
+
readonly message: 'A valid access token is required.';
|
|
31
|
+
};
|
|
32
|
+
readonly forbidden: {
|
|
33
|
+
readonly code: 'FORBIDDEN';
|
|
34
|
+
readonly status: 403;
|
|
35
|
+
readonly message: 'The token does not authorize this operation.';
|
|
36
|
+
};
|
|
37
|
+
readonly notFound: {
|
|
38
|
+
readonly code: 'NOT_FOUND';
|
|
39
|
+
readonly status: 404;
|
|
40
|
+
readonly message: 'The requested operation does not exist.';
|
|
41
|
+
};
|
|
42
|
+
readonly methodNotAllowed: {
|
|
43
|
+
readonly code: 'HTTP_METHOD_NOT_ALLOWED';
|
|
44
|
+
readonly status: 405;
|
|
45
|
+
readonly message: 'The HTTP method is not supported for this resource.';
|
|
46
|
+
};
|
|
47
|
+
readonly tooLarge: {
|
|
48
|
+
readonly code: 'REQUEST_TOO_LARGE';
|
|
49
|
+
readonly status: 413;
|
|
50
|
+
readonly message: 'The request exceeds the allowed size.';
|
|
51
|
+
};
|
|
52
|
+
readonly unsupportedMedia: {
|
|
53
|
+
readonly code: 'UNSUPPORTED_MEDIA_TYPE';
|
|
54
|
+
readonly status: 415;
|
|
55
|
+
readonly message: 'The request content type is not supported.';
|
|
56
|
+
};
|
|
57
|
+
readonly rateLimited: {
|
|
58
|
+
readonly code: 'RATE_LIMITED';
|
|
59
|
+
readonly status: 429;
|
|
60
|
+
readonly message: 'The request rate limit was exceeded. Try again later.';
|
|
61
|
+
readonly retryable: true;
|
|
62
|
+
readonly retryAfter: 60;
|
|
63
|
+
};
|
|
64
|
+
readonly internal: {
|
|
65
|
+
readonly code: 'INTERNAL_ERROR';
|
|
66
|
+
readonly status: 500;
|
|
67
|
+
readonly message: 'The service could not complete the operation.';
|
|
68
|
+
};
|
|
69
|
+
readonly upstreamUnavailable: {
|
|
70
|
+
readonly code: 'UPSTREAM_UNAVAILABLE';
|
|
71
|
+
readonly status: 503;
|
|
72
|
+
readonly message: 'The upstream service could not complete the request.';
|
|
73
|
+
readonly retryable: true;
|
|
74
|
+
};
|
|
75
|
+
readonly upstreamTimeout: {
|
|
76
|
+
readonly code: 'UPSTREAM_TIMEOUT';
|
|
77
|
+
readonly status: 504;
|
|
78
|
+
readonly message: 'The upstream service did not respond before its deadline.';
|
|
79
|
+
readonly retryable: true;
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* A write may have been applied and its answer was lost. Never retried: the caller reconciles (reads
|
|
83
|
+
* the resource or polls the operation) before deciding to repeat anything.
|
|
84
|
+
*/
|
|
85
|
+
readonly outcomeUnknown: {
|
|
86
|
+
readonly code: 'OUTCOME_UNKNOWN';
|
|
87
|
+
readonly status: 502;
|
|
88
|
+
readonly message: 'The operation may have been applied; check its result before repeating it.';
|
|
89
|
+
};
|
|
90
|
+
};
|
|
91
|
+
//#endregion
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
//#region 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
|
+
//#endregion
|
|
75
|
+
export { STANDARD_FAILURES };
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from "node:util";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
4
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
6
|
+
|
|
7
|
+
//#region src/tooling/internal/scaffold.ts
|
|
8
|
+
/**
|
|
9
|
+
* `maximus init`: a new service from the starter template.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* The Maximus package's own directory: the nearest one above this module with a package.json. The
|
|
13
|
+
* build bundles this module into the CLI, so its depth below the package differs from the source's.
|
|
14
|
+
*/
|
|
15
|
+
function packageDirectory() {
|
|
16
|
+
let directory = import.meta.dirname;
|
|
17
|
+
while (!existsSync(join(directory, "package.json"))) {
|
|
18
|
+
const parent = dirname(directory);
|
|
19
|
+
if (parent === directory) throw new Error("Found no package.json above the Maximus CLI.");
|
|
20
|
+
directory = parent;
|
|
21
|
+
}
|
|
22
|
+
return directory;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* `maximus init`: writes a new service from the starter template into a directory that does not exist yet.
|
|
26
|
+
*/
|
|
27
|
+
function scaffold(directory, name) {
|
|
28
|
+
if (!/^(?=.{2,41}$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name)) throw new TypeError("Use a lowercase kebab-case project name of 2 to 41 characters.");
|
|
29
|
+
const root = resolve(directory);
|
|
30
|
+
if (existsSync(root)) throw new Error("Choose a new directory; existing projects are never overwritten.");
|
|
31
|
+
const own = packageDirectory();
|
|
32
|
+
const template = join(own, "templates", "service");
|
|
33
|
+
const { version } = JSON.parse(readFileSync(join(own, "package.json"), "utf-8"));
|
|
34
|
+
const values = {
|
|
35
|
+
__PROJECT_NAME__: name,
|
|
36
|
+
__ENTRYPOINT__: `${name.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("")}Service`,
|
|
37
|
+
__MAXIMUS_VERSION__: version
|
|
38
|
+
};
|
|
39
|
+
for (const file of readdirSync(template, {
|
|
40
|
+
recursive: true,
|
|
41
|
+
withFileTypes: true
|
|
42
|
+
})) {
|
|
43
|
+
if (!file.isFile() || !file.name.endsWith(".template")) continue;
|
|
44
|
+
const source = resolve(file.parentPath, file.name);
|
|
45
|
+
const target = resolve(root, relative(template, source).replace(/\.template$/, ""));
|
|
46
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
47
|
+
let text = readFileSync(source, "utf-8");
|
|
48
|
+
for (const [placeholder, value] of Object.entries(values)) text = text.replaceAll(placeholder, value);
|
|
49
|
+
writeFileSync(target, text, { flag: "wx" });
|
|
50
|
+
}
|
|
51
|
+
writeFileSync(resolve(root, ".dev.vars"), `DEVELOPMENT_TOKEN=${randomBytes(32).toString("hex")}\n`, {
|
|
52
|
+
flag: "wx",
|
|
53
|
+
mode: 384
|
|
54
|
+
});
|
|
55
|
+
symlinkSync("CLAUDE.md", resolve(root, "AGENTS.md"));
|
|
56
|
+
for (const harness of [".claude", ".codex"]) {
|
|
57
|
+
mkdirSync(resolve(root, harness, "skills"), { recursive: true });
|
|
58
|
+
symlinkSync("../../.agents/skills/project", resolve(root, harness, "skills/project"));
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
directory: root,
|
|
62
|
+
next: "Run bun install and bun run dev, and call it with the DEVELOPMENT_TOKEN in .dev.vars. Before the first deployment, set origin, audience and issuer in src/app.ts, run bun run verify, sign in with cf auth login and run bun run deploy."
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
//#endregion
|
|
67
|
+
//#region src/tooling/cli.ts
|
|
68
|
+
/**
|
|
69
|
+
* The `maximus` command: `init` creates a new service. Developing, building and deploying it are `cf`'s own
|
|
70
|
+
* commands, which Maximus does not wrap.
|
|
71
|
+
*/
|
|
72
|
+
const { values, positionals } = parseArgs({
|
|
73
|
+
allowPositionals: true,
|
|
74
|
+
options: {
|
|
75
|
+
name: { type: "string" },
|
|
76
|
+
help: {
|
|
77
|
+
type: "boolean",
|
|
78
|
+
default: false
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
const [command, target] = positionals;
|
|
83
|
+
/** The help the command prints for `--help` or a usage mistake. */
|
|
84
|
+
const USAGE = [
|
|
85
|
+
"Usage: maximus init <new-directory> --name <name>",
|
|
86
|
+
"Creates a new service. Develop, build and deploy it with cf: cf dev, cf build, cf workers types and",
|
|
87
|
+
"cf deploy."
|
|
88
|
+
].join("\n");
|
|
89
|
+
if (values.help) {
|
|
90
|
+
console.info(USAGE);
|
|
91
|
+
process.exit(0);
|
|
92
|
+
}
|
|
93
|
+
/** Runs the command the arguments name. */
|
|
94
|
+
function run() {
|
|
95
|
+
if (command !== "init") {
|
|
96
|
+
console.error(USAGE);
|
|
97
|
+
process.exitCode = 1;
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (!target || !values.name) throw new TypeError("Use maximus init <new-directory> --name <name>.");
|
|
101
|
+
console.info(JSON.stringify(scaffold(target, values.name)));
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
run();
|
|
105
|
+
} catch (error) {
|
|
106
|
+
console.error(error instanceof Error && !process.env.MAXIMUS_DEBUG ? `maximus: ${error.message}` : error);
|
|
107
|
+
process.exitCode = 1;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
//#endregion
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
//#region src/tooling/testing.d.ts
|
|
2
|
+
/** One deployed contract smoke; security and protocol matrices remain framework tests. */
|
|
3
|
+
export declare function verifyContract(fetch: (request: Request) => Promise<Response>, origin: string): Promise<{
|
|
4
|
+
paths: string[];
|
|
5
|
+
operations: string[];
|
|
6
|
+
}>;
|
|
7
|
+
//#endregion
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { parse } from "yaml";
|
|
2
|
+
|
|
3
|
+
//#region src/tooling/testing.ts
|
|
4
|
+
/**
|
|
5
|
+
* `@arbol-ai/maximus/testing`: a contract smoke test for a local or deployed service.
|
|
6
|
+
*/
|
|
7
|
+
/** One deployed contract smoke; security and protocol matrices remain framework tests. */
|
|
8
|
+
async function verifyContract(fetch, origin) {
|
|
9
|
+
const json = await fetch(new Request(`${origin}/openapi.json`));
|
|
10
|
+
const yaml = await fetch(new Request(`${origin}/openapi.yaml`));
|
|
11
|
+
if (!json.ok || !yaml.ok) throw new Error("OpenAPI is unavailable.");
|
|
12
|
+
const schema = await json.json();
|
|
13
|
+
if (JSON.stringify(schema) !== JSON.stringify(parse(await yaml.text()))) throw new Error("OpenAPI JSON/YAML differ.");
|
|
14
|
+
return {
|
|
15
|
+
paths: Object.keys(schema.paths),
|
|
16
|
+
operations: Object.values(schema.paths).flatMap((path) => Object.values(path).map((op) => op.operationId))
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
//#endregion
|
|
21
|
+
export { verifyContract };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { bn as Result, kn as Failure } from "./chunks/types-CGwAhnTE.js";
|
|
2
|
+
//#region src/webhooks.d.ts
|
|
3
|
+
/** Why a webhook signature was refused: absent, malformed, outside the time tolerance, or not matching. */
|
|
4
|
+
export declare const WEBHOOK_SIGNATURE_FAILURES: readonly ['missing', 'malformed', 'expired', 'mismatch'];
|
|
5
|
+
/** Why a webhook signature was refused. */
|
|
6
|
+
export type WebhookSignatureFailureReason = (typeof WEBHOOK_SIGNATURE_FAILURES)[number];
|
|
7
|
+
/** A refused webhook signature, carrying only its reason. */
|
|
8
|
+
export interface WebhookSignatureFailure extends Failure<{
|
|
9
|
+
reason: WebhookSignatureFailureReason;
|
|
10
|
+
}> {
|
|
11
|
+
/**
|
|
12
|
+
* The one code of every refused signature; `data.reason` says whether it was missing, malformed, expired or
|
|
13
|
+
* mismatched.
|
|
14
|
+
*/
|
|
15
|
+
code: 'WEBHOOK_SIGNATURE_INVALID';
|
|
16
|
+
}
|
|
17
|
+
/** The failure for a refused webhook signature. */
|
|
18
|
+
export declare function webhookSignatureFailure(reason: WebhookSignatureFailureReason): WebhookSignatureFailure;
|
|
19
|
+
/** Five minutes either way, the Standard Webhooks recommendation. */
|
|
20
|
+
export declare const DEFAULT_TOLERANCE_SECONDS = 300;
|
|
21
|
+
/**
|
|
22
|
+
* The most signatures one header may carry. A provider rotating its secret sends two or three, and each
|
|
23
|
+
* costs an HMAC of the whole body, so a header with more is refused as malformed before any is computed.
|
|
24
|
+
*/
|
|
25
|
+
export declare const MAX_SIGNATURES = 8;
|
|
26
|
+
/**
|
|
27
|
+
* Verify an HMAC-SHA256 of the raw body. `signature` is the header value,
|
|
28
|
+
* optionally with a scheme prefix such as `sha256=` (removed with `prefix`).
|
|
29
|
+
*/
|
|
30
|
+
export declare function verifyHmacSignature(options: {
|
|
31
|
+
body: string | Uint8Array;
|
|
32
|
+
encoding: 'hex' | 'base64';
|
|
33
|
+
prefix?: string;
|
|
34
|
+
secret: string | Uint8Array;
|
|
35
|
+
signature: string | null | undefined;
|
|
36
|
+
}): Promise<Result<null, WebhookSignatureFailure>>;
|
|
37
|
+
/**
|
|
38
|
+
* Verify a `t=<unix seconds>,v0=<hex>` header (several `v0`/`v1` values may be
|
|
39
|
+
* present during secret rotation, up to {@link MAX_SIGNATURES}; one match is
|
|
40
|
+
* enough) signing `<t>.<body>`.
|
|
41
|
+
*/
|
|
42
|
+
export declare function verifyTimestampedSignature(options: {
|
|
43
|
+
body: string | Uint8Array;
|
|
44
|
+
header: string | null | undefined;
|
|
45
|
+
/** The signature labels to accept, for example `['v1']` or `['v0']`. */
|
|
46
|
+
labels: readonly string[];
|
|
47
|
+
now?: () => number;
|
|
48
|
+
secret: string | Uint8Array;
|
|
49
|
+
toleranceSeconds?: number;
|
|
50
|
+
}): Promise<Result<{
|
|
51
|
+
timestamp: number;
|
|
52
|
+
}, WebhookSignatureFailure>>;
|
|
53
|
+
/**
|
|
54
|
+
* Verify a Standard Webhooks delivery. The secret is the provider's
|
|
55
|
+
* `whsec_<base64>` value (the prefix is optional), and the signature header may
|
|
56
|
+
* list up to {@link MAX_SIGNATURES} signatures. Returns the message id, the
|
|
57
|
+
* idempotency key of the delivery, and its timestamp.
|
|
58
|
+
*/
|
|
59
|
+
export declare function verifyStandardWebhook(options: {
|
|
60
|
+
body: string | Uint8Array;
|
|
61
|
+
headers: Pick<Headers, 'get'>;
|
|
62
|
+
now?: () => number;
|
|
63
|
+
secret: string;
|
|
64
|
+
toleranceSeconds?: number;
|
|
65
|
+
}): Promise<Result<{
|
|
66
|
+
id: string;
|
|
67
|
+
timestamp: number;
|
|
68
|
+
}, WebhookSignatureFailure>>;
|
|
69
|
+
//#endregion
|