@apifn/core 0.1.0 → 0.2.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/testfn.d.cts CHANGED
@@ -1,10 +1,18 @@
1
1
  import type { BaseAdapter, TestCase, RunOptions, TestResult } from '@testfn/core' with { 'resolution-mode': 'import' };
2
2
 
3
+ interface ApifnTestAdapterOptions {
4
+ /** Execute scripts from trusted collections. Defaults to false. */
5
+ allowScripts?: boolean;
6
+ /** Explicit values for collection templates that use {{process.env.NAME}}. */
7
+ processEnv?: NodeJS.ProcessEnv;
8
+ }
3
9
  declare class ApifnTestAdapter extends BaseAdapter {
10
+ private readonly collectionOptions;
4
11
  name: string;
12
+ constructor(collectionOptions?: ApifnTestAdapterOptions);
5
13
  supports(framework: string): boolean;
6
14
  discover(patterns: string[]): Promise<TestCase[]>;
7
15
  run(tests: TestCase[], options: RunOptions): Promise<TestResult[]>;
8
16
  }
9
17
 
10
- export { ApifnTestAdapter };
18
+ export { ApifnTestAdapter, type ApifnTestAdapterOptions };
package/dist/testfn.d.ts CHANGED
@@ -1,10 +1,18 @@
1
1
  import { BaseAdapter, TestCase, RunOptions, TestResult } from '@testfn/core';
2
2
 
3
+ interface ApifnTestAdapterOptions {
4
+ /** Execute scripts from trusted collections. Defaults to false. */
5
+ allowScripts?: boolean;
6
+ /** Explicit values for collection templates that use {{process.env.NAME}}. */
7
+ processEnv?: NodeJS.ProcessEnv;
8
+ }
3
9
  declare class ApifnTestAdapter extends BaseAdapter {
10
+ private readonly collectionOptions;
4
11
  name: string;
12
+ constructor(collectionOptions?: ApifnTestAdapterOptions);
5
13
  supports(framework: string): boolean;
6
14
  discover(patterns: string[]): Promise<TestCase[]>;
7
15
  run(tests: TestCase[], options: RunOptions): Promise<TestResult[]>;
8
16
  }
9
17
 
10
- export { ApifnTestAdapter };
18
+ export { ApifnTestAdapter, type ApifnTestAdapterOptions };
package/dist/testfn.js CHANGED
@@ -4,7 +4,37 @@ import "./chunk-VUNV25KB.js";
4
4
  import * as path from "path";
5
5
  import * as fs from "fs";
6
6
  import { BaseAdapter } from "@testfn/core";
