@apifn/core 0.0.3 → 0.1.0

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.d.cts CHANGED
@@ -2,7 +2,6 @@ import { IntrospectOptions, IntrospectedRoute, SchemaDescriptor, SchemaInput, Js
2
2
  export { AuthConfig, ComponentsObject, CorsOptions, EncodingObject, ExampleObject, ExternalDocsObject, HeaderObject, HttpMethod, LinkObject, MediaTypeObject, MockServerOptions, OAuthFlowObject, OAuthFlowsObject, OpenAPIInfoObject, OperationObject, ParameterDescriptor, ParameterObject, PathItemObject, PathsObject, ReferenceObject, RequestBodyDescriptor, RequestBodyObject, ResponseDescriptor, ResponseObject, SchemaDescriptorResponse, SchemaObject, SecurityRequirement, SecuritySchemeObject, ServerObject, SnippetOptions, SnippetTarget, TagObject } from './types.cjs';
3
3
  import { Router } from '@superfunctions/http';
4
4
  export { Middleware, Route, Router } from '@superfunctions/http';
5
- import { BaseAdapter, TestCase, RunOptions, TestResult } from '@testfn/core';
6
5
 
7
6
  declare function introspectRouter(router: Router<unknown>, options?: IntrospectOptions): IntrospectedRoute[];
8
7
 
@@ -261,11 +260,4 @@ interface CliLoggerOptions {
261
260
  */
262
261
  declare function createCliLogger(options?: CliLoggerOptions): LogFnClient;
263
262
 
264
- declare class ApifnTestAdapter extends BaseAdapter {
265
- name: string;
266
- supports(framework: string): boolean;
267
- discover(patterns: string[]): Promise<TestCase[]>;
268
- run(tests: TestCase[], options: RunOptions): Promise<TestResult[]>;
269
- }
270
-
271
- export { ApifnTestAdapter, type CliLoggerOptions, type CreateWatchFnClientOptions, type DeduplicateSchemaInput, type DeduplicateSchemasResult, DiffEntry, type DiffReportJson, DiffResult, EndpointMetrics, type FetchEndpointMetricsOptions, type FromRouterOptions, IntrospectOptions, IntrospectedRoute, JsonSchema, type MintTestTokenOptions, type MintTestTokenResponse, OpenAPIDocument, OpenAPIGenerateOptions, RateLimitInfo, SchemaDescriptor, SchemaInput, type SchemaType, ValidationError, WatchFnClient, type WatchFnMiddlewareOptions, apiSchema, apifnWatchMiddleware, convertSchema, convertTypeBoxSchema, convertZodSchema, createAuthfnCollectionMiddleware, createCliLogger, createWatchFnClient, deduplicateSchemas, detectSchemaType, diffOpenAPI, fetchEndpointMetrics, fetchRateLimits, formatDiffAsJson, formatDiffAsText, fromRouter, generateOpenAPI, introspectRouter, logfnReporter, mintTestToken, parseOpenAPI, upconvertFrom3_0, validateOpenAPI };
263
+ export { type CliLoggerOptions, type CreateWatchFnClientOptions, type DeduplicateSchemaInput, type DeduplicateSchemasResult, DiffEntry, type DiffReportJson, DiffResult, EndpointMetrics, type FetchEndpointMetricsOptions, type FromRouterOptions, IntrospectOptions, IntrospectedRoute, JsonSchema, type MintTestTokenOptions, type MintTestTokenResponse, OpenAPIDocument, OpenAPIGenerateOptions, RateLimitInfo, SchemaDescriptor, SchemaInput, type SchemaType, ValidationError, WatchFnClient, type WatchFnMiddlewareOptions, apiSchema, apifnWatchMiddleware, convertSchema, convertTypeBoxSchema, convertZodSchema, createAuthfnCollectionMiddleware, createCliLogger, createWatchFnClient, deduplicateSchemas, detectSchemaType, diffOpenAPI, fetchEndpointMetrics, fetchRateLimits, formatDiffAsJson, formatDiffAsText, fromRouter, generateOpenAPI, introspectRouter, logfnReporter, mintTestToken, parseOpenAPI, upconvertFrom3_0, validateOpenAPI };
package/dist/index.d.ts CHANGED
@@ -2,7 +2,6 @@ import { IntrospectOptions, IntrospectedRoute, SchemaDescriptor, SchemaInput, Js
2
2
  export { AuthConfig, ComponentsObject, CorsOptions, EncodingObject, ExampleObject, ExternalDocsObject, HeaderObject, HttpMethod, LinkObject, MediaTypeObject, MockServerOptions, OAuthFlowObject, OAuthFlowsObject, OpenAPIInfoObject, OperationObject, ParameterDescriptor, ParameterObject, PathItemObject, PathsObject, ReferenceObject, RequestBodyDescriptor, RequestBodyObject, ResponseDescriptor, ResponseObject, SchemaDescriptorResponse, SchemaObject, SecurityRequirement, SecuritySchemeObject, ServerObject, SnippetOptions, SnippetTarget, TagObject } from './types.js';
3
3
  import { Router } from '@superfunctions/http';
4
4
  export { Middleware, Route, Router } from '@superfunctions/http';
5
- import { BaseAdapter, TestCase, RunOptions, TestResult } from '@testfn/core';
6
5
 
7
6
  declare function introspectRouter(router: Router<unknown>, options?: IntrospectOptions): IntrospectedRoute[];
8
7
 
@@ -261,11 +260,4 @@ interface CliLoggerOptions {
261
260
  */
262
261
  declare function createCliLogger(options?: CliLoggerOptions): LogFnClient;
263
262
 
264
- declare class ApifnTestAdapter extends BaseAdapter {
265
- name: string;
266
- supports(framework: string): boolean;
267
- discover(patterns: string[]): Promise<TestCase[]>;
268
- run(tests: TestCase[], options: RunOptions): Promise<TestResult[]>;
269
- }
270
-
271
- export { ApifnTestAdapter, type CliLoggerOptions, type CreateWatchFnClientOptions, type DeduplicateSchemaInput, type DeduplicateSchemasResult, DiffEntry, type DiffReportJson, DiffResult, EndpointMetrics, type FetchEndpointMetricsOptions, type FromRouterOptions, IntrospectOptions, IntrospectedRoute, JsonSchema, type MintTestTokenOptions, type MintTestTokenResponse, OpenAPIDocument, OpenAPIGenerateOptions, RateLimitInfo, SchemaDescriptor, SchemaInput, type SchemaType, ValidationError, WatchFnClient, type WatchFnMiddlewareOptions, apiSchema, apifnWatchMiddleware, convertSchema, convertTypeBoxSchema, convertZodSchema, createAuthfnCollectionMiddleware, createCliLogger, createWatchFnClient, deduplicateSchemas, detectSchemaType, diffOpenAPI, fetchEndpointMetrics, fetchRateLimits, formatDiffAsJson, formatDiffAsText, fromRouter, generateOpenAPI, introspectRouter, logfnReporter, mintTestToken, parseOpenAPI, upconvertFrom3_0, validateOpenAPI };
263
+ export { type CliLoggerOptions, type CreateWatchFnClientOptions, type DeduplicateSchemaInput, type DeduplicateSchemasResult, DiffEntry, type DiffReportJson, DiffResult, EndpointMetrics, type FetchEndpointMetricsOptions, type FromRouterOptions, IntrospectOptions, IntrospectedRoute, JsonSchema, type MintTestTokenOptions, type MintTestTokenResponse, OpenAPIDocument, OpenAPIGenerateOptions, RateLimitInfo, SchemaDescriptor, SchemaInput, type SchemaType, ValidationError, WatchFnClient, type WatchFnMiddlewareOptions, apiSchema, apifnWatchMiddleware, convertSchema, convertTypeBoxSchema, convertZodSchema, createAuthfnCollectionMiddleware, createCliLogger, createWatchFnClient, deduplicateSchemas, detectSchemaType, diffOpenAPI, fetchEndpointMetrics, fetchRateLimits, formatDiffAsJson, formatDiffAsText, fromRouter, generateOpenAPI, introspectRouter, logfnReporter, mintTestToken, parseOpenAPI, upconvertFrom3_0, validateOpenAPI };
package/dist/index.js CHANGED
@@ -23,14 +23,14 @@ function hasSchemaDescriptor(meta) {
23
23
  }
24
24
  return KNOWN_DESCRIPTOR_KEYS.some((key) => key in meta);
25
25
  }
26
- function normalizePathSegment(path2) {
27
- if (!path2.startsWith("/")) {
28
- return `/${path2}`;
26
+ function normalizePathSegment(path) {
27
+ if (!path.startsWith("/")) {
28
+ return `/${path}`;
29
29
  }
30
- return path2;
30
+ return path;
31
31
  }
32
- function withBasePath(path2, basePath) {
33
- const routePath = normalizePathSegment(path2);
32
+ function withBasePath(path, basePath) {
33
+ const routePath = normalizePathSegment(path);
34
34
  if (!basePath) {
35
35
  return routePath;
36
36
  }
@@ -44,19 +44,19 @@ function withBasePath(path2, basePath) {
44
44
  }
45
45
  return `${normalizedBasePath}/${normalizedRoutePath}`;
46
46
  }
47
- function toOpenApiPath(path2) {
47
+ function toOpenApiPath(path) {
48
48
  const params = [];
49
49
  let openApiPath = "";
50
50
  let index = 0;
51
- while (index < path2.length) {
52
- const char = path2[index];
51
+ while (index < path.length) {
52
+ const char = path[index];
53
53
  if (char !== ":") {
54
54
  openApiPath += char;
55
55
  index += 1;
56
56
  continue;
57
57
  }
58
58
  let end = index + 1;
59
- while (end < path2.length && /[A-Za-z0-9_]/.test(path2[end])) {
59
+ while (end < path.length && /[A-Za-z0-9_]/.test(path[end])) {
60
60
  end += 1;
61
61
  }
62
62
  if (end === index + 1) {
@@ -64,7 +64,7 @@ function toOpenApiPath(path2) {
64
64
  index += 1;
65
65
  continue;
66
66
  }
67
- const param = path2.slice(index + 1, end);
67
+ const param = path.slice(index + 1, end);
68
68
  params.push(param);
69
69
  openApiPath += `{${param}}`;
70
70
  index = end;
@@ -146,17 +146,17 @@ function toResponses(descriptor) {
146
146
  }
147
147
  return responses;
148
148
  }
149
- function shouldIncludePath(path2, prefixes) {
149
+ function shouldIncludePath(path, prefixes) {
150
150
  if (!prefixes || prefixes.length === 0) {
151
151
  return true;
152
152
  }
153
- return prefixes.some((prefix) => path2.startsWith(prefix));
153
+ return prefixes.some((prefix) => path.startsWith(prefix));
154
154
  }
155
- function shouldExcludePath(path2, prefixes) {
155
+ function shouldExcludePath(path, prefixes) {
156
156
  if (!prefixes || prefixes.length === 0) {
157
157
  return false;
158
158
  }
159
- return prefixes.some((prefix) => path2.startsWith(prefix));
159
+ return prefixes.some((prefix) => path.startsWith(prefix));
160
160
  }
161
161
  function toIntrospectedRoute(route, options) {
162
162
  const fullPath = withBasePath(route.path, options.basePath);
@@ -166,7 +166,7 @@ function toIntrospectedRoute(route, options) {
166
166
  if (shouldExcludePath(fullPath, options.exclude)) {
167
167
  return null;
168
168
  }
169
- const { path: path2, pathParams } = toOpenApiPath(fullPath);
169
+ const { path, pathParams } = toOpenApiPath(fullPath);
170
170
  const rawMeta = route.meta;
171
171
  const meta = isObject(rawMeta) ? rawMeta : {};
172
172
  const descriptor = hasSchemaDescriptor(rawMeta) ? rawMeta : void 0;
@@ -178,7 +178,7 @@ function toIntrospectedRoute(route, options) {
178
178
  }
179
179
  return {
180
180
  method: route.method,
181
- path: path2,
181
+ path,
182
182
  operationId: descriptor?.operationId,
183
183
  summary: descriptor?.summary,
184
184
  description: descriptor?.description,
@@ -503,7 +503,7 @@ function toPaths(routes) {
503
503
  ([a], [b]) => a.localeCompare(b)
504
504
  );
505
505
  const paths = {};
506
- for (const [path2, pathRoutes] of sortedPaths) {
506
+ for (const [path, pathRoutes] of sortedPaths) {
507
507
  const item = {};
508
508
  const sortedRoutes = [...pathRoutes].sort(
509
509
  (a, b) => METHOD_ORDER.indexOf(methodKey(a.method)) - METHOD_ORDER.indexOf(methodKey(b.method))
@@ -512,7 +512,7 @@ function toPaths(routes) {
512
512
  const key = methodKey(route.method);
513
513
  item[key] = toOperation(route);
514
514
  }
515
- paths[path2] = item;
515
+ paths[path] = item;
516
516
  }
517
517
  return paths;
518
518
  }
@@ -605,7 +605,7 @@ function upconvertNode(value) {
605
605
  if (key === "nullable" && nodeValue === true) {
606
606
  continue;
607
607
  }
608
- output[key] = upconvertNode(nodeValue);
608
+ Object.defineProperty(output, key, { value: upconvertNode(nodeValue), enumerable: true, writable: true, configurable: true });
609
609
  }
610
610
  if (value.nullable === true) {
611
611
  const currentType = output.type;
@@ -1279,11 +1279,11 @@ function apifnWatchMiddleware(options) {
1279
1279
  const r = req;
1280
1280
  const s = res;
1281
1281
  const method = r.method ?? "UNKNOWN";
1282
- const path2 = r.path ?? (r.url ? new URL(r.url, "http://localhost").pathname : "/unknown");
1282
+ const path = r.path ?? (r.url ? new URL(r.url, "http://localhost").pathname : "/unknown");
1283
1283
  const statusCode = s.statusCode ?? 200;
1284
1284
  const event = {
1285
1285
  method,
1286
- path: path2,
1286
+ path,
1287
1287
  status_code: statusCode,
1288
1288
  duration_ms: durationMs,
1289
1289
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -1436,172 +1436,7 @@ function createCliLogger(options = {}) {
1436
1436
  }
1437
1437
  };
1438
1438
  }
1439
-
1440
- // src/integrations/testfn.ts
1441
- import * as path from "path";
1442
- import * as fs from "fs";
1443
- import { BaseAdapter } from "@testfn/core";
1444
- var ApifnTestAdapter = class extends BaseAdapter {
1445
- name = "apifn";
1446
- supports(framework) {
1447
- return framework.toLowerCase() === "apifn";
1448
- }
1449
- async discover(patterns) {
1450
- let glob;
1451
- try {
1452
- const fg = await import("./out-X7U3YPXW.js");
1453
- glob = fg.default ?? fg;
1454
- } catch {
1455
- console.warn("[apifn/testfn] fast-glob not found, using basic fs discovery");
1456
- }
1457
- const { readCollection } = await import("@apifn/collections");
1458
- const testCases = [];
1459
- const discoveredDirs = /* @__PURE__ */ new Set();
1460
- for (const pattern of patterns) {
1461
- if (glob) {
1462
- const files = await glob(
1463
- pattern.endsWith(".yml") || pattern.endsWith(".yaml") ? pattern : `${pattern}/**/opencollection.yml`,
1464
- { absolute: true }
1465
- );
1466
- for (const f of files) {
1467
- discoveredDirs.add(path.dirname(f));
1468
- }
1469
- } else {
1470
- try {
1471
- if (fs.existsSync(pattern)) {
1472
- const stat = fs.statSync(pattern);
1473
- if (stat.isDirectory()) {
1474
- if (fs.existsSync(path.join(pattern, "opencollection.yml"))) {
1475
- discoveredDirs.add(pattern);
1476
- }
1477
- } else if (pattern.endsWith("opencollection.yml")) {
1478
- discoveredDirs.add(path.dirname(pattern));
1479
- }
1480
- }
1481
- } catch {
1482
- }
1483
- }
1484
- }
1485
- for (const dir of discoveredDirs) {
1486
- try {
1487
- const collection = await readCollection(dir);
1488
- const walk = (items, suitePath) => {
1489
- for (const item of items) {
1490
- if (item.kind === "request") {
1491
- const suiteName = suitePath.length > 0 ? suitePath.join(" > ") : collection.info.name;
1492
- testCases.push({
1493
- id: this.generateTestId(dir, item.name, suiteName),
1494
- file: dir,
1495
- name: item.name,
1496
- suite: suiteName,
1497
- tags: ["api"]
1498
- });
1499
- } else if (item.kind === "folder" && item.children) {
1500
- walk(item.children, [...suitePath, item.name]);
1501
- }
1502
- }
1503
- };
1504
- walk(collection.items, []);
1505
- } catch (err) {
1506
- console.warn(`[apifn/testfn] Failed to read collection at ${dir}:`, err);
1507
- }
1508
- }
1509
- return testCases;
1510
- }
1511
- async run(tests, options) {
1512
- const { runCollection, readCollection } = await import("@apifn/collections");
1513
- const results = [];
1514
- const collectionsToRun = /* @__PURE__ */ new Map();
1515
- for (const t of tests) {
1516
- const list = collectionsToRun.get(t.file) || [];
1517
- list.push(t);
1518
- collectionsToRun.set(t.file, list);
1519
- }
1520
- let completedCount = 0;
1521
- const updateProgress = (tc) => {
1522
- completedCount++;
1523
- options.onProgress?.({
1524
- completed: completedCount,
1525
- total: tests.length,
1526
- current: tc
1527
- });
1528
- };
1529
- for (const [dir, testsInCollection] of collectionsToRun.entries()) {
1530
- try {
1531
- const collection = await readCollection(dir);
1532
- const report = await runCollection(collection, {
1533
- // Default to the first environment or a dummy one if none exists
1534
- environment: Object.keys(collection.environments)[0] ?? "default",
1535
- parallel: options.parallel !== void 0 && options.parallel > 1,
1536
- concurrency: typeof options.parallel === "number" ? options.parallel : void 0,
1537
- timeout: options.timeout,
1538
- retries: options.retries,
1539
- overrides: options.env
1540
- });
1541
- for (const reqRes of report.results) {
1542
- const matchedTests = testsInCollection.filter((t) => t.name === reqRes.name);
1543
- for (const tc of matchedTests) {
1544
- let status = "passed";
1545
- let testError;
1546
- if (reqRes.status === "failed" || reqRes.status === "error") {
1547
- status = "failed";
1548
- if (reqRes.status === "failed") {
1549
- const failedAsserts = reqRes.assertions.filter((a) => !a.passed);
1550
- const msg = failedAsserts.map((a) => `- ${a.name}`).join("\n");
1551
- testError = {
1552
- message: `Assertions failed:
1553
- ${msg}`
1554
- };
1555
- } else if (reqRes.status === "error") {
1556
- testError = {
1557
- message: reqRes.error || "Unknown Request Error",
1558
- actual: reqRes.statusCode
1559
- };
1560
- }
1561
- } else if (reqRes.status === "skipped") {
1562
- status = "skipped";
1563
- }
1564
- results.push({
1565
- id: tc.id,
1566
- status,
1567
- duration: reqRes.duration,
1568
- error: testError
1569
- });
1570
- updateProgress(tc);
1571
- }
1572
- }
1573
- const runTestNames = new Set(report.results.map((r) => r.name));
1574
- for (const tc of testsInCollection) {
1575
- if (!runTestNames.has(tc.name)) {
1576
- results.push({
1577
- id: tc.id,
1578
- status: "skipped",
1579
- duration: 0,
1580
- error: { message: "Test not found or excluded in collection run" }
1581
- });
1582
- updateProgress(tc);
1583
- }
1584
- }
1585
- } catch (err) {
1586
- for (const tc of testsInCollection) {
1587
- results.push({
1588
- id: tc.id,
1589
- status: "failed",
1590
- duration: 0,
1591
- error: {
1592
- message: err instanceof Error ? err.message : String(err),
1593
- stack: err instanceof Error ? err.stack : void 0
1594
- }
1595
- });
1596
- updateProgress(tc);
1597
- }
1598
- }
1599
- }
1600
- return results;
1601
- }
1602
- };
1603
1439
  export {
1604
- ApifnTestAdapter,
1605
1440
  apiSchema,
1606
1441
  apifnWatchMiddleware,
1607
1442
  convertSchema,