@dittolive/ditto 4.5.1-experimental.aarch64-linux.1.aarch64 → 4.5.2-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/DittoReactNative.podspec +25 -0
  2. package/README.md +2 -2
  3. package/node/ditto.cjs.js +1 -1
  4. package/node/ditto.cjs.js.map +1 -0
  5. package/node/ditto.cjs.pretty.js +9655 -0
  6. package/node/ditto.cjs.pretty.js.map +1 -0
  7. package/node/ditto.darwin-arm64.node +0 -0
  8. package/node/ditto.darwin-x64.node +0 -0
  9. package/node/{ditto.linux-arm64.node → ditto.linux-x64.node} +0 -0
  10. package/node/transports.darwin-arm64.node +0 -0
  11. package/node/transports.darwin-x64.node +0 -0
  12. package/package.json +2 -1
  13. package/react-native/android/CMakeLists.txt +37 -0
  14. package/react-native/android/build.gradle +186 -0
  15. package/react-native/android/cpp-adapter.cpp +254 -0
  16. package/react-native/android/gradle.properties +5 -0
  17. package/react-native/android/src/main/AndroidManifest.xml +4 -0
  18. package/react-native/android/src/main/java/com/dittolive/rnsdk/DittoRNSDKModule.java +85 -0
  19. package/react-native/android/src/main/java/com/dittolive/rnsdk/DittoRNSDKPackage.java +28 -0
  20. package/react-native/cpp/include/Arc.hpp +141 -0
  21. package/react-native/cpp/include/Attachment.h +16 -0
  22. package/react-native/cpp/include/Authentication.h +23 -0
  23. package/react-native/cpp/include/Collection.h +13 -0
  24. package/react-native/cpp/include/DQL.h +21 -0
  25. package/react-native/cpp/include/Document.h +17 -0
  26. package/react-native/cpp/include/Identity.h +17 -0
  27. package/react-native/cpp/include/Lifecycle.h +17 -0
  28. package/react-native/cpp/include/LiveQuery.h +17 -0
  29. package/react-native/cpp/include/Logger.h +22 -0
  30. package/react-native/cpp/include/Misc.h +27 -0
  31. package/react-native/cpp/include/Presence.h +14 -0
  32. package/react-native/cpp/include/SmallPeerInfo.h +19 -0
  33. package/react-native/cpp/include/Transports.h +25 -0
  34. package/react-native/cpp/include/TypedArray.hpp +167 -0
  35. package/react-native/cpp/include/Utils.h +61 -0
  36. package/react-native/cpp/include/main.h +10 -0
  37. package/react-native/cpp/src/Attachment.cpp +86 -0
  38. package/react-native/cpp/src/Authentication.cpp +227 -0
  39. package/react-native/cpp/src/Collection.cpp +54 -0
  40. package/react-native/cpp/src/DQL.cpp +256 -0
  41. package/react-native/cpp/src/Document.cpp +146 -0
  42. package/react-native/cpp/src/Identity.cpp +123 -0
  43. package/react-native/cpp/src/Lifecycle.cpp +110 -0
  44. package/react-native/cpp/src/LiveQuery.cpp +63 -0
  45. package/react-native/cpp/src/Logger.cpp +200 -0
  46. package/react-native/cpp/src/Misc.cpp +283 -0
  47. package/react-native/cpp/src/Presence.cpp +79 -0
  48. package/react-native/cpp/src/SmallPeerInfo.cpp +142 -0
  49. package/react-native/cpp/src/Transports.cpp +270 -0
  50. package/react-native/cpp/src/TypedArray.cpp +303 -0
  51. package/react-native/cpp/src/Utils.cpp +138 -0
  52. package/react-native/cpp/src/main.cpp +152 -0
  53. package/react-native/dittoffi/dittoffi.h +4700 -0
  54. package/react-native/dittoffi/ifaddrs.cpp +385 -0
  55. package/react-native/dittoffi/ifaddrs.h +206 -0
  56. package/react-native/ios/DittoRNSDK.h +7 -0
  57. package/react-native/ios/DittoRNSDK.mm +107 -0
  58. package/react-native/ios/YeetJSIUtils.h +60 -0
  59. package/react-native/ios/YeetJSIUtils.mm +196 -0
  60. package/react-native/lib/commonjs/ditto.rn.js +92 -0
  61. package/react-native/lib/commonjs/ditto.rn.js.map +1 -0
  62. package/react-native/lib/commonjs/index.js +61 -0
  63. package/react-native/lib/commonjs/index.js.map +1 -0
  64. package/react-native/lib/module/ditto.rn.js +88 -0
  65. package/react-native/lib/module/ditto.rn.js.map +1 -0
  66. package/react-native/lib/module/index.js +27 -0
  67. package/react-native/lib/module/index.js.map +1 -0
  68. package/react-native/lib/typescript/ditto.rn.d.ts +15 -0
  69. package/react-native/lib/typescript/ditto.rn.d.ts.map +1 -0
  70. package/react-native/lib/typescript/index.d.ts +1 -0
  71. package/react-native/lib/typescript/index.d.ts.map +1 -0
  72. package/react-native/src/ditto.rn.ts +91 -0
  73. package/react-native/src/environment/environment.fallback.ts +4 -0
  74. package/react-native/src/index.ts +26 -0
  75. package/react-native/src/sources/@cbor-redux.ts +2 -0
  76. package/react-native/src/sources/@ditto.core.ts +1 -0
  77. package/react-native/src/sources/@environment.ts +1 -0
  78. package/react-native/src/sources/attachment-fetch-event.ts +54 -0
  79. package/react-native/src/sources/attachment-fetcher-manager.ts +144 -0
  80. package/react-native/src/sources/attachment-fetcher.ts +134 -0
  81. package/react-native/src/sources/attachment-token.ts +48 -0
  82. package/react-native/src/sources/attachment.ts +74 -0
  83. package/react-native/src/sources/augment.ts +101 -0
  84. package/react-native/src/sources/authenticator.ts +314 -0
  85. package/react-native/src/sources/base-pending-cursor-operation.ts +239 -0
  86. package/react-native/src/sources/base-pending-id-specific-operation.ts +109 -0
  87. package/react-native/src/sources/bridge.ts +553 -0
  88. package/react-native/src/sources/build-time-constants.ts +8 -0
  89. package/react-native/src/sources/cbor.ts +35 -0
  90. package/react-native/src/sources/collection-interface.ts +67 -0
  91. package/react-native/src/sources/collection.ts +212 -0
  92. package/react-native/src/sources/collections-event.ts +99 -0
  93. package/react-native/src/sources/counter.ts +82 -0
  94. package/react-native/src/sources/ditto.ts +979 -0
  95. package/react-native/src/sources/document-id.ts +159 -0
  96. package/react-native/src/sources/document-path.ts +306 -0
  97. package/react-native/src/sources/document.ts +193 -0
  98. package/react-native/src/sources/epilogue.ts +30 -0
  99. package/react-native/src/sources/error-codes.ts +52 -0
  100. package/react-native/src/sources/error.ts +208 -0
  101. package/react-native/src/sources/essentials.ts +53 -0
  102. package/react-native/src/sources/ffi-error.ts +122 -0
  103. package/react-native/src/sources/ffi.ts +2012 -0
  104. package/react-native/src/sources/identity.ts +163 -0
  105. package/react-native/src/sources/init.ts +71 -0
  106. package/react-native/src/sources/internal.ts +109 -0
  107. package/react-native/src/sources/keep-alive.ts +73 -0
  108. package/react-native/src/sources/key-path.ts +198 -0
  109. package/react-native/src/sources/live-query-event.ts +208 -0
  110. package/react-native/src/sources/live-query-manager.ts +102 -0
  111. package/react-native/src/sources/live-query.ts +166 -0
  112. package/react-native/src/sources/logger.ts +196 -0
  113. package/react-native/src/sources/main.ts +60 -0
  114. package/react-native/src/sources/observer-manager.ts +178 -0
  115. package/react-native/src/sources/observer.ts +79 -0
  116. package/react-native/src/sources/pending-collections-operation.ts +232 -0
  117. package/react-native/src/sources/pending-cursor-operation.ts +218 -0
  118. package/react-native/src/sources/pending-id-specific-operation.ts +218 -0
  119. package/react-native/src/sources/presence-manager.ts +161 -0
  120. package/react-native/src/sources/presence.ts +233 -0
  121. package/react-native/src/sources/query-result-item.ts +116 -0
  122. package/react-native/src/sources/query-result.ts +55 -0
  123. package/react-native/src/sources/register.ts +95 -0
  124. package/react-native/src/sources/small-peer-info.ts +177 -0
  125. package/react-native/src/sources/static-tcp-client.ts +6 -0
  126. package/react-native/src/sources/store-observer.ts +177 -0
  127. package/react-native/src/sources/store.ts +385 -0
  128. package/react-native/src/sources/subscription-manager.ts +99 -0
  129. package/react-native/src/sources/subscription.ts +89 -0
  130. package/react-native/src/sources/sync-subscription.ts +90 -0
  131. package/react-native/src/sources/sync.ts +559 -0
  132. package/react-native/src/sources/test-helpers.ts +24 -0
  133. package/react-native/src/sources/transport-conditions-manager.ts +104 -0
  134. package/react-native/src/sources/transport-config.ts +430 -0
  135. package/react-native/src/sources/update-result.ts +66 -0
  136. package/react-native/src/sources/update-results-map.ts +57 -0
  137. package/react-native/src/sources/websocket-client.ts +7 -0
  138. package/react-native/src/sources/write-transaction-collection.ts +122 -0
  139. package/react-native/src/sources/write-transaction-pending-cursor-operation.ts +101 -0
  140. package/react-native/src/sources/write-transaction-pending-id-specific-operation.ts +74 -0
  141. package/react-native/src/sources/write-transaction.ts +121 -0
  142. package/react-native.config.js +9 -0
  143. package/types/ditto.d.ts.map +1 -0
  144. package/web/ditto.es6.js +1 -1
  145. package/web/ditto.es6.js.map +1 -0
  146. package/web/ditto.es6.pretty.js +12600 -0
  147. package/web/ditto.es6.pretty.js.map +1 -0
  148. package/web/ditto.umd.js +1 -1
  149. package/web/ditto.umd.js.map +1 -0
  150. package/web/ditto.umd.pretty.js +12669 -0
  151. package/web/ditto.umd.pretty.js.map +1 -0
  152. package/web/ditto.wasm +0 -0
