@latticecms/core 0.1.0 → 0.3.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 (83) hide show
  1. package/README.md +183 -60
  2. package/dist/access.d.ts +2 -3
  3. package/dist/access.d.ts.map +1 -1
  4. package/dist/access.js +21 -5
  5. package/dist/access.js.map +1 -1
  6. package/dist/build.d.ts +52 -4
  7. package/dist/build.d.ts.map +1 -1
  8. package/dist/build.js +78 -21
  9. package/dist/build.js.map +1 -1
  10. package/dist/collection.d.ts.map +1 -1
  11. package/dist/collection.js +12 -5
  12. package/dist/collection.js.map +1 -1
  13. package/dist/crud.d.ts +24 -8
  14. package/dist/crud.d.ts.map +1 -1
  15. package/dist/crud.js +47 -59
  16. package/dist/crud.js.map +1 -1
  17. package/dist/errors.d.ts +5 -1
  18. package/dist/errors.d.ts.map +1 -1
  19. package/dist/errors.js +5 -1
  20. package/dist/errors.js.map +1 -1
  21. package/dist/family.js +15 -19
  22. package/dist/family.js.map +1 -1
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/mask.d.ts +11 -11
  27. package/dist/mask.d.ts.map +1 -1
  28. package/dist/mask.js +24 -2
  29. package/dist/mask.js.map +1 -1
  30. package/dist/populate.d.ts +9 -2
  31. package/dist/populate.d.ts.map +1 -1
  32. package/dist/populate.js +3 -4
  33. package/dist/populate.js.map +1 -1
  34. package/dist/relations.d.ts +2 -1
  35. package/dist/relations.d.ts.map +1 -1
  36. package/dist/relations.js +18 -2
  37. package/dist/relations.js.map +1 -1
  38. package/dist/repo.d.ts +1 -1
  39. package/dist/repo.d.ts.map +1 -1
  40. package/dist/repo.js +15 -6
  41. package/dist/repo.js.map +1 -1
  42. package/dist/sort.d.ts +32 -7
  43. package/dist/sort.d.ts.map +1 -1
  44. package/dist/sort.js +66 -24
  45. package/dist/sort.js.map +1 -1
  46. package/dist/store/conformance.d.ts.map +1 -1
  47. package/dist/store/conformance.js +146 -5
  48. package/dist/store/conformance.js.map +1 -1
  49. package/dist/store/index.d.ts +1 -1
  50. package/dist/store/index.d.ts.map +1 -1
  51. package/dist/store/index.js +1 -1
  52. package/dist/store/index.js.map +1 -1
  53. package/dist/store.d.ts +6 -0
  54. package/dist/store.d.ts.map +1 -1
  55. package/dist/store.js +1 -1
  56. package/dist/store.js.map +1 -1
  57. package/dist/where.d.ts +3 -1
  58. package/dist/where.d.ts.map +1 -1
  59. package/dist/where.js +31 -5
  60. package/dist/where.js.map +1 -1
  61. package/package.json +12 -11
  62. package/skills/lattice/SKILL.md +2 -2
  63. package/skills/lattice/references/access.md +19 -5
  64. package/skills/lattice/references/collection.md +4 -1
  65. package/skills/lattice/references/method.md +3 -0
  66. package/skills/lattice/references/override.md +89 -6
  67. package/skills/lattice/references/relations.md +3 -2
  68. package/src/access.ts +24 -4
  69. package/src/build.ts +214 -48
  70. package/src/collection.ts +12 -5
  71. package/src/crud.ts +74 -72
  72. package/src/errors.ts +5 -1
  73. package/src/family.ts +21 -21
  74. package/src/index.ts +2 -0
  75. package/src/mask.ts +31 -2
  76. package/src/populate.ts +11 -4
  77. package/src/relations.ts +19 -2
  78. package/src/repo.ts +16 -7
  79. package/src/sort.ts +92 -35
  80. package/src/store/conformance.ts +193 -4
  81. package/src/store/index.ts +7 -1
  82. package/src/store.ts +7 -1
  83. package/src/where.ts +36 -9
@@ -96,6 +96,7 @@ async function found(
96
96
  collection,
97
97
  where,
98
98
  sort: ['id'],
99
+ optional: [],
99
100
  limit: 100,
100
101
  });
101
102
  return idsOf(page.docs);
