@grafctory/blue 0.0.0-stage → 0.15.1

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