@loozo/angular-launch 0.0.5 → 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.
Files changed (92) hide show
  1. package/README.md +1068 -187
  2. package/builders/application.js +32 -3
  3. package/builders/channel-forwarding.d.ts +15 -0
  4. package/builders/channel-forwarding.js +61 -0
  5. package/builders/options.d.ts +6 -2
  6. package/builders/options.js +16 -5
  7. package/builders/serve.js +198 -140
  8. package/channel.d.ts +55 -0
  9. package/channel.js +232 -0
  10. package/client.d.ts +63 -33
  11. package/connect.d.ts +201 -0
  12. package/connect.js +148 -0
  13. package/generation/index.d.ts +2 -123
  14. package/generation/index.js +3 -669
  15. package/generation/redirects.d.ts +14 -0
  16. package/generation/redirects.js +43 -0
  17. package/generation/run.d.ts +168 -0
  18. package/generation/run.js +659 -0
  19. package/index.d.ts +8 -1
  20. package/index.js +3 -0
  21. package/json.d.ts +9 -0
  22. package/json.js +24 -0
  23. package/launch-queries.d.ts +16 -0
  24. package/launch-queries.js +3 -0
  25. package/navigation.d.ts +36 -0
  26. package/navigation.js +47 -0
  27. package/node/index.d.ts +60 -0
  28. package/node/index.js +178 -0
  29. package/node/upgrade-listener-slot.d.ts +1 -0
  30. package/node/upgrade-listener-slot.js +4 -0
  31. package/outcomes.d.ts +71 -0
  32. package/outcomes.js +146 -0
  33. package/package.json +21 -11
  34. package/redirect-translation.d.ts +53 -0
  35. package/redirect-translation.js +141 -0
  36. package/{generated.d.ts → remote-client.d.ts} +1 -1
  37. package/remote-client.js +179 -0
  38. package/route-types.d.ts +130 -0
  39. package/route-types.js +1 -0
  40. package/route.d.ts +45 -0
  41. package/route.js +113 -0
  42. package/schemas/application.json +19 -3
  43. package/schemas/serve.json +3 -3
  44. package/server/application.d.ts +107 -0
  45. package/server/application.js +108 -0
  46. package/server/backend.d.ts +62 -31
  47. package/server/backend.js +149 -55
  48. package/server/channel-messages.d.ts +54 -0
  49. package/server/channel-messages.js +84 -0
  50. package/server/channel-socket.d.ts +67 -0
  51. package/server/channel-socket.js +322 -0
  52. package/server/definitions.d.ts +270 -294
  53. package/server/definitions.js +35 -115
  54. package/server/dispatch.d.ts +121 -66
  55. package/server/dispatch.js +267 -87
  56. package/server/event-stream.d.ts +63 -0
  57. package/server/event-stream.js +173 -0
  58. package/server/generated.d.ts +3 -1
  59. package/server/generated.js +3 -1
  60. package/server/index.d.ts +6 -3
  61. package/server/index.js +3 -2
  62. package/server/outcomes.d.ts +64 -2
  63. package/server/outcomes.js +85 -4
  64. package/server/read-cookies.d.ts +19 -0
  65. package/server/read-cookies.js +39 -0
  66. package/server/response-effects.d.ts +105 -0
  67. package/server/response-effects.js +78 -0
  68. package/server/stages.d.ts +62 -0
  69. package/server/stages.js +51 -0
  70. package/server/upgrade.d.ts +57 -0
  71. package/server/upgrade.js +116 -0
  72. package/source-text.d.ts +1 -0
  73. package/source-text.js +56 -0
  74. package/stream.d.ts +34 -0
  75. package/stream.js +161 -0
  76. package/tanstack-query/README.md +113 -21
  77. package/tanstack-query/create-queries.d.ts +2 -0
  78. package/tanstack-query/{generated.js → create-queries.js} +13 -11
  79. package/tanstack-query/hydration-window.d.ts +11 -0
  80. package/tanstack-query/hydration-window.js +9 -0
  81. package/tanstack-query/hydration.d.ts +4 -14
  82. package/tanstack-query/hydration.js +9 -12
  83. package/tanstack-query/index.d.ts +1 -1
  84. package/tanstack-query/queries.d.ts +50 -33
  85. package/testing/call-procedure.d.ts +154 -0
  86. package/testing/call-procedure.js +97 -0
  87. package/testing/index.d.ts +2 -0
  88. package/testing/index.js +1 -0
  89. package/generated.js +0 -90
  90. package/generation/context-file.d.ts +0 -2
  91. package/generation/context-file.js +0 -3
  92. package/tanstack-query/generated.d.ts +0 -5
@@ -2,27 +2,7 @@ import type { JsonShape } from "../json.js";
2
2
  import type { FrameworkCode } from "../client.js";
3
3
  import { declaredFailures } from "./errors.js";
4
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
- * Middleware and handlers start from 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;
5
+ import type { ResponseControl } from "./response-effects.js";
26
6
  /**
27
7
  * A {@link https://standardschema.dev | Standard Schema} V1 validator, from any library
28
8
  * or written by hand.
@@ -30,8 +10,8 @@ export type Context = Register extends {
30
10
  * @remarks
31
11
  * Launch uses schemas for procedure inputs and declared error data. Validation may be
32
12
  * asynchronous and may transform the value. For a procedure input, callers pass the
33
- * input type and the procedure's middleware and handler receive the output type; group
34
- * middleware receives no input, and the client's success value is the handler's result,
13
+ * input type and the procedure's middleware and handler receive the output type; a
14
+ * route's `.use()` middleware receives no input, and the client's success value is the handler's result,
35
15
  * not a schema output. For declared error data, the client receives the output type.
36
16
  *
37
17
  * @example
@@ -129,51 +109,6 @@ export type InputOf<S extends Schema> = NonNullable<S["~standard"]["types"]>["in
129
109
  * as for a procedure without input.
130
110
  */
