@replit/river 0.18.5 → 0.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/{chunk-VH3NGOXQ.js → chunk-D5PVGZPQ.js} +5 -3
  2. package/dist/{chunk-K7CUSLWL.js → chunk-JH275HID.js} +1 -1
  3. package/dist/{chunk-WER2DWCP.js → chunk-NBE3D667.js} +0 -4
  4. package/dist/{chunk-6Q3MSICL.js → chunk-SR4DBLJ6.js} +11 -3
  5. package/dist/{chunk-UABIFWM7.js → chunk-YFPVQTWL.js} +220 -105
  6. package/dist/{chunk-PUX3U2SZ.js → chunk-ZWPEZS27.js} +1 -1
  7. package/dist/{connection-893bd769.d.ts → connection-aa0ea000.d.ts} +1 -1
  8. package/dist/{connection-89918b74.d.ts → connection-cfec12e6.d.ts} +1 -1
  9. package/dist/index-e2513701.d.ts +342 -0
  10. package/dist/logging/index.cjs +0 -4
  11. package/dist/logging/index.d.cts +2 -1
  12. package/dist/logging/index.d.ts +2 -1
  13. package/dist/logging/index.js +1 -1
  14. package/dist/router/index.cjs +11 -2
  15. package/dist/router/index.d.cts +7 -383
  16. package/dist/router/index.d.ts +7 -383
  17. package/dist/router/index.js +3 -3
  18. package/dist/services-4bba42d8.d.ts +736 -0
  19. package/dist/services-5fc5712d.d.ts +736 -0
  20. package/dist/transport/impls/uds/client.cjs +80 -53
  21. package/dist/transport/impls/uds/client.d.cts +5 -5
  22. package/dist/transport/impls/uds/client.d.ts +5 -5
  23. package/dist/transport/impls/uds/client.js +4 -4
  24. package/dist/transport/impls/uds/server.cjs +151 -62
  25. package/dist/transport/impls/uds/server.d.cts +4 -4
  26. package/dist/transport/impls/uds/server.d.ts +4 -4
  27. package/dist/transport/impls/uds/server.js +4 -4
  28. package/dist/transport/impls/ws/client.cjs +80 -53
  29. package/dist/transport/impls/ws/client.d.cts +3 -3
  30. package/dist/transport/impls/ws/client.d.ts +3 -3
  31. package/dist/transport/impls/ws/client.js +4 -4
  32. package/dist/transport/impls/ws/server.cjs +151 -62
  33. package/dist/transport/impls/ws/server.d.cts +4 -4
  34. package/dist/transport/impls/ws/server.d.ts +4 -4
  35. package/dist/transport/impls/ws/server.js +4 -4
  36. package/dist/transport/index.cjs +188 -71
  37. package/dist/transport/index.d.cts +295 -3
  38. package/dist/transport/index.d.ts +295 -3
  39. package/dist/transport/index.js +3 -4
  40. package/dist/util/testHelpers.cjs +410 -401
  41. package/dist/util/testHelpers.d.cts +3 -3
  42. package/dist/util/testHelpers.d.ts +3 -3
  43. package/dist/util/testHelpers.js +4 -5
  44. package/package.json +1 -1
  45. package/dist/chunk-RPIDSIQG.js +0 -0
  46. package/dist/index-46ed19d8.d.ts +0 -111
  47. package/dist/index-d412ca83.d.ts +0 -420
  48. package/dist/procedures-bfffcb0b.d.ts +0 -324
