@aeye/schema 0.0.0-stage → 0.9.0
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/LICENSE +674 -0
- package/README.md +60 -3
- package/aeye-schema.md +501 -0
- package/dist/index.d.ts +2391 -0
- package/dist/index.js +4834 -0
- package/package.json +84 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,4834 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __export = (target, all) => {
|
|
3
|
+
for (var name in all)
|
|
4
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
// src/a.ts
|
|
8
|
+
var a_exports = {};
|
|
9
|
+
__export(a_exports, {
|
|
10
|
+
array: () => array,
|
|
11
|
+
boolean: () => boolean,
|
|
12
|
+
codec: () => codec,
|
|
13
|
+
conditional: () => conditional,
|
|
14
|
+
declare: () => declare,
|
|
15
|
+
default: () => default_,
|
|
16
|
+
define: () => define,
|
|
17
|
+
dependent: () => dependent,
|
|
18
|
+
discriminatedUnion: () => discriminatedUnion,
|
|
19
|
+
dispatch: () => dispatch,
|
|
20
|
+
enum: () => enum_,
|
|
21
|
+
fromJSONSchema: () => fromJSONSchema,
|
|
22
|
+
int: () => int,
|
|
23
|
+
intersection: () => intersection,
|
|
24
|
+
json: () => json,
|
|
25
|
+
literal: () => literal,
|
|
26
|
+
module: () => module_,
|
|
27
|
+
never: () => never_,
|
|
28
|
+
not: () => not,
|
|
29
|
+
null: () => null_,
|
|
30
|
+
nullable: () => nullable,
|
|
31
|
+
number: () => number,
|
|
32
|
+
object: () => object,
|
|
33
|
+
optional: () => optional,
|
|
34
|
+
record: () => record,
|
|
35
|
+
ref: () => ref,
|
|
36
|
+
refOf: () => refOf,
|
|
37
|
+
string: () => string,
|
|
38
|
+
tuple: () => tuple,
|
|
39
|
+
union: () => union,
|
|
40
|
+
unknown: () => unknown
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// src/profile.ts
|
|
44
|
+
var DEFAULT_JSON_INSTRUCTION = "Return ONLY a single raw JSON object conforming to the schema above: no markdown code fences, no prose, and do NOT echo the schema itself.";
|
|
45
|
+
var ALL_CONSTRAINTS = Object.freeze({ length: true, range: true, items: "all", pattern: "full" });
|
|
46
|
+
var NO_CONSTRAINTS = Object.freeze({ length: false, range: false, items: "none", pattern: "none" });
|
|
47
|
+
var LENIENT = Object.freeze({
|
|
48
|
+
id: "lenient",
|
|
49
|
+
family: "lenient",
|
|
50
|
+
strict: false,
|
|
51
|
+
optional: "omit",
|
|
52
|
+
closedObjects: false,
|
|
53
|
+
records: "open",
|
|
54
|
+
tuples: "prefixItems",
|
|
55
|
+
unions: "anyOf",
|
|
56
|
+
nulls: "type-array",
|
|
57
|
+
allOf: true,
|
|
58
|
+
conditionals: true,
|
|
59
|
+
patternProperties: true,
|
|
60
|
+
defs: true,
|
|
61
|
+
recursion: true,
|
|
62
|
+
any: "empty",
|
|
63
|
+
constraints: ALL_CONSTRAINTS,
|
|
64
|
+
formats: "all",
|
|
65
|
+
examples: "keyword",
|
|
66
|
+
propertyOrdering: false,
|
|
67
|
+
rootObject: false
|
|
68
|
+
});
|
|
69
|
+
var PEOPLE = Object.freeze({ ...LENIENT, id: "people", family: "people", audience: "people" });
|
|
70
|
+
var OPENAI_NON_STRICT = Object.freeze({
|
|
71
|
+
...LENIENT,
|
|
72
|
+
id: "openai",
|
|
73
|
+
family: "openai",
|
|
74
|
+
rootObject: true,
|
|
75
|
+
// Chat Completions `tools`: "A max of 128 functions are supported" (API reference).
|
|
76
|
+
request: Object.freeze({ maxTools: 128 })
|
|
77
|
+
});
|
|
78
|
+
var OPENAI_FORMATS = /* @__PURE__ */ new Set(["date-time", "time", "date", "duration", "email", "hostname", "ipv4", "ipv6", "uuid"]);
|
|
79
|
+
var OPENAI_STRICT = Object.freeze({
|
|
80
|
+
id: "openai-strict",
|
|
81
|
+
family: "openai",
|
|
82
|
+
strict: true,
|
|
83
|
+
optional: "null",
|
|
84
|
+
closedObjects: true,
|
|
85
|
+
records: "pairs",
|
|
86
|
+
tuples: "object",
|
|
87
|
+
unions: "anyOf",
|
|
88
|
+
nulls: "anyOf",
|
|
89
|
+
allOf: false,
|
|
90
|
+
conditionals: false,
|
|
91
|
+
patternProperties: false,
|
|
92
|
+
defs: true,
|
|
93
|
+
recursion: true,
|
|
94
|
+
// OpenAI's own "any" would be a recursive $defs/Any with pairs, which can't
|
|
95
|
+
// be told apart from a real list of {key, value}; JSON text is exact.
|
|
96
|
+
any: "json-text",
|
|
97
|
+
constraints: Object.freeze({ length: true, range: true, items: "all", pattern: "basic" }),
|
|
98
|
+
formats: OPENAI_FORMATS,
|
|
99
|
+
examples: "description",
|
|
100
|
+
propertyOrdering: false,
|
|
101
|
+
maxDepth: 10,
|
|
102
|
+
rootObject: true,
|
|
103
|
+
limits: Object.freeze({
|
|
104
|
+
maxProperties: 5e3,
|
|
105
|
+
maxDepth: 10,
|
|
106
|
+
maxStringChars: 12e4,
|
|
107
|
+
maxEnumValues: 1e3,
|
|
108
|
+
largeEnumValues: 250,
|
|
109
|
+
maxLargeEnumChars: 15e3
|
|
110
|
+
}),
|
|
111
|
+
request: Object.freeze({ maxTools: 128 }),
|
|
112
|
+
loose: OPENAI_NON_STRICT
|
|
113
|
+
});
|
|
114
|
+
var OPENAI_FINETUNED_STRICT = Object.freeze({
|
|
115
|
+
...OPENAI_STRICT,
|
|
116
|
+
id: "openai-finetuned-strict",
|
|
117
|
+
constraints: NO_CONSTRAINTS,
|
|
118
|
+
formats: /* @__PURE__ */ new Set()
|
|
119
|
+
});
|
|
120
|
+
var ANTHROPIC_NON_STRICT = Object.freeze({
|
|
121
|
+
...LENIENT,
|
|
122
|
+
id: "anthropic",
|
|
123
|
+
family: "anthropic",
|
|
124
|
+
rootObject: true
|
|
125
|
+
});
|
|
126
|
+
var ANTHROPIC_STRICT = Object.freeze({
|
|
127
|
+
id: "anthropic-strict",
|
|
128
|
+
family: "anthropic",
|
|
129
|
+
strict: true,
|
|
130
|
+
optional: "omit",
|
|
131
|
+
closedObjects: true,
|
|
132
|
+
records: "pairs",
|
|
133
|
+
tuples: "array",
|
|
134
|
+
unions: "anyOf",
|
|
135
|
+
nulls: "type-array",
|
|
136
|
+
allOf: false,
|
|
137
|
+
conditionals: false,
|
|
138
|
+
patternProperties: false,
|
|
139
|
+
defs: true,
|
|
140
|
+
recursion: false,
|
|
141
|
+
any: "json-text",
|
|
142
|
+
constraints: Object.freeze({ length: false, range: false, items: "min-0-1", pattern: "basic" }),
|
|
143
|
+
formats: /* @__PURE__ */ new Set(["date-time", "time", "date", "duration", "email", "hostname", "uri", "ipv4", "ipv6", "uuid"]),
|
|
144
|
+
examples: "description",
|
|
145
|
+
propertyOrdering: false,
|
|
146
|
+
rootObject: true,
|
|
147
|
+
request: Object.freeze({ maxStrictTools: 20, totals: Object.freeze({ maxOptional: 24, maxUnions: 16 }) }),
|
|
148
|
+
loose: ANTHROPIC_NON_STRICT,
|
|
149
|
+
alwaysStrictOutput: true
|
|
150
|
+
});
|
|
151
|
+
var GEMINI_JSON_INSTRUCTION = "Return ONLY a single raw JSON object that conforms to the schema above. Do NOT wrap it in markdown code fences, do NOT add any prose before or after it, and do NOT echo the schema itself: emit only the JSON instance.";
|
|
152
|
+
var GOOGLE_NON_STRICT = Object.freeze({
|
|
153
|
+
...LENIENT,
|
|
154
|
+
id: "google",
|
|
155
|
+
family: "google",
|
|
156
|
+
recursion: "guarded",
|
|
157
|
+
maxEnumValues: 40,
|
|
158
|
+
rootObject: true,
|
|
159
|
+
jsonInstruction: GEMINI_JSON_INSTRUCTION
|
|
160
|
+
});
|
|
161
|
+
var GOOGLE_STRICT = Object.freeze({
|
|
162
|
+
id: "google-strict",
|
|
163
|
+
family: "google",
|
|
164
|
+
strict: true,
|
|
165
|
+
optional: "omit",
|
|
166
|
+
closedObjects: false,
|
|
167
|
+
records: "open",
|
|
168
|
+
tuples: "prefixItems",
|
|
169
|
+
unions: "anyOf",
|
|
170
|
+
nulls: "type-array",
|
|
171
|
+
allOf: false,
|
|
172
|
+
conditionals: false,
|
|
173
|
+
patternProperties: false,
|
|
174
|
+
defs: true,
|
|
175
|
+
recursion: "guarded",
|
|
176
|
+
any: "empty",
|
|
177
|
+
constraints: Object.freeze({ length: false, range: true, items: "all", pattern: "none" }),
|
|
178
|
+
formats: /* @__PURE__ */ new Set(["date-time", "date", "time"]),
|
|
179
|
+
examples: "description",
|
|
180
|
+
propertyOrdering: false,
|
|
181
|
+
maxEnumValues: 40,
|
|
182
|
+
rootObject: true,
|
|
183
|
+
loose: GOOGLE_NON_STRICT,
|
|
184
|
+
jsonInstruction: GEMINI_JSON_INSTRUCTION
|
|
185
|
+
});
|
|
186
|
+
var GOOGLE_OPENAPI = Object.freeze({
|
|
187
|
+
id: "google-openapi",
|
|
188
|
+
family: "google",
|
|
189
|
+
strict: true,
|
|
190
|
+
optional: "omit",
|
|
191
|
+
closedObjects: false,
|
|
192
|
+
records: "pairs",
|
|
193
|
+
tuples: "array",
|
|
194
|
+
unions: "anyOf",
|
|
195
|
+
nulls: "nullable",
|
|
196
|
+
allOf: false,
|
|
197
|
+
conditionals: false,
|
|
198
|
+
patternProperties: false,
|
|
199
|
+
defs: false,
|
|
200
|
+
recursion: false,
|
|
201
|
+
any: "json-text",
|
|
202
|
+
constraints: Object.freeze({ length: true, range: true, items: "all", pattern: "basic" }),
|
|
203
|
+
formats: /* @__PURE__ */ new Set(["date-time", "date", "time", "duration"]),
|
|
204
|
+
examples: "description",
|
|
205
|
+
propertyOrdering: true,
|
|
206
|
+
maxEnumValues: 40,
|
|
207
|
+
maxDepth: 10,
|
|
208
|
+
rootObject: true,
|
|
209
|
+
loose: GOOGLE_NON_STRICT,
|
|
210
|
+
jsonInstruction: GEMINI_JSON_INSTRUCTION
|
|
211
|
+
});
|
|
212
|
+
var XAI_FORMATS = /* @__PURE__ */ new Set(["date", "time", "date-time", "email", "uuid", "ipv4", "ipv6", "uri"]);
|
|
213
|
+
var XAI_STRICT = Object.freeze({
|
|
214
|
+
id: "xai-strict",
|
|
215
|
+
family: "xai",
|
|
216
|
+
strict: true,
|
|
217
|
+
optional: "omit",
|
|
218
|
+
closedObjects: true,
|
|
219
|
+
records: "open",
|
|
220
|
+
tuples: "prefixItems",
|
|
221
|
+
unions: "anyOf",
|
|
222
|
+
nulls: "type-array",
|
|
223
|
+
allOf: false,
|
|
224
|
+
conditionals: false,
|
|
225
|
+
patternProperties: false,
|
|
226
|
+
defs: true,
|
|
227
|
+
recursion: false,
|
|
228
|
+
any: "flat",
|
|
229
|
+
constraints: Object.freeze({ length: true, range: true, items: "all", pattern: "basic" }),
|
|
230
|
+
formats: XAI_FORMATS,
|
|
231
|
+
examples: "description",
|
|
232
|
+
propertyOrdering: false,
|
|
233
|
+
rootObject: true
|
|
234
|
+
});
|
|
235
|
+
var XAI_NON_STRICT = Object.freeze({ ...XAI_STRICT, id: "xai", strict: false });
|
|
236
|
+
var OLLAMA = Object.freeze({ ...LENIENT, id: "ollama", family: "ollama", rootObject: true });
|
|
237
|
+
var MINIMAL = Object.freeze({
|
|
238
|
+
id: "minimal",
|
|
239
|
+
family: "minimal",
|
|
240
|
+
strict: true,
|
|
241
|
+
optional: "null",
|
|
242
|
+
closedObjects: true,
|
|
243
|
+
records: "pairs",
|
|
244
|
+
tuples: "object",
|
|
245
|
+
unions: "tagged",
|
|
246
|
+
nulls: "type-array",
|
|
247
|
+
allOf: false,
|
|
248
|
+
conditionals: false,
|
|
249
|
+
patternProperties: false,
|
|
250
|
+
defs: false,
|
|
251
|
+
recursion: false,
|
|
252
|
+
any: "json-text",
|
|
253
|
+
constraints: NO_CONSTRAINTS,
|
|
254
|
+
formats: /* @__PURE__ */ new Set(),
|
|
255
|
+
examples: "description",
|
|
256
|
+
propertyOrdering: false,
|
|
257
|
+
maxDepth: 6,
|
|
258
|
+
maxEnumValues: 8,
|
|
259
|
+
rootObject: true
|
|
260
|
+
});
|
|
261
|
+
var BY_ID = /* @__PURE__ */ new Map();
|
|
262
|
+
var BY_FAMILY = /* @__PURE__ */ new Map();
|
|
263
|
+
function registerProfile(profile) {
|
|
264
|
+
BY_ID.set(profile.id, profile);
|
|
265
|
+
const slot = BY_FAMILY.get(profile.family) ?? {};
|
|
266
|
+
if (profile.strict) slot.strict ??= profile;
|
|
267
|
+
else slot.loose ??= profile;
|
|
268
|
+
BY_FAMILY.set(profile.family, slot);
|
|
269
|
+
}
|
|
270
|
+
for (const p of [
|
|
271
|
+
LENIENT,
|
|
272
|
+
PEOPLE,
|
|
273
|
+
OPENAI_NON_STRICT,
|
|
274
|
+
OPENAI_STRICT,
|
|
275
|
+
OPENAI_FINETUNED_STRICT,
|
|
276
|
+
ANTHROPIC_NON_STRICT,
|
|
277
|
+
ANTHROPIC_STRICT,
|
|
278
|
+
GOOGLE_NON_STRICT,
|
|
279
|
+
GOOGLE_STRICT,
|
|
280
|
+
GOOGLE_OPENAPI,
|
|
281
|
+
XAI_STRICT,
|
|
282
|
+
XAI_NON_STRICT,
|
|
283
|
+
OLLAMA,
|
|
284
|
+
MINIMAL
|
|
285
|
+
]) registerProfile(p);
|
|
286
|
+
function getProfile(id) {
|
|
287
|
+
return BY_ID.get(id);
|
|
288
|
+
}
|
|
289
|
+
function familyProfile(family, strict) {
|
|
290
|
+
const slot = BY_FAMILY.get(family);
|
|
291
|
+
return (strict ? slot?.strict : void 0) ?? slot?.loose ?? LENIENT;
|
|
292
|
+
}
|
|
293
|
+
function variant(base, adj) {
|
|
294
|
+
const tags = [];
|
|
295
|
+
const patch = {};
|
|
296
|
+
if (adj.maxEnumValues !== void 0 && adj.maxEnumValues < (base.maxEnumValues ?? Infinity)) {
|
|
297
|
+
patch.maxEnumValues = adj.maxEnumValues;
|
|
298
|
+
tags.push(`enum<=${adj.maxEnumValues}`);
|
|
299
|
+
}
|
|
300
|
+
if (adj.maxDepth !== void 0 && adj.maxDepth < (base.maxDepth ?? Infinity)) {
|
|
301
|
+
patch.maxDepth = adj.maxDepth;
|
|
302
|
+
tags.push(`depth<=${adj.maxDepth}`);
|
|
303
|
+
}
|
|
304
|
+
if (adj.optionalAsNull && base.optional !== "null") {
|
|
305
|
+
patch.optional = "null";
|
|
306
|
+
tags.push("optional=null");
|
|
307
|
+
}
|
|
308
|
+
if (adj.rootObject && !base.rootObject) {
|
|
309
|
+
patch.rootObject = true;
|
|
310
|
+
tags.push("root=object");
|
|
311
|
+
}
|
|
312
|
+
if (!tags.length) return base;
|
|
313
|
+
const id = `${base.id}[${tags.join(",")}]`;
|
|
314
|
+
let p = BY_ID.get(id);
|
|
315
|
+
if (!p) {
|
|
316
|
+
p = Object.freeze({ ...base, ...patch, id });
|
|
317
|
+
BY_ID.set(id, p);
|
|
318
|
+
}
|
|
319
|
+
return p;
|
|
320
|
+
}
|
|
321
|
+
var views = /* @__PURE__ */ new WeakMap();
|
|
322
|
+
function viewOf(profile) {
|
|
323
|
+
let v = views.get(profile);
|
|
324
|
+
if (!v) {
|
|
325
|
+
v = Object.freeze({
|
|
326
|
+
profile,
|
|
327
|
+
records: profile.records,
|
|
328
|
+
optional: profile.optional,
|
|
329
|
+
recordWord: profile.records === "pairs" ? "a list of {key, value} entries" : "an object"
|
|
330
|
+
});
|
|
331
|
+
views.set(profile, v);
|
|
332
|
+
}
|
|
333
|
+
return v;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// src/measure.ts
|
|
337
|
+
var ZERO_MEASURE = Object.freeze({
|
|
338
|
+
properties: 0,
|
|
339
|
+
depth: 0,
|
|
340
|
+
stringChars: 0,
|
|
341
|
+
enumValues: 0,
|
|
342
|
+
enums: Object.freeze([]),
|
|
343
|
+
optional: 0,
|
|
344
|
+
unions: 0
|
|
345
|
+
});
|
|
346
|
+
function measureJson(schema) {
|
|
347
|
+
let properties = 0;
|
|
348
|
+
let stringChars = 0;
|
|
349
|
+
let enumValues = 0;
|
|
350
|
+
let optional2 = 0;
|
|
351
|
+
let unions = 0;
|
|
352
|
+
const enums = [];
|
|
353
|
+
const defs = schema.$defs ?? {};
|
|
354
|
+
for (const name of Object.keys(defs)) stringChars += name.length;
|
|
355
|
+
const count = (j) => {
|
|
356
|
+
if (!j || typeof j !== "object") return;
|
|
357
|
+
if (Array.isArray(j)) {
|
|
358
|
+
for (const x of j) count(x);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
const o = j;
|
|
362
|
+
if (o.properties && typeof o.properties === "object") {
|
|
363
|
+
const props = o.properties;
|
|
364
|
+
const required = new Set(Array.isArray(o.required) ? o.required : []);
|
|
365
|
+
for (const [k, p] of Object.entries(props)) {
|
|
366
|
+
properties++;
|
|
367
|
+
stringChars += k.length;
|
|
368
|
+
if (!required.has(k)) optional2++;
|
|
369
|
+
count(p);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
if (Array.isArray(o.enum)) {
|
|
373
|
+
let chars = 0;
|
|
374
|
+
for (const v of o.enum) if (typeof v === "string") chars += v.length;
|
|
375
|
+
enumValues += o.enum.length;
|
|
376
|
+
stringChars += chars;
|
|
377
|
+
enums.push({ values: o.enum.length, chars });
|
|
378
|
+
}
|
|
379
|
+
if (typeof o.const === "string") stringChars += o.const.length;
|
|
380
|
+
const alts = o.anyOf ?? o.oneOf;
|
|
381
|
+
if (Array.isArray(alts) && alts.length > 1 || Array.isArray(o.type) && o.type.length > 1) unions++;
|
|
382
|
+
for (const k of ["items", "prefixItems", "anyOf", "oneOf", "allOf", "additionalProperties", "not", "if", "then", "else"]) {
|
|
383
|
+
if (k in o) count(o[k]);
|
|
384
|
+
}
|
|
385
|
+
if (o.patternProperties && typeof o.patternProperties === "object") for (const v of Object.values(o.patternProperties)) count(v);
|
|
386
|
+
};
|
|
387
|
+
const { $defs: _d, ...body } = schema;
|
|
388
|
+
count(body);
|
|
389
|
+
for (const d of Object.values(defs)) count(d);
|
|
390
|
+
const refName2 = (o) => {
|
|
391
|
+
if (typeof o.$ref !== "string") return void 0;
|
|
392
|
+
return /^#\/\$defs\/(.+)$/.exec(o.$ref)?.[1]?.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
393
|
+
};
|
|
394
|
+
const sccOf = components(defs, refName2);
|
|
395
|
+
const open = /* @__PURE__ */ new Set();
|
|
396
|
+
const memo = /* @__PURE__ */ new Map();
|
|
397
|
+
const depthOf = (j) => {
|
|
398
|
+
if (!j || typeof j !== "object" || Array.isArray(j)) return 0;
|
|
399
|
+
const o = j;
|
|
400
|
+
if (typeof o.$ref === "string") {
|
|
401
|
+
const name = refName2(o);
|
|
402
|
+
if (!name || open.has(name) || !defs[name]) return 0;
|
|
403
|
+
const comp = sccOf.get(name);
|
|
404
|
+
let key = name;
|
|
405
|
+
if (comp) {
|
|
406
|
+
key += "|";
|
|
407
|
+
for (const m of comp) key += open.has(m) ? "1" : "0";
|
|
408
|
+
}
|
|
409
|
+
const hit = memo.get(key);
|
|
410
|
+
if (hit !== void 0) return hit;
|
|
411
|
+
open.add(name);
|
|
412
|
+
const d = depthOf(defs[name]);
|
|
413
|
+
open.delete(name);
|
|
414
|
+
memo.set(key, d);
|
|
415
|
+
return d;
|
|
416
|
+
}
|
|
417
|
+
const container = o.type === "object" || o.type === "array" || Array.isArray(o.type) && (o.type.includes("object") || o.type.includes("array"));
|
|
418
|
+
let inner = 0;
|
|
419
|
+
const visit = (x) => {
|
|
420
|
+
const d = depthOf(x);
|
|
421
|
+
if (d > inner) inner = d;
|
|
422
|
+
};
|
|
423
|
+
if (o.properties && typeof o.properties === "object") for (const p of Object.values(o.properties)) visit(p);
|
|
424
|
+
for (const k of ["items", "additionalProperties", "not"]) if (k in o) visit(o[k]);
|
|
425
|
+
for (const k of ["prefixItems", "anyOf", "oneOf", "allOf"]) if (Array.isArray(o[k])) for (const x of o[k]) visit(x);
|
|
426
|
+
return (container ? 1 : 0) + inner;
|
|
427
|
+
};
|
|
428
|
+
const depth = depthOf(body);
|
|
429
|
+
return { properties, depth, stringChars, enumValues, enums, optional: optional2, unions };
|
|
430
|
+
}
|
|
431
|
+
function components(defs, refName2) {
|
|
432
|
+
const edges = /* @__PURE__ */ new Map();
|
|
433
|
+
const collect = (j, out) => {
|
|
434
|
+
if (!j || typeof j !== "object") return;
|
|
435
|
+
if (Array.isArray(j)) {
|
|
436
|
+
for (const x of j) collect(x, out);
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
const n = refName2(j);
|
|
440
|
+
if (n !== void 0 && defs[n]) out.add(n);
|
|
441
|
+
for (const v of Object.values(j)) collect(v, out);
|
|
442
|
+
};
|
|
443
|
+
for (const name of Object.keys(defs)) {
|
|
444
|
+
const out = /* @__PURE__ */ new Set();
|
|
445
|
+
collect(defs[name], out);
|
|
446
|
+
edges.set(name, [...out]);
|
|
447
|
+
}
|
|
448
|
+
const index = /* @__PURE__ */ new Map();
|
|
449
|
+
const low = /* @__PURE__ */ new Map();
|
|
450
|
+
const onStack = /* @__PURE__ */ new Set();
|
|
451
|
+
const stack = [];
|
|
452
|
+
const result = /* @__PURE__ */ new Map();
|
|
453
|
+
let next = 0;
|
|
454
|
+
for (const root of edges.keys()) {
|
|
455
|
+
if (index.has(root)) continue;
|
|
456
|
+
const work = [[root, 0]];
|
|
457
|
+
while (work.length) {
|
|
458
|
+
const frame = work[work.length - 1];
|
|
459
|
+
const [v, i] = frame;
|
|
460
|
+
if (i === 0) {
|
|
461
|
+
index.set(v, next);
|
|
462
|
+
low.set(v, next);
|
|
463
|
+
next++;
|
|
464
|
+
stack.push(v);
|
|
465
|
+
onStack.add(v);
|
|
466
|
+
}
|
|
467
|
+
const out = edges.get(v);
|
|
468
|
+
if (i < out.length) {
|
|
469
|
+
frame[1]++;
|
|
470
|
+
const w = out[i];
|
|
471
|
+
if (!index.has(w)) work.push([w, 0]);
|
|
472
|
+
else if (onStack.has(w)) low.set(v, Math.min(low.get(v), index.get(w)));
|
|
473
|
+
continue;
|
|
474
|
+
}
|
|
475
|
+
work.pop();
|
|
476
|
+
const parent = work[work.length - 1];
|
|
477
|
+
if (parent) low.set(parent[0], Math.min(low.get(parent[0]), low.get(v)));
|
|
478
|
+
if (low.get(v) === index.get(v)) {
|
|
479
|
+
const comp = [];
|
|
480
|
+
let w;
|
|
481
|
+
do {
|
|
482
|
+
w = stack.pop();
|
|
483
|
+
onStack.delete(w);
|
|
484
|
+
comp.push(w);
|
|
485
|
+
} while (w !== v);
|
|
486
|
+
if (comp.length > 1 || out.includes(v)) for (const m of comp) result.set(m, comp);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
return result;
|
|
491
|
+
}
|
|
492
|
+
function addMeasures(a, b) {
|
|
493
|
+
return {
|
|
494
|
+
properties: a.properties + b.properties,
|
|
495
|
+
depth: Math.max(a.depth, b.depth),
|
|
496
|
+
stringChars: a.stringChars + b.stringChars,
|
|
497
|
+
enumValues: a.enumValues + b.enumValues,
|
|
498
|
+
enums: [...a.enums, ...b.enums],
|
|
499
|
+
optional: a.optional + b.optional,
|
|
500
|
+
unions: a.unions + b.unions
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
function overLimits(m, limits, scope) {
|
|
504
|
+
if (!limits) return [];
|
|
505
|
+
const out = [];
|
|
506
|
+
const over = (what, n, max) => {
|
|
507
|
+
if (max !== void 0 && n > max) out.push(`${scope}: ${n} ${what} (limit ${max})`);
|
|
508
|
+
};
|
|
509
|
+
over("object properties", m.properties, limits.maxProperties);
|
|
510
|
+
over("levels of nesting", m.depth, limits.maxDepth);
|
|
511
|
+
over("characters of names and enum values", m.stringChars, limits.maxStringChars);
|
|
512
|
+
over("enum values", m.enumValues, limits.maxEnumValues);
|
|
513
|
+
over("optional properties", m.optional, limits.maxOptional);
|
|
514
|
+
over("union-typed properties", m.unions, limits.maxUnions);
|
|
515
|
+
if (limits.largeEnumValues !== void 0 && limits.maxLargeEnumChars !== void 0) {
|
|
516
|
+
for (const e of m.enums) {
|
|
517
|
+
if (e.values > limits.largeEnumValues && e.chars > limits.maxLargeEnumChars) {
|
|
518
|
+
out.push(`${scope}: an enum of ${e.values} values has ${e.chars} characters (limit ${limits.maxLargeEnumChars} above ${limits.largeEnumValues} values)`);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
return out;
|
|
523
|
+
}
|
|
524
|
+
function brokenLimits(m, limits, out = /* @__PURE__ */ new Set()) {
|
|
525
|
+
if (!limits) return out;
|
|
526
|
+
const over = (k, n, max) => {
|
|
527
|
+
if (max !== void 0 && n > max) out.add(k);
|
|
528
|
+
};
|
|
529
|
+
over("maxProperties", m.properties, limits.maxProperties);
|
|
530
|
+
over("maxDepth", m.depth, limits.maxDepth);
|
|
531
|
+
over("maxStringChars", m.stringChars, limits.maxStringChars);
|
|
532
|
+
over("maxEnumValues", m.enumValues, limits.maxEnumValues);
|
|
533
|
+
over("maxOptional", m.optional, limits.maxOptional);
|
|
534
|
+
over("maxUnions", m.unions, limits.maxUnions);
|
|
535
|
+
if (limits.largeEnumValues !== void 0 && limits.maxLargeEnumChars !== void 0) {
|
|
536
|
+
for (const e of m.enums) if (e.values > limits.largeEnumValues && e.chars > limits.maxLargeEnumChars) out.add("largeEnum");
|
|
537
|
+
}
|
|
538
|
+
return out;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// src/errors.ts
|
|
542
|
+
var SchemaDefinitionError = class extends Error {
|
|
543
|
+
constructor(message) {
|
|
544
|
+
super(`@aeye/schema: ${message}`);
|
|
545
|
+
this.name = "SchemaDefinitionError";
|
|
546
|
+
}
|
|
547
|
+
};
|
|
548
|
+
var SchemaParseError = class extends Error {
|
|
549
|
+
constructor(issues, message = formatIssues(issues)) {
|
|
550
|
+
super(message);
|
|
551
|
+
this.issues = issues;
|
|
552
|
+
this.name = "SchemaParseError";
|
|
553
|
+
}
|
|
554
|
+
issues;
|
|
555
|
+
};
|
|
556
|
+
var RequestLimitError = class extends Error {
|
|
557
|
+
constructor(problems) {
|
|
558
|
+
super(`@aeye/schema: the request does not fit the model's limits:
|
|
559
|
+
${problems.map((p) => `- ${p}`).join("\n")}`);
|
|
560
|
+
this.problems = problems;
|
|
561
|
+
this.name = "RequestLimitError";
|
|
562
|
+
}
|
|
563
|
+
problems;
|
|
564
|
+
};
|
|
565
|
+
|
|
566
|
+
// src/suggest.ts
|
|
567
|
+
function editDistance(a, b) {
|
|
568
|
+
const prev = [];
|
|
569
|
+
for (let j = 0; j <= b.length; j++) prev[j] = j;
|
|
570
|
+
for (let i = 1; i <= a.length; i++) {
|
|
571
|
+
let diag = prev[0];
|
|
572
|
+
prev[0] = i;
|
|
573
|
+
for (let j = 1; j <= b.length; j++) {
|
|
574
|
+
const tmp = prev[j];
|
|
575
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
576
|
+
prev[j] = Math.min(prev[j] + 1, prev[j - 1] + 1, diag + cost);
|
|
577
|
+
diag = tmp;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
return prev[b.length];
|
|
581
|
+
}
|
|
582
|
+
function suggestionBudget(len) {
|
|
583
|
+
return Math.min(3, Math.max(1, Math.floor(len / 3)));
|
|
584
|
+
}
|
|
585
|
+
function rankNear(input, candidates, budget = suggestionBudget(input.length)) {
|
|
586
|
+
const lower = input.toLowerCase();
|
|
587
|
+
const scored = [];
|
|
588
|
+
for (let index = 0; index < candidates.length; index++) {
|
|
589
|
+
const candidate = candidates[index];
|
|
590
|
+
if (Math.abs(candidate.length - input.length) > budget) continue;
|
|
591
|
+
const ci = editDistance(lower, candidate.toLowerCase());
|
|
592
|
+
if (ci <= budget) scored.push({ candidate, index, ci, exact: editDistance(input, candidate) });
|
|
593
|
+
}
|
|
594
|
+
scored.sort((a, b) => a.ci - b.ci || a.exact - b.exact || a.index - b.index);
|
|
595
|
+
return scored.map((s) => s.candidate);
|
|
596
|
+
}
|
|
597
|
+
function nearest(input, candidates, budget) {
|
|
598
|
+
return rankNear(input, candidates, budget)[0];
|
|
599
|
+
}
|
|
600
|
+
function didYouMean(input, candidates, opts = {}) {
|
|
601
|
+
const max = Math.max(1, opts.max ?? 1);
|
|
602
|
+
const matches2 = rankNear(input, candidates).slice(0, max);
|
|
603
|
+
if (!matches2.length) return "";
|
|
604
|
+
return ` \u2014 did you mean ${orList(matches2.map((m) => `\`${m}\``))}?`;
|
|
605
|
+
}
|
|
606
|
+
function orList(items) {
|
|
607
|
+
if (items.length === 2) return `${items[0]} or ${items[1]}`;
|
|
608
|
+
if (items.length > 2) return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
|
|
609
|
+
return items.join(", ");
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// src/feedback.ts
|
|
613
|
+
var DEFAULT_ERROR_FORMAT = Object.freeze({
|
|
614
|
+
detail: "full",
|
|
615
|
+
maxErrors: 5,
|
|
616
|
+
maxChars: 2e3,
|
|
617
|
+
suggestions: true,
|
|
618
|
+
context: 3,
|
|
619
|
+
depth: 6,
|
|
620
|
+
header: true
|
|
621
|
+
});
|
|
622
|
+
function mergeErrorFormats(...inputs) {
|
|
623
|
+
let merged;
|
|
624
|
+
for (const i of inputs) if (i !== void 0) merged = { ...merged, ...stripUndefined(typeof i === "string" ? { detail: i } : i) };
|
|
625
|
+
return merged;
|
|
626
|
+
}
|
|
627
|
+
function errorFormat(...inputs) {
|
|
628
|
+
const merged = mergeErrorFormats(...inputs) ?? {};
|
|
629
|
+
const detail = merged.detail ?? DEFAULT_ERROR_FORMAT.detail;
|
|
630
|
+
return {
|
|
631
|
+
...DEFAULT_ERROR_FORMAT,
|
|
632
|
+
...merged,
|
|
633
|
+
detail,
|
|
634
|
+
expected: merged.expected ?? detail === "full"
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
function stripUndefined(o) {
|
|
638
|
+
const out = {};
|
|
639
|
+
for (const [k, v] of Object.entries(o)) if (v !== void 0) out[k] = v;
|
|
640
|
+
return out;
|
|
641
|
+
}
|
|
642
|
+
function echoes(f) {
|
|
643
|
+
const d = typeof f === "string" ? f : f?.detail ?? DEFAULT_ERROR_FORMAT.detail;
|
|
644
|
+
return d === "markers" || d === "full";
|
|
645
|
+
}
|
|
646
|
+
var infos = /* @__PURE__ */ new WeakMap();
|
|
647
|
+
function recordIssue(issue, info) {
|
|
648
|
+
infos.set(issue, info);
|
|
649
|
+
}
|
|
650
|
+
function claimIssues(issues, from, node) {
|
|
651
|
+
for (let i = from; i < issues.length; i++) {
|
|
652
|
+
const info = infos.get(issues[i]);
|
|
653
|
+
if (info && !info.node) info.node = node;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
function issueKind(issue) {
|
|
657
|
+
return infos.get(issue)?.kind ?? "other";
|
|
658
|
+
}
|
|
659
|
+
function suggestionFor(issue) {
|
|
660
|
+
const info = infos.get(issue);
|
|
661
|
+
if (!info?.candidates) return void 0;
|
|
662
|
+
const input = info.kind === "unknown-key" || info.kind === "required" ? issue.path[issue.path.length - 1] : info.received;
|
|
663
|
+
if (typeof input !== "string") return void 0;
|
|
664
|
+
return nearest(input, info.candidates());
|
|
665
|
+
}
|
|
666
|
+
var IDENT = /^[A-Za-z_$][\w$]*$/;
|
|
667
|
+
function modelPath(path) {
|
|
668
|
+
let out = "";
|
|
669
|
+
let part = "";
|
|
670
|
+
for (const seg of path) {
|
|
671
|
+
if (seg === "(json)") {
|
|
672
|
+
out += `${part || "(root)"} \u2192 JSON text \u2192 `;
|
|
673
|
+
part = "";
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
part += typeof seg === "number" ? `[${seg}]` : IDENT.test(seg) ? part ? `.${seg}` : seg : `[${JSON.stringify(seg)}]`;
|
|
677
|
+
}
|
|
678
|
+
if (out && !part) return out.slice(0, -3);
|
|
679
|
+
return out + (part || (out ? "" : "(root)"));
|
|
680
|
+
}
|
|
681
|
+
var ABSENT = /* @__PURE__ */ Symbol("absent");
|
|
682
|
+
function valueAt(root, path) {
|
|
683
|
+
let v = root;
|
|
684
|
+
for (const seg of path) {
|
|
685
|
+
if (seg === "(json)") {
|
|
686
|
+
if (typeof v !== "string") continue;
|
|
687
|
+
v = parseOr(v);
|
|
688
|
+
if (v === ABSENT) return ABSENT;
|
|
689
|
+
continue;
|
|
690
|
+
}
|
|
691
|
+
if (typeof v === "string") v = parseOr(v);
|
|
692
|
+
if (v === null || typeof v !== "object") return ABSENT;
|
|
693
|
+
if (!Object.prototype.hasOwnProperty.call(v, seg)) return ABSENT;
|
|
694
|
+
v = v[seg];
|
|
695
|
+
}
|
|
696
|
+
return v;
|
|
697
|
+
}
|
|
698
|
+
var parsedTexts;
|
|
699
|
+
function parseOr(s) {
|
|
700
|
+
const hit = parsedTexts?.get(s);
|
|
701
|
+
if (hit !== void 0) return hit;
|
|
702
|
+
let v;
|
|
703
|
+
try {
|
|
704
|
+
v = JSON.parse(s);
|
|
705
|
+
} catch {
|
|
706
|
+
v = ABSENT;
|
|
707
|
+
}
|
|
708
|
+
parsedTexts?.set(s, v);
|
|
709
|
+
return v;
|
|
710
|
+
}
|
|
711
|
+
function shortType(json2, max = 160) {
|
|
712
|
+
for (const depth of [2, 1, 0]) {
|
|
713
|
+
const t2 = tsOf(json2, depth, 6);
|
|
714
|
+
if (t2.length <= max) return t2;
|
|
715
|
+
}
|
|
716
|
+
const t = tsOf(json2, 0, 3);
|
|
717
|
+
return t.length <= max ? t : `${t.slice(0, max - 1)}\u2026`;
|
|
718
|
+
}
|
|
719
|
+
function refName(ref2) {
|
|
720
|
+
const name = ref2.replace(/^#\/\$defs\//, "");
|
|
721
|
+
return name.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
722
|
+
}
|
|
723
|
+
function tsOf(j, depth, width) {
|
|
724
|
+
if (typeof j.$ref === "string") return refName(j.$ref);
|
|
725
|
+
if ("const" in j) return JSON.stringify(j.const);
|
|
726
|
+
if (Array.isArray(j.enum)) return listed(j.enum.map((v) => JSON.stringify(v)), width, " | ");
|
|
727
|
+
const opts = j.anyOf ?? j.oneOf;
|
|
728
|
+
if (Array.isArray(opts)) {
|
|
729
|
+
const ts = [...new Set(opts.map((o) => tsOf(o, depth, width)))];
|
|
730
|
+
return listed(ts, width, " | ", "options");
|
|
731
|
+
}
|
|
732
|
+
if (Array.isArray(j.allOf)) return j.allOf.map((o) => paren(tsOf(o, depth, width))).join(" & ");
|
|
733
|
+
if (Array.isArray(j.type)) return j.type.map((t) => tsOf({ ...j, type: t }, depth, width)).join(" | ");
|
|
734
|
+
if (j.nullable === true) return `${paren(tsOf({ ...j, nullable: false }, depth, width))} | null`;
|
|
735
|
+
switch (j.type) {
|
|
736
|
+
case "string": {
|
|
737
|
+
if (typeof j.description === "string" && /JSON text/.test(j.description)) {
|
|
738
|
+
const m = /TypeScript type: ([^\n(]+?)(?: \(its named types|\.\s*$)/.exec(j.description);
|
|
739
|
+
return m ? `string (JSON text of ${m[1].trim()})` : "string (JSON text)";
|
|
740
|
+
}
|
|
741
|
+
return typeof j.format === "string" ? `string (${j.format})` : "string";
|
|
742
|
+
}
|
|
743
|
+
case "integer":
|
|
744
|
+
return "integer";
|
|
745
|
+
case "number":
|
|
746
|
+
return "number";
|
|
747
|
+
case "boolean":
|
|
748
|
+
return "boolean";
|
|
749
|
+
case "null":
|
|
750
|
+
return "null";
|
|
751
|
+
case "array": {
|
|
752
|
+
if (Array.isArray(j.prefixItems)) return `[${j.prefixItems.map((x) => tsOf(x, depth - 1, width)).join(", ")}]`;
|
|
753
|
+
const items = j.items && typeof j.items === "object" ? tsOf(j.items, depth - 1, width) : "any";
|
|
754
|
+
return `${paren(items)}[]`;
|
|
755
|
+
}
|
|
756
|
+
case "object": {
|
|
757
|
+
const props = j.properties ?? {};
|
|
758
|
+
const keys = Object.keys(props);
|
|
759
|
+
const extra = j.additionalProperties && typeof j.additionalProperties === "object" ? j.additionalProperties : void 0;
|
|
760
|
+
if (!keys.length && !extra) return j.additionalProperties === false ? "{}" : "object";
|
|
761
|
+
if (depth <= 0) return "{\u2026}";
|
|
762
|
+
const req = new Set(j.required ?? []);
|
|
763
|
+
const parts = keys.slice(0, width).map((k) => `${IDENT.test(k) ? k : JSON.stringify(k)}${req.has(k) ? "" : "?"}: ${tsOf(props[k], depth - 1, width)}`);
|
|
764
|
+
if (keys.length > width) parts.push(`\u2026 ${keys.length - width} more`);
|
|
765
|
+
if (extra) parts.push(`[key: string]: ${tsOf(extra, depth - 1, width)}`);
|
|
766
|
+
return `{ ${parts.join("; ")} }`;
|
|
767
|
+
}
|
|
768
|
+
default:
|
|
769
|
+
return "any JSON value";
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
function paren(t) {
|
|
773
|
+
return / \| | & /.test(t) && !/^[{[(]/.test(t) ? `(${t})` : t;
|
|
774
|
+
}
|
|
775
|
+
function listed(items, width, sep, noun = "more") {
|
|
776
|
+
if (items.length <= width) return items.join(sep);
|
|
777
|
+
return `${items.slice(0, width).join(sep)}${sep}\u2026 (${items.length} ${noun === "more" ? "values" : noun})`;
|
|
778
|
+
}
|
|
779
|
+
function expectedOf(issue, info) {
|
|
780
|
+
const node = info?.node;
|
|
781
|
+
if (!node || !info) return void 0;
|
|
782
|
+
if (info.kind === "enum" || info.kind === "literal" || info.kind === "tag" || info.kind === "tool" || info.kind === "rule" || info.kind === "unknown-key" || info.kind === "not-allowed") return void 0;
|
|
783
|
+
try {
|
|
784
|
+
if (node.jsonText && node.schema) {
|
|
785
|
+
const text = node.typeText();
|
|
786
|
+
return `string (JSON text of ${text.length > 120 ? `${text.slice(0, 119)}\u2026` : text})`;
|
|
787
|
+
}
|
|
788
|
+
const t = shortType(node.json());
|
|
789
|
+
if (info.kind === "type" && /^(string|number|integer|boolean|null)$/.test(t)) return void 0;
|
|
790
|
+
return t;
|
|
791
|
+
} catch {
|
|
792
|
+
return void 0;
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
function groupKey(i) {
|
|
796
|
+
let k = i.message;
|
|
797
|
+
for (const s of i.path) k += `\0${typeof s === "number" ? "#" : s}`;
|
|
798
|
+
return k;
|
|
799
|
+
}
|
|
800
|
+
function problemsOf(issues) {
|
|
801
|
+
const out = [];
|
|
802
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
803
|
+
for (const issue of issues) {
|
|
804
|
+
const key = groupKey(issue);
|
|
805
|
+
const g = byKey.get(key);
|
|
806
|
+
if (g) {
|
|
807
|
+
g.paths.push(issue.path);
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
const p = { issue, info: infos.get(issue), paths: [issue.path] };
|
|
811
|
+
byKey.set(key, p);
|
|
812
|
+
out.push(p);
|
|
813
|
+
}
|
|
814
|
+
return out;
|
|
815
|
+
}
|
|
816
|
+
function problemText(p, f) {
|
|
817
|
+
let text = p.issue.message;
|
|
818
|
+
const kind2 = p.info?.kind;
|
|
819
|
+
if (f.terse && p.info?.candidates && (kind2 === "enum" || kind2 === "tag" || kind2 === "tool")) {
|
|
820
|
+
const n = p.info.candidates().length;
|
|
821
|
+
text = text.replace(/ one of: .*$/s, ` one of ${n} value${n === 1 ? "" : "s"}.`);
|
|
822
|
+
}
|
|
823
|
+
if (f.suggestions && p.info?.candidates) {
|
|
824
|
+
const s = suggestionText(p.issue, p.info);
|
|
825
|
+
if (s) text = text.replace(/\.$/, "") + s;
|
|
826
|
+
}
|
|
827
|
+
if (p.paths.length > 1) {
|
|
828
|
+
if (f.terse) text += ` (the same at ${p.paths.length - 1} more place${p.paths.length === 2 ? "" : "s"})`;
|
|
829
|
+
else {
|
|
830
|
+
const more = p.paths.slice(1, 3).map(modelPath);
|
|
831
|
+
const rest = p.paths.length - 1 - more.length;
|
|
832
|
+
text += ` (the same at ${more.join(", ")}${rest > 0 ? ` and ${rest} more place${rest === 1 ? "" : "s"}` : ""})`;
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
return text.length > 400 ? `${text.slice(0, 399)}\u2026` : text;
|
|
836
|
+
}
|
|
837
|
+
function suggestionText(issue, info) {
|
|
838
|
+
const cands = info.candidates();
|
|
839
|
+
if (!cands.length) return "";
|
|
840
|
+
if (info.kind === "required") {
|
|
841
|
+
const key = issue.path[issue.path.length - 1];
|
|
842
|
+
if (typeof key !== "string") return "";
|
|
843
|
+
const near2 = nearest(key, cands);
|
|
844
|
+
return near2 ? ` \u2014 you wrote \`${near2}\`; did you mean \`${key}\`?` : "";
|
|
845
|
+
}
|
|
846
|
+
const input = info.kind === "unknown-key" ? issue.path[issue.path.length - 1] : info.received;
|
|
847
|
+
if (typeof input !== "string") return "";
|
|
848
|
+
const near = rankNear(input, cands)[0];
|
|
849
|
+
return near !== void 0 && near !== input ? ` \u2014 did you mean \`${near}\`?` : "";
|
|
850
|
+
}
|
|
851
|
+
function formatErrors(issues, wire, format, label = "your answer") {
|
|
852
|
+
if (!issues.length) return "";
|
|
853
|
+
const f = isResolved(format) ? format : errorFormat(format);
|
|
854
|
+
const all = problemsOf(f.suggestions ? oneMistakeOnce(issues) : issues);
|
|
855
|
+
const outer = parsedTexts;
|
|
856
|
+
parsedTexts = /* @__PURE__ */ new Map();
|
|
857
|
+
try {
|
|
858
|
+
for (const attempt of attempts(f)) {
|
|
859
|
+
const out = render(all, wire, attempt, label);
|
|
860
|
+
if (out.length <= f.maxChars) return out;
|
|
861
|
+
}
|
|
862
|
+
const last = render(all, wire, { ...f, detail: "summary", maxErrors: 1, terse: true }, label);
|
|
863
|
+
return last.length <= f.maxChars ? last : `${last.slice(0, Math.max(0, f.maxChars - 1))}\u2026`;
|
|
864
|
+
} finally {
|
|
865
|
+
parsedTexts = outer;
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
function oneMistakeOnce(issues) {
|
|
869
|
+
let drop;
|
|
870
|
+
let checked = 0;
|
|
871
|
+
for (const i of issues) {
|
|
872
|
+
const info = infos.get(i);
|
|
873
|
+
if (info?.kind !== "required" || !info.candidates || ++checked > 50) continue;
|
|
874
|
+
const key = i.path[i.path.length - 1];
|
|
875
|
+
const near = typeof key === "string" ? nearest(key, info.candidates()) : void 0;
|
|
876
|
+
if (near !== void 0) (drop ??= /* @__PURE__ */ new Set()).add(keyOf([...i.path.slice(0, -1), near]));
|
|
877
|
+
}
|
|
878
|
+
if (!drop) return issues;
|
|
879
|
+
return issues.filter((i) => !(infos.get(i)?.kind === "unknown-key" && drop.has(keyOf(i.path))));
|
|
880
|
+
}
|
|
881
|
+
function isResolved(f) {
|
|
882
|
+
return typeof f === "object" && f !== null && "detail" in f && "maxChars" in f && "expected" in f && "context" in f && "depth" in f && "header" in f && "suggestions" in f && "maxErrors" in f;
|
|
883
|
+
}
|
|
884
|
+
function* attempts(f) {
|
|
885
|
+
for (const s of steps(f)) {
|
|
886
|
+
yield s;
|
|
887
|
+
yield { ...s, terse: true };
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
function* steps(f) {
|
|
891
|
+
let cur = f;
|
|
892
|
+
yield cur;
|
|
893
|
+
if (cur.detail === "markers" || cur.detail === "full") {
|
|
894
|
+
if (cur.expected) yield cur = { ...cur, expected: false };
|
|
895
|
+
if (cur.context > 0) yield cur = { ...cur, context: 0 };
|
|
896
|
+
if (cur.depth > 2) yield cur = { ...cur, depth: 2 };
|
|
897
|
+
while (cur.maxErrors > 1) yield cur = { ...cur, maxErrors: Math.max(1, Math.floor(cur.maxErrors / 2)) };
|
|
898
|
+
yield cur = { ...cur, detail: "list", maxErrors: f.maxErrors };
|
|
899
|
+
}
|
|
900
|
+
while (cur.maxErrors > 1) yield cur = { ...cur, maxErrors: Math.max(1, Math.floor(cur.maxErrors / 2)) };
|
|
901
|
+
if (cur.detail !== "summary") yield { ...cur, detail: "summary" };
|
|
902
|
+
}
|
|
903
|
+
function render(all, wire, f, label) {
|
|
904
|
+
const shown = all.slice(0, Math.max(1, f.maxErrors));
|
|
905
|
+
const total = all.reduce((n, p) => n + p.paths.length, 0);
|
|
906
|
+
const hiddenGroups = all.length - shown.length;
|
|
907
|
+
const hidden = all.slice(shown.length).reduce((n, p) => n + p.paths.length, 0);
|
|
908
|
+
const count = `${total} problem${total === 1 ? "" : "s"}`;
|
|
909
|
+
if (f.detail === "summary") {
|
|
910
|
+
const p = shown[0];
|
|
911
|
+
const more = total - p.paths.length;
|
|
912
|
+
return `${f.header ? `${total === 1 ? "A problem" : count} in ${label}: ` : ""}at ${modelPath(p.issue.path)}: ${problemText(p, f)}${more > 0 ? ` (and ${more} more problem${more === 1 ? "" : "s"})` : ""}`;
|
|
913
|
+
}
|
|
914
|
+
const lines = [];
|
|
915
|
+
if (f.header) lines.push(`${count} in ${label}:`);
|
|
916
|
+
if (f.detail === "list") {
|
|
917
|
+
for (const p of shown) {
|
|
918
|
+
const exp = f.expected ? expectedOf(p.issue, p.info) : void 0;
|
|
919
|
+
lines.push(`- at ${modelPath(p.issue.path)}: ${problemText(p, f)}${exp ? ` (expected: ${exp})` : ""}`);
|
|
920
|
+
}
|
|
921
|
+
} else {
|
|
922
|
+
if (f.header) lines.push("");
|
|
923
|
+
lines.push(...echo(shown, wire, f));
|
|
924
|
+
}
|
|
925
|
+
if (hidden > 0) lines.push(`\u2026 and ${hidden} more problem${hidden === 1 ? "" : "s"}${hiddenGroups > 1 ? ` (${hiddenGroups} kinds)` : ""} not shown.`);
|
|
926
|
+
return lines.join("\n");
|
|
927
|
+
}
|
|
928
|
+
var keyOf = (path) => {
|
|
929
|
+
let k = "";
|
|
930
|
+
for (const s of path) k += `${typeof s === "number" ? "#" : "$"}${s}\0`;
|
|
931
|
+
return k;
|
|
932
|
+
};
|
|
933
|
+
function cmpPath(a, b) {
|
|
934
|
+
for (let i = 0; i < Math.min(a.length, b.length); i++) {
|
|
935
|
+
const x = a[i];
|
|
936
|
+
const y = b[i];
|
|
937
|
+
if (x === y) continue;
|
|
938
|
+
if (typeof x === "number" && typeof y === "number") return x - y;
|
|
939
|
+
return String(x) < String(y) ? -1 : 1;
|
|
940
|
+
}
|
|
941
|
+
return a.length - b.length;
|
|
942
|
+
}
|
|
943
|
+
function commonPrefix(a, b) {
|
|
944
|
+
const out = [];
|
|
945
|
+
for (let i = 0; i < Math.min(a.length, b.length) && a[i] === b[i]; i++) out.push(a[i]);
|
|
946
|
+
return out;
|
|
947
|
+
}
|
|
948
|
+
var levels = (path) => path.filter((s) => s !== "(json)").length;
|
|
949
|
+
function echo(shown, wire, f) {
|
|
950
|
+
const located = [];
|
|
951
|
+
const unplaced = [];
|
|
952
|
+
for (const p of shown) {
|
|
953
|
+
const path = p.issue.path;
|
|
954
|
+
const kind2 = p.info?.kind;
|
|
955
|
+
if (wire === void 0) unplaced.push(p);
|
|
956
|
+
else if (valueAt(wire, path) !== ABSENT) {
|
|
957
|
+
located.push({ p, at: path, where: kind2 === "unknown-key" || kind2 === "not-allowed" ? "key" : "value" });
|
|
958
|
+
} else if (path.length && isContainer(valueAt(wire, path.slice(0, -1)))) {
|
|
959
|
+
located.push({ p, at: path.slice(0, -1), where: "missing" });
|
|
960
|
+
} else unplaced.push(p);
|
|
961
|
+
}
|
|
962
|
+
located.sort((x, y) => cmpPath(x.p.issue.path, y.p.issue.path));
|
|
963
|
+
const sections = [];
|
|
964
|
+
const anchorFor = (path) => {
|
|
965
|
+
const out2 = [];
|
|
966
|
+
for (const seg of path) {
|
|
967
|
+
if (levels(path) - levels(out2) <= f.depth) break;
|
|
968
|
+
out2.push(seg);
|
|
969
|
+
}
|
|
970
|
+
return out2;
|
|
971
|
+
};
|
|
972
|
+
for (const l of located) {
|
|
973
|
+
const cur = sections[sections.length - 1];
|
|
974
|
+
if (cur) {
|
|
975
|
+
const cp = commonPrefix(cur.anchor, l.at);
|
|
976
|
+
const fits = [...cur.members, l].every((m) => levels(m.at) - levels(cp) <= f.depth + 1);
|
|
977
|
+
if (fits) {
|
|
978
|
+
cur.anchor = cp;
|
|
979
|
+
cur.members.push(l);
|
|
980
|
+
continue;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
sections.push({ anchor: anchorFor(l.at), members: [l] });
|
|
984
|
+
}
|
|
985
|
+
const out = [];
|
|
986
|
+
for (const s of sections) {
|
|
987
|
+
let anchor = s.anchor;
|
|
988
|
+
while (anchor.length && valueAt(wire, anchor) === ABSENT) anchor = anchor.slice(0, -1);
|
|
989
|
+
const marks = /* @__PURE__ */ new Map();
|
|
990
|
+
const below = /* @__PURE__ */ new Map();
|
|
991
|
+
for (const m of s.members) {
|
|
992
|
+
const k = keyOf(m.at);
|
|
993
|
+
const list = marks.get(k);
|
|
994
|
+
if (list) list.push({ p: m.p, where: m.where });
|
|
995
|
+
else marks.set(k, [{ p: m.p, where: m.where }]);
|
|
996
|
+
for (let i = anchor.length; i < m.at.length; i++) {
|
|
997
|
+
const pk = keyOf(m.at.slice(0, i));
|
|
998
|
+
const kids = below.get(pk);
|
|
999
|
+
if (kids) kids.add(m.at[i]);
|
|
1000
|
+
else below.set(pk, /* @__PURE__ */ new Set([m.at[i]]));
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
if (out.length) out.push("");
|
|
1004
|
+
if (anchor.length) out.push(`at ${modelPath(anchor)}:`);
|
|
1005
|
+
new Echo(marks, below, f, out, anchor.length).node(valueAt(wire, anchor), anchor, "", "", "");
|
|
1006
|
+
}
|
|
1007
|
+
for (const p of unplaced) out.push(`- at ${modelPath(p.issue.path)}: ${problemText(p, f)}`);
|
|
1008
|
+
return out;
|
|
1009
|
+
}
|
|
1010
|
+
var isContainer = (v) => typeof v === "object" && v !== null;
|
|
1011
|
+
function relPath(rest) {
|
|
1012
|
+
if (!rest.length) return "\u2026";
|
|
1013
|
+
const head = rest[0];
|
|
1014
|
+
const text = modelPath(rest);
|
|
1015
|
+
if (head === "(json)") return `\u2026 \u2192 ${text.replace(/^\(root\) → /, "")}`;
|
|
1016
|
+
return typeof head === "number" || !IDENT.test(head) ? `\u2026${text}` : `\u2026.${text}`;
|
|
1017
|
+
}
|
|
1018
|
+
var Echo = class {
|
|
1019
|
+
constructor(marks, below, f, out, from = 0) {
|
|
1020
|
+
this.marks = marks;
|
|
1021
|
+
this.below = below;
|
|
1022
|
+
this.f = f;
|
|
1023
|
+
this.out = out;
|
|
1024
|
+
this.from = from;
|
|
1025
|
+
}
|
|
1026
|
+
marks;
|
|
1027
|
+
below;
|
|
1028
|
+
f;
|
|
1029
|
+
out;
|
|
1030
|
+
from;
|
|
1031
|
+
node(v, path, indent, prefix, comma) {
|
|
1032
|
+
const k = keyOf(path);
|
|
1033
|
+
const deeper = this.below.has(k);
|
|
1034
|
+
if (typeof v === "string" && deeper) {
|
|
1035
|
+
const parsed = parseOr(v);
|
|
1036
|
+
if (parsed !== ABSENT) {
|
|
1037
|
+
const jp = [...path, "(json)"];
|
|
1038
|
+
const jk = keyOf(jp);
|
|
1039
|
+
if (this.marks.has(jk) || this.below.has(jk)) return this.node(parsed, jp, indent, `${prefix}/* JSON text */ `, comma);
|
|
1040
|
+
return this.node(parsed, path, indent, prefix, comma);
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
const marks = this.marks.get(k) ?? [];
|
|
1044
|
+
const open = isContainer(v) && (deeper || marks.some((m) => m.where === "missing"));
|
|
1045
|
+
if (!open) {
|
|
1046
|
+
const text = inline(v, 60);
|
|
1047
|
+
this.out.push(indent + prefix + text + comma);
|
|
1048
|
+
for (const m of marks) {
|
|
1049
|
+
if (m.where === "key") this.mark(m.p, indent.length, prefix.length + text.length);
|
|
1050
|
+
else this.mark(m.p, indent.length + prefix.length, text.length);
|
|
1051
|
+
}
|
|
1052
|
+
return;
|
|
1053
|
+
}
|
|
1054
|
+
const arr = Array.isArray(v);
|
|
1055
|
+
this.out.push(`${indent}${prefix}${arr ? "[" : "{"}`);
|
|
1056
|
+
for (const m of marks) this.mark(m.p, indent.length + prefix.length, 1);
|
|
1057
|
+
const inner = `${indent} `;
|
|
1058
|
+
if (arr) this.items(v, path, inner);
|
|
1059
|
+
else this.keys(v, path, inner);
|
|
1060
|
+
this.out.push(`${indent}${arr ? "]" : "}"}${comma}`);
|
|
1061
|
+
}
|
|
1062
|
+
keys(obj, path, indent) {
|
|
1063
|
+
const keys = Object.keys(obj);
|
|
1064
|
+
const kids = this.below.get(keyOf(path));
|
|
1065
|
+
const on = keys.filter((key) => kids?.has(key));
|
|
1066
|
+
const others = keys.filter((key) => !on.includes(key));
|
|
1067
|
+
const short = new Set(others.filter((key) => inline(obj[key], 40).length <= 40 && !isContainer(obj[key])).slice(0, this.f.context));
|
|
1068
|
+
for (const key of others) if (short.size < this.f.context && !short.has(key)) short.add(key);
|
|
1069
|
+
const show = keys.filter((key) => on.includes(key) || short.has(key));
|
|
1070
|
+
const elided = keys.length - show.length;
|
|
1071
|
+
show.forEach((key, i) => {
|
|
1072
|
+
const last = i === show.length - 1 && !elided;
|
|
1073
|
+
this.node(obj[key], [...path, key], indent, `${JSON.stringify(key)}: `, last ? "" : ",");
|
|
1074
|
+
});
|
|
1075
|
+
if (elided) this.out.push(`${indent}\u2026 ${elided} more key${elided === 1 ? "" : "s"}`);
|
|
1076
|
+
}
|
|
1077
|
+
items(arr, path, indent) {
|
|
1078
|
+
const on = /* @__PURE__ */ new Set();
|
|
1079
|
+
for (const i of this.below.get(keyOf(path)) ?? []) if (typeof i === "number" && i < arr.length) on.add(i);
|
|
1080
|
+
const whole = arr.length - on.size <= this.f.context && arr.every((x, i) => on.has(i) || inline(x, 40).length <= 40);
|
|
1081
|
+
let skipped = 0;
|
|
1082
|
+
let elidedAny = false;
|
|
1083
|
+
const flush = () => {
|
|
1084
|
+
if (!skipped) return;
|
|
1085
|
+
this.out.push(`${indent}\u2026 ${skipped} item${skipped === 1 ? "" : "s"}`);
|
|
1086
|
+
skipped = 0;
|
|
1087
|
+
elidedAny = true;
|
|
1088
|
+
};
|
|
1089
|
+
for (let i = 0; i < arr.length; i++) {
|
|
1090
|
+
if (!whole && !on.has(i)) {
|
|
1091
|
+
skipped++;
|
|
1092
|
+
continue;
|
|
1093
|
+
}
|
|
1094
|
+
flush();
|
|
1095
|
+
const last = i === arr.length - 1;
|
|
1096
|
+
const tag = elidedAny || !whole && i > 0 ? `/* ${i} */ ` : "";
|
|
1097
|
+
this.node(arr[i], [...path, i], indent, tag, last ? "" : ",");
|
|
1098
|
+
}
|
|
1099
|
+
flush();
|
|
1100
|
+
}
|
|
1101
|
+
mark(p, col, width) {
|
|
1102
|
+
const w = Math.max(1, Math.min(width, 40));
|
|
1103
|
+
const text = `${this.from ? relPath(p.issue.path.slice(this.from)) : modelPath(p.issue.path)}: ${problemText(p, this.f)}`;
|
|
1104
|
+
this.out.push(`${" ".repeat(col)}${"^".repeat(w)} ${text}`);
|
|
1105
|
+
const exp = this.f.expected ? expectedOf(p.issue, p.info) : void 0;
|
|
1106
|
+
if (exp) this.out.push(`${" ".repeat(col + w + 1)}expected: ${exp}`);
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
function inline(v, max) {
|
|
1110
|
+
if (typeof v === "string") {
|
|
1111
|
+
const s = JSON.stringify(v);
|
|
1112
|
+
return s.length <= max ? s : `${s.slice(0, max - 2)}\u2026"`;
|
|
1113
|
+
}
|
|
1114
|
+
if (!isContainer(v)) return v === void 0 ? "undefined" : JSON.stringify(v);
|
|
1115
|
+
const small = boundedJson(v, max);
|
|
1116
|
+
if (small !== void 0) return small;
|
|
1117
|
+
if (Array.isArray(v)) return `[\u2026 ${v.length} item${v.length === 1 ? "" : "s"}]`;
|
|
1118
|
+
const n = Object.keys(v).length;
|
|
1119
|
+
return `{\u2026 ${n} key${n === 1 ? "" : "s"}}`;
|
|
1120
|
+
}
|
|
1121
|
+
function boundedJson(v, max) {
|
|
1122
|
+
let out = "";
|
|
1123
|
+
const go = (x) => {
|
|
1124
|
+
if (out.length > max) return false;
|
|
1125
|
+
if (Array.isArray(x)) {
|
|
1126
|
+
out += "[";
|
|
1127
|
+
for (let i = 0; i < x.length; i++) {
|
|
1128
|
+
if (i) out += ",";
|
|
1129
|
+
if (!go(x[i])) return false;
|
|
1130
|
+
}
|
|
1131
|
+
out += "]";
|
|
1132
|
+
return out.length <= max;
|
|
1133
|
+
}
|
|
1134
|
+
if (isContainer(x)) {
|
|
1135
|
+
out += "{";
|
|
1136
|
+
let first = true;
|
|
1137
|
+
for (const k of Object.keys(x)) {
|
|
1138
|
+
const val = x[k];
|
|
1139
|
+
if (val === void 0) continue;
|
|
1140
|
+
if (!first) out += ",";
|
|
1141
|
+
first = false;
|
|
1142
|
+
out += `${JSON.stringify(k)}:`;
|
|
1143
|
+
if (!go(val)) return false;
|
|
1144
|
+
}
|
|
1145
|
+
out += "}";
|
|
1146
|
+
return out.length <= max;
|
|
1147
|
+
}
|
|
1148
|
+
out += x === void 0 ? "null" : JSON.stringify(x);
|
|
1149
|
+
return out.length <= max;
|
|
1150
|
+
};
|
|
1151
|
+
return go(v) ? out : void 0;
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
// src/render.ts
|
|
1155
|
+
var Rejection = class {
|
|
1156
|
+
constructor(issues) {
|
|
1157
|
+
this.issues = issues;
|
|
1158
|
+
}
|
|
1159
|
+
issues;
|
|
1160
|
+
};
|
|
1161
|
+
function newStats() {
|
|
1162
|
+
return { objects: 0, arrays: 0, edits: 0, parsed: 0, repaired: 0 };
|
|
1163
|
+
}
|
|
1164
|
+
function formatPath(path) {
|
|
1165
|
+
let out = "";
|
|
1166
|
+
for (const seg of path) {
|
|
1167
|
+
out += typeof seg === "number" ? `[${seg}]` : /^[A-Za-z_$][\w$]*$/.test(seg) ? out ? `.${seg}` : seg : `[${JSON.stringify(seg)}]`;
|
|
1168
|
+
}
|
|
1169
|
+
return out || "(root)";
|
|
1170
|
+
}
|
|
1171
|
+
var COUNTED = Object.freeze({ path: [], codePath: [], message: "" });
|
|
1172
|
+
var DRY_STATS = newStats();
|
|
1173
|
+
var ABSENT2 = /* @__PURE__ */ Symbol("absent");
|
|
1174
|
+
var ORDER = /* @__PURE__ */ Symbol("order");
|
|
1175
|
+
var spareUndo;
|
|
1176
|
+
var Cx = class _Cx {
|
|
1177
|
+
constructor(inPlace, dry, stats, repair = true, countOnly = false) {
|
|
1178
|
+
this.inPlace = inPlace;
|
|
1179
|
+
this.dry = dry;
|
|
1180
|
+
this.stats = stats;
|
|
1181
|
+
this.repair = repair;
|
|
1182
|
+
this.countOnly = countOnly;
|
|
1183
|
+
}
|
|
1184
|
+
inPlace;
|
|
1185
|
+
dry;
|
|
1186
|
+
stats;
|
|
1187
|
+
repair;
|
|
1188
|
+
countOnly;
|
|
1189
|
+
errors = [];
|
|
1190
|
+
/**
|
|
1191
|
+
* In-place writes, as (container, key, old value) triples, so a failed
|
|
1192
|
+
* decode can put the model's answer back as it was sent (the echo shows
|
|
1193
|
+
* the wire, not a half-decoded mix). Only kept when the message echoes.
|
|
1194
|
+
*/
|
|
1195
|
+
undo;
|
|
1196
|
+
undoN = 0;
|
|
1197
|
+
wire = [];
|
|
1198
|
+
code = [];
|
|
1199
|
+
wd = 0;
|
|
1200
|
+
cd = 0;
|
|
1201
|
+
/**
|
|
1202
|
+
* Record a problem at the current path. `kind` and `candidates` drive the
|
|
1203
|
+
* model's message ("did you mean"); `received` is what the model wrote
|
|
1204
|
+
* there; `node` is the expected type when it isn't the failing node (which
|
|
1205
|
+
* claims its issues as the run unwinds: nothing is tracked while it passes).
|
|
1206
|
+
*/
|
|
1207
|
+
fail(message, kind2 = "other", received, candidates, node) {
|
|
1208
|
+
if (this.countOnly) {
|
|
1209
|
+
this.errors.push(COUNTED);
|
|
1210
|
+
return;
|
|
1211
|
+
}
|
|
1212
|
+
const issue = { path: this.wire.slice(0, this.wd), codePath: this.code.slice(0, this.cd), message };
|
|
1213
|
+
this.errors.push(issue);
|
|
1214
|
+
recordIssue(issue, { kind: kind2, node, received, candidates });
|
|
1215
|
+
}
|
|
1216
|
+
/** Record a problem at `rel` below the current path (code-shape segments, used for both paths). */
|
|
1217
|
+
failAt(rel, message, kind2 = "rule") {
|
|
1218
|
+
if (!rel.length) return this.fail(message, kind2);
|
|
1219
|
+
if (this.countOnly) {
|
|
1220
|
+
this.errors.push(COUNTED);
|
|
1221
|
+
return;
|
|
1222
|
+
}
|
|
1223
|
+
const issue = { path: [...this.wire.slice(0, this.wd), ...rel], codePath: [...this.code.slice(0, this.cd), ...rel], message };
|
|
1224
|
+
this.errors.push(issue);
|
|
1225
|
+
recordIssue(issue, { kind: kind2 });
|
|
1226
|
+
}
|
|
1227
|
+
enter(wire, code = wire) {
|
|
1228
|
+
this.wire[this.wd++] = wire;
|
|
1229
|
+
if (code !== null) this.code[this.cd++] = code;
|
|
1230
|
+
}
|
|
1231
|
+
leave(code = true) {
|
|
1232
|
+
this.wd--;
|
|
1233
|
+
if (code) this.cd--;
|
|
1234
|
+
}
|
|
1235
|
+
/**
|
|
1236
|
+
* A dry sibling (for union option tests). Count-only by default: only
|
|
1237
|
+
* whether it fails is read. With `issues`, its failures are real issues
|
|
1238
|
+
* at the current paths (they are copied into this context).
|
|
1239
|
+
*/
|
|
1240
|
+
dryRun(issues = false) {
|
|
1241
|
+
if (!issues) return new _Cx(false, true, DRY_STATS, this.repair, true);
|
|
1242
|
+
const d = new _Cx(false, true, DRY_STATS, this.repair);
|
|
1243
|
+
for (let i = 0; i < this.wd; i++) d.wire[d.wd++] = this.wire[i];
|
|
1244
|
+
for (let i = 0; i < this.cd; i++) d.code[d.cd++] = this.code[i];
|
|
1245
|
+
return d;
|
|
1246
|
+
}
|
|
1247
|
+
/**
|
|
1248
|
+
* Before an in-place write of `key`: remember its old value (when keeping
|
|
1249
|
+
* the undo log). Before the first delete from an object, its key order too:
|
|
1250
|
+
* a key put back after a delete would otherwise come last.
|
|
1251
|
+
*/
|
|
1252
|
+
saving(container, key, deleting = false) {
|
|
1253
|
+
const u = this.undo;
|
|
1254
|
+
if (!u) return;
|
|
1255
|
+
if (deleting && this.ordered !== container) {
|
|
1256
|
+
this.ordered = container;
|
|
1257
|
+
u[this.undoN++] = container;
|
|
1258
|
+
u[this.undoN++] = ORDER;
|
|
1259
|
+
u[this.undoN++] = Object.keys(container);
|
|
1260
|
+
}
|
|
1261
|
+
const has2 = Object.prototype.hasOwnProperty.call(container, key);
|
|
1262
|
+
u[this.undoN++] = container;
|
|
1263
|
+
u[this.undoN++] = key;
|
|
1264
|
+
u[this.undoN++] = has2 ? container[key] : ABSENT2;
|
|
1265
|
+
}
|
|
1266
|
+
ordered;
|
|
1267
|
+
/** Put every in-place write back, newest first: the caller's value is as the model sent it. */
|
|
1268
|
+
restore() {
|
|
1269
|
+
const u = this.undo;
|
|
1270
|
+
if (!u) return;
|
|
1271
|
+
for (let i = this.undoN - 3; i >= 0; i -= 3) {
|
|
1272
|
+
const c = u[i];
|
|
1273
|
+
const k = u[i + 1];
|
|
1274
|
+
const old = u[i + 2];
|
|
1275
|
+
if (k === ORDER) {
|
|
1276
|
+
for (const key of old) {
|
|
1277
|
+
const v = c[key];
|
|
1278
|
+
delete c[key];
|
|
1279
|
+
c[key] = v;
|
|
1280
|
+
}
|
|
1281
|
+
} else if (old === ABSENT2) delete c[k];
|
|
1282
|
+
else c[k] = old;
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
/** Start keeping the undo log (a reused buffer). */
|
|
1286
|
+
keepUndo() {
|
|
1287
|
+
this.undo = spareUndo ?? [];
|
|
1288
|
+
spareUndo = void 0;
|
|
1289
|
+
this.undoN = 0;
|
|
1290
|
+
}
|
|
1291
|
+
/** Drop the undo log's references and hand the buffer back. */
|
|
1292
|
+
releaseUndo() {
|
|
1293
|
+
const u = this.undo;
|
|
1294
|
+
if (!u) return;
|
|
1295
|
+
for (let i = 0; i < this.undoN; i++) u[i] = void 0;
|
|
1296
|
+
this.undo = void 0;
|
|
1297
|
+
this.undoN = 0;
|
|
1298
|
+
if (u.length <= 65536) spareUndo = u;
|
|
1299
|
+
}
|
|
1300
|
+
};
|
|
1301
|
+
var Node = class {
|
|
1302
|
+
constructor(impl, compiler) {
|
|
1303
|
+
this.impl = impl;
|
|
1304
|
+
this.compiler = compiler;
|
|
1305
|
+
}
|
|
1306
|
+
impl;
|
|
1307
|
+
compiler;
|
|
1308
|
+
/** True when decoding or encoding may change this subtree (its own change or any dependency's). */
|
|
1309
|
+
needs = false;
|
|
1310
|
+
schema;
|
|
1311
|
+
/** An outer wrapper (e.g. `.optional()` around a field) whose metadata also applies. */
|
|
1312
|
+
outer;
|
|
1313
|
+
/** The model writes this value as a string of JSON text (an escape, or "any" on a dialect without it). */
|
|
1314
|
+
jsonText = false;
|
|
1315
|
+
_json;
|
|
1316
|
+
get own() {
|
|
1317
|
+
return !!this.impl?.own;
|
|
1318
|
+
}
|
|
1319
|
+
get deps() {
|
|
1320
|
+
return this.impl?.deps ?? [];
|
|
1321
|
+
}
|
|
1322
|
+
json() {
|
|
1323
|
+
if (!this._json) this._json = this.compiler.decorate(this, this.impl.emit());
|
|
1324
|
+
return this._json;
|
|
1325
|
+
}
|
|
1326
|
+
run(value, cx) {
|
|
1327
|
+
const errors = cx.errors;
|
|
1328
|
+
const before = errors.length;
|
|
1329
|
+
const out = this.impl.run(value, cx);
|
|
1330
|
+
if (errors.length === before) {
|
|
1331
|
+
if (this.schema?.checks.length) this.check(out, cx, this.schema);
|
|
1332
|
+
if (this.outer?.checks.length && errors.length === before) this.check(out, cx, this.outer);
|
|
1333
|
+
if (errors.length === before) return out;
|
|
1334
|
+
}
|
|
1335
|
+
if (!cx.countOnly) claimIssues(errors, before, this);
|
|
1336
|
+
return out;
|
|
1337
|
+
}
|
|
1338
|
+
check(value, cx, schema) {
|
|
1339
|
+
if (!schema) return;
|
|
1340
|
+
for (const c of schema.checks) {
|
|
1341
|
+
const r = c.fn(value);
|
|
1342
|
+
if (r === true) continue;
|
|
1343
|
+
if (Array.isArray(r)) {
|
|
1344
|
+
for (const m of r) {
|
|
1345
|
+
if (typeof m === "string") cx.fail(m, "rule");
|
|
1346
|
+
else cx.failAt(m.path, m.message, "rule");
|
|
1347
|
+
}
|
|
1348
|
+
continue;
|
|
1349
|
+
}
|
|
1350
|
+
cx.fail(typeof r === "string" ? r : c.message ?? "Failed a check.", "rule");
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
/** This node's schema as TypeScript-like text (the code shape; for spots written as JSON text). */
|
|
1354
|
+
typeText() {
|
|
1355
|
+
return this.schema ? this.schema.print(new Printer(this.compiler.env)) : "any JSON value";
|
|
1356
|
+
}
|
|
1357
|
+
encode(value, stats = newStats()) {
|
|
1358
|
+
return this.needs ? this.impl.encode(value, stats) : value;
|
|
1359
|
+
}
|
|
1360
|
+
child(seg) {
|
|
1361
|
+
return this.impl?.child?.(seg);
|
|
1362
|
+
}
|
|
1363
|
+
};
|
|
1364
|
+
var Printer = class {
|
|
1365
|
+
constructor(env) {
|
|
1366
|
+
this.env = env;
|
|
1367
|
+
}
|
|
1368
|
+
env;
|
|
1369
|
+
names = /* @__PURE__ */ new Set();
|
|
1370
|
+
print(s) {
|
|
1371
|
+
return s.print(this);
|
|
1372
|
+
}
|
|
1373
|
+
ref(name) {
|
|
1374
|
+
this.names.add(name);
|
|
1375
|
+
return name;
|
|
1376
|
+
}
|
|
1377
|
+
/** The named types printed so far. */
|
|
1378
|
+
used() {
|
|
1379
|
+
return [...this.names];
|
|
1380
|
+
}
|
|
1381
|
+
/** `type X = …` for these named types and every named type they reach. */
|
|
1382
|
+
definitions(names) {
|
|
1383
|
+
for (const n of names) this.names.add(n);
|
|
1384
|
+
const lines = [];
|
|
1385
|
+
const done = /* @__PURE__ */ new Set();
|
|
1386
|
+
for (let again = true; again; ) {
|
|
1387
|
+
again = false;
|
|
1388
|
+
for (const n of [...this.names]) {
|
|
1389
|
+
if (done.has(n)) continue;
|
|
1390
|
+
done.add(n);
|
|
1391
|
+
again = true;
|
|
1392
|
+
const def = this.env.get(n);
|
|
1393
|
+
if (def) lines.push(`type ${n} = ${def.print(this)}`);
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
return lines.join("\n");
|
|
1397
|
+
}
|
|
1398
|
+
/** The shape plus a `type X = …` line for every named type it reaches. */
|
|
1399
|
+
full(s) {
|
|
1400
|
+
const head = this.print(s);
|
|
1401
|
+
const lines = [];
|
|
1402
|
+
const done = /* @__PURE__ */ new Set();
|
|
1403
|
+
for (let again = true; again; ) {
|
|
1404
|
+
again = false;
|
|
1405
|
+
for (const n of [...this.names]) {
|
|
1406
|
+
if (done.has(n)) continue;
|
|
1407
|
+
done.add(n);
|
|
1408
|
+
again = true;
|
|
1409
|
+
const def = this.env.get(n);
|
|
1410
|
+
if (def) lines.push(`type ${n} = ${def.print(this)}`);
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
return lines.length ? `${head}
|
|
1414
|
+
where
|
|
1415
|
+
${lines.join("\n")}` : head;
|
|
1416
|
+
}
|
|
1417
|
+
};
|
|
1418
|
+
var CONTAINERS = /* @__PURE__ */ new Set(["object", "array", "record", "tuple"]);
|
|
1419
|
+
var dynamicBelow = /* @__PURE__ */ new WeakMap();
|
|
1420
|
+
function hasDependent(s) {
|
|
1421
|
+
let d = dynamicBelow.get(s);
|
|
1422
|
+
if (d === void 0) {
|
|
1423
|
+
d = s.kind === "dependent" || s.children().some(hasDependent);
|
|
1424
|
+
dynamicBelow.set(s, d);
|
|
1425
|
+
}
|
|
1426
|
+
return d;
|
|
1427
|
+
}
|
|
1428
|
+
var nesting = /* @__PURE__ */ new WeakMap();
|
|
1429
|
+
function nestingOf(s) {
|
|
1430
|
+
let n = nesting.get(s);
|
|
1431
|
+
if (n === void 0) {
|
|
1432
|
+
n = (CONTAINERS.has(s.kind) ? 1 : 0) + Math.max(0, ...s.children().map(nestingOf));
|
|
1433
|
+
nesting.set(s, n);
|
|
1434
|
+
}
|
|
1435
|
+
return n;
|
|
1436
|
+
}
|
|
1437
|
+
var refFreeCache = /* @__PURE__ */ new WeakMap();
|
|
1438
|
+
var sharedCompilers = /* @__PURE__ */ new WeakMap();
|
|
1439
|
+
function sharedCompiler(profile) {
|
|
1440
|
+
let c = sharedCompilers.get(profile);
|
|
1441
|
+
if (!c) sharedCompilers.set(profile, c = new Compiler(profile, EMPTY_ENV, sharedLenient, false, true));
|
|
1442
|
+
return c;
|
|
1443
|
+
}
|
|
1444
|
+
var EMPTY_ENV = /* @__PURE__ */ new Map();
|
|
1445
|
+
var sharedLenientRendered;
|
|
1446
|
+
function sharedLenient() {
|
|
1447
|
+
if (!sharedLenientRendered) {
|
|
1448
|
+
const c = sharedCompiler(LENIENT);
|
|
1449
|
+
sharedLenientRendered = new Rendered(c, c.node({ emit: () => ({}), run: (v) => v, encode: (v) => v }));
|
|
1450
|
+
}
|
|
1451
|
+
return sharedLenientRendered;
|
|
1452
|
+
}
|
|
1453
|
+
var INLINE_BUDGET = 4e3;
|
|
1454
|
+
var InlineBudgetExceeded = class extends Error {
|
|
1455
|
+
};
|
|
1456
|
+
var Compiler = class {
|
|
1457
|
+
constructor(profile, env, lenient, inlineOnce = false, shared = false) {
|
|
1458
|
+
this.profile = profile;
|
|
1459
|
+
this.env = env;
|
|
1460
|
+
this.lenient = lenient;
|
|
1461
|
+
this.inlineOnce = inlineOnce;
|
|
1462
|
+
this.shared = shared;
|
|
1463
|
+
this.view = viewOf(profile);
|
|
1464
|
+
}
|
|
1465
|
+
profile;
|
|
1466
|
+
env;
|
|
1467
|
+
lenient;
|
|
1468
|
+
inlineOnce;
|
|
1469
|
+
shared;
|
|
1470
|
+
nodes = [];
|
|
1471
|
+
/** Named types emitted into `$defs` (defs mode). */
|
|
1472
|
+
defs = /* @__PURE__ */ new Map();
|
|
1473
|
+
/** Named types the JSON-text escapes mention: defined once, in the root description. */
|
|
1474
|
+
glossary = /* @__PURE__ */ new Set();
|
|
1475
|
+
/** Without `$defs`: recursive named types inlined so far (`inlineOnce` mode). */
|
|
1476
|
+
inlined = /* @__PURE__ */ new Set();
|
|
1477
|
+
recursive = /* @__PURE__ */ new Map();
|
|
1478
|
+
view;
|
|
1479
|
+
/** Named types being compiled, with the guard level at their start. */
|
|
1480
|
+
stack = [];
|
|
1481
|
+
depth = 0;
|
|
1482
|
+
/** How many optional / nullable / may-be-empty containers enclose the current position. */
|
|
1483
|
+
guard = 0;
|
|
1484
|
+
/** Does a named type reach itself? */
|
|
1485
|
+
isRecursive(name) {
|
|
1486
|
+
let r = this.recursive.get(name);
|
|
1487
|
+
if (r === void 0) {
|
|
1488
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1489
|
+
const stack = [...this.env.get(name)?.refNames() ?? []];
|
|
1490
|
+
r = false;
|
|
1491
|
+
while (stack.length) {
|
|
1492
|
+
const n = stack.pop();
|
|
1493
|
+
if (n === name) {
|
|
1494
|
+
r = true;
|
|
1495
|
+
break;
|
|
1496
|
+
}
|
|
1497
|
+
if (seen.has(n)) continue;
|
|
1498
|
+
seen.add(n);
|
|
1499
|
+
stack.push(...this.env.get(n)?.refNames() ?? []);
|
|
1500
|
+
}
|
|
1501
|
+
this.recursive.set(name, r);
|
|
1502
|
+
}
|
|
1503
|
+
return r;
|
|
1504
|
+
}
|
|
1505
|
+
node(impl) {
|
|
1506
|
+
return new Node(impl, this);
|
|
1507
|
+
}
|
|
1508
|
+
/** Compile a schema; `outer` is a wrapper whose metadata/checks also apply (an optional field). */
|
|
1509
|
+
compile(s, outer) {
|
|
1510
|
+
if (this.profile.audience !== "people" && s.meta.forModels) {
|
|
1511
|
+
const { forModels, ...rest } = s.meta;
|
|
1512
|
+
const m = forModels;
|
|
1513
|
+
s = m.meta.description === void 0 && rest.description !== void 0 ? m.describe(rest.description) : m;
|
|
1514
|
+
}
|
|
1515
|
+
const container = CONTAINERS.has(s.kind);
|
|
1516
|
+
if (container && this.profile.maxDepth !== void 0 && this.depth >= this.profile.maxDepth) {
|
|
1517
|
+
return this.escape(s, `Nested too deep for this model to describe directly.`);
|
|
1518
|
+
}
|
|
1519
|
+
const cacheable = !outer && s.refNames().size === 0 && !hasDependent(s) && (this.profile.maxDepth === void 0 || this.depth + nestingOf(s) < this.profile.maxDepth);
|
|
1520
|
+
if (cacheable) {
|
|
1521
|
+
const hit = refFreeCache.get(s)?.get(this.profile.id);
|
|
1522
|
+
if (hit) return hit;
|
|
1523
|
+
if (!this.shared) {
|
|
1524
|
+
const shared = sharedCompiler(this.profile);
|
|
1525
|
+
const n2 = shared.compile(s);
|
|
1526
|
+
shared.finish();
|
|
1527
|
+
return n2;
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
if (container) this.depth++;
|
|
1531
|
+
const n = s.compile(this);
|
|
1532
|
+
if (container) this.depth--;
|
|
1533
|
+
n.schema = s;
|
|
1534
|
+
n.outer = outer;
|
|
1535
|
+
this.nodes.push(n);
|
|
1536
|
+
if (cacheable) {
|
|
1537
|
+
let m = refFreeCache.get(s);
|
|
1538
|
+
if (!m) refFreeCache.set(s, m = /* @__PURE__ */ new Map());
|
|
1539
|
+
m.set(this.profile.id, n);
|
|
1540
|
+
}
|
|
1541
|
+
return n;
|
|
1542
|
+
}
|
|
1543
|
+
/** Compile below a position the value may skip (optional, nullable, an array that may be empty). */
|
|
1544
|
+
guarded(s, outer) {
|
|
1545
|
+
this.guard++;
|
|
1546
|
+
try {
|
|
1547
|
+
return this.compile(s, outer);
|
|
1548
|
+
} finally {
|
|
1549
|
+
this.guard--;
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
/** A use of a named type. */
|
|
1553
|
+
ref(name) {
|
|
1554
|
+
const s = this.env.get(name);
|
|
1555
|
+
if (!s) throw new SchemaDefinitionError(`ref "${name}" is not defined (the chain's types should have prevented this).`);
|
|
1556
|
+
const p = this.profile;
|
|
1557
|
+
const open = this.stack.find((e) => e.name === name);
|
|
1558
|
+
if (open) {
|
|
1559
|
+
const allowed = p.defs && (p.recursion === true || p.recursion === "guarded" && this.guard > open.guard);
|
|
1560
|
+
if (allowed) return this.defRef(name, this.defs.get(name));
|
|
1561
|
+
return this.escape(s, `"${name}" contains itself, which this model cannot describe directly.`, name);
|
|
1562
|
+
}
|
|
1563
|
+
if (p.defs) {
|
|
1564
|
+
const existing = this.defs.get(name);
|
|
1565
|
+
if (existing) return this.defRef(name, existing);
|
|
1566
|
+
const target = new DefTarget(this);
|
|
1567
|
+
this.defs.set(name, target);
|
|
1568
|
+
this.stack.push({ name, guard: this.guard });
|
|
1569
|
+
target.target = this.compile(s);
|
|
1570
|
+
this.stack.pop();
|
|
1571
|
+
this.nodes.push(target);
|
|
1572
|
+
return this.defRef(name, target);
|
|
1573
|
+
}
|
|
1574
|
+
if (this.inlineOnce && this.isRecursive(name)) {
|
|
1575
|
+
if (this.inlined.has(name)) return this.escape(s, `"${name}" is written out once elsewhere in this schema.`, name);
|
|
1576
|
+
this.inlined.add(name);
|
|
1577
|
+
} else if (!this.inlineOnce && this.nodes.length > INLINE_BUDGET) {
|
|
1578
|
+
throw new InlineBudgetExceeded();
|
|
1579
|
+
}
|
|
1580
|
+
this.stack.push({ name, guard: this.guard });
|
|
1581
|
+
const n = this.compile(s);
|
|
1582
|
+
this.stack.pop();
|
|
1583
|
+
return n;
|
|
1584
|
+
}
|
|
1585
|
+
defRef(name, def) {
|
|
1586
|
+
const n = this.node({
|
|
1587
|
+
deps: [def],
|
|
1588
|
+
// JSON Pointer escaping: a named type like `shop/Product` is `#/$defs/shop~1Product`.
|
|
1589
|
+
emit: () => ({ $ref: `#/$defs/${name.replace(/~/g, "~0").replace(/\//g, "~1")}` }),
|
|
1590
|
+
run: (v, cx) => def.run(v, cx),
|
|
1591
|
+
encode: (v, st) => def.encode(v, st),
|
|
1592
|
+
child: (seg) => def.child(seg)
|
|
1593
|
+
});
|
|
1594
|
+
this.nodes.push(n);
|
|
1595
|
+
n.refName = name;
|
|
1596
|
+
return n;
|
|
1597
|
+
}
|
|
1598
|
+
/**
|
|
1599
|
+
* The escape hatch: a string holding JSON text in the CODE shape, used for
|
|
1600
|
+
* whatever the profile cannot express (recursion, depth, "any"). The JSON
|
|
1601
|
+
* text is parsed once and validated by the LENIENT rendering of the same
|
|
1602
|
+
* schema, so nothing is lost — only moved into a string.
|
|
1603
|
+
*/
|
|
1604
|
+
escape(s, why, name) {
|
|
1605
|
+
const printer = new Printer(this.env);
|
|
1606
|
+
const shape = name ?? printer.print(s);
|
|
1607
|
+
for (const n2 of name ? [name] : printer.used()) this.glossary.add(n2);
|
|
1608
|
+
const where = name || printer.used().length ? " (its named types are defined in the description of the whole schema)" : "";
|
|
1609
|
+
let inner;
|
|
1610
|
+
const lenientNode = () => inner ??= this.lenient().nodeFor(s);
|
|
1611
|
+
const n = this.node({
|
|
1612
|
+
own: true,
|
|
1613
|
+
emit: () => ({ type: "string", description: `${why} Write it as JSON text of this TypeScript type: ${shape}${where}.` }),
|
|
1614
|
+
run: (v, cx) => {
|
|
1615
|
+
const parsed = readJsonText(v, cx);
|
|
1616
|
+
if (parsed === FAILED) return v;
|
|
1617
|
+
cx.enter("(json)", null);
|
|
1618
|
+
const out = lenientNode().run(parsed, cx);
|
|
1619
|
+
cx.leave(false);
|
|
1620
|
+
return out;
|
|
1621
|
+
},
|
|
1622
|
+
encode: (v) => JSON.stringify(v)
|
|
1623
|
+
});
|
|
1624
|
+
n.jsonText = true;
|
|
1625
|
+
this.nodes.push(n);
|
|
1626
|
+
return n;
|
|
1627
|
+
}
|
|
1628
|
+
/** A node for a subschema in this compiler, compiled on demand (after `finish`). */
|
|
1629
|
+
late(s) {
|
|
1630
|
+
const n = this.compile(s);
|
|
1631
|
+
this.finish();
|
|
1632
|
+
return n;
|
|
1633
|
+
}
|
|
1634
|
+
/** Least fixpoint of `needs = own || any(dep.needs)` (handles cycles). */
|
|
1635
|
+
finish() {
|
|
1636
|
+
for (let changed = true; changed; ) {
|
|
1637
|
+
changed = false;
|
|
1638
|
+
for (const n of this.nodes) {
|
|
1639
|
+
if (n.needs) continue;
|
|
1640
|
+
if (n.own || n.deps.some((d) => d.needs)) {
|
|
1641
|
+
n.needs = true;
|
|
1642
|
+
changed = true;
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
if (this.shared) this.nodes.length = 0;
|
|
1647
|
+
}
|
|
1648
|
+
/** Text of a `Text` for this profile. */
|
|
1649
|
+
text(t) {
|
|
1650
|
+
return t === void 0 ? void 0 : typeof t === "function" ? t(this.view) : t;
|
|
1651
|
+
}
|
|
1652
|
+
/** `T | null` in this profile's spelling. */
|
|
1653
|
+
nullable(j) {
|
|
1654
|
+
const spelling = this.profile.nulls;
|
|
1655
|
+
if (j.nullable === true || Array.isArray(j.type) && j.type.includes("null") || j.type === "null") return j;
|
|
1656
|
+
if (spelling === "nullable") return { ...j, nullable: true };
|
|
1657
|
+
if (spelling === "type-array" && typeof j.type === "string" && !("$ref" in j) && !("anyOf" in j)) {
|
|
1658
|
+
const out = { ...j, type: [j.type, "null"] };
|
|
1659
|
+
if (Array.isArray(j.enum)) out.enum = [...j.enum, null];
|
|
1660
|
+
return out;
|
|
1661
|
+
}
|
|
1662
|
+
if (Array.isArray(j.anyOf) && !("$ref" in j)) {
|
|
1663
|
+
if (j.anyOf.some((o) => o.type === "null")) return j;
|
|
1664
|
+
return { ...j, anyOf: [...j.anyOf, { type: "null" }] };
|
|
1665
|
+
}
|
|
1666
|
+
const { description, ...rest } = j;
|
|
1667
|
+
return description === void 0 ? { anyOf: [rest, { type: "null" }] } : { anyOf: [rest, { type: "null" }], description };
|
|
1668
|
+
}
|
|
1669
|
+
/** An object schema, closed when the profile closes objects. */
|
|
1670
|
+
object(properties, required, closed = this.profile.closedObjects) {
|
|
1671
|
+
const j = { type: "object", properties, required: [...required] };
|
|
1672
|
+
if (closed) j.additionalProperties = false;
|
|
1673
|
+
if (this.profile.propertyOrdering) j.propertyOrdering = Object.keys(properties);
|
|
1674
|
+
return j;
|
|
1675
|
+
}
|
|
1676
|
+
/** Add description, examples and title to an emitted schema. */
|
|
1677
|
+
decorate(node, json2) {
|
|
1678
|
+
const parts = [];
|
|
1679
|
+
const metas = [node.schema?.meta, node.outer?.meta];
|
|
1680
|
+
let title;
|
|
1681
|
+
const examples = [];
|
|
1682
|
+
for (const m of metas) {
|
|
1683
|
+
if (!m) continue;
|
|
1684
|
+
const d = this.text(m.description);
|
|
1685
|
+
if (d) parts.push(d);
|
|
1686
|
+
if (m.title) title = m.title;
|
|
1687
|
+
if (m.examples) {
|
|
1688
|
+
for (const e of m.examples) {
|
|
1689
|
+
this.checkExample(node, e);
|
|
1690
|
+
examples.push(node.encode(e));
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
}
|
|
1694
|
+
const hint = node.impl?.hint?.(this.view);
|
|
1695
|
+
if (hint) parts.push(hint);
|
|
1696
|
+
const prior = typeof json2.description === "string" ? json2.description : void 0;
|
|
1697
|
+
if (prior) parts.push(prior);
|
|
1698
|
+
const out = { ...json2 };
|
|
1699
|
+
if (title) out.title = title;
|
|
1700
|
+
if (examples.length) {
|
|
1701
|
+
if (this.profile.examples === "keyword") out.examples = examples;
|
|
1702
|
+
else if (this.profile.examples === "description")
|
|
1703
|
+
parts.push(`Example${examples.length > 1 ? "s" : ""}: ${examples.map((e) => JSON.stringify(e)).join(" ; ")}`);
|
|
1704
|
+
}
|
|
1705
|
+
if (parts.length) out.description = parts.join("\n");
|
|
1706
|
+
return out;
|
|
1707
|
+
}
|
|
1708
|
+
/** An example is typed in the code shape; one that doesn't fit is a definition mistake, reported once. */
|
|
1709
|
+
checkExample(node, example) {
|
|
1710
|
+
const s = node.schema;
|
|
1711
|
+
if (!s) return;
|
|
1712
|
+
const cx = new Cx(false, true, newStats(), false);
|
|
1713
|
+
this.lenient().nodeFor(s).run(example, cx);
|
|
1714
|
+
if (cx.errors.length) {
|
|
1715
|
+
throw new SchemaDefinitionError(`example ${JSON.stringify(example)} does not fit its schema:
|
|
1716
|
+
${formatIssues(cx.errors)}`);
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
};
|
|
1720
|
+
var DefTarget = class extends Node {
|
|
1721
|
+
target;
|
|
1722
|
+
constructor(compiler) {
|
|
1723
|
+
super(void 0, compiler);
|
|
1724
|
+
}
|
|
1725
|
+
get own() {
|
|
1726
|
+
return false;
|
|
1727
|
+
}
|
|
1728
|
+
get deps() {
|
|
1729
|
+
return this.target ? [this.target] : [];
|
|
1730
|
+
}
|
|
1731
|
+
json() {
|
|
1732
|
+
return this.target.json();
|
|
1733
|
+
}
|
|
1734
|
+
run(v, cx) {
|
|
1735
|
+
return this.target.run(v, cx);
|
|
1736
|
+
}
|
|
1737
|
+
encode(v, stats = newStats()) {
|
|
1738
|
+
return this.target.encode(v, stats);
|
|
1739
|
+
}
|
|
1740
|
+
child(seg) {
|
|
1741
|
+
return this.target.child(seg);
|
|
1742
|
+
}
|
|
1743
|
+
};
|
|
1744
|
+
var FAILED = /* @__PURE__ */ Symbol("failed");
|
|
1745
|
+
function readJsonText(v, cx) {
|
|
1746
|
+
if (typeof v !== "string") {
|
|
1747
|
+
if (cx.repair && v !== void 0) {
|
|
1748
|
+
if (!cx.dry) cx.stats.repaired++;
|
|
1749
|
+
return v;
|
|
1750
|
+
}
|
|
1751
|
+
cx.fail("Expected a string of JSON text.", "type");
|
|
1752
|
+
return FAILED;
|
|
1753
|
+
}
|
|
1754
|
+
try {
|
|
1755
|
+
const out = JSON.parse(v);
|
|
1756
|
+
if (!cx.dry) cx.stats.parsed++;
|
|
1757
|
+
return out;
|
|
1758
|
+
} catch (e) {
|
|
1759
|
+
cx.fail(`Not valid JSON text: ${e.message}`, "json");
|
|
1760
|
+
return FAILED;
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
var Rendered = class {
|
|
1764
|
+
constructor(compiler, root) {
|
|
1765
|
+
this.compiler = compiler;
|
|
1766
|
+
this.root = root;
|
|
1767
|
+
}
|
|
1768
|
+
compiler;
|
|
1769
|
+
root;
|
|
1770
|
+
_json;
|
|
1771
|
+
_body;
|
|
1772
|
+
_wrapped;
|
|
1773
|
+
_measure;
|
|
1774
|
+
_encoder;
|
|
1775
|
+
get profile() {
|
|
1776
|
+
return this.compiler.profile;
|
|
1777
|
+
}
|
|
1778
|
+
/** The root schema without `$defs` (a root ref is inlined). */
|
|
1779
|
+
body() {
|
|
1780
|
+
if (!this._body) {
|
|
1781
|
+
const refName2 = this.root.refName;
|
|
1782
|
+
this._body = refName2 ? this.compiler.defs.get(refName2).json() : this.root.json();
|
|
1783
|
+
}
|
|
1784
|
+
return this._body;
|
|
1785
|
+
}
|
|
1786
|
+
/**
|
|
1787
|
+
* True when the profile needs an object root and this schema's root isn't
|
|
1788
|
+
* one: the model then writes `{ "input": … }`, unwrapped on decode.
|
|
1789
|
+
*/
|
|
1790
|
+
get wrapped() {
|
|
1791
|
+
if (this._wrapped === void 0) {
|
|
1792
|
+
const b = this.body();
|
|
1793
|
+
this._wrapped = this.profile.rootObject && !(b.type === "object" && !("anyOf" in b));
|
|
1794
|
+
}
|
|
1795
|
+
return this._wrapped;
|
|
1796
|
+
}
|
|
1797
|
+
/** The JSON Schema the model is given. */
|
|
1798
|
+
get jsonSchema() {
|
|
1799
|
+
if (this._json) return this._json;
|
|
1800
|
+
let body = this.body();
|
|
1801
|
+
if (this.wrapped) body = this.compiler.object({ input: body }, ["input"], this.profile.closedObjects || this.profile.strict);
|
|
1802
|
+
if (this.compiler.glossary.size) {
|
|
1803
|
+
const defs2 = new Printer(this.compiler.env).definitions(this.compiler.glossary);
|
|
1804
|
+
const note = `Named types used by the fields written as JSON text:
|
|
1805
|
+
${defs2}`;
|
|
1806
|
+
body = { ...body, description: typeof body.description === "string" ? `${body.description}
|
|
1807
|
+
${note}` : note };
|
|
1808
|
+
}
|
|
1809
|
+
const defs = {};
|
|
1810
|
+
for (const [name, def] of this.compiler.defs) defs[name] = def.json();
|
|
1811
|
+
this._json = this.compiler.defs.size ? { ...body, $defs: defs } : body;
|
|
1812
|
+
return this._json;
|
|
1813
|
+
}
|
|
1814
|
+
/** Size of the emitted schema: properties, depth, enum values, optionals, unions (memoized). */
|
|
1815
|
+
get measure() {
|
|
1816
|
+
return this._measure ??= measureJson(this.jsonSchema);
|
|
1817
|
+
}
|
|
1818
|
+
/**
|
|
1819
|
+
* Validate + decode the model's answer (already `JSON.parse`d). With
|
|
1820
|
+
* `inPlace` (default) the value is decoded in place and returned; see the
|
|
1821
|
+
* copy rules at the top of this file. On failure `message` is the feedback
|
|
1822
|
+
* for the model (`opts.errorFormat`, see feedback.ts); with an echoing
|
|
1823
|
+
* format (the default) the value is first put back as the model sent it.
|
|
1824
|
+
*/
|
|
1825
|
+
parse(wire, opts) {
|
|
1826
|
+
return this.decode(wire, opts, void 0);
|
|
1827
|
+
}
|
|
1828
|
+
decode(wire, opts, original) {
|
|
1829
|
+
const stats = newStats();
|
|
1830
|
+
const inPlace = opts?.inPlace ?? true;
|
|
1831
|
+
const cx = new Cx(inPlace, false, stats, opts?.repair ?? true);
|
|
1832
|
+
const keep = inPlace && !original && echoes(opts?.errorFormat);
|
|
1833
|
+
if (keep) cx.keepUndo();
|
|
1834
|
+
let value;
|
|
1835
|
+
if (this.wrapped) {
|
|
1836
|
+
if (typeof wire !== "object" || wire === null || Array.isArray(wire) || !("input" in wire)) {
|
|
1837
|
+
cx.fail('Expected an object with an "input" field.', "type");
|
|
1838
|
+
} else {
|
|
1839
|
+
cx.enter("input", null);
|
|
1840
|
+
value = this.root.run(wire.input, cx);
|
|
1841
|
+
cx.leave(false);
|
|
1842
|
+
}
|
|
1843
|
+
} else {
|
|
1844
|
+
value = this.root.run(wire, cx);
|
|
1845
|
+
}
|
|
1846
|
+
if (cx.errors.length) {
|
|
1847
|
+
cx.restore();
|
|
1848
|
+
cx.releaseUndo();
|
|
1849
|
+
const sent = original ? original() : wire;
|
|
1850
|
+
return { ok: false, issues: cx.errors, message: formatErrors(cx.errors, sent, errorFormat(opts?.errorFormat), opts?.label), stats };
|
|
1851
|
+
}
|
|
1852
|
+
if (keep) cx.releaseUndo();
|
|
1853
|
+
return { ok: true, value, stats };
|
|
1854
|
+
}
|
|
1855
|
+
/** `JSON.parse` then decode in place (we own the parsed value; a failure's echo re-reads the text). */
|
|
1856
|
+
parseText(text, opts) {
|
|
1857
|
+
let wire;
|
|
1858
|
+
try {
|
|
1859
|
+
wire = JSON.parse(text);
|
|
1860
|
+
} catch (e) {
|
|
1861
|
+
const issues = [{ path: [], codePath: [], message: `Not valid JSON: ${e.message}` }];
|
|
1862
|
+
recordIssue(issues[0], { kind: "json" });
|
|
1863
|
+
return { ok: false, issues, message: formatErrors(issues, void 0, errorFormat(opts?.errorFormat), opts?.label), stats: newStats() };
|
|
1864
|
+
}
|
|
1865
|
+
return this.decode(wire, opts, () => JSON.parse(text));
|
|
1866
|
+
}
|
|
1867
|
+
/** `parse`, throwing a `SchemaParseError` (with the issues and the model's message) on failure. */
|
|
1868
|
+
parseOrThrow(wire, opts) {
|
|
1869
|
+
const r = this.parse(wire, opts);
|
|
1870
|
+
if (!r.ok) throw new SchemaParseError(r.issues, r.message);
|
|
1871
|
+
return r.value;
|
|
1872
|
+
}
|
|
1873
|
+
/**
|
|
1874
|
+
* Code shape → the shape this model writes (few-shot examples, values in
|
|
1875
|
+
* instructions, echoing prior args). Never mutates `value`; untouched
|
|
1876
|
+
* subtrees are shared. Pass `stats` to count what was allocated.
|
|
1877
|
+
*/
|
|
1878
|
+
encode(value, stats = newStats()) {
|
|
1879
|
+
const enc = this.root.encode(value, stats);
|
|
1880
|
+
if (!this.wrapped) return enc;
|
|
1881
|
+
stats.objects++;
|
|
1882
|
+
return { input: enc };
|
|
1883
|
+
}
|
|
1884
|
+
/** `encode` of a part: `value` is the value at code path `path` (`'limits'`, `['rows', '*', 'tags']`). */
|
|
1885
|
+
encodeAt(value, path, stats = newStats()) {
|
|
1886
|
+
const segs = splitPath(path);
|
|
1887
|
+
if (!segs.length) return this.encode(value, stats);
|
|
1888
|
+
let node = this.root;
|
|
1889
|
+
for (const seg of segs) {
|
|
1890
|
+
node = node?.child(seg);
|
|
1891
|
+
if (!node) throw new SchemaDefinitionError(`no schema at path ${formatPath(segs)}.`);
|
|
1892
|
+
}
|
|
1893
|
+
return node.encode(value, stats);
|
|
1894
|
+
}
|
|
1895
|
+
/** `encode` as JSON text (of a part, with `opts.path`). */
|
|
1896
|
+
encodeText(value, opts = {}) {
|
|
1897
|
+
const wire = opts.path === void 0 ? this.encode(value) : this.encodeAt(value, opts.path);
|
|
1898
|
+
const indent = opts.pretty === true ? 2 : typeof opts.pretty === "number" ? opts.pretty : void 0;
|
|
1899
|
+
return JSON.stringify(wire, null, indent);
|
|
1900
|
+
}
|
|
1901
|
+
/** An encoder bound to this rendering: hand it to code that has only the value. */
|
|
1902
|
+
get encoder() {
|
|
1903
|
+
if (!this._encoder) {
|
|
1904
|
+
const fn = ((value, opts) => this.encodeText(value, opts));
|
|
1905
|
+
fn.wire = (value, path) => path === void 0 ? this.encode(value) : this.encodeAt(value, path);
|
|
1906
|
+
this._encoder = Object.freeze(fn);
|
|
1907
|
+
}
|
|
1908
|
+
return this._encoder;
|
|
1909
|
+
}
|
|
1910
|
+
/**
|
|
1911
|
+
* Node for a subschema in this rendering (escape hatches use the LENIENT one),
|
|
1912
|
+
* compiled once per subschema instance: union encoding and checks ask for the
|
|
1913
|
+
* same option nodes on every value, and a fresh compile each time grew the
|
|
1914
|
+
* compiler (and its `needs` fixpoint) by the subschema's size per call.
|
|
1915
|
+
*/
|
|
1916
|
+
nodeFor(s) {
|
|
1917
|
+
let n = this.lateNodes.get(s);
|
|
1918
|
+
if (!n) this.lateNodes.set(s, n = this.compiler.late(s));
|
|
1919
|
+
return n;
|
|
1920
|
+
}
|
|
1921
|
+
lateNodes = /* @__PURE__ */ new WeakMap();
|
|
1922
|
+
/** The whole shape as TypeScript-like text (prompt-text delivery). */
|
|
1923
|
+
typescript() {
|
|
1924
|
+
const s = this.root.schema;
|
|
1925
|
+
return new Printer(this.compiler.env).full(s);
|
|
1926
|
+
}
|
|
1927
|
+
};
|
|
1928
|
+
function splitPath(path) {
|
|
1929
|
+
if (path === void 0 || path === "") return [];
|
|
1930
|
+
if (typeof path !== "string") return [...path];
|
|
1931
|
+
return path.split(".").map((s) => /^\d+$/.test(s) ? Number(s) : s);
|
|
1932
|
+
}
|
|
1933
|
+
function formatIssues(issues) {
|
|
1934
|
+
return issues.map((i) => `- at ${formatPath(i.path)}: ${i.message}`).join("\n");
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1937
|
+
// src/module.ts
|
|
1938
|
+
var Module = class _Module {
|
|
1939
|
+
constructor(defs = {}) {
|
|
1940
|
+
this.defs = defs;
|
|
1941
|
+
}
|
|
1942
|
+
defs;
|
|
1943
|
+
define(defs) {
|
|
1944
|
+
for (const k of Object.keys(defs)) if (k in this.defs) throw new SchemaDefinitionError(`"${k}" is already defined.`);
|
|
1945
|
+
return new _Module({ ...this.defs, ...defs });
|
|
1946
|
+
}
|
|
1947
|
+
/** Pin the code type of refs the dynamic step will supply. */
|
|
1948
|
+
declare() {
|
|
1949
|
+
return this;
|
|
1950
|
+
}
|
|
1951
|
+
/** Supply the remaining refs from runtime args (a ctx, a registry, a DB engine...). */
|
|
1952
|
+
dynamic(fn, opts = {}) {
|
|
1953
|
+
return new DynamicModule(this.defs, fn, opts);
|
|
1954
|
+
}
|
|
1955
|
+
/** End the chain: a named type, or an inline schema (which may use refs). */
|
|
1956
|
+
result(root) {
|
|
1957
|
+
return new Bundle(this.defs, rootOf(root));
|
|
1958
|
+
}
|
|
1959
|
+
};
|
|
1960
|
+
var DynamicModule = class {
|
|
1961
|
+
constructor(defs, fn, opts) {
|
|
1962
|
+
this.defs = defs;
|
|
1963
|
+
this.fn = fn;
|
|
1964
|
+
this.opts = opts;
|
|
1965
|
+
}
|
|
1966
|
+
defs;
|
|
1967
|
+
fn;
|
|
1968
|
+
opts;
|
|
1969
|
+
result(root) {
|
|
1970
|
+
return new Bundle(this.defs, rootOf(root), { fn: this.fn, opts: this.opts });
|
|
1971
|
+
}
|
|
1972
|
+
};
|
|
1973
|
+
function rootOf(root) {
|
|
1974
|
+
return typeof root === "string" ? new RefType(root) : root;
|
|
1975
|
+
}
|
|
1976
|
+
var Bundle = class _Bundle {
|
|
1977
|
+
constructor(defs, root, dyn) {
|
|
1978
|
+
this.defs = defs;
|
|
1979
|
+
this.root = root;
|
|
1980
|
+
this.dyn = dyn;
|
|
1981
|
+
}
|
|
1982
|
+
defs;
|
|
1983
|
+
root;
|
|
1984
|
+
dyn;
|
|
1985
|
+
cache = /* @__PURE__ */ new Map();
|
|
1986
|
+
staticBound;
|
|
1987
|
+
bind = (...args) => {
|
|
1988
|
+
const dyn = this.dyn;
|
|
1989
|
+
if (!dyn) return this.staticBound ??= new Bound(new Map(Object.entries(this.defs)), this.root);
|
|
1990
|
+
const key = dyn.opts.key?.(...args);
|
|
1991
|
+
if (key !== void 0) {
|
|
1992
|
+
const hit = this.cache.get(key);
|
|
1993
|
+
if (hit) {
|
|
1994
|
+
this.cache.delete(key);
|
|
1995
|
+
this.cache.set(key, hit);
|
|
1996
|
+
return hit;
|
|
1997
|
+
}
|
|
1998
|
+
}
|
|
1999
|
+
const extra = dyn.fn(...args);
|
|
2000
|
+
const env = new Map(Object.entries(this.defs));
|
|
2001
|
+
for (const [k, s] of Object.entries(extra)) {
|
|
2002
|
+
if (env.has(k)) throw new SchemaDefinitionError(`the dynamic step redefined "${k}".`);
|
|
2003
|
+
env.set(k, s);
|
|
2004
|
+
}
|
|
2005
|
+
const bound = new Bound(env, this.root);
|
|
2006
|
+
if (key !== void 0) {
|
|
2007
|
+
this.cache.set(key, bound);
|
|
2008
|
+
const max = dyn.opts.cacheSize ?? 4;
|
|
2009
|
+
while (this.cache.size > max) this.cache.delete(this.cache.keys().next().value);
|
|
2010
|
+
}
|
|
2011
|
+
return bound;
|
|
2012
|
+
};
|
|
2013
|
+
/**
|
|
2014
|
+
* The same bundle, bound from other arguments: `QueryModule.result(...)`
|
|
2015
|
+
* takes `(catalog, options)`, a tool's schema takes `(ctx)` —
|
|
2016
|
+
* `bundle.adapt((ctx: Ctx) => [ctx.catalog, { strict: true }])`. The bind
|
|
2017
|
+
* cache keys on the mapped arguments.
|
|
2018
|
+
*/
|
|
2019
|
+
adapt(map) {
|
|
2020
|
+
const dyn = this.dyn;
|
|
2021
|
+
if (!dyn) return this;
|
|
2022
|
+
const key = dyn.opts.key;
|
|
2023
|
+
return new _Bundle(this.defs, this.root, {
|
|
2024
|
+
fn: (...b) => dyn.fn(...map(...b)),
|
|
2025
|
+
opts: { ...dyn.opts, ...key ? { key: (...b) => key(...map(...b)) } : {} }
|
|
2026
|
+
});
|
|
2027
|
+
}
|
|
2028
|
+
/** Shorthand for `bind(...args).render(profile)`. */
|
|
2029
|
+
render(profile, ...args) {
|
|
2030
|
+
return this.bind(...args).render(profile);
|
|
2031
|
+
}
|
|
2032
|
+
};
|
|
2033
|
+
var Bound = class {
|
|
2034
|
+
constructor(env, root) {
|
|
2035
|
+
this.env = env;
|
|
2036
|
+
this.root = root;
|
|
2037
|
+
const missing = [];
|
|
2038
|
+
const check = (s) => {
|
|
2039
|
+
for (const n of s.refNames()) if (!env.has(n) && !missing.includes(n)) missing.push(n);
|
|
2040
|
+
};
|
|
2041
|
+
check(root);
|
|
2042
|
+
for (const s of env.values()) check(s);
|
|
2043
|
+
if (missing.length) throw new SchemaDefinitionError(`unresolved ref(s) ${missing.join(", ")}.`);
|
|
2044
|
+
}
|
|
2045
|
+
env;
|
|
2046
|
+
root;
|
|
2047
|
+
rendered = /* @__PURE__ */ new Map();
|
|
2048
|
+
/** The model-facing rendering for a profile, memoized on this bound instance. */
|
|
2049
|
+
render(profile) {
|
|
2050
|
+
let r = this.rendered.get(profile.id);
|
|
2051
|
+
if (!r) {
|
|
2052
|
+
const lenient = () => this.render(LENIENT);
|
|
2053
|
+
let c = new Compiler(profile, this.env, lenient);
|
|
2054
|
+
let node;
|
|
2055
|
+
try {
|
|
2056
|
+
node = c.compile(this.root);
|
|
2057
|
+
} catch (e) {
|
|
2058
|
+
if (!(e instanceof InlineBudgetExceeded)) throw e;
|
|
2059
|
+
c = new Compiler(profile, this.env, lenient, true);
|
|
2060
|
+
node = c.compile(this.root);
|
|
2061
|
+
}
|
|
2062
|
+
c.finish();
|
|
2063
|
+
r = new Rendered(c, node);
|
|
2064
|
+
this.rendered.set(profile.id, r);
|
|
2065
|
+
}
|
|
2066
|
+
return r;
|
|
2067
|
+
}
|
|
2068
|
+
};
|
|
2069
|
+
var statics = /* @__PURE__ */ new WeakMap();
|
|
2070
|
+
function staticBundle(s) {
|
|
2071
|
+
let b = statics.get(s);
|
|
2072
|
+
if (!b) statics.set(s, b = new Bundle({}, s));
|
|
2073
|
+
return b;
|
|
2074
|
+
}
|
|
2075
|
+
|
|
2076
|
+
// src/schema.ts
|
|
2077
|
+
var EMPTY = Object.freeze({});
|
|
2078
|
+
var NONE = Object.freeze([]);
|
|
2079
|
+
var Schema = class {
|
|
2080
|
+
meta = EMPTY;
|
|
2081
|
+
checks = NONE;
|
|
2082
|
+
_refNames;
|
|
2083
|
+
/** Runtime twin of `_refs`. */
|
|
2084
|
+
refNames() {
|
|
2085
|
+
if (!this._refNames) {
|
|
2086
|
+
const s = /* @__PURE__ */ new Set();
|
|
2087
|
+
if (this instanceof RefType) s.add(this.name);
|
|
2088
|
+
for (const c of this.children()) for (const n of c.refNames()) s.add(n);
|
|
2089
|
+
if (this.meta.forModels) for (const n of this.meta.forModels.refNames()) s.add(n);
|
|
2090
|
+
this._refNames = s;
|
|
2091
|
+
}
|
|
2092
|
+
return this._refNames;
|
|
2093
|
+
}
|
|
2094
|
+
/** @internal A copy with metadata/checks/fields replaced (schemas are immutable). */
|
|
2095
|
+
with(patch) {
|
|
2096
|
+
const c = Object.create(Object.getPrototypeOf(this));
|
|
2097
|
+
Object.assign(c, this, patch, { _refNames: void 0 });
|
|
2098
|
+
return c;
|
|
2099
|
+
}
|
|
2100
|
+
/** Description for the model (a string, or a function of the model-facing view). */
|
|
2101
|
+
describe(text) {
|
|
2102
|
+
return this.with({ meta: { ...this.meta, description: text } });
|
|
2103
|
+
}
|
|
2104
|
+
title(title) {
|
|
2105
|
+
return this.with({ meta: { ...this.meta, title } });
|
|
2106
|
+
}
|
|
2107
|
+
/** Examples in the CODE shape; each profile renders them in its own wire shape. */
|
|
2108
|
+
example(...values) {
|
|
2109
|
+
return this.with({ meta: { ...this.meta, examples: [...this.meta.examples ?? [], ...values] } });
|
|
2110
|
+
}
|
|
2111
|
+
/**
|
|
2112
|
+
* A rule the type system can't say. Runs after decoding on the code value;
|
|
2113
|
+
* the error path is where the model wrote it (a `{ path, message }`
|
|
2114
|
+
* entry is a problem at that path below it). With a message the rule is
|
|
2115
|
+
* also shown to the model (pass `{ visible: false }` to keep it quiet).
|
|
2116
|
+
*/
|
|
2117
|
+
refine(fn, message, opts) {
|
|
2118
|
+
const check = { fn, ...message !== void 0 ? { message } : {}, visible: opts?.visible ?? message !== void 0 };
|
|
2119
|
+
return this.with({ checks: [...this.checks, check] });
|
|
2120
|
+
}
|
|
2121
|
+
/** Nominal brand (type only). */
|
|
2122
|
+
brand() {
|
|
2123
|
+
return this;
|
|
2124
|
+
}
|
|
2125
|
+
/** Only for people (web forms, API callers); a model never sees or sends it. */
|
|
2126
|
+
forPeople() {
|
|
2127
|
+
return this.with({ meta: { ...this.meta, audience: "people" } });
|
|
2128
|
+
}
|
|
2129
|
+
/** What the model sees instead of this schema; its output must fit this one's. */
|
|
2130
|
+
forModels(model) {
|
|
2131
|
+
return this.with({ meta: { ...this.meta, forModels: model } });
|
|
2132
|
+
}
|
|
2133
|
+
optional() {
|
|
2134
|
+
return new OptionalType(this);
|
|
2135
|
+
}
|
|
2136
|
+
nullable() {
|
|
2137
|
+
return new NullableType(this);
|
|
2138
|
+
}
|
|
2139
|
+
/** May be left out; then decodes as `value` (zod's `.default`). Required in the code shape. */
|
|
2140
|
+
default(value) {
|
|
2141
|
+
return new DefaultType(this, value);
|
|
2142
|
+
}
|
|
2143
|
+
/** A ref-free schema is its own static bundle. */
|
|
2144
|
+
bind() {
|
|
2145
|
+
return staticBundle(this).bind();
|
|
2146
|
+
}
|
|
2147
|
+
/** Shorthand for `bind().render(profile)` (ref-free schemas only). */
|
|
2148
|
+
render(profile) {
|
|
2149
|
+
return staticBundle(this).bind().render(profile);
|
|
2150
|
+
}
|
|
2151
|
+
/** Rules with messages, as model-facing text. */
|
|
2152
|
+
ruleHint() {
|
|
2153
|
+
const rules = this.checks.filter((c) => c.visible && c.message).map((c) => c.message);
|
|
2154
|
+
return rules.length ? `Rules: ${rules.join(" ")}` : void 0;
|
|
2155
|
+
}
|
|
2156
|
+
/** Constraint words (what the dialect couldn't say as keywords) and the rules, as one hint. */
|
|
2157
|
+
hintOf(words) {
|
|
2158
|
+
const parts = [...words];
|
|
2159
|
+
const rules = this.ruleHint();
|
|
2160
|
+
if (rules) parts.push(rules);
|
|
2161
|
+
return parts.length ? parts.join(" ") : void 0;
|
|
2162
|
+
}
|
|
2163
|
+
};
|
|
2164
|
+
var FORMATS = {
|
|
2165
|
+
"date-time": /^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,
|
|
2166
|
+
date: /^\d{4}-\d{2}-\d{2}$/,
|
|
2167
|
+
time: /^\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,
|
|
2168
|
+
duration: /^-?P(?=\d|T\d)(\d+(\.\d+)?Y)?(\d+(\.\d+)?M)?(\d+(\.\d+)?W)?(\d+(\.\d+)?D)?(T(?=\d)(\d+(\.\d+)?H)?(\d+(\.\d+)?M)?(\d+(\.\d+)?S)?)?$/,
|
|
2169
|
+
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
|
|
2170
|
+
uuid: /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,
|
|
2171
|
+
uri: /^[a-zA-Z][a-zA-Z\d+.-]*:\S*$/,
|
|
2172
|
+
hostname: /^(?=.{1,253}$)[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
|
|
2173
|
+
ipv4: /^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,
|
|
2174
|
+
ipv6: { test: (v) => v.includes(":") && /^[0-9a-fA-F:.]+$/.test(v) && validHost(`[${v}]`) }
|
|
2175
|
+
};
|
|
2176
|
+
function validHost(host) {
|
|
2177
|
+
try {
|
|
2178
|
+
new URL(`http://${host}/`);
|
|
2179
|
+
return true;
|
|
2180
|
+
} catch {
|
|
2181
|
+
return false;
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
function isBasicPattern(p) {
|
|
2185
|
+
if (/\(\?<?[=!]|\\[bB]|\\[pP]\{|\\[1-9]|\\k</.test(p)) return false;
|
|
2186
|
+
for (const m of p.matchAll(/\{(\d+)(?:,(\d*))?\}/g)) if (Number(m[1]) > 100 || Number(m[2] || 0) > 100) return false;
|
|
2187
|
+
return true;
|
|
2188
|
+
}
|
|
2189
|
+
var StringType = class extends Schema {
|
|
2190
|
+
constructor(options = {}) {
|
|
2191
|
+
super();
|
|
2192
|
+
this.options = options;
|
|
2193
|
+
}
|
|
2194
|
+
options;
|
|
2195
|
+
kind = "string";
|
|
2196
|
+
children() {
|
|
2197
|
+
return [];
|
|
2198
|
+
}
|
|
2199
|
+
min(n) {
|
|
2200
|
+
return this.opts({ minLength: n });
|
|
2201
|
+
}
|
|
2202
|
+
max(n) {
|
|
2203
|
+
return this.opts({ maxLength: n });
|
|
2204
|
+
}
|
|
2205
|
+
pattern(re, flags) {
|
|
2206
|
+
const f = typeof re === "string" ? flags : flags ?? (re.flags || void 0);
|
|
2207
|
+
return this.opts({ pattern: typeof re === "string" ? re : re.source, ...f ? { flags: f } : {} });
|
|
2208
|
+
}
|
|
2209
|
+
format(f) {
|
|
2210
|
+
return this.opts({ format: f });
|
|
2211
|
+
}
|
|
2212
|
+
opts(o) {
|
|
2213
|
+
return this.with({ options: { ...this.options, ...o } });
|
|
2214
|
+
}
|
|
2215
|
+
print() {
|
|
2216
|
+
return "string";
|
|
2217
|
+
}
|
|
2218
|
+
compile(c) {
|
|
2219
|
+
const o = this.options;
|
|
2220
|
+
const p = c.profile;
|
|
2221
|
+
const re = o.pattern !== void 0 ? new RegExp(o.pattern, o.flags?.replace(/[gy]/g, "")) : void 0;
|
|
2222
|
+
const shown = `/${o.pattern}/${o.flags ?? ""}`;
|
|
2223
|
+
const fmt = o.format !== void 0 ? FORMATS[o.format] : void 0;
|
|
2224
|
+
const words = [];
|
|
2225
|
+
return c.node({
|
|
2226
|
+
hint: () => this.hintOf(words),
|
|
2227
|
+
emit: () => {
|
|
2228
|
+
const j = { type: "string" };
|
|
2229
|
+
keyword(j, words, "minLength", o.minLength, p.constraints.length, `At least ${o.minLength} characters.`);
|
|
2230
|
+
keyword(j, words, "maxLength", o.maxLength, p.constraints.length, `At most ${o.maxLength} characters.`);
|
|
2231
|
+
const patternOk = !o.flags && (p.constraints.pattern === "full" || p.constraints.pattern === "basic" && o.pattern !== void 0 && isBasicPattern(o.pattern));
|
|
2232
|
+
keyword(j, words, "pattern", o.pattern, patternOk, `Must match ${shown}.`);
|
|
2233
|
+
keyword(j, words, "format", o.format, p.formats === "all" || o.format !== void 0 && p.formats.has(o.format), `Format: ${o.format}.`);
|
|
2234
|
+
return j;
|
|
2235
|
+
},
|
|
2236
|
+
run: (v, cx) => {
|
|
2237
|
+
if (typeof v !== "string") return fail(cx, v, `Expected a string, got ${kind(v)}.`);
|
|
2238
|
+
if (o.minLength !== void 0 && v.length < o.minLength) cx.fail(`Must be at least ${o.minLength} characters.`, "rule");
|
|
2239
|
+
if (o.maxLength !== void 0 && v.length > o.maxLength) cx.fail(`Must be at most ${o.maxLength} characters.`, "rule");
|
|
2240
|
+
if (re && !re.test(v)) cx.fail(`Must match ${shown}.`, "rule");
|
|
2241
|
+
if (fmt && !fmt.test(v)) cx.fail(`Must be a valid ${o.format}.`, "rule");
|
|
2242
|
+
return v;
|
|
2243
|
+
},
|
|
2244
|
+
encode: (v) => v
|
|
2245
|
+
});
|
|
2246
|
+
}
|
|
2247
|
+
};
|
|
2248
|
+
var NumberType = class extends Schema {
|
|
2249
|
+
constructor(options = {}) {
|
|
2250
|
+
super();
|
|
2251
|
+
this.options = options;
|
|
2252
|
+
}
|
|
2253
|
+
options;
|
|
2254
|
+
kind = "number";
|
|
2255
|
+
children() {
|
|
2256
|
+
return [];
|
|
2257
|
+
}
|
|
2258
|
+
min(n) {
|
|
2259
|
+
return this.opts({ minimum: n });
|
|
2260
|
+
}
|
|
2261
|
+
max(n) {
|
|
2262
|
+
return this.opts({ maximum: n });
|
|
2263
|
+
}
|
|
2264
|
+
/** Strictly greater than `n` (`exclusiveMinimum`). */
|
|
2265
|
+
gt(n) {
|
|
2266
|
+
return this.opts({ exclusiveMinimum: n });
|
|
2267
|
+
}
|
|
2268
|
+
/** Strictly less than `n` (`exclusiveMaximum`). */
|
|
2269
|
+
lt(n) {
|
|
2270
|
+
return this.opts({ exclusiveMaximum: n });
|
|
2271
|
+
}
|
|
2272
|
+
positive() {
|
|
2273
|
+
return this.gt(0);
|
|
2274
|
+
}
|
|
2275
|
+
negative() {
|
|
2276
|
+
return this.lt(0);
|
|
2277
|
+
}
|
|
2278
|
+
nonnegative() {
|
|
2279
|
+
return this.min(0);
|
|
2280
|
+
}
|
|
2281
|
+
int() {
|
|
2282
|
+
return this.opts({ int: true });
|
|
2283
|
+
}
|
|
2284
|
+
opts(o) {
|
|
2285
|
+
return this.with({ options: { ...this.options, ...o } });
|
|
2286
|
+
}
|
|
2287
|
+
print() {
|
|
2288
|
+
return "number";
|
|
2289
|
+
}
|
|
2290
|
+
compile(c) {
|
|
2291
|
+
const o = this.options;
|
|
2292
|
+
const range = c.profile.constraints.range;
|
|
2293
|
+
const words = [];
|
|
2294
|
+
return c.node({
|
|
2295
|
+
hint: () => this.hintOf(words),
|
|
2296
|
+
emit: () => {
|
|
2297
|
+
const j = { type: o.int ? "integer" : "number" };
|
|
2298
|
+
keyword(j, words, "minimum", o.minimum, range, `At least ${o.minimum}.`);
|
|
2299
|
+
keyword(j, words, "maximum", o.maximum, range, `At most ${o.maximum}.`);
|
|
2300
|
+
keyword(j, words, "exclusiveMinimum", o.exclusiveMinimum, range, `Greater than ${o.exclusiveMinimum}.`);
|
|
2301
|
+
keyword(j, words, "exclusiveMaximum", o.exclusiveMaximum, range, `Less than ${o.exclusiveMaximum}.`);
|
|
2302
|
+
return j;
|
|
2303
|
+
},
|
|
2304
|
+
run: (v, cx) => {
|
|
2305
|
+
if (typeof v !== "number" || !Number.isFinite(v)) return fail(cx, v, `Expected a number, got ${kind(v)}.`);
|
|
2306
|
+
if (o.int && !Number.isInteger(v)) cx.fail("Expected a whole number.", "type");
|
|
2307
|
+
if (o.minimum !== void 0 && v < o.minimum) cx.fail(`Must be at least ${o.minimum}.`, "rule");
|
|
2308
|
+
if (o.exclusiveMinimum !== void 0 && v <= o.exclusiveMinimum) cx.fail(`Must be greater than ${o.exclusiveMinimum}.`, "rule");
|
|
2309
|
+
if (o.exclusiveMaximum !== void 0 && v >= o.exclusiveMaximum) cx.fail(`Must be less than ${o.exclusiveMaximum}.`, "rule");
|
|
2310
|
+
if (o.maximum !== void 0 && v > o.maximum) cx.fail(`Must be at most ${o.maximum}.`, "rule");
|
|
2311
|
+
return v;
|
|
2312
|
+
},
|
|
2313
|
+
encode: (v) => v
|
|
2314
|
+
});
|
|
2315
|
+
}
|
|
2316
|
+
};
|
|
2317
|
+
var BooleanType = class extends Schema {
|
|
2318
|
+
kind = "boolean";
|
|
2319
|
+
children() {
|
|
2320
|
+
return [];
|
|
2321
|
+
}
|
|
2322
|
+
print() {
|
|
2323
|
+
return "boolean";
|
|
2324
|
+
}
|
|
2325
|
+
compile(c) {
|
|
2326
|
+
return c.node({
|
|
2327
|
+
hint: () => this.ruleHint(),
|
|
2328
|
+
emit: () => ({ type: "boolean" }),
|
|
2329
|
+
run: (v, cx) => typeof v === "boolean" ? v : fail(cx, v, `Expected true or false, got ${kind(v)}.`),
|
|
2330
|
+
encode: (v) => v
|
|
2331
|
+
});
|
|
2332
|
+
}
|
|
2333
|
+
};
|
|
2334
|
+
var NullType = class extends Schema {
|
|
2335
|
+
kind = "null";
|
|
2336
|
+
children() {
|
|
2337
|
+
return [];
|
|
2338
|
+
}
|
|
2339
|
+
print() {
|
|
2340
|
+
return "null";
|
|
2341
|
+
}
|
|
2342
|
+
compile(c) {
|
|
2343
|
+
return c.node({
|
|
2344
|
+
emit: () => ({ type: "null" }),
|
|
2345
|
+
run: (v, cx) => v === null ? v : fail(cx, v, `Expected null, got ${kind(v)}.`),
|
|
2346
|
+
encode: (v) => v
|
|
2347
|
+
});
|
|
2348
|
+
}
|
|
2349
|
+
};
|
|
2350
|
+
var LiteralType = class extends Schema {
|
|
2351
|
+
constructor(value) {
|
|
2352
|
+
super();
|
|
2353
|
+
this.value = value;
|
|
2354
|
+
}
|
|
2355
|
+
value;
|
|
2356
|
+
kind = "literal";
|
|
2357
|
+
children() {
|
|
2358
|
+
return [];
|
|
2359
|
+
}
|
|
2360
|
+
print() {
|
|
2361
|
+
return JSON.stringify(this.value);
|
|
2362
|
+
}
|
|
2363
|
+
compile(c) {
|
|
2364
|
+
const v0 = this.value;
|
|
2365
|
+
return c.node({
|
|
2366
|
+
hint: () => this.ruleHint(),
|
|
2367
|
+
emit: () => v0 === null ? { type: "null" } : { type: jsonType(v0), enum: [v0] },
|
|
2368
|
+
run: (v, cx) => v === v0 ? v : fail(cx, v, `Expected ${JSON.stringify(v0)}.`, "literal", typeof v0 === "string" ? () => [v0] : void 0),
|
|
2369
|
+
encode: (v) => v
|
|
2370
|
+
});
|
|
2371
|
+
}
|
|
2372
|
+
};
|
|
2373
|
+
var EnumType = class extends Schema {
|
|
2374
|
+
constructor(values) {
|
|
2375
|
+
super();
|
|
2376
|
+
this.values = values;
|
|
2377
|
+
}
|
|
2378
|
+
values;
|
|
2379
|
+
kind = "enum";
|
|
2380
|
+
children() {
|
|
2381
|
+
return [];
|
|
2382
|
+
}
|
|
2383
|
+
print() {
|
|
2384
|
+
return this.values.length ? this.values.map((v) => JSON.stringify(v)).join(" | ") : "never";
|
|
2385
|
+
}
|
|
2386
|
+
compile(c) {
|
|
2387
|
+
const values = this.values;
|
|
2388
|
+
if (!values.length) return neverNode(c, () => this.ruleHint());
|
|
2389
|
+
const set = new Set(values);
|
|
2390
|
+
const cap = c.profile.maxEnumValues;
|
|
2391
|
+
const widened = cap !== void 0 && values.length > cap;
|
|
2392
|
+
return c.node({
|
|
2393
|
+
// Over the dialect's cap the enum is WIDENED (never truncated): every
|
|
2394
|
+
// value moves into the description, and decoding still enforces it.
|
|
2395
|
+
hint: () => this.hintOf(widened ? [`One of: ${values.join(", ")}.`] : []),
|
|
2396
|
+
emit: () => widened ? { type: "string" } : { type: "string", enum: [...values] },
|
|
2397
|
+
run: (v, cx) => {
|
|
2398
|
+
if (typeof v !== "string" || !set.has(v)) return fail(cx, v, `Expected one of: ${listOf(values)}.`, "enum", () => values);
|
|
2399
|
+
return v;
|
|
2400
|
+
},
|
|
2401
|
+
encode: (v) => v
|
|
2402
|
+
});
|
|
2403
|
+
}
|
|
2404
|
+
};
|
|
2405
|
+
var AnyType = class extends Schema {
|
|
2406
|
+
kind = "any";
|
|
2407
|
+
children() {
|
|
2408
|
+
return [];
|
|
2409
|
+
}
|
|
2410
|
+
print() {
|
|
2411
|
+
return "any JSON value";
|
|
2412
|
+
}
|
|
2413
|
+
compile(c) {
|
|
2414
|
+
const mode = c.profile.any;
|
|
2415
|
+
if (mode === "empty" || mode === "flat") {
|
|
2416
|
+
return c.node({
|
|
2417
|
+
hint: () => this.ruleHint(),
|
|
2418
|
+
emit: () => mode === "empty" ? {} : { anyOf: FLAT_ANY.map((b) => ({ ...b })) },
|
|
2419
|
+
run: (v, cx) => v === void 0 ? fail(cx, v, "Required.", "required") : v,
|
|
2420
|
+
encode: (v) => v
|
|
2421
|
+
});
|
|
2422
|
+
}
|
|
2423
|
+
return markJsonText(c.node({
|
|
2424
|
+
own: true,
|
|
2425
|
+
hint: () => this.hintOf(["Write the value as JSON text."]),
|
|
2426
|
+
emit: () => ({ type: "string" }),
|
|
2427
|
+
run: (v, cx) => {
|
|
2428
|
+
const out = readJsonText(v, cx);
|
|
2429
|
+
return out === FAILED ? v : out;
|
|
2430
|
+
},
|
|
2431
|
+
encode: (v) => JSON.stringify(v)
|
|
2432
|
+
}));
|
|
2433
|
+
}
|
|
2434
|
+
};
|
|
2435
|
+
function markJsonText(n) {
|
|
2436
|
+
n.jsonText = true;
|
|
2437
|
+
return n;
|
|
2438
|
+
}
|
|
2439
|
+
var FLAT_ANY = Object.freeze([
|
|
2440
|
+
{ type: "string" },
|
|
2441
|
+
{ type: "number" },
|
|
2442
|
+
{ type: "boolean" },
|
|
2443
|
+
{ type: "null" },
|
|
2444
|
+
{ type: "array" },
|
|
2445
|
+
{ type: "object", additionalProperties: true }
|
|
2446
|
+
]);
|
|
2447
|
+
var ArrayType = class extends Schema {
|
|
2448
|
+
constructor(element, options = {}) {
|
|
2449
|
+
super();
|
|
2450
|
+
this.element = element;
|
|
2451
|
+
this.options = options;
|
|
2452
|
+
}
|
|
2453
|
+
element;
|
|
2454
|
+
options;
|
|
2455
|
+
kind = "array";
|
|
2456
|
+
children() {
|
|
2457
|
+
return [this.element];
|
|
2458
|
+
}
|
|
2459
|
+
min(n) {
|
|
2460
|
+
return this.with({ options: { ...this.options, minItems: n } });
|
|
2461
|
+
}
|
|
2462
|
+
max(n) {
|
|
2463
|
+
return this.with({ options: { ...this.options, maxItems: n } });
|
|
2464
|
+
}
|
|
2465
|
+
print(p) {
|
|
2466
|
+
const inner = p.print(this.element);
|
|
2467
|
+
return /[|&]/.test(inner) ? `(${inner})[]` : `${inner}[]`;
|
|
2468
|
+
}
|
|
2469
|
+
compile(c) {
|
|
2470
|
+
const o = isNever(this.element, c.env) ? { ...this.options, maxItems: 0 } : this.options;
|
|
2471
|
+
const el = (o.minItems ?? 0) > 0 ? c.compile(this.element) : c.guarded(this.element);
|
|
2472
|
+
const items = c.profile.constraints.items;
|
|
2473
|
+
const words = [];
|
|
2474
|
+
return c.node({
|
|
2475
|
+
deps: [el],
|
|
2476
|
+
hint: () => this.hintOf(words),
|
|
2477
|
+
emit: () => {
|
|
2478
|
+
const j = { type: "array", items: el.json() };
|
|
2479
|
+
keyword(j, words, "minItems", o.minItems, items === "all" || items === "min-0-1" && (o.minItems ?? 0) <= 1, `At least ${o.minItems} items.`);
|
|
2480
|
+
keyword(j, words, "maxItems", o.maxItems, items === "all", `At most ${o.maxItems} items.`);
|
|
2481
|
+
return j;
|
|
2482
|
+
},
|
|
2483
|
+
run: (v0, cx) => {
|
|
2484
|
+
const v = repairJson(v0, cx, "array");
|
|
2485
|
+
if (!Array.isArray(v)) return fail(cx, v, `Expected a list, got ${kind(v)}.`);
|
|
2486
|
+
if (o.minItems !== void 0 && v.length < o.minItems) cx.fail(`Must have at least ${o.minItems} items.`, "rule");
|
|
2487
|
+
if (o.maxItems !== void 0 && v.length > o.maxItems) cx.fail(`Must have at most ${o.maxItems} items.`, "rule");
|
|
2488
|
+
let out = v;
|
|
2489
|
+
for (let i = 0; i < v.length; i++) {
|
|
2490
|
+
cx.enter(i);
|
|
2491
|
+
const r = el.run(v[i], cx);
|
|
2492
|
+
cx.leave();
|
|
2493
|
+
if (r !== v[i] && !cx.dry) out = writeIndex(out, v, i, r, cx);
|
|
2494
|
+
}
|
|
2495
|
+
return out;
|
|
2496
|
+
},
|
|
2497
|
+
encode: (v, st) => encodeItems(v, (x) => el.encode(x, st), st),
|
|
2498
|
+
child: () => el
|
|
2499
|
+
});
|
|
2500
|
+
}
|
|
2501
|
+
};
|
|
2502
|
+
var TupleType = class extends Schema {
|
|
2503
|
+
constructor(items) {
|
|
2504
|
+
super();
|
|
2505
|
+
this.items = items;
|
|
2506
|
+
}
|
|
2507
|
+
items;
|
|
2508
|
+
kind = "tuple";
|
|
2509
|
+
children() {
|
|
2510
|
+
return this.items;
|
|
2511
|
+
}
|
|
2512
|
+
print(p) {
|
|
2513
|
+
return `[${this.items.map((i) => p.print(i)).join(", ")}]`;
|
|
2514
|
+
}
|
|
2515
|
+
compile(c) {
|
|
2516
|
+
const nodes = this.items.map((i) => c.compile(i));
|
|
2517
|
+
const mode = c.profile.tuples;
|
|
2518
|
+
const n = nodes.length;
|
|
2519
|
+
const runItems = (arr, cx, path) => {
|
|
2520
|
+
let out = arr;
|
|
2521
|
+
for (let i = 0; i < n; i++) {
|
|
2522
|
+
cx.enter(path(i), i);
|
|
2523
|
+
const r = nodes[i].run(arr[i], cx);
|
|
2524
|
+
cx.leave();
|
|
2525
|
+
if (r !== arr[i] && !cx.dry) out = writeIndex(out, arr, i, r, cx);
|
|
2526
|
+
}
|
|
2527
|
+
return out;
|
|
2528
|
+
};
|
|
2529
|
+
return c.node({
|
|
2530
|
+
own: mode === "object",
|
|
2531
|
+
deps: nodes,
|
|
2532
|
+
hint: () => this.hintOf(
|
|
2533
|
+
mode === "object" ? [`Positions are written as keys "0".."${n - 1}".`] : mode === "array" ? [`Exactly ${n} items, in order: ${this.items.map((i) => i.print(new Printer(c.env))).join(", ")}.`] : []
|
|
2534
|
+
),
|
|
2535
|
+
emit: () => {
|
|
2536
|
+
if (mode === "object") {
|
|
2537
|
+
const properties = {};
|
|
2538
|
+
nodes.forEach((x, i) => properties[String(i)] = x.json());
|
|
2539
|
+
return c.object(properties, Object.keys(properties));
|
|
2540
|
+
}
|
|
2541
|
+
if (mode === "prefixItems") return { type: "array", prefixItems: nodes.map((x) => x.json()), minItems: n, maxItems: n };
|
|
2542
|
+
const j = { type: "array", items: { anyOf: nodes.map((x) => x.json()) } };
|
|
2543
|
+
return j;
|
|
2544
|
+
},
|
|
2545
|
+
run: (v0, cx) => {
|
|
2546
|
+
if (mode === "object") {
|
|
2547
|
+
const v2 = repairJson(v0, cx, "object");
|
|
2548
|
+
if (!isObject(v2)) return fail(cx, v2, 'Expected an object with keys "0".."' + (n - 1) + '".');
|
|
2549
|
+
const arr = new Array(n);
|
|
2550
|
+
for (let i = 0; i < n; i++) arr[i] = v2[String(i)];
|
|
2551
|
+
if (!cx.dry) cx.stats.arrays++;
|
|
2552
|
+
const out = runItems(arr, cx, (i) => String(i));
|
|
2553
|
+
return cx.dry ? v2 : out;
|
|
2554
|
+
}
|
|
2555
|
+
const v = repairJson(v0, cx, "array");
|
|
2556
|
+
if (!Array.isArray(v)) return fail(cx, v, `Expected a list of ${n} items.`);
|
|
2557
|
+
if (v.length !== n) cx.fail(`Expected exactly ${n} items.`, "rule");
|
|
2558
|
+
return runItems(v, cx, (i) => i);
|
|
2559
|
+
},
|
|
2560
|
+
encode: (v, st) => {
|
|
2561
|
+
const arr = v;
|
|
2562
|
+
if (mode !== "object") return encodeItems(arr, (x, i) => nodes[i].encode(x, st), st);
|
|
2563
|
+
const o = {};
|
|
2564
|
+
st.objects++;
|
|
2565
|
+
arr.forEach((x, i) => o[String(i)] = nodes[i].encode(x, st));
|
|
2566
|
+
return o;
|
|
2567
|
+
},
|
|
2568
|
+
child: (seg) => nodes[Number(seg)]
|
|
2569
|
+
});
|
|
2570
|
+
}
|
|
2571
|
+
};
|
|
2572
|
+
var ObjectType = class _ObjectType extends Schema {
|
|
2573
|
+
constructor(shape, closed = false, extras = {}) {
|
|
2574
|
+
super();
|
|
2575
|
+
this.shape = shape;
|
|
2576
|
+
this.closed = closed;
|
|
2577
|
+
this.extras = extras;
|
|
2578
|
+
}
|
|
2579
|
+
shape;
|
|
2580
|
+
closed;
|
|
2581
|
+
extras;
|
|
2582
|
+
kind = "object";
|
|
2583
|
+
children() {
|
|
2584
|
+
const out = Object.values(this.shape);
|
|
2585
|
+
if (this.extras.rest) out.push(this.extras.rest);
|
|
2586
|
+
for (const p of this.extras.patterns ?? []) out.push(p.schema);
|
|
2587
|
+
return out;
|
|
2588
|
+
}
|
|
2589
|
+
/** Unknown keys are an error (default: left in place untouched — no copy to strip them). */
|
|
2590
|
+
strict() {
|
|
2591
|
+
return this.with({ closed: true });
|
|
2592
|
+
}
|
|
2593
|
+
extend(more) {
|
|
2594
|
+
return new _ObjectType({ ...this.shape, ...more }, this.closed, this.extras);
|
|
2595
|
+
}
|
|
2596
|
+
/** Keys beyond the shape, each a `V` (zod's `catchall`). */
|
|
2597
|
+
rest(value) {
|
|
2598
|
+
return new _ObjectType(this.shape, this.closed, { ...this.extras, rest: value });
|
|
2599
|
+
}
|
|
2600
|
+
/** Keys matching a pattern (`patternProperties`); their values are typed `unknown` in the code shape. */
|
|
2601
|
+
patterns(patterns) {
|
|
2602
|
+
const list = Object.entries(patterns).map(([pattern, schema]) => ({ pattern, schema }));
|
|
2603
|
+
return new _ObjectType(this.shape, this.closed, { ...this.extras, patterns: [...this.extras.patterns ?? [], ...list] });
|
|
2604
|
+
}
|
|
2605
|
+
/**
|
|
2606
|
+
* A field whose schema depends on a sibling's DECODED value — e.g. a value
|
|
2607
|
+
* typed by the `type` the model wrote next to it. The model sees `base`
|
|
2608
|
+
* (default any JSON); decoding checks the value against `schemaFor(sibling)`.
|
|
2609
|
+
*/
|
|
2610
|
+
dependent(key, on, schemaFor, base) {
|
|
2611
|
+
const dep = new DependentType(on, schemaFor, base ?? new AnyType());
|
|
2612
|
+
return new _ObjectType({ ...this.shape, [key]: dep }, this.closed, this.extras);
|
|
2613
|
+
}
|
|
2614
|
+
print(p) {
|
|
2615
|
+
const parts = Object.entries(this.shape).map(([k, s]) => {
|
|
2616
|
+
const opt = s instanceof OptionalType || s instanceof DefaultType;
|
|
2617
|
+
return `${/^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k)}${opt ? "?" : ""}: ${p.print(opt ? s.inner : s)}`;
|
|
2618
|
+
});
|
|
2619
|
+
const extra = this.extraValue();
|
|
2620
|
+
if (extra) parts.push(`[key: string]: ${p.print(extra)}`);
|
|
2621
|
+
return `{ ${parts.join("; ")} }`;
|
|
2622
|
+
}
|
|
2623
|
+
_extraValue;
|
|
2624
|
+
/** The schema of an extra key's value as the model sees it (rest and patterns together). */
|
|
2625
|
+
extraValue() {
|
|
2626
|
+
if (this._extraValue === void 0) {
|
|
2627
|
+
const opts = [...(this.extras.patterns ?? []).map((p) => p.schema), ...this.extras.rest ? [this.extras.rest] : []];
|
|
2628
|
+
this._extraValue = opts.length === 0 ? null : opts.length === 1 ? opts[0] : new UnionType(opts);
|
|
2629
|
+
}
|
|
2630
|
+
return this._extraValue ?? void 0;
|
|
2631
|
+
}
|
|
2632
|
+
compile(c) {
|
|
2633
|
+
const p = c.profile;
|
|
2634
|
+
const nullMode = p.optional === "null";
|
|
2635
|
+
const forModel = p.audience !== "people";
|
|
2636
|
+
const fields = [];
|
|
2637
|
+
const hidden = /* @__PURE__ */ new Set();
|
|
2638
|
+
for (const [key, s0] of Object.entries(this.shape)) {
|
|
2639
|
+
const fm = forModel ? s0.meta.forModels : void 0;
|
|
2640
|
+
const s = fm ? fm.meta.description === void 0 && s0.meta.description !== void 0 ? fm.describe(s0.meta.description) : fm : s0;
|
|
2641
|
+
if (forModel && s0.meta.audience === "people") {
|
|
2642
|
+
hidden.add(key);
|
|
2643
|
+
continue;
|
|
2644
|
+
}
|
|
2645
|
+
const dflt = s instanceof DefaultType ? s : void 0;
|
|
2646
|
+
const optional2 = s instanceof OptionalType || !!dflt;
|
|
2647
|
+
const inner = s instanceof OptionalType ? s.inner : dflt ? dflt.inner : s;
|
|
2648
|
+
if (optional2 && isNever(inner, c.env)) {
|
|
2649
|
+
hidden.add(key);
|
|
2650
|
+
continue;
|
|
2651
|
+
}
|
|
2652
|
+
const node = optional2 ? c.guarded(inner, s) : c.compile(inner);
|
|
2653
|
+
fields.push({ key, optional: optional2, node, nullable: inner instanceof NullableType, ...inner instanceof DependentType ? { dep: inner } : {}, ...dflt ? { dflt } : {} });
|
|
2654
|
+
}
|
|
2655
|
+
const plain = fields.filter((f) => !f.dep);
|
|
2656
|
+
const deps = fields.filter((f) => f.dep);
|
|
2657
|
+
const known = new Set(Object.keys(this.shape));
|
|
2658
|
+
const extra = this.extraValue();
|
|
2659
|
+
const patterns = (this.extras.patterns ?? []).map((x) => ({ re: new RegExp(x.pattern), pattern: x.pattern, node: c.guarded(x.schema) }));
|
|
2660
|
+
const restNode = this.extras.rest ? c.guarded(this.extras.rest) : void 0;
|
|
2661
|
+
const extraMode = !extra ? "none" : p.records === "pairs" ? "pairs" : p.patternProperties ? "keywords" : "open";
|
|
2662
|
+
const extraKey = extraMode === "pairs" ? known.has("extra") ? "_extra" : "extra" : "";
|
|
2663
|
+
const extraNode = extra && extraMode !== "keywords" ? c.guarded(extra) : void 0;
|
|
2664
|
+
const nodeForKey = (k) => patterns.find((x) => x.re.test(k))?.node ?? restNode;
|
|
2665
|
+
return c.node({
|
|
2666
|
+
own: nullMode && fields.some((f) => f.optional && !f.nullable) || hidden.size > 0 || extraMode === "pairs" || fields.some((f) => f.dflt),
|
|
2667
|
+
deps: [...fields.map((f) => f.node), ...patterns.map((x) => x.node), ...restNode ? [restNode] : [], ...extraNode ? [extraNode] : []],
|
|
2668
|
+
hint: () => this.hintOf(
|
|
2669
|
+
extraMode === "pairs" ? [`Other keys go in "${extraKey}" as a list of {key, value} entries.`] : extraMode === "open" && patterns.length ? [`Other keys: ${patterns.map((x) => `keys matching /${x.pattern}/ hold ${x.node.schema?.print(new Printer(c.env)) ?? "a value"}`).join("; ")}${restNode ? "; any other key holds the rest" : ""}.`] : []
|
|
2670
|
+
),
|
|
2671
|
+
emit: () => {
|
|
2672
|
+
const properties = {};
|
|
2673
|
+
const required = [];
|
|
2674
|
+
for (const f of fields) {
|
|
2675
|
+
let j2 = f.node.json();
|
|
2676
|
+
if (f.dep) j2 = { ...j2, description: [j2.description, `Its type is given by "${f.dep.on}".`].filter(Boolean).join("\n") };
|
|
2677
|
+
if (f.dflt) j2 = { ...j2, description: [j2.description, `Default when left out: ${JSON.stringify(f.node.encode(f.dflt.value))}.`].filter(Boolean).join("\n") };
|
|
2678
|
+
if (f.optional && nullMode) {
|
|
2679
|
+
j2 = c.nullable(j2);
|
|
2680
|
+
j2.description = [j2.description, "Write null to leave it out."].filter(Boolean).join("\n");
|
|
2681
|
+
}
|
|
2682
|
+
properties[f.key] = j2;
|
|
2683
|
+
if (!f.optional || nullMode) required.push(f.key);
|
|
2684
|
+
}
|
|
2685
|
+
if (extraMode === "pairs") {
|
|
2686
|
+
properties[extraKey] = {
|
|
2687
|
+
type: "array",
|
|
2688
|
+
items: c.object({ key: { type: "string" }, value: extraNode.json() }, ["key", "value"], true)
|
|
2689
|
+
};
|
|
2690
|
+
if (nullMode) required.push(extraKey);
|
|
2691
|
+
}
|
|
2692
|
+
const j = c.object(properties, required, this.closed || p.closedObjects);
|
|
2693
|
+
if (extraMode === "keywords") {
|
|
2694
|
+
if (patterns.length) j.patternProperties = Object.fromEntries(patterns.map((x) => [x.pattern, x.node.json()]));
|
|
2695
|
+
if (restNode) j.additionalProperties = restNode.json();
|
|
2696
|
+
} else if (extraMode === "open") {
|
|
2697
|
+
j.additionalProperties = extraNode.json();
|
|
2698
|
+
}
|
|
2699
|
+
return j;
|
|
2700
|
+
},
|
|
2701
|
+
run: (v0, cx) => {
|
|
2702
|
+
const v = repairJson(v0, cx, "object");
|
|
2703
|
+
if (!isObject(v)) return fail(cx, v, `Expected an object, got ${kind(v)}.`);
|
|
2704
|
+
const obj = v;
|
|
2705
|
+
let out = obj;
|
|
2706
|
+
for (let fi = 0; fi < plain.length; fi++) {
|
|
2707
|
+
const f = plain[fi];
|
|
2708
|
+
const has2 = Object.prototype.hasOwnProperty.call(obj, f.key);
|
|
2709
|
+
const val = has2 ? obj[f.key] : void 0;
|
|
2710
|
+
if (val === void 0) {
|
|
2711
|
+
if (f.dflt) {
|
|
2712
|
+
if (!cx.dry) out = writeKey(out, obj, f.key, f.dflt.fresh(cx.stats), cx);
|
|
2713
|
+
} else if (!f.optional) {
|
|
2714
|
+
cx.enter(f.key);
|
|
2715
|
+
cx.fail("Required.", "required", void 0, () => Object.keys(obj).filter((k) => !known.has(k)), f.node);
|
|
2716
|
+
cx.leave();
|
|
2717
|
+
}
|
|
2718
|
+
continue;
|
|
2719
|
+
}
|
|
2720
|
+
if (val === null && f.optional && nullMode && !f.nullable) {
|
|
2721
|
+
if (!cx.dry) out = f.dflt ? writeKey(out, obj, f.key, f.dflt.fresh(cx.stats), cx) : deleteKey(out, obj, f.key, cx);
|
|
2722
|
+
continue;
|
|
2723
|
+
}
|
|
2724
|
+
cx.enter(f.key);
|
|
2725
|
+
const r = f.node.run(val, cx);
|
|
2726
|
+
cx.leave();
|
|
2727
|
+
if (r !== val && !cx.dry) out = writeKey(out, obj, f.key, r, cx);
|
|
2728
|
+
}
|
|
2729
|
+
for (let fi = 0; fi < deps.length; fi++) {
|
|
2730
|
+
const f = deps[fi];
|
|
2731
|
+
const val = obj[f.key];
|
|
2732
|
+
if (val === void 0 || val === null && f.optional && nullMode) {
|
|
2733
|
+
if (val === null && !cx.dry) out = deleteKey(out, obj, f.key, cx);
|
|
2734
|
+
else if (!f.optional) {
|
|
2735
|
+
cx.enter(f.key);
|
|
2736
|
+
cx.fail("Required.", "required", void 0, () => Object.keys(obj).filter((k) => !known.has(k)), f.node);
|
|
2737
|
+
cx.leave();
|
|
2738
|
+
}
|
|
2739
|
+
continue;
|
|
2740
|
+
}
|
|
2741
|
+
cx.enter(f.key);
|
|
2742
|
+
const before = cx.errors.length;
|
|
2743
|
+
let r = f.node.run(val, cx);
|
|
2744
|
+
if (cx.errors.length === before) {
|
|
2745
|
+
const s = f.dep.schemaFor(out[f.dep.on]);
|
|
2746
|
+
if (s) r = c.lenient().nodeFor(s).run(r, cx);
|
|
2747
|
+
}
|
|
2748
|
+
cx.leave();
|
|
2749
|
+
if (r !== val && !cx.dry) out = writeKey(out, obj, f.key, r, cx);
|
|
2750
|
+
}
|
|
2751
|
+
if (hidden.size) for (const key of hidden) {
|
|
2752
|
+
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
2753
|
+
cx.enter(key);
|
|
2754
|
+
cx.fail("Not allowed.", "not-allowed");
|
|
2755
|
+
cx.leave();
|
|
2756
|
+
}
|
|
2757
|
+
}
|
|
2758
|
+
if (extraMode === "pairs") {
|
|
2759
|
+
const list = obj[extraKey];
|
|
2760
|
+
if (list !== void 0 && list !== null) {
|
|
2761
|
+
cx.enter(extraKey, null);
|
|
2762
|
+
const entries = repairJson(list, cx, "array");
|
|
2763
|
+
if (!Array.isArray(entries)) fail(cx, entries, "Expected a list of {key, value} entries.");
|
|
2764
|
+
else {
|
|
2765
|
+
if (!cx.dry) out = deleteKey(out, obj, extraKey, cx);
|
|
2766
|
+
for (let i = 0; i < entries.length; i++) {
|
|
2767
|
+
const e = entries[i];
|
|
2768
|
+
cx.enter(i, null);
|
|
2769
|
+
if (!isObject(e) || typeof e.key !== "string") {
|
|
2770
|
+
cx.fail("Expected a {key, value} entry with a string key.", "type");
|
|
2771
|
+
cx.leave(false);
|
|
2772
|
+
continue;
|
|
2773
|
+
}
|
|
2774
|
+
const k = e.key;
|
|
2775
|
+
if (known.has(k) || Object.prototype.hasOwnProperty.call(out, k)) {
|
|
2776
|
+
cx.enter("key", null);
|
|
2777
|
+
cx.fail(`Duplicate key "${k}".`, "rule");
|
|
2778
|
+
cx.leave(false);
|
|
2779
|
+
cx.leave(false);
|
|
2780
|
+
continue;
|
|
2781
|
+
}
|
|
2782
|
+
const node = nodeForKey(k);
|
|
2783
|
+
cx.enter("value", k);
|
|
2784
|
+
const r = node ? node.run(e.value, cx) : this.closed ? fail(cx, e.value, `Key "${k}" is not allowed.`, "not-allowed") : e.value;
|
|
2785
|
+
cx.leave();
|
|
2786
|
+
if (!cx.dry) out = writeKey(out, obj, k, r, cx);
|
|
2787
|
+
cx.leave(false);
|
|
2788
|
+
}
|
|
2789
|
+
}
|
|
2790
|
+
cx.leave(false);
|
|
2791
|
+
} else if (extraKey && list === null && !cx.dry) out = deleteKey(out, obj, extraKey, cx);
|
|
2792
|
+
} else if (extra || this.closed) {
|
|
2793
|
+
const keys = Object.keys(obj);
|
|
2794
|
+
for (let ki = 0; ki < keys.length; ki++) {
|
|
2795
|
+
const key = keys[ki];
|
|
2796
|
+
if (known.has(key)) continue;
|
|
2797
|
+
const node = extra ? nodeForKey(key) : void 0;
|
|
2798
|
+
if (node) {
|
|
2799
|
+
cx.enter(key);
|
|
2800
|
+
const r = node.run(obj[key], cx);
|
|
2801
|
+
cx.leave();
|
|
2802
|
+
if (r !== obj[key] && !cx.dry) out = writeKey(out, obj, key, r, cx);
|
|
2803
|
+
} else if (this.closed) {
|
|
2804
|
+
cx.enter(key);
|
|
2805
|
+
cx.fail(`Unknown field "${key}".`, "unknown-key", key, () => [...known].filter((k) => !Object.prototype.hasOwnProperty.call(obj, k)));
|
|
2806
|
+
cx.leave();
|
|
2807
|
+
}
|
|
2808
|
+
}
|
|
2809
|
+
}
|
|
2810
|
+
return out;
|
|
2811
|
+
},
|
|
2812
|
+
encode: (v, st) => {
|
|
2813
|
+
const obj = v;
|
|
2814
|
+
const out = {};
|
|
2815
|
+
st.objects++;
|
|
2816
|
+
const pairs = [];
|
|
2817
|
+
for (const k of Object.keys(obj)) {
|
|
2818
|
+
if (hidden.has(k)) continue;
|
|
2819
|
+
if (known.has(k)) continue;
|
|
2820
|
+
const node = nodeForKey(k);
|
|
2821
|
+
const enc = node ? node.encode(obj[k], st) : obj[k];
|
|
2822
|
+
if (extraMode === "pairs") pairs.push({ key: k, value: enc });
|
|
2823
|
+
else out[k] = enc;
|
|
2824
|
+
}
|
|
2825
|
+
for (const f of fields) {
|
|
2826
|
+
const val = obj[f.key];
|
|
2827
|
+
if (val === void 0) {
|
|
2828
|
+
if (f.optional && nullMode) out[f.key] = null;
|
|
2829
|
+
continue;
|
|
2830
|
+
}
|
|
2831
|
+
out[f.key] = f.node.encode(val, st);
|
|
2832
|
+
}
|
|
2833
|
+
if (extraMode === "pairs") {
|
|
2834
|
+
if (pairs.length || nullMode) {
|
|
2835
|
+
st.arrays++;
|
|
2836
|
+
st.objects += pairs.length;
|
|
2837
|
+
out[extraKey] = pairs;
|
|
2838
|
+
}
|
|
2839
|
+
}
|
|
2840
|
+
return out;
|
|
2841
|
+
},
|
|
2842
|
+
child: (seg) => fields.find((f) => f.key === seg)?.node ?? (typeof seg === "string" ? nodeForKey(seg) : void 0)
|
|
2843
|
+
});
|
|
2844
|
+
}
|
|
2845
|
+
};
|
|
2846
|
+
var RecordType = class extends Schema {
|
|
2847
|
+
constructor(value, key) {
|
|
2848
|
+
super();
|
|
2849
|
+
this.value = value;
|
|
2850
|
+
this.key = key;
|
|
2851
|
+
}
|
|
2852
|
+
value;
|
|
2853
|
+
key;
|
|
2854
|
+
kind = "record";
|
|
2855
|
+
children() {
|
|
2856
|
+
return this.key ? [this.key, this.value] : [this.value];
|
|
2857
|
+
}
|
|
2858
|
+
print(p) {
|
|
2859
|
+
return `{ [key: ${this.key ? p.print(this.key) : "string"}]: ${p.print(this.value)} }`;
|
|
2860
|
+
}
|
|
2861
|
+
compile(c) {
|
|
2862
|
+
const val = c.guarded(this.value);
|
|
2863
|
+
const key = c.compile(this.key ?? STRING);
|
|
2864
|
+
const pairs = c.profile.records === "pairs";
|
|
2865
|
+
return c.node({
|
|
2866
|
+
own: pairs,
|
|
2867
|
+
deps: [val, key],
|
|
2868
|
+
// The one place that says how a record looks to THIS model. Prose that
|
|
2869
|
+
// must mention it uses `view.recordWord` (see `Text`).
|
|
2870
|
+
hint: (view) => this.hintOf(pairs ? [`A map written as ${view.recordWord}; each key at most once.`] : []),
|
|
2871
|
+
emit: () => {
|
|
2872
|
+
if (pairs) {
|
|
2873
|
+
return { type: "array", items: c.object({ key: key.json(), value: val.json() }, ["key", "value"], true) };
|
|
2874
|
+
}
|
|
2875
|
+
const j = { type: "object", additionalProperties: val.json() };
|
|
2876
|
+
if (this.key && !c.profile.closedObjects && !(this.key instanceof StringType && !Object.keys(this.key.options).length)) j.propertyNames = key.json();
|
|
2877
|
+
return j;
|
|
2878
|
+
},
|
|
2879
|
+
run: (v0, cx) => {
|
|
2880
|
+
if (pairs) {
|
|
2881
|
+
const v2 = repairJson(v0, cx, "array");
|
|
2882
|
+
if (!Array.isArray(v2)) {
|
|
2883
|
+
const o = cx.repair ? repairJson(v0, cx, "object") : v0;
|
|
2884
|
+
if (cx.repair && !cx.dry && isObject(o)) {
|
|
2885
|
+
if (o === v0) cx.stats.repaired++;
|
|
2886
|
+
const obj2 = o;
|
|
2887
|
+
const codeVal = c.lenient().nodeFor(this.value);
|
|
2888
|
+
let out2 = obj2;
|
|
2889
|
+
for (const k of Object.keys(obj2)) {
|
|
2890
|
+
cx.enter(k);
|
|
2891
|
+
key.run(k, cx);
|
|
2892
|
+
const r = codeVal.run(obj2[k], cx);
|
|
2893
|
+
cx.leave();
|
|
2894
|
+
if (r !== obj2[k] && !cx.dry) out2 = writeKey(out2, obj2, k, r, cx);
|
|
2895
|
+
}
|
|
2896
|
+
return out2;
|
|
2897
|
+
}
|
|
2898
|
+
return fail(cx, v2, `Expected a list of {key, value} entries, got ${kind(v2)}.`);
|
|
2899
|
+
}
|
|
2900
|
+
const rec = {};
|
|
2901
|
+
if (!cx.dry) cx.stats.objects++;
|
|
2902
|
+
for (let i = 0; i < v2.length; i++) {
|
|
2903
|
+
const e = v2[i];
|
|
2904
|
+
cx.enter(i, null);
|
|
2905
|
+
if (!isObject(e)) {
|
|
2906
|
+
fail(cx, e, "Expected a {key, value} entry.");
|
|
2907
|
+
cx.leave(false);
|
|
2908
|
+
continue;
|
|
2909
|
+
}
|
|
2910
|
+
const k = e.key;
|
|
2911
|
+
cx.enter("key", null);
|
|
2912
|
+
if (k === void 0) cx.fail("Required.", "required", void 0, () => Object.keys(e).filter((x) => x !== "key" && x !== "value"), key);
|
|
2913
|
+
else key.run(k, cx);
|
|
2914
|
+
cx.leave(false);
|
|
2915
|
+
if (typeof k === "string") {
|
|
2916
|
+
if (Object.prototype.hasOwnProperty.call(rec, k)) {
|
|
2917
|
+
cx.enter("key", null);
|
|
2918
|
+
cx.fail(`Duplicate key "${k}".`, "rule");
|
|
2919
|
+
cx.leave(false);
|
|
2920
|
+
}
|
|
2921
|
+
cx.enter("value", k);
|
|
2922
|
+
rec[k] = val.run(e.value, cx);
|
|
2923
|
+
cx.leave();
|
|
2924
|
+
}
|
|
2925
|
+
cx.leave(false);
|
|
2926
|
+
}
|
|
2927
|
+
return cx.dry ? v2 : rec;
|
|
2928
|
+
}
|
|
2929
|
+
const v = repairJson(v0, cx, "object");
|
|
2930
|
+
if (!isObject(v)) return fail(cx, v, `Expected an object, got ${kind(v)}.`);
|
|
2931
|
+
const obj = v;
|
|
2932
|
+
let out = obj;
|
|
2933
|
+
for (const k of Object.keys(obj)) {
|
|
2934
|
+
if (this.key) {
|
|
2935
|
+
cx.enter(k);
|
|
2936
|
+
key.run(k, cx);
|
|
2937
|
+
cx.leave();
|
|
2938
|
+
}
|
|
2939
|
+
cx.enter(k);
|
|
2940
|
+
const r = val.run(obj[k], cx);
|
|
2941
|
+
cx.leave();
|
|
2942
|
+
if (r !== obj[k] && !cx.dry) out = writeKey(out, obj, k, r, cx);
|
|
2943
|
+
}
|
|
2944
|
+
return out;
|
|
2945
|
+
},
|
|
2946
|
+
encode: (v, st) => {
|
|
2947
|
+
const obj = v;
|
|
2948
|
+
if (pairs) {
|
|
2949
|
+
const keys = Object.keys(obj);
|
|
2950
|
+
st.arrays++;
|
|
2951
|
+
st.objects += keys.length;
|
|
2952
|
+
return keys.map((k) => ({ key: k, value: val.encode(obj[k], st) }));
|
|
2953
|
+
}
|
|
2954
|
+
let out = obj;
|
|
2955
|
+
for (const k of Object.keys(obj)) {
|
|
2956
|
+
const e = val.encode(obj[k], st);
|
|
2957
|
+
if (e !== obj[k]) {
|
|
2958
|
+
if (out === obj) {
|
|
2959
|
+
out = { ...obj };
|
|
2960
|
+
st.objects++;
|
|
2961
|
+
}
|
|
2962
|
+
out[k] = e;
|
|
2963
|
+
}
|
|
2964
|
+
}
|
|
2965
|
+
return out;
|
|
2966
|
+
},
|
|
2967
|
+
child: () => val
|
|
2968
|
+
});
|
|
2969
|
+
}
|
|
2970
|
+
};
|
|
2971
|
+
var STRING = new StringType();
|
|
2972
|
+
var UnionType = class extends Schema {
|
|
2973
|
+
constructor(options, tag) {
|
|
2974
|
+
super();
|
|
2975
|
+
this.options = options;
|
|
2976
|
+
this.tag = tag;
|
|
2977
|
+
}
|
|
2978
|
+
options;
|
|
2979
|
+
tag;
|
|
2980
|
+
kind = "union";
|
|
2981
|
+
children() {
|
|
2982
|
+
return this.options;
|
|
2983
|
+
}
|
|
2984
|
+
print(p) {
|
|
2985
|
+
return this.options.map((o) => p.print(o)).join(" | ");
|
|
2986
|
+
}
|
|
2987
|
+
/**
|
|
2988
|
+
* For a discriminated union: option index by tag value. A tag that is a
|
|
2989
|
+
* ref (e.g. a dynamic enum of registered names) is resolved through the
|
|
2990
|
+
* bound env. Options whose tag can't be indexed (a plain string) are the
|
|
2991
|
+
* fallback, tried in order.
|
|
2992
|
+
*/
|
|
2993
|
+
tagIndex(env, skip) {
|
|
2994
|
+
const tag = this.tag ?? autoTag(this.options, env);
|
|
2995
|
+
if (!tag) return void 0;
|
|
2996
|
+
const byTag = /* @__PURE__ */ new Map();
|
|
2997
|
+
const fallback = [];
|
|
2998
|
+
this.options.forEach((o, i) => {
|
|
2999
|
+
const values = skip.has(i) ? void 0 : tagValues(o, tag, env);
|
|
3000
|
+
if (values) {
|
|
3001
|
+
for (const v of values) if (!byTag.has(v)) byTag.set(v, i);
|
|
3002
|
+
} else fallback.push(i);
|
|
3003
|
+
});
|
|
3004
|
+
return { tag, byTag, fallback };
|
|
3005
|
+
}
|
|
3006
|
+
label(i, env) {
|
|
3007
|
+
const tagSchema = this.tag ? deref(this.options[i], env).shape?.[this.tag] : void 0;
|
|
3008
|
+
if (tagSchema instanceof LiteralType && typeof tagSchema.value === "string") return tagSchema.value;
|
|
3009
|
+
return `option${i + 1}`;
|
|
3010
|
+
}
|
|
3011
|
+
compile(c) {
|
|
3012
|
+
if (this.options.some((o) => isNever(o, c.env))) {
|
|
3013
|
+
const live = this.options.filter((o) => !isNever(o, c.env));
|
|
3014
|
+
if (!live.length) return neverNode(c, () => this.ruleHint());
|
|
3015
|
+
const u = this.with({ options: live });
|
|
3016
|
+
const n = u.compile(c);
|
|
3017
|
+
return n;
|
|
3018
|
+
}
|
|
3019
|
+
const tagged = c.profile.unions === "tagged";
|
|
3020
|
+
const wrapped = /* @__PURE__ */ new Set();
|
|
3021
|
+
const compiled = this.options.map((o) => c.compile(o));
|
|
3022
|
+
if (compiled.length > 1 && compiled.every((n) => n.jsonText)) return c.escape(this, "Nested too deep for this model to describe directly.");
|
|
3023
|
+
const kindOf = (o) => deref(o, c.env)?.kind;
|
|
3024
|
+
const hasList = this.options.some((o) => kindOf(o) === "array" || kindOf(o) === "tuple" && c.profile.tuples !== "object");
|
|
3025
|
+
const nodes = compiled.map((n, i, all) => {
|
|
3026
|
+
if (tagged || all.length < 2) return n;
|
|
3027
|
+
if (n.jsonText) {
|
|
3028
|
+
wrapped.add(i);
|
|
3029
|
+
return jsonWrapped(c, n);
|
|
3030
|
+
}
|
|
3031
|
+
if (hasList && c.profile.records === "pairs" && kindOf(this.options[i]) === "record") {
|
|
3032
|
+
wrapped.add(i);
|
|
3033
|
+
return jsonWrapped(c, n, "entries");
|
|
3034
|
+
}
|
|
3035
|
+
return n;
|
|
3036
|
+
});
|
|
3037
|
+
const index = this.tagIndex(c.env, wrapped);
|
|
3038
|
+
const byTag = index?.byTag;
|
|
3039
|
+
const tag = index?.tag;
|
|
3040
|
+
const labels = this.options.map((_, i) => this.label(i, c.env));
|
|
3041
|
+
const isNullOpt = (i) => deref(this.options[i], c.env) instanceof NullType;
|
|
3042
|
+
const pick = (v, cx) => {
|
|
3043
|
+
if (byTag && isObject(v)) {
|
|
3044
|
+
const i = byTag.get(v[tag]);
|
|
3045
|
+
if (i !== void 0) {
|
|
3046
|
+
const own = new Set(optionKeys(this.options[i], c.env));
|
|
3047
|
+
if (c.profile.closedObjects && own.size && index.fallback.length && Object.keys(v).some((k) => !own.has(k))) {
|
|
3048
|
+
for (const j of index.fallback) {
|
|
3049
|
+
const d = cx.dryRun();
|
|
3050
|
+
nodes[j].run(v, d);
|
|
3051
|
+
if (!d.errors.length) return j;
|
|
3052
|
+
}
|
|
3053
|
+
}
|
|
3054
|
+
return i;
|
|
3055
|
+
}
|
|
3056
|
+
}
|
|
3057
|
+
const untagged = !isObject(v) || v[tag] === void 0;
|
|
3058
|
+
for (const i of index && !untagged ? index.fallback : nodes.keys()) {
|
|
3059
|
+
const d = cx.dryRun();
|
|
3060
|
+
nodes[i].run(v, d);
|
|
3061
|
+
if (!d.errors.length) return i;
|
|
3062
|
+
}
|
|
3063
|
+
return -1;
|
|
3064
|
+
};
|
|
3065
|
+
const printer = () => new Printer(c.env);
|
|
3066
|
+
return c.node({
|
|
3067
|
+
own: tagged,
|
|
3068
|
+
deps: nodes,
|
|
3069
|
+
hint: () => this.hintOf(tagged ? ["Fill exactly one of these fields and set the others to null."] : []),
|
|
3070
|
+
emit: () => {
|
|
3071
|
+
if (tagged) {
|
|
3072
|
+
const properties = {};
|
|
3073
|
+
nodes.forEach((n, i) => properties[labels[i]] = c.nullable(isNullOpt(i) ? { type: "boolean", enum: [true], description: "true for null" } : n.json()));
|
|
3074
|
+
return c.object(properties, labels);
|
|
3075
|
+
}
|
|
3076
|
+
return { anyOf: nodes.map((n) => n.json()) };
|
|
3077
|
+
},
|
|
3078
|
+
run: (v, cx) => {
|
|
3079
|
+
if (tagged) {
|
|
3080
|
+
if (!isObject(v)) return fail(cx, v, `Expected an object with one of: ${labels.join(", ")}.`);
|
|
3081
|
+
const set = labels.filter((l) => v[l] != null);
|
|
3082
|
+
if (set.length !== 1) return fail(cx, v, `Fill exactly one of: ${labels.join(", ")} (got ${set.length}).`, "union");
|
|
3083
|
+
const i2 = labels.indexOf(set[0]);
|
|
3084
|
+
if (isNullOpt(i2)) return v[set[0]] === true ? null : fail(cx, v, `Set ${set[0]} to true for null.`, "literal");
|
|
3085
|
+
cx.enter(set[0], null);
|
|
3086
|
+
const out = nodes[i2].run(v[set[0]], cx);
|
|
3087
|
+
cx.leave(false);
|
|
3088
|
+
return out;
|
|
3089
|
+
}
|
|
3090
|
+
const i = pick(v, cx);
|
|
3091
|
+
if (i < 0) {
|
|
3092
|
+
if (byTag && !index.fallback.length && isObject(v) && v[tag] !== void 0) {
|
|
3093
|
+
cx.enter(tag);
|
|
3094
|
+
const tagValue = v[tag];
|
|
3095
|
+
cx.fail(`Expected ${tag} to be one of: ${listOf([...byTag.keys()].map((k) => JSON.stringify(k)))}.`, "tag", tagValue, () => [...byTag.keys()].filter((k) => typeof k === "string"));
|
|
3096
|
+
cx.leave();
|
|
3097
|
+
return v;
|
|
3098
|
+
}
|
|
3099
|
+
const best = closestOption(this.options, v, c.env);
|
|
3100
|
+
if (best >= 0) return nodes[best].run(v, cx);
|
|
3101
|
+
return fail(cx, v, `Did not match any of: ${clip(this.options.map((o) => o.print(printer())).join(" | "), 300)}.`, "union", typeof v === "string" ? () => stringValues(this.options, c.env) : void 0);
|
|
3102
|
+
}
|
|
3103
|
+
return nodes[i].run(v, cx);
|
|
3104
|
+
},
|
|
3105
|
+
encode: (v, st) => {
|
|
3106
|
+
const i = this.optionOf(v, c, byTag, tag);
|
|
3107
|
+
if (i < 0) return v;
|
|
3108
|
+
const enc = isNullOpt(i) && tagged ? true : nodes[i].encode(v, st);
|
|
3109
|
+
if (!tagged) return enc;
|
|
3110
|
+
st.objects++;
|
|
3111
|
+
return Object.fromEntries(labels.map((l, j) => [l, j === i ? enc : null]));
|
|
3112
|
+
},
|
|
3113
|
+
// A part of a union: the options that have that part; which one is decided by the value encoded.
|
|
3114
|
+
child: (seg) => {
|
|
3115
|
+
const kids = nodes.map((n2) => n2.child(seg)).filter((k) => !!k);
|
|
3116
|
+
if (kids.length <= 1) return kids[0];
|
|
3117
|
+
const pickKid = (v) => kids.find((k) => !k.schema || matches(c, k.schema, v)) ?? kids[0];
|
|
3118
|
+
const n = c.node({
|
|
3119
|
+
deps: kids,
|
|
3120
|
+
emit: () => ({ anyOf: kids.map((k) => k.json()) }),
|
|
3121
|
+
run: (v, cx) => pickKid(v).run(v, cx),
|
|
3122
|
+
encode: (v, st) => pickKid(v).encode(v, st),
|
|
3123
|
+
child: (s) => kids[0].child(s)
|
|
3124
|
+
});
|
|
3125
|
+
n.needs = kids.some((k) => k.needs);
|
|
3126
|
+
return n;
|
|
3127
|
+
}
|
|
3128
|
+
});
|
|
3129
|
+
}
|
|
3130
|
+
/** Which option a CODE value belongs to (by tag, else the first whose code shape accepts it). */
|
|
3131
|
+
optionOf(v, c, byTag, tag) {
|
|
3132
|
+
if (byTag && isObject(v)) {
|
|
3133
|
+
const i = byTag.get(v[tag]);
|
|
3134
|
+
if (i !== void 0) return i;
|
|
3135
|
+
}
|
|
3136
|
+
const lenient = c.lenient();
|
|
3137
|
+
return this.options.findIndex((o) => {
|
|
3138
|
+
const d = new Cx(false, true, newStats(), false, true);
|
|
3139
|
+
lenient.nodeFor(o).run(v, d);
|
|
3140
|
+
return d.errors.length === 0;
|
|
3141
|
+
});
|
|
3142
|
+
}
|
|
3143
|
+
};
|
|
3144
|
+
var IntersectionType = class extends Schema {
|
|
3145
|
+
constructor(members) {
|
|
3146
|
+
super();
|
|
3147
|
+
this.members = members;
|
|
3148
|
+
}
|
|
3149
|
+
members;
|
|
3150
|
+
kind = "intersection";
|
|
3151
|
+
children() {
|
|
3152
|
+
return this.members;
|
|
3153
|
+
}
|
|
3154
|
+
print(p) {
|
|
3155
|
+
return this.members.map((m) => p.print(m)).join(" & ");
|
|
3156
|
+
}
|
|
3157
|
+
mergedByEnv = /* @__PURE__ */ new WeakMap();
|
|
3158
|
+
/** The members as one object, when every member is (or refers to) an object. */
|
|
3159
|
+
merged(env) {
|
|
3160
|
+
let m = this.mergedByEnv.get(env);
|
|
3161
|
+
if (m === void 0) {
|
|
3162
|
+
const objs = this.members.map((x) => deref(x, env));
|
|
3163
|
+
if (objs.every((o) => o instanceof ObjectType)) {
|
|
3164
|
+
const os = objs;
|
|
3165
|
+
const shape = {};
|
|
3166
|
+
for (const o of os) Object.assign(shape, o.shape);
|
|
3167
|
+
const rest = os.map((o) => o.extras.rest).filter(Boolean).at(-1);
|
|
3168
|
+
const patterns = os.flatMap((o) => o.extras.patterns ?? []);
|
|
3169
|
+
const merged = new ObjectType(shape, os.some((o) => o.closed), { ...rest ? { rest } : {}, ...patterns.length ? { patterns } : {} });
|
|
3170
|
+
m = merged.with({ checks: [...os.flatMap((o) => o.checks), ...this.checks], meta: this.meta });
|
|
3171
|
+
} else m = null;
|
|
3172
|
+
this.mergedByEnv.set(env, m);
|
|
3173
|
+
}
|
|
3174
|
+
return m ?? void 0;
|
|
3175
|
+
}
|
|
3176
|
+
compile(c) {
|
|
3177
|
+
const merged = this.merged(c.env);
|
|
3178
|
+
if (merged) {
|
|
3179
|
+
const n = c.compile(merged);
|
|
3180
|
+
return c.node({ deps: [n], emit: () => n.json(), run: (v, cx) => n.run(v, cx), encode: (v, st) => n.encode(v, st), child: (s) => n.child(s) });
|
|
3181
|
+
}
|
|
3182
|
+
const nodes = this.members.map((m) => c.compile(m));
|
|
3183
|
+
const rest = this.members.slice(1);
|
|
3184
|
+
const asAllOf = () => c.profile.allOf && nodes.every((n) => !n.needs);
|
|
3185
|
+
return c.node({
|
|
3186
|
+
deps: nodes,
|
|
3187
|
+
hint: () => this.hintOf(asAllOf() ? [] : [`Must also be: ${rest.map((m) => m.print(new Printer(c.env))).join(" & ")}.`]),
|
|
3188
|
+
emit: () => asAllOf() ? { allOf: nodes.map((n) => n.json()) } : nodes[0].json(),
|
|
3189
|
+
run: (v, cx) => {
|
|
3190
|
+
const before = cx.errors.length;
|
|
3191
|
+
const out = nodes[0].run(v, cx);
|
|
3192
|
+
if (cx.errors.length !== before) return out;
|
|
3193
|
+
const lenient = c.lenient();
|
|
3194
|
+
for (const m of rest) {
|
|
3195
|
+
const d = cx.dryRun(true);
|
|
3196
|
+
lenient.nodeFor(m).run(out, d);
|
|
3197
|
+
for (const e of d.errors) cx.errors.push(e);
|
|
3198
|
+
}
|
|
3199
|
+
return out;
|
|
3200
|
+
},
|
|
3201
|
+
encode: (v, st) => nodes[0].encode(v, st),
|
|
3202
|
+
child: (s) => nodes[0].child(s)
|
|
3203
|
+
});
|
|
3204
|
+
}
|
|
3205
|
+
};
|
|
3206
|
+
var NotType = class extends Schema {
|
|
3207
|
+
constructor(excluded, base) {
|
|
3208
|
+
super();
|
|
3209
|
+
this.excluded = excluded;
|
|
3210
|
+
this.base = base;
|
|
3211
|
+
}
|
|
3212
|
+
excluded;
|
|
3213
|
+
base;
|
|
3214
|
+
kind = "not";
|
|
3215
|
+
children() {
|
|
3216
|
+
return [this.base, this.excluded];
|
|
3217
|
+
}
|
|
3218
|
+
print(p) {
|
|
3219
|
+
return p.print(this.base);
|
|
3220
|
+
}
|
|
3221
|
+
compile(c) {
|
|
3222
|
+
const base = c.compile(this.base);
|
|
3223
|
+
const words = () => c.profile.conditionals ? [] : [`Must not be: ${this.excluded.print(new Printer(c.env))}.`];
|
|
3224
|
+
return c.node({
|
|
3225
|
+
deps: [base],
|
|
3226
|
+
hint: () => this.hintOf(words()),
|
|
3227
|
+
emit: () => c.profile.conditionals ? { ...base.json(), not: c.lenient().nodeFor(this.excluded).json() } : base.json(),
|
|
3228
|
+
run: (v, cx) => {
|
|
3229
|
+
const before = cx.errors.length;
|
|
3230
|
+
const out = base.run(v, cx);
|
|
3231
|
+
if (cx.errors.length === before && matches(c, this.excluded, out)) cx.fail(`Must not be: ${this.excluded.print(new Printer(c.env))}.`, "rule");
|
|
3232
|
+
return out;
|
|
3233
|
+
},
|
|
3234
|
+
encode: (v, st) => base.encode(v, st),
|
|
3235
|
+
child: (s) => base.child(s)
|
|
3236
|
+
});
|
|
3237
|
+
}
|
|
3238
|
+
};
|
|
3239
|
+
var ConditionalType = class extends Schema {
|
|
3240
|
+
constructor(base, when, then, otherwise) {
|
|
3241
|
+
super();
|
|
3242
|
+
this.base = base;
|
|
3243
|
+
this.when = when;
|
|
3244
|
+
this.then = then;
|
|
3245
|
+
this.otherwise = otherwise;
|
|
3246
|
+
}
|
|
3247
|
+
base;
|
|
3248
|
+
when;
|
|
3249
|
+
then;
|
|
3250
|
+
otherwise;
|
|
3251
|
+
kind = "conditional";
|
|
3252
|
+
children() {
|
|
3253
|
+
return [this.base, this.when, ...this.then ? [this.then] : [], ...this.otherwise ? [this.otherwise] : []];
|
|
3254
|
+
}
|
|
3255
|
+
print(p) {
|
|
3256
|
+
return p.print(this.base);
|
|
3257
|
+
}
|
|
3258
|
+
compile(c) {
|
|
3259
|
+
const base = c.compile(this.base);
|
|
3260
|
+
const ts = (s) => s.print(new Printer(c.env));
|
|
3261
|
+
const rule = [
|
|
3262
|
+
this.then ? `If it is ${ts(this.when)}, it must also be ${ts(this.then)}.` : "",
|
|
3263
|
+
this.otherwise ? `${this.then ? "Otherwise" : `If it is not ${ts(this.when)}`}, it must be ${ts(this.otherwise)}.` : ""
|
|
3264
|
+
].filter(Boolean).join(" ");
|
|
3265
|
+
return c.node({
|
|
3266
|
+
deps: [base],
|
|
3267
|
+
hint: () => this.hintOf(c.profile.conditionals ? [] : [rule]),
|
|
3268
|
+
emit: () => {
|
|
3269
|
+
if (!c.profile.conditionals) return base.json();
|
|
3270
|
+
const l = c.lenient();
|
|
3271
|
+
return {
|
|
3272
|
+
...base.json(),
|
|
3273
|
+
if: l.nodeFor(this.when).json(),
|
|
3274
|
+
...this.then ? { then: l.nodeFor(this.then).json() } : {},
|
|
3275
|
+
...this.otherwise ? { else: l.nodeFor(this.otherwise).json() } : {}
|
|
3276
|
+
};
|
|
3277
|
+
},
|
|
3278
|
+
run: (v, cx) => {
|
|
3279
|
+
const before = cx.errors.length;
|
|
3280
|
+
const out = base.run(v, cx);
|
|
3281
|
+
if (cx.errors.length !== before) return out;
|
|
3282
|
+
const branch = matches(c, this.when, out) ? this.then : this.otherwise;
|
|
3283
|
+
if (branch && !matches(c, branch, out)) cx.fail(rule, "rule");
|
|
3284
|
+
return out;
|
|
3285
|
+
},
|
|
3286
|
+
encode: (v, st) => base.encode(v, st),
|
|
3287
|
+
child: (s) => base.child(s)
|
|
3288
|
+
});
|
|
3289
|
+
}
|
|
3290
|
+
};
|
|
3291
|
+
var DependentType = class extends Schema {
|
|
3292
|
+
constructor(on, schemaFor, base = new AnyType()) {
|
|
3293
|
+
super();
|
|
3294
|
+
this.on = on;
|
|
3295
|
+
this.schemaFor = schemaFor;
|
|
3296
|
+
this.base = base;
|
|
3297
|
+
}
|
|
3298
|
+
on;
|
|
3299
|
+
schemaFor;
|
|
3300
|
+
base;
|
|
3301
|
+
kind = "dependent";
|
|
3302
|
+
children() {
|
|
3303
|
+
return [this.base];
|
|
3304
|
+
}
|
|
3305
|
+
print(p) {
|
|
3306
|
+
return p.print(this.base);
|
|
3307
|
+
}
|
|
3308
|
+
compile(c) {
|
|
3309
|
+
const base = c.compile(this.base);
|
|
3310
|
+
return c.node({
|
|
3311
|
+
deps: [base],
|
|
3312
|
+
hint: () => this.ruleHint(),
|
|
3313
|
+
emit: () => base.json(),
|
|
3314
|
+
run: (v, cx) => base.run(v, cx),
|
|
3315
|
+
encode: (v, st) => base.encode(v, st)
|
|
3316
|
+
});
|
|
3317
|
+
}
|
|
3318
|
+
};
|
|
3319
|
+
var DispatchType = class extends Schema {
|
|
3320
|
+
constructor(cases, tagKey = "tool", argsKey = "args") {
|
|
3321
|
+
super();
|
|
3322
|
+
this.cases = cases;
|
|
3323
|
+
this.tagKey = tagKey;
|
|
3324
|
+
this.argsKey = argsKey;
|
|
3325
|
+
}
|
|
3326
|
+
cases;
|
|
3327
|
+
tagKey;
|
|
3328
|
+
argsKey;
|
|
3329
|
+
kind = "dispatch";
|
|
3330
|
+
children() {
|
|
3331
|
+
return this.cases.map((x) => x.schema);
|
|
3332
|
+
}
|
|
3333
|
+
print(p) {
|
|
3334
|
+
return this.cases.map((x) => `{ ${this.tagKey}: ${JSON.stringify(x.name)}; ${this.argsKey}: ${p.print(x.schema)} }`).join(" | ");
|
|
3335
|
+
}
|
|
3336
|
+
compile(c) {
|
|
3337
|
+
const names = this.cases.map((x) => x.name);
|
|
3338
|
+
const index = new Map(names.map((n, i) => [n, i]));
|
|
3339
|
+
const nodes = this.cases.map((x) => c.compile(x.schema));
|
|
3340
|
+
const tag = c.compile(new EnumType(names));
|
|
3341
|
+
const tagged = c.profile.unions === "tagged";
|
|
3342
|
+
const { tagKey, argsKey } = this;
|
|
3343
|
+
const list = this.cases.map((x) => `- ${x.name}${x.description ? `: ${x.description}` : ""}`).join("\n");
|
|
3344
|
+
return c.node({
|
|
3345
|
+
own: true,
|
|
3346
|
+
deps: [tag, ...nodes],
|
|
3347
|
+
hint: () => this.hintOf([`Set "${tagKey}" to the tool to run and "${argsKey}" to its arguments.`]),
|
|
3348
|
+
emit: () => {
|
|
3349
|
+
const toolJson = { ...tag.json(), description: [tag.json().description, `The tool to run:
|
|
3350
|
+
${list}`].filter(Boolean).join("\n") };
|
|
3351
|
+
let args;
|
|
3352
|
+
if (tagged) {
|
|
3353
|
+
const props = {};
|
|
3354
|
+
names.forEach((n, i) => props[n] = c.nullable(nodes[i].json()));
|
|
3355
|
+
args = { ...c.object(props, names), description: `Fill only the field named by "${tagKey}"; set the others to null.` };
|
|
3356
|
+
} else {
|
|
3357
|
+
args = nodes.length === 1 ? nodes[0].json() : { anyOf: nodes.map((n) => n.json()) };
|
|
3358
|
+
}
|
|
3359
|
+
return c.object({ [tagKey]: toolJson, [argsKey]: args }, [tagKey, argsKey]);
|
|
3360
|
+
},
|
|
3361
|
+
run: (v0, cx) => {
|
|
3362
|
+
const v = repairJson(v0, cx, "object");
|
|
3363
|
+
if (!isObject(v)) return fail(cx, v, `Expected an object with "${tagKey}" and "${argsKey}".`);
|
|
3364
|
+
const rec = v;
|
|
3365
|
+
const name = rec[tagKey];
|
|
3366
|
+
const i = typeof name === "string" ? index.get(name) : void 0;
|
|
3367
|
+
if (i === void 0) {
|
|
3368
|
+
cx.enter(tagKey);
|
|
3369
|
+
cx.fail(`Expected one of: ${listOf(names)}.`, "tool", name, () => names);
|
|
3370
|
+
cx.leave();
|
|
3371
|
+
return v;
|
|
3372
|
+
}
|
|
3373
|
+
let raw = rec[argsKey];
|
|
3374
|
+
if (tagged) {
|
|
3375
|
+
const box = repairJson(raw, cx, "object");
|
|
3376
|
+
raw = isObject(box) ? box[name] : void 0;
|
|
3377
|
+
cx.enter(argsKey);
|
|
3378
|
+
cx.enter(name, null);
|
|
3379
|
+
} else cx.enter(argsKey);
|
|
3380
|
+
const out = raw === void 0 ? fail(cx, raw, "Required.", "required", nodes[i]) : nodes[i].run(raw, cx);
|
|
3381
|
+
if (tagged) cx.leave(false);
|
|
3382
|
+
cx.leave();
|
|
3383
|
+
if (out !== rec[argsKey] && !cx.dry) return writeKey(rec, rec, argsKey, out, cx);
|
|
3384
|
+
return rec;
|
|
3385
|
+
},
|
|
3386
|
+
encode: (v, st) => {
|
|
3387
|
+
const rec = v;
|
|
3388
|
+
const name = rec[tagKey];
|
|
3389
|
+
const i = index.get(name);
|
|
3390
|
+
if (i === void 0) return v;
|
|
3391
|
+
const enc = nodes[i].encode(rec[argsKey], st);
|
|
3392
|
+
st.objects++;
|
|
3393
|
+
if (!tagged) return { [tagKey]: name, [argsKey]: enc };
|
|
3394
|
+
st.objects++;
|
|
3395
|
+
return { [tagKey]: name, [argsKey]: Object.fromEntries(names.map((n) => [n, n === name ? enc : null])) };
|
|
3396
|
+
}
|
|
3397
|
+
});
|
|
3398
|
+
}
|
|
3399
|
+
};
|
|
3400
|
+
var NeverType = class extends Schema {
|
|
3401
|
+
kind = "never";
|
|
3402
|
+
children() {
|
|
3403
|
+
return [];
|
|
3404
|
+
}
|
|
3405
|
+
print() {
|
|
3406
|
+
return "never";
|
|
3407
|
+
}
|
|
3408
|
+
compile(c) {
|
|
3409
|
+
return neverNode(c, () => this.ruleHint());
|
|
3410
|
+
}
|
|
3411
|
+
};
|
|
3412
|
+
function isNever(s, env) {
|
|
3413
|
+
const d = deref(s, env);
|
|
3414
|
+
if (!d) return false;
|
|
3415
|
+
if (d.kind === "never") return true;
|
|
3416
|
+
if (d instanceof EnumType) return d.values.length === 0;
|
|
3417
|
+
if (d instanceof UnionType) return d.options.every((o) => isNever(o, env));
|
|
3418
|
+
return false;
|
|
3419
|
+
}
|
|
3420
|
+
function neverNode(c, rules) {
|
|
3421
|
+
return c.node({
|
|
3422
|
+
hint: () => ["No value is allowed here.", rules()].filter(Boolean).join(" "),
|
|
3423
|
+
emit: () => c.profile.conditionals ? { not: {} } : { type: "null" },
|
|
3424
|
+
run: (v, cx) => fail(cx, v, "No value is allowed here.", "not-allowed"),
|
|
3425
|
+
encode: (v) => v
|
|
3426
|
+
});
|
|
3427
|
+
}
|
|
3428
|
+
var DefaultType = class extends Schema {
|
|
3429
|
+
constructor(inner, value) {
|
|
3430
|
+
super();
|
|
3431
|
+
this.inner = inner;
|
|
3432
|
+
this.value = value;
|
|
3433
|
+
}
|
|
3434
|
+
inner;
|
|
3435
|
+
value;
|
|
3436
|
+
kind = "default";
|
|
3437
|
+
children() {
|
|
3438
|
+
return [this.inner];
|
|
3439
|
+
}
|
|
3440
|
+
print(p) {
|
|
3441
|
+
return p.print(this.inner);
|
|
3442
|
+
}
|
|
3443
|
+
/** A fresh copy of the default (containers are never shared between decoded values). */
|
|
3444
|
+
fresh(stats) {
|
|
3445
|
+
const v = this.value;
|
|
3446
|
+
if (typeof v !== "object" || v === null) return v;
|
|
3447
|
+
if (stats) {
|
|
3448
|
+
if (Array.isArray(v)) stats.arrays++;
|
|
3449
|
+
else stats.objects++;
|
|
3450
|
+
}
|
|
3451
|
+
return structuredClone(v);
|
|
3452
|
+
}
|
|
3453
|
+
compile(c) {
|
|
3454
|
+
const inner = c.guarded(this.inner, this);
|
|
3455
|
+
const nullMode = c.profile.optional === "null";
|
|
3456
|
+
const nullable2 = this.inner instanceof NullableType;
|
|
3457
|
+
return c.node({
|
|
3458
|
+
own: true,
|
|
3459
|
+
deps: [inner],
|
|
3460
|
+
hint: () => this.hintOf([`Default when left out: ${JSON.stringify(inner.encode(this.value))}.`]),
|
|
3461
|
+
emit: () => nullMode && !nullable2 ? c.nullable(inner.json()) : inner.json(),
|
|
3462
|
+
run: (v, cx) => v === void 0 || v === null && nullMode && !nullable2 ? this.fresh(cx.dry ? void 0 : cx.stats) : inner.run(v, cx),
|
|
3463
|
+
encode: (v, st) => inner.encode(v, st),
|
|
3464
|
+
child: (seg) => inner.child(seg)
|
|
3465
|
+
});
|
|
3466
|
+
}
|
|
3467
|
+
};
|
|
3468
|
+
var OptionalType = class extends Schema {
|
|
3469
|
+
constructor(inner) {
|
|
3470
|
+
super();
|
|
3471
|
+
this.inner = inner;
|
|
3472
|
+
}
|
|
3473
|
+
inner;
|
|
3474
|
+
kind = "optional";
|
|
3475
|
+
children() {
|
|
3476
|
+
return [this.inner];
|
|
3477
|
+
}
|
|
3478
|
+
print(p) {
|
|
3479
|
+
return `${p.print(this.inner)} | undefined`;
|
|
3480
|
+
}
|
|
3481
|
+
/** Outside an object (array element, root): null-for-absent becomes `undefined`. */
|
|
3482
|
+
compile(c) {
|
|
3483
|
+
const inner = c.guarded(this.inner, this);
|
|
3484
|
+
const nullMode = c.profile.optional === "null";
|
|
3485
|
+
return c.node({
|
|
3486
|
+
own: nullMode,
|
|
3487
|
+
deps: [inner],
|
|
3488
|
+
emit: () => nullMode ? c.nullable(inner.json()) : inner.json(),
|
|
3489
|
+
run: (v, cx) => v === void 0 ? v : v === null && nullMode && !(this.inner instanceof NullableType) ? void 0 : inner.run(v, cx),
|
|
3490
|
+
encode: (v, st) => v === void 0 ? nullMode ? null : void 0 : inner.encode(v, st),
|
|
3491
|
+
child: (s) => inner.child(s)
|
|
3492
|
+
});
|
|
3493
|
+
}
|
|
3494
|
+
};
|
|
3495
|
+
var NullableType = class extends Schema {
|
|
3496
|
+
constructor(inner) {
|
|
3497
|
+
super();
|
|
3498
|
+
this.inner = inner;
|
|
3499
|
+
}
|
|
3500
|
+
inner;
|
|
3501
|
+
kind = "nullable";
|
|
3502
|
+
children() {
|
|
3503
|
+
return [this.inner];
|
|
3504
|
+
}
|
|
3505
|
+
print(p) {
|
|
3506
|
+
return `${p.print(this.inner)} | null`;
|
|
3507
|
+
}
|
|
3508
|
+
compile(c) {
|
|
3509
|
+
const inner = c.guarded(this.inner);
|
|
3510
|
+
return c.node({
|
|
3511
|
+
deps: [inner],
|
|
3512
|
+
hint: () => this.ruleHint(),
|
|
3513
|
+
emit: () => c.nullable(inner.json()),
|
|
3514
|
+
run: (v, cx) => v === null ? v : inner.run(v, cx),
|
|
3515
|
+
encode: (v, st) => v === null ? null : inner.encode(v, st),
|
|
3516
|
+
child: (s) => inner.child(s)
|
|
3517
|
+
});
|
|
3518
|
+
}
|
|
3519
|
+
};
|
|
3520
|
+
var RefType = class extends Schema {
|
|
3521
|
+
constructor(name) {
|
|
3522
|
+
super();
|
|
3523
|
+
this.name = name;
|
|
3524
|
+
}
|
|
3525
|
+
name;
|
|
3526
|
+
kind = "ref";
|
|
3527
|
+
children() {
|
|
3528
|
+
return [];
|
|
3529
|
+
}
|
|
3530
|
+
print(p) {
|
|
3531
|
+
return p.ref(this.name);
|
|
3532
|
+
}
|
|
3533
|
+
compile(c) {
|
|
3534
|
+
return c.ref(this.name);
|
|
3535
|
+
}
|
|
3536
|
+
};
|
|
3537
|
+
var CodecType = class extends Schema {
|
|
3538
|
+
constructor(wire, codec2) {
|
|
3539
|
+
super();
|
|
3540
|
+
this.wire = wire;
|
|
3541
|
+
this.codec = codec2;
|
|
3542
|
+
}
|
|
3543
|
+
wire;
|
|
3544
|
+
codec;
|
|
3545
|
+
kind = "codec";
|
|
3546
|
+
children() {
|
|
3547
|
+
return [this.wire];
|
|
3548
|
+
}
|
|
3549
|
+
print(p) {
|
|
3550
|
+
return p.print(this.wire);
|
|
3551
|
+
}
|
|
3552
|
+
compile(c) {
|
|
3553
|
+
const inner = c.compile(this.wire);
|
|
3554
|
+
return c.node({
|
|
3555
|
+
own: true,
|
|
3556
|
+
deps: [inner],
|
|
3557
|
+
hint: () => this.ruleHint(),
|
|
3558
|
+
emit: () => inner.json(),
|
|
3559
|
+
run: (v, cx) => {
|
|
3560
|
+
const before = cx.errors.length;
|
|
3561
|
+
const w = inner.run(v, cx);
|
|
3562
|
+
if (cx.errors.length !== before) return v;
|
|
3563
|
+
const out = this.codec.decode(w);
|
|
3564
|
+
if (out instanceof Error) return fail(cx, v, out.message, "other");
|
|
3565
|
+
if (out instanceof Rejection) {
|
|
3566
|
+
if (!out.issues.length) return fail(cx, v, "Rejected.", "rule");
|
|
3567
|
+
for (const issue of out.issues) cx.failAt(issue.path, issue.message, "rule");
|
|
3568
|
+
return v;
|
|
3569
|
+
}
|
|
3570
|
+
return out;
|
|
3571
|
+
},
|
|
3572
|
+
encode: (v, st) => inner.encode(this.codec.encode(v), st)
|
|
3573
|
+
});
|
|
3574
|
+
}
|
|
3575
|
+
};
|
|
3576
|
+
function isObject(v) {
|
|
3577
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
3578
|
+
}
|
|
3579
|
+
function kind(v) {
|
|
3580
|
+
if (typeof v === "string") return brokenJsonText(v) ?? "string";
|
|
3581
|
+
return v === null ? "null" : Array.isArray(v) ? "a list" : typeof v === "object" ? "an object" : typeof v;
|
|
3582
|
+
}
|
|
3583
|
+
function brokenJsonText(v) {
|
|
3584
|
+
const head = v.trimStart()[0];
|
|
3585
|
+
if (head !== "{" && head !== "[") return void 0;
|
|
3586
|
+
try {
|
|
3587
|
+
JSON.parse(v);
|
|
3588
|
+
return void 0;
|
|
3589
|
+
} catch (e) {
|
|
3590
|
+
return `a string of JSON text that doesn't parse (${e.message}); send the value itself, not as a string`;
|
|
3591
|
+
}
|
|
3592
|
+
}
|
|
3593
|
+
function jsonType(v) {
|
|
3594
|
+
return typeof v === "string" ? "string" : typeof v === "number" ? "number" : typeof v === "boolean" ? "boolean" : "null";
|
|
3595
|
+
}
|
|
3596
|
+
function fail(cx, v, message, kind2 = "type", candidates) {
|
|
3597
|
+
if (typeof candidates === "function") cx.fail(message, kind2, v, candidates);
|
|
3598
|
+
else cx.fail(message, kind2, v, void 0, candidates);
|
|
3599
|
+
return v;
|
|
3600
|
+
}
|
|
3601
|
+
function listOf(values, max = 30) {
|
|
3602
|
+
return values.length <= max ? values.join(", ") : `${values.slice(0, max).join(", ")}, \u2026 (${values.length - max} more)`;
|
|
3603
|
+
}
|
|
3604
|
+
function clip(text, max) {
|
|
3605
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}\u2026`;
|
|
3606
|
+
}
|
|
3607
|
+
function tagValues(o, key, env, depth = 0) {
|
|
3608
|
+
const d = deref(o, env);
|
|
3609
|
+
if (d instanceof ObjectType) {
|
|
3610
|
+
const t = deref(d.shape[key], env);
|
|
3611
|
+
if (t instanceof LiteralType) return [t.value];
|
|
3612
|
+
if (t instanceof EnumType) return [...t.values];
|
|
3613
|
+
return void 0;
|
|
3614
|
+
}
|
|
3615
|
+
if (d instanceof UnionType && depth < 8) {
|
|
3616
|
+
const out = [];
|
|
3617
|
+
for (const x of d.options) {
|
|
3618
|
+
const v = tagValues(x, key, env, depth + 1);
|
|
3619
|
+
if (!v) return void 0;
|
|
3620
|
+
out.push(...v);
|
|
3621
|
+
}
|
|
3622
|
+
return out;
|
|
3623
|
+
}
|
|
3624
|
+
return void 0;
|
|
3625
|
+
}
|
|
3626
|
+
function stringValues(options, env, depth = 0) {
|
|
3627
|
+
const out = [];
|
|
3628
|
+
for (const o of options) {
|
|
3629
|
+
const d = deref(o, env);
|
|
3630
|
+
if (d instanceof EnumType) out.push(...d.values);
|
|
3631
|
+
else if (d instanceof LiteralType && typeof d.value === "string") out.push(d.value);
|
|
3632
|
+
else if (d instanceof UnionType && depth < 8) out.push(...stringValues(d.options, env, depth + 1));
|
|
3633
|
+
}
|
|
3634
|
+
return out;
|
|
3635
|
+
}
|
|
3636
|
+
function optionKeys(o, env, depth = 0) {
|
|
3637
|
+
const d = deref(o, env);
|
|
3638
|
+
if (d instanceof ObjectType) return Object.keys(d.shape);
|
|
3639
|
+
if (d instanceof UnionType && depth < 8) return optionKeys(d.options[0], env, depth + 1);
|
|
3640
|
+
return [];
|
|
3641
|
+
}
|
|
3642
|
+
var autoTags = /* @__PURE__ */ new WeakMap();
|
|
3643
|
+
function autoTag(options, env) {
|
|
3644
|
+
let byEnv = autoTags.get(options);
|
|
3645
|
+
if (!byEnv) autoTags.set(options, byEnv = /* @__PURE__ */ new WeakMap());
|
|
3646
|
+
let found = byEnv.get(env);
|
|
3647
|
+
if (found === void 0) {
|
|
3648
|
+
found = null;
|
|
3649
|
+
if (options.length > 1) {
|
|
3650
|
+
for (const key of optionKeys(options[0], env)) {
|
|
3651
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3652
|
+
let ok = true;
|
|
3653
|
+
for (const o of options) {
|
|
3654
|
+
const vs = tagValues(o, key, env);
|
|
3655
|
+
if (!vs || vs.some((v) => seen.has(v))) {
|
|
3656
|
+
ok = false;
|
|
3657
|
+
break;
|
|
3658
|
+
}
|
|
3659
|
+
for (const v of vs) seen.add(v);
|
|
3660
|
+
}
|
|
3661
|
+
if (ok) {
|
|
3662
|
+
found = key;
|
|
3663
|
+
break;
|
|
3664
|
+
}
|
|
3665
|
+
}
|
|
3666
|
+
}
|
|
3667
|
+
byEnv.set(env, found);
|
|
3668
|
+
}
|
|
3669
|
+
return found ?? void 0;
|
|
3670
|
+
}
|
|
3671
|
+
function closestOption(options, v, env) {
|
|
3672
|
+
if (!isObject(v)) return -1;
|
|
3673
|
+
const rec = v;
|
|
3674
|
+
let best = -1;
|
|
3675
|
+
let bestScore = 0;
|
|
3676
|
+
let tie = false;
|
|
3677
|
+
options.forEach((o, i) => {
|
|
3678
|
+
let score = 0;
|
|
3679
|
+
for (const k of optionKeys(o, env)) {
|
|
3680
|
+
const vs = tagValues(o, k, env);
|
|
3681
|
+
if (vs && k in rec) score += vs.includes(rec[k]) ? 1 : -1;
|
|
3682
|
+
}
|
|
3683
|
+
if (score > bestScore) {
|
|
3684
|
+
best = i;
|
|
3685
|
+
bestScore = score;
|
|
3686
|
+
tie = false;
|
|
3687
|
+
} else if (score === bestScore && score > 0) tie = true;
|
|
3688
|
+
});
|
|
3689
|
+
if (!tie && best >= 0) return best;
|
|
3690
|
+
const keys = Object.keys(rec);
|
|
3691
|
+
if (!keys.length) return -1;
|
|
3692
|
+
best = -1;
|
|
3693
|
+
bestScore = 0;
|
|
3694
|
+
tie = false;
|
|
3695
|
+
options.forEach((o, i) => {
|
|
3696
|
+
const own = new Set(optionKeys(o, env));
|
|
3697
|
+
if (!own.size || keys.some((k) => !own.has(k))) return;
|
|
3698
|
+
const score = keys.length;
|
|
3699
|
+
if (score > bestScore) {
|
|
3700
|
+
best = i;
|
|
3701
|
+
bestScore = score;
|
|
3702
|
+
tie = false;
|
|
3703
|
+
} else if (score === bestScore) tie = true;
|
|
3704
|
+
});
|
|
3705
|
+
return tie ? -1 : best;
|
|
3706
|
+
}
|
|
3707
|
+
function jsonWrapped(c, n, key = "json") {
|
|
3708
|
+
const w = c.node({
|
|
3709
|
+
own: true,
|
|
3710
|
+
deps: [n],
|
|
3711
|
+
emit: () => c.object({ [key]: n.json() }, [key]),
|
|
3712
|
+
run: (v, cx) => {
|
|
3713
|
+
if (!isObject(v) || !(key in v)) return fail(cx, v, key === "json" ? 'Expected {"json": "<JSON text>"}.' : `Expected {"${key}": [...]}.`);
|
|
3714
|
+
cx.enter(key, null);
|
|
3715
|
+
const out = n.run(v[key], cx);
|
|
3716
|
+
cx.leave(false);
|
|
3717
|
+
return out;
|
|
3718
|
+
},
|
|
3719
|
+
encode: (v, st) => {
|
|
3720
|
+
st.objects++;
|
|
3721
|
+
return { [key]: n.encode(v, st) };
|
|
3722
|
+
}
|
|
3723
|
+
});
|
|
3724
|
+
c.nodes.push(w);
|
|
3725
|
+
return w;
|
|
3726
|
+
}
|
|
3727
|
+
function deref(s, env) {
|
|
3728
|
+
for (let hops = 0; s instanceof RefType && hops < 16; hops++) s = env.get(s.name);
|
|
3729
|
+
return s;
|
|
3730
|
+
}
|
|
3731
|
+
function matches(c, s, value) {
|
|
3732
|
+
const d = new Cx(false, true, newStats(), false, true);
|
|
3733
|
+
c.lenient().nodeFor(s).run(value, d);
|
|
3734
|
+
return d.errors.length === 0;
|
|
3735
|
+
}
|
|
3736
|
+
function keyword(j, words, key, value, supported, phrase) {
|
|
3737
|
+
if (value === void 0) return;
|
|
3738
|
+
if (supported) j[key] = value;
|
|
3739
|
+
else if (!words.includes(phrase)) words.push(phrase);
|
|
3740
|
+
}
|
|
3741
|
+
function repairJson(v, cx, want) {
|
|
3742
|
+
if (!cx.repair || typeof v !== "string") return v;
|
|
3743
|
+
let x = v;
|
|
3744
|
+
for (let i = 0; i < 2 && typeof x === "string"; i++) {
|
|
3745
|
+
const t = x.trim();
|
|
3746
|
+
if (!/^[[{"]/.test(t)) return v;
|
|
3747
|
+
try {
|
|
3748
|
+
x = JSON.parse(t);
|
|
3749
|
+
} catch {
|
|
3750
|
+
return v;
|
|
3751
|
+
}
|
|
3752
|
+
}
|
|
3753
|
+
if (want === "array" ? Array.isArray(x) : isObject(x)) {
|
|
3754
|
+
if (!cx.dry) cx.stats.repaired++;
|
|
3755
|
+
return x;
|
|
3756
|
+
}
|
|
3757
|
+
return v;
|
|
3758
|
+
}
|
|
3759
|
+
function encodeItems(arr, enc, st) {
|
|
3760
|
+
let out = arr;
|
|
3761
|
+
for (let i = 0; i < arr.length; i++) {
|
|
3762
|
+
const e = enc(arr[i], i);
|
|
3763
|
+
if (e !== arr[i]) {
|
|
3764
|
+
if (out === arr) {
|
|
3765
|
+
out = arr.slice();
|
|
3766
|
+
st.arrays++;
|
|
3767
|
+
}
|
|
3768
|
+
out[i] = e;
|
|
3769
|
+
}
|
|
3770
|
+
}
|
|
3771
|
+
return out;
|
|
3772
|
+
}
|
|
3773
|
+
function writeKey(out, orig, key, value, cx) {
|
|
3774
|
+
if (cx.inPlace) {
|
|
3775
|
+
cx.saving(orig, key);
|
|
3776
|
+
orig[key] = value;
|
|
3777
|
+
cx.stats.edits++;
|
|
3778
|
+
return orig;
|
|
3779
|
+
}
|
|
3780
|
+
if (out === orig) {
|
|
3781
|
+
out = { ...orig };
|
|
3782
|
+
cx.stats.objects++;
|
|
3783
|
+
}
|
|
3784
|
+
out[key] = value;
|
|
3785
|
+
return out;
|
|
3786
|
+
}
|
|
3787
|
+
function deleteKey(out, orig, key, cx) {
|
|
3788
|
+
if (cx.inPlace) {
|
|
3789
|
+
cx.saving(orig, key, true);
|
|
3790
|
+
delete orig[key];
|
|
3791
|
+
cx.stats.edits++;
|
|
3792
|
+
return orig;
|
|
3793
|
+
}
|
|
3794
|
+
if (out === orig) {
|
|
3795
|
+
out = { ...orig };
|
|
3796
|
+
cx.stats.objects++;
|
|
3797
|
+
}
|
|
3798
|
+
delete out[key];
|
|
3799
|
+
return out;
|
|
3800
|
+
}
|
|
3801
|
+
function writeIndex(out, orig, i, value, cx) {
|
|
3802
|
+
if (cx.inPlace) {
|
|
3803
|
+
cx.saving(orig, i);
|
|
3804
|
+
orig[i] = value;
|
|
3805
|
+
cx.stats.edits++;
|
|
3806
|
+
return orig;
|
|
3807
|
+
}
|
|
3808
|
+
if (out === orig) {
|
|
3809
|
+
out = orig.slice();
|
|
3810
|
+
cx.stats.arrays++;
|
|
3811
|
+
}
|
|
3812
|
+
out[i] = value;
|
|
3813
|
+
return out;
|
|
3814
|
+
}
|
|
3815
|
+
|
|
3816
|
+
// src/json-schema.ts
|
|
3817
|
+
function fromJSONSchema(schema, report = { unsupported: [] }) {
|
|
3818
|
+
const root = typeof schema === "object" ? schema : {};
|
|
3819
|
+
const rawDefs = { ...root.definitions ?? {}, ...root.$defs ?? {} };
|
|
3820
|
+
const defs = {};
|
|
3821
|
+
let usesRoot = false;
|
|
3822
|
+
const refName2 = (ref2) => {
|
|
3823
|
+
if (ref2 === "#") {
|
|
3824
|
+
usesRoot = true;
|
|
3825
|
+
return "__root";
|
|
3826
|
+
}
|
|
3827
|
+
const m = /^#\/(?:\$defs|definitions)\/(.+)$/.exec(ref2);
|
|
3828
|
+
if (!m) {
|
|
3829
|
+
report.unsupported.push(`$ref ${ref2}`);
|
|
3830
|
+
return "__any";
|
|
3831
|
+
}
|
|
3832
|
+
return m[1].replace(/~1/g, "/").replace(/~0/g, "~");
|
|
3833
|
+
};
|
|
3834
|
+
const conv = (j) => {
|
|
3835
|
+
if (j === true || j === void 0) return new AnyType();
|
|
3836
|
+
if (j === false) return new UnionType([new NullType()]).refine(() => false, "No value is allowed here.");
|
|
3837
|
+
const { allOf, not: not2, if: cond, then, else: otherwise, ...rest } = j;
|
|
3838
|
+
const bare = Object.keys(rest).every((k) => ["description", "title", "examples", "$comment", "default"].includes(k));
|
|
3839
|
+
let s = convBody(rest);
|
|
3840
|
+
if (Array.isArray(allOf) && allOf.length) {
|
|
3841
|
+
const members = allOf.map(conv);
|
|
3842
|
+
const all = bare ? members : [s, ...members];
|
|
3843
|
+
s = all.length === 1 ? all[0] : new IntersectionType(all);
|
|
3844
|
+
}
|
|
3845
|
+
if (not2 !== void 0) s = new NotType(conv(not2), s);
|
|
3846
|
+
if (cond !== void 0) s = new ConditionalType(s, conv(cond), then !== void 0 ? conv(then) : void 0, otherwise !== void 0 ? conv(otherwise) : void 0);
|
|
3847
|
+
for (const k of ["dependentSchemas", "dependentRequired"]) if (k in j) report.unsupported.push(k);
|
|
3848
|
+
if (typeof j.description === "string") s = s.describe(j.description);
|
|
3849
|
+
if (typeof j.title === "string") s = s.title(j.title);
|
|
3850
|
+
if (Array.isArray(j.examples)) s = s.example(...j.examples);
|
|
3851
|
+
return s;
|
|
3852
|
+
};
|
|
3853
|
+
const convBody = (j) => {
|
|
3854
|
+
if (typeof j.$ref === "string") return new RefType(refName2(j.$ref));
|
|
3855
|
+
if ("const" in j) return new LiteralType(j.const);
|
|
3856
|
+
if (Array.isArray(j.enum)) {
|
|
3857
|
+
const vals = j.enum;
|
|
3858
|
+
const strings = vals.filter((v) => typeof v === "string");
|
|
3859
|
+
const hasNull = vals.includes(null);
|
|
3860
|
+
const base = strings.length === vals.length - (hasNull ? 1 : 0) && strings.length ? new EnumType(strings) : new UnionType(vals.filter((v) => v !== null).map((v) => new LiteralType(v)));
|
|
3861
|
+
return hasNull ? new NullableType(base) : base;
|
|
3862
|
+
}
|
|
3863
|
+
const alts = j.anyOf ?? j.oneOf;
|
|
3864
|
+
if (Array.isArray(alts)) {
|
|
3865
|
+
const opts = alts.map(conv);
|
|
3866
|
+
const nonNull = opts.filter((o) => !(o instanceof NullType));
|
|
3867
|
+
const u = nonNull.length === 1 ? nonNull[0] : new UnionType(nonNull);
|
|
3868
|
+
return nonNull.length < opts.length ? new NullableType(u) : u;
|
|
3869
|
+
}
|
|
3870
|
+
if (Array.isArray(j.type)) {
|
|
3871
|
+
const types = j.type;
|
|
3872
|
+
const nonNull = types.filter((t) => t !== "null");
|
|
3873
|
+
const parts = nonNull.map((t) => convBody({ ...j, type: t }));
|
|
3874
|
+
const u = parts.length === 1 ? parts[0] : parts.length ? new UnionType(parts) : new NullType();
|
|
3875
|
+
return types.includes("null") && parts.length ? new NullableType(u) : u;
|
|
3876
|
+
}
|
|
3877
|
+
const type = j.type ?? implied(j);
|
|
3878
|
+
switch (type) {
|
|
3879
|
+
case "string": {
|
|
3880
|
+
let s = new StringType();
|
|
3881
|
+
if (typeof j.minLength === "number") s = s.min(j.minLength);
|
|
3882
|
+
if (typeof j.maxLength === "number") s = s.max(j.maxLength);
|
|
3883
|
+
if (typeof j.pattern === "string") s = s.pattern(j.pattern);
|
|
3884
|
+
if (typeof j.format === "string") s = s.format(j.format);
|
|
3885
|
+
return s;
|
|
3886
|
+
}
|
|
3887
|
+
case "number":
|
|
3888
|
+
case "integer": {
|
|
3889
|
+
let s = new NumberType({ int: j.type === "integer" });
|
|
3890
|
+
if (typeof j.minimum === "number") s = s.min(j.minimum);
|
|
3891
|
+
if (typeof j.maximum === "number") s = s.max(j.maximum);
|
|
3892
|
+
return s;
|
|
3893
|
+
}
|
|
3894
|
+
case "boolean":
|
|
3895
|
+
return new BooleanType();
|
|
3896
|
+
case "null":
|
|
3897
|
+
return new NullType();
|
|
3898
|
+
case "array": {
|
|
3899
|
+
if (Array.isArray(j.prefixItems) && j.prefixItems.length) return new TupleType(j.prefixItems.map(conv));
|
|
3900
|
+
let s = new ArrayType(conv(j.items ?? true));
|
|
3901
|
+
if (typeof j.minItems === "number") s = s.min(j.minItems);
|
|
3902
|
+
if (typeof j.maxItems === "number") s = s.max(j.maxItems);
|
|
3903
|
+
return s;
|
|
3904
|
+
}
|
|
3905
|
+
case "object":
|
|
3906
|
+
default: {
|
|
3907
|
+
if (type === void 0 && !j.properties && !j.patternProperties && j.additionalProperties === void 0 && !j.required) return new AnyType();
|
|
3908
|
+
if (!j.properties && !j.patternProperties && j.additionalProperties === void 0 && !j.required) return new RecordType(new AnyType());
|
|
3909
|
+
const props = j.properties ?? {};
|
|
3910
|
+
const required = new Set(j.required ?? []);
|
|
3911
|
+
const ap = j.additionalProperties;
|
|
3912
|
+
const pp = j.patternProperties;
|
|
3913
|
+
if (!Object.keys(props).length && !pp && ap !== void 0 && ap !== false && ap !== true) return new RecordType(conv(ap));
|
|
3914
|
+
const shape = {};
|
|
3915
|
+
for (const [k, p] of Object.entries(props)) shape[k] = required.has(k) ? conv(p) : new OptionalType(conv(p));
|
|
3916
|
+
for (const k of required) if (!(k in shape)) shape[k] = new AnyType();
|
|
3917
|
+
let o = new ObjectType(shape);
|
|
3918
|
+
if (pp) o = o.patterns(Object.fromEntries(Object.entries(pp).map(([p, v]) => [p, conv(v)])));
|
|
3919
|
+
if (ap !== void 0 && typeof ap === "object") o = o.rest(conv(ap));
|
|
3920
|
+
return ap === false ? o.strict() : o;
|
|
3921
|
+
}
|
|
3922
|
+
}
|
|
3923
|
+
};
|
|
3924
|
+
for (const [name, d] of Object.entries(rawDefs)) defs[name] = conv(d);
|
|
3925
|
+
const { $defs: _a, definitions: _b, ...body } = root;
|
|
3926
|
+
const top = conv(body);
|
|
3927
|
+
if (usesRoot) defs.__root = top;
|
|
3928
|
+
if (report.unsupported.includes("$ref") || Object.values(defs).some(() => false)) defs.__any = new AnyType();
|
|
3929
|
+
for (const n of [top, ...Object.values(defs)].flatMap((s) => [...s.refNames()])) {
|
|
3930
|
+
if (n in defs) continue;
|
|
3931
|
+
if (!n.startsWith("__")) report.unsupported.push(`$ref to a missing definition "${n}" (any JSON instead)`);
|
|
3932
|
+
defs[n] = new AnyType().describe(`Unknown reference ${n}.`);
|
|
3933
|
+
}
|
|
3934
|
+
return new Bundle(defs, usesRoot ? new RefType("__root") : top);
|
|
3935
|
+
}
|
|
3936
|
+
function implied(j) {
|
|
3937
|
+
if (["minLength", "maxLength", "pattern", "format"].some((k) => k in j)) return "string";
|
|
3938
|
+
if (["minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"].some((k) => k in j)) return "number";
|
|
3939
|
+
if (["items", "prefixItems", "minItems", "maxItems"].some((k) => k in j)) return "array";
|
|
3940
|
+
if (["properties", "required", "patternProperties", "additionalProperties"].some((k) => k in j)) return "object";
|
|
3941
|
+
return void 0;
|
|
3942
|
+
}
|
|
3943
|
+
|
|
3944
|
+
// src/a.ts
|
|
3945
|
+
var string = () => new StringType();
|
|
3946
|
+
var number = () => new NumberType();
|
|
3947
|
+
var int = () => new NumberType({ int: true });
|
|
3948
|
+
var boolean = () => new BooleanType();
|
|
3949
|
+
var null_ = () => new NullType();
|
|
3950
|
+
var literal = (value) => new LiteralType(value);
|
|
3951
|
+
function enum_(values) {
|
|
3952
|
+
return new EnumType([...values]);
|
|
3953
|
+
}
|
|
3954
|
+
var never_ = () => new NeverType();
|
|
3955
|
+
var unknown = () => new AnyType();
|
|
3956
|
+
var json = () => new AnyType();
|
|
3957
|
+
var object = (shape) => new ObjectType(shape);
|
|
3958
|
+
var array = (element) => new ArrayType(element);
|
|
3959
|
+
var tuple = (items) => new TupleType(items);
|
|
3960
|
+
function record(a1, a2) {
|
|
3961
|
+
return a2 ? new RecordType(a2, a1) : new RecordType(a1);
|
|
3962
|
+
}
|
|
3963
|
+
function union(options) {
|
|
3964
|
+
return new UnionType([...options]);
|
|
3965
|
+
}
|
|
3966
|
+
function discriminatedUnion(tag, options) {
|
|
3967
|
+
return new UnionType([...options], tag);
|
|
3968
|
+
}
|
|
3969
|
+
var intersection = (members) => new IntersectionType(members);
|
|
3970
|
+
function not(excluded, base) {
|
|
3971
|
+
return new NotType(excluded, base ?? new AnyType());
|
|
3972
|
+
}
|
|
3973
|
+
function conditional(base, rule) {
|
|
3974
|
+
return new ConditionalType(base, rule.if, rule.then, rule.else);
|
|
3975
|
+
}
|
|
3976
|
+
function dependent(on, schemaFor, base) {
|
|
3977
|
+
return new DependentType(on, schemaFor, base);
|
|
3978
|
+
}
|
|
3979
|
+
var optional = (inner) => new OptionalType(inner);
|
|
3980
|
+
var default_ = (inner, value) => new DefaultType(inner, value);
|
|
3981
|
+
var nullable = (inner) => new NullableType(inner);
|
|
3982
|
+
var ref = (name) => new RefType(name);
|
|
3983
|
+
var refOf = (name) => new RefType(name);
|
|
3984
|
+
var codec = (wire, codec2) => new CodecType(wire, codec2);
|
|
3985
|
+
var dispatch = (cases, keys = {}) => new DispatchType(cases, keys.tag ?? "tool", keys.args ?? "args");
|
|
3986
|
+
var define = (defs) => new Module(defs);
|
|
3987
|
+
var declare = () => new Module();
|
|
3988
|
+
var module_ = () => new Module();
|
|
3989
|
+
|
|
3990
|
+
// src/template.ts
|
|
3991
|
+
var SCHEMA_DATA_KEY = "aeyeSchema";
|
|
3992
|
+
var Safe = class {
|
|
3993
|
+
constructor(text) {
|
|
3994
|
+
this.text = text;
|
|
3995
|
+
}
|
|
3996
|
+
text;
|
|
3997
|
+
toHTML() {
|
|
3998
|
+
return this.text;
|
|
3999
|
+
}
|
|
4000
|
+
toString() {
|
|
4001
|
+
return this.text;
|
|
4002
|
+
}
|
|
4003
|
+
};
|
|
4004
|
+
function isRequest(t) {
|
|
4005
|
+
return "entries" in t && "degradations" in t;
|
|
4006
|
+
}
|
|
4007
|
+
function resolve(target, hash, defaultName) {
|
|
4008
|
+
if (!isRequest(target)) {
|
|
4009
|
+
if (hash?.tool !== void 0 || hash?.output !== void 0) {
|
|
4010
|
+
throw new Error("@aeye/schema: tool=/output= need a whole request (request.helpers()).");
|
|
4011
|
+
}
|
|
4012
|
+
return "rendered" in target ? target.rendered : target;
|
|
4013
|
+
}
|
|
4014
|
+
const name = typeof hash?.tool === "string" ? hash.tool : hash?.output ? target.output?.name : defaultName ?? (target.entries.length === 1 ? target.entries[0].name : void 0);
|
|
4015
|
+
if (name === void 0) throw new Error('@aeye/schema: say which schema: {{encode value tool="name"}} or output=true.');
|
|
4016
|
+
if (!target.has(name)) throw new Error(`@aeye/schema: no schema named "${name}" in this request.`);
|
|
4017
|
+
return target.get(name).rendered;
|
|
4018
|
+
}
|
|
4019
|
+
function optionsOf(hash) {
|
|
4020
|
+
const out = {};
|
|
4021
|
+
if (hash?.pretty !== void 0) out.pretty = hash.pretty;
|
|
4022
|
+
if (typeof hash?.path === "string") out.path = hash.path;
|
|
4023
|
+
return out;
|
|
4024
|
+
}
|
|
4025
|
+
function makeHelpers(get) {
|
|
4026
|
+
return {
|
|
4027
|
+
encode(...args) {
|
|
4028
|
+
const options = args[args.length - 1];
|
|
4029
|
+
if (args.length < 2) throw new Error("@aeye/schema: {{encode value}} needs a value.");
|
|
4030
|
+
const { target, defaultName } = get(options);
|
|
4031
|
+
return new Safe(resolve(target, options.hash, defaultName).encodeText(args[0], optionsOf(options.hash)));
|
|
4032
|
+
},
|
|
4033
|
+
schema(...args) {
|
|
4034
|
+
const options = args[args.length - 1];
|
|
4035
|
+
const { target, defaultName } = get(options);
|
|
4036
|
+
return new Safe(resolve(target, options.hash, defaultName).typescript());
|
|
4037
|
+
}
|
|
4038
|
+
};
|
|
4039
|
+
}
|
|
4040
|
+
function schemaHelpers(target, defaultName) {
|
|
4041
|
+
const bound = { target, defaultName };
|
|
4042
|
+
return makeHelpers(() => bound);
|
|
4043
|
+
}
|
|
4044
|
+
function schemaData(target, defaultName) {
|
|
4045
|
+
return { [SCHEMA_DATA_KEY]: { target, defaultName } };
|
|
4046
|
+
}
|
|
4047
|
+
function registerSchemaHelpers(handlebars, names = {}) {
|
|
4048
|
+
const helpers = makeHelpers((options) => {
|
|
4049
|
+
const d = options.data?.[SCHEMA_DATA_KEY];
|
|
4050
|
+
if (!d) throw new Error("@aeye/schema: no schema for this render; pass { data: schemaData(entry) } to the template.");
|
|
4051
|
+
return d;
|
|
4052
|
+
});
|
|
4053
|
+
handlebars.registerHelper(names.encode ?? "encode", helpers.encode);
|
|
4054
|
+
handlebars.registerHelper(names.schema ?? "schema", helpers.schema);
|
|
4055
|
+
}
|
|
4056
|
+
|
|
4057
|
+
// src/request.ts
|
|
4058
|
+
function strictPriority(requested) {
|
|
4059
|
+
if (requested === true) return Infinity;
|
|
4060
|
+
if (requested === false) return -Infinity;
|
|
4061
|
+
if (typeof requested === "number") return requested > 0 ? requested : 0;
|
|
4062
|
+
return 0;
|
|
4063
|
+
}
|
|
4064
|
+
var RequestEntry = class {
|
|
4065
|
+
constructor(name, kind2, requested, base, profile, strict, delivery, adjustments, reasons, rendered, requestedName = name, via, boundSchema = void 0) {
|
|
4066
|
+
this.name = name;
|
|
4067
|
+
this.kind = kind2;
|
|
4068
|
+
this.requested = requested;
|
|
4069
|
+
this.base = base;
|
|
4070
|
+
this.profile = profile;
|
|
4071
|
+
this.strict = strict;
|
|
4072
|
+
this.delivery = delivery;
|
|
4073
|
+
this.adjustments = adjustments;
|
|
4074
|
+
this.reasons = reasons;
|
|
4075
|
+
this.rendered = rendered;
|
|
4076
|
+
this.requestedName = requestedName;
|
|
4077
|
+
this.via = via;
|
|
4078
|
+
this.boundSchema = boundSchema;
|
|
4079
|
+
}
|
|
4080
|
+
name;
|
|
4081
|
+
kind;
|
|
4082
|
+
requested;
|
|
4083
|
+
base;
|
|
4084
|
+
profile;
|
|
4085
|
+
strict;
|
|
4086
|
+
delivery;
|
|
4087
|
+
adjustments;
|
|
4088
|
+
reasons;
|
|
4089
|
+
rendered;
|
|
4090
|
+
requestedName;
|
|
4091
|
+
via;
|
|
4092
|
+
boundSchema;
|
|
4093
|
+
/** How a bad answer is told to the model: the request's format, then the item's (`ToolItem.errorFormat`). */
|
|
4094
|
+
errorFormat;
|
|
4095
|
+
/** What the model wrote, as the error message names it: `the arguments of search`, `your answer`. */
|
|
4096
|
+
get label() {
|
|
4097
|
+
if (this.kind === "output") return "your answer";
|
|
4098
|
+
return this.via ? `the arguments of ${this.requestedName} (called through ${this.via})` : `the arguments of ${this.requestedName}`;
|
|
4099
|
+
}
|
|
4100
|
+
/** Parse options with this entry's error format and label (a call's own options win). */
|
|
4101
|
+
opts(opts) {
|
|
4102
|
+
return { ...opts, errorFormat: mergeErrorFormats(this.errorFormat, opts?.errorFormat), label: opts?.label ?? this.label };
|
|
4103
|
+
}
|
|
4104
|
+
/** The JSON Schema to send; `undefined` when the schema goes as prompt text or through the dispatcher. */
|
|
4105
|
+
get jsonSchema() {
|
|
4106
|
+
return this.delivery === "structured" ? this.rendered.jsonSchema : void 0;
|
|
4107
|
+
}
|
|
4108
|
+
/** The schema as prompt text (prompt-text delivery), with the family's JSON instruction. */
|
|
4109
|
+
get promptText() {
|
|
4110
|
+
return `${this.rendered.typescript()}
|
|
4111
|
+
|
|
4112
|
+
${this.base.jsonInstruction ?? DEFAULT_JSON_INSTRUCTION}`;
|
|
4113
|
+
}
|
|
4114
|
+
/** What this schema counts toward the provider's limits. */
|
|
4115
|
+
get measure() {
|
|
4116
|
+
return this.rendered.measure;
|
|
4117
|
+
}
|
|
4118
|
+
/** Decode the model's answer; a failure's `message` is in this entry's error format. */
|
|
4119
|
+
parse(wire, opts) {
|
|
4120
|
+
return this.rendered.parse(wire, this.opts(opts));
|
|
4121
|
+
}
|
|
4122
|
+
parseText(text, opts) {
|
|
4123
|
+
return this.rendered.parseText(text, this.opts(opts));
|
|
4124
|
+
}
|
|
4125
|
+
parseOrThrow(wire, opts) {
|
|
4126
|
+
return this.rendered.parseOrThrow(wire, this.opts(opts));
|
|
4127
|
+
}
|
|
4128
|
+
/** A value as this model writes it for this schema. */
|
|
4129
|
+
encode(value, stats) {
|
|
4130
|
+
return this.rendered.encode(value, stats);
|
|
4131
|
+
}
|
|
4132
|
+
encodeText(value, opts) {
|
|
4133
|
+
return this.rendered.encodeText(value, opts);
|
|
4134
|
+
}
|
|
4135
|
+
/** `encode` needing only the value: for instruction functions, examples and injected values. */
|
|
4136
|
+
get encoder() {
|
|
4137
|
+
return this.rendered.encoder;
|
|
4138
|
+
}
|
|
4139
|
+
/** Handlebars helpers bound to this schema (`{{encode value}}`, `{{schema}}`). */
|
|
4140
|
+
helpers() {
|
|
4141
|
+
return schemaHelpers(this);
|
|
4142
|
+
}
|
|
4143
|
+
};
|
|
4144
|
+
var RenderedRequest = class {
|
|
4145
|
+
constructor(target, entries, used, strictTools, limits, degradations, dispatcher, checkLater = /* @__PURE__ */ new Set()) {
|
|
4146
|
+
this.target = target;
|
|
4147
|
+
this.entries = entries;
|
|
4148
|
+
this.used = used;
|
|
4149
|
+
this.strictTools = strictTools;
|
|
4150
|
+
this.limits = limits;
|
|
4151
|
+
this.degradations = degradations;
|
|
4152
|
+
this.dispatcher = dispatcher;
|
|
4153
|
+
this.checkLater = checkLater;
|
|
4154
|
+
for (const e of entries) this.byName.set(e.name, e);
|
|
4155
|
+
}
|
|
4156
|
+
target;
|
|
4157
|
+
entries;
|
|
4158
|
+
used;
|
|
4159
|
+
strictTools;
|
|
4160
|
+
limits;
|
|
4161
|
+
degradations;
|
|
4162
|
+
dispatcher;
|
|
4163
|
+
checkLater;
|
|
4164
|
+
byName = /* @__PURE__ */ new Map();
|
|
4165
|
+
/** The entry of a tool by name, or of the output (`'output'` unless named). */
|
|
4166
|
+
get(name) {
|
|
4167
|
+
const e = this.byName.get(name);
|
|
4168
|
+
if (!e) throw new Error(`@aeye/schema: no schema named "${name}" in this request.`);
|
|
4169
|
+
return e;
|
|
4170
|
+
}
|
|
4171
|
+
has(name) {
|
|
4172
|
+
return this.byName.has(name);
|
|
4173
|
+
}
|
|
4174
|
+
/** Every tool entry (dispatched ones included). */
|
|
4175
|
+
get tools() {
|
|
4176
|
+
return this.entries.filter((e) => e.kind === "tool");
|
|
4177
|
+
}
|
|
4178
|
+
/** The tools to SEND: each direct tool, and the dispatcher. */
|
|
4179
|
+
get sent() {
|
|
4180
|
+
return this.entries.filter((e) => e.kind === "tool" && e.delivery === "structured");
|
|
4181
|
+
}
|
|
4182
|
+
get output() {
|
|
4183
|
+
return this.entries.find((e) => e.kind === "output");
|
|
4184
|
+
}
|
|
4185
|
+
/**
|
|
4186
|
+
* Decode a tool call the model made: by the name it called and its raw
|
|
4187
|
+
* args (parsed JSON). A dispatcher call comes back as the ORIGINAL tool's
|
|
4188
|
+
* name and decoded args, with `via` naming the dispatcher.
|
|
4189
|
+
*/
|
|
4190
|
+
decodeCall(name, args, opts) {
|
|
4191
|
+
const d = this.dispatcher;
|
|
4192
|
+
if (d && name === d.name) {
|
|
4193
|
+
const named = typeof args?.tool === "string" ? this.byName.get(args.tool) : void 0;
|
|
4194
|
+
const inner0 = named?.delivery === "dispatched" ? named : void 0;
|
|
4195
|
+
const res2 = d.parse(args, {
|
|
4196
|
+
...opts,
|
|
4197
|
+
errorFormat: mergeErrorFormats(d.errorFormat, inner0?.errorFormat, opts?.errorFormat),
|
|
4198
|
+
label: opts?.label ?? (inner0 ? inner0.label : `your call to ${d.name}`)
|
|
4199
|
+
});
|
|
4200
|
+
if (!res2.ok) return { ok: false, tool: inner0?.requestedName, issues: res2.issues, message: res2.message };
|
|
4201
|
+
const inner = this.byName.get(res2.value.tool);
|
|
4202
|
+
if (this.checkLater.has(inner.name)) {
|
|
4203
|
+
const checked = innerLenient(inner).parse(res2.value.args, { ...opts, errorFormat: mergeErrorFormats(inner.errorFormat, opts?.errorFormat), label: opts?.label ?? inner.label });
|
|
4204
|
+
if (!checked.ok) return { ok: false, tool: inner.requestedName, issues: checked.issues, message: checked.message };
|
|
4205
|
+
return { ok: true, tool: inner.requestedName, value: checked.value, via: d.name };
|
|
4206
|
+
}
|
|
4207
|
+
return { ok: true, tool: inner.requestedName, value: res2.value.args, via: d.name };
|
|
4208
|
+
}
|
|
4209
|
+
const e = this.byName.get(name);
|
|
4210
|
+
if (!e || e.kind !== "tool") return this.unknownTool(name, opts);
|
|
4211
|
+
const res = e.parse(args, e.delivery === "dispatched" ? { ...opts, label: opts?.label ?? `the arguments of ${e.requestedName}` } : opts);
|
|
4212
|
+
return res.ok ? { ok: true, tool: e.requestedName, value: res.value } : { ok: false, tool: e.requestedName, issues: res.issues, message: res.message };
|
|
4213
|
+
}
|
|
4214
|
+
/** A call to a tool the request doesn't have: the nearest name, or the list. */
|
|
4215
|
+
unknownTool(name, opts) {
|
|
4216
|
+
const names = this.entries.filter((x) => x.kind === "tool" && x !== this.dispatcher).map((x) => x.name);
|
|
4217
|
+
const near = rankNear(name, names)[0];
|
|
4218
|
+
const hint = near !== void 0 ? ` \u2014 did you mean \`${near}\`?` : ` Tools: ${names.slice(0, 30).join(", ")}${names.length > 30 ? `, \u2026 (${names.length - 30} more)` : ""}.`;
|
|
4219
|
+
const issue = { path: [], codePath: [], message: `No tool named "${name}" in this request.` };
|
|
4220
|
+
recordIssue(issue, { kind: "tool", received: name, candidates: () => names });
|
|
4221
|
+
const f = errorFormat(opts?.errorFormat);
|
|
4222
|
+
const text = near === void 0 ? `${issue.message}${hint}` : f.suggestions ? `${issue.message.replace(/\.$/, "")}${hint}` : issue.message;
|
|
4223
|
+
const message = text.length <= f.maxChars ? text : formatErrors([issue], void 0, { ...f, detail: "summary" }, `your call to ${name}`);
|
|
4224
|
+
return { ok: false, tool: void 0, issues: [issue], message };
|
|
4225
|
+
}
|
|
4226
|
+
/** A call to a tool as this model would make it: `{ name, args }` (through the dispatcher when the tool is behind it). */
|
|
4227
|
+
encodeCall(tool, value) {
|
|
4228
|
+
const e = this.byName.get(tool);
|
|
4229
|
+
if (!e) throw new Error(`@aeye/schema: no schema named "${tool}" in this request.`);
|
|
4230
|
+
if (e.delivery === "dispatched" && this.dispatcher) return { name: this.dispatcher.name, args: this.dispatcher.encode({ tool: e.name, args: value }) };
|
|
4231
|
+
return { name: e.name, args: e.encode(value) };
|
|
4232
|
+
}
|
|
4233
|
+
/** Throw a `RequestLimitError` when anything was degraded (opt-in; requests never throw by themselves). */
|
|
4234
|
+
assertNoDegradation() {
|
|
4235
|
+
if (this.degradations.length) throw new RequestLimitError(this.degradations);
|
|
4236
|
+
return this;
|
|
4237
|
+
}
|
|
4238
|
+
/**
|
|
4239
|
+
* Handlebars helpers over the whole request: `{{encode value}}` uses
|
|
4240
|
+
* `defaultName` (a tool's own schema in its instructions, the output in a
|
|
4241
|
+
* prompt), `{{encode value tool="search"}}` / `{{encode value output=true}}`
|
|
4242
|
+
* pick another schema of the request.
|
|
4243
|
+
*/
|
|
4244
|
+
helpers(defaultName) {
|
|
4245
|
+
return schemaHelpers(this, defaultName);
|
|
4246
|
+
}
|
|
4247
|
+
};
|
|
4248
|
+
function innerLenient(e) {
|
|
4249
|
+
return e.boundSchema.render(LENIENT);
|
|
4250
|
+
}
|
|
4251
|
+
function boundOf(s) {
|
|
4252
|
+
return "env" in s && "root" in s ? s : s.bind();
|
|
4253
|
+
}
|
|
4254
|
+
function minLimit(a, b) {
|
|
4255
|
+
return a === void 0 ? b : b === void 0 ? a : Math.min(a, b);
|
|
4256
|
+
}
|
|
4257
|
+
function mergeTotals(a, b) {
|
|
4258
|
+
if (!a) return b;
|
|
4259
|
+
if (!b) return a;
|
|
4260
|
+
const out = {};
|
|
4261
|
+
for (const k of /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])) out[k] = minLimit(a[k], b[k]);
|
|
4262
|
+
return out;
|
|
4263
|
+
}
|
|
4264
|
+
function requestLimitsOf(target) {
|
|
4265
|
+
const a = target.tool.request ?? {};
|
|
4266
|
+
const b = target.output.request ?? {};
|
|
4267
|
+
const out = {};
|
|
4268
|
+
const maxTools = minLimit(a.maxTools, b.maxTools);
|
|
4269
|
+
const maxStrictTools = minLimit(a.maxStrictTools, b.maxStrictTools);
|
|
4270
|
+
const totals = mergeTotals(a.totals, b.totals);
|
|
4271
|
+
if (maxTools !== void 0) out.maxTools = maxTools;
|
|
4272
|
+
if (maxStrictTools !== void 0) out.maxStrictTools = maxStrictTools;
|
|
4273
|
+
if (totals) out.totals = totals;
|
|
4274
|
+
return out;
|
|
4275
|
+
}
|
|
4276
|
+
var ENUM_CAPS = [250, 100, 40, 16, 8];
|
|
4277
|
+
var ENUM_LIMITS = /* @__PURE__ */ new Set(["maxEnumValues", "maxStringChars", "largeEnum"]);
|
|
4278
|
+
function climb(base, first, broken, wantNull, attempt) {
|
|
4279
|
+
const keep = base.rootObject ? { rootObject: true } : {};
|
|
4280
|
+
const m = first.rendered.measure;
|
|
4281
|
+
if (wantNull && m.optional > 0 && base.optional !== "null") {
|
|
4282
|
+
const t = attempt(variant(base, { ...keep, optionalAsNull: true }), { optionalAsNull: true });
|
|
4283
|
+
if (!t.problems.length) return t;
|
|
4284
|
+
}
|
|
4285
|
+
const biggest = Math.max(0, ...m.enums.map((e) => e.values));
|
|
4286
|
+
const caps = ENUM_CAPS.filter((cap) => biggest > cap && cap < (base.maxEnumValues ?? Infinity));
|
|
4287
|
+
const withCap = (cap, depth) => {
|
|
4288
|
+
const adj = { ...depth !== void 0 ? { maxDepth: depth } : {}, ...cap !== void 0 ? { maxEnumValues: cap } : {} };
|
|
4289
|
+
return attempt(variant(base, { ...keep, ...adj }), adj);
|
|
4290
|
+
};
|
|
4291
|
+
const leastCap = (depth, options, known) => {
|
|
4292
|
+
let lo2 = 0, hi2 = options.length - 1, best2 = known;
|
|
4293
|
+
while (lo2 < hi2) {
|
|
4294
|
+
const mid = lo2 + hi2 >> 1;
|
|
4295
|
+
const t = withCap(options[mid], depth);
|
|
4296
|
+
if (!t.problems.length) {
|
|
4297
|
+
best2 = t;
|
|
4298
|
+
hi2 = mid;
|
|
4299
|
+
} else lo2 = mid + 1;
|
|
4300
|
+
}
|
|
4301
|
+
return best2;
|
|
4302
|
+
};
|
|
4303
|
+
if (caps.length && [...broken].every((k) => ENUM_LIMITS.has(k))) {
|
|
4304
|
+
const last = withCap(caps[caps.length - 1]);
|
|
4305
|
+
if (!last.problems.length) return caps.length > 1 ? leastCap(void 0, caps, last) : last;
|
|
4306
|
+
}
|
|
4307
|
+
const top = Math.min(m.depth - 1, (base.maxDepth ?? Infinity) - 1);
|
|
4308
|
+
if (top < 1) return void 0;
|
|
4309
|
+
const lastCap = caps.length ? caps[caps.length - 1] : void 0;
|
|
4310
|
+
const shallow = withCap(lastCap, 1);
|
|
4311
|
+
if (shallow.problems.length) return void 0;
|
|
4312
|
+
let lo = 1, hi = top, best = shallow;
|
|
4313
|
+
while (lo < hi) {
|
|
4314
|
+
const mid = lo + hi + 1 >> 1;
|
|
4315
|
+
const t = withCap(lastCap, mid);
|
|
4316
|
+
if (!t.problems.length) {
|
|
4317
|
+
best = t;
|
|
4318
|
+
lo = mid;
|
|
4319
|
+
} else hi = mid - 1;
|
|
4320
|
+
}
|
|
4321
|
+
return caps.length ? leastCap(lo, [void 0, ...caps], best) : best;
|
|
4322
|
+
}
|
|
4323
|
+
function adjustmentsOf(adj) {
|
|
4324
|
+
const out = [];
|
|
4325
|
+
if (adj.optionalAsNull) out.push({ kind: "optional-as-null" });
|
|
4326
|
+
if (adj.maxEnumValues !== void 0) out.push({ kind: "enums-widened", maxEnumValues: adj.maxEnumValues });
|
|
4327
|
+
if (adj.maxDepth !== void 0) out.push({ kind: "depth-limited", maxDepth: adj.maxDepth });
|
|
4328
|
+
return out;
|
|
4329
|
+
}
|
|
4330
|
+
function dispatcherSchema(overflow) {
|
|
4331
|
+
const env = {};
|
|
4332
|
+
const checkLater = /* @__PURE__ */ new Set();
|
|
4333
|
+
const cases = overflow.map((t) => {
|
|
4334
|
+
let clash = false;
|
|
4335
|
+
for (const [k, s] of t.bound.env) if (k in env && env[k] !== s) clash = true;
|
|
4336
|
+
if (!clash) for (const [k, s] of t.bound.env) env[k] = s;
|
|
4337
|
+
else checkLater.add(t.name);
|
|
4338
|
+
const schema = clash ? new AnyType().describe(`Arguments: ${t.bound.render(LENIENT).typescript()}`) : t.bound.root;
|
|
4339
|
+
return { name: t.name, ...t.description ? { description: t.description } : {}, schema };
|
|
4340
|
+
});
|
|
4341
|
+
return { bound: new Bundle(env, new DispatchType(cases)).bind(), checkLater };
|
|
4342
|
+
}
|
|
4343
|
+
function planRequest(target, items, opts = {}) {
|
|
4344
|
+
const limits = requestLimitsOf(target);
|
|
4345
|
+
const totals = limits.totals;
|
|
4346
|
+
let used = ZERO_MEASURE;
|
|
4347
|
+
let strictTools = 0;
|
|
4348
|
+
const degradations = [];
|
|
4349
|
+
const taken = /* @__PURE__ */ new Set();
|
|
4350
|
+
const names = items.map((item) => {
|
|
4351
|
+
const want = item.kind === "output" ? item.name ?? "output" : item.name;
|
|
4352
|
+
let n = want;
|
|
4353
|
+
for (let k = 2; taken.has(n); k++) n = `${want}_${k}`;
|
|
4354
|
+
taken.add(n);
|
|
4355
|
+
if (n !== want) degradations.push(`"${want}" is named twice; the second is "${n}"`);
|
|
4356
|
+
return n;
|
|
4357
|
+
});
|
|
4358
|
+
const toolIdx = items.map((it, i) => it.kind === "tool" ? i : -1).filter((i) => i >= 0);
|
|
4359
|
+
const byPriority = [...toolIdx].sort((x, y) => strictPriority(items[y].strict ?? 1) - strictPriority(items[x].strict ?? 1) || x - y);
|
|
4360
|
+
const overflow = /* @__PURE__ */ new Set();
|
|
4361
|
+
if (limits.maxTools !== void 0 && toolIdx.length > limits.maxTools) {
|
|
4362
|
+
for (const i of byPriority.slice(Math.max(0, limits.maxTools - 1))) overflow.add(i);
|
|
4363
|
+
}
|
|
4364
|
+
let dispatcherName = opts.dispatcherName ?? "run_tool";
|
|
4365
|
+
for (let k = 2; taken.has(dispatcherName); k++) dispatcherName = `${opts.dispatcherName ?? "run_tool"}_${k}`;
|
|
4366
|
+
const work = [];
|
|
4367
|
+
items.forEach((item, i) => {
|
|
4368
|
+
if (overflow.has(i)) return;
|
|
4369
|
+
work.push({
|
|
4370
|
+
schema: item.schema,
|
|
4371
|
+
kind: item.kind,
|
|
4372
|
+
name: names[i],
|
|
4373
|
+
requestedName: item.kind === "output" ? item.name ?? "output" : item.name,
|
|
4374
|
+
strict: item.strict ?? 1,
|
|
4375
|
+
...item.kind === "output" && item.delivery ? { delivery: item.delivery } : {},
|
|
4376
|
+
slot: i
|
|
4377
|
+
});
|
|
4378
|
+
});
|
|
4379
|
+
let dispatchBound;
|
|
4380
|
+
let checkLater = /* @__PURE__ */ new Set();
|
|
4381
|
+
if (overflow.size) {
|
|
4382
|
+
const list = [...overflow].sort((x, y) => x - y);
|
|
4383
|
+
const d = dispatcherSchema(list.map((i) => {
|
|
4384
|
+
const it = items[i];
|
|
4385
|
+
return { name: names[i], ...it.description ? { description: it.description } : {}, bound: boundOf(it.schema) };
|
|
4386
|
+
}));
|
|
4387
|
+
dispatchBound = d.bound;
|
|
4388
|
+
checkLater = d.checkLater;
|
|
4389
|
+
const best = Math.max(...list.map((i) => strictPriority(items[i].strict ?? 1)));
|
|
4390
|
+
work.push({ schema: dispatchBound, kind: "tool", name: dispatcherName, requestedName: dispatcherName, strict: best === -Infinity ? false : best === Infinity ? 1 : best, slot: items.length });
|
|
4391
|
+
degradations.push(`${toolIdx.length} tools (limit ${limits.maxTools}): ${list.length} go through "${dispatcherName}"`);
|
|
4392
|
+
}
|
|
4393
|
+
const entries = new Array(items.length + (overflow.size ? 1 : 0));
|
|
4394
|
+
const order = work.map((w) => ({ w, p: strictPriority(w.strict) })).sort((x, y) => y.p - x.p || x.w.slot - y.w.slot);
|
|
4395
|
+
for (const { w, p } of order) {
|
|
4396
|
+
const { name } = w;
|
|
4397
|
+
const requested = w.strict;
|
|
4398
|
+
const bound = boundOf(w.schema);
|
|
4399
|
+
const offered = w.kind === "tool" ? target.tool : target.output;
|
|
4400
|
+
const base = w.kind === "tool" ? variant(offered, { rootObject: true }) : offered;
|
|
4401
|
+
const loose = (b) => b.strict ? variant(b.loose ?? LENIENT, { rootObject: b.rootObject }) : b;
|
|
4402
|
+
const reasons = [];
|
|
4403
|
+
const renamed = name !== w.requestedName ? [{ kind: "renamed", from: w.requestedName }] : [];
|
|
4404
|
+
const make = (profile, strict, delivery, adj) => {
|
|
4405
|
+
const rendered = bound.render(profile);
|
|
4406
|
+
if (delivery === "structured" && rendered.wrapped) adj.push({ kind: "root-wrapped" });
|
|
4407
|
+
return new RequestEntry(name, w.kind, requested, base, profile, strict, delivery, [...renamed, ...adj], reasons, rendered, w.requestedName, void 0, bound);
|
|
4408
|
+
};
|
|
4409
|
+
const promptAsked = w.kind === "output" && (w.delivery === "prompt" || target.outputDelivery === "prompt" && w.delivery !== "structured");
|
|
4410
|
+
if (promptAsked) {
|
|
4411
|
+
const why2 = w.delivery === "prompt" ? "asked for prompt text" : "the model has no structured output";
|
|
4412
|
+
if (w.delivery !== "prompt") degradations.push(`"${name}": sent as prompt text (${why2})`);
|
|
4413
|
+
entries[w.slot] = make(loose(base), false, "prompt", [{ kind: "prompt-text", reason: why2 }]);
|
|
4414
|
+
continue;
|
|
4415
|
+
}
|
|
4416
|
+
if (!base.strict || p <= 0) {
|
|
4417
|
+
const why2 = !base.strict ? "the model has no strict mode for this" : requested === false ? "strict: false" : "strict not requested";
|
|
4418
|
+
if (w.kind === "output" && base.strict && base.alwaysStrictOutput && w.delivery !== "structured") {
|
|
4419
|
+
entries[w.slot] = make(loose(base), false, "prompt", [{ kind: "prompt-text", reason: why2 }]);
|
|
4420
|
+
} else {
|
|
4421
|
+
entries[w.slot] = make(loose(base), false, "structured", base.strict ? [{ kind: "not-strict", reason: why2 }] : []);
|
|
4422
|
+
}
|
|
4423
|
+
continue;
|
|
4424
|
+
}
|
|
4425
|
+
const fits = (r, profile) => {
|
|
4426
|
+
const m = r.measure;
|
|
4427
|
+
const out = overLimits(m, profile.limits, `"${name}"`);
|
|
4428
|
+
out.push(...overLimits(m, totals, `"${name}" alone`));
|
|
4429
|
+
if (out.length) return out;
|
|
4430
|
+
if (w.kind === "tool" && limits.maxStrictTools !== void 0 && strictTools >= limits.maxStrictTools) {
|
|
4431
|
+
out.push(`"${name}": no strict tool slots left (limit ${limits.maxStrictTools})`);
|
|
4432
|
+
}
|
|
4433
|
+
out.push(...overLimits(addMeasures(used, m), totals, `"${name}" with the request so far`));
|
|
4434
|
+
return out;
|
|
4435
|
+
};
|
|
4436
|
+
let chosen;
|
|
4437
|
+
const attempt = (profile, adj) => {
|
|
4438
|
+
const rendered = bound.render(profile);
|
|
4439
|
+
return { profile, adj, rendered, problems: fits(rendered, profile) };
|
|
4440
|
+
};
|
|
4441
|
+
const first = attempt(base, {});
|
|
4442
|
+
const firstProblems = first.problems;
|
|
4443
|
+
if (!firstProblems.length) chosen = first;
|
|
4444
|
+
else if (!firstProblems.some((x) => x.includes("no strict tool slots left"))) {
|
|
4445
|
+
reasons.push(...firstProblems);
|
|
4446
|
+
const m = first.rendered.measure;
|
|
4447
|
+
const broken = brokenLimits(m, base.limits);
|
|
4448
|
+
brokenLimits(m, totals, broken);
|
|
4449
|
+
brokenLimits(addMeasures(used, m), totals, broken);
|
|
4450
|
+
const wantNull = !!totals?.maxOptional && used.optional + m.optional > totals.maxOptional;
|
|
4451
|
+
chosen = climb(base, first, broken, wantNull, attempt);
|
|
4452
|
+
} else reasons.push(...firstProblems);
|
|
4453
|
+
if (chosen) {
|
|
4454
|
+
used = addMeasures(used, chosen.rendered.measure);
|
|
4455
|
+
if (w.kind === "tool") strictTools++;
|
|
4456
|
+
const adj = adjustmentsOf(chosen.adj);
|
|
4457
|
+
if (adj.length) degradations.push(`"${name}": ${adj.map((x) => x.kind).join(", ")} (${reasons.join("; ")})`);
|
|
4458
|
+
entries[w.slot] = make(chosen.profile, true, "structured", adj);
|
|
4459
|
+
continue;
|
|
4460
|
+
}
|
|
4461
|
+
const why = reasons.join("; ");
|
|
4462
|
+
if (requested !== false) degradations.push(`"${name}": not strict (${why})`);
|
|
4463
|
+
if (w.kind === "output" && base.alwaysStrictOutput && w.delivery !== "structured") {
|
|
4464
|
+
entries[w.slot] = make(loose(base), false, "prompt", [{ kind: "prompt-text", reason: why }]);
|
|
4465
|
+
} else {
|
|
4466
|
+
entries[w.slot] = make(loose(base), false, "structured", [{ kind: "not-strict", reason: why }]);
|
|
4467
|
+
}
|
|
4468
|
+
}
|
|
4469
|
+
let dispatcher;
|
|
4470
|
+
if (overflow.size) {
|
|
4471
|
+
dispatcher = entries[items.length];
|
|
4472
|
+
for (const i of overflow) {
|
|
4473
|
+
const it = items[i];
|
|
4474
|
+
const bound = boundOf(it.schema);
|
|
4475
|
+
const reason = `${toolIdx.length} tools (limit ${limits.maxTools}); lower priority than the ${limits.maxTools - 1} sent directly`;
|
|
4476
|
+
const renamed = names[i] !== it.name ? [{ kind: "renamed", from: it.name }] : [];
|
|
4477
|
+
entries[i] = new RequestEntry(
|
|
4478
|
+
names[i],
|
|
4479
|
+
"tool",
|
|
4480
|
+
it.strict ?? 1,
|
|
4481
|
+
variant(target.tool, { rootObject: true }),
|
|
4482
|
+
dispatcher.profile,
|
|
4483
|
+
dispatcher.strict,
|
|
4484
|
+
"dispatched",
|
|
4485
|
+
[...renamed, { kind: "dispatched", via: dispatcher.name, reason }],
|
|
4486
|
+
[reason],
|
|
4487
|
+
bound.render(dispatcher.profile),
|
|
4488
|
+
it.name,
|
|
4489
|
+
dispatcher.name,
|
|
4490
|
+
bound
|
|
4491
|
+
);
|
|
4492
|
+
}
|
|
4493
|
+
}
|
|
4494
|
+
items.forEach((it, i) => entries[i].errorFormat = mergeErrorFormats(opts.errorFormat, it.errorFormat));
|
|
4495
|
+
if (dispatcher) dispatcher.errorFormat = mergeErrorFormats(opts.errorFormat);
|
|
4496
|
+
const req = new RenderedRequest(target, entries, used, strictTools, limits, degradations, dispatcher, checkLater);
|
|
4497
|
+
if (opts.failOnDegrade) req.assertNoDegradation();
|
|
4498
|
+
return req;
|
|
4499
|
+
}
|
|
4500
|
+
|
|
4501
|
+
// src/model.ts
|
|
4502
|
+
var PROVIDER_FAMILY = {
|
|
4503
|
+
openai: "openai",
|
|
4504
|
+
anthropic: "anthropic",
|
|
4505
|
+
google: "google",
|
|
4506
|
+
gemini: "google",
|
|
4507
|
+
xai: "xai",
|
|
4508
|
+
"x-ai": "xai",
|
|
4509
|
+
ollama: "ollama"
|
|
4510
|
+
};
|
|
4511
|
+
function familyOf(model) {
|
|
4512
|
+
if (model.strictFormat === "none") return model.provider === "ollama" ? "ollama" : "lenient";
|
|
4513
|
+
if (model.strictFormat) return PROVIDER_FAMILY[model.strictFormat] ?? model.strictFormat;
|
|
4514
|
+
const id = model.id.replace(/^~/, "");
|
|
4515
|
+
if (model.provider === "aws") {
|
|
4516
|
+
return /(^|\.)anthropic\.claude/.test(id) ? "anthropic" : "lenient";
|
|
4517
|
+
}
|
|
4518
|
+
const direct = PROVIDER_FAMILY[model.provider];
|
|
4519
|
+
if (direct) return direct;
|
|
4520
|
+
if (/^(openai\/gpt-oss|google\/gemma)/.test(id)) return "lenient";
|
|
4521
|
+
const slash = id.indexOf("/");
|
|
4522
|
+
return slash > 0 ? PROVIDER_FAMILY[id.slice(0, slash)] ?? "lenient" : "lenient";
|
|
4523
|
+
}
|
|
4524
|
+
function has(caps, cap) {
|
|
4525
|
+
if (!caps) return false;
|
|
4526
|
+
return Array.isArray(caps) ? caps.includes(cap) : caps.has(cap);
|
|
4527
|
+
}
|
|
4528
|
+
var ModelProfile = class _ModelProfile {
|
|
4529
|
+
constructor(tool, output = tool, outputDelivery = "structured") {
|
|
4530
|
+
this.tool = tool;
|
|
4531
|
+
this.output = output;
|
|
4532
|
+
this.outputDelivery = outputDelivery;
|
|
4533
|
+
}
|
|
4534
|
+
tool;
|
|
4535
|
+
output;
|
|
4536
|
+
outputDelivery;
|
|
4537
|
+
/**
|
|
4538
|
+
* Render every schema of one request together, so the request as a whole
|
|
4539
|
+
* fits this model's limits (see `planRequest`). Each entry records what
|
|
4540
|
+
* its schema was rendered with; parse and encode through the entry.
|
|
4541
|
+
*/
|
|
4542
|
+
request(items, opts) {
|
|
4543
|
+
return planRequest(this, items, opts);
|
|
4544
|
+
}
|
|
4545
|
+
/** Both kinds through one profile. */
|
|
4546
|
+
static of(profile) {
|
|
4547
|
+
return new _ModelProfile(profile, profile);
|
|
4548
|
+
}
|
|
4549
|
+
};
|
|
4550
|
+
function profileFor(model, opts = {}) {
|
|
4551
|
+
let family = familyOf(model);
|
|
4552
|
+
if (opts.speaks && !opts.speaks.has(family)) family = "lenient";
|
|
4553
|
+
const toolsStrict = family === "xai" || has(model.capabilities, "toolsStrict");
|
|
4554
|
+
const structured = has(model.capabilities, "structured");
|
|
4555
|
+
const finetuned = family === "openai" && /(^|\/)ft:/.test(model.id);
|
|
4556
|
+
const pick = (strict) => finetuned && strict ? OPENAI_FINETUNED_STRICT : familyProfile(family, strict);
|
|
4557
|
+
const tool = pick(toolsStrict);
|
|
4558
|
+
const output = pick(structured);
|
|
4559
|
+
const delivery = !structured && (model.provider === "aws" || output.alwaysStrictOutput || familyProfile(family, true).alwaysStrictOutput || !has(model.capabilities, "json")) ? "prompt" : "structured";
|
|
4560
|
+
return new ModelProfile(tool, output, delivery);
|
|
4561
|
+
}
|
|
4562
|
+
|
|
4563
|
+
// src/gin/from-gin.ts
|
|
4564
|
+
var GIN_BUILTINS = /* @__PURE__ */ new Set([
|
|
4565
|
+
"text",
|
|
4566
|
+
"num",
|
|
4567
|
+
"bool",
|
|
4568
|
+
"null",
|
|
4569
|
+
"void",
|
|
4570
|
+
"any",
|
|
4571
|
+
"date",
|
|
4572
|
+
"timestamp",
|
|
4573
|
+
"duration",
|
|
4574
|
+
"color",
|
|
4575
|
+
"list",
|
|
4576
|
+
"map",
|
|
4577
|
+
"optional",
|
|
4578
|
+
"nullable",
|
|
4579
|
+
"obj",
|
|
4580
|
+
"enum",
|
|
4581
|
+
"literal",
|
|
4582
|
+
"or",
|
|
4583
|
+
"tuple",
|
|
4584
|
+
"typ",
|
|
4585
|
+
"fn",
|
|
4586
|
+
"and",
|
|
4587
|
+
"not",
|
|
4588
|
+
"iface",
|
|
4589
|
+
"interface",
|
|
4590
|
+
"record"
|
|
4591
|
+
]);
|
|
4592
|
+
var GIN_DATE = "^\\d{4}-\\d{2}-\\d{2}";
|
|
4593
|
+
var GIN_TIMESTAMP = "^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$";
|
|
4594
|
+
function fromGin(def, opts = {}) {
|
|
4595
|
+
let s = def.extends ? convertDefinition(def, opts) : convert(def, opts);
|
|
4596
|
+
const parts = [def.docs, def.constraint !== void 0 ? `Each value must satisfy this gin constraint: ${JSON.stringify(def.constraint)}` : void 0].filter(Boolean);
|
|
4597
|
+
if (parts.length) s = s.describe(parts.join("\n"));
|
|
4598
|
+
return s;
|
|
4599
|
+
}
|
|
4600
|
+
var stored = (p) => !p.get && p.type.name !== "fn";
|
|
4601
|
+
function propsShape(props, opts) {
|
|
4602
|
+
const shape = {};
|
|
4603
|
+
for (const [k, p] of Object.entries(props ?? {})) {
|
|
4604
|
+
if (!stored(p)) continue;
|
|
4605
|
+
let s = fromGin(p.type, opts);
|
|
4606
|
+
if (p.docs) s = s.describe(p.docs);
|
|
4607
|
+
shape[k] = s;
|
|
4608
|
+
}
|
|
4609
|
+
return shape;
|
|
4610
|
+
}
|
|
4611
|
+
function convertDefinition(def, opts) {
|
|
4612
|
+
const { name: _n, extends: base, props, docs: _d, constraint: _c, ...rest } = def;
|
|
4613
|
+
const local = propsShape(props, opts);
|
|
4614
|
+
if (base === "obj" || base === "interface" || base === "iface") return new ObjectType(local);
|
|
4615
|
+
const b = convert({ ...rest, name: base }, opts);
|
|
4616
|
+
if (!Object.keys(local).length) return b;
|
|
4617
|
+
return new IntersectionType([b, new ObjectType(local)]);
|
|
4618
|
+
}
|
|
4619
|
+
function substitute(def, args) {
|
|
4620
|
+
if (!def.generic && !def.props && !def.options && def.name in args) return args[def.name];
|
|
4621
|
+
const sub = (d) => substitute(d, args);
|
|
4622
|
+
return {
|
|
4623
|
+
...def,
|
|
4624
|
+
...def.generic ? { generic: Object.fromEntries(Object.entries(def.generic).map(([k, v]) => [k, sub(v)])) } : {},
|
|
4625
|
+
...def.props ? { props: Object.fromEntries(Object.entries(def.props).map(([k, p]) => [k, { ...p, type: sub(p.type) }])) } : {},
|
|
4626
|
+
...def.options && Array.isArray(def.options.types) ? { options: { ...def.options, types: def.options.types.map(sub) } } : {}
|
|
4627
|
+
};
|
|
4628
|
+
}
|
|
4629
|
+
function convert(def, opts) {
|
|
4630
|
+
const o = def.options ?? {};
|
|
4631
|
+
const g = def.generic ?? {};
|
|
4632
|
+
const sub = (d) => fromGin(d, opts);
|
|
4633
|
+
switch (def.name) {
|
|
4634
|
+
case "text": {
|
|
4635
|
+
let s = new StringType();
|
|
4636
|
+
if (typeof o.minLength === "number") s = s.min(o.minLength);
|
|
4637
|
+
if (typeof o.maxLength === "number") s = s.max(o.maxLength);
|
|
4638
|
+
if (typeof o.pattern === "string") s = s.pattern(o.pattern, typeof o.flags === "string" ? o.flags : void 0);
|
|
4639
|
+
return s;
|
|
4640
|
+
}
|
|
4641
|
+
case "num": {
|
|
4642
|
+
let s = new NumberType({ int: !!o.whole });
|
|
4643
|
+
if (typeof o.min === "number") s = s.min(o.min);
|
|
4644
|
+
if (typeof o.max === "number") s = s.max(o.max);
|
|
4645
|
+
return s;
|
|
4646
|
+
}
|
|
4647
|
+
case "bool":
|
|
4648
|
+
return new BooleanType();
|
|
4649
|
+
case "null":
|
|
4650
|
+
case "void":
|
|
4651
|
+
return new NullType();
|
|
4652
|
+
case "any":
|
|
4653
|
+
return new AnyType();
|
|
4654
|
+
case "date":
|
|
4655
|
+
return new StringType().pattern(GIN_DATE).describe("An ISO 8601 date (YYYY-MM-DD).");
|
|
4656
|
+
case "timestamp":
|
|
4657
|
+
return new StringType().pattern(GIN_TIMESTAMP).describe("An ISO 8601 timestamp (YYYY-MM-DD HH:MM[:SS][Z]).");
|
|
4658
|
+
case "duration":
|
|
4659
|
+
return new NumberType().describe("A duration in milliseconds.");
|
|
4660
|
+
case "color":
|
|
4661
|
+
return new NumberType({ int: true }).min(0).max(4294967295).describe(o.hasAlpha ? "A color as a 32-bit integer 0xRRGGBBAA." : "A color as an integer 0xRRGGBB.");
|
|
4662
|
+
case "list": {
|
|
4663
|
+
let s = new ArrayType(g.V ? sub(g.V) : new AnyType());
|
|
4664
|
+
if (typeof o.minLength === "number") s = s.min(o.minLength);
|
|
4665
|
+
if (typeof o.maxLength === "number") s = s.max(o.maxLength);
|
|
4666
|
+
return s;
|
|
4667
|
+
}
|
|
4668
|
+
case "map": {
|
|
4669
|
+
const V = g.V ? sub(g.V) : new AnyType();
|
|
4670
|
+
if (!g.K || g.K.name === "text") return new RecordType(V);
|
|
4671
|
+
return new ArrayType(new ObjectType({ key: sub(g.K), value: V }));
|
|
4672
|
+
}
|
|
4673
|
+
// The harness's gin `record<V>` (sdk gin-record.ts): string keys.
|
|
4674
|
+
case "record":
|
|
4675
|
+
return new RecordType(g.V ? sub(g.V) : new AnyType());
|
|
4676
|
+
case "optional":
|
|
4677
|
+
return new OptionalType(g.T ? sub(g.T) : new AnyType());
|
|
4678
|
+
case "nullable":
|
|
4679
|
+
return new NullableType(g.T ? sub(g.T) : new AnyType());
|
|
4680
|
+
case "obj":
|
|
4681
|
+
return new ObjectType(propsShape(def.props, opts));
|
|
4682
|
+
case "enum": {
|
|
4683
|
+
const values = Object.values(o.values ?? {});
|
|
4684
|
+
if (values.length && values.every((v) => typeof v === "string")) return new EnumType(values);
|
|
4685
|
+
return new UnionType(values.map((v) => new LiteralType(v)));
|
|
4686
|
+
}
|
|
4687
|
+
case "literal":
|
|
4688
|
+
return new LiteralType(o.value);
|
|
4689
|
+
case "or":
|
|
4690
|
+
return new UnionType((o.types ?? []).map(sub));
|
|
4691
|
+
// gin types/tuple.ts serializes `options.elements` (older defs: `types`).
|
|
4692
|
+
case "tuple":
|
|
4693
|
+
return new TupleType((o.elements ?? o.types ?? []).map(sub));
|
|
4694
|
+
// A value that IS a gin type / program: a ref into the grammar module (see corpus/gin-grammar.ts).
|
|
4695
|
+
case "typ":
|
|
4696
|
+
return new RefType("TypeDef");
|
|
4697
|
+
case "fn":
|
|
4698
|
+
return new RefType("Expr");
|
|
4699
|
+
// An intersection: objects merge into one object (every dialect can say
|
|
4700
|
+
// that), anything else is validated after the first part.
|
|
4701
|
+
case "and": {
|
|
4702
|
+
const parts = (o.types ?? []).map(sub);
|
|
4703
|
+
return parts.length === 0 ? new AnyType() : parts.length === 1 ? parts[0] : new IntersectionType(parts);
|
|
4704
|
+
}
|
|
4705
|
+
// Any value except the excluded type: said in words, checked on decode.
|
|
4706
|
+
case "not":
|
|
4707
|
+
return new NotType(o.excluded ? sub(o.excluded) : new AnyType(), new AnyType());
|
|
4708
|
+
// A structural contract: an object with at least these props (wider values still satisfy it, as in gin).
|
|
4709
|
+
case "interface":
|
|
4710
|
+
case "iface":
|
|
4711
|
+
return new ObjectType(propsShape(def.props, opts));
|
|
4712
|
+
default: {
|
|
4713
|
+
const template = opts.named?.get(def.name);
|
|
4714
|
+
if (template && def.generic && Object.keys(def.generic).length) {
|
|
4715
|
+
return fromGin(substitute(template.extends ? { ...template, name: def.name } : template, def.generic), opts);
|
|
4716
|
+
}
|
|
4717
|
+
return new RefType(def.name);
|
|
4718
|
+
}
|
|
4719
|
+
}
|
|
4720
|
+
}
|
|
4721
|
+
function ginNamedTypes(registry) {
|
|
4722
|
+
const named = registry.named();
|
|
4723
|
+
const out = {};
|
|
4724
|
+
for (const [name, def] of named) {
|
|
4725
|
+
const body = def.generic && !def.extends ? substitute({ ...def, generic: void 0 }, def.generic) : def;
|
|
4726
|
+
const { generic: _g, ...plain } = body;
|
|
4727
|
+
out[name] = fromGin(def.generic && !def.extends ? plain : body, { named });
|
|
4728
|
+
}
|
|
4729
|
+
return out;
|
|
4730
|
+
}
|
|
4731
|
+
export {
|
|
4732
|
+
ANTHROPIC_NON_STRICT,
|
|
4733
|
+
ANTHROPIC_STRICT,
|
|
4734
|
+
AnyType,
|
|
4735
|
+
ArrayType,
|
|
4736
|
+
BooleanType,
|
|
4737
|
+
Bound,
|
|
4738
|
+
Bundle,
|
|
4739
|
+
CodecType,
|
|
4740
|
+
Compiler,
|
|
4741
|
+
ConditionalType,
|
|
4742
|
+
Cx,
|
|
4743
|
+
DEFAULT_ERROR_FORMAT,
|
|
4744
|
+
DEFAULT_JSON_INSTRUCTION,
|
|
4745
|
+
DefTarget,
|
|
4746
|
+
DefaultType,
|
|
4747
|
+
DependentType,
|
|
4748
|
+
DispatchType,
|
|
4749
|
+
DynamicModule,
|
|
4750
|
+
EnumType,
|
|
4751
|
+
FAILED,
|
|
4752
|
+
GIN_BUILTINS,
|
|
4753
|
+
GOOGLE_NON_STRICT,
|
|
4754
|
+
GOOGLE_OPENAPI,
|
|
4755
|
+
GOOGLE_STRICT,
|
|
4756
|
+
INLINE_BUDGET,
|
|
4757
|
+
InlineBudgetExceeded,
|
|
4758
|
+
IntersectionType,
|
|
4759
|
+
LENIENT,
|
|
4760
|
+
LiteralType,
|
|
4761
|
+
MINIMAL,
|
|
4762
|
+
ModelProfile,
|
|
4763
|
+
Module,
|
|
4764
|
+
NeverType,
|
|
4765
|
+
Node,
|
|
4766
|
+
NotType,
|
|
4767
|
+
NullType,
|
|
4768
|
+
NullableType,
|
|
4769
|
+
NumberType,
|
|
4770
|
+
OLLAMA,
|
|
4771
|
+
OPENAI_FINETUNED_STRICT,
|
|
4772
|
+
OPENAI_NON_STRICT,
|
|
4773
|
+
OPENAI_STRICT,
|
|
4774
|
+
ObjectType,
|
|
4775
|
+
OptionalType,
|
|
4776
|
+
PEOPLE,
|
|
4777
|
+
Printer,
|
|
4778
|
+
RecordType,
|
|
4779
|
+
RefType,
|
|
4780
|
+
Rejection,
|
|
4781
|
+
Rendered,
|
|
4782
|
+
RenderedRequest,
|
|
4783
|
+
RequestEntry,
|
|
4784
|
+
RequestLimitError,
|
|
4785
|
+
SCHEMA_DATA_KEY,
|
|
4786
|
+
Schema,
|
|
4787
|
+
SchemaDefinitionError,
|
|
4788
|
+
SchemaParseError,
|
|
4789
|
+
StringType,
|
|
4790
|
+
TupleType,
|
|
4791
|
+
UnionType,
|
|
4792
|
+
XAI_NON_STRICT,
|
|
4793
|
+
XAI_STRICT,
|
|
4794
|
+
ZERO_MEASURE,
|
|
4795
|
+
a_exports as a,
|
|
4796
|
+
addMeasures,
|
|
4797
|
+
brokenLimits,
|
|
4798
|
+
didYouMean,
|
|
4799
|
+
editDistance,
|
|
4800
|
+
errorFormat,
|
|
4801
|
+
familyOf,
|
|
4802
|
+
familyProfile,
|
|
4803
|
+
formatErrors,
|
|
4804
|
+
formatIssues,
|
|
4805
|
+
formatPath,
|
|
4806
|
+
fromGin,
|
|
4807
|
+
fromJSONSchema,
|
|
4808
|
+
getProfile,
|
|
4809
|
+
ginNamedTypes,
|
|
4810
|
+
isBasicPattern,
|
|
4811
|
+
isNever,
|
|
4812
|
+
issueKind,
|
|
4813
|
+
measureJson,
|
|
4814
|
+
mergeErrorFormats,
|
|
4815
|
+
modelPath,
|
|
4816
|
+
nearest,
|
|
4817
|
+
newStats,
|
|
4818
|
+
overLimits,
|
|
4819
|
+
planRequest,
|
|
4820
|
+
profileFor,
|
|
4821
|
+
rankNear,
|
|
4822
|
+
readJsonText,
|
|
4823
|
+
registerProfile,
|
|
4824
|
+
registerSchemaHelpers,
|
|
4825
|
+
schemaData,
|
|
4826
|
+
schemaHelpers,
|
|
4827
|
+
shortType,
|
|
4828
|
+
staticBundle,
|
|
4829
|
+
strictPriority,
|
|
4830
|
+
suggestionBudget,
|
|
4831
|
+
suggestionFor,
|
|
4832
|
+
variant,
|
|
4833
|
+
viewOf
|
|
4834
|
+
};
|