pi-lean-host 0.2.1 → 0.3.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 +62 -89
- package/core/api-guide-types.ts +9 -0
- package/core/api-toggle.ts +23 -1
- package/core/delete-command.ts +190 -0
- package/core/guide-picker.ts +104 -0
- package/core/helpers-command.ts +2 -4
- package/core/helpers.ts +28 -0
- package/core/parse-api-guide.ts +451 -24
- package/core/resolve-op.ts +222 -0
- package/core/transport.ts +1 -1
- package/core/verify-command.ts +399 -0
- package/package.json +5 -1
- package/tools/api-fetch.ts +149 -229
- package/tools/api-guide.ts +33 -38
- package/tools/api-learn.ts +432 -131
- package/tools/api-probe.ts +146 -36
package/core/parse-api-guide.ts
CHANGED
|
@@ -15,6 +15,7 @@ import type { Guide } from "./guide-loader.js";
|
|
|
15
15
|
import { extractPathTokens } from "./path-template.js";
|
|
16
16
|
import {
|
|
17
17
|
GATHER_ALL_MAX_FALLBACK,
|
|
18
|
+
GUIDE_SCHEMA_VERSION,
|
|
18
19
|
KNOWN_AUTH_KINDS,
|
|
19
20
|
type ApiGuide,
|
|
20
21
|
type DateParamFormat,
|
|
@@ -43,6 +44,42 @@ const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/;
|
|
|
43
44
|
|
|
44
45
|
export const TODAY = () => new Date().toISOString().slice(0, 10);
|
|
45
46
|
|
|
47
|
+
/**
|
|
48
|
+
* Line-level frontmatter stamp — replace (or insert) a single `key: value`
|
|
49
|
+
* line inside the isolated frontmatter block, preserving comments and key
|
|
50
|
+
* order (no YAML round-trip — a round-trip reformats and strips comments).
|
|
51
|
+
* Used by api-learn (schemaVersion save-stamp) and /api verify (verified
|
|
52
|
+
* stamp). Returns the document unchanged when it has no frontmatter block.
|
|
53
|
+
*/
|
|
54
|
+
export function stampFrontmatterField(
|
|
55
|
+
raw: string,
|
|
56
|
+
key: string,
|
|
57
|
+
value: string,
|
|
58
|
+
): string {
|
|
59
|
+
const match = raw.match(FRONTMATTER_RE);
|
|
60
|
+
if (!match) return raw;
|
|
61
|
+
const fm = match[1] ?? "";
|
|
62
|
+
const content = match[2] ?? "";
|
|
63
|
+
const nl = /^---(\r?\n)/.exec(raw)?.[1] ?? "\n";
|
|
64
|
+
const lines = fm.split(nl);
|
|
65
|
+
const keyRe = new RegExp(`^${key}:\\s*.+$`);
|
|
66
|
+
const idx = lines.findIndex((l) => keyRe.test(l));
|
|
67
|
+
const line = `${key}: ${value}`;
|
|
68
|
+
if (idx === -1) {
|
|
69
|
+
// Insert-only separation: a new key would land flush against the
|
|
70
|
+
// preceding line (e.g. under the last op's params block). Push a
|
|
71
|
+
// blank line first when the preceding line is non-empty. Replace
|
|
72
|
+
// must NOT do this — every /api verify re-stamp would drift the file.
|
|
73
|
+
if (lines.length > 0 && lines.at(-1)?.trim() !== "") {
|
|
74
|
+
lines.push("");
|
|
75
|
+
}
|
|
76
|
+
lines.push(line);
|
|
77
|
+
} else {
|
|
78
|
+
lines[idx] = line;
|
|
79
|
+
}
|
|
80
|
+
return `---${nl}${lines.join(nl)}${nl}---${nl}${content}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
46
83
|
const VALID_VIA: ReadonlySet<string> = new Set(["restGet", "paginate"]);
|
|
47
84
|
// accept is a free-form string — any media type is valid (`json`/`xml`
|
|
48
85
|
// shorthands are mapped by the helper).
|
|
@@ -61,6 +98,23 @@ const VALID_PAGINATION_STYLE: ReadonlySet<string> = new Set([
|
|
|
61
98
|
"tokenBag",
|
|
62
99
|
]);
|
|
63
100
|
|
|
101
|
+
// Strict auth schema: the only keys validateAuth reads. Any other key
|
|
102
|
+
// under `auth` is rejected at parse — the parser used to silently drop
|
|
103
|
+
// unknowns, so a wrong-but-plausible shape (e.g. `name`/`secret`) saved a
|
|
104
|
+
// guide the executor then silently couldn't honor.
|
|
105
|
+
const KNOWN_AUTH_KEYS: ReadonlySet<string> = new Set([
|
|
106
|
+
"kind",
|
|
107
|
+
"headers",
|
|
108
|
+
"secretRefs",
|
|
109
|
+
"secretQueryRefs",
|
|
110
|
+
"requires",
|
|
111
|
+
"optional",
|
|
112
|
+
"headerPrefixes",
|
|
113
|
+
]);
|
|
114
|
+
// Set insertion order — used to render the known-key list in error strings
|
|
115
|
+
// (expected + fallback fix) so they can't drift from the set.
|
|
116
|
+
const KNOWN_AUTH_KEYS_LIST = [...KNOWN_AUTH_KEYS].join(", ");
|
|
117
|
+
|
|
64
118
|
// ═══════════════════════════════════════════════════════════════════
|
|
65
119
|
// Error helper
|
|
66
120
|
// ═══════════════════════════════════════════════════════════════════
|
|
@@ -111,6 +165,58 @@ function snippetFor(frontmatter: string, key: string): string | undefined {
|
|
|
111
165
|
return out.join("\n");
|
|
112
166
|
}
|
|
113
167
|
|
|
168
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
169
|
+
// Reserved-char plain-scalar pre-scan
|
|
170
|
+
// ═══════════════════════════════════════════════════════════════════
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Chars that make a plain scalar invalid as a value — yaml's
|
|
174
|
+
* "Plain value cannot start with reserved character" error class. Backtick is
|
|
175
|
+
* the observed footgun (markdown-style `` `field` `` refs pasted into
|
|
176
|
+
* descriptions); `%`/`@`/`,` are the same error class and never legitimate at
|
|
177
|
+
* the start of a value. `|`/`>` (block scalars), `[`/`{` (flow), quotes, and
|
|
178
|
+
* `#` (comments) are all legitimate starts and deliberately NOT flagged.
|
|
179
|
+
*/
|
|
180
|
+
const RESERVED_PLAIN_START = new Set(["`", "%", "@", ","]);
|
|
181
|
+
|
|
182
|
+
interface ReservedPlainHit {
|
|
183
|
+
line: number;
|
|
184
|
+
col: number;
|
|
185
|
+
char: string;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Best-effort one-pass scan for `key: <value>` lines whose plain-scalar value
|
|
190
|
+
* starts with a reserved YAML character. yamlParse throws on the FIRST such
|
|
191
|
+
* value and stops, so a multi-backtick frontmatter needs one save/validate
|
|
192
|
+
* cycle per offender — this lists them all at once. Line/column are reported
|
|
193
|
+
* relative to the frontmatter block (matching yamlParse) and count from the
|
|
194
|
+
* raw line, indentation included. Advisory: only fires on the reserved-char
|
|
195
|
+
* class, which the parser would reject anyway.
|
|
196
|
+
*/
|
|
197
|
+
function scanReservedPlainStarts(fm: string): ReservedPlainHit[] {
|
|
198
|
+
const hits: ReservedPlainHit[] = [];
|
|
199
|
+
const lines = fm.split("\n");
|
|
200
|
+
for (let i = 0; i < lines.length; i++) {
|
|
201
|
+
const raw = lines[i] ?? "";
|
|
202
|
+
const line = raw.trimStart();
|
|
203
|
+
// Skip blank, comment, and list-item lines (op headers like
|
|
204
|
+
// `- name: …` — the backtick footgun lives in `description:`-style
|
|
205
|
+
// value lines, which are never `- `-prefixed).
|
|
206
|
+
if (line === "" || line.startsWith("#") || line.startsWith("- ")) continue;
|
|
207
|
+
const m = /^[^:#]+: /.exec(line);
|
|
208
|
+
if (!m) continue;
|
|
209
|
+
const ch = line[m[0].length];
|
|
210
|
+
if (ch === undefined || !RESERVED_PLAIN_START.has(ch)) continue;
|
|
211
|
+
hits.push({
|
|
212
|
+
line: i + 1,
|
|
213
|
+
col: raw.length - line.length + m[0].length + 1,
|
|
214
|
+
char: ch,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
return hits;
|
|
218
|
+
}
|
|
219
|
+
|
|
114
220
|
// ═══════════════════════════════════════════════════════════════════
|
|
115
221
|
// Field validators
|
|
116
222
|
// ═══════════════════════════════════════════════════════════════════
|
|
@@ -156,10 +262,13 @@ function requireStringArray(
|
|
|
156
262
|
key: string,
|
|
157
263
|
file: string | undefined,
|
|
158
264
|
fm: string,
|
|
265
|
+
opts?: { missingFix?: string },
|
|
159
266
|
): string[] | ParseApiGuideResult {
|
|
160
267
|
const v = m[key];
|
|
161
268
|
if (v === undefined) {
|
|
162
|
-
return fail(file, key, "a list of strings", "missing"
|
|
269
|
+
return fail(file, key, "a list of strings", "missing", {
|
|
270
|
+
...(opts?.missingFix ? { fix: opts.missingFix } : {}),
|
|
271
|
+
});
|
|
163
272
|
}
|
|
164
273
|
if (!Array.isArray(v) || v.length === 0) {
|
|
165
274
|
return fail(file, key, "a non-empty list of strings", describeFound(v), {
|
|
@@ -431,6 +540,65 @@ function isParseErr<T>(v: T | ParseApiGuideResult): v is ParseApiGuideResult {
|
|
|
431
540
|
);
|
|
432
541
|
}
|
|
433
542
|
|
|
543
|
+
/** Levenshtein edit distance — spots near-miss auth keys (e.g. `requiers:` →
|
|
544
|
+
* `requires`) so the unknown-key error can say "did you mean X?" instead of a
|
|
545
|
+
* bare rejection. */
|
|
546
|
+
function editDistance(a: string, b: string): number {
|
|
547
|
+
const m = a.length;
|
|
548
|
+
const n = b.length;
|
|
549
|
+
if (m === 0) return n;
|
|
550
|
+
if (n === 0) return m;
|
|
551
|
+
let prev = Array.from({ length: n + 1 }, (_, j) => j);
|
|
552
|
+
for (let i = 1; i <= m; i++) {
|
|
553
|
+
const cur = new Array<number>(n + 1);
|
|
554
|
+
cur[0] = i;
|
|
555
|
+
for (let j = 1; j <= n; j++) {
|
|
556
|
+
cur[j] = Math.min(
|
|
557
|
+
prev[j]! + 1,
|
|
558
|
+
cur[j - 1]! + 1,
|
|
559
|
+
prev[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1),
|
|
560
|
+
);
|
|
561
|
+
}
|
|
562
|
+
prev = cur;
|
|
563
|
+
}
|
|
564
|
+
return prev[n]!;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** Nearest known auth key within edit distance ≤ 2, or undefined. */
|
|
568
|
+
function nearestKnownKey(
|
|
569
|
+
key: string,
|
|
570
|
+
known: ReadonlySet<string>,
|
|
571
|
+
): string | undefined {
|
|
572
|
+
let best: string | undefined;
|
|
573
|
+
let bestDist = Infinity;
|
|
574
|
+
for (const k of known) {
|
|
575
|
+
const d = editDistance(key, k);
|
|
576
|
+
if (d < bestDist) {
|
|
577
|
+
bestDist = d;
|
|
578
|
+
best = k;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
return bestDist <= 2 ? best : undefined;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/**
|
|
585
|
+
* Adaptive fix for an unknown-auth-key rejection: near-miss → "did you mean
|
|
586
|
+
* X?"; the observed wrong shape (`name`/`secret` under static-key) → point at
|
|
587
|
+
* the real secretRefs/requires shape; anything else → list the known keys.
|
|
588
|
+
*/
|
|
589
|
+
function authUnknownKeyFix(unknownKeys: string[]): string {
|
|
590
|
+
for (const key of unknownKeys) {
|
|
591
|
+
const known = nearestKnownKey(key, KNOWN_AUTH_KEYS);
|
|
592
|
+
if (known !== undefined) {
|
|
593
|
+
return `Unknown auth key "${key}" — did you mean "${known}"?`;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
if (unknownKeys.includes("name") || unknownKeys.includes("secret")) {
|
|
597
|
+
return `The keyed-header shape is auth.secretRefs: { <header>: <secret-name> } with the secret declared in auth.requires (or auth.optional) — replace name/secret with secretRefs + requires.`;
|
|
598
|
+
}
|
|
599
|
+
return `Unknown auth key(s): ${unknownKeys.join(", ")} — known keys: ${KNOWN_AUTH_KEYS_LIST}.`;
|
|
600
|
+
}
|
|
601
|
+
|
|
434
602
|
function validateAuth(
|
|
435
603
|
raw: unknown,
|
|
436
604
|
file: string | undefined,
|
|
@@ -453,6 +621,9 @@ function validateAuth(
|
|
|
453
621
|
"auth.kind",
|
|
454
622
|
"a string",
|
|
455
623
|
kindRaw === undefined ? "missing" : describeFound(kindRaw),
|
|
624
|
+
{
|
|
625
|
+
fix: "kind is one of: none | static-key — use `kind: none` (public) or `kind: static-key` (keyed header); or call api-learn({domain, new: true}) for a full skeleton",
|
|
626
|
+
},
|
|
456
627
|
);
|
|
457
628
|
}
|
|
458
629
|
if (!KNOWN_AUTH_KINDS.has(kindRaw)) {
|
|
@@ -471,6 +642,25 @@ function validateAuth(
|
|
|
471
642
|
fix: "OAuth2 is not yet implemented. Use kind: none (public) or kind: static-key (keyed header) for now.",
|
|
472
643
|
});
|
|
473
644
|
}
|
|
645
|
+
// Strict auth schema — reject unknown keys. The parser used to
|
|
646
|
+
// silently drop unknown keys (a wrong-but-plausible shape like
|
|
647
|
+
// `name`/`secret` saved a guide the executor then silently couldn't
|
|
648
|
+
// honor). Reject, don't infer: the fix is adaptive (near-miss → "did you
|
|
649
|
+
// mean X?", wrong shape → secretRefs/requires).
|
|
650
|
+
const unknownKeys = Object.keys(a).filter((k) => !KNOWN_AUTH_KEYS.has(k));
|
|
651
|
+
if (unknownKeys.length > 0) {
|
|
652
|
+
const first = unknownKeys[0]!;
|
|
653
|
+
return fail(
|
|
654
|
+
file,
|
|
655
|
+
`auth.${first}`,
|
|
656
|
+
`a known auth key (${KNOWN_AUTH_KEYS_LIST})`,
|
|
657
|
+
`unknown key(s): ${unknownKeys.join(", ")}`,
|
|
658
|
+
{
|
|
659
|
+
snippet: snippetFor(fm, "auth"),
|
|
660
|
+
fix: authUnknownKeyFix(unknownKeys),
|
|
661
|
+
},
|
|
662
|
+
);
|
|
663
|
+
}
|
|
474
664
|
// Parse optional headers (per-kind extra headers, e.g. X-Api-Key for DEMO_KEY).
|
|
475
665
|
let headers: Record<string, string> | undefined;
|
|
476
666
|
if (a["headers"] !== undefined) {
|
|
@@ -565,7 +755,8 @@ function validateAuth(
|
|
|
565
755
|
fm,
|
|
566
756
|
"auth.headerPrefixes",
|
|
567
757
|
"a YAML mapping of header name → non-empty prefix string",
|
|
568
|
-
(v) =>
|
|
758
|
+
(v) =>
|
|
759
|
+
typeof v === "string" && v.length > 0 && !/^\{[a-zA-Z0-9_]+\}$/.test(v),
|
|
569
760
|
);
|
|
570
761
|
if (isParseErr(hp)) return hp;
|
|
571
762
|
headerPrefixes = hp;
|
|
@@ -867,6 +1058,76 @@ function validateOperation(
|
|
|
867
1058
|
}
|
|
868
1059
|
}
|
|
869
1060
|
|
|
1061
|
+
// requiresAnyOf — at-least-one-of constraint (one group per op, v1).
|
|
1062
|
+
// Parser cross-field checks, same class as the secretQueryRefs collision
|
|
1063
|
+
// guard: empty-array reject (check #0, before member inspection),
|
|
1064
|
+
// member-exists, path-param reject, no `required: true` overlap, no
|
|
1065
|
+
// `default` on a member. A group member that is `required` would defeat
|
|
1066
|
+
// the group at runtime; a `default` would fire alongside a caller-supplied
|
|
1067
|
+
// sibling (the members are mutually exclusive peers).
|
|
1068
|
+
const requiresAnyOfRaw = o["requiresAnyOf"];
|
|
1069
|
+
let requiresAnyOf: string[] | undefined;
|
|
1070
|
+
if (requiresAnyOfRaw !== undefined) {
|
|
1071
|
+
if (!Array.isArray(requiresAnyOfRaw) || requiresAnyOfRaw.length === 0) {
|
|
1072
|
+
return fail(
|
|
1073
|
+
file,
|
|
1074
|
+
fieldPath("requiresAnyOf"),
|
|
1075
|
+
"a non-empty list of param names",
|
|
1076
|
+
describeFound(requiresAnyOfRaw),
|
|
1077
|
+
);
|
|
1078
|
+
}
|
|
1079
|
+
for (const member of requiresAnyOfRaw) {
|
|
1080
|
+
if (typeof member !== "string" || member === "") {
|
|
1081
|
+
return fail(
|
|
1082
|
+
file,
|
|
1083
|
+
fieldPath("requiresAnyOf"),
|
|
1084
|
+
"a non-empty list of param names",
|
|
1085
|
+
`contains ${describeFound(member)}`,
|
|
1086
|
+
);
|
|
1087
|
+
}
|
|
1088
|
+
if (pathParams.includes(member)) {
|
|
1089
|
+
return fail(
|
|
1090
|
+
file,
|
|
1091
|
+
fieldPath(`requiresAnyOf.${member}`),
|
|
1092
|
+
"a query param name (not a path param)",
|
|
1093
|
+
`"${member}" is a path param — path params are always required via {${member}} in path`,
|
|
1094
|
+
);
|
|
1095
|
+
}
|
|
1096
|
+
const spec = params[member];
|
|
1097
|
+
if (spec === undefined) {
|
|
1098
|
+
return fail(
|
|
1099
|
+
file,
|
|
1100
|
+
fieldPath(`requiresAnyOf.${member}`),
|
|
1101
|
+
"a param name declared in this operation's params",
|
|
1102
|
+
`"${member}" is not a declared param`,
|
|
1103
|
+
);
|
|
1104
|
+
}
|
|
1105
|
+
if (spec.required === true) {
|
|
1106
|
+
return fail(
|
|
1107
|
+
file,
|
|
1108
|
+
fieldPath(`requiresAnyOf.${member}`),
|
|
1109
|
+
"a param that is not also required: true",
|
|
1110
|
+
`"${member}" is required: true`,
|
|
1111
|
+
{
|
|
1112
|
+
fix: `Remove required: true from params.${member} — it is governed by the requiresAnyOf group, not per-param required.`,
|
|
1113
|
+
},
|
|
1114
|
+
);
|
|
1115
|
+
}
|
|
1116
|
+
if (spec.default !== undefined) {
|
|
1117
|
+
return fail(
|
|
1118
|
+
file,
|
|
1119
|
+
fieldPath(`requiresAnyOf.${member}`),
|
|
1120
|
+
"a param that does not also declare a default",
|
|
1121
|
+
`"${member}" has a default`,
|
|
1122
|
+
{
|
|
1123
|
+
fix: `Remove the default from params.${member} — requiresAnyOf members are mutually exclusive peers, so a default would fire alongside a caller-supplied sibling.`,
|
|
1124
|
+
},
|
|
1125
|
+
);
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
requiresAnyOf = requiresAnyOfRaw as string[];
|
|
1129
|
+
}
|
|
1130
|
+
|
|
870
1131
|
// dateParams — param name → date format normalization
|
|
871
1132
|
const dateParamsRaw = o["dateParams"];
|
|
872
1133
|
let dateParams: Record<string, DateParamFormat> | undefined;
|
|
@@ -1006,6 +1267,7 @@ function validateOperation(
|
|
|
1006
1267
|
...(transform === undefined ? {} : { transform }),
|
|
1007
1268
|
...(passthrough === undefined ? {} : { passthrough }),
|
|
1008
1269
|
...(dateParams === undefined ? {} : { dateParams }),
|
|
1270
|
+
...(requiresAnyOf === undefined ? {} : { requiresAnyOf }),
|
|
1009
1271
|
...(parseOverride ? { parse: parseOverride } : {}),
|
|
1010
1272
|
...(opPagination ? { pagination: opPagination } : {}),
|
|
1011
1273
|
...(opGatherAllMax === undefined ? {} : { gatherAllMax: opGatherAllMax }),
|
|
@@ -1026,6 +1288,34 @@ export function parseApiGuide(
|
|
|
1026
1288
|
|
|
1027
1289
|
const match = raw.match(FRONTMATTER_RE);
|
|
1028
1290
|
if (!match) {
|
|
1291
|
+
// Opening delimiter present → the failure is on the closing side, not
|
|
1292
|
+
// a missing frontmatter block. Detect the opener with /^---\r?\n/ (not
|
|
1293
|
+
// startsWith("---\n")) so a CRLF-prefixed file is routed here too.
|
|
1294
|
+
if (/^---\r?\n/.test(raw)) {
|
|
1295
|
+
// A `\n---` after the opener means a closer exists but FRONTMATTER_RE
|
|
1296
|
+
// still failed — the closer is malformed (e.g. no trailing newline
|
|
1297
|
+
// at EOF). Otherwise there is no closer at all.
|
|
1298
|
+
if (/\n---/.test(raw.replace(/^---\r?\n/, ""))) {
|
|
1299
|
+
return fail(
|
|
1300
|
+
file,
|
|
1301
|
+
"frontmatter",
|
|
1302
|
+
"a closing --- followed by a newline",
|
|
1303
|
+
"closing --- present but malformed (missing trailing newline after it)",
|
|
1304
|
+
{
|
|
1305
|
+
fix: "Ensure the closing --- is on its own line and followed by a newline before any prose.",
|
|
1306
|
+
},
|
|
1307
|
+
);
|
|
1308
|
+
}
|
|
1309
|
+
return fail(
|
|
1310
|
+
file,
|
|
1311
|
+
"frontmatter",
|
|
1312
|
+
"YAML frontmatter delimited by ---",
|
|
1313
|
+
"missing closing ---",
|
|
1314
|
+
{
|
|
1315
|
+
fix: "Close the frontmatter block with a --- line after the YAML.",
|
|
1316
|
+
},
|
|
1317
|
+
);
|
|
1318
|
+
}
|
|
1029
1319
|
return fail(
|
|
1030
1320
|
file,
|
|
1031
1321
|
"frontmatter",
|
|
@@ -1047,6 +1337,29 @@ export function parseApiGuide(
|
|
|
1047
1337
|
);
|
|
1048
1338
|
}
|
|
1049
1339
|
|
|
1340
|
+
// One-pass reserved-char pre-scan: yamlParse throws on the FIRST
|
|
1341
|
+
// backtick-leading plain scalar and stops, so a multi-offender
|
|
1342
|
+
// frontmatter costs one save/validate cycle per line. Scan first and
|
|
1343
|
+
// list them all at once. Advisory only — it fires solely on the
|
|
1344
|
+
// "Plain value cannot start with reserved character" class, which
|
|
1345
|
+
// yamlParse would reject anyway — the parser stays the source of truth.
|
|
1346
|
+
const reservedHits = scanReservedPlainStarts(fm);
|
|
1347
|
+
if (reservedHits.length > 0) {
|
|
1348
|
+
const where = reservedHits
|
|
1349
|
+
.map((h) => `line ${h.line}, column ${h.col}: ${h.char}`)
|
|
1350
|
+
.join(" ; ");
|
|
1351
|
+
return fail(
|
|
1352
|
+
file,
|
|
1353
|
+
"frontmatter",
|
|
1354
|
+
"valid YAML",
|
|
1355
|
+
`plain scalar value(s) start with a reserved YAML character — ${where}`,
|
|
1356
|
+
{
|
|
1357
|
+
snippet: fm,
|
|
1358
|
+
fix: 'Quote the value (description: "`the id`") or remove the leading backtick — a plain scalar cannot start with a reserved YAML character.',
|
|
1359
|
+
},
|
|
1360
|
+
);
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1050
1363
|
let meta: unknown;
|
|
1051
1364
|
try {
|
|
1052
1365
|
meta = yamlParse(fm);
|
|
@@ -1088,7 +1401,10 @@ export function parseApiGuide(
|
|
|
1088
1401
|
}
|
|
1089
1402
|
const kind = "api";
|
|
1090
1403
|
|
|
1091
|
-
const domainsRes = requireStringArray(m, "domains", file, fm
|
|
1404
|
+
const domainsRes = requireStringArray(m, "domains", file, fm, {
|
|
1405
|
+
missingFix:
|
|
1406
|
+
"Call api-learn({domain: '<domain>', new: true}) — it returns a template with `domains` pre-filled",
|
|
1407
|
+
});
|
|
1092
1408
|
if (!Array.isArray(domainsRes)) return domainsRes;
|
|
1093
1409
|
const domains = domainsRes;
|
|
1094
1410
|
|
|
@@ -1101,7 +1417,7 @@ export function parseApiGuide(
|
|
|
1101
1417
|
// ── recipe slice ──────────────────────────────────────────────
|
|
1102
1418
|
const apiHostRes = requireHttpUrl(m["apiHost"], "apiHost", file, fm, {
|
|
1103
1419
|
protocolFix: "Use https:// as the scheme",
|
|
1104
|
-
invalidFix: "Include the scheme, e.g. https://
|
|
1420
|
+
invalidFix: "Include the scheme, e.g. https://api.example.com/v1",
|
|
1105
1421
|
});
|
|
1106
1422
|
if (typeof apiHostRes !== "string") return apiHostRes;
|
|
1107
1423
|
const apiHost = apiHostRes;
|
|
@@ -1169,22 +1485,22 @@ export function parseApiGuide(
|
|
|
1169
1485
|
description = descriptionRaw;
|
|
1170
1486
|
}
|
|
1171
1487
|
|
|
1172
|
-
// schemaVersion —
|
|
1173
|
-
//
|
|
1174
|
-
//
|
|
1175
|
-
//
|
|
1176
|
-
//
|
|
1177
|
-
|
|
1488
|
+
// schemaVersion — breaking-change detection (design: "schemaVersion is
|
|
1489
|
+
// detection, not enforcement"). Stamped on save by api-learn; absent-on-
|
|
1490
|
+
// read defaults to 0 (the floor), so an unversioned guide flags as
|
|
1491
|
+
// potentially stale after any schema bump rather than silently inheriting
|
|
1492
|
+
// the new current. A valid-integer frontmatter value overrides the floor.
|
|
1493
|
+
// A stale value (< current) warns non-blockingly in the api-guide catalog/
|
|
1494
|
+
// detail and on api-fetch; never gates. A malformed (non-integer/negative)
|
|
1495
|
+
// value falls back to 0 and never rejects a guide.
|
|
1496
|
+
let schemaVersion = 0;
|
|
1178
1497
|
const schemaVersionRaw = m["schemaVersion"];
|
|
1179
|
-
if (
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
schemaVersion = schemaVersionRaw;
|
|
1186
|
-
}
|
|
1187
|
-
// else: tolerated + ignored — metadata stays silent on malformed input.
|
|
1498
|
+
if (
|
|
1499
|
+
typeof schemaVersionRaw === "number" &&
|
|
1500
|
+
Number.isInteger(schemaVersionRaw) &&
|
|
1501
|
+
schemaVersionRaw >= 0
|
|
1502
|
+
) {
|
|
1503
|
+
schemaVersion = schemaVersionRaw;
|
|
1188
1504
|
}
|
|
1189
1505
|
|
|
1190
1506
|
let gatherAllMax = GATHER_ALL_MAX_FALLBACK;
|
|
@@ -1291,7 +1607,7 @@ export function parseApiGuide(
|
|
|
1291
1607
|
...(docs ? { docs } : {}),
|
|
1292
1608
|
...(organization ? { organization } : {}),
|
|
1293
1609
|
...(description ? { description } : {}),
|
|
1294
|
-
|
|
1610
|
+
schemaVersion,
|
|
1295
1611
|
gatherAllMax,
|
|
1296
1612
|
auth,
|
|
1297
1613
|
responseShape,
|
|
@@ -1373,6 +1689,37 @@ export function loadApiGuidesFromDir(dir: string): LoadedApiGuides {
|
|
|
1373
1689
|
return result;
|
|
1374
1690
|
}
|
|
1375
1691
|
|
|
1692
|
+
// ════════════════════════════════════════════════════════════════════
|
|
1693
|
+
// Schema-version staleness — detection, never a gate
|
|
1694
|
+
// ════════════════════════════════════════════════════════════════════
|
|
1695
|
+
|
|
1696
|
+
/**
|
|
1697
|
+
* Pure staleness predicate: a guide is stale when its schemaVersion predates
|
|
1698
|
+
* the current schema (a bump may have broken it). A forward-stamped guide
|
|
1699
|
+
* (authored against a newer schema than the running host) is NOT stale.
|
|
1700
|
+
*/
|
|
1701
|
+
export function isStaleSchema(
|
|
1702
|
+
guideSchemaVersion: number,
|
|
1703
|
+
currentSchemaVersion: number,
|
|
1704
|
+
): boolean {
|
|
1705
|
+
return guideSchemaVersion < currentSchemaVersion;
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
/**
|
|
1709
|
+
* Non-blocking stale-schema warning line for a guide, or undefined when the
|
|
1710
|
+
* guide is current. Peer of the `⚠ malformed` catalog line — detection,
|
|
1711
|
+
* never a gate (the guide still loads and runs). `current` defaults to
|
|
1712
|
+
* GUIDE_SCHEMA_VERSION; tests pass a bumped value to force staleness.
|
|
1713
|
+
*/
|
|
1714
|
+
export function staleSchemaLine(
|
|
1715
|
+
guide: ApiGuide,
|
|
1716
|
+
current: number = GUIDE_SCHEMA_VERSION,
|
|
1717
|
+
): string | undefined {
|
|
1718
|
+
const v = guide.schemaVersion ?? 0;
|
|
1719
|
+
if (!isStaleSchema(v, current)) return undefined;
|
|
1720
|
+
return ` ⚠ schemaVersion ${v} < current ${current} — guide may need updating`;
|
|
1721
|
+
}
|
|
1722
|
+
|
|
1376
1723
|
// ════════════════════════════════════════════════════════════════════
|
|
1377
1724
|
// Disambiguation helpers — shared by the api-guide menu and the
|
|
1378
1725
|
// api-fetch ambiguous-operation error. One rendering of the per-guide
|
|
@@ -1402,7 +1749,10 @@ function formatOpSummary(ops: { name: string }[]): string {
|
|
|
1402
1749
|
* shortName + op names only (the status-quo shape), so un-backfilled
|
|
1403
1750
|
* guides render consistently with those that have a one-line summary.
|
|
1404
1751
|
*/
|
|
1405
|
-
export function formatGuideListings(
|
|
1752
|
+
export function formatGuideListings(
|
|
1753
|
+
entries: { guide: ApiGuide }[],
|
|
1754
|
+
current: number = GUIDE_SCHEMA_VERSION,
|
|
1755
|
+
): string {
|
|
1406
1756
|
const lines: string[] = [];
|
|
1407
1757
|
for (const { guide } of entries) {
|
|
1408
1758
|
lines.push(
|
|
@@ -1410,10 +1760,73 @@ export function formatGuideListings(entries: { guide: ApiGuide }[]): string {
|
|
|
1410
1760
|
(guide.description ? ` — ${guide.description}` : ""),
|
|
1411
1761
|
);
|
|
1412
1762
|
lines.push(` ${formatOpSummary(guide.operations)}`);
|
|
1763
|
+
const stale = staleSchemaLine(guide, current);
|
|
1764
|
+
if (stale) lines.push(stale);
|
|
1413
1765
|
}
|
|
1414
1766
|
return lines.join("\n");
|
|
1415
1767
|
}
|
|
1416
1768
|
|
|
1769
|
+
/**
|
|
1770
|
+
* Resolve a guide by shortName across a domain's matches (exact,
|
|
1771
|
+
* case-insensitive). Shared by api-guide, api-learn's fetch-recipe, and
|
|
1772
|
+
* /api verify — three call sites, one resolution rule (a drifted copy would
|
|
1773
|
+
* ship a known second bug). Returns a structured outcome; each caller renders
|
|
1774
|
+
* its own message (tool result vs command notify).
|
|
1775
|
+
*/
|
|
1776
|
+
export function selectGuideByShortName(
|
|
1777
|
+
matches: { guide: ApiGuide; dirName: string }[],
|
|
1778
|
+
selector: string,
|
|
1779
|
+
):
|
|
1780
|
+
| { ok: true; guide: ApiGuide; dirName: string }
|
|
1781
|
+
| { ok: false; reason: "no_match"; valid: string[] }
|
|
1782
|
+
| { ok: false; reason: "ambiguous"; directories: string[] } {
|
|
1783
|
+
const lc = selector.toLowerCase();
|
|
1784
|
+
const sel = matches.filter((m) => m.guide.shortName.toLowerCase() === lc);
|
|
1785
|
+
if (sel.length === 0) {
|
|
1786
|
+
return {
|
|
1787
|
+
ok: false,
|
|
1788
|
+
reason: "no_match",
|
|
1789
|
+
valid: matches.map((m) => m.guide.shortName),
|
|
1790
|
+
};
|
|
1791
|
+
}
|
|
1792
|
+
if (sel.length > 1) {
|
|
1793
|
+
return {
|
|
1794
|
+
ok: false,
|
|
1795
|
+
reason: "ambiguous",
|
|
1796
|
+
directories: sel.map((s) => s.dirName),
|
|
1797
|
+
};
|
|
1798
|
+
}
|
|
1799
|
+
return { ok: true, guide: sel[0]!.guide, dirName: sel[0]!.dirName };
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
/**
|
|
1803
|
+
* Render the no-match / ambiguous error text for a failed
|
|
1804
|
+
* `selectGuideByShortName` result. `callToAction` is the trailing
|
|
1805
|
+
* "how to see the menu" sentence — it differs per surface (tool vs
|
|
1806
|
+
* command), so callers pass their own.
|
|
1807
|
+
*/
|
|
1808
|
+
export function shortNameErrorText(
|
|
1809
|
+
sel: Extract<ReturnType<typeof selectGuideByShortName>, { ok: false }>,
|
|
1810
|
+
domain: string,
|
|
1811
|
+
selector: string,
|
|
1812
|
+
callToAction: string,
|
|
1813
|
+
): string {
|
|
1814
|
+
if (sel.reason === "no_match") {
|
|
1815
|
+
return (
|
|
1816
|
+
`No guide named '${selector}' for '${domain}'. ` +
|
|
1817
|
+
`Available guides: ${sel.valid.join(", ")}. ` +
|
|
1818
|
+
callToAction
|
|
1819
|
+
);
|
|
1820
|
+
}
|
|
1821
|
+
return (
|
|
1822
|
+
`Ambiguous guide '${selector}' for '${domain}' — ` +
|
|
1823
|
+
`${sel.directories.length} guides share shortName '${selector}' ` +
|
|
1824
|
+
`(directories: ${sel.directories.join(", ")}). Rename one guide's shortName to ` +
|
|
1825
|
+
`disambiguate. ` +
|
|
1826
|
+
callToAction
|
|
1827
|
+
);
|
|
1828
|
+
}
|
|
1829
|
+
|
|
1417
1830
|
// ════════════════════════════════════════════════════════════════════
|
|
1418
1831
|
// Catalog rendering — healthy + ⚠ malformed together
|
|
1419
1832
|
//
|
|
@@ -1425,7 +1838,10 @@ export function formatGuideListings(entries: { guide: ApiGuide }[]): string {
|
|
|
1425
1838
|
// here, where they'd bloat context for orgs with many guides.
|
|
1426
1839
|
// ════════════════════════════════════════════════════════════════════
|
|
1427
1840
|
|
|
1428
|
-
export function formatApiGuideCatalog(
|
|
1841
|
+
export function formatApiGuideCatalog(
|
|
1842
|
+
loaded: LoadedApiGuides,
|
|
1843
|
+
current: number = GUIDE_SCHEMA_VERSION,
|
|
1844
|
+
): string {
|
|
1429
1845
|
const lines: string[] = ["API guides:"];
|
|
1430
1846
|
|
|
1431
1847
|
// Org-grouped rows preserve first-appearance order; guides without
|
|
@@ -1454,7 +1870,14 @@ export function formatApiGuideCatalog(loaded: LoadedApiGuides): string {
|
|
|
1454
1870
|
}
|
|
1455
1871
|
const domList = domains.size > 0 ? [...domains].join(", ") : "—";
|
|
1456
1872
|
const n = row.guides.length;
|
|
1457
|
-
|
|
1873
|
+
// Collapsed org row: a trailing ⚠ glyph when ANY guide in it is stale
|
|
1874
|
+
// (hint only — the per-guide ⚠ line lives on the menu / detail view).
|
|
1875
|
+
const stale = row.guides.some((g) =>
|
|
1876
|
+
isStaleSchema(g.schemaVersion ?? 0, current),
|
|
1877
|
+
);
|
|
1878
|
+
lines.push(
|
|
1879
|
+
` 🏛️ ${row.org} — ${n} guide${n > 1 ? "s" : ""} (${domList})${stale ? " ⚠" : ""}`,
|
|
1880
|
+
);
|
|
1458
1881
|
}
|
|
1459
1882
|
for (const { name, guide } of orgless) {
|
|
1460
1883
|
const domains =
|
|
@@ -1462,6 +1885,8 @@ export function formatApiGuideCatalog(loaded: LoadedApiGuides): string {
|
|
|
1462
1885
|
lines.push(
|
|
1463
1886
|
` ${guide.icon} ${guide.shortName} — ${domains} (verified ${guide.verified}, ${guide.operations.length} ops)`,
|
|
1464
1887
|
);
|
|
1888
|
+
const stale = staleSchemaLine(guide, current);
|
|
1889
|
+
if (stale) lines.push(stale);
|
|
1465
1890
|
}
|
|
1466
1891
|
for (const mal of loaded.malformed) {
|
|
1467
1892
|
lines.push(
|
|
@@ -1469,7 +1894,9 @@ export function formatApiGuideCatalog(loaded: LoadedApiGuides): string {
|
|
|
1469
1894
|
);
|
|
1470
1895
|
}
|
|
1471
1896
|
if (Object.keys(loaded.guides).length === 0 && loaded.malformed.length === 0) {
|
|
1472
|
-
lines.push(
|
|
1897
|
+
lines.push(
|
|
1898
|
+
" (no guides — call api-learn({domain, recipeFile}) to author one)",
|
|
1899
|
+
);
|
|
1473
1900
|
}
|
|
1474
1901
|
lines.push("");
|
|
1475
1902
|
lines.push(
|