@kedem/okdb 2.3.5 → 2.4.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 (59) hide show
  1. package/CHANGELOG.md +349 -0
  2. package/algorithm-worker-thread.js +1 -1
  3. package/bin/okdb.js +1 -1
  4. package/docs/auth-and-sync.md +28 -4
  5. package/docs/auth-permissions.md +19 -6
  6. package/docs/change-log.md +79 -59
  7. package/docs/data-model.md +20 -18
  8. package/docs/deployment.md +25 -0
  9. package/docs/diagnostics.md +59 -17
  10. package/docs/embeddings.md +57 -6
  11. package/docs/fts.md +50 -5
  12. package/docs/functions.md +21 -8
  13. package/docs/http-api.md +139 -98
  14. package/docs/http-cluster.md +30 -8
  15. package/docs/indexes.md +5 -4
  16. package/docs/logging.md +18 -0
  17. package/docs/migration.md +94 -2
  18. package/docs/pipelines.md +6 -1
  19. package/docs/plugins.md +12 -18
  20. package/docs/process-registry.md +50 -39
  21. package/docs/processors.md +40 -22
  22. package/docs/querying.md +50 -36
  23. package/docs/queue.md +110 -14
  24. package/docs/subscriptions.md +35 -24
  25. package/docs/sync.md +96 -37
  26. package/docs/time-machine.md +23 -17
  27. package/docs/transactions.md +11 -19
  28. package/docs/ttl.md +118 -67
  29. package/docs/upgrade-2.0.md +2 -2
  30. package/docs/views.md +71 -52
  31. package/okdb-functions-sandbox-worker.js +1 -1
  32. package/okdb-http-worker-child.js +1 -1
  33. package/okdb-views-bootstrap-worker.js +1 -1
  34. package/okdb.js +1 -1
  35. package/package.json +1 -1
  36. package/public/sections/db/parts/type-viewer.ok.js +1 -1
  37. package/public/sections/embeddings/parts/engines-overview.ok.js +1 -1
  38. package/public/sections/queue/parts/queue-jobs.ok.js +1 -1
  39. package/public/sections/system/modals/data-ops-modal.ok.js +1 -1
  40. package/types/environment.d.ts +320 -52
  41. package/types/features/admin.d.ts +8 -2
  42. package/types/features/api.d.ts +10 -16
  43. package/types/features/auth.d.ts +135 -16
  44. package/types/features/embeddings.d.ts +639 -31
  45. package/types/features/engines.d.ts +368 -14
  46. package/types/features/files.d.ts +0 -3
  47. package/types/features/fts.d.ts +98 -26
  48. package/types/features/functions.d.ts +175 -15
  49. package/types/features/mcp.d.ts +23 -10
  50. package/types/features/pipelines.d.ts +268 -9
  51. package/types/features/queue.d.ts +230 -34
  52. package/types/features/sync.d.ts +177 -14
  53. package/types/features/time-machine.d.ts +117 -16
  54. package/types/features/views.d.ts +230 -39
  55. package/types/index.d.ts +357 -254
  56. package/types/okdb.d.ts +377 -0
  57. package/types/options.d.ts +309 -48
  58. package/public/test-cron-input.html +0 -60
  59. package/public/test-json-input.html +0 -280
