@orpc/standard-server-node 0.0.0-next.d0e429d → 0.0.0-next.d12598b

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/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  <div align="center">
2
- <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 />
2
+ <image align="center" src="https://orpc.dev/logo.webp" width=280 alt="oRPC logo" />
3
3
  </div>
4
4
 
5
5
  <h1></h1>
@@ -17,52 +17,65 @@
17
17
  <a href="https://discord.gg/TXEbwRBvQn">
18
18
  <img alt="Discord" src="https://img.shields.io/discord/1308966753044398161?color=7389D8&label&logo=discord&logoColor=ffffff" />
19
19
  </a>
20
+ <a href="https://deepwiki.com/unnoq/orpc">
21
+ <img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki">
22
+ </a>
20
23
  </div>
21
24
 
22
25
  <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
23
26
 
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, ensuring a smooth and enjoyable developer experience.
27
+ **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
28
 
26
29
  ---
27
30
 
28
31
  ## Highlights
29
32
 
30
- - **End-to-End Type Safety 🔒**: Ensure complete type safety from inputs to outputs and errors, bridging server and client seamlessly.
31
- - **First-Class OpenAPI 📄**: Adheres to the OpenAPI standard out of the box, ensuring seamless integration and comprehensive API documentation.
32
- - **Contract-First Development 📜**: (Optional) Define your API contract upfront and implement it with confidence.
33
- - **Exceptional Developer Experience ✨**: Enjoy a streamlined workflow with robust typing and clear, in-code documentation.
34
- - **Multi-Runtime Support 🌍**: Run your code seamlessly on Cloudflare, Deno, Bun, Node.js, and more.
35
- - **Framework Integrations 🧩**: Supports Tanstack Query (React, Vue), Pinia Colada, and more.
36
- - **Server Actions ⚡️**: Fully compatible with React Server Actions on Next.js, TanStack Start, and more.
37
- - **Standard Schema Support 🗂️**: Effortlessly work with Zod, Valibot, ArkType, and others right out of the box.
38
- - **Fast & Lightweight 💨**: Built on native APIs across all runtimes – optimized for speed and efficiency.
39
- - **Native Types 📦**: Enjoy built-in support for Date, File, Blob, BigInt, URL and more with no extra setup.
40
- - **Lazy Router ⏱️**: Improve cold start times with our lazy routing feature.
41
- - **SSE & Streaming 📡**: Provides SSE and streaming features – perfect for real-time notifications and AI-powered streaming responses.
42
- - **Reusability 🔄**: Write once and reuse your code across multiple purposes effortlessly.
43
- - **Extendability 🔌**: Easily enhance oRPC with plugins, middleware, and interceptors.
44
- - **Reliability 🛡️**: Well-tested, fully TypeScript, production-ready, and MIT licensed for peace of mind.
45
- - **Simplicity 💡**: Enjoy straightforward, clean code with no hidden magic.
33
+ - **🔗 End-to-End Type Safety**: Ensure type-safe inputs, outputs, and errors from client to server.
34
+ - **📘 First-Class OpenAPI**: Built-in support that fully adheres to the OpenAPI standard.
35
+ - **📝 Contract-First Development**: Optionally define your API contract before implementation.
36
+ - **🔍 First-Class OpenTelemetry**: Seamlessly integrate with OpenTelemetry for observability.
37
+ - **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte, Angular), SWR, Pinia Colada, and more.
38
+ - **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms.
39
+ - **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators.
40
+ - **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more.
41
+ - **⏱️ Lazy Router**: Enhance cold start times with our lazy routing feature.
42
+ - **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming.
43
+ - **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond.
44
+ - **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors.
46
45
 
47
46
  ## Documentation
48
47
 
