@replit/river 0.216.1 → 0.217.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +2 -2
  2. package/dist/{adapter-BXCk-dmy.d.ts → adapter-Dl5Mewp3.d.ts} +1 -1
  3. package/dist/{chunk-C4EPHIKQ.js → chunk-JFFRB3SS.js} +48 -26
  4. package/dist/chunk-JFFRB3SS.js.map +1 -0
  5. package/dist/{chunk-62BM2WOT.js → chunk-VK3VJZGG.js} +19 -18
  6. package/dist/chunk-VK3VJZGG.js.map +1 -0
  7. package/dist/chunk-WMPWPIA4.js +72 -0
  8. package/dist/chunk-WMPWPIA4.js.map +1 -0
  9. package/dist/{client-BNc5Pj_4.d.ts → client-YP9bECp8.d.ts} +2 -2
  10. package/dist/codec/index.d.ts +3 -3
  11. package/dist/codec/index.js +2 -2
  12. package/dist/{connection-ou9w2dSY.d.ts → connection-D_HE_YQB.d.ts} +3 -3
  13. package/dist/customSchemas/index.d.ts +34 -0
  14. package/dist/customSchemas/index.js +9 -0
  15. package/dist/customSchemas/index.js.map +1 -0
  16. package/dist/{index-ZWkoesQD.d.ts → index-DgUMnNOi.d.ts} +1 -1
  17. package/dist/logging/index.d.ts +3 -3
  18. package/dist/{message-CpXWqmJw.d.ts → message-DxS8db8A.d.ts} +30 -31
  19. package/dist/protobuf/index.d.ts +11 -15
  20. package/dist/protobuf/index.js +7 -5
  21. package/dist/protobuf/index.js.map +1 -1
  22. package/dist/router/index.d.ts +11 -11
  23. package/dist/router/index.js +1 -1
  24. package/dist/{server-BPu7Td80.d.ts → server-BfM3_JLq.d.ts} +5 -5
  25. package/dist/{services-DpT2yNtt.d.ts → services-CL6k3HMH.d.ts} +8 -9
  26. package/dist/testUtil/index.d.ts +8 -8
  27. package/dist/testUtil/index.js +2 -2
  28. package/dist/testUtil/index.js.map +1 -1
  29. package/dist/transport/impls/ws/client.d.ts +7 -7
  30. package/dist/transport/impls/ws/client.js +2 -2
  31. package/dist/transport/impls/ws/server.d.ts +7 -7
  32. package/dist/transport/impls/ws/server.js +2 -2
  33. package/dist/transport/impls/ws/server.js.map +1 -1
  34. package/dist/transport/index.d.ts +8 -8
  35. package/dist/transport/index.js +2 -2
  36. package/dist/{transport-B1MUtXL7.d.ts → transport-CUpXnch7.d.ts} +4 -4
  37. package/package.json +14 -39
  38. package/dist/adapter-D5X11kmP.d.cts +0 -29
  39. package/dist/chunk-62BM2WOT.js.map +0 -1
  40. package/dist/chunk-C4EPHIKQ.js.map +0 -1
  41. package/dist/client-BZUvFL6B.d.cts +0 -54
  42. package/dist/codec/index.cjs +0 -268
  43. package/dist/codec/index.cjs.map +0 -1
  44. package/dist/codec/index.d.cts +0 -19
  45. package/dist/connection-xxgJHs2o.d.cts +0 -40
  46. package/dist/index-BAGGleT3.d.cts +0 -37
  47. package/dist/logging/index.cjs +0 -55
  48. package/dist/logging/index.cjs.map +0 -1
  49. package/dist/logging/index.d.cts +0 -4
  50. package/dist/message-CpXWqmJw.d.cts +0 -119
  51. package/dist/protobuf/codec.cjs +0 -107
  52. package/dist/protobuf/codec.cjs.map +0 -1
  53. package/dist/protobuf/codec.d.cts +0 -13
  54. package/dist/protobuf/index.cjs +0 -1877
  55. package/dist/protobuf/index.cjs.map +0 -1
  56. package/dist/protobuf/index.d.cts +0 -488
  57. package/dist/router/index.cjs +0 -2043
  58. package/dist/router/index.cjs.map +0 -1
  59. package/dist/router/index.d.cts +0 -80
  60. package/dist/server-JdnoVO11.d.cts +0 -72
  61. package/dist/services-CjigASqe.d.cts +0 -1135
  62. package/dist/testUtil/index.cjs +0 -3051
  63. package/dist/testUtil/index.cjs.map +0 -1
  64. package/dist/testUtil/index.d.cts +0 -122
  65. package/dist/transport/impls/ws/client.cjs +0 -2308
  66. package/dist/transport/impls/ws/client.cjs.map +0 -1
  67. package/dist/transport/impls/ws/client.d.cts +0 -33
  68. package/dist/transport/impls/ws/server.cjs +0 -2179
  69. package/dist/transport/impls/ws/server.cjs.map +0 -1
  70. package/dist/transport/impls/ws/server.d.cts +0 -21
  71. package/dist/transport/index.cjs +0 -2727
  72. package/dist/transport/index.cjs.map +0 -1
  73. package/dist/transport/index.d.cts +0 -11
  74. package/dist/transport-BnU3Zb0Q.d.cts +0 -590
  75. package/dist/types-BGGvYIJM.d.cts +0 -20
  76. package/dist/wslike-Dng9H1C7.d.cts +0 -40
