raiton 3.1.1 → 5.4.0-beta.2

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 (120) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +38 -3
  3. package/build/bin/index.mjs +822 -524
  4. package/examples/user-controller.example.ts +53 -0
  5. package/package.json +8 -10
  6. package/scripts/update-version.ts +1 -1
  7. package/source/bin/bootstrapper.ts +1 -1
  8. package/source/bin/cli-tools.ts +2 -0
  9. package/source/commands/build.command.ts +2 -1
  10. package/source/commands/develop.command.ts +2 -1
  11. package/source/commands/start.command.ts +15 -10
  12. package/source/core/application.ts +42 -33
  13. package/source/core/artifacts/artifact.ts +10 -0
  14. package/source/core/artifacts/index.ts +1 -0
  15. package/source/core/artifacts/runner.ts +3 -0
  16. package/source/core/builder.ts +44 -15
  17. package/source/core/config/define.ts +1 -1
  18. package/source/core/controller/builder.ts +1 -1
  19. package/source/core/controller/metadata.ts +1 -1
  20. package/source/core/hooks.ts +0 -8
  21. package/source/core/index.ts +15 -14
  22. package/source/core/injection/injection.ts +9 -6
  23. package/source/core/middleware/compose.ts +1 -1
  24. package/source/core/middleware/pipeline.ts +2 -8
  25. package/source/core/plugins/scope.ts +18 -6
  26. package/source/core/router/handler.ts +26 -80
  27. package/source/core/router/handler.utils.ts +135 -0
  28. package/source/core/router/matcher.ts +13 -9
  29. package/source/core/router/router.ts +6 -2
  30. package/source/core/socket/index.ts +1 -0
  31. package/source/core/socket/metadata.ts +13 -0
  32. package/source/core/thread.ts +23 -20
  33. package/source/{sdk → framework}/artifacts.ts +8 -1
  34. package/source/framework/constants/decorators.constant.ts +17 -0
  35. package/source/framework/decorators/api-response.decorator.ts +127 -0
  36. package/source/framework/decorators/api.decorator.ts +185 -0
  37. package/source/framework/decorators/index.ts +9 -0
  38. package/source/{sdk/decorators/parametrable.ts → framework/decorators/parametrable.decorator.ts} +1 -1
  39. package/source/framework/decorators/socket.decorator.ts +41 -0
  40. package/source/{sdk → framework}/encryption.ts +2 -1
  41. package/source/{sdk → framework}/enums/encrypted.enum.ts +2 -2
  42. package/source/{sdk → framework}/enums/http-parameters.enum.ts +1 -0
  43. package/source/{sdk → framework}/enums/runtime.enum.ts +2 -2
  44. package/source/{sdk → framework}/env.ts +2 -2
  45. package/source/{sdk → framework}/exceptions/http-exception.ts +1 -1
  46. package/source/{sdk → framework}/index.ts +3 -2
  47. package/source/{sdk → framework}/plugins/body-parser.plugin.ts +28 -11
  48. package/source/framework/plugins/index.ts +3 -0
  49. package/source/framework/plugins/openapi.plugin.ts +98 -0
  50. package/source/framework/plugins/security/cors.ts +78 -0
  51. package/source/{sdk → framework}/responses/helpers.ts +4 -3
  52. package/source/{sdk → framework}/responses/http-throwable.ts +2 -2
  53. package/source/{sdk → framework}/responses/http.ts +3 -3
  54. package/source/{sdk → framework}/runtime/bun/server.ts +6 -2
  55. package/source/framework/runtime/deno/server.ts +104 -0
  56. package/source/{sdk → framework}/runtime/index.ts +18 -13
  57. package/source/framework/runtime/node/reply.ts +37 -0
  58. package/source/framework/runtime/node/request.ts +47 -0
  59. package/source/framework/runtime/node/server.ts +32 -0
  60. package/source/framework/runtime/web/server.ts +73 -0
  61. package/source/{sdk → framework}/utilities/artifact.util.ts +3 -0
  62. package/source/framework/utilities/cookie.util.ts +11 -0
  63. package/source/{sdk → framework}/utilities/index.ts +3 -1
  64. package/source/framework/utilities/openapi.utils.ts +497 -0
  65. package/source/framework/view-model.ts +4 -0
  66. package/source/types/access-guards.ts +4 -0
  67. package/source/types/application.ts +1 -1
  68. package/source/types/artifact.ts +42 -1
  69. package/source/types/builder.ts +6 -1
  70. package/source/types/controller.ts +1 -1
  71. package/source/types/http-responses.ts +8 -0
  72. package/source/types/index.ts +1 -0
  73. package/source/types/responses.ts +1 -1
  74. package/source/types/router.ts +1 -1
  75. package/source/types/runtime.ts +5 -3
  76. package/source/types/scheme.ts +153 -0
  77. package/source/types/socket.ts +15 -0
  78. package/source/types/thread.ts +4 -2
  79. package/source/sdk/constants/decorators.constant.ts +0 -8
  80. package/source/sdk/decorators/index.ts +0 -6
  81. package/source/sdk/plugins/index.ts +0 -2
  82. package/source/sdk/plugins/security/cors.ts +0 -44
  83. package/source/sdk/runtime/deno/server.ts +0 -53
  84. package/source/sdk/runtime/node/reply.ts +0 -0
  85. package/source/sdk/runtime/node/request.ts +0 -0
  86. package/source/sdk/runtime/node/server.ts +0 -60
  87. package/source/sdk/runtime/web/server.ts +0 -57
  88. /package/source/{sdk → framework}/constants/index.ts +0 -0
  89. /package/source/{sdk → framework}/constants/microservices.constant.ts +0 -0
  90. /package/source/{sdk → framework}/controllers.ts +0 -0
  91. /package/source/{sdk → framework}/data-transfer-object.ts +0 -0
  92. /package/source/{sdk → framework}/decorators/access-guard.decorator.ts +0 -0
  93. /package/source/{sdk → framework}/decorators/controllable.decorator.ts +0 -0
  94. /package/source/{sdk → framework}/decorators/guard.decorator.ts +0 -0
  95. /package/source/{sdk → framework}/decorators/injection.decorator.ts +0 -0
  96. /package/source/{sdk → framework}/decorators/middleware.decorator.ts +0 -0
  97. /package/source/{sdk → framework}/decorators/routable.decorator.ts +0 -0
  98. /package/source/{sdk → framework}/enums/event.message.enum.ts +0 -0
  99. /package/source/{sdk → framework}/enums/http-method.enum.ts +0 -0
  100. /package/source/{sdk → framework}/enums/http-status.enum.ts +0 -0
  101. /package/source/{sdk → framework}/enums/index.ts +0 -0
  102. /package/source/{sdk → framework}/enums/timestamp.enum.ts +0 -0
  103. /package/source/{sdk → framework}/exceptions/index.ts +0 -0
  104. /package/source/{sdk → framework}/exceptions/throwable.ts +0 -0
  105. /package/source/{sdk → framework}/parameter-bag.ts +0 -0
  106. /package/source/{sdk → framework}/plugins/security/body-limit.ts +0 -0
  107. /package/source/{sdk → framework}/plugins/security/headers.ts +0 -0
  108. /package/source/{sdk → framework}/plugins/security/index.ts +0 -0
  109. /package/source/{sdk → framework}/plugins/security/method-guard.ts +0 -0
  110. /package/source/{sdk → framework}/plugins/security/rate-limit.ts +0 -0
  111. /package/source/{sdk → framework}/repositories.ts +0 -0
  112. /package/source/{sdk → framework}/responses/error.ts +0 -0
  113. /package/source/{sdk → framework}/responses/index.ts +0 -0
  114. /package/source/{sdk → framework}/services.ts +0 -0
  115. /package/source/{sdk → framework}/utilities/alias-path.util.ts +0 -0
  116. /package/source/{sdk → framework}/utilities/callable.util.ts +0 -0
  117. /package/source/{sdk → framework}/utilities/json.util.ts +0 -0
  118. /package/source/{sdk → framework}/utilities/path.util.ts +0 -0
  119. /package/source/{sdk → framework}/utilities/url.ts +0 -0
  120. /package/source/{sdk → framework}/utilities/utilities.util.ts +0 -0
