@kedem/okdb 2.7.1 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +111 -33
  2. package/README.md +68 -36
  3. package/bin/okdb +2 -0
  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 +78 -35
  8. package/docs/data-model.md +32 -8
  9. package/docs/deployment.md +42 -38
  10. package/docs/diagnostics.md +61 -125
  11. package/docs/embeddings.md +143 -51
  12. package/docs/files.md +53 -18
  13. package/docs/fts.md +48 -23
  14. package/docs/functions.md +107 -56
  15. package/docs/getting-started.md +125 -9
  16. package/docs/http-api.md +68 -11
  17. package/docs/http-cluster.md +80 -88
  18. package/docs/index.md +33 -15
  19. package/docs/indexes.md +53 -17
  20. package/docs/licensing.md +18 -4
  21. package/docs/logging.md +11 -22
  22. package/docs/manifest.json +4 -2
  23. package/docs/migration.md +40 -15
  24. package/docs/pipelines.md +96 -32
  25. package/docs/plugins.md +47 -15
  26. package/docs/process-registry.md +23 -24
  27. package/docs/processors.md +26 -23
  28. package/docs/querying.md +102 -29
  29. package/docs/queue.md +167 -51
  30. package/docs/resolved-fields.md +24 -1
  31. package/docs/subscriptions.md +4 -4
  32. package/docs/sync.md +9 -6
  33. package/docs/time-machine.md +40 -11
  34. package/docs/transactions.md +63 -15
  35. package/docs/ttl.md +34 -13
  36. package/docs/upgrade-2.0.md +32 -15
  37. package/docs/upgrade-2.1.md +10 -12
  38. package/docs/upgrade-3.0.md +144 -0
  39. package/docs/views.md +131 -42
  40. package/index.js +1 -0
  41. package/native/linux-x64-gnu/okdb +0 -0
  42. package/native/linux-x64-gnu/okdb-node.linux-x64-gnu.node +0 -0
  43. package/native-loader.d.ts +20 -0
  44. package/native-loader.js +1 -0
  45. package/okdb-native.js +1 -0
  46. package/package.json +27 -14
  47. package/types/environment.d.ts +32 -11
  48. package/types/errors.d.ts +20 -0
  49. package/types/features/admin.d.ts +3 -5
  50. package/types/features/api.d.ts +5 -7
  51. package/types/features/embeddings.d.ts +8 -7
  52. package/types/features/engines.d.ts +9 -1
  53. package/types/features/files.d.ts +2 -1
  54. package/types/features/fts.d.ts +3 -3
  55. package/types/features/functions.d.ts +14 -8
  56. package/types/features/pipelines.d.ts +10 -10
  57. package/types/features/queue.d.ts +15 -10
  58. package/types/features/sync.d.ts +7 -0
  59. package/types/features/time-machine.d.ts +3 -0
  60. package/types/index.d.ts +3 -0
  61. package/types/okdb.d.ts +70 -7
  62. package/types/options.d.ts +12 -8
  63. package/algorithm-worker-thread.js +0 -1
  64. package/bin/okdb.js +0 -2
  65. package/docs/OKDB-ARCHITECTURE.md +0 -1061
  66. package/okdb-functions-sandbox-worker.js +0 -1
  67. package/okdb-http-worker-child.js +0 -1
  68. package/okdb-views-bootstrap-worker.js +0 -1
  69. package/okdb.js +0 -1
@@ -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 pure shape/signature fragment that cannot run -->
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 pure shape/signature fragment that cannot run -->
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 pure shape/signature fragment that cannot run -->
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 pure shape/signature fragment that cannot run -->
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 pure shape/signature fragment that cannot run -->
196
+
161
197
  ```js
162
198
  {
163
199
  totalGroups: 2,
@@ -170,19 +206,14 @@ 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
 
215
+ <!-- not-runnable: a pure shape/signature fragment that cannot run -->
216
+
186
217
  ```js
