@kedem/okdb 3.0.0 → 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 (62) hide show
  1. package/CHANGELOG.md +38 -3
  2. package/README.md +68 -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 +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 -1
  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.js +1 -1
  44. package/okdb-native.js +1 -1
  45. package/package.json +1 -1
  46. package/types/environment.d.ts +32 -11
  47. package/types/errors.d.ts +20 -0
  48. package/types/features/admin.d.ts +3 -5
  49. package/types/features/api.d.ts +5 -7
  50. package/types/features/embeddings.d.ts +8 -7
  51. package/types/features/engines.d.ts +9 -1
  52. package/types/features/files.d.ts +2 -1
  53. package/types/features/fts.d.ts +3 -3
  54. package/types/features/functions.d.ts +14 -8
  55. package/types/features/pipelines.d.ts +10 -10
  56. package/types/features/queue.d.ts +15 -10
  57. package/types/features/sync.d.ts +7 -0
  58. package/types/features/time-machine.d.ts +3 -0
  59. package/types/index.d.ts +3 -0
  60. package/types/okdb.d.ts +70 -7
  61. package/types/options.d.ts +12 -8
  62. package/docs/OKDB-ARCHITECTURE.md +0 -1061
package/CHANGELOG.md CHANGED
@@ -4,10 +4,45 @@ All notable changes to `@kedem/okdb` are documented here. Format loosely follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.0.0/); versions follow [SemVer](https://semver.org/).
5
5
  Dates are release dates.
6
6
 
7
+ ## [3.0.1] - 2026-10-18
8
+
9
+ A bug-fix release for 3.0.0. Nothing changes on disk.
10
+
11
+ ### Changed (read before upgrading)
12
+
13
+ - **`runtime.memoryMb` is enforced per function run.** A run that grows its heap past the function's limit (default 32
14
+ MB, or the `functions.memoryMb` constructor option) fails with `FUNCTION_OOM`; the process and other functions are
15
+ unaffected. Earlier versions documented the limit but did not apply it. Raise `runtime.memoryMb` for functions that
16
+ need more.
17
+
18
+ ### Fixed
19
+
20
+ - **`functions.run()` no longer blocks the event loop.** The function runs on the sandbox thread while the loop keeps
21
+ serving; timeouts, cancellation, `OKDB_FN_SANDBOX_CONCURRENCY` and the run ledger behave as before.
22
+ - **Full-text indexes after `removeEnvironment()`.** Recreating an environment with the same name in the same process
23
+ no longer fails `fts.ensure` with `ALREADY_EXISTS` for an index of the removed environment.
24
+ - **`query()` refuses unknown options again** with the same messages as 2.x (3.0.0 silently ignored them, including on
25
+ the full-text and vector paths).
26
+ - **`byIndex` / `getIndex` / `countByIndex` accept a scalar `prefix`** (`{ prefix: 'x' }` = `['x']`, as in 2.x);
27
+ 3.0.0 ignored it and scanned the whole index.
28
+ - **The queue's `cron_next` option is honoured again** (a function `(expr, fromTs) => ms` that replaces the built-in
29
+ cron scheduler); 3.0.0 accepted and ignored it.
30
+ - **Engine drivers registered on the database** (stored in `~system`) get a working `ctx` (`okdb`, `storeEnv`, `emit`,
31
+ `updateStatus`); 3.0.0 threw from `ctx.emit`.
32
+ - **Embeddings:** `listAlgorithms()` describes the algorithms as built into the core, and the `flat` / `hnsw` /
33
+ `usearch` config schemas list every option the core reads (`idleEvictMs`, `snapshotMaxLagMs`, `tmpMaxAgeMs`, …)
34
+ instead of rejecting them.
35
+ - **Error and log messages** no longer describe 2.x internals (error codes are unchanged).
36
+
37
+ ### Documentation
38
+
39
+ - Every page reviewed for 3.0; new [Upgrading to 3.0](docs/upgrade-3.0.md) and [C bridge](docs/c-bridge.md) pages; the
40
+ code examples in the docs are now run as tests.
41
+
7
42
  ## [3.0.0] - 2026-10-18
8
43
 
9
44
  okdb 3 is a Rust core with the same JavaScript API. The storage format is unchanged: a store written by 2.x opens
10
- as-is, with no migration and no index rebuild. Read [UPGRADING-v3](rs/UPGRADING-v3.md) before upgrading: stop
45
+ as-is, with no migration and no index rebuild. Read [Upgrading to 3.0](docs/upgrade-3.0.md) before upgrading: stop
11
46
  every 2.x process before okdb 3 opens a store, and never run 2.x and 3.x writers on one store at the same time.
12
47
 
13
48
  ### Changed (read before upgrading)
@@ -19,11 +54,11 @@ every 2.x process before okdb 3 opens a store, and never run 2.x and 3.x writers
19
54
  platform. `OKDB_NATIVE_BINARY` overrides the bundled addon. Runtime dependencies are only `msgpackr` and `sift`.
20
55
  - **The `okdb` command is native** (a small launcher that runs the CLI inside the addon; no Node needed).
