@dittolive/ditto 4.4.5 → 4.5.1-experimental.aarch64-linux.1.aarch64

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
@@ -72,8 +72,8 @@ declare class ObserverManager {
72
72
 
73
73
  /** @internal */
74
74
  interface ObserverManaging {
75
- hasObserver(token: ObserverToken): any;
76
- removeObserver(token: ObserverToken): any;
75
+ hasObserver(token: ObserverToken): boolean;
76
+ removeObserver(token: ObserverToken): void;
77
77
  }
78
78
  /** @internal */
79
79
  type ObserverOptions = {
@@ -89,7 +89,7 @@ declare class Observer {
89
89
  /** @internal */
90
90
  readonly observerManager: ObserverManaging;
91
91
  /** @internal */
92
- readonly token?: ObserverToken;
92
+ get token(): ObserverToken | undefined;
93
93
  /** @internal */
94
94
  readonly options?: ObserverOptions;
95
95
  /** @internal */
@@ -104,9 +104,91 @@ declare class Observer {
104
104
  */
105
105
  stop(): void;
106
106
  private static finalizationRegistry;
107
+ private _token?;
107
108
  private static finalize;
108
109
  }
109
110
 
111
+ /** Represents a unique identifier for a {@link Document}. */
112
+ type DocumentIDValue = any;
113
+ /** Represents a unique identifier for a {@link Document}. */
114
+ declare class DocumentID {
115
+ /**
116
+ * Returns the value of the receiver, lazily decoded from its CBOR
117
+ * representation if needed.
118
+ */
119
+ get value(): any;
120
+ /**
121
+ * Returns `false` if validation has been skipped at construction time,
122
+ * otherwise returns `true`. This is mostly for internal use only, you
123
+ * shouldn't need this in client code.
124
+ */
125
+ readonly isValidated: boolean;
126
+ /**
127
+ * Creates a new `DocumentID`.
128
+ *
129
+ * A document ID can be created from any of the following:
130
+ *
131
+ * - `string`
132
+ * - `number` (integer)
133
+ * - `boolean`
134
+ * - `null`
135
+ * - raw data in the form of a JS [Typed Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
136
+ * - `Array` (containing any of the items in this list)
137
+ * - Map (a raw JS `object`, where the keys must be strings and the values
138
+ * can be made up of any of the items in this list)
139
+ *
140
+ * Note that you cannot use floats or other custom types to create a document
141
+ * ID.
142
+ *
143
+ * Document IDs are also limited in size, based on their serialized
144
+ * representation, to 256 bytes. You will receive an error if you try to
145
+ * create a document ID that exceeds the size limit.
146
+ *
147
+ * @param value The value that represents the document identifier.
148
+ * @param skipCBOREncoding If `true, skips CBOR encoding and assumes
149
+ * the passed in `value` is already CBOR encoded. You shouldn't need to ever
150
+ * pass this parameter, it's only used internally for certain edge cases.
151
+ * @param skipValidation If `true, skips validation of the passed in value or
152
+ * CBOR. You shouldn't need to ever pass this parameter, it's only used
153
+ * internally for certain edge cases.
154
+ */
155
+ constructor(value: any, skipCBOREncoding?: boolean, skipValidation?: boolean);
156
+ /**
157
+ * Returns `true` if passed in `documentID` is equal to the receiver,
158
+ * otherwise returns `false`.
159
+ */
160
+ equals(documentID: DocumentID): boolean;
161
+ /**
162
+ * Returns a string representation of the receiver.
163
+ *
164
+ * If you need a string representation to be used directly in a query,
165
+ * please use `toQueryCompatibleString()` instead.
166
+ */
167
+ toString(): string;
168
+ /**
169
+ * Returns a byte representation of the document ID value as base64 string.
170
+ */
171
+ toBase64String(): string;
172
+ /**
173
+ * Returns a query compatible string representation of the receiver.
174
+ *
175
+ * The returned string can be used directly in queries that you use with
176
+ * other Ditto functions. For example you could create a query that was like
177
+ * this:
178
+ *
179
+ * ``` TypeScript
180
+ * collection.find(`_id == ${documentID.toQueryCompatibleString()}`)
181
+ * ```
182
+ */
183
+ toQueryCompatibleString(): string;
184
+ /** @internal */
185
+ toCBOR(): Uint8Array;
186
+ }
187
+ /** @internal */
188
+ declare function validateDocumentIDValue(id: DocumentIDValue): DocumentIDValue;
189
+ /** @internal */
190
+ declare function validateDocumentIDCBOR(idCBOR: Uint8Array): Uint8Array;
191
+
110
192
  /**
111
193
  * Describes the direction when sorting a query.
112
194
  */
@@ -139,13 +221,19 @@ type WriteStrategy = 'merge' | 'insertIfAbsent' | 'insertDefaultIfAbsent';
139
221
  type QueryArguments = {
140
222
  [key: string]: any;
141
223
  };
142
-
143
- /** @internal */
144
- declare class Value {
145
- readonly value: unknown;
146
- readonly isDefault: boolean;
147
- constructor(value: unknown, options?: unknown);
148
- }
224
+ /**
225
+ * Values to be incorporated into a query, keyed by the placeholder used within
226
+ * that query.
227
+ */
228
+ type DQLQueryArguments = {
229
+ [key: string]: DQLQueryArgumentValue | undefined;
230
+ };
231
+ /**
232
+ * Individual value in a {@link DQLQueryArguments} object.
233
+ */
234
+ type DQLQueryArgumentValue = string | number | boolean | Uint8Array | null | DocumentID | DQLQueryArgumentValue[] | {
235
+ [key: string]: DQLQueryArgumentValue;
236
+ };
149
237
 
150
238
  /**
151
239
  * Represents a CRDT counter that can be upserted as part of a document or
@@ -153,15 +241,16 @@ declare class Value {
153
241
  */
154
242
  declare class Counter {
155
243
  /** The value of the counter. */
156
- readonly value: number;
244
+ get value(): number;
157
245
  /**
158
246
  * Creates a new counter that can be used as part of a document's content.
159
247
  */
160
248
  constructor();
161
249
  /** @internal */
162
250
  static '@ditto.create'(mutDoc: any, path: any, value: any): any;
163
- private mutDoc;
164
- private path;
251
+ protected mutDoc: any;
252
+ protected path: any;
253
+ protected _value: number;
165
254
  }
166
255
  /**
167
256
  * Represents a mutable CRDT counter that can be incremented by a specific
@@ -181,7 +270,7 @@ declare class MutableCounter extends Counter {
181
270
  */
182
271
  increment(amount: number): void;
183
272
  /** @internal */
184
- constructor();
273
+ protected constructor();
185
274
  }
186
275
 
187
276
  /**
@@ -255,6 +344,8 @@ type Pointer<Type> = {
255
344
  addr: string;
256
345
  };
257
346
  /** @internal */
347
+ type FFIDqlResponse = 'CDqlResponse_t';
348
+ /** @internal */
258
349
  type FFIWriteTransaction = 'CWriteTransaction_t';
259
350
  /** @internal */
260
351
  type OrderBy = {
@@ -301,7 +392,7 @@ declare class Logger {
301
392
  * Registers a file path where logs will be written to, whenever Ditto wants
302
393
  * to issue a log (on _top_ of emitting the log to the console).
303
394
  */
304
- static readonly logFile?: string;
395
+ static get logFile(): string | undefined;
305
396
  /**
306
397
  * On Node, registers a file path where logs will be written to, whenever
307
398
  * Ditto wants to issue a log (on _top_ of emitting the log to the console).
@@ -350,13 +441,15 @@ declare class Logger {
350
441
  * {@link setCustomLogCallback | setCustomLogCallback()} for a detailed
351
442
  * description.
352
443
  */
353
- static readonly customLogCallback?: CustomLogCallback;
444
+ static get customLogCallback(): CustomLogCallback | undefined;
354
445
  /**
355
446
  * Registers a custom callback that will be called to report each log entry.
356
447
  *
357
448
  * @param callback function called for each log entry. `undefined` will
358
449
  * unregister any previous callback and stop reporting log entries through
359
450
  * callbacks.
451
+ *
452
+ * @throws {Error} if called in a React Native environment.
360
453
  */
361
454
  static setCustomLogCallback(callback: CustomLogCallback | undefined): Promise<void>;
362
455
  /**
@@ -394,90 +487,11 @@ declare class Logger {
394
487
  * {@link LogLevel} `Verbose`.
395
488
  */
396
489
  static verbose(message: string): void;
490
+ private static _logFile?;
491
+ private static _customLogCallback?;
397
492
  private constructor();
398
493
  }
399
494
 
400
- /** Represents a unique identifier for a {@link Document}. */
401
- type DocumentIDValue = any;
402
- /** Represents a unique identifier for a {@link Document}. */
403
- declare class DocumentID {
404
- /**
405
- * Returns the value of the receiver, lazily decoded from its CBOR
406
- * representation if needed.
407
- */
408
- get value(): any;
409
- /**
410
- * Returns `false` if validation has been skipped at construction time,
411
- * otherwise returns `true`. This is mostly for internal use only, you
412
- * shouldn't need this in client code.
413
- */
414
- readonly isValidated: boolean;
415
- /**
416
- * Creates a new `DocumentID`.
417
- *
418
- * A document ID can be created from any of the following:
419
- *
420
- * - `string`
421
- * - `number` (integer)
422
- * - `boolean`
423
- * - `null`
424
- * - raw data in the form of a JS [Typed Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays)
425
- * - `Array` (containing any of the items in this list)
426
- * - Map (a raw JS `object`, where the keys must be strings and the values
427
- * can be made up of any of the items in this list)
428
- *
429
- * Note that you cannot use floats or other custom types to create a document
430
- * ID.
431
- *
432
- * Document IDs are also limited in size, based on their serialized
433
- * representation, to 256 bytes. You will receive an error if you try to
434
- * create a document ID that exceeds the size limit.
435
- *
436
- * @param value The value that represents the document identifier.
437
- * @param skipCBOREncoding If `true, skips CBOR encoding and assumes
438
- * the passed in `value` is already CBOR encoded. You shouldn't need to ever
439
- * pass this parameter, it's only used internally for certain edge cases.
440
- * @param skipValidation If `true, skips validation of the passed in value or
441
- * CBOR. You shouldn't need to ever pass this parameter, it's only used
442
- * internally for certain edge cases.
443
- */
444
- constructor(value: any, skipCBOREncoding?: boolean, skipValidation?: boolean);
445
- /**
446
- * Returns `true` if passed in `documentID` is equal to the receiver,
447
- * otherwise returns `false`.
448
- */
449
- equals(documentID: DocumentID): boolean;
450
- /**
451
- * Returns a string representation of the receiver.
452
- *
453
- * If you need a string representation to be used directly in a query,
454
- * please use `toQueryCompatibleString()` instead.
455
- */
456
- toString(): string;
457
- /**
458
- * Returns a byte representation of the document ID value as base64 string.
459
- */
460
- toBase64String(): string;
461
- /**
462
- * Returns a query compatible string representation of the receiver.
463
- *
464
- * The returned string can be used directly in queries that you use with
465
- * other Ditto functions. For example you could create a query that was like
466
- * this:
467
- *
468
- * ``` TypeScript
469
- * collection.find(`_id == ${documentID.toQueryCompatibleString()}`)
470
- * ```
471
- */
472
- toQueryCompatibleString(): string;
473
- /** @internal */
474
- toCBOR(): Uint8Array;
475
- }
476
- /** @internal */
477
- declare function validateDocumentIDValue(id: DocumentIDValue): DocumentIDValue;
478
- /** @internal */
479
- declare function validateDocumentIDCBOR(idCBOR: Uint8Array): Uint8Array;
480
-
481
495
  /**
482
496
  * Represents a portion of the document at a specific key-path.
483
497
  *
@@ -805,6 +819,9 @@ interface TransportConfigPeerToPeer {
805
819
  interface TransportConfigLan {
806
820
  isEnabled: boolean;
807
821
  isMdnsEnabled: boolean;
822
+ /**
823
+ * @deprecated Multicast is deprecated. Please use mDNS instead.
824
+ */
808
825
  isMulticastEnabled: boolean;
809
826
  }
810
827
  /**
@@ -915,7 +932,7 @@ declare class TransportConfig {
915
932
  * Returns `true` if the transport configuration is frozen, otherwise
916
933
  * returns `false`.
917
934
  */
918
- readonly isFrozen: boolean;
935
+ get isFrozen(): boolean;
919
936
  /**
920
937
  * (Deep) freezes the receiver such that it can't be modified anymore.
921
938
  */
@@ -934,6 +951,7 @@ declare class TransportConfig {
934
951
  * returns `false`.
935
952
  */
936
953
  static areListenHTTPsEqual(left: TransportConfigListenHTTP, right: TransportConfigListenHTTP): boolean;
954
+ private _isFrozen;
937
955
  }
938
956
 
939
957
  /**
@@ -988,7 +1006,7 @@ interface AuthenticationHandler {
988
1006
  */
989
1007
  declare class Authenticator {
990
1008
  /**
991
- * Returns `true` if authentication is avaiable and the login methods can be
1009
+ * Returns `true` if authentication is available and the login methods can be
992
1010
  * used, otherwise returns `false`. Currently, authentication is only
993
1011
  * available if Ditto was initialized with an identity of type
994
1012
  * {@link IdentityOnlineWithAuthentication | 'onlineWithAuthentication'}.
@@ -997,7 +1015,7 @@ declare class Authenticator {
997
1015
  /**
998
1016
  Returns the current authentication status.
999
1017
  */
1000
- readonly status: AuthenticationStatus;
1018
+ get status(): AuthenticationStatus;
1001
1019
  /**
1002
1020
  * Log in to Ditto with a third-party token. Throws if authentication is not
1003
1021
  * available, which can be checked with {@link loginSupported}.
@@ -1027,7 +1045,7 @@ declare class Authenticator {
1027
1045
  * [Ditto] instance as the sole argument that allows you to perform any
1028
1046
  * required cleanup of the store as part of the logout process.
1029
1047
  */
1030
- logout(cleanupFn?: (Ditto: any) => void): Promise<void>;
1048
+ logout(cleanupFn?: (ditto: Ditto) => void): Promise<void>;
1031
1049
  observeStatus(callback: (authenticationStatus: AuthenticationStatus) => void): Observer;
1032
1050
  /** @internal */
1033
1051
  constructor(keepAlive: KeepAlive);
@@ -1041,12 +1059,15 @@ declare class Authenticator {
1041
1059
  protected keepAlive: KeepAlive;
1042
1060
  /** @internal */
1043
1061
  protected observerManager: ObserverManager;
1062
+ /** @internal */
1063
+ protected _status: AuthenticationStatus;
1044
1064
  }
1045
1065
  /** @internal */
1046
1066
  declare class OnlineAuthenticator extends Authenticator {
1067
+ readonly loginSupported: boolean;
1047
1068
  loginWithToken(token: string, provider: string): Promise<void>;
1048
1069
  loginWithUsernameAndPassword(username: string, password: string, provider: string): Promise<void>;
1049
- logout(cleanupFn?: (Ditto: any) => void): Promise<void>;
1070
+ logout(cleanupFn?: (ditto: Ditto) => void): Promise<void>;
1050
1071
  readonly authenticationHandler: AuthenticationHandler;
1051
1072
  private ditto;
1052
1073
  constructor(keepAlive: KeepAlive, ditto: Ditto, authenticationHandler: AuthenticationHandler);
@@ -1056,194 +1077,57 @@ declare class OnlineAuthenticator extends Authenticator {
1056
1077
  }
1057
1078
  /** @internal */
1058
1079
  declare class NotAvailableAuthenticator extends Authenticator {
1059
- loginWithToken(token: string, provider: string): Promise<void>;
1060
- loginWithUsernameAndPassword(username: string, password: string, provider: string): Promise<void>;
1061
- logout(cleanupFn?: (Ditto: any) => void): Promise<void>;
1062
- '@ditto.authenticationExpiring'(secondsRemaining: any): void;
1063
- '@ditto.authClientValidityChanged'(isWebValid: boolean, isX509Valid: boolean): void;
1080
+ loginWithToken(token: string, provider: string): Promise<never>;
1081
+ loginWithUsernameAndPassword(username: string, password: string, provider: string): Promise<never>;
1082
+ logout(cleanupFn?: (ditto: Ditto) => void): Promise<never>;
1083
+ '@ditto.authenticationExpiring'(secondsRemaining: number): never;
1084
+ '@ditto.authClientValidityChanged'(isWebValid: boolean, isX509Valid: boolean): never;
1064
1085
  }
1065
1086
 
1087
+ /** Types of connections that can be established between two peers. */
1088
+ type ConnectionType = 'P2PWiFi' | 'WebSocket' | 'AccessPoint' | 'Bluetooth';
1066
1089
  /**
1067
- * An identity to be used while in development when you want to control the app
1068
- * name and the site ID of the peer.
1090
+ * An opaque address uniquely identifying another peer on the Ditto mesh
1091
+ * network.
1092
+ *
1093
+ * IMPORTANT: You should not rely on the individual components of the address,
1094
+ * those can change at any time. Please use
1095
+ * {@link addressToString | addressToString()} to compare individual addresses
1096
+ * with each other.
1069
1097
  */
1070
- interface IdentityOfflinePlayground {
1071
- type: 'offlinePlayground';
1072
- /**
1073
- * The app ID for the Ditto instance.
1074
- */
1075
- appID: string;
1076
- /**
1077
- * The `siteID` needs to be an unsigned 64 bit integer >= 0, i.e. either a
1078
- * regular non-fractional `number` or a `BigInt` in the range between 0 and
1079
- * 2^64 - 1 (inclusive). If `siteID` is `0`, Ditto will generate an
1080
- * appropriate site ID and persist it when needed. Default is `0`.
1081
- */
1082
- siteID?: number | BigInt;
1083
- }
1098
+ type Address = {
1099
+ siteId: number | BigInt;
1100
+ pubkey: Uint8Array;
1101
+ };
1084
1102
  /**
1085
- * An identity with intermediate level of security where all users and devices
1086
- * are trusted and a single shared secret (key) between all peers satisfies the
1087
- * security requirements.
1088
- *
1089
- * **NOTE**: This identity type is only supported for Node environments, using
1090
- * this to create a Ditto instance in the web browser will throw an exception.
1103
+ * Returns a string representation of the given address. Use this function
1104
+ * to compare multiple addresses or whenever you need the address to be a key
1105
+ * in a hash object.
1091
1106
  */
1092
- interface IdentitySharedKey {
1093
- type: 'sharedKey';
1094
- /**
1095
- * The app ID for the Ditto instance.
1107
+ declare function addressToString(address: Address): string;
1108
+ /** Represents a connection between two peers on the Ditto mesh network. */
1109
+ type Connection = {
1110
+ /** Unique identifier for the connection.
1111
+ *
1112
+ * These IDs are stable for any two peer keys and a given connection type.
1113
+ *
1114
+ * **Example ID**
1115
+ *
1116
+ * "1<->2:Bluetooth"
1096
1117
  */
1097
- appID: string;
1118
+ id: string;
1119
+ /** Type of transport enabling this connection. */
1120
+ connectionType: ConnectionType;
1098
1121
  /**
1099
- * The `siteID` needs to be an unsigned 64 bit integer >= 0, i.e. either a
1100
- * regular non-fractional `number` or a `BigInt` in the range between 0 and
1101
- * 2^64 - 1 (inclusive). If `siteID` is `0`, Ditto will generate an
1102
- * appropriate site ID and persist it when needed. Default is `0`.
1122
+ * Peer key of the peer at one end of the connection.
1123
+ *
1124
+ * This peer key is lexicographically smaller than `peer2`.
1103
1125
  */
1104
- siteID?: number | BigInt;
1126
+ peer1: Uint8Array;
1105
1127
  /**
1106
- * A base64 encoded DER representation of a private key, which is shared
1107
- * between devices for a single app.
1108
- */
1109
- sharedKey: string;
1110
- }
1111
- /**
1112
- * A manually-provided certificate identity. This accepts a
1113
- * base64-encoded bundle.
1114
- *
1115
- * A manual identity's `appID` is encoded in its certificate.
1116
- */
1117
- interface IdentityManual {
1118
- type: 'manual';
1119
- certificate: string;
1120
- }
1121
- /**
1122
- * Test a Ditto Cloud app with weak shared token authentication ("Playground
1123
- * mode"). This mode is not secure and must only be used for development.
1124
- */
1125
- interface IdentityOnlinePlayground {
1126
- type: 'onlinePlayground';
1127
- /**
1128
- * An ID identifying this app registration on the Ditto portal, which can be
1129
- * found at https://portal.ditto.live.
1130
- */
1131
- appID: string;
1132
- /**
1133
- * A shared token used to set up the OnlinePlayground session. This token is
1134
- * provided by the Ditto Portal when setting up the application.
1135
- */
1136
- token: string;
1137
- /** If true, auto-configure sync with Ditto Cloud. Default is `true`. */
1138
- enableDittoCloudSync?: boolean;
1139
- /**
1140
- * If specified, use a custom authentication service instead of Ditto Cloud.
1141
- * @internal
1142
- */
1143
- customAuthURL?: string;
1144
- /**
1145
- * A custom Ditto Cloud URL.
1146
- * @internal
1147
- */
1148
- customDittoCloudURL?: string;
1149
- }
1150
- /**
1151
- * Run Ditto in secure production mode, logging on to Ditto Cloud or an
1152
- * on-premises authentication server. User permissions are centrally managed.
1153
- * Sync will not work until a successful login has occurred.
1154
- *
1155
- * The only required configuration is the application's UUID, which can be found
1156
- * on the Ditto portal where the app is registered.
1157
- *
1158
- * By default cloud sync is enabled. This means the SDK will sync to a Big Peer
1159
- * in Ditto's cloud when an internet connection is available. This is controlled
1160
- * by the `enableCloudSync` parameter. If `true` (default), a suitable wss://
1161
- * URL will be added to the `TransportConfig`. To prevent cloud sync, or to
1162
- * specify your own URL later, pass `false`.
1163
- *
1164
- * Authentication requests are handled by Ditto's cloud by default, configured
1165
- * in the portal at https://portal.ditto.live.
1166
- *
1167
- * To use a different or on-premises authentication service, pass a custom HTTPS
1168
- * base URL as the `customAuthUrl` parameter.
1169
- */
1170
- interface IdentityOnlineWithAuthentication {
1171
- type: 'onlineWithAuthentication';
1172
- /**
1173
- * An ID identifying this app registration on the Ditto portal, which can be
1174
- * found at https://portal.ditto.live.
1175
- */
1176
- appID: string;
1177
- /**
1178
- * If true, auto-configure sync with Ditto Cloud. Default is `true`.
1179
- */
1180
- enableDittoCloudSync?: boolean;
1181
- /**
1182
- * A handler for when Ditto requires (re)authentication.
1183
- */
1184
- authHandler: AuthenticationHandler;
1185
- /**
1186
- * If specified, use a custom authentication service instead of Ditto Cloud.
1187
- */
1188
- customAuthURL?: string;
1189
- /**
1190
- * A custom Ditto Cloud URL.
1191
- * @internal
1192
- */
1193
- customDittoCloudURL?: string;
1194
- }
1195
- /**
1196
- * The various identity configurations that you can use when initializing a
1197
- * `Ditto` instance.
1198
- */
1199
- type Identity = IdentityOfflinePlayground | IdentitySharedKey | IdentityManual | IdentityOnlinePlayground | IdentityOnlineWithAuthentication;
1200
- /** The list of identity types that require activation through an offlineLicenseToken */
1201
- declare const IdentityTypesRequiringOfflineLicenseToken: string[];
1202
-
1203
- /** Types of connections that can be established between two peers. */
1204
- type ConnectionType = 'P2PWiFi' | 'WebSocket' | 'AccessPoint' | 'Bluetooth';
1205
- /**
1206
- * An opaque address uniquely identifying another peer on the Ditto mesh
1207
- * network.
1208
- *
1209
- * IMPORTANT: You should not rely on the individual components of the address,
1210
- * those can change at any time. Please use
1211
- * {@link addressToString | addressToString()} to compare individual addresses
1212
- * with each other.
1213
- */
1214
- type Address = {
1215
- siteId: number | BigInt;
1216
- pubkey: Uint8Array;
1217
- };
1218
- /**
1219
- * Returns a string representation of the given address. Use this function
1220
- * to compare multiple addresses or whenever you need the address to be a key
1221
- * in a hash object.
1222
- */
1223
- declare function addressToString(address: Address): string;
1224
- /** Represents a connection between two peers on the Ditto mesh network. */
1225
- type Connection = {
1226
- /** Unique identifier for the connection.
1227
- *
1228
- * These IDs are stable for any two peer keys and a given connection type.
1229
- *
1230
- * **Example ID**
1231
- *
1232
- * "1<->2:Bluetooth"
1233
- */
1234
- id: string;
1235
- /** Type of transport enabling this connection. */
1236
- connectionType: ConnectionType;
1237
- /**
1238
- * Peer key of the peer at one end of the connection.
1239
- *
1240
- * This peer key is lexicographically smaller than `peer2`.
1241
- */
1242
- peer1: Uint8Array;
1243
- /**
1244
- * Peer key of the peer at the other end of the connection.
1245
- *
1246
- * This peer key is lexicographically larger than `peer1`.
1128
+ * Peer key of the peer at the other end of the connection.
1129
+ *
1130
+ * This peer key is lexicographically larger than `peer1`.
1247
1131
  */
1248
1132
  peer2: Uint8Array;
1249
1133
  approximateDistanceInMeters?: number;
@@ -1400,7 +1284,7 @@ declare class Subscription {
1400
1284
  * Returns `true` if subscription has been explicitly cancelled, `false`
1401
1285
  * otherwise.
1402
1286
  */
1403
- readonly isCancelled = false;
1287
+ get isCancelled(): boolean;
1404
1288
  /**
1405
1289
  * The name of the collection that the subscription is based on.
1406
1290
  */
@@ -1416,8 +1300,6 @@ declare class Subscription {
1416
1300
  * @internal Because not exposed in any of the other SDKs (yet?).
1417
1301
  */
1418
1302
  readonly collection: Collection;
1419
- /** @internal */
1420
- private readonly manager;
1421
1303
  /**
1422
1304
  * The corresponding named arguments for {@link query}, if any.
1423
1305
  * @internal Because not exposed in any of the other SDKs (yet?).
@@ -1425,6 +1307,8 @@ declare class Subscription {
1425
1307
  readonly queryArgsCBOR: Uint8Array | null;
1426
1308
  /** @internal */
1427
1309
  readonly contextInfo: SubscriptionContextInfo;
1310
+ private readonly manager;
1311
+ private _isCancelled;
1428
1312
  }
1429
1313
 
1430
1314
  /**
@@ -1711,14 +1595,19 @@ declare class LiveQuery {
1711
1595
  readonly collection: Collection;
1712
1596
  /** @internal */
1713
1597
  readonly handler: QueryObservationHandler;
1714
- /** @internal */
1598
+ /**
1599
+ * This field is only populated while a live query is active and set to null
1600
+ * when the live query is stopped.
1601
+ *
1602
+ * @internal
1603
+ */
1715
1604
  liveQueryManager: LiveQueryManager | null;
1716
- /** @internal */
1717
- readonly liveQueryID: number;
1605
+ get liveQueryID(): number;
1718
1606
  /** @internal */
1719
1607
  constructor(query: string, queryArgs: QueryArguments | null, queryArgsCBOR: Uint8Array | null, orderBys: OrderBy[], limit: number, offset: number, collection: Collection, handler: QueryObservationHandler);
1720
1608
  /** @internal */
1721
1609
  signalNext(): Promise<void>;
1610
+ private _liveQueryID;
1722
1611
  }
1723
1612
 
1724
1613
  /** @internal */
@@ -1740,128 +1629,417 @@ declare class LiveQueryManager {
1740
1629
  }
1741
1630
 
1742
1631
  /**
1743
- * The types of attachment fetch events that can be delivered to an attachment
1744
- * fetcher's `callback`.
1745
- */
1746
- type AttachmentFetchEventType = 'Completed' | 'Progress' | 'Deleted';
1747
- /**
1748
- * An attachment fetch event used when the attachment's download has completed.
1749
- */
1750
- type AttachmentFetchEventCompleted = {
1751
- type: 'Completed';
1752
- attachment: Attachment;
1753
- };
1754
- /**
1755
- * An attachment fetch event used when the attachment's download progressed but
1756
- * is not yet complete.
1757
- */
1758
- type AttachmentFetchEventProgress = {
1759
- type: 'Progress';
1760
- totalBytes: number | BigInt;
1761
- downloadedBytes: number | BigInt;
1762
- };
1763
- /**
1764
- * An attachment fetch event used when the attachment is deleted.
1765
- */
1766
- type AttachmentFetchEventDeleted = {
1767
- type: 'Deleted';
1768
- };
1769
- /**
1770
- * A representation of the events that can occur in relation to an attachment
1771
- * fetch.
1772
- *
1773
- * There are three different attachment fetch events: `Completed`, `Progress`,
1774
- * or `Deleted`.
1632
+ * A sync subscription configures Ditto to receive updates from remote peers
1633
+ * about documents matching the subscription's query.
1775
1634
  *
1776
- * There will be at most one `Completed` or `Deleted` event per attachment
1777
- * fetch. There can be many `Progress` events delivered for each attachment
1778
- * fetch.
1635
+ * The sync subscription will remain active until it is
1636
+ * {@link SyncSubscription.cancel | cancelled}, or the Ditto instance managing
1637
+ * the subscription has been {@link Ditto.close | closed}.
1779
1638
  *
1780
- * Updates relating to an attachment fetch are delivered by registering an
1781
- * {@link AttachmentFetcher} through a call to
1782
- * {@link Collection.fetchAttachment | fetchAttachment()} on a
1783
- * {@link Collection} instance.
1784
- */
1785
- type AttachmentFetchEvent = AttachmentFetchEventCompleted | AttachmentFetchEventProgress | AttachmentFetchEventDeleted;
1786
-
1787
- /**
1788
- * These objects are returned by calls to
1789
- * {@link Collection.fetchAttachment | fetchAttachment()} on {@link Collection}
1790
- * and allow you to stop an in-flight attachment fetch.
1639
+ * Create a sync subscription by calling
1640
+ * {@link Sync.registerSubscription | `ditto.sync.registerSubscription()`}.
1791
1641
  */
1792
- declare class AttachmentFetcher implements PromiseLike<Attachment | null> {
1642
+ declare class SyncSubscription {
1793
1643
  /**
1794
- * Returns a promise for the attachment that you can `await`. The promise
1795
- * resolves to either an attachment or `null` if the attachment has been
1796
- * deleted meanwhile. The promise is rejected if an error occurs during
1797
- * the fetch. Note that the `AttachmentFetcher` itself implementes
1798
- * `PromiseLike`, so you can `await` it directly.
1644
+ * Documents matching this query will be included in the sync subscription.
1799
1645
  */
1800
- readonly attachment: Promise<Attachment | null>;
1646
+ readonly queryString: string;
1801
1647
  /**
1802
- * Stops fetching the associated attachment and cleans up any associated
1803
- * resources.
1804
- *
1805
- * Note that you are not required to call `stop()` once your attachment fetch
1806
- * operation has finished. The method primarily exists to allow you to cancel
1807
- * an attachment fetch request while it is ongoing if you no longer wish for
1808
- * the attachment to be made available locally to the device.
1648
+ * The query arguments of the sync subscription (as passed when
1649
+ * adding it to the store).
1809
1650
  */
1810
- stop(): void;
1811
- /** @internal */
1812
- readonly cancelTokenPromise: Promise<unknown | null> | null;
1813
- /** @internal */
1814
- readonly ditto: Ditto;
1815
- /** @internal */
1816
- readonly id: string;
1817
- /** @internal */
1818
- readonly manager: AttachmentFetcherManager;
1819
- /** @internal */
1820
- readonly token: AttachmentToken;
1821
- /** @internal */
1822
- then<TResult1 = any, TResult2 = never>(onfulfilled?: ((value: any) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): PromiseLike<TResult1 | TResult2>;
1823
- /** @internal */
1824
- constructor(ditto: Ditto, token: AttachmentToken, manager: AttachmentFetcherManager, eventHandler?: (attachmentFetchEvent: AttachmentFetchEvent) => void);
1651
+ readonly queryArguments?: Readonly<DQLQueryArguments>;
1825
1652
  /**
1826
- * This function is defined while a fetch is in progress and is used to reject
1827
- * the promise `this.attachment` when the fetch is canceled.
1828
- *
1829
- * @internal
1653
+ * The {@link Ditto} instance this sync subscription belongs to.
1830
1654
  */
1831
- private rejectPendingFetch;
1832
- }
1833
-
1834
- /**
1835
- * Manages attachment fetchers to make sure we free all resources when the
1836
- * fetcher is garbage collected and to allow us to wait for freeing of
1837
- * ressources to be finished before the ditto instance is closed.
1838
- *
1839
- * @internal */
1840
- declare class AttachmentFetcherManager {
1841
1655
  readonly ditto: Ditto;
1842
- /** @internal */
1843
- constructor(ditto: Ditto);
1844
1656
  /**
1845
- * Start an attachment fetcher.
1846
- *
1847
- * @internal */
1848
- startAttachmentFetcher(token: AttachmentToken, eventHandler?: (attachmentFetchEvent: AttachmentFetchEvent) => void): AttachmentFetcher;
1657
+ * `true` when the sync subscription has been cancelled or the {@link Ditto}
1658
+ * instance managing this subscription has been closed.
1659
+ */
1660
+ get isCancelled(): boolean;
1849
1661
  /**
1850
- * Stop an attachment fetcher and wait for it to be stopped.
1851
- *
1852
- * @internal */
1853
- stopAttachmentFetcher(attachmentFetcher: AttachmentFetcher): Promise<void>;
1662
+ * Cancels the sync subscription and unregisters it. No-op
1663
+ * if the sync subscription has already been cancelled or the {@link Ditto}
1664
+ * instance managing this subscription has been closed.
1665
+ */
1666
+ cancel(): void;
1667
+ /** @internal */
1668
+ constructor(ditto: Ditto, query: string, queryArguments: DQLQueryArguments | null, queryArgumentsCBOR: Uint8Array | null);
1854
1669
  /**
1855
- * Closing the manager will cancel all attachment fetchers.
1670
+ * The CBOR-encoded query arguments, or `null` if no query arguments were
1671
+ * passed in.
1856
1672
  *
1857
1673
  * @internal
1858
1674
  */
1859
- close(): void;
1860
- private contextInfoByID;
1861
- private finalizationRegistry;
1675
+ readonly queryArgumentsCBOR: Uint8Array | null;
1862
1676
  /**
1863
- * Stop the attachment fetcher without unregistering it from the finalization
1864
- * registry.
1677
+ * `true` when the ssync ubscription has been cancelled.
1678
+ *
1679
+ * We mark the sync subscription as cancelled here as an optimization to avoid
1680
+ * a scan of all subscriptions in the store whenever the `isCancelled`
1681
+ * property is checked.
1682
+ */
1683
+ private _isCancelled;
1684
+ }
1685
+
1686
+ /**
1687
+ * An identity to be used while in development when you want to control the app
1688
+ * name and the site ID of the peer.
1689
+ */
1690
+ interface IdentityOfflinePlayground {
1691
+ type: 'offlinePlayground';
1692
+ /**
1693
+ * The app ID for the Ditto instance.
1694
+ */
1695
+ appID: string;
1696
+ /**
1697
+ * The `siteID` needs to be an unsigned 64 bit integer >= 0, i.e. either a
1698
+ * regular non-fractional `number` or a `BigInt` in the range between 0 and
1699
+ * 2^64 - 1 (inclusive). If `siteID` is `0`, Ditto will generate an
1700
+ * appropriate site ID and persist it when needed. Default is `0`.
1701
+ */
1702
+ siteID?: number | BigInt;
1703
+ }
1704
+ /**
1705
+ * An identity with intermediate level of security where all users and devices
1706
+ * are trusted and a single shared secret (key) between all peers satisfies the
1707
+ * security requirements.
1708
+ *
1709
+ * **NOTE**: This identity type is only supported for Node environments, using
1710
+ * this to create a Ditto instance in the web browser will throw an exception.
1711
+ */
1712
+ interface IdentitySharedKey {
1713
+ type: 'sharedKey';
1714
+ /**
1715
+ * The app ID for the Ditto instance.
1716
+ */
1717
+ appID: string;
1718
+ /**
1719
+ * The `siteID` needs to be an unsigned 64 bit integer >= 0, i.e. either a
1720
+ * regular non-fractional `number` or a `BigInt` in the range between 0 and
1721
+ * 2^64 - 1 (inclusive). If `siteID` is `0`, Ditto will generate an
1722
+ * appropriate site ID and persist it when needed. Default is `0`.
1723
+ */
1724
+ siteID?: number | BigInt;
1725
+ /**
1726
+ * A base64 encoded DER representation of a private key, which is shared
1727
+ * between devices for a single app.
1728
+ */
1729
+ sharedKey: string;
1730
+ }
1731
+ /**
1732
+ * A manually-provided certificate identity. This accepts a
1733
+ * base64-encoded bundle.
1734
+ *
1735
+ * A manual identity's `appID` is encoded in its certificate.
1736
+ */
1737
+ interface IdentityManual {
1738
+ type: 'manual';
1739
+ certificate: string;
1740
+ }
1741
+ /**
1742
+ * Test a Ditto Cloud app with weak shared token authentication ("Playground
1743
+ * mode"). This mode is not secure and must only be used for development.
1744
+ */
1745
+ interface IdentityOnlinePlayground {
1746
+ type: 'onlinePlayground';
1747
+ /**
1748
+ * An ID identifying this app registration on the Ditto portal, which can be
1749
+ * found at https://portal.ditto.live.
1750
+ */
1751
+ appID: string;
1752
+ /**
1753
+ * A shared token used to set up the OnlinePlayground session. This token is
1754
+ * provided by the Ditto Portal when setting up the application.
1755
+ */
1756
+ token: string;
1757
+ /** If true, auto-configure sync with Ditto Cloud. Default is `true`. */
1758
+ enableDittoCloudSync?: boolean;
1759
+ /**
1760
+ * If specified, use a custom authentication service instead of Ditto Cloud.
1761
+ * @internal
1762
+ */
1763
+ customAuthURL?: string;
1764
+ /**
1765
+ * A custom Ditto Cloud URL.
1766
+ * @internal
1767
+ */
1768
+ customDittoCloudURL?: string;
1769
+ }
1770
+ /**
1771
+ * Run Ditto in secure production mode, logging on to Ditto Cloud or an
1772
+ * on-premises authentication server. User permissions are centrally managed.
1773
+ * Sync will not work until a successful login has occurred.
1774
+ *
1775
+ * The only required configuration is the application's UUID, which can be found
1776
+ * on the Ditto portal where the app is registered.
1777
+ *
1778
+ * By default cloud sync is enabled. This means the SDK will sync to a Big Peer
1779
+ * in Ditto's cloud when an internet connection is available. This is controlled
1780
+ * by the `enableCloudSync` parameter. If `true` (default), a suitable wss://
1781
+ * URL will be added to the `TransportConfig`. To prevent cloud sync, or to
1782
+ * specify your own URL later, pass `false`.
1783
+ *
1784
+ * Authentication requests are handled by Ditto's cloud by default, configured
1785
+ * in the portal at https://portal.ditto.live.
1786
+ *
1787
+ * To use a different or on-premises authentication service, pass a custom HTTPS
1788
+ * base URL as the `customAuthUrl` parameter.
1789
+ */
1790
+ interface IdentityOnlineWithAuthentication {
1791
+ type: 'onlineWithAuthentication';
1792
+ /**
1793
+ * An ID identifying this app registration on the Ditto portal, which can be
1794
+ * found at https://portal.ditto.live.
1795
+ */
1796
+ appID: string;
1797
+ /**
1798
+ * If true, auto-configure sync with Ditto Cloud. Default is `true`.
1799
+ */
1800
+ enableDittoCloudSync?: boolean;
1801
+ /**
1802
+ * A handler for when Ditto requires (re)authentication.
1803
+ */
1804
+ authHandler: AuthenticationHandler;
1805
+ /**
1806
+ * If specified, use a custom authentication service instead of Ditto Cloud.
1807
+ */
1808
+ customAuthURL?: string;
1809
+ /**
1810
+ * A custom Ditto Cloud URL.
1811
+ * @internal
1812
+ */
1813
+ customDittoCloudURL?: string;
1814
+ }
1815
+ /**
1816
+ * The various identity configurations that you can use when initializing a
1817
+ * `Ditto` instance.
1818
+ */
1819
+ type Identity = IdentityOfflinePlayground | IdentitySharedKey | IdentityManual | IdentityOnlinePlayground | IdentityOnlineWithAuthentication;
1820
+ /** The list of identity types that require activation through an offlineLicenseToken */
1821
+ declare const IdentityTypesRequiringOfflineLicenseToken: string[];
1822
+
1823
+ /** @internal */
1824
+ type SyncParameters = {
1825
+ readonly isSyncActive: boolean;
1826
+ readonly isX509Valid: boolean;
1827
+ readonly isWebValid: boolean;
1828
+ readonly ditto: Ditto;
1829
+ readonly identity: Identity;
1830
+ readonly transportConfig: TransportConfig;
1831
+ };
1832
+ /** @internal */
1833
+ type SyncState = {
1834
+ readonly underlyingSyncParameters: SyncParameters;
1835
+ readonly effectiveTransportConfig: TransportConfig;
1836
+ };
1837
+ /**
1838
+ * Provides access to sync related functionality of Ditto.
1839
+ *
1840
+ * Access this object via {@link Ditto.sync | Ditto.sync} on any Ditto instance.
1841
+ */
1842
+ declare class Sync {
1843
+ /**
1844
+ * The {@link Ditto} instance managed by this sync object.
1845
+ */
1846
+ readonly ditto: Ditto;
1847
+ /**
1848
+ * All currently active sync subscriptions.
1849
+ *
1850
+ * **Note:** Manage sync subscriptions using
1851
+ * {@link registerSubscription | registerSubscription()} to register a new
1852
+ * sync subscription and
1853
+ * {@link SyncSubscription.cancel | SyncSubscription.cancel()} to remove an
1854
+ * existing sync subscription.
1855
+ */
1856
+ readonly subscriptions: Readonly<Array<SyncSubscription>>;
1857
+ /**
1858
+ * Installs and returns a sync subscription for a query, configuring Ditto to
1859
+ * receive updates from other peers for documents matching that query. The
1860
+ * passed in query must be a `SELECT` query, otherwise an error is thrown.
1861
+ *
1862
+ * @param query a string containing a valid query expressed in DQL.
1863
+ * @param queryArguments an object containing the arguments for the query.
1864
+ * Example: `{mileage: 123}` for a query with `:mileage` placeholder.
1865
+ * @returns An active `SyncSubscription` for the passed in query and
1866
+ * arguments. It will remain active until it is
1867
+ * {@link SyncSubscription.cancel | cancelled} or the {@link Ditto} instance
1868
+ * managing the sync subscription has been closed.
1869
+ * @throws {@link DittoError} `query/invalid`: if `query` argument is not a
1870
+ * string or not valid DQL.
1871
+ * @throws {@link DittoError} `query/arguments-invalid`: if `queryArguments`
1872
+ * argument is invalid (e.g. contains unsupported types).
1873
+ * @throws {@link DittoError} `query/unsupported`: if the query is not a
1874
+ * `SELECT` query.
1875
+ * @throws {@link DittoError} may throw other errors.
1876
+ */
1877
+ registerSubscription(query: string, queryArguments?: DQLQueryArguments): SyncSubscription;
1878
+ /** @internal */
1879
+ get parameters(): SyncParameters;
1880
+ /** @internal */
1881
+ constructor(ditto: Ditto);
1882
+ /**
1883
+ * Removes the passed in `syncSubscription`, configuring Ditto to not receive
1884
+ * updates for documents matching the corresponding query anymore. No-op if
1885
+ * the passed in `syncSubscription` has already been removed.
1886
+ *
1887
+ * This must only be called by the sync subscription itself.
1888
+ *
1889
+ * @param syncSubscription the sync subscription to remove
1890
+ * @returns `true` if the passed in sync subscription could be found and has
1891
+ * been removed, otherwise returns `false`.
1892
+ * @throws {@link DittoError} `internal`: if the replication subscription does not
1893
+ * belong to this store
1894
+ * @throws {@link DittoError} `internal`: if the replication subscription has not
1895
+ * been cancelled yet
1896
+ * @internal
1897
+ */
1898
+ unregisterSubscription(syncSubscription: SyncSubscription): boolean;
1899
+ /** @internal */
1900
+ update(parameters: SyncParameters): void;
1901
+ /** @internal */
1902
+ close(): void;
1903
+ private state;
1904
+ private bluetoothLETransportPointer;
1905
+ private awdlTransportPointer;
1906
+ private lanTransportPointer;
1907
+ private mdnsClientTransportPointer;
1908
+ private mdnsServerAdvertiserPointer;
1909
+ private updatePeerToPeerBluetoothLE;
1910
+ private updatePeerToPeerAWDL;
1911
+ private updatePeerToPeerLAN;
1912
+ private updateListenTCP;
1913
+ private updateListenHTTP;
1914
+ private updateConnectTCPServers;
1915
+ private updateConnectWebsocketURLs;
1916
+ private updateGlobal;
1917
+ private updateConnectRetryInterval;
1918
+ }
1919
+
1920
+ /**
1921
+ * The types of attachment fetch events that can be delivered to an attachment
1922
+ * fetcher's `callback`.
1923
+ */
1924
+ type AttachmentFetchEventType = 'Completed' | 'Progress' | 'Deleted';
1925
+ /**
1926
+ * An attachment fetch event used when the attachment's download has completed.
1927
+ */
1928
+ type AttachmentFetchEventCompleted = {
1929
+ type: 'Completed';
1930
+ attachment: Attachment;
1931
+ };
1932
+ /**
1933
+ * An attachment fetch event used when the attachment's download progressed but
1934
+ * is not yet complete.
1935
+ */
1936
+ type AttachmentFetchEventProgress = {
1937
+ type: 'Progress';
1938
+ totalBytes: number | BigInt;
1939
+ downloadedBytes: number | BigInt;
1940
+ };
1941
+ /**
1942
+ * An attachment fetch event used when the attachment is deleted.
1943
+ */
1944
+ type AttachmentFetchEventDeleted = {
1945
+ type: 'Deleted';
1946
+ };
1947
+ /**
1948
+ * A representation of the events that can occur in relation to an attachment
1949
+ * fetch.
1950
+ *
1951
+ * There are three different attachment fetch events: `Completed`, `Progress`,
1952
+ * or `Deleted`.
1953
+ *
1954
+ * There will be at most one `Completed` or `Deleted` event per attachment
1955
+ * fetch. There can be many `Progress` events delivered for each attachment
1956
+ * fetch.
1957
+ *
1958
+ * Updates relating to an attachment fetch are delivered by registering an
1959
+ * {@link AttachmentFetcher} through a call to
1960
+ * {@link Collection.fetchAttachment | fetchAttachment()} on a
1961
+ * {@link Collection} instance.
1962
+ */
1963
+ type AttachmentFetchEvent = AttachmentFetchEventCompleted | AttachmentFetchEventProgress | AttachmentFetchEventDeleted;
1964
+
1965
+ /**
1966
+ * These objects are returned by calls to
1967
+ * {@link Collection.fetchAttachment | fetchAttachment()} on {@link Collection}
1968
+ * and allow you to stop an in-flight attachment fetch.
1969
+ */
1970
+ declare class AttachmentFetcher implements PromiseLike<Attachment | null> {
1971
+ /**
1972
+ * Returns a promise for the attachment that you can `await`. The promise
1973
+ * resolves to either an attachment or `null` if the attachment has been
1974
+ * deleted meanwhile. The promise is rejected if an error occurs during
1975
+ * the fetch. Note that the `AttachmentFetcher` itself implementes
1976
+ * `PromiseLike`, so you can `await` it directly.
1977
+ */
1978
+ readonly attachment: Promise<Attachment | null>;
1979
+ /**
1980
+ * Stops fetching the associated attachment and cleans up any associated
1981
+ * resources.
1982
+ *
1983
+ * Note that you are not required to call `stop()` once your attachment fetch
1984
+ * operation has finished. The method primarily exists to allow you to cancel
1985
+ * an attachment fetch request while it is ongoing if you no longer wish for
1986
+ * the attachment to be made available locally to the device.
1987
+ */
1988
+ stop(): void;
1989
+ /** @internal */
1990
+ readonly cancelTokenPromise: Promise<unknown | null> | null;
1991
+ /** @internal */
1992
+ readonly ditto: Ditto;
1993
+ /** @internal */
1994
+ readonly id: string;
1995
+ /** @internal */
1996
+ readonly manager: AttachmentFetcherManager;
1997
+ /** @internal */
1998
+ readonly token: AttachmentToken;
1999
+ /** @internal */
2000
+ then<TResult1 = any, TResult2 = never>(onfulfilled?: ((value: any) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): PromiseLike<TResult1 | TResult2>;
2001
+ /** @internal */
2002
+ constructor(ditto: Ditto, token: AttachmentToken, manager: AttachmentFetcherManager, eventHandler?: (attachmentFetchEvent: AttachmentFetchEvent) => void);
2003
+ /**
2004
+ * This function is defined while a fetch is in progress and is used to reject
2005
+ * the promise `this.attachment` when the fetch is canceled.
2006
+ *
2007
+ * @internal
2008
+ */
2009
+ private rejectPendingFetch;
2010
+ }
2011
+
2012
+ /**
2013
+ * Manages attachment fetchers to make sure we free all resources when the
2014
+ * fetcher is garbage collected and to allow us to wait for freeing of
2015
+ * ressources to be finished before the ditto instance is closed.
2016
+ *
2017
+ * @internal */
2018
+ declare class AttachmentFetcherManager {
2019
+ readonly ditto: Ditto;
2020
+ /** @internal */
2021
+ constructor(ditto: Ditto);
2022
+ /**
2023
+ * Start an attachment fetcher.
2024
+ *
2025
+ * @internal */
2026
+ startAttachmentFetcher(token: AttachmentToken, eventHandler?: (attachmentFetchEvent: AttachmentFetchEvent) => void): AttachmentFetcher;
2027
+ /**
2028
+ * Stop an attachment fetcher and wait for it to be stopped.
2029
+ *
2030
+ * @internal */
2031
+ stopAttachmentFetcher(attachmentFetcher: AttachmentFetcher): Promise<void>;
2032
+ /**
2033
+ * Closing the manager will cancel all attachment fetchers.
2034
+ *
2035
+ * @internal
2036
+ */
2037
+ close(): void;
2038
+ private contextInfoByID;
2039
+ private finalizationRegistry;
2040
+ /**
2041
+ * Stop the attachment fetcher without unregistering it from the finalization
2042
+ * registry.
1865
2043
  */
1866
2044
  private stopWithContextInfo;
1867
2045
  }
@@ -1876,19 +2054,21 @@ declare class AttachmentFetcherManager {
1876
2054
  */
1877
2055
  type SmallPeerInfoSyncScope = 'LocalPeerOnly' | 'BigPeerOnly';
1878
2056
  /**
1879
- * The entrypoint for small peer user info collection. Small peer info consists of information
1880
- * gathered into a system collection on a regular interval and optionally synced to the Big Peer
1881
- * for device dashboard and debugging purposes.
2057
+ * The entrypoint for small peer user info collection. Small peer info consists
2058
+ * of information gathered into a system collection on a regular interval and
2059
+ * optionally synced to the Big Peer for device dashboard and debugging
2060
+ * purposes.
1882
2061
  *
1883
- * You don't create this class directly, but can access it from a particular `Ditto`
1884
- * instance via its {@link Ditto.smallPeerInfo | `smallPeerInfo`} property.
2062
+ * An instance of this class is available on each `Ditto` instance via its
2063
+ * {@link Ditto.smallPeerInfo | `smallPeerInfo`} property. Instantiating this
2064
+ * class directly is not supported.
1885
2065
  */
1886
2066
  declare class SmallPeerInfo {
1887
2067
  /**
1888
2068
  * Indicates whether small peer info collection is currently enabled, defaults
1889
2069
  * to `false`.
1890
2070
  *
1891
- * Note: whether the background ingestion process is enabled or not is a
2071
+ * **Note**: whether the background ingestion process is enabled or not is a
1892
2072
  * separate decision to whether this information is allowed to sync to other
1893
2073
  * peers (including the big peer). This is controlled by
1894
2074
  * {@link getSyncScope | getSyncScope()} and
@@ -1901,6 +2081,60 @@ declare class SmallPeerInfo {
1901
2081
  * @throws when set to a non-boolean value.
1902
2082
  */
1903
2083
  set isEnabled(newValue: boolean);
2084
+ /**
2085
+ * The metadata associated with the small peer info.
2086
+ *
2087
+ * Small peer info metadata is a free-form, user-provided JSON object that
2088
+ * is inserted into the small peer info system document at each collection
2089
+ * interval.
2090
+ */
2091
+ get metadata(): Record<string, any>;
2092
+ /**
2093
+ * Set the metadata associated with the small peer info.
2094
+ *
2095
+ * The metadata must be a JSON-serializable object that conforms to the
2096
+ * following constraints:
2097
+ *
2098
+ * - Must be a JSON object (not an array, string, number, etc.)
2099
+ * - The size when encoded as JSON must be less than 128 KB
2100
+ * - May only be nested up to 2 levels deep
2101
+ *
2102
+ * @example <caption>Valid metadata</caption>
2103
+ * ditto.smallPeerInfo.metadata = {
2104
+ * "foo": "bar",
2105
+ * "nested": {
2106
+ * "inner": "value"
2107
+ * }
2108
+ * }
2109
+ *
2110
+ * @example <caption>Invalid metadata</caption>
2111
+ * // This is invalid and results in an error.
2112
+ * ditto.smallPeerInfo.metadata = {
2113
+ * "foo": "bar",
2114
+ * "nested": {
2115
+ * "illegal": {
2116
+ * "inner": "value"
2117
+ * }
2118
+ * }
2119
+ * }
2120
+ *
2121
+ * @throws when set to a value that violates any of the constraints listed
2122
+ * above.
2123
+ */
2124
+ set metadata(metadata: Record<string, any>);
2125
+ /**
2126
+ * The metadata associated with the small peer info, as a JSON string.
2127
+ */
2128
+ get metadataJSONString(): string;
2129
+ /**
2130
+ * Set the metadata associated with the small peer info, as a JSON string.
2131
+ *
2132
+ * @see {@link SmallPeerInfo.metadata | `metadata`} for more information on
2133
+ * valid values.
2134
+ * @throws when set to a value that violates any of the constraints listed in
2135
+ * {@link SmallPeerInfo.metadata | `metadata`}.
2136
+ */
2137
+ set metadataJSONString(metadata: string);
1904
2138
  /**
1905
2139
  * Determines which "kind" of peers the small peer info will be
1906
2140
  * replicated to.
@@ -1947,6 +2181,10 @@ type RemotePeer = {
1947
2181
  * Ditto is the entry point for accessing Ditto-related functionality.
1948
2182
  */
1949
2183
  declare class Ditto {
2184
+ /**
2185
+ * A string containing the semantic version of the Ditto SDK. Example: 4.4.3
2186
+ */
2187
+ static get VERSION(): string;
1950
2188
  /**
1951
2189
  * Configure a custom identifier for the current device.
1952
2190
  *
@@ -1982,6 +2220,10 @@ declare class Ditto {
1982
2220
  * Provides access to the SDK's store functionality.
1983
2221
  */
1984
2222
  readonly store: Store;
2223
+ /**
2224
+ * Provides access to the SDK's sync functionality.
2225
+ */
2226
+ readonly sync: Sync;
1985
2227
  /**
1986
2228
  * Provides access to the SDK's presence functionality.
1987
2229
  */
@@ -2003,18 +2245,18 @@ declare class Ditto {
2003
2245
  *
2004
2246
  * @see {@link setOfflineOnlyLicenseToken | setOfflineOnlyLicenseToken()}
2005
2247
  */
2006
- readonly isActivated: boolean;
2248
+ get isActivated(): boolean;
2007
2249
  /**
2008
2250
  * `true` once {@link close | Ditto.close()} has been called, otherwise
2009
2251
  * `false`.
2010
2252
  */
2011
- readonly isClosed: boolean;
2253
+ get isClosed(): boolean;
2012
2254
  /**
2013
2255
  * Returns `true` if sync is active, otherwise returns `false`. Use
2014
2256
  * {@link startSync | startSync()} to activate and
2015
2257
  * {@link stopSync | stopSync()} to deactivate sync.
2016
2258
  */
2017
- readonly isSyncActive: boolean;
2259
+ get isSyncActive(): boolean;
2018
2260
  /**
2019
2261
  * Application ID associated with the {@link Identity | identity} used by this
2020
2262
  * Ditto instance.
@@ -2036,6 +2278,9 @@ declare class Ditto {
2036
2278
  *
2037
2279
  * @see {@link Ditto.identity}
2038
2280
  * @see {@link Ditto.persistenceDirectory}
2281
+ * @throws {Error} when the current environment is not supported by this SDK.
2282
+ * @throws {Error} for other failures during initialization of Ditto and
2283
+ * validation of the provided identity.
2039
2284
  */
2040
2285
  constructor(identity?: Identity, persistenceDirectory?: string);
2041
2286
  /**
@@ -2102,6 +2347,8 @@ declare class Ditto {
2102
2347
  *
2103
2348
  * @param licenseToken the license token to activate the `Ditto` instance
2104
2349
  * with. You can find yours on the [Ditto portal](https://portal.ditto.live).
2350
+ *
2351
+ * @throws {Error} if called in a React Native environment.
2105
2352
  */
2106
2353
  setOfflineOnlyLicenseToken(licenseToken: string): void;
2107
2354
  /**
@@ -2115,7 +2362,7 @@ declare class Ditto {
2115
2362
  * @see {@link setTransportConfig | setTransportConfig()}
2116
2363
  * @see {@link updateTransportConfig | updateTransportConfig()}
2117
2364
  */
2118
- readonly transportConfig: TransportConfig;
2365
+ get transportConfig(): TransportConfig;
2119
2366
  /**
2120
2367
  * Assigns a new transports configuration. By default peer-to-peer transports
2121
2368
  * (Bluetooth, WiFi, and AWDL) are enabled. You may use this method to alter
@@ -2212,6 +2459,8 @@ declare class Ditto {
2212
2459
  * peers using SDKs in the v4 (or higher) series of releases. Note that this
2213
2460
  * disabling of sync spreads to peers that sync with a peer that has disabled,
2214
2461
  * or has (transitively) had disabled, syncing with v3 SDK peers.
2462
+ *
2463
+ * @throws {Error} if called in a React Native environment.
2215
2464
  */
2216
2465
  disableSyncWithV3(): void;
2217
2466
  /**
@@ -2256,12 +2505,14 @@ declare class Ditto {
2256
2505
  * @throws if the Ditto instance was closed before calling this method.
2257
2506
  * @internal */
2258
2507
  deferCloseAsync<T>(closure: () => Promise<T>): Promise<T>;
2259
- private sync;
2260
2508
  private deferCloseAllowed;
2261
2509
  private isWebValid;
2262
2510
  private isX509Valid;
2263
2511
  private presenceManager;
2264
2512
  private transportConditionsManager;
2513
+ private _isActivated;
2514
+ private _isSyncActive;
2515
+ private _isClosed;
2265
2516
  /** Set of pending operations that need to complete before the Ditto instance can be closed in a safe manner. */
2266
2517
  private pendingOperations;
2267
2518
  private authClientValidityChanged;
@@ -2277,7 +2528,7 @@ declare class Ditto {
2277
2528
  * @returns `true` iff all required APIs exist on `global`.
2278
2529
  * @internal
2279
2530
  */
2280
- declare const checkAPIs: (_globalObject?: Window | typeof globalThis) => boolean;
2531
+ declare const checkAPIs: (_globalObject?: typeof globalThis) => boolean;
2281
2532
  /**
2282
2533
  * Disable deadlock timeout when Node.js is running with `--inspect` parameter.
2283
2534
  *
@@ -2585,503 +2836,362 @@ declare class Collection implements CollectionInterface {
2585
2836
  findByIDCBOR(idCBOR: Uint8Array): PendingIDSpecificOperation;
2586
2837
  }
2587
2838
 
2588
- /** @internal */
2589
- interface CollectionsEventParams {
2590
- isInitial: boolean;
2591
- collections: Collection[];
2592
- oldCollections: Collection[];
2593
- insertions: number[];
2594
- deletions: number[];
2595
- updates: number[];
2596
- moves: LiveQueryMove[];
2597
- }
2598
2839
  /**
2599
- * Provides information about the changes that have occurred in relation to an
2600
- * event delivered when observing the collections in a {@link Store}.
2840
+ * Represents a single match of a DQL query, similar to a “row” in SQL terms.
2841
+ * It’s a reference type serving as a “cursor”, allowing for efficient access of
2842
+ * the underlying data in various formats.
2601
2843
  *
2602
- * It contains information about the collections that are known about as well as
2603
- * the collections that were previously known about in the previous event, along
2604
- * with information about what collections have been inserted, deleted, updated,
2605
- * or moved since the last event.
2844
+ * The {@link QueryResultItem.value | value } property is lazily
2845
+ * materialized and kept in memory until it goes out of scope. To reduce the
2846
+ * memory footprint, structure your code such that items can be processed as a
2847
+ * stream, i.e. one by one (or in batches) and
2848
+ * {@link QueryResultItem.dematerialize | dematerialize() } them
2849
+ * right after use.
2606
2850
  */
2607
- declare class CollectionsEvent {
2608
- /**
2609
- * Indicates whether or not this is the first event to be delivered when
2610
- * observing collections in the store.
2611
- */
2612
- readonly isInitial: boolean;
2851
+ declare class QueryResultItem {
2613
2852
  /**
2614
- * A list of all of the known collections.
2853
+ * Returns the content as a materialized object.
2854
+ *
2855
+ * The item's value is
2856
+ * {@link QueryResultItem.materialize | materialized() } on first access
2857
+ * and subsequently on each access after performing
2858
+ * {@link QueryResultItem.dematerialize | dematerialize() }. Once
2859
+ * materialized, the value is kept in memory until explicitly
2860
+ * {@link QueryResultItem.dematerialize | dematerialize() }-ed or the item
2861
+ * goes out of scope.
2862
+ *
2863
+ * Note: This property is very similar to {@link Document.value}.
2615
2864
  */
2616
- readonly collections: Collection[];
2865
+ get value(): any;
2617
2866
  /**
2618
- * A list of all of the known collections at the time the previous event was
2619
- * delivered.
2867
+ * Returns `true` if value is currently held materialized in memory, otherwise
2868
+ * returns `false`.
2869
+ *
2870
+ * See {@link QueryResultItem.materialize | materialize()} and
2871
+ * {@link QueryResultItem.dematerialize | dematerialize()}.
2620
2872
  */
2621
- readonly oldCollections: Collection[];
2873
+ get isMaterialized(): boolean;
2622
2874
  /**
2623
- * A list of the indexes in the list of currently known about collections at
2624
- * which new collections have been inserted.
2875
+ * Loads the CBOR representation of the item's content, decodes it as an
2876
+ * object so it can be accessed via {@link QueryResultItem.value | value }.
2877
+ * Keeps the object in memory until
2878
+ * {@link QueryResultItem.dematerialize | dematerialize() } is called. No-op
2879
+ * if {@link QueryResultItem.value | value } is already materialized.
2625
2880
  */
2626
- readonly insertions: number[];
2881
+ materialize(): void;
2627
2882
  /**
2628
- * A list of the indexes in the list of previously known about collections at
2629
- * which collections have been removed.
2883
+ * Releases the materialized value from memory. No-op if item is not
2884
+ * materialized.
2630
2885
  */
2631
- readonly deletions: number[];
2886
+ dematerialize(): void;
2632
2887
  /**
2633
- * A list of the indexes in the list of currently known about collections at
2634
- * which pre-existing collections have been updated.
2888
+ * Returns the content of the item as CBOR data.
2889
+ *
2890
+ * Important: The returned CBOR data is not cached, make sure to call this
2891
+ * method once and keep it for as long as needed.
2635
2892
  */
2636
- readonly updates: number[];
2893
+ cborData(): Uint8Array;
2637
2894
  /**
2638
- * A list of the tuples that provides the indexes, in relation to the list of
2639
- * previously known about collections, that already known about collections
2640
- * have moved from and the indexes, in relation to the list of currently known
2641
- * about collections, that the collections have moved to.
2895
+ * Returns the content of the item as a JSON string.
2896
+ *
2897
+ * Important: The returned JSON string is not cached, make sure to call this
2898
+ * method once and keep it for as long as needed.
2642
2899
  */
2643
- readonly moves: LiveQueryMove[];
2644
- /** @internal */
2645
- static initial(collections: Collection[]): CollectionsEvent;
2900
+ jsonString(): string;
2901
+ private materializedValue;
2646
2902
  /** @internal */
2647
- constructor(params: CollectionsEventParams);
2903
+ constructor();
2648
2904
  }
2649
2905
 
2650
2906
  /**
2651
- * The closure that is called whenever the collections covered by a live query
2652
- * change.
2653
- */
2654
- type CollectionsObservationHandler = (event: CollectionsEvent, signalNext?: () => void) => void | Promise<void>;
2655
- /**
2656
- * These objects are returned when calling
2657
- * {@link Store.collections | collections()} on {@link Store}.
2658
- *
2659
- * They allow chaining of further collections-related functions. You can either
2660
- * call {@link exec | exec()} on the object to get an array of
2661
- * {@link Collection}s as an immediate return value, or you can establish either
2662
- * a live query or a subscription, which both work over time.
2663
- *
2664
- * A live query, established by calling
2665
- * {@link PendingCollectionsOperation.observeLocal | observeLocal()}, will
2666
- * notify you every time there's a change in the collections that the device
2667
- * knows about.
2907
+ * Represents results returned when executing a DQL query containing a
2908
+ * {@link QueryResultItem} for each match.
2668
2909
  *
2669
- * A subscription, established by calling {@link subscribe | subscribe()}, will
2670
- * act as a signal to other peers that the device connects to that you would
2671
- * like to receive updates from them about the collections that they know about.
2910
+ * More info, such as metrics, will be provided in the near future.
2672
2911
  */
2673
- declare class PendingCollectionsOperation implements PromiseLike<Collection[]> {
2674
- /**
2675
- * Sort the collections based on a property of the collection.
2676
- *
2677
- * @param propertyPath The property path specifies the logic to be used when
2678
- * sorting the matching collections.
2679
- *
2680
- * @param direction Specify whether you want the sorting order to be
2681
- * `Ascending` or `Descending`.
2682
- *
2683
- * @return A {@link PendingCollectionsOperation} that you can chain further
2684
- * function calls to.
2685
- */
2686
- sort(propertyPath: string, direction?: SortDirection): PendingCollectionsOperation;
2687
- /**
2688
- * Offset the resulting set of collections.
2689
- *
2690
- * This is useful if you aren't interested in the first N collections for one
2691
- * reason or another. For example, you might already have obtained the first
2692
- * 20 collections and so you might want to get the next 20 collections, and
2693
- * that is when you would use {@link offset | offset()}.
2694
- *
2695
- * @param offset The number of collections that you want the eventual
2696
- * resulting set of collections to be offset by (and thus not include).
2697
- *
2698
- * @return A {@link PendingCollectionsOperation} that you can chain further
2699
- * function calls to.
2700
- */
2701
- offset(offset: number): PendingCollectionsOperation;
2702
- /**
2703
- * Limit the number of collections that get returned.
2704
- *
2705
- * @param limit The maximum number of collections that will be returned.
2706
- *
2707
- * @return A {@link PendingCollectionsOperation} that you can chain further
2708
- * function calls to.
2709
- */
2710
- limit(limit: number): PendingCollectionsOperation;
2711
- /**
2712
- * Subscribes the device to updates about collections that other devices know
2713
- * about.
2714
- *
2715
- * The returned {@link Subscription} object must be kept in scope for as long
2716
- * as you want to keep receiving updates.
2717
- *
2718
- * @return A {@link Subscription} object that must be kept in scope for as
2719
- * long as you want to keep receiving updates from other devices about the
2720
- * collections that they know about.
2721
- */
2722
- subscribe(): Subscription;
2912
+ declare class QueryResult {
2723
2913
  /**
2724
- * Enables you to listen for changes that occur in relation to the collections
2725
- * that are known about locally.
2726
- *
2727
- * The returned {@link LiveQuery} object must be kept in scope for as long as
2728
- * you want the provided `handler` to be called when an update occurs.
2729
- *
2730
- * This won't subscribe to receive updates from other devices and so it will
2731
- * only fire when a local change to the known about collections occurs. If
2732
- * you want to receive remote updates as well, then create a subscription via
2733
- * {@link PendingCollectionsOperation.subscribe | subscribe()}.
2734
- *
2735
- * @param handler A closure that will be called every time there is an update
2736
- * about the list of known about collections.
2737
- *
2738
- * @return A {@link LiveQuery} object that must be kept in scope for as long
2739
- * as you want to keep receiving updates.
2914
+ * Individual items matching a DQL query.
2740
2915
  */
2741
- observeLocal(handler: CollectionsObservationHandler): LiveQuery;
2916
+ readonly items: QueryResultItem[];
2742
2917
  /**
2743
- * Enables you to listen for changes that occur in relation to the collections
2744
- * that are known about locally.
2918
+ * IDs of documents that were mutated _locally_ by a _mutating_ DQL query
2919
+ * passed to {@link Store.execute | `execute()`}. Empty array if no documents
2920
+ * have been mutated.
2745
2921
  *
2746
- * The returned {@link LiveQuery} object must be kept in scope for as long as
2747
- * you want the provided `handler` to be called when an update occurs.
2748
- *
2749
- * This won't subscribe to receive updates from other devices and so it will
2750
- * only fire when a local change to the known about collections occurs. If
2751
- * you want to receive remote updates as well, then create a subscription via
2752
- * {@link PendingCollectionsOperation.subscribe | subscribe()}.
2753
- *
2754
- * @param handler A closure that will be called every time there is an update
2755
- * about the list of known about collections.
2922
+ * **Note: Query results received from a {@link StoreObserver} never contain
2923
+ * mutated document IDs because a store observer is always registered using a
2924
+ * non-mutating `SELECT` query.
2756
2925
  *
2757
- * @return A {@link LiveQuery} object that must be kept in scope for as long
2758
- * as you want to keep receiving updates.
2759
- */
2760
- observeLocalWithNextSignal(handler: CollectionsObservationHandler): LiveQuery;
2761
- /**
2762
- * Return the list of collections requested based on the preceding function
2763
- * chaining.
2926
+ * **Important:** The returned document IDs are not cached, make sure to call
2927
+ * this method once and keep the return value for as long as needed.
2764
2928
  *
2765
- * @return A list of {@link Collection}s based on the preceding function
2766
- * chaining.
2929
+ * @returns an array of document IDs
2767
2930
  */
2768
- exec(): Promise<Collection[]>;
2769
- /** @internal */
2770
- readonly store: Store;
2771
- /** @internal */
2772
- constructor(store: Store);
2931
+ mutatedDocumentIDs(): DocumentID[];
2773
2932
  /** @internal */
2774
- then<TResult1 = any, TResult2 = never>(onfulfilled?: ((value: any) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): PromiseLike<TResult1 | TResult2>;
2775
- /** @internal */
2776
- _observe(handler: CollectionsObservationHandler, waitForNextSignal: boolean): LiveQuery;
2777
- private readonly pendingCursorOperation;
2933
+ constructor(responsePointer: Pointer<FFIDqlResponse>);
2778
2934
  }
2779
2935
 
2780
2936
  /**
2781
- * A change listener starts out in the `active` state and can be stopped by
2782
- * calling {@link ExperimentalChangeListener.stop | `stop()`} or letting it
2783
- * go out of scope.
2937
+ * A store observation handler is called whenever an active store observer
2938
+ * receives new results.
2939
+ */
2940
+ type StoreObservationHandler = (queryResult: QueryResult) => void;
2941
+ /**
2942
+ * A store observation handler is called whenever an active store observer
2943
+ * receives new results.
2784
2944
  *
2785
- * @internal
2945
+ * Call `signalNext()` to signal that the handler is ready to receive the next
2946
+ * callback from the store observer.
2786
2947
  */
2787
- type ExperimentalChangeListenerStatus = 'active' | 'stopped';
2948
+ type StoreObservationHandlerWithSignalNext = (queryResult: QueryResult, signalNext: () => void) => void;
2788
2949
  /**
2789
- * A change listener invokes a change handler whenever results for its query
2950
+ * A store observer invokes a given handler whenever results for its query
2790
2951
  * change.
2791
2952
  *
2792
- * Create a listener by calling
2793
- * {@link ExperimentalStore.addChangeListener | `ditto.store.experimental.addChangeListener()`}.
2953
+ * The store observer will remain active until it is {@link cancel | cancelled},
2954
+ * or the Ditto instance managing the observer has been
2955
+ * {@link Ditto.close | closed}.
2794
2956
  *
2795
- * @internal
2957
+ * Create a store observer by calling
2958
+ * {@link Store.registerObserver | `ditto.store.registerObserver()`}.
2796
2959
  */
2797
- declare class ExperimentalChangeListener {
2798
- /**
2799
- * The DQL query this listener is reacting to.
2800
- */
2801
- readonly query: string;
2802
- /**
2803
- * The arguments to this listener's query.
2804
- */
2805
- readonly queryArgs?: QueryArguments;
2806
- /** @internal */
2807
- constructor(store: ExperimentalStore, query: string, queryArgs: QueryArguments | null, onChange: ChangeHandler | ChangeHandlerWithSignalNext, onError?: ErrorHandler, withSignalNext?: boolean);
2808
- /**
2809
- * A change listener starts out in the `active` state and can be stopped by
2810
- * calling {@link ExperimentalChangeListener.stop | `stop()`} or letting it go
2811
- * out of scope.
2812
- */
2813
- get status(): ExperimentalChangeListenerStatus;
2960
+ declare class StoreObserver {
2814
2961
  /**
2815
- * Stops the listener from receiving any more updates.
2962
+ * The Ditto instance this store observer is registered with.
2816
2963
  */
2817
- stop(): void;
2964
+ readonly ditto: Ditto;
2818
2965
  /**
2819
- * The ID of this listener's live query.
2820
- *
2821
- * @internal
2966
+ * The query string of the store observer (as passed when registering it).
2822
2967
  */
2823
- readonly liveQueryID: number;
2824
- /**
2825
- * Closes the listener, preventing it from receiving any more updates.
2826
- *
2827
- * @internal
2828
- * */
2829
- close(): void;
2830
- private store;
2831
- private _status;
2968
+ readonly queryString: string;
2832
2969
  /**
2833
- * Signals to Ditto Core that the listener is ready for the next event.
2970
+ * The query arguments of the store observer (as passed when registering it).
2834
2971
  */
2835
- private signalNext;
2972
+ readonly queryArguments?: Readonly<DQLQueryArguments>;
2836
2973
  /**
2837
- * Creates bridged arguments for the user's change handler from the raw C callback arguments.
2974
+ * Convenience property, returns `true` once the store observer has been
2975
+ * cancelled.
2838
2976
  */
2839
- private static bridgeEventArguments;
2840
- }
2841
-
2842
- /**
2843
- * A change handler is called whenever an active change listener receives new
2844
- * results.
2845
- *
2846
- * @internal
2847
- */
2848
- type ChangeHandler = (result: Document[], event: LiveQueryEvent) => void;
2849
- /**
2850
- * A change handler is called whenever an active change listener receives new
2851
- * results.
2852
- *
2853
- * Call `signalNext()` to signal that the handler is ready to receive the next
2854
- * callback from the change listener.
2855
- *
2856
- * @internal
2857
- */
2858
- type ChangeHandlerWithSignalNext = (result: Document[], event: LiveQueryEvent, signalNext: () => void) => void;
2859
- /**
2860
- * An error handler is called when a change handler throws an error.
2861
- *
2862
- * @internal
2863
- */
2864
- type ErrorHandler = (error: Error) => void;
2865
- /**
2866
- * Manages `ExperimentalChangeListener` instances and removes them when Ditto is closed.
2867
- *
2868
- * @internal
2869
- */
2870
- declare class ExperimentalChangeListenerManager {
2871
- constructor(ditto: Ditto);
2977
+ get isCancelled(): boolean;
2872
2978
  /**
2873
- * Register and start a change listener in core, also registering it in the listener manager.
2874
- *
2875
- * @internal
2979
+ * Cancels the store observer and unregisters it. No-op if the
2980
+ * store observer has already been cancelled.
2876
2981
  */
2877
- addChangeListener(listener: ExperimentalChangeListener): void;
2982
+ cancel(): void;
2878
2983
  /**
2879
- * Mark all change listeners as closed while deferring the closing of Ditto.
2984
+ * The ID of this observer's live query.
2880
2985
  *
2881
2986
  * @internal
2882
2987
  */
2883
- close(): void;
2988
+ readonly liveQueryID: number;
2989
+ /** @internal */
2990
+ constructor(ditto: Ditto, query: string, queryArguments: DQLQueryArguments | null, observationHandler: StoreObservationHandlerWithSignalNext);
2884
2991
  /**
2885
- * Remove a change listener from the listener manager and stop it in core.
2992
+ * `true` when the store observer has been cancelled.
2886
2993
  *
2887
- * @internal
2888
- * @param listener The change listener to remove.
2994
+ * We mark the store observer as cancelled here as an optimization to avoid a
2995
+ * scan of all store observers in the store whenever the `isCancelled`
2996
+ * property is checked.
2889
2997
  */
2890
- removeChangeListener(listener: ExperimentalChangeListener): void;
2891
- private readonly ditto;
2892
- private readonly keepAlive;
2893
- private readonly listenersById;
2998
+ private _isCancelled;
2894
2999
  /**
2895
- * Keeps track of change listeners by live query ID.
3000
+ * Signals to Ditto Core that the observer is ready for the next event.
2896
3001
  */
2897
- private readonly finalizationRegistry;
2898
- /**
2899
- * Remove a change listener without unregistering it from the finalization registry.
2900
- */
2901
- private stopLiveQuery;
3002
+ private signalNext;
2902
3003
  }
2903
3004
 
3005
+ /** @internal */
3006
+ interface CollectionsEventParams {
3007
+ isInitial: boolean;
3008
+ collections: Collection[];
3009
+ oldCollections: Collection[];
3010
+ insertions: number[];
3011
+ deletions: number[];
3012
+ updates: number[];
3013
+ moves: LiveQueryMove[];
3014
+ }
2904
3015
  /**
2905
- * Manages `ExperimentalReplicationSubscription` instances and removes them when Ditto is
2906
- * closed.
3016
+ * Provides information about the changes that have occurred in relation to an
3017
+ * event delivered when observing the collections in a {@link Store}.
2907
3018
  *
2908
- * @internal
3019
+ * It contains information about the collections that are known about as well as
3020
+ * the collections that were previously known about in the previous event, along
3021
+ * with information about what collections have been inserted, deleted, updated,
3022
+ * or moved since the last event.
2909
3023
  */
2910
- declare class ExperimentalReplicationSubscriptionManager {
2911
- constructor(ditto: Ditto);
2912
- /**
2913
- * Begin tracking a replication subscription instance and start it.
2914
- *
2915
- * @internal
2916
- */
2917
- addSubscription(subscription: ExperimentalReplicationSubscription): void;
3024
+ declare class CollectionsEvent {
2918
3025
  /**
2919
- * Stop tracking a replication subscription instance and cancel it.
2920
- *
2921
- * @internal
3026
+ * Indicates whether or not this is the first event to be delivered when
3027
+ * observing collections in the store.
2922
3028
  */
2923
- removeSubscription(subscription: ExperimentalReplicationSubscription): void;
3029
+ readonly isInitial: boolean;
2924
3030
  /**
2925
- * Stop tracking all replication subscriptions and cancel them.
2926
- *
2927
- * @internal
3031
+ * A list of all of the known collections.
2928
3032
  */
2929
- close(): void;
2930
- private readonly ditto;
2931
- private subscriptions;
2932
- private finalizationRegistry;
3033
+ readonly collections: Collection[];
2933
3034
  /**
2934
- * Remove tracked replication subscription without unregistering from
2935
- * finalization registry.
3035
+ * A list of all of the known collections at the time the previous event was
3036
+ * delivered.
2936
3037
  */
2937
- private removeWithContextInfo;
2938
- }
2939
-
2940
- /**
2941
- * Contains all information required to deregister a replication subscription in
2942
- * Ditto Core, even when the replication subscription instance itself has
2943
- * already been garbage collected.
2944
- *
2945
- * @internal
2946
- */
2947
- type ExperimentalReplicationSubscriptionContextInfo = {
2948
- /** Unique ID per `ExperimentalSubscription` instance. */
2949
- id: string;
2950
- query: string;
2951
- queryArgsCBOR: Uint8Array | null;
2952
- };
2953
- /**
2954
- * Create a replication subscription to receive updates from remote peers about
2955
- * documents matching the replication subscription's query.
2956
- *
2957
- * The replication subscription will remain active until
2958
- * {@link cancel | cancel()} is called or the replication subscription object
2959
- * goes out of scope and is garbage collected.
2960
- *
2961
- * @internal
2962
- */
2963
- declare class ExperimentalReplicationSubscription {
3038
+ readonly oldCollections: Collection[];
2964
3039
  /**
2965
- * Documents matching this query will be included in the replication subscription.
3040
+ * A list of the indexes in the list of currently known about collections at
3041
+ * which new collections have been inserted.
2966
3042
  */
2967
- readonly query: string;
3043
+ readonly insertions: number[];
2968
3044
  /**
2969
- * `true` when {@link cancel | cancel()} has been called or the Ditto instance
2970
- * managing this replication subscription has been closed.
3045
+ * A list of the indexes in the list of previously known about collections at
3046
+ * which collections have been removed.
2971
3047
  */
2972
- readonly isCancelled = false;
3048
+ readonly deletions: number[];
2973
3049
  /**
2974
- * Cancels a replication subscription and releases all associated resources.
3050
+ * A list of the indexes in the list of currently known about collections at
3051
+ * which pre-existing collections have been updated.
2975
3052
  */
2976
- cancel(): void;
2977
- /** @internal */
2978
- constructor(manager: ExperimentalReplicationSubscriptionManager, query: string, queryArgsCBOR: Uint8Array | null);
2979
- /** @internal */
2980
- contextInfo: ExperimentalReplicationSubscriptionContextInfo;
3053
+ readonly updates: number[];
2981
3054
  /**
2982
- * The corresponding named arguments for {@link query}, if any.
2983
- *
2984
- * @internal
3055
+ * A list of the tuples that provides the indexes, in relation to the list of
3056
+ * previously known about collections, that already known about collections
3057
+ * have moved from and the indexes, in relation to the list of currently known
3058
+ * about collections, that the collections have moved to.
2985
3059
  */
2986
- readonly queryArgsCBOR: Uint8Array | null;
3060
+ readonly moves: LiveQueryMove[];
2987
3061
  /** @internal */
2988
- private manager;
3062
+ static initial(collections: Collection[]): CollectionsEvent;
3063
+ /** @internal */
3064
+ constructor(params: CollectionsEventParams);
2989
3065
  }
2990
3066
 
2991
3067
  /**
2992
- * An addon for the Ditto store that contains experimental features. Accessible
2993
- * on `ditto.store.experimental`.
3068
+ * The closure that is called whenever the collections covered by a live query
3069
+ * change.
3070
+ */
3071
+ type CollectionsObservationHandler = (event: CollectionsEvent, signalNext?: () => void) => void | Promise<void>;
3072
+ /**
3073
+ * These objects are returned when calling
3074
+ * {@link Store.collections | collections()} on {@link Store}.
2994
3075
  *
2995
- * @internal
3076
+ * They allow chaining of further collections-related functions. You can either
3077
+ * call {@link exec | exec()} on the object to get an array of
3078
+ * {@link Collection}s as an immediate return value, or you can establish either
3079
+ * a live query or a subscription, which both work over time.
3080
+ *
3081
+ * A live query, established by calling
3082
+ * {@link PendingCollectionsOperation.observeLocal | observeLocal()}, will
3083
+ * notify you every time there's a change in the collections that the device
3084
+ * knows about.
3085
+ *
3086
+ * A subscription, established by calling {@link subscribe | subscribe()}, will
3087
+ * act as a signal to other peers that the device connects to that you would
3088
+ * like to receive updates from them about the collections that they know about.
2996
3089
  */
2997
- declare class ExperimentalStore {
2998
- /**
2999
- * The {@link Ditto} instance this store belongs to.
3000
- * @internal
3001
- * */
3002
- readonly ditto: Ditto;
3003
- /** @internal */
3004
- readonly listenerManager: ExperimentalChangeListenerManager;
3005
- /** @internal */
3006
- constructor(ditto: Ditto);
3090
+ declare class PendingCollectionsOperation implements PromiseLike<Collection[]> {
3007
3091
  /**
3008
- * Register a handler to be called whenever a query's results change in the
3009
- * local store.
3092
+ * Sort the collections based on a property of the collection.
3093
+ *
3094
+ * @param propertyPath The property path specifies the logic to be used when
3095
+ * sorting the matching collections.
3010
3096
  *
3011
- * The returned {@link ExperimentalChangeListener} must be kept in scope for
3012
- * as long as the change handler should be called with new change events.
3097
+ * @param direction Specify whether you want the sorting order to be
3098
+ * `Ascending` or `Descending`.
3013
3099
  *
3014
- * The given query may not modify any documents and must be a valid Ditto
3015
- * Query Language query.
3100
+ * @return A {@link PendingCollectionsOperation} that you can chain further
3101
+ * function calls to.
3102
+ */
3103
+ sort(propertyPath: string, direction?: SortDirection): PendingCollectionsOperation;
3104
+ /**
3105
+ * Offset the resulting set of collections.
3016
3106
  *
3017
- * If no `onError` argument is provided, errors that are thrown in the
3018
- * provided change handler will be logged to the console.
3107
+ * This is useful if you aren't interested in the first N collections for one
3108
+ * reason or another. For example, you might already have obtained the first
3109
+ * 20 collections and so you might want to get the next 20 collections, and
3110
+ * that is when you would use {@link offset | offset()}.
3019
3111
  *
3020
- * The first invocation of `onChange` will always happen after this method
3021
- * returns. The next call to `onChange` will always wait until the previous
3022
- * call has returned. Use
3023
- * {@link ExperimentalStore.addChangeListenerWithSignalNext | addChangeListenerWithSignalNext()}
3024
- * if you want to control the rate of callbacks yourself.
3112
+ * @param offset The number of collections that you want the eventual
3113
+ * resulting set of collections to be offset by (and thus not include).
3025
3114
  *
3026
- * @internal
3115
+ * @return A {@link PendingCollectionsOperation} that you can chain further
3116
+ * function calls to.
3027
3117
  */
3028
- addChangeListener(query: string, onChange: ChangeHandler, onError?: ErrorHandler, queryArgs?: QueryArguments): ExperimentalChangeListener;
3118
+ offset(offset: number): PendingCollectionsOperation;
3029
3119
  /**
3030
- * Register a handler to be called whenever a query's results change in the
3031
- * local store and control when the next invocation of the change handler
3032
- * happens.
3033
- *
3034
- * Here, a function is passed as an additional argument to the change handler.
3035
- * Call this function as soon as the change handler is ready to process the
3036
- * the next change event. This allows the change handler to control how often
3037
- * it is called.
3120
+ * Limit the number of collections that get returned.
3038
3121
  *
3039
- * Otherwise identical to
3040
- * {@link ExperimentalStore.addChangeListener | addChangeListener()}.
3122
+ * @param limit The maximum number of collections that will be returned.
3041
3123
  *
3042
- * @internal
3124
+ * @return A {@link PendingCollectionsOperation} that you can chain further
3125
+ * function calls to.
3043
3126
  */
3044
- addChangeListenerWithSignalNext(query: string, onChange: ChangeHandlerWithSignalNext, onError?: ErrorHandler, queryArgs?: QueryArguments): ExperimentalChangeListener;
3127
+ limit(limit: number): PendingCollectionsOperation;
3045
3128
  /**
3046
- * Registers a URL to be called whenever the given query observes changes.
3129
+ * Subscribes the device to updates about collections that other devices know
3130
+ * about.
3047
3131
  *
3048
- * This API will stay internal-only as it is only used in the portal.
3132
+ * The returned {@link Subscription} object must be kept in scope for as long
3133
+ * as you want to keep receiving updates.
3049
3134
  *
3050
- * @internal
3051
- * @returns a promise for a document id that acts as a webhook id
3135
+ * @return A {@link Subscription} object that must be kept in scope for as
3136
+ * long as you want to keep receiving updates from other devices about the
3137
+ * collections that they know about.
3052
3138
  */
3053
- addChangeListenerWebhook(query: string, url: string, queryArgs?: QueryArguments): Promise<DocumentID>;
3139
+ subscribe(): Subscription;
3054
3140
  /**
3055
- * Run the provided query on the device of connected peers and send the
3056
- * results of the query back to the local peer's data store.
3141
+ * Enables you to listen for changes that occur in relation to the collections
3142
+ * that are known about locally.
3057
3143
  *
3058
- * The returned {@link ExperimentalReplicationSubscription} object must be kept in scope
3059
- * for as long as you want to keep receiving updates.
3144
+ * The returned {@link LiveQuery} object must be kept in scope for as long as
3145
+ * you want the provided `handler` to be called when an update occurs.
3060
3146
  *
3061
- * @internal
3062
- * @param query a Ditto Query Language query string of the form SELECT * FROM
3063
- * collection WHERE expression
3064
- * @returns {@link ExperimentalReplicationSubscription} object
3147
+ * This won't subscribe to receive updates from other devices and so it will
3148
+ * only fire when a local change to the known about collections occurs. If
3149
+ * you want to receive remote updates as well, then create a subscription via
3150
+ * {@link PendingCollectionsOperation.subscribe | subscribe()}.
3151
+ *
3152
+ * @param handler A closure that will be called every time there is an update
3153
+ * about the list of known about collections.
3154
+ *
3155
+ * @return A {@link LiveQuery} object that must be kept in scope for as long
3156
+ * as you want to keep receiving updates.
3065
3157
  */
3066
- addReplicationSubscription(query: string): ExperimentalReplicationSubscription;
3067
- /** @internal */
3068
- close(): void;
3158
+ observeLocal(handler: CollectionsObservationHandler): LiveQuery;
3069
3159
  /**
3070
- * Executes the given query in the local store and returns the result.
3160
+ * Enables you to listen for changes that occur in relation to the collections
3161
+ * that are known about locally.
3162
+ *
3163
+ * The returned {@link LiveQuery} object must be kept in scope for as long as
3164
+ * you want the provided `handler` to be called when an update occurs.
3071
3165
  *
3072
- * Limitations:
3166
+ * This won't subscribe to receive updates from other devices and so it will
3167
+ * only fire when a local change to the known about collections occurs. If
3168
+ * you want to receive remote updates as well, then create a subscription via
3169
+ * {@link PendingCollectionsOperation.subscribe | subscribe()}.
3073
3170
  *
3074
- * - Supports `SELECT * FROM <collection name>` with optional `WHERE
3075
- * <expression>`
3076
- * - No query parameters as function arguments yet
3077
- * - No transactions
3171
+ * @param handler A closure that will be called every time there is an update
3172
+ * about the list of known about collections.
3078
3173
  *
3079
- * @internal
3080
- * @param query a Ditto Query Language query string
3081
- * @returns a promise for an array of Ditto documents matching the query
3174
+ * @return A {@link LiveQuery} object that must be kept in scope for as long
3175
+ * as you want to keep receiving updates.
3176
+ */
3177
+ observeLocalWithNextSignal(handler: CollectionsObservationHandler): LiveQuery;
3178
+ /**
3179
+ * Return the list of collections requested based on the preceding function
3180
+ * chaining.
3181
+ *
3182
+ * @return A list of {@link Collection}s based on the preceding function
3183
+ * chaining.
3082
3184
  */
3083
- execute(query: string): Promise<Document[]>;
3084
- private replicationSubscriptionManager;
3185
+ exec(): Promise<Collection[]>;
3186
+ /** @internal */
3187
+ readonly store: Store;
3188
+ /** @internal */
3189
+ constructor(store: Store);
3190
+ /** @internal */
3191
+ then<TResult1 = any, TResult2 = never>(onfulfilled?: ((value: any) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): PromiseLike<TResult1 | TResult2>;
3192
+ /** @internal */
3193
+ _observe(handler: CollectionsObservationHandler, waitForNextSignal: boolean): LiveQuery;
3194
+ private readonly pendingCursorOperation;
3085
3195
  }
3086
3196
 
3087
3197
  /**
@@ -3253,8 +3363,77 @@ declare class WriteTransaction {
3253
3363
  declare class Store {
3254
3364
  /** The {@link Ditto} instance this store belongs to. */
3255
3365
  readonly ditto: Ditto;
3256
- /** @internal */
3257
- readonly experimental: ExperimentalStore;
3366
+ /**
3367
+ * All currently active store observers.
3368
+ *
3369
+ * **Note:** Manage store observers using
3370
+ * {@link registerObserver | registerObserver()} to register a new store
3371
+ * observer and {@link StoreObserver.cancel | StoreObserver.cancel()} to
3372
+ * remove an existing store observer.
3373
+ */
3374
+ readonly observers: Readonly<Array<StoreObserver>>;
3375
+ /**
3376
+ * Register a handler to be called whenever a query's results change in the
3377
+ * local store.
3378
+ *
3379
+ * Convenience method, same as
3380
+ * {@link registerObserverWithSignalNext | registerObserverWithSignalNext()},
3381
+ * except that here, the next invocation of the observation handler is
3382
+ * triggered automatically instead of having to call the passed in
3383
+ * `signalNext` function.
3384
+ *
3385
+ * @param query a string containing a valid query expressed in DQL.
3386
+ * @param observationHandler a function that is called whenever the query's results
3387
+ * change. The function is passed a {@link QueryResult} containing a
3388
+ * {@link QueryResultItem} for each match.
3389
+ * @param queryArguments an object of values keyed by the placeholder name
3390
+ * without the leading `:`. Example: `{ "name": "Joanna" }` for a query like
3391
+ * `SELECT * FROM people WHERE name = :name`.
3392
+ * @returns a {@link StoreObserver} that can be used to cancel the
3393
+ * observation.
3394
+ * @throws {@link DittoError} `query/invalid`: if `query` argument is not a
3395
+ * string or not valid DQL.
3396
+ * @throws {@link DittoError} `query/arguments-invalid`: if `queryArguments`
3397
+ * argument is invalid (e.g. contains unsupported types).
3398
+ * @throws {@link DittoError} `query/unsupported`: if the query is not a
3399
+ * `SELECT` query.
3400
+ * @throws {@link DittoError} may throw other errors.
3401
+ */
3402
+ registerObserver(query: string, observationHandler: StoreObservationHandler, queryArguments?: DQLQueryArguments): StoreObserver;
3403
+ /**
3404
+ * Registers and returns a store observer for a query, configuring Ditto to
3405
+ * trigger the passed in observation handler whenever documents in the local
3406
+ * store change such that the result of the matching query changes. The passed
3407
+ * in query must be a `SELECT` query.
3408
+ *
3409
+ * Here, a function is passed as an additional argument to the observation
3410
+ * handler. Call this function as soon as the observation handler is ready to
3411
+ * process the the next change event. This allows the observation handler to
3412
+ * control how frequently it is called. See
3413
+ * {@link registerObserver | registerObserver()} for a convenience method that
3414
+ * automatically signals the next invocation.
3415
+ *
3416
+ * The first invocation of `observationHandler` will always happen after this
3417
+ * method has returned.
3418
+ *
3419
+ * @param query a string containing a valid query expressed in DQL.
3420
+ * @param observationHandler an observation handler function that is called
3421
+ * whenever the query's results change. The function is passed a
3422
+ * {@link QueryResult} containing a {@link QueryResultItem} for each match.
3423
+ * @param queryArguments an object of values keyed by the placeholder name
3424
+ * without the leading `:`. Example: `{ "name": "Joanna" }` for a query like
3425
+ * `SELECT * FROM people WHERE name = :name`.
3426
+ * @returns a {@link StoreObserver} that can be used to cancel the
3427
+ * observation.
3428
+ * @throws {@link DittoError} `query/invalid`: if `query` argument is not a
3429
+ * string or not valid DQL.
3430
+ * @throws {@link DittoError} `query/arguments-invalid`: if `queryArguments`
3431
+ * argument is invalid (e.g. contains unsupported types).
3432
+ * @throws {@link DittoError} `query/unsupported`: if the query is not a
3433
+ * `SELECT` query.
3434
+ * @throws {@link DittoError} may throw other errors.
3435
+ */
3436
+ registerObserverWithSignalNext(query: string, observationHandler: StoreObservationHandlerWithSignalNext, queryArguments?: DQLQueryArguments): StoreObserver;
3258
3437
  /**
3259
3438
  * Returns the collection for the given name. If the collection doesn't
3260
3439
  * exist yet, it will be created automatically as soon as the first
@@ -3279,6 +3458,22 @@ declare class Store {
3279
3458
  * related {@link Ditto} instance.
3280
3459
  */
3281
3460
  collectionNames(): Promise<string[]>;
3461
+ /**
3462
+ * Executes a DQL query and returns matching items as a query result.
3463
+ *
3464
+ * @param query a string containing a valid query expressed in DQL.
3465
+ * @param queryArguments an object of values keyed by the placeholder name
3466
+ * without the leading `:`. Example: `{ "name": "John" }` for a query like
3467
+ * `SELECT * FROM people WHERE name = :name`.
3468
+ * @returns a promise for a {@link QueryResult} containing a
3469
+ * {@link QueryResultItem} for each match.
3470
+ * @throws {@link DittoError} `query/invalid`: if `query` argument is not a
3471
+ * string or not valid DQL.
3472
+ * @throws {@link DittoError} `query/arguments-invalid`: if `queryArguments`
3473
+ * argument is invalid (e.g. contains unsupported types).
3474
+ * @throws {@link DittoError} may throw other errors.
3475
+ */
3476
+ execute(query: string, queryArguments?: DQLQueryArguments): Promise<QueryResult>;
3282
3477
  /**
3283
3478
  * Initiate a write transaction in a callback.
3284
3479
  *
@@ -3290,6 +3485,40 @@ declare class Store {
3290
3485
  write(callback: (transaction: WriteTransaction) => Promise<void>): Promise<WriteTransactionResult[]>;
3291
3486
  /** @internal */
3292
3487
  constructor(ditto: Ditto);
3488
+ /**
3489
+ * Registers a URL to be called whenever the given `SELECT` query observes
3490
+ * changes.
3491
+ *
3492
+ * No validation is performed on the URL, so it is up to the caller to ensure
3493
+ * that the URL is valid and can be reached.
3494
+ *
3495
+ * @internal
3496
+ * @returns a promise for a document id that acts as a webhook id
3497
+ * @throws {@link DittoError} `store/query-invalid`: if the query is invalid
3498
+ * @throws {@link DittoError} `store/query-arguments-invalid`: if the query arguments
3499
+ * are invalid
3500
+ * @throws {@link DittoError} `store/query-unsupported`: if the query is not a
3501
+ * `SELECT` query
3502
+ * @throws {@link DittoError} for any other error that occurs during query execution
3503
+ */
3504
+ registerObserverWebhook(query: string, url: string, queryArguments?: DQLQueryArguments): Promise<DocumentID>;
3505
+ /**
3506
+ * Unregister a store observer. No-op if the change observer has already
3507
+ * been removed.
3508
+ *
3509
+ * This must only be called by the store observer itself.
3510
+ *
3511
+ * @param changeObserver the store observer to unregister
3512
+ * @returns true if the store observer was found and removed, false otherwise
3513
+ * @throws {@link DittoError} `internal`: if the store observer does not belong to
3514
+ * this store
3515
+ * @throws {@link DittoError} `internal`: if the store observer has not been
3516
+ * cancelled yet
3517
+ * @throws {@link DittoError} `internal`: for any other error that occurs while
3518
+ * trying to unregister the store observer
3519
+ * @internal
3520
+ */
3521
+ unregisterObserver(storeObserver: StoreObserver): boolean;
3293
3522
  /** @internal */
3294
3523
  close(): void;
3295
3524
  /**
@@ -3462,6 +3691,200 @@ declare abstract class BasePendingCursorOperation implements PromiseLike<Documen
3462
3691
  protected orderBys: OrderBy[];
3463
3692
  }
3464
3693
 
3694
+ type ErrorCode = keyof typeof ERROR_CODES;
3695
+ /**
3696
+ * Error code and default error message for all Ditto error messages.
3697
+ *
3698
+ * Keys of this object define _error codes_ with each value containing the
3699
+ * accompanying error description that is set as the default error message for
3700
+ * errors instantiated with this code.
3701
+ *
3702
+ * Error codes may start with an error domain and a slash to group categories of
3703
+ * errors together.
3704
+ */
3705
+ declare const ERROR_CODES: {
3706
+ /** Internal error for unexpected system states */
3707
+ readonly internal: "An unexpected internal error occured. Please get in touch with Ditto customer service to report this incident.";
3708
+ /** Internal error with an unknown error cause **/
3709
+ readonly 'internal/unknown-error': "An unexpected internal error occured. Please get in touch with Ditto customer service to report this incident.";
3710
+ /** Error for invalid DQL query arguments. */
3711
+ readonly 'query/arguments-invalid': "The query arguments were invalid.";
3712
+ /** Errors that occur during execution of a query */
3713
+ readonly 'query/execution': "The query could not be executed.";
3714
+ /** Error for an invalid DQL query. */
3715
+ readonly 'query/invalid': "The query was invalid.";
3716
+ /** Error for a query that uses DQL features not supported in this version or not supported by the currently used API. */
3717
+ readonly 'query/unsupported': "The query contains unsupported features.";
3718
+ /** Error in the storage backend. */
3719
+ readonly 'store/backend': "An error occurred with the storage backend.";
3720
+ /** Error for an invalid CRDT. */
3721
+ readonly 'store/crdt': "An error occurred processing a CRDT.";
3722
+ /** Error for a document not found. */
3723
+ readonly 'store/document-not-found': "The document with the provided ID could not be found.";
3724
+ };
3725
+
3726
+ /**
3727
+ * Error codes for FFI result.
3728
+ *
3729
+ * @internal
3730
+ */
3731
+ type FFIResultErrorCode = 'StoreDocumentNotFound' | 'StoreDatabase' | 'StoreQuery' | 'Crdt' | 'JsFloatingStoreOperation' | 'DqlQueryCompilation' | 'DqlInvalidQueryArgs' | 'DqlUnsupported';
3732
+ /**
3733
+ * Represents an exception that occurred during a call into the Ditto FFI.
3734
+ *
3735
+ * Use the {@link throwOnErrorStatus | throwOnErrorStatus()} helper to
3736
+ * automatically throw this error when an FFI call returns with a non-zero
3737
+ * return value.
3738
+ *
3739
+ * @internal
3740
+ */
3741
+ declare class DittoFFIError extends Error {
3742
+ /**
3743
+ * The code identifying this error.
3744
+ *
3745
+ * May be a numerical status code returned by an FFI call or an
3746
+ * {@link FFIResultErrorCode} for errors returned on FFI result objects.
3747
+ *
3748
+ * @see {@link throwOnErrorStatus | throwOnErrorStatus()}
3749
+ */
3750
+ readonly code: number | FFIResultErrorCode;
3751
+ /**
3752
+ * Only call this constructor after having called `FFI.ensureInitialized()`
3753
+ * and `FFI.trace()`.
3754
+ *
3755
+ * @param code numerical status code returned by an FFI call or an
3756
+ * {@link FFIResultErrorCode} for errors returned on FFI result objects
3757
+ * @param messageOverride overrides the thread-local error message set in
3758
+ * Ditto core
3759
+ * @param messageFallback fallback message to use if the thread-local error
3760
+ * message is empty
3761
+ */
3762
+ constructor(code: number | FFIResultErrorCode, messageOverride?: string, messageFallback?: string);
3763
+ }
3764
+
3765
+ /**
3766
+ * Additional data, which provides context to the error and may help with
3767
+ * debugging.
3768
+ *
3769
+ * **Warning:** The contents of this object may change in future versions of
3770
+ * the SDK.
3771
+ */
3772
+ type ErrorContext = Record<string, any>;
3773
+ /**
3774
+ * `DittoError` is a subclass of the default Javascript `Error`. You can
3775
+ * identify specific errors programatically using the
3776
+ * {@link DittoError.code | code} property.
3777
+ *
3778
+ * Please reference {@link ERROR_CODES} for a comprehensive list of
3779
+ * possible error codes in this SDK version.
3780
+ */
3781
+ declare class DittoError extends Error {
3782
+ /**
3783
+ * Use the error code to identify a specific error programatically.
3784
+ *
3785
+ * @see {@link ERROR_CODES} for a comprehensive list of possible
3786
+ * error codes in this SDK version.
3787
+ */
3788
+ readonly code: ErrorCode;
3789
+ /** Some environments provide a stack trace that is attached to any error. */
3790
+ readonly stack?: string;
3791
+ /**
3792
+ * Additional data, which provides context to the error and may help with
3793
+ * debugging.
3794
+ *
3795
+ * **Warning:** The contents of this object may change in future versions of
3796
+ * the SDK.
3797
+ */
3798
+ readonly context: Readonly<ErrorContext>;
3799
+ /**
3800
+ * @internal
3801
+ * @param code string error code, see {@link ERROR_CODES}
3802
+ * @param message optional error message that replace's the message for the given error code
3803
+ * @param context optional object containing data that can help debug this error
3804
+ * @throws {@link DittoError} `internal`: when supplied with an invalid error code
3805
+ */
3806
+ constructor(code: ErrorCode, message?: string | null, context?: ErrorContext);
3807
+ /**
3808
+ * Create a {@link DittoError} from a {@link DittoFFIError}.
3809
+ *
3810
+ * The error message will be set to the optional `messageOverride` parameter
3811
+ * if supplied, otherwise it will be taken from the `message` property of the
3812
+ * given {@link DittoFFIError}. In any case, the details of the underlying FFI
3813
+ * error are made available in the error context of the returned {@link DittoError}.
3814
+ *
3815
+ * @internal
3816
+ * @param code string error code from {@link ERROR_CODES}
3817
+ * @param messageOverride optional string that will be used as the error
3818
+ * message even if a thread-local error message has been retrieved from the
3819
+ * FFI
3820
+ * @param context optional object containing data that can help debug this error
3821
+ * @returns {@link DittoError}
3822
+ */
3823
+ static fromFFIError(ffiError: DittoFFIError, code: ErrorCode, messageOverride?: string, context?: ErrorContext): DittoError;
3824
+ }
3825
+ /**
3826
+ * Wraps the given function to catch any {@link DittoFFIError} and rethrow it as
3827
+ * a {@link DittoError}, mapping status codes of the {@link DittoFFIError} to
3828
+ * error codes of the {@link DittoError} using the given `statusCodeMapping`.
3829
+ *
3830
+ * Use either this function or {@link mapFFIErrorsAsync} to wrap all calls into
3831
+ * the FFI that can fail.
3832
+ *
3833
+ * If the given status code mapping contains error messages, they will replace
3834
+ * any error message that is returned by the FFI.
3835
+ *
3836
+ * @internal
3837
+ * @param closure function that can throw a {@link DittoFFIError}
3838
+ * @param statusCodeMapping optional mapping of status codes of the
3839
+ * {@link DittoFFIError} to error codes of the {@link DittoError}
3840
+ * @param context optional object containing data that can help debug this error
3841
+ * @throws {@link DittoError} when the wrapped function throws a {@link DittoFFIError}
3842
+ */
3843
+ declare function mapFFIErrors<T>(closure: () => T, statusCodeMapping?: FFIErrorMapping, context?: ErrorContext): T;
3844
+ /**
3845
+ * Wraps the given async function to catch any {@link DittoFFIError} and rethrow
3846
+ * it as a {@link DittoError}, mapping status codes of the {@link DittoFFIError}
3847
+ * to error codes of the {@link DittoError} using the given `statusCodeMapping`.
3848
+ *
3849
+ * Use either this function or {@link mapFFIErrors} to wrap any calls into the
3850
+ * FFI that can fail.
3851
+ *
3852
+ * If the given status code mapping contains error messages, they will replace
3853
+ * any error message that is returned by the FFI.
3854
+ *
3855
+ * @internal
3856
+ * @param closure async function that can throw a {@link DittoFFIError}
3857
+ * @param statusCodeMapping optional mapping of status codes of the
3858
+ * {@link DittoFFIError} to error codes of the {@link DittoError}.
3859
+ * @param context optional object containing data that can help debug this error
3860
+ * @throws {@link DittoError} when the wrapped function throws a {@link DittoFFIError}
3861
+ */
3862
+ declare function mapFFIErrorsAsync<T>(closure: () => Promise<T>, statusCodeMapping?: FFIErrorMapping, context?: ErrorContext): Promise<T>;
3863
+ /**
3864
+ * Defines which status code of an FFI response should be mapped to which error
3865
+ * code of a {@link DittoError}.
3866
+ *
3867
+ * The second element of the tuple is an optional string that will be used as
3868
+ * the error message of the {@link DittoError} instead of the FFI error message
3869
+ * if defined.
3870
+ *
3871
+ * If a key `default` is present, it will be used as the error code if no
3872
+ * mapping for a given status code is found.
3873
+ *
3874
+ * @example
3875
+ * ```typescript
3876
+ * const statusCodeMapping: FFIErrorMapping = {
3877
+ * '1': ['activation/failed', 'It just didn\'t work out'],
3878
+ * 'default': ['sdk/environment-incompatible']
3879
+ * }
3880
+ * ```
3881
+ *
3882
+ * @internal
3883
+ */
3884
+ type FFIErrorMapping = {
3885
+ [statusCode: string]: [ErrorCode, string?];
3886
+ };
3887
+
3465
3888
  /**
3466
3889
  * Get a count of bridged objects binned by bridge type.
3467
3890
  *
@@ -3477,10 +3900,17 @@ declare function getBridgeLoad(): {
3477
3900
  /** @internal */
3478
3901
  declare class CBOR {
3479
3902
  /** @internal */
3480
- static encode(data: any): Uint8Array;
3903
+ static encode(data: any, replacer?: (key: any, value: any) => any): Uint8Array;
3481
3904
  /** @internal */
3482
- static decode(data: Uint8Array): any;
3905
+ static decode(data: Uint8Array, reviver?: (key: any, value: any) => any): any;
3483
3906
  }
3907
+ /**
3908
+ * Custom replacer that converts `DocumentID` instances to their string
3909
+ * representation.
3910
+ *
3911
+ * @internal
3912
+ */
3913
+ declare function documentIDReplacer(key: any, value: any): any;
3484
3914
 
3485
- export { Address, Attachment, AttachmentFetchEvent, AttachmentFetchEventCompleted, AttachmentFetchEventDeleted, AttachmentFetchEventProgress, AttachmentFetchEventType, AttachmentFetcher, AttachmentToken, AuthenticationHandler, AuthenticationStatus, Authenticator, BasePendingCursorOperation, BasePendingIDSpecificOperation, CBOR, ChangeHandler, ChangeHandlerWithSignalNext, Collection, CollectionInterface, CollectionsEvent, CollectionsEventParams, CollectionsObservationHandler, ConditionSource, Connection, ConnectionType, Counter, CustomLogCallback, Ditto, Document, DocumentID, DocumentIDValue, DocumentPath, DocumentValue, ErrorHandler, ExperimentalChangeListener, ExperimentalChangeListenerManager, ExperimentalChangeListenerStatus, ExperimentalReplicationSubscription, ExperimentalReplicationSubscriptionContextInfo, ExperimentalReplicationSubscriptionManager, 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, SmallPeerInfo, SmallPeerInfoSyncScope, 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, disableDeadlockTimeoutWhenDebugging, getBridgeLoad, init, transportConfigFromDeserializable, transportConfigToSerializable, validateDocumentIDCBOR, validateDocumentIDValue };
3915
+ 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, DQLQueryArgumentValue, DQLQueryArguments, Ditto, DittoError, Document, DocumentID, DocumentIDValue, DocumentPath, DocumentValue, ERROR_CODES, ErrorCode, ErrorContext, 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, QueryResult, QueryResultItem, Register, RemotePeer, SingleDocumentLiveQueryEvent, SingleObservationHandler, SmallPeerInfo, SmallPeerInfoSyncScope, SortDirection, Store, StoreObservationHandler, StoreObservationHandlerWithSignalNext, StoreObserver, Subscription, Sync, SyncParameters, SyncState, SyncSubscription, TransportCondition, TransportConfig, TransportConfigConnect, TransportConfigGlobal, TransportConfigLan, TransportConfigListen, TransportConfigListenHTTP, TransportConfigListenTCP, TransportConfigPeerToPeer, UpdateResult, UpdateResultType, UpdateResultsMap, UpsertOptions, WebAssemblyModule, WriteStrategy, WriteTransaction, WriteTransactionCollection, WriteTransactionPendingCursorOperation, WriteTransactionPendingIDSpecificOperation, WriteTransactionResult, addressToString, checkAPIs, disableDeadlockTimeoutWhenDebugging, documentIDReplacer, getBridgeLoad, init, mapFFIErrors, mapFFIErrorsAsync, transportConfigFromDeserializable, transportConfigToSerializable, validateDocumentIDCBOR, validateDocumentIDValue };
3486
3916
  //# sourceMappingURL=ditto.d.ts.map