@moostjs/swagger 0.3.10 → 0.3.12

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
@@ -20,7 +20,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
20
20
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21
21
  PERFORMANCE OF THIS SOFTWARE.
22
22
  ***************************************************************************** */
23
- /* global Reflect, Promise */
23
+ /* global Reflect, Promise, SuppressedError, Symbol */
24
24
 
25
25
 
26
26
  function __decorate(decorators, target, key, desc) {
@@ -38,467 +38,455 @@ function __metadata(metadataKey, metadataValue) {
38
38
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
39
39
  }
40
40
 
41
- function __awaiter(thisArg, _arguments, P, generator) {
42
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
43
- return new (P || (P = Promise))(function (resolve, reject) {
44
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
45
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
46
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
47
- step((generator = generator.apply(thisArg, _arguments || [])).next());
48
- });
49
- }
41
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
42
+ var e = new Error(message);
43
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
44
+ };
50
45
 
51
- function getSwaggerMate() {
52
- return getMoostMate();
46
+ function getSwaggerMate() {
47
+ return getMoostMate();
53
48
  }
54
49
 
55
- const SwaggerTag = (tag) => getSwaggerMate().decorate('swaggerTags', tag, true);
56
- const SwaggerExclude = () => getSwaggerMate().decorate('swaggerExclude', true);
57
- const SwaggerDescription = (descr) => getSwaggerMate().decorate('swaggerDescription', descr);
58
- function SwaggerResponse(code, opts) {
59
- return getSwaggerMate().decorate((meta) => {
60
- meta.swaggerResponses = meta.swaggerResponses || {};
61
- const keyCode = typeof code === 'number' ? code : 0;
62
- const opt = typeof code === 'number' ? opts : code;
63
- const contentType = typeof opt.contentType === 'string' ? opt.contentType : '*/*';
64
- // const description = typeof (opt as { description: string }).description === 'string' ? (opt as { description: string }).description : undefined
65
- const response = (['object', 'function'].includes(typeof opt.response) ? opt.response : opt);
66
- meta.swaggerResponses[keyCode] = meta.swaggerResponses[keyCode] || {};
67
- meta.swaggerResponses[keyCode][contentType] = response;
68
- // meta.swaggerResponses[keyCode].description = description
69
- return meta;
70
- });
71
- }
72
- function SwaggerRequestBody(opt) {
73
- return getSwaggerMate().decorate((meta) => {
74
- meta.swaggerRequestBody = meta.swaggerRequestBody || {};
75
- const contentType = typeof opt.contentType === 'string' ? opt.contentType : 'application/json';
76
- const response = (typeof opt.contentType === 'string' ? opt.response : opt);
77
- meta.swaggerRequestBody[contentType] = response;
78
- return meta;
79
- });
50
+ const SwaggerTag = (tag) => getSwaggerMate().decorate('swaggerTags', tag, true);
51
+ const SwaggerExclude = () => getSwaggerMate().decorate('swaggerExclude', true);
52
+ const SwaggerDescription = (descr) => getSwaggerMate().decorate('swaggerDescription', descr);
53
+ function SwaggerResponse(code, opts) {
54
+ return getSwaggerMate().decorate((meta) => {
55
+ meta.swaggerResponses = meta.swaggerResponses || {};
56
+ const keyCode = typeof code === 'number' ? code : 0;
57
+ const opt = typeof code === 'number' ? opts : code;
58
+ const contentType = typeof opt.contentType === 'string' ? opt.contentType : '*/*';
59
+ const response = (['object', 'function'].includes(typeof opt.response) ? opt.response : opt);
60
+ meta.swaggerResponses[keyCode] = meta.swaggerResponses[keyCode] || {};
61
+ meta.swaggerResponses[keyCode][contentType] = response;
62
+ return meta;
63
+ });
64
+ }
65
+ function SwaggerRequestBody(opt) {
66
+ return getSwaggerMate().decorate((meta) => {
67
+ meta.swaggerRequestBody = meta.swaggerRequestBody || {};
68
+ const contentType = typeof opt.contentType === 'string' ? opt.contentType : 'application/json';
69
+ const response = (typeof opt.contentType === 'string' ? opt.response : opt);
70
+ meta.swaggerRequestBody[contentType] = response;
71
+ return meta;
72
+ });
80
73
  }
81
74
 
82
- function mapToSwaggerSpec(metadata, options, logger) {
83
- var _a;
84
- const swaggerSpec = {
85
- openapi: '3.0.0',
86
- info: {
87
- title: (options === null || options === void 0 ? void 0 : options.title) || 'API Documentation',
88
- version: (options === null || options === void 0 ? void 0 : options.version) || '1.0.0',
89
- },
90
- paths: {},
91
- tags: [],
92
- components: {
93
- schemas: globalSchemas,
94
- },
95
- };
96
- for (const controller of metadata) {
97
- const cmeta = controller.meta;
98
- if (cmeta === null || cmeta === void 0 ? void 0 : cmeta.swaggerExclude)
99
- continue;
100
- const controllerTags = (cmeta === null || cmeta === void 0 ? void 0 : cmeta.swaggerTags) || [];
101
- for (const handler of controller.handlers) {
102
- const hmeta = handler.meta;
103
- const hh = handler.handler;
104
- if (hh.type !== 'HTTP' || (hmeta === null || hmeta === void 0 ? void 0 : hmeta.swaggerExclude) || !handler.registeredAs.length)
105
- continue;
106
- const handlerPath = handler.registeredAs[0].path;
107
- const handlerMethod = ((_a = hh.method) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || 'get';
108
- const handlerDescription = hmeta === null || hmeta === void 0 ? void 0 : hmeta.description;
109
- const handlerTags = [...controllerTags, ...((hmeta === null || hmeta === void 0 ? void 0 : hmeta.swaggerTags) || [])];
110
- if (!swaggerSpec.paths[handlerPath]) {
111
- swaggerSpec.paths[handlerPath] = {};
112
- }
113
- let responses = undefined;
114
- if (hmeta === null || hmeta === void 0 ? void 0 : hmeta.swaggerResponses) {
115
- for (const [code, responseConfigs] of Object.entries(hmeta.swaggerResponses)) {
116
- const newCode = code === '0' ? getDefaultStatusCode(handlerMethod) : code;
117
- for (const [contentType, type] of Object.entries(responseConfigs)) {
118
- let schema = undefined;
119
- let zt = undefined;
120
- if (type instanceof z.ZodType) {
121
- zt = type;
122
- }
123
- else if (typeof type === 'function') {
124
- zt = getZodType({
125
- type,
126
- });
127
- }
128
- if (zt) {
129
- const parsed = myParseZod(zt);
130
- if (['ZodString', 'ZodNumber', 'ZodObject', 'ZodArray', 'ZodBoolean'].includes(parsed.$type)) {
131
- schema = getSwaggerSchema(parsed);
132
- }
133
- }
134
- if (schema) {
135
- responses = responses || {};
136
- responses[newCode] = { content: { [contentType]: { schema } } };
137
- }
138
- }
139
- }
140
- }
141
- else if (hmeta === null || hmeta === void 0 ? void 0 : hmeta.returnType) {
142
- const parsed = myParseZod(getZodType({
143
- type: hmeta.returnType,
144
- }));
145
- if (['ZodString', 'ZodNumber', 'ZodObject', 'ZodArray', 'ZodBoolean'].includes(parsed.$type)) {
146
- const schema = getSwaggerSchema(parsed);
147
- if (schema) {
148
- responses = responses || {};
149
- responses[getDefaultStatusCode(handlerMethod)] = {
150
- content: {
151
- '*/*': {
152
- schema,
153
- },
154
- },
155
- };
156
- }
157
- }
158
- }
159
- let reqBodyRequired = true;
160
- const bodyConfig = {};
161
- if (hmeta === null || hmeta === void 0 ? void 0 : hmeta.swaggerRequestBody) {
162
- for (const [contentType, type] of Object.entries(hmeta === null || hmeta === void 0 ? void 0 : hmeta.swaggerRequestBody)) {
163
- let zt;
164
- let schema;
165
- if (type instanceof z.ZodType) {
166
- zt = type;
167
- }
168
- else if (typeof type === 'function') {
169
- zt = getZodType({
170
- type,
171
- });
172
- }
173
- if (zt) {
174
- const parsed = myParseZod(zt);
175
- if (['ZodString', 'ZodNumber', 'ZodObject', 'ZodArray', 'ZodBoolean'].includes(parsed.$type)) {
176
- schema = getSwaggerSchema(parsed);
177
- }
178
- }
179
- bodyConfig[contentType] = { schema };
180
- }
181
- }
182
- swaggerSpec.paths[handlerPath][handlerMethod] = {
183
- summary: handlerDescription,
184
- operationId: handlerMethod.toUpperCase() + '_' + handlerPath.replace(/\//g, '_').replace(/[\{\}]/g, '__').replace(/[^A-Za-z0-9]/g, '_'),
185
- tags: handlerTags,
186
- parameters: [],
187
- responses,
188
- };
189
- const endpointSpec = swaggerSpec.paths[handlerPath][handlerMethod];
190
- for (const paramName of handler.registeredAs[0].args) {
191
- const paramIndex = handler.meta.params.findIndex(param => param.paramSource === 'ROUTE' && param.paramName === paramName);
192
- const paramMeta = handler.meta.params[paramIndex];
193
- let schema;
194
- let parsed;
195
- if (paramMeta) {
196
- const zodType = getZodTypeForProp({
197
- type: controller.type,
198
- key: handler.method,
199
- index: paramIndex,
200
- }, {
201
- type: paramMeta.type,
202
- additionalMeta: paramMeta,
203
- }, undefined, logger);
204
- parsed = myParseZod(zodType);
205
- schema = getSwaggerSchema(parsed, true);
206
- }
207
- endpointSpec.parameters.push({
208
- name: paramName,
209
- in: 'path',
210
- description: paramMeta ? paramMeta.description : undefined,
211
- required: !(paramMeta === null || paramMeta === void 0 ? void 0 : paramMeta.optional) && !(parsed === null || parsed === void 0 ? void 0 : parsed.$optional),
212
- schema: schema || { type: 'string' },
213
- });
214
- }
215
- for (let i = 0; i < handler.meta.params.length; i++) {
216
- const paramMeta = handler.meta.params[i];
217
- if (paramMeta.paramSource && ['QUERY_ITEM', 'QUERY'].includes(paramMeta.paramSource)) {
218
- const zodType = getZodTypeForProp({
219
- type: controller.type,
220
- key: handler.method,
221
- index: i,
222
- }, {
223
- type: paramMeta.type,
224
- additionalMeta: paramMeta,
225
- }, undefined, logger);
226
- const parsed = myParseZod(zodType);
227
- const schema = getSwaggerSchema(parsed, true);
228
- if (paramMeta.paramSource == 'QUERY_ITEM') {
229
- endpointSpec.parameters.push({
230
- name: paramMeta.paramName || '',
231
- in: 'query',
232
- description: paramMeta.description,
233
- required: !(paramMeta === null || paramMeta === void 0 ? void 0 : paramMeta.optional) && !(parsed === null || parsed === void 0 ? void 0 : parsed.$optional),
234
- schema: schema || { type: 'string' },
235
- });
236
- }
237
- else if (paramMeta.paramSource == 'QUERY') {
238
- if (parsed.$type === 'ZodObject') {
239
- for (const [key, value] of Object.entries(parsed.$inner)) {
240
- const schema = getSwaggerSchema(value, true);
241
- if (schema) {
242
- const swaggerSchema = {
243
- name: key,
244
- in: 'query',
245
- description: value.description,
246
- required: !parsed.$optional && !value.$optional,
247
- schema,
248
- };
249
- endpointSpec.parameters.push(swaggerSchema);
250
- }
251
- }
252
- }
253
- }
254
- }
255
- if ((paramMeta === null || paramMeta === void 0 ? void 0 : paramMeta.paramSource) === 'BODY') {
256
- const zodType = getZodTypeForProp({
257
- type: controller.type,
258
- key: handler.method,
259
- index: i,
260
- }, {
261
- type: paramMeta.type,
262
- additionalMeta: paramMeta,
263
- }, undefined, logger);
264
- const parsed = myParseZod(zodType);
265
- let contentType = '';
266
- switch (parsed.$type) {
267
- case 'ZodString':
268
- case 'ZodNumber':
269
- case 'ZodBigInt':
270
- case 'ZodBoolean':
271
- case 'ZodDate':
272
- case 'ZodEnum':
273
- case 'ZodNativeEnum':
274
- case 'ZodLiteral':
275
- contentType = 'text/plan';
276
- break;
277
- default: contentType = 'application/json';
278
- }
279
- if (!bodyConfig[contentType]) {
280
- bodyConfig[contentType] = { schema: getSwaggerSchema(parsed) };
281
- }
282
- reqBodyRequired = !zodType.isOptional() && !paramMeta.optional;
283
- }
284
- }
285
- if (bodyConfig && Object.entries(bodyConfig).filter(e => !!e[1]).length > 0) {
286
- swaggerSpec.paths[handlerPath][handlerMethod].requestBody = {
287
- content: bodyConfig,
288
- required: reqBodyRequired,
289
- };
290
- }
291
- }
292
- }
293
- return swaggerSpec;
294
- }
295
- const globalSchemas = {};
296
- function getSwaggerSchema(parsed, forParam) {
297
- var _a, _b;
298
- const zodType = parsed.$ref;
299
- if (!forParam && zodType.__type_ref && globalSchemas[zodType.__type_ref.name])
300
- return { $ref: `#/components/schemas/${zodType.__type_ref.name}` };
301
- if (forParam && zodType.__type_ref && globalSchemas[zodType.__type_ref.name])
302
- return globalSchemas[zodType.__type_ref.name];
303
- const schema = {};
304
- if (!forParam && zodType.__type_ref) {
305
- globalSchemas[zodType.__type_ref.name] = schema;
306
- }
307
- function asString() {
308
- schema.type = 'string';
309
- if (parsed.$checks) {
310
- const { regex } = parsed.$checks;
311
- if (regex) {
312
- schema.pattern = regex.source;
313
- }
314
- }
315
- }
316
- function asLiteral() {
317
- if (parsed.$type === 'ZodLiteral') {
318
- schema.type = 'string';
319
- schema.enum = [parsed.$value];
320
- }
321
- }
322
- function asEnum() {
323
- if (parsed.$type === 'ZodEnum') {
324
- schema.type = 'string';
325
- schema.enum = parsed.$value;
326
- }
327
- }
328
- function asNativeEnum() {
329
- if (parsed.$type === 'ZodNativeEnum') {
330
- schema.type = 'string';
331
- schema.enum = Object.keys(parsed.$value);
332
- }
333
- }
334
- if (forParam) {
335
- switch (parsed.$type) {
336
- case 'ZodAny':
337
- case 'ZodUnknown':
338
- case 'ZodString':
339
- asString();
340
- break;
341
- case 'ZodNumber':
342
- schema.type = 'number';
343
- break;
344
- case 'ZodBigInt':
345
- schema.type = 'integer';
346
- break;
347
- case 'ZodBoolean':
348
- schema.type = 'boolean';
349
- break;
350
- case 'ZodLiteral':
351
- asLiteral();
352
- break;
353
- case 'ZodEnum':
354
- asEnum();
355
- break;
356
- case 'ZodNativeEnum':
357
- asNativeEnum();
358
- break;
359
- case 'ZodDate':
360
- schema.type = 'string';
361
- break;
362
- case 'ZodNull':
363
- schema.type = 'null';
364
- break;
365
- default: return undefined;
366
- }
367
- }
368
- else {
369
- switch (parsed.$type) {
370
- case 'ZodString':
371
- asString();
372
- break;
373
- case 'ZodNumber':
374
- schema.type = 'number';
375
- break;
376
- case 'ZodBigInt':
377
- schema.type = 'integer';
378
- break;
379
- case 'ZodBoolean':
380
- schema.type = 'boolean';
381
- break;
382
- case 'ZodLiteral':
383
- asLiteral();
384
- break;
385
- case 'ZodEnum':
386
- asEnum();
387
- break;
388
- case 'ZodNativeEnum':
389
- asNativeEnum();
390
- break;
391
- case 'ZodDate':
392
- schema.type = 'string';
393
- break;
394
- case 'ZodNull':
395
- schema.type = 'null';
396
- break;
397
- case 'ZodFunction':
398
- case 'ZodSymbol':
399
- case 'ZodUndefined':
400
- case 'ZodUnknown':
401
- case 'ZodNever':
402
- case 'ZodVoid':
403
- case 'ZodNaN':
404
- return undefined;
405
- // case 'ZodAny':
406
- case 'ZodArray':
407
- schema.type = 'array';
408
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
409
- schema.minItems = ((_a = parsed.$checks) === null || _a === void 0 ? void 0 : _a.minLength) || undefined;
410
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
411
- schema.maxItems = ((_b = parsed.$checks) === null || _b === void 0 ? void 0 : _b.maxLength) || undefined;
412
- schema.items = getSwaggerSchema(parsed.$inner);
413
- break;
414
- case 'ZodTuple':
415
- schema.type = 'array';
416
- schema.items = parsed.$inner.map(t => getSwaggerSchema(t)).filter(t => !!t);
417
- break;
418
- case 'ZodObject':
419
- schema.type = 'object';
420
- schema.properties = {};
421
- schema.required = [];
422
- if (zodType._def.unknownKeys === 'passthrough')
423
- schema.additionalProperties = {};
424
- for (const [key, val] of Object.entries(parsed.$inner)) {
425
- const prop = getSwaggerSchema(val);
426
- if (prop) {
427
- schema.properties[key] = prop;
428
- if (!val.$optional)
429
- schema.required.push(key);
430
- }
431
- }
432
- break;
433
- case 'ZodPromise':
434
- case 'ZodRecord':
435
- case 'ZodMap':
436
- case 'ZodSet':
437
- schema.type = 'object';
438
- schema.properties = {};
439
- schema.additionalProperties = parsed.$type === 'ZodRecord' ? {} : undefined;
440
- break;
441
- case 'ZodUnion':
442
- case 'ZodDiscriminatedUnion':
443
- schema.oneOf = parsed.$inner.map(t => getSwaggerSchema(t)).filter(t => !!t);
444
- break;
445
- case 'ZodIntersection':
446
- schema.allOf = parsed.$inner.map(t => getSwaggerSchema(t)).filter(t => !!t);
447
- break;
448
- case 'ZodLazy':
449
- return getSwaggerSchema(parsed.$get());
450
- }
451
- }
452
- if (parsed.$nullable) {
453
- schema.nullable = parsed.$nullable;
454
- }
455
- if (parsed.$ref._def.description) {
456
- schema.description = parsed.$ref._def.description;
457
- }
458
- if (parsed.$checks) {
459
- const checks = parsed.$checks;
460
- if (parsed.$type === 'ZodString') {
461
- if (typeof checks.min === 'number')
462
- schema.minLength = checks.min;
463
- if (typeof checks.max === 'number')
464
- schema.maxLength = checks.max;
465
- }
466
- else {
467
- if (typeof checks.min === 'number')
468
- schema.minimum = checks.min;
469
- if (typeof checks.max === 'number')
470
- schema.maximum = checks.max;
471
- }
472
- }
473
- if (!forParam && zodType.__type_ref) {
474
- return { $ref: `#/components/schemas/${zodType.__type_ref.name}` };
475
- }
476
- return schema;
477
- }
478
- function myParseZod(schema) {
479
- return parseZodType(schema);
480
- }
481
- function getDefaultStatusCode(httpMethod) {
482
- const defaultStatusCodes = {
483
- GET: 200,
484
- PUT: 200,
485
- POST: 201,
486
- DELETE: 204,
487
- };
488
- return defaultStatusCodes[httpMethod.toUpperCase()] || 200;
75
+ function mapToSwaggerSpec(metadata, options, logger) {
76
+ const swaggerSpec = {
77
+ openapi: '3.0.0',
78
+ info: {
79
+ title: options?.title || 'API Documentation',
80
+ version: options?.version || '1.0.0',
81
+ },
82
+ paths: {},
83
+ tags: [],
84
+ components: {
85
+ schemas: globalSchemas,
86
+ },
87
+ };
88
+ for (const controller of metadata) {
89
+ const cmeta = controller.meta;
90
+ if (cmeta?.swaggerExclude)
91
+ continue;
92
+ const controllerTags = cmeta?.swaggerTags || [];
93
+ for (const handler of controller.handlers) {
94
+ const hmeta = handler.meta;
95
+ const hh = handler.handler;
96
+ if (hh.type !== 'HTTP' || hmeta?.swaggerExclude || !handler.registeredAs.length)
97
+ continue;
98
+ const handlerPath = handler.registeredAs[0].path;
99
+ const handlerMethod = hh.method?.toLowerCase() || 'get';
100
+ const handlerDescription = hmeta?.description;
101
+ const handlerTags = [...controllerTags, ...(hmeta?.swaggerTags || [])];
102
+ if (!swaggerSpec.paths[handlerPath]) {
103
+ swaggerSpec.paths[handlerPath] = {};
104
+ }
105
+ let responses = undefined;
106
+ if (hmeta?.swaggerResponses) {
107
+ for (const [code, responseConfigs] of Object.entries(hmeta.swaggerResponses)) {
108
+ const newCode = code === '0' ? getDefaultStatusCode(handlerMethod) : code;
109
+ for (const [contentType, type] of Object.entries(responseConfigs)) {
110
+ let schema = undefined;
111
+ let zt = undefined;
112
+ if (type instanceof z.ZodType) {
113
+ zt = type;
114
+ }
115
+ else if (typeof type === 'function') {
116
+ zt = getZodType({
117
+ type,
118
+ });
119
+ }
120
+ if (zt) {
121
+ const parsed = myParseZod(zt);
122
+ if (['ZodString', 'ZodNumber', 'ZodObject', 'ZodArray', 'ZodBoolean'].includes(parsed.$type)) {
123
+ schema = getSwaggerSchema(parsed);
124
+ }
125
+ }
126
+ if (schema) {
127
+ responses = responses || {};
128
+ responses[newCode] = { content: { [contentType]: { schema } } };
129
+ }
130
+ }
131
+ }
132
+ }
133
+ else if (hmeta?.returnType) {
134
+ const parsed = myParseZod(getZodType({
135
+ type: hmeta.returnType,
136
+ }));
137
+ if (['ZodString', 'ZodNumber', 'ZodObject', 'ZodArray', 'ZodBoolean'].includes(parsed.$type)) {
138
+ const schema = getSwaggerSchema(parsed);
139
+ if (schema) {
140
+ responses = responses || {};
141
+ responses[getDefaultStatusCode(handlerMethod)] = {
142
+ content: {
143
+ '*/*': {
144
+ schema,
145
+ },
146
+ },
147
+ };
148
+ }
149
+ }
150
+ }
151
+ let reqBodyRequired = true;
152
+ const bodyConfig = {};
153
+ if (hmeta?.swaggerRequestBody) {
154
+ for (const [contentType, type] of Object.entries(hmeta?.swaggerRequestBody)) {
155
+ let zt;
156
+ let schema;
157
+ if (type instanceof z.ZodType) {
158
+ zt = type;
159
+ }
160
+ else if (typeof type === 'function') {
161
+ zt = getZodType({
162
+ type,
163
+ });
164
+ }
165
+ if (zt) {
166
+ const parsed = myParseZod(zt);
167
+ if (['ZodString', 'ZodNumber', 'ZodObject', 'ZodArray', 'ZodBoolean'].includes(parsed.$type)) {
168
+ schema = getSwaggerSchema(parsed);
169
+ }
170
+ }
171
+ bodyConfig[contentType] = { schema };
172
+ }
173
+ }
174
+ swaggerSpec.paths[handlerPath][handlerMethod] = {
175
+ summary: handlerDescription,
176
+ operationId: handlerMethod.toUpperCase() + '_' + handlerPath.replace(/\//g, '_').replace(/[\{\}]/g, '__').replace(/[^A-Za-z0-9]/g, '_'),
177
+ tags: handlerTags,
178
+ parameters: [],
179
+ responses,
180
+ };
181
+ const endpointSpec = swaggerSpec.paths[handlerPath][handlerMethod];
182
+ for (const paramName of handler.registeredAs[0].args) {
183
+ const paramIndex = handler.meta.params.findIndex(param => param.paramSource === 'ROUTE' && param.paramName === paramName);
184
+ const paramMeta = handler.meta.params[paramIndex];
185
+ let schema;
186
+ let parsed;
187
+ if (paramMeta) {
188
+ const zodType = getZodTypeForProp({
189
+ type: controller.type,
190
+ key: handler.method,
191
+ index: paramIndex,
192
+ }, {
193
+ type: paramMeta.type,
194
+ additionalMeta: paramMeta,
195
+ }, undefined, logger);
196
+ parsed = myParseZod(zodType);
197
+ schema = getSwaggerSchema(parsed, true);
198
+ }
199
+ endpointSpec.parameters.push({
200
+ name: paramName,
201
+ in: 'path',
202
+ description: paramMeta ? paramMeta.description : undefined,
203
+ required: !paramMeta?.optional && !parsed?.$optional,
204
+ schema: schema || { type: 'string' },
205
+ });
206
+ }
207
+ for (let i = 0; i < handler.meta.params.length; i++) {
208
+ const paramMeta = handler.meta.params[i];
209
+ if (paramMeta.paramSource && ['QUERY_ITEM', 'QUERY'].includes(paramMeta.paramSource)) {
210
+ const zodType = getZodTypeForProp({
211
+ type: controller.type,
212
+ key: handler.method,
213
+ index: i,
214
+ }, {
215
+ type: paramMeta.type,
216
+ additionalMeta: paramMeta,
217
+ }, undefined, logger);
218
+ const parsed = myParseZod(zodType);
219
+ const schema = getSwaggerSchema(parsed, true);
220
+ if (paramMeta.paramSource == 'QUERY_ITEM') {
221
+ endpointSpec.parameters.push({
222
+ name: paramMeta.paramName || '',
223
+ in: 'query',
224
+ description: paramMeta.description,
225
+ required: !paramMeta?.optional && !parsed?.$optional,
226
+ schema: schema || { type: 'string' },
227
+ });
228
+ }
229
+ else if (paramMeta.paramSource == 'QUERY') {
230
+ if (parsed.$type === 'ZodObject') {
231
+ for (const [key, value] of Object.entries(parsed.$inner)) {
232
+ const schema = getSwaggerSchema(value, true);
233
+ if (schema) {
234
+ const swaggerSchema = {
235
+ name: key,
236
+ in: 'query',
237
+ description: value.description,
238
+ required: !parsed.$optional && !value.$optional,
239
+ schema,
240
+ };
241
+ endpointSpec.parameters.push(swaggerSchema);
242
+ }
243
+ }
244
+ }
245
+ }
246
+ }
247
+ if (paramMeta?.paramSource === 'BODY') {
248
+ const zodType = getZodTypeForProp({
249
+ type: controller.type,
250
+ key: handler.method,
251
+ index: i,
252
+ }, {
253
+ type: paramMeta.type,
254
+ additionalMeta: paramMeta,
255
+ }, undefined, logger);
256
+ const parsed = myParseZod(zodType);
257
+ let contentType = '';
258
+ switch (parsed.$type) {
259
+ case 'ZodString':
260
+ case 'ZodNumber':
261
+ case 'ZodBigInt':
262
+ case 'ZodBoolean':
263
+ case 'ZodDate':
264
+ case 'ZodEnum':
265
+ case 'ZodNativeEnum':
266
+ case 'ZodLiteral':
267
+ contentType = 'text/plan';
268
+ break;
269
+ default: contentType = 'application/json';
270
+ }
271
+ if (!bodyConfig[contentType]) {
272
+ bodyConfig[contentType] = { schema: getSwaggerSchema(parsed) };
273
+ }
274
+ reqBodyRequired = !zodType.isOptional() && !paramMeta.optional;
275
+ }
276
+ }
277
+ if (bodyConfig && Object.entries(bodyConfig).filter(e => !!e[1]).length > 0) {
278
+ swaggerSpec.paths[handlerPath][handlerMethod].requestBody = {
279
+ content: bodyConfig,
280
+ required: reqBodyRequired,
281
+ };
282
+ }
283
+ }
284
+ }
285
+ return swaggerSpec;
286
+ }
287
+ const globalSchemas = {};
288
+ function getSwaggerSchema(parsed, forParam) {
289
+ const zodType = parsed.$ref;
290
+ if (!forParam && zodType.__type_ref && globalSchemas[zodType.__type_ref.name])
291
+ return { $ref: `#/components/schemas/${zodType.__type_ref.name}` };
292
+ if (forParam && zodType.__type_ref && globalSchemas[zodType.__type_ref.name])
293
+ return globalSchemas[zodType.__type_ref.name];
294
+ const schema = {};
295
+ if (!forParam && zodType.__type_ref) {
296
+ globalSchemas[zodType.__type_ref.name] = schema;
297
+ }
298
+ function asString() {
299
+ schema.type = 'string';
300
+ if (parsed.$checks) {
301
+ const { regex } = parsed.$checks;
302
+ if (regex) {
303
+ schema.pattern = regex.source;
304
+ }
305
+ }
306
+ }
307
+ function asLiteral() {
308
+ if (parsed.$type === 'ZodLiteral') {
309
+ schema.type = 'string';
310
+ schema.enum = [parsed.$value];
311
+ }
312
+ }
313
+ function asEnum() {
314
+ if (parsed.$type === 'ZodEnum') {
315
+ schema.type = 'string';
316
+ schema.enum = parsed.$value;
317
+ }
318
+ }
319
+ function asNativeEnum() {
320
+ if (parsed.$type === 'ZodNativeEnum') {
321
+ schema.type = 'string';
322
+ schema.enum = Object.keys(parsed.$value);
323
+ }
324
+ }
325
+ if (forParam) {
326
+ switch (parsed.$type) {
327
+ case 'ZodAny':
328
+ case 'ZodUnknown':
329
+ case 'ZodString':
330
+ asString();
331
+ break;
332
+ case 'ZodNumber':
333
+ schema.type = 'number';
334
+ break;
335
+ case 'ZodBigInt':
336
+ schema.type = 'integer';
337
+ break;
338
+ case 'ZodBoolean':
339
+ schema.type = 'boolean';
340
+ break;
341
+ case 'ZodLiteral':
342
+ asLiteral();
343
+ break;
344
+ case 'ZodEnum':
345
+ asEnum();
346
+ break;
347
+ case 'ZodNativeEnum':
348
+ asNativeEnum();
349
+ break;
350
+ case 'ZodDate':
351
+ schema.type = 'string';
352
+ break;
353
+ case 'ZodNull':
354
+ schema.type = 'null';
355
+ break;
356
+ default: return undefined;
357
+ }
358
+ }
359
+ else {
360
+ switch (parsed.$type) {
361
+ case 'ZodString':
362
+ asString();
363
+ break;
364
+ case 'ZodNumber':
365
+ schema.type = 'number';
366
+ break;
367
+ case 'ZodBigInt':
368
+ schema.type = 'integer';
369
+ break;
370
+ case 'ZodBoolean':
371
+ schema.type = 'boolean';
372
+ break;
373
+ case 'ZodLiteral':
374
+ asLiteral();
375
+ break;
376
+ case 'ZodEnum':
377
+ asEnum();
378
+ break;
379
+ case 'ZodNativeEnum':
380
+ asNativeEnum();
381
+ break;
382
+ case 'ZodDate':
383
+ schema.type = 'string';
384
+ break;
385
+ case 'ZodNull':
386
+ schema.type = 'null';
387
+ break;
388
+ case 'ZodFunction':
389
+ case 'ZodSymbol':
390
+ case 'ZodUndefined':
391
+ case 'ZodUnknown':
392
+ case 'ZodNever':
393
+ case 'ZodVoid':
394
+ case 'ZodNaN':
395
+ return undefined;
396
+ case 'ZodArray':
397
+ schema.type = 'array';
398
+ schema.minItems = parsed.$checks?.minLength || undefined;
399
+ schema.maxItems = parsed.$checks?.maxLength || undefined;
400
+ schema.items = getSwaggerSchema(parsed.$inner);
401
+ break;
402
+ case 'ZodTuple':
403
+ schema.type = 'array';
404
+ schema.items = parsed.$inner.map(t => getSwaggerSchema(t)).filter(t => !!t);
405
+ break;
406
+ case 'ZodObject':
407
+ schema.type = 'object';
408
+ schema.properties = {};
409
+ schema.required = [];
410
+ if (zodType._def.unknownKeys === 'passthrough')
411
+ schema.additionalProperties = {};
412
+ for (const [key, val] of Object.entries(parsed.$inner)) {
413
+ const prop = getSwaggerSchema(val);
414
+ if (prop) {
415
+ schema.properties[key] = prop;
416
+ if (!val.$optional)
417
+ schema.required.push(key);
418
+ }
419
+ }
420
+ break;
421
+ case 'ZodPromise':
422
+ case 'ZodRecord':
423
+ case 'ZodMap':
424
+ case 'ZodSet':
425
+ schema.type = 'object';
426
+ schema.properties = {};
427
+ schema.additionalProperties = parsed.$type === 'ZodRecord' ? {} : undefined;
428
+ break;
429
+ case 'ZodUnion':
430
+ case 'ZodDiscriminatedUnion':
431
+ schema.oneOf = parsed.$inner.map(t => getSwaggerSchema(t)).filter(t => !!t);
432
+ break;
433
+ case 'ZodIntersection':
434
+ schema.allOf = parsed.$inner.map(t => getSwaggerSchema(t)).filter(t => !!t);
435
+ break;
436
+ case 'ZodLazy':
437
+ return getSwaggerSchema(parsed.$get());
438
+ }
439
+ }
440
+ if (parsed.$nullable) {
441
+ schema.nullable = parsed.$nullable;
442
+ }
443
+ if (parsed.$ref._def.description) {
444
+ schema.description = parsed.$ref._def.description;
445
+ }
446
+ if (parsed.$checks) {
447
+ const checks = parsed.$checks;
448
+ if (parsed.$type === 'ZodString') {
449
+ if (typeof checks.min === 'number')
450
+ schema.minLength = checks.min;
451
+ if (typeof checks.max === 'number')
452
+ schema.maxLength = checks.max;
453
+ }
454
+ else {
455
+ if (typeof checks.min === 'number')
456
+ schema.minimum = checks.min;
457
+ if (typeof checks.max === 'number')
458
+ schema.maximum = checks.max;
459
+ }
460
+ }
461
+ if (!forParam && zodType.__type_ref) {
462
+ return { $ref: `#/components/schemas/${zodType.__type_ref.name}` };
463
+ }
464
+ return schema;
465
+ }
466
+ function myParseZod(schema) {
467
+ return parseZodType(schema);
468
+ }
469
+ function getDefaultStatusCode(httpMethod) {
470
+ const defaultStatusCodes = {
471
+ GET: 200,
472
+ PUT: 200,
473
+ POST: 201,
474
+ DELETE: 204,
475
+ };
476
+ return defaultStatusCodes[httpMethod.toUpperCase()] || 200;
489
477
  }
490
478
 
491
- let SwaggerController = class SwaggerController {
492
- constructor(title = 'Moost API') {
493
- this.title = title;
494
- this.assetPath = getAbsoluteFSPath();
495
- }
496
- serveIndex(url, location, status) {
497
- if (!url.endsWith('index.html') && !url.endsWith('/')) {
498
- status.value = 302;
499
- location.value = join(url, '/');
500
- return '';
501
- }
479
+ let SwaggerController = class SwaggerController {
480
+ constructor(title = 'Moost API') {
481
+ this.title = title;
482
+ this.assetPath = getAbsoluteFSPath();
483
+ }
484
+ serveIndex(url, location, status) {
485
+ if (!url.endsWith('index.html') && !url.endsWith('/')) {
486
+ status.value = 302;
487
+ location.value = join(url, '/');
488
+ return '';
489
+ }
502
490
  return `<!DOCTYPE html>
503
491
  <html lang="en">
504
492
  <head>
@@ -516,9 +504,9 @@ let SwaggerController = class SwaggerController {
516
504
  <script src="./swagger-ui-standalone-preset.js" charset="UTF-8"> </script>
517
505
  <script src="./swagger-initializer.js" charset="UTF-8"> </script>
518
506
  </body>
519
- </html>`;
520
- }
521
- 'swagger-initializer.js'() {
507
+ </html>`;
508
+ }
509
+ 'swagger-initializer.js'() {
522
510
  return `window.onload = function() {
523
511
  window.ui = SwaggerUIBundle({
524
512
  url: "./spec.json",
@@ -533,73 +521,71 @@ let SwaggerController = class SwaggerController {
533
521
  ],
534
522
  layout: "BaseLayout"
535
523
  });
536
- };`;
537
- }
538
- 'spec.json'() {
539
- return __awaiter(this, void 0, void 0, function* () {
540
- const logger = useEventLogger('@moostjs/zod');
541
- if (!this.spec) {
542
- const { instantiate } = useControllerContext();
543
- const moost = yield instantiate(Moost);
544
- this.spec = mapToSwaggerSpec(moost.getControllersOverview(), { title: this.title }, logger);
545
- }
546
- return this.spec;
547
- });
548
- }
549
- files(url) {
550
- return this.serve(url.split('/').pop());
551
- }
552
- serve(path) {
553
- return serveFile(path, {
554
- baseDir: this.assetPath,
555
- cacheControl: {
556
- public: true,
557
- maxAge: '1w',
558
- },
559
- });
560
- }
561
- };
562
- __decorate([
563
- Get(''),
564
- Get('//'),
565
- Get('index.html'),
566
- SetHeader('content-type', 'text/html'),
567
- __param(0, Url()),
568
- __param(1, HeaderHook('location')),
569
- __param(2, StatusHook()),
570
- __metadata("design:type", Function),
571
- __metadata("design:paramtypes", [String, Object, Object]),
572
- __metadata("design:returntype", void 0)
573
- ], SwaggerController.prototype, "serveIndex", null);
574
- __decorate([
575
- Get(),
576
- SetHeader('content-type', 'application/javascript'),
577
- __metadata("design:type", Function),
578
- __metadata("design:paramtypes", []),
579
- __metadata("design:returntype", void 0)
580
- ], SwaggerController.prototype, "swagger-initializer.js", null);
581
- __decorate([
582
- Get(),
583
- __metadata("design:type", Function),
584
- __metadata("design:paramtypes", []),
585
- __metadata("design:returntype", Promise)
586
- ], SwaggerController.prototype, "spec.json", null);
587
- __decorate([
588
- Get('swagger-ui-bundle.*(js|js\\.map)'),
589
- Get('swagger-ui-standalone-preset.*(js|js\\.map)'),
590
- Get('swagger-ui.*(css|css\\.map)'),
591
- Get('index.*(css|css\\.map)'),
592
- __param(0, Url()),
593
- __metadata("design:type", Function),
594
- __metadata("design:paramtypes", [String]),
595
- __metadata("design:returntype", void 0)
596
- ], SwaggerController.prototype, "files", null);
597
- SwaggerController = __decorate([
598
- SwaggerExclude(),
599
- ZodSkip(),
600
- Controller('api-docs'),
601
- __param(0, Const('Moost API')),
602
- __metadata("design:paramtypes", [Object])
524
+ };`;
525
+ }
526
+ async 'spec.json'() {
527
+ const logger = useEventLogger('@moostjs/zod');
528
+ if (!this.spec) {
529
+ const { instantiate } = useControllerContext();
530
+ const moost = await instantiate(Moost);
531
+ this.spec = mapToSwaggerSpec(moost.getControllersOverview(), { title: this.title }, logger);
532
+ }
533
+ return this.spec;
534
+ }
535
+ files(url) {
536
+ return this.serve(url.split('/').pop());
537
+ }
538
+ serve(path) {
539
+ return serveFile(path, {
540
+ baseDir: this.assetPath,
541
+ cacheControl: {
542
+ public: true,
543
+ maxAge: '1w',
544
+ },
545
+ });
546
+ }
547
+ };
548
+ __decorate([
549
+ Get(''),
550
+ Get('//'),
551
+ Get('index.html'),
552
+ SetHeader('content-type', 'text/html'),
553
+ __param(0, Url()),
554
+ __param(1, HeaderHook('location')),
555
+ __param(2, StatusHook()),
556
+ __metadata("design:type", Function),
557
+ __metadata("design:paramtypes", [String, Object, Object]),
558
+ __metadata("design:returntype", void 0)
559
+ ], SwaggerController.prototype, "serveIndex", null);
560
+ __decorate([
561
+ Get(),
562
+ SetHeader('content-type', 'application/javascript'),
563
+ __metadata("design:type", Function),
564
+ __metadata("design:paramtypes", []),
565
+ __metadata("design:returntype", void 0)
566
+ ], SwaggerController.prototype, "swagger-initializer.js", null);
567
+ __decorate([
568
+ Get(),
569
+ __metadata("design:type", Function),
570
+ __metadata("design:paramtypes", []),
571
+ __metadata("design:returntype", Promise)
572
+ ], SwaggerController.prototype, "spec.json", null);
573
+ __decorate([
574
+ Get('swagger-ui-bundle.*(js|js\\.map)'),
575
+ Get('swagger-ui-standalone-preset.*(js|js\\.map)'),
576
+ Get('swagger-ui.*(css|css\\.map)'),
577
+ Get('index.*(css|css\\.map)'),
578
+ __param(0, Url()),
579
+ __metadata("design:type", Function),
580
+ __metadata("design:paramtypes", [String]),
581
+ __metadata("design:returntype", void 0)
582
+ ], SwaggerController.prototype, "files", null);
583
+ SwaggerController = __decorate([
584
+ SwaggerExclude(),
585
+ ZodSkip(),
586
+ Controller('api-docs'),
587
+ __param(0, Const('Moost API')),
588
+ __metadata("design:paramtypes", [Object])
603
589
  ], SwaggerController);
604
590
 
605
591
  export { SwaggerController, SwaggerDescription, SwaggerExclude, SwaggerRequestBody, SwaggerResponse, SwaggerTag, getSwaggerMate };