@@ -0,0 +1,736 @@
1
+ import { Static, TObject, TUnion, TString, TSchema, TNever, TLiteral } from '@sinclair/typebox';
2
+ import { ClientTransport } from './transport/index.js';
3
+ import { Pushable } from 'it-pushable';
4
+ import { C as Connection, T as TransportClientId, a as Session, b as ParsedHandshakeMetadata } from './index-e2513701.js';
5
+
6
+ type AsyncIter<T> = AsyncGenerator<T, T>;
7
+ /**
8
+ * A helper type to transform an actual service type into a type
9
+ * we can case to in the proxy.
10
+ * @template Router - The type of the Router.
11
+ */
12
+ type ServiceClient<Router extends AnyService> = {
13
+ [ProcName in keyof Router['procedures']]: ProcType<Router, ProcName> extends 'rpc' ? {
14
+ rpc: (input: Static<ProcInput<Router, ProcName>>) => Promise<Result<Static<ProcOutput<Router, ProcName>>, Static<ProcErrors<Router, ProcName>>>>;
15
+ } : ProcType<Router, ProcName> extends 'upload' ? ProcHasInit<Router, ProcName> extends true ? {
16
+ upload: (init: Static<ProcInit<Router, ProcName>>) => Promise<[
17
+ Pushable<Static<ProcInput<Router, ProcName>>>,
18
+ Promise<Result<Static<ProcOutput<Router, ProcName>>, Static<ProcErrors<Router, ProcName>>>>
19
+ ]>;
20
+ } : {
21
+ upload: () => Promise<[
22
+ Pushable<Static<ProcInput<Router, ProcName>>>,
23
+ Promise<Result<Static<ProcOutput<Router, ProcName>>, Static<ProcErrors<Router, ProcName>>>>
24
+ ]>;
25
+ } : ProcType<Router, ProcName> extends 'stream' ? ProcHasInit<Router, ProcName> extends true ? {
26
+ stream: (init: Static<ProcInit<Router, ProcName>>) => Promise<[
27
+ Pushable<Static<ProcInput<Router, ProcName>>>,
28
+ AsyncIter<Result<Static<ProcOutput<Router, ProcName>>, Static<ProcErrors<Router, ProcName>>>>,
29
+ () => void
30
+ ]>;
31
+ } : {
32
+ stream: () => Promise<[
33
+ Pushable<Static<ProcInput<Router, ProcName>>>,
34
+ AsyncIter<Result<Static<ProcOutput<Router, ProcName>>, Static<ProcErrors<Router, ProcName>>>>,
35
+ () => void
36
+ ]>;
37
+ } : ProcType<Router, ProcName> extends 'subscription' ? {
38
+ subscribe: (input: Static<ProcInput<Router, ProcName>>) => Promise<[
39
+ AsyncIter<Result<Static<ProcOutput<Router, ProcName>>, Static<ProcErrors<Router, ProcName>>>>,
40
+ () => void
41
+ ]>;
42
+ } : never;
43
+ };
44
+ /**
45
+ * Defines a type that represents a client for a server with a set of services.
46
+ * @template Srv - The type of the server.
47
+ */
48
+ type Client<Services extends AnyServiceSchemaMap, IS extends InstantiatedServiceSchemaMap<Services> = InstantiatedServiceSchemaMap<Services>> = {
49
+ [SvcName in keyof IS]: ServiceClient<IS[SvcName]>;
50
+ };
51
+ interface ClientOptions {
52
+ connectOnInvoke: boolean;
53
+ eagerlyConnect: boolean;
54
+ }
55
+ /**
56
+ * Creates a client for a given server using the provided transport.
57
+ * Note that the client only needs the type of the server, not the actual
58
+ * server definition itself.
59
+ *
60
+ * This relies on a proxy to dynamically create the client, so the client
61
+ * will be typed as if it were the actual server with the appropriate services
62
+ * and procedures.
63
+ *
64
+ * @template Srv - The type of the server.
65
+ * @param {Transport} transport - The transport to use for communication.
66
+ * @returns The client for the server.
67
+ */
68
+ declare const createClient: <ServiceSchemaMap extends AnyServiceSchemaMap>(transport: ClientTransport<Connection>, serverId: TransportClientId, providedClientOptions?: Partial<ClientOptions>) => Client<ServiceSchemaMap, InstantiatedServiceSchemaMap<ServiceSchemaMap>>;
69
+
70
+ type TLiteralString = TLiteral<string>;
71
+ type RiverErrorSchema = TObject<{
72
+ code: TLiteralString | TUnion<Array<TLiteralString>>;
73
+ message: TLiteralString | TString;
74
+ }> | TObject<{
75
+ code: TLiteralString | TUnion<Array<TLiteralString>>;
76
+ message: TLiteralString | TString;
77
+ extras: TSchema;
78
+ }>;
79
+ type RiverError = TUnion<Array<RiverErrorSchema>> | RiverErrorSchema | TNever;
80
+ declare const UNCAUGHT_ERROR = "UNCAUGHT_ERROR";
81
+ declare const RiverUncaughtSchema: TObject<{
82
+ code: TUnion<[TLiteral<"UNCAUGHT_ERROR">, TLiteral<"UNEXPECTED_DISCONNECT">]>;
83
+ message: TString;
84
+ }>;
85
+ type Result<T, E> = {
86
+ ok: true;
87
+ payload: T;
88
+ } | {
89
+ ok: false;
90
+ payload: E;
91
+ };
92
+ declare function Ok<const T, const E>(payload: T): Result<T, E>;
93
+ declare function Err<const T, const E>(error: E): Result<T, E>;
94
+ /**
95
+ * Refine a {@link Result} type to its returned payload.
96
+ */
97
+ type ResultUnwrapOk<R> = R extends Result<infer T, infer __E> ? T : never;
98
+ /**
99
+ * Refine a {@link Result} type to its error payload.
100
+ */
101
+ type ResultUnwrapErr<R> = R extends Result<infer __T, infer E> ? E : never;
102
+ /**
103
+ * Retrieve the output type for a procedure, represented as a {@link Result}
104
+ * type.
105
+ * Example:
106
+ * ```
107
+ * type Message = Output<typeof client, 'serviceName', 'procedureName'>
108
+ * ```
109
+ */
110
+ type Output<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 & {
111
+ rpc: infer RpcHandler extends Fn;
112
+ } ? Awaited<ReturnType<RpcHandler>> : Procedure extends object & {
113
+ upload: infer UploadHandler extends Fn;
114
+ } ? Awaited<ReturnType<UploadHandler>> extends [
115
+ infer __UploadInputMessage,
116
+ infer UploadOutputMessage
117
+ ] ? Awaited<UploadOutputMessage> : never : Procedure extends object & {
118
+ stream: infer StreamHandler extends Fn;
119
+ } ? Awaited<ReturnType<StreamHandler>> extends [
120
+ infer __StreamInputMessage,
121
+ AsyncGenerator<infer StreamOutputMessage>,
122
+ infer __StreamCloseHandle
123
+ ] ? StreamOutputMessage : never : Procedure extends object & {
124
+ subscribe: infer SubscriptionHandler extends Fn;
125
+ } ? Awaited<ReturnType<SubscriptionHandler>> extends [
126
+ AsyncGenerator<infer SubscriptionOutputMessage>,
127
+ infer __SubscriptionCloseHandle
128
+ ] ? SubscriptionOutputMessage : never : never : never : never;
129
+
130
+ /**
131
+ * The context for services/procedures. This is used only on
132
+ * the server.
133
+ *
134
+ * An important detail is that the state prop is always on
135
+ * this interface and it shouldn't be changed, removed, or
136
+ * extended. This prop is for the state of a service.
137
+ *
138
+ * You should use declaration merging to extend this interface
139
+ * with whatever you need. For example, if you need to access
140
+ * a database, you could do:
141
+ *
142
+ * ```ts
143
+ * declare module '@replit/river' {
144
+ * interface ServiceContext {
145
+ * db: Database;
146
+ * }
147
+ * }
148
+ * ```
149
+ */
150
+ interface ServiceContext {
151
+ }
152
+ /**
153
+ * The {@link ServiceContext} with state. This is what is passed to procedures.
154
+ */
155
+ type ServiceContextWithState<State> = ServiceContext & {
156
+ state: State;
157
+ };
158
+ type ServiceContextWithTransportInfo<State> = ServiceContext & {
159
+ state: Omit<State, typeof Symbol.dispose>;
160
+ to: TransportClientId;
161
+ from: TransportClientId;
162
+ streamId: string;
163
+ session: Session<Connection> & {
164
+ metadata: ParsedHandshakeMetadata;
165
+ };
166
+ };
167
+
168
+ /**
169
+ * Brands a type to prevent it from being directly constructed.
170
+ */
171
+ type Branded<T> = T & {
172
+ readonly __BRAND_DO_NOT_USE: unique symbol;
173
+ };
174
+ /**
175
+ * Unbrands a {@link Branded} type.
176
+ */
177
+ type Unbranded<T> = T extends Branded<infer U> ? U : never;
178
+ /**
179
+ * The valid {@link Procedure} types. The `stream` and `upload` types can optionally have a
180
+ * different type for the very first initialization message. The suffixless types correspond to
181
+ * gRPC's four combinations of stream / non-stream in each direction.
182
+ */
183
+ type ValidProcType = 'rpc' | 'upload' | 'subscription' | 'stream';
184
+ /**
185
+ * Represents the payload type for {@link Procedure}s.
186
+ */
187
+ type PayloadType = TSchema;
188
+ /**
189
+ * Represents results from a {@link Procedure}. Might come from inside a stream or
190
+ * from a single message.
191
+ */
192
+ type ProcedureResult<O extends PayloadType, E extends RiverError> = Result<Static<O>, Static<E> | Static<typeof RiverUncaughtSchema>>;
193
+ /**
194
+ * Procedure for a single message in both directions (1:1).
195
+ *
196
+ * @template State - The context state object.
197
+ * @template I - The TypeBox schema of the input object.
198
+ * @template O - The TypeBox schema of the output object.
199
+ * @template E - The TypeBox schema of the error object.
200
+ */
201
+ interface RPCProcedure<State, I extends PayloadType, O extends PayloadType, E extends RiverError> {
202
+ type: 'rpc';
203
+ input: I;
204
+ output: O;
205
+ errors: E;
206
+ description?: string;
207
+ handler(context: ServiceContextWithTransportInfo<State>, input: Static<I>): Promise<ProcedureResult<O, E>>;
208
+ }
209
+ /**
210
+ * Procedure for a client-stream (potentially preceded by an initialization message),
211
+ * single message from server (n:1).
212
+ *
213
+ * @template State - The context state object.
214
+ * @template I - The TypeBox schema of the input object.
215
+ * @template O - The TypeBox schema of the output object.
216
+ * @template E - The TypeBox schema of the error object.
217
+ * @template Init - The TypeBox schema of the input initialization object, if any.
218
+ */
219
+ type UploadProcedure<State, I extends PayloadType, O extends PayloadType, E extends RiverError, Init extends PayloadType | null = null> = Init extends PayloadType ? {
220
+ type: 'upload';
221
+ init: Init;
222
+ input: I;
223
+ output: O;
224
+ errors: E;
225
+ description?: string;
226
+ handler(context: ServiceContextWithTransportInfo<State>, init: Static<Init>, input: AsyncIterableIterator<Static<I>>): Promise<ProcedureResult<O, E>>;
227
+ } : {
228
+ type: 'upload';
229
+ input: I;
230
+ output: O;
231
+ errors: E;
232
+ description?: string;
233
+ handler(context: ServiceContextWithTransportInfo<State>, input: AsyncIterableIterator<Static<I>>): Promise<ProcedureResult<O, E>>;
234
+ };
235
+ /**
236
+ * Procedure for a single message from client, stream from server (1:n).
237
+ *
238
+ * @template State - The context state object.
239
+ * @template I - The TypeBox schema of the input object.
240
+ * @template O - The TypeBox schema of the output object.
241
+ * @template E - The TypeBox schema of the error object.
242
+ */
243
+ interface SubscriptionProcedure<State, I extends PayloadType, O extends PayloadType, E extends RiverError> {
244
+ type: 'subscription';
245
+ input: I;
246
+ output: O;
247
+ errors: E;
248
+ description?: string;
249
+ handler(context: ServiceContextWithTransportInfo<State>, input: Static<I>, output: Pushable<ProcedureResult<O, E>>): Promise<(() => void) | void>;
250
+ }
251
+ /**
252
+ * Procedure for a bidirectional stream (potentially preceded by an initialization message),
253
+ * (n:n).
254
+ *
255
+ * @template State - The context state object.
256
+ * @template I - The TypeBox schema of the input object.
257
+ * @template O - The TypeBox schema of the output object.
258
+ * @template E - The TypeBox schema of the error object.
259
+ * @template Init - The TypeBox schema of the input initialization object, if any.
260
+ */
261
+ type StreamProcedure<State, I extends PayloadType, O extends PayloadType, E extends RiverError, Init extends PayloadType | null = null> = Init extends PayloadType ? {
262
+ type: 'stream';
263
+ init: Init;
264
+ input: I;
265
+ output: O;
266
+ errors: E;
267
+ description?: string;
268
+ handler(context: ServiceContextWithTransportInfo<State>, init: Static<Init>, input: AsyncIterableIterator<Static<I>>, output: Pushable<ProcedureResult<O, E>>): Promise<(() => void) | void>;
269
+ } : {
270
+ type: 'stream';
271
+ input: I;
272
+ output: O;
273
+ errors: E;
274
+ description?: string;
275
+ handler(context: ServiceContextWithTransportInfo<State>, input: AsyncIterableIterator<Static<I>>, output: Pushable<ProcedureResult<O, E>>): Promise<(() => void) | void>;
276
+ };
277
+ /**
278
+ * Represents any {@link Procedure} type.
279
+ *
280
+ * @template State - The context state object. You can provide this to constrain
281
+ * the type of procedures.
282
+ */
283
+ type AnyProcedure<State = object> = Procedure<State, ValidProcType, PayloadType, PayloadType, RiverError, PayloadType | null>;
284
+ /**
285
+ * Represents a map of {@link Procedure}s.
286
+ *
287
+ * @template State - The context state object. You can provide this to constrain
288
+ * the type of procedures.
289
+ */
290
+ type ProcedureMap<State = object> = Record<string, AnyProcedure<State>>;
291
+ /**
292
+ * Creates an {@link RPCProcedure}.
293
+ */
294
+ declare function rpc<State, I extends PayloadType, O extends PayloadType>(def: {
295
+ input: I;
296
+ output: O;
297
+ errors?: never;
298
+ description?: string;
299
+ handler: RPCProcedure<State, I, O, TNever>['handler'];
300
+ }): Branded<RPCProcedure<State, I, O, TNever>>;
301
+ declare function rpc<State, I extends PayloadType, O extends PayloadType, E extends RiverError>(def: {
302
+ input: I;
303
+ output: O;
304
+ errors: E;
305
+ description?: string;
306
+ handler: RPCProcedure<State, I, O, E>['handler'];
307
+ }): Branded<RPCProcedure<State, I, O, E>>;
308
+ /**
309
+ * Creates an {@link UploadProcedure}, optionally with an initialization message.
310
+ */
311
+ declare function upload<State, I extends PayloadType, O extends PayloadType, Init extends PayloadType>(def: {
312
+ init: Init;
313
+ input: I;
314
+ output: O;
315
+ errors?: never;
316
+ description?: string;
317
+ handler: UploadProcedure<State, I, O, TNever, Init>['handler'];
318
+ }): Branded<UploadProcedure<State, I, O, TNever, Init>>;
319
+ declare function upload<State, I extends PayloadType, O extends PayloadType, E extends RiverError, Init extends PayloadType>(def: {
320
+ init: Init;
321
+ input: I;
322
+ output: O;
323
+ errors: E;
324
+ description?: string;
325
+ handler: UploadProcedure<State, I, O, E, Init>['handler'];
326
+ }): Branded<UploadProcedure<State, I, O, E, Init>>;
327
+ declare function upload<State, I extends PayloadType, O extends PayloadType>(def: {
328
+ init?: never;
329
+ input: I;
330
+ output: O;
331
+ errors?: never;
332
+ description?: string;
333
+ handler: UploadProcedure<State, I, O, TNever>['handler'];
334
+ }): Branded<UploadProcedure<State, I, O, TNever>>;
335
+ declare function upload<State, I extends PayloadType, O extends PayloadType, E extends RiverError>(def: {
336
+ init?: never;
337
+ input: I;
338
+ output: O;
339
+ errors: E;
340
+ description?: string;
341
+ handler: UploadProcedure<State, I, O, E>['handler'];
342
+ }): Branded<UploadProcedure<State, I, O, E>>;
343
+ /**
344
+ * Creates a {@link SubscriptionProcedure}.
345
+ */
346
+ declare function subscription<State, I extends PayloadType, O extends PayloadType>(def: {
347
+ input: I;
348
+ output: O;
349
+ errors?: never;
350
+ description?: string;
351
+ handler: SubscriptionProcedure<State, I, O, TNever>['handler'];
352
+ }): Branded<SubscriptionProcedure<State, I, O, TNever>>;
353
+ declare function subscription<State, I extends PayloadType, O extends PayloadType, E extends RiverError>(def: {
354
+ input: I;
355
+ output: O;
356
+ errors: E;
357
+ description?: string;
358
+ handler: SubscriptionProcedure<State, I, O, E>['handler'];
359
+ }): Branded<SubscriptionProcedure<State, I, O, E>>;
360
+ /**
361
+ * Creates a {@link StreamProcedure}, optionally with an initialization message.
362
+ */
363
+ declare function stream<State, I extends PayloadType, O extends PayloadType, Init extends PayloadType>(def: {
364
+ init: Init;
365
+ input: I;
366
+ output: O;
367
+ errors?: never;
368
+ description?: string;
369
+ handler: StreamProcedure<State, I, O, TNever, Init>['handler'];
370
+ }): Branded<StreamProcedure<State, I, O, TNever, Init>>;
371
+ declare function stream<State, I extends PayloadType, O extends PayloadType, E extends RiverError, Init extends PayloadType>(def: {
372
+ init: Init;
373
+ input: I;
374
+ output: O;
375
+ errors: E;
376
+ description?: string;
377
+ handler: StreamProcedure<State, I, O, E, Init>['handler'];
378
+ }): Branded<StreamProcedure<State, I, O, E, Init>>;
379
+ declare function stream<State, I extends PayloadType, O extends PayloadType>(def: {
380
+ init?: never;
381
+ input: I;
382
+ output: O;
383
+ errors?: never;
384
+ description?: string;
385
+ handler: StreamProcedure<State, I, O, TNever>['handler'];
386
+ }): Branded<StreamProcedure<State, I, O, TNever>>;
387
+ declare function stream<State, I extends PayloadType, O extends PayloadType, E extends RiverError>(def: {
388
+ init?: never;
389
+ input: I;
390
+ output: O;
391
+ errors: E;
392
+ description?: string;
393
+ handler: StreamProcedure<State, I, O, E>['handler'];
394
+ }): Branded<StreamProcedure<State, I, O, E>>;
395
+ /**
396
+ * Defines a Procedure type that can be a:
397
+ * - {@link RPCProcedure} for a single message in both directions (1:1)
398
+ * - {@link UploadProcedure} for a client-stream (potentially preceded by an
399
+ * initialization message)
400
+ * - {@link SubscriptionProcedure} for a single message from client, stream from server (1:n)
401
+ * - {@link StreamProcedure} for a bidirectional stream (potentially preceded by an
402
+ * initialization message)
403
+ *
404
+ * @template State - The TypeBox schema of the state object.
405
+ * @template Ty - The type of the procedure.
406
+ * @template I - The TypeBox schema of the input object.
407
+ * @template O - The TypeBox schema of the output object.
408
+ * @template Init - The TypeBox schema of the input initialization object, if any.
409
+ */
410
+ type Procedure<State, Ty extends ValidProcType, I extends PayloadType, O extends PayloadType, E extends RiverError, Init extends PayloadType | null = null> = {
411
+ type: Ty;
412
+ } & (Init extends PayloadType ? Ty extends 'upload' ? UploadProcedure<State, I, O, E, Init> : Ty extends 'stream' ? StreamProcedure<State, I, O, E, Init> : never : Ty extends 'rpc' ? RPCProcedure<State, I, O, E> : Ty extends 'upload' ? UploadProcedure<State, I, O, E> : Ty extends 'subscription' ? SubscriptionProcedure<State, I, O, E> : Ty extends 'stream' ? StreamProcedure<State, I, O, E> : never);
413
+ /**
414
+ * Holds the {@link Procedure} creation functions. Use these to create
415
+ * procedures for services. You aren't allowed to create procedures directly.
416
+ */
417
+ declare const Procedure: {
418
+ rpc: typeof rpc;
419
+ upload: typeof upload;
420
+ subscription: typeof subscription;
421
+ stream: typeof stream;
422
+ };
423
+
424
+ /**
425
+ * An instantiated service, probably from a {@link ServiceSchema}.
426
+ *
427
+ * You shouldn't construct these directly, use {@link ServiceSchema} instead.
428
+ */
429
+ interface Service<State extends object, Procs extends ProcedureMap<State>> {
430
+ readonly state: State;
431
+ readonly procedures: Procs;
432
+ }
433
+ /**
434
+ * Represents any {@link Service} object.
435
+ */
436
+ type AnyService = Service<object, ProcedureMap>;
437
+ /**
438
+ * Represents any {@link ServiceSchema} object.
439
+ */
440
+ type AnyServiceSchema = ServiceSchema<object, ProcedureMap>;
441
+ /**
442
+ * A dictionary of {@link ServiceSchema}s, where the key is the service name.
443
+ */
444
+ type AnyServiceSchemaMap = Record<string, AnyServiceSchema>;
445
+ /**
446
+ * Takes a {@link AnyServiceSchemaMap} and returns a dictionary of instantiated
447
+ * services.
448
+ */
449
+ type InstantiatedServiceSchemaMap<T extends AnyServiceSchemaMap> = {
450
+ [K in keyof T]: T[K] extends ServiceSchema<infer S, infer P> ? Service<S, P> : never;
451
+ };
452
+ /**
453
+ * Helper to get the type definition for a specific handler of a procedure in a service.
454
+ * @template S - The service.
455
+ * @template ProcName - The name of the procedure.
456
+ */
457
+ type ProcHandler<S extends AnyService, ProcName extends keyof S['procedures']> = S['procedures'][ProcName]['handler'];
458
+ /**
459
+ * Helper to get whether the type definition for the procedure contains an init type.
460
+ * @template S - The service.
461
+ * @template ProcName - The name of the procedure.
462
+ */
463
+ type ProcHasInit<S extends AnyService, ProcName extends keyof S['procedures']> = S['procedures'][ProcName] extends {
464
+ init: PayloadType;
465
+ } ? true : false;
466
+ /**
467
+ * Helper to get the type definition for the procedure init type of a service.
468
+ * @template S - The service.
469
+ * @template ProcName - The name of the procedure.
470
+ */
471
+ type ProcInit<S extends AnyService, ProcName extends keyof S['procedures']> = S['procedures'][ProcName] extends {
472
+ init: PayloadType;
473
+ } ? S['procedures'][ProcName]['init'] : never;
474
+ /**
475
+ * Helper to get the type definition for the procedure input of a service.
476
+ * @template S - The service.
477
+ * @template ProcName - The name of the procedure.
478
+ */
479
+ type ProcInput<S extends AnyService, ProcName extends keyof S['procedures']> = S['procedures'][ProcName]['input'];
480
+ /**
481
+ * Helper to get the type definition for the procedure output of a service.
482
+ * @template S - The service.
483
+ * @template ProcName - The name of the procedure.
484
+ */
485
+ type ProcOutput<S extends AnyService, ProcName extends keyof S['procedures']> = S['procedures'][ProcName]['output'];
486
+ /**
487
+ * Helper to get the type definition for the procedure errors of a service.
488
+ * @template S - The service.
489
+ * @template ProcName - The name of the procedure.
490
+ */
491
+ type ProcErrors<S extends AnyService, ProcName extends keyof S['procedures']> = TUnion<[S['procedures'][ProcName]['errors'], typeof RiverUncaughtSchema]>;
492
+ /**
493
+ * Helper to get the type of procedure in a service.
494
+ * @template S - The service.
495
+ * @template ProcName - The name of the procedure.
496
+ */
497
+ type ProcType<S extends AnyService, ProcName extends keyof S['procedures']> = S['procedures'][ProcName]['type'];
498
+ /**
499
+ * A list of procedures where every procedure is "branded", as-in the procedure
500
+ * was created via the {@link Procedure} constructors.
501
+ */
502
+ type BrandedProcedureMap<State> = Record<string, Branded<AnyProcedure<State>>>;
503
+ /**
504
+ * The configuration for a service.
505
+ */
506
+ interface ServiceConfiguration<State extends object> {
507
+ /**
508
+ * A factory function for creating a fresh state.
509
+ */
510
+ initializeState: () => State;
511
+ }
512
+ interface SerializedServiceSchema {
513
+ procedures: Record<string, {
514
+ input: PayloadType;
515
+ output: PayloadType;
516
+ errors?: RiverError;
517
+ type: 'rpc' | 'subscription' | 'upload' | 'stream';
518
+ init?: PayloadType;
519
+ }>;
520
+ }
521
+ type SerializedServerSchema = Record<string, SerializedServiceSchema>;
522
+ declare function serializeSchema(services: AnyServiceSchemaMap): SerializedServerSchema;
523
+ /**
524
+ * The schema for a {@link Service}. This is used to define a service, specifically
525
+ * its initial state and procedures.
526
+ *
527
+ * There are two ways to define a service:
528
+ * 1. the {@link ServiceSchema.define} static method, which takes a configuration and
529
+ * a list of procedures directly. Use this to ergonomically define a service schema
530
+ * in one go. Good for smaller services, especially if they're stateless.
531
+ * 2. the {@link ServiceSchema.scaffold} static method, which creates a scaffold that
532
+ * can be used to define procedures separately from the configuration. Use this to
533
+ * better organize your service's definition, especially if it's a large service.
534
+ * You can also use it in a builder pattern to define the service in a more
535
+ * fluent way.
536
+ *
537
+ * See the static methods for more information and examples.
538
+ *
539
+ * When defining procedures, use the {@link Procedure} constructors to create them.
540
+ */
541
+ declare class ServiceSchema<State extends object, Procedures extends ProcedureMap<State>> {
542
+ /**
543
+ * Factory function for creating a fresh state.
544
+ */
545
+ protected readonly initializeState: () => State;
546
+ /**
547
+ * The procedures for this service.
548
+ */
549
+ readonly procedures: Procedures;
550
+ /**
551
+ * @param config - The configuration for this service.
552
+ * @param procedures - The procedures for this service.
553
+ */
554
+ protected constructor(config: ServiceConfiguration<State>, procedures: Procedures);
555
+ /**
556
+ * Creates a {@link ServiceScaffold}, which can be used to define procedures
557
+ * that can then be merged into a {@link ServiceSchema}, via the scaffold's
558
+ * `finalize` method.
559
+ *
560
+ * There are two patterns that work well with this method. The first is using
561
+ * it to separate the definition of procedures from the definition of the
562
+ * service's configuration:
563
+ * ```ts
564
+ * const MyServiceScaffold = ServiceSchema.scaffold({
565
+ * initializeState: () => ({ count: 0 }),
566
+ * });
567
+ *
568
+ * const incrementProcedures = MyServiceScaffold.procedures({
569
+ * increment: Procedure.rpc({
570
+ * input: Type.Object({ amount: Type.Number() }),
571
+ * output: Type.Object({ current: Type.Number() }),
572
+ * async handler(ctx, input) {
573
+ * ctx.state.count += input.amount;
574
+ * return Ok({ current: ctx.state.count });
575
+ * }
576
+ * }),
577
+ * })
578
+ *
579
+ * const MyService = MyServiceScaffold.finalize({
580
+ * ...incrementProcedures,
581
+ * // you can also directly define procedures here
582
+ * });
583
+ * ```
584
+ * This might be really handy if you have a very large service and you're
585
+ * wanting to split it over multiple files. You can define the scaffold
586
+ * in one file, and then import that scaffold in other files where you
587
+ * define procedures - and then finally import the scaffolds and your
588
+ * procedure objects in a final file where you finalize the scaffold into
589
+ * a service schema.
590
+ *
591
+ * The other way is to use it like in a builder pattern:
592
+ * ```ts
593
+ * const MyService = ServiceSchema
594
+ * .scaffold({ initializeState: () => ({ count: 0 }) })
595
+ * .finalize({
596
+ * increment: Procedure.rpc({
597
+ * input: Type.Object({ amount: Type.Number() }),
598
+ * output: Type.Object({ current: Type.Number() }),
599
+ * async handler(ctx, input) {
600
+ * ctx.state.count += input.amount;
601
+ * return Ok({ current: ctx.state.count });
602
+ * }
603
+ * }),
604
+ * })
605
+ * ```
606
+ * Depending on your preferences, this may be a more appealing way to define
607
+ * a schema versus using the {@link ServiceSchema.define} method.
608
+ */
609
+ static scaffold<State extends object>(config: ServiceConfiguration<State>): ServiceScaffold<State>;
610
+ /**
611
+ * Creates a new {@link ServiceSchema} with the given configuration and procedures.
612
+ *
613
+ * All procedures must be created with the {@link Procedure} constructors.
614
+ *
615
+ * NOTE: There is an overload that lets you just provide the procedures alone if your
616
+ * service has no state.
617
+ *
618
+ * @param config - The configuration for this service.
619
+ * @param procedures - The procedures for this service.
620
+ *
621
+ * @example
622
+ * ```
623
+ * const service = ServiceSchema.define(
624
+ * { initializeState: () => ({ count: 0 }) },
625
+ * {
626
+ * increment: Procedure.rpc({
627
+ * input: Type.Object({ amount: Type.Number() }),
628
+ * output: Type.Object({ current: Type.Number() }),
629
+ * async handler(ctx, input) {
630
+ * ctx.state.count += input.amount;
631
+ * return Ok({ current: ctx.state.count });
632
+ * }
633
+ * }),
634
+ * },
635
+ * );
636
+ * ```
637
+ */
638
+ static define<State extends object, Procedures extends BrandedProcedureMap<State>>(config: ServiceConfiguration<State>, procedures: Procedures): ServiceSchema<State, {
639
+ [K in keyof Procedures]: Unbranded<Procedures[K]>;
640
+ }>;
641
+ /**
642
+ * Creates a new {@link ServiceSchema} with the given procedures.
643
+ *
644
+ * All procedures must be created with the {@link Procedure} constructors.
645
+ *
646
+ * NOTE: There is an overload that lets you provide configuration as well,
647
+ * if your service has extra configuration like a state.
648
+ *
649
+ * @param procedures - The procedures for this service.
650
+ *
651
+ * @example
652
+ * ```
653
+ * const service = ServiceSchema.define({
654
+ * add: Procedure.rpc({
655
+ * input: Type.Object({ a: Type.Number(), b: Type.Number() }),
656
+ * output: Type.Object({ result: Type.Number() }),
657
+ * async handler(ctx, input) {
658
+ * return Ok({ result: input.a + input.b });
659
+ * }
660
+ * }),
661
+ * });
662
+ */
663
+ static define<Procedures extends BrandedProcedureMap<Record<string, never>>>(procedures: Procedures): ServiceSchema<Record<string, never>, {
664
+ [K in keyof Procedures]: Unbranded<Procedures[K]>;
665
+ }>;
666
+ /**
667
+ * Serializes this schema's procedures into a plain object that is JSON compatible.
668
+ */
669
+ serialize(): SerializedServiceSchema;
670
+ /**
671
+ * Instantiates this schema into a {@link Service} object.
672
+ *
673
+ * You probably don't need this, usually the River server will handle this
674
+ * for you.
675
+ */
676
+ instantiate(): Service<State, Procedures>;
677
+ }
678
+ /**
679
+ * A scaffold for defining a service's procedures.
680
+ *
681
+ * @see {@link ServiceSchema.scaffold}
682
+ */
683
+ declare class ServiceScaffold<State extends object> {
684
+ /**
685
+ * The configuration for this service.
686
+ */
687
+ protected readonly config: ServiceConfiguration<State>;
688
+ /**
689
+ * @param config - The configuration for this service.
690
+ */
691
+ constructor(config: ServiceConfiguration<State>);
692
+ /**
693
+ * Define procedures for this service. Use the {@link Procedure} constructors
694
+ * to create them. This returns the procedures object, which can then be
695
+ * passed to {@link ServiceSchema.finalize} to create a {@link ServiceSchema}.
696
+ *
697
+ * @example
698
+ * ```
699
+ * const myProcedures = MyServiceScaffold.procedures({
700
+ * myRPC: Procedure.rpc({
701
+ * // ...
702
+ * }),
703
+ * });
704
+ *
705
+ * const MyService = MyServiceScaffold.finalize({
706
+ * ...myProcedures,
707
+ * });
708
+ * ```
709
+ *
710
+ * @param procedures - The procedures for this service.
711
+ */
712
+ procedures<T extends BrandedProcedureMap<State>>(procedures: T): T;
713
+ /**
714
+ * Finalizes the scaffold into a {@link ServiceSchema}. This is where you
715
+ * provide the service's procedures and get a {@link ServiceSchema} in return.
716
+ *
717
+ * You can directly define procedures here, or you can define them separately
718
+ * with the {@link ServiceScaffold.procedures} method, and then pass them here.
719
+ *
720
+ * @example
721
+ * ```
722
+ * const MyService = MyServiceScaffold.finalize({
723
+ * myRPC: Procedure.rpc({
724
+ * // ...
725
+ * }),
726
+ * // e.g. from the procedures method
727
+ * ...myOtherProcedures,
728
+ * });
729
+ * ```
730
+ */
731
+ finalize<T extends BrandedProcedureMap<State>>(procedures: T): ServiceSchema<State, {
732
+ [K in keyof T]: Unbranded<T[K]>;
733
+ }>;
734
+ }
735
+
736
+ export { AnyServiceSchemaMap as A, Output as B, Client as C, Err as E, InstantiatedServiceSchemaMap as I, Ok as O, PayloadType as P, RiverError as R, ServiceContext as S, UploadProcedure as U, ValidProcType as V, Procedure as a, Result as b, RiverUncaughtSchema as c, ProcedureResult as d, Service as e, ServiceConfiguration as f, ProcHandler as g, ProcInit as h, ProcInput as i, ProcOutput as j, ProcErrors as k, ProcType as l, ServiceSchema as m, SerializedServerSchema as n, ProcedureMap as o, RPCProcedure as p, SubscriptionProcedure as q, StreamProcedure as r, serializeSchema as s, createClient as t, ServiceContextWithState as u, ServiceContextWithTransportInfo as v, UNCAUGHT_ERROR as w, RiverErrorSchema as x, ResultUnwrapOk as y, ResultUnwrapErr as z };