@@ -0,0 +1,109 @@
1
+ //
2
+ // Copyright © 2023 DittoLive Incorporated. All rights reserved.
3
+ //
4
+
5
+ import * as FFI from './ffi'
6
+
7
+ import { Bridge } from './bridge'
8
+ import { performAsyncToWorkaroundNonAsyncFFIAPI } from './internal'
9
+
10
+ import type { Document, MutableDocument } from './document'
11
+ import type { DocumentID } from './document-id'
12
+ import type { CollectionInterface } from './collection-interface'
13
+ import type { UpdateResult } from './update-result'
14
+
15
+ /**
16
+ * These objects are returned when using
17
+ * {@link Collection.findByID | findByID()} functionality on
18
+ * {@link Collection | collections}.
19
+ *
20
+ * You can either call {@link exec | exec()} on the object to get an immediate
21
+ * return value, or chain calls to update, evict or remove the document.
22
+ *
23
+ * Live queries and subscriptions are only available outside of a transaction.
24
+ */
25
+ export abstract class BasePendingIDSpecificOperation implements PromiseLike<Document | undefined> {
26
+ /**
27
+ * Removes the document with the matching ID.
28
+ *
29
+ * @returns `true` promise if the document was found and removed. `false`
30
+ * promise if the document wasn't found and therefore wasn't removed.
31
+ */
32
+ abstract remove(): Promise<boolean>
33
+
34
+ /**
35
+ * Evicts the document with the matching ID.
36
+ *
37
+ * @returns `true` promise if the document was found and evicted. `false`
38
+ * promise if the document wasn't found and therefore wasn't evicted.
39
+ */
40
+ abstract evict(): Promise<boolean>
41
+
42
+ /**
43
+ * Updates the document with the matching ID.
44
+ *
45
+ * @param closure A closure that gets called with the document matching the
46
+ * ID. If found, the document is a {@link MutableDocument}, so you can call
47
+ * update-related functions on it. If the document is not found then the value
48
+ * provided to the closure will be `undefined`.
49
+ *
50
+ * @return An array promise of {@link UpdateResult | update results} that
51
+ * describe the updates that were performed on the document.
52
+ */
53
+ abstract update(closure: (document: MutableDocument) => void): Promise<UpdateResult[]>
54
+
55
+ // ----------------------------------------------------------- Public --------
56
+
57
+ /** The ID of the document this operation operates on. */
58
+ readonly documentID: DocumentID
59
+
60
+ /** The collection the receiver is operating on. */
61
+ readonly collection: CollectionInterface
62
+
63
+ /**
64
+ * Executes the find operation to return the document with the matching ID.
65
+ *
66
+ * @returns The {@link Document} promise with the ID provided in the
67
+ * {@link Collection.findByID | findByID()} call or `undefined` if the document was
68
+ * not found.
69
+ */
70
+ async exec(): Promise<Document | undefined> {
71
+ const ditto = this.collection.store.ditto
72
+ const dittoHandle = Bridge.ditto.handleFor(ditto)
73
+ return ditto.deferCloseAsync(async () => {
74
+ return await performAsyncToWorkaroundNonAsyncFFIAPI(async () => {
75
+ const readTransactionX = await FFI.readTransaction(dittoHandle.deref())
76
+ const documentX = await FFI.collectionGet(dittoHandle.deref(), this.collection.name, this.documentIDCBOR, readTransactionX)
77
+
78
+ let document: Document | undefined = undefined
79
+ if (documentX) document = Bridge.document.bridge(documentX)
80
+
81
+ FFI.readTransactionFree(readTransactionX)
82
+ return document
83
+ })
84
+ })
85
+ }
86
+
87
+ // ----------------------------------------------------------- Internal ------
88
+
89
+ /** @internal */
90
+ constructor(documentID: DocumentID, collection: CollectionInterface) {
91
+ this.documentID = documentID
92
+ this.collection = collection
93
+ this.documentIDCBOR = documentID.toCBOR()
94
+ }
95
+
96
+ /** @internal */
97
+ then<TResult1 = any, TResult2 = never>(onfulfilled?: ((value: any) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): PromiseLike<TResult1 | TResult2> {
98
+ return this.exec().then(onfulfilled, onrejected)
99
+ }
100
+
101
+ /** @internal */
102
+ get query(): string {
103
+ return `_id == ${this.documentID.toQueryCompatibleString()}`
104
+ }
105
+
106
+ // ---------------------------------------------------------- Protected ------
107
+
108
+ protected documentIDCBOR: Uint8Array
109
+ }
@@ -0,0 +1,553 @@
1
+ //
2
+ // Copyright © 2023 DittoLive Incorporated. All rights reserved.
3
+ //
4
+
5
+ import * as FFI from './ffi'
6
+
7
+ import { Logger } from './logger'
8
+ import { QueryResult } from './query-result'
9
+ import { QueryResultItem } from './query-result-item'
10
+
11
+ import type { Document, MutableDocument } from './document'
12
+ import type { Attachment } from './attachment'
13
+
14
+ import type { StaticTCPClient } from './static-tcp-client'
15
+ import type { WebsocketClient } from './websocket-client'
16
+
17
+ import type { Ditto } from './ditto'
18
+
19
+ // Add bridged type name to debug, for example 'Ditto'.
20
+ const DEBUG_TYPE_NAMES: string[] = []
21
+ const DEBUG_ALL_TYPES = false
22
+
23
+ // -----------------------------------------------------------------------------
24
+
25
+ /**
26
+ * A JavaScript class that identifies a bridge's type and may be used to create
27
+ * new instances.
28
+ */
29
+ export type BridgeType<T extends object> = new (...args: any[]) => T
30
+
31
+ /**
32
+ * A handle serves as a safe wrapper around a pointer to a native object.
33
+ *
34
+ * A bridge keeps track of all handles that have been created on its
35
+ * {@link Bridge.handlesByAddress | `handlesByAddress`} property, which allows
36
+ * enumerating all objects that are currently managed by the bridge.
37
+ *
38
+ * @internal */
39
+ export class Handle<T extends object, FFIType> {
40
+ readonly bridge: Bridge<T, FFIType>
41
+ readonly pointer: FFI.Pointer<FFIType>
42
+
43
+ private objectWeakRef: WeakRef<T>
44
+
45
+ readonly isClosed: boolean = false
46
+ readonly isFinalized: boolean = false
47
+ readonly isUnregistered: boolean = false
48
+
49
+ /**
50
+ * Warning: Do not call this constructor directly. Use
51
+ * {@link Bridge.handleFor | `Bridge.<type>.handleFor()`} instead.
52
+ *
53
+ * @internal
54
+ */
55
+ constructor(bridge: Bridge<T, FFIType>, object: T, pointer: FFI.Pointer<FFIType>) {
56
+ this.bridge = bridge
57
+ this.objectWeakRef = new WeakRef(object)
58
+ this.pointer = pointer
59
+ }
60
+
61
+ /** The type of this handle's bridge */
62
+ get type(): BridgeType<T> {
63
+ return this.bridge.type
64
+ }
65
+
66
+ /**
67
+ * Returns the pointer associated with this handle.
68
+ *
69
+ * @throws {Error} if the object has already been closed, garbage collected,
70
+ * or unregistered from the bridge.
71
+ */
72
+ deref(): FFI.Pointer<FFIType> {
73
+ if (this.isClosed) {
74
+ throw new Error(`Bridging error: can't get pointer for an object that has been closed.`)
75
+ }
76
+
77
+ if (this.isFinalized) {
78
+ throw new Error(`Bridging error: can't get pointer for an object that has been finalized.`)
79
+ }
80
+
81
+ if (this.isUnregistered) {
82
+ throw new Error(`Bridging error: can't get pointer for an object that has been unregistered.`)
83
+ }
84
+
85
+ return this.pointer
86
+ }
87
+
88
+ /**
89
+ * Returns the pointer associated with this handle or `null` if the object
90
+ * has been closed, garbage collected, or unregistered.
91
+ */
92
+ derefOrNull(): FFI.Pointer<FFIType> | null {
93
+ if (this.isClosed) {
94
+ return null
95
+ }
96
+
97
+ if (this.isFinalized) {
98
+ return null
99
+ }
100
+
101
+ if (this.isUnregistered) {
102
+ return null
103
+ }
104
+
105
+ return this.pointer ?? null
106
+ }
107
+
108
+ /**
109
+ * Returns the object associated with this handle.
110
+ *
111
+ * @throws {Error} if the object has been closed, unregistered, or garbage collected,
112
+ * closed or unregistered.
113
+ */
114
+ object(): T {
115
+ const object = this.objectWeakRef.deref()
116
+ if (object == null) {
117
+ throw new Error(`Bridging error: ${this.bridge.type.name} object has been garbage collected.`)
118
+ }
119
+
120
+ if (this.isClosed) {
121
+ throw new Error(`Bridging error: ${this.bridge.type.name} object has been closed.`)
122
+ }
123
+
124
+ if (this.isUnregistered) {
125
+ throw new Error(`Bridging error: ${this.bridge.type.name} object has been unregistered.`)
126
+ }
127
+
128
+ return object
129
+ }
130
+
131
+ /**
132
+ * Returns the object associated with this handle or `null` if the object
133
+ * has been closed, unregistered, or garbage collected.
134
+ */
135
+ objectOrNull(): T | null {
136
+ return this.objectWeakRef.deref() ?? null
137
+ }
138
+
139
+ /** @internal */
140
+ toString(): string {
141
+ const pointer = this.derefOrNull()
142
+ return `{ Handle | type: ${this.bridge.type}, object: ${this.objectWeakRef.deref()}, FFI address: ${pointer?.addr}, FFI type: ${pointer?.type} }`
143
+ }
144
+
145
+ /** @internal */
146
+ bridgeWillClose() {
147
+ // @ts-expect-error setting readonly property
148
+ this.isClosed = true
149
+ }
150
+
151
+ /** @internal */
152
+ bridgeDidClose() {
153
+ // @ts-expect-error setting readonly property
154
+ this.pointer = null
155
+ }
156
+
157
+ /** @internal */
158
+ bridgeWillFinalize() {
159
+ // @ts-expect-error setting readonly property
160
+ this.isFinalized = true
161
+ }
162
+
163
+ /** @internal */
164
+ bridgeDidFinalize() {
165
+ // @ts-expect-error setting readonly property
166
+ this.pointer = null
167
+ }
168
+
169
+ /** @internal */
170
+ bridgeWillUnregister() {
171
+ // @ts-expect-error setting readonly property
172
+ this.isUnregistered = true
173
+ }
174
+
175
+ /** @internal */
176
+ bridgeDidUnregister() {
177
+ // @ts-expect-error setting readonly property
178
+ this.pointer = null
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Use this for passing arrays of pointers to the FFI.
184
+ */
185
+ export class Handles<T extends object, FFIType> {
186
+ readonly handles: Handle<T, FFIType>[]
187
+
188
+ /**
189
+ * @throws {Error} if any of the objects are not registered in the bridge.
190
+ * @throws {Error} if any of the objects have already been garbage collected.
191
+ */
192
+ constructor(bridge: Bridge<T, FFIType>, objects: T[]) {
193
+ this.handles = objects.map((object) => bridge.handleFor(object))
194
+ }
195
+
196
+ deref(): FFI.Pointer<FFIType>[] {
197
+ return this.handles.map((handle) => handle.deref())
198
+ }
199
+ }
200
+
201
+ /**
202
+ * A bridge manages memory allocated by the FFI that is used in the JS SDK.
203
+ *
204
+ * The main purpose of a bridge is keeping track of JavaScript objects that
205
+ * require access to memory allocated by the FFI. When such objects are
206
+ * garbage collected in JavaScript, the bridge instructs the FFI to free the
207
+ * corresponding memory. Every managed memory pointer corresponds to exactly
208
+ * one JS Object.
209
+ *
210
+ * There is a static `Bridge` instance for every class of objects that can be
211
+ * managed:
212
+ *
213
+ * - {@link Attachment}: `Bridge.attachment`
214
+ * - {@link Ditto}: `Bridge.ditto`
215
+ * - {@link Document}: `Bridge.document`
216
+ * - {@link MutableDocument}: `Bridge.mutableDocument`
217
+ * - {@link StaticTCPClient}: `Bridge.staticTCPClient`
218
+ * - {@link WebsocketClient}: `Bridge.websocketClient`
219
+ *
220
+ * Use `Bridge.<type>.handleFor()` to obtain a handle, which is a wrapper around
221
+ * the raw pointer, and `Bridge.<type>.bridge()` to get or create the matching
222
+ * object for a memory address.
223
+ *
224
+ * @internal */
225
+ export class Bridge<T extends object, FFIType> {
226
+ readonly release: (pointer: FFI.Pointer<FFIType>) => void | Promise<void>
227
+
228
+ /**
229
+ * Creates a new bridge for objects of `type`. Requires a `release` function
230
+ * that is called whenever a registered object is garbage collected, passing
231
+ * the associated `pointer` to it. The release function is then responsible
232
+ * to free or drop the corresponding native object.
233
+ *
234
+ * **IMPORTANT**: The `type` of all bridges needs to be set in `epilogue.ts`
235
+ * after initiating the bridge instance. This helps avoid import cycles
236
+ * (otherwise anything importing the bridge instance, would also have to
237
+ * import the type, which usually leads to import cycles).
238
+ *
239
+ * @private
240
+ */
241
+ constructor(release: (pointer: FFI.Pointer<FFIType>) => void | Promise<void>) {
242
+ this.release = release
243
+ this.handlesByAddress = {}
244
+ this.handlesByObject = new WeakMap()
245
+ this.finalizationRegistry = new FinalizationRegistry(this.finalize.bind(this))
246
+
247
+ Bridge.all.push(new WeakRef(this))
248
+ }
249
+
250
+ /**
251
+ * The type of a bridge is the JavaScript `Class` of objects it represents.
252
+ *
253
+ * @internal */
254
+ get type(): BridgeType<T> {
255
+ if (this.internalType == null) {
256
+ throw new Error('Bridge type has not been registered yet.')
257
+ }
258
+ return this.internalType
259
+ }
260
+
261
+ /**
262
+ * All bridges' types have to be registered in `epilogue.ts` before using
263
+ * them.
264
+ *
265
+ * @internal */
266
+ registerType(value: BridgeType<T>) {
267
+ if (this.internalType === value) {
268
+ // Nothing to do.
269
+ return
270
+ }
271
+
272
+ if (this.internalType) {
273
+ throw new Error(`Can't register bridged type '${value.name}', another type was already registered: ${this.internalType}`)
274
+ }
275
+
276
+ this.internalType = value
277
+ }
278
+
279
+ /**
280
+ * Returns the handle for a bridged object.
281
+ *
282
+ * Use `handle.deref()` to get the pointer for the object at the time of use.
283
+ *
284
+ * @throws {Error} if the object is not registered.
285
+ *
286
+ * @internal
287
+ */
288
+ handleFor(object: T): Handle<T, FFIType> {
289
+ const handle = this.handlesByObject.get(object)
290
+ if (handle == null) {
291
+ throw new Error(`Bridging error: ${this.type.name} object is not currently registered in this bridge.`)
292
+ }
293
+
294
+ return handle
295
+ }
296
+
297
+ /**
298
+ * Returns a `Handles` instance for an array of objects.
299
+ *
300
+ * @internal
301
+ */
302
+ handlesFor(objects: T[]): Handles<T, FFIType> {
303
+ return new Handles(this, objects)
304
+ }
305
+
306
+ /**
307
+ * Convenience method, returns the object for the FFI `pointer` if registered,
308
+ * otherwise returns `undefined`. If the object associated with the `pointer`
309
+ * has been unregistered before, returns `undefined`, too.
310
+ *
311
+ * @internal
312
+ */
313
+ objectFor(pointer: FFI.Pointer<FFIType>): T | undefined {
314
+ const handle = this.handlesByAddress[pointer.addr]
315
+ if (!handle) return undefined
316
+ if (handle.type !== this.type) throw new Error(`Can't return object for pointer, pointer is associated with an object of type ${handle.type} but this bridge is configured for ${this.type}`)
317
+
318
+ // This throws an error if the object has been garbage collected but the
319
+ // finalizer has not been called yet.
320
+ return handle.object()
321
+ }
322
+
323
+ /**
324
+ * Returns the object for the FFI `pointer` if registered. Otherwise, calls
325
+ * the passed in `create` function to create a new object, which it then
326
+ * returns after registering. If no `create` function is given, uses the
327
+ * type of the bridge as a constructor and creates a new instance of it
328
+ * without passing any parameters.
329
+ *
330
+ * @param pointer reference to the FFi instance for the object
331
+ * @param objectOrCreate can either be the JS object, or a function that returns the instance when called. If undefined, an object is created based on the Bridge type.
332
+ * @throws {Error} if `objectOrCreate` is a function that returns an object that is not an instance of the bridge's type.
333
+ * @internal
334
+ */
335
+ bridge(pointer: FFI.Pointer<FFIType>, objectOrCreate?: T | (() => T)): T {
336
+ const existingObject = this.objectFor(pointer)
337
+ if (existingObject) {
338
+ return existingObject
339
+ }
340
+
341
+ if (!objectOrCreate) {
342
+ objectOrCreate = () => {
343
+ return Reflect.construct(this.type, [])
344
+ }
345
+ }
346
+
347
+ let object: T
348
+ if (typeof objectOrCreate === 'function') {
349
+ object = objectOrCreate()
350
+ if (!(object instanceof this.type)) {
351
+ throw new Error(`Can't bridge, expected passed in create function to return a ${this.type.name} object but got: ${object}`)
352
+ }
353
+ } else {
354
+ object = objectOrCreate
355
+ }
356
+
357
+ this.register(object, pointer)
358
+ return object
359
+ }
360
+
361
+ /**
362
+ * Registers an instance in this bridge's {@link FinalizationRegistry}.
363
+ *
364
+ * This causes the FFI to drop the memory linked to the object as soon as it
365
+ * is garbage collected in JavaScript.
366
+ *
367
+ * If you want to control the order with which a number of objects' memory is
368
+ * dropped, use {@link Bridge.unregister | Bridge.unregister()}
369
+ *
370
+ * @private */
371
+ register(object: T, pointer: FFI.Pointer<FFIType>) {
372
+ const objectType = object.constructor as BridgeType<T>
373
+ if (objectType !== this.type) throw new Error(`Can't register, bridge is configured for type ${this.type.name} but passed in object is of type ${objectType.name}`)
374
+
375
+ const existingHandle = this.handlesByObject.get(object)
376
+ const existingPointer = existingHandle ? existingHandle.pointer : null
377
+
378
+ // Check that both pointer and handle are undefined at this point.
379
+ if (existingPointer != null && existingHandle != null) throw new Error(`Can't register, an object for the passed in pointer has previously been registered: ${existingHandle.object()}`)
380
+
381
+ if (existingPointer != null && existingHandle == null) throw new Error(`Internal inconsistency, trying to register an object which has an associated pointer but no handle entry: ${objectType.name} at ${existingPointer.type} ${existingPointer.addr}`)
382
+ if (existingPointer == null && existingHandle != null) throw new Error(`Internal inconsistency, trying to register an object which has a handle entry but no associated pointer: ${objectType.name} ${object}`)
383
+
384
+ const handle = new Handle<T, FFIType>(this, object, pointer)
385
+ this.handlesByAddress[pointer.addr] = handle
386
+ this.handlesByObject.set(object, handle)
387
+
388
+ this.finalizationRegistry.register(object as object, handle, object as object)
389
+
390
+ if (DEBUG_TYPE_NAMES.includes(this.type.name) || DEBUG_ALL_TYPES) {
391
+ Logger.debug(`[VERBOSE] Bridge REGISTERED a new instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)
392
+ }
393
+ }
394
+
395
+ /**
396
+ * Removes an instance from this bridge's {@link FinalizationRegistry}.
397
+ *
398
+ * This lets you control the order with which memory is dropped in the FFI.
399
+ * After calling this function, manually call the FFI function to drop the
400
+ * memory then finally delete the JavaScript instance.
401
+ *
402
+ * @internal */
403
+ unregister(object: T) {
404
+ const objectType = object.constructor
405
+ const bridgeType = this.type
406
+ if (objectType !== bridgeType) throw new Error(`Can't unregister, bridge is configured for type ${bridgeType.name} but passed in object is of type ${objectType.name}`)
407
+
408
+ const handle = this.handlesByObject.get(object)
409
+ if (handle == null) throw new Error(`Can't unregister, object has not been registered before: ${object}`)
410
+ if (handle.type !== bridgeType) throw new Error(`Internal inconsistency, trying to unregister an object that has a handle with a different type than that of the bridge: ${handle}`)
411
+ if (handle.objectOrNull() !== object) throw new Error(`Internal inconsistency, trying to unregister an object whose associated handle holds a different object: ${handle}`)
412
+
413
+ if (handle.isClosed) throw new Error(`Can't unregister, object has been closed before: ${object}`)
414
+ if (handle.isFinalized) throw new Error(`Can't unregister, object has been finalized before: ${object}`)
415
+ if (handle.isUnregistered) throw new Error(`Can't unregister, object has been unregistered already: ${object}`)
416
+
417
+ handle.bridgeWillUnregister()
418
+ this.finalizationRegistry.unregister(object as object)
419
+ delete this.handlesByAddress[handle.pointer.addr]
420
+ this.handlesByObject.delete(object)
421
+ handle.bridgeDidUnregister()
422
+
423
+ if (DEBUG_TYPE_NAMES.includes(this.type.name) || DEBUG_ALL_TYPES) {
424
+ Logger.debug(`[VERBOSE] Bridge UNREGISTERED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)
425
+ }
426
+ }
427
+
428
+ /** @internal */
429
+ unregisterAll() {
430
+ if (DEBUG_TYPE_NAMES.includes(this.type.name) || DEBUG_ALL_TYPES) {
431
+ Logger.debug(`[VERBOSE] Unregistering ALL bridged instances of type ${this.type.name}.`)
432
+ }
433
+
434
+ for (const handle of Object.values(this.handlesByAddress)) {
435
+ const object = handle.object()
436
+ if (object) {
437
+ this.unregister(object)
438
+ }
439
+ }
440
+ }
441
+
442
+ /**
443
+ * Closes the object by calling `release()` and `null`-ing its pointer, such
444
+ * that its handle can't be `deref()`-ed afterwards.
445
+ *
446
+ * @internal */
447
+ async close(object: T): Promise<void> {
448
+ const objectType = object.constructor
449
+ const bridgeType = this.type
450
+ if (objectType !== bridgeType) throw new Error(`Can't close, bridge is configured for type ${bridgeType.name} but passed in object is of type ${objectType.name}`)
451
+
452
+ const handle = this.handlesByObject.get(object)
453
+ if (handle == null) throw new Error(`Can't close an object that has not been registered before: ${object}`)
454
+ if (handle.type !== bridgeType) throw new Error(`Internal inconsistency, trying to close an object that has a handle with a different type than that of the bridge: ${handle}`)
455
+
456
+ if (handle.isUnregistered) throw new Error(`Can't close object, object has been unregistered.`)
457
+ if (handle.isFinalized) throw new Error(`Internal inconsistency, trying to close an object that has already been finalized.`)
458
+ if (handle.isClosed) return
459
+
460
+ const pointer = handle.pointer
461
+ if (!pointer) throw new Error(`Internal inconsistency, trying to close an object whose pointer is null.`)
462
+
463
+ handle.bridgeWillClose()
464
+ delete this.handlesByAddress[pointer.addr]
465
+ await this.release(pointer)
466
+ handle.bridgeDidClose()
467
+
468
+ if (DEBUG_TYPE_NAMES.includes(this.type.name) || DEBUG_ALL_TYPES) {
469
+ Logger.debug(`[VERBOSE] Bridge CLOSED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)
470
+ }
471
+ }
472
+
473
+ /** @internal */
474
+ get count(): number {
475
+ return Object.keys(this.handlesByAddress).length
476
+ }
477
+
478
+ /**
479
+ * Keeps track of all bridges for debugging and test purposes. With this, we
480
+ * can iterate over all bridges and make sure everything is deallocated after
481
+ * a test, or a suite of tests, has run.
482
+ *
483
+ * @internal */
484
+ static readonly all: Array<WeakRef<Bridge<any, any>>> = []
485
+
486
+ /** @internal */
487
+ static readonly attachment = new Bridge<Attachment, FFI.AttachmentHandle>(FFI.freeAttachmentHandle)
488
+
489
+ /** @internal */
490
+ static readonly document = new Bridge<Document, FFI.FFIDocument>(FFI.documentFree)
491
+
492
+ /** @internal */
493
+ static readonly mutableDocument = new Bridge<MutableDocument, FFI.FFIDocument>(FFI.documentFree)
494
+
495
+ /** @internal */
496
+ static readonly dqlResponse = new Bridge<QueryResult, FFI.FFIDqlResponse>(FFI.dqlResponseFree)
497
+
498
+ /** @internal */
499
+ static readonly dqlResult = new Bridge<QueryResultItem, FFI.FFIDqlResult>(FFI.dqlResultFree)
500
+
501
+ /** @internal */
502
+ static readonly staticTCPClient = new Bridge<StaticTCPClient, FFI.FFIStaticTCPClient>(FFI.staticTCPClientFreeHandle)
503
+
504
+ /** @internal */
505
+ static readonly websocketClient = new Bridge<WebsocketClient, FFI.FFIWebsocketClient>(FFI.websocketClientFreeHandle)
506
+
507
+ /** @internal */
508
+ static readonly ditto = new Bridge<Ditto, FFI.FFIDitto>(async (dittoPointer) => {
509
+ FFI.dittoClearPresenceCallback(dittoPointer)
510
+ await FFI.dittoShutdown(dittoPointer)
511
+ FFI.dittoFree(dittoPointer)
512
+ })
513
+
514
+ // ------ Private ------
515
+
516
+ private internalType: BridgeType<T> | null = null
517
+
518
+ /**
519
+ * All bridged objects' {@link Handle} entries for lookup by pointer address.
520
+ */
521
+ private handlesByAddress: { [key: FFI.Pointer<T>['addr']]: Handle<T, FFIType> }
522
+
523
+ /**
524
+ * Look up a handle given its object.
525
+ *
526
+ * As `WeakMap` does not allow for enumeration, use `this.handlesByAddress` to
527
+ * iterate over all handles.
528
+ */
529
+ private handlesByObject: WeakMap<T, Handle<T, FFIType>>
530
+
531
+ private finalizationRegistry: FinalizationRegistry<any>
532
+
533
+ private async finalize(handle: Handle<T, FFIType>): Promise<void> {
534
+ if (handle.isFinalized) throw new Error(`Internal inconsistency, trying to finalize an object that has already been finalized.`)
535
+ if (handle.isUnregistered) throw new Error(`Internal inconsistency, trying to finalize an object that has been unregistered before.`)
536
+
537
+ handle.bridgeWillFinalize()
538
+
539
+ if (!handle.isClosed) {
540
+ const pointer = handle.pointer
541
+ if (!pointer) throw new Error(`Internal inconsistency, trying to finalize an object whose pointer is null.`)
542
+
543
+ delete this.handlesByAddress[pointer.addr]
544
+ await this.release(pointer)
545
+ }
546
+
547
+ handle.bridgeDidFinalize()
548
+
549
+ if (DEBUG_TYPE_NAMES.includes(this.type.name) || DEBUG_ALL_TYPES) {
550
+ Logger.debug(`[VERBOSE] Bridge FINALIZED an instance of ${this.type.name}, current count: ${Object.keys(this.handlesByAddress).length}`)
551
+ }
552
+ }
553
+ }
@@ -0,0 +1,8 @@
1
+ // NOTE: this is patched up with the actual build version by Jake task
2
+ // build:package and has to be a valid semantic version as defined here: https://semver.org.
3
+ export const fullBuildVersionString = '{full-build-version-string}'
4
+
5
+ // NOTE: this is patched up with the default URL for the ditto.wasm by Jake task
6
+ // build:package. Usually it looks something like this:
7
+ // https://software.ditto.live/js/Ditto/1.2.3-alpha.456/ditto.wasm
8
+ export const defaultDittoWasmFileURL = '{default-ditto-wasm-file-url}'