@orpc/server 2.0.0-beta.47 → 2.0.0-beta.49

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.
Files changed (178) hide show
  1. package/README.md +6 -7
  2. package/dist/adapters/aws-lambda/handler.d.ts +25 -0
  3. package/dist/adapters/aws-lambda/handler.js +24 -0
  4. package/dist/adapters/aws-lambda/index.d.ts +10 -45
  5. package/dist/adapters/aws-lambda/index.js +2 -0
  6. package/dist/adapters/aws-lambda/rpc-handler.d.ts +19 -0
  7. package/dist/adapters/aws-lambda/rpc-handler.js +18 -0
  8. package/dist/adapters/crossws/handler.d.ts +45 -0
  9. package/dist/adapters/crossws/handler.js +60 -0
  10. package/dist/adapters/crossws/index.d.ts +2 -63
  11. package/dist/adapters/crossws/index.js +2 -0
  12. package/dist/adapters/crossws/rpc-handler.d.ts +16 -0
  13. package/dist/adapters/crossws/rpc-handler.js +15 -0
  14. package/dist/adapters/fastify/handler.d.ts +21 -0
  15. package/dist/adapters/fastify/handler.js +20 -0
  16. package/dist/adapters/fastify/index.d.ts +2 -42
  17. package/dist/adapters/fastify/index.js +2 -0
  18. package/dist/adapters/fastify/rpc-handler.d.ts +15 -0
  19. package/dist/adapters/fastify/rpc-handler.js +14 -0
  20. package/dist/adapters/fetch/handler.d.ts +23 -0
  21. package/dist/adapters/fetch/handler.js +22 -0
  22. package/dist/adapters/fetch/index.d.ts +5 -45
  23. package/dist/adapters/fetch/index.js +7 -0
  24. package/dist/adapters/fetch/rpc-handler.d.ts +17 -0
  25. package/dist/adapters/fetch/rpc-handler.js +16 -0
  26. package/dist/adapters/message-port/{index.d.mts → handler.d.ts} +17 -30
  27. package/dist/adapters/message-port/handler.js +86 -0
  28. package/dist/adapters/message-port/index.d.ts +2 -77
  29. package/dist/adapters/message-port/index.js +2 -0
  30. package/dist/adapters/message-port/rpc-handler.d.ts +16 -0
  31. package/dist/adapters/message-port/rpc-handler.js +15 -0
  32. package/dist/adapters/node/handler.d.ts +21 -0
  33. package/dist/adapters/node/handler.js +20 -0
  34. package/dist/adapters/node/index.d.ts +5 -42
  35. package/dist/adapters/node/index.js +7 -0
  36. package/dist/adapters/node/rpc-handler.d.ts +16 -0
  37. package/dist/adapters/node/rpc-handler.js +15 -0
  38. package/dist/adapters/standard/codec.d.ts +16 -0
  39. package/dist/adapters/standard/codec.js +1 -0
  40. package/dist/adapters/standard/handler.d.ts +68 -0
  41. package/dist/adapters/standard/handler.js +205 -0
  42. package/dist/adapters/standard/index.d.ts +6 -95
  43. package/dist/adapters/standard/index.js +5 -0
  44. package/dist/adapters/standard/plugin.d.ts +32 -0
  45. package/dist/adapters/standard/plugin.js +16 -0
  46. package/dist/adapters/standard/rpc-handler-codec.d.ts +46 -0
  47. package/dist/adapters/standard/rpc-handler-codec.js +51 -0
  48. package/dist/adapters/standard/rpc-matcher.d.ts +53 -0
  49. package/dist/adapters/standard/rpc-matcher.js +152 -0
  50. package/dist/adapters/standard/utils.d.ts +10 -0
  51. package/dist/adapters/standard/utils.js +6 -0
  52. package/dist/adapters/standard-peer/index.d.ts +1 -11
  53. package/dist/adapters/standard-peer/index.js +1 -0
  54. package/dist/adapters/standard-peer/utils.d.ts +4 -0
  55. package/dist/adapters/standard-peer/utils.js +7 -0
  56. package/dist/adapters/websocket/{index.d.mts → handler.d.ts} +11 -29
  57. package/dist/adapters/websocket/handler.js +85 -0
  58. package/dist/adapters/websocket/index.d.ts +2 -77
  59. package/dist/adapters/websocket/index.js +2 -0
  60. package/dist/adapters/websocket/rpc-handler.d.ts +16 -0
  61. package/dist/adapters/websocket/rpc-handler.js +15 -0
  62. package/dist/builder-variants.d.ts +226 -0
  63. package/dist/builder-variants.js +1 -0
  64. package/dist/builder.d.ts +127 -0
  65. package/dist/builder.js +226 -0
  66. package/dist/constants.d.ts +2 -0
  67. package/dist/constants.js +2 -0
  68. package/dist/context.d.ts +6 -0
  69. package/dist/context.js +1 -0
  70. package/dist/extensions/callable.d.ts +6 -5
  71. package/dist/extensions/callable.js +7 -0
  72. package/dist/helpers/base64url.d.ts +31 -0
  73. package/dist/helpers/base64url.js +53 -0
  74. package/dist/helpers/cookie.d.ts +51 -0
  75. package/dist/helpers/cookie.js +69 -0
  76. package/dist/helpers/encryption.d.ts +28 -0
  77. package/dist/helpers/encryption.js +80 -0
  78. package/dist/helpers/index.d.ts +4 -167
  79. package/dist/helpers/index.js +4 -0
  80. package/dist/helpers/signing.d.ts +50 -0
  81. package/dist/helpers/signing.js +88 -0
  82. package/dist/implementer-procedure.d.ts +16 -0
  83. package/dist/implementer-procedure.js +44 -0
  84. package/dist/implementer-router.d.ts +40 -0
  85. package/dist/implementer-router.js +117 -0
  86. package/dist/implementer.d.ts +16 -0
  87. package/dist/implementer.js +37 -0
  88. package/dist/index.d.ts +45 -460
  89. package/dist/index.js +48 -0
  90. package/dist/lazy.d.ts +20 -0
  91. package/dist/lazy.js +31 -0
  92. package/dist/middleware-decorated.d.ts +10 -0
  93. package/dist/middleware-decorated.js +71 -0
  94. package/dist/middleware.d.ts +54 -0
  95. package/dist/middleware.js +1 -0
  96. package/dist/plugins/batch.d.ts +102 -0
  97. package/dist/plugins/batch.js +405 -0
  98. package/dist/plugins/cors.d.ts +73 -0
  99. package/dist/plugins/cors.js +112 -0
  100. package/dist/plugins/get-method-csrf-protection.d.ts +23 -0
  101. package/dist/plugins/get-method-csrf-protection.js +64 -0
  102. package/dist/plugins/head-method.d.ts +23 -0
  103. package/dist/plugins/head-method.js +104 -0
  104. package/dist/plugins/index.d.ts +29 -422
  105. package/dist/plugins/index.js +29 -0
  106. package/dist/plugins/method-override.d.ts +38 -0
  107. package/dist/plugins/method-override.js +50 -0
  108. package/dist/plugins/request-compression.d.ts +16 -0
  109. package/dist/plugins/request-compression.js +82 -0
  110. package/dist/plugins/request-headers.d.ts +22 -0
  111. package/dist/plugins/request-headers.js +30 -0
  112. package/dist/{shared/server.CgBF3Vj1.d.ts → plugins/request-limit.d.ts} +4 -8
  113. package/dist/plugins/request-limit.js +68 -0
  114. package/dist/plugins/response-compression.d.ts +59 -0
  115. package/dist/plugins/response-compression.js +209 -0
  116. package/dist/plugins/response-headers.d.ts +30 -0
  117. package/dist/plugins/response-headers.js +47 -0
  118. package/dist/plugins/rethrow.d.ts +33 -0
  119. package/dist/plugins/rethrow.js +59 -0
  120. package/dist/plugins/signal-sync.d.ts +13 -0
  121. package/dist/plugins/signal-sync.js +91 -0
  122. package/dist/plugins/timeout.d.ts +37 -0
  123. package/dist/plugins/timeout.js +59 -0
  124. package/dist/procedure-client.d.ts +19 -0
  125. package/dist/procedure-client.js +175 -0
  126. package/dist/procedure-decorated.d.ts +10 -0
  127. package/dist/procedure-decorated.js +44 -0
  128. package/dist/procedure-utils.d.ts +41 -0
  129. package/dist/procedure-utils.js +49 -0
  130. package/dist/procedure.d.ts +72 -0
  131. package/dist/procedure.js +24 -0
  132. package/dist/router-client.d.ts +23 -0
  133. package/dist/router-client.js +43 -0
  134. package/dist/router-hidden.d.ts +5 -0
  135. package/dist/router-hidden.js +14 -0
  136. package/dist/router-utils.d.ts +48 -0
  137. package/dist/router-utils.js +202 -0
  138. package/dist/{shared/server.Dz7j9BEh.d.ts → router.d.ts} +14 -15
  139. package/dist/router.js +1 -0
  140. package/package.json +84 -86
  141. package/dist/adapters/aws-lambda/index.d.mts +0 -51
  142. package/dist/adapters/aws-lambda/index.mjs +0 -39
  143. package/dist/adapters/crossws/index.d.mts +0 -63
  144. package/dist/adapters/crossws/index.mjs +0 -68
  145. package/dist/adapters/fastify/index.d.mts +0 -42
  146. package/dist/adapters/fastify/index.mjs +0 -39
  147. package/dist/adapters/fetch/index.d.mts +0 -47
  148. package/dist/adapters/fetch/index.mjs +0 -42
  149. package/dist/adapters/message-port/index.mjs +0 -87
  150. package/dist/adapters/node/index.d.mts +0 -44
  151. package/dist/adapters/node/index.mjs +0 -41
  152. package/dist/adapters/standard/index.d.mts +0 -95
  153. package/dist/adapters/standard/index.mjs +0 -8
  154. package/dist/adapters/standard-peer/index.d.mts +0 -11
  155. package/dist/adapters/standard-peer/index.mjs +0 -10
  156. package/dist/adapters/websocket/index.mjs +0 -87
  157. package/dist/extensions/callable.d.mts +0 -10
  158. package/dist/extensions/callable.mjs +0 -11
  159. package/dist/helpers/index.d.mts +0 -167
  160. package/dist/helpers/index.mjs +0 -200
  161. package/dist/index.d.mts +0 -476
  162. package/dist/index.mjs +0 -463
  163. package/dist/plugins/index.d.mts +0 -432
  164. package/dist/plugins/index.mjs +0 -965
  165. package/dist/shared/server.1ExWFMze.mjs +0 -69
  166. package/dist/shared/server.9B1jEm5a.d.mts +0 -105
  167. package/dist/shared/server.BB464y-6.mjs +0 -207
  168. package/dist/shared/server.BC5BIu02.d.mts +0 -73
  169. package/dist/shared/server.BSYGskId.d.ts +0 -14
  170. package/dist/shared/server.BvG3boBj.d.mts +0 -14
  171. package/dist/shared/server.CTV_mC2P.d.mts +0 -34
  172. package/dist/shared/server.CYbIpHbH.mjs +0 -239
  173. package/dist/shared/server.Chq5FpXf.mjs +0 -353
  174. package/dist/shared/server.DFPxP2v3.d.mts +0 -166
  175. package/dist/shared/server.DFPxP2v3.d.ts +0 -166
  176. package/dist/shared/server.DOg7ke6y.d.ts +0 -105
  177. package/dist/shared/server.W91HSRkE.mjs +0 -9
  178. package/dist/shared/server.sBQSgqK3.mjs +0 -41
