export { ProtoCodec } from './codec.js'; import { DescService, DescMethod, DescMethodUnary, MessageShape, MessageInitShape, DescMethodServerStreaming, DescMethodClientStreaming, DescMethodBiDiStreaming, DescMessage } from '@bufbuild/protobuf'; import { TSchema, Static } from 'typebox'; import { C as ClientTransport } from '../client-C8pwDvTN.js'; import { A as SessionId, C as Connection, n as ClientHandshakeOptions, q as ConnectionExtras, r as ServerHandshakeOptions } from '../transport-DF2T202E.js'; import { T as TransportClientId, C as CustomHandshakeErrorCodeSchema, j as HandshakeErrorCustomHandlerFatalResponseCodes, k as CustomHandshakeErrorCode, O as OpaqueTransportMessage } from '../message-C2qDAau6.js'; import { a2 as ErrorPayload, C as CANCEL_CODE, g as INVALID_REQUEST_CODE, U as UNCAUGHT_ERROR_CODE, T as UNEXPECTED_DISCONNECT_CODE, f as ErrResult, x as Result, X as Writable, s as Readable } from '../services-DPANPmhb.js'; export { E as Err, O as Ok, h as OkResult, t as ReadableBrokenError, u as ReadableResult, y as ResultUnwrapErr, z as ResultUnwrapOk } from '../services-DPANPmhb.js'; import { Span } from '@opentelemetry/api'; import { TUint8Array } from '../customSchemas/index.js'; import { S as ServerTransport } from '../server-D88e2r09.js'; import '../types-BGGvYIJM.js'; import '../index-CIMpdW6z.js'; import '../adapter-K2HsfQLt.js'; /** * Canonical RPC error codes shared by gRPC and Connect. * * The protobuf router uses these codes for unary rejections and streamed error * messages so applications can reason about familiar transport-agnostic error * categories. */ declare enum RiverErrorCode { OK = "OK", CANCELED = "CANCELED", UNKNOWN = "UNKNOWN", INVALID_ARGUMENT = "INVALID_ARGUMENT", DEADLINE_EXCEEDED = "DEADLINE_EXCEEDED", NOT_FOUND = "NOT_FOUND", ALREADY_EXISTS = "ALREADY_EXISTS", PERMISSION_DENIED = "PERMISSION_DENIED", RESOURCE_EXHAUSTED = "RESOURCE_EXHAUSTED", FAILED_PRECONDITION = "FAILED_PRECONDITION", ABORTED = "ABORTED", OUT_OF_RANGE = "OUT_OF_RANGE", UNIMPLEMENTED = "UNIMPLEMENTED", INTERNAL = "INTERNAL", UNAVAILABLE = "UNAVAILABLE", DATA_LOSS = "DATA_LOSS", UNAUTHENTICATED = "UNAUTHENTICATED" } /** * Protocol-level error codes surfaced by River itself rather than user * handlers. */ type ProtocolErrorCode = typeof CANCEL_CODE | typeof INVALID_REQUEST_CODE | typeof UNCAUGHT_ERROR_CODE | typeof UNEXPECTED_DISCONNECT_CODE; /** * Error codes visible from the protobuf client surface. */ type ClientErrorCode = RiverErrorCode | ProtocolErrorCode; /** * A serialized protobuf error detail. * * The `typeName` identifies the protobuf message descriptor the client can use * to decode `value`. */ interface RiverErrorDetail { readonly typeName: string; readonly value: Uint8Array; } /** * A plain-object error payload used by the protobuf router. * * Handlers return these via `Err({ code, message, ... })`. */ interface ClientError extends ErrorPayload { readonly code: ClientErrorCode; readonly metadata?: Readonly>; readonly details?: ReadonlyArray; } /** * A protocol error emitted by the River runtime. */ interface ProtocolError extends ClientError { readonly code: ProtocolErrorCode; } /** * Returns true when the given value matches the wire shape of a client error * with a canonical RPC error code. */ declare function isRiverError(value: unknown): value is ClientError; /** * Returns true when the given value is a protocol error. */ declare function isProtocolError(value: unknown): value is ProtocolError; /** * Returns true when the given value is any client-visible error. */ declare function isClientError(value: unknown): value is ClientError; /** * Returns true when the given value matches the `Err(...)` wrapper used for * protobuf cancel payloads sent by the runtime or handlers. */ declare function isSerializedClientErrorResult(value: unknown): value is ErrResult; /** * Returns true when the given value matches the protocol-only cancel payloads * sent by clients. */ declare function isSerializedProtocolErrorResult(value: unknown): value is ErrResult; /** * Context passed to protobuf handler invocations. * * User-provided `Context` is spread into the type so handler authors can * access application dependencies directly (e.g. `ctx.db`). Per-service * `State` is available via `ctx.state`. */ type ProtobufHandlerContext = Context & { /** * Per-service state created by {@link ProtoService}'s `initializeState`. */ readonly state: State; /** * The span for the current procedure call. */ readonly span: Span; /** * Metadata parsed during the transport handshake. */ readonly metadata: ParsedMetadata; /** * The session this invocation belongs to. */ readonly sessionId: SessionId; /** * The remote transport client id that initiated the invocation. */ readonly from: TransportClientId; /** * The protobuf service being invoked. */ readonly service: DescService; /** * The protobuf method being invoked. */ readonly method: DescMethod; /** * Register cleanup work that should run once the invocation finishes. */ readonly deferCleanup: (fn: () => void | Promise) => void; /** * Cancel the invocation and notify the client with a protocol-level cancel * error. */ readonly cancel: (message?: string) => ErrResult; /** * Aborts when the invocation finishes for any reason. */ readonly signal: AbortSignal; }; type Awaitable = T | PromiseLike; type HandlerResult = Result, ClientError>; /** * Options shared by protobuf-router client calls. */ interface CallOptions { readonly signal?: AbortSignal; } /** * The client-side surface for a client-streaming method. */ interface ClientStreamingCall { readonly reqWritable: Writable>; readonly finalize: () => Promise, ClientError>>; } /** * The client-side surface for a bidi-streaming method. */ interface BiDiStreamingCall { readonly reqWritable: Writable>; readonly resReadable: Readable, ClientError>; } /** * A protobuf-router unary handler. */ type UnaryImpl = (request: MessageShape, ctx: ProtobufHandlerContext) => Awaitable>; /** * A protobuf-router server-streaming handler. */ type ServerStreamingImpl = (param: { readonly request: MessageShape; readonly ctx: ProtobufHandlerContext; readonly resWritable: Writable>; }) => Awaitable; /** * A protobuf-router client-streaming handler. */ type ClientStreamingImpl = (param: { readonly ctx: ProtobufHandlerContext; readonly reqReadable: Readable, ProtocolError>; }) => Awaitable>; /** * A protobuf-router bidi-streaming handler. */ type BiDiStreamingImpl = (param: { readonly ctx: ProtobufHandlerContext; readonly reqReadable: Readable, ProtocolError>; readonly resWritable: Writable>; }) => Awaitable; /** * The handler type for an arbitrary protobuf method descriptor. */ type MethodImpl = Method extends DescMethodUnary ? UnaryImpl : Method extends DescMethodServerStreaming ? ServerStreamingImpl : Method extends DescMethodClientStreaming ? ClientStreamingImpl : Method extends DescMethodBiDiStreaming ? BiDiStreamingImpl : never; type RawMethodImpl = Method extends DescMethodUnary ? (request: Request, ctx: HandlerContext) => Awaitable> : Method extends DescMethodServerStreaming ? (param: { readonly request: Request; readonly ctx: HandlerContext; readonly resWritable: Writable>; }) => Awaitable : Method extends DescMethodClientStreaming ? (param: { readonly ctx: HandlerContext; readonly reqReadable: Readable; }) => Awaitable> : Method extends DescMethodBiDiStreaming ? (param: { readonly ctx: HandlerContext; readonly reqReadable: Readable; readonly resWritable: Writable>; }) => Awaitable : never; /** A raw handler owns protobuf-body validation; River still validates the envelope. */ type RawHandler = { readonly raw: 'both'; readonly handler: RawMethodImpl>; } | { readonly raw: 'output'; readonly handler: RawMethodImpl, ProtobufHandlerContext>; }; /** * Partial implementation shape for a protobuf service. * * All methods are optional -- missing methods return UNIMPLEMENTED at runtime. */ type ServiceImpl = { [MethodName in keyof Service['method']]?: MethodImpl; }; type ServiceImplWithRawHandlers = { [MethodName in keyof Service['method']]?: ServiceImpl[MethodName] | RawHandler; }; /** * The client surface for an arbitrary protobuf method descriptor. */ type ClientMethod = Method extends DescMethodUnary ? (request: MessageInitShape, options?: CallOptions) => Promise, ClientError>> : Method extends DescMethodServerStreaming ? (request: MessageInitShape, options?: CallOptions) => Readable, ClientError> : Method extends DescMethodClientStreaming ? (options?: CallOptions) => ClientStreamingCall : Method extends DescMethodBiDiStreaming ? (options?: CallOptions) => BiDiStreamingCall : never; /** * The generated client shape for a protobuf service descriptor. */ type Client = { [MethodName in keyof Service['method']]: Service['method'][MethodName] extends DescMethod ? ClientMethod : never; }; /** * Options for the protobuf client. */ interface ClientOptions { readonly connectOnInvoke: boolean; readonly eagerlyConnect: boolean; } /** * Creates a protobuf client for a single protobuf service descriptor. */ declare function createClient(service: Service, transport: ClientTransport, serverId: TransportClientId, providedClientOptions?: Partial; }>): Client; declare const HandshakeBytesSchema: TUint8Array; type ProtobufHandshakeFailureCode = Static; type ConstructHandshake = () => MessageInitShape | Promise>; type ValidateHandshake = (metadata: MessageShape, previousParsedMetadata?: ParsedMetadata, from?: TransportClientId, connectionExtras?: ConnectionExtras) => ParsedMetadata | ProtobufHandshakeFailureCode | CustomHandshakeErrorCode | Promise>; /** * Create client-side handshake options backed by a protobuf message type. */ declare function createClientHandshakeOptions(schema: Schema, construct: ConstructHandshake, eager?: boolean, rejectionCodeSchema?: RejectionCodeSchema): ClientHandshakeOptions; /** * Create server-side handshake options backed by a protobuf message type. */ declare function createServerHandshakeOptions(schema: Schema, validate: ValidateHandshake>, expiry?: (parsedMetadata: ParsedMetadata) => Date | undefined, rejectionCodeSchema?: RejectionCodeSchema): ServerHandshakeOptions; /** * An object that may implement async or sync disposal. */ type MaybeDisposable> = T & { [Symbol.asyncDispose]?: () => PromiseLike; [Symbol.dispose]?: () => void; }; /** * Stored registration for a single protobuf method handler. */ interface RegisteredMethod { readonly service: DescService; readonly method: DescMethod; readonly impl: MethodImpl; readonly raw?: 'both' | 'output'; } /** * An instantiated protobuf service with initialized state and a disposal hook. */ interface InstantiatedProtoService { readonly descriptor: DescService; readonly state: MaybeDisposable; readonly methods: ReadonlyMap; [Symbol.asyncDispose]: () => PromiseLike; } /** * Type-erased interface used by the server to interact with a * service definition without knowing its full generic signature. */ interface AnyProtoService { readonly descriptor: DescService; readonly methods: ReadonlyMap; instantiate(ctx: object): InstantiatedProtoService; } interface ServiceConfiguration { initializeState: (ctx: Context) => MaybeDisposable; } /** * A scaffold for defining a protobuf service's handlers across multiple files. * * @see {@link ProtoServiceSchema.scaffold} */ declare class ProtoServiceScaffold { private readonly descriptor; private readonly config; constructor(descriptor: Service, config: ServiceConfiguration); /** * Type-check a partial set of handler implementations against this * service's types. Returns the input unchanged -- this is purely a * type-level helper for splitting handlers across files. * * @param handlers - A partial set of method implementations. */ procedures(handlers: ServiceImpl): ServiceImpl; /** * Finalize the scaffold into a service definition. Provide all handlers * here (or spread in handler objects from {@link procedures}). * * @param handlers - Method implementations (missing methods return * UNIMPLEMENTED at runtime). */ finalize(handlers: ServiceImpl): { readonly descriptor: Service; readonly methods: ReadonlyMap; /** @internal */ readonly initializeStateFn: ((ctx: Context) => MaybeDisposable) | undefined; /** * Create a live service instance with initialized state. * * @param ctx - The user-provided context, passed to `initializeState`. */ instantiate(ctx: Context): InstantiatedProtoService; }; } /** * Creates a factory for defining protobuf services with typed context and * metadata. * * This mirrors {@link createServiceSchema} from the TypeBox router. The * factory binds the `Context` and `ParsedMetadata` types, then provides * `.define()` and `.scaffold()` methods for creating service definitions. * * @example * ```ts * const ProtoService = createProtoService(); * * // all-in-one (stateless) * const testSvc = ProtoService.define(TestService, { * echo: (req, ctx) => Ok({ text: req.text }), * }); * * // all-in-one (with state) * const testSvc = ProtoService.define( * TestService, * { initializeState: (ctx) => ({ counter: 0 }) }, * { * echo: (req, ctx) => { * ctx.state.counter++; * return Ok({ text: req.text }); * }, * }, * ); * * // scaffold for file-splitting * const scaffold = ProtoService.scaffold(TestService, { * initializeState: (ctx) => ({ counter: 0 }), * }); * const echoHandlers = scaffold.procedures({ * echo: (req, ctx) => Ok({ text: req.text }), * }); * const testSvc = scaffold.finalize({ * ...echoHandlers, * }); * * const server = createServer(transport, [testSvc], { * context: myAppContext, * }); * ``` */ declare function createProtoService(): { new (descriptor: Service, initializeStateFn: ((ctx: Context) => MaybeDisposable) | undefined, methods: Map): { readonly descriptor: Service; readonly methods: ReadonlyMap; /** @internal */ readonly initializeStateFn: ((ctx: Context) => MaybeDisposable) | undefined; /** * Create a live service instance with initialized state. * * @param ctx - The user-provided context, passed to `initializeState`. */ instantiate(ctx: Context): InstantiatedProtoService; }; define(descriptor: S, handlers: ServiceImplWithRawHandlers): { readonly descriptor: S; readonly methods: ReadonlyMap; /** @internal */ readonly initializeStateFn: ((ctx: Context) => MaybeDisposable) | undefined; /** * Create a live service instance with initialized state. * * @param ctx - The user-provided context, passed to `initializeState`. */ instantiate(ctx: Context): InstantiatedProtoService; }; define(descriptor: S_1, config: ServiceConfiguration, handlers: ServiceImplWithRawHandlers): { readonly descriptor: S_1; readonly methods: ReadonlyMap; /** @internal */ readonly initializeStateFn: ((ctx: Context) => MaybeDisposable) | undefined; /** * Create a live service instance with initialized state. * * @param ctx - The user-provided context, passed to `initializeState`. */ instantiate(ctx: Context): InstantiatedProtoService; }; define(descriptor: S_2, handlers: ServiceImpl): { readonly descriptor: S_2; readonly methods: ReadonlyMap; /** @internal */ readonly initializeStateFn: ((ctx: Context) => MaybeDisposable) | undefined; /** * Create a live service instance with initialized state. * * @param ctx - The user-provided context, passed to `initializeState`. */ instantiate(ctx: Context): InstantiatedProtoService; }; define(descriptor: S_3, config: ServiceConfiguration, handlers: ServiceImpl): { readonly descriptor: S_3; readonly methods: ReadonlyMap; /** @internal */ readonly initializeStateFn: ((ctx: Context) => MaybeDisposable) | undefined; /** * Create a live service instance with initialized state. * * @param ctx - The user-provided context, passed to `initializeState`. */ instantiate(ctx: Context): InstantiatedProtoService; }; /** * Create a scaffold for splitting handler implementations across files. * * @param descriptor - The generated protobuf service descriptor. * @param config - Service configuration including `initializeState`. */ scaffold(descriptor: S_4, config: ServiceConfiguration): ProtoServiceScaffold; }; type StreamId = string; interface ProcStream { readonly streamId: StreamId; readonly from: TransportClientId; readonly service: DescService; readonly method: DescMethod; readonly handleMsg: (msg: OpaqueTransportMessage) => void; readonly handleSessionDisconnect: () => void; } /** * Server instance for the protobuf router. */ interface Server { readonly streams: Map; close(): Promise; } /** * Context passed to protobuf middleware. */ type MiddlewareContext = Readonly, 'cancel'>> & { readonly streamId: StreamId; readonly procedureName: string; readonly serviceName: string; }; /** * Parameters passed to protobuf middleware. */ interface MiddlewareParam { readonly ctx: MiddlewareContext; readonly reqInit: MessageShape | null; next: () => void; } /** * Middleware is a function that can inspect protobuf requests as they are * received. */ type Middleware = (param: MiddlewareParam) => void; /** * Options for creating a protobuf server. */ interface ServerOptions { readonly extendedContext?: object; readonly handshakeOptions?: ServerHandshakeOptions; readonly middlewares?: Array>; readonly maxCancelledStreamTombstonesPerSession?: number; } /** * Creates a protobuf server that listens on an existing River transport. * * @param transport - The server transport to listen on. * @param services - Array of {@link ProtoService} definitions. * @param options - Server options including context, handshake, and middleware. */ declare function createServer(transport: ServerTransport, services: ReadonlyArray, options?: ServerOptions): Server; export { type AnyProtoService, type BiDiStreamingCall, CANCEL_CODE, type CallOptions, type Client, type ClientError, type ClientErrorCode, type ClientMethod, type ClientStreamingCall, ErrResult, INVALID_REQUEST_CODE, type InstantiatedProtoService, type MaybeDisposable, type MethodImpl, type Middleware, type MiddlewareContext, type MiddlewareParam, type ClientOptions as ProtobufClientOptions, type ProtobufHandlerContext, type ServerOptions as ProtobufServerOptions, type ProtocolError, type ProtocolErrorCode, type RawHandler, Readable, Result, RiverErrorCode, type RiverErrorDetail, type Server, type ServiceImpl, type ServiceImplWithRawHandlers, UNCAUGHT_ERROR_CODE, UNEXPECTED_DISCONNECT_CODE, Writable, createClient, createClientHandshakeOptions, createProtoService, createServer, createServerHandshakeOptions, isClientError, isProtocolError, isRiverError, isSerializedClientErrorResult, isSerializedProtocolErrorResult };