@dittolive/ditto 4.0.1 → 4.0.2-experimental.shutdown-support.2.darwin-arm64

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.
package/types/ditto.d.ts CHANGED
@@ -1,102 +1,152 @@
1
1
  /** @internal */
2
- type Pointer<Type> = {
3
- type: Type;
4
- addr: string;
5
- };
6
- /** @internal */
7
- type FFIWriteTransaction = 'CWriteTransaction_t';
2
+ declare class KeepAlive {
3
+ /** @internal */
4
+ get isActive(): boolean;
5
+ /** @internal */
6
+ constructor();
7
+ /** @internal */
8
+ retain(id: string): void;
9
+ /** @internal */
10
+ release(id: string): void;
11
+ /** @internal */
12
+ currentIDs(): string[];
13
+ /** @internal */
14
+ countForID(id: string): number | null;
15
+ private static finalizationRegistry;
16
+ private intervalID;
17
+ private countsByID;
18
+ }
19
+
8
20
  /** @internal */
9
- type FFIAuthClient = 'CAuthClient_t';
21
+ type ObserverToken = string;
10
22
  /** @internal */
11
- type OrderBy = {
12
- query: string;
13
- direction: 'Ascending' | 'Descending';
23
+ type ObserverManagerConstructorOptions = {
24
+ keepAlive?: KeepAlive;
25
+ register?: (callback: (...args: any[]) => void) => void;
26
+ unregister?: () => void;
27
+ process?: (...args: any[]) => any[];
14
28
  };
15
29
  /** @internal */
16
- type PathAccessorType = 'String' | 'Number' | 'Int' | 'UInt' | 'Float' | 'Double' | 'Bool' | 'Null' | 'Object' | 'Array' | 'Any' | 'Counter' | 'Register' | 'Attachment' | 'Rga' | 'RWMap';
17
- /** Various options to pass the web assembly module to Ditto. */
18
- type WebAssemblyModule = RequestInfo | URL | Response | BufferSource | WebAssembly.Module | string | null;
19
-
20
- /** Represents a unique identifier for a {@link Document}. */
21
- type DocumentIDValue = any;
22
- /** Represents a unique identifier for a {@link Document}. */
23
- declare class DocumentID {
24
- /**
25
- * Returns the value of the receiver, lazily decoded from its CBOR
26
- * representation if needed.
27
- */
28
- get value(): any;
29
- /**
30
- * Returns `false` if validation has been skipped at construction time,
31
- * otherwise returns `true`. This is mostly for internal use only, you
32
- * shouldn't need this in client code.
33
- */
34
- readonly isValidated: boolean;
30
+ declare class ObserverManager {
31
+ /** @internal */
32
+ readonly id: string;
33
+ /** @internal */
34
+ readonly keepAlive: KeepAlive | null;
35
+ /** @internal */
36
+ constructor(id: string, options?: ObserverManagerConstructorOptions);
37
+ /** @internal */
38
+ addObserver(callback: any): ObserverToken;
39
+ /** @internal */
40
+ removeObserver(token: ObserverToken): void;
41
+ hasObserver(token: ObserverToken): boolean;
42
+ /** @internal */
43
+ notify(...args: any[]): void;
44
+ /** @internal */
45
+ close(): void;
35
46
  /**
36
- * Creates a new `DocumentID`.
37
- *
38
- * A document ID can be created from any of the following:
39
- *
40
- * - `string`
41
- * - `number` (integer)
42
- * - `boolean`
43
- * - `null`
44
- * - raw data in the form of a JS [Typed Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
45
- * - `Array` (containing any of the items in this list)
46
- * - Map (a raw JS `object`, where the keys must be strings and the values
47
- * can be made up of any of the items in this list)
48
- *
49
- * Note that you cannot use floats or other custom types to create a document
50
- * ID.
51
- *
52
- * Document IDs are also limited in size, based on their serialized
53
- * representation, to 256 bytes. You will receive an error if you try to
54
- * create a document ID that exceeds the size limit.
47
+ * Can be injected and replaced via constructor options.
55
48
  *
56
- * @param value The value that represents the document identifier.
57
- * @param skipCBOREncoding If `true, skips CBOR encoding and assumes
58
- * the passed in `value` is already CBOR encoded. You shouldn't need to ever
59
- * pass this parameter, it's only used internally for certain edge cases.
60
- * @param skipValidation If `true, skips validation of the passed in value or
61
- * CBOR. You shouldn't need to ever pass this parameter, it's only used
62
- * internally for certain edge cases.
49
+ * @abstract
63
50
  */
64
- constructor(value: any, skipCBOREncoding?: boolean, skipValidation?: boolean);
51
+ protected register(callback: (...args: any[]) => void): void;
65
52
  /**
66
- * Returns `true` if passed in `documentID` is equal to the receiver,
67
- * otherwise returns `false`.
53
+ * Can be injected and replaced via constructor options.
54
+ *
55
+ * @abstract
68
56
  */
69
- equals(documentID: DocumentID): boolean;
57
+ protected unregister(): void;
70
58
  /**
71
- * Returns a string representation of the receiver.
59
+ * Can be injected and replaced via constructor options.
72
60
  *
73
- * If you need a string representation to be used directly in a query,
74
- * please use `toQueryCompatibleString()` instead.
61
+ * @abstract
75
62
  */
76
- toString(): string;
63
+ protected process(...args: any[]): any[];
64
+ private isClosed;
65
+ private isRegistered;
66
+ private callbacksByToken;
67
+ private constructorOptions;
68
+ private hasObservers;
69
+ private registerIfNeeded;
70
+ private unregisterIfNeeded;
71
+ private finalize;
72
+ }
73
+
74
+ /** @internal */
75
+ interface ObserverManaging {
76
+ hasObserver(token: ObserverToken): any;
77
+ removeObserver(token: ObserverToken): any;
78
+ }
79
+ /** @internal */
80
+ type ObserverOptions = {
81
+ stopsWhenFinalized?: boolean;
82
+ };
83
+ /**
84
+ * Generic observer handle returned by various observation APIs. The observation
85
+ * remains active until the {@link stop | stop()} method is called explicitly or
86
+ * the observer instance is garbage collected. Therefore, to keep the observation
87
+ * alive, you have to keep a reference to the corresponding observer.
88
+ */
89
+ declare class Observer {
90
+ /** @internal */
91
+ readonly observerManager: ObserverManaging;
92
+ /** @internal */
93
+ readonly token?: ObserverToken;
94
+ /** @internal */
95
+ readonly options?: ObserverOptions;
96
+ /** @internal */
97
+ constructor(observerManager: ObserverManaging, token: any, options?: ObserverOptions);
77
98
  /**
78
- * Returns a byte representation of the document ID value as base64 string.
99
+ * Returns `true` if the observer has been explicitly stopped via the `stop()`
100
+ * method. Otherwise returns `false`.
79
101
  */
80
- toBase64String(): string;
102
+ get isStopped(): boolean;
81
103
  /**
82
- * Returns a query compatible string representation of the receiver.
83
- *
84
- * The returned string can be used directly in queries that you use with
85
- * other Ditto functions. For example you could create a query that was like
86
- * this:
87
- *
88
- * ``` TypeScript
89
- * collection.find(`_id == ${documentID.toQueryCompatibleString()}`)
90
- * ```
104
+ * Stops the observation. Calling this method multiple times has no effect.
91
105
  */
92
- toQueryCompatibleString(): string;
93
- /** @internal */
94
- toCBOR(): Uint8Array;
106
+ stop(): void;
107
+ private static finalizationRegistry;
108
+ private static finalize;
95
109
  }
110
+
111
+ /**
112
+ * Describes the direction when sorting a query.
113
+ */
114
+ type SortDirection = 'ascending' | 'descending';
115
+ /**
116
+ * Defines the various strategies available when inserting a document into a
117
+ * collection.
118
+ *
119
+ * - `merge`: the existing document will be merged with the document being
120
+ * inserted, if there is a pre-existing document.
121
+ *
122
+ * - `insertIfAbsent`: insert the document only if there is not already a
123
+ * document with the same ID in the store. If there is already a document in
124
+ * the store with the same ID then this will be a no-op.
125
+ *
126
+ * - `insertDefaultIfAbsent`: insert the document, with its contents treated as
127
+ * default data, only if there is not already a document with the same ID in
128
+ * the store. If there is already a document in the store with the same ID
129
+ * then this will be a no-op. Use this strategy if you want to insert default
130
+ * data for a given document ID, which you want to treat as common initial
131
+ * data amongst all peers and that you expect to be mutated or overwritten in
132
+ * due course.
133
+ */
134
+ type WriteStrategy = 'merge' | 'insertIfAbsent' | 'insertDefaultIfAbsent';
135
+ /**
136
+ * Represents a dictionary of values to be incorporated into a query keyed
137
+ * by the placeholder used within that query. See method
138
+ * {@link Collection.find | find()} of {@link Collection} for more info.
139
+ */
140
+ type QueryArguments = {
141
+ [key: string]: any;
142
+ };
143
+
96
144
  /** @internal */
97
- declare function validateDocumentIDValue(id: DocumentIDValue): DocumentIDValue;
98
- /** @internal */
99
- declare function validateDocumentIDCBOR(idCBOR: Uint8Array): Uint8Array;
145
+ declare class Value {
146
+ readonly value: unknown;
147
+ readonly isDefault: boolean;
148
+ constructor(value: unknown, options?: unknown);
149
+ }
100
150
 
101
151
  /**
102
152
  * Represents a CRDT counter that can be upserted as part of a document or
@@ -200,41 +250,272 @@ declare class AttachmentToken {
200
250
  constructor(jsObj: object);
201
251
  }
202
252
 
253
+ /** @internal */
254
+ type Pointer<Type> = {
255
+ type: Type;
256
+ addr: string;
257
+ };
258
+ /** @internal */
259
+ type FFIWriteTransaction = 'CWriteTransaction_t';
260
+ /** @internal */
261
+ type FFIAuthClient = 'CAuthClient_t';
262
+ /** @internal */
263
+ type OrderBy = {
264
+ query: string;
265
+ direction: 'Ascending' | 'Descending';
266
+ };
267
+ /** @internal */
268
+ type PathAccessorType = 'String' | 'Number' | 'Int' | 'UInt' | 'Float' | 'Double' | 'Bool' | 'Null' | 'Object' | 'Array' | 'Any' | 'Counter' | 'Register' | 'Attachment' | 'Rga' | 'RWMap';
269
+ /** Various options to pass the web assembly module to Ditto. */
270
+ type WebAssemblyModule = RequestInfo | URL | Response | BufferSource | WebAssembly.Module | string | null;
271
+
203
272
  /**
204
- * Represents a portion of the document at a specific key-path.
205
- *
206
- * Provides an interface to specify a path to a key in a document that you can
207
- * then call a function on to get the value at the specified key as a specific
208
- * type. You don't create a `DocumentPath` directly but obtain one via the
209
- * {@link Document.path | path} property or the {@link Document.at | at()}
210
- * method of {@link Document}.
273
+ * Available options for {@link init | init()}.
211
274
  */
212
- declare class DocumentPath {
213
- /** The document this path belongs to. */
214
- readonly document: Document;
215
- /** The full document path so far. */
216
- readonly path: string;
275
+ type InitOptions = {
217
276
  /**
218
- * Returns a new document path instance with the passed in key-path or
219
- * index appended.
220
- *
221
- * A key-path can be a single property name or multiple property names
222
- * separated by a dot. Indexes can also be specified as part of the key
223
- * path using the square bracket syntax. The empty string returns a document
224
- * path representing the same portion of the document as the receiver. If a
225
- * key-path starts with a property name and is prefixed by a dot, the dot is
226
- * ignored.
227
- *
228
- * Examples:
229
- *
230
- * - `documentPath.at('mileage')`
231
- * - `documentPath.at('driver.name')`
232
- * - `documentPath.at('passengers[2]')`
233
- * - `documentPath.at('passengers[2].belongings[1].kind')`
234
- * - `documentPath.at('.mileage')`
277
+ * You can explicitly pass the WebAssembly module or its location via the
278
+ * `webAssemblyModule` option. By default, Ditto tries to load the WebAssembly
279
+ * module from the same path where this JavaScript is served.
235
280
  */
236
- at(keyPathOrIndex: string | number): DocumentPath;
237
- /**
281
+ webAssemblyModule?: WebAssemblyModule;
282
+ };
283
+ /**
284
+ * Initializes the whole Ditto module. Needs to be called and complete before
285
+ * any of the Ditto API is used.
286
+ *
287
+ * @param options - Dictionary with global {@link InitOptions | initialization options}.
288
+ */
289
+ declare function init(options?: InitOptions): Promise<void>;
290
+
291
+ /** The log levels supported by Ditto. */
292
+ type LogLevel = 'Error' | 'Warning' | 'Info' | 'Debug' | 'Verbose';
293
+ /**
294
+ * Closure that {@link Logger.setCustomLogCallback} can be set as a custom
295
+ * log callback on {@link Logger}.
296
+ */
297
+ type CustomLogCallback = (logLevel: LogLevel, message: string) => void;
298
+ /**
299
+ * Class with static methods to customize the logging behavior from Ditto and
300
+ * log messages with the Ditto logging infrastructure.
301
+ */
302
+ declare class Logger {
303
+ /**
304
+ * Registers a file path where logs will be written to, whenever Ditto wants
305
+ * to issue a log (on _top_ of emitting the log to the console).
306
+ */
307
+ static readonly logFile?: string;
308
+ /**
309
+ * On Node, registers a file path where logs will be written to, whenever
310
+ * Ditto wants to issue a log (on _top_ of emitting the log to the console).
311
+ * In the browser, this method has no effect.
312
+ *
313
+ * @param path can be `null`, in which case the current logging file, if any,
314
+ * is unregistered, otherwise, the file path must be within an already
315
+ * existing directory.
316
+ */
317
+ static setLogFile(path: string | null): void;
318
+ /**
319
+ * Convenience method, takes the path part of the URL and calls
320
+ * {@link setLogFile | setLogFile()} with it.
321
+ */
322
+ static setLogFileURL(url: URL | undefined): void;
323
+ /** Whether the logger is currently enabled. */
324
+ static get enabled(): boolean;
325
+ /** Enables or disables logging. */
326
+ static set enabled(enabled: boolean);
327
+ /**
328
+ * Represents whether or not emojis should be used as the log level
329
+ * indicator in the logs.
330
+ */
331
+ static get emojiLogLevelHeadingsEnabled(): boolean;
332
+ /**
333
+ * Represents whether or not emojis should be used as the log level
334
+ * indicator in the logs.
335
+ */
336
+ static set emojiLogLevelHeadingsEnabled(emojiLogLevelHeadingsEnabled: boolean);
337
+ /**
338
+ * The minimum log level at which logs will be logged.
339
+ *
340
+ * For example if this is set to `Warning`, then only logs that are logged
341
+ * with the `Warning` or `Error` log levels will be shown.
342
+ */
343
+ static get minimumLogLevel(): LogLevel;
344
+ /**
345
+ * The minimum log level at which logs will be logged.
346
+ *
347
+ * For example if this is set to `Warning`, then only logs that are logged
348
+ * with the `Warning` or `Error` log levels will be shown.
349
+ */
350
+ static set minimumLogLevel(minimumLogLevel: LogLevel);
351
+ /**
352
+ * Returns the current custom log callback, `undefined` by default. See
353
+ * {@link setCustomLogCallback | setCustomLogCallback()} for a detailed
354
+ * description.
355
+ */
356
+ static readonly customLogCallback?: CustomLogCallback;
357
+ /**
358
+ * Registers a custom callback that will be called to report each log entry.
359
+ *
360
+ * @param callback function called for each log entry. `undefined` will
361
+ * unregister any previous callback and stop reporting log entries through
362
+ * callbacks.
363
+ */
364
+ static setCustomLogCallback(callback: CustomLogCallback | undefined): Promise<void>;
365
+ /**
366
+ * Logs the message for the given `level`.
367
+ *
368
+ * @see {@link error | error()}
369
+ * @see {@link warning | warning()}
370
+ * @see {@link info | info()}
371
+ * @see {@link debug | debug()}
372
+ * @see {@link verbose | verbose()}
373
+ */
374
+ static log(level: LogLevel, message: string): void;
375
+ /**
376
+ * Convenience method, same as calling {@link log | log()} with
377
+ * {@link LogLevel} `Error`.
378
+ */
379
+ static error(message: string): void;
380
+ /**
381
+ * Convenience method, same as calling {@link log | log()} with
382
+ * {@link LogLevel} `Warning`.
383
+ */
384
+ static warning(message: string): void;
385
+ /**
386
+ * Convenience method, same as calling {@link log | log()} with
387
+ * {@link LogLevel} `Info`.
388
+ */
389
+ static info(message: string): void;
390
+ /**
391
+ * Convenience method, same as calling {@link log | log()} with
392
+ * {@link LogLevel} `Debug`.
393
+ */
394
+ static debug(message: string): void;
395
+ /**
396
+ * Convenience method, same as calling {@link log | log()} with
397
+ * {@link LogLevel} `Verbose`.
398
+ */
399
+ static verbose(message: string): void;
400
+ private constructor();
401
+ }
402
+
403
+ /** Represents a unique identifier for a {@link Document}. */
404
+ type DocumentIDValue = any;
405
+ /** Represents a unique identifier for a {@link Document}. */
406
+ declare class DocumentID {
407
+ /**
408
+ * Returns the value of the receiver, lazily decoded from its CBOR
409
+ * representation if needed.
410
+ */
411
+ get value(): any;
412
+ /**
413
+ * Returns `false` if validation has been skipped at construction time,
414
+ * otherwise returns `true`. This is mostly for internal use only, you
415
+ * shouldn't need this in client code.
416
+ */
417
+ readonly isValidated: boolean;
418
+ /**
419
+ * Creates a new `DocumentID`.
420
+ *
421
+ * A document ID can be created from any of the following:
422
+ *
423
+ * - `string`
424
+ * - `number` (integer)
425
+ * - `boolean`
426
+ * - `null`
427
+ * - raw data in the form of a JS [Typed Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
428
+ * - `Array` (containing any of the items in this list)
429
+ * - Map (a raw JS `object`, where the keys must be strings and the values
430
+ * can be made up of any of the items in this list)
431
+ *
432
+ * Note that you cannot use floats or other custom types to create a document
433
+ * ID.
434
+ *
435
+ * Document IDs are also limited in size, based on their serialized
436
+ * representation, to 256 bytes. You will receive an error if you try to
437
+ * create a document ID that exceeds the size limit.
438
+ *
439
+ * @param value The value that represents the document identifier.
440
+ * @param skipCBOREncoding If `true, skips CBOR encoding and assumes
441
+ * the passed in `value` is already CBOR encoded. You shouldn't need to ever
442
+ * pass this parameter, it's only used internally for certain edge cases.
443
+ * @param skipValidation If `true, skips validation of the passed in value or
444
+ * CBOR. You shouldn't need to ever pass this parameter, it's only used
445
+ * internally for certain edge cases.
446
+ */
447
+ constructor(value: any, skipCBOREncoding?: boolean, skipValidation?: boolean);
448
+ /**
449
+ * Returns `true` if passed in `documentID` is equal to the receiver,
450
+ * otherwise returns `false`.
451
+ */
452
+ equals(documentID: DocumentID): boolean;
453
+ /**
454
+ * Returns a string representation of the receiver.
455
+ *
456
+ * If you need a string representation to be used directly in a query,
457
+ * please use `toQueryCompatibleString()` instead.
458
+ */
459
+ toString(): string;
460
+ /**
461
+ * Returns a byte representation of the document ID value as base64 string.
462
+ */
463
+ toBase64String(): string;
464
+ /**
465
+ * Returns a query compatible string representation of the receiver.
466
+ *
467
+ * The returned string can be used directly in queries that you use with
468
+ * other Ditto functions. For example you could create a query that was like
469
+ * this:
470
+ *
471
+ * ``` TypeScript
472
+ * collection.find(`_id == ${documentID.toQueryCompatibleString()}`)
473
+ * ```
474
+ */
475
+ toQueryCompatibleString(): string;
476
+ /** @internal */
477
+ toCBOR(): Uint8Array;
478
+ }
479
+ /** @internal */
480
+ declare function validateDocumentIDValue(id: DocumentIDValue): DocumentIDValue;
481
+ /** @internal */
482
+ declare function validateDocumentIDCBOR(idCBOR: Uint8Array): Uint8Array;
483
+
484
+ /**
485
+ * Represents a portion of the document at a specific key-path.
486
+ *
487
+ * Provides an interface to specify a path to a key in a document that you can
488
+ * then call a function on to get the value at the specified key as a specific
489
+ * type. You don't create a `DocumentPath` directly but obtain one via the
490
+ * {@link Document.path | path} property or the {@link Document.at | at()}
491
+ * method of {@link Document}.
492
+ */
493
+ declare class DocumentPath {
494
+ /** The document this path belongs to. */
495
+ readonly document: Document;
496
+ /** The full document path so far. */
497
+ readonly path: string;
498
+ /**
499
+ * Returns a new document path instance with the passed in key-path or
500
+ * index appended.
501
+ *
502
+ * A key-path can be a single property name or multiple property names
503
+ * separated by a dot. Indexes can also be specified as part of the key
504
+ * path using the square bracket syntax. The empty string returns a document
505
+ * path representing the same portion of the document as the receiver. If a
506
+ * key-path starts with a property name and is prefixed by a dot, the dot is
507
+ * ignored.
508
+ *
509
+ * Examples:
510
+ *
511
+ * - `documentPath.at('mileage')`
512
+ * - `documentPath.at('driver.name')`
513
+ * - `documentPath.at('passengers[2]')`
514
+ * - `documentPath.at('passengers[2].belongings[1].kind')`
515
+ * - `documentPath.at('.mileage')`
516
+ */
517
+ at(keyPathOrIndex: string | number): DocumentPath;
518
+ /**
238
519
  * Traverses the document with the key-path represented by the receiver and
239
520
  * returns the corresponding object or value.
240
521
  */
@@ -450,21 +731,44 @@ declare class MutableDocument {
450
731
  }
451
732
 
452
733
  /**
453
- * Part of {@link TransportConfig} type, configuration for listening for TCP
454
- * connections.
455
- */
456
- interface TransportConfigListenTCP {
457
- isEnabled: boolean;
458
- interfaceIP: string;
459
- port: number;
460
- }
461
- /**
462
- * Part of {@link TransportConfig} type, configuration for listening for HTTP,
463
- * including Websocket, connections.
734
+ * Maps a {@link DocumentID} to an array of
735
+ * {@link UpdateResult | update results}. This is the data structure you get
736
+ * when {@link PendingCursorOperation.update | updating} a set of documents
737
+ * with detailed info about the performed updates.
464
738
  */
465
- interface TransportConfigListenHTTP {
466
- isEnabled: boolean;
467
- interfaceIP: string;
739
+ declare class UpdateResultsMap {
740
+ /**
741
+ * Returns an array of {@link UpdateResult | update results} associated with
742
+ * the `documentID` or undefined if not found.
743
+ */
744
+ get(documentIDOrValue: DocumentID | DocumentIDValue): UpdateResult[] | undefined;
745
+ /**
746
+ * Returns all contained keys, i.e. {@link DocumentID | document IDs}
747
+ * contained in this map.
748
+ */
749
+ keys(): DocumentID[];
750
+ /** @internal */
751
+ constructor(documentIDs: DocumentID[], updateResultsByDocumentIDString: object);
752
+ private documentIDs;
753
+ private updateResultsByDocumentIDString;
754
+ }
755
+
756
+ /**
757
+ * Part of {@link TransportConfig} type, configuration for listening for TCP
758
+ * connections.
759
+ */
760
+ interface TransportConfigListenTCP {
761
+ isEnabled: boolean;
762
+ interfaceIP: string;
763
+ port: number;
764
+ }
765
+ /**
766
+ * Part of {@link TransportConfig} type, configuration for listening for HTTP,
767
+ * including Websocket, connections.
768
+ */
769
+ interface TransportConfigListenHTTP {
770
+ isEnabled: boolean;
771
+ interfaceIP: string;
468
772
  port: number;
469
773
  staticContentPath?: string;
470
774
  websocketSync: boolean;
@@ -620,111 +924,6 @@ declare class TransportConfig {
620
924
  static areListenHTTPsEqual(left: TransportConfigListenHTTP, right: TransportConfigListenHTTP): boolean;
621
925
  }
622
926
 
623
- /** @internal */
624
- interface ObserverRemoving {
625
- removeObserver(token: any): any;
626
- }
627
- /** @internal */
628
- type ObserverOptions = {
629
- stopsWhenFinalized?: boolean;
630
- };
631
- /**
632
- * Generic observer handle returned by various observation APIs. The observation
633
- * remains active until the {@link stop | stop()} method is called explicitly or
634
- * the observer instance is garbage collected. Therefore, to keep the observation
635
- * alive, you have to keep a reference to the corresponding observer.
636
- */
637
- declare class Observer {
638
- /** @internal */
639
- readonly observerManager: ObserverRemoving;
640
- /** @internal */
641
- readonly token?: any;
642
- /** @internal */
643
- readonly options?: ObserverOptions;
644
- /** @internal */
645
- constructor(observerManager: ObserverRemoving, token: any, options?: ObserverOptions);
646
- /**
647
- * Returns `true` if the observer has been explicitly stopped via the `stop()`
648
- * method. Otherwise returns `false`.
649
- */
650
- get isStopped(): boolean;
651
- /**
652
- * Stops the observation. Calling this method multiple times has no effect.
653
- */
654
- stop(): void;
655
- private static finalizationRegistry;
656
- private static finalize;
657
- }
658
-
659
- /** @internal */
660
- declare class KeepAlive {
661
- /** @internal */
662
- get isActive(): boolean;
663
- /** @internal */
664
- constructor();
665
- /** @internal */
666
- retain(id: string): void;
667
- /** @internal */
668
- release(id: string): void;
669
- /** @internal */
670
- currentIDs(): string[];
671
- /** @internal */
672
- countForID(id: string): number | null;
673
- private static finalizationRegistry;
674
- private intervalID;
675
- private countsByID;
676
- }
677
-
678
- /** @internal */
679
- type ObserverToken = string;
680
- /** @internal */
681
- type ObserverManagerConstructorOptions = {
682
- keepAlive?: KeepAlive;
683
- register?: (callback: (...args: any[]) => void) => void;
684
- unregister?: () => void;
685
- process?: (...args: any[]) => any[];
686
- };
687
- /** @internal */
688
- declare class ObserverManager {
689
- /** @internal */
690
- readonly id: string;
691
- /** @internal */
692
- readonly keepAlive: KeepAlive | null;
693
- /** @internal */
694
- constructor(id: string, options?: ObserverManagerConstructorOptions);
695
- /** @internal */
696
- addObserver(callback: any): ObserverToken;
697
- /** @internal */
698
- removeObserver(token: ObserverToken): void;
699
- /** @internal */
700
- notify(...args: any[]): void;
701
- /**
702
- * Can be injected and replaced via constructor options.
703
- *
704
- * @abstract
705
- */
706
- protected register(callback: (...args: any[]) => void): void;
707
- /**
708
- * Can be injected and replaced via constructor options.
709
- *
710
- * @abstract
711
- */
712
- protected unregister(): void;
713
- /**
714
- * Can be injected and replaced via constructor options.
715
- *
716
- * @abstract
717
- */
718
- protected process(...args: any[]): any[];
719
- private isRegistered;
720
- private callbacksByToken;
721
- private constructorOptions;
722
- private hasObservers;
723
- private registerIfNeeded;
724
- private unregisterIfNeeded;
725
- private finalize;
726
- }
727
-
728
927
  /**
729
928
  * Provides info about the authentication status.
730
929
  */
@@ -825,6 +1024,8 @@ declare class Authenticator {
825
1024
  /** @internal */
826
1025
  '@ditto.authClientValidityChanged'(isWebValid: boolean, isX509Valid: boolean): void;
827
1026
  /** @internal */
1027
+ close(): void;
1028
+ /** @internal */
828
1029
  protected keepAlive: KeepAlive;
829
1030
  /** @internal */
830
1031
  protected observerManager: ObserverManager;
@@ -834,6 +1035,7 @@ declare class OnlineAuthenticator extends Authenticator {
834
1035
  loginWithToken(token: string, provider: string): Promise<void>;
835
1036
  loginWithUsernameAndPassword(username: string, password: string, provider: string): Promise<void>;
836
1037
  logout(cleanupFn?: (Ditto: any) => void): Promise<void>;
1038
+ close(): void;
837
1039
  readonly authClientPointer: Pointer<FFIAuthClient>;
838
1040
  readonly authenticationHandler: AuthenticationHandler;
839
1041
  private ditto;
@@ -988,474 +1190,633 @@ type Identity = IdentityOfflinePlayground | IdentitySharedKey | IdentityManual |
988
1190
  /** The list of identity types that require activation through an offlineLicenseToken */
989
1191
  declare const IdentityTypesRequiringOfflineLicenseToken: string[];
990
1192
 
1193
+ /** Types of connections that can be established between two peers. */
1194
+ type ConnectionType = 'P2PWiFi' | 'WebSocket' | 'AccessPoint' | 'Bluetooth';
991
1195
  /**
992
- * Describes the direction when sorting a query.
993
- */
994
- type SortDirection = 'ascending' | 'descending';
995
- /**
996
- * Defines the various strategies available when inserting a document into a
997
- * collection.
998
- *
999
- * - `merge`: the existing document will be merged with the document being
1000
- * inserted, if there is a pre-existing document.
1001
- *
1002
- * - `insertIfAbsent`: insert the document only if there is not already a
1003
- * document with the same ID in the store. If there is already a document in
1004
- * the store with the same ID then this will be a no-op.
1196
+ * An opaque address uniquely identifying another peer on the Ditto mesh
1197
+ * network.
1005
1198
  *
1006
- * - `insertDefaultIfAbsent`: insert the document, with its contents treated as
1007
- * default data, only if there is not already a document with the same ID in
1008
- * the store. If there is already a document in the store with the same ID
1009
- * then this will be a no-op. Use this strategy if you want to insert default
1010
- * data for a given document ID, which you want to treat as common initial
1011
- * data amongst all peers and that you expect to be mutated or overwritten in
1012
- * due course.
1013
- */
1014
- type WriteStrategy = 'merge' | 'insertIfAbsent' | 'insertDefaultIfAbsent';
1015
- /**
1016
- * Represents a dictionary of values to be incorporated into a query keyed
1017
- * by the placeholder used within that query. See method
1018
- * {@link Collection.find | find()} of {@link Collection} for more info.
1019
- */
1020
- type QueryArguments = {
1021
- [key: string]: any;
1022
- };
1023
-
1024
- /**
1025
- * The types of attachment fetch events that can be delivered to an attachment
1026
- * fetcher's `callback`.
1027
- */
1028
- type AttachmentFetchEventType = 'Completed' | 'Progress' | 'Deleted';
1029
- /**
1030
- * An attachment fetch event used when the attachment's download has completed.
1031
- */
1032
- type AttachmentFetchEventCompleted = {
1033
- type: 'Completed';
1034
- attachment: Attachment;
1035
- };
1036
- /**
1037
- * An attachment fetch event used when the attachment's download progressed but
1038
- * is not yet complete.
1199
+ * IMPORTANT: You should not rely on the individual components of the address,
1200
+ * those can change at any time. Please use
1201
+ * {@link addressToString | addressToString()} to compare individual addresses
1202
+ * with each other.
1039
1203
  */
1040
- type AttachmentFetchEventProgress = {
1041
- type: 'Progress';
1042
- totalBytes: number | BigInt;
1043
- downloadedBytes: number | BigInt;
1204
+ type Address = {
1205
+ siteId: string;
1206
+ pubkey: Uint8Array;
1044
1207
  };
1045
1208
  /**
1046
- * An attachment fetch event used when the attachment is deleted.
1209
+ * Returns a string representation of the given address. Use this function
1210
+ * to compare multiple addresses or whenever you need the address to be a key
1211
+ * in a hash object.
1047
1212
  */
1048
- type AttachmentFetchEventDeleted = {
1049
- type: 'Deleted';
1213
+ declare function addressToString(address: Address): string;
1214
+ /** Represents a connection between two peers on the Ditto mesh network. */
1215
+ type Connection = {
1216
+ /** Unique identifier for the connection. */
1217
+ id: string;
1218
+ /** Type of transport enabling this connection. */
1219
+ type: ConnectionType;
1220
+ /** The peer key of the peer at one end of the connection. */
1221
+ peer1: Uint8Array;
1222
+ /** The peer key of the peer at one end of the connection. */
1223
+ peer2: Uint8Array;
1224
+ approximateDistanceInMeters?: number;
1050
1225
  };
1051
- /**
1052
- * A representation of the events that can occur in relation to an attachment
1053
- * fetch.
1054
- *
1055
- * There are three different attachment fetch events: `Completed`, `Progress`,
1056
- * or `Deleted`.
1057
- *
1058
- * There will be at most one `Completed` or `Deleted` event per attachment
1059
- * fetch. There can be many `Progress` events delivered for each attachment
1060
- * fetch.
1061
- *
1062
- * Updates relating to an attachment fetch are delivered by registering an
1063
- * {@link AttachmentFetcher} through a call to
1064
- * {@link Collection.fetchAttachment | fetchAttachment()} on a
1065
- * {@link Collection} instance.
1066
- */
1067
- type AttachmentFetchEvent = AttachmentFetchEventCompleted | AttachmentFetchEventProgress | AttachmentFetchEventDeleted;
1068
-
1069
- /**
1070
- * These objects are returned by calls to
1071
- * {@link Collection.fetchAttachment | fetchAttachment()} on {@link Collection}
1072
- * and allow you to stop an in-flight attachment fetch.
1073
- */
1074
- declare class AttachmentFetcher implements PromiseLike<Attachment | null> {
1226
+ /** An instance of Ditto taking part in the Ditto mesh network. */
1227
+ type Peer = {
1075
1228
  /**
1076
- * Returns a promise for the attachment that you can `await`. The promise
1077
- * resolves to either an attachment or `null` if the attachment has been
1078
- * deleted meanwhile. The promise is rejected if an error occurs during
1079
- * the fetch. Note that the `AttachmentFetcher` itself implementes
1080
- * `PromiseLike`, so you can `await` it directly.
1229
+ * Address to contact this peer via Ditto Bus, unique with a Ditto mesh
1230
+ * network.
1081
1231
  */
1082
- readonly attachment: Promise<Attachment | null>;
1232
+ address: Address;
1083
1233
  /**
1084
- * Stops fetching the associated attachment and cleans up any associated
1085
- * resources.
1234
+ * The peer key is a unique identifier for a given peer, equal to or derived
1235
+ * from the cryptographic public key used to authenticate it.
1086
1236
  *
1087
- * Note that you are not required to call `stop()` once your attachment fetch
1088
- * operation has finished. The method primarily exists to allow you to cancel
1089
- * an attachment fetch request while it is ongoing if you no longer wish for
1090
- * the attachment to be made available locally to the device.
1237
+ * NOTE: This will be be empty when a peer is not updated to the latest
1238
+ * version of the SDK.
1091
1239
  */
1092
- stop(): void;
1093
- /** @internal */
1094
- then<TResult1 = any, TResult2 = never>(onfulfilled?: ((value: any) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): PromiseLike<TResult1 | TResult2>;
1095
- /** @internal */
1096
- readonly ditto: Ditto;
1097
- /** @internal */
1098
- readonly token: AttachmentToken;
1099
- /** @internal */
1100
- readonly eventHandler: (attachmentFetchEvent: AttachmentFetchEvent) => void | null;
1101
- /** @internal */
1102
- constructor(ditto: Ditto, token: AttachmentToken, eventHandler?: (attachmentFetchEvent: AttachmentFetchEvent) => void);
1103
- private cancelTokenPromise;
1104
- private static finalizationRegistry;
1105
- private static stopWithContextInfo;
1106
- }
1107
-
1108
- /**
1109
- * Used to subscribe to receive updates from remote peers about matching
1110
- * documents.
1111
- *
1112
- * While {@link Subscription} objects remain in scope they ensure that
1113
- * documents in the collection specified and that match the query provided will
1114
- * try to be kept up-to-date with the latest changes from remote peers.
1115
- */
1116
- declare class Subscription {
1240
+ peerKey: Uint8Array;
1117
1241
  /**
1118
- * The query that the subscription is based on.
1242
+ * The human-readable device name of the peer. This defaults to the hostname
1243
+ * but can be manually set by the application developer of the other peer.
1244
+ * It is not necessarily unique.
1119
1245
  */
1120
- readonly query: string;
1246
+ deviceName: string;
1121
1247
  /**
1122
- * Returns `true` if subscription has been explicitly cancelled, `false`
1123
- * otherwise.
1248
+ * Currently active connections of the peer.
1124
1249
  */
1125
- readonly isCancelled = false;
1250
+ connections: Connection[];
1126
1251
  /**
1127
- * The name of the collection that the subscription is based on.
1252
+ * Indicates whether the peer is connected to Ditto Cloud.
1128
1253
  */
1129
- get collectionName(): string;
1254
+ isConnectedToDittoCloud: boolean;
1255
+ /** The operating system the peer is running on, `undefined` if (yet) unknown. */
1256
+ os?: string;
1257
+ /** The Ditto SDK version the peer is running with, `undefined` if (yet) unknown. */
1258
+ dittoSDKVersion?: string;
1259
+ };
1260
+ /**
1261
+ * Represents the Ditto mesh network of peers and their connections between each
1262
+ * other. The `localPeer` is the entry point, all others are remote peers known
1263
+ * by the local peer (either directly or via other remote peers).
1264
+ */
1265
+ type PresenceGraph = {
1130
1266
  /**
1131
- * Cancels a subscription and releases all associated resources.
1267
+ * Returns the local peer (usually the peer that is represented by the
1268
+ * currently running Ditto instance). The `localPeer` is the entry point, all
1269
+ * others are remote peers known by the local peer (either directly or via
1270
+ * other remote peers).
1132
1271
  */
1133
- cancel(): void;
1134
- /** @internal */
1135
- constructor(collection: Collection, query: string, queryArgsCBOR: Uint8Array | null, orderBys: OrderBy[], limit: number, offset: number);
1272
+ localPeer: Peer;
1136
1273
  /**
1137
- * The collection this subscription belongs to.
1138
- * @internal Because not exposed in any of the other SDKs (yet?).
1274
+ * Returns all remote peers known by the `localPeer`, either directly or via
1275
+ * other remote peers.
1139
1276
  */
1140
- readonly collection: Collection;
1277
+ remotePeers: Peer[];
1141
1278
  /**
1142
- * The corresponding named arguments for {@link query}, if any.
1143
- * @internal Because not exposed in any of the other SDKs (yet?).
1279
+ * Returns the underlying CBOR data if the presence graph has been initialized
1280
+ * with CBOR. All of Ditto API returning a presence graph has this property
1281
+ * set.
1144
1282
  */
1145
- readonly queryArgsCBOR: Uint8Array | null;
1146
- private static finalizationRegistry;
1147
- private static add;
1148
- private static remove;
1149
- private contextInfo;
1150
- }
1151
-
1283
+ underlyingCBOR?: Uint8Array;
1284
+ };
1152
1285
  /**
1153
- * The type that is returned when calling
1154
- * {@link PendingCursorOperation.observeLocal | observeLocal()} on a
1155
- * {@link PendingCursorOperation} object. It handles the logic for calling the
1156
- * event handler that is provided to `observeLocal()` calls.
1157
- *
1158
- * Ditto will prevent the process from exiting as long as there are active live
1159
- * queries (not relevant when running in the browser).
1286
+ * The entrypoint for all actions that relate presence of other peers known by
1287
+ * the current peer, either directly or through other peers.
1160
1288
  *
1161
- * `LiveQuery` objects must be kept in scope for as long as you wish to have
1162
- * your event handler be called when there is an update to a document matching
1163
- * the query you provide. When you no longer want to receive updates about
1164
- * documents matching a query then you must call {@link stop | stop()}.
1289
+ * You don't create one directly but can access it from a particular `Ditto`
1290
+ * instance via its `presence` property.
1165
1291
  */
1166
- declare class LiveQuery {
1167
- /** The query that the live query is based on. */
1168
- readonly query: string;
1169
- /** The arguments belonging to {@link query}. */
1170
- readonly queryArgs: QueryArguments | null;
1171
- /** The name of the collection that the live query is based on. */
1172
- get collectionName(): string;
1173
- /** Returns true if the receiver has been stopped. */
1174
- get isStopped(): boolean;
1292
+ declare class Presence {
1293
+ /** The Ditto instance this object belongs to. */
1294
+ readonly ditto: Ditto;
1175
1295
  /**
1176
- * Stop the live query from delivering updates.
1296
+ * Returns the current presence graph capturing all known peers and
1297
+ * connections between them.
1177
1298
  */
1178
- stop(): void;
1179
- /** @internal */
1180
- readonly limit: number;
1181
- /** @internal */
1182
- readonly offset: number;
1183
- /** @internal */
1184
- readonly collection: Collection;
1185
- /** @internal */
1186
- readonly subscription?: Subscription;
1187
- /** @internal */
1188
- readonly handler: QueryObservationHandler;
1299
+ get graph(): PresenceGraph;
1300
+ /**
1301
+ * Request information about Ditto peers in range of this device.
1302
+ *
1303
+ * This method returns an observer which should be held as long as updates are
1304
+ * required. A newly registered observer will have a peers update delivered to
1305
+ * it immediately. From then on it will be invoked repeatedly when Ditto
1306
+ * devices come and go, or the active connections to them change.
1307
+ */
1308
+ observe(didChangeHandler: (presenceGraph: PresenceGraph) => void): Observer;
1189
1309
  /** @internal */
1190
- constructor(query: string, queryArgs: QueryArguments | null, queryArgsCBOR: Uint8Array | null, orderBys: OrderBy[], limit: number, offset: number, collection: Collection, subscription: Subscription | null, handler: QueryObservationHandler);
1310
+ constructor(ditto: Ditto);
1191
1311
  /** @internal */
1192
- signalNext(): Promise<void>;
1193
- private orderBys;
1194
- private queryArgsCBOR;
1195
- private liveQueryID;
1312
+ close(): void;
1313
+ private observerManager;
1196
1314
  }
1197
1315
 
1316
+ /** Types of connections that can be established between two peers. */
1317
+ type TransportCondition = 'Unknown' | 'OK' | 'GenericFailure' | 'AppInBackground' | 'MDNSFailure' | 'TCPListenFailure' | 'NoBLECentralPermission' | 'NoBLEPeripheralPermission' | 'CannotEstablishConnection' | 'BLEDisabled' | 'NoBLEHardware' | 'WiFiDisabled' | 'TemporarilyUnavailable';
1318
+ /** The source for a transport condition. */
1319
+ type ConditionSource = 'BLE' | 'TCP' | 'AWDL' | 'MDNS';
1198
1320
  /**
1199
- * Maps a {@link DocumentID} to an array of
1200
- * {@link UpdateResult | update results}. This is the data structure you get
1201
- * when {@link PendingCursorOperation.update | updating} a set of documents
1202
- * with detailed info about the performed updates.
1321
+ * Types of connections that can be established between two peers.
1322
+ * @deprecated replaced by {@link ConnectionType}.
1203
1323
  */
1204
- declare class UpdateResultsMap {
1205
- /**
1206
- * Returns an array of {@link UpdateResult | update results} associated with
1207
- * the `documentID` or undefined if not found.
1208
- */
1209
- get(documentIDOrValue: DocumentID | DocumentIDValue): UpdateResult[] | undefined;
1210
- /**
1211
- * Returns all contained keys, i.e. {@link DocumentID | document IDs}
1212
- * contained in this map.
1213
- */
1214
- keys(): DocumentID[];
1215
- /** @internal */
1216
- constructor(documentIDs: DocumentID[], updateResultsByDocumentIDString: object);
1217
- private documentIDs;
1218
- private updateResultsByDocumentIDString;
1219
- }
1220
-
1324
+ type PresenceConnectionType = 'WiFi' | 'WebSocket' | 'AWDL' | 'BLE';
1221
1325
  /**
1222
- * These objects are returned when using
1223
- * {@link Collection.findByID | findByID()} functionality on
1224
- * {@link Collection | collections}.
1225
- *
1226
- * You can either call {@link exec | exec()} on the object to get an immediate
1227
- * return value, or chain calls to update, evict or remove the document.
1228
- *
1229
- * Live queries and subscriptions are only available outside of a transaction.
1326
+ * A peer object with information about an observed peer.
1327
+ * @deprecated replaced by {@link Peer}.
1230
1328
  */
1231
- declare abstract class BasePendingIDSpecificOperation implements PromiseLike<Document | undefined> {
1329
+ type RemotePeer = {
1330
+ networkID: string;
1331
+ deviceName: string;
1332
+ rssi?: number;
1333
+ approximateDistanceInMeters?: number;
1334
+ connections: PresenceConnectionType[];
1335
+ };
1336
+ /**
1337
+ * Ditto is the entry point for accessing Ditto-related functionality.
1338
+ */
1339
+ declare class Ditto {
1232
1340
  /**
1233
- * Removes the document with the matching ID.
1341
+ * Configure a custom identifier for the current device.
1234
1342
  *
1235
- * @returns `true` promise if the document was found and removed. `false`
1236
- * promise if the document wasn't found and therefore wasn't removed.
1343
+ * When using {@link Presence.observe | presence.observe()}, each remote peer is
1344
+ * represented by a short UTF-8 "device name". By default this will be a
1345
+ * truncated version of the device's hostname. It does not need to be unique
1346
+ * among peers. Configure the device name before calling
1347
+ * {@link startSync | startSync()}. If it is too long it may be truncated.
1237
1348
  */
1238
- abstract remove(): Promise<boolean>;
1349
+ deviceName: string;
1350
+ /** Returns a string identifying the version of the Ditto SDK. */
1351
+ get sdkVersion(): string;
1239
1352
  /**
1240
- * Evicts the document with the matching ID.
1241
- *
1242
- * @returns `true` promise if the document was found and evicted. `false`
1243
- * promise if the document wasn't found and therefore wasn't evicted.
1353
+ * The (validated) identity this Ditto instance was initialized with.
1244
1354
  */
1245
- abstract evict(): Promise<boolean>;
1355
+ readonly identity: Identity;
1246
1356
  /**
1247
- * Updates the document with the matching ID.
1248
- *
1249
- * @param closure A closure that gets called with the document matching the
1250
- * ID. If found, the document is a {@link MutableDocument}, so you can call
1251
- * update-related functions on it. If the document is not found then the value
1252
- * provided to the closure will be `undefined`.
1253
- *
1254
- * @return An array promise of {@link UpdateResult | update results} that
1255
- * describe the updates that were performed on the document.
1357
+ * The path this Ditto instance was initialized with, if no path was given at
1358
+ * construction time, the default value is returned (see constructor).
1256
1359
  */
1257
- abstract update(closure: (document: MutableDocument) => void): Promise<UpdateResult[]>;
1258
- /** The ID of the document this operation operates on. */
1259
- readonly documentID: DocumentID;
1260
- /** The collection the receiver is operating on. */
1261
- readonly collection: CollectionInterface;
1360
+ readonly path: string;
1262
1361
  /**
1263
- * Executes the find operation to return the document with the matching ID.
1264
- *
1265
- * @returns The {@link Document} promise with the ID provided in the
1266
- * {@link Collection.findByID | findByID()} call or `undefined` if the document was
1267
- * not found.
1362
+ * Provides access to the SDK's store functionality.
1268
1363
  */
1269
- exec(): Promise<Document | undefined>;
1270
- /** @internal */
1271
- constructor(documentID: DocumentID, collection: CollectionInterface);
1272
- /** @internal */
1273
- then<TResult1 = any, TResult2 = never>(onfulfilled?: ((value: any) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): PromiseLike<TResult1 | TResult2>;
1274
- /** @internal */
1275
- get query(): string;
1276
- protected documentIDCBOR: Uint8Array;
1277
- }
1278
-
1279
- type UpsertOptions = {
1280
- writeStrategy?: WriteStrategy;
1281
- };
1282
- interface CollectionInterface {
1283
- /** The name of the collection. */
1284
- readonly name: string;
1364
+ readonly store: Store;
1285
1365
  /**
1286
- * The store this collection belongs to.
1287
- * @internal
1366
+ * Provides access to the SDK's presence functionality.
1288
1367
  */
1289
- readonly store: Store;
1368
+ readonly presence: Presence;
1290
1369
  /**
1291
- * Search for documents in this collection using the provided query string.
1370
+ * Provides access to authentication methods for logging on to Ditto Cloud.
1371
+ */
1372
+ readonly auth: Authenticator;
1373
+ /**
1374
+ * The site ID that the instance of `Ditto` is using as part of its identity.
1375
+ */
1376
+ readonly siteID: number | BigInt;
1377
+ /**
1378
+ * Returns `true` if an offline license token has been set, otherwise returns `false`.
1292
1379
  *
1293
- * @param query The query to run against the collection.
1294
- * @param queryArgs These arguments replace placeholders in the provided
1295
- * query.
1380
+ * @see {@link setOfflineOnlyLicenseToken | setOfflineOnlyLicenseToken()}
1296
1381
  */
1297
- find(query: string, queryArgs?: QueryArguments): BasePendingCursorOperation;
1382
+ readonly isActivated: boolean;
1298
1383
  /**
1299
- * Convenience method, equivalent to calling {@link find | find()} and passing
1300
- * the query `"true"`.
1384
+ * `true` once {@link close | Ditto.close()} has been called, otherwise
1385
+ * `false`.
1301
1386
  */
1302
- findAll(): BasePendingCursorOperation;
1387
+ get isClosed(): boolean;
1303
1388
  /**
1304
- * Find documents given a specific ID.
1389
+ * Returns `true` if sync is active, otherwise returns `false`. Use
1390
+ * {@link startSync | startSync()} to activate and {@link stopSync | stopSync()}
1391
+ * to deactivate sync.
1392
+ */
1393
+ readonly isSyncActive: boolean;
1394
+ /**
1395
+ * Initializes a new `Ditto` instance.
1305
1396
  *
1306
- * Use the returned cursor instance to chain operations on the search result.
1397
+ * **NOTE**: The `sharedKey` identity is only supported for Node environments,
1398
+ * using this to create a Ditto instance in the web browser will throw an
1399
+ * exception.
1307
1400
  *
1308
- * @param id The document's identifier
1401
+ * @param identity - Identity for the new Ditto instance, defaults to
1402
+ * `offlinePlayground` with `appID` being the empty string `''`.
1403
+ *
1404
+ * @param path - On Node, `path` corresponds to a real directory
1405
+ * on the file system (intermediate directories are created if needed). In the
1406
+ * browser, `path` is used as an internal namespace for the in-memory storage.
1407
+ * Defaults to `"ditto"`.
1408
+ *
1409
+ * @see {@link Ditto.identity}
1410
+ * @see {@link Ditto.path}
1309
1411
  */
1310
- findByID(id: DocumentID | DocumentIDValue): BasePendingIDSpecificOperation;
1412
+ constructor(identity?: Identity, path?: string);
1311
1413
  /**
1312
- * TEMPORARY: helper to deal with non-canonical IDs.
1414
+ * Check if the current environment supports running Ditto.
1313
1415
  *
1314
- * @internal
1416
+ * Required APIs include:
1417
+ *
1418
+ * - `BigInt`
1419
+ * - `FinalizationRegistry`
1420
+ * - `WeakRef`
1421
+ *
1422
+ * Internet Explorer is not supported.
1423
+ *
1424
+ * @returns true if the environment is supported
1315
1425
  */
1316
- findByIDCBOR(idCBOR: Uint8Array): BasePendingIDSpecificOperation;
1426
+ static isEnvironmentSupported(): boolean;
1317
1427
  /**
1318
- * Inserts a new document into the collection and returns its ID. If the
1319
- * document already exists, the contents of both are merged by default. You
1320
- * can change this by providing a different `writeStrategy` via `options`.
1428
+ * Activate a `Ditto` instance by setting an offline only license token. You cannot initiate sync
1429
+ * with `Ditto` before you have activated it. The offline license token is only valid for identities
1430
+ * of type `development`, `manual`, `offlinePlayground`, and `sharedKey`.
1321
1431
  *
1322
- * @param value The content of the document to be inserted or updated.
1323
- * @param options.writeStrategy Specifies the desired strategy for inserting a
1324
- * document, defaults to `'merge'`.
1432
+ * @param licenseToken the license token to activate the `Ditto` instance
1433
+ * with. You can find yours on the [Ditto portal](https://portal.ditto.live).
1325
1434
  */
1326
- upsert(value: DocumentValue, options: UpsertOptions): Promise<DocumentID>;
1327
- }
1328
-
1329
- declare abstract class BasePendingCursorOperation implements PromiseLike<Document[]> {
1435
+ setOfflineOnlyLicenseToken(licenseToken: string): void;
1330
1436
  /**
1331
- * Removes all documents that match the query generated by the preceding
1332
- * function chaining.
1437
+ * Returns the current transport configuration, frozen. If you want to modify
1438
+ * the transport config, make a {@link TransportConfig.copy | copy} first. Or
1439
+ * use the {@link updateTransportConfig | updateTransportConfig()}
1440
+ * convenience method. By default peer-to-peer transports (Bluetooth, WiFi,
1441
+ * and AWDL) are enabled if available in the current environment
1442
+ * (Web, Node, OS, etc.).
1333
1443
  *
1334
- * @returns An array promise containing the IDs of the documents that were
1335
- * removed.
1444
+ * @see {@link setTransportConfig | setTransportConfig()}
1445
+ * @see {@link updateTransportConfig | updateTransportConfig()}
1336
1446
  */
1337
- abstract remove(): Promise<DocumentID[]>;
1447
+ readonly transportConfig: TransportConfig;
1338
1448
  /**
1339
- * Evicts all documents that match the query generated by the preceding
1340
- * function chaining.
1449
+ * Assigns a new transports configuration. By default peer-to-peer transports
1450
+ * (Bluetooth, WiFi, and AWDL) are enabled. You may use this method to alter
1451
+ * the configuration at any time, however sync will not begin until
1452
+ * {@link startSync | startSync()} is called.
1341
1453
  *
1342
- * @return An array promise containing the IDs of the documents that were
1343
- * evicted.
1454
+ * @see {@link transportConfig}
1455
+ * @see {@link updateTransportConfig | updateTransportConfig()}
1344
1456
  */
1345
- abstract evict(): Promise<DocumentID[]>;
1457
+ setTransportConfig(transportConfig: TransportConfig): void;
1346
1458
  /**
1347
- * Updates documents that match the query generated by the preceding function
1348
- * chaining.
1459
+ * Convenience method for updating the transport config. Creates a copy of the
1460
+ * current transport config, passes that copy to the `update` closure,
1461
+ * allowing it to mutate as needed, and sets that updated copy afterwards.
1462
+ */
1463
+ updateTransportConfig(update: (transportConfig: TransportConfig) => void): Ditto;
1464
+ /**
1465
+ * Starts the network transports. Ditto will connect to other devices.
1349
1466
  *
1350
- * @param closure A closure that gets called with all of the documents
1351
- * matching the query. The documents are instances of {@link MutableDocument}
1352
- * so you can call update-related functions on them.
1467
+ * By default Ditto will enable all peer-to-peer transport types. On **Node**,
1468
+ * this means BluetoothLE, WiFi/LAN, and AWDL. On the **Web**, only connecting
1469
+ * via Websockets is supported. The network configuration can be
1470
+ * customized with {@link updateTransportConfig | updateTransportConfig()}
1471
+ * or replaced entirely with {@link setTransportConfig | setTransportConfig()}.
1353
1472
  *
1354
- * @returns An {@link UpdateResultsMap} promise mapping document IDs to lists
1355
- * of {@link UpdateResult | update results} that describe the updates that
1356
- * were performed for each document.
1473
+ *
1474
+ * Ditto will prevent the process from exiting until sync is stopped (not
1475
+ * relevant when running in the browser).
1476
+ *
1477
+ * **NOTE**: the BluetoothLE transport on Linux is experimental, this
1478
+ * method panics if no BluetoothLE hardware is available. Therefore, contrary
1479
+ * to the above, the BluetoothLE transport is temporarily disabled by default
1480
+ * on Linux.
1481
+ *
1482
+ * @see {@link isSyncActive}
1483
+ * @see {@link stopSync | stopSync()}
1357
1484
  */
1358
- abstract update(closure: (documents: MutableDocument[]) => void): Promise<UpdateResultsMap>;
1359
- /** The query the receiver is operating with. */
1360
- readonly query: string;
1361
- /** The named arguments for the {@link query}. */
1362
- readonly queryArgs: QueryArguments | null;
1363
- /** The collection the receiver is operating on. */
1364
- readonly collection: CollectionInterface;
1485
+ startSync(): void;
1365
1486
  /**
1366
- * Sorts the documents that match the query provided in the preceding
1367
- * `find`-like function call.
1368
- *
1369
- * @param query The query specifies the logic to be used when sorting the
1370
- * matching documents.
1487
+ * Stops all network transports.
1371
1488
  *
1372
- * @param direction Specify whether you want the sorting order to be
1373
- * `Ascending` or `Descending`.
1489
+ * You may continue to use the database locally but no data will sync to or
1490
+ * from other devices.
1374
1491
  *
1375
- * @return A cursor that you can chain further function calls and then either
1376
- * get the matching documents immediately or get updates about them over time.
1492
+ * @see {@link isSyncActive}
1493
+ * @see {@link startSync | startSync()}
1377
1494
  */
1378
- sort(propertyPath: string, direction?: SortDirection): BasePendingCursorOperation;
1495
+ stopSync(): void;
1379
1496
  /**
1380
- * Offsets the resulting set of matching documents.
1497
+ * Registers an observer for info about Ditto peers in range of this device.
1381
1498
  *
1382
- * This is useful if you aren't interested in the first N matching documents
1383
- * for one reason or another. For example, you might already have queried the
1384
- * collection and obtained the first 20 matching documents and so you might
1385
- * want to run the same query as you did previously but ignore the first 20
1386
- * matching documents, and that is when you would use `offset`.
1499
+ * Ditto will prevent the process from exiting as long as there are active
1500
+ * peers observers (not relevant when running in the browser).
1387
1501
  *
1388
- * @param offset The number of matching documents that you want the eventual
1389
- * resulting set of matching documents to be offset by (and thus not include).
1502
+ * @param callback called immediately with the current state of peers
1503
+ * in range and whenever that state changes. Then it will be invoked
1504
+ * repeatedly when Ditto devices come and go, or the active connections to
1505
+ * them change.
1390
1506
  *
1391
- * @return A cursor that you can chain further function calls and then either
1392
- * get the matching documents immediately or get updates about them over time.
1507
+ * @deprecated please use {@link Presence.observe | presence.observe()} instead.
1393
1508
  */
1394
- offset(offset: number): BasePendingCursorOperation;
1509
+ observePeers(callback: (peersData: RemotePeer[]) => void): Observer;
1395
1510
  /**
1396
- * Limits the number of documents that get returned when querying a collection
1397
- * for matching documents.
1511
+ * Register observer for changes of underlying transport conditions.
1398
1512
  *
1399
- * @param limit The maximum number of documents that will be returned.
1513
+ * Ditto will prevent the process from exiting as long as there are active
1514
+ * transport conditions observers (not relevant when running in the browser).
1400
1515
  *
1401
- * @return A cursor that you can chain further function calls and then either
1402
- * get the matching documents immediately or get updates about them over time.
1516
+ * @param callback called when underlying transport conditions change with
1517
+ * the changed `condition` and it's `source`.
1403
1518
  */
1404
- limit(limit: number): BasePendingCursorOperation;
1519
+ observeTransportConditions(callback: (condition: TransportCondition, source: ConditionSource) => void): Observer;
1405
1520
  /**
1406
- * Executes the query generated by the preceding function chaining and return
1407
- * the list of matching documents.
1521
+ * Removes all sync metadata for any remote peers which aren't currently
1522
+ * connected. This method shouldn't usually be called. Manually running
1523
+ * garbage collection often will result in slower sync times. Ditto
1524
+ * automatically runs a garbage a collection process in the background at
1525
+ * optimal times.
1408
1526
  *
1409
- * @returns An array promise containing {@link Document | documents} matching
1410
- * the query generated by the preceding function chaining.
1527
+ * Manually running garbage collection is typically only useful during testing
1528
+ * if large amounts of data are being generated. Alternatively, if an entire
1529
+ * data set is to be evicted and it's clear that maintaining this metadata
1530
+ * isn't necessary, then garbage collection could be run after evicting the
1531
+ * old data.
1532
+ *
1533
+ * Only available in Node environments at the moment, no-op in the browser.
1411
1534
  */
1412
- exec(): Promise<Document[]>;
1535
+ runGarbageCollection(): void;
1413
1536
  /**
1414
- * Updates documents that match the query generated by the preceding function
1415
- * chaining.
1537
+ * Explicitly opt-in to disabling the ability to sync with Ditto peers running
1538
+ * any version of the SDK in the v3 (or lower) series of releases.
1416
1539
  *
1417
- * @param closure A closure that gets called with all of the documents
1418
- * matching the query. The documents are instances of {@link MutableDocument}
1419
- * so you can call update-related functions on them.
1420
- * @param writeTransactionX a transaction to perform the operation in.
1540
+ * Assuming this succeeds then this peer will only be able to sync with other
1541
+ * peers using SDKs in the v4 (or higher) series of releases. Note that this
1542
+ * disabling of sync spreads to peers that sync with a peer that has disabled,
1543
+ * or has (transitively) had disabled, syncing with v3 SDK peers.
1544
+ */
1545
+ disableSyncWithV3(): void;
1546
+ /**
1547
+ * Shut down Ditto and release all resources.
1421
1548
  *
1422
- * @returns An {@link UpdateResultsMap} promise mapping document IDs to lists
1423
- * of {@link UpdateResult | update results} that describe the updates that
1424
- * were performed for each document.
1425
- * @internal
1549
+ * Must be called before recreating a Ditto instance that uses the same
1550
+ * persistence directory.
1426
1551
  */
1427
- updateWithTransaction(closure: (documents: MutableDocument[]) => void, writeTransactionX: Pointer<FFIWriteTransaction>): Promise<UpdateResultsMap>;
1428
- /** @internal */
1429
- constructor(query: string, queryArgs: QueryArguments | null, collection: CollectionInterface);
1430
- /** @internal */
1431
- then<TResult1 = any, TResult2 = never>(onfulfilled?: ((value: any) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): PromiseLike<TResult1 | TResult2>;
1432
- /** @internal */
1433
- protected queryArgsCBOR: Uint8Array | null;
1434
- /** @internal */
1435
- protected currentLimit: number;
1436
- /** @internal */
1437
- protected currentOffset: number;
1552
+ close(): Promise<void>;
1438
1553
  /** @internal */
1439
- protected orderBys: OrderBy[];
1440
- }
1441
-
1442
- /**
1443
- * An object that describes how a document's position in a live query's list of
1444
- * matching documents has changed since the previous live query event.
1445
- */
1446
- interface LiveQueryMove {
1554
+ keepAlive: KeepAlive;
1447
1555
  /**
1448
- * The index of the document in the list of matching documents from the
1449
- * previous live query event.
1450
- */
1451
- readonly from: number;
1556
+ * The number of operations pending before the Ditto instance can be closed.
1557
+ *
1558
+ * For testing purposes only.
1559
+ * @internal */
1560
+ get numPendingOperations(): number;
1452
1561
  /**
1453
- * The index of the document in the list of matching documents from the new
1454
- * live query event.
1455
- */
1456
- readonly to: number;
1457
- }
1458
- /** @internal */
1562
+ * Makes sure that the closure is executed only if the Ditto instance hasn't
1563
+ * been closed yet.
1564
+ *
1565
+ * @param closure the synchronous closure to execute.
1566
+ * @returns the result of the closure.
1567
+ * @throws if the Ditto instance was closed before calling this method.
1568
+ * @internal */
1569
+ deferClose<T>(closure: () => T): T;
1570
+ /**
1571
+ * Makes sure that the closure is executed to completion before the Ditto
1572
+ * instance is closed.
1573
+ *
1574
+ * Any calls to {@link close | `Ditto.close()`} will wait until the closure
1575
+ * has completed before closing the Ditto instance.
1576
+ *
1577
+ * @param closure the asynchronous closure to execute.
1578
+ * @returns the result of the closure.
1579
+ * @throws if the Ditto instance was closed before calling this method.
1580
+ * @internal */
1581
+ deferCloseAsync<T>(closure: () => Promise<T>): Promise<T>;
1582
+ private sync;
1583
+ private _isClosed;
1584
+ private deferCloseAllowed;
1585
+ private isWebValid;
1586
+ private isX509Valid;
1587
+ private presenceManager;
1588
+ private transportConditionsManager;
1589
+ /** Set of pending operations that need to complete before the Ditto instance can be closed in a safe manner. */
1590
+ private pendingOperations;
1591
+ private authClientValidityChanged;
1592
+ private validateIdentity;
1593
+ private setSyncActive;
1594
+ private makeDefaultTransportConfig;
1595
+ }
1596
+ /** @internal */
1597
+ declare const checkAPIs: (_globalObject?: Window | typeof globalThis) => boolean;
1598
+
1599
+ /**
1600
+ * Represents an attachment and can be used to insert the associated attachment
1601
+ * into a document at a specific key-path. You can't instantiate an attachment
1602
+ * directly, please use the {@link Collection.newAttachment | newAttachment()}
1603
+ * method of {@link Collection} instead.
1604
+ */
1605
+ declare class Attachment {
1606
+ /** @internal */
1607
+ readonly ditto: Ditto;
1608
+ /** @internal */
1609
+ readonly token: AttachmentToken;
1610
+ /** The attachment's metadata. */
1611
+ get metadata(): {
1612
+ [key: string]: string;
1613
+ };
1614
+ /**
1615
+ * Returns the attachment's data.
1616
+ */
1617
+ getData(): Promise<Uint8Array>;
1618
+ /**
1619
+ * Copies the attachment to the specified file path. Node-only,
1620
+ * throws in the browser.
1621
+ *
1622
+ * @param path The path that the attachment should be copied to.
1623
+ */
1624
+ copyToPath(path: string): Promise<void>;
1625
+ /** @internal */
1626
+ constructor(ditto: Ditto, token: AttachmentToken);
1627
+ }
1628
+
1629
+ /**
1630
+ * The types of attachment fetch events that can be delivered to an attachment
1631
+ * fetcher's `callback`.
1632
+ */
1633
+ type AttachmentFetchEventType = 'Completed' | 'Progress' | 'Deleted';
1634
+ /**
1635
+ * An attachment fetch event used when the attachment's download has completed.
1636
+ */
1637
+ type AttachmentFetchEventCompleted = {
1638
+ type: 'Completed';
1639
+ attachment: Attachment;
1640
+ };
1641
+ /**
1642
+ * An attachment fetch event used when the attachment's download progressed but
1643
+ * is not yet complete.
1644
+ */
1645
+ type AttachmentFetchEventProgress = {
1646
+ type: 'Progress';
1647
+ totalBytes: number | BigInt;
1648
+ downloadedBytes: number | BigInt;
1649
+ };
1650
+ /**
1651
+ * An attachment fetch event used when the attachment is deleted.
1652
+ */
1653
+ type AttachmentFetchEventDeleted = {
1654
+ type: 'Deleted';
1655
+ };
1656
+ /**
1657
+ * A representation of the events that can occur in relation to an attachment
1658
+ * fetch.
1659
+ *
1660
+ * There are three different attachment fetch events: `Completed`, `Progress`,
1661
+ * or `Deleted`.
1662
+ *
1663
+ * There will be at most one `Completed` or `Deleted` event per attachment
1664
+ * fetch. There can be many `Progress` events delivered for each attachment
1665
+ * fetch.
1666
+ *
1667
+ * Updates relating to an attachment fetch are delivered by registering an
1668
+ * {@link AttachmentFetcher} through a call to
1669
+ * {@link Collection.fetchAttachment | fetchAttachment()} on a
1670
+ * {@link Collection} instance.
1671
+ */
1672
+ type AttachmentFetchEvent = AttachmentFetchEventCompleted | AttachmentFetchEventProgress | AttachmentFetchEventDeleted;
1673
+
1674
+ /**
1675
+ * These objects are returned by calls to
1676
+ * {@link Collection.fetchAttachment | fetchAttachment()} on {@link Collection}
1677
+ * and allow you to stop an in-flight attachment fetch.
1678
+ */
1679
+ declare class AttachmentFetcher implements PromiseLike<Attachment | null> {
1680
+ /**
1681
+ * Returns a promise for the attachment that you can `await`. The promise
1682
+ * resolves to either an attachment or `null` if the attachment has been
1683
+ * deleted meanwhile. The promise is rejected if an error occurs during
1684
+ * the fetch. Note that the `AttachmentFetcher` itself implementes
1685
+ * `PromiseLike`, so you can `await` it directly.
1686
+ */
1687
+ readonly attachment: Promise<Attachment | null>;
1688
+ /**
1689
+ * Stops fetching the associated attachment and cleans up any associated
1690
+ * resources.
1691
+ *
1692
+ * Note that you are not required to call `stop()` once your attachment fetch
1693
+ * operation has finished. The method primarily exists to allow you to cancel
1694
+ * an attachment fetch request while it is ongoing if you no longer wish for
1695
+ * the attachment to be made available locally to the device.
1696
+ */
1697
+ stop(): void;
1698
+ /** @internal */
1699
+ then<TResult1 = any, TResult2 = never>(onfulfilled?: ((value: any) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): PromiseLike<TResult1 | TResult2>;
1700
+ /** @internal */
1701
+ readonly ditto: Ditto;
1702
+ /** @internal */
1703
+ readonly token: AttachmentToken;
1704
+ /** @internal */
1705
+ readonly eventHandler: (attachmentFetchEvent: AttachmentFetchEvent) => void | null;
1706
+ /** @internal */
1707
+ constructor(ditto: Ditto, token: AttachmentToken, eventHandler?: (attachmentFetchEvent: AttachmentFetchEvent) => void);
1708
+ private cancelTokenPromise;
1709
+ private static finalizationRegistry;
1710
+ private static stopWithContextInfo;
1711
+ }
1712
+
1713
+ /**
1714
+ * Used to subscribe to receive updates from remote peers about matching
1715
+ * documents.
1716
+ *
1717
+ * While {@link Subscription} objects remain in scope they ensure that
1718
+ * documents in the collection specified and that match the query provided will
1719
+ * try to be kept up-to-date with the latest changes from remote peers.
1720
+ */
1721
+ declare class Subscription {
1722
+ /**
1723
+ * The query that the subscription is based on.
1724
+ */
1725
+ readonly query: string;
1726
+ /**
1727
+ * Returns `true` if subscription has been explicitly cancelled, `false`
1728
+ * otherwise.
1729
+ */
1730
+ readonly isCancelled = false;
1731
+ /**
1732
+ * The name of the collection that the subscription is based on.
1733
+ */
1734
+ get collectionName(): string;
1735
+ /**
1736
+ * Cancels a subscription and releases all associated resources.
1737
+ */
1738
+ cancel(): void;
1739
+ /** @internal */
1740
+ constructor(collection: Collection, query: string, queryArgsCBOR: Uint8Array | null, orderBys: OrderBy[], limit: number, offset: number);
1741
+ /**
1742
+ * The collection this subscription belongs to.
1743
+ * @internal Because not exposed in any of the other SDKs (yet?).
1744
+ */
1745
+ readonly collection: Collection;
1746
+ /**
1747
+ * The corresponding named arguments for {@link query}, if any.
1748
+ * @internal Because not exposed in any of the other SDKs (yet?).
1749
+ */
1750
+ readonly queryArgsCBOR: Uint8Array | null;
1751
+ private static finalizationRegistry;
1752
+ private static add;
1753
+ private static remove;
1754
+ private contextInfo;
1755
+ }
1756
+
1757
+ /**
1758
+ * The type that is returned when calling
1759
+ * {@link PendingCursorOperation.observeLocal | observeLocal()} on a
1760
+ * {@link PendingCursorOperation} object. It handles the logic for calling the
1761
+ * event handler that is provided to `observeLocal()` calls.
1762
+ *
1763
+ * Ditto will prevent the process from exiting as long as there are active live
1764
+ * queries (not relevant when running in the browser).
1765
+ *
1766
+ * `LiveQuery` objects must be kept in scope for as long as you wish to have
1767
+ * your event handler be called when there is an update to a document matching
1768
+ * the query you provide. When you no longer want to receive updates about
1769
+ * documents matching a query then you must call {@link stop | stop()}.
1770
+ */
1771
+ declare class LiveQuery {
1772
+ /** The query that the live query is based on. */
1773
+ readonly query: string;
1774
+ /** The arguments belonging to {@link query}. */
1775
+ readonly queryArgs: QueryArguments | null;
1776
+ /** The name of the collection that the live query is based on. */
1777
+ get collectionName(): string;
1778
+ /** Returns true if the receiver has been stopped. */
1779
+ get isStopped(): boolean;
1780
+ /**
1781
+ * Stop the live query from delivering updates.
1782
+ */
1783
+ stop(): void;
1784
+ /** @internal */
1785
+ readonly limit: number;
1786
+ /** @internal */
1787
+ readonly offset: number;
1788
+ /** @internal */
1789
+ readonly collection: Collection;
1790
+ /** @internal */
1791
+ readonly subscription?: Subscription;
1792
+ /** @internal */
1793
+ readonly handler: QueryObservationHandler;
1794
+ /** @internal */
1795
+ constructor(query: string, queryArgs: QueryArguments | null, queryArgsCBOR: Uint8Array | null, orderBys: OrderBy[], limit: number, offset: number, collection: Collection, subscription: Subscription | null, handler: QueryObservationHandler);
1796
+ /** @internal */
1797
+ signalNext(): Promise<void>;
1798
+ private orderBys;
1799
+ private queryArgsCBOR;
1800
+ private liveQueryID;
1801
+ }
1802
+
1803
+ /**
1804
+ * An object that describes how a document's position in a live query's list of
1805
+ * matching documents has changed since the previous live query event.
1806
+ */
1807
+ interface LiveQueryMove {
1808
+ /**
1809
+ * The index of the document in the list of matching documents from the
1810
+ * previous live query event.
1811
+ */
1812
+ readonly from: number;
1813
+ /**
1814
+ * The index of the document in the list of matching documents from the new
1815
+ * live query event.
1816
+ */
1817
+ readonly to: number;
1818
+ }
1819
+ /** @internal */
1459
1820
  interface LiveQueryEventUpdateParams {
1460
1821
  oldDocuments: Document[];
1461
1822
  insertions: number[];
@@ -1673,21 +2034,79 @@ declare class PendingCursorOperation extends BasePendingCursorOperation {
1673
2034
  }
1674
2035
 
1675
2036
  /**
1676
- * The closure that is called whenever a single documunent covered by a
1677
- * live query changes.
1678
- */
1679
- type SingleObservationHandler = (document: Document | null, event: SingleDocumentLiveQueryEvent, signalNext?: () => void) => void | Promise<void>;
1680
- /**
1681
- * These objects are returned when using {@link Collection.findByID | findByID()}
1682
- * functionality on {@link Collection | collections}.
2037
+ * These objects are returned when using
2038
+ * {@link Collection.findByID | findByID()} functionality on
2039
+ * {@link Collection | collections}.
1683
2040
  *
1684
2041
  * You can either call {@link exec | exec()} on the object to get an immediate
1685
- * return value, or you can establish either a live query or a subscription,
1686
- * which both work over time.
2042
+ * return value, or chain calls to update, evict or remove the document.
1687
2043
  *
1688
- * A live query, established by calling
1689
- * {@link PendingIDSpecificOperation.observeLocal | observeLocal()}, will notify
1690
- * you every time there's an update to the document with the ID you provided in
2044
+ * Live queries and subscriptions are only available outside of a transaction.
2045
+ */
2046
+ declare abstract class BasePendingIDSpecificOperation implements PromiseLike<Document | undefined> {
2047
+ /**
2048
+ * Removes the document with the matching ID.
2049
+ *
2050
+ * @returns `true` promise if the document was found and removed. `false`
2051
+ * promise if the document wasn't found and therefore wasn't removed.
2052
+ */
2053
+ abstract remove(): Promise<boolean>;
2054
+ /**
2055
+ * Evicts the document with the matching ID.
2056
+ *
2057
+ * @returns `true` promise if the document was found and evicted. `false`
2058
+ * promise if the document wasn't found and therefore wasn't evicted.
2059
+ */
2060
+ abstract evict(): Promise<boolean>;
2061
+ /**
2062
+ * Updates the document with the matching ID.
2063
+ *
2064
+ * @param closure A closure that gets called with the document matching the
2065
+ * ID. If found, the document is a {@link MutableDocument}, so you can call
2066
+ * update-related functions on it. If the document is not found then the value
2067
+ * provided to the closure will be `undefined`.
2068
+ *
2069
+ * @return An array promise of {@link UpdateResult | update results} that
2070
+ * describe the updates that were performed on the document.
2071
+ */
2072
+ abstract update(closure: (document: MutableDocument) => void): Promise<UpdateResult[]>;
2073
+ /** The ID of the document this operation operates on. */
2074
+ readonly documentID: DocumentID;
2075
+ /** The collection the receiver is operating on. */
2076
+ readonly collection: CollectionInterface;
2077
+ /**
2078
+ * Executes the find operation to return the document with the matching ID.
2079
+ *
2080
+ * @returns The {@link Document} promise with the ID provided in the
2081
+ * {@link Collection.findByID | findByID()} call or `undefined` if the document was
2082
+ * not found.
2083
+ */
2084
+ exec(): Promise<Document | undefined>;
2085
+ /** @internal */
2086
+ constructor(documentID: DocumentID, collection: CollectionInterface);
2087
+ /** @internal */
2088
+ then<TResult1 = any, TResult2 = never>(onfulfilled?: ((value: any) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): PromiseLike<TResult1 | TResult2>;
2089
+ /** @internal */
2090
+ get query(): string;
2091
+ protected documentIDCBOR: Uint8Array;
2092
+ }
2093
+
2094
+ /**
2095
+ * The closure that is called whenever a single documunent covered by a
2096
+ * live query changes.
2097
+ */
2098
+ type SingleObservationHandler = (document: Document | null, event: SingleDocumentLiveQueryEvent, signalNext?: () => void) => void | Promise<void>;
2099
+ /**
2100
+ * These objects are returned when using {@link Collection.findByID | findByID()}
2101
+ * functionality on {@link Collection | collections}.
2102
+ *
2103
+ * You can either call {@link exec | exec()} on the object to get an immediate
2104
+ * return value, or you can establish either a live query or a subscription,
2105
+ * which both work over time.
2106
+ *
2107
+ * A live query, established by calling
2108
+ * {@link PendingIDSpecificOperation.observeLocal | observeLocal()}, will notify
2109
+ * you every time there's an update to the document with the ID you provided in
1691
2110
  * the preceding {@link Collection.findByID | findByID()} call.
1692
2111
  *
1693
2112
  * A subscription, established by calling {@link PendingIDSpecificOperation.subscribe | subscribe()}, will
@@ -2101,6 +2520,8 @@ declare class ExperimentalStore {
2101
2520
  * @returns a promise for an array of Ditto documents matching the query
2102
2521
  **/
2103
2522
  execute(query: string): Promise<Document[]>;
2523
+ /** @internal */
2524
+ close(): void;
2104
2525
  }
2105
2526
 
2106
2527
  /**
@@ -2147,782 +2568,346 @@ declare class WriteTransactionPendingIDSpecificOperation extends BasePendingIDSp
2147
2568
  * Create a `WriteTransactionCollection` by starting a {@link WriteTransaction}
2148
2569
  * and using its `scoped` method.
2149
2570
  */
2150
- declare class WriteTransactionCollection implements CollectionInterface {
2151
- /** The name of the collection. */
2152
- readonly name: string;
2153
- /**
2154
- * The store this collection belongs to.
2155
- * @internal
2156
- */
2157
- readonly store: Store;
2158
- /**
2159
- * The write transaction within which this collection instance is used.
2160
- * @internal
2161
- */
2162
- readonly writeTransaction: WriteTransaction;
2163
- /**
2164
- * Search for documents in this collection using the provided query string.
2165
- *
2166
- * The returned cursor operation can be used to chain operations on the
2167
- * resulting document set.
2168
- *
2169
- * @param query The query to run against the collection.
2170
- * @param queryArgs These arguments replace placeholders in the provided
2171
- * query.
2172
- */
2173
- find(query: string, queryArgs?: QueryArguments | undefined): WriteTransactionPendingCursorOperation;
2174
- /**
2175
- * Convenience method, equivalent to calling {@link find | find()} and passing
2176
- * the query `"true"`.
2177
- */
2178
- findAll(): WriteTransactionPendingCursorOperation;
2179
- /**
2180
- * Generates a {@link WriteTransactionPendingIDSpecificOperation} with the
2181
- * provided document ID.
2182
- *
2183
- * The returned object can be used to find and return the document. It can also be used to update, remove or evict the document.
2184
- *
2185
- * @param id The ID of the document to find.
2186
- */
2187
- findByID(id: any): WriteTransactionPendingIDSpecificOperation;
2188
- upsert(value: DocumentValue, options?: UpsertOptions): Promise<DocumentID>;
2189
- /**
2190
- * See comment in {@link CollectionInterface.findByIDCBOR()}
2191
- *
2192
- * @internal */
2193
- findByIDCBOR(idCBOR: Uint8Array): WriteTransactionPendingIDSpecificOperation;
2194
- /**
2195
- * This constructor is marked internal because write transaction collections
2196
- * should be created from a {@link WriteTransaction} instance.
2197
- *
2198
- * @internal */
2199
- constructor(name: string, store: Store, writeTransaction: WriteTransaction);
2200
- }
2201
-
2202
- /**
2203
- * Provides information about the result of an operation on a document that was
2204
- * part of a write transaction.
2205
- *
2206
- * The write transaction result can be one of the following types:
2207
- *
2208
- * - `inserted`
2209
- * - `removed`
2210
- * - `evicted`
2211
- * - `updated`
2212
- *
2213
- * Please note that an `upsert` operation always results in the result type
2214
- * `inserted`, regardless of whether it resulted in an update or insert.
2215
- */
2216
- interface WriteTransactionResult {
2217
- type: 'inserted' | 'removed' | 'evicted' | 'updated';
2218
- docID: DocumentID;
2219
- collectionName: string;
2220
- }
2221
- /**
2222
- * Perform writes in a transaction.
2223
- *
2224
- * Create a write transaction using {@link Store.write | ditto.store.write}.
2225
- */
2226
- declare class WriteTransaction {
2227
- /** @internal */
2228
- readonly writeTransactionPointer: Pointer<FFIWriteTransaction>;
2229
- /** @internal */
2230
- readonly ditto: Ditto;
2231
- readonly results: WriteTransactionResult[];
2232
- /**
2233
- * Initialise a write transaction given a Ditto instance.
2234
- *
2235
- * This is not implemented as a constructor in order to be able to use FFI
2236
- * async functions. Users start transactions through {@link Store.write}.
2237
- *
2238
- * @param ditto an instance of Ditto
2239
- * @internal
2240
- */
2241
- static init(ditto: Ditto): Promise<WriteTransaction>;
2242
- /**
2243
- * Creates a transaction-specific
2244
- * {@link WriteTransactionCollection | collection} object that will ensure
2245
- * that operations called on it are all in the context of the collection name
2246
- * provided to this function. You can create many
2247
- * {@link WriteTransactionCollection | collection} objects per
2248
- * {@link WriteTransaction} object.
2249
- * */
2250
- scoped(toCollectionNamed: string): WriteTransactionCollection;
2251
- /** @internal */
2252
- commit(): Promise<void>;
2253
- /** @internal */
2254
- rollback(): Promise<void>;
2255
- /**
2256
- * Adds an entry to the list of results that is returned at the end of a
2257
- * transaction.
2258
- *
2259
- * @internal */
2260
- addResult(type: WriteTransactionResult['type'], docID: DocumentID, collectionName: string): void;
2261
- /** @internal */
2262
- constructor(ditto: Ditto, cTransaction: Pointer<FFIWriteTransaction>);
2263
- }
2264
-
2265
- /**
2266
- * The entrypoint for all actions that relate to data stored by Ditto. Provides
2267
- * access to collections, a write transaction API, and a query hash API.
2268
- *
2269
- * You don't create one directly but can access it from a particular
2270
- * {@link Ditto} instance via its {@link Ditto.store | store} property.
2271
- */
2272
- declare class Store {
2273
- /** The {@link Ditto} instance this store belongs to. */
2274
- readonly ditto: Ditto;
2275
- /** @internal */
2276
- readonly experimental: ExperimentalStore;
2277
- /**
2278
- * Returns the collection for the given name. If the collection doesn't
2279
- * exist yet, it will be created automatically as soon as the first
2280
- * entry is inserted.
2281
- */
2282
- collection(name: string): Collection;
2283
- /**
2284
- * Returns an object that lets you fetch or observe the collections in the
2285
- * store.
2286
- *
2287
- * @return A {@link PendingCollectionsOperation} object that you can use to
2288
- * fetch or observe the collections in the store
2289
- */
2290
- collections(): PendingCollectionsOperation;
2291
- /**
2292
- * Returns the names of all available collections in the store of the
2293
- * related {@link Ditto} instance.
2294
- */
2295
- collectionNames(): Promise<string[]>;
2296
- /**
2297
- * Initiate a write transaction in a callback.
2298
- *
2299
- * Allows you to group multiple operations together that affect multiple documents, potentially across multiple collections.
2300
- *
2301
- * @param callback is given access to a {@link WriteTransaction | write transaction object} that can be used to perform operations on the store.
2302
- * @returns a list of `WriteTransactionResult`s. There is a result for each operation performed as part of the write transaction.
2303
- */
2304
- write(callback: (transaction: WriteTransaction) => Promise<void>): Promise<WriteTransactionResult[]>;
2305
- /** @internal */
2306
- constructor(ditto: Ditto);
2307
- /**
2308
- * Private method, used only by the Portal https://github.com/getditto/ditto/pull/3652
2309
- * @internal
2310
- */
2311
- registerLiveQueryWebhook(collectionName: string, query: string, url: string): Promise<DocumentID>;
2312
- }
2313
-
2314
- /** Types of connections that can be established between two peers. */
2315
- type ConnectionType = 'P2PWiFi' | 'WebSocket' | 'AccessPoint' | 'Bluetooth';
2316
- /**
2317
- * An opaque address uniquely identifying another peer on the Ditto mesh
2318
- * network.
2319
- *
2320
- * IMPORTANT: You should not rely on the individual components of the address,
2321
- * those can change at any time. Please use
2322
- * {@link addressToString | addressToString()} to compare individual addresses
2323
- * with each other.
2324
- */
2325
- type Address = {
2326
- siteId: string;
2327
- pubkey: Uint8Array;
2328
- };
2329
- /**
2330
- * Returns a string representation of the given address. Use this function
2331
- * to compare multiple addresses or whenever you need the address to be a key
2332
- * in a hash object.
2333
- */
2334
- declare function addressToString(address: Address): string;
2335
- /** Represents a connection between two peers on the Ditto mesh network. */
2336
- type Connection = {
2337
- /** Unique identifier for the connection. */
2338
- id: string;
2339
- /** Type of transport enabling this connection. */
2340
- type: ConnectionType;
2341
- /** The peer key of the peer at one end of the connection. */
2342
- peer1: Uint8Array;
2343
- /** The peer key of the peer at one end of the connection. */
2344
- peer2: Uint8Array;
2345
- approximateDistanceInMeters?: number;
2346
- };
2347
- /** An instance of Ditto taking part in the Ditto mesh network. */
2348
- type Peer = {
2349
- /**
2350
- * Address to contact this peer via Ditto Bus, unique with a Ditto mesh
2351
- * network.
2352
- */
2353
- address: Address;
2354
- /**
2355
- * The peer key is a unique identifier for a given peer, equal to or derived
2356
- * from the cryptographic public key used to authenticate it.
2357
- *
2358
- * NOTE: This will be be empty when a peer is not updated to the latest
2359
- * version of the SDK.
2360
- */
2361
- peerKey: Uint8Array;
2362
- /**
2363
- * The human-readable device name of the peer. This defaults to the hostname
2364
- * but can be manually set by the application developer of the other peer.
2365
- * It is not necessarily unique.
2366
- */
2367
- deviceName: string;
2368
- /**
2369
- * Currently active connections of the peer.
2370
- */
2371
- connections: Connection[];
2372
- /**
2373
- * Indicates whether the peer is connected to Ditto Cloud.
2374
- */
2375
- isConnectedToDittoCloud: boolean;
2376
- /** The operating system the peer is running on, `undefined` if (yet) unknown. */
2377
- os?: string;
2378
- /** The Ditto SDK version the peer is running with, `undefined` if (yet) unknown. */
2379
- dittoSDKVersion?: string;
2380
- };
2381
- /**
2382
- * Represents the Ditto mesh network of peers and their connections between each
2383
- * other. The `localPeer` is the entry point, all others are remote peers known
2384
- * by the local peer (either directly or via other remote peers).
2385
- */
2386
- type PresenceGraph = {
2387
- /**
2388
- * Returns the local peer (usually the peer that is represented by the
2389
- * currently running Ditto instance). The `localPeer` is the entry point, all
2390
- * others are remote peers known by the local peer (either directly or via
2391
- * other remote peers).
2392
- */
2393
- localPeer: Peer;
2394
- /**
2395
- * Returns all remote peers known by the `localPeer`, either directly or via
2396
- * other remote peers.
2397
- */
2398
- remotePeers: Peer[];
2399
- /**
2400
- * Returns the underlying CBOR data if the presence graph has been initialized
2401
- * with CBOR. All of Ditto API returning a presence graph has this property
2402
- * set.
2403
- */
2404
- underlyingCBOR?: Uint8Array;
2405
- };
2406
- /**
2407
- * The entrypoint for all actions that relate presence of other peers known by
2408
- * the current peer, either directly or through other peers.
2409
- *
2410
- * You don't create one directly but can access it from a particular `Ditto`
2411
- * instance via its `presence` property.
2412
- */
2413
- declare class Presence {
2414
- /** The Ditto instance this object belongs to. */
2415
- readonly ditto: Ditto;
2416
- /**
2417
- * Returns the current presence graph capturing all known peers and
2418
- * connections between them.
2419
- */
2420
- get graph(): PresenceGraph;
2421
- /**
2422
- * Request information about Ditto peers in range of this device.
2423
- *
2424
- * This method returns an observer which should be held as long as updates are
2425
- * required. A newly registered observer will have a peers update delivered to
2426
- * it immediately. From then on it will be invoked repeatedly when Ditto
2427
- * devices come and go, or the active connections to them change.
2428
- */
2429
- observe(didChangeHandler: (presenceGraph: PresenceGraph) => void): Observer;
2430
- /** @internal */
2431
- constructor(ditto: Ditto);
2432
- private observerManager;
2433
- }
2434
-
2435
- /** Types of connections that can be established between two peers. */
2436
- type TransportCondition = 'Unknown' | 'OK' | 'GenericFailure' | 'AppInBackground' | 'MDNSFailure' | 'TCPListenFailure' | 'NoBLECentralPermission' | 'NoBLEPeripheralPermission' | 'CannotEstablishConnection' | 'BLEDisabled' | 'NoBLEHardware' | 'WiFiDisabled' | 'TemporarilyUnavailable';
2437
- /** The source for a transport condition. */
2438
- type ConditionSource = 'BLE' | 'TCP' | 'AWDL' | 'MDNS';
2439
- /**
2440
- * Types of connections that can be established between two peers.
2441
- * @deprecated replaced by {@link ConnectionType}.
2442
- */
2443
- type PresenceConnectionType = 'WiFi' | 'WebSocket' | 'AWDL' | 'BLE';
2444
- /**
2445
- * A peer object with information about an observed peer.
2446
- * @deprecated replaced by {@link Peer}.
2447
- */
2448
- type RemotePeer = {
2449
- networkID: string;
2450
- deviceName: string;
2451
- rssi?: number;
2452
- approximateDistanceInMeters?: number;
2453
- connections: PresenceConnectionType[];
2454
- };
2455
- /**
2456
- * Ditto is the entry point for accessing Ditto-related functionality.
2457
- */
2458
- declare class Ditto {
2459
- /**
2460
- * Configure a custom identifier for the current device.
2461
- *
2462
- * When using {@link Presence.observe | presence.observe()}, each remote peer is
2463
- * represented by a short UTF-8 "device name". By default this will be a
2464
- * truncated version of the device's hostname. It does not need to be unique
2465
- * among peers. Configure the device name before calling
2466
- * {@link startSync | startSync()}. If it is too long it may be truncated.
2467
- */
2468
- deviceName: string;
2469
- /** Returns a string identifying the version of the Ditto SDK. */
2470
- get sdkVersion(): string;
2471
- /**
2472
- * The (validated) identity this Ditto instance was initialized with.
2473
- */
2474
- readonly identity: Identity;
2475
- /**
2476
- * The path this Ditto instance was initialized with, if no path was given at
2477
- * construction time, the default value is returned (see constructor).
2478
- */
2479
- readonly path: string;
2480
- /**
2481
- * Provides access to the SDK's store functionality.
2482
- */
2483
- readonly store: Store;
2484
- /**
2485
- * Provides access to the SDK's presence functionality.
2486
- */
2487
- readonly presence: Presence;
2488
- /**
2489
- * Provides access to authentication methods for logging on to Ditto Cloud.
2490
- */
2491
- readonly auth: Authenticator;
2492
- /**
2493
- * The site ID that the instance of `Ditto` is using as part of its identity.
2494
- */
2495
- readonly siteID: number | BigInt;
2496
- /**
2497
- * Returns `true` if an offline license token has been set, otherwise returns `false`.
2498
- *
2499
- * @see {@link setOfflineOnlyLicenseToken | setOfflineOnlyLicenseToken()}
2500
- */
2501
- readonly isActivated: boolean;
2502
- /**
2503
- * Returns `true` if sync is active, otherwise returns `false`. Use
2504
- * {@link startSync | startSync()} to activate and {@link stopSync | stopSync()}
2505
- * to deactivate sync.
2506
- */
2507
- readonly isSyncActive: boolean;
2508
- /**
2509
- * Initializes a new `Ditto` instance.
2510
- *
2511
- * **NOTE**: The `sharedKey` identity is only supported for Node environments,
2512
- * using this to create a Ditto instance in the web browser will throw an
2513
- * exception.
2514
- *
2515
- * @param identity - Identity for the new Ditto instance, defaults to
2516
- * `offlinePlayground` with `appID` being the empty string `''`.
2517
- *
2518
- * @param path - On Node, `path` corresponds to a real directory
2519
- * on the file system (intermediate directories are created if needed). In the
2520
- * browser, `path` is used as an internal namespace for the in-memory storage.
2521
- * Defaults to `"ditto"`.
2522
- *
2523
- * @see {@link Ditto.identity}
2524
- * @see {@link Ditto.path}
2525
- */
2526
- constructor(identity?: Identity, path?: string);
2527
- /**
2528
- * Check if the current environment supports running Ditto.
2529
- *
2530
- * Required APIs include:
2531
- *
2532
- * - `BigInt`
2533
- * - `FinalizationRegistry`
2534
- * - `WeakRef`
2535
- *
2536
- * Internet Explorer is not supported.
2537
- *
2538
- * @returns true if the environment is supported
2539
- */
2540
- static isEnvironmentSupported(): boolean;
2571
+ declare class WriteTransactionCollection implements CollectionInterface {
2572
+ /** The name of the collection. */
2573
+ readonly name: string;
2541
2574
  /**
2542
- * Activate a `Ditto` instance by setting an offline only license token. You cannot initiate sync
2543
- * with `Ditto` before you have activated it. The offline license token is only valid for identities
2544
- * of type `development`, `manual`, `offlinePlayground`, and `sharedKey`.
2545
- *
2546
- * @param licenseToken the license token to activate the `Ditto` instance
2547
- * with. You can find yours on the [Ditto portal](https://portal.ditto.live).
2575
+ * The store this collection belongs to.
2576
+ * @internal
2548
2577
  */
2549
- setOfflineOnlyLicenseToken(licenseToken: string): void;
2578
+ readonly store: Store;
2550
2579
  /**
2551
- * Returns the current transport configuration, frozen. If you want to modify
2552
- * the transport config, make a {@link TransportConfig.copy | copy} first. Or
2553
- * use the {@link updateTransportConfig | updateTransportConfig()}
2554
- * convenience method. By default peer-to-peer transports (Bluetooth, WiFi,
2555
- * and AWDL) are enabled if available in the current environment
2556
- * (Web, Node, OS, etc.).
2557
- *
2558
- * @see {@link setTransportConfig | setTransportConfig()}
2559
- * @see {@link updateTransportConfig | updateTransportConfig()}
2580
+ * The write transaction within which this collection instance is used.
2581
+ * @internal
2560
2582
  */
2561
- readonly transportConfig: TransportConfig;
2583
+ readonly writeTransaction: WriteTransaction;
2562
2584
  /**
2563
- * Assigns a new transports configuration. By default peer-to-peer transports
2564
- * (Bluetooth, WiFi, and AWDL) are enabled. You may use this method to alter
2565
- * the configuration at any time, however sync will not begin until
2566
- * {@link startSync | startSync()} is called.
2585
+ * Search for documents in this collection using the provided query string.
2567
2586
  *
2568
- * @see {@link transportConfig}
2569
- * @see {@link updateTransportConfig | updateTransportConfig()}
2587
+ * The returned cursor operation can be used to chain operations on the
2588
+ * resulting document set.
2589
+ *
2590
+ * @param query The query to run against the collection.
2591
+ * @param queryArgs These arguments replace placeholders in the provided
2592
+ * query.
2570
2593
  */
2571
- setTransportConfig(transportConfig: TransportConfig): void;
2594
+ find(query: string, queryArgs?: QueryArguments | undefined): WriteTransactionPendingCursorOperation;
2572
2595
  /**
2573
- * Convenience method for updating the transport config. Creates a copy of the
2574
- * current transport config, passes that copy to the `update` closure,
2575
- * allowing it to mutate as needed, and sets that updated copy afterwards.
2596
+ * Convenience method, equivalent to calling {@link find | find()} and passing
2597
+ * the query `"true"`.
2576
2598
  */
2577
- updateTransportConfig(update: (transportConfig: TransportConfig) => void): Ditto;
2599
+ findAll(): WriteTransactionPendingCursorOperation;
2578
2600
  /**
2579
- * Starts the network transports. Ditto will connect to other devices.
2580
- *
2581
- * By default Ditto will enable all peer-to-peer transport types. On **Node**,
2582
- * this means BluetoothLE, WiFi/LAN, and AWDL. On the **Web**, only connecting
2583
- * via Websockets is supported. The network configuration can be
2584
- * customized with {@link updateTransportConfig | updateTransportConfig()}
2585
- * or replaced entirely with {@link setTransportConfig | setTransportConfig()}.
2586
- *
2587
- *
2588
- * Ditto will prevent the process from exiting until sync is stopped (not
2589
- * relevant when running in the browser).
2601
+ * Generates a {@link WriteTransactionPendingIDSpecificOperation} with the
2602
+ * provided document ID.
2590
2603
  *
2591
- * **NOTE**: the BluetoothLE transport on Linux is experimental, this
2592
- * method panics if no BluetoothLE hardware is available. Therefore, contrary
2593
- * to the above, the BluetoothLE transport is temporarily disabled by default
2594
- * on Linux.
2604
+ * The returned object can be used to find and return the document. It can also be used to update, remove or evict the document.
2595
2605
  *
2596
- * @see {@link isSyncActive}
2597
- * @see {@link stopSync | stopSync()}
2606
+ * @param id The ID of the document to find.
2598
2607
  */
2599
- startSync(): void;
2608
+ findByID(id: any): WriteTransactionPendingIDSpecificOperation;
2609
+ upsert(value: DocumentValue, options?: UpsertOptions): Promise<DocumentID>;
2600
2610
  /**
2601
- * Stops all network transports.
2602
- *
2603
- * You may continue to use the database locally but no data will sync to or
2604
- * from other devices.
2611
+ * See comment in {@link CollectionInterface.findByIDCBOR()}
2605
2612
  *
2606
- * @see {@link isSyncActive}
2607
- * @see {@link startSync | startSync()}
2608
- */
2609
- stopSync(): void;
2613
+ * @internal */
2614
+ findByIDCBOR(idCBOR: Uint8Array): WriteTransactionPendingIDSpecificOperation;
2610
2615
  /**
2611
- * Registers an observer for info about Ditto peers in range of this device.
2612
- *
2613
- * Ditto will prevent the process from exiting as long as there are active
2614
- * peers observers (not relevant when running in the browser).
2615
- *
2616
- * @param callback called immediately with the current state of peers
2617
- * in range and whenever that state changes. Then it will be invoked
2618
- * repeatedly when Ditto devices come and go, or the active connections to
2619
- * them change.
2616
+ * This constructor is marked internal because write transaction collections
2617
+ * should be created from a {@link WriteTransaction} instance.
2620
2618
  *
2621
- * @deprecated please use {@link Presence.observe | presence.observe()} instead.
2622
- */
2623
- observePeers(callback: (peersData: RemotePeer[]) => void): Observer;
2619
+ * @internal */
2620
+ constructor(name: string, store: Store, writeTransaction: WriteTransaction);
2621
+ }
2622
+
2623
+ /**
2624
+ * Provides information about the result of an operation on a document that was
2625
+ * part of a write transaction.
2626
+ *
2627
+ * The write transaction result can be one of the following types:
2628
+ *
2629
+ * - `inserted`
2630
+ * - `removed`
2631
+ * - `evicted`
2632
+ * - `updated`
2633
+ *
2634
+ * Please note that an `upsert` operation always results in the result type
2635
+ * `inserted`, regardless of whether it resulted in an update or insert.
2636
+ */
2637
+ interface WriteTransactionResult {
2638
+ type: 'inserted' | 'removed' | 'evicted' | 'updated';
2639
+ docID: DocumentID;
2640
+ collectionName: string;
2641
+ }
2642
+ /**
2643
+ * Perform writes in a transaction.
2644
+ *
2645
+ * Create a write transaction using {@link Store.write | ditto.store.write}.
2646
+ */
2647
+ declare class WriteTransaction {
2648
+ /** @internal */
2649
+ readonly writeTransactionPointer: Pointer<FFIWriteTransaction>;
2650
+ /** @internal */
2651
+ readonly ditto: Ditto;
2652
+ readonly results: WriteTransactionResult[];
2624
2653
  /**
2625
- * Register observer for changes of underlying transport conditions.
2654
+ * Initialise a write transaction given a Ditto instance.
2626
2655
  *
2627
- * Ditto will prevent the process from exiting as long as there are active
2628
- * transport conditions observers (not relevant when running in the browser).
2656
+ * This is not implemented as a constructor in order to be able to use FFI
2657
+ * async functions. Users start transactions through {@link Store.write}.
2629
2658
  *
2630
- * @param callback called when underlying transport conditions change with
2631
- * the changed `condition` and it's `source`.
2659
+ * @param ditto an instance of Ditto
2660
+ * @internal
2632
2661
  */
2633
- observeTransportConditions(callback: (condition: TransportCondition, source: ConditionSource) => void): Observer;
2662
+ static init(ditto: Ditto): Promise<WriteTransaction>;
2634
2663
  /**
2635
- * Removes all sync metadata for any remote peers which aren't currently
2636
- * connected. This method shouldn't usually be called. Manually running
2637
- * garbage collection often will result in slower sync times. Ditto
2638
- * automatically runs a garbage a collection process in the background at
2639
- * optimal times.
2640
- *
2641
- * Manually running garbage collection is typically only useful during testing
2642
- * if large amounts of data are being generated. Alternatively, if an entire
2643
- * data set is to be evicted and it's clear that maintaining this metadata
2644
- * isn't necessary, then garbage collection could be run after evicting the
2645
- * old data.
2646
- *
2647
- * Only available in Node environments at the moment, no-op in the browser.
2648
- */
2649
- runGarbageCollection(): void;
2664
+ * Creates a transaction-specific
2665
+ * {@link WriteTransactionCollection | collection} object that will ensure
2666
+ * that operations called on it are all in the context of the collection name
2667
+ * provided to this function. You can create many
2668
+ * {@link WriteTransactionCollection | collection} objects per
2669
+ * {@link WriteTransaction} object.
2670
+ * */
2671
+ scoped(toCollectionNamed: string): WriteTransactionCollection;
2672
+ /** @internal */
2673
+ commit(): Promise<void>;
2674
+ /** @internal */
2675
+ rollback(): Promise<void>;
2650
2676
  /**
2651
- * Explicitly opt-in to disabling the ability to sync with Ditto peers running
2652
- * any version of the SDK in the v3 (or lower) series of releases.
2677
+ * Adds an entry to the list of results that is returned at the end of a
2678
+ * transaction.
2653
2679
  *
2654
- * Assuming this succeeds then this peer will only be able to sync with other
2655
- * peers using SDKs in the v4 (or higher) series of releases. Note that this
2656
- * disabling of sync spreads to peers that sync with a peer that has disabled,
2657
- * or has (transitively) had disabled, syncing with v3 SDK peers.
2658
- */
2659
- disableSyncWithV3(): void;
2680
+ * @internal */
2681
+ addResult(type: WriteTransactionResult['type'], docID: DocumentID, collectionName: string): void;
2660
2682
  /** @internal */
2661
- keepAlive: KeepAlive;
2662
- private sync;
2663
- private isWebValid;
2664
- private isX509Valid;
2665
- private presenceManager;
2666
- private transportConditionsManager;
2667
- private authClientValidityChanged;
2668
- private validateIdentity;
2669
- private setSyncActive;
2670
- private makeDefaultTransportConfig;
2683
+ constructor(ditto: Ditto, cTransaction: Pointer<FFIWriteTransaction>);
2671
2684
  }
2672
- /** @internal */
2673
- declare const checkAPIs: (_globalObject?: Window | typeof globalThis) => boolean;
2674
2685
 
2675
2686
  /**
2676
- * Represents an attachment and can be used to insert the associated attachment
2677
- * into a document at a specific key-path. You can't instantiate an attachment
2678
- * directly, please use the {@link Collection.newAttachment | newAttachment()}
2679
- * method of {@link Collection} instead.
2687
+ * The entrypoint for all actions that relate to data stored by Ditto. Provides
2688
+ * access to collections, a write transaction API, and a query hash API.
2689
+ *
2690
+ * You don't create one directly but can access it from a particular
2691
+ * {@link Ditto} instance via its {@link Ditto.store | store} property.
2680
2692
  */
2681
- declare class Attachment {
2682
- /** @internal */
2693
+ declare class Store {
2694
+ /** The {@link Ditto} instance this store belongs to. */
2683
2695
  readonly ditto: Ditto;
2684
2696
  /** @internal */
2685
- readonly token: AttachmentToken;
2686
- /** The attachment's metadata. */
2687
- get metadata(): {
2688
- [key: string]: string;
2689
- };
2690
- /**
2691
- * Returns the attachment's data.
2692
- */
2693
- getData(): Promise<Uint8Array>;
2697
+ readonly experimental: ExperimentalStore;
2694
2698
  /**
2695
- * Copies the attachment to the specified file path. Node-only,
2696
- * throws in the browser.
2697
- *
2698
- * @param path The path that the attachment should be copied to.
2699
+ * Returns the collection for the given name. If the collection doesn't
2700
+ * exist yet, it will be created automatically as soon as the first
2701
+ * entry is inserted.
2699
2702
  */
2700
- copyToPath(path: string): Promise<void>;
2701
- /** @internal */
2702
- constructor(ditto: Ditto, token: AttachmentToken);
2703
- }
2704
-
2705
- /** @internal */
2706
- declare class StaticTCPClient {
2707
- }
2708
-
2709
- /** @internal */
2710
- declare class WebsocketClient {
2711
- }
2712
-
2713
- /** @internal */
2714
- declare class Bridge<JSClass extends object, FFIType> {
2715
- readonly release: (pointer: Pointer<FFIType>) => void;
2703
+ collection(name: string): Collection;
2716
2704
  /**
2717
- * Creates a new bridge for objects of `type`. Requires a `release` function
2718
- * that is called whenever a registered object is garbage collected, passing
2719
- * the associated `pointer` to it. The release function is then responsible
2720
- * to free or drop the corresponding native object.
2721
- *
2722
- * **IMPORTANT**: The `type` of all bridges needs to be set in `epilogue.ts`
2723
- * after initiating the bridge instance. This helps avoid import cycles
2724
- * (otherwise anything importing the bridge instance, would also have to
2725
- * import the type, which usually leads to import cycles).
2705
+ * Returns an object that lets you fetch or observe the collections in the
2706
+ * store.
2726
2707
  *
2727
- * @internal
2708
+ * @return A {@link PendingCollectionsOperation} object that you can use to
2709
+ * fetch or observe the collections in the store
2728
2710
  */
2729
- constructor(release: (pointer: Pointer<FFIType>) => void, options?: {});
2730
- /** @internal */
2731
- get type(): Function;
2711
+ collections(): PendingCollectionsOperation;
2732
2712
  /**
2733
- * Returns the FFI pointer for `object` if registered, otherwise returns
2734
- * `undefined`. If `object` has been unregistered before, returns
2735
- * `undefined`, too.
2736
- *
2737
- * @internal
2713
+ * Returns the names of all available collections in the store of the
2714
+ * related {@link Ditto} instance.
2738
2715
  */
2739
- pointerFor(object: JSClass): Pointer<FFIType> | undefined;
2716
+ collectionNames(): Promise<string[]>;
2740
2717
  /**
2741
- * Convenience method, returns the object for the FFI `pointer` if registered,
2742
- * otherwise returns `undefined`. If the object associated with the `pointer`
2743
- * has been unregistered before, returns `undefined`, too.
2718
+ * Initiate a write transaction in a callback.
2744
2719
  *
2745
- * @internal
2746
- */
2747
- objectFor(pointer: Pointer<FFIType>): JSClass | undefined;
2748
- /**
2749
- * Returns the object for the FFI `pointer` if registered. Otherwise, calls
2750
- * the passed in `create` function to create a new object, which it then
2751
- * returns after registering. If no `create` function is given, uses the
2752
- * type of the bridge as a constructor and creates a new instance of it
2753
- * without passing any parameters.
2720
+ * Allows you to group multiple operations together that affect multiple documents, potentially across multiple collections.
2754
2721
  *
2755
- * @internal
2722
+ * @param callback is given access to a {@link WriteTransaction | write transaction object} that can be used to perform operations on the store.
2723
+ * @returns a list of `WriteTransactionResult`s. There is a result for each operation performed as part of the write transaction.
2756
2724
  */
2757
- bridge(pointer: Pointer<FFIType>, objectOrCreate?: object | (() => JSClass), options?: {}): JSClass;
2758
- /** @internal */
2759
- registerType(value: Function): void;
2760
- /** @internal */
2761
- register(object: JSClass, pointer: Pointer<FFIType>): void;
2762
- /** @internal */
2763
- unregister(object: JSClass): void;
2764
- /** @internal */
2765
- unregisterAll(): void;
2766
- /** @internal */
2767
- get count(): number;
2768
- /** @internal */
2769
- static readonly all: any[];
2770
- /** @internal */
2771
- static readonly attachment: Bridge<Attachment, "AttachmentHandle_t">;
2772
- /** @internal */
2773
- static readonly document: Bridge<Document, "CDocument_t">;
2774
- /** @internal */
2775
- static readonly mutableDocument: Bridge<MutableDocument, "CDocument_t">;
2776
- /** @internal */
2777
- static readonly staticTCPClient: Bridge<StaticTCPClient, "TransportHandle_StaticTCPClientPlatformEvent_t">;
2725
+ write(callback: (transaction: WriteTransaction) => Promise<void>): Promise<WriteTransactionResult[]>;
2778
2726
  /** @internal */
2779
- static readonly websocketClient: Bridge<WebsocketClient, "TransportHandle_WebsocketClientPlatformEvent_t">;
2727
+ constructor(ditto: Ditto);
2780
2728
  /** @internal */
2781
- static readonly ditto: Bridge<Ditto, "CDitto_t">;
2782
- private internalType;
2783
- private metaByAddrMap;
2784
- private finalizationRegistry;
2785
- private finalize;
2786
- }
2787
-
2788
- /** @internal */
2789
- declare class Value {
2790
- readonly value: unknown;
2791
- readonly isDefault: boolean;
2792
- constructor(value: unknown, options?: unknown);
2793
- }
2794
-
2795
- /**
2796
- * Available options for {@link init | init()}.
2797
- */
2798
- type InitOptions = {
2729
+ close(): void;
2799
2730
  /**
2800
- * You can explicitly pass the WebAssembly module or its location via the
2801
- * `webAssemblyModule` option. By default, Ditto tries to load the WebAssembly
2802
- * module from the same path where this JavaScript is served.
2731
+ * Private method, used only by the Portal https://github.com/getditto/ditto/pull/3652
2732
+ * @internal
2803
2733
  */
2804
- webAssemblyModule?: WebAssemblyModule;
2805
- };
2806
- /**
2807
- * Initializes the whole Ditto module. Needs to be called and complete before
2808
- * any of the Ditto API is used.
2809
- *
2810
- * @param options - Dictionary with global {@link InitOptions | initialization options}.
2811
- */
2812
- declare function init(options?: InitOptions): Promise<void>;
2734
+ registerLiveQueryWebhook(collectionName: string, query: string, url: string): Promise<DocumentID>;
2735
+ }
2813
2736
 
2814
- /** The log levels supported by Ditto. */
2815
- type LogLevel = 'Error' | 'Warning' | 'Info' | 'Debug' | 'Verbose';
2816
- /**
2817
- * Closure that {@link Logger.setCustomLogCallback} can be set as a custom
2818
- * log callback on {@link Logger}.
2819
- */
2820
- type CustomLogCallback = (logLevel: LogLevel, message: string) => void;
2821
- /**
2822
- * Class with static methods to customize the logging behavior from Ditto and
2823
- * log messages with the Ditto logging infrastructure.
2824
- */
2825
- declare class Logger {
2737
+ type UpsertOptions = {
2738
+ writeStrategy?: WriteStrategy;
2739
+ };
2740
+ interface CollectionInterface {
2741
+ /** The name of the collection. */
2742
+ readonly name: string;
2826
2743
  /**
2827
- * Registers a file path where logs will be written to, whenever Ditto wants
2828
- * to issue a log (on _top_ of emitting the log to the console).
2744
+ * The store this collection belongs to.
2745
+ * @internal
2829
2746
  */
2830
- static readonly logFile?: string;
2747
+ readonly store: Store;
2831
2748
  /**
2832
- * On Node, registers a file path where logs will be written to, whenever
2833
- * Ditto wants to issue a log (on _top_ of emitting the log to the console).
2834
- * In the browser, this method has no effect.
2749
+ * Search for documents in this collection using the provided query string.
2835
2750
  *
2836
- * @param path can be `null`, in which case the current logging file, if any,
2837
- * is unregistered, otherwise, the file path must be within an already
2838
- * existing directory.
2839
- */
2840
- static setLogFile(path: string | null): void;
2841
- /**
2842
- * Convenience method, takes the path part of the URL and calls
2843
- * {@link setLogFile | setLogFile()} with it.
2751
+ * @param query The query to run against the collection.
2752
+ * @param queryArgs These arguments replace placeholders in the provided
2753
+ * query.
2844
2754
  */
2845
- static setLogFileURL(url: URL | undefined): void;
2846
- /** Whether the logger is currently enabled. */
2847
- static get enabled(): boolean;
2848
- /** Enables or disables logging. */
2849
- static set enabled(enabled: boolean);
2755
+ find(query: string, queryArgs?: QueryArguments): BasePendingCursorOperation;
2850
2756
  /**
2851
- * Represents whether or not emojis should be used as the log level
2852
- * indicator in the logs.
2757
+ * Convenience method, equivalent to calling {@link find | find()} and passing
2758
+ * the query `"true"`.
2853
2759
  */
2854
- static get emojiLogLevelHeadingsEnabled(): boolean;
2760
+ findAll(): BasePendingCursorOperation;
2855
2761
  /**
2856
- * Represents whether or not emojis should be used as the log level
2857
- * indicator in the logs.
2762
+ * Find documents given a specific ID.
2763
+ *
2764
+ * Use the returned cursor instance to chain operations on the search result.
2765
+ *
2766
+ * @param id The document's identifier
2858
2767
  */
2859
- static set emojiLogLevelHeadingsEnabled(emojiLogLevelHeadingsEnabled: boolean);
2768
+ findByID(id: DocumentID | DocumentIDValue): BasePendingIDSpecificOperation;
2860
2769
  /**
2861
- * The minimum log level at which logs will be logged.
2770
+ * TEMPORARY: helper to deal with non-canonical IDs.
2862
2771
  *
2863
- * For example if this is set to `Warning`, then only logs that are logged
2864
- * with the `Warning` or `Error` log levels will be shown.
2772
+ * @internal
2865
2773
  */
2866
- static get minimumLogLevel(): LogLevel;
2774
+ findByIDCBOR(idCBOR: Uint8Array): BasePendingIDSpecificOperation;
2867
2775
  /**
2868
- * The minimum log level at which logs will be logged.
2776
+ * Inserts a new document into the collection and returns its ID. If the
2777
+ * document already exists, the contents of both are merged by default. You
2778
+ * can change this by providing a different `writeStrategy` via `options`.
2869
2779
  *
2870
- * For example if this is set to `Warning`, then only logs that are logged
2871
- * with the `Warning` or `Error` log levels will be shown.
2780
+ * @param value The content of the document to be inserted or updated.
2781
+ * @param options.writeStrategy Specifies the desired strategy for inserting a
2782
+ * document, defaults to `'merge'`.
2872
2783
  */
2873
- static set minimumLogLevel(minimumLogLevel: LogLevel);
2784
+ upsert(value: DocumentValue, options: UpsertOptions): Promise<DocumentID>;
2785
+ }
2786
+
2787
+ declare abstract class BasePendingCursorOperation implements PromiseLike<Document[]> {
2874
2788
  /**
2875
- * Returns the current custom log callback, `undefined` by default. See
2876
- * {@link setCustomLogCallback | setCustomLogCallback()} for a detailed
2877
- * description.
2789
+ * Removes all documents that match the query generated by the preceding
2790
+ * function chaining.
2791
+ *
2792
+ * @returns An array promise containing the IDs of the documents that were
2793
+ * removed.
2878
2794
  */
2879
- static readonly customLogCallback?: CustomLogCallback;
2795
+ abstract remove(): Promise<DocumentID[]>;
2880
2796
  /**
2881
- * Registers a custom callback that will be called to report each log entry.
2797
+ * Evicts all documents that match the query generated by the preceding
2798
+ * function chaining.
2882
2799
  *
2883
- * @param callback function called for each log entry. `undefined` will
2884
- * unregister any previous callback and stop reporting log entries through
2885
- * callbacks.
2800
+ * @return An array promise containing the IDs of the documents that were
2801
+ * evicted.
2886
2802
  */
2887
- static setCustomLogCallback(callback: CustomLogCallback | undefined): Promise<void>;
2803
+ abstract evict(): Promise<DocumentID[]>;
2888
2804
  /**
2889
- * Logs the message for the given `level`.
2805
+ * Updates documents that match the query generated by the preceding function
2806
+ * chaining.
2890
2807
  *
2891
- * @see {@link error | error()}
2892
- * @see {@link warning | warning()}
2893
- * @see {@link info | info()}
2894
- * @see {@link debug | debug()}
2895
- * @see {@link verbose | verbose()}
2808
+ * @param closure A closure that gets called with all of the documents
2809
+ * matching the query. The documents are instances of {@link MutableDocument}
2810
+ * so you can call update-related functions on them.
2811
+ *
2812
+ * @returns An {@link UpdateResultsMap} promise mapping document IDs to lists
2813
+ * of {@link UpdateResult | update results} that describe the updates that
2814
+ * were performed for each document.
2896
2815
  */
2897
- static log(level: LogLevel, message: string): void;
2816
+ abstract update(closure: (documents: MutableDocument[]) => void): Promise<UpdateResultsMap>;
2817
+ /** The query the receiver is operating with. */
2818
+ readonly query: string;
2819
+ /** The named arguments for the {@link query}. */
2820
+ readonly queryArgs: QueryArguments | null;
2821
+ /** The collection the receiver is operating on. */
2822
+ readonly collection: CollectionInterface;
2898
2823
  /**
2899
- * Convenience method, same as calling {@link log | log()} with
2900
- * {@link LogLevel} `Error`.
2824
+ * Sorts the documents that match the query provided in the preceding
2825
+ * `find`-like function call.
2826
+ *
2827
+ * @param query The query specifies the logic to be used when sorting the
2828
+ * matching documents.
2829
+ *
2830
+ * @param direction Specify whether you want the sorting order to be
2831
+ * `Ascending` or `Descending`.
2832
+ *
2833
+ * @return A cursor that you can chain further function calls and then either
2834
+ * get the matching documents immediately or get updates about them over time.
2901
2835
  */
2902
- static error(message: string): void;
2836
+ sort(propertyPath: string, direction?: SortDirection): BasePendingCursorOperation;
2903
2837
  /**
2904
- * Convenience method, same as calling {@link log | log()} with
2905
- * {@link LogLevel} `Warning`.
2838
+ * Offsets the resulting set of matching documents.
2839
+ *
2840
+ * This is useful if you aren't interested in the first N matching documents
2841
+ * for one reason or another. For example, you might already have queried the
2842
+ * collection and obtained the first 20 matching documents and so you might
2843
+ * want to run the same query as you did previously but ignore the first 20
2844
+ * matching documents, and that is when you would use `offset`.
2845
+ *
2846
+ * @param offset The number of matching documents that you want the eventual
2847
+ * resulting set of matching documents to be offset by (and thus not include).
2848
+ *
2849
+ * @return A cursor that you can chain further function calls and then either
2850
+ * get the matching documents immediately or get updates about them over time.
2906
2851
  */
2907
- static warning(message: string): void;
2852
+ offset(offset: number): BasePendingCursorOperation;
2908
2853
  /**
2909
- * Convenience method, same as calling {@link log | log()} with
2910
- * {@link LogLevel} `Info`.
2854
+ * Limits the number of documents that get returned when querying a collection
2855
+ * for matching documents.
2856
+ *
2857
+ * @param limit The maximum number of documents that will be returned.
2858
+ *
2859
+ * @return A cursor that you can chain further function calls and then either
2860
+ * get the matching documents immediately or get updates about them over time.
2911
2861
  */
2912
- static info(message: string): void;
2862
+ limit(limit: number): BasePendingCursorOperation;
2913
2863
  /**
2914
- * Convenience method, same as calling {@link log | log()} with
2915
- * {@link LogLevel} `Debug`.
2864
+ * Executes the query generated by the preceding function chaining and return
2865
+ * the list of matching documents.
2866
+ *
2867
+ * @returns An array promise containing {@link Document | documents} matching
2868
+ * the query generated by the preceding function chaining.
2916
2869
  */
2917
- static debug(message: string): void;
2870
+ exec(): Promise<Document[]>;
2918
2871
  /**
2919
- * Convenience method, same as calling {@link log | log()} with
2920
- * {@link LogLevel} `Verbose`.
2872
+ * Updates documents that match the query generated by the preceding function
2873
+ * chaining.
2874
+ *
2875
+ * @param closure A closure that gets called with all of the documents
2876
+ * matching the query. The documents are instances of {@link MutableDocument}
2877
+ * so you can call update-related functions on them.
2878
+ * @param writeTransactionX a transaction to perform the operation in.
2879
+ *
2880
+ * @returns An {@link UpdateResultsMap} promise mapping document IDs to lists
2881
+ * of {@link UpdateResult | update results} that describe the updates that
2882
+ * were performed for each document.
2883
+ * @internal
2921
2884
  */
2922
- static verbose(message: string): void;
2923
- private constructor();
2885
+ updateWithTransaction(closure: (documents: MutableDocument[]) => void, writeTransactionX: Pointer<FFIWriteTransaction>): Promise<UpdateResultsMap>;
2886
+ /** @internal */
2887
+ constructor(query: string, queryArgs: QueryArguments | null, collection: CollectionInterface);
2888
+ /** @internal */
2889
+ then<TResult1 = any, TResult2 = never>(onfulfilled?: ((value: any) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): PromiseLike<TResult1 | TResult2>;
2890
+ /** @internal */
2891
+ protected queryArgsCBOR: Uint8Array | null;
2892
+ /** @internal */
2893
+ protected currentLimit: number;
2894
+ /** @internal */
2895
+ protected currentOffset: number;
2896
+ /** @internal */
2897
+ protected orderBys: OrderBy[];
2924
2898
  }
2925
2899
 
2900
+ /**
2901
+ * Get a count of bridged objects binned by bridge type.
2902
+ *
2903
+ * Use this in testing to ensure that all objects are properly garbage collected at the end of tests.
2904
+ *
2905
+ * @returns an object with a key per bridge type, containing the number of registered objects.
2906
+ */
2907
+ declare function getBridgeLoad(): {
2908
+ [bridgeName: string]: number;
2909
+ };
2910
+
2926
2911
  /** @internal */
2927
2912
  declare class CBOR {
2928
2913
  /** @internal */
@@ -2931,5 +2916,5 @@ declare class CBOR {
2931
2916
  static decode(data: Uint8Array): any;
2932
2917
  }
2933
2918
 
2934
- export { Address, Attachment, AttachmentFetchEvent, AttachmentFetchEventCompleted, AttachmentFetchEventDeleted, AttachmentFetchEventProgress, AttachmentFetchEventType, AttachmentFetcher, AttachmentToken, AuthenticationHandler, AuthenticationStatus, Authenticator, BasePendingCursorOperation, BasePendingIDSpecificOperation, Bridge, CBOR, Collection, CollectionInterface, CollectionsEvent, CollectionsEventParams, CollectionsObservationHandler, ConditionSource, Connection, ConnectionType, Counter, CustomLogCallback, Ditto, Document, DocumentID, DocumentIDValue, DocumentPath, DocumentValue, ExperimentalStore, Identity, IdentityManual, IdentityOfflinePlayground, IdentityOnlinePlayground, IdentityOnlineWithAuthentication, IdentitySharedKey, IdentityTypesRequiringOfflineLicenseToken, InitOptions, KeepAlive, LiveQuery, LiveQueryEvent, LiveQueryEventInitial, LiveQueryEventUpdate, LiveQueryEventUpdateParams, LiveQueryMove, LogLevel, Logger, MutableCounter, MutableDocument, MutableDocumentPath, MutableRegister, NotAvailableAuthenticator, Observer, ObserverOptions, OnlineAuthenticator, Peer, PendingCollectionsOperation, PendingCursorOperation, PendingIDSpecificOperation, Presence, PresenceConnectionType, PresenceGraph, QueryArguments, QueryObservationHandler, Register, RemotePeer, SingleDocumentLiveQueryEvent, SingleObservationHandler, SortDirection, Store, Subscription, TransportCondition, TransportConfig, TransportConfigConnect, TransportConfigGlobal, TransportConfigLan, TransportConfigListen, TransportConfigListenHTTP, TransportConfigListenTCP, TransportConfigPeerToPeer, UpdateResult, UpdateResultType, UpdateResultsMap, UpsertOptions, Value, WebAssemblyModule, WriteStrategy, WriteTransaction, WriteTransactionCollection, WriteTransactionPendingCursorOperation, WriteTransactionPendingIDSpecificOperation, WriteTransactionResult, addressToString, checkAPIs, init, validateDocumentIDCBOR, validateDocumentIDValue };
2919
+ export { Address, Attachment, AttachmentFetchEvent, AttachmentFetchEventCompleted, AttachmentFetchEventDeleted, AttachmentFetchEventProgress, AttachmentFetchEventType, AttachmentFetcher, AttachmentToken, AuthenticationHandler, AuthenticationStatus, Authenticator, BasePendingCursorOperation, BasePendingIDSpecificOperation, CBOR, Collection, CollectionInterface, CollectionsEvent, CollectionsEventParams, CollectionsObservationHandler, ConditionSource, Connection, ConnectionType, Counter, CustomLogCallback, Ditto, Document, DocumentID, DocumentIDValue, DocumentPath, DocumentValue, ExperimentalStore, Identity, IdentityManual, IdentityOfflinePlayground, IdentityOnlinePlayground, IdentityOnlineWithAuthentication, IdentitySharedKey, IdentityTypesRequiringOfflineLicenseToken, InitOptions, KeepAlive, LiveQuery, LiveQueryEvent, LiveQueryEventInitial, LiveQueryEventUpdate, LiveQueryEventUpdateParams, LiveQueryMove, LogLevel, Logger, MutableCounter, MutableDocument, MutableDocumentPath, MutableRegister, NotAvailableAuthenticator, Observer, ObserverOptions, OnlineAuthenticator, Peer, PendingCollectionsOperation, PendingCursorOperation, PendingIDSpecificOperation, Presence, PresenceConnectionType, PresenceGraph, QueryArguments, QueryObservationHandler, Register, RemotePeer, SingleDocumentLiveQueryEvent, SingleObservationHandler, SortDirection, Store, Subscription, TransportCondition, TransportConfig, TransportConfigConnect, TransportConfigGlobal, TransportConfigLan, TransportConfigListen, TransportConfigListenHTTP, TransportConfigListenTCP, TransportConfigPeerToPeer, UpdateResult, UpdateResultType, UpdateResultsMap, UpsertOptions, Value, WebAssemblyModule, WriteStrategy, WriteTransaction, WriteTransactionCollection, WriteTransactionPendingCursorOperation, WriteTransactionPendingIDSpecificOperation, WriteTransactionResult, addressToString, checkAPIs, getBridgeLoad, init, validateDocumentIDCBOR, validateDocumentIDValue };
2935
2920
  //# sourceMappingURL=ditto.d.ts.map