@koolbase/core 10.0.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 (104) hide show
  1. package/README.md +19 -0
  2. package/dist/cjs/analytics.d.ts +24 -0
  3. package/dist/cjs/analytics.js +110 -0
  4. package/dist/cjs/auth-errors.d.ts +117 -0
  5. package/dist/cjs/auth-errors.js +250 -0
  6. package/dist/cjs/auth.d.ts +213 -0
  7. package/dist/cjs/auth.js +813 -0
  8. package/dist/cjs/cache-store.d.ts +50 -0
  9. package/dist/cjs/cache-store.js +194 -0
  10. package/dist/cjs/conflict.d.ts +80 -0
  11. package/dist/cjs/conflict.js +84 -0
  12. package/dist/cjs/database-errors.d.ts +101 -0
  13. package/dist/cjs/database-errors.js +200 -0
  14. package/dist/cjs/database.d.ts +298 -0
  15. package/dist/cjs/database.js +852 -0
  16. package/dist/cjs/device-id.d.ts +1 -0
  17. package/dist/cjs/device-id.js +57 -0
  18. package/dist/cjs/device-metadata.d.ts +36 -0
  19. package/dist/cjs/device-metadata.js +94 -0
  20. package/dist/cjs/errors.d.ts +64 -0
  21. package/dist/cjs/errors.js +85 -0
  22. package/dist/cjs/flags.d.ts +15 -0
  23. package/dist/cjs/flags.js +76 -0
  24. package/dist/cjs/function-errors.d.ts +51 -0
  25. package/dist/cjs/function-errors.js +103 -0
  26. package/dist/cjs/functions.d.ts +15 -0
  27. package/dist/cjs/functions.js +83 -0
  28. package/dist/cjs/index.d.ts +22 -0
  29. package/dist/cjs/index.js +56 -0
  30. package/dist/cjs/messaging.d.ts +13 -0
  31. package/dist/cjs/messaging.js +36 -0
  32. package/dist/cjs/offline-state.d.ts +97 -0
  33. package/dist/cjs/offline-state.js +198 -0
  34. package/dist/cjs/package.json +3 -0
  35. package/dist/cjs/pending-write.d.ts +47 -0
  36. package/dist/cjs/pending-write.js +22 -0
  37. package/dist/cjs/platform.d.ts +51 -0
  38. package/dist/cjs/platform.js +41 -0
  39. package/dist/cjs/realtime.d.ts +44 -0
  40. package/dist/cjs/realtime.js +195 -0
  41. package/dist/cjs/record.d.ts +2 -0
  42. package/dist/cjs/record.js +23 -0
  43. package/dist/cjs/shared.d.ts +9 -0
  44. package/dist/cjs/shared.js +43 -0
  45. package/dist/cjs/storage-errors.d.ts +163 -0
  46. package/dist/cjs/storage-errors.js +253 -0
  47. package/dist/cjs/storage.d.ts +198 -0
  48. package/dist/cjs/storage.js +451 -0
  49. package/dist/cjs/sync-engine.d.ts +30 -0
  50. package/dist/cjs/sync-engine.js +286 -0
  51. package/dist/cjs/types.d.ts +487 -0
  52. package/dist/cjs/types.js +40 -0
  53. package/dist/esm/analytics.d.ts +24 -0
  54. package/dist/esm/analytics.js +106 -0
  55. package/dist/esm/auth-errors.d.ts +117 -0
  56. package/dist/esm/auth-errors.js +222 -0
  57. package/dist/esm/auth.d.ts +213 -0
  58. package/dist/esm/auth.js +809 -0
  59. package/dist/esm/cache-store.d.ts +50 -0
  60. package/dist/esm/cache-store.js +179 -0
  61. package/dist/esm/conflict.d.ts +80 -0
  62. package/dist/esm/conflict.js +80 -0
  63. package/dist/esm/database-errors.d.ts +101 -0
  64. package/dist/esm/database-errors.js +189 -0
  65. package/dist/esm/database.d.ts +298 -0
  66. package/dist/esm/database.js +848 -0
  67. package/dist/esm/device-id.d.ts +1 -0
  68. package/dist/esm/device-id.js +54 -0
  69. package/dist/esm/device-metadata.d.ts +36 -0
  70. package/dist/esm/device-metadata.js +90 -0
  71. package/dist/esm/errors.d.ts +64 -0
  72. package/dist/esm/errors.js +79 -0
  73. package/dist/esm/flags.d.ts +15 -0
  74. package/dist/esm/flags.js +72 -0
  75. package/dist/esm/function-errors.d.ts +51 -0
  76. package/dist/esm/function-errors.js +93 -0
  77. package/dist/esm/functions.d.ts +15 -0
  78. package/dist/esm/functions.js +79 -0
  79. package/dist/esm/index.d.ts +22 -0
  80. package/dist/esm/index.js +25 -0
  81. package/dist/esm/messaging.d.ts +13 -0
  82. package/dist/esm/messaging.js +32 -0
  83. package/dist/esm/offline-state.d.ts +97 -0
  84. package/dist/esm/offline-state.js +189 -0
  85. package/dist/esm/package.json +3 -0
  86. package/dist/esm/pending-write.d.ts +47 -0
  87. package/dist/esm/pending-write.js +19 -0
  88. package/dist/esm/platform.d.ts +51 -0
  89. package/dist/esm/platform.js +36 -0
  90. package/dist/esm/realtime.d.ts +44 -0
  91. package/dist/esm/realtime.js +191 -0
  92. package/dist/esm/record.d.ts +2 -0
  93. package/dist/esm/record.js +20 -0
  94. package/dist/esm/shared.d.ts +9 -0
  95. package/dist/esm/shared.js +39 -0
  96. package/dist/esm/storage-errors.d.ts +163 -0
  97. package/dist/esm/storage-errors.js +239 -0
  98. package/dist/esm/storage.d.ts +198 -0
  99. package/dist/esm/storage.js +447 -0
  100. package/dist/esm/sync-engine.d.ts +30 -0
  101. package/dist/esm/sync-engine.js +282 -0
  102. package/dist/esm/types.d.ts +487 -0
  103. package/dist/esm/types.js +37 -0
  104. package/package.json +45 -0