@@ -108,6 +109,7 @@ async function pages(
108
109
  sort: readonly string[],
109
110
  limit: number,
110
111
  where?: AnyWhere,
112
+ optional: readonly string[] = [],
111
113
  ): Promise<string[][]> {
112
114
  const seen: string[][] = [];
113
115
  let after: string | undefined;
@@ -115,6 +117,7 @@ async function pages(
115
117
  const page = await store.find({
116
118
  collection,
117
119
  sort,
120
+ optional,
118
121
  limit,
119
122
  ...(where === undefined ? {} : { where }),
120
123
  ...(after === undefined ? {} : { after }),
@@ -244,6 +247,75 @@ function checkPages(
244
247
  );
245
248
  }
246
249
 
250
+ /**
251
+ * Eleven documents for sorts on optional fields: `due` is a date, null,
252
+ * missing or explicitly undefined, and `note` a string, null or missing,
253
+ * with ties on each; `rank` is a required number that ties.
254
+ */
255
+ const dated: readonly StoredDoc[] = [
256
+ { id: 'e00', due: '2026-01-03', rank: 1, note: 'b' },
257
+ { id: 'e01', rank: 2, note: 'a' },
258
+ { id: 'e02', due: '2026-01-01', rank: 1 },
259
+ { id: 'e03', due: null, rank: 1, note: 'a' },
260
+ { id: 'e04', due: '2026-01-03', rank: 2, note: null },
261
+ { id: 'e05', rank: 1, note: 'b' },
262
+ { id: 'e06', due: '2026-01-02', rank: 2 },
263
+ { id: 'e07', due: '2026-01-01', rank: 2, note: 'a' },
264
+ { id: 'e08', due: null, rank: 2, note: 'b' },
265
+ { id: 'e09', rank: 1, note: null },
266
+ { id: 'e10', due: undefined, rank: 2, note: 'a' },
267
+ ];
268
+
269
+ /** The optional fields of `dated`. */
270
+ const datedOptional = ['due', 'note'];
271
+
272
+ /**
273
+ * The order of `docs` under `sort`, with a missing or null value after
274
+ * every value in either direction, written without any store's code.
275
+ */
276
+ function expectedMissingLast(
277
+ docs: readonly StoredDoc[],
278
+ sort: readonly string[],
279
+ ): string[] {
280
+ const keys = sort.map((key) =>
281
+ key.startsWith('-')
282
+ ? { field: key.slice(1), dir: -1 }
283
+ : { field: key, dir: 1 },
284
+ );
285
+ keys.push({ field: 'id', dir: 1 });
286
+ return [...docs]
287
+ .sort((x, y) => {
288
+ for (const { field, dir } of keys) {
289
+ const [p, q] = [x[field] ?? null, y[field] ?? null];
290
+ if (p === q) continue;
291
+ if (p === null) return 1;
292
+ if (q === null) return -1;
293
+ return String(p) < String(q) ? -dir : dir;
294
+ }
295
+ return 0;
296
+ })
297
+ .map((doc) => doc.id);
298
+ }
299
+
300
+ /**
301
+ * Sorts on `dated`, each with the plan MongoStore takes for it: a plain
302
+ * sort when no ascending key is optional, two phases when only the first
303
+ * key is, and a computed key otherwise.
304
+ */
305
+ const optionalSorts: readonly (readonly string[])[] = [
306
+ ['due'], // two phases
307
+ ['-due'], // plain
308
+ ['due', '-rank'], // two phases
309
+ ['-due', 'rank'], // plain
310
+ ['rank', 'due'], // computed
311
+ ['-rank', '-due'], // plain
312
+ ['due', 'note'], // computed, two flags
313
+ ['-due', '-note'], // plain: a nested or after an exists: false prefix
314
+ ['due', '-note'], // two phases, then a descending optional key
315
+ ['-due', 'note'], // computed
316
+ ['note', '-due'], // two phases on note
317
+ ];
318
+
247
319
  export const storeCases: readonly StoreCase[] = [
248
320
  // ---------------------------------------------------------------- methods
249
321
  {
@@ -434,7 +506,12 @@ export const storeCases: readonly StoreCase[] = [
434
506
  name: 'find on an empty or unknown collection is an empty last page',
435
507
  async run(store) {
436
508
  same(
437
- await store.find({ collection: 'm_none', sort: [], limit: 10 }),
509
+ await store.find({
510
+ collection: 'm_none',
511
+ sort: [],
512
+ optional: [],
513
+ limit: 10,
514
+ }),
438
515
  { docs: [], next: null },
439
516
  'find on an unknown collection',
440
517
  );
@@ -482,7 +559,7 @@ export const storeCases: readonly StoreCase[] = [
482
559
  [{ at: { lt: '2027-01-01T00:00:00.000Z' } }, ['t1', 't2', 't3']],
483
560
  ]),
484
561
  {
485
- name: 'where: has matches an array with an equal element; a missing or null array has none',
562
+ name: 'where: has matches an array with an equal element, nhas one without; a missing or null array has none',
486
563
  async run(store) {
487
564
  await seed(store, 'where_has', [
488
565
  { id: 'h1', tags: ['a', 'b'], nums: [1, 2] },
@@ -499,6 +576,18 @@ export const storeCases: readonly StoreCase[] = [
499
576
  [{ nums: { has: 2 } }, ['h1']],
500
577
  [{ nums: { has: 3 } }, []],
501
578
  [{ or: [{ tags: { has: 'a' } }, { nums: { has: 9 } }] }, ['h1']],
579
+ [{ tags: { nhas: 'a' } }, ['h2', 'h3', 'h4', 'h5']],
580
+ [{ tags: { nhas: 'b' } }, ['h3', 'h4', 'h5']],
581
+ [{ nums: { nhas: 2 } }, ['h2', 'h3', 'h4', 'h5']],
582
+ [{ tags: { has: 'b', nhas: 'a' } }, ['h2']],
583
+ [{ tags: { has: 'a', nhas: 'a' } }, []],
584
+ [{ tags: { nhas: 'a', exists: false } }, ['h4', 'h5']],
585
+ [
586
+ { or: [{ tags: { nhas: 'b' } }, { nums: { has: 1 } }] },
587
+ ['h1', 'h3', 'h4', 'h5'],
588
+ ],
589
+ // `nhas` and `exists: true` are both `$ne` in Mongo.
590
+ [{ tags: { nhas: 'a', exists: true } }, ['h2', 'h3']],
502
591
  ];
503
592
  for (const [where, ids] of expectations) {
504
593
  same(
@@ -512,6 +601,11 @@ export const storeCases: readonly StoreCase[] = [
512
601
  2,
513
602
  'count with has',
514
603
  );
604
+ same(
605
+ await store.count('where_has', { tags: { nhas: 'a' } }),
606
+ 4,
607
+ 'count with nhas',
608
+ );
515
609
  },
516
610
  },
517
611
  whereCase('exists: null does not exist; arrays and objects', [
@@ -574,7 +668,12 @@ export const storeCases: readonly StoreCase[] = [
574
668
  const [many] = await store.getMany('c_copies', ['p1']);
575
669
  Object.assign(many ?? {}, { title: 'changed' });
576
670
  const [first] = (
577
- await store.find({ collection: 'c_copies', sort: [], limit: 1 })
671
+ await store.find({
672
+ collection: 'c_copies',
673
+ sort: [],
674
+ optional: [],
675
+ limit: 1,
676
+ })
578
677
  ).docs;
579
678
  Object.assign(first ?? {}, { title: 'changed' });
580
679
  const patch = { meta: { tags: ['b'] } };
@@ -664,6 +763,7 @@ export const storeCases: readonly StoreCase[] = [
664
763
  const first = await store.find({
665
764
  collection: 'k_insert',
666
765
  sort: ['a'],
766
+ optional: [],
667
767
  limit: 4,
668
768
  });
669
769
  same(idsOf(first.docs), ['d00', 'd03', 'd06', 'd09'], 'page one');
@@ -676,6 +776,7 @@ export const storeCases: readonly StoreCase[] = [
676
776
  const page = await store.find({
677
777
  collection: 'k_insert',
678
778
  sort: ['a'],
779
+ optional: [],
679
780
  limit: 4,
680
781
  after,
681
782
  });
@@ -696,6 +797,7 @@ export const storeCases: readonly StoreCase[] = [
696
797
  const first = await store.find({
697
798
  collection: 'k_bad',
698
799
  sort: ['a'],
800
+ optional: [],
699
801
  limit: 2,
700
802
  });
701
803
  const next = first.next ?? '';
@@ -711,7 +813,13 @@ export const storeCases: readonly StoreCase[] = [
711
813
  ];
712
814
  for (const [sort, after] of bad) {
713
815
  const error = await rejection(
714
- store.find({ collection: 'k_bad', sort, limit: 2, after }),
816
+ store.find({
817
+ collection: 'k_bad',
818
+ sort,
819
+ optional: [],
820
+ limit: 2,
821
+ after,
822
+ }),
715
823
  `find with sort ${show(sort)} and cursor ${after}`,
716
824
  );
717
825
  same(
@@ -727,6 +835,7 @@ export const storeCases: readonly StoreCase[] = [
727
835
  await store.find({
728
836
  collection: 'k_bad',
729
837
  sort: ['a'],
838
+ optional: [],
730
839
  limit: 2,
731
840
  after: next,
732
841
  })
@@ -737,6 +846,84 @@ export const storeCases: readonly StoreCase[] = [
737
846
  },
738
847
  },
739
848
 
849
+ {
850
+ name: 'an optional field sorts with missing and null values last, in either direction, paging across the boundary',
851
+ async run(store) {
852
+ await seed(store, 'o_dated', dated);
853
+ for (const sort of optionalSorts) {
854
+ const expected = expectedMissingLast(dated, sort);
855
+ for (const limit of [1, 2, 3, 4, 10]) {
856
+ checkPages(
857
+ await pages(
858
+ store,
859
+ 'o_dated',
860
+ sort,
861
+ limit,
862
+ undefined,
863
+ datedOptional,
864
+ ),
865
+ expected,
866
+ limit,
867
+ `sort ${show(sort)} by ${limit}`,
868
+ );
869
+ }
870
+ }
871
+ },
872
+ },
873
+ {
874
+ name: 'an optional sort pages under a where, and the where on the field is unchanged',
875
+ async run(store) {
876
+ await seed(store, 'o_where', dated);
877
+ const ranked = dated.filter((doc) => doc.rank === 2);
878
+ // One sort per plan, under a where.
879
+ for (const sort of [['-due'], ['due', '-note'], ['due', 'note']]) {
880
+ checkPages(
881
+ await pages(
882
+ store,
883
+ 'o_where',
884
+ sort,
885
+ 2,
886
+ { rank: { eq: 2 } },
887
+ datedOptional,
888
+ ),
889
+ expectedMissingLast(ranked, sort),
890
+ 2,
891
+ `sort ${show(sort)} under rank 2`,
892
+ );
893
+ }
894
+ same(
895
+ await found(store, 'o_where', { due: { exists: false } }),
896
+ ['e01', 'e03', 'e05', 'e08', 'e09', 'e10'],
897
+ 'the rows without a due date',
898
+ );
899
+ },
900
+ },
901
+ {
902
+ name: 'a cursor with no value for a required key is VALIDATION on after',
903
+ async run(store) {
904
+ await seed(store, 'o_bad', dated);
905
+ const encode = (value: unknown) =>
906
+ Buffer.from(JSON.stringify(value)).toString('base64url');
907
+ const error = await rejection(
908
+ store.find({
909
+ collection: 'o_bad',
910
+ sort: ['rank'],
911
+ optional: [],
912
+ limit: 2,
913
+ after: encode({ sort: ['rank', 'id'], values: [null, 'e00'] }),
914
+ }),
915
+ 'find after a null on a required key',
916
+ );
917
+ same(
918
+ LatticeError.is(error) && error.code === 'VALIDATION'
919
+ ? error.data.issues.map((issue) => issue.path)
920
+ : error,
921
+ [['after']],
922
+ 'the error',
923
+ );
924
+ },
925
+ },
926
+
740
927
  // ---------------------------------------------------------------- transaction
741
928
  {
742
929
  name: 'transaction commits its writes, returns its value, and reads them inside',
@@ -761,6 +948,7 @@ export const storeCases: readonly StoreCase[] = [
761
948
  await store.find({
762
949
  collection: 'x_commit',
763
950
  sort: ['id'],
951
+ optional: [],
764
952
  limit: 10,
765
953
  })
766
954
  ).docs,
@@ -801,6 +989,7 @@ export const storeCases: readonly StoreCase[] = [
801
989
  await store.find({
802
990
  collection: 'x_rollback',
803
991
  sort: ['id'],
992
+ optional: [],
804
993
  limit: 10,
805
994
  })
806
995
  ).docs,
@@ -4,7 +4,13 @@
4
4
  * The conformance suite is `@latticecms/core/store/conformance`.
5
5
  */
6
6
 
7
- export { after, encodeCursor, type Order, orderOf } from '../sort.js';
7
+ export {
8
+ after,
9
+ cursorValues,
10
+ encodeCursor,
11
+ type Order,
12
+ orderOf,
13
+ } from '../sort.js';
8
14
  export {
9
15
  CollectionStore,
10
16
  type FindQuery,
package/src/store.ts CHANGED
@@ -18,6 +18,12 @@ export type FindQuery = {
18
18
  readonly where?: AnyWhere;
19
19
  /** Keys as `field` or `-field`. Stores add `id` as the last tiebreak. */
20
20
  readonly sort: readonly string[];
21
+ /**
22
+ * The sort fields a document may have no value for. Such a document comes
23
+ * after every one with a value, in either direction (0037). `orderOf`
24
+ * takes it, so a store plans a plain sort when nothing here is ascending.
25
+ */
26
+ readonly optional: readonly string[];
21
27
  readonly limit: number;
22
28
  /** The `next` cursor of the previous page. */
23
29
  readonly after?: string;
@@ -214,7 +220,7 @@ export class MemoryStore extends Adapter(CollectionStore) {
214
220
  }
215
221
 
216
222
  async find(query: FindQuery): Promise<Page> {
217
- const order = orderOf(query.sort);
223
+ const order = orderOf(query.sort, query.optional);
218
224
  const start =
219
225
  query.after === undefined ? undefined : after(order, query.after);
220
226
  const matching = [...this.rows(query.collection).values()]
package/src/where.ts CHANGED
@@ -19,8 +19,10 @@ const operators = {
19
19
  lt: ordered,
20
20
  lte: ordered,
21
21
  contains: ['string'],
22
- // An array of strings, numbers or enum values: has one equal element.
22
+ // An array of strings, numbers or enum values: has one equal element, or
23
+ // has none.
23
24
  has: ['array'],
25
+ nhas: ['array'],
24
26
  exists: ['string', 'number', 'boolean', 'enum', 'array', 'other'],
25
27
  } as const satisfies Record<string, readonly Kind[]>;
26
28
 
@@ -70,7 +72,7 @@ type Operand<Op extends Operator, B> = Op extends 'eq' | 'ne'
70
72
  ? string
71
73
  : Op extends 'exists'
72
74
  ? boolean
73
- : Op extends 'has'
75
+ : Op extends 'has' | 'nhas'
74
76
  ? B extends readonly (infer E)[]
75
77
  ? Exclude<E, null | undefined>
76
78
  : never
@@ -263,8 +265,29 @@ function valueSchema(kind: Kind, leaf: z.core.$ZodType): z.core.$ZodType {
263
265
  }
264
266
  }
265
267
 
268
+ /**
269
+ * `schema` refusing null: a clone with one more check, so its JSON Schema is
270
+ * unchanged.
271
+ */
272
+ function notNull(schema: z.core.$ZodType): z.core.$ZodType {
273
+ const { def } = schema._zod;
274
+ return z.core.util.clone(schema, {
275
+ ...def,
276
+ checks: [
277
+ ...(def.checks ?? []),
278
+ z.refine((operand) => operand !== null, 'Expected a value, not null'),
279
+ ],
280
+ });
281
+ }
282
+
266
283
  function operandSchema(op: string, value: z.core.$ZodType): z.core.$ZodType {
267
284
  switch (op) {
285
+ case 'has':
286
+ case 'nhas':
287
+ // An element schema may allow null inside a union, which unwrap leaves.
288
+ // Mongo matches a missing array with `$eq: null` and not with
289
+ // `$ne: null`, the reverse of "no elements", so null is refused.
290
+ return notNull(value);
268
291
  case 'eq':
269
292
  case 'ne':
270
293
  return z.nullable(value);
@@ -352,6 +375,7 @@ export type FieldOps = {
352
375
  readonly lte?: unknown;
353
376
  readonly contains?: string;
354
377
  readonly has?: unknown;
378
+ readonly nhas?: unknown;
355
379
  readonly exists?: boolean;
356
380
  };
357
381
 
@@ -406,6 +430,12 @@ function compares(
406
430
  return order !== undefined && test(order);
407
431
  }
408
432
 
433
+ function hasElement(value: unknown, target: unknown): boolean {
434
+ return (
435
+ Array.isArray(value) && value.some((element) => equals(element, target))
436
+ );
437
+ }
438
+
409
439
  function matchesField(value: unknown, ops: FieldOps): boolean {
410
440
  if (ops.eq !== undefined && !equals(value, ops.eq)) return false;
411
441
  if (ops.ne !== undefined && equals(value, ops.ne)) return false;
@@ -424,13 +454,10 @@ function matchesField(value: unknown, ops: FieldOps): boolean {
424
454
  return false;
425
455
  }
426
456
  }
427
- // An element equal to the operand. A missing or null array has none.
428
- if (
429
- ops.has !== undefined &&
430
- !(Array.isArray(value) && value.some((element) => equals(element, ops.has)))
431
- ) {
432
- return false;
433
- }
457
+ // An element equal to the operand. A missing or null array has none, so
458
+ // `nhas` matches it, as Mongo's `$ne` on an array does.
459
+ if (ops.has !== undefined && !hasElement(value, ops.has)) return false;
460
+ if (ops.nhas !== undefined && hasElement(value, ops.nhas)) return false;
434
461
  if (ops.exists !== undefined && present(value) !== ops.exists) return false;
435
462
  return true;
436
463
  }