@xrystal/dto 26.6.27-v12

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 (87) hide show
  1. package/README.md +724 -0
  2. package/dist/adapters/elysia.cjs +820 -0
  3. package/dist/adapters/elysia.d.ts +138 -0
  4. package/dist/adapters/elysia.js +816 -0
  5. package/dist/adapters/express.cjs +789 -0
  6. package/dist/adapters/express.d.ts +49 -0
  7. package/dist/adapters/express.js +785 -0
  8. package/dist/adapters/index.d.ts +7 -0
  9. package/dist/adapters/node.cjs +790 -0
  10. package/dist/adapters/node.d.ts +27 -0
  11. package/dist/adapters/node.js +786 -0
  12. package/dist/adapters/shared.d.ts +11 -0
  13. package/dist/adapters/socketio.cjs +767 -0
  14. package/dist/adapters/socketio.d.ts +31 -0
  15. package/dist/adapters/socketio.js +763 -0
  16. package/dist/adapters/websocket.cjs +759 -0
  17. package/dist/adapters/websocket.d.ts +31 -0
  18. package/dist/adapters/websocket.js +754 -0
  19. package/dist/core/assemble-log.d.ts +1 -0
  20. package/dist/core/assemble-queue.d.ts +1 -0
  21. package/dist/core/assemble.d.ts +9 -0
  22. package/dist/core/builder.d.ts +49 -0
  23. package/dist/core/config.d.ts +10 -0
  24. package/dist/core/context.d.ts +5 -0
  25. package/dist/core/hooks.d.ts +8 -0
  26. package/dist/core/index.cjs +1002 -0
  27. package/dist/core/index.d.ts +14 -0
  28. package/dist/core/index.js +986 -0
  29. package/dist/core/log-dto.d.ts +1 -0
  30. package/dist/core/metadata.d.ts +6 -0
  31. package/dist/core/plugins.d.ts +10 -0
  32. package/dist/core/presets.d.ts +32 -0
  33. package/dist/core/queue-dto.d.ts +1 -0
  34. package/dist/core/response-dto.d.ts +1 -0
  35. package/dist/core/schema-utils.d.ts +1 -0
  36. package/dist/dto/index.cjs +909 -0
  37. package/dist/dto/index.d.ts +6 -0
  38. package/dist/dto/index.js +898 -0
  39. package/dist/dto/log/assemble.d.ts +3 -0
  40. package/dist/dto/log/builder.d.ts +41 -0
  41. package/dist/dto/log/index.cjs +152 -0
  42. package/dist/dto/log/index.d.ts +3 -0
  43. package/dist/dto/log/index.js +149 -0
  44. package/dist/dto/log/types.d.ts +26 -0
  45. package/dist/dto/queue/assemble.d.ts +2 -0
  46. package/dist/dto/queue/builder.d.ts +35 -0
  47. package/dist/dto/queue/index.cjs +154 -0
  48. package/dist/dto/queue/index.d.ts +3 -0
  49. package/dist/dto/queue/index.js +151 -0
  50. package/dist/dto/queue/types.d.ts +34 -0
  51. package/dist/dto/response/assemble.d.ts +1 -0
  52. package/dist/dto/response/dto.d.ts +39 -0
  53. package/dist/dto/response/index.cjs +179 -0
  54. package/dist/dto/response/index.d.ts +2 -0
  55. package/dist/dto/response/index.js +176 -0
  56. package/dist/dto/runtime/dto.cjs +1318 -0
  57. package/dist/dto/runtime/dto.d.ts +64 -0
  58. package/dist/dto/runtime/dto.js +1315 -0
  59. package/dist/dto/shared/base-dto.d.ts +12 -0
  60. package/dist/dto/shared/schema-utils.d.ts +1 -0
  61. package/dist/enums/node-env.d.ts +5 -0
  62. package/dist/errors/codes.d.ts +15 -0
  63. package/dist/errors/error.d.ts +32 -0
  64. package/dist/errors/index.d.ts +2 -0
  65. package/dist/index.cjs +1482 -0
  66. package/dist/index.d.ts +22 -0
  67. package/dist/index.js +1433 -0
  68. package/dist/types/builder.d.ts +15 -0
  69. package/dist/types/codes.d.ts +7 -0
  70. package/dist/types/context.d.ts +16 -0
  71. package/dist/types/hooks.d.ts +7 -0
  72. package/dist/types/index.d.ts +10 -0
  73. package/dist/types/log.d.ts +1 -0
  74. package/dist/types/metadata.d.ts +7 -0
  75. package/dist/types/options.d.ts +24 -0
  76. package/dist/types/plugin.d.ts +35 -0
  77. package/dist/types/queue.d.ts +1 -0
  78. package/dist/types/response.d.ts +43 -0
  79. package/dist/utils/constants/http.d.ts +2 -0
  80. package/dist/utils/constants/index.d.ts +3 -0
  81. package/dist/utils/constants/security-headers.d.ts +1 -0
  82. package/dist/utils/constants/status-codes.d.ts +35 -0
  83. package/dist/utils/helpers/index.d.ts +2 -0
  84. package/dist/utils/helpers/request-id.d.ts +3 -0
  85. package/dist/utils/helpers/uuid.d.ts +2 -0
  86. package/dist/utils/index.d.ts +2 -0
  87. package/package.json +130 -0