187
218
  $group: {
188
219
  by: ['product_id', 'region'],
@@ -211,6 +242,7 @@ Filters are evaluated at three levels:
211
242
  ### Example
212
243
 
213
244
  ```js
245
+ await db.registerType('line_items');
214
246
  await env.views.create('lineItemStats', {
215
247
  type: 'line_items',
216
248
  reduce: {
@@ -226,15 +258,24 @@ await env.views.create('lineItemStats', {
226
258
  },
227
259
  });
228
260
 
261
+ await db.put('line_items', 'li1', { product_id: 'p1', amount: 1000 });
262
+ await db.put('line_items', 'li2', { product_id: 'p1', amount: 500 });
263
+ await db.put('line_items', 'li3', { product_id: 'p2', amount: 800 });
264
+
229
265
  const stats = env.views.get('lineItemStats');
230
266
  // stats.byProduct.preview = [
231
- // { key: 'p1', revenue: { value: 1500 }, count: { value: 3 } },
232
- // { key: 'p2', revenue: { value: 800 }, count: { value: 2 } },
267
+ // { key: 'p1', revenue: { value: 1500 }, count: { value: 2 } },
268
+ // { key: 'p2', revenue: { value: 800 }, count: { value: 1 } },
233
269
  // ]
270
+ const p1 = stats.byProduct.preview.find((e) => e.key === 'p1');
271
+ p1.revenue.value; // → 1500
272
+ p1.count.value; // → 2
234
273
  ```
235
274
 
236
275
  `$group` also works inside `$ref.reduce`:
237
276
 
277
+ <!-- not-runnable: a pure shape/signature fragment that cannot run -->
278
+
238
279
  ```js
239
280
  reduce: {
240
281
  lineItems: {
@@ -264,6 +305,8 @@ A map field with `live: true` on its `$ref` spec is a **live enrichment**: when
264
305
 
265
306
  ### Syntax
266
307
 
308
+ <!-- not-runnable: a pure shape/signature fragment that cannot run -->
309
+
267
310
  ```js
268
311
  map: {
269
312
  vendorName: { $ref: ['vendors', '$vendor_id', 'name'], live: true },
@@ -279,6 +322,8 @@ The array form is identical to the snapshot `$ref` — the only difference is th
279
322
  | 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
323
  | 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
324
 
325
+ <!-- not-runnable: a pure shape/signature fragment that cannot run -->
326
+
282
327
  ```js
283
328
  // Snapshot — p1's vendor change does NOT update the view
284
329
  map: { vendor: { $ref: ['products', '$product_id', 'vendor'] } }
@@ -331,6 +376,8 @@ await db.put('products', 'p1', { vendor: 'NewCo' }); // rename the vendor
331
376
  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
377
 
333
378
  ```js
379
+ await db.registerType('stores');
380
+ await db.registerType('orders');
334
381
  await env.views.create('storeStats', {
335
382
  type: 'stores',
336
383
  filter: { active: true },
@@ -369,6 +416,8 @@ Bucketed views partition their aggregations by a time period (or a custom groupi
369
416
 
370
417
  Add a `bucket` object to the view definition:
371
418
 
419
+ <!-- not-runnable: a pure shape/signature fragment that cannot run -->
420
+
372
421
  ```js
373
422
  {
374
423
  type: string, // source type (required)
@@ -401,11 +450,10 @@ The `field` value is interpreted as a Unix timestamp in milliseconds or an ISO d
401
450
  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
451
 
403
452
  ```js
404
- const OKDB = require('okdb');
405
-
406
- // Once per process, BEFORE db.open():
453
+ // Once per process, before db.open() (see the note below):
407
454
  OKDB.registerBucketProjection('lowercase', (value) => String(value ?? 'unknown').toLowerCase());
408
455
 
456
+ await db.registerType('products');
409
457
  await env.views.create('byCategory', {
410
458
  type: 'products',
411
459
  reduce: { count: { $count: true } },
@@ -423,12 +471,13 @@ Stores that hold a view created with a function projection before this contract
423
471
  ### Create example
424
472
 
425
473
  ```js
474
+ await db.registerType('orders');
426
475
  await env.views.create('salesByDay', {
427
476
  type: 'orders',
428
477
  filter: { status: 'completed' },
429
478
  reduce: {
430
479
  revenue: { $sum: 'amount' },
431
- count: { $count: true },
480
+ count: { $count: true, items: true },
432
481
  },
433
482
  bucket: {
434
483
  field: 'completedAt', // Unix ms or ISO date string on each source doc
@@ -436,12 +485,18 @@ await env.views.create('salesByDay', {
436
485
  granularity: 'day',
437
486
  },
438
487
  });
488
+
489
+ await db.put('orders', 'o1', { status: 'completed', amount: 500, completedAt: '2024-01-01T09:00:00Z' });
490
+ await db.put('orders', 'o2', { status: 'completed', amount: 700, completedAt: '2024-01-01T15:00:00Z' });
491
+ await db.put('orders', 'o3', { status: 'completed', amount: 890, completedAt: '2024-01-02T10:00:00Z' });
439
492
  ```
440
493
 
441
494
  ### `range(name, options?)` — per-bucket aggregates
442
495
 
443
496
  Returns a sparse ordered array of bucket entries. Only buckets with at least one document appear.
444
497
 
498
+ <!-- continues -->
499
+
445
500
  ```js
446
501
  const rows = env.views.range('salesByDay', {
447
502
  from: '2024-01-01', // ISO date / epoch ms / Date — optional lower bound
@@ -450,8 +505,8 @@ const rows = env.views.range('salesByDay', {
450
505
  includePartial: false, // true = include the bucket containing Date.now()
451
506
  });
452
507
  // → [
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: {} },
508
+ // { bucketKey: '2024-01-01', granularity: 'day', reducers: { revenue: { value: 1200 }, count: { value: 2 } }, refs: {} },
509
+ // { bucketKey: '2024-01-02', granularity: 'day', reducers: { revenue: { value: 890 }, count: { value: 1 } }, refs: {} },
455
510
  // ]
456
511
  ```
457
512
 
@@ -466,6 +521,8 @@ Each entry:
466
521
 
467
522
  Returns an ordered list of bucket keys that have at least one document, with per-bucket counts.
468
523
 
524
+ <!-- continues -->
525
+
469
526
  ```js
470
527
  const buckets = env.views.listBuckets('salesByDay', {
471
528
  granularity: 'day', // required — must equal the view's configured granularity
@@ -475,8 +532,8 @@ const buckets = env.views.listBuckets('salesByDay', {
475
532
  reverse: true, // optional — true = latest-first
476
533
  });
477
534
  // → [
478
- // { bucketKey: '2024-12-31', count: 5 },
479
- // { bucketKey: '2024-12-30', count: 12 },
535
+ // { bucketKey: '2024-01-02', count: 1 },
536
+ // { bucketKey: '2024-01-01', count: 2 },
480
537
  // ]
481
538
  ```
482
539
 
@@ -484,10 +541,12 @@ const buckets = env.views.listBuckets('salesByDay', {
484
541
 
485
542
  When a reducer has `items: true`, pass a `bucket` option to `.items()` to restrict results to a single bucket:
486
543
 
544
+ <!-- continues -->
545
+
487
546
  ```js
488
547
  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)
548
+ const items = view.count.items({ bucket: { granularity: 'day', key: '2024-01-01' } });
549
+ // → Order[] (only orders in the 2024-01-01 bucket)
491
550
  ```
492
551
 
493
552
  ---
@@ -514,11 +573,19 @@ A stored view that can't be compiled when the store opens — a custom reducer o
514
573
  A full rebuild clears all accumulated state and re-scans the source type from scratch. Triggered automatically on clock regression; also available manually:
515
574
 
516
575
  ```js
576
+ await db.registerType('orders');
577
+ await env.views.create('orderStats', {
578
+ type: 'orders',
579
+ reduce: { total: { $sum: 'amount' }, highest: { $max: 'amount' } },
580
+ });
581
+
517
582
  await env.views.rebuild('orderStats');
518
583
  ```
519
584
 
520
585
  ### Stop / start
521
586
 
587
+ <!-- continues -->
588
+
522
589
  ```js
523
590
  await env.views.stop('orderStats'); // pause processing; definition is preserved
524
591
  await env.views.start('orderStats'); // resume; catches up optimistically or rebuilds
@@ -532,14 +599,22 @@ When a view is stopped and later started:
532
599
 
533
600
  ### Remove
534
601
 
535
- ```js
536
- await env.views.remove('orderStats');
602
+ 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
603
 
538
- // If the view owns an auto-created index, you must decide what happens to it:
604
+ <!-- continues -->
605
+
606
+ ```js
607
+ try {
608
+ await env.views.remove('orderStats');
609
+ } catch (err) {
610
+ err.code; // → 'VIEW_HAS_ORPHANED_INDEXES' — orderStats owns the index on 'amount'
611
+ }
539
612
  await env.views.remove('orderStats', { managedIndexes: 'drop' }); // drop the index
540
- await env.views.remove('orderStats', { managedIndexes: 'keep' }); // retain the index
613
+ // or: { managedIndexes: 'keep' } — retain the index
541
614
  ```
542
615
 
616
+ A view without managed indexes is removed with `await env.views.remove(name)`.
617
+
543
618
  ---
544
619
 
545
620
  ## Custom reducers
@@ -549,6 +624,8 @@ Register a custom reducer before creating a view that uses it. Custom reducer na
549
624
  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
625
 
551
626
  ```js
627
+ await db.registerType('items');
628
+
552
629
  const product = {
553
630
  apply(state, before, after, opts) {
554
631
  // state — current accumulated value (null on first call)
@@ -561,15 +638,18 @@ const product = {
561
638
  return state;
562
639
  },
563
640
  };
564
- OKDB.registerViewReducer('$product', product); // before db.open()
641
+ OKDB.registerViewReducer('$product', product); // normally before db.open()
565
642
 
566
643
  await env.views.create('priceProduct', {
567
644
  type: 'items',
568
645
  reduce: { product: { $product: 'multiplier' } },
569
646
  });
647
+ await db.put('items', 'a', { multiplier: 3 });
648
+ await db.put('items', 'b', { multiplier: 4 });
649
+ env.views.get('priceProduct').product.value; // → 12
570
650
  ```
571
651
 
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).
652
+ 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
653
 
574
654
  ---
575
655
 
@@ -577,6 +657,8 @@ Documents that already exist when the view is created are folded in by the boots
577
657
 
578
658
  All methods are on `env.views` (`OKDBEnv#views`):
579
659
 
660
+ <!-- not-runnable: a pure shape/signature fragment that cannot run -->
661
+
580
662
  ```js
581
663
  const env = db.env('myEnv');
582
664
 
@@ -584,7 +666,7 @@ const env = db.env('myEnv');
584
666
  await env.views.create(name, definition) // → { name }
585
667
 
586
668
  // Read
587
- env.views.get(name) // → output object | null (synchronous)
669
+ env.views.get(name, { preview? }) // → output object | null (synchronous)
588
670
  env.views.getMeta(name) // → { state, clock, error, refs, storageVersion, ... } | null
589
671
  await env.views.getDefinition(name) // → stored definition | null
590
672
  await env.views.list() // → string[]
@@ -592,7 +674,8 @@ await env.views.list() // → string[]
592
674
  // Bucketing (bucketed views only)
593
675
  env.views.range(name, options?) // → BucketEntry[] | null (synchronous)
594
676
  env.views.listBuckets(name, options) // → { bucketKey, count }[] (synchronous)
595
- env.views.itemsGroups(name, opts) // → one page of all groups of a grouped reducer
677
+ env.views.itemsGroups(name, { reducerName, refName?, bucket?, axis?, order?, limit?, cursor? })
678
+ // → { items, totalGroups, hasMore, cursor } — one page of all groups of a grouped reducer
596
679
 
597
680
  // Lifecycle
598
681
  await env.views.rebuild(name)
@@ -717,12 +800,18 @@ The one case the upgrade cannot see: writes stamped with an explicit foreign `or
717
800
  | `VIEW_INVALID_REDUCER_NAME` | Custom reducer name does not start with `$` |
718
801
  | `VIEW_REDUCER_CONFLICT` | Custom reducer name conflicts with a built-in |
719
802
  | `VIEW_INVALID_REDUCER` | Custom reducer missing an `apply` function |
803
+ | `VIEW_UNKNOWN_REDUCER` | The definition uses a `$name` no registered reducer matches |
804
+ | `VIEW_INVALID_MODE` | `mode` is not `'sync'` or `'async'` |
805
+ | `VIEW_RESERVED_NAME` | A reducer (or `$ref` sub-reducer) is named `items` |
806
+ | `BUCKET_PROJECT_UNKNOWN` | `bucket.project` names a projection not registered in this process |
807
+ | `BUCKET_PROJECT_NOT_PERSISTABLE` | `bucket.project` is a function instead of a registered name |
720
808
  | `BUCKET_CONFIG_INVALID` | `bucket` config is missing required fields, uses an unsupported preset, or has an invalid granularity |
721
809
  | `BUCKET_INVALID_TIME_VALUE` | A document's bucket field could not be parsed as a time value |
722
810
  | `VIEW_NOT_BUCKETED` | `range()` or `listBuckets()` was called on a view that has no `bucket` config |
723
811
  | `VIEW_RANGE_GRANULARITY_MISMATCH` | The `granularity` option does not match the view's configured granularity |
724
812
  | `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` |
813
+ | `VIEW_ITEMS_SCOPE_INVALID` | HTTP items `scope` is not one of `view`, `reducer`, `ref`, `ref-reducer`, `groups` |
814
+ | `VIEW_ITEMS_REDUCER_NOT_GROUPED` | `itemsGroups()` named a reducer that is not `$countBy` / `$group` |
726
815
  | `VIEW_ITEMS_REDUCER_NOT_FOUND` | The named reducer does not exist on the view |
727
816
  | `VIEW_ITEMS_REF_NOT_FOUND` | The named `$ref` slot does not exist on the view |
728
817
  | `VIEW_ITEMS_GROUP_NOT_FOUND` | The named group key does not exist on the `$countBy` reducer |
package/index.js ADDED
@@ -0,0 +1 @@
1
+ 'use strict';const _0x5f4eba=_0x2399;(function(_0x520d35,_0x331dda){const _0x55c99c=_0x2399,_0x15fd9c=_0x520d35();while(!![]){try{const _0x2513f4=-parseInt(_0x55c99c(0xff))/0x1+-parseInt(_0x55c99c(0xf3))/0x2*(parseInt(_0x55c99c(0x106))/0x3)+-parseInt(_0x55c99c(0x116))/0x4+parseInt(_0x55c99c(0x108))/0x5*(parseInt(_0x55c99c(0xf4))/0x6)+-parseInt(_0x55c99c(0x10d))/0x7+-parseInt(_0x55c99c(0xfc))/0x8+parseInt(_0x55c99c(0x10a))/0x9;if(_0x2513f4===_0x331dda)break;else _0x15fd9c['push'](_0x15fd9c['shift']());}catch(_0x196a19){_0x15fd9c['push'](_0x15fd9c['shift']());}}}(_0x2ca6,0x9f1b8));function _0x2399(_0x5d66ca,_0x17d434){_0x5d66ca=_0x5d66ca-0xf2;const _0x2ca6ac=_0x2ca6();let _0x239987=_0x2ca6ac[_0x5d66ca];return _0x239987;}const loader=require(_0x5f4eba(0x105)),p=loader[_0x5f4eba(0xf7)]();if(!p['ok']){const e=new Error(p[_0x5f4eba(0x10b)]?_0x5f4eba(0x110)+p[_0x5f4eba(0x109)]+_0x5f4eba(0xf5)+_0x5f4eba(0x117):_0x5f4eba(0x110)+p[_0x5f4eba(0x109)]+_0x5f4eba(0x113)+_0x5f4eba(0x10e));e[_0x5f4eba(0xfa)]=_0x5f4eba(0x10c);if(p['error'])e['cause']=p[_0x5f4eba(0xf9)];throw e;}if(process.env.OKDB_NATIVE_DEBUG)process[_0x5f4eba(0x100)][_0x5f4eba(0x107)]('[okdb]\x20native\x20core:\x20'+p[_0x5f4eba(0x10f)]+'\x20('+p[_0x5f4eba(0x115)]+')\x20'+p[_0x5f4eba(0xfe)]+'\x0a');{const path=require(_0x5f4eba(0x114)),fs=require('node:fs');for(const [k,rel]of[[_0x5f4eba(0xf2),_0x5f4eba(0xfb)],[_0x5f4eba(0xf8),'docs']]){const d=path[_0x5f4eba(0x111)](__dirname,rel);if(!process.env[k]&&fs['existsSync'](d))process.env[k]=d;}}function _0x2ca6(){const _0x2e637b=['key','okdb:\x20the\x20native\x20core\x20is\x20unavailable\x20—\x20','join','call','.\x20Reinstall\x20@kedem/okdb\x20(the\x20addon\x20ships\x20inside\x20the\x20package\x20under\x20','node:path','source','4706500TZkguR','(glibc),\x20or\x20stay\x20on\x20okdb\x202.x\x20on\x20this\x20platform.\x20OKDB_NATIVE_BINARY=<okdb-node\x20.node>\x20loads\x20a\x20build\x20you\x20made\x20yourself.','OKDB_ADMIN_PUBLIC_DIR','4EzIbHe','7459566cJNrAy','.\x20okdb\x203.x\x20has\x20no\x20JavaScript\x20fallback:\x20run\x20it\x20on\x20Linux\x20x64\x20','native','probe','OKDB_DOCS_DIR','error','code','public','463528QWgrWO','defineProperty','path','1196929DZmxFx','stderr','exports','nativeBinaryPath','./okdb-native.js','hasOwnProperty','./native-loader.js','907716dsEWuq','write','5wxltyv','reason','24137595MrCQxB','unsupported','NATIVE_UNAVAILABLE','1658111srmvBw','native/),\x20or\x20set\x20OKDB_NATIVE_BINARY\x20to\x20an\x20okdb-node\x20.node\x20file.'];_0x2ca6=function(){return _0x2e637b;};return _0x2ca6();}const OKDB=require(_0x5f4eba(0x103));module[_0x5f4eba(0x101)]=OKDB,Object[_0x5f4eba(0xfd)](OKDB,'implementation',{'value':_0x5f4eba(0xf6),'enumerable':![],'configurable':!![]});if(!Object['prototype'][_0x5f4eba(0x104)][_0x5f4eba(0x112)](OKDB,_0x5f4eba(0x102)))Object[_0x5f4eba(0xfd)](OKDB,'nativeBinaryPath',{'value':p[_0x5f4eba(0xfe)],'enumerable':![],'configurable':!![]});
Binary file
@@ -0,0 +1,20 @@
1
+ export type PlatformKey = 'linux-x64-gnu' | 'linux-arm64-gnu' | 'linux-x64-musl' | 'linux-arm64-musl';
2
+ export interface Located { path: string | null; key: PlatformKey | null; source?: 'env' | 'bundled' | 'package'; reason?: string; unsupported?: boolean }
3
+ export type Probe =
4
+ | { ok: true; mod: unknown; path: string; key: PlatformKey | null; source?: string; bindingVersion: string | null }
5
+ | { ok: false; reason: string; unsupported?: boolean; error?: Error };
6
+ export function platformKey(): PlatformKey | null;
7
+ export function packageName(key: PlatformKey): string;
8
+ /** "linux/x64/glibc", "darwin/arm64" */
9
+ export function describeHost(): string;
10
+ /** the platform keys bundled under native/ in this package (3.0: ['linux-x64-gnu']) */
11
+ export function bundledKeys(): PlatformKey[];
12
+ /** the stable bundled path: <pkg>/native/<key>/okdb-node.<key>.node (addon) or <pkg>/native/<key>/okdb (launcher) */
13
+ export function bundledPath(key: PlatformKey, kind: 'addon' | 'launcher' | 'cli'): string;
14
+ export function loadedPath(): string | null;
15
+ export const BUNDLED_DIR: 'native';
16
+ export function locate(kind: 'addon' | 'launcher' | 'cli'): Located;
17
+ export function probe(): Probe;
18
+ export function load(): unknown;
19
+ export function isMusl(): boolean;
20
+ export const KEYS: PlatformKey[];
@@ -0,0 +1 @@
1
+ 'use strict';const _0xc25bbd=_0x41a4;(function(_0x557a30,_0x343a2e){const _0x575620=_0x41a4,_0x398eee=_0x557a30();while(!![]){try{const _0x59db9f=-parseInt(_0x575620(0xec))/0x1+-parseInt(_0x575620(0xb3))/0x2+parseInt(_0x575620(0xd2))/0x3+parseInt(_0x575620(0xd0))/0x4+-parseInt(_0x575620(0xd6))/0x5*(-parseInt(_0x575620(0xc3))/0x6)+-parseInt(_0x575620(0xef))/0x7+-parseInt(_0x575620(0xbd))/0x8*(parseInt(_0x575620(0xb4))/0x9);if(_0x59db9f===_0x343a2e)break;else _0x398eee['push'](_0x398eee['shift']());}catch(_0x152cdf){_0x398eee['push'](_0x398eee['shift']());}}}(_0x3b33,0x736da));const fs=require('node:fs'),path=require(_0xc25bbd(0xdd)),SCOPE=_0xc25bbd(0xe5),PREFIX=_0xc25bbd(0xcf),BUNDLED_DIR=_0xc25bbd(0xcf),KEYS=[_0xc25bbd(0xbc),_0xc25bbd(0xce),'linux-x64-musl',_0xc25bbd(0xab)];function isMusl(){const _0x1337a9=_0xc25bbd;try{const _0x104fd8=process['report']&&process[_0x1337a9(0xd4)]['getReport']&&process['report'][_0x1337a9(0xb8)]();if(_0x104fd8&&_0x104fd8['header'])return!_0x104fd8['header'][_0x1337a9(0xc8)];}catch{}try{return fs[_0x1337a9(0xd3)](_0x1337a9(0xd9),_0x1337a9(0xeb))[_0x1337a9(0xb1)](_0x1337a9(0xe4));}catch{}try{return require(_0x1337a9(0xc0))[_0x1337a9(0xc5)](_0x1337a9(0xb9),{'encoding':_0x1337a9(0xeb)})['includes'](_0x1337a9(0xe4));}catch{return![];}}function host(){const _0x3ce539=_0xc25bbd,_0x24bf3e=process.env.OKDB_NATIVE_PLATFORM;if(_0x24bf3e){const [_0x9d38f5,_0x165682,_0x5d0b4a]=_0x24bf3e['split']('-');return{'platform':_0x9d38f5,'arch':_0x165682,'libc':_0x9d38f5===_0x3ce539(0xbf)?_0x5d0b4a==='musl'?_0x3ce539(0xe4):'glibc':null};}const _0x2e04f0=process[_0x3ce539(0xdf)];return{'platform':_0x2e04f0,'arch':process['arch'],'libc':_0x2e04f0===_0x3ce539(0xbf)?isMusl()?_0x3ce539(0xe4):_0x3ce539(0xa9):null};}function _0x41a4(_0x274e74,_0x539589){_0x274e74=_0x274e74-0xa8;const _0x3b3331=_0x3b33();let _0x41a4b6=_0x3b3331[_0x274e74];return _0x41a4b6;}function describeHost(){const _0x1e481a=_0xc25bbd,_0x55b924=host();return[_0x55b924[_0x1e481a(0xdf)],_0x55b924[_0x1e481a(0xb6)],_0x55b924[_0x1e481a(0xb2)]][_0x1e481a(0xb7)](Boolean)[_0x1e481a(0xf0)]('/');}function platformKey(){const _0x2caa3f=_0xc25bbd,_0x2828e5=host();if(_0x2828e5[_0x2caa3f(0xdf)]!==_0x2caa3f(0xbf))return null;const _0x46e975=_0x2828e5[_0x2caa3f(0xb6)]==='x64'?_0x2caa3f(0xaf):_0x2828e5[_0x2caa3f(0xb6)]==='arm64'?_0x2caa3f(0xba):null;if(!_0x46e975)return null;return _0x2caa3f(0xc9)+_0x46e975+'-'+(_0x2828e5[_0x2caa3f(0xb2)]===_0x2caa3f(0xe4)?'musl':'gnu');}function packageName(_0x6cd3cc){return SCOPE+'/'+PREFIX+'-'+_0x6cd3cc;}function bundledKeys(){const _0x9722f7=_0xc25bbd;try{return fs[_0x9722f7(0xca)](path[_0x9722f7(0xf0)](__dirname,BUNDLED_DIR))['filter'](_0x314b4b=>fs[_0x9722f7(0xaa)](path[_0x9722f7(0xf0)](__dirname,BUNDLED_DIR,_0x314b4b,_0x9722f7(0xae)+_0x314b4b+_0x9722f7(0xbe))))['sort']();}catch{return[];}}function bundledPath(_0x2187ca,_0x29191f){const _0x1c7441=_0xc25bbd;if(_0x29191f==='cli')_0x29191f=_0x1c7441(0xcc);return path[_0x1c7441(0xf0)](__dirname,BUNDLED_DIR,_0x2187ca,_0x29191f==='addon'?'okdb-node.'+_0x2187ca+_0x1c7441(0xbe):_0x1c7441(0xc6));}function fromPackage(_0x763f50,_0x8be564){const _0x52a0bf=_0xc25bbd;let _0x69c545;try{_0x69c545=require['resolve'](packageName(_0x763f50)+_0x52a0bf(0xc1),{'paths':[__dirname]});}catch{return null;}const _0x157c3b=path[_0x52a0bf(0xf0)](path[_0x52a0bf(0xe1)](_0x69c545),_0x8be564);return fs['existsSync'](_0x157c3b)?{'path':_0x157c3b}:{'installed':!![]};}function unsupported(){const _0x45da6b=_0xc25bbd,_0x10a045=bundledKeys();return _0x45da6b(0xdc)+describeHost()+':\x20okdb\x203.0\x20ships\x20Linux\x20x64\x20(glibc)\x20only'+(_0x45da6b(0xd7)+(_0x10a045['length']?_0x10a045[_0x45da6b(0xf0)](',\x20'):_0x45da6b(0xc7))+')');}function locate(_0x34baf1){const _0x35fdae=_0xc25bbd;if(_0x34baf1===_0x35fdae(0xa8))_0x34baf1='launcher';const _0x36022e=platformKey(),_0x4e68de=_0x34baf1===_0x35fdae(0xbb)?process.env.OKDB_NATIVE_BINARY:process.env.OKDB_NATIVE_CLI;if(_0x4e68de)return fs[_0x35fdae(0xaa)](_0x4e68de)?{'path':_0x4e68de,'key':_0x36022e,'source':_0x35fdae(0xe8)}:{'path':null,'key':_0x36022e,'reason':(_0x34baf1===_0x35fdae(0xbb)?_0x35fdae(0xd8):'OKDB_NATIVE_CLI')+_0x35fdae(0xe3)+_0x4e68de};if(!_0x36022e)return{'path':null,'key':_0x36022e,'unsupported':!![],'reason':unsupported()};const _0x2c616e=bundledPath(_0x36022e,_0x34baf1);if(fs[_0x35fdae(0xaa)](_0x2c616e))return{'path':_0x2c616e,'key':_0x36022e,'source':_0x35fdae(0xb5)};const _0x43c3ad=_0x34baf1==='addon'?'okdb-node.'+_0x36022e+_0x35fdae(0xbe):path[_0x35fdae(0xf0)](_0x35fdae(0xcd),_0x35fdae(0xc6)),_0x4992ee=fromPackage(_0x36022e,_0x43c3ad);if(_0x4992ee&&_0x4992ee['path'])return{'path':_0x4992ee[_0x35fdae(0xd1)],'key':_0x36022e,'source':_0x35fdae(0xee)};if(_0x4992ee)return{'path':null,'key':_0x36022e,'reason':packageName(_0x36022e)+_0x35fdae(0xcb)+_0x43c3ad[_0x35fdae(0xe6)](/\\/g,'/')+_0x35fdae(0xb0)};if(bundledKeys()[_0x35fdae(0xb1)](_0x36022e))return{'path':null,'key':_0x36022e,'reason':_0x35fdae(0xf1)+path[_0x35fdae(0xc2)](__dirname,_0x2c616e)[_0x35fdae(0xe6)](/\\/g,'/')+_0x35fdae(0xac)+_0x34baf1+')'};return{'path':null,'key':_0x36022e,'unsupported':!![],'reason':unsupported()};}let cached=null;function probe(){const _0x2c3e5c=_0xc25bbd;if(cached)return cached;const _0x53e066=locate('addon');if(!_0x53e066[_0x2c3e5c(0xd1)])return cached={'ok':![],'reason':_0x53e066[_0x2c3e5c(0xe9)],'unsupported':!!_0x53e066[_0x2c3e5c(0xed)]};try{const _0x30b830=require(_0x53e066['path']),_0xda081d=typeof _0x30b830[_0x2c3e5c(0xe0)]===_0x2c3e5c(0xdb)?_0x30b830['bindingVersion']():null;return cached={'ok':!![],'mod':_0x30b830,'path':_0x53e066[_0x2c3e5c(0xd1)],'key':_0x53e066[_0x2c3e5c(0xe2)],'source':_0x53e066['source'],'bindingVersion':_0xda081d};}catch(_0x2906c2){return cached={'ok':![],'reason':'loading\x20'+_0x53e066[_0x2c3e5c(0xd1)]+_0x2c3e5c(0xde)+(_0x2906c2&&_0x2906c2[_0x2c3e5c(0xad)]),'error':_0x2906c2};}}function load(){const _0x2e5cdd=_0xc25bbd,_0x5da53c=probe();if(_0x5da53c['ok'])return _0x5da53c['mod'];const _0x4199b2=new Error('okdb:\x20native\x20core\x20unavailable\x20—\x20'+_0x5da53c[_0x2e5cdd(0xe9)]);_0x4199b2['code']=_0x2e5cdd(0xe7);if(_0x5da53c['error'])_0x4199b2['cause']=_0x5da53c[_0x2e5cdd(0xc4)];throw _0x4199b2;}function loadedPath(){const _0x4861f6=_0xc25bbd;if(!cached||!cached['ok'])return null;try{return fs[_0x4861f6(0xea)](cached['path']);}catch{return path[_0x4861f6(0xd5)](cached[_0x4861f6(0xd1)]);}}module[_0xc25bbd(0xda)]={'load':load,'loadedPath':loadedPath,'probe':probe,'locate':locate,'platformKey':platformKey,'describeHost':describeHost,'bundledKeys':bundledKeys,'bundledPath':bundledPath,'packageName':packageName,'isMusl':isMusl,'KEYS':KEYS,'BUNDLED_DIR':BUNDLED_DIR};function _0x3b33(){const _0x5efa6b=['\x20is\x20installed\x20but\x20has\x20no\x20','launcher','bin','linux-arm64-gnu','native','2529824rmyOOi','path','423936QOLJyM','readFileSync','report','resolve','4405955lxuhOa','\x20(this\x20package\x20bundles:\x20','OKDB_NATIVE_BINARY','/usr/bin/ldd','exports','function','no\x20native\x20build\x20for\x20','node:path','\x20failed:\x20','platform','bindingVersion','dirname','key','\x20points\x20to\x20a\x20missing\x20file:\x20','musl','@okdb','replace','NATIVE_BINARY_MISSING','env','reason','realpathSync','utf8','768844XhIMEU','unsupported','package','1797852jfxNEM','join','this\x20package\x20has\x20no\x20','cli','glibc','existsSync','linux-arm64-musl','\x20(a\x20build\x20without\x20the\x20','message','okdb-node.','x64','\x20(a\x20build\x20without\x20it)','includes','libc','165044KLsnFH','665667vlfCmh','bundled','arch','filter','getReport','ldd\x20--version\x202>&1\x20||\x20true','arm64','addon','linux-x64-gnu','8IsXJxx','.node','linux','node:child_process','/package.json','relative','6lzpRAb','error','execSync','okdb','nothing','glibcVersionRuntime','linux-','readdirSync'];_0x3b33=function(){return _0x5efa6b;};return _0x3b33();}