@toiroakr/chisel 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +464 -2
  2. package/dist/behavior.d.ts +181 -0
  3. package/dist/behavior.js +422 -0
  4. package/dist/behavior.js.map +1 -0
  5. package/dist/beside.d.ts +27 -0
  6. package/dist/beside.js +88 -0
  7. package/dist/beside.js.map +1 -0
  8. package/dist/border.d.ts +64 -0
  9. package/dist/border.js +426 -0
  10. package/dist/border.js.map +1 -0
  11. package/dist/cli.d.ts +5 -0
  12. package/dist/cli.js +567 -0
  13. package/dist/cli.js.map +1 -0
  14. package/dist/codec.d.ts +6 -0
  15. package/dist/codec.js +83 -0
  16. package/dist/codec.js.map +1 -0
  17. package/dist/codegen.d.ts +2 -0
  18. package/dist/codegen.js +65 -0
  19. package/dist/codegen.js.map +1 -0
  20. package/dist/composition.d.ts +38 -0
  21. package/dist/composition.js +242 -0
  22. package/dist/composition.js.map +1 -0
  23. package/dist/data.d.ts +16 -0
  24. package/dist/data.js +49 -0
  25. package/dist/data.js.map +1 -0
  26. package/dist/dependency.d.ts +98 -0
  27. package/dist/dependency.js +155 -0
  28. package/dist/dependency.js.map +1 -0
  29. package/dist/domain.d.ts +8 -0
  30. package/dist/domain.js +217 -0
  31. package/dist/domain.js.map +1 -0
  32. package/dist/ensures.d.ts +15 -0
  33. package/dist/ensures.js +88 -0
  34. package/dist/ensures.js.map +1 -0
  35. package/dist/exact.d.ts +21 -0
  36. package/dist/exact.js +80 -0
  37. package/dist/exact.js.map +1 -0
  38. package/dist/feasibility.d.ts +61 -0
  39. package/dist/feasibility.js +984 -0
  40. package/dist/feasibility.js.map +1 -0
  41. package/dist/guard-borders.d.ts +50 -0
  42. package/dist/guard-borders.js +809 -0
  43. package/dist/guard-borders.js.map +1 -0
  44. package/dist/index.d.ts +37 -0
  45. package/dist/index.js +19 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/interval.d.ts +3 -0
  48. package/dist/interval.js +161 -0
  49. package/dist/interval.js.map +1 -0
  50. package/dist/isolated.d.ts +9 -0
  51. package/dist/isolated.js +41 -0
  52. package/dist/isolated.js.map +1 -0
  53. package/dist/model.d.ts +95 -0
  54. package/dist/model.js +343 -0
  55. package/dist/model.js.map +1 -0
  56. package/dist/pairs.d.ts +26 -0
  57. package/dist/pairs.js +107 -0
  58. package/dist/pairs.js.map +1 -0
  59. package/dist/partition.d.ts +44 -0
  60. package/dist/partition.js +275 -0
  61. package/dist/partition.js.map +1 -0
  62. package/dist/proof.d.ts +15 -0
  63. package/dist/proof.js +482 -0
  64. package/dist/proof.js.map +1 -0
  65. package/dist/report-json.d.ts +11 -0
  66. package/dist/report-json.js +94 -0
  67. package/dist/report-json.js.map +1 -0
  68. package/dist/rule.d.ts +146 -0
  69. package/dist/rule.js +599 -0
  70. package/dist/rule.js.map +1 -0
  71. package/dist/schema.d.ts +163 -0
  72. package/dist/schema.js +524 -0
  73. package/dist/schema.js.map +1 -0
  74. package/dist/specification.d.ts +256 -0
  75. package/dist/specification.js +1583 -0
  76. package/dist/specification.js.map +1 -0
  77. package/dist/text.d.ts +1 -0
  78. package/dist/text.js +11 -0
  79. package/dist/text.js.map +1 -0
  80. package/dist/ways.d.ts +25 -0
  81. package/dist/ways.js +95 -0
  82. package/dist/ways.js.map +1 -0
  83. package/package.json +53 -4
  84. package/schema/report.schema.json +1062 -0