@@ -0,0 +1,898 @@
1
+ // src/dto/log/assemble.ts
2
+ function assembleLogBody(input) {
3
+ const ordered = {
4
+ level: input.level,
5
+ service: input.service
6
+ };
7
+ if (input.message !== void 0) {
8
+ ordered.message = input.message;
9
+ }
10
+ if (input.payload !== void 0 && Object.keys(input.payload).length > 0) {
11
+ ordered.payload = input.payload;
12
+ }
13
+ if (input.code !== void 0) {
14
+ ordered.code = input.code;
15
+ }
16
+ ordered.timestamp = input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
17
+ if (input.id !== void 0) {
18
+ ordered.id = input.id;
19
+ }
20
+ ordered.env = input.env;
21
+ return ordered;
22
+ }
23
+
24
+ // src/dto/shared/schema-utils.ts
25
+ function assertRequiredFields(input, fields, label = "Missing required fields") {
26
+ const missing = fields.filter((field) => {
27
+ const value = input[field];
28
+ return value === void 0 || value === null || value === "";
29
+ });
30
+ if (missing.length > 0) {
31
+ throw new Error(`${label}: ${missing.join(", ")}`);
32
+ }
33
+ }
34
+
35
+ // src/dto/shared/base-dto.ts
36
+ var BaseDTO = class {
37
+ };
38
+
39
+ // src/dto/log/builder.ts
40
+ var LogDTO = class _LogDTO extends BaseDTO {
41
+ _level;
42
+ _service;
43
+ _env;
44
+ _message;
45
+ _payload = {};
46
+ _code;
47
+ _timestamp;
48
+ _id;
49
+ static level(value) {
50
+ return new _LogDTO().level(value);
51
+ }
52
+ static service(value) {
53
+ return new _LogDTO().service(value);
54
+ }
55
+ static env(value) {
56
+ return new _LogDTO().env(value);
57
+ }
58
+ static message(value) {
59
+ return new _LogDTO().message(value);
60
+ }
61
+ static code(value) {
62
+ return new _LogDTO().code(value);
63
+ }
64
+ static timestamp(value) {
65
+ return new _LogDTO().timestamp(value);
66
+ }
67
+ static id(value) {
68
+ return new _LogDTO().id(value);
69
+ }
70
+ static payload(partial) {
71
+ return new _LogDTO().payload(partial);
72
+ }
73
+ /** One-shot body input — same last-wins rules as the instance `.schema()`. */
74
+ static schema(input = {}) {
75
+ return new _LogDTO().schema(input);
76
+ }
77
+ level(value) {
78
+ this._level = value;
79
+ return this;
80
+ }
81
+ service(value) {
82
+ this._service = value;
83
+ return this;
84
+ }
85
+ env(value) {
86
+ this._env = value;
87
+ return this;
88
+ }
89
+ message(value) {
90
+ this._message = value;
91
+ return this;
92
+ }
93
+ code(value) {
94
+ this._code = value;
95
+ return this;
96
+ }
97
+ timestamp(value) {
98
+ this._timestamp = value;
99
+ return this;
100
+ }
101
+ id(value) {
102
+ this._id = value;
103
+ return this;
104
+ }
105
+ payload(partial) {
106
+ this._payload = { ...this._payload, ...partial };
107
+ return this;
108
+ }
109
+ schema(input = {}) {
110
+ const { level, service, message, env, code, timestamp, id, payload } = input;
111
+ if (level !== void 0) this.level(level);
112
+ if (service !== void 0) this.service(service);
113
+ if (env !== void 0) this.env(env);
114
+ if (message !== void 0) this.message(message);
115
+ if (code !== void 0) this.code(code);
116
+ if (timestamp !== void 0) this.timestamp(timestamp);
117
+ if (id !== void 0) this.id(id);
118
+ if (payload !== void 0) {
119
+ this._payload = { ...payload };
120
+ }
121
+ return this;
122
+ }
123
+ build() {
124
+ assertRequiredFields(
125
+ {
126
+ level: this._level,
127
+ service: this._service,
128
+ env: this._env
129
+ },
130
+ ["level", "service", "env"],
131
+ "Missing log fields"
132
+ );
133
+ const input = {
134
+ level: this._level,
135
+ service: this._service,
136
+ env: this._env,
137
+ message: this._message,
138
+ code: this._code,
139
+ timestamp: this._timestamp,
140
+ id: this._id
141
+ };
142
+ if (Object.keys(this._payload).length > 0) {
143
+ input.payload = this._payload;
144
+ }
145
+ return assembleLogBody(input);
146
+ }
147
+ };
148
+
149
+ // src/dto/queue/assemble.ts
150
+ function assembleQueueMessage(metadata, payload) {
151
+ const orderedMetadata = {
152
+ source: metadata.source,
153
+ eventType: metadata.eventType,
154
+ timestamp: metadata.timestamp,
155
+ correlationId: metadata.correlationId
156
+ };
157
+ if (metadata.userId !== void 0) {
158
+ orderedMetadata.userId = metadata.userId;
159
+ }
160
+ if (metadata.extraData !== void 0) {
161
+ orderedMetadata.extraData = metadata.extraData;
162
+ }
163
+ return {
164
+ metadata: orderedMetadata,
165
+ payload
166
+ };
167
+ }
168
+
169
+ // src/utils/helpers/uuid.ts
170
+ function generateUUID() {
171
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
172
+ return crypto.randomUUID();
173
+ }
174
+ const bytes = new Uint8Array(16);
175
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
176
+ crypto.getRandomValues(bytes);
177
+ } else {
178
+ for (let i = 0; i < bytes.length; i++) {
179
+ bytes[i] = Math.floor(Math.random() * 256);
180
+ }
181
+ }
182
+ bytes[6] = bytes[6] & 15 | 64;
183
+ bytes[8] = bytes[8] & 63 | 128;
184
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
185
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
186
+ }
187
+
188
+ // src/dto/queue/builder.ts
189
+ var QueueDTO = class _QueueDTO extends BaseDTO {
190
+ _source;
191
+ _eventType;
192
+ _userId;
193
+ _correlationId;
194
+ _extraData;
195
+ _payload;
196
+ _timestamp;
197
+ static source(value) {
198
+ return new _QueueDTO().source(value);
199
+ }
200
+ static eventType(value) {
201
+ return new _QueueDTO().eventType(value);
202
+ }
203
+ static userId(value) {
204
+ return new _QueueDTO().userId(value);
205
+ }
206
+ static correlationId(value) {
207
+ return new _QueueDTO().correlationId(value);
208
+ }
209
+ static extraData(value) {
210
+ return new _QueueDTO().extraData(value);
211
+ }
212
+ static timestamp(value) {
213
+ return new _QueueDTO().timestamp(value);
214
+ }
215
+ static payload(value) {
216
+ return new _QueueDTO().payload(value);
217
+ }
218
+ static schema(input = {}) {
219
+ return new _QueueDTO().schema(input);
220
+ }
221
+ source(value) {
222
+ this._source = value;
223
+ return this;
224
+ }
225
+ eventType(value) {
226
+ this._eventType = value;
227
+ return this;
228
+ }
229
+ userId(value) {
230
+ this._userId = value;
231
+ return this;
232
+ }
233
+ correlationId(value) {
234
+ this._correlationId = value;
235
+ return this;
236
+ }
237
+ extraData(value) {
238
+ this._extraData = value;
239
+ return this;
240
+ }
241
+ timestamp(value) {
242
+ this._timestamp = value;
243
+ return this;
244
+ }
245
+ payload(value) {
246
+ this._payload = value;
247
+ return this;
248
+ }
249
+ schema(input = {}) {
250
+ const { metadata, payload } = input;
251
+ if (metadata?.source !== void 0) this.source(metadata.source);
252
+ if (metadata?.eventType !== void 0) this.eventType(metadata.eventType);
253
+ if (metadata?.userId !== void 0) this.userId(metadata.userId);
254
+ if (metadata?.correlationId !== void 0) this.correlationId(metadata.correlationId);
255
+ if (metadata?.extraData !== void 0) this.extraData(metadata.extraData);
256
+ if (payload !== void 0) {
257
+ this._payload = payload;
258
+ }
259
+ return this;
260
+ }
261
+ build() {
262
+ assertRequiredFields(
263
+ {
264
+ source: this._source,
265
+ eventType: this._eventType
266
+ },
267
+ ["source", "eventType"],
268
+ "Missing queue metadata fields"
269
+ );
270
+ return assembleQueueMessage(
271
+ {
272
+ source: this._source,
273
+ eventType: this._eventType,
274
+ timestamp: this._timestamp ?? Date.now(),
275
+ correlationId: this._correlationId ?? generateUUID(),
276
+ userId: this._userId,
277
+ extraData: this._extraData
278
+ },
279
+ this._payload
280
+ );
281
+ }
282
+ };
283
+
284
+ // src/core/assemble.ts
285
+ function assembleResponseBody(input) {
286
+ const ordered = {
287
+ status: input.status,
288
+ message: input.message
289
+ };
290
+ if (input.payload !== void 0 && Object.keys(input.payload).length > 0) {
291
+ ordered.payload = input.payload;
292
+ }
293
+ ordered.code = input.code;
294
+ return ordered;
295
+ }
296
+
297
+ // src/utils/constants/status-codes.ts
298
+ var StatusCodes = {
299
+ SUCCESSFUL: {
300
+ OK: 200,
301
+ CREATED: 201,
302
+ ACCEPTED: 202,
303
+ NO_CONTENT: 204
304
+ },
305
+ CLIENT_ERROR: {
306
+ BAD_REQUEST: 400,
307
+ UNAUTHORIZED: 401,
308
+ FORBIDDEN: 403,
309
+ NOT_FOUND: 404,
310
+ CONFLICT: 409,
311
+ UNPROCESSABLE_ENTITY: 422,
312
+ TOO_MANY_REQUESTS: 429
313
+ },
314
+ SERVER_ERROR: {
315
+ INTERNAL_SERVER_ERROR: 500,
316
+ SERVICE_UNAVAILABLE: 503,
317
+ GATEWAY_TIMEOUT: 504
318
+ }
319
+ };
320
+
321
+ // src/errors/codes.ts
322
+ var DefaultCodes = {
323
+ SUCCESS: 0,
324
+ CLIENT: 1,
325
+ SERVER: 2,
326
+ VALIDATION: 3
327
+ };
328
+ function createCodeRegistry(overrides = {}) {
329
+ return { ...DefaultCodes, ...overrides };
330
+ }
331
+ function isSuccessCode(code, codes) {
332
+ return code === codes.SUCCESS;
333
+ }
334
+ function resolveCodeFromHttpStatus(statusCode, codes) {
335
+ if (statusCode >= 200 && statusCode < 300) return codes.SUCCESS;
336
+ if (statusCode === 422) return codes.VALIDATION;
337
+ if (statusCode >= 400 && statusCode < 500) return codes.CLIENT;
338
+ if (statusCode >= 500) return codes.SERVER;
339
+ if (statusCode >= 300 && statusCode < 400) return codes.SUCCESS;
340
+ return codes.CLIENT;
341
+ }
342
+ function defaultMessageForCode(code, codes) {
343
+ if (code === codes.SUCCESS) return "Operation successful";
344
+ if (code === codes.CLIENT) return "Client error";
345
+ if (code === codes.SERVER) return "Internal server error";
346
+ if (code === codes.VALIDATION) return "Validation failed";
347
+ return "Operation failed";
348
+ }
349
+ function resolveStatusFromCode(code, codes) {
350
+ return isSuccessCode(code, codes);
351
+ }
352
+
353
+ // src/dto/response/dto.ts
354
+ var ResponseDTO = class _ResponseDTO extends BaseDTO {
355
+ _status;
356
+ _message;
357
+ _code;
358
+ _payload = {};
359
+ static status(value) {
360
+ return new _ResponseDTO().status(value);
361
+ }
362
+ static message(value) {
363
+ return new _ResponseDTO().message(value);
364
+ }
365
+ static code(value) {
366
+ return new _ResponseDTO().code(value);
367
+ }
368
+ static data(data) {
369
+ return new _ResponseDTO().data(data);
370
+ }
371
+ static payload(partial) {
372
+ return new _ResponseDTO().payload(partial);
373
+ }
374
+ static schema(input = {}, codes = DefaultCodes) {
375
+ return new _ResponseDTO().schema(input, codes);
376
+ }
377
+ status(value) {
378
+ this._status = value;
379
+ return this;
380
+ }
381
+ message(msg) {
382
+ this._message = msg;
383
+ return this;
384
+ }
385
+ code(code) {
386
+ this._code = code;
387
+ return this;
388
+ }
389
+ data(data) {
390
+ if (data === void 0) {
391
+ delete this._payload.data;
392
+ } else {
393
+ this._payload.data = data;
394
+ }
395
+ return this;
396
+ }
397
+ payload(partial) {
398
+ this._payload = { ...this._payload, ...partial };
399
+ return this;
400
+ }
401
+ setMeta(meta) {
402
+ this._payload.meta = { ...this._payload.meta ?? {}, ...meta };
403
+ return this;
404
+ }
405
+ paginate(total, page, limit) {
406
+ if (limit <= 0) {
407
+ throw new Error("ResponseDTO.paginate: limit must be greater than 0");
408
+ }
409
+ this._payload.pagination = {
410
+ total,
411
+ page,
412
+ limit,
413
+ totalPages: Math.ceil(total / limit),
414
+ hasNext: page * limit < total
415
+ };
416
+ return this;
417
+ }
418
+ schema(input = {}, codes = DefaultCodes) {
419
+ const { status, message, code, payload } = input;
420
+ if (code !== void 0) {
421
+ this.code(code);
422
+ }
423
+ if (status !== void 0) {
424
+ this.status(status);
425
+ } else if (code !== void 0) {
426
+ this.status(resolveStatusFromCode(code, codes));
427
+ }
428
+ if (message !== void 0) {
429
+ this.message(message);
430
+ }
431
+ if (payload !== void 0) {
432
+ this._payload = { ...payload };
433
+ }
434
+ return this;
435
+ }
436
+ getCode() {
437
+ return this._code;
438
+ }
439
+ getMessage() {
440
+ return this._message;
441
+ }
442
+ setCodeFromHttpStatus(httpStatusCode, codes) {
443
+ if (this._code === void 0) {
444
+ this._code = resolveCodeFromHttpStatus(httpStatusCode, codes);
445
+ }
446
+ return this;
447
+ }
448
+ transformData(fn) {
449
+ const next = new _ResponseDTO();
450
+ next._status = this._status;
451
+ next._message = this._message;
452
+ next._code = this._code;
453
+ next._payload = { ...this._payload };
454
+ if (this._payload.data !== void 0) {
455
+ next._payload.data = fn(this._payload.data);
456
+ }
457
+ return next;
458
+ }
459
+ build(options = {}) {
460
+ const codes = options.codes ?? DefaultCodes;
461
+ const code = this._code ?? (options.httpStatusCode !== void 0 ? resolveCodeFromHttpStatus(options.httpStatusCode, codes) : codes.SUCCESS);
462
+ const status = this._status ?? isSuccessCode(code, codes);
463
+ const message = this._message ?? defaultMessageForCode(code, codes);
464
+ if (options.withDefaultBody === false) {
465
+ return assembleResponseBody({ status, message, code });
466
+ }
467
+ const payload = this.buildPayload();
468
+ return assembleResponseBody({
469
+ status,
470
+ message,
471
+ payload,
472
+ code
473
+ });
474
+ }
475
+ buildPayload() {
476
+ const entries = Object.entries(this._payload).filter(([, value]) => value !== void 0);
477
+ if (entries.length === 0) return void 0;
478
+ return Object.fromEntries(entries);
479
+ }
480
+ };
481
+
482
+ // src/core/metadata.ts
483
+ var MetadataFactory = class {
484
+ static create(options = {}, context) {
485
+ return {
486
+ requestId: context?.requestId ?? generateUUID(),
487
+ serverTime: (/* @__PURE__ */ new Date()).toISOString(),
488
+ statusCode: 200,
489
+ ...options
490
+ };
491
+ }
492
+ };
493
+
494
+ // src/core/plugins.ts
495
+ function sortPlugins(plugins) {
496
+ return [...plugins].sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
497
+ }
498
+ var PluginRegistry = class {
499
+ plugins;
500
+ constructor(plugins = []) {
501
+ this.plugins = sortPlugins(plugins);
502
+ }
503
+ runBeforeBuild(ctx) {
504
+ for (const plugin of this.plugins) {
505
+ plugin.beforeBuild?.(ctx);
506
+ }
507
+ }
508
+ runAfterBuild(result, ctx) {
509
+ let current = result;
510
+ for (const plugin of this.plugins) {
511
+ const next = plugin.afterBuild?.(current, ctx);
512
+ if (next) current = next;
513
+ }
514
+ return current;
515
+ }
516
+ runBeforeDispatch(result, ctx) {
517
+ let current = result;
518
+ for (const plugin of this.plugins) {
519
+ const next = plugin.beforeDispatch?.(current, ctx);
520
+ if (next) current = next;
521
+ }
522
+ return current;
523
+ }
524
+ runAfterDispatch(result, ctx) {
525
+ for (const plugin of this.plugins) {
526
+ plugin.afterDispatch?.(result, ctx);
527
+ }
528
+ }
529
+ };
530
+
531
+ // src/core/presets.ts
532
+ var ResponsePresets = class {
533
+ builder;
534
+ codes;
535
+ constructor(builder, codes) {
536
+ this.builder = builder;
537
+ this.codes = codes;
538
+ }
539
+ applyExtras(extras) {
540
+ if (extras && Object.keys(extras).length > 0) {
541
+ this.builder.payload(extras);
542
+ }
543
+ }
544
+ dispatch() {
545
+ return this.builder.build();
546
+ }
547
+ resolveFailureArgs(dataOrMessage, messageOrExtras, extras) {
548
+ if (typeof dataOrMessage === "string") {
549
+ return {
550
+ message: dataOrMessage,
551
+ extras: typeof messageOrExtras === "string" ? extras : messageOrExtras
552
+ };
553
+ }
554
+ return {
555
+ data: dataOrMessage,
556
+ message: typeof messageOrExtras === "string" ? messageOrExtras : void 0,
557
+ extras: typeof messageOrExtras === "string" ? extras : messageOrExtras
558
+ };
559
+ }
560
+ failure(httpStatus, code, dataOrMessage, messageOrExtras, extras) {
561
+ const resolved = this.resolveFailureArgs(dataOrMessage, messageOrExtras, extras);
562
+ this.builder.httpStatus(httpStatus).code(code).status(false).message(resolved.message ?? defaultMessageForCode(code, this.codes)).data(resolved.data);
563
+ this.applyExtras(resolved.extras);
564
+ return this.dispatch();
565
+ }
566
+ ok(data, message, extras) {
567
+ this.builder.httpStatus(StatusCodes.SUCCESSFUL.OK).code(this.codes.SUCCESS).status(true).message(message ?? defaultMessageForCode(this.codes.SUCCESS, this.codes)).data(data);
568
+ this.applyExtras(extras);
569
+ return this.dispatch();
570
+ }
571
+ created(data, message, extras) {
572
+ this.builder.httpStatus(StatusCodes.SUCCESSFUL.CREATED).code(this.codes.SUCCESS).status(true).message(message ?? defaultMessageForCode(this.codes.SUCCESS, this.codes)).data(data);
573
+ this.applyExtras(extras);
574
+ return this.dispatch();
575
+ }
576
+ accepted(message, extras) {
577
+ this.builder.httpStatus(StatusCodes.SUCCESSFUL.ACCEPTED).code(this.codes.SUCCESS).status(true).message(message ?? defaultMessageForCode(this.codes.SUCCESS, this.codes));
578
+ this.applyExtras(extras);
579
+ return this.dispatch();
580
+ }
581
+ noContent(extras) {
582
+ this.builder.httpStatus(StatusCodes.SUCCESSFUL.NO_CONTENT).code(this.codes.SUCCESS).status(true).message("").data(void 0);
583
+ this.applyExtras(extras);
584
+ return this.dispatch();
585
+ }
586
+ /** Generic client failure — HTTP 400, CLIENT code */
587
+ fail(dataOrMessage, messageOrExtras, extras) {
588
+ return this.failure(StatusCodes.CLIENT_ERROR.BAD_REQUEST, this.codes.CLIENT, dataOrMessage, messageOrExtras, extras);
589
+ }
590
+ /** Generic server failure — HTTP 500, SERVER code */
591
+ error(dataOrMessage, messageOrExtras, extras) {
592
+ return this.failure(
593
+ StatusCodes.SERVER_ERROR.INTERNAL_SERVER_ERROR,
594
+ this.codes.SERVER,
595
+ dataOrMessage,
596
+ messageOrExtras,
597
+ extras
598
+ );
599
+ }
600
+ badRequest(dataOrMessage, messageOrExtras, extras) {
601
+ return this.failure(StatusCodes.CLIENT_ERROR.BAD_REQUEST, this.codes.CLIENT, dataOrMessage, messageOrExtras, extras);
602
+ }
603
+ unauthorized(dataOrMessage, messageOrExtras, extras) {
604
+ return this.failure(StatusCodes.CLIENT_ERROR.UNAUTHORIZED, this.codes.CLIENT, dataOrMessage, messageOrExtras, extras);
605
+ }
606
+ forbidden(dataOrMessage, messageOrExtras, extras) {
607
+ return this.failure(StatusCodes.CLIENT_ERROR.FORBIDDEN, this.codes.CLIENT, dataOrMessage, messageOrExtras, extras);
608
+ }
609
+ notFound(dataOrMessage, messageOrExtras, extras) {
610
+ return this.failure(StatusCodes.CLIENT_ERROR.NOT_FOUND, this.codes.CLIENT, dataOrMessage, messageOrExtras, extras);
611
+ }
612
+ conflict(dataOrMessage, messageOrExtras, extras) {
613
+ return this.failure(StatusCodes.CLIENT_ERROR.CONFLICT, this.codes.CLIENT, dataOrMessage, messageOrExtras, extras);
614
+ }
615
+ unprocessable(dataOrMessage, messageOrExtras, extras) {
616
+ return this.failure(
617
+ StatusCodes.CLIENT_ERROR.UNPROCESSABLE_ENTITY,
618
+ this.codes.VALIDATION,
619
+ dataOrMessage,
620
+ messageOrExtras,
621
+ extras
622
+ );
623
+ }
624
+ tooManyRequests(dataOrMessage, messageOrExtras, extras) {
625
+ return this.failure(StatusCodes.CLIENT_ERROR.TOO_MANY_REQUESTS, this.codes.CLIENT, dataOrMessage, messageOrExtras, extras);
626
+ }
627
+ internalServerError(dataOrMessage, messageOrExtras, extras) {
628
+ return this.failure(
629
+ StatusCodes.SERVER_ERROR.INTERNAL_SERVER_ERROR,
630
+ this.codes.SERVER,
631
+ dataOrMessage,
632
+ messageOrExtras,
633
+ extras
634
+ );
635
+ }
636
+ serviceUnavailable(dataOrMessage, messageOrExtras, extras) {
637
+ return this.failure(
638
+ StatusCodes.SERVER_ERROR.SERVICE_UNAVAILABLE,
639
+ this.codes.SERVER,
640
+ dataOrMessage,
641
+ messageOrExtras,
642
+ extras
643
+ );
644
+ }
645
+ gatewayTimeout(dataOrMessage, messageOrExtras, extras) {
646
+ return this.failure(
647
+ StatusCodes.SERVER_ERROR.GATEWAY_TIMEOUT,
648
+ this.codes.SERVER,
649
+ dataOrMessage,
650
+ messageOrExtras,
651
+ extras
652
+ );
653
+ }
654
+ };
655
+
656
+ // src/core/config.ts
657
+ function resolveBuilderConfig(options = {}) {
658
+ return {
659
+ verbose: options.verbose === true,
660
+ includeStack: options.includeStack,
661
+ withDefaultBody: options.withDefaultBody !== false,
662
+ codes: createCodeRegistry(options.codes),
663
+ hooks: options.hooks,
664
+ plugins: options.plugins ?? []
665
+ };
666
+ }
667
+
668
+ // src/errors/error.ts
669
+ var ResponseError = class extends Error {
670
+ code;
671
+ httpStatus;
672
+ payload;
673
+ constructor(options = {}) {
674
+ const codes = createCodeRegistry(options.codes);
675
+ const code = options.code ?? codes.SERVER;
676
+ const message = options.message ?? defaultMessageForCode(code, codes);
677
+ super(message, { cause: options.cause });
678
+ this.name = "ResponseError";
679
+ this.code = code;
680
+ this.httpStatus = options.httpStatus ?? codeToDefaultHttpStatus(code, codes);
681
+ if (options.payload !== void 0) {
682
+ this.payload = options.payload;
683
+ }
684
+ }
685
+ toJSON() {
686
+ return {
687
+ name: this.name,
688
+ message: this.message,
689
+ code: this.code,
690
+ httpStatus: this.httpStatus,
691
+ payload: this.payload
692
+ };
693
+ }
694
+ };
695
+ function isResponseError(value) {
696
+ return value instanceof ResponseError;
697
+ }
698
+ function codeToDefaultHttpStatus(code, codes) {
699
+ if (code === codes.SUCCESS) return 200;
700
+ if (code === codes.CLIENT) return 400;
701
+ if (code === codes.SERVER) return 500;
702
+ if (code === codes.VALIDATION) return 422;
703
+ return 500;
704
+ }
705
+
706
+ // src/core/builder.ts
707
+ var Builder = class {
708
+ dispatcher;
709
+ options;
710
+ context;
711
+ plugins;
712
+ body;
713
+ _statusCode = StatusCodes.SUCCESSFUL.OK;
714
+ _headers = {};
715
+ _cookies = [];
716
+ _presets;
717
+ constructor(dispatcher, options = {}, context) {
718
+ this.dispatcher = dispatcher;
719
+ this.options = resolveBuilderConfig(options);
720
+ this.context = context;
721
+ this.plugins = new PluginRegistry(this.options.plugins);
722
+ this.body = new ResponseDTO();
723
+ }
724
+ get dto() {
725
+ return this.body;
726
+ }
727
+ httpStatus(code) {
728
+ this._statusCode = code;
729
+ this.body.setCodeFromHttpStatus(code, this.options.codes);
730
+ return this;
731
+ }
732
+ code(code) {
733
+ this.body.code(code);
734
+ return this;
735
+ }
736
+ status(value) {
737
+ this.body.status(value);
738
+ return this;
739
+ }
740
+ message(msg) {
741
+ this.body.message(msg);
742
+ return this;
743
+ }
744
+ data(data) {
745
+ this.body.data(data);
746
+ return this;
747
+ }
748
+ payload(partial) {
749
+ this.body.payload(partial);
750
+ return this;
751
+ }
752
+ schema(input = {}) {
753
+ this.body.schema(input, this.options.codes);
754
+ return this;
755
+ }
756
+ setMeta(meta) {
757
+ this.body.setMeta(meta);
758
+ return this;
759
+ }
760
+ withMetadata(options = {}) {
761
+ const generated = MetadataFactory.create(
762
+ { statusCode: this._statusCode, ...options },
763
+ { requestId: this.context?.requestId }
764
+ );
765
+ return this.setMeta(generated);
766
+ }
767
+ paginate(total, page, limit) {
768
+ this.body.paginate(total, page, limit);
769
+ return this;
770
+ }
771
+ setHeaders(keyOrHeaders, value) {
772
+ if (typeof keyOrHeaders === "string") {
773
+ if (value !== void 0) {
774
+ this._headers[keyOrHeaders] = value;
775
+ }
776
+ } else {
777
+ this._headers = { ...this._headers, ...keyOrHeaders };
778
+ }
779
+ return this;
780
+ }
781
+ header(key, value) {
782
+ return this.setHeaders(key, value);
783
+ }
784
+ setCookies(nameOrCookies, valueOrOptions, options) {
785
+ if (typeof nameOrCookies === "string") {
786
+ if (typeof valueOrOptions === "string") {
787
+ this._cookies.push({ name: nameOrCookies, value: valueOrOptions, options });
788
+ }
789
+ } else {
790
+ const sharedOptions = typeof valueOrOptions === "object" ? valueOrOptions : void 0;
791
+ for (const [name, value] of Object.entries(nameOrCookies)) {
792
+ this._cookies.push({ name, value, options: sharedOptions });
793
+ }
794
+ }
795
+ return this;
796
+ }
797
+ fromError(error) {
798
+ if (isResponseError(error)) {
799
+ return this.httpStatus(error.httpStatus).code(error.code).message(error.message).payload(error.payload ? { ...error.payload } : {}).data(void 0);
800
+ }
801
+ return this.httpStatus(StatusCodes.SERVER_ERROR.INTERNAL_SERVER_ERROR).code(this.options.codes.SERVER).message(this.resolvePublicErrorMessage(error)).data(void 0);
802
+ }
803
+ async wrap(promise) {
804
+ try {
805
+ this.data(await promise);
806
+ return this;
807
+ } catch (error) {
808
+ this.fromError(error);
809
+ this.options.hooks?.emit("error", {
810
+ error,
811
+ message: this.body.getMessage(),
812
+ statusCode: this._statusCode,
813
+ code: this.body.getCode() ?? resolveCodeFromHttpStatus(this._statusCode, this.options.codes)
814
+ });
815
+ return this;
816
+ }
817
+ }
818
+ transform(fn) {
819
+ const next = this;
820
+ next.body = this.body.transformData(fn);
821
+ return next;
822
+ }
823
+ when(condition, fn) {
824
+ if (condition) fn(this);
825
+ return this;
826
+ }
827
+ get as() {
828
+ if (!this._presets) {
829
+ this._presets = new ResponsePresets(this, this.options.codes);
830
+ }
831
+ return this._presets;
832
+ }
833
+ build() {
834
+ const pluginCtx = this.createPluginContext();
835
+ this.options.hooks?.emit("before_build", { statusCode: this._statusCode });
836
+ this.plugins.runBeforeBuild(pluginCtx);
837
+ const body = this.body.build({
838
+ codes: this.options.codes,
839
+ withDefaultBody: this.options.withDefaultBody,
840
+ httpStatusCode: this._statusCode
841
+ });
842
+ let result = {
843
+ body,
844
+ statusCode: this._statusCode,
845
+ headers: { ...this._headers },
846
+ cookies: [...this._cookies]
847
+ };
848
+ result = this.plugins.runAfterBuild(result, pluginCtx);
849
+ this.emitHook("after_build", result);
850
+ if (this.dispatcher) {
851
+ result = this.plugins.runBeforeDispatch(result, pluginCtx);
852
+ this.emitHook("before_dispatch", result);
853
+ const dispatched = this.dispatcher.dispatch(result);
854
+ this.plugins.runAfterDispatch(result, pluginCtx);
855
+ this.emitHook("after_dispatch", result);
856
+ return dispatched ?? result;
857
+ }
858
+ return result;
859
+ }
860
+ resolvePublicErrorMessage(error) {
861
+ if (!this.options.verbose && !isResponseError(error)) {
862
+ return defaultMessageForCode(this.options.codes.SERVER, this.options.codes);
863
+ }
864
+ if (error instanceof Error) {
865
+ if (this.options.includeStack && error.stack) return error.stack;
866
+ return error.message || defaultMessageForCode(this.options.codes.SERVER, this.options.codes);
867
+ }
868
+ if (typeof error === "string") return error;
869
+ return defaultMessageForCode(this.options.codes.SERVER, this.options.codes);
870
+ }
871
+ createPluginContext() {
872
+ return {
873
+ builder: this,
874
+ context: this.context,
875
+ options: this.options,
876
+ codes: this.options.codes
877
+ };
878
+ }
879
+ emitHook(event, result) {
880
+ const hooks = this.options.hooks;
881
+ if (!hooks?.hasListeners(event)) return;
882
+ hooks.emit(event, structuredClone(result));
883
+ }
884
+ };
885
+ function createBuilderProxy(dispatcher, options = {}, context) {
886
+ const instance = new Builder(dispatcher, options, context);
887
+ return new Proxy(instance, {
888
+ get(target, prop, receiver) {
889
+ const value = Reflect.get(target, prop, receiver);
890
+ if (typeof value === "function") {
891
+ return value.bind(target);
892
+ }
893
+ return value;
894
+ }
895
+ });
896
+ }
897
+
898
+ export { BaseDTO, Builder, LogDTO, QueueDTO, ResponseDTO, ResponsePresets, assembleLogBody, assembleQueueMessage, assembleResponseBody, createBuilderProxy };