@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.
Files changed (151) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/dist/client.d.ts +16 -0
  4. package/dist/client.d.ts.map +1 -0
  5. package/dist/client.js +98 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/error.d.ts +2 -0
  8. package/dist/error.d.ts.map +1 -0
  9. package/dist/error.js +2 -0
  10. package/dist/error.js.map +1 -0
  11. package/dist/index.d.ts +153 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +640 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/lib/chosen.d.ts +12 -0
  16. package/dist/lib/chosen.d.ts.map +1 -0
  17. package/dist/lib/chosen.js +18 -0
  18. package/dist/lib/chosen.js.map +1 -0
  19. package/dist/lib/cursor.d.ts +68 -0
  20. package/dist/lib/cursor.d.ts.map +1 -0
  21. package/dist/lib/cursor.js +220 -0
  22. package/dist/lib/cursor.js.map +1 -0
  23. package/dist/lib/limits.d.ts +4 -0
  24. package/dist/lib/limits.d.ts.map +1 -0
  25. package/dist/lib/limits.js +10 -0
  26. package/dist/lib/limits.js.map +1 -0
  27. package/dist/lib/local-origin.d.ts +2 -0
  28. package/dist/lib/local-origin.d.ts.map +1 -0
  29. package/dist/lib/local-origin.js +17 -0
  30. package/dist/lib/local-origin.js.map +1 -0
  31. package/dist/lib/slugify.d.ts +4 -0
  32. package/dist/lib/slugify.d.ts.map +1 -0
  33. package/dist/lib/slugify.js +26 -0
  34. package/dist/lib/slugify.js.map +1 -0
  35. package/dist/lib/window.d.ts +52 -0
  36. package/dist/lib/window.d.ts.map +1 -0
  37. package/dist/lib/window.js +70 -0
  38. package/dist/lib/window.js.map +1 -0
  39. package/dist/mcp-path.d.ts +2 -0
  40. package/dist/mcp-path.d.ts.map +1 -0
  41. package/dist/mcp-path.js +3 -0
  42. package/dist/mcp-path.js.map +1 -0
  43. package/dist/mcp.d.ts +15 -0
  44. package/dist/mcp.d.ts.map +1 -0
  45. package/dist/mcp.js +5 -0
  46. package/dist/mcp.js.map +1 -0
  47. package/dist/node/barrel.d.ts +3 -0
  48. package/dist/node/barrel.d.ts.map +1 -0
  49. package/dist/node/barrel.js +70 -0
  50. package/dist/node/barrel.js.map +1 -0
  51. package/dist/node/codegen.d.ts +10 -0
  52. package/dist/node/codegen.d.ts.map +1 -0
  53. package/dist/node/codegen.js +132 -0
  54. package/dist/node/codegen.js.map +1 -0
  55. package/dist/node/procedure-codegen.d.ts +14 -0
  56. package/dist/node/procedure-codegen.d.ts.map +1 -0
  57. package/dist/node/procedure-codegen.js +95 -0
  58. package/dist/node/procedure-codegen.js.map +1 -0
  59. package/dist/node/schema-child.d.ts +2 -0
  60. package/dist/node/schema-child.d.ts.map +1 -0
  61. package/dist/node/schema-child.js +31 -0
  62. package/dist/node/schema-child.js.map +1 -0
  63. package/dist/node/schema-source.d.ts +3 -0
  64. package/dist/node/schema-source.d.ts.map +1 -0
  65. package/dist/node/schema-source.js +33 -0
  66. package/dist/node/schema-source.js.map +1 -0
  67. package/dist/node/server-client.d.ts +19 -0
  68. package/dist/node/server-client.d.ts.map +1 -0
  69. package/dist/node/server-client.js +45 -0
  70. package/dist/node/server-client.js.map +1 -0
  71. package/dist/node/types.d.ts +42 -0
  72. package/dist/node/types.d.ts.map +1 -0
  73. package/dist/node/types.js +13 -0
  74. package/dist/node/types.js.map +1 -0
  75. package/dist/not-found.d.ts +2 -0
  76. package/dist/not-found.d.ts.map +1 -0
  77. package/dist/not-found.js +6 -0
  78. package/dist/not-found.js.map +1 -0
  79. package/dist/procedure.d.ts +188 -0
  80. package/dist/procedure.d.ts.map +1 -0
  81. package/dist/procedure.js +392 -0
  82. package/dist/procedure.js.map +1 -0
  83. package/dist/query-invalidation.d.ts +20 -0
  84. package/dist/query-invalidation.d.ts.map +1 -0
  85. package/dist/query-invalidation.js +66 -0
  86. package/dist/query-invalidation.js.map +1 -0
  87. package/dist/schema.d.ts +32 -0
  88. package/dist/schema.d.ts.map +1 -0
  89. package/dist/schema.js +103 -0
  90. package/dist/schema.js.map +1 -0
  91. package/dist/types.d.ts +30 -0
  92. package/dist/types.d.ts.map +1 -0
  93. package/dist/types.js +2 -0
  94. package/dist/types.js.map +1 -0
  95. package/dist/wire.d.ts +11 -0
  96. package/dist/wire.d.ts.map +1 -0
  97. package/dist/wire.js +26 -0
  98. package/dist/wire.js.map +1 -0
  99. package/dist/worker/guards.d.ts +6 -0
  100. package/dist/worker/guards.d.ts.map +1 -0
  101. package/dist/worker/guards.js +29 -0
  102. package/dist/worker/guards.js.map +1 -0
  103. package/dist/worker/index.d.ts +57 -0
  104. package/dist/worker/index.d.ts.map +1 -0
  105. package/dist/worker/index.js +418 -0
  106. package/dist/worker/index.js.map +1 -0
  107. package/dist/worker/mcp.d.ts +28 -0
  108. package/dist/worker/mcp.d.ts.map +1 -0
  109. package/dist/worker/mcp.js +361 -0
  110. package/dist/worker/mcp.js.map +1 -0
  111. package/dist/worker/request-log.d.ts +10 -0
  112. package/dist/worker/request-log.d.ts.map +1 -0
  113. package/dist/worker/request-log.js +37 -0
  114. package/dist/worker/request-log.js.map +1 -0
  115. package/guide/add-a-procedure.md +42 -0
  116. package/guide/background.md +86 -0
  117. package/guide/client.md +93 -0
  118. package/guide/config.md +85 -0
  119. package/guide/mcp.md +68 -0
  120. package/guide/middleware.md +79 -0
  121. package/guide/procedures.md +95 -0
  122. package/guide/utilities.md +135 -0
  123. package/package.json +120 -3
  124. package/src/client.ts +129 -0
  125. package/src/error.ts +1 -0
  126. package/src/index.ts +787 -0
  127. package/src/lib/chosen.ts +31 -0
  128. package/src/lib/cursor.ts +354 -0
  129. package/src/lib/limits.ts +10 -0
  130. package/src/lib/local-origin.ts +18 -0
  131. package/src/lib/slugify.ts +29 -0
  132. package/src/lib/window.ts +155 -0
  133. package/src/mcp-path.ts +2 -0
  134. package/src/mcp.ts +30 -0
  135. package/src/node/barrel.ts +77 -0
  136. package/src/node/codegen.ts +173 -0
  137. package/src/node/procedure-codegen.ts +131 -0
  138. package/src/node/schema-child.ts +31 -0
  139. package/src/node/schema-source.ts +45 -0
  140. package/src/node/server-client.ts +67 -0
  141. package/src/node/types.ts +64 -0
  142. package/src/not-found.ts +6 -0
  143. package/src/procedure.ts +935 -0
  144. package/src/query-invalidation.ts +106 -0
  145. package/src/schema.ts +133 -0
  146. package/src/types.ts +72 -0
  147. package/src/wire.ts +34 -0
  148. package/src/worker/guards.ts +37 -0
  149. package/src/worker/index.ts +681 -0
  150. package/src/worker/mcp.ts +470 -0
  151. package/src/worker/request-log.ts +50 -0
