Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

collection.ts

823 lines25.8 KB

1import { Derived, Store, batch } from "@tanstack/store"
2import { withArrayChangeTracking, withChangeTracking } from "./lib/proxy"
3import { getTransactionManager } from "./TransactionManager"
4import { TransactionStore } from "./TransactionStore"
5import type {
6 ChangeMessage,
7 CollectionConfig,
8 InsertConfig,
9 OperationConfig,
10 PendingMutation,
11 StandardSchema,
12 Transaction,
13 TransactionState,
14} from "./types"
15​
16// Store collections in memory using Tanstack store
17​
18export const collectionsStore = new Store(new Map<string, Collection<any>>())
19​
20// Map to track loading collections
21​
22const loadingCollections = new Map<string, Promise<void>>()
23​
24interface PendingSyncedTransaction<T extends object = Record<string, unknown>> {
25 committed: boolean
26 operations: Array<ChangeMessage<T>>
28​
29/**
30 * Preloads a collection with the given configuration
31 * Returns a promise that resolves once the sync tool has done its first commit (initial sync is finished)
32 * If the collection has already loaded, it resolves immediately
33 *
34 * This function is useful in route loaders or similar pre-rendering scenarios where you want
35 * to ensure data is available before a route transition completes. It uses the same shared collection
36 * instance that will be used by useCollection, ensuring data consistency.
37 *
38 * @example
39 * ```typescript
40 * // In a route loader
41 * async function loader({ params }) {
42 * await preloadCollection({
43 * id: `users-${params.userId}`,
44 * sync: { ... },
45 * mutationFn: { ... }
46 * });
47 *
48 * return null;
49 * }
50 * ```
51 *
52 * @template T - The type of items in the collection
53 * @param config - Configuration for the collection, including id, sync, and mutationFn
54 * @returns Promise that resolves when the initial sync is finished
55 */
56export function preloadCollection<T extends object = Record<string, unknown>>(
57 config: CollectionConfig<T>
58): Promise<void> {
59 // If the collection is already fully loaded, return a resolved promise
60 if (
61 collectionsStore.state.has(config.id) &&
62 !loadingCollections.has(config.id)
63 ) {
64 return Promise.resolve()
65 }
66​
67 // If the collection is in the process of loading, return its promise
68 if (loadingCollections.has(config.id)) {
69 return loadingCollections.get(config.id)!
70 }
71​
72 // Create a new collection instance if it doesn't exist
73 if (!collectionsStore.state.has(config.id)) {
74 collectionsStore.setState((prev) => {
75 const next = new Map(prev)
76 next.set(
77 config.id,
78 new Collection<T>({
79 id: config.id,
80 sync: config.sync,
81 mutationFn: config.mutationFn,
82 schema: config.schema,
83 })
84 )
85 return next
86 })
87 }
88​
89 const collection = collectionsStore.state.get(config.id)! as Collection<T>
90​
91 // Create a promise that will resolve after the first commit
92 let resolveFirstCommit: () => void
93 const firstCommitPromise = new Promise<void>((resolve) => {
94 resolveFirstCommit = resolve
95 })
96​
97 // Register a one-time listener for the first commit
98 collection.onFirstCommit(() => {
99 if (loadingCollections.has(config.id)) {
100 loadingCollections.delete(config.id)
101 resolveFirstCommit()
102 }
103 })
104​
105 // Store the loading promise
106 loadingCollections.set(config.id, firstCommitPromise)
107​
108 return firstCommitPromise
110​
111/**
112 * Custom error class for schema validation errors
113 */
114export class SchemaValidationError extends Error {
115 type: `insert` | `update`
116 issues: ReadonlyArray<{
117 message: string
118 path?: ReadonlyArray<string | number | symbol>
119 }>
120​
121 constructor(
122 type: `insert` | `update`,
123 issues: ReadonlyArray<{
124 message: string
125 path?: ReadonlyArray<string | number | symbol>
126 }>,
127 message?: string
128 ) {
129 const defaultMessage = `${type === `insert` ? `Insert` : `Update`} validation failed: ${issues
130 .map((issue) => issue.message)
131 .join(`, `)}`
132​
133 super(message || defaultMessage)
134 this.name = `SchemaValidationError`
135 this.type = type
136 this.issues = issues
137 }
139​
140export class Collection<T extends object = Record<string, unknown>> {
141 public transactionManager!: ReturnType<typeof getTransactionManager<T>>
142 private transactionStore: TransactionStore
143​
144 public optimisticOperations: Derived<Array<ChangeMessage<T>>>
145 public derivedState: Derived<Map<string, T>>
146 public derivedArray: Derived<Array<T>>
147​
148 private syncedData = new Store<Map<string, T>>(new Map())
149 public syncedMetadata = new Store(new Map<string, unknown>())
150 private pendingSyncedTransactions: Array<PendingSyncedTransaction<T>> = []
151 public config: CollectionConfig<T>
152 private hasReceivedFirstCommit = false
153​
154 // WeakMap to associate objects with their keys
155 public objectKeyMap = new WeakMap<object, string>()
156​
157 // Array to store one-time commit listeners
158 private onFirstCommitCallbacks: Array<() => void> = []
159​
160 /**
161 * Register a callback to be executed on the next commit
162 * Useful for preloading collections
163 * @param callback Function to call after the next commit
164 */
165 public onFirstCommit(callback: () => void): void {
166 this.onFirstCommitCallbacks.push(callback)
167 }
168​
169 public id = crypto.randomUUID()
170​
171 /**
172 * Creates a new Collection instance
173 *
174 * @param config - Configuration object for the collection
175 * @throws Error if sync config or mutationFn is missing
176 */
177 constructor(config?: CollectionConfig<T>) {
178 if (!config?.sync) {
179 throw new Error(`Collection requires a sync config`)
180 }
181 if (!config.mutationFn as unknown) {
182 throw new Error(`Collection requires a mutationFn`)
183 }
184​
185 this.transactionStore = new TransactionStore()
186 this.transactionManager = getTransactionManager<T>(
187 this.transactionStore,
188 this
189 )
190​
191 // Copies of live mutations are stored here and removed once the transaction completes.
192 this.optimisticOperations = new Derived({
193 fn: ({ currDepVals: [transactions] }) => {
194 const result = Array.from(transactions.values())
195 .filter(
196 (transaction) =>
197 transaction.state !== `completed` &&
198 transaction.state !== `failed`
199 )
200 .map((transaction) =>
201 transaction.mutations.map((mutation) => {
202 const message: ChangeMessage<T> = {
203 type: mutation.type,
204 key: mutation.key,
205 value: mutation.modified as T,
206 }
207 if (
208 mutation.metadata !== undefined &&
209 mutation.metadata !== null
210 ) {
211 message.metadata = mutation.metadata as Record<string, unknown>
212 }
213 return message
214 })
215 )
216 .flat()
217​
218 return result
219 },
220 deps: [this.transactionManager.transactions],
221 })
222 this.optimisticOperations.mount()
223​
224 // Combine together synced data & optimistic operations.
225 this.derivedState = new Derived({
226 fn: ({ currDepVals: [syncedData, operations] }) => {
227 const combined = new Map<string, T>(syncedData)
228 // Apply the optimistic operations on top of the synced state.
229 for (const operation of operations) {
230 let existingValue
231 switch (operation.type) {
232 case `insert`:
233 combined.set(operation.key, operation.value)
234 break
235 case `update`:
236 existingValue = syncedData.get(operation.key)
237 combined.set(operation.key, {
238 ...(existingValue || {}),
239 ...operation.value,
240 })
241 break
242 case `delete`:
243 combined.delete(operation.key)
244 break
245 }
246 }
247​
248 // Update object => key mappings
249 const optimisticKeys = new Set<string>()
250 for (const operation of operations) {
251 optimisticKeys.add(operation.key)
252 }
253​
254 optimisticKeys.forEach((key) => {
255 if (combined.has(key)) {
256 this.objectKeyMap.set(combined.get(key)!, key)
257 }
258 })
259​
260 return combined
261 },
262 deps: [this.syncedData, this.optimisticOperations],
263 })
264​
265 // Create a derived array from the map to avoid recalculating it
266 this.derivedArray = new Derived({
267 fn: ({ currDepVals: [stateMap] }) => {
268 return Array.from(stateMap.values())
269 },
270 deps: [this.derivedState],
271 })
272 this.derivedArray.mount()
273​
274 this.config = config
275​
276 this.derivedState.mount()
277​
278 // Start the sync process
279 config.sync.sync({
280 collection: this,
281 begin: () => {
282 this.pendingSyncedTransactions.push({
283 committed: false,
284 operations: [],
285 })
286 },
287 write: (message: ChangeMessage<T>) => {
288 const pendingTransaction =
289 this.pendingSyncedTransactions[
290 this.pendingSyncedTransactions.length - 1
291 ]
292 if (!pendingTransaction) {
293 throw new Error(`No pending sync transaction to write to`)
294 }
295 if (pendingTransaction.committed) {
296 throw new Error(
297 `The pending sync transaction is already committed, you can't still write to it.`
298 )
299 }
300 pendingTransaction.operations.push(message)
301 },
302 commit: () => {
303 const pendingTransaction =
304 this.pendingSyncedTransactions[
305 this.pendingSyncedTransactions.length - 1
306 ]
307 if (!pendingTransaction) {
308 throw new Error(`No pending sync transaction to commit`)
309 }
310 if (pendingTransaction.committed) {
311 throw new Error(
312 `The pending sync transaction is already committed, you can't commit it again.`
313 )
314 }
315​
316 pendingTransaction.committed = true
317​
318 this.commitPendingTransactions()
319 },
320 })
321​
322 // Listen to transactions and re-run commitPendingTransactions on changes
323 // this.transactionManager.transactions.subscribe(
324 // this.commitPendingTransactions
325 // )
326 }
327​
328 /**
329 * Attempts to commit pending synced transactions if there are no active transactions
330 * This method processes operations from pending transactions and applies them to the synced data
331 */
332 commitPendingTransactions = () => {
333 // Check if there's any transactions that aren't finished.
334 // If not, proceed.
335 // If so, subscribe to transactions and keep checking if can proceed.
336 //
337 // The plan is to have a finer-grained locking but just blocking applying
338 // synced data until a persisting transaction is finished seems fine.
339 // We also don't yet have support for transactions that don't immediately
340 // persist so right now, blocking sync only delays their application for a
341 // few hundred milliseconds. So not the worse thing in th world.
342 // But something to fix in the future.
343 // Create a Set with only the terminal states
344 const terminalStates = new Set<TransactionState>([`completed`, `failed`])
345​
346 // Function to check if a state is NOT a terminal state
347 function isNotTerminalState({ state }: Transaction): boolean {
348 return !terminalStates.has(state)
349 }
350 if (
351 this.transactions.size === 0 ||
352 !Array.from(this.transactions.values()).some(isNotTerminalState)
353 ) {
354 const keys = new Set<string>()
355 batch(() => {
356 for (const transaction of this.pendingSyncedTransactions) {
357 for (const operation of transaction.operations) {
358 keys.add(operation.key)
359 this.syncedMetadata.setState((prevData) => {
360 switch (operation.type) {
361 case `insert`:
362 prevData.set(operation.key, operation.metadata)
363 break
364 case `update`:
365 prevData.set(operation.key, {
366 ...prevData.get(operation.key)!,
367 ...operation.metadata,
368 })
369 break
370 case `delete`:
371 prevData.delete(operation.key)
372 break
373 }
374 return prevData
375 })
376 this.syncedData.setState((prevData) => {
377 switch (operation.type) {
378 case `insert`:
379 prevData.set(operation.key, operation.value)
380 break
381 case `update`:
382 prevData.set(operation.key, {
383 ...prevData.get(operation.key)!,
384 ...operation.value,
385 })
386 break
387 case `delete`:
388 prevData.delete(operation.key)
389 break
390 }
391 return prevData
392 })
393 }
394 }
395 })
396​
397 keys.forEach((key) => {
398 const curValue = this.state.get(key)
399 if (curValue) {
400 this.objectKeyMap.set(curValue, key)
401 }
402 })
403​
404 this.pendingSyncedTransactions = []
405​
406 // Call any registered one-time commit listeners
407 if (!this.hasReceivedFirstCommit) {
408 this.hasReceivedFirstCommit = true
409 const callbacks = [...this.onFirstCommitCallbacks]
410 this.onFirstCommitCallbacks = []
411 callbacks.forEach((callback) => callback())
412 }
413 }
414 }
415​
416 private ensureStandardSchema(schema: unknown): StandardSchema<T> {
417 // If the schema already implements the standard-schema interface, return it
418 if (schema && typeof schema === `object` && `~standard` in schema) {
419 return schema as StandardSchema<T>
420 }
421​
422 throw new Error(
423 `Schema must either implement the standard-schema interface or be a Zod schema`
424 )
425 }
426​
427 private validateData(
428 data: unknown,
429 type: `insert` | `update`,
430 key?: string
431 ): T | never {
432 if (!this.config.schema) return data as T
433​
434 const standardSchema = this.ensureStandardSchema(this.config.schema)
435​
436 // For updates, we need to merge with the existing data before validation
437 if (type === `update` && key) {
438 // Get the existing data for this key
439 const existingData = this.state.get(key)
440​
441 if (
442 existingData &&
443 data &&
444 typeof data === `object` &&
445 typeof existingData === `object`
446 ) {
447 // Merge the update with the existing data
448 const mergedData = { ...existingData, ...data }
449​
450 // Validate the merged data
451 const result = standardSchema[`~standard`].validate(mergedData)
452​
453 // Ensure validation is synchronous
454 if (result instanceof Promise) {
455 throw new TypeError(`Schema validation must be synchronous`)
456 }
457​
458 // If validation fails, throw a SchemaValidationError with the issues
459 if (`issues` in result && result.issues) {
460 const typedIssues = result.issues.map((issue) => ({
461 message: issue.message,
462 path: issue.path?.map((p) => String(p)),
463 }))
464 throw new SchemaValidationError(type, typedIssues)
465 }
466​
467 // Return the original update data, not the merged data
468 // We only used the merged data for validation
469 return data as T
470 }
471 }
472​
473 // For inserts or updates without existing data, validate the data directly
474 const result = standardSchema[`~standard`].validate(data)
475​
476 // Ensure validation is synchronous
477 if (result instanceof Promise) {
478 throw new TypeError(`Schema validation must be synchronous`)
479 }
480​
481 // If validation fails, throw a SchemaValidationError with the issues
482 if (`issues` in result && result.issues) {
483 const typedIssues = result.issues.map((issue) => ({
484 message: issue.message,
485 path: issue.path?.map((p) => String(p)),
486 }))
487 throw new SchemaValidationError(type, typedIssues)
488 }
489​
490 return result.value as T
491 }
492​
493 private generateKey(data: unknown): string {
494 const str = JSON.stringify(data)
495 let h = 0
496​
497 for (let i = 0; i < str.length; i++) {
498 h = (Math.imul(31, h) + str.charCodeAt(i)) | 0
499 }
500​
501 return Math.abs(h).toString(36)
502 }
503​
504 /**
505 * Inserts one or more items into the collection
506 * @param items - Single item or array of items to insert
507 * @param config - Optional configuration including metadata and custom keys
508 * @returns A Transaction object representing the insert operation(s)
509 * @throws {SchemaValidationError} If the data fails schema validation
510 * @example
511 * // Insert a single item
512 * insert({ text: "Buy groceries", completed: false })
513 *
514 * // Insert multiple items
515 * insert([
516 * { text: "Buy groceries", completed: false },
517 * { text: "Walk dog", completed: false }
518 * ])
519 *
520 * // Insert with custom key
521 * insert({ text: "Buy groceries" }, { key: "grocery-task" })
522 */
523 insert = (data: T | Array<T>, config?: InsertConfig) => {
524 const items = Array.isArray(data) ? data : [data]
525 const mutations: Array<PendingMutation> = []
526​
527 // Handle keys - convert to array if string, or generate if not provided
528 let keys: Array<string>
529 if (config?.key) {
530 const configKeys = Array.isArray(config.key) ? config.key : [config.key]
531 // If keys are provided, ensure we have the right number or allow sparse array
532 if (Array.isArray(config.key) && configKeys.length > items.length) {
533 throw new Error(`More keys provided than items to insert`)
534 }
535 keys = items.map((_, i) => configKeys[i] ?? this.generateKey(items[i]))
536 } else {
537 // No keys provided, generate for all items
538 keys = items.map((item) => this.generateKey(item))
539 }
540​
541 // Create mutations for each item
542 items.forEach((item, index) => {
543 // Validate the data against the schema if one exists
544 const validatedData = this.validateData(item, `insert`)
545 const key = keys[index]
546​
547 const mutation: PendingMutation = {
548 mutationId: crypto.randomUUID(),
549 original: {},
550 modified: validatedData as Record<string, unknown>,
551 changes: validatedData as Record<string, unknown>,
552 key,
553 metadata: config?.metadata as unknown,
554 syncMetadata: this.config.sync.getSyncMetadata?.() || {},
555 type: `insert`,
556 createdAt: new Date(),
557 updatedAt: new Date(),
558 }
559​
560 mutations.push(mutation)
561 })
562​
563 return this.transactionManager.applyTransaction(mutations, {
564 type: `ordered`,
565 })
566 }
567​
568 /**
569 * Updates one or more items in the collection using a callback function
570 * @param items - Single item/key or array of items/keys to update
571 * @param configOrCallback - Either update configuration or update callback
572 * @param maybeCallback - Update callback if config was provided
573 * @returns A Transaction object representing the update operation(s)
574 * @throws {SchemaValidationError} If the updated data fails schema validation
575 * @example
576 * // Update a single item
577 * update(todo, (draft) => { draft.completed = true })
578 *
579 * // Update multiple items
580 * update([todo1, todo2], (drafts) => {
581 * drafts.forEach(draft => { draft.completed = true })
582 * })
583 *
584 * // Update with metadata
585 * update(todo, { metadata: { reason: "user update" } }, (draft) => { draft.text = "Updated text" })
586 */
587​
588 update<TItem extends object = T>(
589 item: TItem,
590 configOrCallback: ((draft: TItem) => void) | OperationConfig,
591 maybeCallback?: (draft: TItem) => void
592 ): Transaction
593​
594 update<TItem extends object = T>(
595 items: Array<TItem>,
596 configOrCallback: ((draft: Array<TItem>) => void) | OperationConfig,
597 maybeCallback?: (draft: Array<TItem>) => void
598 ): Transaction
599​
600 update<TItem extends object = T>(
601 items: TItem | Array<TItem>,
602 configOrCallback: ((draft: TItem | Array<TItem>) => void) | OperationConfig,
603 maybeCallback?: (draft: TItem | Array<TItem>) => void
604 ) {
605 const isArray = Array.isArray(items)
606 const itemsArray = Array.isArray(items) ? items : [items]
607 const callback =
608 typeof configOrCallback === `function` ? configOrCallback : maybeCallback!
609 const config =
610 typeof configOrCallback === `function` ? {} : configOrCallback
611​
612 const keys = itemsArray.map((item) => {
613 if (typeof item === `object` && (item as unknown) !== null) {
614 const key = this.objectKeyMap.get(item)
615 if (key === undefined) {
616 throw new Error(`Object not found in collection`)
617 }
618 return key
619 }
620 throw new Error(`Invalid item type for update - must be an object`)
621 })
622​
623 // Get the current objects or empty objects if they don't exist
624 const currentObjects = keys.map((key) => ({
625 ...(this.state.get(key) || {}),
626 })) as Array<TItem>
627​
628 let changesArray
629 if (isArray) {
630 // Use the proxy to track changes for all objects
631 changesArray = withArrayChangeTracking(
632 currentObjects,
633 callback as (draft: Array<TItem>) => void
634 )
635 } else {
636 const result = withChangeTracking(
637 currentObjects[0],
638 callback as (draft: TItem) => void
639 )
640 changesArray = [result]
641 }
642​
643 // Create mutations for each object that has changes
644 const mutations: Array<PendingMutation> = keys
645 .map((key, index) => {
646 const changes = changesArray[index]
647​
648 // Skip items with no changes
649 if (!changes || Object.keys(changes).length === 0) {
650 return null
651 }
652​
653 // Validate the changes for this item
654 const validatedData = this.validateData(changes, `update`, key)
655​
656 return {
657 mutationId: crypto.randomUUID(),
658 original: (this.state.get(key) || {}) as Record<string, unknown>,
659 modified: {
660 ...(this.state.get(key) || {}),
661 ...validatedData,
662 } as Record<string, unknown>,
663 changes: validatedData as Record<string, unknown>,
664 key,
665 metadata: config.metadata as unknown,
666 syncMetadata: (this.syncedMetadata.state.get(key) || {}) as Record<
667 string,
668 unknown
669 >,
670 type: `update`,
671 createdAt: new Date(),
672 updatedAt: new Date(),
673 }
674 })
675 .filter(Boolean) as Array<PendingMutation>
676​
677 // If no changes were made, return early
678 if (mutations.length === 0) {
679 throw new Error(`No changes were made to any of the objects`)
680 }
681​
682 return this.transactionManager.applyTransaction(mutations, {
683 type: `ordered`,
684 })
685 }
686​
687 /**
688 * Deletes one or more items from the collection
689 * @param items - Single item/key or array of items/keys to delete
690 * @param config - Optional configuration including metadata
691 * @returns A Transaction object representing the delete operation(s)
692 * @example
693 * // Delete a single item
694 * delete(todo)
695 *
696 * // Delete multiple items
697 * delete([todo1, todo2])
698 *
699 * // Delete with metadata
700 * delete(todo, { metadata: { reason: "completed" } })
701 */
702 delete = (
703 items: Array<T | string> | T | string,
704 config?: OperationConfig
705 ) => {
706 const itemsArray = Array.isArray(items) ? items : [items]
707 const mutations: Array<PendingMutation> = []
708​
709 for (const item of itemsArray) {
710 let key: string
711 if (typeof item === `object` && (item as unknown) !== null) {
712 const objectKey = this.objectKeyMap.get(item)
713 if (objectKey === undefined) {
714 throw new Error(`Object not found in collection`)
715 }
716 key = objectKey
717 } else if (typeof item === `string`) {
718 key = item
719 } else {
720 throw new Error(
721 `Invalid item type for delete - must be an object or string key`
722 )
723 }
724​
725 const mutation: PendingMutation = {
726 mutationId: crypto.randomUUID(),
727 original: (this.state.get(key) || {}) as Record<string, unknown>,
728 modified: { _deleted: true },
729 changes: { _deleted: true },
730 key,
731 metadata: config?.metadata as unknown,
732 syncMetadata: (this.syncedMetadata.state.get(key) || {}) as Record<
733 string,
734 unknown
735 >,
736 type: `delete`,
737 createdAt: new Date(),
738 updatedAt: new Date(),
739 }
740​
741 mutations.push(mutation)
742 }
743​
744 // Delete object => key mapping.
745 mutations.forEach((mutation) => {
746 const curValue = this.state.get(mutation.key)
747 if (curValue) {
748 this.objectKeyMap.delete(curValue)
749 }
750 })
751​
752 return this.transactionManager.applyTransaction(mutations, {
753 type: `ordered`,
754 })
755 }
756​
757 /**
758 * Gets the current state of the collection as a Map
759 *
760 * @returns A Map containing all items in the collection, with keys as identifiers
761 */
762 get state() {
763 return this.derivedState.state
764 }
765​
766 /**
767 * Gets the current state of the collection as a Map, but only resolves when data is available
768 * Waits for the first sync commit to complete before resolving
769 *
770 * @returns Promise that resolves to a Map containing all items in the collection
771 */
772 stateWhenReady(): Promise<Map<string, T>> {
773 // If we already have data or there are no loading collections, resolve immediately
774 if (this.state.size > 0 || this.hasReceivedFirstCommit === true) {
775 return Promise.resolve(this.state)
776 }
777​
778 // Otherwise, wait for the first commit
779 return new Promise<Map<string, T>>((resolve) => {
780 this.onFirstCommit(() => {
781 resolve(this.state)
782 })
783 })
784 }
785​
786 /**
787 * Gets the current state of the collection as an Array
788 *
789 * @returns An Array containing all items in the collection
790 */
791 get toArray() {
792 return this.derivedArray.state
793 }
794​
795 /**
796 * Gets the current state of the collection as an Array, but only resolves when data is available
797 * Waits for the first sync commit to complete before resolving
798 *
799 * @returns Promise that resolves to an Array containing all items in the collection
800 */
801 toArrayWhenReady(): Promise<Array<T>> {
802 // If we already have data or there are no loading collections, resolve immediately
803 if (this.toArray.length > 0 || this.hasReceivedFirstCommit === true) {
804 return Promise.resolve(this.toArray)
805 }
806​
807 // Otherwise, wait for the first commit
808 return new Promise<Array<T>>((resolve) => {
809 this.onFirstCommit(() => {
810 resolve(this.toArray)
811 })
812 })
813 }
814​
815 /**
816 * Gets the current transactions in the collection
817 *
818 * @returns A SortedMap of all transactions in the collection
819 */
820 get transactions() {
821 return this.transactionManager.transactions.state
822 }