pi-lean-host 0.0.1 → 0.1.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/README.md +777 -30
- package/core/api-guide-types.ts +244 -0
- package/core/api-toggle.ts +313 -0
- package/core/guide-loader.ts +80 -0
- package/core/guide-store.ts +125 -0
- package/core/helpers-command.ts +110 -0
- package/core/helpers.ts +801 -0
- package/core/local-helpers.ts +246 -0
- package/core/parse-api-guide.ts +1218 -0
- package/core/path-template.ts +50 -0
- package/core/portal-projection.ts +69 -0
- package/core/response-spill.ts +185 -0
- package/core/ssrf-guard.ts +99 -0
- package/core/transport.ts +451 -0
- package/core/verify-ship-manifest.ts +118 -0
- package/index.ts +46 -0
- package/package.json +42 -13
- package/tools/api-fetch.ts +578 -0
- package/tools/api-guide.ts +320 -0
- package/tools/api-learn.ts +348 -0
- package/tools/api-probe.ts +500 -0
- package/tools/index.ts +7 -0
- package/tools/utils.ts +34 -0
- package/AGENTS.md +0 -22
|
@@ -0,0 +1,1218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `parseApiGuide()` — the single parser both `api-learn` (validate-before-
|
|
3
|
+
* write) and the loader (read-from-disk) route through. One parser, two call
|
|
4
|
+
* sites (design: "One parser, two call sites").
|
|
5
|
+
*
|
|
6
|
+
* Uses a real YAML parser for the nested `operations` / `auth` / `pagination`
|
|
7
|
+
* / `responseShape` blocks — portal's flat `key: value` splitter cannot handle
|
|
8
|
+
* them and is intentionally not reused (design: "Parser split").
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { parse as yamlParse } from "yaml";
|
|
12
|
+
import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
import type { Guide } from "./guide-loader.js";
|
|
15
|
+
import { extractPathTokens } from "./path-template.js";
|
|
16
|
+
import {
|
|
17
|
+
GATHER_ALL_MAX_FALLBACK,
|
|
18
|
+
KNOWN_AUTH_KINDS,
|
|
19
|
+
type ApiGuide,
|
|
20
|
+
type DateParamFormat,
|
|
21
|
+
type ParseError,
|
|
22
|
+
type ParseApiGuideResult,
|
|
23
|
+
type ParseApiGuideOptions,
|
|
24
|
+
type Operation,
|
|
25
|
+
type PaginationConfig,
|
|
26
|
+
type PaginationStyle,
|
|
27
|
+
type ResponseShape,
|
|
28
|
+
type ResponseFormat,
|
|
29
|
+
type ResponseCharset,
|
|
30
|
+
type AuthConfig,
|
|
31
|
+
type AuthKind,
|
|
32
|
+
type ExecutorVia,
|
|
33
|
+
type AcceptType,
|
|
34
|
+
type QueryParamSpec,
|
|
35
|
+
type LoadedApiGuides,
|
|
36
|
+
} from "./api-guide-types.js";
|
|
37
|
+
|
|
38
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
39
|
+
// Frontmatter split
|
|
40
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
41
|
+
|
|
42
|
+
const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/;
|
|
43
|
+
|
|
44
|
+
export const TODAY = () => new Date().toISOString().slice(0, 10);
|
|
45
|
+
|
|
46
|
+
const VALID_VIA: ReadonlySet<string> = new Set(["restGet", "paginate"]);
|
|
47
|
+
// accept is a free-form string — any media type is valid (`json`/`xml`
|
|
48
|
+
// shorthands are mapped by the helper).
|
|
49
|
+
const VALID_FORMAT: ReadonlySet<string> = new Set(["json", "xml", "text"]);
|
|
50
|
+
const DATE_PARAM_FORMATS: ReadonlySet<string> = new Set([
|
|
51
|
+
"iso8601",
|
|
52
|
+
"yyyymmdd",
|
|
53
|
+
"yyyy-mm-dd",
|
|
54
|
+
]);
|
|
55
|
+
const VALID_PAGINATION_STYLE: ReadonlySet<string> = new Set([
|
|
56
|
+
"offset-limit",
|
|
57
|
+
"nextLink",
|
|
58
|
+
"cursor",
|
|
59
|
+
"page",
|
|
60
|
+
"resumptionToken",
|
|
61
|
+
"tokenBag",
|
|
62
|
+
]);
|
|
63
|
+
|
|
64
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
65
|
+
// Error helper
|
|
66
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
67
|
+
|
|
68
|
+
function fail(
|
|
69
|
+
file: string | undefined,
|
|
70
|
+
field: string,
|
|
71
|
+
expected: string,
|
|
72
|
+
found: string,
|
|
73
|
+
extra?: { snippet?: string | undefined; fix?: string | undefined },
|
|
74
|
+
): ParseApiGuideResult {
|
|
75
|
+
const error: ParseError = {
|
|
76
|
+
field,
|
|
77
|
+
expected,
|
|
78
|
+
found,
|
|
79
|
+
...(file ? { file } : {}),
|
|
80
|
+
...(extra?.snippet ? { snippet: extra.snippet } : {}),
|
|
81
|
+
...(extra?.fix ? { fix: extra.fix } : {}),
|
|
82
|
+
};
|
|
83
|
+
return { ok: false, error };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Describe a value's type for `found` strings. */
|
|
87
|
+
function describeFound(v: unknown): string {
|
|
88
|
+
if (v === null) return "null";
|
|
89
|
+
if (v === undefined) return "undefined";
|
|
90
|
+
if (Array.isArray(v)) return "an array";
|
|
91
|
+
return typeof v;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Extract a verbatim snippet for a top-level key from the raw frontmatter. */
|
|
95
|
+
function snippetFor(frontmatter: string, key: string): string | undefined {
|
|
96
|
+
const lines = frontmatter.split("\n");
|
|
97
|
+
const start = lines.findIndex((l) => l.startsWith(`${key}:`));
|
|
98
|
+
const first = lines[start];
|
|
99
|
+
if (start === -1 || first === undefined) return undefined;
|
|
100
|
+
const out: string[] = [first];
|
|
101
|
+
for (let i = start + 1; i < lines.length; i++) {
|
|
102
|
+
const line = lines[i];
|
|
103
|
+
if (line === undefined) break;
|
|
104
|
+
// Continue while indented (nested block) or blank.
|
|
105
|
+
if (line.startsWith(" ") || line.startsWith("\t") || line === "") {
|
|
106
|
+
out.push(line);
|
|
107
|
+
} else {
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return out.join("\n");
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
115
|
+
// Field validators
|
|
116
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Required http/https URL string — returns it back on success, or a
|
|
120
|
+
* ParseApiGuideResult on failure (missing, non-string, empty, unparseable,
|
|
121
|
+
* or a non-http(s) protocol). Callers with an optional field check
|
|
122
|
+
* presence themselves before calling.
|
|
123
|
+
*/
|
|
124
|
+
function requireHttpUrl(
|
|
125
|
+
value: unknown,
|
|
126
|
+
key: string,
|
|
127
|
+
file: string | undefined,
|
|
128
|
+
fm: string,
|
|
129
|
+
opts?: { protocolFix?: string; invalidFix?: string },
|
|
130
|
+
): string | ParseApiGuideResult {
|
|
131
|
+
if (value === undefined) {
|
|
132
|
+
return fail(file, key, "a string", "missing");
|
|
133
|
+
}
|
|
134
|
+
if (typeof value !== "string" || value === "") {
|
|
135
|
+
return fail(file, key, "a string (http/https URL)", describeFound(value), {
|
|
136
|
+
snippet: snippetFor(fm, key),
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
try {
|
|
140
|
+
const u = new URL(value);
|
|
141
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") {
|
|
142
|
+
return fail(
|
|
143
|
+
file,
|
|
144
|
+
key,
|
|
145
|
+
"an http or https URL",
|
|
146
|
+
`protocol "${u.protocol}"`,
|
|
147
|
+
{ ...(opts?.protocolFix ? { fix: opts.protocolFix } : {}) },
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
} catch {
|
|
151
|
+
return fail(file, key, "a valid http/https URL", `"${value}"`, {
|
|
152
|
+
...(opts?.invalidFix ? { fix: opts.invalidFix } : {}),
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
return value;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function requireStringArray(
|
|
159
|
+
m: Record<string, unknown>,
|
|
160
|
+
key: string,
|
|
161
|
+
file: string | undefined,
|
|
162
|
+
fm: string,
|
|
163
|
+
): string[] | ParseApiGuideResult {
|
|
164
|
+
const v = m[key];
|
|
165
|
+
if (v === undefined) {
|
|
166
|
+
return fail(file, key, "a list of strings", "missing");
|
|
167
|
+
}
|
|
168
|
+
if (!Array.isArray(v) || v.length === 0) {
|
|
169
|
+
return fail(file, key, "a non-empty list of strings", describeFound(v), {
|
|
170
|
+
snippet: snippetFor(fm, key),
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
for (const item of v) {
|
|
174
|
+
if (typeof item !== "string") {
|
|
175
|
+
return fail(
|
|
176
|
+
file,
|
|
177
|
+
key,
|
|
178
|
+
"a list of strings",
|
|
179
|
+
`contains ${describeFound(item)}`,
|
|
180
|
+
{
|
|
181
|
+
snippet: snippetFor(fm, key),
|
|
182
|
+
},
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return v as string[];
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
190
|
+
// Pagination
|
|
191
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
192
|
+
|
|
193
|
+
function validatePagination(
|
|
194
|
+
raw: unknown,
|
|
195
|
+
fieldPrefix: string,
|
|
196
|
+
file: string | undefined,
|
|
197
|
+
): PaginationConfig | ParseApiGuideResult {
|
|
198
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
199
|
+
return fail(
|
|
200
|
+
file,
|
|
201
|
+
fieldPrefix,
|
|
202
|
+
"a YAML mapping (style: ..., itemsPath: ...)",
|
|
203
|
+
describeFound(raw),
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
const p = raw as Record<string, unknown>;
|
|
207
|
+
|
|
208
|
+
const styleRaw = p["style"];
|
|
209
|
+
if (typeof styleRaw !== "string" || !VALID_PAGINATION_STYLE.has(styleRaw)) {
|
|
210
|
+
return fail(
|
|
211
|
+
file,
|
|
212
|
+
`${fieldPrefix}.style`,
|
|
213
|
+
"one of: offset-limit | nextLink | cursor | page | resumptionToken | tokenBag",
|
|
214
|
+
styleRaw === undefined ? "missing" : String(styleRaw),
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
const style = styleRaw as PaginationStyle;
|
|
218
|
+
|
|
219
|
+
const itemsPath = p["itemsPath"];
|
|
220
|
+
if (typeof itemsPath !== "string" || itemsPath === "") {
|
|
221
|
+
return fail(
|
|
222
|
+
file,
|
|
223
|
+
`${fieldPrefix}.itemsPath`,
|
|
224
|
+
"a string (JSON path to the items array)",
|
|
225
|
+
itemsPath === undefined ? "missing" : describeFound(itemsPath),
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const cfg: PaginationConfig = { style, itemsPath };
|
|
230
|
+
|
|
231
|
+
// Style-specific required fields.
|
|
232
|
+
if (style === "offset-limit" || style === "page") {
|
|
233
|
+
for (const req of ["pageParam", "pageSizeParam"] as const) {
|
|
234
|
+
const v = p[req];
|
|
235
|
+
if (typeof v !== "string" || v === "") {
|
|
236
|
+
return fail(
|
|
237
|
+
file,
|
|
238
|
+
`${fieldPrefix}.${req}`,
|
|
239
|
+
"a string param name",
|
|
240
|
+
v === undefined ? "missing" : describeFound(v),
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
Object.assign(cfg, { [req]: v });
|
|
244
|
+
}
|
|
245
|
+
const ps = p["pageSize"];
|
|
246
|
+
if (ps !== undefined) {
|
|
247
|
+
if (typeof ps !== "number" || !Number.isFinite(ps) || ps <= 0) {
|
|
248
|
+
return fail(
|
|
249
|
+
file,
|
|
250
|
+
`${fieldPrefix}.pageSize`,
|
|
251
|
+
"a positive number",
|
|
252
|
+
describeFound(ps),
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
cfg.pageSize = ps;
|
|
256
|
+
}
|
|
257
|
+
} else if (style === "nextLink") {
|
|
258
|
+
const nlp = p["nextLinkPath"];
|
|
259
|
+
if (typeof nlp !== "string" || nlp === "") {
|
|
260
|
+
return fail(
|
|
261
|
+
file,
|
|
262
|
+
`${fieldPrefix}.nextLinkPath`,
|
|
263
|
+
"a string (JSON path to the next-page URL)",
|
|
264
|
+
nlp === undefined ? "missing" : describeFound(nlp),
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
cfg.nextLinkPath = nlp;
|
|
268
|
+
} else if (style === "cursor") {
|
|
269
|
+
for (const req of ["cursorParam", "cursorPath"] as const) {
|
|
270
|
+
const v = p[req];
|
|
271
|
+
if (typeof v !== "string" || v === "") {
|
|
272
|
+
return fail(
|
|
273
|
+
file,
|
|
274
|
+
`${fieldPrefix}.${req}`,
|
|
275
|
+
"a string",
|
|
276
|
+
v === undefined ? "missing" : describeFound(v),
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
Object.assign(cfg, { [req]: v });
|
|
280
|
+
}
|
|
281
|
+
} else if (style === "resumptionToken") {
|
|
282
|
+
for (const req of ["tokenParam", "tokenPath"] as const) {
|
|
283
|
+
const v = p[req];
|
|
284
|
+
if (typeof v !== "string" || v === "") {
|
|
285
|
+
return fail(
|
|
286
|
+
file,
|
|
287
|
+
`${fieldPrefix}.${req}`,
|
|
288
|
+
"a string",
|
|
289
|
+
v === undefined ? "missing" : describeFound(v),
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
Object.assign(cfg, { [req]: v });
|
|
293
|
+
}
|
|
294
|
+
} else if (style === "tokenBag") {
|
|
295
|
+
const cpRaw = p["continuationParams"];
|
|
296
|
+
if (!Array.isArray(cpRaw) || cpRaw.length === 0) {
|
|
297
|
+
return fail(
|
|
298
|
+
file,
|
|
299
|
+
`${fieldPrefix}.continuationParams`,
|
|
300
|
+
"a non-empty list of strings",
|
|
301
|
+
cpRaw === undefined ? "missing" : describeFound(cpRaw),
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
for (const item of cpRaw) {
|
|
305
|
+
if (typeof item !== "string" || item === "") {
|
|
306
|
+
return fail(
|
|
307
|
+
file,
|
|
308
|
+
`${fieldPrefix}.continuationParams`,
|
|
309
|
+
"a non-empty list of strings",
|
|
310
|
+
`contains ${describeFound(item)}`,
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
cfg.continuationParams = cpRaw as string[];
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// optional totalCountPath (any style) — JSON path to the server's
|
|
318
|
+
// reported total count, surfaced as serverTotal in paginate results.
|
|
319
|
+
const tcp = p["totalCountPath"];
|
|
320
|
+
if (tcp !== undefined) {
|
|
321
|
+
if (typeof tcp !== "string" || tcp === "") {
|
|
322
|
+
return fail(
|
|
323
|
+
file,
|
|
324
|
+
`${fieldPrefix}.totalCountPath`,
|
|
325
|
+
"a non-empty string (JSON path to the server total count)",
|
|
326
|
+
describeFound(tcp),
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
cfg.totalCountPath = tcp;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
return cfg;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
336
|
+
// Response shape
|
|
337
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
338
|
+
|
|
339
|
+
function validateResponseShape(
|
|
340
|
+
raw: unknown,
|
|
341
|
+
fieldPrefix: string,
|
|
342
|
+
file: string | undefined,
|
|
343
|
+
): ResponseShape | ParseApiGuideResult {
|
|
344
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
345
|
+
return fail(
|
|
346
|
+
file,
|
|
347
|
+
fieldPrefix,
|
|
348
|
+
"a YAML mapping (format: ..., charset: ...)",
|
|
349
|
+
describeFound(raw),
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
const r = raw as Record<string, unknown>;
|
|
353
|
+
|
|
354
|
+
const formatRaw = r["format"];
|
|
355
|
+
let format: ResponseFormat = "json";
|
|
356
|
+
if (formatRaw !== undefined) {
|
|
357
|
+
if (typeof formatRaw !== "string" || !VALID_FORMAT.has(formatRaw)) {
|
|
358
|
+
return fail(
|
|
359
|
+
file,
|
|
360
|
+
`${fieldPrefix}.format`,
|
|
361
|
+
"one of: json | xml | text",
|
|
362
|
+
String(formatRaw),
|
|
363
|
+
);
|
|
364
|
+
}
|
|
365
|
+
format = formatRaw as ResponseFormat;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const charsetRaw = r["charset"];
|
|
369
|
+
let charset: ResponseCharset = "utf-8";
|
|
370
|
+
if (charsetRaw !== undefined) {
|
|
371
|
+
if (typeof charsetRaw !== "string" || charsetRaw === "") {
|
|
372
|
+
return fail(
|
|
373
|
+
file,
|
|
374
|
+
`${fieldPrefix}.charset`,
|
|
375
|
+
"a string (utf-8 | IANA charset name)",
|
|
376
|
+
describeFound(charsetRaw),
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
charset = charsetRaw;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
return { format, charset };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
386
|
+
// Auth
|
|
387
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
388
|
+
|
|
389
|
+
function validateAuth(
|
|
390
|
+
raw: unknown,
|
|
391
|
+
file: string | undefined,
|
|
392
|
+
fm: string,
|
|
393
|
+
): AuthConfig | ParseApiGuideResult {
|
|
394
|
+
if (raw === undefined) {
|
|
395
|
+
// Default: none. No auth block = none.
|
|
396
|
+
return { kind: "none" };
|
|
397
|
+
}
|
|
398
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
399
|
+
return fail(
|
|
400
|
+
file,
|
|
401
|
+
"auth",
|
|
402
|
+
"a YAML mapping (kind: ...)",
|
|
403
|
+
describeFound(raw),
|
|
404
|
+
{
|
|
405
|
+
snippet: snippetFor(fm, "auth"),
|
|
406
|
+
},
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
const a = raw as Record<string, unknown>;
|
|
410
|
+
const kindRaw = a["kind"];
|
|
411
|
+
if (typeof kindRaw !== "string") {
|
|
412
|
+
return fail(
|
|
413
|
+
file,
|
|
414
|
+
"auth.kind",
|
|
415
|
+
"a string",
|
|
416
|
+
kindRaw === undefined ? "missing" : describeFound(kindRaw),
|
|
417
|
+
);
|
|
418
|
+
}
|
|
419
|
+
if (!KNOWN_AUTH_KINDS.has(kindRaw)) {
|
|
420
|
+
return fail(
|
|
421
|
+
file,
|
|
422
|
+
"auth.kind",
|
|
423
|
+
"one of: none | static-key | oauth2",
|
|
424
|
+
kindRaw,
|
|
425
|
+
{ fix: "Use `kind: none` (v1 realizes only none)" },
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
// Parse optional headers (per-kind extra headers, e.g. X-Api-Key for DEMO_KEY).
|
|
429
|
+
let headers: Record<string, string> | undefined;
|
|
430
|
+
const headersRaw = a["headers"];
|
|
431
|
+
if (headersRaw !== undefined) {
|
|
432
|
+
if (
|
|
433
|
+
headersRaw === null ||
|
|
434
|
+
typeof headersRaw !== "object" ||
|
|
435
|
+
Array.isArray(headersRaw) ||
|
|
436
|
+
Object.values(headersRaw).some((v) => typeof v !== "string")
|
|
437
|
+
) {
|
|
438
|
+
return fail(
|
|
439
|
+
file,
|
|
440
|
+
"auth.headers",
|
|
441
|
+
"a YAML mapping of string → string",
|
|
442
|
+
describeFound(headersRaw),
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
headers = headersRaw as Record<string, string>;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
const result: AuthConfig = { kind: kindRaw as AuthKind };
|
|
449
|
+
if (headers !== undefined) result.headers = headers;
|
|
450
|
+
return result;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
454
|
+
// Operations
|
|
455
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
456
|
+
|
|
457
|
+
function validateOperation(
|
|
458
|
+
raw: unknown,
|
|
459
|
+
index: number,
|
|
460
|
+
file: string | undefined,
|
|
461
|
+
topPagination: PaginationConfig | undefined,
|
|
462
|
+
): Operation | ParseApiGuideResult {
|
|
463
|
+
const fieldPath = (leaf: string) => `operations[${index}].${leaf}`;
|
|
464
|
+
|
|
465
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
466
|
+
return fail(
|
|
467
|
+
file,
|
|
468
|
+
`operations[${index}]`,
|
|
469
|
+
"a YAML mapping",
|
|
470
|
+
describeFound(raw),
|
|
471
|
+
);
|
|
472
|
+
}
|
|
473
|
+
const o = raw as Record<string, unknown>;
|
|
474
|
+
|
|
475
|
+
// name
|
|
476
|
+
const name = o["name"];
|
|
477
|
+
if (typeof name !== "string" || name === "") {
|
|
478
|
+
return fail(
|
|
479
|
+
file,
|
|
480
|
+
fieldPath("name"),
|
|
481
|
+
"a non-empty string",
|
|
482
|
+
name === undefined ? "missing" : describeFound(name),
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// via
|
|
487
|
+
const viaRaw = o["via"];
|
|
488
|
+
if (typeof viaRaw !== "string" || !VALID_VIA.has(viaRaw)) {
|
|
489
|
+
return fail(
|
|
490
|
+
file,
|
|
491
|
+
fieldPath("via"),
|
|
492
|
+
"one of: restGet | paginate",
|
|
493
|
+
viaRaw === undefined ? "missing" : String(viaRaw),
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
const via = viaRaw as ExecutorVia;
|
|
497
|
+
|
|
498
|
+
// path
|
|
499
|
+
const path = o["path"];
|
|
500
|
+
if (typeof path !== "string") {
|
|
501
|
+
return fail(
|
|
502
|
+
file,
|
|
503
|
+
fieldPath("path"),
|
|
504
|
+
"a string",
|
|
505
|
+
path === undefined ? "missing" : describeFound(path),
|
|
506
|
+
);
|
|
507
|
+
}
|
|
508
|
+
if (!path.startsWith("/")) {
|
|
509
|
+
return fail(
|
|
510
|
+
file,
|
|
511
|
+
fieldPath("path"),
|
|
512
|
+
"a string beginning with /",
|
|
513
|
+
`"${path}" (missing leading /)`,
|
|
514
|
+
{ fix: `Prefix the path with /: /${path}` },
|
|
515
|
+
);
|
|
516
|
+
}
|
|
517
|
+
const pathParams = extractPathTokens(path);
|
|
518
|
+
|
|
519
|
+
// accept — any media-type string, default "json"
|
|
520
|
+
const acceptRaw = o["accept"];
|
|
521
|
+
let accept: AcceptType = "json";
|
|
522
|
+
if (acceptRaw !== undefined) {
|
|
523
|
+
if (typeof acceptRaw !== "string") {
|
|
524
|
+
return fail(
|
|
525
|
+
file,
|
|
526
|
+
fieldPath("accept"),
|
|
527
|
+
"a string (media type, or json/xml shorthand)",
|
|
528
|
+
String(acceptRaw),
|
|
529
|
+
);
|
|
530
|
+
}
|
|
531
|
+
accept = acceptRaw;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// params (query params only)
|
|
535
|
+
const paramsRaw = o["params"];
|
|
536
|
+
const params: Record<string, QueryParamSpec> = {};
|
|
537
|
+
// Docs-only descriptions for path-param tokens (see api-guide-types
|
|
538
|
+
// `Operation.pathParamDocs`): declared as `params.<token>.description`
|
|
539
|
+
// in the recipe, surfaced via api-guide, never sent as a query param.
|
|
540
|
+
const pathParamDocs: Record<string, string> = {};
|
|
541
|
+
if (paramsRaw !== undefined) {
|
|
542
|
+
if (
|
|
543
|
+
paramsRaw === null ||
|
|
544
|
+
typeof paramsRaw !== "object" ||
|
|
545
|
+
Array.isArray(paramsRaw)
|
|
546
|
+
) {
|
|
547
|
+
return fail(
|
|
548
|
+
file,
|
|
549
|
+
fieldPath("params"),
|
|
550
|
+
"a YAML mapping",
|
|
551
|
+
describeFound(paramsRaw),
|
|
552
|
+
);
|
|
553
|
+
}
|
|
554
|
+
for (const [key, spec] of Object.entries(
|
|
555
|
+
paramsRaw as Record<string, unknown>,
|
|
556
|
+
)) {
|
|
557
|
+
// A path-param token may declare only a docs-only `description`
|
|
558
|
+
// (`params.<token>.description`); `required`/`default` are
|
|
559
|
+
// rejected — the value is filled from `{token}` in `path`.
|
|
560
|
+
if (pathParams.includes(key)) {
|
|
561
|
+
if (spec === null || typeof spec !== "object" || Array.isArray(spec)) {
|
|
562
|
+
return fail(
|
|
563
|
+
file,
|
|
564
|
+
fieldPath(`params.${key}`),
|
|
565
|
+
"a docs-only mapping (params.<token>.description)",
|
|
566
|
+
describeFound(spec),
|
|
567
|
+
{
|
|
568
|
+
fix: `Write params.${key}.description to document the {${key}} path token — it is filled from {${key}} in the path, not the query string`,
|
|
569
|
+
},
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
const s = spec as Record<string, unknown>;
|
|
573
|
+
const onlyDescription =
|
|
574
|
+
Object.keys(s).length === 1 && "description" in s;
|
|
575
|
+
if (!onlyDescription) {
|
|
576
|
+
return fail(
|
|
577
|
+
file,
|
|
578
|
+
fieldPath(`params.${key}`),
|
|
579
|
+
"a docs-only mapping (params.<token>.description only — path params are inferred from {token} in path)",
|
|
580
|
+
Object.keys(s).length === 0
|
|
581
|
+
? "an empty mapping"
|
|
582
|
+
: `key(s): ${Object.keys(s).join(", ")}`,
|
|
583
|
+
{
|
|
584
|
+
fix: `Keep only params.${key}.description — {${key}} is a path param, filled from {${key}} in the path, not the query string`,
|
|
585
|
+
},
|
|
586
|
+
);
|
|
587
|
+
}
|
|
588
|
+
const desc = s["description"];
|
|
589
|
+
if (typeof desc !== "string") {
|
|
590
|
+
return fail(
|
|
591
|
+
file,
|
|
592
|
+
fieldPath(`params.${key}.description`),
|
|
593
|
+
"a string",
|
|
594
|
+
describeFound(desc),
|
|
595
|
+
);
|
|
596
|
+
}
|
|
597
|
+
pathParamDocs[key] = desc;
|
|
598
|
+
continue;
|
|
599
|
+
}
|
|
600
|
+
if (spec === null || typeof spec !== "object" || Array.isArray(spec)) {
|
|
601
|
+
return fail(
|
|
602
|
+
file,
|
|
603
|
+
fieldPath(`params.${key}`),
|
|
604
|
+
"a YAML mapping (required?, default?)",
|
|
605
|
+
describeFound(spec),
|
|
606
|
+
);
|
|
607
|
+
}
|
|
608
|
+
const s = spec as Record<string, unknown>;
|
|
609
|
+
const paramSpec: QueryParamSpec = {};
|
|
610
|
+
if (s["required"] !== undefined) {
|
|
611
|
+
if (typeof s["required"] !== "boolean") {
|
|
612
|
+
return fail(
|
|
613
|
+
file,
|
|
614
|
+
fieldPath(`params.${key}.required`),
|
|
615
|
+
"a boolean",
|
|
616
|
+
describeFound(s["required"]),
|
|
617
|
+
);
|
|
618
|
+
}
|
|
619
|
+
paramSpec.required = s["required"];
|
|
620
|
+
}
|
|
621
|
+
if (s["default"] !== undefined) {
|
|
622
|
+
paramSpec.default = s["default"];
|
|
623
|
+
}
|
|
624
|
+
if (s["description"] !== undefined) {
|
|
625
|
+
if (typeof s["description"] !== "string") {
|
|
626
|
+
return fail(
|
|
627
|
+
file,
|
|
628
|
+
fieldPath(`params.${key}.description`),
|
|
629
|
+
"a string",
|
|
630
|
+
describeFound(s["description"]),
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
paramSpec.description = s["description"];
|
|
634
|
+
}
|
|
635
|
+
params[key] = paramSpec;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// dateParams — param name → date format normalization
|
|
640
|
+
const dateParamsRaw = o["dateParams"];
|
|
641
|
+
let dateParams: Record<string, DateParamFormat> | undefined;
|
|
642
|
+
if (dateParamsRaw !== undefined) {
|
|
643
|
+
if (
|
|
644
|
+
dateParamsRaw === null ||
|
|
645
|
+
typeof dateParamsRaw !== "object" ||
|
|
646
|
+
Array.isArray(dateParamsRaw)
|
|
647
|
+
) {
|
|
648
|
+
return fail(
|
|
649
|
+
file,
|
|
650
|
+
fieldPath("dateParams"),
|
|
651
|
+
"a YAML mapping of string param name → date format (iso8601 | yyyymmdd | yyyy-mm-dd)",
|
|
652
|
+
describeFound(dateParamsRaw),
|
|
653
|
+
);
|
|
654
|
+
}
|
|
655
|
+
for (const [k, fmt] of Object.entries(
|
|
656
|
+
dateParamsRaw as Record<string, unknown>,
|
|
657
|
+
)) {
|
|
658
|
+
if (typeof fmt !== "string" || !DATE_PARAM_FORMATS.has(fmt)) {
|
|
659
|
+
return fail(
|
|
660
|
+
file,
|
|
661
|
+
fieldPath(`dateParams.${k}`),
|
|
662
|
+
"one of: iso8601 | yyyymmdd | yyyy-mm-dd",
|
|
663
|
+
describeFound(fmt),
|
|
664
|
+
);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
dateParams = dateParamsRaw as Record<string, DateParamFormat>;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// helper (local user-transform) — boolean gate for this domain's helper.ts
|
|
671
|
+
const helper = o["helper"];
|
|
672
|
+
if (helper !== undefined) {
|
|
673
|
+
if (typeof helper !== "boolean") {
|
|
674
|
+
return fail(
|
|
675
|
+
file,
|
|
676
|
+
fieldPath("helper"),
|
|
677
|
+
"true or omitted",
|
|
678
|
+
describeFound(helper),
|
|
679
|
+
);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// transform (post-response local transform) — boolean gate for this
|
|
684
|
+
// domain's helper.ts named `transform` export (declared, not yet executed).
|
|
685
|
+
const transform = o["transform"];
|
|
686
|
+
if (transform !== undefined) {
|
|
687
|
+
if (typeof transform !== "boolean") {
|
|
688
|
+
return fail(
|
|
689
|
+
file,
|
|
690
|
+
fieldPath("transform"),
|
|
691
|
+
"a boolean (true or omitted)",
|
|
692
|
+
describeFound(transform),
|
|
693
|
+
);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
// passthrough — boolean gate: forward undeclared caller params onto the
|
|
698
|
+
// query string (open param surfaces like Infogami /query.json, CKAN).
|
|
699
|
+
const passthrough = o["passthrough"];
|
|
700
|
+
if (passthrough !== undefined) {
|
|
701
|
+
if (typeof passthrough !== "boolean") {
|
|
702
|
+
return fail(
|
|
703
|
+
file,
|
|
704
|
+
fieldPath("passthrough"),
|
|
705
|
+
"true or omitted",
|
|
706
|
+
describeFound(passthrough),
|
|
707
|
+
);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// parse (op-level responseShape override)
|
|
712
|
+
const parseRaw = o["parse"];
|
|
713
|
+
let parseOverride: ResponseShape | undefined;
|
|
714
|
+
if (parseRaw !== undefined) {
|
|
715
|
+
const pr = validateResponseShape(parseRaw, fieldPath("parse"), file);
|
|
716
|
+
if (!("format" in pr && typeof pr.format === "string")) {
|
|
717
|
+
return pr as ParseApiGuideResult;
|
|
718
|
+
}
|
|
719
|
+
parseOverride = pr;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// pagination (op-level override)
|
|
723
|
+
const opPaginationRaw = o["pagination"];
|
|
724
|
+
let opPagination: PaginationConfig | undefined;
|
|
725
|
+
if (opPaginationRaw !== undefined) {
|
|
726
|
+
const pr = validatePagination(
|
|
727
|
+
opPaginationRaw,
|
|
728
|
+
fieldPath("pagination"),
|
|
729
|
+
file,
|
|
730
|
+
);
|
|
731
|
+
if (!("style" in pr && typeof pr.style === "string")) {
|
|
732
|
+
return pr as ParseApiGuideResult;
|
|
733
|
+
}
|
|
734
|
+
opPagination = pr;
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
// via: paginate requires pagination (top-level or op-level).
|
|
738
|
+
const effectivePagination = opPagination ?? topPagination;
|
|
739
|
+
if (via === "paginate" && effectivePagination === undefined) {
|
|
740
|
+
return fail(
|
|
741
|
+
file,
|
|
742
|
+
fieldPath("pagination"),
|
|
743
|
+
"a pagination block (required when via: paginate)",
|
|
744
|
+
"missing — no top-level pagination and no op-level override",
|
|
745
|
+
{
|
|
746
|
+
fix: "Add a top-level pagination: block or an op-level pagination: override",
|
|
747
|
+
},
|
|
748
|
+
);
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
// gatherAllMax (op-level override)
|
|
752
|
+
const opGatherAllMaxRaw = o["gatherAllMax"];
|
|
753
|
+
let opGatherAllMax: number | undefined;
|
|
754
|
+
if (opGatherAllMaxRaw !== undefined) {
|
|
755
|
+
if (
|
|
756
|
+
typeof opGatherAllMaxRaw !== "number" ||
|
|
757
|
+
!Number.isFinite(opGatherAllMaxRaw) ||
|
|
758
|
+
opGatherAllMaxRaw <= 0
|
|
759
|
+
) {
|
|
760
|
+
return fail(
|
|
761
|
+
file,
|
|
762
|
+
fieldPath("gatherAllMax"),
|
|
763
|
+
"a positive number",
|
|
764
|
+
describeFound(opGatherAllMaxRaw),
|
|
765
|
+
);
|
|
766
|
+
}
|
|
767
|
+
opGatherAllMax = opGatherAllMaxRaw;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
const operation: Operation = {
|
|
771
|
+
name,
|
|
772
|
+
via,
|
|
773
|
+
path,
|
|
774
|
+
accept,
|
|
775
|
+
params,
|
|
776
|
+
pathParams,
|
|
777
|
+
...(Object.keys(pathParamDocs).length > 0 ? { pathParamDocs } : {}),
|
|
778
|
+
...(helper !== undefined ? { helper } : {}),
|
|
779
|
+
...(transform !== undefined ? { transform } : {}),
|
|
780
|
+
...(passthrough !== undefined ? { passthrough } : {}),
|
|
781
|
+
...(dateParams !== undefined ? { dateParams } : {}),
|
|
782
|
+
...(parseOverride ? { parse: parseOverride } : {}),
|
|
783
|
+
...(opPagination ? { pagination: opPagination } : {}),
|
|
784
|
+
...(opGatherAllMax !== undefined ? { gatherAllMax: opGatherAllMax } : {}),
|
|
785
|
+
};
|
|
786
|
+
return operation;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
790
|
+
// parseApiGuide — one parser, two call sites
|
|
791
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
792
|
+
|
|
793
|
+
export function parseApiGuide(
|
|
794
|
+
raw: string,
|
|
795
|
+
opts?: ParseApiGuideOptions,
|
|
796
|
+
): ParseApiGuideResult {
|
|
797
|
+
const file = opts?.file;
|
|
798
|
+
const filename = opts?.filename ?? "api-guide";
|
|
799
|
+
|
|
800
|
+
const match = raw.match(FRONTMATTER_RE);
|
|
801
|
+
if (!match) {
|
|
802
|
+
return fail(
|
|
803
|
+
file,
|
|
804
|
+
"frontmatter",
|
|
805
|
+
"YAML frontmatter delimited by ---",
|
|
806
|
+
"no frontmatter found",
|
|
807
|
+
{
|
|
808
|
+
fix: "Begin the file with:\n---\n<yaml>\n---\n<prose>",
|
|
809
|
+
},
|
|
810
|
+
);
|
|
811
|
+
}
|
|
812
|
+
const fm = match[1] ?? "";
|
|
813
|
+
const content = (match[2] ?? "").trim();
|
|
814
|
+
if (fm === "") {
|
|
815
|
+
return fail(
|
|
816
|
+
file,
|
|
817
|
+
"frontmatter",
|
|
818
|
+
"a non-empty YAML mapping",
|
|
819
|
+
"empty frontmatter",
|
|
820
|
+
);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
let meta: unknown;
|
|
824
|
+
try {
|
|
825
|
+
meta = yamlParse(fm);
|
|
826
|
+
} catch (e) {
|
|
827
|
+
return fail(
|
|
828
|
+
file,
|
|
829
|
+
"frontmatter",
|
|
830
|
+
"valid YAML",
|
|
831
|
+
e instanceof Error ? e.message : String(e),
|
|
832
|
+
{
|
|
833
|
+
snippet: fm,
|
|
834
|
+
},
|
|
835
|
+
);
|
|
836
|
+
}
|
|
837
|
+
if (meta === null || typeof meta !== "object" || Array.isArray(meta)) {
|
|
838
|
+
return fail(
|
|
839
|
+
file,
|
|
840
|
+
"frontmatter",
|
|
841
|
+
"a YAML mapping (key: value)",
|
|
842
|
+
describeFound(meta),
|
|
843
|
+
{
|
|
844
|
+
snippet: fm,
|
|
845
|
+
},
|
|
846
|
+
);
|
|
847
|
+
}
|
|
848
|
+
const m = meta as Record<string, unknown>;
|
|
849
|
+
|
|
850
|
+
// ── projection slice ──────────────────────────────────────────
|
|
851
|
+
const kindRaw = m["kind"];
|
|
852
|
+
if (kindRaw !== undefined && kindRaw !== "api") {
|
|
853
|
+
return fail(
|
|
854
|
+
file,
|
|
855
|
+
"kind",
|
|
856
|
+
'"api" (or omitted — api-guides are always API kind)',
|
|
857
|
+
kindRaw === "web"
|
|
858
|
+
? '"web" — move this file to a web-guides dir instead'
|
|
859
|
+
: String(kindRaw),
|
|
860
|
+
);
|
|
861
|
+
}
|
|
862
|
+
const kind = "api";
|
|
863
|
+
|
|
864
|
+
const domainsRes = requireStringArray(m, "domains", file, fm);
|
|
865
|
+
if (!Array.isArray(domainsRes)) return domainsRes;
|
|
866
|
+
const domains = domainsRes;
|
|
867
|
+
|
|
868
|
+
const icon = typeof m["icon"] === "string" ? (m["icon"] as string) : "📖";
|
|
869
|
+
const shortName =
|
|
870
|
+
typeof m["shortName"] === "string" ? (m["shortName"] as string) : filename;
|
|
871
|
+
const updated =
|
|
872
|
+
typeof m["updated"] === "string" ? (m["updated"] as string) : TODAY();
|
|
873
|
+
|
|
874
|
+
// ── recipe slice ──────────────────────────────────────────────
|
|
875
|
+
const apiHostRes = requireHttpUrl(m["apiHost"], "apiHost", file, fm, {
|
|
876
|
+
protocolFix: "Use https:// as the scheme",
|
|
877
|
+
invalidFix: "Include the scheme, e.g. https://apidatos.boe.es/v1",
|
|
878
|
+
});
|
|
879
|
+
if (typeof apiHostRes !== "string") return apiHostRes;
|
|
880
|
+
const apiHost = apiHostRes;
|
|
881
|
+
|
|
882
|
+
const verified =
|
|
883
|
+
typeof m["verified"] === "string" ? (m["verified"] as string) : TODAY();
|
|
884
|
+
|
|
885
|
+
// docs — optional canonical API documentation URL (http/https);
|
|
886
|
+
// omitted when the key is absent.
|
|
887
|
+
let docs: string | undefined;
|
|
888
|
+
const docsRaw = m["docs"];
|
|
889
|
+
if (docsRaw !== undefined) {
|
|
890
|
+
const docsRes = requireHttpUrl(docsRaw, "docs", file, fm);
|
|
891
|
+
if (typeof docsRes !== "string") return docsRes;
|
|
892
|
+
docs = docsRes;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
// organization — optional org identity for catalog grouping +
|
|
896
|
+
// disambiguation. Routing-independent; free-form non-empty string.
|
|
897
|
+
// ponytail: no controlled vocab / uniqueness check — registrable-domain
|
|
898
|
+
// convention bounds collision to cosmetic (routing is on domains:).
|
|
899
|
+
let organization: string | undefined;
|
|
900
|
+
const organizationRaw = m["organization"];
|
|
901
|
+
if (organizationRaw !== undefined) {
|
|
902
|
+
if (typeof organizationRaw !== "string" || organizationRaw === "") {
|
|
903
|
+
return fail(
|
|
904
|
+
file,
|
|
905
|
+
"organization",
|
|
906
|
+
"a non-empty string",
|
|
907
|
+
describeFound(organizationRaw),
|
|
908
|
+
{ snippet: snippetFor(fm, "organization") },
|
|
909
|
+
);
|
|
910
|
+
}
|
|
911
|
+
organization = organizationRaw;
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
// description — optional one-line API summary; the primary signal in the
|
|
915
|
+
// multi-guide disambiguation menu. Structural validation only (non-empty,
|
|
916
|
+
// single line). The ≤200-char cap is an api-learn write-path policy, not a
|
|
917
|
+
// parser concern (strict-on-write, lenient-on-read).
|
|
918
|
+
let description: string | undefined;
|
|
919
|
+
const descriptionRaw = m["description"];
|
|
920
|
+
if (descriptionRaw !== undefined) {
|
|
921
|
+
if (typeof descriptionRaw !== "string" || descriptionRaw === "") {
|
|
922
|
+
return fail(
|
|
923
|
+
file,
|
|
924
|
+
"description",
|
|
925
|
+
"a non-empty string",
|
|
926
|
+
describeFound(descriptionRaw),
|
|
927
|
+
{ snippet: snippetFor(fm, "description") },
|
|
928
|
+
);
|
|
929
|
+
}
|
|
930
|
+
if (descriptionRaw.includes("\n")) {
|
|
931
|
+
return fail(
|
|
932
|
+
file,
|
|
933
|
+
"description",
|
|
934
|
+
"a single-line string (no newlines)",
|
|
935
|
+
"contains a newline",
|
|
936
|
+
{
|
|
937
|
+
snippet: snippetFor(fm, "description"),
|
|
938
|
+
fix: "Keep description to one line; put longer prose in the guide body (after ---).",
|
|
939
|
+
},
|
|
940
|
+
);
|
|
941
|
+
}
|
|
942
|
+
description = descriptionRaw;
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
let gatherAllMax = GATHER_ALL_MAX_FALLBACK;
|
|
946
|
+
const gatherAllMaxRaw = m["gatherAllMax"];
|
|
947
|
+
if (gatherAllMaxRaw !== undefined) {
|
|
948
|
+
if (
|
|
949
|
+
typeof gatherAllMaxRaw !== "number" ||
|
|
950
|
+
!Number.isFinite(gatherAllMaxRaw) ||
|
|
951
|
+
gatherAllMaxRaw <= 0
|
|
952
|
+
) {
|
|
953
|
+
return fail(
|
|
954
|
+
file,
|
|
955
|
+
"gatherAllMax",
|
|
956
|
+
"a positive integer",
|
|
957
|
+
describeFound(gatherAllMaxRaw),
|
|
958
|
+
);
|
|
959
|
+
}
|
|
960
|
+
gatherAllMax = gatherAllMaxRaw;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
const authRes = validateAuth(m["auth"], file, fm);
|
|
964
|
+
if (!("kind" in authRes)) return authRes as ParseApiGuideResult;
|
|
965
|
+
const auth = authRes;
|
|
966
|
+
|
|
967
|
+
let pagination: PaginationConfig | undefined;
|
|
968
|
+
if (m["pagination"] !== undefined) {
|
|
969
|
+
const pr = validatePagination(m["pagination"], "pagination", file);
|
|
970
|
+
if (!("style" in pr)) return pr as ParseApiGuideResult;
|
|
971
|
+
pagination = pr;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
let responseShape: ResponseShape = { format: "json", charset: "utf-8" };
|
|
975
|
+
if (m["responseShape"] !== undefined) {
|
|
976
|
+
const rs = validateResponseShape(m["responseShape"], "responseShape", file);
|
|
977
|
+
if (!("format" in rs)) return rs as ParseApiGuideResult;
|
|
978
|
+
responseShape = rs;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
// operations
|
|
982
|
+
const opsRaw = m["operations"];
|
|
983
|
+
if (opsRaw === undefined) {
|
|
984
|
+
return fail(
|
|
985
|
+
file,
|
|
986
|
+
"operations",
|
|
987
|
+
"a non-empty list of operation mappings",
|
|
988
|
+
"missing",
|
|
989
|
+
);
|
|
990
|
+
}
|
|
991
|
+
if (!Array.isArray(opsRaw) || opsRaw.length === 0) {
|
|
992
|
+
return fail(
|
|
993
|
+
file,
|
|
994
|
+
"operations",
|
|
995
|
+
"a non-empty list of operation mappings",
|
|
996
|
+
describeFound(opsRaw),
|
|
997
|
+
{
|
|
998
|
+
snippet: snippetFor(fm, "operations"),
|
|
999
|
+
},
|
|
1000
|
+
);
|
|
1001
|
+
}
|
|
1002
|
+
const operations: Operation[] = [];
|
|
1003
|
+
for (let i = 0; i < opsRaw.length; i++) {
|
|
1004
|
+
const opRaw = opsRaw[i];
|
|
1005
|
+
if (opRaw === undefined) continue;
|
|
1006
|
+
const opRes = validateOperation(opRaw, i, file, pagination);
|
|
1007
|
+
if (!("name" in opRes)) return opRes as ParseApiGuideResult;
|
|
1008
|
+
operations.push(opRes);
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
const guide: ApiGuide = {
|
|
1012
|
+
content,
|
|
1013
|
+
updated,
|
|
1014
|
+
category: "site",
|
|
1015
|
+
source: "user",
|
|
1016
|
+
icon,
|
|
1017
|
+
shortName,
|
|
1018
|
+
domains,
|
|
1019
|
+
kind,
|
|
1020
|
+
apiHost,
|
|
1021
|
+
verified,
|
|
1022
|
+
...(docs ? { docs } : {}),
|
|
1023
|
+
...(organization ? { organization } : {}),
|
|
1024
|
+
...(description ? { description } : {}),
|
|
1025
|
+
gatherAllMax,
|
|
1026
|
+
auth,
|
|
1027
|
+
responseShape,
|
|
1028
|
+
operations,
|
|
1029
|
+
...(pagination ? { pagination } : {}),
|
|
1030
|
+
};
|
|
1031
|
+
return { ok: true, guide };
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
1035
|
+
// projectToGuide — strips recipe fields, keeps presentation + kind
|
|
1036
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
1037
|
+
|
|
1038
|
+
export function projectToGuide(guide: ApiGuide): Guide {
|
|
1039
|
+
const projection: Guide = {
|
|
1040
|
+
content: guide.content,
|
|
1041
|
+
updated: guide.updated,
|
|
1042
|
+
category: guide.category,
|
|
1043
|
+
source: guide.source,
|
|
1044
|
+
icon: guide.icon,
|
|
1045
|
+
shortName: guide.shortName,
|
|
1046
|
+
kind: guide.kind,
|
|
1047
|
+
...(guide.domains ? { domains: guide.domains } : {}),
|
|
1048
|
+
};
|
|
1049
|
+
return projection;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
1053
|
+
// Directory loader — one malformed guide doesn't block the store.
|
|
1054
|
+
//
|
|
1055
|
+
// Loads from per-domain subdirectories: <dir>/<domain>/guide.md.
|
|
1056
|
+
// Flat top-level .md files are no longer loaded (pre-ship break;
|
|
1057
|
+
// no production user guides exist before this change).
|
|
1058
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
1059
|
+
|
|
1060
|
+
export function loadApiGuidesFromDir(dir: string): LoadedApiGuides {
|
|
1061
|
+
const result: LoadedApiGuides = { guides: {}, malformed: [] };
|
|
1062
|
+
if (!existsSync(dir)) return result;
|
|
1063
|
+
let entries: string[];
|
|
1064
|
+
try {
|
|
1065
|
+
entries = readdirSync(dir);
|
|
1066
|
+
} catch {
|
|
1067
|
+
return result;
|
|
1068
|
+
}
|
|
1069
|
+
for (const entry of entries) {
|
|
1070
|
+
const entryPath = join(dir, entry);
|
|
1071
|
+
try {
|
|
1072
|
+
if (!statSync(entryPath).isDirectory()) continue;
|
|
1073
|
+
} catch {
|
|
1074
|
+
continue;
|
|
1075
|
+
}
|
|
1076
|
+
const guidePath = join(entryPath, "guide.md");
|
|
1077
|
+
try {
|
|
1078
|
+
if (!statSync(guidePath).isFile()) continue;
|
|
1079
|
+
} catch {
|
|
1080
|
+
continue;
|
|
1081
|
+
}
|
|
1082
|
+
const name = entry; // domain name = subdir name
|
|
1083
|
+
let raw: string;
|
|
1084
|
+
try {
|
|
1085
|
+
raw = readFileSync(guidePath, "utf-8");
|
|
1086
|
+
} catch {
|
|
1087
|
+
continue;
|
|
1088
|
+
}
|
|
1089
|
+
const parsed = parseApiGuide(raw, {
|
|
1090
|
+
file: guidePath,
|
|
1091
|
+
filename: name,
|
|
1092
|
+
});
|
|
1093
|
+
if (parsed.ok) {
|
|
1094
|
+
result.guides[name] = parsed.guide;
|
|
1095
|
+
} else {
|
|
1096
|
+
result.malformed.push({
|
|
1097
|
+
file: guidePath,
|
|
1098
|
+
filename: name,
|
|
1099
|
+
error: parsed.error,
|
|
1100
|
+
});
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
return result;
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
// ════════════════════════════════════════════════════════════════════
|
|
1107
|
+
// Disambiguation helpers — shared by the api-guide menu and the
|
|
1108
|
+
// api-fetch ambiguous-operation error. One rendering of the per-guide
|
|
1109
|
+
// listing so the two surfaces stay visually consistent.
|
|
1110
|
+
// ════════════════════════════════════════════════════════════════════
|
|
1111
|
+
|
|
1112
|
+
/**
|
|
1113
|
+
* Truncated op-name summary for disambiguation surfaces:
|
|
1114
|
+
* "N ops: a, b, c, d, e, +K more" (first 5 names, then the remaining count).
|
|
1115
|
+
* A 50-op guide must not dump 50 names into context — the menu exists to
|
|
1116
|
+
* help pick a guide cheaply; the full op list is one api-guide call away.
|
|
1117
|
+
*/
|
|
1118
|
+
function formatOpSummary(ops: { name: string }[]): string {
|
|
1119
|
+
const names = ops.map((o) => o.name);
|
|
1120
|
+
const count = names.length;
|
|
1121
|
+
const head = names.slice(0, 5);
|
|
1122
|
+
const remaining = count - head.length;
|
|
1123
|
+
const tail = remaining > 0 ? `, +${remaining} more` : "";
|
|
1124
|
+
return `${count} ops: ${head.join(", ")}${tail}`;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
/**
|
|
1128
|
+
* Per-guide listing lines for a disambiguation surface (the api-guide
|
|
1129
|
+
* multi-guide menu and the api-fetch ambiguous-op error). Each entry:
|
|
1130
|
+
* `icon shortName` [+ ` — description` when present] then the truncated
|
|
1131
|
+
* op-name list. When `description:` is absent the line falls back to
|
|
1132
|
+
* shortName + op names only (the status-quo shape), so un-backfilled
|
|
1133
|
+
* guides render consistently with those that have a one-line summary.
|
|
1134
|
+
*/
|
|
1135
|
+
export function formatGuideListings(
|
|
1136
|
+
entries: { guide: ApiGuide; dirName: string }[],
|
|
1137
|
+
): string {
|
|
1138
|
+
const lines: string[] = [];
|
|
1139
|
+
for (const { guide } of entries) {
|
|
1140
|
+
lines.push(
|
|
1141
|
+
` ${guide.icon} ${guide.shortName}` +
|
|
1142
|
+
(guide.description ? ` — ${guide.description}` : ""),
|
|
1143
|
+
);
|
|
1144
|
+
lines.push(` ${formatOpSummary(guide.operations)}`);
|
|
1145
|
+
}
|
|
1146
|
+
return lines.join("\n");
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
// ════════════════════════════════════════════════════════════════════
|
|
1150
|
+
// Catalog rendering — healthy + ⚠ malformed together
|
|
1151
|
+
//
|
|
1152
|
+
// Base catalog is collapsed by `organization:`: one line per org with its
|
|
1153
|
+
// guide count and domain set. Guides without `organization:` fall back to
|
|
1154
|
+
// the per-guide line, so the un-backfilled corpus renders unchanged (no
|
|
1155
|
+
// forced migration). Op counts live on the per-domain disambiguation menu
|
|
1156
|
+
// (api-guide {domain}), where they're useful for picking a guide — not
|
|
1157
|
+
// here, where they'd bloat context for orgs with many guides.
|
|
1158
|
+
// ════════════════════════════════════════════════════════════════════
|
|
1159
|
+
|
|
1160
|
+
export function formatApiGuideCatalog(loaded: LoadedApiGuides): string {
|
|
1161
|
+
const lines: string[] = ["API guides:"];
|
|
1162
|
+
|
|
1163
|
+
// Org-grouped rows preserve first-appearance order; guides without
|
|
1164
|
+
// organization fall back to the per-guide line (no forced migration).
|
|
1165
|
+
const orgRows: { org: string; guides: ApiGuide[] }[] = [];
|
|
1166
|
+
const orgIndex = new Map<string, number>();
|
|
1167
|
+
const orgless: { name: string; guide: ApiGuide }[] = [];
|
|
1168
|
+
for (const [name, guide] of Object.entries(loaded.guides)) {
|
|
1169
|
+
if (guide.organization) {
|
|
1170
|
+
const idx = orgIndex.get(guide.organization);
|
|
1171
|
+
if (idx !== undefined) {
|
|
1172
|
+
orgRows[idx]!.guides.push(guide);
|
|
1173
|
+
} else {
|
|
1174
|
+
orgIndex.set(guide.organization, orgRows.length);
|
|
1175
|
+
orgRows.push({ org: guide.organization, guides: [guide] });
|
|
1176
|
+
}
|
|
1177
|
+
} else {
|
|
1178
|
+
orgless.push({ name, guide });
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
for (const row of orgRows) {
|
|
1183
|
+
const domains = new Set<string>();
|
|
1184
|
+
for (const g of row.guides) {
|
|
1185
|
+
for (const d of g.domains ?? []) domains.add(d);
|
|
1186
|
+
}
|
|
1187
|
+
const domList = domains.size > 0 ? [...domains].join(", ") : "—";
|
|
1188
|
+
const n = row.guides.length;
|
|
1189
|
+
lines.push(` 🏛️ ${row.org} — ${n} guide${n > 1 ? "s" : ""} (${domList})`);
|
|
1190
|
+
}
|
|
1191
|
+
for (const { name, guide } of orgless) {
|
|
1192
|
+
const domains =
|
|
1193
|
+
guide.domains && guide.domains.length > 0
|
|
1194
|
+
? guide.domains.join(", ")
|
|
1195
|
+
: name;
|
|
1196
|
+
lines.push(
|
|
1197
|
+
` ${guide.icon} ${guide.shortName} — ${domains} (verified ${guide.verified}, ${guide.operations.length} ops)`,
|
|
1198
|
+
);
|
|
1199
|
+
}
|
|
1200
|
+
for (const mal of loaded.malformed) {
|
|
1201
|
+
lines.push(
|
|
1202
|
+
` ⚠ malformed — ${mal.filename}: ${mal.error.field} — expected ${mal.error.expected}; found ${mal.error.found}`,
|
|
1203
|
+
);
|
|
1204
|
+
}
|
|
1205
|
+
if (
|
|
1206
|
+
Object.keys(loaded.guides).length === 0 &&
|
|
1207
|
+
loaded.malformed.length === 0
|
|
1208
|
+
) {
|
|
1209
|
+
lines.push(
|
|
1210
|
+
" (no guides — call api-learn({domain, recipe}) to author one)",
|
|
1211
|
+
);
|
|
1212
|
+
}
|
|
1213
|
+
lines.push("");
|
|
1214
|
+
lines.push(
|
|
1215
|
+
'Call api-guide({domain: "<name>"}) for detail. Multiple guides for a domain show a disambiguation menu.',
|
|
1216
|
+
);
|
|
1217
|
+
return lines.join("\n");
|
|
1218
|
+
}
|