@tahminator/sapling 2.0.5 → 2.1.0-beta.da115635

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/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import e, { Router } from "express";
2
+ import swagger from "swagger-ui-express";
2
3
  //#region src/html/404.ts
3
4
  /**
4
5
  * Default Express.js 404 error page, as a string.
@@ -22,6 +23,7 @@ const Html404ErrorPage = (error) => `<!DOCTYPE html>
22
23
  * You can either return `new RedirectView(url)` or `RedirectView.redirect(url)` inside of a controller method.
23
24
  */
24
25
  var RedirectView = class RedirectView {
26
+ _url;
25
27
  constructor(url) {
26
28
  this._url = url;
27
29
  }
@@ -117,8 +119,10 @@ let HttpStatus = /* @__PURE__ */ function(HttpStatus) {
117
119
  * @typeParam T - the type of the response body
118
120
  */
119
121
  var ResponseEntity = class {
122
+ _statusCode;
123
+ _headers = {};
124
+ _body;
120
125
  constructor(body, headers = {}, statusCode = 200) {
121
- this._headers = {};
122
126
  this._body = body;
123
127
  this._headers = headers;
124
128
  this._statusCode = statusCode;
@@ -171,8 +175,9 @@ var ResponseEntity = class {
171
175
  * ensuring type safety when constructing the response.
172
176
  */
173
177
  var ResponseEntityBuilder = class {
178
+ _statusCode;
179
+ _headers = {};
174
180
  constructor(statusCode) {
175
- this._headers = {};
176
181
  this._statusCode = statusCode;
177
182
  }
178
183
  /**
@@ -204,6 +209,7 @@ var ResponseEntityBuilder = class {
204
209
  * @see {@link Sapling.loadResponseStatusErrorMiddleware}
205
210
  */
206
211
  var ResponseStatusError = class ResponseStatusError extends Error {
212
+ status;
207
213
  constructor(status, message) {
208
214
  super(message ?? "Something went wrong.");
209
215
  this.status = status;
@@ -215,150 +221,30 @@ var ResponseStatusError = class ResponseStatusError extends Error {
215
221
  //#endregion
216
222
  //#region src/helper/error/parse.ts
217
223
  /**
218
- * This error should be thrown when some data cannot be parsed by a given schema.
224
+ * This error should be thrown when some data cannot be parsed by a given Standard Schema compatible schema.
219
225
  */
220
226
  var ParserError = class ParserError extends ResponseStatusError {
221
- constructor(location, issues, vendor) {
222
- super(400, ParserError.formatMessage(location, issues, vendor));
227
+ constructor(location, issues, vendor, functionName) {
228
+ super(400, ParserError.formatMessage(location, issues, vendor, functionName));
223
229
  Object.setPrototypeOf(this, new.target.prototype);
224
230
  }
225
- static formatMessage(location, issues, vendor) {
231
+ static formatMessage(location, issues, vendor, functionName) {
226
232
  const formatted = issues.map((i) => {
227
233
  const path = Array.isArray(i.path) ? i.path.map((seg) => typeof seg === "object" && seg ? String(seg.key) : String(seg)).join(".") : "";
228
234
  return path ? `${path}: ${i.message}` : i.message;
229
235
  }).join("; ");
230
- return `${vendor} failed to parse ${(() => {
231
- switch (location) {
232
- case "reqbody": return "request body";
233
- case "reqparams": return "request params";
234
- case "reqquery": return "request query";
235
- }
236
- })()}: ${formatted}`;
237
- }
238
- };
239
- //#endregion
240
- //#region src/helper/sapling.ts
241
- const settings = {
242
- serialize: JSON.stringify,
243
- deserialize: JSON.parse
244
- };
245
- /**
246
- * Collection of utility functions which are essential for Sapling to function.
247
- */
248
- var Sapling = class Sapling {
249
- /**
250
- * If you would prefer to manually resolve your controllers instead, call resolve
251
- * on the controller class.
252
- *
253
- * @example```ts
254
- * import { Sapling } from "@tahminator/sapling";
255
- * import TestController from "./path/to/test.controller";
256
- *
257
- * const app = express();
258
- *
259
- * const router = Sapling.resolve(TestController);
260
- * app.use(router);
261
- * ```
262
- */
263
- static resolve(clazz) {
264
- const router = _ControllerRegistry.get(clazz);
265
- if (!router) throw new Error("Controller cannot be found");
266
- return router;
267
- }
268
- /**
269
- * Register this function as a middleware in order to utilize Sapling's `deserialize` function.
270
- *
271
- * @example```ts
272
- * import { Sapling } from "@tahminator/sapling";
273
- * import express from "express";
274
- *
275
- * const app = express();
276
- *
277
- * app.use(Sapling.json());
278
- * ```
279
- */
280
- static json() {
281
- return (request, _response, next) => {
282
- try {
283
- if (!request.body) return next();
284
- if (request.headers["content-type"] !== "application/json") return next();
285
- if (typeof request.body === "string") request.body = Sapling.deserialize(request.body);
286
- else if (typeof request.body === "object") {
287
- const raw = JSON.stringify(request.body);
288
- request.body = Sapling.deserialize(raw);
289
- }
290
- next();
291
- } catch (err) {
292
- next(err);
293
- }
294
- };
236
+ return `Failed to parse ${this.getPrettyLocationString(location)} with ${vendor} on ${functionName}: ${formatted}`;
295
237
  }
296
- /**
297
- * Register your application with all the necessary middlewares and logics for Sapling to function.
298
- *
299
- * @example```ts
300
- * import { Sapling } from "@tahminator/sapling";
301
- * import express from "express";
302
- *
303
- * const app = express();
304
- *
305
- * app.registerApp(app);
306
- * ```
307
- */
308
- static registerApp(app) {
309
- app.use(e.text({ type: "application/json" }));
310
- app.use(Sapling.json());
311
- }
312
- /**
313
- * Serialize a value into a JSON string.
314
- *
315
- * This function is used in {@link ResponseEntity} to serialize the `body`.
316
- *
317
- * Use `setSerializeFn` to override underlying implementation.
318
- *
319
- * @defaultValue `JSON.stringify`
320
- */
321
- static serialize(value) {
322
- return settings.serialize(value);
323
- }
324
- /**
325
- * Replace the function used for `serialize`.
326
- */
327
- static setSerializeFn(fn) {
328
- settings.serialize = fn;
329
- }
330
- /**
331
- * De-serialize a JSON string back to a JavaScript object.
332
- *
333
- * This function is used to de-serialize a string into a `body`.
334
- *
335
- * Use `setDeserializeFn` to override underlying implementation.
336
- *
337
- * @defaultValue `JSON.parse`
338
- */
339
- static deserialize(value) {
340
- return settings.deserialize(value);
341
- }
342
- /**
343
- * Replace the function used for `deserialize`
344
- */
345
- static setDeserializeFn(fn) {
346
- settings.deserialize = fn;
238
+ static getPrettyLocationString(location) {
239
+ switch (location) {
240
+ case "reqbody": return "request body";
241
+ case "reqparams": return "request params";
242
+ case "reqquery": return "request query";
243
+ case "resbody": return "response body";
244
+ }
347
245
  }
348
246
  };
349
247
  //#endregion
350
- //#region src/types.ts
351
- const methodResolve = {
352
- GET: "get",
353
- PUT: "put",
354
- POST: "post",
355
- DELETE: "delete",
356
- OPTIONS: "options",
357
- PATCH: "patch",
358
- HEAD: "head",
359
- USE: "use"
360
- };
361
- //#endregion
362
248
  //#region lib/weakmap.ts
363
249
  /**
364
250
  * WeakMap that is iterable.
@@ -479,132 +365,243 @@ function _resolve(ctor) {
479
365
  return _InjectableRegistry.get(ctor);
480
366
  }
481
367
  //#endregion
482
- //#region src/annotation/request.ts
483
- const _requestSchemaStore = /* @__PURE__ */ new WeakMap();
484
- /**
485
- * Apply to a route method to have `request.body` be parsed by `schema`.
486
- *
487
- * This annotation will parse `request.body` & then override `request.body`.
488
- * You can then just simply cast `request.body` for your use
489
- *
490
- * @example
491
- * ```ts
492
- * const CREATE_BOOK_REQUEST_BODY_SCHEMA = z.object({
493
- * name: z.string(),
494
- * description: z.string().optional(),
495
- * });
496
- *
497
- * ⠀@Controller({ prefix: "/api/book" })
498
- * class BookController {
499
- * ⠀@RequestBody(CREATE_BOOK_REQUEST_BODY_SCHEMA)
500
- * ⠀@POST()
501
- * public createBook(request: e.Request) {
502
- * const { name, description } = request.body as unknown as z.infer<
503
- * typeof CREATE_BOOK_REQUEST_BODY_SCHEMA
504
- * >;
505
- * }
506
- * }
507
- * ```
508
- */
509
- function RequestBody(schema) {
510
- return (target, propertyKey) => {
511
- const ctor = target.constructor;
512
- const fnName = String(propertyKey);
513
- _setOnce(_getOrCreateRequestSchemaDefinition(ctor, fnName), "body", schema, fnName);
514
- };
515
- }
516
- /**
517
- * Apply to a route method to have `request.param` be parsed by `schema`.
518
- *
519
- * This annotation will parse `request.param` & then override `request.param`.
520
- * You can then just simply cast `request.param` for your use
521
- *
522
- * @example
523
- * ```ts
524
- * const GET_BOOK_REQUEST_PARAM_SCHEMA = z.object({
525
- * bookId: z.string(),
526
- * });
527
- *
528
- * ⠀@Controller({ prefix: "/api/book" })
529
- * class BookController {
530
- * ⠀@RequestParam(GET_BOOK_REQUEST_PARAM_SCHEMA)
531
- * ⠀@GET("/:bookId")
532
- * public getBook(request: e.Request) {
533
- * const { bookId } = request.param as unknown as z.infer<
534
- * typeof GET_BOOK_REQUEST_PARAM_SCHEMA
535
- * >;
536
- * }
537
- * }
538
- * ```
539
- */
540
- function RequestParam(schema) {
541
- return (target, propertyKey) => {
542
- const ctor = target.constructor;
543
- const fnName = String(propertyKey);
544
- _setOnce(_getOrCreateRequestSchemaDefinition(ctor, fnName), "param", schema, fnName);
545
- };
368
+ //#region \0@oxc-project+runtime@0.127.0/helpers/decorate.js
369
+ function __decorate(decorators, target, key, desc) {
370
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
371
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
372
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
373
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
546
374
  }
375
+ //#endregion
376
+ //#region src/middleware/health/registrar.ts
377
+ let HealthRegistrar = class HealthRegistrar {
378
+ _checks;
379
+ _sealed;
380
+ constructor() {
381
+ this._checks = [];
382
+ this._sealed = false;
383
+ }
384
+ add(healthCheck) {
385
+ this._checks.push(healthCheck);
386
+ }
387
+ seal() {
388
+ this._sealed = true;
389
+ }
390
+ async check() {
391
+ if (!this._sealed) return false;
392
+ return (await Promise.all(this._checks.map((c) => c()))).every((c) => c === true);
393
+ }
394
+ };
395
+ HealthRegistrar = __decorate([Injectable()], HealthRegistrar);
396
+ //#endregion
397
+ //#region src/helper/sapling.ts
398
+ const _settings = {
399
+ serialize: JSON.stringify,
400
+ deserialize: JSON.parse,
401
+ health: { path: "/up" },
402
+ doc: {
403
+ openApiPath: "/openapi.json",
404
+ swaggerPath: "/swagger.html",
405
+ metadata: {
406
+ title: "API",
407
+ version: "1.0.0"
408
+ }
409
+ }
410
+ };
547
411
  /**
548
- * Apply to a route method to have `request.query` be parsed by `schema`.
549
- *
550
- * This annotation will parse `request.query` & then override `request.query`.
551
- * You can then just simply cast `request.query` for your use
552
- *
553
- * @example
554
- * ```ts
555
- * const LIST_BOOKS_REQUEST_QUERY_SCHEMA = z.object({
556
- * sort: z.enum(["name", "createdAt"]).optional(),
557
- * q: z.string().optional(),
558
- * });
559
- *
560
- * ⠀@Controller({ prefix: "/api/book" })
561
- * class BookController {
562
- * ⠀@RequestQuery(LIST_BOOKS_REQUEST_QUERY_SCHEMA)
563
- * ⠀@GET()
564
- * public listBooks(request: e.Request) {
565
- * const { sort, q } = request.query as unknown as z.infer<
566
- * typeof LIST_BOOKS_REQUEST_QUERY_SCHEMA
567
- * >;
568
- * }
569
- * }
570
- * ```
412
+ * Collection of utility functions which are essential for Sapling to function.
571
413
  */
572
- function RequestQuery(schema) {
573
- return (target, propertyKey) => {
574
- const ctor = target.constructor;
575
- const fnName = String(propertyKey);
576
- _setOnce(_getOrCreateRequestSchemaDefinition(ctor, fnName), "query", schema, fnName);
577
- };
578
- }
579
- function _getOrCreateRequestSchemaDefinition(ctor, fnName) {
580
- const byFn = (() => {
581
- const fn = _requestSchemaStore.get(ctor);
582
- if (fn) return fn;
583
- const newFn = /* @__PURE__ */ new Map();
584
- _requestSchemaStore.set(ctor, newFn);
585
- return newFn;
586
- })();
587
- const existing = byFn.get(fnName);
588
- if (existing) return existing;
589
- const created = {};
590
- byFn.set(fnName, created);
591
- return created;
592
- }
593
- function _setOnce(def, key, schema, fnName) {
594
- if (def[key]) throw new Error(`Duplicate request schema for "${String(key)}" on method "${fnName}"`);
595
- def[key] = schema;
596
- }
597
- function _getRequestSchemas(ctor, fnName) {
598
- return _requestSchemaStore.get(ctor)?.get(fnName);
599
- }
600
- async function _parseOrThrow(schema, input, kind) {
601
- const result = await schema["~standard"].validate(input);
602
- if (result.issues) {
603
- console.debug(`Failed to parse a schema`);
604
- throw new ParserError(kind, result.issues, schema["~standard"].vendor);
414
+ var Sapling = class Sapling {
415
+ /**
416
+ * If you would prefer to manually resolve your controllers instead, call resolve
417
+ * on the controller class.
418
+ *
419
+ * @example```ts
420
+ * import { Sapling } from "@tahminator/sapling";
421
+ * import TestController from "./path/to/test.controller";
422
+ *
423
+ * const app = express();
424
+ *
425
+ * const router = Sapling.resolve(TestController);
426
+ * app.use(router);
427
+ * ```
428
+ */
429
+ static resolve(clazz) {
430
+ const router = _ControllerRegistry.get(clazz);
431
+ if (!router) throw new Error("Controller cannot be found");
432
+ return router;
605
433
  }
606
- return result.value;
607
- }
434
+ /**
435
+ * Register this function as a middleware in order to utilize Sapling's `deserialize` function.
436
+ *
437
+ * @example```ts
438
+ * import { Sapling } from "@tahminator/sapling";
439
+ * import express from "express";
440
+ *
441
+ * const app = express();
442
+ *
443
+ * app.use(Sapling.json());
444
+ * ```
445
+ */
446
+ static json() {
447
+ return (request, _response, next) => {
448
+ try {
449
+ if (!request.body) return next();
450
+ if (request.headers["content-type"] !== "application/json") return next();
451
+ if (typeof request.body === "string") request.body = Sapling.deserialize(request.body);
452
+ else if (typeof request.body === "object") {
453
+ const raw = JSON.stringify(request.body);
454
+ request.body = Sapling.deserialize(raw);
455
+ }
456
+ next();
457
+ } catch (err) {
458
+ next(err);
459
+ }
460
+ };
461
+ }
462
+ /**
463
+ * Register your application with all the necessary middlewares and logics for Sapling to function.
464
+ *
465
+ * @example```ts
466
+ * import { Sapling } from "@tahminator/sapling";
467
+ * import express from "express";
468
+ *
469
+ * const app = express();
470
+ *
471
+ * app.registerApp(app);
472
+ * ```
473
+ */
474
+ static registerApp(app) {
475
+ app.use(e.text({ type: "application/json" }));
476
+ app.use(Sapling.json());
477
+ return new Proxy(app, { get(target, prop, receiver) {
478
+ if (prop === "listen") {
479
+ const originalListen = target[prop];
480
+ return function(...args) {
481
+ const lastArg = args[args.length - 1];
482
+ let originalCallback;
483
+ if (typeof lastArg === "function") {
484
+ originalCallback = lastArg;
485
+ args.pop();
486
+ }
487
+ const server = originalListen.apply(target, args);
488
+ server.once("listening", function(...cbArgs) {
489
+ Sapling.onStartup();
490
+ console.log("Sapling successfully initialized post-startup hooks on server start");
491
+ if (originalCallback) originalCallback(...cbArgs);
492
+ });
493
+ return server;
494
+ };
495
+ }
496
+ return Reflect.get(target, prop, receiver);
497
+ } });
498
+ }
499
+ static onStartup() {
500
+ _InjectableRegistry.get(HealthRegistrar)?.seal();
501
+ }
502
+ /**
503
+ * Serialize a value into a JSON string.
504
+ *
505
+ * This function is used in {@link ResponseEntity} to serialize the `body`.
506
+ *
507
+ * Use `setSerializeFn` to override underlying implementation.
508
+ *
509
+ * @defaultValue `JSON.stringify`
510
+ */
511
+ static serialize(value) {
512
+ return _settings.serialize(value);
513
+ }
514
+ /**
515
+ * Replace the function used for `serialize`.
516
+ */
517
+ static setSerializeFn(fn) {
518
+ _settings.serialize = fn;
519
+ }
520
+ /**
521
+ * De-serialize a JSON string back to a JavaScript object.
522
+ *
523
+ * This function is used to de-serialize a string into a `body`.
524
+ *
525
+ * Use `setDeserializeFn` to override underlying implementation.
526
+ *
527
+ * @defaultValue `JSON.parse`
528
+ */
529
+ static deserialize(value) {
530
+ return _settings.deserialize(value);
531
+ }
532
+ /**
533
+ * Replace the function used for `deserialize`
534
+ */
535
+ static setDeserializeFn(fn) {
536
+ _settings.deserialize = fn;
537
+ }
538
+ /**
539
+ * Modify extra settings
540
+ */
541
+ static Extras = {
542
+ /**
543
+ * Modify default settings applied to OpenAPI & Swagger
544
+ */
545
+ swaggerAndOpenApi: {
546
+ /**
547
+ * Set base OpenAPI metadata values.
548
+ *
549
+ * @default { title: "API", version: "1.0.0" }
550
+ */
551
+ setMetadata(metadata) {
552
+ _settings.doc.metadata = metadata;
553
+ },
554
+ /**
555
+ * change default endpoint that will serve OpenAPI spec.
556
+ * Swagger will also load this endpoint on load.
557
+ *
558
+ * @default `/openapi.json`
559
+ */
560
+ setOpenApiPath(path) {
561
+ _settings.doc.openApiPath = path;
562
+ },
563
+ /**
564
+ * change Swagger endpoint.
565
+ *
566
+ * @default `/swagger.html`
567
+ */
568
+ setSwaggerPath(path) {
569
+ _settings.doc.swaggerPath = path;
570
+ }
571
+ } };
572
+ /**
573
+ * This method can be used in a `@MiddlewareClass` to register any libraries
574
+ * that expect you to register multiple registers at once. An example is `swagger-ui-express`
575
+ *
576
+ * @example
577
+ * ```ts
578
+ * ⠀@MiddlewareClass()
579
+ * class Serve {
580
+ * // `swagger.serve` returns multiple Express handlers for all the assets and routes
581
+ * // that will be served
582
+ * private readonly handlers: RequestHandler[] = swagger.serve;
583
+ *
584
+ * ⠀@Middleware(_settings.doc.swaggerPath)
585
+ * handle(request: Request, response: Response, next: NextFunction) {
586
+ * return Sapling.chainHandlers(this.handlers, request, response, next);
587
+ * }
588
+ * }
589
+ * ```
590
+ */
591
+ static chainHandlers(handlers, request, response, next, index = 0) {
592
+ if (index >= handlers.length) {
593
+ next();
594
+ return;
595
+ }
596
+ handlers[index]?.(request, response, (err) => {
597
+ if (err) {
598
+ next(err);
599
+ return;
600
+ }
601
+ Sapling.chainHandlers(handlers, request, response, next, index + 1);
602
+ });
603
+ }
604
+ };
608
605
  //#endregion
609
606
  //#region src/annotation/route.ts
610
607
  const _routeStore = /* @__PURE__ */ new WeakMap();
@@ -687,6 +684,245 @@ function _getRoutes(ctor) {
687
684
  return _routeStore.get(ctor) ?? [];
688
685
  }
689
686
  //#endregion
687
+ //#region src/annotation/schema.ts
688
+ function ControllerSchema(options) {
689
+ return (target) => {
690
+ _setControllerSchema(target, options);
691
+ };
692
+ }
693
+ function RouteSchema(options) {
694
+ return (target, propertyKey) => {
695
+ const ctor = target.constructor;
696
+ _setRouteSchema(ctor, String(propertyKey), options);
697
+ };
698
+ }
699
+ const _routeSchemaStore = /* @__PURE__ */ new WeakMap();
700
+ const _controllerSchemaStore = /* @__PURE__ */ new WeakMap();
701
+ function getOrCreateRouteSchemaStore(store, ctor) {
702
+ const existing = store.get(ctor);
703
+ if (existing) return existing;
704
+ const created = /* @__PURE__ */ new Map();
705
+ store.set(ctor, created);
706
+ return created;
707
+ }
708
+ function _setRouteSchema(ctor, fnName, options) {
709
+ getOrCreateRouteSchemaStore(_routeSchemaStore, ctor).set(fnName, options);
710
+ }
711
+ function _setControllerSchema(ctor, options) {
712
+ _controllerSchemaStore.set(ctor, options);
713
+ }
714
+ function _getRouteSchema(ctor, fnName) {
715
+ return _routeSchemaStore.get(ctor)?.get(fnName);
716
+ }
717
+ function _getControllerSchema(ctor) {
718
+ return _controllerSchemaStore.get(ctor);
719
+ }
720
+ //#endregion
721
+ //#region src/annotation/validator.ts
722
+ const _validatorSchemaStore = /* @__PURE__ */ new WeakMap();
723
+ function ResponseBody(schema) {
724
+ return (target, propertyKey) => {
725
+ const ctor = target.constructor;
726
+ const fnName = String(propertyKey);
727
+ _saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "responseBody", schema, fnName);
728
+ };
729
+ }
730
+ function RequestBody(schema) {
731
+ return (target, propertyKey) => {
732
+ const ctor = target.constructor;
733
+ const fnName = String(propertyKey);
734
+ _saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "requestBody", schema, fnName);
735
+ };
736
+ }
737
+ function RequestParam(schema) {
738
+ return (target, propertyKey) => {
739
+ const ctor = target.constructor;
740
+ const fnName = String(propertyKey);
741
+ _saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "requestParam", schema, fnName);
742
+ };
743
+ }
744
+ function RequestQuery(schema) {
745
+ return (target, propertyKey) => {
746
+ const ctor = target.constructor;
747
+ const fnName = String(propertyKey);
748
+ _saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "requestQuery", schema, fnName);
749
+ };
750
+ }
751
+ function getOrCreateValidatorSchemaStore(store, ctor) {
752
+ const existing = store.get(ctor);
753
+ if (existing) return existing;
754
+ const created = /* @__PURE__ */ new Map();
755
+ store.set(ctor, created);
756
+ return created;
757
+ }
758
+ function _getOrCreateSchemaDefinition(ctor, fnName) {
759
+ const byFn = getOrCreateValidatorSchemaStore(_validatorSchemaStore, ctor);
760
+ const existing = byFn.get(fnName);
761
+ if (existing) return existing;
762
+ const created = {};
763
+ byFn.set(fnName, created);
764
+ return created;
765
+ }
766
+ async function _parseOrThrow(schema, input, location, fnName) {
767
+ const result = await schema["~standard"].validate(input);
768
+ if (result.issues) throw new ParserError(location, result.issues, schema["~standard"].vendor, fnName);
769
+ return result.value;
770
+ }
771
+ function _saveValidatorSchema(def, key, schema, fnName) {
772
+ if (def[key]) throw new Error(`Duplicate schema for "${String(key)}" on method "${fnName}"`);
773
+ def[key] = schema;
774
+ }
775
+ function _getValidatorSchema(ctor, fnName) {
776
+ return _validatorSchemaStore.get(ctor)?.get(fnName);
777
+ }
778
+ //#endregion
779
+ //#region src/helper/openapi.ts
780
+ var OpenAPIGenerator = class {
781
+ OPENAPI_VERSION = "3.0.0";
782
+ controllers = /* @__PURE__ */ new Set();
783
+ registerController(controllerClass, prefix) {
784
+ this.controllers.add({
785
+ class: controllerClass,
786
+ prefix
787
+ });
788
+ }
789
+ /**
790
+ * visible for testing
791
+ */
792
+ _clearControllers() {
793
+ this.controllers.clear();
794
+ }
795
+ get metadata() {
796
+ return _settings.doc.metadata;
797
+ }
798
+ generateSpec() {
799
+ const metadata = this.metadata;
800
+ const paths = {};
801
+ const tags = [];
802
+ for (const { class: controllerClass, prefix } of this.controllers) {
803
+ const routes = _getRoutes(controllerClass);
804
+ const controllerSchema = _getControllerSchema(controllerClass);
805
+ if (controllerSchema?.title) tags.push({
806
+ name: controllerSchema.title,
807
+ description: controllerSchema.description
808
+ });
809
+ for (const route of routes) {
810
+ if (route.method === "USE") continue;
811
+ const schemas = _getValidatorSchema(controllerClass, route.fnName);
812
+ const routeSchema = _getRouteSchema(controllerClass, route.fnName);
813
+ if (route.path instanceof RegExp) throw new Error(`You have a route with a regex path of ${route.path.source}. This is not compatible with OpenAPI.`);
814
+ const openApiPath = (prefix + route.path).replace(/:([A-Za-z0-9_]+)/g, "{$1}");
815
+ if (!paths[openApiPath]) paths[openApiPath] = {};
816
+ const responses = {};
817
+ if (schemas?.responseBody) {
818
+ const responseSchema = this.toJsonSchema(schemas.responseBody, "output");
819
+ responses["200"] = {
820
+ description: responseSchema.description ?? "Successful response",
821
+ content: { "application/json": { schema: responseSchema } }
822
+ };
823
+ } else responses["200"] = { description: "Successful response" };
824
+ if (routeSchema?.responses) for (const resp of routeSchema.responses) {
825
+ const statusCode = String(resp.statusCode);
826
+ const existingResponse = responses[statusCode];
827
+ const existingSchema = existingResponse && "content" in existingResponse ? existingResponse.content?.["application/json"]?.schema : void 0;
828
+ const responseSchema = resp.schema ? this.toJsonSchema(resp.schema, "output") : statusCode === "200" ? existingSchema : void 0;
829
+ responses[statusCode] = {
830
+ ...existingResponse,
831
+ description: resp.description ?? responseSchema?.description ?? existingResponse?.description ?? `Response ${resp.statusCode}`,
832
+ ...responseSchema ? { content: { "application/json": { schema: responseSchema } } } : {}
833
+ };
834
+ }
835
+ const operation = {
836
+ responses,
837
+ summary: routeSchema?.summary,
838
+ description: routeSchema?.description,
839
+ tags: controllerSchema?.title ? [controllerSchema.title] : void 0
840
+ };
841
+ const parameters = [];
842
+ if (schemas?.requestParam) {
843
+ const paramSchema = this.toJsonSchema(schemas.requestParam, "input");
844
+ if (paramSchema.type === "object" && paramSchema.properties) for (const [name, schema] of Object.entries(paramSchema.properties)) {
845
+ const parameterSchema = schema;
846
+ parameters.push({
847
+ name,
848
+ in: "path",
849
+ required: true,
850
+ description: parameterSchema.description,
851
+ schema: parameterSchema
852
+ });
853
+ }
854
+ }
855
+ if (schemas?.requestQuery) {
856
+ const querySchema = this.toJsonSchema(schemas.requestQuery, "input");
857
+ if (querySchema.type === "object" && querySchema.properties) for (const [name, schema] of Object.entries(querySchema.properties)) {
858
+ const isRequired = Array.isArray(querySchema.required) && querySchema.required.includes(name);
859
+ const parameterSchema = schema;
860
+ parameters.push({
861
+ name,
862
+ in: "query",
863
+ required: isRequired,
864
+ description: parameterSchema.description,
865
+ schema: parameterSchema
866
+ });
867
+ }
868
+ }
869
+ if (parameters.length > 0) operation.parameters = parameters;
870
+ if (schemas?.requestBody) {
871
+ const requestSchema = this.toJsonSchema(schemas.requestBody, "input");
872
+ operation.requestBody = {
873
+ required: true,
874
+ description: requestSchema.description,
875
+ content: { "application/json": { schema: requestSchema } }
876
+ };
877
+ }
878
+ const method = route.method.toLowerCase();
879
+ paths[openApiPath][method] = operation;
880
+ }
881
+ }
882
+ return {
883
+ openapi: this.OPENAPI_VERSION,
884
+ info: {
885
+ title: metadata.title,
886
+ version: metadata.version,
887
+ description: metadata.description
888
+ },
889
+ tags: tags.length > 0 ? tags : void 0,
890
+ paths
891
+ };
892
+ }
893
+ toJsonSchema(schema, direction = "output") {
894
+ try {
895
+ const jsonSchema = schema["~standard"].jsonSchema;
896
+ return direction === "input" ? jsonSchema.input({ target: "openapi-3.0" }) : jsonSchema.output({ target: "openapi-3.0" });
897
+ } catch (e) {
898
+ if (e instanceof Error && e.message.includes("Transforms cannot be represented in JSON Schema")) throw new Error(`${e.message}.\nIt appears that you are using z.transform() - it is highly recommended that you use z.codec instead - https://zod.dev/codecs`, { cause: e });
899
+ throw e;
900
+ }
901
+ }
902
+ };
903
+ const openApiGenerator = new OpenAPIGenerator();
904
+ function _registerController(controllerClass, prefix) {
905
+ openApiGenerator.registerController(controllerClass, prefix);
906
+ }
907
+ function generateOpenApiSpec() {
908
+ return openApiGenerator.generateSpec();
909
+ }
910
+ function _clearOpenApiRegistry() {
911
+ openApiGenerator._clearControllers();
912
+ }
913
+ //#endregion
914
+ //#region src/types.ts
915
+ const methodResolve = {
916
+ GET: "get",
917
+ PUT: "put",
918
+ POST: "post",
919
+ DELETE: "delete",
920
+ OPTIONS: "options",
921
+ PATCH: "patch",
922
+ HEAD: "head",
923
+ USE: "use"
924
+ };
925
+ //#endregion
690
926
  //#region src/annotation/controller.ts
691
927
  const _ControllerRegistry = /* @__PURE__ */ new WeakMap();
692
928
  /**
@@ -698,6 +934,7 @@ const _ControllerRegistry = /* @__PURE__ */ new WeakMap();
698
934
  function Controller({ prefix = "", deps = [] } = {}) {
699
935
  return (target) => {
700
936
  const targetClass = target;
937
+ _registerController(target, prefix);
701
938
  const router = Router();
702
939
  const routes = _getRoutes(target);
703
940
  const usedRoutes = /* @__PURE__ */ new Set();
@@ -722,15 +959,20 @@ Split these into separate @MiddlewareClass classes, or merge the logic into a si
722
959
  if (method === "USE" && fn.length >= 4) {
723
960
  const middlewareFn = async (err, request, response, next) => {
724
961
  try {
725
- const result = fn.bind(controllerInstance)(err, request, response, next);
726
- if (result instanceof ResponseEntity) {
727
- response.contentType("application/json").status(result.getStatusCode()).set(result.getHeaders()).send(Sapling.serialize(result.getBody()));
728
- return;
729
- }
730
- if (result instanceof RedirectView) {
731
- response.redirect(result.getUrl());
732
- return;
733
- }
962
+ await validate({
963
+ target,
964
+ fnName,
965
+ request
966
+ });
967
+ await handleResult({
968
+ result: fn.bind(controllerInstance)(err, request, response, next),
969
+ response,
970
+ target,
971
+ fnName,
972
+ method,
973
+ path: path instanceof RegExp ? path.source : fp,
974
+ isErrorMiddleware: true
975
+ });
734
976
  } catch (e) {
735
977
  console.error(e);
736
978
  next(e);
@@ -740,34 +982,52 @@ Split these into separate @MiddlewareClass classes, or merge the logic into a si
740
982
  return;
741
983
  }
742
984
  router[methodName](fp, async (request, response, next) => {
743
- const schemas = _getRequestSchemas(target, fnName);
744
- if (schemas) {
745
- if (schemas.body) request.body = await _parseOrThrow(schemas.body, request.body, "reqbody");
746
- if (schemas.param) request.params = await _parseOrThrow(schemas.param, request.params, "reqparams");
747
- if (schemas.query) {
748
- const parsedQuery = await _parseOrThrow(schemas.query, request.query, "reqquery");
749
- Object.defineProperty(request, "query", {
750
- value: parsedQuery,
751
- writable: true,
752
- configurable: true
753
- });
754
- }
755
- }
756
- const result = await fn.bind(controllerInstance)(request, response, next);
757
- if (result instanceof ResponseEntity) {
758
- response.contentType("application/json").status(result.getStatusCode()).set(result.getHeaders()).send(Sapling.serialize(result.getBody()));
759
- return;
760
- }
761
- if (result instanceof RedirectView) {
762
- response.redirect(result.getUrl());
763
- return;
764
- }
765
- if (method !== "USE" && !response.writableEnded) response.status(404).send(Html404ErrorPage(`Cannot ${methodName.toUpperCase()} ${path instanceof RegExp ? path.source : fp}`));
985
+ await validate({
986
+ target,
987
+ fnName,
988
+ request
989
+ });
990
+ await handleResult({
991
+ result: await fn.bind(controllerInstance)(request, response, next),
992
+ response,
993
+ target,
994
+ fnName,
995
+ method,
996
+ path: path instanceof RegExp ? path.source : fp
997
+ });
766
998
  });
767
999
  }
768
1000
  _ControllerRegistry.set(targetClass, router);
769
1001
  };
770
1002
  }
1003
+ async function handleResult({ result, target, fnName, response, method, path, isErrorMiddleware = false }) {
1004
+ const schemas = _getValidatorSchema(target, fnName);
1005
+ if (result instanceof ResponseEntity) {
1006
+ const body = schemas && schemas.responseBody ? await _parseOrThrow(schemas.responseBody, result.getBody(), "resbody", fnName) : result.getBody();
1007
+ response.contentType("application/json").status(result.getStatusCode()).set(result.getHeaders()).send(Sapling.serialize(body));
1008
+ return;
1009
+ }
1010
+ if (result instanceof RedirectView) {
1011
+ response.redirect(result.getUrl());
1012
+ return;
1013
+ }
1014
+ if (!isErrorMiddleware && method !== "USE" && !response.writableEnded) response.status(404).send(Html404ErrorPage(`Cannot ${method} ${path}`));
1015
+ }
1016
+ async function validate({ target, fnName, request }) {
1017
+ const schemas = _getValidatorSchema(target, fnName);
1018
+ if (schemas) {
1019
+ if (schemas.requestBody) request.body = await _parseOrThrow(schemas.requestBody, request.body, "reqbody", fnName);
1020
+ if (schemas.requestParam) request.params = await _parseOrThrow(schemas.requestParam, request.params, "reqparams", fnName);
1021
+ if (schemas.requestQuery) {
1022
+ const parsedQuery = await _parseOrThrow(schemas.requestQuery, request.query, "reqquery", fnName);
1023
+ Object.defineProperty(request, "query", {
1024
+ value: parsedQuery,
1025
+ writable: true,
1026
+ configurable: true
1027
+ });
1028
+ }
1029
+ }
1030
+ }
771
1031
  //#endregion
772
1032
  //#region src/annotation/middleware.ts
773
1033
  /**
@@ -781,15 +1041,7 @@ function MiddlewareClass(...args) {
781
1041
  return Controller(...args);
782
1042
  }
783
1043
  //#endregion
784
- //#region \0@oxc-project+runtime@0.127.0/helpers/decorate.js
785
- function __decorate(decorators, target, key, desc) {
786
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
787
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
788
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
789
- return c > 3 && r && Object.defineProperty(target, key, r), r;
790
- }
791
- //#endregion
792
- //#region src/middleware/default/base.ts
1044
+ //#region src/middleware/default/error/base.ts
793
1045
  let DefaultBaseErrorMiddleware = class DefaultBaseErrorMiddleware {
794
1046
  handle(err, _request, _response, _next) {
795
1047
  console.error("[Error]", err);
@@ -799,7 +1051,20 @@ let DefaultBaseErrorMiddleware = class DefaultBaseErrorMiddleware {
799
1051
  __decorate([Middleware()], DefaultBaseErrorMiddleware.prototype, "handle", null);
800
1052
  DefaultBaseErrorMiddleware = __decorate([MiddlewareClass()], DefaultBaseErrorMiddleware);
801
1053
  //#endregion
802
- //#region src/middleware/default/responsestatus.ts
1054
+ //#region src/middleware/default/error/parse.ts
1055
+ let DefaultParserErrorMiddleware = class DefaultParserErrorMiddleware {
1056
+ handle(err, _request, _response, next) {
1057
+ if (err instanceof ParserError) {
1058
+ console.warn(err);
1059
+ return ResponseEntity.status(err.status).body({ message: err.message });
1060
+ }
1061
+ next(err);
1062
+ }
1063
+ };
1064
+ __decorate([Middleware()], DefaultParserErrorMiddleware.prototype, "handle", null);
1065
+ DefaultParserErrorMiddleware = __decorate([MiddlewareClass()], DefaultParserErrorMiddleware);
1066
+ //#endregion
1067
+ //#region src/middleware/default/error/responsestatus.ts
803
1068
  let DefaultResponseStatusErrorMiddleware = class DefaultResponseStatusErrorMiddleware {
804
1069
  handle(err, _request, _response, next) {
805
1070
  if (err instanceof ResponseStatusError) return ResponseEntity.status(err.status).body({ message: err.message });
@@ -809,4 +1074,99 @@ let DefaultResponseStatusErrorMiddleware = class DefaultResponseStatusErrorMiddl
809
1074
  __decorate([Middleware()], DefaultResponseStatusErrorMiddleware.prototype, "handle", null);
810
1075
  DefaultResponseStatusErrorMiddleware = __decorate([MiddlewareClass()], DefaultResponseStatusErrorMiddleware);
811
1076
  //#endregion
812
- export { Controller, DELETE, DefaultBaseErrorMiddleware, DefaultResponseStatusErrorMiddleware, GET, HEAD, Html404ErrorPage, HttpStatus, Injectable, Middleware, MiddlewareClass, OPTIONS, PATCH, POST, PUT, ParserError, RedirectView, RequestBody, RequestParam, RequestQuery, ResponseEntity, ResponseEntityBuilder, ResponseStatusError, Sapling, _ControllerRegistry, _InjectableDeps, _InjectableRegistry, _Route, _getRequestSchemas, _getRoutes, _parseOrThrow, _resolve, methodResolve };
1077
+ //#region src/middleware/default/openapi/index.ts
1078
+ let DefaultOpenApiMiddleware = class DefaultOpenApiMiddleware {
1079
+ handle(_request, _response, _next) {
1080
+ return ResponseEntity.ok().body(generateOpenApiSpec());
1081
+ }
1082
+ };
1083
+ __decorate([GET(_settings.doc.openApiPath)], DefaultOpenApiMiddleware.prototype, "handle", null);
1084
+ DefaultOpenApiMiddleware = __decorate([MiddlewareClass()], DefaultOpenApiMiddleware);
1085
+ //#endregion
1086
+ //#region src/middleware/default/swagger/index.ts
1087
+ /**
1088
+ * Enable the serving of the Swagger endpoint used to serve the OpenAPI spec generated by Sapling.
1089
+ *
1090
+ * Configure any middleware-specific settings with `Sapling.Extras.swaggerAndOpenApi`
1091
+ *
1092
+ * You must register `DefaultSwaggerMiddleware.Serve` & `DefaultSwaggerMiddleware.Setup` after `DefaultOpenApiMiddleware`
1093
+ *
1094
+ * ```ts
1095
+ * const middlewares = [
1096
+ * DefaultOpenApiMiddleware,
1097
+ * DefaultSwaggerMiddleware.Serve,
1098
+ * DefaultSwaggerMiddleware.Setup,
1099
+ * ];
1100
+ * middlewares.map(Sapling.resolve).forEach((r) => app.use(r));
1101
+ * ```
1102
+ */
1103
+ let Serve = class Serve {
1104
+ handlers = swagger.serve;
1105
+ handle(request, response, next) {
1106
+ return Sapling.chainHandlers(this.handlers, request, response, next);
1107
+ }
1108
+ };
1109
+ __decorate([Middleware(_settings.doc.swaggerPath)], Serve.prototype, "handle", null);
1110
+ Serve = __decorate([MiddlewareClass()], Serve);
1111
+ /**
1112
+ * Enable the serving of the Swagger endpoint used to serve the OpenAPI spec generated by Sapling.
1113
+ *
1114
+ * Configure any middleware-specific settings with `Sapling.Extras.swaggerAndOpenApi`
1115
+ *
1116
+ * You must register `DefaultSwaggerMiddleware.Serve` & `DefaultSwaggerMiddleware.Setup` after `DefaultOpenApiMiddleware`
1117
+ *
1118
+ * ```ts
1119
+ * const middlewares = [
1120
+ * DefaultOpenApiMiddleware,
1121
+ * DefaultSwaggerMiddleware.Serve,
1122
+ * DefaultSwaggerMiddleware.Setup,
1123
+ * ];
1124
+ * middlewares.map(Sapling.resolve).forEach((r) => app.use(r));
1125
+ * ```
1126
+ */
1127
+ let Setup = class Setup {
1128
+ handler;
1129
+ constructor() {
1130
+ this.handler = swagger.setup(null, { swaggerOptions: { url: _settings.doc.openApiPath } });
1131
+ }
1132
+ handle(request, response, next) {
1133
+ return this.handler(request, response, next);
1134
+ }
1135
+ };
1136
+ __decorate([Middleware(_settings.doc.swaggerPath)], Setup.prototype, "handle", null);
1137
+ Setup = __decorate([MiddlewareClass()], Setup);
1138
+ /**
1139
+ * Enable the serving of the Swagger endpoint used to serve the OpenAPI spec generated by Sapling.
1140
+ *
1141
+ * Configure any middleware-specific settings with `Sapling.Extras.swaggerAndOpenApi`
1142
+ *
1143
+ * You must register `DefaultSwaggerMiddleware.Serve` & `DefaultSwaggerMiddleware.Setup` after `DefaultOpenApiMiddleware`
1144
+ *
1145
+ * ```ts
1146
+ * const middlewares = [
1147
+ * DefaultOpenApiMiddleware,
1148
+ * DefaultSwaggerMiddleware.Serve,
1149
+ * DefaultSwaggerMiddleware.Setup,
1150
+ * ];
1151
+ * middlewares.map(Sapling.resolve).forEach((r) => app.use(r));
1152
+ * ```
1153
+ */
1154
+ const DefaultSwaggerMiddleware = {
1155
+ Serve,
1156
+ Setup
1157
+ };
1158
+ //#endregion
1159
+ //#region src/middleware/default/health/index.ts
1160
+ let DefaultHealthMiddleware = class DefaultHealthMiddleware {
1161
+ constructor(healthRegistrar) {
1162
+ this.healthRegistrar = healthRegistrar;
1163
+ }
1164
+ async serve(_request, _response, _next) {
1165
+ const up = await this.healthRegistrar.check();
1166
+ return ResponseEntity.ok().body({ up });
1167
+ }
1168
+ };
1169
+ __decorate([GET(_settings.health.path)], DefaultHealthMiddleware.prototype, "serve", null);
1170
+ DefaultHealthMiddleware = __decorate([MiddlewareClass({ deps: [HealthRegistrar] })], DefaultHealthMiddleware);
1171
+ //#endregion
1172
+ export { Controller, ControllerSchema, DELETE, DefaultBaseErrorMiddleware, DefaultHealthMiddleware, DefaultOpenApiMiddleware, DefaultParserErrorMiddleware, DefaultResponseStatusErrorMiddleware, DefaultSwaggerMiddleware, GET, HEAD, HealthRegistrar, Html404ErrorPage, HttpStatus, Injectable, Middleware, MiddlewareClass, OPTIONS, PATCH, POST, PUT, ParserError, RedirectView, RequestBody, RequestParam, RequestQuery, ResponseBody, ResponseEntity, ResponseEntityBuilder, ResponseStatusError, RouteSchema, Sapling, _ControllerRegistry, _InjectableDeps, _InjectableRegistry, _Route, _clearOpenApiRegistry, _getControllerSchema, _getOrCreateSchemaDefinition, _getRouteSchema, _getRoutes, _getValidatorSchema, _parseOrThrow, _registerController, _resolve, _saveValidatorSchema, _setControllerSchema, _setRouteSchema, _settings, generateOpenApiSpec, methodResolve, openApiGenerator };