@apifn/core 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1582 @@
1
+ import "./chunk-VUNV25KB.js";
2
+
3
+ // src/introspect.ts
4
+ var KNOWN_DESCRIPTOR_KEYS = [
5
+ "body",
6
+ "query",
7
+ "params",
8
+ "responses",
9
+ "summary",
10
+ "operationId",
11
+ "tags",
12
+ "description",
13
+ "deprecated",
14
+ "headers",
15
+ "security"
16
+ ];
17
+ var PATH_PARAM_PATTERN = /:([A-Za-z0-9_]+)/g;
18
+ function isObject(value) {
19
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20
+ }
21
+ function hasSchemaDescriptor(meta) {
22
+ if (!isObject(meta)) {
23
+ return false;
24
+ }
25
+ return KNOWN_DESCRIPTOR_KEYS.some((key) => key in meta);
26
+ }
27
+ function normalizePathSegment(path2) {
28
+ if (!path2.startsWith("/")) {
29
+ return `/${path2}`;
30
+ }
31
+ return path2;
32
+ }
33
+ function withBasePath(path2, basePath) {
34
+ const routePath = normalizePathSegment(path2);
35
+ if (!basePath) {
36
+ return routePath;
37
+ }
38
+ const normalizedBasePath = normalizePathSegment(basePath).replace(/\/+$/, "");
39
+ const normalizedRoutePath = routePath.replace(/^\/+/, "");
40
+ if (!normalizedRoutePath) {
41
+ return normalizedBasePath || "/";
42
+ }
43
+ if (normalizedBasePath === "/") {
44
+ return `/${normalizedRoutePath}`;
45
+ }
46
+ return `${normalizedBasePath}/${normalizedRoutePath}`;
47
+ }
48
+ function toOpenApiPath(path2) {
49
+ const params = [];
50
+ const openApiPath = path2.replace(PATH_PARAM_PATTERN, (_match, param) => {
51
+ params.push(param);
52
+ return `{${param}}`;
53
+ });
54
+ return { path: openApiPath, pathParams: params };
55
+ }
56
+ function pathParamsToDescriptors(pathParams) {
57
+ return pathParams.map((name) => ({
58
+ name,
59
+ in: "path",
60
+ required: true,
61
+ schema: { type: "string" }
62
+ }));
63
+ }
64
+ function applyParameterRecord(parameters, source, location, required) {
65
+ if (!source) {
66
+ return;
67
+ }
68
+ for (const [name, schema] of Object.entries(source)) {
69
+ const existingIndex = parameters.findIndex(
70
+ (parameter) => parameter.in === location && parameter.name === name
71
+ );
72
+ const descriptor = {
73
+ name,
74
+ in: location,
75
+ required,
76
+ schema
77
+ };
78
+ if (existingIndex >= 0) {
79
+ parameters[existingIndex] = descriptor;
80
+ } else {
81
+ parameters.push(descriptor);
82
+ }
83
+ }
84
+ }
85
+ function toRequestBody(descriptor) {
86
+ if (descriptor.body === void 0) {
87
+ return void 0;
88
+ }
89
+ return {
90
+ required: true,
91
+ content: {
92
+ "application/json": {
93
+ schema: descriptor.body
94
+ }
95
+ }
96
+ };
97
+ }
98
+ function toResponse(response) {
99
+ const normalized = {
100
+ description: response.description || "Success"
101
+ };
102
+ if (response.schema !== void 0) {
103
+ normalized.content = {
104
+ "application/json": {
105
+ schema: response.schema
106
+ }
107
+ };
108
+ }
109
+ if (response.headers && isObject(response.headers)) {
110
+ normalized.headers = Object.fromEntries(
111
+ Object.entries(response.headers).map(([name, schema]) => [
112
+ name,
113
+ {
114
+ schema
115
+ }
116
+ ])
117
+ );
118
+ }
119
+ return normalized;
120
+ }
121
+ function toResponses(descriptor) {
122
+ if (!descriptor?.responses || Object.keys(descriptor.responses).length === 0) {
123
+ return { "200": { description: "Success" } };
124
+ }
125
+ const responses = {};
126
+ for (const [status, response] of Object.entries(descriptor.responses)) {
127
+ responses[String(status)] = toResponse(response);
128
+ }
129
+ return responses;
130
+ }
131
+ function shouldIncludePath(path2, prefixes) {
132
+ if (!prefixes || prefixes.length === 0) {
133
+ return true;
134
+ }
135
+ return prefixes.some((prefix) => path2.startsWith(prefix));
136
+ }
137
+ function shouldExcludePath(path2, prefixes) {
138
+ if (!prefixes || prefixes.length === 0) {
139
+ return false;
140
+ }
141
+ return prefixes.some((prefix) => path2.startsWith(prefix));
142
+ }
143
+ function toIntrospectedRoute(route, options) {
144
+ const fullPath = withBasePath(route.path, options.basePath);
145
+ if (!shouldIncludePath(fullPath, options.include)) {
146
+ return null;
147
+ }
148
+ if (shouldExcludePath(fullPath, options.exclude)) {
149
+ return null;
150
+ }
151
+ const { path: path2, pathParams } = toOpenApiPath(fullPath);
152
+ const rawMeta = route.meta;
153
+ const meta = isObject(rawMeta) ? rawMeta : {};
154
+ const descriptor = hasSchemaDescriptor(rawMeta) ? rawMeta : void 0;
155
+ const parameters = pathParamsToDescriptors(pathParams);
156
+ if (descriptor) {
157
+ applyParameterRecord(parameters, descriptor.params, "path", true);
158
+ applyParameterRecord(parameters, descriptor.query, "query", false);
159
+ applyParameterRecord(parameters, descriptor.headers, "header", false);
160
+ }
161
+ return {
162
+ method: route.method,
163
+ path: path2,
164
+ operationId: descriptor?.operationId,
165
+ summary: descriptor?.summary,
166
+ description: descriptor?.description,
167
+ tags: descriptor?.tags,
168
+ deprecated: descriptor?.deprecated,
169
+ parameters,
170
+ requestBody: descriptor ? toRequestBody(descriptor) : void 0,
171
+ responses: toResponses(descriptor),
172
+ security: descriptor?.security,
173
+ meta
174
+ };
175
+ }
176
+ function introspectRouter(router, options = {}) {
177
+ const routes = router.getRoutes();
178
+ const introspected = [];
179
+ for (const route of routes) {
180
+ const item = toIntrospectedRoute(route, options);
181
+ if (item) {
182
+ introspected.push(item);
183
+ }
184
+ }
185
+ return introspected;
186
+ }
187
+
188
+ // src/api-schema.ts
189
+ function apiSchema(descriptor) {
190
+ return descriptor;
191
+ }
192
+
193
+ // src/schema/detect.ts
194
+ function isObject2(value) {
195
+ return typeof value === "object" && value !== null;
196
+ }
197
+ function detectSchemaType(schema) {
198
+ if (!isObject2(schema)) {
199
+ throw new Error("Unsupported schema type: expected object-like schema");
200
+ }
201
+ if ("_def" in schema) {
202
+ return "zod";
203
+ }
204
+ if (/* @__PURE__ */ Symbol.for("TypeBox.Kind") in schema) {
205
+ return "typebox";
206
+ }
207
+ return "jsonschema";
208
+ }
209
+ function assertJsonSchema(schema) {
210
+ if (!isObject2(schema)) {
211
+ throw new Error("Unsupported schema type: expected object-like schema");
212
+ }
213
+ return schema;
214
+ }
215
+
216
+ // src/schema/zod.ts
217
+ import { zodToJsonSchema } from "zod-to-json-schema";
218
+ function cleanupZodSchema(schema) {
219
+ if (Array.isArray(schema)) {
220
+ return schema.map((item) => cleanupZodSchema(item));
221
+ }
222
+ if (!schema || typeof schema !== "object") {
223
+ return schema;
224
+ }
225
+ const input = schema;
226
+ const output = {};
227
+ for (const [key, value] of Object.entries(input)) {
228
+ if (key === "$schema") {
229
+ continue;
230
+ }
231
+ output[key] = cleanupZodSchema(value);
232
+ }
233
+ return output;
234
+ }
235
+ function convertZodSchema(schema) {
236
+ const converted = zodToJsonSchema(schema, {
237
+ $refStrategy: "none",
238
+ target: "jsonSchema2019-09"
239
+ });
240
+ return cleanupZodSchema(converted);
241
+ }
242
+
243
+ // src/schema/typebox.ts
244
+ function stripTypeBoxMetadata(value) {
245
+ if (Array.isArray(value)) {
246
+ return value.map((item) => stripTypeBoxMetadata(item));
247
+ }
248
+ if (!value || typeof value !== "object") {
249
+ return value;
250
+ }
251
+ const input = value;
252
+ const output = {};
253
+ for (const key of Object.keys(input)) {
254
+ output[key] = stripTypeBoxMetadata(input[key]);
255
+ }
256
+ return output;
257
+ }
258
+ function convertTypeBoxSchema(schema) {
259
+ return stripTypeBoxMetadata(schema);
260
+ }
261
+
262
+ // src/schema/convert.ts
263
+ function convertSchema(schema) {
264
+ const schemaType = detectSchemaType(schema);
265
+ if (schemaType === "zod") {
266
+ return convertZodSchema(schema);
267
+ }
268
+ if (schemaType === "typebox") {
269
+ return convertTypeBoxSchema(schema);
270
+ }
271
+ return assertJsonSchema(schema);
272
+ }
273
+
274
+ // src/schema/dedup.ts
275
+ function stableStringify(value) {
276
+ if (Array.isArray(value)) {
277
+ return `[${value.map((item) => stableStringify(item)).join(",")}]`;
278
+ }
279
+ if (value && typeof value === "object") {
280
+ const entries = Object.entries(value).sort(
281
+ ([a], [b]) => a.localeCompare(b)
282
+ );
283
+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`).join(",")}}`;
284
+ }
285
+ return JSON.stringify(value);
286
+ }
287
+ function toComponentName(rawName, usedNames) {
288
+ const cleaned = rawName.replace(/[^A-Za-z0-9_]/g, "");
289
+ const baseName = cleaned.length > 0 ? cleaned : "Schema";
290
+ if (!usedNames.has(baseName)) {
291
+ usedNames.add(baseName);
292
+ return baseName;
293
+ }
294
+ let index = 2;
295
+ while (usedNames.has(`${baseName}${index}`)) {
296
+ index += 1;
297
+ }
298
+ const candidate = `${baseName}${index}`;
299
+ usedNames.add(candidate);
300
+ return candidate;
301
+ }
302
+ function deduplicateSchemas(schemas) {
303
+ const refs = [];
304
+ const components = {};
305
+ const byIdentity = /* @__PURE__ */ new Map();
306
+ const byStructure = /* @__PURE__ */ new Map();
307
+ const usedNames = /* @__PURE__ */ new Set();
308
+ for (let index = 0; index < schemas.length; index += 1) {
309
+ const input = schemas[index];
310
+ const schema = input.schema;
311
+ const identityHit = byIdentity.get(schema);
312
+ if (identityHit) {
313
+ refs.push(`#/components/schemas/${identityHit}`);
314
+ continue;
315
+ }
316
+ const structureKey = stableStringify(schema);
317
+ const structureHit = byStructure.get(structureKey);
318
+ if (structureHit) {
319
+ byIdentity.set(schema, structureHit);
320
+ refs.push(`#/components/schemas/${structureHit}`);
321
+ continue;
322
+ }
323
+ const explicitName = input.name || (typeof schema.title === "string" ? schema.title : void 0);
324
+ const fallbackName = `Schema${index + 1}`;
325
+ const componentName = toComponentName(explicitName ?? fallbackName, usedNames);
326
+ components[componentName] = schema;
327
+ byIdentity.set(schema, componentName);
328
+ byStructure.set(structureKey, componentName);
329
+ refs.push(`#/components/schemas/${componentName}`);
330
+ }
331
+ return { refs, components };
332
+ }
333
+
334
+ // src/openapi/generate.ts
335
+ var METHOD_ORDER = [
336
+ "get",
337
+ "put",
338
+ "post",
339
+ "delete",
340
+ "options",
341
+ "head",
342
+ "patch",
343
+ "trace"
344
+ ];
345
+ function methodKey(method) {
346
+ return method.toLowerCase();
347
+ }
348
+ function toOperationId(route) {
349
+ if (route.operationId) {
350
+ return route.operationId;
351
+ }
352
+ const method = route.method.toLowerCase();
353
+ const pathToken = route.path.replace(/[{}]/g, "").replace(/[^A-Za-z0-9]+/g, " ").trim().split(/\s+/).map(
354
+ (segment, index) => index === 0 ? segment.toLowerCase() : segment.charAt(0).toUpperCase() + segment.slice(1).toLowerCase()
355
+ ).join("");
356
+ return `${method}${pathToken.charAt(0).toUpperCase()}${pathToken.slice(1)}`;
357
+ }
358
+ function sortedUnique(values) {
359
+ return Array.from(new Set(values)).sort((a, b) => a.localeCompare(b));
360
+ }
361
+ function isObject3(value) {
362
+ return typeof value === "object" && value !== null && !Array.isArray(value);
363
+ }
364
+ function normalizeOptionalSchema(schema) {
365
+ if (!isObject3(schema)) {
366
+ return schema;
367
+ }
368
+ const anyOf = schema.anyOf;
369
+ if (!Array.isArray(anyOf) || anyOf.length !== 2) {
370
+ return schema;
371
+ }
372
+ const first = anyOf[0];
373
+ const second = anyOf[1];
374
+ if (isObject3(first) && "not" in first && isObject3(second)) {
375
+ return second;
376
+ }
377
+ return schema;
378
+ }
379
+ function toParameters(route) {
380
+ if (!route.parameters.length) {
381
+ return void 0;
382
+ }
383
+ const parameters = route.parameters.map((parameter) => ({
384
+ name: parameter.name,
385
+ in: parameter.in,
386
+ required: parameter.required,
387
+ description: parameter.description,
388
+ deprecated: parameter.deprecated,
389
+ schema: normalizeOptionalSchema(convertSchema(parameter.schema))
390
+ }));
391
+ return parameters.sort((a, b) => {
392
+ if (a.in !== b.in) {
393
+ return a.in.localeCompare(b.in);
394
+ }
395
+ return a.name.localeCompare(b.name);
396
+ });
397
+ }
398
+ function toResponses2(route) {
399
+ const entries = Object.entries(route.responses);
400
+ const withFallback = entries.length ? entries : [["200", { description: "Success" }]];
401
+ const sorted = withFallback.sort(([a], [b]) => {
402
+ const aNum = Number(a);
403
+ const bNum = Number(b);
404
+ if (Number.isNaN(aNum) || Number.isNaN(bNum)) {
405
+ return a.localeCompare(b);
406
+ }
407
+ return aNum - bNum;
408
+ });
409
+ return Object.fromEntries(
410
+ sorted.map(([status, response]) => {
411
+ const normalized = {
412
+ description: response.description || "Success"
413
+ };
414
+ if (response.content?.["application/json"]?.schema) {
415
+ normalized.content = {
416
+ "application/json": {
417
+ schema: normalizeOptionalSchema(
418
+ convertSchema(response.content["application/json"].schema)
419
+ )
420
+ }
421
+ };
422
+ }
423
+ if (response.headers) {
424
+ normalized.headers = Object.fromEntries(
425
+ Object.entries(response.headers).sort(([a], [b]) => a.localeCompare(b)).map(([header, headerValue]) => [
426
+ header,
427
+ {
428
+ description: headerValue.description,
429
+ schema: normalizeOptionalSchema(convertSchema(headerValue.schema))
430
+ }
431
+ ])
432
+ );
433
+ }
434
+ return [status, normalized];
435
+ })
436
+ );
437
+ }
438
+ function toOperation(route) {
439
+ const operation = {
440
+ operationId: toOperationId(route),
441
+ responses: toResponses2(route)
442
+ };
443
+ if (route.summary) {
444
+ operation.summary = route.summary;
445
+ }
446
+ if (route.description) {
447
+ operation.description = route.description;
448
+ }
449
+ if (route.deprecated !== void 0) {
450
+ operation.deprecated = route.deprecated;
451
+ }
452
+ if (route.tags?.length) {
453
+ operation.tags = sortedUnique(route.tags);
454
+ }
455
+ const parameters = toParameters(route);
456
+ if (parameters?.length) {
457
+ operation.parameters = parameters;
458
+ }
459
+ if (route.requestBody?.content?.["application/json"]?.schema) {
460
+ operation.requestBody = {
461
+ required: route.requestBody.required ?? true,
462
+ description: route.requestBody.description,
463
+ content: {
464
+ "application/json": {
465
+ schema: normalizeOptionalSchema(
466
+ convertSchema(route.requestBody.content["application/json"].schema)
467
+ )
468
+ }
469
+ }
470
+ };
471
+ }
472
+ if (route.security?.length) {
473
+ operation.security = route.security;
474
+ }
475
+ return operation;
476
+ }
477
+ function toPaths(routes) {
478
+ const grouped = /* @__PURE__ */ new Map();
479
+ for (const route of routes) {
480
+ const existing = grouped.get(route.path) ?? [];
481
+ existing.push(route);
482
+ grouped.set(route.path, existing);
483
+ }
484
+ const sortedPaths = Array.from(grouped.entries()).sort(
485
+ ([a], [b]) => a.localeCompare(b)
486
+ );
487
+ const paths = {};
488
+ for (const [path2, pathRoutes] of sortedPaths) {
489
+ const item = {};
490
+ const sortedRoutes = [...pathRoutes].sort(
491
+ (a, b) => METHOD_ORDER.indexOf(methodKey(a.method)) - METHOD_ORDER.indexOf(methodKey(b.method))
492
+ );
493
+ for (const route of sortedRoutes) {
494
+ const key = methodKey(route.method);
495
+ item[key] = toOperation(route);
496
+ }
497
+ paths[path2] = item;
498
+ }
499
+ return paths;
500
+ }
501
+ function collectTags(routes) {
502
+ const tags = sortedUnique(
503
+ routes.flatMap((route) => route.tags ?? []).filter((tag) => Boolean(tag))
504
+ );
505
+ if (!tags.length) {
506
+ return void 0;
507
+ }
508
+ return tags.map((name) => ({ name }));
509
+ }
510
+ function sortObjectDeep(value) {
511
+ if (Array.isArray(value)) {
512
+ return value.map((item) => sortObjectDeep(item));
513
+ }
514
+ if (value && typeof value === "object") {
515
+ const object = value;
516
+ const sorted = Object.keys(object).sort((a, b) => a.localeCompare(b)).reduce((acc, key) => {
517
+ acc[key] = sortObjectDeep(object[key]);
518
+ return acc;
519
+ }, {});
520
+ return sorted;
521
+ }
522
+ return value;
523
+ }
524
+ function generateOpenAPI(routes, options) {
525
+ const paths = toPaths(routes);
526
+ const tags = collectTags(routes);
527
+ const document = {
528
+ openapi: "3.1.0",
529
+ info: options.info,
530
+ paths
531
+ };
532
+ if (options.servers?.length) {
533
+ document.servers = [...options.servers].sort((a, b) => a.url.localeCompare(b.url));
534
+ }
535
+ if (options.security?.length) {
536
+ document.security = options.security;
537
+ }
538
+ if (options.externalDocs) {
539
+ document.externalDocs = options.externalDocs;
540
+ }
541
+ if (tags?.length) {
542
+ document.tags = tags;
543
+ }
544
+ if (options.securitySchemes && Object.keys(options.securitySchemes).length > 0) {
545
+ document.components = {
546
+ ...document.components ?? {},
547
+ securitySchemes: Object.fromEntries(
548
+ Object.entries(options.securitySchemes).sort(([a], [b]) => a.localeCompare(b))
549
+ )
550
+ };
551
+ }
552
+ if (options.extensions) {
553
+ for (const [key, value] of Object.entries(options.extensions)) {
554
+ const extensionKey = key.startsWith("x-") ? key : `x-${key}`;
555
+ document[extensionKey] = value;
556
+ }
557
+ }
558
+ return sortObjectDeep(document);
559
+ }
560
+
561
+ // src/openapi/from-router.ts
562
+ function fromRouter(router, options) {
563
+ const routes = introspectRouter(router, {
564
+ include: options.include,
565
+ exclude: options.exclude,
566
+ basePath: options.basePath
567
+ });
568
+ return generateOpenAPI(routes, options);
569
+ }
570
+
571
+ // src/openapi/parse.ts
572
+ import { parse as parseYaml } from "yaml";
573
+
574
+ // src/openapi/upconvert.ts
575
+ function isObject4(value) {
576
+ return typeof value === "object" && value !== null && !Array.isArray(value);
577
+ }
578
+ function upconvertNode(value) {
579
+ if (Array.isArray(value)) {
580
+ return value.map((item) => upconvertNode(item));
581
+ }
582
+ if (!isObject4(value)) {
583
+ return value;
584
+ }
585
+ const output = {};
586
+ for (const [key, nodeValue] of Object.entries(value)) {
587
+ if (key === "nullable" && nodeValue === true) {
588
+ continue;
589
+ }
590
+ output[key] = upconvertNode(nodeValue);
591
+ }
592
+ if (value.nullable === true) {
593
+ const currentType = output.type;
594
+ if (typeof currentType === "string") {
595
+ output.type = [currentType, "null"];
596
+ } else if (Array.isArray(currentType)) {
597
+ const merged = new Set(currentType);
598
+ merged.add("null");
599
+ output.type = Array.from(merged);
600
+ } else {
601
+ output.type = ["null"];
602
+ }
603
+ }
604
+ return output;
605
+ }
606
+ function upconvertFrom3_0(document) {
607
+ if (!isObject4(document)) {
608
+ throw new Error("Invalid OpenAPI document: expected object");
609
+ }
610
+ const converted = upconvertNode(document);
611
+ converted.openapi = "3.1.0";
612
+ return converted;
613
+ }
614
+
615
+ // src/openapi/parse.ts
616
+ function isObject5(value) {
617
+ return typeof value === "object" && value !== null && !Array.isArray(value);
618
+ }
619
+ function parseStringInput(input) {
620
+ const trimmed = input.trim();
621
+ if (!trimmed) {
622
+ throw new Error("Invalid OpenAPI input: empty string");
623
+ }
624
+ try {
625
+ return JSON.parse(trimmed);
626
+ } catch {
627
+ try {
628
+ return parseYaml(trimmed);
629
+ } catch (error) {
630
+ const message = error instanceof Error ? error.message : String(error);
631
+ throw new Error(`Invalid OpenAPI input: failed to parse JSON or YAML (${message})`);
632
+ }
633
+ }
634
+ }
635
+ function normalizeDocument(raw) {
636
+ if (!isObject5(raw)) {
637
+ throw new Error("Invalid OpenAPI document: expected object");
638
+ }
639
+ const version = raw.openapi;
640
+ if (typeof version !== "string") {
641
+ throw new Error("Invalid OpenAPI document: missing openapi version");
642
+ }
643
+ if (version.startsWith("3.0.")) {
644
+ return upconvertFrom3_0(raw);
645
+ }
646
+ if (version !== "3.1.0") {
647
+ throw new Error(`Unsupported OpenAPI version: ${version}`);
648
+ }
649
+ return raw;
650
+ }
651
+ function parseOpenAPI(input) {
652
+ if (typeof input === "string") {
653
+ const parsed = parseStringInput(input);
654
+ return normalizeDocument(parsed);
655
+ }
656
+ return normalizeDocument(input);
657
+ }
658
+
659
+ // src/openapi/validate.ts
660
+ import SwaggerParser from "@apidevtools/swagger-parser";
661
+ function toValidationErrors(error) {
662
+ const details = error?.details;
663
+ if (Array.isArray(details) && details.length > 0) {
664
+ return details.map((detail) => ({
665
+ path: Array.isArray(detail.path) ? detail.path.join(".") : detail.path || "openapi",
666
+ message: detail.message || "Validation error",
667
+ severity: "error"
668
+ }));
669
+ }
670
+ const message = error instanceof Error ? error.message : "Validation error";
671
+ return [
672
+ {
673
+ path: "openapi",
674
+ message,
675
+ severity: "error"
676
+ }
677
+ ];
678
+ }
679
+ async function validateOpenAPI(document) {
680
+ try {
681
+ await SwaggerParser.validate(document);
682
+ return [];
683
+ } catch (error) {
684
+ return toValidationErrors(error);
685
+ }
686
+ }
687
+
688
+ // src/diff/rules.ts
689
+ var HTTP_METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
690
+ function isRef(obj) {
691
+ return typeof obj === "object" && obj !== null && "$ref" in obj;
692
+ }
693
+ function resolveParam(p) {
694
+ if (isRef(p)) return null;
695
+ if (typeof p === "object" && p !== null && "name" in p && "in" in p) {
696
+ return p;
697
+ }
698
+ return null;
699
+ }
700
+ function schemaTypes(schema) {
701
+ if (!schema) return [];
702
+ const t = schema.type;
703
+ if (Array.isArray(t)) return t.map(String);
704
+ if (typeof t === "string") return [t];
705
+ return [];
706
+ }
707
+ function isTypeNarrowing(before, after) {
708
+ if (!before || !after) return false;
709
+ const bt = schemaTypes(before);
710
+ const at = schemaTypes(after);
711
+ if (bt.length === 0 || at.length === 0) return false;
712
+ if (at.length < bt.length) {
713
+ return at.every((t) => bt.includes(t));
714
+ }
715
+ return false;
716
+ }
717
+ function diffParameters(opPath, before, after, emit) {
718
+ const beforeParams = (before.parameters ?? []).map(resolveParam).filter((p) => p !== null);
719
+ const afterParams = (after.parameters ?? []).map(resolveParam).filter((p) => p !== null);
720
+ const beforeMap = /* @__PURE__ */ new Map();
721
+ for (const p of beforeParams) {
722
+ beforeMap.set(`${p.in}:${p.name}`, p);
723
+ }
724
+ const afterMap = /* @__PURE__ */ new Map();
725
+ for (const p of afterParams) {
726
+ afterMap.set(`${p.in}:${p.name}`, p);
727
+ }
728
+ for (const [key, afterParam] of afterMap) {
729
+ if (!beforeMap.has(key)) {
730
+ const required = afterParam.required === true;
731
+ emit({
732
+ type: "added",
733
+ breaking: required,
734
+ path: `${opPath}.parameters.${afterParam.name}`,
735
+ description: required ? `Required parameter '${afterParam.name}' (${afterParam.in}) added to ${opPath} \u2014 breaking` : `Optional parameter '${afterParam.name}' (${afterParam.in}) added to ${opPath}`
736
+ });
737
+ }
738
+ }
739
+ for (const [key, beforeParam] of beforeMap) {
740
+ if (!afterMap.has(key)) {
741
+ emit({
742
+ type: "removed",
743
+ breaking: true,
744
+ path: `${opPath}.parameters.${beforeParam.name}`,
745
+ description: `Parameter '${beforeParam.name}' (${beforeParam.in}) removed from ${opPath}`
746
+ });
747
+ }
748
+ }
749
+ for (const [key, beforeParam] of beforeMap) {
750
+ const afterParam = afterMap.get(key);
751
+ if (!afterParam) continue;
752
+ const bs = beforeParam.schema;
753
+ const as = afterParam.schema;
754
+ if (isTypeNarrowing(bs, as)) {
755
+ emit({
756
+ type: "modified",
757
+ breaking: true,
758
+ path: `${opPath}.parameters.${beforeParam.name}.schema.type`,
759
+ description: `Parameter '${beforeParam.name}' type narrowed in ${opPath}`,
760
+ before: bs?.type,
761
+ after: as?.type
762
+ });
763
+ }
764
+ if (!beforeParam.required && afterParam.required) {
765
+ emit({
766
+ type: "modified",
767
+ breaking: true,
768
+ path: `${opPath}.parameters.${beforeParam.name}.required`,
769
+ description: `Parameter '${beforeParam.name}' became required in ${opPath}`,
770
+ before: false,
771
+ after: true
772
+ });
773
+ }
774
+ }
775
+ }
776
+ function diffRequestBody(opPath, before, after, emit) {
777
+ const beforeBody = isRef(before.requestBody) ? null : before.requestBody;
778
+ const afterBody = isRef(after.requestBody) ? null : after.requestBody;
779
+ if (beforeBody && !afterBody) {
780
+ emit({
781
+ type: "removed",
782
+ breaking: true,
783
+ path: `${opPath}.requestBody`,
784
+ description: `Request body removed from ${opPath}`
785
+ });
786
+ return;
787
+ }
788
+ if (!beforeBody && afterBody) {
789
+ const required = afterBody.required === true;
790
+ emit({
791
+ type: "added",
792
+ breaking: required,
793
+ path: `${opPath}.requestBody`,
794
+ description: required ? `Required request body added to ${opPath} \u2014 breaking` : `Optional request body added to ${opPath}`
795
+ });
796
+ return;
797
+ }
798
+ if (!beforeBody || !afterBody) return;
799
+ const beforeSchema = beforeBody.content?.["application/json"]?.schema ?? null;
800
+ const afterSchema = afterBody.content?.["application/json"]?.schema ?? null;
801
+ if (!beforeSchema || !afterSchema) return;
802
+ if (isTypeNarrowing(beforeSchema, afterSchema)) {
803
+ emit({
804
+ type: "modified",
805
+ breaking: true,
806
+ path: `${opPath}.requestBody.content.application/json.schema.type`,
807
+ description: `Request body type narrowed in ${opPath}`,
808
+ before: beforeSchema.type,
809
+ after: afterSchema.type
810
+ });
811
+ }
812
+ diffObjectSchemaRequiredFields(opPath, "requestBody.content.application/json.schema", beforeSchema, afterSchema, emit);
813
+ }
814
+ function diffObjectSchemaRequiredFields(opPath, schemaPath, before, after, emit) {
815
+ const beforeRequired = new Set(Array.isArray(before.required) ? before.required : []);
816
+ const afterRequired = new Set(Array.isArray(after.required) ? after.required : []);
817
+ const afterProps = after.properties ?? {};
818
+ const beforeProps = before.properties ?? {};
819
+ for (const field of afterRequired) {
820
+ if (!beforeRequired.has(field) && !beforeProps[field]) {
821
+ emit({
822
+ type: "modified",
823
+ breaking: true,
824
+ path: `${opPath}.${schemaPath}.required`,
825
+ description: `New required field '${field}' added to request body in ${opPath}`
826
+ });
827
+ }
828
+ }
829
+ for (const prop of Object.keys(beforeProps)) {
830
+ if (!(prop in afterProps)) {
831
+ }
832
+ }
833
+ }
834
+ function diffResponses(opPath, before, after, emit) {
835
+ const beforeResponses = before.responses ?? {};
836
+ const afterResponses = after.responses ?? {};
837
+ for (const statusCode of Object.keys(beforeResponses).sort()) {
838
+ if (!(statusCode in afterResponses)) {
839
+ emit({
840
+ type: "removed",
841
+ breaking: true,
842
+ path: `${opPath}.responses.${statusCode}`,
843
+ description: `Response status ${statusCode} removed from ${opPath}`
844
+ });
845
+ }
846
+ }
847
+ for (const statusCode of Object.keys(afterResponses).sort()) {
848
+ if (!(statusCode in beforeResponses)) {
849
+ emit({
850
+ type: "added",
851
+ breaking: false,
852
+ path: `${opPath}.responses.${statusCode}`,
853
+ description: `Response status ${statusCode} added to ${opPath}`
854
+ });
855
+ }
856
+ }
857
+ for (const statusCode of Object.keys(beforeResponses).sort()) {
858
+ if (!(statusCode in afterResponses)) continue;
859
+ const beforeResp = beforeResponses[statusCode];
860
+ const afterResp = afterResponses[statusCode];
861
+ if (isRef(beforeResp) || isRef(afterResp)) continue;
862
+ const beforeSchema = beforeResp?.content?.["application/json"]?.schema ?? null;
863
+ const afterSchema = afterResp?.content?.["application/json"]?.schema ?? null;
864
+ if (!beforeSchema || !afterSchema) continue;
865
+ const schemaBasePath = `${opPath}.responses.${statusCode}.content.application/json.schema`;
866
+ if (typeof beforeSchema.properties === "object" && typeof afterSchema.properties === "object") {
867
+ const beforeProps = beforeSchema.properties ?? {};
868
+ const afterProps = afterSchema.properties ?? {};
869
+ for (const prop of Object.keys(beforeProps).sort()) {
870
+ if (!(prop in afterProps)) {
871
+ emit({
872
+ type: "removed",
873
+ breaking: true,
874
+ path: `${schemaBasePath}.properties.${prop}`,
875
+ description: `Response field '${prop}' removed from ${opPath} (status ${statusCode})`
876
+ });
877
+ }
878
+ }
879
+ for (const prop of Object.keys(afterProps).sort()) {
880
+ if (!(prop in beforeProps)) {
881
+ emit({
882
+ type: "added",
883
+ breaking: false,
884
+ path: `${schemaBasePath}.properties.${prop}`,
885
+ description: `Response field '${prop}' added to ${opPath} (status ${statusCode})`
886
+ });
887
+ }
888
+ }
889
+ }
890
+ if (isTypeNarrowing(beforeSchema, afterSchema)) {
891
+ emit({
892
+ type: "modified",
893
+ breaking: true,
894
+ path: `${schemaBasePath}.type`,
895
+ description: `Response type narrowed in ${opPath} (status ${statusCode})`,
896
+ before: beforeSchema.type,
897
+ after: afterSchema.type
898
+ });
899
+ }
900
+ }
901
+ }
902
+ function diffSecurity(opPath, before, after, emit) {
903
+ const beforeSec = before.security ?? [];
904
+ const afterSec = after.security ?? [];
905
+ const secKey = (req) => JSON.stringify(Object.keys(req).sort());
906
+ const beforeKeys = new Set(beforeSec.map(secKey));
907
+ const afterKeys = new Set(afterSec.map(secKey));
908
+ for (const key of afterKeys) {
909
+ if (!beforeKeys.has(key)) {
910
+ emit({
911
+ type: "added",
912
+ breaking: true,
913
+ path: `${opPath}.security`,
914
+ description: `Security requirement added to ${opPath} \u2014 breaking`,
915
+ before: beforeSec,
916
+ after: afterSec
917
+ });
918
+ return;
919
+ }
920
+ }
921
+ for (const key of beforeKeys) {
922
+ if (!afterKeys.has(key)) {
923
+ emit({
924
+ type: "removed",
925
+ breaking: false,
926
+ path: `${opPath}.security`,
927
+ description: `Security requirement removed from ${opPath}`,
928
+ before: beforeSec,
929
+ after: afterSec
930
+ });
931
+ return;
932
+ }
933
+ }
934
+ }
935
+ function diffMetadata(opPath, before, after, emit) {
936
+ if (before.description !== after.description && (before.description || after.description)) {
937
+ emit({
938
+ type: "modified",
939
+ breaking: false,
940
+ path: `${opPath}.description`,
941
+ description: `Description changed for ${opPath}`,
942
+ before: before.description,
943
+ after: after.description
944
+ });
945
+ }
946
+ if (before.summary !== after.summary && (before.summary || after.summary)) {
947
+ emit({
948
+ type: "modified",
949
+ breaking: false,
950
+ path: `${opPath}.summary`,
951
+ description: `Summary changed for ${opPath}`,
952
+ before: before.summary,
953
+ after: after.summary
954
+ });
955
+ }
956
+ if (before.deprecated !== after.deprecated && after.deprecated) {
957
+ emit({
958
+ type: "modified",
959
+ breaking: false,
960
+ path: `${opPath}.deprecated`,
961
+ description: `Endpoint ${opPath} marked as deprecated`,
962
+ before: false,
963
+ after: true
964
+ });
965
+ }
966
+ }
967
+
968
+ // src/diff/diff.ts
969
+ function diffOpenAPI(before, after) {
970
+ const allEntries = [];
971
+ const emit = (entry) => allEntries.push(entry);
972
+ const beforePaths = before.paths ?? {};
973
+ const afterPaths = after.paths ?? {};
974
+ const allPaths = /* @__PURE__ */ new Set([...Object.keys(beforePaths), ...Object.keys(afterPaths)]);
975
+ for (const apiPath of [...allPaths].sort()) {
976
+ const beforeItem = beforePaths[apiPath];
977
+ const afterItem = afterPaths[apiPath];
978
+ if (!beforeItem && afterItem) {
979
+ for (const method of HTTP_METHODS) {
980
+ const op = afterItem[method];
981
+ if (op) {
982
+ emit({
983
+ type: "added",
984
+ breaking: false,
985
+ path: `paths.${apiPath}.${method}`,
986
+ description: `New endpoint ${method.toUpperCase()} ${apiPath} added`
987
+ });
988
+ }
989
+ }
990
+ continue;
991
+ }
992
+ if (beforeItem && !afterItem) {
993
+ for (const method of HTTP_METHODS) {
994
+ const op = beforeItem[method];
995
+ if (op) {
996
+ emit({
997
+ type: "removed",
998
+ breaking: true,
999
+ path: `paths.${apiPath}.${method}`,
1000
+ description: `Endpoint ${method.toUpperCase()} ${apiPath} was removed`
1001
+ });
1002
+ }
1003
+ }
1004
+ continue;
1005
+ }
1006
+ if (!beforeItem || !afterItem) continue;
1007
+ diffPathItem(apiPath, beforeItem, afterItem, emit);
1008
+ }
1009
+ allEntries.sort((a, b) => a.path.localeCompare(b.path));
1010
+ const breaking = allEntries.filter((e) => e.breaking);
1011
+ const nonBreaking = allEntries.filter((e) => !e.breaking);
1012
+ const added = allEntries.filter((e) => e.type === "added").length;
1013
+ const removed = allEntries.filter((e) => e.type === "removed").length;
1014
+ const modified = allEntries.filter((e) => e.type === "modified").length;
1015
+ return {
1016
+ breaking,
1017
+ nonBreaking,
1018
+ hasBreakingChanges: breaking.length > 0,
1019
+ summary: {
1020
+ added,
1021
+ removed,
1022
+ modified,
1023
+ breaking: breaking.length,
1024
+ nonBreaking: nonBreaking.length
1025
+ }
1026
+ };
1027
+ }
1028
+ function diffPathItem(apiPath, before, after, emit) {
1029
+ for (const method of HTTP_METHODS) {
1030
+ const beforeOp = before[method];
1031
+ const afterOp = after[method];
1032
+ if (!beforeOp && afterOp) {
1033
+ emit({
1034
+ type: "added",
1035
+ breaking: false,
1036
+ path: `paths.${apiPath}.${method}`,
1037
+ description: `New endpoint ${method.toUpperCase()} ${apiPath} added`
1038
+ });
1039
+ continue;
1040
+ }
1041
+ if (beforeOp && !afterOp) {
1042
+ emit({
1043
+ type: "removed",
1044
+ breaking: true,
1045
+ path: `paths.${apiPath}.${method}`,
1046
+ description: `Endpoint ${method.toUpperCase()} ${apiPath} was removed`
1047
+ });
1048
+ continue;
1049
+ }
1050
+ if (!beforeOp || !afterOp) continue;
1051
+ const opPath = `paths.${apiPath}.${method}`;
1052
+ diffParameters(opPath, beforeOp, afterOp, emit);
1053
+ diffRequestBody(opPath, beforeOp, afterOp, emit);
1054
+ diffResponses(opPath, beforeOp, afterOp, emit);
1055
+ diffSecurity(opPath, beforeOp, afterOp, emit);
1056
+ diffMetadata(opPath, beforeOp, afterOp, emit);
1057
+ }
1058
+ }
1059
+
1060
+ // src/diff/format.ts
1061
+ function formatDiffAsJson(result, timestamp) {
1062
+ return {
1063
+ timestamp: timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
1064
+ hasBreakingChanges: result.hasBreakingChanges,
1065
+ summary: result.summary,
1066
+ breaking: result.breaking,
1067
+ nonBreaking: result.nonBreaking
1068
+ };
1069
+ }
1070
+ function formatDiffAsText(result, colors) {
1071
+ const c = {
1072
+ red: colors?.red ?? ((s2) => s2),
1073
+ green: colors?.green ?? ((s2) => s2),
1074
+ yellow: colors?.yellow ?? ((s2) => s2),
1075
+ bold: colors?.bold ?? ((s2) => s2),
1076
+ dim: colors?.dim ?? ((s2) => s2)
1077
+ };
1078
+ const lines = [];
1079
+ lines.push(c.bold("API Diff Report"));
1080
+ lines.push("\u2500".repeat(60));
1081
+ const s = result.summary;
1082
+ lines.push(`Added: ${c.green(String(s.added))}`);
1083
+ lines.push(`Removed: ${s.removed > 0 ? c.red(String(s.removed)) : String(s.removed)}`);
1084
+ lines.push(`Modified: ${String(s.modified)}`);
1085
+ lines.push(`Breaking: ${s.breaking > 0 ? c.red(String(s.breaking)) : String(s.breaking)}`);
1086
+ lines.push(`Non-breaking:${String(s.nonBreaking)}`);
1087
+ lines.push("\u2500".repeat(60));
1088
+ if (result.breaking.length > 0) {
1089
+ lines.push(c.bold(c.red("Breaking Changes:")));
1090
+ for (const entry of result.breaking) {
1091
+ const icon = entry.type === "removed" ? "\u2013" : entry.type === "added" ? "+" : "~";
1092
+ lines.push(` ${c.red(icon)} ${entry.description}`);
1093
+ lines.push(` ${c.dim(`path: ${entry.path}`)}`);
1094
+ }
1095
+ lines.push("");
1096
+ }
1097
+ if (result.nonBreaking.length > 0) {
1098
+ lines.push(c.bold("Non-Breaking Changes:"));
1099
+ for (const entry of result.nonBreaking) {
1100
+ const icon = entry.type === "removed" ? "\u2013" : entry.type === "added" ? "+" : "~";
1101
+ lines.push(` ${icon} ${entry.description}`);
1102
+ lines.push(` ${c.dim(`path: ${entry.path}`)}`);
1103
+ }
1104
+ lines.push("");
1105
+ }
1106
+ if (result.breaking.length === 0 && result.nonBreaking.length === 0) {
1107
+ lines.push(c.green("No changes detected."));
1108
+ }
1109
+ lines.push("\u2500".repeat(60));
1110
+ if (result.hasBreakingChanges) {
1111
+ lines.push(c.red(c.bold(`\u26A0 ${result.summary.breaking} breaking change(s) detected!`)));
1112
+ } else {
1113
+ lines.push(c.green("\u2713 No breaking changes."));
1114
+ }
1115
+ return lines.join("\n");
1116
+ }
1117
+
1118
+ // src/integrations/watchfn.ts
1119
+ function parseMetric(raw) {
1120
+ return {
1121
+ method: raw.method,
1122
+ path: raw.path,
1123
+ latency: {
1124
+ p50: raw.latency_p50,
1125
+ p95: raw.latency_p95,
1126
+ p99: raw.latency_p99,
1127
+ avg: raw.latency_avg
1128
+ },
1129
+ throughput: {
1130
+ rpm: raw.rpm,
1131
+ total: raw.total_requests
1132
+ },
1133
+ errors: {
1134
+ rate: raw.error_rate,
1135
+ count: raw.error_count,
1136
+ lastError: raw.last_error
1137
+ },
1138
+ availability: raw.availability,
1139
+ lastUpdated: raw.last_updated
1140
+ };
1141
+ }
1142
+ async function fetchEndpointMetrics(options) {
1143
+ const {
1144
+ baseUrl,
1145
+ timeRange,
1146
+ endpoints,
1147
+ timeoutMs = 5e3,
1148
+ apiKey
1149
+ } = options;
1150
+ const url = new URL("/api/metrics", baseUrl.replace(/\/$/, ""));
1151
+ if (timeRange) url.searchParams.set("timeRange", timeRange);
1152
+ if (endpoints?.length) {
1153
+ for (const ep of endpoints) url.searchParams.append("endpoint", ep);
1154
+ }
1155
+ const headers = {
1156
+ Accept: "application/json"
1157
+ };
1158
+ if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
1159
+ let res;
1160
+ try {
1161
+ const controller = new AbortController();
1162
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1163
+ try {
1164
+ res = await fetch(url.toString(), { headers, signal: controller.signal });
1165
+ } finally {
1166
+ clearTimeout(timer);
1167
+ }
1168
+ } catch (err) {
1169
+ const msg = err instanceof Error ? err.message : String(err);
1170
+ console.warn(`[apifn/watchfn] Could not reach watchfn at ${baseUrl}: ${msg}`);
1171
+ return [];
1172
+ }
1173
+ if (!res.ok) {
1174
+ console.warn(
1175
+ `[apifn/watchfn] watchfn returned HTTP ${res.status} from ${url.toString()}`
1176
+ );
1177
+ return [];
1178
+ }
1179
+ let body;
1180
+ try {
1181
+ body = await res.json();
1182
+ } catch {
1183
+ console.warn("[apifn/watchfn] Failed to parse watchfn response as JSON");
1184
+ return [];
1185
+ }
1186
+ const rawList = Array.isArray(body) ? body : Array.isArray(body.data) ? body.data : [];
1187
+ return rawList.map(parseMetric);
1188
+ }
1189
+ function createWatchFnClient(options) {
1190
+ return {
1191
+ fetchMetrics: (opts) => fetchEndpointMetrics({
1192
+ ...options,
1193
+ timeRange: opts?.timeRange,
1194
+ endpoints: opts?.endpoints
1195
+ })
1196
+ };
1197
+ }
1198
+ function apifnWatchMiddleware(options) {
1199
+ const {
1200
+ baseUrl,
1201
+ apiKey,
1202
+ fireAndForget = true,
1203
+ silent = false
1204
+ } = options;
1205
+ const eventUrl = `${baseUrl.replace(/\/$/, "")}/api/events`;
1206
+ const headers = {
1207
+ "Content-Type": "application/json",
1208
+ Accept: "application/json"
1209
+ };
1210
+ if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
1211
+ async function sendEvent(event) {
1212
+ try {
1213
+ const res = await fetch(eventUrl, {
1214
+ method: "POST",
1215
+ headers,
1216
+ body: JSON.stringify(event)
1217
+ });
1218
+ if (!res.ok && !silent) {
1219
+ console.warn(`[apifn/watchfn] Event POST returned HTTP ${res.status}`);
1220
+ }
1221
+ } catch (err) {
1222
+ if (!silent) {
1223
+ const msg = err instanceof Error ? err.message : String(err);
1224
+ console.warn(`[apifn/watchfn] Failed to send event to watchfn: ${msg}`);
1225
+ }
1226
+ }
1227
+ }
1228
+ return async function watchMiddleware(req, res, next) {
1229
+ const start = Date.now();
1230
+ await next();
1231
+ const durationMs = Date.now() - start;
1232
+ const r = req;
1233
+ const s = res;
1234
+ const method = r.method ?? "UNKNOWN";
1235
+ const path2 = r.path ?? (r.url ? new URL(r.url, "http://localhost").pathname : "/unknown");
1236
+ const statusCode = s.statusCode ?? 200;
1237
+ const event = {
1238
+ method,
1239
+ path: path2,
1240
+ status_code: statusCode,
1241
+ duration_ms: durationMs,
1242
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1243
+ };
1244
+ if (fireAndForget) {
1245
+ sendEvent(event).catch(() => {
1246
+ });
1247
+ } else {
1248
+ await sendEvent(event);
1249
+ }
1250
+ };
1251
+ }
1252
+
1253
+ // src/integrations/authfn.ts
1254
+ async function mintTestToken(client, options) {
1255
+ if (options.ttl > 3600) {
1256
+ throw new Error("TTL cannot exceed 3600 seconds for test tokens");
1257
+ }
1258
+ const url = new URL("/admin/keys/test", client.baseUrl.replace(/\/$/, ""));
1259
+ const headers = {
1260
+ "Content-Type": "application/json",
1261
+ Accept: "application/json"
1262
+ };
1263
+ if (client.adminKey) {
1264
+ headers["Authorization"] = `Bearer ${client.adminKey}`;
1265
+ }
1266
+ const res = await fetch(url.toString(), {
1267
+ method: "POST",
1268
+ headers,
1269
+ body: JSON.stringify({
1270
+ ttl: options.ttl,
1271
+ scopes: options.scopes ?? [],
1272
+ resourceIds: options.resourceIds ?? []
1273
+ })
1274
+ });
1275
+ if (!res.ok) {
1276
+ const text = await res.text().catch(() => "");
1277
+ throw new Error(`Failed to mint test token: HTTP ${res.status} ${text}`);
1278
+ }
1279
+ const data = await res.json();
1280
+ return data;
1281
+ }
1282
+ function createAuthfnCollectionMiddleware(baseClient, token) {
1283
+ return {
1284
+ async send(req) {
1285
+ const headers = { ...req.headers };
1286
+ const hasAuth = Object.keys(headers).some(
1287
+ (k) => k.toLowerCase() === "authorization"
1288
+ );
1289
+ if (!hasAuth) {
1290
+ headers["Authorization"] = `Bearer ${token}`;
1291
+ }
1292
+ return baseClient.send({ ...req, headers });
1293
+ }
1294
+ };
1295
+ }
1296
+
1297
+ // src/integrations/secfn.ts
1298
+ async function fetchRateLimits(rateLimiter, endpoints, context) {
1299
+ const results = [];
1300
+ for (const endpoint of endpoints) {
1301
+ try {
1302
+ const info = await rateLimiter.peek(endpoint, context);
1303
+ if (info) {
1304
+ results.push(info);
1305
+ }
1306
+ } catch (err) {
1307
+ console.warn(`[apifn/secfn] Failed to peek rate limit for ${endpoint}:`, err);
1308
+ }
1309
+ }
1310
+ return results;
1311
+ }
1312
+
1313
+ // src/integrations/logfn.ts
1314
+ function logfnReporter(logfn) {
1315
+ return {
1316
+ onStart(collection, options) {
1317
+ logfn.info("collection_run_start", {
1318
+ collection: collection.info.name,
1319
+ environment: typeof options.environment === "string" ? options.environment : options.environment.name
1320
+ });
1321
+ },
1322
+ onRequestStart(item) {
1323
+ logfn.debug("collection_request_start", {
1324
+ name: item.name,
1325
+ path: item.path
1326
+ });
1327
+ },
1328
+ onRequestComplete(result) {
1329
+ const ctx = logfn.child({
1330
+ request_name: result.name,
1331
+ method: result.method,
1332
+ url: result.url,
1333
+ duration_ms: result.duration
1334
+ });
1335
+ if (result.status === "passed") {
1336
+ ctx.info("collection_request_complete", { status: "passed" });
1337
+ } else if (result.status === "failed") {
1338
+ ctx.error("collection_request_complete", "Request failed assertions", {
1339
+ status: "failed",
1340
+ failed_assertions: result.assertions.filter((a) => !a.passed)
1341
+ });
1342
+ } else if (result.status === "error") {
1343
+ ctx.error("collection_request_complete", result.error ?? "Unknown error", {
1344
+ status: "error"
1345
+ });
1346
+ } else {
1347
+ ctx.info("collection_request_complete", { status: result.status });
1348
+ }
1349
+ },
1350
+ onComplete(report) {
1351
+ logfn.info("collection_run_complete", {
1352
+ duration_ms: report.duration,
1353
+ summary: report.summary
1354
+ });
1355
+ }
1356
+ };
1357
+ }
1358
+ function createCliLogger(options = {}) {
1359
+ const { level = "info", logfn } = options;
1360
+ if (logfn) {
1361
+ return logfn;
1362
+ }
1363
+ const levels = { debug: 0, info: 1, warn: 2, error: 3 };
1364
+ const currentLevel = levels[level] ?? 1;
1365
+ function shouldLog(l) {
1366
+ return levels[l] >= currentLevel;
1367
+ }
1368
+ return {
1369
+ info(eventType, payload) {
1370
+ if (shouldLog("info")) console.info(`[INFO] ${eventType}`, payload ?? "");
1371
+ },
1372
+ warn(eventType, payload) {
1373
+ if (shouldLog("warn")) console.warn(`[WARN] ${eventType}`, payload ?? "");
1374
+ },
1375
+ error(eventType, err, payload) {
1376
+ if (shouldLog("error")) console.error(`[ERROR] ${eventType}`, err, payload ?? "");
1377
+ },
1378
+ debug(eventType, payload) {
1379
+ if (shouldLog("debug")) console.debug(`[DEBUG] ${eventType}`, payload ?? "");
1380
+ },
1381
+ child(context) {
1382
+ return {
1383
+ ...this,
1384
+ info: (e, p) => this.info(e, { ...context, ...p }),
1385
+ warn: (e, p) => this.warn(e, { ...context, ...p }),
1386
+ error: (event, err, p) => this.error(event, err, { ...context, ...p }),
1387
+ debug: (e, p) => this.debug(e, { ...context, ...p })
1388
+ };
1389
+ }
1390
+ };
1391
+ }
1392
+
1393
+ // src/integrations/testfn.ts
1394
+ import * as path from "path";
1395
+ import * as fs from "fs";
1396
+ import { BaseAdapter } from "@testfn/core";
1397
+ var ApifnTestAdapter = class extends BaseAdapter {
1398
+ name = "apifn";
1399
+ supports(framework) {
1400
+ return framework.toLowerCase() === "apifn";
1401
+ }
1402
+ async discover(patterns) {
1403
+ let glob;
1404
+ try {
1405
+ const fg = await import("./out-ZUKS5QZF.js");
1406
+ glob = fg.default ?? fg;
1407
+ } catch {
1408
+ console.warn("[apifn/testfn] fast-glob not found, using basic fs discovery");
1409
+ }
1410
+ const { readCollection } = await import("@apifn/collections");
1411
+ const testCases = [];
1412
+ const discoveredDirs = /* @__PURE__ */ new Set();
1413
+ for (const pattern of patterns) {
1414
+ if (glob) {
1415
+ const files = await glob(
1416
+ pattern.endsWith(".yml") || pattern.endsWith(".yaml") ? pattern : `${pattern}/**/opencollection.yml`,
1417
+ { absolute: true }
1418
+ );
1419
+ for (const f of files) {
1420
+ discoveredDirs.add(path.dirname(f));
1421
+ }
1422
+ } else {
1423
+ try {
1424
+ if (fs.existsSync(pattern)) {
1425
+ const stat = fs.statSync(pattern);
1426
+ if (stat.isDirectory()) {
1427
+ if (fs.existsSync(path.join(pattern, "opencollection.yml"))) {
1428
+ discoveredDirs.add(pattern);
1429
+ }
1430
+ } else if (pattern.endsWith("opencollection.yml")) {
1431
+ discoveredDirs.add(path.dirname(pattern));
1432
+ }
1433
+ }
1434
+ } catch {
1435
+ }
1436
+ }
1437
+ }
1438
+ for (const dir of discoveredDirs) {
1439
+ try {
1440
+ const collection = await readCollection(dir);
1441
+ const walk = (items, suitePath) => {
1442
+ for (const item of items) {
1443
+ if (item.kind === "request") {
1444
+ const suiteName = suitePath.length > 0 ? suitePath.join(" > ") : collection.info.name;
1445
+ testCases.push({
1446
+ id: this.generateTestId(dir, item.name, suiteName),
1447
+ file: dir,
1448
+ name: item.name,
1449
+ suite: suiteName,
1450
+ tags: ["api"]
1451
+ });
1452
+ } else if (item.kind === "folder" && item.children) {
1453
+ walk(item.children, [...suitePath, item.name]);
1454
+ }
1455
+ }
1456
+ };
1457
+ walk(collection.items, []);
1458
+ } catch (err) {
1459
+ console.warn(`[apifn/testfn] Failed to read collection at ${dir}:`, err);
1460
+ }
1461
+ }
1462
+ return testCases;
1463
+ }
1464
+ async run(tests, options) {
1465
+ const { runCollection, readCollection } = await import("@apifn/collections");
1466
+ const results = [];
1467
+ const collectionsToRun = /* @__PURE__ */ new Map();
1468
+ for (const t of tests) {
1469
+ const list = collectionsToRun.get(t.file) || [];
1470
+ list.push(t);
1471
+ collectionsToRun.set(t.file, list);
1472
+ }
1473
+ let completedCount = 0;
1474
+ const updateProgress = (tc) => {
1475
+ completedCount++;
1476
+ options.onProgress?.({
1477
+ completed: completedCount,
1478
+ total: tests.length,
1479
+ current: tc
1480
+ });
1481
+ };
1482
+ for (const [dir, testsInCollection] of collectionsToRun.entries()) {
1483
+ try {
1484
+ const collection = await readCollection(dir);
1485
+ const report = await runCollection(collection, {
1486
+ // Default to the first environment or a dummy one if none exists
1487
+ environment: Object.keys(collection.environments)[0] ?? "default",
1488
+ parallel: options.parallel !== void 0 && options.parallel > 1,
1489
+ concurrency: typeof options.parallel === "number" ? options.parallel : void 0,
1490
+ timeout: options.timeout,
1491
+ retries: options.retries,
1492
+ overrides: options.env
1493
+ });
1494
+ for (const reqRes of report.results) {
1495
+ const matchedTests = testsInCollection.filter((t) => t.name === reqRes.name);
1496
+ for (const tc of matchedTests) {
1497
+ let status = "passed";
1498
+ let testError;
1499
+ if (reqRes.status === "failed" || reqRes.status === "error") {
1500
+ status = "failed";
1501
+ if (reqRes.status === "failed") {
1502
+ const failedAsserts = reqRes.assertions.filter((a) => !a.passed);
1503
+ const msg = failedAsserts.map((a) => `- ${a.name}`).join("\n");
1504
+ testError = {
1505
+ message: `Assertions failed:
1506
+ ${msg}`
1507
+ };
1508
+ } else if (reqRes.status === "error") {
1509
+ testError = {
1510
+ message: reqRes.error || "Unknown Request Error",
1511
+ actual: reqRes.statusCode
1512
+ };
1513
+ }
1514
+ } else if (reqRes.status === "skipped") {
1515
+ status = "skipped";
1516
+ }
1517
+ results.push({
1518
+ id: tc.id,
1519
+ status,
1520
+ duration: reqRes.duration,
1521
+ error: testError
1522
+ });
1523
+ updateProgress(tc);
1524
+ }
1525
+ }
1526
+ const runTestNames = new Set(report.results.map((r) => r.name));
1527
+ for (const tc of testsInCollection) {
1528
+ if (!runTestNames.has(tc.name)) {
1529
+ results.push({
1530
+ id: tc.id,
1531
+ status: "skipped",
1532
+ duration: 0,
1533
+ error: { message: "Test not found or excluded in collection run" }
1534
+ });
1535
+ updateProgress(tc);
1536
+ }
1537
+ }
1538
+ } catch (err) {
1539
+ for (const tc of testsInCollection) {
1540
+ results.push({
1541
+ id: tc.id,
1542
+ status: "failed",
1543
+ duration: 0,
1544
+ error: {
1545
+ message: err instanceof Error ? err.message : String(err),
1546
+ stack: err instanceof Error ? err.stack : void 0
1547
+ }
1548
+ });
1549
+ updateProgress(tc);
1550
+ }
1551
+ }
1552
+ }
1553
+ return results;
1554
+ }
1555
+ };
1556
+ export {
1557
+ ApifnTestAdapter,
1558
+ apiSchema,
1559
+ apifnWatchMiddleware,
1560
+ convertSchema,
1561
+ convertTypeBoxSchema,
1562
+ convertZodSchema,
1563
+ createAuthfnCollectionMiddleware,
1564
+ createCliLogger,
1565
+ createWatchFnClient,
1566
+ deduplicateSchemas,
1567
+ detectSchemaType,
1568
+ diffOpenAPI,
1569
+ fetchEndpointMetrics,
1570
+ fetchRateLimits,
1571
+ formatDiffAsJson,
1572
+ formatDiffAsText,
1573
+ fromRouter,
1574
+ generateOpenAPI,
1575
+ introspectRouter,
1576
+ logfnReporter,
1577
+ mintTestToken,
1578
+ parseOpenAPI,
1579
+ upconvertFrom3_0,
1580
+ validateOpenAPI
1581
+ };
1582
+ //# sourceMappingURL=index.js.map