@koolbase/core 12.50.0 → 12.51.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.
@@ -2,7 +2,7 @@ import type { KbWhereNode } from './query-builder.js';
2
2
  import { KoolbaseAggregateRequest, KoolbaseAggregateResult } from './aggregate.js';
3
3
  import { KoolbaseConflict } from './conflict.js';
4
4
  import { PendingWrite } from './pending-write.js';
5
- import { KoolbaseConfig, KoolbaseRecord, QueryOptions, QueryResult, UpsertResult, BatchOp, BatchResult, KoolbaseVector, SemanticSearchResult, SearchMode } from './types.js';
5
+ import { KoolbaseConfig, KoolbaseRecord, QueryOptions, QueryResult, UpsertResult, BatchOp, BatchResult, KeyedWriteOptions, MutationResult, KoolbaseVector, SemanticSearchResult, SearchMode } from './types.js';
6
6
  export declare class KoolbaseDatabase {
7
7
  private config;
8
8
  private getUserId;
@@ -66,7 +66,9 @@ export declare class KoolbaseDatabase {
66
66
  * accepted optimistically: saved to the local cache and queued for sync
67
67
  * when connectivity returns.
68
68
  */
69
- insert(collection: string, data: Record<string, unknown>): Promise<KoolbaseRecord>;
69
+ insert(collection: string, data: Record<string, unknown>,
70
+ /** idempotencyKey: run this insert exactly once (E4a). */
71
+ options?: KeyedWriteOptions): Promise<KoolbaseRecord>;
70
72
  /**
71
73
  * Insert a record, or update the existing one matching `match`.
72
74
  *
@@ -82,7 +84,9 @@ export declare class KoolbaseDatabase {
82
84
  * fetch is used (not `request`) so the status code is readable: 201 =
83
85
  * created, 200 = updated.
84
86
  */
85
- upsert(collection: string, match: Record<string, unknown>, data: Record<string, unknown>): Promise<UpsertResult>;
87
+ upsert(collection: string, match: Record<string, unknown>, data: Record<string, unknown>,
88
+ /** idempotencyKey: run this upsert exactly once (E4a). */
89
+ options?: KeyedWriteOptions): Promise<UpsertResult>;
86
90
  /**
87
91
  * Bulk-delete every record in `collection` matching `filters`.
88
92
  *
@@ -118,7 +122,24 @@ export declare class KoolbaseDatabase {
118
122
  * BatchOp.delete(cartItemId),
119
123
  * ]);
120
124
  */
121
- batch(operations: BatchOp[]): Promise<BatchResult[]>;
125
+ batch(operations: BatchOp[],
126
+ /** idempotencyKey: run this batch exactly once (E4a). */
127
+ options?: KeyedWriteOptions): Promise<BatchResult[]>;
128
+ /**
129
+ * Run `operations` as one atomic write, exactly once per `idempotencyKey`
130
+ * (E4a), and say whether this call ran it or replayed it.
131
+ *
132
+ * Use one key per logical write and send the same key on every retry of it.
133
+ * A first run returns `results`; a retry the server had already run returns
134
+ * `replayed: true` with `outcome` (what the original write did) and
135
+ * `current` (each record as it is now). The same key with a different write
136
+ * throws `KoolbaseConflictError` with code `idempotency_key_reused`.
137
+ *
138
+ * Online-only, as `batch`.
139
+ */
140
+ mutate(operations: BatchOp[], options: {
141
+ idempotencyKey: string;
142
+ }): Promise<MutationResult>;
122
143
  get(recordId: string): Promise<KoolbaseRecord>;
123
144
  /**
124
145
  * The device's saved copy of a record: what this device last read, with the
@@ -261,14 +282,14 @@ export declare class KoolbaseDatabase {
261
282
  * with KoolbaseRevisionMismatchError otherwise (as the Flutter SDK). */
262
283
  options?: {
263
284
  expectedRevision?: number;
264
- }): Promise<KoolbaseRecord>;
285
+ } & KeyedWriteOptions): Promise<KoolbaseRecord>;
265
286
  delete(recordId: string,
266
287
  /** expectedRevision: delete only if the record still carries it (as the
267
288
  * Flutter SDK) -- removing a record someone changed a moment ago is the
268
289
  * more destructive stale write. */
269
290
  options?: {
270
291
  expectedRevision?: number;
271
- }): Promise<void>;
292
+ } & KeyedWriteOptions): Promise<void>;
272
293
  /**
273
294
  * Write (or replace) a vector for a record on the named `field`.
274
295
  *
@@ -15,6 +15,10 @@ const sync_engine_js_1 = require("./sync-engine.js");
15
15
  const record_js_1 = require("./record.js");
16
16
  const database_errors_js_2 = require("./database-errors.js");
17
17
  const query_builder_js_1 = require("./query-builder.js");
18
+ /** The headers a keyed write sends (E4a); none without a key. */
19
+ function keyHeaders(options) {
20
+ return options.idempotencyKey ? { 'Idempotency-Key': options.idempotencyKey } : undefined;
21
+ }
18
22
  function generateWriteId() {
19
23
  return 'local_' + Math.random().toString(36).slice(2) + Date.now().toString(36);
20
24
  }