@@ -0,0 +1,361 @@
1
+ import { call, isProcedure, ORPCError } from "@orpc/server";
2
+ import { z } from "zod";
3
+ import { MCP_PATH } from "../mcp-path.js";
4
+ import { inputJsonSchema } from "../schema.js";
5
+ import { ipLimited, isForbiddenOrigin } from "./guards.js";
6
+ // The MCP endpoint: `POST /mcp` over the consumer's procedures. The SDK loads
7
+ // on the first request, so a worker without `src/worker/mcp.ts` never reads it.
8
+ const TOOL_NAME = /^[A-Za-z0-9_.-]{1,128}$/;
9
+ const MAX_BODY_BYTES = 4 * 1024 * 1024;
10
+ const SERVER_VERSION = "1.0.0";
11
+ const INTERNAL = {
12
+ code: "INTERNAL_SERVER_ERROR",
13
+ message: "Internal server error",
14
+ };
15
+ // The schemas a walk of `def` reaches below the one holding it.
16
+ function children(schema) {
17
+ // zod's `def` is a union keyed by `type`; the walk reads each member's own fields by name.
18
+ const def = schema._zod.def;
19
+ const found = [];
20
+ switch (def.type) {
21
+ case "object":
22
+ found.push(...Object.values(def.shape));
23
+ break;
24
+ case "array":
25
+ found.push(def.element);
26
+ break;
27
+ case "optional":
28
+ case "nullable":
29
+ case "default":
30
+ case "prefault":
31
+ case "nonoptional":
32
+ case "readonly":
33
+ case "catch":
34
+ found.push(def.innerType);
35
+ break;
36
+ case "union":
37
+ found.push(...def.options);
38
+ break;
39
+ case "pipe":
40
+ found.push(def.in);
41
+ break;
42
+ case "record":
43
+ found.push(def.keyType, def.valueType);
44
+ break;
45
+ case "tuple":
46
+ found.push(...def.items, def.rest);
47
+ break;
48
+ case "intersection":
49
+ found.push(def.left, def.right);
50
+ break;
51
+ case "lazy":
52
+ found.push(def.getter());
53
+ break;
54
+ }
55
+ return found.filter((child) => child !== undefined);
56
+ }
57
+ function containsDate(schema, seen) {
58
+ if (seen.has(schema))
59
+ return false;
60
+ seen.add(schema);
61
+ if (schema._zod.def.type === "date")
62
+ return true;
63
+ return children(schema).some((child) => containsDate(child, seen));
64
+ }
65
+ const RFC_3339 = /^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})$/;
66
+ function parseDate(text) {
67
+ if (!RFC_3339.test(text))
68
+ return undefined;
69
+ const date = new Date(text.toUpperCase());
70
+ return Number.isNaN(date.getTime()) ? undefined : date;
71
+ }
72
+ function isPlainObject(value) {
73
+ if (typeof value !== "object" || value === null)
74
+ return false;
75
+ const prototype = Object.getPrototypeOf(value);
76
+ return prototype === Object.prototype || prototype === null;
77
+ }
78
+ // How to convert a value of `schema`, or undefined when no date lies below it.
79
+ // A date under a container the walk cannot enter would reach the procedure as
80
+ // the string it arrived as, so it is refused when the tool is built.
81
+ function datePlan(schema) {
82
+ const type = schema._zod.def.type;
83
+ switch (type) {
84
+ case "date":
85
+ return (value) => typeof value === "string" ? (parseDate(value) ?? value) : value;
86
+ case "object": {
87
+ const plans = [];
88
+ for (const [key, child] of Object.entries(schema.shape)) {
89
+ const plan = datePlan(child);
90
+ if (plan)
91
+ plans.push([key, plan]);
92
+ }
93
+ if (plans.length === 0)
94
+ return undefined;
95
+ return (value) => {
96
+ if (!isPlainObject(value))
97
+ return value;
98
+ const out = { ...value };
99
+ for (const [key, plan] of plans) {
100
+ if (key in out)
101
+ out[key] = plan(out[key]);
102
+ }
103
+ return out;
104
+ };
105
+ }
106
+ case "array": {
107
+ const plan = datePlan(schema.element);
108
+ if (!plan)
109
+ return undefined;
110
+ return (value) => (Array.isArray(value) ? value.map(plan) : value);
111
+ }
112
+ case "optional":
113
+ case "nullable":
114
+ case "default":
115
+ case "prefault":
116
+ case "nonoptional":
117
+ case "readonly":
118
+ case "catch":
119
+ case "pipe": {
120
+ const [inner] = children(schema);
121
+ return inner ? datePlan(inner) : undefined;
122
+ }
123
+ case "union": {
124
+ const plans = children(schema)
125
+ .map(datePlan)
126
+ .filter((plan) => plan !== undefined);
127
+ if (plans.length === 0)
128
+ return undefined;
129
+ return (value) => plans.reduce((acc, plan) => plan(acc), value);
130
+ }
131
+ default:
132
+ if (containsDate(schema, new Set())) {
133
+ throw new Error(`a date inside a ${type} cannot be converted from its string`);
134
+ }
135
+ return undefined;
136
+ }
137
+ }
138
+ function resolvePath(routes, path) {
139
+ let node = routes;
140
+ for (const segment of path.split(".")) {
141
+ if ((typeof node !== "object" && typeof node !== "function") ||
142
+ node === null ||
143
+ !Object.hasOwn(node, segment)) {
144
+ return undefined;
145
+ }
146
+ node = node[segment];
147
+ }
148
+ return node;
149
+ }
150
+ // Resolves every tool of `definition` against the consumer's routes, in the
151
+ // definition's order. A tool the endpoint could not serve throws here, naming
152
+ // the tool, so a worker never boots with it.
153
+ export function buildMcpTools(routes, definition) {
154
+ const tools = [];
155
+ for (const [name, description] of Object.entries(definition.tools)) {
156
+ const refuse = (reason) => new Error(`createWorker: MCP tool "${name}" ${reason}.`);
157
+ if (!TOOL_NAME.test(name)) {
158
+ throw refuse("is not a valid name: MCP names hold 1 to 128 letters, digits, `_`, `-` and `.`");
159
+ }
160
+ if (typeof description !== "string") {
161
+ throw refuse("has no description");
162
+ }
163
+ const procedure = resolvePath(routes, name);
164
+ if (!isProcedure(procedure))
165
+ throw refuse("names no procedure in the routes");
166
+ const def = procedure["~orpc"];
167
+ const schema = def.inputSchema;
168
+ if (schema !== undefined && !(schema instanceof z.ZodType)) {
169
+ throw refuse("has an input that is not a zod schema");
170
+ }
171
+ let inputSchema;
172
+ let convert;
173
+ try {
174
+ inputSchema = inputJsonSchema(schema);
175
+ convert = schema && datePlan(schema);
176
+ }
177
+ catch (error) {
178
+ const reason = error instanceof Error ? error.message : String(error);
179
+ throw refuse(`cannot be served: ${reason}`);
180
+ }
181
+ tools.push({
182
+ name,
183
+ description,
184
+ inputSchema,
185
+ readOnly: def.meta?.kind === "query",
186
+ procedure,
187
+ convert: convert ?? ((args) => args),
188
+ });
189
+ }
190
+ return tools;
191
+ }
192
+ function toResult(value, isError = false) {
193
+ const parsed = JSON.parse(JSON.stringify(value ?? null));
194
+ const structured = isPlainObject(parsed) ? parsed : { result: parsed };
195
+ return {
196
+ content: [{ type: "text", text: JSON.stringify(structured) }],
197
+ structuredContent: structured,
198
+ ...(isError ? { isError: true } : {}),
199
+ };
200
+ }
201
+ async function runTool(tool, args, context) {
202
+ try {
203
+ const output = await call(tool.procedure, tool.convert(args ?? {}), {
204
+ context,
205
+ });
206
+ return toResult(output);
207
+ }
208
+ catch (error) {
209
+ if (error instanceof ORPCError) {
210
+ try {
211
+ return toResult({ code: error.code, message: error.message, data: error.data }, true);
212
+ }
213
+ catch {
214
+ // Error data JSON cannot hold: masked like any other failure.
215
+ }
216
+ }
217
+ console.error(`[mcp] tool "${tool.name}" failed:`, error);
218
+ return toResult(INTERNAL, true);
219
+ }
220
+ }
221
+ export function createMcpEndpoint(options) {
222
+ const listed = options.tools.map((tool) => ({
223
+ name: tool.name,
224
+ description: tool.description,
225
+ inputSchema: tool.inputSchema,
226
+ ...(tool.readOnly ? { annotations: { readOnlyHint: true } } : {}),
227
+ }));
228
+ const byName = new Map(options.tools.map((tool) => [tool.name, tool]));
229
+ let sdk;
230
+ const loadSdk = () => {
231
+ sdk ??= import("@modelcontextprotocol/server").catch((error) => {
232
+ sdk = undefined;
233
+ throw error;
234
+ });
235
+ return sdk;
236
+ };
237
+ let handler;
238
+ const loadHandler = () => {
239
+ handler ??= build().catch((error) => {
240
+ handler = undefined;
241
+ throw error;
242
+ });
243
+ return handler;
244
+ };
245
+ // One handler per worker, one server per request: nothing is held between
246
+ // calls, so the 2025-era leg needs no session store.
247
+ async function build() {
248
+ const { createMcpHandler, Server, ProtocolError, ProtocolErrorCode } = await loadSdk();
249
+ const factory = (request) => {
250
+ const extra = request.authInfo?.extra;
251
+ if (!extra) {
252
+ throw new Error("mcp: the request reached the server unauthenticated");
253
+ }
254
+ const server = new Server({ name: options.name, version: SERVER_VERSION }, {
255
+ capabilities: { tools: {} },
256
+ instructions: `${options.instructions}\n\nThis connection acts in the organization with id ${extra.organizationId}`,
257
+ });
258
+ server.setRequestHandler("tools/list", () => ({ tools: listed }));
259
+ server.setRequestHandler("tools/call", ({ params }) => {
260
+ const tool = byName.get(params.name);
261
+ if (!tool) {
262
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Unknown tool: ${params.name}`);
263
+ }
264
+ return runTool(tool, params.arguments, extra.context);
265
+ });
266
+ return server;
267
+ };
268
+ return createMcpHandler(factory, {
269
+ legacy: "stateless",
270
+ // No need names `subscriptions/listen`, which a Worker would hold open.
271
+ maxSubscriptions: 0,
272
+ onerror: (error) => console.error("[mcp] SDK error:", error),
273
+ });
274
+ }
275
+ return {
276
+ async fetch(request, init) {
277
+ return (await loadHandler()).fetch(request, init);
278
+ },
279
+ async readBody(request) {
280
+ const { readRequestBody } = await loadSdk();
281
+ const read = await readRequestBody(request, MAX_BODY_BYTES);
282
+ return read.tooLarge ? null : read.text;
283
+ },
284
+ };
285
+ }
286
+ function jsonRpcError(code, message, status) {
287
+ return Response.json({ jsonrpc: "2.0", error: { code, message }, id: null }, { status });
288
+ }
289
+ export function createMcpRoute(endpoint) {
290
+ return async (c, ctx) => {
291
+ if (isForbiddenOrigin(c)) {
292
+ return c.json({ code: "FORBIDDEN" }, 403);
293
+ }
294
+ const oauth = ctx.oauth;
295
+ if (!oauth) {
296
+ throw new Error("mcp: the request context has no `oauth`; the MCP endpoint needs auth({ mcp: true }).");
297
+ }
298
+ const request = c.req.raw;
299
+ const verified = await oauth.verify(request);
300
+ if (verified instanceof Response) {
301
+ // A forged `kid` costs a key refetch, so a refused token draws the
302
+ // per-IP budget. An accepted token never does: hosted clients share
303
+ // egress, and `verify` limits per grant.
304
+ if (verified.status === 401 && (await ipLimited(c, ctx))) {
305
+ return c.json({ code: "TOO_MANY_REQUESTS" }, 429);
306
+ }
307
+ return verified;
308
+ }
309
+ const text = await endpoint.readBody(request);
310
+ if (text === null) {
311
+ return jsonRpcError(-32000, "Request body too large", 413);
312
+ }
313
+ let parsedBody;
314
+ try {
315
+ parsedBody = JSON.parse(text);
316
+ }
317
+ catch {
318
+ return jsonRpcError(-32700, "Parse error: the body is not valid JSON", 400);
319
+ }
320
+ // One POST is one call, so the grant's limit counts calls.
321
+ if (Array.isArray(parsedBody)) {
322
+ return jsonRpcError(-32600, "Invalid request: batches are not served", 400);
323
+ }
324
+ const reqHeaders = new Headers(request.headers);
325
+ reqHeaders.delete("cookie");
326
+ reqHeaders.delete("authorization");
327
+ const env = ctx.env;
328
+ const appUrl = env?.APP_URL;
329
+ const token = request.headers.get("authorization")?.split(/\s+/)[1] ?? "";
330
+ const authInfo = {
331
+ token,
332
+ clientId: verified.grant.clientId,
333
+ scopes: verified.grant.scopes,
334
+ expiresAt: Math.floor(verified.session.expiresAt.getTime() / 1000),
335
+ ...(typeof appUrl === "string"
336
+ ? { resource: new URL(`${appUrl.replace(/\/+$/, "")}${MCP_PATH}`) }
337
+ : {}),
338
+ extra: {
339
+ context: {
340
+ ...ctx,
341
+ tenancy: verified.tenancy,
342
+ _caller: { user: verified.user, session: verified.session },
343
+ reqHeaders,
344
+ // The request without its body or credentials, so a procedure that
345
+ // forwards headers to Better Auth finds no session.
346
+ httpRequest: new Request(request.url, {
347
+ method: request.method,
348
+ headers: reqHeaders,
349
+ }),
350
+ resHeaders: new Headers(),
351
+ },
352
+ organizationId: verified.grant.organizationId,
353
+ },
354
+ };
355
+ return endpoint.fetch(new Request(request.url, {
356
+ method: request.method,
357
+ headers: request.headers,
358
+ }), { parsedBody, authInfo });
359
+ };
360
+ }
361
+ //# sourceMappingURL=mcp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp.js","sourceRoot":"","sources":["../../src/worker/mcp.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAE5D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAE3D,8EAA8E;AAC9E,gFAAgF;AAEhF,MAAM,SAAS,GAAG,yBAAyB,CAAC;AAC5C,MAAM,cAAc,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AACvC,MAAM,cAAc,GAAG,OAAO,CAAC;AAC/B,MAAM,QAAQ,GAAG;IAChB,IAAI,EAAE,uBAAuB;IAC7B,OAAO,EAAE,uBAAuB;CAChC,CAAC;AAcF,gEAAgE;AAChE,SAAS,QAAQ,CAAC,MAAiB;IAClC,2FAA2F;IAC3F,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,GAAyC,CAAC;IAClE,MAAM,KAAK,GAAc,EAAE,CAAC;IAC5B,QAAQ,GAAG,CAAC,IAAI,EAAE,CAAC;QAClB,KAAK,QAAQ;YACZ,KAAK,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,KAAgC,CAAC,CAAC,CAAC;YACnE,MAAM;QACP,KAAK,OAAO;YACX,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;YACxB,MAAM;QACP,KAAK,UAAU,CAAC;QAChB,KAAK,UAAU,CAAC;QAChB,KAAK,SA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E;oBACR,GAAG,GAAG;oBACN,OAAO,EAAE,QAAQ,CAAC,OAAO;oBACzB,OAAO,EAAE,EAAE,IAAI,EAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,QAAQ,CAAC,OAAO,EAAE;oBAC3D,UAAU;oBACV,mEAAmE;oBACnE,oDAAoD;oBACpD,WAAW,EAAE,IAAI,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE;wBACrC,MAAM,EAAE,OAAO,CAAC,MAAM;wBACtB,OAAO,EAAE,UAAU;qBACnB,CAAC;oBACF,UAAU,EAAE,IAAI,OAAO,EAAE;iBACzB;gBACD,cAAc,EAAE,QAAQ,CAAC,KAAK,CAAC,cAAc;aACzB;SACrB,CAAC;QACF,OAAO,QAAQ,CAAC,KAAK,CACpB,IAAI,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE;YACxB,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,OAAO,EAAE,OAAO,CAAC,OAAO;SACxB,CAAC,EACF,EAAE,UAAU,EAAE,QAAQ,EAAE,CACxB,CAAC;IACH,CAAC,CAAC;AACH,CAAC"}
@@ -0,0 +1,10 @@
1
+ import type { MiddlewareHandler } from "hono";
2
+ export declare function pathnameOf(url: string): string;
3
+ export declare function formatRequestLog(line: {
4
+ method: string;
5
+ url: string;
6
+ status?: number;
7
+ ms?: number;
8
+ }): string;
9
+ export declare function requestLogger(print?: (line: string) => void): MiddlewareHandler;
10
+ //# sourceMappingURL=request-log.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-log.d.ts","sourceRoot":"","sources":["../../src/worker/request-log.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAQ9C,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAO9C;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE;IACtC,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,EAAE,CAAC,EAAE,MAAM,CAAC;CACZ,GAAG,MAAM,CAMT;AAGD,wBAAgB,aAAa,CAC5B,KAAK,GAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAkB,GACzC,iBAAiB,CAgBnB"}
@@ -0,0 +1,37 @@
1
+ // Request log without query strings: docs/architecture/plugins/api.md, "Logging".
2
+ function formatDuration(ms) {
3
+ return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`;
4
+ }
5
+ export function pathnameOf(url) {
6
+ const end = url.search(/[?#]/);
7
+ const head = end === -1 ? url : url.slice(0, end);
8
+ const scheme = head.indexOf("://");
9
+ if (scheme === -1)
10
+ return head;
11
+ const path = head.indexOf("/", scheme + 3);
12
+ return path === -1 ? "/" : head.slice(path);
13
+ }
14
+ export function formatRequestLog(line) {
15
+ const path = pathnameOf(line.url);
16
+ if (line.status === undefined || line.ms === undefined) {
17
+ return `<-- ${line.method} ${path}`;
18
+ }
19
+ return `--> ${line.method} ${path} ${line.status} ${formatDuration(line.ms)}`;
20
+ }
21
+ // `print` is the test's seam: the worker prints through the console.
22
+ export function requestLogger(print = console.log) {
23
+ return async (c, next) => {
24
+ const { method } = c.req;
25
+ const url = c.req.url;
26
+ print(formatRequestLog({ method, url }));
27
+ const start = Date.now();
28
+ await next();
29
+ print(formatRequestLog({
30
+ method,
31
+ url,
32
+ status: c.res.status,
33
+ ms: Date.now() - start,
34
+ }));
35
+ };
36
+ }
37
+ //# sourceMappingURL=request-log.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-log.js","sourceRoot":"","sources":["../../src/worker/request-log.ts"],"names":[],"mappings":"AAEA,kFAAkF;AAElF,SAAS,cAAc,CAAC,EAAU;IACjC,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CA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E,MAAM,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC;QACzB,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC;QACtB,KAAK,CAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;QACzC,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACzB,MAAM,IAAI,EAAE,CAAC;QACb,KAAK,CACJ,gBAAgB,CAAC;YAChB,MAAM;YACN,GAAG;YACH,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,MAAM;YACpB,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK;SACtB,CAAC,CACF,CAAC;IACH,CAAC,CAAC;AACH,CAAC"}
@@ -0,0 +1,42 @@
1
+ # Add a procedure
2
+
3
+ An endpoint the app calls is one procedure in a route file, and its client call. Work
4
+ the steps in order; each names the page it needs and ends with its check.
5
+
6
+ ## 1. Name what it reads and writes
7
+
8
+ Decide the entities the procedure reads or writes (the Drizzle tables by their export names), who
9
+ may call it (public, signed in, a member of a scope, a member who `can` act), and whether it pages.
10
+ Page: [procedures](./procedures.md), its options table.
11
+
12
+ **Check:** you can write its `procedure({ ... })` line.
13
+
14
+ ## 2. Write it
15
+
16
+ Add the procedure to a file in `src/worker/routes/`, a new named export or a key of an existing
17
+ one. A new file joins the router when `slotform generate` (or `slotform dev`'s watcher) rewrites the
18
+ barrel. Page: [procedures](./procedures.md).
19
+
20
+ ```ts
21
+ // src/worker/routes/projects.ts
22
+ export const projects = {
23
+ rename: procedure({ auth: true, scope: organization, can: ["update", "project"], writes: ["projects"] })
24
+ .input(z.object({ id: z.string(), name: z.string().min(1) }))
25
+ .mutation(async ({ input, context }) => {
26
+ // update the row through context.db
27
+ }),
28
+ };
29
+ ```
30
+
31
+ **Check:** `slotform generate`, then `pnpm check` passes.
32
+
33
+ ## 3. Call it from the app
34
+
35
+ Call it through the typed client, as a query or a mutation; the cache invalidates from its
36
+ `writes` on its own. Page: [client](./client.md).
37
+
38
+ ```tsx
39
+ const rename = useMutation(orpc.projects.rename.mutationOptions());
40
+ ```
41
+
42
+ **Check:** `pnpm check` passes, and the call answers under `pnpm dev`.
@@ -0,0 +1,86 @@
1
+ # Background work
2
+
3
+ Two files in `src/worker/` run work outside a request on the Cloudflare target. `queue.ts` answers
4
+ a queue batch and `scheduled.ts` answers a cron event. A file's existence is the switch:
5
+ `slotform generate` mounts each one on the worker, and no option turns either on. Both need a worker,
6
+ a routable file in `src/worker/routes` or a plugin runtime; `generate` refuses a file without one,
7
+ naming it. On node, background work is a service in `src/server/services`, whose `jobContext()`
8
+ gives it this same context (the `node` plugin's `services.md`, "Writing to the database").
9
+
10
+ ## A queue handler
11
+
12
+ ```ts
13
+ // src/worker/queue.ts
14
+ import { defineQueue } from "virtual:slotform-procedure";
15
+
16
+ type Job = { kind: "welcome"; email: string } | { kind: "digest"; org: string };
17
+
18
+ export default defineQueue<Job>(async (batch, { db, env }) => {
19
+ for (const message of batch.messages) {
20
+ try {
21
+ if (message.body.kind === "welcome") await sendWelcome(env, message.body.email);
22
+ else await sendDigest(db, message.body.org);
23
+ message.ack();
24
+ } catch {
25
+ message.retry({ delaySeconds: 30 });
26
+ }
27
+ }
28
+ });
29
+ ```
30
+
31
+ `batch.messages` holds each message's `id`, `body`, `attempts` and `timestamp`, with `ack()` and
32
+ `retry({ delaySeconds })` per message and `ackAll()` and `retryAll()` for the batch. Ack each
33
+ message as it succeeds: a handler that throws sends every message it has not acked back to the
34
+ queue, and the ones it acked stay done. Delivery is at least once, so write a job that can run
35
+ twice without harm. One queue carries every kind of job, so put the kind in the body and branch on
36
+ it, as above.
37
+
38
+ ## A cron handler
39
+
40
+ ```ts
41
+ // src/worker/scheduled.ts
42
+ import { defineScheduled } from "virtual:slotform-procedure";
43
+
44
+ export default defineScheduled(async (event, { db }) => {
45
+ switch (event.cron) {
46
+ case "*/10 * * * *":
47
+ await sweepStuckWork(db);
48
+ break;
49
+ case "0 7 * * *":
50
+ await sendDailyDigest(db);
51
+ break;
52
+ }
53
+ });
54
+ ```
55
+
56
+ `event.cron` is the schedule that fired, exactly as written in the root `wrangler.toml`
57
+ `[triggers]`, and `event.scheduledTime` is when it was due, in milliseconds. One handler answers
58
+ every schedule, so dispatch on `cron`. A throw is logged as a failed invocation and nothing
59
+ retries it: the next tick is the retry.
60
+
61
+ ## The context
62
+
63
+ The second argument is `JobContext`, the context a procedure gets without its request. It holds
64
+ `env`, `executionCtx` (`waitUntil`), `_devMode` and whatever the plugins provide: `db`, the
65
+ `auth` runtime, `tenancy`. It has no `httpRequest`, `reqHeaders` or `resHeaders`, and no user or
66
+ session, because nothing called the job as someone. Check what the job may do in the job, not in
67
+ a scope: a job reads and writes the whole database. No plugin `fetch` and no middleware run for
68
+ it, and the env checks run first, so a worker missing a var fails the batch the way it fails a
69
+ request. A node service gets the same context from `jobContext()`, built afresh on each call.
70
+
71
+ ## Enqueueing and bindings
72
+
73
+ A procedure puts a job on the queue through the `QUEUE` binding on `context.env`; the queue, its
74
+ consumer settings and the cron `[triggers]` are Cloudflare's, set in the `cloudflare` plugin (its
75
+ `wrangler` page for the bindings and local runs, its `deploy` page for creating the queue).
76
+ The shape of a message is yours: type the body with `defineQueue<Body>` and share the type with
77
+ the code that sends it.
78
+
79
+ ## Rules
80
+
81
+ - Make a job idempotent. A retry, a redelivery and a crash after the work but before the ack all
82
+ run it again.
83
+ - Ack per message when the batch mixes work that can fail separately; `ackAll()` only when the
84
+ batch stands or falls as one.
85
+ - Keep a request's work out of the queue when the member waits on its result; the queue is for
86
+ what a third party's slowness must not hold up.
@@ -0,0 +1,93 @@
1
+ # Calling the API
2
+
3
+ `createClient` from `@slotform/api/client` builds the typed client, on the web and the
4
+ phone alike, from the generated worker's `AppRouter`, imported type-only, so the app holds none of
5
+ the worker's source.
6
+
7
+ ```ts
8
+ // src/app/lib/api.ts
9
+ import { createClient } from "@slotform/api/client";
10
+ import { createApiQueryUtils } from "@slotform/query/tanstack-query";
11
+ import type { AppRouter } from "../../../.slotform/worker";
12
+
13
+ export const api = createClient<AppRouter>(); // url "/rpc", credentials "include"
14
+ export const orpc = createApiQueryUtils(api);
15
+ ```
16
+
17
+ A query made through `orpc.*.queryOptions` travels as `GET` (its input in the URL) and a mutation as `POST`. Build the utils with `createApiQueryUtils` (the query plugin, `query()`): oRPC's own `createTanstackQueryUtils` sends queries as `POST`.
18
+
19
+ On the phone, pass an absolute `url` (`process.env.EXPO_PUBLIC_API_URL`). `headers` takes an
20
+ object, or a function returning one or a promise of one, read on every request (a key the device's
21
+ secure store answers later). `url` takes a function too, for a server chosen while the app runs (a
22
+ phone told its server's address at sign-in); clear the query cache when it changes, since the data
23
+ held is the old server's. A machine with no browser sends its device key there:
24
+ `headers: { authorization: "Bearer " + key }` (see the auth plugin's devices page).
25
+
26
+ ## Queries
27
+
28
+ `@slotform/query/tanstack-query` pairs the client with TanStack Query 5 and re-exports its
29
+ hooks (`useQuery`, `useMutation`, `useInfiniteQuery`, `useSuspenseQuery`, `useQueryClient`). Drawing a query on a screen is
30
+ `node_modules/@slotform/query/guide/reads.md`.
31
+
32
+ ```tsx
33
+ const { data } = useQuery(orpc.projects.list.queryOptions({ input: { organizationId } }));
34
+ const create = useMutation(orpc.projects.create.mutationOptions());
35
+ ```
36
+
37
+ ## Scope
38
+
39
+ A procedure with a `scope` takes the scope's id in its input (`organizationId`, `projectId`), and
40
+ the route's boundary supplies it: `ScopeBoundary` from `@slotform/ui-core/react/scope` registers
41
+ the ids the layout resolved from the URL slug, and every call under it whose procedure names that
42
+ key gets the id (an explicit id wins). The query key carries the id, so two organizations'
43
+ `projects.list` never share a cache entry, and a screen under the boundary writes no id.
44
+
45
+ ```tsx
46
+ <ScopeBoundary ids={{ organizationId: organization.id }}>
47
+ <Outlet />
48
+ </ScopeBoundary>
49
+
50
+ useQuery(orpc.projects.list.queryOptions());
51
+ ```
52
+
53
+ A boundary under another extends the outer ids (a project's `{ projectId }` joins the
54
+ organization's `{ organizationId }`). A call that names another scope passes its id.
55
+
56
+ A route `loader` runs before the boundary renders, so it names the ids it resolved, in the input or
57
+ once with `scoped(orpc, { organizationId })` from `@slotform/query/tanstack-query`. A call
58
+ of a scoped procedure with no registered scope and no id throws before any request, naming the
59
+ procedure and the key; a procedure added since the last `slotform generate` is not scoped until
60
+ generate runs.
61
+
62
+ ## Not found
63
+
64
+ A procedure that throws `ApiError("NOT_FOUND")` reaches the screen as a failed query.
65
+ `isNotFound(error)` from `@slotform/api/client` tells that error from any other, so the
66
+ screen draws its not-found state for it and its error state for the rest. A read's not found
67
+ travels as a 200 carrying `x-slotform-not-found`, so a client of `/rpc` that is not Slotform's sees the
68
+ 200.
69
+
70
+ ```tsx
71
+ const project = useQuery(orpc.projects.get.queryOptions({ input: { projectId } }));
72
+ if (project.isError) return isNotFound(project.error) ? <ProjectNotFound /> : <ProjectError />;
73
+ ```
74
+
75
+ ## Cache invalidation
76
+
77
+ Write no invalidation code. A successful mutation invalidates every cached query whose `reads`
78
+ meet its `writes`, so the procedures declare both and the screens declare nothing.
79
+
80
+ - A query that never declared `reads` never invalidates on its own.
81
+ - A mutation that owns every cache it changes opts out with `meta: { skipAutoInvalidation: true }`.
82
+ - A query outside the API declares its reads on its options, `meta: { reads: ["member"] }`, and
83
+ then refetches on those writes like an API query.
84
+ - A write the API never answered (a socket frame, a webhook) calls
85
+ `invalidateForWrites(queryClient, ["member"])` from `@slotform/api/query-invalidation`.
86
+ - The names in `meta.reads` and `invalidateForWrites` are the app's `Entity` (the union in
87
+ `.slotform/procedure.ts`, also exported from `.slotform/worker`), so a typo fails `tsc` on web and
88
+ phone. Slotform registers TanStack Query's `queryMeta`; the app adds its own meta keys to a query
89
+ directly and never registers `queryMeta` itself.
90
+ - A custom `mutationCache` passed to `createQueryClient` turns auto-invalidation off: the app
91
+ owns invalidation then.
92
+
93
+ **Check:** `pnpm check` passes, and the screen shows the data under `pnpm dev`.