@@ -0,0 +1,185 @@
1
+ import "reflect-metadata";
2
+ import {METADATA_KEYS} from "../constants/decorators.constant";
3
+
4
+ /**
5
+ * Tag metadata for OpenAPI grouping
6
+ */
7
+ export interface ApiTagOptions {
8
+ /**
9
+ * Tag name
10
+ */
11
+ name: string;
12
+
13
+ /**
14
+ * Tag description (optional)
15
+ */
16
+ description?: string;
17
+
18
+ /**
19
+ * External documentation URL (optional)
20
+ */
21
+ externalDocs?: {
22
+ description?: string;
23
+ url: string;
24
+ };
25
+ }
26
+
27
+ /**
28
+ * Decorator to add API tags to a controller or method
29
+ * @param tags Tag(s) to apply
30
+ */
31
+ export function ApiTags(...tags: (string | ApiTagOptions)[]) {
32
+ return function (target: any, propertyKey?: string | symbol) {
33
+ const tagsMetadata = Reflect.getMetadata(METADATA_KEYS.API_TAGS, target) || [];
34
+
35
+ // Convert string tags to objects
36
+ const processedTags = tags.map(tag =>
37
+ typeof tag === 'string' ? { name: tag } : tag
38
+ );
39
+
40
+ if (propertyKey) {
41
+ // Method-level decorator
42
+ const methodTags = Reflect.getMetadata(METADATA_KEYS.API_TAGS, target, propertyKey) || [];
43
+ Reflect.defineMetadata(METADATA_KEYS.API_TAGS, [...methodTags, ...processedTags], target, propertyKey);
44
+ } else {
45
+ // Class-level decorator
46
+ Reflect.defineMetadata(METADATA_KEYS.API_TAGS, [...tagsMetadata, ...processedTags], target);
47
+ }
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Operation metadata for OpenAPI
53
+ */
54
+ export interface ApiOperationOptions {
55
+ /**
56
+ * Operation summary
57
+ */
58
+ summary?: string;
59
+
60
+ /**
61
+ * Operation description
62
+ */
63
+ description?: string;
64
+
65
+ /**
66
+ * Operation ID (unique identifier)
67
+ */
68
+ operationId?: string;
69
+
70
+ /**
71
+ * Whether the operation is deprecated
72
+ */
73
+ deprecated?: boolean;
74
+
75
+ /**
76
+ * External documentation
77
+ */
78
+ externalDocs?: {
79
+ description?: string;
80
+ url: string;
81
+ };
82
+ }
83
+
84
+ /**
85
+ * Decorator to add operation metadata to a method
86
+ * @param options Operation options
87
+ */
88
+ export function ApiOperation(options: ApiOperationOptions = {}) {
89
+ return function (target: any, propertyKey: string | symbol) {
90
+ const existing = Reflect.getMetadata(METADATA_KEYS.API_OPERATION, target, propertyKey) || {};
91
+ Reflect.defineMetadata(METADATA_KEYS.API_OPERATION, {...existing, ...options}, target, propertyKey);
92
+ };
93
+ }
94
+
95
+ /**
96
+ * Security requirements for OpenAPI
97
+ */
98
+ export interface ApiSecurityOptions {
99
+ /**
100
+ * Security scheme name
101
+ */
102
+ [key: string]: string[] | undefined;
103
+ }
104
+
105
+ /**
106
+ * Decorator to add security requirements to a controller or method
107
+ * @param security Security requirements (scheme name -> scopes[])
108
+ */
109
+ export function ApiSecurity(...security: ApiSecurityOptions[]) {
110
+ return function (target: any, propertyKey?: string | symbol) {
111
+ const securities = Reflect.getMetadata(METADATA_KEYS.API_SECURITY, target) || [];
112
+
113
+ if (propertyKey) {
114
+ // Method-level decorator
115
+ const methodSecurities = Reflect.getMetadata(METADATA_KEYS.API_SECURITY, target, propertyKey) || [];
116
+ Reflect.defineMetadata(METADATA_KEYS.API_SECURITY, [...methodSecurities, ...security], target, propertyKey);
117
+ } else {
118
+ // Class-level decorator
119
+ Reflect.defineMetadata(METADATA_KEYS.API_SECURITY, [...securities, ...security], target);
120
+ }
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Decorator to define request body for a method (alternative to using type detection)
126
+ * @param type The type/schema of the request body
127
+ * @param description Description of the request body (optional)
128
+ * @param required Whether the request body is required (default: true)
129
+ */
130
+ export function ApiBody(type: any, description?: string, required: boolean = true) {
131
+ return function (target: any, propertyKey: string | symbol) {
132
+ Reflect.defineMetadata(METADATA_KEYS.API_REQUEST_BODY, {
133
+ type,
134
+ description,
135
+ required
136
+ }, target, propertyKey);
137
+ };
138
+ }
139
+
140
+ /**
141
+ * Decorator to add additional parameters (complements Parametrable decorators)
142
+ * @param name Parameter name
143
+ * @param options Parameter options
144
+ */
145
+ export function ApiParam(name: string, options: {
146
+ /**
147
+ * Parameter location (path, query, header, cookie)
148
+ */
149
+ in: 'path' | 'query' | 'header' | 'cookie';
150
+
151
+ /**
152
+ * Parameter description
153
+ */
154
+ description?: string;
155
+
156
+ /**
157
+ * Whether the parameter is required
158
+ */
159
+ required?: boolean;
160
+
161
+ /**
162
+ * Parameter type (for schema generation)
163
+ */
164
+ type?: any;
165
+
166
+ /**
167
+ * Default value (optional)
168
+ */
169
+ default?: any;
170
+
171
+ /**
172
+ * Whether this parameter should be excluded from documentation (deprecated)
173
+ * @deprecated
174
+ */
175
+ deprecated?: boolean;
176
+ }) {
177
+ return function (target: any, propertyKey: string | symbol) {
178
+ const params = Reflect.getMetadata(METADATA_KEYS.API_PARAMETERS, target) || {};
179
+ if (!params[propertyKey]) {
180
+ params[propertyKey] = [];
181
+ }
182
+ params[propertyKey].push({name, ...options});
183
+ Reflect.defineMetadata(METADATA_KEYS.API_PARAMETERS, params, target, propertyKey);
184
+ };
185
+ }
@@ -0,0 +1,9 @@
1
+ export * from "./controllable.decorator"
2
+ export * from "./socket.decorator"
3
+ export * from "./middleware.decorator"
4
+ export * from "./routable.decorator"
5
+ export * from "./parametrable.decorator"
6
+ export * from "./injection.decorator"
7
+ export * from "./guard.decorator"
8
+ export * from "./api-response.decorator"
9
+ export * from "./api.decorator"
@@ -23,6 +23,6 @@ export const Param = createRouteParametrableDecorator(Parametrable.PARAM)
23
23
  export const Body = createRouteParametrableDecorator(Parametrable.BODY)
24
24
  export const UploadedFile = createRouteParametrableDecorator(Parametrable.UPLOAD_FILE)
25
25
  export const Headers = createRouteParametrableDecorator(Parametrable.HEADER)
26
+ export const Cookie = createRouteParametrableDecorator(Parametrable.COOKIE);
26
27
  export const Req = createRouteParametrableDecorator(Parametrable.REQ)
27
28
  export const Reply = createRouteParametrableDecorator(Parametrable.REPLY)
28
-
@@ -0,0 +1,41 @@
1
+ import {getSocketMetadata} from "../../core/socket";
2
+ import {Injectable} from "..";
3
+ import {LifetimeEnum} from "@protorians/core";
4
+ import {SocketEventType} from "../../types";
5
+
6
+ export function Socket(namespace = '/') {
7
+ return (target: any) => {
8
+ const name = target.name;
9
+ Injectable(LifetimeEnum.TRANSIENT, name)(target)
10
+
11
+ const meta = getSocketMetadata(target.prototype || target)
12
+ meta.namespace = namespace;
13
+ }
14
+ }
15
+
16
+ function createSocketEventDecorator(type: SocketEventType, name?: string) {
17
+ return (target: any, propertyKey: string) => {
18
+ const meta = getSocketMetadata(target)
19
+ meta.events.push({
20
+ type,
21
+ name: name || propertyKey,
22
+ propertyKey
23
+ })
24
+ }
25
+ }
26
+
27
+ export function OnConnect() {
28
+ return createSocketEventDecorator('connect')
29
+ }
30
+
31
+ export function OnDisconnect() {
32
+ return createSocketEventDecorator('disconnect')
33
+ }
34
+
35
+ export function OnMessage(name?: string) {
36
+ return createSocketEventDecorator('message', name)
37
+ }
38
+
39
+ export function OnEvent(name: string) {
40
+ return createSocketEventDecorator('event', name)
41
+ }
@@ -21,7 +21,8 @@ export class Encryption {
21
21
  }
22
22
 
23
23
  async compare(value: string, hash: string): Promise<boolean> {
24
- return this.make(value).then(result => result === hash);
24
+ const result = await this.make(value)
25
+ return result === hash;
25
26
  }
26
27
 
27
28
  async make(value: string, options?: DerivationOptionsInterface | ScryptOptionsInterface): Promise<EncryptionResultType> {
@@ -17,7 +17,7 @@ export enum CipherAlgoEnum {
17
17
  }
18
18
 
19
19
  export enum PasswordAlgoEnum {
20
- ARGON2ID = 'argon2id',
20
+ ARGON2ID = 'ARGON2ID',
21
21
  BCRYPT = 'BCRYPT',
22
- SCRYPT = 'SCRYPT',
22
+ // SCRYPT = 'SCRYPT',
23
23
  }
@@ -3,6 +3,7 @@ export enum Parametrable {
3
3
  BODY = "body",
4
4
  QUERY = "query",
5
5
  HEADER = "header",
6
+ COOKIE = "cookie",
6
7
  REQ = "req",
7
8
  REPLY = "reply",
8
9
  UPLOAD_FILE = "upload",
@@ -1,6 +1,6 @@
1
1
  export enum RuntimeType {
2
2
  Node = "node",
3
- Deno = "deno",
3
+ // Deno = "deno",
4
4
  Bun = "bun",
5
- Web = "web"
5
+ // Web = "web"
6
6
  }
@@ -1,8 +1,8 @@
1
1
  import {GenericValueType} from "../types/generic";
2
2
  import {getType} from "./utilities";
3
3
 
4
- export function env<T>(key: string, type?: GenericValueType): T | undefined {
5
- const value = process.env[key];
4
+ export function env<T>(key: string, defaultValue?: string, type?: GenericValueType): T | undefined {
5
+ const value = process.env[key] || defaultValue;
6
6
  type = type || getType(value) as GenericValueType;
7
7
 
8
8
  if (value) {
@@ -16,7 +16,7 @@ export class HttpException extends Error {
16
16
  message: this.message,
17
17
  statusCode: this.statusCode,
18
18
  error: true,
19
- stack: Raiton.thread?.builder?.options?.development
19
+ stack: Raiton.thread?.builder?.options?.serve
20
20
  ? this.stack?.split('\n').map(e => e.trim())
21
21
  : undefined
22
22
  }
@@ -1,13 +1,14 @@
1
1
  export * from "./enums/index"
2
2
  export * from "./constants/index"
3
- export * from "./decorators/index"
3
+ export * from "./utilities/index"
4
4
  export * from "./responses/index"
5
+ export * from "./decorators/index"
5
6
  export * from "./plugins/index"
6
- export * from "./utilities/index"
7
7
  export * from "./runtime/index"
8
8
  export * from "./exceptions/index"
9
9
  export * from "./controllers"
10
10
  export * from "./data-transfer-object"
11
+ export * from "./view-model"
11
12
  export * from "./encryption"
12
13
  export * from "./parameter-bag"
13
14
  export * from "./repositories"
@@ -8,21 +8,29 @@ export function bodyParserPlugin(): PluginInterface {
8
8
  name: 'body-parser-plugin',
9
9
  setup: (scope) => {
10
10
  scope.use(async ({context, next}: MiddlewareParametersInterface) => {
11
- const contentType = context.req.headers.get('content-type') || '';
11
+ readQueryBody(context);
12
12
 
13
- if (context.req.body && !context.state.bodyParsed) {
13
+ const isGetOrHead = ['GET', 'HEAD'].includes(context.req.method.toUpperCase());
14
+
15
+ if (isGetOrHead) {
16
+ context.req.body = context.req.query;
17
+ }
18
+
19
+ const hasBody = context.req.body !== undefined && context.req.body !== null;
20
+
21
+ if (hasBody && !context.state.bodyParsed && !isGetOrHead) {
14
22
  try {
23
+ const contentType = context.req.headers.get('content-type') || '';
15
24
  const rawBody = await readRawBody(context.req.body);
16
- context.req.body = rawBody as unknown as any;
17
25
  const bodyString = decode(rawBody);
18
26
 
19
- readQueryBody(context);
20
- await readMultipartBody(context, contentType);
27
+ await readMultipartBody(context, contentType, rawBody);
21
28
  readJsonBody(context, contentType, bodyString);
22
29
  readUrlEncodedBody(context, contentType, bodyString);
23
30
  readTextBody(context, contentType, bodyString);
24
31
 
25
32
  if (!context.state.bodyParsed) {
33
+ context.req.body = rawBody as any;
26
34
  context.state.bodyParsed = true;
27
35
  }
28
36
 
@@ -37,22 +45,20 @@ export function bodyParserPlugin(): PluginInterface {
37
45
  };
38
46
  }
39
47
 
40
- function readJsonBody(ctx: RequestContext, contentType: string, body: any) {
48
+ function readJsonBody(ctx: RequestContext, contentType: string, body: string) {
41
49
  if (contentType.includes('application/json')) {
42
- ctx.req.body = tryParseJson(body) || {} as unknown as any;
50
+ ctx.req.body = tryParseJson(body) || {};
43
51
  ctx.state.bodyParsed = true;
44
52
  }
45
53
  }
46
54
 
47
- async function readMultipartBody(ctx: RequestContext, contentType: string) {
55
+ async function readMultipartBody(ctx: RequestContext, contentType: string, rawBody: any) {
48
56
  if (contentType.includes('multipart/form-data')) {
49
- const body = ctx.req.body;
50
-
51
57
  try {
52
58
  const tempRequest = new Request(ctx.req.url, {
53
59
  method: ctx.req.method,
54
60
  headers: ctx.req.headers,
55
- body: body as any
61
+ body: rawBody
56
62
  });
57
63
 
58
64
  const formData = await tempRequest.formData();
@@ -104,6 +110,7 @@ function readTextBody(ctx: RequestContext, contentType: string, body: string) {
104
110
  }
105
111
 
106
112
  function readQueryBody(ctx: RequestContext) {
113
+
107
114
  const searchParams = new URLSearchParams(ctx.req.url.split('?')[1] || '');
108
115
  const record = {} as Record<string, any>;
109
116
  searchParams.forEach((value, key) => record[key] = value);
@@ -111,6 +118,16 @@ function readQueryBody(ctx: RequestContext) {
111
118
  }
112
119
 
113
120
  async function readRawBody(body: any): Promise<Uint8Array | string> {
121
+ if (!body) return new Uint8Array(0);
122
+
123
+ if (body instanceof Uint8Array || typeof body === 'string') {
124
+ return body;
125
+ }
126
+
127
+ if (typeof body === 'object' && !('on' in body) && !(body instanceof ReadableStream)) {
128
+ return JSON.stringify(body);
129
+ }
130
+
114
131
  if (body instanceof ReadableStream) {
115
132
  const reader = body.getReader();
116
133
  const chunks: Uint8Array[] = [];
@@ -0,0 +1,3 @@
1
+ export * from "./body-parser.plugin";
2
+ export * from "./security/index";
3
+ export * from "./openapi.plugin";
@@ -0,0 +1,98 @@
1
+ import type {PluginInterface} from "../../types";
2
+ import type {ContextInterface} from "../../types/core";
3
+ import {PluginScope} from "../../core";
4
+ import {Logger} from "@protorians/logger";
5
+ import {generateOpenApiSpec} from "../utilities/openapi.utils";
6
+
7
+ /**
8
+ * OpenAPI plugin options
9
+ */
10
+ export interface OpenApiOptions {
11
+ /**
12
+ * The base route for the documentation UI (e.g., '/docs')
13
+ * @default '/docs'
14
+ */
15
+ route?: string;
16
+
17
+ /**
18
+ * The HTML string page
19
+ */
20
+ ui?: (config: Omit<OpenApiOptions, 'ui'>, context: ContextInterface) => string;
21
+
22
+ /**
23
+ * The endpoint for the raw JSON OpenAPI spec (e.g., '/docs/json')
24
+ * If set to false, disables the JSON endpoint.
25
+ * @default '/docs/json'
26
+ */
27
+ endpoint?: string | false;
28
+ /**
29
+ * Title of the API
30
+ * @default 'API'
31
+ */
32
+ title?: string;
33
+ /**
34
+ * Version of the API
35
+ * @default '1.0.0'
36
+ */
37
+ version?: string;
38
+ /**
39
+ * Description of the API
40
+ * @default ''
41
+ */
42
+ description?: string;
43
+ /**
44
+ * Terms of service URL
45
+ */
46
+ termsOfService?: string;
47
+ /**
48
+ * Contact information
49
+ */
50
+ contact?: {
51
+ name?: string;
52
+ url?: string;
53
+ email?: string;
54
+ };
55
+ /**
56
+ * License information
57
+ */
58
+ license?: {
59
+ name?: string;
60
+ url?: string;
61
+ };
62
+ }
63
+
64
+ export function openApiPlugin(options: OpenApiOptions = {}): PluginInterface {
65
+ const opts = {
66
+ endpoint: '/docs/json',
67
+ title: 'API',
68
+ version: '1.0.0',
69
+ description: '',
70
+ termsOfService: undefined,
71
+ contact: undefined,
72
+ license: undefined,
73
+ ...options
74
+ };
75
+
76
+ return {
77
+ name: 'openapi-plugin',
78
+ setup: (scope: PluginScope) => {
79
+
80
+ if (opts.route && opts.ui) {
81
+ scope.get(opts.route, async ({reply, req, ...context}: ContextInterface) => {
82
+ const optionsWithoutUi = {...opts, ui: undefined}
83
+ const html = opts.ui?.(optionsWithoutUi, {reply, req, ...context});
84
+ reply.type('text/html');
85
+ reply.send(html || 'No Ui function defined');
86
+ });
87
+ }
88
+
89
+ if (opts.endpoint) {
90
+ scope.get(opts.endpoint, async ({reply}: ContextInterface) => {
91
+ const spec = await generateOpenApiSpec(scope, opts);
92
+ reply.type('application/json');
93
+ return spec
94
+ });
95
+ }
96
+ }
97
+ };
98
+ }
@@ -0,0 +1,78 @@
1
+ import {definePlugin} from "../../../core/plugins";
2
+ import {MiddlewareParametersInterface} from "../../../types";
3
+ import {Logger} from "@protorians/logger";
4
+
5
+ export interface CorsOptions {
6
+ origin?: string | string[] | boolean | ((origin: string) => boolean | Promise<boolean>)
7
+ methods?: string[]
8
+ headers?: string[]
9
+ credentials?: boolean
10
+ maxAge?: number
11
+ exposeHeaders?: string[]
12
+ }
13
+
14
+ export const secureCors = (opts: CorsOptions = {}) => {
15
+
16
+ return (async ({context, next}: MiddlewareParametersInterface) => {
17
+ const origin = context.req.headers.get('origin')
18
+
19
+ if (origin) {
20
+ context.reply.header('Vary', 'Origin')
21
+ }
22
+
23
+ let allowedOrigin: string | null = null
24
+
25
+ if (opts.origin === undefined || opts.origin === '*') {
26
+ allowedOrigin = '*'
27
+ } else if (opts.origin === true) {
28
+ allowedOrigin = origin || '*'
29
+ } else if (typeof opts.origin === 'function') {
30
+ if (origin && await opts.origin(origin)) {
31
+ allowedOrigin = origin
32
+ }
33
+ } else if (Array.isArray(opts.origin)) {
34
+ if (origin && opts.origin.includes(origin)) {
35
+ allowedOrigin = origin
36
+ }
37
+ } else if (typeof opts.origin === 'string') {
38
+ if (opts.origin === origin) {
39
+ allowedOrigin = origin
40
+ } else if (opts.origin === '*') {
41
+ allowedOrigin = '*'
42
+ }
43
+ }
44
+
45
+ if (allowedOrigin) {
46
+ context.reply.header('Access-Control-Allow-Origin', allowedOrigin)
47
+ }
48
+
49
+ if (opts.credentials) {
50
+ context.reply.header('Access-Control-Allow-Credentials', 'true')
51
+ }
52
+
53
+ if (opts.exposeHeaders) {
54
+ context.reply.header('Access-Control-Expose-Headers', opts.exposeHeaders.join(','))
55
+ }
56
+
57
+ if (context.req.method === 'OPTIONS') {
58
+ context.reply.header(
59
+ 'Access-Control-Allow-Methods',
60
+ (opts.methods ?? ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).join(',')
61
+ )
62
+
63
+ context.reply.header(
64
+ 'Access-Control-Allow-Headers',
65
+ (opts.headers ?? ['Content-Type', 'Authorization', 'X-Requested-With']).join(',')
66
+ )
67
+
68
+ if (opts.maxAge) {
69
+ context.reply.header('Access-Control-Max-Age', opts.maxAge.toString())
70
+ }
71
+
72
+ context.reply.status(204)
73
+ return context.send(null)
74
+ }
75
+
76
+ await next()
77
+ })
78
+ }
@@ -5,16 +5,17 @@ import {Raiton} from "../../core";
5
5
 
6
6
  export function RaitonResponses(
7
7
  message: string,
8
- data: HttpResponseInterface,
8
+ data: any,
9
+ // data: HttpResponseInterface<any> | null,
9
10
  statusCode: HttpStatus,
10
11
  metadata?: Omit<HttpResponseInterface<any>, 'data' | 'message' | 'statusCode'>
11
12
  ) {
12
13
 
13
14
  if (metadata) {
14
- metadata.error = typeof data.error === 'boolean' ? data.error : false
15
+ metadata.error = typeof data?.error === 'boolean' ? data?.error : false
15
16
  metadata.errorStack = (metadata.errorStack instanceof Error)
16
17
  ? metadata.errorStack
17
- : (Raiton.thread?.builder?.options?.development
18
+ : (Raiton.thread?.builder?.options?.serve
18
19
  ? (Array.isArray(metadata.errorStack) ? metadata.errorStack : [])
19
20
  : undefined)
20
21
  }
@@ -5,7 +5,7 @@ import {Raiton} from "../../core";
5
5
 
6
6
  export class ThrowableResponse extends Error {
7
7
  constructor(
8
- public input: string | HttpResponseInterface,
8
+ public input: string | HttpResponseInterface<any>,
9
9
  public statusCode: HttpStatus = HttpStatus.INTERNAL_SERVER_ERROR,
10
10
  ) {
11
11
  super(typeof input === 'string' ? input : input.message);
@@ -19,7 +19,7 @@ export class ThrowableResponse extends Error {
19
19
  data: (typeof this.input === 'object') ? this.input.data : undefined,
20
20
  error: (typeof this.input === 'object') ? this.input.error : false,
21
21
  stack: stack instanceof Error ?
22
- (Raiton.thread?.builder?.options?.development
22
+ (Raiton.thread?.builder?.options?.serve
23
23
  ? this.stack?.split('\n').map(e => e.trim())
24
24
  : undefined)
25
25
  : stack
@@ -4,7 +4,7 @@ import {ThrowableResponse} from ".";
4
4
 
5
5
 
6
6
  export class HttpResponse {
7
- public static push(response: Partial<HttpResponseInterface>): void {
7
+ public static push(response: Partial<HttpResponseInterface<any>>): void {
8
8
  throw new ThrowableResponse({
9
9
  statusCode: response.statusCode || HttpStatus.BAD_REQUEST,
10
10
  message: response.message || 'No response message provided',
@@ -14,7 +14,7 @@ export class HttpResponse {
14
14
  })
15
15
  }
16
16
 
17
- constructor(public readonly response: HttpResponseInterface) {
17
+ constructor(public readonly response: HttpResponseInterface<any>) {
18
18
  }
19
19
 
20
20
  status(statusCode: HttpStatus): this {
@@ -42,7 +42,7 @@ export class HttpResponse {
42
42
  return this;
43
43
  }
44
44
 
45
- render(): HttpResponseInterface {
45
+ render(): HttpResponseInterface<any> {
46
46
  return (new ThrowableResponse({...this.response})).render()
47
47
  }
48
48
  }