21
56
  - **Coded errors** replace several free-text errors (`INVALID_KEY`, `INVALID_TYPE_NAME`, `INVALID_ARGUMENT`,
22
- `INVALID_OPTIONS`, …): see UPGRADING-v3.
57
+ `INVALID_OPTIONS`, …): see [Upgrading to 3.0](docs/upgrade-3.0.md#errors-invalid-arguments-have-codes).
23
58
  - **Opening retries transient storage errors** for about 2.4 s and never quarantines an environment for them;
24
59
  if one outlasts the retries, `open()` fails (restart the process). Corruption still quarantines the tenant env.
25
60
  - **Plugins:** 2.x JS plugins work through the Node binding; `start()` runs after the whole open, and `okdb.api`
26
- / `okdb.admin` are not available. See [PLUGINS-v3](rs/PLUGINS-v3.md).
61
+ / `okdb.admin` are not available. See [Upgrading to 3.0](docs/upgrade-3.0.md#plugins).
27
62
 
28
63
  ### Added
29
64
 
package/README.md CHANGED
@@ -19,7 +19,10 @@
19
19
 
20
20
  **OKDB** is an embedded, document-centric database for Node.js. No separate server. No network hop. Open a path, write data.
21
21
 
22
- It wraps [LMDB](https://www.symas.com/lmdb) — one of the fastest memory-mapped key-value stores ever built — and layers on top: typed collections, composite secondary indexes, full-text search, vector embeddings, multi-node sync, a durable job queue, file storage, point-in-time time-machine queries, reactive materialized views, and a built-in HTTP API. All in one process. All ACID.
22
+ It is built on [LMDB](https://www.symas.com/lmdb) — one of the fastest memory-mapped key-value stores ever built — and layers on top: typed collections, composite secondary indexes, full-text search, vector embeddings, multi-node sync, a durable job queue, file storage, point-in-time time-machine queries, reactive materialized views, and a built-in HTTP API. All in one process. All ACID.
23
+
24
+ okdb 3 runs a native core (written in Rust) behind the same JavaScript API as okdb 2.x. The core ships inside the npm package, for
25
+ Linux x64 (glibc 2.28 or newer). Upgrading from 2.x? Read [Upgrading to 3.0](docs/upgrade-3.0.md).
23
26
 
24
27
  ```js
25
28
  const OKDB = require('@kedem/okdb');
@@ -34,7 +37,9 @@ await db.ensureType('users', {
34
37
  await db.put('users', 'alice', { name: 'Alice', role: 'admin', email: 'alice@example.com' });
35
38
 
36
39
  const alice = db.get('users', 'alice'); // synchronous — instant
37
- const admins = db.query('users', { role: 'admin' }); // MongoDB-style filter
40
+ const admins = [...db.query('users', { role: 'admin' })]; // MongoDB-style filter
41
+
42
+ await db.close();
38
43
  ```
39
44
 
40
45
  ---
@@ -63,7 +68,7 @@ Most Node.js apps reach for a separate database server — Postgres, MongoDB, Re
63
68
 
64
69
  ### ⚡ Synchronous reads
65
70
 
66
- LMDB maps the database file directly into process memory. Reads are pointer dereferences — no `await`, no round-trip, no copy.
71
+ LMDB maps the database file directly into process memory. Reads run in-process and return immediately — no `await`, no round-trip.
67
72
 
68
73
  ### 🔒 ACID transactions
69
74
 
@@ -93,28 +98,33 @@ for (const { key, value } of db.byIndex('orders', ['customerId', 'createdAt'], {
93
98
 
94
99
  ### 🔍 Full-text search
95
100
 
96
- Built-in inverted-index FTS backed by a dedicated LMDB environment. No Elasticsearch. No external process.
101
+ Built-in inverted-index FTS (BM25 ranking) backed by a dedicated LMDB environment. No Elasticsearch. No external process.
97
102
 
98
103
  ```js
104
+ await db.ensureType('articles');
105
+ await db.put('articles', 'a1', { title: 'Hello', body: 'hello world from okdb' });
106
+
99
107
  await db.fts.register('articles', 'content', { fields: ['title', 'body'] });
100
108
  await db.fts.ready('articles', 'content');
101
109
 
102
- const results = await db.fts.search('articles', 'content', 'hello world');
110
+ const results = db.fts.search('articles', 'content', 'hello world');
103
111
  ```
104
112
 
105
113
  ### 🤖 Vector embeddings + semantic search
106
114
 
107
115
  First-class embedding pipeline. Point it at a type and a field, connect an embedder (Ollama, OpenAI, or custom), and OKDB handles indexing automatically. Nearest-neighbour search uses an in-process HNSW graph.
108
116
 
117
+ <!-- not-runnable: needs a running Ollama server -->
118
+
109
119
  ```js
110
- await db.embeddings.createPipeline('articles', {
120
+ const { api } = await db.embeddings.createPipeline('articles', {
111
121
  source_type: 'articles',
112
122
  field: 'body',
113
123
  dims: 1024,
114
124
  embedder: { type: 'ollama', model: 'mxbai-embed-large', url: 'http://localhost:11434' },
115
125
  });
116
126
 
117
- const similar = await db.embeddings.search('articles', queryVector, { limit: 10 });
127
+ const similar = await api.searchDocs('how do I bake bread?', { limit: 10 }); // best chunk per document
118
128
  ```
119
129
 
120
130
  ### 🌍 Geo queries
@@ -123,7 +133,9 @@ Built-in geospatial index for radius and bounding-box queries. See [docs/indexes
123
133
 
124
134
  ### 🔄 Multi-node sync
125
135
 
126
- Peer-to-peer last-write-wins replication over HTTP. No coordinator. No Raft. Nodes exchange deltas; HLC timestamps resolve conflicts.
136
+ Peer-to-peer last-write-wins replication over HTTP. No coordinator. No Raft. Nodes exchange deltas; HLC timestamps resolve conflicts. Sync needs a license (it is off on the free tier, see [Licensing](docs/licensing.md)).
137
+
138
+ <!-- not-runnable: needs a license (sync) and a second node -->
127
139
 
128
140
  ```js
129
141
  const db = new OKDB('./node1', {
@@ -138,7 +150,19 @@ await db.sync.join('http://192.168.1.11:8080', { token: 'cluster-bearer-token' }
138
150
 
139
151
  ### 📬 Durable job queue
140
152
 
141
- Crash-safe job queue stored in LMDB. Workers pull jobs, process them, and acknowledge — all without Redis.
153
+ Crash-safe job queue stored in LMDB. Consumers claim jobs, process them, and acknowledge — all without Redis. See [docs/queue.md](docs/queue.md).
154
+
155
+ ```js
156
+ await db.queue.enqueue('email', { to: 'alice@example.com' });
157
+
158
+ // a consumer in this process; run more processes to scale out (each job is claimed exactly once)
159
+ await new Promise((resolve) => {
160
+ db.queue.process('email', async (payload, ctx) => {
161
+ console.log('sending to', payload.to, 'job', ctx.jobId);
162
+ resolve();
163
+ });
164
+ });
165
+ ```
142
166
 
143
167
  ### 📁 File / blob storage
144
168
 
@@ -146,7 +170,7 @@ SHA-256 content-addressable binary blob storage, integrated with the sync system
146
170
 
147
171
  ### 🧩 Sandboxed custom functions
148
172
 
149
- Store JavaScript functions in the database, validate them, and execute them in pooled sandbox runners.
173
+ Store JavaScript functions in the database, validate them, and execute them in a sandbox.
150
174
 
151
175
  - all functions execute with env-local facades: `ctx.env`, `ctx.env.queue`, `ctx.env.files`
152
176
  - mark a function `unsafe: true` to additionally receive `ctx.okdb` for cross-env access
@@ -155,6 +179,8 @@ Store JavaScript functions in the database, validate them, and execute them in p
155
179
  - logging flows through `ctx.log(...)`
156
180
 
157
181
  ```js
182
+ await db.createEnvironment('analytics');
183
+ await db.env('analytics').registerType('events');
158
184
  await db.env('analytics').functions.create({
159
185
  name: 'countEvents',
160
186
  source: '(ctx) => ({ count: ctx.env.getCount("events") })',
@@ -168,12 +194,16 @@ console.log(run.result.value.count);
168
194
 
169
195
  Zero-config REST API and a browser-based admin UI for data exploration, index management, and real-time monitoring.
170
196
 
197
+ <!-- not-runnable: starts a long-running server -->
198
+
171
199
  ```js
172
200
  db.http.listen(8080);
173
- // REST API: http://localhost:8080/api/type/users
201
+ // REST API: http://localhost:8080/api/...
174
202
  // Admin UI: http://localhost:8080/admin/
175
203
  ```
176
204
 
205
+ Or without writing code: `npx okdb --path ./mydb --port 8080` (the `okdb` CLI, see [HTTP API](docs/http-api.md)).
206
+
177
207
  ### 🧠 MCP endpoint (Inspector-ready example)
178
208
 
179
209
  OKDB also exposes an MCP server over SSE + POST:
@@ -181,13 +211,7 @@ OKDB also exposes an MCP server over SSE + POST:
181
211
  - `GET /mcp/sse`
182
212
  - `POST /mcp/messages`
183
213
 
184
- For a local working example, run:
185
-
186
- ```bash
187
- node examples/mcp-inspector.js
188
- ```
189
-
190
- Then in MCP Inspector choose the SSE transport and connect to:
214
+ For a local working example, run `examples/mcp-inspector.js` from the okdb repository, then in MCP Inspector choose the SSE transport and connect to:
191
215
 
192
216
  - `http://localhost:8787/mcp/sse`
193
217
 
@@ -200,9 +224,7 @@ The server responds with browser CORS headers for common Inspector origins, acce
200
224
  - `queue_list_jobs`
201
225
  - `processor_list`
202
226
 
203
- OKDB now derives MCP tools primarily from route operation metadata instead of keeping a separate hand-maintained MCP tool list. Routes marked with canonical metadata and `mcp.include !== false` can participate in MCP generation, while streaming/SSE/raw transport routes stay excluded by default.
204
-
205
- If you run Inspector from a different origin, allow that origin in `src/features/mcp/okdb-mcp.js`.
227
+ MCP tools are derived from the HTTP API's route metadata; streaming / SSE routes are not exposed as tools.
206
228
 
207
229
  ### ⚙️ Reactive processors
208
230
 
@@ -210,22 +232,23 @@ Composable change handlers — like database triggers, written in JavaScript. Re
210
232
 
211
233
  ### ⏱️ Time-machine
212
234
 
213
- Full edit history for every record. Ask what any document looked like at any point in the past — OKDB stores diffs automatically and reconstructs the state on demand.
235
+ Full edit history for every record. Ask what any document looked like at any point in the past — OKDB stores diffs automatically and reconstructs the state on demand. Time machine needs a license (it is off on the free tier).
236
+
237
+ <!-- not-runnable: needs a license (timeMachine) -->
214
238
 
215
239
  ```js
216
- // Enable once; tracking starts from current clock
217
- await db.timeMachine.enable();
240
+ const db = new OKDB('./mydb', { timeMachine: true });
241
+ await db.open();
242
+ const tm = db.env('default').timeMachine;
243
+
244
+ // Enable per type; tracking starts from the current clock
245
+ await tm.enable('orders');
218
246
 
219
247
  // Point-in-time read — synchronous, no await
220
- const snapshot = db.timeMachine.getStateAt('orders', 'ord-42', historicClock);
248
+ const snapshot = tm.getStateAt('orders', 'ord-42', historicClock);
221
249
 
222
250
  // Full history for a single record
223
- const { diffs, head } = db.timeMachine.getHistory('orders', 'ord-42');
224
-
225
- // All changes to a type within a clock range — useful for auditing
226
- for (const change of db.timeMachine.getChanges('orders', fromClock, toClock)) {
227
- console.log(change.key, change.diff);
228
- }
251
+ const history = tm.getHistory('orders', 'ord-42');
229
252
  ```
230
253
 
231
254
  ### 📊 Materialized views
@@ -234,6 +257,8 @@ Reactive aggregations that update automatically on every write. Declare a view w
234
257
 
235
258
  ```js
236
259
  const env = db.env('default');
260
+ await env.ensureType('orders');
261
+ await env.put('orders', 'o1', { status: 'completed', amount: 120, region: 'EU' });
237
262
 
238
263
  await env.views.create('orderStats', {
239
264
  type: 'orders',
@@ -271,10 +296,15 @@ Multi-mode security layer built into the HTTP API. No separate auth service need
271
296
  ## Installation
272
297
 
273
298
  ```bash
274
- npm install okdb
299
+ npm install @kedem/okdb
275
300
  ```
276
301
 
277
- > **Runtime:** Node.js only. Requires a native LMDB build (handled automatically by the `lmdb` package via node-gyp).
302
+ > **Runtime:** Node.js 18 or newer on **Linux x64 with glibc 2.28+**. The native core ships inside the package (no compiler,
303
+ > no install scripts, no separate platform package). npm refuses to install it on other platforms; on a host it slips through
304
+ > (musl/Alpine, a forced install) `require('@kedem/okdb')` throws `NATIVE_UNAVAILABLE`. Those platforms can stay on okdb 2.x.
305
+ >
306
+ > The same native file also serves programs written in other languages through a stable C interface: see
307
+ > [C bridge](docs/c-bridge.md).
278
308
 
279
309
  ---
280
310
 
@@ -325,15 +355,17 @@ main().catch(console.error);
325
355
  | [Full-Text Search](docs/fts.md) | Registering FTS indexes, tokenizer config, search |
326
356
  | [Embeddings](docs/embeddings.md) | Vector pipeline, embedders, HNSW search |
327
357
  | [Sync](docs/sync.md) | Cluster setup, joining peers, conflict resolution |
328
- | [Queue](docs/queue.md) | Durable job queue, workers, retry |
358
+ | [Queue](docs/queue.md) | Durable job queue, consumers, retry |
329
359
  | [Files](docs/files.md) | Blob storage, upload, download, sync |
330
360
  | [Custom Functions](docs/functions.md) | Stored sandboxed JS functions, env/global execution, HTTP routes |
331
361
  | [Pipelines](docs/pipelines.md) | Composable data-flow orchestration with queue and processor drivers |
332
362
  | [HTTP API](docs/http-api.md) | REST endpoints, auth, admin UI |
333
363
  | [Auth](docs/auth-permissions.md) | Token, OIDC, IP allowlist authentication |
334
364
  | [Plugins](docs/plugins.md) | Extending OKDB with custom features |
335
- | [Migration](docs/migration.md) | Schema evolution, data migration |
336
- | [Architecture](OKDB-ARCHITECTURE.md) | Deep-dive technical reference |
365
+ | [Migration](docs/migration.md) | Export, import, backup, restore |
366
+ | [Licensing](docs/licensing.md) | Free tier, license files, limits |
367
+ | [Upgrading to 3.0](docs/upgrade-3.0.md) | What changes when you move from okdb 2.x |
368
+ | [C bridge](docs/c-bridge.md) | Using the native core from C, Rust, Go, ... without Node |
337
369
 
338
370
  ---
339
371
 
package/bin/okdb CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';const _0x43ed0a=_0x534d;(function(_0x386ae9,_0x58d115){const _0x100047=_0x534d,_0x55f4b7=_0x386ae9();while(!![]){try{const _0x35076d=-parseInt(_0x100047(0x9d))/0x1*(parseInt(_0x100047(0xc1))/0x2)+-parseInt(_0x100047(0xb7))/0x3+-parseInt(_0x100047(0xcb))/0x4*(-parseInt(_0x100047(0xa9))/0x5)+parseInt(_0x100047(0xc6))/0x6*(parseInt(_0x100047(0xae))/0x7)+parseInt(_0x100047(0x9f))/0x8+parseInt(_0x100047(0xc8))/0x9*(-parseInt(_0x100047(0xbe))/0xa)+parseInt(_0x100047(0xb1))/0xb;if(_0x35076d===_0x58d115)break;else _0x55f4b7['push'](_0x55f4b7['shift']());}catch(_0x1fc31b){_0x55f4b7['push'](_0x55f4b7['shift']());}}}(_0xb8f6,0xa45ed));const path=require('node:path'),fs=require(_0x43ed0a(0xbc)),root=path[_0x43ed0a(0xa6)](__dirname,'..'),which=process[_0x43ed0a(0xb5)][0x2]==='--okdb-which';function die(_0x1f4b66){const _0x35c563=_0x43ed0a;console[_0x35c563(0xc4)](_0x35c563(0xc3)+_0x1f4b66+_0x35c563(0xaf)+_0x35c563(0xbf)),process['exit'](0x1);}function _0x534d(_0x488a1a,_0x251dbc){_0x488a1a=_0x488a1a-0x99;const _0xb8f67a=_0xb8f6();let _0x534de9=_0xb8f67a[_0x488a1a];return _0x534de9;}function resolveLauncher(){const _0xe050ed=_0x43ed0a;if(process.env.OKDB_SHIM_ACTIVE==='1')return{'reason':_0xe050ed(0xac)};let _0x5d3e53;try{_0x5d3e53=require(path[_0xe050ed(0xbd)](root,_0xe050ed(0xbb)));}catch(_0x419089){return{'reason':_0x419089[_0xe050ed(0x9c)]};}const _0x592b05=_0x5d3e53[_0xe050ed(0xa5)](_0xe050ed(0xa1));if(!_0x592b05['path'])return{'reason':_0x592b05[_0xe050ed(0xaa)]};try{if(fs[_0xe050ed(0xc5)](_0x592b05[_0xe050ed(0xa2)])===fs['realpathSync'](__filename))return{'reason':_0x592b05[_0xe050ed(0xa2)]+_0xe050ed(0xb6)};if(fs[_0xe050ed(0xba)](_0x592b05[_0xe050ed(0xa2)])['subarray'](0x0,0x2)[_0xe050ed(0x9b)]()==='#!')return{'reason':_0x592b05[_0xe050ed(0xa2)]+_0xe050ed(0xb3)};}catch(_0x3c513c){return{'reason':_0x3c513c[_0xe050ed(0x9c)]};}const _0x42b638=_0x5d3e53[_0xe050ed(0xa5)](_0xe050ed(0xca));return{'loc':_0x592b05,'addon':_0x42b638[_0xe050ed(0xa2)]};}const {loc,addon,reason}=resolveLauncher();if(!loc)die(reason);which&&(console[_0x43ed0a(0xc2)]('native\x20'+loc[_0x43ed0a(0xa2)]+'\x20('+loc[_0x43ed0a(0xa4)]+',\x20'+loc[_0x43ed0a(0x99)]+')'+(addon?_0x43ed0a(0xab)+addon:'')),process[_0x43ed0a(0x9e)](0x0));function _0xb8f6(){const _0x2d751b=['reason','\x20addon\x20','nested\x20shim\x20(OKDB_SHIM_ACTIVE)','spawn','238rlvsdM','.\x20okdb\x203.x\x20bundles\x20the\x20CLI\x20under\x20native/<platform>/okdb\x20(3.0:\x20Linux\x20x64\x20glibc\x20','OKDB_BRIDGE_LIB','12936946sTZMAu','public','\x20is\x20a\x20script,\x20not\x20a\x20native\x20binary','kill','argv','\x20resolves\x20to\x20the\x20shim\x20itself','3911496LrzBxX','OKDB_ADMIN_PUBLIC_DIR','SIGHUP','readFileSync','native-loader.js','node:fs','join','10KrKtMf','only);\x20reinstall\x20@kedem/okdb,\x20or\x20set\x20OKDB_NATIVE_CLI\x20to\x20the\x20launcher\x20binary.','slice','8yPHkuN','log','okdb:\x20no\x20native\x20CLI\x20launcher:\x20','error','realpathSync','215802ihsUim','SIGQUIT','3117951viJaya','SIGTERM','addon','62324uZTUTY','source','inherit','toString','message','304457uWQtyO','exit','7768040CQiZIP','pid','launcher','path','SIGINT','key','locate','resolve','cannot\x20run\x20','node:child_process','55MedrJv'];_0xb8f6=function(){return _0x2d751b;};return _0xb8f6();}const env={...process.env,'OKDB_SHIM_ACTIVE':'1'};if(addon&&!env['OKDB_BRIDGE_LIB'])env[_0x43ed0a(0xb0)]=addon;for(const [k,rel]of[[_0x43ed0a(0xb8),_0x43ed0a(0xb2)],['OKDB_DOCS_DIR','docs']]){const p=path['join'](root,rel);if(!env[k]&&fs['existsSync'](p))env[k]=p;}const SIGS=[_0x43ed0a(0xa3),_0x43ed0a(0xc9),_0x43ed0a(0xb9),_0x43ed0a(0xc7)],child=require(_0x43ed0a(0xa8))[_0x43ed0a(0xad)](loc[_0x43ed0a(0xa2)],process['argv'][_0x43ed0a(0xc0)](0x2),{'stdio':_0x43ed0a(0x9a),'env':env}),relay=_0x593b5e=>()=>{try{child['kill'](_0x593b5e);}catch{}};for(const sig of SIGS)process['on'](sig,relay(sig));child['on'](_0x43ed0a(0xc4),_0x3ac40d=>die(_0x43ed0a(0xa7)+loc[_0x43ed0a(0xa2)]+':\x20'+_0x3ac40d['message'])),child['on'](_0x43ed0a(0x9e),(_0x17eb18,_0x20e873)=>{const _0x48d588=_0x43ed0a;if(_0x20e873){for(const _0x363ca2 of SIGS)process['removeAllListeners'](_0x363ca2);process[_0x48d588(0xb4)](process[_0x48d588(0xa0)],_0x20e873),setTimeout(()=>process[_0x48d588(0x9e)](0x80),0x64);}else process[_0x48d588(0x9e)](_0x17eb18??0x0);});
2
+ 'use strict';const _0x2bac0e=_0x5c94;(function(_0x3b39f8,_0x1427b2){const _0x409fa8=_0x5c94,_0x3faa15=_0x3b39f8();while(!![]){try{const _0x55ea75=parseInt(_0x409fa8(0xe1))/0x1*(-parseInt(_0x409fa8(0xfb))/0x2)+parseInt(_0x409fa8(0xf9))/0x3*(-parseInt(_0x409fa8(0xe5))/0x4)+parseInt(_0x409fa8(0xcc))/0x5*(parseInt(_0x409fa8(0xde))/0x6)+parseInt(_0x409fa8(0xf3))/0x7+parseInt(_0x409fa8(0xd3))/0x8*(parseInt(_0x409fa8(0xda))/0x9)+parseInt(_0x409fa8(0xf1))/0xa*(parseInt(_0x409fa8(0xeb))/0xb)+parseInt(_0x409fa8(0xd2))/0xc;if(_0x55ea75===_0x1427b2)break;else _0x3faa15['push'](_0x3faa15['shift']());}catch(_0x4809bb){_0x3faa15['push'](_0x3faa15['shift']());}}}(_0x3ab7,0xbcdd2));function _0x3ab7(){const _0x47d658=['5985960bPYrkT','136smrPic','reason','native-loader.js','realpathSync','exit','toString','slice','387045vsFYgO','node:path','log','okdb:\x20no\x20native\x20CLI\x20launcher:\x20','174zCnfaP','message','node:fs','219WNrFvC','path','docs','SIGTERM','2075224vUOTgx','nested\x20shim\x20(OKDB_SHIM_ACTIVE)','source','only);\x20reinstall\x20@kedem/okdb,\x20or\x20set\x20OKDB_NATIVE_CLI\x20to\x20the\x20launcher\x20binary.','removeAllListeners','inherit','1166561sxrKti','addon','key','OKDB_BRIDGE_LIB','pid','kill','50fJsnZD','error','172039dBKKce','\x20resolves\x20to\x20the\x20shim\x20itself','readFileSync','\x20addon\x20','SIGINT','join','6VIGeGc','.\x20okdb\x203.x\x20bundles\x20the\x20CLI\x20under\x20native/<platform>/okdb\x20(3.0:\x20Linux\x20x64\x20glibc\x20','866icWhsf','20910XQhdvR','native\x20','--okdb-which','resolve','node:child_process','argv'];_0x3ab7=function(){return _0x47d658;};return _0x3ab7();}function _0x5c94(_0x10a57b,_0x4fe5bc){_0x10a57b=_0x10a57b-0xcc;const _0x3ab739=_0x3ab7();let _0x5c94c5=_0x3ab739[_0x10a57b];return _0x5c94c5;}const path=require(_0x2bac0e(0xdb)),fs=require(_0x2bac0e(0xe0)),root=path[_0x2bac0e(0xcf)](__dirname,'..'),which=process[_0x2bac0e(0xd1)][0x2]===_0x2bac0e(0xce);function die(_0x3ff310){const _0x1810ab=_0x2bac0e;console[_0x1810ab(0xf2)](_0x1810ab(0xdd)+_0x3ff310+_0x1810ab(0xfa)+_0x1810ab(0xe8)),process['exit'](0x1);}function resolveLauncher(){const _0x4ee90e=_0x2bac0e;if(process.env.OKDB_SHIM_ACTIVE==='1')return{'reason':_0x4ee90e(0xe6)};let _0x1ab100;try{_0x1ab100=require(path[_0x4ee90e(0xf8)](root,_0x4ee90e(0xd5)));}catch(_0x346e9a){return{'reason':_0x346e9a[_0x4ee90e(0xdf)]};}const _0x3b0c06=_0x1ab100['locate']('launcher');if(!_0x3b0c06[_0x4ee90e(0xe2)])return{'reason':_0x3b0c06[_0x4ee90e(0xd4)]};try{if(fs[_0x4ee90e(0xd6)](_0x3b0c06[_0x4ee90e(0xe2)])===fs['realpathSync'](__filename))return{'reason':_0x3b0c06[_0x4ee90e(0xe2)]+_0x4ee90e(0xf4)};if(fs[_0x4ee90e(0xf5)](_0x3b0c06[_0x4ee90e(0xe2)])['subarray'](0x0,0x2)[_0x4ee90e(0xd8)]()==='#!')return{'reason':_0x3b0c06[_0x4ee90e(0xe2)]+'\x20is\x20a\x20script,\x20not\x20a\x20native\x20binary'};}catch(_0x3b3ffb){return{'reason':_0x3b3ffb[_0x4ee90e(0xdf)]};}const _0x3c214a=_0x1ab100['locate'](_0x4ee90e(0xec));return{'loc':_0x3b0c06,'addon':_0x3c214a[_0x4ee90e(0xe2)]};}const {loc,addon,reason}=resolveLauncher();if(!loc)die(reason);which&&(console[_0x2bac0e(0xdc)](_0x2bac0e(0xcd)+loc[_0x2bac0e(0xe2)]+'\x20('+loc[_0x2bac0e(0xed)]+',\x20'+loc[_0x2bac0e(0xe7)]+')'+(addon?_0x2bac0e(0xf6)+addon:'')),process[_0x2bac0e(0xd7)](0x0));const env={...process.env,'OKDB_SHIM_ACTIVE':'1'};if(addon&&!env['OKDB_BRIDGE_LIB'])env[_0x2bac0e(0xee)]=addon;for(const [k,rel]of[['OKDB_ADMIN_PUBLIC_DIR','public'],['OKDB_DOCS_DIR',_0x2bac0e(0xe3)]]){const p=path[_0x2bac0e(0xf8)](root,rel);if(!env[k]&&fs['existsSync'](p))env[k]=p;}const SIGS=[_0x2bac0e(0xf7),_0x2bac0e(0xe4),'SIGHUP','SIGQUIT'],child=require(_0x2bac0e(0xd0))['spawn'](loc['path'],process[_0x2bac0e(0xd1)][_0x2bac0e(0xd9)](0x2),{'stdio':_0x2bac0e(0xea),'env':env}),relay=_0x1d0e03=>()=>{try{child['kill'](_0x1d0e03);}catch{}};for(const sig of SIGS)process['on'](sig,relay(sig));child['on'](_0x2bac0e(0xf2),_0x34ba37=>die('cannot\x20run\x20'+loc[_0x2bac0e(0xe2)]+':\x20'+_0x34ba37[_0x2bac0e(0xdf)])),child['on'](_0x2bac0e(0xd7),(_0x128e73,_0x4227d9)=>{const _0x2959e7=_0x2bac0e;if(_0x4227d9){for(const _0x51b432 of SIGS)process[_0x2959e7(0xe9)](_0x51b432);process[_0x2959e7(0xf0)](process[_0x2959e7(0xef)],_0x4227d9),setTimeout(()=>process[_0x2959e7(0xd7)](0x80),0x64);}else process[_0x2959e7(0xd7)](_0x128e73??0x0);});
@@ -20,7 +20,7 @@ an optional `name` + `password` (for login), a raw bearer value, `permissions` a
20
20
 
21
21
  Every request goes through `db.auth.authenticateRequest(req)`:
22
22
 
23
- ```
23
+ ```text
24
24
  1. Bootstrap window ~tokens empty and not open mode → localhost gets full access, others refused
25
25
  2. Open mode client IP matches auth.open → full access, no credentials
26
26
  3. Bearer token Authorization: Bearer <token> → see "Bearer verification" below
@@ -43,7 +43,7 @@ const okdb = new OKDB('./data', {
43
43
  });
44
44
  ```
45
45
 
46
- `bin/okdb` passes the `auth` block of `.kdbconfig` through unchanged; `--open` overrides
46
+ The `okdb` CLI passes the `auth` block of `.kdbconfig` through unchanged; `--open` overrides
47
47
  `auth.open`. `auth.token.secret` is only used the first time: the secret is persisted in the store
48
48
  as `__tokenSecret` (local, never replicated) and reused from then on, generated if unset.
49
49
 
@@ -63,7 +63,7 @@ Anything else is rejected; an invalid bearer never falls back to the cookie.
63
63
 
64
64
  ### Login
65
65
 
66
- ```
66
+ ```http
67
67
  POST /auth/login
68
68
  { "username": "admin", "password": "s3cret" }
69
69
  ```
@@ -86,28 +86,32 @@ OAuth only obtains a session: it creates no users and stores nothing. Configure
86
86
  under `auth.providers` (only the first entry is used):
87
87
 
88
88
  ```js
89
- auth: {
90
- providers: {
91
- google: {
92
- issuer: 'https://accounts.google.com', // enables OIDC bearer validation
93
- clientId: 'YOUR_CLIENT_ID',
94
- redirectUri: 'http://localhost:8484/admin/auth/callback',
95
- scopes: ['openid', 'email', 'profile'],
96
-
97
- allowedDomains: ['mycompany.com'], // required: allowedDomains and/or allowedEmails
98
- allowedEmails: ['contractor@gmail.com'],
99
- defaultRoles: ['admin'], // default ['admin']
100
-
101
- getAuthorizationUrl: ({ state, codeChallenge, redirectUri, scopes }) => '...',
102
- exchangeCode: async ({ code, state, redirectUri }) => {
103
- // return { subject, email, claims }
89
+ const okdb = new OKDB('./data', {
90
+ auth: {
91
+ providers: {
92
+ google: {
93
+ issuer: 'https://accounts.google.com', // enables OIDC bearer validation
94
+ clientId: 'YOUR_CLIENT_ID',
95
+ redirectUri: 'http://localhost:8484/admin/auth/callback',
96
+ scopes: ['openid', 'email', 'profile'],
97
+
98
+ allowedDomains: ['mycompany.com'], // required: allowedDomains and/or allowedEmails
99
+ allowedEmails: ['contractor@gmail.com'],
100
+ defaultRoles: ['admin'], // default ['admin']
101
+
102
+ getAuthorizationUrl: ({ state, codeChallenge, redirectUri, scopes }) =>
103
+ `https://accounts.google.com/o/oauth2/v2/auth?state=${state}&code_challenge=${codeChallenge}`,
104
+ exchangeCode: async ({ code, state, redirectUri }) => {
105
+ // call the provider's token endpoint, then:
106
+ return { subject: 'user-1', email: 'me@mycompany.com', claims: {} };
107
+ },
104
108
  },
105
109
  },
106
110
  },
107
- }
111
+ });
108
112
  ```
109
113
 
110
- ```
114
+ ```text
111
115
  GET /admin/auth/start?redirect=/admin/index.html → redirect to the provider (PKCE)
112
116
  GET /admin/auth/callback?code=...&state=... → exchangeCode → email allowlist check
113
117
  allowed → HMAC session token in okdb_session, redirect
@@ -138,7 +142,7 @@ GET /admin/auth/callback?code=...&state=... → exchangeCode → email al
138
142
 
139
143
  Pull-based, last-write-wins replication over HTTP; no coordinator, no consensus.
140
144
 
141
- ```
145
+ ```text
142
146
  1. A write advances the env's HLC clock and logs a change entry
143
147
  2. Peers are poked; each pulls a delta (POST /api/sync/delta) from the changed node
144
148
  3. Changes are compared by HLC — the higher wins; ties broken by origin node id
@@ -192,6 +196,8 @@ okdb join http://node-a:8484 --token <raw-token> --address http://node-b:8484
192
196
 
193
197
  In code:
194
198
 
199
+ <!-- not-runnable: needs a license (sync) and a peer -->
200
+
195
201
  ```js
196
202
  const okdb = new OKDB('./node-b', { sync: { address: 'http://node-b:8484' } });
197
203
  await okdb.open();
@@ -202,7 +208,7 @@ await okdb.sync.join('http://node-a:8484', { token: process.env.OKDB_JOIN_TOKEN
202
208
  Over HTTP (the admin UI's **System → Sync → Connect** does this), on node B with a credential
203
209
  for B that has `sync:peer`:
204
210
 
205
- ```
211
+ ```http
206
212
  POST /api/sync/connect
207
213
  { "address": "http://node-a:8484", "token": "<raw-token-on-A>" }
208
214
  ```
@@ -212,8 +218,8 @@ link. If B has no `sync.address`, it is taken from `my_address` in the body or t
212
218
  `Host` header.
213
219
 
214
220
  `join()` fetches `/api/sync/info` from A, stores A in `~sync_nodes`, creates a data link, POSTs to
215
- A's `/api/sync/join` (where A enforces its `sync` license and peer limit — the joiner needs no
216
- license of its own), and pulls an initial delta.
221
+ A's `/api/sync/join`, and pulls an initial delta. Sync is a licensed feature (off on the free
222
+ tier) — see [Licensing](./licensing.md).
217
223
 
218
224
  ### Sync options
219
225
 
@@ -177,8 +177,9 @@ is only applied on routes that resolve their env from the path (see the note abo
177
177
 
178
178
  `join()` first reads `GET /api/sync/info` (`sync:read`); `sync:peer` alone does not imply it.
179
179
 
180
- ## Adding a new permission
180
+ ## Permissions on your own routes
181
181
 
182
- 1. Add the namespace/operation to `src/features/auth/okdb-auth-namespaces.js` in `NAMESPACES`.
183
- 2. Add `permission: 'ns:op'` to the route's `access` object.
184
- 3. The catalog endpoint at `GET /admin/api/auth/permissions` picks it up automatically — no UI changes needed.
182
+ The permission catalog is fixed (it is what `GET /admin/api/auth/permissions` returns, and what
183
+ the admin token editor offers). A route you add with `okdb.http.add()` declares one of these
184
+ permissions in its metadata — `access: { permission: 'data:read' }` — and the auth guard enforces
185
+ it like on a built-in route. There is no API to add a namespace.
@@ -0,0 +1,94 @@
1
+ # C bridge
2
+
3
+ The native file in `@kedem/okdb` (`native/linux-x64-gnu/okdb-node.linux-x64-gnu.node`) is one binary with two front doors:
4
+
5
+ - **Node.js** loads it as an addon (Node-API) — that is what `require('@kedem/okdb')` does;
6
+ - **any other program** (C, C++, Rust, Go, Zig, ...) can `dlopen()` it and talk to okdb through a stable C ABI, without compiling
7
+ okdb in and without Node. An editor or agent process such as okcode uses okdb this way.
8
+
9
+ The contract is the header `okdb_bridge.h`, attached to each okdb release on GitHub next to the native file. This page is an
10
+ overview; the header is the reference.
11
+
12
+ ## Loading
13
+
14
+ ```c
15
+ #include <dlfcn.h>
16
+ #include "okdb_bridge.h"
17
+
18
+ void *so = dlopen("/path/to/okdb-node.linux-x64-gnu.node", RTLD_NOW | RTLD_LOCAL);
19
+ okdb_bridge_fn get = (okdb_bridge_fn)dlsym(so, "okdb_bridge");
20
+ const OkdbBridgeV1 *ok = get ? get(OKDB_BRIDGE_ABI_MAJOR) : NULL; /* NULL: this file does not speak ABI 1 */
21
+ ```
22
+
23
+ The file has no undefined Node-API symbols, so it loads into a plain process. `okdb_bridge(1)` returns the function table
24
+ `OkdbBridgeV1`: `version`, `open`, `attach`, `close`, `dispatch`, `dispatch_batch`, `submit`, `free`, `set_host`, `pump`,
25
+ `cli_main`, and, in later minors, `submit_batch` (1.1) and `read` (1.2).
26
+
27
+ ## Requests
28
+
29
+ Every call carries MessagePack. A request is `[scope, env | nil, method, args]` — the same scopes and methods the JavaScript
30
+ binding uses (`["env", "default", "put", ["docs", "k1", {"body": "hi"}]]`, `["env", "default", "get", ["docs", "k1"]]`). A reply
31
+ is `{"ok": value}` or `{"err": {"code", "message", "details"?}}`, with the same error codes the JavaScript API throws; the return
32
+ status (`OKDB_OK`, `OKDB_ERR`, `OKDB_INVALID`, `OKDB_WRONG_THREAD`, `OKDB_CLOSED`, `OKDB_PANIC`, `OKDB_UNSUPPORTED`) is the coarse
33
+ class. Every buffer okdb returns is released with `free(ptr, len)`. `dispatch_batch` runs an array of requests as one write group.
34
+
35
+ ## Open or attach
36
+
37
+ - **`open(path, opts, flags, &h, ...)`** opens a standalone instance (options as in `new OKDB(path, opts)`). Without flags the
38
+ calling thread is the owner and must call **`pump(h, budget_ms, &next_ms)`** from its loop: it runs processor drains, timers,
39
+ lease heartbeats and queued submits, and says when to call again. `OKDB_OPEN_OWNER_THREAD` makes okdb run its own owner thread
40
+ (no pump needed; `dispatch` from other threads is forwarded). `OKDB_OPEN_DEFER` constructs without opening, so callbacks can be
41
+ registered first; then send `["bridge", nil, "open", []]`.
42
+ - **`attach(native_handle, &h, ...)`** joins an instance a Node.js host in the same process already opened, instead of opening the
43
+ store a second time. Call it on that instance's JavaScript thread; `close()` only detaches. From Node, the host finds the same
44
+ image with `require('@kedem/okdb').nativeBinaryPath` (dlopen it with `RTLD_NOLOAD`), and the handle with
45
+ `db._native.bridgeHandle()` (`db._native.bridgeTable()` is the table's address, `db._native.bridgeLibPath()` the image path).
46
+
47
+ ```js
48
+ // in the Node host, before handing the instance to native code in the same process
49
+ const OKDB = require('@kedem/okdb');
50
+ const db = new OKDB('./mydb');
51
+ await db.open();
52
+
53
+ const image = OKDB.nativeBinaryPath; // dlopen(image, RTLD_NOW | RTLD_NOLOAD)
54
+ const handle = db._native.bridgeHandle(); // pass to table->attach() on this thread
55
+ console.log(image, handle);
56
+ await db.close();
57
+ ```
58
+
59
+ ## Threads
60
+
61
+ An okdb instance is single-threaded: everything runs on its owner thread. `dispatch` / `dispatch_batch` from another thread
62
+ fail with `OKDB_WRONG_THREAD` (except on owner-thread handles, which forward and block). Two calls work from **any** thread:
63
+
64
+ - **`submit` / `submit_batch`** queue a request; its `done(ctx, status, reply, len)` callback runs later on the owner thread.
65
+ - **`read`** (ABI 1.2) runs a read-only request on the **calling** thread, with no hop to the owner and no pump: the env read
66
+ methods (`get`, `getEntry`, `has`, `count`, `getMany`, `getRange`, `getKeys`, `getValues`, `getCount`, `getByPrefix`,
67
+ `getIndex`, `byIndex`, `countByIndex`) against committed data. Anything else answers `READ_METHOD_NOT_ALLOWED`. This is how a
68
+ worker thread reads without blocking the owner.
69
+
70
+ ## Host callbacks
71
+
72
+ Features that call user code — chunk strategies, embedder factories and embedders, queue and processor handlers, event
73
+ subscriptions — take functions in JavaScript. Over the bridge a function is the marker `{"$fn": <id>}` with an id the host picks;
74
+ `set_host(h, &host)` installs the host's `OkdbBridgeHostV1` vtable (`call`, `release`, `free_reply`, `drop`), and okdb calls
75
+ `host.call(ctx, op, args)` on the owner thread when it needs the function.
76
+
77
+ ## The CLI
78
+
79
+ `cli_main(argc, argv)` (also exported as `okdb_cli_main`) runs the `okdb` command line inside the calling process. The `okdb`
80
+ launcher shipped in the package is a small program that does exactly that.
81
+
82
+ ## ABI versions
83
+
84
+ The ABI is **major 1, minor 2**. Within a major, the function table, the host vtable and the message shapes only grow: fields are
85
+ appended, never removed or reordered. Before using a field added in a later minor, check the table's `struct_size`:
86
+
87
+ ```c
88
+ #include <stddef.h>
89
+ int has_read = ok->struct_size >= offsetof(OkdbBridgeV1, read) + sizeof ok->read; /* ABI 1.2 */
90
+ ```
91
+
92
+ okdb reads `host->struct_size` the same way. A breaking change would be a new major (`OkdbBridgeV2`), and `okdb_bridge(1)` keeps
93
+ answering as long as major 1 is supported. `version()` returns the okdb package version, for features newer than the ABI minor
94
+ (new methods).