@orpc/standard-server-fetch 0.0.0-next.f635909 → 0.0.0-next.f677f1d

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
@@ -17,6 +17,9 @@
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>
@@ -30,7 +33,8 @@
30
33
  - **🔗 End-to-End Type Safety**: Ensure type-safe inputs, outputs, and errors from client to server.
31
34
  - **📘 First-Class OpenAPI**: Built-in support that fully adheres to the OpenAPI standard.
32
35
  - **📝 Contract-First Development**: Optionally define your API contract before implementation.
33
- - **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte), Pinia Colada, and more.
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.
34
38
  - **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms.
35
39
  - **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators.
36
40
  - **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more.
@@ -38,7 +42,6 @@
38
42
  - **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming.
39
43
  - **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond.
40
44
  - **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors.
41
- - **🛡️ Reliability**: Well-tested, TypeScript-based, production-ready, and MIT licensed.
42
45
 
43
46
  ## Documentation
44
47
 
@@ -49,13 +52,14 @@ You can find the full documentation [here](https://orpc.unnoq.com).
49
52
  - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
50
53
  - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
51
54
  - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
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/).
52
58
  - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
53
- - [@orpc/react-query](https://www.npmjs.com/package/@orpc/react-query): Integration with [React Query](https://tanstack.com/query/latest/docs/framework/react/overview).
54
- - [@orpc/vue-query](https://www.npmjs.com/package/@orpc/vue-query): Integration with [Vue Query](https://tanstack.com/query/latest/docs/framework/vue/overview).
55
- - [@orpc/solid-query](https://www.npmjs.com/package/@orpc/solid-query): Integration with [Solid Query](https://tanstack.com/query/latest/docs/framework/solid/overview).
56
- - [@orpc/svelte-query](https://www.npmjs.com/package/@orpc/svelte-query): Integration with [Svelte Query](https://tanstack.com/query/latest/docs/framework/svelte/overview).
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.
57
61
  - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
58
- - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
62
+ - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
59
63
  - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
60
64
  - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
61
65
  - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
package/dist/index.d.mts CHANGED
@@ -1,6 +1,9 @@
1
1
  import { StandardBody, StandardHeaders, StandardLazyRequest, StandardRequest, StandardResponse, StandardLazyResponse } from '@orpc/standard-server';
2
+ import { SetSpanErrorOptions, AsyncIteratorClass } from '@orpc/shared';
2
3
 
3
- declare function toEventIterator(stream: ReadableStream<Uint8Array>): AsyncGenerator<unknown | void, unknown | void, void>;
4
+ interface ToEventIteratorOptions extends SetSpanErrorOptions {
5
+ }
6
+ declare function toEventIterator(stream: ReadableStream<Uint8Array> | null, options?: ToEventIteratorOptions): AsyncIteratorClass<unknown>;
4
7
  interface ToEventStreamOptions {
5
8
  /**
6
9
  * If true, a ping comment is sent periodically to keep the connection alive.
@@ -23,7 +26,9 @@ interface ToEventStreamOptions {
23
26
  }
24
27
  declare function toEventStream(iterator: AsyncIterator<unknown | void, unknown | void, void>, options?: ToEventStreamOptions): ReadableStream<Uint8Array>;
25
28
 
26
- declare function toStandardBody(re: Request | Response): Promise<StandardBody>;
29
+ interface ToStandardBodyOptions extends ToEventIteratorOptions {
30
+ }
31
+ declare function toStandardBody(re: Request | Response, options?: ToStandardBodyOptions): Promise<StandardBody>;
27
32
  interface ToFetchBodyOptions extends ToEventStreamOptions {
28
33
  }
29
34
  /**
@@ -51,7 +56,9 @@ declare function toFetchRequest(request: StandardRequest, options?: ToFetchReque
51
56
  interface ToFetchResponseOptions extends ToFetchBodyOptions {
52
57
  }
53
58
  declare function toFetchResponse(response: StandardResponse, options?: ToFetchResponseOptions): Response;
54
- declare function toStandardLazyResponse(response: Response): StandardLazyResponse;
59
+ interface ToStandardLazyResponseOptions extends ToStandardBodyOptions {
60
+ }
61
+ declare function toStandardLazyResponse(response: Response, options?: ToStandardLazyResponseOptions): StandardLazyResponse;
55
62
 
56
63
  export { toEventIterator, toEventStream, toFetchBody, toFetchHeaders, toFetchRequest, toFetchResponse, toStandardBody, toStandardHeaders, toStandardLazyRequest, toStandardLazyResponse };
57
- export type { ToEventStreamOptions, ToFetchBodyOptions, ToFetchRequestOptions, ToFetchResponseOptions };
64
+ export type { ToEventIteratorOptions, ToEventStreamOptions, ToFetchBodyOptions, ToFetchRequestOptions, ToFetchResponseOptions, ToStandardBodyOptions, ToStandardLazyResponseOptions };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import { StandardBody, StandardHeaders, StandardLazyRequest, StandardRequest, StandardResponse, StandardLazyResponse } from '@orpc/standard-server';
2
+ import { SetSpanErrorOptions, AsyncIteratorClass } from '@orpc/shared';
2
3
 
3
- declare function toEventIterator(stream: ReadableStream<Uint8Array>): AsyncGenerator<unknown | void, unknown | void, void>;
4
+ interface ToEventIteratorOptions extends SetSpanErrorOptions {
5
+ }
6
+ declare function toEventIterator(stream: ReadableStream<Uint8Array> | null, options?: ToEventIteratorOptions): AsyncIteratorClass<unknown>;
4
7
  interface ToEventStreamOptions {
5
8
  /**
6
9
  * If true, a ping comment is sent periodically to keep the connection alive.
@@ -23,7 +26,9 @@ interface ToEventStreamOptions {
23
26
  }
24
27
  declare function toEventStream(iterator: AsyncIterator<unknown | void, unknown | void, void>, options?: ToEventStreamOptions): ReadableStream<Uint8Array>;
25
28
 
26
- declare function toStandardBody(re: Request | Response): Promise<StandardBody>;
29
+ interface ToStandardBodyOptions extends ToEventIteratorOptions {
30
+ }
31
+ declare function toStandardBody(re: Request | Response, options?: ToStandardBodyOptions): Promise<StandardBody>;
27
32
  interface ToFetchBodyOptions extends ToEventStreamOptions {
28
33
  }
29
34
  /**
@@ -51,7 +56,9 @@ declare function toFetchRequest(request: StandardRequest, options?: ToFetchReque
51
56
  interface ToFetchResponseOptions extends ToFetchBodyOptions {
52
57
  }
53
58
  declare function toFetchResponse(response: StandardResponse, options?: ToFetchResponseOptions): Response;
54
- declare function toStandardLazyResponse(response: Response): StandardLazyResponse;
59
+ interface ToStandardLazyResponseOptions extends ToStandardBodyOptions {
60
+ }
61
+ declare function toStandardLazyResponse(response: Response, options?: ToStandardLazyResponseOptions): StandardLazyResponse;
55
62
 
56
63
  export { toEventIterator, toEventStream, toFetchBody, toFetchHeaders, toFetchRequest, toFetchResponse, toStandardBody, toStandardHeaders, toStandardLazyRequest, toStandardLazyResponse };
57
- export type { ToEventStreamOptions, ToFetchBodyOptions, ToFetchRequestOptions, ToFetchResponseOptions };
64
+ export type { ToEventIteratorOptions, ToEventStreamOptions, ToFetchBodyOptions, ToFetchRequestOptions, ToFetchResponseOptions, ToStandardBodyOptions, ToStandardLazyResponseOptions };
package/dist/index.mjs CHANGED
@@ -1,15 +1,24 @@
1
- import { stringifyJSON, parseEmptyableJSON, isTypescriptObject, isAsyncIteratorObject, once } from '@orpc/shared';
2
- import { EventDecoderStream, encodeEventMessage, getEventMeta, ErrorEvent, withEventMeta, getFilenameFromContentDisposition, generateContentDisposition } from '@orpc/standard-server';
1
+ import { AsyncIteratorClass, startSpan, runInSpanContext, AbortError, parseEmptyableJSON, isTypescriptObject, setSpanError, stringifyJSON, runWithSpan, isAsyncIteratorObject, once } from '@orpc/shared';
2
+ import { EventDecoderStream, withEventMeta, ErrorEvent, encodeEventMessage, getEventMeta, getFilenameFromContentDisposition, generateContentDisposition } from '@orpc/standard-server';
3
3
 
4
- function toEventIterator(stream) {
5
- const eventStream = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream());
6
- const reader = eventStream.getReader();
7
- async function* gen() {
4
+ function toEventIterator(stream, options = {}) {
5
+ const eventStream = stream?.pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream());
6
+ const reader = eventStream?.getReader();
7
+ let span;
8
+ let isCancelled = false;
9
+ return new AsyncIteratorClass(async () => {
10
+ span ??= startSpan("consume_event_iterator_stream");
8
11
  try {
9
12
  while (true) {
10
- const { done, value } = await reader.read();
13
+ if (reader === void 0) {
14
+ return { done: true, value: void 0 };
15
+ }
16
+ const { done, value } = await runInSpanContext(span, () => reader.read());
11
17
  if (done) {
12
- return;
18
+ if (isCancelled) {
19
+ throw new AbortError("Stream was cancelled");
20
+ }
21
+ return { done: true, value: void 0 };
13
22
  }
14
23
  switch (value.event) {
15
24
  case "message": {
@@ -17,14 +26,15 @@ function toEventIterator(stream) {
17
26
  if (isTypescriptObject(message)) {
18
27
  message = withEventMeta(message, value);
19
28
  }
20
- yield message;
21
- break;
29
+ span?.addEvent("message");
30
+ return { done: false, value: message };
22
31
  }
23
32
  case "error": {
24
33
  let error = new ErrorEvent({
25
34
  data: parseEmptyableJSON(value.data)
26
35
  });
27
36
  error = withEventMeta(error, value);
37
+ span?.addEvent("error");
28
38
  throw error;
29
39
  }
30
40
  case "done": {
@@ -32,22 +42,46 @@ function toEventIterator(stream) {
32
42
  if (isTypescriptObject(done2)) {
33
43
  done2 = withEventMeta(done2, value);
34
44
  }
35
- return done2;
45
+ span?.addEvent("done");
46
+ return { done: true, value: done2 };
47
+ }
48
+ default: {
49
+ span?.addEvent("maybe_keepalive");
36
50
  }
37
51
  }
38
52
  }
53
+ } catch (e) {
54
+ if (!(e instanceof ErrorEvent)) {
55
+ setSpanError(span, e, options);
56
+ }
57
+ throw e;
58
+ }
59
+ }, async (reason) => {
60
+ try {
61
+ if (reason !== "next") {
62
+ isCancelled = true;
63
+ span?.addEvent("cancelled");
64
+ }
65
+ await runInSpanContext(span, () => reader?.cancel());
66
+ } catch (e) {
67
+ setSpanError(span, e, options);
68
+ throw e;
39
69
  } finally {
40
- await reader.cancel();
70
+ span?.end();
41
71
  }
42
- }
43
- return gen();
72
+ });
44
73
  }
45
74
  function toEventStream(iterator, options = {}) {
46
75
  const keepAliveEnabled = options.eventIteratorKeepAliveEnabled ?? true;
47
76
  const keepAliveInterval = options.eventIteratorKeepAliveInterval ?? 5e3;
48
77
  const keepAliveComment = options.eventIteratorKeepAliveComment ?? "";
78
+ let cancelled = false;
49
79
  let timeout;
80
+ let span;
50
81
  const stream = new ReadableStream({
82
+ start() {
83
+ span = startSpan("stream_event_iterator");
84
+ },
51
85
  async pull(controller) {
52
86
  try {
53
87
  if (keepAliveEnabled) {
@@ -55,76 +89,101 @@ function toEventStream(iterator, options = {}) {
55
89
  controller.enqueue(encodeEventMessage({
56
90
  comments: [keepAliveComment]
57
91
  }));
92
+ span?.addEvent("keepalive");
58
93
  }, keepAliveInterval);
59
94
  }
60
- const value = await iterator.next();
95
+ const value = await runInSpanContext(span, () => iterator.next());
61
96
  clearInterval(timeout);
97
+ if (cancelled) {
98
+ return;
99
+ }
62
100
  const meta = getEventMeta(value.value);
63
101
  if (!value.done || value.value !== void 0 || meta !== void 0) {
102
+ const event = value.done ? "done" : "message";
64
103
  controller.enqueue(encodeEventMessage({
65
104
  ...meta,
66
- event: value.done ? "done" : "message",
105
+ event,
67
106
  data: stringifyJSON(value.value)
68
107
  }));
108
+ span?.addEvent(event);
69
109
  }
70
110
  if (value.done) {
71
111
  controller.close();
112
+ span?.end();
72
113
  }
73
114
  } catch (err) {
74
115
  clearInterval(timeout);
75
- controller.enqueue(encodeEventMessage({
76
- ...getEventMeta(err),
77
- event: "error",
78
- data: err instanceof ErrorEvent ? stringifyJSON(err.data) : void 0
79
- }));
80
- controller.close();
116
+ if (cancelled) {
117
+ return;
118
+ }
119
+ if (err instanceof ErrorEvent) {
120
+ controller.enqueue(encodeEventMessage({
121
+ ...getEventMeta(err),
122
+ event: "error",
123
+ data: stringifyJSON(err.data)
124
+ }));
125
+ span?.addEvent("error");
126
+ controller.close();
127
+ } else {
128
+ setSpanError(span, err);
129
+ controller.error(err);
130
+ }
131
+ span?.end();
81
132
  }
82
133
  },
83
- async cancel(reason) {
84
- if (reason) {
85
- await iterator.throw?.(reason);
86
- } else {
87
- await iterator.return?.();
134
+ async cancel() {
135
+ try {
136
+ cancelled = true;
137
+ clearInterval(timeout);
138
+ span?.addEvent("cancelled");
139
+ await runInSpanContext(span, () => iterator.return?.());
140
+ } catch (e) {
141
+ setSpanError(span, e);
142
+ throw e;
143
+ } finally {
144
+ span?.end();
88
145
  }
89
146
  }
90
147
  }).pipeThrough(new TextEncoderStream());
91
148
  return stream;
92
149
  }
93
150
 
94
- async function toStandardBody(re) {
95
- if (re.body === null) {
96
- return void 0;
97
- }
98
- const contentDisposition = re.headers.get("content-disposition");
99
- if (typeof contentDisposition === "string") {
100
- const fileName = getFilenameFromContentDisposition(contentDisposition) ?? "blob";
101
- const blob2 = await re.blob();
102
- return new File([blob2], fileName, {
103
- type: blob2.type
104
- });
105
- }
106
- const contentType = re.headers.get("content-type");
107
- if (!contentType || contentType.startsWith("application/json")) {
108
- const text = await re.text();
109
- return parseEmptyableJSON(text);
110
- }
111
- if (contentType.startsWith("multipart/form-data")) {
112
- return await re.formData();
113
- }
114
- if (contentType.startsWith("application/x-www-form-urlencoded")) {
115
- const text = await re.text();
116
- return new URLSearchParams(text);
117
- }
118
- if (contentType.startsWith("text/event-stream")) {
119
- return toEventIterator(re.body);
120
- }
121
- if (contentType.startsWith("text/plain")) {
122
- return await re.text();
123
- }
124
- const blob = await re.blob();
125
- return new File([blob], "blob", {
126
- type: blob.type
127
- });
151
+ function toStandardBody(re, options = {}) {
152
+ return runWithSpan(
153
+ { name: "parse_standard_body", signal: options.signal },
154
+ async () => {
155
+ const contentDisposition = re.headers.get("content-disposition");
156
+ if (typeof contentDisposition === "string") {
157
+ const fileName = getFilenameFromContentDisposition(contentDisposition) ?? "blob";
158
+ const blob2 = await re.blob();
159
+ return new File([blob2], fileName, {
160
+ type: blob2.type
161
+ });
162
+ }
163
+ const contentType = re.headers.get("content-type");
164
+ if (!contentType || contentType.startsWith("application/json")) {
165
+ const text = await re.text();
166
+ return parseEmptyableJSON(text);
167
+ }
168
+ if (contentType.startsWith("multipart/form-data")) {
169
+ return await re.formData();
170
+ }
171
+ if (contentType.startsWith("application/x-www-form-urlencoded")) {
172
+ const text = await re.text();
173
+ return new URLSearchParams(text);
174
+ }
175
+ if (contentType.startsWith("text/event-stream")) {
176
+ return toEventIterator(re.body, options);
177
+ }
178
+ if (contentType.startsWith("text/plain")) {
179
+ return await re.text();
180
+ }
181
+ const blob = await re.blob();
182
+ return new File([blob], "blob", {
183
+ type: blob.type
184
+ });
185
+ }
186
+ );
128
187
  }
129
188
  function toFetchBody(body, headers, options = {}) {
130
189
  const currentContentDisposition = headers.get("content-disposition");
@@ -150,8 +209,6 @@ function toFetchBody(body, headers, options = {}) {
150
209
  }
151
210
  if (isAsyncIteratorObject(body)) {
152
211
  headers.set("content-type", "text/event-stream");
153
- headers.set("cache-control", "no-cache");
154
- headers.set("connection", "keep-alive");
155
212
  return toEventStream(body, options);
156
213
  }
157
214
  headers.set("content-type", "application/json");
@@ -159,7 +216,7 @@ function toFetchBody(body, headers, options = {}) {
159
216
  }
160
217
 
161
218
  function toStandardHeaders(headers, standardHeaders = {}) {
162
- for (const [key, value] of headers) {
219
+ headers.forEach((value, key) => {
163
220
  if (Array.isArray(standardHeaders[key])) {
164
221
  standardHeaders[key].push(value);
165
222
  } else if (standardHeaders[key] !== void 0) {
@@ -167,7 +224,7 @@ function toStandardHeaders(headers, standardHeaders = {}) {
167
224
  } else {
168
225
  standardHeaders[key] = value;
169
226
  }
170
- }
227
+ });
171
228
  return standardHeaders;
172
229
  }
173
230
  function toFetchHeaders(headers, fetchHeaders = new Headers()) {
@@ -188,7 +245,7 @@ function toStandardLazyRequest(request) {
188
245
  url: new URL(request.url),
189
246
  signal: request.signal,
190
247
  method: request.method,
191
- body: once(() => toStandardBody(request)),
248
+ body: once(() => toStandardBody(request, { signal: request.signal })),
192
249
  get headers() {
193
250
  const headers = toStandardHeaders(request.headers);
194
251
  Object.defineProperty(this, "headers", { value: headers, writable: true });
@@ -215,9 +272,9 @@ function toFetchResponse(response, options = {}) {
215
272
  const body = toFetchBody(response.body, headers, options);
216
273
  return new Response(body, { headers, status: response.status });
217
274
  }
218
- function toStandardLazyResponse(response) {
275
+ function toStandardLazyResponse(response, options = {}) {
219
276
  return {
220
- body: once(() => toStandardBody(response)),
277
+ body: once(() => toStandardBody(response, options)),
221
278
  status: response.status,
222
279
  get headers() {
223
280
  const headers = toStandardHeaders(response.headers);
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.f635909",
4
+ "version": "0.0.0-next.f677f1d",
5
5
  "license": "MIT",
6
6
  "homepage": "https://unnoq.com",
7
7
  "repository": {
@@ -23,11 +23,11 @@
23
23
  "dist"
24
24
  ],
25
25
  "dependencies": {
26
- "@orpc/shared": "0.0.0-next.f635909",
27
- "@orpc/standard-server": "0.0.0-next.f635909"
26
+ "@orpc/shared": "0.0.0-next.f677f1d",
27
+ "@orpc/standard-server": "0.0.0-next.f677f1d"
28
28
  },
29
29
  "devDependencies": {
30
- "@hono/node-server": "^1.14.1"
30
+ "@hono/node-server": "^1.19.4"
31
31
  },
32
32
  "scripts": {
33
33
  "build": "unbuild",