@slotform/api 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +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/src/procedure.ts
ADDED
|
@@ -0,0 +1,935 @@
|
|
|
1
|
+
import { ORPCError, os } from "@orpc/server";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { DEFAULT_LIMIT, LIMIT_CEILING, MAX_LIMIT } from "./lib/limits.ts";
|
|
4
|
+
import type { Procedure } from "./types.ts";
|
|
5
|
+
import {
|
|
6
|
+
ENTITY_NAME_RE,
|
|
7
|
+
SLOTFORM_READS_HEADER,
|
|
8
|
+
SLOTFORM_WRITES_HEADER,
|
|
9
|
+
} from "./wire.ts";
|
|
10
|
+
|
|
11
|
+
// Re-exported wire constants: docs/architecture/plugins/api.md, "Wire contract".
|
|
12
|
+
export {
|
|
13
|
+
ORG_RULES_PATH,
|
|
14
|
+
SCOPE_ROUTES_PATH,
|
|
15
|
+
SLOTFORM_READS_HEADER,
|
|
16
|
+
SLOTFORM_WRITES_HEADER,
|
|
17
|
+
} from "./wire.ts";
|
|
18
|
+
|
|
19
|
+
// A scope's name in plain words: camelCase and snake_case split at their words
|
|
20
|
+
// and lower-cased (`lineItem` and `line_item` read "line item").
|
|
21
|
+
function scopeWords(name: string): string {
|
|
22
|
+
return name
|
|
23
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
24
|
+
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
|
|
25
|
+
.split(/[\s_-]+/)
|
|
26
|
+
.filter(Boolean)
|
|
27
|
+
.join(" ")
|
|
28
|
+
.toLowerCase();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The refusal a scoped call answers when the scope's row is missing or not visible: `NOT_FOUND`, "No such <scope>" with the scope's name in plain words (`lineItem` reads "No such line item"). Scoped procedures and the `auth` plugin's `bySlug` throw this one. */
|
|
32
|
+
export function noSuch(scope: {
|
|
33
|
+
name: string;
|
|
34
|
+
}): ORPCError<"NOT_FOUND", unknown> {
|
|
35
|
+
return new ORPCError("NOT_FOUND", {
|
|
36
|
+
message: `No such ${scopeWords(scope.name)}`,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
type Promisable<T> = T | Promise<T>;
|
|
41
|
+
type DefaultStatements = Record<string, readonly string[]>;
|
|
42
|
+
|
|
43
|
+
interface HandlerOptions<TContext, TInput> {
|
|
44
|
+
input: TInput;
|
|
45
|
+
context: TContext;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type Middleware<
|
|
49
|
+
TContext extends Record<string, unknown>,
|
|
50
|
+
TExtra extends Record<string, unknown>,
|
|
51
|
+
> = (opts: { context: TContext; input: unknown }) => Promisable<TExtra>;
|
|
52
|
+
|
|
53
|
+
type Rbac<TStatements extends DefaultStatements> = {
|
|
54
|
+
[R in keyof TStatements & string]: readonly [
|
|
55
|
+
R,
|
|
56
|
+
readonly [TStatements[R][number], ...TStatements[R][number][]],
|
|
57
|
+
];
|
|
58
|
+
}[keyof TStatements & string];
|
|
59
|
+
|
|
60
|
+
// `can` is a tuple of exactly two strings, so no conditions element exists: docs/architecture/plugins/api.md, "Procedure factory".
|
|
61
|
+
type Can<TStatements extends DefaultStatements> = {
|
|
62
|
+
[R in keyof TStatements & string]: readonly [TStatements[R][number], R];
|
|
63
|
+
}[keyof TStatements & string];
|
|
64
|
+
|
|
65
|
+
interface BaseOptions<TEntity extends string = string> {
|
|
66
|
+
rateLimit?: RateLimitKind | readonly RateLimitKind[];
|
|
67
|
+
// `paginated`: docs/architecture/plugins/api.md, "Procedure factory".
|
|
68
|
+
paginated?: boolean | "window";
|
|
69
|
+
// The most rows one call may ask for (`limit`); 100 unless named.
|
|
70
|
+
maxLimit?: number;
|
|
71
|
+
// The columns the caller may sort the page by: the input gains
|
|
72
|
+
// `sort?: { column, direction }`, typed to these. A Table over the read
|
|
73
|
+
// sends its header sort through it.
|
|
74
|
+
sort?: readonly [string, ...string[]];
|
|
75
|
+
// Entity headers: docs/architecture/plugins/api.md, "Entity headers".
|
|
76
|
+
reads?: readonly TEntity[];
|
|
77
|
+
writes?: readonly TEntity[];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// A tenancy tier, structurally: docs/architecture/plugins/api.md, "Scope".
|
|
81
|
+
export interface ScopeLike<TName extends string = string, TContext = unknown> {
|
|
82
|
+
readonly name: TName;
|
|
83
|
+
readonly __context?: TContext;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
interface PublicOptions<TEntity extends string = string>
|
|
87
|
+
extends BaseOptions<TEntity> {
|
|
88
|
+
auth?: false;
|
|
89
|
+
scope?: never;
|
|
90
|
+
rbac?: never;
|
|
91
|
+
can?: never;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
interface AuthOnlyOptions<TEntity extends string = string>
|
|
95
|
+
extends BaseOptions<TEntity> {
|
|
96
|
+
auth: true;
|
|
97
|
+
scope?: never;
|
|
98
|
+
rbac?: never;
|
|
99
|
+
can?: never;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
interface ScopedOptions<
|
|
103
|
+
TStatements extends DefaultStatements,
|
|
104
|
+
TEntity extends string = string,
|
|
105
|
+
> extends BaseOptions<TEntity> {
|
|
106
|
+
auth: true;
|
|
107
|
+
// The scope the procedure acts inside: docs/architecture/plugins/auth.md, "Scopes".
|
|
108
|
+
scope: ScopeLike;
|
|
109
|
+
rbac?: Rbac<TStatements>;
|
|
110
|
+
// `can`, the preferred spelling over `rbac`: docs/architecture/plugins/api.md, "Procedure factory".
|
|
111
|
+
can?: Can<TStatements>;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export type ProcedureConfig<
|
|
115
|
+
TStatements extends DefaultStatements = DefaultStatements,
|
|
116
|
+
TEntity extends string = string,
|
|
117
|
+
> =
|
|
118
|
+
| PublicOptions<TEntity>
|
|
119
|
+
| AuthOnlyOptions<TEntity>
|
|
120
|
+
| ScopedOptions<TStatements, TEntity>;
|
|
121
|
+
|
|
122
|
+
export interface RateLimitBinding {
|
|
123
|
+
limit(options: { key: string }): Promise<{ success: boolean }>;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export type RateLimitKind = "ip" | "email";
|
|
127
|
+
|
|
128
|
+
type InferAuthContext<TContext> = TContext extends {
|
|
129
|
+
auth: {
|
|
130
|
+
$Infer: {
|
|
131
|
+
Session: {
|
|
132
|
+
user: infer U extends Record<string, unknown>;
|
|
133
|
+
session: infer S extends Record<string, unknown>;
|
|
134
|
+
};
|
|
135
|
+
};
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
? { user: U; session: S }
|
|
139
|
+
: {
|
|
140
|
+
user: { id: string; [key: string]: unknown };
|
|
141
|
+
session: { id: string; [key: string]: unknown };
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
type ResolvedContext<O, TBase extends Record<string, unknown>> = TBase &
|
|
145
|
+
(O extends { auth: true } ? InferAuthContext<TBase> : unknown) &
|
|
146
|
+
(O extends { scope: ScopeLike<string, infer C> } ? C : unknown);
|
|
147
|
+
|
|
148
|
+
// The two types one schema gives a procedure: what the caller sends and what
|
|
149
|
+
// the handler holds once oRPC has parsed it. An output schema swaps them: the
|
|
150
|
+
// handler returns what the schema accepts and the caller receives what it
|
|
151
|
+
// produces.
|
|
152
|
+
// `scope` is the input key the config adds for the procedure's scope
|
|
153
|
+
// (`organizationId`), `never` for a procedure with none; it rides to
|
|
154
|
+
// `Procedure`'s third parameter, where the client type reads it.
|
|
155
|
+
interface Sides<TClient, THandler, TScope extends string = never> {
|
|
156
|
+
client: TClient;
|
|
157
|
+
handler: THandler;
|
|
158
|
+
scope: TScope;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
type AnySides = Sides<unknown, unknown, string>;
|
|
162
|
+
|
|
163
|
+
type ScopeKey<O> = O extends { scope: ScopeLike<infer N> } ? `${N}Id` : never;
|
|
164
|
+
|
|
165
|
+
type ScopeInput<O> = { [K in ScopeKey<O>]: string };
|
|
166
|
+
|
|
167
|
+
type SortSide<O> = O extends { sort: readonly (infer C extends string)[] }
|
|
168
|
+
? { sort?: { column: C; direction: "asc" | "desc" } }
|
|
169
|
+
: unknown;
|
|
170
|
+
|
|
171
|
+
// `pageShape` defaults `limit` (and a window's `offset`), so only the caller
|
|
172
|
+
// may omit them.
|
|
173
|
+
type PageInput<O> = O extends { paginated: "window" }
|
|
174
|
+
? Sides<
|
|
175
|
+
{ offset?: number; limit?: number } & SortSide<O>,
|
|
176
|
+
{ offset: number; limit: number } & SortSide<O>
|
|
177
|
+
>
|
|
178
|
+
: O extends { paginated: true }
|
|
179
|
+
? Sides<
|
|
180
|
+
{ cursor?: string; limit?: number } & SortSide<O>,
|
|
181
|
+
{ cursor?: string; limit: number } & SortSide<O>
|
|
182
|
+
>
|
|
183
|
+
: Sides<unknown, unknown>;
|
|
184
|
+
|
|
185
|
+
type IsPaginated = { paginated: true } | { paginated: "window" };
|
|
186
|
+
|
|
187
|
+
// Both sides are `undefined` when the config adds nothing, so a procedure
|
|
188
|
+
// with no input is called with no argument (`ProcedureCall`).
|
|
189
|
+
type InputAdditions<O> = O extends { scope: ScopeLike } | IsPaginated
|
|
190
|
+
? Sides<
|
|
191
|
+
ScopeInput<O> & PageInput<O>["client"],
|
|
192
|
+
ScopeInput<O> & PageInput<O>["handler"],
|
|
193
|
+
ScopeKey<O>
|
|
194
|
+
>
|
|
195
|
+
: Sides<undefined, undefined>;
|
|
196
|
+
|
|
197
|
+
// zod types `z.object({})` as `Record<string, never>`, whose index signature
|
|
198
|
+
// would refuse every key the config adds, so an empty schema adds nothing.
|
|
199
|
+
type IsEmptyObject<T> = [T] extends [Record<string, never>]
|
|
200
|
+
? [Record<string, never>] extends [T]
|
|
201
|
+
? true
|
|
202
|
+
: false
|
|
203
|
+
: false;
|
|
204
|
+
|
|
205
|
+
type MergeSide<TBaseSide, TSchemaSide> = TBaseSide extends undefined
|
|
206
|
+
? TSchemaSide
|
|
207
|
+
: IsEmptyObject<TSchemaSide> extends true
|
|
208
|
+
? TBaseSide
|
|
209
|
+
: TSchemaSide & TBaseSide;
|
|
210
|
+
|
|
211
|
+
type MergedInput<
|
|
212
|
+
TBaseInput extends AnySides,
|
|
213
|
+
TSchema extends z.ZodType,
|
|
214
|
+
> = Sides<
|
|
215
|
+
MergeSide<TBaseInput["client"], z.input<TSchema>>,
|
|
216
|
+
MergeSide<TBaseInput["handler"], z.output<TSchema>>,
|
|
217
|
+
TBaseInput["scope"]
|
|
218
|
+
>;
|
|
219
|
+
|
|
220
|
+
type OutputSides<TSchema extends z.ZodType> = Sides<
|
|
221
|
+
z.output<TSchema>,
|
|
222
|
+
z.input<TSchema>
|
|
223
|
+
>;
|
|
224
|
+
|
|
225
|
+
type TerminalName = "handler" | "query" | "mutation";
|
|
226
|
+
|
|
227
|
+
// The terminals of a procedure whose handler's return types its output.
|
|
228
|
+
type Terminals<TContext, TInput extends AnySides> = Record<
|
|
229
|
+
TerminalName,
|
|
230
|
+
<TOutput>(
|
|
231
|
+
fn: (
|
|
232
|
+
opts: HandlerOptions<TContext, TInput["handler"]>,
|
|
233
|
+
) => Promisable<TOutput>,
|
|
234
|
+
) => Procedure<TInput["client"], TOutput, TInput["scope"]>
|
|
235
|
+
>;
|
|
236
|
+
|
|
237
|
+
// The terminals of a procedure whose output schema types its output.
|
|
238
|
+
type OutputTerminals<
|
|
239
|
+
TContext,
|
|
240
|
+
TInput extends AnySides,
|
|
241
|
+
TOutput extends AnySides,
|
|
242
|
+
> = Record<
|
|
243
|
+
TerminalName,
|
|
244
|
+
(
|
|
245
|
+
fn: (
|
|
246
|
+
opts: HandlerOptions<TContext, TInput["handler"]>,
|
|
247
|
+
) => Promisable<TOutput["handler"]>,
|
|
248
|
+
) => Procedure<TInput["client"], TOutput["client"], TInput["scope"]>
|
|
249
|
+
>;
|
|
250
|
+
|
|
251
|
+
interface ProcedureWithInput<TContext, TInput extends AnySides>
|
|
252
|
+
extends Terminals<TContext, TInput> {
|
|
253
|
+
output<TSchema extends z.ZodType>(
|
|
254
|
+
schema: TSchema,
|
|
255
|
+
): OutputTerminals<TContext, TInput, OutputSides<TSchema>>;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
interface ProcedureWithOutput<
|
|
259
|
+
TContext,
|
|
260
|
+
TBaseInput extends AnySides,
|
|
261
|
+
TOutput extends AnySides,
|
|
262
|
+
> extends OutputTerminals<TContext, TBaseInput, TOutput> {
|
|
263
|
+
input<TSchema extends z.ZodType>(
|
|
264
|
+
schema: TSchema,
|
|
265
|
+
): OutputTerminals<TContext, MergedInput<TBaseInput, TSchema>, TOutput>;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export interface ProcedureBuilder<
|
|
269
|
+
TContext extends Record<string, unknown>,
|
|
270
|
+
TBaseInput extends AnySides,
|
|
271
|
+
> extends Terminals<TContext, TBaseInput> {
|
|
272
|
+
use<TExtra extends Record<string, unknown>>(
|
|
273
|
+
middleware: Middleware<TContext, TExtra>,
|
|
274
|
+
): ProcedureBuilder<TContext & TExtra, TBaseInput>;
|
|
275
|
+
|
|
276
|
+
input<TSchema extends z.ZodType>(
|
|
277
|
+
schema: TSchema,
|
|
278
|
+
): ProcedureWithInput<TContext, MergedInput<TBaseInput, TSchema>>;
|
|
279
|
+
|
|
280
|
+
output<TSchema extends z.ZodType>(
|
|
281
|
+
schema: TSchema,
|
|
282
|
+
): ProcedureWithOutput<TContext, TBaseInput, OutputSides<TSchema>>;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export type ProcedureFactory<
|
|
286
|
+
TBase extends Record<string, unknown>,
|
|
287
|
+
TStatements extends DefaultStatements,
|
|
288
|
+
TEntity extends string = string,
|
|
289
|
+
> = <
|
|
290
|
+
const O extends ProcedureConfig<
|
|
291
|
+
TStatements,
|
|
292
|
+
TEntity
|
|
293
|
+
> = PublicOptions<TEntity>,
|
|
294
|
+
>(
|
|
295
|
+
config?: O,
|
|
296
|
+
) => ProcedureBuilder<ResolvedContext<O, TBase>, InputAdditions<O>>;
|
|
297
|
+
|
|
298
|
+
// A credential refusal, read structurally: docs/architecture/plugins/api.md, "Auth refusals".
|
|
299
|
+
function credentialRefusal(error: unknown): ORPCError<string, unknown> | null {
|
|
300
|
+
if (typeof error !== "object" || error === null) return null;
|
|
301
|
+
const { statusCode, body } = error as {
|
|
302
|
+
statusCode?: unknown;
|
|
303
|
+
body?: { message?: unknown } | null;
|
|
304
|
+
};
|
|
305
|
+
const message =
|
|
306
|
+
typeof body?.message === "string"
|
|
307
|
+
? body.message
|
|
308
|
+
: "Authentication required";
|
|
309
|
+
if (statusCode === 401 || statusCode === 403) {
|
|
310
|
+
return new ORPCError("UNAUTHORIZED", { message });
|
|
311
|
+
}
|
|
312
|
+
if (statusCode === 429) {
|
|
313
|
+
return new ORPCError("TOO_MANY_REQUESTS", { message });
|
|
314
|
+
}
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function createAuthMiddleware() {
|
|
319
|
+
return async ({
|
|
320
|
+
context,
|
|
321
|
+
next,
|
|
322
|
+
}: {
|
|
323
|
+
context: {
|
|
324
|
+
reqHeaders: Headers;
|
|
325
|
+
// Set only by the MCP endpoint, which has verified its bearer token:
|
|
326
|
+
// the caller it names stands in for the cookie session.
|
|
327
|
+
_caller?: { user: unknown; session: unknown };
|
|
328
|
+
auth: {
|
|
329
|
+
api: {
|
|
330
|
+
getSession: (opts: {
|
|
331
|
+
headers: Headers;
|
|
332
|
+
}) => Promise<{ user: unknown; session: unknown } | null>;
|
|
333
|
+
};
|
|
334
|
+
};
|
|
335
|
+
};
|
|
336
|
+
next: (opts: { context: unknown }) => Promise<unknown>;
|
|
337
|
+
}) => {
|
|
338
|
+
if (context._caller) {
|
|
339
|
+
return next({
|
|
340
|
+
context: {
|
|
341
|
+
user: context._caller.user,
|
|
342
|
+
session: context._caller.session,
|
|
343
|
+
},
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
// A session-store outage surfaces as a 500, never UNAUTHORIZED: docs/architecture/plugins/api.md, "Auth refusals".
|
|
347
|
+
let sessionData: { user: unknown; session: unknown } | null;
|
|
348
|
+
try {
|
|
349
|
+
sessionData = await context.auth.api.getSession({
|
|
350
|
+
headers: context.reqHeaders,
|
|
351
|
+
});
|
|
352
|
+
} catch (error) {
|
|
353
|
+
// A credential the auth layer refuses (a revoked, expired or
|
|
354
|
+
// rate-limited device key) answers as the refusal it is, with its
|
|
355
|
+
// status, not as a failure of the store.
|
|
356
|
+
throw credentialRefusal(error) ?? error;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
if (!sessionData?.session || !sessionData?.user) {
|
|
360
|
+
throw new ORPCError("UNAUTHORIZED", {
|
|
361
|
+
message: "Authentication required",
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
return next({
|
|
366
|
+
context: {
|
|
367
|
+
user: sessionData.user,
|
|
368
|
+
session: sessionData.session,
|
|
369
|
+
},
|
|
370
|
+
});
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// The request context's tenancy capability, put there by the `auth` plugin's
|
|
375
|
+
// runtime when organizations are on. Structural, so api never imports auth.
|
|
376
|
+
type TenancyContext = {
|
|
377
|
+
tenancy: {
|
|
378
|
+
resolve(
|
|
379
|
+
scope: ScopeLike,
|
|
380
|
+
id: string,
|
|
381
|
+
userId: string,
|
|
382
|
+
): Promise<Record<string, unknown> | null>;
|
|
383
|
+
can(role: string, permissions: Record<string, readonly string[]>): boolean;
|
|
384
|
+
};
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
function scopeInputKey(scope: ScopeLike): string {
|
|
388
|
+
return `${scope.name}Id`;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// Scope resolution answers NOT_FOUND for an absent row and a non-member alike: docs/architecture/plugins/auth.md, "Scopes".
|
|
392
|
+
function createScopeMiddleware(scope: ScopeLike) {
|
|
393
|
+
const key = scopeInputKey(scope);
|
|
394
|
+
return async (
|
|
395
|
+
{
|
|
396
|
+
context,
|
|
397
|
+
next,
|
|
398
|
+
}: {
|
|
399
|
+
context: { user: { id: string } } & TenancyContext;
|
|
400
|
+
next: (opts: { context: unknown }) => Promise<unknown>;
|
|
401
|
+
},
|
|
402
|
+
input: unknown,
|
|
403
|
+
) => {
|
|
404
|
+
const id = (input as Record<string, unknown>)[key];
|
|
405
|
+
const resolved =
|
|
406
|
+
typeof id === "string"
|
|
407
|
+
? await context.tenancy.resolve(scope, id, context.user.id)
|
|
408
|
+
: null;
|
|
409
|
+
if (!resolved) {
|
|
410
|
+
throw noSuch(scope);
|
|
411
|
+
}
|
|
412
|
+
return next({ context: resolved });
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// The caller's role in the scope's organization, checked locally against
|
|
417
|
+
// the roles the auth config declares.
|
|
418
|
+
function createPermissionMiddleware(resource: string, actions: string[]) {
|
|
419
|
+
return async ({
|
|
420
|
+
context,
|
|
421
|
+
next,
|
|
422
|
+
}: {
|
|
423
|
+
context: { member: { role: string } } & TenancyContext;
|
|
424
|
+
next: (opts: { context: unknown }) => Promise<unknown>;
|
|
425
|
+
}) => {
|
|
426
|
+
if (!context.tenancy.can(context.member.role, { [resource]: actions })) {
|
|
427
|
+
throw new ORPCError("FORBIDDEN", {
|
|
428
|
+
message: "Insufficient permissions",
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
return next({ context: {} });
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
type KeyExtractor = (
|
|
436
|
+
context: { reqHeaders: Headers },
|
|
437
|
+
input: unknown,
|
|
438
|
+
) => string;
|
|
439
|
+
|
|
440
|
+
// `X-Forwarded-For` may be a comma-separated list (client, proxy1, proxy2…).
|
|
441
|
+
// The originating client is the first entry; trim per RFC 7239.
|
|
442
|
+
export function extractIp(headers: Headers): string {
|
|
443
|
+
const cfIp = headers.get("CF-Connecting-IP");
|
|
444
|
+
if (cfIp) return cfIp;
|
|
445
|
+
const fwd = headers.get("X-Forwarded-For");
|
|
446
|
+
if (fwd) {
|
|
447
|
+
const first = fwd.split(",")[0]?.trim();
|
|
448
|
+
if (first) return first;
|
|
449
|
+
}
|
|
450
|
+
return "unknown";
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function extractEmail(input: unknown): string {
|
|
454
|
+
if (
|
|
455
|
+
input === null ||
|
|
456
|
+
typeof input !== "object" ||
|
|
457
|
+
!("email" in input) ||
|
|
458
|
+
typeof (input as { email: unknown }).email !== "string" ||
|
|
459
|
+
(input as { email: string }).email.length === 0
|
|
460
|
+
) {
|
|
461
|
+
throw new ORPCError("BAD_REQUEST", {
|
|
462
|
+
message:
|
|
463
|
+
'rateLimit: "email" requires the procedure input to include a non-empty `email: string` field',
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
return (input as { email: string }).email.toLowerCase();
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const KEY_EXTRACTORS: Record<RateLimitKind, KeyExtractor> = {
|
|
470
|
+
ip: (context) => extractIp(context.reqHeaders),
|
|
471
|
+
email: (_, input) => extractEmail(input),
|
|
472
|
+
};
|
|
473
|
+
|
|
474
|
+
function createRateLimitMiddleware(kind: RateLimitKind) {
|
|
475
|
+
return async (
|
|
476
|
+
{
|
|
477
|
+
context,
|
|
478
|
+
next,
|
|
479
|
+
}: {
|
|
480
|
+
context: {
|
|
481
|
+
reqHeaders: Headers;
|
|
482
|
+
_rateLimiter?: { ip?: RateLimitBinding; email?: RateLimitBinding };
|
|
483
|
+
_devMode?: boolean;
|
|
484
|
+
};
|
|
485
|
+
next: (opts: { context: unknown }) => Promise<unknown>;
|
|
486
|
+
},
|
|
487
|
+
input: unknown,
|
|
488
|
+
) => {
|
|
489
|
+
const limiter = context._rateLimiter?.[kind];
|
|
490
|
+
const isDev = context._devMode ?? false;
|
|
491
|
+
|
|
492
|
+
if (isDev) return next({ context: {} });
|
|
493
|
+
|
|
494
|
+
if (!limiter) {
|
|
495
|
+
console.error(
|
|
496
|
+
`[api] Procedure requires rate limiting ("${kind}") but no ${kind} rate limiter is bound to the worker context. ` +
|
|
497
|
+
`Ensure the auth plugin is configured with a rateLimiter binding, or inject { _rateLimiter: { ${kind}: binding } } via .use() when constructing the worker.`,
|
|
498
|
+
);
|
|
499
|
+
throw new ORPCError("INTERNAL_SERVER_ERROR", {
|
|
500
|
+
message: "Server configuration error",
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const key = KEY_EXTRACTORS[kind](context, input);
|
|
505
|
+
const result = await limiter.limit({ key });
|
|
506
|
+
if (!result.success) {
|
|
507
|
+
throw new ORPCError("TOO_MANY_REQUESTS", {
|
|
508
|
+
message: "Rate limit exceeded. Please try again later.",
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
return next({ context: {} });
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// oRPC's RPCHandler flattens any non-ORPCError throw into an opaque
|
|
517
|
+
// INTERNAL_SERVER_ERROR before it reaches Hono's onError, so a real bug (a
|
|
518
|
+
// D1 error, a typo) leaves zero server-side trace. ORPCError throws are
|
|
519
|
+
// intentional control flow (auth/rate-limit/validation failures) and must
|
|
520
|
+
// stay silent.
|
|
521
|
+
function createErrorLoggingMiddleware(): OrpcMiddlewareFn {
|
|
522
|
+
return async ({ next }, _input) => {
|
|
523
|
+
try {
|
|
524
|
+
return await next({ context: {} });
|
|
525
|
+
} catch (error) {
|
|
526
|
+
if (!(error instanceof ORPCError)) {
|
|
527
|
+
console.error("[api] Unexpected procedure error:", error);
|
|
528
|
+
}
|
|
529
|
+
throw error;
|
|
530
|
+
}
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// Entity names are validated at construction: docs/architecture/plugins/api.md, "Entities".
|
|
535
|
+
function assertValidEntityNames(
|
|
536
|
+
kind: "reads" | "writes",
|
|
537
|
+
entities: readonly string[],
|
|
538
|
+
): void {
|
|
539
|
+
for (const name of entities) {
|
|
540
|
+
if (!ENTITY_NAME_RE.test(name)) {
|
|
541
|
+
throw new Error(
|
|
542
|
+
`procedure(): invalid entity name "${name}" in \`${kind}\` -- entity names become ` +
|
|
543
|
+
"comma-joined Headers values (x-slotform-reads/x-slotform-writes) and may only contain " +
|
|
544
|
+
'letters, digits, "_", ".", and "-". Rename the entity.',
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// Entity headers are stamped only on success: docs/architecture/plugins/api.md, "Entity headers".
|
|
551
|
+
function createEntityHeadersMiddleware(
|
|
552
|
+
reads: readonly string[],
|
|
553
|
+
writes: readonly string[],
|
|
554
|
+
): OrpcMiddlewareFn<{ resHeaders: Headers }> {
|
|
555
|
+
return async ({ context, next }, _input) => {
|
|
556
|
+
const result = await next({ context: {} });
|
|
557
|
+
if (reads.length > 0) {
|
|
558
|
+
context.resHeaders.set(SLOTFORM_READS_HEADER, reads.join(","));
|
|
559
|
+
}
|
|
560
|
+
if (writes.length > 0) {
|
|
561
|
+
context.resHeaders.set(SLOTFORM_WRITES_HEADER, writes.join(","));
|
|
562
|
+
}
|
|
563
|
+
return result;
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// The input a paginated procedure adds: the page (a cursor, or an offset) and
|
|
568
|
+
// its size, and the sort when columns are declared. A `maxLimit` below the
|
|
569
|
+
// default limit lowers the default with it.
|
|
570
|
+
function pageShape(opts: BaseOptions): z.ZodRawShape {
|
|
571
|
+
const max = opts.maxLimit ?? MAX_LIMIT;
|
|
572
|
+
if (!Number.isInteger(max) || max < 1 || max > LIMIT_CEILING) {
|
|
573
|
+
throw new Error(
|
|
574
|
+
`procedure(): \`maxLimit\` is a whole number from 1 to ${LIMIT_CEILING}, got ${max}`,
|
|
575
|
+
);
|
|
576
|
+
}
|
|
577
|
+
return {
|
|
578
|
+
...(opts.paginated === "window"
|
|
579
|
+
? { offset: z.number().int().min(0).default(0) }
|
|
580
|
+
: { cursor: z.string().optional() }),
|
|
581
|
+
limit: z
|
|
582
|
+
.number()
|
|
583
|
+
.int()
|
|
584
|
+
.min(1)
|
|
585
|
+
.max(max)
|
|
586
|
+
.default(Math.min(DEFAULT_LIMIT, max)),
|
|
587
|
+
...(opts.sort
|
|
588
|
+
? {
|
|
589
|
+
sort: z
|
|
590
|
+
.object({
|
|
591
|
+
column: z.enum(opts.sort),
|
|
592
|
+
direction: z.enum(["asc", "desc"]),
|
|
593
|
+
})
|
|
594
|
+
.optional(),
|
|
595
|
+
}
|
|
596
|
+
: {}),
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
function toOrpcMiddleware<
|
|
601
|
+
TIn extends Record<string, unknown>,
|
|
602
|
+
TExtra extends Record<string, unknown>,
|
|
603
|
+
>(mw: Middleware<TIn, TExtra>) {
|
|
604
|
+
return async (
|
|
605
|
+
{
|
|
606
|
+
context,
|
|
607
|
+
next,
|
|
608
|
+
}: {
|
|
609
|
+
context: TIn;
|
|
610
|
+
next: (opts: { context: unknown }) => Promise<unknown>;
|
|
611
|
+
},
|
|
612
|
+
input: unknown,
|
|
613
|
+
) => {
|
|
614
|
+
const extra = await mw({ context, input });
|
|
615
|
+
return next({ context: { ...context, ...extra } });
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
function normalizeRateLimits(
|
|
620
|
+
rateLimit: RateLimitKind | readonly RateLimitKind[] | undefined,
|
|
621
|
+
): readonly RateLimitKind[] {
|
|
622
|
+
if (!rateLimit) return [];
|
|
623
|
+
return Array.isArray(rateLimit) ? rateLimit : [rateLimit as RateLimitKind];
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
// We call a small subset of methods on the oRPC Builder / ProcedureBuilder*.
|
|
627
|
+
// Modeling the full oRPC generic chain here would force us to re-derive all
|
|
628
|
+
// of oRPC's internal type machinery; instead we describe just the surface we
|
|
629
|
+
// touch. Every oRPC builder object satisfies this shape structurally, and the
|
|
630
|
+
// returned `OrpcChain` values are funneled through our strictly-typed public
|
|
631
|
+
// `ProcedureBuilder` interface before they reach consumers.
|
|
632
|
+
//
|
|
633
|
+
// Middleware and handler types are intentionally permissive on `context`
|
|
634
|
+
// (`Record<string, unknown>` or a narrower required subset) so that the
|
|
635
|
+
// concrete middleware factories below — each of which requires specific
|
|
636
|
+
// context keys like `auth` / `session` / `_rateLimiter` — are assignable
|
|
637
|
+
// without casts. oRPC itself does the same: its runtime only peeks at
|
|
638
|
+
// `context` to spread it, never constrains its shape at call time.
|
|
639
|
+
type OrpcNext = (opts: { context: unknown }) => Promise<unknown>;
|
|
640
|
+
|
|
641
|
+
// A middleware whose required context is `TCtx`. Because function parameters
|
|
642
|
+
// are contravariant, an `OrpcMiddlewareFn<{ auth: X }>` is assignable to
|
|
643
|
+
// `OrpcMiddlewareFn<Record<string, unknown> & { auth: X }>` — exactly the
|
|
644
|
+
// structural relationship we want between our typed factories and the chain.
|
|
645
|
+
type OrpcMiddlewareFn<
|
|
646
|
+
TCtx extends Record<string, unknown> = Record<string, unknown>,
|
|
647
|
+
> = (
|
|
648
|
+
opts: { context: TCtx; next: OrpcNext },
|
|
649
|
+
input: unknown,
|
|
650
|
+
) => Promise<unknown>;
|
|
651
|
+
|
|
652
|
+
type OrpcHandlerFn = (opts: {
|
|
653
|
+
context: Record<string, unknown>;
|
|
654
|
+
input: unknown;
|
|
655
|
+
}) => unknown;
|
|
656
|
+
|
|
657
|
+
interface OrpcChain {
|
|
658
|
+
// `use` is parameterized so middleware factories with narrower required
|
|
659
|
+
// context (e.g. `{ auth: ..., reqHeaders: Headers }`) are accepted without
|
|
660
|
+
// casts. Method-parameter bivariance makes this assignment legal even
|
|
661
|
+
// under `strictFunctionTypes`.
|
|
662
|
+
use<TCtx extends Record<string, unknown>>(
|
|
663
|
+
middleware: OrpcMiddlewareFn<TCtx>,
|
|
664
|
+
): OrpcChain;
|
|
665
|
+
input(schema: z.ZodType): OrpcChain;
|
|
666
|
+
output(schema: z.ZodType): OrpcChain;
|
|
667
|
+
handler(fn: OrpcHandlerFn): OrpcTerminal;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// The oRPC `DecoratedProcedure` value our handler calls produce. Consumers
|
|
671
|
+
// only read it as our opaque `Procedure<TInput, TOutput>` brand.
|
|
672
|
+
interface OrpcTerminal {
|
|
673
|
+
readonly "~orpc": unknown;
|
|
674
|
+
meta(meta: Record<string, unknown>): OrpcTerminal;
|
|
675
|
+
route(route: { method: "GET" }): OrpcTerminal;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
// What a procedure's terminal call says it is, as the oRPC meta the MCP
|
|
679
|
+
// endpoint reads: a query is read-only, a mutation and a bare handler are not.
|
|
680
|
+
type ProcedureKind = "query" | "mutation";
|
|
681
|
+
|
|
682
|
+
// Only a query answers a GET: docs/architecture/plugins/api.md, "Reads travel as GET".
|
|
683
|
+
function stamp(
|
|
684
|
+
terminal: OrpcTerminal,
|
|
685
|
+
kind: ProcedureKind,
|
|
686
|
+
scope: string | null,
|
|
687
|
+
): OrpcTerminal {
|
|
688
|
+
const stamped = terminal.meta({ kind, ...(scope ? { scope } : {}) });
|
|
689
|
+
return kind === "query" ? stamped.route({ method: "GET" }) : stamped;
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
interface BuilderState {
|
|
693
|
+
chain: OrpcChain;
|
|
694
|
+
baseShape: z.ZodRawShape | null;
|
|
695
|
+
// The input key the procedure's `scope` adds (`organizationId`), stamped on
|
|
696
|
+
// its meta as `scope`; the client's types read it from `Procedure`'s third parameter.
|
|
697
|
+
scope: string | null;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
// `safeExtend` keeps the unknown-key policy and refinements: docs/architecture/plugins/api.md, "Procedure factory".
|
|
701
|
+
function mergeInput(
|
|
702
|
+
baseShape: z.ZodRawShape | null,
|
|
703
|
+
schema: z.ZodType,
|
|
704
|
+
): z.ZodType {
|
|
705
|
+
if (baseShape === null) return schema;
|
|
706
|
+
if (!(schema instanceof z.ZodObject)) {
|
|
707
|
+
throw new Error(
|
|
708
|
+
"procedure() with `scope` or `paginated` requires an object input schema. Use .input(z.object({...})).",
|
|
709
|
+
);
|
|
710
|
+
}
|
|
711
|
+
for (const key of Object.keys(baseShape)) {
|
|
712
|
+
if (key in schema.shape) {
|
|
713
|
+
throw new Error(
|
|
714
|
+
`procedure(): the input schema declares \`${key}\`, a key the procedure's \`scope\` or \`paginated\` config adds. Drop \`${key}\` from the input schema.`,
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
return schema.safeExtend(baseShape);
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
function createBuilder<
|
|
722
|
+
TContext extends Record<string, unknown>,
|
|
723
|
+
TBaseInput extends AnySides,
|
|
724
|
+
>(state: BuilderState): ProcedureBuilder<TContext, TBaseInput> {
|
|
725
|
+
const { chain, baseShape, scope } = state;
|
|
726
|
+
|
|
727
|
+
// The end of a chain no `.input()` was called on: the config's own keys,
|
|
728
|
+
// when it adds any, are the input.
|
|
729
|
+
function terminate(on: OrpcChain) {
|
|
730
|
+
return (fn: OrpcHandlerFn): OrpcTerminal =>
|
|
731
|
+
(baseShape === null ? on : on.input(z.object(baseShape))).handler(fn);
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// `.handler()` is a mutation under another name.
|
|
735
|
+
function terminals(end: (fn: OrpcHandlerFn) => OrpcTerminal) {
|
|
736
|
+
return {
|
|
737
|
+
handler: (fn: OrpcHandlerFn) => stamp(end(fn), "mutation", scope),
|
|
738
|
+
query: (fn: OrpcHandlerFn) => stamp(end(fn), "query", scope),
|
|
739
|
+
mutation: (fn: OrpcHandlerFn) => stamp(end(fn), "mutation", scope),
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
const builder = {
|
|
744
|
+
use(
|
|
745
|
+
middleware: Middleware<Record<string, unknown>, Record<string, unknown>>,
|
|
746
|
+
) {
|
|
747
|
+
return createBuilder<TContext, TBaseInput>({
|
|
748
|
+
chain: chain.use(toOrpcMiddleware(middleware)),
|
|
749
|
+
baseShape,
|
|
750
|
+
scope,
|
|
751
|
+
});
|
|
752
|
+
},
|
|
753
|
+
|
|
754
|
+
input(userSchema: z.ZodType) {
|
|
755
|
+
const withInputChain = chain.input(mergeInput(baseShape, userSchema));
|
|
756
|
+
const run = (fn: OrpcHandlerFn) => withInputChain.handler(fn);
|
|
757
|
+
|
|
758
|
+
const withInput = {
|
|
759
|
+
output(outputSchema: z.ZodType) {
|
|
760
|
+
const withOutputChain = withInputChain.output(outputSchema);
|
|
761
|
+
const runWithOutput = (fn: OrpcHandlerFn) =>
|
|
762
|
+
withOutputChain.handler(fn);
|
|
763
|
+
return terminals(runWithOutput);
|
|
764
|
+
},
|
|
765
|
+
...terminals(run),
|
|
766
|
+
};
|
|
767
|
+
// Boundary: our literal shares method names/arities with
|
|
768
|
+
// `ProcedureWithInput`, but its internal generics don't propagate
|
|
769
|
+
// into the object-literal type. One cast bridges the two.
|
|
770
|
+
return withInput as unknown as ProcedureWithInput<
|
|
771
|
+
TContext,
|
|
772
|
+
MergedInput<TBaseInput, z.ZodType>
|
|
773
|
+
>;
|
|
774
|
+
},
|
|
775
|
+
|
|
776
|
+
output(outputSchema: z.ZodType) {
|
|
777
|
+
const withOutputChain = chain.output(outputSchema);
|
|
778
|
+
const withOutput = {
|
|
779
|
+
input(inputSchema: z.ZodType) {
|
|
780
|
+
const innerChain = withOutputChain.input(
|
|
781
|
+
mergeInput(baseShape, inputSchema),
|
|
782
|
+
);
|
|
783
|
+
const run = (fn: OrpcHandlerFn) => innerChain.handler(fn);
|
|
784
|
+
return terminals(run);
|
|
785
|
+
},
|
|
786
|
+
...terminals(terminate(withOutputChain)),
|
|
787
|
+
};
|
|
788
|
+
// Same boundary as in `input()` above.
|
|
789
|
+
return withOutput as unknown as ProcedureWithOutput<
|
|
790
|
+
TContext,
|
|
791
|
+
TBaseInput,
|
|
792
|
+
AnySides
|
|
793
|
+
>;
|
|
794
|
+
},
|
|
795
|
+
|
|
796
|
+
...terminals(terminate(chain)),
|
|
797
|
+
};
|
|
798
|
+
|
|
799
|
+
// Final boundary: this literal satisfies every method required by
|
|
800
|
+
// `ProcedureBuilder<TContext, TBaseInput>`, but the generic linkage (ctx
|
|
801
|
+
// extensions from `use`, input additions from `org`/`paginated`) is only
|
|
802
|
+
// tracked at `procedure()`'s return type — not through this literal.
|
|
803
|
+
return builder as unknown as ProcedureBuilder<TContext, TBaseInput>;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
export function createProcedure<
|
|
807
|
+
TContext extends Record<string, unknown>,
|
|
808
|
+
TStatements extends DefaultStatements = Record<string, string[]>,
|
|
809
|
+
TEntity extends string = string,
|
|
810
|
+
>(): ProcedureFactory<TContext, TStatements, TEntity> {
|
|
811
|
+
// oRPC's root `Builder` has 6 generics we don't surface; treat it as an
|
|
812
|
+
// `OrpcChain` from here on so the chain's structural type is stable.
|
|
813
|
+
const base = os.$context<TContext>() as unknown as OrpcChain;
|
|
814
|
+
|
|
815
|
+
function procedure(config?: ProcedureConfig<TStatements, TEntity>) {
|
|
816
|
+
const opts = (config ?? {}) as ProcedureConfig<TStatements, TEntity> &
|
|
817
|
+
BaseOptions<TEntity>;
|
|
818
|
+
let chain: OrpcChain = base;
|
|
819
|
+
|
|
820
|
+
// Root middleware, ahead of rate-limit/auth/org/rbac: logs unexpected
|
|
821
|
+
// (non-ORPCError) throws before oRPC flattens them into an opaque 500.
|
|
822
|
+
chain = chain.use(createErrorLoggingMiddleware());
|
|
823
|
+
|
|
824
|
+
// Right after error logging, so the header-setting middleware
|
|
825
|
+
// still sees (and rethrows past) any error the inner chain produces.
|
|
826
|
+
const reads = opts.reads ?? [];
|
|
827
|
+
const writes = opts.writes ?? [];
|
|
828
|
+
assertValidEntityNames("reads", reads);
|
|
829
|
+
assertValidEntityNames("writes", writes);
|
|
830
|
+
if (reads.length > 0 || writes.length > 0) {
|
|
831
|
+
chain = chain.use(createEntityHeadersMiddleware(reads, writes));
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// Each middleware factory declares its own required `context` shape
|
|
835
|
+
// (e.g. `{ reqHeaders, auth }` for auth, `{ session }` for org). The
|
|
836
|
+
// generic `OrpcChain.use<TCtx>` infers TCtx from that shape, so no
|
|
837
|
+
// cast is needed — the structural match carries through.
|
|
838
|
+
for (const kind of normalizeRateLimits(opts.rateLimit)) {
|
|
839
|
+
chain = chain.use(createRateLimitMiddleware(kind));
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
const isAuth = "auth" in opts && opts.auth === true;
|
|
843
|
+
if (isAuth) {
|
|
844
|
+
chain = chain.use(createAuthMiddleware());
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
const scope = "scope" in opts ? opts.scope : undefined;
|
|
848
|
+
if (scope) {
|
|
849
|
+
chain = chain.use(createScopeMiddleware(scope));
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
if ("rbac" in opts && opts.rbac) {
|
|
853
|
+
const [resource, actions] = opts.rbac;
|
|
854
|
+
chain = chain.use(createPermissionMiddleware(resource, [...actions]));
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
// `can` is sugar over the same check, action-first. If both `rbac` and
|
|
858
|
+
// `can` are set, both run (independent checks).
|
|
859
|
+
if ("can" in opts && opts.can) {
|
|
860
|
+
const [action, resource] = opts.can;
|
|
861
|
+
chain = chain.use(createPermissionMiddleware(resource, [action]));
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
const isPaginated = opts.paginated === true || opts.paginated === "window";
|
|
865
|
+
if (opts.sort && !isPaginated) {
|
|
866
|
+
throw new Error("procedure(): `sort` needs `paginated`");
|
|
867
|
+
}
|
|
868
|
+
let baseShape: z.ZodRawShape | null = null;
|
|
869
|
+
if (scope || isPaginated) {
|
|
870
|
+
baseShape = {
|
|
871
|
+
...(scope ? { [scopeInputKey(scope)]: z.string().min(1) } : {}),
|
|
872
|
+
...(isPaginated ? pageShape(opts) : {}),
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
return createBuilder({
|
|
877
|
+
chain,
|
|
878
|
+
baseShape,
|
|
879
|
+
scope: scope ? scopeInputKey(scope) : null,
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
// `procedure` takes a config and returns a builder, but `ProcedureFactory`'s
|
|
884
|
+
// return type is derived from the config's literal type, which one runtime
|
|
885
|
+
// signature cannot state.
|
|
886
|
+
return procedure as unknown as ProcedureFactory<
|
|
887
|
+
TContext,
|
|
888
|
+
TStatements,
|
|
889
|
+
TEntity
|
|
890
|
+
>;
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
// A queue batch as a handler sees it. Structural, so this package takes no
|
|
894
|
+
// dependency on Cloudflare's types: a `MessageBatch` satisfies it.
|
|
895
|
+
export interface JobMessage<Body = unknown> {
|
|
896
|
+
readonly id: string;
|
|
897
|
+
readonly body: Body;
|
|
898
|
+
readonly attempts: number;
|
|
899
|
+
readonly timestamp: Date;
|
|
900
|
+
ack(): void;
|
|
901
|
+
retry(options?: { delaySeconds?: number }): void;
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
export interface JobBatch<Body = unknown> {
|
|
905
|
+
readonly queue: string;
|
|
906
|
+
readonly messages: readonly JobMessage<Body>[];
|
|
907
|
+
ackAll(): void;
|
|
908
|
+
retryAll(options?: { delaySeconds?: number }): void;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
// The cron event a scheduled handler sees (`ScheduledController`'s members).
|
|
912
|
+
export interface JobScheduledEvent {
|
|
913
|
+
readonly cron: string;
|
|
914
|
+
readonly scheduledTime: number;
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
// The convention files' factories: docs/architecture/runtime.md, "Background handlers".
|
|
918
|
+
export function createJobs<TContext>(): {
|
|
919
|
+
defineQueue<Body = unknown>(
|
|
920
|
+
run: (batch: JobBatch<Body>, context: TContext) => Promise<void>,
|
|
921
|
+
): (batch: JobBatch<Body>, context: TContext) => Promise<void>;
|
|
922
|
+
defineScheduled(
|
|
923
|
+
run: (event: JobScheduledEvent, context: TContext) => Promise<void>,
|
|
924
|
+
): (event: JobScheduledEvent, context: TContext) => Promise<void>;
|
|
925
|
+
} {
|
|
926
|
+
return {
|
|
927
|
+
defineQueue: (run) => run,
|
|
928
|
+
defineScheduled: (run) => run,
|
|
929
|
+
};
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
// The app's `JobContext`, which `.slotform/procedure.ts` registers for code that
|
|
933
|
+
// cannot import it (a plugin's node service): docs/architecture/runtime.md, "Background handlers".
|
|
934
|
+
// biome-ignore lint/suspicious/noEmptyInterface: an interface so `.slotform/procedure.ts` can merge into it
|
|
935
|
+
export interface Register {}
|