@latticecms/core 0.1.0 → 0.2.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 (78) hide show
  1. package/README.md +180 -57
  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 +132 -4
  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/package.json +12 -11
  58. package/skills/lattice/SKILL.md +2 -2
  59. package/skills/lattice/references/access.md +19 -5
  60. package/skills/lattice/references/collection.md +4 -1
  61. package/skills/lattice/references/method.md +3 -0
  62. package/skills/lattice/references/override.md +89 -6
  63. package/skills/lattice/references/relations.md +3 -2
  64. package/src/access.ts +24 -4
  65. package/src/build.ts +214 -48
  66. package/src/collection.ts +12 -5
  67. package/src/crud.ts +74 -72
  68. package/src/errors.ts +5 -1
  69. package/src/family.ts +21 -21
  70. package/src/index.ts +2 -0
  71. package/src/mask.ts +31 -2
  72. package/src/populate.ts +11 -4
  73. package/src/relations.ts +19 -2
  74. package/src/repo.ts +16 -7
  75. package/src/sort.ts +92 -35
  76. package/src/store/conformance.ts +175 -3
  77. package/src/store/index.ts +7 -1
  78. package/src/store.ts +7 -1
package/src/errors.ts CHANGED
@@ -58,7 +58,11 @@ export const declaredErrors = {
58
58
 
59
59
  export type Issue = z.output<typeof issue>;
60
60
 
61
- /** A VALIDATION error for Zod issues, with one issue per path. */
61
+ /**
62
+ * A VALIDATION error for Zod issues: each issue as Zod reports it, with
63
+ * every unknown key on its own path. A field that fails two checks has two
64
+ * issues, in the order its schema declares them.
65
+ */
62
66
  export function invalid(issues: readonly z.core.$ZodIssue[]) {
63
67
  return LatticeError.VALIDATION({
64
68
  issues: issues.flatMap((issue): Issue[] => {
package/src/family.ts CHANGED
@@ -5,8 +5,8 @@ import { type StandardSchemaV1, UseCase } from 'hexok';
5
5
  import { z } from 'zod';
6
6
  import { CallAccess } from './access.js';
7
7
  import type { AnyCollection } from './collection.js';
8
- import { invalid, LatticeError, refusal } from './errors.js';
9
- import { withheldPaths, withheldWrites } from './mask.js';
8
+ import { invalid, LatticeError, parse, refusal } from './errors.js';
9
+ import { refuseWithheld } from './mask.js';
10
10
  import { type Tenant, tenancy } from './tenancy.js';
11
11
  import { failed, tracer } from './tracing.js';
12
12
 
@@ -203,14 +203,17 @@ export function family<
203
203
  // FORBIDDEN check. The answer stays on ctx.access for execute's scope.
204
204
  .guard(async ({ ctx, spec, token, input }) => {
205
205
  const action = actionOf(spec, token);
206
- // Create's function receives the parsed input, as execute will see it.
207
- const data =
208
- action !== 'create'
209
- ? undefined
210
- : spec.input === undefined
211
- ? input
212
- : z.parse(spec.input, input);
206
+ // Create's function receives the parsed input, as the create body
207
+ // will see it. The generated create's input schema is the collection's
208
+ // schema (operations() in collection.ts), for the generated create and
209
+ // an override alike, so this parse and the body's come from one
210
+ // schema; building the operations here would rebuild every schema on
211
+ // every call.
213
212
  try {
213
+ const data =
214
+ action === 'create'
215
+ ? parse(spec.collection.schema, input)
216
+ : undefined;
214
217
  await ctx.access.scope(spec.collection, action, data);
215
218
  } catch (error) {
216
219
  const log = callLogger(ctx.logger, spec, token, caller(ctx.actor));
@@ -222,19 +225,16 @@ export function family<
222
225
  // a value the caller cannot see (0035), so each is refused, on every
223
226
  // path. Output masking happens where a client receives the result.
224
227
  .guard(async ({ ctx, spec, token, input }) => {
225
- const action = actionOf(spec, token);
226
- if (action !== 'find' && action !== 'count' && action !== 'update') {
227
- return;
228
- }
229
- const withheld = await CallAccess.withheld(ctx.access, spec.collection);
230
- if (withheld.size === 0) return;
231
- const issues =
232
- action === 'update'
233
- ? withheldWrites(input, withheld)
234
- : withheldPaths(input, withheld);
235
- if (issues.length > 0) {
228
+ try {
229
+ await refuseWithheld(
230
+ ctx.access,
231
+ spec.collection,
232
+ actionOf(spec, token),
233
+ input,
234
+ );
235
+ } catch (error) {
236
236
  const log = callLogger(ctx.logger, spec, token, caller(ctx.actor));
237
- throw logThrown(log, token, LatticeError.VALIDATION({ issues }));
237
+ throw logThrown(log, token, error);
238
238
  }
239
239
  })
240
240
  .hooks({
package/src/index.ts CHANGED
@@ -6,10 +6,12 @@ export {
6
6
  } from './access.js';
7
7
  export {
8
8
  type Contract,
9
+ type CreateInput,
9
10
  type Framework,
10
11
  framework,
11
12
  type ReadUseCase,
12
13
  reservedNames,
14
+ type UpdateInput,
13
15
  } from './build.js';
14
16
  export {
15
17
  type Collection,
package/src/mask.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { z } from 'zod';
2
+ import { CallAccess } from './access.js';
3
+ import { LatticeError } from './errors.js';
2
4
  import { type Masked, marked, markOf } from './marker.js';
3
5
  import { innerOf } from './where.js';
4
6
 
@@ -255,11 +257,38 @@ export function applyMask(
255
257
  }
256
258
  }
257
259
 
260
+ /**
261
+ * Refuses, as VALIDATION, a `where` or `sort` on find or count, or an
262
+ * update patch, that names a field withheld from the caller (0031, 0035).
263
+ * A query would reveal it through which rows match or their order, and an
264
+ * update would change a value the caller cannot see. The family guard runs
265
+ * it on every use case, and the generated bodies run it again (0036), so a
266
+ * body called from an override skips nothing.
267
+ */
268
+ export async function refuseWithheld(
269
+ access: CallAccess,
270
+ collection: {
271
+ readonly slug: string;
272
+ readonly maskable: readonly string[];
273
+ },
274
+ action: string,
275
+ input: unknown,
276
+ ): Promise<void> {
277
+ if (action !== 'find' && action !== 'count' && action !== 'update') return;
278
+ const withheld = await CallAccess.withheld(access, collection);
279
+ if (withheld.size === 0) return;
280
+ const issues =
281
+ action === 'update'
282
+ ? withheldWrites(input, withheld)
283
+ : withheldPaths(input, withheld);
284
+ if (issues.length > 0) throw LatticeError.VALIDATION({ issues });
285
+ }
286
+
258
287
  /**
259
288
  * The keys of an update's patch that name a withheld field, for VALIDATION
260
289
  * issues (0035): a caller cannot change, or clear, what it cannot read.
261
290
  */
262
- export function withheldWrites(
291
+ function withheldWrites(
263
292
  input: unknown,
264
293
  withheld: ReadonlySet<string>,
265
294
  ): { path: (string | number)[]; message: string }[] {
@@ -273,7 +302,7 @@ export function withheldWrites(
273
302
  }
274
303
 
275
304
  /** The where and sort paths that name a withheld field, for VALIDATION issues. */
276
- export function withheldPaths(
305
+ function withheldPaths(
277
306
  input: unknown,
278
307
  withheld: ReadonlySet<string>,
279
308
  ): { path: (string | number)[]; message: string }[] {
package/src/populate.ts CHANGED
@@ -9,12 +9,19 @@ const withheld = z.object({ id: z.string() });
9
9
 
10
10
  export type Withheld = z.output<typeof withheld>;
11
11
 
12
- /** The `populate` input field for `keys`, or no field when there are none. */
13
- export function populateShape(keys: readonly string[]): z.core.$ZodShape {
12
+ /**
13
+ * A read's `populate` input: a list of `keys`, or no field when there are
14
+ * none. An object, so a read's input extends its `shape`, and typed, so the
15
+ * read's body takes its list from one parse.
16
+ */
17
+ export type PopulateInput = z.ZodObject &
18
+ z.ZodType<{ populate?: string[] | undefined }>;
19
+
20
+ export function populateInput(keys: readonly string[]): PopulateInput {
14
21
  const [first, ...rest] = keys;
15
22
  return first === undefined
16
- ? {}
17
- : { populate: z.array(z.enum([first, ...rest])).optional() };
23
+ ? z.object({})
24
+ : z.object({ populate: z.array(z.enum([first, ...rest])).optional() });
18
25
  }
19
26
 
20
27
  /**
package/src/relations.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import type { AnyCollection } from './collection.js';
3
+ import { labelOf } from './describe.js';
3
4
  import { innerOf } from './where.js';
4
5
 
5
6
  /**
@@ -31,12 +32,24 @@ function isMarker(check: unknown): check is RefMarker {
31
32
  return typeof check === 'object' && check !== null && '~lattice' in check;
32
33
  }
33
34
 
35
+ /**
36
+ * What a ref says to an empty id, in words from its slug's label: "Choose
37
+ * the company". "The", not "a" or "an": the article depends on how the
38
+ * label sounds. A slug whose singular labelOf cannot find, such as
39
+ * `people`, says "Choose one".
40
+ */
41
+ function emptyRef(slug: string): string {
42
+ const { singular, plural } = labelOf(slug);
43
+ return singular === plural ? 'Choose one' : `Choose the ${singular}`;
44
+ }
45
+
34
46
  /**
35
47
  * Marks a string field as the id of a document in collection `slug`. The
36
48
  * slug, not the collection, so collections can refer to each other.
37
49
  * `z.array(ref(slug))` is a list of ids. The marker is what Lattice reads;
38
50
  * `x-lattice-ref` is what the field's JSON Schema says, so a client such as
39
- * the admin knows where an id points. Both come from `slug`, here.
51
+ * the admin knows where an id points. Both come from `slug`, here. No
52
+ * document has an empty id, so a ref refuses ''.
40
53
  */
41
54
  export function ref<
42
55
  const Slug extends string,
@@ -47,7 +60,11 @@ export function ref<
47
60
  z.check<string>(() => {}),
48
61
  { '~lattice': info },
49
62
  );
50
- return z.string().check(marker).meta({ 'x-lattice-ref': slug });
63
+ return z
64
+ .string()
65
+ .min(1, emptyRef(slug))
66
+ .check(marker)
67
+ .meta({ 'x-lattice-ref': slug });
51
68
  }
52
69
 
53
70
  // ---------------------------------------------------------------- many
package/src/repo.ts CHANGED
@@ -2,10 +2,10 @@ import type { z } from 'zod';
2
2
  import { unscoped, whereOf } from './access.js';
3
3
  import type { AnyCollection } from './collection.js';
4
4
  import { LatticeError, parse } from './errors.js';
5
- import { defaultLimit, defaultSort, type Sort } from './sort.js';
5
+ import { defaultLimit, defaultSort, keyOf, type Sort } from './sort.js';
6
6
  import type { CollectionStore, FindQuery, Patch, StoredDoc } from './store.js';
7
7
  import { type Scope, type TenantField, withoutTenant } from './tenancy.js';
8
- import { type AnyWhere, both, type Where } from './where.js';
8
+ import { type AnyWhere, both, nullish, type Where } from './where.js';
9
9
 
10
10
  /** A collection's stored document: its schema plus `id`, `createdAt` and `updatedAt`. */
11
11
  export type Doc<C extends { readonly output: z.ZodType }> = z.output<
@@ -122,7 +122,7 @@ export function touched<P extends Patch>(patch: P) {
122
122
 
123
123
  /** A store query with find's default sort and limit. */
124
124
  export function findQuery(
125
- collection: string,
125
+ collection: AnyCollection,
126
126
  query: {
127
127
  readonly where?: AnyWhere | undefined;
128
128
  readonly sort?: readonly string[] | undefined;
@@ -130,10 +130,19 @@ export function findQuery(
130
130
  readonly after?: string | undefined;
131
131
  },
132
132
  ): FindQuery {
133
- const { where, sort, limit, after } = query;
133
+ const { where, limit, after } = query;
134
+ const sort = query.sort ?? defaultSort;
135
+ const { shape } = collection.output;
134
136
  return {
135
- collection,
136
- sort: sort ?? defaultSort,
137
+ collection: collection.slug,
138
+ sort,
139
+ // The sort fields the schema lets a document lack.
140
+ optional: sort
141
+ .map((key) => keyOf(key).field)
142
+ .filter((field) => {
143
+ const schema = shape[field];
144
+ return schema !== undefined && nullish(schema);
145
+ }),
137
146
  limit: limit ?? defaultLimit,
138
147
  ...(where === undefined ? {} : { where }),
139
148
  ...(after === undefined ? {} : { after }),
@@ -172,7 +181,7 @@ export function repo(
172
181
  },
173
182
  async find(query, scope) {
174
183
  const where = both(query.where, whereOf(slug, scope));
175
- return store.find(findQuery(slug, { ...query, where }));
184
+ return store.find(findQuery(collection, { ...query, where }));
176
185
  },
177
186
  async count(where, scope) {
178
187
  return store.count(slug, both(where, whereOf(slug, scope)));
package/src/sort.ts CHANGED
@@ -5,9 +5,9 @@ import { markOf } from './marker.js';
5
5
  import {
6
6
  type AnyWhere,
7
7
  compare,
8
+ type FieldOps,
8
9
  type KindOf,
9
10
  kindOf,
10
- nullish,
11
11
  } from './where.js';
12
12
 
13
13
  /** The generated find's sort when the caller gives none. */
@@ -20,21 +20,17 @@ export const maxLimit = 100;
20
20
  const sortableKinds = ['string', 'number', 'enum'] as const;
21
21
 
22
22
  /**
23
- * Whether a field can be sorted: never null or missing, so a cursor
24
- * predicate never meets null, and of an ordered kind. Mirrors `sortable`.
23
+ * Whether a field can be sorted: of an ordered kind. An optional or
24
+ * nullable one sorts too, with its missing values last (0037). Mirrors
25
+ * `sortable`.
25
26
  */
26
- export type IsSortable<V> = null extends V
27
- ? false
28
- : undefined extends V
29
- ? false
30
- : KindOf<V> extends (typeof sortableKinds)[number]
31
- ? true
32
- : false;
27
+ export type IsSortable<V> =
28
+ KindOf<V> extends (typeof sortableKinds)[number] ? true : false;
33
29
 
34
30
  /** Whether a field can be sorted, from its schema. Mirrors `IsSortable`. */
35
31
  export function sortable(schema: z.core.$ZodType): boolean {
36
32
  const kind = kindOf(schema);
37
- return !nullish(schema) && sortableKinds.some((k) => k === kind);
33
+ return sortableKinds.some((k) => k === kind);
38
34
  }
39
35
 
40
36
  type SortableField<Doc> = {
@@ -80,7 +76,7 @@ export function sortSchema(schema: z.ZodObject): z.ZodType {
80
76
  if (typeof input !== 'string') return undefined;
81
77
  const { field } = keyOf(input);
82
78
  return fields.some(([name]) => name === field)
83
- ? `"${field}" cannot be sorted: it is optional, nullable, or not a string, number or enum`
79
+ ? `"${field}" cannot be sorted: it is not a string, number or enum`
84
80
  : `"${field}" is not a field`;
85
81
  },
86
82
  });
@@ -115,23 +111,38 @@ export function parseSort<S extends z.ZodObject>(
115
111
  throw invalid(result.error.issues);
116
112
  }
117
113
 
118
- type OrderKey = { readonly field: string; readonly direction: 1 | -1 };
114
+ type OrderKey = {
115
+ readonly field: string;
116
+ readonly direction: 1 | -1;
117
+ /** Whether a document may have no value here: it then sorts last. */
118
+ readonly optional: boolean;
119
+ };
119
120
 
120
121
  /** A sort as stores apply it: keys in priority order, ending with `id`. */
121
122
  export type Order = readonly OrderKey[];
122
123
 
123
- function keyOf(key: string): OrderKey {
124
+ /** The field a sort key names, and its direction. */
125
+ export function keyOf(key: string): { field: string; direction: 1 | -1 } {
124
126
  return key.startsWith('-')
125
127
  ? { field: key.slice(1), direction: -1 }
126
128
  : { field: key, direction: 1 };
127
129
  }
128
130
 
129
- /** The order a sort means. `id` is the last tiebreak unless the sort has it. */
130
- export function orderOf(sort: readonly string[]): Order {
131
- const keys = sort.map(keyOf);
131
+ /**
132
+ * The order a sort means. `id` is the last tiebreak unless the sort has
133
+ * it. `optional` names the sort fields a document may lack.
134
+ */
135
+ export function orderOf(
136
+ sort: readonly string[],
137
+ optional: readonly string[],
138
+ ): Order {
139
+ const keys = sort.map((key) => {
140
+ const { field, direction } = keyOf(key);
141
+ return { field, direction, optional: optional.includes(field) };
142
+ });
132
143
  return keys.some((key) => key.field === 'id')
133
144
  ? keys
134
- : [...keys, { field: 'id', direction: 1 }];
145
+ : [...keys, { field: 'id', direction: 1, optional: false }];
135
146
  }
136
147
 
137
148
  function keysOf(order: Order): string[] {
@@ -140,23 +151,43 @@ function keysOf(order: Order): string[] {
140
151
  );
141
152
  }
142
153
 
143
- /** Orders documents by `order`. Values compare as `Where` comparisons do. */
154
+ /** The value of `field` in `doc`, null when it has none. */
155
+ function sortValue(
156
+ doc: Readonly<Record<string, unknown>>,
157
+ field: string,
158
+ ): unknown {
159
+ return doc[field] ?? null;
160
+ }
161
+
162
+ /**
163
+ * Orders documents by `order`. Values compare as `Where` comparisons do. On
164
+ * an optional key, a missing value comes after every value, in either
165
+ * direction, and two missing values tie, so the next key decides (0037). A
166
+ * required key compares as before, so an old row that lacks it ties.
167
+ */
144
168
  export function compareDocs(order: Order) {
145
169
  return (
146
170
  a: Readonly<Record<string, unknown>>,
147
171
  b: Readonly<Record<string, unknown>>,
148
172
  ): number => {
149
173
  for (const key of order) {
150
- const result = compare(a[key.field], b[key.field]) ?? 0;
174
+ const x = sortValue(a, key.field);
175
+ const y = sortValue(b, key.field);
176
+ if (key.optional && (x === null || y === null)) {
177
+ if (x === y) continue;
178
+ return x === null ? 1 : -1;
179
+ }
180
+ const result = compare(x, y) ?? 0;
151
181
  if (result !== 0) return result * key.direction;
152
182
  }
153
183
  return 0;
154
184
  };
155
185
  }
156
186
 
187
+ // A missing value is null: JSON has no undefined.
157
188
  const cursorSchema = z.object({
158
189
  sort: z.array(z.string()),
159
- values: z.array(z.union([z.string(), z.number()])),
190
+ values: z.array(z.union([z.string(), z.number(), z.null()])),
160
191
  });
161
192
 
162
193
  /** An opaque cursor that starts the next page after `doc`. */
@@ -166,7 +197,7 @@ export function encodeCursor(
166
197
  ): string {
167
198
  const cursor = {
168
199
  sort: keysOf(order),
169
- values: order.map((key) => doc[key.field]),
200
+ values: order.map((key) => sortValue(doc, key.field)),
170
201
  };
171
202
  return Buffer.from(JSON.stringify(cursor)).toString('base64url');
172
203
  }
@@ -184,31 +215,57 @@ function readCursor(cursor: string): unknown {
184
215
  }
185
216
 
186
217
  /**
187
- * The keyset filter for the documents after `cursor` under `order`: the
188
- * tuple of sort values comes after the cursor's, key by key, in each key's
189
- * direction. It is a `Where`, so every store applies it as it applies any
190
- * filter, and sort fields are never null, so no key meets a missing value.
218
+ * The sort values `cursor` holds under `order`, one per key, null where its
219
+ * document had none. Throws VALIDATION at `after` for a malformed cursor,
220
+ * one from another sort, or a null on a required key.
191
221
  */
192
- export function after(order: Order, cursor: string): AnyWhere {
222
+ export function cursorValues(
223
+ order: Order,
224
+ cursor: string,
225
+ ): readonly (string | number | null)[] {
193
226
  const parsed = cursorSchema.safeParse(readCursor(cursor));
194
227
  if (!parsed.success) throw badCursor('The cursor is malformed');
195
228
  const { sort, values } = parsed.data;
196
229
  if (sort.join(',') !== keysOf(order).join(',')) {
197
230
  throw badCursor('The cursor is for a different sort');
198
231
  }
199
- if (values.length !== order.length) {
232
+ if (
233
+ values.length !== order.length ||
234
+ order.some((key, index) => values[index] === null && !key.optional)
235
+ ) {
200
236
  throw badCursor('The cursor is malformed');
201
237
  }
238
+ return values;
239
+ }
240
+
241
+ /**
242
+ * The keyset filter for the documents after `cursor` under `order`: the
243
+ * tuple of sort values comes after the cursor's, key by key, in each key's
244
+ * direction. It is a `Where`, so every store applies it as it applies any
245
+ * filter. A missing value comes after every value (0037): after a value, an
246
+ * optional key also takes the rows that have none, and nothing comes after
247
+ * a missing one but the rows that tie on it. A required key's filter is a
248
+ * plain comparison.
249
+ */
250
+ export function after(order: Order, cursor: string): AnyWhere {
251
+ const values = cursorValues(order, cursor);
202
252
  const clauses: AnyWhere[] = [];
203
- const equal: Record<string, { readonly eq: string | number }> = {};
204
- order.forEach(({ field, direction }, index) => {
253
+ const equal: Record<string, FieldOps> = {};
254
+ order.forEach(({ field, direction, optional }, index) => {
205
255
  const value = values[index];
206
256
  if (value === undefined) throw badCursor('The cursor is malformed');
207
- clauses.push({
208
- ...equal,
209
- [field]: direction === 1 ? { gt: value } : { lt: value },
210
- });
211
- equal[field] = { eq: value };
257
+ if (value !== null) {
258
+ const beyond = direction === 1 ? { gt: value } : { lt: value };
259
+ clauses.push(
260
+ optional
261
+ ? {
262
+ ...equal,
263
+ or: [{ [field]: beyond }, { [field]: { exists: false } }],
264
+ }
265
+ : { ...equal, [field]: beyond },
266
+ );
267
+ }
268
+ equal[field] = value === null ? { exists: false } : { eq: value };
212
269
  });
213
270
  return { or: clauses };
214
271
  }