@apifn/core 0.0.1 → 0.0.3

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/README.md ADDED
@@ -0,0 +1,255 @@
1
+ # @apifn/core
2
+
3
+ Core JavaScript/TypeScript library for ApiFn — route introspection, schema conversion, OpenAPI generation, and diff. The other ApiFn npm packages build on `@apifn/core`.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @apifn/core
9
+ ```
10
+
11
+ ## Features
12
+
13
+ - **Route Introspection** — Walk a `@superfunctions/http` router and describe every route (parameters, request bodies, responses, security)
14
+ - **Schema Conversion** — Convert Zod and TypeBox schemas to JSON Schema, with auto-detection and deduplication
15
+ - **OpenAPI Generation** — Produce an OpenAPI 3.1 document directly from a router
16
+ - **OpenAPI Parsing & Validation** — Parse YAML/JSON specs and validate them against the OpenAPI schema
17
+ - **Diff** — Compare two OpenAPI documents and classify changes as breaking / non-breaking
18
+ - **Integrations** — First-class hooks for authfn, secfn, watchfn, logfn, and testfn
19
+
20
+ ---
21
+
22
+ ## OpenAPI Generation
23
+
24
+ ### fromRouter
25
+
26
+ Generate an OpenAPI document from a `@superfunctions/http` router in one step. `FromRouterOptions` combines `OpenAPIGenerateOptions` (info, servers, security schemes) and `IntrospectOptions` (include/exclude/basePath).
27
+
28
+ ```typescript
29
+ import { fromRouter } from "@apifn/core";
30
+
31
+ const doc = fromRouter(router, {
32
+ info: {
33
+ title: "My API",
34
+ version: "1.0.0",
35
+ description: "Public API surface",
36
+ },
37
+ servers: [{ url: "https://api.example.com" }],
38
+ // IntrospectOptions
39
+ include: ["/v1"],
40
+ exclude: ["/internal"],
41
+ basePath: "/api",
42
+ });
43
+ ```
44
+
45
+ ### introspectRouter
46
+
47
+ Describe a router's routes without generating a full document. Returns `IntrospectedRoute[]`.
48
+
49
+ ```typescript
50
+ import { introspectRouter } from "@apifn/core";
51
+
52
+ const routes = introspectRouter(router, { include: ["/v1"] });
53
+ // [{ method, path, parameters, requestBody, responses, security }, ...]
54
+ ```
55
+
56
+ ### generateOpenAPI
57
+
58
+ Build the document from already-introspected routes. `fromRouter` is `introspectRouter` + `generateOpenAPI`.
59
+
60
+ ```typescript
61
+ import { introspectRouter, generateOpenAPI } from "@apifn/core";
62
+
63
+ const doc = generateOpenAPI(introspectRouter(router), {
64
+ info: { title: "My API", version: "1.0.0" },
65
+ });
66
+ ```
67
+
68
+ ---
69
+
70
+ ## Parsing & Validation
71
+
72
+ ### parseOpenAPI
73
+
74
+ Parse a YAML or JSON OpenAPI string into an `OpenAPIDocument`.
75
+
76
+ ```typescript
77
+ import { parseOpenAPI } from "@apifn/core";
78
+ import { readFile } from "node:fs/promises";
79
+
80
+ const doc = parseOpenAPI(await readFile("./openapi.yml", "utf8"));
81
+ ```
82
+
83
+ ### validateOpenAPI
84
+
85
+ Validate a document. Returns validation errors (`ValidationError[]`) for a report or gate.
86
+
87
+ ```typescript
88
+ import { validateOpenAPI } from "@apifn/core";
89
+
90
+ const errors = await validateOpenAPI(doc);
91
+ if (errors.length > 0) {
92
+ // handle invalid spec
93
+ }
94
+ ```
95
+
96
+ ### upconvertFrom3_0
97
+
98
+ Up-convert an OpenAPI 3.0 document to 3.1.
99
+
100
+ ```typescript
101
+ import { upconvertFrom3_0 } from "@apifn/core";
102
+
103
+ const doc31 = upconvertFrom3_0(doc30);
104
+ ```
105
+
106
+ ---
107
+
108
+ ## Schema Conversion
109
+
110
+ ApiFn converts framework-native schemas to JSON Schema for OpenAPI output.
111
+
112
+ | Function | Description |
113
+ |----------|-------------|
114
+ | `detectSchemaType(schema)` | Detect whether a value is a Zod, TypeBox, or plain JSON schema (`SchemaType`) |
115
+ | `convertSchema(schema)` | Convert any supported schema to JSON Schema, auto-detecting the type |
116
+ | `convertZodSchema(schema)` | Convert a Zod schema to JSON Schema |
117
+ | `convertTypeBoxSchema(schema)` | Convert a TypeBox schema to JSON Schema |
118
+ | `deduplicateSchemas(input)` | Extract shared/duplicated schemas into reusable `components` (`DeduplicateSchemasResult`) |
119
+
120
+ ```typescript
121
+ import { convertSchema, detectSchemaType } from "@apifn/core";
122
+ import { z } from "zod";
123
+
124
+ detectSchemaType(z.object({ id: z.string() })); // "zod"
125
+ const jsonSchema = convertSchema(z.object({ id: z.string() }));
126
+ ```
127
+
128
+ ### apiSchema
129
+
130
+ Attach a schema descriptor to a route so introspection can pick up request/response shapes.
131
+
132
+ ```typescript
133
+ import { apiSchema } from "@apifn/core";
134
+ ```
135
+
136
+ ---
137
+
138
+ ## Diff
139
+
140
+ ### diffOpenAPI
141
+
142
+ Compare two OpenAPI documents. Returns a `DiffResult` with a list of `DiffEntry` changes, each classified by severity.
143
+
144
+ ```typescript
145
+ import { diffOpenAPI, formatDiffAsText, formatDiffAsJson } from "@apifn/core";
146
+
147
+ const result = diffOpenAPI(beforeDoc, afterDoc);
148
+
149
+ console.log(formatDiffAsText(result)); // human-readable
150
+ const report = formatDiffAsJson(result); // DiffReportJson (machine-readable)
151
+ ```
152
+
153
+ - `formatDiffAsText(result)` — colored/plain text summary
154
+ - `formatDiffAsJson(result)` — structured `DiffReportJson` for CI artifacts
155
+
156
+ ---
157
+
158
+ ## Integrations
159
+
160
+ ### watchfn
161
+
162
+ Fetch endpoint performance metrics and stream request telemetry to a watchfn instance.
163
+
164
+ ```typescript
165
+ import {
166
+ fetchEndpointMetrics,
167
+ createWatchFnClient,
168
+ apifnWatchMiddleware,
169
+ } from "@apifn/core";
170
+
171
+ // Fetch p50/p95/p99 + error-rate metrics; degrades gracefully to [] on failure
172
+ const metrics = await fetchEndpointMetrics({
173
+ baseUrl: "https://watch.example.com",
174
+ timeRange: "PT1H", // ISO 8601 duration
175
+ });
176
+
177
+ const client = createWatchFnClient({ baseUrl: "https://watch.example.com" });
178
+
179
+ // Middleware records per-endpoint timing to watchfn
180
+ router.use(apifnWatchMiddleware({ baseUrl: "https://watch.example.com" }));
181
+ ```
182
+
183
+ ### authfn
184
+
185
+ Mint short-lived test tokens (TTL ≤ 3600s) and inject bearer auth into collection runs.
186
+
187
+ ```typescript
188
+ import { mintTestToken, createAuthfnCollectionMiddleware } from "@apifn/core";
189
+
190
+ const { token, expiresAt } = await mintTestToken(
191
+ { baseUrl: "https://auth.example.com", adminKey: process.env.AUTHFN_ADMIN_KEY },
192
+ { ttl: 900, scopes: ["read"] },
193
+ );
194
+
195
+ const client = createAuthfnCollectionMiddleware(baseHttpClient, token);
196
+ ```
197
+
198
+ ### secfn
199
+
200
+ Fetch (non-consuming) rate-limit information for endpoints.
201
+
202
+ ```typescript
203
+ import { fetchRateLimits } from "@apifn/core";
204
+
205
+ const limits = await fetchRateLimits(rateLimiter, ["GET /users"]); // RateLimitInfo[]
206
+ ```
207
+
208
+ ### logfn
209
+
210
+ Structured reporter and CLI logger.
211
+
212
+ ```typescript
213
+ import { logfnReporter, createCliLogger } from "@apifn/core";
214
+
215
+ const logger = createCliLogger({ /* CliLoggerOptions */ });
216
+ ```
217
+
218
+ ### testfn
219
+
220
+ Adapter that plugs ApiFn collection runs into testfn.
221
+
222
+ ```typescript
223
+ import { ApifnTestAdapter } from "@apifn/core";
224
+ ```
225
+
226
+ ---
227
+
228
+ ## Exports
229
+
230
+ ```typescript
231
+ // OpenAPI
232
+ export { fromRouter, introspectRouter, generateOpenAPI, parseOpenAPI, validateOpenAPI, upconvertFrom3_0 }
233
+
234
+ // Schema
235
+ export { detectSchemaType, convertSchema, convertZodSchema, convertTypeBoxSchema, deduplicateSchemas, apiSchema }
236
+
237
+ // Diff
238
+ export { diffOpenAPI, formatDiffAsText, formatDiffAsJson }
239
+
240
+ // Integrations
241
+ export { fetchEndpointMetrics, createWatchFnClient, apifnWatchMiddleware }
242
+ export { mintTestToken, createAuthfnCollectionMiddleware }
243
+ export { fetchRateLimits }
244
+ export { logfnReporter, createCliLogger }
245
+ export { ApifnTestAdapter }
246
+
247
+ // Types — HTTP, OpenAPI document objects, introspection descriptors,
248
+ // diff, validation, snippets, mock, and integration types
249
+ ```
250
+
251
+ The `@apifn/core/types` subpath exports the shared model types declared by the core package, including HTTP/OpenAPI, schema, diff, validation, snippet, mock, and integration data shapes. Types declared alongside runtime modules, such as `FromRouterOptions`, `SchemaType`, and `DiffReportJson`, are exported from the package root.
252
+
253
+ ## License
254
+
255
+ MIT
package/dist/index.cjs CHANGED
@@ -4505,11 +4505,12 @@ var require_queue = __commonJS({
4505
4505
  current.value = null;
4506
4506
  current.callback = noop;
4507
4507
  current.errorHandler = null;
4508
+ current.next = null;
4508
4509
  if (errorHandler2) {
4509
4510
  errorHandler2(new Error("abort"), val);
4510
4511
  }
4511
4512
  callback.call(context2, new Error("abort"));
4512
- current.release(current);
4513
+ cache.release(current);
4513
4514
  current = next;
4514
4515
  }
4515
4516
  self.drain = noop;
@@ -5823,7 +5824,6 @@ var KNOWN_DESCRIPTOR_KEYS = [
5823
5824
  "headers",
5824
5825
  "security"
5825
5826
  ];
5826
- var PATH_PARAM_PATTERN = /:([A-Za-z0-9_]+)/g;
5827
5827
  function isObject(value) {
5828
5828
  return typeof value === "object" && value !== null && !Array.isArray(value);
5829
5829
  }
@@ -5856,10 +5856,29 @@ function withBasePath(path2, basePath) {
5856
5856
  }
5857
5857
  function toOpenApiPath(path2) {
5858
5858
  const params = [];
5859
- const openApiPath = path2.replace(PATH_PARAM_PATTERN, (_match, param) => {
5859
+ let openApiPath = "";
5860
+ let index = 0;
5861
+ while (index < path2.length) {
5862
+ const char = path2[index];
5863
+ if (char !== ":") {
5864
+ openApiPath += char;
5865
+ index += 1;
5866
+ continue;
5867
+ }
5868
+ let end = index + 1;
5869
+ while (end < path2.length && /[A-Za-z0-9_]/.test(path2[end])) {
5870
+ end += 1;
5871
+ }
5872
+ if (end === index + 1) {
5873
+ openApiPath += char;
5874
+ index += 1;
5875
+ continue;
5876
+ }
5877
+ const param = path2.slice(index + 1, end);
5860
5878
  params.push(param);
5861
- return `{${param}}`;
5862
- });
5879
+ openApiPath += `{${param}}`;
5880
+ index = end;
5881
+ }
5863
5882
  return { path: openApiPath, pathParams: params };
5864
5883
  }
5865
5884
  function pathParamsToDescriptors(pathParams) {
@@ -6406,8 +6425,6 @@ function upconvertNode(value) {
6406
6425
  const merged = new Set(currentType);
6407
6426
  merged.add("null");
6408
6427
  output.type = Array.from(merged);
6409
- } else {
6410
- output.type = ["null"];
6411
6428
  }
6412
6429
  }
6413
6430
  return output;
@@ -6499,8 +6516,19 @@ var HTTP_METHODS = ["get", "put", "post", "delete", "options", "head", "patch",
6499
6516
  function isRef(obj) {
6500
6517
  return typeof obj === "object" && obj !== null && "$ref" in obj;
6501
6518
  }
6502
- function resolveParam(p) {
6503
- if (isRef(p)) return null;
6519
+ function emitUnresolvedRef(opPath, location, ref, emit) {
6520
+ emit({
6521
+ type: "modified",
6522
+ breaking: true,
6523
+ path: `${opPath}.${location}`,
6524
+ description: `Parameter reference '${ref}' in ${opPath} could not be resolved; diff coverage is incomplete`
6525
+ });
6526
+ }
6527
+ function resolveParam(p, opPath, location, emit) {
6528
+ if (isRef(p)) {
6529
+ emitUnresolvedRef(opPath, location, p.$ref, emit);
6530
+ return null;
6531
+ }
6504
6532
  if (typeof p === "object" && p !== null && "name" in p && "in" in p) {
6505
6533
  return p;
6506
6534
  }
@@ -6524,8 +6552,8 @@ function isTypeNarrowing(before, after) {
6524
6552
  return false;
6525
6553
  }
6526
6554
  function diffParameters(opPath, before, after, emit) {
6527
- const beforeParams = (before.parameters ?? []).map(resolveParam).filter((p) => p !== null);
6528
- const afterParams = (after.parameters ?? []).map(resolveParam).filter((p) => p !== null);
6555
+ const beforeParams = (before.parameters ?? []).map((param, index) => resolveParam(param, opPath, `parameters[${index}]`, emit)).filter((p) => p !== null);
6556
+ const afterParams = (after.parameters ?? []).map((param, index) => resolveParam(param, opPath, `parameters[${index}]`, emit)).filter((p) => p !== null);
6529
6557
  const beforeMap = /* @__PURE__ */ new Map();
6530
6558
  for (const p of beforeParams) {
6531
6559
  beforeMap.set(`${p.in}:${p.name}`, p);
@@ -6605,6 +6633,16 @@ function diffRequestBody(opPath, before, after, emit) {
6605
6633
  return;
6606
6634
  }
6607
6635
  if (!beforeBody || !afterBody) return;
6636
+ if (!beforeBody.required && afterBody.required) {
6637
+ emit({
6638
+ type: "modified",
6639
+ breaking: true,
6640
+ path: `${opPath}.requestBody.required`,
6641
+ description: `Request body became required in ${opPath}`,
6642
+ before: false,
6643
+ after: true
6644
+ });
6645
+ }
6608
6646
  const beforeSchema = beforeBody.content?.["application/json"]?.schema ?? null;
6609
6647
  const afterSchema = afterBody.content?.["application/json"]?.schema ?? null;
6610
6648
  if (!beforeSchema || !afterSchema) return;
@@ -6626,12 +6664,12 @@ function diffObjectSchemaRequiredFields(opPath, schemaPath, before, after, emit)
6626
6664
  const afterProps = after.properties ?? {};
6627
6665
  const beforeProps = before.properties ?? {};
6628
6666
  for (const field of afterRequired) {
6629
- if (!beforeRequired.has(field) && !beforeProps[field]) {
6667
+ if (!beforeRequired.has(field)) {
6630
6668
  emit({
6631
6669
  type: "modified",
6632
6670
  breaking: true,
6633
6671
  path: `${opPath}.${schemaPath}.required`,
6634
- description: `New required field '${field}' added to request body in ${opPath}`
6672
+ description: beforeProps[field] ? `Existing request body field '${field}' became required in ${opPath}` : `New required field '${field}' added to request body in ${opPath}`
6635
6673
  });
6636
6674
  }
6637
6675
  }
@@ -6729,11 +6767,12 @@ function diffSecurity(opPath, before, after, emit) {
6729
6767
  }
6730
6768
  for (const key of beforeKeys) {
6731
6769
  if (!afterKeys.has(key)) {
6770
+ const removedAlternative = afterSec.length > 0;
6732
6771
  emit({
6733
6772
  type: "removed",
6734
- breaking: false,
6773
+ breaking: removedAlternative,
6735
6774
  path: `${opPath}.security`,
6736
- description: `Security requirement removed from ${opPath}`,
6775
+ description: removedAlternative ? `Security requirement alternative removed from ${opPath} \u2014 breaking` : `Security requirement removed from ${opPath}`,
6737
6776
  before: beforeSec,
6738
6777
  after: afterSec
6739
6778
  });
@@ -7009,7 +7048,8 @@ function apifnWatchMiddleware(options) {
7009
7048
  baseUrl,
7010
7049
  apiKey,
7011
7050
  fireAndForget = true,
7012
- silent = false
7051
+ silent = false,
7052
+ timeoutMs = 2e3
7013
7053
  } = options;
7014
7054
  const eventUrl = `${baseUrl.replace(/\/$/, "")}/api/events`;
7015
7055
  const headers = {
@@ -7019,11 +7059,19 @@ function apifnWatchMiddleware(options) {
7019
7059
  if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
7020
7060
  async function sendEvent(event) {
7021
7061
  try {
7022
- const res = await fetch(eventUrl, {
7023
- method: "POST",
7024
- headers,
7025
- body: JSON.stringify(event)
7026
- });
7062
+ const controller = new AbortController();
7063
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
7064
+ let res;
7065
+ try {
7066
+ res = await fetch(eventUrl, {
7067
+ method: "POST",
7068
+ headers,
7069
+ body: JSON.stringify(event),
7070
+ signal: controller.signal
7071
+ });
7072
+ } finally {
7073
+ clearTimeout(timer);
7074
+ }
7027
7075
  if (!res.ok && !silent) {
7028
7076
  console.warn(`[apifn/watchfn] Event POST returned HTTP ${res.status}`);
7029
7077
  }