@@ -1,239 +0,0 @@
1
- import { ProcedureContract, resolveMetaPlugins, mergeErrorMap } from '@orpc/contract';
2
- import { isTypescriptObject, getOwn, omit } from '@orpc/shared';
3
- import { c as createProcedureClient, L as Lazy, u as unlazy, P as Procedure } from './server.BB464y-6.mjs';
4
-
5
- const DEFAULT_SUCCESS_STATUS = 200;
6
- const DEFAULT_ERROR_STATUS = 400;
7
-
8
- function createGuardedProcedureLazy(lazy) {
9
- const guarded = new Lazy({
10
- ...lazy["~orpc"],
11
- async loader() {
12
- const { default: maybeProcedure } = await unlazy(lazy);
13
- if (!(maybeProcedure instanceof Procedure)) {
14
- throw new TypeError(`
15
- Expected a lazy<procedure> but got lazy<unknown>.
16
- This should be caught by TypeScript compilation.
17
- Please report this issue if you think this is a bug.
18
- `);
19
- }
20
- return { default: maybeProcedure };
21
- }
22
- });
23
- return guarded;
24
- }
25
- function createContractProcedure(procedure, contract) {
26
- return new Procedure({
27
- ...procedure["~orpc"],
28
- errorMap: contract["~orpc"].errorMap,
29
- meta: contract["~orpc"].meta,
30
- metaPlugins: contract["~orpc"].metaPlugins
31
- });
32
- }
33
- function call(lazyableProcedure, ...[
34
- input = void 0,
35
- options = {}
36
- ]) {
37
- return createProcedureClient(lazyableProcedure, options)(input, options);
38
- }
39
-
40
- const HIDDEN_ROUTER_CONTRACT_SYMBOL = Symbol.for("ORPC_HIDDEN_ROUTER_CONTRACT");
41
- function withHiddenRouterContract(router, contract) {
42
- return new Proxy(router, {
43
- get(target, key) {
44
- if (key === HIDDEN_ROUTER_CONTRACT_SYMBOL) {
45
- return contract;
46
- }
47
- return Reflect.get(target, key);
48
- }
49
- });
50
- }
51
- function getHiddenRouterContract(router) {
52
- return router[HIDDEN_ROUTER_CONTRACT_SYMBOL];
53
- }
54
-
55
- function augmentRouter(router, options) {
56
- if (router instanceof Lazy) {
57
- const [meta, metaPlugins] = resolveMetaPlugins(
58
- options.meta,
59
- options.metaPlugins,
60
- router["~orpc"].metaPlugins
61
- );
62
- const enhanced2 = new Lazy({
63
- meta,
64
- metaPlugins,
65
- async loader() {
66
- const { default: unlaziedRouter } = await unlazy(router);
67
- const enhanced3 = augmentRouter(unlaziedRouter, options);
68
- return unlazy(enhanced3);
69
- }
70
- });
71
- return enhanced2;
72
- }
73
- if (router instanceof Procedure) {
74
- const [meta, metaPlugins] = resolveMetaPlugins(
75
- options.meta,
76
- options.metaPlugins,
77
- router["~orpc"].metaPlugins
78
- );
79
- const enhanced2 = new Procedure({
80
- ...omit(options, ["middlewares", "errorMap", "meta", "metaPlugins"]),
81
- ...router["~orpc"],
82
- meta,
83
- metaPlugins,
84
- errorMap: mergeErrorMap(options.errorMap, router["~orpc"].errorMap),
85
- orderedMiddlewares: [
86
- ...options.middlewares.map((middleware) => ({ middleware, inputSchemasLengthAtUse: 0, outputSchemasLengthAtUse: 0 })),
87
- ...router["~orpc"].orderedMiddlewares
88
- ]
89
- });
90
- return enhanced2;
91
- }
92
- if (!isTypescriptObject(router)) {
93
- return router;
94
- }
95
- const enhanced = {};
96
- for (const [key, child] of Object.entries(router)) {
97
- enhanced[key] = augmentRouter(child, options);
98
- }
99
- return enhanced;
100
- }
101
- function augmentImplementedRouter(router, options) {
102
- if (router instanceof Lazy) {
103
- const enhanced2 = new Lazy({
104
- ...router["~orpc"],
105
- async loader() {
106
- const { default: unlaziedRouter } = await unlazy(router);
107
- const enhanced3 = augmentImplementedRouter(unlaziedRouter, options);
108
- return unlazy(enhanced3);
109
- }
110
- });
111
- return enhanced2;
112
- }
113
- if (router instanceof Procedure) {
114
- const enhanced2 = new Procedure({
115
- ...omit(options, ["middlewares"]),
116
- ...router["~orpc"],
117
- orderedMiddlewares: [
118
- ...options.middlewares.map((middleware) => ({ middleware, inputSchemasLengthAtUse: 0, outputSchemasLengthAtUse: 0 })),
119
- ...router["~orpc"].orderedMiddlewares
120
- ]
121
- });
122
- return enhanced2;
123
- }
124
- if (!isTypescriptObject(router)) {
125
- return router;
126
- }
127
- const enhanced = {};
128
- for (const [key, child] of Object.entries(router)) {
129
- enhanced[key] = augmentImplementedRouter(child, options);
130
- }
131
- return enhanced;
132
- }
133
- async function resolveContractProcedure(router, contract, path) {
134
- if (contract instanceof Procedure) {
135
- return contract;
136
- }
137
- const { default: maybeProcedure } = await unlazy(getRouter(router, path));
138
- if (!(maybeProcedure instanceof Procedure)) {
139
- throw new TypeError(
140
- `[Contract-First] Missing or invalid implementation for procedure at path: "${path.join(".")}". Ensure the procedure is correctly implemented and matches its contract.`
141
- );
142
- }
143
- return createContractProcedure(maybeProcedure, contract);
144
- }
145
- function getRouter(router, path) {
146
- let current = router;
147
- for (let i = 0; i < path.length; i++) {
148
- const segment = path[i];
149
- if (!isTypescriptObject(current)) {
150
- return void 0;
151
- }
152
- if (current instanceof Procedure) {
153
- return void 0;
154
- }
155
- if (!(current instanceof Lazy)) {
156
- current = getOwn(current, segment);
157
- continue;
158
- }
159
- const lazied = current;
160
- const rest = path.slice(i);
161
- return new Lazy({
162
- ...lazied["~orpc"],
163
- async loader() {
164
- const unwrapped = await unlazy(lazied);
165
- const next = getRouter(unwrapped.default, rest);
166
- return await unlazy(next);
167
- }
168
- });
169
- }
170
- if (!isTypescriptObject(current)) {
171
- return void 0;
172
- }
173
- return current;
174
- }
175
- function walkProcedureContractsSync(router, callback, path = []) {
176
- const lazyResults = [];
177
- walkProcedureContractsSyncInternal(router, callback, path.slice(), lazyResults);
178
- return lazyResults;
179
- }
180
- function walkProcedureContractsSyncInternal(router, callback, path, lazyResults) {
181
- const hiddenContract = getHiddenRouterContract(router);
182
- if (hiddenContract !== void 0) {
183
- router = hiddenContract;
184
- }
185
- if (router instanceof ProcedureContract) {
186
- callback(router, path.slice());
187
- return;
188
- }
189
- if (!isTypescriptObject(router)) {
190
- return;
191
- }
192
- for (const [key, value] of Object.entries(router)) {
193
- path.push(key);
194
- if (value instanceof Lazy) {
195
- lazyResults.push({ router: value, path: path.slice() });
196
- } else {
197
- walkProcedureContractsSyncInternal(value, callback, path, lazyResults);
198
- }
199
- path.pop();
200
- }
201
- }
202
- async function walkProcedureContractsAsync(router, callback, path = []) {
203
- const hiddenContract = getHiddenRouterContract(router);
204
- if (hiddenContract !== void 0) {
205
- router = hiddenContract;
206
- }
207
- if (router instanceof ProcedureContract) {
208
- await callback(router, path);
209
- return;
210
- }
211
- if (!isTypescriptObject(router)) {
212
- return;
213
- }
214
- for (const [key, value] of Object.entries(router)) {
215
- if (value instanceof Lazy) {
216
- const { default: router2 } = await unlazy(value);
217
- await walkProcedureContractsAsync(router2, callback, [...path, key]);
218
- } else {
219
- await walkProcedureContractsAsync(value, callback, [...path, key]);
220
- }
221
- }
222
- }
223
- async function unlazyRouter(router) {
224
- if (router instanceof Procedure) {
225
- return router;
226
- }
227
- if (!isTypescriptObject(router)) {
228
- return router;
229
- }
230
- const unlazied = {};
231
- for (const key of Object.keys(router)) {
232
- const item = router[key];
233
- const { default: unlaziedRouter } = await unlazy(item);
234
- unlazied[key] = await unlazyRouter(unlaziedRouter);
235
- }
236
- return unlazied;
237
- }
238
-
239
- export { DEFAULT_SUCCESS_STATUS as D, DEFAULT_ERROR_STATUS as a, augmentRouter as b, augmentImplementedRouter as c, withHiddenRouterContract as d, createGuardedProcedureLazy as e, call as f, getRouter as g, walkProcedureContractsAsync as h, resolveContractProcedure as r, unlazyRouter as u, walkProcedureContractsSync as w };
@@ -1,353 +0,0 @@
1
- import { ORPCError, toORPCError, RPCSerializer, COMMON_ERROR_STATUS_MAP } from '@orpc/client';
2
- import { sortPlugins, toArray, matchesHttpPathPrefix, value, intercept, getTracer, runWithSpan, ORPC_NAME, isAsyncIteratorObject, override, traceAsyncIterator, traceReadableStream, recordSpanError, wrapAsyncIterator, toTracingException, wrapReadableStream, pathToHttpPath, normalizeHttpPath, parseEmptyableJSON, getOwn } from '@orpc/shared';
3
- import { flattenStandardHeader, parseStandardUrl, ErrorEvent } from '@standard-server/core';
4
- import { c as createProcedureClient, u as unlazy, P as Procedure } from './server.BB464y-6.mjs';
5
- import { w as walkProcedureContractsSync, r as resolveContractProcedure, D as DEFAULT_SUCCESS_STATUS, a as DEFAULT_ERROR_STATUS } from './server.CYbIpHbH.mjs';
6
-
7
- class CompositeStandardHandlerPlugin {
8
- name = "~composite";
9
- plugins;
10
- constructor(plugins = []) {
11
- this.plugins = sortPlugins(plugins);
12
- }
13
- init(options) {
14
- for (const plugin of this.plugins) {
15
- if (plugin.init) {
16
- options = plugin.init(options);
17
- }
18
- }
19
- return options;
20
- }
21
- }
22
-
23
- class StandardHandler {
24
- constructor(codec, options) {
25
- this.codec = codec;
26
- options = new CompositeStandardHandlerPlugin([
27
- ...toArray(options.plugins),
28
- new TracingHandlerPlugin()
29
- ]).init(options);
30
- this.routingInterceptors = options.routingInterceptors;
31
- this.interceptors = options.interceptors;
32
- this.clientInterceptors = options.clientInterceptors;
33
- }
34
- routingInterceptors;
35
- interceptors;
36
- clientInterceptors;
37
- async handle(request, options) {
38
- const { prefix } = options;
39
- if (prefix && !matchesHttpPathPrefix(request.url, prefix)) {
40
- return { matched: false, response: void 0 };
41
- }
42
- const context = await value(options.context, request);
43
- return intercept(
44
- this.routingInterceptors,
45
- { context, prefix, request },
46
- async ({ context: context2, prefix: prefix2, request: request2 }) => {
47
- const span = getTracer()?.getActiveSpan();
48
- let step;
49
- const matchedOrNot = await runWithSpan("find_procedure", () => this.codec.resolveProcedure(request2, { context: context2, prefix: prefix2 }));
50
- if (!matchedOrNot) {
51
- span?.updateName(`${ORPC_NAME}_no_match`);
52
- span?.setAttribute("http.request.method", request2.method);
53
- span?.setAttribute("url.path", request2.url);
54
- return { matched: false };
55
- }
56
- const { path, procedure, decodeInput } = matchedOrNot;
57
- span?.updateName(`${ORPC_NAME}.${path.join("/")}`);
58
- span?.setAttribute("rpc.system", ORPC_NAME);
59
- span?.setAttribute("rpc.method", path.join("."));
60
- try {
61
- const response = await intercept(
62
- this.interceptors,
63
- { context: context2, prefix: prefix2, request: request2, path, procedure, decodeInput },
64
- async ({ context: context3, prefix: prefix3, request: request3, path: path2, procedure: procedure2, decodeInput: decodeInput2 }) => {
65
- step = "decode_input";
66
- let input = await runWithSpan("decode_input", decodeInput2);
67
- step = void 0;
68
- if (getTracer() && isAsyncIteratorObject(input)) {
69
- input = override(input, traceAsyncIterator("consume_async_iterator_object_input", input));
70
- } else if (getTracer() && input instanceof ReadableStream) {
71
- input = override(input, traceReadableStream("consume_octet_stream_input", input));
72
- }
73
- const client = createProcedureClient(procedure2, {
74
- context: context3,
75
- path: path2,
76
- interceptors: this.clientInterceptors
77
- });
78
- step = "call_procedure";
79
- const output = await client(input, {
80
- signal: request3.signal,
81
- lastEventId: flattenStandardHeader(request3.headers["last-event-id"])
82
- });
83
- step = void 0;
84
- const response2 = await this.codec.encodeOutput(output, procedure2, path2, { context: context3, prefix: prefix3 });
85
- return response2;
86
- }
87
- );
88
- return { matched: true, response };
89
- } catch (e) {
90
- if (step !== "call_procedure") {
91
- recordSpanError(span, e);
92
- }
93
- const error = step === "decode_input" && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
94
- message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
95
- cause: e
96
- }) : toORPCError(e);
97
- const response = await this.codec.encodeError(error, procedure, path, { context: context2, prefix: prefix2 });
98
- return { matched: true, response };
99
- }
100
- }
101
- );
102
- }
103
- }
104
- class TracingHandlerPlugin {
105
- name = "~tracing";
106
- init(options) {
107
- return {
108
- ...options,
109
- routingInterceptors: [
110
- // Should be placed before user-provided interceptors to help them access the current active span.
111
- async ({ next, request }) => {
112
- const tracer = getTracer();
113
- if (!tracer) {
114
- return next();
115
- }
116
- const parent = tracer.extract?.(request.headers);
117
- const [pathname] = parseStandardUrl(request.url);
118
- return tracer.startActiveSpan(`${request.method} ${pathname}`, parent, async (span) => {
119
- try {
120
- const result = await next();
121
- if (!result.matched) {
122
- span.end();
123
- return result;
124
- }
125
- const body = result.response.body;
126
- if (isAsyncIteratorObject(body)) {
127
- return {
128
- ...result,
129
- response: {
130
- ...result.response,
131
- /**
132
- * @remarks
133
- * **Warning**: Remember use `override` for remaining special properties
134
- */
135
- body: override(body, wrapAsyncIterator(body, {
136
- runWith: (fn) => tracer.withActiveSpan(span, fn),
137
- onError(error) {
138
- if (!(error instanceof ErrorEvent)) {
139
- span.recordException("error", toTracingException(error));
140
- }
141
- },
142
- onFinish() {
143
- span.end();
144
- }
145
- }))
146
- }
147
- };
148
- }
149
- if (body instanceof ReadableStream) {
150
- return {
151
- ...result,
152
- response: {
153
- ...result.response,
154
- /**
155
- * @remarks
156
- * **Warning**: Remember use `override` for remaining special properties
157
- */
158
- body: override(body, wrapReadableStream(body, {
159
- runWith: (fn) => tracer.withActiveSpan(span, fn),
160
- onError(error) {
161
- span.recordException("error", toTracingException(error));
162
- },
163
- onFinish() {
164
- span.end();
165
- }
166
- }))
167
- }
168
- };
169
- }
170
- span.end();
171
- return result;
172
- } catch (e) {
173
- span.recordException("error", toTracingException(e));
174
- span.end();
175
- throw e;
176
- }
177
- });
178
- },
179
- ...toArray(options.routingInterceptors)
180
- ]
181
- };
182
- }
183
- }
184
-
185
- const RPC_DEFAULT_ALLOW_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
186
- const NORMALIZABLE_PATHNAME_REGEX = /[^\w\-.!~*'()/]/;
187
- class RPCMatcher {
188
- filter;
189
- allowMethodsSet;
190
- allowMethodsFn;
191
- rootRouter;
192
- tree = /* @__PURE__ */ new Map();
193
- pendingLazyRouters = /* @__PURE__ */ new Map();
194
- /** segment count of the deepest pending key, never lowered so it stays an upper bound */
195
- maxPendingLazyRouterDepth = 0;
196
- constructor(router, options = {}) {
197
- this.filter = options.filter ?? true;
198
- const allowMethods = options.allowMethods ?? RPC_DEFAULT_ALLOW_METHODS;
199
- if (typeof allowMethods !== "function") {
200
- this.allowMethodsSet = new Set(allowMethods);
201
- } else {
202
- this.allowMethodsFn = allowMethods;
203
- }
204
- this.rootRouter = router;
205
- this.index(router);
206
- }
207
- index(router, path = []) {
208
- const lazyResults = walkProcedureContractsSync(router, (procedure, procedurePath) => {
209
- if (!value(this.filter, procedure, procedurePath)) {
210
- return;
211
- }
212
- this.tree.set(pathToHttpPath(procedurePath), {
213
- path: procedurePath,
214
- contract: procedure,
215
- // contract-first entries have no implementation yet, resolveProcedure fills it in on demand
216
- procedure: procedure instanceof Procedure ? procedure : void 0
217
- });
218
- }, path);
219
- for (const result of lazyResults) {
220
- this.pendingLazyRouters.set(pathToHttpPath(result.path), result);
221
- this.maxPendingLazyRouterDepth = Math.max(this.maxPendingLazyRouterDepth, result.path.length);
222
- }
223
- }
224
- async match(method, pathname, prefix) {
225
- if (this.allowMethodsSet && !this.allowMethodsSet.has(method)) {
226
- return void 0;
227
- }
228
- if (prefix) {
229
- if (!pathname.startsWith(prefix)) {
230
- return void 0;
231
- }
232
- const charAfterPrefix = pathname[prefix.length];
233
- if (charAfterPrefix === "/") {
234
- pathname = pathname.slice(prefix.length);
235
- } else if (charAfterPrefix === void 0) {
236
- pathname = "/";
237
- } else if (prefix[prefix.length - 1] === "/") {
238
- pathname = pathname.slice(prefix.length - 1);
239
- } else {
240
- return void 0;
241
- }
242
- }
243
- if (pathname.length > 1 && pathname.endsWith("/")) {
244
- pathname = pathname.slice(0, -1);
245
- }
246
- const loading = this.resolvePendingLazyRouters(pathname);
247
- if (loading !== void 0) {
248
- await loading;
249
- }
250
- let entry = this.tree.get(pathname);
251
- if (entry === void 0 && NORMALIZABLE_PATHNAME_REGEX.test(pathname)) {
252
- const normalizedPathname = normalizeHttpPath(pathname);
253
- const normalizedLoading = this.resolvePendingLazyRouters(normalizedPathname);
254
- if (normalizedLoading !== void 0) {
255
- await normalizedLoading;
256
- }
257
- entry = this.tree.get(normalizedPathname);
258
- }
259
- if (entry === void 0) {
260
- return void 0;
261
- }
262
- const procedure = entry.procedure ?? await this.resolveProcedure(entry);
263
- if (this.allowMethodsFn && !this.allowMethodsFn(method, procedure, entry.path)) {
264
- return void 0;
265
- }
266
- return {
267
- path: entry.path,
268
- procedure
269
- };
270
- }
271
- resolvePendingLazyRouters(pathname) {
272
- if (this.pendingLazyRouters.size === 0) {
273
- return;
274
- }
275
- let slashIndex = 0;
276
- for (let depth = 1; slashIndex !== -1 && depth <= this.maxPendingLazyRouterDepth; depth++) {
277
- const nextSlashIndex = pathname.indexOf("/", slashIndex + 1);
278
- const httpPathPrefix = nextSlashIndex === -1 ? pathname : pathname.slice(0, nextSlashIndex);
279
- const pending = this.pendingLazyRouters.get(httpPathPrefix);
280
- if (pending !== void 0) {
281
- return this.loadPendingLazyRouter(httpPathPrefix, pending).then(() => this.resolvePendingLazyRouters(pathname));
282
- }
283
- slashIndex = nextSlashIndex;
284
- }
285
- }
286
- loadPendingLazyRouter(httpPathPrefix, pending) {
287
- if (pending.loading === void 0) {
288
- pending.loading = this.indexPendingLazyRouter(httpPathPrefix, pending).catch((error) => {
289
- pending.loading = void 0;
290
- throw error;
291
- });
292
- }
293
- return pending.loading;
294
- }
295
- async indexPendingLazyRouter(httpPathPrefix, pending) {
296
- const { default: router } = await unlazy(pending.router);
297
- this.index(router, pending.path);
298
- this.pendingLazyRouters.delete(httpPathPrefix);
299
- }
300
- async resolveProcedure(entry) {
301
- entry.procedure = await resolveContractProcedure(this.rootRouter, entry.contract, entry.path);
302
- return entry.procedure;
303
- }
304
- }
305
-
306
- class RPCHandlerCodec {
307
- matcher;
308
- serializer;
309
- errorStatusMap;
310
- outputStatus;
311
- constructor(router, options = {}) {
312
- this.matcher = new RPCMatcher(router, options);
313
- this.serializer = options.serializer ?? new RPCSerializer();
314
- this.errorStatusMap = options.errorStatusMap ?? COMMON_ERROR_STATUS_MAP;
315
- this.outputStatus = options.outputStatus;
316
- }
317
- async resolveProcedure(request, options) {
318
- const [pathname, query] = parseStandardUrl(request.url);
319
- const matched = await this.matcher.match(request.method, pathname, options.prefix);
320
- if (!matched) {
321
- return void 0;
322
- }
323
- return {
324
- procedure: matched.procedure,
325
- path: matched.path,
326
- decodeInput: async () => {
327
- if (request.method === "GET") {
328
- const dataString = new URLSearchParams(query).getAll("data").at(-1);
329
- return this.serializer.deserialize(parseEmptyableJSON(dataString));
330
- }
331
- const body = await request.resolveBody();
332
- return this.serializer.deserialize(body);
333
- }
334
- };
335
- }
336
- encodeOutput(output, procedure, path, options) {
337
- return {
338
- headers: {},
339
- status: value(this.outputStatus, output, procedure, path, options) ?? DEFAULT_SUCCESS_STATUS,
340
- body: this.serializer.serialize(output)
341
- };
342
- }
343
- encodeError(error, _procedure, _path, _options) {
344
- const status = getOwn(this.errorStatusMap, error.code) ?? DEFAULT_ERROR_STATUS;
345
- return {
346
- headers: {},
347
- status,
348
- body: this.serializer.serialize(error.toJSON())
349
- };
350
- }
351
- }
352
-
353
- export { RPCHandlerCodec as R, StandardHandler as S, RPCMatcher as a, RPC_DEFAULT_ALLOW_METHODS as b };