@verdant-web/store 3.3.1 → 3.4.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle/index.js +8 -8
- package/dist/bundle/index.js.map +4 -4
- package/dist/esm/BackoffScheduler.js.map +1 -1
- package/dist/esm/IDBService.js.map +1 -1
- package/dist/esm/UndoHistory.js.map +1 -1
- package/dist/esm/__tests__/documents.test.js.map +1 -1
- package/dist/esm/__tests__/queries.test.js.map +1 -1
- package/dist/esm/backup.js.map +1 -1
- package/dist/esm/client/Client.js +7 -0
- package/dist/esm/client/Client.js.map +1 -1
- package/dist/esm/client/ClientDescriptor.js.map +1 -1
- package/dist/esm/entities/Entity.js.map +1 -1
- package/dist/esm/entities/EntityCache.js.map +1 -1
- package/dist/esm/entities/EntityMetadata.js.map +1 -1
- package/dist/esm/entities/EntityStore.js.map +1 -1
- package/dist/esm/entities/OperationBatcher.js.map +1 -1
- package/dist/esm/files/EntityFile.js.map +1 -1
- package/dist/esm/files/FileManager.js +3 -0
- package/dist/esm/files/FileManager.js.map +1 -1
- package/dist/esm/files/FileStorage.js.map +1 -1
- package/dist/esm/files/utils.js.map +1 -1
- package/dist/esm/idb.js.map +1 -1
- package/dist/esm/metadata/AckInfoStore.js.map +1 -1
- package/dist/esm/metadata/LocalReplicaStore.js.map +1 -1
- package/dist/esm/metadata/MessageCreator.js.map +1 -1
- package/dist/esm/metadata/Metadata.js +7 -4
- package/dist/esm/metadata/Metadata.js.map +1 -1
- package/dist/esm/metadata/OperationsStore.js.map +1 -1
- package/dist/esm/metadata/SchemaStore.js.map +1 -1
- package/dist/esm/metadata/openMetadataDatabase.js.map +1 -1
- package/dist/esm/migration/db.js.map +1 -1
- package/dist/esm/migration/openDatabase.js.map +1 -1
- package/dist/esm/migration/paths.js.map +1 -1
- package/dist/esm/queries/BaseQuery.js.map +1 -1
- package/dist/esm/queries/QueryCache.js.map +1 -1
- package/dist/esm/queries/QueryableStorage.js.map +1 -1
- package/dist/esm/queries/dbQueries.js.map +1 -1
- package/dist/esm/queries/keys.js.map +1 -1
- package/dist/esm/queries/ranges.js.map +1 -1
- package/dist/esm/queries/utils.js.map +1 -1
- package/dist/esm/sync/FileSync.js.map +1 -1
- package/dist/esm/sync/Heartbeat.js.map +1 -1
- package/dist/esm/sync/PresenceManager.js.map +1 -1
- package/dist/esm/sync/PushPullSync.js.map +1 -1
- package/dist/esm/sync/ServerSyncEndpointProvider.js.map +1 -1
- package/dist/esm/sync/Sync.js.map +1 -1
- package/dist/esm/sync/WebSocketSync.js.map +1 -1
- package/package.json +9 -10
- package/src/client/Client.ts +8 -1
- package/src/files/FileManager.ts +4 -0
- package/src/metadata/Metadata.ts +11 -7
- package/src/sync/Sync.ts +2 -2
- package/dist/cjs/BackoffScheduler.d.ts +0 -19
- package/dist/cjs/BackoffScheduler.js +0 -45
- package/dist/cjs/BackoffScheduler.js.map +0 -1
- package/dist/cjs/DocumentManager.d.ts +0 -28
- package/dist/cjs/DocumentManager.js +0 -45
- package/dist/cjs/DocumentManager.js.map +0 -1
- package/dist/cjs/FakeWeakRef.d.ts +0 -11
- package/dist/cjs/FakeWeakRef.js +0 -19
- package/dist/cjs/FakeWeakRef.js.map +0 -1
- package/dist/cjs/IDBService.d.ts +0 -30
- package/dist/cjs/IDBService.js +0 -101
- package/dist/cjs/IDBService.js.map +0 -1
- package/dist/cjs/UndoHistory.d.ts +0 -16
- package/dist/cjs/UndoHistory.js +0 -55
- package/dist/cjs/UndoHistory.js.map +0 -1
- package/dist/cjs/__tests__/batching.test.d.ts +0 -1
- package/dist/cjs/__tests__/batching.test.js +0 -47
- package/dist/cjs/__tests__/batching.test.js.map +0 -1
- package/dist/cjs/__tests__/documents.test.d.ts +0 -1
- package/dist/cjs/__tests__/documents.test.js +0 -468
- package/dist/cjs/__tests__/documents.test.js.map +0 -1
- package/dist/cjs/__tests__/fixtures/testStorage.d.ts +0 -76
- package/dist/cjs/__tests__/fixtures/testStorage.js +0 -96
- package/dist/cjs/__tests__/fixtures/testStorage.js.map +0 -1
- package/dist/cjs/__tests__/legacyOids.test.d.ts +0 -1
- package/dist/cjs/__tests__/legacyOids.test.js +0 -354
- package/dist/cjs/__tests__/legacyOids.test.js.map +0 -1
- package/dist/cjs/__tests__/mutations.test.d.ts +0 -1
- package/dist/cjs/__tests__/mutations.test.js +0 -48
- package/dist/cjs/__tests__/mutations.test.js.map +0 -1
- package/dist/cjs/__tests__/queries.test.d.ts +0 -1
- package/dist/cjs/__tests__/queries.test.js +0 -323
- package/dist/cjs/__tests__/queries.test.js.map +0 -1
- package/dist/cjs/__tests__/setup/indexedDB.d.ts +0 -1
- package/dist/cjs/__tests__/setup/indexedDB.js +0 -16
- package/dist/cjs/__tests__/setup/indexedDB.js.map +0 -1
- package/dist/cjs/__tests__/undo.test.d.ts +0 -1
- package/dist/cjs/__tests__/undo.test.js +0 -94
- package/dist/cjs/__tests__/undo.test.js.map +0 -1
- package/dist/cjs/backup.d.ts +0 -10
- package/dist/cjs/backup.js +0 -58
- package/dist/cjs/backup.js.map +0 -1
- package/dist/cjs/client/Client.d.ts +0 -120
- package/dist/cjs/client/Client.js +0 -300
- package/dist/cjs/client/Client.js.map +0 -1
- package/dist/cjs/client/ClientDescriptor.d.ts +0 -76
- package/dist/cjs/client/ClientDescriptor.js +0 -213
- package/dist/cjs/client/ClientDescriptor.js.map +0 -1
- package/dist/cjs/client/constants.d.ts +0 -1
- package/dist/cjs/client/constants.js +0 -5
- package/dist/cjs/client/constants.js.map +0 -1
- package/dist/cjs/constants.d.ts +0 -1
- package/dist/cjs/constants.js +0 -5
- package/dist/cjs/constants.js.map +0 -1
- package/dist/cjs/context.d.ts +0 -38
- package/dist/cjs/context.js +0 -3
- package/dist/cjs/context.js.map +0 -1
- package/dist/cjs/entities/Entity.d.ts +0 -148
- package/dist/cjs/entities/Entity.js +0 -711
- package/dist/cjs/entities/Entity.js.map +0 -1
- package/dist/cjs/entities/Entity.test.d.ts +0 -1
- package/dist/cjs/entities/Entity.test.js +0 -194
- package/dist/cjs/entities/Entity.test.js.map +0 -1
- package/dist/cjs/entities/EntityCache.d.ts +0 -15
- package/dist/cjs/entities/EntityCache.js +0 -39
- package/dist/cjs/entities/EntityCache.js.map +0 -1
- package/dist/cjs/entities/EntityMetadata.d.ts +0 -68
- package/dist/cjs/entities/EntityMetadata.js +0 -261
- package/dist/cjs/entities/EntityMetadata.js.map +0 -1
- package/dist/cjs/entities/EntityStore.d.ts +0 -80
- package/dist/cjs/entities/EntityStore.js +0 -352
- package/dist/cjs/entities/EntityStore.js.map +0 -1
- package/dist/cjs/entities/OperationBatcher.d.ts +0 -52
- package/dist/cjs/entities/OperationBatcher.js +0 -165
- package/dist/cjs/entities/OperationBatcher.js.map +0 -1
- package/dist/cjs/entities/types.d.ts +0 -103
- package/dist/cjs/entities/types.js +0 -3
- package/dist/cjs/entities/types.js.map +0 -1
- package/dist/cjs/files/EntityFile.d.ts +0 -35
- package/dist/cjs/files/EntityFile.js +0 -81
- package/dist/cjs/files/EntityFile.js.map +0 -1
- package/dist/cjs/files/FileManager.d.ts +0 -46
- package/dist/cjs/files/FileManager.js +0 -174
- package/dist/cjs/files/FileManager.js.map +0 -1
- package/dist/cjs/files/FileStorage.d.ts +0 -39
- package/dist/cjs/files/FileStorage.js +0 -110
- package/dist/cjs/files/FileStorage.js.map +0 -1
- package/dist/cjs/files/utils.d.ts +0 -10
- package/dist/cjs/files/utils.js +0 -62
- package/dist/cjs/files/utils.js.map +0 -1
- package/dist/cjs/files/utils.test.d.ts +0 -1
- package/dist/cjs/files/utils.test.js +0 -81
- package/dist/cjs/files/utils.test.js.map +0 -1
- package/dist/cjs/idb.d.ts +0 -13
- package/dist/cjs/idb.js +0 -158
- package/dist/cjs/idb.js.map +0 -1
- package/dist/cjs/index.d.ts +0 -23
- package/dist/cjs/index.js +0 -25
- package/dist/cjs/index.js.map +0 -1
- package/dist/cjs/metadata/AckInfoStore.d.ts +0 -10
- package/dist/cjs/metadata/AckInfoStore.js +0 -26
- package/dist/cjs/metadata/AckInfoStore.js.map +0 -1
- package/dist/cjs/metadata/BaselinesStore.d.ts +0 -40
- package/dist/cjs/metadata/BaselinesStore.js +0 -106
- package/dist/cjs/metadata/BaselinesStore.js.map +0 -1
- package/dist/cjs/metadata/LocalReplicaStore.d.ts +0 -18
- package/dist/cjs/metadata/LocalReplicaStore.js +0 -62
- package/dist/cjs/metadata/LocalReplicaStore.js.map +0 -1
- package/dist/cjs/metadata/MessageCreator.d.ts +0 -19
- package/dist/cjs/metadata/MessageCreator.js +0 -128
- package/dist/cjs/metadata/MessageCreator.js.map +0 -1
- package/dist/cjs/metadata/Metadata.d.ts +0 -134
- package/dist/cjs/metadata/Metadata.js +0 -405
- package/dist/cjs/metadata/Metadata.js.map +0 -1
- package/dist/cjs/metadata/OperationsStore.d.ts +0 -62
- package/dist/cjs/metadata/OperationsStore.js +0 -179
- package/dist/cjs/metadata/OperationsStore.js.map +0 -1
- package/dist/cjs/metadata/SchemaStore.d.ts +0 -9
- package/dist/cjs/metadata/SchemaStore.js +0 -39
- package/dist/cjs/metadata/SchemaStore.js.map +0 -1
- package/dist/cjs/metadata/openMetadataDatabase.d.ts +0 -19
- package/dist/cjs/metadata/openMetadataDatabase.js +0 -220
- package/dist/cjs/metadata/openMetadataDatabase.js.map +0 -1
- package/dist/cjs/migration/db.d.ts +0 -8
- package/dist/cjs/migration/db.js +0 -112
- package/dist/cjs/migration/db.js.map +0 -1
- package/dist/cjs/migration/errors.d.ts +0 -5
- package/dist/cjs/migration/errors.js +0 -12
- package/dist/cjs/migration/errors.js.map +0 -1
- package/dist/cjs/migration/openDatabase.d.ts +0 -20
- package/dist/cjs/migration/openDatabase.js +0 -468
- package/dist/cjs/migration/openDatabase.js.map +0 -1
- package/dist/cjs/migration/paths.d.ts +0 -6
- package/dist/cjs/migration/paths.js +0 -53
- package/dist/cjs/migration/paths.js.map +0 -1
- package/dist/cjs/migration/paths.test.d.ts +0 -1
- package/dist/cjs/migration/paths.test.js +0 -91
- package/dist/cjs/migration/paths.test.js.map +0 -1
- package/dist/cjs/queries/BaseQuery.d.ts +0 -53
- package/dist/cjs/queries/BaseQuery.js +0 -148
- package/dist/cjs/queries/BaseQuery.js.map +0 -1
- package/dist/cjs/queries/CollectionQueries.d.ts +0 -55
- package/dist/cjs/queries/CollectionQueries.js +0 -92
- package/dist/cjs/queries/CollectionQueries.js.map +0 -1
- package/dist/cjs/queries/FindAllQuery.d.ts +0 -12
- package/dist/cjs/queries/FindAllQuery.js +0 -44
- package/dist/cjs/queries/FindAllQuery.js.map +0 -1
- package/dist/cjs/queries/FindInfiniteQuery.d.ts +0 -19
- package/dist/cjs/queries/FindInfiniteQuery.js +0 -70
- package/dist/cjs/queries/FindInfiniteQuery.js.map +0 -1
- package/dist/cjs/queries/FindOneQuery.d.ts +0 -12
- package/dist/cjs/queries/FindOneQuery.js +0 -43
- package/dist/cjs/queries/FindOneQuery.js.map +0 -1
- package/dist/cjs/queries/FindPageQuery.d.ts +0 -24
- package/dist/cjs/queries/FindPageQuery.js +0 -77
- package/dist/cjs/queries/FindPageQuery.js.map +0 -1
- package/dist/cjs/queries/GetQuery.d.ts +0 -10
- package/dist/cjs/queries/GetQuery.js +0 -30
- package/dist/cjs/queries/GetQuery.js.map +0 -1
- package/dist/cjs/queries/QueryCache.d.ts +0 -17
- package/dist/cjs/queries/QueryCache.js +0 -46
- package/dist/cjs/queries/QueryCache.js.map +0 -1
- package/dist/cjs/queries/QueryableStorage.d.ts +0 -20
- package/dist/cjs/queries/QueryableStorage.js +0 -94
- package/dist/cjs/queries/QueryableStorage.js.map +0 -1
- package/dist/cjs/queries/dbQueries.d.ts +0 -22
- package/dist/cjs/queries/dbQueries.js +0 -136
- package/dist/cjs/queries/dbQueries.js.map +0 -1
- package/dist/cjs/queries/keys.d.ts +0 -10
- package/dist/cjs/queries/keys.js +0 -34
- package/dist/cjs/queries/keys.js.map +0 -1
- package/dist/cjs/queries/ranges.d.ts +0 -2
- package/dist/cjs/queries/ranges.js +0 -70
- package/dist/cjs/queries/ranges.js.map +0 -1
- package/dist/cjs/queries/types.d.ts +0 -6
- package/dist/cjs/queries/types.js +0 -3
- package/dist/cjs/queries/types.js.map +0 -1
- package/dist/cjs/queries/utils.d.ts +0 -3
- package/dist/cjs/queries/utils.js +0 -25
- package/dist/cjs/queries/utils.js.map +0 -1
- package/dist/cjs/sync/FileSync.d.ts +0 -24
- package/dist/cjs/sync/FileSync.js +0 -87
- package/dist/cjs/sync/FileSync.js.map +0 -1
- package/dist/cjs/sync/Heartbeat.d.ts +0 -25
- package/dist/cjs/sync/Heartbeat.js +0 -64
- package/dist/cjs/sync/Heartbeat.js.map +0 -1
- package/dist/cjs/sync/PresenceManager.d.ts +0 -55
- package/dist/cjs/sync/PresenceManager.js +0 -126
- package/dist/cjs/sync/PresenceManager.js.map +0 -1
- package/dist/cjs/sync/PushPullSync.d.ts +0 -39
- package/dist/cjs/sync/PushPullSync.js +0 -159
- package/dist/cjs/sync/PushPullSync.js.map +0 -1
- package/dist/cjs/sync/ServerSyncEndpointProvider.d.ts +0 -34
- package/dist/cjs/sync/ServerSyncEndpointProvider.js +0 -69
- package/dist/cjs/sync/ServerSyncEndpointProvider.js.map +0 -1
- package/dist/cjs/sync/Sync.d.ts +0 -160
- package/dist/cjs/sync/Sync.js +0 -293
- package/dist/cjs/sync/Sync.js.map +0 -1
- package/dist/cjs/sync/WebSocketSync.d.ts +0 -44
- package/dist/cjs/sync/WebSocketSync.js +0 -221
- package/dist/cjs/sync/WebSocketSync.js.map +0 -1
- package/dist/cjs/types.d.ts +0 -12
- package/dist/cjs/types.js +0 -3
- package/dist/cjs/types.js.map +0 -1
- package/dist/cjs/utils/Disposable.d.ts +0 -6
- package/dist/cjs/utils/Disposable.js +0 -19
- package/dist/cjs/utils/Disposable.js.map +0 -1
- package/dist/cjs/utils/Resolvable.d.ts +0 -8
- package/dist/cjs/utils/Resolvable.js +0 -23
- package/dist/cjs/utils/Resolvable.js.map +0 -1
- package/dist/cjs/vanilla.d.ts +0 -1
- package/dist/cjs/vanilla.js +0 -28
- package/dist/cjs/vanilla.js.map +0 -1
- package/dist/esm/BackoffScheduler.d.ts +0 -19
- package/dist/esm/DocumentManager.d.ts +0 -28
- package/dist/esm/FakeWeakRef.d.ts +0 -11
- package/dist/esm/IDBService.d.ts +0 -30
- package/dist/esm/UndoHistory.d.ts +0 -16
- package/dist/esm/__tests__/batching.test.d.ts +0 -1
- package/dist/esm/__tests__/documents.test.d.ts +0 -1
- package/dist/esm/__tests__/fixtures/testStorage.d.ts +0 -76
- package/dist/esm/__tests__/legacyOids.test.d.ts +0 -1
- package/dist/esm/__tests__/mutations.test.d.ts +0 -1
- package/dist/esm/__tests__/queries.test.d.ts +0 -1
- package/dist/esm/__tests__/setup/indexedDB.d.ts +0 -1
- package/dist/esm/__tests__/undo.test.d.ts +0 -1
- package/dist/esm/backup.d.ts +0 -10
- package/dist/esm/client/Client.d.ts +0 -120
- package/dist/esm/client/ClientDescriptor.d.ts +0 -76
- package/dist/esm/client/constants.d.ts +0 -1
- package/dist/esm/constants.d.ts +0 -1
- package/dist/esm/context.d.ts +0 -38
- package/dist/esm/entities/Entity.d.ts +0 -148
- package/dist/esm/entities/Entity.test.d.ts +0 -1
- package/dist/esm/entities/EntityCache.d.ts +0 -15
- package/dist/esm/entities/EntityMetadata.d.ts +0 -68
- package/dist/esm/entities/EntityStore.d.ts +0 -80
- package/dist/esm/entities/OperationBatcher.d.ts +0 -52
- package/dist/esm/entities/types.d.ts +0 -103
- package/dist/esm/files/EntityFile.d.ts +0 -35
- package/dist/esm/files/FileManager.d.ts +0 -46
- package/dist/esm/files/FileStorage.d.ts +0 -39
- package/dist/esm/files/utils.d.ts +0 -10
- package/dist/esm/files/utils.test.d.ts +0 -1
- package/dist/esm/idb.d.ts +0 -13
- package/dist/esm/index.d.ts +0 -23
- package/dist/esm/metadata/AckInfoStore.d.ts +0 -10
- package/dist/esm/metadata/BaselinesStore.d.ts +0 -40
- package/dist/esm/metadata/LocalReplicaStore.d.ts +0 -18
- package/dist/esm/metadata/MessageCreator.d.ts +0 -19
- package/dist/esm/metadata/Metadata.d.ts +0 -134
- package/dist/esm/metadata/OperationsStore.d.ts +0 -62
- package/dist/esm/metadata/SchemaStore.d.ts +0 -9
- package/dist/esm/metadata/openMetadataDatabase.d.ts +0 -19
- package/dist/esm/migration/db.d.ts +0 -8
- package/dist/esm/migration/errors.d.ts +0 -5
- package/dist/esm/migration/openDatabase.d.ts +0 -20
- package/dist/esm/migration/paths.d.ts +0 -6
- package/dist/esm/migration/paths.test.d.ts +0 -1
- package/dist/esm/queries/BaseQuery.d.ts +0 -53
- package/dist/esm/queries/CollectionQueries.d.ts +0 -55
- package/dist/esm/queries/FindAllQuery.d.ts +0 -12
- package/dist/esm/queries/FindInfiniteQuery.d.ts +0 -19
- package/dist/esm/queries/FindOneQuery.d.ts +0 -12
- package/dist/esm/queries/FindPageQuery.d.ts +0 -24
- package/dist/esm/queries/GetQuery.d.ts +0 -10
- package/dist/esm/queries/QueryCache.d.ts +0 -17
- package/dist/esm/queries/QueryableStorage.d.ts +0 -20
- package/dist/esm/queries/dbQueries.d.ts +0 -22
- package/dist/esm/queries/keys.d.ts +0 -10
- package/dist/esm/queries/ranges.d.ts +0 -2
- package/dist/esm/queries/types.d.ts +0 -6
- package/dist/esm/queries/utils.d.ts +0 -3
- package/dist/esm/sync/FileSync.d.ts +0 -24
- package/dist/esm/sync/Heartbeat.d.ts +0 -25
- package/dist/esm/sync/PresenceManager.d.ts +0 -55
- package/dist/esm/sync/PushPullSync.d.ts +0 -39
- package/dist/esm/sync/ServerSyncEndpointProvider.d.ts +0 -34
- package/dist/esm/sync/Sync.d.ts +0 -160
- package/dist/esm/sync/WebSocketSync.d.ts +0 -44
- package/dist/esm/types.d.ts +0 -12
- package/dist/esm/utils/Disposable.d.ts +0 -6
- package/dist/esm/utils/Resolvable.d.ts +0 -8
- package/dist/esm/vanilla.d.ts +0 -1
- package/dist/tsconfig-cjs.tsbuildinfo +0 -1
- package/dist/tsconfig.tsbuildinfo +0 -1
package/dist/bundle/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Uo=Object.create;var Pt=Object.defineProperty;var Vo=Object.getOwnPropertyDescriptor;var No=Object.getOwnPropertyNames;var $o=Object.getPrototypeOf,zo=Object.prototype.hasOwnProperty;var Ko=(n,i)=>()=>(n&&(i=n(n=0)),i);var oe=(n,i)=>()=>(i||n((i={exports:{}}).exports,i),i.exports),Zi=(n,i)=>{for(var e in i)Pt(n,e,{get:i[e],enumerable:!0})},er=(n,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of No(i))!zo.call(n,r)&&r!==e&&Pt(n,r,{get:()=>i[r],enumerable:!(t=Vo(i,r))||t.enumerable});return n};var Je=(n,i,e)=>(e=n!=null?Uo($o(n)):{},er(i||!n||!n.__esModule?Pt(e,"default",{value:n,enumerable:!0}):e,n)),Ge=n=>er(Pt({},"__esModule",{value:!0}),n);var Qn=oe((Pa,tr)=>{tr.exports=function(i,e){var t="000000000"+i;return t.substr(t.length-e)}});var ir=oe((Ra,nr)=>{var qo=Qn(),Ho=typeof window=="object"?window:self,Wo=Object.keys(Ho).length,Qo=navigator.mimeTypes?navigator.mimeTypes.length:0,Jo=qo((Qo+navigator.userAgent.length).toString(36)+Wo.toString(36),4);nr.exports=function(){return Jo}});var ar=oe((Fa,sr)=>{var Jn,rr=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;rr?(or=Math.pow(2,32)-1,Jn=function(){return Math.abs(rr.getRandomValues(new Uint32Array(1))[0]/or)}):Jn=Math.random;var or;sr.exports=Jn});var ct=oe((Ta,ur)=>{var Rt=ir(),cr=Qn(),Go=ar(),st=0,Yn=4,Ft=36,lr=Math.pow(Ft,Yn);function Gn(){return cr((Go()*lr<<0).toString(Ft),Yn)}function dr(){return st=st<lr?st:0,st++,st-1}function at(){var n="c",i=new Date().getTime().toString(Ft),e=cr(dr().toString(Ft),Yn),t=Rt(),r=Gn()+Gn();return n+i+e+t+r}at.slug=function(){var i=new Date().getTime().toString(36),e=dr().toString(36).slice(-4),t=Rt().slice(0,1)+Rt().slice(-1),r=Gn().slice(-2);return i.slice(-2)+e+t+r};at.isCuid=function(i){return typeof i!="string"?!1:!!i.startsWith("c")};at.isSlug=function(i){if(typeof i!="string")return!1;var e=i.length;return e>=7&&e<=10};at.fingerprint=Rt;ur.exports=at});var Or=oe((xr,Sr)=>{(function(n){var i;typeof xr=="object"?Sr.exports=n():typeof define=="function"&&define.amd?define(n):(typeof window<"u"?i=window:typeof global<"u"?i=global:typeof self<"u"&&(i=self),i.objectHash=n())})(function(){return function n(i,e,t){function r(a,h){if(!e[a]){if(!i[a]){var u=typeof require=="function"&&require;if(!h&&u)return u(a,!0);if(o)return o(a,!0);throw new Error("Cannot find module '"+a+"'")}h=e[a]={exports:{}},i[a][0].call(h.exports,function(m){var v=i[a][1][m];return r(v||m)},h,h.exports,n,i,e,t)}return e[a].exports}for(var o=typeof require=="function"&&require,s=0;s<t.length;s++)r(t[s]);return r}({1:[function(n,i,e){(function(t,r,o,s,a,h,u,m,v){"use strict";var y=n("crypto");function C(b,D){D=I(b,D);var d;return(d=D.algorithm!=="passthrough"?y.createHash(D.algorithm):new R).write===void 0&&(d.write=d.update,d.end=d.update),_(D,d).dispatch(b),d.update||d.end(""),d.digest?d.digest(D.encoding==="buffer"?void 0:D.encoding):(b=d.read(),D.encoding!=="buffer"?b.toString(D.encoding):b)}(e=i.exports=C).sha1=function(b){return C(b)},e.keys=function(b){return C(b,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},e.MD5=function(b){return C(b,{algorithm:"md5",encoding:"hex"})},e.keysMD5=function(b){return C(b,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var w=y.getHashes?y.getHashes().slice():["sha1","md5"],S=(w.push("passthrough"),["buffer","hex","binary","base64"]);function I(b,D){var d={};if(d.algorithm=(D=D||{}).algorithm||"sha1",d.encoding=D.encoding||"hex",d.excludeValues=!!D.excludeValues,d.algorithm=d.algorithm.toLowerCase(),d.encoding=d.encoding.toLowerCase(),d.ignoreUnknown=D.ignoreUnknown===!0,d.respectType=D.respectType!==!1,d.respectFunctionNames=D.respectFunctionNames!==!1,d.respectFunctionProperties=D.respectFunctionProperties!==!1,d.unorderedArrays=D.unorderedArrays===!0,d.unorderedSets=D.unorderedSets!==!1,d.unorderedObjects=D.unorderedObjects!==!1,d.replacer=D.replacer||void 0,d.excludeKeys=D.excludeKeys||void 0,b===void 0)throw new Error("Object argument required.");for(var p=0;p<w.length;++p)w[p].toLowerCase()===d.algorithm.toLowerCase()&&(d.algorithm=w[p]);if(w.indexOf(d.algorithm)===-1)throw new Error('Algorithm "'+d.algorithm+'" not supported. supported values: '+w.join(", "));if(S.indexOf(d.encoding)===-1&&d.algorithm!=="passthrough")throw new Error('Encoding "'+d.encoding+'" not supported. supported values: '+S.join(", "));return d}function x(b){if(typeof b=="function")return/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(b))!=null}function _(b,D,d){d=d||[];function p(l){return D.update?D.update(l,"utf8"):D.write(l,"utf8")}return{dispatch:function(l){return this["_"+((l=b.replacer?b.replacer(l):l)===null?"null":typeof l)](l)},_object:function(l){var O,E=Object.prototype.toString.call(l),j=/\[object (.*)\]/i.exec(E);if(j=(j=j?j[1]:"unknown:["+E+"]").toLowerCase(),0<=(E=d.indexOf(l)))return this.dispatch("[CIRCULAR:"+E+"]");if(d.push(l),o!==void 0&&o.isBuffer&&o.isBuffer(l))return p("buffer:"),p(l);if(j==="object"||j==="function"||j==="asyncfunction")return E=Object.keys(l),b.unorderedObjects&&(E=E.sort()),b.respectType===!1||x(l)||E.splice(0,0,"prototype","__proto__","constructor"),b.excludeKeys&&(E=E.filter(function(B){return!b.excludeKeys(B)})),p("object:"+E.length+":"),O=this,E.forEach(function(B){O.dispatch(B),p(":"),b.excludeValues||O.dispatch(l[B]),p(",")});if(!this["_"+j]){if(b.ignoreUnknown)return p("["+j+"]");throw new Error('Unknown object type "'+j+'"')}this["_"+j](l)},_array:function(l,B){B=B!==void 0?B:b.unorderedArrays!==!1;var E=this;if(p("array:"+l.length+":"),!B||l.length<=1)return l.forEach(function(M){return E.dispatch(M)});var j=[],B=l.map(function(M){var k=new R,q=d.slice();return _(b,k,q).dispatch(M),j=j.concat(q.slice(d.length)),k.read().toString()});return d=d.concat(j),B.sort(),this._array(B,!1)},_date:function(l){return p("date:"+l.toJSON())},_symbol:function(l){return p("symbol:"+l.toString())},_error:function(l){return p("error:"+l.toString())},_boolean:function(l){return p("bool:"+l.toString())},_string:function(l){p("string:"+l.length+":"),p(l.toString())},_function:function(l){p("fn:"),x(l)?this.dispatch("[native]"):this.dispatch(l.toString()),b.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(l.name)),b.respectFunctionProperties&&this._object(l)},_number:function(l){return p("number:"+l.toString())},_xml:function(l){return p("xml:"+l.toString())},_null:function(){return p("Null")},_undefined:function(){return p("Undefined")},_regexp:function(l){return p("regex:"+l.toString())},_uint8array:function(l){return p("uint8array:"),this.dispatch(Array.prototype.slice.call(l))},_uint8clampedarray:function(l){return p("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(l))},_int8array:function(l){return p("int8array:"),this.dispatch(Array.prototype.slice.call(l))},_uint16array:function(l){return p("uint16array:"),this.dispatch(Array.prototype.slice.call(l))},_int16array:function(l){return p("int16array:"),this.dispatch(Array.prototype.slice.call(l))},_uint32array:function(l){return p("uint32array:"),this.dispatch(Array.prototype.slice.call(l))},_int32array:function(l){return p("int32array:"),this.dispatch(Array.prototype.slice.call(l))},_float32array:function(l){return p("float32array:"),this.dispatch(Array.prototype.slice.call(l))},_float64array:function(l){return p("float64array:"),this.dispatch(Array.prototype.slice.call(l))},_arraybuffer:function(l){return p("arraybuffer:"),this.dispatch(new Uint8Array(l))},_url:function(l){return p("url:"+l.toString())},_map:function(l){return p("map:"),l=Array.from(l),this._array(l,b.unorderedSets!==!1)},_set:function(l){return p("set:"),l=Array.from(l),this._array(l,b.unorderedSets!==!1)},_file:function(l){return p("file:"),this.dispatch([l.name,l.size,l.type,l.lastModfied])},_blob:function(){if(b.ignoreUnknown)return p("[blob]");throw Error(`Hashing Blob objects is currently not supported
|
|
2
2
|
(see https://github.com/puleos/object-hash/issues/26)
|
|
3
3
|
Use "options.replacer" or "options.ignoreUnknown"
|
|
4
|
-
`)},_domwindow:function(){return
|
|
5
|
-
list should be an Array.`),c.length===0)return new w(0);if(c.length===1)return c[0];if(typeof f!="number")for(P=f=0;P<c.length;P++)f+=c[P].length;for(var g=new w(f),A=0,P=0;P<c.length;P++){var T=c[P];T.copy(g,A),A+=T.length}return g},w.prototype.write=function(c,f,g,A){isFinite(f)?isFinite(g)||(A=g,g=void 0):(Y=A,A=f,f=g,g=Y),f=Number(f)||0;var P,T,N,W,Y=this.length-f;switch((!g||Y<(g=Number(g)))&&(g=Y),A=String(A||"utf8").toLowerCase()){case"hex":P=function(ye,ie,re,X){re=Number(re)||0;var G=ye.length-re;(!X||G<(X=Number(X)))&&(X=G),R((G=ie.length)%2==0,"Invalid hex string"),G/2<X&&(X=G/2);for(var We=0;We<X;We++){var Gi=parseInt(ie.substr(2*We,2),16);R(!isNaN(Gi),"Invalid hex string"),ye[re+We]=Gi}return w._charsWritten=2*We,We}(this,c,f,g);break;case"utf8":case"utf-8":T=this,N=f,W=g,P=w._charsWritten=Et(_e(c),T,N,W);break;case"ascii":case"binary":P=x(this,c,f,g);break;case"base64":T=this,N=f,W=g,P=w._charsWritten=Et(Wi(c),T,N,W);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":P=I(this,c,f,g);break;default:throw new Error("Unknown encoding")}return P},w.prototype.toString=function(c,f,g){var A,P,T,N,W=this;if(c=String(c||"utf8").toLowerCase(),f=Number(f)||0,(g=g!==void 0?Number(g):W.length)===f)return"";switch(c){case"hex":A=function(Y,ye,ie){var re=Y.length;(!ye||ye<0)&&(ye=0),(!ie||ie<0||re<ie)&&(ie=re);for(var X="",G=ye;G<ie;G++)X+=z(Y[G]);return X}(W,f,g);break;case"utf8":case"utf-8":A=function(Y,ye,ie){var re="",X="";ie=Math.min(Y.length,ie);for(var G=ye;G<ie;G++)Y[G]<=127?(re+=Qi(X)+String.fromCharCode(Y[G]),X=""):X+="%"+Y[G].toString(16);return re+Qi(X)}(W,f,g);break;case"ascii":case"binary":A=S(W,f,g);break;case"base64":P=W,N=g,A=(T=f)===0&&N===P.length?y.fromByteArray(P):y.fromByteArray(P.slice(T,N));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":A=function(Y,ye,ie){for(var re=Y.slice(ye,ie),X="",G=0;G<re.length;G+=2)X+=String.fromCharCode(re[G]+256*re[G+1]);return X}(W,f,g);break;default:throw new Error("Unknown encoding")}return A},w.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},w.prototype.copy=function(c,f,g,A){if(f=f||0,(A=A||A===0?A:this.length)!==(g=g||0)&&c.length!==0&&this.length!==0){R(g<=A,"sourceEnd < sourceStart"),R(0<=f&&f<c.length,"targetStart out of bounds"),R(0<=g&&g<this.length,"sourceStart out of bounds"),R(0<=A&&A<=this.length,"sourceEnd out of bounds"),A>this.length&&(A=this.length);var P=(A=c.length-f<A-g?c.length-f+g:A)-g;if(P<100||!w._useTypedArrays)for(var T=0;T<P;T++)c[T+f]=this[T+g];else c._set(this.subarray(g,g+P),f)}},w.prototype.slice=function(c,f){var g=this.length;if(c=q(c,g,0),f=q(f,g,g),w._useTypedArrays)return w._augment(this.subarray(c,f));for(var A=f-c,P=new w(A,void 0,!0),T=0;T<A;T++)P[T]=this[T+c];return P},w.prototype.get=function(c){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(c)},w.prototype.set=function(c,f){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(c,f)},w.prototype.readUInt8=function(c,f){if(f||(R(c!=null,"missing offset"),R(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return this[c]},w.prototype.readUInt16LE=function(c,f){return D(this,c,!0,f)},w.prototype.readUInt16BE=function(c,f){return D(this,c,!1,f)},w.prototype.readUInt32LE=function(c,f){return F(this,c,!0,f)},w.prototype.readUInt32BE=function(c,f){return F(this,c,!1,f)},w.prototype.readInt8=function(c,f){if(f||(R(c!=null,"missing offset"),R(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return 128&this[c]?-1*(255-this[c]+1):this[c]},w.prototype.readInt16LE=function(c,f){return b(this,c,!0,f)},w.prototype.readInt16BE=function(c,f){return b(this,c,!1,f)},w.prototype.readInt32LE=function(c,f){return _(this,c,!0,f)},w.prototype.readInt32BE=function(c,f){return _(this,c,!1,f)},w.prototype.readFloatLE=function(c,f){return u(this,c,!0,f)},w.prototype.readFloatBE=function(c,f){return u(this,c,!1,f)},w.prototype.readDoubleLE=function(c,f){return h(this,c,!0,f)},w.prototype.readDoubleBE=function(c,f){return h(this,c,!1,f)},w.prototype.writeUInt8=function(c,f,g){g||(R(c!=null,"missing value"),R(f!=null,"missing offset"),R(f<this.length,"trying to write beyond buffer length"),zn(c,255)),f>=this.length||(this[f]=c)},w.prototype.writeUInt16LE=function(c,f,g){d(this,c,f,!0,g)},w.prototype.writeUInt16BE=function(c,f,g){d(this,c,f,!1,g)},w.prototype.writeUInt32LE=function(c,f,g){O(this,c,f,!0,g)},w.prototype.writeUInt32BE=function(c,f,g){O(this,c,f,!1,g)},w.prototype.writeInt8=function(c,f,g){g||(R(c!=null,"missing value"),R(f!=null,"missing offset"),R(f<this.length,"Trying to write beyond buffer length"),qn(c,127,-128)),f>=this.length||(0<=c?this.writeUInt8(c,f,g):this.writeUInt8(255+c+1,f,g))},w.prototype.writeInt16LE=function(c,f,g){E(this,c,f,!0,g)},w.prototype.writeInt16BE=function(c,f,g){E(this,c,f,!1,g)},w.prototype.writeInt32LE=function(c,f,g){B(this,c,f,!0,g)},w.prototype.writeInt32BE=function(c,f,g){B(this,c,f,!1,g)},w.prototype.writeFloatLE=function(c,f,g){M(this,c,f,!0,g)},w.prototype.writeFloatBE=function(c,f,g){M(this,c,f,!1,g)},w.prototype.writeDoubleLE=function(c,f,g){j(this,c,f,!0,g)},w.prototype.writeDoubleBE=function(c,f,g){j(this,c,f,!1,g)},w.prototype.fill=function(c,f,g){if(f=f||0,g=g||this.length,R(typeof(c=typeof(c=c||0)=="string"?c.charCodeAt(0):c)=="number"&&!isNaN(c),"value is not a number"),R(f<=g,"end < start"),g!==f&&this.length!==0){R(0<=f&&f<this.length,"start out of bounds"),R(0<=g&&g<=this.length,"end out of bounds");for(var A=f;A<g;A++)this[A]=c}},w.prototype.inspect=function(){for(var c=[],f=this.length,g=0;g<f;g++)if(c[g]=z(this[g]),g===e.INSPECT_MAX_BYTES){c[g+1]="...";break}return"<Buffer "+c.join(" ")+">"},w.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(w._useTypedArrays)return new w(this).buffer;for(var c=new Uint8Array(this.length),f=0,g=c.length;f<g;f+=1)c[f]=this[f];return c.buffer};var k=w.prototype;function q(c,f,g){return typeof c!="number"?g:f<=(c=~~c)?f:0<=c||0<=(c+=f)?c:0}function te(c){return(c=~~Math.ceil(+c))<0?0:c}function H(c){return(Array.isArray||function(f){return Object.prototype.toString.call(f)==="[object Array]"})(c)}function z(c){return c<16?"0"+c.toString(16):c.toString(16)}function _e(c){for(var f=[],g=0;g<c.length;g++){var A=c.charCodeAt(g);if(A<=127)f.push(c.charCodeAt(g));else for(var P=g,T=(55296<=A&&A<=57343&&g++,encodeURIComponent(c.slice(P,g+1)).substr(1).split("%")),N=0;N<T.length;N++)f.push(parseInt(T[N],16))}return f}function Wi(c){return y.toByteArray(c)}function Et(c,f,g,A){for(var P=0;P<A&&!(P+g>=f.length||P>=c.length);P++)f[P+g]=c[P];return P}function Qi(c){try{return decodeURIComponent(c)}catch{return String.fromCharCode(65533)}}function zn(c,f){R(typeof c=="number","cannot write a non-number as a number"),R(0<=c,"specified a negative value for writing an unsigned value"),R(c<=f,"value is larger than maximum value for type"),R(Math.floor(c)===c,"value has a fractional component")}function qn(c,f,g){R(typeof c=="number","cannot write a non-number as a number"),R(c<=f,"value larger than maximum allowed value"),R(g<=c,"value smaller than minimum allowed value"),R(Math.floor(c)===c,"value has a fractional component")}function Ji(c,f,g){R(typeof c=="number","cannot write a non-number as a number"),R(c<=f,"value larger than maximum allowed value"),R(g<=c,"value smaller than minimum allowed value")}function R(c,f){if(!c)throw new Error(f||"Failed assertion")}w._augment=function(c){return c._isBuffer=!0,c._get=c.get,c._set=c.set,c.get=k.get,c.set=k.set,c.write=k.write,c.toString=k.toString,c.toLocaleString=k.toString,c.toJSON=k.toJSON,c.copy=k.copy,c.slice=k.slice,c.readUInt8=k.readUInt8,c.readUInt16LE=k.readUInt16LE,c.readUInt16BE=k.readUInt16BE,c.readUInt32LE=k.readUInt32LE,c.readUInt32BE=k.readUInt32BE,c.readInt8=k.readInt8,c.readInt16LE=k.readInt16LE,c.readInt16BE=k.readInt16BE,c.readInt32LE=k.readInt32LE,c.readInt32BE=k.readInt32BE,c.readFloatLE=k.readFloatLE,c.readFloatBE=k.readFloatBE,c.readDoubleLE=k.readDoubleLE,c.readDoubleBE=k.readDoubleBE,c.writeUInt8=k.writeUInt8,c.writeUInt16LE=k.writeUInt16LE,c.writeUInt16BE=k.writeUInt16BE,c.writeUInt32LE=k.writeUInt32LE,c.writeUInt32BE=k.writeUInt32BE,c.writeInt8=k.writeInt8,c.writeInt16LE=k.writeInt16LE,c.writeInt16BE=k.writeInt16BE,c.writeInt32LE=k.writeInt32LE,c.writeInt32BE=k.writeInt32BE,c.writeFloatLE=k.writeFloatLE,c.writeFloatBE=k.writeFloatBE,c.writeDoubleLE=k.writeDoubleLE,c.writeDoubleBE=k.writeDoubleBE,c.fill=k.fill,c.inspect=k.inspect,c.toArrayBuffer=k.toArrayBuffer,c}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(i,t,e){(function(n,r,y,s,a,p,l,m,v){var y=i("buffer").Buffer,C=4,w=new y(C);w.fill(0),t.exports={hash:function(x,I,S,D){for(var F=I(function(d,O){d.length%C!=0&&(E=d.length+(C-d.length%C),d=y.concat([d,w],E));for(var E,B=[],M=O?d.readInt32BE:d.readInt32LE,j=0;j<d.length;j+=C)B.push(M.call(d,j));return B}(x=y.isBuffer(x)?x:new y(x),D),8*x.length),I=D,b=new y(S),_=I?b.writeInt32BE:b.writeInt32LE,u=0;u<F.length;u++)_.call(b,F[u],4*u,!0);return b}}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(i,t,e){(function(n,r,y,s,a,p,l,m,v){var y=i("buffer").Buffer,C=i("./sha"),w=i("./sha256"),x=i("./rng"),I={sha1:C,sha256:w,md5:i("./md5")},S=64,D=new y(S);function F(d,O){var E=I[d=d||"sha1"],B=[];return E||b("algorithm:",d,"is not yet supported"),{update:function(M){return y.isBuffer(M)||(M=new y(M)),B.push(M),M.length,this},digest:function(M){var j=y.concat(B),j=O?function(k,q,te){y.isBuffer(q)||(q=new y(q)),y.isBuffer(te)||(te=new y(te)),q.length>S?q=k(q):q.length<S&&(q=y.concat([q,D],S));for(var H=new y(S),z=new y(S),_e=0;_e<S;_e++)H[_e]=54^q[_e],z[_e]=92^q[_e];return te=k(y.concat([H,te])),k(y.concat([z,te]))}(E,O,j):E(j);return B=null,M?j.toString(M):j}}}function b(){var d=[].slice.call(arguments).join(" ");throw new Error([d,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
|
|
6
|
-
`))}D.fill(0),e.createHash=function(d){return F(d)},e.createHmac=F,e.randomBytes=function(d,O){if(!O||!O.call)return new y(x(d));try{O.call(this,void 0,new y(x(d)))}catch(E){O(E)}};var _,u=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],h=function(d){e[d]=function(){b("sorry,",d,"is not implemented yet")}};for(_ in u)h(u[_],_)}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(i,t,e){(function(n,r,o,s,a,p,l,m,v){var y=i("./helpers");function C(b,_){b[_>>5]|=128<<_%32,b[14+(_+64>>>9<<4)]=_;for(var u=1732584193,h=-271733879,d=-1732584194,O=271733878,E=0;E<b.length;E+=16){var B=u,M=h,j=d,k=O,u=x(u,h,d,O,b[E+0],7,-680876936),O=x(O,u,h,d,b[E+1],12,-389564586),d=x(d,O,u,h,b[E+2],17,606105819),h=x(h,d,O,u,b[E+3],22,-1044525330);u=x(u,h,d,O,b[E+4],7,-176418897),O=x(O,u,h,d,b[E+5],12,1200080426),d=x(d,O,u,h,b[E+6],17,-1473231341),h=x(h,d,O,u,b[E+7],22,-45705983),u=x(u,h,d,O,b[E+8],7,1770035416),O=x(O,u,h,d,b[E+9],12,-1958414417),d=x(d,O,u,h,b[E+10],17,-42063),h=x(h,d,O,u,b[E+11],22,-1990404162),u=x(u,h,d,O,b[E+12],7,1804603682),O=x(O,u,h,d,b[E+13],12,-40341101),d=x(d,O,u,h,b[E+14],17,-1502002290),u=I(u,h=x(h,d,O,u,b[E+15],22,1236535329),d,O,b[E+1],5,-165796510),O=I(O,u,h,d,b[E+6],9,-1069501632),d=I(d,O,u,h,b[E+11],14,643717713),h=I(h,d,O,u,b[E+0],20,-373897302),u=I(u,h,d,O,b[E+5],5,-701558691),O=I(O,u,h,d,b[E+10],9,38016083),d=I(d,O,u,h,b[E+15],14,-660478335),h=I(h,d,O,u,b[E+4],20,-405537848),u=I(u,h,d,O,b[E+9],5,568446438),O=I(O,u,h,d,b[E+14],9,-1019803690),d=I(d,O,u,h,b[E+3],14,-187363961),h=I(h,d,O,u,b[E+8],20,1163531501),u=I(u,h,d,O,b[E+13],5,-1444681467),O=I(O,u,h,d,b[E+2],9,-51403784),d=I(d,O,u,h,b[E+7],14,1735328473),u=S(u,h=I(h,d,O,u,b[E+12],20,-1926607734),d,O,b[E+5],4,-378558),O=S(O,u,h,d,b[E+8],11,-2022574463),d=S(d,O,u,h,b[E+11],16,1839030562),h=S(h,d,O,u,b[E+14],23,-35309556),u=S(u,h,d,O,b[E+1],4,-1530992060),O=S(O,u,h,d,b[E+4],11,1272893353),d=S(d,O,u,h,b[E+7],16,-155497632),h=S(h,d,O,u,b[E+10],23,-1094730640),u=S(u,h,d,O,b[E+13],4,681279174),O=S(O,u,h,d,b[E+0],11,-358537222),d=S(d,O,u,h,b[E+3],16,-722521979),h=S(h,d,O,u,b[E+6],23,76029189),u=S(u,h,d,O,b[E+9],4,-640364487),O=S(O,u,h,d,b[E+12],11,-421815835),d=S(d,O,u,h,b[E+15],16,530742520),u=D(u,h=S(h,d,O,u,b[E+2],23,-995338651),d,O,b[E+0],6,-198630844),O=D(O,u,h,d,b[E+7],10,1126891415),d=D(d,O,u,h,b[E+14],15,-1416354905),h=D(h,d,O,u,b[E+5],21,-57434055),u=D(u,h,d,O,b[E+12],6,1700485571),O=D(O,u,h,d,b[E+3],10,-1894986606),d=D(d,O,u,h,b[E+10],15,-1051523),h=D(h,d,O,u,b[E+1],21,-2054922799),u=D(u,h,d,O,b[E+8],6,1873313359),O=D(O,u,h,d,b[E+15],10,-30611744),d=D(d,O,u,h,b[E+6],15,-1560198380),h=D(h,d,O,u,b[E+13],21,1309151649),u=D(u,h,d,O,b[E+4],6,-145523070),O=D(O,u,h,d,b[E+11],10,-1120210379),d=D(d,O,u,h,b[E+2],15,718787259),h=D(h,d,O,u,b[E+9],21,-343485551),u=F(u,B),h=F(h,M),d=F(d,j),O=F(O,k)}return Array(u,h,d,O)}function w(b,_,u,h,d,O){return F((_=F(F(_,b),F(h,O)))<<d|_>>>32-d,u)}function x(b,_,u,h,d,O,E){return w(_&u|~_&h,b,_,d,O,E)}function I(b,_,u,h,d,O,E){return w(_&h|u&~h,b,_,d,O,E)}function S(b,_,u,h,d,O,E){return w(_^u^h,b,_,d,O,E)}function D(b,_,u,h,d,O,E){return w(u^(_|~h),b,_,d,O,E)}function F(b,_){var u=(65535&b)+(65535&_);return(b>>16)+(_>>16)+(u>>16)<<16|65535&u}t.exports=function(b){return y.hash(b,C,16)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(i,t,e){(function(n,r,o,s,a,p,l,m,v){var y;t.exports=y||function(C){for(var w,x=new Array(C),I=0;I<C;I++)!(3&I)&&(w=4294967296*Math.random()),x[I]=w>>>((3&I)<<3)&255;return x}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(i,t,e){(function(n,r,o,s,a,p,l,m,v){var y=i("./helpers");function C(I,S){I[S>>5]|=128<<24-S%32,I[15+(S+64>>9<<4)]=S;for(var D,F,b,_=Array(80),u=1732584193,h=-271733879,d=-1732584194,O=271733878,E=-1009589776,B=0;B<I.length;B+=16){for(var M=u,j=h,k=d,q=O,te=E,H=0;H<80;H++){_[H]=H<16?I[B+H]:x(_[H-3]^_[H-8]^_[H-14]^_[H-16],1);var z=w(w(x(u,5),(z=h,F=d,b=O,(D=H)<20?z&F|~z&b:!(D<40)&&D<60?z&F|z&b|F&b:z^F^b)),w(w(E,_[H]),(D=H)<20?1518500249:D<40?1859775393:D<60?-1894007588:-899497514)),E=O,O=d,d=x(h,30),h=u,u=z}u=w(u,M),h=w(h,j),d=w(d,k),O=w(O,q),E=w(E,te)}return Array(u,h,d,O,E)}function w(I,S){var D=(65535&I)+(65535&S);return(I>>16)+(S>>16)+(D>>16)<<16|65535&D}function x(I,S){return I<<S|I>>>32-S}t.exports=function(I){return y.hash(I,C,20,!0)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(i,t,e){(function(n,r,o,s,a,p,l,m,v){function y(S,D){var F=(65535&S)+(65535&D);return(S>>16)+(D>>16)+(F>>16)<<16|65535&F}function C(S,D){var F,b=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),_=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),u=new Array(64);S[D>>5]|=128<<24-D%32,S[15+(D+64>>9<<4)]=D;for(var h,d,O=0;O<S.length;O+=16){for(var E=_[0],B=_[1],M=_[2],j=_[3],k=_[4],q=_[5],te=_[6],H=_[7],z=0;z<64;z++)u[z]=z<16?S[z+O]:y(y(y((d=u[z-2],x(d,17)^x(d,19)^I(d,10)),u[z-7]),(d=u[z-15],x(d,7)^x(d,18)^I(d,3))),u[z-16]),F=y(y(y(y(H,x(d=k,6)^x(d,11)^x(d,25)),k&q^~k&te),b[z]),u[z]),h=y(x(h=E,2)^x(h,13)^x(h,22),E&B^E&M^B&M),H=te,te=q,q=k,k=y(j,F),j=M,M=B,B=E,E=y(F,h);_[0]=y(E,_[0]),_[1]=y(B,_[1]),_[2]=y(M,_[2]),_[3]=y(j,_[3]),_[4]=y(k,_[4]),_[5]=y(q,_[5]),_[6]=y(te,_[6]),_[7]=y(H,_[7])}return _}var w=i("./helpers"),x=function(S,D){return S>>>D|S<<32-D},I=function(S,D){return S>>>D};t.exports=function(S){return w.hash(S,C,32,!0)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(i,t,e){(function(n,r,o,s,a,p,l,m,v){e.read=function(y,C,w,x,O){var S,D,F=8*O-x-1,b=(1<<F)-1,_=b>>1,u=-7,h=w?O-1:0,d=w?-1:1,O=y[C+h];for(h+=d,S=O&(1<<-u)-1,O>>=-u,u+=F;0<u;S=256*S+y[C+h],h+=d,u-=8);for(D=S&(1<<-u)-1,S>>=-u,u+=x;0<u;D=256*D+y[C+h],h+=d,u-=8);if(S===0)S=1-_;else{if(S===b)return D?NaN:1/0*(O?-1:1);D+=Math.pow(2,x),S-=_}return(O?-1:1)*D*Math.pow(2,S-x)},e.write=function(y,C,w,x,I,E){var D,F,b=8*E-I-1,_=(1<<b)-1,u=_>>1,h=I===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=x?0:E-1,O=x?1:-1,E=C<0||C===0&&1/C<0?1:0;for(C=Math.abs(C),isNaN(C)||C===1/0?(F=isNaN(C)?1:0,D=_):(D=Math.floor(Math.log(C)/Math.LN2),C*(x=Math.pow(2,-D))<1&&(D--,x*=2),2<=(C+=1<=D+u?h/x:h*Math.pow(2,1-u))*x&&(D++,x/=2),_<=D+u?(F=0,D=_):1<=D+u?(F=(C*x-1)*Math.pow(2,I),D+=u):(F=C*Math.pow(2,u-1)*Math.pow(2,I),D=0));8<=I;y[w+d]=255&F,d+=O,F/=256,I-=8);for(D=D<<I|F,b+=I;0<b;y[w+d]=255&D,d+=O,D/=256,b-=8);y[w+d-O]|=128*E}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(i,t,e){(function(n,r,o,s,a,p,l,m,v){var y,C,w;function x(){}(n=t.exports={}).nextTick=(C=typeof window<"u"&&window.setImmediate,w=typeof window<"u"&&window.postMessage&&window.addEventListener,C?function(I){return window.setImmediate(I)}:w?(y=[],window.addEventListener("message",function(I){var S=I.source;S!==window&&S!==null||I.data!=="process-tick"||(I.stopPropagation(),0<y.length&&y.shift()())},!0),function(I){y.push(I),window.postMessage("process-tick","*")}):function(I){setTimeout(I,0)}),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.on=x,n.addListener=x,n.once=x,n.off=x,n.removeListener=x,n.removeAllListeners=x,n.emit=x,n.binding=function(I){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(I){throw new Error("process.chdir is not supported")}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1)})});var ze={};Yi(ze,{__addDisposableResource:()=>So,__assign:()=>bn,__asyncDelegator:()=>po,__asyncGenerator:()=>fo,__asyncValues:()=>ho,__await:()=>nt,__awaiter:()=>oo,__classPrivateFieldGet:()=>bo,__classPrivateFieldIn:()=>vo,__classPrivateFieldSet:()=>wo,__createBinding:()=>vn,__decorate:()=>no,__disposeResources:()=>xo,__esDecorate:()=>ia,__exportStar:()=>ao,__extends:()=>eo,__generator:()=>so,__importDefault:()=>yo,__importStar:()=>go,__makeTemplateObject:()=>mo,__metadata:()=>ro,__param:()=>io,__propKey:()=>oa,__read:()=>Pi,__rest:()=>to,__runInitializers:()=>ra,__setFunctionName:()=>sa,__spread:()=>co,__spreadArray:()=>uo,__spreadArrays:()=>lo,__values:()=>wn,default:()=>la});function eo(i,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");Ci(i,t);function e(){this.constructor=i}i.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function to(i,t){var e={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,n=Object.getOwnPropertySymbols(i);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(i,n[r])&&(e[n[r]]=i[n[r]]);return e}function no(i,t,e,n){var r=arguments.length,o=r<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(i,t,e,n);else for(var a=i.length-1;a>=0;a--)(s=i[a])&&(o=(r<3?s(o):r>3?s(t,e,o):s(t,e))||o);return r>3&&o&&Object.defineProperty(t,e,o),o}function io(i,t){return function(e,n){t(e,n,i)}}function ia(i,t,e,n,r,o){function s(S){if(S!==void 0&&typeof S!="function")throw new TypeError("Function expected");return S}for(var a=n.kind,p=a==="getter"?"get":a==="setter"?"set":"value",l=!t&&i?n.static?i:i.prototype:null,m=t||(l?Object.getOwnPropertyDescriptor(l,n.name):{}),v,y=!1,C=e.length-1;C>=0;C--){var w={};for(var x in n)w[x]=x==="access"?{}:n[x];for(var x in n.access)w.access[x]=n.access[x];w.addInitializer=function(S){if(y)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(S||null))};var I=(0,e[C])(a==="accessor"?{get:m.get,set:m.set}:m[p],w);if(a==="accessor"){if(I===void 0)continue;if(I===null||typeof I!="object")throw new TypeError("Object expected");(v=s(I.get))&&(m.get=v),(v=s(I.set))&&(m.set=v),(v=s(I.init))&&r.unshift(v)}else(v=s(I))&&(a==="field"?r.unshift(v):m[p]=v)}l&&Object.defineProperty(l,n.name,m),y=!0}function ra(i,t,e){for(var n=arguments.length>2,r=0;r<t.length;r++)e=n?t[r].call(i,e):t[r].call(i);return n?e:void 0}function oa(i){return typeof i=="symbol"?i:"".concat(i)}function sa(i,t,e){return typeof t=="symbol"&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(i,"name",{configurable:!0,value:e?"".concat(e," ",t):t})}function ro(i,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(i,t)}function oo(i,t,e,n){function r(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function a(m){try{l(n.next(m))}catch(v){s(v)}}function p(m){try{l(n.throw(m))}catch(v){s(v)}}function l(m){m.done?o(m.value):r(m.value).then(a,p)}l((n=n.apply(i,t||[])).next())})}function so(i,t){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,r,o,s;return s={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(l){return function(m){return p([l,m])}}function p(l){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,l[0]&&(e=0)),e;)try{if(n=1,r&&(o=l[0]&2?r.return:l[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,l[1])).done)return o;switch(r=0,o&&(l=[l[0]&2,o.value]),l[0]){case 0:case 1:o=l;break;case 4:return e.label++,{value:l[1],done:!1};case 5:e.label++,r=l[1],l=[0];continue;case 7:l=e.ops.pop(),e.trys.pop();continue;default:if(o=e.trys,!(o=o.length>0&&o[o.length-1])&&(l[0]===6||l[0]===2)){e=0;continue}if(l[0]===3&&(!o||l[1]>o[0]&&l[1]<o[3])){e.label=l[1];break}if(l[0]===6&&e.label<o[1]){e.label=o[1],o=l;break}if(o&&e.label<o[2]){e.label=o[2],e.ops.push(l);break}o[2]&&e.ops.pop(),e.trys.pop();continue}l=t.call(i,e)}catch(m){l=[6,m],r=0}finally{n=o=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function ao(i,t){for(var e in i)e!=="default"&&!Object.prototype.hasOwnProperty.call(t,e)&&vn(t,i,e)}function wn(i){var t=typeof Symbol=="function"&&Symbol.iterator,e=t&&i[t],n=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Pi(i,t){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var n=e.call(i),r,o=[],s;try{for(;(t===void 0||t-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(e=n.return)&&e.call(n)}finally{if(s)throw s.error}}return o}function co(){for(var i=[],t=0;t<arguments.length;t++)i=i.concat(Pi(arguments[t]));return i}function lo(){for(var i=0,t=0,e=arguments.length;t<e;t++)i+=arguments[t].length;for(var n=Array(i),r=0,t=0;t<e;t++)for(var o=arguments[t],s=0,a=o.length;s<a;s++,r++)n[r]=o[s];return n}function uo(i,t,e){if(e||arguments.length===2)for(var n=0,r=t.length,o;n<r;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return i.concat(o||Array.prototype.slice.call(t))}function nt(i){return this instanceof nt?(this.v=i,this):new nt(i)}function fo(i,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=e.apply(i,t||[]),r,o=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(y){n[y]&&(r[y]=function(C){return new Promise(function(w,x){o.push([y,C,w,x])>1||a(y,C)})})}function a(y,C){try{p(n[y](C))}catch(w){v(o[0][3],w)}}function p(y){y.value instanceof nt?Promise.resolve(y.value.v).then(l,m):v(o[0][2],y)}function l(y){a("next",y)}function m(y){a("throw",y)}function v(y,C){y(C),o.shift(),o.length&&a(o[0][0],o[0][1])}}function po(i){var t,e;return t={},n("next"),n("throw",function(r){throw r}),n("return"),t[Symbol.iterator]=function(){return this},t;function n(r,o){t[r]=i[r]?function(s){return(e=!e)?{value:nt(i[r](s)),done:!1}:o?o(s):s}:o}}function ho(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=i[Symbol.asyncIterator],e;return t?t.call(i):(i=typeof wn=="function"?wn(i):i[Symbol.iterator](),e={},n("next"),n("throw"),n("return"),e[Symbol.asyncIterator]=function(){return this},e);function n(o){e[o]=i[o]&&function(s){return new Promise(function(a,p){s=i[o](s),r(a,p,s.done,s.value)})}}function r(o,s,a,p){Promise.resolve(p).then(function(l){o({value:l,done:a})},s)}}function mo(i,t){return Object.defineProperty?Object.defineProperty(i,"raw",{value:t}):i.raw=t,i}function go(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)e!=="default"&&Object.prototype.hasOwnProperty.call(i,e)&&vn(t,i,e);return aa(t,i),t}function yo(i){return i&&i.__esModule?i:{default:i}}function bo(i,t,e,n){if(e==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?i!==t||!n:!t.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?n:e==="a"?n.call(i):n?n.value:t.get(i)}function wo(i,t,e,n,r){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?i!==t||!r:!t.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(i,e):r?r.value=e:t.set(i,e),e}function vo(i,t){if(t===null||typeof t!="object"&&typeof t!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof i=="function"?t===i:i.has(t)}function So(i,t,e){if(t!=null){if(typeof t!="object"&&typeof t!="function")throw new TypeError("Object expected.");var n;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose]}if(typeof n!="function")throw new TypeError("Object not disposable.");i.stack.push({value:t,dispose:n,async:e})}else e&&i.stack.push({async:!0});return t}function xo(i){function t(n){i.error=i.hasError?new ca(n,i.error,"An error was suppressed during disposal."):n,i.hasError=!0}function e(){for(;i.stack.length;){var n=i.stack.pop();try{var r=n.dispose&&n.dispose.call(n.value);if(n.async)return Promise.resolve(r).then(e,function(o){return t(o),e()})}catch(o){t(o)}}if(i.hasError)throw i.error}return e()}var Ci,bn,vn,aa,ca,la,qe=$o(()=>{Ci=function(i,t){return Ci=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])},Ci(i,t)};bn=function(){return bn=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++){e=arguments[n];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},bn.apply(this,arguments)};vn=Object.create?function(i,t,e,n){n===void 0&&(n=e);var r=Object.getOwnPropertyDescriptor(t,e);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(i,n,r)}:function(i,t,e,n){n===void 0&&(n=e),i[n]=t[e]};aa=Object.create?function(i,t){Object.defineProperty(i,"default",{enumerable:!0,value:t})}:function(i,t){i.default=t};ca=typeof SuppressedError=="function"?SuppressedError:function(i,t,e){var n=new Error(e);return n.name="SuppressedError",n.error=i,n.suppressed=t,n};la={__extends:eo,__assign:bn,__rest:to,__decorate:no,__param:io,__metadata:ro,__awaiter:oo,__generator:so,__createBinding:vn,__exportStar:ao,__values:wn,__read:Pi,__spread:co,__spreadArrays:lo,__spreadArray:uo,__await:nt,__asyncGenerator:fo,__asyncDelegator:po,__asyncValues:ho,__makeTemplateObject:mo,__importStar:go,__importDefault:yo,__classPrivateFieldGet:bo,__classPrivateFieldSet:wo,__classPrivateFieldIn:vo,__addDisposableResource:So,__disposeResources:xo}});var Io=oe(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0})});var Fi=oe(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.invokeEventHandlersAsync=De.invokeEventHandlers=De.eventHandlerSafeInvokeAsync=De.eventHandlerSafeInvoke=void 0;var Do=(qe(),Je(ze));function _o(i,t,e){try{return i(t,e),{succeeded:!0}}catch(n){return{error:n,succeeded:!1}}}De.eventHandlerSafeInvoke=_o;function Ai(i,t,e){return(0,Do.__awaiter)(this,void 0,void 0,function*(){try{return yield i(t,e),{succeeded:!0}}catch(n){return{error:n,succeeded:!1}}})}De.eventHandlerSafeInvokeAsync=Ai;function da(i,t,e,n){for(let r of i){let{succeeded:o,error:s}=_o(r,t,e);if(!o&&n?.swallowExceptions!==!0)throw s}}De.invokeEventHandlers=da;function ua(i,t,e,n){return(0,Do.__awaiter)(this,void 0,void 0,function*(){if(n?.parallelize===!1)for(let r of i){let{succeeded:o,error:s}=yield Ai(r,t,e);if(!o&&n?.swallowExceptions!==!0)throw s}else{let r=[];for(let o of i)r.push(Ai(o,t,e).then(({succeeded:s,error:a})=>{if(!s&&n?.swallowExceptions!==!0)throw a}));yield Promise.all(r)}})}De.invokeEventHandlersAsync=ua});var Po=oe(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.TypedEvent=void 0;var fa=(qe(),Je(ze)),Eo=Fi(),Co={swallowExceptions:!1,parallelize:!0},Ri=class{constructor(){this._handlers=[]}attach(t){this._handlers.push(t)}detach(t){this.tryRemoveHandler(t)}invoke(t,e,n=Co){(0,Eo.invokeEventHandlers)(this._handlers,t,e,n)}invokeAsync(t,e,n=Co){return(0,fa.__awaiter)(this,void 0,void 0,function*(){yield(0,Eo.invokeEventHandlersAsync)(this._handlers,t,e,n)})}tryRemoveHandler(t){let e=this._handlers.findIndex(n=>n===t);e>=0&&this._handlers.splice(e,1)}};Sn.TypedEvent=Ri});var ki=oe(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});var pa=(qe(),Je(ze));(0,pa.__exportStar)(Po(),Ti)});var Ao=oe(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.FinalizationRegistryMissingError=void 0;var Mi=class extends Error{};xn.FinalizationRegistryMissingError=Mi});var ji=oe(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.WeakHandlerHolder=void 0;var ha=Ao(),Bi=class{constructor(t){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(t)}catch(e){throw e.name==="FinalizationRegistry"?new ha.FinalizationRegistryMissingError("FinalizationRegistry is not defined. Weak Events cannot be used. Please consult 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry' for compatibility information"):e}}getWeakHandler(t,e){let n=new WeakRef(e);return this._finalizationRegistry.register(e,{eventSource:t,handlerRef:n},n),this._refs.push(n),n}releaseWeakHandler(t){let n=this._refs.find(r=>r?.deref()===t)||new WeakRef(t);return this._finalizationRegistry.unregister(n),n}unregisterRef(t){this._finalizationRegistry.unregister(t)}};On.WeakHandlerHolder=Bi});var Fo=oe(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.WeakEvent=void 0;var Li=(qe(),Je(ze)),ma=ki(),ga=ji(),Ni=Fi(),ya={swallowExceptions:!1,parallelize:!0},Ui=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new ma.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new ga.WeakHandlerHolder(t=>{this.onHandlerFinalizer(t)})}invoke(t,e,n){for(let r of this._handlers){let o=r?.deref();if(o){let{succeeded:s,error:a}=(0,Ni.eventHandlerSafeInvoke)(o,t,e);if(!s&&n?.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}}invokeAsync(t,e,n=ya){return(0,Li.__awaiter)(this,void 0,void 0,function*(){n?.parallelize===!1?yield this.sequentialInvokeAsync(t,e,n):yield this.parallelInvokeAsync(t,e,n)})}sequentialInvokeAsync(t,e,n){return(0,Li.__awaiter)(this,void 0,void 0,function*(){for(let r of this._handlers){let o=r?.deref();if(o){let{succeeded:s,error:a}=yield(0,Ni.eventHandlerSafeInvokeAsync)(o,t,e);if(!s&&n.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}})}parallelInvokeAsync(t,e,n){return(0,Li.__awaiter)(this,void 0,void 0,function*(){let r=[];for(let o of this._handlers){let s=o?.deref();s?r.push((0,Ni.eventHandlerSafeInvokeAsync)(s,t,e).then(({succeeded:a,error:p})=>{if(!a&&n.swallowExceptions!==!0)throw p})):this.releaseHandler(o)}yield Promise.all(r)})}attach(t){this._handlers.push(this._refHolder.getWeakHandler(this,t))}detach(t){let e=this._refHolder.releaseWeakHandler(t);this.tryRemoveHandlerRef(e)}onHandlerFinalizer(t){this.tryRemoveHandlerRef(t?.handlerRef),this._handlerFinalizedEvent.invokeAsync(this,t,{swallowExceptions:!0})}tryRemoveHandlerRef(t){let e=this._handlers.findIndex(n=>n===t);e>=0&&this._handlers.splice(e,1)}releaseHandler(t){this._refHolder.unregisterRef(t),this.tryRemoveHandlerRef(t)}};In.WeakEvent=Ui});var To=oe(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});var Ro=(qe(),Je(ze));(0,Ro.__exportStar)(ji(),Dn);(0,Ro.__exportStar)(Fo(),Dn)});var ko=oe(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});var Vi=(qe(),Je(ze));(0,Vi.__exportStar)(Io(),It);(0,Vi.__exportStar)(ki(),It);(0,Vi.__exportStar)(To(),It)});var Hi={};Yi(Hi,{Client:()=>He,ClientDescriptor:()=>$n,Entity:()=>ue,EntityFile:()=>de,MigrationPathError:()=>Ze,ServerSync:()=>rt,Storage:()=>He,StorageDescriptor:()=>$n,collection:()=>yi,createDefaultMigration:()=>bi,createMigration:()=>wi,migrate:()=>Wt,schema:()=>gt});var hr=Qe(at(),1),Mt=4,lt=36;function dr(i){return i.toString(lt).padStart(Mt,"0")}function Go(i){return i.toString().padStart(6,"0")}var Ft=class{constructor(){this.latest={time:Date.now(),counter:0,node:Yo()};this.zeroCounter=0;this.now=t=>(this.latest=fr(this.latest),this.get(t,this.latest));this.OLD_now=t=>(this.latest=fr(this.latest),Go(t)+Zo(this.latest));this.timerState=()=>this.latest;this.update=t=>{let e=t.slice(Mt);this.latest=Xo(this.latest,mr(e))};this.get=(t,e)=>dr(t)+ur(e);this.zero=t=>dr(t)+ur({time:0,counter:this.zeroCounter++,node:this.latest.node});this.getWallClockTime=Zn}},Rt=class extends Error{constructor(...e){super();this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(e).join(" ")}},Tt=class extends Error{constructor(){super();this.type="OverflowError",this.message="timestamp counter overflow"}},Gn=4,Yn=7,kt=60*1e3,ct=9;function Yo(){return hr.default.slug().padStart(Yn,"0").slice(0,Yn)}function ur(i){let t=new Date(i.time).getTime().toString(lt).padStart(ct,"0"),e=i.counter.toString(lt).padStart(Gn,"0"),n=i.node.padStart(Yn,"0");return`${t}${e}${n}`}function fr(i){let t=Date.now(),e=Math.max(i.time,t),n=i.time===e?i.counter+1:0;if(e-t>kt)throw new Rt(e,t,kt);if(n>65535)throw new Tt;return{time:e,counter:n,node:i.node}}function Xo(i,t){let e=Date.now(),n=Math.max(e,Math.max(i.time,t.time)),r=Math.max(i.counter,t.counter),o;if(i.time===n&&t.time===n?o=r+1:i.time===n?o=i.counter+1:t.time===n?o=t.counter+1:o=0,n-e>kt)throw new Rt(n,e,kt);if(o>65535)throw new Tt;return{time:n,counter:o,node:i.node}}function mr(i){let t=i.slice(0,ct),e=i.slice(ct,ct+Gn),n=i.slice(ct+Gn),r=parseInt(t,lt),o=parseInt(e,lt);if(isNaN(r)||isNaN(o))throw new Error("invalid clock format");return{time:r,counter:o,node:n}}function Zo(i){let t=new Date(i.time).toISOString(),e=i.counter.toString(16).toUpperCase().padStart(4,"0"),n=i.node.padStart(16,"0");return`${t}-${e}-${n}`}function pr(i){return parseInt(i.slice(0,Mt),36)}function Xn(i,t){return pr(i)-pr(t)}function Zn(i){return mr(i.slice(Mt)).time}function be(i){return i&&i["@@type"]==="file"}function Bt(i){return{"@@type":"file",id:i}}var jt,es=new Uint8Array(16);function ei(){if(!jt&&(jt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!jt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return jt(es)}var gr=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function ts(i){return typeof i=="string"&&gr.test(i)}var yr=ts;var ee=[];for(Lt=0;Lt<256;++Lt)ee.push((Lt+256).toString(16).substr(1));var Lt;function ns(i){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(ee[i[t+0]]+ee[i[t+1]]+ee[i[t+2]]+ee[i[t+3]]+"-"+ee[i[t+4]]+ee[i[t+5]]+"-"+ee[i[t+6]]+ee[i[t+7]]+"-"+ee[i[t+8]]+ee[i[t+9]]+"-"+ee[i[t+10]]+ee[i[t+11]]+ee[i[t+12]]+ee[i[t+13]]+ee[i[t+14]]+ee[i[t+15]]).toLowerCase();if(!yr(e))throw TypeError("Stringified UUID is invalid");return e}var br=ns;function is(i,t,e){i=i||{};var n=i.random||(i.rng||ei)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){e=e||0;for(var r=0;r<16;++r)t[e+r]=n[r];return t}return br(n)}var dt=is;function Q(i){return Se(i)||be(i)}function Ge(i,t){return i===t?!0:!(!Q(i)||!Q(t)||i["@@type"]!==t["@@type"]||i.id!==t.id)}var xr=Qe(Sr(),1);function rs(i,t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([e],[n])=>e<n?-1:e>n?1:0))}function ut(i){return JSON.stringify(i,rs)}function ae(i,t=!0){if(V(i)||Array.isArray(i)){let e=pe(i),n;if(Array.isArray(i))n=i.map(r=>ae(r,t));else{n={};for(let[r,o]of Object.entries(i))n[r]=ae(o,t)}return t&&e&&K(n,e),n}return i}function Fe(i){return(0,xr.default)(i)}function V(i){return i&&typeof i=="object"}function Or(i){for(var t=[],e=[i],n=0;e.length;){var r=e.pop();if(typeof r=="boolean")n+=4;else if(typeof r=="string")n+=r.length*2;else if(typeof r=="number")n+=8;else if(typeof r=="object"&&t.indexOf(r)===-1){t.push(r);for(var o in r)e.push(r[o])}}return n}function L(i,t="assertion failed"){if(!i)throw new Error(t)}function Nt(i=16){return dt().replace("-","").slice(0,i)}function Ir(i,t){for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1}function Dr(i,t){let e;return function(...n){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,n),t)}}var Me="__@@oid_do_not_use",Oe="@@id",os="/",pt=":",ni=new WeakMap;function ne(i){let t=pe(i);return L(!!t,`Object ${JSON.stringify(i)} does not have an OID assigned to it`),t}function pe(i){if(V(i))return ni.get(i)??i[Oe]??i[Me]}function K(i,t){return L(V(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),ii(i)&&Kt(i),ni.set(i,t),i}function ii(i){return!!pe(i)}function Kt(i){return ni.delete(i),i}function ri(i){return i===Oe||i===Me}function oi(i,t,e){if(ii(i))return ne(i);{let n=xe(t,e);return K(i,n),n}}function _r(i,t,e){if(ii(i)){let n=ne(i);if(Ee(n,t))return ne(i);{let r=xe(t,e);return K(i,r),r}}else{let n=xe(t,e);return K(i,n),n}}var ti={".":"˙","/":"&slash;",":":":"};function Er(i){return i.replace(/[/]/g,ti["/"]).replace(/[:]/g,ti[":"]).replace(/[.]/g,ti["."])}function Cr(i){return i.replace(/&slash;/g,"/").replace(/:/g,":").replace(/˙/g,".")}function Z(i,t,e){let n=Er(i)+os+Er(t);return e&&(n+=pt+e),n}function xe(i,t=ls){let{collection:e,id:n}=me(i);return Z(e,n,t())}function me(i){let[t,e]=i.split(pt),[n,r,...o]=t.split("/");o.length&&(r+="/"+o.join("/"));let s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:Cr(n),id:Cr(s),subId:e}}function Ye(i,t){let e=ne(i);if(Array.isArray(i)){let n;for(let r=0;r<i.length;r++)n=i[r],V(n)&&!Q(n)&&(_r(n,e,t),Ye(n,t))}else if(V(i)&&!Q(i))for(let n of Object.keys(i))V(i[n])&&!Q(i[n])&&(_r(i[n],e,t),Ye(i[n],t))}function ss(i){if(V(i))return i[Oe]||i[Me]}function as(i){return V(i)&&(delete i[Me],delete i[Oe]),i}function cs(i){let t=ss(i);t&&K(i,t)}function ft(i){if(cs(i),as(i),Array.isArray(i))for(let t=0;t<i.length;t++)ft(i[t]);else if(V(i))for(let t of Object.keys(i))ft(i[t])}function Ut(i){if(Kt(i),Array.isArray(i))for(let t=0;t<i.length;t++)Ut(i[t]);else if(V(i))for(let t of Object.keys(i))Ut(i[t])}function ls(){return dt().slice(0,8)}function he(i){return{"@@type":"ref",id:i}}function Vt(i,t=new Map){if(Array.isArray(i)){let e=ne(i),n=K([],e);for(let r=0;r<i.length;r++){let o=i[r];if(V(o)){if(Se(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(be(o)){n[r]=o;continue}else{let s=ne(o);n[r]=he(s),Vt(o,t)}}else n[r]=o}t.set(e,n)}else if(V(i)&&!Q(i)){let e=ne(i),n=K({},e);for(let r of Object.keys(i)){let o=i[r];if(V(o)){if(Se(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(be(o))n[r]=o;else{let s=ne(o);n[r]=he(s),Vt(o,t)}}else n[r]=o}t.set(e,n)}else Q(i);return t}function $(i){return i.split(".")[0].split(pt)[0]}function si(i){let t=$(i),e=xe(t,()=>"\uFFFF");return[`${t}${pt}`,e]}function ai(i){let t=$(i);return[`${t}.`,`${t}.\uFFFF`]}function Ee(i,t){return $(i)===$(t)}function ds(i){let{collection:t,id:e,subId:n}=me(i);return Z(t,e,n)}var us=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function fs(i){return i.replaceAll(us,t=>{let e=t.slice(1,t.length-1);return`"${ds(e)}"`})}function ci(i){return JSON.parse(fs(JSON.stringify(i)))}function Pr(i){return!i.includes(pt)}function Se(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function li(i){return V(i)&&!Q(i)}function ps(i,t){return i===t?!0:Q(i)&&Q(t)?Ge(i,t):!1}function ht(i,t,e,n,r=[],o={}){let s=ne(i);function a(p,l,m){if(!li(l))ps(l,m)||r.push({oid:s,timestamp:e(),data:{op:"set",name:p,value:l}});else{let v=pe(m),y=pe(l);y&&!Ee(s,y)?(l=ae(l,!1),y=xe(s,n),K(l,y)):o.mergeUnknownObjects?!y&&v?(K(l,v),y=v):y=oi(l,s,n):y=oi(l,s,n),L(!!y,"Error: no value OID was resolved during diff. This is a bug in Verdant."),L(Ee(s,y),`Error: value OID ${y} is not related to parent OID ${s}. This is a bug in Verdant.`),m===void 0||y!==v?(Re(l,y,e,n,r),r.push({oid:s,timestamp:e(),data:{op:"set",name:p,value:he(y)}}),v!==void 0&&r.push({oid:v,timestamp:e(),data:{op:"delete"}})):ht(m,l,e,n,r,o)}}if(Array.isArray(i)&&Array.isArray(t)){for(let l=0;l<t.length;l++){let m=t[l],v=i[l];a(l,m,v)}let p=i.length-t.length;if(p>0){for(let l=t.length;l<i.length;l++){let m=i[l],v=pe(m);v&&r.push({oid:v,timestamp:e(),data:{op:"delete"}})}r.push({oid:s,timestamp:e(),data:{op:"list-delete",index:t.length,count:p}})}}else{if(Array.isArray(i)||Array.isArray(t))throw new Error("Cannot diff an array with an object");if(li(i)&&li(t)){let p=new Set(Object.keys(i));for(let[l,m]of Object.entries(t)){if(m===void 0&&o.defaultUndefined||(p.delete(l),ri(l)))continue;let v=i[l];a(l,m,v)}if(!o.defaultUndefined)for(let l of p)ri(l)||r.push({oid:s,timestamp:e(),data:{op:"remove",name:l}})}}return r}function Re(i,t,e,n,r=[]){K(i,t),Ye(i,n);let o=Vt(i);for(let s of o.keys()){let a=o.get(s);r.push({oid:s,timestamp:e(),data:{op:"initialize",value:Kt(a)}})}return r}function mt(i){let t={};for(let e of i)e.oid in t?t[e.oid].push(e):t[e.oid]=[e];return t}function Fr(i){let t={};for(let e of i){let n=$(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Rr(i){let t={};for(let e of i){let n=$(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Be(i){return Array.isArray(i)?!0:(console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(i)}. This suggests your data is changing from a list to an object over time. (OID: ${pe(i)})`),!1)}function je(i,t,e){if(i==null&&t.op!=="initialize")return i;let n=i,r,o;function s(a){e&&Q(a)&&e.push(a)}switch(t.op){case"set":s(n[t.name]),n[t.name]=t.value;break;case"remove":s(n[t.name]),delete n[t.name];break;case"list-push":Be(i)&&i.push(t.value);break;case"list-delete":Be(i)&&(s(i[t.index]),i.splice(t.index,t.count));break;case"list-move-by-index":Be(i)&&(o=i.splice(t.from,1),i.splice(t.to,0,o[0]));break;case"list-remove":if(Be(i))do{let a=t.value;t.only==="last"?Se(a)?r=Ir(i,p=>p.id===a.id):r=i.lastIndexOf(a):Se(a)?r=i.findIndex(p=>p.id===a.id):r=i.indexOf(a),r!==-1&&(s(i[r]),i.splice(r,1))}while(!t.only&&r!==-1);break;case"list-add":Be(i)&&(i.some(p=>Se(p)&&Se(t.value)?p.id===t.value.id:p===t.value)||i.push(t.value));break;case"list-move-by-ref":Be(i)&&(r=i.findIndex(a=>Ge(a,t.value)),o=i.splice(r,1),i.splice(t.index,0,o[0]));break;case"list-insert":if(Be(i)){if(!t.value&&!t.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(t)}`);t.value?i.splice(t.index,0,t.value):i.splice(t.index,0,...t.values)}break;case"delete":Array.isArray(i)?i.forEach(s):V(i)&&Object.values(i||{}).forEach(s);return;case"initialize":return ae(t.value);case"touch":return i;default:throw new Error(`Unsupported patch operation: ${t.op}`)}return i}function $t(i,t,e=[]){if(Array.isArray(i))for(let n=0;n<i.length;n++){let r=i[n];i[n]=Ar(r,t,e),V(i[n])&&$t(i[n],t,e)}else if(!be(i)){if(V(i)){L(pe(i),`Object ${JSON.stringify(i)} must have an oid`);for(let n of Object.keys(i))i[n]=Ar(i[n],t,e),V(i[n])&&$t(i[n],t,e)}}return e}function Ar(i,t,e){if(Se(i)){e.push(i.id);let n=t.get(i.id);return L(!!n,`No value was found in object map for ${i.id}`),K(n,i.id)}else return i}var hs=i=>({type:"object",...i}),ms=i=>({type:"array",...i}),gs=i=>({type:"string",...i}),ys=i=>({type:"number",...i}),bs=i=>({type:"boolean",...i}),ws=i=>({type:"any",...i}),vs=i=>({type:"map",...i}),Ss=i=>({type:"file",...i}),Tr={object:hs,array:ms,string:gs,number:ys,boolean:bs,any:ws,map:vs,file:Ss};var Br=Qe(at(),1);function di(i){return i.equals!==void 0}function ui(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function xs(i){return!!i.match}function fi(i){return i.startsWith!==void 0}function kr(i){return!ui(i)&&!di(i)&&!xs(i)&&!fi(i)&&i.order}function we(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function Ce(i){return i?i.type==="map"||i.type==="array"?!0:i.type==="file"?!1:i.default!==void 0:!1}function hi(i){if(!(!i||!Ce(i)))return i.type==="file"?we(i)?null:void 0:i.type==="map"?{}:i.type==="array"?we(i)?null:[]:i.type==="object"?we(i)?null:void 0:typeof i.default=="function"?i.default():i.default}function Pe(i,t){for(let[e,n]of Object.entries(i.fields)){let r=mi(n);(r!==void 0&&t[e]===void 0||!we(n)&&t[e]===null)&&(t[e]=r),t[e]&&Le(t[e],n)}return t}function Le(i,t){if(i==null)return i;if(t.type==="object")for(let[e,n]of Object.entries(t.properties)){if(i[e]===void 0){let r=mi(n);r!==void 0&&(i[e]=r)}Le(i[e],n)}else if(t.type==="array")for(let e of i)Le(e,t.items);else if(t.type==="map")for(let[e,n]of Object.entries(i))e===Oe||e===Me||Le(n,t.values)}function mi(i){if(i.type==="string"||i.type==="number"||i.type==="boolean"||i.type==="any"){if(i.default&&typeof i.default=="function")return i.default();if(i.default!==void 0)return JSON.parse(JSON.stringify(i.default))}if(i.type==="array")return[];if(i.type==="map")return{};if(i.type!=="any"&&i.nullable)return null;if(i.type==="object"&&i.default){let t=typeof i.default=="function"?i.default():JSON.parse(JSON.stringify(i.default));for(let[e,n]of Object.entries(i.properties))t[e]===void 0&&(t[e]=mi(n));return t}}function gi(i,t){for(let[e,n]of Object.entries(t))e===Oe||e===Me||(i.fields[e]?pi(n,i.fields[e]):delete t[e]);return t}function pi(i,t){if(V(i)&&t.type==="object")for(let[e,n]of Object.entries(i))t.properties[e]?pi(n,t.properties[e]):delete i[e];else if(Array.isArray(i)&&t.type==="array")for(let e of i)pi(e,t.items)}function Mr(i,t){for(let[e,n]of Object.entries(t))if(e!==Oe){if(!i[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(n){let r=Te({field:i[e],value:n,fieldPath:[e]});if(r)return r}}}function Te({field:i,value:t,fieldPath:e=[],depth:n,requireDefaults:r}){if(!(n!==void 0&&n<=0)&&!(we(i)&&t===null)){if(t===null&&(r||!Ce(i)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${Ae(e)}`};if(i.type==="object"){if(!V(t))return{type:"invalid-type",fieldPath:e,message:`Expected object${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};for(let[o,s]of Object.entries(i.properties))o!==Oe&&t[o]&&Te({field:s,value:t[o],fieldPath:[...e,o],depth:n!==void 0?n-1:void 0});for(let o of Object.keys(t))if(!i.properties[o])return{type:"invalid-key",fieldPath:[...e,o],message:`Invalid unexpected field "${o}" on value ${Ae(e)}`}}else if(i.type==="array"){if(!Array.isArray(t))return t===null&&i.nullable?void 0:{type:"invalid-value",fieldPath:e,message:`Expected array${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};for(let o of t)Te({field:i.items,value:o,fieldPath:[...e,"[]"],depth:n!==void 0?n-1:void 0})}else if(i.type==="map"){if(!V(t))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${Ae(e)}, got ${t}`};for(let[o,s]of Object.entries(t))Te({field:i.values,value:s,fieldPath:[...e,o],depth:n!==void 0?n-1:void 0})}else if(i.type==="string"){if(typeof t!="string")return{type:"invalid-type",fieldPath:e,message:`Expected string ${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};if(i.options&&!i.options.includes(t))return{type:"invalid-value",fieldPath:e,message:`Expected one of ${i.options.join(", ")} for field ${Ae(e)}, got ${t}`}}else if(i.type==="boolean"){if(typeof t!="boolean")return{type:"invalid-type",fieldPath:e,message:`Expected boolean ${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`}}else if(i.type==="number"){if(typeof t!="number")return{type:"invalid-type",fieldPath:e,message:`Expected number ${i.nullable?" or null":""} for field ${Ae(e)}, got ${t}`}}else i.type}}function Ae(i){return i.length===0?"root":i.join(".")}function Ne(i,t){return i.type==="object"?i.properties[t]:i.type==="array"?i.items:i.type==="map"?i.values:i.type==="any"?i:"type"in i?null:i[t]??null}function yi({synthetics:i,indexes:t,...e}){let n={...i,...t};for(let[r,o]of Object.entries(e.fields))"indexed"in o&&(n[r]={field:r});return{...e,indexes:n}}function gt(i){return i}gt.collection=yi;gt.fields=Tr;gt.generated={id:Br.default};var zt="\uFFFFFE",Os="\0",Is="\uFFFFFF";function ce(...i){let t=Ds(i);return t.length===1?t[0]:t}function Ue(...i){return i.join(zt)+`${Is}`}function Ve(...i){return i.join(zt)+`${zt}${Os}`}function Ds(i){let t=[[]];for(let e of i)if(Array.isArray(e)){let n=[];for(let r of t)for(let o of e)n.push(r.concat(o));t=n}else for(let n of t)n.push(`${e}`);return Array.from(new Set(t.map(e=>e.join(zt))))}function _s(i){return!!i.field}function Es(i,t){let e={};for(let[n,r]of Object.entries(i.indexes||{})){let o=r;_s(o)?e[n]=ve(t[o.field]):e[n]=ve(o.compute(t))}return e}function Cs(i,t){return Object.entries(i.compounds||{}).reduce((e,[n,r])=>(e[n]=ce(...r.of.map(o=>t[o])),e),{})}function Ps(i,t){return Object.entries(i.fields).reduce((e,[n,r])=>("indexed"in r&&(e[n]=ve(t[n])),e),{})}function qt(i,t){let e={[i.primaryKey]:t[i.primaryKey],...Ps(i,t),...Es(i,t)};return Object.assign(e,Cs(i,{...t,...e})),e["@@@snapshot"]=t,e}var As="null";function ve(i){if(i===null)return As;if(typeof i=="string"||typeof i=="number")return i;if(typeof i=="boolean"||i===null)return`${i}`;if(i===void 0)return"undefined";if(Array.isArray(i))return i.map(ve);throw new Error(`Unsupported index value: ${i}`)}var jr={version:0,collections:{}};function Wt(i,t,e){let n=typeof t=="function",r=n?jr:i,o=n?i:t,s=n?t:e,a=Object.keys(o.collections).filter(x=>r.collections[x]&&ut(r.collections[x])!==ut(o.collections[x])),p=Object.keys(r.collections).filter(x=>!o.collections[x]),l=Object.keys(o.collections).filter(x=>!r.collections[x]),m=new Set;for(let x of a){let I=r.collections[x].fields,S=o.collections[x].fields;Object.keys(S).some(D=>!I[D]?.default&&S[D]?.default)&&m.add(x),Object.keys(I).some(D=>!S[D])&&m.add(x)}let v={},y={};for(let x of[...a,...l]){let I=Ht(r.collections[x]),S=Ht(o.collections[x]),D=S.filter(b=>!I.find(_=>_.name===b.name)),F=I.filter(b=>!S.find(_=>_.name===b.name));D.length>0&&(v[x]=D,a.includes(x)&&m.add(x)),F.length>0&&(y[x]=F,a.includes(x)&&m.add(x))}let C=(x,I)=>Pe(o.collections[x],I),w=x=>I=>{let S=o.collections[x];return Pe(S,gi(S,I))};return{version:o.version,migrate:async x=>{let I=[];if(await s({migrate:async(S,D)=>{let F=w(S),b=async _=>{let u=await D(_);return K(u,ne(_)),F(u)};await x.migrate(S,b),I.push(S),m.delete(S)},identity:S=>S,withDefaults:C,info:{changedCollections:a,addedCollections:l,removedCollections:p},queries:x.queries,mutations:x.mutations}),o.version>1){x.log("debug","auto-migrating collections with new defaults",m);for(let D of m)await x.migrate(D,w(D)),I.push(D);let S=a.filter(D=>!I.includes(D));S.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,S)}},removedCollections:p,addedIndexes:v,removedIndexes:y,allCollections:Object.keys(o.collections),changedCollections:a,addedCollections:l,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function Ht(i){return i?[...Object.keys(i.indexes||{}).map(t=>({name:t,multiEntry:["array","string[]","number[]","boolean[]"].includes(i.indexes[t].type),synthetic:!0,compound:!1})),...Object.keys(i.compounds||{}).map(t=>({name:t,multiEntry:i.compounds[t].of.some(e=>(i.fields[e]||i.indexes[e]).type==="array"),synthetic:!1,compound:!0}))]:[]}function bi(i,t){return Wt(t?i:{version:0,collections:{}},t||i,async({migrate:n,info:r})=>{if((t||i).version!==1)for(let o of r.changedCollections)await n(o,s=>s)})}function wi(i,t,e){let n=typeof t=="function"||t===void 0,r=n?jr:i,o=n?i:t,s=n?t:e;L(r,"Invalid arguments to createMigration"),L(o,"Invalid arguments to createMigration");let{changedCollections:a,addedCollections:p,removedCollections:l,addedIndexes:m,removedIndexes:v,autoMigratedCollections:y,autoMigration:C}=Fs(r,o);return{version:o.version,migrate:async w=>{let x=[];if(await s?.({migrate:async(S,D)=>{let F=C(S),b=async _=>{let u=await D(_);K(u,ne(_));let h=F(u),d=Mr(o.collections[S].fields,h);return h};await w.migrate(S,b),x.push(S),y.delete(S)},info:{changedCollections:a,addedCollections:p,removedCollections:l},queries:w.queries,mutations:w.mutations}),o.version>1){w.log("debug","auto-migrating collections with new defaults",y);for(let D of y)await w.migrate(D,C(D)),x.push(D);for(let D of l)await w.deleteCollection(D);let S=a.filter(D=>!x.includes(D));S.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,S)}},removedCollections:l,addedIndexes:m,removedIndexes:v,allCollections:Object.keys(o.collections),changedCollections:a,addedCollections:p,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function Fs(i,t){let e=Object.keys(t.collections).filter(m=>i.collections[m]&&ut(i.collections[m])!==ut(t.collections[m])),n=Object.keys(i.collections).filter(m=>!t.collections[m]),r=Object.keys(t.collections).filter(m=>!i.collections[m]),o=new Set;for(let m of e){let v=i.collections[m].fields,y=t.collections[m].fields;Object.keys(y).some(C=>!Ce(v[C])&&Ce(y[C]))&&o.add(m),Object.keys(v).some(C=>!y[C])&&o.add(m)}let s={},a={};for(let m of[...e,...r]){let v=Ht(i.collections[m]),y=Ht(t.collections[m]),C=y.filter(x=>!v.find(I=>I.name===x.name)),w=v.filter(x=>!y.find(I=>I.name===x.name));C.length>0&&(s[m]=C,e.includes(m)&&o.add(m)),w.length>0&&(a[m]=w,e.includes(m)&&o.add(m))}return{changedCollections:e,addedCollections:r,removedCollections:n,addedIndexes:s,removedIndexes:a,autoMigratedCollections:o,withDefaults:(m,v)=>Pe(t.collections[m],v),autoMigration:m=>v=>{let y=t.collections[m];return Pe(y,gi(y,v))}}}var Qt=class{constructor(t,e){this.getNow=t;this.createSubId=e;this.isPrimitive=t=>!V(t)||Q(t);this.createDiff=(t,e,n={})=>ht(t,e,this.getNow,this.createSubId,[],n);this.createInitialize=(t,e)=>Re(t,e,this.getNow,this.createSubId);this.createSet=(t,e,n)=>{if(this.isPrimitive(n))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:e,value:n}}];{let r=xe(t,this.createSubId);return[...Re(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:he(r),name:e}}]}};this.createRemove=(t,e)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:e}}];this.createListPush=(t,e)=>{if(this.isPrimitive(e))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:e}}];{let n=xe(t,this.createSubId);return[...Re(e,n,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:he(n)}}]}};this.createListAdd=(t,e)=>this.isPrimitive(e)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:e}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:he(e)}}];this.createListInsert=(t,e,n)=>{if(this.isPrimitive(n))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:n,index:e}}];{let r=xe(t,this.createSubId);return[...Re(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:he(r),index:e}}]}};this.createListRemove=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:e,only:n}}];this.createListDelete=(t,e,n=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:e,count:n}}];this.createListMoveByRef=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:e,index:n}}];this.createListMoveByIndex=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:e,to:n}}];this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}];this.createDeleteAll=t=>t.map(e=>({oid:e,timestamp:this.getNow(),data:{op:"delete"}}))}};var U=class{constructor(t){this._onAllUnsubscribed=t;this.subscribers={};this.counts={};this._disabled=!1;this.disposed=!1;this.subscriberCount=t=>this.counts[t]??0;this.totalSubscriberCount=()=>Object.values(this.counts).reduce((t,e)=>t+e,0);this.subscribe=(t,e)=>{let n=Nt(),r=this.subscribers[t];return r||(r=this.subscribers[t]={}),r[n]=e,this.counts[t]=(this.counts[t]||0)+1,()=>{this.subscribers[t]&&(delete this.subscribers[t][n],this.counts[t]--,this.counts[t]===0&&(delete this.subscribers[t],delete this.counts[t],this._onAllUnsubscribed&&this._onAllUnsubscribed(t)))}};this.emit=(t,...e)=>{this._disabled||this.subscribers[t]&&Object.values(this.subscribers[t]).forEach(n=>n(...e))};this.dispose=()=>{this._disabled=!0,this.disposed=!0;let t=Object.keys(this.subscribers);this.subscribers={},this.counts={},t.forEach(e=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(e)})};this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};function Lr(i,t,e,n){if(t==null)return[{oid:i,timestamp:n(),data:{op:"delete"}}];let r=ae(t),o=[];for(let s of e){let a=Rs(i,r,s,n);o.unshift(...a),je(r,s.data)}return o}function Rs(i,t,e,n){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:i,timestamp:n(),data:{op:"set",name:r.name,value:t[r.name]}}];case"list-insert":return[{oid:i,timestamp:n(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:i,timestamp:n(),data:{op:"list-insert",index:r.index,values:t.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:i,timestamp:n(),data:{op:"list-move-by-ref",value:r.value,index:t.indexOf(r.value)}}];case"list-move-by-index":return[{oid:i,timestamp:n(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:i,timestamp:n(),data:{op:"initialize",value:t}}];case"list-push":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let o=t.lastIndexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:o,values:[r.value]}}]}else if(r.only==="first"){let o=t.indexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:o,values:[r.value]}}]}else{let o=[],s=t.indexOf(r.value);for(;s!==-1;)o.push(s),s=t.indexOf(r.value,s+1);return o.map(a=>({oid:i,timestamp:n(),data:{op:"list-insert",index:a,value:r.value}}))}case"list-add":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"initialize":return[{oid:i,timestamp:n(),data:{op:"delete"}}];case"touch":return[];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var Xe=class{constructor(t){this.flusher=t;this.batches=new Map;this.flush=t=>{let e=this.batches.get(t);if(e)return e.flush()};this.discard=t=>{let e=this.batches.get(t);e&&(e.discard(),this.batches.delete(t))};this.flushAll=()=>[...this.batches.values()].map(t=>t.flush());this.getSize=t=>{let e=this.batches.get(t);return e?e.items.length:0}}add({key:t,userData:e,items:n,max:r,timeout:o}){let s=this.batches.get(t);return s||(s=new vi({max:r||null,startedAt:Date.now(),userData:e,timeout:o||null,flusher:this.flusher,key:t}),this.batches.set(t,s)),s.update({items:n,max:r,timeout:o,userData:e}),s}},vi=class{constructor({max:t,startedAt:e,timeout:n,userData:r,flusher:o,key:s}){this.items=[];this.update=({items:t,max:e,timeout:n,userData:r})=>{this.items.push(...t),e!==void 0&&(this.max=e),n!==void 0&&(this.timeout=n),r&&(this.userData=r);let o=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():o&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))};this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let t=this.items;return this.items=[],this.flusher(t,this.key,this.userData)};this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]};this.max=t,this.startedAt=e,this.timeout=n,this.userData=r,this.flusher=o,this.key=s}};function Nr(i,t){let e,n;return(...r)=>{let o=t();return e&&e.length===o.length&&e.every((s,a)=>s===o[a])||(e=[...o],n=i(...r)),n}}var Si=(l=>(l[l.InvalidRequest=4e3]="InvalidRequest",l[l.BodyRequired=4001]="BodyRequired",l[l.NoToken=4010]="NoToken",l[l.InvalidToken=4011]="InvalidToken",l[l.TokenExpired=4012]="TokenExpired",l[l.NotFound=4040]="NotFound",l[l.Unexpected=5e3]="Unexpected",l[l.ConfigurationError=5010]="ConfigurationError",l[l.NoFileStorage=5011]="NoFileStorage",l))(Si||{}),Ur=class extends Error{constructor(e,n,r){super(r??`Verdant error: ${e}`,{cause:n});this.code=e;this.toResponse=()=>JSON.stringify({code:this.code})}static{this.Code=Si}get httpStatus(){let e=Math.floor(this.code/10);return e<600?e:500}};function Vr(i){return typeof i=="object"&&"code"in i&&typeof i.code=="number"}function le(i){return i instanceof Error&&i.name==="AbortError"}function J(i){return new Promise((t,e)=>{i.onsuccess=()=>{t(i.result)},i.onerror=()=>{i.error&&le(i.error)?t(i.result):e(i.error)}})}function yt(i,t){return new Promise((e,n)=>{let r=i.transaction([t],"readonly"),s=r.objectStore(t).openCursor(),a=0,p=0;s.onsuccess=function(l){let m=s.result;m&&(a++,p=p+Or(m.value),m.continue())},s.onerror=function(l){s.error&&le(s.error)?e({count:a,size:p}):n(s.error)},r.oncomplete=function(l){e({count:a,size:p})},r.onabort=function(l){n(l)},r.onerror=function(l){n(l)}})}function Jt(i,t){let e=i.transaction(t,"readonly"),n=t.map(r=>{let o=e.objectStore(r);return J(o.getAll())});return Promise.all(n)}async function Ke(i){i.close(),await new Promise((t,e)=>{t()})}async function Gt(i,t=window.indexedDB){let e=t.deleteDatabase([i,"meta"].join("_")),n=t.deleteDatabase([i,"collections"].join("_"));await Promise.all([new Promise((r,o)=>{e.onsuccess=r,e.onerror=o}),new Promise((r,o)=>{n.onsuccess=r,n.onerror=o})]),window.location.reload()}function Kr(i,t=window.indexedDB){return J(t.deleteDatabase(i))}async function $r(i=window.indexedDB){return i.databases()}function Yt(i,t,e,n,r){let o=i.transaction(t,e);if(n){let s=()=>{r?.("debug","aborting transaction");try{o.abort()}catch(a){r?.("debug","aborting transaction failed",a)}};n.addEventListener("abort",s),o.addEventListener("error",()=>{n.removeEventListener("abort",s)}),o.addEventListener("complete",()=>{n.removeEventListener("abort",s)})}return o}var Ie=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(t=>t()),this._disposes=[]};this.addDispose=t=>{this._disposes.push(t)}}};var se=class extends Ie{constructor(e,{log:n}={}){super();this.db=e;this.globalAbortController=new AbortController;this.createTransaction=(e,n)=>{let r=Yt(this.db,e,n?.mode||"readonly",n?.abort,this.log);return this.globalAbortController.signal.addEventListener("abort",r.abort),r.addEventListener("complete",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r.addEventListener("error",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r};this.run=async(e,n,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve(void 0);let s=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=n(s);return J(a)};this.runAll=async(e,n,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve([]);let s=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=n(s);return Promise.all(a.map(J))};this.iterate=async(e,n,r,o)=>{let a=(o?.transaction||this.createTransaction([e],o)).objectStore(e),p=n(a);return Array.isArray(p)?Promise.all(p.map(l=>new Promise((m,v)=>{l.onsuccess=()=>{let y=l.result;y?(r(y.value,a),y.continue()):m()},l.onerror=()=>{l.error&&le(l.error)?m():v(l.error)}}))).then(()=>{}):new Promise((l,m)=>{p.onsuccess=()=>{let v=p.result;v?(r(v.value,a),v.continue()):l()},p.onerror=()=>{p.error&&le(p.error)?l():m(p.error)}})};this.clear=e=>this.run(e,n=>n.clear(),{mode:"readwrite"});this.log=n,this.addDispose(()=>{this.globalAbortController.abort()})}};var Xt=class extends se{constructor(){super(...arguments);this.getAckInfo=async()=>{let e=await this.run("info",n=>n.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",n=>n.put({type:"ack",globalAckTimestamp:e}),{mode:"readwrite"})}}};var Zt=class extends se{constructor(e,n){super(e,n);this.getAllForDocument=async(e,{mode:n="readonly",transaction:r}={})=>{let o=[];return await this.iterateOverAllForDocument(e,s=>{o.push(s)},{mode:n,transaction:r}),o};this.iterateOverAllForDocument=async(e,n,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>{let a=$(e),[p,l]=si(e),[m,v]=ai(e);return[s.openCursor(IDBKeyRange.only(a)),s.openCursor(IDBKeyRange.bound(p,l,!1,!1)),s.openCursor(IDBKeyRange.bound(m,v,!1,!1))]},n,{mode:r,transaction:o});this.iterateOverAllForCollection=async(e,n,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],n,{mode:r,transaction:o});this.getAllForMultipleDocuments=async(e,{mode:n="readonly"}={})=>(await this.runAll("baselines",o=>e.flatMap(s=>{let a=$(s),[p,l]=si(s),[m,v]=ai(s);return[o.get(a),o.getAll(IDBKeyRange.bound(p,l,!1,!1)),o.getAll(IDBKeyRange.bound(m,v,!1,!1))]}),{mode:n})).flat();this.getAllSince=async(e,{mode:n="readonly"}={})=>this.run("baselines",r=>{let o=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(o)},{mode:n});this.get=async(e,{transaction:n,mode:r="readonly"}={})=>this.run("baselines",o=>o.get(e),{mode:r,transaction:n});this.set=async(e,{transaction:n}={})=>{await this.run("baselines",r=>r.put(e),{mode:"readwrite",transaction:n})};this.setAll=async(e,{transaction:n}={})=>{await this.runAll("baselines",r=>e.map(o=>r.put(o)),{mode:"readwrite",transaction:n})};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:n})=>{await this.run("baselines",r=>r.delete(e),{mode:"readwrite",transaction:n})}}};var zr=Qe(at(),1);var en=class extends se{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let n=await this.run("info",r=>r.get("localReplicaInfo"),{transaction:e});return n?(this.cached=n,n):(this._creating||(this._creating=(async()=>{let o={type:"localReplicaInfo",id:(0,zr.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};await this.run("info",s=>s.put(o),{mode:"readwrite"}),this.cached=o})()),await this._creating,this.get({transaction:e}))};this.update=async(e,{transaction:n}={})=>{let r=await this.get({transaction:n});Object.assign(r,e),await this.run("info",o=>o.put(r),{mode:"readwrite"}),this.cached=r};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",n=>n.put(e),{mode:"readwrite"})}}};var tn=class{constructor(t){this.meta=t;this.createOperation=async t=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:t.operations.map(n=>({data:n.data,oid:n.oid,timestamp:n.timestamp}))}};this.createMigrationOperation=async({targetVersion:t,...e})=>{let n=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(r=>({...r,timestamp:this.meta.time.zero(t)})),timestamp:this.meta.time.zero(t),replicaId:n.id}};this.createSyncStep1=async t=>{let e=await this.meta.localReplica.get(),n=t===null?null:e.lastSyncedLogicalTime,r=[],o=new Set;n?await this.meta.operations.iterateOverAllLocalOperations(a=>{r.push({data:a.data,oid:a.oid,timestamp:a.timestamp}),o.add($(a.oid))},{after:n,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(a=>{r.push({data:a.data,oid:a.oid,timestamp:a.timestamp}),o.add($(a.oid))},{mode:"readwrite"});let s=[];return n||(s=await this.meta.baselines.getAllSince("")),{type:"sync",schemaVersion:this.meta.schema.currentVersion,timestamp:this.meta.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:s,since:n}};this.createPresenceUpdate=async t=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:t,replicaId:e.id}};this.createHeartbeat=async()=>{let t=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:t.id}};this.createAck=async t=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:t}}}};var nn=class extends se{constructor(e,n){super(e,n);this.iterateOverAllOperationsForDocument=async(e,n,{to:r,from:o,after:s,mode:a="readonly",transaction:p}={})=>{let m=(p||this.createTransaction(["operations"],{mode:a})).objectStore("operations"),v=m.index("d_t"),y=o||s,C=y?ce(e,y):Ve(e),w=r?ce(e,r):Ue(e),x=IDBKeyRange.bound(C,w,!!s,!1),I=v.openCursor(x,"next");return new Promise((S,D)=>{let F;I.onsuccess=b=>{let _=I.result;if(_){let u=_.value;L(u.oid.startsWith(e)),L(F===void 0||F<=u.timestamp,`expected ${F} <= ${u.timestamp}`),n(u,m),F=u.timestamp,_.continue()}else S()},I.onerror=b=>{if(le(I.error)){S();return}else D(I.error)}})};this.iterateOverAllOperationsForEntity=async(e,n,{after:r,to:o,mode:s,transaction:a})=>{let l=(a||this.createTransaction(["operations"],{mode:s})).objectStore("operations"),m=r?ce(e,r):Ve(e),v=o?ce(e,o):Ue(e),y=IDBKeyRange.bound(m,v,!!r,!1),C=l.openCursor(y,"next");return new Promise((w,x)=>{let I;C.onsuccess=S=>{let D=C.result;if(D){let F=D.value;L(F.oid.startsWith(e)),L(I===void 0||I<=F.timestamp,`expected ${I} <= ${F.timestamp}`),n(F,l),I=F.timestamp,D.continue()}else w()},C.onerror=S=>{le(C.error)?w():x(C.error)}})};this.iterateOverAllOperationsForCollection=async(e,n,{after:r,to:o,mode:s,transaction:a})=>{let p=a||this.createTransaction(["operations"],{mode:s});return this.iterate("operations",l=>l.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),n,{mode:s,transaction:p})};this.iterateOverAllLocalOperations=async(e,{before:n,after:r,mode:o="readonly",transaction:s})=>{let p=(s||this.createTransaction(["operations"],{mode:o})).objectStore("operations"),l=p.index("l_t"),m=r?ce(!0,r):Ve(!0),v=n?ce(!0,n):Ue(!0),y=IDBKeyRange.bound(m,v,!!r,!0),C=l.openCursor(y,"next");return new Promise((w,x)=>{let I;C.onsuccess=S=>{let D=C.result;if(D){let F=D.value;L(I===void 0||I<=F.timestamp,`expected ${I} <= ${F.timestamp}`),e(F,p),I=F.timestamp,D.continue()}else w()},C.onerror=S=>{le(C.error)?w():x(C.error)}})};this.iterateOverAllOperations=async(e,{before:n,transaction:r,mode:o,from:s})=>{await this.iterate("operations",a=>{let p=s?Ve(s):void 0,l=n?Ue(n):void 0,m=p&&l?window.IDBKeyRange.bound(p,l,!1,!0):p?window.IDBKeyRange.lowerBound(p,!1):l?window.IDBKeyRange.upperBound(l,!0):void 0;return a.index("timestamp").openCursor(m,"next")},e,{mode:o,transaction:r})};this.addOperations=async(e,{transaction:n}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:n});this.addCompoundIndexes=e=>({...e,oid_timestamp:ce(e.oid,e.timestamp),l_t:ce(e.isLocal,e.timestamp),d_t:ce($(e.oid),e.timestamp)});this.insert=async(e,{transaction:n})=>{let r=new Set;return await this.runAll("operations",o=>e.map(s=>(r.add($(s.oid)),o.put(s))),{mode:"readwrite",transaction:n}),Array.from(r)};this.reset=()=>this.clear("operations")}};var rn=class{constructor(t,e){this.db=t;this.currentVersion=e;this.cached=null;this.get=async()=>{if(this.cached)return this.cached;let r=this.db.transaction("info","readonly").objectStore("info").get("schema"),o=await J(r);return o?(this.cached=JSON.parse(o.schema),this.cached):null};this.set=async t=>{let o=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(t)});this.cached=t,await J(o)}}};var bt=class extends U{constructor({disableRebasing:e,context:n}){super();this.time=new Ft;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=(e,n={})=>Yt(this.db,e,"readwrite",n.abort,this.context.log);this.getAllDocumentRelatedOids=async e=>{let n=new Set,r=$(e);L(r===e,"Must be root document OID"),n.add(r);let o=this.createTransaction(["baselines","operations"]);return await Promise.all([this.baselines.iterateOverAllForDocument(r,s=>{n.add(s.oid)},{transaction:o}),this.operations.iterateOverAllOperationsForDocument(r,s=>{n.add(s.oid)},{transaction:o})]),Array.from(n)};this.getAllCollectionRelatedOids=async e=>{let n=new Set,r=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForCollection(e,o=>{n.add(o.oid)},{transaction:r}),this.operations.iterateOverAllOperationsForCollection(e,o=>{n.add(o.oid)},{transaction:r})]),Array.from(n)};this.getDocumentSnapshot=async(e,n={})=>{let r=$(e);L(r===e,"Must be root document OID");let o=this.db.transaction(["baselines","operations"],"readwrite"),s=await this.baselines.getAllForDocument(r,{transaction:o}),a=new Map;for(let l of s)l.snapshot&&K(l.snapshot,l.oid),a.set(l.oid,l.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,l=>{let m=a.get(l.oid)||void 0,v=je(m,l.data);v&&K(v,l.oid),a.set(l.oid,v)},{transaction:o,to:n.to||this.now});let p=a.get(r);return p&&$t(p,a),p};this.getDocumentData=async(e,n)=>{let r=this.createTransaction(["baselines","operations"],n),o=[],s={};return await Promise.all([this.baselines.iterateOverAllForDocument(e,a=>{o.push(a)},{transaction:r}),this.operations.iterateOverAllOperationsForDocument(e,a=>{s[a.oid]??=[],s[a.oid].push(a)},{transaction:r})]),{baselines:o,operations:s}};this.ack=async e=>{let n=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:n.id,timestamp:e}),!this._closing&&(!n.ackedLogicalTime||e>n.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperations=async(e,n)=>{if(e.length===0)return;this.log("debug",`Inserting ${e.length} local operations`,e);for(let o of e)o.isLocal=!0;await this.operations.addOperations(e,n);let r=await this.messageCreator.createOperation({operations:e});this.emit("message",r),this.tryAutonomousRebase()};this.insertRemoteOperations=async(e,n)=>{if(e.length===0)return[];this.log("debug",`Inserting ${e.length} remote operations`,e);let r=await this.operations.addOperations(e.map(o=>({...o,isLocal:!1})),n);return this.ack(e[e.length-1].timestamp),r};this.insertRemoteBaselines=async(e,n)=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e,n);let r=new Set;return e.forEach(o=>{r.add($(o.oid))}),Array.from(r)};this.insertData=async(e,n)=>{let r=this.createTransaction(["baselines","operations"],n);e.baselines&&await this.insertRemoteBaselines(e.baselines,{transaction:r}),!n?.abort?.aborted&&e.operations&&(e.isLocal?await this.insertLocalOperations(e.operations,{transaction:r}):await this.insertRemoteOperations(e.operations,{transaction:r}))};this.updateLastSynced=async e=>{if(!this._closing)return this.localReplica.update({lastSyncedLogicalTime:e})};this.lastSyncedTimestamp=async()=>(await this.localReplica.get()).lastSyncedLogicalTime;this.tryAutonomousRebase=async()=>{this.disableRebasing||(await this.localReplica.get()).lastSyncedLogicalTime||await this.runRebase(this.now)};this.runRebase=async e=>{if(this._closing)return;let n,r=new Set,o=this.createTransaction(["baselines","operations"]),s=0;if(await this.operations.iterateOverAllOperations(p=>{r.add(p.oid),n=p.timestamp,s++},{before:e,transaction:o}),!r.size||this._closing)return;let a=[];for(let p of r)a.push(await this.rebase(p,n||e,o));this.emit("rebase",a)};this.rebase=async(e,n,r)=>{let o=(await this.localReplica.get()).id;this.log("[",o,"]","Rebasing",e,"up to",n);let s=r||this.createTransaction(["operations","baselines"]),a=await this.baselines.get(e,{transaction:s}),p=a?.snapshot||void 0,l=0,m=[];await this.operations.iterateOverAllOperationsForEntity(e,(y,C)=>{(!a||y.timestamp>a.timestamp)&&(p=je(p,y.data,m)),l++,C.delete(y.oid_timestamp)},{to:n,transaction:s}),p&&K(p,e);let v={oid:e,snapshot:p,timestamp:n};if(v.snapshot?await this.baselines.set(v,{transaction:s}):await this.baselines.delete(e,{transaction:s}),this.log("debug","successfully rebased",e,"up to",n,":",p,"and deleted",l,"operations"),m.length){let y=m.filter(be);y.length&&this.emit("filesDeleted",y)}return v};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,n)=>{let r=await this.schema.get();if(r&&n===r.version&&r.version===e.version&&JSON.stringify(r)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
|
|
4
|
+
`)},_domwindow:function(){return p("domwindow")},_bigint:function(l){return p("bigint:"+l.toString())},_process:function(){return p("process")},_timer:function(){return p("timer")},_pipe:function(){return p("pipe")},_tcp:function(){return p("tcp")},_udp:function(){return p("udp")},_tty:function(){return p("tty")},_statwatcher:function(){return p("statwatcher")},_securecontext:function(){return p("securecontext")},_connection:function(){return p("connection")},_zlib:function(){return p("zlib")},_context:function(){return p("context")},_nodescript:function(){return p("nodescript")},_httpparser:function(){return p("httpparser")},_dataview:function(){return p("dataview")},_signal:function(){return p("signal")},_fsevent:function(){return p("fsevent")},_tlswrap:function(){return p("tlswrap")}}}function R(){return{buf:"",write:function(b){this.buf+=b},end:function(b){this.buf+=b},read:function(){return this.buf}}}e.writeToStream=function(b,D,d){return d===void 0&&(d=D,D={}),_(D=I(b,D),d).dispatch(b)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(n,i,e){(function(t,r,o,s,a,h,u,m,v){(function(y){"use strict";var C=typeof Uint8Array<"u"?Uint8Array:Array,w="+".charCodeAt(0),S="/".charCodeAt(0),I="0".charCodeAt(0),x="a".charCodeAt(0),_="A".charCodeAt(0),R="-".charCodeAt(0),b="_".charCodeAt(0);function D(d){return d=d.charCodeAt(0),d===w||d===R?62:d===S||d===b?63:d<I?-1:d<I+10?d-I+26+26:d<_+26?d-_:d<x+26?d-x+26:void 0}y.toByteArray=function(d){var p,l;if(0<d.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var O=d.length,O=d.charAt(O-2)==="="?2:d.charAt(O-1)==="="?1:0,E=new C(3*d.length/4-O),j=0<O?d.length-4:d.length,B=0;function M(k){E[B++]=k}for(p=0;p<j;p+=4,0)M((16711680&(l=D(d.charAt(p))<<18|D(d.charAt(p+1))<<12|D(d.charAt(p+2))<<6|D(d.charAt(p+3))))>>16),M((65280&l)>>8),M(255&l);return O==2?M(255&(l=D(d.charAt(p))<<2|D(d.charAt(p+1))>>4)):O==1&&(M((l=D(d.charAt(p))<<10|D(d.charAt(p+1))<<4|D(d.charAt(p+2))>>2)>>8&255),M(255&l)),E},y.fromByteArray=function(d){var p,l,O,E,j=d.length%3,B="";function M(k){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(k)}for(p=0,O=d.length-j;p<O;p+=3)l=(d[p]<<16)+(d[p+1]<<8)+d[p+2],B+=M((E=l)>>18&63)+M(E>>12&63)+M(E>>6&63)+M(63&E);switch(j){case 1:B=(B+=M((l=d[d.length-1])>>2))+M(l<<4&63)+"==";break;case 2:B=(B=(B+=M((l=(d[d.length-2]<<8)+d[d.length-1])>>10))+M(l>>4&63))+M(l<<2&63)+"="}return B}})(e===void 0?this.base64js={}:e)}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(n,i,e){(function(t,r,w,s,a,h,u,m,v){var y=n("base64-js"),C=n("ieee754");function w(c,f,g){if(!(this instanceof w))return new w(c,f,g);var P,A,T,U,W=typeof c;if(f==="base64"&&W=="string")for(c=(U=c).trim?U.trim():U.replace(/^\s+|\s+$/g,"");c.length%4!=0;)c+="=";if(W=="number")P=te(c);else if(W=="string")P=w.byteLength(c,f);else{if(W!="object")throw new Error("First argument needs to be a number, array or string.");P=te(c.length)}if(w._useTypedArrays?A=w._augment(new Uint8Array(P)):((A=this).length=P,A._isBuffer=!0),w._useTypedArrays&&typeof c.byteLength=="number")A._set(c);else if(H(U=c)||w.isBuffer(U)||U&&typeof U=="object"&&typeof U.length=="number")for(T=0;T<P;T++)w.isBuffer(c)?A[T]=c.readUInt8(T):A[T]=c[T];else if(W=="string")A.write(c,0,f);else if(W=="number"&&!w._useTypedArrays&&!g)for(T=0;T<P;T++)A[T]=0;return A}function S(c,f,g,P){return w._charsWritten=At(function(A){for(var T=[],U=0;U<A.length;U++)T.push(255&A.charCodeAt(U));return T}(f),c,g,P)}function I(c,f,g,P){return w._charsWritten=At(function(A){for(var T,U,W=[],Y=0;Y<A.length;Y++)U=A.charCodeAt(Y),T=U>>8,U=U%256,W.push(U),W.push(T);return W}(f),c,g,P)}function x(c,f,g){var P="";g=Math.min(c.length,g);for(var A=f;A<g;A++)P+=String.fromCharCode(c[A]);return P}function _(c,f,g,T){T||(F(typeof g=="boolean","missing or invalid endian"),F(f!=null,"missing offset"),F(f+1<c.length,"Trying to read beyond buffer length"));var A,T=c.length;if(!(T<=f))return g?(A=c[f],f+1<T&&(A|=c[f+1]<<8)):(A=c[f]<<8,f+1<T&&(A|=c[f+1])),A}function R(c,f,g,T){T||(F(typeof g=="boolean","missing or invalid endian"),F(f!=null,"missing offset"),F(f+3<c.length,"Trying to read beyond buffer length"));var A,T=c.length;if(!(T<=f))return g?(f+2<T&&(A=c[f+2]<<16),f+1<T&&(A|=c[f+1]<<8),A|=c[f],f+3<T&&(A+=c[f+3]<<24>>>0)):(f+1<T&&(A=c[f+1]<<16),f+2<T&&(A|=c[f+2]<<8),f+3<T&&(A|=c[f+3]),A+=c[f]<<24>>>0),A}function b(c,f,g,P){if(P||(F(typeof g=="boolean","missing or invalid endian"),F(f!=null,"missing offset"),F(f+1<c.length,"Trying to read beyond buffer length")),!(c.length<=f))return P=_(c,f,g,!0),32768&P?-1*(65535-P+1):P}function D(c,f,g,P){if(P||(F(typeof g=="boolean","missing or invalid endian"),F(f!=null,"missing offset"),F(f+3<c.length,"Trying to read beyond buffer length")),!(c.length<=f))return P=R(c,f,g,!0),2147483648&P?-1*(4294967295-P+1):P}function d(c,f,g,P){return P||(F(typeof g=="boolean","missing or invalid endian"),F(f+3<c.length,"Trying to read beyond buffer length")),C.read(c,f,g,23,4)}function p(c,f,g,P){return P||(F(typeof g=="boolean","missing or invalid endian"),F(f+7<c.length,"Trying to read beyond buffer length")),C.read(c,f,g,52,8)}function l(c,f,g,P,A){if(A||(F(f!=null,"missing value"),F(typeof P=="boolean","missing or invalid endian"),F(g!=null,"missing offset"),F(g+1<c.length,"trying to write beyond buffer length"),Hn(f,65535)),A=c.length,!(A<=g))for(var T=0,U=Math.min(A-g,2);T<U;T++)c[g+T]=(f&255<<8*(P?T:1-T))>>>8*(P?T:1-T)}function O(c,f,g,P,A){if(A||(F(f!=null,"missing value"),F(typeof P=="boolean","missing or invalid endian"),F(g!=null,"missing offset"),F(g+3<c.length,"trying to write beyond buffer length"),Hn(f,4294967295)),A=c.length,!(A<=g))for(var T=0,U=Math.min(A-g,4);T<U;T++)c[g+T]=f>>>8*(P?T:3-T)&255}function E(c,f,g,P,A){A||(F(f!=null,"missing value"),F(typeof P=="boolean","missing or invalid endian"),F(g!=null,"missing offset"),F(g+1<c.length,"Trying to write beyond buffer length"),Wn(f,32767,-32768)),c.length<=g||l(c,0<=f?f:65535+f+1,g,P,A)}function j(c,f,g,P,A){A||(F(f!=null,"missing value"),F(typeof P=="boolean","missing or invalid endian"),F(g!=null,"missing offset"),F(g+3<c.length,"Trying to write beyond buffer length"),Wn(f,2147483647,-2147483648)),c.length<=g||O(c,0<=f?f:4294967295+f+1,g,P,A)}function B(c,f,g,P,A){A||(F(f!=null,"missing value"),F(typeof P=="boolean","missing or invalid endian"),F(g!=null,"missing offset"),F(g+3<c.length,"Trying to write beyond buffer length"),Yi(f,34028234663852886e22,-34028234663852886e22)),c.length<=g||C.write(c,f,g,P,23,4)}function M(c,f,g,P,A){A||(F(f!=null,"missing value"),F(typeof P=="boolean","missing or invalid endian"),F(g!=null,"missing offset"),F(g+7<c.length,"Trying to write beyond buffer length"),Yi(f,17976931348623157e292,-17976931348623157e292)),c.length<=g||C.write(c,f,g,P,52,8)}e.Buffer=w,e.SlowBuffer=w,e.INSPECT_MAX_BYTES=50,w.poolSize=8192,w._useTypedArrays=function(){try{var c=new ArrayBuffer(0),f=new Uint8Array(c);return f.foo=function(){return 42},f.foo()===42&&typeof f.subarray=="function"}catch{return!1}}(),w.isEncoding=function(c){switch(String(c).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},w.isBuffer=function(c){return!(c==null||!c._isBuffer)},w.byteLength=function(c,f){var g;switch(c+="",f||"utf8"){case"hex":g=c.length/2;break;case"utf8":case"utf-8":g=De(c).length;break;case"ascii":case"binary":case"raw":g=c.length;break;case"base64":g=Ji(c).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":g=2*c.length;break;default:throw new Error("Unknown encoding")}return g},w.concat=function(c,f){if(F(H(c),`Usage: Buffer.concat(list, [totalLength])
|
|
5
|
+
list should be an Array.`),c.length===0)return new w(0);if(c.length===1)return c[0];if(typeof f!="number")for(A=f=0;A<c.length;A++)f+=c[A].length;for(var g=new w(f),P=0,A=0;A<c.length;A++){var T=c[A];T.copy(g,P),P+=T.length}return g},w.prototype.write=function(c,f,g,P){isFinite(f)?isFinite(g)||(P=g,g=void 0):(Y=P,P=f,f=g,g=Y),f=Number(f)||0;var A,T,U,W,Y=this.length-f;switch((!g||Y<(g=Number(g)))&&(g=Y),P=String(P||"utf8").toLowerCase()){case"hex":A=function(ye,ie,re,X){re=Number(re)||0;var G=ye.length-re;(!X||G<(X=Number(X)))&&(X=G),F((G=ie.length)%2==0,"Invalid hex string"),G/2<X&&(X=G/2);for(var Qe=0;Qe<X;Qe++){var Xi=parseInt(ie.substr(2*Qe,2),16);F(!isNaN(Xi),"Invalid hex string"),ye[re+Qe]=Xi}return w._charsWritten=2*Qe,Qe}(this,c,f,g);break;case"utf8":case"utf-8":T=this,U=f,W=g,A=w._charsWritten=At(De(c),T,U,W);break;case"ascii":case"binary":A=S(this,c,f,g);break;case"base64":T=this,U=f,W=g,A=w._charsWritten=At(Ji(c),T,U,W);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":A=I(this,c,f,g);break;default:throw new Error("Unknown encoding")}return A},w.prototype.toString=function(c,f,g){var P,A,T,U,W=this;if(c=String(c||"utf8").toLowerCase(),f=Number(f)||0,(g=g!==void 0?Number(g):W.length)===f)return"";switch(c){case"hex":P=function(Y,ye,ie){var re=Y.length;(!ye||ye<0)&&(ye=0),(!ie||ie<0||re<ie)&&(ie=re);for(var X="",G=ye;G<ie;G++)X+=K(Y[G]);return X}(W,f,g);break;case"utf8":case"utf-8":P=function(Y,ye,ie){var re="",X="";ie=Math.min(Y.length,ie);for(var G=ye;G<ie;G++)Y[G]<=127?(re+=Gi(X)+String.fromCharCode(Y[G]),X=""):X+="%"+Y[G].toString(16);return re+Gi(X)}(W,f,g);break;case"ascii":case"binary":P=x(W,f,g);break;case"base64":A=W,U=g,P=(T=f)===0&&U===A.length?y.fromByteArray(A):y.fromByteArray(A.slice(T,U));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":P=function(Y,ye,ie){for(var re=Y.slice(ye,ie),X="",G=0;G<re.length;G+=2)X+=String.fromCharCode(re[G]+256*re[G+1]);return X}(W,f,g);break;default:throw new Error("Unknown encoding")}return P},w.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},w.prototype.copy=function(c,f,g,P){if(f=f||0,(P=P||P===0?P:this.length)!==(g=g||0)&&c.length!==0&&this.length!==0){F(g<=P,"sourceEnd < sourceStart"),F(0<=f&&f<c.length,"targetStart out of bounds"),F(0<=g&&g<this.length,"sourceStart out of bounds"),F(0<=P&&P<=this.length,"sourceEnd out of bounds"),P>this.length&&(P=this.length);var A=(P=c.length-f<P-g?c.length-f+g:P)-g;if(A<100||!w._useTypedArrays)for(var T=0;T<A;T++)c[T+f]=this[T+g];else c._set(this.subarray(g,g+A),f)}},w.prototype.slice=function(c,f){var g=this.length;if(c=q(c,g,0),f=q(f,g,g),w._useTypedArrays)return w._augment(this.subarray(c,f));for(var P=f-c,A=new w(P,void 0,!0),T=0;T<P;T++)A[T]=this[T+c];return A},w.prototype.get=function(c){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(c)},w.prototype.set=function(c,f){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(c,f)},w.prototype.readUInt8=function(c,f){if(f||(F(c!=null,"missing offset"),F(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return this[c]},w.prototype.readUInt16LE=function(c,f){return _(this,c,!0,f)},w.prototype.readUInt16BE=function(c,f){return _(this,c,!1,f)},w.prototype.readUInt32LE=function(c,f){return R(this,c,!0,f)},w.prototype.readUInt32BE=function(c,f){return R(this,c,!1,f)},w.prototype.readInt8=function(c,f){if(f||(F(c!=null,"missing offset"),F(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return 128&this[c]?-1*(255-this[c]+1):this[c]},w.prototype.readInt16LE=function(c,f){return b(this,c,!0,f)},w.prototype.readInt16BE=function(c,f){return b(this,c,!1,f)},w.prototype.readInt32LE=function(c,f){return D(this,c,!0,f)},w.prototype.readInt32BE=function(c,f){return D(this,c,!1,f)},w.prototype.readFloatLE=function(c,f){return d(this,c,!0,f)},w.prototype.readFloatBE=function(c,f){return d(this,c,!1,f)},w.prototype.readDoubleLE=function(c,f){return p(this,c,!0,f)},w.prototype.readDoubleBE=function(c,f){return p(this,c,!1,f)},w.prototype.writeUInt8=function(c,f,g){g||(F(c!=null,"missing value"),F(f!=null,"missing offset"),F(f<this.length,"trying to write beyond buffer length"),Hn(c,255)),f>=this.length||(this[f]=c)},w.prototype.writeUInt16LE=function(c,f,g){l(this,c,f,!0,g)},w.prototype.writeUInt16BE=function(c,f,g){l(this,c,f,!1,g)},w.prototype.writeUInt32LE=function(c,f,g){O(this,c,f,!0,g)},w.prototype.writeUInt32BE=function(c,f,g){O(this,c,f,!1,g)},w.prototype.writeInt8=function(c,f,g){g||(F(c!=null,"missing value"),F(f!=null,"missing offset"),F(f<this.length,"Trying to write beyond buffer length"),Wn(c,127,-128)),f>=this.length||(0<=c?this.writeUInt8(c,f,g):this.writeUInt8(255+c+1,f,g))},w.prototype.writeInt16LE=function(c,f,g){E(this,c,f,!0,g)},w.prototype.writeInt16BE=function(c,f,g){E(this,c,f,!1,g)},w.prototype.writeInt32LE=function(c,f,g){j(this,c,f,!0,g)},w.prototype.writeInt32BE=function(c,f,g){j(this,c,f,!1,g)},w.prototype.writeFloatLE=function(c,f,g){B(this,c,f,!0,g)},w.prototype.writeFloatBE=function(c,f,g){B(this,c,f,!1,g)},w.prototype.writeDoubleLE=function(c,f,g){M(this,c,f,!0,g)},w.prototype.writeDoubleBE=function(c,f,g){M(this,c,f,!1,g)},w.prototype.fill=function(c,f,g){if(f=f||0,g=g||this.length,F(typeof(c=typeof(c=c||0)=="string"?c.charCodeAt(0):c)=="number"&&!isNaN(c),"value is not a number"),F(f<=g,"end < start"),g!==f&&this.length!==0){F(0<=f&&f<this.length,"start out of bounds"),F(0<=g&&g<=this.length,"end out of bounds");for(var P=f;P<g;P++)this[P]=c}},w.prototype.inspect=function(){for(var c=[],f=this.length,g=0;g<f;g++)if(c[g]=K(this[g]),g===e.INSPECT_MAX_BYTES){c[g+1]="...";break}return"<Buffer "+c.join(" ")+">"},w.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(w._useTypedArrays)return new w(this).buffer;for(var c=new Uint8Array(this.length),f=0,g=c.length;f<g;f+=1)c[f]=this[f];return c.buffer};var k=w.prototype;function q(c,f,g){return typeof c!="number"?g:f<=(c=~~c)?f:0<=c||0<=(c+=f)?c:0}function te(c){return(c=~~Math.ceil(+c))<0?0:c}function H(c){return(Array.isArray||function(f){return Object.prototype.toString.call(f)==="[object Array]"})(c)}function K(c){return c<16?"0"+c.toString(16):c.toString(16)}function De(c){for(var f=[],g=0;g<c.length;g++){var P=c.charCodeAt(g);if(P<=127)f.push(c.charCodeAt(g));else for(var A=g,T=(55296<=P&&P<=57343&&g++,encodeURIComponent(c.slice(A,g+1)).substr(1).split("%")),U=0;U<T.length;U++)f.push(parseInt(T[U],16))}return f}function Ji(c){return y.toByteArray(c)}function At(c,f,g,P){for(var A=0;A<P&&!(A+g>=f.length||A>=c.length);A++)f[A+g]=c[A];return A}function Gi(c){try{return decodeURIComponent(c)}catch{return String.fromCharCode(65533)}}function Hn(c,f){F(typeof c=="number","cannot write a non-number as a number"),F(0<=c,"specified a negative value for writing an unsigned value"),F(c<=f,"value is larger than maximum value for type"),F(Math.floor(c)===c,"value has a fractional component")}function Wn(c,f,g){F(typeof c=="number","cannot write a non-number as a number"),F(c<=f,"value larger than maximum allowed value"),F(g<=c,"value smaller than minimum allowed value"),F(Math.floor(c)===c,"value has a fractional component")}function Yi(c,f,g){F(typeof c=="number","cannot write a non-number as a number"),F(c<=f,"value larger than maximum allowed value"),F(g<=c,"value smaller than minimum allowed value")}function F(c,f){if(!c)throw new Error(f||"Failed assertion")}w._augment=function(c){return c._isBuffer=!0,c._get=c.get,c._set=c.set,c.get=k.get,c.set=k.set,c.write=k.write,c.toString=k.toString,c.toLocaleString=k.toString,c.toJSON=k.toJSON,c.copy=k.copy,c.slice=k.slice,c.readUInt8=k.readUInt8,c.readUInt16LE=k.readUInt16LE,c.readUInt16BE=k.readUInt16BE,c.readUInt32LE=k.readUInt32LE,c.readUInt32BE=k.readUInt32BE,c.readInt8=k.readInt8,c.readInt16LE=k.readInt16LE,c.readInt16BE=k.readInt16BE,c.readInt32LE=k.readInt32LE,c.readInt32BE=k.readInt32BE,c.readFloatLE=k.readFloatLE,c.readFloatBE=k.readFloatBE,c.readDoubleLE=k.readDoubleLE,c.readDoubleBE=k.readDoubleBE,c.writeUInt8=k.writeUInt8,c.writeUInt16LE=k.writeUInt16LE,c.writeUInt16BE=k.writeUInt16BE,c.writeUInt32LE=k.writeUInt32LE,c.writeUInt32BE=k.writeUInt32BE,c.writeInt8=k.writeInt8,c.writeInt16LE=k.writeInt16LE,c.writeInt16BE=k.writeInt16BE,c.writeInt32LE=k.writeInt32LE,c.writeInt32BE=k.writeInt32BE,c.writeFloatLE=k.writeFloatLE,c.writeFloatBE=k.writeFloatBE,c.writeDoubleLE=k.writeDoubleLE,c.writeDoubleBE=k.writeDoubleBE,c.fill=k.fill,c.inspect=k.inspect,c.toArrayBuffer=k.toArrayBuffer,c}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(n,i,e){(function(t,r,y,s,a,h,u,m,v){var y=n("buffer").Buffer,C=4,w=new y(C);w.fill(0),i.exports={hash:function(S,I,x,_){for(var R=I(function(l,O){l.length%C!=0&&(E=l.length+(C-l.length%C),l=y.concat([l,w],E));for(var E,j=[],B=O?l.readInt32BE:l.readInt32LE,M=0;M<l.length;M+=C)j.push(B.call(l,M));return j}(S=y.isBuffer(S)?S:new y(S),_),8*S.length),I=_,b=new y(x),D=I?b.writeInt32BE:b.writeInt32LE,d=0;d<R.length;d++)D.call(b,R[d],4*d,!0);return b}}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(n,i,e){(function(t,r,y,s,a,h,u,m,v){var y=n("buffer").Buffer,C=n("./sha"),w=n("./sha256"),S=n("./rng"),I={sha1:C,sha256:w,md5:n("./md5")},x=64,_=new y(x);function R(l,O){var E=I[l=l||"sha1"],j=[];return E||b("algorithm:",l,"is not yet supported"),{update:function(B){return y.isBuffer(B)||(B=new y(B)),j.push(B),B.length,this},digest:function(B){var M=y.concat(j),M=O?function(k,q,te){y.isBuffer(q)||(q=new y(q)),y.isBuffer(te)||(te=new y(te)),q.length>x?q=k(q):q.length<x&&(q=y.concat([q,_],x));for(var H=new y(x),K=new y(x),De=0;De<x;De++)H[De]=54^q[De],K[De]=92^q[De];return te=k(y.concat([H,te])),k(y.concat([K,te]))}(E,O,M):E(M);return j=null,B?M.toString(B):M}}}function b(){var l=[].slice.call(arguments).join(" ");throw new Error([l,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
|
|
6
|
+
`))}_.fill(0),e.createHash=function(l){return R(l)},e.createHmac=R,e.randomBytes=function(l,O){if(!O||!O.call)return new y(S(l));try{O.call(this,void 0,new y(S(l)))}catch(E){O(E)}};var D,d=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],p=function(l){e[l]=function(){b("sorry,",l,"is not implemented yet")}};for(D in d)p(d[D],D)}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(n,i,e){(function(t,r,o,s,a,h,u,m,v){var y=n("./helpers");function C(b,D){b[D>>5]|=128<<D%32,b[14+(D+64>>>9<<4)]=D;for(var d=1732584193,p=-271733879,l=-1732584194,O=271733878,E=0;E<b.length;E+=16){var j=d,B=p,M=l,k=O,d=S(d,p,l,O,b[E+0],7,-680876936),O=S(O,d,p,l,b[E+1],12,-389564586),l=S(l,O,d,p,b[E+2],17,606105819),p=S(p,l,O,d,b[E+3],22,-1044525330);d=S(d,p,l,O,b[E+4],7,-176418897),O=S(O,d,p,l,b[E+5],12,1200080426),l=S(l,O,d,p,b[E+6],17,-1473231341),p=S(p,l,O,d,b[E+7],22,-45705983),d=S(d,p,l,O,b[E+8],7,1770035416),O=S(O,d,p,l,b[E+9],12,-1958414417),l=S(l,O,d,p,b[E+10],17,-42063),p=S(p,l,O,d,b[E+11],22,-1990404162),d=S(d,p,l,O,b[E+12],7,1804603682),O=S(O,d,p,l,b[E+13],12,-40341101),l=S(l,O,d,p,b[E+14],17,-1502002290),d=I(d,p=S(p,l,O,d,b[E+15],22,1236535329),l,O,b[E+1],5,-165796510),O=I(O,d,p,l,b[E+6],9,-1069501632),l=I(l,O,d,p,b[E+11],14,643717713),p=I(p,l,O,d,b[E+0],20,-373897302),d=I(d,p,l,O,b[E+5],5,-701558691),O=I(O,d,p,l,b[E+10],9,38016083),l=I(l,O,d,p,b[E+15],14,-660478335),p=I(p,l,O,d,b[E+4],20,-405537848),d=I(d,p,l,O,b[E+9],5,568446438),O=I(O,d,p,l,b[E+14],9,-1019803690),l=I(l,O,d,p,b[E+3],14,-187363961),p=I(p,l,O,d,b[E+8],20,1163531501),d=I(d,p,l,O,b[E+13],5,-1444681467),O=I(O,d,p,l,b[E+2],9,-51403784),l=I(l,O,d,p,b[E+7],14,1735328473),d=x(d,p=I(p,l,O,d,b[E+12],20,-1926607734),l,O,b[E+5],4,-378558),O=x(O,d,p,l,b[E+8],11,-2022574463),l=x(l,O,d,p,b[E+11],16,1839030562),p=x(p,l,O,d,b[E+14],23,-35309556),d=x(d,p,l,O,b[E+1],4,-1530992060),O=x(O,d,p,l,b[E+4],11,1272893353),l=x(l,O,d,p,b[E+7],16,-155497632),p=x(p,l,O,d,b[E+10],23,-1094730640),d=x(d,p,l,O,b[E+13],4,681279174),O=x(O,d,p,l,b[E+0],11,-358537222),l=x(l,O,d,p,b[E+3],16,-722521979),p=x(p,l,O,d,b[E+6],23,76029189),d=x(d,p,l,O,b[E+9],4,-640364487),O=x(O,d,p,l,b[E+12],11,-421815835),l=x(l,O,d,p,b[E+15],16,530742520),d=_(d,p=x(p,l,O,d,b[E+2],23,-995338651),l,O,b[E+0],6,-198630844),O=_(O,d,p,l,b[E+7],10,1126891415),l=_(l,O,d,p,b[E+14],15,-1416354905),p=_(p,l,O,d,b[E+5],21,-57434055),d=_(d,p,l,O,b[E+12],6,1700485571),O=_(O,d,p,l,b[E+3],10,-1894986606),l=_(l,O,d,p,b[E+10],15,-1051523),p=_(p,l,O,d,b[E+1],21,-2054922799),d=_(d,p,l,O,b[E+8],6,1873313359),O=_(O,d,p,l,b[E+15],10,-30611744),l=_(l,O,d,p,b[E+6],15,-1560198380),p=_(p,l,O,d,b[E+13],21,1309151649),d=_(d,p,l,O,b[E+4],6,-145523070),O=_(O,d,p,l,b[E+11],10,-1120210379),l=_(l,O,d,p,b[E+2],15,718787259),p=_(p,l,O,d,b[E+9],21,-343485551),d=R(d,j),p=R(p,B),l=R(l,M),O=R(O,k)}return Array(d,p,l,O)}function w(b,D,d,p,l,O){return R((D=R(R(D,b),R(p,O)))<<l|D>>>32-l,d)}function S(b,D,d,p,l,O,E){return w(D&d|~D&p,b,D,l,O,E)}function I(b,D,d,p,l,O,E){return w(D&p|d&~p,b,D,l,O,E)}function x(b,D,d,p,l,O,E){return w(D^d^p,b,D,l,O,E)}function _(b,D,d,p,l,O,E){return w(d^(D|~p),b,D,l,O,E)}function R(b,D){var d=(65535&b)+(65535&D);return(b>>16)+(D>>16)+(d>>16)<<16|65535&d}i.exports=function(b){return y.hash(b,C,16)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(n,i,e){(function(t,r,o,s,a,h,u,m,v){var y;i.exports=y||function(C){for(var w,S=new Array(C),I=0;I<C;I++)!(3&I)&&(w=4294967296*Math.random()),S[I]=w>>>((3&I)<<3)&255;return S}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(n,i,e){(function(t,r,o,s,a,h,u,m,v){var y=n("./helpers");function C(I,x){I[x>>5]|=128<<24-x%32,I[15+(x+64>>9<<4)]=x;for(var _,R,b,D=Array(80),d=1732584193,p=-271733879,l=-1732584194,O=271733878,E=-1009589776,j=0;j<I.length;j+=16){for(var B=d,M=p,k=l,q=O,te=E,H=0;H<80;H++){D[H]=H<16?I[j+H]:S(D[H-3]^D[H-8]^D[H-14]^D[H-16],1);var K=w(w(S(d,5),(K=p,R=l,b=O,(_=H)<20?K&R|~K&b:!(_<40)&&_<60?K&R|K&b|R&b:K^R^b)),w(w(E,D[H]),(_=H)<20?1518500249:_<40?1859775393:_<60?-1894007588:-899497514)),E=O,O=l,l=S(p,30),p=d,d=K}d=w(d,B),p=w(p,M),l=w(l,k),O=w(O,q),E=w(E,te)}return Array(d,p,l,O,E)}function w(I,x){var _=(65535&I)+(65535&x);return(I>>16)+(x>>16)+(_>>16)<<16|65535&_}function S(I,x){return I<<x|I>>>32-x}i.exports=function(I){return y.hash(I,C,20,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(n,i,e){(function(t,r,o,s,a,h,u,m,v){function y(x,_){var R=(65535&x)+(65535&_);return(x>>16)+(_>>16)+(R>>16)<<16|65535&R}function C(x,_){var R,b=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),D=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),d=new Array(64);x[_>>5]|=128<<24-_%32,x[15+(_+64>>9<<4)]=_;for(var p,l,O=0;O<x.length;O+=16){for(var E=D[0],j=D[1],B=D[2],M=D[3],k=D[4],q=D[5],te=D[6],H=D[7],K=0;K<64;K++)d[K]=K<16?x[K+O]:y(y(y((l=d[K-2],S(l,17)^S(l,19)^I(l,10)),d[K-7]),(l=d[K-15],S(l,7)^S(l,18)^I(l,3))),d[K-16]),R=y(y(y(y(H,S(l=k,6)^S(l,11)^S(l,25)),k&q^~k&te),b[K]),d[K]),p=y(S(p=E,2)^S(p,13)^S(p,22),E&j^E&B^j&B),H=te,te=q,q=k,k=y(M,R),M=B,B=j,j=E,E=y(R,p);D[0]=y(E,D[0]),D[1]=y(j,D[1]),D[2]=y(B,D[2]),D[3]=y(M,D[3]),D[4]=y(k,D[4]),D[5]=y(q,D[5]),D[6]=y(te,D[6]),D[7]=y(H,D[7])}return D}var w=n("./helpers"),S=function(x,_){return x>>>_|x<<32-_},I=function(x,_){return x>>>_};i.exports=function(x){return w.hash(x,C,32,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(n,i,e){(function(t,r,o,s,a,h,u,m,v){e.read=function(y,C,w,S,O){var x,_,R=8*O-S-1,b=(1<<R)-1,D=b>>1,d=-7,p=w?O-1:0,l=w?-1:1,O=y[C+p];for(p+=l,x=O&(1<<-d)-1,O>>=-d,d+=R;0<d;x=256*x+y[C+p],p+=l,d-=8);for(_=x&(1<<-d)-1,x>>=-d,d+=S;0<d;_=256*_+y[C+p],p+=l,d-=8);if(x===0)x=1-D;else{if(x===b)return _?NaN:1/0*(O?-1:1);_+=Math.pow(2,S),x-=D}return(O?-1:1)*_*Math.pow(2,x-S)},e.write=function(y,C,w,S,I,E){var _,R,b=8*E-I-1,D=(1<<b)-1,d=D>>1,p=I===23?Math.pow(2,-24)-Math.pow(2,-77):0,l=S?0:E-1,O=S?1:-1,E=C<0||C===0&&1/C<0?1:0;for(C=Math.abs(C),isNaN(C)||C===1/0?(R=isNaN(C)?1:0,_=D):(_=Math.floor(Math.log(C)/Math.LN2),C*(S=Math.pow(2,-_))<1&&(_--,S*=2),2<=(C+=1<=_+d?p/S:p*Math.pow(2,1-d))*S&&(_++,S/=2),D<=_+d?(R=0,_=D):1<=_+d?(R=(C*S-1)*Math.pow(2,I),_+=d):(R=C*Math.pow(2,d-1)*Math.pow(2,I),_=0));8<=I;y[w+l]=255&R,l+=O,R/=256,I-=8);for(_=_<<I|R,b+=I;0<b;y[w+l]=255&_,l+=O,_/=256,b-=8);y[w+l-O]|=128*E}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(n,i,e){(function(t,r,o,s,a,h,u,m,v){var y,C,w;function S(){}(t=i.exports={}).nextTick=(C=typeof window<"u"&&window.setImmediate,w=typeof window<"u"&&window.postMessage&&window.addEventListener,C?function(I){return window.setImmediate(I)}:w?(y=[],window.addEventListener("message",function(I){var x=I.source;x!==window&&x!==null||I.data!=="process-tick"||(I.stopPropagation(),0<y.length&&y.shift()())},!0),function(I){y.push(I),window.postMessage("process-tick","*")}):function(I){setTimeout(I,0)}),t.title="browser",t.browser=!0,t.env={},t.argv=[],t.on=S,t.addListener=S,t.once=S,t.off=S,t.removeListener=S,t.removeAllListeners=S,t.emit=S,t.binding=function(I){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(I){throw new Error("process.chdir is not supported")}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1)})});var qe={};Zi(qe,{__addDisposableResource:()=>So,__assign:()=>vn,__asyncDelegator:()=>po,__asyncGenerator:()=>ho,__asyncValues:()=>mo,__await:()=>it,__awaiter:()=>so,__classPrivateFieldGet:()=>wo,__classPrivateFieldIn:()=>xo,__classPrivateFieldSet:()=>vo,__createBinding:()=>Sn,__decorate:()=>io,__disposeResources:()=>Oo,__esDecorate:()=>oa,__exportStar:()=>co,__extends:()=>to,__generator:()=>ao,__importDefault:()=>bo,__importStar:()=>yo,__makeTemplateObject:()=>go,__metadata:()=>oo,__param:()=>ro,__propKey:()=>aa,__read:()=>Ri,__rest:()=>no,__runInitializers:()=>sa,__setFunctionName:()=>ca,__spread:()=>lo,__spreadArray:()=>fo,__spreadArrays:()=>uo,__values:()=>xn,default:()=>ua});function to(n,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");Pi(n,i);function e(){this.constructor=n}n.prototype=i===null?Object.create(i):(e.prototype=i.prototype,new e)}function no(n,i){var e={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&i.indexOf(t)<0&&(e[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(n);r<t.length;r++)i.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(n,t[r])&&(e[t[r]]=n[t[r]]);return e}function io(n,i,e,t){var r=arguments.length,o=r<3?i:t===null?t=Object.getOwnPropertyDescriptor(i,e):t,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,i,e,t);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(o=(r<3?s(o):r>3?s(i,e,o):s(i,e))||o);return r>3&&o&&Object.defineProperty(i,e,o),o}function ro(n,i){return function(e,t){i(e,t,n)}}function oa(n,i,e,t,r,o){function s(x){if(x!==void 0&&typeof x!="function")throw new TypeError("Function expected");return x}for(var a=t.kind,h=a==="getter"?"get":a==="setter"?"set":"value",u=!i&&n?t.static?n:n.prototype:null,m=i||(u?Object.getOwnPropertyDescriptor(u,t.name):{}),v,y=!1,C=e.length-1;C>=0;C--){var w={};for(var S in t)w[S]=S==="access"?{}:t[S];for(var S in t.access)w.access[S]=t.access[S];w.addInitializer=function(x){if(y)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(x||null))};var I=(0,e[C])(a==="accessor"?{get:m.get,set:m.set}:m[h],w);if(a==="accessor"){if(I===void 0)continue;if(I===null||typeof I!="object")throw new TypeError("Object expected");(v=s(I.get))&&(m.get=v),(v=s(I.set))&&(m.set=v),(v=s(I.init))&&r.unshift(v)}else(v=s(I))&&(a==="field"?r.unshift(v):m[h]=v)}u&&Object.defineProperty(u,t.name,m),y=!0}function sa(n,i,e){for(var t=arguments.length>2,r=0;r<i.length;r++)e=t?i[r].call(n,e):i[r].call(n);return t?e:void 0}function aa(n){return typeof n=="symbol"?n:"".concat(n)}function ca(n,i,e){return typeof i=="symbol"&&(i=i.description?"[".concat(i.description,"]"):""),Object.defineProperty(n,"name",{configurable:!0,value:e?"".concat(e," ",i):i})}function oo(n,i){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,i)}function so(n,i,e,t){function r(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function a(m){try{u(t.next(m))}catch(v){s(v)}}function h(m){try{u(t.throw(m))}catch(v){s(v)}}function u(m){m.done?o(m.value):r(m.value).then(a,h)}u((t=t.apply(n,i||[])).next())})}function ao(n,i){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},t,r,o,s;return s={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(u){return function(m){return h([u,m])}}function h(u){if(t)throw new TypeError("Generator is already executing.");for(;s&&(s=0,u[0]&&(e=0)),e;)try{if(t=1,r&&(o=u[0]&2?r.return:u[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,u[1])).done)return o;switch(r=0,o&&(u=[u[0]&2,o.value]),u[0]){case 0:case 1:o=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,r=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(o=e.trys,!(o=o.length>0&&o[o.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!o||u[1]>o[0]&&u[1]<o[3])){e.label=u[1];break}if(u[0]===6&&e.label<o[1]){e.label=o[1],o=u;break}if(o&&e.label<o[2]){e.label=o[2],e.ops.push(u);break}o[2]&&e.ops.pop(),e.trys.pop();continue}u=i.call(n,e)}catch(m){u=[6,m],r=0}finally{t=o=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function co(n,i){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(i,e)&&Sn(i,n,e)}function xn(n){var i=typeof Symbol=="function"&&Symbol.iterator,e=i&&n[i],t=0;if(e)return e.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&t>=n.length&&(n=void 0),{value:n&&n[t++],done:!n}}};throw new TypeError(i?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ri(n,i){var e=typeof Symbol=="function"&&n[Symbol.iterator];if(!e)return n;var t=e.call(n),r,o=[],s;try{for(;(i===void 0||i-- >0)&&!(r=t.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(s)throw s.error}}return o}function lo(){for(var n=[],i=0;i<arguments.length;i++)n=n.concat(Ri(arguments[i]));return n}function uo(){for(var n=0,i=0,e=arguments.length;i<e;i++)n+=arguments[i].length;for(var t=Array(n),r=0,i=0;i<e;i++)for(var o=arguments[i],s=0,a=o.length;s<a;s++,r++)t[r]=o[s];return t}function fo(n,i,e){if(e||arguments.length===2)for(var t=0,r=i.length,o;t<r;t++)(o||!(t in i))&&(o||(o=Array.prototype.slice.call(i,0,t)),o[t]=i[t]);return n.concat(o||Array.prototype.slice.call(i))}function it(n){return this instanceof it?(this.v=n,this):new it(n)}function ho(n,i,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e.apply(n,i||[]),r,o=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(y){t[y]&&(r[y]=function(C){return new Promise(function(w,S){o.push([y,C,w,S])>1||a(y,C)})})}function a(y,C){try{h(t[y](C))}catch(w){v(o[0][3],w)}}function h(y){y.value instanceof it?Promise.resolve(y.value.v).then(u,m):v(o[0][2],y)}function u(y){a("next",y)}function m(y){a("throw",y)}function v(y,C){y(C),o.shift(),o.length&&a(o[0][0],o[0][1])}}function po(n){var i,e;return i={},t("next"),t("throw",function(r){throw r}),t("return"),i[Symbol.iterator]=function(){return this},i;function t(r,o){i[r]=n[r]?function(s){return(e=!e)?{value:it(n[r](s)),done:!1}:o?o(s):s}:o}}function mo(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n[Symbol.asyncIterator],e;return i?i.call(n):(n=typeof xn=="function"?xn(n):n[Symbol.iterator](),e={},t("next"),t("throw"),t("return"),e[Symbol.asyncIterator]=function(){return this},e);function t(o){e[o]=n[o]&&function(s){return new Promise(function(a,h){s=n[o](s),r(a,h,s.done,s.value)})}}function r(o,s,a,h){Promise.resolve(h).then(function(u){o({value:u,done:a})},s)}}function go(n,i){return Object.defineProperty?Object.defineProperty(n,"raw",{value:i}):n.raw=i,n}function yo(n){if(n&&n.__esModule)return n;var i={};if(n!=null)for(var e in n)e!=="default"&&Object.prototype.hasOwnProperty.call(n,e)&&Sn(i,n,e);return la(i,n),i}function bo(n){return n&&n.__esModule?n:{default:n}}function wo(n,i,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof i=="function"?n!==i||!t:!i.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(n):t?t.value:i.get(n)}function vo(n,i,e,t,r){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof i=="function"?n!==i||!r:!i.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?r.call(n,e):r?r.value=e:i.set(n,e),e}function xo(n,i){if(i===null||typeof i!="object"&&typeof i!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof n=="function"?i===n:n.has(i)}function So(n,i,e){if(i!=null){if(typeof i!="object"&&typeof i!="function")throw new TypeError("Object expected.");var t;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");t=i[Symbol.asyncDispose]}if(t===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");t=i[Symbol.dispose]}if(typeof t!="function")throw new TypeError("Object not disposable.");n.stack.push({value:i,dispose:t,async:e})}else e&&n.stack.push({async:!0});return i}function Oo(n){function i(t){n.error=n.hasError?new da(t,n.error,"An error was suppressed during disposal."):t,n.hasError=!0}function e(){for(;n.stack.length;){var t=n.stack.pop();try{var r=t.dispose&&t.dispose.call(t.value);if(t.async)return Promise.resolve(r).then(e,function(o){return i(o),e()})}catch(o){i(o)}}if(n.hasError)throw n.error}return e()}var Pi,vn,Sn,la,da,ua,He=Ko(()=>{Pi=function(n,i){return Pi=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},Pi(n,i)};vn=function(){return vn=Object.assign||function(i){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(i[o]=e[o])}return i},vn.apply(this,arguments)};Sn=Object.create?function(n,i,e,t){t===void 0&&(t=e);var r=Object.getOwnPropertyDescriptor(i,e);(!r||("get"in r?!i.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return i[e]}}),Object.defineProperty(n,t,r)}:function(n,i,e,t){t===void 0&&(t=e),n[t]=i[e]};la=Object.create?function(n,i){Object.defineProperty(n,"default",{enumerable:!0,value:i})}:function(n,i){n.default=i};da=typeof SuppressedError=="function"?SuppressedError:function(n,i,e){var t=new Error(e);return t.name="SuppressedError",t.error=n,t.suppressed=i,t};ua={__extends:to,__assign:vn,__rest:no,__decorate:io,__param:ro,__metadata:oo,__awaiter:so,__generator:ao,__createBinding:Sn,__exportStar:co,__values:xn,__read:Ri,__spread:lo,__spreadArrays:uo,__spreadArray:fo,__await:it,__asyncGenerator:ho,__asyncDelegator:po,__asyncValues:mo,__makeTemplateObject:go,__importStar:yo,__importDefault:bo,__classPrivateFieldGet:wo,__classPrivateFieldSet:vo,__classPrivateFieldIn:xo,__addDisposableResource:So,__disposeResources:Oo}});var _o=oe(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0})});var Ti=oe(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.invokeEventHandlersAsync=_e.invokeEventHandlers=_e.eventHandlerSafeInvokeAsync=_e.eventHandlerSafeInvoke=void 0;var Do=(He(),Ge(qe));function Eo(n,i,e){try{return n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}}_e.eventHandlerSafeInvoke=Eo;function Fi(n,i,e){return(0,Do.__awaiter)(this,void 0,void 0,function*(){try{return yield n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}})}_e.eventHandlerSafeInvokeAsync=Fi;function fa(n,i,e,t){for(let r of n){let{succeeded:o,error:s}=Eo(r,i,e);if(!o&&t?.swallowExceptions!==!0)throw s}}_e.invokeEventHandlers=fa;function ha(n,i,e,t){return(0,Do.__awaiter)(this,void 0,void 0,function*(){if(t?.parallelize===!1)for(let r of n){let{succeeded:o,error:s}=yield Fi(r,i,e);if(!o&&t?.swallowExceptions!==!0)throw s}else{let r=[];for(let o of n)r.push(Fi(o,i,e).then(({succeeded:s,error:a})=>{if(!s&&t?.swallowExceptions!==!0)throw a}));yield Promise.all(r)}})}_e.invokeEventHandlersAsync=ha});var Po=oe(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.TypedEvent=void 0;var pa=(He(),Ge(qe)),Co=Ti(),Ao={swallowExceptions:!1,parallelize:!0},ki=class{constructor(){this._handlers=[]}attach(i){this._handlers.push(i)}detach(i){this.tryRemoveHandler(i)}invoke(i,e,t=Ao){(0,Co.invokeEventHandlers)(this._handlers,i,e,t)}invokeAsync(i,e,t=Ao){return(0,pa.__awaiter)(this,void 0,void 0,function*(){yield(0,Co.invokeEventHandlersAsync)(this._handlers,i,e,t)})}tryRemoveHandler(i){let e=this._handlers.findIndex(t=>t===i);e>=0&&this._handlers.splice(e,1)}};On.TypedEvent=ki});var ji=oe(Bi=>{"use strict";Object.defineProperty(Bi,"__esModule",{value:!0});var ma=(He(),Ge(qe));(0,ma.__exportStar)(Po(),Bi)});var Ro=oe(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.FinalizationRegistryMissingError=void 0;var Mi=class extends Error{};In.FinalizationRegistryMissingError=Mi});var Ui=oe(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.WeakHandlerHolder=void 0;var ga=Ro(),Li=class{constructor(i){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(i)}catch(e){throw e.name==="FinalizationRegistry"?new ga.FinalizationRegistryMissingError("FinalizationRegistry is not defined. Weak Events cannot be used. Please consult 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry' for compatibility information"):e}}getWeakHandler(i,e){let t=new WeakRef(e);return this._finalizationRegistry.register(e,{eventSource:i,handlerRef:t},t),this._refs.push(t),t}releaseWeakHandler(i){let t=this._refs.find(r=>r?.deref()===i)||new WeakRef(i);return this._finalizationRegistry.unregister(t),t}unregisterRef(i){this._finalizationRegistry.unregister(i)}};_n.WeakHandlerHolder=Li});var Fo=oe(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.WeakEvent=void 0;var Vi=(He(),Ge(qe)),ya=ji(),ba=Ui(),Ni=Ti(),wa={swallowExceptions:!1,parallelize:!0},$i=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new ya.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new ba.WeakHandlerHolder(i=>{this.onHandlerFinalizer(i)})}invoke(i,e,t){for(let r of this._handlers){let o=r?.deref();if(o){let{succeeded:s,error:a}=(0,Ni.eventHandlerSafeInvoke)(o,i,e);if(!s&&t?.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}}invokeAsync(i,e,t=wa){return(0,Vi.__awaiter)(this,void 0,void 0,function*(){t?.parallelize===!1?yield this.sequentialInvokeAsync(i,e,t):yield this.parallelInvokeAsync(i,e,t)})}sequentialInvokeAsync(i,e,t){return(0,Vi.__awaiter)(this,void 0,void 0,function*(){for(let r of this._handlers){let o=r?.deref();if(o){let{succeeded:s,error:a}=yield(0,Ni.eventHandlerSafeInvokeAsync)(o,i,e);if(!s&&t.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}})}parallelInvokeAsync(i,e,t){return(0,Vi.__awaiter)(this,void 0,void 0,function*(){let r=[];for(let o of this._handlers){let s=o?.deref();s?r.push((0,Ni.eventHandlerSafeInvokeAsync)(s,i,e).then(({succeeded:a,error:h})=>{if(!a&&t.swallowExceptions!==!0)throw h})):this.releaseHandler(o)}yield Promise.all(r)})}attach(i){this._handlers.push(this._refHolder.getWeakHandler(this,i))}detach(i){let e=this._refHolder.releaseWeakHandler(i);this.tryRemoveHandlerRef(e)}onHandlerFinalizer(i){this.tryRemoveHandlerRef(i?.handlerRef),this._handlerFinalizedEvent.invokeAsync(this,i,{swallowExceptions:!0})}tryRemoveHandlerRef(i){let e=this._handlers.findIndex(t=>t===i);e>=0&&this._handlers.splice(e,1)}releaseHandler(i){this._refHolder.unregisterRef(i),this.tryRemoveHandlerRef(i)}};Dn.WeakEvent=$i});var ko=oe(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});var To=(He(),Ge(qe));(0,To.__exportStar)(Ui(),En);(0,To.__exportStar)(Fo(),En)});var Bo=oe(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});var zi=(He(),Ge(qe));(0,zi.__exportStar)(_o(),Dt);(0,zi.__exportStar)(ji(),Dt);(0,zi.__exportStar)(ko(),Dt)});var Qi={};Zi(Qi,{Client:()=>We,ClientDescriptor:()=>qn,Entity:()=>ue,EntityFile:()=>de,MigrationPathError:()=>et,ServerSync:()=>ot,Storage:()=>We,StorageDescriptor:()=>qn,collection:()=>wi,createDefaultMigration:()=>vi,createMigration:()=>xi,migrate:()=>Jt,schema:()=>yt});var gr=Je(ct(),1),Mt=4,dt=36;function fr(n){return n.toString(dt).padStart(Mt,"0")}function Yo(n){return n.toString().padStart(6,"0")}var Tt=class{constructor(){this.latest={time:Date.now(),counter:0,node:Xo()},this.zeroCounter=0,this.now=i=>(this.latest=pr(this.latest),this.get(i,this.latest)),this.OLD_now=i=>(this.latest=pr(this.latest),Yo(i)+es(this.latest)),this.timerState=()=>this.latest,this.update=i=>{let e=i.slice(Mt);this.latest=Zo(this.latest,yr(e))},this.get=(i,e)=>fr(i)+hr(e),this.zero=i=>fr(i)+hr({time:0,counter:this.zeroCounter++,node:this.latest.node}),this.getWallClockTime=ti}},kt=class extends Error{constructor(...i){super(),this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(i).join(" ")}},Bt=class extends Error{constructor(){super(),this.type="OverflowError",this.message="timestamp counter overflow"}},Xn=4,Zn=7,jt=60*1e3,lt=9;function Xo(){return gr.default.slug().padStart(Zn,"0").slice(0,Zn)}function hr(n){let i=new Date(n.time).getTime().toString(dt).padStart(lt,"0"),e=n.counter.toString(dt).padStart(Xn,"0"),t=n.node.padStart(Zn,"0");return`${i}${e}${t}`}function pr(n){let i=Date.now(),e=Math.max(n.time,i),t=n.time===e?n.counter+1:0;if(e-i>jt)throw new kt(e,i,jt);if(t>65535)throw new Bt;return{time:e,counter:t,node:n.node}}function Zo(n,i){let e=Date.now(),t=Math.max(e,Math.max(n.time,i.time)),r=Math.max(n.counter,i.counter),o;if(n.time===t&&i.time===t?o=r+1:n.time===t?o=n.counter+1:i.time===t?o=i.counter+1:o=0,t-e>jt)throw new kt(t,e,jt);if(o>65535)throw new Bt;return{time:t,counter:o,node:n.node}}function yr(n){let i=n.slice(0,lt),e=n.slice(lt,lt+Xn),t=n.slice(lt+Xn),r=parseInt(i,dt),o=parseInt(e,dt);if(isNaN(r)||isNaN(o))throw new Error("invalid clock format");return{time:r,counter:o,node:t}}function es(n){let i=new Date(n.time).toISOString(),e=n.counter.toString(16).toUpperCase().padStart(4,"0"),t=n.node.padStart(16,"0");return`${i}-${e}-${t}`}function mr(n){return parseInt(n.slice(0,Mt),36)}function ei(n,i){return mr(n)-mr(i)}function ti(n){return yr(n.slice(Mt)).time}function be(n){return n&&n["@@type"]==="file"}function Lt(n){return{"@@type":"file",id:n}}var Ut,ts=new Uint8Array(16);function ni(){if(!Ut&&(Ut=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Ut))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ut(ts)}var br=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function ns(n){return typeof n=="string"&&br.test(n)}var wr=ns;var ee=[];for(Vt=0;Vt<256;++Vt)ee.push((Vt+256).toString(16).substr(1));var Vt;function is(n){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(ee[n[i+0]]+ee[n[i+1]]+ee[n[i+2]]+ee[n[i+3]]+"-"+ee[n[i+4]]+ee[n[i+5]]+"-"+ee[n[i+6]]+ee[n[i+7]]+"-"+ee[n[i+8]]+ee[n[i+9]]+"-"+ee[n[i+10]]+ee[n[i+11]]+ee[n[i+12]]+ee[n[i+13]]+ee[n[i+14]]+ee[n[i+15]]).toLowerCase();if(!wr(e))throw TypeError("Stringified UUID is invalid");return e}var vr=is;function rs(n,i,e){n=n||{};var t=n.random||(n.rng||ni)();if(t[6]=t[6]&15|64,t[8]=t[8]&63|128,i){e=e||0;for(var r=0;r<16;++r)i[e+r]=t[r];return i}return vr(t)}var ut=rs;function Q(n){return xe(n)||be(n)}function Ye(n,i){return n===i?!0:!(!Q(n)||!Q(i)||n["@@type"]!==i["@@type"]||n.id!==i.id)}var Ir=Je(Or(),1);function os(n,i){return typeof i!="object"||i===null||Array.isArray(i)?i:Object.fromEntries(Object.entries(i).sort(([e],[t])=>e<t?-1:e>t?1:0))}function ft(n){return JSON.stringify(n,os)}function ae(n,i=!0){if(N(n)||Array.isArray(n)){let e=he(n),t;if(Array.isArray(n))t=n.map(r=>ae(r,i));else{t={};for(let[r,o]of Object.entries(n))t[r]=ae(o,i)}return i&&e&&$(t,e),t}return n}function Re(n){return(0,Ir.default)(n)}function N(n){return n&&typeof n=="object"}function _r(n){for(var i=[],e=[n],t=0;e.length;){var r=e.pop();if(typeof r=="boolean")t+=4;else if(typeof r=="string")t+=r.length*2;else if(typeof r=="number")t+=8;else if(typeof r=="object"&&i.indexOf(r)===-1){i.push(r);for(var o in r)e.push(r[o])}}return t}function L(n,i="assertion failed"){if(!n)throw new Error(i)}function Nt(n=16){return ut().replace("-","").slice(0,n)}function Dr(n,i){for(let e=n.length-1;e>=0;e--)if(i(n[e]))return e;return-1}function Er(n,i){let e;return function(...t){let r=this;clearTimeout(e),e=setTimeout(()=>n.apply(r,t),i)}}var je="__@@oid_do_not_use",Oe="@@id",ss="/",pt=":",ri=new WeakMap;function ne(n){let i=he(n);return L(!!i,`Object ${JSON.stringify(n)} does not have an OID assigned to it`),i}function he(n){var i,e;if(N(n))return(e=(i=ri.get(n))!==null&&i!==void 0?i:n[Oe])!==null&&e!==void 0?e:n[je]}function $(n,i){return L(N(n),`Only objects can be assigned OIDs, received ${JSON.stringify(n)}`),oi(n)&&Kt(n),ri.set(n,i),n}function oi(n){return!!he(n)}function Kt(n){return ri.delete(n),n}function si(n){return n===Oe||n===je}function ai(n,i,e){if(oi(n))return ne(n);{let t=Se(i,e);return $(n,t),t}}function Cr(n,i,e){if(oi(n)){let t=ne(n);if(Ee(t,i))return ne(n);{let r=Se(i,e);return $(n,r),r}}else{let t=Se(i,e);return $(n,t),t}}var ii={".":"˙","/":"&slash;",":":":"};function Ar(n){return n.replace(/[/]/g,ii["/"]).replace(/[:]/g,ii[":"]).replace(/[.]/g,ii["."])}function Pr(n){return n.replace(/&slash;/g,"/").replace(/:/g,":").replace(/˙/g,".")}function Z(n,i,e){let t=Ar(n)+ss+Ar(i);return e&&(t+=pt+e),t}function Se(n,i=ds){let{collection:e,id:t}=me(n);return Z(e,t,i())}function me(n){let[i,e]=n.split(pt),[t,r,...o]=i.split("/");o.length&&(r+="/"+o.join("/"));let s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:Pr(t),id:Pr(s),subId:e}}function Xe(n,i){let e=ne(n);if(Array.isArray(n)){let t;for(let r=0;r<n.length;r++)t=n[r],N(t)&&!Q(t)&&(Cr(t,e,i),Xe(t,i))}else if(N(n)&&!Q(n))for(let t of Object.keys(n))N(n[t])&&!Q(n[t])&&(Cr(n[t],e,i),Xe(n[t],i))}function as(n){if(N(n))return n[Oe]||n[je]}function cs(n){return N(n)&&(delete n[je],delete n[Oe]),n}function ls(n){let i=as(n);i&&$(n,i)}function ht(n){if(ls(n),cs(n),Array.isArray(n))for(let i=0;i<n.length;i++)ht(n[i]);else if(N(n))for(let i of Object.keys(n))ht(n[i])}function $t(n){if(Kt(n),Array.isArray(n))for(let i=0;i<n.length;i++)$t(n[i]);else if(N(n))for(let i of Object.keys(n))$t(n[i])}function ds(){return ut().slice(0,8)}function pe(n){return{"@@type":"ref",id:n}}function zt(n,i=new Map){if(Array.isArray(n)){let e=ne(n),t=$([],e);for(let r=0;r<n.length;r++){let o=n[r];if(N(o)){if(xe(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(be(o)){t[r]=o;continue}else{let s=ne(o);t[r]=pe(s),zt(o,i)}}else t[r]=o}i.set(e,t)}else if(N(n)&&!Q(n)){let e=ne(n),t=$({},e);for(let r of Object.keys(n)){let o=n[r];if(N(o)){if(xe(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(be(o))t[r]=o;else{let s=ne(o);t[r]=pe(s),zt(o,i)}}else t[r]=o}i.set(e,t)}else Q(n);return i}function z(n){return n.split(".")[0].split(pt)[0]}function ci(n){let i=z(n),e=Se(i,()=>"\uFFFF");return[`${i}${pt}`,e]}function li(n){let i=z(n);return[`${i}.`,`${i}.\uFFFF`]}function Ee(n,i){return z(n)===z(i)}function us(n){let{collection:i,id:e,subId:t}=me(n);return Z(i,e,t)}var fs=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function hs(n){return n.replaceAll(fs,i=>{let e=i.slice(1,i.length-1);return`"${us(e)}"`})}function di(n){return JSON.parse(hs(JSON.stringify(n)))}function Rr(n){return!n.includes(pt)}function xe(n){return n&&typeof n=="object"&&n["@@type"]==="ref"}function ui(n){return N(n)&&!Q(n)}function ps(n,i){return n===i?!0:Q(n)&&Q(i)?Ye(n,i):!1}function mt(n,i,e,t,r=[],o={}){let s=ne(n);function a(h,u,m){if(!ui(u))ps(u,m)||r.push({oid:s,timestamp:e(),data:{op:"set",name:h,value:u}});else{let v=he(m),y=he(u);y&&!Ee(s,y)?(u=ae(u,!1),y=Se(s,t),$(u,y)):o.mergeUnknownObjects?!y&&v?($(u,v),y=v):y=ai(u,s,t):y=ai(u,s,t),L(!!y,"Error: no value OID was resolved during diff. This is a bug in Verdant."),L(Ee(s,y),`Error: value OID ${y} is not related to parent OID ${s}. This is a bug in Verdant.`),m===void 0||y!==v?(Fe(u,y,e,t,r),r.push({oid:s,timestamp:e(),data:{op:"set",name:h,value:pe(y)}}),v!==void 0&&r.push({oid:v,timestamp:e(),data:{op:"delete"}})):mt(m,u,e,t,r,o)}}if(Array.isArray(n)&&Array.isArray(i)){for(let u=0;u<i.length;u++){let m=i[u],v=n[u];a(u,m,v)}let h=n.length-i.length;if(h>0){for(let u=i.length;u<n.length;u++){let m=n[u],v=he(m);v&&r.push({oid:v,timestamp:e(),data:{op:"delete"}})}r.push({oid:s,timestamp:e(),data:{op:"list-delete",index:i.length,count:h}})}}else{if(Array.isArray(n)||Array.isArray(i))throw new Error("Cannot diff an array with an object");if(ui(n)&&ui(i)){let h=new Set(Object.keys(n));for(let[u,m]of Object.entries(i)){if(m===void 0&&o.defaultUndefined||(h.delete(u),si(u)))continue;let v=n[u];a(u,m,v)}if(!o.defaultUndefined)for(let u of h)si(u)||r.push({oid:s,timestamp:e(),data:{op:"remove",name:u}})}}return r}function Fe(n,i,e,t,r=[]){$(n,i),Xe(n,t);let o=zt(n);for(let s of o.keys()){let a=o.get(s);r.push({oid:s,timestamp:e(),data:{op:"initialize",value:Kt(a)}})}return r}function gt(n){let i={};for(let e of n)e.oid in i?i[e.oid].push(e):i[e.oid]=[e];return i}function Tr(n){let i={};for(let e of n){let t=z(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function kr(n){let i={};for(let e of n){let t=z(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function Me(n){return Array.isArray(n)?!0:(console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(n)}. This suggests your data is changing from a list to an object over time. (OID: ${he(n)})`),!1)}function Le(n,i,e){if(n==null&&i.op!=="initialize")return n;let t=n,r,o;function s(a){e&&Q(a)&&e.push(a)}switch(i.op){case"set":s(t[i.name]),t[i.name]=i.value;break;case"remove":s(t[i.name]),delete t[i.name];break;case"list-push":Me(n)&&n.push(i.value);break;case"list-delete":Me(n)&&(s(n[i.index]),n.splice(i.index,i.count));break;case"list-move-by-index":Me(n)&&(o=n.splice(i.from,1),n.splice(i.to,0,o[0]));break;case"list-remove":if(Me(n))do{let a=i.value;i.only==="last"?xe(a)?r=Dr(n,h=>h.id===a.id):r=n.lastIndexOf(a):xe(a)?r=n.findIndex(h=>h.id===a.id):r=n.indexOf(a),r!==-1&&(s(n[r]),n.splice(r,1))}while(!i.only&&r!==-1);break;case"list-add":Me(n)&&(n.some(h=>xe(h)&&xe(i.value)?h.id===i.value.id:h===i.value)||n.push(i.value));break;case"list-move-by-ref":Me(n)&&(r=n.findIndex(a=>Ye(a,i.value)),o=n.splice(r,1),n.splice(i.index,0,o[0]));break;case"list-insert":if(Me(n)){if(!i.value&&!i.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(i)}`);i.value?n.splice(i.index,0,i.value):n.splice(i.index,0,...i.values)}break;case"delete":Array.isArray(n)?n.forEach(s):N(n)&&Object.values(n||{}).forEach(s);return;case"initialize":return ae(i.value);case"touch":return n;default:throw new Error(`Unsupported patch operation: ${i.op}`)}return n}function qt(n,i,e=[]){if(Array.isArray(n))for(let t=0;t<n.length;t++){let r=n[t];n[t]=Fr(r,i,e),N(n[t])&&qt(n[t],i,e)}else if(!be(n)){if(N(n)){L(he(n),`Object ${JSON.stringify(n)} must have an oid`);for(let t of Object.keys(n))n[t]=Fr(n[t],i,e),N(n[t])&&qt(n[t],i,e)}}return e}function Fr(n,i,e){if(xe(n)){e.push(n.id);let t=i.get(n.id);return L(!!t,`No value was found in object map for ${n.id}`),$(t,n.id)}else return n}var Te;(function(n){n[n.Realtime=0]="Realtime",n[n.Push=1]="Push",n[n.PassiveRealtime=2]="PassiveRealtime",n[n.PassivePush=3]="PassivePush",n[n.ReadOnlyPull=4]="ReadOnlyPull",n[n.ReadOnlyRealtime=5]="ReadOnlyRealtime"})(Te||(Te={}));var ms=n=>Object.assign({type:"object"},n),gs=n=>Object.assign({type:"array"},n),ys=n=>Object.assign({type:"string"},n),bs=n=>Object.assign({type:"number"},n),ws=n=>Object.assign({type:"boolean"},n),vs=n=>Object.assign({type:"any"},n),xs=n=>Object.assign({type:"map"},n),Ss=n=>Object.assign({type:"file"},n),Br={object:ms,array:gs,string:ys,number:bs,boolean:ws,any:vs,map:xs,file:Ss};var Lr=Je(ct(),1);function fi(n){return n.equals!==void 0}function hi(n){return n.gte!==void 0||n.lte!==void 0||n.gt!==void 0||n.lt!==void 0}function Os(n){return!!n.match}function pi(n){return n.startsWith!==void 0}function jr(n){return!hi(n)&&!fi(n)&&!Os(n)&&!pi(n)&&n.order}function we(n){return n.type==="any"?!0:n.type==="map"?!1:n.nullable}function Ce(n){return n?n.type==="map"||n.type==="array"?!0:n.type==="file"?!1:n.default!==void 0:!1}function gi(n){if(!(!n||!Ce(n)))return n.type==="file"?we(n)?null:void 0:n.type==="map"?{}:n.type==="array"?we(n)?null:[]:n.type==="object"?we(n)?null:void 0:typeof n.default=="function"?n.default():n.default}function Ae(n,i){for(let[e,t]of Object.entries(n.fields)){let r=yi(t);(r!==void 0&&i[e]===void 0||!we(t)&&i[e]===null)&&(i[e]=r),i[e]&&Ue(i[e],t)}return i}function Ue(n,i){if(n==null)return n;if(i.type==="object")for(let[e,t]of Object.entries(i.properties)){if(n[e]===void 0){let r=yi(t);r!==void 0&&(n[e]=r)}Ue(n[e],t)}else if(i.type==="array")for(let e of n)Ue(e,i.items);else if(i.type==="map")for(let[e,t]of Object.entries(n))e===Oe||e===je||Ue(t,i.values)}function yi(n){if(n.type==="string"||n.type==="number"||n.type==="boolean"||n.type==="any"){if(n.default&&typeof n.default=="function")return n.default();if(n.default!==void 0)return JSON.parse(JSON.stringify(n.default))}if(n.type==="array")return[];if(n.type==="map")return{};if(n.type!=="any"&&n.nullable)return null;if(n.type==="object"&&n.default){let i=typeof n.default=="function"?n.default():JSON.parse(JSON.stringify(n.default));for(let[e,t]of Object.entries(n.properties))i[e]===void 0&&(i[e]=yi(t));return i}}function bi(n,i){for(let[e,t]of Object.entries(i))e===Oe||e===je||(n.fields[e]?mi(t,n.fields[e]):delete i[e]);return i}function mi(n,i){if(N(n)&&i.type==="object")for(let[e,t]of Object.entries(n))i.properties[e]?mi(t,i.properties[e]):delete n[e];else if(Array.isArray(n)&&i.type==="array")for(let e of n)mi(e,i.items)}function Mr(n,i){for(let[e,t]of Object.entries(i))if(e!==Oe){if(!n[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(t){let r=ke({field:n[e],value:t,fieldPath:[e]});if(r)return r}}}function ke({field:n,value:i,fieldPath:e=[],depth:t,requireDefaults:r}){if(!(t!==void 0&&t<=0)&&!(we(n)&&i===null)){if(i===null&&(r||!Ce(n)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${Pe(e)}`};if(n.type==="object"){if(!N(i))return{type:"invalid-type",fieldPath:e,message:`Expected object${n.nullable?" or null":""} for field ${Pe(e)}, got ${i}`};for(let[o,s]of Object.entries(n.properties))o!==Oe&&i[o]&&ke({field:s,value:i[o],fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});for(let o of Object.keys(i))if(!n.properties[o])return{type:"invalid-key",fieldPath:[...e,o],message:`Invalid unexpected field "${o}" on value ${Pe(e)}`}}else if(n.type==="array"){if(!Array.isArray(i))return i===null&&n.nullable?void 0:{type:"invalid-value",fieldPath:e,message:`Expected array${n.nullable?" or null":""} for field ${Pe(e)}, got ${i}`};for(let o of i)ke({field:n.items,value:o,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})}else if(n.type==="map"){if(!N(i))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${Pe(e)}, got ${i}`};for(let[o,s]of Object.entries(i))ke({field:n.values,value:s,fieldPath:[...e,o],depth:t!==void 0?t-1:void 0})}else if(n.type==="string"){if(typeof i!="string")return{type:"invalid-type",fieldPath:e,message:`Expected string ${n.nullable?" or null":""} for field ${Pe(e)}, got ${i}`};if(n.options&&!n.options.includes(i))return{type:"invalid-value",fieldPath:e,message:`Expected one of ${n.options.join(", ")} for field ${Pe(e)}, got ${i}`}}else if(n.type==="boolean"){if(typeof i!="boolean")return{type:"invalid-type",fieldPath:e,message:`Expected boolean ${n.nullable?" or null":""} for field ${Pe(e)}, got ${i}`}}else if(n.type==="number"){if(typeof i!="number")return{type:"invalid-type",fieldPath:e,message:`Expected number ${n.nullable?" or null":""} for field ${Pe(e)}, got ${i}`}}else n.type}}function Pe(n){return n.length===0?"root":n.join(".")}function Ve(n,i){var e;return n.type==="object"?n.properties[i]:n.type==="array"?n.items:n.type==="map"?n.values:n.type==="any"?n:"type"in n?null:(e=n[i])!==null&&e!==void 0?e:null}var Is=function(n,i){var e={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&i.indexOf(t)<0&&(e[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(n);r<t.length;r++)i.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(n,t[r])&&(e[t[r]]=n[t[r]]);return e};function wi(n){var{synthetics:i,indexes:e}=n,t=Is(n,["synthetics","indexes"]);let r=Object.assign(Object.assign({},i),e);for(let[o,s]of Object.entries(t.fields))"indexed"in s&&(r[o]={field:o});return Object.assign(Object.assign({},t),{indexes:r})}function yt(n){return n}yt.collection=wi;yt.fields=Br;yt.generated={id:Lr.default};var Ht="\uFFFFFE",_s="\0",Ds="\uFFFFFF";function ce(...n){let i=Es(n);return i.length===1?i[0]:i}function Ne(...n){return n.join(Ht)+`${Ds}`}function $e(...n){return n.join(Ht)+`${Ht}${_s}`}function Es(n){let i=[[]];for(let e of n)if(Array.isArray(e)){let t=[];for(let r of i)for(let o of e)t.push(r.concat(o));i=t}else for(let t of i)t.push(`${e}`);return Array.from(new Set(i.map(e=>e.join(Ht))))}function Cs(n){return!!n.field}function As(n,i){let e={};for(let[t,r]of Object.entries(n.indexes||{})){let o=r;Cs(o)?e[t]=ve(i[o.field]):e[t]=ve(o.compute(i))}return e}function Ps(n,i){return Object.entries(n.compounds||{}).reduce((e,[t,r])=>(e[t]=ce(...r.of.map(o=>i[o])),e),{})}function Rs(n,i){return Object.entries(n.fields).reduce((e,[t,r])=>("indexed"in r&&(e[t]=ve(i[t])),e),{})}function Wt(n,i){let e=Object.assign(Object.assign({[n.primaryKey]:i[n.primaryKey]},Rs(n,i)),As(n,i));return Object.assign(e,Ps(n,Object.assign(Object.assign({},i),e))),e["@@@snapshot"]=i,e}var Fs="null";function ve(n){if(n===null)return Fs;if(typeof n=="string"||typeof n=="number")return n;if(typeof n=="boolean"||n===null)return`${n}`;if(n===void 0)return"undefined";if(Array.isArray(n))return n.map(ve);throw new Error(`Unsupported index value: ${n}`)}var Ur={version:0,collections:{}};function Jt(n,i,e){let t=typeof i=="function",r=t?Ur:n,o=t?n:i,s=t?i:e,a=Object.keys(o.collections).filter(S=>r.collections[S]&&ft(r.collections[S])!==ft(o.collections[S])),h=Object.keys(r.collections).filter(S=>!o.collections[S]),u=Object.keys(o.collections).filter(S=>!r.collections[S]),m=new Set;for(let S of a){let I=r.collections[S].fields,x=o.collections[S].fields;Object.keys(x).some(_=>{var R,b;return!(!((R=I[_])===null||R===void 0)&&R.default)&&((b=x[_])===null||b===void 0?void 0:b.default)})&&m.add(S),Object.keys(I).some(_=>!x[_])&&m.add(S)}let v={},y={};for(let S of[...a,...u]){let I=Qt(r.collections[S]),x=Qt(o.collections[S]),_=x.filter(b=>!I.find(D=>D.name===b.name)),R=I.filter(b=>!x.find(D=>D.name===b.name));_.length>0&&(v[S]=_,a.includes(S)&&m.add(S)),R.length>0&&(y[S]=R,a.includes(S)&&m.add(S))}let C=(S,I)=>Ae(o.collections[S],I),w=S=>I=>{let x=o.collections[S];return Ae(x,bi(x,I))};return{version:o.version,migrate:async S=>{let I=[];if(await s({migrate:async(x,_)=>{let R=w(x),b=async D=>{let d=await _(D);return $(d,ne(D)),R(d)};await S.migrate(x,b),I.push(x),m.delete(x)},identity:x=>x,withDefaults:C,info:{changedCollections:a,addedCollections:u,removedCollections:h},queries:S.queries,mutations:S.mutations}),o.version>1){S.log("debug","auto-migrating collections with new defaults",m);for(let _ of m)await S.migrate(_,w(_)),I.push(_);let x=a.filter(_=>!I.includes(_));x.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,x)}},removedCollections:h,addedIndexes:v,removedIndexes:y,allCollections:Object.keys(o.collections),changedCollections:a,addedCollections:u,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function Qt(n){return n?[...Object.keys(n.indexes||{}).map(i=>({name:i,multiEntry:["array","string[]","number[]","boolean[]"].includes(n.indexes[i].type),synthetic:!0,compound:!1})),...Object.keys(n.compounds||{}).map(i=>({name:i,multiEntry:n.compounds[i].of.some(e=>(n.fields[e]||n.indexes[e]).type==="array"),synthetic:!1,compound:!0}))]:[]}function vi(n,i){return Jt(i?n:{version:0,collections:{}},i||n,async({migrate:t,info:r})=>{if((i||n).version!==1)for(let o of r.changedCollections)await t(o,s=>s)})}function xi(n,i,e){let t=typeof i=="function"||i===void 0,r=t?Ur:n,o=t?n:i,s=t?i:e;L(r,"Invalid arguments to createMigration"),L(o,"Invalid arguments to createMigration");let{changedCollections:a,addedCollections:h,removedCollections:u,addedIndexes:m,removedIndexes:v,autoMigratedCollections:y,autoMigration:C}=Ts(r,o);return{version:o.version,migrate:async w=>{let S=[];if(await s?.({migrate:async(x,_)=>{let R=C(x),b=async D=>{let d=await _(D);$(d,ne(D));let p=R(d),l=Mr(o.collections[x].fields,p);return p};await w.migrate(x,b),S.push(x),y.delete(x)},info:{changedCollections:a,addedCollections:h,removedCollections:u},queries:w.queries,mutations:w.mutations}),o.version>1){w.log("debug","auto-migrating collections with new defaults",y);for(let _ of y)await w.migrate(_,C(_)),S.push(_);for(let _ of u)await w.deleteCollection(_);let x=a.filter(_=>!S.includes(_));x.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,x)}},removedCollections:u,addedIndexes:m,removedIndexes:v,allCollections:Object.keys(o.collections),changedCollections:a,addedCollections:h,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function Ts(n,i){let e=Object.keys(i.collections).filter(m=>n.collections[m]&&ft(n.collections[m])!==ft(i.collections[m])),t=Object.keys(n.collections).filter(m=>!i.collections[m]),r=Object.keys(i.collections).filter(m=>!n.collections[m]),o=new Set;for(let m of e){let v=n.collections[m].fields,y=i.collections[m].fields;Object.keys(y).some(C=>!Ce(v[C])&&Ce(y[C]))&&o.add(m),Object.keys(v).some(C=>!y[C])&&o.add(m)}let s={},a={};for(let m of[...e,...r]){let v=Qt(n.collections[m]),y=Qt(i.collections[m]),C=y.filter(S=>!v.find(I=>I.name===S.name)),w=v.filter(S=>!y.find(I=>I.name===S.name));C.length>0&&(s[m]=C,e.includes(m)&&o.add(m)),w.length>0&&(a[m]=w,e.includes(m)&&o.add(m))}return{changedCollections:e,addedCollections:r,removedCollections:t,addedIndexes:s,removedIndexes:a,autoMigratedCollections:o,withDefaults:(m,v)=>Ae(i.collections[m],v),autoMigration:m=>v=>{let y=i.collections[m];return Ae(y,bi(y,v))}}}var Gt=class{constructor(i,e){this.getNow=i,this.createSubId=e,this.isPrimitive=t=>!N(t)||Q(t),this.createDiff=(t,r,o={})=>mt(t,r,this.getNow,this.createSubId,[],o),this.createInitialize=(t,r)=>Fe(t,r,this.getNow,this.createSubId),this.createSet=(t,r,o)=>{if(this.isPrimitive(o))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:r,value:o}}];{let s=Se(t,this.createSubId);return[...Fe(o,s,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:pe(s),name:r}}]}},this.createRemove=(t,r)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:r}}],this.createListPush=(t,r)=>{if(this.isPrimitive(r))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:r}}];{let o=Se(t,this.createSubId);return[...Fe(r,o,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:pe(o)}}]}},this.createListAdd=(t,r)=>this.isPrimitive(r)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:r}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:pe(r)}}],this.createListInsert=(t,r,o)=>{if(this.isPrimitive(o))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:o,index:r}}];{let s=Se(t,this.createSubId);return[...Fe(o,s,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:pe(s),index:r}}]}},this.createListRemove=(t,r,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:r,only:o}}],this.createListDelete=(t,r,o=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:r,count:o}}],this.createListMoveByRef=(t,r,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:r,index:o}}],this.createListMoveByIndex=(t,r,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:r,to:o}}],this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}],this.createDeleteAll=t=>t.map(r=>({oid:r,timestamp:this.getNow(),data:{op:"delete"}}))}};var V=class{constructor(i){this._onAllUnsubscribed=i,this.subscribers={},this.counts={},this._disabled=!1,this.disposed=!1,this.subscriberCount=e=>{var t;return(t=this.counts[e])!==null&&t!==void 0?t:0},this.totalSubscriberCount=()=>Object.values(this.counts).reduce((e,t)=>e+t,0),this.subscribe=(e,t)=>{let r=Nt(),o=this.subscribers[e];return o||(o=this.subscribers[e]={}),o[r]=t,this.counts[e]=(this.counts[e]||0)+1,()=>{this.subscribers[e]&&(delete this.subscribers[e][r],this.counts[e]--,this.counts[e]===0&&(delete this.subscribers[e],delete this.counts[e],this._onAllUnsubscribed&&this._onAllUnsubscribed(e)))}},this.emit=(e,...t)=>{this._disabled||this.subscribers[e]&&Object.values(this.subscribers[e]).forEach(r=>r(...t))},this.dispose=()=>{this._disabled=!0,this.disposed=!0;let e=Object.keys(this.subscribers);this.subscribers={},this.counts={},e.forEach(t=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(t)})},this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};function Vr(n,i,e,t){if(i==null)return[{oid:n,timestamp:t(),data:{op:"delete"}}];let r=ae(i),o=[];for(let s of e){let a=ks(n,r,s,t);o.unshift(...a),Le(r,s.data)}return o}function ks(n,i,e,t){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:n,timestamp:t(),data:{op:"set",name:r.name,value:i[r.name]}}];case"list-insert":return[{oid:n,timestamp:t(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:n,timestamp:t(),data:{op:"list-insert",index:r.index,values:i.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:n,timestamp:t(),data:{op:"list-move-by-ref",value:r.value,index:i.indexOf(r.value)}}];case"list-move-by-index":return[{oid:n,timestamp:t(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:n,timestamp:t(),data:{op:"initialize",value:i}}];case"list-push":return[{oid:n,timestamp:t(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let o=i.lastIndexOf(r.value);return[{oid:n,timestamp:t(),data:{op:"list-insert",index:o,values:[r.value]}}]}else if(r.only==="first"){let o=i.indexOf(r.value);return[{oid:n,timestamp:t(),data:{op:"list-insert",index:o,values:[r.value]}}]}else{let o=[],s=i.indexOf(r.value);for(;s!==-1;)o.push(s),s=i.indexOf(r.value,s+1);return o.map(a=>({oid:n,timestamp:t(),data:{op:"list-insert",index:a,value:r.value}}))}case"list-add":return[{oid:n,timestamp:t(),data:{op:"list-remove",value:r.value,only:"last"}}];case"initialize":return[{oid:n,timestamp:t(),data:{op:"delete"}}];case"touch":return[];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var Ze=class{constructor(i){this.flusher=i,this.batches=new Map,this.flush=e=>{let t=this.batches.get(e);if(t)return t.flush()},this.discard=e=>{let t=this.batches.get(e);t&&(t.discard(),this.batches.delete(e))},this.flushAll=()=>[...this.batches.values()].map(e=>e.flush()),this.getSize=e=>{let t=this.batches.get(e);return t?t.items.length:0}}add({key:i,userData:e,items:t,max:r,timeout:o}){let s=this.batches.get(i);return s||(s=new Si({max:r||null,startedAt:Date.now(),userData:e,timeout:o||null,flusher:this.flusher,key:i}),this.batches.set(i,s)),s.update({items:t,max:r,timeout:o,userData:e}),s}},Si=class{constructor({max:i,startedAt:e,timeout:t,userData:r,flusher:o,key:s}){this.items=[],this.update=({items:a,max:h,timeout:u,userData:m})=>{this.items.push(...a),h!==void 0&&(this.max=h),u!==void 0&&(this.timeout=u),m&&(this.userData=m);let v=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():v&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))},this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let a=this.items;return this.items=[],this.flusher(a,this.key,this.userData)},this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]},this.max=i,this.startedAt=e,this.timeout=t,this.userData=r,this.flusher=o,this.key=s}};function Nr(n,i){let e,t;return(...r)=>{let o=i();return e&&e.length===o.length&&e.every((s,a)=>s===o[a])||(e=[...o],t=n(...r)),t}}var bt;(function(n){n[n.InvalidRequest=4e3]="InvalidRequest",n[n.BodyRequired=4001]="BodyRequired",n[n.NoToken=4010]="NoToken",n[n.InvalidToken=4011]="InvalidToken",n[n.TokenExpired=4012]="TokenExpired",n[n.Forbidden=4030]="Forbidden",n[n.NotFound=4040]="NotFound",n[n.Unexpected=5e3]="Unexpected",n[n.ConfigurationError=5010]="ConfigurationError",n[n.NoFileStorage=5011]="NoFileStorage"})(bt||(bt={}));var Oi=class extends Error{constructor(i,e,t){super(t??`Verdant error: ${i}`,{cause:e}),this.code=i,this.toResponse=()=>JSON.stringify({code:this.code})}get httpStatus(){let i=Math.floor(this.code/10);return i<600?i:500}};Oi.Code=bt;function $r(n){return typeof n=="object"&&"code"in n&&typeof n.code=="number"}function le(n){return n instanceof Error&&n.name==="AbortError"}function J(n){return new Promise((i,e)=>{n.onsuccess=()=>{i(n.result)},n.onerror=()=>{n.error&&le(n.error)?i(n.result):e(n.error)}})}function wt(n,i){return new Promise((e,t)=>{let r=n.transaction([i],"readonly"),s=r.objectStore(i).openCursor(),a=0,h=0;s.onsuccess=function(u){let m=s.result;m&&(a++,h=h+_r(m.value),m.continue())},s.onerror=function(u){s.error&&le(s.error)?e({count:a,size:h}):t(s.error)},r.oncomplete=function(u){e({count:a,size:h})},r.onabort=function(u){t(u)},r.onerror=function(u){t(u)}})}function Yt(n,i){let e=n.transaction(i,"readonly"),t=i.map(r=>{let o=e.objectStore(r);return J(o.getAll())});return Promise.all(t)}async function ze(n){n.close(),await new Promise((i,e)=>{i()})}async function Xt(n,i=window.indexedDB){let e=i.deleteDatabase([n,"meta"].join("_")),t=i.deleteDatabase([n,"collections"].join("_"));await Promise.all([new Promise((r,o)=>{e.onsuccess=r,e.onerror=o}),new Promise((r,o)=>{t.onsuccess=r,t.onerror=o})]),window.location.reload()}function zr(n,i=window.indexedDB){return J(i.deleteDatabase(n))}async function Kr(n=window.indexedDB){return n.databases()}function Zt(n,i,e,t,r){let o=n.transaction(i,e);if(t){let s=()=>{r?.("debug","aborting transaction");try{o.abort()}catch(a){r?.("debug","aborting transaction failed",a)}};t.addEventListener("abort",s),o.addEventListener("error",()=>{t.removeEventListener("abort",s)}),o.addEventListener("complete",()=>{t.removeEventListener("abort",s)})}return o}var Ie=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(i=>i()),this._disposes=[]};this.addDispose=i=>{this._disposes.push(i)}}};var se=class extends Ie{constructor(e,{log:t}={}){super();this.db=e;this.globalAbortController=new AbortController;this.createTransaction=(e,t)=>{let r=Zt(this.db,e,t?.mode||"readonly",t?.abort,this.log);return this.globalAbortController.signal.addEventListener("abort",r.abort),r.addEventListener("complete",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r.addEventListener("error",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r};this.run=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve(void 0);let s=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=t(s);return J(a)};this.runAll=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve([]);let s=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=t(s);return Promise.all(a.map(J))};this.iterate=async(e,t,r,o)=>{let a=(o?.transaction||this.createTransaction([e],o)).objectStore(e),h=t(a);return Array.isArray(h)?Promise.all(h.map(u=>new Promise((m,v)=>{u.onsuccess=()=>{let y=u.result;y?(r(y.value,a),y.continue()):m()},u.onerror=()=>{u.error&&le(u.error)?m():v(u.error)}}))).then(()=>{}):new Promise((u,m)=>{h.onsuccess=()=>{let v=h.result;v?(r(v.value,a),v.continue()):u()},h.onerror=()=>{h.error&&le(h.error)?u():m(h.error)}})};this.clear=e=>this.run(e,t=>t.clear(),{mode:"readwrite"});this.log=t,this.addDispose(()=>{this.globalAbortController.abort()})}};var en=class extends se{constructor(){super(...arguments);this.getAckInfo=async()=>{let e=await this.run("info",t=>t.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",t=>t.put({type:"ack",globalAckTimestamp:e}),{mode:"readwrite"})}}};var tn=class extends se{constructor(e,t){super(e,t);this.getAllForDocument=async(e,{mode:t="readonly",transaction:r}={})=>{let o=[];return await this.iterateOverAllForDocument(e,s=>{o.push(s)},{mode:t,transaction:r}),o};this.iterateOverAllForDocument=async(e,t,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>{let a=z(e),[h,u]=ci(e),[m,v]=li(e);return[s.openCursor(IDBKeyRange.only(a)),s.openCursor(IDBKeyRange.bound(h,u,!1,!1)),s.openCursor(IDBKeyRange.bound(m,v,!1,!1))]},t,{mode:r,transaction:o});this.iterateOverAllForCollection=async(e,t,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],t,{mode:r,transaction:o});this.getAllForMultipleDocuments=async(e,{mode:t="readonly"}={})=>(await this.runAll("baselines",o=>e.flatMap(s=>{let a=z(s),[h,u]=ci(s),[m,v]=li(s);return[o.get(a),o.getAll(IDBKeyRange.bound(h,u,!1,!1)),o.getAll(IDBKeyRange.bound(m,v,!1,!1))]}),{mode:t})).flat();this.getAllSince=async(e,{mode:t="readonly"}={})=>this.run("baselines",r=>{let o=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(o)},{mode:t});this.get=async(e,{transaction:t,mode:r="readonly"}={})=>this.run("baselines",o=>o.get(e),{mode:r,transaction:t});this.set=async(e,{transaction:t}={})=>{await this.run("baselines",r=>r.put(e),{mode:"readwrite",transaction:t})};this.setAll=async(e,{transaction:t}={})=>{await this.runAll("baselines",r=>e.map(o=>r.put(o)),{mode:"readwrite",transaction:t})};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:t})=>{await this.run("baselines",r=>r.delete(e),{mode:"readwrite",transaction:t})}}};var qr=Je(ct(),1);var nn=class extends se{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let t=await this.run("info",r=>r.get("localReplicaInfo"),{transaction:e});return t?(this.cached=t,t):(this._creating||(this._creating=(async()=>{let o={type:"localReplicaInfo",id:(0,qr.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};await this.run("info",s=>s.put(o),{mode:"readwrite"}),this.cached=o})()),await this._creating,this.get({transaction:e}))};this.update=async(e,{transaction:t}={})=>{let r=await this.get({transaction:t});Object.assign(r,e),await this.run("info",o=>o.put(r),{mode:"readwrite"}),this.cached=r};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",t=>t.put(e),{mode:"readwrite"})}}};var rn=class{constructor(i){this.meta=i;this.createOperation=async i=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:i.operations.map(t=>({data:t.data,oid:t.oid,timestamp:t.timestamp}))}};this.createMigrationOperation=async({targetVersion:i,...e})=>{let t=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(r=>({...r,timestamp:this.meta.time.zero(i)})),timestamp:this.meta.time.zero(i),replicaId:t.id}};this.createSyncStep1=async i=>{let e=await this.meta.localReplica.get(),t=i===null?null:e.lastSyncedLogicalTime,r=[],o=new Set;t?await this.meta.operations.iterateOverAllLocalOperations(a=>{r.push({data:a.data,oid:a.oid,timestamp:a.timestamp}),o.add(z(a.oid))},{after:t,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(a=>{r.push({data:a.data,oid:a.oid,timestamp:a.timestamp}),o.add(z(a.oid))},{mode:"readwrite"});let s=[];return t||(s=await this.meta.baselines.getAllSince("")),{type:"sync",schemaVersion:this.meta.schema.currentVersion,timestamp:this.meta.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:s,since:t}};this.createPresenceUpdate=async i=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:i,replicaId:e.id}};this.createHeartbeat=async()=>{let i=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:i.id}};this.createAck=async i=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:i}}}};var on=class extends se{constructor(e,t){super(e,t);this.iterateOverAllOperationsForDocument=async(e,t,{to:r,from:o,after:s,mode:a="readonly",transaction:h}={})=>{let m=(h||this.createTransaction(["operations"],{mode:a})).objectStore("operations"),v=m.index("d_t"),y=o||s,C=y?ce(e,y):$e(e),w=r?ce(e,r):Ne(e),S=IDBKeyRange.bound(C,w,!!s,!1),I=v.openCursor(S,"next");return new Promise((x,_)=>{let R;I.onsuccess=b=>{let D=I.result;if(D){let d=D.value;L(d.oid.startsWith(e)),L(R===void 0||R<=d.timestamp,`expected ${R} <= ${d.timestamp}`),t(d,m),R=d.timestamp,D.continue()}else x()},I.onerror=b=>{if(le(I.error)){x();return}else _(I.error)}})};this.iterateOverAllOperationsForEntity=async(e,t,{after:r,to:o,mode:s,transaction:a})=>{let u=(a||this.createTransaction(["operations"],{mode:s})).objectStore("operations"),m=r?ce(e,r):$e(e),v=o?ce(e,o):Ne(e),y=IDBKeyRange.bound(m,v,!!r,!1),C=u.openCursor(y,"next");return new Promise((w,S)=>{let I;C.onsuccess=x=>{let _=C.result;if(_){let R=_.value;L(R.oid.startsWith(e)),L(I===void 0||I<=R.timestamp,`expected ${I} <= ${R.timestamp}`),t(R,u),I=R.timestamp,_.continue()}else w()},C.onerror=x=>{le(C.error)?w():S(C.error)}})};this.iterateOverAllOperationsForCollection=async(e,t,{after:r,to:o,mode:s,transaction:a})=>{let h=a||this.createTransaction(["operations"],{mode:s});return this.iterate("operations",u=>u.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),t,{mode:s,transaction:h})};this.iterateOverAllLocalOperations=async(e,{before:t,after:r,mode:o="readonly",transaction:s})=>{let h=(s||this.createTransaction(["operations"],{mode:o})).objectStore("operations"),u=h.index("l_t"),m=r?ce(!0,r):$e(!0),v=t?ce(!0,t):Ne(!0),y=IDBKeyRange.bound(m,v,!!r,!0),C=u.openCursor(y,"next");return new Promise((w,S)=>{let I;C.onsuccess=x=>{let _=C.result;if(_){let R=_.value;L(I===void 0||I<=R.timestamp,`expected ${I} <= ${R.timestamp}`),e(R,h),I=R.timestamp,_.continue()}else w()},C.onerror=x=>{le(C.error)?w():S(C.error)}})};this.iterateOverAllOperations=async(e,{before:t,transaction:r,mode:o,from:s})=>{await this.iterate("operations",a=>{let h=s?$e(s):void 0,u=t?Ne(t):void 0,m=h&&u?window.IDBKeyRange.bound(h,u,!1,!0):h?window.IDBKeyRange.lowerBound(h,!1):u?window.IDBKeyRange.upperBound(u,!0):void 0;return a.index("timestamp").openCursor(m,"next")},e,{mode:o,transaction:r})};this.addOperations=async(e,{transaction:t}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:t});this.addCompoundIndexes=e=>({...e,oid_timestamp:ce(e.oid,e.timestamp),l_t:ce(e.isLocal,e.timestamp),d_t:ce(z(e.oid),e.timestamp)});this.insert=async(e,{transaction:t})=>{let r=new Set;return await this.runAll("operations",o=>e.map(s=>(r.add(z(s.oid)),o.put(s))),{mode:"readwrite",transaction:t}),Array.from(r)};this.reset=()=>this.clear("operations")}};var sn=class{constructor(i,e){this.db=i;this.currentVersion=e;this.cached=null;this.get=async()=>{if(this.cached)return this.cached;let r=this.db.transaction("info","readonly").objectStore("info").get("schema"),o=await J(r);return o?(this.cached=JSON.parse(o.schema),this.cached):null};this.set=async i=>{let o=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(i)});this.cached=i,await J(o)}}};var vt=class extends V{constructor({disableRebasing:e,context:t}){super();this.time=new Tt;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=(e,t={})=>Zt(this.db,e,t.write?"readwrite":"readonly",t.abort,this.context.log);this.getAllDocumentRelatedOids=async e=>{let t=new Set,r=z(e);L(r===e,"Must be root document OID"),t.add(r);let o=this.createTransaction(["baselines","operations"]);return await Promise.all([this.baselines.iterateOverAllForDocument(r,s=>{t.add(s.oid)},{transaction:o}),this.operations.iterateOverAllOperationsForDocument(r,s=>{t.add(s.oid)},{transaction:o})]),Array.from(t)};this.getAllCollectionRelatedOids=async e=>{let t=new Set,r=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForCollection(e,o=>{t.add(o.oid)},{transaction:r}),this.operations.iterateOverAllOperationsForCollection(e,o=>{t.add(o.oid)},{transaction:r})]),Array.from(t)};this.getDocumentSnapshot=async(e,t={})=>{let r=z(e);L(r===e,"Must be root document OID");let o=this.db.transaction(["baselines","operations"],"readwrite"),s=await this.baselines.getAllForDocument(r,{transaction:o}),a=new Map;for(let u of s)u.snapshot&&$(u.snapshot,u.oid),a.set(u.oid,u.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,u=>{let m=a.get(u.oid)||void 0,v=Le(m,u.data);v&&$(v,u.oid),a.set(u.oid,v)},{transaction:o,to:t.to||this.now});let h=a.get(r);return h&&qt(h,a),h};this.getDocumentData=async(e,t)=>{let r=this.createTransaction(["baselines","operations"],t),o=[],s={};return await Promise.all([this.baselines.iterateOverAllForDocument(e,a=>{o.push(a)},{transaction:r}),this.operations.iterateOverAllOperationsForDocument(e,a=>{s[a.oid]??=[],s[a.oid].push(a)},{transaction:r})]),{baselines:o,operations:s}};this.ack=async e=>{let t=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:t.id,timestamp:e}),!this._closing&&(!t.ackedLogicalTime||e>t.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperations=async(e,t)=>{if(e.length===0)return;this.log("debug",`Inserting ${e.length} local operations`,e);for(let o of e)o.isLocal=!0;await this.operations.addOperations(e,t);let r=await this.messageCreator.createOperation({operations:e});this.emit("message",r),this.tryAutonomousRebase()};this.insertRemoteOperations=async(e,t)=>{if(e.length===0)return[];this.log("debug",`Inserting ${e.length} remote operations`,e);let r=await this.operations.addOperations(e.map(o=>({...o,isLocal:!1})),t);return this.ack(e[e.length-1].timestamp),r};this.insertRemoteBaselines=async(e,t)=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e,t);let r=new Set;return e.forEach(o=>{r.add(z(o.oid))}),Array.from(r)};this.insertData=async(e,t)=>{let r=this.createTransaction(["baselines","operations"],{...t,write:!0});e.baselines&&await this.insertRemoteBaselines(e.baselines,{transaction:r}),!t?.abort?.aborted&&e.operations&&(e.isLocal?await this.insertLocalOperations(e.operations,{transaction:r}):await this.insertRemoteOperations(e.operations,{transaction:r}))};this.updateLastSynced=async e=>{if(!this._closing)return this.localReplica.update({lastSyncedLogicalTime:e})};this.lastSyncedTimestamp=async()=>(await this.localReplica.get()).lastSyncedLogicalTime;this.tryAutonomousRebase=async()=>{this.disableRebasing||(await this.localReplica.get()).lastSyncedLogicalTime||await this.runRebase(this.now)};this.runRebase=async e=>{if(this._closing)return;let t,r=new Set,o=this.createTransaction(["baselines","operations"],{write:!0}),s=0;if(await this.operations.iterateOverAllOperations(h=>{r.add(h.oid),t=h.timestamp,s++},{before:e,transaction:o}),!r.size||this._closing)return;let a=[];for(let h of r)a.push(await this.rebase(h,t||e,o));this.emit("rebase",a)};this.rebase=async(e,t,r)=>{let o=(await this.localReplica.get()).id;this.log("[",o,"]","Rebasing",e,"up to",t);let s=r||this.createTransaction(["operations","baselines"],{write:!0}),a=await this.baselines.get(e,{transaction:s}),h=a?.snapshot||void 0,u=0,m=[];await this.operations.iterateOverAllOperationsForEntity(e,(y,C)=>{(!a||y.timestamp>a.timestamp)&&(h=Le(h,y.data,m)),u++,C.delete(y.oid_timestamp)},{to:t,transaction:s}),h&&$(h,e);let v={oid:e,snapshot:h,timestamp:t};if(v.snapshot?await this.baselines.set(v,{transaction:s}):await this.baselines.delete(e,{transaction:s}),this.log("debug","successfully rebased",e,"up to",t,":",h,"and deleted",u,"operations"),m.length){let y=m.filter(be);y.length&&this.emit("filesDeleted",y)}return v};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,t)=>{let r=await this.schema.get();if(r&&t===r.version&&r.version===e.version&&JSON.stringify(r)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
|
|
7
7
|
${JSON.stringify(r)}
|
|
8
|
-
${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[n,r]=await Jt(e,["baselines","operations"]),o=await this.localReplica.get(),s=await this.schema.get();if(!s)throw new Error("Cannot export Client data before initializing");return{operations:r,baselines:n,localReplica:o,schema:s}};this.resetFrom=async e=>{let r=this.db.transaction(["baselines","operations","info"],"readwrite");await J(r.objectStore("baselines").clear()),await J(r.objectStore("operations").clear()),await J(r.objectStore("info").clear()),await this.localReplica.update({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:r})};this.stats=async()=>{let e=this.db,n=await yt(e,"operations"),r=await yt(e,"baselines");return{operationsSize:n,baselinesSize:r}};this.context=n,this.schema=new rn(n.metaDb,n.schema.version),this.operations=new nn(this.db,{log:n.log}),this.baselines=new Zt(this.db,{log:n.log}),this.localReplica=new en(this.db),this.ackInfo=new Xt(this.db),this.messageCreator=new tn(this),this.patchCreator=new Qt(()=>this.now),e&&(this.disableRebasing=e)}get db(){return this.context.metaDb}get log(){return this.context.log}get now(){return this.time.now(this.schema.currentVersion)}};var Ts=[ks,Ms,Bs,js,Ls];function on({indexedDB:i=window.indexedDB,namespace:t,log:e,metadataVersion:n=5}){return new Promise((r,o)=>{let s=i.open(`${t}_meta`,n),a=!1;s.onupgradeneeded=async p=>{let l=s.result,m=s.transaction,v=Ts.slice(p.oldVersion);for(let y of v)await y(l,m);await new Promise((y,C)=>{m.addEventListener("complete",y),m.addEventListener("error",C)}),p.oldVersion||(a=!0)},s.onerror=()=>{console.error("Error opening database",s.error),o(s.error)},s.onsuccess=()=>{r({db:s.result,wasInitialized:a})}})}async function qr({wipNamespace:i,namespace:t,indexedDB:e,log:n,metadataVersion:r}){let o=await on({namespace:i,indexedDB:e,log:n,metadataVersion:r});if(!o.wasInitialized)return o;n?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await on({namespace:t,indexedDB:e,log:n,metadataVersion:r}),a=s.transaction(["baselines","operations","info"],"readonly"),[p,l,m]=await Promise.all([J(a.objectStore("baselines").getAll()),J(a.objectStore("operations").getAll()),J(a.objectStore("info").getAll())]),v=o.db.transaction(["baselines","operations","info"],"readwrite"),y=v.objectStore("baselines"),C=v.objectStore("operations"),w=v.objectStore("info");for(let x of p)y.put(x);for(let x of l)C.put(x);for(let x of m)w.put(x);return await new Promise((x,I)=>{v.oncomplete=()=>{x()},v.onerror=S=>{I(S)},v.onabort=S=>{I(S)}}),await Ke(s),n?.("debug","Finished copy of production metadata database to WIP. Copied:",p.length,"baselines,",l.length,"operations"),o}async function ks(i,t){let e=i.createObjectStore("baselines",{keyPath:"oid"}),n=i.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=i.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),n.createIndex("isLocal_timestamp","isLocal_timestamp"),n.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Ms(i,t){let e=t.objectStore("operations");await new Promise((n,r)=>{let o=e.openCursor();o.onsuccess=()=>{let s=o.result;if(s){let{isLocal_timestamp:a,documentOid_timestamp:p,...l}=s.value;s.update({...l,l_t:a,d_t:p}),s.continue()}else n()},o.onerror=s=>{r(o.error)}}),e.deleteIndex("isLocal_timestamp"),e.deleteIndex("documentOid_timestamp"),e.createIndex("l_t","l_t",{unique:!1}),e.createIndex("o_t","o_t",{unique:!1}),e.createIndex("d_t","d_t",{unique:!1})}async function Bs(i,t){t.objectStore("operations").createIndex("timestamp","timestamp")}async function js(i,t){let e=i.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function Ls(i,t){let e=t.objectStore("operations");await new Promise((r,o)=>{let s=e.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let p=ci(a.value);p.oid_timestamp!==a.primaryKey?(a.delete(),e.put(p)):a.update(p),a.continue()}else r()},s.onerror=a=>{o(s.error)}});let n=t.objectStore("baselines");await new Promise((r,o)=>{let s=n.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let p=ci(a.value);p.oid!==a.primaryKey?(a.delete(),n.put(p)):a.update(p),a.continue()}else r()},s.onerror=a=>{o(s.error)}})}var Ns=i=>IDBKeyRange.only(ve(i.equals)),Us=i=>{},Vs=i=>{let t=i.gte||i.gt,e=i.lte||i.lt;return t===e?IDBKeyRange.only(ve(t)):t?e?IDBKeyRange.bound(ve(t),ve(e),!!i.gt,!!i.lt):IDBKeyRange.lowerBound(ve(t),!!i.gt):IDBKeyRange.upperBound(ve(e),!!i.lt)},Ks=(i,t,e)=>{let n=i.collections[t].compounds[e.where];L(n,`Index ${e.where} does not exist on collection ${t}`);let r=Object.keys(e.match).sort((p,l)=>n.of.indexOf(p)-n.of.indexOf(l));for(let p of r)if(n.of.indexOf(p)!==r.indexOf(p))throw new Error(`Compound index ${e.where} does not have ${p} at the start of its order`);let o=r.map(p=>e.match[p]);if(r.length===n.of.length)return IDBKeyRange.only(ce(...o));let s=Ve(...o),a=Ue(...o);return IDBKeyRange.bound(s,a)};function $s(i){let t=i.startsWith,e=i.startsWith+"\uFFFF";return IDBKeyRange.bound(t,e)}function sn(i,t,e){if(e)return ui(e)?Vs(e):di(e)?Ns(e):kr(e)?Us(e):fi(e)?$s(e):Ks(i,t,e)}function xi(i,t,e){return i.transaction(t,e?"readwrite":"readonly").objectStore(t)}async function an({collection:i,index:t,context:e}){let n=xi(e.documentDb,i),r=t?.where?n.index(t.where):n,o=sn(e.schema,i,t),s=t?.order==="desc"?"prev":"next",a=r.openCursor(o,s);return await new Promise((l,m)=>{a.onsuccess=()=>{let v=a.result;l(v?Z(i,v.primaryKey.toString()):null)},a.onerror=()=>{a.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",a.error),l(null)):le(a.error)?l(null):m(a.error)}})}async function cn({collection:i,index:t,context:e}){let n=xi(e.documentDb,i),r=t?.where?n.index(t.where):n,o=sn(e.schema,i,t),s=t?.order==="desc"?"prev":"next",a=r.openCursor(o,s);return await new Promise((l,m)=>{let v=new Set;a.onsuccess=()=>{let y=a.result;y?(v.add(Z(i,y.primaryKey.toString())),y.continue()):l(Array.from(v))},a.onerror=()=>{a.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",a.error),l([])):le(a.error)?l([]):m(a.error)}})}async function wt({collection:i,index:t,context:e,limit:n,offset:r}){let o=xi(e.documentDb,i),s=t?.where?o.index(t.where):o,a=sn(e.schema,i,t),p=t?.order==="desc"?"prev":"next",l=s.openCursor(a,p),m=!r,v=!1,y=0;return{result:await new Promise((w,x)=>{let I=new Set;l.onsuccess=()=>{y++;let S=l.result;S?r&&!m?(S.advance(r),m=!0):(n&&I.size<n&&I.add(Z(i,S.primaryKey.toString())),n&&y>n?(v=!0,w(Array.from(I))):S.continue()):w(Array.from(I))},l.onerror=()=>{l.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",l.error),w([])):le(l.error)?w([]):x(l.error)}}),hasNextPage:v}}async function Oi(i,t,e,n){function r(a,p){let l,m,v=i.open([t,"collections"].join("_"),e);v.onupgradeneeded=async y=>{l=y.oldVersion;let C=v.transaction;m=v.result,C.abort()},v.onsuccess=y=>{a([v.result.version,v.result])},v.onblocked=y=>{n?.("Database blocked, waiting...")},v.onerror=y=>{a([l,m])}}let[o,s]=await new Promise(r);return await ln(s),o}async function ln(i){i.close(),await new Promise(t=>t())}async function Hr(i,t,e,n,r){function o(s,a){let p=i.open([t,"collections"].join("_"),e),l=!1;p.onupgradeneeded=m=>{let v=p.transaction;n(v,p.result,m),l=!0},p.onsuccess=m=>{p.result.close(),l?s():a(new Error("Database was not upgraded when a version change was expected"))},p.onerror=m=>{a(p.error||new Error("Unknown error"))},p.onblocked=m=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(o)}async function Wr(i,t){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${i}`,t):await t()}async function $e(i,t,e,n){n?.("debug","Opening database",t,"at version",e);let r=await new Promise((o,s)=>{let a=i.open([t,"collections"].join("_"),e);a.onupgradeneeded=async p=>{a.transaction.abort(),n?.("error","Database upgrade needed, but not expected","Expected",e,"Got",a.result.version),s(a.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${a.result.version}`))},a.onsuccess=p=>{o(a.result)},a.onblocked=p=>{s(new Error("Migration error: database blocked"))},a.onerror=p=>{s(new Error("Migration error: database error"))}});return r.addEventListener("versionchange",o=>{r.close()}),r}var Ze=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function dn({currentVersion:i,targetVersion:t,migrations:e}){let n=Qr({currentVersion:i,targetVersion:t,migrations:e});if(!n)throw new Ze(`No migration path found from ${i} to ${t}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return n}function Qr({currentVersion:i,targetVersion:t,migrations:e}){if(i===t)return[];let n=e.filter(r=>r.oldSchema.version===i).sort((r,o)=>o.newSchema.version-r.newSchema.version);for(;n.length>0;){let r=n.shift();if(r.newSchema.version>t)return null;if(r.newSchema.version===t)return[r];let o=Qr({currentVersion:r.newSchema.version,targetVersion:t,migrations:e});if(o)return[r,...o]}return null}var Di=typeof window<"u"?window.indexedDB:void 0;async function vt({version:i,indexedDB:t=Di,migrations:e,meta:n,context:r}){if(r.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let o=await Oi(t,r.namespace,i,r.log);r.log("debug","Current database version:",o,"target version:",i);let s=dn({currentVersion:o,targetVersion:i,migrations:e});return s.length>0&&(r.log("debug","Migrations to run:",s.map(a=>a.version)),await Ii({context:r,toRun:s,meta:n,indexedDB:t})),$e(t,r.namespace,i,r.log)}async function Jr({version:i,indexedDB:t=Di,migrations:e,meta:n,context:r,wipNamespace:o}){r.log("debug","Opening WIP database",o);let s=await Oi(t,o,i,r.log);if(s===i)r.log("info","WIP schema is up-to-date; not refreshing database");else{r.log("info","WIP schema is out-of-date; refreshing database");let a=dn({currentVersion:s,targetVersion:i-1,migrations:e});if(a.length>0){await Ii({context:r,toRun:a,meta:n,indexedDB:t,namespace:o});let l=await $e(t,r.namespace,i-1,r.log),m=await $e(t,o,i-1,r.log),v=new Array;for(let S=0;S<l.objectStoreNames.length;S++)v.push(l.objectStoreNames[S]);let y=l.transaction(v,"readonly"),C=v.map(S=>y.objectStore(S)),w=await Promise.all(C.map(S=>J(S.getAll()))),x=m.transaction(v,"readwrite"),I=v.map(S=>x.objectStore(S));for(let S=0;S<I.length;S++)await Promise.all(w[S].map(D=>J(I[S].put(D))))}let p=dn({currentVersion:i-1,targetVersion:i,migrations:e});p.length>0&&await Ii({context:r,toRun:p,meta:n,indexedDB:t,namespace:o})}return $e(t,o,i,r.log)}async function Ii({context:i,toRun:t,meta:e,indexedDB:n=Di,namespace:r=i.namespace}){await Wr(r,async()=>{for(let o of t){let s;if(o.oldSchema.version===0)s=Hs({meta:e,migration:o,context:i}),await o.migrate(s);else{let l=await $e(n,r,o.oldSchema.version,i.log);s=qs({meta:e,migration:o,context:{...i,documentDb:l}});try{await o.migrate(s),await Promise.all(s.awaitables)}catch(m){throw i.log("critical",`Migration failed (${o.oldSchema.version} -> ${o.newSchema.version})`,m),m instanceof Error?m:new Error("Unknown error during migration")}await ln(l)}i.log("debug","Upgrading database",r,"to version",o.newSchema.version),await Hr(n,r,o.newSchema.version,(l,m)=>{for(let v of o.addedCollections)m.createObjectStore(v,{keyPath:o.newSchema.collections[v].primaryKey,autoIncrement:!1});for(let v of o.allCollections){let y=l.objectStore(v);for(let C of o.addedIndexes[v]||[])y.createIndex(C.name,C.name,{multiEntry:C.multiEntry});for(let C of o.removedIndexes[v]||[])y.deleteIndex(C.name)}for(let v of o.removedCollections)l.objectStore(v).clear()},i.log);let a=await Gs({meta:e,currentVersion:o.oldSchema.version,newVersion:o.newSchema.version}),p=await $e(n,r,o.newSchema.version,i.log);for(let l of o.allCollections){let v=p.transaction(l,"readwrite").objectStore(l),C=(await Ws(v)).map(D=>Z(l,`${D}`));C.push(...s.newOids.filter(D=>me(D).collection===l),...a.filter(D=>me(D).collection===l));let x=(await Promise.all(C.map(async D=>{try{let F=await e.getDocumentSnapshot(D);return[D,F]}catch(F){return i.log("error","Could not regenerate snapshot during migration for oid",D,"this document will not be preserved",F),null}}))).filter(D=>!!D).map(([D,F])=>{if(!F)return[D,void 0];let b=qt(o.newSchema.collections[l],F);return[D,b]}),S=p.transaction(l,"readwrite").objectStore(l);await Promise.all(x.map(([D,F])=>{if(F)return Js(S,F);{let{id:b}=me(D);return Qs(S,b)}}))}await ln(p),i.log("debug",`Migration of ${r} complete.`),i.log(`
|
|
8
|
+
${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[t,r]=await Yt(e,["baselines","operations"]),o=await this.localReplica.get(),s=await this.schema.get();if(!s)throw new Error("Cannot export Client data before initializing");return{operations:r,baselines:t,localReplica:o,schema:s}};this.resetFrom=async e=>{let r=this.db.transaction(["baselines","operations","info"],"readwrite");await J(r.objectStore("baselines").clear()),await J(r.objectStore("operations").clear()),await J(r.objectStore("info").clear()),await this.localReplica.update({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:r})};this.stats=async()=>{let e=this.db,t=await wt(e,"operations"),r=await wt(e,"baselines");return{operationsSize:t,baselinesSize:r}};this.context=t,this.schema=new sn(t.metaDb,t.schema.version),this.operations=new on(this.db,{log:t.log}),this.baselines=new tn(this.db,{log:t.log}),this.localReplica=new nn(this.db),this.ackInfo=new en(this.db),this.messageCreator=new rn(this),this.patchCreator=new Gt(()=>this.now),e&&(this.disableRebasing=e)}get db(){return this.context.metaDb}get log(){return this.context.log}get now(){return this.time.now(this.schema.currentVersion)}};var Bs=[js,Ms,Ls,Us,Vs];function an({indexedDB:n=window.indexedDB,namespace:i,log:e,metadataVersion:t=5}){return new Promise((r,o)=>{let s=n.open(`${i}_meta`,t),a=!1;s.onupgradeneeded=async h=>{let u=s.result,m=s.transaction,v=Bs.slice(h.oldVersion);for(let y of v)await y(u,m);await new Promise((y,C)=>{m.addEventListener("complete",y),m.addEventListener("error",C)}),h.oldVersion||(a=!0)},s.onerror=()=>{console.error("Error opening database",s.error),o(s.error)},s.onsuccess=()=>{r({db:s.result,wasInitialized:a})}})}async function Hr({wipNamespace:n,namespace:i,indexedDB:e,log:t,metadataVersion:r}){let o=await an({namespace:n,indexedDB:e,log:t,metadataVersion:r});if(!o.wasInitialized)return o;t?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await an({namespace:i,indexedDB:e,log:t,metadataVersion:r}),a=s.transaction(["baselines","operations","info"],"readonly"),[h,u,m]=await Promise.all([J(a.objectStore("baselines").getAll()),J(a.objectStore("operations").getAll()),J(a.objectStore("info").getAll())]),v=o.db.transaction(["baselines","operations","info"],"readwrite"),y=v.objectStore("baselines"),C=v.objectStore("operations"),w=v.objectStore("info");for(let S of h)y.put(S);for(let S of u)C.put(S);for(let S of m)w.put(S);return await new Promise((S,I)=>{v.oncomplete=()=>{S()},v.onerror=x=>{I(x)},v.onabort=x=>{I(x)}}),await ze(s),t?.("debug","Finished copy of production metadata database to WIP. Copied:",h.length,"baselines,",u.length,"operations"),o}async function js(n,i){let e=n.createObjectStore("baselines",{keyPath:"oid"}),t=n.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=n.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),t.createIndex("isLocal_timestamp","isLocal_timestamp"),t.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Ms(n,i){let e=i.objectStore("operations");await new Promise((t,r)=>{let o=e.openCursor();o.onsuccess=()=>{let s=o.result;if(s){let{isLocal_timestamp:a,documentOid_timestamp:h,...u}=s.value;s.update({...u,l_t:a,d_t:h}),s.continue()}else t()},o.onerror=s=>{r(o.error)}}),e.deleteIndex("isLocal_timestamp"),e.deleteIndex("documentOid_timestamp"),e.createIndex("l_t","l_t",{unique:!1}),e.createIndex("o_t","o_t",{unique:!1}),e.createIndex("d_t","d_t",{unique:!1})}async function Ls(n,i){i.objectStore("operations").createIndex("timestamp","timestamp")}async function Us(n,i){let e=n.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function Vs(n,i){let e=i.objectStore("operations");await new Promise((r,o)=>{let s=e.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let h=di(a.value);h.oid_timestamp!==a.primaryKey?(a.delete(),e.put(h)):a.update(h),a.continue()}else r()},s.onerror=a=>{o(s.error)}});let t=i.objectStore("baselines");await new Promise((r,o)=>{let s=t.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let h=di(a.value);h.oid!==a.primaryKey?(a.delete(),t.put(h)):a.update(h),a.continue()}else r()},s.onerror=a=>{o(s.error)}})}var Ns=n=>IDBKeyRange.only(ve(n.equals)),$s=n=>{},zs=n=>{let i=n.gte||n.gt,e=n.lte||n.lt;return i===e?IDBKeyRange.only(ve(i)):i?e?IDBKeyRange.bound(ve(i),ve(e),!!n.gt,!!n.lt):IDBKeyRange.lowerBound(ve(i),!!n.gt):IDBKeyRange.upperBound(ve(e),!!n.lt)},Ks=(n,i,e)=>{let t=n.collections[i].compounds[e.where];L(t,`Index ${e.where} does not exist on collection ${i}`);let r=Object.keys(e.match).sort((h,u)=>t.of.indexOf(h)-t.of.indexOf(u));for(let h of r)if(t.of.indexOf(h)!==r.indexOf(h))throw new Error(`Compound index ${e.where} does not have ${h} at the start of its order`);let o=r.map(h=>e.match[h]);if(r.length===t.of.length)return IDBKeyRange.only(ce(...o));let s=$e(...o),a=Ne(...o);return IDBKeyRange.bound(s,a)};function qs(n){let i=n.startsWith,e=n.startsWith+"\uFFFF";return IDBKeyRange.bound(i,e)}function cn(n,i,e){if(e)return hi(e)?zs(e):fi(e)?Ns(e):jr(e)?$s(e):pi(e)?qs(e):Ks(n,i,e)}function Ii(n,i,e){return n.transaction(i,e?"readwrite":"readonly").objectStore(i)}async function ln({collection:n,index:i,context:e}){let t=Ii(e.documentDb,n),r=i?.where?t.index(i.where):t,o=cn(e.schema,n,i),s=i?.order==="desc"?"prev":"next",a=r.openCursor(o,s);return await new Promise((u,m)=>{a.onsuccess=()=>{let v=a.result;u(v?Z(n,v.primaryKey.toString()):null)},a.onerror=()=>{a.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",a.error),u(null)):le(a.error)?u(null):m(a.error)}})}async function dn({collection:n,index:i,context:e}){let t=Ii(e.documentDb,n),r=i?.where?t.index(i.where):t,o=cn(e.schema,n,i),s=i?.order==="desc"?"prev":"next",a=r.openCursor(o,s);return await new Promise((u,m)=>{let v=new Set;a.onsuccess=()=>{let y=a.result;y?(v.add(Z(n,y.primaryKey.toString())),y.continue()):u(Array.from(v))},a.onerror=()=>{a.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",a.error),u([])):le(a.error)?u([]):m(a.error)}})}async function xt({collection:n,index:i,context:e,limit:t,offset:r}){let o=Ii(e.documentDb,n),s=i?.where?o.index(i.where):o,a=cn(e.schema,n,i),h=i?.order==="desc"?"prev":"next",u=s.openCursor(a,h),m=!r,v=!1,y=0;return{result:await new Promise((w,S)=>{let I=new Set;u.onsuccess=()=>{y++;let x=u.result;x?r&&!m?(x.advance(r),m=!0):(t&&I.size<t&&I.add(Z(n,x.primaryKey.toString())),t&&y>t?(v=!0,w(Array.from(I))):x.continue()):w(Array.from(I))},u.onerror=()=>{u.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",u.error),w([])):le(u.error)?w([]):S(u.error)}}),hasNextPage:v}}async function _i(n,i,e,t){function r(a,h){let u,m,v=n.open([i,"collections"].join("_"),e);v.onupgradeneeded=async y=>{u=y.oldVersion;let C=v.transaction;m=v.result,C.abort()},v.onsuccess=y=>{a([v.result.version,v.result])},v.onblocked=y=>{t?.("Database blocked, waiting...")},v.onerror=y=>{a([u,m])}}let[o,s]=await new Promise(r);return await un(s),o}async function un(n){n.close(),await new Promise(i=>i())}async function Wr(n,i,e,t,r){function o(s,a){let h=n.open([i,"collections"].join("_"),e),u=!1;h.onupgradeneeded=m=>{let v=h.transaction;t(v,h.result,m),u=!0},h.onsuccess=m=>{h.result.close(),u?s():a(new Error("Database was not upgraded when a version change was expected"))},h.onerror=m=>{a(h.error||new Error("Unknown error"))},h.onblocked=m=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(o)}async function Qr(n,i){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${n}`,i):await i()}async function Ke(n,i,e,t){t?.("debug","Opening database",i,"at version",e);let r=await new Promise((o,s)=>{let a=n.open([i,"collections"].join("_"),e);a.onupgradeneeded=async h=>{a.transaction.abort(),t?.("error","Database upgrade needed, but not expected","Expected",e,"Got",a.result.version),s(a.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${a.result.version}`))},a.onsuccess=h=>{o(a.result)},a.onblocked=h=>{s(new Error("Migration error: database blocked"))},a.onerror=h=>{s(new Error("Migration error: database error"))}});return r.addEventListener("versionchange",o=>{r.close()}),r}var et=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function fn({currentVersion:n,targetVersion:i,migrations:e}){let t=Jr({currentVersion:n,targetVersion:i,migrations:e});if(!t)throw new et(`No migration path found from ${n} to ${i}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return t}function Jr({currentVersion:n,targetVersion:i,migrations:e}){if(n===i)return[];let t=e.filter(r=>r.oldSchema.version===n).sort((r,o)=>o.newSchema.version-r.newSchema.version);for(;t.length>0;){let r=t.shift();if(r.newSchema.version>i)return null;if(r.newSchema.version===i)return[r];let o=Jr({currentVersion:r.newSchema.version,targetVersion:i,migrations:e});if(o)return[r,...o]}return null}var Ei=typeof window<"u"?window.indexedDB:void 0;async function St({version:n,indexedDB:i=Ei,migrations:e,meta:t,context:r}){if(r.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let o=await _i(i,r.namespace,n,r.log);r.log("debug","Current database version:",o,"target version:",n);let s=fn({currentVersion:o,targetVersion:n,migrations:e});return s.length>0&&(r.log("debug","Migrations to run:",s.map(a=>a.version)),await Di({context:r,toRun:s,meta:t,indexedDB:i})),Ke(i,r.namespace,n,r.log)}async function Gr({version:n,indexedDB:i=Ei,migrations:e,meta:t,context:r,wipNamespace:o}){r.log("debug","Opening WIP database",o);let s=await _i(i,o,n,r.log);if(s===n)r.log("info","WIP schema is up-to-date; not refreshing database");else{r.log("info","WIP schema is out-of-date; refreshing database");let a=fn({currentVersion:s,targetVersion:n-1,migrations:e});if(a.length>0){await Di({context:r,toRun:a,meta:t,indexedDB:i,namespace:o});let u=await Ke(i,r.namespace,n-1,r.log),m=await Ke(i,o,n-1,r.log),v=new Array;for(let x=0;x<u.objectStoreNames.length;x++)v.push(u.objectStoreNames[x]);let y=u.transaction(v,"readonly"),C=v.map(x=>y.objectStore(x)),w=await Promise.all(C.map(x=>J(x.getAll()))),S=m.transaction(v,"readwrite"),I=v.map(x=>S.objectStore(x));for(let x=0;x<I.length;x++)await Promise.all(w[x].map(_=>J(I[x].put(_))))}let h=fn({currentVersion:n-1,targetVersion:n,migrations:e});h.length>0&&await Di({context:r,toRun:h,meta:t,indexedDB:i,namespace:o})}return Ke(i,o,n,r.log)}async function Di({context:n,toRun:i,meta:e,indexedDB:t=Ei,namespace:r=n.namespace}){await Qr(r,async()=>{for(let o of i){let s;if(o.oldSchema.version===0)s=Qs({meta:e,migration:o,context:n}),await o.migrate(s);else{let u=await Ke(t,r,o.oldSchema.version,n.log);s=Ws({meta:e,migration:o,context:{...n,documentDb:u}});try{await o.migrate(s),await Promise.all(s.awaitables)}catch(m){throw n.log("critical",`Migration failed (${o.oldSchema.version} -> ${o.newSchema.version})`,m),m instanceof Error?m:new Error("Unknown error during migration")}await un(u)}n.log("debug","Upgrading database",r,"to version",o.newSchema.version),await Wr(t,r,o.newSchema.version,(u,m)=>{for(let v of o.addedCollections)m.createObjectStore(v,{keyPath:o.newSchema.collections[v].primaryKey,autoIncrement:!1});for(let v of o.allCollections){let y=u.objectStore(v);for(let C of o.addedIndexes[v]||[])y.createIndex(C.name,C.name,{multiEntry:C.multiEntry});for(let C of o.removedIndexes[v]||[])y.deleteIndex(C.name)}for(let v of o.removedCollections)u.objectStore(v).clear()},n.log);let a=await Xs({meta:e,currentVersion:o.oldSchema.version,newVersion:o.newSchema.version}),h=await Ke(t,r,o.newSchema.version,n.log);for(let u of o.allCollections){let v=h.transaction(u,"readwrite").objectStore(u),C=(await Js(v)).map(_=>Z(u,`${_}`));C.push(...s.newOids.filter(_=>me(_).collection===u),...a.filter(_=>me(_).collection===u));let S=(await Promise.all(C.map(async _=>{try{let R=await e.getDocumentSnapshot(_);return[_,R]}catch(R){return n.log("error","Could not regenerate snapshot during migration for oid",_,"this document will not be preserved",R),null}}))).filter(_=>!!_).map(([_,R])=>{if(!R)return[_,void 0];let b=Wt(o.newSchema.collections[u],R);return[_,b]}),x=h.transaction(u,"readwrite").objectStore(u);await Promise.all(S.map(([_,R])=>{if(R)return Ys(x,R);{let{id:b}=me(_);return Gs(x,b)}}))}await un(h),n.log("debug",`Migration of ${r} complete.`),n.log(`
|
|
9
9
|
\u2B06\uFE0F v${o.newSchema.version} Migration complete. Here's the rundown:
|
|
10
10
|
- Added collections: ${o.addedCollections.join(", ")}
|
|
11
11
|
- Removed collections: ${o.removedCollections.join(", ")}
|
|
12
12
|
- Changed collections: ${o.changedCollections.join(", ")}
|
|
13
|
-
- New indexes: ${Object.keys(o.addedIndexes).map(
|
|
14
|
-
- Removed indexes: ${Object.keys(o.removedIndexes).map(
|
|
15
|
-
`)}})}function Gr({migration:i,meta:t,getMigrationNow:e,newOids:n}){return i.allCollections.reduce((r,o)=>(r[o]={put:async s=>{Pe(i.newSchema.collections[o],s);let a=s[i.newSchema.collections[o].primaryKey],p=Z(o,a);return n.push(p),await t.insertLocalOperations(Re(s,p,e)),s},delete:async s=>{let a=Z(o,s),p=await t.getAllDocumentRelatedOids(a);return t.insertLocalOperations(p.map(l=>({oid:l,timestamp:e(),data:{op:"delete"}})))}},r),{})}function zs({migration:i,context:t,meta:e}){return i.oldCollections.reduce((n,r)=>(n[r]={get:async o=>{let s=Z(r,o);return await e.getDocumentSnapshot(s,{to:e.time.now(i.oldSchema.version)})},findOne:async o=>{let s=await an({collection:r,index:o,context:t});return s?await e.getDocumentSnapshot(s,{to:e.time.now(i.oldSchema.version)}):null},findAll:async o=>{let s=await cn({collection:r,index:o,context:t});return await Promise.all(s.map(p=>e.getDocumentSnapshot(p,{to:e.time.now(i.oldSchema.version)})))}},n),{})}function qs({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,o=zs({migration:t,context:e,meta:i}),s=Gr({migration:t,getMigrationNow:n,newOids:r,meta:i}),a=async m=>{let v=await i.getAllCollectionRelatedOids(m);return i.insertLocalOperations(v.map(y=>({oid:y,timestamp:n(),data:{op:"delete"}})))},p=new Array;return{log:e.log,newOids:r,deleteCollection:a,migrate:async(m,v)=>{let y=await o[m].findAll();await Promise.all(y.filter(Boolean).map(async C=>{let w=ne(C);L(!!w,`Document is missing an OID: ${JSON.stringify(C)}`);let x=ae(C),I=await v(C);if(I){ft(x),ft(I),Ye(I);let S=ht(x,I,n,void 0,[],{mergeUnknownObjects:!0});S.length>0&&await i.insertLocalOperations(S)}}))},queries:o,mutations:s,awaitables:p}}function Hs({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,o=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),s=Gr({migration:t,getMigrationNow:n,newOids:r,meta:i});return{log:e.log,newOids:r,deleteCollection:()=>{throw new Error("Calling deleteCollection() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:o,mutations:s,awaitables:[]}}async function Ws(i){return new Promise((t,e)=>{let n=i.getAllKeys();n.onsuccess=r=>{t(n.result)},n.onerror=r=>{e(n.error)}})}async function Qs(i,t){let e=i.delete(t);return new Promise((n,r)=>{e.onsuccess=o=>{n()},e.onerror=o=>{r(e.error)}})}async function Js(i,t){let e=i.put(t);return new Promise((n,r)=>{e.onsuccess=o=>{n()},e.onerror=o=>{r(e.error)}})}async function Gs({meta:i,currentVersion:t,newVersion:e}){let n=[];return await i.operations.iterateOverAllOperations(r=>n.push(r),{from:i.time.zero(t+1)}),Array.from(new Set(n.map(r=>$(r.oid))))}var St=class extends U{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();if(e){let n=await e();return n&&this._undone.push(n),this.emit("change"),!0}return!1};this.redo=async()=>{let e=this._undone.pop();if(e){let n=await e();return n&&this._undoable.push(n),this.emit("change"),!0}return!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var un=class{constructor(t,e,n){this.meta=t;this.schema=e;this.entities=n;this.getOid=(t,e)=>{let n=this.schema.collections[t].primaryKey,r=e[n];return L(r,`Document must have a primary key: ${n.toString()} (got: ${JSON.stringify(e)})`),Z(t,r)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return Pe(n,e)};this.create=(t,e,n={})=>{let r=this.addDefaults(t,e),o=this.getOid(t,r);return this.entities.create(r,o,n)};this.delete=async(t,e,n={})=>{let r=Z(t,e);return this.entities.delete(r,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,r])=>Z(n,r)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(r=>Z(t,r)),n)}};var et=Symbol("entity-file-update"),xt=Symbol("entity-file-mark-failed"),Ys,Xs,de=class extends U{constructor(e,{downloadRemote:n=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._downloadRemote=!1;this[Ys]=e=>{this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[Xs]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.destroy=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this.dispose()};this._downloadRemote=n}static{Ys=et,Xs=xt}get downloadRemote(){return this._downloadRemote}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}getSnapshot(){return{id:this.id,url:this.loading||this.failed?void 0:this.url}}};var Yr=Qe(at(),1);function Zs(i){return{id:(0,Yr.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function _i(i){return i instanceof File||typeof Blob<"u"&&i instanceof Blob}function tt(i,t){if(typeof window<"u"&&_i(i)){let e=Zs(i);return t(e),Bt(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=tt(i[e],t);return i}if(typeof i=="object"){for(let e in i)i[e]=tt(i[e],t);return i}return i}function Xr(i){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(i)})}var fn=class extends se{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:r=!1}={})=>{let o=e.file?await Xr(e.file):void 0;if(!o&&r&&e.url)try{o=await fetch(e.url,{method:"GET",credentials:"include"}).then(s=>s.arrayBuffer())}catch(s){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",s)}return this.run("files",s=>s.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:o}),{mode:"readwrite",transaction:n})};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?ea(n,e.type):void 0,e};this.markUploaded=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",o=>o.put({...r,remote:"true"}),{mode:"readwrite",transaction:n})};this.getFileRaw=async(e,{transaction:n}={})=>{let r=await this.run("files",o=>o.get(e),{mode:"readonly",transaction:n});if(r)return r};this.getFile=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",o=>o.put({...r,deletedAt:Date.now()}),{mode:"readwrite",transaction:n})};this.listUnsynced=async()=>(await this.run("files",n=>n.index("remote").getAll("false"),{mode:"readonly"})).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,n)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,o)=>{e(this.hydrateFileData(r),o)},{mode:"readwrite",transaction:n});this.getAll=async()=>{let[e]=await Jt(this.db,["files"]);return e.map(this.hydrateFileData)}}deleteFile(e,{transaction:n}={}){return this.run("files",r=>r.delete(e),{mode:"readwrite",transaction:n})}};function ea(i,t){return new Blob([i],{type:t})}function ta(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3}var pn=class{constructor({db:t,sync:e,context:n,meta:r,config:o={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[et](e);else{let n=new de(e.id);n[et](e),this.files.set(e.id,n)}await this.storage.addFile(e),e.file&&await this.uploadFile(e,1)};this.uploadFile=async(t,e=0)=>{let n=await this.sync.uploadFile(t);n.success?await this.storage.markUploaded(t.id):n.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,t,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=(t,e)=>{if(this.files.has(t))return this.files.get(t);let n=new de(t,e);return this.files.set(t,n),this.load(n),n};this.load=async(t,e=0)=>{if(e>5){this.context.log("error","Failed to load file after 5 retries"),t[xt]();return}let n=await this.storage.getFile(t.id);if(n)t[et](n);else try{let r=await this.sync.getFile(t.id);r.success?(t[et](r.data),await this.storage.addFile(r.data,{downloadRemote:t.downloadRemote})):(this.context.log("error","Failed to load file",r),t[xt](),r.retry&&setTimeout(this.load,1e3,t,e+1))}catch(r){this.context.log("error","Failed to load file",r),t[xt](),setTimeout(this.load,1e3,t,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.exportAll=async(t=!1)=>{let e=await this.storage.getAll();if(t){for(let n of e)if(!n.file&&n.url)try{let r=await fetch(n.url,{method:"GET",credentials:"include"}).then(o=>o.blob());n.file=r}catch(r){this.context.log("error","Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",r)}}return e};this.importAll=async t=>{await Promise.all(t.map(e=>this.add(e)))};this.onOnlineChange=async t=>{if(t){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let t=0,e=0;await this.storage.iterateOverPendingDelete((n,r)=>{this.config.canCleanupDeletedFile(n)?(t++,r.delete(n.id)):e++}),this.context.log("info",`Cleaned up ${t} files, skipped ${e} files`)};this.handleFileRefsDeleted=async t=>{let e=this.storage.createTransaction(["files"],{mode:"readwrite"});await Promise.all(t.map(async n=>{try{await this.storage.markPendingDelete(n.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${t.length} files as pending delete`)};this.storage=new fn(t),this.sync=e,this.context=n,this.meta=r,this.config={canCleanupDeletedFile:ta,...o},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var hn=class{constructor({initial:t}={}){this.cache=new Map;this.get=t=>{if(this.cache.has(t.oid))return this.cache.get(t.oid);let e=new ue(t);return this.cache.set(t.oid,e),e};this.has=t=>this.cache.has(t);this.getFile=(t,e)=>{if(this.cache.has(t))return this.cache.get(t);let n=new de(t,e);return this.cache.set(t,n),n};this.getCached=t=>this.cache.get(t);if(t)for(let e of t)this.cache.set(e.oid,e)}};var ue=class i extends U{constructor({oid:e,schema:n,entityFamily:r,parent:o,ctx:s,metadataFamily:a,readonlyKeys:p,files:l,patchCreator:m,events:v}){super();this.fieldPath=[];this._viewData=void 0;this.validationError=void 0;this.cachedDeepUpdatedAt=null;this.wasDeletedLastChange=!1;this.cachedView=void 0;this.onAdd=(e,n)=>{n.oid===this.oid&&this.addConfirmedData(n)};this.onReplace=(e,n)=>{n.oid===this.oid&&this.replaceAllData(n)};this.onResetAll=()=>{this.resetAllData()};this.childIsNull=e=>{if(e instanceof i){let n=e.view;return n==null}return e==null};this.validate=Nr(()=>(this.validationError=Te({field:this.schema,value:this.rawView,fieldPath:this.fieldPath,depth:1})??void 0,this.validationError),()=>[this.viewData]);this.viewWithMappedChildren=e=>{let n=this.view;if(!n)return null;if(Array.isArray(n)){let r=n.map(o=>o instanceof i||o instanceof de?e(o):o);return K(r,this.oid),r}else{let r=Object.entries(n).reduce((o,[s,a])=>(a instanceof i||a instanceof de?o[s]=e(a):o[s]=a,o),{});return K(r,this.oid),r}};this.getSnapshot=()=>this.viewWithMappedChildren(e=>e.getSnapshot());this.addPendingOperations=e=>{this.ctx.log("debug","Entity: adding pending operations",this.oid);let n=this.metadataFamily.addPendingData(e);for(let r of n)this.change(r)};this.addConfirmedData=e=>{this.ctx.log("debug","Entity: adding confirmed data",this.oid);let n=this.metadataFamily.addConfirmedData(e);for(let r of n)this.change(r)};this.replaceAllData=e=>{this.ctx.log("debug","Entity: replacing all data",this.oid);let n=this.metadataFamily.replaceAllData(e);for(let r of n)this.change(r)};this.resetAllData=()=>{this.ctx.log("debug","Entity: resetting all data",this.oid),this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this._viewData=void 0;let e=this.metadataFamily.replaceAllData({});for(let n of e)this.change(n)};this.change=e=>{if(e.oid===this.oid)this._viewData=void 0,this.cachedView=void 0,this.deepChange(this,e),this.ctx.log("Emitting change event",this.oid),this.emit("change",{isLocal:e.isLocal}),this.parent||(this.deleted&&!this.wasDeletedLastChange?(this.ctx.log("debug","Entity deleted",this.oid),this.emit("delete",{isLocal:e.isLocal}),this.wasDeletedLastChange=!0):!this.deleted&&this.wasDeletedLastChange&&(this.ctx.log("debug","Entity restored",this.oid),this.emit("restore",{isLocal:e.isLocal}),this.wasDeletedLastChange=!1));else{let n=this.entityFamily.getCached(e.oid);n&&n instanceof i&&n.change(e)}};this.deepChange=(e,n)=>{this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this.ctx.log("debug","Deep change detected at",this.oid,"reset cached view"),this.ctx.log("debug","Emitting deep change event",this.oid),this.emit("changeDeep",e,n),this.parent?.deepChange(e,n)};this.getChild=(e,n)=>{let r=Ne(this.schema,e);if(!r)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);return this.entityFamily.get({oid:n,schema:r,entityFamily:this.entityFamily,metadataFamily:this.metadataFamily,parent:this,ctx:this.ctx,files:this.files,fieldPath:[...this.fieldPath,e],patchCreator:this.patchCreator,events:this.events})};this.get=e=>{Zr(e);let n=this.rawView;if(!n)throw new Error(`Cannot access data at key ${e} on deleted entity ${this.oid}`);let r=n[e],o=Ne(this.schema,e);if(!o)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if(Q(r))if(be(r)){if(o.type!=="file")throw new Error(`Expected file schema for key ${String(e)}, got ${o.type}`);let s=this.files.get(r.id,{downloadRemote:!!o.downloadRemote});return s.subscribe("change",()=>{this.deepChange(this,{isLocal:!1,oid:this.oid})}),s}else return this.getChild(e,r.id);else return Te({field:o,value:r,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0})?Ce(o)?hi(o):we(o)?null:void 0:r};this.processInputValue=(e,n)=>{if(this.readonlyKeys.includes(n))throw new Error(`Cannot set readonly key ${n.toString()}`);_i(e)||(e=ae(e,!1));let r=Ne(this.schema,n);if(r){Le(e,r);let o=Te({field:r,value:e,fieldPath:[...this.fieldPath,n]});if(o)throw new Error(o.message)}return tt(e,this.files.add)};this.getDeleteMode=e=>{if(this.readonlyKeys.includes(e))return!1;if(this.schema.type==="any"||this.schema.type==="map")return"delete";if(this.schema.type==="object"){let n=this.schema.properties[e];if(!n||n.type==="any")return"delete";if(n.type==="map")return!1;if(n.nullable)return"null"}return!1};this.getItemRefValue=e=>{if(e instanceof i)return he(e.oid);if(e instanceof de)return Bt(e.id);if(typeof e=="object"){let n=pe(e);if(!n||!this.entityFamily.has(n))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return he(n)}else return e};this.set=(e,n)=>{Zr(e),this.addPendingOperations(this.patchCreator.createSet(this.oid,e,this.processInputValue(n,e)))};this.getAll=()=>this.view;this.delete=e=>{if(this.isList)na(e),this.addPendingOperations(this.patchCreator.createListDelete(this.oid,e));else{let n=this.getDeleteMode(e);if(!n)throw new Error(`Cannot delete key ${e.toString()} - the property is not marked as optional in the schema.`);n==="delete"?this.addPendingOperations(this.patchCreator.createRemove(this.oid,e)):this.addPendingOperations(this.patchCreator.createSet(this.oid,e,null))}};this.keys=()=>this.view?Object.keys(this.view):[];this.entries=()=>this.view?Object.entries(this.view):[];this.values=()=>this.view?Object.values(this.view):[];this.update=(e,{merge:n=!0,replaceSubObjects:r=!1}={})=>{if(!n&&this.schema.type!=="any"&&this.schema.type!=="map")throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');let o={};K(o,this.oid);for(let[s,a]of Object.entries(e)){if(this.readonlyKeys.includes(s))throw new Error(`Cannot set readonly key ${s.toString()}`);let p=Ne(this.schema,s);p&&Le(a,p),o[s]=this.processInputValue(a,s)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),o,{mergeUnknownObjects:!r,defaultUndefined:n}))};this.push=e=>{this.addPendingOperations(this.patchCreator.createListPush(this.oid,this.processInputValue(e,this.view.length)))};this.insert=(e,n)=>{this.addPendingOperations(this.patchCreator.createListInsert(this.oid,e,this.processInputValue(n,e)))};this.move=(e,n)=>{this.addPendingOperations(this.patchCreator.createListMoveByIndex(this.oid,e,n))};this.moveItem=(e,n)=>{let r=this.getItemRefValue(e);if(Q(r))this.addPendingOperations(this.patchCreator.createListMoveByRef(this.oid,r,n));else{let o=this.view.indexOf(e);if(o===-1)throw new Error(`Cannot move item ${JSON.stringify(e)} which does not exist in this list`);this.move(o,n)}};this.add=e=>{this.addPendingOperations(this.patchCreator.createListAdd(this.oid,this.processInputValue(e,this.view.length)))};this.removeAll=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e)))};this.removeFirst=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"first"))};this.removeLast=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"last"))};this.map=e=>this.view.map(e);this.filter=e=>this.view.filter(e);this.has=e=>{if(!this.isList)throw new Error("has() is only available on list entities");let n=this.getItemRefValue(e);return Q(n)?this.view.some(r=>{if(Q(r))return Ge(r,n)}):this.view.includes(e)};this.forEach=e=>{this.view.forEach(e)};this.some=e=>this.view.some(e);this.every=e=>this.view.every(e);this.find=e=>this.view.find(e);this.includes=this.has;this.__getViewData__=(e,n)=>this.metadataFamily.get(e).computeView(n==="confirmed");this.__getFamilyOids__=()=>this.metadataFamily.getAllOids();L(!!e,"oid is required"),this.oid=e,this.readonlyKeys=p||[],this.ctx=s,this.files=l,this.schema=n,this.entityFamily=r||new hn({initial:[this]}),this.patchCreator=m,this.metadataFamily=a,this.events=v,this.parent=o,this.parent||(v.add.attach(this.onAdd),v.replace.attach(this.onReplace),v.resetAll.attach(this.onResetAll))}get metadata(){return this.metadataFamily.get(this.oid)}get viewData(){return this._viewData===void 0&&(this._viewData=this.metadata.computeView(),this.validate()),this._viewData}get rawView(){return this.viewData.view}get view(){if(this.cachedView!==void 0)return this.cachedView;if(this.viewData.deleted)return null;let e=this.rawView;if(!e&&!we(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!V(e))return Ce(this.schema)?hi(this.schema):null;if(this.cachedView=this.isList?[]:{},K(this.cachedView,this.oid),Array.isArray(e)){let r=Ne(this.schema,0);if(!r)this.ctx.log("error","No child field schema for list entity.",this.oid);else for(let o=0;o<e.length;o++){let s=this.get(o);this.childIsNull(s)&&!we(r)?this.ctx.log("error","Child missing in non-nullable field",this.oid,"index:",o):this.cachedView.push(s)}}else if(V(e)){let r=this.schema.type==="object"?Object.keys(this.schema.properties):Object.keys(e);for(let o of r){let s=Ne(this.schema,o);if(!s){this.ctx.log("error","No child field schema for object entity at key",o),this.schema.type==="map"?this.cachedView={}:this.cachedView=null;break}let a=this.get(o);if(this.childIsNull(a)&&!we(s)){if(this.ctx.log("error","Child entity is missing for non-nullable field",this.oid,"key:",o),this.schema.type!=="map"){this.cachedView=null;break}}else this.cachedView[o]=a}}return this.cachedView}get uid(){return this.oid}get deleted(){return this.viewData.deleted||this.view===null}get invalid(){return!!this.validate()}get isList(){return this.schema.type==="array"||Array.isArray(this.viewData.view)}get updatedAt(){return this.viewData.updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let e=this.updatedAt;return this.isList?this.forEach(n=>{if(n instanceof i){let r=n.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}):this.values().forEach(n=>{if(n instanceof i){let r=n.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}),this.cachedDeepUpdatedAt=e,e}get isOutdatedVersion(){return this.parent?this.parent.isOutdatedVersion:this.viewData.fromOlderVersion}get length(){return this.view.length}[Symbol.iterator](){let e=0,n=this.view?.length;return{next:()=>e<n?{value:this.get(e++),done:!1}:{value:void 0,done:!0}}}};function Zr(i){if(typeof i=="symbol")throw new Error("Symbol keys aren't supported")}function na(i){if(typeof i!="number")throw new Error("Only number keys are supported in list entities")}var Ei=class{constructor({oid:t,ctx:e,confirmedOperations:n,pendingOperations:r,baseline:o}){this.baseline=null;this.confirmedOperations=[];this.pendingOperations=[];this.computeView=(t=!1)=>{let e=ae(this.baseline?.snapshot??void 0),n=this.baseline?.timestamp??null,r=this.applyOperations(e,!e,this.confirmedOperations,n,n);r.futureSeen&&this.ctx.globalEvents.emit("futureSeen",r.futureSeen);let o=t?r:this.applyOperations(r.view,r.deleted,this.pendingOperations,r.latestTimestamp,null);o.view&&K(o.view,this.oid);let s=!!r.latestTimestamp&&Xn(r.latestTimestamp,this.ctx.getNow())<0,a=!this.baseline&&!this.pendingOperations.length&&!this.confirmedOperations.length;a&&this.ctx.log("warn",`Tried to load Entity ${this.oid} with no data`);let p=o.latestTimestamp??r.latestTimestamp??n,l=p?Zn(p):0;if(!o.view&&!o.deleted&&!a){this.ctx.log("warn",`Entity ${this.oid} has no view, no deleted flag, and not empty`);debugger}return{view:o.view??void 0,deleted:o.deleted,empty:a,fromOlderVersion:s,updatedAt:l}};this.addBaseline=t=>{if(!(this.baseline&&this.baseline.timestamp>=t.timestamp))for(this.baseline=t;this.confirmedOperations[0]?.timestamp<t.timestamp;)this.confirmedOperations.shift()};this.addConfirmedOperations=t=>{let e=0;for(let n of t){let r=this.confirmedOperations.findIndex(s=>s.timestamp>=n.timestamp);r!==-1?this.confirmedOperations[r].timestamp!==n.timestamp&&(this.confirmedOperations.splice(r,0,n),e++):(this.confirmedOperations.push(n),e++);let o=this.pendingOperations.length;this.pendingOperations=this.pendingOperations.filter(s=>n.timestamp!==s.timestamp),e-=o-this.pendingOperations.length}return e};this.addPendingOperation=t=>{this.pendingOperations.push(t)};this.applyOperations=(t,e,n,r,o)=>{let s,a=this.ctx.getNow();for(let p of n)if(!(o&&p.timestamp<=o)){if(Xn(p.timestamp,a)>0){s=p.timestamp;continue}p.data.op==="delete"?e=!0:(t=je(t,p.data),p.data.op==="initialize"&&(e=!1)),(!r||p.timestamp>r)&&(r=p.timestamp)}return{view:t,latestTimestamp:r??null,deleted:e,futureSeen:s}};L(t,"oid is required"),this.ctx=e,this.oid=t,n&&(this.confirmedOperations=n),r&&(this.pendingOperations=r),o&&(this.baseline=o)}},mn=class{constructor({ctx:t,onPendingOperations:e,rootOid:n}){this.entities=new Map;this.get=t=>(L(t,"oid is required"),this.entities.has(t)||this.entities.set(t,new Ei({oid:t,ctx:this.ctx})),this.entities.get(t));this.getAllOids=()=>Array.from(this.entities.keys());this.addConfirmedData=({baselines:t=[],operations:e={},isLocal:n=!1})=>{let r={};for(let o of t){if(!Ee(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o)}for(let[o,s]of Object.entries(e)){if(!Ee(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s)!==0&&(r[o]??={oid:o,isLocal:n})}return Object.values(r)};this.addPendingData=t=>{let e={};for(let n of t)this.get(n.oid).addPendingOperation(n),e[n.oid]??={oid:n.oid,isLocal:!0};return this.onPendingOperations(t),Object.values(e)};this.replaceAllData=({operations:t={},baselines:e=[]})=>{let n=Array.from(this.entities.keys());this.entities.clear();let r={};for(let o of n)r[o]={oid:o,isLocal:!1};for(let o of e){if(!Ee(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o),r[o.oid]??={oid:o.oid,isLocal:!1}}for(let[o,s]of Object.entries(t)){if(!Ee(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s),r[o]??={oid:o,isLocal:!1}}return Object.values(r)};this.ctx=t,this.rootOid=n,this.onPendingOperations=e}};var Ot="@@default",gn=class{constructor({batchTimeout:t=200,meta:e,ctx:n,entities:r}){this.currentBatchKey=Ot;this.flushOperations=async(t,e,n)=>{if(this.ctx.log("debug","Flushing",t.length,"operations from batch",e,"to storage / sync"),!!t.length){for(let r of t)r.timestamp=this.meta.now;await this.commitOperations(t,n)}};this.commitOperations=async(t,e)=>{if(t.length){if(e.undoable){let n=await this.createUndo({ops:t,source:e.source});n&&this.ctx.undoHistory.addUndo(n)}await this.entities.addData({operations:t,baselines:[],isLocal:!0})}};this.addOperations=t=>{t.length&&(this.batcher.add({key:this.currentBatchKey,items:t}),this.ctx.log("debug","added",t.length,"ops to batch",this.currentBatchKey,", size = ",this.batcher.getSize(this.currentBatchKey)))};this.batch=({undoable:t=!0,batchName:e=Nt(),max:n=null,timeout:r=this.defaultBatchTimeout}={})=>{let o=this.batcher.add({key:e,max:n,timeout:r,items:[],userData:{undoable:t}}),s={run:a=>(this.currentBatchKey=e,a(),this.currentBatchKey=Ot,s),commit:async()=>(await this.batcher.flush(Ot),o.flush()),flush:()=>s.commit(),discard:()=>{this.batcher.discard(e)}};return s};this.flushAll=()=>Promise.all(this.batcher.flushAll());this.createUndo=async t=>{let e=await this.getInverseOperations(t);return e.length?async()=>{let n=await this.createUndo({ops:e,source:t.source});for(let r of e)r.timestamp=this.meta.now;return await this.commitOperations(e,{undoable:!1}),n}:null};this.getInverseOperations=async({ops:t,source:e})=>{let n=mt(t),r=[],o=()=>this.meta.now;return await Promise.all(Object.entries(n).map(async([s,a])=>{let l=(e??await this.entities.hydrate($(s)))?.__getViewData__(s,"confirmed");if(!l){this.ctx.log("warn","could not find entity",s,"for undo operation",t);return}let m=Lr(s,l.view,a,o);r.unshift(...m)})),r};this.meta=e,this.ctx=n,this.entities=r,this.defaultBatchTimeout=t,this.batcher=new Xe(this.flushOperations),this.batcher.add({key:Ot,items:[],max:100,timeout:t,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===Ot}};var yn=class extends se{constructor({ctx:e}){super(e.documentDb,{log:e.log});this.reset=async()=>{let e=Object.keys(this.ctx.schema.collections),n=this.ctx.documentDb.transaction(e,"readwrite");await Promise.all(e.map(r=>{let o=n.objectStore(r);return J(o.clear())})),this.ctx.entityEvents.emit("collectionsChanged",e),this.ctx.log("info","\u{1F4A8} Reset queryable storage")};this.saveEntities=async(e,n)=>{if(e.length===0)return;let r=Array.from(new Set(e.map(a=>me(a.oid).collection))),o=r.filter(a=>!this.ctx.schema.collections[a]);if(o.length>0){this.ctx.log("warn",`Ignoring entities from collections that no longer exist: ${o.join(", ")}`);let a=new Set(r);o.forEach(p=>a.delete(p)),r=Array.from(a)}let s={transaction:this.createTransaction(r,{mode:"readwrite",abort:n?.abort})};await Promise.all(e.map(async a=>{let p=a.getSnapshot();try{await this.saveDocument(a.oid,p,s)}catch(l){throw this.ctx.log("error",`Error saving document ${a.oid} (${JSON.stringify(p)})`,l),l instanceof Error?l:new Error("Unknown error saving document")}})),s.transaction.commit(),this.ctx.entityEvents.emit("collectionsChanged",r);for(let a of e)this.ctx.entityEvents.emit("documentChanged",a.oid)};this.saveDocument=async(e,n,{transaction:r})=>{this.ctx.log("debug",`Saving document indexes for querying ${e}`,n);let{collection:o,id:s}=me(e);if(!n)await this.run(o,a=>a.delete(s),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Deleted document indexes for querying ${e}`);else{let a=this.ctx.schema.collections[o],p=qt(a,n);await this.run(o,l=>l.put(p),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Saved document indexes for querying ${e}`,n)}};this.ctx=e,this.addDispose(this.ctx.internalEvents.subscribe("documentDbChanged",n=>{this.db=n}))}};var _n=Qe(ko(),1);var En=class extends Ie{constructor({ctx:e,meta:n,files:r}){super();this.events={add:new _n.WeakEvent,replace:new _n.WeakEvent,resetAll:new _n.WeakEvent};this.cache=new Map;this.pendingEntityPromises=new Map;this.abortDataQueueController=new AbortController;this.ongoingResetPromise=null;this.entityFinalizationRegistry=new FinalizationRegistry(e=>{this.ctx.log("debug","Entity GC",e)});this.addData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not adding incoming data");return}e.reset&&(this.ctx.log("info","Resetting local store to replicate remote synced data - dropping any current transactions"),this.abortDataQueueController.abort(0),this.abortDataQueueController=new AbortController,this.ongoingResetPromise=this.resetData().finally(()=>{this.ongoingResetPromise=null})),this.ongoingResetPromise&&(this.ctx.log("debug","Waiting for ongoing reset to complete"),await this.ongoingResetPromise,this.ctx.log("debug","Ongoing reset complete")),await this.processData(e)};this.resetData=async()=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not resetting local data");return}await this.meta.reset(),await this.queryableStorage.reset(),this.events.resetAll.invoke(this)};this.processData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not processing incoming data");return}let n=e?.baselines??[],r=e?.operations??[];this.ctx.log("debug","Processing incoming data",{operations:r.length,baselines:n.length,reset:!!e.reset});let o=Array.from(new Set(n.map(m=>$(m.oid)).concat(r.map(m=>$(m.oid))))),s=Rr(n),a=Fr(r);this.ctx.log("debug","Applying data to live entities");for(let m of o){let v=s[m],y=a[m]??[],C=mt(y),w=e.reset?this.events.replace:this.events.add,x=this.pendingEntityPromises.get(m);x?x.then(()=>{w.invoke(this,{oid:m,baselines:v,operations:C,isLocal:!1})}):(this.cache.has(m)&&this.ctx.log("debug","Cache has",m,", an event should follow."),w.invoke(this,{oid:m,baselines:v,operations:C,isLocal:!1}))}let p={abort:this.abortDataQueueController.signal};await this.meta.insertData(e,p);let l=await Promise.all(o.map(async m=>await this.hydrate(m,p)??{oid:m,getSnapshot(){return null}}));try{await this.queryableStorage.saveEntities(l,p)}catch(m){this.disposed?this.ctx.log("warn","Error saving entities to queryable storage - EntityStore is disposed",m):this.ctx.log("error","Error saving entities to queryable storage",m)}};this.hydrate=async(e,n)=>{if(!Pr(e))throw new Error("Cannot hydrate non-root entity");if(this.cache.has(e)){this.ctx.log("debug","Hydrating entity from cache",e);let o=this.cache.get(e);if(o){let s=o.deref();if(s)return s.deleted?null:s;this.ctx.log("debug","Removing GC'd entity from cache",e),this.cache.delete(e)}}let r=this.pendingEntityPromises.get(e);if(r)return this.ctx.log("debug","Waiting for entity hydration",e),r;{this.ctx.log("debug","Hydrating entity from storage",e);let o=this.constructEntity(e);if(!o)return null;let s=this.loadEntity(o,n);return s.finally(()=>{this.pendingEntityPromises.delete(e)}),this.pendingEntityPromises.set(e,s),s}};this.destroy=async()=>{this.dispose(),await this.batcher.flushAll()};this.create=async(e,n,{undoable:r=!0}={})=>{this.ctx.log("debug","Creating new entity",n);let{collection:o}=me(n);Ut(e);let s=tt(e,this.files.add);K(s,n);let a=this.constructEntity(n);if(!a)throw new Error(`Could not put new document: no schema exists for collection ${o}`);let p=this.meta.patchCreator.createInitialize(s,n);await this.batcher.commitOperations(p,{undoable:!!r,source:a});let l=mt(p);return this.events.add.invoke(this,{operations:l,isLocal:!0,oid:n}),this.cache.set(n,this.ctx.weakRef(a)),a};this.deleteAll=async(e,n)=>{this.ctx.log("info","Deleting documents",e),L(e.every(s=>s===$(s)),"Only root documents may be deleted via client methods");let r=await Promise.all(e.flatMap(async s=>(await this.hydrate(s))?.__getFamilyOids__()??[]));e.forEach(s=>{this.cache.delete(s),this.ctx.log("debug","Deleted document from cache",s)});let o=this.meta.patchCreator.createDeleteAll(r.flat());await this.batcher.commitOperations(o,{undoable:n?.undoable===void 0?!0:n.undoable})};this.delete=async(e,n)=>this.deleteAll([e],n);this.getCollectionSchema=e=>{let n=this.ctx.schema.collections[e];return n?{schema:{type:"object",nullable:!1,properties:n.fields},readonlyKeys:[n.primaryKey]}:(this.ctx.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]})};this.constructEntity=e=>{let{collection:n}=me(e),{schema:r,readonlyKeys:o}=this.getCollectionSchema(n);if(!r)return null;if(this.disposed)throw new Error("Cannot hydrate entity after store has been disposed");let s=new mn({ctx:this.ctx,onPendingOperations:this.onPendingOperations,rootOid:e});return new ue({ctx:this.ctx,oid:e,schema:r,readonlyKeys:o,files:this.files,metadataFamily:s,patchCreator:this.meta.patchCreator,events:this.events})};this.onPendingOperations=e=>{this.batcher.addOperations(e)};this.loadEntity=async(e,n)=>{let{operations:r,baselines:o}=await this.meta.getDocumentData(e.oid,n);return!o.length&&!Object.keys(r).length?(this.ctx.log("debug","No data found for entity",e.oid),null):(this.ctx.log("debug","Loaded entity from storage",e.oid),this.events.replace.invoke(this,{oid:e.oid,baselines:o,operations:r,isLocal:!1}),this.cache.set(e.oid,this.ctx.weakRef(e)),this.entityFinalizationRegistry.register(e,e.oid),e)};this.ctx=e,this.meta=n,this.files=r,this.queryableStorage=new yn({ctx:e}),this.batcher=new gn({ctx:e,meta:n,entities:this})}get batch(){return this.batcher.batch}get flushAllBatches(){return this.batcher.flushAll}};var Ki=Symbol("handleMessage"),ba,Dt=class extends U{constructor({initialPresence:e,updateBatchTimeout:n=200,defaultProfile:r,replicaStore:o}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,n)=>e.id===n.replicaId||this._selfReplicaIds.has(n.replicaId)||this._self.id===n.id;this[ba]=async(e,n)=>{let r=!1,o=new Set(this.peerIds);if(n.type==="presence-changed")this.isSelf(e,n.userInfo)?(this._self=n.userInfo,this._selfReplicaIds.add(n.userInfo.replicaId),this.emit("selfChanged",n.userInfo)):(o.add(n.userInfo.id),this._peers[n.userInfo.id]=n.userInfo,r=!0,this.emit("peerChanged",n.userInfo.id,n.userInfo));else if(n.type==="sync-resp"){this._peers={},o.clear();for(let[s,a]of Object.entries(n.peerPresence))this.isSelf(e,a)?(this._self=a,this._selfReplicaIds.add(a.replicaId),this.emit("selfChanged",a)):(r=!0,o.add(s),this._peers[s]=a,this.emit("peerChanged",s,a))}else if(n.type==="presence-offline"){o.delete(n.userId),this._selfReplicaIds.delete(n.replicaId);let s=this._peers[n.userId];delete this._peers[n.userId],r=!0,this.emit("peerLeft",n.userId,s)}r&&(this._peerIds=Array.from(o),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let n=e.reduce((r,o)=>({...r,...o}),this.self.presence);this.emit("update",n)};this.self.presence=e,this.self.profile=r,this.self.id="",this.self.replicaId="",o.get().then(s=>{this.self.replicaId=s.id}),this._updateBatcher=new Xe(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{ba=Ki}get self(){return this._self}get peers(){return this._peers}get peerIds(){return this._peerIds}get everyone(){let e={...this._peers};return e[this.self.id]=this.self,e}get selfReplicaIds(){return this._selfReplicaIds}};var Cn=class{constructor({endpointProvider:t,log:e}){this.uploadFile=async t=>{let e=t.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:n,token:r}=await this.endpointProvider.getEndpoints(),o=new window.FormData;o.append("file",e);try{let s=await fetch(n+`/${t.id}`,{method:"POST",body:o,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return s.ok?(this.log("info","File upload successful"),{success:!0,retry:!1}):(this.log("error","File upload failed",s.status,await s.text()),{success:!1,retry:s.status>=500})}catch(s){return this.log("error","File upload failed",s),{success:!1,retry:!0}}};this.getFile=async t=>{let{files:e,token:n}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${t}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});return r.ok?{success:!0,data:await r.json()}:(this.log("error","File information fetch failed",r.status,await r.text()),{success:!1,retry:r.status>=500||r.status===404})}catch(r){return this.log("error","File information fetch failed",r),{success:!1,error:r,retry:!0}}};this.endpointProvider=t,this.log=e}};var it=class extends U{constructor({interval:e=15*1e3,deadlineLength:n=3*1e3,restartOnTabFocus:r=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=n,typeof window<"u"&&r&&(window.addEventListener("pageshow",()=>this.start(!0)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.start(!0)}))}get interval(){return this._interval}};var Pn=class extends U{constructor({endpointProvider:e,meta:n,presence:r,interval:o=15*1e3,log:s=()=>{},fetch:a=window.fetch.bind(window)}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:n,token:r}=await this.endpointProvider.getEndpoints(),o=await this.fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(o.ok){this.heartbeat.keepAlive();let s=await o.json();for(let a of s.messages)this.handleServerMessage(a);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else{this.log("Sync request failed",o.status,await o.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1));let s=await o.json();Vr(s)&&s.code===4012&&(this.endpointProvider.clearCache(),this.heartbeat.keepAlive()),o.status>=500&&this.heartbeat.keepAlive()}}catch(n){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(n),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.destroy=()=>{this.dispose(),this.stop()};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.log=s,this.meta=n,this.presence=r,this.endpointProvider=e,this.fetch=a,this.heartbeat=new it({interval:o}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}ignoreIncoming(){this.stop()}get isConnected(){return this._isConnected}get status(){return this._status}};function $i(i){this.message=i}$i.prototype=new Error,$i.prototype.name="InvalidCharacterError";var Mo=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var t=String(i).replace(/=+$/,"");if(t.length%4==1)throw new $i("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,r=0,o=0,s="";n=t.charAt(o++);~n&&(e=r%4?64*e+n:n,r++%4)?s+=String.fromCharCode(255&e>>(-2*r&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return s};function wa(i){var t=i.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(Mo(e).replace(/(.)/g,function(n,r){var o=r.charCodeAt(0).toString(16).toUpperCase();return o.length<2&&(o="0"+o),"%"+o}))}(t)}catch{return Mo(t)}}function An(i){this.message=i}function va(i,t){if(typeof i!="string")throw new An("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(wa(i.split(".")[e]))}catch(n){throw new An("Invalid token specified: "+n.message)}}An.prototype=new Error,An.prototype.name="InvalidTokenError";var Bo=va;var Fn=class{constructor(t){this.config=t;this.cached=null;this.type=0;this.getEndpoints=async()=>{if(this.cached)return this.cached;let t;this.config.fetchAuth?t=await this.config.fetchAuth():t=await(this.config.fetch||fetch.bind(window))(this.config.authEndpoint,{credentials:"include"}).then(p=>{if(p.ok)return p.json();throw new Error(`Auth endpoint returned non-200 response: ${p.status}`)}),L(t.accessToken,"No access token provided from auth endpoint");let e=Bo(t.accessToken);L(e.url,"No sync endpoint provided from auth endpoint"),L(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let n=new URL(e.url);n.protocol=n.protocol.replace("ws","http");let r=n.toString();n.protocol=n.protocol.replace("http","ws");let o=n.toString(),s=e.file;if(!s){let a=new URL(r);a.pathname=a.pathname+"/files",s=a.toString()}return this.cached={http:r,websocket:o,files:s,token:t.accessToken},this.cached};this.clearCache=()=>{this.cached=null};if(!t.authEndpoint&&!t.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var Rn=class extends U{constructor(e){super();this.timer=null;this.isScheduled=!1;this.next=()=>{this.isScheduled||(this.isScheduled=!0,this.timer=setTimeout(()=>{this.emit("trigger"),this.isScheduled=!1,this.backoff.next()},this.backoff.current))};this.reset=()=>{this.backoff.reset(),this.timer&&(clearTimeout(this.timer),this.timer=null)};this.backoff=e}},Tn=class{constructor(t,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=t,this.factor=e}};var kn=class extends U{constructor({endpointProvider:e,meta:n,presence:r,log:o}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this.incomingQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this._ignoreIncoming=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new it;this.reconnectScheduler=new Rn(new Tn(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),!this.disposed&&(e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e))};this.onMessage=async e=>{if(this._ignoreIncoming){this.log("Ignoring incoming message (ignore incoming flag set)",e.data);return}let n=JSON.parse(e.data);switch(n.type){case"sync-resp":if(n.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(n.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length)if(n.overwriteLocalData)this.log("warn","Overwriting local data - dropping outgoing message queue"),this.syncQueue=[];else{for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}if(this.emit("message",n),this.incomingQueue.length){for(let r of this.incomingQueue)this.emit("message",r);this.incomingQueue=[]}break;case"need-since":case"presence-changed":case"presence-offline":this.emit("message",n);break;case"op-re":if(!this.synced){this.log("Enqueueing op-re message because sync hasn't finished yet",n),this.incomingQueue.push(n);break}this.emit("message",n);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",n);break;default:this.synced&&this.emit("message",n);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.destroy=()=>{this.dispose(),this.stop()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.close(),this.socket=null,this._status="paused"};this.log=o||this.log,this.endpointProvider=e,this.meta=n,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}ignoreIncoming(){this.incomingQueue=[],this._ignoreIncoming=!0}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var Mn=class extends U{constructor({meta:e}){super();this.mode="pull";this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1});this.presence=new Dt({initialPresence:null,defaultProfile:null,replicaStore:e.localReplica})}send(){}start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},rt=class extends U{constructor({authEndpoint:e,fetchAuth:n,fetch:r,initialPresence:o,automaticTransportSelection:s=!0,autoStart:a,initialTransport:p,pullInterval:l,presenceUpdateBatchTimeout:m,defaultProfile:v,useBroadcastChannel:y},{meta:C,log:w,onData:x}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.onTokenExpired=()=>{this.endpointProvider.clearCache()};this.handleMessage=async(e,{source:n}={source:"network"})=>{if(e.type==="op-re"||e.type==="sync-resp")for(let r of e.operations)this.meta.time.update(r.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}n==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[Ki](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let n;e==="realtime"?n=this.webSocketSync:n=this.pushPullSync,n!==this.activeSync&&(this.log("debug","switching to",e,"mode"),this.activeSync.status==="active"&&n.start(),this.activeSync.stop(),this.activeSync=n)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=e=>{if(this.activeSync.status==="active")return this.activeSync.send(e)};this.uploadFile=async e=>(this.log("info","Uploading file",{name:e.name,type:e.type,id:e.id}),this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1});this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.destroy=()=>{this.dispose(),this.webSocketSync.destroy(),this.pushPullSync.destroy()};this.reconnect=()=>this.activeSync.reconnect();if(this.meta=C,this.onData=x,this.log=w||(()=>{}),this.presence=new Dt({initialPresence:o,defaultProfile:v,updateBatchTimeout:m,replicaStore:C.localReplica}),this.endpointProvider=new Fn({authEndpoint:e,fetchAuth:n,fetch:r}),this.webSocketSync=new kn({endpointProvider:this.endpointProvider,meta:C,presence:this.presence,log:this.log}),this.pushPullSync=new Pn({endpointProvider:this.endpointProvider,meta:C,presence:this.presence,log:this.log,interval:l,fetch:r}),this.fileSync=new Cn({endpointProvider:this.endpointProvider,log:this.log}),y&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),p==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),s&&this.canDoRealtime){let I=()=>{S&&clearTimeout(S);let F=Object.keys(this.presence.peers).length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;F&&this.mode==="pull"?this.setMode("realtime"):!F&&this.mode==="realtime"&&(S=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},S;this.presence.subscribe("peersChanged",I),s!=="peers-only"&&this.presence.subscribe("selfChanged",I)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}ignoreIncoming(){this.activeSync.ignoreIncoming()}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};function xa(i){return i!==null}function zi(i){return Array.isArray(i)?i.map(zi).filter(xa):i instanceof ue&&i.deleted?null:i}function ke(i,t){return!i&&!t||i&&t&&Fe(i)===Fe(t)}var qi=Symbol("ON_ALL_UNSUBSCRIBED"),fe=Symbol("UPDATE"),Oa,ge=class extends Ie{constructor({initial:e,context:n,collection:r,key:o,shouldUpdate:s}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{if(this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=zi(e),Array.isArray(this._value)&&this._value.some(n=>n.getSnapshot()===null))debugger;this._status="ready",this._events.emit("change",this._value)};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(n=>{n instanceof ue&&(this._internalUnsubscribes.push(n.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(n.subscribe("restore",this.refreshValue)))}):e instanceof ue&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>(this.context.log("debug","Executing query",this.key),this._status==="initial"?this._status="initializing":this._status==="ready"&&(this._status="revalidating"),this._executionPromise=this.run().then(()=>this._value).catch(e=>{if(e instanceof Error){if(e.name==="InvalidStateError"||e.name==="InvalidAccessError")return this._value;throw e}else throw new Error("Unknown error executing query")}),this._executionPromise);this[Oa]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this._events=new U(p=>{p==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=n,this.key=o,this.collection=r;let a=s||(p=>p.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",p=>{a(p)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Oa=qi}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}subscribe(e,n){if(n===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&n!==void 0)return this.resolved,this._events.subscribe("change",n);if(e==="statusChange"&&typeof n=="function")return this._events.subscribe(e,n);throw new Error("Invalid invocation of Query.subscribe")}};var Bn=class extends ge{constructor({id:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=Z(r.collection,e),this.hydrate=n}};var Ia,jn=class extends ge{constructor({index:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await an({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Ia]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Ia=fe}};var Da,Ln=class extends ge{constructor({index:e,hydrate:n,pageSize:r,page:o,...s}){super({initial:[],...s});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await wt({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.nextPage=async()=>{this.hasNextPage&&(this._page++,await this.run())};this.previousPage=async()=>{this._page!==0&&(this._page--,await this.run())};this.setPage=async e=>{this._page=e,await this.run()};this[Da]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=r,this._page=o}static{Da=fe}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var _a,Nn=class extends ge{constructor({hydrate:e,pageSize:n,index:r,...o}){super({initial:[],...o});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await wt({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:n}=await wt({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=n,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[_a]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=n}static{_a=fe}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Ea,Un=class extends ge{constructor({index:e,hydrate:n,...r}){super({initial:[],...r});this.run=async()=>{let e=await cn({collection:this.collection,index:this.index,context:this.context});this.context.log("debug",`FindAllQuery: ${e.length} oids found: ${e}`),this.setValue(await Promise.all(e.map(this.hydrate)))};this[Ea]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Ea=fe}};var Vn=class{constructor({collection:t,cache:e,entities:n,context:r,documentManager:o}){this.serializeIndex=t=>t?Fe(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new Bn({id:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:t,key:e}={})=>{let n=e||`findOne:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new jn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[fe](t)})};this.findAll=({index:t,key:e}={})=>{let n=e||`findAll:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new Un({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[fe](t)})};this.findPage=({index:t,pageSize:e,page:n,key:r})=>{let o=r||`findPage:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(o,()=>new Ln({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:o,pageSize:e,page:n}),s=>{s[fe](t)})};this.findAllInfinite=({index:t,pageSize:e,key:n})=>{let r=n||`findAllInfinite:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(r,()=>new Nn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),o=>{o[fe](t)})};this.cache=e,this.collection=t,this.hydrate=n.hydrate,this.context=r,this.documentManager=o,this.put=this.documentManager.create.bind(this.documentManager,this.collection),this.delete=this.documentManager.delete.bind(this.documentManager,this.collection),this.deleteAll=this.documentManager.deleteAllFromCollection.bind(this.documentManager,this.collection)}};var Kn=class extends Ie{constructor({evictionTime:e=5*1e3,context:n}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this.dropAll=()=>{this._cache.forEach(e=>e.dispose()),this._cache.clear()};this._evictionTime=e,this.context=n}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[qi](this.onQueryUnsubscribed),e}getOrSet(e,n,r){let o=this.get(e);return o?(r?.(o),o):this.set(n())}};var He=class extends U{constructor(e,n,r){super();this.config=e;this.context=n;this._closed=!1;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),n={};for(let l of e)try{n[l]=await yt(this.documentDb,l)}catch(m){this.context.log?.("error",m)}let r=await this.meta.stats(),o=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,s=Object.values(n).reduce((l,{size:m})=>l+m,0),a=r.baselinesSize.size+r.operationsSize.size,p=a/s;return{collections:n,meta:r,storage:o,totalMetaSize:a,totalCollectionsSize:s,metaToDataRatio:p,quotaUsage:o?.usage&&o?.quota?o.usage/o.quota:void 0}};this.close=async()=>{this._closed=!0,this.sync.ignoreIncoming(),await this._entities.flushAllBatches(),this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await Ke(this.documentDb),await Ke(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Gt(this.namespace,indexedDB)};this.export=async({downloadRemoteFiles:e}={downloadRemoteFiles:!0})=>{this.context.log("info","Exporting data...");let n=await this.meta.export(),r=await this._fileManager.exportAll(e),o=[],s=[];for(let a of r){let p=a.file;if(delete a.file,o.push(a),p){let l=new File([p],this.getFileExportName(a.name,a.id),{type:a.type});s.push(l)}else this.context.log("warn",`File ${a.id} was could not be loaded locally or from the server. It will be missing in the export.`)}return{data:n,fileData:o,files:s}};this.getFileExportName=(e,n)=>`${n}___${e}`;this.parseFileExportname=e=>{let[n,r]=e.split("___");return{id:n,originalFileName:r}};this.import=async({data:e,fileData:n,files:r})=>{this.context.log("info","Importing data..."),await Ke(this.context.documentDb),await this.meta.resetFrom(e);let o=new Map(r.map(m=>{let{id:v}=this.parseFileExportname(m.name);return[v,m]})),s=n.map(m=>{let v=o.get(m.id);return{...m,file:v}});await this._fileManager.importAll(s);let a=e.schema.version,p=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((m,v)=>{p.onsuccess=m,p.onerror=v});let l=this.context.schema;if(l.version!==a)throw new Error("Only exports from the current schema version can be imported");this.context.documentDb=await vt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:a}),this.context.internalEvents.emit("documentDbChanged",this.documentDb),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:e.operations,baselines:e.baselines,reset:!0}),await Ke(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=l,this.context.documentDb=await vt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:l.version}),this.context.internalEvents.emit("documentDbChanged",this.documentDb)};this.__dangerous__hardReset=async()=>{let e=await this.export();await this.import(e)};this.meta=r.meta,this.collectionNames=Object.keys(n.schema.collections),this._sync=this.config.syncConfig&&!n.schema.wip?new rt(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new Mn({meta:this.meta}),n.schema.wip&&this.config.syncConfig&&n.log("warn","\u26A0\uFE0F\u26A0\uFE0F Sync is disabled for WIP schemas. Commit your schema changes to start syncing again. \u26A0\uFE0F\u26A0\uFE0F"),this._fileManager=new pn({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new En({ctx:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new Kn({context:n}),this._documentManager=new un(this.meta,this.schema,this._entities);let o=Dr(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",o),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[s,a]of Object.entries(n.schema.collections)){let p=s;this[p]=new Vn({collection:p,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get batch(){return this.entities.batch}};var _t=class{constructor(t){this.value=t}deref(){return this.value}};var jo=Symbol("metadataVersion");var $n=class{constructor(t){this.init=t;this._initializing=!1;this.initialize=async t=>{if(typeof window>"u"&&!t.indexedDb)throw new Error("A verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e;return t.schema.wip?e=await this.initializeWIPDatabases(t):(e=await this.initializeDatabases(t),this.cleanupWIPDatabases(t)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw e instanceof Error?(this.rejectReady(e),e):new Error("Unknown error initializing storage")}finally{this._initializing=!1}};this.initializeDatabases=async t=>{let e=t[jo],{db:n}=await on({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,metadataVersion:e}),r={namespace:this._namespace,metaDb:n,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new St,entityEvents:new U,globalEvents:new U,internalEvents:new U,weakRef:m=>t.EXPERIMENTAL_weakRefs?new WeakRef(m):new _t(m),migrations:t.migrations},o=new bt({context:r,disableRebasing:t.disableRebasing});await o.updateSchema(t.schema,t.overrideSchemaConflict);let s=Object.assign(r,{getNow:()=>o.now}),a=await vt({context:s,version:t.schema.version,meta:o,migrations:t.migrations,indexedDB:t.indexedDb}),p=Object.assign(s,{documentDb:a});return new He({syncConfig:t.sync,migrations:t.migrations,files:t.files},p,{meta:o})};this.initializeWIPDatabases=async t=>{let e=Fe(t.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let n=`@@wip_${t.namespace}_${e}`,{db:r}=await qr({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,wipNamespace:n}),o={namespace:this._namespace,metaDb:r,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new St,entityEvents:new U,globalEvents:new U,internalEvents:new U,weakRef:v=>t.EXPERIMENTAL_weakRefs?new WeakRef(v):new _t(v),migrations:t.migrations},s=new bt({context:o,disableRebasing:t.disableRebasing}),a=Object.assign(o,{getNow:()=>s.now});await s.updateSchema(t.schema,t.overrideSchemaConflict);let p=await Jr({context:a,version:t.schema.version,meta:s,migrations:t.migrations,indexedDB:t.indexedDb,wipNamespace:n}),l=Object.assign(a,{documentDb:p});return new He({syncConfig:t.sync,migrations:t.migrations,files:t.files},l,{meta:s})};this.cleanupWIPDatabases=async t=>{let r=(await $r(t.indexedDb)).filter(o=>o.name?.startsWith("@@wip_")).map(o=>o.name).filter(o=>!o.startsWith(`@@wip_${t.namespace}_${Fe(t.schema)}`));for(let o of r)await Kr(o,t.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await Gt(this.namespace)};this._readyPromise=new Promise((e,n)=>{this.resolveReady=e,this.rejectReady=n}),this._namespace=t.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};window.Verdant=Hi;
|
|
13
|
+
- New indexes: ${Object.keys(o.addedIndexes).map(u=>o.addedIndexes[u].map(m=>`${u}.${m.name}`)).flatMap(u=>u).join(", ")}
|
|
14
|
+
- Removed indexes: ${Object.keys(o.removedIndexes).map(u=>o.removedIndexes[u].map(m=>`${u}.${m.name}`)).flatMap(u=>u).join(", ")}
|
|
15
|
+
`)}})}function Yr({migration:n,meta:i,getMigrationNow:e,newOids:t}){return n.allCollections.reduce((r,o)=>(r[o]={put:async s=>{Ae(n.newSchema.collections[o],s);let a=s[n.newSchema.collections[o].primaryKey],h=Z(o,a);return t.push(h),await i.insertLocalOperations(Fe(s,h,e)),s},delete:async s=>{let a=Z(o,s),h=await i.getAllDocumentRelatedOids(a);return i.insertLocalOperations(h.map(u=>({oid:u,timestamp:e(),data:{op:"delete"}})))}},r),{})}function Hs({migration:n,context:i,meta:e}){return n.oldCollections.reduce((t,r)=>(t[r]={get:async o=>{let s=Z(r,o);return await e.getDocumentSnapshot(s,{to:e.time.now(n.oldSchema.version)})},findOne:async o=>{let s=await ln({collection:r,index:o,context:i});return s?await e.getDocumentSnapshot(s,{to:e.time.now(n.oldSchema.version)}):null},findAll:async o=>{let s=await dn({collection:r,index:o,context:i});return await Promise.all(s.map(h=>e.getDocumentSnapshot(h,{to:e.time.now(n.oldSchema.version)})))}},t),{})}function Ws({meta:n,migration:i,context:e}){function t(){return n.time.zero(i.version)}let r=new Array,o=Hs({migration:i,context:e,meta:n}),s=Yr({migration:i,getMigrationNow:t,newOids:r,meta:n}),a=async m=>{let v=await n.getAllCollectionRelatedOids(m);return n.insertLocalOperations(v.map(y=>({oid:y,timestamp:t(),data:{op:"delete"}})))},h=new Array;return{log:e.log,newOids:r,deleteCollection:a,migrate:async(m,v)=>{let y=await o[m].findAll();await Promise.all(y.filter(Boolean).map(async C=>{let w=ne(C);L(!!w,`Document is missing an OID: ${JSON.stringify(C)}`);let S=ae(C),I=await v(C);if(I){ht(S),ht(I),Xe(I);let x=mt(S,I,t,void 0,[],{mergeUnknownObjects:!0});x.length>0&&await n.insertLocalOperations(x)}}))},queries:o,mutations:s,awaitables:h}}function Qs({meta:n,migration:i,context:e}){function t(){return n.time.zero(i.version)}let r=new Array,o=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),s=Yr({migration:i,getMigrationNow:t,newOids:r,meta:n});return{log:e.log,newOids:r,deleteCollection:()=>{throw new Error("Calling deleteCollection() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:o,mutations:s,awaitables:[]}}async function Js(n){return new Promise((i,e)=>{let t=n.getAllKeys();t.onsuccess=r=>{i(t.result)},t.onerror=r=>{e(t.error)}})}async function Gs(n,i){let e=n.delete(i);return new Promise((t,r)=>{e.onsuccess=o=>{t()},e.onerror=o=>{r(e.error)}})}async function Ys(n,i){let e=n.put(i);return new Promise((t,r)=>{e.onsuccess=o=>{t()},e.onerror=o=>{r(e.error)}})}async function Xs({meta:n,currentVersion:i,newVersion:e}){let t=[];return await n.operations.iterateOverAllOperations(r=>t.push(r),{from:n.time.zero(i+1)}),Array.from(new Set(t.map(r=>z(r.oid))))}var Ot=class extends V{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();if(e){let t=await e();return t&&this._undone.push(t),this.emit("change"),!0}return!1};this.redo=async()=>{let e=this._undone.pop();if(e){let t=await e();return t&&this._undoable.push(t),this.emit("change"),!0}return!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var hn=class{constructor(i,e,t){this.meta=i;this.schema=e;this.entities=t;this.getOid=(i,e)=>{let t=this.schema.collections[i].primaryKey,r=e[t];return L(r,`Document must have a primary key: ${t.toString()} (got: ${JSON.stringify(e)})`),Z(i,r)};this.addDefaults=(i,e)=>{let t=this.schema.collections[i];return Ae(t,e)};this.create=(i,e,t={})=>{let r=this.addDefaults(i,e),o=this.getOid(i,r);return this.entities.create(r,o,t)};this.delete=async(i,e,t={})=>{let r=Z(i,e);return this.entities.delete(r,t)};this.deleteAll=async(i,e={})=>this.entities.deleteAll(i.map(([t,r])=>Z(t,r)),e);this.deleteAllFromCollection=async(i,e,t={})=>this.entities.deleteAll(e.map(r=>Z(i,r)),t)}};var tt=Symbol("entity-file-update"),It=Symbol("entity-file-mark-failed"),Zs,ea,de=class extends V{constructor(e,{downloadRemote:t=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._downloadRemote=!1;this[Zs]=e=>{this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[ea]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.destroy=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this.dispose()};this._downloadRemote=t}static{Zs=tt,ea=It}get downloadRemote(){return this._downloadRemote}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}getSnapshot(){return{id:this.id,url:this.loading||this.failed?void 0:this.url}}};var Xr=Je(ct(),1);function ta(n){return{id:(0,Xr.default)(),file:n,url:void 0,remote:!1,name:n.name,type:n.type}}function Ci(n){return n instanceof File||typeof Blob<"u"&&n instanceof Blob}function nt(n,i){if(typeof window<"u"&&Ci(n)){let e=ta(n);return i(e),Lt(e.id)}if(Array.isArray(n)){for(let e=0;e<n.length;e++)n[e]=nt(n[e],i);return n}if(typeof n=="object"){for(let e in n)n[e]=nt(n[e],i);return n}return n}function Zr(n){return new Promise((i,e)=>{let t=new FileReader;t.onload=()=>{i(t.result)},t.onerror=e,t.readAsArrayBuffer(n)})}var pn=class extends se{constructor(){super(...arguments);this.addFile=async(e,{transaction:t,downloadRemote:r=!1}={})=>{let o=e.file?await Zr(e.file):void 0;if(!o&&r&&e.url)try{o=await fetch(e.url,{method:"GET",credentials:"include"}).then(s=>s.arrayBuffer())}catch(s){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",s)}return this.run("files",s=>s.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:o}),{mode:"readwrite",transaction:t})};this.hydrateFileData=e=>{e.remote=e.remote==="true";let t=e.buffer;return delete e.buffer,e.file=t?na(t,e.type):void 0,e};this.markUploaded=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(!r)throw new Error("File is not in local database");return this.run("files",o=>o.put({...r,remote:"true"}),{mode:"readwrite",transaction:t})};this.getFileRaw=async(e,{transaction:t}={})=>{let r=await this.run("files",o=>o.get(e),{mode:"readonly",transaction:t});if(r)return r};this.getFile=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(!r)throw new Error("File is not in local database");return this.run("files",o=>o.put({...r,deletedAt:Date.now()}),{mode:"readwrite",transaction:t})};this.listUnsynced=async()=>(await this.run("files",t=>t.index("remote").getAll("false"),{mode:"readonly"})).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,t)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,o)=>{e(this.hydrateFileData(r),o)},{mode:"readwrite",transaction:t});this.getAll=async()=>{let[e]=await Yt(this.db,["files"]);return e.map(this.hydrateFileData)}}deleteFile(e,{transaction:t}={}){return this.run("files",r=>r.delete(e),{mode:"readwrite",transaction:t})}};function na(n,i){return new Blob([n],{type:i})}function ia(n){return n.deletedAt!==null&&n.deletedAt<Date.now()-1e3*60*24*3}var mn=class{constructor({db:i,sync:e,context:t,meta:r,config:o={}}){this.files=new Map;this.add=async i=>{let e=i;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[tt](e);else{let t=new de(e.id);t[tt](e),this.files.set(e.id,t)}await this.storage.addFile(e),e.file&&await this.uploadFile(e,1)};this.uploadFile=async(i,e=0)=>{let t=await this.sync.uploadFile(i);t.success?await this.storage.markUploaded(i.id):t.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,i,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=(i,e)=>{if(this.files.has(i))return this.files.get(i);let t=new de(i,e);return this.files.set(i,t),this.load(t),t};this.load=async(i,e=0)=>{if(e>5){this.context.log("error","Failed to load file after 5 retries"),i[It]();return}let t=await this.storage.getFile(i.id);if(t)i[tt](t);else try{let r=await this.sync.getFile(i.id);r.success?(i[tt](r.data),await this.storage.addFile(r.data,{downloadRemote:i.downloadRemote})):(this.context.log("error","Failed to load file",r),i[It](),r.retry&&setTimeout(this.load,1e3,i,e+1))}catch(r){this.context.log("error","Failed to load file",r),i[It](),setTimeout(this.load,1e3,i,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.exportAll=async(i=!1)=>{let e=await this.storage.getAll();if(i){for(let t of e)if(!t.file&&t.url)try{let r=await fetch(t.url,{method:"GET",credentials:"include"}).then(o=>o.blob());t.file=r}catch(r){this.context.log("error","Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",r)}}return e};this.importAll=async i=>{await Promise.all(i.map(e=>this.add(e)))};this.onOnlineChange=async i=>{if(i){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let i=0,e=0;await this.storage.iterateOverPendingDelete((t,r)=>{this.config.canCleanupDeletedFile(t)?(i++,r.delete(t.id)):e++}),this.context.log("info",`Cleaned up ${i} files, skipped ${e} files`)};this.handleFileRefsDeleted=async i=>{let e=this.storage.createTransaction(["files"],{mode:"readwrite"});await Promise.all(i.map(async t=>{try{await this.storage.markPendingDelete(t.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${i.length} files as pending delete`)};this.close=()=>{this.storage.dispose()};this.storage=new pn(i),this.sync=e,this.context=t,this.meta=r,this.config={canCleanupDeletedFile:ia,...o},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var gn=class{constructor({initial:i}={}){this.cache=new Map;this.get=i=>{if(this.cache.has(i.oid))return this.cache.get(i.oid);let e=new ue(i);return this.cache.set(i.oid,e),e};this.has=i=>this.cache.has(i);this.getFile=(i,e)=>{if(this.cache.has(i))return this.cache.get(i);let t=new de(i,e);return this.cache.set(i,t),t};this.getCached=i=>this.cache.get(i);if(i)for(let e of i)this.cache.set(e.oid,e)}};var ue=class n extends V{constructor({oid:e,schema:t,entityFamily:r,parent:o,ctx:s,metadataFamily:a,readonlyKeys:h,files:u,patchCreator:m,events:v}){super();this.fieldPath=[];this._viewData=void 0;this.validationError=void 0;this.cachedDeepUpdatedAt=null;this.wasDeletedLastChange=!1;this.cachedView=void 0;this.onAdd=(e,t)=>{t.oid===this.oid&&this.addConfirmedData(t)};this.onReplace=(e,t)=>{t.oid===this.oid&&this.replaceAllData(t)};this.onResetAll=()=>{this.resetAllData()};this.childIsNull=e=>{if(e instanceof n){let t=e.view;return t==null}return e==null};this.validate=Nr(()=>(this.validationError=ke({field:this.schema,value:this.rawView,fieldPath:this.fieldPath,depth:1})??void 0,this.validationError),()=>[this.viewData]);this.viewWithMappedChildren=e=>{let t=this.view;if(!t)return null;if(Array.isArray(t)){let r=t.map(o=>o instanceof n||o instanceof de?e(o):o);return $(r,this.oid),r}else{let r=Object.entries(t).reduce((o,[s,a])=>(a instanceof n||a instanceof de?o[s]=e(a):o[s]=a,o),{});return $(r,this.oid),r}};this.getSnapshot=()=>this.viewWithMappedChildren(e=>e.getSnapshot());this.addPendingOperations=e=>{this.ctx.log("debug","Entity: adding pending operations",this.oid);let t=this.metadataFamily.addPendingData(e);for(let r of t)this.change(r)};this.addConfirmedData=e=>{this.ctx.log("debug","Entity: adding confirmed data",this.oid);let t=this.metadataFamily.addConfirmedData(e);for(let r of t)this.change(r)};this.replaceAllData=e=>{this.ctx.log("debug","Entity: replacing all data",this.oid);let t=this.metadataFamily.replaceAllData(e);for(let r of t)this.change(r)};this.resetAllData=()=>{this.ctx.log("debug","Entity: resetting all data",this.oid),this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this._viewData=void 0;let e=this.metadataFamily.replaceAllData({});for(let t of e)this.change(t)};this.change=e=>{if(e.oid===this.oid)this._viewData=void 0,this.cachedView=void 0,this.deepChange(this,e),this.ctx.log("Emitting change event",this.oid),this.emit("change",{isLocal:e.isLocal}),this.parent||(this.deleted&&!this.wasDeletedLastChange?(this.ctx.log("debug","Entity deleted",this.oid),this.emit("delete",{isLocal:e.isLocal}),this.wasDeletedLastChange=!0):!this.deleted&&this.wasDeletedLastChange&&(this.ctx.log("debug","Entity restored",this.oid),this.emit("restore",{isLocal:e.isLocal}),this.wasDeletedLastChange=!1));else{let t=this.entityFamily.getCached(e.oid);t&&t instanceof n&&t.change(e)}};this.deepChange=(e,t)=>{this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this.ctx.log("debug","Deep change detected at",this.oid,"reset cached view"),this.ctx.log("debug","Emitting deep change event",this.oid),this.emit("changeDeep",e,t),this.parent?.deepChange(e,t)};this.getChild=(e,t)=>{let r=Ve(this.schema,e);if(!r)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);return this.entityFamily.get({oid:t,schema:r,entityFamily:this.entityFamily,metadataFamily:this.metadataFamily,parent:this,ctx:this.ctx,files:this.files,fieldPath:[...this.fieldPath,e],patchCreator:this.patchCreator,events:this.events})};this.get=e=>{eo(e);let t=this.rawView;if(!t)throw new Error(`Cannot access data at key ${e} on deleted entity ${this.oid}`);let r=t[e],o=Ve(this.schema,e);if(!o)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if(Q(r))if(be(r)){if(o.type!=="file")throw new Error(`Expected file schema for key ${String(e)}, got ${o.type}`);let s=this.files.get(r.id,{downloadRemote:!!o.downloadRemote});return s.subscribe("change",()=>{this.deepChange(this,{isLocal:!1,oid:this.oid})}),s}else return this.getChild(e,r.id);else return ke({field:o,value:r,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0})?Ce(o)?gi(o):we(o)?null:void 0:r};this.processInputValue=(e,t)=>{if(this.readonlyKeys.includes(t))throw new Error(`Cannot set readonly key ${t.toString()}`);Ci(e)||(e=ae(e,!1));let r=Ve(this.schema,t);if(r){Ue(e,r);let o=ke({field:r,value:e,fieldPath:[...this.fieldPath,t]});if(o)throw new Error(o.message)}return nt(e,this.files.add)};this.getDeleteMode=e=>{if(this.readonlyKeys.includes(e))return!1;if(this.schema.type==="any"||this.schema.type==="map")return"delete";if(this.schema.type==="object"){let t=this.schema.properties[e];if(!t||t.type==="any")return"delete";if(t.type==="map")return!1;if(t.nullable)return"null"}return!1};this.getItemRefValue=e=>{if(e instanceof n)return pe(e.oid);if(e instanceof de)return Lt(e.id);if(typeof e=="object"){let t=he(e);if(!t||!this.entityFamily.has(t))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return pe(t)}else return e};this.set=(e,t)=>{eo(e),this.addPendingOperations(this.patchCreator.createSet(this.oid,e,this.processInputValue(t,e)))};this.getAll=()=>this.view;this.delete=e=>{if(this.isList)ra(e),this.addPendingOperations(this.patchCreator.createListDelete(this.oid,e));else{let t=this.getDeleteMode(e);if(!t)throw new Error(`Cannot delete key ${e.toString()} - the property is not marked as optional in the schema.`);t==="delete"?this.addPendingOperations(this.patchCreator.createRemove(this.oid,e)):this.addPendingOperations(this.patchCreator.createSet(this.oid,e,null))}};this.keys=()=>this.view?Object.keys(this.view):[];this.entries=()=>this.view?Object.entries(this.view):[];this.values=()=>this.view?Object.values(this.view):[];this.update=(e,{merge:t=!0,replaceSubObjects:r=!1}={})=>{if(!t&&this.schema.type!=="any"&&this.schema.type!=="map")throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');let o={};$(o,this.oid);for(let[s,a]of Object.entries(e)){if(this.readonlyKeys.includes(s))throw new Error(`Cannot set readonly key ${s.toString()}`);let h=Ve(this.schema,s);h&&Ue(a,h),o[s]=this.processInputValue(a,s)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),o,{mergeUnknownObjects:!r,defaultUndefined:t}))};this.push=e=>{this.addPendingOperations(this.patchCreator.createListPush(this.oid,this.processInputValue(e,this.view.length)))};this.insert=(e,t)=>{this.addPendingOperations(this.patchCreator.createListInsert(this.oid,e,this.processInputValue(t,e)))};this.move=(e,t)=>{this.addPendingOperations(this.patchCreator.createListMoveByIndex(this.oid,e,t))};this.moveItem=(e,t)=>{let r=this.getItemRefValue(e);if(Q(r))this.addPendingOperations(this.patchCreator.createListMoveByRef(this.oid,r,t));else{let o=this.view.indexOf(e);if(o===-1)throw new Error(`Cannot move item ${JSON.stringify(e)} which does not exist in this list`);this.move(o,t)}};this.add=e=>{this.addPendingOperations(this.patchCreator.createListAdd(this.oid,this.processInputValue(e,this.view.length)))};this.removeAll=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e)))};this.removeFirst=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"first"))};this.removeLast=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"last"))};this.map=e=>this.view.map(e);this.filter=e=>this.view.filter(e);this.has=e=>{if(!this.isList)throw new Error("has() is only available on list entities");let t=this.getItemRefValue(e);return Q(t)?this.view.some(r=>{if(Q(r))return Ye(r,t)}):this.view.includes(e)};this.forEach=e=>{this.view.forEach(e)};this.some=e=>this.view.some(e);this.every=e=>this.view.every(e);this.find=e=>this.view.find(e);this.includes=this.has;this.__getViewData__=(e,t)=>this.metadataFamily.get(e).computeView(t==="confirmed");this.__getFamilyOids__=()=>this.metadataFamily.getAllOids();L(!!e,"oid is required"),this.oid=e,this.readonlyKeys=h||[],this.ctx=s,this.files=u,this.schema=t,this.entityFamily=r||new gn({initial:[this]}),this.patchCreator=m,this.metadataFamily=a,this.events=v,this.parent=o,this.parent||(v.add.attach(this.onAdd),v.replace.attach(this.onReplace),v.resetAll.attach(this.onResetAll))}get metadata(){return this.metadataFamily.get(this.oid)}get viewData(){return this._viewData===void 0&&(this._viewData=this.metadata.computeView(),this.validate()),this._viewData}get rawView(){return this.viewData.view}get view(){if(this.cachedView!==void 0)return this.cachedView;if(this.viewData.deleted)return null;let e=this.rawView;if(!e&&!we(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!N(e))return Ce(this.schema)?gi(this.schema):null;if(this.cachedView=this.isList?[]:{},$(this.cachedView,this.oid),Array.isArray(e)){let r=Ve(this.schema,0);if(!r)this.ctx.log("error","No child field schema for list entity.",this.oid);else for(let o=0;o<e.length;o++){let s=this.get(o);this.childIsNull(s)&&!we(r)?this.ctx.log("error","Child missing in non-nullable field",this.oid,"index:",o):this.cachedView.push(s)}}else if(N(e)){let r=this.schema.type==="object"?Object.keys(this.schema.properties):Object.keys(e);for(let o of r){let s=Ve(this.schema,o);if(!s){this.ctx.log("error","No child field schema for object entity at key",o),this.schema.type==="map"?this.cachedView={}:this.cachedView=null;break}let a=this.get(o);if(this.childIsNull(a)&&!we(s)){if(this.ctx.log("error","Child entity is missing for non-nullable field",this.oid,"key:",o),this.schema.type!=="map"){this.cachedView=null;break}}else this.cachedView[o]=a}}return this.cachedView}get uid(){return this.oid}get deleted(){return this.viewData.deleted||this.view===null}get invalid(){return!!this.validate()}get isList(){return this.schema.type==="array"||Array.isArray(this.viewData.view)}get updatedAt(){return this.viewData.updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let e=this.updatedAt;return this.isList?this.forEach(t=>{if(t instanceof n){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}):this.values().forEach(t=>{if(t instanceof n){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}),this.cachedDeepUpdatedAt=e,e}get isOutdatedVersion(){return this.parent?this.parent.isOutdatedVersion:this.viewData.fromOlderVersion}get length(){return this.view.length}[Symbol.iterator](){let e=0,t=this.view?.length;return{next:()=>e<t?{value:this.get(e++),done:!1}:{value:void 0,done:!0}}}};function eo(n){if(typeof n=="symbol")throw new Error("Symbol keys aren't supported")}function ra(n){if(typeof n!="number")throw new Error("Only number keys are supported in list entities")}var Ai=class{constructor({oid:i,ctx:e,confirmedOperations:t,pendingOperations:r,baseline:o}){this.baseline=null;this.confirmedOperations=[];this.pendingOperations=[];this.computeView=(i=!1)=>{let e=ae(this.baseline?.snapshot??void 0),t=this.baseline?.timestamp??null,r=this.applyOperations(e,!e,this.confirmedOperations,t,t);r.futureSeen&&this.ctx.globalEvents.emit("futureSeen",r.futureSeen);let o=i?r:this.applyOperations(r.view,r.deleted,this.pendingOperations,r.latestTimestamp,null);o.view&&$(o.view,this.oid);let s=!!r.latestTimestamp&&ei(r.latestTimestamp,this.ctx.getNow())<0,a=!this.baseline&&!this.pendingOperations.length&&!this.confirmedOperations.length;a&&this.ctx.log("warn",`Tried to load Entity ${this.oid} with no data`);let h=o.latestTimestamp??r.latestTimestamp??t,u=h?ti(h):0;if(!o.view&&!o.deleted&&!a){this.ctx.log("warn",`Entity ${this.oid} has no view, no deleted flag, and not empty`);debugger}return{view:o.view??void 0,deleted:o.deleted,empty:a,fromOlderVersion:s,updatedAt:u}};this.addBaseline=i=>{if(!(this.baseline&&this.baseline.timestamp>=i.timestamp))for(this.baseline=i;this.confirmedOperations[0]?.timestamp<i.timestamp;)this.confirmedOperations.shift()};this.addConfirmedOperations=i=>{let e=0;for(let t of i){let r=this.confirmedOperations.findIndex(s=>s.timestamp>=t.timestamp);r!==-1?this.confirmedOperations[r].timestamp!==t.timestamp&&(this.confirmedOperations.splice(r,0,t),e++):(this.confirmedOperations.push(t),e++);let o=this.pendingOperations.length;this.pendingOperations=this.pendingOperations.filter(s=>t.timestamp!==s.timestamp),e-=o-this.pendingOperations.length}return e};this.addPendingOperation=i=>{this.pendingOperations.push(i)};this.applyOperations=(i,e,t,r,o)=>{let s,a=this.ctx.getNow();for(let h of t)if(!(o&&h.timestamp<=o)){if(ei(h.timestamp,a)>0){s=h.timestamp;continue}h.data.op==="delete"?e=!0:(i=Le(i,h.data),h.data.op==="initialize"&&(e=!1)),(!r||h.timestamp>r)&&(r=h.timestamp)}return{view:i,latestTimestamp:r??null,deleted:e,futureSeen:s}};L(i,"oid is required"),this.ctx=e,this.oid=i,t&&(this.confirmedOperations=t),r&&(this.pendingOperations=r),o&&(this.baseline=o)}},yn=class{constructor({ctx:i,onPendingOperations:e,rootOid:t}){this.entities=new Map;this.get=i=>(L(i,"oid is required"),this.entities.has(i)||this.entities.set(i,new Ai({oid:i,ctx:this.ctx})),this.entities.get(i));this.getAllOids=()=>Array.from(this.entities.keys());this.addConfirmedData=({baselines:i=[],operations:e={},isLocal:t=!1})=>{let r={};for(let o of i){if(!Ee(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o)}for(let[o,s]of Object.entries(e)){if(!Ee(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s)!==0&&(r[o]??={oid:o,isLocal:t})}return Object.values(r)};this.addPendingData=i=>{let e={};for(let t of i)this.get(t.oid).addPendingOperation(t),e[t.oid]??={oid:t.oid,isLocal:!0};return this.onPendingOperations(i),Object.values(e)};this.replaceAllData=({operations:i={},baselines:e=[]})=>{let t=Array.from(this.entities.keys());this.entities.clear();let r={};for(let o of t)r[o]={oid:o,isLocal:!1};for(let o of e){if(!Ee(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o),r[o.oid]??={oid:o.oid,isLocal:!1}}for(let[o,s]of Object.entries(i)){if(!Ee(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s),r[o]??={oid:o,isLocal:!1}}return Object.values(r)};this.ctx=i,this.rootOid=t,this.onPendingOperations=e}};var _t="@@default",bn=class{constructor({batchTimeout:i=200,meta:e,ctx:t,entities:r}){this.currentBatchKey=_t;this.flushOperations=async(i,e,t)=>{if(this.ctx.log("debug","Flushing",i.length,"operations from batch",e,"to storage / sync"),!!i.length){for(let r of i)r.timestamp=this.meta.now;await this.commitOperations(i,t)}};this.commitOperations=async(i,e)=>{if(i.length){if(e.undoable){let t=await this.createUndo({ops:i,source:e.source});t&&this.ctx.undoHistory.addUndo(t)}await this.entities.addData({operations:i,baselines:[],isLocal:!0})}};this.addOperations=i=>{i.length&&(this.batcher.add({key:this.currentBatchKey,items:i}),this.ctx.log("debug","added",i.length,"ops to batch",this.currentBatchKey,", size = ",this.batcher.getSize(this.currentBatchKey)))};this.batch=({undoable:i=!0,batchName:e=Nt(),max:t=null,timeout:r=this.defaultBatchTimeout}={})=>{let o=this.batcher.add({key:e,max:t,timeout:r,items:[],userData:{undoable:i}}),s={run:a=>(this.currentBatchKey=e,a(),this.currentBatchKey=_t,s),commit:async()=>(await this.batcher.flush(_t),o.flush()),flush:()=>s.commit(),discard:()=>{this.batcher.discard(e)}};return s};this.flushAll=()=>Promise.all(this.batcher.flushAll());this.createUndo=async i=>{let e=await this.getInverseOperations(i);return e.length?async()=>{let t=await this.createUndo({ops:e,source:i.source});for(let r of e)r.timestamp=this.meta.now;return await this.commitOperations(e,{undoable:!1}),t}:null};this.getInverseOperations=async({ops:i,source:e})=>{let t=gt(i),r=[],o=()=>this.meta.now;return await Promise.all(Object.entries(t).map(async([s,a])=>{let u=(e??await this.entities.hydrate(z(s)))?.__getViewData__(s,"confirmed");if(!u){this.ctx.log("warn","could not find entity",s,"for undo operation",i);return}let m=Vr(s,u.view,a,o);r.unshift(...m)})),r};this.meta=e,this.ctx=t,this.entities=r,this.defaultBatchTimeout=i,this.batcher=new Ze(this.flushOperations),this.batcher.add({key:_t,items:[],max:100,timeout:i,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===_t}};var wn=class extends se{constructor({ctx:e}){super(e.documentDb,{log:e.log});this.reset=async()=>{let e=Object.keys(this.ctx.schema.collections),t=this.ctx.documentDb.transaction(e,"readwrite");await Promise.all(e.map(r=>{let o=t.objectStore(r);return J(o.clear())})),this.ctx.entityEvents.emit("collectionsChanged",e),this.ctx.log("info","\u{1F4A8} Reset queryable storage")};this.saveEntities=async(e,t)=>{if(e.length===0)return;let r=Array.from(new Set(e.map(a=>me(a.oid).collection))),o=r.filter(a=>!this.ctx.schema.collections[a]);if(o.length>0){this.ctx.log("warn",`Ignoring entities from collections that no longer exist: ${o.join(", ")}`);let a=new Set(r);o.forEach(h=>a.delete(h)),r=Array.from(a)}let s={transaction:this.createTransaction(r,{mode:"readwrite",abort:t?.abort})};await Promise.all(e.map(async a=>{let h=a.getSnapshot();try{await this.saveDocument(a.oid,h,s)}catch(u){throw this.ctx.log("error",`Error saving document ${a.oid} (${JSON.stringify(h)})`,u),u instanceof Error?u:new Error("Unknown error saving document")}})),s.transaction.commit(),this.ctx.entityEvents.emit("collectionsChanged",r);for(let a of e)this.ctx.entityEvents.emit("documentChanged",a.oid)};this.saveDocument=async(e,t,{transaction:r})=>{this.ctx.log("debug",`Saving document indexes for querying ${e}`,t);let{collection:o,id:s}=me(e);if(!t)await this.run(o,a=>a.delete(s),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Deleted document indexes for querying ${e}`);else{let a=this.ctx.schema.collections[o],h=Wt(a,t);await this.run(o,u=>u.put(h),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Saved document indexes for querying ${e}`,t)}};this.ctx=e,this.addDispose(this.ctx.internalEvents.subscribe("documentDbChanged",t=>{this.db=t}))}};var Cn=Je(Bo(),1);var An=class extends Ie{constructor({ctx:e,meta:t,files:r}){super();this.events={add:new Cn.WeakEvent,replace:new Cn.WeakEvent,resetAll:new Cn.WeakEvent};this.cache=new Map;this.pendingEntityPromises=new Map;this.abortDataQueueController=new AbortController;this.ongoingResetPromise=null;this.entityFinalizationRegistry=new FinalizationRegistry(e=>{this.ctx.log("debug","Entity GC",e)});this.addData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not adding incoming data");return}e.reset&&(this.ctx.log("info","Resetting local store to replicate remote synced data - dropping any current transactions"),this.abortDataQueueController.abort(0),this.abortDataQueueController=new AbortController,this.ongoingResetPromise=this.resetData().finally(()=>{this.ongoingResetPromise=null})),this.ongoingResetPromise&&(this.ctx.log("debug","Waiting for ongoing reset to complete"),await this.ongoingResetPromise,this.ctx.log("debug","Ongoing reset complete")),await this.processData(e)};this.resetData=async()=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not resetting local data");return}await this.meta.reset(),await this.queryableStorage.reset(),this.events.resetAll.invoke(this)};this.processData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not processing incoming data");return}let t=e?.baselines??[],r=e?.operations??[];this.ctx.log("debug","Processing incoming data",{operations:r.length,baselines:t.length,reset:!!e.reset});let o=Array.from(new Set(t.map(m=>z(m.oid)).concat(r.map(m=>z(m.oid))))),s=kr(t),a=Tr(r);this.ctx.log("debug","Applying data to live entities");for(let m of o){let v=s[m],y=a[m]??[],C=gt(y),w=e.reset?this.events.replace:this.events.add,S=this.pendingEntityPromises.get(m);S?S.then(()=>{w.invoke(this,{oid:m,baselines:v,operations:C,isLocal:!1})}):(this.cache.has(m)&&this.ctx.log("debug","Cache has",m,", an event should follow."),w.invoke(this,{oid:m,baselines:v,operations:C,isLocal:!1}))}let h={abort:this.abortDataQueueController.signal};await this.meta.insertData(e,h);let u=await Promise.all(o.map(async m=>await this.hydrate(m,h)??{oid:m,getSnapshot(){return null}}));try{await this.queryableStorage.saveEntities(u,h)}catch(m){this.disposed?this.ctx.log("warn","Error saving entities to queryable storage - EntityStore is disposed",m):this.ctx.log("error","Error saving entities to queryable storage",m)}};this.hydrate=async(e,t)=>{if(!Rr(e))throw new Error("Cannot hydrate non-root entity");if(this.cache.has(e)){this.ctx.log("debug","Hydrating entity from cache",e);let o=this.cache.get(e);if(o){let s=o.deref();if(s)return s.deleted?null:s;this.ctx.log("debug","Removing GC'd entity from cache",e),this.cache.delete(e)}}let r=this.pendingEntityPromises.get(e);if(r)return this.ctx.log("debug","Waiting for entity hydration",e),r;{this.ctx.log("debug","Hydrating entity from storage",e);let o=this.constructEntity(e);if(!o)return null;let s=this.loadEntity(o,t);return s.finally(()=>{this.pendingEntityPromises.delete(e)}),this.pendingEntityPromises.set(e,s),s}};this.destroy=async()=>{this.dispose(),await this.batcher.flushAll()};this.create=async(e,t,{undoable:r=!0}={})=>{this.ctx.log("debug","Creating new entity",t);let{collection:o}=me(t);$t(e);let s=nt(e,this.files.add);$(s,t);let a=this.constructEntity(t);if(!a)throw new Error(`Could not put new document: no schema exists for collection ${o}`);let h=this.meta.patchCreator.createInitialize(s,t);await this.batcher.commitOperations(h,{undoable:!!r,source:a});let u=gt(h);return this.events.add.invoke(this,{operations:u,isLocal:!0,oid:t}),this.cache.set(t,this.ctx.weakRef(a)),a};this.deleteAll=async(e,t)=>{this.ctx.log("info","Deleting documents",e),L(e.every(s=>s===z(s)),"Only root documents may be deleted via client methods");let r=await Promise.all(e.flatMap(async s=>(await this.hydrate(s))?.__getFamilyOids__()??[]));e.forEach(s=>{this.cache.delete(s),this.ctx.log("debug","Deleted document from cache",s)});let o=this.meta.patchCreator.createDeleteAll(r.flat());await this.batcher.commitOperations(o,{undoable:t?.undoable===void 0?!0:t.undoable})};this.delete=async(e,t)=>this.deleteAll([e],t);this.getCollectionSchema=e=>{let t=this.ctx.schema.collections[e];return t?{schema:{type:"object",nullable:!1,properties:t.fields},readonlyKeys:[t.primaryKey]}:(this.ctx.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]})};this.constructEntity=e=>{let{collection:t}=me(e),{schema:r,readonlyKeys:o}=this.getCollectionSchema(t);if(!r)return null;if(this.disposed)throw new Error("Cannot hydrate entity after store has been disposed");let s=new yn({ctx:this.ctx,onPendingOperations:this.onPendingOperations,rootOid:e});return new ue({ctx:this.ctx,oid:e,schema:r,readonlyKeys:o,files:this.files,metadataFamily:s,patchCreator:this.meta.patchCreator,events:this.events})};this.onPendingOperations=e=>{this.batcher.addOperations(e)};this.loadEntity=async(e,t)=>{let{operations:r,baselines:o}=await this.meta.getDocumentData(e.oid,t);return!o.length&&!Object.keys(r).length?(this.ctx.log("debug","No data found for entity",e.oid),null):(this.ctx.log("debug","Loaded entity from storage",e.oid),this.events.replace.invoke(this,{oid:e.oid,baselines:o,operations:r,isLocal:!1}),this.cache.set(e.oid,this.ctx.weakRef(e)),this.entityFinalizationRegistry.register(e,e.oid),e)};this.ctx=e,this.meta=t,this.files=r,this.queryableStorage=new wn({ctx:e}),this.batcher=new bn({ctx:e,meta:t,entities:this})}get batch(){return this.batcher.batch}get flushAllBatches(){return this.batcher.flushAll}};var Ki=Symbol("handleMessage"),va,Et=class extends V{constructor({initialPresence:e,updateBatchTimeout:t=200,defaultProfile:r,replicaStore:o}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,t)=>e.id===t.replicaId||this._selfReplicaIds.has(t.replicaId)||this._self.id===t.id;this[va]=async(e,t)=>{let r=!1,o=new Set(this.peerIds);if(t.type==="presence-changed")this.isSelf(e,t.userInfo)?(this._self=t.userInfo,this._selfReplicaIds.add(t.userInfo.replicaId),this.emit("selfChanged",t.userInfo)):(o.add(t.userInfo.id),this._peers[t.userInfo.id]=t.userInfo,r=!0,this.emit("peerChanged",t.userInfo.id,t.userInfo));else if(t.type==="sync-resp"){this._peers={},o.clear();for(let[s,a]of Object.entries(t.peerPresence))this.isSelf(e,a)?(this._self=a,this._selfReplicaIds.add(a.replicaId),this.emit("selfChanged",a)):(r=!0,o.add(s),this._peers[s]=a,this.emit("peerChanged",s,a))}else if(t.type==="presence-offline"){o.delete(t.userId),this._selfReplicaIds.delete(t.replicaId);let s=this._peers[t.userId];delete this._peers[t.userId],r=!0,this.emit("peerLeft",t.userId,s)}r&&(this._peerIds=Array.from(o),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let t=e.reduce((r,o)=>({...r,...o}),this.self.presence);this.emit("update",t)};this.self.presence=e,this.self.profile=r,this.self.id="",this.self.replicaId="",o.get().then(s=>{this.self.replicaId=s.id}),this._updateBatcher=new Ze(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:t,items:[],key:"default"})}static{va=Ki}get self(){return this._self}get peers(){return this._peers}get peerIds(){return this._peerIds}get everyone(){let e={...this._peers};return e[this.self.id]=this.self,e}get selfReplicaIds(){return this._selfReplicaIds}};var Pn=class{constructor({endpointProvider:i,log:e}){this.uploadFile=async i=>{let e=i.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:t,token:r}=await this.endpointProvider.getEndpoints(),o=new window.FormData;o.append("file",e);try{let s=await fetch(t+`/${i.id}`,{method:"POST",body:o,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return s.ok?(this.log("info","File upload successful"),{success:!0,retry:!1}):(this.log("error","File upload failed",s.status,await s.text()),{success:!1,retry:s.status>=500})}catch(s){return this.log("error","File upload failed",s),{success:!1,retry:!0}}};this.getFile=async i=>{let{files:e,token:t}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${i}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});return r.ok?{success:!0,data:await r.json()}:(this.log("error","File information fetch failed",r.status,await r.text()),{success:!1,retry:r.status>=500||r.status===404})}catch(r){return this.log("error","File information fetch failed",r),{success:!1,error:r,retry:!0}}};this.endpointProvider=i,this.log=e}};var rt=class extends V{constructor({interval:e=15*1e3,deadlineLength:t=3*1e3,restartOnTabFocus:r=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=t,typeof window<"u"&&r&&(window.addEventListener("pageshow",()=>this.start(!0)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.start(!0)}))}get interval(){return this._interval}};var Rn=class extends V{constructor({endpointProvider:e,meta:t,presence:r,interval:o=15*1e3,log:s=()=>{},fetch:a=window.fetch.bind(window)}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:t,token:r}=await this.endpointProvider.getEndpoints(),o=await this.fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(o.ok){this.heartbeat.keepAlive();let s=await o.json();for(let a of s.messages)this.handleServerMessage(a);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else{this.log("Sync request failed",o.status,await o.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1));let s=await o.json();$r(s)&&s.code===bt.TokenExpired&&(this.endpointProvider.clearCache(),this.heartbeat.keepAlive()),o.status>=500&&this.heartbeat.keepAlive()}}catch(t){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(t),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.destroy=()=>{this.dispose(),this.stop()};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.log=s,this.meta=t,this.presence=r,this.endpointProvider=e,this.fetch=a,this.heartbeat=new rt({interval:o}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}ignoreIncoming(){this.stop()}get isConnected(){return this._isConnected}get status(){return this._status}};function qi(n){this.message=n}qi.prototype=new Error,qi.prototype.name="InvalidCharacterError";var jo=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(n){var i=String(n).replace(/=+$/,"");if(i.length%4==1)throw new qi("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,t,r=0,o=0,s="";t=i.charAt(o++);~t&&(e=r%4?64*e+t:t,r++%4)?s+=String.fromCharCode(255&e>>(-2*r&6)):0)t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);return s};function xa(n){var i=n.replace(/-/g,"+").replace(/_/g,"/");switch(i.length%4){case 0:break;case 2:i+="==";break;case 3:i+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(jo(e).replace(/(.)/g,function(t,r){var o=r.charCodeAt(0).toString(16).toUpperCase();return o.length<2&&(o="0"+o),"%"+o}))}(i)}catch{return jo(i)}}function Fn(n){this.message=n}function Sa(n,i){if(typeof n!="string")throw new Fn("Invalid token specified");var e=(i=i||{}).header===!0?0:1;try{return JSON.parse(xa(n.split(".")[e]))}catch(t){throw new Fn("Invalid token specified: "+t.message)}}Fn.prototype=new Error,Fn.prototype.name="InvalidTokenError";var Mo=Sa;var Tn=class{constructor(i){this.config=i;this.cached=null;this.type=Te.Realtime;this.getEndpoints=async()=>{if(this.cached)return this.cached;let i;this.config.fetchAuth?i=await this.config.fetchAuth():i=await(this.config.fetch||fetch.bind(window))(this.config.authEndpoint,{credentials:"include"}).then(h=>{if(h.ok)return h.json();throw new Error(`Auth endpoint returned non-200 response: ${h.status}`)}),L(i.accessToken,"No access token provided from auth endpoint");let e=Mo(i.accessToken);L(e.url,"No sync endpoint provided from auth endpoint"),L(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let t=new URL(e.url);t.protocol=t.protocol.replace("ws","http");let r=t.toString();t.protocol=t.protocol.replace("http","ws");let o=t.toString(),s=e.file;if(!s){let a=new URL(r);a.pathname=a.pathname+"/files",s=a.toString()}return this.cached={http:r,websocket:o,files:s,token:i.accessToken},this.cached};this.clearCache=()=>{this.cached=null};if(!i.authEndpoint&&!i.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var kn=class extends V{constructor(e){super();this.timer=null;this.isScheduled=!1;this.next=()=>{this.isScheduled||(this.isScheduled=!0,this.timer=setTimeout(()=>{this.emit("trigger"),this.isScheduled=!1,this.backoff.next()},this.backoff.current))};this.reset=()=>{this.backoff.reset(),this.timer&&(clearTimeout(this.timer),this.timer=null)};this.backoff=e}},Bn=class{constructor(i,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=i,this.factor=e}};var jn=class extends V{constructor({endpointProvider:e,meta:t,presence:r,log:o}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this.incomingQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this._ignoreIncoming=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new rt;this.reconnectScheduler=new kn(new Bn(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),!this.disposed&&(e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e))};this.onMessage=async e=>{if(this._ignoreIncoming){this.log("Ignoring incoming message (ignore incoming flag set)",e.data);return}let t=JSON.parse(e.data);switch(t.type){case"sync-resp":if(t.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(t.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length)if(t.overwriteLocalData)this.log("warn","Overwriting local data - dropping outgoing message queue"),this.syncQueue=[];else{for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}if(this.emit("message",t),this.incomingQueue.length){for(let r of this.incomingQueue)this.emit("message",r);this.incomingQueue=[]}break;case"need-since":case"presence-changed":case"presence-offline":this.emit("message",t);break;case"op-re":if(!this.synced){this.log("Enqueueing op-re message because sync hasn't finished yet",t),this.incomingQueue.push(t);break}this.emit("message",t);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",t);break;default:this.synced&&this.emit("message",t);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.destroy=()=>{this.dispose(),this.stop()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.close(),this.socket=null,this._status="paused"};this.log=o||this.log,this.endpointProvider=e,this.meta=t,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}ignoreIncoming(){this.incomingQueue=[],this._ignoreIncoming=!0}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var Mn=class extends V{constructor({meta:e}){super();this.mode="pull";this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1});this.presence=new Et({initialPresence:null,defaultProfile:null,replicaStore:e.localReplica})}send(){}start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},ot=class extends V{constructor({authEndpoint:e,fetchAuth:t,fetch:r,initialPresence:o,automaticTransportSelection:s=!0,autoStart:a,initialTransport:h,pullInterval:u,presenceUpdateBatchTimeout:m,defaultProfile:v,useBroadcastChannel:y},{meta:C,log:w,onData:S}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.onTokenExpired=()=>{this.endpointProvider.clearCache()};this.handleMessage=async(e,{source:t}={source:"network"})=>{if(e.type==="op-re"||e.type==="sync-resp")for(let r of e.operations)this.meta.time.update(r.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}t==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[Ki](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let t;e==="realtime"?t=this.webSocketSync:t=this.pushPullSync,t!==this.activeSync&&(this.log("debug","switching to",e,"mode"),this.activeSync.status==="active"&&t.start(),this.activeSync.stop(),this.activeSync=t)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=e=>{if(this.activeSync.status==="active")return this.activeSync.send(e)};this.uploadFile=async e=>(this.log("info","Uploading file",{name:e.name,type:e.type,id:e.id}),this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1});this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.destroy=()=>{this.dispose(),this.webSocketSync.destroy(),this.pushPullSync.destroy()};this.reconnect=()=>this.activeSync.reconnect();if(this.meta=C,this.onData=S,this.log=w||(()=>{}),this.presence=new Et({initialPresence:o,defaultProfile:v,updateBatchTimeout:m,replicaStore:C.localReplica}),this.endpointProvider=new Tn({authEndpoint:e,fetchAuth:t,fetch:r}),this.webSocketSync=new jn({endpointProvider:this.endpointProvider,meta:C,presence:this.presence,log:this.log}),this.pushPullSync=new Rn({endpointProvider:this.endpointProvider,meta:C,presence:this.presence,log:this.log,interval:u,fetch:r}),this.fileSync=new Pn({endpointProvider:this.endpointProvider,log:this.log}),y&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),h==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),s&&this.canDoRealtime){let I=()=>{x&&clearTimeout(x);let R=Object.keys(this.presence.peers).length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;R&&this.mode==="pull"?this.setMode("realtime"):!R&&this.mode==="realtime"&&(x=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},x;this.presence.subscribe("peersChanged",I),s!=="peers-only"&&this.presence.subscribe("selfChanged",I)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===Te.Realtime||this.endpointProvider.type===Te.PassiveRealtime||this.endpointProvider.type===Te.ReadOnlyRealtime}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}ignoreIncoming(){this.activeSync.ignoreIncoming()}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};function Oa(n){return n!==null}function Hi(n){return Array.isArray(n)?n.map(Hi).filter(Oa):n instanceof ue&&n.deleted?null:n}function Be(n,i){return!n&&!i||n&&i&&Re(n)===Re(i)}var Wi=Symbol("ON_ALL_UNSUBSCRIBED"),fe=Symbol("UPDATE"),Ia,ge=class extends Ie{constructor({initial:e,context:t,collection:r,key:o,shouldUpdate:s}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{if(this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=Hi(e),Array.isArray(this._value)&&this._value.some(t=>t.getSnapshot()===null))debugger;this._status="ready",this._events.emit("change",this._value)};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(t=>{t instanceof ue&&(this._internalUnsubscribes.push(t.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(t.subscribe("restore",this.refreshValue)))}):e instanceof ue&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>(this.context.log("debug","Executing query",this.key),this._status==="initial"?this._status="initializing":this._status==="ready"&&(this._status="revalidating"),this._executionPromise=this.run().then(()=>this._value).catch(e=>{if(e instanceof Error){if(e.name==="InvalidStateError"||e.name==="InvalidAccessError")return this._value;throw e}else throw new Error("Unknown error executing query")}),this._executionPromise);this[Ia]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this._events=new V(h=>{h==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=t,this.key=o,this.collection=r;let a=s||(h=>h.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",h=>{a(h)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Ia=Wi}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}subscribe(e,t){if(t===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&t!==void 0)return this.resolved,this._events.subscribe("change",t);if(e==="statusChange"&&typeof t=="function")return this._events.subscribe(e,t);throw new Error("Invalid invocation of Query.subscribe")}};var Ln=class extends ge{constructor({id:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=Z(r.collection,e),this.hydrate=t}};var _a,Un=class extends ge{constructor({index:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await ln({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[_a]=e=>{Be(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{_a=fe}};var Da,Vn=class extends ge{constructor({index:e,hydrate:t,pageSize:r,page:o,...s}){super({initial:[],...s});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await xt({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=t,this.setValue(await Promise.all(e.map(this.hydrate)))};this.nextPage=async()=>{this.hasNextPage&&(this._page++,await this.run())};this.previousPage=async()=>{this._page!==0&&(this._page--,await this.run())};this.setPage=async e=>{this._page=e,await this.run()};this[Da]=e=>{Be(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t,this._pageSize=r,this._page=o}static{Da=fe}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Ea,Nn=class extends ge{constructor({hydrate:e,pageSize:t,index:r,...o}){super({initial:[],...o});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await xt({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=t,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:t}=await xt({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=t,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[Ea]=e=>{Be(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=t}static{Ea=fe}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Ca,$n=class extends ge{constructor({index:e,hydrate:t,...r}){super({initial:[],...r});this.run=async()=>{let e=await dn({collection:this.collection,index:this.index,context:this.context});this.context.log("debug",`FindAllQuery: ${e.length} oids found: ${e}`),this.setValue(await Promise.all(e.map(this.hydrate)))};this[Ca]=e=>{Be(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Ca=fe}};var zn=class{constructor({collection:i,cache:e,entities:t,context:r,documentManager:o}){this.serializeIndex=i=>i?Re(i):"";this.get=i=>{let e=`get:${this.collection}:${i}`;return this.cache.getOrSet(e,()=>new Ln({id:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:i,key:e}={})=>{let t=e||`findOne:${this.collection}:${this.serializeIndex(i)}`;return this.cache.getOrSet(t,()=>new Un({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[fe](i)})};this.findAll=({index:i,key:e}={})=>{let t=e||`findAll:${this.collection}:${this.serializeIndex(i)}`;return this.cache.getOrSet(t,()=>new $n({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[fe](i)})};this.findPage=({index:i,pageSize:e,page:t,key:r})=>{let o=r||`findPage:${this.collection}:${this.serializeIndex(i)}:${e}`;return this.cache.getOrSet(o,()=>new Vn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:o,pageSize:e,page:t}),s=>{s[fe](i)})};this.findAllInfinite=({index:i,pageSize:e,key:t})=>{let r=t||`findAllInfinite:${this.collection}:${this.serializeIndex(i)}:${e}`;return this.cache.getOrSet(r,()=>new Nn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),o=>{o[fe](i)})};this.cache=e,this.collection=i,this.hydrate=t.hydrate,this.context=r,this.documentManager=o,this.put=this.documentManager.create.bind(this.documentManager,this.collection),this.delete=this.documentManager.delete.bind(this.documentManager,this.collection),this.deleteAll=this.documentManager.deleteAllFromCollection.bind(this.documentManager,this.collection)}};var Kn=class extends Ie{constructor({evictionTime:e=5*1e3,context:t}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this.dropAll=()=>{this._cache.forEach(e=>e.dispose()),this._cache.clear()};this._evictionTime=e,this.context=t}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[Wi](this.onQueryUnsubscribed),e}getOrSet(e,t,r){let o=this.get(e);return o?(r?.(o),o):this.set(t())}};var We=class extends V{constructor(e,t,r){super();this.config=e;this.context=t;this._closed=!1;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),t={};if(this.disposed)return{};for(let u of e)try{t[u]=await wt(this.documentDb,u)}catch(m){this.context.log?.("error",m)}if(this.disposed)return{collections:t};let r=await this.meta.stats(),o=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,s=Object.values(t).reduce((u,{size:m})=>u+m,0),a=r.baselinesSize.size+r.operationsSize.size,h=a/s;return{collections:t,meta:r,storage:o,totalMetaSize:a,totalCollectionsSize:s,metaToDataRatio:h,quotaUsage:o?.usage&&o?.quota?o.usage/o.quota:void 0}};this.close=async()=>{this._closed=!0,this.sync.ignoreIncoming(),await this._entities.flushAllBatches(),this._fileManager.close(),this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await ze(this.documentDb),await ze(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Xt(this.namespace,indexedDB)};this.export=async({downloadRemoteFiles:e}={downloadRemoteFiles:!0})=>{this.context.log("info","Exporting data...");let t=await this.meta.export(),r=await this._fileManager.exportAll(e),o=[],s=[];for(let a of r){let h=a.file;if(delete a.file,o.push(a),h){let u=new File([h],this.getFileExportName(a.name,a.id),{type:a.type});s.push(u)}else this.context.log("warn",`File ${a.id} was could not be loaded locally or from the server. It will be missing in the export.`)}return{data:t,fileData:o,files:s}};this.getFileExportName=(e,t)=>`${t}___${e}`;this.parseFileExportname=e=>{let[t,r]=e.split("___");return{id:t,originalFileName:r}};this.import=async({data:e,fileData:t,files:r})=>{this.context.log("info","Importing data..."),await ze(this.context.documentDb),await this.meta.resetFrom(e);let o=new Map(r.map(m=>{let{id:v}=this.parseFileExportname(m.name);return[v,m]})),s=t.map(m=>{let v=o.get(m.id);return{...m,file:v}});await this._fileManager.importAll(s);let a=e.schema.version,h=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((m,v)=>{h.onsuccess=m,h.onerror=v});let u=this.context.schema;if(u.version!==a)throw new Error("Only exports from the current schema version can be imported");this.context.documentDb=await St({meta:this.meta,migrations:this.config.migrations,context:this.context,version:a}),this.context.internalEvents.emit("documentDbChanged",this.documentDb),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:e.operations,baselines:e.baselines,reset:!0}),await ze(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=u,this.context.documentDb=await St({meta:this.meta,migrations:this.config.migrations,context:this.context,version:u.version}),this.context.internalEvents.emit("documentDbChanged",this.documentDb)};this.__dangerous__hardReset=async()=>{let e=await this.export();await this.import(e)};this.meta=r.meta,this.collectionNames=Object.keys(t.schema.collections),this._sync=this.config.syncConfig&&!t.schema.wip?new ot(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new Mn({meta:this.meta}),t.schema.wip&&this.config.syncConfig&&t.log("warn","\u26A0\uFE0F\u26A0\uFE0F Sync is disabled for WIP schemas. Commit your schema changes to start syncing again. \u26A0\uFE0F\u26A0\uFE0F"),this._fileManager=new mn({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new An({ctx:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new Kn({context:t}),this._documentManager=new hn(this.meta,this.schema,this._entities);let o=Er(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",o),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[s,a]of Object.entries(t.schema.collections)){let h=s;this[h]=new zn({collection:h,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get batch(){return this.entities.batch}};var Ct=class{constructor(i){this.value=i}deref(){return this.value}};var Lo=Symbol("metadataVersion");var qn=class{constructor(i){this.init=i;this._initializing=!1;this.initialize=async i=>{if(typeof window>"u"&&!i.indexedDb)throw new Error("A verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e;return i.schema.wip?e=await this.initializeWIPDatabases(i):(e=await this.initializeDatabases(i),this.cleanupWIPDatabases(i)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw e instanceof Error?(this.rejectReady(e),e):new Error("Unknown error initializing storage")}finally{this._initializing=!1}};this.initializeDatabases=async i=>{let e=i[Lo],{db:t}=await an({indexedDB:i.indexedDb,log:i.log,namespace:i.namespace,metadataVersion:e}),r={namespace:this._namespace,metaDb:t,schema:i.schema,log:i.log||(()=>{}),undoHistory:i.undoHistory||new Ot,entityEvents:new V,globalEvents:new V,internalEvents:new V,weakRef:m=>i.EXPERIMENTAL_weakRefs?new WeakRef(m):new Ct(m),migrations:i.migrations},o=new vt({context:r,disableRebasing:i.disableRebasing});await o.updateSchema(i.schema,i.overrideSchemaConflict);let s=Object.assign(r,{getNow:()=>o.now}),a=await St({context:s,version:i.schema.version,meta:o,migrations:i.migrations,indexedDB:i.indexedDb}),h=Object.assign(s,{documentDb:a});return new We({syncConfig:i.sync,migrations:i.migrations,files:i.files},h,{meta:o})};this.initializeWIPDatabases=async i=>{let e=Re(i.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let t=`@@wip_${i.namespace}_${e}`,{db:r}=await Hr({indexedDB:i.indexedDb,log:i.log,namespace:i.namespace,wipNamespace:t}),o={namespace:this._namespace,metaDb:r,schema:i.schema,log:i.log||(()=>{}),undoHistory:i.undoHistory||new Ot,entityEvents:new V,globalEvents:new V,internalEvents:new V,weakRef:v=>i.EXPERIMENTAL_weakRefs?new WeakRef(v):new Ct(v),migrations:i.migrations},s=new vt({context:o,disableRebasing:i.disableRebasing}),a=Object.assign(o,{getNow:()=>s.now});await s.updateSchema(i.schema,i.overrideSchemaConflict);let h=await Gr({context:a,version:i.schema.version,meta:s,migrations:i.migrations,indexedDB:i.indexedDb,wipNamespace:t}),u=Object.assign(a,{documentDb:h});return new We({syncConfig:i.sync,migrations:i.migrations,files:i.files},u,{meta:s})};this.cleanupWIPDatabases=async i=>{let r=(await Kr(i.indexedDb)).filter(o=>o.name?.startsWith("@@wip_")).map(o=>o.name).filter(o=>!o.startsWith(`@@wip_${i.namespace}_${Re(i.schema)}`));for(let o of r)await zr(o,i.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await Xt(this.namespace)};this._readyPromise=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}),this._namespace=i.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};window.Verdant=Qi;
|
|
16
16
|
//# sourceMappingURL=index.js.map
|