@@ -0,0 +1,377 @@
1
+ import type { EventEmitter } from 'events';
2
+ import type { Server, IncomingMessage, ServerResponse } from 'http';
3
+ import type {
4
+ OKDBOptions,
5
+ OKDBEnvironmentConfig,
6
+ OKDBPrimaryKey,
7
+ OKDBIndexKey,
8
+ OKDBIndexSpec,
9
+ OKDBFilter,
10
+ OKDBRangeOptions,
11
+ OKDBQueryOptions,
12
+ OKDBHybridQueryOptions,
13
+ OKDBIndexRangeOptions,
14
+ OKDBGeoQueryOptions,
15
+ OKDBFtsQueryOptions,
16
+ OKDBWriteOptions,
17
+ OKDBRemoveOptions,
18
+ OKDBTransactionOptions,
19
+ OKDBEntry,
20
+ OKDBIndexEntry,
21
+ OKDBQueryEntry,
22
+ OKDBChangeEntry,
23
+ OKDBRangeIterable,
24
+ OKDBIndexDefinition,
25
+ OKDBRegisterIndexOptions,
26
+ OKDBEnsureDefinition,
27
+ OKDBTypeSchema,
28
+ OKDBRemoveEnvironmentResult,
29
+ OKDBTtlListOptions,
30
+ OKDBTtlInfo,
31
+ OKDBTtlListResult,
32
+ OKDBTtlStats,
33
+ OKDBTtlSweepResult,
34
+ OKDBResolvedOptions,
35
+ OKDBRoleFlags,
36
+ OKDBInfoResult,
37
+ } from './options';
38
+ import type {
39
+ OKDBEnvironment,
40
+ OKDBEnvProcessor,
41
+ OKDBProcessorStatus,
42
+ OKDBTransaction,
43
+ OKDBTransactionFacade,
44
+ OKDBTransactionOp,
45
+ OKDBTxnResult,
46
+ } from './environment';
47
+ import type { OKDBQueue } from './features/queue';
48
+ import type { OKDBFiles } from './features/files';
49
+ import type { OKDBSync } from './features/sync';
50
+ import type { OKDBAuth } from './features/auth';
51
+ import type { OKDBEmbeddings } from './features/embeddings';
52
+ import type { OKDBFts, OKDBFtsSearchResult } from './features/fts';
53
+ import type { OKDBEngines } from './features/engines';
54
+ import type { OKDBFunctions } from './features/functions';
55
+ import type { OKDBPipelines } from './features/pipelines';
56
+ import type { OKDBMcp } from './features/mcp';
57
+ import type { OKDBAdmin } from './features/admin';
58
+ import type { OKDBApi } from './features/api';
59
+ import type { OKDBLicenses } from './features/licenses';
60
+
61
+ // ── HTTP ──────────────────────────────────────────────────────────────────────
62
+
63
+ /** Request object seen by middleware, guards and route handlers. */
64
+ export interface OKDBHttpRequest {
65
+ method: string;
66
+ path: string;
67
+ headers: Record<string, string | string[] | undefined>;
68
+ body: unknown;
69
+ query: Record<string, unknown>;
70
+ params?: Record<string, string | undefined>;
71
+ cookies?: Record<string, string>;
72
+ context: Record<string, unknown>;
73
+ [key: string]: unknown;
74
+ }
75
+
76
+ /** A normalized response (`handle()` resolves to one). JSON bodies use the
77
+ * `{ data, error, meta }` envelope. */
78
+ export interface OKDBHttpResponse {
79
+ status: number;
80
+ headers: Record<string, string>;
81
+ body: unknown;
82
+ }
83
+
84
+ /** Route handler input: `{ params, query, headers, body, context, … }`. Return
85
+ * `{ result }`, `{ status, body, headers }`, a stream/buffer/string, or nothing. */
86
+ export type OKDBHttpRouteHandler = (req: OKDBHttpRequest & Record<string, any>) => unknown;
87
+
88
+ export interface OKDBHttp {
89
+ /**
90
+ * Start the built-in HTTP server (REST API + admin UI). Single-process only — a
91
+ * `{ workers }` option throws HTTP_CLUSTER_REMOVED (use `bin/okdb` or Node `cluster`).
92
+ * `host` binds one address (default: all interfaces); an array binds each address with its
93
+ * own server sharing one request handler. Returns the Node `http.Server` — for an array, the
94
+ * one bound to the first address (all of them are on `servers`; an 'error' from any is
95
+ * re-emitted on the returned one; `close()` closes them all). A string / array second
96
+ * argument is shorthand for `{ host }`.
97
+ */
98
+ listen(port: number, opts?: string | string[] | { host?: string | string[] }): Server;
99
+ /** Stop every server started by listen(). */
100
+ close(options?: Record<string, unknown>): Promise<void>;
101
+ /** The server returned by the last listen(), or null. */
102
+ readonly server: Server | null;
103
+ /** Every server the last listen() started (one per bound host). */
104
+ readonly servers: Server[];
105
+ /** Max JSON request body in bytes (default 5 MB). */
106
+ maxBodyBytes: number;
107
+ /** Add a middleware: `(req, res, next) => …`; call `await next()` to continue. */
108
+ use(fn: (req: OKDBHttpRequest, res: unknown, next: () => Promise<unknown>) => unknown): void;
109
+ /** Add a guard: runs before middleware for matching requests; return false to deny. */
110
+ guard(match: (req: OKDBHttpRequest) => boolean, handler: (req: OKDBHttpRequest, res: unknown) => unknown): void;
111
+ /** Register a route. Path params use `:name`; a trailing `/*` matches a subtree. */
112
+ add(method: string, path: string, handler: OKDBHttpRouteHandler, meta?: Record<string, unknown>): void;
113
+ /** Register a raw-body route (`context.rawStream` carries the unparsed request body). */
114
+ addRaw(method: string, path: string, handler: OKDBHttpRouteHandler, meta?: Record<string, unknown>): void;
115
+ /** Register a Server-Sent Events endpoint. `setup` returns an optional cleanup function. */
116
+ addSSE(
117
+ path: string,
118
+ setup: (conn: {
119
+ send(event: string, data: unknown): void;
120
+ close(): void;
121
+ query: Record<string, unknown>;
122
+ headers: Record<string, unknown>;
123
+ context: { req?: IncomingMessage; res?: ServerResponse; [key: string]: unknown };
124
+ setHeader(name: string, value: string): void;
125
+ }) => unknown,
126
+ meta?: Record<string, unknown>,
127
+ ): void;
128
+ /** Dispatch a request through guards, middleware and routes without a server (bring your own
129
+ * framework). */
130
+ handle(
131
+ method: string,
132
+ path: string,
133
+ request?: {
134
+ body?: unknown;
135
+ query?: Record<string, unknown>;
136
+ headers?: Record<string, unknown>;
137
+ [key: string]: unknown;
138
+ },
139
+ context?: { req?: IncomingMessage; res?: ServerResponse; [key: string]: unknown },
140
+ ): Promise<OKDBHttpResponse>;
141
+ listRoutes(): Array<{ method: string; path: string; meta: Record<string, unknown>; [key: string]: unknown }>;
142
+ }
143
+
144
+ // ── Processors facade ─────────────────────────────────────────────────────────
145
+
146
+ /**
147
+ * `db.processors` — processing participation control + status.
148
+ * Removed: `process()`, `processRest()`, `processEverything()` (throw — use `processors: true`).
149
+ */
150
+ export interface OKDBProcessors {
151
+ /** Begin participating — un-gate lease claiming; the first call also runs the per-store
152
+ * view boot that open() skips on a non-participating node. Resolves true on state change. */
153
+ start(): Promise<boolean>;
154
+ /** Cease participating — finish in-flight quanta, release leases (peers fail over), park
155
+ * registrations. Resolves true on state change. */
156
+ stop(): Promise<boolean>;
157
+ /** Leased (`single`) processors across user envs. */
158
+ status(): { participate: boolean; processors: Array<OKDBProcessorStatus & { env: string }> };
159
+ }
160
+
161
+ export interface OKDBPressure {
162
+ /** Max oldest-pending commit age across open envs (THE stall signal). */
163
+ writerStallMs: number;
164
+ writerDepth: number;
165
+ /** Max durable processor lag (clock units) across user envs. */
166
+ maxDurableLag: number;
167
+ /** Pending + retry jobs across user envs (workload context; not in `score`). */
168
+ queuePending: number;
169
+ loopLagMs: number;
170
+ /** Max of the normalized distress signals: ≥ 1 ≈ at the documented limits. */
171
+ score: number;
172
+ }
173
+
174
+ // ── Main class ────────────────────────────────────────────────────────────────
175
+
176
+ /**
177
+ * The top-level okdb instance. Document operations on `db` delegate to the `default`
178
+ * environment; use `db.env(name)` for others.
179
+ *
180
+ * Removed: `db.workers` (throws WORKERS_REMOVED — run more processes with `processors: true`).
181
+ */
182
+ export declare class OKDB {
183
+ static defaults: OKDBOptions;
184
+ /** Sentinel Buffer for open-ended index range ends: `end: [prefix, OKDB.HIGH_SENTINEL]`. */
185
+ static HIGH_SENTINEL: Buffer;
186
+ /**
187
+ * Register a named custom bucket projection, process-wide. Views reference it by name
188
+ * (`bucket: { field, granularity, project: '<name>' }`) — a function can't be persisted.
189
+ * Call before open() in every process that opens the store; a stored view whose projection
190
+ * is unregistered at open() is held back (getMeta → state 'error') until registered + rebuilt.
191
+ */
192
+ static registerBucketProjection(name: string, fn: (value: unknown) => string | null | undefined): void;
193
+ /**
194
+ * Register a named custom view reducer, process-wide (all envs). Like
195
+ * `env.views.registerReducer`, but callable before open() so a stored view using it is
196
+ * live from boot. Name must start with '$' and not be a built-in or `$ref`.
197
+ */
198
+ static registerViewReducer(name: string, reducer: import('./features/views').OKDBCustomReducer): void;
199
+
200
+ constructor(dbPath: string, options?: OKDBOptions);
201
+
202
+ readonly path: string;
203
+ /** Instance identity (set at open()). */
204
+ readonly id: string;
205
+ readonly options: OKDBOptions;
206
+ readonly events: EventEmitter;
207
+ /** The okdb package version (no env needs to be open). */
208
+ readonly version: string;
209
+ /** Lifecycle state. */
210
+ readonly state: string;
211
+
212
+ // ── Subsystems ────────────────────────────────────────────────────────────
213
+ readonly http: OKDBHttp;
214
+ readonly auth: OKDBAuth;
215
+ readonly log: unknown;
216
+ /** UDP bus (null when the shmbuf native binding is missing). */
217
+ readonly bus: unknown;
218
+ /** null when constructed with `admin: false`. */
219
+ readonly admin: OKDBAdmin | null;
220
+ readonly api: OKDBApi;
221
+ readonly sync: OKDBSync;
222
+ readonly embeddings: OKDBEmbeddings;
223
+ readonly fts: OKDBFts;
224
+ /** Engine orchestrator (per-env engines live on `env.engines`). */
225
+ readonly engines: OKDBEngines;
226
+ /** Read-only pipeline coordinator (create/update on `env.pipelines`). */
227
+ readonly pipelines: OKDBPipelines;
228
+ /** Install / list / inspect licenses from code (after open()). */
229
+ readonly licenses: OKDBLicenses;
230
+ /** Functions registered in `~system` (per-env functions live on `env.functions`). */
231
+ readonly functions: OKDBFunctions;
232
+ readonly mcp: OKDBMcp;
233
+ readonly processors: OKDBProcessors;
234
+ /** Process registry (the `/api/processes` census). */
235
+ readonly processes: unknown;
236
+ readonly meta: unknown;
237
+ readonly migrate: unknown;
238
+ readonly plugins: unknown;
239
+ /** Named cross-process mutexes in `~system`. */
240
+ readonly locks: unknown;
241
+ /** The default env's processor. */
242
+ readonly processor: OKDBEnvProcessor;
243
+
244
+ // ── Queue and files are shortcuts to the default env ──────────────────────
245
+ readonly queue: OKDBQueue;
246
+ readonly files: OKDBFiles;
247
+
248
+ // ── Lifecycle ─────────────────────────────────────────────────────────────
249
+ open(): Promise<void>;
250
+ close(): Promise<void>;
251
+ /** Resolved role flags. `engines`/`compaction` are fixed for the instance's lifetime;
252
+ * `processors` reflects CURRENT participation (see processors.start/stop). */
253
+ readonly role: OKDBRoleFlags;
254
+ /** Composite load signal for this node (cached 250 ms; safe to poll per claim). The
255
+ * standard admission policy is `() => db.pressure().score < 1`. */
256
+ pressure(): OKDBPressure;
257
+ /** OKDB_DIAG snapshot (`{ enabled: false, … }` unless OKDB_DIAG=1). */
258
+ diag(): Record<string, unknown>;
259
+ /** @deprecated Pools were removed; use per-processor pause/resume instead. */
260
+ setProcessingConfig(config: Record<string, unknown>): Promise<void>;
261
+
262
+ // ── Environment management ────────────────────────────────────────────────
263
+ readonly default: OKDBEnvironment;
264
+ /** An already-open env (throws ENV_NOT_FOUND otherwise — use openEnv() for lazy open). */
265
+ env(name?: string): OKDBEnvironment;
266
+ /** Open a registered env on demand (envs always open lazily). Idempotent; throws
267
+ * ENV_NOT_FOUND for an unregistered name. */
268
+ openEnv(name: string): Promise<OKDBEnvironment>;
269
+ /** Create (register + open) an env; idempotent. */
270
+ createEnvironment(name: string, config?: OKDBEnvironmentConfig): Promise<OKDBEnvironment>;
271
+ removeEnvironment(name: string, options?: { keepSubEnvs?: string[] }): Promise<OKDBRemoveEnvironmentResult>;
272
+ /** Envs that failed to open at boot: `{ [name]: { path, error, at } }`. */
273
+ readonly quarantinedEnvs: Record<string, { path: string; error: unknown; at: number }>;
274
+
275
+ // ── Info ──────────────────────────────────────────────────────────────────
276
+ readonly info: OKDBInfoResult;
277
+ getResolvedOptions(): OKDBResolvedOptions;
278
+
279
+ // ── Transactions ──────────────────────────────────────────────────────────
280
+ transaction(options?: OKDBTransactionOptions): OKDBTransaction;
281
+ txn(
282
+ work: ((txn: OKDBTransactionFacade) => unknown) | OKDBTransactionOp[],
283
+ options?: OKDBTransactionOptions,
284
+ ): Promise<OKDBTxnResult>;
285
+
286
+ // ── CRUD (default env) ────────────────────────────────────────────────────
287
+ put(type: string, key: OKDBPrimaryKey, value: unknown, options?: OKDBWriteOptions): Promise<void>;
288
+ update(type: string, key: OKDBPrimaryKey, value: unknown, options?: OKDBWriteOptions): Promise<void>;
289
+ patch(type: string, key: OKDBPrimaryKey, patch: Record<string, unknown>, options?: OKDBWriteOptions): Promise<void>;
290
+ create(type: string, key: OKDBPrimaryKey, value: unknown, options?: OKDBWriteOptions): Promise<void>;
291
+ remove(type: string, key: OKDBPrimaryKey, options?: OKDBRemoveOptions): Promise<void>;
292
+
293
+ // ── Read (synchronous) ────────────────────────────────────────────────────
294
+ get<T = unknown>(type: string, key: OKDBPrimaryKey, options?: Record<string, unknown>): T | undefined;
295
+ getMany<T = unknown>(type: string, keys: OKDBPrimaryKey[], options?: Record<string, unknown>): (T | undefined)[];
296
+ getEntry<T = unknown>(
297
+ type: string,
298
+ key: OKDBPrimaryKey,
299
+ options?: Record<string, unknown>,
300
+ ): OKDBEntry<T> | undefined;
301
+ getRange<T = unknown>(type: string, options?: OKDBRangeOptions): OKDBRangeIterable<OKDBEntry<T>>;
302
+ getValues<T = unknown>(type: string, options?: OKDBRangeOptions): OKDBRangeIterable<T>;
303
+ getKeys(type: string, options?: OKDBRangeOptions): OKDBRangeIterable<OKDBPrimaryKey>;
304
+ getCount(type: string, options?: OKDBRangeOptions): number;
305
+ getByPrefix<T = unknown>(type: string, prefix: string, options?: OKDBRangeOptions): OKDBRangeIterable<OKDBEntry<T>>;
306
+
307
+ // ── Index queries ─────────────────────────────────────────────────────────
308
+ getIndex(type: string, index: string[], options?: OKDBIndexRangeOptions): OKDBRangeIterable<OKDBPrimaryKey>;
309
+ byIndex<T = unknown>(
310
+ type: string,
311
+ index: OKDBIndexSpec,
312
+ options?: OKDBIndexRangeOptions,
313
+ ): OKDBRangeIterable<OKDBIndexEntry<T>>;
314
+ countByIndex(type: string, index: OKDBIndexSpec, options?: OKDBIndexRangeOptions): number;
315
+ /** With an `fts` or `vector` signal, query() is async and resolves to an array. */
316
+ query<T = unknown>(type: string, filter: OKDBFilter, options: OKDBHybridQueryOptions): Promise<OKDBQueryEntry<T>[]>;
317
+ query<T = unknown>(type: string, filter?: OKDBFilter, options?: OKDBQueryOptions): Iterable<OKDBQueryEntry<T>>;
318
+ geoQuery<T = unknown>(type: string, field: string, options: OKDBGeoQueryOptions): Iterable<OKDBQueryEntry<T>>;
319
+ ftsQuery(
320
+ type: string,
321
+ name: string,
322
+ text: string,
323
+ filter?: OKDBFilter,
324
+ options?: OKDBFtsQueryOptions,
325
+ ): OKDBFtsSearchResult[];
326
+
327
+ // ── Type management ───────────────────────────────────────────────────────
328
+ registerType(type: string, timestamp?: number): Promise<void>;
329
+ ensureType(
330
+ type: string,
331
+ options?: { timestamp?: number; indexes?: Array<string[] | OKDBIndexDefinition> },
332
+ ): Promise<void>;
333
+ ensure(definition: OKDBEnsureDefinition): Promise<void>;
334
+ getSchema(type: string): OKDBTypeSchema | null;
335
+ hasType(type: string): boolean;
336
+ dropType(type: string, timestamp?: number): Promise<void>;
337
+
338
+ // ── Index management ──────────────────────────────────────────────────────
339
+ registerIndex(type: string, index: OKDBIndexSpec, options?: OKDBRegisterIndexOptions | number): Promise<void>;
340
+ hasIndex(type: string, index: OKDBIndexSpec): boolean;
341
+ dropIndex(type: string, index: OKDBIndexSpec, timestamp?: number): Promise<void>;
342
+ resetIndex(type: string, index: OKDBIndexSpec, clear?: boolean): Promise<void>;
343
+ indexReady(type: string, index: OKDBIndexSpec): Promise<boolean>;
344
+ getIndexStatus(type: string, index: OKDBIndexSpec): string;
345
+ getUniqueViolations(type?: string | null, index?: OKDBIndexSpec): unknown[];
346
+ hasUniqueViolations(type?: string | null, index?: OKDBIndexSpec): boolean;
347
+ getUniqueViolation(type: string, index: OKDBIndexSpec, indexKey: OKDBIndexKey): unknown;
348
+
349
+ // ── Change tracking ───────────────────────────────────────────────────────
350
+ getClock(type?: string | null, options?: Record<string, unknown>): number;
351
+ getChanges(
352
+ type?: string | null,
353
+ from?: number,
354
+ to?: number,
355
+ options?: { snapshot?: boolean | 'tolerant'; limit?: number; transaction?: unknown },
356
+ ): Iterable<OKDBChangeEntry>;
357
+
358
+ // ── TTL ───────────────────────────────────────────────────────────────────
359
+ setTTL(type: string, key: OKDBPrimaryKey, ttlMs: number): Promise<void>;
360
+ getTTL(type: string, key: OKDBPrimaryKey): OKDBTtlInfo | null;
361
+ clearTTL(type: string, key: OKDBPrimaryKey): Promise<void>;
362
+ sweepExpiredTTL(batchSize?: number): Promise<OKDBTtlSweepResult>;
363
+ listTTL(options?: OKDBTtlListOptions): OKDBTtlListResult;
364
+ ttlStats(type?: string | null): OKDBTtlStats;
365
+ setDefaultTTL(type: string, ttlMs: number): Promise<void>;
366
+ getDefaultTTL(type: string): number | null;
367
+ clearDefaultTTL(type: string): Promise<void>;
368
+
369
+ // ── Utilities ─────────────────────────────────────────────────────────────
370
+ count(iterable: Iterable<unknown>): number;
371
+ /** Yield every item of a range iterable (e.g. a `getRange()` result) or any iterable. */
372
+ range<T>(iterable: Iterable<T>): Generator<T, void, undefined>;
373
+ /** Current HLC time in ms. */
374
+ now(): number;
375
+ /** Deep equality as used by okdb. */
376
+ equal(a: unknown, b: unknown): boolean;
377
+ }