orpc-fn 0.6.1 → 0.7.0

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
@@ -288,6 +288,7 @@ Behaviour:
288
288
  - The response gets a `Server-Timing` header built from the request timing collector: app-recorded queue/auth/context metrics plus library-owned procedure time. Nested calls do not overwrite parent timing; batches aggregate their top-level procedure durations (which may overlap). `fn` does not mutate an arbitrary `context.timing` field. `formatServerTiming` and `finishOrpcHeaders` are available for composed Fetch adapters.
289
289
  - SSE responses get keep-alive comments (15 s) and anti-buffering headers.
290
290
  - RPC calls are batched (`BatchHandlerPlugin`).
291
+ - JSON and batch responses are gzipped when the client accepts it (`compress: false` turns it off). A streaming batch sends each result as it finishes, so it is flushed after every result instead of buffered; Hono's `compress()` skips event streams entirely. Live event streams are never compressed. A response that already has a `content-encoding` is left alone.
291
292
  - Scalar docs are served at the OpenAPI prefix.
292
293
  - `onError` sees only unexpected errors.
293
294
  - `openapi.filter`, `openapi.smartCoercion` and `openapi.spec` (for security schemes) cover an external API with its own auth.
package/dist/hono.d.ts CHANGED
@@ -51,6 +51,12 @@ export type MountOrpcOptions<E extends Env, R extends AnyRouter> = ContextOption
51
51
  };
52
52
  /** Add a Server-Timing header from the request timing. Default: true */
53
53
  serverTiming?: boolean;
54
+ /**
55
+ * gzip JSON responses and batch event streams for clients that accept it,
56
+ * flushing after every batch result. Other event streams are left alone.
57
+ * Default: true
58
+ */
59
+ compress?: boolean;
54
60
  /** SSE keep-alive comments every N ms (default 15000), or false. */
55
61
  sseKeepAlive?: boolean | number;
56
62
  /** Extra RPC plugins (e.g. `CORSPlugin`). */
@@ -1 +1 @@
1
- {"version":3,"file":"hono.d.ts","sourceRoot":"","sources":["../src/hono.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,eAAe,CAAA;AAGpE,OAAO,EACN,KAAK,SAAS,EACd,KAAK,yBAAyB,EAE9B,MAAM,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,IAAI,CAEzD;AAED,iFAAiF;AACjF,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAG1E;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAMzD;AAED,wBAAgB,kBAAkB,CACjC,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GACxC,MAAM,CAQR;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAChC,QAAQ,EAAE,QAAQ,EAClB,YAAY,EAAE,MAAM,GAAG,SAAS,GAC9B,OAAO,CAWT;AAmCD,2DAA2D;AAC3D,wBAAgB,SAAS,CAAC,CAAC,SAAS,GAAG,EAAE,CAAC,SAAS,SAAS,EAC3D,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,EACZ,OAAO,EAAE,gBAAgB,CAAC,CAAC,EAAE,CAAC,CAAC,GAC7B,IAAI,CAuIN"}
package/dist/hono.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { Readable, pipeline } from 'node:stream';
2
+ import zlib from 'node:zlib';
1
3
  import { SmartCoercionPlugin } from '@orpc/json-schema';
2
4
  import { OpenAPIHandler } from '@orpc/openapi/fetch';
3
5
  import { OpenAPIReferencePlugin } from '@orpc/openapi/plugins';
@@ -60,9 +62,40 @@ export function finishOrpcHeaders(response, serverTiming) {
60
62
  }
61
63
  return headers;
62
64
  }
65
+ const NO_TRANSFORM = /(?:^|,)\s*no-transform\s*(?:,|$)/i;
66
+ /**
67
+ * JSON, and the event stream oRPC answers a streaming batch with (one event
68
+ * per result). Other event streams are live: they stay open and carry little.
69
+ */
70
+ function shouldCompress(request, response) {
71
+ if (request.method === 'HEAD')
72
+ return false;
73
+ if (!request.headers.get('accept-encoding')?.includes('gzip'))
74
+ return false;
75
+ if (response.headers.has('content-encoding'))
76
+ return false;
77
+ if (NO_TRANSFORM.test(response.headers.get('cache-control') ?? '')) {
78
+ return false;
79
+ }
80
+ const type = response.headers.get('content-type') ?? '';
81
+ if (type.startsWith('text/event-stream')) {
82
+ // BatchHandlerPlugin keys on this header too, whatever the URL.
83
+ return request.headers.has('x-orpc-batch');
84
+ }
85
+ return type.startsWith('application/json');
86
+ }
87
+ /**
88
+ * gzip that emits every chunk at once, so a fast batch result is not held
89
+ * back by a slow one. Cancelling the result cancels `body`.
90
+ */
91
+ function gzipFlushingEachChunk(body) {
92
+ const gzip = zlib.createGzip({ flush: zlib.constants.Z_SYNC_FLUSH });
93
+ pipeline(Readable.fromWeb(body), gzip, () => { });
94
+ return Readable.toWeb(gzip);
95
+ }
63
96
  /** Mount oRPC's RPC and OpenAPI handlers on a Hono app. */
