@slotform/api 0.0.0-stage → 0.1.1
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 +50 -2
- package/dist/client.d.ts +16 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +98 -0
- package/dist/client.js.map +1 -0
- package/dist/error.d.ts +2 -0
- package/dist/error.d.ts.map +1 -0
- package/dist/error.js +2 -0
- package/dist/error.js.map +1 -0
- package/dist/index.d.ts +153 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +640 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/chosen.d.ts +12 -0
- package/dist/lib/chosen.d.ts.map +1 -0
- package/dist/lib/chosen.js +18 -0
- package/dist/lib/chosen.js.map +1 -0
- package/dist/lib/cursor.d.ts +68 -0
- package/dist/lib/cursor.d.ts.map +1 -0
- package/dist/lib/cursor.js +220 -0
- package/dist/lib/cursor.js.map +1 -0
- package/dist/lib/limits.d.ts +4 -0
- package/dist/lib/limits.d.ts.map +1 -0
- package/dist/lib/limits.js +10 -0
- package/dist/lib/limits.js.map +1 -0
- package/dist/lib/local-origin.d.ts +2 -0
- package/dist/lib/local-origin.d.ts.map +1 -0
- package/dist/lib/local-origin.js +17 -0
- package/dist/lib/local-origin.js.map +1 -0
- package/dist/lib/slugify.d.ts +4 -0
- package/dist/lib/slugify.d.ts.map +1 -0
- package/dist/lib/slugify.js +26 -0
- package/dist/lib/slugify.js.map +1 -0
- package/dist/lib/window.d.ts +52 -0
- package/dist/lib/window.d.ts.map +1 -0
- package/dist/lib/window.js +70 -0
- package/dist/lib/window.js.map +1 -0
- package/dist/mcp-path.d.ts +2 -0
- package/dist/mcp-path.d.ts.map +1 -0
- package/dist/mcp-path.js +3 -0
- package/dist/mcp-path.js.map +1 -0
- package/dist/mcp.d.ts +15 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +5 -0
- package/dist/mcp.js.map +1 -0
- package/dist/node/barrel.d.ts +3 -0
- package/dist/node/barrel.d.ts.map +1 -0
- package/dist/node/barrel.js +70 -0
- package/dist/node/barrel.js.map +1 -0
- package/dist/node/codegen.d.ts +10 -0
- package/dist/node/codegen.d.ts.map +1 -0
- package/dist/node/codegen.js +132 -0
- package/dist/node/codegen.js.map +1 -0
- package/dist/node/procedure-codegen.d.ts +14 -0
- package/dist/node/procedure-codegen.d.ts.map +1 -0
- package/dist/node/procedure-codegen.js +95 -0
- package/dist/node/procedure-codegen.js.map +1 -0
- package/dist/node/schema-child.d.ts +2 -0
- package/dist/node/schema-child.d.ts.map +1 -0
- package/dist/node/schema-child.js +31 -0
- package/dist/node/schema-child.js.map +1 -0
- package/dist/node/schema-source.d.ts +3 -0
- package/dist/node/schema-source.d.ts.map +1 -0
- package/dist/node/schema-source.js +33 -0
- package/dist/node/schema-source.js.map +1 -0
- package/dist/node/server-client.d.ts +19 -0
- package/dist/node/server-client.d.ts.map +1 -0
- package/dist/node/server-client.js +45 -0
- package/dist/node/server-client.js.map +1 -0
- package/dist/node/types.d.ts +42 -0
- package/dist/node/types.d.ts.map +1 -0
- package/dist/node/types.js +13 -0
- package/dist/node/types.js.map +1 -0
- package/dist/not-found.d.ts +2 -0
- package/dist/not-found.d.ts.map +1 -0
- package/dist/not-found.js +6 -0
- package/dist/not-found.js.map +1 -0
- package/dist/procedure.d.ts +188 -0
- package/dist/procedure.d.ts.map +1 -0
- package/dist/procedure.js +392 -0
- package/dist/procedure.js.map +1 -0
- package/dist/query-invalidation.d.ts +20 -0
- package/dist/query-invalidation.d.ts.map +1 -0
- package/dist/query-invalidation.js +66 -0
- package/dist/query-invalidation.js.map +1 -0
- package/dist/schema.d.ts +32 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +103 -0
- package/dist/schema.js.map +1 -0
- package/dist/types.d.ts +30 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/wire.d.ts +11 -0
- package/dist/wire.d.ts.map +1 -0
- package/dist/wire.js +26 -0
- package/dist/wire.js.map +1 -0
- package/dist/worker/guards.d.ts +6 -0
- package/dist/worker/guards.d.ts.map +1 -0
- package/dist/worker/guards.js +29 -0
- package/dist/worker/guards.js.map +1 -0
- package/dist/worker/index.d.ts +57 -0
- package/dist/worker/index.d.ts.map +1 -0
- package/dist/worker/index.js +418 -0
- package/dist/worker/index.js.map +1 -0
- package/dist/worker/mcp.d.ts +28 -0
- package/dist/worker/mcp.d.ts.map +1 -0
- package/dist/worker/mcp.js +361 -0
- package/dist/worker/mcp.js.map +1 -0
- package/dist/worker/request-log.d.ts +10 -0
- package/dist/worker/request-log.d.ts.map +1 -0
- package/dist/worker/request-log.js +37 -0
- package/dist/worker/request-log.js.map +1 -0
- package/guide/add-a-procedure.md +42 -0
- package/guide/background.md +86 -0
- package/guide/client.md +93 -0
- package/guide/config.md +85 -0
- package/guide/mcp.md +68 -0
- package/guide/middleware.md +79 -0
- package/guide/procedures.md +95 -0
- package/guide/utilities.md +135 -0
- package/package.json +120 -3
- package/src/client.ts +129 -0
- package/src/error.ts +1 -0
- package/src/index.ts +787 -0
- package/src/lib/chosen.ts +31 -0
- package/src/lib/cursor.ts +354 -0
- package/src/lib/limits.ts +10 -0
- package/src/lib/local-origin.ts +18 -0
- package/src/lib/slugify.ts +29 -0
- package/src/lib/window.ts +155 -0
- package/src/mcp-path.ts +2 -0
- package/src/mcp.ts +30 -0
- package/src/node/barrel.ts +77 -0
- package/src/node/codegen.ts +173 -0
- package/src/node/procedure-codegen.ts +131 -0
- package/src/node/schema-child.ts +31 -0
- package/src/node/schema-source.ts +45 -0
- package/src/node/server-client.ts +67 -0
- package/src/node/types.ts +64 -0
- package/src/not-found.ts +6 -0
- package/src/procedure.ts +935 -0
- package/src/query-invalidation.ts +106 -0
- package/src/schema.ts +133 -0
- package/src/types.ts +72 -0
- package/src/wire.ts +34 -0
- package/src/worker/guards.ts +37 -0
- package/src/worker/index.ts +681 -0
- package/src/worker/mcp.ts +470 -0
- package/src/worker/request-log.ts +50 -0
package/guide/config.md
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# API options
|
|
2
|
+
|
|
3
|
+
`api()` in `slotform.config.ts` serves the procedures under `src/worker/routes/` from the worker.
|
|
4
|
+
Its CORS allow-list is no option of its own: it derives from `app.domain` and `app.origins`
|
|
5
|
+
(`node_modules/@slotform/cli/guide/config.md`), plus, on a request a deploy target's listener
|
|
6
|
+
names an origin for (`SLOTFORM_ORIGIN` on the env, the node target's further listeners), that
|
|
7
|
+
origin.
|
|
8
|
+
|
|
9
|
+
| Option | Default | What it sets |
|
|
10
|
+
| --- | --- | --- |
|
|
11
|
+
| `prefix` | `"/rpc"` | The path the RPC handler is mounted under; starts with `/` |
|
|
12
|
+
| `env` | `[]` | The env vars your own worker code reads, each `{ name, devDefault, validate? }` |
|
|
13
|
+
| `entities` | `[]` | The names of state your app keeps outside the database, for `reads` / `writes` to type |
|
|
14
|
+
| `server` | none | A client app: the path from this app's root to the Slotform app it talks to (`"../server"`), for a web or native app that owns no worker. See [A client of another app's server](#a-client-of-another-apps-server) |
|
|
15
|
+
|
|
16
|
+
## Env vars
|
|
17
|
+
|
|
18
|
+
Declare every var your worker code reads in `env`, never by hand in `.dev.vars` or
|
|
19
|
+
`wrangler.toml`:
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
api({ env: [{ name: "RESEND_API_KEY", devDefault: "re_dev", validate: { minLength: 8 } }] }),
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
A declared var joins the ones plugins declare: the deploy target gives it its dev default under
|
|
26
|
+
`slotform dev` (cloudflare's `.dev.vars`, node's process env), `Env` types it, and the worker
|
|
27
|
+
asserts it on its first request and refuses to serve when it fails.
|
|
28
|
+
|
|
29
|
+
| `validate` hint | Refuses |
|
|
30
|
+
| --- | --- |
|
|
31
|
+
| (always) | a missing or empty value |
|
|
32
|
+
| `minLength: n` | a value shorter than `n` |
|
|
33
|
+
| `url: true` | a value that is not a URL |
|
|
34
|
+
| `devLocalhost: true` | under `SLOTFORM_DEV`, a URL whose host is not local: the sign of a deploy that shipped dev settings |
|
|
35
|
+
|
|
36
|
+
## Rules
|
|
37
|
+
|
|
38
|
+
- A `devDefault` satisfies its own `validate` hints, or a fresh project refuses to serve.
|
|
39
|
+
- A name a plugin already declares (auth's `AUTH_SECRET`, `APP_URL`) is an error: read the
|
|
40
|
+
plugin's var instead of declaring it again.
|
|
41
|
+
|
|
42
|
+
**Check:** `pnpm check` passes, and `pnpm dev` serves with the var at its dev default.
|
|
43
|
+
|
|
44
|
+
## Entities
|
|
45
|
+
|
|
46
|
+
`procedure({ reads, writes })` types its names from the entities plugins declare: the Drizzle
|
|
47
|
+
schema's exports and auth's tables, so a table's name is already an entity. State kept anywhere
|
|
48
|
+
else (files, a repo, a remote service) has no table, so name it in `entities`:
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
api({ entities: ["settings", "repos"] }),
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Then `procedure({ auth: true, writes: ["settings"] })` types, and a screen that reads
|
|
55
|
+
`settings` redraws after it. A name may contain letters, digits, `_`, `.` and `-`; a bad name
|
|
56
|
+
fails `slotform generate`. A name a plugin already declares (a table) is an error: use the table's
|
|
57
|
+
name as it is. With no database and no auth, the names you list are the whole vocabulary, so
|
|
58
|
+
`reads` and `writes` take only them.
|
|
59
|
+
|
|
60
|
+
**Check:** `pnpm check` passes, and a `writes` name outside the vocabulary is a type error.
|
|
61
|
+
|
|
62
|
+
## A client of another app's server
|
|
63
|
+
|
|
64
|
+
A web or native app that only talks to a server another Slotform app runs names it with `server`.
|
|
65
|
+
It owns no worker, so it carries no `db()`, `auth()` or deploy target, and `api()` then requires
|
|
66
|
+
none:
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
// slotform.config.ts
|
|
70
|
+
plugins: [vite(), react(), reactUi(), api({ server: "../server" })], // web
|
|
71
|
+
plugins: [expo({ scheme: "acme" }), api({ server: "../server" }), nativeUi()], // native
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`slotform generate` writes, in the client app, `.slotform/schema.ts` (a copy of the server's, so a `Form`
|
|
75
|
+
derives its fields from the server's procedures and a write invalidates the entities the server
|
|
76
|
+
names) and `.slotform/server.ts`, which exports the server's `AppRouter` type. The client is typed by it
|
|
77
|
+
(`createClient<AppRouter>({ url })`, [the client page](./client.md)) and its `url` is the server's
|
|
78
|
+
address, which the app owns. Generate fails, naming the fix, when the server app has not generated
|
|
79
|
+
its `.slotform/schema.ts`, `.slotform/server.json` or router declaration (run `slotform generate` there
|
|
80
|
+
first, and again after its procedures change), and when this app has routable files under
|
|
81
|
+
`src/worker/routes`. `slotform dev` copies the schema again when the server's changes.
|
|
82
|
+
|
|
83
|
+
A web client calls the server cross-origin, so the server's `app.origins` lists this app's origin.
|
|
84
|
+
|
|
85
|
+
**Check:** `pnpm check` passes, and a procedure the server does not have is a type error on the client.
|
package/guide/mcp.md
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# Serving MCP
|
|
2
|
+
|
|
3
|
+
A worker serves MCP clients at `POST /mcp` when `src/worker/mcp.ts` exists. Its default export
|
|
4
|
+
lists the procedures an agent may call; every other procedure is unknown to it. It needs
|
|
5
|
+
`auth({ mcp: true })` (auth's `mcp-oauth` page): the access token that
|
|
6
|
+
provider issues is the only credential `/mcp` accepts.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
// src/worker/mcp.ts
|
|
10
|
+
import { defineMcp } from "@slotform/api/mcp";
|
|
11
|
+
import type * as routes from "./routes/index.ts";
|
|
12
|
+
|
|
13
|
+
export default defineMcp<typeof routes>({
|
|
14
|
+
instructions: "Plan and describe a tracking setup.",
|
|
15
|
+
tools: {
|
|
16
|
+
"projects.list": "Lists the projects of the organization.",
|
|
17
|
+
"pages.describe": "Edits a page's description.",
|
|
18
|
+
},
|
|
19
|
+
});
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
A tool is a procedure under its dotted router path as its name, and its description is the
|
|
23
|
+
string. The keys are typed as the router's procedure paths, so a namespace or a missing path
|
|
24
|
+
fails type-checking. `tools/list` answers in the file's order.
|
|
25
|
+
|
|
26
|
+
## What generate checks
|
|
27
|
+
|
|
28
|
+
`slotform generate` refuses the file without `auth({ mcp: true })`, without a routable file in
|
|
29
|
+
`src/worker/routes`, and when `api({ prefix })` is `/mcp`. Otherwise the worker mounts the
|
|
30
|
+
endpoint, `/mcp` joins `api.slots.routePrefixes`, and `mcp` is a reserved organization slug.
|
|
31
|
+
Building the worker refuses, naming the tool, a path that names no procedure, a name outside
|
|
32
|
+
letters, digits, `_`, `-` and `.` or over 128 characters, an input that is not an object schema
|
|
33
|
+
or holds a type JSON Schema cannot (a `bigint`), and a `z.date()` inside a record, tuple,
|
|
34
|
+
intersection or lazy schema.
|
|
35
|
+
|
|
36
|
+
## A call
|
|
37
|
+
|
|
38
|
+
Each request, in order: a browser `Origin` off the allow-list is `403`; the bearer token is
|
|
39
|
+
verified (`401`, `403` and `429` answer with the challenge unchanged, and a refused token draws
|
|
40
|
+
the per-IP budget); the body is read, at most 4 MiB (`413`), and a JSON error or a batch is `400`.
|
|
41
|
+
The procedure then runs in process as the grant's member in the grant's organization, every
|
|
42
|
+
middleware included. A cookie authenticates nothing here, and the procedure's `reqHeaders` hold
|
|
43
|
+
no `cookie` or `authorization`.
|
|
44
|
+
|
|
45
|
+
- **Input.** The tool's input schema is the procedure's whole input as JSON Schema (scope ids and
|
|
46
|
+
pagination included); a `z.date()` is a `date-time` string and arrives as a `Date`.
|
|
47
|
+
- **Result.** A plain object is `structuredContent`; any other value is `{ result: value }`. The
|
|
48
|
+
text content is the same JSON.
|
|
49
|
+
- **Refusals.** An `ApiError` is an `isError` result carrying `{ code, message, data }`; any other
|
|
50
|
+
throw is `isError` with `INTERNAL_SERVER_ERROR` and no message, and is logged. An unlisted
|
|
51
|
+
name is the protocol's invalid-params error.
|
|
52
|
+
- **Read-only.** A procedure written with `.query()` carries `readOnlyHint`; `.mutation()` and
|
|
53
|
+
`.handler()` carry none.
|
|
54
|
+
- **Eras.** Clients of protocol 2026-07-28 and of the 2025 era are both served, statelessly:
|
|
55
|
+
nothing is held between requests, GET and DELETE are `405`, and `subscriptions/listen` is
|
|
56
|
+
refused.
|
|
57
|
+
- **Instructions.** The worker appends the grant's organization id, which is the only place an
|
|
58
|
+
agent learns it.
|
|
59
|
+
|
|
60
|
+
## Rules
|
|
61
|
+
|
|
62
|
+
- A tool that must differ from its procedure is a new procedure; the file only lists.
|
|
63
|
+
- A procedure that forwards `reqHeaders` to the auth service finds no session: an agent has no
|
|
64
|
+
cookie.
|
|
65
|
+
- The context key `_caller` is the endpoint's, and `oauth` is the provider's; neither is a scope
|
|
66
|
+
name.
|
|
67
|
+
|
|
68
|
+
**Check:** `slotform generate`, then an MCP client lists the tools and calls one.
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# Worker middleware
|
|
2
|
+
|
|
3
|
+
Two optional files hold plain Hono middleware, and the worker mounts both on its own:
|
|
4
|
+
|
|
5
|
+
| File | Runs | Sees |
|
|
6
|
+
| --- | --- | --- |
|
|
7
|
+
| `src/worker/middleware.ts` | after CORS and logging, before the plugin context is built | the request only |
|
|
8
|
+
| `src/worker/middleware.context.ts` | after the context is built, before any route | `slotformContext(c)` |
|
|
9
|
+
|
|
10
|
+
Put a guard that needs no database in the first, so it rejects before the worker pays for a db
|
|
11
|
+
client. Put anything that needs `db` or `auth` in the second, including a raw Hono route outside
|
|
12
|
+
the RPC tree (a multipart upload, a webhook), which then reaches the same clients the procedures
|
|
13
|
+
use. Type the context with the generated `WorkerContext`.
|
|
14
|
+
|
|
15
|
+
A raw route answers under a prefix the worker owns, since the deploy target forwards only those
|
|
16
|
+
paths to it (the dev server proxies them, the deployed assets let them reach the worker first;
|
|
17
|
+
anything else is the web client's fallback). Mount it under the api prefix (`/rpc` by default,
|
|
18
|
+
`api({ prefix })`): this middleware runs ahead of the RPC tree's own handler and its JSON-only
|
|
19
|
+
gate. `/api/auth` and `/mcp` are other plugins' prefixes.
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
// src/worker/middleware.context.ts
|
|
23
|
+
import type { WorkerContext } from "virtual:slotform-procedure";
|
|
24
|
+
import { isForbiddenOrigin, slotformContext } from "@slotform/api/runtime";
|
|
25
|
+
import { createMiddleware } from "hono/factory";
|
|
26
|
+
|
|
27
|
+
export default createMiddleware(async (c, next) => {
|
|
28
|
+
if (c.req.path === "/rpc/photos" && c.req.method === "POST") {
|
|
29
|
+
if (isForbiddenOrigin(c)) return c.json({ code: "FORBIDDEN" }, 403);
|
|
30
|
+
const { db } = slotformContext<WorkerContext>(c);
|
|
31
|
+
// store the upload with db
|
|
32
|
+
}
|
|
33
|
+
await next();
|
|
34
|
+
});
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Rules
|
|
38
|
+
|
|
39
|
+
- Export Hono middleware as it is, `(c, next) => …` or `createMiddleware(…)`, never wrapped: the
|
|
40
|
+
worker tells it by its two parameters from a function that adds to the context.
|
|
41
|
+
- Neither file imports from `src/worker/routes/`, and `WorkerContext` comes in with `import type`:
|
|
42
|
+
the generated `.slotform/procedure.ts` imports these files back, so either import is a cycle.
|
|
43
|
+
- Every raw route that changes state calls `isForbiddenOrigin(c)` first. The RPC tree gets its
|
|
44
|
+
CSRF guard from its JSON content type on a `POST` (a `GET` reaches queries only and has no
|
|
45
|
+
body); a multipart upload has no such guard. It refuses a request whose browser `Origin` is off
|
|
46
|
+
the CORS allow-list and passes one with no `Origin` (a browser cannot forge that cross-site, and
|
|
47
|
+
the native client sends none).
|
|
48
|
+
|
|
49
|
+
## Renamed cache headers
|
|
50
|
+
|
|
51
|
+
A procedure's response carries `x-slotform-reads` and `x-slotform-writes` (`SLOTFORM_READS_HEADER`,
|
|
52
|
+
`SLOTFORM_WRITES_HEADER` from `@slotform/api/procedure`). A worker replacing hand-rolled code
|
|
53
|
+
whose deployed clients parse other names mirrors them in `src/worker/middleware.ts` until those
|
|
54
|
+
builds are gone:
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
// src/worker/middleware.ts
|
|
58
|
+
import { SLOTFORM_READS_HEADER, SLOTFORM_WRITES_HEADER } from "@slotform/api/procedure";
|
|
59
|
+
import { createMiddleware } from "hono/factory";
|
|
60
|
+
|
|
61
|
+
const LEGACY: Record<string, string> = {
|
|
62
|
+
[SLOTFORM_READS_HEADER]: "x-sw-reads",
|
|
63
|
+
[SLOTFORM_WRITES_HEADER]: "x-sw-writes",
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
export default createMiddleware(async (c, next) => {
|
|
67
|
+
await next();
|
|
68
|
+
for (const [current, legacy] of Object.entries(LEGACY)) {
|
|
69
|
+
const value = c.res.headers.get(current);
|
|
70
|
+
if (value) c.header(legacy, value);
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Request headers have no such mirror: expo's version gate reads only `x-slotform-client-build` and
|
|
76
|
+
`x-slotform-client-platform`, so a build stamping other names is never walled. Ship a release that
|
|
77
|
+
stamps the current names before raising a floor.
|
|
78
|
+
|
|
79
|
+
**Check:** `pnpm check` passes, and the route answers under `pnpm dev`.
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# Procedures
|
|
2
|
+
|
|
3
|
+
A procedure is one typed endpoint. Route files live flat in `src/worker/routes/` (a
|
|
4
|
+
subdirectory is ignored); each named export is an object of procedures, and the generated
|
|
5
|
+
barrel merges every file's exports into the router.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
// src/worker/routes/projects.ts
|
|
9
|
+
import { procedure } from "virtual:slotform-procedure";
|
|
10
|
+
import { ApiError } from "@slotform/api/error";
|
|
11
|
+
import { z } from "@slotform/api/schema";
|
|
12
|
+
import { organization } from "@slotform/auth/scope";
|
|
13
|
+
|
|
14
|
+
export const projects = {
|
|
15
|
+
list: procedure({ auth: true, scope: organization, paginated: true, reads: ["projects"] })
|
|
16
|
+
.input(z.object({ status: z.enum(["active", "archived"]).optional() }))
|
|
17
|
+
.query(async ({ input, context }) => {
|
|
18
|
+
// context.db, context.user, context.session, context.organization, context.member
|
|
19
|
+
// context.env.APP_URL: typed as the generated `Env` on Cloudflare, `unknown` on node
|
|
20
|
+
// input.organizationId (the scope), input.cursor and input.limit (paginated)
|
|
21
|
+
}),
|
|
22
|
+
|
|
23
|
+
create: procedure({ auth: true, scope: organization, can: ["create", "project"], writes: ["projects"] })
|
|
24
|
+
.input(z.object({ name: z.string().min(1) }))
|
|
25
|
+
.mutation(async ({ input, context }) => {
|
|
26
|
+
if (input.name === "admin") throw new ApiError("BAD_REQUEST", { message: "Reserved name" });
|
|
27
|
+
}),
|
|
28
|
+
};
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Rules
|
|
32
|
+
|
|
33
|
+
- A route file exports procedures and nothing else: every `export` of every file (`export *` in
|
|
34
|
+
the generated barrel) is a key of the router, which `AppRouter`, the client and
|
|
35
|
+
`.slotform/schema.ts` take whole. So `export const` is an object of procedures (nested objects
|
|
36
|
+
of procedures are namespaces); a constant, a zod schema, a type's value or a helper function
|
|
37
|
+
exported from a route file becomes a router key that is no procedure. Keep those unexported
|
|
38
|
+
in the file, or in `src/worker/lib/` and import them; `export type` and `export interface`
|
|
39
|
+
are fine. These are the API's routes: the web app's `src/app/routes/` are
|
|
40
|
+
TanStack file routes (`node_modules/@slotform/react/guide/routes.md`).
|
|
41
|
+
- Import `procedure` from `virtual:slotform-procedure`, `z` from `@slotform/api/schema`, and
|
|
42
|
+
`ApiError` from `@slotform/api/error`, never the package root, which drags Node-only
|
|
43
|
+
codegen into the worker bundle.
|
|
44
|
+
- A procedure with a `scope` or `paginated` takes an object input schema, which keeps its
|
|
45
|
+
unknown-key policy (`.strict()` refuses extras) and refinements. Another schema, or one
|
|
46
|
+
declaring a key the config adds, throws when the route loads.
|
|
47
|
+
- Use `.query()` for a read and `.mutation()` for a write: a query travels as a `GET`, and MCP
|
|
48
|
+
marks it read-only. `.handler()` is a mutation.
|
|
49
|
+
- Declare `reads` on every query and `writes` on every mutation that touches an entity. The client
|
|
50
|
+
invalidates caches from them, and a procedure that declares nothing invalidates nothing.
|
|
51
|
+
- Prefer `can: [action, resource]` to `rbac: [resource, actions[]]`; both check the same thing,
|
|
52
|
+
and both run when both are set. `rbac` takes at least one action (`["task", []]` does not
|
|
53
|
+
type-check), and an empty request is refused.
|
|
54
|
+
- Never read the session's active organization: a scope's id arrives in the input.
|
|
55
|
+
|
|
56
|
+
## Options
|
|
57
|
+
|
|
58
|
+
| Option | Effect |
|
|
59
|
+
| --- | --- |
|
|
60
|
+
| none | Public, no middleware |
|
|
61
|
+
| `auth: true` | Requires a session |
|
|
62
|
+
| `scope` | Requires `auth: true`. A scope from `@slotform/auth/scope` (`organization`, or one declared with `defineScope`): the input gains `<name>Id`, and the row, every tier above it and the caller's `member` row of the organization are loaded into the context. A missing row, a non-member, and a row the consumer's membership or visibility predicates hide all answer `NOT_FOUND` |
|
|
63
|
+
| `can` / `rbac` | Require `auth: true` and a `scope`. Check the caller's role in the scope's organization against the roles the auth config declares. Names autocomplete from `auth({ organization: { ac } })`; with no organization they cannot be set |
|
|
64
|
+
| `rateLimit` | `"ip"`, `"email"` (keyed by `input.email`) or both |
|
|
65
|
+
| `paginated: true` | Adds `cursor` and `limit` to the input; `limit` defaults to 20 and a value outside 1 to `maxLimit` answers `BAD_REQUEST` |
|
|
66
|
+
| `paginated: "window"` | Adds `offset` and `limit` instead of `cursor`; the handler answers `{ data, total, offset }` (`paginateWindow`, [utilities](./utilities.md)) |
|
|
67
|
+
| `maxLimit` | With `paginated`: the most rows one call may ask for, 100 unless named (at most 10000); the default `limit` is 20 or `maxLimit` if lower |
|
|
68
|
+
| `sort` | With `paginated` (without it the procedure throws when built): the columns a caller may order by (`sort: ["createdAt", "title"]`); the input gains `sort?: { column, direction }`, typed to them, and a `Table` over the read sends its header sort there |
|
|
69
|
+
| `reads` / `writes` | The entities the procedure reads or writes, autocompleting from the Drizzle schema's exports, auth's tables and the names `api`'s `entities` option adds. On success the response carries `x-slotform-reads` / `x-slotform-writes`; a thrown error carries neither |
|
|
70
|
+
|
|
71
|
+
## Input and output
|
|
72
|
+
|
|
73
|
+
One schema types two sides: the caller sends `z.input` and the handler reads `z.output`. A
|
|
74
|
+
`.default()` field is optional for the caller and present in the handler; a `.transform()` field
|
|
75
|
+
takes the value before the transform and hands over the value after it. `.output(schema)`
|
|
76
|
+
mirrors it: the handler returns the schema's input, and the caller receives its output.
|
|
77
|
+
|
|
78
|
+
## Middleware on one procedure
|
|
79
|
+
|
|
80
|
+
`.use()` returns extra context, typed from its return value. Type a reusable one with
|
|
81
|
+
`Middleware<TContextIn, TExtra>` from `@slotform/api`:
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
procedure({ auth: true })
|
|
85
|
+
.use(async ({ context }) => {
|
|
86
|
+
const project = await findProject(context.db, context.session);
|
|
87
|
+
if (!project) throw new ApiError("NOT_FOUND");
|
|
88
|
+
return { project };
|
|
89
|
+
})
|
|
90
|
+
.query(({ context }) => context.project);
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
How the screen tells it from another failure is under [not found](./client.md#not-found).
|
|
94
|
+
|
|
95
|
+
**Check:** `pnpm check` passes.
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# Pagination and slugs
|
|
2
|
+
|
|
3
|
+
Helpers a procedure handler imports: cursor and window pagination over a Drizzle query, a
|
|
4
|
+
selection resolved to a where clause, and slugs for a URL segment.
|
|
5
|
+
|
|
6
|
+
## Cursor pagination
|
|
7
|
+
|
|
8
|
+
A `paginated: true` procedure ([procedures](./procedures.md)) takes `input.cursor` and
|
|
9
|
+
`input.limit`; hand both to `paginate` with a relational query whose rows have `id` and
|
|
10
|
+
`createdAt` (or the order columns you name):
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import { paginate } from "@slotform/api/lib/cursor";
|
|
14
|
+
|
|
15
|
+
return paginate(db.query.projects, {
|
|
16
|
+
where: eq(projects.organizationId, input.organizationId),
|
|
17
|
+
orderBy: { column: projects.createdAt, direction: "desc" },
|
|
18
|
+
idColumn: projects.id,
|
|
19
|
+
cursor: input.cursor,
|
|
20
|
+
limit: input.limit,
|
|
21
|
+
});
|
|
22
|
+
// { data: Project[], nextCursor: string | null }
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Rows order by the order column in the direction given, an empty value (`null`) last either way,
|
|
26
|
+
then by `id` in the first column's direction, so a `desc` page is the newest rows and rows sharing
|
|
27
|
+
a moment page in a stable order by `id`. The cursor encodes the last row's order-column values and
|
|
28
|
+
`id`, so the next page continues past that row, into the empty values once the others are spent.
|
|
29
|
+
`nextCursor` is `null` on the last page.
|
|
30
|
+
|
|
31
|
+
`orderBy` takes one column or an array of them (`[{ column: tasks.title, direction: "asc" }, ...]`),
|
|
32
|
+
and `sort: input.sort` (the caller's, from a procedure declaring `sort`) replaces it; `id` is always
|
|
33
|
+
the last tiebreak. Any column of the table is a key, nullable or not. A cursor with another number
|
|
34
|
+
of order columns answers `BAD_REQUEST`.
|
|
35
|
+
|
|
36
|
+
`columns` is Drizzle's relational `columns` config narrowed to exclusion: the row's keys other than
|
|
37
|
+
`id` and the order columns, each `false` (`columns: { body: false }`). The answer's row type omits each
|
|
38
|
+
key it names, and `id` and the order columns always stay because the cursor reads them. A malformed
|
|
39
|
+
cursor (not base64, not the JSON of the values and an id, a non-numeric time, an empty id)
|
|
40
|
+
answers `BAD_REQUEST`, before any query. `clampLimit(limit)` keeps a limit within 1 to
|
|
41
|
+
`LIMIT_CEILING` (10 000), defaulting to `DEFAULT_LIMIT` (20).
|
|
42
|
+
|
|
43
|
+
## Window pagination
|
|
44
|
+
|
|
45
|
+
A `paginated: "window"` procedure answers a page at an offset and the filter's total, both from
|
|
46
|
+
the one `where`:
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { paginateWindow } from "@slotform/api/lib/window";
|
|
50
|
+
|
|
51
|
+
return paginateWindow(db.query.tasks, {
|
|
52
|
+
where: input.q ? like(tasks.title, `%${input.q}%`) : undefined,
|
|
53
|
+
orderBy: { column: tasks.createdAt, direction: "desc" },
|
|
54
|
+
idColumn: tasks.id,
|
|
55
|
+
sort: input.sort,
|
|
56
|
+
offset: input.offset,
|
|
57
|
+
limit: input.limit,
|
|
58
|
+
db,
|
|
59
|
+
});
|
|
60
|
+
// { data: Task[], total: number, offset: number }
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Order follows the same rules as `paginate`, and a window may order by an SQL expression, not only a
|
|
64
|
+
column. `sorts` maps each key the procedure's `sort` names to what it orders by, a column or an
|
|
65
|
+
expression, so the header sort of a `Table` reaches the whole query:
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
import { bm25, eq, sql } from "@slotform/db/orm";
|
|
69
|
+
|
|
70
|
+
const nocase = (column: SQLiteColumn) => sql`${column} collate nocase`;
|
|
71
|
+
|
|
72
|
+
return paginateWindow(db.query.tasks, {
|
|
73
|
+
where: match ? sql`${taskSearch} MATCH ${match}` : undefined,
|
|
74
|
+
// A search with no sort ranks by relevance.
|
|
75
|
+
orderBy: match
|
|
76
|
+
? { column: bm25(taskSearch), direction: "asc" }
|
|
77
|
+
: { column: tasks.addedAt, direction: "desc" },
|
|
78
|
+
sorts: { title: nocase(tasks.title), points: tasks.points },
|
|
79
|
+
sort: input.sort,
|
|
80
|
+
// The ids and the count come from this query: join what `where` and the order name.
|
|
81
|
+
join: (query) => query.innerJoin(taskSearch, eq(taskSearch.rowid, tasks.seq)),
|
|
82
|
+
idColumn: tasks.id,
|
|
83
|
+
offset: input.offset,
|
|
84
|
+
limit: input.limit,
|
|
85
|
+
db,
|
|
86
|
+
});
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
A key `sorts` does not name sorts by the column of that name (and an unknown key answers
|
|
90
|
+
`BAD_REQUEST`). The page is read ids first: one statement orders and pages the ids alone (a sorter
|
|
91
|
+
holding a key and an id, not every column of a wide row), then the rows are read by id, so a deep
|
|
92
|
+
offset over tens of thousands of rows stays a narrow sort. Keep the filter's columns indexed: the
|
|
93
|
+
count scans the matches.
|
|
94
|
+
|
|
95
|
+
`paginate` takes `sorts` too, columns only: a keyset reads the order values off the row, which an
|
|
96
|
+
expression is not. Order a cursor list by a column, or window it.
|
|
97
|
+
|
|
98
|
+
## Selection over a query
|
|
99
|
+
|
|
100
|
+
A `Table` with `choose` over a window or `pages` read can hold "every row the query matches but
|
|
101
|
+
these". The mutation takes that as a field, `selector(query)` from `@slotform/api/schema`
|
|
102
|
+
(`{ ids } | { query, except }`, the query typed as the list's filter), and resolves it:
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { chosenWhere } from "@slotform/api/lib/chosen";
|
|
106
|
+
|
|
107
|
+
const query = z.object({ q: z.string().optional() });
|
|
108
|
+
const where = ({ q }: z.infer<typeof query>) => (q ? like(tasks.title, `%${q}%`) : undefined);
|
|
109
|
+
|
|
110
|
+
remove: procedure({ auth: true, writes: ["tasks"] })
|
|
111
|
+
.input(z.object({ tasks: selector(query) }))
|
|
112
|
+
.mutation(({ input, context }) =>
|
|
113
|
+
context.db.delete(tasks).where(chosenWhere(input.tasks, { id: tasks.id, where })),
|
|
114
|
+
),
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Build the list's `where` from the same `query` function, so the selection and the table mean the
|
|
118
|
+
same rows. Each id list binds one value, so a selection of any length fits a D1 statement. The
|
|
119
|
+
client passes the table's `picked` whole: `mutateAsync({ tasks: picked })`.
|
|
120
|
+
|
|
121
|
+
## Slugs
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
import { isReservedSlug, slugify } from "@slotform/api/lib/slugify";
|
|
125
|
+
|
|
126
|
+
slugify("My Project"); // "my-project"
|
|
127
|
+
slugify("shop.example.com"); // "shop-example-com": a dot is a word boundary
|
|
128
|
+
isReservedSlug("admin"); // true
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
`slugify` never refuses. A procedure checks `isReservedSlug(slug)` and answers a reserved slug as
|
|
132
|
+
its own field error; the words are `RESERVED_SLUGS`. An organization's slug is refused on the server
|
|
133
|
+
by auth (`node_modules/@slotform/auth/guide/organizations.md`).
|
|
134
|
+
|
|
135
|
+
**Check:** `pnpm check` passes, and a list call pages past the first `nextCursor`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,123 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@slotform/api",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "API plugin for slotform: Hono + oRPC + Zod behind a procedure builder and a typed client.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/fcalell/slotform.git",
|
|
9
|
+
"directory": "plugins/api"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/fcalell/slotform/tree/master/plugins/api#readme",
|
|
12
|
+
"publishConfig": {
|
|
13
|
+
"access": "public"
|
|
14
|
+
},
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=24.14.0"
|
|
17
|
+
},
|
|
18
|
+
"type": "module",
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"default": "./dist/index.js"
|
|
24
|
+
},
|
|
25
|
+
"./runtime": {
|
|
26
|
+
"types": "./dist/worker/index.d.ts",
|
|
27
|
+
"default": "./dist/worker/index.js"
|
|
28
|
+
},
|
|
29
|
+
"./procedure": {
|
|
30
|
+
"types": "./dist/procedure.d.ts",
|
|
31
|
+
"default": "./dist/procedure.js"
|
|
32
|
+
},
|
|
33
|
+
"./mcp": {
|
|
34
|
+
"types": "./dist/mcp.d.ts",
|
|
35
|
+
"default": "./dist/mcp.js"
|
|
36
|
+
},
|
|
37
|
+
"./error": {
|
|
38
|
+
"types": "./dist/error.d.ts",
|
|
39
|
+
"default": "./dist/error.js"
|
|
40
|
+
},
|
|
41
|
+
"./client": {
|
|
42
|
+
"types": "./dist/client.d.ts",
|
|
43
|
+
"default": "./dist/client.js"
|
|
44
|
+
},
|
|
45
|
+
"./wire": {
|
|
46
|
+
"types": "./dist/wire.d.ts",
|
|
47
|
+
"default": "./dist/wire.js"
|
|
48
|
+
},
|
|
49
|
+
"./query-invalidation": {
|
|
50
|
+
"types": "./dist/query-invalidation.d.ts",
|
|
51
|
+
"default": "./dist/query-invalidation.js"
|
|
52
|
+
},
|
|
53
|
+
"./schema": {
|
|
54
|
+
"types": "./dist/schema.d.ts",
|
|
55
|
+
"default": "./dist/schema.js"
|
|
56
|
+
},
|
|
57
|
+
"./types": {
|
|
58
|
+
"types": "./dist/types.d.ts",
|
|
59
|
+
"default": "./dist/types.js"
|
|
60
|
+
},
|
|
61
|
+
"./lib/cursor": {
|
|
62
|
+
"types": "./dist/lib/cursor.d.ts",
|
|
63
|
+
"default": "./dist/lib/cursor.js"
|
|
64
|
+
},
|
|
65
|
+
"./lib/window": {
|
|
66
|
+
"types": "./dist/lib/window.d.ts",
|
|
67
|
+
"default": "./dist/lib/window.js"
|
|
68
|
+
},
|
|
69
|
+
"./lib/chosen": {
|
|
70
|
+
"types": "./dist/lib/chosen.d.ts",
|
|
71
|
+
"default": "./dist/lib/chosen.js"
|
|
72
|
+
},
|
|
73
|
+
"./lib/slugify": {
|
|
74
|
+
"types": "./dist/lib/slugify.d.ts",
|
|
75
|
+
"default": "./dist/lib/slugify.js"
|
|
76
|
+
},
|
|
77
|
+
"./local-origin": {
|
|
78
|
+
"types": "./dist/lib/local-origin.d.ts",
|
|
79
|
+
"default": "./dist/lib/local-origin.js"
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
"files": [
|
|
83
|
+
"dist",
|
|
84
|
+
"src",
|
|
85
|
+
"guide",
|
|
86
|
+
"README.md",
|
|
87
|
+
"LICENSE",
|
|
88
|
+
"!src/**/*.test.ts",
|
|
89
|
+
"!src/**/__fixtures__",
|
|
90
|
+
"!dist/**/*.test.*"
|
|
91
|
+
],
|
|
92
|
+
"dependencies": {
|
|
93
|
+
"@slotform/cli": "^0.1.1",
|
|
94
|
+
"@modelcontextprotocol/server": "2.4.0",
|
|
95
|
+
"slugify": "^1.6.9",
|
|
96
|
+
"ws": "^8.23.0"
|
|
97
|
+
},
|
|
98
|
+
"devDependencies": {
|
|
99
|
+
"@slotform/typescript-config": "^0.1.1",
|
|
100
|
+
"@orpc/client": "^1.16.2",
|
|
101
|
+
"@orpc/server": "^1.16.2",
|
|
102
|
+
"@types/better-sqlite3": "^9.6.0",
|
|
103
|
+
"@types/node": "^26.6.6",
|
|
104
|
+
"better-sqlite3": "^13.2.0",
|
|
105
|
+
"drizzle-orm": "^0.45.4",
|
|
106
|
+
"hono": "^4.13.19",
|
|
107
|
+
"typescript": "^7.0.2",
|
|
108
|
+
"zod": "^4.6.7"
|
|
109
|
+
},
|
|
110
|
+
"peerDependencies": {
|
|
111
|
+
"@orpc/client": "^1.16.2",
|
|
112
|
+
"@orpc/server": "^1.16.2",
|
|
113
|
+
"drizzle-orm": "^0.45.4",
|
|
114
|
+
"hono": "^4.13.19",
|
|
115
|
+
"zod": "^4.6.7"
|
|
116
|
+
},
|
|
117
|
+
"scripts": {
|
|
118
|
+
"build": "tsc -p tsconfig.build.json",
|
|
119
|
+
"check-types": "tsc --noEmit --pretty",
|
|
120
|
+
"test": "node --test 'src/**/*.test.ts'",
|
|
121
|
+
"clear": "rm -rf dist node_modules .turbo"
|
|
122
|
+
}
|
|
6
123
|
}
|