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