64
97
  export function mountOrpc(app, options) {
65
- const { router, batch = true, serverTiming = true, sseKeepAlive = true } = options;
98
+ const { router, batch = true, serverTiming = true, sseKeepAlive = true, compress = true } = options;
66
99
  const isExpectedError = options.isExpectedError ?? isExpectedClientError;
67
100
  const keepAlive = sseKeepAlive === false
68
101
  ? { eventIteratorKeepAliveEnabled: false }
@@ -115,10 +148,18 @@ export function mountOrpc(app, options) {
115
148
  handler_ms: invocationTiming.procedureMs
116
149
  })
117
150
  : undefined;
118
- return c.newResponse(response.body, {
151
+ const responseHeaders = finishOrpcHeaders(response, timed);
152
+ let body = response.body;
153
+ if (body && compress && shouldCompress(c.req.raw, response)) {
154
+ body = gzipFlushingEachChunk(body);
155
+ responseHeaders.set('content-encoding', 'gzip');
156
+ responseHeaders.delete('content-length');
157
+ responseHeaders.append('vary', 'accept-encoding');
158
+ }
159
+ return c.newResponse(body, {
119
160
  // oRPC only produces valid HTTP status codes.
120
161
  status: response.status,
121
- headers: finishOrpcHeaders(response, timed)
162
+ headers: responseHeaders
122
163
  });
123
164
  });
124
165
  };
