@matatbread/matbot-tool-types 0.4.7 → 0.4.12
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 +164 -6
- package/src/index.ts +50 -1
- 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.12",
|
|
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-
|
|
40
|
-
"@matatbread/matbot-
|
|
39
|
+
"@matatbread/matbot-core": "^0.4.12",
|
|
40
|
+
"@matatbread/matbot-plugin-api": "^0.4.12"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@types/node": "^22.0.0",
|
|
44
44
|
"typescript": "^6.0.3",
|
|
45
|
-
"@matatbread/matbot-plugin-api": "^0.4.
|
|
46
|
-
"@matatbread/matbot-core": "^0.4.
|
|
45
|
+
"@matatbread/matbot-plugin-api": "^0.4.12",
|
|
46
|
+
"@matatbread/matbot-core": "^0.4.12"
|
|
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');
|
|
@@ -164,7 +182,7 @@ export async function buildMatbotToolsDts(
|
|
|
164
182
|
}
|
|
165
183
|
if (roots.size === 1) return null; // nothing to scan beyond plugin-api itself
|
|
166
184
|
|
|
167
|
-
const
|
|
185
|
+
const options: TS.CompilerOptions = {
|
|
168
186
|
target: ts.ScriptTarget.ES2022,
|
|
169
187
|
module: ts.ModuleKind.NodeNext,
|
|
170
188
|
moduleResolution: ts.ModuleResolutionKind.NodeNext,
|
|
@@ -173,7 +191,8 @@ export async function buildMatbotToolsDts(
|
|
|
173
191
|
noEmit: true,
|
|
174
192
|
skipLibCheck: true,
|
|
175
193
|
baseUrl: projectRoot,
|
|
176
|
-
}
|
|
194
|
+
};
|
|
195
|
+
const program = ts.createProgram([...roots], options);
|
|
177
196
|
const checker = program.getTypeChecker();
|
|
178
197
|
|
|
179
198
|
const apiSf = program.getSourceFile(pluginApiIndex)
|
|
@@ -185,6 +204,125 @@ export async function buildMatbotToolsDts(
|
|
|
185
204
|
const TYPE_FLAGS = ts.SymbolFlags.Type | ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias;
|
|
186
205
|
const apiTypeNames = new Set(apiExports.filter(s => (s.flags & TYPE_FLAGS) !== 0).map(s => s.name));
|
|
187
206
|
|
|
207
|
+
/**
|
|
208
|
+
* Validators for the tools whose contract is a `toolContract` STRING. The emitter needs a `ts.Type`,
|
|
209
|
+
* and a string is not one, so the strings are rendered into a virtual augmentation file and typed.
|
|
210
|
+
*
|
|
211
|
+
* This is a SECOND, deliberately tiny Program — the virtual file plus plugin-api, no workspace scan —
|
|
212
|
+
* rather than an extra root on the one above, because the exact import list is only knowable once
|
|
213
|
+
* plugin-api's exports have been resolved by a checker, and that is the Program above. Guessing the
|
|
214
|
+
* list instead (rewrite every capitalised bare name to an inline `import(...)`) needs a denylist of
|
|
215
|
+
* TypeScript's own utility types, and the first thing it breaks is `Record<string, never>` — which is
|
|
216
|
+
* `NoParams`, the commonest synthetic params type there is. Exactness is worth the second Program;
|
|
217
|
+
* nothing is built at all when no synthetic tool is loaded.
|
|
218
|
+
*
|
|
219
|
+
* Only `paramNodes` is taken from here. The wire text and the dts arm are spliced from the same strings
|
|
220
|
+
* by the caller and are what the model already reads; re-deriving them from the resolved type would
|
|
221
|
+
* expand an alias the author wrote deliberately, for no gain.
|
|
222
|
+
*/
|
|
223
|
+
const syntheticValidators = (): Record<string, ToolValidator> => {
|
|
224
|
+
const out: Record<string, ToolValidator> = {};
|
|
225
|
+
const usable: Record<string, string> = {};
|
|
226
|
+
|
|
227
|
+
// Screened one at a time, BEFORE any is rendered into the shared file: they become properties of one
|
|
228
|
+
// interface, where a single stray brace would swallow every arm after it and take the whole batch
|
|
229
|
+
// down. A malformed string is a stated refusal rather than a silent absence — nothing else in the
|
|
230
|
+
// system parses these, so until now a broken one was merely bad documentation.
|
|
231
|
+
for (const [name, text] of Object.entries(syntheticContracts ?? {})) {
|
|
232
|
+
const probe = ts.createSourceFile('/probe.ts', `type __P = ${text};\n`, ts.ScriptTarget.ES2022, true);
|
|
233
|
+
const bad = (probe as unknown as { parseDiagnostics?: readonly TS.Diagnostic[] }).parseDiagnostics ?? [];
|
|
234
|
+
if (bad.length > 0) {
|
|
235
|
+
out[name] = { refused: `toolContract does not parse as a type: ${ts.flattenDiagnosticMessageText(bad[0]!.messageText, ' ')}` };
|
|
236
|
+
} else out[name] = (usable[name] = text, { refused: 'not resolved' }); // replaced below, or kept as the refusal
|
|
237
|
+
}
|
|
238
|
+
const names = Object.keys(usable);
|
|
239
|
+
if (names.length === 0) return out;
|
|
240
|
+
|
|
241
|
+
const body = names.map(n => ` ${JSON.stringify(n)}: ${usable[n]!};`).join('\n');
|
|
242
|
+
// Exactly the plugin-api types these arms name, from the resolved export set — the same rule
|
|
243
|
+
// `registryBlock` uses for the dts. A synthetic tool inlines its own shape types, so what is left is
|
|
244
|
+
// genuine plugin-api exports.
|
|
245
|
+
const referenced = ['ToolContract', ...[...apiTypeNames].filter(t => new RegExp(`\\b${t}\\b`).test(body))];
|
|
246
|
+
const src = `import type { ${[...new Set(referenced)].join(', ')} } from '@matatbread/matbot-plugin-api';\n`
|
|
247
|
+
+ `declare module '@matatbread/matbot-plugin-api' {\n interface ToolContracts {\n${body}\n }\n}\n`;
|
|
248
|
+
|
|
249
|
+
const virtualPath = join(projectRoot, '__matbot_synthetic_contracts__.ts');
|
|
250
|
+
const host = ts.createCompilerHost(options);
|
|
251
|
+
const innerGet = host.getSourceFile.bind(host);
|
|
252
|
+
const innerExists = host.fileExists.bind(host);
|
|
253
|
+
const innerRead = host.readFile.bind(host);
|
|
254
|
+
host.getSourceFile = (f, v, onError, create) =>
|
|
255
|
+
f === virtualPath ? ts.createSourceFile(f, src, v, true) : innerGet(f, v, onError, create);
|
|
256
|
+
host.fileExists = f => f === virtualPath || innerExists(f);
|
|
257
|
+
host.readFile = f => (f === virtualPath ? src : innerRead(f));
|
|
258
|
+
|
|
259
|
+
// Anchor the import by PATH, exactly as the checker worker does. Resolving it by name would depend on
|
|
260
|
+
// where `projectRoot` happens to sit relative to a `node_modules` holding plugin-api, and in a pnpm
|
|
261
|
+
// workspace the repo root does not hold one — whereupon the import silently yields `any`, the emitter
|
|
262
|
+
// reports "accepts anything" as a caveat, and the tool looks validated while its params are wide open.
|
|
263
|
+
const prog = ts.createProgram([virtualPath, pluginApiIndex], {
|
|
264
|
+
...options, paths: { '@matatbread/matbot-plugin-api': [pluginApiIndex] },
|
|
265
|
+
}, host);
|
|
266
|
+
const chk = prog.getTypeChecker();
|
|
267
|
+
const sf = prog.getSourceFile(virtualPath);
|
|
268
|
+
if (!sf) return out;
|
|
269
|
+
|
|
270
|
+
// The virtual file must typecheck. It is machine-generated from strings, so ANY diagnostic in it means
|
|
271
|
+
// a name did not resolve or an arm is malformed — and the consequence of continuing is not a wrong
|
|
272
|
+
// answer but a silent one: an unresolved reference is `any`, which validates everything. Refusing per
|
|
273
|
+
// tool keeps that visible and confines it, since `ts-validation` then defers to the `inputSchema`
|
|
274
|
+
// instead of claiming the type was enforced.
|
|
275
|
+
const broken = new Map<string, string>();
|
|
276
|
+
for (const d of [...prog.getSemanticDiagnostics(sf), ...prog.getSyntacticDiagnostics(sf)]) {
|
|
277
|
+
if (d.start === undefined) continue;
|
|
278
|
+
// Walk up from the diagnostic to the arm it sits inside; the property's name is the tool's.
|
|
279
|
+
let n: TS.Node | undefined = (function find(node: TS.Node): TS.Node | undefined {
|
|
280
|
+
if (d.start! < node.getStart() || d.start! >= node.getEnd()) return undefined;
|
|
281
|
+
for (const c of node.getChildren()) { const hit = find(c); if (hit) return hit; }
|
|
282
|
+
return ts.isPropertySignature(node) ? node : undefined;
|
|
283
|
+
})(sf);
|
|
284
|
+
const name = n !== undefined && ts.isPropertySignature(n)
|
|
285
|
+
? (ts.isStringLiteral(n.name) || ts.isIdentifier(n.name) ? n.name.text : undefined)
|
|
286
|
+
: undefined;
|
|
287
|
+
const msg = ts.flattenDiagnosticMessageText(d.messageText, ' ');
|
|
288
|
+
if (name !== undefined) broken.set(name, msg);
|
|
289
|
+
// A file-level diagnostic (a failed import) cannot be attributed to one arm, so it condemns them all.
|
|
290
|
+
else for (const k of names) broken.set(k, msg);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Read the arms off the virtual file's own declarations rather than the merged ToolContracts symbol:
|
|
294
|
+
// this Program has no scanned arms to merge, and going via the file keeps each tool's node in hand.
|
|
295
|
+
const walk = (n: TS.Node): void => {
|
|
296
|
+
if (ts.isPropertySignature(n) && n.type !== undefined
|
|
297
|
+
&& (ts.isStringLiteral(n.name) || ts.isIdentifier(n.name))) {
|
|
298
|
+
const name = ts.isStringLiteral(n.name) ? n.name.text : n.name.text;
|
|
299
|
+
if (Object.hasOwn(usable, name)) {
|
|
300
|
+
const fault = broken.get(name);
|
|
301
|
+
if (fault !== undefined) {
|
|
302
|
+
out[name] = { refused: `toolContract does not typecheck: ${fault}` };
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
const ann = n.type;
|
|
306
|
+
const arms = ts.isUnionTypeNode(ann) ? [...ann.types] : [ann];
|
|
307
|
+
const paramNodes: TS.TypeNode[] = [];
|
|
308
|
+
let ok = true;
|
|
309
|
+
for (const a of arms) {
|
|
310
|
+
// A `toolContract` is by contract `ToolContract<R, A>` or a `|`-union of those, written
|
|
311
|
+
// literally — so there is no alias to resolve here, and anything else is not a contract.
|
|
312
|
+
if (!ts.isTypeReferenceNode(a) || a.typeName.getText() !== 'ToolContract' || a.typeArguments?.length !== 2) { ok = false; break; }
|
|
313
|
+
paramNodes.push(a.typeArguments[1]!);
|
|
314
|
+
}
|
|
315
|
+
out[name] = ok
|
|
316
|
+
? buildToolValidator(ts, chk, paramNodes.map(nd => chk.getTypeFromTypeNode(nd)), ann, { excessProperties: 'reject' })
|
|
317
|
+
: { refused: 'toolContract is not `ToolContract<Result, Args>` (or a union of those)' };
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
ts.forEachChild(n, walk);
|
|
321
|
+
};
|
|
322
|
+
walk(sf);
|
|
323
|
+
return out;
|
|
324
|
+
};
|
|
325
|
+
|
|
188
326
|
// Resolve an augmentable interface from its CANONICAL top-level declaration in plugin-api, not the
|
|
189
327
|
// index.ts re-export: `export * from './plugin.js'` (MatbotServices) exposes a stunted re-export view
|
|
190
328
|
// that drops cross-file augmentations; the canonical declaration's symbol carries the merged set.
|
|
@@ -555,19 +693,21 @@ export async function buildMatbotToolsDts(
|
|
|
555
693
|
return text;
|
|
556
694
|
};
|
|
557
695
|
|
|
558
|
-
const extractArms = (ann: TS.TypeNode): { params: string; result: string } | undefined => {
|
|
696
|
+
const extractArms = (ann: TS.TypeNode): { params: string; result: string; paramNodes: TS.TypeNode[] } | undefined => {
|
|
559
697
|
const resolved = resolveAlias(ann);
|
|
560
698
|
const arms = ts.isUnionTypeNode(resolved) ? [...resolved.types] : [resolved];
|
|
561
|
-
const params: string[] = [], results: string[] = [];
|
|
699
|
+
const params: string[] = [], results: string[] = [], paramNodes: TS.TypeNode[] = [];
|
|
562
700
|
for (const raw of arms) {
|
|
563
701
|
const a = resolveAlias(raw);
|
|
564
702
|
if (!ts.isTypeReferenceNode(a) || a.typeName.getText() !== 'ToolContract' || a.typeArguments?.length !== 2) return undefined;
|
|
565
703
|
results.push(expandNamed(a.typeArguments[0]!, new Set(), 0));
|
|
566
704
|
params.push(expandNamed(a.typeArguments[1]!, new Set(), 0));
|
|
705
|
+
paramNodes.push(a.typeArguments[1]!);
|
|
567
706
|
}
|
|
568
|
-
return { result: results.join(' | '), params: params.join(' | ') };
|
|
707
|
+
return { result: results.join(' | '), params: params.join(' | '), paramNodes };
|
|
569
708
|
};
|
|
570
709
|
const contracts: Record<string, { params: string; result: string }> = {};
|
|
710
|
+
const validators: Record<string, ToolValidator> = {};
|
|
571
711
|
const toolContractsSym = findCanonicalSymbol('ToolContracts');
|
|
572
712
|
if (toolContractsSym) {
|
|
573
713
|
for (const prop of checker.getPropertiesOfType(checker.getDeclaredTypeOfSymbol(toolContractsSym))) {
|
|
@@ -576,10 +716,27 @@ export async function buildMatbotToolsDts(
|
|
|
576
716
|
const ann = decl && ts.isPropertySignature(decl) ? decl.type : undefined;
|
|
577
717
|
if (!ann) continue;
|
|
578
718
|
const c = extractArms(ann);
|
|
579
|
-
if (c)
|
|
719
|
+
if (!c) continue;
|
|
720
|
+
contracts[prop.name] = { params: c.params, result: c.result };
|
|
721
|
+
// Excess properties are REJECTED, matching TypeScript's own treatment of a fresh object literal —
|
|
722
|
+
// which is exactly what a model-authored params object is. An invented or misspelled key otherwise
|
|
723
|
+
// fails silently: it is dropped, and the tool runs with a parameter the caller believes it passed
|
|
724
|
+
// (`sessionId` mis-sent as `session_id` reads as "no session given"). Rejecting turns the single
|
|
725
|
+
// most common tool-call hallucination into an error the model can repair. It also makes `NoParams`
|
|
726
|
+
// consistent rather than accidentally special: `Record<string, never>` already refuses every key,
|
|
727
|
+
// via its index signature's `never`, so without this a closed contract was the LOOSER of the two.
|
|
728
|
+
validators[prop.name] = buildToolValidator(
|
|
729
|
+
ts, checker, c.paramNodes.map(nd => checker.getTypeFromTypeNode(nd)), ann,
|
|
730
|
+
{ excessProperties: 'reject' },
|
|
731
|
+
);
|
|
580
732
|
}
|
|
581
733
|
}
|
|
582
734
|
|
|
735
|
+
// Source-declared arms WIN: a scanned augmentation is the tool's own compiled contract, whereas a
|
|
736
|
+
// `toolContract` string is a runtime assertion about it. They only collide if a plugin ships source
|
|
737
|
+
// for a tool it also registers dynamically, and then the compiler-checked one is the truth.
|
|
738
|
+
for (const [name, v] of Object.entries(syntheticValidators())) validators[name] ??= v;
|
|
739
|
+
|
|
583
740
|
const block = (name: string, lines: string[]): string =>
|
|
584
741
|
lines.length ? ` interface ${name} {\n${lines.join('\n')}\n }\n` : '';
|
|
585
742
|
const imports = [...importNames].filter(n => apiTypeNames.has(n)).sort();
|
|
@@ -595,6 +752,7 @@ ${block('ToolContracts', tools.lines)}${block('MatbotServices', services.lines)}
|
|
|
595
752
|
services: { emitted: services.emitted, unknown: services.unknown },
|
|
596
753
|
conflicts,
|
|
597
754
|
contracts,
|
|
755
|
+
validators,
|
|
598
756
|
apiExports: [...apiTypeNames],
|
|
599
757
|
};
|
|
600
758
|
}
|
package/src/index.ts
CHANGED
|
@@ -6,9 +6,43 @@ import type { MatbotMachine, MatbotPluginSpec, ToolTypeIndex } from '@matatbread
|
|
|
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
|
|
|
@@ -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
|
}
|
|
@@ -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
|
+
}
|