@orpc/standard-server-peer 0.0.0-next.0021fba

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 oRPC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,77 @@
1
+ <div align="center">
2
+ <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 alt="oRPC logo" />
3
+ </div>
4
+
5
+ <h1></h1>
6
+
7
+ <div align="center">
8
+ <a href="https://codecov.io/gh/unnoq/orpc">
9
+ <img alt="codecov" src="https://codecov.io/gh/unnoq/orpc/branch/main/graph/badge.svg">
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/@orpc/standard-server-peer">
12
+ <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fstandard-server-peer?logo=npm" />
13
+ </a>
14
+ <a href="https://github.com/unnoq/orpc/blob/main/LICENSE">
15
+ <img alt="MIT License" src="https://img.shields.io/github/license/unnoq/orpc?logo=open-source-initiative" />
16
+ </a>
17
+ <a href="https://discord.gg/TXEbwRBvQn">
18
+ <img alt="Discord" src="https://img.shields.io/discord/1308966753044398161?color=7389D8&label&logo=discord&logoColor=ffffff" />
19
+ </a>
20
+ </div>
21
+
22
+ <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
23
+
24
+ **oRPC is a powerful combination of RPC and OpenAPI**, makes it easy to build APIs that are end-to-end type-safe and adhere to OpenAPI standards
25
+
26
+ ---
27
+
28
+ ## Highlights
29
+
30
+ - **🔗 End-to-End Type Safety**: Ensure type-safe inputs, outputs, and errors from client to server.
31
+ - **📘 First-Class OpenAPI**: Built-in support that fully adheres to the OpenAPI standard.
32
+ - **📝 Contract-First Development**: Optionally define your API contract before implementation.
33
+ - **🔍 First-Class OpenTelemetry**: Seamlessly integrate with OpenTelemetry for observability.
34
+ - **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte, Angular), Pinia Colada, and more.
35
+ - **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms.
36
+ - **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators.
37
+ - **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more.
38
+ - **⏱️ Lazy Router**: Enhance cold start times with our lazy routing feature.
39
+ - **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming.
40
+ - **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond.
41
+ - **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors.
42
+
43
+ ## Documentation
44
+
45
+ You can find the full documentation [here](https://orpc.unnoq.com).
46
+
47
+ ## Packages
48
+
49
+ - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
50
+ - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
51
+ - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
52
+ - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
53
+ - [@orpc/otel](https://www.npmjs.com/package/@orpc/otel): [OpenTelemetry](https://opentelemetry.io/) integration for observability.
54
+ - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with [NestJS](https://nestjs.com/).
55
+ - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
56
+ - [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration.
57
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
58
+ - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
59
+ - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
60
+ - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
61
+ - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
62
+
63
+ ## `@orpc/standard-server-peer`
64
+
65
+ Provides a standard interface for oRPC server adapters to interact with connected peers across various transports (e.g., WebSocket, IPC).
66
+
67
+ ## Sponsors
68
+
69
+ <p align="center">
70
+ <a href="https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg">
71
+ <img src='https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg'/>
72
+ </a>
73
+ </p>
74
+
75
+ ## License
76
+
77
+ Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
@@ -0,0 +1,134 @@
1
+ import { Promisable, AsyncIdQueueCloseOptions as AsyncIdQueueCloseOptions$1, SetSpanErrorOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClass } from '@orpc/shared';
2
+ import { StandardRequest, StandardResponse, EventMeta } from '@orpc/standard-server';
3
+
4
+ type EncodedMessage = string | ArrayBufferLike | Uint8Array;
5
+ interface EncodedMessageSendFn {
6
+ (message: EncodedMessage): Promisable<void>;
7
+ }
8
+
9
+ interface ClientPeerCloseOptions extends AsyncIdQueueCloseOptions$1 {
10
+ /**
11
+ * Should abort or not?
12
+ *
13
+ * @default true
14
+ */
15
+ abort?: boolean;
16
+ }
17
+ declare class ClientPeer {
18
+ private readonly idGenerator;
19
+ /**
20
+ * Queue of responses sent from server, awaiting consumption
21
+ */
22
+ private readonly responseQueue;
23
+ /**
24
+ * Queue of event iterator messages sent from server, awaiting consumption
25
+ */
26
+ private readonly serverEventIteratorQueue;
27
+ /**
28
+ * Controllers used to signal that the client should stop sending event iterator messages
29
+ */
30
+ private readonly serverControllers;
31
+ /**
32
+ * Cleanup functions invoked when the request/response is closed
33
+ */
34
+ private readonly cleanupFns;
35
+ private readonly send;
36
+ constructor(send: EncodedMessageSendFn);
37
+ get length(): number;
38
+ open(id: string): AbortController;
39
+ request(request: StandardRequest): Promise<StandardResponse>;
40
+ message(raw: EncodedMessage): Promise<void>;
41
+ close(options?: AsyncIdQueueCloseOptions$1): void;
42
+ }
43
+
44
+ declare enum MessageType {
45
+ REQUEST = 1,
46
+ RESPONSE = 2,
47
+ EVENT_ITERATOR = 3,
48
+ ABORT_SIGNAL = 4
49
+ }
50
+ type EventIteratorEvent = 'message' | 'error' | 'done';
51
+ interface EventIteratorPayload {
52
+ event: EventIteratorEvent;
53
+ data: unknown;
54
+ meta?: EventMeta;
55
+ }
56
+ interface RequestMessageMap {
57
+ [MessageType.REQUEST]: Omit<StandardRequest, 'signal'>;
58
+ [MessageType.EVENT_ITERATOR]: EventIteratorPayload;
59
+ [MessageType.ABORT_SIGNAL]: void;
60
+ }
61
+ interface ResponseMessageMap {
62
+ [MessageType.RESPONSE]: StandardResponse;
63
+ [MessageType.EVENT_ITERATOR]: EventIteratorPayload;
64
+ [MessageType.ABORT_SIGNAL]: void;
65
+ }
66
+ type DecodedMessageUnion<TMap extends RequestMessageMap | ResponseMessageMap> = {
67
+ [K in keyof TMap]: [id: string, type: K, payload: TMap[K]];
68
+ }[keyof TMap];
69
+ type DecodedRequestMessage = DecodedMessageUnion<RequestMessageMap>;
70
+ type DecodedResponseMessage = DecodedMessageUnion<ResponseMessageMap>;
71
+ declare function encodeRequestMessage<T extends keyof RequestMessageMap>(id: string, type: T, payload: RequestMessageMap[T]): Promise<EncodedMessage>;
72
+ declare function decodeRequestMessage(raw: EncodedMessage): Promise<DecodedRequestMessage>;
73
+ declare function encodeResponseMessage<T extends keyof ResponseMessageMap>(id: string, type: T, payload: ResponseMessageMap[T]): Promise<EncodedMessage>;
74
+ declare function decodeResponseMessage(raw: EncodedMessage): Promise<DecodedResponseMessage>;
75
+
76
+ interface AsyncIdQueueCloseOptions {
77
+ id?: string;
78
+ reason?: unknown;
79
+ }
80
+ declare class AsyncIdQueue<T> {
81
+ private readonly openIds;
82
+ private readonly items;
83
+ private readonly pendingPulls;
84
+ get length(): number;
85
+ open(id: string): void;
86
+ isOpen(id: string): boolean;
87
+ push(id: string, item: T): void;
88
+ pull(id: string): Promise<T>;
89
+ close({ id, reason }?: AsyncIdQueueCloseOptions): void;
90
+ assertOpen(id: string): void;
91
+ }
92
+
93
+ interface ToEventIteratorOptions extends SetSpanErrorOptions {
94
+ }
95
+ declare function toEventIterator(queue: AsyncIdQueue<EventIteratorPayload>, id: string, cleanup: AsyncIteratorClassCleanupFn, options?: ToEventIteratorOptions): AsyncIteratorClass<unknown>;
96
+ declare function resolveEventIterator(iterator: AsyncIterator<any>, callback: (payload: EventIteratorPayload) => Promise<'next' | 'abort'>): Promise<void>;
97
+
98
+ interface ServerPeerHandleRequestFn {
99
+ (request: StandardRequest): Promise<StandardResponse>;
100
+ }
101
+ interface ServerPeerCloseOptions extends AsyncIdQueueCloseOptions$1 {
102
+ /**
103
+ * Should abort or not?
104
+ *
105
+ * @default true
106
+ */
107
+ abort?: boolean;
108
+ }
109
+ declare class ServerPeer {
110
+ /**
111
+ * Queue of event iterator messages sent from client, awaiting consumption
112
+ */
113
+ private readonly clientEventIteratorQueue;
114
+ /**
115
+ * Map of active client request controllers, should be synced to request signal
116
+ */
117
+ private readonly clientControllers;
118
+ private readonly send;
119
+ constructor(send: EncodedMessageSendFn);
120
+ get length(): number;
121
+ open(id: string): AbortController;
122
+ /**
123
+ * @todo This method will return Promise<void> in the next major version.
124
+ */
125
+ message(raw: EncodedMessage, handleRequest?: ServerPeerHandleRequestFn): Promise<[id: string, StandardRequest | undefined]>;
126
+ /**
127
+ * @deprecated Please pass the `handleRequest` (second arg) function to the `message` method instead.
128
+ */
129
+ response(id: string, response: StandardResponse): Promise<void>;
130
+ close({ abort, ...options }?: ServerPeerCloseOptions): void;
131
+ }
132
+
133
+ export { ClientPeer, MessageType, ServerPeer, decodeRequestMessage, decodeResponseMessage, encodeRequestMessage, encodeResponseMessage, resolveEventIterator, toEventIterator };
134
+ export type { ClientPeerCloseOptions, DecodedRequestMessage, DecodedResponseMessage, EncodedMessage, EncodedMessageSendFn, EventIteratorEvent, EventIteratorPayload, RequestMessageMap, ResponseMessageMap, ServerPeerCloseOptions, ServerPeerHandleRequestFn, ToEventIteratorOptions };
@@ -0,0 +1,134 @@
1
+ import { Promisable, AsyncIdQueueCloseOptions as AsyncIdQueueCloseOptions$1, SetSpanErrorOptions, AsyncIteratorClassCleanupFn, AsyncIteratorClass } from '@orpc/shared';
2
+ import { StandardRequest, StandardResponse, EventMeta } from '@orpc/standard-server';
3
+
4
+ type EncodedMessage = string | ArrayBufferLike | Uint8Array;
5
+ interface EncodedMessageSendFn {
6
+ (message: EncodedMessage): Promisable<void>;
7
+ }
8
+
9
+ interface ClientPeerCloseOptions extends AsyncIdQueueCloseOptions$1 {
10
+ /**
11
+ * Should abort or not?
12
+ *
13
+ * @default true
14
+ */
15
+ abort?: boolean;
16
+ }
17
+ declare class ClientPeer {
18
+ private readonly idGenerator;
19
+ /**
20
+ * Queue of responses sent from server, awaiting consumption
21
+ */
22
+ private readonly responseQueue;
23
+ /**
24
+ * Queue of event iterator messages sent from server, awaiting consumption
25
+ */
26
+ private readonly serverEventIteratorQueue;
27
+ /**
28
+ * Controllers used to signal that the client should stop sending event iterator messages
29
+ */
30
+ private readonly serverControllers;
31
+ /**
32
+ * Cleanup functions invoked when the request/response is closed
33
+ */
34
+ private readonly cleanupFns;
35
+ private readonly send;
36
+ constructor(send: EncodedMessageSendFn);
37
+ get length(): number;
38
+ open(id: string): AbortController;
39
+ request(request: StandardRequest): Promise<StandardResponse>;
40
+ message(raw: EncodedMessage): Promise<void>;
41
+ close(options?: AsyncIdQueueCloseOptions$1): void;
42
+ }
43
+
44
+ declare enum MessageType {
45
+ REQUEST = 1,
46
+ RESPONSE = 2,
47
+ EVENT_ITERATOR = 3,
48
+ ABORT_SIGNAL = 4
49
+ }
50
+ type EventIteratorEvent = 'message' | 'error' | 'done';
51
+ interface EventIteratorPayload {
52
+ event: EventIteratorEvent;
53
+ data: unknown;
54
+ meta?: EventMeta;
55
+ }
56
+ interface RequestMessageMap {
57
+ [MessageType.REQUEST]: Omit<StandardRequest, 'signal'>;
58
+ [MessageType.EVENT_ITERATOR]: EventIteratorPayload;
59
+ [MessageType.ABORT_SIGNAL]: void;
60
+ }
61
+ interface ResponseMessageMap {
62
+ [MessageType.RESPONSE]: StandardResponse;
63
+ [MessageType.EVENT_ITERATOR]: EventIteratorPayload;
64
+ [MessageType.ABORT_SIGNAL]: void;
65
+ }
66
+ type DecodedMessageUnion<TMap extends RequestMessageMap | ResponseMessageMap> = {
67
+ [K in keyof TMap]: [id: string, type: K, payload: TMap[K]];
68
+ }[keyof TMap];
69
+ type DecodedRequestMessage = DecodedMessageUnion<RequestMessageMap>;
70
+ type DecodedResponseMessage = DecodedMessageUnion<ResponseMessageMap>;
71
+ declare function encodeRequestMessage<T extends keyof RequestMessageMap>(id: string, type: T, payload: RequestMessageMap[T]): Promise<EncodedMessage>;
72
+ declare function decodeRequestMessage(raw: EncodedMessage): Promise<DecodedRequestMessage>;
73
+ declare function encodeResponseMessage<T extends keyof ResponseMessageMap>(id: string, type: T, payload: ResponseMessageMap[T]): Promise<EncodedMessage>;
74
+ declare function decodeResponseMessage(raw: EncodedMessage): Promise<DecodedResponseMessage>;
75
+
76
+ interface AsyncIdQueueCloseOptions {
77
+ id?: string;
78
+ reason?: unknown;
79
+ }
80
+ declare class AsyncIdQueue<T> {
81
+ private readonly openIds;
82
+ private readonly items;
83
+ private readonly pendingPulls;
84
+ get length(): number;
85
+ open(id: string): void;
86
+ isOpen(id: string): boolean;
87
+ push(id: string, item: T): void;
88
+ pull(id: string): Promise<T>;
89
+ close({ id, reason }?: AsyncIdQueueCloseOptions): void;
90
+ assertOpen(id: string): void;
91
+ }
92
+
93
+ interface ToEventIteratorOptions extends SetSpanErrorOptions {
94
+ }
95
+ declare function toEventIterator(queue: AsyncIdQueue<EventIteratorPayload>, id: string, cleanup: AsyncIteratorClassCleanupFn, options?: ToEventIteratorOptions): AsyncIteratorClass<unknown>;
96
+ declare function resolveEventIterator(iterator: AsyncIterator<any>, callback: (payload: EventIteratorPayload) => Promise<'next' | 'abort'>): Promise<void>;
97
+
98
+ interface ServerPeerHandleRequestFn {
99
+ (request: StandardRequest): Promise<StandardResponse>;
100
+ }
101
+ interface ServerPeerCloseOptions extends AsyncIdQueueCloseOptions$1 {
102
+ /**
103
+ * Should abort or not?
104
+ *
105
+ * @default true
106
+ */
107
+ abort?: boolean;
108
+ }
109
+ declare class ServerPeer {
110
+ /**
111
+ * Queue of event iterator messages sent from client, awaiting consumption
112
+ */
113
+ private readonly clientEventIteratorQueue;
114
+ /**
115
+ * Map of active client request controllers, should be synced to request signal
116
+ */
117
+ private readonly clientControllers;
118
+ private readonly send;
119
+ constructor(send: EncodedMessageSendFn);
120
+ get length(): number;
121
+ open(id: string): AbortController;
122
+ /**
123
+ * @todo This method will return Promise<void> in the next major version.
124
+ */
125
+ message(raw: EncodedMessage, handleRequest?: ServerPeerHandleRequestFn): Promise<[id: string, StandardRequest | undefined]>;
126
+ /**
127
+ * @deprecated Please pass the `handleRequest` (second arg) function to the `message` method instead.
128
+ */
129
+ response(id: string, response: StandardResponse): Promise<void>;
130
+ close({ abort, ...options }?: ServerPeerCloseOptions): void;
131
+ }
132
+
133
+ export { ClientPeer, MessageType, ServerPeer, decodeRequestMessage, decodeResponseMessage, encodeRequestMessage, encodeResponseMessage, resolveEventIterator, toEventIterator };
134
+ export type { ClientPeerCloseOptions, DecodedRequestMessage, DecodedResponseMessage, EncodedMessage, EncodedMessageSendFn, EventIteratorEvent, EventIteratorPayload, RequestMessageMap, ResponseMessageMap, ServerPeerCloseOptions, ServerPeerHandleRequestFn, ToEventIteratorOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,569 @@
1
+ import { isAsyncIteratorObject, stringifyJSON, readAsBuffer, AsyncIteratorClass, startSpan, runInSpanContext, isTypescriptObject, setSpanError, runWithSpan, SequentialIdGenerator, AsyncIdQueue, getGlobalOtelConfig, clone, AbortError } from '@orpc/shared';
2
+ import { generateContentDisposition, flattenHeader, getFilenameFromContentDisposition, withEventMeta, ErrorEvent, getEventMeta, isEventIteratorHeaders, HibernationEventIterator } from '@orpc/standard-server';
3
+
4
+ var MessageType = /* @__PURE__ */ ((MessageType2) => {
5
+ MessageType2[MessageType2["REQUEST"] = 1] = "REQUEST";
6
+ MessageType2[MessageType2["RESPONSE"] = 2] = "RESPONSE";
7
+ MessageType2[MessageType2["EVENT_ITERATOR"] = 3] = "EVENT_ITERATOR";
8
+ MessageType2[MessageType2["ABORT_SIGNAL"] = 4] = "ABORT_SIGNAL";
9
+ return MessageType2;
10
+ })(MessageType || {});
11
+ async function encodeRequestMessage(id, type, payload) {
12
+ if (type === 3 /* EVENT_ITERATOR */) {
13
+ const eventPayload = payload;
14
+ const serializedPayload2 = {
15
+ e: eventPayload.event,
16
+ d: eventPayload.data,
17
+ m: eventPayload.meta
18
+ };
19
+ return encodeRawMessage({ i: id, t: type, p: serializedPayload2 });
20
+ }
21
+ if (type === 4 /* ABORT_SIGNAL */) {
22
+ return encodeRawMessage({ i: id, t: type, p: payload });
23
+ }
24
+ const request = payload;
25
+ const { body: processedBody, headers: processedHeaders } = await serializeBodyAndHeaders(
26
+ request.body,
27
+ request.headers
28
+ );
29
+ const serializedPayload = {
30
+ u: request.url.toString().replace(/^orpc:\//, "/"),
31
+ b: processedBody instanceof Blob ? void 0 : processedBody,
32
+ h: Object.keys(processedHeaders).length > 0 ? processedHeaders : void 0,
33
+ m: request.method === "POST" ? void 0 : request.method
34
+ };
35
+ const baseMessage = {
36
+ i: id,
37
+ p: serializedPayload
38
+ };
39
+ if (processedBody instanceof Blob) {
40
+ return encodeRawMessage(baseMessage, processedBody);
41
+ }
42
+ return encodeRawMessage(baseMessage);
43
+ }
44
+ async function decodeRequestMessage(raw) {
45
+ const { json: message, buffer } = await decodeRawMessage(raw);
46
+ const id = message.i;
47
+ const type = message.t;
48
+ if (type === 3 /* EVENT_ITERATOR */) {
49
+ const payload2 = message.p;
50
+ return [id, type, { event: payload2.e, data: payload2.d, meta: payload2.m }];
51
+ }
52
+ if (type === 4 /* ABORT_SIGNAL */) {
53
+ return [id, type, message.p];
54
+ }
55
+ const payload = message.p;
56
+ const headers = payload.h ?? {};
57
+ const body = await deserializeBody(headers, payload.b, buffer);
58
+ return [id, 1 /* REQUEST */, { url: new URL(payload.u, "orpc:/"), headers, method: payload.m ?? "POST", body }];
59
+ }
60
+ async function encodeResponseMessage(id, type, payload) {
61
+ if (type === 3 /* EVENT_ITERATOR */) {
62
+ const eventPayload = payload;
63
+ const serializedPayload2 = {
64
+ e: eventPayload.event,
65
+ d: eventPayload.data,
66
+ m: eventPayload.meta
67
+ };
68
+ return encodeRawMessage({ i: id, t: type, p: serializedPayload2 });
69
+ }
70
+ if (type === 4 /* ABORT_SIGNAL */) {
71
+ return encodeRawMessage({ i: id, t: type, p: void 0 });
72
+ }
73
+ const response = payload;
74
+ const { body: processedBody, headers: processedHeaders } = await serializeBodyAndHeaders(
75
+ response.body,
76
+ response.headers
77
+ );
78
+ const serializedPayload = {
79
+ s: response.status === 200 ? void 0 : response.status,
80
+ h: Object.keys(processedHeaders).length > 0 ? processedHeaders : void 0,
81
+ b: processedBody instanceof Blob ? void 0 : processedBody
82
+ };
83
+ const baseMessage = {
84
+ i: id,
85
+ p: serializedPayload
86
+ };
87
+ if (processedBody instanceof Blob) {
88
+ return encodeRawMessage(baseMessage, processedBody);
89
+ }
90
+ return encodeRawMessage(baseMessage);
91
+ }
92
+ async function decodeResponseMessage(raw) {
93
+ const { json: message, buffer } = await decodeRawMessage(raw);
94
+ const id = message.i;
95
+ const type = message.t;
96
+ if (type === 3 /* EVENT_ITERATOR */) {
97
+ const payload2 = message.p;
98
+ return [id, type, { event: payload2.e, data: payload2.d, meta: payload2.m }];
99
+ }
100
+ if (type === 4 /* ABORT_SIGNAL */) {
101
+ return [id, type, message.p];
102
+ }
103
+ const payload = message.p;
104
+ const headers = payload.h ?? {};
105
+ const body = await deserializeBody(headers, payload.b, buffer);
106
+ return [id, 2 /* RESPONSE */, { status: payload.s ?? 200, headers, body }];
107
+ }
108
+ async function serializeBodyAndHeaders(body, originalHeaders) {
109
+ const headers = { ...originalHeaders };
110
+ const originalContentDisposition = headers["content-disposition"];
111
+ delete headers["content-type"];
112
+ delete headers["content-disposition"];
113
+ if (body instanceof Blob) {
114
+ headers["content-type"] = body.type;
115
+ headers["content-disposition"] = originalContentDisposition ?? generateContentDisposition(
116
+ body instanceof File ? body.name : "blob"
117
+ );
118
+ return { body, headers };
119
+ }
120
+ if (body instanceof FormData) {
121
+ const tempRes = new Response(body);
122
+ headers["content-type"] = tempRes.headers.get("content-type");
123
+ const formDataBlob = await tempRes.blob();
124
+ return { body: formDataBlob, headers };
125
+ }
126
+ if (body instanceof URLSearchParams) {
127
+ headers["content-type"] = "application/x-www-form-urlencoded";
128
+ return { body: body.toString(), headers };
129
+ }
130
+ if (isAsyncIteratorObject(body)) {
131
+ headers["content-type"] = "text/event-stream";
132
+ return { body: void 0, headers };
133
+ }
134
+ return { body, headers };
135
+ }
136
+ async function deserializeBody(headers, body, buffer) {
137
+ const contentType = flattenHeader(headers["content-type"]);
138
+ const contentDisposition = flattenHeader(headers["content-disposition"]);
139
+ if (typeof contentDisposition === "string") {
140
+ const filename = getFilenameFromContentDisposition(contentDisposition) ?? "blob";
141
+ return new File(buffer === void 0 ? [] : [buffer], filename, { type: contentType });
142
+ }
143
+ if (contentType?.startsWith("multipart/form-data")) {
144
+ const tempRes = new Response(buffer, { headers: { "content-type": contentType } });
145
+ return tempRes.formData();
146
+ }
147
+ if (contentType?.startsWith("application/x-www-form-urlencoded") && typeof body === "string") {
148
+ return new URLSearchParams(body);
149
+ }
150
+ return body;
151
+ }
152
+ const JSON_AND_BINARY_DELIMITER = 255;
153
+ async function encodeRawMessage(data, blob) {
154
+ const json = stringifyJSON(data);
155
+ if (blob === void 0 || blob.size === 0) {
156
+ return json;
157
+ }
158
+ return readAsBuffer(new Blob([
159
+ new TextEncoder().encode(json),
160
+ new Uint8Array([JSON_AND_BINARY_DELIMITER]),
161
+ blob
162
+ ]));
163
+ }
164
+ async function decodeRawMessage(raw) {
165
+ if (typeof raw === "string") {
166
+ return { json: JSON.parse(raw) };
167
+ }
168
+ const buffer = raw instanceof Uint8Array ? raw : new Uint8Array(raw);
169
+ const delimiterIndex = buffer.indexOf(JSON_AND_BINARY_DELIMITER);
170
+ if (delimiterIndex === -1) {
171
+ const jsonPart2 = new TextDecoder().decode(buffer);
172
+ return { json: JSON.parse(jsonPart2) };
173
+ }
174
+ const jsonPart = new TextDecoder().decode(buffer.subarray(0, delimiterIndex));
175
+ const bufferPart = buffer.subarray(delimiterIndex + 1);
176
+ return {
177
+ json: JSON.parse(jsonPart),
178
+ buffer: bufferPart
179
+ };
180
+ }
181
+
182
+ function toEventIterator(queue, id, cleanup, options = {}) {
183
+ let span;
184
+ return new AsyncIteratorClass(async () => {
185
+ span ??= startSpan("consume_event_iterator_stream");
186
+ try {
187
+ const item = await runInSpanContext(span, () => queue.pull(id));
188
+ switch (item.event) {
189
+ case "message": {
190
+ let data = item.data;
191
+ if (item.meta && isTypescriptObject(data)) {
192
+ data = withEventMeta(data, item.meta);
193
+ }
194
+ span?.addEvent("message");
195
+ return { value: data, done: false };
196
+ }
197
+ case "error": {
198
+ let error = new ErrorEvent({
199
+ data: item.data
200
+ });
201
+ if (item.meta) {
202
+ error = withEventMeta(error, item.meta);
203
+ }
204
+ span?.addEvent("error");
205
+ throw error;
206
+ }
207
+ case "done": {
208
+ let data = item.data;
209
+ if (item.meta && isTypescriptObject(data)) {
210
+ data = withEventMeta(data, item.meta);
211
+ }
212
+ span?.addEvent("done");
213
+ return { value: data, done: true };
214
+ }
215
+ }
216
+ } catch (e) {
217
+ if (!(e instanceof ErrorEvent)) {
218
+ setSpanError(span, e, options);
219
+ }
220
+ throw e;
221
+ }
222
+ }, async (reason) => {
223
+ try {
224
+ if (reason !== "next") {
225
+ span?.addEvent("cancelled");
226
+ }
227
+ await runInSpanContext(span, () => cleanup(reason));
228
+ } catch (e) {
229
+ setSpanError(span, e, options);
230
+ throw e;
231
+ } finally {
232
+ span?.end();
233
+ }
234
+ });
235
+ }
236
+ function resolveEventIterator(iterator, callback) {
237
+ return runWithSpan(
238
+ { name: "stream_event_iterator" },
239
+ async (span) => {
240
+ while (true) {
241
+ const payload = await (async () => {
242
+ try {
243
+ const { value, done } = await iterator.next();
244
+ if (done) {
245
+ span?.addEvent("done");
246
+ return { event: "done", data: value, meta: getEventMeta(value) };
247
+ }
248
+ span?.addEvent("message");
249
+ return { event: "message", data: value, meta: getEventMeta(value) };
250
+ } catch (err) {
251
+ if (err instanceof ErrorEvent) {
252
+ span?.addEvent("error");
253
+ return {
254
+ event: "error",
255
+ data: err.data,
256
+ meta: getEventMeta(err)
257
+ };
258
+ } else {
259
+ try {
260
+ await callback({ event: "error", data: void 0 });
261
+ } catch (err2) {
262
+ setSpanError(span, err);
263
+ throw err2;
264
+ }
265
+ throw err;
266
+ }
267
+ }
268
+ })();
269
+ let isInvokeCleanupFn = false;
270
+ try {
271
+ const direction = await callback(payload);
272
+ if (payload.event === "done" || payload.event === "error") {
273
+ return;
274
+ }
275
+ if (direction === "abort") {
276
+ isInvokeCleanupFn = true;
277
+ await iterator.return?.();
278
+ return;
279
+ }
280
+ } catch (err) {
281
+ if (!isInvokeCleanupFn) {
282
+ try {
283
+ await iterator.return?.();
284
+ } catch (err2) {
285
+ setSpanError(span, err);
286
+ throw err2;
287
+ }
288
+ }
289
+ throw err;
290
+ }
291
+ }
292
+ }
293
+ );
294
+ }
295
+
296
+ class ClientPeer {
297
+ idGenerator = new SequentialIdGenerator();
298
+ /**
299
+ * Queue of responses sent from server, awaiting consumption
300
+ */
301
+ responseQueue = new AsyncIdQueue();
302
+ /**
303
+ * Queue of event iterator messages sent from server, awaiting consumption
304
+ */
305
+ serverEventIteratorQueue = new AsyncIdQueue();
306
+ /**
307
+ * Controllers used to signal that the client should stop sending event iterator messages
308
+ */
309
+ serverControllers = /* @__PURE__ */ new Map();
310
+ /**
311
+ * Cleanup functions invoked when the request/response is closed
312
+ */
313
+ cleanupFns = /* @__PURE__ */ new Map();
314
+ send;
315
+ constructor(send) {
316
+ this.send = async (id, ...rest) => encodeRequestMessage(id, ...rest).then(async (raw) => {
317
+ if (this.serverControllers.has(id)) {
318
+ await send(raw);
319
+ }
320
+ });
321
+ }
322
+ get length() {
323
+ return (+this.responseQueue.length + this.serverEventIteratorQueue.length + this.serverControllers.size + this.cleanupFns.size) / 4;
324
+ }
325
+ open(id) {
326
+ this.serverEventIteratorQueue.open(id);
327
+ this.responseQueue.open(id);
328
+ const controller = new AbortController();
329
+ this.serverControllers.set(id, controller);
330
+ this.cleanupFns.set(id, []);
331
+ return controller;
332
+ }
333
+ async request(request) {
334
+ const signal = request.signal;
335
+ return runWithSpan(
336
+ { name: "send_peer_request", signal },
337
+ async () => {
338
+ if (signal?.aborted) {
339
+ throw signal.reason;
340
+ }
341
+ const id = this.idGenerator.generate();
342
+ const serverController = this.open(id);
343
+ try {
344
+ const otelConfig = getGlobalOtelConfig();
345
+ if (otelConfig) {
346
+ const headers = clone(request.headers);
347
+ otelConfig.propagation.inject(otelConfig.context.active(), headers);
348
+ request = { ...request, headers };
349
+ }
350
+ await this.send(id, MessageType.REQUEST, request);
351
+ if (signal?.aborted) {
352
+ await this.send(id, MessageType.ABORT_SIGNAL, void 0);
353
+ throw signal.reason;
354
+ }
355
+ let abortListener;
356
+ signal?.addEventListener("abort", abortListener = async () => {
357
+ await this.send(id, MessageType.ABORT_SIGNAL, void 0);
358
+ this.close({ id, reason: signal.reason });
359
+ }, { once: true });
360
+ this.cleanupFns.get(id)?.push(() => {
361
+ signal?.removeEventListener("abort", abortListener);
362
+ });
363
+ if (isAsyncIteratorObject(request.body)) {
364
+ const iterator = request.body;
365
+ void resolveEventIterator(iterator, async (payload) => {
366
+ if (serverController.signal.aborted) {
367
+ return "abort";
368
+ }
369
+ await this.send(id, MessageType.EVENT_ITERATOR, payload);
370
+ return "next";
371
+ });
372
+ }
373
+ const response = await this.responseQueue.pull(id);
374
+ if (isEventIteratorHeaders(response.headers)) {
375
+ const iterator = toEventIterator(
376
+ this.serverEventIteratorQueue,
377
+ id,
378
+ async (reason) => {
379
+ try {
380
+ if (reason !== "next") {
381
+ await this.send(id, MessageType.ABORT_SIGNAL, void 0);
382
+ }
383
+ } finally {
384
+ this.close({ id });
385
+ }
386
+ },
387
+ { signal }
388
+ );
389
+ return {
390
+ ...response,
391
+ body: iterator
392
+ };
393
+ }
394
+ this.close({ id });
395
+ return response;
396
+ } catch (err) {
397
+ this.close({ id, reason: err });
398
+ throw err;
399
+ }
400
+ }
401
+ );
402
+ }
403
+ async message(raw) {
404
+ const [id, type, payload] = await decodeResponseMessage(raw);
405
+ if (type === MessageType.ABORT_SIGNAL) {
406
+ this.serverControllers.get(id)?.abort();
407
+ return;
408
+ }
409
+ if (type === MessageType.EVENT_ITERATOR) {
410
+ if (this.serverEventIteratorQueue.isOpen(id)) {
411
+ this.serverEventIteratorQueue.push(id, payload);
412
+ }
413
+ return;
414
+ }
415
+ if (!this.responseQueue.isOpen(id)) {
416
+ return;
417
+ }
418
+ this.responseQueue.push(id, payload);
419
+ }
420
+ close(options = {}) {
421
+ if (options.id !== void 0) {
422
+ this.serverControllers.get(options.id)?.abort(options.reason);
423
+ this.serverControllers.delete(options.id);
424
+ this.cleanupFns.get(options.id)?.forEach((fn) => fn());
425
+ this.cleanupFns.delete(options.id);
426
+ } else {
427
+ this.serverControllers.forEach((c) => c.abort(options.reason));
428
+ this.serverControllers.clear();
429
+ this.cleanupFns.forEach((fns) => fns.forEach((fn) => fn()));
430
+ this.cleanupFns.clear();
431
+ }
432
+ this.responseQueue.close(options);
433
+ this.serverEventIteratorQueue.close(options);
434
+ }
435
+ }
436
+
437
+ class ServerPeer {
438
+ /**
439
+ * Queue of event iterator messages sent from client, awaiting consumption
440
+ */
441
+ clientEventIteratorQueue = new AsyncIdQueue();
442
+ /**
443
+ * Map of active client request controllers, should be synced to request signal
444
+ */
445
+ clientControllers = /* @__PURE__ */ new Map();
446
+ send;
447
+ constructor(send) {
448
+ this.send = (id, ...rest) => encodeResponseMessage(id, ...rest).then(async (raw) => {
449
+ if (this.clientControllers.has(id)) {
450
+ await send(raw);
451
+ }
452
+ });
453
+ }
454
+ get length() {
455
+ return (this.clientEventIteratorQueue.length + this.clientControllers.size) / 2;
456
+ }
457
+ open(id) {
458
+ this.clientEventIteratorQueue.open(id);
459
+ const controller = new AbortController();
460
+ this.clientControllers.set(id, controller);
461
+ return controller;
462
+ }
463
+ /**
464
+ * @todo This method will return Promise<void> in the next major version.
465
+ */
466
+ async message(raw, handleRequest) {
467
+ const [id, type, payload] = await decodeRequestMessage(raw);
468
+ if (type === MessageType.ABORT_SIGNAL) {
469
+ this.close({ id, reason: new AbortError("Client aborted the request") });
470
+ return [id, void 0];
471
+ }
472
+ if (type === MessageType.EVENT_ITERATOR) {
473
+ if (this.clientEventIteratorQueue.isOpen(id)) {
474
+ this.clientEventIteratorQueue.push(id, payload);
475
+ }
476
+ return [id, void 0];
477
+ }
478
+ const clientController = this.open(id);
479
+ const signal = clientController.signal;
480
+ const request = {
481
+ ...payload,
482
+ signal,
483
+ body: isEventIteratorHeaders(payload.headers) ? toEventIterator(
484
+ this.clientEventIteratorQueue,
485
+ id,
486
+ async (reason) => {
487
+ if (reason !== "next") {
488
+ await this.send(id, MessageType.ABORT_SIGNAL, void 0);
489
+ }
490
+ },
491
+ { signal }
492
+ ) : payload.body
493
+ };
494
+ if (handleRequest) {
495
+ let context;
496
+ const otelConfig = getGlobalOtelConfig();
497
+ if (otelConfig) {
498
+ context = otelConfig.propagation.extract(otelConfig.context.active(), request.headers);
499
+ }
500
+ await runWithSpan(
501
+ { name: "receive_peer_request", context },
502
+ async () => {
503
+ const response = await runWithSpan(
504
+ { name: "handle_request" },
505
+ async () => {
506
+ try {
507
+ return await handleRequest(request);
508
+ } catch (reason) {
509
+ this.close({ id, reason, abort: false });
510
+ throw reason;
511
+ }
512
+ }
513
+ );
514
+ await runWithSpan(
515
+ { name: "send_peer_response" },
516
+ () => this.response(id, response)
517
+ );
518
+ }
519
+ );
520
+ }
521
+ return [id, request];
522
+ }
523
+ /**
524
+ * @deprecated Please pass the `handleRequest` (second arg) function to the `message` method instead.
525
+ */
526
+ async response(id, response) {
527
+ const signal = this.clientControllers.get(id)?.signal;
528
+ if (!signal || signal.aborted) {
529
+ return;
530
+ }
531
+ try {
532
+ await this.send(id, MessageType.RESPONSE, response);
533
+ if (!signal.aborted && isAsyncIteratorObject(response.body)) {
534
+ if (response.body instanceof HibernationEventIterator) {
535
+ response.body.hibernationCallback?.(id);
536
+ } else {
537
+ const iterator = response.body;
538
+ await resolveEventIterator(iterator, async (payload) => {
539
+ if (signal.aborted) {
540
+ return "abort";
541
+ }
542
+ await this.send(id, MessageType.EVENT_ITERATOR, payload);
543
+ return "next";
544
+ });
545
+ }
546
+ }
547
+ this.close({ id, abort: false });
548
+ } catch (reason) {
549
+ this.close({ id, reason, abort: false });
550
+ throw reason;
551
+ }
552
+ }
553
+ close({ abort = true, ...options } = {}) {
554
+ if (options.id === void 0) {
555
+ if (abort) {
556
+ this.clientControllers.forEach((c) => c.abort(options.reason));
557
+ }
558
+ this.clientControllers.clear();
559
+ } else {
560
+ if (abort) {
561
+ this.clientControllers.get(options.id)?.abort(options.reason);
562
+ }
563
+ this.clientControllers.delete(options.id);
564
+ }
565
+ this.clientEventIteratorQueue.close(options);
566
+ }
567
+ }
568
+
569
+ export { ClientPeer, MessageType, ServerPeer, decodeRequestMessage, decodeResponseMessage, encodeRequestMessage, encodeResponseMessage, resolveEventIterator, toEventIterator };
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@orpc/standard-server-peer",
3
+ "type": "module",
4
+ "version": "0.0.0-next.0021fba",
5
+ "license": "MIT",
6
+ "homepage": "https://unnoq.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/unnoq/orpc.git",
10
+ "directory": "packages/standard-server-peer"
11
+ },
12
+ "keywords": [
13
+ "orpc"
14
+ ],
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.mts",
18
+ "import": "./dist/index.mjs",
19
+ "default": "./dist/index.mjs"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "dependencies": {
26
+ "@orpc/shared": "0.0.0-next.0021fba",
27
+ "@orpc/standard-server": "0.0.0-next.0021fba"
28
+ },
29
+ "scripts": {
30
+ "build": "unbuild",
31
+ "build:watch": "pnpm run build --watch",
32
+ "type:check": "tsc -b"
33
+ }
34
+ }