@temporary-name/server 1.9.3-alpha.e2d8d164da72fb570c2b14a4fa956c80f9e33cdc → 1.9.3-alpha.ec3bfb9dce56198911349c322c970208b21b50db

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 (42) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +4 -6
  2. package/dist/adapters/aws-lambda/index.d.ts +4 -6
  3. package/dist/adapters/aws-lambda/index.mjs +4 -4
  4. package/dist/adapters/fetch/index.d.mts +8 -86
  5. package/dist/adapters/fetch/index.d.ts +8 -86
  6. package/dist/adapters/fetch/index.mjs +16 -155
  7. package/dist/adapters/node/index.d.mts +8 -63
  8. package/dist/adapters/node/index.d.ts +8 -63
  9. package/dist/adapters/node/index.mjs +14 -120
  10. package/dist/adapters/standard/index.d.mts +10 -7
  11. package/dist/adapters/standard/index.d.ts +10 -7
  12. package/dist/adapters/standard/index.mjs +4 -4
  13. package/dist/helpers/index.mjs +3 -29
  14. package/dist/index.d.mts +121 -239
  15. package/dist/index.d.ts +121 -239
  16. package/dist/index.mjs +167 -352
  17. package/dist/openapi/index.d.mts +12 -28
  18. package/dist/openapi/index.d.ts +12 -28
  19. package/dist/openapi/index.mjs +59 -112
  20. package/dist/shared/server.C1RJffw4.mjs +30 -0
  21. package/dist/shared/server.CQIFwyhc.mjs +40 -0
  22. package/dist/shared/server.CVhIyQ4x.d.mts +41 -0
  23. package/dist/shared/server.CYa9puL2.mjs +403 -0
  24. package/dist/shared/server.ChOv1yG3.mjs +319 -0
  25. package/dist/shared/server.Cj3_Lp61.d.mts +373 -0
  26. package/dist/shared/server.Cj3_Lp61.d.ts +373 -0
  27. package/dist/shared/server.Cza0RB3u.mjs +160 -0
  28. package/dist/shared/server.D8RAzJ_p.d.ts +41 -0
  29. package/dist/shared/server.YUvuxHty.mjs +48 -0
  30. package/package.json +10 -28
  31. package/dist/plugins/index.d.mts +0 -160
  32. package/dist/plugins/index.d.ts +0 -160
  33. package/dist/plugins/index.mjs +0 -288
  34. package/dist/shared/server.B93y_8tj.d.mts +0 -23
  35. package/dist/shared/server.BYYf0Wn6.mjs +0 -202
  36. package/dist/shared/server.C3RuMHWl.d.mts +0 -192
  37. package/dist/shared/server.C3RuMHWl.d.ts +0 -192
  38. package/dist/shared/server.CT1xhSmE.d.mts +0 -56
  39. package/dist/shared/server.CqTex_jI.mjs +0 -265
  40. package/dist/shared/server.D_fags8X.d.ts +0 -23
  41. package/dist/shared/server.Kxw442A9.mjs +0 -247
  42. package/dist/shared/server.cjcgLdr1.d.ts +0 -56