7
+ var REQUEST_ID_PREFIX = "apifn:";
8
+ function requestId(directory, requestPath) {
9
+ return REQUEST_ID_PREFIX + JSON.stringify([directory, requestPath]);
10
+ }
11
+ function isRequestPathId(id) {
12
+ if (!id.startsWith(REQUEST_ID_PREFIX)) return false;
13
+ try {
14
+ const parts = JSON.parse(id.slice(REQUEST_ID_PREFIX.length));
15
+ return Array.isArray(parts) && parts.length === 2 && parts.every((part) => typeof part === "string");
16
+ } catch {
17
+ return false;
18
+ }
19
+ }
20
+ function visitRequests(collection, visit) {
21
+ function walk(items, suitePath) {
22
+ for (const item of items) {
23
+ if (item.kind === "request") {
24
+ visit(item, suitePath.length ? suitePath.join(" > ") : collection.info.name);
25
+ } else if (item.kind === "folder" && item.children) {
26
+ walk(item.children, [...suitePath, item.name]);
27
+ }
28
+ }
29
+ }
30
+ walk(collection.items, []);
31
+ }
7
32
  var ApifnTestAdapter = class extends BaseAdapter {
33
+ constructor(collectionOptions = {}) {
34
+ super();
35
+ this.collectionOptions = collectionOptions;
36
+ }
37
+ collectionOptions;
8
38
  name = "apifn";
9
39
  supports(framework) {
10
40
  return framework.toLowerCase() === "apifn";
@@ -48,23 +78,15 @@ var ApifnTestAdapter = class extends BaseAdapter {
48
78
  for (const dir of discoveredDirs) {
49
79
  try {
50
80
  const collection = await readCollection(dir);
51
- const walk = (items, suitePath) => {
52
- for (const item of items) {
53
- if (item.kind === "request") {
54
- const suiteName = suitePath.length > 0 ? suitePath.join(" > ") : collection.info.name;
55
- testCases.push({
56
- id: this.generateTestId(dir, item.name, suiteName),
57
- file: dir,
58
- name: item.name,
59
- suite: suiteName,
60
- tags: ["api"]
61
- });
62
- } else if (item.kind === "folder" && item.children) {
63
- walk(item.children, [...suitePath, item.name]);
64
- }
65
- }
66
- };
67
- walk(collection.items, []);
81
+ visitRequests(collection, (item, suite) => {
82
+ testCases.push({
83
+ id: requestId(dir, item.path),
84
+ file: dir,
85
+ name: item.name,
86
+ suite,
87
+ tags: ["api"]
88
+ });
89
+ });
68
90
  } catch (err) {
69
91
  console.warn(`[apifn/testfn] Failed to read collection at ${dir}:`, err);
70
92
  }
@@ -72,7 +94,10 @@ var ApifnTestAdapter = class extends BaseAdapter {
72
94
  return testCases;
73
95
  }
74
96
  async run(tests, options) {
75
- const { runCollection, readCollection } = await import("@apifn/collections");
97
+ const { runCollection, readCollection, COLLECTION_RUNNER_TRUST_OPTIONS } = await import("@apifn/collections");
98
+ if (COLLECTION_RUNNER_TRUST_OPTIONS !== true) {
99
+ throw new Error("The ApiFn TestFn adapter requires @apifn/collections 0.0.5 or later.");
100
+ }
76
101
  const results = [];
77
102
  const collectionsToRun = /* @__PURE__ */ new Map();
78
103
  for (const t of tests) {
@@ -90,20 +115,55 @@ var ApifnTestAdapter = class extends BaseAdapter {
90
115
  });
91
116
  };
92
117
  for (const [dir, testsInCollection] of collectionsToRun.entries()) {
118
+ const completedCases = /* @__PURE__ */ new Set();
93
119
  try {
94
120
  const collection = await readCollection(dir);
95
- const report = await runCollection(collection, {
121
+ const requestsByName = /* @__PURE__ */ new Map();
122
+ const pathsById = /* @__PURE__ */ new Map();
123
+ const casesByPath = /* @__PURE__ */ new Map();
124
+ visitRequests(collection, (item, suite) => {
125
+ const matches = requestsByName.get(item.name) ?? [];
126
+ matches.push({ path: item.path, suite });
127
+ requestsByName.set(item.name, matches);
128
+ pathsById.set(requestId(dir, item.path), item.path);
129
+ });
130
+ for (const test of testsInCollection) {
131
+ const matches = isRequestPathId(test.id) ? [] : requestsByName.get(test.name)?.filter((request) => !test.suite || test.suite === request.suite) ?? [];
132
+ const selectedPath = pathsById.get(test.id) ?? (matches.length === 1 ? matches[0].path : void 0);
133
+ if (selectedPath !== void 0) {
134
+ const known = casesByPath.get(selectedPath) ?? [];
135
+ known.push(test);
136
+ casesByPath.set(selectedPath, known);
137
+ } else {
138
+ completedCases.add(test);
139
+ const ambiguous = matches.length > 1;
140
+ results.push({
141
+ id: test.id,
142
+ status: ambiguous ? "failed" : "skipped",
143
+ duration: 0,
144
+ error: {
145
+ message: ambiguous ? "Multiple collection requests match this test. Discover the tests again to select a request by path." : "Test not found in collection"
146
+ }
147
+ });
148
+ updateProgress(test);
149
+ }
150
+ }
151
+ const runOptions = {
96
152
  // Default to the first environment or a dummy one if none exists
97
153
  environment: Object.keys(collection.environments)[0] ?? "default",
98
154
  parallel: options.parallel !== void 0 && options.parallel > 1,
99
155
  concurrency: typeof options.parallel === "number" ? options.parallel : void 0,
100
156
  timeout: options.timeout,
101
157
  retries: options.retries,
102
- overrides: options.env
103
- });
158
+ overrides: options.env,
159
+ allowScripts: this.collectionOptions.allowScripts === true,
160
+ processEnv: this.collectionOptions.processEnv,
161
+ includePaths: [...casesByPath.keys()]
162
+ };
163
+ const report = casesByPath.size ? await runCollection(collection, runOptions) : { results: [] };
104
164
  for (const reqRes of report.results) {
105
- const matchedTests = testsInCollection.filter((t) => t.name === reqRes.name);
106
- for (const tc of matchedTests) {
165
+ for (const tc of casesByPath.get(reqRes.path) ?? []) {
166
+ completedCases.add(tc);
107
167
  let status = "passed";
108
168
  let testError;
109
169
  if (reqRes.status === "failed" || reqRes.status === "error") {
@@ -133,9 +193,8 @@ ${msg}`
133
193
  updateProgress(tc);
134
194
  }
135
195
  }
136
- const runTestNames = new Set(report.results.map((r) => r.name));
137
196
  for (const tc of testsInCollection) {
138
- if (!runTestNames.has(tc.name)) {
197
+ if (!completedCases.has(tc)) {
139
198
  results.push({
140
199
  id: tc.id,
141
200
  status: "skipped",
@@ -147,6 +206,7 @@ ${msg}`
147
206
  }
148
207
  } catch (err) {
149
208
  for (const tc of testsInCollection) {
209
+ if (completedCases.has(tc)) continue;
150
210
  results.push({
151
211
  id: tc.id,
152
212
  status: "failed",
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/integrations/testfn.ts"],"sourcesContent":["import * as path from \"path\";\nimport * as fs from \"fs\";\nimport type {\n TestCase,\n TestResult,\n RunOptions,\n TestStatus,\n TestError,\n TestProgress,\n} from \"@testfn/core\";\nimport { BaseAdapter } from \"@testfn/core\";\n\n// Duck-typing collection types to avoid circular dependency\ninterface CollectionItem { kind: string; name: string; children?: CollectionItem[];[key: string]: any; }\ninterface CollectionInfo { name: string;[key: string]: any; }\ninterface Collection { info: CollectionInfo; items: CollectionItem[]; environments: Record<string, any>;[key: string]: any; }\ninterface AssertionResult { passed: boolean; name: string;[key: string]: any; }\ninterface RequestResult { name: string; status: \"passed\" | \"failed\" | \"error\" | \"skipped\"; duration: number; assertions: AssertionResult[]; error?: string; statusCode?: number;[key: string]: any; }\ninterface RunReport { results: RequestResult[];[key: string]: any; }\n\nexport class ApifnTestAdapter extends BaseAdapter {\n name = \"apifn\";\n\n supports(framework: string): boolean {\n return framework.toLowerCase() === \"apifn\";\n }\n\n async discover(patterns: string[]): Promise<TestCase[]> {\n // Dynamic import to avoid circular dependency\n let glob: ((pattern: string | string[], options?: { absolute?: boolean }) => Promise<string[]>) | undefined;\n try {\n // @testfn/core depends on fast-glob, so reuse it when available.\n const fg = await import(\"fast-glob\");\n glob = (fg as any).default ?? (fg as any);\n } catch {\n console.warn(\"[apifn/testfn] fast-glob not found, using basic fs discovery\");\n }\n\n // @ts-ignore\n const { readCollection } = await import(\"@apifn/collections\");\n const testCases: TestCase[] = [];\n const discoveredDirs = new Set<string>();\n\n for (const pattern of patterns) {\n if (glob) {\n // Find opencollection.yml files matching the pattern\n const files: string[] = await glob(\n pattern.endsWith(\".yml\") || pattern.endsWith(\".yaml\")\n ? pattern\n : `${pattern}/**/opencollection.yml`,\n { absolute: true }\n );\n for (const f of files) {\n discoveredDirs.add(path.dirname(f));\n }\n } else {\n // Fallback if no glob (unlikely since testfn has it)\n try {\n if (fs.existsSync(pattern)) {\n const stat = fs.statSync(pattern);\n if (stat.isDirectory()) {\n if (fs.existsSync(path.join(pattern, \"opencollection.yml\"))) {\n discoveredDirs.add(pattern);\n }\n } else if (pattern.endsWith(\"opencollection.yml\")) {\n discoveredDirs.add(path.dirname(pattern));\n }\n }\n } catch {\n // ignore\n }\n }\n }\n\n for (const dir of discoveredDirs) {\n try {\n const collection: Collection = await readCollection(dir);\n\n // Walk collection to emit test cases\n const walk = (items: CollectionItem[], suitePath: string[]) => {\n for (const item of items) {\n if (item.kind === \"request\") {\n const suiteName = suitePath.length > 0 ? suitePath.join(\" > \") : collection.info.name;\n testCases.push({\n id: this.generateTestId(dir, item.name, suiteName),\n file: dir,\n name: item.name,\n suite: suiteName,\n tags: [\"api\"],\n });\n } else if (item.kind === \"folder\" && item.children) {\n walk(item.children, [...suitePath, item.name]);\n }\n }\n };\n\n walk(collection.items, []);\n } catch (err) {\n console.warn(`[apifn/testfn] Failed to read collection at ${dir}:`, err);\n }\n }\n\n return testCases;\n }\n\n async run(tests: TestCase[], options: RunOptions): Promise<TestResult[]> {\n // @ts-ignore\n const { runCollection, readCollection } = await import(\"@apifn/collections\");\n const results: TestResult[] = [];\n\n // Group tests by collection file/directory\n const collectionsToRun = new Map<string, TestCase[]>();\n for (const t of tests) {\n const list = collectionsToRun.get(t.file) || [];\n list.push(t);\n collectionsToRun.set(t.file, list);\n }\n\n let completedCount = 0;\n const updateProgress = (tc: TestCase) => {\n completedCount++;\n options.onProgress?.({\n completed: completedCount,\n total: tests.length,\n current: tc,\n });\n };\n\n for (const [dir, testsInCollection] of collectionsToRun.entries()) {\n try {\n const collection = await readCollection(dir);\n\n // We need to run the collection, but ideally only the mapped tests.\n // For simplicity, we run the collection with 'include' filter based on matched paths.\n // Since testfn focuses on names, we map names back to items.\n // Or we just run the whole collection and filter the output (if it's fast enough).\n // Best approach: Use `include` with the paths of the requests.\n const report: RunReport = await runCollection(collection, {\n // Default to the first environment or a dummy one if none exists\n environment: Object.keys(collection.environments)[0] ?? \"default\",\n parallel: options.parallel !== undefined && options.parallel > 1,\n concurrency: typeof options.parallel === \"number\" ? options.parallel : undefined,\n timeout: options.timeout,\n retries: options.retries,\n overrides: options.env,\n });\n\n // Map collection results to testfn TestResults\n for (const reqRes of report.results) {\n // Match by request name (testfn test case granularity is per request name).\n const matchedTests = testsInCollection.filter((t) => t.name === reqRes.name);\n for (const tc of matchedTests) {\n let status: TestStatus = \"passed\";\n let testError: TestError | undefined;\n\n if (reqRes.status === \"failed\" || reqRes.status === \"error\") {\n status = \"failed\";\n\n if (reqRes.status === \"failed\") {\n const failedAsserts = reqRes.assertions.filter((a: any) => !a.passed);\n const msg = failedAsserts.map((a: any) => `- ${a.name}`).join(\"\\n\");\n testError = {\n message: `Assertions failed:\\n${msg}`,\n };\n } else if (reqRes.status === \"error\") {\n testError = {\n message: reqRes.error || \"Unknown Request Error\",\n actual: reqRes.statusCode,\n };\n }\n } else if (reqRes.status === \"skipped\") {\n status = \"skipped\";\n }\n\n results.push({\n id: tc.id,\n status,\n duration: reqRes.duration,\n error: testError,\n });\n updateProgress(tc);\n }\n }\n\n // Handle skipped/omitted tests from collection that were requested\n const runTestNames = new Set(report.results.map((r: RequestResult) => r.name));\n for (const tc of testsInCollection) {\n if (!runTestNames.has(tc.name)) {\n results.push({\n id: tc.id,\n status: \"skipped\",\n duration: 0,\n error: { message: \"Test not found or excluded in collection run\" },\n });\n updateProgress(tc);\n }\n }\n } catch (err) {\n // Collection load or execution failure applies error to all tests in it\n for (const tc of testsInCollection) {\n results.push({\n id: tc.id,\n status: \"failed\",\n duration: 0,\n error: {\n message: err instanceof Error ? err.message : String(err),\n stack: err instanceof Error ? err.stack : undefined,\n },\n });\n updateProgress(tc);\n }\n }\n }\n\n return results;\n }\n}\n"],"mappings":";;;AAAA,YAAY,UAAU;AACtB,YAAY,QAAQ;AASpB,SAAS,mBAAmB;AAUrB,IAAM,mBAAN,cAA+B,YAAY;AAAA,EAC9C,OAAO;AAAA,EAEP,SAAS,WAA4B;AACjC,WAAO,UAAU,YAAY,MAAM;AAAA,EACvC;AAAA,EAEA,MAAM,SAAS,UAAyC;AAEpD,QAAI;AACJ,Q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mBAAW,MAAM,mBAAmB;AAChC,kBAAQ,KAAK;AAAA,YACT,IAAI,GAAG;AAAA,YACP,QAAQ;AAAA,YACR,UAAU;AAAA,YACV,OAAO;AAAA,cACH,SAAS,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,cACxD,OAAO,eAAe,QAAQ,IAAI,QAAQ;AAAA,YAC9C;AAAA,UACJ,CAAC;AACD,yBAAe,EAAE;AAAA,QACrB;AAAA,MACJ;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AACJ;","names":[]}
1
+ {"version":3,"sources":["../src/integrations/testfn.ts"],"sourcesContent":["import * as path from \"path\";\nimport * as fs from \"fs\";\nimport type {\n TestCase,\n TestResult,\n RunOptions,\n TestStatus,\n TestError,\n TestProgress,\n} from \"@testfn/core\";\nimport { BaseAdapter } from \"@testfn/core\";\n\n// Duck-typing collection types to avoid circular dependency\ninterface CollectionItem { kind: string; name: string; path: string; children?: CollectionItem[];[key: string]: any; }\ninterface CollectionInfo { name: string;[key: string]: any; }\ninterface Collection { info: CollectionInfo; items: CollectionItem[]; environments: Record<string, any>;[key: string]: any; }\ninterface AssertionResult { passed: boolean; name: string;[key: string]: any; }\ninterface RequestResult { path: string; status: \"passed\" | \"failed\" | \"error\" | \"skipped\"; duration: number; assertions: AssertionResult[]; error?: string; statusCode?: number;[key: string]: any; }\ninterface RunReport { results: RequestResult[];[key: string]: any; }\n\nconst REQUEST_ID_PREFIX = \"apifn:\";\n\nfunction requestId(directory: string, requestPath: string): string {\n return REQUEST_ID_PREFIX + JSON.stringify([directory, requestPath]);\n}\n\nfunction isRequestPathId(id: string): boolean {\n if (!id.startsWith(REQUEST_ID_PREFIX)) return false;\n try {\n const parts: unknown = JSON.parse(id.slice(REQUEST_ID_PREFIX.length));\n return Array.isArray(parts) && parts.length === 2 && parts.every((part) => typeof part === \"string\");\n } catch {\n return false;\n }\n}\n\nfunction visitRequests(\n collection: Collection,\n visit: (item: CollectionItem, suite: string) => void,\n): void {\n function walk(items: CollectionItem[], suitePath: string[]): void {\n for (const item of items) {\n if (item.kind === \"request\") {\n visit(item, suitePath.length ? suitePath.join(\" > \") : collection.info.name);\n } else if (item.kind === \"folder\" && item.children) {\n walk(item.children, [...suitePath, item.name]);\n }\n }\n }\n walk(collection.items, []);\n}\n\nexport interface ApifnTestAdapterOptions {\n /** Execute scripts from trusted collections. Defaults to false. */\n allowScripts?: boolean;\n /** Explicit values for collection templates that use {{process.env.NAME}}. */\n processEnv?: NodeJS.ProcessEnv;\n}\n\nexport class ApifnTestAdapter extends BaseAdapter {\n name = \"apifn\";\n\n constructor(private readonly collectionOptions: ApifnTestAdapterOptions = {}) {\n super();\n }\n\n supports(framework: string): boolean {\n return framework.toLowerCase() === \"apifn\";\n }\n\n async discover(patterns: string[]): Promise<TestCase[]> {\n // Dynamic import to avoid circular dependency\n let glob: ((pattern: string | string[], options?: { absolute?: boolean }) => Promise<string[]>) | undefined;\n try {\n // @testfn/core depends on fast-glob, so reuse it when available.\n const fg = await import(\"fast-glob\");\n glob = (fg as any).default ?? (fg as any);\n } catch {\n console.warn(\"[apifn/testfn] fast-glob not found, using basic fs discovery\");\n }\n\n // @ts-ignore\n const { readCollection } = await import(\"@apifn/collections\");\n const testCases: TestCase[] = [];\n const discoveredDirs = new Set<string>();\n\n for (const pattern of patterns) {\n if (glob) {\n // Find opencollection.yml files matching the pattern\n const files: string[] = await glob(\n pattern.endsWith(\".yml\") || pattern.endsWith(\".yaml\")\n ? pattern\n : `${pattern}/**/opencollection.yml`,\n { absolute: true }\n );\n for (const f of files) {\n discoveredDirs.add(path.dirname(f));\n }\n } else {\n // Fallback if no glob (unlikely since testfn has it)\n try {\n if (fs.existsSync(pattern)) {\n const stat = fs.statSync(pattern);\n if (stat.isDirectory()) {\n if (fs.existsSync(path.join(pattern, \"opencollection.yml\"))) {\n discoveredDirs.add(pattern);\n }\n } else if (pattern.endsWith(\"opencollection.yml\")) {\n discoveredDirs.add(path.dirname(pattern));\n }\n }\n } catch {\n // ignore\n }\n }\n }\n\n for (const dir of discoveredDirs) {\n try {\n const collection: Collection = await readCollection(dir);\n\n visitRequests(collection, (item, suite) => {\n testCases.push({\n id: requestId(dir, item.path),\n file: dir,\n name: item.name,\n suite,\n tags: [\"api\"],\n });\n });\n } catch (err) {\n console.warn(`[apifn/testfn] Failed to read collection at ${dir}:`, err);\n }\n }\n\n return testCases;\n }\n\n async run(tests: TestCase[], options: RunOptions): Promise<TestResult[]> {\n // @ts-ignore\n const { runCollection, readCollection, COLLECTION_RUNNER_TRUST_OPTIONS } = await import(\"@apifn/collections\");\n if (COLLECTION_RUNNER_TRUST_OPTIONS !== true) {\n throw new Error(\"The ApiFn TestFn adapter requires @apifn/collections 0.0.5 or later.\");\n }\n const results: TestResult[] = [];\n\n // Group tests by collection file/directory\n const collectionsToRun = new Map<string, TestCase[]>();\n for (const t of tests) {\n const list = collectionsToRun.get(t.file) || [];\n list.push(t);\n collectionsToRun.set(t.file, list);\n }\n\n let completedCount = 0;\n const updateProgress = (tc: TestCase) => {\n completedCount++;\n options.onProgress?.({\n completed: completedCount,\n total: tests.length,\n current: tc,\n });\n };\n\n for (const [dir, testsInCollection] of collectionsToRun.entries()) {\n const completedCases = new Set<TestCase>();\n try {\n const collection = await readCollection(dir);\n const requestsByName = new Map<string, Array<{ path: string; suite: string }>>();\n const pathsById = new Map<string, string>();\n const casesByPath = new Map<string, TestCase[]>();\n visitRequests(collection, (item, suite) => {\n const matches = requestsByName.get(item.name) ?? [];\n matches.push({ path: item.path, suite });\n requestsByName.set(item.name, matches);\n pathsById.set(requestId(dir, item.path), item.path);\n });\n\n for (const test of testsInCollection) {\n const matches = isRequestPathId(test.id)\n ? []\n : requestsByName.get(test.name)?.filter((request) => !test.suite || test.suite === request.suite) ?? [];\n const selectedPath = pathsById.get(test.id) ?? (matches.length === 1 ? matches[0].path : undefined);\n if (selectedPath !== undefined) {\n const known = casesByPath.get(selectedPath) ?? [];\n known.push(test);\n casesByPath.set(selectedPath, known);\n } else {\n completedCases.add(test);\n const ambiguous = matches.length > 1;\n results.push({\n id: test.id,\n status: ambiguous ? \"failed\" : \"skipped\",\n duration: 0,\n error: {\n message: ambiguous\n ? \"Multiple collection requests match this test. Discover the tests again to select a request by path.\"\n : \"Test not found in collection\",\n },\n });\n updateProgress(test);\n }\n }\n\n const runOptions = {\n // Default to the first environment or a dummy one if none exists\n environment: Object.keys(collection.environments)[0] ?? \"default\",\n parallel: options.parallel !== undefined && options.parallel > 1,\n concurrency: typeof options.parallel === \"number\" ? options.parallel : undefined,\n timeout: options.timeout,\n retries: options.retries,\n overrides: options.env,\n allowScripts: this.collectionOptions.allowScripts === true,\n processEnv: this.collectionOptions.processEnv,\n includePaths: [...casesByPath.keys()],\n };\n const report: RunReport = casesByPath.size\n ? await runCollection(collection, runOptions)\n : { results: [] };\n\n // Map collection results to testfn TestResults\n for (const reqRes of report.results) {\n for (const tc of casesByPath.get(reqRes.path) ?? []) {\n completedCases.add(tc);\n let status: TestStatus = \"passed\";\n let testError: TestError | undefined;\n\n if (reqRes.status === \"failed\" || reqRes.status === \"error\") {\n status = \"failed\";\n\n if (reqRes.status === \"failed\") {\n const failedAsserts = reqRes.assertions.filter((a: any) => !a.passed);\n const msg = failedAsserts.map((a: any) => `- ${a.name}`).join(\"\\n\");\n testError = {\n message: `Assertions failed:\\n${msg}`,\n };\n } else if (reqRes.status === \"error\") {\n testError = {\n message: reqRes.error || \"Unknown Request Error\",\n actual: reqRes.statusCode,\n };\n }\n } else if (reqRes.status === \"skipped\") {\n status = \"skipped\";\n }\n\n results.push({\n id: tc.id,\n status,\n duration: reqRes.duration,\n error: testError,\n });\n updateProgress(tc);\n }\n }\n\n // Handle skipped/omitted tests from collection that were requested\n for (const tc of testsInCollection) {\n if (!completedCases.has(tc)) {\n results.push({\n id: tc.id,\n status: \"skipped\",\n duration: 0,\n error: { message: \"Test not found or excluded in collection run\" },\n });\n updateProgress(tc);\n }\n }\n } catch (err) {\n // Collection load or execution failure applies error to all tests in it\n for (const tc of testsInCollection) {\n if (completedCases.has(tc)) continue;\n results.push({\n id: tc.id,\n status: \"failed\",\n duration: 0,\n error: {\n message: err instanceof Error ? err.message : String(err),\n stack: err instanceof Error ? err.stack : undefined,\n },\n });\n updateProgress(tc);\n }\n }\n }\n\n return results;\n }\n}\n"],"mappings":";;;AAAA,YAAY,UAAU;AACtB,YAAY,QAAQ;AASpB,SAAS,mBAAmB;AAU5B,IAAM,oBAAoB;AAE1B,SAAS,UAAU,WAAmB,aAA6B;AAC/D,SAAO,oBAAoB,KAAK,UAAU,CAAC,WAAW,WAAW,CAAC;AACtE;AAEA,SAAS,gBAAgB,IAAqB;AAC1C,MAAI,CAAC,GAAG,WAAW,iBAAiB,EAAG,QAAO;AAC9C,MAAI;AACA,UAAM,QAAiB,KAAK,MAAM,GAAG,MAAM,kBAAkB,MAAM,CAAC;AACpE,WAAO,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,KAAK,MAAM,MAAM,CAAC,SAAS,OAAO,SAAS,QAAQ;AAAA,EACvG,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAEA,SAAS,cACL,YACA,OACI;AACJ,WAAS,KAAK,OAAyB,WAA2B;AAC9D,eAAW,QAAQ,OAAO;AACtB,UAAI,KAAK,SAAS,WAAW;AACzB,cAAM,MAAM,UAAU,SAAS,UAAU,KAAK,KAAK,IAAI,WAAW,KAAK,IAAI;AAAA,MAC/E,WAAW,KAAK,SAAS,YAAY,KAAK,UAAU;AAChD,aAAK,KAAK,UAAU,CAAC,GAAG,WAAW,KAAK,IAAI,CAAC;AAAA,MACjD;AAAA,IACJ;AAAA,EACJ;AACA,OAAK,WAAW,OAAO,CAAC,CAAC;AAC7B;AASO,IAAM,mBAAN,cAA+B,YAAY;AAAA,EAG9C,YAA6B,oBAA6C,CAAC,GAAG;AAC1E,UAAM;AADmB;AAAA,EAE7B;AAAA,EAF6B;AAAA,EAF7B,OAAO;AAAA,EAMP,SAAS,WAA4B;AACjC,WAAO,UAAU,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,cACxD,OAAO,eAAe,QAAQ,IAAI,QAAQ;AAAA,YAC9C;AAAA,UACJ,CAAC;AACD,yBAAe,EAAE;AAAA,QACrB;AAAA,MACJ;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AACJ;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apifn/core",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Core library for ApiFn — route introspection, schema conversion, OpenAPI generation, and diff",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -17,6 +17,16 @@
17
17
  "import": "./dist/types.js",
18
18
  "require": "./dist/types.cjs"
19
19
  },
20
+ "./internal/openapi-reference-context": {
21
+ "import": {
22
+ "types": "./dist/openapi-reference-context.d.ts",
23
+ "default": "./dist/openapi-reference-context.js"
24
+ },
25
+ "require": {
26
+ "types": "./dist/openapi-reference-context.d.cts",
27
+ "default": "./dist/openapi-reference-context.cjs"
28
+ }
29
+ },
20
30
  "./testfn": {
21
31
  "import": {
22
32
  "types": "./dist/testfn.d.ts",
@@ -82,5 +92,5 @@
82
92
  "files": [
83
93
  "dist"
84
94
  ],
85
- "gitHead": "b8ace8ea1da0fd09dbd5ab1600cd12a81a000c6e"
95
+ "gitHead": "732b81733586a8e40ebffa8b4107537382b6002b"
86
96
  }