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