@matatbread/matbot-tool-types 0.4.7 → 0.4.13
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/package.json +5 -5
- package/src/build-dts.ts +171 -8
- package/src/checker.ts +58 -14
- package/src/index.ts +53 -4
- package/src/validator.ts +370 -0
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"matbotRuntime": [
|
|
4
4
|
"node"
|
|
5
5
|
],
|
|
6
|
-
"version": "0.4.
|
|
6
|
+
"version": "0.4.13",
|
|
7
7
|
"engines": {
|
|
8
8
|
"node": ">=24.0.0"
|
|
9
9
|
},
|
|
@@ -36,14 +36,14 @@
|
|
|
36
36
|
"typescript": "^6.0.3"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
|
-
"@matatbread/matbot-plugin-api": "^0.4.
|
|
40
|
-
"@matatbread/matbot-core": "^0.4.
|
|
39
|
+
"@matatbread/matbot-plugin-api": "^0.4.14",
|
|
40
|
+
"@matatbread/matbot-core": "^0.4.14"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@types/node": "^22.0.0",
|
|
44
44
|
"typescript": "^6.0.3",
|
|
45
|
-
"@matatbread/matbot-
|
|
46
|
-
"@matatbread/matbot-
|
|
45
|
+
"@matatbread/matbot-core": "^0.4.14",
|
|
46
|
+
"@matatbread/matbot-plugin-api": "^0.4.14"
|
|
47
47
|
},
|
|
48
48
|
"scripts": {
|
|
49
49
|
"typecheck": "tsc --noEmit"
|
package/src/build-dts.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type TS from 'typescript';
|
|
2
|
+
import { buildToolValidator, type ToolValidator } from './validator.js';
|
|
2
3
|
|
|
3
4
|
// Derive a self-contained `declare module … { interface ToolContracts {…} interface MatbotServices {…} }`
|
|
4
5
|
// from the live type graph, so a compiled (or hand-rolled) plugin's compilation sees correct types for
|
|
@@ -57,6 +58,12 @@ export interface MatbotToolsDts {
|
|
|
57
58
|
// (the arms) is thus also the source of the wire description, so a source tool's `ToolContracts`
|
|
58
59
|
// augmentation is its single contract.
|
|
59
60
|
contracts: Record<string, { params: string; result: string }>;
|
|
61
|
+
// Per source-scanned tool: a callable pure-JS validator for its params, emitted from the checker's
|
|
62
|
+
// RESOLVED type in this same pass — so conditionals/generics/`Omit` are already evaluated and no
|
|
63
|
+
// second `ts.Program` is ever built. A contract that cannot be honestly validated yields
|
|
64
|
+
// `{ refused }` rather than a permissive validator — and those refusals are the census of what the
|
|
65
|
+
// typed path does not cover. The emitted TEXT is not carried: `generateValidator` regenerates it.
|
|
66
|
+
validators: Record<string, ToolValidator>;
|
|
60
67
|
// The names of every plugin-api type export. A source-less tool's `toolContract` string may name one
|
|
61
68
|
// (e.g. `StoreQuery`); the consumer (ToolTypeIndex) uses this to import the ones it references so those
|
|
62
69
|
// references resolve rather than dangle.
|
|
@@ -83,8 +90,19 @@ type Classification =
|
|
|
83
90
|
// throws "not registered" at runtime, which is the one failure the check gate exists to prevent. Omit it
|
|
84
91
|
// only when the caller genuinely wants the whole scanned tree (the clash census test); the registry is not
|
|
85
92
|
// optional information for anything that shows the dts to a model.
|
|
93
|
+
// `syntheticContracts` maps a tool name to its `toolContract` STRING — the form a tool built at runtime
|
|
94
|
+
// must use, having no source to carry a `ToolContracts` augmentation (`function-tools`' generated
|
|
95
|
+
// functions, `tool-store`'s per-namespace tools). They are rendered into one virtual augmentation file
|
|
96
|
+
// added to THIS Program, so declaration merging puts them in the same `ToolContracts` as every scanned
|
|
97
|
+
// arm and the validator generator below reaches them with no second code path and no second Program.
|
|
98
|
+
//
|
|
99
|
+
// They are then held OUT of the emitted dts and out of `contracts`: the caller splices those verbatim
|
|
100
|
+
// from the same strings (`registryBlock`, `splitContract`), which is what the model already sees, and
|
|
101
|
+
// re-deriving that text from the resolved type would change it — expanding an alias the author wrote
|
|
102
|
+
// deliberately — for no gain. So this argument buys exactly one thing: the validators.
|
|
86
103
|
export async function buildMatbotToolsDts(
|
|
87
104
|
projectRoot: string, pluginEntryUrls?: readonly string[], liveToolNames?: readonly string[],
|
|
105
|
+
syntheticContracts?: Readonly<Record<string, string>>,
|
|
88
106
|
): Promise<MatbotToolsDts | null> {
|
|
89
107
|
const ts = (await import('typescript')).default as typeof TS;
|
|
90
108
|
const { readFileSync, readdirSync, statSync, existsSync } = await import('node:fs');
|
|
@@ -139,12 +157,17 @@ export async function buildMatbotToolsDts(
|
|
|
139
157
|
// because the name IS live.
|
|
140
158
|
// Generated `matbot-tools.d.ts` files are skipped (don't feed prior output back in).
|
|
141
159
|
if (existsSync(join(projectRoot, 'plugins'))) {
|
|
142
|
-
|
|
160
|
+
// Dot-directories wholesale rather than by name: this used to list `compiled-plugins` explicitly,
|
|
161
|
+
// which was both a second spelling of a constant skills_compiler owns (now settings-relocatable, so
|
|
162
|
+
// unknowable here) and unreachable — the walk roots at `plugins/`, and that build dir is its sibling.
|
|
163
|
+
// A source tree keeps no augmentations under a dot-directory; `.git`, `.plugins` and a build root
|
|
164
|
+
// sited there are all covered by one rule that cannot go stale.
|
|
165
|
+
const SKIP = new Set(['node_modules', 'dist']);
|
|
143
166
|
const walk = (dir: string): void => {
|
|
144
167
|
let entries: string[];
|
|
145
168
|
try { entries = readdirSync(dir); } catch { return; }
|
|
146
169
|
for (const name of entries) {
|
|
147
|
-
if (SKIP.has(name)) continue;
|
|
170
|
+
if (SKIP.has(name) || name.startsWith('.')) continue;
|
|
148
171
|
const p = join(dir, name);
|
|
149
172
|
let isDir: boolean;
|
|
150
173
|
try { isDir = statSync(p).isDirectory(); } catch { continue; }
|
|
@@ -164,7 +187,7 @@ export async function buildMatbotToolsDts(
|
|
|
164
187
|
}
|
|
165
188
|
if (roots.size === 1) return null; // nothing to scan beyond plugin-api itself
|
|
166
189
|
|
|
167
|
-
const
|
|
190
|
+
const options: TS.CompilerOptions = {
|
|
168
191
|
target: ts.ScriptTarget.ES2022,
|
|
169
192
|
module: ts.ModuleKind.NodeNext,
|
|
170
193
|
moduleResolution: ts.ModuleResolutionKind.NodeNext,
|
|
@@ -173,7 +196,8 @@ export async function buildMatbotToolsDts(
|
|
|
173
196
|
noEmit: true,
|
|
174
197
|
skipLibCheck: true,
|
|
175
198
|
baseUrl: projectRoot,
|
|
176
|
-
}
|
|
199
|
+
};
|
|
200
|
+
const program = ts.createProgram([...roots], options);
|
|
177
201
|
const checker = program.getTypeChecker();
|
|
178
202
|
|
|
179
203
|
const apiSf = program.getSourceFile(pluginApiIndex)
|
|
@@ -185,6 +209,125 @@ export async function buildMatbotToolsDts(
|
|
|
185
209
|
const TYPE_FLAGS = ts.SymbolFlags.Type | ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias;
|
|
186
210
|
const apiTypeNames = new Set(apiExports.filter(s => (s.flags & TYPE_FLAGS) !== 0).map(s => s.name));
|
|
187
211
|
|
|
212
|
+
/**
|
|
213
|
+
* Validators for the tools whose contract is a `toolContract` STRING. The emitter needs a `ts.Type`,
|
|
214
|
+
* and a string is not one, so the strings are rendered into a virtual augmentation file and typed.
|
|
215
|
+
*
|
|
216
|
+
* This is a SECOND, deliberately tiny Program — the virtual file plus plugin-api, no workspace scan —
|
|
217
|
+
* rather than an extra root on the one above, because the exact import list is only knowable once
|
|
218
|
+
* plugin-api's exports have been resolved by a checker, and that is the Program above. Guessing the
|
|
219
|
+
* list instead (rewrite every capitalised bare name to an inline `import(...)`) needs a denylist of
|
|
220
|
+
* TypeScript's own utility types, and the first thing it breaks is `Record<string, never>` — which is
|
|
221
|
+
* `NoParams`, the commonest synthetic params type there is. Exactness is worth the second Program;
|
|
222
|
+
* nothing is built at all when no synthetic tool is loaded.
|
|
223
|
+
*
|
|
224
|
+
* Only `paramNodes` is taken from here. The wire text and the dts arm are spliced from the same strings
|
|
225
|
+
* by the caller and are what the model already reads; re-deriving them from the resolved type would
|
|
226
|
+
* expand an alias the author wrote deliberately, for no gain.
|
|
227
|
+
*/
|
|
228
|
+
const syntheticValidators = (): Record<string, ToolValidator> => {
|
|
229
|
+
const out: Record<string, ToolValidator> = {};
|
|
230
|
+
const usable: Record<string, string> = {};
|
|
231
|
+
|
|
232
|
+
// Screened one at a time, BEFORE any is rendered into the shared file: they become properties of one
|
|
233
|
+
// interface, where a single stray brace would swallow every arm after it and take the whole batch
|
|
234
|
+
// down. A malformed string is a stated refusal rather than a silent absence — nothing else in the
|
|
235
|
+
// system parses these, so until now a broken one was merely bad documentation.
|
|
236
|
+
for (const [name, text] of Object.entries(syntheticContracts ?? {})) {
|
|
237
|
+
const probe = ts.createSourceFile('/probe.ts', `type __P = ${text};\n`, ts.ScriptTarget.ES2022, true);
|
|
238
|
+
const bad = (probe as unknown as { parseDiagnostics?: readonly TS.Diagnostic[] }).parseDiagnostics ?? [];
|
|
239
|
+
if (bad.length > 0) {
|
|
240
|
+
out[name] = { refused: `toolContract does not parse as a type: ${ts.flattenDiagnosticMessageText(bad[0]!.messageText, ' ')}` };
|
|
241
|
+
} else out[name] = (usable[name] = text, { refused: 'not resolved' }); // replaced below, or kept as the refusal
|
|
242
|
+
}
|
|
243
|
+
const names = Object.keys(usable);
|
|
244
|
+
if (names.length === 0) return out;
|
|
245
|
+
|
|
246
|
+
const body = names.map(n => ` ${JSON.stringify(n)}: ${usable[n]!};`).join('\n');
|
|
247
|
+
// Exactly the plugin-api types these arms name, from the resolved export set — the same rule
|
|
248
|
+
// `registryBlock` uses for the dts. A synthetic tool inlines its own shape types, so what is left is
|
|
249
|
+
// genuine plugin-api exports.
|
|
250
|
+
const referenced = ['ToolContract', ...[...apiTypeNames].filter(t => new RegExp(`\\b${t}\\b`).test(body))];
|
|
251
|
+
const src = `import type { ${[...new Set(referenced)].join(', ')} } from '@matatbread/matbot-plugin-api';\n`
|
|
252
|
+
+ `declare module '@matatbread/matbot-plugin-api' {\n interface ToolContracts {\n${body}\n }\n}\n`;
|
|
253
|
+
|
|
254
|
+
const virtualPath = join(projectRoot, '__matbot_synthetic_contracts__.ts');
|
|
255
|
+
const host = ts.createCompilerHost(options);
|
|
256
|
+
const innerGet = host.getSourceFile.bind(host);
|
|
257
|
+
const innerExists = host.fileExists.bind(host);
|
|
258
|
+
const innerRead = host.readFile.bind(host);
|
|
259
|
+
host.getSourceFile = (f, v, onError, create) =>
|
|
260
|
+
f === virtualPath ? ts.createSourceFile(f, src, v, true) : innerGet(f, v, onError, create);
|
|
261
|
+
host.fileExists = f => f === virtualPath || innerExists(f);
|
|
262
|
+
host.readFile = f => (f === virtualPath ? src : innerRead(f));
|
|
263
|
+
|
|
264
|
+
// Anchor the import by PATH, exactly as the checker worker does. Resolving it by name would depend on
|
|
265
|
+
// where `projectRoot` happens to sit relative to a `node_modules` holding plugin-api, and in a pnpm
|
|
266
|
+
// workspace the repo root does not hold one — whereupon the import silently yields `any`, the emitter
|
|
267
|
+
// reports "accepts anything" as a caveat, and the tool looks validated while its params are wide open.
|
|
268
|
+
const prog = ts.createProgram([virtualPath, pluginApiIndex], {
|
|
269
|
+
...options, paths: { '@matatbread/matbot-plugin-api': [pluginApiIndex] },
|
|
270
|
+
}, host);
|
|
271
|
+
const chk = prog.getTypeChecker();
|
|
272
|
+
const sf = prog.getSourceFile(virtualPath);
|
|
273
|
+
if (!sf) return out;
|
|
274
|
+
|
|
275
|
+
// The virtual file must typecheck. It is machine-generated from strings, so ANY diagnostic in it means
|
|
276
|
+
// a name did not resolve or an arm is malformed — and the consequence of continuing is not a wrong
|
|
277
|
+
// answer but a silent one: an unresolved reference is `any`, which validates everything. Refusing per
|
|
278
|
+
// tool keeps that visible and confines it, since `ts-validation` then defers to the `inputSchema`
|
|
279
|
+
// instead of claiming the type was enforced.
|
|
280
|
+
const broken = new Map<string, string>();
|
|
281
|
+
for (const d of [...prog.getSemanticDiagnostics(sf), ...prog.getSyntacticDiagnostics(sf)]) {
|
|
282
|
+
if (d.start === undefined) continue;
|
|
283
|
+
// Walk up from the diagnostic to the arm it sits inside; the property's name is the tool's.
|
|
284
|
+
let n: TS.Node | undefined = (function find(node: TS.Node): TS.Node | undefined {
|
|
285
|
+
if (d.start! < node.getStart() || d.start! >= node.getEnd()) return undefined;
|
|
286
|
+
for (const c of node.getChildren()) { const hit = find(c); if (hit) return hit; }
|
|
287
|
+
return ts.isPropertySignature(node) ? node : undefined;
|
|
288
|
+
})(sf);
|
|
289
|
+
const name = n !== undefined && ts.isPropertySignature(n)
|
|
290
|
+
? (ts.isStringLiteral(n.name) || ts.isIdentifier(n.name) ? n.name.text : undefined)
|
|
291
|
+
: undefined;
|
|
292
|
+
const msg = ts.flattenDiagnosticMessageText(d.messageText, ' ');
|
|
293
|
+
if (name !== undefined) broken.set(name, msg);
|
|
294
|
+
// A file-level diagnostic (a failed import) cannot be attributed to one arm, so it condemns them all.
|
|
295
|
+
else for (const k of names) broken.set(k, msg);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// Read the arms off the virtual file's own declarations rather than the merged ToolContracts symbol:
|
|
299
|
+
// this Program has no scanned arms to merge, and going via the file keeps each tool's node in hand.
|
|
300
|
+
const walk = (n: TS.Node): void => {
|
|
301
|
+
if (ts.isPropertySignature(n) && n.type !== undefined
|
|
302
|
+
&& (ts.isStringLiteral(n.name) || ts.isIdentifier(n.name))) {
|
|
303
|
+
const name = ts.isStringLiteral(n.name) ? n.name.text : n.name.text;
|
|
304
|
+
if (Object.hasOwn(usable, name)) {
|
|
305
|
+
const fault = broken.get(name);
|
|
306
|
+
if (fault !== undefined) {
|
|
307
|
+
out[name] = { refused: `toolContract does not typecheck: ${fault}` };
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
const ann = n.type;
|
|
311
|
+
const arms = ts.isUnionTypeNode(ann) ? [...ann.types] : [ann];
|
|
312
|
+
const paramNodes: TS.TypeNode[] = [];
|
|
313
|
+
let ok = true;
|
|
314
|
+
for (const a of arms) {
|
|
315
|
+
// A `toolContract` is by contract `ToolContract<R, A>` or a `|`-union of those, written
|
|
316
|
+
// literally — so there is no alias to resolve here, and anything else is not a contract.
|
|
317
|
+
if (!ts.isTypeReferenceNode(a) || a.typeName.getText() !== 'ToolContract' || a.typeArguments?.length !== 2) { ok = false; break; }
|
|
318
|
+
paramNodes.push(a.typeArguments[1]!);
|
|
319
|
+
}
|
|
320
|
+
out[name] = ok
|
|
321
|
+
? buildToolValidator(ts, chk, paramNodes.map(nd => chk.getTypeFromTypeNode(nd)), ann, { excessProperties: 'reject' })
|
|
322
|
+
: { refused: 'toolContract is not `ToolContract<Result, Args>` (or a union of those)' };
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
ts.forEachChild(n, walk);
|
|
326
|
+
};
|
|
327
|
+
walk(sf);
|
|
328
|
+
return out;
|
|
329
|
+
};
|
|
330
|
+
|
|
188
331
|
// Resolve an augmentable interface from its CANONICAL top-level declaration in plugin-api, not the
|
|
189
332
|
// index.ts re-export: `export * from './plugin.js'` (MatbotServices) exposes a stunted re-export view
|
|
190
333
|
// that drops cross-file augmentations; the canonical declaration's symbol carries the merged set.
|
|
@@ -555,19 +698,21 @@ export async function buildMatbotToolsDts(
|
|
|
555
698
|
return text;
|
|
556
699
|
};
|
|
557
700
|
|
|
558
|
-
const extractArms = (ann: TS.TypeNode): { params: string; result: string } | undefined => {
|
|
701
|
+
const extractArms = (ann: TS.TypeNode): { params: string; result: string; paramNodes: TS.TypeNode[] } | undefined => {
|
|
559
702
|
const resolved = resolveAlias(ann);
|
|
560
703
|
const arms = ts.isUnionTypeNode(resolved) ? [...resolved.types] : [resolved];
|
|
561
|
-
const params: string[] = [], results: string[] = [];
|
|
704
|
+
const params: string[] = [], results: string[] = [], paramNodes: TS.TypeNode[] = [];
|
|
562
705
|
for (const raw of arms) {
|
|
563
706
|
const a = resolveAlias(raw);
|
|
564
707
|
if (!ts.isTypeReferenceNode(a) || a.typeName.getText() !== 'ToolContract' || a.typeArguments?.length !== 2) return undefined;
|
|
565
708
|
results.push(expandNamed(a.typeArguments[0]!, new Set(), 0));
|
|
566
709
|
params.push(expandNamed(a.typeArguments[1]!, new Set(), 0));
|
|
710
|
+
paramNodes.push(a.typeArguments[1]!);
|
|
567
711
|
}
|
|
568
|
-
return { result: results.join(' | '), params: params.join(' | ') };
|
|
712
|
+
return { result: results.join(' | '), params: params.join(' | '), paramNodes };
|
|
569
713
|
};
|
|
570
714
|
const contracts: Record<string, { params: string; result: string }> = {};
|
|
715
|
+
const validators: Record<string, ToolValidator> = {};
|
|
571
716
|
const toolContractsSym = findCanonicalSymbol('ToolContracts');
|
|
572
717
|
if (toolContractsSym) {
|
|
573
718
|
for (const prop of checker.getPropertiesOfType(checker.getDeclaredTypeOfSymbol(toolContractsSym))) {
|
|
@@ -576,10 +721,27 @@ export async function buildMatbotToolsDts(
|
|
|
576
721
|
const ann = decl && ts.isPropertySignature(decl) ? decl.type : undefined;
|
|
577
722
|
if (!ann) continue;
|
|
578
723
|
const c = extractArms(ann);
|
|
579
|
-
if (c)
|
|
724
|
+
if (!c) continue;
|
|
725
|
+
contracts[prop.name] = { params: c.params, result: c.result };
|
|
726
|
+
// Excess properties are REJECTED, matching TypeScript's own treatment of a fresh object literal —
|
|
727
|
+
// which is exactly what a model-authored params object is. An invented or misspelled key otherwise
|
|
728
|
+
// fails silently: it is dropped, and the tool runs with a parameter the caller believes it passed
|
|
729
|
+
// (`sessionId` mis-sent as `session_id` reads as "no session given"). Rejecting turns the single
|
|
730
|
+
// most common tool-call hallucination into an error the model can repair. It also makes `NoParams`
|
|
731
|
+
// consistent rather than accidentally special: `Record<string, never>` already refuses every key,
|
|
732
|
+
// via its index signature's `never`, so without this a closed contract was the LOOSER of the two.
|
|
733
|
+
validators[prop.name] = buildToolValidator(
|
|
734
|
+
ts, checker, c.paramNodes.map(nd => checker.getTypeFromTypeNode(nd)), ann,
|
|
735
|
+
{ excessProperties: 'reject' },
|
|
736
|
+
);
|
|
580
737
|
}
|
|
581
738
|
}
|
|
582
739
|
|
|
740
|
+
// Source-declared arms WIN: a scanned augmentation is the tool's own compiled contract, whereas a
|
|
741
|
+
// `toolContract` string is a runtime assertion about it. They only collide if a plugin ships source
|
|
742
|
+
// for a tool it also registers dynamically, and then the compiler-checked one is the truth.
|
|
743
|
+
for (const [name, v] of Object.entries(syntheticValidators())) validators[name] ??= v;
|
|
744
|
+
|
|
583
745
|
const block = (name: string, lines: string[]): string =>
|
|
584
746
|
lines.length ? ` interface ${name} {\n${lines.join('\n')}\n }\n` : '';
|
|
585
747
|
const imports = [...importNames].filter(n => apiTypeNames.has(n)).sort();
|
|
@@ -595,6 +757,7 @@ ${block('ToolContracts', tools.lines)}${block('MatbotServices', services.lines)}
|
|
|
595
757
|
services: { emitted: services.emitted, unknown: services.unknown },
|
|
596
758
|
conflicts,
|
|
597
759
|
contracts,
|
|
760
|
+
validators,
|
|
598
761
|
apiExports: [...apiTypeNames],
|
|
599
762
|
};
|
|
600
763
|
}
|
package/src/checker.ts
CHANGED
|
@@ -9,6 +9,9 @@
|
|
|
9
9
|
// own virtual file, the same resolved typescript module), so a checker failure is a plumbing bug
|
|
10
10
|
// that must surface as the caller's error, not be absorbed by a quieter path.
|
|
11
11
|
|
|
12
|
+
import { renderToolCheckOmitted } from '@matatbread/matbot-plugin-api';
|
|
13
|
+
import type { ToolCheckDiagnostic, ToolCheckReport } from '@matatbread/matbot-plugin-api';
|
|
14
|
+
|
|
12
15
|
export interface CheckResult { ok: boolean; output: string }
|
|
13
16
|
|
|
14
17
|
interface DiagnosticRecord {
|
|
@@ -20,7 +23,7 @@ interface DiagnosticRecord {
|
|
|
20
23
|
frame?: string;
|
|
21
24
|
sourceLine?: string;
|
|
22
25
|
related?: string[];
|
|
23
|
-
/** True for a cast-gate finding (a structural rule, not a tsc error) —
|
|
26
|
+
/** True for a cast-gate finding (a structural rule, not a tsc error) — labelled CAST-GATE, not TSnnnn. */
|
|
24
27
|
syn?: boolean;
|
|
25
28
|
}
|
|
26
29
|
|
|
@@ -82,10 +85,16 @@ function hintFor(d: DiagnosticRecord): string | undefined {
|
|
|
82
85
|
|
|
83
86
|
const MAX_FULL = 8;
|
|
84
87
|
|
|
88
|
+
// One rule, one name, in every renderer: a per-rule label read off the record rather than spelled at
|
|
89
|
+
// each render site, so a summary can never call a finding something its own entry did not.
|
|
90
|
+
function label(d: DiagnosticRecord): string {
|
|
91
|
+
return d.syn ? 'CAST-GATE' : `TS${d.code}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
85
94
|
function formatOne(d: DiagnosticRecord): string {
|
|
86
95
|
const loc = d.file !== undefined ? `${d.file}(${d.line},${d.col})`
|
|
87
96
|
: d.line !== undefined ? `line ${d.line}` : '(project)';
|
|
88
|
-
const parts = [`${loc} ${d
|
|
97
|
+
const parts = [`${loc} ${label(d)}: ${d.message}`];
|
|
89
98
|
if (d.frame !== undefined) parts.push(d.frame);
|
|
90
99
|
if (d.related) for (const r of d.related) parts.push(` related: ${r}`);
|
|
91
100
|
const hint = hintFor(d);
|
|
@@ -93,10 +102,47 @@ function formatOne(d: DiagnosticRecord): string {
|
|
|
93
102
|
return parts.join('\n');
|
|
94
103
|
}
|
|
95
104
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
105
|
+
// The findings the cap hides, tallied by the same `label` the detailed ones carry.
|
|
106
|
+
function omittedOf(diags: DiagnosticRecord[]): { count: number; byLabel: Record<string, number> } | undefined {
|
|
107
|
+
const hidden = diags.slice(MAX_FULL);
|
|
108
|
+
if (hidden.length === 0) return undefined;
|
|
109
|
+
const byLabel: Record<string, number> = {};
|
|
110
|
+
for (const d of hidden) byLabel[label(d)] = (byLabel[label(d)] ?? 0) + 1;
|
|
111
|
+
return { count: hidden.length, byLabel };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The worker's records as the service's {@link ToolCheckReport}: structured findings, the cap expressed
|
|
116
|
+
* as `omitted` data, and each finding's annotated rendering carried on the record itself.
|
|
117
|
+
*
|
|
118
|
+
* The rendering used to be the WHOLE return value — one `string[]` of formatted blocks with the overflow
|
|
119
|
+
* summary appended as a further element. So `diagnostics.length` counted prose as a finding, and any
|
|
120
|
+
* per-code breakdown taken by iterating the array was unreliable wherever an overflow had occurred.
|
|
121
|
+
* The typed record existed upstream all along and was discarded at render time; it is kept now, and the
|
|
122
|
+
* text is one field of it.
|
|
123
|
+
*/
|
|
124
|
+
function reportOf(diags: DiagnosticRecord[]): ToolCheckReport {
|
|
125
|
+
const omitted = omittedOf(diags);
|
|
126
|
+
const detailed: ToolCheckDiagnostic[] = diags.slice(0, MAX_FULL).map(d => ({
|
|
127
|
+
label: label(d),
|
|
128
|
+
code: d.code,
|
|
129
|
+
message: d.message,
|
|
130
|
+
...(d.file !== undefined ? { file: d.file } : {}),
|
|
131
|
+
...(d.line !== undefined ? { line: d.line } : {}),
|
|
132
|
+
...(d.col !== undefined ? { col: d.col } : {}),
|
|
133
|
+
...(d.frame !== undefined ? { frame: d.frame } : {}),
|
|
134
|
+
...(d.related !== undefined ? { related: d.related } : {}),
|
|
135
|
+
...(hintFor(d) !== undefined ? { hint: hintFor(d)! } : {}),
|
|
136
|
+
...(d.syn === true ? { syn: true as const } : {}),
|
|
137
|
+
rendered: formatOne(d),
|
|
138
|
+
}));
|
|
139
|
+
return {
|
|
140
|
+
ok: diags.length === 0,
|
|
141
|
+
checked: true,
|
|
142
|
+
total: diags.length,
|
|
143
|
+
diagnostics: detailed,
|
|
144
|
+
...(omitted !== undefined ? { omitted } : {}),
|
|
145
|
+
};
|
|
100
146
|
}
|
|
101
147
|
|
|
102
148
|
async function runWorker(data: Record<string, unknown>): Promise<DiagnosticRecord[] | null> {
|
|
@@ -133,10 +179,11 @@ export async function checkProjectDir(
|
|
|
133
179
|
...(opts?.ownContracts !== undefined ? { ownContracts: [...opts.ownContracts] } : {}),
|
|
134
180
|
});
|
|
135
181
|
if (diags === null) return { ok: true, output: '' };
|
|
182
|
+
const report = reportOf(diags);
|
|
136
183
|
const parts: string[] = [];
|
|
137
|
-
if (
|
|
138
|
-
for (const d of
|
|
139
|
-
if (
|
|
184
|
+
if (report.total > 1) parts.push(`${report.total} errors. Fix the FIRST error first — later errors often cascade from it.\n`);
|
|
185
|
+
for (const d of report.diagnostics) { parts.push(d.rendered); parts.push(''); }
|
|
186
|
+
if (report.omitted !== undefined) parts.push(renderToolCheckOmitted(report.omitted));
|
|
140
187
|
return { ok: false, output: parts.join('\n').trim() };
|
|
141
188
|
}
|
|
142
189
|
|
|
@@ -149,7 +196,7 @@ export async function checkSnippetAgainst(opts: {
|
|
|
149
196
|
prefixLen: number;
|
|
150
197
|
prefixLines: number;
|
|
151
198
|
apiIndexPath?: string;
|
|
152
|
-
}): Promise<
|
|
199
|
+
}): Promise<ToolCheckReport> {
|
|
153
200
|
const diags = await runWorker({
|
|
154
201
|
mode: 'snippet',
|
|
155
202
|
root: opts.root,
|
|
@@ -159,10 +206,7 @@ export async function checkSnippetAgainst(opts: {
|
|
|
159
206
|
virtualPath: `${opts.root}/__mb_toolcheck_${crypto.randomUUID()}.ts`,
|
|
160
207
|
...(opts.apiIndexPath !== undefined ? { apiIndexPath: opts.apiIndexPath } : {}),
|
|
161
208
|
});
|
|
162
|
-
|
|
163
|
-
const out = diags.slice(0, MAX_FULL).map(formatOne);
|
|
164
|
-
if (diags.length > MAX_FULL) out.push(overflowNote(diags));
|
|
165
|
-
return out;
|
|
209
|
+
return reportOf(diags ?? []);
|
|
166
210
|
}
|
|
167
211
|
|
|
168
212
|
// The worker body: plain CommonJS (Worker eval mode is CJS, so `require` exists and no loader hooks
|
package/src/index.ts
CHANGED
|
@@ -2,13 +2,47 @@ import { dirname, join } from 'node:path';
|
|
|
2
2
|
import { existsSync } from 'node:fs';
|
|
3
3
|
import { createRequire } from 'node:module';
|
|
4
4
|
import { PLUGIN_API_VERSION, RegistryChangeKind } from '@matatbread/matbot-plugin-api';
|
|
5
|
-
import type { MatbotMachine, MatbotPluginSpec, ToolTypeIndex } from '@matatbread/matbot-plugin-api';
|
|
5
|
+
import type { MatbotMachine, MatbotPluginSpec, ToolCheckReport, ToolTypeIndex } from '@matatbread/matbot-plugin-api';
|
|
6
6
|
import { getRegisteredPlugins } from '@matatbread/matbot-core';
|
|
7
7
|
import { buildMatbotToolsDts } from './build-dts.js';
|
|
8
8
|
import { checkSnippetAgainst } from './checker.js';
|
|
9
|
+
import type { ToolValidator } from './validator.js';
|
|
9
10
|
|
|
10
11
|
export { buildMatbotToolsDts, type MatbotToolsDts } from './build-dts.js';
|
|
11
12
|
export { checkProjectDir, checkSnippetAgainst, type CheckResult } from './checker.js';
|
|
13
|
+
export {
|
|
14
|
+
generateValidator, buildToolValidator, compileValidator,
|
|
15
|
+
type ValidationError, type Validator, type ValidatorSource, type ToolValidator,
|
|
16
|
+
} from './validator.js';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* What tool-types SUPPLIES: the generated validator for each live tool, keyed by name. This package does
|
|
20
|
+
* type formation and analysis — it derives the dts, the wire contracts and the JSON Schemas from each
|
|
21
|
+
* tool's `ToolContract`, and emits a validator from the checker's resolved params type — but it is not
|
|
22
|
+
* itself a validator and registers no validator service. Enforcement is a consumer's:
|
|
23
|
+
* `@matatbread/matbot-tool-ts-validation` calls this, applies a policy, and registers the
|
|
24
|
+
* `ToolCallValidator` that core consults at the executor.
|
|
25
|
+
*
|
|
26
|
+
* That separation is the point. A code generator (`skills_compiler`, `function-tools`) loads this package
|
|
27
|
+
* for `dts()`/`check()` alone; if loading it also switched input enforcement on, adopting typed codegen
|
|
28
|
+
* would silently start rejecting tool calls.
|
|
29
|
+
*
|
|
30
|
+
* Reached by duck-typing `services.ToolTypeIndex` (the same structural check `asProfileDirectory` uses),
|
|
31
|
+
* so plugin-api's `ToolTypeIndex` need not learn about validation at all.
|
|
32
|
+
*/
|
|
33
|
+
export interface ToolValidatorSupplier {
|
|
34
|
+
/** Per live tool: its compiled params validator, or the stated reason none could be generated.
|
|
35
|
+
* Rebuilt with the dts and cached, so this costs nothing after the first call. */
|
|
36
|
+
toolValidators(): Promise<Record<string, ToolValidator>>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Structural recovery of the supplier from whatever is registered as `ToolTypeIndex` — method presence,
|
|
40
|
+
* never `instanceof`, so it survives hot reload and follows a swap. */
|
|
41
|
+
export function asToolValidatorSupplier(index: unknown): ToolValidatorSupplier | undefined {
|
|
42
|
+
return typeof (index as ToolValidatorSupplier | undefined)?.toolValidators === 'function'
|
|
43
|
+
? index as ToolValidatorSupplier
|
|
44
|
+
: undefined;
|
|
45
|
+
}
|
|
12
46
|
|
|
13
47
|
// Split a string on `sep` at bracket-depth 0 only (respecting `<> {} () []`), so a top-level `|` or `,`
|
|
14
48
|
// inside a nested type isn't mistaken for a separator.
|
|
@@ -109,6 +143,7 @@ class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
109
143
|
private covered = new Set<string>(); // tool names the source scan already declares (registry-block dedup)
|
|
110
144
|
private cache: string | null = null; // null ⇒ (re)build needed
|
|
111
145
|
private contracts: Record<string, { params: string; result: string }> = {}; // per-tool wire contract
|
|
146
|
+
private validators: Record<string, ToolValidator> = {}; // per-tool compiled validator
|
|
112
147
|
private apiExports: string[] = []; // plugin-api type export names (for importing those a toolContract names)
|
|
113
148
|
private dirty = true;
|
|
114
149
|
|
|
@@ -125,7 +160,7 @@ class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
125
160
|
if (this.dirty || this.cache === null) {
|
|
126
161
|
const root = this.machine.configPath !== undefined ? dirname(this.machine.configPath) : '.';
|
|
127
162
|
// Scan the source each loaded plugin was actually loaded from (its resolvedUrl) — builtin, compiled
|
|
128
|
-
// (compiled-plugins/), or installed (.plugins/) alike — so every registered tool's real augmentation
|
|
163
|
+
// (.compiled-plugins/), or installed (.plugins/) alike — so every registered tool's real augmentation
|
|
129
164
|
// is read. build-dts UNIONs a glob of the monorepo `plugins/` tree onto these roots (not a fallback:
|
|
130
165
|
// it catches host-constructed builtins that have no resolvedUrl), so the scanned set is a SUPERSET of
|
|
131
166
|
// the loaded one — wherever that tree exists, plugins for other runtimes and plugins nobody loaded are
|
|
@@ -135,10 +170,19 @@ class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
135
170
|
// registered" at runtime. What the scan CAN'T settle is two roots declaring one live name; that stays
|
|
136
171
|
// Program-order and audible via `conflicts`.
|
|
137
172
|
const urls = getRegisteredPlugins().map(p => p.resolvedUrl).filter((u): u is string => u !== undefined);
|
|
138
|
-
|
|
173
|
+
// A tool built at runtime declares its contract as a string, having no source to augment from. The
|
|
174
|
+
// scan cannot see those, so they are handed over to be typed from a virtual augmentation — without
|
|
175
|
+
// which they were described to the model in full and then enforced only by their loose
|
|
176
|
+
// `inputSchema`, which is backwards: their params were authored by an LLM, not a compiler.
|
|
177
|
+
const live = this.machine.tools.list();
|
|
178
|
+
const synthetic = Object.fromEntries(
|
|
179
|
+
live.flatMap(t => (t.toolContract !== undefined ? [[t.name, t.toolContract] as const] : [])),
|
|
180
|
+
);
|
|
181
|
+
const built = await buildMatbotToolsDts(root, urls, live.map(t => t.name), synthetic);
|
|
139
182
|
this.cache = built?.dts ?? '';
|
|
140
183
|
this.covered = new Set([...(built?.tools.emitted ?? []), ...(built?.tools.unknown ?? [])]);
|
|
141
184
|
this.contracts = built?.contracts ?? {};
|
|
185
|
+
this.validators = built?.validators ?? {};
|
|
142
186
|
this.apiExports = built?.apiExports ?? [];
|
|
143
187
|
this.dirty = false;
|
|
144
188
|
}
|
|
@@ -167,7 +211,7 @@ class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
167
211
|
return out;
|
|
168
212
|
}
|
|
169
213
|
|
|
170
|
-
async check(snippet: string): Promise<
|
|
214
|
+
async check(snippet: string): Promise<ToolCheckReport> {
|
|
171
215
|
const root = this.machine.configPath !== undefined ? dirname(this.machine.configPath) : '.';
|
|
172
216
|
const prefix = `${await this.dts()}\n`;
|
|
173
217
|
const source = `${prefix}${snippet}\nexport {};\n`; // trailing export ⇒ this file is a module
|
|
@@ -224,6 +268,11 @@ class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
224
268
|
: '';
|
|
225
269
|
return `${head}${derived}\ndeclare module '@matatbread/matbot-plugin-api' {\n interface ToolContracts {\n${body}\n }\n}\n`;
|
|
226
270
|
}
|
|
271
|
+
|
|
272
|
+
async toolValidators(): Promise<Record<string, ToolValidator>> {
|
|
273
|
+
await this.ensureBuilt();
|
|
274
|
+
return this.validators;
|
|
275
|
+
}
|
|
227
276
|
}
|
|
228
277
|
|
|
229
278
|
export function createToolTypesPlugin(): MatbotPluginSpec {
|
package/src/validator.ts
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
import type TS from 'typescript';
|
|
2
|
+
|
|
3
|
+
// Emits a pure-JS validator for a tool's params type, from the CHECKER'S RESOLVED TYPE rather than
|
|
4
|
+
// from syntax. That distinction is the whole reason this is ~200 lines: conditionals, mapped types,
|
|
5
|
+
// generic instantiations, `Omit`/`Pick`/`Record`/`keyof` and indexed access all arrive already
|
|
6
|
+
// evaluated, so none of them is implemented here. Nothing in this file knows they exist.
|
|
7
|
+
//
|
|
8
|
+
// The target is the JSON PROJECTION of the type — what `JSON.stringify` actually puts on the wire —
|
|
9
|
+
// not the type as written. So a `Date` is validated as the string its `toJSON` returns; a class
|
|
10
|
+
// instance as its own enumerable data properties (methods live on the prototype and are dropped); a
|
|
11
|
+
// method or function-valued property as absent, because a payload can never carry one. The only
|
|
12
|
+
// refusal left is `bigint`, and it is refused because `JSON.stringify` itself throws on it.
|
|
13
|
+
//
|
|
14
|
+
// Refusals are DATA, never a throw at the seam: a contract this cannot honestly validate yields
|
|
15
|
+
// `{ refused }`, so the caller reports "no opinion" instead of a validator that silently passes.
|
|
16
|
+
|
|
17
|
+
export interface ValidationError {
|
|
18
|
+
/** JSON Pointer into the value (`/where/0/op`); `/` for the root. */
|
|
19
|
+
path: string;
|
|
20
|
+
message: string;
|
|
21
|
+
value?: unknown;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type Validator = (value: unknown) => ValidationError[];
|
|
25
|
+
|
|
26
|
+
/** A generated validator's source, or the reason none could be generated. */
|
|
27
|
+
export type ValidatorSource =
|
|
28
|
+
| { src: string; warnings: string[] }
|
|
29
|
+
| { refused: string };
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* What a consumer wants: the callable validator, plus what it does NOT constrain.
|
|
33
|
+
*
|
|
34
|
+
* The emitted source is deliberately not handed out. Anyone who wants the text calls
|
|
35
|
+
* {@link generateValidator}, which is the same generation this went through — so carrying a copy on
|
|
36
|
+
* every entry would be a second way to obtain one thing. (Note `validate.toString()` is NOT that copy:
|
|
37
|
+
* the helper functions live in the enclosing scope of `new Function`, so it recovers only the entry
|
|
38
|
+
* stub, never the logic.)
|
|
39
|
+
*
|
|
40
|
+
* Compiling eagerly rather than lazily is deliberate: `new Function` compiles in the GLOBAL scope, so
|
|
41
|
+
* the validator captures nothing — not the checker, not a `ts.Type`, not this module's locals — and the
|
|
42
|
+
* `ts.Program` is collectable the moment the build returns either way. There is nothing to defer.
|
|
43
|
+
*/
|
|
44
|
+
export type ToolValidator =
|
|
45
|
+
| { validate: Validator; warnings: string[] }
|
|
46
|
+
| { refused: string };
|
|
47
|
+
|
|
48
|
+
/** Generate and compile in one step — {@link generateValidator} followed by {@link compileValidator}. */
|
|
49
|
+
export function buildToolValidator(
|
|
50
|
+
ts: typeof TS, checker: TS.TypeChecker, root: TS.Type | readonly TS.Type[], location: TS.Node,
|
|
51
|
+
opts: { excessProperties?: 'allow' | 'reject' } = {},
|
|
52
|
+
): ToolValidator {
|
|
53
|
+
const out = generateValidator(ts, checker, root, location, opts);
|
|
54
|
+
if ('refused' in out) return out;
|
|
55
|
+
return { validate: compileValidator(out.src), warnings: out.warnings };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
class Unsupported extends Error {
|
|
59
|
+
readonly label: string;
|
|
60
|
+
constructor(where: string, label: string) { super(`${where || '<root>'}: ${label}`); this.label = label; }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const PROTO_KEYS = new Set(Object.getOwnPropertyNames(Object.prototype));
|
|
64
|
+
|
|
65
|
+
// Instances of these stringify to `{}` — all state sits behind prototype accessors or internal slots,
|
|
66
|
+
// so nothing reaches the wire. Validated as "some object", with a data-loss warning: the contract is
|
|
67
|
+
// expressible but says less than its author believes.
|
|
68
|
+
const EMPTY_JSON = new Set([
|
|
69
|
+
'Map', 'Set', 'WeakMap', 'WeakSet', 'WeakRef', 'RegExp', 'Promise',
|
|
70
|
+
'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError',
|
|
71
|
+
]);
|
|
72
|
+
|
|
73
|
+
interface Check { expr: string; msg: string; reports: boolean }
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* `root` is either a single type, or the ARM LIST of a multi-action tool — one params type per
|
|
77
|
+
* `ToolContract` arm. They arrive separately (each is its own type argument) and TypeScript exposes no
|
|
78
|
+
* way to construct a union type, so the list is unioned here instead, which also means a multi-action
|
|
79
|
+
* tool gets ONE validator that dispatches on its discriminant.
|
|
80
|
+
*/
|
|
81
|
+
export function generateValidator(
|
|
82
|
+
ts: typeof TS, checker: TS.TypeChecker, root: TS.Type | readonly TS.Type[], location: TS.Node,
|
|
83
|
+
opts: { excessProperties?: 'allow' | 'reject' } = {},
|
|
84
|
+
): ValidatorSource {
|
|
85
|
+
const F = ts.TypeFlags;
|
|
86
|
+
const reject = opts.excessProperties === 'reject';
|
|
87
|
+
const fns = new Map<TS.Type, string>();
|
|
88
|
+
const bodies: (string | null)[] = [];
|
|
89
|
+
const warnings: string[] = [];
|
|
90
|
+
let n = 0;
|
|
91
|
+
|
|
92
|
+
const lit = (v: unknown): string => JSON.stringify(v);
|
|
93
|
+
const access = (v: string, k: string): string => /^[A-Za-z_$][\w$]*$/.test(k) ? `${v}.${k}` : `${v}[${lit(k)}]`;
|
|
94
|
+
// Reported paths read as the ACCESS a caller would write — `.items[0].name`, not `/items/0/name` —
|
|
95
|
+
// because the reader is a model repairing its own call, or a developer looking at a 422. Same rule as
|
|
96
|
+
// `access` above, so a key needing brackets in code gets them in the diagnostic too.
|
|
97
|
+
const propPath = (k: string): string => /^[A-Za-z_$][\w$]*$/.test(k) ? `.${k}` : `[${lit(k)}]`;
|
|
98
|
+
const typeOfProp = (s: TS.Symbol): TS.Type =>
|
|
99
|
+
checker.getTypeOfSymbolAtLocation(s, s.valueDeclaration ?? location);
|
|
100
|
+
|
|
101
|
+
function guard(t: TS.Type, where: string): void {
|
|
102
|
+
if (t.getCallSignatures().length) throw new Unsupported(where, 'function type (not JSON-serializable)');
|
|
103
|
+
// `JSON.stringify({ n: 1n })` throws `TypeError: Do not know how to serialize a BigInt`, so the
|
|
104
|
+
// generator refusing here mirrors what the runtime would do anyway.
|
|
105
|
+
if (t.flags & (F.BigInt | F.BigIntLiteral)) throw new Unsupported(where, 'bigint (JSON.stringify throws on it)');
|
|
106
|
+
if (t.flags & (F.ESSymbol | F.UniqueESSymbol)) throw new Unsupported(where, 'symbol (not JSON-serializable)');
|
|
107
|
+
// `string & { __brand }`. Without this it reaches the object walker, which refuses it only by
|
|
108
|
+
// accident (a `string` carries a numeric index signature) and reports a misleading reason.
|
|
109
|
+
const PRIM = F.String | F.Number | F.Boolean | F.StringLiteral | F.NumberLiteral | F.BooleanLiteral | F.BigInt | F.ESSymbol;
|
|
110
|
+
if (t.isIntersection() && t.types.some(m => m.flags & PRIM)) {
|
|
111
|
+
throw new Unsupported(where, 'intersection with a primitive (a brand is not checkable at runtime)');
|
|
112
|
+
}
|
|
113
|
+
if (t.flags & F.TypeParameter) throw new Unsupported(where, 'unresolved type parameter');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// `toJSON()` wins outright: a Date is a string on the wire, not an object with no fields. Applies to
|
|
117
|
+
// any type declaring one, so a hand-written `toJSON(): { v, ccy }` is handled without a special case.
|
|
118
|
+
function viaToJSON(t: TS.Type): TS.Type | undefined {
|
|
119
|
+
if (!(t.flags & F.Object)) return undefined;
|
|
120
|
+
const tj = checker.getPropertyOfType(t, 'toJSON');
|
|
121
|
+
if (!tj) return undefined;
|
|
122
|
+
const sigs = typeOfProp(tj).getCallSignatures();
|
|
123
|
+
const first = sigs[0];
|
|
124
|
+
if (!first) return undefined;
|
|
125
|
+
const ret = checker.getReturnTypeOfSignature(first);
|
|
126
|
+
return ret === t ? undefined : ret;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Properties `JSON.stringify` never emits, so a payload cannot carry them and a validator must not
|
|
130
|
+
// require them: methods, accessors (non-enumerable on a prototype), and any property whose value is
|
|
131
|
+
// a function, undefined or a symbol.
|
|
132
|
+
function isDropped(s: TS.Symbol, pt: TS.Type): boolean {
|
|
133
|
+
const d = s.valueDeclaration ?? s.declarations?.[0];
|
|
134
|
+
if (d && (ts.isMethodDeclaration(d) || ts.isMethodSignature(d) || ts.isGetAccessor(d) || ts.isSetAccessor(d))) return true;
|
|
135
|
+
if (pt.getCallSignatures().length) return true;
|
|
136
|
+
return (pt.flags & (F.Undefined | F.Void | F.ESSymbol | F.UniqueESSymbol)) !== 0;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function templateRegex(t: TS.TemplateLiteralType, where: string): string {
|
|
140
|
+
const esc = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
141
|
+
let src = '^';
|
|
142
|
+
for (let i = 0; i < t.texts.length; i++) {
|
|
143
|
+
src += esc(t.texts[i] ?? '');
|
|
144
|
+
const inner = t.types[i];
|
|
145
|
+
if (!inner) continue;
|
|
146
|
+
if (inner.flags & F.String) src += '[\\s\\S]*';
|
|
147
|
+
else if (inner.flags & F.Number) src += '-?\\d+(?:\\.\\d+)?';
|
|
148
|
+
else if (inner.isStringLiteral()) src += esc(inner.value);
|
|
149
|
+
else throw new Unsupported(where, 'template literal with an unsupported placeholder');
|
|
150
|
+
}
|
|
151
|
+
return `${src}$`;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function check(t: TS.Type, v: string, p: string, where: string): Check {
|
|
155
|
+
const projected = viaToJSON(t);
|
|
156
|
+
if (projected) return check(projected, v, p, `${where} (via toJSON)`);
|
|
157
|
+
|
|
158
|
+
const sname = t.symbol?.name;
|
|
159
|
+
if (sname !== undefined && EMPTY_JSON.has(sname) && !checker.isArrayType(t)) {
|
|
160
|
+
warnings.push(`${where || '<root>'}: ${sname} stringifies to {} — no state reaches the wire`);
|
|
161
|
+
return { expr: `(typeof ${v} === 'object' && ${v} !== null && !Array.isArray(${v}))`, msg: `expected object (${sname} carries no JSON state)`, reports: false };
|
|
162
|
+
}
|
|
163
|
+
guard(t, where);
|
|
164
|
+
|
|
165
|
+
if (t.flags & (F.Any | F.Unknown)) {
|
|
166
|
+
warnings.push(`${where || '<root>'}: ${t.flags & F.Any ? 'any' : 'unknown'} — accepts anything`);
|
|
167
|
+
return { expr: 'true', msg: '', reports: false };
|
|
168
|
+
}
|
|
169
|
+
if (t.flags & F.Never) return { expr: 'false', msg: 'never (no value is valid)', reports: false };
|
|
170
|
+
// The bare `object` type — `NonPrimitive`, not `Object`. It says only "not a primitive", so an
|
|
171
|
+
// array satisfies it too. Warned about rather than refused: it is a real (if loose) contract, and
|
|
172
|
+
// refusing would report a whole tool as unvalidatable over one deliberately-open field.
|
|
173
|
+
if (t.flags & F.NonPrimitive) {
|
|
174
|
+
warnings.push(`${where || '<root>'}: bare \`object\` — accepts any non-primitive`);
|
|
175
|
+
return { expr: `(typeof ${v} === 'object' && ${v} !== null)`, msg: 'expected object', reports: false };
|
|
176
|
+
}
|
|
177
|
+
if (t.flags & F.Null) return { expr: `${v} === null`, msg: 'expected null', reports: false };
|
|
178
|
+
if (t.flags & (F.Undefined | F.Void)) return { expr: `${v} === undefined`, msg: 'expected undefined', reports: false };
|
|
179
|
+
if (t.isStringLiteral()) return { expr: `${v} === ${lit(t.value)}`, msg: `expected ${lit(t.value)}`, reports: false };
|
|
180
|
+
if (t.isNumberLiteral()) return { expr: `${v} === ${t.value}`, msg: `expected ${t.value}`, reports: false };
|
|
181
|
+
if (t.flags & F.BooleanLiteral) {
|
|
182
|
+
const b = checker.typeToString(t) === 'true';
|
|
183
|
+
return { expr: `${v} === ${b}`, msg: `expected ${b}`, reports: false };
|
|
184
|
+
}
|
|
185
|
+
if (t.flags & F.String) return { expr: `typeof ${v} === 'string'`, msg: 'expected string', reports: false };
|
|
186
|
+
// JSON carries neither NaN nor Infinity, so `Number.isFinite` is the honest check.
|
|
187
|
+
if (t.flags & F.Number) return { expr: `Number.isFinite(${v})`, msg: 'expected number', reports: false };
|
|
188
|
+
if (t.flags & F.Boolean) return { expr: `typeof ${v} === 'boolean'`, msg: 'expected boolean', reports: false };
|
|
189
|
+
if (t.flags & F.TemplateLiteral) {
|
|
190
|
+
const re = templateRegex(t as TS.TemplateLiteralType, where);
|
|
191
|
+
return { expr: `(typeof ${v} === 'string' && /${re}/.test(${v}))`, msg: `expected string matching /${re}/`, reports: false };
|
|
192
|
+
}
|
|
193
|
+
return { expr: `${fnFor(t, where)}(${v}, ${p}, e)`, msg: '', reports: true };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function member(t: TS.Type, v: string, p: string, where: string, ind: string): string {
|
|
197
|
+
const c = check(t, v, p, where);
|
|
198
|
+
if (c.expr === 'true') return `${ind}/* ${where}: unconstrained */`;
|
|
199
|
+
return c.reports
|
|
200
|
+
? `${ind}if (!(${c.expr})) ok = false;`
|
|
201
|
+
: `${ind}if (!(${c.expr})) { E(${p}, ${lit(c.msg)}, ${v}, e); ok = false; }`;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// A property present in every arm with a distinct literal type: lets the union dispatch instead of
|
|
205
|
+
// guess, so a failure is reported against the arm the caller MEANT rather than as "nothing matched".
|
|
206
|
+
function discriminantOf(arms: readonly TS.Type[]): { name: string; vals: (string | number)[] } | undefined {
|
|
207
|
+
// "object-like" must include Intersection, or a single `{ action: 'x' } & Omit<…>` arm defeats
|
|
208
|
+
// discriminant dispatch for the WHOLE tool and every failure degrades to "no union member
|
|
209
|
+
// matched" — which is exactly the error quality this dispatch exists to avoid.
|
|
210
|
+
const objectLike = F.Object | F.Intersection;
|
|
211
|
+
const first = arms[0];
|
|
212
|
+
if (!first || !arms.every(a => a.flags & objectLike)) return undefined;
|
|
213
|
+
for (const s0 of checker.getPropertiesOfType(first)) {
|
|
214
|
+
const vals: (string | number)[] = [];
|
|
215
|
+
let good = true;
|
|
216
|
+
for (const arm of arms) {
|
|
217
|
+
const s = checker.getPropertyOfType(arm, s0.name);
|
|
218
|
+
if (!s || (s.flags & ts.SymbolFlags.Optional)) { good = false; break; }
|
|
219
|
+
const pt = typeOfProp(s);
|
|
220
|
+
if (pt.isStringLiteral() || pt.isNumberLiteral()) vals.push(pt.value);
|
|
221
|
+
else { good = false; break; }
|
|
222
|
+
}
|
|
223
|
+
if (good && new Set(vals).size === arms.length) return { name: s0.name, vals };
|
|
224
|
+
}
|
|
225
|
+
return undefined;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function fnFor(t: TS.Type, where: string): string {
|
|
229
|
+
const seen = fns.get(t);
|
|
230
|
+
if (seen !== undefined) return seen;
|
|
231
|
+
const name = `T${n++}`;
|
|
232
|
+
fns.set(t, name); // BEFORE the body: this is what makes recursion terminate
|
|
233
|
+
bodies.push(null);
|
|
234
|
+
const slot = bodies.length - 1;
|
|
235
|
+
bodies[slot] = `function ${name}(v, p, e) {\n${bodyOf(t, where)}\n}`;
|
|
236
|
+
return name;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const OBJ_GUARD = ` if (typeof v !== 'object' || v === null || Array.isArray(v)) { E(p, 'expected object', v, e); return false; }\n`;
|
|
240
|
+
|
|
241
|
+
// Shared by a real union type and by a multi-action tool's arm LIST (which is a union in the
|
|
242
|
+
// contract but reaches us as separate `ToolContract` type arguments, with no API to union them).
|
|
243
|
+
function unionBody(arms: readonly TS.Type[], where: string): string {
|
|
244
|
+
const disc = discriminantOf(arms);
|
|
245
|
+
if (disc) {
|
|
246
|
+
const cases = arms.map((a, i) => ` case ${lit(disc.vals[i])}: return ${fnFor(a, `${where}(${lit(disc.vals[i])})`)}(v, p, e);`).join('\n');
|
|
247
|
+
return `${OBJ_GUARD} switch (${access('v', disc.name)}) {\n${cases}\n`
|
|
248
|
+
+ ` default: E(p + ${lit(propPath(disc.name))}, 'expected one of ${disc.vals.map(lit).join(', ')}', ${access('v', disc.name)}, e); return false;\n }`;
|
|
249
|
+
}
|
|
250
|
+
// No discriminant: try each arm against a scratch buffer so a failed arm's errors don't leak.
|
|
251
|
+
const attempts = arms.map((a, i) => {
|
|
252
|
+
const c = check(a, 'v', 'p', `${where}|${i}`);
|
|
253
|
+
return ` if (${c.reports ? c.expr.replace(/, e\)$/, ', scratch)') : c.expr}) return true;`;
|
|
254
|
+
}).join('\n');
|
|
255
|
+
return ` const scratch = [];\n${attempts}\n E(p, 'no union member matched', v, e);\n return false;`;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function bodyOf(t: TS.Type, where: string): string {
|
|
259
|
+
if (t.isUnion()) return unionBody(t.types, where);
|
|
260
|
+
// An intersection carries `Intersection`, NOT `Object`, so it needs its own arm or it falls
|
|
261
|
+
// through to the throw below — and `{ action: 'query' } & Omit<StoreQuery, 'immutable'>` is the
|
|
262
|
+
// commonest real shape in this repo. `getPropertiesOfType` already merges the members.
|
|
263
|
+
if (t.isIntersection()) return objectBody(t, where);
|
|
264
|
+
if (checker.isArrayType(t)) {
|
|
265
|
+
const el = checker.getTypeArguments(t as TS.TypeReference)[0];
|
|
266
|
+
if (!el) throw new Unsupported(where, 'array with no element type');
|
|
267
|
+
const c = check(el, 'x', `p + '[' + i + ']'`, `${where}[]`);
|
|
268
|
+
const inner = c.expr === 'true' ? ''
|
|
269
|
+
: c.reports ? ` if (!(${c.expr})) ok = false;\n`
|
|
270
|
+
: ` if (!(${c.expr})) { E(p + '[' + i + ']', ${lit(c.msg)}, x, e); ok = false; }\n`;
|
|
271
|
+
return ` if (!Array.isArray(v)) { E(p, 'expected array', v, e); return false; }\n let ok = true;\n`
|
|
272
|
+
+ ` for (let i = 0; i < v.length; i++) { const x = v[i];\n${inner} }\n return ok;`;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (checker.isTupleType(t)) {
|
|
276
|
+
const els = checker.getTypeArguments(t as TS.TypeReference);
|
|
277
|
+
const flags = (t as TS.TupleTypeReference).target.elementFlags;
|
|
278
|
+
if (flags.some(f => f & ts.ElementFlags.Rest)) throw new Unsupported(where, 'rest element in a tuple');
|
|
279
|
+
const min = els.filter((_, i) => (flags[i] ?? ts.ElementFlags.Required) & ts.ElementFlags.Required).length;
|
|
280
|
+
const lines = els.map((el, i) => {
|
|
281
|
+
const c = check(el, `v[${i}]`, `p + '[${i}]'`, `${where}[${i}]`);
|
|
282
|
+
const one = c.reports ? `if (!(${c.expr})) ok = false;` : `if (!(${c.expr})) { E(p + '[${i}]', ${lit(c.msg)}, v[${i}], e); ok = false; }`;
|
|
283
|
+
return ((flags[i] ?? 0) & ts.ElementFlags.Optional) ? ` if (v.length > ${i}) { ${one} }` : ` ${one}`;
|
|
284
|
+
}).join('\n');
|
|
285
|
+
const span = min === els.length ? `${els.length}` : `${min}..${els.length}`;
|
|
286
|
+
return ` if (!Array.isArray(v)) { E(p, 'expected array', v, e); return false; }\n`
|
|
287
|
+
+ ` if (v.length < ${min} || v.length > ${els.length}) { E(p, 'expected ${span} elements', v.length, e); return false; }\n`
|
|
288
|
+
+ ` let ok = true;\n${lines}\n return ok;`;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (t.flags & F.Object) return objectBody(t, where);
|
|
292
|
+
throw new Unsupported(where, `unhandled type ${checker.typeToString(t)}`);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function objectBody(t: TS.Type, where: string): string {
|
|
296
|
+
const props = checker.getPropertiesOfType(t);
|
|
297
|
+
const strIdx = checker.getIndexInfoOfType(t, ts.IndexKind.String);
|
|
298
|
+
const numIdx = checker.getIndexInfoOfType(t, ts.IndexKind.Number);
|
|
299
|
+
if (numIdx && !strIdx) throw new Unsupported(where, 'numeric index signature');
|
|
300
|
+
// `known` keeps every declared name, so strict mode never flags a DROPPED one as excess; only the
|
|
301
|
+
// data properties are actually validated.
|
|
302
|
+
const known = props.map(s => s.name);
|
|
303
|
+
let out = `${OBJ_GUARD} let ok = true;\n`;
|
|
304
|
+
|
|
305
|
+
for (const s of props) {
|
|
306
|
+
const pt = typeOfProp(s);
|
|
307
|
+
if (isDropped(s, pt)) continue;
|
|
308
|
+
const acc = access('v', s.name);
|
|
309
|
+
const path = `p + ${lit(propPath(s.name))}`;
|
|
310
|
+
const body = member(pt, acc, path, `${where}.${s.name}`, ' ');
|
|
311
|
+
// `in` walks the prototype chain, so a key shadowed by `Object.prototype` (`__proto__`,
|
|
312
|
+
// `toString`, `constructor`) reads as present on EVERY object — which misdiagnoses a missing key
|
|
313
|
+
// and, where the member type is unconstrained, accepts an object that lacks it. `Object.hasOwn`
|
|
314
|
+
// is correct but ~3x slower, so it is reserved for the keys that need it: `JSON.parse` can never
|
|
315
|
+
// produce an `undefined` VALUE, so for every other key `!== undefined` is an exact own-presence
|
|
316
|
+
// test on a JSON payload.
|
|
317
|
+
const needsHasOwn = PROTO_KEYS.has(s.name) || (pt.flags & F.Undefined) !== 0
|
|
318
|
+
|| (pt.isUnion() && pt.types.some(m => m.flags & F.Undefined));
|
|
319
|
+
const present = needsHasOwn ? `Object.hasOwn(v, ${lit(s.name)})` : `${acc} !== undefined`;
|
|
320
|
+
out += (s.flags & ts.SymbolFlags.Optional)
|
|
321
|
+
? ` if (${present}${needsHasOwn ? ` && ${acc} !== undefined` : ''}) {\n${body}\n }\n`
|
|
322
|
+
: ` if (!(${present})) { E(${path}, 'required property missing', undefined, e); ok = false; }\n else {\n${body}\n }\n`;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
if (strIdx) {
|
|
326
|
+
const c = check(strIdx.type, 'x', `K(p, k)`, `${where}[string]`);
|
|
327
|
+
const skip = known.length ? `if (${lit(known)}.includes(k)) continue;\n ` : '';
|
|
328
|
+
const inner = c.expr === 'true' ? ''
|
|
329
|
+
: c.reports ? ` if (!(${c.expr})) ok = false;\n`
|
|
330
|
+
: ` if (!(${c.expr})) { E(K(p, k), ${lit(c.msg)}, x, e); ok = false; }\n`;
|
|
331
|
+
out += ` for (const k of Object.keys(v)) { ${skip}const x = v[k];\n${inner} }\n`;
|
|
332
|
+
} else if (reject && known.length) {
|
|
333
|
+
out += ` for (const k of Object.keys(v)) if (!${lit(known)}.includes(k)) { E(K(p, k), 'unexpected property', v[k], e); ok = false; }\n`;
|
|
334
|
+
}
|
|
335
|
+
return `${out} return ok;`;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
try {
|
|
339
|
+
const arms = Array.isArray(root) ? root as readonly TS.Type[] : undefined;
|
|
340
|
+
const single = arms === undefined ? root as TS.Type : arms.length === 1 ? arms[0] : undefined;
|
|
341
|
+
if (arms !== undefined && arms.length === 0) return { refused: 'contract declares no arms' };
|
|
342
|
+
|
|
343
|
+
let rootCheck: Check;
|
|
344
|
+
if (single !== undefined) {
|
|
345
|
+
rootCheck = check(single, 'value', `''`, '');
|
|
346
|
+
} else {
|
|
347
|
+
const name = `T${n++}`;
|
|
348
|
+
bodies.push(null);
|
|
349
|
+
const slot = bodies.length - 1;
|
|
350
|
+
bodies[slot] = `function ${name}(v, p, e) {\n${unionBody(arms!, '')}\n}`;
|
|
351
|
+
rootCheck = { expr: `${name}(value, '', e)`, msg: '', reports: true };
|
|
352
|
+
}
|
|
353
|
+
const entry = rootCheck.reports
|
|
354
|
+
? ` const e = []; ${rootCheck.expr}; return e;`
|
|
355
|
+
: ` const e = []; if (!(${rootCheck.expr})) E('', ${lit(rootCheck.msg)}, value, e); return e;`;
|
|
356
|
+
const src = `'use strict';\nconst E = (p, m, v, e) => e.push({ path: p || '.', message: m, value: v });\n`
|
|
357
|
+
+ `const K = (p, k) => p + (/^[A-Za-z_$][\\w$]*$/.test(k) ? '.' + k : '[' + JSON.stringify(k) + ']');\n`
|
|
358
|
+
+ `${bodies.join('\n')}\nreturn function validate(value) {\n${entry}\n};`;
|
|
359
|
+
return { src, warnings };
|
|
360
|
+
} catch (err) {
|
|
361
|
+
if (err instanceof Unsupported) return { refused: err.message };
|
|
362
|
+
throw err;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** Instantiate a generated validator. The source is emitted by {@link generateValidator} from a type
|
|
367
|
+
* in this process — never from user input — and is plain JS with no free identifiers but `Object`. */
|
|
368
|
+
export function compileValidator(src: string): Validator {
|
|
369
|
+
return new Function(src)() as Validator;
|
|
370
|
+
}
|