@grafctory/blue 0.0.0-stage → 0.16.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 (139) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +524 -2
  3. package/dist/boolean/assembler.d.ts +53 -0
  4. package/dist/boolean/assembler.d.ts.map +1 -0
  5. package/dist/boolean/assembler.js +78 -0
  6. package/dist/boolean/assembler.js.map +1 -0
  7. package/dist/boolean/index.d.ts +86 -0
  8. package/dist/boolean/index.d.ts.map +1 -0
  9. package/dist/boolean/index.js +99 -0
  10. package/dist/boolean/index.js.map +1 -0
  11. package/dist/boolean/validator.d.ts +30 -0
  12. package/dist/boolean/validator.d.ts.map +1 -0
  13. package/dist/boolean/validator.js +68 -0
  14. package/dist/boolean/validator.js.map +1 -0
  15. package/dist/dictionary/assembler.d.ts +70 -0
  16. package/dist/dictionary/assembler.d.ts.map +1 -0
  17. package/dist/dictionary/assembler.js +178 -0
  18. package/dist/dictionary/assembler.js.map +1 -0
  19. package/dist/dictionary/index.d.ts +237 -0
  20. package/dist/dictionary/index.d.ts.map +1 -0
  21. package/dist/dictionary/index.js +43 -0
  22. package/dist/dictionary/index.js.map +1 -0
  23. package/dist/dictionary/inference.d.ts +42 -0
  24. package/dist/dictionary/inference.d.ts.map +1 -0
  25. package/dist/dictionary/inference.js +17 -0
  26. package/dist/dictionary/inference.js.map +1 -0
  27. package/dist/dictionary/validator.d.ts +37 -0
  28. package/dist/dictionary/validator.d.ts.map +1 -0
  29. package/dist/dictionary/validator.js +106 -0
  30. package/dist/dictionary/validator.js.map +1 -0
  31. package/dist/index.core.d.ts +33 -0
  32. package/dist/index.core.d.ts.map +1 -0
  33. package/dist/index.core.js +149 -0
  34. package/dist/index.core.js.map +1 -0
  35. package/dist/index.d.ts +333 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +378 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/number/assembler.d.ts +70 -0
  40. package/dist/number/assembler.d.ts.map +1 -0
  41. package/dist/number/assembler.js +188 -0
  42. package/dist/number/assembler.js.map +1 -0
  43. package/dist/number/index.d.ts +329 -0
  44. package/dist/number/index.d.ts.map +1 -0
  45. package/dist/number/index.js +312 -0
  46. package/dist/number/index.js.map +1 -0
  47. package/dist/number/validator.d.ts +31 -0
  48. package/dist/number/validator.d.ts.map +1 -0
  49. package/dist/number/validator.js +57 -0
  50. package/dist/number/validator.js.map +1 -0
  51. package/dist/reference/accessors.d.ts +29 -0
  52. package/dist/reference/accessors.d.ts.map +1 -0
  53. package/dist/reference/accessors.js +38 -0
  54. package/dist/reference/accessors.js.map +1 -0
  55. package/dist/reference/assembler.d.ts +63 -0
  56. package/dist/reference/assembler.d.ts.map +1 -0
  57. package/dist/reference/assembler.js +127 -0
  58. package/dist/reference/assembler.js.map +1 -0
  59. package/dist/reference/index.d.ts +108 -0
  60. package/dist/reference/index.d.ts.map +1 -0
  61. package/dist/reference/index.js +40 -0
  62. package/dist/reference/index.js.map +1 -0
  63. package/dist/reference/validator.d.ts +33 -0
  64. package/dist/reference/validator.d.ts.map +1 -0
  65. package/dist/reference/validator.js +56 -0
  66. package/dist/reference/validator.js.map +1 -0
  67. package/dist/resource/accessors.d.ts +140 -0
  68. package/dist/resource/accessors.d.ts.map +1 -0
  69. package/dist/resource/accessors.js +173 -0
  70. package/dist/resource/accessors.js.map +1 -0
  71. package/dist/resource/assembler.d.ts +265 -0
  72. package/dist/resource/assembler.d.ts.map +1 -0
  73. package/dist/resource/assembler.js +816 -0
  74. package/dist/resource/assembler.js.map +1 -0
  75. package/dist/resource/index.d.ts +903 -0
  76. package/dist/resource/index.d.ts.map +1 -0
  77. package/dist/resource/index.js +160 -0
  78. package/dist/resource/index.js.map +1 -0
  79. package/dist/resource/inference.d.ts +310 -0
  80. package/dist/resource/inference.d.ts.map +1 -0
  81. package/dist/resource/inference.js +17 -0
  82. package/dist/resource/inference.js.map +1 -0
  83. package/dist/resource/validator.d.ts +158 -0
  84. package/dist/resource/validator.d.ts.map +1 -0
  85. package/dist/resource/validator.js +1013 -0
  86. package/dist/resource/validator.js.map +1 -0
  87. package/dist/string/assembler.d.ts +69 -0
  88. package/dist/string/assembler.d.ts.map +1 -0
  89. package/dist/string/assembler.js +143 -0
  90. package/dist/string/assembler.js.map +1 -0
  91. package/dist/string/index.d.ts +431 -0
  92. package/dist/string/index.d.ts.map +1 -0
  93. package/dist/string/index.js +528 -0
  94. package/dist/string/index.js.map +1 -0
  95. package/dist/string/validator.d.ts +30 -0
  96. package/dist/string/validator.d.ts.map +1 -0
  97. package/dist/string/validator.js +69 -0
  98. package/dist/string/validator.js.map +1 -0
  99. package/dist/union/accessors.d.ts +137 -0
  100. package/dist/union/accessors.d.ts.map +1 -0
  101. package/dist/union/accessors.js +253 -0
  102. package/dist/union/accessors.js.map +1 -0
  103. package/dist/union/assembler.d.ts +56 -0
  104. package/dist/union/assembler.d.ts.map +1 -0
  105. package/dist/union/assembler.js +140 -0
  106. package/dist/union/assembler.js.map +1 -0
  107. package/dist/union/index.d.ts +172 -0
  108. package/dist/union/index.d.ts.map +1 -0
  109. package/dist/union/index.js +45 -0
  110. package/dist/union/index.js.map +1 -0
  111. package/dist/union/inference.d.ts +30 -0
  112. package/dist/union/inference.d.ts.map +1 -0
  113. package/dist/union/inference.js +17 -0
  114. package/dist/union/inference.js.map +1 -0
  115. package/dist/union/validator.d.ts +94 -0
  116. package/dist/union/validator.d.ts.map +1 -0
  117. package/dist/union/validator.js +171 -0
  118. package/dist/union/validator.js.map +1 -0
  119. package/dist/value/accessors.d.ts +151 -0
  120. package/dist/value/accessors.d.ts.map +1 -0
  121. package/dist/value/accessors.js +468 -0
  122. package/dist/value/accessors.js.map +1 -0
  123. package/dist/value/assembler.d.ts +129 -0
  124. package/dist/value/assembler.d.ts.map +1 -0
  125. package/dist/value/assembler.js +248 -0
  126. package/dist/value/assembler.js.map +1 -0
  127. package/dist/value/index.d.ts +309 -0
  128. package/dist/value/index.d.ts.map +1 -0
  129. package/dist/value/index.js +26 -0
  130. package/dist/value/index.js.map +1 -0
  131. package/dist/value/inference.d.ts +292 -0
  132. package/dist/value/inference.d.ts.map +1 -0
  133. package/dist/value/inference.js +17 -0
  134. package/dist/value/inference.js.map +1 -0
  135. package/dist/value/validator.d.ts +76 -0
  136. package/dist/value/validator.d.ts.map +1 -0
  137. package/dist/value/validator.js +111 -0
  138. package/dist/value/validator.js.map +1 -0
  139. package/package.json +95 -4