131
111
  export type OutputOf<S> = S extends Schema<unknown, infer Output> ? Output : undefined;
132
- /**
133
- * The application's context factory, created by {@link defineContext}.
134
- *
135
- * @typeParam Value - The factory's return type, possibly a promise.
136
- */
137
- export interface ContextDefinition<Value> {
138
- /**
139
- * Creates the context for one live server request.
140
- *
141
- * @param request - The request bound to the new request scope.
142
- * @returns The context value, or a promise of it.
143
- */
144
- readonly create: (request: Request) => Value;
145
- }
146
- /**
147
- * Defines the application's per-request server context.
148
- *
149
- * @remarks
150
- * Default-export the call itself from exactly one file in your application's sources,
151
- * as `export default defineContext(...)`: generation finds it by that default export and
152
- * registers its awaited return type as {@link Context}. Import `defineContext` by name
153
- * from this entry point and call it without type arguments; a context assigned to a
154
- * variable and exported later, or `defineContext<MyContext>(...)`, fails generation.
155
- * The factory runs once per live server request, for page renders
156
- * and RPC requests alike, and its value is the `context` middleware and handlers start
157
- * from. Keep per-request state in the context rather than in module variables.
158
- *
159
- * @example
160
- * ```ts
161
- * import { defineContext } from "@loozo/angular-launch/server";
162
- * import { sessions } from "./sessions.server";
163
- *
164
- * export default defineContext(async (request: Request) => ({
165
- * user: await sessions.authenticate(request),
166
- * }));
167
- * ```
168
- *
169
- * @typeParam Value - The factory's return type, possibly a promise.
170
- * @param create - Creates the context for one request. A rejection or throw fails that
171
- * request: an RPC request returns `INTERNAL`.
172
- * @returns The context definition to default-export.
173
- */
174
- export declare function defineContext<Value>(create: (request: Request) => Value): ContextDefinition<Value>;
175
- /** The awaited context type of a context created by {@link defineContext}. */
176
- export type ContextOf<Definition> = Definition extends ContextDefinition<infer Value> ? Awaited<Value> : never;
177
112
  type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
178
113
  type StatusNumber<Value> = Value extends `${infer Status extends number}` ? Status : never;
179
114
  /** An HTTP error status from 400 to 599, as an integer literal type. */
@@ -222,235 +157,243 @@ export type ErrorFactories<Definitions extends ErrorDefinitions> = {
222
157
  };
223
158
  type JsonContract<Value> = 0 extends 1 & Value ? never : [Value] extends [JsonShape<Value>] ? unknown : never;
224
159
  type InputContract<Input> = Input extends Schema ? JsonContract<InputOf<Input>> : unknown;
160
+ type MessageContract<Message> = Message extends Schema ? JsonContract<InputOf<Message>> : never;
225
161
  type ErrorContract<Definitions extends ErrorDefinitions> = {
226
162
  readonly [Code in keyof Definitions]: Code extends FrameworkCode | "__proto__" ? never : Definitions[Code]["message"] extends "" ? never : Definitions[Code] & JsonContract<OutputOf<Definitions[Code]["data"]>>;
227
163
  };
228
164
  type JsonResult<Value> = Value extends Promise<infer Result> ? Promise<JsonShape<Result>> : JsonShape<Value>;
229
- /** Whether a procedure reads (`"query"`) or writes (`"mutation"`). */
230
- export type ProcedureKind = "query" | "mutation";
165
+ /**
166
+ * Whether a procedure reads (`"query"`), writes (`"mutation"`), streams values while it
167
+ * runs (`"stream"`) or talks both ways over a websocket (`"channel"`).
168
+ */
169
+ export type ProcedureKind = "query" | "mutation" | "stream" | "channel";
170
+ type StreamResult<Value> = Value extends AsyncIterable<infer Item> ? AsyncIterable<JsonShape<Item>, void> : never;
231
171
  declare const middlewareResult: unique symbol;
232
- type OptionalKeys<Value> = {
233
- [Key in keyof Value]-?: {} extends Pick<Value, Key> ? Key : never;
234
- }[keyof Value];
235
- type IsUnion<Value, Whole = Value> = Value extends unknown ? [Whole] extends [Value] ? false : true : never;
236
- type AdditionRule<Value> = true extends IsUnion<Value> ? never : {
237
- readonly [Key in OptionalKeys<Value>]-?: never;
238
- };
239
172
  /**
240
173
  * What a middleware's `next()` resolves to, and what the middleware must return.
241
174
  *
242
175
  * @remarks
243
- * Opaque: it proves the rest of the call ran, and its type carries what the middleware
244
- * added to the context. There's no other way to create one.
176
+ * Opaque: it proves the rest of the call ran. There's no other way to create one.
177
+ */
178
+ export interface MiddlewareResult {
179
+ /** Type-only brand; absent at runtime. */
180
+ readonly [middlewareResult]: true;
181
+ }
182
+ /**
183
+ * What a route's `.context()` stage receives.
245
184
  *
246
- * Results that add different keys don't combine, so a middleware whose `next(...)` calls
247
- * add different keys is a type error rather than a result that hides some of them.
248
- * Results with the same keys combine only when one's values already include the
249
- * other's, so a value that differs per branch belongs in one `next()` call.
185
+ * @remarks
186
+ * A stage runs at most once per request scope, the first time a call needs it, and returns
187
+ * the whole context the stages, middleware and handlers below it receive: spread `context`
188
+ * to keep its keys. Annotate a standalone stage's argument with this type and the context
189
+ * it receives.
250
190
  *
251
- * @typeParam Added - The values the middleware passed to `next()`.
252
- * @typeParam Keys - The keys of `Added`. Leave it to its default.
191
+ * @example
192
+ * ```ts
193
+ * import { redirect, type StageArgs } from "@loozo/angular-launch/server";
194
+ * import type { Context } from "./routes/route.generated";
195
+ * import { destination as signIn } from "./routes/sign-in/destination.generated";
196
+ *
197
+ * export function signedIn({ context }: StageArgs<Context>) {
198
+ * if (context.user === null) {
199
+ * throw redirect(signIn, {});
200
+ * }
201
+ *
202
+ * return { ...context, user: context.user };
203
+ * }
204
+ * ```
205
+ *
206
+ * @typeParam ContextValue - The context of the stages above this one; `{}` for the first.
253
207
  */