package/dist/hono.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"hono.js","sourceRoot":"","sources":["../src/hono.ts"],"names":[],"mappings":"AAAA,OAAO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O,CAAC,IAAI,CACX,IAAI,sBAAsB,CAAC;YAC1B,YAAY,EAAE,QAAQ;YACtB,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC3D,gBAAgB,EAAE,UAAU;YAC5B,mBAAmB,EAAE;gBACpB,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE;gBACxD,OAAO,EAAE,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC;gBAClC,GAAG,MAAM;gBACT,GAAG,OAAO,CAAC,IAAI;aACf;SACD,CAAC,CACF,CAAA;QACD,KAAK,CACJ,OAAO,CAAC,MAAM,EACd,IAAI,cAAc,CAAC,MAAM,EAAE;YAC1B,GAAG,SAAS;YACZ,GAAG,MAAM;YACT,OAAO;YACP,YAAY,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE;SAC1D,CAAC,CACF,CAAA;IACF,CAAC;AACF,CAAC","sourcesContent":["import { SmartCoercionPlugin } from '@orpc/json-schema'\nimport type { OpenAPIGeneratorGenerateOptions } from '@orpc/openapi'\nimport { OpenAPIHandler } from '@orpc/openapi/fetch'\nimport { OpenAPIReferencePlugin } from '@orpc/openapi/plugins'\nimport {\n\ttype AnyRouter,\n\ttype InferRouterInitialContext,\n\tonError as orpcOnError\n} from '@orpc/server'\nimport { RPCHandler } from '@orpc/server/fetch'\nimport { BatchHandlerPlugin } from '@orpc/server/plugins'\nimport type { StandardHandlerPlugin } from '@orpc/server/standard'\nimport { ZodToJsonSchemaConverter } from '@orpc/zod/zod4'\nimport type { Context as HonoContext, Env, Hono } from 'hono'\nimport type { StatusCode } from 'hono/utils/http-status'\nimport { REQUEST_TIMING, type InvocationTiming } from './timing.js'\nimport { isExpectedClientError } from './expected-client-error.js'\nimport type { ProcedureFilter } from './mcp.js'\n\n/** Per-request timings in ms; `fn()` adds `handler_ms`. Sent as Server-Timing. */\nexport type RequestTiming = Record<string, number>\n\n/** What every request starts with; the default context when `context` is omitted. */\nexport type BaseContext = { headers: Headers; timing: RequestTiming }\n\n/**\n * Builds the router's initial context from the request. Return a `Response`\n * to answer (e.g. 401) instead.\n */\nexport type ContextFactory<E extends Env, R extends AnyRouter> = (\n\tc: HonoContext<E>,\n\tbase: BaseContext\n) =>\n\t| InferRouterInitialContext<R>\n\t| Response\n\t| Promise<InferRouterInitialContext<R> | Response>\n\n/** `context` is optional only when the base context already satisfies the router. */\ntype ContextOption<E extends Env, R extends AnyRouter> =\n\tBaseContext extends InferRouterInitialContext<R>\n\t\t? { context?: ContextFactory<E, R> }\n\t\t: { context: ContextFactory<E, R> }\n\ntype Path = `/${string}`\ntype Plugin<T extends object> = StandardHandlerPlugin<T>\n\nexport type MountOrpcOptions<\n\tE extends Env,\n\tR extends AnyRouter\n> = ContextOption<E, R> & {\n\trouter: R\n\t/** Mount the RPC handler (oRPC's `RPCLink`) here. Omit to skip it. */\n\trpcPrefix?: Path\n\t/** Mount the OpenAPI (REST) handler and its Scalar docs here. */\n\topenapi?: {\n\t\tprefix: Path\n\t\tinfo?: { title: string; version: string; description?: string }\n\t\t/** Docs page, relative to `prefix` (default '/'); the spec is at `/spec.json`. */\n\t\tdocsPath?: Path\n\t\t/** Only expose matching procedures (also filters the spec). */\n\t\tfilter?: ProcedureFilter\n\t\t/** Turn JSON strings back into `Date`s etc. for `z.date()` inputs. */\n\t\tsmartCoercion?: boolean\n\t\t/** Extra spec fields, e.g. `components.securitySchemes` and `security`. */\n\t\tspec?: Omit<OpenAPIGeneratorGenerateOptions, 'filter'>\n\t\tplugins?: Plugin<InferRouterInitialContext<R>>[]\n\t}\n\t/** Collapse parallel RPC calls into one HTTP request. Default: true (25 calls). */\n\tbatch?: boolean | { maxSize: number }\n\t/** Add a Server-Timing header from the request timing. Default: true */\n\tserverTiming?: boolean\n\t/** SSE keep-alive comments every N ms (default 15000), or false. */\n\tsseKeepAlive?: boolean | number\n\t/** Extra RPC plugins (e.g. `CORSPlugin`). */\n\tplugins?: Plugin<InferRouterInitialContext<R>>[]\n\t/** Rewrite request headers before they reach the context (see `normalizeExpoOrigin`). */\n\tnormalizeHeaders?: (headers: Headers) => Headers\n\t/**\n\t * Time spent before the handler ran, reported as `queue`. Default: time\n\t * since {@link markRequestArrival}, when the server marked the request.\n\t */\n\tqueueMs?: (request: Request) => number | undefined\n\t/**\n\t * Unexpected procedure errors (oRPC turns thrown errors into responses, so\n\t * Hono's `onError` never sees them). Expected client errors are skipped.\n\t */\n\tonError?: (error: unknown, request: { url: string; method: string }) => void\n\t/** Default: 4xx `ORPCError` or `AbortError`. */\n\tisExpectedError?: (error: unknown) => boolean\n}\n\nconst arrivals = new WeakMap<Request, number>()\n\n/**\n * Marks a request at the server's front door (`Bun.serve({ fetch })`), before\n * routing and middleware. `mountOrpc` reports the time until the procedure\n * runs as `queue_ms`: in-process queueing no handler timer can see.\n */\nexport function markRequestArrival(request: Request): void {\n\tarrivals.set(request, performance.now())\n}\n\n/** Milliseconds since {@link markRequestArrival}, or undefined when unmarked. */\nexport function msSinceRequestArrival(request: Request): number | undefined {\n\tconst arrivedAt = arrivals.get(request)\n\treturn arrivedAt === undefined ? undefined : performance.now() - arrivedAt\n}\n\n/**\n * Expo native sends `expo-origin` but not `origin`; copy it so cookie-based\n * auth (e.g. Better Auth) sees the origin.\n */\nexport function normalizeExpoOrigin(raw: Headers): Headers {\n\tconst expo = raw.get('expo-origin')\n\tif (!expo || raw.get('origin')) return raw\n\tconst headers = new Headers(raw)\n\theaders.set('origin', expo)\n\treturn headers\n}\n\nexport function formatServerTiming(\n\ttotalMs: number,\n\ttiming: Record<string, number | undefined>\n): string {\n\tconst parts = [`total;dur=${totalMs.toFixed(2)}`]\n\tfor (const [key, value] of Object.entries(timing)) {\n\t\tif (value !== undefined) {\n\t\t\tparts.push(`${key.replace(/_ms$/, '')};dur=${value.toFixed(2)}`)\n\t\t}\n\t}\n\treturn parts.join(', ')\n}\n\n/**\n * Response headers plus Server-Timing. For SSE, also disable proxy buffering\n * so keep-alive comments reach the edge (empty `:` lines are otherwise easy\n * for nginx/Fastly to hold until an idle kill). A copy: some responses (e.g.\n * redirects) have immutable headers.\n */\nexport function finishOrpcHeaders(\n\tresponse: Response,\n\tserverTiming: string | undefined\n): Headers {\n\tconst headers = new Headers(response.headers)\n\tif (serverTiming) {\n\t\theaders.set('Server-Timing', serverTiming)\n\t\theaders.append('Access-Control-Expose-Headers', 'Server-Timing')\n\t}\n\tif ((headers.get('content-type') ?? '').includes('text/event-stream')) {\n\t\theaders.set('Cache-Control', 'no-cache')\n\t\theaders.set('X-Accel-Buffering', 'no')\n\t}\n\treturn headers\n}\n\n/** Mount oRPC's RPC and OpenAPI handlers on a Hono app. */\nexport function mountOrpc<E extends Env, R extends AnyRouter>(\n\tapp: Hono<E>,\n\toptions: MountOrpcOptions<E, R>\n): void {\n\tconst {\n\t\trouter,\n\t\tbatch = true,\n\t\tserverTiming = true,\n\t\tsseKeepAlive = true\n\t} = options\n\tconst isExpectedError = options.isExpectedError ?? isExpectedClientError\n\tconst keepAlive =\n\t\tsseKeepAlive === false\n\t\t\t? { eventIteratorKeepAliveEnabled: false }\n\t\t\t: {\n\t\t\t\t\teventIteratorKeepAliveEnabled: true,\n\t\t\t\t\t// Explicit keep-alive under proxy idle timers (~30s); oRPC's default is 5s.\n\t\t\t\t\teventIteratorKeepAliveInterval:\n\t\t\t\t\t\tsseKeepAlive === true ? 15_000 : sseKeepAlive\n\t\t\t\t}\n\tconst report = (\n\t\terror: unknown,\n\t\t{ request }: { request: { url: URL; method: string } }\n\t) => {\n\t\ttry {\n\t\t\tif (isExpectedError(error)) return\n\t\t\toptions.onError?.(error, {\n\t\t\t\turl: request.url.pathname,\n\t\t\t\tmethod: request.method\n\t\t\t})\n\t\t} catch {\n\t\t\t/* Error reporting cannot replace transport outcomes. */\n\t\t}\n\t}\n\n\tconst mount = (\n\t\tprefix: Path,\n\t\thandler: Pick<RPCHandler<InferRouterInitialContext<R>>, 'handle'>\n\t) => {\n\t\tapp.use(`${prefix}/*`, async (c, next) => {\n\t\t\tconst timing: RequestTiming = {}\n\t\t\tconst queueMs = (options.queueMs ?? msSinceRequestArrival)(c.req.raw)\n\t\t\tif (queueMs !== undefined)\n\t\t\t\ttiming.queue_ms = Math.round(queueMs * 100) / 100\n\t\t\tconst started = performance.now()\n\t\t\tconst headers = options.normalizeHeaders\n\t\t\t\t? options.normalizeHeaders(c.req.raw.headers)\n\t\t\t\t: c.req.raw.headers\n\t\t\tconst context = options.context\n\t\t\t\t? await options.context(c, { headers, timing })\n\t\t\t\t: { headers, timing }\n\t\t\tif (context instanceof Response) return context\n\t\t\tconst invocationTiming: InvocationTiming = { procedureMs: 0, calls: 0 }\n\t\t\tconst { matched, response } = await handler.handle(c.req.raw, {\n\t\t\t\tprefix,\n\t\t\t\tcontext: {\n\t\t\t\t\t...context,\n\t\t\t\t\t[REQUEST_TIMING]: invocationTiming\n\t\t\t\t} as InferRouterInitialContext<R>\n\t\t\t})\n\t\t\tif (!matched) return next()\n\t\t\tconst timed = serverTiming\n\t\t\t\t? formatServerTiming(performance.now() - started, {\n\t\t\t\t\t\t...timing,\n\t\t\t\t\t\thandler_ms: invocationTiming.procedureMs\n\t\t\t\t\t})\n\t\t\t\t: undefined\n\t\t\treturn c.newResponse(response.body, {\n\t\t\t\t// oRPC only produces valid HTTP status codes.\n\t\t\t\tstatus: response.status as StatusCode,\n\t\t\t\theaders: finishOrpcHeaders(response, timed)\n\t\t\t})\n\t\t})\n\t}\n\n\tif (options.rpcPrefix) {\n\t\tconst plugins: Plugin<InferRouterInitialContext<R>>[] = [\n\t\t\t...(options.plugins ?? [])\n\t\t]\n\t\tif (batch) {\n\t\t\tplugins.push(\n\t\t\t\tnew BatchHandlerPlugin({\n\t\t\t\t\tmaxSize: batch === true ? 25 : batch.maxSize\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tmount(\n\t\t\toptions.rpcPrefix,\n\t\t\tnew RPCHandler(router, {\n\t\t\t\t...keepAlive,\n\t\t\t\tplugins,\n\t\t\t\tinterceptors: options.onError ? [orpcOnError(report)] : []\n\t\t\t})\n\t\t)\n\t}\n\n\tif (options.openapi) {\n\t\tconst { openapi } = options\n\t\tconst filter = openapi.filter ? { filter: openapi.filter } : {}\n\t\tconst converters = [new ZodToJsonSchemaConverter()]\n\t\tconst plugins: Plugin<InferRouterInitialContext<R>>[] = [\n\t\t\t...(openapi.plugins ?? [])\n\t\t]\n\t\tif (openapi.smartCoercion) {\n\t\t\tplugins.push(new SmartCoercionPlugin({ schemaConverters: converters }))\n\t\t}\n\t\tplugins.push(\n\t\t\tnew OpenAPIReferencePlugin({\n\t\t\t\tdocsProvider: 'scalar',\n\t\t\t\t...(openapi.docsPath ? { docsPath: openapi.docsPath } : {}),\n\t\t\t\tschemaConverters: converters,\n\t\t\t\tspecGenerateOptions: {\n\t\t\t\t\tinfo: openapi.info ?? { title: 'API', version: '0.0.0' },\n\t\t\t\t\tservers: [{ url: openapi.prefix }],\n\t\t\t\t\t...filter,\n\t\t\t\t\t...openapi.spec\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\t\tmount(\n\t\t\topenapi.prefix,\n\t\t\tnew OpenAPIHandler(router, {\n\t\t\t\t...keepAlive,\n\t\t\t\t...filter,\n\t\t\t\tplugins,\n\t\t\t\tinterceptors: options.onError ? [orpcOnError(report)] : []\n\t\t\t})\n\t\t)\n\t}\n}\n"]}
1
+ {"version":3,"file":"hono.js","sourceRoot":"","sources":["../src/hono.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAChD,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,m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'\nimport type { OpenAPIGeneratorGenerateOptions } from '@orpc/openapi'\nimport { OpenAPIHandler } from '@orpc/openapi/fetch'\nimport { OpenAPIReferencePlugin } from '@orpc/openapi/plugins'\nimport {\n\ttype AnyRouter,\n\ttype InferRouterInitialContext,\n\tonError as orpcOnError\n} from '@orpc/server'\nimport { RPCHandler } from '@orpc/server/fetch'\nimport { BatchHandlerPlugin } from '@orpc/server/plugins'\nimport type { StandardHandlerPlugin } from '@orpc/server/standard'\nimport { ZodToJsonSchemaConverter } from '@orpc/zod/zod4'\nimport type { Context as HonoContext, Env, Hono } from 'hono'\nimport type { StatusCode } from 'hono/utils/http-status'\nimport { REQUEST_TIMING, type InvocationTiming } from './timing.js'\nimport { isExpectedClientError } from './expected-client-error.js'\nimport type { ProcedureFilter } from './mcp.js'\n\n/** Per-request timings in ms; `fn()` adds `handler_ms`. Sent as Server-Timing. */\nexport type RequestTiming = Record<string, number>\n\n/** What every request starts with; the default context when `context` is omitted. */\nexport type BaseContext = { headers: Headers; timing: RequestTiming }\n\n/**\n * Builds the router's initial context from the request. Return a `Response`\n * to answer (e.g. 401) instead.\n */\nexport type ContextFactory<E extends Env, R extends AnyRouter> = (\n\tc: HonoContext<E>,\n\tbase: BaseContext\n) =>\n\t| InferRouterInitialContext<R>\n\t| Response\n\t| Promise<InferRouterInitialContext<R> | Response>\n\n/** `context` is optional only when the base context already satisfies the router. */\ntype ContextOption<E extends Env, R extends AnyRouter> =\n\tBaseContext extends InferRouterInitialContext<R>\n\t\t? { context?: ContextFactory<E, R> }\n\t\t: { context: ContextFactory<E, R> }\n\ntype Path = `/${string}`\ntype Plugin<T extends object> = StandardHandlerPlugin<T>\n\nexport type MountOrpcOptions<\n\tE extends Env,\n\tR extends AnyRouter\n> = ContextOption<E, R> & {\n\trouter: R\n\t/** Mount the RPC handler (oRPC's `RPCLink`) here. Omit to skip it. */\n\trpcPrefix?: Path\n\t/** Mount the OpenAPI (REST) handler and its Scalar docs here. */\n\topenapi?: {\n\t\tprefix: Path\n\t\tinfo?: { title: string; version: string; description?: string }\n\t\t/** Docs page, relative to `prefix` (default '/'); the spec is at `/spec.json`. */\n\t\tdocsPath?: Path\n\t\t/** Only expose matching procedures (also filters the spec). */\n\t\tfilter?: ProcedureFilter\n\t\t/** Turn JSON strings back into `Date`s etc. for `z.date()` inputs. */\n\t\tsmartCoercion?: boolean\n\t\t/** Extra spec fields, e.g. `components.securitySchemes` and `security`. */\n\t\tspec?: Omit<OpenAPIGeneratorGenerateOptions, 'filter'>\n\t\tplugins?: Plugin<InferRouterInitialContext<R>>[]\n\t}\n\t/** Collapse parallel RPC calls into one HTTP request. Default: true (25 calls). */\n\tbatch?: boolean | { maxSize: number }\n\t/** Add a Server-Timing header from the request timing. Default: true */\n\tserverTiming?: boolean\n\t/**\n\t * gzip JSON responses and batch event streams for clients that accept it,\n\t * flushing after every batch result. Other event streams are left alone.\n\t * Default: true\n\t */\n\tcompress?: boolean\n\t/** SSE keep-alive comments every N ms (default 15000), or false. */\n\tsseKeepAlive?: boolean | number\n\t/** Extra RPC plugins (e.g. `CORSPlugin`). */\n\tplugins?: Plugin<InferRouterInitialContext<R>>[]\n\t/** Rewrite request headers before they reach the context (see `normalizeExpoOrigin`). */\n\tnormalizeHeaders?: (headers: Headers) => Headers\n\t/**\n\t * Time spent before the handler ran, reported as `queue`. Default: time\n\t * since {@link markRequestArrival}, when the server marked the request.\n\t */\n\tqueueMs?: (request: Request) => number | undefined\n\t/**\n\t * Unexpected procedure errors (oRPC turns thrown errors into responses, so\n\t * Hono's `onError` never sees them). Expected client errors are skipped.\n\t */\n\tonError?: (error: unknown, request: { url: string; method: string }) => void\n\t/** Default: 4xx `ORPCError` or `AbortError`. */\n\tisExpectedError?: (error: unknown) => boolean\n}\n\nconst arrivals = new WeakMap<Request, number>()\n\n/**\n * Marks a request at the server's front door (`Bun.serve({ fetch })`), before\n * routing and middleware. `mountOrpc` reports the time until the procedure\n * runs as `queue_ms`: in-process queueing no handler timer can see.\n */\nexport function markRequestArrival(request: Request): void {\n\tarrivals.set(request, performance.now())\n}\n\n/** Milliseconds since {@link markRequestArrival}, or undefined when unmarked. */\nexport function msSinceRequestArrival(request: Request): number | undefined {\n\tconst arrivedAt = arrivals.get(request)\n\treturn arrivedAt === undefined ? undefined : performance.now() - arrivedAt\n}\n\n/**\n * Expo native sends `expo-origin` but not `origin`; copy it so cookie-based\n * auth (e.g. Better Auth) sees the origin.\n */\nexport function normalizeExpoOrigin(raw: Headers): Headers {\n\tconst expo = raw.get('expo-origin')\n\tif (!expo || raw.get('origin')) return raw\n\tconst headers = new Headers(raw)\n\theaders.set('origin', expo)\n\treturn headers\n}\n\nexport function formatServerTiming(\n\ttotalMs: number,\n\ttiming: Record<string, number | undefined>\n): string {\n\tconst parts = [`total;dur=${totalMs.toFixed(2)}`]\n\tfor (const [key, value] of Object.entries(timing)) {\n\t\tif (value !== undefined) {\n\t\t\tparts.push(`${key.replace(/_ms$/, '')};dur=${value.toFixed(2)}`)\n\t\t}\n\t}\n\treturn parts.join(', ')\n}\n\n/**\n * Response headers plus Server-Timing. For SSE, also disable proxy buffering\n * so keep-alive comments reach the edge (empty `:` lines are otherwise easy\n * for nginx/Fastly to hold until an idle kill). A copy: some responses (e.g.\n * redirects) have immutable headers.\n */\nexport function finishOrpcHeaders(\n\tresponse: Response,\n\tserverTiming: string | undefined\n): Headers {\n\tconst headers = new Headers(response.headers)\n\tif (serverTiming) {\n\t\theaders.set('Server-Timing', serverTiming)\n\t\theaders.append('Access-Control-Expose-Headers', 'Server-Timing')\n\t}\n\tif ((headers.get('content-type') ?? '').includes('text/event-stream')) {\n\t\theaders.set('Cache-Control', 'no-cache')\n\t\theaders.set('X-Accel-Buffering', 'no')\n\t}\n\treturn headers\n}\n\nconst NO_TRANSFORM = /(?:^|,)\\s*no-transform\\s*(?:,|$)/i\n\n/**\n * JSON, and the event stream oRPC answers a streaming batch with (one event\n * per result). Other event streams are live: they stay open and carry little.\n */\nfunction shouldCompress(request: Request, response: Response): boolean {\n\tif (request.method === 'HEAD') return false\n\tif (!request.headers.get('accept-encoding')?.includes('gzip')) return false\n\tif (response.headers.has('content-encoding')) return false\n\tif (NO_TRANSFORM.test(response.headers.get('cache-control') ?? '')) {\n\t\treturn false\n\t}\n\tconst type = response.headers.get('content-type') ?? ''\n\tif (type.startsWith('text/event-stream')) {\n\t\t// BatchHandlerPlugin keys on this header too, whatever the URL.\n\t\treturn request.headers.has('x-orpc-batch')\n\t}\n\treturn type.startsWith('application/json')\n}\n\n/**\n * gzip that emits every chunk at once, so a fast batch result is not held\n * back by a slow one. Cancelling the result cancels `body`.\n */\nfunction gzipFlushingEachChunk(\n\tbody: ReadableStream<Uint8Array>\n): ReadableStream<Uint8Array> {\n\tconst gzip = zlib.createGzip({ flush: zlib.constants.Z_SYNC_FLUSH })\n\tpipeline(Readable.fromWeb(body as never), gzip, () => {})\n\treturn Readable.toWeb(gzip) as unknown as ReadableStream<Uint8Array>\n}\n\n/** Mount oRPC's RPC and OpenAPI handlers on a Hono app. */\nexport function mountOrpc<E extends Env, R extends AnyRouter>(\n\tapp: Hono<E>,\n\toptions: MountOrpcOptions<E, R>\n): void {\n\tconst {\n\t\trouter,\n\t\tbatch = true,\n\t\tserverTiming = true,\n\t\tsseKeepAlive = true,\n\t\tcompress = true\n\t} = options\n\tconst isExpectedError = options.isExpectedError ?? isExpectedClientError\n\tconst keepAlive =\n\t\tsseKeepAlive === false\n\t\t\t? { eventIteratorKeepAliveEnabled: false }\n\t\t\t: {\n\t\t\t\t\teventIteratorKeepAliveEnabled: true,\n\t\t\t\t\t// Explicit keep-alive under proxy idle timers (~30s); oRPC's default is 5s.\n\t\t\t\t\teventIteratorKeepAliveInterval:\n\t\t\t\t\t\tsseKeepAlive === true ? 15_000 : sseKeepAlive\n\t\t\t\t}\n\tconst report = (\n\t\terror: unknown,\n\t\t{ request }: { request: { url: URL; method: string } }\n\t) => {\n\t\ttry {\n\t\t\tif (isExpectedError(error)) return\n\t\t\toptions.onError?.(error, {\n\t\t\t\turl: request.url.pathname,\n\t\t\t\tmethod: request.method\n\t\t\t})\n\t\t} catch {\n\t\t\t/* Error reporting cannot replace transport outcomes. */\n\t\t}\n\t}\n\n\tconst mount = (\n\t\tprefix: Path,\n\t\thandler: Pick<RPCHandler<InferRouterInitialContext<R>>, 'handle'>\n\t) => {\n\t\tapp.use(`${prefix}/*`, async (c, next) => {\n\t\t\tconst timing: RequestTiming = {}\n\t\t\tconst queueMs = (options.queueMs ?? msSinceRequestArrival)(c.req.raw)\n\t\t\tif (queueMs !== undefined)\n\t\t\t\ttiming.queue_ms = Math.round(queueMs * 100) / 100\n\t\t\tconst started = performance.now()\n\t\t\tconst headers = options.normalizeHeaders\n\t\t\t\t? options.normalizeHeaders(c.req.raw.headers)\n\t\t\t\t: c.req.raw.headers\n\t\t\tconst context = options.context\n\t\t\t\t? await options.context(c, { headers, timing })\n\t\t\t\t: { headers, timing }\n\t\t\tif (context instanceof Response) return context\n\t\t\tconst invocationTiming: InvocationTiming = { procedureMs: 0, calls: 0 }\n\t\t\tconst { matched, response } = await handler.handle(c.req.raw, {\n\t\t\t\tprefix,\n\t\t\t\tcontext: {\n\t\t\t\t\t...context,\n\t\t\t\t\t[REQUEST_TIMING]: invocationTiming\n\t\t\t\t} as InferRouterInitialContext<R>\n\t\t\t})\n\t\t\tif (!matched) return next()\n\t\t\tconst timed = serverTiming\n\t\t\t\t? formatServerTiming(performance.now() - started, {\n\t\t\t\t\t\t...timing,\n\t\t\t\t\t\thandler_ms: invocationTiming.procedureMs\n\t\t\t\t\t})\n\t\t\t\t: undefined\n\t\t\tconst responseHeaders = finishOrpcHeaders(response, timed)\n\t\t\tlet body = response.body\n\t\t\tif (body && compress && shouldCompress(c.req.raw, response)) {\n\t\t\t\tbody = gzipFlushingEachChunk(body)\n\t\t\t\tresponseHeaders.set('content-encoding', 'gzip')\n\t\t\t\tresponseHeaders.delete('content-length')\n\t\t\t\tresponseHeaders.append('vary', 'accept-encoding')\n\t\t\t}\n\t\t\treturn c.newResponse(body, {\n\t\t\t\t// oRPC only produces valid HTTP status codes.\n\t\t\t\tstatus: response.status as StatusCode,\n\t\t\t\theaders: responseHeaders\n\t\t\t})\n\t\t})\n\t}\n\n\tif (options.rpcPrefix) {\n\t\tconst plugins: Plugin<InferRouterInitialContext<R>>[] = [\n\t\t\t...(options.plugins ?? [])\n\t\t]\n\t\tif (batch) {\n\t\t\tplugins.push(\n\t\t\t\tnew BatchHandlerPlugin({\n\t\t\t\t\tmaxSize: batch === true ? 25 : batch.maxSize\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tmount(\n\t\t\toptions.rpcPrefix,\n\t\t\tnew RPCHandler(router, {\n\t\t\t\t...keepAlive,\n\t\t\t\tplugins,\n\t\t\t\tinterceptors: options.onError ? [orpcOnError(report)] : []\n\t\t\t})\n\t\t)\n\t}\n\n\tif (options.openapi) {\n\t\tconst { openapi } = options\n\t\tconst filter = openapi.filter ? { filter: openapi.filter } : {}\n\t\tconst converters = [new ZodToJsonSchemaConverter()]\n\t\tconst plugins: Plugin<InferRouterInitialContext<R>>[] = [\n\t\t\t...(openapi.plugins ?? [])\n\t\t]\n\t\tif (openapi.smartCoercion) {\n\t\t\tplugins.push(new SmartCoercionPlugin({ schemaConverters: converters }))\n\t\t}\n\t\tplugins.push(\n\t\t\tnew OpenAPIReferencePlugin({\n\t\t\t\tdocsProvider: 'scalar',\n\t\t\t\t...(openapi.docsPath ? { docsPath: openapi.docsPath } : {}),\n\t\t\t\tschemaConverters: converters,\n\t\t\t\tspecGenerateOptions: {\n\t\t\t\t\tinfo: openapi.info ?? { title: 'API', version: '0.0.0' },\n\t\t\t\t\tservers: [{ url: openapi.prefix }],\n\t\t\t\t\t...filter,\n\t\t\t\t\t...openapi.spec\n\t\t\t\t}\n\t\t\t})\n\t\t)\n\t\tmount(\n\t\t\topenapi.prefix,\n\t\t\tnew OpenAPIHandler(router, {\n\t\t\t\t...keepAlive,\n\t\t\t\t...filter,\n\t\t\t\tplugins,\n\t\t\t\tinterceptors: options.onError ? [orpcOnError(report)] : []\n\t\t\t})\n\t\t)\n\t}\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "orpc-fn",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "Define a backend function once: a typed oRPC procedure with tracing, logging, guards, injected handler extras, nested calls and live queries over Redis.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/hono.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { Readable, pipeline } from 'node:stream'
2
+ import zlib from 'node:zlib'
1
3
  import { SmartCoercionPlugin } from '@orpc/json-schema'
2
4
  import type { OpenAPIGeneratorGenerateOptions } from '@orpc/openapi'
3
5
  import { OpenAPIHandler } from '@orpc/openapi/fetch'
@@ -69,6 +71,12 @@ export type MountOrpcOptions<
69
71
  batch?: boolean | { maxSize: number }
70
72
  /** Add a Server-Timing header from the request timing. Default: true */
71
73
  serverTiming?: boolean
74
+ /**
75
+ * gzip JSON responses and batch event streams for clients that accept it,
76
+ * flushing after every batch result. Other event streams are left alone.
77
+ * Default: true
78
+ */
79
+ compress?: boolean
72
80
  /** SSE keep-alive comments every N ms (default 15000), or false. */
73
81
  sseKeepAlive?: boolean | number
74
82
  /** Extra RPC plugins (e.g. `CORSPlugin`). */
@@ -153,6 +161,39 @@ export function finishOrpcHeaders(
153
161
  return headers
154
162
  }
155
163
 
164
+ const NO_TRANSFORM = /(?:^|,)\s*no-transform\s*(?:,|$)/i
165
+
166
+ /**
167
+ * JSON, and the event stream oRPC answers a streaming batch with (one event
168
+ * per result). Other event streams are live: they stay open and carry little.
169
+ */
170
+ function shouldCompress(request: Request, response: Response): boolean {
171
+ if (request.method === 'HEAD') return false
172
+ if (!request.headers.get('accept-encoding')?.includes('gzip')) return false
173
+ if (response.headers.has('content-encoding')) return false
174
+ if (NO_TRANSFORM.test(response.headers.get('cache-control') ?? '')) {
175
+ return false
176
+ }
177
+ const type = response.headers.get('content-type') ?? ''
178
+ if (type.startsWith('text/event-stream')) {
179
+ // BatchHandlerPlugin keys on this header too, whatever the URL.
180
+ return request.headers.has('x-orpc-batch')
181
+ }
182
+ return type.startsWith('application/json')
183
+ }
184
+
185
+ /**
186
+ * gzip that emits every chunk at once, so a fast batch result is not held
187
+ * back by a slow one. Cancelling the result cancels `body`.
188
+ */
189
+ function gzipFlushingEachChunk(
190
+ body: ReadableStream<Uint8Array>
191
+ ): ReadableStream<Uint8Array> {
192
+ const gzip = zlib.createGzip({ flush: zlib.constants.Z_SYNC_FLUSH })
193
+ pipeline(Readable.fromWeb(body as never), gzip, () => {})
194
+ return Readable.toWeb(gzip) as unknown as ReadableStream<Uint8Array>
195
+ }
196
+
156
197
  /** Mount oRPC's RPC and OpenAPI handlers on a Hono app. */
157
198
  export function mountOrpc<E extends Env, R extends AnyRouter>(
158
199
  app: Hono<E>,
@@ -162,7 +203,8 @@ export function mountOrpc<E extends Env, R extends AnyRouter>(
162
203
  router,
163
204
  batch = true,
164
205
  serverTiming = true,
165
- sseKeepAlive = true
206
+ sseKeepAlive = true,
207
+ compress = true
166
208
  } = options
167
209
  const isExpectedError = options.isExpectedError ?? isExpectedClientError
168
210
  const keepAlive =
@@ -221,10 +263,18 @@ export function mountOrpc<E extends Env, R extends AnyRouter>(
221
263
  handler_ms: invocationTiming.procedureMs
222
264
  })
223
265
  : undefined
224
- return c.newResponse(response.body, {
266
+ const responseHeaders = finishOrpcHeaders(response, timed)
267
+ let body = response.body
268
+ if (body && compress && shouldCompress(c.req.raw, response)) {
269
+ body = gzipFlushingEachChunk(body)
270
+ responseHeaders.set('content-encoding', 'gzip')
271
+ responseHeaders.delete('content-length')
272
+ responseHeaders.append('vary', 'accept-encoding')
273
+ }
274
+ return c.newResponse(body, {
225
275
  // oRPC only produces valid HTTP status codes.
226
276
  status: response.status as StatusCode,
227
- headers: finishOrpcHeaders(response, timed)
277
+ headers: responseHeaders
228
278
  })
229
279
  })
230
280
  }