@@ -0,0 +1,403 @@
1
+ import { isObject, NullProtoObj, isAsyncIteratorObject, isORPCErrorJson, createORPCErrorFromJson, toORPCError, fallbackContractConfig, stringifyJSON, isORPCErrorStatus, tryDecodeURIComponent, toHttpPath, runWithSpan, ORPC_NAME, asyncIteratorWithSpan, setSpanError, ORPCError } from '@temporary-name/shared';
2
+ import { c as createProcedureClient } from './server.Cza0RB3u.mjs';
3
+ import { mapEventIterator, ErrorEvent } from '@temporary-name/standard-server';
4
+ import { j as jsonSerialize } from './server.CQIFwyhc.mjs';
5
+ import { traverseContractProcedures, getLazyMeta, unlazy } from '@temporary-name/server';
6
+ import { createRouter, addRoute, findRoute } from 'rou3';
7
+ import { s as standardizeHTTPPath } from './server.ChOv1yG3.mjs';
8
+
9
+ function bracketNotationSerialize(data, segments = [], result = []) {
10
+ if (Array.isArray(data)) {
11
+ data.forEach((item, i) => {
12
+ bracketNotationSerialize(item, [...segments, i], result);
13
+ });
14
+ } else if (isObject(data)) {
15
+ for (const key in data) {
16
+ bracketNotationSerialize(data[key], [...segments, key], result);
17
+ }
18
+ } else {
19
+ result.push([stringifyPath(segments), data]);
20
+ }
21
+ return result;
22
+ }
23
+ function bracketNotationDeserialize(serialized, { maxArrayIndex = 9999 } = {}) {
24
+ if (serialized.length === 0) {
25
+ return {};
26
+ }
27
+ const arrayPushStyles = /* @__PURE__ */ new WeakSet();
28
+ const ref = { value: [] };
29
+ for (const [path, value] of serialized) {
30
+ const segments = parsePath(path);
31
+ let currentRef = ref;
32
+ let nextSegment = "value";
33
+ segments.forEach((segment, i) => {
34
+ if (!Array.isArray(currentRef[nextSegment]) && !isObject(currentRef[nextSegment])) {
35
+ currentRef[nextSegment] = [];
36
+ }
37
+ if (i !== segments.length - 1) {
38
+ if (Array.isArray(currentRef[nextSegment]) && !isValidArrayIndex(segment, maxArrayIndex)) {
39
+ if (arrayPushStyles.has(currentRef[nextSegment])) {
40
+ arrayPushStyles.delete(currentRef[nextSegment]);
41
+ currentRef[nextSegment] = pushStyleArrayToObject(currentRef[nextSegment]);
42
+ } else {
43
+ currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
44
+ }
45
+ }
46
+ } else {
47
+ if (Array.isArray(currentRef[nextSegment])) {
48
+ if (segment === "") {
49
+ if (currentRef[nextSegment].length && !arrayPushStyles.has(currentRef[nextSegment])) {
50
+ currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
51
+ }
52
+ } else {
53
+ if (arrayPushStyles.has(currentRef[nextSegment])) {
54
+ arrayPushStyles.delete(currentRef[nextSegment]);
55
+ currentRef[nextSegment] = pushStyleArrayToObject(currentRef[nextSegment]);
56
+ } else if (!isValidArrayIndex(segment, maxArrayIndex)) {
57
+ currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
58
+ }
59
+ }
60
+ }
61
+ }
62
+ currentRef = currentRef[nextSegment];
63
+ nextSegment = segment;
64
+ });
65
+ if (Array.isArray(currentRef) && nextSegment === "") {
66
+ arrayPushStyles.add(currentRef);
67
+ currentRef.push(value);
68
+ } else if (nextSegment in currentRef) {
69
+ if (Array.isArray(currentRef[nextSegment])) {
70
+ currentRef[nextSegment].push(value);
71
+ } else {
72
+ currentRef[nextSegment] = [currentRef[nextSegment], value];
73
+ }
74
+ } else {
75
+ currentRef[nextSegment] = value;
76
+ }
77
+ }
78
+ return ref.value;
79
+ }
80
+ function stringifyPath(segments) {
81
+ return segments.map((segment) => {
82
+ return segment.toString().replace(/[\\[\]]/g, (match) => {
83
+ switch (match) {
84
+ case "\\":
85
+ return "\\\\";
86
+ case "[":
87
+ return "\\[";
88
+ case "]":
89
+ return "\\]";
90
+ /* v8 ignore next 2 */
91
+ default:
92
+ return match;
93
+ }
94
+ });
95
+ }).reduce((result, segment, i) => {
96
+ if (i === 0) {
97
+ return segment;
98
+ }
99
+ return `${result}[${segment}]`;
100
+ }, "");
101
+ }
102
+ function parsePath(path) {
103
+ const segments = [];
104
+ let inBrackets = false;
105
+ let currentSegment = "";
106
+ let backslashCount = 0;
107
+ for (let i = 0; i < path.length; i++) {
108
+ const char = path[i];
109
+ const nextChar = path[i + 1];
110
+ if (inBrackets && char === "]" && (nextChar === void 0 || nextChar === "[") && backslashCount % 2 === 0) {
111
+ if (nextChar === void 0) {
112
+ inBrackets = false;
113
+ }
114
+ segments.push(currentSegment);
115
+ currentSegment = "";
116
+ i++;
117
+ } else if (segments.length === 0 && char === "[" && backslashCount % 2 === 0) {
118
+ inBrackets = true;
119
+ segments.push(currentSegment);
120
+ currentSegment = "";
121
+ } else if (char === "\\") {
122
+ backslashCount++;
123
+ } else {
124
+ currentSegment += "\\".repeat(backslashCount / 2) + char;
125
+ backslashCount = 0;
126
+ }
127
+ }
128
+ return inBrackets || segments.length === 0 ? [path] : segments;
129
+ }
130
+ function isValidArrayIndex(value, maxIndex) {
131
+ return /^0$|^[1-9]\d*$/.test(value) && Number(value) <= maxIndex;
132
+ }
133
+ function arrayToObject(array) {
134
+ const obj = new NullProtoObj();
135
+ array.forEach((item, i) => {
136
+ obj[i] = item;
137
+ });
138
+ return obj;
139
+ }
140
+ function pushStyleArrayToObject(array) {
141
+ const obj = new NullProtoObj();
142
+ obj[""] = array.length === 1 ? array[0] : array;
143
+ return obj;
144
+ }
145
+
146
+ function serialize(data, options = {}) {
147
+ if (isAsyncIteratorObject(data) && !options.outputFormat) {
148
+ return mapEventIterator(data, {
149
+ value: async (value) => _serialize(value, { outputFormat: "plain" }),
150
+ error: async (e) => {
151
+ return new ErrorEvent({
152
+ data: _serialize(toORPCError(e).toJSON(), { outputFormat: "plain" }),
153
+ cause: e
154
+ });
155
+ }
156
+ });
157
+ }
158
+ return _serialize(data, options);
159
+ }
160
+ function _serialize(data, options) {
161
+ const [json, hasBlob] = jsonSerialize(data);
162
+ if (options.outputFormat === "plain") {
163
+ return json;
164
+ }
165
+ if (options.outputFormat === "URLSearchParams") {
166
+ const params = new URLSearchParams();
167
+ for (const [path, value] of bracketNotationSerialize(json)) {
168
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
169
+ params.append(path, value.toString());
170
+ }
171
+ }
172
+ return params;
173
+ }
174
+ if (json instanceof Blob || json === void 0 || !hasBlob) {
175
+ return json;
176
+ }
177
+ const form = new FormData();
178
+ for (const [path, value] of bracketNotationSerialize(json)) {
179
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
180
+ form.append(path, value.toString());
181
+ } else if (value instanceof Blob) {
182
+ form.append(path, value);
183
+ }
184
+ }
185
+ return form;
186
+ }
187
+ function deserialize(data) {
188
+ if (data instanceof URLSearchParams || data instanceof FormData) {
189
+ return bracketNotationDeserialize(Array.from(data.entries()));
190
+ }
191
+ if (isAsyncIteratorObject(data)) {
192
+ return mapEventIterator(data, {
193
+ value: async (value) => value,
194
+ error: async (e) => {
195
+ if (e instanceof ErrorEvent && isORPCErrorJson(e.data)) {
196
+ return createORPCErrorFromJson(e.data, { cause: e });
197
+ }
198
+ return e;
199
+ }
200
+ });
201
+ }
202
+ return data;
203
+ }
204
+
205
+ async function decode(request, pathParams) {
206
+ return {
207
+ path: pathParams ?? {},
208
+ query: bracketNotationDeserialize(Array.from(request.url.searchParams.entries())),
209
+ headers: request.headers,
210
+ body: deserialize(await request.body()) ?? {}
211
+ };
212
+ }
213
+ function encode(output, procedure) {
214
+ const successStatus = fallbackContractConfig(
215
+ "defaultSuccessStatus",
216
+ procedure["~orpc"].route.successStatus
217
+ );
218
+ const outputStructure = fallbackContractConfig(
219
+ "defaultOutputStructure",
220
+ procedure["~orpc"].route.outputStructure
221
+ );
222
+ if (outputStructure === "compact") {
223
+ return {
224
+ status: successStatus,
225
+ headers: new Headers(),
226
+ body: serialize(output)
227
+ };
228
+ }
229
+ if (!isDetailedOutput(output)) {
230
+ throw new Error(`
231
+ Invalid "detailed" output structure:
232
+ \u2022 Expected an object with optional properties:
233
+ - status (number 200-399)
234
+ - headers (Record<string, string | string[]>)
235
+ - body (any)
236
+ \u2022 No extra keys allowed.
237
+
238
+ Actual value:
239
+ ${stringifyJSON(output)}
240
+ `);
241
+ }
242
+ return {
243
+ status: output.status ?? successStatus,
244
+ headers: output.headers ?? new Headers(),
245
+ body: serialize(output.body)
246
+ };
247
+ }
248
+ function encodeError(error) {
249
+ return {
250
+ status: error.status,
251
+ headers: new Headers(),
252
+ body: serialize(error.toJSON(), { outputFormat: "plain" })
253
+ };
254
+ }
255
+ function isDetailedOutput(output) {
256
+ if (!isObject(output)) {
257
+ return false;
258
+ }
259
+ if (output.headers && !isObject(output.headers)) {
260
+ return false;
261
+ }
262
+ if (output.status !== void 0 && (typeof output.status !== "number" || !Number.isInteger(output.status) || isORPCErrorStatus(output.status))) {
263
+ return false;
264
+ }
265
+ return true;
266
+ }
267
+
268
+ function resolveFriendlyStandardHandleOptions(options) {
269
+ return {
270
+ ...options,
271
+ context: options.context ?? {}
272
+ // Context only optional if all fields are optional
273
+ };
274
+ }
275
+ function toRou3Pattern(path) {
276
+ return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
277
+ }
278
+ function decodeParams(params) {
279
+ return Object.fromEntries(
280
+ Object.entries(params).map(([key, value]) => [key, tryDecodeURIComponent(value)])
281
+ );
282
+ }
283
+
284
+ class StandardOpenAPIMatcher {
285
+ tree = createRouter();
286
+ pendingRouters = [];
287
+ init(router, path = []) {
288
+ const laziedOptions = traverseContractProcedures({ router, path }, (traverseOptions) => {
289
+ const { path: path2, contract } = traverseOptions;
290
+ const method = fallbackContractConfig("defaultMethod", contract["~orpc"].route.method);
291
+ const httpPath = toRou3Pattern(contract["~orpc"].route.path ?? toHttpPath(path2));
292
+ addRoute(this.tree, method, httpPath, {
293
+ path: path2,
294
+ // cast is safe because router is typed as Router (not ContractRouter)
295
+ procedure: contract,
296
+ router
297
+ });
298
+ });
299
+ this.pendingRouters.push(
300
+ ...laziedOptions.map((option) => ({
301
+ ...option,
302
+ httpPathPrefix: toHttpPath(option.path),
303
+ laziedPrefix: getLazyMeta(option.router).prefix
304
+ }))
305
+ );
306
+ }
307
+ async match(method, pathname) {
308
+ if (this.pendingRouters.length) {
309
+ const newPendingRouters = [];
310
+ for (const pendingRouter of this.pendingRouters) {
311
+ if (!pendingRouter.laziedPrefix || pathname.startsWith(pendingRouter.laziedPrefix) || pathname.startsWith(pendingRouter.httpPathPrefix)) {
312
+ const { default: router } = await unlazy(pendingRouter.router);
313
+ this.init(router, pendingRouter.path);
314
+ } else {
315
+ newPendingRouters.push(pendingRouter);
316
+ }
317
+ }
318
+ this.pendingRouters = newPendingRouters;
319
+ }
320
+ const match = findRoute(this.tree, method, pathname);
321
+ if (!match) {
322
+ return void 0;
323
+ }
324
+ return {
325
+ path: match.data.path,
326
+ procedure: match.data.procedure,
327
+ params: match.params ? decodeParams(match.params) : void 0
328
+ };
329
+ }
330
+ }
331
+
332
+ class StandardHandler {
333
+ matcher;
334
+ constructor(router, _options) {
335
+ this.matcher = new StandardOpenAPIMatcher();
336
+ this.matcher.init(router);
337
+ }
338
+ async handle(request, options) {
339
+ const prefix = options.prefix?.replace(/\/$/, "") || void 0;
340
+ if (prefix && !request.url.pathname.startsWith(`${prefix}/`) && request.url.pathname !== prefix) {
341
+ return { matched: false, response: void 0 };
342
+ }
343
+ return runWithSpan({ name: `${request.method} ${request.url.pathname}` }, async (span) => {
344
+ let step;
345
+ try {
346
+ const context = options.context;
347
+ const method = request.method;
348
+ const url = request.url;
349
+ const pathname = prefix ? url.pathname.replace(prefix, "") : url.pathname;
350
+ const match = await runWithSpan(
351
+ { name: "find_procedure" },
352
+ () => this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`)
353
+ );
354
+ if (!match) {
355
+ return { matched: false, response: void 0 };
356
+ }
357
+ span?.updateName(`${ORPC_NAME}.${match.path.join("/")}`);
358
+ span?.setAttribute("rpc.system", ORPC_NAME);
359
+ span?.setAttribute("rpc.method", match.path.join("."));
360
+ step = "decode_input";
361
+ const input = await runWithSpan({ name: "decode_input" }, () => decode(request, match.params));
362
+ step = void 0;
363
+ if (isAsyncIteratorObject(input.body)) {
364
+ input.body = asyncIteratorWithSpan(
365
+ { name: "consume_event_iterator_input", signal: request.signal },
366
+ input.body
367
+ );
368
+ }
369
+ const client = createProcedureClient(match.procedure, {
370
+ context,
371
+ path: match.path
372
+ });
373
+ step = "call_procedure";
374
+ const output = await client(input, {
375
+ request,
376
+ signal: request.signal,
377
+ lastEventId: request.headers.get("last-event-id") ?? void 0
378
+ });
379
+ step = void 0;
380
+ const response = encode(output, match.procedure);
381
+ return {
382
+ matched: true,
383
+ response
384
+ };
385
+ } catch (e) {
386
+ if (step !== "call_procedure") {
387
+ setSpanError(span, e);
388
+ }
389
+ const error = step === "decode_input" && !(e instanceof ORPCError) ? new ORPCError("BAD_REQUEST", {
390
+ message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
391
+ cause: e
392
+ }) : toORPCError(e);
393
+ const response = encodeError(error);
394
+ return {
395
+ matched: true,
396
+ response
397
+ };
398
+ }
399
+ });
400
+ }
401
+ }
402
+
403
+ export { StandardHandler as S, encodeError as a, StandardOpenAPIMatcher as b, decodeParams as c, decode as d, encode as e, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };