@kedem/okdb 3.0.0 → 3.1.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 (64) hide show
  1. package/CHANGELOG.md +114 -3
  2. package/README.md +72 -36
  3. package/bin/okdb +1 -1
  4. package/docs/auth-and-sync.md +30 -24
  5. package/docs/auth-permissions.md +5 -4
  6. package/docs/c-bridge.md +94 -0
  7. package/docs/change-log.md +79 -36
  8. package/docs/data-model.md +35 -9
  9. package/docs/deployment.md +42 -38
  10. package/docs/diagnostics.md +61 -125
  11. package/docs/embeddings.md +143 -51
  12. package/docs/encryption.md +132 -0
  13. package/docs/files.md +64 -27
  14. package/docs/fts.md +48 -23
  15. package/docs/functions.md +109 -56
  16. package/docs/getting-started.md +121 -9
  17. package/docs/http-api.md +66 -11
  18. package/docs/http-cluster.md +80 -88
  19. package/docs/index.md +33 -15
  20. package/docs/indexes.md +53 -17
  21. package/docs/licensing.md +19 -5
  22. package/docs/logging.md +11 -22
  23. package/docs/manifest.json +6 -3
  24. package/docs/migration.md +41 -16
  25. package/docs/pipelines.md +111 -46
  26. package/docs/plugins.md +47 -15
  27. package/docs/process-registry.md +23 -24
  28. package/docs/processors.md +26 -23
  29. package/docs/querying.md +102 -29
  30. package/docs/queue.md +165 -51
  31. package/docs/resolved-fields.md +24 -1
  32. package/docs/subscriptions.md +4 -4
  33. package/docs/sync.md +9 -6
  34. package/docs/time-machine.md +52 -14
  35. package/docs/transactions.md +63 -15
  36. package/docs/ttl.md +34 -13
  37. package/docs/upgrade-2.0.md +32 -15
  38. package/docs/upgrade-2.1.md +10 -12
  39. package/docs/upgrade-3.0.md +144 -0
  40. package/docs/views.md +165 -61
  41. package/index.js +1 -1
  42. package/native/linux-x64-gnu/okdb +0 -0
  43. package/native/linux-x64-gnu/okdb-node.linux-x64-gnu.node +0 -0
  44. package/native-loader.js +1 -1
  45. package/okdb-native.js +1 -1
  46. package/package.json +1 -1
  47. package/public/features/files/parts/files-blob-status.ok.js +1 -1
  48. package/types/environment.d.ts +32 -11
  49. package/types/errors.d.ts +20 -0
  50. package/types/features/admin.d.ts +3 -5
  51. package/types/features/api.d.ts +5 -7
  52. package/types/features/embeddings.d.ts +8 -7
  53. package/types/features/engines.d.ts +9 -1
  54. package/types/features/files.d.ts +2 -1
  55. package/types/features/fts.d.ts +3 -3
  56. package/types/features/functions.d.ts +14 -8
  57. package/types/features/pipelines.d.ts +10 -10
  58. package/types/features/queue.d.ts +15 -10
  59. package/types/features/sync.d.ts +7 -0
  60. package/types/features/time-machine.d.ts +3 -0
  61. package/types/index.d.ts +3 -0
  62. package/types/okdb.d.ts +70 -7
  63. package/types/options.d.ts +12 -8
  64. package/docs/OKDB-ARCHITECTURE.md +0 -1061
@@ -0,0 +1,144 @@
1
+ # Upgrading to 3.0
2
+
3
+ okdb 3 replaces the Node.js implementation of okdb 2.x with a native core written in Rust. The JavaScript API is the same:
4
+ `new OKDB(path, options)`, environments, types, indexes, queries, views, FTS, embeddings, queue, files, functions, sync, auth, the
5
+ HTTP API and MCP behave as in 2.x. This page lists the deliberate, user-visible differences a 2.x application has to account for.
6
+
7
+ ## Upgrading a store
8
+
9
+ **Stop every okdb 2.x process that uses the store, then open it with okdb 3.** Do not run 2.x and 3.x writers on the same store at
10
+ the same time: the LMDB binding 2.x uses can silently drop one concurrent commit from another process whenever it opens an
11
+ environment (a 2.x known issue; okdb 3's storage layer does not have it).
12
+
13
+ Stores open as-is: the on-disk format is unchanged, and a healthy 2.x store opens without any index rebuild (an index a crash
14
+ left mid-build is rebuilt once, as in 2.x). Backups, exports and `.kdbconfig` files carry over unchanged.
15
+
16
+ Opening an environment retries transient storage errors (for example `EINVAL`, `EAGAIN`, a map resize, a full reader table) for
17
+ about 2.4 seconds and never quarantines an environment because of them. If such an error outlasts the retries, `open()` fails and
18
+ the process should be restarted by its supervisor; there is no per-environment degraded mode for transient errors. Corruption
19
+ still quarantines the affected tenant environment immediately, and permanent failures (disk full, permissions, bad configuration)
20
+ quarantine it as in 2.x (`db.quarantinedEnvs`).
21
+
22
+ ## The package
23
+
24
+ - **Native only, no JavaScript fallback.** The core ships inside the package:
25
+ `node_modules/@kedem/okdb/native/linux-x64-gnu/okdb-node.linux-x64-gnu.node`. There is no separate platform package and no
26
+ optional dependency to lose (`--omit=optional` and cross-platform lockfiles no longer matter). The 2.x JavaScript implementation
27
+ is not shipped (no `okdb.js`, no `bin/okdb.js`, no worker entry files). The 2.x `OKDB_NATIVE` switch is ignored.
28
+ - **Linux x64 (glibc 2.28+) only in 3.0.** The package declares `"os": ["linux"], "cpu": ["x64"]`, so npm refuses to install it on
29
+ macOS, Windows or arm64 (`EBADPLATFORM`). On a host npm lets through anyway (musl/Alpine, `--force`, a package manager that
30
+ ignores `os`/`cpu`), `require('@kedem/okdb')` throws an error with `code: 'NATIVE_UNAVAILABLE'` naming the platform; `err.cause`
31
+ is the load error when the native file exists but fails to load (for example a glibc older than 2.28). Those platforms stay on
32
+ okdb 2.x for now; more platforms come later.
33
+ - **`OKDB_NATIVE_BINARY=<file.node>`** loads an explicit native file and wins over the bundled one (a missing file is an error,
34
+ not a fallback). `OKDB.nativeBinaryPath` is the file actually loaded; `OKDB.implementation` is always `'native'`.
35
+ - **Fewer dependencies.** `lmdb`, `usearch`, `hnswlib-node`, `roaring`, `shmbuf`, `croner` and `uuid` are no longer dependencies
36
+ (the core has its own LMDB binding, vector index, cron parser and shared-memory coordination). The remaining runtime
37
+ dependencies are `msgpackr` and `sift`. Code that imported those packages through okdb's dependency tree must depend on them
38
+ itself.
39
+ - **The `okdb` command** is a small native launcher bundled next to the core that runs the CLI inside the same native file (no
40
+ Node needed to run it): `node_modules/@kedem/okdb/native/linux-x64-gnu/okdb`. `npx okdb` still works through a Node wrapper,
41
+ `okdb --okdb-which` prints the launcher path, and containers can run the launcher directly. Commands, flags, `.kdbconfig` and
42
+ the HTTP cluster (`--workers`, `--no-cluster`) are unchanged.
43
+ - **A C interface.** The same native file exports a stable C ABI for programs that are not Node.js: see [C bridge](./c-bridge.md).
44
+
45
+ ```js
46
+ const OKDB = require('@kedem/okdb');
47
+
48
+ console.log(OKDB.implementation); // 'native'
49
+ console.log(OKDB.nativeBinaryPath); // .../native/linux-x64-gnu/okdb-node.linux-x64-gnu.node
50
+ ```
51
+
52
+ ## Errors: invalid arguments have codes
53
+
54
+ okdb 2.x let a malformed argument run into whatever it hit first and surfaced that component's error as-is: LMDB key errors
55
+ (`A key is required for get, but is undefined`, `Unable to serialize object as a key: {...}`), raw `TypeError`s
56
+ (`Cannot read properties of null (reading 'type')`, `operations is not iterable`), Node's `ERR_INVALID_ARG_TYPE`, or a type name
57
+ coerced to `"[object Object]"` and reported as `TYPE_NOT_REGISTERED`.
58
+
59
+ okdb 3 validates arguments at the API boundary and throws an `OKDBError` with a stable `code`, a message that names the argument,
60
+ and `details = { argument, expected?, got }` (`problem` instead of `expected`/`got` for `INVALID_OPTIONS`). `got` is the kind of the
61
+ value: `undefined`, `null`, `boolean`, `number`, `bigint`, `string`, `empty string`, `array`, `empty array`, `object`, `Date`,
62
+ `Map`, `Buffer`, `function`.
63
+
64
+ | code | thrown when | example message |
65
+ | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
66
+ | `INVALID_KEY` | a document key or range bound that cannot be a key: `undefined`, `[]`, a plain object, a `Map`, a `Date`, a function (`get`, `getEntry`, `getMany`, `getRange`, `getKeys`, `getValues`, `getCount` bounds, `byIndex` parts, name arguments used as keys such as `db.env(name)`) | `key must be a string, number, or array of them; got object` |
67
+ | `INVALID_TYPE_NAME` | a document type argument that is not a string (`get`, `put`, `query`, `getTTL`, `dropType`, `registerType`, HTTP `/transaction` operations, ...). `''` is a string and still answers `TYPE_NOT_REGISTERED` | `type must be a non-empty string; got undefined` |
68
+ | `INVALID_ARGUMENT` | a positional argument of the wrong kind: an object, array, boolean, Date or function where a name or id is expected (`views.get({})`, `queue.pauseJobType({})`, `files.get({})`); a non-string path (`backup`); a non-function handler (`registerHandler`); a missing upload stream | `path must be a string (a filesystem path); got undefined` |
69
+ | `INVALID_OPTIONS` | an options object that is `null` where an object is required (`listTTL(null)`, `queue.list(null)`, `files.upload(null)`, ...), or an unknown enum value / wrong-typed option field (`fts.process({ mode })`, processor `originMode`) | `options: must be an object; got null` |
70
+
71
+ Over HTTP all four codes are **400** with the code in the standard error envelope
72
+ (`{ "error": { "code": "INVALID_KEY", "message": "…", "details": {…} } }`; 2.x answered most of these with a code-less 500). Over
73
+ MCP they are JSON-RPC `-32602` (Invalid params) with `error.data.code` set (2.x: `-32603`).
74
+
75
+ **Absence is not an error.** A lookup of a well-formed value that names nothing still answers `undefined` / `null` / `false` /
76
+ empty, exactly as in 2.x: `get(type, null)` → `undefined`, `hasType(123)` → `false`, `views.get(undefined)` finds nothing, an
77
+ unknown (string) type → `TYPE_NOT_REGISTERED`. Only genuinely invalid input throws.
78
+
79
+ Existing codes are unchanged where they already fit (`INVALID_PRIMARY_KEY`, `INVALID_INDEX_KEY`, `INVALID_VALUE`, `BAD_PARAM`,
80
+ `INVALID_FTS`, `VIEW_INVALID_NAME`, ...).
81
+
82
+ ```js
83
+ await db.registerType('users');
84
+
85
+ try {
86
+ db.get('users', { id: 1 }); // an object is not a key
87
+ } catch (err) {
88
+ console.log(err.code); // 'INVALID_KEY'
89
+ console.log(err.details); // { argument: 'key', expected: '…', got: 'object' }
90
+ }
91
+
92
+ console.log(db.get('users', null)); // undefined — absence, not an error
93
+ ```
94
+
95
+ **Migrating:**
96
+
97
+ - Code that matched messages such as `/A key is required/`, `/Unable to serialize object as a key/`, `/Cannot read properties/` or
98
+ `/is not a function/` to detect bad input should branch on `err.code` instead. `err instanceof OKDBError` is now true for these
99
+ errors (they were plain `Error` / `TypeError` before); `err.name` is `'OKDBError'`.
100
+ - HTTP clients that treated a 500 from a malformed request as a server fault now get a 400 with a code.
101
+ - Inside `env.transaction()` / `txn.commit()`, a bad type or key is reported with its own code rather than wrapped as `TXN_ERROR`.
102
+
103
+ Errors raised by user-supplied code keep the JavaScript error that code raised (function sandbox code, view `map` specs).
104
+
105
+ ## Behaviour fixed in 3.0
106
+
107
+ These were 2.7.0 known issues (or found while building 3.0); code that worked around them may need a look:
108
+
109
+ - `queue.samplePayloads(type)` returns the type's payloads, latest first (limit 1–100, default 50); 2.x always returned `[]`.
110
+ - A view whose `$ref` section crashed mid-scan is rebuilt on the next open instead of staying `partially-ready`; a halted view
111
+ restarted after a reopen is rebuilt when its state can't be trusted.
112
+ - A write with `origin: ""` counts as local everywhere: unique, schema and foreign-key checks apply.
113
+ - `VIEW_TYPE_NOT_REGISTERED` over HTTP is a 404 (was 500).
114
+ - Opening a store no longer drops a concurrent commit from another process, and a peer closing a store no longer leaves the
115
+ others failing every write with `EINVAL`.
116
+
117
+ ## Other behaviour differences
118
+
119
+ - HTTP middleware (`okdb.http.use`): code after `await next()` runs before the route handler, not after it.
120
+ - `functions.run()` held the calling event loop while the function ran in 3.0.0; from 3.0.1 it is asynchronous again (the
121
+ loop keeps running), and a stored function's `runtime.memoryMb` is enforced per run (`FUNCTION_OOM`).
122
+ - The queue's cron expressions are parsed by okdb's own parser; the 2.x `cron_next` hook still overrides it (ignored in 3.0.0, honoured again from 3.0.1).
123
+
124
+ ## Plugins
125
+
126
+ The plugin contract (`db.plugins.register(module, options)` before `open()`, `requires`, `start` / `stop` hooks, the
127
+ `PLUGIN_*` errors) works unchanged, with these differences:
128
+
129
+ - `start()` runs after the whole `open()` has finished (in 2.x it ran in the middle of open, before views and runtime
130
+ declarations booted). A plugin sees a fully started instance.
131
+ - `okdb.api` and `okdb.admin` are stubs: any member call throws `NOT_IMPLEMENTED_NATIVE`. Use HTTP routes
132
+ (`okdb.http.add / use / guard`) and the public facades instead.
133
+ - Plugins that reached into JavaScript internals (`_`-prefixed fields, lmdb handles such as `env.db`) have no equivalent; use the
134
+ public API.
135
+ - The standalone `okdb` server loads no plugins (as in 2.x).
136
+
137
+ See [Plugins](./plugins.md).
138
+
139
+ ## Everything else
140
+
141
+ Removed 2.x options keep throwing the same codes as 2.x (`ENVS_REMOVED`, `SYNC_OPTION_REMOVED`, `BUS_OPTION_REMOVED`,
142
+ `WORKERS_REMOVED`, `QUEUE_WORKER_REMOVED`, `HTTP_CLUSTER_REMOVED`, `DEFER_PROCESSING_REMOVED`, ...): see
143
+ [Upgrading to 2.0](./upgrade-2.0.md). The read-range rules of [2.1](./upgrade-2.1.md) and every other 2.x API are kept unless a
144
+ page in these docs says otherwise.
package/docs/views.md CHANGED
@@ -25,13 +25,18 @@ await env.views.create('orderStats', {
25
25
  },
26
26
  });
27
27
 
28
+ await db.put('orders', 'o1', { status: 'completed', amount: 100, region: 'EU' });
29
+ await db.put('orders', 'o2', { status: 'completed', amount: 300, region: 'EU' });
30
+ await db.put('orders', 'o3', { status: 'completed', amount: 200, region: 'US' });
31
+ await db.put('orders', 'o4', { status: 'pending', amount: 999, region: 'US' }); // filtered out
32
+
28
33
  // Read the live result — synchronous, O(1)
29
34
  const stats = env.views.get('orderStats');
30
35
  // → {
31
- // total: { value: 142500 },
32
- // count: { value: 312 },
33
- // avgValue: { value: 456.7 },
34
- // byRegion: { totalGroups: 2, preview: [{ key: 'EU', value: 140 }, { key: 'US', value: 172 }], hasMore: false, cursor: null }
36
+ // total: { value: 600 },
37
+ // count: { value: 3 },
38
+ // avgValue: { value: 200 },
39
+ // byRegion: { totalGroups: 2, preview: [{ key: 'EU', value: 2 }, { key: 'US', value: 1 }], hasMore: false, cursor: null }
35
40
  // }
36
41
  ```
37
42
 
@@ -39,19 +44,27 @@ const stats = env.views.get('orderStats');
39
44
 
40
45
  ## Definition shape
41
46
 
47
+ <!-- not-runnable: a shape fragment -->
48
+
42
49
  ```js