49
- You can find the full documentation [here](https://orpc.unnoq.com).
48
+ You can find the full documentation [here](https://orpc.dev).
50
49
 
51
50
  ## Packages
52
51
 
53
52
  - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
54
53
  - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
55
54
  - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
56
- - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
57
- - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
58
- - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
59
55
  - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
56
+ - [@orpc/otel](https://www.npmjs.com/package/@orpc/otel): [OpenTelemetry](https://opentelemetry.io/) integration for observability.
57
+ - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with [NestJS](https://nestjs.com/).
58
+ - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
59
+ - [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration.
60
+ - [@orpc/experimental-react-swr](https://www.npmjs.com/package/@orpc/experimental-react-swr): [SWR](https://swr.vercel.app/) integration.
61
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
62
+ - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
60
63
  - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
64
+ - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
65
+ - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
61
66
 
62
67
  ## `@orpc/standard-server-node`
63
68
 
64
69
  [Node.js](https://nodejs.org) server adapter for oRPC.
65
70
 
71
+ ## Sponsors
72
+
73
+ <p align="center">
74
+ <a href="https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg">
75
+ <img src='https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg'/>
76
+ </a>
77
+ </p>
78
+
66
79
  ## License
67
80
 
68
81
  Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
@@ -0,0 +1,54 @@
1
+ import { StandardBody, StandardHeaders, StandardLazyRequest, StandardResponse } from '@orpc/standard-server';
2
+ import { ToEventIteratorOptions as ToEventIteratorOptions$1, ToEventStreamOptions as ToEventStreamOptions$1 } from '@orpc/standard-server-fetch';
3
+ import Stream, { Readable } from 'node:stream';
4
+ import { IncomingMessage, ServerResponse, OutgoingHttpHeaders } from 'node:http';
5
+ import { Http2ServerRequest, Http2ServerResponse } from 'node:http2';
6
+
7
+ interface ToEventIteratorOptions extends ToEventIteratorOptions$1 {
8
+ }
9
+ declare function toEventIterator(stream: Readable, options?: ToEventIteratorOptions): AsyncIteratorObject<unknown | void, unknown | void, void> & AsyncGenerator<unknown | void, unknown | void, void>;
10
+ interface ToEventStreamOptions extends ToEventStreamOptions$1 {
11
+ }
12
+ declare function toEventStream(iterator: AsyncIterator<unknown | void, unknown | void, void>, options?: ToEventStreamOptions): Readable;
13
+
14
+ type NodeHttpRequest = (IncomingMessage | Http2ServerRequest) & {
15
+ /**
16
+ * Replace `req.url` with `req.originalUrl` when `req.originalUrl` is available.
17
+ * This is useful for `express.js` middleware.
18
+ */
19
+ originalUrl?: string;
20
+ /**
21
+ * Prefer parsed body if it is available.
22
+ */
23
+ body?: unknown;
24
+ };
25
+ type NodeHttpResponse = ServerResponse | Http2ServerResponse;
26
+
27
+ interface ToStandardBodyOptions extends ToEventIteratorOptions {
28
+ }
29
+ declare function toStandardBody(req: NodeHttpRequest, options?: ToStandardBodyOptions): Promise<StandardBody>;
30
+ interface ToNodeHttpBodyOptions extends ToEventStreamOptions {
31
+ }
32
+ /**
33
+ * @param body
34
+ * @param headers - WARNING: The headers can be changed by the function and effects on the original headers.
35
+ * @param options
36
+ */
37
+ declare function toNodeHttpBody(body: StandardBody, headers: StandardHeaders, options?: ToNodeHttpBodyOptions): Readable | undefined | string;
38
+
39
+ declare function toNodeHttpHeaders(headers: StandardHeaders): OutgoingHttpHeaders;
40
+
41
+ declare function toStandardMethod(method: string | undefined): string;
42
+
43
+ declare function toStandardLazyRequest(req: NodeHttpRequest, res: NodeHttpResponse): StandardLazyRequest;
44
+
45
+ interface SendStandardResponseOptions extends ToNodeHttpBodyOptions {
46
+ }
47
+ declare function sendStandardResponse(res: NodeHttpResponse, standardResponse: StandardResponse, options?: SendStandardResponseOptions): Promise<void>;
48
+
49
+ declare function toAbortSignal(stream: Stream.Writable): AbortSignal;
50
+
51
+ declare function toStandardUrl(req: NodeHttpRequest): URL;
52
+
53
+ export { sendStandardResponse, toAbortSignal, toEventIterator, toEventStream, toNodeHttpBody, toNodeHttpHeaders, toStandardBody, toStandardLazyRequest, toStandardMethod, toStandardUrl };
54
+ export type { NodeHttpRequest, NodeHttpResponse, SendStandardResponseOptions, ToEventIteratorOptions, ToEventStreamOptions, ToNodeHttpBodyOptions, ToStandardBodyOptions };
@@ -0,0 +1,54 @@
1
+ import { StandardBody, StandardHeaders, StandardLazyRequest, StandardResponse } from '@orpc/standard-server';
2
+ import { ToEventIteratorOptions as ToEventIteratorOptions$1, ToEventStreamOptions as ToEventStreamOptions$1 } from '@orpc/standard-server-fetch';
3
+ import Stream, { Readable } from 'node:stream';
4
+ import { IncomingMessage, ServerResponse, OutgoingHttpHeaders } from 'node:http';
5
+ import { Http2ServerRequest, Http2ServerResponse } from 'node:http2';
6
+
7
+ interface ToEventIteratorOptions extends ToEventIteratorOptions$1 {
8
+ }
9
+ declare function toEventIterator(stream: Readable, options?: ToEventIteratorOptions): AsyncIteratorObject<unknown | void, unknown | void, void> & AsyncGenerator<unknown | void, unknown | void, void>;
10
+ interface ToEventStreamOptions extends ToEventStreamOptions$1 {
11
+ }
12
+ declare function toEventStream(iterator: AsyncIterator<unknown | void, unknown | void, void>, options?: ToEventStreamOptions): Readable;
13
+
14
+ type NodeHttpRequest = (IncomingMessage | Http2ServerRequest) & {
15
+ /**
16
+ * Replace `req.url` with `req.originalUrl` when `req.originalUrl` is available.
17
+ * This is useful for `express.js` middleware.
18
+ */
19
+ originalUrl?: string;
20
+ /**
21
+ * Prefer parsed body if it is available.
22
+ */
23
+ body?: unknown;
24
+ };
25
+ type NodeHttpResponse = ServerResponse | Http2ServerResponse;
26
+
27
+ interface ToStandardBodyOptions extends ToEventIteratorOptions {
28
+ }
29
+ declare function toStandardBody(req: NodeHttpRequest, options?: ToStandardBodyOptions): Promise<StandardBody>;
30
+ interface ToNodeHttpBodyOptions extends ToEventStreamOptions {
31
+ }
32
+ /**
33
+ * @param body
34
+ * @param headers - WARNING: The headers can be changed by the function and effects on the original headers.
35
+ * @param options
36
+ */
37
+ declare function toNodeHttpBody(body: StandardBody, headers: StandardHeaders, options?: ToNodeHttpBodyOptions): Readable | undefined | string;
38
+
39
+ declare function toNodeHttpHeaders(headers: StandardHeaders): OutgoingHttpHeaders;
40
+
41
+ declare function toStandardMethod(method: string | undefined): string;
42
+
43
+ declare function toStandardLazyRequest(req: NodeHttpRequest, res: NodeHttpResponse): StandardLazyRequest;
44
+
45
+ interface SendStandardResponseOptions extends ToNodeHttpBodyOptions {
46
+ }
47
+ declare function sendStandardResponse(res: NodeHttpResponse, standardResponse: StandardResponse, options?: SendStandardResponseOptions): Promise<void>;
48
+
49
+ declare function toAbortSignal(stream: Stream.Writable): AbortSignal;
50
+
51
+ declare function toStandardUrl(req: NodeHttpRequest): URL;
52
+
53
+ export { sendStandardResponse, toAbortSignal, toEventIterator, toEventStream, toNodeHttpBody, toNodeHttpHeaders, toStandardBody, toStandardLazyRequest, toStandardMethod, toStandardUrl };
54
+ export type { NodeHttpRequest, NodeHttpResponse, SendStandardResponseOptions, ToEventIteratorOptions, ToEventStreamOptions, ToNodeHttpBodyOptions, ToStandardBodyOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,162 @@
1
+ import { Readable } from 'node:stream';
2
+ import { runWithSpan, parseEmptyableJSON, isAsyncIteratorObject, stringifyJSON, AbortError, guard, once } from '@orpc/shared';
3
+ import { getFilenameFromContentDisposition, flattenHeader, generateContentDisposition } from '@orpc/standard-server';
4
+ import { toEventIterator as toEventIterator$1, toEventStream as toEventStream$1 } from '@orpc/standard-server-fetch';
5
+
6
+ function toEventIterator(stream, options = {}) {
7
+ return toEventIterator$1(Readable.toWeb(stream), options);
8
+ }
9
+ function toEventStream(iterator, options = {}) {
10
+ return Readable.fromWeb(toEventStream$1(iterator, options));
11
+ }
12
+
13
+ function toStandardBody(req, options = {}) {
14
+ if (req.body !== void 0) {
15
+ return Promise.resolve(req.body);
16
+ }
17
+ return runWithSpan({ name: "parse_standard_body", signal: options.signal }, async () => {
18
+ const contentDisposition = req.headers["content-disposition"];
19
+ const contentType = req.headers["content-type"];
20
+ if (typeof contentDisposition === "string") {
21
+ const fileName = getFilenameFromContentDisposition(contentDisposition) ?? "blob";
22
+ return _streamToFile(req, fileName, contentType ?? "");
23
+ }
24
+ if (!contentType || contentType.startsWith("application/json")) {
25
+ const text = await _streamToString(req);
26
+ return parseEmptyableJSON(text);
27
+ }
28
+ if (contentType.startsWith("multipart/form-data")) {
29
+ return _streamToFormData(req, contentType);
30
+ }
31
+ if (contentType.startsWith("application/x-www-form-urlencoded")) {
32
+ const text = await _streamToString(req);
33
+ return new URLSearchParams(text);
34
+ }
35
+ if (contentType.startsWith("text/event-stream")) {
36
+ return toEventIterator(req, options);
37
+ }
38
+ if (contentType.startsWith("text/plain")) {
39
+ return _streamToString(req);
40
+ }
41
+ return _streamToFile(req, "blob", contentType);
42
+ });
43
+ }
44
+ function toNodeHttpBody(body, headers, options = {}) {
45
+ const currentContentDisposition = flattenHeader(headers["content-disposition"]);
46
+ delete headers["content-type"];
47
+ delete headers["content-disposition"];
48
+ if (body === void 0) {
49
+ return;
50
+ }
51
+ if (body instanceof Blob) {
52
+ headers["content-type"] = body.type;
53
+ headers["content-length"] = body.size.toString();
54
+ headers["content-disposition"] = currentContentDisposition ?? generateContentDisposition(body instanceof File ? body.name : "blob");
55
+ return Readable.fromWeb(body.stream());
56
+ }
57
+ if (body instanceof FormData) {
58
+ const response = new Response(body);
59
+ headers["content-type"] = response.headers.get("content-type");
60
+ return Readable.fromWeb(response.body);
61
+ }
62
+ if (body instanceof URLSearchParams) {
63
+ headers["content-type"] = "application/x-www-form-urlencoded";
64
+ return body.toString();
65
+ }
66
+ if (isAsyncIteratorObject(body)) {
67
+ headers["content-type"] = "text/event-stream";
68
+ return toEventStream(body, options);
69
+ }
70
+ headers["content-type"] = "application/json";
71
+ return stringifyJSON(body);
72
+ }
73
+ function _streamToFormData(stream, contentType) {
74
+ const response = new Response(stream, {
75
+ headers: {
76
+ "content-type": contentType
77
+ }
78
+ });
79
+ return response.formData();
80
+ }
81
+ async function _streamToString(stream) {
82
+ let string = "";
83
+ for await (const chunk of stream) {
84
+ string += chunk.toString();
85
+ }
86
+ return string;
87
+ }
88
+ async function _streamToFile(stream, fileName, contentType) {
89
+ const chunks = [];
90
+ for await (const chunk of stream) {
91
+ chunks.push(chunk);
92
+ }
93
+ return new File(chunks, fileName, { type: contentType });
94
+ }
95
+
96
+ function toNodeHttpHeaders(headers) {
97
+ const nodeHttpHeaders = {};
98
+ for (const [key, value] of Object.entries(headers)) {
99
+ if (value !== void 0) {
100
+ nodeHttpHeaders[key] = value;
101
+ }
102
+ }
103
+ return nodeHttpHeaders;
104
+ }
105
+
106
+ function toStandardMethod(method) {
107
+ return method ?? "GET";
108
+ }
109
+
110
+ function toAbortSignal(stream) {
111
+ const controller = new AbortController();
112
+ stream.once("error", (error) => controller.abort(error));
113
+ stream.once("close", () => {
114
+ if (!stream.writableFinished) {
115
+ controller.abort(new AbortError("Writable stream closed before it finished writing"));
116
+ }
117
+ });
118
+ return controller.signal;
119
+ }
120
+
121
+ function toStandardUrl(req) {
122
+ const protocol = "encrypted" in req.socket && req.socket.encrypted ? "https:" : "http:";
123
+ const origin = guard(() => new URL(`${protocol}//${req.headers.host ?? "localhost"}`).origin) ?? `${protocol}//localhost`;
124
+ const path = req.originalUrl ?? req.url ?? "/";
125
+ return new URL(`${origin}${path.startsWith("/") ? "" : "/"}${path}`);
126
+ }
127
+
128
+ function toStandardLazyRequest(req, res) {
129
+ const signal = toAbortSignal(res);
130
+ return {
131
+ method: toStandardMethod(req.method),
132
+ url: toStandardUrl(req),
133
+ headers: req.headers,
134
+ body: once(() => toStandardBody(req, { signal })),
135
+ signal
136
+ };
137
+ }
138
+
139
+ function sendStandardResponse(res, standardResponse, options = {}) {
140
+ return new Promise((resolve, reject) => {
141
+ res.once("error", reject);
142
+ res.once("close", resolve);
143
+ const resHeaders = { ...standardResponse.headers };
144
+ const resBody = toNodeHttpBody(standardResponse.body, resHeaders, options);
145
+ res.writeHead(standardResponse.status, toNodeHttpHeaders(resHeaders));
146
+ if (resBody === void 0) {
147
+ res.end();
148
+ } else if (typeof resBody === "string") {
149
+ res.end(resBody);
150
+ } else {
151
+ res.once("close", () => {
152
+ if (!resBody.closed) {
153
+ resBody.destroy(res.errored ?? void 0);
154
+ }
155
+ });
156
+ resBody.once("error", (error) => res.destroy(error));
157
+ resBody.pipe(res);
158
+ }
159
+ });
160
+ }
161
+
162
+ export { sendStandardResponse, toAbortSignal, toEventIterator, toEventStream, toNodeHttpBody, toNodeHttpHeaders, toStandardBody, toStandardLazyRequest, toStandardMethod, toStandardUrl };
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@orpc/standard-server-node",
3
3
  "type": "module",
4
- "version": "0.0.0-next.d0e429d",
4
+ "version": "0.0.0-next.d12598b",
5
5
  "license": "MIT",
6
- "homepage": "https://orpc.unnoq.com",
6
+ "homepage": "https://orpc.dev",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "git+https://github.com/unnoq/orpc.git",
@@ -14,30 +14,26 @@
14
14
  ],
15
15
  "exports": {
16
16
  ".": {
17
- "types": "./dist/src/index.d.ts",
18
- "import": "./dist/index.js",
19
- "default": "./dist/index.js"
20
- },
21
- "./🔒/*": {
22
- "types": "./dist/src/*.d.ts"
17
+ "types": "./dist/index.d.mts",
18
+ "import": "./dist/index.mjs",
19
+ "default": "./dist/index.mjs"
23
20
  }
24
21
  },
25
22
  "files": [
26
- "!**/*.map",
27
- "!**/*.tsbuildinfo",
28
23
  "dist"
29
24
  ],
30
25
  "dependencies": {
31
- "@orpc/shared": "0.0.0-next.d0e429d",
32
- "@orpc/standard-server": "0.0.0-next.d0e429d"
26
+ "@orpc/standard-server": "0.0.0-next.d12598b",
27
+ "@orpc/shared": "0.0.0-next.d12598b",
28
+ "@orpc/standard-server-fetch": "0.0.0-next.d12598b"
33
29
  },
34
30
  "devDependencies": {
35
- "@types/node": "^22.13.1",
36
- "@types/supertest": "^6.0.2",
37
- "supertest": "^7.0.0"
31
+ "@types/node": "^22.15.30",
32
+ "@types/supertest": "^6.0.3",
33
+ "supertest": "^7.1.4"
38
34
  },
39
35
  "scripts": {
40
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
36
+ "build": "unbuild",
41
37
  "build:watch": "pnpm run build --watch",
42
38
  "type:check": "tsc -b"
43
39
  }
package/dist/index.js DELETED
@@ -1,257 +0,0 @@
1
- // src/body.ts
2
- import { Readable as Readable2 } from "node:stream";
3
- import { isAsyncIteratorObject, parseEmptyableJSON as parseEmptyableJSON2, stringifyJSON as stringifyJSON2 } from "@orpc/shared";
4
- import { contentDisposition, parseContentDisposition } from "@orpc/standard-server";
5
-
6
- // src/event-source.ts
7
- import { Readable } from "node:stream";
8
- import { isTypescriptObject, parseEmptyableJSON, stringifyJSON } from "@orpc/shared";
9
- import {
10
- encodeEventMessage,
11
- ErrorEvent,
12
- EventDecoderStream,
13
- getEventMeta,
14
- withEventMeta
15
- } from "@orpc/standard-server";
16
- function toEventIterator(stream) {
17
- const eventStream = Readable.toWeb(stream).pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream());
18
- const reader = eventStream.getReader();
19
- async function* gen() {
20
- try {
21
- while (true) {
22
- const { done, value } = await reader.read();
23
- if (done) {
24
- return;
25
- }
26
- switch (value.event) {
27
- case "message": {
28
- let message = parseEmptyableJSON(value.data);
29
- if (isTypescriptObject(message)) {
30
- message = withEventMeta(message, value);
31
- }
32
- yield message;
33
- break;
34
- }
35
- case "error": {
36
- let error = new ErrorEvent({
37
- data: parseEmptyableJSON(value.data)
38
- });
39
- error = withEventMeta(error, value);
40
- throw error;
41
- }
42
- case "done": {
43
- let done2 = parseEmptyableJSON(value.data);
44
- if (isTypescriptObject(done2)) {
45
- done2 = withEventMeta(done2, value);
46
- }
47
- return done2;
48
- }
49
- }
50
- }
51
- } finally {
52
- await reader.cancel();
53
- }
54
- }
55
- return gen();
56
- }
57
- function toEventStream(iterator, options = {}) {
58
- const pingEnabled = options.eventSourcePingEnabled ?? true;
59
- const pingInterval = options.eventSourcePingInterval ?? 5e3;
60
- const pingContent = options.eventSourcePingContent ?? "";
61
- let timeout;
62
- const stream = new ReadableStream({
63
- async pull(controller) {
64
- try {
65
- if (pingEnabled) {
66
- timeout = setInterval(() => {
67
- controller.enqueue(encodeEventMessage({
68
- comments: [pingContent]
69
- }));
70
- }, pingInterval);
71
- }
72
- const value = await iterator.next();
73
- clearInterval(timeout);
74
- controller.enqueue(encodeEventMessage({
75
- ...getEventMeta(value.value),
76
- event: value.done ? "done" : "message",
77
- data: stringifyJSON(value.value)
78
- }));
79
- if (value.done) {
80
- controller.close();
81
- }
82
- } catch (err) {
83
- clearInterval(timeout);
84
- controller.enqueue(encodeEventMessage({
85
- ...getEventMeta(err),
86
- event: "error",
87
- data: err instanceof ErrorEvent ? stringifyJSON(err.data) : void 0
88
- }));
89
- controller.close();
90
- }
91
- },
92
- async cancel(reason) {
93
- if (reason) {
94
- await iterator.throw?.(reason);
95
- } else {
96
- await iterator.return?.();
97
- }
98
- }
99
- });
100
- return Readable.fromWeb(stream);
101
- }
102
-
103
- // src/body.ts
104
- async function toStandardBody(req) {
105
- const method = req.method ?? "GET";
106
- if (method === "GET" || method === "HEAD") {
107
- return void 0;
108
- }
109
- const contentDisposition2 = req.headers["content-disposition"];
110
- const contentType = req.headers["content-type"];
111
- if (contentDisposition2) {
112
- const fileName = parseContentDisposition(contentDisposition2).parameters.filename;
113
- if (typeof fileName === "string") {
114
- return _streamToFile(req, fileName, contentType ?? "");
115
- }
116
- }
117
- if (!contentType || contentType.startsWith("application/json")) {
118
- const text = await _streamToString(req);
119
- return parseEmptyableJSON2(text);
120
- }
121
- if (contentType.startsWith("multipart/form-data")) {
122
- return _streamToFormData(req, contentType);
123
- }
124
- if (contentType.startsWith("application/x-www-form-urlencoded")) {
125
- const text = await _streamToString(req);
126
- return new URLSearchParams(text);
127
- }
128
- if (contentType.startsWith("text/event-stream")) {
129
- return toEventIterator(req);
130
- }
131
- if (contentType.startsWith("text/plain")) {
132
- return _streamToString(req);
133
- }
134
- return _streamToFile(req, "blob", contentType);
135
- }
136
- function toNodeHttpBody(body, headers, options = {}) {
137
- delete headers["content-type"];
138
- delete headers["content-disposition"];
139
- if (body === void 0) {
140
- return;
141
- }
142
- if (body instanceof Blob) {
143
- headers["content-type"] = body.type;
144
- headers["content-length"] = body.size.toString();
145
- headers["content-disposition"] = contentDisposition(
146
- body instanceof File ? body.name : "blob",
147
- { type: "inline" }
148
- );
149
- return Readable2.fromWeb(body.stream());
150
- }
151
- if (body instanceof FormData) {
152
- const response = new Response(body);
153
- headers["content-type"] = response.headers.get("content-type");
154
- return Readable2.fromWeb(response.body);
155
- }
156
- if (body instanceof URLSearchParams) {
157
- headers["content-type"] = "application/x-www-form-urlencoded";
158
- return body.toString();
159
- }
160
- if (isAsyncIteratorObject(body)) {
161
- headers["content-type"] = "text/event-stream";
162
- headers["cache-control"] = "no-cache";
163
- headers.connection = "keep-alive";
164
- return toEventStream(body, options);
165
- }
166
- headers["content-type"] = "application/json";
167
- return stringifyJSON2(body);
168
- }
169
- function _streamToFormData(stream, contentType) {
170
- const response = new Response(stream, {
171
- headers: {
172
- "content-type": contentType
173
- }
174
- });
175
- return response.formData();
176
- }
177
- async function _streamToString(stream) {
178
- let string = "";
179
- for await (const chunk of stream) {
180
- string += chunk.toString();
181
- }
182
- return string;
183
- }
184
- async function _streamToFile(stream, fileName, contentType) {
185
- const chunks = [];
186
- for await (const chunk of stream) {
187
- chunks.push(chunk);
188
- }
189
- return new File(chunks, fileName, { type: contentType });
190
- }
191
-
192
- // src/request.ts
193
- import { once } from "@orpc/shared";
194
-
195
- // src/signal.ts
196
- function toAbortSignal(res) {
197
- const controller = new AbortController();
198
- res.on("close", () => {
199
- if (res.errored) {
200
- controller.abort(res.errored.toString());
201
- } else if (!res.writableFinished) {
202
- controller.abort("Client connection prematurely closed.");
203
- } else {
204
- controller.abort("Server closed the connection.");
205
- }
206
- });
207
- return controller.signal;
208
- }
209
-
210
- // src/request.ts
211
- function toStandardRequest(req, res) {
212
- const method = req.method ?? "GET";
213
- const protocol = "encrypted" in req.socket && req.socket.encrypted ? "https:" : "http:";
214
- const host = req.headers.host ?? "localhost";
215
- const url = new URL(req.originalUrl ?? req.url ?? "/", `${protocol}//${host}`);
216
- return {
217
- raw: { request: req, response: res },
218
- method,
219
- url,
220
- headers: req.headers,
221
- body: once(() => toStandardBody(req)),
222
- signal: toAbortSignal(res)
223
- };
224
- }
225
-
226
- // src/response.ts
227
- function sendStandardResponse(res, standardResponse, options = {}) {
228
- return new Promise((resolve, reject) => {
229
- res.on("error", reject);
230
- res.on("finish", resolve);
231
- const resHeaders = standardResponse.headers;
232
- const resBody = toNodeHttpBody(standardResponse.body, resHeaders, options);
233
- res.writeHead(standardResponse.status, resHeaders);
234
- if (resBody === void 0) {
235
- res.end(resBody);
236
- } else if (typeof resBody === "string") {
237
- res.end(resBody);
238
- } else {
239
- res.on("close", () => {
240
- if (!resBody.closed) {
241
- resBody.destroy(res.errored ?? void 0);
242
- }
243
- });
244
- resBody.pipe(res);
245
- }
246
- });
247
- }
248
- export {
249
- sendStandardResponse,
250
- toAbortSignal,
251
- toEventIterator,
252
- toEventStream,
253
- toNodeHttpBody,
254
- toStandardBody,
255
- toStandardRequest
256
- };
257
- //# sourceMappingURL=index.js.map
@@ -1,14 +0,0 @@
1
- import type { StandardBody, StandardHeaders } from '@orpc/standard-server';
2
- import type { ToEventStreamOptions } from './event-source';
3
- import type { NodeHttpRequest } from './types';
4
- import { Readable } from 'node:stream';
5
- export declare function toStandardBody(req: NodeHttpRequest): Promise<StandardBody>;
6
- export interface ToNodeHttpBodyOptions extends ToEventStreamOptions {
7
- }
8
- /**
9
- * @param body
10
- * @param headers - WARNING: The headers can be changed by the function and effects on the original headers.
11
- * @param options
12
- */
13
- export declare function toNodeHttpBody(body: StandardBody, headers: StandardHeaders, options?: ToNodeHttpBodyOptions): Readable | undefined | string;
14
- //# sourceMappingURL=body.d.ts.map
@@ -1,24 +0,0 @@
1
- import { Readable } from 'node:stream';
2
- export declare function toEventIterator(stream: Readable): AsyncGenerator<unknown | void, unknown | void, void>;
3
- export interface ToEventStreamOptions {
4
- /**
5
- * If true, a ping comment is sent periodically to keep the connection alive.
6
- *
7
- * @default true
8
- */
9
- eventSourcePingEnabled?: boolean;
10
- /**
11
- * Interval (in milliseconds) between ping comments sent after the last event.
12
- *
13
- * @default 5000
14
- */
15
- eventSourcePingInterval?: number;
16
- /**
17
- * The content of the ping comment. Must not include newline characters.
18
- *
19
- * @default ''
20
- */
21
- eventSourcePingContent?: string;
22
- }
23
- export declare function toEventStream(iterator: AsyncIterator<unknown | void, unknown | void, void>, options?: ToEventStreamOptions): Readable;
24
- //# sourceMappingURL=event-source.d.ts.map
@@ -1,7 +0,0 @@
1
- export * from './body';
2
- export * from './event-source';
3
- export * from './request';
4
- export * from './response';
5
- export * from './signal';
6
- export * from './types';
7
- //# sourceMappingURL=index.d.ts.map
@@ -1,4 +0,0 @@
1
- import type { StandardRequest } from '@orpc/standard-server';
2
- import type { NodeHttpRequest, NodeHttpResponse } from './types';
3
- export declare function toStandardRequest(req: NodeHttpRequest, res: NodeHttpResponse): StandardRequest;
4
- //# sourceMappingURL=request.d.ts.map
@@ -1,7 +0,0 @@
1
- import type { StandardResponse } from '@orpc/standard-server';
2
- import type { ToNodeHttpBodyOptions } from './body';
3
- import type { NodeHttpResponse } from './types';
4
- export interface SendStandardResponseOptions extends ToNodeHttpBodyOptions {
5
- }
6
- export declare function sendStandardResponse(res: NodeHttpResponse, standardResponse: StandardResponse, options?: SendStandardResponseOptions): Promise<void>;
7
- //# sourceMappingURL=response.d.ts.map
@@ -1,3 +0,0 @@
1
- import type { NodeHttpResponse } from './types';
2
- export declare function toAbortSignal(res: NodeHttpResponse): AbortSignal;
3
- //# sourceMappingURL=signal.d.ts.map
@@ -1,11 +0,0 @@
1
- import type { IncomingMessage, ServerResponse } from 'node:http';
2
- import type { Http2ServerRequest, Http2ServerResponse } from 'node:http2';
3
- export type NodeHttpRequest = (IncomingMessage | Http2ServerRequest) & {
4
- /**
5
- * Replace `req.url` with `req.originalUrl` when `req.originalUrl` is available.
6
- * This is useful for `express.js` middleware.
7
- */
8
- originalUrl?: string;
9
- };
10
- export type NodeHttpResponse = ServerResponse | Http2ServerResponse;
11
- //# sourceMappingURL=types.d.ts.map