254
- export interface MiddlewareResult<Added, Keys = keyof Added> {
255
- /** Type-only brand; absent at runtime. */
256
- readonly [middlewareResult]: {
257
- /** The added keys, in both directions so that results only combine with the same keys. */
258
- readonly keys: (key: Keys) => Keys;
259
- /** The added values. */
260
- readonly values: Added;
261
- };
208
+ export interface StageArgs<ContextValue> {
209
+ /** The context of the stages above this one, read-only at the top level. */
210
+ readonly context: Readonly<ContextValue>;
211
+ /**
212
+ * The request scope's request: the scope's copy of the RPC HTTP request or of the page
213
+ * request, or, when Angular prerenders a page, a cookie-less `GET` of its URL.
214
+ */
215
+ readonly request: Request;
216
+ /**
217
+ * The cookies and headers of the call that first needed this stage. A stage runs once
218
+ * per scope, so its cookies go out once, with that call's response.
219
+ */
220
+ readonly response: ResponseControl;
221
+ /** The request scope's signal: it aborts when the request does. */
222
+ readonly signal: AbortSignal;
262
223
  }
263
224
  /**
264
225
  * What middleware and handlers receive for one call.
265
226
  *
266
- * @typeParam ContextValue - The context at this point of the call.
267
- * @typeParam Input - The validated input, or `unknown` for group middleware.
227
+ * @typeParam ContextValue - The context of the call: what the route's stages returned.
228
+ * @typeParam Input - The validated input, or `unknown` for a route's `.use()` middleware.
268
229
  */
269
230
  export interface CallArgs<ContextValue, Input> {
270
231
  /**
271
- * The context created for the request, with what earlier middleware added to it.
232
+ * The context the owning route's stages built for the request scope, root first.
272
233
  *
273
234
  * @remarks
274
- * Read-only at the top level: a middleware adds or replaces values through `next()`,
275
- * so later middleware and the handler see their types. Nested objects stay writable.
235
+ * Read-only at the top level. Nested objects stay writable.
276
236
  */
277
237
  readonly context: Readonly<ContextValue>;
278
238
  /**
279
239
  * The validated input: the schema's output, or `undefined` without an input schema.
280
- * Group middleware runs before validation and receives `undefined`.
240
+ * A route's `.use()` middleware runs before validation and receives `undefined`.
281
241
  */
282
242
  readonly input: Input;
283
243
  /**
284
244
  * The live request the call runs in, bound to its request scope: the scope's copy of
285
245
  * the RPC HTTP request, or, during server rendering, the page request given to Angular.
246
+ * When Angular prerenders a page, it's a cookie-less `GET` of the page's URL.
286
247
  */
287
248
  readonly request: Request;
288
249
  /**
289
250
  * Aborts when the caller goes away: over HTTP when the incoming request's signal
290
251
  * aborts, and during server rendering when the page request aborts or `HttpClient`
291
- * unsubscribes before the call settled. Advisory: pass it on to work that accepts one.
252
+ * unsubscribes before the call settled. When Angular prerenders a page, the page
253
+ * request aborts when the render's application is destroyed. Advisory: pass it on to work that accepts one.
292
254
  */
293
255
  readonly signal: AbortSignal;
256
+ /**
257
+ * The call's cookies and headers. Over HTTP they go on the RPC response; during server
258
+ * rendering, cookies go on the page response and headers are dropped. A prerendered page
259
+ * has no response, so a cookie set while Angular prerenders it fails the build, unless
260
+ * it's set after the app is first stable, such as in a `BEFORE_APP_SERIALIZED` hook.
261
+ */
262
+ readonly response: ResponseControl;
294
263
  }
295
264
  /**
296
265
  * What a middleware receives: the call's arguments and `next`.
297
266
  *
298
267
  * @remarks
299
- * Annotate a middleware's argument with this type to declare what it needs: the context
300
- * values earlier middleware must have added, and the input the procedure's schema must
301
- * produce. Without an annotation a middleware needs the registered {@link Context} and
302
- * `unknown` input, so it fits anywhere.
268
+ * Annotate a standalone middleware's argument with this type, or pass `middleware` its
269
+ * type arguments, to declare what it needs: the context the route's stages must have
270
+ * built, and the input the procedure's schema must produce. Without them a middleware
271
+ * needs nothing, so it fits anywhere.
303
272
  *
304
273
  * @example
305
274
  * ```ts
306
- * export const ownTodo = middleware(
307
- * async ({ context, input, next }: MiddlewareArgs<{ user: User; db: Db }, { id: string }>) => {
308
- * const todo = await context.db.todos.findForUser(context.user.id, input.id);
275
+ * export const audit = middleware<{ user: User }>(async ({ context, next }) => {
276
+ * log(context.user.id);
309
277
  *
310
- * if (todo === null) {
311
- * throw forbidden();
312
- * }
313
- *
314
- * return next({ todo });
315
- * },
316
- * );
278
+ * return next();
279
+ * });
317
280
  * ```
318
281
  *
319
- * @typeParam Needs - The context the middleware needs. Defaults to {@link Context}.
282
+ * @typeParam Needs - The context the middleware needs. Defaults to `{}`.
320
283
  * @typeParam Input - The input the middleware needs. Defaults to `unknown`.
321
284
  */
322
- export interface MiddlewareArgs<Needs = Context, Input = unknown> extends CallArgs<Needs, Input> {
285
+ export interface MiddlewareArgs<Needs = {}, Input = unknown> extends CallArgs<Needs, Input> {
323
286
  /**
324
- * Continues the call, optionally with values merged into the context.
287
+ * Continues the call.
325
288
  *
326
289
  * @remarks
327
- * A function property rather than a method, so destructuring it is safe.
290
+ * A function property rather than a method, so destructuring it is safe. Middleware
291
+ * doesn't change the context; a route's `.context()` stage does.
292
+ *
293
+ * @returns The result to return from the middleware. It rejects with whatever the rest
294
+ * of the call threw, including declared errors and outcomes such as `forbidden()`.
328
295
  */
329
- readonly next: {
330
- /**
331
- * Continues the call with the context unchanged.
332
- *
333
- * @returns The result to return from the middleware. It rejects with whatever the
334
- * rest of the call threw, including declared errors and `forbidden()`.
335
- */
336
- (): Promise<MiddlewareResult<{}>>;
337
- /**
338
- * Continues the call with `added` merged into the context by spread, so later
339
- * middleware and the handler see its values and types.
340
- *
341
- * @remarks
342
- * `added` must be a single object type whose properties are all required: a missing
343
- * optional value would leave the earlier one in place, which the context's type can't
344
- * follow, and a union could hide such a key in one of its members. Write a value that
345
- * may be missing as `next({ user: maybeUser })` with a type such as `User | null`, and
346
- * alternatives as a union value: `next({ session: a | b })`.
347
- *
348
- * @param added - The values to add or replace.
349
- * @returns The result to return from the middleware. It rejects with whatever the
350
- * rest of the call threw, including declared errors and `forbidden()`.
351
- */
352
- <Added extends object>(added: Added & AdditionRule<Added>): Promise<MiddlewareResult<Added>>;
353
- };
296
+ readonly next: () => Promise<MiddlewareResult>;
354
297
  }
355
298
  /**
356
299
  * A middleware created by {@link middleware}.
357
300
  *
358
301
  * @typeParam Needs - The context it needs.
359
- * @typeParam Added - The values it adds to the context.
360
302
  * @typeParam Input - The input it needs.
361
303
  */
362
- export interface MiddlewareDefinition<Needs, Added, Input> {
304
+ export interface MiddlewareDefinition<Needs = {}, Input = unknown> {
363
305
  /** Runs the middleware for one call. */
364
- readonly run: (args: MiddlewareArgs<Needs, Input>) => Promise<MiddlewareResult<Added>>;
306
+ readonly run: (args: MiddlewareArgs<Needs, Input>) => Promise<MiddlewareResult>;
365
307
  }
366
308
  type AnyMiddleware = {
367
- readonly run: (args: never) => Promise<{
368
- readonly [middlewareResult]: {
369
- readonly keys: (key: never) => PropertyKey;
370
- readonly values: object;
371
- };
372
- }>;
373
- };
309
+ readonly run: (args: never) => Promise<MiddlewareResult>;
310
+ } | ((args: never) => Promise<MiddlewareResult>);
311
+ type ProcedureMiddleware<ContextValue, Input> = {
312
+ readonly run: (args: never) => Promise<MiddlewareResult>;
313
+ } | MiddlewareDefinition<ContextValue, Input>["run"];
374
314
  /**
375
- * Creates a middleware: code that runs around a procedure call, to refuse it, add typed
376
- * values to its context, or wrap the rest of it.
315
+ * Creates a middleware: code that runs around a procedure call, to refuse it or wrap the
316
+ * rest of it.
377
317
  *
378
318
  * @remarks
379
- * List middleware in `defineRpc`'s `use` to run it for every procedure in the group, or
380
- * in a procedure's `use` to run it for that procedure. A call runs the group's
381
- * middleware with no input, then validates the input, then runs the procedure's
382
- * middleware with the validated input, then the handler. Middleware runs for every
383
- * call, also during server rendering, where `request` is the page request.
319
+ * List middleware in a route's `.use()` to run it for that route's own procedures, or in
320
+ * a procedure's `use` to run it for that procedure. Those lists also take a bare `run`
321
+ * function, typed with the route's context and, on a procedure, the validated input, so use
322
+ * `middleware` for middleware you share. A call runs the owning route's stages,
323
+ * then its `.use()` middleware with no input, then validates the input, then runs the
324
+ * procedure's middleware with the validated input, then the handler. Middleware runs for
325
+ * every call, also during server rendering, where `request` is the page request, and when
326
+ * Angular prerenders a page, where it's a cookie-less `GET` of the page's URL. A route's
327
+ * `.use()` isn't inherited: a child route's procedures don't run it.
384
328
  *
385
329
  * `run` must call `next()` exactly once and return its result: calling it twice or
386
- * returning anything else fails the call with `INTERNAL`. `next(added)` merges `added`
387
- * into the context by spread, so the context must be a plain object. The context is
388
- * read-only at the top level: change it through `next()`. Every `next(...)` in a
389
- * middleware adds the same keys, and a value that differs per branch goes in one
390
- * `next()` call with a union-typed value, such as
391
- * `next({ user: preview ? null : context.user })`: separate `next({ user: null })` and
392
- * `next({ user: context.user })` calls don't infer `User | null` when `context.user` is
393
- * a `User`. `next()` rejects when anything after it throws, so `await next()` in a `try`
394
- * wraps the rest of the call.
395
- *
396
- * Refuse a call with `throw forbidden()`, which fails it with `FORBIDDEN`. Any other
397
- * exception fails it with `INTERNAL` and is logged on the server. Declared errors belong
398
- * to handlers.
330
+ * returning anything else fails the call with `INTERNAL`. `next()` rejects when anything
331
+ * after it throws, so `await next()` in a `try` wraps the rest of the call. Middleware
332
+ * can't add to the context: derive values in a `.context()` stage instead.
333
+ *
334
+ * Refuse a call with `throw forbidden()`, which fails it with `FORBIDDEN`, or answer it
335
+ * with `throw notFound()` or `throw redirect(destination, values)`. Any other exception fails it with
336
+ * `INTERNAL` and is logged on the server. Declared errors belong to handlers.
399
337
  *
400
338
  * @example
401
339
  * ```ts
402
- * import { forbidden, middleware } from "@loozo/angular-launch/server";
340
+ * import { middleware } from "@loozo/angular-launch/server";
403
341
  *
404
- * export const signedIn = middleware(async ({ context, next }) => {
405
- * if (context.user === null) {
406
- * throw forbidden();
407
- * }
342
+ * export const timing = middleware(async ({ next, response }) => {
343
+ * const start = performance.now();
408
344
  *
409
- * return next({ user: context.user });
345
+ * try {
346
+ * return await next();
347
+ * } finally {
348
+ * response.headers.append("server-timing", `rpc;dur=${performance.now() - start}`);
349
+ * }
410
350
  * });
411
351
  * ```
412
352
  *
413
- * @typeParam Needs - The context it needs, from an annotated argument. Defaults to
414
- * {@link Context}.
415
- * @typeParam Added - The values it adds, inferred from what it passes to `next()`.
416
- * @typeParam Input - The input it needs, from an annotated argument. Defaults to
417
- * `unknown`.
353
+ * @typeParam Needs - The context it needs. Defaults to `{}`, also when the call is written
354
+ * inline in `.use()`: pass the keys it reads, as in `middleware<{ user: User }>(…)`, or
355
+ * write a bare function there instead.
356
+ * @typeParam Input - The input it needs. Defaults to `unknown`.
418
357
  * @param run - Runs the middleware for one call.
419
- * @returns The middleware, to list in a `use` array.
358
+ * @returns The middleware, to list in `.use()` or a procedure's `use`.
420
359
  */
421
- export declare function middleware<Needs = Context, Added extends object = {}, Input = unknown>(run: (args: MiddlewareArgs<Needs, Input>) => Promise<MiddlewareResult<Added>>): MiddlewareDefinition<Needs, Added, Input>;
422
- type KeySpellings<Key> = Key extends number ? Key | `${Key}` : Key extends `${infer Numeric extends number}` ? number extends Numeric ? Key : `${Numeric}` extends Key ? Key | Numeric : Key : Key;
423
- type Merge<Base, Added> = [keyof Added] extends [never] ? Base : Base extends unknown ? Omit<Base, KeySpellings<keyof Added>> & Added : never;
424
- type Flat<Value> = {
425
- [Key in keyof Value]: Value[Key];
426
- } & {};
427
- type ContextAfter<Base, Use> = Use extends readonly [infer First, ...infer Rest] ? First extends MiddlewareDefinition<infer _Needs, infer Added, infer _Input> ? ContextAfter<Flat<Merge<Base, Added>>, Rest> : Base : Base;
428
- type CheckChain<Base, Input, Use> = Use extends readonly [infer First, ...infer Rest] ? First extends MiddlewareDefinition<infer Needs, infer Added, infer NeedsInput> ? [
360
+ export declare function middleware<Needs = {}, Input = unknown>(run: (args: MiddlewareArgs<Needs, Input>) => Promise<MiddlewareResult>): MiddlewareDefinition<Needs, Input>;
361
+ type CheckChain<ContextValue, Input, Use> = Use extends readonly [] ? [] : Use extends readonly [infer First, ...infer Rest] ? First extends MiddlewareDefinition<infer Needs, infer NeedsInput> ? [
429
362
  [
430
- Base
431
- ] extends [Needs] ? [Input] extends [NeedsInput] ? true extends IsUnion<Added> ? never : [OptionalKeys<Added>] extends [never] ? First : never : never : never,
432
- ...CheckChain<Flat<Merge<Base, Added>>, Input, Rest>
433
- ] : [never] : [];
363
+ ContextValue
364
+ ] extends [Needs] ? ([Input] extends [NeedsInput] ? First : never) : never,
365
+ ...CheckChain<ContextValue, Input, Rest>
366
+ ] : First extends (args: never) => Promise<MiddlewareResult> ? [First, ...CheckChain<ContextValue, Input, Rest>] : [never] : readonly (MiddlewareDefinition<ContextValue, Input> | MiddlewareDefinition<ContextValue, Input>["run"])[];
434
367
  /**
435
- * A procedure created by a group's `query` or `mutation` builder.
368
+ * A procedure created by a `.remote()` builder's `query`, `mutation`, `stream` or
369
+ * `channel`.
436
370
  *
437
371
  * @remarks
438
- * Procedures are values for `defineRpc`. Their types drive the generated client;
439
- * the server dispatches calls to them. Don't build one by hand.
372
+ * Procedures are values in a route's `.remote()` namespaces. Their types drive the
373
+ * route's client; the server dispatches calls to them. Don't build one by hand.
440
374
  *
441
375
  * @typeParam Input - The input schema, or `undefined` without input.
442
376
  * @typeParam Output - The handler's return type.
443
- * @typeParam Kind - Whether the procedure is a query or a mutation.
377
+ * @typeParam Kind - Whether the procedure is a query, a mutation, a stream or a channel.
444
378
  * @typeParam Errors - The declared errors.
379
+ * @typeParam Message - A channel's message schema; `undefined` for the other kinds.
445
380
  */
446
- export interface Procedure<Input, Output, Kind extends ProcedureKind = "query", Errors extends ErrorDefinitions = {}> {
447
- /** Whether the procedure is a `"query"` or a `"mutation"`. */
381
+ export interface Procedure<Input, Output, Kind extends ProcedureKind = "query", Errors extends ErrorDefinitions = {}, Message = undefined> {
382
+ /** Whether the procedure is a `"query"`, a `"mutation"`, a `"stream"` or a `"channel"`. */
448
383
  readonly kind: Kind;
449
384
  /** The input schema, or `undefined` for a procedure without input. */
450
385
  readonly input: Input;
386
+ /**
387
+ * The schema a channel validates each message from its caller with; `undefined` for the
388
+ * other kinds.
389
+ */
390
+ readonly message: Message;
451
391
  /** The declared errors, as written in the procedure's options. */
452
392
  readonly errors: Errors;
453
- /** The procedure's middleware, in the order it runs. Empty when none was given. */
393
+ /**
394
+ * The procedure's middleware, `middleware()` definitions and bare functions, in the order
395
+ * it runs. Empty when none was given.
396
+ */
454
397
  readonly use: readonly AnyMiddleware[];
455
398
  /**
456
399
  * Runs the authored handler with the procedure's own error factories.
@@ -464,12 +407,12 @@ export interface Procedure<Input, Output, Kind extends ProcedureKind = "query",
464
407
  readonly [declaredFailures]: WeakMap<object, DeclaredFailure>;
465
408
  }
466
409
  /**
467
- * The options a group's `query` and `mutation` builders take.
410
+ * The options the `query` and `mutation` builders take.
468
411
  *
469
412
  * @remarks
470
413
  * Write them inline in the call; generation reads them statically.
471
414
  *
472
- * @typeParam ContextValue - The context after the group's middleware.
415
+ * @typeParam ContextValue - The context the declaring route's stages build.
473
416
  * @typeParam Input - The input schema, or `undefined` without input.
474
417
  * @typeParam Use - The procedure's middleware.
475
418
  * @typeParam Output - The handler's return type.
@@ -479,7 +422,7 @@ export interface ProcedureOptions<ContextValue, Input, Use extends readonly AnyM
479
422
  /** The schema the server validates the input with; omit it for a procedure without input. */
480
423
  readonly input?: Input & InputContract<NoInfer<Input>>;
481
424
  /**
482
- * Middleware that runs in order after the group's middleware and input validation,
425
+ * Middleware that runs in order after the route's `.use()` middleware and input validation,
483
426
  * with the validated input. Each entry must accept the context and input before it.
484
427
  */
485
428
  readonly use?: Use & CheckChain<ContextValue, OutputOf<Input>, NoInfer<Use>>;
@@ -491,32 +434,75 @@ export interface ProcedureOptions<ContextValue, Input, Use extends readonly AnyM
491
434
  * @param args - The call's arguments and the error factories.
492
435
  * @returns The call's result, or a promise of it.
493
436
  */
494
- readonly handler: (args: CallArgs<ContextAfter<ContextValue, Use>, OutputOf<Input>> & {
437
+ readonly handler: (args: CallArgs<ContextValue, OutputOf<Input>> & {
495
438
  /** One factory per declared error code, creating an error to `throw`. */
496
439
  readonly errors: ErrorFactories<Errors>;
497
440
  }) => Output & JsonResult<NoInfer<Output>>;
498
441
  }
499
442
  /**
500
- * The `query` and `mutation` builders `defineRpc` passes to its callback.
443
+ * The options the `stream` builder takes: those of `query`, with a handler that
444
+ * returns an async iterable, usually an `async function*`.
445
+ */
446
+ export interface StreamOptions<ContextValue, Input, Use extends readonly AnyMiddleware[], Output, Errors extends ErrorDefinitions> extends Omit<ProcedureOptions<ContextValue, Input, Use, Output, Errors>, "handler"> {
447
+ /**
448
+ * Runs the stream: each value it yields is sent to the caller as strict JSON, until it
449
+ * returns or throws.
450
+ */
451
+ readonly handler: (args: CallArgs<ContextValue, OutputOf<Input>> & {
452
+ /** One factory per declared error code, creating an error to `throw`. */
453
+ readonly errors: ErrorFactories<Errors>;
454
+ }) => Output & StreamResult<NoInfer<Output>>;
455
+ }
456
+ /**
457
+ * The options the `channel` builder takes: those of `stream`, with a required
458
+ * `message` schema and a handler that also receives the caller's `messages`.
459
+ */
460
+ export interface ChannelOptions<ContextValue, Input, Message, Use extends readonly AnyMiddleware[], Output, Errors extends ErrorDefinitions> extends Omit<ProcedureOptions<ContextValue, Input, Use, Output, Errors>, "handler"> {
461
+ /**
462
+ * The schema the server validates each message from the caller with, when the handler
463
+ * reads it. Its caller input type is what the client's `send` takes.
464
+ */
465
+ readonly message: Message & MessageContract<NoInfer<Message>>;
466
+ /**
467
+ * Runs the channel: each value it yields is sent to the caller as strict JSON, until it
468
+ * returns or throws.
469
+ */
470
+ readonly handler: (args: CallArgs<ContextValue, OutputOf<Input>> & {
471
+ /** One factory per declared error code, creating an error to `throw`. */
472
+ readonly errors: ErrorFactories<Errors>;
473
+ /**
474
+ * The caller's messages, validated with `message` as they're read, in arrival order.
475
+ *
476
+ * @remarks
477
+ * One consumer only: a second iterator throws. Iteration ends when the caller closes
478
+ * the channel. A message that fails validation ends the call with `INVALID_INPUT` and
479
+ * the schema's issues.
480
+ */
481
+ readonly messages: AsyncIterable<OutputOf<Message>>;
482
+ }) => Output & StreamResult<NoInfer<Output>>;
483
+ }
484
+ /**
485
+ * The `query`, `mutation`, `stream` and `channel` builders a route's `.remote()` passes to
486
+ * its callback.
501
487
  *
502
488
  * @remarks
503
489
  * Function properties rather than methods, so destructuring them is safe.
504
490
  *
505
- * @typeParam ContextValue - The context after the group's middleware.
491
+ * @typeParam ContextValue - The context the declaring route's stages build.
506
492
  */
507
493
  export interface ProcedureBuilder<ContextValue> {
508
494
  /**
509
495
  * Defines a procedure that reads data.
510
496
  *
511
497
  * @remarks
512
- * The handler receives `{ context, input, errors, request, signal }`: the context
513
- * after the group's and the procedure's middleware, the validated input (`undefined`
514
- * without an input schema), the error factories for the declared errors, the request
515
- * the call runs in and its abort signal. Inputs and results must be strict JSON; a
498
+ * The handler receives `{ context, input, errors, request, signal, response }`: the
499
+ * context the declaring route's stages built, the validated input
500
+ * (`undefined` without an input schema), the error factories for the declared errors,
501
+ * the request the call runs in, its abort signal and its response cookies and headers. Inputs and results must be strict JSON; a
516
502
  * result that isn't fails the call with `INTERNAL`. Throwing an error created by
517
- * `errors` returns that declared error, and throwing `forbidden()` fails the call with
518
- * `FORBIDDEN`; any other exception fails the call with `INTERNAL` and is logged on the
519
- * server.
503
+ * `errors` returns that declared error, throwing `forbidden()` fails the call with
504
+ * `FORBIDDEN`, and throwing `notFound()` or `redirect()` answers it with that outcome;
505
+ * any other exception fails the call with `INTERNAL` and is logged on the server.
520
506
  *
521
507
  * An explicit `input` schema must have a concrete type, without `undefined`, `null`,
522
508
  * `any` or `unknown` branches, or generation fails: `Schema<string> | undefined` is
@@ -544,7 +530,7 @@ export interface ProcedureBuilder<ContextValue> {
544
530
  * `__proto__` or a framework code, its status isn't an integer from 400 to 599, its
545
531
  * message is empty, or its data isn't a Standard Schema V1.
546
532
  */
547
- readonly query: <Input extends Schema | undefined = undefined, const Use extends readonly AnyMiddleware[] = [], Output = unknown, const Errors extends ErrorDefinitions = {}>(options: ProcedureOptions<ContextValue, Input, Use, Output, Errors>) => Procedure<Input, Output, "query", Errors>;
533
+ readonly query: <Input extends Schema | undefined = undefined, const Use extends readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[] = readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[], Output = unknown, const Errors extends ErrorDefinitions = {}>(options: ProcedureOptions<ContextValue, Input, Use, Output, Errors>) => Procedure<Input, Output, "query", Errors>;
548
534
  /**
549
535
  * Defines a procedure that writes data.
550
536
  *
@@ -552,7 +538,7 @@ export interface ProcedureBuilder<ContextValue> {
552
538
  * Takes the same options as `query`, and its handler receives the same arguments.
553
539
  *
554
540
  * Mutations never use the HTTP transfer cache. During server rendering they fail with
555
- * `FORBIDDEN` before any middleware, validation or the handler runs.
541
+ * `FORBIDDEN` before any stage, middleware, validation or the handler runs.
556
542
  *
557
543
  * @example
558
544
  * ```ts
@@ -571,87 +557,77 @@ export interface ProcedureBuilder<ContextValue> {
571
557
  * @returns The procedure, to use as a value in the callback's result.
572
558
  * @throws TypeError when a declared error is invalid, as for `query`.
573
559
  */
574
- readonly mutation: <Input extends Schema | undefined = undefined, const Use extends readonly AnyMiddleware[] = [], Output = unknown, const Errors extends ErrorDefinitions = {}>(options: ProcedureOptions<ContextValue, Input, Use, Output, Errors>) => Procedure<Input, Output, "mutation", Errors>;
560
+ readonly mutation: <Input extends Schema | undefined = undefined, const Use extends readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[] = readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[], Output = unknown, const Errors extends ErrorDefinitions = {}>(options: ProcedureOptions<ContextValue, Input, Use, Output, Errors>) => Procedure<Input, Output, "mutation", Errors>;
561
+ /**
562
+ * Defines a procedure that sends values while it runs: a stream.
563
+ *
564
+ * @remarks
565
+ * Takes the same options as `query`, except that the handler returns an async iterable,
566
+ * usually written as `handler: async function* ({ context, input, signal }) { … }`. Each
567
+ * value it yields reaches the caller as soon as it's yielded.
568
+ *
569
+ * The stream's response starts once the handler returned its iterable, so cookies must
570
+ * be set before that: in a stage, in middleware before `next()`, or in a handler that
571
+ * isn't a generator. A stage's cookies are set before the iterable starts. Setting one later throws, and later header changes are ignored.
572
+ *
573
+ * @example
574
+ * ```ts
575
+ * watch: stream({
576
+ * input: idSchema,
577
+ * handler: async function* ({ context, input, signal }) {
578
+ * for await (const chat of context.chats.changes(input.id, { signal })) {
579
+ * yield chat;
580
+ * }
581
+ * },
582
+ * }),
583
+ * ```
584
+ */
585
+ readonly stream: <Input extends Schema | undefined = undefined, const Use extends readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[] = readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[], Output extends AsyncIterable<unknown> = AsyncIterable<unknown>, const Errors extends ErrorDefinitions = {}>(options: StreamOptions<ContextValue, Input, Use, Output, Errors>) => Procedure<Input, Output, "stream", Errors>;
586
+ /**
587
+ * Defines a procedure that talks both ways over a websocket: a channel.
588
+ *
589
+ * @remarks
590
+ * Takes a stream's options plus a required `message` schema. The handler is a stream
591
+ * handler that also receives `messages`, the caller's messages validated with `message` as
592
+ * it reads them, written as `handler: async function* ({ context, input, messages }) { … }`.
593
+ * Each value it yields reaches the caller as soon as the caller has room for it; a slow
594
+ * reader pauses the handler at its `yield`, and a handler that stops reading `messages`
595
+ * makes the caller's `send` wait.
596
+ *
597
+ * The call runs over `GET /_rpc/<namespace>/<procedure>?input=…` upgraded to a websocket by
598
+ * the generated `handleUpgrade`, not `handleRequest`. The route's stages, middleware, input
599
+ * validation and the handler run before the upgrade's `101` response, which carries the
600
+ * call's cookies and headers, so cookies follow a stream's rules: set them in a stage, in
601
+ * middleware before `next()` or in a handler that isn't a generator. During server
602
+ * rendering a channel fails with `FORBIDDEN` before any stage or middleware runs.
603
+ *
604
+ * @example
605
+ * ```ts
606
+ * talk: channel({
607
+ * input: chatSchema,
608
+ * message: textSchema,
609
+ * handler: async function* ({ context, input, messages, signal }) {
610
+ * yield { kind: "history", messages: await context.chats.history(input.chatId) };
611
+ *
612
+ * for await (const message of messages) {
613
+ * yield { kind: "answer", text: await context.chats.answer(input.chatId, message.text, signal) };
614
+ * }
615
+ * },
616
+ * }),
617
+ * ```
618
+ */
619
+ readonly channel: <Input extends Schema | undefined = undefined, Message extends Schema = Schema, const Use extends readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[] = readonly ProcedureMiddleware<ContextValue, OutputOf<Input>>[], Output extends AsyncIterable<unknown> = AsyncIterable<unknown>, const Errors extends ErrorDefinitions = {}>(options: ChannelOptions<ContextValue, Input, Message, Use, Output, Errors>) => Procedure<Input, Output, "channel", Errors, Message>;
575
620
  }
621
+ export declare const builder: ProcedureBuilder<never>;
576
622
  /**
577
- * The minimal shape `defineRpc` accepts for each procedure.
623
+ * The minimal shape `.remote()` accepts for each procedure.
578
624
  *
579
625
  * @remarks
580
- * Create procedures with the `query` and `mutation` builders `defineRpc` passes to its
581
- * callback; generation rejects any other value.
626
+ * Create procedures with the builders `.remote()` passes to its callback; generation
627
+ * rejects any other value.
582
628
  */
583
629
  export interface ProcedureDefinition {
584
- /** Whether the procedure is a `"query"` or a `"mutation"`. */
630
+ /** Whether the procedure is a `"query"`, a `"mutation"`, a `"stream"` or a `"channel"`. */
585
631
  readonly kind: ProcedureKind;
586
632
  }
587
- /**
588
- * An RPC group created by {@link defineRpc}.
589
- *
590
- * @typeParam Name - The group's namespace.
591
- * @typeParam Procedures - The group's procedures, keyed by name.
592
- */
593
- export interface Group<Name extends string, Procedures extends Record<string, ProcedureDefinition>> {
594
- /** The namespace the generated client exposes the group under. */
595
- readonly name: Name;
596
- /** The group's procedures, keyed by procedure name. */
597
- readonly procedures: Procedures;
598
- /** The group's middleware, in the order it runs. Empty when none was given. */
599
- readonly use: readonly AnyMiddleware[];
600
- }
601
- /**
602
- * Defines the RPC group for the route declared in the same directory.
603
- *
604
- * @remarks
605
- * Default-export the result from a file next to the route's `route.ts`; one group per
606
- * route. That route must be one that gets generated files: not a redirect, and with a
607
- * page or descendants with pages that aren't all redirects. Generation reads the call
608
- * statically without running it: import `defineRpc` by name from this entry point and
609
- * call it directly without type arguments, with a literal identifier other than
610
- * `__proto__` for the namespace; pass an arrow function whose parameter destructures
611
- * `query` and/or `mutation` without renaming and whose body is a parenthesized object
612
- * literal of procedures, each a direct `query(...)` or `mutation(...)` call with inline
613
- * options; and write the group options inline. Each route's generated `injectRpc()`
614
- * exposes its own group and its ancestors' groups under their namespaces. Each namespace
615
- * must be unique across the app: calls go to `/_rpc/<namespace>/<procedure>`.
616
- *
617
- * The group's `use` middleware runs for every procedure in the group, before input
618
- * validation, and the procedures' handlers and middleware see what it adds to the
619
- * context. It isn't inherited through the route tree.
620
- *
621
- * Exposure isn't authorization: anyone who can reach the server can call any
622
- * procedure, so protect every group and procedure that needs it.
623
- *
624
- * @example
625
- * ```ts
626
- * import { defineRpc } from "@loozo/angular-launch/server";
627
- * import { signedIn } from "../../auth.server";
628
- *
629
- * export default defineRpc(
630
- * "todos",
631
- * ({ query }) => ({
632
- * list: query({
633
- * handler: ({ context }) => context.db.todos.listForUser(context.user.id),
634
- * }),
635
- * }),
636
- * { use: [signedIn] },
637
- * );
638
- * ```
639
- *
640
- * @typeParam Name - The namespace literal.
641
- * @typeParam Use - The group's middleware, written inline.
642
- * @typeParam Procedures - The procedures, keyed by name.
643
- * @param name - The namespace the generated client exposes the group under.
644
- * @param build - Returns the procedures, keyed by name, built with the `query` and
645
- * `mutation` builders it receives.
646
- * @param options - `use`: middleware that runs for every procedure in the group.
647
- * @returns The group, to default-export.
648
- */
649
- export declare function defineRpc<Name extends string, const Use extends readonly AnyMiddleware[] = [], Procedures extends Record<string, ProcedureDefinition> = {}>(name: Name, build: (builder: ProcedureBuilder<ContextAfter<Context, Use>>) => Procedures, { use, }?: {
650
- /**
651
- * Middleware that runs in order for every call to any procedure in the group, before
652
- * input validation and the procedure's own middleware. It receives no input. Each
653
- * entry must accept the context before it.
654
- */
655
- readonly use?: Use & CheckChain<Context, unknown, NoInfer<Use>>;
656
- }): Group<Name, Procedures>;
657
633
  export {};