@orpc/standard-server-fetch 0.0.0-next.d0e429d → 0.0.0-next.d146c28

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.unnoq.com/logo.webp" width=280 alt="oRPC logo" />
3
3
  </div>
4
4
 
5
5
  <h1></h1>
@@ -21,28 +21,24 @@
21
21
 
22
22
  <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
23
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, ensuring a smooth and enjoyable developer experience.
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
25
 
26
26
  ---
27
27
 
28
28
  ## Highlights
29
29
 
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.
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
+ - **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte, Angular), Pinia Colada, and more.
34
+ - **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms.
35
+ - **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators.
36
+ - **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more.
37
+ - **⏱️ Lazy Router**: Enhance cold start times with our lazy routing feature.
38
+ - **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming.
39
+ - **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond.
40
+ - **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors.
41
+ - **🛡️ Reliability**: Well-tested, TypeScript-based, production-ready, and MIT licensed.
46
42
 
47
43
  ## Documentation
48
44
 
@@ -53,16 +49,28 @@ You can find the full documentation [here](https://orpc.unnoq.com).
53
49
  - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
54
50
  - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
55
51
  - [@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
52
  - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
53
+ - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with [NestJS](https://nestjs.com/).
54
+ - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
55
+ - [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration.
56
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
57
+ - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
60
58
  - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
59
+ - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
60
+ - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
61
61
 
62
62
  ## `@orpc/standard-server-fetch`
63
63
 
64
64
  [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) server adapter for oRPC.
65
65
 
66
+ ## Sponsors
67
+
68
+ <p align="center">
69
+ <a href="https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg">
70
+ <img src='https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg'/>
71
+ </a>
72
+ </p>
73
+
66
74
  ## License
67
75
 
68
76
  Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
@@ -0,0 +1,58 @@
1
+ import { StandardBody, StandardHeaders, StandardLazyRequest, StandardRequest, StandardResponse, StandardLazyResponse } from '@orpc/standard-server';
2
+ import { AsyncIteratorClass } from '@orpc/shared';
3
+
4
+ declare function toEventIterator(stream: ReadableStream<Uint8Array> | null): AsyncIteratorClass<unknown>;
5
+ interface ToEventStreamOptions {
6
+ /**
7
+ * If true, a ping comment is sent periodically to keep the connection alive.
8
+ *
9
+ * @default true
10
+ */
11
+ eventIteratorKeepAliveEnabled?: boolean;
12
+ /**
13
+ * Interval (in milliseconds) between ping comments sent after the last event.
14
+ *
15
+ * @default 5000
16
+ */
17
+ eventIteratorKeepAliveInterval?: number;
18
+ /**
19
+ * The content of the ping comment. Must not include newline characters.
20
+ *
21
+ * @default ''
22
+ */
23
+ eventIteratorKeepAliveComment?: string;
24
+ }
25
+ declare function toEventStream(iterator: AsyncIterator<unknown | void, unknown | void, void>, options?: ToEventStreamOptions): ReadableStream<Uint8Array>;
26
+
27
+ declare function toStandardBody(re: Request | Response): Promise<StandardBody>;
28
+ interface ToFetchBodyOptions extends ToEventStreamOptions {
29
+ }
30
+ /**
31
+ * @param body
32
+ * @param headers - The headers can be changed by the function and effects on the original headers.
33
+ */
34
+ declare function toFetchBody(body: StandardBody, headers: Headers, options?: ToFetchBodyOptions): string | Blob | FormData | URLSearchParams | undefined | ReadableStream<Uint8Array>;
35
+
36
+ /**
37
+ * @param headers
38
+ * @param standardHeaders - The base headers can be changed by the function and effects on the original headers.
39
+ */
40
+ declare function toStandardHeaders(headers: Headers, standardHeaders?: StandardHeaders): StandardHeaders;
41
+ /**
42
+ * @param headers
43
+ * @param fetchHeaders - The base headers can be changed by the function and effects on the original headers.
44
+ */
45
+ declare function toFetchHeaders(headers: StandardHeaders, fetchHeaders?: Headers): Headers;
46
+
47
+ declare function toStandardLazyRequest(request: Request): StandardLazyRequest;
48
+ interface ToFetchRequestOptions extends ToFetchBodyOptions {
49
+ }
50
+ declare function toFetchRequest(request: StandardRequest, options?: ToFetchRequestOptions): Request;
51
+
52
+ interface ToFetchResponseOptions extends ToFetchBodyOptions {
53
+ }
54
+ declare function toFetchResponse(response: StandardResponse, options?: ToFetchResponseOptions): Response;
55
+ declare function toStandardLazyResponse(response: Response): StandardLazyResponse;
56
+
57
+ export { toEventIterator, toEventStream, toFetchBody, toFetchHeaders, toFetchRequest, toFetchResponse, toStandardBody, toStandardHeaders, toStandardLazyRequest, toStandardLazyResponse };
58
+ export type { ToEventStreamOptions, ToFetchBodyOptions, ToFetchRequestOptions, ToFetchResponseOptions };
@@ -0,0 +1,58 @@
1
+ import { StandardBody, StandardHeaders, StandardLazyRequest, StandardRequest, StandardResponse, StandardLazyResponse } from '@orpc/standard-server';
2
+ import { AsyncIteratorClass } from '@orpc/shared';
3
+
4
+ declare function toEventIterator(stream: ReadableStream<Uint8Array> | null): AsyncIteratorClass<unknown>;
5
+ interface ToEventStreamOptions {
6
+ /**
7
+ * If true, a ping comment is sent periodically to keep the connection alive.
8
+ *
9
+ * @default true
10
+ */
11
+ eventIteratorKeepAliveEnabled?: boolean;
12
+ /**
13
+ * Interval (in milliseconds) between ping comments sent after the last event.
14
+ *
15
+ * @default 5000
16
+ */
17
+ eventIteratorKeepAliveInterval?: number;
18
+ /**
19
+ * The content of the ping comment. Must not include newline characters.
20
+ *
21
+ * @default ''
22
+ */
23
+ eventIteratorKeepAliveComment?: string;
24
+ }
25
+ declare function toEventStream(iterator: AsyncIterator<unknown | void, unknown | void, void>, options?: ToEventStreamOptions): ReadableStream<Uint8Array>;
26
+
27
+ declare function toStandardBody(re: Request | Response): Promise<StandardBody>;
28
+ interface ToFetchBodyOptions extends ToEventStreamOptions {
29
+ }
30
+ /**
31
+ * @param body
32
+ * @param headers - The headers can be changed by the function and effects on the original headers.
33
+ */
34
+ declare function toFetchBody(body: StandardBody, headers: Headers, options?: ToFetchBodyOptions): string | Blob | FormData | URLSearchParams | undefined | ReadableStream<Uint8Array>;
35
+
36
+ /**
37
+ * @param headers
38
+ * @param standardHeaders - The base headers can be changed by the function and effects on the original headers.
39
+ */
40
+ declare function toStandardHeaders(headers: Headers, standardHeaders?: StandardHeaders): StandardHeaders;
41
+ /**
42
+ * @param headers
43
+ * @param fetchHeaders - The base headers can be changed by the function and effects on the original headers.
44
+ */
45
+ declare function toFetchHeaders(headers: StandardHeaders, fetchHeaders?: Headers): Headers;
46
+
47
+ declare function toStandardLazyRequest(request: Request): StandardLazyRequest;
48
+ interface ToFetchRequestOptions extends ToFetchBodyOptions {
49
+ }
50
+ declare function toFetchRequest(request: StandardRequest, options?: ToFetchRequestOptions): Request;
51
+
52
+ interface ToFetchResponseOptions extends ToFetchBodyOptions {
53
+ }
54
+ declare function toFetchResponse(response: StandardResponse, options?: ToFetchResponseOptions): Response;
55
+ declare function toStandardLazyResponse(response: Response): StandardLazyResponse;
56
+
57
+ export { toEventIterator, toEventStream, toFetchBody, toFetchHeaders, toFetchRequest, toFetchResponse, toStandardBody, toStandardHeaders, toStandardLazyRequest, toStandardLazyResponse };
58
+ export type { ToEventStreamOptions, ToFetchBodyOptions, ToFetchRequestOptions, ToFetchResponseOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,232 @@
1
+ import { AsyncIteratorClass, parseEmptyableJSON, isTypescriptObject, stringifyJSON, isAsyncIteratorObject, once } from '@orpc/shared';
2
+ import { EventDecoderStream, withEventMeta, ErrorEvent, encodeEventMessage, getEventMeta, getFilenameFromContentDisposition, generateContentDisposition } from '@orpc/standard-server';
3
+
4
+ function toEventIterator(stream) {
5
+ const eventStream = stream?.pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream());
6
+ const reader = eventStream?.getReader();
7
+ return new AsyncIteratorClass(async () => {
8
+ while (true) {
9
+ if (reader === void 0) {
10
+ return { done: true, value: void 0 };
11
+ }
12
+ const { done, value } = await reader.read();
13
+ if (done) {
14
+ return { done: true, value: void 0 };
15
+ }
16
+ switch (value.event) {
17
+ case "message": {
18
+ let message = parseEmptyableJSON(value.data);
19
+ if (isTypescriptObject(message)) {
20
+ message = withEventMeta(message, value);
21
+ }
22
+ return { done: false, value: message };
23
+ }
24
+ case "error": {
25
+ let error = new ErrorEvent({
26
+ data: parseEmptyableJSON(value.data)
27
+ });
28
+ error = withEventMeta(error, value);
29
+ throw error;
30
+ }
31
+ case "done": {
32
+ let done2 = parseEmptyableJSON(value.data);
33
+ if (isTypescriptObject(done2)) {
34
+ done2 = withEventMeta(done2, value);
35
+ }
36
+ return { done: true, value: done2 };
37
+ }
38
+ }
39
+ }
40
+ }, async () => {
41
+ await reader?.cancel();
42
+ });
43
+ }
44
+ function toEventStream(iterator, options = {}) {
45
+ const keepAliveEnabled = options.eventIteratorKeepAliveEnabled ?? true;
46
+ const keepAliveInterval = options.eventIteratorKeepAliveInterval ?? 5e3;
47
+ const keepAliveComment = options.eventIteratorKeepAliveComment ?? "";
48
+ let cancelled = false;
49
+ let timeout;
50
+ const stream = new ReadableStream({
51
+ async pull(controller) {
52
+ try {
53
+ if (keepAliveEnabled) {
54
+ timeout = setInterval(() => {
55
+ controller.enqueue(encodeEventMessage({
56
+ comments: [keepAliveComment]
57
+ }));
58
+ }, keepAliveInterval);
59
+ }
60
+ const value = await iterator.next();
61
+ clearInterval(timeout);
62
+ if (cancelled) {
63
+ return;
64
+ }
65
+ const meta = getEventMeta(value.value);
66
+ if (!value.done || value.value !== void 0 || meta !== void 0) {
67
+ controller.enqueue(encodeEventMessage({
68
+ ...meta,
69
+ event: value.done ? "done" : "message",
70
+ data: stringifyJSON(value.value)
71
+ }));
72
+ }
73
+ if (value.done) {
74
+ controller.close();
75
+ }
76
+ } catch (err) {
77
+ clearInterval(timeout);
78
+ if (cancelled) {
79
+ return;
80
+ }
81
+ controller.enqueue(encodeEventMessage({
82
+ ...getEventMeta(err),
83
+ event: "error",
84
+ data: err instanceof ErrorEvent ? stringifyJSON(err.data) : void 0
85
+ }));
86
+ controller.close();
87
+ }
88
+ },
89
+ async cancel() {
90
+ cancelled = true;
91
+ clearInterval(timeout);
92
+ await iterator.return?.();
93
+ }
94
+ }).pipeThrough(new TextEncoderStream());
95
+ return stream;
96
+ }
97
+
98
+ async function toStandardBody(re) {
99
+ const contentDisposition = re.headers.get("content-disposition");
100
+ if (typeof contentDisposition === "string") {
101
+ const fileName = getFilenameFromContentDisposition(contentDisposition) ?? "blob";
102
+ const blob2 = await re.blob();
103
+ return new File([blob2], fileName, {
104
+ type: blob2.type
105
+ });
106
+ }
107
+ const contentType = re.headers.get("content-type");
108
+ if (!contentType || contentType.startsWith("application/json")) {
109
+ const text = await re.text();
110
+ return parseEmptyableJSON(text);
111
+ }
112
+ if (contentType.startsWith("multipart/form-data")) {
113
+ return await re.formData();
114
+ }
115
+ if (contentType.startsWith("application/x-www-form-urlencoded")) {
116
+ const text = await re.text();
117
+ return new URLSearchParams(text);
118
+ }
119
+ if (contentType.startsWith("text/event-stream")) {
120
+ return toEventIterator(re.body);
121
+ }
122
+ if (contentType.startsWith("text/plain")) {
123
+ return await re.text();
124
+ }
125
+ const blob = await re.blob();
126
+ return new File([blob], "blob", {
127
+ type: blob.type
128
+ });
129
+ }
130
+ function toFetchBody(body, headers, options = {}) {
131
+ const currentContentDisposition = headers.get("content-disposition");
132
+ headers.delete("content-type");
133
+ headers.delete("content-disposition");
134
+ if (body === void 0) {
135
+ return void 0;
136
+ }
137
+ if (body instanceof Blob) {
138
+ headers.set("content-type", body.type);
139
+ headers.set("content-length", body.size.toString());
140
+ headers.set(
141
+ "content-disposition",
142
+ currentContentDisposition ?? generateContentDisposition(body instanceof File ? body.name : "blob")
143
+ );
144
+ return body;
145
+ }
146
+ if (body instanceof FormData) {
147
+ return body;
148
+ }
149
+ if (body instanceof URLSearchParams) {
150
+ return body;
151
+ }
152
+ if (isAsyncIteratorObject(body)) {
153
+ headers.set("content-type", "text/event-stream");
154
+ return toEventStream(body, options);
155
+ }
156
+ headers.set("content-type", "application/json");
157
+ return stringifyJSON(body);
158
+ }
159
+
160
+ function toStandardHeaders(headers, standardHeaders = {}) {
161
+ for (const [key, value] of headers) {
162
+ if (Array.isArray(standardHeaders[key])) {
163
+ standardHeaders[key].push(value);
164
+ } else if (standardHeaders[key] !== void 0) {
165
+ standardHeaders[key] = [standardHeaders[key], value];
166
+ } else {
167
+ standardHeaders[key] = value;
168
+ }
169
+ }
170
+ return standardHeaders;
171
+ }
172
+ function toFetchHeaders(headers, fetchHeaders = new Headers()) {
173
+ for (const [key, value] of Object.entries(headers)) {
174
+ if (Array.isArray(value)) {
175
+ for (const v of value) {
176
+ fetchHeaders.append(key, v);
177
+ }
178
+ } else if (value !== void 0) {
179
+ fetchHeaders.append(key, value);
180
+ }
181
+ }
182
+ return fetchHeaders;
183
+ }
184
+
185
+ function toStandardLazyRequest(request) {
186
+ return {
187
+ url: new URL(request.url),
188
+ signal: request.signal,
189
+ method: request.method,
190
+ body: once(() => toStandardBody(request)),
191
+ get headers() {
192
+ const headers = toStandardHeaders(request.headers);
193
+ Object.defineProperty(this, "headers", { value: headers, writable: true });
194
+ return headers;
195
+ },
196
+ set headers(value) {
197
+ Object.defineProperty(this, "headers", { value, writable: true });
198
+ }
199
+ };
200
+ }
201
+ function toFetchRequest(request, options = {}) {
202
+ const headers = toFetchHeaders(request.headers);
203
+ const body = toFetchBody(request.body, headers, options);
204
+ return new Request(request.url, {
205
+ signal: request.signal,
206
+ method: request.method,
207
+ headers,
208
+ body
209
+ });
210
+ }
211
+
212
+ function toFetchResponse(response, options = {}) {
213
+ const headers = toFetchHeaders(response.headers);
214
+ const body = toFetchBody(response.body, headers, options);
215
+ return new Response(body, { headers, status: response.status });
216
+ }
217
+ function toStandardLazyResponse(response) {
218
+ return {
219
+ body: once(() => toStandardBody(response)),
220
+ status: response.status,
221
+ get headers() {
222
+ const headers = toStandardHeaders(response.headers);
223
+ Object.defineProperty(this, "headers", { value: headers, writable: true });
224
+ return headers;
225
+ },
226
+ set headers(value) {
227
+ Object.defineProperty(this, "headers", { value, writable: true });
228
+ }
229
+ };
230
+ }
231
+
232
+ export { toEventIterator, toEventStream, toFetchBody, toFetchHeaders, toFetchRequest, toFetchResponse, toStandardBody, toStandardHeaders, toStandardLazyRequest, toStandardLazyResponse };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@orpc/standard-server-fetch",
3
3
  "type": "module",
4
- "version": "0.0.0-next.d0e429d",
4
+ "version": "0.0.0-next.d146c28",
5
5
  "license": "MIT",
6
6
  "homepage": "https://unnoq.com",
7
7
  "repository": {
@@ -14,28 +14,23 @@
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/shared": "0.0.0-next.d146c28",
27
+ "@orpc/standard-server": "0.0.0-next.d146c28"
33
28
  },
34
29
  "devDependencies": {
35
- "@hono/node-server": "^1.13.8"
30
+ "@hono/node-server": "^1.16.0"
36
31
  },
37
32
  "scripts": {
38
- "build": "tsup --clean --sourcemap --entry.index=src/index.ts --format=esm --onSuccess='tsc -b --noCheck'",
33
+ "build": "unbuild",
39
34
  "build:watch": "pnpm run build --watch",
40
35
  "type:check": "tsc -b"
41
36
  }
package/dist/index.js DELETED
@@ -1,232 +0,0 @@
1
- // src/body.ts
2
- import { isAsyncIteratorObject, parseEmptyableJSON as parseEmptyableJSON2, stringifyJSON as stringifyJSON2 } from "@orpc/shared";
3
- import { contentDisposition, parseContentDisposition } from "@orpc/standard-server";
4
-
5
- // src/event-source.ts
6
- import { isTypescriptObject, parseEmptyableJSON, stringifyJSON } from "@orpc/shared";
7
- import {
8
- encodeEventMessage,
9
- ErrorEvent,
10
- EventDecoderStream,
11
- getEventMeta,
12
- withEventMeta
13
- } from "@orpc/standard-server";
14
- function toEventIterator(stream) {
15
- const eventStream = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream());
16
- const reader = eventStream.getReader();
17
- async function* gen() {
18
- try {
19
- while (true) {
20
- const { done, value } = await reader.read();
21
- if (done) {
22
- return;
23
- }
24
- switch (value.event) {
25
- case "message": {
26
- let message = parseEmptyableJSON(value.data);
27
- if (isTypescriptObject(message)) {
28
- message = withEventMeta(message, value);
29
- }
30
- yield message;
31
- break;
32
- }
33
- case "error": {
34
- let error = new ErrorEvent({
35
- data: parseEmptyableJSON(value.data)
36
- });
37
- error = withEventMeta(error, value);
38
- throw error;
39
- }
40
- case "done": {
41
- let done2 = parseEmptyableJSON(value.data);
42
- if (isTypescriptObject(done2)) {
43
- done2 = withEventMeta(done2, value);
44
- }
45
- return done2;
46
- }
47
- }
48
- }
49
- } finally {
50
- await reader.cancel();
51
- }
52
- }
53
- return gen();
54
- }
55
- function toEventStream(iterator, options = {}) {
56
- const pingEnabled = options.eventSourcePingEnabled ?? true;
57
- const pingInterval = options.eventSourcePingInterval ?? 5e3;
58
- const pingContent = options.eventSourcePingContent ?? "";
59
- let timeout;
60
- const stream = new ReadableStream({
61
- async pull(controller) {
62
- try {
63
- if (pingEnabled) {
64
- timeout = setInterval(() => {
65
- controller.enqueue(encodeEventMessage({
66
- comments: [pingContent]
67
- }));
68
- }, pingInterval);
69
- }
70
- const value = await iterator.next();
71
- clearInterval(timeout);
72
- controller.enqueue(encodeEventMessage({
73
- ...getEventMeta(value.value),
74
- event: value.done ? "done" : "message",
75
- data: stringifyJSON(value.value)
76
- }));
77
- if (value.done) {
78
- controller.close();
79
- }
80
- } catch (err) {
81
- clearInterval(timeout);
82
- controller.enqueue(encodeEventMessage({
83
- ...getEventMeta(err),
84
- event: "error",
85
- data: err instanceof ErrorEvent ? stringifyJSON(err.data) : void 0
86
- }));
87
- controller.close();
88
- }
89
- },
90
- async cancel(reason) {
91
- if (reason) {
92
- await iterator.throw?.(reason);
93
- } else {
94
- await iterator.return?.();
95
- }
96
- }
97
- }).pipeThrough(new TextEncoderStream());
98
- return stream;
99
- }
100
-
101
- // src/body.ts
102
- async function toStandardBody(re) {
103
- if (!re.body) {
104
- return void 0;
105
- }
106
- const contentDisposition2 = re.headers.get("content-disposition");
107
- if (contentDisposition2) {
108
- const fileName = parseContentDisposition(contentDisposition2).parameters.filename;
109
- if (typeof fileName === "string") {
110
- const blob2 = await re.blob();
111
- return new File([blob2], fileName, {
112
- type: blob2.type
113
- });
114
- }
115
- }
116
- const contentType = re.headers.get("content-type");
117
- if (!contentType || contentType.startsWith("application/json")) {
118
- const text = await re.text();
119
- return parseEmptyableJSON2(text);
120
- }
121
- if (contentType.startsWith("multipart/form-data")) {
122
- return await re.formData();
123
- }
124
- if (contentType.startsWith("application/x-www-form-urlencoded")) {
125
- const text = await re.text();
126
- return new URLSearchParams(text);
127
- }
128
- if (contentType.startsWith("text/event-stream")) {
129
- return toEventIterator(re.body);
130
- }
131
- if (contentType.startsWith("text/plain")) {
132
- return await re.text();
133
- }
134
- const blob = await re.blob();
135
- return new File([blob], "blob", {
136
- type: blob.type
137
- });
138
- }
139
- function toFetchBody(body, headers, options = {}) {
140
- headers.delete("content-type");
141
- headers.delete("content-disposition");
142
- if (body === void 0) {
143
- return void 0;
144
- }
145
- if (body instanceof Blob) {
146
- headers.set("content-type", body.type);
147
- headers.set("content-length", body.size.toString());
148
- headers.set(
149
- "content-disposition",
150
- contentDisposition(body instanceof File ? body.name : "blob", { type: "inline" })
151
- );
152
- return body;
153
- }
154
- if (body instanceof FormData) {
155
- return body;
156
- }
157
- if (body instanceof URLSearchParams) {
158
- return body;
159
- }
160
- if (isAsyncIteratorObject(body)) {
161
- headers.set("content-type", "text/event-stream");
162
- headers.set("cache-control", "no-cache");
163
- headers.set("connection", "keep-alive");
164
- return toEventStream(body, options);
165
- }
166
- headers.set("content-type", "application/json");
167
- return stringifyJSON2(body);
168
- }
169
-
170
- // src/headers.ts
171
- function toStandardHeaders(headers, standardHeaders = {}) {
172
- for (const [key, value] of headers) {
173
- if (Array.isArray(standardHeaders[key])) {
174
- standardHeaders[key].push(value);
175
- } else if (standardHeaders[key] !== void 0) {
176
- standardHeaders[key] = [standardHeaders[key], value];
177
- } else {
178
- standardHeaders[key] = value;
179
- }
180
- }
181
- return standardHeaders;
182
- }
183
- function toFetchHeaders(headers, fetchHeaders = new Headers()) {
184
- for (const [key, value] of Object.entries(headers)) {
185
- if (Array.isArray(value)) {
186
- for (const v of value) {
187
- fetchHeaders.append(key, v);
188
- }
189
- } else if (value !== void 0) {
190
- fetchHeaders.append(key, value);
191
- }
192
- }
193
- return fetchHeaders;
194
- }
195
-
196
- // src/request.ts
197
- import { once } from "@orpc/shared";
198
- function toStandardRequest(request) {
199
- return {
200
- raw: { request },
201
- url: new URL(request.url),
202
- signal: request.signal,
203
- method: request.method,
204
- body: once(() => toStandardBody(request)),
205
- get headers() {
206
- const headers = toStandardHeaders(request.headers);
207
- Object.defineProperty(this, "headers", { value: headers, writable: true });
208
- return headers;
209
- },
210
- set headers(value) {
211
- Object.defineProperty(this, "headers", { value, writable: true });
212
- }
213
- };
214
- }
215
-
216
- // src/response.ts
217
- function toFetchResponse(response, options = {}) {
218
- const headers = toFetchHeaders(response.headers);
219
- const body = toFetchBody(response.body, headers, options);
220
- return new Response(body, { headers, status: response.status });
221
- }
222
- export {
223
- toEventIterator,
224
- toEventStream,
225
- toFetchBody,
226
- toFetchHeaders,
227
- toFetchResponse,
228
- toStandardBody,
229
- toStandardHeaders,
230
- toStandardRequest
231
- };
232
- //# sourceMappingURL=index.js.map
@@ -1,11 +0,0 @@
1
- import type { StandardBody } from '@orpc/standard-server';
2
- import type { ToEventStreamOptions } from './event-source';
3
- export declare function toStandardBody(re: Request | Response): Promise<StandardBody>;
4
- export interface ToFetchBodyOptions extends ToEventStreamOptions {
5
- }
6
- /**
7
- * @param body
8
- * @param headers - The headers can be changed by the function and effects on the original headers.
9
- */
10
- export declare function toFetchBody(body: StandardBody, headers: Headers, options?: ToFetchBodyOptions): string | Blob | FormData | URLSearchParams | undefined | ReadableStream<Uint8Array>;
11
- //# sourceMappingURL=body.d.ts.map
@@ -1,23 +0,0 @@
1
- export declare function toEventIterator(stream: ReadableStream<Uint8Array>): AsyncGenerator<unknown | void, unknown | void, void>;
2
- export interface ToEventStreamOptions {
3
- /**
4
- * If true, a ping comment is sent periodically to keep the connection alive.
5
- *
6
- * @default true
7
- */
8
- eventSourcePingEnabled?: boolean;
9
- /**
10
- * Interval (in milliseconds) between ping comments sent after the last event.
11
- *
12
- * @default 5000
13
- */
14
- eventSourcePingInterval?: number;
15
- /**
16
- * The content of the ping comment. Must not include newline characters.
17
- *
18
- * @default ''
19
- */
20
- eventSourcePingContent?: string;
21
- }
22
- export declare function toEventStream(iterator: AsyncIterator<unknown | void, unknown | void, void>, options?: ToEventStreamOptions): ReadableStream<Uint8Array>;
23
- //# sourceMappingURL=event-source.d.ts.map
@@ -1,12 +0,0 @@
1
- import type { StandardHeaders } from '@orpc/standard-server';
2
- /**
3
- * @param headers
4
- * @param standardHeaders - The base headers can be changed by the function and effects on the original headers.
5
- */
6
- export declare function toStandardHeaders(headers: Headers, standardHeaders?: StandardHeaders): StandardHeaders;
7
- /**
8
- * @param headers
9
- * @param fetchHeaders - The base headers can be changed by the function and effects on the original headers.
10
- */
11
- export declare function toFetchHeaders(headers: StandardHeaders, fetchHeaders?: Headers): Headers;
12
- //# sourceMappingURL=headers.d.ts.map
@@ -1,6 +0,0 @@
1
- export * from './body';
2
- export * from './event-source';
3
- export * from './headers';
4
- export * from './request';
5
- export * from './response';
6
- //# sourceMappingURL=index.d.ts.map
@@ -1,3 +0,0 @@
1
- import type { StandardRequest } from '@orpc/standard-server';
2
- export declare function toStandardRequest(request: Request): StandardRequest;
3
- //# sourceMappingURL=request.d.ts.map
@@ -1,6 +0,0 @@
1
- import type { StandardResponse } from '@orpc/standard-server';
2
- import type { ToFetchBodyOptions } from './body';
3
- export interface ToFetchResponseOptions extends ToFetchBodyOptions {
4
- }
5
- export declare function toFetchResponse(response: StandardResponse, options?: ToFetchResponseOptions): Response;
6
- //# sourceMappingURL=response.d.ts.map