@@ -0,0 +1,298 @@
1
+ import { KoolbaseConflict } from './conflict.js';
2
+ import { PendingWrite } from './pending-write.js';
3
+ import { KoolbaseConfig, KoolbaseRecord, QueryOptions, QueryResult, UpsertResult, BatchOp, BatchResult, KoolbaseVector, SemanticSearchResult, SearchMode } from './types.js';
4
+ export declare class KoolbaseDatabase {
5
+ private config;
6
+ private getUserId;
7
+ private getToken;
8
+ /**
9
+ * Called when the server rejects the caller's credentials.
10
+ *
11
+ * A session stops working for the whole SDK at once, so it is cleared before
12
+ * the error reaches the caller — otherwise the app keeps believing it is
13
+ * signed in and every subsequent call fails the same way, with no path back
14
+ * to login.
15
+ */
16
+ private onSessionExpired?;
17
+ private syncEngine;
18
+ constructor(config: KoolbaseConfig, getUserId: () => string | null, getToken: () => Promise<string | null>, onSessionExpired?: () => Promise<void>);
19
+ private buildHeaders;
20
+ private request;
21
+ /**
22
+ * Like [request], but returns the status alongside the body.
23
+ *
24
+ * Several operations need it — upsert distinguishes create from update by a
25
+ * 201, batch reports per-operation outcomes — and needing it was why they
26
+ * hand-rolled their own fetch, each mapping errors slightly differently and
27
+ * none of them clearing a rejected session. One path, two shapes of result.
28
+ */
29
+ private requestWithStatus;
30
+ private runQuery;
31
+ /**
32
+ * Query records, cache-first (stale-while-revalidate).
33
+ *
34
+ * A cache hit is returned immediately with `isFromCache: true`, and a
35
+ * background refresh updates the cache for the next call — so a repeat
36
+ * query converges on the server's state one call behind it. Only a cache
37
+ * miss awaits the network (`isFromCache: false`).
38
+ *
39
+ * Two consequences worth designing for: results can be one refresh stale,
40
+ * even online — re-query if you need convergence after a known write; and
41
+ * background refresh failures are swallowed by design (the cached result
42
+ * has already been returned), so a dead network looks identical to a slow
43
+ * refresh. Check `isFromCache` when the difference matters.
44
+ *
45
+ * The cache is per-user and persisted; it doubles as the offline baseline
46
+ * store for `update`/`delete`.
47
+ */
48
+ query(collection: string, options?: QueryOptions): Promise<QueryResult>;
49
+ /**
50
+ * Insert a new record into a collection.
51
+ *
52
+ * Online-first: awaits the server so a server-side rejection (unique
53
+ * violation, validation error, permission denial) surfaces as the typed
54
+ * `KoolbaseDataError` subclass — `insert` now throws `KoolbaseConflictError`
55
+ * with the offending field on a 409, matching `upsert` and `update`.
56
+ *
57
+ * On genuine network failure (server unreachable, timeout) the write is
58
+ * accepted optimistically: saved to the local cache and queued for sync
59
+ * when connectivity returns.
60
+ */
61
+ insert(collection: string, data: Record<string, unknown>): Promise<KoolbaseRecord>;
62
+ /**
63
+ * Insert a record, or update the existing one matching `match`.
64
+ *
65
+ * The server decides: exactly one match updates it, no match inserts a new
66
+ * record (seeded with the `match` fields), more than one match is an error.
67
+ * Returns the resulting record and a `created` flag (true = inserted, false
68
+ * = updated).
69
+ *
70
+ * Online-only by design. Unlike `insert`, an upsert is NOT queued offline:
71
+ * the insert-vs-update decision needs the server's authoritative view of
72
+ * what already exists, so deferring it could create a duplicate or apply a
73
+ * wrong update on later sync. It throws on network failure instead. A raw
74
+ * fetch is used (not `request`) so the status code is readable: 201 =
75
+ * created, 200 = updated.
76
+ */
77
+ upsert(collection: string, match: Record<string, unknown>, data: Record<string, unknown>): Promise<UpsertResult>;
78
+ /**
79
+ * Bulk-delete every record in `collection` matching `filters`.
80
+ *
81
+ * The server applies the collection's delete rule (scoping to the caller for
82
+ * owner/scoped rules) and returns the number of records deleted.
83
+ *
84
+ * Online-only by design — like upsert, this is NOT queued offline: a bulk
85
+ * delete needs the server's authoritative view of what matches, so it throws
86
+ * on network failure rather than risk deleting the wrong set on later sync.
87
+ * The collection cache is invalidated on success.
88
+ */
89
+ deleteWhere(collection: string, filters: Record<string, unknown>): Promise<number>;
90
+ /**
91
+ * Run multiple writes as a single atomic transaction.
92
+ *
93
+ * All `operations` commit together or none are applied — the server runs
94
+ * them in one database transaction and rolls back entirely on any failure.
95
+ * Operations apply in order and may span multiple collections.
96
+ *
97
+ * Online-only by design (like `upsert` and `deleteWhere`): atomicity needs
98
+ * the server's authoritative view, so a batch is never queued offline — it
99
+ * throws on network failure. A server-side rejection throws a
100
+ * `KoolbaseDataException` whose message identifies which operation failed;
101
+ * nothing was persisted.
102
+ *
103
+ * Returns one `BatchResult` per operation, in order.
104
+ *
105
+ * @example
106
+ * const results = await Koolbase.db.batch([
107
+ * BatchOp.insert('orders', { total: 50 }),
108
+ * BatchOp.update(inventoryId, { stock: 9 }),
109
+ * BatchOp.upsert('counters', { match: { name: 'orders' }, data: { value: 1 } }),
110
+ * BatchOp.delete(cartItemId),
111
+ * ]);
112
+ */
113
+ batch(operations: BatchOp[]): Promise<BatchResult[]>;
114
+ get(recordId: string): Promise<KoolbaseRecord>;
115
+ /**
116
+ * Writes that could not be applied, waiting for a decision.
117
+ *
118
+ * Held rather than discarded, and surviving restarts. An app that never reads
119
+ * these accumulates them invisibly, with the changes they hold never applied —
120
+ * so if you support offline editing, surface them somewhere.
121
+ */
122
+ /**
123
+ * Changes made offline, waiting to be sent. Oldest first.
124
+ *
125
+ * For sync indicators ("3 changes waiting") and for warning a user who is
126
+ * about to log out with unsynced edits — see [PendingWrite] for why that
127
+ * moment matters. Snapshot, not a live handle; per-user.
128
+ */
129
+ pendingWrites(): Promise<PendingWrite[]>;
130
+ conflicts(): Promise<KoolbaseConflict[]>;
131
+ /**
132
+ * Resolves by id, reloading the stored conflict first.
133
+ *
134
+ * A conflict object handed to a UI can sit there while someone decides, and a
135
+ * sync pass may resolve it or another write supersede it meanwhile. Acting on
136
+ * values captured when the object was built would write against a state that
137
+ * no longer exists.
138
+ */
139
+ private readonly conflictResolver;
140
+ /**
141
+ * Per-user state demands a user. Signed out, "no answer" must not be
142
+ * disguised as "empty" — tonight's fake-zero: the display read the anonymous
143
+ * bucket while a signed-in user's writes sat unseen in theirs.
144
+ */
145
+ private requireUserId;
146
+ private requireConflict;
147
+ private dropConflict;
148
+ /**
149
+ * Issues the resolving write, conditional on the revision the refusal
150
+ * reported, and clears the conflict only once the server accepts it.
151
+ *
152
+ * Clearing first would lose the change if the write then failed.
153
+ */
154
+ private applyResolution;
155
+ /**
156
+ * Update a record's fields by id.
157
+ *
158
+ * Online-first: awaits the server so a server-side rejection (unique
159
+ * violation, not found, permission denial) surfaces as the typed
160
+ * `KoolbaseDataError` subclass. An update that would violate a unique
161
+ * constraint now throws `KoolbaseConflictError` with the offending field —
162
+ * same shape as `insert` and `upsert`.
163
+ *
164
+ * On genuine network failure the update is queued for sync and a partial
165
+ * optimistic record is returned so the UI can re-render the new fields
166
+ * immediately.
167
+ */
168
+ /**
169
+ * The record's state as the SDK last knew it, for composing an offline
170
+ * mutation against.
171
+ *
172
+ * Two sources, in order. A record created offline is not in the cache as a
173
+ * server record, but its queued insert holds the state a later edit builds on
174
+ * — insert-then-correct is the ordinary offline sequence. Otherwise the cached
175
+ * copy, with the revision it was read at.
176
+ *
177
+ * Null when neither exists: never seen on this device, or a queued delete has
178
+ * already removed it locally.
179
+ */
180
+ private resolveBaseline;
181
+ update(recordId: string, data: Record<string, unknown>): Promise<KoolbaseRecord>;
182
+ delete(recordId: string): Promise<void>;
183
+ /**
184
+ * Write (or replace) a vector for a record on the named `field`.
185
+ *
186
+ * The field must already be declared on the collection via the dashboard
187
+ * or CLI. `vector.length` must match the field's declared dimension;
188
+ * otherwise throws `KoolbaseVectorDimensionMismatchError`.
189
+ *
190
+ * Online-only — vectors are not cached locally or queued offline because
191
+ * HNSW similarity search has no useful offline semantics.
192
+ *
193
+ * @example
194
+ * await Koolbase.db.setVector(
195
+ * articleId,
196
+ * 'embedding',
197
+ * await myEmbeddingModel.encode(article.content),
198
+ * );
199
+ */
200
+ setVector(recordId: string, field: string, vector: number[]): Promise<void>;
201
+ /**
202
+ * Read a record's stored vector on the named `field`.
203
+ *
204
+ * Throws `KoolbaseNotFoundError` if either the field is not declared or
205
+ * no vector has been set for this record on this field. Throws
206
+ * `KoolbasePermissionError` if the caller cannot read this record per
207
+ * the collection's read rule.
208
+ *
209
+ * Online-only.
210
+ *
211
+ * @example
212
+ * const v = await Koolbase.db.getVector(articleId, 'embedding');
213
+ * console.log(`${v.vector.length}-dim, updated ${v.updatedAt}`);
214
+ */
215
+ getVector(recordId: string, field: string): Promise<KoolbaseVector>;
216
+ /**
217
+ * Remove a record's stored vector on the named `field`.
218
+ *
219
+ * Online-only. Throws `KoolbaseNotFoundError` if no vector is set for
220
+ * `(recordId, field)`; throws `KoolbasePermissionError` if the caller
221
+ * cannot write this record per the collection's write rule.
222
+ *
223
+ * Note: this removes the vector from the dimension table but does NOT
224
+ * remove the field declaration itself — the field stays on the
225
+ * collection and is still settable on other records.
226
+ */
227
+ deleteVector(recordId: string, field: string): Promise<void>;
228
+ /**
229
+ * Queue an embedding job for a record's vector field. The server's
230
+ * embedding worker picks it up within ~1 second.
231
+ *
232
+ * If `text` is omitted, the vector field's configured `source_field`
233
+ * value on the record is used.
234
+ *
235
+ * @example
236
+ * await Koolbase.db.embedText({
237
+ * collection: 'articles',
238
+ * recordId: article.$id,
239
+ * vectorField: 'content_embedding',
240
+ * });
241
+ */
242
+ embedText(opts: {
243
+ collection: string;
244
+ recordId: string;
245
+ vectorField: string;
246
+ text?: string;
247
+ }): Promise<void>;
248
+ /**
249
+ * Search for records based on their semantic similarity to a query.
250
+ *
251
+ * @example
252
+ * // Server-side embedding — most common:
253
+ * const result = await Koolbase.db.searchSemantic({
254
+ * collection: 'articles',
255
+ * field: 'content_embedding',
256
+ * queryText: 'how do I configure CI/CD?',
257
+ * limit: 10,
258
+ * });
259
+ *
260
+ * // Client-side embedding:
261
+ * const result = await Koolbase.db.searchSemantic({
262
+ * collection: 'articles',
263
+ * field: 'content_embedding',
264
+ * queryVector: precomputed,
265
+ * limit: 10,
266
+ * });
267
+ *
268
+ * // Hybrid search (vector + BM25, RRF-fused):
269
+ * const result = await Koolbase.db.searchSemantic({
270
+ * collection: 'articles',
271
+ * field: 'content_embedding',
272
+ * queryText: 'how do I configure CI/CD?',
273
+ * mode: 'hybrid',
274
+ * minSimilarity: 70,
275
+ * });
276
+ *
277
+ * `mode` selects the retrieval strategy:
278
+ * - `'semantic'` (default) — pure vector search via HNSW
279
+ * - `'lexical'` — pure BM25 over the field's source text
280
+ * - `'hybrid'` — vector + lexical, RRF-fused (k=60)
281
+ *
282
+ * `minSimilarity` (0..100, optional) filters out results below the
283
+ * given similarity percentage server-side. Saves bandwidth on weak
284
+ * matches. Only valid for semantic and hybrid; rejected by the
285
+ * server on lexical mode.
286
+ */
287
+ searchSemantic(opts: {
288
+ collection: string;
289
+ field: string;
290
+ queryVector?: number[];
291
+ queryText?: string;
292
+ limit?: number;
293
+ where?: Record<string, unknown>;
294
+ mode?: SearchMode;
295
+ minSimilarity?: number;
296
+ }): Promise<SemanticSearchResult>;
297
+ syncPendingWrites(): Promise<void>;
298
+ }