@@ -108,10 +112,10 @@ class KoolbaseDatabase {
108
112
  ...(token ? { Authorization: `Bearer ${token}` } : {}),
109
113
  };
110
114
  }
111
- async request(method, path, body) {
115
+ async request(method, path, body, extraHeaders) {
112
116
  const res = await (0, network_js_1.sessionFetch)(`${this.config.baseUrl}${path}`, {
113
117
  method,
114
- headers: await this.buildHeaders(),
118
+ headers: { ...(await this.buildHeaders()), ...(extraHeaders ?? {}) },
115
119
  body: body ? JSON.stringify(body) : undefined,
116
120
  });
117
121
  // A 204 carries no body, and some error responses carry none either.
@@ -146,10 +150,10 @@ class KoolbaseDatabase {
146
150
  * hand-rolled their own fetch, each mapping errors slightly differently and
147
151
  * none of them clearing a rejected session. One path, two shapes of result.
148
152
  */
149
- async requestWithStatus(method, path, body) {
153
+ async requestWithStatus(method, path, body, extraHeaders) {
150
154
  const res = await (0, network_js_1.sessionFetch)(`${this.config.baseUrl}${path}`, {
151
155
  method,
152
- headers: await this.buildHeaders(),
156
+ headers: { ...(await this.buildHeaders()), ...(extraHeaders ?? {}) },
153
157
  body: body ? JSON.stringify(body) : undefined,
154
158
  });
155
159
  const text = await res.text();
@@ -295,13 +299,15 @@ class KoolbaseDatabase {
295
299
  * accepted optimistically: saved to the local cache and queued for sync
296
300
  * when connectivity returns.
297
301
  */
298
- async insert(collection, data) {
302
+ async insert(collection, data,
303
+ /** idempotencyKey: run this insert exactly once (E4a). */
304
+ options = {}) {
299
305
  const userId = this.getUserId() ?? 'anonymous';
300
306
  try {
301
307
  // Online path: await the server and return the authoritative record
302
308
  // (with the server-assigned id). Refresh the collection cache so the
303
309
  // next query sees real data instead of a stale optimistic copy.
304
- const raw = await this.request('POST', '/v1/sdk/db/insert', { collection, data });
310
+ const raw = await this.request('POST', '/v1/sdk/db/insert', { collection, data }, keyHeaders(options));
305
311
  const record = (0, record_js_1.recordFromWire)(raw);
306
312
  await (0, cache_store_js_3.invalidateCache)(userId, collection);
307
313
  void (0, query_refresh_js_1.refreshCollectionQueries)(collection);
@@ -372,8 +378,10 @@ class KoolbaseDatabase {
372
378
  * fetch is used (not `request`) so the status code is readable: 201 =
373
379
  * created, 200 = updated.
374
380
  */
375
- async upsert(collection, match, data) {
376
- const { status, data: body } = await this.requestWithStatus('POST', '/v1/sdk/db/upsert', { collection, match, data });
381
+ async upsert(collection, match, data,
382
+ /** idempotencyKey: run this upsert exactly once (E4a). */
383
+ options = {}) {
384
+ const { status, data: body } = await this.requestWithStatus('POST', '/v1/sdk/db/upsert', { collection, match, data }, keyHeaders(options));
377
385
  const created = status === 201;
378
386
  const record = (0, record_js_1.recordFromWire)(body);
379
387
  // Keep the cache fresh, same intent as insert's post-success invalidate.
@@ -426,7 +434,9 @@ class KoolbaseDatabase {
426
434
  * BatchOp.delete(cartItemId),
427
435
  * ]);
428
436
  */
429
- async batch(operations) {
437
+ async batch(operations,
438
+ /** idempotencyKey: run this batch exactly once (E4a). */
439
+ options = {}) {
430
440
  if (operations.length === 0) {
431
441
  throw new Error('batch requires at least one operation');
432
442
  }
@@ -442,7 +452,7 @@ class KoolbaseDatabase {
442
452
  }
443
453
  const body = await this.request('POST', '/v1/sdk/db/batch', {
444
454
  operations: operations.map(batchOpToWire),
445
- });
455
+ }, keyHeaders(options));
446
456
  const results = (body.results ?? []).map(r => ({
447
457
  type: r.type ?? '',
448
458
  record: r.record
@@ -496,7 +506,53 @@ class KoolbaseDatabase {
496
506
  void (0, query_refresh_js_1.refreshCollectionQueries)(undefined);
497
507
  return results;
498
508
  }
499
- // ─── Get single record ──────────────────────────────────────────────────────
509
+ // ─── Mutate (keyed, exactly once) ───────────────────────────────────────────
510
+ /**
511
+ * Run `operations` as one atomic write, exactly once per `idempotencyKey`
512
+ * (E4a), and say whether this call ran it or replayed it.
513
+ *
514
+ * Use one key per logical write and send the same key on every retry of it.
515
+ * A first run returns `results`; a retry the server had already run returns
516
+ * `replayed: true` with `outcome` (what the original write did) and
517
+ * `current` (each record as it is now). The same key with a different write
518
+ * throws `KoolbaseConflictError` with code `idempotency_key_reused`.
519
+ *
520
+ * Online-only, as `batch`.
521
+ */
522
+ async mutate(operations, options) {
523
+ if (operations.length === 0) {
524
+ throw new Error('mutate requires at least one operation');
525
+ }
526
+ const body = await this.request('POST', '/v1/sdk/db/batch', { operations: operations.map(batchOpToWire) }, { 'Idempotency-Key': options.idempotencyKey, 'Accept-Idempotency': 'v2' });
527
+ if (body?.replayed === true) {
528
+ const outcome = (body.outcome ?? []).map((o) => ({
529
+ type: o.type ?? '',
530
+ collection: o.collection,
531
+ id: o.id,
532
+ revisionBefore: o.revision_before,
533
+ revisionAfter: o.revision_after,
534
+ created: o.created,
535
+ record: o.record,
536
+ }));
537
+ // What the original write left behind may have changed since: live
538
+ // queries re-read rather than trust a cached copy.
539
+ void (0, query_refresh_js_1.refreshCollectionQueries)(undefined);
540
+ return {
541
+ replayed: true,
542
+ outcome,
543
+ current: body.current ?? [],
544
+ valuesOmitted: body.values_omitted === true,
545
+ };
546
+ }
547
+ const results = (body?.results ?? []).map((r) => ({
548
+ type: r.type ?? '',
549
+ record: r.record ? (0, record_js_1.recordFromWire)(r.record) : undefined,
550
+ created: r.created,
551
+ deleted: r.deleted ?? false,
552
+ }));
553
+ void (0, query_refresh_js_1.refreshCollectionQueries)(undefined);
554
+ return { replayed: false, results };
555
+ }
500
556
  // ─── Get single record ──────────────────────────────────────────────────────
501
557
  async get(recordId) {
502
558
  const raw = await this.request('GET', `/v1/sdk/db/records/${recordId}`);
@@ -887,7 +943,7 @@ class KoolbaseDatabase {
887
943
  // Resolved before the request, so a network failure has somewhere to go.
888
944
  const base = await this.resolveBaseline(userId, recordId);
889
945
  try {
890
- const raw = await this.request('PATCH', `/v1/sdk/db/records/${recordId}`, { data, ...(options.expectedRevision !== undefined ? { expected_revision: options.expectedRevision } : {}) });
946
+ const raw = await this.request('PATCH', `/v1/sdk/db/records/${recordId}`, { data, ...(options.expectedRevision !== undefined ? { expected_revision: options.expectedRevision } : {}) }, keyHeaders(options));
891
947
  const updated = (0, record_js_1.recordFromWire)(raw);
892
948
  // Its collection's live queries re-run (every one, if the record's
893
949
  // collection is not known).
@@ -953,7 +1009,7 @@ class KoolbaseDatabase {
953
1009
  const userId = this.getUserId() ?? 'anonymous';
954
1010
  const base = await this.resolveBaseline(userId, recordId);
955
1011
  try {
956
- await this.request('DELETE', `/v1/sdk/db/records/${recordId}${options.expectedRevision !== undefined ? `?expected_revision=${options.expectedRevision}` : ''}`);
1012
+ await this.request('DELETE', `/v1/sdk/db/records/${recordId}${options.expectedRevision !== undefined ? `?expected_revision=${options.expectedRevision}` : ''}`, undefined, keyHeaders(options));
957
1013
  await (0, cache_store_js_1.removeCachedRecord)(userId, recordId);
958
1014
  // Its collection is known from the baseline when the record was seen;
959
1015
  // otherwise every live query re-runs, rather than a guess.
@@ -276,7 +276,10 @@ class SyncEngine {
276
276
  else if (write.operation === 'update') {
277
277
  res = await (0, network_js_1.sessionFetch)(url, {
278
278
  method: 'PATCH',
279
- headers,
279
+ // E4a: the write's own id as its key, so an update whose response was
280
+ // lost replays as a success instead of meeting its own revision as a
281
+ // conflict on the next attempt.
282
+ headers: { ...headers, 'Idempotency-Key': write.id },
280
283
  // The revision the change was composed against. The server applies it
281
284
  // only if the record still carries that revision, so nothing can land
282
285
  // between the client deciding the write is safe and the server applying
@@ -293,7 +296,10 @@ class SyncEngine {
293
296
  const q = write.baseRevision !== undefined
294
297
  ? `?expected_revision=${write.baseRevision}`
295
298
  : '';
296
- res = await (0, network_js_1.sessionFetch)(`${url}${q}`, { method: 'DELETE', headers });
299
+ res = await (0, network_js_1.sessionFetch)(`${url}${q}`, {
300
+ method: 'DELETE',
301
+ headers: { ...headers, 'Idempotency-Key': write.id },
302
+ });
297
303
  }
298
304
  if (res.status === 401) {
299
305
  // A refused app key is setup, not a session (#169): never signs out.
@@ -750,6 +750,41 @@ export declare const BatchOp: {
750
750
  data: Record<string, unknown>;
751
751
  }) => BatchOp;
752
752
  };
753
+ /**
754
+ * Options for a write that must run exactly once (E4a).
755
+ *
756
+ * `idempotencyKey`: 16 to 128 letters, digits, `_` or `-`, one per logical
757
+ * write and the same on every retry of it. The server runs the write once;
758
+ * a retry gets the original answer, and the same key with a different write
759
+ * is refused with `idempotency_key_reused`.
760
+ */
761
+ export interface KeyedWriteOptions {
762
+ idempotencyKey?: string;
763
+ }
764
+ /**
765
+ * What a keyed `mutate` returned (E4a).
766
+ *
767
+ * On a first run, `results` holds each operation's result. On a retry the
768
+ * server already ran, `replayed` is true and `outcome` holds what the
769
+ * original write did (each record as that write left it) while `current`
770
+ * holds each record as it is now -- never merged. A record the caller can no
771
+ * longer read comes back as `{ $id, readable: false }`, with no values.
772
+ */
773
+ export interface MutationResult {
774
+ replayed: boolean;
775
+ results?: BatchResult[];
776
+ outcome?: Array<{
777
+ type: string;
778
+ collection?: string;
779
+ id?: string;
780
+ revisionBefore?: number;
781
+ revisionAfter?: number;
782
+ created?: boolean;
783
+ record?: Record<string, unknown>;
784
+ }>;
785
+ current?: Array<Record<string, unknown> | null>;
786
+ valuesOmitted?: boolean;
787
+ }
753
788
  export interface BatchResult {
754
789
  type: string;
755
790
  record?: KoolbaseRecord;
@@ -2,7 +2,7 @@ import type { KbWhereNode } from './query-builder.js';
2
2
  import { KoolbaseAggregateRequest, KoolbaseAggregateResult } from './aggregate.js';
3
3
  import { KoolbaseConflict } from './conflict.js';
4
4
  import { PendingWrite } from './pending-write.js';
5
- import { KoolbaseConfig, KoolbaseRecord, QueryOptions, QueryResult, UpsertResult, BatchOp, BatchResult, KoolbaseVector, SemanticSearchResult, SearchMode } from './types.js';
5
+ import { KoolbaseConfig, KoolbaseRecord, QueryOptions, QueryResult, UpsertResult, BatchOp, BatchResult, KeyedWriteOptions, MutationResult, KoolbaseVector, SemanticSearchResult, SearchMode } from './types.js';
6
6
  export declare class KoolbaseDatabase {
7
7
  private config;
8
8
  private getUserId;
@@ -66,7 +66,9 @@ export declare class KoolbaseDatabase {
66
66
  * accepted optimistically: saved to the local cache and queued for sync
67
67
  * when connectivity returns.
68
68
  */
69
- insert(collection: string, data: Record<string, unknown>): Promise<KoolbaseRecord>;
69
+ insert(collection: string, data: Record<string, unknown>,
70
+ /** idempotencyKey: run this insert exactly once (E4a). */
71
+ options?: KeyedWriteOptions): Promise<KoolbaseRecord>;
70
72
  /**
71
73
  * Insert a record, or update the existing one matching `match`.
72
74
  *
@@ -82,7 +84,9 @@ export declare class KoolbaseDatabase {
82
84
  * fetch is used (not `request`) so the status code is readable: 201 =
83
85
  * created, 200 = updated.
84
86
  */
85
- upsert(collection: string, match: Record<string, unknown>, data: Record<string, unknown>): Promise<UpsertResult>;
87
+ upsert(collection: string, match: Record<string, unknown>, data: Record<string, unknown>,
88
+ /** idempotencyKey: run this upsert exactly once (E4a). */
89
+ options?: KeyedWriteOptions): Promise<UpsertResult>;
86
90
  /**
87
91
  * Bulk-delete every record in `collection` matching `filters`.
88
92
  *
@@ -118,7 +122,24 @@ export declare class KoolbaseDatabase {
118
122
  * BatchOp.delete(cartItemId),
119
123
  * ]);
120
124
  */
121
- batch(operations: BatchOp[]): Promise<BatchResult[]>;
125
+ batch(operations: BatchOp[],
126
+ /** idempotencyKey: run this batch exactly once (E4a). */
127
+ options?: KeyedWriteOptions): Promise<BatchResult[]>;
128
+ /**
129
+ * Run `operations` as one atomic write, exactly once per `idempotencyKey`
130
+ * (E4a), and say whether this call ran it or replayed it.
131
+ *
132
+ * Use one key per logical write and send the same key on every retry of it.
133
+ * A first run returns `results`; a retry the server had already run returns
134
+ * `replayed: true` with `outcome` (what the original write did) and
135
+ * `current` (each record as it is now). The same key with a different write
136
+ * throws `KoolbaseConflictError` with code `idempotency_key_reused`.
137
+ *
138
+ * Online-only, as `batch`.
139
+ */
140
+ mutate(operations: BatchOp[], options: {
141
+ idempotencyKey: string;
142
+ }): Promise<MutationResult>;
122
143
  get(recordId: string): Promise<KoolbaseRecord>;
123
144
  /**
124
145
  * The device's saved copy of a record: what this device last read, with the
@@ -261,14 +282,14 @@ export declare class KoolbaseDatabase {
261
282
  * with KoolbaseRevisionMismatchError otherwise (as the Flutter SDK). */
262
283
  options?: {
263
284
  expectedRevision?: number;
264
- }): Promise<KoolbaseRecord>;
285
+ } & KeyedWriteOptions): Promise<KoolbaseRecord>;
265
286
  delete(recordId: string,
266
287
  /** expectedRevision: delete only if the record still carries it (as the
267
288
  * Flutter SDK) -- removing a record someone changed a moment ago is the
268
289
  * more destructive stale write. */
269
290
  options?: {
270
291
  expectedRevision?: number;
271
- }): Promise<void>;
292
+ } & KeyedWriteOptions): Promise<void>;
272
293
  /**
273
294
  * Write (or replace) a vector for a record on the named `field`.
274
295
  *
@@ -12,6 +12,10 @@ import { SyncEngine } from './sync-engine.js';
12
12
  import { recordFromWire } from './record.js';
13
13
  import { koolbaseDataError, KoolbaseDataError } from './database-errors.js';
14
14
  import { deviceZone, isTypedQuery } from './query-builder.js';
15
+ /** The headers a keyed write sends (E4a); none without a key. */
16
+ function keyHeaders(options) {
17
+ return options.idempotencyKey ? { 'Idempotency-Key': options.idempotencyKey } : undefined;
18
+ }
15
19
  function generateWriteId() {
16
20
  return 'local_' + Math.random().toString(36).slice(2) + Date.now().toString(36);
17
21
  }
@@ -105,10 +109,10 @@ export class KoolbaseDatabase {
105
109
  ...(token ? { Authorization: `Bearer ${token}` } : {}),
106
110
  };
107
111
  }
108
- async request(method, path, body) {
112
+ async request(method, path, body, extraHeaders) {
109
113
  const res = await sessionFetch(`${this.config.baseUrl}${path}`, {
110
114
  method,
111
- headers: await this.buildHeaders(),
115
+ headers: { ...(await this.buildHeaders()), ...(extraHeaders ?? {}) },
112
116
  body: body ? JSON.stringify(body) : undefined,
113
117
  });
114
118
  // A 204 carries no body, and some error responses carry none either.
@@ -143,10 +147,10 @@ export class KoolbaseDatabase {
143
147
  * hand-rolled their own fetch, each mapping errors slightly differently and
144
148
  * none of them clearing a rejected session. One path, two shapes of result.
145
149
  */
146
- async requestWithStatus(method, path, body) {
150
+ async requestWithStatus(method, path, body, extraHeaders) {
147
151
  const res = await sessionFetch(`${this.config.baseUrl}${path}`, {
148
152
  method,
149
- headers: await this.buildHeaders(),
153
+ headers: { ...(await this.buildHeaders()), ...(extraHeaders ?? {}) },
150
154
  body: body ? JSON.stringify(body) : undefined,
151
155
  });
152
156
  const text = await res.text();
@@ -292,13 +296,15 @@ export class KoolbaseDatabase {
292
296
  * accepted optimistically: saved to the local cache and queued for sync
293
297
  * when connectivity returns.
294
298
  */
295
- async insert(collection, data) {
299
+ async insert(collection, data,
300
+ /** idempotencyKey: run this insert exactly once (E4a). */
301
+ options = {}) {
296
302
  const userId = this.getUserId() ?? 'anonymous';
297
303
  try {
298
304
  // Online path: await the server and return the authoritative record
299
305
  // (with the server-assigned id). Refresh the collection cache so the
300
306
  // next query sees real data instead of a stale optimistic copy.
301
- const raw = await this.request('POST', '/v1/sdk/db/insert', { collection, data });
307
+ const raw = await this.request('POST', '/v1/sdk/db/insert', { collection, data }, keyHeaders(options));
302
308
  const record = recordFromWire(raw);
303
309
  await invalidateCache(userId, collection);
304
310
  void refreshCollectionQueries(collection);
@@ -369,8 +375,10 @@ export class KoolbaseDatabase {
369
375
  * fetch is used (not `request`) so the status code is readable: 201 =
370
376
  * created, 200 = updated.
371
377
  */
372
- async upsert(collection, match, data) {
373
- const { status, data: body } = await this.requestWithStatus('POST', '/v1/sdk/db/upsert', { collection, match, data });
378
+ async upsert(collection, match, data,
379
+ /** idempotencyKey: run this upsert exactly once (E4a). */
380
+ options = {}) {
381
+ const { status, data: body } = await this.requestWithStatus('POST', '/v1/sdk/db/upsert', { collection, match, data }, keyHeaders(options));
374
382
  const created = status === 201;
375
383
  const record = recordFromWire(body);
376
384
  // Keep the cache fresh, same intent as insert's post-success invalidate.
@@ -423,7 +431,9 @@ export class KoolbaseDatabase {
423
431
  * BatchOp.delete(cartItemId),
424
432
  * ]);
425
433
  */
426
- async batch(operations) {
434
+ async batch(operations,
435
+ /** idempotencyKey: run this batch exactly once (E4a). */
436
+ options = {}) {
427
437
  if (operations.length === 0) {
428
438
  throw new Error('batch requires at least one operation');
429
439
  }
@@ -439,7 +449,7 @@ export class KoolbaseDatabase {
439
449
  }
440
450
  const body = await this.request('POST', '/v1/sdk/db/batch', {
441
451
  operations: operations.map(batchOpToWire),
442
- });
452
+ }, keyHeaders(options));
443
453
  const results = (body.results ?? []).map(r => ({
444
454
  type: r.type ?? '',
445
455
  record: r.record
@@ -493,7 +503,53 @@ export class KoolbaseDatabase {
493
503
  void refreshCollectionQueries(undefined);
494
504
  return results;
495
505
  }
496
- // ─── Get single record ──────────────────────────────────────────────────────
506
+ // ─── Mutate (keyed, exactly once) ───────────────────────────────────────────
507
+ /**
508
+ * Run `operations` as one atomic write, exactly once per `idempotencyKey`
509
+ * (E4a), and say whether this call ran it or replayed it.
510
+ *
511
+ * Use one key per logical write and send the same key on every retry of it.
512
+ * A first run returns `results`; a retry the server had already run returns
513
+ * `replayed: true` with `outcome` (what the original write did) and
514
+ * `current` (each record as it is now). The same key with a different write
515
+ * throws `KoolbaseConflictError` with code `idempotency_key_reused`.
516
+ *
517
+ * Online-only, as `batch`.
518
+ */
519
+ async mutate(operations, options) {
520
+ if (operations.length === 0) {
521
+ throw new Error('mutate requires at least one operation');
522
+ }
523
+ const body = await this.request('POST', '/v1/sdk/db/batch', { operations: operations.map(batchOpToWire) }, { 'Idempotency-Key': options.idempotencyKey, 'Accept-Idempotency': 'v2' });
524
+ if (body?.replayed === true) {
525
+ const outcome = (body.outcome ?? []).map((o) => ({
526
+ type: o.type ?? '',
527
+ collection: o.collection,
528
+ id: o.id,
529
+ revisionBefore: o.revision_before,
530
+ revisionAfter: o.revision_after,
531
+ created: o.created,
532
+ record: o.record,
533
+ }));
534
+ // What the original write left behind may have changed since: live
535
+ // queries re-read rather than trust a cached copy.
536
+ void refreshCollectionQueries(undefined);
537
+ return {
538
+ replayed: true,
539
+ outcome,
540
+ current: body.current ?? [],
541
+ valuesOmitted: body.values_omitted === true,
542
+ };
543
+ }
544
+ const results = (body?.results ?? []).map((r) => ({
545
+ type: r.type ?? '',
546
+ record: r.record ? recordFromWire(r.record) : undefined,
547
+ created: r.created,
548
+ deleted: r.deleted ?? false,
549
+ }));
550
+ void refreshCollectionQueries(undefined);
551
+ return { replayed: false, results };
552
+ }
497
553
  // ─── Get single record ──────────────────────────────────────────────────────
498
554
  async get(recordId) {
499
555
  const raw = await this.request('GET', `/v1/sdk/db/records/${recordId}`);
@@ -884,7 +940,7 @@ export class KoolbaseDatabase {
884
940
  // Resolved before the request, so a network failure has somewhere to go.
885
941
  const base = await this.resolveBaseline(userId, recordId);
886
942
  try {
887
- const raw = await this.request('PATCH', `/v1/sdk/db/records/${recordId}`, { data, ...(options.expectedRevision !== undefined ? { expected_revision: options.expectedRevision } : {}) });
943
+ const raw = await this.request('PATCH', `/v1/sdk/db/records/${recordId}`, { data, ...(options.expectedRevision !== undefined ? { expected_revision: options.expectedRevision } : {}) }, keyHeaders(options));
888
944
  const updated = recordFromWire(raw);
889
945
  // Its collection's live queries re-run (every one, if the record's
890
946
  // collection is not known).
@@ -950,7 +1006,7 @@ export class KoolbaseDatabase {
950
1006
  const userId = this.getUserId() ?? 'anonymous';
951
1007
  const base = await this.resolveBaseline(userId, recordId);
952
1008
  try {
953
- await this.request('DELETE', `/v1/sdk/db/records/${recordId}${options.expectedRevision !== undefined ? `?expected_revision=${options.expectedRevision}` : ''}`);
1009
+ await this.request('DELETE', `/v1/sdk/db/records/${recordId}${options.expectedRevision !== undefined ? `?expected_revision=${options.expectedRevision}` : ''}`, undefined, keyHeaders(options));
954
1010
  await removeCachedRecord(userId, recordId);
955
1011
  // Its collection is known from the baseline when the record was seen;
956
1012
  // otherwise every live query re-runs, rather than a guess.
@@ -273,7 +273,10 @@ export class SyncEngine {
273
273
  else if (write.operation === 'update') {
274
274
  res = await sessionFetch(url, {
275
275
  method: 'PATCH',
276
- headers,
276
+ // E4a: the write's own id as its key, so an update whose response was
277
+ // lost replays as a success instead of meeting its own revision as a
278
+ // conflict on the next attempt.
279
+ headers: { ...headers, 'Idempotency-Key': write.id },
277
280
  // The revision the change was composed against. The server applies it
278
281
  // only if the record still carries that revision, so nothing can land
279
282
  // between the client deciding the write is safe and the server applying
@@ -290,7 +293,10 @@ export class SyncEngine {
290
293
  const q = write.baseRevision !== undefined
291
294
  ? `?expected_revision=${write.baseRevision}`
292
295
  : '';
293
- res = await sessionFetch(`${url}${q}`, { method: 'DELETE', headers });
296
+ res = await sessionFetch(`${url}${q}`, {
297
+ method: 'DELETE',
298
+ headers: { ...headers, 'Idempotency-Key': write.id },
299
+ });
294
300
  }
295
301
  if (res.status === 401) {
296
302
  // A refused app key is setup, not a session (#169): never signs out.
@@ -750,6 +750,41 @@ export declare const BatchOp: {
750
750
  data: Record<string, unknown>;
751
751
  }) => BatchOp;
752
752
  };
753
+ /**
754
+ * Options for a write that must run exactly once (E4a).
755
+ *
756
+ * `idempotencyKey`: 16 to 128 letters, digits, `_` or `-`, one per logical
757
+ * write and the same on every retry of it. The server runs the write once;
758
+ * a retry gets the original answer, and the same key with a different write
759
+ * is refused with `idempotency_key_reused`.
760
+ */
761
+ export interface KeyedWriteOptions {
762
+ idempotencyKey?: string;
763
+ }
764
+ /**
765
+ * What a keyed `mutate` returned (E4a).
766
+ *
767
+ * On a first run, `results` holds each operation's result. On a retry the
768
+ * server already ran, `replayed` is true and `outcome` holds what the
769
+ * original write did (each record as that write left it) while `current`
770
+ * holds each record as it is now -- never merged. A record the caller can no
771
+ * longer read comes back as `{ $id, readable: false }`, with no values.
772
+ */
773
+ export interface MutationResult {
774
+ replayed: boolean;
775
+ results?: BatchResult[];
776
+ outcome?: Array<{
777
+ type: string;
778
+ collection?: string;
779
+ id?: string;
780
+ revisionBefore?: number;
781
+ revisionAfter?: number;
782
+ created?: boolean;
783
+ record?: Record<string, unknown>;
784
+ }>;
785
+ current?: Array<Record<string, unknown> | null>;
786
+ valuesOmitted?: boolean;
787
+ }
753
788
  export interface BatchResult {
754
789
  type: string;
755
790
  record?: KoolbaseRecord;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koolbase/core",
3
- "version": "12.50.0",
3
+ "version": "12.51.0",
4
4
  "description": "Koolbase SDK core — shared behaviour behind @koolbase/react-native and @koolbase/js. Install one of those, not this.",
5
5
  "main": "./dist/cjs/index.js",
6
6
  "react-native": "./dist/esm/index.js",