@codexsploitx/schemaapi 1.0.5 → 1.0.6

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.
@@ -1,13 +1,1724 @@
1
1
  'use strict';
2
2
 
3
- function createContract(schema) {
3
+ var zod = require('zod');
4
+
5
+ class SchemaApiError extends Error {
6
+ constructor(code, message) {
7
+ super(message);
8
+ this.code = code;
9
+ this.name = "SchemaApiError";
10
+ }
11
+ }
12
+ function buildErrorPayload(error) {
13
+ if (error instanceof SchemaApiError) {
14
+ return {
15
+ error: error.message,
16
+ message: error.message,
17
+ status: error.code,
18
+ };
19
+ }
20
+ const typedError = error;
21
+ const status = typeof typedError.status === "number"
22
+ ? typedError.status
23
+ : typeof typedError.code === "number"
24
+ ? typedError.code
25
+ : 500;
26
+ const message = typeof typedError.message === "string"
27
+ ? typedError.message
28
+ : "Internal Server Error";
4
29
  return {
30
+ error: message,
31
+ message,
32
+ status,
33
+ };
34
+ }
35
+ function extractRouteParams(route) {
36
+ return route
37
+ .split("/")
38
+ .filter((segment) => segment.startsWith(":"))
39
+ .map((segment) => segment.slice(1))
40
+ .filter((name) => name.length > 0);
41
+ }
42
+ function getBaseSchema(schema) {
43
+ let current = schema;
44
+ while (current._def &&
45
+ current._def?.innerType) {
46
+ const def = current._def;
47
+ current = def.innerType;
48
+ }
49
+ return current;
50
+ }
51
+ function getObjectShape(schema) {
52
+ if (!schema) {
53
+ return null;
54
+ }
55
+ const base = getBaseSchema(schema);
56
+ if (base instanceof zod.ZodObject) {
57
+ const objectSchema = base;
58
+ return objectSchema.shape;
59
+ }
60
+ return null;
61
+ }
62
+ function getTypeName(schema) {
63
+ const base = getBaseSchema(schema);
64
+ const def = base._def;
65
+ if (!def || typeof def !== "object") {
66
+ return undefined;
67
+ }
68
+ const record = def;
69
+ const value = record["typeName"] || record["type"];
70
+ if (typeof value === "string") {
71
+ return value;
72
+ }
73
+ return undefined;
74
+ }
75
+ function isOptional(schema) {
76
+ return schema.isOptional();
77
+ }
78
+ function createContract(schema) {
79
+ const api = {
5
80
  handle(endpoint, handler) {
6
- return handler;
81
+ const [method, route] = endpoint.split(" ");
82
+ const routeSchema = schema[route];
83
+ if (!routeSchema) {
84
+ throw new SchemaApiError(404, `Route ${route} not defined in contract`);
85
+ }
86
+ const methodSchema = routeSchema[method];
87
+ if (!methodSchema) {
88
+ throw new SchemaApiError(405, `Method ${method} not defined for route ${route}`);
89
+ }
90
+ const dynamicParams = extractRouteParams(route);
91
+ if (dynamicParams.length > 0) {
92
+ const paramsShape = getObjectShape(methodSchema.params);
93
+ if (!paramsShape) {
94
+ throw new Error(`Route ${route} has dynamic params but no params schema is defined`);
95
+ }
96
+ dynamicParams.forEach((name) => {
97
+ if (!(name in paramsShape)) {
98
+ throw new Error(`Dynamic path param :${name} in ${route} is not defined in params`);
99
+ }
100
+ });
101
+ }
102
+ return async (ctx) => {
103
+ const context = ctx;
104
+ const media = methodSchema.media;
105
+ if (media && media.kind === "upload") {
106
+ const rawHeaders = (context.headers ??
107
+ {});
108
+ const headers = {};
109
+ Object.keys(rawHeaders).forEach((key) => {
110
+ const value = rawHeaders[key];
111
+ if (typeof value === "string") {
112
+ headers[key.toLowerCase()] = value;
113
+ }
114
+ });
115
+ const contentTypeHeader = headers["content-type"];
116
+ if (media.contentTypes && media.contentTypes.length > 0) {
117
+ const matches = !!contentTypeHeader &&
118
+ media.contentTypes.some((expected) => {
119
+ if (expected.endsWith("/*")) {
120
+ const prefix = expected.slice(0, -1);
121
+ return contentTypeHeader.startsWith(prefix);
122
+ }
123
+ return (contentTypeHeader === expected ||
124
+ contentTypeHeader.startsWith(`${expected};`));
125
+ });
126
+ if (!matches) {
127
+ throw new SchemaApiError(415, "Unsupported Media Type");
128
+ }
129
+ }
130
+ if (media.maxSize && media.maxSize > 0) {
131
+ const lengthHeader = headers["content-length"];
132
+ if (lengthHeader !== undefined) {
133
+ const parsed = Number(lengthHeader);
134
+ if (!Number.isNaN(parsed) && parsed > media.maxSize) {
135
+ throw new SchemaApiError(413, "Payload Too Large");
136
+ }
137
+ }
138
+ }
139
+ }
140
+ if (methodSchema.roles && methodSchema.roles.length > 0) {
141
+ const userRole = context.user?.role;
142
+ if (!userRole || !methodSchema.roles.includes(userRole)) {
143
+ throw new SchemaApiError(403, "Forbidden");
144
+ }
145
+ }
146
+ try {
147
+ if (methodSchema.params && context.params !== undefined) {
148
+ context.params = methodSchema.params.parse(context.params);
149
+ }
150
+ if (methodSchema.query && context.query !== undefined) {
151
+ context.query = methodSchema.query.parse(context.query);
152
+ }
153
+ if (methodSchema.body && context.body !== undefined) {
154
+ context.body = methodSchema.body.parse(context.body);
155
+ }
156
+ if (methodSchema.headers && context.headers !== undefined) {
157
+ context.headers = methodSchema.headers.parse(context.headers);
158
+ }
159
+ }
160
+ catch (error) {
161
+ if (error instanceof zod.z.ZodError) {
162
+ throw new SchemaApiError(400, `Validation Error: ${JSON.stringify(error.flatten())}`);
163
+ }
164
+ throw error;
165
+ }
166
+ let result;
167
+ try {
168
+ result = await handler(context);
169
+ }
170
+ catch (error) {
171
+ if (error instanceof SchemaApiError) {
172
+ const code = error.code;
173
+ const errorsConfig = (methodSchema.errors ??
174
+ {});
175
+ const allowedStatuses = Object.keys(errorsConfig);
176
+ if (code >= 400 && code !== 400 && code !== 500) {
177
+ if (!allowedStatuses.includes(String(code))) {
178
+ throw new SchemaApiError(code, `${code} is not defined in contract.errors`);
179
+ }
180
+ }
181
+ throw error;
182
+ }
183
+ throw error;
184
+ }
185
+ if (methodSchema.response) {
186
+ try {
187
+ return methodSchema.response.parse(result);
188
+ }
189
+ catch (error) {
190
+ if (error instanceof zod.z.ZodError) {
191
+ throw new SchemaApiError(500, `Response Validation Error: ${JSON.stringify(error.flatten())}`);
192
+ }
193
+ throw error;
194
+ }
195
+ }
196
+ return result;
197
+ };
198
+ },
199
+ compareWith(other) {
200
+ const breaking = [];
201
+ const oldSchema = other.schema;
202
+ const newSchema = schema;
203
+ Object.keys(oldSchema).forEach((route) => {
204
+ if (!(route in newSchema)) {
205
+ breaking.push(`Route removed: ${route}`);
206
+ return;
207
+ }
208
+ const oldRoute = oldSchema[route];
209
+ const newRoute = newSchema[route];
210
+ Object.keys(oldRoute).forEach((method) => {
211
+ const oldMethod = oldRoute[method];
212
+ const newMethod = newRoute[method];
213
+ const pathId = `${method} ${route}`;
214
+ if (!newMethod) {
215
+ breaking.push(`Method removed: ${pathId}`);
216
+ return;
217
+ }
218
+ // Check Response (Output)
219
+ const oldResponseShape = getObjectShape(oldMethod.response);
220
+ const newResponseShape = getObjectShape(newMethod.response);
221
+ if (oldResponseShape && newResponseShape) {
222
+ Object.keys(oldResponseShape).forEach((field) => {
223
+ if (!(field in newResponseShape)) {
224
+ breaking.push(`Response field removed: ${field} in ${pathId}`);
225
+ return;
226
+ }
227
+ const oldField = oldResponseShape[field];
228
+ const newField = newResponseShape[field];
229
+ const oldType = getTypeName(oldField);
230
+ const newType = getTypeName(newField);
231
+ if (oldType && newType && oldType !== newType) {
232
+ breaking.push(`Response field type changed: ${field} in ${pathId}`);
233
+ }
234
+ });
235
+ }
236
+ // Check Request Body (Input)
237
+ const oldBodyShape = getObjectShape(oldMethod.body);
238
+ const newBodyShape = getObjectShape(newMethod.body);
239
+ if (newBodyShape) {
240
+ Object.keys(newBodyShape).forEach((field) => {
241
+ const newField = newBodyShape[field];
242
+ const oldField = oldBodyShape ? oldBodyShape[field] : undefined;
243
+ if (!oldField) {
244
+ // New field added. Check if required.
245
+ if (!newField.isOptional()) {
246
+ breaking.push(`New required request body field: ${field} in ${pathId}`);
247
+ }
248
+ }
249
+ else {
250
+ // Field exists in both. Check type change.
251
+ const oldType = getTypeName(oldField);
252
+ const newType = getTypeName(newField);
253
+ if (oldType && newType && oldType !== newType) {
254
+ breaking.push(`Request body field type changed: ${field} in ${pathId}`);
255
+ }
256
+ // Check if became required (was optional)
257
+ if (oldField.isOptional() && !newField.isOptional()) {
258
+ breaking.push(`Request body field became required: ${field} in ${pathId}`);
259
+ }
260
+ }
261
+ });
262
+ }
263
+ // Check Query Params (Input)
264
+ const oldQueryShape = getObjectShape(oldMethod.query);
265
+ const newQueryShape = getObjectShape(newMethod.query);
266
+ if (newQueryShape) {
267
+ Object.keys(newQueryShape).forEach((field) => {
268
+ const newField = newQueryShape[field];
269
+ const oldField = oldQueryShape ? oldQueryShape[field] : undefined;
270
+ if (!oldField) {
271
+ if (!newField.isOptional()) {
272
+ breaking.push(`New required query param: ${field} in ${pathId}`);
273
+ }
274
+ }
275
+ else {
276
+ const oldType = getTypeName(oldField);
277
+ const newType = getTypeName(newField);
278
+ if (oldType && newType && oldType !== newType) {
279
+ breaking.push(`Query param type changed: ${field} in ${pathId}`);
280
+ }
281
+ }
282
+ });
283
+ }
284
+ // Check Path Params (Input)
285
+ const oldParamsShape = getObjectShape(oldMethod.params);
286
+ const newParamsShape = getObjectShape(newMethod.params);
287
+ if (newParamsShape) {
288
+ Object.keys(newParamsShape).forEach((field) => {
289
+ const newField = newParamsShape[field];
290
+ const oldField = oldParamsShape ? oldParamsShape[field] : undefined;
291
+ if (oldField) {
292
+ const oldType = getTypeName(oldField);
293
+ const newType = getTypeName(newField);
294
+ if (oldType && newType && oldType !== newType) {
295
+ breaking.push(`Path param type changed: ${field} in ${pathId}`);
296
+ }
297
+ }
298
+ });
299
+ }
300
+ const oldErrors = (oldMethod.errors ?? {});
301
+ const newErrors = (newMethod.errors ?? {});
302
+ Object.keys(oldErrors).forEach((status) => {
303
+ if (!(status in newErrors)) {
304
+ breaking.push(`Status code removed: ${status} in ${pathId}`);
305
+ }
306
+ else {
307
+ const oldError = oldErrors[status];
308
+ const newError = newErrors[status];
309
+ if (oldError !== newError) {
310
+ breaking.push(`Error code changed for status ${status} in ${pathId}`);
311
+ }
312
+ }
313
+ });
314
+ const oldRoles = (oldMethod.roles ?? []);
315
+ const newRoles = (newMethod.roles ?? []);
316
+ oldRoles.forEach((role) => {
317
+ if (!newRoles.includes(role)) {
318
+ breaking.push(`Role removed: ${role} in ${pathId}`);
319
+ }
320
+ });
321
+ });
322
+ });
323
+ return { breakingChanges: breaking };
324
+ },
325
+ docs() {
326
+ const routesDocs = [];
327
+ const current = schema;
328
+ Object.keys(current).forEach((route) => {
329
+ const routeDef = current[route];
330
+ Object.keys(routeDef).forEach((method) => {
331
+ const methodDef = routeDef[method];
332
+ const doc = {
333
+ method,
334
+ path: route,
335
+ roles: methodDef.roles ? [...methodDef.roles] : undefined,
336
+ media: methodDef.media,
337
+ errors: methodDef.errors
338
+ ? Object.keys(methodDef.errors).map((status) => ({
339
+ status,
340
+ code: String(methodDef.errors?.[status]),
341
+ }))
342
+ : undefined,
343
+ };
344
+ const fillFields = (source, assign) => {
345
+ if (!source) {
346
+ return;
347
+ }
348
+ const shape = getObjectShape(source);
349
+ if (!shape) {
350
+ return;
351
+ }
352
+ const fields = Object.keys(shape).map((name) => {
353
+ const fieldSchema = shape[name];
354
+ const typeName = getTypeName(fieldSchema);
355
+ const optional = isOptional(fieldSchema);
356
+ return {
357
+ name,
358
+ type: typeName,
359
+ optional,
360
+ };
361
+ });
362
+ assign(fields);
363
+ };
364
+ fillFields(methodDef.params, (fields) => {
365
+ doc.params = fields;
366
+ });
367
+ fillFields(methodDef.query, (fields) => {
368
+ doc.query = fields;
369
+ });
370
+ fillFields(methodDef.body, (fields) => {
371
+ doc.body = fields;
372
+ });
373
+ fillFields(methodDef.headers, (fields) => {
374
+ doc.headers = fields;
375
+ });
376
+ routesDocs.push(doc);
377
+ });
378
+ });
379
+ return { routes: routesDocs };
7
380
  },
8
381
  schema,
9
382
  };
383
+ return api;
384
+ }
385
+
386
+ // Definimos tipos básicos para simular la estructura del cliente
387
+ // En una implementación real, estos tipos se inferirían recursivamente del esquema T
388
+ function createClient(contract, config) {
389
+ const { baseUrl, fetch: customFetch } = config;
390
+ const fetchFn = customFetch || globalThis.fetch;
391
+ return new Proxy({}, {
392
+ get(_target, resource) {
393
+ return new Proxy({}, {
394
+ get(_target, operation) {
395
+ // operation podría ser 'get', 'post', 'put', 'delete', 'ws', etc.
396
+ // resource sería 'users', 'posts', etc.
397
+ return async (params = {}) => {
398
+ const method = operation.toUpperCase();
399
+ let path = `/${resource}`;
400
+ // Si hay params.id, asumimos que va en la URL
401
+ if (params.id) {
402
+ path += `/${params.id}`;
403
+ }
404
+ // Manejo de WebSocket
405
+ if (method === "WS") {
406
+ const wsUrlStr = baseUrl.replace(/^http/, "ws");
407
+ const url = new URL(`${wsUrlStr}${path}`);
408
+ // Agregar query params
409
+ Object.keys(params).forEach(key => {
410
+ if (key !== 'id' && key !== 'headers' && key !== 'body') {
411
+ url.searchParams.append(key, String(params[key]));
412
+ }
413
+ });
414
+ const globalWithWebSocket = globalThis;
415
+ const WebSocketCtor = config.WebSocket || globalWithWebSocket.WebSocket;
416
+ if (!WebSocketCtor) {
417
+ throw new Error("WebSocket implementation not found. Please provide it in config.");
418
+ }
419
+ return new WebSocketCtor(url.toString());
420
+ }
421
+ const url = new URL(`${baseUrl}${path}`);
422
+ // Agregar query params si existen (excluyendo id y body)
423
+ Object.keys(params).forEach(key => {
424
+ if (key !== 'id' && key !== 'body' && key !== 'headers') {
425
+ url.searchParams.append(key, String(params[key]));
426
+ }
427
+ });
428
+ const headers = {
429
+ "Content-Type": "application/json",
430
+ ...(params.headers || {})
431
+ };
432
+ const response = await fetchFn(url.toString(), {
433
+ method,
434
+ headers,
435
+ body: params.body ? JSON.stringify(params.body) : undefined,
436
+ });
437
+ if (!response.ok) {
438
+ throw new Error(`Request failed: ${response.status} ${response.statusText}`);
439
+ }
440
+ return response.json();
441
+ };
442
+ }
443
+ });
444
+ }
445
+ });
446
+ }
447
+
448
+ function generateSDK(contract, options) {
449
+ return createClient(contract, {
450
+ baseUrl: options.baseUrl,
451
+ fetch: options.fetch,
452
+ });
453
+ }
454
+
455
+ function handleContract$6(app, contract, handlers) {
456
+ const schema = contract.schema;
457
+ Object.keys(schema).forEach((route) => {
458
+ const methods = schema[route];
459
+ Object.keys(methods).forEach((method) => {
460
+ const endpoint = `${method} ${route}`;
461
+ const implementation = handlers[endpoint];
462
+ const methodSchema = methods[method];
463
+ if (!implementation) {
464
+ return;
465
+ }
466
+ const wrapped = contract.handle(endpoint, implementation);
467
+ const httpMethod = method.toLowerCase();
468
+ const register = app[httpMethod];
469
+ if (!register) {
470
+ return;
471
+ }
472
+ register(route, async (req, res, next) => {
473
+ try {
474
+ const context = {
475
+ params: req.params || {},
476
+ query: req.query || {},
477
+ body: req.body,
478
+ headers: req.headers || {},
479
+ user: req.user,
480
+ };
481
+ const result = await wrapped(context);
482
+ const media = methodSchema?.media;
483
+ if (media && media.kind === "download") {
484
+ const download = result;
485
+ const data = download &&
486
+ typeof download === "object" &&
487
+ "data" in download
488
+ ? download.data
489
+ : download;
490
+ const contentType = download &&
491
+ typeof download === "object" &&
492
+ "contentType" in download
493
+ ? download.contentType
494
+ : "application/octet-stream";
495
+ const filename = download &&
496
+ typeof download === "object" &&
497
+ "filename" in download
498
+ ? download.filename
499
+ : undefined;
500
+ if (typeof res.setHeader === "function") {
501
+ res.setHeader("Content-Type", contentType);
502
+ if (filename) {
503
+ res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
504
+ }
505
+ }
506
+ if (typeof res.send === "function") {
507
+ res.send(data);
508
+ return;
509
+ }
510
+ }
511
+ res.json(result);
512
+ }
513
+ catch (error) {
514
+ next(error);
515
+ }
516
+ });
517
+ });
518
+ });
519
+ }
520
+
521
+ var express = /*#__PURE__*/Object.freeze({
522
+ __proto__: null,
523
+ handleContract: handleContract$6
524
+ });
525
+
526
+ // Helper para obtener NextResponse (asumiendo que el usuario lo tiene disponible o lo importamos dinámicamente si fuera un paquete real)
527
+ // Aquí simularemos una respuesta JSON estándar
528
+ function jsonResponse(data, status = 200) {
529
+ return new Response(JSON.stringify(data), {
530
+ status,
531
+ headers: { "Content-Type": "application/json" },
532
+ });
533
+ }
534
+ function handleContract$5(contract, handlers) {
535
+ // Retorna un handler compatible con Route Handlers de Next.js (App Router)
536
+ // Uso: export const { GET, POST, PUT, DELETE } = adapters.next.handleContract(contract, handlers);
537
+ // en app/api/[...route]/route.ts
538
+ const dispatcher = async (req, { params }) => {
539
+ const url = new URL(req.url);
540
+ // En App Router [...route], params.route es un array. Pero aquí asumimos que el usuario mapea rutas específicas o catch-all.
541
+ // Si es catch-all, necesitamos reconstruir la ruta.
542
+ // Simplificación: Iteramos sobre el contrato para encontrar la ruta que coincida.
543
+ // Esto es ineficiente O(N) por request, pero funciona para validación.
544
+ // Una implementación más robusta usaría un router interno.
545
+ const method = req.method;
546
+ const path = url.pathname; // Ojo: esto incluye el prefijo /api si está ahí.
547
+ // Intentar hacer match con las rutas del contrato
548
+ const schema = contract.schema;
549
+ for (const routePattern of Object.keys(schema)) {
550
+ // Convertir /users/:id a regex simple
551
+ const regexPattern = routePattern.replace(/:[a-zA-Z0-9_]+/g, "([^/]+)");
552
+ const regex = new RegExp(`^.*${regexPattern}$`); // ^.* para permitir prefijos como /api
553
+ const match = path.match(regex);
554
+ if (match) {
555
+ // Verificar método
556
+ const routeMethods = schema[routePattern];
557
+ if (routeMethods[method]) {
558
+ const endpoint = `${method} ${routePattern}`;
559
+ const implementation = handlers[endpoint];
560
+ const methodSchema = routeMethods[method];
561
+ if (!implementation)
562
+ return jsonResponse({ error: "Not Implemented" }, 501);
563
+ const contextParams = params || {};
564
+ const wrapped = contract.handle(endpoint, implementation);
565
+ try {
566
+ // Parse body safely
567
+ let body = undefined;
568
+ if (method !== 'GET' && method !== 'HEAD') {
569
+ try {
570
+ body = await req.json();
571
+ }
572
+ catch { }
573
+ }
574
+ const context = {
575
+ params: contextParams,
576
+ query: Object.fromEntries(url.searchParams.entries()),
577
+ body,
578
+ headers: Object.fromEntries(req.headers.entries()),
579
+ };
580
+ const result = await wrapped(context);
581
+ const media = methodSchema?.media;
582
+ if (media && media.kind === "download") {
583
+ const download = result;
584
+ const hasData = download &&
585
+ typeof download === "object" &&
586
+ Object.prototype.hasOwnProperty.call(download, "data");
587
+ const data = hasData
588
+ ? download.data
589
+ : download;
590
+ const contentType = download &&
591
+ typeof download === "object" &&
592
+ "contentType" in download &&
593
+ typeof download.contentType ===
594
+ "string"
595
+ ? download.contentType
596
+ : "application/octet-stream";
597
+ const filename = download &&
598
+ typeof download === "object" &&
599
+ "filename" in download &&
600
+ typeof download.filename ===
601
+ "string"
602
+ ? download.filename
603
+ : undefined;
604
+ const headers = {
605
+ "Content-Type": String(contentType),
606
+ };
607
+ if (filename) {
608
+ headers["Content-Disposition"] =
609
+ `attachment; filename="${filename}"`;
610
+ }
611
+ return new Response(data, {
612
+ status: 200,
613
+ headers,
614
+ });
615
+ }
616
+ return jsonResponse(result);
617
+ }
618
+ catch (err) {
619
+ const payload = buildErrorPayload(err);
620
+ return jsonResponse(payload, payload.status);
621
+ }
622
+ }
623
+ }
624
+ }
625
+ return jsonResponse({ error: "Not Found" }, 404);
626
+ };
627
+ return {
628
+ GET: dispatcher,
629
+ POST: dispatcher,
630
+ PUT: dispatcher,
631
+ DELETE: dispatcher,
632
+ PATCH: dispatcher,
633
+ };
634
+ }
635
+
636
+ var next = /*#__PURE__*/Object.freeze({
637
+ __proto__: null,
638
+ handleContract: handleContract$5
639
+ });
640
+
641
+ function handleContract$4(fastify, contract, handlers) {
642
+ const schema = contract.schema;
643
+ Object.keys(schema).forEach((route) => {
644
+ const methods = schema[route];
645
+ Object.keys(methods).forEach((method) => {
646
+ const endpoint = `${method} ${route}`;
647
+ const implementation = handlers[endpoint];
648
+ const methodSchema = methods[method];
649
+ if (!implementation) {
650
+ return;
651
+ }
652
+ const wrapped = contract.handle(endpoint, implementation);
653
+ fastify.route({
654
+ method: method,
655
+ url: route, // Fastify soporta /:id sintaxis
656
+ handler: async (request, reply) => {
657
+ try {
658
+ const context = {
659
+ params: request.params || {},
660
+ query: request.query || {},
661
+ body: request.body,
662
+ headers: request.headers || {},
663
+ user: request.user,
664
+ };
665
+ const result = await wrapped(context);
666
+ const media = methodSchema?.media;
667
+ if (media && media.kind === "download") {
668
+ const download = result;
669
+ const data = download &&
670
+ typeof download === "object" &&
671
+ "data" in download
672
+ ? download.data
673
+ : download;
674
+ const contentType = download &&
675
+ typeof download === "object" &&
676
+ "contentType" in download
677
+ ? download.contentType
678
+ : "application/octet-stream";
679
+ const filename = download &&
680
+ typeof download === "object" &&
681
+ "filename" in download
682
+ ? download.filename
683
+ : undefined;
684
+ if (typeof reply.header === "function") {
685
+ reply.header("Content-Type", contentType);
686
+ if (filename) {
687
+ reply.header("Content-Disposition", `attachment; filename="${filename}"`);
688
+ }
689
+ }
690
+ reply.send(data);
691
+ return;
692
+ }
693
+ reply.send(result);
694
+ }
695
+ catch (error) {
696
+ const payload = buildErrorPayload(error);
697
+ reply.status(payload.status).send(payload);
698
+ }
699
+ },
700
+ });
701
+ });
702
+ });
703
+ }
704
+
705
+ var fastify = /*#__PURE__*/Object.freeze({
706
+ __proto__: null,
707
+ handleContract: handleContract$4
708
+ });
709
+
710
+ const SchemaApiModule = {
711
+ register(app, contract, handlers) {
712
+ const adapter = app.getHttpAdapter();
713
+ const schema = contract.schema;
714
+ Object.keys(schema).forEach((route) => {
715
+ const methods = schema[route];
716
+ Object.keys(methods).forEach((method) => {
717
+ const endpoint = `${method} ${route}`;
718
+ const implementation = handlers[endpoint];
719
+ if (!implementation) {
720
+ return;
721
+ }
722
+ const wrapped = contract.handle(endpoint, implementation);
723
+ const methodLower = method.toLowerCase();
724
+ if (typeof adapter[methodLower] === "function") {
725
+ adapter[methodLower](route, async (req, res, _next) => {
726
+ try {
727
+ // Intentamos normalizar request/response independientemente del driver (Express/Fastify)
728
+ // Nota: Esto asume Express por defecto para req.params/query/body.
729
+ // En Fastify, req.params/query/body también existen en el objeto Request estándar de Fastify.
730
+ const context = {
731
+ params: req.params || {},
732
+ query: req.query || {},
733
+ body: req.body,
734
+ headers: req.headers || {},
735
+ user: req.user,
736
+ };
737
+ const result = await wrapped(context);
738
+ // Responder
739
+ if (typeof res.send === "function") {
740
+ // Express / Fastify
741
+ res.send(result);
742
+ }
743
+ else if (typeof res.json === "function") {
744
+ // Express alternative
745
+ res.json(result);
746
+ }
747
+ else {
748
+ // Fallback simple
749
+ res.end(JSON.stringify(result));
750
+ }
751
+ }
752
+ catch (error) {
753
+ const typedError = error;
754
+ if (res.status)
755
+ res.status(typedError.status || 500);
756
+ else if (res.code)
757
+ res.code(typedError.status || 500); // Fastify
758
+ if (res.send)
759
+ res.send({ error: typedError.message });
760
+ else
761
+ res.end(JSON.stringify({ error: typedError.message }));
762
+ }
763
+ });
764
+ }
765
+ });
766
+ });
767
+ },
768
+ };
769
+
770
+ var nest = /*#__PURE__*/Object.freeze({
771
+ __proto__: null,
772
+ SchemaApiModule: SchemaApiModule
773
+ });
774
+
775
+ function handleContract$3(router, contract, handlers) {
776
+ const schema = contract.schema;
777
+ Object.keys(schema).forEach((route) => {
778
+ const methods = schema[route];
779
+ Object.keys(methods).forEach((method) => {
780
+ const endpoint = `${method} ${route}`;
781
+ const implementation = handlers[endpoint];
782
+ const methodSchema = methods[method];
783
+ if (!implementation) {
784
+ return;
785
+ }
786
+ const wrapped = contract.handle(endpoint, implementation);
787
+ // Koa Router register
788
+ router.register(route, [method], async (ctx, _next) => {
789
+ try {
790
+ const context = {
791
+ params: ctx.params || {},
792
+ query: ctx.query || {},
793
+ body: ctx.request.body, // requires koa-bodyparser or koa-body
794
+ headers: ctx.headers || {},
795
+ user: ctx.state?.user, // common pattern
796
+ };
797
+ const result = await wrapped(context);
798
+ const media = methodSchema?.media;
799
+ if (media && media.kind === "download") {
800
+ const download = result;
801
+ const data = download &&
802
+ typeof download === "object" &&
803
+ "data" in download
804
+ ? download.data
805
+ : download;
806
+ const contentType = download &&
807
+ typeof download === "object" &&
808
+ "contentType" in download
809
+ ? download.contentType
810
+ : "application/octet-stream";
811
+ const filename = download &&
812
+ typeof download === "object" &&
813
+ "filename" in download
814
+ ? download.filename
815
+ : undefined;
816
+ ctx.body = data;
817
+ ctx.type = contentType;
818
+ if (filename) {
819
+ ctx.set("Content-Disposition", `attachment; filename="${filename}"`);
820
+ }
821
+ }
822
+ else {
823
+ ctx.body = result;
824
+ }
825
+ }
826
+ catch (error) {
827
+ const payload = buildErrorPayload(error);
828
+ ctx.status = payload.status;
829
+ ctx.body = payload;
830
+ }
831
+ });
832
+ });
833
+ });
834
+ }
835
+
836
+ var koa = /*#__PURE__*/Object.freeze({
837
+ __proto__: null,
838
+ handleContract: handleContract$3
839
+ });
840
+
841
+ function handleContract$2(server, contract, handlers) {
842
+ const schema = contract.schema;
843
+ Object.keys(schema).forEach((route) => {
844
+ const methods = schema[route];
845
+ // Convertir ruta express-style :param a hapi-style {param}
846
+ const hapiRoute = route.replace(/:([a-zA-Z0-9_]+)/g, "{$1}");
847
+ Object.keys(methods).forEach((method) => {
848
+ const endpoint = `${method} ${route}`;
849
+ const implementation = handlers[endpoint];
850
+ const methodSchema = methods[method];
851
+ if (!implementation) {
852
+ return;
853
+ }
854
+ const wrapped = contract.handle(endpoint, implementation);
855
+ server.route({
856
+ method: method,
857
+ path: hapiRoute,
858
+ handler: async (request, h) => {
859
+ try {
860
+ const context = {
861
+ params: request.params || {},
862
+ query: request.query || {},
863
+ body: request.payload,
864
+ headers: request.headers || {},
865
+ user: request.auth?.credentials, // Common Hapi auth pattern
866
+ };
867
+ const result = await wrapped(context);
868
+ const media = methodSchema?.media;
869
+ if (media && media.kind === "download") {
870
+ const download = result;
871
+ const data = download &&
872
+ typeof download === "object" &&
873
+ "data" in download
874
+ ? download.data
875
+ : download;
876
+ const contentType = download &&
877
+ typeof download === "object" &&
878
+ "contentType" in download
879
+ ? download.contentType
880
+ : "application/octet-stream";
881
+ const filename = download &&
882
+ typeof download === "object" &&
883
+ "filename" in download
884
+ ? download.filename
885
+ : undefined;
886
+ const response = h.response(data);
887
+ response.type(contentType);
888
+ if (filename) {
889
+ response.header("Content-Disposition", `attachment; filename="${filename}"`);
890
+ }
891
+ return response;
892
+ }
893
+ return result;
894
+ }
895
+ catch (error) {
896
+ const payload = buildErrorPayload(error);
897
+ const response = h.response(payload);
898
+ response.code(payload.status);
899
+ return response;
900
+ }
901
+ },
902
+ });
903
+ });
904
+ });
905
+ }
906
+
907
+ var hapi = /*#__PURE__*/Object.freeze({
908
+ __proto__: null,
909
+ handleContract: handleContract$2
910
+ });
911
+
912
+ function createRouteHandlers(contract, handlers, routePattern) {
913
+ const schema = contract.schema;
914
+ const methods = schema[routePattern];
915
+ if (!methods) {
916
+ const notFound = () => {
917
+ throw new Response("Not Found in Contract", { status: 404 });
918
+ };
919
+ return { loader: notFound, action: notFound };
920
+ }
921
+ const handleRequest = async (request, params) => {
922
+ const method = request.method;
923
+ const endpoint = `${method} ${routePattern}`;
924
+ const implementation = handlers[endpoint];
925
+ const methodSchema = methods && methods[method];
926
+ if (!implementation) {
927
+ throw new Response("Method Not Implemented", { status: 501 });
928
+ }
929
+ const wrapped = contract.handle(endpoint, implementation);
930
+ try {
931
+ let body = undefined;
932
+ // Parse body only for non-GET/HEAD methods
933
+ if (method !== "GET" && method !== "HEAD") {
934
+ try {
935
+ body = await request.json();
936
+ }
937
+ catch {
938
+ // Si falla json, tal vez es FormData? Remix usa mucho FormData.
939
+ // Por simplicidad, aquí asumimos JSON como el estándar de SchemaApi.
940
+ // Si se requiere FormData, se debería procesar antes o aquí.
941
+ }
942
+ }
943
+ const url = new URL(request.url);
944
+ const context = {
945
+ params: params || {},
946
+ query: Object.fromEntries(url.searchParams.entries()),
947
+ body,
948
+ headers: Object.fromEntries(request.headers.entries()),
949
+ };
950
+ const result = await wrapped(context);
951
+ const media = methodSchema?.media;
952
+ if (media && media.kind === "download") {
953
+ const download = result;
954
+ const hasData = download &&
955
+ typeof download === "object" &&
956
+ Object.prototype.hasOwnProperty.call(download, "data");
957
+ const data = hasData
958
+ ? download.data
959
+ : download;
960
+ const contentType = download &&
961
+ typeof download === "object" &&
962
+ "contentType" in download &&
963
+ typeof download.contentType ===
964
+ "string"
965
+ ? download.contentType
966
+ : "application/octet-stream";
967
+ const filename = download &&
968
+ typeof download === "object" &&
969
+ "filename" in download &&
970
+ typeof download.filename === "string"
971
+ ? download.filename
972
+ : undefined;
973
+ const headers = {
974
+ "Content-Type": String(contentType),
975
+ };
976
+ if (filename) {
977
+ headers["Content-Disposition"] = `attachment; filename="${filename}"`;
978
+ }
979
+ return new Response(data, {
980
+ headers,
981
+ });
982
+ }
983
+ return new Response(JSON.stringify(result), {
984
+ headers: { "Content-Type": "application/json" },
985
+ });
986
+ }
987
+ catch (err) {
988
+ const payload = buildErrorPayload(err);
989
+ return new Response(JSON.stringify(payload), {
990
+ status: payload.status,
991
+ headers: { "Content-Type": "application/json" },
992
+ });
993
+ }
994
+ };
995
+ const loader = async (args) => {
996
+ if (methods["GET"]) {
997
+ return handleRequest(args.request, args.params);
998
+ }
999
+ // Si no hay GET definido pero se llama al loader
1000
+ throw new Response("Method Not Allowed", { status: 405 });
1001
+ };
1002
+ const action = async (args) => {
1003
+ const method = args.request.method;
1004
+ if (methods[method]) {
1005
+ return handleRequest(args.request, args.params);
1006
+ }
1007
+ throw new Response("Method Not Allowed", { status: 405 });
1008
+ };
1009
+ return { loader, action };
1010
+ }
1011
+
1012
+ var remix = /*#__PURE__*/Object.freeze({
1013
+ __proto__: null,
1014
+ createRouteHandlers: createRouteHandlers
1015
+ });
1016
+
1017
+ function handleContract$1(contract, handlers) {
1018
+ // Retorna una función (req: Request) => Promise<Response> compatible con Deno.serve
1019
+ return async (req) => {
1020
+ const url = new URL(req.url);
1021
+ const path = url.pathname;
1022
+ const method = req.method;
1023
+ const schema = contract.schema;
1024
+ for (const routePattern of Object.keys(schema)) {
1025
+ // Regex simple para matching: /users/:id -> /users/([^/]+)
1026
+ // Agregamos ^ y $ para match exacto
1027
+ const regexPattern = routePattern.replace(/:[a-zA-Z0-9_]+/g, "([^/]+)");
1028
+ const regex = new RegExp(`^${regexPattern}$`);
1029
+ const match = path.match(regex);
1030
+ if (match) {
1031
+ const routeMethods = schema[routePattern];
1032
+ if (routeMethods[method]) {
1033
+ const endpoint = `${method} ${routePattern}`;
1034
+ const implementation = handlers[endpoint];
1035
+ const methodSchema = routeMethods[method];
1036
+ if (!implementation) {
1037
+ return new Response("Not Implemented", { status: 501 });
1038
+ }
1039
+ // Extraer params
1040
+ // Necesitamos saber los nombres de los parámetros para mapearlos
1041
+ // routePattern: /users/:id/posts/:postId
1042
+ // match: [..., "123", "456"]
1043
+ const paramNames = (routePattern.match(/:[a-zA-Z0-9_]+/g) || []).map((p) => p.substring(1));
1044
+ const params = {};
1045
+ paramNames.forEach((name, index) => {
1046
+ params[name] = match[index + 1];
1047
+ });
1048
+ const wrapped = contract.handle(endpoint, implementation);
1049
+ try {
1050
+ let body = undefined;
1051
+ if (method !== "GET" && method !== "HEAD") {
1052
+ try {
1053
+ body = await req.json();
1054
+ }
1055
+ catch { }
1056
+ }
1057
+ const context = {
1058
+ params,
1059
+ query: Object.fromEntries(url.searchParams.entries()),
1060
+ body,
1061
+ headers: Object.fromEntries(req.headers.entries()),
1062
+ };
1063
+ const result = await wrapped(context);
1064
+ const media = methodSchema?.media;
1065
+ if (media && media.kind === "download") {
1066
+ const download = result;
1067
+ const data = download &&
1068
+ typeof download === "object" &&
1069
+ "data" in download
1070
+ ? download.data
1071
+ : download;
1072
+ const contentType = download &&
1073
+ typeof download === "object" &&
1074
+ "contentType" in download
1075
+ ? download.contentType
1076
+ : "application/octet-stream";
1077
+ const filename = download &&
1078
+ typeof download === "object" &&
1079
+ "filename" in download
1080
+ ? download.filename
1081
+ : undefined;
1082
+ const headers = {
1083
+ "Content-Type": String(contentType),
1084
+ };
1085
+ if (filename) {
1086
+ headers["Content-Disposition"] = `attachment; filename="${filename}"`;
1087
+ }
1088
+ return new Response(data, {
1089
+ headers,
1090
+ });
1091
+ }
1092
+ return new Response(JSON.stringify(result), {
1093
+ headers: { "Content-Type": "application/json" },
1094
+ });
1095
+ }
1096
+ catch (err) {
1097
+ const payload = buildErrorPayload(err);
1098
+ return new Response(JSON.stringify(payload), {
1099
+ status: payload.status,
1100
+ headers: { "Content-Type": "application/json" },
1101
+ });
1102
+ }
1103
+ }
1104
+ }
1105
+ }
1106
+ return new Response("Not Found", { status: 404 });
1107
+ };
1108
+ }
1109
+
1110
+ var deno = /*#__PURE__*/Object.freeze({
1111
+ __proto__: null,
1112
+ handleContract: handleContract$1
1113
+ });
1114
+
1115
+ function handleContract(wss, contract, handlers) {
1116
+ const schema = contract.schema;
1117
+ wss.on("connection", async (ws, req) => {
1118
+ const url = req.url ? new URL(req.url, "http://localhost") : null;
1119
+ if (!url) {
1120
+ ws.close(1002, "Invalid URL");
1121
+ return;
1122
+ }
1123
+ const path = url.pathname;
1124
+ let matched = false;
1125
+ for (const routePattern of Object.keys(schema)) {
1126
+ const methods = schema[routePattern];
1127
+ const wsDef = methods["WS"];
1128
+ if (!wsDef)
1129
+ continue;
1130
+ // Match path
1131
+ const regexPattern = routePattern.replace(/:[a-zA-Z0-9_]+/g, "([^/]+)");
1132
+ const regex = new RegExp(`^${regexPattern}$`);
1133
+ const match = path.match(regex);
1134
+ if (match) {
1135
+ matched = true;
1136
+ const implementation = handlers[`WS ${routePattern}`];
1137
+ if (!implementation) {
1138
+ ws.close(1011, "Handler not found");
1139
+ return;
1140
+ }
1141
+ // Extract params
1142
+ const paramNames = (routePattern.match(/:[a-zA-Z0-9_]+/g) || []).map((p) => p.substring(1));
1143
+ const params = {};
1144
+ paramNames.forEach((name, index) => {
1145
+ params[name] = match[index + 1];
1146
+ });
1147
+ const query = Object.fromEntries(url.searchParams.entries());
1148
+ const context = {
1149
+ params,
1150
+ query,
1151
+ headers: req.headers,
1152
+ ws,
1153
+ send: (data) => {
1154
+ if (wsDef.serverMessages) {
1155
+ try {
1156
+ wsDef.serverMessages.parse(data);
1157
+ }
1158
+ catch (e) {
1159
+ console.error("Server message validation failed", e);
1160
+ }
1161
+ }
1162
+ ws.send(JSON.stringify(data));
1163
+ },
1164
+ onMessage: (cb) => {
1165
+ ws.on("message", (raw) => {
1166
+ try {
1167
+ const json = JSON.parse(raw.toString());
1168
+ if (wsDef.clientMessages) {
1169
+ try {
1170
+ const parsed = wsDef.clientMessages.parse(json);
1171
+ cb(parsed);
1172
+ }
1173
+ catch (e) {
1174
+ console.error("Client message validation failed", e);
1175
+ ws.send(JSON.stringify({
1176
+ error: "Invalid Message Schema",
1177
+ details: e,
1178
+ }));
1179
+ }
1180
+ }
1181
+ else {
1182
+ cb(json);
1183
+ }
1184
+ }
1185
+ catch (e) {
1186
+ console.error("Invalid JSON", e);
1187
+ }
1188
+ });
1189
+ },
1190
+ };
1191
+ try {
1192
+ await implementation(context);
1193
+ }
1194
+ catch (e) {
1195
+ console.error("Error in WS handler", e);
1196
+ ws.close(1011, "Internal Error");
1197
+ }
1198
+ break;
1199
+ }
1200
+ }
1201
+ if (!matched) {
1202
+ ws.close(4404, "Not Found");
1203
+ }
1204
+ });
1205
+ return wss;
1206
+ }
1207
+
1208
+ var ws = /*#__PURE__*/Object.freeze({
1209
+ __proto__: null,
1210
+ handleContract: handleContract
1211
+ });
1212
+
1213
+ var index = /*#__PURE__*/Object.freeze({
1214
+ __proto__: null,
1215
+ deno: deno,
1216
+ express: express,
1217
+ fastify: fastify,
1218
+ hapi: hapi,
1219
+ koa: koa,
1220
+ nest: nest,
1221
+ next: next,
1222
+ remix: remix,
1223
+ ws: ws
1224
+ });
1225
+
1226
+ function renderDocsJSON(docs) {
1227
+ return JSON.stringify(docs, null, 2);
1228
+ }
1229
+ function renderDocsText(docs) {
1230
+ const lines = [];
1231
+ lines.push("SchemaApi Contract");
1232
+ lines.push("================================");
1233
+ docs.routes.forEach((route) => {
1234
+ lines.push("");
1235
+ lines.push(`${route.method} ${route.path}`);
1236
+ lines.push("-".repeat((route.method + route.path).length + 1));
1237
+ if (route.roles && route.roles.length > 0) {
1238
+ lines.push(`roles: ${route.roles.join(", ")}`);
1239
+ }
1240
+ if (route.media) {
1241
+ const mediaParts = [];
1242
+ if (route.media.kind) {
1243
+ mediaParts.push(`kind=${route.media.kind}`);
1244
+ }
1245
+ if (route.media.contentTypes && route.media.contentTypes.length > 0) {
1246
+ mediaParts.push(`types=[${route.media.contentTypes.join(", ")}]`);
1247
+ }
1248
+ if (route.media.maxSize) {
1249
+ mediaParts.push(`maxSize=${route.media.maxSize}`);
1250
+ }
1251
+ lines.push(`media: ${mediaParts.join(" ")}`);
1252
+ }
1253
+ const renderSection = (name, fields) => {
1254
+ if (!fields || fields.length === 0) {
1255
+ return;
1256
+ }
1257
+ lines.push(``);
1258
+ lines.push(`${name}:`);
1259
+ fields.forEach((f) => {
1260
+ const flag = f.optional ? "optional" : "required";
1261
+ const typeName = f.type ? f.type : "unknown";
1262
+ lines.push(` - ${f.name}: ${typeName} (${flag})`);
1263
+ });
1264
+ };
1265
+ renderSection("params", route.params);
1266
+ renderSection("query", route.query);
1267
+ renderSection("body", route.body);
1268
+ renderSection("headers", route.headers);
1269
+ if (route.errors && route.errors.length > 0) {
1270
+ lines.push("");
1271
+ lines.push("errors:");
1272
+ route.errors.forEach((e) => {
1273
+ lines.push(` - ${e.status}: ${e.code}`);
1274
+ });
1275
+ }
1276
+ });
1277
+ return lines.join("\n");
1278
+ }
1279
+ function getThemeBackground(theme) {
1280
+ if (theme === "dark") {
1281
+ return "#020617";
1282
+ }
1283
+ if (theme === "light") {
1284
+ return "#f9fafb";
1285
+ }
1286
+ return "#0b1120";
1287
+ }
1288
+ function getThemeForeground(theme) {
1289
+ if (theme === "dark") {
1290
+ return "#e5e7eb";
1291
+ }
1292
+ if (theme === "light") {
1293
+ return "#111827";
1294
+ }
1295
+ return "#e5e7eb";
1296
+ }
1297
+ function renderDocsHTML(docs, options) {
1298
+ const title = options?.title ?? "SchemaApi Docs";
1299
+ const bg = getThemeBackground(options?.theme);
1300
+ const fg = getThemeForeground(options?.theme);
1301
+ const escape = (value) => {
1302
+ if (value === undefined || value === null) {
1303
+ return "";
1304
+ }
1305
+ return String(value)
1306
+ .replace(/&/g, "&amp;")
1307
+ .replace(/</g, "&lt;")
1308
+ .replace(/>/g, "&gt;")
1309
+ .replace(/"/g, "&quot;");
1310
+ };
1311
+ const renderFieldsTable = (caption, fields) => {
1312
+ if (!fields || fields.length === 0) {
1313
+ return "";
1314
+ }
1315
+ const rows = fields
1316
+ .map((f) => {
1317
+ const typeName = f.type ? f.type : "unknown";
1318
+ const badge = f.optional ? "optional" : "required";
1319
+ return `<tr>
1320
+ <td class="field-name">${escape(f.name)}</td>
1321
+ <td class="field-type">${escape(typeName)}</td>
1322
+ <td class="field-badge ${badge}">${badge}</td>
1323
+ </tr>`;
1324
+ })
1325
+ .join("\n");
1326
+ return `<section class="block">
1327
+ <div class="block-title">${escape(caption)}</div>
1328
+ <table class="fields">
1329
+ <thead>
1330
+ <tr>
1331
+ <th>name</th>
1332
+ <th>type</th>
1333
+ <th>required</th>
1334
+ </tr>
1335
+ </thead>
1336
+ <tbody>
1337
+ ${rows}
1338
+ </tbody>
1339
+ </table>
1340
+ </section>`;
1341
+ };
1342
+ const renderRoute = (route) => {
1343
+ const method = escape(route.method);
1344
+ const path = escape(route.path);
1345
+ const roles = route.roles && route.roles.length > 0
1346
+ ? `<div class="pill-group">
1347
+ ${route.roles
1348
+ .map((r) => `<span class="pill pill-role">role: ${escape(r)}</span>`)
1349
+ .join("\n")}
1350
+ </div>`
1351
+ : "";
1352
+ const media = route.media
1353
+ ? (() => {
1354
+ const parts = [];
1355
+ if (route.media?.kind) {
1356
+ parts.push(`kind=${escape(route.media.kind)}`);
1357
+ }
1358
+ if (route.media?.contentTypes && route.media.contentTypes.length) {
1359
+ parts.push(`types=[${route.media.contentTypes
1360
+ .map((t) => escape(t))
1361
+ .join(", ")}]`);
1362
+ }
1363
+ if (route.media?.maxSize) {
1364
+ parts.push(`maxSize=${escape(route.media.maxSize)}`);
1365
+ }
1366
+ return `<div class="pill-group">
1367
+ <span class="pill pill-media">media ${parts.join(" · ")}</span>
1368
+ </div>`;
1369
+ })()
1370
+ : "";
1371
+ const errors = route.errors && route.errors.length > 0
1372
+ ? `<section class="block">
1373
+ <div class="block-title">errors</div>
1374
+ <table class="fields">
1375
+ <thead>
1376
+ <tr>
1377
+ <th>status</th>
1378
+ <th>code</th>
1379
+ </tr>
1380
+ </thead>
1381
+ <tbody>
1382
+ ${route.errors
1383
+ .map((e) => `<tr>
1384
+ <td class="field-status">${escape(e.status)}</td>
1385
+ <td class="field-error-code">${escape(e.code)}</td>
1386
+ </tr>`)
1387
+ .join("\n")}
1388
+ </tbody>
1389
+ </table>
1390
+ </section>`
1391
+ : "";
1392
+ const params = renderFieldsTable("params", route.params);
1393
+ const query = renderFieldsTable("query", route.query);
1394
+ const body = renderFieldsTable("body", route.body);
1395
+ const headers = renderFieldsTable("headers", route.headers);
1396
+ return `<article class="route-card route-${method.toLowerCase()}">
1397
+ <header class="route-header">
1398
+ <span class="method method-${method.toLowerCase()}">${method}</span>
1399
+ <span class="path">${path}</span>
1400
+ </header>
1401
+ <div class="route-meta">
1402
+ ${roles}
1403
+ ${media}
1404
+ </div>
1405
+ <div class="route-content">
1406
+ ${params}
1407
+ ${query}
1408
+ ${body}
1409
+ ${headers}
1410
+ ${errors}
1411
+ </div>
1412
+ </article>`;
1413
+ };
1414
+ const routesHtml = docs.routes.map((r) => renderRoute(r)).join("\n");
1415
+ return `<!doctype html>
1416
+ <html lang="en">
1417
+ <head>
1418
+ <meta charset="utf-8" />
1419
+ <title>${escape(title)}</title>
1420
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1421
+ <style>
1422
+ :root {
1423
+ --bg: ${bg};
1424
+ --fg: ${fg};
1425
+ --accent: #38bdf8;
1426
+ --accent-soft: rgba(56, 189, 248, 0.12);
1427
+ --card-bg: rgba(15, 23, 42, 0.9);
1428
+ --border-subtle: rgba(148, 163, 184, 0.35);
1429
+ --badge-get: #22c55e;
1430
+ --badge-post: #3b82f6;
1431
+ --badge-put: #eab308;
1432
+ --badge-delete: #ef4444;
1433
+ --badge-other: #a855f7;
1434
+ --font-sans: system-ui, -apple-system, BlinkMacSystemFont, "SF Pro Text",
1435
+ "Inter", sans-serif;
1436
+ --font-mono: ui-monospace, Menlo, Monaco, Consolas, "Liberation Mono",
1437
+ "Courier New", monospace;
1438
+ }
1439
+
1440
+ * {
1441
+ box-sizing: border-box;
1442
+ }
1443
+
1444
+ body {
1445
+ margin: 0;
1446
+ padding: 2.5rem 1.5rem 3rem;
1447
+ background: radial-gradient(circle at top left, #0f172a 0, var(--bg) 45%),
1448
+ radial-gradient(circle at bottom right, #020617 0, var(--bg) 55%);
1449
+ color: var(--fg);
1450
+ font-family: var(--font-sans);
1451
+ -webkit-font-smoothing: antialiased;
1452
+ }
1453
+
1454
+ .shell {
1455
+ max-width: 1120px;
1456
+ margin: 0 auto;
1457
+ }
1458
+
1459
+ .masthead {
1460
+ display: flex;
1461
+ flex-direction: column;
1462
+ gap: 0.75rem;
1463
+ margin-bottom: 2rem;
1464
+ }
1465
+
1466
+ .brand {
1467
+ display: inline-flex;
1468
+ align-items: center;
1469
+ gap: 0.5rem;
1470
+ font-family: var(--font-mono);
1471
+ font-size: 0.9rem;
1472
+ letter-spacing: 0.12em;
1473
+ text-transform: uppercase;
1474
+ color: #9ca3af;
1475
+ }
1476
+
1477
+ .brand-mark {
1478
+ width: 0.65rem;
1479
+ height: 0.65rem;
1480
+ border-radius: 999px;
1481
+ background: radial-gradient(circle at 30% 30%, #e5e7eb, #38bdf8);
1482
+ box-shadow: 0 0 0 4px rgba(56, 189, 248, 0.2);
1483
+ }
1484
+
1485
+ .title {
1486
+ font-size: 1.9rem;
1487
+ font-weight: 600;
1488
+ letter-spacing: -0.03em;
1489
+ }
1490
+
1491
+ .subtitle {
1492
+ font-size: 0.95rem;
1493
+ color: #9ca3af;
1494
+ max-width: 520px;
1495
+ }
1496
+
1497
+ .routes-grid {
1498
+ display: grid;
1499
+ grid-template-columns: minmax(0, 1fr);
1500
+ gap: 1rem;
1501
+ }
1502
+
1503
+ @media (min-width: 900px) {
1504
+ .routes-grid {
1505
+ grid-template-columns: repeat(2, minmax(0, 1fr));
1506
+ }
1507
+ }
1508
+
1509
+ .route-card {
1510
+ border-radius: 1rem;
1511
+ padding: 1rem 1.1rem 1.1rem;
1512
+ background: rgba(15, 23, 42, 0.92);
1513
+ border: 1px solid var(--border-subtle);
1514
+ box-shadow: 0 18px 55px rgba(15, 23, 42, 0.8);
1515
+ display: flex;
1516
+ flex-direction: column;
1517
+ gap: 0.75rem;
1518
+ }
1519
+
1520
+ .route-header {
1521
+ display: flex;
1522
+ align-items: center;
1523
+ gap: 0.75rem;
1524
+ font-family: var(--font-mono);
1525
+ font-size: 0.85rem;
1526
+ letter-spacing: 0.06em;
1527
+ text-transform: uppercase;
1528
+ }
1529
+
1530
+ .method {
1531
+ padding: 0.15rem 0.55rem;
1532
+ border-radius: 999px;
1533
+ border: 1px solid rgba(148, 163, 184, 0.5);
1534
+ background: rgba(15, 23, 42, 0.8);
1535
+ }
1536
+
1537
+ .method-get {
1538
+ border-color: rgba(34, 197, 94, 0.6);
1539
+ color: #bbf7d0;
1540
+ background: rgba(34, 197, 94, 0.08);
1541
+ }
1542
+
1543
+ .method-post {
1544
+ border-color: rgba(59, 130, 246, 0.6);
1545
+ color: #bfdbfe;
1546
+ background: rgba(59, 130, 246, 0.08);
1547
+ }
1548
+
1549
+ .method-put {
1550
+ border-color: rgba(234, 179, 8, 0.6);
1551
+ color: #fef9c3;
1552
+ background: rgba(234, 179, 8, 0.08);
1553
+ }
1554
+
1555
+ .method-delete {
1556
+ border-color: rgba(239, 68, 68, 0.6);
1557
+ color: #fee2e2;
1558
+ background: rgba(239, 68, 68, 0.08);
1559
+ }
1560
+
1561
+ .method-patch {
1562
+ border-color: rgba(168, 85, 247, 0.6);
1563
+ color: #ede9fe;
1564
+ background: rgba(168, 85, 247, 0.08);
1565
+ }
1566
+
1567
+ .path {
1568
+ padding: 0.1rem 0.65rem;
1569
+ border-radius: 999px;
1570
+ background: radial-gradient(circle at 0% 0%, #0f172a, #020617);
1571
+ border: 1px solid rgba(148, 163, 184, 0.5);
1572
+ color: #e5e7eb;
1573
+ }
1574
+
1575
+ .route-meta {
1576
+ display: flex;
1577
+ flex-direction: column;
1578
+ gap: 0.25rem;
1579
+ }
1580
+
1581
+ .pill-group {
1582
+ display: flex;
1583
+ flex-wrap: wrap;
1584
+ gap: 0.25rem;
1585
+ }
1586
+
1587
+ .pill {
1588
+ font-family: var(--font-mono);
1589
+ font-size: 0.7rem;
1590
+ padding: 0.1rem 0.45rem;
1591
+ border-radius: 999px;
1592
+ border: 1px solid rgba(148, 163, 184, 0.4);
1593
+ background: rgba(15, 23, 42, 0.9);
1594
+ color: #9ca3af;
1595
+ }
1596
+
1597
+ .pill-role {
1598
+ border-color: rgba(52, 211, 153, 0.5);
1599
+ color: #a7f3d0;
1600
+ }
1601
+
1602
+ .pill-media {
1603
+ border-color: rgba(56, 189, 248, 0.6);
1604
+ color: #bae6fd;
1605
+ background: rgba(15, 23, 42, 0.9);
1606
+ }
1607
+
1608
+ .route-content {
1609
+ display: flex;
1610
+ flex-direction: column;
1611
+ gap: 0.6rem;
1612
+ margin-top: 0.2rem;
1613
+ }
1614
+
1615
+ .block {
1616
+ border-radius: 0.75rem;
1617
+ border: 1px solid rgba(31, 41, 55, 0.9);
1618
+ background: radial-gradient(circle at top left, #020617, #020617);
1619
+ padding: 0.6rem 0.7rem 0.55rem;
1620
+ }
1621
+
1622
+ .block-title {
1623
+ font-family: var(--font-mono);
1624
+ font-size: 0.65rem;
1625
+ letter-spacing: 0.2em;
1626
+ text-transform: uppercase;
1627
+ color: #6b7280;
1628
+ margin-bottom: 0.35rem;
1629
+ }
1630
+
1631
+ table.fields {
1632
+ width: 100%;
1633
+ border-collapse: collapse;
1634
+ font-size: 0.8rem;
1635
+ font-family: var(--font-mono);
1636
+ }
1637
+
1638
+ table.fields th {
1639
+ text-align: left;
1640
+ font-weight: 500;
1641
+ color: #9ca3af;
1642
+ padding-bottom: 0.2rem;
1643
+ }
1644
+
1645
+ table.fields td {
1646
+ padding: 0.12rem 0;
1647
+ }
1648
+
1649
+ .field-name {
1650
+ color: #e5e7eb;
1651
+ }
1652
+
1653
+ .field-type {
1654
+ color: #a5b4fc;
1655
+ }
1656
+
1657
+ .field-badge {
1658
+ font-size: 0.7rem;
1659
+ padding: 0 0.4rem;
1660
+ border-radius: 999px;
1661
+ border: 1px solid rgba(148, 163, 184, 0.4);
1662
+ color: #9ca3af;
1663
+ }
1664
+
1665
+ .field-badge.required {
1666
+ border-color: rgba(248, 113, 113, 0.6);
1667
+ color: #fecaca;
1668
+ }
1669
+
1670
+ .field-badge.optional {
1671
+ border-color: rgba(59, 130, 246, 0.6);
1672
+ color: #bfdbfe;
1673
+ }
1674
+
1675
+ .field-status {
1676
+ color: #f97316;
1677
+ }
1678
+
1679
+ .field-error-code {
1680
+ color: #fca5a5;
1681
+ }
1682
+ </style>
1683
+ </head>
1684
+ <body>
1685
+ <div class="shell">
1686
+ <header class="masthead">
1687
+ <div class="brand">
1688
+ <span class="brand-mark"></span>
1689
+ <span>SCHEMAAPI · CONTRACT DOCS</span>
1690
+ </div>
1691
+ <h1 class="title">${escape(title)}</h1>
1692
+ <p class="subtitle">
1693
+ Contratos de API descritos directamente desde el runtime. Sin Swagger, sin
1694
+ YAML. Solo SchemaApi como única fuente de verdad.
1695
+ </p>
1696
+ </header>
1697
+ <main class="routes-grid">
1698
+ ${routesHtml}
1699
+ </main>
1700
+ </div>
1701
+ </body>
1702
+ </html>`;
1703
+ }
1704
+ function renderDocs(docs, options) {
1705
+ if (options.format === "json") {
1706
+ return renderDocsJSON(docs);
1707
+ }
1708
+ if (options.format === "html") {
1709
+ return renderDocsHTML(docs, options);
1710
+ }
1711
+ return renderDocsText(docs);
10
1712
  }
11
1713
 
1714
+ exports.SchemaApiError = SchemaApiError;
1715
+ exports.adapters = index;
1716
+ exports.buildErrorPayload = buildErrorPayload;
1717
+ exports.createClient = createClient;
12
1718
  exports.createContract = createContract;
1719
+ exports.generateSDK = generateSDK;
1720
+ exports.renderDocs = renderDocs;
1721
+ exports.renderDocsHTML = renderDocsHTML;
1722
+ exports.renderDocsJSON = renderDocsJSON;
1723
+ exports.renderDocsText = renderDocsText;
13
1724
  //# sourceMappingURL=schemaapi.cjs.js.map