@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,1318 @@
1
+ 'use strict';
2
+
3
+ var elysia = require('elysia');
4
+
5
+ // src/dto/log/assemble.ts
6
+ function assembleLogBody(input) {
7
+ const ordered = {
8
+ level: input.level,
9
+ service: input.service
10
+ };
11
+ if (input.message !== void 0) {
12
+ ordered.message = input.message;
13
+ }
14
+ if (input.payload !== void 0 && Object.keys(input.payload).length > 0) {
15
+ ordered.payload = input.payload;
16
+ }
17
+ if (input.code !== void 0) {
18
+ ordered.code = input.code;
19
+ }
20
+ ordered.timestamp = input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
21
+ if (input.id !== void 0) {
22
+ ordered.id = input.id;
23
+ }
24
+ ordered.env = input.env;
25
+ return ordered;
26
+ }
27
+
28
+ // src/dto/shared/schema-utils.ts
29
+ function assertRequiredFields(input, fields, label = "Missing required fields") {
30
+ const missing = fields.filter((field) => {
31
+ const value = input[field];
32
+ return value === void 0 || value === null || value === "";
33
+ });
34
+ if (missing.length > 0) {
35
+ throw new Error(`${label}: ${missing.join(", ")}`);
36
+ }
37
+ }
38
+
39
+ // src/dto/shared/base-dto.ts
40
+ var BaseDTO = class {
41
+ };
42
+
43
+ // src/dto/log/builder.ts
44
+ var LogDTO = class _LogDTO extends BaseDTO {
45
+ _level;
46
+ _service;
47
+ _env;
48
+ _message;
49
+ _payload = {};
50
+ _code;
51
+ _timestamp;
52
+ _id;
53
+ static level(value) {
54
+ return new _LogDTO().level(value);
55
+ }
56
+ static service(value) {
57
+ return new _LogDTO().service(value);
58
+ }
59
+ static env(value) {
60
+ return new _LogDTO().env(value);
61
+ }
62
+ static message(value) {
63
+ return new _LogDTO().message(value);
64
+ }
65
+ static code(value) {
66
+ return new _LogDTO().code(value);
67
+ }
68
+ static timestamp(value) {
69
+ return new _LogDTO().timestamp(value);
70
+ }
71
+ static id(value) {
72
+ return new _LogDTO().id(value);
73
+ }
74
+ static payload(partial) {
75
+ return new _LogDTO().payload(partial);
76
+ }
77
+ /** One-shot body input — same last-wins rules as the instance `.schema()`. */
78
+ static schema(input = {}) {
79
+ return new _LogDTO().schema(input);
80
+ }
81
+ level(value) {
82
+ this._level = value;
83
+ return this;
84
+ }
85
+ service(value) {
86
+ this._service = value;
87
+ return this;
88
+ }
89
+ env(value) {
90
+ this._env = value;
91
+ return this;
92
+ }
93
+ message(value) {
94
+ this._message = value;
95
+ return this;
96
+ }
97
+ code(value) {
98
+ this._code = value;
99
+ return this;
100
+ }
101
+ timestamp(value) {
102
+ this._timestamp = value;
103
+ return this;
104
+ }
105
+ id(value) {
106
+ this._id = value;
107
+ return this;
108
+ }
109
+ payload(partial) {
110
+ this._payload = { ...this._payload, ...partial };
111
+ return this;
112
+ }
113
+ schema(input = {}) {
114
+ const { level, service, message, env, code, timestamp, id, payload } = input;
115
+ if (level !== void 0) this.level(level);
116
+ if (service !== void 0) this.service(service);
117
+ if (env !== void 0) this.env(env);
118
+ if (message !== void 0) this.message(message);
119
+ if (code !== void 0) this.code(code);
120
+ if (timestamp !== void 0) this.timestamp(timestamp);
121
+ if (id !== void 0) this.id(id);
122
+ if (payload !== void 0) {
123
+ this._payload = { ...payload };
124
+ }
125
+ return this;
126
+ }
127
+ build() {
128
+ assertRequiredFields(
129
+ {
130
+ level: this._level,
131
+ service: this._service,
132
+ env: this._env
133
+ },
134
+ ["level", "service", "env"],
135
+ "Missing log fields"
136
+ );
137
+ const input = {
138
+ level: this._level,
139
+ service: this._service,
140
+ env: this._env,
141
+ message: this._message,
142
+ code: this._code,
143
+ timestamp: this._timestamp,
144
+ id: this._id
145
+ };
146
+ if (Object.keys(this._payload).length > 0) {
147
+ input.payload = this._payload;
148
+ }
149
+ return assembleLogBody(input);
150
+ }
151
+ };
152
+
153
+ // src/utils/helpers/uuid.ts
154
+ function generateUUID() {
155
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
156
+ return crypto.randomUUID();
157
+ }
158
+ const bytes = new Uint8Array(16);
159
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
160
+ crypto.getRandomValues(bytes);
161
+ } else {
162
+ for (let i = 0; i < bytes.length; i++) {
163
+ bytes[i] = Math.floor(Math.random() * 256);
164
+ }
165
+ }
166
+ bytes[6] = bytes[6] & 15 | 64;
167
+ bytes[8] = bytes[8] & 63 | 128;
168
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
169
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
170
+ }
171
+ function isValidUUID(id) {
172
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id);
173
+ }
174
+
175
+ // src/dto/queue/assemble.ts
176
+ function assembleQueueMessage(metadata, payload) {
177
+ const orderedMetadata = {
178
+ source: metadata.source,
179
+ eventType: metadata.eventType,
180
+ timestamp: metadata.timestamp,
181
+ correlationId: metadata.correlationId
182
+ };
183
+ if (metadata.userId !== void 0) {
184
+ orderedMetadata.userId = metadata.userId;
185
+ }
186
+ if (metadata.extraData !== void 0) {
187
+ orderedMetadata.extraData = metadata.extraData;
188
+ }
189
+ return {
190
+ metadata: orderedMetadata,
191
+ payload
192
+ };
193
+ }
194
+
195
+ // src/dto/queue/builder.ts
196
+ var QueueDTO = class _QueueDTO extends BaseDTO {
197
+ _source;
198
+ _eventType;
199
+ _userId;
200
+ _correlationId;
201
+ _extraData;
202
+ _payload;
203
+ _timestamp;
204
+ static source(value) {
205
+ return new _QueueDTO().source(value);
206
+ }
207
+ static eventType(value) {
208
+ return new _QueueDTO().eventType(value);
209
+ }
210
+ static userId(value) {
211
+ return new _QueueDTO().userId(value);
212
+ }
213
+ static correlationId(value) {
214
+ return new _QueueDTO().correlationId(value);
215
+ }
216
+ static extraData(value) {
217
+ return new _QueueDTO().extraData(value);
218
+ }
219
+ static timestamp(value) {
220
+ return new _QueueDTO().timestamp(value);
221
+ }
222
+ static payload(value) {
223
+ return new _QueueDTO().payload(value);
224
+ }
225
+ static schema(input = {}) {
226
+ return new _QueueDTO().schema(input);
227
+ }
228
+ source(value) {
229
+ this._source = value;
230
+ return this;
231
+ }
232
+ eventType(value) {
233
+ this._eventType = value;
234
+ return this;
235
+ }
236
+ userId(value) {
237
+ this._userId = value;
238
+ return this;
239
+ }
240
+ correlationId(value) {
241
+ this._correlationId = value;
242
+ return this;
243
+ }
244
+ extraData(value) {
245
+ this._extraData = value;
246
+ return this;
247
+ }
248
+ timestamp(value) {
249
+ this._timestamp = value;
250
+ return this;
251
+ }
252
+ payload(value) {
253
+ this._payload = value;
254
+ return this;
255
+ }
256
+ schema(input = {}) {
257
+ const { metadata, payload } = input;
258
+ if (metadata?.source !== void 0) this.source(metadata.source);
259
+ if (metadata?.eventType !== void 0) this.eventType(metadata.eventType);
260
+ if (metadata?.userId !== void 0) this.userId(metadata.userId);
261
+ if (metadata?.correlationId !== void 0) this.correlationId(metadata.correlationId);
262
+ if (metadata?.extraData !== void 0) this.extraData(metadata.extraData);
263
+ if (payload !== void 0) {
264
+ this._payload = payload;
265
+ }
266
+ return this;
267
+ }
268
+ build() {
269
+ assertRequiredFields(
270
+ {
271
+ source: this._source,
272
+ eventType: this._eventType
273
+ },
274
+ ["source", "eventType"],
275
+ "Missing queue metadata fields"
276
+ );
277
+ return assembleQueueMessage(
278
+ {
279
+ source: this._source,
280
+ eventType: this._eventType,
281
+ timestamp: this._timestamp ?? Date.now(),
282
+ correlationId: this._correlationId ?? generateUUID(),
283
+ userId: this._userId,
284
+ extraData: this._extraData
285
+ },
286
+ this._payload
287
+ );
288
+ }
289
+ };
290
+
291
+ // src/utils/constants/status-codes.ts
292
+ var StatusCodes = {
293
+ SUCCESSFUL: {
294
+ OK: 200,
295
+ CREATED: 201,
296
+ ACCEPTED: 202,
297
+ NO_CONTENT: 204
298
+ },
299
+ CLIENT_ERROR: {
300
+ BAD_REQUEST: 400,
301
+ UNAUTHORIZED: 401,
302
+ FORBIDDEN: 403,
303
+ NOT_FOUND: 404,
304
+ CONFLICT: 409,
305
+ UNPROCESSABLE_ENTITY: 422,
306
+ TOO_MANY_REQUESTS: 429
307
+ },
308
+ SERVER_ERROR: {
309
+ INTERNAL_SERVER_ERROR: 500,
310
+ SERVICE_UNAVAILABLE: 503,
311
+ GATEWAY_TIMEOUT: 504
312
+ }
313
+ };
314
+
315
+ // src/errors/codes.ts
316
+ var DefaultCodes = {
317
+ SUCCESS: 0,
318
+ CLIENT: 1,
319
+ SERVER: 2,
320
+ VALIDATION: 3
321
+ };
322
+ function createCodeRegistry(overrides = {}) {
323
+ return { ...DefaultCodes, ...overrides };
324
+ }
325
+ function isSuccessCode(code, codes) {
326
+ return code === codes.SUCCESS;
327
+ }
328
+ function resolveCodeFromHttpStatus(statusCode, codes) {
329
+ if (statusCode >= 200 && statusCode < 300) return codes.SUCCESS;
330
+ if (statusCode === 422) return codes.VALIDATION;
331
+ if (statusCode >= 400 && statusCode < 500) return codes.CLIENT;
332
+ if (statusCode >= 500) return codes.SERVER;
333
+ if (statusCode >= 300 && statusCode < 400) return codes.SUCCESS;
334
+ return codes.CLIENT;
335
+ }
336
+ function defaultMessageForCode(code, codes) {
337
+ if (code === codes.SUCCESS) return "Operation successful";
338
+ if (code === codes.CLIENT) return "Client error";
339
+ if (code === codes.SERVER) return "Internal server error";
340
+ if (code === codes.VALIDATION) return "Validation failed";
341
+ return "Operation failed";
342
+ }
343
+ function resolveStatusFromCode(code, codes) {
344
+ return isSuccessCode(code, codes);
345
+ }
346
+
347
+ // src/core/assemble.ts
348
+ function assembleResponseBody(input) {
349
+ const ordered = {
350
+ status: input.status,
351
+ message: input.message
352
+ };
353
+ if (input.payload !== void 0 && Object.keys(input.payload).length > 0) {
354
+ ordered.payload = input.payload;
355
+ }
356
+ ordered.code = input.code;
357
+ return ordered;
358
+ }
359
+
360
+ // src/dto/response/dto.ts
361
+ var ResponseDTO = class _ResponseDTO extends BaseDTO {
362
+ _status;
363
+ _message;
364
+ _code;
365
+ _payload = {};
366
+ static status(value) {
367
+ return new _ResponseDTO().status(value);
368
+ }
369
+ static message(value) {
370
+ return new _ResponseDTO().message(value);
371
+ }
372
+ static code(value) {
373
+ return new _ResponseDTO().code(value);
374
+ }
375
+ static data(data) {
376
+ return new _ResponseDTO().data(data);
377
+ }
378
+ static payload(partial) {
379
+ return new _ResponseDTO().payload(partial);
380
+ }
381
+ static schema(input = {}, codes = DefaultCodes) {
382
+ return new _ResponseDTO().schema(input, codes);
383
+ }
384
+ status(value) {
385
+ this._status = value;
386
+ return this;
387
+ }
388
+ message(msg) {
389
+ this._message = msg;
390
+ return this;
391
+ }
392
+ code(code) {
393
+ this._code = code;
394
+ return this;
395
+ }
396
+ data(data) {
397
+ if (data === void 0) {
398
+ delete this._payload.data;
399
+ } else {
400
+ this._payload.data = data;
401
+ }
402
+ return this;
403
+ }
404
+ payload(partial) {
405
+ this._payload = { ...this._payload, ...partial };
406
+ return this;
407
+ }
408
+ setMeta(meta) {
409
+ this._payload.meta = { ...this._payload.meta ?? {}, ...meta };
410
+ return this;
411
+ }
412
+ paginate(total, page, limit) {
413
+ if (limit <= 0) {
414
+ throw new Error("ResponseDTO.paginate: limit must be greater than 0");
415
+ }
416
+ this._payload.pagination = {
417
+ total,
418
+ page,
419
+ limit,
420
+ totalPages: Math.ceil(total / limit),
421
+ hasNext: page * limit < total
422
+ };
423
+ return this;
424
+ }
425
+ schema(input = {}, codes = DefaultCodes) {
426
+ const { status, message, code, payload } = input;
427
+ if (code !== void 0) {
428
+ this.code(code);
429
+ }
430
+ if (status !== void 0) {
431
+ this.status(status);
432
+ } else if (code !== void 0) {
433
+ this.status(resolveStatusFromCode(code, codes));
434
+ }
435
+ if (message !== void 0) {
436
+ this.message(message);
437
+ }
438
+ if (payload !== void 0) {
439
+ this._payload = { ...payload };
440
+ }
441
+ return this;
442
+ }
443
+ getCode() {
444
+ return this._code;
445
+ }
446
+ getMessage() {
447
+ return this._message;
448
+ }
449
+ setCodeFromHttpStatus(httpStatusCode, codes) {
450
+ if (this._code === void 0) {
451
+ this._code = resolveCodeFromHttpStatus(httpStatusCode, codes);
452
+ }
453
+ return this;
454
+ }
455
+ transformData(fn) {
456
+ const next = new _ResponseDTO();
457
+ next._status = this._status;
458
+ next._message = this._message;
459
+ next._code = this._code;
460
+ next._payload = { ...this._payload };
461
+ if (this._payload.data !== void 0) {
462
+ next._payload.data = fn(this._payload.data);
463
+ }
464
+ return next;
465
+ }
466
+ build(options = {}) {
467
+ const codes = options.codes ?? DefaultCodes;
468
+ const code = this._code ?? (options.httpStatusCode !== void 0 ? resolveCodeFromHttpStatus(options.httpStatusCode, codes) : codes.SUCCESS);
469
+ const status = this._status ?? isSuccessCode(code, codes);
470
+ const message = this._message ?? defaultMessageForCode(code, codes);
471
+ if (options.withDefaultBody === false) {
472
+ return assembleResponseBody({ status, message, code });
473
+ }
474
+ const payload = this.buildPayload();
475
+ return assembleResponseBody({
476
+ status,
477
+ message,
478
+ payload,
479
+ code
480
+ });
481
+ }
482
+ buildPayload() {
483
+ const entries = Object.entries(this._payload).filter(([, value]) => value !== void 0);
484
+ if (entries.length === 0) return void 0;
485
+ return Object.fromEntries(entries);
486
+ }
487
+ };
488
+
489
+ // src/utils/constants/security-headers.ts
490
+ var DEFAULT_SECURITY_HEADERS = {
491
+ "X-Content-Type-Options": "nosniff",
492
+ "X-Frame-Options": "DENY",
493
+ "Referrer-Policy": "strict-origin-when-cross-origin",
494
+ "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none';",
495
+ "Cross-Origin-Opener-Policy": "same-origin",
496
+ "Cache-Control": "no-store",
497
+ Pragma: "no-cache",
498
+ "X-DNS-Prefetch-Control": "off"
499
+ };
500
+
501
+ // src/utils/constants/http.ts
502
+ var NO_BODY_STATUS_CODES = /* @__PURE__ */ new Set([204, 205, 304]);
503
+ function shouldSendResponseBody(statusCode) {
504
+ return !NO_BODY_STATUS_CODES.has(statusCode);
505
+ }
506
+
507
+ // src/utils/helpers/request-id.ts
508
+ var DEFAULT_REQUEST_ID_HEADERS = [
509
+ "x-request-id",
510
+ "x-correlation-id",
511
+ "traceparent"
512
+ ];
513
+ function readHeader(req, name) {
514
+ const fromGet = req.get?.(name);
515
+ if (fromGet) return fromGet;
516
+ const headers = req.headers;
517
+ if (!headers) return void 0;
518
+ const direct = headers[name] ?? headers[name.toLowerCase()];
519
+ if (direct === void 0) return void 0;
520
+ return Array.isArray(direct) ? direct[0] : direct;
521
+ }
522
+ function traceIdFromTraceparent(traceparent) {
523
+ const parts = traceparent.trim().split("-");
524
+ if (parts.length < 2) return void 0;
525
+ const traceId = parts[1];
526
+ if (!traceId || !/^[0-9a-f]{32}$/i.test(traceId)) return void 0;
527
+ return `${traceId.slice(0, 8)}-${traceId.slice(8, 12)}-${traceId.slice(12, 16)}-${traceId.slice(16, 20)}-${traceId.slice(20)}`;
528
+ }
529
+ function resolveRequestId(req, headerNames = DEFAULT_REQUEST_ID_HEADERS) {
530
+ for (const name of headerNames) {
531
+ const raw = readHeader(req, name);
532
+ if (!raw?.trim()) continue;
533
+ if (name === "traceparent") {
534
+ const traceId = traceIdFromTraceparent(raw);
535
+ if (traceId) return traceId;
536
+ continue;
537
+ }
538
+ const id = raw.trim();
539
+ if (isValidUUID(id)) return id;
540
+ return id;
541
+ }
542
+ return generateUUID();
543
+ }
544
+
545
+ // src/core/context.ts
546
+ var ContextFactory = class {
547
+ static create(req, options = {}) {
548
+ return {
549
+ requestId: resolveRequestId(req, options.requestIdHeaders),
550
+ startTime: Date.now()
551
+ };
552
+ }
553
+ static fromId(requestId) {
554
+ return {
555
+ requestId,
556
+ startTime: Date.now()
557
+ };
558
+ }
559
+ };
560
+
561
+ // src/core/config.ts
562
+ function resolveBuilderConfig(options = {}) {
563
+ return {
564
+ verbose: options.verbose === true,
565
+ includeStack: options.includeStack,
566
+ withDefaultBody: options.withDefaultBody !== false,
567
+ codes: createCodeRegistry(options.codes),
568
+ hooks: options.hooks,
569
+ plugins: options.plugins ?? []
570
+ };
571
+ }
572
+
573
+ // src/core/metadata.ts
574
+ var MetadataFactory = class {
575
+ static create(options = {}, context) {
576
+ return {
577
+ requestId: context?.requestId ?? generateUUID(),
578
+ serverTime: (/* @__PURE__ */ new Date()).toISOString(),
579
+ statusCode: 200,
580
+ ...options
581
+ };
582
+ }
583
+ };
584
+
585
+ // src/core/plugins.ts
586
+ function sortPlugins(plugins) {
587
+ return [...plugins].sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
588
+ }
589
+ var PluginRegistry = class {
590
+ plugins;
591
+ constructor(plugins = []) {
592
+ this.plugins = sortPlugins(plugins);
593
+ }
594
+ runBeforeBuild(ctx) {
595
+ for (const plugin of this.plugins) {
596
+ plugin.beforeBuild?.(ctx);
597
+ }
598
+ }
599
+ runAfterBuild(result, ctx) {
600
+ let current = result;
601
+ for (const plugin of this.plugins) {
602
+ const next = plugin.afterBuild?.(current, ctx);
603
+ if (next) current = next;
604
+ }
605
+ return current;
606
+ }
607
+ runBeforeDispatch(result, ctx) {
608
+ let current = result;
609
+ for (const plugin of this.plugins) {
610
+ const next = plugin.beforeDispatch?.(current, ctx);
611
+ if (next) current = next;
612
+ }
613
+ return current;
614
+ }
615
+ runAfterDispatch(result, ctx) {
616
+ for (const plugin of this.plugins) {
617
+ plugin.afterDispatch?.(result, ctx);
618
+ }
619
+ }
620
+ };
621
+
622
+ // src/core/presets.ts
623
+ var ResponsePresets = class {
624
+ builder;
625
+ codes;
626
+ constructor(builder, codes) {
627
+ this.builder = builder;
628
+ this.codes = codes;
629
+ }
630
+ applyExtras(extras) {
631
+ if (extras && Object.keys(extras).length > 0) {
632
+ this.builder.payload(extras);
633
+ }
634
+ }
635
+ dispatch() {
636
+ return this.builder.build();
637
+ }
638
+ resolveFailureArgs(dataOrMessage, messageOrExtras, extras) {
639
+ if (typeof dataOrMessage === "string") {
640
+ return {
641
+ message: dataOrMessage,
642
+ extras: typeof messageOrExtras === "string" ? extras : messageOrExtras
643
+ };
644
+ }
645
+ return {
646
+ data: dataOrMessage,
647
+ message: typeof messageOrExtras === "string" ? messageOrExtras : void 0,
648
+ extras: typeof messageOrExtras === "string" ? extras : messageOrExtras
649
+ };
650
+ }
651
+ failure(httpStatus, code, dataOrMessage, messageOrExtras, extras) {
652
+ const resolved = this.resolveFailureArgs(dataOrMessage, messageOrExtras, extras);
653
+ this.builder.httpStatus(httpStatus).code(code).status(false).message(resolved.message ?? defaultMessageForCode(code, this.codes)).data(resolved.data);
654
+ this.applyExtras(resolved.extras);
655
+ return this.dispatch();
656
+ }
657
+ ok(data, message, extras) {
658
+ this.builder.httpStatus(StatusCodes.SUCCESSFUL.OK).code(this.codes.SUCCESS).status(true).message(message ?? defaultMessageForCode(this.codes.SUCCESS, this.codes)).data(data);
659
+ this.applyExtras(extras);
660
+ return this.dispatch();
661
+ }
662
+ created(data, message, extras) {
663
+ this.builder.httpStatus(StatusCodes.SUCCESSFUL.CREATED).code(this.codes.SUCCESS).status(true).message(message ?? defaultMessageForCode(this.codes.SUCCESS, this.codes)).data(data);
664
+ this.applyExtras(extras);
665
+ return this.dispatch();
666
+ }
667
+ accepted(message, extras) {
668
+ this.builder.httpStatus(StatusCodes.SUCCESSFUL.ACCEPTED).code(this.codes.SUCCESS).status(true).message(message ?? defaultMessageForCode(this.codes.SUCCESS, this.codes));
669
+ this.applyExtras(extras);
670
+ return this.dispatch();
671
+ }
672
+ noContent(extras) {
673
+ this.builder.httpStatus(StatusCodes.SUCCESSFUL.NO_CONTENT).code(this.codes.SUCCESS).status(true).message("").data(void 0);
674
+ this.applyExtras(extras);
675
+ return this.dispatch();
676
+ }
677
+ /** Generic client failure — HTTP 400, CLIENT code */
678
+ fail(dataOrMessage, messageOrExtras, extras) {
679
+ return this.failure(StatusCodes.CLIENT_ERROR.BAD_REQUEST, this.codes.CLIENT, dataOrMessage, messageOrExtras, extras);
680
+ }
681
+ /** Generic server failure — HTTP 500, SERVER code */
682
+ error(dataOrMessage, messageOrExtras, extras) {
683
+ return this.failure(
684
+ StatusCodes.SERVER_ERROR.INTERNAL_SERVER_ERROR,
685
+ this.codes.SERVER,
686
+ dataOrMessage,
687
+ messageOrExtras,
688
+ extras
689
+ );
690
+ }
691
+ badRequest(dataOrMessage, messageOrExtras, extras) {
692
+ return this.failure(StatusCodes.CLIENT_ERROR.BAD_REQUEST, this.codes.CLIENT, dataOrMessage, messageOrExtras, extras);
693
+ }
694
+ unauthorized(dataOrMessage, messageOrExtras, extras) {
695
+ return this.failure(StatusCodes.CLIENT_ERROR.UNAUTHORIZED, this.codes.CLIENT, dataOrMessage, messageOrExtras, extras);
696
+ }
697
+ forbidden(dataOrMessage, messageOrExtras, extras) {
698
+ return this.failure(StatusCodes.CLIENT_ERROR.FORBIDDEN, this.codes.CLIENT, dataOrMessage, messageOrExtras, extras);
699
+ }
700
+ notFound(dataOrMessage, messageOrExtras, extras) {
701
+ return this.failure(StatusCodes.CLIENT_ERROR.NOT_FOUND, this.codes.CLIENT, dataOrMessage, messageOrExtras, extras);
702
+ }
703
+ conflict(dataOrMessage, messageOrExtras, extras) {
704
+ return this.failure(StatusCodes.CLIENT_ERROR.CONFLICT, this.codes.CLIENT, dataOrMessage, messageOrExtras, extras);
705
+ }
706
+ unprocessable(dataOrMessage, messageOrExtras, extras) {
707
+ return this.failure(
708
+ StatusCodes.CLIENT_ERROR.UNPROCESSABLE_ENTITY,
709
+ this.codes.VALIDATION,
710
+ dataOrMessage,
711
+ messageOrExtras,
712
+ extras
713
+ );
714
+ }
715
+ tooManyRequests(dataOrMessage, messageOrExtras, extras) {
716
+ return this.failure(StatusCodes.CLIENT_ERROR.TOO_MANY_REQUESTS, this.codes.CLIENT, dataOrMessage, messageOrExtras, extras);
717
+ }
718
+ internalServerError(dataOrMessage, messageOrExtras, extras) {
719
+ return this.failure(
720
+ StatusCodes.SERVER_ERROR.INTERNAL_SERVER_ERROR,
721
+ this.codes.SERVER,
722
+ dataOrMessage,
723
+ messageOrExtras,
724
+ extras
725
+ );
726
+ }
727
+ serviceUnavailable(dataOrMessage, messageOrExtras, extras) {
728
+ return this.failure(
729
+ StatusCodes.SERVER_ERROR.SERVICE_UNAVAILABLE,
730
+ this.codes.SERVER,
731
+ dataOrMessage,
732
+ messageOrExtras,
733
+ extras
734
+ );
735
+ }
736
+ gatewayTimeout(dataOrMessage, messageOrExtras, extras) {
737
+ return this.failure(
738
+ StatusCodes.SERVER_ERROR.GATEWAY_TIMEOUT,
739
+ this.codes.SERVER,
740
+ dataOrMessage,
741
+ messageOrExtras,
742
+ extras
743
+ );
744
+ }
745
+ };
746
+
747
+ // src/errors/error.ts
748
+ var ResponseError = class extends Error {
749
+ code;
750
+ httpStatus;
751
+ payload;
752
+ constructor(options = {}) {
753
+ const codes = createCodeRegistry(options.codes);
754
+ const code = options.code ?? codes.SERVER;
755
+ const message = options.message ?? defaultMessageForCode(code, codes);
756
+ super(message, { cause: options.cause });
757
+ this.name = "ResponseError";
758
+ this.code = code;
759
+ this.httpStatus = options.httpStatus ?? codeToDefaultHttpStatus(code, codes);
760
+ if (options.payload !== void 0) {
761
+ this.payload = options.payload;
762
+ }
763
+ }
764
+ toJSON() {
765
+ return {
766
+ name: this.name,
767
+ message: this.message,
768
+ code: this.code,
769
+ httpStatus: this.httpStatus,
770
+ payload: this.payload
771
+ };
772
+ }
773
+ };
774
+ function isResponseError(value) {
775
+ return value instanceof ResponseError;
776
+ }
777
+ function codeToDefaultHttpStatus(code, codes) {
778
+ if (code === codes.SUCCESS) return 200;
779
+ if (code === codes.CLIENT) return 400;
780
+ if (code === codes.SERVER) return 500;
781
+ if (code === codes.VALIDATION) return 422;
782
+ return 500;
783
+ }
784
+
785
+ // src/core/builder.ts
786
+ var Builder = class {
787
+ dispatcher;
788
+ options;
789
+ context;
790
+ plugins;
791
+ body;
792
+ _statusCode = StatusCodes.SUCCESSFUL.OK;
793
+ _headers = {};
794
+ _cookies = [];
795
+ _presets;
796
+ constructor(dispatcher, options = {}, context) {
797
+ this.dispatcher = dispatcher;
798
+ this.options = resolveBuilderConfig(options);
799
+ this.context = context;
800
+ this.plugins = new PluginRegistry(this.options.plugins);
801
+ this.body = new ResponseDTO();
802
+ }
803
+ get dto() {
804
+ return this.body;
805
+ }
806
+ httpStatus(code) {
807
+ this._statusCode = code;
808
+ this.body.setCodeFromHttpStatus(code, this.options.codes);
809
+ return this;
810
+ }
811
+ code(code) {
812
+ this.body.code(code);
813
+ return this;
814
+ }
815
+ status(value) {
816
+ this.body.status(value);
817
+ return this;
818
+ }
819
+ message(msg) {
820
+ this.body.message(msg);
821
+ return this;
822
+ }
823
+ data(data) {
824
+ this.body.data(data);
825
+ return this;
826
+ }
827
+ payload(partial) {
828
+ this.body.payload(partial);
829
+ return this;
830
+ }
831
+ schema(input = {}) {
832
+ this.body.schema(input, this.options.codes);
833
+ return this;
834
+ }
835
+ setMeta(meta) {
836
+ this.body.setMeta(meta);
837
+ return this;
838
+ }
839
+ withMetadata(options = {}) {
840
+ const generated = MetadataFactory.create(
841
+ { statusCode: this._statusCode, ...options },
842
+ { requestId: this.context?.requestId }
843
+ );
844
+ return this.setMeta(generated);
845
+ }
846
+ paginate(total, page, limit) {
847
+ this.body.paginate(total, page, limit);
848
+ return this;
849
+ }
850
+ setHeaders(keyOrHeaders, value) {
851
+ if (typeof keyOrHeaders === "string") {
852
+ if (value !== void 0) {
853
+ this._headers[keyOrHeaders] = value;
854
+ }
855
+ } else {
856
+ this._headers = { ...this._headers, ...keyOrHeaders };
857
+ }
858
+ return this;
859
+ }
860
+ header(key, value) {
861
+ return this.setHeaders(key, value);
862
+ }
863
+ setCookies(nameOrCookies, valueOrOptions, options) {
864
+ if (typeof nameOrCookies === "string") {
865
+ if (typeof valueOrOptions === "string") {
866
+ this._cookies.push({ name: nameOrCookies, value: valueOrOptions, options });
867
+ }
868
+ } else {
869
+ const sharedOptions = typeof valueOrOptions === "object" ? valueOrOptions : void 0;
870
+ for (const [name, value] of Object.entries(nameOrCookies)) {
871
+ this._cookies.push({ name, value, options: sharedOptions });
872
+ }
873
+ }
874
+ return this;
875
+ }
876
+ fromError(error) {
877
+ if (isResponseError(error)) {
878
+ return this.httpStatus(error.httpStatus).code(error.code).message(error.message).payload(error.payload ? { ...error.payload } : {}).data(void 0);
879
+ }
880
+ return this.httpStatus(StatusCodes.SERVER_ERROR.INTERNAL_SERVER_ERROR).code(this.options.codes.SERVER).message(this.resolvePublicErrorMessage(error)).data(void 0);
881
+ }
882
+ async wrap(promise) {
883
+ try {
884
+ this.data(await promise);
885
+ return this;
886
+ } catch (error) {
887
+ this.fromError(error);
888
+ this.options.hooks?.emit("error", {
889
+ error,
890
+ message: this.body.getMessage(),
891
+ statusCode: this._statusCode,
892
+ code: this.body.getCode() ?? resolveCodeFromHttpStatus(this._statusCode, this.options.codes)
893
+ });
894
+ return this;
895
+ }
896
+ }
897
+ transform(fn) {
898
+ const next = this;
899
+ next.body = this.body.transformData(fn);
900
+ return next;
901
+ }
902
+ when(condition, fn) {
903
+ if (condition) fn(this);
904
+ return this;
905
+ }
906
+ get as() {
907
+ if (!this._presets) {
908
+ this._presets = new ResponsePresets(this, this.options.codes);
909
+ }
910
+ return this._presets;
911
+ }
912
+ build() {
913
+ const pluginCtx = this.createPluginContext();
914
+ this.options.hooks?.emit("before_build", { statusCode: this._statusCode });
915
+ this.plugins.runBeforeBuild(pluginCtx);
916
+ const body = this.body.build({
917
+ codes: this.options.codes,
918
+ withDefaultBody: this.options.withDefaultBody,
919
+ httpStatusCode: this._statusCode
920
+ });
921
+ let result = {
922
+ body,
923
+ statusCode: this._statusCode,
924
+ headers: { ...this._headers },
925
+ cookies: [...this._cookies]
926
+ };
927
+ result = this.plugins.runAfterBuild(result, pluginCtx);
928
+ this.emitHook("after_build", result);
929
+ if (this.dispatcher) {
930
+ result = this.plugins.runBeforeDispatch(result, pluginCtx);
931
+ this.emitHook("before_dispatch", result);
932
+ const dispatched = this.dispatcher.dispatch(result);
933
+ this.plugins.runAfterDispatch(result, pluginCtx);
934
+ this.emitHook("after_dispatch", result);
935
+ return dispatched ?? result;
936
+ }
937
+ return result;
938
+ }
939
+ resolvePublicErrorMessage(error) {
940
+ if (!this.options.verbose && !isResponseError(error)) {
941
+ return defaultMessageForCode(this.options.codes.SERVER, this.options.codes);
942
+ }
943
+ if (error instanceof Error) {
944
+ if (this.options.includeStack && error.stack) return error.stack;
945
+ return error.message || defaultMessageForCode(this.options.codes.SERVER, this.options.codes);
946
+ }
947
+ if (typeof error === "string") return error;
948
+ return defaultMessageForCode(this.options.codes.SERVER, this.options.codes);
949
+ }
950
+ createPluginContext() {
951
+ return {
952
+ builder: this,
953
+ context: this.context,
954
+ options: this.options,
955
+ codes: this.options.codes
956
+ };
957
+ }
958
+ emitHook(event, result) {
959
+ const hooks = this.options.hooks;
960
+ if (!hooks?.hasListeners(event)) return;
961
+ hooks.emit(event, structuredClone(result));
962
+ }
963
+ };
964
+ function createBuilderProxy(dispatcher, options = {}, context) {
965
+ const instance = new Builder(dispatcher, options, context);
966
+ return new Proxy(instance, {
967
+ get(target, prop, receiver) {
968
+ const value = Reflect.get(target, prop, receiver);
969
+ if (typeof value === "function") {
970
+ return value.bind(target);
971
+ }
972
+ return value;
973
+ }
974
+ });
975
+ }
976
+
977
+ // src/adapters/shared.ts
978
+ function createBuilderRuntime(dispatcher, options, context) {
979
+ const builderOptions = {
980
+ verbose: options.verbose,
981
+ includeStack: options.includeStack,
982
+ withDefaultBody: options.withDefaultBody,
983
+ codes: options.codes,
984
+ hooks: options.hooks,
985
+ plugins: options.plugins
986
+ };
987
+ return {
988
+ context,
989
+ codes: resolveBuilderConfig(builderOptions).codes,
990
+ builder: createBuilderProxy(dispatcher, builderOptions, context)
991
+ };
992
+ }
993
+
994
+ // src/adapters/elysia.ts
995
+ function createElysiaDerive(options = {}) {
996
+ return ({ request, set }) => {
997
+ const context = ContextFactory.create({
998
+ headers: headersToRecord(request.headers)
999
+ }, {
1000
+ requestIdHeaders: options.requestIdHeaders
1001
+ });
1002
+ if (options.withDefaultHeaders !== false) {
1003
+ const headers = options.defaultHeaders ?? DEFAULT_SECURITY_HEADERS;
1004
+ set.headers = { ...set.headers ?? {}, ...headers };
1005
+ }
1006
+ const runtime = createBuilderRuntime(
1007
+ {
1008
+ dispatch(result) {
1009
+ set.status = result.statusCode;
1010
+ set.headers = {
1011
+ ...set.headers ?? {},
1012
+ ...normalizeHeaders(result.headers),
1013
+ "Content-Type": "application/json; charset=utf-8"
1014
+ };
1015
+ if (!shouldSendResponseBody(result.statusCode)) {
1016
+ return null;
1017
+ }
1018
+ return result.body;
1019
+ }
1020
+ },
1021
+ options,
1022
+ context
1023
+ );
1024
+ return {
1025
+ builder: runtime.builder,
1026
+ requestId: runtime.context.requestId,
1027
+ startTime: runtime.context.startTime
1028
+ };
1029
+ };
1030
+ }
1031
+ var ElysiaAdapter = class {
1032
+ options;
1033
+ constructor(options = {}) {
1034
+ this.options = options;
1035
+ }
1036
+ /** Elysia plugin — adds `builder`, `requestId`, `startTime` to the handler context */
1037
+ plugin() {
1038
+ const derive = createElysiaDerive(this.options);
1039
+ return new elysia.Elysia({ name: "x" }).derive(
1040
+ { as: "scoped" },
1041
+ (context) => derive({
1042
+ request: context.request,
1043
+ set: context.set
1044
+ })
1045
+ );
1046
+ }
1047
+ middleware() {
1048
+ return this.plugin();
1049
+ }
1050
+ handler() {
1051
+ return this.plugin();
1052
+ }
1053
+ };
1054
+ function headersToRecord(headers) {
1055
+ const record = {};
1056
+ headers.forEach((value, key) => {
1057
+ record[key] = value;
1058
+ });
1059
+ return record;
1060
+ }
1061
+ function normalizeHeaders(headers) {
1062
+ const normalized = {};
1063
+ for (const [key, value] of Object.entries(headers)) {
1064
+ if (Array.isArray(value)) {
1065
+ normalized[key] = value.join(", ");
1066
+ } else {
1067
+ normalized[key] = String(value);
1068
+ }
1069
+ }
1070
+ return normalized;
1071
+ }
1072
+
1073
+ // src/adapters/express.ts
1074
+ var ExpressDispatcher = class {
1075
+ res;
1076
+ constructor(res) {
1077
+ this.res = res;
1078
+ }
1079
+ dispatch(result) {
1080
+ if (this.res.headersSent) {
1081
+ return result;
1082
+ }
1083
+ for (const [key, value] of Object.entries(result.headers)) {
1084
+ this.res.setHeader(key, value);
1085
+ }
1086
+ if (result.cookies.length && this.res.cookie) {
1087
+ for (const cookie of result.cookies) {
1088
+ this.res.cookie(cookie.name, cookie.value, cookie.options ?? {});
1089
+ }
1090
+ }
1091
+ this.res.status(result.statusCode);
1092
+ if (shouldSendResponseBody(result.statusCode)) {
1093
+ this.res.json(result.body);
1094
+ } else {
1095
+ this.res.end();
1096
+ }
1097
+ return result;
1098
+ }
1099
+ };
1100
+ var ExpressAdapter = class {
1101
+ options;
1102
+ constructor(options = {}) {
1103
+ this.options = options;
1104
+ }
1105
+ handler() {
1106
+ return this.middleware.bind(this);
1107
+ }
1108
+ middleware(req, res, next) {
1109
+ const context = ContextFactory.create(req, {
1110
+ requestIdHeaders: this.options.requestIdHeaders
1111
+ });
1112
+ if (this.options.withDefaultHeaders !== false) {
1113
+ const headers = this.options.defaultHeaders ?? DEFAULT_SECURITY_HEADERS;
1114
+ for (const [key, value] of Object.entries(headers)) {
1115
+ res.setHeader(key, value);
1116
+ }
1117
+ }
1118
+ const runtime = createBuilderRuntime(new ExpressDispatcher(res), this.options, context);
1119
+ req.ctx = runtime.context;
1120
+ res.builder = runtime.builder;
1121
+ next();
1122
+ }
1123
+ };
1124
+
1125
+ // src/adapters/node.ts
1126
+ var NodeDispatcher = class {
1127
+ res;
1128
+ constructor(res) {
1129
+ this.res = res;
1130
+ }
1131
+ dispatch(result) {
1132
+ if (this.res.headersSent) {
1133
+ return result;
1134
+ }
1135
+ for (const [key, value] of Object.entries(result.headers)) {
1136
+ this.res.setHeader(key, value);
1137
+ }
1138
+ this.res.statusCode = result.statusCode;
1139
+ if (!shouldSendResponseBody(result.statusCode)) {
1140
+ this.res.end();
1141
+ return result;
1142
+ }
1143
+ const body = JSON.stringify(result.body);
1144
+ if (!this.res.getHeader("Content-Type")) {
1145
+ this.res.setHeader("Content-Type", "application/json; charset=utf-8");
1146
+ }
1147
+ this.res.end(body);
1148
+ return result;
1149
+ }
1150
+ };
1151
+ var NodeAdapter = class {
1152
+ options;
1153
+ constructor(options = {}) {
1154
+ this.options = options;
1155
+ }
1156
+ handler() {
1157
+ return this.middleware.bind(this);
1158
+ }
1159
+ middleware(req, res, next) {
1160
+ const context = ContextFactory.create(req, {
1161
+ requestIdHeaders: this.options.requestIdHeaders
1162
+ });
1163
+ if (this.options.withDefaultHeaders !== false) {
1164
+ const headers = this.options.defaultHeaders ?? DEFAULT_SECURITY_HEADERS;
1165
+ for (const [key, value] of Object.entries(headers)) {
1166
+ if (!res.getHeader(key)) {
1167
+ res.setHeader(key, value);
1168
+ }
1169
+ }
1170
+ }
1171
+ const runtime = createBuilderRuntime(new NodeDispatcher(res), this.options, context);
1172
+ req.ctx = runtime.context;
1173
+ res.builder = runtime.builder;
1174
+ next();
1175
+ }
1176
+ };
1177
+
1178
+ // src/adapters/socketio.ts
1179
+ var SocketIoDispatcher = class {
1180
+ socket;
1181
+ event;
1182
+ constructor(socket, event = "response") {
1183
+ this.socket = socket;
1184
+ this.event = event;
1185
+ }
1186
+ dispatch(result) {
1187
+ this.socket.emit(this.event, result.body);
1188
+ return result;
1189
+ }
1190
+ };
1191
+ var SocketIoAdapter = class {
1192
+ options;
1193
+ constructor(options = {}) {
1194
+ this.options = {
1195
+ event: "response",
1196
+ ...options
1197
+ };
1198
+ }
1199
+ attach(socket) {
1200
+ const context = ContextFactory.create({
1201
+ headers: socket.handshake?.headers
1202
+ }, {
1203
+ requestIdHeaders: this.options.requestIdHeaders
1204
+ });
1205
+ const runtime = createBuilderRuntime(
1206
+ new SocketIoDispatcher(socket, this.options.event),
1207
+ this.options,
1208
+ context
1209
+ );
1210
+ socket.ctx = runtime.context;
1211
+ socket.builder = runtime.builder;
1212
+ return runtime;
1213
+ }
1214
+ handler() {
1215
+ return (socket, next) => {
1216
+ try {
1217
+ this.attach(socket);
1218
+ next?.();
1219
+ } catch (error) {
1220
+ next?.(error instanceof Error ? error : new Error(String(error)));
1221
+ }
1222
+ };
1223
+ }
1224
+ };
1225
+
1226
+ // src/adapters/websocket.ts
1227
+ var WS_OPEN = 1;
1228
+ var WebSocketDispatcher = class {
1229
+ socket;
1230
+ constructor(socket) {
1231
+ this.socket = socket;
1232
+ }
1233
+ dispatch(result) {
1234
+ if (this.socket.readyState !== void 0 && this.socket.readyState !== WS_OPEN) {
1235
+ return result;
1236
+ }
1237
+ this.socket.send(JSON.stringify(result.body));
1238
+ return result;
1239
+ }
1240
+ };
1241
+ var WebSocketAdapter = class {
1242
+ options;
1243
+ constructor(options = {}) {
1244
+ this.options = options;
1245
+ }
1246
+ attach(socket, requestId) {
1247
+ const context = requestId ? ContextFactory.fromId(requestId) : ContextFactory.fromId(generateUUID());
1248
+ const runtime = createBuilderRuntime(
1249
+ new WebSocketDispatcher(socket),
1250
+ this.options,
1251
+ context
1252
+ );
1253
+ socket.ctx = runtime.context;
1254
+ socket.builder = runtime.builder;
1255
+ return runtime;
1256
+ }
1257
+ handler() {
1258
+ return (socket, next) => {
1259
+ this.attach(socket);
1260
+ next?.();
1261
+ };
1262
+ }
1263
+ };
1264
+
1265
+ // src/types/plugin.ts
1266
+ function mergePlugins(...groups) {
1267
+ return groups.flatMap((group) => group ?? []);
1268
+ }
1269
+
1270
+ // src/dto/runtime/dto.ts
1271
+ var DTO = class _DTO {
1272
+ static Log = LogDTO;
1273
+ static Queue = QueueDTO;
1274
+ static Response = ResponseDTO;
1275
+ options;
1276
+ constructor(options = {}) {
1277
+ this.options = options;
1278
+ }
1279
+ use(...plugins) {
1280
+ return new _DTO({
1281
+ ...this.options,
1282
+ plugins: mergePlugins(this.options.plugins, plugins)
1283
+ });
1284
+ }
1285
+ express() {
1286
+ return new ExpressAdapter(this.options).handler();
1287
+ }
1288
+ node() {
1289
+ return new NodeAdapter(this.options).handler();
1290
+ }
1291
+ elysia() {
1292
+ return new ElysiaAdapter(this.options).middleware();
1293
+ }
1294
+ websocket() {
1295
+ return new WebSocketAdapter(this.socketOptions()).handler();
1296
+ }
1297
+ attachWebSocket(socket, requestId) {
1298
+ return new WebSocketAdapter(this.socketOptions()).attach(socket, requestId);
1299
+ }
1300
+ socketIo() {
1301
+ return new SocketIoAdapter(this.socketOptions()).handler();
1302
+ }
1303
+ attachSocketIo(socket) {
1304
+ return new SocketIoAdapter(this.socketOptions()).attach(socket);
1305
+ }
1306
+ socketOptions() {
1307
+ return {
1308
+ ...this.options,
1309
+ event: this.options.socket?.event ?? this.options.event ?? "response"
1310
+ };
1311
+ }
1312
+ };
1313
+ function createDTO(options = {}) {
1314
+ return new DTO(options);
1315
+ }
1316
+
1317
+ exports.DTO = DTO;
1318
+ exports.createDTO = createDTO;