foldkit-entity 0.7.0 → 0.8.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.
package/dist/index.mjs CHANGED
@@ -1,877 +1,2 @@
1
- import { Option, Pipeable, Schema, SchemaAST } from "effect";
2
- import { Metadata } from "foldkit-metadata";
3
- //#region src/shape.ts
4
- const isNullish = (ast) => SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast);
5
- const isText = (ast) => SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal === "string" || SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText);
6
- /** What a schema's AST holds, read through Effect's own guards. */
7
- const SchemaShape = {
8
- /** True for the `null` and `undefined` members that make a schema optional. */
9
- isNullish,
10
- /**
11
- * The members of a schema with `null` and `undefined` set aside, so optional
12
- * text is still text; a schema that is not a union is its one member.
13
- */
14
- present: (ast) => SchemaAST.isUnion(ast) ? ast.types.filter((member) => !isNullish(member)) : [ast],
15
- /** True when every value the schema admits is a string. */
16
- isText
17
- };
18
- //#endregion
19
- //#region src/expr.ts
20
- /**
21
- * `Expr` — a query's scalar computations as typed values.
22
- *
23
- * An Entity says what a domain has; an `Expr` says something about one row of
24
- * it. A field reference, an input placeholder, a literal, and comparisons of
25
- * those are all immutable data: building one performs no work, reads nothing,
26
- * and names no database. An interpreter compiles it — `foldkit-remote-drizzle`
27
- * to SQL, an in-memory evaluator to a predicate over rows.
28
- *
29
- * This is deliberately not SQL and deliberately not arbitrary JavaScript. Every
30
- * operation here is one a real query in this repository needs; the set grows
31
- * from queries, not from what a database could express.
32
- */
33
- const tagOf = (value) => typeof value === "object" && value !== null && "_tag" in value ? value._tag : void 0;
34
- /**
35
- * An Entity's field and a `FieldExpr` are the same three members under the same
36
- * tag — the Entity's carries `metadata` besides — so this reads either and is
37
- * idempotent on its own output. Nothing needs to tell them apart, which is
38
- * better than telling them apart by which extra member happens to be present.
39
- */
40
- /**
41
- * Every node is frozen as it is made, so a query built from it stays the value
42
- * it was when `Query.where` checked it: nothing can swap a field or a literal
43
- * in afterwards. It also means no node can come to contain itself. A literal's
44
- * own payload is the caller's; the kernel compares scalars.
45
- */
46
- const node = (value) => Object.freeze(value);
47
- const literal = (value) => node({
48
- _tag: "Literal",
49
- value
50
- });
51
- const fieldExpr = (field) => node({
52
- _tag: "Field",
53
- owner: field.owner,
54
- key: field.key,
55
- schema: field.schema
56
- });
57
- const predicateTags = /* @__PURE__ */ new Set([
58
- "Eq",
59
- "Null",
60
- "Contains"
61
- ]);
62
- /** Whether a value is a predicate, and so usable where a boolean is wanted. */
63
- const isPredicate = (value) => predicateTags.has(tagOf(value));
64
- /**
65
- * A field of either kind becomes a `FieldExpr`, a scalar or a predicate is
66
- * itself, and anything else is the constant it is.
67
- */
68
- const toOperand = (value) => {
69
- const tag = tagOf(value);
70
- if (tag === "Field") return fieldExpr(value);
71
- if (tag === "Literal" || tag === "Input" || predicateTags.has(tag)) return value;
72
- return literal(value);
73
- };
74
- /** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */
75
- const toExpr = (value, step) => {
76
- const operand = toOperand(value);
77
- if (isPredicate(operand)) throw new Error(`[foldkit-entity] Expr.${step}: a predicate is already an answer, so asking this of one is not a question`);
78
- return operand;
79
- };
80
- const Expr = {
81
- /** A constant. Comparisons coerce a plain value, so this is rarely written. */
82
- literal,
83
- /**
84
- * A value the query is given when it runs. A definition builds these from its
85
- * `Input` schema; written by hand only when constructing a body directly.
86
- */
87
- input: (key, schema) => node({
88
- _tag: "Input",
89
- key,
90
- schema
91
- }),
92
- /** One field of one Entity, as a scalar. */
93
- field: (field) => fieldExpr(field),
94
- /**
95
- * Two scalars are the same value. A field or a plain value on either side is
96
- * coerced, so the common form reads as it means:
97
- *
98
- * ```ts
99
- * Expr.eq(Post.fields.slug, input.slug)
100
- * Expr.eq(Post.fields.status, 'active')
101
- * ```
102
- */
103
- eq: (left, right) => node({
104
- _tag: "Eq",
105
- left: toOperand(left),
106
- right: toOperand(right)
107
- }),
108
- /**
109
- * Whether a field holds no value. Its opposite is `isNotNull`; both are the
110
- * one node, because a query asks which of the two it means and nothing here
111
- * can negate a predicate.
112
- */
113
- isNull: (operand) => node({
114
- _tag: "Null",
115
- operand: toExpr(operand, "isNull"),
116
- present: false
117
- }),
118
- /** Whether a field holds a value. */
119
- isNotNull: (operand) => node({
120
- _tag: "Null",
121
- operand: toExpr(operand, "isNotNull"),
122
- present: true
123
- }),
124
- /**
125
- * Whether a text value contains `search`, anywhere in it. Containing the
126
- * empty string is everything, so a search box with nothing typed in it is the
127
- * same query as one with something — no branch, and no second query.
128
- *
129
- * **Case-insensitive**, which is what a search means, and which has to be
130
- * said rather than left to the interpreter: SQLite's `like` ignores case and
131
- * Postgres's does not, so a body that left it open would mean two things.
132
- * Folding is ASCII-only, because that is what `lower` does in SQLite without
133
- * ICU.
134
- *
135
- * **Over a column that can be null this is not the same as no filter.** A
136
- * null contains nothing, not even the empty string, so its rows drop out. A
137
- * nullable column that should match everything on an empty search says so:
138
- * `Expr.or` does not exist yet, so for now such a column needs its own
139
- * predicate or a native escape hatch.
140
- */
141
- contains: (value, search) => node({
142
- _tag: "Contains",
143
- value: toExpr(value, "contains"),
144
- search: toOperand(search)
145
- }),
146
- /** An expression as readable text; see `showExpr` for what it is and is not. */
147
- show: (node) => showExpr(node)
148
- };
149
- const Order = {
150
- asc: (expr) => node({
151
- direction: "asc",
152
- expr: toExpr(expr, "asc")
153
- }),
154
- desc: (expr) => node({
155
- direction: "desc",
156
- expr: toExpr(expr, "desc")
157
- })
158
- };
159
- /**
160
- * Visits each node once. A node can be shared by several paths (`eq(n, n)`),
161
- * and a walk that followed every path would take time exponential in the depth.
162
- */
163
- const walk = (expr, found) => {
164
- if (found.seen.has(expr)) return;
165
- found.seen.add(expr);
166
- switch (expr._tag) {
167
- case "Literal": return;
168
- case "Field": {
169
- const byKey = found.fields.get(expr.owner.token) ?? /* @__PURE__ */ new Map();
170
- found.fields.set(expr.owner.token, byKey);
171
- if (!byKey.has(expr.key)) {
172
- const field = {
173
- entity: expr.owner.name,
174
- key: expr.key,
175
- owner: expr.owner
176
- };
177
- byKey.set(expr.key, field);
178
- found.order.push(field);
179
- }
180
- return;
181
- }
182
- case "Input":
183
- found.inputs.add(expr.key);
184
- return;
185
- case "Eq":
186
- found.operations.add("eq");
187
- walk(expr.left, found);
188
- walk(expr.right, found);
189
- return;
190
- case "Null":
191
- found.operations.add(expr.present ? "isNotNull" : "isNull");
192
- walk(expr.operand, found);
193
- return;
194
- case "Contains":
195
- found.operations.add("contains");
196
- walk(expr.value, found);
197
- walk(expr.search, found);
198
- return;
199
- }
200
- };
201
- /**
202
- * What an expression reads and uses, for the planner and for an interpreter
203
- * deciding whether it can run this query at all. Distinct entries only, in the
204
- * order first seen, so the answer is stable enough to assert on.
205
- */
206
- const dependenciesOf = (...nodes) => {
207
- const found = {
208
- seen: /* @__PURE__ */ new Set(),
209
- fields: /* @__PURE__ */ new Map(),
210
- order: [],
211
- inputs: /* @__PURE__ */ new Set(),
212
- operations: /* @__PURE__ */ new Set()
213
- };
214
- for (const term of nodes) walk("direction" in term ? term.expr : term, found);
215
- return {
216
- fields: found.order,
217
- inputs: [...found.inputs],
218
- operations: [...found.operations]
219
- };
220
- };
221
- /** Every field an expression reads, as the nodes themselves, each node visited once. */
222
- const fieldsIn = function* (expr, seen) {
223
- if (seen.has(expr)) return;
224
- seen.add(expr);
225
- switch (expr._tag) {
226
- case "Field":
227
- yield expr;
228
- return;
229
- case "Literal":
230
- case "Input": return;
231
- case "Eq":
232
- yield* fieldsIn(expr.left, seen);
233
- yield* fieldsIn(expr.right, seen);
234
- return;
235
- case "Null":
236
- yield* fieldsIn(expr.operand, seen);
237
- return;
238
- case "Contains":
239
- yield* fieldsIn(expr.value, seen);
240
- yield* fieldsIn(expr.search, seen);
241
- return;
242
- }
243
- };
244
- /**
245
- * A query reads one Entity, so a predicate or ordering term naming a different
246
- * one cannot be answered — an interpreter would be asked for a column of a
247
- * table it was never told to read. Compared by identity, not by name, because
248
- * two Entities defined with the same name are two Entities.
249
- */
250
- const checkOwnership = (step, what, entity, nodes) => {
251
- const seen = /* @__PURE__ */ new Set();
252
- for (const term of nodes) for (const field of fieldsIn("direction" in term ? term.expr : term, seen)) if (field.owner.token !== entity.identity.token) throw new Error(`[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}`);
253
- };
254
- const QueryProto = {
255
- _tag: "Query",
256
- pipe() {
257
- return Pipeable.pipeArguments(this, arguments);
258
- }
259
- };
260
- const query = (entity, where, orderBy) => Object.freeze(Object.assign(Object.create(QueryProto), {
261
- entity,
262
- where: Object.freeze(where),
263
- orderBy: Object.freeze(orderBy)
264
- }));
265
- const Query = {
266
- /** Every row of an Entity: the query each transformation narrows. */
267
- from: (entity) => query(entity, [], []),
268
- /**
269
- * Narrows to the rows the predicate holds for. Two `where`s conjoin — the
270
- * second never replaces the first — so a fragment can be written once and
271
- * piped into any query over the same Entity:
272
- *
273
- * ```ts
274
- * const published = Query.where(Expr.eq(Post.fields.published, true))
275
- * Query.from(Post).pipe(published, Query.where(byTitle))
276
- * ```
277
- */
278
- where: (...predicates) => (self) => {
279
- if (predicates.length === 0) return self;
280
- checkOwnership("where", "a predicate", self.entity, predicates);
281
- return query(self.entity, [...self.where, ...predicates], self.orderBy);
282
- },
283
- /**
284
- * Reads the rows in this order. Two `orderBy`s append, so an earlier term
285
- * stays the more significant one and a later call adds a tie-breaker rather
286
- * than silently winning.
287
- */
288
- orderBy: (...terms) => (self) => {
289
- if (terms.length === 0) return self;
290
- checkOwnership("orderBy", "a term", self.entity, terms);
291
- return query(self.entity, self.where, [...self.orderBy, ...terms]);
292
- },
293
- /**
294
- * What the whole query reads: the fields and inputs of every predicate and
295
- * every ordering term, and the operations it uses.
296
- */
297
- dependencies: (self) => dependenciesOf(...self.where, ...self.orderBy),
298
- /**
299
- * The operations this query needs that `supported` does not list, in the
300
- * order the query uses them. Empty means an interpreter declaring
301
- * `supported` can answer it.
302
- *
303
- * An interpreter declares what it runs and refuses the rest, rather than
304
- * ignoring an operation it does not implement — which would answer a
305
- * different question and say nothing. The refusal is the interpreter's to
306
- * raise: this only says what is missing, because what to do about it differs
307
- * between one that compiles at registration and one that runs a body
308
- * directly.
309
- *
310
- * ```ts
311
- * const missing = Query.unsupported(body, ['eq', 'isNull', 'isNotNull'])
312
- * if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)
313
- * ```
314
- */
315
- unsupported: (self, supported) => {
316
- const runs = new Set(supported);
317
- return Query.dependencies(self).operations.filter((operation) => !runs.has(operation));
318
- },
319
- /**
320
- * The whole query as readable text, one clause per line:
321
- *
322
- * ```text
323
- * FROM Post
324
- * WHERE Post.slug = $slug
325
- * AND Post.published = true
326
- * ORDER BY Post.updatedAt DESC
327
- * ```
328
- *
329
- * For an explanation or a diagnostic, never for an interpreter — see
330
- * `Expr.show`. A query with no `where` or no `orderBy` omits that line rather
331
- * than printing an empty one, so what is shown is what was written.
332
- */
333
- show: (self) => [
334
- `FROM ${self.entity.name}`,
335
- ...self.where.map((predicate, index) => `${index === 0 ? "WHERE" : " AND"} ${Expr.show(predicate)}`),
336
- ...self.orderBy.length === 0 ? [] : [`ORDER BY ${self.orderBy.map((term) => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`).join(", ")}`]
337
- ].join("\n")
338
- };
339
- /**
340
- * An expression as readable text, in the IR's own terms.
341
- *
342
- * This is for a human — an explanation, a diagnostic, a test that wants to
343
- * assert on a whole predicate at once — and deliberately **not** for an
344
- * interpreter. It is close enough to SQL to read at a glance and unlike it
345
- * everywhere that matters: an input is `$slug` rather than a bound parameter,
346
- * `contains` is named rather than rendered as somebody's `like`, and no
347
- * dialect's escaping or collation is implied. What actually ran is whatever
348
- * that backend compiled, which is not this.
349
- *
350
- * A predicate standing where a value is wanted is parenthesised, because
351
- * `x is not null = $archived` reads as three operands and is two. A predicate
352
- * that *is* the whole expression is not: nothing encloses it.
353
- */
354
- const showExpr = (node) => {
355
- switch (node._tag) {
356
- case "Literal": return JSON.stringify(node.value) ?? String(node.value);
357
- case "Field": return `${node.owner.name}.${node.key}`;
358
- case "Input": return `$${node.key}`;
359
- case "Eq": return `${showOperand(node.left)} = ${showOperand(node.right)}`;
360
- case "Null": return `${showOperand(node.operand)} is ${node.present ? "not null" : "null"}`;
361
- case "Contains": return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`;
362
- }
363
- };
364
- const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
365
- //#endregion
366
- //#region src/words.ts
367
- const text = (value) => typeof value === "string" ? Option.some(value) : Option.none();
368
- const Words = {
369
- /**
370
- * A schema's words, as a label and its help text. Under Effect 4 a checked
371
- * schema resolves to its last check's annotations, which say what the check
372
- * expects and carry no `title`, so a title given before the check is read from
373
- * the schema's own annotations. Read words through this, never through
374
- * `Schema.resolveAnnotations` directly.
375
- */
376
- of: (schema) => {
377
- const resolved = Schema.resolveAnnotations(schema) ?? {};
378
- const own = schema.ast.annotations ?? {};
379
- return {
380
- title: Option.orElse(text(resolved.title), () => text(own["title"])),
381
- description: Option.orElse(text(resolved.description), () => text(own["description"]))
382
- };
383
- } };
384
- //#endregion
385
- //#region src/evaluate.ts
386
- /**
387
- * The reference interpreter: a query body run over rows already in memory.
388
- *
389
- * `foldkit-remote-drizzle` compiles a body to SQL. This runs the same body
390
- * directly, which is what makes "source-neutral" a fact rather than a claim —
391
- * the two are checked against each other over a real database, and a body that
392
- * means one thing here and another there is a bug in one of them.
393
- *
394
- * It is also the interpreter to reach for when there is no database: a test
395
- * that wants rows, a server assembling a page from values it already holds, or
396
- * a client judging rows it already has.
397
- *
398
- * It lives in `foldkit-entity` because it is the **reference semantics** of the
399
- * IR this package owns — what §6.0.1 means operationally rather than in prose —
400
- * and a specification's reference implementation belongs with the
401
- * specification. The rule that keeps it here: **it may depend on the IR and
402
- * nothing else.** The moment it wants a Remote concept it has moved to the
403
- * wrong place and should leave.
404
- *
405
- * **It follows SQL, not JavaScript.** Where the two disagree this follows SQL,
406
- * because SQL is what the other interpreter runs. The important case is null:
407
- * `null = null` is unknown in SQL and a row is not matched by it, where
408
- * JavaScript would happily call the two equal.
409
- */
410
- var QueryEvaluateError = class extends Error {
411
- constructor(message) {
412
- super(`[foldkit-entity] ${message}`);
413
- this.name = "QueryEvaluateError";
414
- }
415
- };
416
- const valueOf = (node, row, input) => {
417
- switch (node._tag) {
418
- case "Field": return row[node.key];
419
- case "Literal": return node.value;
420
- case "Input": return input[node.key];
421
- }
422
- };
423
- const isNull = (value) => value === null || value === void 0;
424
- /**
425
- * Lowercases ASCII letters and leaves every other character as it is, which is
426
- * what SQLite's `lower` does without ICU and so what the compiled SQL folds to.
427
- * `toLowerCase` would fold `É` to `é` here and not there.
428
- */
429
- const foldAscii = (text) => text.replace(/[A-Z]+/g, (upper) => upper.toLowerCase());
430
- const NUL = String.fromCharCode(0);
431
- /** A predicate used as a value is its own truth; anything else is its value. */
432
- const sideOf = (node, row, input) => isPredicate(node) ? truthValue(holds(node, row, input)) : valueOf(node, row, input);
433
- /**
434
- * A predicate compared as a value. SQL's unknown is null there too, so an
435
- * unknown compared to anything stays unknown rather than becoming false.
436
- */
437
- const truthValue = (truth) => truth === "unknown" ? null : truth;
438
- const holds = (node, row, input) => {
439
- switch (node._tag) {
440
- case "Eq": {
441
- const left = sideOf(node.left, row, input);
442
- const right = sideOf(node.right, row, input);
443
- if (isNull(left) || isNull(right)) return "unknown";
444
- return left === right;
445
- }
446
- case "Null": return isNull(valueOf(node.operand, row, input)) !== node.present;
447
- case "Contains": {
448
- const value = valueOf(node.value, row, input);
449
- const search = sideOf(node.search, row, input);
450
- if (isNull(value) || isNull(search)) return "unknown";
451
- if (typeof value !== "string" || typeof search !== "string") throw new QueryEvaluateError("a containment test was given something that is not text");
452
- if (value.includes(NUL) || search.includes(NUL)) throw new QueryEvaluateError("a containment test was given text holding a NUL character, which SQL text cannot hold portably");
453
- return foldAscii(value).includes(foldAscii(search));
454
- }
455
- }
456
- };
457
- /** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
458
- const matches = (body, row, input) => body.where.every((node) => holds(node, row, input) === true);
459
- /** The kinds of value this interpreter orders by; every key of one term must share one. */
460
- const comparable = /* @__PURE__ */ new Set([
461
- "string",
462
- "number",
463
- "boolean"
464
- ]);
465
- const compare = (left, right) => {
466
- if (typeof left === "string" && typeof right === "string") return left < right ? -1 : left > right ? 1 : 0;
467
- if (typeof left === "boolean" && typeof right === "boolean") return Number(left) - Number(right);
468
- return left - right;
469
- };
470
- /**
471
- * Refuses an ordering this interpreter will not answer for, before sorting, so
472
- * the refusal names the first offending row in row order rather than whichever
473
- * pair the engine's sort happened to compare first. Every term is checked over
474
- * every row: a null key, or a key whose kind differs from the first row's.
475
- */
476
- const checkOrder = (rows, terms, query) => {
477
- for (const term of terms) {
478
- if (term.expr._tag !== "Field") throw new QueryEvaluateError(`query "${query}" orders by something that is not a field, which this interpreter cannot run yet`);
479
- const key = term.expr.key;
480
- let first;
481
- for (const row of rows) {
482
- const value = row[key];
483
- if (isNull(value)) throw new QueryEvaluateError(`query "${query}" orders by "${key}", which is null in a row; where nulls sort is a thing databases disagree about, so it is outside what this interpreter will answer for`);
484
- const kind = typeof value;
485
- first ??= kind;
486
- if (kind !== first || !comparable.has(kind)) throw new QueryEvaluateError(`query "${query}" orders by values this interpreter cannot compare (${first} and ${kind})`);
487
- }
488
- }
489
- };
490
- const ordered = (rows, terms, query) => {
491
- if (terms.length === 0 || rows.length < 2) return [...rows];
492
- checkOrder(rows, terms, query);
493
- return [...rows].sort((left, right) => {
494
- for (const term of terms) {
495
- const key = term.expr.key;
496
- const sign = compare(left[key], right[key]);
497
- if (sign !== 0) return term.direction === "asc" ? sign : -sign;
498
- }
499
- return 0;
500
- });
501
- };
502
- /**
503
- * The operations this interpreter runs. It is the reference, so this is the
504
- * whole kernel — but it is declared rather than assumed, because an
505
- * interpreter that gains an operator and forgets to say so is exactly what
506
- * `Query.unsupported` exists to catch.
507
- */
508
- const supported = [
509
- "eq",
510
- "isNull",
511
- "isNotNull",
512
- "contains"
513
- ];
514
- /**
515
- * Refuses a body needing an operation this interpreter does not run, rather
516
- * than skipping it and answering a different question. Called by `evaluate`;
517
- * call it directly to check a body once instead of on every run.
518
- */
519
- const assertSupported = (body) => {
520
- const missing = Query.unsupported(body, supported);
521
- if (missing.length > 0) throw new QueryEvaluateError(`this interpreter does not run ${missing.join(", ")}, which query "${body.entity.name}" needs`);
522
- };
523
- /**
524
- * The rows the body matches, in the order it asks for. Pure: it reads the rows
525
- * it is given and nothing else.
526
- *
527
- * `input` holds the values this run was given, by the keys the body's
528
- * placeholders were built with — the same record the query would be called
529
- * with anywhere else.
530
- */
531
- const evaluate = (body, input, rows) => {
532
- assertSupported(body);
533
- return ordered(rows.filter((row) => matches(body, row, input)), body.orderBy, body.entity.name);
534
- };
535
- //#endregion
536
- //#region src/index.ts
537
- /**
538
- * `foldkit-entity` — domain structure as typed values.
539
- *
540
- * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations
541
- * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable
542
- * values an interpreter supplies). It describes; it fetches, stores, and
543
- * renders nothing. Remote, Drizzle, and form packages interpret it and attach
544
- * what they need as `foldkit-metadata`.
545
- */
546
- const EntityTypeId = Symbol.for("foldkit-entity/Entity");
547
- const SelectionTypeId = Symbol.for("foldkit-entity/Selection");
548
- const SelectionPageTypeId = Symbol.for("foldkit-entity/SelectionPage");
549
- /** The `id` field's schema when it is text, so a ref's id keeps its brand and its checks; else text. */
550
- const idSchemaOf = (entity) => {
551
- const id = entity.fields.id;
552
- if (id === void 0 || id._tag !== "Field") return Schema.String;
553
- const type = Schema.toType(id.schema);
554
- return SchemaShape.isText(type.ast) ? type : Schema.String;
555
- };
556
- const isSelectionPage = (value) => typeof value === "object" && value !== null && SelectionPageTypeId in value;
557
- const isSelection = (value) => typeof value === "object" && value !== null && SelectionTypeId in value;
558
- const unmapped = Object.freeze({ _tag: "Unmapped" });
559
- const EntityProto = {
560
- [EntityTypeId]: EntityTypeId,
561
- pipe() {
562
- return Pipeable.pipeArguments(this, arguments);
563
- }
564
- };
565
- const make = (parts) => Object.freeze(Object.assign(Object.create(EntityProto), parts, {
566
- name: parts.identity.name,
567
- fields: Object.freeze(parts.fields),
568
- relations: Object.freeze(parts.relations),
569
- derived: Object.freeze(parts.derived),
570
- members: Object.freeze({
571
- ...parts.fields,
572
- ...parts.relations,
573
- ...parts.derived
574
- })
575
- }));
576
- const isSameEntity = (left, right) => left.identity.token === right.identity.token;
577
- const fail = (entity, message) => {
578
- throw new Error(`Entity "${entity.name}": ${message}`);
579
- };
580
- const isEntity = (value) => typeof value === "object" && value !== null && EntityTypeId in value;
581
- const kindName = {
582
- Field: "field",
583
- Relation: "relation",
584
- Derived: "derived member"
585
- };
586
- const kindOf = (entity, key) => {
587
- const member = entity.members[key];
588
- return member && kindName[member._tag];
589
- };
590
- const assertFree = (entity, keys, adding) => {
591
- for (const key of keys) {
592
- const kind = kindOf(entity, key);
593
- if (kind !== void 0) throw new Error(`Entity "${entity.name}": cannot add ${adding} "${key}", it is already a ${kind}`);
594
- }
595
- };
596
- const mapValues = (record, f) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, f(value, key)]));
597
- const Entity = {
598
- /** Declares an Entity from its intrinsic fields. Each call is a new identity. */
599
- define: (name, schema) => {
600
- const identity = Object.freeze({
601
- name,
602
- token: Symbol(name)
603
- });
604
- return make({
605
- identity,
606
- schema,
607
- fields: mapValues(schema.fields, (fieldSchema, key) => Object.freeze({
608
- _tag: "Field",
609
- owner: identity,
610
- key,
611
- schema: fieldSchema,
612
- metadata: Metadata.empty
613
- })),
614
- relations: {},
615
- derived: {},
616
- metadata: Metadata.empty
617
- });
618
- },
619
- /**
620
- * Declares the relations between a set of Entities in one step, and returns
621
- * them related. One step, because Entities that point at each other cannot
622
- * each be declared in terms of the other.
623
- */
624
- relate: (entities, relations) => {
625
- const keyByToken = /* @__PURE__ */ new Map();
626
- for (const [key, entity] of Object.entries(entities)) {
627
- if (!isEntity(entity)) throw new Error(`Entity.relate: "${key}" is not an Entity`);
628
- const earlier = keyByToken.get(entity.identity.token);
629
- if (earlier !== void 0) throw new Error(`Entity.relate: "${earlier}" and "${key}" are the same Entity`);
630
- keyByToken.set(entity.identity.token, key);
631
- }
632
- const given = relations;
633
- for (const owner of Object.keys(given)) if (!(owner in entities)) throw new Error(`Entity.relate: relations given for "${owner}", which is not being related`);
634
- const related = {};
635
- for (const [ownerKey, entity] of Object.entries(entities)) {
636
- const specs = given[ownerKey] ?? {};
637
- assertFree(entity, Object.keys(specs), "relation");
638
- const added = mapValues(specs, (spec, key) => {
639
- const targetKey = isEntity(spec.target) ? keyByToken.get(spec.target.identity.token) : void 0;
640
- if (targetKey === void 0) throw new Error(`Entity "${entity.name}": relation "${key}" targets an Entity that is not being related`);
641
- return Object.freeze({
642
- _tag: "Relation",
643
- owner: entity.identity,
644
- key,
645
- target: () => related[targetKey],
646
- cardinality: spec.cardinality,
647
- optional: spec.optional,
648
- metadata: Metadata.empty
649
- });
650
- });
651
- related[ownerKey] = make({
652
- ...entity,
653
- relations: {
654
- ...entity.relations,
655
- ...added
656
- }
657
- });
658
- }
659
- return Object.freeze(related);
660
- },
661
- /**
662
- * Selects members of an Entity and assembles the schema of the result. A
663
- * relation selected with `true` yields an `EntityRef`; with a Selection of its
664
- * target, that Selection's value. `many` yields an array, an optional `one`
665
- * is nullable.
666
- */
667
- select: (entity, spec) => {
668
- const members = entity.members;
669
- const fields = mapValues(spec, (selected, key) => {
670
- const member = members[key];
671
- if (member === void 0) throw new Error(`Entity "${entity.name}": cannot select "${key}", it is not a member`);
672
- if (member._tag !== "Relation") {
673
- if (selected !== true) throw new Error(`Entity "${entity.name}": "${key}" is a ${kindName[member._tag]}, select it with true`);
674
- return member.schema;
675
- }
676
- const target = member.target();
677
- if (isSelectionPage(selected)) {
678
- if (member.cardinality !== "many") throw new Error(`Entity "${entity.name}": "${key}" is one ${target.name}, so it has no pages`);
679
- if (!isSameEntity(selected.selection.entity, target)) throw new Error(`Entity "${entity.name}": "${key}" pages a Selection of ${target.name}`);
680
- return Schema.Struct({
681
- items: Schema.Array(selected.selection.schema),
682
- hasNext: Schema.Boolean,
683
- hasPrevious: Schema.Boolean
684
- });
685
- }
686
- let item;
687
- if (selected === true) item = Schema.Struct({
688
- entity: Schema.Literal(target.name),
689
- id: idSchemaOf(target)
690
- });
691
- else if (isSelection(selected) && isSameEntity(selected.entity, target)) item = selected.schema;
692
- else throw new Error(`Entity "${entity.name}": "${key}" takes true or a Selection of ${target.name}`);
693
- return member.cardinality === "many" ? Schema.Array(item) : member.optional ? Schema.NullOr(item) : item;
694
- });
695
- return Object.freeze({
696
- [SelectionTypeId]: SelectionTypeId,
697
- entity,
698
- members: spec,
699
- schema: Schema.Struct(fields)
700
- });
701
- },
702
- /**
703
- * A `many` relation read a page at a time, in place of its Selection:
704
- * `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page
705
- * of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.
706
- */
707
- page: (selection, window) => {
708
- const sides = [window.first, window.last].filter((size) => size !== void 0);
709
- if (sides.length !== 1 || !sides.every((size) => Number.isInteger(size) && size >= 0)) throw new Error(`Entity.page: a window of ${selection.entity.name} takes first or last, a non-negative integer`);
710
- if (window.first !== void 0 && window.before !== void 0 || window.last !== void 0 && window.after !== void 0) throw new Error(`Entity.page: a window of ${selection.entity.name} reads first after a cursor, or last before one`);
711
- return Object.freeze({
712
- [SelectionPageTypeId]: SelectionPageTypeId,
713
- selection,
714
- window
715
- });
716
- },
717
- /** Adds readable members that are not part of `entity.schema`. */
718
- derived: (specs) => (entity) => {
719
- assertFree(entity, Object.keys(specs), "derived member");
720
- const added = mapValues(specs, (spec, key) => Object.freeze({
721
- _tag: "Derived",
722
- owner: entity.identity,
723
- key,
724
- schema: spec.schema,
725
- metadata: Metadata.empty
726
- }));
727
- return make({
728
- ...entity,
729
- derived: {
730
- ...entity.derived,
731
- ...added
732
- }
733
- });
734
- },
735
- /** Attaches an interpreter's metadata to the Entity itself. */
736
- annotate: (metadata) => (entity) => make({
737
- ...entity,
738
- metadata: Metadata.combine([entity.metadata, metadata])
739
- }),
740
- /** Attaches an interpreter's metadata to members, by key. */
741
- annotateMembers: (metadata) => (entity) => {
742
- const given = metadata;
743
- for (const key of Object.keys(given)) if (kindOf(entity, key) === void 0) throw new Error(`Entity "${entity.name}": cannot annotate "${key}", it is not a member`);
744
- const annotate = (members) => mapValues(members, (member, key) => {
745
- const extra = given[key];
746
- return extra === void 0 ? member : Object.freeze({
747
- ...member,
748
- metadata: Metadata.combine([member.metadata, extra])
749
- });
750
- });
751
- return make({
752
- ...entity,
753
- fields: annotate(entity.fields),
754
- relations: annotate(entity.relations),
755
- derived: annotate(entity.derived)
756
- });
757
- },
758
- /**
759
- * Reads an operation's input schema against an Entity. A key that names a
760
- * field maps to it; any other key is mapped explicitly, to a Field, to
761
- * `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred
762
- * from a naming convention such as `authorId`.
763
- */
764
- input: (entity, schema, ...mapping) => {
765
- const written = mapping[0] ?? {};
766
- for (const key of Object.keys(written)) if (!(key in schema.fields)) throw new Error(`Entity "${entity.name}": "${key}" is mapped but is not a key of the input`);
767
- const named = (key, name) => {
768
- const member = entity.members[name];
769
- switch (member?._tag) {
770
- case "Field": return member;
771
- case "Relation": return Object.freeze({
772
- _tag: "RelationInput",
773
- relation: member
774
- });
775
- case "Derived":
776
- case void 0: return fail(entity, `input key "${key}" is mapped to "${name}", which names no field or relation`);
777
- }
778
- };
779
- const given = mapValues(written, (member, key) => typeof member === "string" ? named(key, member) : member);
780
- const fields = entity.fields;
781
- const members = mapValues(schema.fields, (_, key) => {
782
- const member = given[key] ?? fields[key] ?? fail(entity, `input key "${key}" names no field; map it to a member or Entity.unmapped`);
783
- const owned = member._tag === "Field" ? member : member._tag === "RelationInput" || member._tag === "NestedInput" ? member.relation : member._tag === "Unmapped" ? void 0 : fail(entity, `input key "${key}" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`);
784
- if (owned !== void 0 && owned.owner.token !== entity.identity.token) fail(entity, `input key "${key}" is mapped to a member of "${owned.owner.name}"`);
785
- if (member._tag === "NestedInput" && !isSameEntity(member.input.entity, member.relation.target())) fail(entity, `input key "${key}" nests an input of "${member.input.entity.name}", but "${member.relation.key}" is of "${member.relation.target().name}"`);
786
- return member;
787
- });
788
- return Object.freeze({
789
- entity,
790
- schema,
791
- members: Object.freeze(members)
792
- });
793
- },
794
- /** For an input key that is about the operation rather than the Entity. */
795
- unmapped,
796
- /**
797
- * The schemas of some of an Entity's fields, by key, to spread into an input's
798
- * struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.
799
- * The input then keeps the field's own rules, and its keys map themselves.
800
- */
801
- fields: (entity, ...keys) => Object.fromEntries(keys.map((key) => [key, (entity.fields[key] ?? fail(entity, `"${key}" is not a field`)).schema])),
802
- /**
803
- * The Selection of every member an input writes, with each relation as refs:
804
- * what an edit screen loads before it shows the input's current values.
805
- */
806
- selectFor: (input) => {
807
- const members = input.members;
808
- const spec = Object.fromEntries(Object.values(members).flatMap((member) => member._tag === "Field" ? [[member.key, true]] : member._tag === "RelationInput" ? [[member.relation.key, true]] : member._tag === "NestedInput" ? [[member.relation.key, Entity.selectFor(member.input)]] : []));
809
- return Entity.select(input.entity, spec);
810
- },
811
- /**
812
- * The input values that reproduce `value`, a value read through `selectFor`
813
- * (or any Selection with those members): a field as it is, a relation as the
814
- * id or ids of its refs. A key whose member `value` lacks is left out, as is
815
- * an unmapped key, which the Entity knows nothing about.
816
- */
817
- valuesFor: (input, value) => {
818
- const members = input.members;
819
- const idOf = (held) => held === null ? null : typeof held === "object" && "id" in held ? held.id : typeof held === "string" ? held : void 0;
820
- const entries = Object.entries(members).flatMap(([key, member]) => {
821
- if (member._tag === "Unmapped") return [];
822
- const written = member._tag === "Field" ? member.key : member.relation.key;
823
- if (!(written in value)) return [];
824
- const read = value[written];
825
- switch (member._tag) {
826
- case "Field": return [[key, read]];
827
- case "NestedInput": {
828
- const nested = (held) => typeof held === "object" && held !== null ? Entity.valuesFor(member.input, held) : null;
829
- return [[key, Array.isArray(read) ? read.map(nested) : nested(read)]];
830
- }
831
- case "RelationInput": {
832
- const ids = Array.isArray(read) ? read.map(idOf) : idOf(read);
833
- return (Array.isArray(ids) ? !ids.includes(void 0) : ids !== void 0) ? [[key, ids]] : [];
834
- }
835
- }
836
- });
837
- return Object.fromEntries(entries);
838
- },
839
- is: isEntity,
840
- /** True when both descriptors are versions of one Entity. */
841
- same: isSameEntity
842
- };
843
- function one(target, options) {
844
- return {
845
- target,
846
- cardinality: "one",
847
- optional: options?.optional ?? false
848
- };
849
- }
850
- /** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */
851
- const Relation = {
852
- one,
853
- /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */
854
- input: (relation) => Object.freeze({
855
- _tag: "RelationInput",
856
- relation
857
- }),
858
- /**
859
- * For `Entity.input`: the input key holds the relation's target itself, written
860
- * through `input`, an `Entity.input` of the target. A `many` holds a list.
861
- */
862
- nested: (relation, input) => Object.freeze({
863
- _tag: "NestedInput",
864
- relation,
865
- input
866
- }),
867
- many: (target) => ({
868
- target,
869
- cardinality: "many",
870
- optional: false
871
- })
872
- };
873
- const Derived = { make: (schema) => ({ schema }) };
874
- //#endregion
875
- export { Derived, Entity, EntityTypeId, Expr, Order, Query, QueryEvaluateError, Relation, SchemaShape, SelectionPageTypeId, SelectionTypeId, Words, assertSupported, dependenciesOf, evaluate, isPredicate, supported };
876
-
877
- //# sourceMappingURL=index.mjs.map
1
+ import { S as SchemaShape, _ as Query, a as SelectionPageTypeId, b as maxQueryNodes, c as QueryEvaluateError, d as evaluate, f as supported, g as Order, h as Expr, i as Relation, l as assertSupported, m as ReadFilter, n as Entity, o as SelectionTypeId, p as Words, r as EntityTypeId, s as Write, t as Derived, u as compareRows, v as dependenciesOf, x as Collation, y as isPredicate } from "./src-BAA6oWw-.mjs";
2
+ export { Collation, Derived, Entity, EntityTypeId, Expr, Order, Query, QueryEvaluateError, ReadFilter, Relation, SchemaShape, SelectionPageTypeId, SelectionTypeId, Words, Write, assertSupported, compareRows, dependenciesOf, evaluate, isPredicate, maxQueryNodes, supported };