43
50
  {
44
51
  type: string, // required — source type (must be registered)
45
52
  filter: object, // optional — sift-style filter applied before reducers
46
53
  map: object, // optional — declarative per-doc transform applied before reducers
47
54
  reduce: object, // required, non-empty — output-field → reducer spec
55
+ bucket: object, // optional — see Bucketing
56
+ mode: 'sync' | 'async', // optional, default 'sync'
48
57
  }
49
58
  ```
50
59
 
60
+ `mode: 'sync'` (the default) updates the view inside the commit of every write, so `get()` right after `await put()` already reflects it. `mode: 'async'` maintains the view from a background processor instead: writes commit faster, and `get()` catches up shortly after. Any other value is refused with `VIEW_INVALID_MODE`. `items` is reserved and cannot be a reducer name (`VIEW_RESERVED_NAME`).
61
+
51
62
  ### `filter`
52
63
 
53
64
  Uses [sift](https://github.com/crcn/sift.js) query operators (MongoDB-style). Only documents that pass the filter contribute to the view.
54
65
 
66
+ <!-- not-runnable: a shape fragment -->
67
+
55
68
  ```js
56
69
  filter: { status: 'active', amount: { $gte: 100 } }
57
70
  ```
@@ -67,6 +80,8 @@ A declarative transform merged onto each source document before reducers run. Th
67
80
  | Concatenate | `{ label: { $concat: ['$city', ' – ', '$name'] } }` | `$`-prefixed tokens are field refs (dot paths ok); others are literals |
68
81
  | Coalesce | `{ display: { $coalesce: ['$nickname', '$name', 'Unknown'] } }` | First non-null wins; `$`-prefixed tokens are field refs (dot paths supported) |
69
82
 
83
+ <!-- not-runnable: a shape fragment -->
84
+
70
85
  ```js
71
86
  // Example: enrich each store with its region name via a FK lookup,
72
87
  // then group-count by that enriched field
@@ -105,11 +120,13 @@ Field paths in all reducers support dot notation for nested access: `{ $sum: 'me
105
120
  - **Grouped reducers** (`$countBy`, `$group`): `{ totalGroups, preview: [...], hasMore, cursor }` — a paginated top-N of groups, not a plain `{ [groupKey]: ... }` map. `preview` entries are `{ key, value }` for `$countBy` and `{ key, <subReducerName>: { value } , ... }` for `$group`. By default `$countBy` sorts by count descending, capped at 50 groups; pass `{ preview: { limit, order, axis, cursor } }` to `get()` to page through the rest (`hasMore`/`cursor` mirror the next page).
106
121
  - **`$ref` slots**: a nested object with the same shape as a top-level `reduce` result (see [$ref aggregations](#ref-aggregations))
107
122
 
123
+ <!-- continues -->
124
+
108
125
  ```js
109
126
  const result = env.views.get('orderStats');
110
- result.total.value; // → 142500 (number)
111
- result.avgValue.value; // → 456.7 (number)
112
- result.byRegion.preview.find((e) => e.key === 'EU').value; // → 140 (number)
127
+ result.total.value; // → 600 (number)
128
+ result.avgValue.value; // → 200 (number)
129
+ result.byRegion.preview.find((e) => e.key === 'EU').value; // → 2 (number)
113
130
  ```
114
131
 
115
132
  ### `items: true`
@@ -117,18 +134,33 @@ result.byRegion.preview.find((e) => e.key === 'EU').value; // → 140 (number)
117
134
  Add `items: true` to any reducer spec to enable a `.items()` method on the result group. Calling it returns the live source documents that contribute to that aggregation bucket.
118
135
 
119
136
  ```js
120
- reduce: {
121
- byRegion: { $countBy: 'region', items: true },
122
- total: { $sum: 'amount', items: true },
123
- }
137
+ await db.registerType('orders');
138
+ await env.views.create('regionOrders', {
139
+ type: 'orders',
140
+ reduce: {
141
+ byRegion: { $countBy: 'region', items: true },
142
+ total: { $sum: 'amount', items: true },
143
+ },
144
+ });
145
+ await db.put('orders', 'o1', { amount: 100, region: 'EU' });
146
+ await db.put('orders', 'o2', { amount: 200, region: 'US' });
147
+
148
+ const result = env.views.get('regionOrders');
124
149
 
125
150
  // Access source docs for a specific group
126
- const euOrders = result.byRegion.preview.find((e) => e.key === 'EU').items(); // → Order[]
151
+ const euOrders = result.byRegion.preview.find((e) => e.key === 'EU').items(); // → [{ amount: 100, region: 'EU' }]
127
152
 
128
153
  // Scalar items() returns all matching docs
