@orkestrel/contract 0.0.21 → 0.0.22
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/dist/src/core/index.cjs +2135 -423
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +766 -48
- package/dist/src/core/index.d.ts +766 -48
- package/dist/src/core/index.js +2108 -424
- package/dist/src/core/index.js.map +1 -1
- package/package.json +9 -9
package/dist/src/core/index.js
CHANGED
|
@@ -1,5 +1,51 @@
|
|
|
1
1
|
// src/core/constants.ts
|
|
2
2
|
/**
|
|
3
|
+
* Lists the fields recognized for every contract declaration category, frozen.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```ts
|
|
7
|
+
* SHAPE_FIELDS.shape // ['description']
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
var SHAPE_FIELDS = Object.freeze({
|
|
11
|
+
string: Object.freeze([
|
|
12
|
+
"min",
|
|
13
|
+
"max",
|
|
14
|
+
"pattern",
|
|
15
|
+
"description"
|
|
16
|
+
]),
|
|
17
|
+
number: Object.freeze([
|
|
18
|
+
"integer",
|
|
19
|
+
"min",
|
|
20
|
+
"max",
|
|
21
|
+
"description"
|
|
22
|
+
]),
|
|
23
|
+
boolean: Object.freeze(["description"]),
|
|
24
|
+
null: Object.freeze(["description"]),
|
|
25
|
+
literal: Object.freeze(["values", "description"]),
|
|
26
|
+
array: Object.freeze([
|
|
27
|
+
"items",
|
|
28
|
+
"min",
|
|
29
|
+
"max",
|
|
30
|
+
"description"
|
|
31
|
+
]),
|
|
32
|
+
object: Object.freeze([
|
|
33
|
+
"properties",
|
|
34
|
+
"additionalProperties",
|
|
35
|
+
"description"
|
|
36
|
+
]),
|
|
37
|
+
union: Object.freeze([
|
|
38
|
+
"variants",
|
|
39
|
+
"mode",
|
|
40
|
+
"description"
|
|
41
|
+
]),
|
|
42
|
+
optional: Object.freeze(["inner", "default"]),
|
|
43
|
+
nullable: Object.freeze(["inner"]),
|
|
44
|
+
json: Object.freeze(["description"]),
|
|
45
|
+
raw: Object.freeze(["schema"]),
|
|
46
|
+
shape: Object.freeze(["description"])
|
|
47
|
+
});
|
|
48
|
+
/**
|
|
3
49
|
* Holds the registry-global key used to recognize {@link ContractError} values
|
|
4
50
|
* across package copies.
|
|
5
51
|
*
|
|
@@ -295,6 +341,48 @@ var JSON_SCHEMA_TYPES = Object.freeze([
|
|
|
295
341
|
"string"
|
|
296
342
|
]);
|
|
297
343
|
/**
|
|
344
|
+
* Lists the JSON Schema keywords a strict `schemaToShape` conversion reads, frozen.
|
|
345
|
+
*
|
|
346
|
+
* @remarks
|
|
347
|
+
* The keywords a shape can honour, plus the annotations that assert nothing and so
|
|
348
|
+
* lose nothing when a shape drops them: `title`, `$schema`, `$id`, `$comment`,
|
|
349
|
+
* `examples`, `deprecated`, `readOnly`, and `writeOnly`. Every other keyword refuses.
|
|
350
|
+
* `pattern` and `format` are absent because no compiled shape asserts them, so a
|
|
351
|
+
* schema holding one would convert to a shape wider than the schema it came from.
|
|
352
|
+
*
|
|
353
|
+
* @example
|
|
354
|
+
* ```ts
|
|
355
|
+
* STRICT_SCHEMA_KEYWORDS.includes('title') // true
|
|
356
|
+
* STRICT_SCHEMA_KEYWORDS.includes('pattern') // false
|
|
357
|
+
* ```
|
|
358
|
+
*/
|
|
359
|
+
var STRICT_SCHEMA_KEYWORDS = Object.freeze([
|
|
360
|
+
"type",
|
|
361
|
+
"title",
|
|
362
|
+
"description",
|
|
363
|
+
"$schema",
|
|
364
|
+
"$id",
|
|
365
|
+
"$comment",
|
|
366
|
+
"examples",
|
|
367
|
+
"deprecated",
|
|
368
|
+
"readOnly",
|
|
369
|
+
"writeOnly",
|
|
370
|
+
"default",
|
|
371
|
+
"enum",
|
|
372
|
+
"minLength",
|
|
373
|
+
"maxLength",
|
|
374
|
+
"minimum",
|
|
375
|
+
"maximum",
|
|
376
|
+
"minItems",
|
|
377
|
+
"maxItems",
|
|
378
|
+
"items",
|
|
379
|
+
"properties",
|
|
380
|
+
"required",
|
|
381
|
+
"additionalProperties",
|
|
382
|
+
"anyOf",
|
|
383
|
+
"oneOf"
|
|
384
|
+
]);
|
|
385
|
+
/**
|
|
298
386
|
* Lists every declared {@link ContractCode} refusal category, frozen.
|
|
299
387
|
*
|
|
300
388
|
* @remarks
|
|
@@ -328,6 +416,47 @@ var CONTRACT_CODES = Object.freeze([
|
|
|
328
416
|
"expansion"
|
|
329
417
|
]);
|
|
330
418
|
/**
|
|
419
|
+
* Lists every {@link FaultKind}, frozen.
|
|
420
|
+
*
|
|
421
|
+
* @remarks
|
|
422
|
+
* The runtime source of truth for the vocabulary, which {@link isFault} reads.
|
|
423
|
+
*
|
|
424
|
+
* @example
|
|
425
|
+
* ```ts
|
|
426
|
+
* FAULT_KINDS.includes('string') // true
|
|
427
|
+
* ```
|
|
428
|
+
*/
|
|
429
|
+
var FAULT_KINDS = Object.freeze([
|
|
430
|
+
"string",
|
|
431
|
+
"number",
|
|
432
|
+
"integer",
|
|
433
|
+
"boolean",
|
|
434
|
+
"null",
|
|
435
|
+
"literal",
|
|
436
|
+
"array",
|
|
437
|
+
"object",
|
|
438
|
+
"union",
|
|
439
|
+
"json",
|
|
440
|
+
"shape"
|
|
441
|
+
]);
|
|
442
|
+
/**
|
|
443
|
+
* Lists every {@link FaultConstraint}, frozen.
|
|
444
|
+
*
|
|
445
|
+
* @remarks
|
|
446
|
+
* The runtime source of truth for the vocabulary, which {@link isFault} reads.
|
|
447
|
+
*
|
|
448
|
+
* @example
|
|
449
|
+
* ```ts
|
|
450
|
+
* FAULT_CONSTRAINTS.includes('min') // true
|
|
451
|
+
* ```
|
|
452
|
+
*/
|
|
453
|
+
var FAULT_CONSTRAINTS = Object.freeze([
|
|
454
|
+
"min",
|
|
455
|
+
"max",
|
|
456
|
+
"pattern",
|
|
457
|
+
"integer"
|
|
458
|
+
]);
|
|
459
|
+
/**
|
|
331
460
|
* Caps at `64` the number of {@link Fault} / {@link AuditFault} entries a single
|
|
332
461
|
* `explain` or `audit` report ever returns, frozen.
|
|
333
462
|
*
|
|
@@ -612,6 +741,12 @@ var TEXT_LIMIT = 1048576;
|
|
|
612
741
|
* ```
|
|
613
742
|
*/
|
|
614
743
|
var NODE_LIMIT = 16384;
|
|
744
|
+
/** Caps a fault message at 2048 UTF-16 code units. */
|
|
745
|
+
var FAULT_TEXT_LIMIT = 2048;
|
|
746
|
+
/** Caps the keys or literal candidates named in a fault line. */
|
|
747
|
+
var FAULT_LIST_LIMIT = 12;
|
|
748
|
+
/** Caps a schema summary's UTF-16 code units. */
|
|
749
|
+
var FAULT_SCHEMA_LIMIT = 160;
|
|
615
750
|
// src/core/errors.ts
|
|
616
751
|
/**
|
|
617
752
|
* Carries a machine-readable contract category, optional context, and an exact optional
|
|
@@ -1262,6 +1397,103 @@ function isObject(value) {
|
|
|
1262
1397
|
function isRecord(value) {
|
|
1263
1398
|
return holds(() => matchesRecordBrand(value));
|
|
1264
1399
|
}
|
|
1400
|
+
/**
|
|
1401
|
+
* Determines whether a value is the {@link FieldPath} a fault carries: a key, or a dense list of keys.
|
|
1402
|
+
*
|
|
1403
|
+
* @param value - The value to inspect
|
|
1404
|
+
* @returns True if the value is a string or a dense array of strings; false otherwise
|
|
1405
|
+
*
|
|
1406
|
+
* @example
|
|
1407
|
+
* ```ts
|
|
1408
|
+
* isFaultPath(['user', 'name']) // true
|
|
1409
|
+
* isFaultPath([1]) // false
|
|
1410
|
+
* ```
|
|
1411
|
+
*/
|
|
1412
|
+
function isFaultPath(value) {
|
|
1413
|
+
if (isString(value)) return true;
|
|
1414
|
+
return holds(() => {
|
|
1415
|
+
if (!isArray(value)) return false;
|
|
1416
|
+
const snapshot = readArrayEntries(value);
|
|
1417
|
+
if (isFailure(snapshot) || !snapshot.value.dense) return false;
|
|
1418
|
+
return !INTRINSICS.reflect.apply(INTRINSICS.some, snapshot.value.entries, [(entry) => !isString(entry)]);
|
|
1419
|
+
});
|
|
1420
|
+
}
|
|
1421
|
+
/**
|
|
1422
|
+
* Determines whether a value is exactly one {@link Fault}.
|
|
1423
|
+
*
|
|
1424
|
+
* @remarks
|
|
1425
|
+
* A closed reading of the union: each reason's required fields, each with its own
|
|
1426
|
+
* vocabulary, and no other key, so `{}` and a fault carrying a stray field both answer
|
|
1427
|
+
* `false`. An undeclared-key fault is an {@link AuditFault} and answers `false` here.
|
|
1428
|
+
*
|
|
1429
|
+
* @param value - The value to inspect
|
|
1430
|
+
* @returns True if the value is a well-formed fault; false otherwise
|
|
1431
|
+
*
|
|
1432
|
+
* @example
|
|
1433
|
+
* ```ts
|
|
1434
|
+
* isFault({ reason: 'missing', path: ['a'], expected: 'string' }) // true
|
|
1435
|
+
* isFault({}) // false
|
|
1436
|
+
* ```
|
|
1437
|
+
*/
|
|
1438
|
+
function isFault(value) {
|
|
1439
|
+
return holds(() => {
|
|
1440
|
+
if (!isRecord(value) || !isFaultPath(value.path)) return false;
|
|
1441
|
+
const kind = INTRINSICS.reflect.apply(INTRINSICS.some, FAULT_KINDS, [(entry) => entry === value.expected]);
|
|
1442
|
+
const named = INTRINSICS.own(value, "key") || INTRINSICS.own(value, "expected");
|
|
1443
|
+
const list = readArrayEntries(isArray(value.expected) ? value.expected : [void 0]);
|
|
1444
|
+
const hinted = !named || isString(value.key) && !isFailure(list) && list.value.dense && !INTRINSICS.reflect.apply(INTRINSICS.some, list.value.entries, [(entry) => !isLiteralValue(entry) || isNumber(entry) && !isFiniteNumber(entry)]);
|
|
1445
|
+
switch (value.reason) {
|
|
1446
|
+
case "type": return kind && isString(value.received) && matchesExactKeys(value, [
|
|
1447
|
+
"reason",
|
|
1448
|
+
"path",
|
|
1449
|
+
"expected",
|
|
1450
|
+
"received"
|
|
1451
|
+
]);
|
|
1452
|
+
case "missing": return kind && matchesExactKeys(value, [
|
|
1453
|
+
"reason",
|
|
1454
|
+
"path",
|
|
1455
|
+
"expected"
|
|
1456
|
+
]);
|
|
1457
|
+
case "constraint": return kind && isString(value.received) && INTRINSICS.reflect.apply(INTRINSICS.some, FAULT_CONSTRAINTS, [(entry) => entry === value.constraint]) && (!INTRINSICS.own(value, "limit") || isFiniteNumber(value.limit) || isString(value.limit)) && matchesExactKeys(value, [
|
|
1458
|
+
"reason",
|
|
1459
|
+
"path",
|
|
1460
|
+
"expected",
|
|
1461
|
+
"constraint",
|
|
1462
|
+
"received"
|
|
1463
|
+
], ["limit"]);
|
|
1464
|
+
case "variant": return isNonNegativeInteger(value.variants) && hinted && matchesExactKeys(value, [
|
|
1465
|
+
"reason",
|
|
1466
|
+
"path",
|
|
1467
|
+
"variants"
|
|
1468
|
+
], named ? ["key", "expected"] : []);
|
|
1469
|
+
case "oneOf": return isNonNegativeInteger(value.matched) && hinted && matchesExactKeys(value, [
|
|
1470
|
+
"reason",
|
|
1471
|
+
"path",
|
|
1472
|
+
"matched"
|
|
1473
|
+
], named ? ["key", "expected"] : []);
|
|
1474
|
+
default: return false;
|
|
1475
|
+
}
|
|
1476
|
+
});
|
|
1477
|
+
}
|
|
1478
|
+
/**
|
|
1479
|
+
* Determines whether a value is exactly one {@link AuditFault}.
|
|
1480
|
+
*
|
|
1481
|
+
* @remarks
|
|
1482
|
+
* Every {@link Fault}, and the undeclared-key fault an audit adds.
|
|
1483
|
+
*
|
|
1484
|
+
* @param value - The value to inspect
|
|
1485
|
+
* @returns True if the value is a well-formed audit fault; false otherwise
|
|
1486
|
+
*
|
|
1487
|
+
* @example
|
|
1488
|
+
* ```ts
|
|
1489
|
+
* isAuditFault({ reason: 'extra', path: ['a'] }) // true
|
|
1490
|
+
* isAuditFault({}) // false
|
|
1491
|
+
* ```
|
|
1492
|
+
*/
|
|
1493
|
+
function isAuditFault(value) {
|
|
1494
|
+
if (isFault(value)) return true;
|
|
1495
|
+
return holds(() => isRecord(value) && value.reason === "extra" && isFaultPath(value.path) && matchesExactKeys(value, ["reason", "path"]));
|
|
1496
|
+
}
|
|
1265
1497
|
/** Determines whether a value is a `Map`.
|
|
1266
1498
|
*
|
|
1267
1499
|
* @param value - The value to inspect
|
|
@@ -1905,6 +2137,126 @@ function isJSONPrimitive(value) {
|
|
|
1905
2137
|
}
|
|
1906
2138
|
// src/core/helpers.ts
|
|
1907
2139
|
/**
|
|
2140
|
+
* Admits a stable readable value with only lossless repairs and returns the parser's value.
|
|
2141
|
+
*
|
|
2142
|
+
* @remarks
|
|
2143
|
+
* Reads must remain stable across artifacts. Guard-valid input skips both reports and parses
|
|
2144
|
+
* once. Repairs use audit, parse once, and explain only on parse failure. Unresolved unions,
|
|
2145
|
+
* extras, lossy repairs, and a capped audit refuse. An own optional undefined field omitted or
|
|
2146
|
+
* filled by its declared default is not a repair. The result preserves parser ownership, including union input identity.
|
|
2147
|
+
* A read failure returns its cause rather than throwing.
|
|
2148
|
+
* Snapshot a foreign object before admission, as Tool.execute does. A getter changing between
|
|
2149
|
+
* is and parse can publish a value that no recorded repair describes. A shallow snapshot only
|
|
2150
|
+
* stabilizes its own level; nested foreign values must also provide stable reads.
|
|
2151
|
+
*
|
|
2152
|
+
* @example
|
|
2153
|
+
* ```ts
|
|
2154
|
+
* admitValue(createContract(numberShape()), '3') // success carrying 3 and its type repair
|
|
2155
|
+
* ```
|
|
2156
|
+
*/
|
|
2157
|
+
function admitValue(contract, value) {
|
|
2158
|
+
try {
|
|
2159
|
+
if (contract.is(value)) {
|
|
2160
|
+
const parsed = contract.parse(value);
|
|
2161
|
+
if (parsed === void 0 && value !== void 0) return failure({ faults: [] });
|
|
2162
|
+
return success({
|
|
2163
|
+
value: parsed === void 0 ? value : parsed,
|
|
2164
|
+
repairs: []
|
|
2165
|
+
});
|
|
2166
|
+
}
|
|
2167
|
+
const audited = contract.audit(value);
|
|
2168
|
+
const parsed = contract.parse(value);
|
|
2169
|
+
const explained = parsed === void 0 ? contract.explain(value) : [];
|
|
2170
|
+
const repairs = audited.filter((fault) => matchesLosslessRepair(fault, value, parsed));
|
|
2171
|
+
const refused = audited.filter((fault) => !repairs.includes(fault) && !matchesUndefinedField(fault, value, parsed));
|
|
2172
|
+
const merged = [...explained, ...refused];
|
|
2173
|
+
const faults = [...new Map(merged.map((fault) => [JSON.stringify([fault.reason, extractPath(fault)]), fault])).values()];
|
|
2174
|
+
const covers = faults.filter((fault) => fault.reason === "variant" || fault.reason === "oneOf").map((fault) => extractPath(fault));
|
|
2175
|
+
const uncovered = faults.filter((fault) => {
|
|
2176
|
+
const path = extractPath(fault);
|
|
2177
|
+
const room = fault.reason === "variant" || fault.reason === "oneOf" ? 1 : 0;
|
|
2178
|
+
return !covers.some((cover) => cover.length + room <= path.length && cover.every((segment, index) => segment === path[index]));
|
|
2179
|
+
});
|
|
2180
|
+
if (uncovered.length > 0) return failure({ faults: limitEntries(uncovered, 64) });
|
|
2181
|
+
if (audited.length >= 64) return failure({ faults: limitEntries(audited, 64) });
|
|
2182
|
+
if (parsed === void 0) return failure({ faults: limitEntries(audited, 64) });
|
|
2183
|
+
return success({
|
|
2184
|
+
value: parsed,
|
|
2185
|
+
repairs
|
|
2186
|
+
});
|
|
2187
|
+
} catch (cause) {
|
|
2188
|
+
return failure({
|
|
2189
|
+
faults: [],
|
|
2190
|
+
cause
|
|
2191
|
+
});
|
|
2192
|
+
}
|
|
2193
|
+
}
|
|
2194
|
+
/**
|
|
2195
|
+
* Checks whether a type fault describes an own undefined field omitted or defaulted by a successful parse.
|
|
2196
|
+
*
|
|
2197
|
+
* @remarks
|
|
2198
|
+
* Reads own members directly so absence and an unreadable member cannot stand for undefined.
|
|
2199
|
+
* A compiled parser fills an undefined field only through its declared default; it never coerces it.
|
|
2200
|
+
* Required reads propagate their cause to the admission boundary.
|
|
2201
|
+
*
|
|
2202
|
+
* @example
|
|
2203
|
+
* ```ts
|
|
2204
|
+
* matchesUndefinedField({ reason: 'type', path: ['note'], expected: 'string', received: 'undefined' }, { note: undefined }, {}) // true
|
|
2205
|
+
* ```
|
|
2206
|
+
*/
|
|
2207
|
+
function matchesUndefinedField(fault, value, parsed) {
|
|
2208
|
+
if (fault.reason !== "type" || parsed === void 0) return false;
|
|
2209
|
+
const path = extractPath(fault);
|
|
2210
|
+
const key = path.at(-1);
|
|
2211
|
+
if (key === void 0) return false;
|
|
2212
|
+
const [raw, result] = path.slice(0, -1).reduce(([raw, result], segment) => [isObject(raw) && INTRINSICS.own(raw, segment) ? INTRINSICS.reflect.read(raw, segment) : void 0, isObject(result) && INTRINSICS.own(result, segment) ? INTRINSICS.reflect.read(result, segment) : void 0], [value, parsed]);
|
|
2213
|
+
return isObject(raw) && INTRINSICS.own(raw, key) && INTRINSICS.reflect.read(raw, key) === void 0 && isObject(result);
|
|
2214
|
+
}
|
|
2215
|
+
/**
|
|
2216
|
+
* Truncates text to a UTF-16 budget without splitting a surrogate pair.
|
|
2217
|
+
*
|
|
2218
|
+
* @example
|
|
2219
|
+
* ```ts
|
|
2220
|
+
* truncateFaultText('abcdef', 4) // 'abc…'
|
|
2221
|
+
* ```
|
|
2222
|
+
*/
|
|
2223
|
+
function truncateFaultText(text, limit) {
|
|
2224
|
+
if (limit <= 0) return "";
|
|
2225
|
+
if (text.length <= limit) return text;
|
|
2226
|
+
return `${text.slice(0, limit - 1).replace(/[\uD800-\uDBFF]$/u, "")}…`;
|
|
2227
|
+
}
|
|
2228
|
+
/**
|
|
2229
|
+
* Describes bounded faults with encoded values and a schema-derived correction summary.
|
|
2230
|
+
*
|
|
2231
|
+
* @remarks
|
|
2232
|
+
* Default: 2048 UTF-16 code units. A smaller non-negative integer limit reserves a caller's
|
|
2233
|
+
* heading budget. The report reserves room for omitted-fault and cap notices, and ends with a
|
|
2234
|
+
* send summary when a schema is supplied. Untrusted names, descriptions, and strings use preview.
|
|
2235
|
+
*
|
|
2236
|
+
* @example
|
|
2237
|
+
* ```ts
|
|
2238
|
+
* describeFaults([{ reason: 'missing', path: ['age'], expected: 'number' }])
|
|
2239
|
+
* // 'age: missing; expected number'
|
|
2240
|
+
* ```
|
|
2241
|
+
*/
|
|
2242
|
+
function describeFaults(faults, schema, options) {
|
|
2243
|
+
const requested = options?.limit ?? 2048;
|
|
2244
|
+
if (!isInteger(requested) || requested < 0) throw new ContractError("Fault text limit must be a non-negative integer", { code: "range" });
|
|
2245
|
+
const limit = Math.min(requested, FAULT_TEXT_LIMIT);
|
|
2246
|
+
const send = schema === void 0 ? "" : `send ${renderForm(schema, Math.min(160, Math.floor(limit / 3)))}`;
|
|
2247
|
+
const lines = limitEntries(faults, 64).map((fault) => describeFaultLine(fault, schema ?? {}));
|
|
2248
|
+
const room = Math.max(0, limit - send.length - 82);
|
|
2249
|
+
const kept = lines.filter((_, index) => lines.slice(0, index + 1).join("\n").length <= room);
|
|
2250
|
+
const hidden = faults.length - kept.length;
|
|
2251
|
+
const note = [...hidden > 0 ? [`and ${String(hidden)} more faults`] : [], ...faults.length >= 64 ? [`the report stops at ${String(64)}`] : []].join(", ");
|
|
2252
|
+
return truncateFaultText([
|
|
2253
|
+
...kept,
|
|
2254
|
+
...kept.length === 0 && lines.length > 0 && room > 0 ? [truncateFaultText(lines[0] ?? "", room)] : [],
|
|
2255
|
+
...note.length === 0 ? [] : [note],
|
|
2256
|
+
...send.length === 0 ? [] : [send]
|
|
2257
|
+
].join("\n"), limit);
|
|
2258
|
+
}
|
|
2259
|
+
/**
|
|
1908
2260
|
* Iterates indices while rereading the upper bound before every step.
|
|
1909
2261
|
*
|
|
1910
2262
|
* @remarks
|
|
@@ -2487,6 +2839,93 @@ function matchesPattern(pattern, value) {
|
|
|
2487
2839
|
return INTRINSICS.reflect.apply(INTRINSICS.captures, pattern, [value]) !== null;
|
|
2488
2840
|
}
|
|
2489
2841
|
/**
|
|
2842
|
+
* Checks whether a string's length in code points falls within optional bounds.
|
|
2843
|
+
*
|
|
2844
|
+
* @remarks
|
|
2845
|
+
* Counts what JSON Schema's `minLength` and `maxLength` count: a surrogate pair is
|
|
2846
|
+
* one, and a lone surrogate is one. A string holds at most `.length` code points and
|
|
2847
|
+
* at least half that, so `.length` decides every bound it can with no count. The
|
|
2848
|
+
* count runs only where a bound sits between those two figures, which limits its
|
|
2849
|
+
* work to about twice the bound rather than to the size of the string.
|
|
2850
|
+
*
|
|
2851
|
+
* @param value - The string to measure
|
|
2852
|
+
* @param min - The inclusive lower bound, when there is one
|
|
2853
|
+
* @param max - The inclusive upper bound, when there is one
|
|
2854
|
+
* @returns True if the code-point count is within every present bound; false otherwise
|
|
2855
|
+
*
|
|
2856
|
+
* @example
|
|
2857
|
+
* ```ts
|
|
2858
|
+
* matchesStringLength('😀😀', undefined, 2) // true
|
|
2859
|
+
* matchesStringLength('😀', 2, undefined) // false
|
|
2860
|
+
* ```
|
|
2861
|
+
*/
|
|
2862
|
+
function matchesStringLength(value, min, max) {
|
|
2863
|
+
const length = value.length;
|
|
2864
|
+
if (min !== void 0 && length < min) return false;
|
|
2865
|
+
if (max !== void 0 && length > 2 * max) return false;
|
|
2866
|
+
if ((min === void 0 || INTRINSICS.ceil(length / 2) >= min) && (max === void 0 || length <= max)) return true;
|
|
2867
|
+
const points = length - computeSurrogatePairs(value, length - (min === void 0 ? max ?? 0 : min - 1));
|
|
2868
|
+
return (min === void 0 || points >= min) && (max === void 0 || points <= max);
|
|
2869
|
+
}
|
|
2870
|
+
/**
|
|
2871
|
+
* Counts the surrogate pairs in a string, stopping at a limit.
|
|
2872
|
+
*
|
|
2873
|
+
* @remarks
|
|
2874
|
+
* A regular-expression literal builds a fresh `RegExp` per evaluation, so this call
|
|
2875
|
+
* owns the `lastIndex` that is its cursor, and the captured `exec` reads the internal
|
|
2876
|
+
* slots and no member a caller can replace. Text with no surrogate costs one native
|
|
2877
|
+
* scan, and a string of pairs costs one `exec` per pair up to the limit.
|
|
2878
|
+
*
|
|
2879
|
+
* @param value - The string to scan
|
|
2880
|
+
* @param limit - The count to stop at
|
|
2881
|
+
* @returns The number of surrogate pairs, or `limit` when the string holds at least that many
|
|
2882
|
+
*
|
|
2883
|
+
* @example
|
|
2884
|
+
* ```ts
|
|
2885
|
+
* computeSurrogatePairs('😀a😀', 8) // 2
|
|
2886
|
+
* computeSurrogatePairs('😀😀😀', 2) // 2
|
|
2887
|
+
* ```
|
|
2888
|
+
*/
|
|
2889
|
+
function computeSurrogatePairs(value, limit) {
|
|
2890
|
+
const pair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
|
|
2891
|
+
const steps = limit > 0 ? INTRINSICS.ceil(limit) : 0;
|
|
2892
|
+
for (const step of iterateIndices(() => steps)) if (INTRINSICS.reflect.apply(INTRINSICS.captures, pair, [value]) === null) return step;
|
|
2893
|
+
return steps;
|
|
2894
|
+
}
|
|
2895
|
+
/**
|
|
2896
|
+
* Refuses an options record that holds a key its builder does not read.
|
|
2897
|
+
*
|
|
2898
|
+
* @remarks
|
|
2899
|
+
* The door for an option that decides what a contract accepts, where a misspelled key
|
|
2900
|
+
* would otherwise read as an absent option and fail open. It looks at own enumerable
|
|
2901
|
+
* string keys, so an inherited or symbol-keyed member is not a misspelling.
|
|
2902
|
+
*
|
|
2903
|
+
* @param source - The builder options, when there are any
|
|
2904
|
+
* @param keys - The keys that builder reads
|
|
2905
|
+
* @param builder - The builder name used in the refusal
|
|
2906
|
+
* @param shape - The shape category used in structured error context
|
|
2907
|
+
* @throws {ContractError} When the record holds any other key
|
|
2908
|
+
*
|
|
2909
|
+
* @example
|
|
2910
|
+
* ```ts
|
|
2911
|
+
* refuseOptionKeys({ strict: true }, ['strict'], 'schemaToShape', 'schema') // returns
|
|
2912
|
+
* refuseOptionKeys({ strct: true }, ['strict'], 'schemaToShape', 'schema') // throws
|
|
2913
|
+
* ```
|
|
2914
|
+
*/
|
|
2915
|
+
function refuseOptionKeys(source, keys, builder, shape) {
|
|
2916
|
+
if (source === void 0) return;
|
|
2917
|
+
const first = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(INTRINSICS.keys(source)), [(key) => !INTRINSICS.reflect.apply(INTRINSICS.some, keys, [(name) => name === key])])[0];
|
|
2918
|
+
if (first === void 0) return;
|
|
2919
|
+
const known = INTRINSICS.reflect.apply(INTRINSICS.join, keys, [", "]);
|
|
2920
|
+
throw new ContractError(`${builder}: unknown option ${preview(first)}; the options are ${known}`, {
|
|
2921
|
+
code: "structure",
|
|
2922
|
+
context: {
|
|
2923
|
+
path: [first],
|
|
2924
|
+
shape
|
|
2925
|
+
}
|
|
2926
|
+
});
|
|
2927
|
+
}
|
|
2928
|
+
/**
|
|
2490
2929
|
* Escapes every regular-expression metacharacter in a text, so the text
|
|
2491
2930
|
* matches literally inside a larger `RegExp` source.
|
|
2492
2931
|
*
|
|
@@ -2812,7 +3251,7 @@ function readValue(callback, reader, options) {
|
|
|
2812
3251
|
};
|
|
2813
3252
|
const requested = options?.code;
|
|
2814
3253
|
const subject = options?.subject;
|
|
2815
|
-
const code = requested !== void 0 &&
|
|
3254
|
+
const code = requested !== void 0 && INTRINSICS.reflect.apply(INTRINSICS.some, CONTRACT_CODES, [(known) => known === requested]) ? requested : "structure";
|
|
2816
3255
|
return {
|
|
2817
3256
|
reader: isString(reader) ? reader : "readValue",
|
|
2818
3257
|
subject: isString(subject) ? subject : "value",
|
|
@@ -3308,6 +3747,70 @@ function resolveField(record, path) {
|
|
|
3308
3747
|
return isSuccess(outcome) ? outcome.value : void 0;
|
|
3309
3748
|
}
|
|
3310
3749
|
/**
|
|
3750
|
+
* Determines whether an object holds exactly the named own keys.
|
|
3751
|
+
*
|
|
3752
|
+
* @remarks
|
|
3753
|
+
* Every required key must be own, and every own key, symbols and non-enumerable ones
|
|
3754
|
+
* included, must be named, so an inherited field and a stray one both answer `false`.
|
|
3755
|
+
*
|
|
3756
|
+
* @param value - The object to inspect
|
|
3757
|
+
* @param required - The keys it must own
|
|
3758
|
+
* @param optional - The keys it may own
|
|
3759
|
+
* @returns True if its own keys are exactly those; false otherwise
|
|
3760
|
+
*
|
|
3761
|
+
* @example
|
|
3762
|
+
* ```ts
|
|
3763
|
+
* matchesExactKeys({ a: 1 }, ['a']) // true
|
|
3764
|
+
* matchesExactKeys({ a: 1, b: 2 }, ['a']) // false
|
|
3765
|
+
* matchesExactKeys({ a: 1, b: 2 }, ['a'], ['b']) // true
|
|
3766
|
+
* ```
|
|
3767
|
+
*/
|
|
3768
|
+
function matchesExactKeys(value, required, optional = []) {
|
|
3769
|
+
if (INTRINSICS.reflect.apply(INTRINSICS.some, required, [(key) => !INTRINSICS.own(value, key)])) return false;
|
|
3770
|
+
return !INTRINSICS.reflect.apply(INTRINSICS.some, INTRINSICS.reflect.members(value), [(key) => !INTRINSICS.reflect.apply(INTRINSICS.some, required, [(name) => name === key]) && !INTRINSICS.reflect.apply(INTRINSICS.some, optional, [(name) => name === key])]);
|
|
3771
|
+
}
|
|
3772
|
+
/**
|
|
3773
|
+
* Determines whether a repair `parse` made kept everything the value said.
|
|
3774
|
+
*
|
|
3775
|
+
* @remarks
|
|
3776
|
+
* `parse`'s coercions are published and form input relies on them, but some change what
|
|
3777
|
+
* a value means: `1` to `true`, `'9007199254740993'` to `...992`, `'1e-400'` to `0`,
|
|
3778
|
+
* `'0x10'` to `16`. A door that must not guess asks this about each fault `audit` reported,
|
|
3779
|
+
* since `audit` already names every nested repair with its path and the kind it wanted.
|
|
3780
|
+
*
|
|
3781
|
+
* Only a `type` fault is a repair. A number needs a string whose trim is the number's own
|
|
3782
|
+
* text, so `'30'` and `' 30 '` pass while `'30.0'`, `'007'`, `'0x10'`, `'1e3'`, `'+5'`,
|
|
3783
|
+
* `'.5'`, `'-0'`, and `'9007199254740993'` do not. A boolean needs `'true'` or `'false'`,
|
|
3784
|
+
* a literal its trimmed text, and a string a finite number. Anything else refuses.
|
|
3785
|
+
*
|
|
3786
|
+
* @param fault - A fault `audit` reported
|
|
3787
|
+
* @param input - The value as it arrived
|
|
3788
|
+
* @param parsed - What `parse` made of it
|
|
3789
|
+
* @returns True if the repair loses nothing; false otherwise
|
|
3790
|
+
*
|
|
3791
|
+
* @example
|
|
3792
|
+
* ```ts
|
|
3793
|
+
* const fault = { reason: 'type', path: ['a'], expected: 'number', received: '' } as const
|
|
3794
|
+
* matchesLosslessRepair(fault, { a: ' 30 ' }, { a: 30 }) // true
|
|
3795
|
+
* matchesLosslessRepair(fault, { a: '30.0' }, { a: 30 }) // false
|
|
3796
|
+
* ```
|
|
3797
|
+
*/
|
|
3798
|
+
function matchesLosslessRepair(fault, input, parsed) {
|
|
3799
|
+
if (fault.reason !== "type") return false;
|
|
3800
|
+
const keys = isString(fault.path) ? [fault.path] : fault.path;
|
|
3801
|
+
const route = INTRINSICS.from(iterateIndices(() => keys.length + 1), (index) => index === 0 ? "root" : keys[index - 1] ?? "");
|
|
3802
|
+
const raw = resolveField({ root: input }, route);
|
|
3803
|
+
const value = resolveField({ root: parsed }, route);
|
|
3804
|
+
switch (fault.expected) {
|
|
3805
|
+
case "number":
|
|
3806
|
+
case "integer": return isString(raw) && isNumber(value) && raw.trim() === INTRINSICS.text(value);
|
|
3807
|
+
case "literal": return isString(raw) && (isString(value) || isNumber(value) || isBoolean(value)) && raw.trim() === INTRINSICS.text(value);
|
|
3808
|
+
case "boolean": return raw === "true" || raw === "false";
|
|
3809
|
+
case "string": return isFiniteNumber(raw);
|
|
3810
|
+
default: return false;
|
|
3811
|
+
}
|
|
3812
|
+
}
|
|
3813
|
+
/**
|
|
3311
3814
|
* Determines whether a readable value stays within the fixed JSON container-depth limit.
|
|
3312
3815
|
*
|
|
3313
3816
|
* @remarks
|
|
@@ -3415,13 +3918,16 @@ function matchesJSONDepth(value) {
|
|
|
3415
3918
|
*
|
|
3416
3919
|
* Beside the ancestor set the walk keeps a walk-local PROVED set, so a node
|
|
3417
3920
|
* whose whole subtree already matched is not re-walked when a second path
|
|
3418
|
-
* reaches it.
|
|
3921
|
+
* reaches it. A supplied capture budget instead charges each occurrence that
|
|
3922
|
+
* ownership would copy; exhaustion throws `structure` with a `clone` cause.
|
|
3923
|
+
* Removing the recursion alone left the work exponential in shared
|
|
3419
3924
|
* aliases: thirty aliases — thirty-one ordinary records — cost `2^30` visits
|
|
3420
3925
|
* through `isJSONValue`, `parseJSONValue`, `canonicalStringify` and every
|
|
3421
3926
|
* `jsonShape` contract.
|
|
3422
3927
|
*
|
|
3423
3928
|
* @param entry - The value to inspect
|
|
3424
3929
|
* @param ancestors - Objects on the active traversal path
|
|
3930
|
+
* @param budget - Remaining capture nodes; aliases are charged for each copied occurrence when supplied
|
|
3425
3931
|
* @returns True if the value is a cycle-free JSON value; false otherwise
|
|
3426
3932
|
*
|
|
3427
3933
|
* @example
|
|
@@ -3430,8 +3936,12 @@ function matchesJSONDepth(value) {
|
|
|
3430
3936
|
* matchesJSONValue(Number.NaN, new WeakSet()) // false
|
|
3431
3937
|
* ```
|
|
3432
3938
|
*/
|
|
3433
|
-
function matchesJSONValue(entry, ancestors) {
|
|
3939
|
+
function matchesJSONValue(entry, ancestors, budget) {
|
|
3434
3940
|
return readValue(() => {
|
|
3941
|
+
if (budget !== void 0) {
|
|
3942
|
+
if (!INTRINSICS.safe(budget.left)) throw new ContractError("matchesJSONValue: invalid node budget", { code: "clone" });
|
|
3943
|
+
budget.left = INTRINSICS.min(budget.left, CLONE_NODE_LIMIT);
|
|
3944
|
+
}
|
|
3435
3945
|
const stack = [{
|
|
3436
3946
|
operation: "enter",
|
|
3437
3947
|
value: entry
|
|
@@ -3445,11 +3955,18 @@ function matchesJSONValue(entry, ancestors) {
|
|
|
3445
3955
|
admitVisited(proved, frame.value);
|
|
3446
3956
|
continue;
|
|
3447
3957
|
}
|
|
3958
|
+
if (budget !== void 0) {
|
|
3959
|
+
budget.left -= 1;
|
|
3960
|
+
if (budget.left < 0) throw new ContractError(`validateShape: default exceeds the capture node limit ${CLONE_NODE_LIMIT}`, {
|
|
3961
|
+
code: "clone",
|
|
3962
|
+
context: { limit: CLONE_NODE_LIMIT }
|
|
3963
|
+
});
|
|
3964
|
+
}
|
|
3448
3965
|
const node = frame.value;
|
|
3449
3966
|
if (node === null || isString(node) || isBoolean(node) || isFiniteNumber(node)) continue;
|
|
3450
3967
|
if (INTRINSICS.array(node)) {
|
|
3451
3968
|
if (matchesVisited(ancestors, node)) return false;
|
|
3452
|
-
if (matchesVisited(proved, node)) continue;
|
|
3969
|
+
if (budget === void 0 && matchesVisited(proved, node)) continue;
|
|
3453
3970
|
const snapshot = readArrayEntries(node);
|
|
3454
3971
|
if (isFailure(snapshot)) throw snapshot.error;
|
|
3455
3972
|
if (!snapshot.value.dense) return false;
|
|
@@ -3470,7 +3987,7 @@ function matchesJSONValue(entry, ancestors) {
|
|
|
3470
3987
|
}
|
|
3471
3988
|
if (!isRecord(node)) return false;
|
|
3472
3989
|
if (matchesVisited(ancestors, node)) return false;
|
|
3473
|
-
if (matchesVisited(proved, node)) continue;
|
|
3990
|
+
if (budget === void 0 && matchesVisited(proved, node)) continue;
|
|
3474
3991
|
admitVisited(ancestors, node);
|
|
3475
3992
|
stack[stack.length] = {
|
|
3476
3993
|
operation: "exit",
|
|
@@ -3580,7 +4097,7 @@ function schemaToObject(schema) {
|
|
|
3580
4097
|
return contain(() => {
|
|
3581
4098
|
return readValue(() => {
|
|
3582
4099
|
INTRINSICS.values(schema);
|
|
3583
|
-
if (schema.type === "object") return schema;
|
|
4100
|
+
if (INTRINSICS.own(schema, "type") && schema.type === "object") return schema;
|
|
3584
4101
|
return {
|
|
3585
4102
|
type: "object",
|
|
3586
4103
|
properties: { value: schema },
|
|
@@ -4049,7 +4566,7 @@ function preview(value) {
|
|
|
4049
4566
|
function buildStringFaults(shape, value, path, pattern) {
|
|
4050
4567
|
return readValue(() => {
|
|
4051
4568
|
const faults = [];
|
|
4052
|
-
if (shape.min !== void 0 && value
|
|
4569
|
+
if (INTRINSICS.own(shape, "min") && shape.min !== void 0 && !matchesStringLength(value, shape.min, void 0)) faults[faults.length] = {
|
|
4053
4570
|
reason: "constraint",
|
|
4054
4571
|
path,
|
|
4055
4572
|
expected: "string",
|
|
@@ -4057,7 +4574,7 @@ function buildStringFaults(shape, value, path, pattern) {
|
|
|
4057
4574
|
limit: shape.min,
|
|
4058
4575
|
received: preview(value)
|
|
4059
4576
|
};
|
|
4060
|
-
if (shape.max !== void 0 && value
|
|
4577
|
+
if (INTRINSICS.own(shape, "max") && shape.max !== void 0 && !matchesStringLength(value, void 0, shape.max)) faults[faults.length] = {
|
|
4061
4578
|
reason: "constraint",
|
|
4062
4579
|
path,
|
|
4063
4580
|
expected: "string",
|
|
@@ -4065,7 +4582,7 @@ function buildStringFaults(shape, value, path, pattern) {
|
|
|
4065
4582
|
limit: shape.max,
|
|
4066
4583
|
received: preview(value)
|
|
4067
4584
|
};
|
|
4068
|
-
const stateless = pattern ?? (shape.pattern === void 0 ? void 0 : readPattern(shape.pattern));
|
|
4585
|
+
const stateless = pattern ?? (!INTRINSICS.own(shape, "pattern") || shape.pattern === void 0 ? void 0 : readPattern(shape.pattern));
|
|
4069
4586
|
if (stateless !== void 0 && !matchesPattern(stateless, value)) {
|
|
4070
4587
|
const limit = readPatternSource(stateless);
|
|
4071
4588
|
faults[faults.length] = {
|
|
@@ -4105,16 +4622,16 @@ function buildStringFaults(shape, value, path, pattern) {
|
|
|
4105
4622
|
*/
|
|
4106
4623
|
function buildNumberFaults(shape, value, path) {
|
|
4107
4624
|
return readValue(() => {
|
|
4108
|
-
const expected = shape.integer === true ? "integer" : "number";
|
|
4625
|
+
const expected = INTRINSICS.own(shape, "integer") && shape.integer === true ? "integer" : "number";
|
|
4109
4626
|
const faults = [];
|
|
4110
|
-
if (shape.integer === true && !INTRINSICS.integer(value)) faults[faults.length] = {
|
|
4627
|
+
if (INTRINSICS.own(shape, "integer") && shape.integer === true && !INTRINSICS.integer(value)) faults[faults.length] = {
|
|
4111
4628
|
reason: "constraint",
|
|
4112
4629
|
path,
|
|
4113
4630
|
expected,
|
|
4114
4631
|
constraint: "integer",
|
|
4115
4632
|
received: preview(value)
|
|
4116
4633
|
};
|
|
4117
|
-
if (shape.min !== void 0 && value < shape.min) faults[faults.length] = {
|
|
4634
|
+
if (INTRINSICS.own(shape, "min") && shape.min !== void 0 && value < shape.min) faults[faults.length] = {
|
|
4118
4635
|
reason: "constraint",
|
|
4119
4636
|
path,
|
|
4120
4637
|
expected,
|
|
@@ -4122,7 +4639,7 @@ function buildNumberFaults(shape, value, path) {
|
|
|
4122
4639
|
limit: shape.min,
|
|
4123
4640
|
received: preview(value)
|
|
4124
4641
|
};
|
|
4125
|
-
if (shape.max !== void 0 && value > shape.max) faults[faults.length] = {
|
|
4642
|
+
if (INTRINSICS.own(shape, "max") && shape.max !== void 0 && value > shape.max) faults[faults.length] = {
|
|
4126
4643
|
reason: "constraint",
|
|
4127
4644
|
path,
|
|
4128
4645
|
expected,
|
|
@@ -4160,7 +4677,7 @@ function buildNumberFaults(shape, value, path) {
|
|
|
4160
4677
|
function buildArrayFaults(shape, length, path) {
|
|
4161
4678
|
return readValue(() => {
|
|
4162
4679
|
const faults = [];
|
|
4163
|
-
if (shape.min !== void 0 && length < shape.min) faults[faults.length] = {
|
|
4680
|
+
if (INTRINSICS.own(shape, "min") && shape.min !== void 0 && length < shape.min) faults[faults.length] = {
|
|
4164
4681
|
reason: "constraint",
|
|
4165
4682
|
path,
|
|
4166
4683
|
expected: "array",
|
|
@@ -4168,7 +4685,7 @@ function buildArrayFaults(shape, length, path) {
|
|
|
4168
4685
|
limit: shape.min,
|
|
4169
4686
|
received: INTRINSICS.text(length)
|
|
4170
4687
|
};
|
|
4171
|
-
if (shape.max !== void 0 && length > shape.max) faults[faults.length] = {
|
|
4688
|
+
if (INTRINSICS.own(shape, "max") && shape.max !== void 0 && length > shape.max) faults[faults.length] = {
|
|
4172
4689
|
reason: "constraint",
|
|
4173
4690
|
path,
|
|
4174
4691
|
expected: "array",
|
|
@@ -4242,7 +4759,7 @@ function shapeToKind(shape) {
|
|
|
4242
4759
|
return readValue(() => {
|
|
4243
4760
|
switch (shape.category) {
|
|
4244
4761
|
case "string": return "string";
|
|
4245
|
-
case "number": return shape.integer === true ? "integer" : "number";
|
|
4762
|
+
case "number": return INTRINSICS.own(shape, "integer") && shape.integer === true ? "integer" : "number";
|
|
4246
4763
|
case "boolean": return "boolean";
|
|
4247
4764
|
case "null": return "null";
|
|
4248
4765
|
case "literal": return "literal";
|
|
@@ -4250,6 +4767,7 @@ function shapeToKind(shape) {
|
|
|
4250
4767
|
case "object": return "object";
|
|
4251
4768
|
case "union": return "union";
|
|
4252
4769
|
case "json": return "json";
|
|
4770
|
+
case "shape": return "shape";
|
|
4253
4771
|
case "optional": return shapeToKind(shape.inner);
|
|
4254
4772
|
case "nullable": return shapeToKind(shape.inner);
|
|
4255
4773
|
case "raw": return "json";
|
|
@@ -4394,6 +4912,233 @@ for (const generator of [iterateIndices, encodeParts]) {
|
|
|
4394
4912
|
INTRINSICS.freeze(generator.prototype);
|
|
4395
4913
|
INTRINSICS.freeze(generator);
|
|
4396
4914
|
}
|
|
4915
|
+
/**
|
|
4916
|
+
* Extracts a fault's path as its segments, reading a string path as one segment.
|
|
4917
|
+
*
|
|
4918
|
+
* @param fault - The fault to read
|
|
4919
|
+
* @returns The path's segments, empty at the root
|
|
4920
|
+
*
|
|
4921
|
+
* @example
|
|
4922
|
+
* ```ts
|
|
4923
|
+
* import { extractPath } from '@orkestrel/contract'
|
|
4924
|
+
*
|
|
4925
|
+
* extractPath({ reason: 'extra', path: ['page', 'typo'] }) // ['page', 'typo']
|
|
4926
|
+
* ```
|
|
4927
|
+
*/
|
|
4928
|
+
function extractPath(fault) {
|
|
4929
|
+
return isString(fault.path) ? [fault.path] : fault.path;
|
|
4930
|
+
}
|
|
4931
|
+
/**
|
|
4932
|
+
* Extracts a schema's forms: the schema itself, then its union arms, so a read looks
|
|
4933
|
+
* through a nullable the same way everywhere.
|
|
4934
|
+
*
|
|
4935
|
+
* @param schema - The schema to read, or `undefined` where none was found
|
|
4936
|
+
* @returns The forms, empty when there is no schema
|
|
4937
|
+
*
|
|
4938
|
+
* @example
|
|
4939
|
+
* ```ts
|
|
4940
|
+
* import { extractForms } from '@orkestrel/contract'
|
|
4941
|
+
*
|
|
4942
|
+
* const object = { type: 'object' } as const
|
|
4943
|
+
* extractForms({ anyOf: [object] }) // [{ anyOf: [object] }, object]
|
|
4944
|
+
* ```
|
|
4945
|
+
*/
|
|
4946
|
+
function extractForms(schema) {
|
|
4947
|
+
if (schema === void 0) return [];
|
|
4948
|
+
const anyOf = INTRINSICS.own(schema, "anyOf") ? schema.anyOf : void 0;
|
|
4949
|
+
const oneOf = INTRINSICS.own(schema, "oneOf") ? schema.oneOf : void 0;
|
|
4950
|
+
return [schema, ...anyOf ?? oneOf ?? []];
|
|
4951
|
+
}
|
|
4952
|
+
/**
|
|
4953
|
+
* Extracts the part of a schema a path reaches, through properties, array items, record values,
|
|
4954
|
+
* and the arms of a union.
|
|
4955
|
+
*
|
|
4956
|
+
* @remarks
|
|
4957
|
+
* Each path segment takes one step, so a union that nests itself cannot hold the walk. Only a
|
|
4958
|
+
* schema's own `properties` keys match, so `constructor` reaches nothing. The walk keeps every
|
|
4959
|
+
* matching union declaration until the end; differing declarations yield no schema. Independently
|
|
4960
|
+
* built declarations agree when their canonical JSON encodings agree.
|
|
4961
|
+
*
|
|
4962
|
+
* @param schema - The schema to walk
|
|
4963
|
+
* @param path - The segments to follow
|
|
4964
|
+
* @returns The schema at that path, or `undefined` where no declaration or no agreement exists
|
|
4965
|
+
*
|
|
4966
|
+
* @example
|
|
4967
|
+
* ```ts
|
|
4968
|
+
* import { extractSchema } from '@orkestrel/contract'
|
|
4969
|
+
*
|
|
4970
|
+
* const schema = { type: 'object', properties: { limit: { type: 'number' } } } as const
|
|
4971
|
+
* extractSchema(schema, ['limit']) // { type: 'number' }
|
|
4972
|
+
* ```
|
|
4973
|
+
*/
|
|
4974
|
+
function extractSchema(schema, path) {
|
|
4975
|
+
const nodes = path.reduce((parents, key) => Array.from(new Set(parents.flatMap((node) => extractForms(node)).map((form) => {
|
|
4976
|
+
const properties = INTRINSICS.own(form, "properties") ? form.properties : void 0;
|
|
4977
|
+
const additional = INTRINSICS.own(form, "additionalProperties") ? form.additionalProperties : void 0;
|
|
4978
|
+
return properties !== void 0 && INTRINSICS.own(properties, key) ? properties[key] : isRecord(additional) ? additional : INTRINSICS.own(form, "items") ? form.items : void 0;
|
|
4979
|
+
}).filter((child) => child !== void 0))), [schema]);
|
|
4980
|
+
const first = nodes[0];
|
|
4981
|
+
if (nodes.length < 2) return first;
|
|
4982
|
+
const encoded = canonicalStringify(first);
|
|
4983
|
+
return encoded !== void 0 && nodes.every((node) => canonicalStringify(node) === encoded) ? first : void 0;
|
|
4984
|
+
}
|
|
4985
|
+
/**
|
|
4986
|
+
* Renders a path as text, encoding what a caller could have sent and eliding the middle of a long
|
|
4987
|
+
* one.
|
|
4988
|
+
*
|
|
4989
|
+
* @remarks
|
|
4990
|
+
* A segment that is not a plain identifier is JSON-encoded and length-capped, because a key the
|
|
4991
|
+
* caller sent is untrusted text. A path of more than four segments past 120 characters keeps its
|
|
4992
|
+
* first segment and its last three.
|
|
4993
|
+
*
|
|
4994
|
+
* @param path - The segments to render
|
|
4995
|
+
* @returns The segments joined with `.`, empty at the root
|
|
4996
|
+
*
|
|
4997
|
+
* @example
|
|
4998
|
+
* ```ts
|
|
4999
|
+
* import { renderPath } from '@orkestrel/contract'
|
|
5000
|
+
*
|
|
5001
|
+
* renderPath(['rows', '0', 'a b']) // 'rows.0."a b"'
|
|
5002
|
+
* ```
|
|
5003
|
+
*/
|
|
5004
|
+
function renderPath(path) {
|
|
5005
|
+
const segments = path.map((segment) => /^[\w$-]{1,64}$/u.test(segment) ? segment : preview(segment));
|
|
5006
|
+
const text = segments.join(".");
|
|
5007
|
+
return segments.length <= 4 || text.length <= 120 ? text : [
|
|
5008
|
+
...segments.slice(0, 1),
|
|
5009
|
+
"…",
|
|
5010
|
+
...segments.slice(-3)
|
|
5011
|
+
].join(".");
|
|
5012
|
+
}
|
|
5013
|
+
/**
|
|
5014
|
+
* Renders a list as text, naming at most `FAULT_LIST_LIMIT` of its entries and counting the rest.
|
|
5015
|
+
*
|
|
5016
|
+
* @param entries - The rendered entries
|
|
5017
|
+
* @returns The entries joined with `, `
|
|
5018
|
+
*
|
|
5019
|
+
* @example
|
|
5020
|
+
* ```ts
|
|
5021
|
+
* import { renderList } from '@orkestrel/contract'
|
|
5022
|
+
*
|
|
5023
|
+
* renderList(['city', 'units']) // 'city, units'
|
|
5024
|
+
* ```
|
|
5025
|
+
*/
|
|
5026
|
+
function renderList(entries) {
|
|
5027
|
+
const listed = entries.slice(0, 12).join(", ");
|
|
5028
|
+
return entries.length > 12 ? `${listed} and ${String(entries.length - 12)} more` : listed;
|
|
5029
|
+
}
|
|
5030
|
+
/**
|
|
5031
|
+
* Renders a schema as a short summary of what to send, such as `{"city": string, "note"?: string}`.
|
|
5032
|
+
*
|
|
5033
|
+
* @remarks
|
|
5034
|
+
* An object lists its required keys first and marks the rest with `?`, at most `FAULT_LIST_LIMIT`
|
|
5035
|
+
* of them. A leaf or array keeps its numeric bounds and pattern, a union joins its forms with ` | `,
|
|
5036
|
+
* and a schema that says nothing reads `any`. Each nested form takes half the room of its parent, and
|
|
5037
|
+
* below 16 characters a form stops at its type, so a schema that holds itself still ends. Text past
|
|
5038
|
+
* `room` is cut and closes with `…`. A type word outside JSON Schema's vocabulary is encoded.
|
|
5039
|
+
*
|
|
5040
|
+
* @param schema - The schema to summarize
|
|
5041
|
+
* @param room - The characters the summary can take. Default: `FAULT_SCHEMA_LIMIT`
|
|
5042
|
+
* @returns The summary
|
|
5043
|
+
*
|
|
5044
|
+
* @example
|
|
5045
|
+
* ```ts
|
|
5046
|
+
* import { renderForm } from '@orkestrel/contract'
|
|
5047
|
+
*
|
|
5048
|
+
* renderForm({ type: 'object', properties: { zip: { type: 'number' } }, required: ['zip'] }) // '{"zip": number}'
|
|
5049
|
+
* ```
|
|
5050
|
+
*/
|
|
5051
|
+
function renderForm(schema, room = 160) {
|
|
5052
|
+
const deep = room >= 16;
|
|
5053
|
+
const inner = Math.floor(room / 2);
|
|
5054
|
+
const anyOf = INTRINSICS.own(schema, "anyOf") ? schema.anyOf : void 0;
|
|
5055
|
+
const oneOf = INTRINSICS.own(schema, "oneOf") ? schema.oneOf : void 0;
|
|
5056
|
+
const forms = anyOf ?? oneOf;
|
|
5057
|
+
const required = (INTRINSICS.own(schema, "required") ? schema.required : void 0) ?? [];
|
|
5058
|
+
const entries = Object.entries((INTRINSICS.own(schema, "properties") ? schema.properties : void 0) ?? {});
|
|
5059
|
+
const type = INTRINSICS.own(schema, "type") ? schema.type : void 0;
|
|
5060
|
+
const enumeration = INTRINSICS.own(schema, "enum") ? schema.enum : void 0;
|
|
5061
|
+
const additional = INTRINSICS.own(schema, "additionalProperties") ? schema.additionalProperties : void 0;
|
|
5062
|
+
const listed = (deep ? entries : []).toSorted(([left], [right]) => Number(required.includes(right)) - Number(required.includes(left))).slice(0, 12).map(([key, child]) => `${preview(key)}${required.includes(key) ? "" : "?"}: ${renderForm(child, inner)}`);
|
|
5063
|
+
const left = entries.length - listed.length;
|
|
5064
|
+
const child = type === "array" ? INTRINSICS.own(schema, "items") ? schema.items : void 0 : isRecord(additional) ? additional : void 0;
|
|
5065
|
+
const bounds = Object.entries(schema).filter(([key]) => [
|
|
5066
|
+
"minLength",
|
|
5067
|
+
"maxLength",
|
|
5068
|
+
"minimum",
|
|
5069
|
+
"maximum",
|
|
5070
|
+
"minItems",
|
|
5071
|
+
"maxItems",
|
|
5072
|
+
"pattern"
|
|
5073
|
+
].includes(key)).map(([key, value]) => `${key} ${preview(value)}`);
|
|
5074
|
+
return truncateFaultText(forms !== void 0 ? deep ? forms.map((form) => renderForm(form, inner)).join(" | ") : "any" : enumeration !== void 0 ? enumeration.map((value) => preview(value)).join(" | ") : listed.length > 0 ? `{${[...listed, ...left > 0 ? [`and ${String(left)} more`] : []].join(", ")}}` : [
|
|
5075
|
+
type === void 0 ? entries.length > 0 ? "object" : "any" : JSON_SCHEMA_TYPES.some((name) => name === type) ? type : preview(type),
|
|
5076
|
+
...deep && child !== void 0 ? [` of ${renderForm(child, inner)}`] : [],
|
|
5077
|
+
...bounds.length > 0 ? [` (${bounds.join(", ")})`] : []
|
|
5078
|
+
].join(""), room);
|
|
5079
|
+
}
|
|
5080
|
+
/**
|
|
5081
|
+
* Describes one fault as the line a caller corrects from, naming what to send where the schema
|
|
5082
|
+
* says.
|
|
5083
|
+
*
|
|
5084
|
+
* @remarks
|
|
5085
|
+
* Each line opens with the fault's path (or `value` at the root) and reason. An `extra` fault lists
|
|
5086
|
+
* its parent's keys only when the declaring arms agree. A literal names candidates only where
|
|
5087
|
+
* the declarations agree; lists are deduplicated and bounded. A received preview stays as written
|
|
5088
|
+
* within PREVIEW_LIMIT and without control or line-separator characters; otherwise it is encoded
|
|
5089
|
+
* through preview. Received, constraint, and limit details read only own fields. A `variant` or
|
|
5090
|
+
* `oneOf` fault says that the value matches none of the declared forms, or several where one must
|
|
5091
|
+
* match, and summarizes each form through `renderForm`. It names no fault of any one form, because
|
|
5092
|
+
* none of them holds for the others. Those summaries share half of `FAULT_TEXT_LIMIT`.
|
|
5093
|
+
*
|
|
5094
|
+
* @param fault - The fault to describe
|
|
5095
|
+
* @param schema - The compiled schema the fault's path reads
|
|
5096
|
+
* @returns The line, with no line break
|
|
5097
|
+
*
|
|
5098
|
+
* @example
|
|
5099
|
+
* ```ts
|
|
5100
|
+
* import { describeFaultLine } from '@orkestrel/contract'
|
|
5101
|
+
*
|
|
5102
|
+
* describeFaultLine({ reason: 'missing', path: ['left'], expected: 'number' }, {}) // 'left: missing; expected number'
|
|
5103
|
+
* ```
|
|
5104
|
+
*/
|
|
5105
|
+
function describeFaultLine(fault, schema) {
|
|
5106
|
+
const path = extractPath(fault);
|
|
5107
|
+
const head = `${renderPath(path) || "value"}: ${fault.reason}`;
|
|
5108
|
+
if (fault.reason === "extra") {
|
|
5109
|
+
const declarations = extractForms(extractSchema(schema, path.slice(0, -1))).filter((form) => INTRINSICS.own(form, "properties") && form.properties !== void 0).map((form) => Object.keys(form.properties ?? {}));
|
|
5110
|
+
const first = declarations[0] ?? [];
|
|
5111
|
+
const keys = declarations.every((declared) => declared.length === first.length && declared.every((key) => first.includes(key))) ? first : [];
|
|
5112
|
+
return keys.length === 0 ? `${head}; this key is not declared, remove it` : `${head}; this key is not declared, remove it or use a declared key: ${renderList(keys.map((key) => renderPath([key])))}`;
|
|
5113
|
+
}
|
|
5114
|
+
const node = extractSchema(schema, path);
|
|
5115
|
+
const anyOf = node !== void 0 && INTRINSICS.own(node, "anyOf") ? node.anyOf : void 0;
|
|
5116
|
+
const oneOf = node !== void 0 && INTRINSICS.own(node, "oneOf") ? node.oneOf : void 0;
|
|
5117
|
+
if (fault.reason === "variant" || fault.reason === "oneOf") {
|
|
5118
|
+
const count = fault.reason === "variant" ? fault.variants : oneOf?.length;
|
|
5119
|
+
const forms = count === void 0 ? "the declared forms" : `the ${String(count)} declared forms`;
|
|
5120
|
+
const claim = fault.reason === "oneOf" && fault.matched > 0 ? `the value matches ${String(fault.matched)} of ${forms} and must match exactly one` : `the value matches none of ${forms}`;
|
|
5121
|
+
const declared = anyOf ?? oneOf ?? [];
|
|
5122
|
+
const shown = declared.slice(0, 12);
|
|
5123
|
+
const room = Math.min(160, Math.floor(FAULT_TEXT_LIMIT / 2 / Math.max(shown.length, 1)));
|
|
5124
|
+
const more = declared.length - shown.length;
|
|
5125
|
+
const summary = shown.length === 0 ? "" : `, one of: ${shown.map((form) => renderForm(form, room)).join(" or ")}${more > 0 ? ` and ${String(more)} more` : ""}`;
|
|
5126
|
+
return `${head}; ${claim}${fault.key === void 0 ? "" : `; discriminator ${preview(fault.key)} expects ${renderList((fault.expected ?? []).map((value) => preview(value)))}`}; send it exactly as the schema declares${summary}`;
|
|
5127
|
+
}
|
|
5128
|
+
const candidates = fault.expected === "literal" ? extractForms(node).flatMap((form) => [...(INTRINSICS.own(form, "enum") ? form.enum : void 0) ?? [], ...INTRINSICS.own(form, "type") && form.type === "null" ? [null] : []]) : [];
|
|
5129
|
+
const description = node !== void 0 && INTRINSICS.own(node, "description") ? node.description : void 0;
|
|
5130
|
+
const received = "received" in fault && INTRINSICS.own(fault, "received") ? fault.received : void 0;
|
|
5131
|
+
const shown = received !== void 0 && received.length <= 64 && !/[\p{Cc}\p{Zl}\p{Zp}]/u.test(received) ? received : preview(received);
|
|
5132
|
+
return [
|
|
5133
|
+
head,
|
|
5134
|
+
`expected ${fault.expected}`,
|
|
5135
|
+
...received !== void 0 ? [`received ${shown}`] : [],
|
|
5136
|
+
..."constraint" in fault && INTRINSICS.own(fault, "constraint") ? [`constraint ${fault.constraint}`] : [],
|
|
5137
|
+
..."limit" in fault && INTRINSICS.own(fault, "limit") && fault.limit !== void 0 ? [`limit ${preview(fault.limit)}`] : [],
|
|
5138
|
+
...description === void 0 ? [] : [`description ${preview(description)}`],
|
|
5139
|
+
...candidates.length > 0 ? [`send one of ${renderList(Array.from(new Set(candidates), (value) => preview(value)))}`] : []
|
|
5140
|
+
].join("; ");
|
|
5141
|
+
}
|
|
4397
5142
|
// src/core/JSONCloner.ts
|
|
4398
5143
|
/**
|
|
4399
5144
|
* Owns the state of one exact JSON snapshot operation.
|
|
@@ -4425,7 +5170,6 @@ var JSONCloner = class JSONCloner {
|
|
|
4425
5170
|
#owned;
|
|
4426
5171
|
#active;
|
|
4427
5172
|
#pending;
|
|
4428
|
-
#produced;
|
|
4429
5173
|
#poison;
|
|
4430
5174
|
#terminal;
|
|
4431
5175
|
constructor(value) {
|
|
@@ -4433,17 +5177,17 @@ var JSONCloner = class JSONCloner {
|
|
|
4433
5177
|
this.#owned = new JSONCloner.#weakSet();
|
|
4434
5178
|
this.#active = new JSONCloner.#weakSet();
|
|
4435
5179
|
this.#pending = [];
|
|
4436
|
-
this.#produced = 0;
|
|
4437
5180
|
this.#poison = void 0;
|
|
4438
5181
|
this.#terminal = void 0;
|
|
4439
5182
|
}
|
|
4440
5183
|
/**
|
|
4441
5184
|
* Clones the retained source into exact, deeply frozen JSON data.
|
|
4442
5185
|
*
|
|
5186
|
+
* @param budget - Remaining nodes shared with an enclosing ownership operation
|
|
4443
5187
|
* @returns The settled JSON snapshot
|
|
4444
5188
|
* @throws {ContractError} When the source is inexact, cyclic, unreadable, or cloning is reentered
|
|
4445
5189
|
*/
|
|
4446
|
-
clone() {
|
|
5190
|
+
clone(budget = { left: CLONE_NODE_LIMIT }) {
|
|
4447
5191
|
const terminal = this.#terminal;
|
|
4448
5192
|
if (terminal !== void 0) {
|
|
4449
5193
|
if (isSuccess(terminal)) return terminal.value;
|
|
@@ -4455,7 +5199,7 @@ var JSONCloner = class JSONCloner {
|
|
|
4455
5199
|
throw poison;
|
|
4456
5200
|
}
|
|
4457
5201
|
this.#poison = this.#create("JSONCloner.clone: JSON cloning may not be reentered");
|
|
4458
|
-
const outcome = attempt(() => this.#execute());
|
|
5202
|
+
const outcome = attempt(() => this.#execute(budget));
|
|
4459
5203
|
const interruption = this.#terminal;
|
|
4460
5204
|
if (interruption !== void 0) {
|
|
4461
5205
|
if (isSuccess(interruption)) return interruption.value;
|
|
@@ -4473,12 +5217,14 @@ var JSONCloner = class JSONCloner {
|
|
|
4473
5217
|
this.#pending = JSONCloner.#emptyPending;
|
|
4474
5218
|
throw error;
|
|
4475
5219
|
}
|
|
4476
|
-
#execute() {
|
|
4477
|
-
|
|
4478
|
-
|
|
5220
|
+
#execute(budget) {
|
|
5221
|
+
if (!INTRINSICS.safe(budget.left)) this.#refuse("cloneJSONValue: invalid node budget");
|
|
5222
|
+
budget.left = INTRINSICS.min(budget.left, CLONE_NODE_LIMIT);
|
|
5223
|
+
const root = this.#capture(this.#source, budget);
|
|
5224
|
+
this.#drain(budget);
|
|
4479
5225
|
return root;
|
|
4480
5226
|
}
|
|
4481
|
-
#drain() {
|
|
5227
|
+
#drain(budget) {
|
|
4482
5228
|
while (this.#pending.length > 0) {
|
|
4483
5229
|
const frame = this.#pending[this.#pending.length - 1];
|
|
4484
5230
|
if (frame === void 0) continue;
|
|
@@ -4491,7 +5237,7 @@ var JSONCloner = class JSONCloner {
|
|
|
4491
5237
|
continue;
|
|
4492
5238
|
}
|
|
4493
5239
|
frame.index += 1;
|
|
4494
|
-
const clone = this.#capture(entry[1]);
|
|
5240
|
+
const clone = this.#capture(entry[1], budget);
|
|
4495
5241
|
INTRINSICS.define(frame.clone, entry[0], {
|
|
4496
5242
|
value: clone,
|
|
4497
5243
|
enumerable: true,
|
|
@@ -4500,9 +5246,9 @@ var JSONCloner = class JSONCloner {
|
|
|
4500
5246
|
});
|
|
4501
5247
|
}
|
|
4502
5248
|
}
|
|
4503
|
-
#capture(value) {
|
|
4504
|
-
|
|
4505
|
-
if (
|
|
5249
|
+
#capture(value, budget) {
|
|
5250
|
+
budget.left -= 1;
|
|
5251
|
+
if (budget.left < 0) this.#refuse(`cloneJSONValue: snapshot exceeds the node limit ${CLONE_NODE_LIMIT}`, CLONE_NODE_LIMIT);
|
|
4506
5252
|
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
4507
5253
|
if (typeof value === "number") {
|
|
4508
5254
|
if (INTRINSICS.finite(value)) return value;
|
|
@@ -4565,10 +5311,13 @@ var JSONCloner = class JSONCloner {
|
|
|
4565
5311
|
return [key, descriptor.value];
|
|
4566
5312
|
});
|
|
4567
5313
|
}
|
|
4568
|
-
#create(message) {
|
|
5314
|
+
#create(message, limit) {
|
|
4569
5315
|
const error = new ContractError(message, {
|
|
4570
5316
|
code: "clone",
|
|
4571
|
-
context: {
|
|
5317
|
+
context: {
|
|
5318
|
+
shape: "json",
|
|
5319
|
+
...limit === void 0 ? {} : { limit }
|
|
5320
|
+
}
|
|
4572
5321
|
});
|
|
4573
5322
|
admitVisited(this.#owned, error);
|
|
4574
5323
|
return error;
|
|
@@ -4576,10 +5325,10 @@ var JSONCloner = class JSONCloner {
|
|
|
4576
5325
|
#owns(error) {
|
|
4577
5326
|
return isObject(error) && matchesVisited(this.#owned, error);
|
|
4578
5327
|
}
|
|
4579
|
-
#refuse(message) {
|
|
5328
|
+
#refuse(message, limit) {
|
|
4580
5329
|
const terminal = this.#terminal;
|
|
4581
5330
|
if (terminal !== void 0 && isFailure(terminal)) throw terminal.error;
|
|
4582
|
-
throw this.#create(message);
|
|
5331
|
+
throw this.#create(message, limit);
|
|
4583
5332
|
}
|
|
4584
5333
|
static {
|
|
4585
5334
|
INTRINSICS.freeze(JSONCloner.#emptyPending);
|
|
@@ -4785,7 +5534,23 @@ var SchemaCloner = class SchemaCloner {
|
|
|
4785
5534
|
var ShapePass = class ShapePass {
|
|
4786
5535
|
static #weakSet = WeakSet;
|
|
4787
5536
|
static #weakMap = WeakMap;
|
|
5537
|
+
static #arrays = Array.prototype;
|
|
5538
|
+
static #pop = Array.prototype.pop;
|
|
5539
|
+
static #iterators = INTRINSICS.prototype(INTRINSICS.reflect.apply(INTRINSICS.indices, [], []));
|
|
5540
|
+
static #blank = INTRINSICS.freeze(new INTRINSICS.pattern(""));
|
|
5541
|
+
static #fields = [
|
|
5542
|
+
"min",
|
|
5543
|
+
"max",
|
|
5544
|
+
"pattern",
|
|
5545
|
+
"description",
|
|
5546
|
+
"integer",
|
|
5547
|
+
"additionalProperties",
|
|
5548
|
+
"mode",
|
|
5549
|
+
"default"
|
|
5550
|
+
];
|
|
5551
|
+
static #seals = new ShapePass.#weakMap();
|
|
4788
5552
|
#source;
|
|
5553
|
+
#budget;
|
|
4789
5554
|
#stack = [];
|
|
4790
5555
|
#path = [];
|
|
4791
5556
|
#active = new ShapePass.#weakSet();
|
|
@@ -4795,25 +5560,96 @@ var ShapePass = class ShapePass {
|
|
|
4795
5560
|
#height = [];
|
|
4796
5561
|
#reach = [];
|
|
4797
5562
|
#via = [];
|
|
5563
|
+
#within = [];
|
|
4798
5564
|
#counts = [];
|
|
4799
5565
|
#schemas = new ShapePass.#weakMap();
|
|
4800
5566
|
#children = [];
|
|
4801
5567
|
#category;
|
|
4802
5568
|
#raw = 0;
|
|
5569
|
+
#defaulted = false;
|
|
5570
|
+
#open = false;
|
|
4803
5571
|
#structure;
|
|
4804
5572
|
#cycle;
|
|
4805
5573
|
#domain;
|
|
4806
|
-
#clock = 0;
|
|
4807
|
-
#oldest = 0;
|
|
4808
|
-
#trail = [];
|
|
4809
5574
|
#poison;
|
|
4810
|
-
constructor(shape) {
|
|
5575
|
+
constructor(shape, budget) {
|
|
4811
5576
|
this.#source = shape;
|
|
5577
|
+
this.#budget = budget;
|
|
4812
5578
|
}
|
|
4813
|
-
/**
|
|
4814
|
-
|
|
4815
|
-
|
|
4816
|
-
|
|
5579
|
+
/**
|
|
5580
|
+
* Validates a node fresh from a builder, freezes it, and records what the walk found.
|
|
5581
|
+
*
|
|
5582
|
+
* @remarks
|
|
5583
|
+
* The node's own fields are always observed, and each child is answered from its
|
|
5584
|
+
* seal rather than walked. Anything short of a clean answer takes the whole walk
|
|
5585
|
+
* instead, which is what authors every refusal, so a refusal reads the same and
|
|
5586
|
+
* fires at the same call as it would with no seals at all. That second look is safe
|
|
5587
|
+
* because the first read nothing a caller wrote: the node is this package's own
|
|
5588
|
+
* literal, and a child with no seal stops the survey before it is read.
|
|
5589
|
+
*
|
|
5590
|
+
* @param shape - The builder's fresh node, which no caller has seen
|
|
5591
|
+
* @param check - What the whole walk validates, when the node is only legal in a slot
|
|
5592
|
+
* @returns The frozen node
|
|
5593
|
+
* @throws {ContractError} When the node is refused
|
|
5594
|
+
*/
|
|
5595
|
+
static seal(shape, check = shape) {
|
|
5596
|
+
const frozen = INTRINSICS.freeze(shape);
|
|
5597
|
+
if (!new ShapePass(shape).#survey(check === shape ? 0 : 1)) new ShapePass(check, { left: CLONE_NODE_LIMIT }).validate();
|
|
5598
|
+
return frozen;
|
|
5599
|
+
}
|
|
5600
|
+
/**
|
|
5601
|
+
* Reports the expansion of a sealed node a compiler can take as it stands.
|
|
5602
|
+
*
|
|
5603
|
+
* @remarks
|
|
5604
|
+
* `undefined` sends the caller to its own ownership and validation: the node was
|
|
5605
|
+
* never sealed, an inherited field would answer a walk of it, or it is an `optional`
|
|
5606
|
+
* node, which a walk refuses as a root.
|
|
5607
|
+
*
|
|
5608
|
+
* @param shape - The declaration to look up
|
|
5609
|
+
* @returns The expansion a walk would report, or `undefined`
|
|
5610
|
+
*/
|
|
5611
|
+
static expansionOf(shape) {
|
|
5612
|
+
if (ShapePass.polluted()) return void 0;
|
|
5613
|
+
const seal = INTRINSICS.reflect.apply(INTRINSICS.recall, ShapePass.#seals, [shape]);
|
|
5614
|
+
return seal === void 0 || seal.category === "optional" ? void 0 : seal.count;
|
|
5615
|
+
}
|
|
5616
|
+
/**
|
|
5617
|
+
* Reports whether a walk could answer differently from a seal.
|
|
5618
|
+
*
|
|
5619
|
+
* @remarks
|
|
5620
|
+
* A field a node may leave out reads through to `Object.prototype`, which is a
|
|
5621
|
+
* verdict about the declaration, and a {@link tampered} host breaks a walk into a
|
|
5622
|
+
* refusal a seal would otherwise skip.
|
|
5623
|
+
*
|
|
5624
|
+
* @returns True when a walk has to answer rather than a seal
|
|
5625
|
+
*/
|
|
5626
|
+
static polluted() {
|
|
5627
|
+
if (ShapePass.tampered()) return true;
|
|
5628
|
+
return INTRINSICS.reflect.apply(INTRINSICS.some, ShapePass.#fields, [(field) => INTRINSICS.own(INTRINSICS.base, field)]);
|
|
5629
|
+
}
|
|
5630
|
+
/**
|
|
5631
|
+
* Reports whether a member a walk or a compile runs on has been replaced.
|
|
5632
|
+
*
|
|
5633
|
+
* @remarks
|
|
5634
|
+
* An index on either prototype, reached by array writes, a replaced `pop` or array
|
|
5635
|
+
* iterator `next`, and a flag getter a pattern's `flags` reads. An array's `length`
|
|
5636
|
+
* always passes its highest index, and own keys list an index first, so one read
|
|
5637
|
+
* answers for every index, and a name that merely opens with a digit only costs a walk.
|
|
5638
|
+
*
|
|
5639
|
+
* @returns True when the host is not the one this package loaded on
|
|
5640
|
+
*/
|
|
5641
|
+
static tampered() {
|
|
5642
|
+
if (ShapePass.#arrays.length !== 0) return true;
|
|
5643
|
+
const first = INTRINSICS.reflect.members(INTRINSICS.base)[0];
|
|
5644
|
+
if (typeof first === "string" && first >= "0" && first < ":") return true;
|
|
5645
|
+
if (INTRINSICS.describe(ShapePass.#arrays, "pop")?.value !== ShapePass.#pop) return true;
|
|
5646
|
+
if (INTRINSICS.describe(ShapePass.#iterators, "next")?.value !== INTRINSICS.advance) return true;
|
|
5647
|
+
return !holds(() => readPatternFlags(ShapePass.#blank) === "");
|
|
5648
|
+
}
|
|
5649
|
+
/** Poisons this pass and throws the same refusal on every reentry. */
|
|
5650
|
+
interrupt() {
|
|
5651
|
+
this.#poison ??= new ContractError("ShapeValidator.validate: shape validation may not be reentered", {
|
|
5652
|
+
code: "structure",
|
|
4817
5653
|
context: { path: [] }
|
|
4818
5654
|
});
|
|
4819
5655
|
throw this.#poison;
|
|
@@ -4830,6 +5666,34 @@ var ShapePass = class ShapePass {
|
|
|
4830
5666
|
cause: outcome.error
|
|
4831
5667
|
});
|
|
4832
5668
|
}
|
|
5669
|
+
#survey(lift) {
|
|
5670
|
+
if (ShapePass.polluted()) return false;
|
|
5671
|
+
const shape = this.#source;
|
|
5672
|
+
if (!isRecord(shape)) return false;
|
|
5673
|
+
const outcome = attempt(() => this.#observe(shape, 0));
|
|
5674
|
+
if (isFailure(outcome) || !outcome.value || this.#domain !== void 0) return false;
|
|
5675
|
+
const seal = {
|
|
5676
|
+
category: shape.category,
|
|
5677
|
+
reach: this.#raw,
|
|
5678
|
+
count: 1,
|
|
5679
|
+
defaulted: this.#defaulted,
|
|
5680
|
+
held: this.#defaulted
|
|
5681
|
+
};
|
|
5682
|
+
for (const index of iterateIndices(() => this.#children.length)) {
|
|
5683
|
+
const child = this.#children[index];
|
|
5684
|
+
const known = INTRINSICS.reflect.apply(INTRINSICS.recall, ShapePass.#seals, [child?.shape]);
|
|
5685
|
+
if (child === void 0 || known === void 0) return false;
|
|
5686
|
+
if (known.category === "optional" && !child.optional) return false;
|
|
5687
|
+
if (known.held && shape.category === "union") return false;
|
|
5688
|
+
if (known.defaulted && this.#open) return false;
|
|
5689
|
+
seal.reach = INTRINSICS.max(seal.reach, known.reach + 1);
|
|
5690
|
+
seal.count += known.count;
|
|
5691
|
+
seal.held ||= known.held;
|
|
5692
|
+
}
|
|
5693
|
+
if (seal.reach + lift > 512) return false;
|
|
5694
|
+
INTRINSICS.reflect.apply(INTRINSICS.retain, ShapePass.#seals, [shape, seal]);
|
|
5695
|
+
return true;
|
|
5696
|
+
}
|
|
4833
5697
|
#execute() {
|
|
4834
5698
|
this.#stack[this.#stack.length] = {
|
|
4835
5699
|
operation: "enter",
|
|
@@ -4851,9 +5715,11 @@ var ShapePass = class ShapePass {
|
|
|
4851
5715
|
this.#path.length -= frame.segments;
|
|
4852
5716
|
return;
|
|
4853
5717
|
}
|
|
4854
|
-
const
|
|
4855
|
-
|
|
4856
|
-
|
|
5718
|
+
const first = INTRINSICS.own(frame, "first") ? frame.first : void 0;
|
|
5719
|
+
const second = INTRINSICS.own(frame, "second") ? frame.second : void 0;
|
|
5720
|
+
const segments = (first === void 0 ? 0 : 1) + (second === void 0 ? 0 : 1);
|
|
5721
|
+
if (first !== void 0) this.#path[this.#path.length] = first;
|
|
5722
|
+
if (second !== void 0) this.#path[this.#path.length] = second;
|
|
4857
5723
|
const current = frame.shape;
|
|
4858
5724
|
if (typeof current !== "object" || current === null || !isRecord(current)) {
|
|
4859
5725
|
this.#structure ??= new ContractError("validateShape: every structural child must be a shape", {
|
|
@@ -4880,7 +5746,10 @@ var ShapePass = class ShapePass {
|
|
|
4880
5746
|
this.#children = [];
|
|
4881
5747
|
this.#category = void 0;
|
|
4882
5748
|
this.#raw = 0;
|
|
5749
|
+
this.#defaulted = false;
|
|
5750
|
+
this.#open = false;
|
|
4883
5751
|
const outcome = attempt(() => this.#observe(current, frame.depth));
|
|
5752
|
+
this.#spend(0);
|
|
4884
5753
|
if (isFailure(outcome) || !outcome.value) {
|
|
4885
5754
|
this.#structure ??= new ContractError("validateShape: every node must be a recognized shape", {
|
|
4886
5755
|
code: "structure",
|
|
@@ -4897,7 +5766,7 @@ var ShapePass = class ShapePass {
|
|
|
4897
5766
|
if (descriptor === void 0 || !INTRINSICS.own(descriptor, "value")) return this.#refuse("validateShape: every node must be a recognized shape");
|
|
4898
5767
|
const category = current.category;
|
|
4899
5768
|
if (current.category !== category || descriptor.value !== category) return this.#refuse("validateShape: every node must be a recognized shape");
|
|
4900
|
-
const fields =
|
|
5769
|
+
const fields = typeof category === "string" && INTRINSICS.own(SHAPE_FIELDS, category) ? SHAPE_FIELDS[category] : void 0;
|
|
4901
5770
|
if (fields === void 0) return this.#refuse("validateShape: every node must be a recognized shape");
|
|
4902
5771
|
this.#category = category;
|
|
4903
5772
|
if (!this.#scan(current, fields)) return false;
|
|
@@ -4926,45 +5795,6 @@ var ShapePass = class ShapePass {
|
|
|
4926
5795
|
}
|
|
4927
5796
|
return this.#populate(current);
|
|
4928
5797
|
}
|
|
4929
|
-
#recognize(category) {
|
|
4930
|
-
switch (category) {
|
|
4931
|
-
case "string": return [
|
|
4932
|
-
"min",
|
|
4933
|
-
"max",
|
|
4934
|
-
"pattern",
|
|
4935
|
-
"description"
|
|
4936
|
-
];
|
|
4937
|
-
case "number": return [
|
|
4938
|
-
"integer",
|
|
4939
|
-
"min",
|
|
4940
|
-
"max",
|
|
4941
|
-
"description"
|
|
4942
|
-
];
|
|
4943
|
-
case "boolean":
|
|
4944
|
-
case "null":
|
|
4945
|
-
case "json": return ["description"];
|
|
4946
|
-
case "literal": return ["values", "description"];
|
|
4947
|
-
case "array": return [
|
|
4948
|
-
"items",
|
|
4949
|
-
"min",
|
|
4950
|
-
"max",
|
|
4951
|
-
"description"
|
|
4952
|
-
];
|
|
4953
|
-
case "object": return [
|
|
4954
|
-
"properties",
|
|
4955
|
-
"additionalProperties",
|
|
4956
|
-
"description"
|
|
4957
|
-
];
|
|
4958
|
-
case "union": return [
|
|
4959
|
-
"variants",
|
|
4960
|
-
"mode",
|
|
4961
|
-
"description"
|
|
4962
|
-
];
|
|
4963
|
-
case "optional":
|
|
4964
|
-
case "nullable": return ["inner"];
|
|
4965
|
-
case "raw": return ["schema"];
|
|
4966
|
-
}
|
|
4967
|
-
}
|
|
4968
5798
|
#scan(current, fields) {
|
|
4969
5799
|
for (const fieldIndex of iterateIndices(() => fields.length)) {
|
|
4970
5800
|
const field = fields[fieldIndex];
|
|
@@ -4987,6 +5817,10 @@ var ShapePass = class ShapePass {
|
|
|
4987
5817
|
}
|
|
4988
5818
|
#constrain(current) {
|
|
4989
5819
|
if (current.category !== "optional" && current.category !== "nullable" && current.category !== "raw" && current.description !== void 0 && typeof current.description !== "string") return this.#refuse("validateShape: description must be a string", "description");
|
|
5820
|
+
if (current.category === "optional" && INTRINSICS.own(current, "default")) {
|
|
5821
|
+
if (!holds(() => matchesJSONValue(current.default, new ShapePass.#weakSet(), this.#budget))) return this.#refuse("validateShape: an optional default must be a JSON value", "default");
|
|
5822
|
+
this.#defaulted = true;
|
|
5823
|
+
}
|
|
4990
5824
|
if (current.category === "string") {
|
|
4991
5825
|
if (current.min !== void 0 && typeof current.min !== "number") return this.#refuse("validateShape: string min must be a number", "min");
|
|
4992
5826
|
if (current.max !== void 0 && typeof current.max !== "number") return this.#refuse("validateShape: string max must be a number", "max");
|
|
@@ -5022,7 +5856,7 @@ var ShapePass = class ShapePass {
|
|
|
5022
5856
|
received: INTRINSICS.text(current.max)
|
|
5023
5857
|
}
|
|
5024
5858
|
});
|
|
5025
|
-
if (this.#domain === void 0 && current.min !== void 0 && current.max !== void 0 && current.min > current.max) this.#domain = new ContractError("validateShape: a number shape has min greater than max", {
|
|
5859
|
+
if (this.#domain === void 0 && current.min !== void 0 && current.max !== void 0 && typeof current.min === "number" && typeof current.max === "number" && current.min > current.max) this.#domain = new ContractError("validateShape: a number shape has min greater than max", {
|
|
5026
5860
|
code: "range",
|
|
5027
5861
|
context: {
|
|
5028
5862
|
path: pathOf(this.#path),
|
|
@@ -5041,7 +5875,7 @@ var ShapePass = class ShapePass {
|
|
|
5041
5875
|
}
|
|
5042
5876
|
if (current.category === "array" && current.min !== void 0 && typeof current.min !== "number") return this.#refuse("validateShape: array min must be a number", "min");
|
|
5043
5877
|
if (current.category === "array" && current.max !== void 0 && typeof current.max !== "number") return this.#refuse("validateShape: array max must be a number", "max");
|
|
5044
|
-
if (current.category === "array" && this.#domain === void 0 && current.min !== void 0 && (!INTRINSICS.safe(current.min) || current.min < 0)) this.#domain = new ContractError("validateShape: an array shape min must be a non-negative safe integer", {
|
|
5878
|
+
if (current.category === "array" && this.#domain === void 0 && current.min !== void 0 && (typeof current.min !== "number" || !INTRINSICS.safe(current.min) || current.min < 0)) this.#domain = new ContractError("validateShape: an array shape min must be a non-negative safe integer", {
|
|
5045
5879
|
code: "bound",
|
|
5046
5880
|
context: {
|
|
5047
5881
|
path: pathOf(this.#path),
|
|
@@ -5050,7 +5884,7 @@ var ShapePass = class ShapePass {
|
|
|
5050
5884
|
received: INTRINSICS.text(current.min)
|
|
5051
5885
|
}
|
|
5052
5886
|
});
|
|
5053
|
-
if (current.category === "array" && this.#domain === void 0 && current.max !== void 0 && (!INTRINSICS.safe(current.max) || current.max < 0)) this.#domain = new ContractError("validateShape: an array shape max must be a non-negative safe integer", {
|
|
5887
|
+
if (current.category === "array" && this.#domain === void 0 && current.max !== void 0 && (typeof current.max !== "number" || !INTRINSICS.safe(current.max) || current.max < 0)) this.#domain = new ContractError("validateShape: an array shape max must be a non-negative safe integer", {
|
|
5054
5888
|
code: "bound",
|
|
5055
5889
|
context: {
|
|
5056
5890
|
path: pathOf(this.#path),
|
|
@@ -5059,7 +5893,7 @@ var ShapePass = class ShapePass {
|
|
|
5059
5893
|
received: INTRINSICS.text(current.max)
|
|
5060
5894
|
}
|
|
5061
5895
|
});
|
|
5062
|
-
if (current.category === "array" && this.#domain === void 0 && current.min !== void 0 && current.max !== void 0 && current.min > current.max) this.#domain = new ContractError("validateShape: an array shape has min greater than max", {
|
|
5896
|
+
if (current.category === "array" && this.#domain === void 0 && current.min !== void 0 && current.max !== void 0 && typeof current.min === "number" && typeof current.max === "number" && current.min > current.max) this.#domain = new ContractError("validateShape: an array shape has min greater than max", {
|
|
5063
5897
|
code: "range",
|
|
5064
5898
|
context: {
|
|
5065
5899
|
path: pathOf(this.#path),
|
|
@@ -5081,7 +5915,7 @@ var ShapePass = class ShapePass {
|
|
|
5081
5915
|
});
|
|
5082
5916
|
}
|
|
5083
5917
|
#restrict(current, source = "", flags = "") {
|
|
5084
|
-
if (this.#domain === void 0 && current.min !== void 0 && (!INTRINSICS.safe(current.min) || current.min < 0)) this.#domain = new ContractError("validateShape: a string shape min must be a non-negative safe integer", {
|
|
5918
|
+
if (this.#domain === void 0 && current.min !== void 0 && (typeof current.min !== "number" || !INTRINSICS.safe(current.min) || current.min < 0)) this.#domain = new ContractError("validateShape: a string shape min must be a non-negative safe integer", {
|
|
5085
5919
|
code: "bound",
|
|
5086
5920
|
context: {
|
|
5087
5921
|
path: pathOf(this.#path),
|
|
@@ -5090,7 +5924,7 @@ var ShapePass = class ShapePass {
|
|
|
5090
5924
|
received: INTRINSICS.text(current.min)
|
|
5091
5925
|
}
|
|
5092
5926
|
});
|
|
5093
|
-
if (this.#domain === void 0 && current.max !== void 0 && (!INTRINSICS.safe(current.max) || current.max < 0)) this.#domain = new ContractError("validateShape: a string shape max must be a non-negative safe integer", {
|
|
5927
|
+
if (this.#domain === void 0 && current.max !== void 0 && (typeof current.max !== "number" || !INTRINSICS.safe(current.max) || current.max < 0)) this.#domain = new ContractError("validateShape: a string shape max must be a non-negative safe integer", {
|
|
5094
5928
|
code: "bound",
|
|
5095
5929
|
context: {
|
|
5096
5930
|
path: pathOf(this.#path),
|
|
@@ -5107,7 +5941,7 @@ var ShapePass = class ShapePass {
|
|
|
5107
5941
|
received: `/${source}/${flags}`
|
|
5108
5942
|
}
|
|
5109
5943
|
});
|
|
5110
|
-
if (this.#domain === void 0 && current.min !== void 0 && current.max !== void 0 && current.min > current.max) this.#domain = new ContractError("validateShape: a string shape has min greater than max", {
|
|
5944
|
+
if (this.#domain === void 0 && current.min !== void 0 && current.max !== void 0 && typeof current.min === "number" && typeof current.max === "number" && current.min > current.max) this.#domain = new ContractError("validateShape: a string shape has min greater than max", {
|
|
5111
5945
|
code: "range",
|
|
5112
5946
|
context: {
|
|
5113
5947
|
path: pathOf(this.#path),
|
|
@@ -5116,6 +5950,7 @@ var ShapePass = class ShapePass {
|
|
|
5116
5950
|
});
|
|
5117
5951
|
}
|
|
5118
5952
|
#inspect(source) {
|
|
5953
|
+
if (this.#structure !== void 0) return true;
|
|
5119
5954
|
if (!isRecord(source)) return this.#refuse("validateShape: raw schema must be a plain record", "schema");
|
|
5120
5955
|
const active = new ShapePass.#weakSet();
|
|
5121
5956
|
const stack = [{
|
|
@@ -5130,24 +5965,27 @@ var ShapePass = class ShapePass {
|
|
|
5130
5965
|
this.#settleSchema(frame.schema, frame.nested);
|
|
5131
5966
|
continue;
|
|
5132
5967
|
}
|
|
5968
|
+
const first = INTRINSICS.own(frame, "first") ? frame.first : void 0;
|
|
5969
|
+
const second = INTRINSICS.own(frame, "second") ? frame.second : void 0;
|
|
5133
5970
|
const schema = frame.schema;
|
|
5134
|
-
if (!isRecord(schema)) return this.#
|
|
5135
|
-
if (matchesVisited(active, schema)) return this.#
|
|
5971
|
+
if (!isRecord(schema)) return this.#refuseSchema("validateShape: every raw schema child must be a plain record", stack, first, second, void 0);
|
|
5972
|
+
if (matchesVisited(active, schema)) return this.#refuseSchema("validateShape: a raw schema may not contain a cycle", stack, first, second, void 0);
|
|
5136
5973
|
if (INTRINSICS.reflect.apply(INTRINSICS.recall, this.#schemas, [schema]) !== void 0) continue;
|
|
5137
5974
|
admitVisited(active, schema);
|
|
5138
5975
|
const keyList = INTRINSICS.keys(schema);
|
|
5139
5976
|
for (const keyIndex of iterateIndices(() => keyList.length)) {
|
|
5140
5977
|
const key = keyList[keyIndex];
|
|
5141
5978
|
if (key === void 0) continue;
|
|
5142
|
-
if (key !== "type" && key !== "description" && key !== "enum" && key !== "minLength" && key !== "maxLength" && key !== "pattern" && key !== "format" && key !== "minimum" && key !== "maximum" && key !== "minItems" && key !== "maxItems" && key !== "items" && key !== "properties" && key !== "required" && key !== "additionalProperties" && key !== "anyOf" && key !== "oneOf") return this.#
|
|
5979
|
+
if (key !== "type" && key !== "description" && key !== "default" && key !== "enum" && key !== "minLength" && key !== "maxLength" && key !== "pattern" && key !== "format" && key !== "minimum" && key !== "maximum" && key !== "minItems" && key !== "maxItems" && key !== "items" && key !== "properties" && key !== "required" && key !== "additionalProperties" && key !== "anyOf" && key !== "oneOf") return this.#refuseSchema("validateShape: raw schema contains an unsupported keyword", stack, first, second, key);
|
|
5143
5980
|
}
|
|
5144
|
-
const category = schema.type;
|
|
5145
|
-
if (category !== void 0 && category !== "null" && category !== "boolean" && category !== "object" && category !== "array" && category !== "number" && category !== "integer" && category !== "string") return this.#
|
|
5146
|
-
if (schema.description !== void 0 && typeof schema.description !== "string") return this.#
|
|
5147
|
-
if (schema
|
|
5148
|
-
if (schema.
|
|
5149
|
-
|
|
5150
|
-
if (
|
|
5981
|
+
const category = INTRINSICS.own(schema, "type") ? schema.type : void 0;
|
|
5982
|
+
if (category !== void 0 && category !== "null" && category !== "boolean" && category !== "object" && category !== "array" && category !== "number" && category !== "integer" && category !== "string") return this.#refuseSchema("validateShape: raw schema type is outside the supported vocabulary", stack, first, second, "type");
|
|
5983
|
+
if (INTRINSICS.own(schema, "description") && schema.description !== void 0 && typeof schema.description !== "string") return this.#refuseSchema("validateShape: raw schema description must be a string", stack, first, second, "description");
|
|
5984
|
+
if (INTRINSICS.own(schema, "default") && !isJSONValue(schema.default)) return this.#refuseSchema("validateShape: raw schema default must be a JSON value", stack, first, second, "default");
|
|
5985
|
+
if (INTRINSICS.own(schema, "format") && schema.format !== void 0 && typeof schema.format !== "string") return this.#refuseSchema("validateShape: raw schema format must be a string", stack, first, second, "format");
|
|
5986
|
+
if (INTRINSICS.own(schema, "pattern") && schema.pattern !== void 0) {
|
|
5987
|
+
if (typeof schema.pattern !== "string") return this.#refuseSchema("validateShape: raw schema pattern must be a string", stack, first, second, "pattern");
|
|
5988
|
+
if (isFailure(attempt(() => INTRINSICS.reflect.apply(INTRINSICS.pattern, void 0, [schema.pattern])))) return this.#refuseSchema("validateShape: raw schema pattern must be valid", stack, first, second, "pattern");
|
|
5151
5989
|
}
|
|
5152
5990
|
const lengthList = [
|
|
5153
5991
|
"minLength",
|
|
@@ -5158,77 +5996,95 @@ var ShapePass = class ShapePass {
|
|
|
5158
5996
|
for (const lengthIndex of iterateIndices(() => lengthList.length)) {
|
|
5159
5997
|
const key = lengthList[lengthIndex];
|
|
5160
5998
|
if (key === void 0) continue;
|
|
5161
|
-
const value = schema[key];
|
|
5162
|
-
if (value !== void 0 && (!INTRINSICS.safe(value) || INTRINSICS.numeric(value) < 0)) return this.#
|
|
5999
|
+
const value = INTRINSICS.own(schema, key) ? schema[key] : void 0;
|
|
6000
|
+
if (value !== void 0 && (!INTRINSICS.safe(value) || INTRINSICS.numeric(value) < 0)) return this.#refuseSchema("validateShape: raw schema length bounds must be non-negative safe integers", stack, first, second, key);
|
|
5163
6001
|
}
|
|
5164
6002
|
const rangeList = ["minimum", "maximum"];
|
|
5165
6003
|
for (const rangeIndex of iterateIndices(() => rangeList.length)) {
|
|
5166
6004
|
const key = rangeList[rangeIndex];
|
|
5167
6005
|
if (key === void 0) continue;
|
|
5168
|
-
const value = schema[key];
|
|
5169
|
-
if (value !== void 0 && (typeof value !== "number" || !INTRINSICS.finite(value))) return this.#
|
|
6006
|
+
const value = INTRINSICS.own(schema, key) ? schema[key] : void 0;
|
|
6007
|
+
if (value !== void 0 && (typeof value !== "number" || !INTRINSICS.finite(value))) return this.#refuseSchema("validateShape: raw schema numeric bounds must be finite numbers", stack, first, second, key);
|
|
5170
6008
|
}
|
|
5171
|
-
const population = schema.enum;
|
|
6009
|
+
const population = INTRINSICS.own(schema, "enum") ? schema.enum : void 0;
|
|
5172
6010
|
if (population !== void 0) {
|
|
5173
|
-
if (!INTRINSICS.array(population)) return this.#
|
|
6011
|
+
if (!INTRINSICS.array(population)) return this.#refuseSchema("validateShape: raw schema enum must be a non-empty array", stack, first, second, "enum");
|
|
5174
6012
|
const snapshot = readArrayEntries(population);
|
|
5175
|
-
if (isFailure(snapshot) || snapshot.value.entries.length === 0) return this.#
|
|
5176
|
-
if (!snapshot.value.dense) return this.#
|
|
6013
|
+
if (isFailure(snapshot) || snapshot.value.entries.length === 0) return this.#refuseSchema("validateShape: raw schema enum must be a non-empty array", stack, first, second, "enum");
|
|
6014
|
+
if (!snapshot.value.dense) return this.#refuseSchema("validateShape: raw schema enum must be dense", stack, first, second, "enum");
|
|
5177
6015
|
const values = collectMembers([]);
|
|
5178
6016
|
for (const valueIndex of iterateIndices(() => snapshot.value.entries.length)) {
|
|
5179
6017
|
const value = snapshot.value.entries[valueIndex];
|
|
5180
|
-
if (!isLiteralValue(value) || typeof value === "number" && !INTRINSICS.finite(value) || matchesMember(values, value)) return this.#
|
|
6018
|
+
if (!isLiteralValue(value) || typeof value === "number" && !INTRINSICS.finite(value) || matchesMember(values, value)) return this.#refuseSchema("validateShape: raw schema enum values must be finite unique primitives", stack, first, second, "enum", INTRINSICS.text(valueIndex));
|
|
5181
6019
|
admitMember(values, value);
|
|
5182
6020
|
}
|
|
5183
6021
|
}
|
|
5184
|
-
const names = schema.required;
|
|
6022
|
+
const names = INTRINSICS.own(schema, "required") ? schema.required : void 0;
|
|
5185
6023
|
if (names !== void 0) {
|
|
5186
|
-
if (!INTRINSICS.array(names)) return this.#
|
|
6024
|
+
if (!INTRINSICS.array(names)) return this.#refuseSchema("validateShape: raw schema required must be an array", stack, first, second, "required");
|
|
5187
6025
|
const snapshot = readArrayEntries(names);
|
|
5188
|
-
if (isFailure(snapshot)) return this.#
|
|
5189
|
-
if (!snapshot.value.dense) return this.#
|
|
6026
|
+
if (isFailure(snapshot)) return this.#refuseSchema("validateShape: raw schema required must be an array", stack, first, second, "required");
|
|
6027
|
+
if (!snapshot.value.dense) return this.#refuseSchema("validateShape: raw schema required must be dense", stack, first, second, "required");
|
|
5190
6028
|
const required = collectMembers([]);
|
|
5191
6029
|
for (const valueIndex of iterateIndices(() => snapshot.value.entries.length)) {
|
|
5192
6030
|
const value = snapshot.value.entries[valueIndex];
|
|
5193
6031
|
if (value === void 0) continue;
|
|
5194
|
-
if (typeof value !== "string" || matchesMember(required, value)) return this.#
|
|
6032
|
+
if (typeof value !== "string" || matchesMember(required, value)) return this.#refuseSchema("validateShape: raw schema required values must be unique strings", stack, first, second, "required", INTRINSICS.text(valueIndex));
|
|
5195
6033
|
admitMember(required, value);
|
|
5196
6034
|
}
|
|
5197
6035
|
}
|
|
5198
6036
|
const nested = [];
|
|
5199
|
-
|
|
5200
|
-
if (schema.
|
|
5201
|
-
|
|
6037
|
+
const edges = [];
|
|
6038
|
+
if (INTRINSICS.own(schema, "items") && schema.items !== void 0) {
|
|
6039
|
+
edges[nested.length] = ["items"];
|
|
6040
|
+
nested[nested.length] = schema.items;
|
|
6041
|
+
}
|
|
6042
|
+
if (INTRINSICS.own(schema, "properties") && schema.properties !== void 0) {
|
|
6043
|
+
if (!isRecord(schema.properties)) return this.#refuseSchema("validateShape: raw schema properties must be a plain record", stack, first, second, "properties");
|
|
5202
6044
|
const propertyList = INTRINSICS.keys(schema.properties);
|
|
5203
6045
|
for (const propertyIndex of iterateIndices(() => propertyList.length)) {
|
|
5204
6046
|
const key = propertyList[propertyIndex];
|
|
5205
6047
|
if (key === void 0) continue;
|
|
5206
|
-
|
|
6048
|
+
edges[nested.length] = ["properties", key];
|
|
6049
|
+
nested[nested.length] = INTRINSICS.own(schema.properties, key) ? schema.properties[key] : void 0;
|
|
5207
6050
|
}
|
|
5208
6051
|
}
|
|
5209
|
-
if (schema.additionalProperties !== void 0 && schema.additionalProperties !== true && schema.additionalProperties !== false)
|
|
6052
|
+
if (INTRINSICS.own(schema, "additionalProperties") && schema.additionalProperties !== void 0 && schema.additionalProperties !== true && schema.additionalProperties !== false) {
|
|
6053
|
+
edges[nested.length] = ["additionalProperties"];
|
|
6054
|
+
nested[nested.length] = schema.additionalProperties;
|
|
6055
|
+
}
|
|
5210
6056
|
const unionList = ["anyOf", "oneOf"];
|
|
5211
6057
|
for (const unionIndex of iterateIndices(() => unionList.length)) {
|
|
5212
6058
|
const key = unionList[unionIndex];
|
|
5213
6059
|
if (key === void 0) continue;
|
|
5214
|
-
const variants = schema[key];
|
|
6060
|
+
const variants = INTRINSICS.own(schema, key) ? schema[key] : void 0;
|
|
5215
6061
|
if (variants === void 0) continue;
|
|
5216
|
-
if (!INTRINSICS.array(variants)) return this.#
|
|
6062
|
+
if (!INTRINSICS.array(variants)) return this.#refuseSchema("validateShape: raw schema unions must be non-empty arrays", stack, first, second, key);
|
|
5217
6063
|
const snapshot = readArrayEntries(variants);
|
|
5218
|
-
if (isFailure(snapshot) || snapshot.value.entries.length === 0) return this.#
|
|
5219
|
-
if (!snapshot.value.dense) return this.#
|
|
5220
|
-
for (const variantIndex of iterateIndices(() => snapshot.value.entries.length))
|
|
6064
|
+
if (isFailure(snapshot) || snapshot.value.entries.length === 0) return this.#refuseSchema("validateShape: raw schema unions must be non-empty arrays", stack, first, second, key);
|
|
6065
|
+
if (!snapshot.value.dense) return this.#refuseSchema("validateShape: raw schema unions must be dense arrays", stack, first, second, key);
|
|
6066
|
+
for (const variantIndex of iterateIndices(() => snapshot.value.entries.length)) {
|
|
6067
|
+
edges[nested.length] = [key, INTRINSICS.text(variantIndex)];
|
|
6068
|
+
nested[nested.length] = snapshot.value.entries[variantIndex];
|
|
6069
|
+
}
|
|
5221
6070
|
}
|
|
5222
6071
|
stack[stack.length] = {
|
|
5223
6072
|
operation: "exit",
|
|
5224
6073
|
schema,
|
|
5225
|
-
nested
|
|
6074
|
+
nested,
|
|
6075
|
+
...first === void 0 ? {} : { first },
|
|
6076
|
+
...second === void 0 ? {} : { second }
|
|
5226
6077
|
};
|
|
5227
6078
|
for (const offset of iterateIndices(() => nested.length)) {
|
|
5228
6079
|
const index = nested.length - 1 - offset;
|
|
6080
|
+
const childFirst = edges[index]?.[0];
|
|
6081
|
+
const edge = edges[index];
|
|
6082
|
+
const childSecond = edge !== void 0 && INTRINSICS.own(edge, 1) ? edge[1] : void 0;
|
|
5229
6083
|
stack[stack.length] = {
|
|
5230
6084
|
operation: "enter",
|
|
5231
|
-
schema: nested[index]
|
|
6085
|
+
schema: nested[index],
|
|
6086
|
+
...childFirst === void 0 ? {} : { first: childFirst },
|
|
6087
|
+
...childSecond === void 0 ? {} : { second: childSecond }
|
|
5232
6088
|
};
|
|
5233
6089
|
}
|
|
5234
6090
|
}
|
|
@@ -5245,6 +6101,7 @@ var ShapePass = class ShapePass {
|
|
|
5245
6101
|
#populate(current) {
|
|
5246
6102
|
switch (current.category) {
|
|
5247
6103
|
case "array":
|
|
6104
|
+
this.#spend(1);
|
|
5248
6105
|
this.#children[this.#children.length] = {
|
|
5249
6106
|
shape: current.items,
|
|
5250
6107
|
first: "items",
|
|
@@ -5258,6 +6115,7 @@ var ShapePass = class ShapePass {
|
|
|
5258
6115
|
for (const keyIndex of iterateIndices(() => keys.length)) {
|
|
5259
6116
|
const key = keys[keyIndex];
|
|
5260
6117
|
if (key === void 0) continue;
|
|
6118
|
+
this.#spend(1);
|
|
5261
6119
|
const descriptorOutcome = attempt(() => INTRINSICS.describe(properties, key));
|
|
5262
6120
|
if (isFailure(descriptorOutcome)) return this.#refuse("validateShape: every node must be a recognized shape", "properties", key);
|
|
5263
6121
|
const descriptor = descriptorOutcome.value;
|
|
@@ -5270,10 +6128,16 @@ var ShapePass = class ShapePass {
|
|
|
5270
6128
|
};
|
|
5271
6129
|
continue;
|
|
5272
6130
|
}
|
|
5273
|
-
const childOutcome = attempt(() =>
|
|
6131
|
+
const childOutcome = attempt(() => {
|
|
6132
|
+
const population = current.properties;
|
|
6133
|
+
return isRecord(population) ? population[key] : void 0;
|
|
6134
|
+
});
|
|
5274
6135
|
if (isFailure(childOutcome)) return this.#refuse("validateShape: every node must be a recognized shape", "properties", key);
|
|
5275
6136
|
const child = childOutcome.value;
|
|
5276
|
-
const stable = attempt(() =>
|
|
6137
|
+
const stable = attempt(() => {
|
|
6138
|
+
const population = current.properties;
|
|
6139
|
+
return isRecord(population) && INTRINSICS.same(population[key], child) && INTRINSICS.same(descriptor.value, child);
|
|
6140
|
+
});
|
|
5277
6141
|
if (isFailure(stable)) return this.#refuse("validateShape: every node must be a recognized shape", "properties", key);
|
|
5278
6142
|
if (!stable.value) {
|
|
5279
6143
|
this.#children[this.#children.length] = {
|
|
@@ -5292,11 +6156,15 @@ var ShapePass = class ShapePass {
|
|
|
5292
6156
|
};
|
|
5293
6157
|
}
|
|
5294
6158
|
const extra = current.additionalProperties;
|
|
5295
|
-
|
|
5296
|
-
|
|
5297
|
-
|
|
5298
|
-
|
|
5299
|
-
|
|
6159
|
+
this.#open = extra !== void 0 && extra !== false;
|
|
6160
|
+
if (extra !== void 0 && extra !== true && extra !== false) {
|
|
6161
|
+
this.#spend(1);
|
|
6162
|
+
this.#children[this.#children.length] = {
|
|
6163
|
+
shape: extra,
|
|
6164
|
+
first: "additionalProperties",
|
|
6165
|
+
optional: false
|
|
6166
|
+
};
|
|
6167
|
+
}
|
|
5300
6168
|
break;
|
|
5301
6169
|
}
|
|
5302
6170
|
case "union": {
|
|
@@ -5315,6 +6183,7 @@ var ShapePass = class ShapePass {
|
|
|
5315
6183
|
});
|
|
5316
6184
|
for (const index of iterateIndices(() => length)) {
|
|
5317
6185
|
const key = INTRINSICS.text(index);
|
|
6186
|
+
this.#spend(1);
|
|
5318
6187
|
const descriptorOutcome = attempt(() => INTRINSICS.describe(current.variants, key));
|
|
5319
6188
|
if (isFailure(descriptorOutcome)) return this.#refuse("validateShape: every node must be a recognized shape", "variants", key);
|
|
5320
6189
|
const descriptor = descriptorOutcome.value;
|
|
@@ -5328,7 +6197,10 @@ var ShapePass = class ShapePass {
|
|
|
5328
6197
|
continue;
|
|
5329
6198
|
}
|
|
5330
6199
|
const variant = variants[index];
|
|
5331
|
-
const stable = attempt(() =>
|
|
6200
|
+
const stable = attempt(() => {
|
|
6201
|
+
const population = current.variants;
|
|
6202
|
+
return INTRINSICS.array(population) && INTRINSICS.same(population[index], variant) && INTRINSICS.same(descriptor.value, variant);
|
|
6203
|
+
});
|
|
5332
6204
|
if (isFailure(stable)) return this.#refuse("validateShape: every node must be a recognized shape", "variants", key);
|
|
5333
6205
|
if (!stable.value) {
|
|
5334
6206
|
this.#children[this.#children.length] = {
|
|
@@ -5370,7 +6242,10 @@ var ShapePass = class ShapePass {
|
|
|
5370
6242
|
const descriptor = descriptorOutcome.value;
|
|
5371
6243
|
if (descriptor === void 0 || !INTRINSICS.own(descriptor, "value")) return this.#refuse("validateShape: values must be a dense data array", "values", key);
|
|
5372
6244
|
const value = literals[index];
|
|
5373
|
-
const stable = attempt(() =>
|
|
6245
|
+
const stable = attempt(() => {
|
|
6246
|
+
const population = current.values;
|
|
6247
|
+
return INTRINSICS.array(population) && INTRINSICS.same(population[index], value) && INTRINSICS.same(descriptor.value, value);
|
|
6248
|
+
});
|
|
5374
6249
|
if (isFailure(stable)) return this.#refuse("validateShape: every node must be a recognized shape", "values", key);
|
|
5375
6250
|
if (!stable.value) return this.#refuse("validateShape: values must be a stable data array", "values", key);
|
|
5376
6251
|
if (!isLiteralValue(value)) return this.#refuse("validateShape: every literal value must be a string, number, or boolean", "values", key);
|
|
@@ -5388,14 +6263,28 @@ var ShapePass = class ShapePass {
|
|
|
5388
6263
|
break;
|
|
5389
6264
|
}
|
|
5390
6265
|
case "optional":
|
|
5391
|
-
case "nullable":
|
|
5392
|
-
|
|
5393
|
-
|
|
5394
|
-
|
|
5395
|
-
|
|
6266
|
+
case "nullable":
|
|
6267
|
+
this.#spend(1);
|
|
6268
|
+
this.#children[this.#children.length] = {
|
|
6269
|
+
shape: current.inner,
|
|
6270
|
+
first: "inner",
|
|
6271
|
+
optional: false
|
|
6272
|
+
};
|
|
5396
6273
|
}
|
|
5397
6274
|
return true;
|
|
5398
6275
|
}
|
|
6276
|
+
#spend(count) {
|
|
6277
|
+
const budget = this.#budget;
|
|
6278
|
+
if (budget === void 0) return;
|
|
6279
|
+
budget.left -= count;
|
|
6280
|
+
if (budget.left < 0) throw new ContractError(`validateShape: capture exceeds the node limit ${CLONE_NODE_LIMIT}`, {
|
|
6281
|
+
code: "clone",
|
|
6282
|
+
context: {
|
|
6283
|
+
path: pathOf(this.#path),
|
|
6284
|
+
limit: CLONE_NODE_LIMIT
|
|
6285
|
+
}
|
|
6286
|
+
});
|
|
6287
|
+
}
|
|
5399
6288
|
#schedule(current, depth, segments) {
|
|
5400
6289
|
admitVisited(this.#active, current);
|
|
5401
6290
|
const children = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(this.#children), [(child) => child !== void 0]);
|
|
@@ -5414,7 +6303,7 @@ var ShapePass = class ShapePass {
|
|
|
5414
6303
|
depth: depth + 1,
|
|
5415
6304
|
optional: child.optional,
|
|
5416
6305
|
first: child.first,
|
|
5417
|
-
...child.second
|
|
6306
|
+
...INTRINSICS.own(child, "second") && child.second !== void 0 ? { second: child.second } : {}
|
|
5418
6307
|
};
|
|
5419
6308
|
}
|
|
5420
6309
|
return captured;
|
|
@@ -5425,25 +6314,27 @@ var ShapePass = class ShapePass {
|
|
|
5425
6314
|
shape,
|
|
5426
6315
|
category: this.#category,
|
|
5427
6316
|
children,
|
|
5428
|
-
raw: this.#raw
|
|
6317
|
+
raw: this.#raw,
|
|
6318
|
+
defaulted: this.#defaulted,
|
|
6319
|
+
open: this.#open
|
|
5429
6320
|
};
|
|
5430
6321
|
INTRINSICS.reflect.apply(INTRINSICS.retain, this.#index, [shape, index]);
|
|
5431
6322
|
return index;
|
|
5432
6323
|
}
|
|
5433
6324
|
#locate(shape) {
|
|
5434
|
-
if (shape ===
|
|
6325
|
+
if (typeof shape !== "object" || shape === null) return void 0;
|
|
5435
6326
|
return INTRINSICS.reflect.apply(INTRINSICS.recall, this.#index, [shape]);
|
|
5436
6327
|
}
|
|
5437
6328
|
#measure() {
|
|
6329
|
+
if (this.#cycle !== void 0) {
|
|
6330
|
+
this.#finish();
|
|
6331
|
+
return;
|
|
6332
|
+
}
|
|
5438
6333
|
for (const index of iterateIndices(() => this.#captures.length)) {
|
|
5439
6334
|
this.#height[index] = 0;
|
|
5440
6335
|
this.#reach[index] = 0;
|
|
5441
6336
|
this.#counts[index] = 1;
|
|
5442
6337
|
}
|
|
5443
|
-
if (this.#cycle !== void 0) {
|
|
5444
|
-
this.#trace();
|
|
5445
|
-
return;
|
|
5446
|
-
}
|
|
5447
6338
|
for (const step of iterateIndices(() => this.#post.length)) {
|
|
5448
6339
|
const index = this.#post[step];
|
|
5449
6340
|
if (index === void 0) continue;
|
|
@@ -5481,7 +6372,7 @@ var ShapePass = class ShapePass {
|
|
|
5481
6372
|
this.#via[located] = {
|
|
5482
6373
|
parent: index,
|
|
5483
6374
|
first: child.first,
|
|
5484
|
-
...child.second
|
|
6375
|
+
...INTRINSICS.own(child, "second") && child.second !== void 0 ? { second: child.second } : {}
|
|
5485
6376
|
};
|
|
5486
6377
|
}
|
|
5487
6378
|
}
|
|
@@ -5494,11 +6385,52 @@ var ShapePass = class ShapePass {
|
|
|
5494
6385
|
context: { path: pathOf(this.#ascend(index), "schema") }
|
|
5495
6386
|
});
|
|
5496
6387
|
}
|
|
6388
|
+
this.#placeDefaults();
|
|
6389
|
+
}
|
|
6390
|
+
#placeDefaults() {
|
|
6391
|
+
if (!INTRINSICS.reflect.apply(INTRINSICS.some, this.#captures, [(capture) => capture.defaulted])) return;
|
|
6392
|
+
for (const offset of iterateIndices(() => this.#post.length)) {
|
|
6393
|
+
const index = this.#post[this.#post.length - 1 - offset];
|
|
6394
|
+
if (index === void 0) continue;
|
|
6395
|
+
const capture = this.#captures[index];
|
|
6396
|
+
if (capture === void 0) continue;
|
|
6397
|
+
const enclosed = capture.category === "union" || INTRINSICS.own(this.#within, index) && this.#within[index] !== void 0;
|
|
6398
|
+
for (const edge of iterateIndices(() => capture.children.length)) {
|
|
6399
|
+
const child = capture.children[edge];
|
|
6400
|
+
if (child === void 0) continue;
|
|
6401
|
+
const located = this.#locate(child.shape);
|
|
6402
|
+
if (located === void 0) continue;
|
|
6403
|
+
if (enclosed && (!INTRINSICS.own(this.#within, located) || this.#within[located] === void 0)) this.#within[located] = {
|
|
6404
|
+
parent: index,
|
|
6405
|
+
first: child.first,
|
|
6406
|
+
...INTRINSICS.own(child, "second") && child.second !== void 0 ? { second: child.second } : {}
|
|
6407
|
+
};
|
|
6408
|
+
if (this.#captures[located]?.defaulted !== true) continue;
|
|
6409
|
+
if (enclosed) this.#domain ??= new ContractError("validateShape: a default may not sit under a union, whose parser can return a valid value without filling it; move the default outside the union or remove it", {
|
|
6410
|
+
code: "placement",
|
|
6411
|
+
context: {
|
|
6412
|
+
path: pathOf(this.#route(index), child.first, INTRINSICS.own(child, "second") ? child.second : void 0),
|
|
6413
|
+
shape: "optional"
|
|
6414
|
+
}
|
|
6415
|
+
});
|
|
6416
|
+
if (capture.open) this.#domain ??= new ContractError("validateShape: a default may not sit on a property of an open object, where a misspelled key would fill it unreported; close the object or remove the default", {
|
|
6417
|
+
code: "placement",
|
|
6418
|
+
context: {
|
|
6419
|
+
path: pathOf(this.#ascend(index), child.first, INTRINSICS.own(child, "second") ? child.second : void 0),
|
|
6420
|
+
shape: "optional"
|
|
6421
|
+
}
|
|
6422
|
+
});
|
|
6423
|
+
}
|
|
6424
|
+
}
|
|
6425
|
+
}
|
|
6426
|
+
#route(index) {
|
|
6427
|
+
const edge = INTRINSICS.own(this.#within, index) ? this.#within[index] : void 0;
|
|
6428
|
+
return edge === void 0 ? this.#ascend(index) : pathOf(this.#route(edge.parent), edge.first, INTRINSICS.own(edge, "second") ? edge.second : void 0);
|
|
5497
6429
|
}
|
|
5498
6430
|
#ascend(index) {
|
|
5499
6431
|
if (index === 0) return [];
|
|
5500
|
-
const edge = this.#via[index];
|
|
5501
|
-
return edge === void 0 ? [] : pathOf(this.#ascend(edge.parent), edge.first, edge.second);
|
|
6432
|
+
const edge = INTRINSICS.own(this.#via, index) ? this.#via[index] : void 0;
|
|
6433
|
+
return edge === void 0 ? [] : pathOf(this.#ascend(edge.parent), edge.first, INTRINSICS.own(edge, "second") ? edge.second : void 0);
|
|
5502
6434
|
}
|
|
5503
6435
|
#witness(index, depth, path) {
|
|
5504
6436
|
if (depth <= 512) {
|
|
@@ -5509,7 +6441,7 @@ var ShapePass = class ShapePass {
|
|
|
5509
6441
|
const reached = located === void 0 ? 0 : this.#height[located] ?? 0;
|
|
5510
6442
|
return depth + 1 + reached > 512;
|
|
5511
6443
|
}])];
|
|
5512
|
-
if (chosen !== void 0) return this.#witness(this.#locate(chosen.shape), depth + 1, pathOf(path, chosen.first, chosen.second));
|
|
6444
|
+
if (chosen !== void 0) return this.#witness(this.#locate(chosen.shape), depth + 1, pathOf(path, chosen.first, INTRINSICS.own(chosen, "second") ? chosen.second : void 0));
|
|
5513
6445
|
}
|
|
5514
6446
|
throw new ContractError("validateShape: a shape exceeds the compilation depth limit", {
|
|
5515
6447
|
code: "depth",
|
|
@@ -5519,86 +6451,24 @@ var ShapePass = class ShapePass {
|
|
|
5519
6451
|
}
|
|
5520
6452
|
});
|
|
5521
6453
|
}
|
|
5522
|
-
#trace() {
|
|
5523
|
-
const settled = [];
|
|
5524
|
-
const order = [];
|
|
5525
|
-
const active = new ShapePass.#weakSet();
|
|
5526
|
-
const stack = [{
|
|
5527
|
-
operation: "enter",
|
|
5528
|
-
index: 0,
|
|
5529
|
-
depth: 0
|
|
5530
|
-
}];
|
|
5531
|
-
while (stack.length > 0) {
|
|
5532
|
-
const frame = stack.pop();
|
|
5533
|
-
if (frame === void 0) continue;
|
|
5534
|
-
if (frame.operation === "exit") {
|
|
5535
|
-
const capture = this.#captures[frame.index];
|
|
5536
|
-
if (capture !== void 0) omitVisited(active, capture.shape);
|
|
5537
|
-
if (this.#oldest >= (order[frame.index] ?? 0) && (settled[frame.index] ?? -1) < frame.depth) settled[frame.index] = frame.depth;
|
|
5538
|
-
if (frame.outer < this.#oldest) this.#oldest = frame.outer;
|
|
5539
|
-
this.#trail.length -= frame.segments;
|
|
5540
|
-
continue;
|
|
5541
|
-
}
|
|
5542
|
-
const segments = (frame.first === void 0 ? 0 : 1) + (frame.second === void 0 ? 0 : 1);
|
|
5543
|
-
if (frame.first !== void 0) this.#trail[this.#trail.length] = frame.first;
|
|
5544
|
-
if (frame.second !== void 0) this.#trail[this.#trail.length] = frame.second;
|
|
5545
|
-
if (frame.depth > 512) throw new ContractError("validateShape: a shape exceeds the compilation depth limit", {
|
|
5546
|
-
code: "depth",
|
|
5547
|
-
context: {
|
|
5548
|
-
path: pathOf(this.#trail),
|
|
5549
|
-
limit: 512
|
|
5550
|
-
}
|
|
5551
|
-
});
|
|
5552
|
-
const index = frame.index;
|
|
5553
|
-
const capture = index === void 0 ? void 0 : this.#captures[index];
|
|
5554
|
-
if (index === void 0 || capture === void 0) {
|
|
5555
|
-
this.#trail.length -= segments;
|
|
5556
|
-
continue;
|
|
5557
|
-
}
|
|
5558
|
-
if (matchesVisited(active, capture.shape)) {
|
|
5559
|
-
const blocker = order[index] ?? 0;
|
|
5560
|
-
if (blocker < this.#oldest) this.#oldest = blocker;
|
|
5561
|
-
this.#trail.length -= segments;
|
|
5562
|
-
continue;
|
|
5563
|
-
}
|
|
5564
|
-
const recorded = settled[index];
|
|
5565
|
-
if (recorded !== void 0 && frame.depth <= recorded) {
|
|
5566
|
-
this.#trail.length -= segments;
|
|
5567
|
-
continue;
|
|
5568
|
-
}
|
|
5569
|
-
admitVisited(active, capture.shape);
|
|
5570
|
-
order[index] = this.#clock;
|
|
5571
|
-
this.#clock += 1;
|
|
5572
|
-
stack[stack.length] = {
|
|
5573
|
-
operation: "exit",
|
|
5574
|
-
index,
|
|
5575
|
-
depth: frame.depth,
|
|
5576
|
-
segments,
|
|
5577
|
-
outer: this.#oldest
|
|
5578
|
-
};
|
|
5579
|
-
this.#oldest = this.#clock;
|
|
5580
|
-
for (const offset of iterateIndices(() => capture.children.length)) {
|
|
5581
|
-
const edge = capture.children.length - 1 - offset;
|
|
5582
|
-
const child = capture.children[edge];
|
|
5583
|
-
if (child === void 0) continue;
|
|
5584
|
-
stack[stack.length] = {
|
|
5585
|
-
operation: "enter",
|
|
5586
|
-
index: this.#locate(child.shape),
|
|
5587
|
-
depth: frame.depth + 1,
|
|
5588
|
-
first: child.first,
|
|
5589
|
-
...child.second === void 0 ? {} : { second: child.second }
|
|
5590
|
-
};
|
|
5591
|
-
}
|
|
5592
|
-
}
|
|
5593
|
-
}
|
|
5594
6454
|
#finish() {
|
|
5595
6455
|
if (this.#structure !== void 0) throw this.#structure;
|
|
5596
6456
|
if (this.#cycle !== void 0) throw this.#cycle;
|
|
5597
6457
|
if (this.#domain !== void 0) throw this.#domain;
|
|
5598
6458
|
}
|
|
5599
|
-
#
|
|
6459
|
+
#refuseSchema(message, stack, first, second, keyword, member) {
|
|
6460
|
+
if (this.#structure !== void 0) return false;
|
|
6461
|
+
const ancestors = INTRINSICS.reflect.apply(INTRINSICS.expand, readIndexView(stack), [(frame) => frame.operation === "exit" ? pathOf([], INTRINSICS.own(frame, "first") ? frame.first : void 0, INTRINSICS.own(frame, "second") ? frame.second : void 0) : []]);
|
|
6462
|
+
const prefix = [];
|
|
6463
|
+
appendEntries(prefix, this.#path);
|
|
6464
|
+
prefix[prefix.length] = "schema";
|
|
6465
|
+
appendEntries(prefix, ancestors);
|
|
6466
|
+
const path = pathOf(prefix, first, second);
|
|
6467
|
+
return this.#refuse(message, keyword, member, path);
|
|
6468
|
+
}
|
|
6469
|
+
#refuse(message, first, second, prefix = this.#path) {
|
|
5600
6470
|
if (this.#structure === void 0) {
|
|
5601
|
-
const path = pathOf(
|
|
6471
|
+
const path = pathOf(prefix, first, second);
|
|
5602
6472
|
this.#structure = new ContractError(message, {
|
|
5603
6473
|
code: "structure",
|
|
5604
6474
|
context: { path }
|
|
@@ -5666,7 +6536,7 @@ var ShapeValidator = class ShapeValidator {
|
|
|
5666
6536
|
*/
|
|
5667
6537
|
validate() {
|
|
5668
6538
|
INTRINSICS.reflect.apply(INTRINSICS.sweep, this.#passes, [(pass) => pass.interrupt()]);
|
|
5669
|
-
const pass = new ShapePass(this.#source);
|
|
6539
|
+
const pass = new ShapePass(this.#source, { left: CLONE_NODE_LIMIT });
|
|
5670
6540
|
INTRINSICS.reflect.apply(INTRINSICS.admit, this.#passes, [pass]);
|
|
5671
6541
|
this.#expansion = void 0;
|
|
5672
6542
|
try {
|
|
@@ -5769,6 +6639,7 @@ var ShapeCloner = class ShapeCloner {
|
|
|
5769
6639
|
return this.#settle(failure(error));
|
|
5770
6640
|
}
|
|
5771
6641
|
#execute() {
|
|
6642
|
+
const budget = { left: CLONE_NODE_LIMIT };
|
|
5772
6643
|
const paths = this.#paths;
|
|
5773
6644
|
const memo = this.#memo;
|
|
5774
6645
|
if (paths === void 0 || memo === void 0) throw this.#unavailable();
|
|
@@ -5777,7 +6648,7 @@ var ShapeCloner = class ShapeCloner {
|
|
|
5777
6648
|
shape: this.#source,
|
|
5778
6649
|
depth: 0
|
|
5779
6650
|
};
|
|
5780
|
-
this.#drain();
|
|
6651
|
+
this.#drain(budget);
|
|
5781
6652
|
this.#wireNodes();
|
|
5782
6653
|
const root = INTRINSICS.reflect.apply(INTRINSICS.fetch, memo, [this.#source]);
|
|
5783
6654
|
if (root === void 0) throw this.#create("ShapeCloner.clone: captured root is unavailable", {
|
|
@@ -5789,19 +6660,19 @@ var ShapeCloner = class ShapeCloner {
|
|
|
5789
6660
|
if (this.#fidelity !== void 0) throw this.#fidelity;
|
|
5790
6661
|
return root;
|
|
5791
6662
|
}
|
|
5792
|
-
#drain() {
|
|
6663
|
+
#drain(budget) {
|
|
5793
6664
|
const memo = this.#memo;
|
|
5794
6665
|
if (memo === void 0) throw this.#unavailable();
|
|
5795
6666
|
for (const cursor of iterateIndices(() => this.#pending.length)) {
|
|
5796
6667
|
const entry = this.#pending[cursor];
|
|
5797
6668
|
if (entry === void 0) continue;
|
|
5798
6669
|
if (INTRINSICS.reflect.apply(INTRINSICS.keyed, memo, [entry.shape])) continue;
|
|
5799
|
-
if (entry.depth > 512) this.#refuseDepth();
|
|
5800
|
-
this.#captureNode(entry.shape, entry.depth);
|
|
6670
|
+
if (entry.depth > 512) this.#refuseDepth(budget);
|
|
6671
|
+
this.#captureNode(entry.shape, entry.depth, budget);
|
|
5801
6672
|
}
|
|
5802
6673
|
}
|
|
5803
|
-
#refuseDepth() {
|
|
5804
|
-
this.#validateShape(this.#source);
|
|
6674
|
+
#refuseDepth(budget) {
|
|
6675
|
+
this.#validateShape(this.#source, [], budget);
|
|
5805
6676
|
throw this.#create("validateShape: a shape exceeds the compilation depth limit", {
|
|
5806
6677
|
code: "depth",
|
|
5807
6678
|
context: {
|
|
@@ -5810,7 +6681,7 @@ var ShapeCloner = class ShapeCloner {
|
|
|
5810
6681
|
}
|
|
5811
6682
|
});
|
|
5812
6683
|
}
|
|
5813
|
-
#captureShell(source, path) {
|
|
6684
|
+
#captureShell(source, path, budget) {
|
|
5814
6685
|
if (!matchesRecordBrand(source)) throw this.#create("validateShape: every structural child must be a shape", {
|
|
5815
6686
|
code: "structure",
|
|
5816
6687
|
context: { path }
|
|
@@ -5832,13 +6703,14 @@ var ShapeCloner = class ShapeCloner {
|
|
|
5832
6703
|
case "boolean": return this.#captureSimple(source, path, "boolean");
|
|
5833
6704
|
case "null": return this.#captureSimple(source, path, "null");
|
|
5834
6705
|
case "literal": return this.#captureLiteral(source, path);
|
|
5835
|
-
case "array": return this.#captureArray(source, path);
|
|
5836
|
-
case "object": return this.#captureObject(source, path);
|
|
5837
|
-
case "union": return this.#captureUnion(source, path);
|
|
5838
|
-
case "optional": return this.#
|
|
5839
|
-
case "nullable": return this.#
|
|
6706
|
+
case "array": return this.#captureArray(source, path, budget);
|
|
6707
|
+
case "object": return this.#captureObject(source, path, budget);
|
|
6708
|
+
case "union": return this.#captureUnion(source, path, budget);
|
|
6709
|
+
case "optional": return this.#captureOptional(source, path, budget);
|
|
6710
|
+
case "nullable": return this.#captureNullable(source, path, budget);
|
|
5840
6711
|
case "json": return this.#captureSimple(source, path, "json");
|
|
5841
|
-
case "
|
|
6712
|
+
case "shape": return this.#captureSimple(source, path, "shape");
|
|
6713
|
+
case "raw": return this.#captureRaw(source, path, budget);
|
|
5842
6714
|
default: throw this.#create("validateShape: every node must be a recognized shape", {
|
|
5843
6715
|
code: "structure",
|
|
5844
6716
|
context: { path }
|
|
@@ -5926,12 +6798,12 @@ var ShapeCloner = class ShapeCloner {
|
|
|
5926
6798
|
flags
|
|
5927
6799
|
};
|
|
5928
6800
|
}
|
|
5929
|
-
#captureNode(source, depth) {
|
|
6801
|
+
#captureNode(source, depth, budget) {
|
|
5930
6802
|
const paths = this.#paths;
|
|
5931
6803
|
const memo = this.#memo;
|
|
5932
6804
|
if (paths === void 0 || memo === void 0) throw this.#unavailable();
|
|
5933
6805
|
const path = INTRINSICS.reflect.apply(INTRINSICS.fetch, paths, [source]) ?? [];
|
|
5934
|
-
const clone = this.#captureShell(source, path);
|
|
6806
|
+
const clone = this.#captureShell(source, path, budget);
|
|
5935
6807
|
INTRINSICS.reflect.apply(INTRINSICS.store, memo, [source, clone]);
|
|
5936
6808
|
this.#sources[this.#sources.length] = source;
|
|
5937
6809
|
this.#scheduleNode(source, clone, path, depth);
|
|
@@ -5980,6 +6852,10 @@ var ShapeCloner = class ShapeCloner {
|
|
|
5980
6852
|
category: "null",
|
|
5981
6853
|
...description === void 0 ? {} : { description }
|
|
5982
6854
|
};
|
|
6855
|
+
if (category === "shape") return {
|
|
6856
|
+
category: "shape",
|
|
6857
|
+
...description === void 0 ? {} : { description }
|
|
6858
|
+
};
|
|
5983
6859
|
return {
|
|
5984
6860
|
category: "json",
|
|
5985
6861
|
...description === void 0 ? {} : { description }
|
|
@@ -5994,7 +6870,8 @@ var ShapeCloner = class ShapeCloner {
|
|
|
5994
6870
|
...description === void 0 ? {} : { description }
|
|
5995
6871
|
};
|
|
5996
6872
|
}
|
|
5997
|
-
#captureArray(source, path) {
|
|
6873
|
+
#captureArray(source, path, budget) {
|
|
6874
|
+
this.#spend(budget, 1, path);
|
|
5998
6875
|
const items = this.#captureField(source, "items", path);
|
|
5999
6876
|
const min = this.#captureField(source, "min", path);
|
|
6000
6877
|
const max = this.#captureField(source, "max", path);
|
|
@@ -6011,7 +6888,7 @@ var ShapeCloner = class ShapeCloner {
|
|
|
6011
6888
|
...description === void 0 ? {} : { description }
|
|
6012
6889
|
};
|
|
6013
6890
|
}
|
|
6014
|
-
#captureObject(source, path) {
|
|
6891
|
+
#captureObject(source, path, budget) {
|
|
6015
6892
|
const propertySource = this.#captureField(source, "properties", path);
|
|
6016
6893
|
const additional = this.#captureField(source, "additionalProperties", path);
|
|
6017
6894
|
const description = this.#captureField(source, "description", path);
|
|
@@ -6019,7 +6896,8 @@ var ShapeCloner = class ShapeCloner {
|
|
|
6019
6896
|
code: "structure",
|
|
6020
6897
|
context: { path: pathOf(path, "properties") }
|
|
6021
6898
|
});
|
|
6022
|
-
this.#captureProperties(source, propertySource, path);
|
|
6899
|
+
this.#captureProperties(source, propertySource, path, budget);
|
|
6900
|
+
if (additional !== void 0 && additional !== true && additional !== false) this.#spend(budget, 1, path);
|
|
6023
6901
|
return {
|
|
6024
6902
|
category: "object",
|
|
6025
6903
|
properties: INTRINSICS.create(null),
|
|
@@ -6027,11 +6905,11 @@ var ShapeCloner = class ShapeCloner {
|
|
|
6027
6905
|
...description === void 0 ? {} : { description }
|
|
6028
6906
|
};
|
|
6029
6907
|
}
|
|
6030
|
-
#captureUnion(source, path) {
|
|
6908
|
+
#captureUnion(source, path, budget) {
|
|
6031
6909
|
const variantSource = this.#captureField(source, "variants", path);
|
|
6032
6910
|
const mode = this.#captureField(source, "mode", path);
|
|
6033
6911
|
const description = this.#captureField(source, "description", path);
|
|
6034
|
-
this.#captureVariants(source, variantSource, path);
|
|
6912
|
+
this.#captureVariants(source, variantSource, path, budget);
|
|
6035
6913
|
return {
|
|
6036
6914
|
category: "union",
|
|
6037
6915
|
variants: [],
|
|
@@ -6039,21 +6917,41 @@ var ShapeCloner = class ShapeCloner {
|
|
|
6039
6917
|
...description === void 0 ? {} : { description }
|
|
6040
6918
|
};
|
|
6041
6919
|
}
|
|
6042
|
-
#
|
|
6043
|
-
const inner = this.#
|
|
6044
|
-
|
|
6920
|
+
#captureOptional(source, path, budget) {
|
|
6921
|
+
const inner = this.#captureInner(source, path, budget);
|
|
6922
|
+
const value = this.#captureField(source, "default", path);
|
|
6923
|
+
if (!INTRINSICS.own(source, "default")) return {
|
|
6924
|
+
category: "optional",
|
|
6925
|
+
inner
|
|
6926
|
+
};
|
|
6927
|
+
const owned = isJSONValue(value) ? attempt(() => new JSONCloner(value).clone(budget)) : void 0;
|
|
6928
|
+
if (owned !== void 0 && isFailure(owned) && budget.left < 0 && isContractError(owned.error)) throw this.#prefix(owned.error, pathOf(path, "default"));
|
|
6929
|
+
if (owned === void 0 || isFailure(owned)) throw this.#create("validateShape: an optional default must be a JSON value", {
|
|
6045
6930
|
code: "structure",
|
|
6046
|
-
context: { path: pathOf(path, "
|
|
6931
|
+
context: { path: pathOf(path, "default") }
|
|
6047
6932
|
});
|
|
6048
|
-
return
|
|
6933
|
+
return {
|
|
6049
6934
|
category: "optional",
|
|
6050
|
-
inner
|
|
6051
|
-
|
|
6935
|
+
inner,
|
|
6936
|
+
default: owned.value
|
|
6937
|
+
};
|
|
6938
|
+
}
|
|
6939
|
+
#captureNullable(source, path, budget) {
|
|
6940
|
+
return {
|
|
6052
6941
|
category: "nullable",
|
|
6053
|
-
inner
|
|
6942
|
+
inner: this.#captureInner(source, path, budget)
|
|
6054
6943
|
};
|
|
6055
6944
|
}
|
|
6056
|
-
#
|
|
6945
|
+
#captureInner(source, path, budget) {
|
|
6946
|
+
this.#spend(budget, 1, path);
|
|
6947
|
+
const inner = this.#captureField(source, "inner", path);
|
|
6948
|
+
if (inner === void 0) throw this.#create("validateShape: every structural child must be a shape", {
|
|
6949
|
+
code: "structure",
|
|
6950
|
+
context: { path: pathOf(path, "inner") }
|
|
6951
|
+
});
|
|
6952
|
+
return inner;
|
|
6953
|
+
}
|
|
6954
|
+
#captureRaw(source, path, budget) {
|
|
6057
6955
|
const schema = this.#captureField(source, "schema", path);
|
|
6058
6956
|
if (!isRecord(schema)) throw this.#create("validateShape: raw schema must be a plain record", {
|
|
6059
6957
|
code: "structure",
|
|
@@ -6062,10 +6960,10 @@ var ShapeCloner = class ShapeCloner {
|
|
|
6062
6960
|
this.#validateShape({
|
|
6063
6961
|
category: "raw",
|
|
6064
6962
|
schema
|
|
6065
|
-
});
|
|
6963
|
+
}, path, budget);
|
|
6066
6964
|
const outcome = attempt(() => new SchemaCloner(schema).clone());
|
|
6067
6965
|
if (isFailure(outcome)) {
|
|
6068
|
-
if (isContractError(outcome.error))
|
|
6966
|
+
if (isContractError(outcome.error)) throw this.#prefix(outcome.error, pathOf(path, "schema"));
|
|
6069
6967
|
throw outcome.error;
|
|
6070
6968
|
}
|
|
6071
6969
|
return {
|
|
@@ -6108,9 +7006,10 @@ var ShapeCloner = class ShapeCloner {
|
|
|
6108
7006
|
});
|
|
6109
7007
|
return value;
|
|
6110
7008
|
}
|
|
6111
|
-
#captureProperties(source, properties, path) {
|
|
7009
|
+
#captureProperties(source, properties, path, budget) {
|
|
6112
7010
|
const keys = INTRINSICS.keys(properties);
|
|
6113
7011
|
const snapshot = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(keys), [(key) => {
|
|
7012
|
+
this.#spend(budget, 1, path);
|
|
6114
7013
|
const descriptor = INTRINSICS.describe(properties, key);
|
|
6115
7014
|
if (descriptor === void 0 || !INTRINSICS.own(descriptor, "value")) throw this.#create("validateShape: every structural child must be a shape", {
|
|
6116
7015
|
code: "structure",
|
|
@@ -6137,7 +7036,7 @@ var ShapeCloner = class ShapeCloner {
|
|
|
6137
7036
|
if (captured === void 0) throw this.#unavailable();
|
|
6138
7037
|
INTRINSICS.reflect.apply(INTRINSICS.store, captured, [source, snapshot]);
|
|
6139
7038
|
}
|
|
6140
|
-
#captureVariants(source, variants, path) {
|
|
7039
|
+
#captureVariants(source, variants, path, budget) {
|
|
6141
7040
|
if (!INTRINSICS.array(variants)) throw this.#create("validateShape: variants must be a finite array", {
|
|
6142
7041
|
code: "structure",
|
|
6143
7042
|
context: { path: pathOf(path, "variants") }
|
|
@@ -6152,6 +7051,7 @@ var ShapeCloner = class ShapeCloner {
|
|
|
6152
7051
|
context: { path: pathOf(path, "variants") }
|
|
6153
7052
|
});
|
|
6154
7053
|
const entries = snapshot.value.entries;
|
|
7054
|
+
this.#spend(budget, entries.length, path);
|
|
6155
7055
|
const captured = this.#variants;
|
|
6156
7056
|
if (captured === void 0) throw this.#unavailable();
|
|
6157
7057
|
INTRINSICS.reflect.apply(INTRINSICS.store, captured, [source, entries]);
|
|
@@ -6335,12 +7235,40 @@ var ShapeCloner = class ShapeCloner {
|
|
|
6335
7235
|
if (clone !== void 0) INTRINSICS.freeze(clone);
|
|
6336
7236
|
}
|
|
6337
7237
|
}
|
|
6338
|
-
#validateShape(shape) {
|
|
6339
|
-
const outcome = attempt(() => new
|
|
7238
|
+
#validateShape(shape, path = [], budget) {
|
|
7239
|
+
const outcome = attempt(() => new ShapePass(shape, budget).validate());
|
|
6340
7240
|
if (isSuccess(outcome)) return;
|
|
6341
|
-
if (isContractError(outcome.error))
|
|
7241
|
+
if (isContractError(outcome.error)) throw this.#prefix(outcome.error, path);
|
|
6342
7242
|
throw outcome.error;
|
|
6343
7243
|
}
|
|
7244
|
+
#spend(budget, count, path) {
|
|
7245
|
+
budget.left -= count;
|
|
7246
|
+
if (budget.left < 0) throw this.#create(`cloneShape: capture exceeds the node limit ${CLONE_NODE_LIMIT}`, {
|
|
7247
|
+
code: "clone",
|
|
7248
|
+
context: {
|
|
7249
|
+
path,
|
|
7250
|
+
limit: CLONE_NODE_LIMIT
|
|
7251
|
+
}
|
|
7252
|
+
});
|
|
7253
|
+
}
|
|
7254
|
+
#prefix(error, path) {
|
|
7255
|
+
if (path.length === 0) {
|
|
7256
|
+
admitVisited(this.#owned, error);
|
|
7257
|
+
return error;
|
|
7258
|
+
}
|
|
7259
|
+
const tail = error.context?.path;
|
|
7260
|
+
const location = [];
|
|
7261
|
+
appendEntries(location, path);
|
|
7262
|
+
appendEntries(location, typeof tail === "string" ? [tail] : tail ?? []);
|
|
7263
|
+
return this.#create(error.message, {
|
|
7264
|
+
code: error.code,
|
|
7265
|
+
context: {
|
|
7266
|
+
...error.context,
|
|
7267
|
+
path: location
|
|
7268
|
+
},
|
|
7269
|
+
...INTRINSICS.own(error, "cause") ? { cause: error.cause } : {}
|
|
7270
|
+
});
|
|
7271
|
+
}
|
|
6344
7272
|
#unavailable() {
|
|
6345
7273
|
return this.#create("ShapeCloner.clone: the capture state is unavailable", {
|
|
6346
7274
|
code: "clone",
|
|
@@ -6506,7 +7434,7 @@ function ownShape(shape) {
|
|
|
6506
7434
|
const frozen = holds(() => INTRINSICS.frozen(shape));
|
|
6507
7435
|
const fidelity = attempt(() => cloneShape(shape));
|
|
6508
7436
|
if (isSuccess(fidelity)) return fidelity.value;
|
|
6509
|
-
if (isContractError(fidelity.error) && fidelity.error.code !== "clone") throw fidelity.error;
|
|
7437
|
+
if (isContractError(fidelity.error) && (fidelity.error.code !== "clone" || fidelity.error.context?.limit === 262144)) throw fidelity.error;
|
|
6510
7438
|
if (!frozen) throw fidelity.error;
|
|
6511
7439
|
const validation = attempt(() => new ShapeValidator(shape).validate());
|
|
6512
7440
|
if (isFailure(validation) && isContractError(validation.error)) throw validation.error;
|
|
@@ -6983,8 +7911,9 @@ function matchOf(pattern) {
|
|
|
6983
7911
|
* refinements — `min` / `max` length and a `pattern`.
|
|
6984
7912
|
*
|
|
6985
7913
|
* @remarks
|
|
6986
|
-
* Composes {@link isString} with {@link
|
|
6987
|
-
*
|
|
7914
|
+
* Composes {@link isString} with {@link matchesStringLength}, which counts code
|
|
7915
|
+
* points as the `minLength` and `maxLength` a string shape emits do, and an owned
|
|
7916
|
+
* stateless pattern (the same refinement {@link matchOf} performs).
|
|
6988
7917
|
* When `min`, `max`, and `pattern` are all absent it returns the bare {@link isString} guard
|
|
6989
7918
|
* (the unconstrained fast path), so an unrefined string leaf pays no wrapping
|
|
6990
7919
|
* cost. The single source of the string refinement shared by the compiled guard
|
|
@@ -7011,14 +7940,13 @@ function stringOf(options) {
|
|
|
7011
7940
|
"max",
|
|
7012
7941
|
"pattern"
|
|
7013
7942
|
], "stringOf", "string");
|
|
7014
|
-
const min = safe
|
|
7015
|
-
const max = safe
|
|
7016
|
-
const source = safe
|
|
7943
|
+
const min = safe !== void 0 && INTRINSICS.own(safe, "min") ? safe.min : void 0;
|
|
7944
|
+
const max = safe !== void 0 && INTRINSICS.own(safe, "max") ? safe.max : void 0;
|
|
7945
|
+
const source = safe !== void 0 && INTRINSICS.own(safe, "pattern") ? safe.pattern : void 0;
|
|
7017
7946
|
if (source !== void 0 && !isRegExp(source)) throw new ContractError("stringOf: pattern must be a RegExp", { code: "pattern" });
|
|
7018
7947
|
const pattern = source === void 0 ? void 0 : ownPattern(source, "stringOf");
|
|
7019
7948
|
if (min === void 0 && max === void 0 && pattern === void 0) return isString;
|
|
7020
|
-
|
|
7021
|
-
return whereOf(isString, (value) => withinLength(value.length) && (pattern === void 0 || matchesPattern(pattern, value)));
|
|
7949
|
+
return whereOf(isString, (value) => matchesStringLength(value, min, max) && (pattern === void 0 || matchesPattern(pattern, value)));
|
|
7022
7950
|
}, "stringOf");
|
|
7023
7951
|
}
|
|
7024
7952
|
/**
|
|
@@ -7543,7 +8471,9 @@ function seededRandom(seed) {
|
|
|
7543
8471
|
* chain pays a hundred clones of shrinking graphs and a hundred validations —
|
|
7544
8472
|
* quadratic work for a linear declaration. Here ownership runs once, validation runs once over
|
|
7545
8473
|
* that owned result, and each unique node and structural edge is indexed once
|
|
7546
|
-
* into children-before-parent order.
|
|
8474
|
+
* into children-before-parent order. A declaration a builder sealed is frozen and
|
|
8475
|
+
* validated all the way down already, so it takes neither and is indexed as it
|
|
8476
|
+
* stands. Every artifact family is then a single
|
|
7547
8477
|
* postorder pass whose entries are keyed by node identity, so a shared child is
|
|
7548
8478
|
* compiled once however many parents point at it. The same asymmetry exists on
|
|
7549
8479
|
* the VALUE side and is answered the same way: `guard`, `auditor` and `reporter`
|
|
@@ -7555,7 +8485,9 @@ function seededRandom(seed) {
|
|
|
7555
8485
|
* getters after it replay. A getter builds its own family and no other, except
|
|
7556
8486
|
* that `parser`, `reporter` and `generator` build the guard plan when the graph
|
|
7557
8487
|
* holds a union, because a union's membership question IS a guard question in
|
|
7558
|
-
* all three
|
|
8488
|
+
* all three, and every getter builds it when the graph holds a default, because
|
|
8489
|
+
* a default that its inner shape refuses refuses at whichever artifact is read
|
|
8490
|
+
* first.
|
|
7559
8491
|
*
|
|
7560
8492
|
* One terminal lifecycle covers preparation and every family. A failure settles
|
|
7561
8493
|
* the compiler: later getters rethrow that exact error, while an artifact
|
|
@@ -7775,10 +8707,15 @@ var ContractCompiler = class ContractCompiler {
|
|
|
7775
8707
|
shape: "contract"
|
|
7776
8708
|
}
|
|
7777
8709
|
});
|
|
8710
|
+
const sealed = ShapePass.expansionOf(source);
|
|
8711
|
+
if (sealed !== void 0) {
|
|
8712
|
+
refuseExpansion(sealed);
|
|
8713
|
+
this.#discover(source);
|
|
8714
|
+
this.#source = void 0;
|
|
8715
|
+
return;
|
|
8716
|
+
}
|
|
7778
8717
|
const owned = ownShape(source);
|
|
7779
|
-
|
|
7780
|
-
validator.validate();
|
|
7781
|
-
refuseExpansion(validator.expansion);
|
|
8718
|
+
refuseExpansion(new ShapePass(owned).validate());
|
|
7782
8719
|
this.#discover(owned);
|
|
7783
8720
|
this.#source = void 0;
|
|
7784
8721
|
}
|
|
@@ -7807,7 +8744,9 @@ var ContractCompiler = class ContractCompiler {
|
|
|
7807
8744
|
const shape = frame.shape;
|
|
7808
8745
|
if (INTRINSICS.reflect.apply(INTRINSICS.recall, known, [shape]) !== void 0) continue;
|
|
7809
8746
|
const index = this.#nodes.length;
|
|
7810
|
-
|
|
8747
|
+
const node = INTRINSICS.rebase({ ...shape }, null);
|
|
8748
|
+
this.#nodes[index] = node;
|
|
8749
|
+
INTRINSICS.reflect.apply(INTRINSICS.retain, known, [node, index]);
|
|
7811
8750
|
INTRINSICS.reflect.apply(INTRINSICS.retain, known, [shape, index]);
|
|
7812
8751
|
this.#stack[this.#stack.length] = {
|
|
7813
8752
|
operation: "exit",
|
|
@@ -7898,6 +8837,54 @@ var ContractCompiler = class ContractCompiler {
|
|
|
7898
8837
|
for (const index of iterateIndices(() => this.#nodes.length)) if (this.#nodes[index]?.category === "union") return true;
|
|
7899
8838
|
return false;
|
|
7900
8839
|
}
|
|
8840
|
+
#defaults() {
|
|
8841
|
+
for (const index of iterateIndices(() => this.#nodes.length)) {
|
|
8842
|
+
const node = this.#nodes[index];
|
|
8843
|
+
if (node?.category === "optional" && INTRINSICS.own(node, "default")) return true;
|
|
8844
|
+
}
|
|
8845
|
+
return false;
|
|
8846
|
+
}
|
|
8847
|
+
#checkDefaults(shape, path) {
|
|
8848
|
+
switch (shape.category) {
|
|
8849
|
+
case "array":
|
|
8850
|
+
this.#checkDefaults(shape.items, pathOf(path, "items"));
|
|
8851
|
+
return;
|
|
8852
|
+
case "nullable":
|
|
8853
|
+
this.#checkDefaults(shape.inner, pathOf(path, "inner"));
|
|
8854
|
+
return;
|
|
8855
|
+
case "optional":
|
|
8856
|
+
this.#checkDefaults(shape.inner, pathOf(path, "inner"));
|
|
8857
|
+
if (!INTRINSICS.own(shape, "default") || this.#guardAt(shape.inner)(shape.default)) return;
|
|
8858
|
+
throw new ContractError("ContractCompiler: a default must satisfy the shape it fills; change the default or the shape", {
|
|
8859
|
+
code: "structure",
|
|
8860
|
+
context: {
|
|
8861
|
+
path: pathOf(path, "default"),
|
|
8862
|
+
shape: "optional",
|
|
8863
|
+
received: preview(shape.default)
|
|
8864
|
+
}
|
|
8865
|
+
});
|
|
8866
|
+
case "union":
|
|
8867
|
+
for (const index of iterateIndices(() => shape.variants.length)) {
|
|
8868
|
+
const variant = shape.variants[index];
|
|
8869
|
+
if (variant === void 0) continue;
|
|
8870
|
+
this.#checkDefaults(variant, pathOf(path, "variants", INTRINSICS.text(index)));
|
|
8871
|
+
}
|
|
8872
|
+
return;
|
|
8873
|
+
case "object": {
|
|
8874
|
+
const keys = INTRINSICS.keys(shape.properties);
|
|
8875
|
+
for (const index of iterateIndices(() => keys.length)) {
|
|
8876
|
+
const key = keys[index];
|
|
8877
|
+
const child = key === void 0 ? void 0 : shape.properties[key];
|
|
8878
|
+
if (child === void 0) continue;
|
|
8879
|
+
this.#checkDefaults(child, pathOf(path, "properties", key));
|
|
8880
|
+
}
|
|
8881
|
+
const extra = shape.additionalProperties;
|
|
8882
|
+
if (extra !== void 0 && extra !== true && extra !== false) this.#checkDefaults(extra, pathOf(path, "additionalProperties"));
|
|
8883
|
+
return;
|
|
8884
|
+
}
|
|
8885
|
+
default: return;
|
|
8886
|
+
}
|
|
8887
|
+
}
|
|
7901
8888
|
#repeats(index) {
|
|
7902
8889
|
const category = this.#node(index).category;
|
|
7903
8890
|
if (category === "array" || category === "object" || category === "union") return true;
|
|
@@ -7909,10 +8896,64 @@ var ContractCompiler = class ContractCompiler {
|
|
|
7909
8896
|
#trackFaults(plan) {
|
|
7910
8897
|
return (value, path) => EvaluationScope.run(plan, value, path, true);
|
|
7911
8898
|
}
|
|
8899
|
+
#discriminate(owned) {
|
|
8900
|
+
const arms = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(owned.variants), [(variant) => variant?.category === "object"]);
|
|
8901
|
+
const first = arms[0];
|
|
8902
|
+
if (first === void 0 || arms.length !== owned.variants.length) return void 0;
|
|
8903
|
+
const keys = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(INTRINSICS.keys(first.properties)), [(key) => !INTRINSICS.reflect.apply(INTRINSICS.some, arms, [(arm) => !INTRINSICS.own(arm.properties, key) || arm.properties[key]?.category !== "literal"])]);
|
|
8904
|
+
const tables = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(keys), [(key) => ContractCompiler.#tableOf(key, arms)]);
|
|
8905
|
+
const named = tables[0];
|
|
8906
|
+
if (named === void 0) return void 0;
|
|
8907
|
+
return {
|
|
8908
|
+
hint: INTRINSICS.freeze({
|
|
8909
|
+
key: named.key,
|
|
8910
|
+
expected: named.expected
|
|
8911
|
+
}),
|
|
8912
|
+
select: (value) => {
|
|
8913
|
+
if (!isObject(value)) return void 0;
|
|
8914
|
+
for (const index of iterateIndices(() => tables.length)) {
|
|
8915
|
+
const table = tables[index];
|
|
8916
|
+
if (table === void 0) continue;
|
|
8917
|
+
const held = attempt(() => INTRINSICS.describe(value, table.key));
|
|
8918
|
+
if (isFailure(held) || held.value === void 0) continue;
|
|
8919
|
+
if (!INTRINSICS.own(held.value, "value")) continue;
|
|
8920
|
+
const arm = INTRINSICS.reflect.apply(INTRINSICS.fetch, table.members, [held.value.value]);
|
|
8921
|
+
if (arm !== void 0 && arm >= 0) return arm;
|
|
8922
|
+
}
|
|
8923
|
+
}
|
|
8924
|
+
};
|
|
8925
|
+
}
|
|
8926
|
+
static #tableOf(key, arms) {
|
|
8927
|
+
const members = new INTRINSICS.map();
|
|
8928
|
+
const expected = [];
|
|
8929
|
+
for (const armIndex of iterateIndices(() => arms.length)) {
|
|
8930
|
+
const node = arms[armIndex]?.properties[key];
|
|
8931
|
+
if (node?.category !== "literal") continue;
|
|
8932
|
+
for (const valueIndex of iterateIndices(() => node.values.length)) {
|
|
8933
|
+
const literal = node.values[valueIndex];
|
|
8934
|
+
if (literal === void 0) continue;
|
|
8935
|
+
const known = INTRINSICS.reflect.apply(INTRINSICS.fetch, members, [literal]);
|
|
8936
|
+
if (known === void 0) expected[expected.length] = literal;
|
|
8937
|
+
const arm = known === void 0 || known === armIndex ? armIndex : -1;
|
|
8938
|
+
INTRINSICS.reflect.apply(INTRINSICS.store, members, [literal, arm]);
|
|
8939
|
+
}
|
|
8940
|
+
}
|
|
8941
|
+
return {
|
|
8942
|
+
key,
|
|
8943
|
+
members,
|
|
8944
|
+
expected: INTRINSICS.freeze(expected)
|
|
8945
|
+
};
|
|
8946
|
+
}
|
|
8947
|
+
static #parseArm(arm, value) {
|
|
8948
|
+
if (arm.guard(value)) return value;
|
|
8949
|
+
const parsed = arm.parse(value);
|
|
8950
|
+
return parsed !== void 0 && arm.guard(parsed) ? parsed : void 0;
|
|
8951
|
+
}
|
|
7912
8952
|
#buildSchema() {
|
|
7913
8953
|
const ready = this.#schema;
|
|
7914
8954
|
if (ready !== void 0) return ready;
|
|
7915
8955
|
this.#prepare();
|
|
8956
|
+
if (this.#defaults()) this.#buildGuard();
|
|
7916
8957
|
for (const step of iterateIndices(() => this.#order.length)) {
|
|
7917
8958
|
const index = this.#order[step];
|
|
7918
8959
|
if (index === void 0) continue;
|
|
@@ -7936,6 +8977,13 @@ var ContractCompiler = class ContractCompiler {
|
|
|
7936
8977
|
#schemaOf(index) {
|
|
7937
8978
|
const owned = this.#node(index);
|
|
7938
8979
|
switch (owned.category) {
|
|
8980
|
+
case "shape": return INTRINSICS.freeze({
|
|
8981
|
+
type: "object",
|
|
8982
|
+
description: owned.description ?? "Over-approximates declarations whose JSON projection preserves their own enumerable data; values without that projection are outside this schema. is decides whether the complete shape is valid.",
|
|
8983
|
+
properties: INTRINSICS.freeze({ category: INTRINSICS.freeze({ enum: INTRINSICS.freeze(INTRINSICS.keys(SHAPE_FIELDS)) }) }),
|
|
8984
|
+
required: INTRINSICS.freeze(["category"]),
|
|
8985
|
+
additionalProperties: true
|
|
8986
|
+
});
|
|
7939
8987
|
case "string": {
|
|
7940
8988
|
const text = owned.pattern === void 0 ? void 0 : readPatternSource(owned.pattern);
|
|
7941
8989
|
if (owned.pattern !== void 0 && text === void 0) throw new ContractError("compileSchema: pattern source could not be read", {
|
|
@@ -7985,7 +9033,7 @@ var ContractCompiler = class ContractCompiler {
|
|
|
7985
9033
|
if (child === void 0) return [];
|
|
7986
9034
|
return [{
|
|
7987
9035
|
key,
|
|
7988
|
-
schema: this.#schemaAt(child
|
|
9036
|
+
schema: this.#schemaAt(child),
|
|
7989
9037
|
required: child.category !== "optional"
|
|
7990
9038
|
}];
|
|
7991
9039
|
}]);
|
|
@@ -8009,7 +9057,14 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8009
9057
|
...owned.description !== void 0 ? { description: owned.description } : {}
|
|
8010
9058
|
});
|
|
8011
9059
|
}
|
|
8012
|
-
case "optional":
|
|
9060
|
+
case "optional": {
|
|
9061
|
+
const emitted = this.#schemaAt(owned.inner);
|
|
9062
|
+
const value = owned.default;
|
|
9063
|
+
return value === void 0 ? emitted : INTRINSICS.freeze({
|
|
9064
|
+
...emitted,
|
|
9065
|
+
default: value
|
|
9066
|
+
});
|
|
9067
|
+
}
|
|
8013
9068
|
case "nullable": return INTRINSICS.freeze({ anyOf: INTRINSICS.freeze([this.#schemaAt(owned.inner), INTRINSICS.freeze({ type: "null" })]) });
|
|
8014
9069
|
case "raw": return cloneSchema(owned.schema);
|
|
8015
9070
|
}
|
|
@@ -8025,6 +9080,7 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8025
9080
|
this.#guards[index] = this.#repeats(index) ? this.#trackGuard(plan) : plan;
|
|
8026
9081
|
}
|
|
8027
9082
|
const root = this.#guardAt(this.#node(0));
|
|
9083
|
+
if (this.#defaults()) this.#checkDefaults(this.#node(0), []);
|
|
8028
9084
|
this.#guard = root;
|
|
8029
9085
|
return root;
|
|
8030
9086
|
}
|
|
@@ -8039,14 +9095,24 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8039
9095
|
});
|
|
8040
9096
|
return compiled;
|
|
8041
9097
|
}
|
|
9098
|
+
#stringGuard(owned) {
|
|
9099
|
+
return stringOf(INTRINSICS.rebase({
|
|
9100
|
+
...owned.min === void 0 ? {} : { min: owned.min },
|
|
9101
|
+
...owned.max === void 0 ? {} : { max: owned.max },
|
|
9102
|
+
...owned.pattern === void 0 ? {} : { pattern: owned.pattern }
|
|
9103
|
+
}, null));
|
|
9104
|
+
}
|
|
9105
|
+
static #acceptShape(value) {
|
|
9106
|
+
return isSuccess(attempt(() => {
|
|
9107
|
+
const validator = new ShapeValidator(value);
|
|
9108
|
+
validator.validate();
|
|
9109
|
+
refuseExpansion(validator.expansion);
|
|
9110
|
+
}));
|
|
9111
|
+
}
|
|
8042
9112
|
#guardOf(index) {
|
|
8043
9113
|
const owned = this.#node(index);
|
|
8044
9114
|
switch (owned.category) {
|
|
8045
|
-
case "string": return
|
|
8046
|
-
...owned.min === void 0 ? {} : { min: owned.min },
|
|
8047
|
-
...owned.max === void 0 ? {} : { max: owned.max },
|
|
8048
|
-
...owned.pattern === void 0 ? {} : { pattern: owned.pattern }
|
|
8049
|
-
});
|
|
9115
|
+
case "string": return this.#stringGuard(owned);
|
|
8050
9116
|
case "number": {
|
|
8051
9117
|
const base = owned.integer === true ? isInteger : isFiniteNumber;
|
|
8052
9118
|
if (owned.min === void 0 && owned.max === void 0) return base;
|
|
@@ -8055,6 +9121,7 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8055
9121
|
case "boolean": return isBoolean;
|
|
8056
9122
|
case "null": return isNull;
|
|
8057
9123
|
case "json": return isJSONValue;
|
|
9124
|
+
case "shape": return (value) => ContractCompiler.#acceptShape(value);
|
|
8058
9125
|
case "literal": return literalOf(owned.values);
|
|
8059
9126
|
case "array": {
|
|
8060
9127
|
const base = arrayOf(this.#guardAt(owned.items));
|
|
@@ -8131,7 +9198,7 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8131
9198
|
const ready = this.#parser;
|
|
8132
9199
|
if (ready !== void 0) return ready;
|
|
8133
9200
|
this.#prepare();
|
|
8134
|
-
if (this.#unions()) this.#buildGuard();
|
|
9201
|
+
if (this.#unions() || this.#defaults()) this.#buildGuard();
|
|
8135
9202
|
for (const step of iterateIndices(() => this.#order.length)) {
|
|
8136
9203
|
const index = this.#order[step];
|
|
8137
9204
|
if (index === void 0) continue;
|
|
@@ -8157,11 +9224,7 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8157
9224
|
switch (owned.category) {
|
|
8158
9225
|
case "string": {
|
|
8159
9226
|
if (owned.min === void 0 && owned.max === void 0 && owned.pattern === void 0) return parseString;
|
|
8160
|
-
const guard =
|
|
8161
|
-
...owned.min === void 0 ? {} : { min: owned.min },
|
|
8162
|
-
...owned.max === void 0 ? {} : { max: owned.max },
|
|
8163
|
-
...owned.pattern === void 0 ? {} : { pattern: owned.pattern }
|
|
8164
|
-
});
|
|
9227
|
+
const guard = this.#stringGuard(owned);
|
|
8165
9228
|
return (value) => {
|
|
8166
9229
|
const parsed = parseString(value);
|
|
8167
9230
|
return parsed !== void 0 && guard(parsed) ? parsed : void 0;
|
|
@@ -8179,6 +9242,7 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8179
9242
|
case "boolean": return parseBoolean;
|
|
8180
9243
|
case "null": return (value) => value === null ? null : void 0;
|
|
8181
9244
|
case "json": return parseJSONValue;
|
|
9245
|
+
case "shape": return (value) => ContractCompiler.#acceptShape(value) ? value : void 0;
|
|
8182
9246
|
case "literal": {
|
|
8183
9247
|
const allowed = literalOf(owned.values);
|
|
8184
9248
|
return (value) => {
|
|
@@ -8226,7 +9290,8 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8226
9290
|
return [{
|
|
8227
9291
|
key,
|
|
8228
9292
|
parse: this.#parserAt(inner),
|
|
8229
|
-
optional
|
|
9293
|
+
optional,
|
|
9294
|
+
fill: optional && INTRINSICS.own(child, "default") ? child.default : void 0
|
|
8230
9295
|
}];
|
|
8231
9296
|
}]);
|
|
8232
9297
|
const known = readValue(() => collectMembers(INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(entries), [(entry) => entry.key])), "compileParser", {
|
|
@@ -8250,14 +9315,14 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8250
9315
|
for (const entryIndex of iterateIndices(() => entries.length)) {
|
|
8251
9316
|
const entry = entries[entryIndex];
|
|
8252
9317
|
if (entry === void 0) continue;
|
|
8253
|
-
|
|
8254
|
-
if (entry.optional) continue;
|
|
8255
|
-
return;
|
|
8256
|
-
}
|
|
8257
|
-
const raw = record[entry.key];
|
|
9318
|
+
const raw = (present === void 0 ? (seen & 1 << entryIndex) === 0 : !matchesMember(present, entry.key)) ? void 0 : record[entry.key];
|
|
8258
9319
|
if (raw === void 0) {
|
|
8259
|
-
if (entry.optional)
|
|
8260
|
-
|
|
9320
|
+
if (!entry.optional) return void 0;
|
|
9321
|
+
if (entry.fill !== void 0) {
|
|
9322
|
+
const fill = isObject(entry.fill) ? cloneJSONValue(entry.fill) : entry.fill;
|
|
9323
|
+
selected[selected.length] = [entry.key, entry.parse(fill)];
|
|
9324
|
+
}
|
|
9325
|
+
continue;
|
|
8261
9326
|
}
|
|
8262
9327
|
const parsed = entry.parse(raw);
|
|
8263
9328
|
if (parsed === void 0) return void 0;
|
|
@@ -8291,12 +9356,19 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8291
9356
|
parse: this.#parserAt(variant),
|
|
8292
9357
|
guard: this.#guardAt(variant)
|
|
8293
9358
|
}]]);
|
|
9359
|
+
const discriminated = this.#discriminate(owned);
|
|
8294
9360
|
if (owned.mode === "oneOf") return (value) => {
|
|
9361
|
+
const selected = discriminated?.select(value);
|
|
9362
|
+
const arm = selected === void 0 ? void 0 : variants[selected];
|
|
9363
|
+
if (arm !== void 0) return ContractCompiler.#parseArm(arm, value);
|
|
8295
9364
|
const matching = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(variants), [(variant) => variant.guard(value)]);
|
|
8296
9365
|
const only = matching[0];
|
|
8297
|
-
return matching.length === 1 && only !== void 0 ?
|
|
9366
|
+
return matching.length === 1 && only !== void 0 ? value : void 0;
|
|
8298
9367
|
};
|
|
8299
9368
|
return (value) => {
|
|
9369
|
+
const selected = discriminated?.select(value);
|
|
9370
|
+
const arm = selected === void 0 ? void 0 : variants[selected];
|
|
9371
|
+
if (arm !== void 0) return ContractCompiler.#parseArm(arm, value);
|
|
8300
9372
|
for (const variantIndex of iterateIndices(() => variants.length)) {
|
|
8301
9373
|
const variant = variants[variantIndex];
|
|
8302
9374
|
if (variant === void 0) continue;
|
|
@@ -8325,6 +9397,7 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8325
9397
|
const ready = this.#auditor;
|
|
8326
9398
|
if (ready !== void 0) return ready;
|
|
8327
9399
|
this.#prepare();
|
|
9400
|
+
if (this.#defaults()) this.#buildGuard();
|
|
8328
9401
|
for (const step of iterateIndices(() => this.#order.length)) {
|
|
8329
9402
|
const index = this.#order[step];
|
|
8330
9403
|
if (index === void 0) continue;
|
|
@@ -8399,6 +9472,12 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8399
9472
|
expected: "json",
|
|
8400
9473
|
received: preview(value)
|
|
8401
9474
|
}];
|
|
9475
|
+
case "shape": return (value, path) => ContractCompiler.#acceptShape(value) ? [] : [{
|
|
9476
|
+
reason: "type",
|
|
9477
|
+
path,
|
|
9478
|
+
expected: "shape",
|
|
9479
|
+
received: preview(value)
|
|
9480
|
+
}];
|
|
8402
9481
|
case "literal": {
|
|
8403
9482
|
const allowed = literalOf(owned.values);
|
|
8404
9483
|
return (value, path) => allowed(value) ? [] : [{
|
|
@@ -8541,7 +9620,11 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8541
9620
|
const plans = INTRINSICS.reflect.apply(INTRINSICS.expand, readIndexView(owned.variants), [(variant) => variant === void 0 ? [] : [this.#auditAt(variant)]]);
|
|
8542
9621
|
const exclusive = owned.mode === "oneOf";
|
|
8543
9622
|
const count = owned.variants.length;
|
|
9623
|
+
const discriminated = this.#discriminate(owned);
|
|
8544
9624
|
return (value, path) => {
|
|
9625
|
+
const selected = discriminated?.select(value);
|
|
9626
|
+
const arm = selected === void 0 ? void 0 : plans[selected];
|
|
9627
|
+
if (arm !== void 0) return arm(value, path);
|
|
8545
9628
|
const perVariant = [];
|
|
8546
9629
|
for (const index2 of iterateIndices(() => plans.length)) {
|
|
8547
9630
|
const plan = plans[index2];
|
|
@@ -8558,18 +9641,21 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8558
9641
|
if (matched > 1) return [{
|
|
8559
9642
|
reason: "oneOf",
|
|
8560
9643
|
path,
|
|
8561
|
-
matched
|
|
9644
|
+
matched,
|
|
9645
|
+
...discriminated?.hint
|
|
8562
9646
|
}];
|
|
8563
9647
|
}
|
|
8564
9648
|
const closest = selectClosestFaults(perVariant);
|
|
8565
9649
|
const report = [exclusive ? {
|
|
8566
9650
|
reason: "oneOf",
|
|
8567
9651
|
path,
|
|
8568
|
-
matched: 0
|
|
9652
|
+
matched: 0,
|
|
9653
|
+
...discriminated?.hint
|
|
8569
9654
|
} : {
|
|
8570
9655
|
reason: "variant",
|
|
8571
9656
|
path,
|
|
8572
|
-
variants: count
|
|
9657
|
+
variants: count,
|
|
9658
|
+
...discriminated?.hint
|
|
8573
9659
|
}];
|
|
8574
9660
|
appendEntries(report, closest);
|
|
8575
9661
|
return limitEntries(report, 64);
|
|
@@ -8595,7 +9681,7 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8595
9681
|
const ready = this.#reporter;
|
|
8596
9682
|
if (ready !== void 0) return ready;
|
|
8597
9683
|
this.#prepare();
|
|
8598
|
-
if (this.#unions()) this.#buildGuard();
|
|
9684
|
+
if (this.#unions() || this.#defaults()) this.#buildGuard();
|
|
8599
9685
|
for (const step of iterateIndices(() => this.#order.length)) {
|
|
8600
9686
|
const index = this.#order[step];
|
|
8601
9687
|
if (index === void 0) continue;
|
|
@@ -8681,6 +9767,12 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8681
9767
|
received: preview(value)
|
|
8682
9768
|
}];
|
|
8683
9769
|
}
|
|
9770
|
+
case "shape": return (value, path) => ContractCompiler.#acceptShape(value) ? [] : [{
|
|
9771
|
+
reason: "type",
|
|
9772
|
+
path,
|
|
9773
|
+
expected: "shape",
|
|
9774
|
+
received: preview(value)
|
|
9775
|
+
}];
|
|
8684
9776
|
case "array": {
|
|
8685
9777
|
const node = owned;
|
|
8686
9778
|
const item = this.#reportAt(owned.items);
|
|
@@ -8798,7 +9890,11 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8798
9890
|
const guards = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(variants), [(variant) => variant.guard]);
|
|
8799
9891
|
const exclusive = owned.mode === "oneOf";
|
|
8800
9892
|
const count = owned.variants.length;
|
|
9893
|
+
const discriminated = this.#discriminate(owned);
|
|
8801
9894
|
return (value, path) => {
|
|
9895
|
+
const selected = discriminated?.select(value);
|
|
9896
|
+
const arm = selected === void 0 ? void 0 : plans[selected];
|
|
9897
|
+
if (arm !== void 0) return arm(value, path);
|
|
8802
9898
|
const perVariant = [];
|
|
8803
9899
|
for (const index2 of iterateIndices(() => plans.length)) {
|
|
8804
9900
|
const plan = plans[index2];
|
|
@@ -8815,7 +9911,8 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8815
9911
|
const report = [{
|
|
8816
9912
|
reason: "oneOf",
|
|
8817
9913
|
path,
|
|
8818
|
-
matched: 0
|
|
9914
|
+
matched: 0,
|
|
9915
|
+
...discriminated?.hint
|
|
8819
9916
|
}];
|
|
8820
9917
|
appendEntries(report, closest);
|
|
8821
9918
|
return limitEntries(report, 64);
|
|
@@ -8823,13 +9920,15 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8823
9920
|
return [{
|
|
8824
9921
|
reason: "oneOf",
|
|
8825
9922
|
path,
|
|
8826
|
-
matched
|
|
9923
|
+
matched,
|
|
9924
|
+
...discriminated?.hint
|
|
8827
9925
|
}];
|
|
8828
9926
|
}
|
|
8829
9927
|
const report = [{
|
|
8830
9928
|
reason: "variant",
|
|
8831
9929
|
path,
|
|
8832
|
-
variants: count
|
|
9930
|
+
variants: count,
|
|
9931
|
+
...discriminated?.hint
|
|
8833
9932
|
}];
|
|
8834
9933
|
appendEntries(report, closest);
|
|
8835
9934
|
return limitEntries(report, 64);
|
|
@@ -8855,7 +9954,7 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8855
9954
|
const ready = this.#generator;
|
|
8856
9955
|
if (ready !== void 0) return ready;
|
|
8857
9956
|
this.#prepare();
|
|
8858
|
-
if (this.#unions()) this.#buildGuard();
|
|
9957
|
+
if (this.#unions() || this.#defaults()) this.#buildGuard();
|
|
8859
9958
|
for (const step of iterateIndices(() => this.#order.length)) {
|
|
8860
9959
|
const index = this.#order[step];
|
|
8861
9960
|
if (index === void 0) continue;
|
|
@@ -8922,6 +10021,11 @@ var ContractCompiler = class ContractCompiler {
|
|
|
8922
10021
|
}
|
|
8923
10022
|
case "boolean": return (random) => drawRandom(random, "boolean") >= .5;
|
|
8924
10023
|
case "null": return () => null;
|
|
10024
|
+
case "shape": return () => ({
|
|
10025
|
+
category: "object",
|
|
10026
|
+
properties: {},
|
|
10027
|
+
additionalProperties: false
|
|
10028
|
+
});
|
|
8925
10029
|
case "json": return (random) => {
|
|
8926
10030
|
const pick = INTRINSICS.floor(drawRandom(random, "json") * 5);
|
|
8927
10031
|
if (pick === 0) return null;
|
|
@@ -9088,14 +10192,15 @@ var ContractCompiler = class ContractCompiler {
|
|
|
9088
10192
|
* eager well-formedness pass — there is no second prepass and no alias for it:
|
|
9089
10193
|
* it enforces every bound domain and range used by the artifacts, including
|
|
9090
10194
|
* non-empty literal/union vocabularies, finite literal numbers, integer-range
|
|
9091
|
-
* satisfiability, unflagged string patterns, optional-shape
|
|
9092
|
-
* recursively supported raw-schema vocabulary where every
|
|
9093
|
-
* dense union member is a record.
|
|
10195
|
+
* satisfiability, unflagged string patterns, optional-shape and default
|
|
10196
|
+
* placement, and the recursively supported raw-schema vocabulary where every
|
|
10197
|
+
* present property or dense union member is a record. It judges a default's
|
|
10198
|
+
* structure only; each compiler refuses a default its inner guard refuses.
|
|
9094
10199
|
* Active ancestors are tracked so shared children remain legal. Every
|
|
9095
10200
|
* standalone compiler reaches this same validation once, over its owned
|
|
9096
10201
|
* snapshot, through {@link ContractCompiler} preparation.
|
|
9097
|
-
*
|
|
9098
|
-
*
|
|
10202
|
+
* Cyclic graphs refuse before depth measurement, with structure before cycle.
|
|
10203
|
+
* Acyclic graphs report depth before structure, then field and vocabulary policy.
|
|
9099
10204
|
*
|
|
9100
10205
|
* @param shape - The shape graph to gate
|
|
9101
10206
|
* @returns Nothing; successful return means recursive compilation is structurally safe, depth-safe, and bounded in emitted nodes
|
|
@@ -9237,9 +10342,104 @@ function compileReporter(shape, value, path = []) {
|
|
|
9237
10342
|
function compileAuditor(shape, value, path = []) {
|
|
9238
10343
|
return contain(() => new ContractCompiler(shape).auditor(value, path), "compileAuditor");
|
|
9239
10344
|
}
|
|
10345
|
+
// src/core/LazyContract.ts
|
|
10346
|
+
/**
|
|
10347
|
+
* Owns a contract whose function members compile together on the first call to any.
|
|
10348
|
+
*
|
|
10349
|
+
* @remarks
|
|
10350
|
+
* For a declaration made entirely by builders, where preparation and the schema have
|
|
10351
|
+
* already asked everything that can refuse. A module that declares its contracts as
|
|
10352
|
+
* data then pays for a contract only when something uses it, and each member is a
|
|
10353
|
+
* plain function with one identity, so destructuring and spreading compile nothing.
|
|
10354
|
+
*
|
|
10355
|
+
* A compile can still fail for the host's reasons: a first call near the stack limit,
|
|
10356
|
+
* or a host whose members were replaced after this contract was created, which it
|
|
10357
|
+
* refuses to compile on since the result would outlive the replacement. Neither says
|
|
10358
|
+
* anything about a later call, which compiles afresh. Until then a guard answers
|
|
10359
|
+
* `false` and a parser `undefined`, and the diagnostic and seed members publish the
|
|
10360
|
+
* failure as their doors do.
|
|
10361
|
+
*/
|
|
10362
|
+
var LazyContract = class {
|
|
10363
|
+
#shape;
|
|
10364
|
+
#pending;
|
|
10365
|
+
#settled;
|
|
10366
|
+
#bundle;
|
|
10367
|
+
/**
|
|
10368
|
+
* Retains a declaration and the compiler already prepared from it.
|
|
10369
|
+
*
|
|
10370
|
+
* @param shape - The sealed declaration
|
|
10371
|
+
* @param compiler - The compiler that owns its prepared index
|
|
10372
|
+
*/
|
|
10373
|
+
constructor(shape, compiler) {
|
|
10374
|
+
this.#shape = shape;
|
|
10375
|
+
this.#pending = compiler;
|
|
10376
|
+
}
|
|
10377
|
+
/**
|
|
10378
|
+
* Compiles the schema, which refuses a bad declaration, and publishes the bundle.
|
|
10379
|
+
*
|
|
10380
|
+
* @param schema - The schema the prepared compiler emitted
|
|
10381
|
+
* @returns The frozen bundle, in the key order the compiler's own bundle uses
|
|
10382
|
+
*/
|
|
10383
|
+
publish(schema) {
|
|
10384
|
+
return INTRINSICS.freeze({
|
|
10385
|
+
schema,
|
|
10386
|
+
is: this.#is(),
|
|
10387
|
+
parse: this.#parse(),
|
|
10388
|
+
audit: this.#audit(),
|
|
10389
|
+
explain: this.#explain(),
|
|
10390
|
+
generate: this.#generate()
|
|
10391
|
+
});
|
|
10392
|
+
}
|
|
10393
|
+
#is() {
|
|
10394
|
+
return (value) => {
|
|
10395
|
+
const bundle = this.#bundle ?? this.#attempt();
|
|
10396
|
+
return bundle !== void 0 && bundle.is(value);
|
|
10397
|
+
};
|
|
10398
|
+
}
|
|
10399
|
+
#parse() {
|
|
10400
|
+
return (value) => {
|
|
10401
|
+
const bundle = this.#bundle ?? this.#attempt();
|
|
10402
|
+
return bundle === void 0 ? void 0 : bundle.parse(value);
|
|
10403
|
+
};
|
|
10404
|
+
}
|
|
10405
|
+
#audit() {
|
|
10406
|
+
return (value, path = []) => (this.#settled ?? this.#settle("compileAuditor")).auditor(value, path);
|
|
10407
|
+
}
|
|
10408
|
+
#explain() {
|
|
10409
|
+
return (value, path = []) => (this.#settled ?? this.#settle("compileReporter")).reporter(value, path);
|
|
10410
|
+
}
|
|
10411
|
+
#generate() {
|
|
10412
|
+
return (random) => (this.#settled ?? this.#settle("compileGenerator")).generator(random);
|
|
10413
|
+
}
|
|
10414
|
+
#attempt() {
|
|
10415
|
+
attempt(() => this.#settle("createContract"));
|
|
10416
|
+
return this.#bundle;
|
|
10417
|
+
}
|
|
10418
|
+
#settle(door) {
|
|
10419
|
+
return contain(() => {
|
|
10420
|
+
if (ShapePass.tampered()) throw new ContractError(`${door}: a host member this contract compiles on was replaced after it was created`, {
|
|
10421
|
+
code: "structure",
|
|
10422
|
+
context: {
|
|
10423
|
+
path: [],
|
|
10424
|
+
shape: "contract"
|
|
10425
|
+
}
|
|
10426
|
+
});
|
|
10427
|
+
const compiler = this.#pending ?? new ContractCompiler(this.#shape);
|
|
10428
|
+
this.#pending = void 0;
|
|
10429
|
+
this.#bundle = compiler.contract;
|
|
10430
|
+
this.#settled = compiler;
|
|
10431
|
+
return compiler;
|
|
10432
|
+
}, door);
|
|
10433
|
+
}
|
|
10434
|
+
};
|
|
9240
10435
|
// src/core/factories.ts
|
|
9241
10436
|
function createContract(shape) {
|
|
9242
|
-
return contain(() =>
|
|
10437
|
+
return contain(() => {
|
|
10438
|
+
const compiler = new ContractCompiler(shape);
|
|
10439
|
+
const expansion = ShapePass.expansionOf(shape);
|
|
10440
|
+
if (expansion === void 0 || expansion === 1) return compiler.contract;
|
|
10441
|
+
return new LazyContract(shape, compiler).publish(compiler.schema);
|
|
10442
|
+
}, "createContract");
|
|
9243
10443
|
}
|
|
9244
10444
|
// src/core/ValueInferer.ts
|
|
9245
10445
|
/**
|
|
@@ -9846,7 +11046,9 @@ function samplesToSchema(samples, options) {
|
|
|
9846
11046
|
* rather than parameters, so no caller can pre-populate either and change what
|
|
9847
11047
|
* the conversion widens. Construction observes nothing; `shape` runs the whole
|
|
9848
11048
|
* walk and every refusal it raises is published by that door under the door's
|
|
9849
|
-
* own name.
|
|
11049
|
+
* own name. A strict walk refuses where a lenient one widens, through the one
|
|
11050
|
+
* `#widen` both share, and its per-node `#inspect` refuses every keyword the
|
|
11051
|
+
* lenient precedence would read past.
|
|
9850
11052
|
*
|
|
9851
11053
|
* The recursion is `#` private for the same reason it is bounded: it is the
|
|
9852
11054
|
* class's defining spine, and its state has no meaning outside one call. The
|
|
@@ -9862,73 +11064,314 @@ var SchemaShaper = class SchemaShaper {
|
|
|
9862
11064
|
static #weakSet = WeakSet;
|
|
9863
11065
|
static #weakMap = WeakMap;
|
|
9864
11066
|
#source;
|
|
11067
|
+
#strict;
|
|
9865
11068
|
#visited;
|
|
9866
11069
|
#memo;
|
|
9867
|
-
|
|
11070
|
+
#enclosed;
|
|
11071
|
+
#exclusive;
|
|
11072
|
+
#path;
|
|
11073
|
+
#oneOfs;
|
|
11074
|
+
#built;
|
|
11075
|
+
#shared;
|
|
11076
|
+
constructor(schema, strict = false) {
|
|
9868
11077
|
this.#source = schema;
|
|
11078
|
+
this.#strict = strict;
|
|
9869
11079
|
this.#visited = new SchemaShaper.#weakSet();
|
|
9870
11080
|
this.#memo = new SchemaShaper.#weakMap();
|
|
11081
|
+
this.#enclosed = new SchemaShaper.#weakMap();
|
|
11082
|
+
this.#exclusive = new SchemaShaper.#weakMap();
|
|
11083
|
+
this.#path = [];
|
|
11084
|
+
this.#oneOfs = 0;
|
|
11085
|
+
this.#built = 0;
|
|
11086
|
+
this.#shared = false;
|
|
9871
11087
|
}
|
|
9872
11088
|
/**
|
|
9873
11089
|
* Converts the retained schema into a validating contract shape.
|
|
9874
11090
|
*
|
|
9875
|
-
* @returns The built shape, widened wherever
|
|
9876
|
-
* @throws {ContractError} When schema traversal fails
|
|
11091
|
+
* @returns The built shape, widened wherever a lenient schema is inexpressible
|
|
11092
|
+
* @throws {ContractError} When schema traversal fails, or when a strict conversion refuses
|
|
9877
11093
|
*/
|
|
9878
11094
|
shape() {
|
|
9879
|
-
|
|
11095
|
+
if (this.#strict && isRecord(this.#source) && INTRINSICS.own(this.#source, "default")) throw this.#refusal("a default needs an optional property to fill", "default");
|
|
11096
|
+
const shape = this.#convert(this.#source, 32, false);
|
|
11097
|
+
return !this.#strict && this.#exceeds(shape) ? this.#shallow(shape) : shape;
|
|
9880
11098
|
}
|
|
9881
|
-
#
|
|
9882
|
-
if (!
|
|
9883
|
-
|
|
9884
|
-
|
|
9885
|
-
|
|
11099
|
+
#exceeds(shape) {
|
|
11100
|
+
if (!this.#shared && this.#built <= 1024) return false;
|
|
11101
|
+
const validator = new ShapeValidator(shape);
|
|
11102
|
+
validator.validate();
|
|
11103
|
+
return (validator.expansion ?? 0) > COMPILE_NODE_LIMIT;
|
|
11104
|
+
}
|
|
11105
|
+
#shallow(shape) {
|
|
11106
|
+
const raw = rawShape({});
|
|
11107
|
+
switch (shape.category) {
|
|
11108
|
+
case "nullable": return nullableShape(this.#shallow(shape.inner));
|
|
11109
|
+
case "array": return arrayShape(raw, INTRINSICS.rebase({
|
|
11110
|
+
...shape.min === void 0 ? {} : { min: shape.min },
|
|
11111
|
+
...shape.max === void 0 ? {} : { max: shape.max },
|
|
11112
|
+
...shape.description === void 0 ? {} : { description: shape.description }
|
|
11113
|
+
}, null));
|
|
11114
|
+
case "object": {
|
|
11115
|
+
const pairs = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(INTRINSICS.keys(shape.properties)), [(key) => [key, shape.properties[key]?.category === "optional" ? optionalShape(raw) : raw]]);
|
|
11116
|
+
const properties = INTRINSICS.rebase(INTRINSICS.record({ [Symbol.iterator]: INTRINSICS.reflect.apply(INTRINSICS.bind, INTRINSICS.iterator, [pairs]) }), null);
|
|
11117
|
+
const extra = shape.additionalProperties;
|
|
11118
|
+
return objectShape(properties, INTRINSICS.rebase({
|
|
11119
|
+
additionalProperties: isObject(extra) ? raw : extra ?? false,
|
|
11120
|
+
...shape.description === void 0 ? {} : { description: shape.description }
|
|
11121
|
+
}, null));
|
|
11122
|
+
}
|
|
11123
|
+
default: return raw;
|
|
11124
|
+
}
|
|
11125
|
+
}
|
|
11126
|
+
#convert(schema, depth, enclosed) {
|
|
11127
|
+
if (!(depth > 0)) return this.#widen("a schema may not nest past the depth limit", void 0);
|
|
11128
|
+
if (!matchesRecordBrand(schema)) return this.#widen("every schema node must be a plain record", void 0);
|
|
11129
|
+
if (matchesVisited(this.#visited, schema)) return this.#widen("a schema may not contain a cycle", void 0);
|
|
11130
|
+
const memo = this.#oneOfs > 0 ? this.#exclusive : enclosed ? this.#enclosed : this.#memo;
|
|
11131
|
+
const depthMemo = INTRINSICS.reflect.apply(INTRINSICS.recall, memo, [schema]);
|
|
9886
11132
|
const cached = depthMemo === void 0 ? void 0 : INTRINSICS.reflect.apply(INTRINSICS.fetch, depthMemo, [depth]);
|
|
9887
|
-
if (cached)
|
|
11133
|
+
if (cached) {
|
|
11134
|
+
this.#shared = true;
|
|
11135
|
+
return cached;
|
|
11136
|
+
}
|
|
9888
11137
|
admitVisited(this.#visited, schema);
|
|
9889
11138
|
try {
|
|
9890
|
-
|
|
9891
|
-
|
|
11139
|
+
if (this.#strict) this.#inspect(schema);
|
|
11140
|
+
const built = this.#build(schema, depth, enclosed);
|
|
11141
|
+
const shape = INTRINSICS.own(schema, "nullable") && INTRINSICS.reflect.read(schema, "nullable") === true ? nullableShape(built) : built;
|
|
11142
|
+
retainDepth(memo, schema, depth, shape);
|
|
9892
11143
|
return shape;
|
|
9893
11144
|
} finally {
|
|
9894
11145
|
omitVisited(this.#visited, schema);
|
|
9895
11146
|
}
|
|
9896
11147
|
}
|
|
9897
|
-
#
|
|
9898
|
-
|
|
9899
|
-
if (
|
|
11148
|
+
#descend(schema, depth, enclosed, first, second) {
|
|
11149
|
+
this.#path[this.#path.length] = first;
|
|
11150
|
+
if (second !== void 0) this.#path[this.#path.length] = second;
|
|
11151
|
+
if (this.#strict && first !== "properties" && isRecord(schema) && INTRINSICS.own(schema, "default")) throw this.#refusal("a default needs an optional property to fill", "default");
|
|
11152
|
+
const shape = this.#convert(schema, depth, enclosed);
|
|
11153
|
+
this.#path.length -= second === void 0 ? 1 : 2;
|
|
11154
|
+
return shape;
|
|
11155
|
+
}
|
|
11156
|
+
#widen(message, description, first, second) {
|
|
11157
|
+
if (this.#strict) throw this.#refusal(message, first, second);
|
|
11158
|
+
this.#built += 1;
|
|
11159
|
+
return rawShape(description === void 0 ? {} : { description });
|
|
11160
|
+
}
|
|
11161
|
+
#describe(shape, description) {
|
|
11162
|
+
if (description === void 0) return shape;
|
|
11163
|
+
switch (shape.category) {
|
|
11164
|
+
case "optional": return shape;
|
|
11165
|
+
case "nullable": return nullableShape(this.#describe(shape.inner, description));
|
|
11166
|
+
case "raw": return rawShape({
|
|
11167
|
+
...shape.schema,
|
|
11168
|
+
description
|
|
11169
|
+
});
|
|
11170
|
+
default: return INTRINSICS.freeze({
|
|
11171
|
+
...shape,
|
|
11172
|
+
description
|
|
11173
|
+
});
|
|
11174
|
+
}
|
|
11175
|
+
}
|
|
11176
|
+
#refusal(message, first, second, third) {
|
|
11177
|
+
const path = pathOf(this.#path, first, second, third);
|
|
11178
|
+
return new ContractError(`schemaToShape: ${message} at ${truncateFaultText(renderPath(path) || "value", 160)}`, {
|
|
11179
|
+
code: "structure",
|
|
11180
|
+
context: {
|
|
11181
|
+
path,
|
|
11182
|
+
shape: "schema"
|
|
11183
|
+
}
|
|
11184
|
+
});
|
|
11185
|
+
}
|
|
11186
|
+
#inspect(schema) {
|
|
11187
|
+
const keys = INTRINSICS.keys(schema);
|
|
11188
|
+
for (const index of iterateIndices(() => keys.length)) {
|
|
11189
|
+
const key = keys[index];
|
|
11190
|
+
if (key === void 0) continue;
|
|
11191
|
+
if (!INTRINSICS.reflect.apply(INTRINSICS.some, STRICT_SCHEMA_KEYWORDS, [(keyword) => keyword === key])) throw this.#refusal("a strict conversion refuses a keyword it cannot honour", key);
|
|
11192
|
+
}
|
|
11193
|
+
this.#inspectAnnotations(schema);
|
|
11194
|
+
if (INTRINSICS.own(schema, "default") && !isJSONValue(schema.default)) throw this.#refusal("a default must be a JSON value", "default");
|
|
11195
|
+
const types = this.#inspectType(schema);
|
|
11196
|
+
this.#inspectForm(schema, types);
|
|
11197
|
+
const hasForm = INTRINSICS.own(schema, "enum") || INTRINSICS.own(schema, "oneOf") || INTRINSICS.own(schema, "anyOf");
|
|
11198
|
+
const object = types.length === 0 && INTRINSICS.own(schema, "properties") ? ["object"] : types;
|
|
11199
|
+
const effective = hasForm ? [] : object;
|
|
11200
|
+
this.#confine(schema, ["minLength", "maxLength"], this.#names(effective, "string"));
|
|
11201
|
+
this.#confine(schema, ["minimum", "maximum"], this.#names(effective, "number", "integer"));
|
|
11202
|
+
this.#confine(schema, [
|
|
11203
|
+
"items",
|
|
11204
|
+
"minItems",
|
|
11205
|
+
"maxItems"
|
|
11206
|
+
], this.#names(effective, "array"));
|
|
11207
|
+
this.#confine(schema, [
|
|
11208
|
+
"properties",
|
|
11209
|
+
"required",
|
|
11210
|
+
"additionalProperties"
|
|
11211
|
+
], this.#names(effective, "object"));
|
|
11212
|
+
this.#inspectLength(INTRINSICS.own(schema, "minLength") ? schema.minLength : void 0, INTRINSICS.own(schema, "maxLength") ? schema.maxLength : void 0, "minLength", "maxLength");
|
|
11213
|
+
this.#inspectLength(INTRINSICS.own(schema, "minItems") ? schema.minItems : void 0, INTRINSICS.own(schema, "maxItems") ? schema.maxItems : void 0, "minItems", "maxItems");
|
|
11214
|
+
this.#inspectRange(schema, this.#names(effective, "integer"));
|
|
11215
|
+
this.#inspectObject(schema);
|
|
11216
|
+
}
|
|
11217
|
+
#inspectAnnotations(schema) {
|
|
11218
|
+
const texts = [
|
|
11219
|
+
"title",
|
|
11220
|
+
"description",
|
|
11221
|
+
"$schema",
|
|
11222
|
+
"$id",
|
|
11223
|
+
"$comment"
|
|
11224
|
+
];
|
|
11225
|
+
for (const index of iterateIndices(() => texts.length)) {
|
|
11226
|
+
const keyword = texts[index];
|
|
11227
|
+
if (keyword === void 0) continue;
|
|
11228
|
+
const value = INTRINSICS.own(schema, keyword) ? INTRINSICS.reflect.read(schema, keyword) : void 0;
|
|
11229
|
+
if (value !== void 0 && !isString(value)) throw this.#refusal(`${keyword} must be a string`, keyword);
|
|
11230
|
+
}
|
|
11231
|
+
const flags = [
|
|
11232
|
+
"deprecated",
|
|
11233
|
+
"readOnly",
|
|
11234
|
+
"writeOnly"
|
|
11235
|
+
];
|
|
11236
|
+
for (const index of iterateIndices(() => flags.length)) {
|
|
11237
|
+
const keyword = flags[index];
|
|
11238
|
+
if (keyword === void 0) continue;
|
|
11239
|
+
const value = INTRINSICS.own(schema, keyword) ? INTRINSICS.reflect.read(schema, keyword) : void 0;
|
|
11240
|
+
if (value !== void 0 && !isBoolean(value)) throw this.#refusal(`${keyword} must be a boolean`, keyword);
|
|
11241
|
+
}
|
|
11242
|
+
const examples = INTRINSICS.own(schema, "examples") ? INTRINSICS.reflect.read(schema, "examples") : void 0;
|
|
11243
|
+
if (examples !== void 0 && !isArray(examples)) throw this.#refusal("examples must be an array", "examples");
|
|
11244
|
+
}
|
|
11245
|
+
#inspectType(schema) {
|
|
11246
|
+
const declared = INTRINSICS.own(schema, "type") ? schema.type : void 0;
|
|
11247
|
+
if (declared === void 0) return [];
|
|
11248
|
+
const names = isArray(declared) ? this.#entries(declared, "type") : [declared];
|
|
11249
|
+
const known = names.length > 0 && this.#unique(names);
|
|
11250
|
+
const types = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(JSON_SCHEMA_TYPES), [(type) => INTRINSICS.reflect.apply(INTRINSICS.some, names, [(name) => name === type])]);
|
|
11251
|
+
if (!known || types.length !== names.length) throw this.#refusal("type must name the supported types", "type");
|
|
11252
|
+
return types;
|
|
11253
|
+
}
|
|
11254
|
+
#inspectForm(schema, types) {
|
|
11255
|
+
if (INTRINSICS.own(schema, "enum")) {
|
|
11256
|
+
const members = this.#entries(schema.enum, "enum");
|
|
11257
|
+
const malformed = INTRINSICS.reflect.apply(INTRINSICS.some, members, [(entry) => entry !== null && (!isLiteralValue(entry) || typeof entry === "number" && !isFiniteNumber(entry))]);
|
|
11258
|
+
if (members.length === 0 || malformed || !this.#unique(members)) throw this.#refusal("enum must list unique finite primitives", "enum");
|
|
11259
|
+
if (INTRINSICS.reflect.apply(INTRINSICS.some, members, [(entry) => types.length > 0 && !this.#fits(entry, types)])) throw this.#refusal("an enum member contradicts the type", "enum");
|
|
11260
|
+
if (INTRINSICS.own(schema, "oneOf")) throw this.#refusal("a strict conversion refuses oneOf beside enum", "oneOf");
|
|
11261
|
+
if (INTRINSICS.own(schema, "anyOf")) throw this.#refusal("a strict conversion refuses anyOf beside enum", "anyOf");
|
|
11262
|
+
return;
|
|
11263
|
+
}
|
|
11264
|
+
const keywords = ["oneOf", "anyOf"];
|
|
11265
|
+
for (const index of iterateIndices(() => keywords.length)) {
|
|
11266
|
+
const keyword = keywords[index];
|
|
11267
|
+
if (keyword === void 0 || !INTRINSICS.own(schema, keyword)) continue;
|
|
11268
|
+
const variants = this.#entries(INTRINSICS.reflect.read(schema, keyword), keyword);
|
|
11269
|
+
if (variants.length === 0) throw this.#refusal(`${keyword} needs a variant`, keyword);
|
|
11270
|
+
for (const variantIndex of iterateIndices(() => variants.length)) if (!isRecord(variants[variantIndex])) throw this.#refusal("every variant must be a schema", keyword, INTRINSICS.text(variantIndex));
|
|
11271
|
+
}
|
|
11272
|
+
const union = INTRINSICS.own(schema, "oneOf") || INTRINSICS.own(schema, "anyOf");
|
|
11273
|
+
if (INTRINSICS.own(schema, "oneOf") && INTRINSICS.own(schema, "anyOf")) throw this.#refusal("a strict conversion refuses anyOf beside oneOf", "anyOf");
|
|
11274
|
+
if (union && types.length > 0) throw this.#refusal("a strict conversion refuses type beside a union", "type");
|
|
11275
|
+
}
|
|
11276
|
+
#inspectLength(min, max, minKey, maxKey) {
|
|
11277
|
+
if (min !== void 0 && !(INTRINSICS.safe(min) && INTRINSICS.numeric(min) >= 0)) throw this.#refusal("a length bound must be a non-negative safe integer", minKey);
|
|
11278
|
+
if (max !== void 0 && !(INTRINSICS.safe(max) && INTRINSICS.numeric(max) >= 0)) throw this.#refusal("a length bound must be a non-negative safe integer", maxKey);
|
|
11279
|
+
if (isFiniteNumber(min) && isFiniteNumber(max) && min > max) throw this.#refusal("a length range may not be contradictory", minKey);
|
|
11280
|
+
}
|
|
11281
|
+
#inspectRange(schema, integer) {
|
|
11282
|
+
const min = INTRINSICS.own(schema, "minimum") ? schema.minimum : void 0;
|
|
11283
|
+
const max = INTRINSICS.own(schema, "maximum") ? schema.maximum : void 0;
|
|
11284
|
+
if (min !== void 0 && !isFiniteNumber(min)) throw this.#refusal("a range bound must be a finite number", "minimum");
|
|
11285
|
+
if (max !== void 0 && !isFiniteNumber(max)) throw this.#refusal("a range bound must be a finite number", "maximum");
|
|
11286
|
+
if (isFiniteNumber(min) && isFiniteNumber(max)) {
|
|
11287
|
+
if (min > max) throw this.#refusal("a range may not be contradictory", "minimum");
|
|
11288
|
+
if (integer && INTRINSICS.ceil(min) > INTRINSICS.floor(max)) throw this.#refusal("an integer range may not be empty", "minimum");
|
|
11289
|
+
}
|
|
11290
|
+
}
|
|
11291
|
+
#inspectObject(schema) {
|
|
11292
|
+
const properties = INTRINSICS.own(schema, "properties") ? schema.properties : void 0;
|
|
11293
|
+
if (properties !== void 0 && !isRecord(properties)) throw this.#refusal("properties must be a plain record", "properties");
|
|
11294
|
+
const extra = INTRINSICS.own(schema, "additionalProperties") ? schema.additionalProperties : void 0;
|
|
11295
|
+
if (extra !== void 0 && !isBoolean(extra) && !isRecord(extra)) throw this.#refusal("additionalProperties must be a boolean or a schema", "additionalProperties");
|
|
11296
|
+
if (!INTRINSICS.own(schema, "required")) return;
|
|
11297
|
+
const names = this.#entries(schema.required, "required");
|
|
11298
|
+
if (INTRINSICS.reflect.apply(INTRINSICS.some, names, [(name) => !isString(name) || !isRecord(properties) || !INTRINSICS.own(properties, name)]) || !this.#unique(names)) throw this.#refusal("required must list unique declared properties", "required");
|
|
11299
|
+
}
|
|
11300
|
+
#confine(schema, keywords, applies) {
|
|
11301
|
+
if (applies) return;
|
|
11302
|
+
for (const index of iterateIndices(() => keywords.length)) {
|
|
11303
|
+
const keyword = keywords[index];
|
|
11304
|
+
if (keyword !== void 0 && INTRINSICS.own(schema, keyword)) throw this.#refusal("a strict conversion refuses a keyword this node never reads", keyword);
|
|
11305
|
+
}
|
|
11306
|
+
}
|
|
11307
|
+
#names(types, ...names) {
|
|
11308
|
+
return INTRINSICS.reflect.apply(INTRINSICS.some, types, [(type) => INTRINSICS.reflect.apply(INTRINSICS.some, names, [(name) => name === type])]);
|
|
11309
|
+
}
|
|
11310
|
+
#fits(entry, types) {
|
|
11311
|
+
if (entry === null) return this.#names(types, "null");
|
|
11312
|
+
if (isString(entry)) return this.#names(types, "string");
|
|
11313
|
+
if (isBoolean(entry)) return this.#names(types, "boolean");
|
|
11314
|
+
return isInteger(entry) ? this.#names(types, "number", "integer") : this.#names(types, "number");
|
|
11315
|
+
}
|
|
11316
|
+
#entries(value, keyword) {
|
|
11317
|
+
if (!isArray(value)) throw this.#refusal(`${keyword} must be an array`, keyword);
|
|
11318
|
+
const snapshot = readArrayEntries(value);
|
|
11319
|
+
if (isFailure(snapshot)) throw snapshot.error;
|
|
11320
|
+
if (!snapshot.value.dense) throw this.#refusal(`${keyword} must be a dense array`, keyword);
|
|
11321
|
+
return snapshot.value.entries;
|
|
11322
|
+
}
|
|
11323
|
+
#unique(entries) {
|
|
11324
|
+
const seen = collectMembers([]);
|
|
11325
|
+
for (const index of iterateIndices(() => entries.length)) {
|
|
11326
|
+
const entry = entries[index];
|
|
11327
|
+
if (matchesMember(seen, entry)) return false;
|
|
11328
|
+
admitMember(seen, entry);
|
|
11329
|
+
}
|
|
11330
|
+
return true;
|
|
11331
|
+
}
|
|
11332
|
+
#build(schema, depth, enclosed) {
|
|
11333
|
+
this.#built += 1;
|
|
11334
|
+
const description = INTRINSICS.own(schema, "description") && isString(schema.description) ? schema.description : void 0;
|
|
11335
|
+
if (INTRINSICS.own(schema, "$ref")) return this.#widen("a reference is not resolved", description, "$ref");
|
|
11336
|
+
if (INTRINSICS.own(schema, "enum") && isArray(schema.enum)) {
|
|
9900
11337
|
const observed = INTRINSICS.from(iterateIndices(() => INTRINSICS.reflect.apply(INTRINSICS.reflect.read, void 0, [schema, "enum"]).length), (index) => INTRINSICS.reflect.apply(INTRINSICS.reflect.read, void 0, [schema, "enum"])[index]);
|
|
9901
|
-
|
|
11338
|
+
if (INTRINSICS.reflect.apply(INTRINSICS.some, observed, [(entry) => entry !== null && (!isLiteralValue(entry) || typeof entry === "number" && !isFiniteNumber(entry))])) return this.#widen("an enum entry has no literal form", description, "enum");
|
|
11339
|
+
const valid = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [(entry) => entry !== null]);
|
|
11340
|
+
const nullable = valid.length < observed.length;
|
|
9902
11341
|
const pairs = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(valid), [(entry, index) => [`${typeof entry}:${INTRINSICS.text(entry)}`, index]]);
|
|
9903
11342
|
const reversed = INTRINSICS.reflect.apply(INTRINSICS.flip, pairs, []);
|
|
9904
11343
|
const first = INTRINSICS.record({ [Symbol.iterator]: INTRINSICS.reflect.apply(INTRINSICS.bind, INTRINSICS.iterator, [reversed]) });
|
|
9905
11344
|
const literals = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(valid), [(entry, index) => first[`${typeof entry}:${INTRINSICS.text(entry)}`] === index]);
|
|
9906
|
-
if (literals.length > 0)
|
|
11345
|
+
if (literals.length > 0) {
|
|
11346
|
+
const literal = literalShape(literals, description === void 0 ? void 0 : { description });
|
|
11347
|
+
return nullable ? nullableShape(literal) : literal;
|
|
11348
|
+
}
|
|
11349
|
+
if (nullable) return nullShape(description === void 0 ? void 0 : { description });
|
|
9907
11350
|
}
|
|
9908
|
-
if (isArray(schema.oneOf)) {
|
|
9909
|
-
const
|
|
9910
|
-
|
|
9911
|
-
if (records.length > 256) return rawShape(description === void 0 ? {} : { description });
|
|
9912
|
-
const variants = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(records), [(entry) => this.#convert(entry, depth - 1)]);
|
|
9913
|
-
if (variants.length > 0) return INTRINSICS.reflect.apply(oneOfShape, void 0, variants);
|
|
11351
|
+
if (INTRINSICS.own(schema, "oneOf") && isArray(schema.oneOf)) {
|
|
11352
|
+
const union = this.#buildUnion(schema.oneOf, "oneOf", depth, description, enclosed);
|
|
11353
|
+
if (union !== void 0) return union;
|
|
9914
11354
|
}
|
|
9915
|
-
if (isArray(schema.anyOf)) {
|
|
9916
|
-
const
|
|
9917
|
-
|
|
9918
|
-
if (records.length > 256) return rawShape(description === void 0 ? {} : { description });
|
|
9919
|
-
const variants = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(records), [(entry) => this.#convert(entry, depth - 1)]);
|
|
9920
|
-
if (variants.length > 0) return INTRINSICS.reflect.apply(unionShape, void 0, variants);
|
|
11355
|
+
if (INTRINSICS.own(schema, "anyOf") && isArray(schema.anyOf)) {
|
|
11356
|
+
const union = this.#buildUnion(schema.anyOf, "anyOf", depth, description, enclosed);
|
|
11357
|
+
if (union !== void 0) return union;
|
|
9921
11358
|
}
|
|
9922
|
-
const category = schema.type;
|
|
11359
|
+
const category = INTRINSICS.own(schema, "type") ? schema.type : void 0;
|
|
9923
11360
|
if (isArray(category)) {
|
|
9924
11361
|
const observed = INTRINSICS.from(parseEnumValues(category, JSON_SCHEMA_TYPES));
|
|
9925
|
-
if (INTRINSICS.reflect.apply(INTRINSICS.some, observed, [(entry) => entry === void 0])) return
|
|
11362
|
+
if (INTRINSICS.reflect.apply(INTRINSICS.some, observed, [(entry) => entry === void 0])) return this.#widen("type must name the supported types", description, "type");
|
|
9926
11363
|
const members = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [(member, index) => INTRINSICS.reflect.apply(INTRINSICS.find, observed, [(entry) => entry === member]) === index]);
|
|
9927
|
-
if (members.length === 0 || members.length > 256) return
|
|
11364
|
+
if (members.length === 0 || members.length > 256) return this.#widen("type must name the supported types", description, "type");
|
|
11365
|
+
const others = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(members), [(member) => member !== "null"]);
|
|
11366
|
+
const other = others[0];
|
|
11367
|
+
if (members.length === 2 && others.length === 1 && other !== void 0) return nullableShape(this.#build({
|
|
11368
|
+
...schema,
|
|
11369
|
+
type: other
|
|
11370
|
+
}, depth, enclosed));
|
|
9928
11371
|
const variants = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(members), [(member) => this.#build({
|
|
9929
11372
|
...schema,
|
|
9930
11373
|
type: member
|
|
9931
|
-
}, depth)]);
|
|
11374
|
+
}, depth, enclosed || members.length > 1)]);
|
|
9932
11375
|
const first = variants[0];
|
|
9933
11376
|
if (variants.length === 1 && first !== void 0) return first;
|
|
9934
11377
|
const union = INTRINSICS.reflect.apply(unionShape, void 0, variants);
|
|
@@ -9937,45 +11380,88 @@ var SchemaShaper = class SchemaShaper {
|
|
|
9937
11380
|
description
|
|
9938
11381
|
});
|
|
9939
11382
|
}
|
|
9940
|
-
const type = isString(category) ? schema.type : void 0;
|
|
9941
|
-
if (type === "string")
|
|
9942
|
-
|
|
9943
|
-
|
|
9944
|
-
|
|
9945
|
-
|
|
9946
|
-
|
|
9947
|
-
|
|
9948
|
-
|
|
11383
|
+
const type = isString(category) && INTRINSICS.own(schema, "type") ? schema.type : void 0;
|
|
11384
|
+
if (type === "string") {
|
|
11385
|
+
const bounds = deriveLengthBounds(INTRINSICS.own(schema, "minLength") ? schema.minLength : void 0, INTRINSICS.own(schema, "maxLength") ? schema.maxLength : void 0);
|
|
11386
|
+
return stringShape(INTRINSICS.rebase({
|
|
11387
|
+
...bounds,
|
|
11388
|
+
...description === void 0 ? {} : { description }
|
|
11389
|
+
}, null));
|
|
11390
|
+
}
|
|
11391
|
+
if (type === "number") {
|
|
11392
|
+
const bounds = deriveRangeBounds(INTRINSICS.own(schema, "minimum") ? schema.minimum : void 0, INTRINSICS.own(schema, "maximum") ? schema.maximum : void 0);
|
|
11393
|
+
return numberShape(INTRINSICS.rebase({
|
|
11394
|
+
...bounds,
|
|
11395
|
+
...description === void 0 ? {} : { description }
|
|
11396
|
+
}, null));
|
|
11397
|
+
}
|
|
9949
11398
|
if (type === "integer") {
|
|
9950
|
-
const bounds = deriveRangeBounds(schema.minimum, schema.maximum);
|
|
9951
|
-
return integerShape(INTRINSICS.ceil(bounds.min ?? Number.NEGATIVE_INFINITY) > INTRINSICS.floor(bounds.max ?? Number.POSITIVE_INFINITY) ? description === void 0 ? void 0 : { description } : {
|
|
11399
|
+
const bounds = deriveRangeBounds(INTRINSICS.own(schema, "minimum") ? schema.minimum : void 0, INTRINSICS.own(schema, "maximum") ? schema.maximum : void 0);
|
|
11400
|
+
return integerShape(INTRINSICS.ceil(bounds.min ?? Number.NEGATIVE_INFINITY) > INTRINSICS.floor(bounds.max ?? Number.POSITIVE_INFINITY) ? description === void 0 ? void 0 : INTRINSICS.rebase({ description }, null) : INTRINSICS.rebase({
|
|
9952
11401
|
...bounds,
|
|
9953
11402
|
...description === void 0 ? {} : { description }
|
|
9954
|
-
});
|
|
11403
|
+
}, null));
|
|
9955
11404
|
}
|
|
9956
11405
|
if (type === "boolean") return booleanShape(description === void 0 ? void 0 : { description });
|
|
9957
11406
|
if (type === "null") return nullShape(description === void 0 ? void 0 : { description });
|
|
9958
|
-
if (type === "array")
|
|
9959
|
-
|
|
9960
|
-
|
|
9961
|
-
|
|
9962
|
-
|
|
9963
|
-
|
|
11407
|
+
if (type === "array") {
|
|
11408
|
+
const items = INTRINSICS.own(schema, "prefixItems") ? rawShape({}) : INTRINSICS.own(schema, "items") && isRecord(schema.items) ? this.#descend(schema.items, depth - 1, enclosed, "items") : this.#widen("an array needs an items schema", void 0, "items");
|
|
11409
|
+
const bounds = deriveLengthBounds(INTRINSICS.own(schema, "minItems") ? schema.minItems : void 0, INTRINSICS.own(schema, "maxItems") ? schema.maxItems : void 0);
|
|
11410
|
+
return arrayShape(items, INTRINSICS.rebase({
|
|
11411
|
+
...bounds,
|
|
11412
|
+
...description === void 0 ? {} : { description }
|
|
11413
|
+
}, null));
|
|
11414
|
+
}
|
|
11415
|
+
if (type === "object" || this.#strict && type === void 0 && INTRINSICS.own(schema, "properties") && isRecord(schema.properties)) return this.#buildObject(schema, depth, description, enclosed);
|
|
11416
|
+
if (type === void 0 && INTRINSICS.own(schema, "properties") && isRecord(schema.properties)) return this.#describe(unionShape(this.#buildObject(schema, depth, void 0, true), stringShape(), numberShape(), booleanShape(), nullShape(), arrayShape(rawShape({}))), description);
|
|
11417
|
+
return this.#widen("a schema must name a type, an enum, or a union", description);
|
|
11418
|
+
}
|
|
11419
|
+
#buildUnion(list, keyword, depth, description, enclosed) {
|
|
11420
|
+
const observed = INTRINSICS.from(iterateIndices(() => list.length), (index) => list[index]);
|
|
11421
|
+
const arms = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(observed), [(entry) => entry === true || isRecord(entry)]);
|
|
11422
|
+
if (arms.length > 256) return this.#widen(`${keyword} exceeds the breadth limit`, description, keyword);
|
|
11423
|
+
const nulls = INTRINSICS.reflect.apply(INTRINSICS.select, readIndexView(arms), [(entry) => entry !== true && INTRINSICS.own(entry, "type") && entry.type === "null" && !INTRINSICS.own(entry, "$ref") && !INTRINSICS.own(entry, "enum") && !INTRINSICS.own(entry, "oneOf") && !INTRINSICS.own(entry, "anyOf")]);
|
|
11424
|
+
const hasTrue = INTRINSICS.reflect.apply(INTRINSICS.some, arms, [(entry) => entry === true]);
|
|
11425
|
+
const paired = arms.length === 2 && nulls.length === 1 && !hasTrue && !(this.#strict && keyword === "oneOf");
|
|
11426
|
+
const exclusive = this.#strict && keyword === "oneOf" ? 1 : 0;
|
|
11427
|
+
this.#oneOfs += exclusive;
|
|
11428
|
+
const variants = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(arms), [(entry, index) => {
|
|
11429
|
+
if (entry !== true) {
|
|
11430
|
+
const position = paired ? enclosed : true;
|
|
11431
|
+
return this.#descend(entry, depth - 1, position, keyword, INTRINSICS.text(index));
|
|
11432
|
+
}
|
|
11433
|
+
this.#built += 1;
|
|
11434
|
+
return rawShape({});
|
|
11435
|
+
}]);
|
|
11436
|
+
this.#oneOfs -= exclusive;
|
|
11437
|
+
const other = variants[arms[0] === nulls[0] ? 1 : 0];
|
|
11438
|
+
if (paired && other !== void 0) return nullableShape(this.#describe(other, description));
|
|
11439
|
+
if (variants.length > 0) {
|
|
11440
|
+
const build = this.#strict && keyword === "oneOf" ? oneOfShape : unionShape;
|
|
11441
|
+
return this.#describe(INTRINSICS.reflect.apply(build, void 0, variants), description);
|
|
11442
|
+
}
|
|
11443
|
+
return INTRINSICS.reflect.apply(INTRINSICS.some, observed, [(entry) => entry === false]) ? this.#widen(`${keyword} admits nothing`, description, keyword) : void 0;
|
|
9964
11444
|
}
|
|
9965
|
-
#buildObject(schema, depth, description) {
|
|
9966
|
-
|
|
9967
|
-
const
|
|
11445
|
+
#buildObject(schema, depth, description, enclosed) {
|
|
11446
|
+
if (this.#oneOfs > 0 && !INTRINSICS.own(schema, "additionalProperties")) throw this.#refusal("an object below a oneOf must declare additionalProperties, because closing it could change which arms match", "additionalProperties");
|
|
11447
|
+
const propertiesSource = INTRINSICS.own(schema, "properties") && isRecord(schema.properties) ? schema.properties : void 0;
|
|
11448
|
+
const requiredSource = INTRINSICS.own(schema, "required") && isArray(schema.required) ? INTRINSICS.from(iterateIndices(() => INTRINSICS.reflect.apply(INTRINSICS.reflect.read, void 0, [schema, "required"]).length), (index) => INTRINSICS.reflect.apply(INTRINSICS.reflect.read, void 0, [schema, "required"])[index]) : [];
|
|
9968
11449
|
const allKeys = propertiesSource === void 0 ? [] : INTRINSICS.keys(propertiesSource);
|
|
9969
11450
|
const truncated = allKeys.length > 256;
|
|
11451
|
+
if (this.#strict && truncated) throw this.#refusal("properties exceeds the breadth limit", "properties");
|
|
9970
11452
|
const keys = limitEntries(allKeys, 256);
|
|
11453
|
+
const extra = INTRINSICS.own(schema, "additionalProperties") ? schema.additionalProperties : void 0;
|
|
11454
|
+
const unread = truncated || INTRINSICS.own(schema, "patternProperties");
|
|
11455
|
+
const open = unread || extra !== false && (!this.#strict || extra !== void 0);
|
|
9971
11456
|
const pairs = INTRINSICS.reflect.apply(INTRINSICS.project, readIndexView(keys), [(key) => {
|
|
9972
|
-
const child = propertiesSource
|
|
9973
|
-
const childShape = isRecord(child) ? this.#
|
|
9974
|
-
|
|
11457
|
+
const child = propertiesSource !== void 0 && INTRINSICS.own(propertiesSource, key) ? propertiesSource[key] : void 0;
|
|
11458
|
+
const childShape = isRecord(child) ? this.#descend(child, depth - 1, enclosed, "properties", key) : this.#widen("every property schema must be a plain record", void 0, "properties", key);
|
|
11459
|
+
if (!INTRINSICS.reflect.apply(INTRINSICS.some, requiredSource, [(entry) => isString(entry) && entry === key])) return [key, this.#wrap(key, child, childShape, open || enclosed)];
|
|
11460
|
+
if (this.#strict && isRecord(child) && INTRINSICS.own(child, "default")) throw this.#refusal("a default needs an optional property to fill", "properties", key, "default");
|
|
11461
|
+
return [key, childShape];
|
|
9975
11462
|
}]);
|
|
9976
11463
|
const properties = INTRINSICS.rebase(INTRINSICS.record({ [Symbol.iterator]: INTRINSICS.reflect.apply(INTRINSICS.bind, INTRINSICS.iterator, [pairs]) }), null);
|
|
9977
|
-
const
|
|
9978
|
-
const additionalProperties = truncated ? true : extra === false ? false : isRecord(extra) ? this.#convert(extra, depth - 1) : true;
|
|
11464
|
+
const additionalProperties = unread ? true : isRecord(extra) ? this.#descend(extra, depth - 1, enclosed, "additionalProperties") : open;
|
|
9979
11465
|
return INTRINSICS.freeze({
|
|
9980
11466
|
category: "object",
|
|
9981
11467
|
properties: INTRINSICS.freeze(properties),
|
|
@@ -9983,9 +11469,115 @@ var SchemaShaper = class SchemaShaper {
|
|
|
9983
11469
|
...description === void 0 ? {} : { description }
|
|
9984
11470
|
});
|
|
9985
11471
|
}
|
|
11472
|
+
#wrap(key, child, shape, sealed) {
|
|
11473
|
+
this.#built += 1;
|
|
11474
|
+
if (!isRecord(child) || !INTRINSICS.own(child, "default")) return optionalShape(shape);
|
|
11475
|
+
const value = child.default;
|
|
11476
|
+
if (!isJSONValue(value)) return optionalShape(shape);
|
|
11477
|
+
if (this.#strict) {
|
|
11478
|
+
if (sealed) throw new ContractError("schemaToShape: a default cannot fill under a union or on a property of an open object; close the object or remove the default", {
|
|
11479
|
+
code: "placement",
|
|
11480
|
+
context: {
|
|
11481
|
+
path: pathOf(this.#path, "properties", key, "default"),
|
|
11482
|
+
shape: "schema"
|
|
11483
|
+
}
|
|
11484
|
+
});
|
|
11485
|
+
if (new ContractCompiler(shape).guard(value)) return optionalShape(shape, { default: value });
|
|
11486
|
+
throw this.#refusal("a default must satisfy its schema", "properties", key, "default");
|
|
11487
|
+
}
|
|
11488
|
+
const leaf = shape.category === "string" || shape.category === "number" || shape.category === "boolean" || shape.category === "null" || shape.category === "literal";
|
|
11489
|
+
return !sealed && leaf && new ContractCompiler(shape).guard(value) ? optionalShape(shape, { default: value }) : optionalShape(shape);
|
|
11490
|
+
}
|
|
11491
|
+
};
|
|
11492
|
+
// src/core/FaultShaper.ts
|
|
11493
|
+
/**
|
|
11494
|
+
* Retains a lazily built fault declaration without building shapes during module evaluation.
|
|
11495
|
+
*
|
|
11496
|
+
* @example
|
|
11497
|
+
* ```ts
|
|
11498
|
+
* FaultShaper.shape === FaultShaper.shape // true
|
|
11499
|
+
* ```
|
|
11500
|
+
*/
|
|
11501
|
+
var FaultShaper = class FaultShaper {
|
|
11502
|
+
static #shape;
|
|
11503
|
+
/** Returns the shared fault declaration, building it on the first read. */
|
|
11504
|
+
static get shape() {
|
|
11505
|
+
return FaultShaper.#shape ??= new FaultShaper().build();
|
|
11506
|
+
}
|
|
11507
|
+
/**
|
|
11508
|
+
* Builds a closed fault union whose inferred values satisfy the audit fault contract.
|
|
11509
|
+
*
|
|
11510
|
+
* @example
|
|
11511
|
+
* ```ts
|
|
11512
|
+
* createContract(new FaultShaper().build()).is({ reason: 'extra', path: [] }) // true
|
|
11513
|
+
* ```
|
|
11514
|
+
*/
|
|
11515
|
+
build() {
|
|
11516
|
+
const path = unionShape(stringShape(), arrayShape(stringShape()));
|
|
11517
|
+
const expected = literalShape(FAULT_KINDS);
|
|
11518
|
+
const hints = arrayShape(unionShape(stringShape(), numberShape(), booleanShape()));
|
|
11519
|
+
return unionShape(objectShape({
|
|
11520
|
+
reason: literalShape(["type"]),
|
|
11521
|
+
path,
|
|
11522
|
+
expected,
|
|
11523
|
+
received: stringShape()
|
|
11524
|
+
}), objectShape({
|
|
11525
|
+
reason: literalShape(["missing"]),
|
|
11526
|
+
path,
|
|
11527
|
+
expected
|
|
11528
|
+
}), objectShape({
|
|
11529
|
+
reason: literalShape(["constraint"]),
|
|
11530
|
+
path,
|
|
11531
|
+
expected,
|
|
11532
|
+
constraint: literalShape(FAULT_CONSTRAINTS),
|
|
11533
|
+
limit: optionalShape(unionShape(numberShape(), stringShape())),
|
|
11534
|
+
received: stringShape()
|
|
11535
|
+
}), objectShape({
|
|
11536
|
+
reason: literalShape(["variant"]),
|
|
11537
|
+
path,
|
|
11538
|
+
variants: integerShape({ min: 0 })
|
|
11539
|
+
}), objectShape({
|
|
11540
|
+
reason: literalShape(["variant"]),
|
|
11541
|
+
path,
|
|
11542
|
+
variants: integerShape({ min: 0 }),
|
|
11543
|
+
key: stringShape(),
|
|
11544
|
+
expected: hints
|
|
11545
|
+
}), objectShape({
|
|
11546
|
+
reason: literalShape(["oneOf"]),
|
|
11547
|
+
path,
|
|
11548
|
+
matched: integerShape({ min: 0 })
|
|
11549
|
+
}), objectShape({
|
|
11550
|
+
reason: literalShape(["oneOf"]),
|
|
11551
|
+
path,
|
|
11552
|
+
matched: integerShape({ min: 0 }),
|
|
11553
|
+
key: stringShape(),
|
|
11554
|
+
expected: hints
|
|
11555
|
+
}), objectShape({
|
|
11556
|
+
reason: literalShape(["extra"]),
|
|
11557
|
+
path
|
|
11558
|
+
}));
|
|
11559
|
+
}
|
|
11560
|
+
static {
|
|
11561
|
+
pinMembers(FaultShaper.prototype, "FaultShaper");
|
|
11562
|
+
}
|
|
9986
11563
|
};
|
|
9987
11564
|
// src/core/shapers.ts
|
|
9988
11565
|
/**
|
|
11566
|
+
* Returns the shared closed audit-fault shape, building it on the first call.
|
|
11567
|
+
*
|
|
11568
|
+
* @remarks
|
|
11569
|
+
* Numeric bounds, counts, and discriminator literals must be finite. Discriminator hints
|
|
11570
|
+
* carry both key and expected together. The inferred union is assignable to AuditFault.
|
|
11571
|
+
*
|
|
11572
|
+
* @example
|
|
11573
|
+
* ```ts
|
|
11574
|
+
* createContract(auditFaultShape()).is({ reason: 'extra', path: ['typo'] }) // true
|
|
11575
|
+
* ```
|
|
11576
|
+
*/
|
|
11577
|
+
function auditFaultShape() {
|
|
11578
|
+
return contain(() => FaultShaper.shape, "auditFaultShape");
|
|
11579
|
+
}
|
|
11580
|
+
/**
|
|
9989
11581
|
* Builds a string {@link StringShape}.
|
|
9990
11582
|
*
|
|
9991
11583
|
* @remarks
|
|
@@ -10062,8 +11654,9 @@ function stringShape(options) {
|
|
|
10062
11654
|
...patternSnapshot === void 0 ? {} : { pattern: new INTRINSICS.pattern(patternSnapshot.source) },
|
|
10063
11655
|
...safe?.description === void 0 ? {} : { description: safe.description }
|
|
10064
11656
|
};
|
|
11657
|
+
if (patternSnapshot === void 0 && !ShapePass.polluted()) return ShapePass.seal(shape);
|
|
10065
11658
|
new ShapeValidator(shape).validate();
|
|
10066
|
-
return cloneShape(shape);
|
|
11659
|
+
return ShapePass.seal(cloneShape(shape));
|
|
10067
11660
|
}, "stringShape");
|
|
10068
11661
|
}
|
|
10069
11662
|
/**
|
|
@@ -10115,8 +11708,7 @@ function numberShape(options) {
|
|
|
10115
11708
|
...safe?.integer === void 0 ? {} : { integer: safe.integer },
|
|
10116
11709
|
...safe?.description === void 0 ? {} : { description: safe.description }
|
|
10117
11710
|
};
|
|
10118
|
-
|
|
10119
|
-
return INTRINSICS.freeze(result);
|
|
11711
|
+
return ShapePass.seal(result);
|
|
10120
11712
|
}, "numberShape");
|
|
10121
11713
|
}
|
|
10122
11714
|
/**
|
|
@@ -10160,8 +11752,7 @@ function booleanShape(options) {
|
|
|
10160
11752
|
category: "boolean",
|
|
10161
11753
|
...safe?.description === void 0 ? {} : { description: safe.description }
|
|
10162
11754
|
};
|
|
10163
|
-
|
|
10164
|
-
return INTRINSICS.freeze(shape);
|
|
11755
|
+
return ShapePass.seal(shape);
|
|
10165
11756
|
}, "booleanShape");
|
|
10166
11757
|
}
|
|
10167
11758
|
/**
|
|
@@ -10182,8 +11773,7 @@ function nullShape(options) {
|
|
|
10182
11773
|
category: "null",
|
|
10183
11774
|
...safe?.description === void 0 ? {} : { description: safe.description }
|
|
10184
11775
|
};
|
|
10185
|
-
|
|
10186
|
-
return INTRINSICS.freeze(shape);
|
|
11776
|
+
return ShapePass.seal(shape);
|
|
10187
11777
|
}, "nullShape");
|
|
10188
11778
|
}
|
|
10189
11779
|
function literalShape(values, options) {
|
|
@@ -10231,8 +11821,7 @@ function literalShape(values, options) {
|
|
|
10231
11821
|
values: INTRINSICS.freeze(literals),
|
|
10232
11822
|
...safe?.description === void 0 ? {} : { description: safe.description }
|
|
10233
11823
|
};
|
|
10234
|
-
|
|
10235
|
-
return INTRINSICS.freeze(shape);
|
|
11824
|
+
return ShapePass.seal(shape);
|
|
10236
11825
|
}, "literalShape");
|
|
10237
11826
|
}
|
|
10238
11827
|
/**
|
|
@@ -10278,8 +11867,7 @@ function arrayShape(items, options) {
|
|
|
10278
11867
|
...safe?.max === void 0 ? {} : { max: safe.max },
|
|
10279
11868
|
...safe?.description === void 0 ? {} : { description: safe.description }
|
|
10280
11869
|
};
|
|
10281
|
-
|
|
10282
|
-
return INTRINSICS.freeze(shape);
|
|
11870
|
+
return ShapePass.seal(shape);
|
|
10283
11871
|
}, "arrayShape");
|
|
10284
11872
|
}
|
|
10285
11873
|
/**
|
|
@@ -10349,8 +11937,7 @@ function objectShape(properties, options) {
|
|
|
10349
11937
|
...safe?.additionalProperties === void 0 ? {} : { additionalProperties: safe.additionalProperties },
|
|
10350
11938
|
...safe?.description === void 0 ? {} : { description: safe.description }
|
|
10351
11939
|
};
|
|
10352
|
-
|
|
10353
|
-
return INTRINSICS.freeze(shape);
|
|
11940
|
+
return ShapePass.seal(shape);
|
|
10354
11941
|
}, "objectShape");
|
|
10355
11942
|
}
|
|
10356
11943
|
/**
|
|
@@ -10387,13 +11974,19 @@ function recordShape(values, options) {
|
|
|
10387
11974
|
additionalProperties: values,
|
|
10388
11975
|
...safe?.description === void 0 ? {} : { description: safe.description }
|
|
10389
11976
|
};
|
|
10390
|
-
|
|
10391
|
-
return INTRINSICS.freeze(shape);
|
|
11977
|
+
return ShapePass.seal(shape);
|
|
10392
11978
|
}, "recordShape");
|
|
10393
11979
|
}
|
|
10394
11980
|
/**
|
|
10395
11981
|
* Builds a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema).
|
|
10396
11982
|
*
|
|
11983
|
+
* @remarks
|
|
11984
|
+
* When every arm is an object declaring one required literal property, and a value's
|
|
11985
|
+
* own property exactly equals a literal only one arm holds, that arm answers: `explain`
|
|
11986
|
+
* and `audit` report its faults at their real paths, and `parse` repairs through it
|
|
11987
|
+
* alone. Any other value reports `variant`, with `key` and `expected` saying what would
|
|
11988
|
+
* have named an arm. `is` does not change.
|
|
11989
|
+
*
|
|
10397
11990
|
* @param variants - The candidate shapes; the first match wins at runtime
|
|
10398
11991
|
* @returns A union shape whose `Infer` is the union of the variants
|
|
10399
11992
|
*
|
|
@@ -10405,11 +11998,7 @@ function recordShape(values, options) {
|
|
|
10405
11998
|
*/
|
|
10406
11999
|
function unionShape(...variants) {
|
|
10407
12000
|
return contain(() => {
|
|
10408
|
-
|
|
10409
|
-
category: "union",
|
|
10410
|
-
variants
|
|
10411
|
-
}).validate();
|
|
10412
|
-
return INTRINSICS.freeze({
|
|
12001
|
+
return ShapePass.seal({
|
|
10413
12002
|
category: "union",
|
|
10414
12003
|
variants: INTRINSICS.freeze(variants)
|
|
10415
12004
|
});
|
|
@@ -10428,9 +12017,11 @@ function unionShape(...variants) {
|
|
|
10428
12017
|
* {@link unionShape}'s guard.
|
|
10429
12018
|
* - **Parser**: judged on the RAW input's guard matches only, with NO
|
|
10430
12019
|
* coercion fallback for an ambiguous input. When exactly one variant's
|
|
10431
|
-
* guard accepts the raw value,
|
|
12020
|
+
* guard accepts the raw value, the input itself is returned. Zero matches or
|
|
10432
12021
|
* two-or-more matches both parse to `undefined` — a value ambiguous
|
|
10433
|
-
* between variants has no well-defined coercion target.
|
|
12022
|
+
* between variants has no well-defined coercion target. A value that names one
|
|
12023
|
+
* arm through a required literal is not ambiguous, so as in {@link unionShape}
|
|
12024
|
+
* that arm answers alone, and its parser may coerce.
|
|
10434
12025
|
*
|
|
10435
12026
|
* Prefer {@link unionShape} when a value may legitimately satisfy more than
|
|
10436
12027
|
* one variant (for example overlapping shapes) and any match is acceptable. Prefer
|
|
@@ -10449,15 +12040,10 @@ function unionShape(...variants) {
|
|
|
10449
12040
|
*/
|
|
10450
12041
|
function oneOfShape(...variants) {
|
|
10451
12042
|
return contain(() => {
|
|
10452
|
-
|
|
12043
|
+
return ShapePass.seal({
|
|
10453
12044
|
category: "union",
|
|
10454
|
-
variants,
|
|
12045
|
+
variants: INTRINSICS.freeze(variants),
|
|
10455
12046
|
mode: "oneOf"
|
|
10456
|
-
};
|
|
10457
|
-
new ShapeValidator(shape).validate();
|
|
10458
|
-
return INTRINSICS.freeze({
|
|
10459
|
-
...shape,
|
|
10460
|
-
variants: INTRINSICS.freeze(variants)
|
|
10461
12047
|
});
|
|
10462
12048
|
}, "oneOfShape");
|
|
10463
12049
|
}
|
|
@@ -10466,22 +12052,55 @@ function oneOfShape(...variants) {
|
|
|
10466
12052
|
*
|
|
10467
12053
|
* @remarks
|
|
10468
12054
|
* As an {@link objectShape} property, the field becomes a true optional property
|
|
10469
|
-
* in the inferred type.
|
|
12055
|
+
* in the inferred type. A `default` is captured as an owned frozen copy, and the
|
|
12056
|
+
* compiled parser fills it where the property is absent or `undefined`; the guard,
|
|
12057
|
+
* the audit, the report, and the generator keep treating the property as optional.
|
|
12058
|
+
* The compilers refuse a default `inner` refuses, a default under a union, and a
|
|
12059
|
+
* default on a property of an open object.
|
|
10470
12060
|
*
|
|
10471
12061
|
* @param inner - The wrapped shape
|
|
12062
|
+
* @param options - Optional `default`, a JSON value
|
|
10472
12063
|
* @returns An optional shape
|
|
12064
|
+
* @throws {ContractError} When a present `default` is not a JSON value, `undefined` included
|
|
12065
|
+
*
|
|
12066
|
+
* @example
|
|
12067
|
+
* ```ts
|
|
12068
|
+
* const retries = optionalShape(integerShape({ min: 0 }), { default: 3 })
|
|
12069
|
+
* ```
|
|
10473
12070
|
*/
|
|
10474
|
-
function optionalShape(inner) {
|
|
12071
|
+
function optionalShape(inner, options) {
|
|
10475
12072
|
return contain(() => {
|
|
12073
|
+
const safe = readOptions(options, ["default"], "optionalShape", "optional");
|
|
12074
|
+
refuseOptionKeys(options, ["default"], "optionalShape", "optional");
|
|
12075
|
+
const present = options !== void 0 && INTRINSICS.own(options, "default");
|
|
12076
|
+
const value = present ? safe?.default : void 0;
|
|
12077
|
+
if (present && !isJSONValue(value)) throw new ContractError("optionalShape: default must be a JSON value", {
|
|
12078
|
+
code: "structure",
|
|
12079
|
+
context: {
|
|
12080
|
+
path: ["default"],
|
|
12081
|
+
shape: "optional",
|
|
12082
|
+
received: preview(value)
|
|
12083
|
+
}
|
|
12084
|
+
});
|
|
12085
|
+
const owned = value === void 0 ? void 0 : attempt(() => cloneJSONValue(value));
|
|
12086
|
+
if (owned !== void 0 && isFailure(owned)) throw new ContractError("optionalShape: default must be a JSON value", {
|
|
12087
|
+
code: "structure",
|
|
12088
|
+
context: {
|
|
12089
|
+
path: ["default"],
|
|
12090
|
+
shape: "optional",
|
|
12091
|
+
received: preview(value)
|
|
12092
|
+
},
|
|
12093
|
+
cause: owned.error
|
|
12094
|
+
});
|
|
10476
12095
|
const shape = {
|
|
10477
12096
|
category: "optional",
|
|
10478
|
-
inner
|
|
12097
|
+
inner,
|
|
12098
|
+
...owned === void 0 ? {} : { default: owned.value }
|
|
10479
12099
|
};
|
|
10480
|
-
|
|
12100
|
+
return ShapePass.seal(shape, {
|
|
10481
12101
|
category: "object",
|
|
10482
12102
|
properties: { value: shape }
|
|
10483
|
-
})
|
|
10484
|
-
return INTRINSICS.freeze(shape);
|
|
12103
|
+
});
|
|
10485
12104
|
}, "optionalShape");
|
|
10486
12105
|
}
|
|
10487
12106
|
/**
|
|
@@ -10502,8 +12121,7 @@ function nullableShape(inner) {
|
|
|
10502
12121
|
category: "nullable",
|
|
10503
12122
|
inner
|
|
10504
12123
|
};
|
|
10505
|
-
|
|
10506
|
-
return INTRINSICS.freeze(shape);
|
|
12124
|
+
return ShapePass.seal(shape);
|
|
10507
12125
|
}, "nullableShape");
|
|
10508
12126
|
}
|
|
10509
12127
|
/**
|
|
@@ -10535,17 +12153,39 @@ function jsonShape(options) {
|
|
|
10535
12153
|
category: "json",
|
|
10536
12154
|
...safe?.description === void 0 ? {} : { description: safe.description }
|
|
10537
12155
|
};
|
|
10538
|
-
|
|
10539
|
-
return INTRINSICS.freeze(shape);
|
|
12156
|
+
return ShapePass.seal(shape);
|
|
10540
12157
|
}, "jsonShape");
|
|
10541
12158
|
}
|
|
10542
12159
|
/**
|
|
12160
|
+
* Builds a {@link ShapeShape}.
|
|
12161
|
+
*
|
|
12162
|
+
* @param options - Optional description
|
|
12163
|
+
* @returns A shape-valued declaration
|
|
12164
|
+
*
|
|
12165
|
+
* @example
|
|
12166
|
+
* ```ts
|
|
12167
|
+
* const definition = objectShape({ shape: shapeShape() })
|
|
12168
|
+
* ```
|
|
12169
|
+
*/
|
|
12170
|
+
function shapeShape(options) {
|
|
12171
|
+
return contain(() => {
|
|
12172
|
+
const safe = readOptions(options, ["description"], "shapeShape", "shape");
|
|
12173
|
+
const shape = {
|
|
12174
|
+
category: "shape",
|
|
12175
|
+
...safe?.description === void 0 ? {} : { description: safe.description }
|
|
12176
|
+
};
|
|
12177
|
+
return ShapePass.seal(shape);
|
|
12178
|
+
}, "shapeShape");
|
|
12179
|
+
}
|
|
12180
|
+
/**
|
|
10543
12181
|
* Builds a {@link RawShape} from a supported JSON Schema fragment.
|
|
10544
12182
|
*
|
|
10545
12183
|
* @remarks
|
|
10546
12184
|
* For values the shape DSL can't express. The fragment is recursively checked
|
|
10547
12185
|
* against the lean {@link JSONSchema} vocabulary before ownership is taken;
|
|
10548
12186
|
* malformed or unsupported keywords throw a coded {@link ContractError}. The
|
|
12187
|
+
* refusal path starts at `schema` and names the nested keyword or member.
|
|
12188
|
+
* A non-record root is refused at `schema` itself. The
|
|
10549
12189
|
* compiled guard accepts every
|
|
10550
12190
|
* DEFINED value — `undefined` alone fails, because it is the parser's failure
|
|
10551
12191
|
* sentinel; wrap the shape in {@link optionalShape} to admit absence. The
|
|
@@ -10573,22 +12213,18 @@ function rawShape(schema) {
|
|
|
10573
12213
|
category: "raw",
|
|
10574
12214
|
schema
|
|
10575
12215
|
}).validate();
|
|
10576
|
-
|
|
10577
|
-
new ShapeValidator({
|
|
10578
|
-
category: "raw",
|
|
10579
|
-
schema: owned
|
|
10580
|
-
}).validate();
|
|
10581
|
-
return INTRINSICS.freeze({
|
|
12216
|
+
return ShapePass.seal({
|
|
10582
12217
|
category: "raw",
|
|
10583
|
-
schema:
|
|
12218
|
+
schema: cloneSchema(schema)
|
|
10584
12219
|
});
|
|
10585
12220
|
}, "rawShape");
|
|
10586
12221
|
}
|
|
10587
12222
|
/**
|
|
10588
12223
|
* Converts a runtime `JSONSchema` value into a validating {@link ContractShape}
|
|
10589
12224
|
* — the inverse of {@link compileSchema}. Unlike direct {@link rawShape}
|
|
10590
|
-
* construction, which rejects malformed supported-vocabulary keywords,
|
|
10591
|
-
* conversion is total and widens an inexpressible input to a valid raw
|
|
12225
|
+
* construction, which rejects malformed supported-vocabulary keywords, the
|
|
12226
|
+
* lenient conversion is total and widens an inexpressible input to a valid raw
|
|
12227
|
+
* `{}`, and a strict conversion refuses that input.
|
|
10592
12228
|
*
|
|
10593
12229
|
* @remarks
|
|
10594
12230
|
* Readable malformed, cyclic, or deeply nested schema nodes widen to
|
|
@@ -10639,9 +12275,36 @@ function rawShape(schema) {
|
|
|
10639
12275
|
* when the conversion widened anywhere — `schema` / `is` / `parse` / `explain`
|
|
10640
12276
|
* stay total.
|
|
10641
12277
|
*
|
|
12278
|
+
* LENIENT LAW: a value a JSON Schema accepts is never refused by the shape a
|
|
12279
|
+
* lenient conversion builds from it, because the walk widens what it cannot read.
|
|
12280
|
+
* So `oneOf` builds an inclusive union, a `true` arm is a raw variant and a `false`
|
|
12281
|
+
* arm is dropped, an `enum` holding `null` admits it, `nullable: true` wraps the
|
|
12282
|
+
* node, a present `patternProperties` opens the object, a present `prefixItems`
|
|
12283
|
+
* widens the elements, and a `$ref` widens the node before anything beside it is read.
|
|
12284
|
+
* A schema past the compile limit keeps only its root's type, an array's bounds, and an
|
|
12285
|
+
* object's required keys and closure, with every value below them raw.
|
|
12286
|
+
*
|
|
12287
|
+
* DEFAULTS: a lenient conversion carries a property's `default` when the key is
|
|
12288
|
+
* not `required`, its object is closed with no union ancestor, and the value is
|
|
12289
|
+
* one the property's primitive or literal guard accepts. It drops every other
|
|
12290
|
+
* `default`, because carrying it would make the shape refuse to compile.
|
|
12291
|
+
*
|
|
12292
|
+
* STRICT: `{ strict: true }` is the door for a foreign schema. It refuses, with
|
|
12293
|
+
* code `structure`, every node the lenient walk would widen, every keyword it
|
|
12294
|
+
* would ignore (`pattern`, `format`, `nullable`, `patternProperties`,
|
|
12295
|
+
* `propertyNames`, `prefixItems`, and anything else outside
|
|
12296
|
+
* {@link STRICT_SCHEMA_KEYWORDS}), a malformed keyword or annotation, a boolean schema, an `enum` entry
|
|
12297
|
+
* that is neither a finite primitive nor `null`, a contradictory bound, a `required` name not in
|
|
12298
|
+
* `properties`, breadth past {@link INFER_BREADTH_LIMIT}, and a `default` with no
|
|
12299
|
+
* optional property to fill. An object with no `additionalProperties` closes
|
|
12300
|
+
* rather than opens, and `oneOf` keeps exactly-one, because a strict walk reads
|
|
12301
|
+
* every keyword that could keep two arms apart. Below a `oneOf` that object refuses
|
|
12302
|
+
* instead, since closing it could change which arms match.
|
|
12303
|
+
*
|
|
10642
12304
|
* @param schema - The JSON Schema value to convert
|
|
12305
|
+
* @param options - Optional `strict`, default `false`
|
|
10643
12306
|
* @returns The built {@link ContractShape}
|
|
10644
|
-
* @throws {ContractError} When schema traversal fails
|
|
12307
|
+
* @throws {ContractError} When schema traversal fails, or when a strict conversion refuses
|
|
10645
12308
|
*
|
|
10646
12309
|
* @example
|
|
10647
12310
|
* ```ts
|
|
@@ -10651,14 +12314,35 @@ function rawShape(schema) {
|
|
|
10651
12314
|
* contract.parse({ id: 'nope' }) // undefined
|
|
10652
12315
|
* ```
|
|
10653
12316
|
*/
|
|
10654
|
-
function schemaToShape(schema) {
|
|
12317
|
+
function schemaToShape(schema, options) {
|
|
10655
12318
|
return contain(() => {
|
|
10656
|
-
|
|
12319
|
+
const safe = readOptions(options, ["strict"], "schemaToShape", "schema");
|
|
12320
|
+
refuseOptionKeys(options, ["strict"], "schemaToShape", "schema");
|
|
12321
|
+
const strict = options !== void 0 && INTRINSICS.own(options, "strict") ? safe?.strict : void 0;
|
|
12322
|
+
if (strict !== void 0 && typeof strict !== "boolean") throw new ContractError("schemaToShape: strict must be a boolean", {
|
|
12323
|
+
code: "structure",
|
|
12324
|
+
context: {
|
|
12325
|
+
path: ["strict"],
|
|
12326
|
+
shape: "schema",
|
|
12327
|
+
received: preview(strict)
|
|
12328
|
+
}
|
|
12329
|
+
});
|
|
12330
|
+
const shaper = new SchemaShaper(schema, strict === true);
|
|
12331
|
+
if (strict !== true) return readValue(() => shaper.shape(), "schemaToShape", {
|
|
12332
|
+
subject: "schema",
|
|
12333
|
+
context: { shape: "schema" }
|
|
12334
|
+
});
|
|
12335
|
+
const outcome = attempt(() => shaper.shape());
|
|
12336
|
+
if (isSuccess(outcome)) return outcome.value;
|
|
12337
|
+
if (isContractError(outcome.error)) throw outcome.error;
|
|
12338
|
+
return readValue(() => {
|
|
12339
|
+
throw outcome.error;
|
|
12340
|
+
}, "schemaToShape", {
|
|
10657
12341
|
subject: "schema",
|
|
10658
12342
|
context: { shape: "schema" }
|
|
10659
12343
|
});
|
|
10660
12344
|
}, "schemaToShape");
|
|
10661
12345
|
}
|
|
10662
|
-
export { CHOICE_LIMIT, CLONE_NODE_LIMIT, COMPILE_DEPTH_LIMIT, COMPILE_NODE_LIMIT, CONTRACT_CODES, CONTRACT_ERROR_BRAND, ContractCompiler, ContractError, FAULT_LIMIT, FORMAT_MAX_LENGTH, FORMAT_PATTERNS, GENERATION_ATTEMPT_LIMIT, GUARD_DEPTH_LIMIT, INFER_BREADTH_LIMIT, INFER_DEPTH_LIMIT, INFER_ENUM_LIMIT, INTRINSICS, JSONCloner, JSON_SCHEMA_TYPES, NAME_LIMIT, NODE_LIMIT, PRESENCE_MASK_LIMIT, PREVIEW_LIMIT, STRING_LIMIT, SchemaCloner, ShapeCloner, ShapeValidator, TEXT_LIMIT, admitMember, admitVisited, andOf, appendEntries, arrayOf, arrayShape, attempt, booleanShape, boundsOf, buildArrayFaults, buildNumberFaults, buildPositions, buildSampleMemo, buildStringFaults, canonicalStringify, classifyFormat, cloneJSONRecord, cloneJSONValue, cloneSchema, cloneShape, collectEntries, collectMembers, comparePrimitives, compileAuditor, compileGenerator, compileGuard, compileParser, compileReporter, compileSchema, complementOf, contain, createContract, deriveLengthBounds, deriveRangeBounds, drawRandom, encodeLeaf, encodeParts, enumOf, enumerableKeys, enumerableSymbolCount, errorToMessage, escapeRegExp, failure, holds, inferPrimitiveEnum, instanceOf, integerShape, intersectionOf, isArray, isArrayBuffer, isArrayBufferView, isAsyncFunction, isAsyncGeneratorFunction, isAsyncIterable, isBigInt, isBigInt64Array, isBigUint64Array, isBoolean, isBoundedJSONRecord, isBoundedJSONValue, isConstructor, isContractError, isDataView, isDate, isDefined, isEmptyArray, isEmptyMap, isEmptyObject, isEmptySet, isEmptyString, isError, isFailure, isFalse, isFiniteNumber, isFloat32Array, isFloat64Array, isFunction, isGeneratorFunction, isInstance, isInt16Array, isInt32Array, isInt8Array, isInteger, isIterable, isJSONPrimitive, isJSONValue, isLiteralValue, isMap, isNonEmptyArray, isNonEmptyMap, isNonEmptyObject, isNonEmptySet, isNonEmptyString, isNonNegativeInteger, isNonNegativeNumber, isNull, isNullableBoolean, isNullableNumber, isNullableString, isNumber, isObject, isPromise, isPromiseLike, isRecord, isRegExp, isSet, isSharedArrayBuffer, isString, isSuccess, isSymbol, isTrue, isUint16Array, isUint32Array, isUint8Array, isUint8ClampedArray, isUndefined, isWeakMap, isWeakSet, isZeroArg, isZeroArgAsync, isZeroArgAsyncGenerator, isZeroArgGenerator, iterateIndices, jsonShape, keyOf, lazyOf, limitEntries, literalOf, literalShape, mapOf, matchOf, matchesISOInstant, matchesJSONDepth, matchesJSONValue, matchesMember, matchesPattern, matchesRecordBrand, matchesVisited, notOf, nullShape, nullableOf, nullableShape, numberShape, objectOf, objectShape, omitOf, omitVisited, oneOfShape, optionalOf, optionalShape, orOf, ownPattern, ownShape, parseArray, parseArrayField, parseBoolean, parseBooleanField, parseEnum, parseEnumField, parseEnumValues, parseInteger, parseIntegerField, parseJSON, parseJSONAs, parseJSONValue, parseJSONValueField, parseNull, parseNullField, parseNumber, parseNumberField, parseRecord, parseRecordField, parseString, parseStringField, pathOf, pickOf, pinMembers, preview, previewParts, rawShape, readArrayEntries, readGuardShape, readIndexView, readMapEntries, readOptions, readPattern, readPatternFlags, readPatternSource, readPresence, readSampleMemo, readSetEntries, readValue, recordOf, recordShape, refuseExpansion, resolveField, retainDepth, samplesToFormat, samplesToSchema, sanitizeBudget, sanitizeDepth, schemaToObject, schemaToParameters, schemaToShape, seededRandom, selectClosestFaults, setOf, shapeToKind, sortValues, stringOf, stringShape, stringToFormat, success, transformOf, tupleOf, unifySchemas, unionOf, unionShape, validateShape, valueToSchema, whereOf };
|
|
12346
|
+
export { CHOICE_LIMIT, CLONE_NODE_LIMIT, COMPILE_DEPTH_LIMIT, COMPILE_NODE_LIMIT, CONTRACT_CODES, CONTRACT_ERROR_BRAND, ContractCompiler, ContractError, FAULT_CONSTRAINTS, FAULT_KINDS, FAULT_LIMIT, FAULT_LIST_LIMIT, FAULT_SCHEMA_LIMIT, FAULT_TEXT_LIMIT, FORMAT_MAX_LENGTH, FORMAT_PATTERNS, GENERATION_ATTEMPT_LIMIT, GUARD_DEPTH_LIMIT, INFER_BREADTH_LIMIT, INFER_DEPTH_LIMIT, INFER_ENUM_LIMIT, INTRINSICS, JSONCloner, JSON_SCHEMA_TYPES, NAME_LIMIT, NODE_LIMIT, PRESENCE_MASK_LIMIT, PREVIEW_LIMIT, SHAPE_FIELDS, STRICT_SCHEMA_KEYWORDS, STRING_LIMIT, SchemaCloner, ShapeCloner, ShapeValidator, TEXT_LIMIT, admitMember, admitValue, admitVisited, andOf, appendEntries, arrayOf, arrayShape, attempt, auditFaultShape, booleanShape, boundsOf, buildArrayFaults, buildNumberFaults, buildPositions, buildSampleMemo, buildStringFaults, canonicalStringify, classifyFormat, cloneJSONRecord, cloneJSONValue, cloneSchema, cloneShape, collectEntries, collectMembers, comparePrimitives, compileAuditor, compileGenerator, compileGuard, compileParser, compileReporter, compileSchema, complementOf, computeSurrogatePairs, contain, createContract, deriveLengthBounds, deriveRangeBounds, describeFaultLine, describeFaults, drawRandom, encodeLeaf, encodeParts, enumOf, enumerableKeys, enumerableSymbolCount, errorToMessage, escapeRegExp, extractForms, extractPath, extractSchema, failure, holds, inferPrimitiveEnum, instanceOf, integerShape, intersectionOf, isArray, isArrayBuffer, isArrayBufferView, isAsyncFunction, isAsyncGeneratorFunction, isAsyncIterable, isAuditFault, isBigInt, isBigInt64Array, isBigUint64Array, isBoolean, isBoundedJSONRecord, isBoundedJSONValue, isConstructor, isContractError, isDataView, isDate, isDefined, isEmptyArray, isEmptyMap, isEmptyObject, isEmptySet, isEmptyString, isError, isFailure, isFalse, isFault, isFaultPath, isFiniteNumber, isFloat32Array, isFloat64Array, isFunction, isGeneratorFunction, isInstance, isInt16Array, isInt32Array, isInt8Array, isInteger, isIterable, isJSONPrimitive, isJSONValue, isLiteralValue, isMap, isNonEmptyArray, isNonEmptyMap, isNonEmptyObject, isNonEmptySet, isNonEmptyString, isNonNegativeInteger, isNonNegativeNumber, isNull, isNullableBoolean, isNullableNumber, isNullableString, isNumber, isObject, isPromise, isPromiseLike, isRecord, isRegExp, isSet, isSharedArrayBuffer, isString, isSuccess, isSymbol, isTrue, isUint16Array, isUint32Array, isUint8Array, isUint8ClampedArray, isUndefined, isWeakMap, isWeakSet, isZeroArg, isZeroArgAsync, isZeroArgAsyncGenerator, isZeroArgGenerator, iterateIndices, jsonShape, keyOf, lazyOf, limitEntries, literalOf, literalShape, mapOf, matchOf, matchesExactKeys, matchesISOInstant, matchesJSONDepth, matchesJSONValue, matchesLosslessRepair, matchesMember, matchesPattern, matchesRecordBrand, matchesStringLength, matchesUndefinedField, matchesVisited, notOf, nullShape, nullableOf, nullableShape, numberShape, objectOf, objectShape, omitOf, omitVisited, oneOfShape, optionalOf, optionalShape, orOf, ownPattern, ownShape, parseArray, parseArrayField, parseBoolean, parseBooleanField, parseEnum, parseEnumField, parseEnumValues, parseInteger, parseIntegerField, parseJSON, parseJSONAs, parseJSONValue, parseJSONValueField, parseNull, parseNullField, parseNumber, parseNumberField, parseRecord, parseRecordField, parseString, parseStringField, pathOf, pickOf, pinMembers, preview, previewParts, rawShape, readArrayEntries, readGuardShape, readIndexView, readMapEntries, readOptions, readPattern, readPatternFlags, readPatternSource, readPresence, readSampleMemo, readSetEntries, readValue, recordOf, recordShape, refuseExpansion, refuseOptionKeys, renderForm, renderList, renderPath, resolveField, retainDepth, samplesToFormat, samplesToSchema, sanitizeBudget, sanitizeDepth, schemaToObject, schemaToParameters, schemaToShape, seededRandom, selectClosestFaults, setOf, shapeShape, shapeToKind, sortValues, stringOf, stringShape, stringToFormat, success, transformOf, truncateFaultText, tupleOf, unifySchemas, unionOf, unionShape, validateShape, valueToSchema, whereOf };
|
|
10663
12347
|
|
|
10664
12348
|
//# sourceMappingURL=index.js.map
|