@@ -0,0 +1,163 @@
1
+ import { Rational } from "./exact.js";
2
+ import { Decimal } from "decimal.js";
3
+ import type { Temporal as TemporalTypes } from "temporal-spec";
4
+ import type { ElementLabels, InvariantRule, Operator, Rule } from "./rule.js";
5
+ export interface ValidationIssue {
6
+ readonly path: string;
7
+ readonly message: string;
8
+ readonly invariant?: string;
9
+ }
10
+ export type ValidationResult<T> = {
11
+ readonly success: true;
12
+ readonly value: T;
13
+ } | {
14
+ readonly success: false;
15
+ readonly issues: readonly ValidationIssue[];
16
+ };
17
+ export interface Schema<T> {
18
+ readonly kind: string;
19
+ readonly invariants: readonly Rule[];
20
+ readonly description?: string;
21
+ parse(value: unknown, path?: string): ValidationResult<T>;
22
+ placeholder(name?: string): unknown;
23
+ refine(rule: InvariantRule<T>): this;
24
+ refine(name: string, rule: InvariantRule<T>): this;
25
+ describe(text: string): this;
26
+ optional<Self extends AnySchema>(this: Self): OptionalSchema<Infer<Self>>;
27
+ }
28
+ interface ValueBounds<T> {
29
+ min(bound: T): this;
30
+ min(name: string, bound: T): this;
31
+ max(bound: T): this;
32
+ max(name: string, bound: T): this;
33
+ gt(bound: T): this;
34
+ gt(name: string, bound: T): this;
35
+ lt(bound: T): this;
36
+ lt(name: string, bound: T): this;
37
+ }
38
+ interface LengthBounds {
39
+ min(length: number): this;
40
+ min(name: string, length: number): this;
41
+ max(length: number): this;
42
+ max(name: string, length: number): this;
43
+ length(length: number): this;
44
+ length(name: string, length: number): this;
45
+ }
46
+ export type AnySchema = Schema<unknown>;
47
+ export type Infer<S> = S extends Schema<infer T> ? T : never;
48
+ export interface StringSchema extends Schema<string>, LengthBounds {
49
+ readonly kind: "string";
50
+ }
51
+ export interface NumberSchema extends Schema<number>, ValueBounds<number> {
52
+ readonly kind: "number";
53
+ }
54
+ export interface IntSchema extends Schema<number>, ValueBounds<number> {
55
+ readonly kind: "integer";
56
+ }
57
+ export interface Int64Schema extends Schema<bigint>, ValueBounds<bigint> {
58
+ readonly kind: "int64";
59
+ }
60
+ export interface RationalSchema extends Schema<Rational>, ValueBounds<Rational> {
61
+ readonly kind: "rational";
62
+ }
63
+ export interface DecimalSchema extends Schema<Decimal>, ValueBounds<Decimal> {
64
+ readonly kind: "decimal";
65
+ readonly scale: number;
66
+ }
67
+ export interface BooleanSchema extends Schema<boolean> {
68
+ readonly kind: "boolean";
69
+ }
70
+ export interface InstantSchema extends Schema<TemporalTypes.Instant>, ValueBounds<TemporalTypes.Instant> {
71
+ readonly kind: "instant";
72
+ }
73
+ export interface DateSchema extends Schema<TemporalTypes.PlainDate>, ValueBounds<TemporalTypes.PlainDate> {
74
+ readonly kind: "date";
75
+ }
76
+ export interface TimeSchema extends Schema<TemporalTypes.PlainTime>, ValueBounds<TemporalTypes.PlainTime> {
77
+ readonly kind: "time";
78
+ }
79
+ export interface DateTimeSchema extends Schema<TemporalTypes.PlainDateTime>, ValueBounds<TemporalTypes.PlainDateTime> {
80
+ readonly kind: "datetime";
81
+ }
82
+ export interface EnumSchema<T extends string> extends Schema<T> {
83
+ readonly kind: "enum";
84
+ readonly values: readonly T[];
85
+ readonly labels?: {
86
+ readonly [Value in T]?: string;
87
+ };
88
+ }
89
+ export interface LiteralSchema<T extends string | number | boolean | null> extends Schema<T> {
90
+ readonly kind: "literal";
91
+ readonly value: T;
92
+ }
93
+ export interface ArraySchema<T> extends Schema<readonly T[]>, LengthBounds {
94
+ readonly kind: "array";
95
+ readonly element: Schema<T>;
96
+ }
97
+ export interface OptionalSchema<T> extends Schema<T | undefined> {
98
+ readonly kind: "optional";
99
+ readonly schema: Schema<T>;
100
+ }
101
+ export interface RecordSchema<T> extends Schema<Readonly<Record<string, T>>>, LengthBounds {
102
+ readonly kind: "record";
103
+ readonly value: Schema<T>;
104
+ }
105
+ export type ObjectShape = Readonly<Record<string, AnySchema>>;
106
+ type OptionalShapeKeys<Shape extends ObjectShape> = {
107
+ readonly [K in keyof Shape]: Shape[K] extends {
108
+ readonly kind: "optional";
109
+ } ? K : never;
110
+ }[keyof Shape];
111
+ type RequiredShapeKeys<Shape extends ObjectShape> = Exclude<keyof Shape, OptionalShapeKeys<Shape>>;
112
+ export type InferShape<Shape extends ObjectShape> = {
113
+ readonly [K in RequiredShapeKeys<Shape>]: Infer<Shape[K]>;
114
+ } & {
115
+ readonly [K in OptionalShapeKeys<Shape>]?: Exclude<Infer<Shape[K]>, undefined>;
116
+ };
117
+ export interface ObjectSchema<Shape extends ObjectShape> extends Schema<InferShape<Shape>> {
118
+ readonly kind: "object";
119
+ readonly shape: Shape;
120
+ }
121
+ export type VariantTable = Readonly<Record<string, ObjectSchema<ObjectShape>>>;
122
+ export type VariantsValue<Discriminant extends string, Variants extends VariantTable> = {
123
+ [K in keyof Variants & string]: Readonly<Record<Discriminant, K>> & Infer<Variants[K]>;
124
+ }[keyof Variants & string];
125
+ export type VariantValue<Discriminant extends string, Variants extends VariantTable, Tag extends keyof Variants & string> = Readonly<Record<Discriminant, Tag>> & Infer<Variants[Tag]>;
126
+ export interface VariantsSchema<Discriminant extends string, Variants extends VariantTable> extends Schema<VariantsValue<Discriminant, Variants>> {
127
+ readonly kind: "variants";
128
+ readonly discriminant: Discriminant;
129
+ readonly variants: Variants;
130
+ readonly variantTags: readonly (keyof Variants & string)[];
131
+ placeholderFor<Tag extends keyof Variants & string>(tag: Tag): VariantValue<Discriminant, Variants, Tag>;
132
+ }
133
+ export type AnyVariantsSchema = VariantsSchema<any, any>;
134
+ export type Tags<S> = S extends VariantsSchema<any, infer Variants> ? keyof Variants & string : never;
135
+ export type VariantOf<S, Tag extends Tags<S>> = S extends VariantsSchema<infer Discriminant, infer Variants> ? Tag extends keyof Variants & string ? VariantValue<Discriminant, Variants, Tag> : never : never;
136
+ export declare function string(): StringSchema;
137
+ export declare function int64(): Int64Schema;
138
+ export declare function rational(): RationalSchema;
139
+ export declare function number(): NumberSchema;
140
+ export declare function int(): IntSchema;
141
+ export declare function decimal(scale: number): DecimalSchema;
142
+ export declare function boolean(): BooleanSchema;
143
+ export declare function instant(): InstantSchema;
144
+ export declare function date(): DateSchema;
145
+ export declare function time(): TimeSchema;
146
+ export declare function datetime(): DateTimeSchema;
147
+ export declare function enumOf<const T extends string>(values: readonly [T, ...T[]], options?: {
148
+ readonly labels?: {
149
+ readonly [Value in T]?: string;
150
+ };
151
+ }): EnumSchema<T>;
152
+ export declare function literal<const T extends string | number | boolean | null>(expected: T): LiteralSchema<T>;
153
+ export declare function object<const Shape extends ObjectShape>(shape: Shape): ObjectSchema<Shape>;
154
+ export declare function array<T>(element: Schema<T>): ArraySchema<T>;
155
+ export declare function optional<T>(schema: Schema<T>): OptionalSchema<T>;
156
+ export declare function record<T>(value: Schema<T>): RecordSchema<T>;
157
+ export declare function variants<const Discriminant extends string, const Variants extends VariantTable>(discriminant: Discriminant, variants: Variants): VariantsSchema<Discriminant, Variants>;
158
+ export declare function isVariantsSchema(schema: AnySchema): schema is AnyVariantsSchema;
159
+ export declare function tagOf(schema: AnyVariantsSchema, value: unknown): string | undefined;
160
+ export declare function holdsNoDecimal(schema: AnySchema, operator: Operator, bound: unknown): boolean;
161
+ export declare function offGridEquality(rule: Rule, resolve: (path: readonly string[]) => AnySchema | undefined, label: string, labels?: ElementLabels): string | undefined;
162
+ export declare function schemaAtPath(schema: AnySchema, keys: readonly string[]): AnySchema | undefined;
163
+ export {};
package/dist/schema.js ADDED
@@ -0,0 +1,524 @@
1
+ import { Rational, isRational, INT64_MIN, INT64_MAX } from "./exact.js";
2
+ import { Decimal } from "decimal.js";
3
+ import { conjuncts, decimalStep, describeRule, holds, isDecimal, isTerm, satisfy, selfTerm, termData, positionData, positionOf, } from "./rule.js";
4
+ function valid(value) {
5
+ return { success: true, value };
6
+ }
7
+ function invalid(path, message) {
8
+ return { success: false, issues: [{ path, message }] };
9
+ }
10
+ const ORDERED_KINDS = new Set(["int64", "rational", "number", "integer", "decimal", "instant", "date", "time", "datetime"]);
11
+ function refinable(core, invariants = []) {
12
+ const schema = {
13
+ ...core,
14
+ invariants,
15
+ parse(value, path = "$") {
16
+ const result = core.parse(value, path);
17
+ if (!result.success) {
18
+ return result;
19
+ }
20
+ const broken = invariants.filter(rule => !holds(rule, result.value));
21
+ return broken.length === 0
22
+ ? result
23
+ : {
24
+ success: false,
25
+ issues: broken.map(rule => rule.name === undefined
26
+ ? { path, message: `Invariant violated: ${describeRule(rule, path)}` }
27
+ : {
28
+ path,
29
+ message: `Invariant ${rule.name} violated: ${describeRule(rule, path)}`,
30
+ invariant: rule.name,
31
+ }),
32
+ };
33
+ },
34
+ placeholder(name) {
35
+ // An enum has no value to step to, so a rule on one, its own or one an
36
+ // enclosing object or sum writes on it, takes the first value that rule keeps
37
+ // among those the enum's own invariants keep; a decimal steps by the unit of
38
+ // its last digit.
39
+ const stepAt = (path) => {
40
+ const at = fieldOf(schema, path);
41
+ if (at?.kind === "enum") {
42
+ return { among: at.values.filter(value => at.invariants.every(rule => holds(rule, value))) };
43
+ }
44
+ return at?.kind === "decimal" ? decimalStep(at.scale)
45
+ : at?.kind === "int64" ? (value, direction) => value + BigInt(direction)
46
+ : at?.kind === "rational" ? (value, direction) => value.plus(new Rational(BigInt(direction))) : undefined;
47
+ };
48
+ return invariants
49
+ .flatMap(conjuncts)
50
+ .reduce((value, rule) => satisfy(rule, value, stepAt), core.placeholder(name));
51
+ },
52
+ refine(...args) {
53
+ const [name, rule] = args.length === 2 ? args : [undefined, args[0]];
54
+ if (name !== undefined && invariants.some(invariant => invariant.name === name)) {
55
+ throw new Error(`Invariant ${name} is declared more than once`);
56
+ }
57
+ const refined = name === undefined ? rule(selfTerm()) : { ...rule(selfTerm()), name };
58
+ const offGrid = offGridEquality(refined, keys => fieldOf(schema, keys), "$");
59
+ if (offGrid !== undefined) {
60
+ throw new Error(`refine ${offGrid}`);
61
+ }
62
+ return refinable(core, [...invariants, refined]);
63
+ },
64
+ describe(text) {
65
+ return refinable({ ...core, description: text }, invariants);
66
+ },
67
+ optional() {
68
+ return optional(schema);
69
+ },
70
+ };
71
+ // A bound is never a string, so a leading string is the invariant's name.
72
+ const bounded = (write) => (...args) => {
73
+ const bound = args[args.length - 1];
74
+ return typeof args[0] === "string" && args.length === 2
75
+ ? schema.refine(args[0], self => write(self, bound))
76
+ : schema.refine(self => write(self, bound));
77
+ };
78
+ if (ORDERED_KINDS.has(core.kind)) {
79
+ Object.assign(schema, {
80
+ min: bounded((v, bound) => v.$gte(bound)),
81
+ max: bounded((v, bound) => v.$lte(bound)),
82
+ gt: bounded((v, bound) => v.$gt(bound)),
83
+ lt: bounded((v, bound) => v.$lt(bound)),
84
+ });
85
+ }
86
+ if (core.kind === "string" || core.kind === "array" || core.kind === "record") {
87
+ Object.assign(schema, {
88
+ min: bounded((v, length) => v.$length().$gte(length)),
89
+ max: bounded((v, length) => v.$length().$lte(length)),
90
+ length: bounded((v, length) => v.$length().$eq(length)),
91
+ });
92
+ }
93
+ return schema;
94
+ }
95
+ export function string() {
96
+ return refinable({
97
+ kind: "string",
98
+ parse,
99
+ placeholder: (name = "string") => `<${name}>`,
100
+ });
101
+ function parse(value, path = "$") {
102
+ return typeof value === "string" && value.isWellFormed()
103
+ ? valid(value.normalize("NFC"))
104
+ : invalid(path, typeof value === "string" ? "Expected a well-formed Unicode string" : "Expected a string");
105
+ }
106
+ }
107
+ export function int64() {
108
+ return refinable({ kind: "int64", placeholder: () => 0n,
109
+ parse: (value, path = "$") => typeof value === "bigint" && value >= INT64_MIN && value <= INT64_MAX ? valid(value) : invalid(path, "Expected a signed 64-bit bigint"),
110
+ });
111
+ }
112
+ export function rational() {
113
+ return refinable({ kind: "rational", placeholder: () => new Rational(0n),
114
+ parse: (value, path = "$") => isRational(value) && value.denominator > 0n ? valid(new Rational(value.numerator, value.denominator)) : invalid(path, "Expected a Rational"),
115
+ });
116
+ }
117
+ export function number() {
118
+ return refinable({
119
+ kind: "number",
120
+ parse,
121
+ placeholder: () => 0,
122
+ });
123
+ function parse(value, path = "$") {
124
+ return typeof value === "number" && Number.isFinite(value)
125
+ ? valid(value)
126
+ : invalid(path, "Expected a finite number");
127
+ }
128
+ }
129
+ export function int() {
130
+ return refinable({
131
+ kind: "integer",
132
+ parse,
133
+ placeholder: () => 0,
134
+ });
135
+ function parse(value, path = "$") {
136
+ return Number.isSafeInteger(value)
137
+ ? valid(value)
138
+ : invalid(path, "Expected an integer");
139
+ }
140
+ }
141
+ // A Decimal from decimal.js with at most `scale` digits after the point, such as
142
+ // an amount in cents (`decimal(2)`), so the value next to a bound is known and
143
+ // arithmetic on it is exact.
144
+ export function decimal(scale) {
145
+ if (!Number.isSafeInteger(scale) || scale < 0) {
146
+ throw new Error(`decimal takes a whole number of digits, not ${scale}`);
147
+ }
148
+ return refinable({
149
+ kind: "decimal",
150
+ scale,
151
+ parse,
152
+ placeholder: () => new Decimal(0),
153
+ });
154
+ function parse(value, path = "$") {
155
+ if (!isDecimal(value) || !value.isFinite()) {
156
+ return invalid(path, "Expected a Decimal");
157
+ }
158
+ if (value.decimalPlaces() > scale) {
159
+ return invalid(path, `Expected a Decimal with at most ${scale} decimal places`);
160
+ }
161
+ // -0 is 0: a Decimal keeps the sign of a zero, and a row writing 0 must match.
162
+ return valid(value.isZero() && value.isNegative() ? value.abs() : value);
163
+ }
164
+ }
165
+ export function boolean() {
166
+ return refinable({
167
+ kind: "boolean",
168
+ parse,
169
+ placeholder: () => false,
170
+ });
171
+ function parse(value, path = "$") {
172
+ return typeof value === "boolean"
173
+ ? valid(value)
174
+ : invalid(path, "Expected a boolean");
175
+ }
176
+ }
177
+ export function instant() {
178
+ return refinable({
179
+ kind: "instant",
180
+ parse,
181
+ placeholder: () => temporalInstant().from("2000-01-01T00:00:00Z"),
182
+ });
183
+ function parse(value, path = "$") {
184
+ return value instanceof temporalInstant()
185
+ ? valid(value)
186
+ : invalid(path, "Expected a Temporal.Instant");
187
+ }
188
+ }
189
+ export function date() {
190
+ return plain("date", "PlainDate", "2000-01-01");
191
+ }
192
+ export function time() {
193
+ return plain("time", "PlainTime", "00:00");
194
+ }
195
+ export function datetime() {
196
+ return plain("datetime", "PlainDateTime", "2000-01-01T00:00");
197
+ }
198
+ function plain(kind, type, placeholder) {
199
+ return refinable({
200
+ kind,
201
+ parse: (value, path = "$") => value instanceof temporalPlain(type) ? valid(value) : invalid(path, `Expected a Temporal.${type}`),
202
+ placeholder: () => temporalPlain(type).from(placeholder),
203
+ });
204
+ }
205
+ // Exported as `enum`, a word a function may not be named. Each value is a class
206
+ // of the position the enum stands at, the way a boolean is two.
207
+ // What each value means is its second argument, as zod takes its options there:
208
+ // enum(["DRAFT", "SUBMITTED"], { labels: { DRAFT: "下書き", SUBMITTED: "申請中" } }).
209
+ export function enumOf(values, options = {}) {
210
+ if (values.some(value => !value.isWellFormed() || value !== value.normalize("NFC")))
211
+ throw new Error("Enum declarations must use NFC Unicode text");
212
+ if (values.length === 0) {
213
+ throw new Error("enum names no value");
214
+ }
215
+ const repeated = values.find((value, index) => values.indexOf(value) !== index);
216
+ if (repeated !== undefined) {
217
+ throw new Error(`enum names ${repeated} twice`);
218
+ }
219
+ const { labels } = options;
220
+ const unknown = Object.keys(labels ?? {}).find(key => !values.includes(key));
221
+ if (unknown !== undefined) {
222
+ throw new Error(`enum labels ${unknown}, which it does not name`);
223
+ }
224
+ return refinable({
225
+ kind: "enum",
226
+ values,
227
+ ...(labels === undefined ? {} : { labels }),
228
+ parse,
229
+ placeholder: () => values[0],
230
+ });
231
+ function parse(value, path = "$") {
232
+ if (typeof value === "string")
233
+ value = value.normalize("NFC");
234
+ return typeof value === "string" && values.includes(value)
235
+ ? valid(value)
236
+ : invalid(path, `Expected one of ${values.map(value => JSON.stringify(value)).join(", ")}`);
237
+ }
238
+ }
239
+ export function literal(expected) {
240
+ if (typeof expected === "string" && (!expected.isWellFormed() || expected !== expected.normalize("NFC")))
241
+ throw new Error("Literal declarations must use NFC Unicode text");
242
+ return refinable({
243
+ kind: "literal",
244
+ value: expected,
245
+ parse,
246
+ placeholder: () => expected,
247
+ });
248
+ function parse(value, path = "$") {
249
+ if (typeof value === "string")
250
+ value = value.normalize("NFC");
251
+ return value === expected
252
+ ? valid(expected)
253
+ : invalid(path, `Expected ${JSON.stringify(expected)}`);
254
+ }
255
+ }
256
+ export function object(shape) {
257
+ return refinable({
258
+ kind: "object",
259
+ shape,
260
+ parse,
261
+ placeholder,
262
+ });
263
+ function parse(value, path = "$") {
264
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
265
+ return invalid(path, "Expected an object");
266
+ }
267
+ const source = value;
268
+ const output = {};
269
+ const issues = [];
270
+ for (const [key, field] of Object.entries(shape)) {
271
+ const result = field.parse(source[key], `${path}.${key}`);
272
+ if (result.success) {
273
+ if (result.value !== undefined) {
274
+ output[key] = result.value;
275
+ }
276
+ }
277
+ else {
278
+ issues.push(...result.issues);
279
+ }
280
+ }
281
+ for (const key of Object.keys(source)) {
282
+ if (!Object.hasOwn(shape, key)) {
283
+ issues.push({ path: `${path}.${key}`, message: "Unexpected key" });
284
+ }
285
+ }
286
+ return issues.length > 0
287
+ ? { success: false, issues }
288
+ : valid(output);
289
+ }
290
+ function placeholder() {
291
+ const output = {};
292
+ for (const [key, field] of Object.entries(shape)) {
293
+ const value = field.placeholder(key);
294
+ if (value !== undefined) {
295
+ output[key] = value;
296
+ }
297
+ }
298
+ return output;
299
+ }
300
+ }
301
+ export function array(element) {
302
+ return refinable({
303
+ kind: "array",
304
+ element,
305
+ parse,
306
+ placeholder: (name) => [element.placeholder(name)],
307
+ });
308
+ function parse(value, path = "$") {
309
+ if (!Array.isArray(value)) {
310
+ return invalid(path, "Expected an array");
311
+ }
312
+ const output = [];
313
+ const issues = [];
314
+ value.forEach((item, index) => {
315
+ const result = element.parse(item, `${path}[${index}]`);
316
+ if (result.success) {
317
+ output.push(result.value);
318
+ }
319
+ else {
320
+ issues.push(...result.issues);
321
+ }
322
+ });
323
+ return issues.length > 0 ? { success: false, issues } : valid(output);
324
+ }
325
+ }
326
+ export function optional(schema) {
327
+ return refinable({
328
+ kind: "optional",
329
+ schema,
330
+ // A field reads the same whether it may be left out or not.
331
+ ...(schema.description === undefined ? {} : { description: schema.description }),
332
+ parse,
333
+ placeholder: () => undefined,
334
+ });
335
+ function parse(value, path = "$") {
336
+ return value === undefined ? valid(undefined) : schema.parse(value, path);
337
+ }
338
+ }
339
+ export function record(value) {
340
+ return refinable({
341
+ kind: "record",
342
+ value,
343
+ parse,
344
+ placeholder: (name) => ({ "<key>": value.placeholder(name) }),
345
+ });
346
+ function parse(raw, path = "$") {
347
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
348
+ return invalid(path, "Expected an object");
349
+ }
350
+ const output = {};
351
+ const issues = [];
352
+ for (const [key, item] of Object.entries(raw)) {
353
+ const result = value.parse(item, `${path}.${key}`);
354
+ if (result.success) {
355
+ output[key] = result.value;
356
+ }
357
+ else {
358
+ issues.push(...result.issues);
359
+ }
360
+ }
361
+ return issues.length > 0 ? { success: false, issues } : valid(output);
362
+ }
363
+ }
364
+ export function variants(discriminant, variants) {
365
+ const variantTags = Object.keys(variants);
366
+ return refinable({
367
+ kind: "variants",
368
+ discriminant,
369
+ variants,
370
+ variantTags,
371
+ parse,
372
+ placeholder: () => placeholderFor(variantTags[0]),
373
+ placeholderFor,
374
+ });
375
+ function parse(value, path = "$") {
376
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
377
+ return invalid(path, "Expected an object");
378
+ }
379
+ const source = value;
380
+ const tag = source[discriminant];
381
+ if (typeof tag !== "string" || !Object.hasOwn(variants, tag)) {
382
+ return invalid(`${path}.${discriminant}`, `Expected one of ${variantTags.join(", ")}`);
383
+ }
384
+ const variant = variants[tag];
385
+ if (variant === undefined) {
386
+ return invalid(`${path}.${discriminant}`, `Unknown variant ${tag}`);
387
+ }
388
+ const { [discriminant]: _tag, ...fields } = source;
389
+ const result = variant.parse(Object.hasOwn(variant.shape, discriminant) ? source : fields, path);
390
+ return result.success
391
+ ? valid({ [discriminant]: tag, ...result.value })
392
+ : result;
393
+ }
394
+ function placeholderFor(tag) {
395
+ const fields = variants[tag].placeholder();
396
+ return { [discriminant]: tag, ...fields };
397
+ }
398
+ }
399
+ export function isVariantsSchema(schema) {
400
+ return schema.kind === "variants";
401
+ }
402
+ export function tagOf(schema, value) {
403
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
404
+ return undefined;
405
+ }
406
+ const tag = value[schema.discriminant];
407
+ return typeof tag === "string" && schema.variantTags.includes(tag)
408
+ ? tag
409
+ : undefined;
410
+ }
411
+ function temporalInstant() {
412
+ const temporal = globalThis.Temporal;
413
+ if (temporal?.Instant === undefined) {
414
+ throw new Error("Temporal is unavailable; Chisel requires Node.js 26 or later");
415
+ }
416
+ return temporal.Instant;
417
+ }
418
+ function temporalPlain(type) {
419
+ const constructor = globalThis.Temporal?.[type];
420
+ if (constructor === undefined) {
421
+ throw new Error("Temporal is unavailable; Chisel requires Node.js 26 or later");
422
+ }
423
+ return constructor;
424
+ }
425
+ // An equality between a decimal and a value with more digits than it keeps
426
+ // settles without a row, so it is written by mistake.
427
+ export function holdsNoDecimal(schema, operator, bound) {
428
+ return schema.kind === "decimal" && offGrid(schema.scale, operator, bound);
429
+ }
430
+ function offGrid(scale, operator, bound) {
431
+ return (operator === "==" || operator === "!=") && isDecimal(bound) && bound.decimalPlaces() > scale;
432
+ }
433
+ // Says where a rule compares a decimal with such a value, reading each term's
434
+ // schema through `resolve` and an element of `all`/`any` through its array.
435
+ export function offGridEquality(rule, resolve, label, labels = {}) {
436
+ switch (rule.kind) {
437
+ case "and":
438
+ case "or":
439
+ return rule.rules.map(part => offGridEquality(part, resolve, label, labels)).find(Boolean);
440
+ case "not":
441
+ return offGridEquality(rule.rule, resolve, label, labels);
442
+ case "all":
443
+ case "any": {
444
+ const of = positionOf(rule.of).path;
445
+ const collection = resolve(of);
446
+ const element = collection?.kind === "array" ? collection.element : undefined;
447
+ const inner = (path) => path[0] === rule.element ? (element === undefined ? undefined : schemaAtPath(element, path.slice(1))) : resolve(path);
448
+ return offGridEquality(rule.each, inner, label, { ...labels, [rule.element]: `${nameOf(of, label, labels)}[]` });
449
+ }
450
+ case "compare": {
451
+ const [term, bound] = isTerm(rule.left) ? [rule.left, rule.right] : [rule.right, rule.left];
452
+ if (isTerm(term) && !isTerm(bound) && positionData(term) === undefined) {
453
+ return offGridExpression(rule, term, bound, resolve, label, labels);
454
+ }
455
+ const position = isTerm(term) && !isTerm(bound) ? positionData(term) : undefined;
456
+ if (position === undefined || position.measure !== "value") {
457
+ return undefined;
458
+ }
459
+ const { path } = position;
460
+ const schema = resolve(path);
461
+ return schema !== undefined && holdsNoDecimal(schema, rule.operator, bound)
462
+ ? `compares ${nameOf(path, label, labels)} with ${String(bound)}, which no decimal(${schema.scale}) holds: ${describeRule(rule, label, labels)}`
463
+ : undefined;
464
+ }
465
+ }
466
+ }
467
+ // An expression of integers and decimals takes only values on the grid of its
468
+ // finest decimal, shifted by its constant.
469
+ function offGridExpression(rule, term, bound, resolve, label, labels) {
470
+ const data = termData(term);
471
+ if (data.kind !== "linear" || !isDecimal(bound)) {
472
+ return undefined;
473
+ }
474
+ const scales = data.parts.map(part => {
475
+ const schema = part.measure === "length" ? undefined : resolve(part.path);
476
+ return part.measure === "length" || schema?.kind === "integer"
477
+ ? 0
478
+ : schema?.kind === "decimal"
479
+ ? schema.scale
480
+ : undefined;
481
+ });
482
+ const decimals = data.parts.filter(part => part.measure === "value" && resolve(part.path)?.kind === "decimal");
483
+ if (decimals.length === 0 || scales.some(scale => scale === undefined)) {
484
+ return undefined;
485
+ }
486
+ const scale = Math.max(...scales);
487
+ if (!offGrid(scale, rule.operator, bound.minus(data.constant))) {
488
+ return undefined;
489
+ }
490
+ const written = describeRule(rule, label, labels);
491
+ return `compares ${written.slice(0, written.lastIndexOf(` ${rule.operator} `))} with ${String(bound)}, which no decimal(${scale}) holds: ${written}`;
492
+ }
493
+ function nameOf(path, label, labels) {
494
+ const [first, ...rest] = path;
495
+ const [base, keys] = first !== undefined && labels[first] !== undefined ? [labels[first], rest] : [label, path];
496
+ return [base, ...keys].filter(part => part !== "").join(".");
497
+ }
498
+ // The schema a path reads, looked up through the cases of a sum as well, since a
499
+ // rule written on the sum names a field its cases hold.
500
+ function fieldOf(schema, keys) {
501
+ if (!isVariantsSchema(schema)) {
502
+ return schemaAtPath(schema, keys);
503
+ }
504
+ for (const each of Object.values(schema.variants)) {
505
+ const found = schemaAtPath(each, keys);
506
+ if (found !== undefined) {
507
+ return found;
508
+ }
509
+ }
510
+ return undefined;
511
+ }
512
+ export function schemaAtPath(schema, keys) {
513
+ const unwrapped = schema.kind === "optional" ? schema.schema : schema;
514
+ const [key, ...rest] = keys;
515
+ if (key === undefined) {
516
+ return unwrapped;
517
+ }
518
+ if (unwrapped.kind !== "object") {
519
+ return undefined;
520
+ }
521
+ const { shape } = unwrapped;
522
+ return Object.hasOwn(shape, key) ? schemaAtPath(shape[key], rest) : undefined;
523
+ }
524
+ //# sourceMappingURL=schema.js.map