@loozo/angular-launch 0.0.1 → 0.0.2

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.
@@ -0,0 +1,486 @@
1
+ import type { JsonShape } from "../json.js";
2
+ import type { FrameworkCode } from "../client.js";
3
+ import { declaredFailures } from "./errors.js";
4
+ import type { DeclaredFailure } from "./errors.js";
5
+ /**
6
+ * Registration point for the application's context type.
7
+ *
8
+ * @remarks
9
+ * Generation writes `context.generated.d.ts`, which augments this interface with a
10
+ * `context` property typed as the awaited return value of your `defineContext`
11
+ * factory. Don't augment it yourself.
12
+ */
13
+ export interface Register {
14
+ }
15
+ /**
16
+ * The application's context type, as registered by generation.
17
+ *
18
+ * @remarks
19
+ * Handlers and guards receive a value of this type as `context`. It's `never` until
20
+ * generation has registered the context type, so include the generated files in your
21
+ * tsconfig.
22
+ */
23
+ export type Context = Register extends {
24
+ context: infer Value;
25
+ } ? Value : never;
26
+ /**
27
+ * A {@link https://standardschema.dev | Standard Schema} V1 validator, from any library
28
+ * or written by hand.
29
+ *
30
+ * @remarks
31
+ * Launch uses schemas for procedure inputs and declared error data. Validation may be
32
+ * asynchronous and may transform the value. For a procedure input, callers pass the
33
+ * input type and the procedure's guards and handler receive the output type; group
34
+ * guards receive no input, and the client's success value is the handler's result,
35
+ * not a schema output. For declared error data, the client receives the output type.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * import type { Schema } from "@loozo/angular-launch/server";
40
+ *
41
+ * export const idSchema: Schema<{ id: string }> = {
42
+ * "~standard": {
43
+ * version: 1,
44
+ * vendor: "todos",
45
+ * validate: (value) => {
46
+ * if (
47
+ * typeof value !== "object" ||
48
+ * value === null ||
49
+ * !("id" in value) ||
50
+ * typeof value.id !== "string"
51
+ * ) {
52
+ * return { issues: [{ message: "Expected { id: string }" }] };
53
+ * }
54
+ *
55
+ * return { value: { id: value.id } };
56
+ * },
57
+ * },
58
+ * };
59
+ * ```
60
+ *
61
+ * @typeParam Input - The type callers pass in.
62
+ * @typeParam Output - The validated, possibly transformed type.
63
+ */
64
+ export interface Schema<Input = unknown, Output = Input> {
65
+ /** The Standard Schema V1 interface. */
66
+ readonly "~standard": {
67
+ /** The Standard Schema version: always `1`. */
68
+ readonly version: 1;
69
+ /** The name of the schema library, or your own name for a handwritten schema. */
70
+ readonly vendor: string;
71
+ /** Type-only witnesses for the input and output types; not needed at runtime. */
72
+ readonly types?: {
73
+ /** The type callers pass in. */
74
+ readonly input: Input;
75
+ /** The validated, possibly transformed type. */
76
+ readonly output: Output;
77
+ };
78
+ /**
79
+ * Validates an unknown value, synchronously or asynchronously.
80
+ *
81
+ * @param value - The value to validate.
82
+ * @returns `{ value }` with the output on success, or `{ issues }` on failure.
83
+ */
84
+ readonly validate: (value: unknown) => {
85
+ /** The validated, possibly transformed value. */
86
+ readonly value: Output;
87
+ /** Absent on success. */
88
+ readonly issues?: undefined;
89
+ } | {
90
+ /** The problems found, which mark a failure. Not sent to clients. */
91
+ readonly issues: readonly {
92
+ /** A description of the problem. */
93
+ readonly message: string;
94
+ }[];
95
+ } | Promise<{
96
+ /** The validated, possibly transformed value. */
97
+ readonly value: Output;
98
+ /** Absent on success. */
99
+ readonly issues?: undefined;
100
+ } | {
101
+ /** The problems found, which mark a failure. Not sent to clients. */
102
+ readonly issues: readonly {
103
+ /** A description of the problem. */
104
+ readonly message: string;
105
+ }[];
106
+ }>;
107
+ };
108
+ }
109
+ /** The type callers pass to a schema: its Standard Schema input type. */
110
+ export type InputOf<S extends Schema> = NonNullable<S["~standard"]["types"]>["input"];
111
+ /**
112
+ * The validated type a schema produces, or `undefined` when `S` isn't a schema, such
113
+ * as for a procedure without input.
114
+ */
115
+ export type OutputOf<S> = S extends Schema<unknown, infer Output> ? Output : undefined;
116
+ /**
117
+ * The application's context factory, created by {@link defineContext}.
118
+ *
119
+ * @typeParam Value - The factory's return type, possibly a promise.
120
+ */
121
+ export interface ContextDefinition<Value> {
122
+ /**
123
+ * Creates the context for one live server request.
124
+ *
125
+ * @param request - The request bound to the new request scope.
126
+ * @returns The context value, or a promise of it.
127
+ */
128
+ readonly create: (request: Request) => Value;
129
+ }
130
+ /**
131
+ * Defines the application's per-request server context.
132
+ *
133
+ * @remarks
134
+ * Default-export the call itself from exactly one file in your application's sources,
135
+ * as `export default defineContext(...)`: generation finds it by that default export and
136
+ * registers its awaited return type as {@link Context}. Import `defineContext` by name
137
+ * from this entry point and call it without type arguments; a context assigned to a
138
+ * variable and exported later, or `defineContext<MyContext>(...)`, fails generation.
139
+ * The factory runs once per live server request, for page renders
140
+ * and RPC requests alike, and its value is what handlers and guards receive as
141
+ * `context`. Keep per-request state in the context rather than in module variables.
142
+ *
143
+ * @example
144
+ * ```ts
145
+ * import { defineContext } from "@loozo/angular-launch/server";
146
+ * import { sessions } from "./sessions.server";
147
+ *
148
+ * export default defineContext(async (request: Request) => ({
149
+ * user: await sessions.authenticate(request),
150
+ * }));
151
+ * ```
152
+ *
153
+ * @typeParam Value - The factory's return type, possibly a promise.
154
+ * @param create - Creates the context for one request. A rejection or throw fails that
155
+ * request: an RPC request returns `INTERNAL`.
156
+ * @returns The context definition to default-export.
157
+ */
158
+ export declare function defineContext<Value>(create: (request: Request) => Value): ContextDefinition<Value>;
159
+ /** The awaited context type of a context created by {@link defineContext}. */
160
+ export type ContextOf<Definition> = Definition extends ContextDefinition<infer Value> ? Awaited<Value> : never;
161
+ /**
162
+ * A group guard, passed to `defineRpc` in `canActivate`.
163
+ *
164
+ * @remarks
165
+ * Group guards run after input validation and before the procedure's guards, for
166
+ * every procedure in the group. Returning `false` fails the call with `FORBIDDEN`;
167
+ * throwing fails it with `INTERNAL`. Guards aren't inherited through the route tree
168
+ * and don't narrow types.
169
+ *
170
+ * @example
171
+ * ```ts
172
+ * import type { Guard } from "@loozo/angular-launch/server";
173
+ *
174
+ * export const isSignedIn: Guard = ({ context }) => context.user !== null;
175
+ * ```
176
+ */
177
+ export type Guard = (args: {
178
+ /** The context created for the request. */
179
+ readonly context: Context;
180
+ /**
181
+ * The live request the call runs in, bound to its request scope: the scope's copy of
182
+ * the RPC HTTP request, or, during server rendering, the page request given to Angular.
183
+ */
184
+ readonly request: Request;
185
+ }) => boolean | Promise<boolean>;
186
+ /**
187
+ * A procedure guard, passed to `query` or `mutation` in `canActivate`.
188
+ *
189
+ * @remarks
190
+ * Procedure guards run after the group's guards and receive the validated input as
191
+ * well. Returning `false` fails the call with `FORBIDDEN`; throwing fails it with
192
+ * `INTERNAL`.
193
+ *
194
+ * @typeParam Input - The procedure's input schema, or `undefined` without input.
195
+ */
196
+ export type ProcedureGuard<Input> = (args: {
197
+ /** The context created for the request. */
198
+ readonly context: Context;
199
+ /**
200
+ * The live request the call runs in, bound to its request scope: the scope's copy of
201
+ * the RPC HTTP request, or, during server rendering, the page request given to Angular.
202
+ */
203
+ readonly request: Request;
204
+ /** The validated input: the schema's output, or `undefined` without an input schema. */
205
+ readonly input: OutputOf<Input>;
206
+ }) => boolean | Promise<boolean>;
207
+ type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
208
+ type StatusNumber<Value> = Value extends `${infer Status extends number}` ? Status : never;
209
+ /** An HTTP error status from 400 to 599, as an integer literal type. */
210
+ export type ErrorStatus = StatusNumber<`${4 | 5}${Digit}${Digit}`>;
211
+ /**
212
+ * The declaration of one error a procedure can return.
213
+ *
214
+ * @remarks
215
+ * Declare errors inline in `query` or `mutation`. The type is public so that
216
+ * application code can name a procedure's `errors` metadata.
217
+ *
218
+ * @typeParam Data - The schema for the error's data.
219
+ */
220
+ export interface ErrorDefinition<Data extends Schema = Schema> {
221
+ /** The HTTP status the error is sent with: an integer literal from 400 to 599. */
222
+ readonly status: ErrorStatus;
223
+ /** The public message sent with every instance of the error: a non-empty literal. */
224
+ readonly message: string;
225
+ /**
226
+ * The schema the server validates the error's data with before sending it. Use a
227
+ * `Schema<null>` for an error without data.
228
+ */
229
+ readonly data: Data;
230
+ }
231
+ /**
232
+ * A procedure's declared errors, keyed by error code.
233
+ *
234
+ * @remarks
235
+ * Codes are identifiers. The framework codes in `frameworkFailures` and `__proto__`
236
+ * can't be declared.
237
+ */
238
+ export type ErrorDefinitions = Readonly<Record<string, ErrorDefinition>>;
239
+ /**
240
+ * The `errors` a handler receives: one factory per declared error code.
241
+ *
242
+ * @remarks
243
+ * A factory creates an error to `throw` from the handler. The server validates its
244
+ * data with the declared schema and sends it with the declared status and message;
245
+ * data that fails validation turns the response into `INTERNAL`. Only throwing an
246
+ * error created by the same procedure's factory produces a declared error response.
247
+ *
248
+ * @typeParam Definitions - The procedure's declared errors.
249
+ */
250
+ export type ErrorFactories<Definitions extends ErrorDefinitions> = {
251
+ readonly [Code in keyof Definitions]: (data: InputOf<Definitions[Code]["data"]>) => Error;
252
+ };
253
+ type JsonContract<Value> = 0 extends 1 & Value ? never : [Value] extends [JsonShape<Value>] ? unknown : never;
254
+ type InputContract<Input> = Input extends Schema ? JsonContract<InputOf<Input>> : unknown;
255
+ type ErrorContract<Definitions extends ErrorDefinitions> = {
256
+ readonly [Code in keyof Definitions]: Code extends FrameworkCode | "__proto__" ? never : Definitions[Code]["message"] extends "" ? never : Definitions[Code] & JsonContract<OutputOf<Definitions[Code]["data"]>>;
257
+ };
258
+ type JsonResult<Value> = Value extends Promise<infer Result> ? Promise<JsonShape<Result>> : JsonShape<Value>;
259
+ /** Whether a procedure reads (`"query"`) or writes (`"mutation"`). */
260
+ export type ProcedureKind = "query" | "mutation";
261
+ /**
262
+ * A procedure created by {@link query} or {@link mutation}.
263
+ *
264
+ * @remarks
265
+ * Procedures are values for `defineRpc`. Their types drive the generated client;
266
+ * the server dispatches calls to them. Don't build one by hand.
267
+ *
268
+ * @typeParam Input - The input schema, or `undefined` without input.
269
+ * @typeParam Output - The handler's return type.
270
+ * @typeParam Kind - Whether the procedure is a query or a mutation.
271
+ * @typeParam Errors - The declared errors.
272
+ */
273
+ export interface Procedure<Input, Output, Kind extends ProcedureKind = "query", Errors extends ErrorDefinitions = {}> {
274
+ /** Whether the procedure is a `"query"` or a `"mutation"`. */
275
+ readonly kind: Kind;
276
+ /** The input schema, or `undefined` for a procedure without input. */
277
+ readonly input: Input;
278
+ /** The declared errors, as written in the procedure's options. */
279
+ readonly errors: Errors;
280
+ /** The procedure's guards, in the order they run. Empty when none were given. */
281
+ readonly canActivate: readonly ProcedureGuard<Input>[];
282
+ /**
283
+ * Runs the authored handler with the procedure's own error factories.
284
+ *
285
+ * @param args - The context and the validated input. Any `errors` passed here are
286
+ * ignored in favor of the procedure's own factories.
287
+ * @returns The handler's result.
288
+ */
289
+ readonly handler: (args: {
290
+ /** The context created for the request. */
291
+ readonly context: Context;
292
+ /** The validated input: the schema's output, or `undefined` without an input schema. */
293
+ readonly input: OutputOf<Input>;
294
+ /** Ignored; the authored handler receives the procedure's own factories. */
295
+ readonly errors: ErrorFactories<Errors>;
296
+ }) => Output | Promise<Output>;
297
+ /** Internal record of errors created by this procedure's factories; not public API. */
298
+ readonly [declaredFailures]: WeakMap<object, DeclaredFailure>;
299
+ }
300
+ /**
301
+ * The options {@link query} and {@link mutation} take.
302
+ *
303
+ * @remarks
304
+ * Write them inline in the call; generation reads them statically.
305
+ *
306
+ * @typeParam Input - The input schema, or `undefined` without input.
307
+ * @typeParam Output - The handler's return type.
308
+ * @typeParam Errors - The declared errors.
309
+ */
310
+ export interface ProcedureOptions<Input, Output, Errors extends ErrorDefinitions> {
311
+ /** The schema the server validates the input with; omit it for a procedure without input. */
312
+ readonly input?: Input & InputContract<NoInfer<Input>>;
313
+ /** The declared errors, keyed by error code. */
314
+ readonly errors?: Errors & ErrorContract<NoInfer<Errors>>;
315
+ /**
316
+ * Guards run in order after the group's guards. The first to return `false` rejects the
317
+ * call as `FORBIDDEN`.
318
+ */
319
+ readonly canActivate?: readonly ProcedureGuard<Input>[];
320
+ /**
321
+ * Runs the call and returns its strict JSON result.
322
+ *
323
+ * @param args - The request's context, the validated input and the error factories.
324
+ * @returns The call's result, or a promise of it.
325
+ */
326
+ readonly handler: (args: {
327
+ /** The context created for the request. */
328
+ readonly context: Context;
329
+ /** The validated input: the schema's output, or `undefined` without an input schema. */
330
+ readonly input: OutputOf<Input>;
331
+ /** One factory per declared error code, creating an error to `throw`. */
332
+ readonly errors: ErrorFactories<Errors>;
333
+ }) => Output & JsonResult<NoInfer<Output>>;
334
+ }
335
+ /**
336
+ * Defines a procedure that reads data.
337
+ *
338
+ * @remarks
339
+ * The handler receives `{ context, input, errors }`: the request's {@link Context},
340
+ * the validated input (`undefined` without an input schema) and the
341
+ * error factories for the declared errors. A call validates the input, runs the
342
+ * group's guards, then the procedure's guards, then the handler. Inputs and results
343
+ * must be strict JSON; a result that isn't fails the call with `INTERNAL`. Throwing an
344
+ * error created by `errors` returns that declared error; any other exception fails the
345
+ * call with `INTERNAL` and is logged on the server.
346
+ *
347
+ * An explicit `input` schema must have a concrete type, without `undefined`, `null`,
348
+ * `any` or `unknown` branches, or generation fails: `Schema<string> | undefined` is
349
+ * rejected. The schema's caller input type may still be a JSON union, as in
350
+ * `Schema<string | number, number>`.
351
+ *
352
+ * Query responses are stored in Angular's HTTP transfer cache during server rendering
353
+ * by default, so hydration reuses them.
354
+ *
355
+ * @example
356
+ * ```ts
357
+ * list: query({
358
+ * handler: ({ context }) => context.db.todos.listForUser(requireUser(context).id),
359
+ * }),
360
+ * ```
361
+ *
362
+ * @typeParam Input - The input schema; omit `input` for a procedure without input.
363
+ * @typeParam Output - The handler's return type.
364
+ * @typeParam Errors - The declared errors, written inline.
365
+ * @param options - The procedure's `input` schema, `canActivate` guards, inline
366
+ * `errors` declarations and `handler`.
367
+ * @returns The procedure, to use as a value in `defineRpc`.
368
+ * @throws TypeError when a declared error is invalid: its code isn't an identifier, is
369
+ * `__proto__` or a framework code, its status isn't an integer from 400 to 599, its
370
+ * message is empty, or its data isn't a Standard Schema V1.
371
+ */
372
+ export declare function query<Input extends Schema | undefined = undefined, Output = unknown, const Errors extends ErrorDefinitions = {}>(options: ProcedureOptions<Input, Output, Errors>): Procedure<Input, Output, "query", Errors>;
373
+ /**
374
+ * Defines a procedure that writes data.
375
+ *
376
+ * @remarks
377
+ * The handler receives `{ context, input, errors }`: the request's {@link Context},
378
+ * the validated input (`undefined` without an input schema) and the
379
+ * error factories for the declared errors. A call validates the input, runs the
380
+ * group's guards, then the procedure's guards, then the handler. Inputs and results
381
+ * must be strict JSON; a result that isn't fails the call with `INTERNAL`. Throwing an
382
+ * error created by `errors` returns that declared error; any other exception fails the
383
+ * call with `INTERNAL` and is logged on the server.
384
+ *
385
+ * An explicit `input` schema must have a concrete type, without `undefined`, `null`,
386
+ * `any` or `unknown` branches, or generation fails: `Schema<string> | undefined` is
387
+ * rejected. The schema's caller input type may still be a JSON union, as in
388
+ * `Schema<string | number, number>`.
389
+ *
390
+ * Mutations never use the HTTP transfer cache. During server rendering they fail with
391
+ * `FORBIDDEN` before validation, guards or the handler run.
392
+ *
393
+ * @example
394
+ * ```ts
395
+ * add: mutation({
396
+ * input: titleSchema,
397
+ * handler: ({ input, context }) =>
398
+ * context.db.todos.addForUser(requireUser(context).id, input.title),
399
+ * }),
400
+ * ```
401
+ *
402
+ * @typeParam Input - The input schema; omit `input` for a procedure without input.
403
+ * @typeParam Output - The handler's return type.
404
+ * @typeParam Errors - The declared errors, written inline.
405
+ * @param options - The procedure's `input` schema, `canActivate` guards, inline
406
+ * `errors` declarations and `handler`.
407
+ * @returns The procedure, to use as a value in `defineRpc`.
408
+ * @throws TypeError when a declared error is invalid: its code isn't an identifier, is
409
+ * `__proto__` or a framework code, its status isn't an integer from 400 to 599, its
410
+ * message is empty, or its data isn't a Standard Schema V1.
411
+ */
412
+ export declare function mutation<Input extends Schema | undefined = undefined, Output = unknown, const Errors extends ErrorDefinitions = {}>(options: ProcedureOptions<Input, Output, Errors>): Procedure<Input, Output, "mutation", Errors>;
413
+ /**
414
+ * The minimal shape `defineRpc` accepts for each procedure.
415
+ *
416
+ * @remarks
417
+ * Create procedures with {@link query} or {@link mutation}; generation rejects any
418
+ * other value.
419
+ */
420
+ export interface ProcedureDefinition {
421
+ /** Whether the procedure is a `"query"` or a `"mutation"`. */
422
+ readonly kind: ProcedureKind;
423
+ }
424
+ /**
425
+ * An RPC group created by {@link defineRpc}.
426
+ *
427
+ * @typeParam Name - The group's namespace.
428
+ * @typeParam Procedures - The group's procedures, keyed by name.
429
+ */
430
+ export interface Group<Name extends string, Procedures extends Record<string, ProcedureDefinition>> {
431
+ /** The namespace the generated client exposes the group under. */
432
+ readonly name: Name;
433
+ /** The group's procedures, keyed by procedure name. */
434
+ readonly procedures: Procedures;
435
+ /** The group's guards, in the order they run. Empty when none were given. */
436
+ readonly canActivate: readonly Guard[];
437
+ }
438
+ /**
439
+ * Defines the RPC group for the route declared in the same directory.
440
+ *
441
+ * @remarks
442
+ * Default-export the result from a file next to the route's `route.ts`; one group per
443
+ * route. That route must be one that gets generated files: not a redirect, and with a
444
+ * page or descendants with pages that aren't all redirects. Generation reads the call
445
+ * statically without running it: import `defineRpc`, `query` and `mutation` by name
446
+ * from this entry point, call them directly without type arguments, use literal
447
+ * identifiers other than `__proto__` for the namespace and procedure names, and
448
+ * write the procedures, options and `canActivate` arrays inline. Each route's
449
+ * generated `injectRpc()` exposes its own group and its ancestors' groups under their
450
+ * namespaces, so a namespace can't repeat within one route's ancestry.
451
+ *
452
+ * Exposure isn't authorization: anyone who can reach the server can call any
453
+ * procedure, so guard every group and procedure that needs it.
454
+ *
455
+ * @example
456
+ * ```ts
457
+ * import { defineRpc, query } from "@loozo/angular-launch/server";
458
+ * import { isSignedIn, requireUser } from "../../auth.server";
459
+ *
460
+ * export default defineRpc(
461
+ * "todos",
462
+ * {
463
+ * list: query({
464
+ * handler: ({ context }) => context.db.todos.listForUser(requireUser(context).id),
465
+ * }),
466
+ * },
467
+ * { canActivate: [isSignedIn] },
468
+ * );
469
+ * ```
470
+ *
471
+ * @typeParam Name - The namespace literal.
472
+ * @typeParam Procedures - The procedures, keyed by name.
473
+ * @param name - The namespace the generated client exposes the group under.
474
+ * @param procedures - The procedures, keyed by name.
475
+ * @param options - `canActivate`: group guards that run for every procedure in the
476
+ * group.
477
+ * @returns The group, to default-export.
478
+ */
479
+ export declare function defineRpc<Name extends string, Procedures extends Record<string, ProcedureDefinition>>(name: Name, procedures: Procedures, { canActivate, }?: {
480
+ /**
481
+ * Guards run in order for every call to any procedure in the group, before the
482
+ * procedure's own guards. The first to return `false` rejects the call as `FORBIDDEN`.
483
+ */
484
+ readonly canActivate?: readonly Guard[];
485
+ }): Group<Name, Procedures>;
486
+ export {};
@@ -0,0 +1,170 @@
1
+ import { createErrors, declaredFailures } from "./errors.js";
2
+ /**
3
+ * Defines the application's per-request server context.
4
+ *
5
+ * @remarks
6
+ * Default-export the call itself from exactly one file in your application's sources,
7
+ * as `export default defineContext(...)`: generation finds it by that default export and
8
+ * registers its awaited return type as {@link Context}. Import `defineContext` by name
9
+ * from this entry point and call it without type arguments; a context assigned to a
10
+ * variable and exported later, or `defineContext<MyContext>(...)`, fails generation.
11
+ * The factory runs once per live server request, for page renders
12
+ * and RPC requests alike, and its value is what handlers and guards receive as
13
+ * `context`. Keep per-request state in the context rather than in module variables.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { defineContext } from "@loozo/angular-launch/server";
18
+ * import { sessions } from "./sessions.server";
19
+ *
20
+ * export default defineContext(async (request: Request) => ({
21
+ * user: await sessions.authenticate(request),
22
+ * }));
23
+ * ```
24
+ *
25
+ * @typeParam Value - The factory's return type, possibly a promise.
26
+ * @param create - Creates the context for one request. A rejection or throw fails that
27
+ * request: an RPC request returns `INTERNAL`.
28
+ * @returns The context definition to default-export.
29
+ */
30
+ export function defineContext(create) {
31
+ return { create };
32
+ }
33
+ function procedure(kind, options) {
34
+ const definitions = (options.errors ?? {});
35
+ const { factories, failures } = createErrors(definitions);
36
+ return {
37
+ kind,
38
+ input: options.input,
39
+ errors: definitions,
40
+ canActivate: options.canActivate ?? [],
41
+ handler: ({ context, input }) => options.handler({ context, input, errors: factories }),
42
+ [declaredFailures]: failures,
43
+ };
44
+ }
45
+ /**
46
+ * Defines a procedure that reads data.
47
+ *
48
+ * @remarks
49
+ * The handler receives `{ context, input, errors }`: the request's {@link Context},
50
+ * the validated input (`undefined` without an input schema) and the
51
+ * error factories for the declared errors. A call validates the input, runs the
52
+ * group's guards, then the procedure's guards, then the handler. Inputs and results
53
+ * must be strict JSON; a result that isn't fails the call with `INTERNAL`. Throwing an
54
+ * error created by `errors` returns that declared error; any other exception fails the
55
+ * call with `INTERNAL` and is logged on the server.
56
+ *
57
+ * An explicit `input` schema must have a concrete type, without `undefined`, `null`,
58
+ * `any` or `unknown` branches, or generation fails: `Schema<string> | undefined` is
59
+ * rejected. The schema's caller input type may still be a JSON union, as in
60
+ * `Schema<string | number, number>`.
61
+ *
62
+ * Query responses are stored in Angular's HTTP transfer cache during server rendering
63
+ * by default, so hydration reuses them.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * list: query({
68
+ * handler: ({ context }) => context.db.todos.listForUser(requireUser(context).id),
69
+ * }),
70
+ * ```
71
+ *
72
+ * @typeParam Input - The input schema; omit `input` for a procedure without input.
73
+ * @typeParam Output - The handler's return type.
74
+ * @typeParam Errors - The declared errors, written inline.
75
+ * @param options - The procedure's `input` schema, `canActivate` guards, inline
76
+ * `errors` declarations and `handler`.
77
+ * @returns The procedure, to use as a value in `defineRpc`.
78
+ * @throws TypeError when a declared error is invalid: its code isn't an identifier, is
79
+ * `__proto__` or a framework code, its status isn't an integer from 400 to 599, its
80
+ * message is empty, or its data isn't a Standard Schema V1.
81
+ */
82
+ export function query(options) {
83
+ return procedure("query", options);
84
+ }
85
+ /**
86
+ * Defines a procedure that writes data.
87
+ *
88
+ * @remarks
89
+ * The handler receives `{ context, input, errors }`: the request's {@link Context},
90
+ * the validated input (`undefined` without an input schema) and the
91
+ * error factories for the declared errors. A call validates the input, runs the
92
+ * group's guards, then the procedure's guards, then the handler. Inputs and results
93
+ * must be strict JSON; a result that isn't fails the call with `INTERNAL`. Throwing an
94
+ * error created by `errors` returns that declared error; any other exception fails the
95
+ * call with `INTERNAL` and is logged on the server.
96
+ *
97
+ * An explicit `input` schema must have a concrete type, without `undefined`, `null`,
98
+ * `any` or `unknown` branches, or generation fails: `Schema<string> | undefined` is
99
+ * rejected. The schema's caller input type may still be a JSON union, as in
100
+ * `Schema<string | number, number>`.
101
+ *
102
+ * Mutations never use the HTTP transfer cache. During server rendering they fail with
103
+ * `FORBIDDEN` before validation, guards or the handler run.
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * add: mutation({
108
+ * input: titleSchema,
109
+ * handler: ({ input, context }) =>
110
+ * context.db.todos.addForUser(requireUser(context).id, input.title),
111
+ * }),
112
+ * ```
113
+ *
114
+ * @typeParam Input - The input schema; omit `input` for a procedure without input.
115
+ * @typeParam Output - The handler's return type.
116
+ * @typeParam Errors - The declared errors, written inline.
117
+ * @param options - The procedure's `input` schema, `canActivate` guards, inline
118
+ * `errors` declarations and `handler`.
119
+ * @returns The procedure, to use as a value in `defineRpc`.
120
+ * @throws TypeError when a declared error is invalid: its code isn't an identifier, is
121
+ * `__proto__` or a framework code, its status isn't an integer from 400 to 599, its
122
+ * message is empty, or its data isn't a Standard Schema V1.
123
+ */
124
+ export function mutation(options) {
125
+ return procedure("mutation", options);
126
+ }
127
+ /**
128
+ * Defines the RPC group for the route declared in the same directory.
129
+ *
130
+ * @remarks
131
+ * Default-export the result from a file next to the route's `route.ts`; one group per
132
+ * route. That route must be one that gets generated files: not a redirect, and with a
133
+ * page or descendants with pages that aren't all redirects. Generation reads the call
134
+ * statically without running it: import `defineRpc`, `query` and `mutation` by name
135
+ * from this entry point, call them directly without type arguments, use literal
136
+ * identifiers other than `__proto__` for the namespace and procedure names, and
137
+ * write the procedures, options and `canActivate` arrays inline. Each route's
138
+ * generated `injectRpc()` exposes its own group and its ancestors' groups under their
139
+ * namespaces, so a namespace can't repeat within one route's ancestry.
140
+ *
141
+ * Exposure isn't authorization: anyone who can reach the server can call any
142
+ * procedure, so guard every group and procedure that needs it.
143
+ *
144
+ * @example
145
+ * ```ts
146
+ * import { defineRpc, query } from "@loozo/angular-launch/server";
147
+ * import { isSignedIn, requireUser } from "../../auth.server";
148
+ *
149
+ * export default defineRpc(
150
+ * "todos",
151
+ * {
152
+ * list: query({
153
+ * handler: ({ context }) => context.db.todos.listForUser(requireUser(context).id),
154
+ * }),
155
+ * },
156
+ * { canActivate: [isSignedIn] },
157
+ * );
158
+ * ```
159
+ *
160
+ * @typeParam Name - The namespace literal.
161
+ * @typeParam Procedures - The procedures, keyed by name.
162
+ * @param name - The namespace the generated client exposes the group under.
163
+ * @param procedures - The procedures, keyed by name.
164
+ * @param options - `canActivate`: group guards that run for every procedure in the
165
+ * group.
166
+ * @returns The group, to default-export.
167
+ */
168
+ export function defineRpc(name, procedures, { canActivate = [], } = {}) {
169
+ return { name, procedures, canActivate };
170
+ }