1"use strict"; 2!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1c166e6b-2af3-5ce0-999e-f5fe88f21937")}catch(e){}}(); 3(self.webpackChunk_remnote_client=self.webpackChunk_remnote_client||[]).push([["12481"],{646412:function(e,t,a){a.d(t,{P3:function(){return o},TL:function(){return n},Wo:function(){return r},ZK:function(){return d}}),a(448445);var i=a(158876);let s=new Map;async function n(e){if(s.get(e)&&await s.get(e)?.waitUntilFalseThenSetTrue(),!s.has(e)){let t=new i.lN("lock."+e);t.set(!0),s.set(e,t)}}function r(e){let t=s.get(e);t?.hasAwaiters()||s.delete(e),t?.set(!1)}function o(){return`Lock Keys: ${[...s.keys()]} 4`}function d(){return[...s.keys()]}window.keyToLock=s},236664:function(e,t,a){let i;a.d(t,{FE:function(){return eu},FP:function(){return el},LT:function(){return ed},M:function(){return eh},_f:function(){return ef},oM:function(){return eD},v2:function(){return ec},wU:function(){return eb}});var s,n=a(648720),r=a(619360),o=a(185227),d=a(159273),c=a(263510),h=a(448445),l=a(174174),u=a(134173),y=a(86124),S=a(697497),g=a(174577),m=a(963245),D=a(158876),p=a(525949),b=a(804999),f=a(646412),F=a(528037),w=a(536184),T=a(722882),v=a(398793),I=a(315729),L=a(301692),N=a(661982),A=a(357885),R=a(254853),O=a(713885),M=a(506207),E=a(520236),C=a(612142),k=a(410721);a(249442);var U=a(731470),B=a(618637),G=a(344138),Q=a(571054),P=a(401868),z=a(573081),$=a(30318),x=a(863971),X=a(554667),K=a(875410),W=a(651112),J=a(903296),V=a(879474),H=a(11113),q=a(548343),j=a(800209),Y=a(304714),Z=a(23699),ee=a(519166),et=a(571015),ea=a(550614),ei=a(719520);a(301800);var es=a(79117),en=a(513217),er=a(12837),eo=a(291882);let ed=1e4,ec=()=>(i||(i=(0,es.getSyncingServiceWorkerClientSingleton)()),i);var eh=((s={})[s.GloballyNewId=0]="GloballyNewId",s[s.PossiblyReusedId=1]="PossiblyReusedId",s);function el(e){return"deleted_"+e}function eu(e){return"staged_changes_"+e}let ey={},eS={},eg=new D.lN("clientCollectionLock");function em(e,t,a,i){if(i){if(!e.has(a)||t.has(a)){let e=t.get(a)??new Set;for(let t of i)e.add(t.split(".")[0]);t.set(a,e)}}else t.delete(a);e.add(a)}Date.now();setTimeout(()=>{},1);class eD{collectionName;owner;ownershipLevel;transformFunction;finishedLoadingCallback;useReactiveStore;syncWithServer;lazyLoadFromDatabaseStore;serviceWorkerClient;getBackgroundJobManager;schema;storeDeletedDocuments;constructTinyGraphLinker;createNewFunction;skipSearchPortalMaintenance=!1;DatabaseStore;MissingIdsDatabaseStore;DatabaseDeletedStore;StagedChangesDatabaseStore;StagedChangesDatabaseDeletedStore;ReactiveStore;createdDatabaseStoreOrNotPersistentFlag;initializedSyncDataFlag;isInitializingSyncDataFlag;hasDatabaseStore;enableSyncing;hasLoadedReactiveStoreFlag;haveUnsyncedInformationLazyReactiveBool=!1;hasConstructedDatabaseStores;reactiveQueries=new C.H(!1);databaseStoreQueueToDelete=new Map;databaseStoreQueueToDeleteFromOtherTab=new Map;databaseStoreQueueToDeleteThisBatch;databaseStoreQueueToUpsert=new Set;databaseStoreChangedFieldsToUpsert=new Map;databaseStoreQueueToUpsertFromOtherTab=new Set;databaseStoreQueueToUpsertThisBatch;deletedDocToTimestamp=new Map;broadcastQueueToDelete=new Map;broadcastQueueToUpsert=new Set;tinyGraphLinker;tinyGraphLinkerConstructedFlag;tinyGraphLoadedFlag;tinyGraphPartialPhase1FromDBLoadedFlag;findOneFromDatabaseStoreResolvers=[];findOneDatabaseStoreQueue=[];findOneDatabaseStoreQueueTimer;activeFindOneLookupCounts=new Map;findOneFromNumberIdFromDatabaseStoreResolvers=[];findOneFromNumberIdDatabaseStoreQueue=[];findOneFromNumberIdDatabaseStoreQueueTimer;activeFindOneFromNumberIdLookupCounts=new Map;database;Collection;syncModule;closed=!1;syncDataInMemory;syncDataInDatabase;syncDataToStoreThisBatch;nextDatabaseSyncData;syncDataDep=new k.Dependency;mustFlushNewSyncData=!1;reactiveStoreLoadState;idsFetchedFromDatabaseStore=new Set;numberIdsFetchedFromDatabaseStore=new Set;triedToFetchFromDatabaseStore={};loadingFromDatabaseStore=new E.M;enableEventTablesForCollection;inLazyLoadStateReactiveVar=new C.H(!1);hasInitialized;runConsumersAfterFlush=!1;keepInReactiveStoreWhenClearing=void 0;hasFinishedSyncingFirstSyncAndFlushedToDatabaseFlag;isApplyingStagedChangesFlag;hasFetchedFirstSyncDocs=void 0;isCurrentlySyncingFlag=void 0;triggerSyncTimer;constructor(e,t,a,i,s,n=!0,r=!0,o=!1,d,c=ec(),h,l,u=!0,y,S){if(this.collectionName=e,this.owner=t,this.ownershipLevel=a,this.transformFunction=i,this.finishedLoadingCallback=s,this.useReactiveStore=n,this.syncWithServer=r,this.lazyLoadFromDatabaseStore=o,this.serviceWorkerClient=c,this.getBackgroun
4dJobManager=h,this.schema=l,this.storeDeletedDocuments=u,this.constructTinyGraphLinker=y,this.createNewFunction=S,(0,eo.m)(e,t),this.tinyGraphLoadedFlag=new D.lN("tinyGraphLoadedFlag_"+e+"_"+t),this.tinyGraphLinkerConstructedFlag=new D.lN("tinyGraphLinkerConstructedFlag_"+e+"_"+t),this.tinyGraphPartialPhase1FromDBLoadedFlag=new D.lN("tinyGraphPartialPhase1FromDBLoadedFlag_"+e+"_"+t),this.hasConstructedDatabaseStores=new D.lN("hasConstructedDatabaseStores"+e+"_"+t),this.createdDatabaseStoreOrNotPersistentFlag=new D.lN("createdDatabaseStoreOrNotPersistentFlag."+this.collectionName+"_"+t),this.initializedSyncDataFlag=new D.lN("initializedSyncDataFlag."+this.collectionName+"_"+t),this.isInitializingSyncDataFlag=new D.lN("isInitializingSyncDataFlag."+this.collectionName+"_"+t),this.hasLoadedReactiveStoreFlag=new D.lN("hasLoadedReactiveStoreFlag."+this.collectionName+"_"+t),this.isApplyingStagedChangesFlag=new D.lN("isApplyingStagedChangesFlag."+this.collectionName+"."+this.owner),this.hasFinishedSyncingFirstSyncAndFlushedToDatabaseFlag=new D.lN("hasFinishedSyncingAndFlushedToDatabaseFirstLoginFlag."+this.collectionName),this.hasInitialized=new D.lN("hasInitialized."+this.collectionName+"."+this.owner),b.MX&&(this.hasFetchedFirstSyncDocs=new D.lN("hasFetchedFirstSyncDocs."+this.collectionName+"_"+t),this.isCurrentlySyncingFlag=new D.lN("isCurrentlySyncingFlag."+this.collectionName+"_"+t)),!n)throw"No longer support !useReactiveStore for "+e+"_"+t;this.database=d||(0,$.getOrCreateDatabaseForOwner)(t),this.hasDatabaseStore=this.database.databaseStore!==K.$T.None,this.hasDatabaseStore||this.createdDatabaseStoreOrNotPersistentFlag.set(!0),this.log("MAKE NEW COLLECTION"),this.reactiveStoreLoadState=o?"Lazy":"LoadingRequested",this.finishedLoadingCallback=s,this.transformFunction=i;const g=(0,A.du)(t);if(a==q.E.BROWSER&&"browser"!=t)throw console.trace("Owner must be browser",t,e),Error("Owner must be 'browser' - "+t);this.receivedSyncUpdateListeners=new m.t(this.collectionName+this.owner),this.enableEventTablesForCollection="sync"!=this.collectionName&&"client_sync_log"!=this.collectionName,this.syncModule=new X.j(this.collectionName,this);const p=!g&&this.owner!=K.tn&&"search-update-cache"!=this.owner&&this.owner&&r;this.enableSyncing=!Accounts.user()?.fakeCypressUserDisableSyncing&&this.hasDatabaseStore&&!!p&&this.database.enableSyncing,this.enableSyncing||this.hasFinishedSyncingFirstSyncAndFlushedToDatabaseFlag.set(!0),this.inLazyLoadStateReactiveVar.set(o),this.useReactiveStore&&(this.ReactiveStore=new H.sO(this.collectionName,this.database.databaseName,i),y&&this.ReactiveStore.createIndex(Z.A.X_NUMBER_ID)),this.database.addCollection(this),this.reactiveQueries.set(!1),this.setSyncProgress(0),this.database.shouldImmediatelyInitializeCollections&&this.initializeFromDatabaseStore(),b.MX?this.loadDocsToSync():this.ensureLoadedSyncDataAndInitializedFlags(),y?this.constructTinyGraph(y):(this.tinyGraphLinkerConstructedFlag.set(!0),this.tinyGraphLoadedFlag.set(!0),this.tinyGraphPartialPhase1FromDBLoadedFlag.set(!0)),this.triggerSyncTimer=new v.F("triggerSyncTimer",()=>{this.sync("onEdit")},2e3)}async prepareForSynchronousMutation(){await this.getBackgroundJobManager?.()}async waitUntilDatabaseStoresInitialized(){await this.hasConstructedDatabaseStores.waitUntilTrue(),b.MX&&this.enableSyncing&&await this.initializedSyncDataFlag.waitUntilTrue()}async constructTinyGraph(e){this.constructTinyGraphLinker=e,this.tinyGraphLinker=await e(this),this.tinyGraphLinkerConstructedFlag.set(!0)}async getTinyGraphLinkerAsync(){return await this.tinyGraphLinkerConstructedFlag.waitUntilTrue(),this.tinyGraphLinker}strictHasFinishedSyncingFirstSync(){return this.hasFinishedSyncingFirstSyncAndFlushedToDatabaseFlag.getReactive()}forDisplayHasFinishedSyncingFirstSync(){return this.hasFinishedSyncingFirstSyncAndFlushedToDatabaseFlag.getReactive()||c.zM}forDisplayIsWiringKnowledgeBase(){return this.isApplyingStagedChangesFlag.getReactive()}strictHasFinishedFirstSyncAndNotApplyingStagedChanges(){return this.hasFinishedSyncingFirstSyncAndFlushedToDatabaseFlag.getReactive()&&!this.isApplyingStagedChangesFlag.getReactive()}strictHasReactiveStoreLoadedAndFinishedFirstSyncAndNotApplyingChanges(){return this.strictHasFinishedFirstSyncAndNotApplyingStagedChanges()&&this.hasLoadedReactiveStore()}forDisplayHasFinishedFirstSyncAndNotApplyingStagedChanges(){return this.strictHasFinishedFirstSyncAndNotApplyingStagedChanges()||c.zM}forDisplayHasReactiveStoreLoadedAndFinishedFirstSyncAndNotApplyingChanges(){return c.zM?this.hasLoadedReactiveStore():this.strictHasReactiveStoreLoadedAndFinishedFirstSyncAndNotApplyingChanges()}hasLoadedReactiveStore(){return this.hasLoadedReactiveStoreFlag.getReactive()}logSyncPerformanceDebugInfo(e,t){if(t)for(let[a,i]of Object.entries({timeBetweenSendAndServerReceives:t.start-e,timeBetweenServerReplyAndClientReceives:Date.now()-t.end,...t.syncPhases})){let e=`${this.collectionName} - ${this.database.databaseName} - serverPhase - ${a}`;e in ey||(ey[e]=0),ey[e]+=i}}triggerSyncOnEdit(){this.enableSyncing&&p.Mr.triggered&&this.triggerSyncTimer.startOrRestart()}async sync(e){if(!b.MX)return await (await (0,y.N)()).syncCollection(this.owner,this.collectionName,e);{if(!await this.database.hasFinishedInitialBulkDownload())return;let e=await (0,u.B)()-1;
4if(await (0,en.waitUntilFinishedAllWriteGuarantees)("sync"),await (0,et.Bq)(),this.database.deleted||this.closed||this.database.databaseStore==K.$T.None)return;l.VF&&await (0,I.yy)(0x5af3107a3fff),await this.isCurrentlySyncingFlag.runOneSimultaneously(async()=>{await this.syncModule.serverSyncModule.applyAllStagedChangesIfNecessaryBeforeSync(),await p.Mr.waitUntilTrue(),await (0,S.ZM)(async()=>{await (0,O.runJob)(R.pO,"syncAll",async()=>{if(this.enableSyncing)try{await this.syncModule.serverSyncModule.ensureServerSyncedUpToCurrentTimestamp(e,{dontSendDiffsOnlyFetch:!1})}catch(e){throw this.isCurrentlySyncingFlag.set(!1),e}})})})}}testHelperUnregisterCollection(){this.setClosed(!0);let e=this.database.collections.indexOf(this);-1!=e&&this.database.collections.splice(e,1)}closeAndUnregisterFromCache(){throw Error("Unsupported closeAndUnregisterFromCache")}setClosed(e){this.closed=e}async getDatabaseStore(e){return this.hasDatabaseStore?(0,O.runJob)(R.lh,`getDatabaseStore.${this.owner}.${this.collectionName}.skipTinyGraphLoader=${e?.skipTinyGraphLoader})`,async t=>(t("1B"+Math.random()),await this.createdDatabaseStoreOrNotPersistentFlag.waitUntilTrue(),t("2C"),e?.skipTinyGraphLoader||this.tinyGraphLoadedFlag.triggered||await this.tinyGraphLoadedFlag.waitUntilTrue(),t("3"),this.DatabaseStore)):null}async getDeletedDatabaseStore(e){return await this.createdDatabaseStoreOrNotPersistentFlag.waitUntilTrue(),e?.skipTinyGraphLoader||await this.tinyGraphLoadedFlag.waitUntilTrue(),this.DatabaseDeletedStore}async getMissingIdsDatabaseStore(e){return await this.createdDatabaseStoreOrNotPersistentFlag.waitUntilTrue(),e?.skipTinyGraphLoader||await this.tinyGraphLoadedFlag.waitUntilTrue(),this.MissingIdsDatabaseStore}async initializeFromDatabaseStore(e=!1){let t=Math.random().toString().slice(2,5);return(0,d.I)(`${t}.${this.collectionName}.${this.owner}.initializeFromDatabaseStore(allowDatabaseStoreSkip=${e}`,()=>(0,O.runJob)(R.lh,`initializeFromDatabaseStore.${this.collectionName}.${this.owner}.allowDatabaseStoreSkip=${e}`,async a=>{let i=e=>{a(e),this.addPersistedCollectionLogIfAdmin("initializeFromDatabaseStore - "+e)};i("1"),e||await (0,d.I)(`${t}.${this.collectionName}.initializedDatabaseStoreFlag.waitUntilTrue`,()=>this.database.initializedDatabaseStoreFlag.waitUntilTrue()),this.hasDatabaseStore?(i("2"),await (0,d.I)(`${t}.${this.collectionName}.constructDatabaseStores`,async()=>{await this.constructDatabaseStores()}),this.createdDatabaseStoreOrNotPersistentFlag.set(!0),i("3 - Start waiting for tinygraph to load"),await this.tinyGraphLoadedFlag.waitUntilTrue(),i("3A"),this.log("Initializing",this.useReactiveStore),this.useReactiveStore?(o.Os(),"LoadingRequested"==this.reactiveStoreLoadState?(this.reactiveStoreLoadState="Loading",this.DatabaseStore?.fetchAll().then(async t=>{await (0,O.runJob)(R.lh,"initializeFromDatabaseStoreFetchAllSave."+this.collectionName+".allowDatabaseStoreSkip."+e,async a=>{await (0,T.f)(),a("1"),!e&&b.MX&&await this.hasFetchedFirstSyncDocs.waitUntilTrue(),a("2"),await this.ensureDocsExistFromQuery(t,"initializeFromDatabaseStoreFetchAllSave",e),o.m8(),this.finishedLoadingFromDatabaseStore(!1),a("3"),this.setSyncProgress(1)})}).catch(e=>{this.error.bind(this)(e)})):"Loading"==this.reactiveStoreLoadState?o.m8():setTimeout(()=>{o.m8(),this.finishedLoadingFromDatabaseStore(!0),this.setSyncProgress(1)})):this.finishedLoadingFromDatabaseStore(!1)):(this.finishedLoadingFromDatabaseStore(!1),this.hasConstructedDatabaseStores.set(!0)),i("4")}))}isStagedForDeletion(e){return this.databaseStoreQueueToDelete.has(e)||this.databaseStoreQueueToDeleteFromOtherTab.has(e)||this.databaseStoreQueueToDeleteThisBatch?.has(e)}async findManyAsync(e,t=!0,a){if(!e?.length)return[];let i={reactive:!1,...a??{}};return await (0,O.runJob)(R.k1,"findManyAsync_"+e.length+"_"+this.collectionName,async()=>"Full"!=this.reactiveStoreLoadState?_.compact(await (0,w.Di)(e.map(e=>this.findOneAsync(e,i)))):t?_.compact(e.map(e=>this.findOne(e,i))):void 0)}findMany(e,t){return e?_.compact(e.map(e=>this.findOne(e,t))):[]}findManyAsyncReactive(e,t){return e?(this.findManyAsync(e,!1,t),this.findMany(e,t)):[]}_uniqueFastSessionIdentifier(){return this.collectionName+this.database.databaseName}async relookupDatabaseStore(){let e=(0,$.getOrCreateDatabaseForOwner)(this.owner);e&&(this.database=e),await this.constructDatabaseStores()}async constructDatabaseStores(){this.log("constructDatabaseStores"),this.DatabaseStore=await this.database.getClientDatabaseStore(this.collectionName),this.DatabaseDeletedStore=await this.database.getClientDatabaseStore(el(this.collectionName)),await this.getTinyGraphLinkerAsync()&&(this.MissingIdsDatabaseStore=await this.database.getClientDatabaseStore("missing_ids_"+this.collectionName)),this.hasConstructedDatabaseStores.set(!0)}async finishedLoadingFromDatabaseStore(e=!1){await (0,O.runJob)(R.lh,"finishedLoadingFromDatabaseStore."+this.collectionName+"."+this.owner,async t=>{await (0,T.f)(),this.log("Finished loading from database store"),e||(this.reactiveStoreLoadState="Full",this.hasLoadedReactiveStoreFlag.set(!0)),t("1"),await this.ensureLoadedSyncDataAndInitializedFlags(),t("2"),this.reactiveQueries.set(!0),!e&&this.finishedLoadingCallback&&this.finishedLoadingCallback(),this.hasInitialized.set(!0)})}setAllFlagsFromSyncData(){let e=this.syncDataInMemory,t=this.syncDataInDatabase;if(!e)throw Error("Can't call setAllFlagsFromSyncData before loading syncDataInMemory");if(!t)throw Error("Can't call setAllFlagsFromSyncData before loading syncDataInDatabase");this.isApplyingStagedChangesFlag.set(t.isApplyingStagedChanges||e.isApplyingStagedChanges),this.hasFinishedSyncingFirstSyncAndFlushedToDatabaseFlag.set(t?.lastServerFullBatchDoneTime>0&&(t?.finishedApplyingFirstChangeBatch===void 0||t?.finishedApplyingFirstChangeBatch===!0)||!this.enableSyncing)}getSyncDataInMemory(){return this.syncDataInMemory}getSyncDataInDatabase(){return this.syncDataInDatabase}log(){this.collectionName}find(e,t){return e||(e={}),t||(t={}),void 0==t.reactive&&(t.reactive=this.reactiveQueries.get()||!1),this.ReactiveStore.find(e,t)}findOne=(e,t)=>(t||(t={}),this.ReactiveStore.findOne(e,t));async findOneFromNumberIdAsync(e,t){if(!e)return;let a=this.findOneFromNumberId(e,t);if(a)return a;
4if(!this.numberIdsFetchedFromDatabaseStore.has(e)){this.activeFindOneFromNumberIdLookupCounts.set(e,(this.activeFindOneFromNumberIdLookupCounts.get(e)??0)+1);let a=new Promise((e,t)=>this.findOneFromNumberIdFromDatabaseStoreResolvers.push(e));this.findOneFromNumberIdDatabaseStoreQueue.push(e),this.startFindOneFromNumberIdTimer();try{return await a,this.findOneFromNumberId(e,t)}finally{let t=this.activeFindOneFromNumberIdLookupCounts.get(e)-1;0===t?this.activeFindOneFromNumberIdLookupCounts.delete(e):this.activeFindOneFromNumberIdLookupCounts.set(e,t)}}}findOneFromNumberId(e,t){if(e){if(!this.tinyGraphLinker)throw Error("Not supported without tglinker");return this.findOne({[Z.A.X_NUMBER_ID]:e},{...t,useIndex:Z.A.X_NUMBER_ID})}}findOneFromNumberIdAsyncReactive(e,t){if(e)return this.findOneFromNumberIdAsync(e,t),this.findOneFromNumberId(e,t)}async findManyFromNumberIdsAsync(e,t){if(!e?.length)return[];let a={reactive:!1,...t??{}};return await (0,O.runJob)(R.k1,"findManyFromNumberIdsAsync_"+e.length+"_"+this.collectionName,async()=>"Full"==this.reactiveStoreLoadState?_.compact(e.map(e=>this.findOneFromNumberId(e,a))):_.compact(await (0,w.Di)(e.map(e=>this.findOneFromNumberIdAsync(e,a)))))}findManyFromNumberIds(e,t){return e?_.compact(e.map(e=>this.findOneFromNumberId(e,t))):[]}findManyFromNumberIdsAsyncReactive(e,t){return e?(this.findManyFromNumberIdsAsync(e,t),this.findManyFromNumberIds(e,t)):[]}async findOneAsync(e,t){let a={reactive:!1,...t??{}};return await this._findOneAsync(e,a,this.findOne)}async _findOneAsync(e,t,a){if(e)if(this.useReactiveStore&&"Full"==this.reactiveStoreLoadState)return a(e,t);else{if(!this.useReactiveStore||"Full"==this.reactiveStoreLoadState)return await this.findOneFromDisk(e);let i=a(e,t);if(i)return i;if("string"!=typeof e)if("object"!=typeof e||_.isArray(e))return;else{let t=await this.DatabaseStore?.get(e);if(!t||this.isStagedForDeletion(t._id))return;return this.ensureCorrectOwner(t),await (await this.getTinyGraphLinkerAsync())?.onFindAllocateIdsAndEnsureIdsInCacheAndLoadOutgoingAndExistingIdsForDocs([t],"find","findOneAsync"),this.ReactiveStore?.upsert(t),(await this.getTinyGraphLinkerAsync())?.assertNodeHasLoadStatusAndInCache(t._id,Q.bK.Present),this.transformFunction(t)}{if(this.isStagedForDeletion(e)||this.idsFetchedFromDatabaseStore.has(e))return;this.activeFindOneLookupCounts.set(e,(this.activeFindOneLookupCounts.get(e)??0)+1),this.findOneDatabaseStoreQueue.push(e);let i=new Promise((e,t)=>this.findOneFromDatabaseStoreResolvers.push(e));this.startFindOneTimer();try{return await i,a(e,t)}finally{let t=this.activeFindOneLookupCounts.get(e)-1;0===t?this.activeFindOneLookupCounts.delete(e):this.activeFindOneLookupCounts.set(e,t)}}}}startFindOneTimer(){this.findOneDatabaseStoreQueueTimer||(this.findOneDatabaseStoreQueueTimer=setTimeout(this.processFindOneDatabaseStoreQueue))}startFindOneFromNumberIdTimer(){this.findOneFromNumberIdDatabaseStoreQueueTimer||(this.findOneFromNumberIdDatabaseStoreQueueTimer=setTimeout(this.processFindOneFromNumberIdDatabaseStoreQueue))}findOneAsyncReactive(e,t){if(!this.useReactiveStore)throw Error("Can only findOneAsyncReactive with useReactiveStore");let a=this.findOne(e,t);if(a)return a;this.isStagedForDeletion(e)||("string"==typeof e?(this.findOneDatabaseStoreQueue.push(e),this.startFindOneTimer()):this.findOneAsync(e,t))}async findOneFromDisk(e){if(e)try{let t=await this.DatabaseStore?.findOne(e);if(t)return this.transformFunction(this.ensureCorrectOwner(t))}catch(e){this.error(e)}}everyRawDoc(){return this.ReactiveStore.everyRawDoc()}findAllReactive(){return this.ReactiveStore.findAllReactive()}findAllNonReactive(){return this.ReactiveStore.findAllReactive()}numDocs(){return this.ReactiveStore.numDocs()}totalDocsToSync(){return this.syncModule.serverSyncModule.lastTotalDocsToSyncReactiveVar.get()}numDocsBeingSynced(){return this.syncModule.serverSyncModule.docsSyncedInCurrentBatchForDisplay.get()}async loadTinyGraph(e,t,a){if(await this.getTinyGraphLinkerAsync())return await (0,en.writeGuarantee)("loadTinyGraphClientCollection-"+this.owner+"-"+this.collectionName,{skipTinyGraphLoad:!0,skipWindowSyncBlock:!0},async i=>{let s=e=>{i(e),this.addPersistedCollectionLogIfAdmin("loadTinyGraph - "+e)};
4s("00"),await this.createdDatabaseStoreOrNotPersistentFlag.waitUntilTrue(),s("0A");let n=e=>{(0,ee.Ty)(a+e*t,"TinyGraph migration progress updated")},r=await this.getDatabaseStore({skipTinyGraphLoader:!0});if(s("0B"),await (0,T.f)(),e){let e=`migrated_ids-${this.collectionName}`;await (0,G.mX)(this.owner,e)!="true"&&await ea.tinyGraphInitializeIdsSharedLock.withLock(async()=>{await (0,G.mX)(this.owner,e)!="true"&&(s("0C"),h.Env.app.isPlaywright||n(.25),await (0,W.execQueries)(this.owner,[(0,er.l)` 5 DELETE FROM 6 missing_ids_quanta 7 `,(0,er.l)` 8 DELETE FROM 9 missing_ids_cards 10 `,(0,er.l)` 11 UPDATE ${er.l.raw(this.collectionName)} AS t 12 SET ${er.l.raw(Z.A.X_NUMBER_ID)} = numbered.rn 13 FROM ( 14 SELECT _id, ROW_NUMBER() OVER (ORDER BY _id) AS rn 15 FROM ${er.l.raw(this.collectionName)} 16 ) AS numbered 17 WHERE t._id = numbered._id 18 `,(0,er.l)` 19 INSERT INTO 20 tiny_graph_metadata 21 (key, value) 22 VALUES 23 ('${er.l.raw(e)}', 'true') 24 ON CONFLICT(key) DO UPDATE SET value=excluded.value 25 `]))})}s("0D");let o=await this.getTinyGraphLinkerAsync(),d=o.getLastFlushedTime(),c=0==d;!e&&c&&(0,ee.Tx)("show TinyGraph version upgrade migration page"),Q.R1&&console.log("Load after lastFlushedTime",this.collectionName,d),s("4");let l=e||c?[]:await (await this.getDeletedDatabaseStore({skipTinyGraphLoader:!0})).wherePropertyIsGreaterThan(Z.A.Y_LAST_LOCAL_TIME,d,!0,void 0,!0),u=l.filter(e=>e[Z.A.X_NUMBER_ID]);for(let e of u)o.ensureCapacityUpToNumberId(e[Z.A.X_NUMBER_ID]);let y=u.filter(e=>{let t=o.getNodeLoadStatus(e[Z.A.X_NUMBER_ID]);return t==Q.bK.Present||t==Q.bK.Missing});for(let e of y)o.storeIdInMemoryCache(e._id,e[Z.A.X_NUMBER_ID],Q.ak.FromDatabaseLoadOrUpdate,"load"),o.remove(e._id,e[Z.A.X_NUMBER_ID],{inInitialTinyGraphLoad:!0});s("4B");let S=e||c?await (0,W.execQuery)(this.owner,(0,er.l)` 26 SELECT _id, x FROM ${er.l.raw(this.collectionName)} 27 `):await (0,W.execQuery)(this.owner,(0,er.l)` 28 SELECT _id, x 29 FROM ${er.l.raw(this.collectionName)} 30 WHERE json_extract(doc, '$.${er.l.raw(Z.A.Y_LAST_LOCAL_TIME)}') >= ${d} 31 `);this.addPersistedCollectionLogIfAdmin("loadTinyGraph - 4C",{lastFlushedTime:d,knowledgeBaseId:this.owner,needToUpdateRawIds:S}),Y.Y.addPersistedLog("tinygraph_loading","loadTinyGraph",{lastFlushedTime:d,knowledgeBaseId:this.owner,needToUpdateRawIds:S}),s("4C");let g=S.filter(e=>!this.isStagedForDeletion(e._id));for(let t of(Q.R1&&console.log("loadTinyGraphA",this.collectionName,e,l.map(e=>e._id),y.map(e=>e._id),g.map(e=>e._id),{owner:this.owner,collectionName:this.collectionName,lastFlushedTime:d,needToRemove:l,needToRemoveWithNumbers:u,needToRemoveCurrentlyPresentOrMissing:y,needToUpdateIds:g}),s("2"),g))o.setNodeLoadStatus(t._id,t[Z.A.X_NUMBER_ID],Q.bK.Present);s("2A - Load TG in chunks");let m=0,D=_.chunk(g,1e4),p=D.length>1;for(let e of(p&&(0,ee.Tx)("show TinyGraph large load migration page"),D)){let t=await r.bulkGet(e.map(e=>e._id));for(let a of(Q.R1&&console.log("needToUpdateIdsChunk",e.length,t.length,m,D.length,this.owner),await o.onFindAllocateIdsAndEnsureIdsInCacheAndLoadOutgoingAndExistingIdsForDocs(t,"find","loadTinyGraph",{skipWaitForOtherWindows:!0,allowMutateWASMGraphSetIdsToMissingOnFirstLoad:!0,allowAllocateNumberIds:!0}),s("2B"),s("3A"),t))this.isStagedForDeletion(a._id)||o.upsert(a);console.log(m+=1),console.time("Wait"),await (0,T.f)(),console.timeEnd("Wait"),p&&n(.5+m/D.length/2),s("3B")}if(e){s("5A - Store TinyGraph");let e=this.tinyGraphLinker.tinyGraph;e.setLastFlushedTime(Date.now()),s("5B - Snapshot TinyGraph");let t=e.snapshot();s("5C - Store TinyGraph"),await e.store(t),s("5D - Store Backup TinyGraph"),await e.storeBackup(t),await e.storeBackup2(t),await e.storeBackup3(t)}return s("5"),!e&&(c||p)});throw Error("Can't load tinyGraph")}markTinyGraphFinishedLoading(){this.tinyGraphLoadedFlag.set(!0)}markTinyGraphPartialPhase1FromDBFinishedLoading(){this.tinyGraphPartialPhase1FromDBLoadedFlag.set(!0)}async forEveryRawDoc(e){this.useReactiveStore?this.ReactiveStore.forEveryRawDoc(e):(await this.DatabaseStore?.fetchAll().catch(this.error.bind(this))||[]).forEac
31h(t=>e(this.ensureCorrectOwner(t)))}findOneRaw=e=>this.ReactiveStore.docs.get(e);async findOneRawAsync(e){return await this._findOneAsync(e,{reactive:!1},this.findOneRaw)}async getTinyGraphAsync(){return await this.tinyGraphLoadedFlag.waitUntilTrue(),(await this.getTinyGraphLinkerAsync()).tinyGraph}getTinyGraphAsyncReactive(){if(this.tinyGraphLoadedFlag.getReactive())return this.tinyGraphLinker?.tinyGraph}getTinyGraphSyncOrThrow(){if(!this.tinyGraphLoadedFlag.triggered)throw Error(`TinyGraph not loaded yet ${this.owner}`);return this.tinyGraphLinker.tinyGraph}debugInsertedDocsCheck=new WeakSet;async insert(e,t,a=!0,i=!0,s=!1,n,r=!1){if(this.closed)throw console.trace("Trying to insert from closed collection",this.owner,e),Error("Trying to insert from closed collection");await this.tinyGraphLoadedFlag.waitUntilTrue(),await this.ensureLoadedSyncDataAndInitializedFlags();let d=await this.getBackgroundJobManager?.(),c=await this.getTinyGraphLinkerAsync();return await eg.waitUntilFalseThenSetTrue(),await (0,en.writeGuarantee)("insert",async()=>{let h=+!!e._id,l=e._id||this.ReactiveStore?._generateNewId()||(0,ei.c)(),u=void 0!=e._id;if(e._id=l,c){if(e[Z.A.X_NUMBER_ID])throw Error("Insert i shouldnt already have a number id");n?.forceSynchronous||(0==h?(c.debuggingLoadedOutgoingIdForDocsSet.add(l),await c.allocateOrLoadStringIdsAndEnsureInCache([{_id:l,debug:"onInsert"}],Q.bK.Present,"mutate",{allowMutateWASMGraphSetIdsToMissingOnFirstLoad:!0,allowAllocateNumberIds:!0,dontCheckForExistingIds:!0})):await c.allocateNumberIdsAndLoadOutgoingIDsForDocsOrChanges([l],[(0,F.EJ)(e)],Q.bK.Present,"mutate",{allowAllocateNumberIds:!0,...n||{}}))}return await (0,en.writeGuarantee)("insertInner",()=>{let c=new Date().getTime(),{filteredChanges:h}=(0,V.u)(void 0,e,!1,c,this.schema,!1,this.isNotDoingFirstSync(),!s&&!r);if(this.isNotDoingFirstSync()&&(h[Z.A.O_LAST_LOCAL_TIME_NOT_FIRST_SYNC]=c),h[Z.A.Y_LAST_LOCAL_TIME]=c,h._id=l,this.tinyGraphLinker){let t=this.tinyGraphLinker?.upsert(h);e[Z.A.X_NUMBER_ID]=t,h[Z.A.X_NUMBER_ID]=t}i&&(h[Z.A.M_CREATION_OR_LAST_UNDELETE_TIME]=c,h[Z.A.U_LAST_UPDATE_TIME]=c,!s&&this.enableSyncing&&(h[Z.A.P_LOCAL_EDIT_NEED_TO_SEND_TO_SERVER]=c)),this.ReactiveStore?.upsert(h);let y=this.ReactiveStore?this.ReactiveStore.findOne(l):h;y[Z.A.Z_DERIVED_FIELD_VERSIONS]=3,y.owner=this.owner;let S=d?.createSnapshotStubsBeforeRemChange(l,this.owner,null,y,void 0,void 0,!0);if(B.TabSyncedSession.savingToDatabase.set("insert"),em(this.databaseStoreQueueToUpsert,this.databaseStoreChangedFieldsToUpsert,l),this.broadcastQueueToUpsert.add(l),this.databaseStoreQueueToDeleteFromOtherTab.delete(l),this.databaseStoreQueueToDelete.delete(l),this.broadcastQueueToDelete.delete(l),this.deletedDocToTimestamp.delete(l),(0,x.getDatabaseCache)().startDatabaseStoreTimer(),u&&a&&this.syncModule.serverSyncModule?.undeleteItem(l),window.runConsumersNextTime(this.owner,this.collectionName),d?.finishConstructingJobInstances(this.owner,S,l,this.findOne(l)),n?.dontAddToUndoRedo||o.Sx(this,l,y),t&&(this.useReactiveStore?t(this.findOne(l)):t(this.transformFunction(y))),!s&&this.enableSyncing&&this.syncModule.serverSyncModule.recordUpdateId(l),this.updateHaveUnsyncedInformationLazyReactive(),!this.useReactiveStore)return void eg.set(!1);{let e=this.findOne(l);if(e&&void 0===e.owner)throw console.trace("Invalid undefined owner",e.owner,e._id,l,e),Error("Invalid undefined owner");return eg.set(!1),e}})})}async remove(e,t=!1,a){if(_.isObject(e)||!e)return void console.error("Error: Can only remove by ID");await this.tinyGraphLoadedFlag.waitUntilTrue(),await this.ensureLoadedSyncDataAndInitializedFlags(),Q.R1;let i=await this.getBackgroundJobManager?.(),s=await this.findOneRawAsync(e),n=await this.getTinyGraphLinkerAsync();if(s)return await eg.waitUntilFalseThenSetTrue(),await (0,en.writeGuarantee)("remove",()=>{this.debugInsertedDocsCheck.delete(s);let r=_.clone(s),d=new Date().getTime(),c=r?.[Z.A.X_NUMBER_ID],h=i?.createSnapshotStubsBeforeRemChange(e,this.owner,s?this.transformFunction(s):null,null,void 0,void 0,!0);if(s&&delete s[Z.A.X_NUMBER_ID],c&&n?.remove(e,c),!s||t||a?.dontAddToUndoRedo||o.Hg(this,e,s),r&&(t||(r[Z.A.U_LAST_UPDATE_TIME]=d),!t&&this.enableSyncing&&(r[Z.A.P_LOCAL_EDIT_NEED_TO_SEND_TO_SERVER]=d),this.isNotDoingFirstSync()&&(r[Z.A.O_LAST_LOCAL_TIME_NOT_FIRST_SYNC]=d),r[Z.A.Y_LAST_LOCAL_TIME]=d),B.TabSyncedSession.savingToDatabase.set("remove"),!r?.x&&this.tinyGraphLinker)throw console.error("MissingnumberId for "+e,r,s),Error("MissingnumberId for "+e);this.databaseStoreQueueToDelete.set(e,r),this.broadcastQueueToDelete.set(e,r),this.databaseStoreQueueToUpsert.delete(e),this.databaseStoreChangedFieldsToUpsert.delete(e),this.broadcastQueueToUpsert.delete(e),this.databaseStoreQueueToUpsertFromOtherTab.delete(e),this.deletedDocToTimestamp.set(e,d),(0,x.getDatabaseCache)().startDatabaseStoreTimer(),this.useReactiveStore&&this.ReactiveStore.remove(e,e=>{e&&this.error(e)}),window.runConsumersNextTime(this.owner,this.collectionName,"remove"),i?.finishConstructingJobInstances(this.owner,h,e,null),t||this.syncModule?.serverSyncModule.deleteItem(r||{_id:e}),eg.set(!1)})}async updateLinkersInTinyGraph(e){let t=await this.getTinyGraphLinkerAsync(),a=this.findOne(e);a&&t?.update(e,a)}async update(e,t,a=!0,i){if(this.closed)throw console.trace("Trying to update from closed collection"),Error("Trying to update from closed collection");if(_.isObject(e))return void console.error("Error: Can only update by ID");if(!t.$set)return void console.error("Error: Can only $set");
31await this.tinyGraphLoadedFlag.waitUntilTrue(),await this.ensureLoadedSyncDataAndInitializedFlags();let s=await this.getBackgroundJobManager?.(),n=await this.getTinyGraphLinkerAsync();await eg.waitUntilFalseThenSetTrue();let r="knowledgebase_local_stored_data"==this.collectionName||"user_data"==this.collectionName?t.key??this.key:"";return await (0,en.writeGuarantee)(`update.${this.collectionName}.${e}.${r}`,async()=>{let r=this.useReactiveStore?this.findOne(e)||("Full"!=this.reactiveStoreLoadState?await this.findOneAsync(e,void 0):void 0):await this.findOneAsync(e,void 0);i?.forceSynchronous||await n?.allocateNumberIdsAndLoadOutgoingIDsForDocsOrChanges([e],[(0,F.EJ)(t.$set)],Q.bK.Missing,"mutate",{allowAllocateNumberIds:!0,...i||{}});{let d=new Date().getTime();if(r&&!this.isStagedForDeletion(e)){let{filteredChanges:c,filteredChangesWithoutDerivedFields:h,madeChangeToFieldNotFromServer:l,madeChangeToNonDerivedField:u}=(0,V.u)(r,t.$set,a,d,this.schema,!0,this.isNotDoingFirstSync(),!1);a&&l&&(c[Z.A.U_LAST_UPDATE_TIME]=d,u&&(this.enableSyncing&&(c[Z.A.P_LOCAL_EDIT_NEED_TO_SEND_TO_SERVER]=d,this.syncModule.serverSyncModule.recordUpdateId(e)),!r||o.lP()||i?.dontAddToUndoRedo||this._notifyUndoRedoOfUpdateChange(h,r,e))),!a&&t.$set[Z.A.U_LAST_UPDATE_TIME]&&(c[Z.A.U_LAST_UPDATE_TIME]=t.$set[Z.A.U_LAST_UPDATE_TIME]),this.isNotDoingFirstSync()&&(c[Z.A.O_LAST_LOCAL_TIME_NOT_FIRST_SYNC]=d),c[Z.A.Y_LAST_LOCAL_TIME]=d;let y=s?.createSnapshotStubsBeforeRemChange(e,this.owner,r,c,void 0,void 0,!0);this.ReactiveStore.update(e,{$set:c}),window.runConsumersNextTime(this.owner,this.collectionName,"update"+e);let S=this.findOne(e);S&&n?.update(e,S),s?.finishConstructingJobInstances(this.owner,y,e,S),B.TabSyncedSession.savingToDatabase.set("update"),em(this.databaseStoreQueueToUpsert,this.databaseStoreChangedFieldsToUpsert,e,Object.keys(c)),this.broadcastQueueToUpsert.add(e),this.databaseStoreQueueToDelete.delete(e),this.broadcastQueueToDelete.delete(e),this.databaseStoreQueueToDeleteFromOtherTab.delete(e),this.deletedDocToTimestamp.delete(e),(0,x.getDatabaseCache)().startDatabaseStoreTimer(),this.updateHaveUnsyncedInformationLazyReactive(),l&&a&&this.triggerSyncOnEdit()}}eg.set(!1)})}_notifyUndoRedoOfUpdateChange(e,t,a){let i=_.keys(e),s={};for(let e of i)s[e]=(0,F.p)(t,e)||null;let n=(0,N.$)(),r=n?.remId===a?n.focusId:void 0;n?.remId===a&&(0,N.r)(void 0),o.AU(this,a,s,e,r)}setSyncDataFromServerSync(e,t){if(!this.initializedSyncDataFlag.triggered)throw Error("Tried making sync data change before loaded from DB.");this._setSyncData(e),this.mustFlushNewSyncData||=t}setSyncDataFromWindowSync(e,t){if(!this.initializedSyncDataFlag.triggered)throw Error("Tried making sync data change before loaded from DB.");if(!t||!e)throw Error("Tried setting setSyncDataFromWindowSync to undefined");(0,U.D)(this.collectionName,this.owner,"setSyncDataFromWindowSync",{syncDataInMemory:e}),this.syncDataInMemory=e,this.syncDataInDatabase=t,this.syncDataDep.changed(),this.setAllFlagsFromSyncData()}async getNumStagedUpdates(){return await this.syncModule.serverSyncModule.getNumberStagedUpdatesStored()}_setSyncData(e,t=!1){if("number"!=typeof e.lastServerTime)throw console.error("Invalid lastServerTime",e),Error(`Invalid lastServerTime ${e.lastServerTime}`);if(!t){if(!this.syncDataInMemory)throw Error("Setting without syncDataInMemory");if(this.syncDataInMemory.lastServerTime>e.lastServerTime)throw console.error("Last server time cannot decrease ",this.syncDataInMemory,e),Error("Last server time cannot decrease "+this.syncDataInMemory.lastServerTime+" "+e.lastServerTime);if(this.syncDataInMemory.lastSync>e.lastSync)throw console.error("Last sync time cannot decrease",this.syncDataInMemory,e),Error("Last sync time cannot decrease "+this.syncDataInMemory.lastSync+" "+e.lastSync)}!_.isEqual(e,this.syncDataInMemory)&&((0,U.D)(this.collectionName,this.owner,"setSyncData",{syncData:e}),this.syncDataInMemory=e,this.syncDataDep.changed(),this.setAllFlagsFromSyncData(),b.MX&&(0,en.writeGuarantee)("triggerSendUpdatesToOtherTabs",()=>{this.syncModule.windowSyncModule.setNeedToBroadcastSyncDataToTrue()}))}async loadDocsToSync(){if(!b.MX)throw Error("Only loadDocsToSync
31in worker.");this.enableSyncing&&await (0,O.runJob)(R.k1,"loadDocsToSync_"+this.owner+"_"+this.collectionName,async e=>{e("1"),await this.database.initializedDatabaseStoreFlag.waitUntilTrue(),e("2");let t=await this.ensureLoadedSyncDataAndInitializedFlags();e("3");let a=await (await this.getDatabaseStore()).wherePropertyIsGreaterThan(Z.A.P_LOCAL_EDIT_NEED_TO_SEND_TO_SERVER,t.lastSync,!!t.lastSyncPaginationId,void 0,!0);for(let t of(e("4"),this.log("Need to send",a),a?.map(e=>e._id)))this.syncModule.serverSyncModule.updatesForServerIds.add(t),this.syncModule.serverSyncModule.undeleteItem(t);e("5");let i=await (await this.getDeletedDatabaseStore())?.wherePropertyIsGreaterThan(Z.A.P_LOCAL_EDIT_NEED_TO_SEND_TO_SERVER,t.lastSync,!!t.lastSyncPaginationId,void 0,!0);for(let t of(e("6"),i))this.syncModule.serverSyncModule.deleteItem(t);(0,U.D)(this.collectionName,this.owner,"loadDocsToSync",{size:this.syncModule.serverSyncModule.updatesForServerIds.size,firstThirtyIds:[...this.syncModule.serverSyncModule.updatesForServerIds].slice(0,30),lastSync:t.lastSync})}),this.hasFetchedFirstSyncDocs.set(!0)}receivedSyncUpdateListeners;announceReceivedSyncUpdate(e){this.receivedSyncUpdateListeners.dispatchEvent(e)}addReceivedSyncUpdateListener(e){this.receivedSyncUpdateListeners.addListener(e)}removeReceivedSyncUpdateListener(e){this.receivedSyncUpdateListeners.removeListener(e)}_stillSavingToDatabaseStore(){return this.numItemsToSave()>0}didFetchId(e){return this.idsFetchedFromDatabaseStore.has(e)}numItemsToSave(){return this.databaseStoreQueueToUpsert.size+this.databaseStoreQueueToUpsertFromOtherTab.size+this.databaseStoreQueueToDelete.size+this.databaseStoreQueueToDeleteFromOtherTab.size+ +!!this.syncModule.serverSyncModule.getStagedChangeToStore()+this.syncModule.serverSyncModule.stagedChangeProgressToStore.size+(this.tinyGraphLinker?.numItemsToSave()||0)+ +!!this.mustFlushNewSyncData}numItemsToSaveThisBatch(){return(this.databaseStoreQueueToUpsertThisBatch?.ids.length||0)+(this.databaseStoreQueueToDeleteThisBatch?.size||0)+ +!!this.syncModule.serverSyncModule.getStagedChangeToStore()+(this.syncModule.serverSyncModule.stagedChangeProgressToStoreThisBatch?.size??0)+(this.tinyGraphLinker?.numItemsToSaveThisBatch()||0)+ +!!this.syncDataToStoreThisBatch}static onRemDocsLoadedFromDatabaseHook;static setOnRemDocsLoadedFromDatabaseHook(e){eD.onRemDocsLoadedFromDatabaseHook=e}notifyRemDocsLoadedFromDatabase(e){"quanta"===this.collectionName&&this.hasDatabaseStore&&e.length>0&&eD.onRemDocsLoadedFromDatabaseHook?.(this.owner,e)}processFindOneDatabaseStoreQueue=async()=>{let e=this.findOneDatabaseStoreQueue,t=this.findOneFromDatabaseStoreResolvers;this.findOneFromDatabaseStoreResolvers=[],this.findOneDatabaseStoreQueue=[],this.findOneDatabaseStoreQueueTimer=void 0,e.length>0&&await (0,O.runJob)(R.k1,"processFindOneDatabaseStoreQueue_"+e.length,async a=>{a("1"),await this.database.initializedDatabaseStoreFlag.waitUntilTrue(),a("2");try{let i=(0,g.sb)(e);ep+=1,a("3 Get from DB");let s=await this.DatabaseStore?.bulkGet(i);if(a("4 Load into Collection"),s){let e=s.filter(e=>!this.isStagedForDeletion(e._id));await this.ensureDocsExistFromQuery(e,"processFindOneDatabaseStoreQueue"),this.notifyRemDocsLoadedFromDatabase(e)}for(let e of(a("5"),Q.M$&&console.trace("[LOG_LOOKUP_REMS] LookupRems",this.collectionName,i,s),i))this.idsFetchedFromDatabaseStore.add(e);for(let e of t)e();this.findOneDatabaseStoreQueue.length>0&&this.startFindOneTimer(),a("6")}catch(e){this.error(e),console.error("Bulk get error"),console.error(e),console.error(e.stack)}})};processFindOneFromNumberIdDatabaseStoreQueue=async()=>{let e=this.findOneFromNumberIdDatabaseStoreQueue,t=this.findOneFromNumberIdFromDatabaseStoreResolvers;this.findOneFromNumberIdFromDatabaseStoreResolvers=[],this.findOneFromNumberIdDatabaseStoreQueue=[],this.findOneFromNumberIdDatabaseStoreQueueTimer=void 0,e.length>0&&await (0,O.runJob)(R.k1,"processFindOneFromNumberIdDatabaseStoreQueue",async a=>{a("1"),await this.database.initializedDatabaseStoreFlag.waitUntilTrue(),a("2");try{let i=(0,g.sb)(e);ep+=1,a("3 Get from DB");let s=await this.DatabaseStore?.bulkGetFromNumberIds(i);if(a("4 Load into Collection"),Q.M$&&console.trace("[LOG_LOOKUP_REMS] LookupRemsFromNumberIds",this.collectionName,i,s),s){let e=s.filter(e=>
31!this.isStagedForDeletion(e._id));await this.ensureDocsExistFromQuery(e,"processFindOneFromNumberIdDatabaseStoreQueue"),this.notifyRemDocsLoadedFromDatabase(e)}for(let e of(a("5"),i))this.numberIdsFetchedFromDatabaseStore.add(e);for(let e of t)e();this.findOneFromNumberIdDatabaseStoreQueue.length>0&&this.startFindOneFromNumberIdTimer(),a("6")}catch(e){this.error(e),console.error("Bulk get error"),console.error(e),console.error(e.stack)}})};async ensureDocsExistFromQuery(e,t,a=!1){await (0,O.runJob)(R.k1,"ensureDocsExistFromQuery."+a+"."+t,async a=>{a("1"),await this.tinyGraphLoadedFlag.waitUntilTrue(),a("1B");let i=await this.getTinyGraphLinkerAsync();a("2"),a("3");let s=e.filter(e=>!this.isStagedForDeletion(e._id)&&!this.ReactiveStore.findOneRaw(e._id));if(a("3A"),await i?.onFindAllocateIdsAndEnsureIdsInCacheAndLoadOutgoingAndExistingIdsForDocs(s,"find","ensureDocsExistFromQuery."+t),a("4"),this.ReactiveStore.ensureDocsExist(s.filter(e=>!this.isStagedForDeletion(e._id)).map(this.ensureCorrectOwner)),i)for(let e of s)this.isStagedForDeletion(e._id)||i.storeIdInMemoryCache(e._id,e[Z.A.X_NUMBER_ID],Q.ak.FromDatabaseLoadOrUpdate,"query")})}ensureCorrectOwner=e=>(e&&(e.owner=this.database.owner),e);upsertDocsFromOtherWindow(e){for(let t of(Q.R1&&console.log("upsertDocsFromOtherWindow",e.map(e=>e._id),e),e))this.ReactiveStore?.upsert(t),this.tinyGraphLinker?.upsert(t),this.tinyGraphLinker?.assertNodeHasLoadStatusAndInCache(t._id,Q.bK.Present),this.syncModule.serverSyncModule.recordUpdateId(t._id),this.syncModule.serverSyncModule.undeleteItem(t._id),this.databaseStoreQueueToUpsertFromOtherTab.add(t._id),this.databaseStoreChangedFieldsToUpsert.delete(t._id),this.deletedDocToTimestamp.delete(t._id),"quanta"!=this.collectionName||h.Env.isWorker||a.g.triggerExternalTextUpdateVersionIfNotSelected(t)}removeDocsFromOtherWindow(e){for(let t of e){if(this.syncModule.serverSyncModule.deleteItem(t),this.databaseStoreQueueToDeleteFromOtherTab.set(t._id,t),!t?._id)throw Error("Received deleted doc without Id");this.ReactiveStore?.remove(t._id);let e=this.tinyGraphLinker?.getNodeLoadStatus(t[Z.A.X_NUMBER_ID]);Q.R1&&console.log("removeRem deletedDoc",t._id,t.x,t,e),(e==Q.bK.Present||e==Q.bK.Missing)&&this.tinyGraphLinker?.remove(t._id,t[Z.A.X_NUMBER_ID],{fromOtherWindow:!0})}}deleteDocsOnTakeWriteLock(e){for(let t of e)this.ReactiveStore?.remove(t._id)}_prepFlushToDatabaseStore(){if(!b.MX)throw Error("_prepFlushToDatabaseStore only in worker");if(this.databaseStoreQueueToUpsertThisBatch)throw Error("this.databaseStoreQueueToUpsertThisBatch already has a value");if(!this.tinyGraphLinker&&this.constructTinyGraphLinker)throw Error("tinyGraphLinker not constructed, cannot prep save");this.tinyGraphLinker?.prepFlushToDatabaseStore(),this.syncModule.serverSyncModule.prepStagedChangeProgressToStore();let e=(0,g.sb)([...this.databaseStoreQueueToUpsert,...this.databaseStoreQueueToUpsertFromOtherTab]),t=_.compact(e.map(e=>this.findOneRaw(e))),a=new Map;for(let e of t)if(!this.databaseStoreQueueToUpsertFromOtherTab.has(e._id
31)){let t=this.databaseStoreChangedFieldsToUpsert.get(e._id);t&&a.set(e._id,[...t])}if(!this.DatabaseStore)throw Error("No DatabaseStore");let i=this.DatabaseStore.builder.bulkPut(t,{changedFieldsById:a});for(let[a,s]of(this.databaseStoreQueueToUpsertThisBatch={ids:t.map(e=>e._id),query:"dexie"===i.type?this.DatabaseStore.builder.bulkPut(t.map(e=>JSON.parse(JSON.stringify(e)))):i},Q.rT&&console.log("Prep flush",e,this.databaseStoreQueueToUpsertThisBatch.ids),this.databaseStoreQueueToDeleteThisBatch=new Map(this.databaseStoreQueueToDelete),this.databaseStoreQueueToDeleteFromOtherTab.entries()))this.databaseStoreQueueToDeleteThisBatch.set(a,s);this.mustFlushNewSyncData&&b.MX&&(this.syncDataToStoreThisBatch=_.clone(this.syncDataInMemory)),this.databaseStoreQueueToDelete.clear(),this.databaseStoreQueueToDeleteFromOtherTab.clear(),this.databaseStoreQueueToUpsert.clear(),this.databaseStoreChangedFieldsToUpsert.clear(),this.databaseStoreQueueToUpsertFromOtherTab.clear(),this.mustFlushNewSyncData=!1}_flushToDatabaseStore(e,t,a){if(!b.MX)throw Error("_prepFlushToDatabaseStore only in worker");let i=[...this.databaseStoreQueueToDeleteThisBatch?.keys()||[]];if(!this.DatabaseStore)throw Error("No DatabaseStore");if(!this.DatabaseDeletedStore){let e=`No DatabaseDeletedStore ${this.owner} ${this.collectionName}`;throw console.log(e),Error(e)}let s=this.DatabaseStore.builder,n=this.DatabaseDeletedStore.builder;if(this.databaseStoreQueueToDeleteThisBatch?.size>0){let e=this.storeDeletedDocuments?[...this.databaseStoreQueueToDeleteThisBatch.values()].filter(e=>e&&this.isStagedForDeletion(e._id)).map(e=>_.extend(e,{deletedAt:t})):[];this.storeDeletedDocuments&&a.addQuery(n.bulkPut(e)),a.addQuery(s.bulkDelete(i))}if(Q.rT&&console.log("_flushToDatabaseStore",this.collectionName,this.databaseStoreQueueToUpsertThisBatch?.ids),this.ReactiveStore){let e=this.databaseStoreQueueToUpsertThisBatch,t=e?.ids??[];e&&a.addQuery(e.query),a.addQuery(n.bulkDelete(t))}let r=this.syncModule.serverSyncModule.getStagedChangesCollectionName(),o=new Set(this.syncModule.serverSyncModule.stagedChangeIdsToRemove);for(let[e,t]of this.syncModule.serverSyncModule.stagedChangeProgressToStoreThisBatch??[])o.has(e)||a.addQuery((0,J.J)([(0,er.l)`UPDATE ${er.l.raw(r)} SET applied_source_pages = ${t} WHERE _id = ${e}`]));for(let e of _.chunk(this.syncModule.serverSyncModule.stagedChangeIdsToRemove,999))a.addQuery((0,J.J)([(0,er.l)`DELETE FROM ${er.l.raw(r)} WHERE _id IN (${er.l.join(e,", ")})`]));this.syncModule.serverSyncModule.stagedChangeIdsToRemove=[];let d=this.syncModule.serverSyncModule.getStagedChangeToStore();if(d&&(a.addQuery((0,J.J)([(0,er.l)`INSERT INTO ${er.l.raw(r)} (_id, time, changes, num_updates) VALUES (${""+Math.random()}, ${Date.now()}, ${JSON.stringify(d)}, ${d.updateDifs.length})`])),this.syncModule.serverSyncModule.clearStagedChangeToStore()),this.ReactiveStore&&(this.runConsumersAfterFlush=(this.databaseStoreQueueToUpsertThisBatch?.ids.length??0)>0||(this.databaseStoreQueueToDeleteThisBatch?.size??0)>0),!this.tinyGraphLinker&&this.constructTinyGraphLinker)throw Error("tinyGraphLinker not constructed, cannot save");this.tinyGraphLinker?.flushToDatabaseStore(a),this.syncDataToStoreThisBatch&&b.MX&&(a.addQuery(e.builder.update({_id:this.collectionName,newVal:this.syncDataToStoreThisBatch})),this.nextDatabaseSyncData=this.syncDataToStoreThisBatch,this.syncDataToStoreThisBatch=void 0)}_afterFlushToDatabaseStore(){this.nextDatabaseSyncData&&b.MX&&(_.isEqual(this.nextDatabaseSyncData,this.syncDataInDatabase)||(this.syncDataInDatabase=this.nextDatabaseSyncData,this.setAllFlagsFromSyncData(),(0,en.writeGuarantee)("triggerSendUpdatesToOtherTabs",()=>{this.syncModule.windowSyncModule.setNeedToBroadcastSyncDataToTrue()})),this.nextDatabaseSyncData=void 0)}cleanupDatabaseStoreQueueAfterTransactionCommits(){this.databaseStoreQueueToUpsertThisBatch=void 0,this.databaseStoreQueueToDeleteThisBatch=void 0,this.syncModule.serverSyncModule.cleanupStagedChangeProgressAfterTransactionCommits(),this.runConsumersAfterFlush&&window.runConsumersNextTime(this.owner,this.collectionName)}isNotDoingFirstSync(){if(!this.enableSyncing)return!0;
31if(this.enableSyncing&&!this.syncDataInMemory)throw Error("Must load sync data first");let e=this.syncDataInMemory;return e.lastServerFullBatchDoneTime>0&&e.finishedApplyingFirstChangeBatch||c.zM}isDoingFirstLoginForDisplay(){return this.syncDataDep.depend(),!c.zM&&(this.syncDataInDatabase?.lastServerFullBatchDoneTime==0||this.syncDataInDatabase?.finishedApplyingFirstChangeBatch===!1)&&this.enableSyncing}async getSyncData(){return this.database.deleted||!this.hasDatabaseStore?{}:(await this.ensureLoadedSyncDataAndInitializedFlags(),this.log("getSyncData",this.syncDataInMemory),this.syncDataInMemory)}async ensureLoadedSyncDataAndInitializedFlags(){return this.initializedSyncDataFlag.triggered||await this.isInitializingSyncDataFlag.withLock(async()=>{if(!this.initializedSyncDataFlag.triggered){let e=await this._loadSyncData();if("number"!=typeof e.lastServerTime)throw console.error("Invalid lastServerTime on load from DB",e),Error(`Invalid lastServerTime on load from DB ${e.lastServerTime}`);this.syncDataInDatabase=e,this._setSyncData(e,!0),this.addPersistedCollectionLogIfAdmin("ensureLoadedSyncDataAndInitializedFlags Done"),this.initializedSyncDataFlag.set(!0)}}),this.syncDataInMemory}addPersistedCollectionLogIfAdmin(e,t){(0,P.X1)()&&Y.Y.addPersistedLog("collection_"+this.owner+"_"+this.collectionName,e,t)}async _loadSyncData(){return await this.database.initializedDatabaseStoreFlag.waitUntilTrue(),this.log("_loadSyncData",this.syncDataInMemory),await (0,O.runJob)(R.k1,"_loadSyncData",async()=>{let e="loadSyncData"+this.collectionName+this.database.databaseName;await (0,f.TL)(e);let t=await this.database.getSyncStoreOrThrow().findOne(this.collectionName).catch(this.error.bind(this));if(t)return this.setLastSyncedTime(t.lastSync),this.setLastServerTime(t.lastServerTime),(0,f.Wo)(e),t;{let t=await this.database.deprecatedSyncStore?.wherePropertyEquals("collectionName",this.collectionName)||[],a={_id:this.collectionName,lastSync:t.length>0?_.max(t.map(e=>e.lastSync)):0,lastSyncPaginationId:void 0,lastSyncFullBatchDoneTime:0,lastServerTime:t.length>0?_.max(t.map(e=>e.lastServerTime)):0,lastServerFullBatchDoneTime:0,lastServerPaginationId:void 0,minDeletedDocsTime:t.length>0?_.max(t.map(e=>e.minDeletedDocsTime)):new Date().getTime(),lastServerBatchFull:!(t.length>0)||_.any(t.map(e=>e.inMiddleOfSyncBatch)),isApplyingStagedChanges:!1,hasStagedChangesToApply:!1,finishedApplyingFirstChangeBatch:!1,lastSyncRemnoteVersion:L.Mg};return await this.database.getSyncStoreOrThrow().upsert(a).catch(this.error.bind(this)),(0,f.Wo)(e),a}})}getSyncProgress(){return B.TabSyncedSession.syncProgress(this._uniqueFastSessionIdentifier()).get()}lastSyncedTime(){return B.TabSyncedSession.lastSyncedTime(this._uniqueFastSessionIdentifier()).get()}lastServerTime(){return B.TabSyncedSession.lastServerTime(this._uniqueFastSessionIdentifier()).get()}getSyncingStatus(){return B.TabSyncedSession.syncingStatus(this._uniqueFastSessionIdentifier()).get()}_haveUnsyncedInformation(){return this.userVisibleNumberOfUnsyncedDocuments()>0||!this.hasFetchedFirstSyncDocs?.triggered}userVisibleNumberOfUnsyncedDocuments(){if(!b.MX)throw Error("Only userVisibleNumberOfUnsyncedDocuments in the IS_HEAVY_JOB_WORKER");return this.enableSyncing?this.syncModule.serverSyncModule.updatesForServerIds.size+_.keys(this.syncModule.serverSyncModule.deletedDocsForServerDict).length:0}async userVisibleNumberOfUnsyncedDocumentsAsync(){return b.MX?this.userVisibleNumberOfUnsyncedDocuments():(await (0,y.N)()).userVisibleNumberOfUnsyncedDocumentsAsync(this.owner,this.collectionName)}async updatesDownloadedInLast5Minutes(){return b.MX?this.syncModule.serverSyncModule.updatesDownloadedInLast5Minutes():(await (0,y.N)()).updatesDownloadedInLast5Minutes(this.owner,this.collectionName)}syncBackoffExponentTimeForDisplay(){return this.syncModule.serverSyncModule.syncBackoffExponentTimeForDisplay()}haveUnsyncedInformationLazyReactive(){return!!B.TabSyncedSession.haveUnsyncedInformation(this._uniqueFastSessionIdentifier()).get()||!this.hasFetchedFirstSyncDocs?.getReactive()}updateHaveUnsyncedInformationLazyReactive(){if(b.MX){let e=this.syncModule.serverSyncModule.updatesForServerIds.size>0;e!=this.haveUnsyncedInformationLazyReactiveBool&&(B.TabSyncedSession.haveUnsyncedInformation(this._uniqueFastSessionIdentifier()).set(e),this.haveUnsyncedInformationLazyReactiveBool=e)}}setSyncProgress(e){b.MX&&B.TabSyncedSession.syncProgress(this._uniqueFastSessionIdentifier()).set(e)}setSyncingStatus(e){let t=B.TabSyncedSession.syncingStatus(this._uniqueFastSessionIdentifier()),a=`${this.collectionName} - ${this.database.databaseName} - ${t.get()}`,i=new Date().getTime();a in ey||(ey[a]=0),eS[a]&&(ey[a]+=i-eS[a]),ea.ENABLE_SYNC_LOGGING&&console.log("Sync status",this.collectionName,e),t.set(e),eS[`${this.collectionName} - ${this.database.databaseName} - ${e}`]=i,(0,P.X1)()&&(0,U.D)(this.collectionName,this.owner,"setSyncingStatus: "+e,{})}setLastSyncedTime(e){b.MX&&B.TabSyncedSession.lastSyncedTime(this._uniqueFastSessionIdentifier()).set(e)}setLastServerTime(e){b.MX&&B.TabSyncedSession.lastServerTime(this._uniqueFastSessionIdentifier()).set(e)}async deleteEverythingFromSyncedCollection(e=!1){if(!this.hasDatabaseStore)throw Error("Cannot deleteEverythingFromSyncedCollection if DatabaseStore is disabled");
31await this.waitUntilFinishedFirstLoginSyncAndNotApplyingStagedChanges(!1);let t=await this.DatabaseStore?.primaryKeys()||[];await (0,en.writeGuarantee)("deleteEverythingFromSyncedCollection",{pauseUndoRedo:!0},async()=>{for(let e=0;e<t.length;e+=1e3){let a=t.slice(e,e+1e3);for(let e of(await this.findManyAsync(a,!1),a))await this.remove(e)}}),await this.deleteEverythingLocally(!0,e)}async deleteEverythingLocally(e=!0,t=!0){e&&await this.DatabaseStore?.clear().catch(this.error.bind(this)),t&&await this.DatabaseDeletedStore?.clear().catch(this.error.bind(this)),this.ReactiveStore?.clear()}error(...e){if("Key already exists in the object store."==e[0].message)(0,P.$S)()&&r.toast.warn("Ignore Key already exists in the object store.");else throw console.trace("DatabaseStore Error"),console.error(...e),(0,j.setDatabaseError)(e[0].message),(0,P.$S)()&&r.toast.error(e.map(e=>""+e).join(" ")),this?.log("Database Store Error!",e),e}serverError(...e){this.log("Server Error",e[0]?.message),e[0]?.message!="Request failed with status code 500"&&(console.error("Server Error"),console.error(...e))}toastError(e){r.toast.error(e)}toastErrorDebounced=_.debounce(this.toastError.bind(this),5e3,!0);async findDeletedDocsBetweenTimestamps(e,t){if(!this.hasDatabaseStore)throw Error("Cannot findDeletedDocsBetweenTimestamps if IndexedDB is disabled");return await (await this.getDeletedDatabaseStore()).wherePropertyIsBetween(Z.A.P_LOCAL_EDIT_NEED_TO_SEND_TO_SERVER,e,t,!1,!0)}isInLazyLoadState(){return this.inLazyLoadStateReactiveVar.get()}onLoginFromGuestMode(){this.reactiveQueries.set(!1),this.setSyncProgress(0)}async waitUntilFinishedFirstLoginSyncAndNotApplyingStagedChanges(e){await this.waitUntilFinishedFirstSync(e),this.isApplyingStagedChangesFlag.getReactive()&&await this.isApplyingStagedChangesFlag.waitUntilFalse()}async waitUntilFinishedFirstSync(e){!e&&c.zM||this.hasFinishedSyncingFirstSyncAndFlushedToDatabaseFlag.getReactive()||(this.database.syncAll(!0,"waitUntilFinishedFirstLoginSync"),await this.hasFinishedSyncingFirstSyncAndFlushedToDatabaseFlag.waitUntilTrue())}async waitUntilLoadedDatabaseStore(){return await this.waitUntilReactiveStoreLoadedAndFirstSyncAndNotApplyingStagedChanges()}async waitUntilReactiveStoreLoadedAndFirstSyncAndNotApplyingStagedChanges(){await this.waitUntilFinishedFirstLoginSyncAndNotApplyingStagedChanges(!1),await this.waitUntilReactiveStoreLoaded()}async waitUntilFinishedFirstSyncAndReactiveStoreLoaded(){await this.waitUntilFinishedFirstSync(!1),await this.waitUntilReactiveStoreLoaded()}async waitUntilReactiveStoreLoaded(){await this.hasLoadedReactiveStoreFlag.waitUntilTrue()}ensureFullDBLoadedIntoReactiveStore__I_ACKNOWLEDGE_THIS_IS_VERY_BAD_IF_IT_HAPPENS_TO_EXISTING_USERS__(e){this.useReactiveStore&&"Lazy"==this.reactiveStoreLoadState&&(this.reactiveStoreLoadState="LoadingRequested",this.inLazyLoadStateReactiveVar.set(!1),this.initializeFromDatabaseStore())}clearRemFromReactiveStoreToFreeMemory(){if(!(0,en.canClearRemFromReactiveStore)())return console.error("clearRemFromReactiveStoreToFreeMemory is banned inside write guarantees without allowClearingDocsFromMemoryStoreDuringRun"),0;{let e=(0,en.getBlockBroadcastAndForceReloadAfterEndWriteGuarantee)();if((0,z.isRunningWindowReceivers)()||this.closed||!this.useReactiveStore||!this.ReactiveStore||!this.hasDatabaseStore||!this.lazyLoadFromDatabaseStore||"Lazy"!==this.reactiveStoreLoadState&&(!e||"Full"!==this.reactiveStoreLoadState)||this.databaseStoreQueueToUpsertThisBatch||this.databaseStoreQueueToDeleteThisBatch)return 0;if(this.ReactiveStore.findAllReactiveDep.hasDependents())return console.error("clearRemFromReactiveStoreToFreeMemory skipped: a Tracker depends on findAllReactive",this.collectionName,this.owner),0;{"Full"===this.reactiveStoreLoadState&&(this.reactiveStoreLoadState="Lazy",this.inLazyLoadStateReactiveVar.set(!0),this.hasLoadedReactiveStoreFlag.set(!1),Y.Y.addInMemoryLog("memory_release","Switched fully loaded collection to lazy loading for large import",{collectionName:this.collectionName,owner:this.owner}));let t=e||!b._2,a=this.syncModule.serverSyncModule.updatesForServerIds,i=[];for(let[s,n]of this.ReactiveStore.docs){let r=n[Z.A.X_NUMBER_ID];this.databaseStoreQueueToUpsert.has(s)||this.databaseStoreQueueToUpsertFromOtherTab.has(s)||this.databaseStoreQueueToDelete.has(s)||this.databaseStoreQueueToDeleteFromOtherTab.has(s)||this.activeFindOneLookupCounts.has(s)||r&&this.activeFindOneFromNumberIdLookupCounts.has(r)||!t&&(this.broadcastQueueToUpsert.has(s)||this.broadcastQueueToDelete.has(s))||!e&&a.has(s)||this.keepInReactiveStoreWhenClearing?.(n)||this.ReactiveStore.docHasActiveTrackerDependents(s)||i.push(s)}for(let e of i){let a=this.ReactiveStore.docs.get(e);t&&this.broadcastQueueToUpsert.delete(e),this.idsFetchedFromDatabaseStore.delete(e);let i=a[Z.A.X_NUMBER_ID];i&&this.numberIdsFetchedFromDatabaseStore.delete(i),this.debugInsertedDocsCheck.delete(a),this.ReactiveStore.unloadDocFromMemory(e)}return i.length}}}async createNew(){let{createNewFunction:e}=this;if(!e)throw Error("createNewFunction is not set "+this.collectionName);let t=e();return await this.insert(t)}}(0,n.Cg)([(0,M.G)(R.lh)],eD.prototype,"constructTinyGraph",null),(0,n.Cg)([(0,M.G)(R.lh)],eD.prototype,"getTinyGraphLinkerAsync",null),(0,n.Cg)([(0,M.G)(R.lh)],eD.prototype,"getDeletedDatabaseStore",null),(0,n.Cg)([(0,M.G)(R.lh)],eD.prototype,"getMissingIdsDatabaseStore",null),(0,n.Cg)([(0,M.G)(R.lh)],eD.prototype,"initializeFromDatabaseStore",null),(0,n.Cg)([(0,M.G)(R.lh)],eD.prototype,"relookupDatabaseStore",null),(0,n.Cg)([(0,M.G)(R.lh)],eD.prototype,"constructDatabaseStores",null),(0,n.Cg)([(0,M.G)(R.lh)],eD.prototype,"deleteEverythingLocally",null),(0,n.Cg)([(0,M.G)(R.lh)],eD.prototype,"findDeletedDocsBetweenTimestamps",null);let ep=0;function eb(){return!(!(0,j.Pu)()||(0,j.c1)())&&("IndexedDBError"!==FlowRouter.getRouteName()&&FlowRouter.go("IndexedDBError"),!0)}function ef(){return _.sortBy(_.keys(ey),e=>-ey[e]).map(e=>[e,ey[e]])}h.Env.isWorker},11113:function(e,t,a){a.d(t,{sO:function(){return o},y$:function(){return h}});var i=a(528037);a(937859);var s=a(410721),n=a(719520);class r{field;cachedDocs=new Map;deps=new Map;constructor(e){this.field=e}clear(){this.cachedDocs=new Map,this.deps=new Map}}class o{docs=new Map;transformedDocs=new Map;dependencies=new Map;dependenciesByKey=new Map;findAllReactiveDep=new s.Dependency;collectionName;databaseName;transformFunction;indices=new Map;_testIdCounter=0;constructor(e,t,a){this.collectionName=e,this.databaseName=t,this.transformFunction=a}createIndex(e){0!=this.docs.size&&console.error("Index created after document exist",this.collectionName,e),this.indices.set(e,new r(e))}_insert(e,t=null,a=!0){let i=e._id?e._id:this._generateNewId();return e._id||(e._id=i),this.docs.set(i,e),this.transformedDocs.set(i,this.transformFunction(e)),this.addToIndicies(e._id,e,null),a&&this._triggerUpdatesForSelector(i,e,e),t&&t(e),i}removeFromIndicies(e,t){if(e)for(let a of this.indices.values()||[]){let i=e[a.field];i&&(!t||a.field in t&&t[a.field]!=i)&&(a.cachedDocs.get(i)?.delete(e._id),a.deps.get(i)?.changed())}}addToIndicies(e,t,a){for(let i of this.indices.values()){if(a&&!(i.field in a)||a&&i.field in a&&a[i.field]==t[i.field])continue;let s=a&&i.field in a?a[i.field]:t[i.field];s&&(i.cachedDocs.has(s)||i.cachedDocs.set(s,new Set),i.cachedDocs.get(s).add(e),i.deps.get(s)?.changed())}}ensureDocsExist(e,t=!0){for(let a of e)a&&!this.docs.has(a._id)&&this.upsert(a,null,t)}findAllReactive(){return this.findAllReactiveDep.depend(),this.findAllNonReactive()}findAllNonReactive(){return Array.from(this.docs.values()).map(this._transformDoc)}find(e,t=null){let a=new d(this,e,t);if(t?.useIndex){let i=this.indices.get(t?.useIndex),s=i&&e[i.field];i&&s&&!1!=t.reactive&&this._dependOnIndexValue(i,s),a.setCachedResultsToIdsAndFilter(s&&i?.cachedDocs.get(s)||new Set)}return a}findOne(e,t=null){if(e){if(this._selectorIsID(e))return t&&!1==t.reactive||this._dependOnDependencyForId(e,t),this.transformedDocs.get(e);if(e){if(!t?.useIndex)return;let a=this.indices.get(t?.useIndex),i=e[t?.useIndex];if(!i)return;a.cachedDocs.has(i)||a.cachedDocs.set(i,new Set),this._dependOnIndexValue(a,i);let n=[...a?.cachedDocs.get(e[a.field])?.values()||[]],r=s.Tracker.nonreactive(()=>n.map(e=>this.findOne(e))),o=new c(e),d=r.find(e=>o.matches(e));return d&&!1!=t.reactive&&this._dependOnDependencyForId(d._id,t),d}
31}}findOneRaw(e){return this.docs.get(e)}remove(e,t){this._selectorIsID(e)?(this.removeFromIndicies(this.findOneRaw(e),null),this.docs.delete(e),this.transformedDocs.delete(e),this._triggerUpdatesForSelector(e,void 0,void 0),t&&t(null)):console.error("Error: Can only remove by ID")}clear(){for(let e of(this.docs=new Map,this.transformedDocs=new Map,this.dependencies=new Map,this.dependenciesByKey=new Map,this.indices.values()))e.clear()}docHasActiveTrackerDependents(e){let t=this.dependencies.get(e)?.hasDependents()??!1;if(!t){let a=this.dependenciesByKey.get(e);if(a){for(let e of a.values())if(e.hasDependents()){t=!0;break}}}if(!t){let a=this.docs.get(e);if(a)for(let e of this.indices.values()){let i=a[e.field];if(i&&e.deps.get(i)?.hasDependents()){t=!0;break}}}return t}unloadDocFromMemory(e){let t=this.docs.get(e);t&&(this.removeFromIndicies(t,null),this.docs.delete(e),this.transformedDocs.delete(e),this.dependencies.delete(e),this.dependenciesByKey.delete(e))}update(e,t){let a=this.docs.get(e);a&&(this.removeFromIndicies(a,t.$set),this.addToIndicies(a._id,a,t.$set),h(a,t.$set),this._triggerUpdatesForSelector(e,a,t.$set))}_replace(e,t){let a=this.docs.get(e);for(let e of(this.removeFromIndicies(a,null),Object.keys(a)))e in t||delete a[e];for(let e of Object.keys(t))a[e]=t[e];return this.addToIndicies(e,a,null),this._triggerUpdatesForSelector(e,a,t),a._id}upsert(e,t=null,a=!0){return e._id&&this.docs.has(e._id)?this._replace(e._id,e):this._insert(e,t,a)}everyRawDoc(){return Array.from(this.docs.values())}numDocs(){return this.docs.size}forEveryRawDoc(e){this.docs.forEach(e)}_generateNewId(){return(0,n.c)()}_selectorIsID(e){return"string"==typeof e}externalTriggerDepForDocByKey(e,t){let a=this.dependenciesByKey.get(e);null!=a&&this._triggerDepForDocByKey(a,t,void 0,null)}_triggerDepForDocByKey(e,t,a,i){let s=e.get(t);s&&(s.hasDependents()?s.changed(!1):e.delete(t))}externalTriggerDepForDoc(e,t){let a=this.dependencies.get(e);a&&(a.hasDependents()?a.changed(t):this.dependencies.delete(e))}_triggerUpdatesForSelector(e,t,a){this.findAllReactiveDep.changed();let s=this.dependencies.get(e);s&&(s.hasDependents()?s.changed(!1):this.dependencies.delete(e));let n=this.dependenciesByKey.get(e);if(null!=n)if(null==a)for(let e of n.keys())this._triggerDepForDocByKey(n,e,t,null);else{var r;for(let e of(r=Object.keys(a),_.flatten(r.map(e=>e.split(".")),1)))if(n.has(e))for(let s of(0,i.r8)(e))this._triggerDepForDocByKey(n,s,t,a)}}_dependOnIndexValue(e,t){s.Tracker.active&&(e.deps.has(t)||e.deps.set(t,new s.Dependency(()=>{e.deps.delete(t)})),e.deps.get(t).depend())}_dependOnDependencyForId(e,t){if(s.Tracker.active)if(t&&t.fields){let a=this.dependenciesByKey.get(e);for(let i in a||(a=new Map,this.dependenciesByKey.set(e,a)),t.fields){let t=a.get(i);t||(t=new s.Dependency(()=>{a.delete(i),0==a.size&&this.dependenciesByKey.delete(e)}),a.set(i,t)),t.depend()}}else{let t=this.dependencies.get(e);if(t)t.depend();else{let t=new s.Dependency(()=>{this.dependencies.delete(e)});this.dependencies.set(e,t),t.depend()}}}_transformDoc=e=>this.transformFunction?this.transformFunction(e):e}class d{store;selector;options;dependency;matcher;cachedResults;cachedSortedResults;sortKey;reverseSort;constructor(e,t,a){this.store=e,this.selector=t,this.options=a,this.sortKey=a&&a.sort&&Object.keys(a.sort)[0],this.reverseSort=null!=this.sortKey&&-1==a.sort[this.sortKey],this.dependency=new s.Dependency,this.matcher=new c(this.selector),this.cachedResults=null,this.cachedSortedResults=null}fetch(){if(null==this.cachedResults){let e=new Map;this.store.forEveryRawDoc(t=>{this.matcher.matches(t)&&e.set(t._id,t)}),this.cachedResults=e}return s.Tracker.active&&this.dependency.depend(),this._getCachedSortedResults()}setCachedResultsToIdsAndFilter(e){let t=new Map;for(let a of e){let e=this.store.findOneRaw(a);this.matcher.matches(e)&&t.set(a,e)}this.cachedResults=t}
31forEach(e){return this.fetch().forEach(e)}_getCachedSortedResults(){return null==this.cachedSortedResults&&(this.cachedSortedResults=Array.from(this.cachedResults.values()).map(e=>this.store._transformDoc(e)),this.sortKey&&(this.cachedSortedResults=_.sortBy(this.cachedSortedResults,this.sortKey),this.reverseSort&&this.cachedSortedResults.reverse())),this.cachedSortedResults}_name(){return JSON.stringify(this.selector)+JSON.stringify(this.options)}_dependencyChanged(){this.dependency.changed(!1)}_observedFieldsChanged(e,t,a){if(!this.options?.fields||void 0==e!=(void 0==t))return!0;if(void 0==e&&void 0==t||!a)return!1;for(let e in this.options.fields)if(e in a)return!0;return!1}}class c{selector;constructor(e){this.selector=e}matches(e){if(!e)return!1;if(!this.selector)return!0;for(let t in this.selector){let a=this.selector[t];if(e[t]!=a)return!1}return!0}}function h(e,t){for(let a in t)!function e(t,a,i,s=!0){let n=a.indexOf(".");if(-1!=n){let s=a.substring(0,n),r=a.substring(n+1);_.isObject(t[s])||(t[s]={}),e(t[s],r,i,!1)}else void 0===i?s?t[a]=null:delete t[a]:t[a]=i}(e,a,t[a]);return e}},333409:function(e,t,a){a.d(t,{G:function(){return i}});function i(e){return!e.isDerived||e.syncDerivedProperty}},571015:function(e,t,a){a.d(t,{Bq:function(){return d},DB:function(){return h},yw:function(){return r}}),a(448445);var i=a(158876),s=a(719788);let n=()=>[];function r(e){n=e}let o=new i.lN("initialPageLoadFinish");async function d(){await o.waitUntilTrue()}let c=new s.G(e=>new i.lN("loadedOnceFlagMap."+e));async function h(e){c.get(e).set(!0)}setTimeout(async function e(){for(let e of n())await c.get(e).waitUntilTrue();o.set(!0)})},301800:function(e,t,a){function i(e,t,a){return void 0!=e&&e>t&&e<=a}function s(e,t,a,i){return e<a||e==a&&(!i||i&&t<=i)}a.d(t,{k7:function(){return i},pr:function(){return s}})}}]); 32//# debugId=1c166e6b-2af3-5ce0-999e-f5fe88f21937
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.