@aotter/mantle 0.2.0-alpha.9 → 0.2.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 +9 -3
- package/dist/auth/adapter.js +1 -28
- package/dist/auth/admin.js +2 -5
- package/dist/auth/caller.js +0 -27
- package/dist/auth/consent.js +100 -0
- package/dist/auth/hardening.js +0 -7
- package/dist/auth/identity.js +0 -11
- package/dist/auth/oauth.js +0 -32
- package/dist/auth/resource-seeds.js +0 -2
- package/dist/auth/route-http.js +33 -0
- package/dist/auth/routes.js +5 -151
- package/dist/build/compiler.d.ts +19 -609
- package/dist/build/compiler.js +3 -6896
- package/dist/build/spec/domain/model/SqlIr.d.ts +2 -0
- package/dist/build/spec/domain/model/UserFields.d.ts +1 -0
- package/dist/bun/assets.js +0 -2
- package/dist/domain/adminOrder.js +0 -2
- package/dist/domain/columns.js +7 -20
- package/dist/domain/describe/chunk-SGMRVDGE.js +1 -0
- package/dist/domain/describe/index.js +1 -115
- package/dist/domain/describe/target-hash.js +1 -12
- package/dist/domain/entry.js +0 -14
- package/dist/domain/generated-tools.js +0 -1
- package/dist/domain/input.js +0 -2
- package/dist/domain/paging.js +0 -17
- package/dist/domain/recipes.js +10 -7
- package/dist/domain/userReferences.js +0 -1
- package/dist/domain/wireScalars.js +0 -6
- package/dist/infrastructure/adminEntries.js +10 -7
- package/dist/infrastructure/adminPaging.js +55 -57
- package/dist/infrastructure/artifacts.js +0 -4
- package/dist/infrastructure/authSchema.js +0 -9
- package/dist/infrastructure/bundle.js +2 -30
- package/dist/infrastructure/cli.js +25 -11
- package/dist/infrastructure/generate.js +9 -16
- package/dist/infrastructure/generateAuth.js +1 -9
- package/dist/infrastructure/help.js +55 -0
- package/dist/infrastructure/init.js +50 -0
- package/dist/infrastructure/inputs.js +0 -9
- package/dist/infrastructure/mounts.js +22 -0
- package/dist/infrastructure/wrangler.js +0 -6
- package/dist/kernel/authorization.js +0 -1
- package/dist/kernel/binds.d.ts +16 -4
- package/dist/kernel/binds.js +4 -10
- package/dist/kernel/caller-identity.d.ts +0 -3
- package/dist/kernel/caller-identity.js +0 -15
- package/dist/kernel/caller-mode.d.ts +4 -0
- package/dist/kernel/caller-mode.js +14 -0
- package/dist/kernel/contracts.d.ts +6 -10
- package/dist/kernel/contracts.js +5 -41
- package/dist/kernel/cron.js +0 -4
- package/dist/kernel/dialect/common.js +0 -3
- package/dist/kernel/dialect/postgres.js +0 -2
- package/dist/kernel/dialect/sqlite.js +1 -6
- package/dist/kernel/drain.js +2 -8
- package/dist/kernel/driver/bun-sqlite.js +0 -4
- package/dist/kernel/driver/d1.js +0 -1
- package/dist/kernel/driver/postgres.js +2 -17
- package/dist/kernel/driver/transaction-context.js +0 -1
- package/dist/kernel/email.js +0 -4
- package/dist/kernel/host-access.js +2 -3
- package/dist/kernel/host-caller.d.ts +1 -1
- package/dist/kernel/host-caller.js +3 -6
- package/dist/kernel/json-body.js +0 -2
- package/dist/kernel/mcp-apps.js +0 -5
- package/dist/kernel/mcp-call.js +0 -1
- package/dist/kernel/mcp-handler.js +2 -26
- package/dist/kernel/mcp.js +0 -5
- package/dist/kernel/media.js +0 -18
- package/dist/kernel/paging.js +1 -9
- package/dist/kernel/publishing.js +3 -4
- package/dist/kernel/r2-media.js +0 -7
- package/dist/kernel/rest-dispatch.js +0 -1
- package/dist/kernel/rest-router.js +2 -3
- package/dist/kernel/rest.js +0 -3
- package/dist/kernel/scalars.js +1 -9
- package/dist/kernel/search.js +0 -1
- package/dist/kernel/site.js +0 -2
- package/dist/kernel/store.d.ts +11 -1
- package/dist/kernel/store.js +21 -34
- package/dist/kernel/surface-failure.d.ts +10 -0
- package/dist/kernel/surface-failure.js +29 -0
- package/dist/kernel/surface.js +0 -3
- package/dist/kernel/sweep.js +0 -1
- package/dist/kernel/translations.js +0 -1
- package/dist/kernel/user-caller.js +2 -8
- package/dist/kernel/user-fields.d.ts +3 -2
- package/dist/kernel/user-fields.js +9 -9
- package/dist/kernel/validation.js +0 -8
- package/dist/kernel/web-gateway.js +0 -2
- package/dist/kernel/web-head.js +0 -1
- package/dist/kernel/web-index.js +0 -1
- package/dist/kernel/web-response.js +0 -1
- package/dist/kernel/web-serve.js +97 -0
- package/dist/kernel/web.d.ts +1 -1
- package/dist/kernel/web.js +10 -91
- package/dist/kernel/where.js +0 -6
- package/dist/usecase/adminBindings.js +30 -21
- package/dist/usecase/adminClient.js +0 -21
- package/dist/usecase/adminDescriptors.js +2 -9
- package/dist/usecase/generate.js +7 -12
- package/dist/usecase/handlers.js +0 -3
- package/dist/usecase/mcp-media.js +0 -1
- package/dist/usecase/mcp.js +0 -4
- package/dist/usecase/paging.js +1 -3
- package/dist/usecase/publishing.js +0 -4
- package/dist/usecase/rest.js +0 -1
- package/dist/usecase/site.js +0 -1
- package/dist/usecase/stores.js +4 -14
- package/dist/usecase/tool-version.js +0 -3
- package/dist/usecase/translations.js +0 -2
- package/dist/usecase/validation.js +0 -20
- package/docs/examples/README.md +13 -5
- package/docs/examples/app-shell/README.md +38 -7
- package/docs/examples/app-shell/accept.mjs +91 -0
- package/docs/examples/app-shell/gitignore +7 -0
- package/docs/examples/app-shell/package.json +7 -6
- package/docs/examples/app-shell/smoke-kit.mjs +29 -15
- package/docs/examples/app-shell/src/routes.ts +6 -3
- package/docs/examples/app-shell/src/service.ts +2 -1
- package/docs/examples/club-events/README.md +7 -2
- package/docs/examples/club-events/manifests/club-events.yaml +15 -0
- package/docs/examples/club-events/smoke.mjs +7 -1
- package/docs/examples/purchasing/README.md +12 -3
- package/docs/examples/purchasing/manifests/purchasing.yaml +21 -4
- package/docs/examples/purchasing/smoke.mjs +14 -0
- package/docs/examples/recipes/README.md +5 -3
- package/docs/handbook/cloudflare/service-entry.md +3 -0
- package/docs/handbook/examples/hub.md +1 -1
- package/docs/handbook/guides/agent-setup.md +15 -10
- package/docs/handbook/guides/agent-workflow-acceptance.md +113 -103
- package/docs/handbook/guides/local-testing.md +40 -0
- package/docs/handbook/guides/native-admin.md +25 -6
- package/docs/handbook/guides/native-execution.md +5 -4
- package/docs/handbook/guides/public-pages.md +44 -4
- package/docs/handbook/guides/sql-patterns.md +266 -0
- package/docs/handbook/guides/typed-queries.md +138 -0
- package/docs/handbook/navigation.json +16 -0
- package/docs/handbook/reference/admin-descriptors.md +4 -1
- package/docs/handbook/reference/authorization.md +1 -1
- package/docs/handbook/reference/diagnostics.md +6 -1
- package/docs/handbook/reference/procedure.md +5 -5
- package/docs/handbook/reference/schema.md +10 -4
- package/docs/handbook/reference/sql.md +64 -0
- package/docs/handbook/reference/surface.md +5 -2
- package/docs/handbook/reference/view.md +11 -3
- package/docs/handbook/releases/index.md +27 -6
- package/docs/handbook/start/agents.md +45 -0
- package/docs/handbook/start/project-and-cli.md +6 -0
- package/docs/handbook/start/quickstart-worker.md +1 -1
- package/docs/skills/develop/SKILL.md +6 -5
- package/docs/skills/update/SKILL.md +2 -0
- package/package.json +23 -3
- package/skills/README.md +1 -1
- package/skills/mantle/SKILL.md +39 -120
- package/dist/domain/describe/chunk-ZVXBGP7Y.js +0 -424
- package/skills/mantle/references/local-testing.md +0 -20
- package/skills/mantle/references/web.md +0 -41
- package/skills/mantle/references/website.md +0 -51
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
/** Request-only gateway decisions and observation; no database or compiler dependencies. */
|
|
2
1
|
import { forwarded, ContractError, wire } from "./contracts.js";
|
|
3
|
-
import { isHostCaller
|
|
2
|
+
import { isHostCaller } from "./caller-identity.js";
|
|
3
|
+
import { checkFresh } from "./caller-mode.js";
|
|
4
4
|
const logged = new WeakSet();
|
|
5
5
|
export function accessRequest(ctx, options) {
|
|
6
6
|
const present = forwarded(ctx);
|
|
@@ -43,7 +43,6 @@ export function accessRequest(ctx, options) {
|
|
|
43
43
|
logged.add(listener);
|
|
44
44
|
console.error("[mantle onAccess] listener failed");
|
|
45
45
|
} };
|
|
46
|
-
// Schedule observation after the decision without awaiting its promise.
|
|
47
46
|
queueMicrotask(() => { try {
|
|
48
47
|
void Promise.resolve(listener(finished)).catch(log);
|
|
49
48
|
}
|
|
@@ -36,4 +36,4 @@ export declare function gatewayCaller(ctx: RequestContext | undefined, gateway:
|
|
|
36
36
|
/** Host errors are machine-readable and never challenge for application credentials. */
|
|
37
37
|
export declare function hostFailure(error: unknown, caller?: Caller, where?: string, challenge?: string): Response;
|
|
38
38
|
export { isHostCaller } from "./caller-identity.js";
|
|
39
|
-
export { checkFresh } from "./caller-
|
|
39
|
+
export { checkFresh } from "./caller-mode.js";
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
/** Request-only host contract validation. */
|
|
2
1
|
export { draining } from "./drain.js";
|
|
3
|
-
import { forwarded, ContractError
|
|
2
|
+
import { forwarded, ContractError } from "./contracts.js";
|
|
3
|
+
import { surfaceError, surfaceFailure } from "./surface-failure.js";
|
|
4
4
|
import { userCaller } from "./user-caller.js";
|
|
5
5
|
import { identities, isHostCaller } from "./caller-identity.js";
|
|
6
6
|
const hostContract = (message, field) => { throw new ContractError("HOST_CONTRACT", message, "", { status: 412, fields: field ? { field } : undefined }); };
|
|
7
|
-
/** Validate the forwarding contract and reuse the ordinary user validation and brand. */
|
|
8
7
|
export function hostCaller(props, options) {
|
|
9
8
|
const record = (v) => !!v && typeof v === "object" && !Array.isArray(v) && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
|
|
10
9
|
const text = (v) => typeof v === "string" && v.length > 0 && !v.includes("\0") && v.isWellFormed();
|
|
@@ -35,7 +34,6 @@ export function hostCaller(props, options) {
|
|
|
35
34
|
identities.set(caller, Object.freeze({ ...identities.get(base), admin: caller.admin, host: true }));
|
|
36
35
|
return caller;
|
|
37
36
|
}
|
|
38
|
-
/** Resolve only forwarded props, or trip on an entry that did not opt in. */
|
|
39
37
|
export function gatewayCaller(ctx, gateway, fields) {
|
|
40
38
|
const present = forwarded(ctx);
|
|
41
39
|
if (!gateway)
|
|
@@ -44,7 +42,6 @@ export function gatewayCaller(ctx, gateway, fields) {
|
|
|
44
42
|
return { kind: 'anonymous' };
|
|
45
43
|
return hostCaller(ctx.props.mantle, { tenant: gateway.tenant, fields });
|
|
46
44
|
}
|
|
47
|
-
/** Host errors are machine-readable and never challenge for application credentials. */
|
|
48
45
|
export function hostFailure(error, caller, where, challenge) {
|
|
49
46
|
if ((!caller || !isHostCaller(caller)) && !(error instanceof ContractError && error.code === 'HOST_CONTRACT'))
|
|
50
47
|
return surfaceFailure(error, challenge, where);
|
|
@@ -53,4 +50,4 @@ export function hostFailure(error, caller, where, challenge) {
|
|
|
53
50
|
return Response.json({ error: { code, ...(typeof result.error.field === 'string' ? { field: result.error.field } : {}), ...(result.error.path ? { target: result.error.path } : {}) } }, { status: result.status === 401 ? 403 : result.status, headers: { 'cache-control': 'private, no-store' } });
|
|
54
51
|
}
|
|
55
52
|
export { isHostCaller } from "./caller-identity.js";
|
|
56
|
-
export { checkFresh } from "./caller-
|
|
53
|
+
export { checkFresh } from "./caller-mode.js";
|
package/dist/kernel/json-body.js
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
/** Request-only JSON reader: bound bytes before copying or parsing, independent of UTF-8 chunk boundaries. */
|
|
2
|
-
/** Bound raw bytes before decoding a request body. */
|
|
3
1
|
export async function bytes(request, limit, fail) {
|
|
4
2
|
if (!Number.isSafeInteger(limit) || limit < 1)
|
|
5
3
|
fail("Body limit must be a positive safe integer.");
|
package/dist/kernel/mcp-apps.js
CHANGED
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import { ContractError } from "./contracts.js";
|
|
2
|
-
/** MCP Apps (ADR-0029 D7): UI resources served beside the tools that render in them. */
|
|
3
2
|
export const RESOURCE_MIME_TYPE = "text/html;profile=mcp-app";
|
|
4
|
-
/** Flatten contributors; `mcp(...)` reads static resources getters once at construction. */
|
|
5
3
|
export const resourcesOf = (apps) => ({ resources: (Array.isArray(apps) ? apps : [apps]).flatMap(app => app.resources) });
|
|
6
|
-
/** Static contributors are checked at construction; resolved factories are checked per request. A request-bound tool table defers tool-link checks until its first request. */
|
|
7
4
|
export function linkApps(apps, tools, views) {
|
|
8
5
|
const resources = resourcesOf(apps).resources;
|
|
9
6
|
const uris = new Set(), names = new Set(), renders = new Map(), appOnly = new Set();
|
|
@@ -24,7 +21,6 @@ export function linkApps(apps, tools, views) {
|
|
|
24
21
|
refuse(`Tool '${tool}' is claimed by two MCP App resources.`);
|
|
25
22
|
renders.set(tool, resource.uri);
|
|
26
23
|
}
|
|
27
|
-
// an App acts for the user without the model seeing the call, so only a read may be hidden from the model
|
|
28
24
|
for (const tool of resource.appOnly ?? []) {
|
|
29
25
|
if (views && !views.has(tool))
|
|
30
26
|
refuse(`App-only tool '${tool}' must be a View this endpoint serves.`);
|
|
@@ -33,7 +29,6 @@ export function linkApps(apps, tools, views) {
|
|
|
33
29
|
}
|
|
34
30
|
return { resources, renders, appOnly };
|
|
35
31
|
}
|
|
36
|
-
/** One endpoint's Apps bound to its tool table; `previous` is reused while the table's names are unchanged. */
|
|
37
32
|
export function linkSurface(apps, selected, previous) {
|
|
38
33
|
const key = JSON.stringify(selected.map(tool => [tool.name, !!tool.page]).sort(([a], [b]) => a.localeCompare(b)));
|
|
39
34
|
return previous?.key === key ? previous : { key, links: linkApps(apps, new Set(selected.map(tool => tool.name)), new Set(selected.filter(tool => tool.page).map(tool => tool.name))) };
|
package/dist/kernel/mcp-call.js
CHANGED
|
@@ -3,7 +3,6 @@ import { checkPageLimit } from "./paging.js";
|
|
|
3
3
|
export async function callTool(tool, raw, db, caller, handlers) {
|
|
4
4
|
return callToolLazy(tool, raw, () => db, caller, handlers);
|
|
5
5
|
}
|
|
6
|
-
/** Transport input is checked before acquiring an application-owned native handle. */
|
|
7
6
|
export async function callToolLazy(tool, raw, getDb, caller, handlers, dryRun) {
|
|
8
7
|
if (tool.page) {
|
|
9
8
|
const { limit, cursor, ...input } = raw;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
/** Request-only MCP implementation, excluded from Worker startup. */
|
|
2
1
|
import { authorized, authorizeTarget } from "./authorization.js";
|
|
3
|
-
import { forwarded, isAdmin, ContractError,
|
|
2
|
+
import { forwarded, isAdmin, ContractError, wire } from "./contracts.js";
|
|
3
|
+
import { checkOrigin, surfaceCaller, surfaceError } from "./surface-failure.js";
|
|
4
4
|
import { draining } from "./drain.js";
|
|
5
5
|
import { callToolLazy as callTool } from "./mcp-call.js";
|
|
6
6
|
import { RESOURCE_MIME_TYPE, linkSurface, resourcesOf } from "./mcp-apps.js";
|
|
@@ -19,15 +19,8 @@ function observe(listener, event) {
|
|
|
19
19
|
catch { }
|
|
20
20
|
}
|
|
21
21
|
const paging = (schema) => ({ ...schema, properties: { ...schema.properties, limit: { type: "integer", minimum: 1, maximum: 500 }, cursor: { type: "string" } } });
|
|
22
|
-
/**
|
|
23
|
-
* Characters of `JSON.stringify(page)` an MCP View page may hold. A result carries its rows twice (text block and
|
|
24
|
-
* `structuredContent`) and hosts are reported to truncate near 150k characters, so one copy stays at 60k.
|
|
25
|
-
* ponytail: one fixed number; raise it or make it an option if hosts publish their limits.
|
|
26
|
-
*/
|
|
27
22
|
const MCP_PAGE_BUDGET = 60_000;
|
|
28
|
-
/** The scopes a challenge asks for: the credential's, plus what the request needs. */
|
|
29
23
|
const union = (scopes, extra) => [...new Set([...scopes, ...extra])].join(" ");
|
|
30
|
-
/** The handler for `/mcp` (public tools) and `/mcp/admin` (tools for `admin` roles); other paths are undefined. */
|
|
31
24
|
export function handler(tools, options, apps = {}, reads = []) {
|
|
32
25
|
const allowed = options.allowedOrigins ?? [];
|
|
33
26
|
return draining(async (request, env, ctx) => {
|
|
@@ -38,8 +31,6 @@ export function handler(tools, options, apps = {}, reads = []) {
|
|
|
38
31
|
const url = new URL(request.url), path = url.pathname.replace(/\/+$/, ""), surface = path === "/mcp" ? "public" : path === "/mcp/admin" ? "admin" : undefined;
|
|
39
32
|
if (!surface)
|
|
40
33
|
return;
|
|
41
|
-
// MCP transport MUST: a present Origin is a browser, answered only for loopback or `allowedOrigins`. The request's own
|
|
42
|
-
// host is not implied, since a DNS-rebinding page sends Origin == its rebound Host; a missing Origin is a server client.
|
|
43
34
|
if (request.headers.has("origin")) {
|
|
44
35
|
const sdk = await import("@modelcontextprotocol/server");
|
|
45
36
|
const foreign = sdk.originValidationResponse(request, [...sdk.localhostAllowedOrigins(), ...allowed]);
|
|
@@ -51,7 +42,6 @@ export function handler(tools, options, apps = {}, reads = []) {
|
|
|
51
42
|
}
|
|
52
43
|
}
|
|
53
44
|
const select = async () => (typeof tools === "function" ? await tools(request, env) : tools).filter(tool => tool.surface === surface);
|
|
54
|
-
// Dynamic admin tables stay behind the admin gate; cache classification uses generated metadata only.
|
|
55
45
|
let selected = surface === "public" ? await select() : [];
|
|
56
46
|
let parsedBody, tooLarge = false;
|
|
57
47
|
const cookieOnly = request.headers.has("cookie") && !request.headers.has("authorization");
|
|
@@ -120,7 +110,6 @@ export function handler(tools, options, apps = {}, reads = []) {
|
|
|
120
110
|
}
|
|
121
111
|
if (surface === "admin")
|
|
122
112
|
selected = await select();
|
|
123
|
-
// Before per-caller filtering, so every caller of a deploy sees one catalogue version.
|
|
124
113
|
const version = catalogueVersion(selected);
|
|
125
114
|
const { McpServer, ProtocolError, ProtocolErrorCode, createMcpHandler, fromJsonSchema } = await import("@modelcontextprotocol/server");
|
|
126
115
|
if (request.method === "POST" && !cookieOnly && !options.gateway)
|
|
@@ -176,7 +165,6 @@ export function handler(tools, options, apps = {}, reads = []) {
|
|
|
176
165
|
const sources = (Array.isArray(app) ? app : [app]);
|
|
177
166
|
const dynamic = sources.some(source => typeof source === "function");
|
|
178
167
|
const resolved = resourcesOf(await Promise.all(sources.map(source => typeof source === "function" ? source({ env, request }) : source)));
|
|
179
|
-
// Equal tool names say nothing about request-bound resource identity or ownership.
|
|
180
168
|
const current = linkSurface(resolved, selected, dynamic ? undefined : apps[surface]);
|
|
181
169
|
if (!dynamic)
|
|
182
170
|
apps[surface] = current;
|
|
@@ -193,7 +181,6 @@ export function handler(tools, options, apps = {}, reads = []) {
|
|
|
193
181
|
tool.check?.(caller);
|
|
194
182
|
await authorizeTarget(options.authorize, tool.target ?? { kind: tool.page ? "view" : "procedure", name: tool.name }, caller);
|
|
195
183
|
}
|
|
196
|
-
// an App's HTML is rendered for the same tools the caller's tools/list shows
|
|
197
184
|
if ((Array.isArray(parsedBody) ? parsedBody : [parsedBody]).some(message => message?.method === "tools/list" || message?.method === "resources/read")) {
|
|
198
185
|
const visible = [];
|
|
199
186
|
for (const tool of selected) {
|
|
@@ -218,17 +205,13 @@ export function handler(tools, options, apps = {}, reads = []) {
|
|
|
218
205
|
}
|
|
219
206
|
}
|
|
220
207
|
const serverInfo = { name: "aotter.mantle", ...options.serverInfo, version: options.serverInfo?.version ?? version };
|
|
221
|
-
// Host calls execute in the SDK callback, after transport validation.
|
|
222
208
|
const handler = createMcpHandler(() => {
|
|
223
209
|
const schema = (value) => fromJsonSchema(value, { getValidator() { return (input) => ({ valid: true, data: input, errorMessage: undefined }); } });
|
|
224
|
-
// Tools capability after construction: given to the constructor, the SDK installs its tools/call handler before the wrap below.
|
|
225
210
|
const server = new McpServer(serverInfo, options.instructions ? { instructions: options.instructions } : {});
|
|
226
211
|
server.server.registerCapabilities({ tools: { listChanged: false } });
|
|
227
212
|
if (host)
|
|
228
213
|
server.server.onclose = () => access?.finish(isRecord(parsedBody) && parsedBody.method === "initialize" ? undefined : new ContractError("INPUT_VALIDATION_FAILED", "MCP request refused.", "mcp", { status: 400 }));
|
|
229
214
|
const appMeta = links ? registerApps(server, links, parsedBody, new Set(selected.map(tool => tool.name)), { env, request }) : undefined;
|
|
230
|
-
// A host's stale copy names a tool this catalogue lacks: say so, with the catalogue version, instead of the SDK's bare "not found".
|
|
231
|
-
// Wrapped where the SDK stores it, so transport and request validation still answer first.
|
|
232
215
|
const registered = new Set(), set = server.server.setRequestHandler.bind(server.server);
|
|
233
216
|
server.server.setRequestHandler = ((method, handler) => set(method, method === "tools/call" && typeof handler === "function" ? (request, context) => {
|
|
234
217
|
if (!registered.has(request.params.name))
|
|
@@ -240,7 +223,6 @@ export function handler(tools, options, apps = {}, reads = []) {
|
|
|
240
223
|
if (meta === false)
|
|
241
224
|
continue;
|
|
242
225
|
registered.add(tool.name);
|
|
243
|
-
// Not part of structured output: the version, and on failure the current input contract.
|
|
244
226
|
const about = (contract) => { const text = [tool.version && `tool version ${tool.version}`, contract && `input schema ${JSON.stringify(tool.page ? paging(tool.inputSchema) : tool.inputSchema)}`].filter(Boolean).join("; "); return text ? [{ type: "text", text }] : []; };
|
|
245
227
|
server.registerTool(tool.name, { ...(meta ? { _meta: meta } : {}), ...(tool.title ? { title: text(tool.title, locale) } : {}), description: text(tool.description, locale) ?? text(tool.title, locale) ?? tool.name, inputSchema: schema(tool.page ? paging(tool.inputSchema) : tool.inputSchema), ...(tool.outputSchema ? { outputSchema: schema(tool.outputSchema) } : {}), ...(tool.annotations ? { annotations: tool.annotations } : {}) }, async (raw) => {
|
|
246
228
|
const metadata = options.onObservation ? { kind: "invocation", surface, invocationId: crypto.randomUUID(), tool: tool.name, caller: Object.freeze(caller.kind === "user" ? { ...caller, scopes: Object.freeze([...caller.scopes]) } : { ...caller }) } : undefined;
|
|
@@ -256,8 +238,6 @@ export function handler(tools, options, apps = {}, reads = []) {
|
|
|
256
238
|
let db;
|
|
257
239
|
const run = (input) => callTool(tool, input, () => db ??= options.db(env), caller, options.handlers, access?.dryRun ? () => ({ dryRun: true, event: access.finish() }) : undefined);
|
|
258
240
|
let data = await run(raw);
|
|
259
|
-
// A page is cut before the first row that overflows the budget: the same page re-runs with the limit that fits, so the cursor is the View's own.
|
|
260
|
-
// Data can change between reads, so the re-run is measured again. A View without an order is one page and refuses a smaller limit: it stays whole.
|
|
261
241
|
for (let tries = 0; tool.page && isRecord(data) && Array.isArray(data.rows); tries++) {
|
|
262
242
|
const rows = data.rows, total = JSON.stringify(data).length;
|
|
263
243
|
if (total <= MCP_PAGE_BUDGET)
|
|
@@ -299,7 +279,6 @@ export function handler(tools, options, apps = {}, reads = []) {
|
|
|
299
279
|
}
|
|
300
280
|
});
|
|
301
281
|
}
|
|
302
|
-
// An empty catalogue still answers tools/list and refuses calls the same way.
|
|
303
282
|
if (registered.size === 0) {
|
|
304
283
|
server.server.setRequestHandler("tools/list", () => ({ tools: [] }));
|
|
305
284
|
server.server.setRequestHandler("tools/call", () => ({ content: [] }));
|
|
@@ -319,14 +298,12 @@ export function handler(tools, options, apps = {}, reads = []) {
|
|
|
319
298
|
}
|
|
320
299
|
});
|
|
321
300
|
}
|
|
322
|
-
/** A hash of the tools an endpoint serves (`surface:name:version`, sorted), as 32-bit FNV-1a hex: it changes with any tool's definition. */
|
|
323
301
|
function catalogueVersion(tools) {
|
|
324
302
|
const text = JSON.stringify(tools.map(tool => `${tool.surface}:${tool.name}:${tool.version ?? ""}`).sort());
|
|
325
303
|
return [...text].reduce((h, c) => Math.imul(h ^ c.codePointAt(0), 16777619) >>> 0, 2166136261).toString(16).padStart(8, "0");
|
|
326
304
|
}
|
|
327
305
|
const CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities";
|
|
328
306
|
const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
329
|
-
/** `unknown`: a stateless request after `initialize` carries no capabilities, so only an explicit refusal hides Apps. */
|
|
330
307
|
function clientUiSupport(message) {
|
|
331
308
|
for (const m of Array.isArray(message) ? message : [message]) {
|
|
332
309
|
if (!isRecord(m) || !isRecord(m.params))
|
|
@@ -344,7 +321,6 @@ function appMeta(r, csp = r.csp) {
|
|
|
344
321
|
const ui = { ...(csp ? { csp } : {}), ...(r.permissions ? { permissions: r.permissions } : {}), ...(r.domain !== undefined ? { domain: r.domain } : {}), ...(r.prefersBorder !== undefined ? { prefersBorder: r.prefersBorder } : {}) };
|
|
345
322
|
return Object.keys(ui).length > 0 ? { ui } : undefined;
|
|
346
323
|
}
|
|
347
|
-
/** Registration uses the official SDK; HTML loaders run only on resources/read. */
|
|
348
324
|
function registerApps(server, links, message, tools, request) {
|
|
349
325
|
const enabled = clientUiSupport(message) !== "unsupported";
|
|
350
326
|
if (enabled)
|
package/dist/kernel/mcp.js
CHANGED
|
@@ -1,22 +1,18 @@
|
|
|
1
1
|
import { linkApps, linkSurface, resourcesOf } from "./mcp-apps.js";
|
|
2
2
|
export const callTool = async (...args) => (await import("./mcp-call.js")).callTool(...args);
|
|
3
3
|
export const callToolLazy = async (...args) => (await import("./mcp-call.js")).callToolLazy(...args);
|
|
4
|
-
/** The selected MCP routes; all request work loads only when an MCP request arrives. */
|
|
5
4
|
export function mcp(tools, options, reads = []) {
|
|
6
5
|
let serve;
|
|
7
|
-
// Check known static App configuration now; factories wait for the request caller gate.
|
|
8
6
|
const linked = {};
|
|
9
7
|
const apps = {};
|
|
10
8
|
for (const surface of ["public", "admin"]) {
|
|
11
9
|
const declared = options.apps?.[surface];
|
|
12
10
|
if (declared) {
|
|
13
|
-
// Read each static contributor's resources getter once, including mixed arrays.
|
|
14
11
|
const sources = (Array.isArray(declared) ? declared : [declared])
|
|
15
12
|
.map(source => typeof source === "function" ? source : resourcesOf(source));
|
|
16
13
|
const fixed = resourcesOf(sources.filter(source => typeof source !== "function"));
|
|
17
14
|
const dynamic = sources.some(source => typeof source === "function");
|
|
18
15
|
apps[surface] = dynamic ? sources : fixed;
|
|
19
|
-
// Known static conflicts still fail before any request or dynamic factory runs.
|
|
20
16
|
if (typeof tools === "function")
|
|
21
17
|
linkApps(fixed);
|
|
22
18
|
else {
|
|
@@ -35,7 +31,6 @@ export function mcp(tools, options, reads = []) {
|
|
|
35
31
|
return serve(request, env, ctx);
|
|
36
32
|
};
|
|
37
33
|
}
|
|
38
|
-
/** `allowedOrigins` as the hostnames the official SDK compares; a bad entry fails here, not on each request. */
|
|
39
34
|
function originHostnames(origins = []) {
|
|
40
35
|
return Object.freeze(origins.map(origin => {
|
|
41
36
|
let url;
|
package/dist/kernel/media.js
CHANGED
|
@@ -1,33 +1,23 @@
|
|
|
1
|
-
/** 0.2 media lifecycle over native target drivers. No bytes pass through this module. */
|
|
2
1
|
import { ContractError } from "./contracts.js";
|
|
3
2
|
const P = "media";
|
|
4
|
-
/** HTTP status of each media code: a custom MediaStorage may throw them without one. */
|
|
5
3
|
const STATUS = new Map(Object.entries({
|
|
6
4
|
MEDIA_PURPOSE_REJECTED: 400, MEDIA_SVG_REJECTED: 400, MEDIA_MIME_REJECTED: 400, MEDIA_VARIANTS_INCOMPLETE: 400, MEDIA_VARIANT_SIZE_EXCEEDED: 400, MEDIA_VARIANTS_SUSPICIOUS_SIZE: 400,
|
|
7
5
|
MEDIA_ASSET_NOT_FOUND: 404, MEDIA_OBJECT_NOT_FOUND: 409, MEDIA_UPLOAD_EXPIRED: 410, SITE_NOT_CONFIGURED: 501, MEDIA_NOT_CONFIGURED: 501, PARTIAL_FAILURE: 503,
|
|
8
6
|
}));
|
|
9
7
|
const extra = (code) => ({ status: STATUS.get(code), ...(code === "PARTIAL_FAILURE" ? { fields: { failure: { outcome: "partial", retry: "safe", resource: "media" } } } : {}) });
|
|
10
|
-
/**
|
|
11
|
-
* A media, site or partial-failure error with the HTTP status (and `failure` payload) its code has on the wire. Code
|
|
12
|
-
* outside this module raising these codes uses it: core `statusOf` maps only the core codes.
|
|
13
|
-
*/
|
|
14
8
|
export const mediaError = (code, message, path = P, options) => new ContractError(code, message, path, { ...options, ...extra(code) });
|
|
15
9
|
const fail = (code, message, options) => mediaError(code, message, P, options);
|
|
16
|
-
/** A storage error keeps the wire status its code has always had. */
|
|
17
10
|
const own = (error) => { if (error instanceof ContractError && !error.status && STATUS.has(error.code))
|
|
18
11
|
Object.assign(error, extra(error.code)); return error; };
|
|
19
12
|
const rejected = (results) => results.filter((r) => r.status === "rejected");
|
|
20
13
|
const bad = (expected) => fail("INPUT_VALIDATION_FAILED", `expected ${expected}`);
|
|
21
|
-
/** SVG is refused: object storage does not sanitize it, and an SVG can carry script. */
|
|
22
14
|
const ALLOWED = new Set(["image/png", "image/jpeg", "image/webp", "image/avif", "image/gif"]);
|
|
23
|
-
/** Modern formats a skipped optimization makes larger than the fallback. */
|
|
24
15
|
const MODERN = new Set(["image/avif", "image/webp"]);
|
|
25
16
|
const ROLES = new Set(["primary", "alternate", "fallback"]);
|
|
26
17
|
const TTL_MS = 15 * 60 * 1000;
|
|
27
18
|
const obj = (v) => (v !== null && typeof v === "object" && !Array.isArray(v) ? v : {});
|
|
28
19
|
const MAX_TEXT = 1000;
|
|
29
20
|
const MAX_FILENAME = 255;
|
|
30
|
-
/** `alt` and `caption`: absent, or a string of at most 1000 characters. */
|
|
31
21
|
function texts(body) {
|
|
32
22
|
const b = obj(body);
|
|
33
23
|
for (const k of ["alt", "caption"])
|
|
@@ -35,7 +25,6 @@ function texts(body) {
|
|
|
35
25
|
throw bad(`{ alt?: string, caption?: string }, each at most ${MAX_TEXT} characters`);
|
|
36
26
|
return { ...(typeof b["alt"] === "string" ? { alt: b["alt"] } : {}), ...(typeof b["caption"] === "string" ? { caption: b["caption"] } : {}) };
|
|
37
27
|
}
|
|
38
|
-
/** Exactly one variant per required slot, nothing outside them, and exactly one primary. */
|
|
39
28
|
function checkVariants(policy, variants) {
|
|
40
29
|
const slots = policy.required.map(slot => slot.split(","));
|
|
41
30
|
const slotOf = new Map(slots.flatMap((mimes, i) => mimes.map((m) => [m, i])));
|
|
@@ -99,7 +88,6 @@ export function mediaLibrary(driver, d, storage, policies, now = Date.now) {
|
|
|
99
88
|
checkVariants(policy, asked);
|
|
100
89
|
const at = now();
|
|
101
90
|
const expiresAt = at + TTL_MS;
|
|
102
|
-
// bearer-equivalent until commit: storage keys under it must not be guessable
|
|
103
91
|
const uploadGroupId = crypto.randomUUID();
|
|
104
92
|
const specs = asked.map(({ mimeType, byteSize, role }) => ({ mimeType, byteSize, role, maxBytes: policy.maxBytes[mimeType] }));
|
|
105
93
|
let capabilities;
|
|
@@ -126,7 +114,6 @@ export function mediaLibrary(driver, d, storage, policies, now = Date.now) {
|
|
|
126
114
|
return assetOf(committed);
|
|
127
115
|
const row = await one(`SELECT record FROM pending_media_uploads WHERE id = ${p(1)}`, [uploadGroupId]);
|
|
128
116
|
const record = row ? JSON.parse(String(row.record)) : null;
|
|
129
|
-
// a rejected group's objects are deleted: an upload URL takes any type and size, so what was PUT is not trusted
|
|
130
117
|
const discard = () => removeAll(record?.variants ?? []);
|
|
131
118
|
if (!record || record.expiresAt <= now()) {
|
|
132
119
|
if (record) {
|
|
@@ -139,7 +126,6 @@ export function mediaLibrary(driver, d, storage, policies, now = Date.now) {
|
|
|
139
126
|
try {
|
|
140
127
|
asset = await storage.commitUpload({
|
|
141
128
|
uploadGroupId, filename: record.filename, now: record.createdAt,
|
|
142
|
-
// the declared size is the cap: a larger object than announced is refused
|
|
143
129
|
variants: record.variants.map((v) => ({ mimeType: v.mimeType, role: v.role, storageKey: v.storageKey, maxBytes: Math.min(v.maxBytes, v.expectedSize) })),
|
|
144
130
|
...((patch.alt ?? record.alt) !== undefined ? { alt: patch.alt ?? record.alt } : {}),
|
|
145
131
|
...((patch.caption ?? record.caption) !== undefined ? { caption: patch.caption ?? record.caption } : {}),
|
|
@@ -158,7 +144,6 @@ export function mediaLibrary(driver, d, storage, policies, now = Date.now) {
|
|
|
158
144
|
if (asset.id !== uploadGroupId)
|
|
159
145
|
throw new ContractError("OUTCOME_UNKNOWN", "Storage returned a different asset id; reconcile this upload group.", P);
|
|
160
146
|
await driver.write([save(asset, p), unpend(uploadGroupId)]).catch(async (error) => {
|
|
161
|
-
// Cleanup requires positive native rollback evidence; an unclassified failure may have committed.
|
|
162
147
|
if (driver.definitive?.(error) === true) {
|
|
163
148
|
const failed = rejected(await removeAll(asset.variants));
|
|
164
149
|
if (failed.length)
|
|
@@ -168,7 +153,6 @@ export function mediaLibrary(driver, d, storage, policies, now = Date.now) {
|
|
|
168
153
|
throw error instanceof ContractError && error.code === "OUTCOME_UNKNOWN" ? error : new ContractError("OUTCOME_UNKNOWN", "The write outcome is unknown; reconcile this upload group before retrying.", P, { cause: error });
|
|
169
154
|
});
|
|
170
155
|
const durable = await get(uploadGroupId);
|
|
171
|
-
// ON CONFLICT may select another concurrent attempt. Only discard this attempt's unselected copies.
|
|
172
156
|
const selected = new Set(durable.variants.map(v => v.storageKey));
|
|
173
157
|
if (rejected(await removeAll(asset.variants.filter(v => !selected.has(v.storageKey)))).length)
|
|
174
158
|
throw new ContractError("OUTCOME_UNKNOWN", "The asset is committed, but unselected upload copies need storage reconciliation.", P);
|
|
@@ -193,7 +177,6 @@ export function mediaLibrary(driver, d, storage, policies, now = Date.now) {
|
|
|
193
177
|
const patch = Object.entries(texts(request));
|
|
194
178
|
if (!patch.length)
|
|
195
179
|
return get(id);
|
|
196
|
-
// only the patched columns, and only a row that still exists: a concurrent delete or edit of the other field stands
|
|
197
180
|
const [r] = (await driver.write([{ sql: `UPDATE media_assets SET ${patch.map(([k], i) => `${k} = ${p(i + 2)}`).join(", ")} WHERE id = ${p(1)} RETURNING ${COLUMNS}`, binds: [id, ...patch.map(([, v]) => v)] }]))[0];
|
|
198
181
|
if (!r)
|
|
199
182
|
throw fail("MEDIA_ASSET_NOT_FOUND", `no media asset '${id}'`);
|
|
@@ -209,7 +192,6 @@ export function mediaLibrary(driver, d, storage, policies, now = Date.now) {
|
|
|
209
192
|
},
|
|
210
193
|
};
|
|
211
194
|
}
|
|
212
|
-
/** The 0.2 Admin library item's convenience fields, without changing the storage DTO. */
|
|
213
195
|
export function mediaItem(asset) {
|
|
214
196
|
const primary = asset.variants.find(v => v.role === "primary") ?? asset.variants[0];
|
|
215
197
|
return { id: asset.id, variants: asset.variants, primaryUrl: primary?.publicUrl ?? null, mime: primary?.mimeType ?? null, byteSize: primary?.byteSize ?? null, alt: asset.alt ?? null, caption: asset.caption ?? null, createdAt: asset.createdAt };
|
package/dist/kernel/paging.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { modeOf } from "./caller-
|
|
1
|
+
import { modeOf } from "./caller-mode.js";
|
|
2
2
|
import { binds } from "./binds.js";
|
|
3
3
|
import { invalid } from "./surface.js";
|
|
4
|
-
/** Shared keyset wire format; a selected View binds its cursor to its operation. */
|
|
5
4
|
export const encodeCursor = (value, id, operation) => encodeURIComponent(JSON.stringify(operation === undefined ? [value, id] : [value, id, operation]));
|
|
6
5
|
export function decodeCursor(cursor, path = "", operation) {
|
|
7
6
|
try {
|
|
@@ -12,7 +11,6 @@ export function decodeCursor(cursor, path = "", operation) {
|
|
|
12
11
|
catch { }
|
|
13
12
|
invalid("Malformed or foreign cursor.", path);
|
|
14
13
|
}
|
|
15
|
-
/** Selected boundaries may accept a NULL key; their generated kind guard validates it before native I/O. */
|
|
16
14
|
export function decodeNullableCursor(cursor, path, operation) {
|
|
17
15
|
try {
|
|
18
16
|
const c = JSON.parse(decodeURIComponent(cursor));
|
|
@@ -23,7 +21,6 @@ export function decodeNullableCursor(cursor, path, operation) {
|
|
|
23
21
|
invalid("Malformed or foreign cursor.", path);
|
|
24
22
|
}
|
|
25
23
|
export const MAX_PAGE_SIZE = 500;
|
|
26
|
-
/** Transport and native entry bounds share one check; Views retain their declared cap. */
|
|
27
24
|
export function checkPageLimit(limit, path) {
|
|
28
25
|
if (!Number.isSafeInteger(limit) || Number(limit) < 1 || Number(limit) > MAX_PAGE_SIZE)
|
|
29
26
|
invalid("limit is 1 to 500.", path);
|
|
@@ -41,10 +38,6 @@ export function validCursor(kind, sqlite, key) {
|
|
|
41
38
|
default: return typeof key === "string";
|
|
42
39
|
}
|
|
43
40
|
}
|
|
44
|
-
/**
|
|
45
|
-
* A View's paged boundary: `options.limit` defaults to min(50, cap) and is capped at cap and 500. Generated modules
|
|
46
|
-
* call it from their exported function, so importing a View runs no kernel code.
|
|
47
|
-
*/
|
|
48
41
|
export async function page(spec, db, caller, input, options = {}) {
|
|
49
42
|
const { path, cap } = spec;
|
|
50
43
|
spec.auth?.(caller);
|
|
@@ -62,7 +55,6 @@ export async function page(spec, db, caller, input, options = {}) {
|
|
|
62
55
|
throw 0;
|
|
63
56
|
if (spec.keys === 1 && encoded[0] !== encoded[1])
|
|
64
57
|
throw 0;
|
|
65
|
-
// Preserve the existing [id,id,operation] single-key and [value,id,operation] two-key formats.
|
|
66
58
|
keys = spec.keys === 1 ? [encoded[1]] : encoded.slice(0, -1);
|
|
67
59
|
for (const [i, kind] of spec.cursor.entries()) {
|
|
68
60
|
if (!validCursor(kind, spec.sqlite, keys[i]))
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
import { checkFresh } from "./caller-identity.js";
|
|
1
|
+
import { isAdmin, deny, ROW_CONFLICT } from "./contracts.js";
|
|
2
|
+
import { checkFresh } from "./caller-mode.js";
|
|
4
3
|
import { bound } from "./binds.js";
|
|
5
4
|
export async function transition(db, caller, input, path, steps, failure, d, execute, write) {
|
|
6
5
|
checkFresh(caller, false, path);
|
|
@@ -9,7 +8,7 @@ export async function transition(db, caller, input, path, steps, failure, d, exe
|
|
|
9
8
|
return { results: await execute(db, bound(d, steps, caller, input), path).catch(error => {
|
|
10
9
|
if (release && error?.code === "CONFLICT")
|
|
11
10
|
release();
|
|
12
|
-
if (error?.code === "CONFLICT" && error.message ===
|
|
11
|
+
if (error?.code === "CONFLICT" && error.message === ROW_CONFLICT)
|
|
13
12
|
error.message = failure;
|
|
14
13
|
throw error;
|
|
15
14
|
}) };
|
package/dist/kernel/r2-media.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
/** Native R2 binding plus an app-owned SigV4 signer. No SDK dependency. */
|
|
2
1
|
import { ContractError } from "./contracts.js";
|
|
3
2
|
import { mediaError } from "./media.js";
|
|
4
3
|
const EXT = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/avif": "avif", "image/gif": "gif" };
|
|
@@ -16,7 +15,6 @@ export function r2MediaStorage({ bucket, signer, endpoint, publicBase }) {
|
|
|
16
15
|
const ttl = Math.max(60, Math.floor((expiresAt - now) / 1000));
|
|
17
16
|
return {
|
|
18
17
|
capabilities: await Promise.all(variants.map(async (v) => {
|
|
19
|
-
// server-made keys, one directory per asset so its variants list together
|
|
20
18
|
const storageKey = `${UPLOADS}${purpose}/${uploadGroupId}/${v.role}.${ext(v.mimeType)}`;
|
|
21
19
|
const target = new URL(`${s3}/${storageKey}`);
|
|
22
20
|
target.searchParams.set("X-Amz-Expires", String(ttl));
|
|
@@ -26,7 +24,6 @@ export function r2MediaStorage({ bucket, signer, endpoint, publicBase }) {
|
|
|
26
24
|
};
|
|
27
25
|
},
|
|
28
26
|
async commitUpload({ uploadGroupId, filename, variants, alt, caption, now }) {
|
|
29
|
-
// every variant is checked before any is published, so a rejected group publishes nothing
|
|
30
27
|
const heads = await Promise.all(variants.map(spec => bucket.head(spec.storageKey)));
|
|
31
28
|
for (const [i, spec] of variants.entries()) {
|
|
32
29
|
const o = heads[i];
|
|
@@ -38,19 +35,16 @@ export function r2MediaStorage({ bucket, signer, endpoint, publicBase }) {
|
|
|
38
35
|
if (o.size > spec.maxBytes)
|
|
39
36
|
throw fail("MEDIA_VARIANT_SIZE_EXCEEDED", `the stored ${spec.role} is ${o.size} bytes, more than ${spec.maxBytes}`);
|
|
40
37
|
}
|
|
41
|
-
// Each attempt owns its public copies: a concurrent loser cannot overwrite or clean up a committed winner.
|
|
42
38
|
const attempt = crypto.randomUUID();
|
|
43
39
|
const out = [];
|
|
44
40
|
try {
|
|
45
41
|
for (const [i, spec] of variants.entries()) {
|
|
46
42
|
const key = `committed/${uploadGroupId}/${attempt}/${spec.role}.${ext(spec.mimeType)}`;
|
|
47
43
|
const o = await bucket.get(spec.storageKey);
|
|
48
|
-
// an upload URL may PUT again between the check and the copy: the copy must be what was checked
|
|
49
44
|
if (!o || o.size !== heads[i].size || o.httpMetadata?.contentType !== spec.mimeType) {
|
|
50
45
|
await cancel(o);
|
|
51
46
|
throw fail("MEDIA_OBJECT_NOT_FOUND", `variant ${spec.role} of '${uploadGroupId}' changed during commit`);
|
|
52
47
|
}
|
|
53
|
-
// Remember a possibly published key before awaiting put: a failed response may still have stored it.
|
|
54
48
|
out.push({ mimeType: spec.mimeType, publicUrl: `${base}/${key}`, storageKey: key, byteSize: o.size, role: spec.role });
|
|
55
49
|
try {
|
|
56
50
|
await bucket.put(key, o.body, {
|
|
@@ -63,7 +57,6 @@ export function r2MediaStorage({ bucket, signer, endpoint, publicBase }) {
|
|
|
63
57
|
throw error;
|
|
64
58
|
}
|
|
65
59
|
}
|
|
66
|
-
// The use case removes upload keys only after its SQL transaction is durable.
|
|
67
60
|
}
|
|
68
61
|
catch (error) {
|
|
69
62
|
const cleanup = await Promise.allSettled(out.map(v => bucket.delete(v.storageKey)));
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
1
|
+
import { forwarded, ContractError } from "./contracts.js";
|
|
2
|
+
import { checkOrigin, surfaceCaller } from "./surface-failure.js";
|
|
3
3
|
import { decode, invalid } from "./surface.js";
|
|
4
4
|
import { draining } from "./drain.js";
|
|
5
5
|
const isApi = (path) => path === "/api" || path.startsWith("/api/");
|
|
6
6
|
const fail = message => invalid(message, "rest");
|
|
7
|
-
/** Shared matching/auth/error envelope; selected dispatch is supplied by the surface. */
|
|
8
7
|
export function router(routes, options, send) {
|
|
9
8
|
return draining(async (request, env, ctx) => {
|
|
10
9
|
let caller;
|
package/dist/kernel/rest.js
CHANGED
|
@@ -7,7 +7,6 @@ export async function body(request, limit = 1_000_000) {
|
|
|
7
7
|
fail(`Request body exceeds ${limit} bytes.`);
|
|
8
8
|
return (await import("./json-body.js")).body(request, limit, fail);
|
|
9
9
|
}
|
|
10
|
-
/** Shared matching/auth/error envelope; selected dispatch is supplied by the surface. */
|
|
11
10
|
function router(routes, options, send) {
|
|
12
11
|
let handle;
|
|
13
12
|
return async (request, env, ctx) => {
|
|
@@ -15,14 +14,12 @@ function router(routes, options, send) {
|
|
|
15
14
|
return handle(request, env, ctx);
|
|
16
15
|
};
|
|
17
16
|
}
|
|
18
|
-
/** Generated REST routes retain the native View/Procedure dispatch. */
|
|
19
17
|
export function rest(routes, options) {
|
|
20
18
|
return router(routes, options, async (route, request, env, caller, params, access) => {
|
|
21
19
|
const { dispatch } = await import("./rest-dispatch.js");
|
|
22
20
|
return dispatch(route, request, () => options.db(env), caller, params, options, access);
|
|
23
21
|
});
|
|
24
22
|
}
|
|
25
|
-
/** A selected surface's raw/JSON handlers; its branches are absent from ordinary REST bundles. */
|
|
26
23
|
export function nativeRest(routes, options) {
|
|
27
24
|
return router(routes, options, async (route, request, env, caller, params, access) => {
|
|
28
25
|
if (Number(request.headers.get("content-length")) > (route.bodyLimit ?? 1_000_000))
|
package/dist/kernel/scalars.js
CHANGED
|
@@ -1,8 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Declared date-time and date inputs are ISO on every target (the handbook's wire form). A timestamp needs an explicit
|
|
3
|
-
* Z or offset; a day that does not exist (2026-02-30) is refused rather than rolled over. SQLite stores microseconds
|
|
4
|
-
* and days; PostgreSQL receives the canonical text, so it keeps every microsecond.
|
|
5
|
-
*/
|
|
6
1
|
import { ContractError } from "./contracts.js";
|
|
7
2
|
export function encodeTimestamptz(v) {
|
|
8
3
|
if (v instanceof Date) {
|
|
@@ -11,7 +6,6 @@ export function encodeTimestamptz(v) {
|
|
|
11
6
|
throw new ContractError("SQL_TYPE", "Invalid Date is not a timestamp");
|
|
12
7
|
return micros;
|
|
13
8
|
}
|
|
14
|
-
// hours 00-23: Date.parse would roll T24:00 over to the next day
|
|
15
9
|
const m = /^(\d{4}-\d\d-\d\d)[T ]((?:[01]\d|2[0-3]):\d\d(?::\d\d)?)(?:\.(\d{1,6}))?(Z|[+-]\d\d(?::?\d\d)?)$/.exec(v.trim());
|
|
16
10
|
if (!m)
|
|
17
11
|
throw new ContractError("SQL_TYPE", `'${v}' is not a timestamp with an explicit offset`);
|
|
@@ -24,14 +18,13 @@ export function encodeTimestamptz(v) {
|
|
|
24
18
|
throw new ContractError("SQL_TYPE", `'${v}' is not a valid timestamp`);
|
|
25
19
|
return micros;
|
|
26
20
|
}
|
|
27
|
-
/** A date is the string a calendar shows; a Date instant has no single calendar day, so it is not accepted. */
|
|
28
21
|
export function encodeDate(v) {
|
|
29
22
|
const m = /^(\d{4})-(\d\d)-(\d\d)$/.exec(v);
|
|
30
23
|
if (!m)
|
|
31
24
|
throw new ContractError("SQL_TYPE", `'${v}' is not a date`);
|
|
32
25
|
const [, y, mo, d] = m;
|
|
33
26
|
const dt = new Date(0);
|
|
34
|
-
dt.setUTCFullYear(+y, +mo - 1, +d);
|
|
27
|
+
dt.setUTCFullYear(+y, +mo - 1, +d);
|
|
35
28
|
if (dt.getUTCDate() !== +d || dt.getUTCMonth() !== +mo - 1)
|
|
36
29
|
throw new ContractError("SQL_TYPE", `'${v}' is not a valid date`);
|
|
37
30
|
return dt.getTime() / 86_400_000;
|
|
@@ -40,5 +33,4 @@ export function isoTimestamptz(v) {
|
|
|
40
33
|
const us = encodeTimestamptz(v), ms = Math.floor(us / 1000);
|
|
41
34
|
return new Date(ms).toISOString().replace("Z", String(us - ms * 1000).padStart(3, "0") + "Z");
|
|
42
35
|
}
|
|
43
|
-
/** The input itself: the pattern admits only the canonical form, and a day that does not exist was refused. */
|
|
44
36
|
export const isoDate = (v) => (encodeDate(v), v);
|
package/dist/kernel/search.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
/** Native substring predicates matching Core's mantle.search lowering. Values remain bound. */
|
|
2
1
|
export function searchLike(columns, query, operator) {
|
|
3
2
|
const pattern = `'%' || replace(replace(replace(${query}, '!', '!!'), '%', '!%'), '_', '!_') || '%'`;
|
|
4
3
|
return columns.map(column => `${column} ${operator} ${pattern} ESCAPE '!'`).join(' OR ');
|
package/dist/kernel/site.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
/** Optional site capability. Construction does no database work; deployment facts come from generated constants. */
|
|
2
1
|
import { isAdmin, deny } from "./contracts.js";
|
|
3
2
|
import { invalid } from "./surface.js";
|
|
4
3
|
import { mediaLibrary } from "./media.js";
|
|
@@ -23,7 +22,6 @@ export function createSite(db, d, caller, defaults, policies) {
|
|
|
23
22
|
return read();
|
|
24
23
|
}, media(storage) { admin(); return mediaLibrary(db, d, storage, policies); } };
|
|
25
24
|
}
|
|
26
|
-
/** 0.2 /admin/api/site projection; the app supplies its selected capabilities. */
|
|
27
25
|
export function siteInfo(config, options) {
|
|
28
26
|
const { origin, ...stored } = config;
|
|
29
27
|
const publicUrl = URL.canParse(origin) ? origin : options.origin;
|
package/dist/kernel/store.d.ts
CHANGED
|
@@ -44,6 +44,14 @@ export interface Fact {
|
|
|
44
44
|
readonly d?: readonly string[];
|
|
45
45
|
/** Declared searchable text fields; omitted collections search id only. */
|
|
46
46
|
readonly search?: readonly string[];
|
|
47
|
+
/** `x-mantle-ref` columns to a scoped Schema (Core's `refChecks`): a caller's write names a row it sees, in the child's partition. */
|
|
48
|
+
readonly ref?: readonly {
|
|
49
|
+
readonly column: string;
|
|
50
|
+
readonly table: string;
|
|
51
|
+
readonly field: string;
|
|
52
|
+
readonly same: readonly (readonly [parent: string, child: string])[];
|
|
53
|
+
readonly terms: readonly Term[];
|
|
54
|
+
}[];
|
|
47
55
|
/** Generated parent policy and inherited read-only columns; no authored schema is interpreted. */
|
|
48
56
|
readonly parent?: {
|
|
49
57
|
readonly on: string;
|
|
@@ -130,8 +138,10 @@ export interface Collection<T extends Table> {
|
|
|
130
138
|
readonly lock: number | string;
|
|
131
139
|
}): Write<void>;
|
|
132
140
|
}
|
|
133
|
-
/** Lazy, single-execution write: await
|
|
141
|
+
/** Lazy, single-execution write: await it (or `.then`/`.catch`/`.finally`, which run it) or submit it once to its Store's batch. */
|
|
134
142
|
export interface Write<T> extends PromiseLike<T> {
|
|
143
|
+
catch<R = never>(onrejected?: ((reason: any) => R | PromiseLike<R>) | null): Promise<T | R>;
|
|
144
|
+
finally(onfinally?: (() => void) | null): Promise<T>;
|
|
135
145
|
}
|
|
136
146
|
export interface TransactionOptions {
|
|
137
147
|
readonly isolation?: "serializable" | "repeatable read" | "read committed" | "read uncommitted";
|