@temporary-name/server 0.0.1-alpha.123c4256a169035efa84c708de3e315d2a7f5ae1

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 (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +31 -0
  3. package/dist/adapters/aws-lambda/index.d.mts +26 -0
  4. package/dist/adapters/aws-lambda/index.d.ts +26 -0
  5. package/dist/adapters/aws-lambda/index.mjs +29 -0
  6. package/dist/adapters/fastify/index.d.mts +23 -0
  7. package/dist/adapters/fastify/index.d.ts +23 -0
  8. package/dist/adapters/fastify/index.mjs +29 -0
  9. package/dist/adapters/fetch/index.d.mts +28 -0
  10. package/dist/adapters/fetch/index.d.ts +28 -0
  11. package/dist/adapters/fetch/index.mjs +31 -0
  12. package/dist/adapters/node/index.d.mts +26 -0
  13. package/dist/adapters/node/index.d.ts +26 -0
  14. package/dist/adapters/node/index.mjs +29 -0
  15. package/dist/handler/index.d.mts +27 -0
  16. package/dist/handler/index.d.ts +27 -0
  17. package/dist/handler/index.mjs +7 -0
  18. package/dist/helpers/index.d.mts +149 -0
  19. package/dist/helpers/index.d.ts +149 -0
  20. package/dist/helpers/index.mjs +142 -0
  21. package/dist/index.d.mts +414 -0
  22. package/dist/index.d.ts +414 -0
  23. package/dist/index.mjs +696 -0
  24. package/dist/openapi/index.d.mts +166 -0
  25. package/dist/openapi/index.d.ts +166 -0
  26. package/dist/openapi/index.mjs +834 -0
  27. package/dist/shared/server.7EG6rqbI.mjs +496 -0
  28. package/dist/shared/server.B3SSI6V6.d.mts +3026 -0
  29. package/dist/shared/server.B3SSI6V6.d.ts +3026 -0
  30. package/dist/shared/server.BwXNcNk_.mjs +275 -0
  31. package/dist/shared/server.C1RJffw4.mjs +30 -0
  32. package/dist/shared/server.CjPiuQYH.d.mts +51 -0
  33. package/dist/shared/server.CjPiuQYH.d.ts +51 -0
  34. package/dist/shared/server.Cuq0WHVy.mjs +529 -0
  35. package/dist/shared/server.DmZlW6xR.d.ts +39 -0
  36. package/dist/shared/server.KW5uPnMg.d.mts +39 -0
  37. package/package.json +86 -0
@@ -0,0 +1,496 @@
1
+ import { resolveMaybeOptionalOptions, value, runWithSpan, isAsyncIteratorObject, overlayProxy, asyncIteratorWithSpan, isObject, NullProtoObj, fallbackContractConfig, stringifyJSON, tryDecodeURIComponent, parseHTTPEndpoint, KRUSTY_NAME, setSpanError } from '@temporary-name/shared';
2
+ import { N as NotFoundError, V as ValidationError, B as BadRequestError, I as InternalServerError, e as encodeError, i as isApiErrorStatus, s as standardizeHTTPPath, a as isLazyResource, v as validateLazyLoadedResource, A as ApiError, t as toApiError$1 } from './server.BwXNcNk_.mjs';
3
+ import { HibernationEventIterator, mapEventIterator, ErrorEvent } from '@temporary-name/standard-server';
4
+ import { safeDecodeAsync, safeEncodeAsync } from '@temporary-name/zod';
5
+ import { toApiError } from '@temporary-name/server';
6
+ import { createRouter, addRoute, findRoute } from 'rou3';
7
+
8
+ function mergeContext(context, other) {
9
+ return { ...context, ...other };
10
+ }
11
+
12
+ function getEndpointId(endpoint) {
13
+ return `${endpoint.method}:${endpoint.path}`;
14
+ }
15
+
16
+ function middlewareOutputFn(output) {
17
+ return { output, context: {} };
18
+ }
19
+
20
+ function createProcedureClient(procedure, ...rest) {
21
+ const options = resolveMaybeOptionalOptions(rest);
22
+ return async (...[input, callerOptions]) => {
23
+ const clientContext = callerOptions?.context ?? {};
24
+ const context = await value(options.context ?? {}, clientContext);
25
+ const output = await runWithSpan({ name: "call_procedure", signal: callerOptions?.signal }, (span) => {
26
+ span?.setAttribute("procedure.path", getEndpointId(procedure["~def"].endpoint));
27
+ return executeProcedureInternal(procedure, input, {
28
+ context,
29
+ procedure,
30
+ request: callerOptions?.request,
31
+ signal: callerOptions?.signal,
32
+ lastEventId: callerOptions?.lastEventId
33
+ });
34
+ });
35
+ if (isAsyncIteratorObject(output)) {
36
+ if (output instanceof HibernationEventIterator) {
37
+ return output;
38
+ }
39
+ return overlayProxy(
40
+ output,
41
+ mapEventIterator(
42
+ asyncIteratorWithSpan(
43
+ { name: "consume_event_iterator_output", signal: callerOptions?.signal },
44
+ output
45
+ ),
46
+ {
47
+ value: (v) => v,
48
+ error: async (e) => e
49
+ }
50
+ )
51
+ );
52
+ }
53
+ return output;
54
+ };
55
+ }
56
+ async function validateInput(procedure, input) {
57
+ const schemas = procedure["~def"].schemas;
58
+ return runWithSpan({ name: "validate_input" }, async () => {
59
+ const resultBody = await safeDecodeAsync(schemas.bodySchema, input.body, {
60
+ coerce: false,
61
+ defaultStrictObjects: true
62
+ });
63
+ const resultPath = await safeDecodeAsync(schemas.pathSchema, input.path, {
64
+ coerce: true,
65
+ defaultStrictObjects: true
66
+ });
67
+ const resultQuery = await safeDecodeAsync(schemas.querySchema, input.query, {
68
+ coerce: true,
69
+ defaultStrictObjects: true
70
+ });
71
+ const issues = [];
72
+ if (!resultPath.success) {
73
+ issues.push(...resultPath.error.issues.map((i) => ({ ...i, path: ["path", ...i.path] })));
74
+ throw new NotFoundError({
75
+ cause: new ValidationError({
76
+ issues,
77
+ data: input
78
+ })
79
+ });
80
+ }
81
+ if (!resultBody.success) {
82
+ issues.push(...resultBody.error.issues.map((i) => ({ ...i, path: ["body", ...i.path] })));
83
+ }
84
+ if (!resultQuery.success) {
85
+ issues.push(...resultQuery.error.issues.map((i) => ({ ...i, path: ["query", ...i.path] })));
86
+ }
87
+ if (issues.length > 0) {
88
+ throw new BadRequestError({
89
+ code: "input_validation_failed",
90
+ message: "Input validation failed",
91
+ cause: new ValidationError({
92
+ issues,
93
+ data: input
94
+ })
95
+ });
96
+ }
97
+ const results = {
98
+ body: resultBody.data,
99
+ path: resultPath.data,
100
+ query: resultQuery.data
101
+ };
102
+ return results;
103
+ });
104
+ }
105
+ async function validateOutput(procedure, output) {
106
+ const schema = procedure["~def"].schemas.outputSchema;
107
+ if (!schema) {
108
+ return output;
109
+ }
110
+ return runWithSpan({ name: "validate_output" }, async () => {
111
+ const result = await safeEncodeAsync(schema, output);
112
+ if (!result.success) {
113
+ throw new InternalServerError({
114
+ message: "Output validation failed",
115
+ cause: new ValidationError({
116
+ issues: result.error.issues,
117
+ data: output
118
+ })
119
+ });
120
+ }
121
+ return result.data;
122
+ });
123
+ }
124
+ async function executeProcedureInternal(procedure, input, options) {
125
+ const middlewares = procedure["~def"].middlewares;
126
+ const validationIndex = middlewares.length;
127
+ const next = async (index, context, input2) => {
128
+ let currentInput = input2;
129
+ if (index === validationIndex) {
130
+ currentInput = await validateInput(procedure, currentInput);
131
+ }
132
+ const mid = middlewares[index];
133
+ const output = mid ? await runWithSpan({ name: `middleware.${mid.name}`, signal: options.signal }, async (span) => {
134
+ span?.setAttribute("middleware.index", index);
135
+ span?.setAttribute("middleware.name", mid.name);
136
+ const result = await mid(
137
+ {
138
+ ...options,
139
+ context,
140
+ next: async (nextOptions) => {
141
+ const nextContext = nextOptions?.context ?? {};
142
+ return {
143
+ output: await next(index + 1, mergeContext(context, nextContext), currentInput),
144
+ // NB: Pretty sure this isn't used (or meant to be used) at runtime, it's just there
145
+ // to get type inference in the builder (via the caller returning the output of next() in
146
+ // the middleware function)
147
+ context: nextContext
148
+ };
149
+ }
150
+ },
151
+ currentInput,
152
+ middlewareOutputFn
153
+ );
154
+ return result.output;
155
+ }) : await runWithSpan(
156
+ { name: "handler", signal: options.signal },
157
+ () => procedure["~def"].handler(currentInput, { ...options, context })
158
+ );
159
+ if (index === validationIndex) {
160
+ return await validateOutput(procedure, output);
161
+ }
162
+ return output;
163
+ };
164
+ return next(0, options.context, input);
165
+ }
166
+ function call(procedure, input, ...rest) {
167
+ const options = resolveMaybeOptionalOptions(rest);
168
+ return createProcedureClient(procedure, options)(input, options);
169
+ }
170
+
171
+ function bracketNotationDeserialize(serialized, { maxArrayIndex = 9999 } = {}) {
172
+ if (serialized.length === 0) {
173
+ return {};
174
+ }
175
+ const arrayPushStyles = /* @__PURE__ */ new WeakSet();
176
+ const ref = { value: [] };
177
+ for (const [path, value] of serialized) {
178
+ const segments = parsePath(path);
179
+ let currentRef = ref;
180
+ let nextSegment = "value";
181
+ segments.forEach((segment, i) => {
182
+ if (!Array.isArray(currentRef[nextSegment]) && !isObject(currentRef[nextSegment])) {
183
+ currentRef[nextSegment] = [];
184
+ }
185
+ if (i !== segments.length - 1) {
186
+ if (Array.isArray(currentRef[nextSegment]) && !isValidArrayIndex(segment, maxArrayIndex)) {
187
+ if (arrayPushStyles.has(currentRef[nextSegment])) {
188
+ arrayPushStyles.delete(currentRef[nextSegment]);
189
+ currentRef[nextSegment] = pushStyleArrayToObject(currentRef[nextSegment]);
190
+ } else {
191
+ currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
192
+ }
193
+ }
194
+ } else {
195
+ if (Array.isArray(currentRef[nextSegment])) {
196
+ if (segment === "") {
197
+ if (currentRef[nextSegment].length && !arrayPushStyles.has(currentRef[nextSegment])) {
198
+ currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
199
+ }
200
+ } else {
201
+ if (arrayPushStyles.has(currentRef[nextSegment])) {
202
+ arrayPushStyles.delete(currentRef[nextSegment]);
203
+ currentRef[nextSegment] = pushStyleArrayToObject(currentRef[nextSegment]);
204
+ } else if (!isValidArrayIndex(segment, maxArrayIndex)) {
205
+ currentRef[nextSegment] = arrayToObject(currentRef[nextSegment]);
206
+ }
207
+ }
208
+ }
209
+ }
210
+ currentRef = currentRef[nextSegment];
211
+ nextSegment = segment;
212
+ });
213
+ if (Array.isArray(currentRef) && nextSegment === "") {
214
+ arrayPushStyles.add(currentRef);
215
+ currentRef.push(value);
216
+ } else if (nextSegment in currentRef) {
217
+ if (Array.isArray(currentRef[nextSegment])) {
218
+ currentRef[nextSegment].push(value);
219
+ } else {
220
+ currentRef[nextSegment] = [currentRef[nextSegment], value];
221
+ }
222
+ } else {
223
+ currentRef[nextSegment] = value;
224
+ }
225
+ }
226
+ return ref.value;
227
+ }
228
+ function parsePath(path) {
229
+ const segments = [];
230
+ let inBrackets = false;
231
+ let currentSegment = "";
232
+ let backslashCount = 0;
233
+ for (let i = 0; i < path.length; i++) {
234
+ const char = path[i];
235
+ const nextChar = path[i + 1];
236
+ if (inBrackets && char === "]" && (nextChar === void 0 || nextChar === "[") && backslashCount % 2 === 0) {
237
+ if (nextChar === void 0) {
238
+ inBrackets = false;
239
+ }
240
+ segments.push(currentSegment);
241
+ currentSegment = "";
242
+ i++;
243
+ } else if (segments.length === 0 && char === "[" && backslashCount % 2 === 0) {
244
+ inBrackets = true;
245
+ segments.push(currentSegment);
246
+ currentSegment = "";
247
+ } else if (char === "\\") {
248
+ backslashCount++;
249
+ } else {
250
+ currentSegment += "\\".repeat(backslashCount / 2) + char;
251
+ backslashCount = 0;
252
+ }
253
+ }
254
+ return inBrackets || segments.length === 0 ? [path] : segments;
255
+ }
256
+ function isValidArrayIndex(value, maxIndex) {
257
+ return /^0$|^[1-9]\d*$/.test(value) && Number(value) <= maxIndex;
258
+ }
259
+ function arrayToObject(array) {
260
+ const obj = new NullProtoObj();
261
+ array.forEach((item, i) => {
262
+ obj[i] = item;
263
+ });
264
+ return obj;
265
+ }
266
+ function pushStyleArrayToObject(array) {
267
+ const obj = new NullProtoObj();
268
+ obj[""] = array.length === 1 ? array[0] : array;
269
+ return obj;
270
+ }
271
+
272
+ async function decode(request, pathParams) {
273
+ return {
274
+ path: pathParams ?? {},
275
+ query: bracketNotationDeserialize(Array.from(request.url.searchParams.entries())),
276
+ headers: request.headers,
277
+ body: await request.body() ?? {}
278
+ };
279
+ }
280
+ function asyncSafeSerialize(data) {
281
+ if (isAsyncIteratorObject(data)) {
282
+ return mapEventIterator(data, {
283
+ value: async (value) => value,
284
+ error: async (e) => {
285
+ return new ErrorEvent({
286
+ data: encodeError(toApiError(e))["body"],
287
+ cause: e
288
+ });
289
+ }
290
+ });
291
+ }
292
+ return data;
293
+ }
294
+ function encode(output, procedure) {
295
+ const successStatus = fallbackContractConfig(
296
+ "defaultSuccessStatus",
297
+ procedure["~def"].endpoint.successStatus
298
+ );
299
+ const outputStructure = fallbackContractConfig(
300
+ "defaultOutputStructure",
301
+ procedure["~def"].endpoint.outputStructure
302
+ );
303
+ if (outputStructure === "compact") {
304
+ return {
305
+ status: successStatus,
306
+ headers: new Headers(),
307
+ body: asyncSafeSerialize(output)
308
+ };
309
+ }
310
+ if (!isDetailedOutput(output)) {
311
+ throw new Error(`
312
+ Invalid "detailed" output structure:
313
+ \u2022 Expected an object with optional properties:
314
+ - status (number 200-399)
315
+ - headers (Record<string, string | string[]>)
316
+ - body (any)
317
+ \u2022 No extra keys allowed.
318
+
319
+ Actual value:
320
+ ${stringifyJSON(output)}
321
+ `);
322
+ }
323
+ return {
324
+ status: output.status ?? successStatus,
325
+ headers: output.headers ?? new Headers(),
326
+ body: asyncSafeSerialize(output.body)
327
+ };
328
+ }
329
+ function isDetailedOutput(output) {
330
+ if (!isObject(output)) {
331
+ return false;
332
+ }
333
+ if (output.headers && !isObject(output.headers)) {
334
+ return false;
335
+ }
336
+ if (output.status !== void 0 && (typeof output.status !== "number" || !Number.isInteger(output.status) || isApiErrorStatus(output.status))) {
337
+ return false;
338
+ }
339
+ return true;
340
+ }
341
+
342
+ function resolveFriendlyStandardHandleOptions(options) {
343
+ return {
344
+ ...options,
345
+ context: options.context ?? {}
346
+ // Context only optional if all fields are optional
347
+ };
348
+ }
349
+ function toRou3Pattern(path) {
350
+ return standardizeHTTPPath(path).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
351
+ }
352
+ function decodeParams(params) {
353
+ return Object.fromEntries(
354
+ Object.entries(params).map(([key, value]) => [key, tryDecodeURIComponent(value)])
355
+ );
356
+ }
357
+
358
+ class StandardOpenAPIMatcher {
359
+ tree = createRouter();
360
+ constructor(resources) {
361
+ for (const resource of resources) {
362
+ if (isLazyResource(resource)) {
363
+ const { endpointRoutes } = resource;
364
+ for (const methodName in endpointRoutes) {
365
+ const endpoint = endpointRoutes[methodName];
366
+ const [method, path] = parseHTTPEndpoint(endpoint);
367
+ const httpPath = toRou3Pattern(path);
368
+ addRoute(this.tree, method, httpPath, { lazyResource: resource, methodName });
369
+ }
370
+ } else {
371
+ for (const route of Object.values(resource.endpoints)) {
372
+ const { endpoint } = route["~def"];
373
+ const method = endpoint.method;
374
+ const httpPath = toRou3Pattern(endpoint.path ?? "/");
375
+ addRoute(this.tree, method, httpPath, { procedure: route });
376
+ }
377
+ }
378
+ }
379
+ }
380
+ async match(method, pathname) {
381
+ const match = findRoute(this.tree, method, pathname);
382
+ if (!match) {
383
+ return void 0;
384
+ }
385
+ const params = match.params ? decodeParams(match.params) : void 0;
386
+ if ("lazyResource" in match.data) {
387
+ const { lazyResource, methodName } = match.data;
388
+ if (lazyResource.loaderCache === void 0) {
389
+ lazyResource.loaderCache = await lazyResource.loader();
390
+ validateLazyLoadedResource(lazyResource, lazyResource.loaderCache);
391
+ }
392
+ return { procedure: lazyResource.loaderCache.endpoints[methodName], params };
393
+ }
394
+ return { procedure: match.data.procedure, params };
395
+ }
396
+ }
397
+
398
+ function throwOrLog(error) {
399
+ if (process.env.NODE_ENV !== "production") {
400
+ throw error;
401
+ } else {
402
+ console.error(error);
403
+ }
404
+ }
405
+ class StandardHandler {
406
+ matcher;
407
+ constructor(resources) {
408
+ this.matcher = new StandardOpenAPIMatcher(resources);
409
+ }
410
+ async handle(request, options) {
411
+ const prefix = options.prefix?.replace(/\/$/, "") || void 0;
412
+ if (prefix && !request.url.pathname.startsWith(`${prefix}/`) && request.url.pathname !== prefix) {
413
+ return { matched: false, response: void 0 };
414
+ }
415
+ return runWithSpan({ name: `${request.method} ${request.url.pathname}` }, async (span) => {
416
+ let step;
417
+ let errorMap;
418
+ try {
419
+ const context = options.context;
420
+ const method = request.method;
421
+ const url = request.url;
422
+ const pathname = prefix ? url.pathname.replace(prefix, "") : url.pathname;
423
+ const match = await runWithSpan(
424
+ { name: "find_procedure" },
425
+ () => this.matcher.match(method, `/${pathname.replace(/^\/|\/$/g, "")}`)
426
+ );
427
+ if (!match) {
428
+ return { matched: false, response: void 0 };
429
+ }
430
+ errorMap = match.procedure["~def"].errorMap;
431
+ const endpointId = getEndpointId(match.procedure["~def"].endpoint);
432
+ span?.updateName(`${KRUSTY_NAME}.${endpointId}`);
433
+ span?.setAttribute("rpc.system", KRUSTY_NAME);
434
+ span?.setAttribute("rpc.method", endpointId);
435
+ step = "decode_input";
436
+ const input = await runWithSpan({ name: "decode_input" }, () => decode(request, match.params));
437
+ step = void 0;
438
+ if (isAsyncIteratorObject(input.body)) {
439
+ input.body = asyncIteratorWithSpan(
440
+ { name: "consume_event_iterator_input", signal: request.signal },
441
+ input.body
442
+ );
443
+ }
444
+ const client = createProcedureClient(match.procedure, {
445
+ context
446
+ });
447
+ step = "call_procedure";
448
+ const output = await client(input, {
449
+ request,
450
+ signal: request.signal,
451
+ lastEventId: request.headers.get("last-event-id") ?? void 0
452
+ });
453
+ step = void 0;
454
+ const response = encode(output, match.procedure);
455
+ return {
456
+ matched: true,
457
+ response
458
+ };
459
+ } catch (e) {
460
+ if (step !== "call_procedure") {
461
+ setSpanError(span, e);
462
+ }
463
+ const isApiError = e instanceof ApiError;
464
+ if (isApiError) {
465
+ if (!errorMap) {
466
+ throwOrLog(
467
+ new Error(`Got ApiError but errorMap is undefined. ApiError="{${e.message}"`, { cause: e })
468
+ );
469
+ } else if (!errorMap[e.constructor.name]) {
470
+ throwOrLog(
471
+ new Error(
472
+ `ApiError "${e.constructor.name}" (type "${e.constructor.type}") is not registered. Add it to your API with: baseApi.useErrors({ ${e.constructor.name} })`,
473
+ { cause: e }
474
+ )
475
+ );
476
+ }
477
+ }
478
+ const error = step === "decode_input" && !(e instanceof ApiError) ? new BadRequestError({
479
+ code: "malformed_request",
480
+ message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
481
+ cause: e
482
+ }) : toApiError$1(e);
483
+ if (error instanceof InternalServerError) {
484
+ console.error(error.cause ?? error);
485
+ }
486
+ const response = encodeError(error);
487
+ return {
488
+ matched: true,
489
+ response
490
+ };
491
+ }
492
+ });
493
+ }
494
+ }
495
+
496
+ export { StandardHandler as S, StandardOpenAPIMatcher as a, decodeParams as b, middlewareOutputFn as c, decode as d, encode as e, createProcedureClient as f, getEndpointId as g, call as h, mergeContext as m, resolveFriendlyStandardHandleOptions as r, toRou3Pattern as t };