@@ -1,1135 +0,0 @@
1
- import * as _sinclair_typebox from '@sinclair/typebox';
2
- import { TObject, TLiteral, TEnum, TString, TSchema, TNever, TUnion, Static } from '@sinclair/typebox';
3
- import { Span } from '@opentelemetry/api';
4
- import { T as TransportClientId } from './message-CpXWqmJw.cjs';
5
- import { C as Connection, n as ClientHandshakeOptions, z as SessionId } from './transport-BnU3Zb0Q.cjs';
6
- import { C as ClientTransport } from './client-BZUvFL6B.cjs';
7
-
8
- declare const ReadableBrokenError: {
9
- readonly code: "READABLE_BROKEN";
10
- readonly message: "Readable was broken before it is fully consumed";
11
- };
12
- /**
13
- * Similar to {@link Result} but with an extra error to handle cases where {@link Readable.break} is called
14
- */
15
- type ReadableResult<T, E extends ErrorPayload = ErrorPayload> = Result<T, E | typeof ReadableBrokenError>;
16
- /**
17
- * A simple {@link AsyncIterator} used in {@link Readable}
18
- * that doesn't have a the extra "return" and "throw" methods, and
19
- * the doesn't have a "done value" (TReturn).
20
- */
21
- interface ReadableIterator<T, E extends ErrorPayload> extends AsyncIterator<ReadableResult<T, E>> {
22
- next(): Promise<{
23
- done: false;
24
- value: ReadableResult<T, E>;
25
- } | {
26
- done: true;
27
- value: undefined;
28
- }>;
29
- }
30
- /**
31
- * A {@link Readable} is an abstraction from which data is consumed from {@link Writable} source.
32
- *
33
- * - On the server the argument passed the procedure handler for `upload` and `stream` implements a {@link Readable} interface
34
- * so you can read client's request data.
35
- * - On the client the returned value of `subscription` or `stream` invocation implements a {@link Readable} interface
36
- * so you can read server's response data.
37
- *
38
- * A {@link Readable} can only have one consumer (iterator or {@link collect}) for the {@link Readable}'s
39
- * lifetime, in essense, reading from a {@link Readable} locks it forever.
40
- */
41
- interface Readable<T, E extends ErrorPayload> {
42
- /**
43
- * {@link Readable} implements AsyncIterator API and can be consumed via
44
- * for-await-of loops. Iteration locks the Readable. Exiting the loop
45
- * will **not** release the lock and it'll be equivalent of calling
46
- * {@link break}.
47
- */
48
- [Symbol.asyncIterator](): ReadableIterator<T, E>;
49
- /**
50
- * {@link collect} locks the {@link Readable} and returns a promise that resolves
51
- * with an array of the content when the {@link Readable} is fully done. This could
52
- * be due to the {@link Writable} end of the pipe closing cleanly, the procedure invocation
53
- * is cancelled, or {@link break} is called.
54
- */
55
- collect(): Promise<Array<ReadableResult<T, E>>>;
56
- /**
57
- * {@link break} locks the {@link Readable} and discards any existing or future incoming data.
58
- *
59
- * If there is an existing reader waiting for the next value, {@link break} causes it to
60
- * resolve with a {@link ReadableBrokenError} error.
61
- */
62
- break(): undefined;
63
- /**
64
- * {@link isReadable} returns true if it's safe to read from the {@link Readable}, either
65
- * via iteration or {@link collect}. It returns false if the {@link Readable} is locked
66
- * by a consumer (iterator or {@link collect}) or readable was broken via {@link break}.
67
- */
68
- isReadable(): boolean;
69
- }
70
- /**
71
- * A {@link Writeable} is a an abstraction for a {@link Readable} destination to which data is written to.
72
- *
73
- * - On the server the argument passed the procedure handler for `subscription` and `stream` implements a {@link Writeable}
74
- * so you can write server's response data.
75
- * - On the client the returned value of `upload` or `stream` invocation implements a {@link Writeable}
76
- * so you can write client's request data.
77
- *
78
- * Once closed, a {@link Writeable} can't be re-opened.` `
79
- */
80
- interface Writable<T> {
81
- /**
82
- * {@link write} writes a value to the pipe. An error is thrown if writing to a closed {@link Writable}.
83
- */
84
- write(value: T): undefined;
85
- /**
86
- * {@link close} signals the closure of the {@link Writeable}, informing the {@link Readable} end that
87
- * all data has been transmitted and we've cleanly closed.
88
- * Optionally a final value can be passed to {@link close}, which will be the last value
89
- * to write before it closes.
90
- *
91
- * Calling {@link close} multiple times is a no-op.
92
- */
93
- close(value?: T): undefined;
94
- /**
95
- * {@link isWritable} returns true if it's safe to call {@link write}, which
96
- * means that the {@link Writable} hasn't been closed due to {@link close} being called
97
- * on this {@link Writable} or the procedure invocation ending for any reason.
98
- */
99
- isWritable(): boolean;
100
- }
101
- /**
102
- * Internal implementation of a {@link Readable}.
103
- * This should generally not be constructed directly by consumers
104
- * of river, but rather through either the client or procedure handlers.
105
- *
106
- * There are rare cases where this is useful to construct in tests or
107
- * to 'tee' a {@link Readable} to create a copy of the stream but
108
- * this is not the common case.
109
- */
110
- declare class ReadableImpl<T, E extends ErrorPayload> implements Readable<T, E> {
111
- /**
112
- * Whether the {@link Readable} is closed.
113
- *
114
- * Closed {@link Readable}s are done receiving values, but that doesn't affect
115
- * any other aspect of the {@link Readable} such as it's consumability.
116
- */
117
- private closed;
118
- /**
119
- * Whether the {@link Readable} is locked.
120
- *
121
- * @see {@link Readable}'s typedoc to understand locking
122
- */
123
- private locked;
124
- /**
125
- * Whether {@link break} was called.
126
- *
127
- * @see {@link break} for more information
128
- */
129
- private broken;
130
- /**
131
- * This flag allows us to avoid emitting a {@link ReadableBrokenError} after {@link break} was called
132
- * in cases where the {@link queue} is fully consumed and {@link ReadableImpl} is {@link closed}. This is just an
133
- * ergonomic feature to avoid emitting an error in our iteration when we don't have to.
134
- */
135
- private brokenWithValuesLeftToRead;
136
- /**
137
- * A list of values that have been pushed to the {@link ReadableImpl} but not yet emitted to the user.
138
- */
139
- private queue;
140
- /**
141
- * Used by methods in the class to signal to the iterator that it
142
- * should check for the next value.
143
- */
144
- private next;
145
- /**
146
- * Consumes the {@link Readable} and returns an {@link AsyncIterator} that can be used
147
- * to iterate over the values in the {@link Readable}.
148
- */
149
- [Symbol.asyncIterator](): ReadableIterator<T, E>;
150
- /**
151
- * Collects all the values from the {@link Readable} into an array.
152
- *
153
- * @see {@link Readable}'s typedoc for more information
154
- */
155
- collect(): Promise<Array<ReadableResult<T, E>>>;
156
- /**
157
- * Breaks the {@link Readable} and signals an error to any iterators waiting for the next value.
158
- *
159
- * @see {@link Readable}'s typedoc for more information
160
- */
161
- break(): undefined;
162
- /**
163
- * Whether the {@link Readable} is readable.
164
- *
165
- * @see {@link Readable}'s typedoc for more information
166
- */
167
- isReadable(): boolean;
168
- /**
169
- * Pushes a value to be read.
170
- */
171
- _pushValue(value: Result<T, E>): undefined;
172
- /**
173
- * Triggers the close of the {@link Readable}. Make sure to push all remaining
174
- * values before calling this method.
175
- */
176
- _triggerClose(): undefined;
177
- /**
178
- * @internal meant for use within river, not exposed as a public API
179
- */
180
- _hasValuesInQueue(): boolean;
181
- /**
182
- * Whether the {@link Readable} is closed.
183
- */
184
- isClosed(): boolean;
185
- }
186
-
187
- interface CallOptions {
188
- signal?: AbortSignal;
189
- }
190
- type RpcFn<Service extends AnyService, ProcName extends keyof Service['procedures']> = (reqInit: ProcInit<Service, ProcName>, options?: CallOptions) => Promise<Result<ProcResponse<Service, ProcName>, ProcErrors<Service, ProcName>>>;
191
- type UploadFn<Service extends AnyService, ProcName extends keyof Service['procedures']> = (reqInit: ProcInit<Service, ProcName>, options?: CallOptions) => {
192
- reqWritable: Writable<ProcRequest<Service, ProcName>>;
193
- finalize: () => Promise<Result<ProcResponse<Service, ProcName>, ProcErrors<Service, ProcName>>>;
194
- };
195
- type StreamFn<Service extends AnyService, ProcName extends keyof Service['procedures']> = (reqInit: ProcInit<Service, ProcName>, options?: CallOptions) => {
196
- reqWritable: Writable<ProcRequest<Service, ProcName>>;
197
- resReadable: Readable<ProcResponse<Service, ProcName>, ProcErrors<Service, ProcName>>;
198
- };
199
- type SubscriptionFn<Service extends AnyService, ProcName extends keyof Service['procedures']> = (reqInit: ProcInit<Service, ProcName>, options?: CallOptions) => {
200
- resReadable: Readable<ProcResponse<Service, ProcName>, ProcErrors<Service, ProcName>>;
201
- };
202
- /**
203
- * A helper type to transform an actual service type into a type
204
- * we can case to in the proxy.
205
- * @template Service - The type of the Service.
206
- */
207
- type ServiceClient<Service extends AnyService> = {
208
- [ProcName in keyof Service['procedures']]: ProcType<Service, ProcName> extends 'rpc' ? {
209
- rpc: RpcFn<Service, ProcName>;
210
- } : ProcType<Service, ProcName> extends 'upload' ? {
211
- upload: UploadFn<Service, ProcName>;
212
- } : ProcType<Service, ProcName> extends 'stream' ? {
213
- stream: StreamFn<Service, ProcName>;
214
- } : ProcType<Service, ProcName> extends 'subscription' ? {
215
- subscribe: SubscriptionFn<Service, ProcName>;
216
- } : never;
217
- };
218
- /**
219
- * Defines a type that represents a client for a server with a set of services.
220
- * @template Srv - The type of the server.
221
- */
222
- type Client<Services extends AnyServiceSchemaMap<any>, IS extends InstantiatedServiceSchemaMap<any, any, Services> = InstantiatedServiceSchemaMap<any, any, Services>> = {
223
- [SvcName in keyof IS]: ServiceClient<IS[SvcName]>;
224
- };
225
- interface ClientOptions {
226
- connectOnInvoke: boolean;
227
- eagerlyConnect: boolean;
228
- /**
229
- * Default options merged into every leaf call (`rpc`, `stream`,
230
- * `upload`, `subscribe`). Caller-supplied `options` win field-by-field,
231
- * so a caller can override `signal` while keeping other defaults.
232
- *
233
- * Pass a function form when the default needs to be re-resolved per
234
- * call (e.g. an ambient signal that changes between invocations of
235
- * the same client).
236
- */
237
- defaultCallOptions?: CallOptions | (() => CallOptions);
238
- }
239
- /**
240
- * Creates a client for a given server using the provided transport.
241
- * Note that the client only needs the type of the server, not the actual
242
- * server definition itself.
243
- *
244
- * This relies on a proxy to dynamically create the client, so the client
245
- * will be typed as if it were the actual server with the appropriate services
246
- * and procedures.
247
- *
248
- * @template Srv - The type of the server.
249
- * @param {Transport} transport - The transport to use for communication.
250
- * @param {TransportClientId} serverId - The ID of the server to connect to.
251
- * @param {Partial<ClientOptions>} providedClientOptions - The options for the client.
252
- * @returns The client for the server.
253
- */
254
- declare function createClient<ServiceSchemaMap extends AnyServiceSchemaMap<any>>(transport: ClientTransport<Connection>, serverId: TransportClientId, providedClientOptions?: Partial<ClientOptions & {
255
- handshakeOptions: ClientHandshakeOptions;
256
- }>): Client<ServiceSchemaMap>;
257
-
258
- /**
259
- * {@link UNCAUGHT_ERROR_CODE} is the code that is used when an error is thrown
260
- * inside a procedure handler that's not required.
261
- */
262
- declare const UNCAUGHT_ERROR_CODE = "UNCAUGHT_ERROR";
263
- /**
264
- * {@link UNEXPECTED_DISCONNECT_CODE} is the code used the stream's session
265
- * disconnect unexpetedly.
266
- */
267
- declare const UNEXPECTED_DISCONNECT_CODE = "UNEXPECTED_DISCONNECT";
268
- /**
269
- * {@link INVALID_REQUEST_CODE} is the code used when a client's request is invalid.
270
- */
271
- declare const INVALID_REQUEST_CODE = "INVALID_REQUEST";
272
- /**
273
- * {@link CANCEL_CODE} is the code used when either server or client cancels the stream.
274
- */
275
- declare const CANCEL_CODE = "CANCEL";
276
- type TLiteralString = TLiteral<string>;
277
- type TEnumString = TEnum<Record<string, string>>;
278
- type BaseErrorSchemaType = TObject<{
279
- code: TLiteralString | TEnumString;
280
- message: TLiteralString | TString;
281
- }> | TObject<{
282
- code: TLiteralString | TEnumString;
283
- message: TLiteralString | TString;
284
- extras: TSchema;
285
- }>;
286
- /**
287
- * A schema for cancel payloads sent from the client
288
- */
289
- declare const CancelErrorSchema: TObject<{
290
- code: TLiteral<"CANCEL">;
291
- message: TString;
292
- }>;
293
- /**
294
- * {@link ReaderErrorSchema} is the schema for all the built-in river errors that
295
- * can be emitted to a reader (request reader on the server, and response reader
296
- * on the client).
297
- */
298
- declare const ReaderErrorSchema: TUnion<[TObject<{
299
- code: TLiteral<"UNCAUGHT_ERROR">;
300
- message: TString;
301
- }>, TObject<{
302
- code: TLiteral<"UNEXPECTED_DISCONNECT">;
303
- message: TString;
304
- }>, TObject<{
305
- code: TLiteral<"INVALID_REQUEST">;
306
- message: TString;
307
- extras: _sinclair_typebox.TOptional<TObject<{
308
- firstValidationErrors: _sinclair_typebox.TArray<TObject<{
309
- path: TString;
310
- message: TString;
311
- }>>;
312
- totalErrors: _sinclair_typebox.TNumber;
313
- }>>;
314
- }>, TObject<{
315
- code: TLiteral<"CANCEL">;
316
- message: TString;
317
- }>]>;
318
- /**
319
- * Represents an acceptable schema to pass to a procedure.
320
- * Just a type of a schema, not an actual schema.
321
- *
322
- */
323
- type ProcedureErrorSchemaType = TNever | BaseErrorSchemaType | TUnion<Array<BaseErrorSchemaType>>;
324
- type NestableProcedureErrorSchemaType = BaseErrorSchemaType | TUnion<NestableProcedureErrorSchemaTypeArray>;
325
- interface NestableProcedureErrorSchemaTypeArray extends Array<NestableProcedureErrorSchemaType> {
326
- }
327
- type Flatten<T> = T extends BaseErrorSchemaType ? T : T extends TUnion<Array<infer U extends TSchema>> ? Flatten<U> : unknown;
328
- /**
329
- * In the case where API consumers for some god-forsaken reason want to use
330
- * arbitrarily nested unions, this helper flattens them to a single level.
331
- *
332
- * Note that loses some metadata information on the nested unions like
333
- * nested description fields, etc.
334
- *
335
- * @param errType - An arbitrarily union-nested error schema.
336
- * @returns The flattened error schema.
337
- */
338
- declare function flattenErrorType<T extends NestableProcedureErrorSchemaType>(errType: T): Flatten<T>;
339
-
340
- /**
341
- * The minimum error shape supported by river's `Result` and stream primitives.
342
- *
343
- * The existing TypeBox router uses schema-derived object types for this, while
344
- * the protobuf router can use a richer structural error type.
345
- */
346
- interface ErrorPayload {
347
- code: string;
348
- message: string;
349
- extras?: unknown;
350
- }
351
- interface OkResult<T> {
352
- ok: true;
353
- payload: T;
354
- }
355
- interface ErrResult<Err extends ErrorPayload> {
356
- ok: false;
357
- payload: Err;
358
- }
359
- type Result<T, Err extends ErrorPayload> = OkResult<T> | ErrResult<Err>;
360
- declare function Ok<const T extends Array<unknown>>(p: T): OkResult<T>;
361
- declare function Ok<const T extends ReadonlyArray<unknown>>(p: T): OkResult<T>;
362
- declare function Ok<const T>(payload: T): OkResult<T>;
363
- declare function Err<const Err extends ErrorPayload>(error: Err): ErrResult<Err>;
364
- /**
365
- * Refine a {@link Result} type to its returned payload.
366
- */
367
- type ResultUnwrapOk<R> = R extends Result<infer T, infer __E> ? T : never;
368
- /**
369
- * Refine a {@link Result} type to its error payload.
370
- */
371
- type ResultUnwrapErr<R> = R extends Result<infer __T, infer Err> ? Err : never;
372
- /**
373
- * Retrieve the response type for a procedure, represented as a {@link Result}
374
- * type.
375
- * Example:
376
- * ```
377
- * type Message = ResponseData<typeof client, 'serviceName', 'procedureName'>
378
- * ```
379
- */
380
- type ResponseData<RiverClient, ServiceName extends keyof RiverClient, ProcedureName extends keyof RiverClient[ServiceName], Procedure = RiverClient[ServiceName][ProcedureName], Fn extends (...args: never) => unknown = (...args: never) => unknown> = RiverClient extends Client<infer __ServiceSchemaMap> ? Procedure extends object ? Procedure extends object & {
381
- rpc: infer RpcFn extends Fn;
382
- } ? Awaited<ReturnType<RpcFn>> : Procedure extends object & {
383
- upload: infer UploadFn extends Fn;
384
- } ? ReturnType<UploadFn> extends {
385
- finalize: (...args: never) => Promise<infer UploadOutputMessage>;
386
- } ? UploadOutputMessage : never : Procedure extends object & {
387
- stream: infer StreamFn extends Fn;
388
- } ? ReturnType<StreamFn> extends {
389
- resReadable: Readable<infer StreamOutputMessage, Static<BaseErrorSchemaType>>;
390
- } ? StreamOutputMessage : never : Procedure extends object & {
391
- subscribe: infer SubscriptionFn extends Fn;
392
- } ? Awaited<ReturnType<SubscriptionFn>> extends {
393
- resReadable: Readable<infer SubscriptionOutputMessage, Static<BaseErrorSchemaType>>;
394
- } ? SubscriptionOutputMessage : never : never : never : never;
395
-
396
- /**
397
- * This is passed to every procedure handler and contains various context-level
398
- * information and utilities.
399
- */
400
- type ProcedureHandlerContext<State, Context, ParsedMetadata> = Context & {
401
- /**
402
- * State for this service as defined by the service definition.
403
- */
404
- state: State;
405
- /**
406
- * The span for this procedure call. You can use this to add attributes, events, and
407
- * links to the span.
408
- */
409
- span: Span;
410
- /**
411
- * Metadata parsed on the server. See {@link createServerHandshakeOptions}
412
- */
413
- metadata: ParsedMetadata;
414
- /**
415
- * The ID of the session that sent this request.
416
- */
417
- sessionId: SessionId;
418
- /**
419
- * The ID of the client that sent this request. There may be multiple sessions per client.
420
- */
421
- from: TransportClientId;
422
- /**
423
- * This is used to cancel the procedure call from the handler and notify the client that the
424
- * call was cancelled.
425
- *
426
- * Cancelling is not the same as closing procedure calls gracefully, please refer to
427
- * the river documentation to understand the difference between the two concepts.
428
- */
429
- cancel: (message?: string) => ErrResult<Static<typeof CancelErrorSchema>>;
430
- /**
431
- * Register a cleanup function that will run after the procedure handler
432
- * completes (whether it returns normally, throws, or is cancelled).
433
- * Cleanup functions run in reverse registration order (LIFO) and each
434
- * cleanup is awaited before the next one starts.
435
- *
436
- * Prefer this over registering async cleanup work on `signal`'s 'abort'
437
- * event. Abort signal callbacks fire synchronously and do not await async
438
- * work, so multiple async callbacks will interlace their execution
439
- * (coroutine-like behavior) rather than running sequentially to completion.
440
- * `deferCleanup` guarantees each cleanup finishes before the next begins.
441
- *
442
- * If a cleanup function throws, the error is recorded on the cleanup span
443
- * but remaining cleanups continue to run.
444
- */
445
- deferCleanup: (fn: () => void | Promise<void>) => void;
446
- /**
447
- * This signal is a standard [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
448
- * triggered when the procedure invocation is done. This signal tracks the invocation/request finishing
449
- * for _any_ reason, for example:
450
- * - client explicit cancellation
451
- * - procedure handler explicit cancellation via {@link cancel}
452
- * - client session disconnect
453
- * - server cancellation due to client invalid payload
454
- * - invocation finishes cleanly, this depends on the type of the procedure (i.e. rpc handler return, or in a stream after the client-side has closed the request writable and the server-side has closed the response writable)
455
- *
456
- * You can use this to pass it on to asynchronous operations (such as fetch).
457
- *
458
- * You may also want to explicitly register callbacks on the
459
- * ['abort' event](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/abort_event)
460
- * as a way to cleanup after the request is finished.
461
- *
462
- * Note that (per standard AbortSignals) callbacks registered _after_ the procedure invocation
463
- * is done are not triggered. In such cases, you can check the "aborted" property and cleanup
464
- * immediately if needed.
465
- */
466
- signal: AbortSignal;
467
- };
468
-
469
- /**
470
- * Brands a type to prevent it from being directly constructed.
471
- */
472
- type Branded<T> = T & {
473
- readonly __BRAND_DO_NOT_USE: unique symbol;
474
- };
475
- /**
476
- * Unbrands a {@link Branded} type.
477
- */
478
- type Unbranded<T> = T extends Branded<infer U> ? U : never;
479
- /**
480
- * The valid {@link Procedure} types. The `stream` and `upload` types can optionally have a
481
- * different type for the very first initialization message. The suffixless types correspond to
482
- * gRPC's four combinations of stream / non-stream in each direction.
483
- */
484
- type ValidProcType = 'rpc' | 'upload' | 'subscription' | 'stream';
485
- /**
486
- * Represents the payload type for {@link Procedure}s.
487
- */
488
- type PayloadType = TSchema;
489
- type Cancellable<T> = T | Static<typeof CancelErrorSchema>;
490
- /**
491
- * Procedure for a single message in both directions (1:1).
492
- *
493
- * @template State - The context state object.
494
- * @template RequestInit - The TypeBox schema of the initialization object.
495
- * @template ResponseData - The TypeBox schema of the response object.
496
- * @template ResponseErr - The TypeBox schema of the error object.
497
- */
498
- interface RpcProcedure<Context, State, ParsedMetadata, RequestInit extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType> {
499
- type: 'rpc';
500
- requestInit: RequestInit;
501
- responseData: ResponseData;
502
- responseError: ResponseErr;
503
- description?: string;
504
- handler(param: {
505
- ctx: ProcedureHandlerContext<State, Context, ParsedMetadata>;
506
- reqInit: Static<RequestInit>;
507
- }): Promise<Result<Static<ResponseData>, Cancellable<Static<ResponseErr>>>>;
508
- }
509
- /**
510
- * Procedure for a client-stream (potentially preceded by an initialization message),
511
- * single message from server (n:1).
512
- *
513
- * @template State - The context state object.
514
- * @template RequestInit - The TypeBox schema of the initialization object.
515
- * @template RequestData - The TypeBox schema of the request object.
516
- * @template ResponseData - The TypeBox schema of the response object.
517
- * @template ResponseErr - The TypeBox schema of the error object.
518
- */
519
- interface UploadProcedure<Context, State, ParsedMetadata, RequestInit extends PayloadType, RequestData extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType> {
520
- type: 'upload';
521
- requestInit: RequestInit;
522
- requestData: RequestData;
523
- responseData: ResponseData;
524
- responseError: ResponseErr;
525
- description?: string;
526
- handler(param: {
527
- ctx: ProcedureHandlerContext<State, Context, ParsedMetadata>;
528
- reqInit: Static<RequestInit>;
529
- reqReadable: Readable<Static<RequestData>, Static<typeof ReaderErrorSchema>>;
530
- }): Promise<Result<Static<ResponseData>, Cancellable<Static<ResponseErr>>>>;
531
- }
532
- /**
533
- * Procedure for a single message from client, stream from server (1:n).
534
- *
535
- * @template State - The context state object.
536
- * @template RequestInit - The TypeBox schema of the initialization object.
537
- * @template ResponseData - The TypeBox schema of the response object.
538
- * @template ResponseErr - The TypeBox schema of the error object.
539
- */
540
- interface SubscriptionProcedure<Context, State, ParsedMetadata, RequestInit extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType> {
541
- type: 'subscription';
542
- requestInit: RequestInit;
543
- responseData: ResponseData;
544
- responseError: ResponseErr;
545
- description?: string;
546
- handler(param: {
547
- ctx: ProcedureHandlerContext<State, Context, ParsedMetadata>;
548
- reqInit: Static<RequestInit>;
549
- resWritable: Writable<Result<Static<ResponseData>, Cancellable<Static<ResponseErr>>>>;
550
- }): Promise<void | undefined>;
551
- }
552
- /**
553
- * Procedure for a bidirectional stream (potentially preceded by an initialization message),
554
- * (n:n).
555
- *
556
- * @template State - The context state object.
557
- * @template RequestInit - The TypeBox schema of the initialization object.
558
- * @template RequestData - The TypeBox schema of the request object.
559
- * @template ResponseData - The TypeBox schema of the response object.
560
- * @template ResponseErr - The TypeBox schema of the error object.
561
- */
562
- interface StreamProcedure<Context, State, ParsedMetadata, RequestInit extends PayloadType, RequestData extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType> {
563
- type: 'stream';
564
- requestInit: RequestInit;
565
- requestData: RequestData;
566
- responseData: ResponseData;
567
- responseError: ResponseErr;
568
- description?: string;
569
- handler(param: {
570
- ctx: ProcedureHandlerContext<State, Context, ParsedMetadata>;
571
- reqInit: Static<RequestInit>;
572
- reqReadable: Readable<Static<RequestData>, Static<typeof ReaderErrorSchema>>;
573
- resWritable: Writable<Result<Static<ResponseData>, Cancellable<Static<ResponseErr>>>>;
574
- }): Promise<void | undefined>;
575
- }
576
- /**
577
- * Represents any {@link Procedure} type.
578
- *
579
- * @template State - The context state object. You can provide this to constrain
580
- * the type of procedures.
581
- */
582
- type AnyProcedure<Context = object, State = object, ParsedMetadata = object> = Procedure<Context, State, ParsedMetadata, ValidProcType, PayloadType, PayloadType | null, PayloadType, ProcedureErrorSchemaType>;
583
- /**
584
- * Represents a map of {@link Procedure}s.
585
- *
586
- * @template State - The context state object. You can provide this to constrain
587
- * the type of procedures.
588
- */
589
- type ProcedureMap<Context = object, State = object, ParsedMetadata = object> = Record<string, AnyProcedure<Context, State, ParsedMetadata>>;
590
- /**
591
- * Creates an {@link RpcProcedure}.
592
- */
593
- declare function rpc<Context, State, ParsedMetadata, RequestInit extends PayloadType, ResponseData extends PayloadType>(def: {
594
- requestInit: RequestInit;
595
- responseData: ResponseData;
596
- responseError?: never;
597
- description?: string;
598
- handler: RpcProcedure<Context, State, ParsedMetadata, RequestInit, ResponseData, TNever>['handler'];
599
- }): Branded<RpcProcedure<Context, State, ParsedMetadata, RequestInit, ResponseData, TNever>>;
600
- declare function rpc<Context, State, ParsedMetadata, RequestInit extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType>(def: {
601
- requestInit: RequestInit;
602
- responseData: ResponseData;
603
- responseError: ResponseErr;
604
- description?: string;
605
- handler: RpcProcedure<Context, State, ParsedMetadata, RequestInit, ResponseData, ResponseErr>['handler'];
606
- }): Branded<RpcProcedure<Context, State, ParsedMetadata, RequestInit, ResponseData, ResponseErr>>;
607
- /**
608
- * Creates an {@link UploadProcedure}, optionally with an initialization message.
609
- */
610
- declare function upload<Context, State, ParsedMetadata, RequestInit extends PayloadType, RequestData extends PayloadType, ResponseData extends PayloadType>(def: {
611
- requestInit: RequestInit;
612
- requestData: RequestData;
613
- responseData: ResponseData;
614
- responseError?: never;
615
- description?: string;
616
- handler: UploadProcedure<Context, State, ParsedMetadata, RequestInit, RequestData, ResponseData, TNever>['handler'];
617
- }): Branded<UploadProcedure<Context, State, ParsedMetadata, RequestInit, RequestData, ResponseData, TNever>>;
618
- declare function upload<Context, State, ParsedMetadata, RequestInit extends PayloadType, RequestData extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType>(def: {
619
- requestInit: RequestInit;
620
- requestData: RequestData;
621
- responseData: ResponseData;
622
- responseError: ResponseErr;
623
- description?: string;
624
- handler: UploadProcedure<Context, State, ParsedMetadata, RequestInit, RequestData, ResponseData, ResponseErr>['handler'];
625
- }): Branded<UploadProcedure<Context, State, ParsedMetadata, RequestInit, RequestData, ResponseData, ResponseErr>>;
626
- /**
627
- * Creates a {@link SubscriptionProcedure}.
628
- */
629
- declare function subscription<Context, State, ParsedMetadata, RequestInit extends PayloadType, ResponseData extends PayloadType>(def: {
630
- requestInit: RequestInit;
631
- responseData: ResponseData;
632
- responseError?: never;
633
- description?: string;
634
- handler: SubscriptionProcedure<Context, State, ParsedMetadata, RequestInit, ResponseData, TNever>['handler'];
635
- }): Branded<SubscriptionProcedure<Context, State, ParsedMetadata, RequestInit, ResponseData, TNever>>;
636
- declare function subscription<Context, State, ParsedMetadata, RequestInit extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType>(def: {
637
- requestInit: RequestInit;
638
- responseData: ResponseData;
639
- responseError: ResponseErr;
640
- description?: string;
641
- handler: SubscriptionProcedure<Context, State, ParsedMetadata, RequestInit, ResponseData, ResponseErr>['handler'];
642
- }): Branded<SubscriptionProcedure<Context, State, ParsedMetadata, RequestInit, ResponseData, ResponseErr>>;
643
- /**
644
- * Creates a {@link StreamProcedure}, optionally with an initialization message.
645
- */
646
- declare function stream<Context, State, ParsedMetadata, RequestInit extends PayloadType, RequestData extends PayloadType, ResponseData extends PayloadType>(def: {
647
- requestInit: RequestInit;
648
- requestData: RequestData;
649
- responseData: ResponseData;
650
- responseError?: never;
651
- description?: string;
652
- handler: StreamProcedure<Context, State, ParsedMetadata, RequestInit, RequestData, ResponseData, TNever>['handler'];
653
- }): Branded<StreamProcedure<Context, State, ParsedMetadata, RequestInit, RequestData, ResponseData, TNever>>;
654
- declare function stream<Context, State, ParsedMetadata, RequestInit extends PayloadType, RequestData extends PayloadType, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType>(def: {
655
- requestInit: RequestInit;
656
- requestData: RequestData;
657
- responseData: ResponseData;
658
- responseError: ResponseErr;
659
- description?: string;
660
- handler: StreamProcedure<Context, State, ParsedMetadata, RequestInit, RequestData, ResponseData, ResponseErr>['handler'];
661
- }): Branded<StreamProcedure<Context, State, ParsedMetadata, RequestInit, RequestData, ResponseData, ResponseErr>>;
662
- /**
663
- * Defines a Procedure type that can be a:
664
- * - {@link RpcProcedure} for a single message in both directions (1:1)
665
- * - {@link UploadProcedure} for a client-stream (potentially preceded by an
666
- * initialization message)
667
- * - {@link SubscriptionProcedure} for a single message from client, stream from server (1:n)
668
- * - {@link StreamProcedure} for a bidirectional stream (potentially preceded by an
669
- * initialization message)
670
- *
671
- * @template State - The TypeBox schema of the state object.
672
- * @template Ty - The type of the procedure.
673
- * @template RequestData - The TypeBox schema of the request object.
674
- * @template RequestInit - The TypeBox schema of the request initialization object, if any.
675
- * @template ResponseData - The TypeBox schema of the response object.
676
- */
677
- type Procedure<Context, State, ParsedMetadata, Ty extends ValidProcType, RequestInit extends PayloadType, RequestData extends PayloadType | null, ResponseData extends PayloadType, ResponseErr extends ProcedureErrorSchemaType> = {
678
- type: Ty;
679
- } & (RequestData extends PayloadType ? Ty extends 'upload' ? UploadProcedure<Context, State, ParsedMetadata, RequestInit, RequestData, ResponseData, ResponseErr> : Ty extends 'stream' ? StreamProcedure<Context, State, ParsedMetadata, RequestInit, RequestData, ResponseData, ResponseErr> : never : Ty extends 'rpc' ? RpcProcedure<Context, State, ParsedMetadata, RequestInit, ResponseData, ResponseErr> : Ty extends 'subscription' ? SubscriptionProcedure<Context, State, ParsedMetadata, RequestInit, ResponseData, ResponseErr> : never);
680
- /**
681
- * Holds the {@link Procedure} creation functions. Use these to create
682
- * procedures for services. You aren't allowed to create procedures directly.
683
- */
684
- declare const Procedure: {
685
- rpc: typeof rpc;
686
- upload: typeof upload;
687
- subscription: typeof subscription;
688
- stream: typeof stream;
689
- };
690
-
691
- /**
692
- * An instantiated service, probably from a {@link ServiceSchema}.
693
- *
694
- * You shouldn't construct these directly, use {@link ServiceSchema} instead.
695
- */
696
- interface Service<Context, State extends object, ParsedMetadata, Procs extends ProcedureMap<Context, State, ParsedMetadata>> {
697
- readonly state: State;
698
- readonly procedures: Procs;
699
- [Symbol.asyncDispose]: () => PromiseLike<void>;
700
- }
701
- /**
702
- * Represents any {@link Service} object.
703
- */
704
- type AnyService = Service<object, object, object, ProcedureMap>;
705
- /**
706
- * Represents any {@link ServiceSchema} object.
707
- */
708
- type AnyServiceSchema<Context extends MaybeDisposable = MaybeDisposable, ParsedMetadata extends object = object> = InstanceType<ReturnType<typeof createServiceSchema<Context, ParsedMetadata>>>;
709
- /**
710
- * A dictionary of {@link ServiceSchema}s, where the key is the service name.
711
- */
712
- type AnyServiceSchemaMap<Context extends MaybeDisposable = MaybeDisposable, ParsedMetadata extends object = object> = Record<string, AnyServiceSchema<Context, ParsedMetadata>>;
713
- /**
714
- * Takes a {@link AnyServiceSchemaMap} and returns a dictionary of instantiated
715
- * services.
716
- */
717
- type InstantiatedServiceSchemaMap<Context extends MaybeDisposable, ParsedMetadata extends object, T extends AnyServiceSchemaMap<Context, ParsedMetadata>> = {
718
- [K in keyof T]: T[K] extends AnyServiceSchema<Context, ParsedMetadata> ? T[K] extends {
719
- initializeState: (ctx: Context) => infer S;
720
- procedures: infer P;
721
- } ? Service<Context, S extends object ? S : object, ParsedMetadata, P extends ProcedureMap<Context, S extends object ? S : object, ParsedMetadata> ? P : ProcedureMap> : never : never;
722
- };
723
- /**
724
- * Helper to get the type definition for a specific handler of a procedure in a service.
725
- * @template S - The service.
726
- * @template ProcName - The name of the procedure.
727
- */
728
- type ProcHandler<S extends AnyService, ProcName extends keyof S['procedures']> = S['procedures'][ProcName]['handler'];
729
- /**
730
- * Helper to get the type definition for the procedure init type of a service.
731
- * @template S - The service.
732
- * @template ProcName - The name of the procedure.
733
- */
734
- type ProcInit<S extends AnyService, ProcName extends keyof S['procedures']> = Static<S['procedures'][ProcName]['requestInit']>;
735
- /**
736
- * Helper to get the type definition for the procedure request of a service.
737
- * @template S - The service.
738
- * @template ProcName - The name of the procedure.
739
- */
740
- type ProcRequest<S extends AnyService, ProcName extends keyof S['procedures']> = S['procedures'][ProcName] extends {
741
- requestData: PayloadType;
742
- } ? Static<S['procedures'][ProcName]['requestData']> : never;
743
- /**
744
- * Helper to get the type definition for the procedure response of a service.
745
- * @template S - The service.
746
- * @template ProcName - The name of the procedure.
747
- */
748
- type ProcResponse<S extends AnyService, ProcName extends keyof S['procedures']> = Static<S['procedures'][ProcName]['responseData']>;
749
- /**
750
- * Helper to get the type definition for the procedure errors of a service.
751
- * @template S - The service.
752
- * @template ProcName - The name of the procedure.
753
- */
754
- type ProcErrors<S extends AnyService, ProcName extends keyof S['procedures']> = Static<S['procedures'][ProcName]['responseError']> | Static<typeof ReaderErrorSchema>;
755
- /**
756
- * Helper to get the type of procedure in a service.
757
- * @template S - The service.
758
- * @template ProcName - The name of the procedure.
759
- */
760
- type ProcType<S extends AnyService, ProcName extends keyof S['procedures']> = S['procedures'][ProcName]['type'];
761
- /**
762
- * A list of procedures where every procedure is "branded", as-in the procedure
763
- * was created via the {@link Procedure} constructors.
764
- */
765
- type BrandedProcedureMap<Context, State, ParsedMetadata> = Record<string, Branded<AnyProcedure<Context, State, ParsedMetadata>>>;
766
- type MaybeDisposable<T extends object = Record<string, unknown>> = T & {
767
- [Symbol.asyncDispose]?: () => PromiseLike<void>;
768
- [Symbol.dispose]?: () => void;
769
- };
770
- /**
771
- * The configuration for a service.
772
- */
773
- interface ServiceConfiguration<Context extends MaybeDisposable, State extends object> {
774
- /**
775
- * A factory function for creating a fresh state.
776
- */
777
- initializeState: (extendedContext: Context) => MaybeDisposable<State>;
778
- }
779
- interface SerializedProcedureSchemaProtocolv1 {
780
- init?: PayloadType;
781
- input: PayloadType;
782
- output: PayloadType;
783
- errors?: ProcedureErrorSchemaType;
784
- type: 'rpc' | 'subscription' | 'upload' | 'stream';
785
- }
786
- interface SerializedServiceSchemaProtocolv1 {
787
- procedures: Record<string, SerializedProcedureSchemaProtocolv1>;
788
- }
789
- interface SerializedServerSchemaProtocolv1 {
790
- handshakeSchema?: TSchema;
791
- services: Record<string, SerializedServiceSchemaProtocolv1>;
792
- }
793
- /**
794
- * Same as {@link serializeSchema} but with a format that is compatible with
795
- * protocolv1. This is useful to be able to continue to generate schemas for older
796
- * clients as they are still supported.
797
- */
798
- declare function serializeSchemaV1Compat(services: AnyServiceSchemaMap, handshakeSchema?: TSchema): SerializedServerSchemaProtocolv1;
799
- interface SerializedProcedureSchema {
800
- init: PayloadType;
801
- input?: PayloadType;
802
- output: PayloadType;
803
- errors?: ProcedureErrorSchemaType;
804
- type: 'rpc' | 'subscription' | 'upload' | 'stream';
805
- }
806
- interface SerializedServiceSchema {
807
- procedures: Record<string, SerializedProcedureSchema>;
808
- }
809
- interface SerializedServerSchema {
810
- handshakeSchema?: TSchema;
811
- services: Record<string, SerializedServiceSchema>;
812
- }
813
- /**
814
- * Serializes a server schema into a plain object that is JSON compatible.
815
- */
816
- declare function serializeSchema(services: AnyServiceSchemaMap, handshakeSchema?: TSchema): SerializedServerSchema;
817
- /**
818
- * Creates a ServiceSchema class that can be used to define services with their initial state and procedures.
819
- * This is a factory function that returns a ServiceSchema class constructor bound to the specified Context type.
820
- *
821
- * @template Context - The context type that will be available to all procedures in services created with this schema.
822
- * @returns A ServiceSchema class constructor with static methods for defining services.
823
- *
824
- * @example
825
- * ```ts
826
- * // Create a ServiceSchema class for your context type
827
- * const ServiceSchema = createServiceSchema<{ userId: string }>();
828
- *
829
- * // Define a simple stateless service
830
- * const mathService = ServiceSchema.define({
831
- * add: Procedure.rpc({
832
- * requestInit: Type.Object({ a: Type.Number(), b: Type.Number() }),
833
- * responseData: Type.Object({ result: Type.Number() }),
834
- * async handler(ctx, init) {
835
- * return Ok({ result: init.a + init.b });
836
- * }
837
- * }),
838
- * getUserId: Procedure.rpc({
839
- * requestInit: Type.Object({}),
840
- * responseData: Type.Object({ id: Type.String() }),
841
- * async handler(ctx) {
842
- * return Ok({ id: ctx.userId });
843
- * }
844
- * }),
845
- * });
846
- * ```
847
- *
848
- * There are two main ways to define services with the returned ServiceSchema class:
849
- *
850
- * 1. **ServiceSchema.define()** - Takes a configuration and procedures directly.
851
- * Use this for smaller services or when you want to define everything in one place.
852
- *
853
- * 2. **ServiceSchema.scaffold()** - Creates a scaffold that can be used to define
854
- * procedures separately from the configuration. Use this for larger services or
855
- * when you want to organize procedures across multiple files.
856
- *
857
- * When defining procedures, always use the {@link Procedure} constructors to create them.
858
- */
859
- declare function createServiceSchema<Context extends MaybeDisposable = MaybeDisposable, ParsedMetadata extends object = object>(): {
860
- new <State extends object, Procedures extends ProcedureMap<Context, State, ParsedMetadata>>(config: ServiceConfiguration<Context, State>, procedures: Procedures): {
861
- /**
862
- * Factory function for creating a fresh state.
863
- */
864
- readonly initializeState: (extendedContext: Context) => MaybeDisposable<State>;
865
- /**
866
- * The procedures for this service.
867
- */
868
- readonly procedures: Procedures;
869
- /**
870
- * Serializes this schema's procedures into a plain object that is JSON compatible.
871
- */
872
- serialize(): SerializedServiceSchema;
873
- /**
874
- * Same as {@link ServiceSchema.serialize}, but with a format that is compatible with
875
- * protocol v1. This is useful to be able to continue to generate schemas for older
876
- * clients as they are still supported.
877
- */
878
- serializeV1Compat(): SerializedServiceSchemaProtocolv1;
879
- /**
880
- * Instantiates this schema into a {@link Service} object.
881
- *
882
- * You probably don't need this, usually the River server will handle this
883
- * for you.
884
- */
885
- instantiate(extendedContext: Context): Service<Context, State, ParsedMetadata, Procedures>;
886
- };
887
- /**
888
- * Creates a {@link ServiceScaffold}, which can be used to define procedures
889
- * that can then be merged into a {@link ServiceSchema}, via the scaffold's
890
- * `finalize` method.
891
- *
892
- * There are two patterns that work well with this method. The first is using
893
- * it to separate the definition of procedures from the definition of the
894
- * service's configuration:
895
- * ```ts
896
- * const MyServiceScaffold = ServiceSchema.scaffold({
897
- * initializeState: () => ({ count: 0 }),
898
- * });
899
- *
900
- * const incrementProcedures = MyServiceScaffold.procedures({
901
- * increment: Procedure.rpc({
902
- * requestInit: Type.Object({ amount: Type.Number() }),
903
- * responseData: Type.Object({ current: Type.Number() }),
904
- * async handler(ctx, init) {
905
- * ctx.state.count += init.amount;
906
- * return Ok({ current: ctx.state.count });
907
- * }
908
- * }),
909
- * })
910
- *
911
- * const MyService = MyServiceScaffold.finalize({
912
- * ...incrementProcedures,
913
- * // you can also directly define procedures here
914
- * });
915
- * ```
916
- * This might be really handy if you have a very large service and you're
917
- * wanting to split it over multiple files. You can define the scaffold
918
- * in one file, and then import that scaffold in other files where you
919
- * define procedures - and then finally import the scaffolds and your
920
- * procedure objects in a final file where you finalize the scaffold into
921
- * a service schema.
922
- *
923
- * The other way is to use it like in a builder pattern:
924
- * ```ts
925
- * const MyService = ServiceSchema
926
- * .scaffold({ initializeState: () => ({ count: 0 }) })
927
- * .finalize({
928
- * increment: Procedure.rpc({
929
- * requestInit: Type.Object({ amount: Type.Number() }),
930
- * responseData: Type.Object({ current: Type.Number() }),
931
- * async handler(ctx, init) {
932
- * ctx.state.count += init.amount;
933
- * return Ok({ current: ctx.state.count });
934
- * }
935
- * }),
936
- * })
937
- * ```
938
- * Depending on your preferences, this may be a more appealing way to define
939
- * a schema versus using the {@link ServiceSchema.define} method.
940
- */
941
- scaffold<State_1 extends object>(config: ServiceConfiguration<Context, State_1>): ServiceScaffold<Context, State_1, ParsedMetadata>;
942
- /**
943
- * Creates a new {@link ServiceSchema} with the given configuration and procedures.
944
- *
945
- * All procedures must be created with the {@link Procedure} constructors.
946
- *
947
- * NOTE: There is an overload that lets you just provide the procedures alone if your
948
- * service has no state.
949
- *
950
- * @param config - The configuration for this service.
951
- * @param procedures - The procedures for this service.
952
- *
953
- * @example
954
- * ```
955
- * const service = ServiceSchema.define(
956
- * { initializeState: () => ({ count: 0 }) },
957
- * {
958
- * increment: Procedure.rpc({
959
- * requestInit: Type.Object({ amount: Type.Number() }),
960
- * responseData: Type.Object({ current: Type.Number() }),
961
- * async handler(ctx, init) {
962
- * ctx.state.count += init.amount;
963
- * return Ok({ current: ctx.state.count });
964
- * }
965
- * }),
966
- * },
967
- * );
968
- * ```
969
- */
970
- define<State_2 extends object, Procedures_1 extends BrandedProcedureMap<Context, State_2, ParsedMetadata>>(config: ServiceConfiguration<Context, State_2>, procedures: Procedures_1): {
971
- /**
972
- * Factory function for creating a fresh state.
973
- */
974
- readonly initializeState: (extendedContext: Context) => MaybeDisposable<State_2>;
975
- /**
976
- * The procedures for this service.
977
- */
978
- readonly procedures: { [K in keyof Procedures_1]: Unbranded<Procedures_1[K]>; };
979
- /**
980
- * Serializes this schema's procedures into a plain object that is JSON compatible.
981
- */
982
- serialize(): SerializedServiceSchema;
983
- /**
984
- * Same as {@link ServiceSchema.serialize}, but with a format that is compatible with
985
- * protocol v1. This is useful to be able to continue to generate schemas for older
986
- * clients as they are still supported.
987
- */
988
- serializeV1Compat(): SerializedServiceSchemaProtocolv1;
989
- /**
990
- * Instantiates this schema into a {@link Service} object.
991
- *
992
- * You probably don't need this, usually the River server will handle this
993
- * for you.
994
- */
995
- instantiate(extendedContext: Context): Service<Context, State_2, ParsedMetadata, { [K in keyof Procedures_1]: Unbranded<Procedures_1[K]>; }>;
996
- };
997
- /**
998
- * Creates a new {@link ServiceSchema} with the given configuration and procedures.
999
- *
1000
- * All procedures must be created with the {@link Procedure} constructors.
1001
- *
1002
- * NOTE: There is an overload that lets you just provide the procedures alone if your
1003
- * service has no state.
1004
- *
1005
- * @param config - The configuration for this service.
1006
- * @param procedures - The procedures for this service.
1007
- *
1008
- * @example
1009
- * ```
1010
- * const service = ServiceSchema.define(
1011
- * { initializeState: () => ({ count: 0 }) },
1012
- * {
1013
- * increment: Procedure.rpc({
1014
- * requestInit: Type.Object({ amount: Type.Number() }),
1015
- * responseData: Type.Object({ current: Type.Number() }),
1016
- * async handler(ctx, init) {
1017
- * ctx.state.count += init.amount;
1018
- * return Ok({ current: ctx.state.count });
1019
- * }
1020
- * }),
1021
- * },
1022
- * );
1023
- * ```
1024
- */
1025
- define<Procedures_2 extends BrandedProcedureMap<Context, object, ParsedMetadata>>(procedures: Procedures_2): {
1026
- /**
1027
- * Factory function for creating a fresh state.
1028
- */
1029
- readonly initializeState: (extendedContext: Context) => MaybeDisposable<object>;
1030
- /**
1031
- * The procedures for this service.
1032
- */
1033
- readonly procedures: { [K_1 in keyof Procedures_2]: Unbranded<Procedures_2[K_1]>; };
1034
- /**
1035
- * Serializes this schema's procedures into a plain object that is JSON compatible.
1036
- */
1037
- serialize(): SerializedServiceSchema;
1038
- /**
1039
- * Same as {@link ServiceSchema.serialize}, but with a format that is compatible with
1040
- * protocol v1. This is useful to be able to continue to generate schemas for older
1041
- * clients as they are still supported.
1042
- */
1043
- serializeV1Compat(): SerializedServiceSchemaProtocolv1;
1044
- /**
1045
- * Instantiates this schema into a {@link Service} object.
1046
- *
1047
- * You probably don't need this, usually the River server will handle this
1048
- * for you.
1049
- */
1050
- instantiate(extendedContext: Context): Service<Context, object, ParsedMetadata, { [K_1 in keyof Procedures_2]: Unbranded<Procedures_2[K_1]>; }>;
1051
- };
1052
- };
1053
- /**
1054
- * A scaffold for defining a service's procedures.
1055
- *
1056
- * @see {@link ServiceSchema.scaffold}
1057
- */
1058
- declare class ServiceScaffold<Context extends MaybeDisposable, State extends object, ParsedMetadata extends object> {
1059
- /**
1060
- * The configuration for this service.
1061
- */
1062
- protected readonly config: ServiceConfiguration<Context, State>;
1063
- /**
1064
- * @param config - The configuration for this service.
1065
- */
1066
- constructor(config: ServiceConfiguration<Context, State>);
1067
- /**
1068
- * Define procedures for this service. Use the {@link Procedure} constructors
1069
- * to create them. This returns the procedures object, which can then be
1070
- * passed to {@link ServiceSchema.finalize} to create a {@link ServiceSchema}.
1071
- *
1072
- * @example
1073
- * ```
1074
- * const myProcedures = MyServiceScaffold.procedures({
1075
- * myRPC: Procedure.rpc({
1076
- * // ...
1077
- * }),
1078
- * });
1079
- *
1080
- * const MyService = MyServiceScaffold.finalize({
1081
- * ...myProcedures,
1082
- * });
1083
- * ```
1084
- *
1085
- * @param procedures - The procedures for this service.
1086
- */
1087
- procedures<T extends BrandedProcedureMap<Context, State, ParsedMetadata>>(procedures: T): T;
1088
- /**
1089
- * Finalizes the scaffold into a {@link ServiceSchema}. This is where you
1090
- * provide the service's procedures and get a {@link ServiceSchema} in return.
1091
- *
1092
- * You can directly define procedures here, or you can define them separately
1093
- * with the {@link ServiceScaffold.procedures} method, and then pass them here.
1094
- *
1095
- * @example
1096
- * ```
1097
- * const MyService = MyServiceScaffold.finalize({
1098
- * myRPC: Procedure.rpc({
1099
- * // ...
1100
- * }),
1101
- * // e.g. from the procedures method
1102
- * ...myOtherProcedures,
1103
- * });
1104
- * ```
1105
- */
1106
- finalize<T extends BrandedProcedureMap<Context, State, ParsedMetadata>>(procedures: T): {
1107
- /**
1108
- * Factory function for creating a fresh state.
1109
- */
1110
- readonly initializeState: (extendedContext: Context) => MaybeDisposable<State>;
1111
- /**
1112
- * The procedures for this service.
1113
- */
1114
- readonly procedures: { [K in keyof T]: Unbranded<T[K]>; };
1115
- /**
1116
- * Serializes this schema's procedures into a plain object that is JSON compatible.
1117
- */
1118
- serialize(): SerializedServiceSchema;
1119
- /**
1120
- * Same as {@link ServiceSchema.serialize}, but with a format that is compatible with
1121
- * protocol v1. This is useful to be able to continue to generate schemas for older
1122
- * clients as they are still supported.
1123
- */
1124
- serializeV1Compat(): SerializedServiceSchemaProtocolv1;
1125
- /**
1126
- * Instantiates this schema into a {@link Service} object.
1127
- *
1128
- * You probably don't need this, usually the River server will handle this
1129
- * for you.
1130
- */
1131
- instantiate(extendedContext: Context): Service<Context, State, ParsedMetadata, { [K in keyof T]: Unbranded<T[K]>; }>;
1132
- };
1133
- }
1134
-
1135
- export { serializeSchema as $, type AnyServiceSchemaMap as A, type BaseErrorSchemaType as B, CANCEL_CODE as C, type SerializedProcedureSchemaProtocolv1 as D, Err as E, type SerializedServerSchema as F, type SerializedServerSchemaProtocolv1 as G, type SerializedServiceSchema as H, type InstantiatedServiceSchemaMap as I, type SerializedServiceSchemaProtocolv1 as J, type Service as K, type ServiceConfiguration as L, type MaybeDisposable as M, type StreamProcedure as N, Ok as O, type ProcedureHandlerContext as P, type SubscriptionProcedure as Q, type RpcProcedure as R, type SerializedProcedureSchema as S, UNEXPECTED_DISCONNECT_CODE as T, UNCAUGHT_ERROR_CODE as U, type UploadProcedure as V, type ValidProcType as W, type Writable as X, createClient as Y, createServiceSchema as Z, flattenErrorType as _, type PayloadType as a, serializeSchemaV1Compat as a0, type ReadableIterator as a1, type ErrorPayload as a2, type AnyProcedure as b, type CallOptions as c, type Client as d, type ClientOptions as e, type ErrResult as f, INVALID_REQUEST_CODE as g, type OkResult as h, type ProcErrors as i, type ProcHandler as j, type ProcInit as k, type ProcRequest as l, type ProcResponse as m, type ProcType as n, Procedure as o, type ProcedureErrorSchemaType as p, type ProcedureMap as q, ReadableImpl as r, type Readable as s, ReadableBrokenError as t, type ReadableResult as u, ReaderErrorSchema as v, type ResponseData as w, type Result as x, type ResultUnwrapErr as y, type ResultUnwrapOk as z };