129
- const allOrders = result.total.items(); // → Order[]
154
+ const allOrders = result.total.items(); // → Order[]
155
+
156
+ // With options, items() returns one page: { result: [{ key, value }], hasMore, lastKey }
157
+ const page = result.total.items({ limit: 1 });
158
+ const next = result.total.items({ limit: 1, offset: 1 });
159
+ const keys = result.total.items({ keysOnly: true }); // result holds keys only
130
160
  ```
131
161
 
162
+ `items(options)` accepts `limit`, `offset`, `startKey`, `reverse`, `keysOnly`, and `bucket` (see [Items scoped to a bucket](#items-scoped-to-a-bucket)). Without options it returns the plain array of documents.
163
+
132
164
  ---
133
165
 
134
166
  ## `$group` reducer
@@ -137,6 +169,8 @@ const allOrders = result.total.items(); // → Order[]
137
169
 
138
170
  ### Syntax
139
171
 
172
+ <!-- not-runnable: a shape fragment -->
173
+
140
174
  ```js
141
175
  reduce: {
142
176
  outputField: {
@@ -158,6 +192,8 @@ reduce: {
158
192
 
159
193
  Like `$countBy`, the result is the paginated `{ totalGroups, preview, hasMore, cursor }` shape (see [Output shape](#output-shape) above) — not a plain `{ [groupKey]: {...} }` map. Each `preview` entry is `{ key, <subReducerName>: { value }, ... }`:
160
194
 
195
+ <!-- not-runnable: a shape fragment -->
196
+
161
197
  ```js
162
198
  {
163
199
  totalGroups: 2,
@@ -170,27 +206,30 @@ Like `$countBy`, the result is the paginated `{ totalGroups, preview, hasMore, c
170
206
  }
171
207
  ```
172
208
 
173
- Empty groups (count/sum reaching 0) are removed automatically — they are never present as `{ value: 0 }`.
174
-
175
- ```js
176
- const stats = env.views.get('orderStats');
177
- const p1 = stats.byProduct.preview.find((e) => e.key === 'p1');
178
- p1.revenue.value; // → 1200
179
- p1.count.value; // → 4
180
- ```
209
+ Empty groups (count/sum reaching 0) are removed automatically — they are never present as `{ value: 0 }`. Reading one group: see the [example](#example) below.
181
210
 
182
211
  ### Compound key
183
212
 
184
213
  Pass an array to `by` to build a key from multiple fields. The fields are joined with a `\x00` separator:
185
214
 
186
215
  ```js
187
- $group: {
188
- by: ['product_id', 'region'],
189
- reduce: { count: { $count: true } },
190
- }
216
+ await db.registerType('sales');
217
+ await env.views.create('salesStats', {
218
+ type: 'sales',
219
+ reduce: {
220
+ byProductRegion: {
221
+ $group: {
222
+ by: ['product_id', 'region'],
223
+ reduce: { count: { $count: true } },
224
+ },
225
+ },
226
+ },
227
+ });
228
+ await db.put('sales', 's1', { product_id: 'p1', region: 'EU' });
191
229
 
192
230
  // Key for product_id='p1', region='EU': 'p1\x00EU'
193
- stats.byProductRegion.preview.find((e) => e.key === 'p1\x00EU').count.value;
231
+ const stats = env.views.get('salesStats');
232
+ stats.byProductRegion.preview.find((e) => e.key === 'p1\x00EU').count.value; // → 1
194
233
  ```
195
234
 
196
235
  ### Filter semantics
@@ -211,6 +250,7 @@ Filters are evaluated at three levels:
211
250
  ### Example
212
251
 
213
252
  ```js
253
+ await db.registerType('line_items');
214
254
  await env.views.create('lineItemStats', {
215
255
  type: 'line_items',
216
256
  reduce: {
@@ -226,34 +266,50 @@ await env.views.create('lineItemStats', {
226
266
  },
227
267
  });
228
268
 
269
+ await db.put('line_items', 'li1', { product_id: 'p1', amount: 1000 });
270
+ await db.put('line_items', 'li2', { product_id: 'p1', amount: 500 });
271
+ await db.put('line_items', 'li3', { product_id: 'p2', amount: 800 });
272
+
229
273
  const stats = env.views.get('lineItemStats');
230
274
  // stats.byProduct.preview = [
231
- // { key: 'p1', revenue: { value: 1500 }, count: { value: 3 } },
232
- // { key: 'p2', revenue: { value: 800 }, count: { value: 2 } },
275
+ // { key: 'p1', revenue: { value: 1500 }, count: { value: 2 } },
276
+ // { key: 'p2', revenue: { value: 800 }, count: { value: 1 } },
233
277
  // ]
278
+ const p1 = stats.byProduct.preview.find((e) => e.key === 'p1');
279
+ p1.revenue.value; // → 1500
280
+ p1.count.value; // → 2
234
281
  ```
235
282
 
236
283
  `$group` also works inside `$ref.reduce`:
237
284
 
238
285
  ```js
239
- reduce: {
240
- lineItems: {
241
- $ref: {
242
- type: 'line_items',
243
- key: 'order_id',
244
- reduce: {
245
- byProduct: {
246
- $group: {
247
- by: 'product_id',
248
- reduce: { total: { $sum: 'amount' } },
286
+ await db.registerType('orders');
287
+ await db.registerType('line_items');
288
+ await env.views.create('orderStats', {
289
+ type: 'orders',
290
+ reduce: {
291
+ lineItems: {
292
+ $ref: {
293
+ type: 'line_items',
294
+ key: 'order_id',
295
+ reduce: {
296
+ byProduct: {
297
+ $group: {
298
+ by: 'product_id',
299
+ reduce: { total: { $sum: 'amount' } },
300
+ },
249
301
  },
250
302
  },
251
303
  },
252
304
  },
253
305
  },
254
- }
306
+ });
307
+ await db.put('orders', 'o1', {});
308
+ await db.put('line_items', 'li1', { order_id: 'o1', product_id: 'p1', amount: 1000 });
309
+ await db.put('line_items', 'li2', { order_id: 'o1', product_id: 'p1', amount: 500 });
255
310
 
256
- stats.lineItems.byProduct.preview.find((e) => e.key === 'p1').total.value; // → aggregate revenue for product p1
311
+ const stats = env.views.get('orderStats');
312
+ stats.lineItems.byProduct.preview.find((e) => e.key === 'p1').total.value; // → 1500, aggregate revenue for product p1
257
313
  ```
258
314
 
259
315
  ---
@@ -264,6 +320,8 @@ A map field with `live: true` on its `$ref` spec is a **live enrichment**: when
264
320
 
265
321
  ### Syntax
266
322
 
323
+ <!-- not-runnable: a shape fragment -->
324
+
267
325
  ```js
268
326
  map: {
269
327
  vendorName: { $ref: ['vendors', '$vendor_id', 'name'], live: true },
@@ -279,12 +337,14 @@ The array form is identical to the snapshot `$ref` — the only difference is th
279
337
  | Snapshot (default, no `live: true`) | The referenced field is resolved once when the source doc is written. Later changes to the referenced doc are not reflected in the view. |
280
338
  | Live (`live: true`) | OKDB maintains an inverse index mapping each referenced doc key to all source docs that point to it. When the referenced doc changes, every source doc in that fan-out set is re-processed through the filter, map, and reducers. |
281
339
 
340
+ <!-- not-runnable: a shape fragment -->
341
+
282
342
  ```js
283
343
  // Snapshot — p1's vendor change does NOT update the view
284
- map: { vendor: { $ref: ['products', '$product_id', 'vendor'] } }
344
+ map: { vendor: { $ref: ['products', '$product_id', 'vendor'] } },
285
345
 
286
346
  // Live — p1's vendor change re-evaluates all line_items with product_id='p1'
287
- map: { vendor: { $ref: ['products', '$product_id', 'vendor'], live: true } }
347
+ map: { vendor: { $ref: ['products', '$product_id', 'vendor'], live: true } },
288
348
  ```
289
349
 
290
350
  ### Cost considerations
@@ -331,6 +391,8 @@ await db.put('products', 'p1', { vendor: 'NewCo' }); // rename the vendor
331
391
  A `$ref` reducer aggregates documents from a _related_ type, scoped to the filtered parent documents. The child type must have a foreign-key field pointing back to the parent type's key.
332
392
 
333
393
  ```js
394
+ await db.registerType('stores');
395
+ await db.registerType('orders');
334
396
  await env.views.create('storeStats', {
335
397
  type: 'stores',
336
398
  filter: { active: true },
@@ -369,6 +431,8 @@ Bucketed views partition their aggregations by a time period (or a custom groupi
369
431
 
370
432
  Add a `bucket` object to the view definition:
371
433
 
434
+ <!-- not-runnable: a shape fragment -->
435
+
372
436
  ```js
373
437
  {
374
438
  type: string, // source type (required)
@@ -401,11 +465,10 @@ The `field` value is interpreted as a Unix timestamp in milliseconds or an ISO d
401
465
  To map each field value to an arbitrary string bucket key, register a projection function under a name with `OKDB.registerBucketProjection(name, fn)`, then reference that **name** in `bucket.project` (instead of `preset`):
402
466
 
403
467
  ```js
404
- const OKDB = require('okdb');
405
-
406
- // Once per process, BEFORE db.open():
468
+ // Once per process, before db.open() (see the note below):
407
469
  OKDB.registerBucketProjection('lowercase', (value) => String(value ?? 'unknown').toLowerCase());
408
470
 
471
+ await db.registerType('products');
409
472
  await env.views.create('byCategory', {
410
473
  type: 'products',
411
474
  reduce: { count: { $count: true } },
@@ -423,12 +486,13 @@ Stores that hold a view created with a function projection before this contract
423
486
  ### Create example
424
487
 
425
488
  ```js
489
+ await db.registerType('orders');
426
490
  await env.views.create('salesByDay', {
427
491
  type: 'orders',
428
492
  filter: { status: 'completed' },
429
493
  reduce: {
430
494
  revenue: { $sum: 'amount' },
431
- count: { $count: true },
495
+ count: { $count: true, items: true },
432
496
  },
433
497
  bucket: {
434
498
  field: 'completedAt', // Unix ms or ISO date string on each source doc
@@ -436,12 +500,18 @@ await env.views.create('salesByDay', {
436
500
  granularity: 'day',
437
501
  },
438
502
  });
503
+
504
+ await db.put('orders', 'o1', { status: 'completed', amount: 500, completedAt: '2024-01-01T09:00:00Z' });
505
+ await db.put('orders', 'o2', { status: 'completed', amount: 700, completedAt: '2024-01-01T15:00:00Z' });
506
+ await db.put('orders', 'o3', { status: 'completed', amount: 890, completedAt: '2024-01-02T10:00:00Z' });
439
507
  ```
440
508
 
441
509
  ### `range(name, options?)` — per-bucket aggregates
442
510
 
443
511
  Returns a sparse ordered array of bucket entries. Only buckets with at least one document appear.
444
512
 
513
+ <!-- continues -->
514
+
445
515
  ```js
446
516
  const rows = env.views.range('salesByDay', {
447
517
  from: '2024-01-01', // ISO date / epoch ms / Date — optional lower bound
@@ -450,8 +520,8 @@ const rows = env.views.range('salesByDay', {
450
520
  includePartial: false, // true = include the bucket containing Date.now()
451
521
  });
452
522
  // → [
453
- // { bucketKey: '2024-01-01', granularity: 'day', reducers: { revenue: { value: 1200 }, count: { value: 4 } }, refs: {} },
454
- // { bucketKey: '2024-01-02', granularity: 'day', reducers: { revenue: { value: 890 }, count: { value: 3 } }, refs: {} },
523
+ // { bucketKey: '2024-01-01', granularity: 'day', reducers: { revenue: { value: 1200 }, count: { value: 2 } }, refs: {} },
524
+ // { bucketKey: '2024-01-02', granularity: 'day', reducers: { revenue: { value: 890 }, count: { value: 1 } }, refs: {} },
455
525
  // ]
456
526
  ```
457
527
 
@@ -466,6 +536,8 @@ Each entry:
466
536
 
467
537
  Returns an ordered list of bucket keys that have at least one document, with per-bucket counts.
468
538
 
539
+ <!-- continues -->
540
+
469
541
  ```js
470
542
  const buckets = env.views.listBuckets('salesByDay', {
471
543
  granularity: 'day', // required — must equal the view's configured granularity
@@ -475,8 +547,8 @@ const buckets = env.views.listBuckets('salesByDay', {
475
547
  reverse: true, // optional — true = latest-first
476
548
  });
477
549
  // → [
478
- // { bucketKey: '2024-12-31', count: 5 },
479
- // { bucketKey: '2024-12-30', count: 12 },
550
+ // { bucketKey: '2024-01-02', count: 1 },
551
+ // { bucketKey: '2024-01-01', count: 2 },
480
552
  // ]
481
553
  ```
482
554
 
@@ -484,10 +556,12 @@ const buckets = env.views.listBuckets('salesByDay', {
484
556
 
485
557
  When a reducer has `items: true`, pass a `bucket` option to `.items()` to restrict results to a single bucket:
486
558
 
559
+ <!-- continues -->
560
+
487
561
  ```js
488
562
  const view = env.views.get('salesByDay');
489
- const items = view.count.items({ bucket: { granularity: 'day', key: '2024-01-15' } });
490
- // → Order[] (only orders in the 2024-01-15 bucket)
563
+ const items = view.count.items({ bucket: { granularity: 'day', key: '2024-01-01' } });
564
+ // → Order[] (only orders in the 2024-01-01 bucket)
491
565
  ```
492
566
 
493
567
  ---
@@ -514,11 +588,19 @@ A stored view that can't be compiled when the store opens — a custom reducer o
514
588
  A full rebuild clears all accumulated state and re-scans the source type from scratch. Triggered automatically on clock regression; also available manually:
515
589
 
516
590
  ```js
591
+ await db.registerType('orders');
592
+ await env.views.create('orderStats', {
593
+ type: 'orders',
594
+ reduce: { total: { $sum: 'amount' }, highest: { $max: 'amount' } },
595
+ });
596
+
517
597
  await env.views.rebuild('orderStats');
518
598
  ```
519
599
 
520
600
  ### Stop / start
521
601
 
602
+ <!-- continues -->
603
+
522
604
  ```js
523
605
  await env.views.stop('orderStats'); // pause processing; definition is preserved
524
606
  await env.views.start('orderStats'); // resume; catches up optimistically or rebuilds
@@ -532,14 +614,22 @@ When a view is stopped and later started:
532
614
 
533
615
  ### Remove
534
616
 
535
- ```js
536
- await env.views.remove('orderStats');
617
+ A view that owns an auto-created index (from `$min` / `$max`) refuses a plain `remove()` with `VIEW_HAS_ORPHANED_INDEXES`; say what happens to the index:
537
618
 
538
- // If the view owns an auto-created index, you must decide what happens to it:
619
+ <!-- continues -->
620
+
621
+ ```js
622
+ try {
623
+ await env.views.remove('orderStats');
624
+ } catch (err) {
625
+ err.code; // → 'VIEW_HAS_ORPHANED_INDEXES' — orderStats owns the index on 'amount'
626
+ }
539
627
  await env.views.remove('orderStats', { managedIndexes: 'drop' }); // drop the index
540
- await env.views.remove('orderStats', { managedIndexes: 'keep' }); // retain the index
628
+ // or: { managedIndexes: 'keep' } — retain the index
541
629
  ```
542
630
 
631
+ A view without managed indexes is removed with `await env.views.remove(name)`.
632
+
543
633
  ---
544
634
 
545
635
  ## Custom reducers
@@ -549,6 +639,8 @@ Register a custom reducer before creating a view that uses it. Custom reducer na
549
639
  Reducers are referenced by name (the function isn't persisted), so register them in every process that opens the store. Prefer the process-wide `OKDB.registerViewReducer(name, { apply })`, called **before `db.open()`** — the stored view then compiles at boot and stays live from the first write. `env.views.registerReducer(name, { apply })` registers for one env after it is open; a stored view whose reducer is registered only that way is held back at `open()` (`getMeta` → `state: 'error'`, `error.code: 'VIEW_UNKNOWN_REDUCER'`) and is fully re-derived when `registerReducer` is called, so writes made in between are not lost.
550
640
 
551
641
  ```js
642
+ await db.registerType('items');
643
+
552
644
  const product = {
553
645
  apply(state, before, after, opts) {
554
646
  // state — current accumulated value (null on first call)
@@ -561,15 +653,18 @@ const product = {
561
653
  return state;
562
654
  },
563
655
  };
564
- OKDB.registerViewReducer('$product', product); // before db.open()
656
+ OKDB.registerViewReducer('$product', product); // normally before db.open()
565
657
 
566
658
  await env.views.create('priceProduct', {
567
659
  type: 'items',
568
660
  reduce: { product: { $product: 'multiplier' } },
569
661
  });
662
+ await db.put('items', 'a', { multiplier: 3 });
663
+ await db.put('items', 'b', { multiplier: 4 });
664
+ env.views.get('priceProduct').product.value; // → 12
570
665
  ```
571
666
 
572
- Documents that already exist when the view is created are folded in by the bootstrap scan, exactly as live writes are (`views.rebuild()` re-derives the same value). Custom reducers also work as `$group` and `$ref` sub-reducers. Views that use a custom reducer or projection bootstrap on the main thread (the off-thread bootstrap worker has no access to the in-process registries).
667
+ Documents that already exist when the view is created are folded in by the bootstrap scan, exactly as live writes are (`views.rebuild()` re-derives the same value). Custom reducers also work as `$group` and `$ref` sub-reducers.
573
668
 
574
669
  ---
575
670
 
@@ -577,6 +672,8 @@ Documents that already exist when the view is created are folded in by the boots
577
672
 
578
673
  All methods are on `env.views` (`OKDBEnv#views`):
579
674
 
675
+ <!-- fragment: an API signature list (optional parameters marked `?`) -->
676
+
580
677
  ```js
581
678
  const env = db.env('myEnv');
582
679
 
@@ -584,7 +681,7 @@ const env = db.env('myEnv');
584
681
  await env.views.create(name, definition) // → { name }
585
682
 
586
683
  // Read
587
- env.views.get(name) // → output object | null (synchronous)
684
+ env.views.get(name, { preview? }) // → output object | null (synchronous)
588
685
  env.views.getMeta(name) // → { state, clock, error, refs, storageVersion, ... } | null
589
686
  await env.views.getDefinition(name) // → stored definition | null
590
687
  await env.views.list() // → string[]
@@ -592,7 +689,8 @@ await env.views.list() // → string[]
592
689
  // Bucketing (bucketed views only)
593
690
  env.views.range(name, options?) // → BucketEntry[] | null (synchronous)
594
691
  env.views.listBuckets(name, options) // → { bucketKey, count }[] (synchronous)
595
- env.views.itemsGroups(name, opts) // → one page of all groups of a grouped reducer
692
+ env.views.itemsGroups(name, { reducerName, refName?, bucket?, axis?, order?, limit?, cursor? })
693
+ // → { items, totalGroups, hasMore, cursor } — one page of all groups of a grouped reducer
596
694
 
597
695
  // Lifecycle
598
696
  await env.views.rebuild(name)
@@ -717,12 +815,18 @@ The one case the upgrade cannot see: writes stamped with an explicit foreign `or
717
815
  | `VIEW_INVALID_REDUCER_NAME` | Custom reducer name does not start with `$` |
718
816
  | `VIEW_REDUCER_CONFLICT` | Custom reducer name conflicts with a built-in |
719
817
  | `VIEW_INVALID_REDUCER` | Custom reducer missing an `apply` function |
818
+ | `VIEW_UNKNOWN_REDUCER` | The definition uses a `$name` no registered reducer matches |
819
+ | `VIEW_INVALID_MODE` | `mode` is not `'sync'` or `'async'` |
820
+ | `VIEW_RESERVED_NAME` | A reducer (or `$ref` sub-reducer) is named `items` |
821
+ | `BUCKET_PROJECT_UNKNOWN` | `bucket.project` names a projection not registered in this process |
822
+ | `BUCKET_PROJECT_NOT_PERSISTABLE` | `bucket.project` is a function instead of a registered name |
720
823
  | `BUCKET_CONFIG_INVALID` | `bucket` config is missing required fields, uses an unsupported preset, or has an invalid granularity |
721
824
  | `BUCKET_INVALID_TIME_VALUE` | A document's bucket field could not be parsed as a time value |
722
825
  | `VIEW_NOT_BUCKETED` | `range()` or `listBuckets()` was called on a view that has no `bucket` config |
723
826
  | `VIEW_RANGE_GRANULARITY_MISMATCH` | The `granularity` option does not match the view's configured granularity |
724
827
  | `VIEW_RANGE_GRANULARITY_REQUIRED` | `listBuckets()` was called without a `granularity` option |
725
- | `VIEW_ITEMS_SCOPE_INVALID` | `scope` is not one of `view`, `reducer`, `ref`, `ref-reducer` |
828
+ | `VIEW_ITEMS_SCOPE_INVALID` | HTTP items `scope` is not one of `view`, `reducer`, `ref`, `ref-reducer`, `groups` |
829
+ | `VIEW_ITEMS_REDUCER_NOT_GROUPED` | `itemsGroups()` named a reducer that is not `$countBy` / `$group` |
726
830
  | `VIEW_ITEMS_REDUCER_NOT_FOUND` | The named reducer does not exist on the view |
727
831
  | `VIEW_ITEMS_REF_NOT_FOUND` | The named `$ref` slot does not exist on the view |
728
832
  | `VIEW_ITEMS_GROUP_NOT_FOUND` | The named group key does not exist on the `$countBy` reducer |