package/dist/index.js ADDED
@@ -0,0 +1,378 @@
1
+ /*
2
+ * Copyright © 2025-2026 Metreeca srl
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * Linked data validation.
18
+ *
19
+ * Provides shape-based validation for the values, retrieval templates and retrieved data crossing a service boundary.
20
+ * The {@link schema} function describes the payloads a shape admits as a JSON Schema, and the {@link validate}
21
+ * function returns either the value, typed as the shape describes it, or a trace of every violation found. A shape
22
+ * states once what a service accepts, so the description and the checks stay in one place instead of being restated
23
+ * across the interfaces and entry points that exchange data with clients.
24
+ *
25
+ * Shapes are stated with the per-kind modules {@link value! | value} gathers:
26
+ *
27
+ * ```typescript
28
+ * import { boolean } from '@grafctory/blue/boolean';
29
+ * import { integer } from '@grafctory/blue/number';
30
+ * import { id, multiple, optional, required, resource } from '@grafctory/blue/resource';
31
+ * import { date, string } from '@grafctory/blue/string';
32
+ *
33
+ * const Product = resource({
34
+ * id: id(),
35
+ * name: required(string({ minLength: 1, maxLength: 100 })),
36
+ * price: required(integer({ minInclusive: 0 })),
37
+ * available: optional(boolean()),
38
+ * tags: multiple(string()),
39
+ * released: optional(date())
40
+ * });
41
+ * ```
42
+ *
43
+ * **Describing a shape as JSON Schema**
44
+ *
45
+ * A shape also declares schema-driven consumers, such as API descriptions, language model tool interfaces and
46
+ * structured output formats, without a hand-written schema restating it. The {@link schema} function describes the
47
+ * payloads a resource shape admits as a JSON Schema (draft 2020-12). Its strict variant keeps to the subset of JSON
48
+ * Schema accepted by structured output generators, which reject the keywords and formats outside it:
49
+ *
50
+ * ```typescript
51
+ * import { schema } from '@grafctory/blue';
52
+ *
53
+ * schema(Product); // the payloads Product admits
54
+ * schema(Product, { strict: true }); // the same, for strict structured output generators
55
+ * ```
56
+ *
57
+ * **Collecting entry shapes and their dependencies**
58
+ *
59
+ * Model-wide encodings, such as vocabularies, schemas and documentation, cover every shape a set of entry shapes
60
+ * depends on rather than only the entry shapes themselves. The {@link model} function collects the entry shapes and
61
+ * the shapes they extend, link to or embed, each once and in a stable order, ready to be encoded as a whole:
62
+ *
63
+ * ```typescript
64
+ * import { model } from '@grafctory/blue';
65
+ * import { id, optional, resource } from '@grafctory/blue/resource';
66
+ * import { reference } from '@grafctory/blue/reference';
67
+ *
68
+ * const Vendor = resource({
69
+ * id: id()
70
+ * });
71
+ *
72
+ * const Offer = resource({
73
+ * id: id(),
74
+ * vendor: optional(reference(Vendor))
75
+ * });
76
+ *
77
+ * model(Offer); // [Offer, Vendor]
78
+ * ```
79
+ *
80
+ * **Matching a value against a shape**
81
+ *
82
+ * The same shape answers three questions; the `model` option settles which is being asked:
83
+ *
84
+ * ```typescript
85
+ * import { validate } from '@grafctory/blue';
86
+ *
87
+ * validate(product, { shape: Product })({ // a resource in its own right
88
+ * value: product => console.log(product.name),
89
+ * trace: trace => console.error(trace)
90
+ * });
91
+ *
92
+ * validate(response, { shape: Product, model: { name: {} } }); // a retrieval, narrowed by what was asked for
93
+ * validate(request, { shape: Product, model: true }); // a retrieval template, before it is issued
94
+ * ```
95
+ *
96
+ * - omitted, or `false`, matches `value` against the shape as a resource in its own right
97
+ * - a template matches `value` against the members that template asked for, and types what comes back accordingly
98
+ * - `true` matches `value` against the shape as a template, asking whether the shape can serve what it requests
99
+ *
100
+ * > [!CAUTION]
101
+ * > A template may draw on the full query language, including aggregate transforms and nested expansion. Hold an
102
+ * > untrusted caller to what the service will serve: `plain` refuses the aggregate transforms, `depth` caps the
103
+ * > nesting, and `limit` caps the page.
104
+ *
105
+ * @module index
106
+ *
107
+ * @see {@link https://json-schema.org/draft/2020-12/json-schema-core JSON Schema Core (draft 2020-12)}
108
+ * @see {@link https://www.w3.org/TR/shacl/ SHACL - Shapes Constraint Language}
109
+ */
110
+ import { isString, map, memo, opt } from "@grafctory/core";
111
+ import { some } from "@grafctory/core/arrays";
112
+ import { createRelay } from "@grafctory/core/relay";
113
+ import { equals, immutable, seal } from "@grafctory/core/values";
114
+ import { enforce } from "./index.core.js";
115
+ import { getShapeTarget } from "./reference/index.js";
116
+ import { validateResource, validateResult, validateTemplate } from "./resource/validator.js";
117
+ import { date, email, instant, iri, time, timestamp, url } from "./string/index.js";
118
+ import { eager } from "./value/index.js";
119
+ import { validateShape } from "./value/validator.js";
120
+ /**
121
+ * The seal marking a value as already validated.
122
+ *
123
+ * Carries what it was validated against, so that validating it again on the same terms is settled by the seal rather
124
+ * than by walking the value a second time.
125
+ */
126
+ const Validated = Symbol("validated");
127
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
128
+ /**
129
+ * The JSON Schema converted for a shape in each mode, retained for the lifetime of the module (see {@link memo}).
130
+ */
131
+ const schemas = memo((strict) => {
132
+ /**
133
+ * The JSON Schema format each well-known lexical pattern stands for; only `strict` formats are carried by strict
134
+ * schemas, as strict structured output generators reject the others, while plain schemas carry every format.
135
+ *
136
+ * Built on first conversion rather than at module load, as the string module imports this one through a cycle.
137
+ */
138
+ const formats = new Map([
139
+ [url().pattern, { format: "uri" }],
140
+ [iri().pattern, { format: "iri-reference" }],
141
+ [email().pattern, { format: "email", strict: true }],
142
+ [date().pattern, { format: "date", strict: true }],
143
+ [time().pattern, { format: "time", strict: true }],
144
+ [instant().pattern, { format: "date-time", strict: true }],
145
+ [timestamp().pattern, { format: "date-time", strict: true }]
146
+ ]);
147
+ return memo((shape) => immutable(value(shape)));
148
+ function value(shape) {
149
+ switch (shape.kind) {
150
+ case "boolean":
151
+ return {
152
+ type: "boolean"
153
+ };
154
+ case "number":
155
+ return {
156
+ type: shape.integral ? "integer" : "number",
157
+ ...opt(shape.minInclusive, minimum => ({ minimum })),
158
+ ...opt(shape.maxInclusive, maximum => ({ maximum }))
159
+ };
160
+ case "string":
161
+ return {
162
+ type: "string",
163
+ ...opt(shape.in, values => ({ enum: [...values] })),
164
+ ...opt(formats.get(shape.pattern), ({ format, strict: supported }) => strict && !supported ? {} : { format }),
165
+ ...opt(shape.pattern, pattern => ({ pattern })),
166
+ ...opt(shape.minLength, minLength => ({ minLength })),
167
+ ...opt(shape.maxLength, maxLength => ({ maxLength }))
168
+ };
169
+ case "reference":
170
+ return {
171
+ type: "string",
172
+ ...(strict ? {} : { format: "iri-reference" })
173
+ };
174
+ case "resource":
175
+ const properties = Object.entries(shape.members).flatMap(([name, member]) => member.kind === "property" ? [{ name, member }] : []);
176
+ const required = properties
177
+ .filter(({ member: { range: { minCount = 0 } } }) => strict || minCount > 0)
178
+ .map(({ name }) => name);
179
+ return {
180
+ type: "object",
181
+ ...annotations(shape),
182
+ properties: Object.fromEntries(properties.map(({ name, member }) => [name, property(member)])),
183
+ ...(required.length > 0 ? { required } : {}),
184
+ additionalProperties: false
185
+ };
186
+ case "dictionary": // keyed by the language tags a value happens to carry, which a schema has no way to name
187
+ throw new RangeError(`unsupported localised <${shape.kind}> range in JSON Schema`);
188
+ case "union":
189
+ return {
190
+ anyOf: shape.branches.map(branch => value(eager(branch)))
191
+ };
192
+ }
193
+ }
194
+ function property({ range: { shape, minCount = 0, maxCount }, ...member }) {
195
+ const items = value(eager(shape));
196
+ return {
197
+ ...(maxCount !== 1 ? { type: "array", items }
198
+ : strict && minCount === 0 ? { anyOf: [items, { type: "null" }] }
199
+ : items),
200
+ ...annotations(member)
201
+ };
202
+ }
203
+ function annotations({ name, description }) {
204
+ return {
205
+ ...opt(english(name), title => ({ title })),
206
+ ...opt(english(description), description => ({ description }))
207
+ };
208
+ }
209
+ function english(text) {
210
+ return opt(text, text => isString(text) ? text
211
+ : opt(text.en, entry => isString(entry) ? entry : entry.join("\n\n")));
212
+ }
213
+ });
214
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
215
+ /**
216
+ * Converts a resource shape into a JSON Schema.
217
+ *
218
+ * A resource is described as an object with one property per member. Like the shape, the object is closed and admits
219
+ * no other property. Members requiring at least one value are required, and a member admitting more than one value is
220
+ * described as an array of its range. Identifier and class members are left out, as they name the resource rather than
221
+ * describe it, so a payload stating them is rejected. A {@link reference!reference | reference} is described as the
222
+ * IRI it carries, and an embedded resource as a nested object. A {@link union!union | union} is described as the
223
+ * alternatives it admits, so the schema accepts a value conforming to any one of its branches.
224
+ *
225
+ * Value constraints are carried through: the bounds of a number and whether it is an integer, and the values, length
226
+ * bounds and lexical pattern of a string. A string in a well-known lexical form also carries the matching `format`, a
227
+ * hint for the consumers that recognise it about the kind of value expected and how to present or check it:
228
+ *
229
+ * - {@link string!url | url} as `uri`, {@link string!iri | iri} as `iri-reference`
230
+ * - {@link string!email | email} as `email`
231
+ * - {@link string!date | date} as `date`, {@link string!time | time} as `time`
232
+ * - {@link string!instant | instant} and {@link string!timestamp | timestamp} as `date-time`
233
+ *
234
+ * Values are still held to the pattern alone: a validator asserting formats may reject values the shape admits, such
235
+ * as a time with no zone offset, so formats are best read as annotations rather than as constraints.
236
+ *
237
+ * The name and description of a resource and of each member are carried as `title` and `description`. A member
238
+ * admitting more than one value annotates the array rather than its items. Localised names and descriptions are
239
+ * carried in English, and are left out if they are stated in no English, as a schema has room for one language only.
240
+ *
241
+ * A strict schema keeps to the subset of JSON Schema accepted by strict structured output generators. Every member is
242
+ * required. An optional single-valued member also admits `null` for an absent value, and an absent multi-valued member
243
+ * is stated as an empty array. A payload generated under a strict schema therefore conforms to the shape only once its
244
+ * `null` members are dropped. No string carries the `uri` or `iri-reference` format: IRI strings are held to their
245
+ * pattern, and references only to being strings, as strict generators reject both formats.
246
+ *
247
+ * The returned schema is deeply immutable. Conversions are cached, so converting the same shape again with the same
248
+ * options returns the same schema at no cost, whether the shape is passed as is or deferred. Cached schemas are kept
249
+ * for the lifetime of the module, so shapes are best declared once rather than built anew on each conversion.
250
+ *
251
+ * @param shape The resource shape to convert, possibly deferred
252
+ * @param options The conversion options
253
+ *
254
+ * @returns The JSON Schema describing the values `shape` admits
255
+ *
256
+ * @throws {@link @grafctory/core!TraceError | TraceError} Where `shape` is malformed, as where it embeds itself with no
257
+ * link to break the cycle and so admits no finite payload a schema could describe
258
+ * @throws {@link !RangeError RangeError} If `shape` admits a {@link dictionary!dictionary | localised} value range at
259
+ * any depth, as a JSON Schema has no way to name the language tags keying each localised value it describes
260
+ *
261
+ * @see {@link https://json-schema.org/draft/2020-12/json-schema-validation#section-7.3 JSON Schema § 7.3 Defined Formats}
262
+ */
263
+ export function schema(shape, { strict = false } = {}) {
264
+ return schemas(strict)(eager(shape));
265
+ }
266
+ /**
267
+ * Collects entry shapes and their dependencies.
268
+ *
269
+ * A shape depends on the shapes it extends and on the shapes its properties link to or embed, directly or through
270
+ * other shapes. Dependencies include the targets of {@link resource!PropertyConstraints.foreign | foreign} properties
271
+ * and the resource alternatives of {@link union!union | unions}, so the listing covers the whole connected model.
272
+ *
273
+ * Each shape is listed once, even where shapes link to each other in a cycle. The entry shapes come first, in the
274
+ * order given, followed by their dependencies, nearest first. Shapes at the same distance follow the order of the
275
+ * shapes reaching them, each contributing its parents before its property targets, in declaration order.
276
+ *
277
+ * Shapes are compared by reference, so a merged shape is listed alongside the shapes it merges. A property embedding
278
+ * different shapes along different inheritance paths, or re-pointed at a narrower embedded shape, ranges over a new
279
+ * shape stating the class of the narrowest, and the listing may then hold two shapes of that class. A shape embedded
280
+ * alike along every path is listed once, provided the shared definition is passed as its factory, as in
281
+ * `optional(Image)`, rather than built by separate calls to it, which return distinct shapes.
282
+ *
283
+ * @param shapes The entry shape or shapes, possibly deferred
284
+ *
285
+ * @returns The entry shapes followed by their dependencies; empty if `shapes` is empty
286
+ *
287
+ * @see {@link https://www.w3.org/TR/shacl/#shapes-graph SHACL § 3.1 Shapes Graph}
288
+ */
289
+ export function model(shapes) {
290
+ return reachable(some(shapes).map(eager), []);
291
+ function reachable(pending, visited) {
292
+ const [head, ...tail] = pending;
293
+ return head === undefined ? visited
294
+ : visited.includes(head) ? reachable(tail, visited)
295
+ : reachable([...tail, ...neighbours(head)], [...visited, head]);
296
+ }
297
+ function neighbours({ parents, members }) {
298
+ return [
299
+ ...parents.map(eager),
300
+ ...Object.values(members).flatMap(member => member.kind === "property" ? targets(member.range.shape) : [])
301
+ ];
302
+ }
303
+ function targets(shape) {
304
+ const resolved = eager(shape);
305
+ return resolved.kind === "union"
306
+ ? resolved.branches.flatMap(targets)
307
+ : opt(getShapeTarget(resolved), target => [target], []);
308
+ }
309
+ }
310
+ /**
311
+ * Validates a value against a shape.
312
+ */
313
+ export function validate(value, { shape, model, entry, plain, depth, limit }) {
314
+ return map(eager(shape), shape => {
315
+ if (shape.kind !== "resource") {
316
+ // a value outside a resource carries nothing to seal, so it is matched as it stands
317
+ const trace = validateShape([value], shape, { scope: model === true ? "model" : "state" });
318
+ return trace !== undefined ? createRelay({ trace }) : createRelay({ value });
319
+ }
320
+ else if (model === true) {
321
+ return verify(sealed => sealed.model === true
322
+ && (!plain || sealed.plain === true)
323
+ && (depth === undefined || sealed.depth !== undefined && sealed.depth <= depth)
324
+ && (!limit || !!sealed.limit && sealed.limit <= limit), // a limit of 0 leaves the page unbounded
325
+ () => validateTemplate([value], shape, { plain, depth, limit }), {
326
+ model: true,
327
+ shape,
328
+ plain,
329
+ depth,
330
+ limit
331
+ }, () => enforce(value, shape, { limit }));
332
+ }
333
+ else if (model) {
334
+ return verify(sealed => equals(sealed.model, model)
335
+ && (entry === undefined || sealed.entry === entry), () => validateResult([value], { shape, model, entry }), {
336
+ model,
337
+ shape,
338
+ entry
339
+ });
340
+ }
341
+ else {
342
+ return verify(sealed => sealed.model === false
343
+ && (entry === undefined || sealed.entry === entry)
344
+ && (depth === undefined || sealed.depth !== undefined && sealed.depth <= depth), () => validateResource([value], shape, { entry, depth }), {
345
+ model: false,
346
+ shape,
347
+ entry,
348
+ depth
349
+ });
350
+ }
351
+ });
352
+ /**
353
+ * Settles a resource validation against the seal the value may already carry.
354
+ *
355
+ * @param match Tells whether a seal already granted what this validation asks for; the shape the seal was reached
356
+ * under is matched beforehand
357
+ * @param check Runs the validation where the seal settles nothing
358
+ * @param terms The terms to seal on a value that passes
359
+ * @param content Yields the value to seal, defaulting to the one validated
360
+ *
361
+ * @returns A {@link Relay} carrying the value where it passes and a trace of the violations where it doesn't
362
+ */
363
+ function verify(match, check, terms, content = () => value) {
364
+ const sealed = seal(value, Validated);
365
+ const settled = sealed !== undefined && sealed.shape === terms.shape && match(sealed);
366
+ const trace = settled ? undefined : opt(check(), unkeyed);
367
+ return trace !== undefined ? createRelay({ trace })
368
+ : settled ? createRelay({ value })
369
+ : createRelay({ value: seal(content(), Validated, terms) });
370
+ }
371
+ /**
372
+ * Keys the violations of the single value validated by the member or slot at fault rather than by the value.
373
+ */
374
+ function unkeyed(trace) {
375
+ return trace.flatMap(entry => isString(entry) ? [entry] : Object.values(entry).flat());
376
+ }
377
+ }
378
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6FG;AAEH,OAAO,EAAE,QAAQ,EAAa,GAAG,EA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AAG,CAAC,KAAK,EAAE,EAAE,OAAO,CAAC,CAAC;QAE1D,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,CAAC;YAClD,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,CAAC;gBACjC,CAAC,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;IAE/D,CAAC;IAED;;OAEG;IACH,SAAS,OAAO,CAAC,KAAY;QAC5B,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;IACxF,CAAC;AAEF,CAAC"}
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Number shape assembly.
3
+ *
4
+ * Builds the shape a factory states into the form its consumers read, and combines it with the one it overrides: a
5
+ * shape admitting no value at all is rejected as it is built rather than when a value is first matched against it, and
6
+ * an extension is held to the shape it refines before either is committed to.
7
+ *
8
+ * @module
9
+ */
10
+ import { type Optional } from "@grafctory/core";
11
+ import { type Trace } from "@grafctory/core/trace";
12
+ import { type NumberConstraints, type NumberShape } from "./index.js";
13
+ /**
14
+ * Assembles a number shape.
15
+ *
16
+ * Backs every factory the {@link number!} module exposes, fixing what they share: contradictory constraints are
17
+ * rejected as the shape is built, so that a shape that exists admits at least one value.
18
+ *
19
+ * @typeParam V The values the shape admits, as stated by the signature of the calling factory
20
+ *
21
+ * @param constraints The stated shape {@link NumberConstraints constraints}
22
+ *
23
+ * @returns An immutable shape admitting the numbers the constraints bound
24
+ *
25
+ * @throws {@link @grafctory/core!TraceError | TraceError} Where the stated constraints contradict one another
26
+ */
27
+ export declare function assemble<V extends number>(constraints: NumberConstraints): NumberShape<V>;
28
+ /**
29
+ * Checks a set of numeric constraints for internal consistency.
30
+ *
31
+ * Reports the contradictions that would leave a shape admitting no value at all, bounds crossing one another and an
32
+ * integral range enclosing no integer among them, so that a shape is rejected as it is built rather than when a value
33
+ * is first matched against it.
34
+ *
35
+ * @param constraints The constraints to check
36
+ *
37
+ * @returns A trace of the inconsistencies found, or `undefined` where the constraints admit at least one value
38
+ */
39
+ export declare function checkNumber(constraints: Partial<NumberShape>): Optional<Trace>;
40
+ /**
41
+ * Reports whether a number shape narrows an inherited one.
42
+ *
43
+ * Tests the override relation without building the merged shape, so that an incompatible extension is told apart from
44
+ * a legitimate refinement before either is committed to: a shape narrows the inherited one where it matches its
45
+ * `datatype`, keeps its integrality, leaves no bound wider, keeps at least one of its admitted values, requires every
46
+ * value it requires, and yields a consistent set of merged constraints.
47
+ *
48
+ * @param target The overriding shape
49
+ * @param source The inherited shape
50
+ *
51
+ * @returns A trace of the obstacles to the override, or `undefined` where `target` narrows `source`
52
+ */
53
+ export declare function narrowsNumber(target: NumberShape, source: NumberShape): Optional<Trace>;
54
+ /**
55
+ * Merges a number shape with an inherited one.
56
+ *
57
+ * Yields the single shape an extending member is validated against, combining the inherited constraints with the
58
+ * overriding ones: bounds and `hasValue` requirements accumulate, the admitted values intersect, and `datatype` and
59
+ * `integral` carry through from whichever shape states them. Inclusive and exclusive bounds accumulate independently,
60
+ * so a child may narrow a range through the bound of its choice without dropping the inherited one.
61
+ *
62
+ * @param target The overriding shape
63
+ * @param source The inherited shape
64
+ *
65
+ * @returns An immutable shape admitting the values both `target` and `source` admit
66
+ *
67
+ * @throws {@link @grafctory/core!TraceError | TraceError} Where `target` doesn't narrow `source`
68
+ */
69
+ export declare function mergeNumber(target: NumberShape, source: NumberShape): NumberShape;
70
+ //# sourceMappingURL=assembler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assembler.d.ts","sourceRoot":"","sources":["../../src/number/assembler.ts"],"names":[],"mappings":"AAiBA;;;;;;;;GAQG;AAEH,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EAAa,KAAK,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAE9D,OAAO,EAAE,KAAK,iBAAiB,EAAE,KAAK,WAAW,EAAE,MAAM,YAAY,CAAC;AA2CtE;;;;;;;;;;;;;GAaG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,MAAM,EAAE,WAAW,EAAE,iBAAiB,GAAG,WAAW,CAAC,CAAC,CAAC,CAczF;AAKD;;;;;;;;;;GAUG;AACH,wBAAgB,WAAW,CAAC,WAAW,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAkE9E;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,WAAW,GAAG,QAAQ,CAAC,KAAK,CAAC,CA8BvF;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,WAAW,GAAG,WAAW,CAYjF"}
@@ -0,0 +1,188 @@
1
+ /*
2
+ * Copyright © 2025-2026 Metreeca srl
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { immutable } from "@grafctory/core/values";
17
+ import { all, test } from "@grafctory/core/trace";
18
+ import { checkDomain, intersect, narrowsDatatype, narrowsDomain, reject, unite } from "../value/assembler.js";
19
+ /**
20
+ * Every bound a range states, in the order they are reported in.
21
+ */
22
+ const Bounds = [
23
+ "minExclusive",
24
+ "maxExclusive",
25
+ "minInclusive",
26
+ "maxInclusive"
27
+ ];
28
+ /**
29
+ * The bound pairs enclosing a range, each with whether the lower bound must fall strictly below the upper one.
30
+ */
31
+ const Ranges = [
32
+ ["minExclusive", "maxExclusive", true],
33
+ ["minInclusive", "maxInclusive", false],
34
+ ["minExclusive", "maxInclusive", true],
35
+ ["minInclusive", "maxExclusive", true]
36
+ ];
37
+ /**
38
+ * The bounds an override may only tighten, each with the relation holding it to the inherited limit.
39
+ */
40
+ const Limits = [
41
+ ["minExclusive", (limit, inherited) => limit >= inherited],
42
+ ["maxExclusive", (limit, inherited) => limit <= inherited],
43
+ ["minInclusive", (limit, inherited) => limit >= inherited],
44
+ ["maxInclusive", (limit, inherited) => limit <= inherited]
45
+ ];
46
+ /**
47
+ * Assembles a number shape.
48
+ *
49
+ * Backs every factory the {@link number!} module exposes, fixing what they share: contradictory constraints are
50
+ * rejected as the shape is built, so that a shape that exists admits at least one value.
51
+ *
52
+ * @typeParam V The values the shape admits, as stated by the signature of the calling factory
53
+ *
54
+ * @param constraints The stated shape {@link NumberConstraints constraints}
55
+ *
56
+ * @returns An immutable shape admitting the numbers the constraints bound
57
+ *
58
+ * @throws {@link @grafctory/core!TraceError | TraceError} Where the stated constraints contradict one another
59
+ */
60
+ export function assemble(constraints) {
61
+ const shape = immutable({
62
+ kind: "number",
63
+ ...constraints
64
+ }); // ;(cast) the factory signatures fix the admitted values to the enumerated ones
65
+ reject("inconsistent number shape constraints", checkNumber(shape));
66
+ return shape;
67
+ }
68
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
69
+ /**
70
+ * Checks a set of numeric constraints for internal consistency.
71
+ *
72
+ * Reports the contradictions that would leave a shape admitting no value at all, bounds crossing one another and an
73
+ * integral range enclosing no integer among them, so that a shape is rejected as it is built rather than when a value
74
+ * is first matched against it.
75
+ *
76
+ * @param constraints The constraints to check
77
+ *
78
+ * @returns A trace of the inconsistencies found, or `undefined` where the constraints admit at least one value
79
+ */
80
+ export function checkNumber(constraints) {
81
+ return all(test(constraints => {
82
+ const crossed = Ranges.flatMap(([min, max, strict]) => {
83
+ const lower = constraints[min];
84
+ const upper = constraints[max];
85
+ return lower === undefined || upper === undefined || (strict ? lower < upper : lower <= upper) ? []
86
+ : [`{${min}/${max}} inconsistent bounds <${lower}> ${strict ? ">=" : ">"} <${upper}>`];
87
+ });
88
+ return crossed.length === 0 || crossed;
89
+ }), checkDomain(), test(constraints => {
90
+ const fractional = !constraints.integral ? [] : Bounds.flatMap(bound => {
91
+ const limit = constraints[bound];
92
+ return limit === undefined || Number.isInteger(limit) ? []
93
+ : [`{${bound}} fractional bound <${limit}> on integral shape`];
94
+ });
95
+ return fractional.length === 0 || fractional;
96
+ }), test(({ integral, in: allowed }) => {
97
+ return !integral || allowed === undefined || allowed.every(v => Number.isInteger(v)) || [
98
+ `{in} fractional values [${allowed.filter(v => !Number.isInteger(v))}] on integral shape`
99
+ ];
100
+ }), test(({ integral, hasValue }) => {
101
+ return !integral || hasValue === undefined || hasValue.every(v => Number.isInteger(v)) || [
102
+ `{hasValue} fractional values [${hasValue.filter(v => !Number.isInteger(v))}] on integral shape`
103
+ ];
104
+ }), test(({ integral, minInclusive, minExclusive, maxInclusive, maxExclusive }) => {
105
+ const lower = Math.max(minInclusive !== undefined ? Math.ceil(minInclusive) : -Infinity, minExclusive !== undefined ? Math.floor(minExclusive) + 1 : -Infinity);
106
+ const upper = Math.min(maxInclusive !== undefined ? Math.floor(maxInclusive) : Infinity, maxExclusive !== undefined ? Math.ceil(maxExclusive) - 1 : Infinity);
107
+ return !integral || lower <= upper || [
108
+ `{range} no integer within bounds <[${lower}, ${upper}]>`
109
+ ];
110
+ }))(constraints);
111
+ }
112
+ /**
113
+ * Reports whether a number shape narrows an inherited one.
114
+ *
115
+ * Tests the override relation without building the merged shape, so that an incompatible extension is told apart from
116
+ * a legitimate refinement before either is committed to: a shape narrows the inherited one where it matches its
117
+ * `datatype`, keeps its integrality, leaves no bound wider, keeps at least one of its admitted values, requires every
118
+ * value it requires, and yields a consistent set of merged constraints.
119
+ *
120
+ * @param target The overriding shape
121
+ * @param source The inherited shape
122
+ *
123
+ * @returns A trace of the obstacles to the override, or `undefined` where `target` narrows `source`
124
+ */
125
+ export function narrowsNumber(target, source) {
126
+ return all(narrowsDatatype(source), test(({ integral }) => {
127
+ return integral !== false || source.integral !== true || [
128
+ `{integral} dropped integral constraint`
129
+ ];
130
+ }), test(target => {
131
+ const widened = Limits.flatMap(([bound, narrows]) => {
132
+ const limit = target[bound];
133
+ const inherited = source[bound];
134
+ return limit === undefined || inherited === undefined || narrows(limit, inherited) ? []
135
+ : [`{${bound}} widened limit <${limit}> beyond <${inherited}>`];
136
+ });
137
+ return widened.length === 0 || widened;
138
+ }), narrowsDomain(source), () => checkNumber(merge(target, source)) // post-merge constraint consistency
139
+ )(target);
140
+ }
141
+ /**
142
+ * Merges a number shape with an inherited one.
143
+ *
144
+ * Yields the single shape an extending member is validated against, combining the inherited constraints with the
145
+ * overriding ones: bounds and `hasValue` requirements accumulate, the admitted values intersect, and `datatype` and
146
+ * `integral` carry through from whichever shape states them. Inclusive and exclusive bounds accumulate independently,
147
+ * so a child may narrow a range through the bound of its choice without dropping the inherited one.
148
+ *
149
+ * @param target The overriding shape
150
+ * @param source The inherited shape
151
+ *
152
+ * @returns An immutable shape admitting the values both `target` and `source` admit
153
+ *
154
+ * @throws {@link @grafctory/core!TraceError | TraceError} Where `target` doesn't narrow `source`
155
+ */
156
+ export function mergeNumber(target, source) {
157
+ reject("incompatible number shape override", narrowsNumber(target, source));
158
+ return immutable({
159
+ kind: target.kind,
160
+ ...merge(target, source)
161
+ });
162
+ }
163
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
164
+ /**
165
+ * Combines the constraints of an overriding shape with the inherited ones.
166
+ *
167
+ * @param target The overriding shape
168
+ * @param source The inherited shape
169
+ *
170
+ * @returns The merged constraints, as they stand before they are checked for consistency
171
+ */
172
+ function merge(target, source) {
173
+ return {
174
+ // structural: datatype — equal where both are stated
175
+ datatype: target.datatype ?? source.datatype,
176
+ // conjunctive: integral — added but never dropped
177
+ integral: target.integral ?? source.integral,
178
+ // conjunctive: bounds — the tighter limit, each pair merged independently
179
+ minExclusive: target.minExclusive ?? source.minExclusive,
180
+ maxExclusive: target.maxExclusive ?? source.maxExclusive,
181
+ minInclusive: target.minInclusive ?? source.minInclusive,
182
+ maxInclusive: target.maxInclusive ?? source.maxInclusive,
183
+ // conjunctive: in — intersection; hasValue — union
184
+ in: intersect(target.in, source.in),
185
+ hasValue: unite(target.hasValue, source.hasValue)
186
+ };
187
+ }
188
+ //# sourceMappingURL=assembler.js.map