@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/README.md CHANGED
@@ -1,3 +1,525 @@
1
- # Temporary Holding Version
1
+ # @grafctory/blue
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm][npm-badge]][npm]
4
+
5
+ [npm-badge]: https://img.shields.io/npm/v/@grafctory/blue
6
+ [npm]: https://www.npmjs.com/package/@grafctory/blue
7
+ [grafctory]: https://github.com/grafctory
8
+
9
+ Declarative blueprints for model-driven linked data processing.
10
+
11
+ **@grafctory/blue** is the schema module of the [Grafctory][grafctory] model-driven knowledge graph framework. It
12
+ describes resources as shapes over the data model defined by [@grafctory/qest], and the same shapes drive storage in
13
+ [@grafctory/keep] and HTTP endpoints in [@grafctory/gate].
14
+
15
+ Shape-based schemas go beyond structural validation, capturing the complete semantics of a resource (structure,
16
+ constraints, metadata, and relationships), enabling them to act as a single source of truth for automated validation,
17
+ persistence, API publishing, UI generation, and more:
18
+
19
+ - **Define Once, Use Everywhere**: a single schema drives all automated processes
20
+ - **Guaranteed Consistency**: schema changes propagate to all dependent processes automatically
21
+ - **Less Code to Maintain**: declarative definitions replace scattered imperative logic
22
+
23
+ **@grafctory/blue** is designed for a broad range of model-driven tasks and ships with a robust and ready-to-use
24
+ validation engine:
25
+
26
+ - **No Type Duplication**: types and validation rules derived from a single schema
27
+ - **One Schema, Every Mode**: same schema validates state, updates, projections, and queries
28
+ - **Actionable Error Feedback**: per-value, per-property traces surface precise violations
29
+ - **Custom When Needed**: pluggable validators extend built-in constraints
30
+
31
+ [@grafctory/qest]: https://github.com/grafctory/qest
32
+ [@grafctory/keep]: https://github.com/grafctory/keep
33
+ [@grafctory/gate]: https://github.com/grafctory/gate
34
+
35
+ # Installation
36
+
37
+ ```shell
38
+ npm install @grafctory/blue
39
+ ```
40
+
41
+ > [!WARNING]
42
+ >
43
+ > TypeScript consumers must use `"moduleResolution": "nodenext"/"node16"/"bundler"` in `tsconfig.json`.
44
+ > The legacy `"node"` resolver is not supported.
45
+
46
+ # Usage
47
+
48
+ > [!NOTE]
49
+ >
50
+ > This section introduces essential concepts; for complete coverage, see the API reference:
51
+ >
52
+ > | Module | Description |
53
+ > |------------------------------|---------------------------------------|
54
+ > | [@grafctory/blue] | Linked data validation |
55
+ > | [@grafctory/blue/value] | Value shape types and operations |
56
+ > | [@grafctory/blue/boolean] | Boolean shape types and operations |
57
+ > | [@grafctory/blue/number] | Number shape types and operations |
58
+ > | [@grafctory/blue/string] | String shape types and operations |
59
+ > | [@grafctory/blue/dictionary] | Dictionary shape types and operations |
60
+ > | [@grafctory/blue/reference] | Reference shape types and operations |
61
+ > | [@grafctory/blue/resource] | Resource shape types and operations |
62
+ > | [@grafctory/blue/union] | Union shape types and operations |
63
+
64
+ [@grafctory/blue]: https://grafctory.github.io/blue/modules/index.html
65
+
66
+ [@grafctory/blue/value]: https://grafctory.github.io/blue/modules/value.html
67
+
68
+ [@grafctory/blue/boolean]: https://grafctory.github.io/blue/modules/boolean.html
69
+
70
+ [@grafctory/blue/number]: https://grafctory.github.io/blue/modules/number.html
71
+
72
+ [@grafctory/blue/string]: https://grafctory.github.io/blue/modules/string.html
73
+
74
+ [@grafctory/blue/dictionary]: https://grafctory.github.io/blue/modules/dictionary.html
75
+
76
+ [@grafctory/blue/reference]: https://grafctory.github.io/blue/modules/reference.html
77
+
78
+ [@grafctory/blue/resource]: https://grafctory.github.io/blue/modules/resource.html
79
+
80
+ [@grafctory/blue/union]: https://grafctory.github.io/blue/modules/union.html
81
+
82
+
83
+ ## Defining Schemas
84
+
85
+ Schemas describe the expected structure of a resource using shape factories:
86
+
87
+ ```ts
88
+ import { union } from "@grafctory/blue/union";
89
+ import { boolean } from "@grafctory/blue/boolean";
90
+ import { number } from "@grafctory/blue/number";
91
+ import { string, url } from "@grafctory/blue/string";
92
+ import { dictionary } from "@grafctory/blue/dictionary";
93
+ import { reference } from "@grafctory/blue/reference";
94
+ import { id, multiple, optional, required, resource, type } from "@grafctory/blue/resource";
95
+
96
+
97
+ function Thing() {
98
+ return resource({
99
+ id: id(),
100
+ type: type()
101
+ });
102
+ }
103
+
104
+ function Product() {
105
+ return resource(Thing, {
106
+ name: required(dictionary()),
107
+ description: optional(dictionary()),
108
+ price: required(number({ minInclusive: 0 })),
109
+ inStock: required(boolean()),
110
+ tags: multiple(string()),
111
+ rating: optional(Rating),
112
+ vendor: required(reference(Vendor))
113
+ });
114
+ }
115
+
116
+ function Rating() {
117
+ return resource({
118
+ average: required(number({ minInclusive: 0, maxInclusive: 5 })),
119
+ reviews: required(number({ minInclusive: 1 }))
120
+ });
121
+ }
122
+
123
+ function Vendor() {
124
+ return resource(Thing, {
125
+ name: required(string()),
126
+ website: required(url()),
127
+ address: optional(union(
128
+ string(),
129
+ PostalAddress(),
130
+ VirtualLocation()
131
+ ))
132
+ });
133
+ }
134
+ ```
135
+
136
+ Shape factories like `string()`, `number()`, `boolean()`, `dictionary()`, and `reference()` define the expected value
137
+ type and optional constraints for each property. Cardinality factories wrap a shape into a property, controlling how
138
+ many values are expected and determining the inferred TypeScript type:
139
+
140
+ | Factory | Cardinality | TypeScript Type |
141
+ |---------------------------------------------|-------------|-----------------------------|
142
+ | `required(s)` | 1..1 | `V` |
143
+ | `optional(s)` | 0..1 | `undefined \| V` |
144
+ | `nonempty(s)` | 1..* | `readonly [V, ...V[]]` |
145
+ | `multiple(s)` | 0..* | `undefined \| readonly V[]` |
146
+ | `property(s, { minCount: l, maxCount: u })` | l..u | as `l` and `u` imply |
147
+
148
+ An upper bound of 1 yields the bare value and any other an array, non-empty where at least one value is required.
149
+ `property()` follows the same rules, so bounds beyond the four named cardinalities are typed exactly as their
150
+ counterparts are.
151
+
152
+ A `dictionary()` range stands apart: a localised property carries its language map whole, never in an array, so it is
153
+ typed as the bare map at every cardinality. Where a dictionary sits in a union beside other branches, the property is
154
+ typed as either the map or the array those branches imply, since a resource carries one or the other and never both, and
155
+ the bounds count the other branches alone.
156
+
157
+ Each factory takes the constraints the property carries beyond its cardinality, such as IRI mappings, labels, ownership
158
+ flags, or a `hidden` flag withholding it from default serialisation, as a trailing argument:
159
+ `required(string(), { forward: schema })`. The `id()` and `type()` markers take the same `hidden` flag.
160
+
161
+ Cardinalities admitting absence also relax their key to an optional one, so a value literal spells out only the members
162
+ it actually carries; reading an omitted member still yields `undefined`.
163
+
164
+ Resource members link to other resources in two ways. A `reference()` wrapper links to a **standalone resource**, an
165
+ independently identified and managed entity like `Vendor`. A direct shape inclusion defines an **embedded resource**, a
166
+ nested object with no independent identity, created and managed together with its parent like `Rating`.
167
+
168
+ Properties accepting values of more than one type are modelled as unions of positional branches. Matching splits by
169
+ regime: a stored **value** must single out **exactly one** branch (`sh:xone`), tested against all constraints, and is
170
+ rejected when it fits several (ambiguous) or none (unsatisfiable); a relational **bound** must likewise single out
171
+ exactly one, but keys on syntactic traits alone, as it need not be a legal value; a retrieval **placeholder** is tested
172
+ by form alone and must fit **at least one** branch (`sh:or`), may fit several, and is rejected only when it fits none
173
+ (see [Validating Templates](#validating-templates)). A multi-valued property matches each of its values independently,
174
+ and values are stored as they stand with no branch wrapping.
175
+
176
+ Branches are expected to be **disjoint**: overlapping ones are accepted as the shape is built, and an ambiguous value is
177
+ rejected only when it is matched. Either of the following representations is accepted at the same `address` position:
178
+
179
+ ```json
180
+ {
181
+ "address": "12 Harbour Street, Copenhagen"
182
+ }
183
+ ```
184
+
185
+ ```json
186
+ {
187
+ "address": {
188
+ "streetAddress": "12 Harbour Street",
189
+ "addressLocality": "Copenhagen"
190
+ }
191
+ }
192
+ ```
193
+
194
+ ## Extending Schemas
195
+
196
+ Declare parent shapes first to inherit their members and constraints. Local members augment the parent and may override
197
+ inherited ones, but only by *narrowing*: an override restricts what it inherits and never relaxes it. Cardinality
198
+ narrows monotonically (`required` may override `optional`, but not the reverse), per-kind constraints intersect, and the
199
+ override is rejected at the call site when the child relaxes the parent. Names and descriptions restrict no value, so an
200
+ override may replace the ones it inherits to present the member in the terms of the child.
201
+
202
+ ```ts
203
+ const NamedThing = resource({
204
+ id: id(),
205
+ name: required(string({ minLength: 1 }))
206
+ });
207
+
208
+ const Vendor = resource(NamedThing, {
209
+ name: required(string({ minLength: 3, maxLength: 80 })), // narrows minLength
210
+ rating: optional(number({ minInclusive: 0, maxInclusive: 5 }))
211
+ });
212
+ ```
213
+
214
+ ### Refining Nested Targets
215
+
216
+ A member holding a nested resource or a `reference(...)` is refined by re-pointing it at a shape that extends the
217
+ inherited target. The refining shape declares only what it adds or narrows: it reaches the inherited definition through
218
+ its own parents, so the parent definition is never restated. A `reference(...)` target that doesn't extend the inherited
219
+ one, the inherited target's own parent included, is rejected at the call site; a target deferred to break a definition
220
+ cycle is held to the same rule once its definition stands, so shapes reaching themselves or each other may be re-pointed
221
+ just as well.
222
+
223
+ ```ts
224
+ const Organization = resource({
225
+ class: "https://schema.org/Organization"
226
+ }, {
227
+ id: id(),
228
+ name: required(string())
229
+ });
230
+
231
+ const University = resource(Organization, { class: "https://ec2u.eu/University" }, {
232
+ country: required(string())
233
+ });
234
+
235
+ const Unit = resource({
236
+ id: id(),
237
+ unitOf: required(reference(Organization)), // referenced target
238
+ host: required(Organization) // embedded target
239
+ });
240
+
241
+ const ResearchUnit = resource(Unit, {
242
+ unitOf: required(reference(University)), // re-pointed at the extending target
243
+ host: required(University)
244
+ });
245
+ ```
246
+
247
+ Extending the inherited target is what makes the refinement legal for an embedded member: a nested resource value must
248
+ belong to every `class` the inherited target declares, whether the refining shape states it in its own right or inherits
249
+ it, so a standalone shape that merely repeats the inherited members is rejected.
250
+
251
+ ### Narrowing Union Members
252
+
253
+ When the parent declares a `union(...)` member, an extending shape may narrow it in two forms:
254
+
255
+ - **Single-branch narrowing**: the child supplies a non-union shape that narrows exactly one of the parent's branches.
256
+ The merged member becomes a bare value shape, no longer polymorphic.
257
+ - **Branch subsetting**: the child supplies a smaller `union(...)`; each child branch narrows a distinct parent branch
258
+ (an injective pairing), the paired branches are merged, and unpaired parent branches are dropped.
259
+
260
+ A child branch narrowing no parent branch, several, or one already claimed by another child branch is rejected at the
261
+ call site.
262
+
263
+ ```ts
264
+ const Entity = resource({
265
+ code: required(union(string(), number()))
266
+ });
267
+
268
+ // Form 1 — narrows the member to a bare string
269
+ const Vendor = resource(Entity, {
270
+ code: required(string({ pattern: /^[A-Z]/ }))
271
+ });
272
+
273
+ // Form 2 — keeps the union but drops the string branch wholesale
274
+ const Numbered = resource(Entity, {
275
+ code: required(union(number({ minInclusive: 0 })))
276
+ });
277
+ ```
278
+
279
+ Dropping a parent branch changes nothing a retrieval template relies on: the keys of a branch map are opaque labels
280
+ carrying no positional meaning, so a placeholder singles out the alternative it fits by shape rather than by the
281
+ position the branch was stated at (see [Validating Templates](#validating-templates)).
282
+
283
+ ## Type Inference
284
+
285
+ Schemas double as TypeScript type definitions. `State` yields the value a resource carries as it is held:
286
+
287
+ ```ts
288
+ import { type State } from "@grafctory/blue/value";
289
+
290
+
291
+ type ProductType = State<typeof Product>;
292
+
293
+ // {
294
+ // readonly id: Reference,
295
+ // readonly type?: undefined | Reference,
296
+ // readonly name: { readonly [tag: Tag]: readonly string[] },
297
+ // readonly description?: undefined | { readonly [tag: Tag]: readonly string[] },
298
+ // readonly price: number,
299
+ // readonly inStock: boolean,
300
+ // readonly tags?: undefined | readonly string[],
301
+ // readonly rating?: undefined | { readonly average: number, readonly reviews: number },
302
+ // readonly vendor: Reference
303
+ // }
304
+ ```
305
+
306
+ Members admitting absence are optional keys: a value may either set them to `undefined` or leave them out.
307
+
308
+ No separate interface needed: the schema is the type definition.
309
+
310
+ `Draft` yields the state of a resource to be persisted, with its identifier optional, as the target of the operation
311
+ already identifies the resource or leaves the store to assign it; stated with a collection model, such as
312
+ `Draft<typeof Catalog, { items: {} }>`, it yields the state of an item to be added to that collection instead. The
313
+ `blueprint` accessor resolves the shape such an item must satisfy, so that it can be validated before it is stored. The
314
+ `collection` accessor resolves the property holding the collection.
315
+
316
+ `Match` narrows the value to the members a retrieval template asked for, so a caller reads back its own request rather
317
+ than everything the schema declares:
318
+
319
+ ```ts
320
+ import { type Match } from "@grafctory/blue/value";
321
+
322
+
323
+ type ProductSummary = Match<typeof Product, { id: {}, price: {} }>;
324
+
325
+ // {
326
+ // readonly id: Reference,
327
+ // readonly price: number
328
+ // }
329
+ ```
330
+
331
+ The template states which values are wanted and no longer what they are, so depth, cardinality and optionality all come
332
+ from the schema. A member the template leaves out is left out of the result; a polymorphic member, a projection column
333
+ and a localised member come back as wide as the schema describes them.
334
+
335
+ The retrieval models themselves are held to the schema where they are written:
336
+
337
+ - `Model` admits the templates a resource shape serves, rejecting a member the shape doesn't carry
338
+ - `Slice` admits the models a collection held by a property serves, merged with the criteria filtering, ordering and
339
+ paginating it
340
+ - `Items` types the items of such a collection, narrowed to what the model asked for
341
+ - `Frame` types a single item of such a collection, for code generic over the schema and the model
342
+
343
+ The `items` accessor gets those items from the resource a slice retrieval returns, typed as `Items`, without looking up
344
+ the collection property by name.
345
+
346
+ ## Validating Resources
347
+
348
+ The overloaded `validate` function checks a value against a schema and returns a
349
+ [Relay](https://grafctory.github.io/core/interfaces/relay.Relay.html) that dispatches to either a `value` or `trace`
350
+ handler:
351
+
352
+ ```ts
353
+ import { validate } from "@grafctory/blue";
354
+
355
+
356
+ validate(data, { shape: Product })({
357
+ value: product => {
358
+ // product is typed as State<typeof Product>
359
+ },
360
+ trace: trace => {
361
+ // trace describes validation violations
362
+ }
363
+ });
364
+ ```
365
+
366
+ All constraints are enforced, including type, cardinality, closed-shape checks, and custom validators. Unknown and
367
+ missing members are both rejected. On success, the value comes back typed as the shape describes it. Validation is
368
+ idempotent on a given shape: re-validating the same value on the same terms reads the earlier verdict off the value
369
+ rather than walking it again, so a caller may validate defensively wherever it is unsure.
370
+
371
+ Two further options bound what a resource may carry: `entry` names the identifier the resource is expected to be named
372
+ by, and `depth` caps the nesting a captive member may be expanded to, with `0` refusing every expansion while still
373
+ admitting the identifier naming the resource.
374
+
375
+ ## Validating Projections
376
+
377
+ When the projection template is not bonded to the shape (typically at API boundaries where `shape` defines the
378
+ admissible surface and the projection arrives per request), pass `model` as a separate template argument. Only the
379
+ members the template asked for are checked, and the result is narrowed to them:
380
+
381
+ ```ts
382
+ import { validate } from "@grafctory/blue";
383
+
384
+
385
+ const model = { id: {}, name: {} }; // projection requested by the caller
386
+
387
+ validate(response, { shape: Product, model })({
388
+ value: product => {
389
+ // product is typed as Match<typeof Product, typeof model>
390
+ },
391
+ trace: trace => {
392
+ // trace describes validation violations
393
+ }
394
+ });
395
+ ```
396
+
397
+ Constraints on members absent from `model` are not enforced, so an unrequested required member triggers no `minCount`
398
+ violation, nor does a polymorphic member coming back empty where the template reaches only some of its variants, as the
399
+ resource may hold another. A member the template didn't ask for is rejected all the same, as the caller has nowhere to
400
+ put it. A reference member additionally accepts an expanded nested resource, validated against the target shape narrowed
401
+ by the nested projection in `model`. Custom validators are not run, as they are written against a whole resource rather
402
+ than the part of it a template asked for, even where the template asks for every member.
403
+
404
+ ## Validating Templates
405
+
406
+ The same `validate` function validates retrieval
407
+ [templates](https://grafctory.github.io/qest/types/model.Template.html) when the `model` option is set to `true`:
408
+
409
+ ```ts
410
+ import { validate } from "@grafctory/blue";
411
+
412
+
413
+ validate(data, { model: true, shape: Product });
414
+ validate(data, { model: true, shape: Product, plain: true });
415
+ validate(data, { model: true, shape: Product, depth: 0 });
416
+ validate(data, { model: true, shape: Product, limit: 100 });
417
+ ```
418
+
419
+ A template describes what to retrieve rather than what is held, so what it is held to is asking for something the shape
420
+ can give: value constraints are left alone, a placeholder carrying no value of its own. A missing member is accepted as
421
+ not requested, and an explicit `undefined` member reads the same way, marking one elided at construction time.
422
+
423
+ Every leaf is the atomic placeholder `{}`, and a collection is the entry naming it, carrying the constraints that
424
+ filter, sort and page it alongside the keys retrieving its values:
425
+
426
+ ```ts
427
+ const template = {
428
+
429
+ id: {}, // the value as it stands
430
+ vendor: { name: {} }, // a linked resource, expanded
431
+
432
+ items: { name: {}, ">=price": 50, "#": 25 }, // a collection, per-item keys and constraints together
433
+ title: { "*": {} } // a localised property, by tag range
434
+
435
+ };
436
+ ```
437
+
438
+ Cardinality is not stated by the notation, so what refuses a constraint is the shape: a member admitting one value has
439
+ no collection to narrow, and a localised member is filtered by its own tag ranges.
440
+
441
+ What each kind of member may be asked for:
442
+
443
+ - **Reference**: either the atomic placeholder, retrieving the identifier naming the target, or a nested template
444
+ validated against the target shape. An embedded resource, naming no identifier to come back as, is reached through a
445
+ template alone.
446
+ - **Union**: the keyed form (`{"0": …, "1": …}`), one placeholder per alternative wanted, where the alternatives want
447
+ different shapes; where one shape serves them all, the atomic placeholder addresses the property directly. Keys are
448
+ opaque labels carrying no positional meaning: each placeholder is matched by form alone and retrieves every branch it
449
+ fits. The atomic placeholder requests every branch coming back as a value. A nested template reaches every resource
450
+ branch admitting at least one of the members it asks for, so it may span several, each answering the members it
451
+ admits. A member several branches declare may take a different shape in each, and what is asked for it need fit only
452
+ one of them. Only a placeholder fitting no branch at all is rejected. A tag range may also be a member name, so an
453
+ object whose keys each name a member of a resource branch is read as a template, and any other object as a map of tag
454
+ ranges.
455
+ - **Localised**: a map of the tag ranges wanted, each asking for the value a matched tag carries, or the atomic
456
+ placeholder, standing for the content language negotiation settles on. Per-tag arity follows the shape rather than the
457
+ template. A localised branch of a union takes the map under a branch map, or directly on the member if no other branch
458
+ reaches a resource, since the map then cannot be read as a template.
459
+
460
+ Constraint operands follow their own rules: comparison bounds and set-matching options carry content rather than
461
+ placeholders, so each must single out exactly one branch, a bound keying on kind and lexical pattern and an option on
462
+ kind alone, while a `~` text search is a plain string applied to every string branch at once. A plain-string operand
463
+ over a localised member filters the negotiated content under ordinary textual semantics; sorting and focusing still
464
+ require a single-valued key, so they accept a coalesced localised key only where it resolves single-valued. A key that
465
+ groups a projection counts as single-valued, since it holds one value per group even over a multi-valued member.
466
+
467
+ Three options bound the query language a template may draw on:
468
+
469
+ - **`plain`**: rejects the aggregate transforms combining several values into one (`count`, `sum`, `min`, `max`, `avg`)
470
+ - **`depth`**: caps nested template expansion and property path length
471
+ - **`limit`**: caps the `#` pagination constraint, and is injected as a default where a collection states none; `0`,
472
+ like omitting it, leaves the page to the client
473
+
474
+ > [!CAUTION]
475
+ >
476
+ > By default, templates support the full query language, including aggregate transforms and nested expansion.
477
+ > When exposing endpoints to untrusted clients, restrict query complexity as required by setting `plain`
478
+ > to `true`, `depth` to `0` or a positive value, and/or `limit` to a maximum result set size.
479
+
480
+ # SHACL Foundations
481
+
482
+ [SHACL](https://www.w3.org/TR/shacl/) (Shapes Constraint Language) is a [W3C](https://www.w3.org/) standard for
483
+ describing and validating RDF graphs. It defines *shapes* (sets of constraints that nodes in a graph must satisfy)
484
+ covering structure, cardinality, value ranges, and logical combinations.
485
+
486
+ **@grafctory/blue** implements a controlled SHACL subset tailored to the
487
+ [JSON-LD](https://www.w3.org/TR/json-ld11/) profile defined by [@grafctory/qest], enabling TypeScript developers to use
488
+ shape-based validation without mastering SHACL technicalities.
489
+
490
+ This controlled subset is specified by:
491
+
492
+ - [cardinality constraints](https://www.w3.org/TR/shacl/#core-components-count) (`sh:minCount`, `sh:maxCount`)
493
+ for specifying how many values a property must or may have
494
+ - [value range constraints](https://www.w3.org/TR/shacl/#core-components-range) (`sh:minExclusive`,
495
+ `sh:maxExclusive`, `sh:minInclusive`, `sh:maxInclusive`) for numeric value ranges
496
+ - [string constraints](https://www.w3.org/TR/shacl/#core-components-string) (`sh:minLength`, `sh:maxLength`,
497
+ `sh:pattern`, `sh:languageIn`, `sh:uniqueLang`) for text length, patterns, and language tags
498
+ - [value type constraints](https://www.w3.org/TR/shacl/#core-components-value-type) (`sh:class`, `sh:datatype`) for
499
+ declaring the expected type of resource instances and the RDF datatype of literals; `sh:class` is limited to a single
500
+ class
501
+ - [value constraints](https://www.w3.org/TR/shacl/#core-components-others) (`sh:in`, `sh:hasValue`) for enumerations and
502
+ required values
503
+ - [shape-based constraints](https://www.w3.org/TR/shacl/#core-components-shape) limited to `sh:qualifiedValueShape`
504
+ with `sh:qualifiedMinCount`, for requiring localised text to be stated in given languages
505
+ - [logical constraints](https://www.w3.org/TR/shacl/#core-components-logical) limited to `sh:xone` typed unions on
506
+ members, matched exactly-one on write and relaxed to at-least-one (`sh:or`) on read; the `sh:not`, `sh:and`, and
507
+ `sh:or` shape combinators are not supported for authoring
508
+ - [closed shapes](https://www.w3.org/TR/shacl/#ClosedConstraintComponent) enforced by default on all resource shapes;
509
+ unknown properties are always rejected
510
+
511
+ [Property pair constraints](https://www.w3.org/TR/shacl/#core-components-property-pairs) and
512
+ [property paths](https://www.w3.org/TR/shacl/#property-paths) are not supported; cross-property logic can be implemented
513
+ via custom [validators](https://grafctory.github.io/blue/modules/resource.html).
514
+
515
+ # Support
516
+
517
+ - Open an [issue](https://github.com/grafctory/blue/issues) to report a problem or to suggest a new feature
518
+ - Start a [discussion](https://github.com/grafctory/blue/discussions) to ask a how-to question or to share an idea
519
+
520
+ # License
521
+
522
+ This project is licensed under the Apache 2.0 License –
523
+ see [LICENSE](https://github.com/grafctory/blue?tab=Apache-2.0-1-ov-file) file for details.
524
+
525
+ <sub>Grafctory™ is a trademark of Metreeca srl.</sub>
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Boolean shape assembly.
3
+ *
4
+ * Builds the shape the factory states into the form its consumers read, and combines it with the one it overrides: the
5
+ * kind closes the domain to two values, so a shape is never contradictory, while an override admitting the other truth
6
+ * value would leave the member admitting nothing and is rejected before either shape 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 { BooleanConstraints, BooleanShape } from "./index.js";
13
+ /**
14
+ * Assembles a boolean shape.
15
+ *
16
+ * Backs the factory the {@link boolean!} module exposes. The kind closes the domain to two values and the enumeration
17
+ * to one of them, so there is nothing that could make the stated constraints contradictory.
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 BooleanConstraints constraints}
22
+ *
23
+ * @returns An immutable shape admitting the truth values the constraints leave open
24
+ */
25
+ export declare function assemble<V extends boolean>(constraints: BooleanConstraints): BooleanShape<V>;
26
+ /**
27
+ * Reports whether a boolean shape narrows an inherited one.
28
+ *
29
+ * Tests the override relation without building the merged shape, so that an incompatible extension is told apart from
30
+ * a legitimate refinement before either is committed to: a shape narrows the inherited one where it enumerates the
31
+ * same value, or leaves open a domain the inherited shape is free to close.
32
+ *
33
+ * @param target The overriding shape
34
+ * @param source The inherited shape
35
+ *
36
+ * @returns A trace of the obstacles to the override, or `undefined` where `target` narrows `source`
37
+ */
38
+ export declare function narrowsBoolean(target: BooleanShape, source: BooleanShape): Optional<Trace>;
39
+ /**
40
+ * Merges a boolean shape with an inherited one.
41
+ *
42
+ * Yields the single shape an extending member is validated against: the admitted value carries through from whichever
43
+ * shape enumerates it, the two agreeing wherever both do.
44
+ *
45
+ * @param target The overriding shape
46
+ * @param source The inherited shape
47
+ *
48
+ * @returns An immutable shape admitting the values both `target` and `source` admit
49
+ *
50
+ * @throws {@link @grafctory/core!TraceError | TraceError} Where `target` doesn't narrow `source`
51
+ */
52
+ export declare function mergeBoolean(target: BooleanShape, source: BooleanShape): BooleanShape;
53
+ //# sourceMappingURL=assembler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assembler.d.ts","sourceRoot":"","sources":["../../src/boolean/assembler.ts"],"names":[],"mappings":"AAiBA;;;;;;;;GAQG;AAEH,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EAAQ,KAAK,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAEzD,OAAO,KAAK,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAGnE;;;;;;;;;;;GAWG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,OAAO,EAAE,WAAW,EAAE,kBAAkB,GAAG,YAAY,CAAC,CAAC,CAAC,CAU5F;AAKD;;;;;;;;;;;GAWG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,YAAY,GAAG,QAAQ,CAAC,KAAK,CAAC,CAU1F;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,YAAY,GAAG,YAAY,CAcrF"}
@@ -0,0 +1,78 @@
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 { test } from "@grafctory/core/trace";
18
+ import { reject } from "../value/assembler.js";
19
+ /**
20
+ * Assembles a boolean shape.
21
+ *
22
+ * Backs the factory the {@link boolean!} module exposes. The kind closes the domain to two values and the enumeration
23
+ * to one of them, so there is nothing that could make the stated constraints contradictory.
24
+ *
25
+ * @typeParam V The values the shape admits, as stated by the signature of the calling factory
26
+ *
27
+ * @param constraints The stated shape {@link BooleanConstraints constraints}
28
+ *
29
+ * @returns An immutable shape admitting the truth values the constraints leave open
30
+ */
31
+ export function assemble(constraints) {
32
+ return immutable({
33
+ kind: "boolean",
34
+ ...constraints
35
+ }); // ;(cast) the factory signature fixes the admitted values to the enumerated one
36
+ }
37
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
38
+ /**
39
+ * Reports whether a boolean shape narrows an inherited one.
40
+ *
41
+ * Tests the override relation without building the merged shape, so that an incompatible extension is told apart from
42
+ * a legitimate refinement before either is committed to: a shape narrows the inherited one where it enumerates the
43
+ * same value, or leaves open a domain the inherited shape is free to close.
44
+ *
45
+ * @param target The overriding shape
46
+ * @param source The inherited shape
47
+ *
48
+ * @returns A trace of the obstacles to the override, or `undefined` where `target` narrows `source`
49
+ */
50
+ export function narrowsBoolean(target, source) {
51
+ return test(({ in: admitted }) => {
52
+ return admitted === undefined || source.in === undefined || admitted === source.in || [
53
+ `{in} unexpected value <${admitted}>`
54
+ ];
55
+ })(target);
56
+ }
57
+ /**
58
+ * Merges a boolean shape with an inherited one.
59
+ *
60
+ * Yields the single shape an extending member is validated against: the admitted value carries through from whichever
61
+ * shape enumerates it, the two agreeing wherever both do.
62
+ *
63
+ * @param target The overriding shape
64
+ * @param source The inherited shape
65
+ *
66
+ * @returns An immutable shape admitting the values both `target` and `source` admit
67
+ *
68
+ * @throws {@link @grafctory/core!TraceError | TraceError} Where `target` doesn't narrow `source`
69
+ */
70
+ export function mergeBoolean(target, source) {
71
+ reject("incompatible boolean shape override", narrowsBoolean(target, source));
72
+ return immutable({
73
+ kind: target.kind,
74
+ // conjunctive: in — the enumerated value, equal wherever both shapes state one
75
+ in: target.in ?? source.in
76
+ });
77
+ }
78
+ //# sourceMappingURL=assembler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assembler.js","sourceRoot":"","sources":["../../src/boolean/assembler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAcH,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,IAAI,EAAc,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAI/C;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,QAAQ,CAAoB,WAA+B;IAE1E,OAAO,SAAS,CAAC;QAEhB,IAAI,EAAE,SAAS;QAEf,GAAG,WAAW;KAEd,CAAoB,CAAC,CAAC,gFAAgF;AAExG,CAAC;AAGD,wHAAwH;AAExH;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,cAAc,CAAC,MAAoB,EAAE,MAAoB;IAExE,OAAO,IAAI,CAAe,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE;QAE9C,OAAO,QAAQ,KAAK,SAAS,IAAI,MAAM,CAAC,EAAE,KAAK,SAAS,IAAI,QAAQ,KAAK,MAAM,CAAC,EAAE,IAAI;YACrF,0BAA0B,QAAQ,GAAG;SACrC,CAAC;IAEH,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;AAEZ,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,YAAY,CAAC,MAAoB,EAAE,MAAoB;IAEtE,MAAM,CAAC,qCAAqC,EAAE,cAAc,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAE9E,OAAO,SAAS,CAAC;QAEhB,IAAI,EAAE,MAAM,CAAC,IAAI;QAEjB,+EAA+E;QAE/E,EAAE,EAAE,MAAM,CAAC,EAAE,IAAI,MAAM,CAAC,EAAE;KAE1B,CAAC,CAAC;AAEJ,CAAC"}