@powerhousedao/connect 5.1.0-staging.0 → 5.1.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/assets/AddDriveModal-_XSf2ZlN.js +1 -0
- package/dist/assets/ClearStorageModal-CbfJTlAo.js +1 -0
- package/dist/assets/CookiesPolicyModal-DTRuUeM_.js +1 -0
- package/dist/assets/CreateDocumentModal-DUTbfZYr.js +1 -0
- package/dist/assets/{DebugSettingsModal-BLV4d9N1.js → DebugSettingsModal-CooFY-Go.js} +1 -1
- package/dist/assets/{DeleteDriveModal-CQq-0aWd.js → DeleteDriveModal-BOdu1bg5.js} +1 -1
- package/dist/assets/DeleteItemModal-D8MlQS3W.js +1 -0
- package/dist/assets/DisclaimerModal-RBBaiKyO.js +1 -0
- package/dist/assets/DriveSettingsModal-BHBZfzaY.js +1 -0
- package/dist/assets/{ExportDocumentWithErrorsModal-CPfizBgB.js → ExportDocumentWithErrorsModal-BzgGSmxg.js} +1 -1
- package/dist/assets/SettingsModal-BXDXscnR.js +1 -0
- package/dist/assets/UpgradeDriveModal-15TBzq11.js +1 -0
- package/dist/assets/{design_system-pnKFY6jM.js → design_system-DGYPpUGa.js} +1 -1
- package/dist/assets/design_system_connect-Vb8XBnLs.js +45 -0
- package/dist/assets/design_system_ui-Dnwc_Xm9.js +1 -0
- package/dist/assets/{document_drive-CVkeqJ3l.js → document_drive-BEIKnuGM.js} +2 -2
- package/dist/assets/{document_engineering-BAszqzBd.js → document_engineering-B49PhCDR.js} +1 -1
- package/dist/assets/{document_model-LXEZCDPq.js → document_model-DXcLJEjZ.js} +1 -1
- package/dist/assets/{document_model_editor-D5oPro82.js → document_model_editor-lmHQ6HZy.js} +4 -4
- package/dist/assets/{drive_explorer-C6clT2Df.js → drive_explorer-d0kn77Nx.js} +2 -2
- package/dist/assets/{graphql-editor-C6f63OmN.js → graphql-editor-CSkqTexL.js} +2 -2
- package/dist/assets/{hooks-BySGfjQp.js → hooks-D4Uas2SG.js} +1 -1
- package/dist/assets/index-Br7E7qjt.css +1 -0
- package/dist/assets/index-CK2Jk_ho.js +18 -0
- package/dist/assets/json-editor-CQKAVxat.js +1 -0
- package/dist/assets/reactor_browser-BGn_P-dn.js +25 -0
- package/dist/assets/state-schemas-36mF-wEI.js +2 -0
- package/dist/index.html +10 -10
- package/heroku/Dockerfile +1 -4
- package/lib/package.copy.json +2 -7
- package/lib/src/components/app-skeleton.js +1 -1
- package/lib/src/components/app-skeleton.js.map +1 -1
- package/lib/src/components/root.js +1 -1
- package/lib/src/components/root.js.map +1 -1
- package/lib/src/feature-flags.d.ts +3 -17
- package/lib/src/feature-flags.d.ts.map +1 -1
- package/lib/src/feature-flags.js +3 -32
- package/lib/src/feature-flags.js.map +1 -1
- package/lib/src/pages/demo/atlas-import.js +2 -2
- package/lib/src/pages/demo/atlas-import.js.map +1 -1
- package/lib/src/store/reactor.d.ts.map +1 -1
- package/lib/src/store/reactor.js +30 -33
- package/lib/src/store/reactor.js.map +1 -1
- package/lib/src/utils/reactor.d.ts +0 -7
- package/lib/src/utils/reactor.d.ts.map +1 -1
- package/lib/src/utils/reactor.js +2 -30
- package/lib/src/utils/reactor.js.map +1 -1
- package/lib/tsconfig.tsbuildinfo +1 -1
- package/nginx.conf +0 -7
- package/package.copy.json +2 -7
- package/package.json +10 -15
- package/dist/assets/AddDriveModal-CGnuKCkz.js +0 -1
- package/dist/assets/ClearStorageModal-tHn6sdVv.js +0 -1
- package/dist/assets/CookiesPolicyModal-D5y1O9wD.js +0 -1
- package/dist/assets/CreateDocumentModal-DU4C2Y6P.js +0 -1
- package/dist/assets/DeleteItemModal-JV0AvuwF.js +0 -1
- package/dist/assets/DisclaimerModal-DQZyl_zf.js +0 -1
- package/dist/assets/DriveSettingsModal-yXsOiCLy.js +0 -1
- package/dist/assets/SettingsModal-GeNqOEFN.js +0 -1
- package/dist/assets/UpgradeDriveModal-BCRmp5F4.js +0 -1
- package/dist/assets/design_system_connect-BrlN-7x3.js +0 -104
- package/dist/assets/design_system_ui-Cz-kMJRJ.js +0 -1
- package/dist/assets/index-BYfBva47.js +0 -20
- package/dist/assets/index-XUlAOLkX.css +0 -1
- package/dist/assets/json-editor-D27WLv4C.js +0 -1
- package/dist/assets/nodefs-AYr2EwM_.js +0 -1
- package/dist/assets/opfs-ahp-rEGVoJkP.js +0 -3
- package/dist/assets/postgres-CkP7QCDB.data +0 -0
- package/dist/assets/postgres-CyuUVpXN.wasm +0 -0
- package/dist/assets/reactor_browser-D4maXKS-.js +0 -25
- package/dist/assets/state-schemas-DGMOULa-.js +0 -2
- package/lib/src/utils/signer.d.ts +0 -18
- package/lib/src/utils/signer.d.ts.map +0 -1
- package/lib/src/utils/signer.js +0 -215
- package/lib/src/utils/signer.js.map +0 -1
- package/lib/test/utils/signer.test.d.ts +0 -2
- package/lib/test/utils/signer.test.d.ts.map +0 -1
- package/lib/test/utils/signer.test.js +0 -319
- package/lib/test/utils/signer.test.js.map +0 -1
- package/lib/vitest.config.d.ts +0 -3
- package/lib/vitest.config.d.ts.map +0 -1
- package/lib/vitest.config.js +0 -8
- package/lib/vitest.config.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as Ee,g as Pt}from"./react-DQSxOgtG.js";import{c as oe,a as ds,i as ls,B as hs,b as fs,d as gs,e as ps,f as ms,g as ct,h as Lt,j as ys,p as Nr,k as Le,v as He,l as ar,m as cr,r as vs,n as Dt,s as Ge,o as ws,q as bs,t as Ds,u as Ve,w as Cr,x as Ss,y as Es,z as Is,A as Je}from"./document_model-
|
|
1
|
+
import{c as Ee,g as Pt}from"./react-DQSxOgtG.js";import{c as oe,a as ds,i as ls,B as hs,b as fs,d as gs,e as ps,f as ms,g as ct,h as Lt,j as ys,p as Nr,k as Le,v as He,l as ar,m as cr,r as vs,n as Dt,s as Ge,o as ws,q as bs,t as Ds,u as Ve,w as Cr,x as Ss,y as Es,z as Is,A as Je}from"./document_model-DXcLJEjZ.js";import{a as Ts,p as Rs,G as Ms,b as Os,c as St,d as ur,e as Et,f as _s,g as As}from"./graphql-BS4Brs_E.js";import{o as W,s as $,f as Ze,b as ge,e as xr,d as Oe,a as Ns,c as Cs}from"./zod-C6yxFxyo.js";import{i as xs,L as he}from"./config-CU-aFfVJ.js";function $s(i,e){for(var t=0;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const n in r)if(n!=="default"&&!(n in i)){const s=Object.getOwnPropertyDescriptor(r,n);s&&Object.defineProperty(i,n,s.get?s:{enumerable:!0,get:()=>r[n]})}}}return Object.freeze(Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}))}var Ps={};class $r{#e;#t="env";#r;constructor(e,t){this.#e=(e||[]).map(r=>`[${r}]`),this.#r=t,this.log=this.log.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.debug=this.debug.bind(this),this.verbose=this.verbose.bind(this)}get level(){return this.#t}set level(e){if(e!=="env"&&!xs(e))throw new Error(`Invalid log level: ${JSON.stringify(e)}.
|
|
2
2
|
Must be one of ${Object.keys(he).concat(["env"]).join(", ")}.`);this.#t=e}get errorHandler(){return this.#r}set errorHandler(e){this.#r=e}get#n(){if(this.#t==="env"){const e=typeof globalThis<"u"&&globalThis.process&&"env"in globalThis.process?Ps.LOG_LEVEL:void 0;return e?e in he?he[e]:he.info:he.info}return he[this.#t]}log(...e){return this.debug(...e)}verbose(...e){if(!(this.#n>he.verbose))return this.debug(...e)}debug(...e){if(!(this.#n>he.debug))return console.debug(...this.#e,...e)}info(...e){if(!(this.#n>he.info))return console.info(...this.#e,...e)}warn(...e){if(!(this.#n>he.warn))return console.warn(...this.#e,...e)}error(...e){if(!(this.#n>he.error))return this.#r&&this.#r(...e),console.error(...this.#e,...e)}}const ut=new $r;let Ut="env",Pr;ut.level=Ut;ut.errorHandler=Pr;const fe=ut,Ao=i=>{Ut=i,ut.level=i},pe=i=>{const e=new $r(i);return e.level=Ut,e.errorHandler=Pr,e},dr=i=>{const e={};for(const[t,r]of Object.entries(i.operations))r&&(e[t]=r.map(n=>(delete n.resultingState,n)));return{...i,operations:e}};class Ls{index=0;cache;constructor(e){this.cache=e}createStorage(){const e=this.index;this.index+=1;function t(n){return`${e}-${n}`}const r={get:n=>this.cache.get(t(n)),set:(n,s)=>(this.cache.set(t(n),s),r),delete:n=>this.cache.delete(t(n)),clear:()=>{this.cache.clear()}};return r}}class Us{cache;cacheStorageManager;idToDocument;idToDrive;slugToDriveId;constructor(e=new Map){this.cache=e,this.cacheStorageManager=new Ls(e),this.idToDocument=this.cacheStorageManager.createStorage(),this.idToDrive=this.cacheStorageManager.createStorage(),this.slugToDriveId=this.cacheStorageManager.createStorage()}clear(){this.idToDocument.clear(),this.idToDrive.clear(),this.slugToDriveId.clear()}async setDocument(e,t){const r=dr(t);this.idToDocument.set(e,r)}async getDocument(e){return this.idToDocument.get(e)}async deleteDocument(e){return this.idToDocument.delete(e)}async setDrive(e,t){const r=dr(t);this.idToDrive.set(e,r)}async getDrive(e){return this.idToDrive.get(e)}async deleteDrive(e){const t=this.idToDrive.get(e);if(!t)return!1;const r=t.header.slug.length>0?t.header.slug:e;return r&&this.slugToDriveId.delete(r),this.idToDrive.delete(e)}async setDriveBySlug(e,t){const r=t.header.id;this.slugToDriveId.set(e,r),this.setDrive(r,t)}async getDriveBySlug(e){const t=this.slugToDriveId.get(e);if(t)return this.getDrive(t)}async deleteDriveBySlug(e){const t=this.slugToDriveId.get(e);return t?(this.slugToDriveId.delete(e),this.deleteDrive(t)):!1}}const Bs="phdd",Fs=i=>i!=null;Cs().refine(i=>Fs(i));const ks=xr(["Internal","MatrixConnect","PullResponder","RESTWebhook","SecureConnect","SwitchboardPush"]),qs=xr(["PullResponder"]);function Lr(){return W({documentType:$(),id:$(),name:$(),parentFolder:$().nullish()})}function Ur(){return W({id:$(),name:$(),parentFolder:$().nullish()})}function Br(){return W({listener:zr()})}function Fr(){return W({trigger:Kr()})}function kr(){return W({srcId:$(),targetId:$(),targetName:$().nullish(),targetParentFolder:$().nullish()})}function qr(){return W({id:$()})}function zs(){return W({__typename:ge("DocumentDriveLocalState").optional(),availableOffline:Ze(),listeners:Oe(zr()),sharingType:$().nullable(),triggers:Oe(Kr())})}function js(){return W({__typename:ge("DocumentDriveState").optional(),icon:$().nullable(),name:$(),nodes:Oe(Qs())})}function Hs(){return W({__typename:ge("FileNode").optional(),documentType:$(),id:$(),kind:$(),name:$(),parentFolder:$().nullable()})}function Gs(){return W({__typename:ge("FolderNode").optional(),id:$(),kind:$(),name:$(),parentFolder:$().nullable()})}function zr(){return W({__typename:ge("Listener").optional(),block:Ze(),callInfo:Js().nullable(),filter:Ys(),label:$().nullable(),listenerId:$(),system:Ze()})}function Js(){return W({__typename:ge("ListenerCallInfo").optional(),data:$().nullable(),name:$().nullable(),transmitterType:ks.nullable()})}function Ys(){return W({__typename:ge("ListenerFilter").optional(),branch:Oe($()).nullable(),documentId:Oe($()).nullable(),documentType:Oe($()),scope:Oe($()).nullable()})}function jr(){return W({srcFolder:$(),targetParentFolder:$().nullish()})}function Qs(){return Ns([Hs(),Gs()])}function Vs(){return W({__typename:ge("PullResponderTriggerData").optional(),interval:$(),listenerId:$(),url:$()})}function Hr(){return W({listenerId:$()})}function Gr(){return W({triggerId:$()})}function Jr(){return W({availableOffline:Ze()})}function Yr(){return W({icon:$()})}function Qr(){return W({name:$()})}function Vr(){return W({type:$()})}function Kr(){return W({__typename:ge("Trigger").optional(),data:Ks().nullable(),id:$(),type:qs})}function Ks(){return Vs()}function Wr(){return W({documentType:$().nullish(),id:$(),name:$().nullish(),parentFolder:$().nullish()})}function Xr(){return W({id:$(),name:$().nullish(),parentFolder:$().nullish()})}function Ws(i){return i&&typeof i=="object"&&"synchronizationUnits"in i?oe("ADD_FILE",{...i},void 0,void 0,"global"):oe("ADD_FILE",{...i},void 0,Lr,"global")}const Xs=i=>oe("ADD_FOLDER",{...i},void 0,Ur,"global"),Zs=i=>oe("DELETE_NODE",{...i},void 0,qr,"global"),ei=i=>oe("UPDATE_FILE",{...i},void 0,Wr,"global"),ti=i=>oe("UPDATE_NODE",{...i},void 0,Xr,"global"),ri=i=>oe("COPY_NODE",{...i},void 0,kr,"global"),ni=i=>oe("MOVE_NODE",{...i},void 0,jr,"global"),si=i=>oe("SET_DRIVE_NAME",{...i},void 0,Qr,"global"),ii=i=>oe("SET_DRIVE_ICON",{...i},void 0,Yr,"global"),Zr=i=>oe("SET_SHARING_TYPE",{...i},void 0,Vr,"local"),oi=i=>oe("SET_AVAILABLE_OFFLINE",{...i},void 0,Jr,"local"),ai=i=>oe("ADD_LISTENER",{...i},void 0,Br,"local"),en=i=>oe("REMOVE_LISTENER",{...i},void 0,Hr,"local"),ci=i=>oe("ADD_TRIGGER",{...i},void 0,Fr,"local"),tn=i=>oe("REMOVE_TRIGGER",{...i},void 0,Gr,"local"),ui=Object.freeze(Object.defineProperty({__proto__:null,addFile:Ws,addFolder:Xs,addListener:ai,addTrigger:ci,copyNode:ri,deleteNode:Zs,moveNode:ni,removeListener:en,removeTrigger:tn,setAvailableOffline:oi,setDriveIcon:ii,setDriveName:si,setSharingType:Zr,updateFile:ei,updateNode:ti},Symbol.toStringTag,{value:"Module"})),di={id:"powerhouse/document-drive",name:"DocumentDrive",extension:"phdd",description:"",author:{name:"Powerhouse Inc",website:"https://www.powerhouse.inc/"},specifications:[{version:1,changeLog:[],state:{global:{schema:`type FolderNode {
|
|
3
3
|
id: String!
|
|
4
4
|
name: String!
|
|
@@ -302,4 +302,4 @@ type DocumentDriveLocalState{
|
|
|
302
302
|
error
|
|
303
303
|
}
|
|
304
304
|
}
|
|
305
|
-
`,{strands:r.map(o=>({driveId:o.driveId,documentId:o.documentId,documentType:o.documentType,scope:o.scope,branch:o.branch,operations:o.operations.map(a=>({index:a.index,skip:a.skip,type:a.type,id:a.id??void 0,actionId:a.actionId,input:co(a.input),hash:a.hash,timestampUtcMs:a.timestampUtcMs,context:a.context?{signer:a.context.signer}:void 0}))}))});if(!s.pushUpdates)throw new Error("Couldn't update listener revision");return s.pushUpdates}catch(s){throw this.logger.error(s),s}}}function Mr(i,e){return e?Object.keys(i).reduce((t,r)=>{const n=e[r];if(n!==void 0){const s=i[r];s&&(t[r]=s.filter(o=>o.index<=n))}return t},{global:[],local:[]}):i}function Nt(i,e){return!e||Object.entries(e).find(([t,r])=>{const n=i.operations[t]?.at(-1);return r===-1?n!==void 0:n?.index!==r})===void 0}function Ct(i){return{id:uo(i),documentType:lo(i),document:ho(i)}}function uo(i){return"id"in i?i.id:"header"in i?i.header.id:"document"in i?i.document.header.id:void 0}function lo(i){return"documentType"in i?i.documentType:"header"in i?i.header.documentType:i.document.header.documentType}function ho(i){return"document"in i?i.document:void 0}function fo(i){return["LOCAL","CLOUD","PUBLIC"].includes(i)}function $o(i){if(typeof i!="object")return"LOCAL";const e="readContext"in i,{sharingType:t}=e?{sharingType:"PUBLIC"}:i.state.local,r=t?.toUpperCase();return!r||r==="PRIVATE"||!fo(r)?"LOCAL":r}class go{logger=pe(["BaseDocumentDriveServer"]);documentModelModules;legacyStorage;documentStorage;cache;queueManager;eventEmitter;options;listenerManager;synchronizationManager;generateJwtHandler;defaultDrivesManager;defaultDrivesManagerDelegate={detachDrive:this.detachDrive.bind(this),emit:(...e)=>this.eventEmitter.emit("defaultRemoteDrive",...e)};queueDelegate={exists:e=>this.documentStorage.exists(e),processOperationJob:async({documentId:e,operations:t,options:r})=>{const n=await this.getDocument(e);return ye(n)?this.processDriveOperations(e,t,r):this.processOperations(e,t,r)},processActionJob:async({documentId:e,actions:t,options:r})=>{const n=await this.getDocument(e);return ye(n)?this.processDriveActions(e,t,r):this.processActions(e,t,r)},processDocumentJob:async({documentId:e,documentType:t,header:r,initialState:n,options:s})=>{const a=this.getDocumentModelModule(t).utils.createDocument(n),d=Le(e,t);a.header.id=e,a.header.sig=d.sig,a.header.documentType=t,r&&(a.header.meta=r.meta);try{const l=await this.createDocument({document:a},s?.source??{type:"local"},a.header.meta);return{status:"SUCCESS",operations:[],document:l,signals:[]}}catch(l){const m=l instanceof Error?l:new Error(JSON.stringify(l));return{status:"ERROR",error:new ie("ERROR",void 0,`Error creating document: ${m.message}`,m),operations:[],document:void 0,signals:[]}}},processJob:async e=>{if(fn(e))return this.queueDelegate.processOperationJob(e);if(Ui(e))return this.queueDelegate.processActionJob(e);if(Ke(e))return this.queueDelegate.processDocumentJob(e);throw new Error("Unknown job type",e)}};triggerMap=new Map;initializePromise;enableDualActionCreate;constructor(e,t,r,n,s,o,a,d,l){this.documentModelModules=e,this.legacyStorage=t,this.documentStorage=r,this.cache=n,this.queueManager=s,this.eventEmitter=o,this.synchronizationManager=a,this.listenerManager=d,this.options={...l,defaultDrives:{...l?.defaultDrives},listenerManager:{...ot,...l?.listenerManager},jwtHandler:l?.jwtHandler===void 0?()=>Promise.resolve(""):l.jwtHandler,taskQueueMethod:l?.taskQueueMethod===void 0?Ft:l.taskQueueMethod,featureFlags:{...l?.featureFlags}},this.enableDualActionCreate=l?.featureFlags?.enableDualActionCreate??!1,this.enableDualActionCreate&&this.logger.warn("Dual action create is enabled."),this.defaultDrivesManager=new ro(this,this.defaultDrivesManagerDelegate,l),this.initializePromise=this._initialize()}get listeners(){return this.listenerManager}initialize(){return this.initializePromise}async _initialize(){await this.listenerManager.initialize(this.handleListenerError.bind(this)),await this.queueManager.init(this.queueDelegate,r=>{this.logger.error("Error initializing queue manager",r)});try{await this.defaultDrivesManager.removeOldremoteDrives()}catch(r){this.logger.error(r)}const e=[],t=await this.getDrives();for(const r of t)await this._initializeDrive(r).catch(n=>{this.logger.error(`Error initializing drive ${r}`,n),e.push(n)});return this.options.defaultDrives.loadOnInit!==!1&&await this.defaultDrivesManager.initializeDefaultRemoteDrives(),e.length===0?null:e}setDocumentModelModules(e){this.documentModelModules=[...e],this.synchronizationManager.setDocumentModelModules([...e]),this.eventEmitter.emit("documentModelModules",[...e])}initializeDefaultRemoteDrives(){return this.defaultDrivesManager.initializeDefaultRemoteDrives()}getDefaultRemoteDrives(){return this.defaultDrivesManager.getDefaultRemoteDrives()}setDefaultDriveAccessLevel(e,t){return this.defaultDrivesManager.setDefaultDriveAccessLevel(e,t)}setAllDefaultDrivesAccessLevel(e){return this.defaultDrivesManager.setAllDefaultDrivesAccessLevel(e)}getOperationSource(e){return e.type==="local"?"push":"pull"}handleListenerError(e,t,r){this.logger.error(`Listener ${r.listener.label??r.listener.listenerId} error:`,e);const n=e instanceof ie?e.status:"ERROR";this.synchronizationManager.updateSyncStatus(t,{push:n},e)}shouldSyncRemoteDrive(e){return e.state.local.availableOffline&&e.state.local.triggers.length>0}async startSyncRemoteDrive(e){let t=this.triggerMap.get(e);const r=await this.synchronizationManager.getSynchronizationUnitsIds(e),n=await this.getDrive(e);for(const s of n.state.local.triggers)if(!t?.get(s.id)){t||(t=new Map),this.synchronizationManager.updateSyncStatus(e,{pull:"SYNCING"});for(const o of r)this.synchronizationManager.updateSyncStatus(o,{pull:"SYNCING"});if(ce.isPullResponderTrigger(s)){let o=!0;const a=ce.setupPull(e,s,this.saveStrand.bind(this),d=>{const l=d instanceof ie?d.status:"ERROR";this.synchronizationManager.updateSyncStatus(e,{pull:l},d),d instanceof xe&&this.eventEmitter.emit("clientStrandsError",e,s,d.response.status,d.message)},async d=>{d.filter(m=>m.status!=="SUCCESS").length<1&&this.synchronizationManager.updateSyncStatus(e,{pull:"SUCCESS"});for(const m of d){const{documentId:f,scope:b,branch:w,status:y,error:I}=m;this.synchronizationManager.updateSyncStatus({documentId:f,scope:b,branch:w},{pull:y},I)}if(o){o=!1,(await this.synchronizationManager.getSynchronizationUnitsIds(e)).filter(w=>!d.find(y=>y.documentId===w.documentId&&y.scope===w.scope&&y.branch===w.branch)).forEach(w=>{this.synchronizationManager.updateSyncStatus(w,{pull:"SUCCESS"})});const b=n.state.local.listeners.find(w=>s.data.url===w.callInfo?.data);if(b)for(const w of d){const{documentId:y,scope:I,branch:_}=w;this.listenerManager.updateListenerRevision(b.listenerId,e,{documentId:y,scope:I,branch:_},w.revision).catch(this.logger.error)}}},void 0,this.listeners);t.set(s.id,a),this.triggerMap.set(e,t)}}}async stopSyncRemoteDrive(e){this.triggerMap.get(e)?.forEach(n=>n()),this.synchronizationManager.updateSyncStatus(e,null);const r=await this.synchronizationManager.getSynchronizationUnitsIds(e);for(const n of r)this.synchronizationManager.updateSyncStatus(n,null);return this.triggerMap.delete(e)}async _initializeDrive(e){const t=await this.getDrive(e);this.logger.verbose(`[SYNC DEBUG] Initializing drive ${e} with slug "${t.header.slug}"`),await this.synchronizationManager.initializeDriveSyncStatus(e,t),this.shouldSyncRemoteDrive(t)&&(this.logger.verbose(`[SYNC DEBUG] Starting sync for remote drive ${e}`),await this.startSyncRemoteDrive(e)),this.logger.verbose(`[SYNC DEBUG] Processing ${t.state.local.listeners.length} listeners for drive ${e}`);for(const r of t.state.local.listeners)if(r.callInfo?.transmitterType==="SwitchboardPush"){this.logger.verbose(`[SYNC DEBUG] Setting up SwitchboardPush listener ${r.listenerId} for drive ${e}`);const n=new pn(r.callInfo.data??"",this.listeners);this.logger.verbose(`[SYNC DEBUG] Created SwitchboardPush transmitter with URL: ${r.callInfo.data||"none"}`),await this.listenerManager.setListener(e,{block:r.block,driveId:t.header.id,filter:{branch:r.filter.branch??[],documentId:r.filter.documentId??[],documentType:r.filter.documentType??[],scope:r.filter.scope??[]},listenerId:r.listenerId,callInfo:r.callInfo,system:r.system,label:r.label??"",transmitter:n}).then(()=>{this.logger.verbose(`[SYNC DEBUG] Successfully set up listener ${r.listenerId} for drive ${e}`)})}else if(r.callInfo?.transmitterType==="PullResponder"){this.logger.verbose(`[SYNC DEBUG] Setting up PullResponder listener ${r.listenerId} for drive ${e}`);const n={driveId:e,listenerId:r.listenerId,block:!1,filter:r.filter,system:!1,label:`PullResponder #${r.listenerId}`,callInfo:{data:"",name:"PullResponder",transmitterType:"PullResponder"}},s=new ce(n,this.listenerManager);n.transmitter=s,await this.listenerManager.setListener(e,n)}else this.logger.error(`Skipping listener ${r.listenerId} with unsupported type ${r.callInfo?.transmitterType||"unknown"}`)}getDocumentModelModule(e){const t=this.documentModelModules.find(r=>r.documentModel.global.id===e);if(!t)throw new Error(`Document type ${e} not supported`);return t}getDocumentModelModules(){return[...this.documentModelModules]}addDocument(e,t){const r=typeof e=="string"?{documentType:e}:{document:e};return this.createDocument(r,{type:"local"},t)}async addDrive(e,t){const{global:r}=Bt(),n=dn({global:{...r,name:e.global.name??r.name,icon:e.global.icon??r.icon},local:{availableOffline:e.local?.availableOffline??!1,sharingType:e.local?.sharingType??"public",listeners:e.local?.listeners??[],triggers:e.local?.triggers??[]}});e.id&&e.id.length>0&&(n.header.id=e.id),e.slug&&e.slug.length>0&&(n.header.slug=e.slug),e.global.name&&(n.header.name=e.global.name);const s=e.preferredEditor||t;return s&&(n.header.meta={preferredEditor:s}),await this.documentStorage.create(n),e.slug&&e.slug.length>0&&await this.cache.deleteDriveBySlug(e.slug),await this._initializeDrive(n.header.id),this.eventEmitter.emit("driveAdded",n),n}async addRemoteDrive(e,t){await this.generateJwtHandler?.(e);const{id:r,name:n,slug:s,icon:o,meta:a}=t.expectedDriveInfo||await Be(e,this),{pullFilter:d,pullInterval:l,availableOffline:m,sharingType:f,listeners:b,triggers:w}=t,y=await ce.createPullResponderTrigger(r,e,{pullFilter:d,pullInterval:l},this.listeners);return await this.addDrive({id:r,slug:s,global:{name:n,icon:o},local:{triggers:[...w,y],listeners:b,availableOffline:m,sharingType:f}},a?.preferredEditor)}async deleteDrive(e){const t=await Promise.allSettled([this.stopSyncRemoteDrive(e),this.listenerManager.removeDrive(e),this.cache.deleteDrive(e),this.documentStorage.delete(e)]);this.eventEmitter.emit("driveDeleted",e),t.forEach(r=>{if(r.status==="rejected")throw r.reason})}async getDrives(){const e=[];let t;do{const{documents:r,nextCursor:n}=await this.documentStorage.findByType("powerhouse/document-drive",100,t);e.push(...r),t=n}while(t);return e}async getDrivesSlugs(){const e=await this.getDrives();return this.documentStorage.resolveSlugs(e)}async getDrive(e,t){let r;try{const o=await this.cache.getDrive(e);if(o&&ye(o)&&(r=o,Nt(r,t?.revisions)))return r}catch(o){this.logger.error("Error getting drive from cache",o)}const n=r??await this.documentStorage.get(e),s=this._buildDocument(n,t);if(ye(s))return t?.revisions||(this.cache.setDocument(e,s).catch(this.logger.error),this.cache.setDrive(e,s).catch(this.logger.error)),s;throw new Error(`Document with id ${e} is not a Document Drive`)}async getDriveBySlug(e,t){try{const s=await this.cache.getDriveBySlug(e);if(s)return s}catch(s){this.logger.error("Error getting drive from cache",s)}const r=await this.documentStorage.getBySlug(e),n=this._buildDocument(r,t);if(ye(n))return this.cache.setDriveBySlug(e,n).catch(this.logger.error),n;throw new Error(`Document with slug ${e} is not a Document Drive`)}async getDriveIdBySlug(e){try{const r=await this.cache.getDriveBySlug(e);if(r)return r.header.id}catch(r){this.logger.error("Error getting drive from cache",r)}return(await this.documentStorage.getBySlug(e)).header.id}getDocument(e,t,r){const n=typeof t=="string"?t:e,s=typeof t=="object"?t:r;return this._getDocument(n,s)}async _getDocument(e,t){let r;try{if(r=await this.cache.getDocument(e),r&&Nt(r,t?.revisions))return r}catch(o){this.logger.error("Error getting document from cache",o)}const n=r??await this.documentStorage.get(e),s=this._buildDocument(n,t);return t?.revisions||this.cache.setDocument(e,s).catch(this.logger.error),s}getDocuments(e){return this.documentStorage.getChildren(e)}async addChild(e,t){try{await this.documentStorage.addChild(e,t)}catch(r){throw this.logger.error("Error adding child document",r),r}}async removeChild(e,t){try{const r=await this.synchronizationManager.getSynchronizationUnitsIds(e,[t]);await this.listenerManager.removeSyncUnits(e,r)}catch(r){this.logger.warn("Error removing sync units of child",r)}try{await this.documentStorage.removeChild(e,t)}catch(r){throw this.logger.error("Error adding child document",r),r}}async createDocument(e,t,r){return this.enableDualActionCreate?this.createDocumentDualAction(e,t,r):this.createDocumentLegacy(e,t,r)}async createDocumentLegacy(e,t,r){const{documentType:n,document:s}=Ct(e);let o;if(s){if("documentType"in e&&n!==s.header.documentType)throw new Error(`Provided document is not ${n}`);o=this._buildDocument(s).state}const a=s??this.getDocumentModelModule(n).utils.createDocument(o);let d;if("id"in e&&e.id)s?(d=a.header,a.header.id=e.id,this.logger.warn("Assigning an id to a document is deprecated. Use the header field instead.")):(this.logger.warn("Creating a document with an id is deprecated. Use the header field instead."),d=Le(e.id,n));else if("header"in e)await He(e.header),d=e.header;else if(s?.header){if(!s.header.id)throw new Error("Document header id is required");if(!s.header.documentType)throw new Error("Document header documentType is required");if(!s.header.createdAtUtcIso)throw new Error("Document header createdAtUtcIso is required");s.header.sig.nonce?await He(s.header):this.logger.warn("Creating a document with an unsigned id is deprecated. Use createSignedHeaderForSigner."),d=s.header}else d=Le(void 0,n);r&&(d.meta={...d.meta,...r});const l={header:d,operations:{global:[],local:[]},initialState:a.initialState,clipboard:[],state:o??a.state};await this.documentStorage.create(l);const m=Object.values(a.operations).flat();m.length&&(ye(a)?await this.legacyStorage.addDriveOperations(d.id,m,a):await this.legacyStorage.addDocumentOperations(d.id,m,a));const f=await this.getDocument(l.header.id);return this.eventEmitter.emit("documentAdded",f),f}async createDocumentDualAction(e,t,r){const{documentType:n,document:s}=Ct(e);let o;if(s){if("documentType"in e&&n!==s.header.documentType)throw new Error(`Provided document is not ${n}`);o=this._buildDocument(s).state}const a=s??this.getDocumentModelModule(n).utils.createDocument(o);let d,l=!1;if("id"in e&&e.id)s?(d=a.header,a.header.id=e.id,this.logger.warn("Assigning an id to a document is deprecated. Use the header field instead.")):(this.logger.warn("Creating a document with an id is deprecated. Use the header field instead."),d=Le(e.id,n));else if("header"in e)await He(e.header),l=!0,d=e.header;else if(s?.header){if(!s.header.id)throw new Error("Document header id is required");if(!s.header.documentType)throw new Error("Document header documentType is required");if(!s.header.createdAtUtcIso)throw new Error("Document header createdAtUtcIso is required");s.header.sig.nonce?(await He(s.header),l=!0):this.logger.warn("Creating a document with an unsigned id is deprecated. Use createSignedHeaderForSigner."),d=s.header}else d=Le(void 0,n),l=!1;r&&(d.meta={...d.meta,...r});const m="0.1.0",f=o??a.state,b=Object.values(a.operations).flat(),w=b.length===0;let y=[];if(w){const U=new Date().toISOString(),F=l?{signature:d.id,publicKey:d.sig.publicKey,nonce:d.sig.nonce,createdAtUtcIso:d.createdAtUtcIso,documentType:d.documentType}:void 0,E={model:n,version:"0.0.0",documentId:d.id,signing:F},L={id:`${d.id}-create`,type:"CREATE_DOCUMENT",timestampUtcMs:U,input:E,scope:"document"},P={model:n,fromVersion:"0.0.0",toVersion:m,documentId:d.id,initialState:f},j={id:`${d.id}-upgrade`,type:"UPGRADE_DOCUMENT",timestampUtcMs:U,input:P,scope:"document"},V={state:Lt()},Z=ar(V,"document"),se=ar({state:f},"document");y=[{id:`${d.id}-create`,index:0,skip:0,hash:Z,timestampUtcMs:U,action:L},{id:`${d.id}-upgrade`,index:1,skip:0,hash:se,timestampUtcMs:U,action:j}]}else y=b;const I=cr(y);I.header||(I.header=[]),I.document||(I.document=[]),I.global||(I.global=[]),I.local||(I.local=[]);const N={header:d,operations:I,initialState:f,clipboard:[],state:f};await this.documentStorage.create(N);const C=await this.getDocument(N.header.id,{checkHashes:!0});return this.eventEmitter.emit("documentAdded",C),C}async deleteDocument(e){try{const t=await this.synchronizationManager.getSynchronizationUnitsIds(void 0,[e]);for(const n of t)this.synchronizationManager.updateSyncStatus(n,null);const r=await this.documentStorage.getParents(e);for(const n of r)this.listenerManager.removeSyncUnits(n,t).catch(this.logger.warn)}catch(t){this.logger.warn("Error deleting document",t)}await Promise.allSettled([this.cache.deleteDocument(e).catch(this.logger.warn),this.documentStorage.delete(e).catch(this.logger.warn)]),this.eventEmitter.emit("documentDeleted",e)}async _processOperations(e,t,r){const n=[],s=[],o=await this._addDocumentResultingStage(t,e);let a=this._buildDocument(o),d;const l=cr(r);for(const m of Object.keys(l)){const f=t.operations[m]||[],b=vs(l[m]||[],f);if(b.length<1)continue;const w=Dt(Ge(f)),[y,I]=ws(w,b),N=(I.length<1?y:bs(w,y,Is)).filter(C=>w.length<1||Ds(w[w.length-1],C));for(const C of N){let U=!1;if(I.length>0){const F=r.find(E=>E.hash===C.hash);U=!F||F.index!==C.index||F.skip!==C.skip}try{const F=this.options.taskQueueMethod,E=()=>this._performOperation(e,a,C,U),L=await(F?$t(E,F):E());a=L.document,s.push(...L.signals),n.push(L.operation)}catch(F){d=F instanceof ie?F:new ie("ERROR",C,F.message,F.cause);break}}}return{document:a,operationsApplied:n,signals:s,error:d}}async _addDocumentResultingStage(e,t,r){const n=r?.revisions!==void 0?Mr(e.operations,r.revisions):e.operations,s=Ve(n);for(const o of Object.keys(s)){const a=s[o];if(!a)continue;const d=a.at(-1);d&&!d.resultingState&&(d.resultingState=await(ye(e)?this.legacyStorage.getOperationResultingState?.(t,d.index,d.action.scope,"main"):this.legacyStorage.getDriveOperationResultingState?.(t,d.index,d.action.scope,"main")))}return{...e,operations:s}}_buildDocument(e,t){if(e.state&&(!t||t.checkHashes===!1)&&Nt(e,t?.revisions))return e;const r=this.getDocumentModelModule(e.header.documentType),n=t?.revisions!==void 0?Mr(e.operations,t.revisions):e.operations,s=Ve(n),o=Object.keys(s),a=new Set([...o,"global","local"]),d={},l={};for(const w of a)d[w]=[],l[w]=[];for(const[w,y]of Object.entries(s))if(y)for(const I of y)if(I.action.type==="CREATE_DOCUMENT"||I.action.type==="UPGRADE_DOCUMENT"){const _=d[w];_&&_.push(I)}else{const _=l[w];_&&_.push(I)}const m=Cr(e.initialState,l,r.reducer,void 0,e.header,void 0,{...t,checkHashes:t?.checkHashes??!0,reuseOperationResultingState:t?.checkHashes??!0}),f=new Set([...Object.keys(s),...Object.keys(d),...Object.keys(m.operations)]),b={};for(const w of f)b[w]=[...d[w]||[],...m.operations[w]||[]];return{...m,operations:b}}async _performOperation(e,t,r,n=!1){const s=this.getDocumentModelModule(t.header.documentType),o=[];let a=t;const d=r.action.scope,l=t.operations[d]||[],b=Ve({...t.operations,[d]:Ss(l,r)})[d]?.at(-1);b&&!b.resultingState&&(b.resultingState=await(ye(t)?this.legacyStorage.getOperationResultingState?.(e,b.index,b.action.scope,"main"):this.legacyStorage.getDriveOperationResultingState?.(e,b.index,b.action.scope,"main")));const w=a.operations[d]||[],y=[];if(a=s.reducer(a,r.action,C=>{let U;switch(C.type){case"CREATE_CHILD_DOCUMENT":U=()=>this.addChild(e,C.input.id);break;case"DELETE_CHILD_DOCUMENT":U=()=>this.removeChild(e,C.input.id);break;case"COPY_CHILD_DOCUMENT":U=()=>this.addChild(e,C.input.newId);break}U&&y.push(()=>U().then(F=>({signal:C,result:F})))},{skip:r.skip,reuseOperationResultingState:!0,replayOptions:{operation:r}}),r.action.type==="NOOP"&&r.skip>0&&a.clipboard.length===0){const C=a.operations[d]||[],U=Dt(Ge(C)),F=Dt(Ge(w)),E=Es(F,U);a={...a,clipboard:Ge(E.filter(L=>L.action.type!=="NOOP")).reverse()}}const I=a.operations[r.action.scope];if(!I)throw new ie("ERROR",r,`No operations found for scope: ${r.action.scope}`);const N=I.filter(C=>C.index==r.index&&C.skip==r.skip).at(0);if(!N)throw new ie("ERROR",r,`Operation with index ${r.index}:${r.skip} was not applied.`);if(!N.error&&N.hash!==r.hash&&!n)throw this.logger.warn(JSON.stringify(N,null,2)),new hi(r,N);for(const C of y){const U=await C();o.push(U)}return{document:a,signals:o,operation:N}}addOperation(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this.addOperations(s,[o],a)}async _addOperations(e,t){if(this.legacyStorage.addDocumentOperationsWithTransaction)await this.legacyStorage.addDocumentOperationsWithTransaction(e,t);else{const r=await this.documentStorage.get(e),n=await t(r);n.operations.length>0&&await this.legacyStorage.addDocumentOperations(e,n.operations,n.document)}}async queueDocument(e,t){const{id:r,documentType:n,document:s}=Ct(e);if(!r)throw new Error("Document id is required",{cause:e});if(!n)throw new Error("Document type is required",{cause:e});if(await this.documentStorage.exists(r))throw new ke(r);let a;const d=new Promise((l,m)=>{const f=this.queueManager.on("jobCompleted",(w,y)=>{w.jobId===a&&(f(),b(),l(y))}),b=this.queueManager.on("jobFailed",(w,y)=>{w.jobId===a&&(f(),b(),m(y))})});try{a=await this.queueManager.addJob({documentId:r,documentType:n,initialState:s?.state,header:s?.header,options:t})}catch(l){throw this.logger.error("Error adding job",l),l}return d}queueOperation(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueOperations(s,[o],a)}async resultIfExistingOperations(e,t){try{const r=await this.getDocument(e);return t.find(s=>{if(!s.id)return!0;const o=r.operations[s.action.scope];return o?!o.find(a=>a.id===s.id&&a.index===s.index&&a.action.type===s.action.type&&a.hash===s.hash):!0})?void 0:{status:"SUCCESS",document:r,operations:t,signals:[]}}catch(r){r.message.includes(`Document with id ${e} not found`)||console.error(r);return}}queueOperations(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueOperations(s,o,a)}async _queueOperations(e,t,r){const n=await this.resultIfExistingOperations(e,t);if(n)return n;let s;const o=new Promise((a,d)=>{const l=this.queueManager.on("jobCompleted",(f,b)=>{f.jobId===s&&(l(),m(),a(b))}),m=this.queueManager.on("jobFailed",(f,b)=>{f.jobId===s&&(l(),m(),d(b))})});try{s=await this.queueManager.addJob({documentId:e,operations:t,options:r})}catch(a){throw this.logger.error("Error adding job",a),a}return o}queueAction(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueActions(s,[o],a)}queueActions(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueActions(s,o,a)}async _queueActions(e,t,r){try{const n=await this.queueManager.addJob({documentId:e,actions:t,options:r});return await new Promise((s,o)=>{const a=this.queueManager.on("jobCompleted",(l,m)=>{l.jobId===n&&(a(),d(),s(m))}),d=this.queueManager.on("jobFailed",(l,m)=>{l.jobId===n&&(a(),d(),o(m))})})}catch(n){throw this.logger.error("Error adding job",n),n}}async queueDriveAction(e,t,r){return this.queueDriveActions(e,[t],r)}async queueDriveActions(e,t,r){try{const n=await this.queueManager.addJob({documentId:e,actions:t,options:r});return await new Promise((s,o)=>{const a=this.queueManager.on("jobCompleted",(l,m)=>{l.jobId===n&&(a(),d(),s(m))}),d=this.queueManager.on("jobFailed",(l,m)=>{l.jobId===n&&(a(),d(),o(m))})})}catch(n){throw this.logger.error("Error adding drive job",n),n}}addOperations(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueOperations(s,o,a)}async processOperations(e,t,r){const n=await this.resultIfExistingOperations(e,t);if(n)return n;let s;const o=[],a=[];let d;try{await this._addOperations(e,async w=>{const y=await this._processOperations(e,w,t);if(!y.document)throw this.logger.error("Invalid document"),y.error??new Error("Invalid document");return s=y.document,d=y.error,a.push(...y.signals),o.push(...y.operationsApplied),{operations:y.operationsApplied,document:y.document}});const l=new Array;if(s){this.cache.setDocument(e,s).catch(this.logger.error);for(const w of o){const y={documentId:e,documentType:s.header.documentType,scope:w.action.scope,branch:"main",revision:w.index+1,lastUpdated:w.timestampUtcMs};l.some(_=>_.documentId===y.documentId&&_.scope===y.scope&&_.branch===y.branch)||l.push(y)}}const f=o.find(w=>!t.find(y=>y.id===w.id&&y.index===w.index&&y.skip===w.skip&&y.hash===w.hash))?{type:"local"}:r?.source??{type:"local"},b=this.getOperationSource(f);if(l.length&&this.listenerManager.updateSynchronizationRevisions(l,f,()=>{this.synchronizationManager.updateSyncStatus(e,{[b]:"SYNCING"});for(const w of l)this.synchronizationManager.updateSyncStatus(w,{[b]:"SYNCING"})},this.handleListenerError.bind(this),r?.forceSync??f.type==="local").then(w=>{w.length&&this.synchronizationManager.updateSyncStatus(e,{[b]:"SUCCESS"});for(const y of l)this.synchronizationManager.updateSyncStatus(y,{[b]:"SUCCESS"})}).catch(w=>{this.logger.error("Non handled error updating sync revision",w),this.synchronizationManager.updateSyncStatus(e,{[b]:"ERROR"},w);for(const y of l)this.synchronizationManager.updateSyncStatus(y,{[b]:"ERROR"},w)}),d)throw d;return this.eventEmitter.emit("documentOperationsAdded",e,t),this.eventEmitter.emit("operationsAdded",e,t),{status:"SUCCESS",document:s,operations:o,signals:a}}catch(l){const m=l instanceof ie?l:new ie("ERROR",void 0,l.message,l.cause);return{status:m.status,error:m,document:s,operations:o,signals:a}}}addDriveOperation(e,t,r){return this.addDriveOperations(e,[t],r)}async _addDriveOperations(e,t){if(this.legacyStorage.addDriveOperationsWithTransaction)return this.legacyStorage.addDriveOperationsWithTransaction(e,t);{const r=await this.documentStorage.get(e),n=await t(r);return n.operations.length>0&&await this.legacyStorage.addDriveOperations(e,n.operations,n.document),n}}queueDriveOperation(e,t,r){return this.queueDriveOperations(e,[t],r)}async resultIfExistingDriveOperations(e,t){try{const r=await this.getDrive(e);return t.find(s=>{if(!s.id)return!0;const o=r.operations[s.action.scope];return o?!o.find(a=>a.id===s.id&&a.index===s.index&&a.action.type===s.action.type&&a.hash===s.hash):!0})?void 0:{status:"SUCCESS",document:r,operations:t,signals:[]}}catch(r){console.error(r);return}}async queueDriveOperations(e,t,r){const n=await this.resultIfExistingDriveOperations(e,t);if(n)return n;try{const s=await this.queueManager.addJob({documentId:e,operations:t,options:r});return await new Promise((o,a)=>{const d=this.queueManager.on("jobCompleted",(m,f)=>{m.jobId===s&&(d(),l(),o(f))}),l=this.queueManager.on("jobFailed",(m,f)=>{m.jobId===s&&(d(),l(),a(f))})})}catch(s){throw this.logger.error("Error adding drive job",s),s}}async addDriveOperations(e,t,r){return this.queueDriveOperations(e,t,r)}async processDriveOperations(e,t,r){let n;const s=[],o=[];let a;const d=await this.resultIfExistingDriveOperations(e,t);if(d)return d;try{if(await this._addDriveOperations(e,async m=>{const f=await this._processOperations(e,m,t.slice());return n=f.document,s.push(...f.operationsApplied),o.push(...f.signals),a=f.error,{operations:f.operationsApplied,document:f.document}}),!n||!ye(n))throw a??new Error("Invalid Document Drive document");this.cache.setDocument(e,n).catch(this.logger.error),this.cache.setDrive(e,n).catch(this.logger.error);const l=s.filter(m=>m.action.scope==="global").slice().pop();if(l){const f=s.find(w=>!t.find(y=>y.id===w.id&&y.index===w.index&&y.skip===w.skip&&y.hash===w.hash))?{type:"local"}:r?.source??{type:"local"},b=this.getOperationSource(f);this.listenerManager.updateSynchronizationRevisions([{documentId:e,documentType:n.header.documentType,scope:"global",branch:"main",lastUpdated:l.timestampUtcMs,revision:l.index}],f,()=>{this.synchronizationManager.updateSyncStatus(e,{[b]:"SYNCING"})},this.handleListenerError.bind(this),r?.forceSync??f.type==="local").then(w=>{w.length&&this.synchronizationManager.updateSyncStatus(e,{[b]:"SUCCESS"})}).catch(w=>{this.logger.error("Non handled error updating sync revision",w),this.synchronizationManager.updateSyncStatus(e,{[b]:"ERROR"},w)})}if(this.shouldSyncRemoteDrive(n)?this.startSyncRemoteDrive(e).catch(this.logger.error):this.stopSyncRemoteDrive(e).catch(this.logger.error),a)throw a;return this.eventEmitter.emit("driveOperationsAdded",e,t),this.eventEmitter.emit("operationsAdded",e,t),{status:"SUCCESS",document:n,operations:s,signals:o}}catch(l){const m=l instanceof ie?l:new ie("ERROR",void 0,l.message,l);return{status:m.status,error:m,document:n,operations:s,signals:o}}}_buildOperations(e,t){const r=[],{reducer:n}=this.getDocumentModelModule(e.header.documentType);for(const s of t){e=n(e,s);const o=e.operations[s.scope];if(!o)throw new Error(`No operations found for scope: ${s.scope}`);const a=o.slice().pop();if(!a)throw new Error("Error creating operations");r.push(a)}return r}addAction(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._addAction(s,o,a)}async _addAction(e,t,r){return this.addActions(e,[t],r)}addActions(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueActions(s,o,a)}async processActions(e,t,r){const n=await this.getDocument(e),s=this._buildOperations(n,t);return this.processOperations(e,s,r)}async addDriveAction(e,t,r){return"synchronizationUnits"in t.input?this._legacyAddFileAction(e,t,r):this.addDriveActions(e,[t],r)}async _legacyAddFileAction(e,t,r){const n=this.getDocumentModelModule(t.input.documentType).utils.createDocument(t.input.document?.state||void 0);n.header.id=t.input.id,n.header.name=t.input.name,n.header.documentType=t.input.documentType,await this.queueDocument({document:n},{source:r?.source||{type:"local"}});const s={...t,input:{id:t.input.id,documentType:n.header.documentType,name:t.input.name,parentFolder:t.input.parentFolder}};return await this.addAction(e,s,r)}async addDriveActions(e,t,r){return this.queueDriveActions(e,t,r)}async processDriveActions(e,t,r){const n=await this.getDrive(e),s=this._buildOperations(n,t);return this.processDriveOperations(e,s,r)}async detachDrive(e){const t=await this.getDrive(e),r=t.state.local.listeners||[],n=t.state.local.triggers||[];for(const s of r)await this.addDriveAction(e,en({listenerId:s.listenerId}));for(const s of n)await this.addDriveAction(e,tn({triggerId:s.id}));await this.addDriveAction(e,Zr({type:"LOCAL"}))}getSyncStatus(e,t,r){return this.synchronizationManager.getSyncStatus(e,t,r)}on(e,t){return this.eventEmitter.on(e,t)}emit(e,...t){return this.eventEmitter.emit(e,...t)}updateSyncStatus(e,t,r){this.synchronizationManager.updateSyncStatus(e,t,r)}initializeDriveSyncStatus(e,t){return this.synchronizationManager.initializeDriveSyncStatus(e,t)}getCombinedSyncUnitStatus(e){return this.synchronizationManager.getCombinedSyncUnitStatus(e)}async saveStrand(e,t){const r=!await this.documentStorage.exists(e.documentId);let n;r&&(n=await this.queueDocument({id:e.documentId,documentType:e.documentType}));const s=e.operations.map(o=>({...o,action:{id:o.actionId,timestampUtcMs:o.timestampUtcMs,type:o.type,input:o.input,context:o.context,scope:e.scope},scope:e.scope,branch:e.branch}));if((!r||n?.status==="SUCCESS")&&s.length)try{n=await this.queueOperations(e.documentId,s,{source:t})}catch(o){throw this.logger.error("Error queueing operations",o),o}if(!n)return this.logger.debug(`Document ${e.documentId} already exists`),{status:"SUCCESS",document:await this.getDocument(e.documentId),operations:[],signals:[]};if(n.status==="ERROR"){const o=this.getOperationSource(t);this.synchronizationManager.updateSyncStatus({documentId:e.documentId||e.driveId,scope:e.scope,branch:e.branch},{[o]:n.status},n.error)}return this.eventEmitter.emit("strandUpdate",e),n}setGenerateJwtHandler(e){this.generateJwtHandler=e,this.listenerManager.setGenerateJwtHandler(e)}removeJwtHandler(){this.generateJwtHandler=void 0,this.listenerManager.removeJwtHandler()}}const po=eo(go);class at extends Error{constructor(e){super(e||"Aborted"),this.name="AbortError"}}class mo{logger=pe(["MemoryStorage"]);documents;driveManifests;slugToDocumentId;constructor(){this.documents={},this.driveManifests={},this.slugToDocumentId={}}resolveIds(e,t){const r=[];for(const n of e){const s=this.slugToDocumentId[n];if(!s)throw new we(n);r.push(s)}if(t?.aborted)throw new at("Aborted");return Promise.resolve(r)}resolveSlugs(e,t){const r=[];for(const n of e){const s=this.documents[n];if(!s)throw new we(n);r.push(s.header.slug)}if(t?.aborted)throw new at("Aborted");return Promise.resolve(r)}exists(e){return Promise.resolve(!!this.documents[e])}create(e){const t=e.header.id;if(!tt(t))throw new et(t);if(this.documents[t])throw new ke(t);const r=e.header.slug?.length>0?e.header.slug:t;if(!nn(r))throw new rn(r);if(r&&this.slugToDocumentId[r])throw new ke(t,Fe.SLUG);return e.header.slug=r,this.documents[t]=e,r&&(this.slugToDocumentId[r]=t),e.header.documentType==="powerhouse/document-drive"&&this.updateDriveManifest(t,{documentIds:new Set}),Promise.resolve()}get(e){const t=this.documents[e];return t?Promise.resolve(t):Promise.reject(new we(e))}getBySlug(e){const t=this.slugToDocumentId[e];return t?this.get(t):Promise.reject(new we(e))}async findByType(e,t=100,r){const n=Object.entries(this.documents).filter(([d,l])=>l.header.documentType===e).map(([d,l])=>({id:d,document:l}));n.sort((d,l)=>{const m=new Date(d.document.header.createdAtUtcIso),f=new Date(l.document.header.createdAtUtcIso);if(m.getTime()===f.getTime()){const b=d.id,w=l.id;return b.localeCompare(w)}return m.getTime()-f.getTime()});let s=0;if(r){const d=n.findIndex(({id:l})=>l===r);d!==-1&&(s=d)}const o=Math.min(s+t,n.length);let a;return o<n.length&&(a=n[o].id),{documents:n.slice(s,o).map(({id:d})=>d),nextCursor:a}}async delete(e){const t=this.documents[e];if(t){const n=t.header.slug?.length>0?t.header.slug:e;n&&this.slugToDocumentId[n]===e&&delete this.slugToDocumentId[n]}const r=await this.getParents(e);for(const n of r)await this.removeChild(n,e);return delete this.driveManifests[e],this.documents[e]?(delete this.documents[e],Promise.resolve(!0)):Promise.resolve(!1)}async addChild(e,t){if(e===t)return Promise.reject(new Error("Cannot associate a document with itself"));if((await this.getChildren(t)).includes(e))return Promise.reject(new Error("Cannot associate a document with its child"));const n=this.getManifest(e);return n.documentIds.add(t),this.updateDriveManifest(e,n),Promise.resolve()}async removeChild(e,t){const r=this.getManifest(e);return r.documentIds.delete(t)?(this.updateDriveManifest(e,r),Promise.resolve(!0)):Promise.resolve(!1)}async getChildren(e){return[...this.getManifest(e).documentIds]}async getParents(e){const t=[];for(const[r,n]of Object.entries(this.driveManifests))n.documentIds.has(e)&&t.push(r);return t}async clear(){this.documents={},this.driveManifests={},this.slugToDocumentId={}}async addDocumentOperations(e,t,r){const n=await this.get(e);if(!r)return Promise.reject(new we(e));const s=st(n.operations,t),o={};for(const[a,d]of Object.entries(s))o[a]=Ie(d);this.documents[e]={...n,state:r.state,initialState:r.initialState,header:{...n.header,...r.header,revision:o},operations:s,clipboard:r.clipboard}}async addDriveOperations(e,t,r){const n=await this.get(e),s=st(n.operations,t),o={};for(const[a,d]of Object.entries(s))o[a]=Ie(d);this.documents[e]={...n,state:r.state,initialState:r.initialState,header:{...n.header,...r.header,revision:o},operations:s,clipboard:r.clipboard}}async getSynchronizationUnitsRevision(e){return(await Promise.allSettled(e.map(async r=>{try{const n=await this.get(r.documentId);if(!n||!Object.keys(n.state).includes(r.scope))return;const s=n.operations[r.scope];return s?{documentId:r.documentId,documentType:r.documentType,scope:r.scope,branch:r.branch,lastUpdated:s.at(-1)?.timestampUtcMs??n.header.createdAtUtcIso,revision:s.length>0?Ie(s):0}:void 0}catch(n){this.logger.error("Error getting synchronization units revision",n);return}}))).reduce((r,n)=>(n.status==="fulfilled"&&n.value!==void 0&&r.push(n.value),r),[])}async findStorageUnitsBy(e,t,r){const n=[],{parentId:s,documentId:o,documentModelType:a,scope:d}=sn(e);let l;if(s){const w=new Set;for(const y of s)(await this.getChildren(y)).forEach(_=>w.add(_));l=on(s,w)}else l=new Set(Object.keys(this.documents));l=o?an(o,l):l;for(const w of l){const y=this.documents[w];if(y&&!(a&&!a.has(y.header.documentType)))for(const[I]of Object.entries(y.state))d&&!d.has(I)||n.push({documentId:w,documentModelType:y.header.documentType,scope:I,branch:"main"})}let m=0;if(r){const w=n.findIndex(y=>y.documentId===r);w!==-1&&(m=w)}const f=Math.min(m+t,n.length),b=f<n.length?n[f].documentId:void 0;return{units:n.slice(m,f),nextCursor:b}}getManifest(e){return this.driveManifests[e]||(this.driveManifests[e]={documentIds:new Set}),this.driveManifests[e]}updateDriveManifest(e,t){this.driveManifests[e]=t}}class yo{emitter=hn();emit(e,...t){return this.emitter.emit(e,...t)}on(e,t){return this.emitter.on(e,t)}}class X{internalMap=new Map;static keySeparator="|";static escape(e){return e.replace(/\|/g,"\\|")}static unescape(e){return e.replace(/\\\|/g,"|")}static buildKey(e){return`${X.escape(e.documentId)}${X.keySeparator}${X.escape(e.scope)}${X.keySeparator}${X.escape(e.branch)}`}static parseKey(e){const t=e.split(new RegExp("(?<!\\\\)\\|")).map(o=>X.unescape(o)),[r,n,s]=t;return{documentId:r,scope:n,branch:s}}set(e,t){return this.internalMap.set(X.buildKey(e),t),this}get(e){return this.internalMap.get(X.buildKey(e))}has(e){return this.internalMap.has(X.buildKey(e))}delete(e){return this.internalMap.delete(X.buildKey(e))}clear(){this.internalMap.clear()}get size(){return this.internalMap.size}keys(e){const t=this.internalMap.keys();return{[Symbol.iterator](){return this},next(){for(;;){const r=t.next();if(r.done)return{done:!0,value:void 0};const n=r.value,s=X.parseKey(n);if(!(e&&(s.documentId!==e.documentId||e.scope!==void 0&&s.scope!==e.scope)))return{done:!1,value:s}}}}}values(e){const t=this.internalMap.entries();return{[Symbol.iterator](){return this},next(){for(;;){const r=t.next();if(r.done)return{done:!0,value:void 0};const[n,s]=r.value,o=X.parseKey(n);if(!(e&&(o.documentId!==e.documentId||e.scope!==void 0&&o.scope!==e.scope)))return{done:!1,value:s}}}}}entries(e){const t=this.internalMap.entries();return{[Symbol.iterator](){return this},next(){for(;;){const r=t.next();if(r.done)return{done:!0,value:void 0};const[n,s]=r.value,o=X.parseKey(n);if(!(e&&(o.documentId!==e.documentId||e.scope!==void 0&&o.scope!==e.scope)))return{done:!1,value:[o,s]}}}}}[Symbol.iterator](){return this.entries()}forEach(e,t){for(const[r,n]of this.entries())e.call(t,n,r,this)}deleteByDocumentId(e){for(const t of this.internalMap.keys())t.startsWith(e+X.keySeparator)&&this.internalMap.delete(t)}deleteByDocumentIdAndScope(e,t){const r=`${e}${X.keySeparator}${t}${X.keySeparator}`;for(const n of this.internalMap.keys())n.startsWith(r)&&this.internalMap.delete(n)}getAllByDocumentId(e){const t=[];for(const[r,n]of this.internalMap.entries())r.startsWith(e+X.keySeparator)&&t.push([X.parseKey(r),n]);return t}getAllByDocumentIdAndScope(e,t){const r=`${e}${X.keySeparator}${t}${X.keySeparator}`,n=[];for(const[s,o]of this.internalMap.entries())s.startsWith(r)&&n.push([X.parseKey(s),o]);return n}}function vo(i,e=250){let t;return(r=!1,...n)=>(t&&clearTimeout(t),new Promise((s,o)=>{r?i(...n).then(s).catch(o):t=setTimeout(()=>{i(...n).then(s).catch(o)},e)}))}class qt{static LISTENER_UPDATE_DELAY=250;logger=pe(["ListenerManager",Math.floor(Math.random()*999).toString()]);syncManager;options;generateJwtHandler;listenerStateByDriveId=new Map;constructor(e,t=ot){this.syncManager=e,this.options={...ot,...t},this.logger.verbose("constructor(...)")}setGenerateJwtHandler(e){this.generateJwtHandler=e}removeJwtHandler(){this.generateJwtHandler=void 0}async initialize(e){this.logger.verbose("initialize(...)"),typeof window<"u"&&window.addEventListener("online",()=>{this.triggerUpdate(!1,{type:"local"},void 0,e).catch(t=>{this.logger.error("Non handled error updating listeners",t)})})}driveHasListeners(e){return this.listenerStateByDriveId.has(e)}async setListener(e,t){if(this.logger.verbose(`setListener(drive: ${e}, listener: ${t.listenerId})`),e!==t.driveId)throw new Error("Drive ID mismatch");let r;try{r=this.getListenerState(e,t.listenerId)}catch{r={}}this.setListenerState(e,t.listenerId,{...r,block:t.block,driveId:t.driveId,pendingTimeout:"0",listener:t,listenerStatus:"CREATED",syncUnits:new X}),await this.triggerUpdate(!0,{type:"local"})}async removeListener(e,t){this.logger.verbose("setListener()");const r=this.listenerStateByDriveId.get(e);return r?Promise.resolve(r.delete(t)):!1}async removeSyncUnits(e,t){const r=this.listenerStateByDriveId.get(e);if(r){for(const[,n]of r)for(const s of t)n.syncUnits.delete(s);return Promise.resolve()}}async updateSynchronizationRevisions(e,t,r,n,s=!1){const o=this.listenerStateByDriveId.values(),a=[];for(const[[d,l]]of o)if(!(a.find(f=>f.listenerId===l.listener.listenerId)||!l.listener.transmitter?.transmit))for(const f of e){if(!this._checkFilter(l.listener.filter,f))continue;const b=l.syncUnits.get(f);if(!b||b.listenerRev<f.revision){a.push(l.listener);break}}return this.triggerUpdate(s,t,r,n)}async updateListenerRevision(e,t,r,n){const s=this.listenerStateByDriveId.get(t);if(!s)return;const o=s.get(e);if(!o)return;const a=new Date().toISOString();return o.syncUnits.set(r,{listenerRev:n,lastUpdated:a}),Promise.resolve()}triggerUpdate=vo(this._triggerUpdate.bind(this),qt.LISTENER_UPDATE_DELAY);async _triggerUpdate(e,t,r,n=500){if(this.logger.verbose(`_triggerUpdate(source: ${e.type}, maxContinues: ${n})`,this.listenerStateByDriveId),n<0)throw new Error("Maximum retries exhausted.");const s=[];for(const[o,a]of this.listenerStateByDriveId)for(const[d,l]of a){const m=l.listener.transmitter;if(!m?.transmit)continue;const f=await this.getListenerSyncUnits(o,d),b=[];this.logger.verbose("syncUnits",f);const w=f.map(y=>async()=>{const I=l.syncUnits.get(y);if(I&&I.listenerRev>=y.revision){this.logger.verbose(`Abandoning push for sync unit ${JSON.stringify(y)}: already up-to-date (${I.listenerRev} >= ${y.revision})`);return}else this.logger.verbose(`Listener out-of-date for sync unit (${y.scope}, ${y.documentId}): ${I?.listenerRev} < ${y.revision}`);const _=[];if(y.revision>0){try{const N=await this.syncManager.getOperationData(y,{fromRevision:I?.listenerRev});_.push(...N)}catch(N){this.logger.error(N)}if(!_.length){this.logger.verbose(`Abandoning push for ${JSON.stringify(y)}: no operations found`);return}}b.push({driveId:o,documentType:y.documentType,documentId:y.documentId,branch:y.branch,operations:_,scope:y.scope})});if(this.options.sequentialUpdates){this.logger.verbose(`Collecting ${w.length} syncUnit strandUpdates in sequence`);for(const y of w)await y()}else this.logger.verbose(`Collecting ${w.length} syncUnit strandUpdates in parallel`),await Promise.all(w.map(y=>y()));if(b.length==0){this.logger.verbose(`No strandUpdates needed for listener ${d}`);continue}l.pendingTimeout=new Date(new Date().getTime()/1e3+300).toISOString(),l.listenerStatus="PENDING";try{this.logger.verbose(`_triggerUpdate(source: ${e.type}) > transmitter.transmit`);const y=await m.transmit(b,e);this.logger.verbose(`_triggerUpdate(source: ${e.type}) > transmission succeeded`,y),l.pendingTimeout="0",l.listenerStatus="PENDING";const I=new Date().toISOString();let _=!1;for(const N of y){const C=f.find(U=>N.documentId===U.documentId&&N.scope===U.scope&&N.branch===U.branch);if(C){l.syncUnits.set(C,{lastUpdated:I,listenerRev:N.revision});const U=b.find(F=>F.driveId===N.driveId&&F.documentId===N.documentId&&F.scope===N.scope&&F.branch===N.branch);if(U&&U.operations.length>0){const F=U.operations.at(-1)?.index;F!==N.revision?(this.logger.verbose(`Revision still out-of-date for ${U.documentId}:${U.scope}:${U.branch} ${F} <> ${N.revision}`),_=!0):this.logger.verbose(`Revision match for ${U.documentId}:${U.scope}:${U.branch} ${F}`)}}else this.logger.warn(`Received revision for untracked unit for listener ${l.listener.listenerId}`,N)}for(const N of y){const C=N.status==="ERROR";if(N.error?.includes("Missing operations"))_=!0;else if(C)throw new ie(N.status,void 0,N.error,N.error)}if(!_)s.push({listenerId:l.listener.listenerId,listenerRevisions:y});else{const N=await this._triggerUpdate(e,t,r,n-1);s.push(...N)}l.listenerStatus="SUCCESS"}catch(y){r?.(y,o,l),l.listenerStatus=y instanceof ie?y.status:"ERROR"}}return this.logger.verbose(`Returning listener updates (maxContinues: ${n})`,s),s}_checkFilter(e,t){const{branch:r,documentId:n,scope:s,documentType:o}=t;return!!((!e.branch||e.branch.includes(r)||e.branch.includes("*"))&&(!e.documentId||e.documentId.includes(n)||e.documentId.includes("*"))&&(!e.scope||e.scope.includes(s)||e.scope.includes("*"))&&(!e.documentType||e.documentType.includes(o)||e.documentType.includes("*")))}getListenerSyncUnits(e,t){const r=this.listenerStateByDriveId.get(e)?.get(t);if(!r)return[];const n=r.listener.filter;return this.syncManager.getSynchronizationUnits(e,n.documentId??["*"],n.scope??["*"],n.branch??["*"],n.documentType??["*"])}async removeDrive(e){const t=this.listenerStateByDriveId.get(e);if(t){this.listenerStateByDriveId.delete(e);for(const[r,n]of t)try{await n.listener.transmitter?.disconnect?.()}catch(s){this.logger.error(s)}}}async getStrands(e,t,r){this.logger.verbose(`[SYNC DEBUG] ListenerManager.getStrands called for drive: ${e}, listener: ${t}, options: ${JSON.stringify(r||{})}`);let n;try{n=this.getListenerState(e,t),this.logger.verbose(`[SYNC DEBUG] Found listener state for drive: ${e}, listener: ${t}, status: ${n.listenerStatus}`)}catch(o){throw this.logger.error(`[SYNC DEBUG] Failed to find listener state for drive: ${e}, listener: ${t}. Error: ${o}`),o}const s=[];try{const o=await this.getListenerSyncUnits(e,t);this.logger.verbose(`[SYNC DEBUG] Retrieved ${o.length} sync units for drive: ${e}, listener: ${t}`);const a=r?.limit;let d=0;const l=o.map(m=>async()=>{if(a&&d>=a)return;if(m.revision<0){this.logger.verbose(`[SYNC DEBUG] Skipping sync unit with negative revision: ${JSON.stringify(m)}, revision: ${m.revision}`);return}const f=n.syncUnits.get(m);if(f&&f.listenerRev>=m.revision){this.logger.verbose(`[SYNC DEBUG] Skipping sync unit - listener already up to date: ${JSON.stringify(m)}, listenerRev: ${f.listenerRev}, revision: ${m.revision}`);return}const{documentId:b,scope:w,branch:y}=m;let I=[];try{m.revision>0&&(this.logger.verbose(`[SYNC DEBUG] Getting operations for syncUnit: ${JSON.stringify(m)}`),I=await this.syncManager.getOperationData(m,{since:r?.since,fromRevision:r?.fromRevision??f?.listenerRev,limit:a?a-d:void 0})),this.logger.verbose(`[SYNC DEBUG] Retrieved ${I.length} operations for syncUnit: ${JSON.stringify(m)}`),d+=I.length,s.push({driveId:e,documentId:b,documentType:m.documentType,scope:w,branch:y,operations:I}),this.logger.verbose(`[SYNC DEBUG] Added strand with ${I.length} operations for syncUnit: ${JSON.stringify(m)}`)}catch(_){this.logger.error(`Error getting operations for syncUnit: ${JSON.stringify(m)}, error: ${_}`);return}});if(this.options.sequentialUpdates){this.logger.verbose(`[SYNC DEBUG] Processing ${l.length} sync units sequentially`);for(const m of l)await m()}else this.logger.verbose(`[SYNC DEBUG] Processing ${l.length} sync units in parallel`),await Promise.all(l.map(m=>m()))}catch(o){this.logger.error(`Error in getStrands: ${o}`)}return this.logger.verbose(`ListenerManager.getStrands returning ${s.length} strands for drive: ${e}, listener: ${t}`),s}getListenerState(e,t){let r=this.listenerStateByDriveId.get(e);r||(r=new Map,this.listenerStateByDriveId.set(e,r));const n=r.get(t);if(!n)throw new Error("Listener not found");return n}setListenerState(e,t,r){let n=this.listenerStateByDriveId.get(e);n||(n=new Map,this.listenerStateByDriveId.set(e,n)),n.set(t,r)}}class wo{storage;documentStorage;cache;documentModelModules;eventEmitter;syncStatus=new X;logger=pe(["SynchronizationManager"]);constructor(e,t,r,n,s){this.storage=e,this.documentStorage=t,this.cache=r,this.documentModelModules=n,this.eventEmitter=s}async getSynchronizationUnits(e,t,r,n,s){const o=await this.getSynchronizationUnitsIds(e,t,r,n,s);return this.logger.verbose(`getSynchronizationUnits query: ${JSON.stringify(o)}`),(await this.getSynchronizationUnitsRevision(o)).filter(d=>typeof d<"u")}async getSynchronizationUnitsRevision(e){const t=await this.storage.getSynchronizationUnitsRevision(e);return this.logger.verbose(`getSynchronizationUnitsRevision: ${JSON.stringify(t)}`),e.map(r=>t.find(n=>n.documentId===r.documentId&&n.scope===r.scope&&n.branch===r.branch))}async getSynchronizationUnitsIds(e,t,r,n,s){const o={parentId:e?[e]:void 0,documentId:t,documentModelType:s,scope:r,branch:n};let a;const d=[];do{const{units:l,nextCursor:m}=await this.documentStorage.findStorageUnitsBy(o,100,a);d.push(...l),a=m}while(a);return d.reduce((l,{documentModelType:m,...f})=>f.scope==="local"?l:l.concat([{...f,documentType:m}]),new Array)}async getSynchronizationUnit(e){const{scope:t,branch:r,documentId:n}=e,s=await this.getDocument(n);if(!Object.keys(s.state).includes(t))return;const o=s.operations[t]??[],a=o.at(-1);return{scope:t,branch:r,documentId:n,documentType:s.header.documentType,lastUpdated:a?.timestampUtcMs??s.header.lastModifiedAtUtcIso,revision:Ie(o)}}async getOperationData(e,t){this.logger.verbose(`[SYNC DEBUG] SynchronizationManager.getOperationData called for syncId: ${JSON.stringify(e)}, filter: ${JSON.stringify(t)}`);const r=await this.getDocument(e.documentId);this.logger.verbose(`[SYNC DEBUG] Retrieved document ${r.header.id} with type: ${r.header.documentType}`);const n=r.operations[e.scope]??[];this.logger.verbose(`[SYNC DEBUG] Found ${n.length} total operations in scope ${e.scope}`);const s=n.filter(a=>Object.keys(t).length===0||(t.since===void 0||Ci(t.since,a.timestampUtcMs))&&(t.fromRevision===void 0||a.index>=t.fromRevision));this.logger.verbose(`[SYNC DEBUG] Filtered to ${s.length} operations based on filter criteria`+(t.fromRevision!==void 0?` (fromRevision: ${t.fromRevision})`:""));const o=t.limit?s.slice(0,t.limit):s;if(this.logger.verbose(`[SYNC DEBUG] Returning ${o.length} operations after applying limit`),o.length>0){const a=o[0],d=o[o.length-1];this.logger.verbose(`[SYNC DEBUG] First operation: index=${a.index}, type=${a.action.type}`),this.logger.verbose(`[SYNC DEBUG] Last operation: index=${d.index}, type=${d.action.type}`)}return o.map(a=>({actionId:a.action.id,hash:a.hash,index:a.index,timestampUtcMs:a.timestampUtcMs,type:a.action.type,input:a.action.input,skip:a.skip,context:a.action.context,id:a.id}))}async getDocument(e){try{const r=await this.cache.getDocument(e);if(r)return r}catch(r){this.logger.error("Error getting document from cache",r)}const t=await this.documentStorage.get(e);return this._buildDocument(t)}_buildDocument(e){const t=this.getDocumentModelModule(e.header.documentType),r=Ve(e.operations);return Cr(e.initialState,r,t.reducer,void 0,e.header,void 0,{checkHashes:!0,reuseOperationResultingState:!0})}setDocumentModelModules(e){this.documentModelModules=e}getDocumentModelModule(e){const t=this.documentModelModules.find(r=>r.documentModel.global.id===e);if(!t)throw new Error(`Document type ${e} not supported`);return t}getCombinedSyncUnitStatus(e){if(!e.pull&&!e.push||e.pull==="INITIAL_SYNC")return"INITIAL_SYNC";if(e.push==="INITIAL_SYNC")return e.pull||"INITIAL_SYNC";const t=["ERROR","MISSING","CONFLICT","SYNCING","SUCCESS"];return Object.values(e).sort((n,s)=>t.indexOf(n)-t.indexOf(s))[0]}getSyncStatus(e,t="global",r="main"){const n=typeof e=="string"?{documentId:e,scope:t,branch:r}:e,s=this.syncStatus.get(n);return s?this.getCombinedSyncUnitStatus(s):new fi(n)}updateSyncStatus(e,t,r,n="global",s="main"){const o=typeof e=="string"?{documentId:e,scope:n,branch:s}:e;if(t===null){this.syncStatus.delete(o);return}const a=this.syncStatus.get(o);if(!a){this.initSyncStatus(o,t);return}if(Object.entries(t).some(([l,m])=>a[l]!==m)){const l=Object.entries(t).reduce((b,[w,y])=>({...b,[w]:b[w]==="INITIAL_SYNC"&&y==="SYNCING"?"INITIAL_SYNC":y}),a),m=this.getCombinedSyncUnitStatus(a),f=this.getCombinedSyncUnitStatus(l);this.syncStatus.set(o,l),m!==f&&this.eventEmitter&&this.eventEmitter.emit("syncStatus",o.documentId,this.getCombinedSyncUnitStatus(l),r,l,o.scope,o.branch)}}initSyncStatus(e,t){const r=Object.entries(t).reduce((n,[s,o])=>({...n,[s]:o!=="SYNCING"?o:"INITIAL_SYNC"}),{});this.syncStatus.set(e,r),this.eventEmitter&&this.eventEmitter.emit("syncStatus",e.documentId,this.getCombinedSyncUnitStatus(r),void 0,r,e.scope,e.branch)}async initializeDriveSyncStatus(e,t){const r=await this.getSynchronizationUnitsIds(e),n={pull:t.state.local.triggers.length>0?"INITIAL_SYNC":void 0,push:t.state.local.listeners.length>0?"SUCCESS":void 0};if(!n.pull&&!n.push)return;const s=[{documentId:e,scope:"global",branch:"main"},...r];for(const o of s)this.initSyncStatus(o,n)}}class bo{listenerManager;constructor(e){this.listenerManager=e}instance(e,t,r){switch(e){case"SwitchboardPush":{if(!t.callInfo?.data)throw new Error("No call info data: "+JSON.stringify(t));return new pn(t.callInfo.data,this.listenerManager)}case"Internal":throw new Error("Internal transmitter not implemented");default:return new ce(t,this.listenerManager)}}}let Po=class{documentModelModules=[];storage;cache;queueManager;eventEmitter;options;synchronizationManager;listenerManager;transmitterFactory;constructor(e){this.documentModelModules=e}withStorage(e){return this.storage=e,this}withCache(e){return this.cache=e,this}withQueueManager(e){return this.queueManager=e,this}withEventEmitter(e){return this.eventEmitter=e,this}withSynchronizationManager(e){return this.synchronizationManager=e,this}withListenerManager(e){return this.listenerManager=e,this}withTransmitterFactory(e){return this.transmitterFactory=e,this}withOptions(e){return this.options=e,this}build(){if(this.storage||(this.storage=new mo),this.cache||(this.cache=new Us),this.queueManager||(this.queueManager=new Bi),this.eventEmitter||(this.eventEmitter=new yo),this.synchronizationManager||(this.synchronizationManager=new wo(this.storage,this.storage,this.cache,this.documentModelModules,this.eventEmitter)),!this.listenerManager){const e={...ot,...this.options?.listenerManager};this.listenerManager=new qt(this.synchronizationManager,e)}return this.transmitterFactory||(this.transmitterFactory=new bo(this.listenerManager)),new po(this.documentModelModules,this.storage,this.storage,this.cache,this.queueManager,this.eventEmitter,this.synchronizationManager,this.listenerManager,{...this.options,featureFlags:{enableDualActionCreate:!1,...this.options?.featureFlags}})}};function Or(i){let e=!1;const t=Object.entries(i.operations).reduce((r,[n,s])=>{const o=n;if(!s)return r;for(const a of s){const d=Do(a),l=r[o];l&&l.push(d),d!==a&&(e=!0)}return r},{global:[],local:[]});return e?{...i,operations:t}:i}function Do(i){let e=!1,t={...i};const r=i.context?.signer,n=i.action?.context?.signer;if(r){if("signature"in r){const s=r.signature;t={...t,context:{...t.context,signer:{user:r.user,app:r.app,signatures:s?.length?[s]:[]}}},e=!0}else if(r.signatures){const s=r.signatures.filter(o=>o&&o.length>0);s.length!==r.signatures.length&&(t={...t,context:{...t.context,signer:{...r,signatures:s}}},e=!0)}}if(n){if("signature"in n){const s=n.signature,o={...t.action.context,signer:{user:n.user,app:n.app,signatures:s?.length?[s]:[]}};t={...t,action:{...t.action,context:o},context:o},e=!0}else if(n.signatures){const s=n.signatures.filter(o=>o&&o.length>0);if(s.length!==n.signatures.length){const o={...t.action.context,signer:{...n,signatures:s}};t={...t,action:{...t.action,context:o},context:o},e=!0}}}return e?t:i}var xt={exports:{}};var _r;function So(){return _r||(_r=1,(function(i,e){(function(t){i.exports=t()})(function(){return(function t(r,n,s){function o(l,m){if(!n[l]){if(!r[l]){var f=typeof Je=="function"&&Je;if(!m&&f)return f(l,!0);if(a)return a(l,!0);var b=new Error("Cannot find module '"+l+"'");throw b.code="MODULE_NOT_FOUND",b}var w=n[l]={exports:{}};r[l][0].call(w.exports,function(y){var I=r[l][1][y];return o(I||y)},w,w.exports,t,r,n,s)}return n[l].exports}for(var a=typeof Je=="function"&&Je,d=0;d<s.length;d++)o(s[d]);return o})({1:[function(t,r,n){(function(s){var o=s.MutationObserver||s.WebKitMutationObserver,a;if(o){var d=0,l=new o(y),m=s.document.createTextNode("");l.observe(m,{characterData:!0}),a=function(){m.data=d=++d%2}}else if(!s.setImmediate&&typeof s.MessageChannel<"u"){var f=new s.MessageChannel;f.port1.onmessage=y,a=function(){f.port2.postMessage(0)}}else"document"in s&&"onreadystatechange"in s.document.createElement("script")?a=function(){var _=s.document.createElement("script");_.onreadystatechange=function(){y(),_.onreadystatechange=null,_.parentNode.removeChild(_),_=null},s.document.documentElement.appendChild(_)}:a=function(){setTimeout(y,0)};var b,w=[];function y(){b=!0;for(var _,N,C=w.length;C;){for(N=w,w=[],_=-1;++_<C;)N[_]();C=w.length}b=!1}r.exports=I;function I(_){w.push(_)===1&&!b&&a()}}).call(this,typeof Ee<"u"?Ee:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(t,r,n){var s=t(1);function o(){}var a={},d=["REJECTED"],l=["FULFILLED"],m=["PENDING"];r.exports=f;function f(E){if(typeof E!="function")throw new TypeError("resolver must be a function");this.state=m,this.queue=[],this.outcome=void 0,E!==o&&I(this,E)}f.prototype.catch=function(E){return this.then(null,E)},f.prototype.then=function(E,L){if(typeof E!="function"&&this.state===l||typeof L!="function"&&this.state===d)return this;var P=new this.constructor(o);if(this.state!==m){var j=this.state===l?E:L;w(P,j,this.outcome)}else this.queue.push(new b(P,E,L));return P};function b(E,L,P){this.promise=E,typeof L=="function"&&(this.onFulfilled=L,this.callFulfilled=this.otherCallFulfilled),typeof P=="function"&&(this.onRejected=P,this.callRejected=this.otherCallRejected)}b.prototype.callFulfilled=function(E){a.resolve(this.promise,E)},b.prototype.otherCallFulfilled=function(E){w(this.promise,this.onFulfilled,E)},b.prototype.callRejected=function(E){a.reject(this.promise,E)},b.prototype.otherCallRejected=function(E){w(this.promise,this.onRejected,E)};function w(E,L,P){s(function(){var j;try{j=L(P)}catch(H){return a.reject(E,H)}j===E?a.reject(E,new TypeError("Cannot resolve promise with itself")):a.resolve(E,j)})}a.resolve=function(E,L){var P=_(y,L);if(P.status==="error")return a.reject(E,P.value);var j=P.value;if(j)I(E,j);else{E.state=l,E.outcome=L;for(var H=-1,V=E.queue.length;++H<V;)E.queue[H].callFulfilled(L)}return E},a.reject=function(E,L){E.state=d,E.outcome=L;for(var P=-1,j=E.queue.length;++P<j;)E.queue[P].callRejected(L);return E};function y(E){var L=E&&E.then;if(E&&(typeof E=="object"||typeof E=="function")&&typeof L=="function")return function(){L.apply(E,arguments)}}function I(E,L){var P=!1;function j(Y){P||(P=!0,a.reject(E,Y))}function H(Y){P||(P=!0,a.resolve(E,Y))}function V(){L(H,j)}var Z=_(V);Z.status==="error"&&j(Z.value)}function _(E,L){var P={};try{P.value=E(L),P.status="success"}catch(j){P.status="error",P.value=j}return P}f.resolve=N;function N(E){return E instanceof this?E:a.resolve(new this(o),E)}f.reject=C;function C(E){var L=new this(o);return a.reject(L,E)}f.all=U;function U(E){var L=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var P=E.length,j=!1;if(!P)return this.resolve([]);for(var H=new Array(P),V=0,Z=-1,Y=new this(o);++Z<P;)se(E[Z],Z);return Y;function se(le,D){L.resolve(le).then(R,function(B){j||(j=!0,a.reject(Y,B))});function R(B){H[D]=B,++V===P&&!j&&(j=!0,a.resolve(Y,H))}}}f.race=F;function F(E){var L=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var P=E.length,j=!1;if(!P)return this.resolve([]);for(var H=-1,V=new this(o);++H<P;)Z(E[H]);return V;function Z(Y){L.resolve(Y).then(function(se){j||(j=!0,a.resolve(V,se))},function(se){j||(j=!0,a.reject(V,se))})}}},{1:1}],3:[function(t,r,n){(function(s){typeof s.Promise!="function"&&(s.Promise=t(2))}).call(this,typeof Ee<"u"?Ee:typeof self<"u"?self:typeof window<"u"?window:{})},{2:2}],4:[function(t,r,n){var s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(c){return typeof c}:function(c){return c&&typeof Symbol=="function"&&c.constructor===Symbol&&c!==Symbol.prototype?"symbol":typeof c};function o(c,h){if(!(c instanceof h))throw new TypeError("Cannot call a class as a function")}function a(){try{if(typeof indexedDB<"u")return indexedDB;if(typeof webkitIndexedDB<"u")return webkitIndexedDB;if(typeof mozIndexedDB<"u")return mozIndexedDB;if(typeof OIndexedDB<"u")return OIndexedDB;if(typeof msIndexedDB<"u")return msIndexedDB}catch{return}}var d=a();function l(){try{if(!d||!d.open)return!1;var c=typeof openDatabase<"u"&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),h=typeof fetch=="function"&&fetch.toString().indexOf("[native code")!==-1;return(!c||h)&&typeof indexedDB<"u"&&typeof IDBKeyRange<"u"}catch{return!1}}function m(c,h){c=c||[],h=h||{};try{return new Blob(c,h)}catch(g){if(g.name!=="TypeError")throw g;for(var u=typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder,p=new u,v=0;v<c.length;v+=1)p.append(c[v]);return p.getBlob(h.type)}}typeof Promise>"u"&&t(3);var f=Promise;function b(c,h){h&&c.then(function(u){h(null,u)},function(u){h(u)})}function w(c,h,u){typeof h=="function"&&c.then(h),typeof u=="function"&&c.catch(u)}function y(c){return typeof c!="string"&&(console.warn(c+" used as a key, but it is not a string."),c=String(c)),c}function I(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var _="local-forage-detect-blob-support",N=void 0,C={},U=Object.prototype.toString,F="readonly",E="readwrite";function L(c){for(var h=c.length,u=new ArrayBuffer(h),p=new Uint8Array(u),v=0;v<h;v++)p[v]=c.charCodeAt(v);return u}function P(c){return new f(function(h){var u=c.transaction(_,E),p=m([""]);u.objectStore(_).put(p,"key"),u.onabort=function(v){v.preventDefault(),v.stopPropagation(),h(!1)},u.oncomplete=function(){var v=navigator.userAgent.match(/Chrome\/(\d+)/),g=navigator.userAgent.match(/Edge\//);h(g||!v||parseInt(v[1],10)>=43)}}).catch(function(){return!1})}function j(c){return typeof N=="boolean"?f.resolve(N):P(c).then(function(h){return N=h,N})}function H(c){var h=C[c.name],u={};u.promise=new f(function(p,v){u.resolve=p,u.reject=v}),h.deferredOperations.push(u),h.dbReady?h.dbReady=h.dbReady.then(function(){return u.promise}):h.dbReady=u.promise}function V(c){var h=C[c.name],u=h.deferredOperations.pop();if(u)return u.resolve(),u.promise}function Z(c,h){var u=C[c.name],p=u.deferredOperations.pop();if(p)return p.reject(h),p.promise}function Y(c,h){return new f(function(u,p){if(C[c.name]=C[c.name]||_e(),c.db)if(h)H(c),c.db.close();else return u(c.db);var v=[c.name];h&&v.push(c.version);var g=d.open.apply(d,v);h&&(g.onupgradeneeded=function(S){var T=g.result;try{T.createObjectStore(c.storeName),S.oldVersion<=1&&T.createObjectStore(_)}catch(M){if(M.name==="ConstraintError")console.warn('The database "'+c.name+'" has been upgraded from version '+S.oldVersion+" to version "+S.newVersion+', but the storage "'+c.storeName+'" already exists.');else throw M}}),g.onerror=function(S){S.preventDefault(),p(g.error)},g.onsuccess=function(){var S=g.result;S.onversionchange=function(T){T.target.close()},u(S),V(c)}})}function se(c){return Y(c,!1)}function le(c){return Y(c,!0)}function D(c,h){if(!c.db)return!0;var u=!c.db.objectStoreNames.contains(c.storeName),p=c.version<c.db.version,v=c.version>c.db.version;if(p&&(c.version!==h&&console.warn('The database "'+c.name+`" can't be downgraded from version `+c.db.version+" to version "+c.version+"."),c.version=c.db.version),v||u){if(u){var g=c.db.version+1;g>c.version&&(c.version=g)}return!0}return!1}function R(c){return new f(function(h,u){var p=new FileReader;p.onerror=u,p.onloadend=function(v){var g=btoa(v.target.result||"");h({__local_forage_encoded_blob:!0,data:g,type:c.type})},p.readAsBinaryString(c)})}function B(c){var h=L(atob(c.data));return m([h],{type:c.type})}function G(c){return c&&c.__local_forage_encoded_blob}function K(c){var h=this,u=h._initReady().then(function(){var p=C[h._dbInfo.name];if(p&&p.dbReady)return p.dbReady});return w(u,c,c),u}function z(c){H(c);for(var h=C[c.name],u=h.forages,p=0;p<u.length;p++){var v=u[p];v._dbInfo.db&&(v._dbInfo.db.close(),v._dbInfo.db=null)}return c.db=null,se(c).then(function(g){return c.db=g,D(c)?le(c):g}).then(function(g){c.db=h.db=g;for(var S=0;S<u.length;S++)u[S]._dbInfo.db=g}).catch(function(g){throw Z(c,g),g})}function ae(c,h,u,p){p===void 0&&(p=1);try{var v=c.db.transaction(c.storeName,h);u(null,v)}catch(g){if(p>0&&(!c.db||g.name==="InvalidStateError"||g.name==="NotFoundError"))return f.resolve().then(function(){if(!c.db||g.name==="NotFoundError"&&!c.db.objectStoreNames.contains(c.storeName)&&c.version<=c.db.version)return c.db&&(c.version=c.db.version+1),le(c)}).then(function(){return z(c).then(function(){ae(c,h,u,p-1)})}).catch(u);u(g)}}function _e(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function qe(c){var h=this,u={db:null};if(c)for(var p in c)u[p]=c[p];var v=C[u.name];v||(v=_e(),C[u.name]=v),v.forages.push(h),h._initReady||(h._initReady=h.ready,h.ready=K);var g=[];function S(){return f.resolve()}for(var T=0;T<v.forages.length;T++){var M=v.forages[T];M!==h&&g.push(M._initReady().catch(S))}var O=v.forages.slice(0);return f.all(g).then(function(){return u.db=v.db,se(u)}).then(function(A){return u.db=A,D(u,h._defaultConfig.version)?le(u):A}).then(function(A){u.db=v.db=A,h._dbInfo=u;for(var x=0;x<O.length;x++){var k=O[x];k!==h&&(k._dbInfo.db=u.db,k._dbInfo.version=u.version)}})}function ne(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){ae(u._dbInfo,F,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=M.get(c);O.onsuccess=function(){var A=O.result;A===void 0&&(A=null),G(A)&&(A=B(A)),v(A)},O.onerror=function(){g(O.error)}}catch(A){g(A)}})}).catch(g)});return b(p,h),p}function me(c,h){var u=this,p=new f(function(v,g){u.ready().then(function(){ae(u._dbInfo,F,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=M.openCursor(),A=1;O.onsuccess=function(){var x=O.result;if(x){var k=x.value;G(k)&&(k=B(k));var J=c(k,x.key,A++);J!==void 0?v(J):x.continue()}else v()},O.onerror=function(){g(O.error)}}catch(x){g(x)}})}).catch(g)});return b(p,h),p}function mn(c,h,u){var p=this;c=y(c);var v=new f(function(g,S){var T;p.ready().then(function(){return T=p._dbInfo,U.call(h)==="[object Blob]"?j(T.db).then(function(M){return M?h:R(h)}):h}).then(function(M){ae(p._dbInfo,E,function(O,A){if(O)return S(O);try{var x=A.objectStore(p._dbInfo.storeName);M===null&&(M=void 0);var k=x.put(M,c);A.oncomplete=function(){M===void 0&&(M=null),g(M)},A.onabort=A.onerror=function(){var J=k.error?k.error:k.transaction.error;S(J)}}catch(J){S(J)}})}).catch(S)});return b(v,u),v}function yn(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){ae(u._dbInfo,E,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=M.delete(c);T.oncomplete=function(){v()},T.onerror=function(){g(O.error)},T.onabort=function(){var A=O.error?O.error:O.transaction.error;g(A)}}catch(A){g(A)}})}).catch(g)});return b(p,h),p}function vn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){ae(h._dbInfo,E,function(g,S){if(g)return v(g);try{var T=S.objectStore(h._dbInfo.storeName),M=T.clear();S.oncomplete=function(){p()},S.onabort=S.onerror=function(){var O=M.error?M.error:M.transaction.error;v(O)}}catch(O){v(O)}})}).catch(v)});return b(u,c),u}function wn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){ae(h._dbInfo,F,function(g,S){if(g)return v(g);try{var T=S.objectStore(h._dbInfo.storeName),M=T.count();M.onsuccess=function(){p(M.result)},M.onerror=function(){v(M.error)}}catch(O){v(O)}})}).catch(v)});return b(u,c),u}function bn(c,h){var u=this,p=new f(function(v,g){if(c<0){v(null);return}u.ready().then(function(){ae(u._dbInfo,F,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=!1,A=M.openKeyCursor();A.onsuccess=function(){var x=A.result;if(!x){v(null);return}c===0||O?v(x.key):(O=!0,x.advance(c))},A.onerror=function(){g(A.error)}}catch(x){g(x)}})}).catch(g)});return b(p,h),p}function Dn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){ae(h._dbInfo,F,function(g,S){if(g)return v(g);try{var T=S.objectStore(h._dbInfo.storeName),M=T.openKeyCursor(),O=[];M.onsuccess=function(){var A=M.result;if(!A){p(O);return}O.push(A.key),A.continue()},M.onerror=function(){v(M.error)}}catch(A){v(A)}})}).catch(v)});return b(u,c),u}function Sn(c,h){h=I.apply(this,arguments);var u=this.config();c=typeof c!="function"&&c||{},c.name||(c.name=c.name||u.name,c.storeName=c.storeName||u.storeName);var p=this,v;if(!c.name)v=f.reject("Invalid arguments");else{var g=c.name===u.name&&p._dbInfo.db,S=g?f.resolve(p._dbInfo.db):se(c).then(function(T){var M=C[c.name],O=M.forages;M.db=T;for(var A=0;A<O.length;A++)O[A]._dbInfo.db=T;return T});c.storeName?v=S.then(function(T){if(T.objectStoreNames.contains(c.storeName)){var M=T.version+1;H(c);var O=C[c.name],A=O.forages;T.close();for(var x=0;x<A.length;x++){var k=A[x];k._dbInfo.db=null,k._dbInfo.version=M}var J=new f(function(Q,re){var ee=d.open(c.name,M);ee.onerror=function(ue){var Pe=ee.result;Pe.close(),re(ue)},ee.onupgradeneeded=function(){var ue=ee.result;ue.deleteObjectStore(c.storeName)},ee.onsuccess=function(){var ue=ee.result;ue.close(),Q(ue)}});return J.then(function(Q){O.db=Q;for(var re=0;re<A.length;re++){var ee=A[re];ee._dbInfo.db=Q,V(ee._dbInfo)}}).catch(function(Q){throw(Z(c,Q)||f.resolve()).catch(function(){}),Q})}}):v=S.then(function(T){H(c);var M=C[c.name],O=M.forages;T.close();for(var A=0;A<O.length;A++){var x=O[A];x._dbInfo.db=null}var k=new f(function(J,Q){var re=d.deleteDatabase(c.name);re.onerror=function(){var ee=re.result;ee&&ee.close(),Q(re.error)},re.onblocked=function(){console.warn('dropInstance blocked for database "'+c.name+'" until all open connections are closed')},re.onsuccess=function(){var ee=re.result;ee&&ee.close(),J(ee)}});return k.then(function(J){M.db=J;for(var Q=0;Q<O.length;Q++){var re=O[Q];V(re._dbInfo)}}).catch(function(J){throw(Z(c,J)||f.resolve()).catch(function(){}),J})})}return b(v,h),v}var En={_driver:"asyncStorage",_initStorage:qe,_support:l(),iterate:me,getItem:ne,setItem:mn,removeItem:yn,clear:vn,length:wn,key:bn,keys:Dn,dropInstance:Sn};function In(){return typeof openDatabase=="function"}var be="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Tn="~~local_forage_type~",zt=/^~~local_forage_type~([^~]+)~/,ze="__lfsc__:",ht=ze.length,ft="arbf",gt="blob",jt="si08",Ht="ui08",Gt="uic8",Jt="si16",Yt="si32",Qt="ur16",Vt="ui32",Kt="fl32",Wt="fl64",Xt=ht+ft.length,Zt=Object.prototype.toString;function er(c){var h=c.length*.75,u=c.length,p,v=0,g,S,T,M;c[c.length-1]==="="&&(h--,c[c.length-2]==="="&&h--);var O=new ArrayBuffer(h),A=new Uint8Array(O);for(p=0;p<u;p+=4)g=be.indexOf(c[p]),S=be.indexOf(c[p+1]),T=be.indexOf(c[p+2]),M=be.indexOf(c[p+3]),A[v++]=g<<2|S>>4,A[v++]=(S&15)<<4|T>>2,A[v++]=(T&3)<<6|M&63;return O}function pt(c){var h=new Uint8Array(c),u="",p;for(p=0;p<h.length;p+=3)u+=be[h[p]>>2],u+=be[(h[p]&3)<<4|h[p+1]>>4],u+=be[(h[p+1]&15)<<2|h[p+2]>>6],u+=be[h[p+2]&63];return h.length%3===2?u=u.substring(0,u.length-1)+"=":h.length%3===1&&(u=u.substring(0,u.length-2)+"=="),u}function Rn(c,h){var u="";if(c&&(u=Zt.call(c)),c&&(u==="[object ArrayBuffer]"||c.buffer&&Zt.call(c.buffer)==="[object ArrayBuffer]")){var p,v=ze;c instanceof ArrayBuffer?(p=c,v+=ft):(p=c.buffer,u==="[object Int8Array]"?v+=jt:u==="[object Uint8Array]"?v+=Ht:u==="[object Uint8ClampedArray]"?v+=Gt:u==="[object Int16Array]"?v+=Jt:u==="[object Uint16Array]"?v+=Qt:u==="[object Int32Array]"?v+=Yt:u==="[object Uint32Array]"?v+=Vt:u==="[object Float32Array]"?v+=Kt:u==="[object Float64Array]"?v+=Wt:h(new Error("Failed to get type for BinaryArray"))),h(v+pt(p))}else if(u==="[object Blob]"){var g=new FileReader;g.onload=function(){var S=Tn+c.type+"~"+pt(this.result);h(ze+gt+S)},g.readAsArrayBuffer(c)}else try{h(JSON.stringify(c))}catch(S){console.error("Couldn't convert value into a JSON string: ",c),h(null,S)}}function Mn(c){if(c.substring(0,ht)!==ze)return JSON.parse(c);var h=c.substring(Xt),u=c.substring(ht,Xt),p;if(u===gt&&zt.test(h)){var v=h.match(zt);p=v[1],h=h.substring(v[0].length)}var g=er(h);switch(u){case ft:return g;case gt:return m([g],{type:p});case jt:return new Int8Array(g);case Ht:return new Uint8Array(g);case Gt:return new Uint8ClampedArray(g);case Jt:return new Int16Array(g);case Qt:return new Uint16Array(g);case Yt:return new Int32Array(g);case Vt:return new Uint32Array(g);case Kt:return new Float32Array(g);case Wt:return new Float64Array(g);default:throw new Error("Unkown type: "+u)}}var mt={serialize:Rn,deserialize:Mn,stringToBuffer:er,bufferToString:pt};function tr(c,h,u,p){c.executeSql("CREATE TABLE IF NOT EXISTS "+h.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],u,p)}function On(c){var h=this,u={db:null};if(c)for(var p in c)u[p]=typeof c[p]!="string"?c[p].toString():c[p];var v=new f(function(g,S){try{u.db=openDatabase(u.name,String(u.version),u.description,u.size)}catch(T){return S(T)}u.db.transaction(function(T){tr(T,u,function(){h._dbInfo=u,g()},function(M,O){S(O)})},S)});return u.serializer=mt,v}function De(c,h,u,p,v,g){c.executeSql(u,p,v,function(S,T){T.code===T.SYNTAX_ERR?S.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[h.storeName],function(M,O){O.rows.length?g(M,T):tr(M,h,function(){M.executeSql(u,p,v,g)},g)},g):g(S,T)},g)}function _n(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"SELECT * FROM "+S.storeName+" WHERE key = ? LIMIT 1",[c],function(M,O){var A=O.rows.length?O.rows.item(0).value:null;A&&(A=S.serializer.deserialize(A)),v(A)},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function An(c,h){var u=this,p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"SELECT * FROM "+S.storeName,[],function(M,O){for(var A=O.rows,x=A.length,k=0;k<x;k++){var J=A.item(k),Q=J.value;if(Q&&(Q=S.serializer.deserialize(Q)),Q=c(Q,J.key,k+1),Q!==void 0){v(Q);return}}v()},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function rr(c,h,u,p){var v=this;c=y(c);var g=new f(function(S,T){v.ready().then(function(){h===void 0&&(h=null);var M=h,O=v._dbInfo;O.serializer.serialize(h,function(A,x){x?T(x):O.db.transaction(function(k){De(k,O,"INSERT OR REPLACE INTO "+O.storeName+" (key, value) VALUES (?, ?)",[c,A],function(){S(M)},function(J,Q){T(Q)})},function(k){if(k.code===k.QUOTA_ERR){if(p>0){S(rr.apply(v,[c,M,u,p-1]));return}T(k)}})})}).catch(T)});return b(g,u),g}function Nn(c,h,u){return rr.apply(this,[c,h,u,1])}function Cn(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"DELETE FROM "+S.storeName+" WHERE key = ?",[c],function(){v()},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function xn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){var g=h._dbInfo;g.db.transaction(function(S){De(S,g,"DELETE FROM "+g.storeName,[],function(){p()},function(T,M){v(M)})})}).catch(v)});return b(u,c),u}function $n(c){var h=this,u=new f(function(p,v){h.ready().then(function(){var g=h._dbInfo;g.db.transaction(function(S){De(S,g,"SELECT COUNT(key) as c FROM "+g.storeName,[],function(T,M){var O=M.rows.item(0).c;p(O)},function(T,M){v(M)})})}).catch(v)});return b(u,c),u}function Pn(c,h){var u=this,p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"SELECT key FROM "+S.storeName+" WHERE id = ? LIMIT 1",[c+1],function(M,O){var A=O.rows.length?O.rows.item(0).key:null;v(A)},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function Ln(c){var h=this,u=new f(function(p,v){h.ready().then(function(){var g=h._dbInfo;g.db.transaction(function(S){De(S,g,"SELECT key FROM "+g.storeName,[],function(T,M){for(var O=[],A=0;A<M.rows.length;A++)O.push(M.rows.item(A).key);p(O)},function(T,M){v(M)})})}).catch(v)});return b(u,c),u}function Un(c){return new f(function(h,u){c.transaction(function(p){p.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(v,g){for(var S=[],T=0;T<g.rows.length;T++)S.push(g.rows.item(T).name);h({db:c,storeNames:S})},function(v,g){u(g)})},function(p){u(p)})})}function Bn(c,h){h=I.apply(this,arguments);var u=this.config();c=typeof c!="function"&&c||{},c.name||(c.name=c.name||u.name,c.storeName=c.storeName||u.storeName);var p=this,v;return c.name?v=new f(function(g){var S;c.name===u.name?S=p._dbInfo.db:S=openDatabase(c.name,"","",0),c.storeName?g({db:S,storeNames:[c.storeName]}):g(Un(S))}).then(function(g){return new f(function(S,T){g.db.transaction(function(M){function O(J){return new f(function(Q,re){M.executeSql("DROP TABLE IF EXISTS "+J,[],function(){Q()},function(ee,ue){re(ue)})})}for(var A=[],x=0,k=g.storeNames.length;x<k;x++)A.push(O(g.storeNames[x]));f.all(A).then(function(){S()}).catch(function(J){T(J)})},function(M){T(M)})})}):v=f.reject("Invalid arguments"),b(v,h),v}var Fn={_driver:"webSQLStorage",_initStorage:On,_support:In(),iterate:An,getItem:_n,setItem:Nn,removeItem:Cn,clear:xn,length:$n,key:Pn,keys:Ln,dropInstance:Bn};function kn(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}function nr(c,h){var u=c.name+"/";return c.storeName!==h.storeName&&(u+=c.storeName+"/"),u}function qn(){var c="_localforage_support_test";try{return localStorage.setItem(c,!0),localStorage.removeItem(c),!1}catch{return!0}}function zn(){return!qn()||localStorage.length>0}function jn(c){var h=this,u={};if(c)for(var p in c)u[p]=c[p];return u.keyPrefix=nr(c,h._defaultConfig),zn()?(h._dbInfo=u,u.serializer=mt,f.resolve()):f.reject()}function Hn(c){var h=this,u=h.ready().then(function(){for(var p=h._dbInfo.keyPrefix,v=localStorage.length-1;v>=0;v--){var g=localStorage.key(v);g.indexOf(p)===0&&localStorage.removeItem(g)}});return b(u,c),u}function Gn(c,h){var u=this;c=y(c);var p=u.ready().then(function(){var v=u._dbInfo,g=localStorage.getItem(v.keyPrefix+c);return g&&(g=v.serializer.deserialize(g)),g});return b(p,h),p}function Jn(c,h){var u=this,p=u.ready().then(function(){for(var v=u._dbInfo,g=v.keyPrefix,S=g.length,T=localStorage.length,M=1,O=0;O<T;O++){var A=localStorage.key(O);if(A.indexOf(g)===0){var x=localStorage.getItem(A);if(x&&(x=v.serializer.deserialize(x)),x=c(x,A.substring(S),M++),x!==void 0)return x}}});return b(p,h),p}function Yn(c,h){var u=this,p=u.ready().then(function(){var v=u._dbInfo,g;try{g=localStorage.key(c)}catch{g=null}return g&&(g=g.substring(v.keyPrefix.length)),g});return b(p,h),p}function Qn(c){var h=this,u=h.ready().then(function(){for(var p=h._dbInfo,v=localStorage.length,g=[],S=0;S<v;S++){var T=localStorage.key(S);T.indexOf(p.keyPrefix)===0&&g.push(T.substring(p.keyPrefix.length))}return g});return b(u,c),u}function Vn(c){var h=this,u=h.keys().then(function(p){return p.length});return b(u,c),u}function Kn(c,h){var u=this;c=y(c);var p=u.ready().then(function(){var v=u._dbInfo;localStorage.removeItem(v.keyPrefix+c)});return b(p,h),p}function Wn(c,h,u){var p=this;c=y(c);var v=p.ready().then(function(){h===void 0&&(h=null);var g=h;return new f(function(S,T){var M=p._dbInfo;M.serializer.serialize(h,function(O,A){if(A)T(A);else try{localStorage.setItem(M.keyPrefix+c,O),S(g)}catch(x){(x.name==="QuotaExceededError"||x.name==="NS_ERROR_DOM_QUOTA_REACHED")&&T(x),T(x)}})})});return b(v,u),v}function Xn(c,h){if(h=I.apply(this,arguments),c=typeof c!="function"&&c||{},!c.name){var u=this.config();c.name=c.name||u.name,c.storeName=c.storeName||u.storeName}var p=this,v;return c.name?v=new f(function(g){c.storeName?g(nr(c,p._defaultConfig)):g(c.name+"/")}).then(function(g){for(var S=localStorage.length-1;S>=0;S--){var T=localStorage.key(S);T.indexOf(g)===0&&localStorage.removeItem(T)}}):v=f.reject("Invalid arguments"),b(v,h),v}var Zn={_driver:"localStorageWrapper",_initStorage:jn,_support:kn(),iterate:Jn,getItem:Gn,setItem:Wn,removeItem:Kn,clear:Hn,length:Vn,key:Yn,keys:Qn,dropInstance:Xn},es=function(h,u){return h===u||typeof h=="number"&&typeof u=="number"&&isNaN(h)&&isNaN(u)},ts=function(h,u){for(var p=h.length,v=0;v<p;){if(es(h[v],u))return!0;v++}return!1},sr=Array.isArray||function(c){return Object.prototype.toString.call(c)==="[object Array]"},$e={},ir={},Ae={INDEXEDDB:En,WEBSQL:Fn,LOCALSTORAGE:Zn},rs=[Ae.INDEXEDDB._driver,Ae.WEBSQL._driver,Ae.LOCALSTORAGE._driver],je=["dropInstance"],yt=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(je),ns={description:"",driver:rs.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function ss(c,h){c[h]=function(){var u=arguments;return c.ready().then(function(){return c[h].apply(c,u)})}}function vt(){for(var c=1;c<arguments.length;c++){var h=arguments[c];if(h)for(var u in h)h.hasOwnProperty(u)&&(sr(h[u])?arguments[0][u]=h[u].slice():arguments[0][u]=h[u])}return arguments[0]}var is=(function(){function c(h){o(this,c);for(var u in Ae)if(Ae.hasOwnProperty(u)){var p=Ae[u],v=p._driver;this[u]=v,$e[v]||this.defineDriver(p)}this._defaultConfig=vt({},ns),this._config=vt({},this._defaultConfig,h),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return c.prototype.config=function(u){if((typeof u>"u"?"undefined":s(u))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var p in u){if(p==="storeName"&&(u[p]=u[p].replace(/\W/g,"_")),p==="version"&&typeof u[p]!="number")return new Error("Database version must be a number.");this._config[p]=u[p]}return"driver"in u&&u.driver?this.setDriver(this._config.driver):!0}else return typeof u=="string"?this._config[u]:this._config},c.prototype.defineDriver=function(u,p,v){var g=new f(function(S,T){try{var M=u._driver,O=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!u._driver){T(O);return}for(var A=yt.concat("_initStorage"),x=0,k=A.length;x<k;x++){var J=A[x],Q=!ts(je,J);if((Q||u[J])&&typeof u[J]!="function"){T(O);return}}var re=function(){for(var Pe=function(cs){return function(){var us=new Error("Method "+cs+" is not implemented by the current driver"),or=f.reject(us);return b(or,arguments[arguments.length-1]),or}},wt=0,as=je.length;wt<as;wt++){var bt=je[wt];u[bt]||(u[bt]=Pe(bt))}};re();var ee=function(Pe){$e[M]&&console.info("Redefining LocalForage driver: "+M),$e[M]=u,ir[M]=Pe,S()};"_support"in u?u._support&&typeof u._support=="function"?u._support().then(ee,T):ee(!!u._support):ee(!0)}catch(ue){T(ue)}});return w(g,p,v),g},c.prototype.driver=function(){return this._driver||null},c.prototype.getDriver=function(u,p,v){var g=$e[u]?f.resolve($e[u]):f.reject(new Error("Driver not found."));return w(g,p,v),g},c.prototype.getSerializer=function(u){var p=f.resolve(mt);return w(p,u),p},c.prototype.ready=function(u){var p=this,v=p._driverSet.then(function(){return p._ready===null&&(p._ready=p._initDriver()),p._ready});return w(v,u,u),v},c.prototype.setDriver=function(u,p,v){var g=this;sr(u)||(u=[u]);var S=this._getSupportedDrivers(u);function T(){g._config.driver=g.driver()}function M(x){return g._extend(x),T(),g._ready=g._initStorage(g._config),g._ready}function O(x){return function(){var k=0;function J(){for(;k<x.length;){var Q=x[k];return k++,g._dbInfo=null,g._ready=null,g.getDriver(Q).then(M).catch(J)}T();var re=new Error("No available storage method found.");return g._driverSet=f.reject(re),g._driverSet}return J()}}var A=this._driverSet!==null?this._driverSet.catch(function(){return f.resolve()}):f.resolve();return this._driverSet=A.then(function(){var x=S[0];return g._dbInfo=null,g._ready=null,g.getDriver(x).then(function(k){g._driver=k._driver,T(),g._wrapLibraryMethodsWithReady(),g._initDriver=O(S)})}).catch(function(){T();var x=new Error("No available storage method found.");return g._driverSet=f.reject(x),g._driverSet}),w(this._driverSet,p,v),this._driverSet},c.prototype.supports=function(u){return!!ir[u]},c.prototype._extend=function(u){vt(this,u)},c.prototype._getSupportedDrivers=function(u){for(var p=[],v=0,g=u.length;v<g;v++){var S=u[v];this.supports(S)&&p.push(S)}return p},c.prototype._wrapLibraryMethodsWithReady=function(){for(var u=0,p=yt.length;u<p;u++)ss(this,yt[u])},c.prototype.createInstance=function(u){return new c(u)},c})(),os=new is;r.exports=os},{3:3}]},{},[4])(4)})})(xt)),xt.exports}var Eo=So();const Ar=Pt(Eo);class te{logger=pe(["BrowserStorage"]);db;static DBName="DOCUMENT_DRIVES";static SEP=":";static DOCUMENT_KEY="DOCUMENT";static MANIFEST_KEY="MANIFEST";static SLUG_MANIFEST_KEY="SLUG_MANIFEST";constructor(e){this.db=Ar.ready().then(()=>Ar.createInstance({name:e?`${e}:${te.DBName}`:te.DBName}))}async findStorageUnitsBy(e,t,r){const n=[],{parentId:s,documentId:o,documentModelType:a,scope:d}=sn(e),f=(await(await this.db).keys()).filter(_=>_.startsWith(`${te.DOCUMENT_KEY}${te.SEP}`)).map(_=>_.slice(te.DOCUMENT_KEY.length+te.SEP.length));let b;if(s){const _=new Set;for(const N of s)(await this.getChildren(N)).forEach(U=>_.add(U));b=on(s,_)}else b=new Set(f);b=o?an(o,b):b;for(const _ of b){const N=await this.get(_).catch(()=>null);if(N&&!(a&&!a.has(N.header.documentType)))for(const[C]of Object.entries(N.state))d&&!d.has(C)||n.push({documentId:_,documentModelType:N.header.documentType,scope:C,branch:"main"})}let w=0;if(r){const _=n.findIndex(N=>N.documentId===r);_!==-1&&(w=_)}const y=Math.min(w+t,n.length),I=y<n.length?n[y].documentId:void 0;return{units:n.slice(w,y),nextCursor:I}}async resolveIds(e,t){const r=await this.getSlugManifest();if(t?.aborted)throw new at("Aborted");const n=[];for(const s of e){const o=r.slugToId[s];if(!o)throw new we(s);n.push(o)}return Promise.resolve(n)}async resolveSlugs(e,t){const r=await this.getSlugManifest();if(t?.aborted)throw new at("Aborted");const n=[];for(const s of e){let o=!1;for(const[a,d]of Object.entries(r.slugToId))if(d===s){n.push(a),o=!0;break}if(!o)throw new we(s)}return Promise.resolve(n)}async clear(){await(await this.db).clear()}async exists(e){return!!await(await this.db).getItem(this.buildDocumentKey(e))}async create(e){const t=e.header.id;if(!tt(t))throw new et(t);const r=await this.db;if(await this.exists(t))throw new ke(t);const n=e.header.slug&&e.header.slug.length>0?e.header.slug:t;if(!nn(n))throw new rn(n);if((await this.getSlugManifest()).slugToId[n])throw new ke(t,Fe.SLUG);if(e.header.slug=n,await r.setItem(this.buildDocumentKey(t),e),n){const o=await this.getSlugManifest();if(o.slugToId[n])throw new Error(`Document with slug ${n} already exists`);o.slugToId[n]=t,await this.updateSlugManifest(o)}e.header.documentType==="powerhouse/document-drive"&&this.updateDriveManifest(t,{documentIds:[]})}async get(e){const r=await(await this.db).getItem(this.buildDocumentKey(e));return r||Promise.reject(new we(e))}async getBySlug(e){const r=(await this.getSlugManifest()).slugToId[e];return r?this.get(r):Promise.reject(new we(e))}async findByType(e,t=100,r){const n=await this.db,o=(await n.keys()).filter(f=>f.startsWith(`${te.DOCUMENT_KEY}${te.SEP}`)),a=[];for(const f of o){const b=f.slice(te.DOCUMENT_KEY.length+te.SEP.length);try{const w=await n.getItem(f);if(!w||w.header.documentType!==e)continue;a.push({id:b,document:w})}catch{continue}}a.sort((f,b)=>{const w=new Date(f.document.header.createdAtUtcIso),y=new Date(b.document.header.createdAtUtcIso);return w.getTime()===y.getTime()?f.id.localeCompare(b.id):w.getTime()-y.getTime()});let d=0;if(r){const f=a.findIndex(({id:b})=>b===r);f!==-1&&(d=f)}const l=Math.min(d+t,a.length);let m;return l<a.length&&(m=a[l].id),{documents:a.slice(d,l).map(({id:f})=>f),nextCursor:m}}async delete(e){const t=await this.db,r=await t.getItem(this.buildDocumentKey(e));if(!r)return!1;const n=r.header.slug?.length>0?r.header.slug:e;try{if(n){const o=await this.getSlugManifest();o.slugToId[n]===e&&(delete o.slugToId[n],await this.updateSlugManifest(o))}}catch{}const s=await this.getParents(e);for(const o of s)await this.removeChild(o,e);return await t.removeItem(this.buildManifestKey(e)),await t.removeItem(this.buildDocumentKey(e)),!0}async removeChild(e,t){const r=await this.getManifest(e),n=r.documentIds.indexOf(t);return n!==-1?(r.documentIds.splice(n,1),await this.updateDriveManifest(e,r),!0):!1}async addChild(e,t){if(e===t)throw new Error("Cannot associate a document with itself");if((await this.getChildren(t)).includes(e))throw new Error("Cannot associate a document with its child");const n=await this.getManifest(e);n.documentIds.includes(t)||(n.documentIds.push(t),await this.updateDriveManifest(e,n))}async getChildren(e){return(await this.getManifest(e)).documentIds}async getParents(e){const r=await(await this.db).keys(),n=[],s=r.filter(o=>o.startsWith(`${te.MANIFEST_KEY}${te.SEP}`));for(const o of s){const a=o.slice(te.MANIFEST_KEY.length+te.SEP.length);(await this.getManifest(a)).documentIds.includes(e)&&n.push(a)}return n}async getManifest(e){return await(await this.db).getItem(this.buildManifestKey(e))||{documentIds:[]}}async updateDriveManifest(e,t){await(await this.db).setItem(this.buildManifestKey(e),t)}async getSlugManifest(){return await(await this.db).getItem(te.SLUG_MANIFEST_KEY)||{slugToId:{}}}async updateSlugManifest(e){await(await this.db).setItem(te.SLUG_MANIFEST_KEY,e)}async addDocumentOperations(e,t,r){const n=await this.get(e);if(!n)throw new Error(`Document with id ${e} not found`);const s=st(n.operations,t);await(await this.db).setItem(this.buildDocumentKey(e),{...n,...r,operations:s})}async addDriveOperations(e,t,r){const n=await this.get(e),s=st(n.operations,t);await(await this.db).setItem(this.buildDocumentKey(e),{...n,...r,operations:s})}async getSynchronizationUnitsRevision(e){return(await Promise.allSettled(e.map(async r=>{try{const n=await this.get(r.documentId);if(!n?.operations[r.scope])return;const s=n.operations[r.scope];return{documentId:r.documentId,documentType:r.documentType,scope:r.scope,branch:r.branch,lastUpdated:s.at(-1)?.timestampUtcMs??n.header.createdAtUtcIso,revision:s.length>0?Ie(s):0}}catch(n){this.logger.error("Error getting synchronization units revision",n);return}}))).reduce((r,n)=>(n.status==="fulfilled"&&n.value!==void 0&&r.push(n.value),r),[])}async migrateOperationSignatures(){let e;do{const{documents:t,nextCursor:r}=await this.findByType("powerhouse/document-drive",100,e);for(const n of t){await this.migrateDrive(n);const s=await this.getChildren(n);await Promise.all(s.map(async o=>this.migrateDocument(n,o)))}e=r}while(e)}async migrateDrive(e){const t=await this.get(e),r=Or(t);if(r!==t)return(await this.db).setItem(this.buildDocumentKey(e),r)}async migrateDocument(e,t){const r=await this.get(t),n=Or(r);if(n!==r)return(await this.db).setItem(this.buildDocumentKey(t),n)}buildDocumentKey(e){return`${te.DOCUMENT_KEY}${te.SEP}${e}`}buildManifestKey(e){return`${te.MANIFEST_KEY}${te.SEP}${e}`}}export{at as A,te as B,we as D,Bi as E,Us as I,mo as M,ce as P,Po as R,fi as S,Ws as a,Xs as b,gi as c,Zs as d,ri as e,oi as f,No as g,Ne as h,lr as i,si as j,ci as k,fe as l,ni as m,li as n,$o as o,Ye as p,Ao as q,tn as r,Zr as s,pe as t,ti as u,Ni as v,Co as w,gn as x};
|
|
305
|
+
`,{strands:r.map(o=>({driveId:o.driveId,documentId:o.documentId,documentType:o.documentType,scope:o.scope,branch:o.branch,operations:o.operations.map(a=>({index:a.index,skip:a.skip,type:a.type,id:a.id??void 0,actionId:a.actionId,input:co(a.input),hash:a.hash,timestampUtcMs:a.timestampUtcMs,context:a.context?{signer:a.context.signer}:void 0}))}))});if(!s.pushUpdates)throw new Error("Couldn't update listener revision");return s.pushUpdates}catch(s){throw this.logger.error(s),s}}}function Mr(i,e){return e?Object.keys(i).reduce((t,r)=>{const n=e[r];if(n!==void 0){const s=i[r];s&&(t[r]=s.filter(o=>o.index<=n))}return t},{global:[],local:[]}):i}function Nt(i,e){return!e||Object.entries(e).find(([t,r])=>{const n=i.operations[t]?.at(-1);return r===-1?n!==void 0:n?.index!==r})===void 0}function Ct(i){return{id:uo(i),documentType:lo(i),document:ho(i)}}function uo(i){return"id"in i?i.id:"header"in i?i.header.id:"document"in i?i.document.header.id:void 0}function lo(i){return"documentType"in i?i.documentType:"header"in i?i.header.documentType:i.document.header.documentType}function ho(i){return"document"in i?i.document:void 0}function fo(i){return["LOCAL","CLOUD","PUBLIC"].includes(i)}function $o(i){if(typeof i!="object")return"LOCAL";const e="readContext"in i,{sharingType:t}=e?{sharingType:"PUBLIC"}:i.state.local,r=t?.toUpperCase();return!r||r==="PRIVATE"||!fo(r)?"LOCAL":r}class go{logger=pe(["BaseDocumentDriveServer"]);documentModelModules;legacyStorage;documentStorage;cache;queueManager;eventEmitter;options;listenerManager;synchronizationManager;generateJwtHandler;defaultDrivesManager;defaultDrivesManagerDelegate={detachDrive:this.detachDrive.bind(this),emit:(...e)=>this.eventEmitter.emit("defaultRemoteDrive",...e)};queueDelegate={exists:e=>this.documentStorage.exists(e),processOperationJob:async({documentId:e,operations:t,options:r})=>{const n=await this.getDocument(e);return ye(n)?this.processDriveOperations(e,t,r):this.processOperations(e,t,r)},processActionJob:async({documentId:e,actions:t,options:r})=>{const n=await this.getDocument(e);return ye(n)?this.processDriveActions(e,t,r):this.processActions(e,t,r)},processDocumentJob:async({documentId:e,documentType:t,header:r,initialState:n,options:s})=>{const a=this.getDocumentModelModule(t).utils.createDocument(n),d=Le(e,t);a.header.id=e,a.header.sig=d.sig,a.header.documentType=t,r&&(a.header.meta=r.meta);try{const l=await this.createDocument({document:a},s?.source??{type:"local"},a.header.meta);return{status:"SUCCESS",operations:[],document:l,signals:[]}}catch(l){const m=l instanceof Error?l:new Error(JSON.stringify(l));return{status:"ERROR",error:new ie("ERROR",void 0,`Error creating document: ${m.message}`,m),operations:[],document:void 0,signals:[]}}},processJob:async e=>{if(fn(e))return this.queueDelegate.processOperationJob(e);if(Ui(e))return this.queueDelegate.processActionJob(e);if(Ke(e))return this.queueDelegate.processDocumentJob(e);throw new Error("Unknown job type",e)}};triggerMap=new Map;initializePromise;enableDualActionCreate;constructor(e,t,r,n,s,o,a,d,l){this.documentModelModules=e,this.legacyStorage=t,this.documentStorage=r,this.cache=n,this.queueManager=s,this.eventEmitter=o,this.synchronizationManager=a,this.listenerManager=d,this.options={...l,defaultDrives:{...l?.defaultDrives},listenerManager:{...ot,...l?.listenerManager},jwtHandler:l?.jwtHandler===void 0?()=>Promise.resolve(""):l.jwtHandler,taskQueueMethod:l?.taskQueueMethod===void 0?Ft:l.taskQueueMethod,featureFlags:{...l?.featureFlags}},this.enableDualActionCreate=l?.featureFlags?.enableDualActionCreate??!1,this.enableDualActionCreate&&this.logger.warn("Dual action create is enabled."),this.defaultDrivesManager=new ro(this,this.defaultDrivesManagerDelegate,l),this.initializePromise=this._initialize()}get listeners(){return this.listenerManager}initialize(){return this.initializePromise}async _initialize(){await this.listenerManager.initialize(this.handleListenerError.bind(this)),await this.queueManager.init(this.queueDelegate,r=>{this.logger.error("Error initializing queue manager",r)});try{await this.defaultDrivesManager.removeOldremoteDrives()}catch(r){this.logger.error(r)}const e=[],t=await this.getDrives();for(const r of t)await this._initializeDrive(r).catch(n=>{this.logger.error(`Error initializing drive ${r}`,n),e.push(n)});return this.options.defaultDrives.loadOnInit!==!1&&await this.defaultDrivesManager.initializeDefaultRemoteDrives(),e.length===0?null:e}setDocumentModelModules(e){this.documentModelModules=[...e],this.synchronizationManager.setDocumentModelModules([...e]),this.eventEmitter.emit("documentModelModules",[...e])}initializeDefaultRemoteDrives(){return this.defaultDrivesManager.initializeDefaultRemoteDrives()}getDefaultRemoteDrives(){return this.defaultDrivesManager.getDefaultRemoteDrives()}setDefaultDriveAccessLevel(e,t){return this.defaultDrivesManager.setDefaultDriveAccessLevel(e,t)}setAllDefaultDrivesAccessLevel(e){return this.defaultDrivesManager.setAllDefaultDrivesAccessLevel(e)}getOperationSource(e){return e.type==="local"?"push":"pull"}handleListenerError(e,t,r){this.logger.error(`Listener ${r.listener.label??r.listener.listenerId} error:`,e);const n=e instanceof ie?e.status:"ERROR";this.synchronizationManager.updateSyncStatus(t,{push:n},e)}shouldSyncRemoteDrive(e){return e.state.local.availableOffline&&e.state.local.triggers.length>0}async startSyncRemoteDrive(e){let t=this.triggerMap.get(e);const r=await this.synchronizationManager.getSynchronizationUnitsIds(e),n=await this.getDrive(e);for(const s of n.state.local.triggers)if(!t?.get(s.id)){t||(t=new Map),this.synchronizationManager.updateSyncStatus(e,{pull:"SYNCING"});for(const o of r)this.synchronizationManager.updateSyncStatus(o,{pull:"SYNCING"});if(ce.isPullResponderTrigger(s)){let o=!0;const a=ce.setupPull(e,s,this.saveStrand.bind(this),d=>{const l=d instanceof ie?d.status:"ERROR";this.synchronizationManager.updateSyncStatus(e,{pull:l},d),d instanceof xe&&this.eventEmitter.emit("clientStrandsError",e,s,d.response.status,d.message)},async d=>{d.filter(m=>m.status!=="SUCCESS").length<1&&this.synchronizationManager.updateSyncStatus(e,{pull:"SUCCESS"});for(const m of d){const{documentId:f,scope:b,branch:w,status:y,error:I}=m;this.synchronizationManager.updateSyncStatus({documentId:f,scope:b,branch:w},{pull:y},I)}if(o){o=!1,(await this.synchronizationManager.getSynchronizationUnitsIds(e)).filter(w=>!d.find(y=>y.documentId===w.documentId&&y.scope===w.scope&&y.branch===w.branch)).forEach(w=>{this.synchronizationManager.updateSyncStatus(w,{pull:"SUCCESS"})});const b=n.state.local.listeners.find(w=>s.data.url===w.callInfo?.data);if(b)for(const w of d){const{documentId:y,scope:I,branch:_}=w;this.listenerManager.updateListenerRevision(b.listenerId,e,{documentId:y,scope:I,branch:_},w.revision).catch(this.logger.error)}}},void 0,this.listeners);t.set(s.id,a),this.triggerMap.set(e,t)}}}async stopSyncRemoteDrive(e){this.triggerMap.get(e)?.forEach(n=>n()),this.synchronizationManager.updateSyncStatus(e,null);const r=await this.synchronizationManager.getSynchronizationUnitsIds(e);for(const n of r)this.synchronizationManager.updateSyncStatus(n,null);return this.triggerMap.delete(e)}async _initializeDrive(e){const t=await this.getDrive(e);this.logger.verbose(`[SYNC DEBUG] Initializing drive ${e} with slug "${t.header.slug}"`),await this.synchronizationManager.initializeDriveSyncStatus(e,t),this.shouldSyncRemoteDrive(t)&&(this.logger.verbose(`[SYNC DEBUG] Starting sync for remote drive ${e}`),await this.startSyncRemoteDrive(e)),this.logger.verbose(`[SYNC DEBUG] Processing ${t.state.local.listeners.length} listeners for drive ${e}`);for(const r of t.state.local.listeners)if(r.callInfo?.transmitterType==="SwitchboardPush"){this.logger.verbose(`[SYNC DEBUG] Setting up SwitchboardPush listener ${r.listenerId} for drive ${e}`);const n=new pn(r.callInfo.data??"",this.listeners);this.logger.verbose(`[SYNC DEBUG] Created SwitchboardPush transmitter with URL: ${r.callInfo.data||"none"}`),await this.listenerManager.setListener(e,{block:r.block,driveId:t.header.id,filter:{branch:r.filter.branch??[],documentId:r.filter.documentId??[],documentType:r.filter.documentType??[],scope:r.filter.scope??[]},listenerId:r.listenerId,callInfo:r.callInfo,system:r.system,label:r.label??"",transmitter:n}).then(()=>{this.logger.verbose(`[SYNC DEBUG] Successfully set up listener ${r.listenerId} for drive ${e}`)})}else if(r.callInfo?.transmitterType==="PullResponder"){this.logger.verbose(`[SYNC DEBUG] Setting up PullResponder listener ${r.listenerId} for drive ${e}`);const n={driveId:e,listenerId:r.listenerId,block:!1,filter:r.filter,system:!1,label:`PullResponder #${r.listenerId}`,callInfo:{data:"",name:"PullResponder",transmitterType:"PullResponder"}},s=new ce(n,this.listenerManager);n.transmitter=s,await this.listenerManager.setListener(e,n)}else this.logger.error(`Skipping listener ${r.listenerId} with unsupported type ${r.callInfo?.transmitterType||"unknown"}`)}getDocumentModelModule(e){const t=this.documentModelModules.find(r=>r.documentModel.global.id===e);if(!t)throw new Error(`Document type ${e} not supported`);return t}getDocumentModelModules(){return[...this.documentModelModules]}addDocument(e,t){const r=typeof e=="string"?{documentType:e}:{document:e};return this.createDocument(r,{type:"local"},t)}async addDrive(e,t){const{global:r}=Bt(),n=dn({global:{...r,name:e.global.name??r.name,icon:e.global.icon??r.icon},local:{availableOffline:e.local?.availableOffline??!1,sharingType:e.local?.sharingType??"public",listeners:e.local?.listeners??[],triggers:e.local?.triggers??[]}});e.id&&e.id.length>0&&(n.header.id=e.id),e.slug&&e.slug.length>0&&(n.header.slug=e.slug),e.global.name&&(n.header.name=e.global.name);const s=e.preferredEditor||t;return s&&(n.header.meta={preferredEditor:s}),await this.documentStorage.create(n),e.slug&&e.slug.length>0&&await this.cache.deleteDriveBySlug(e.slug),await this._initializeDrive(n.header.id),this.eventEmitter.emit("driveAdded",n),n}async addRemoteDrive(e,t){await this.generateJwtHandler?.(e);const{id:r,name:n,slug:s,icon:o,meta:a}=t.expectedDriveInfo||await Be(e,this),{pullFilter:d,pullInterval:l,availableOffline:m,sharingType:f,listeners:b,triggers:w}=t,y=await ce.createPullResponderTrigger(r,e,{pullFilter:d,pullInterval:l},this.listeners);return await this.addDrive({id:r,slug:s,global:{name:n,icon:o},local:{triggers:[...w,y],listeners:b,availableOffline:m,sharingType:f}},a?.preferredEditor)}async deleteDrive(e){const t=await Promise.allSettled([this.stopSyncRemoteDrive(e),this.listenerManager.removeDrive(e),this.cache.deleteDrive(e),this.documentStorage.delete(e)]);this.eventEmitter.emit("driveDeleted",e),t.forEach(r=>{if(r.status==="rejected")throw r.reason})}async getDrives(){const e=[];let t;do{const{documents:r,nextCursor:n}=await this.documentStorage.findByType("powerhouse/document-drive",100,t);e.push(...r),t=n}while(t);return e}async getDrivesSlugs(){const e=await this.getDrives();return this.documentStorage.resolveSlugs(e)}async getDrive(e,t){let r;try{const o=await this.cache.getDrive(e);if(o&&ye(o)&&(r=o,Nt(r,t?.revisions)))return r}catch(o){this.logger.error("Error getting drive from cache",o)}const n=r??await this.documentStorage.get(e),s=this._buildDocument(n,t);if(ye(s))return t?.revisions||(this.cache.setDocument(e,s).catch(this.logger.error),this.cache.setDrive(e,s).catch(this.logger.error)),s;throw new Error(`Document with id ${e} is not a Document Drive`)}async getDriveBySlug(e,t){try{const s=await this.cache.getDriveBySlug(e);if(s)return s}catch(s){this.logger.error("Error getting drive from cache",s)}const r=await this.documentStorage.getBySlug(e),n=this._buildDocument(r,t);if(ye(n))return this.cache.setDriveBySlug(e,n).catch(this.logger.error),n;throw new Error(`Document with slug ${e} is not a Document Drive`)}async getDriveIdBySlug(e){try{const r=await this.cache.getDriveBySlug(e);if(r)return r.header.id}catch(r){this.logger.error("Error getting drive from cache",r)}return(await this.documentStorage.getBySlug(e)).header.id}getDocument(e,t,r){const n=typeof t=="string"?t:e,s=typeof t=="object"?t:r;return this._getDocument(n,s)}async _getDocument(e,t){let r;try{if(r=await this.cache.getDocument(e),r&&Nt(r,t?.revisions))return r}catch(o){this.logger.error("Error getting document from cache",o)}const n=r??await this.documentStorage.get(e),s=this._buildDocument(n,t);return t?.revisions||this.cache.setDocument(e,s).catch(this.logger.error),s}getDocuments(e){return this.documentStorage.getChildren(e)}async addChild(e,t){try{await this.documentStorage.addChild(e,t)}catch(r){throw this.logger.error("Error adding child document",r),r}}async removeChild(e,t){try{const r=await this.synchronizationManager.getSynchronizationUnitsIds(e,[t]);await this.listenerManager.removeSyncUnits(e,r)}catch(r){this.logger.warn("Error removing sync units of child",r)}try{await this.documentStorage.removeChild(e,t)}catch(r){throw this.logger.error("Error adding child document",r),r}}async createDocument(e,t,r){return this.enableDualActionCreate?this.createDocumentDualAction(e,t,r):this.createDocumentLegacy(e,t,r)}async createDocumentLegacy(e,t,r){const{documentType:n,document:s}=Ct(e);let o;if(s){if("documentType"in e&&n!==s.header.documentType)throw new Error(`Provided document is not ${n}`);o=this._buildDocument(s).state}const a=s??this.getDocumentModelModule(n).utils.createDocument(o);let d;if("id"in e&&e.id)s?(d=a.header,a.header.id=e.id,this.logger.warn("Assigning an id to a document is deprecated. Use the header field instead.")):(this.logger.warn("Creating a document with an id is deprecated. Use the header field instead."),d=Le(e.id,n));else if("header"in e)await He(e.header),d=e.header;else if(s?.header){if(!s.header.id)throw new Error("Document header id is required");if(!s.header.documentType)throw new Error("Document header documentType is required");if(!s.header.createdAtUtcIso)throw new Error("Document header createdAtUtcIso is required");s.header.sig.nonce?await He(s.header):this.logger.warn("Creating a document with an unsigned id is deprecated. Use createSignedHeaderForSigner."),d=s.header}else d=Le(void 0,n);r&&(d.meta={...d.meta,...r});const l={header:d,operations:{global:[],local:[]},initialState:a.initialState,clipboard:[],state:o??a.state};await this.documentStorage.create(l);const m=Object.values(a.operations).flat();m.length&&(ye(a)?await this.legacyStorage.addDriveOperations(d.id,m,a):await this.legacyStorage.addDocumentOperations(d.id,m,a));const f=await this.getDocument(l.header.id);return this.eventEmitter.emit("documentAdded",f),f}async createDocumentDualAction(e,t,r){const{documentType:n,document:s}=Ct(e);let o;if(s){if("documentType"in e&&n!==s.header.documentType)throw new Error(`Provided document is not ${n}`);o=this._buildDocument(s).state}const a=s??this.getDocumentModelModule(n).utils.createDocument(o);let d,l=!1;if("id"in e&&e.id)s?(d=a.header,a.header.id=e.id,this.logger.warn("Assigning an id to a document is deprecated. Use the header field instead.")):(this.logger.warn("Creating a document with an id is deprecated. Use the header field instead."),d=Le(e.id,n));else if("header"in e)await He(e.header),l=!0,d=e.header;else if(s?.header){if(!s.header.id)throw new Error("Document header id is required");if(!s.header.documentType)throw new Error("Document header documentType is required");if(!s.header.createdAtUtcIso)throw new Error("Document header createdAtUtcIso is required");s.header.sig.nonce?(await He(s.header),l=!0):this.logger.warn("Creating a document with an unsigned id is deprecated. Use createSignedHeaderForSigner."),d=s.header}else d=Le(void 0,n),l=!1;r&&(d.meta={...d.meta,...r});const m="0.1.0",f=o??a.state,b=Object.values(a.operations).flat(),w=b.length===0;let y=[];if(w){const U=new Date().toISOString(),F=l?{signature:d.id,publicKey:d.sig.publicKey,nonce:d.sig.nonce,createdAtUtcIso:d.createdAtUtcIso,documentType:d.documentType}:void 0,E={model:n,version:"0.0.0",documentId:d.id,signing:F},L={id:`${d.id}-create`,type:"CREATE_DOCUMENT",timestampUtcMs:U,input:E,scope:"document"},P={model:n,fromVersion:"0.0.0",toVersion:m,documentId:d.id,initialState:f},j={id:`${d.id}-upgrade`,type:"UPGRADE_DOCUMENT",timestampUtcMs:U,input:P,scope:"document"},V={state:Lt()},Z=ar(V,"document"),se=ar({state:f},"document");y=[{index:0,skip:0,hash:Z,timestampUtcMs:U,action:L},{index:1,skip:0,hash:se,timestampUtcMs:U,action:j}]}else y=b;const I=cr(y);I.header||(I.header=[]),I.document||(I.document=[]),I.global||(I.global=[]),I.local||(I.local=[]);const N={header:d,operations:I,initialState:f,clipboard:[],state:f};await this.documentStorage.create(N);const C=await this.getDocument(N.header.id,{checkHashes:!0});return this.eventEmitter.emit("documentAdded",C),C}async deleteDocument(e){try{const t=await this.synchronizationManager.getSynchronizationUnitsIds(void 0,[e]);for(const n of t)this.synchronizationManager.updateSyncStatus(n,null);const r=await this.documentStorage.getParents(e);for(const n of r)this.listenerManager.removeSyncUnits(n,t).catch(this.logger.warn)}catch(t){this.logger.warn("Error deleting document",t)}await Promise.allSettled([this.cache.deleteDocument(e).catch(this.logger.warn),this.documentStorage.delete(e).catch(this.logger.warn)]),this.eventEmitter.emit("documentDeleted",e)}async _processOperations(e,t,r){const n=[],s=[],o=await this._addDocumentResultingStage(t,e);let a=this._buildDocument(o),d;const l=cr(r);for(const m of Object.keys(l)){const f=t.operations[m]||[],b=vs(l[m]||[],f);if(b.length<1)continue;const w=Dt(Ge(f)),[y,I]=ws(w,b),N=(I.length<1?y:bs(w,y,Is)).filter(C=>w.length<1||Ds(w[w.length-1],C));for(const C of N){let U=!1;if(I.length>0){const F=r.find(E=>E.hash===C.hash);U=!F||F.index!==C.index||F.skip!==C.skip}try{const F=this.options.taskQueueMethod,E=()=>this._performOperation(e,a,C,U),L=await(F?$t(E,F):E());a=L.document,s.push(...L.signals),n.push(L.operation)}catch(F){d=F instanceof ie?F:new ie("ERROR",C,F.message,F.cause);break}}}return{document:a,operationsApplied:n,signals:s,error:d}}async _addDocumentResultingStage(e,t,r){const n=r?.revisions!==void 0?Mr(e.operations,r.revisions):e.operations,s=Ve(n);for(const o of Object.keys(s)){const a=s[o];if(!a)continue;const d=a.at(-1);d&&!d.resultingState&&(d.resultingState=await(ye(e)?this.legacyStorage.getOperationResultingState?.(t,d.index,d.action.scope,"main"):this.legacyStorage.getDriveOperationResultingState?.(t,d.index,d.action.scope,"main")))}return{...e,operations:s}}_buildDocument(e,t){if(e.state&&(!t||t.checkHashes===!1)&&Nt(e,t?.revisions))return e;const r=this.getDocumentModelModule(e.header.documentType),n=t?.revisions!==void 0?Mr(e.operations,t.revisions):e.operations,s=Ve(n),o=Object.keys(s),a=new Set([...o,"global","local"]),d={},l={};for(const w of a)d[w]=[],l[w]=[];for(const[w,y]of Object.entries(s))if(y)for(const I of y)if(I.action.type==="CREATE_DOCUMENT"||I.action.type==="UPGRADE_DOCUMENT"){const _=d[w];_&&_.push(I)}else{const _=l[w];_&&_.push(I)}const m=Cr(e.initialState,l,r.reducer,void 0,e.header,void 0,{...t,checkHashes:t?.checkHashes??!0,reuseOperationResultingState:t?.checkHashes??!0}),f=new Set([...Object.keys(s),...Object.keys(d),...Object.keys(m.operations)]),b={};for(const w of f)b[w]=[...d[w]||[],...m.operations[w]||[]];return{...m,operations:b}}async _performOperation(e,t,r,n=!1){const s=this.getDocumentModelModule(t.header.documentType),o=[];let a=t;const d=r.action.scope,l=t.operations[d]||[],b=Ve({...t.operations,[d]:Ss(l,r)})[d]?.at(-1);b&&!b.resultingState&&(b.resultingState=await(ye(t)?this.legacyStorage.getOperationResultingState?.(e,b.index,b.action.scope,"main"):this.legacyStorage.getDriveOperationResultingState?.(e,b.index,b.action.scope,"main")));const w=a.operations[d]||[],y=[];if(a=s.reducer(a,r.action,C=>{let U;switch(C.type){case"CREATE_CHILD_DOCUMENT":U=()=>this.addChild(e,C.input.id);break;case"DELETE_CHILD_DOCUMENT":U=()=>this.removeChild(e,C.input.id);break;case"COPY_CHILD_DOCUMENT":U=()=>this.addChild(e,C.input.newId);break}U&&y.push(()=>U().then(F=>({signal:C,result:F})))},{skip:r.skip,reuseOperationResultingState:!0,replayOptions:{operation:r}}),r.action.type==="NOOP"&&r.skip>0&&a.clipboard.length===0){const C=a.operations[d]||[],U=Dt(Ge(C)),F=Dt(Ge(w)),E=Es(F,U);a={...a,clipboard:Ge(E.filter(L=>L.action.type!=="NOOP")).reverse()}}const I=a.operations[r.action.scope];if(!I)throw new ie("ERROR",r,`No operations found for scope: ${r.action.scope}`);const N=I.filter(C=>C.index==r.index&&C.skip==r.skip).at(0);if(!N)throw new ie("ERROR",r,`Operation with index ${r.index}:${r.skip} was not applied.`);if(!N.error&&N.hash!==r.hash&&!n)throw this.logger.warn(JSON.stringify(N,null,2)),new hi(r,N);for(const C of y){const U=await C();o.push(U)}return{document:a,signals:o,operation:N}}addOperation(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this.addOperations(s,[o],a)}async _addOperations(e,t){if(this.legacyStorage.addDocumentOperationsWithTransaction)await this.legacyStorage.addDocumentOperationsWithTransaction(e,t);else{const r=await this.documentStorage.get(e),n=await t(r);n.operations.length>0&&await this.legacyStorage.addDocumentOperations(e,n.operations,n.document)}}async queueDocument(e,t){const{id:r,documentType:n,document:s}=Ct(e);if(!r)throw new Error("Document id is required",{cause:e});if(!n)throw new Error("Document type is required",{cause:e});if(await this.documentStorage.exists(r))throw new ke(r);let a;const d=new Promise((l,m)=>{const f=this.queueManager.on("jobCompleted",(w,y)=>{w.jobId===a&&(f(),b(),l(y))}),b=this.queueManager.on("jobFailed",(w,y)=>{w.jobId===a&&(f(),b(),m(y))})});try{a=await this.queueManager.addJob({documentId:r,documentType:n,initialState:s?.state,header:s?.header,options:t})}catch(l){throw this.logger.error("Error adding job",l),l}return d}queueOperation(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueOperations(s,[o],a)}async resultIfExistingOperations(e,t){try{const r=await this.getDocument(e);return t.find(s=>{if(!s.id)return!0;const o=r.operations[s.action.scope];return o?!o.find(a=>a.id===s.id&&a.index===s.index&&a.action.type===s.action.type&&a.hash===s.hash):!0})?void 0:{status:"SUCCESS",document:r,operations:t,signals:[]}}catch(r){r.message.includes(`Document with id ${e} not found`)||console.error(r);return}}queueOperations(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueOperations(s,o,a)}async _queueOperations(e,t,r){const n=await this.resultIfExistingOperations(e,t);if(n)return n;let s;const o=new Promise((a,d)=>{const l=this.queueManager.on("jobCompleted",(f,b)=>{f.jobId===s&&(l(),m(),a(b))}),m=this.queueManager.on("jobFailed",(f,b)=>{f.jobId===s&&(l(),m(),d(b))})});try{s=await this.queueManager.addJob({documentId:e,operations:t,options:r})}catch(a){throw this.logger.error("Error adding job",a),a}return o}queueAction(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueActions(s,[o],a)}queueActions(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueActions(s,o,a)}async _queueActions(e,t,r){try{const n=await this.queueManager.addJob({documentId:e,actions:t,options:r});return await new Promise((s,o)=>{const a=this.queueManager.on("jobCompleted",(l,m)=>{l.jobId===n&&(a(),d(),s(m))}),d=this.queueManager.on("jobFailed",(l,m)=>{l.jobId===n&&(a(),d(),o(m))})})}catch(n){throw this.logger.error("Error adding job",n),n}}async queueDriveAction(e,t,r){return this.queueDriveActions(e,[t],r)}async queueDriveActions(e,t,r){try{const n=await this.queueManager.addJob({documentId:e,actions:t,options:r});return await new Promise((s,o)=>{const a=this.queueManager.on("jobCompleted",(l,m)=>{l.jobId===n&&(a(),d(),s(m))}),d=this.queueManager.on("jobFailed",(l,m)=>{l.jobId===n&&(a(),d(),o(m))})})}catch(n){throw this.logger.error("Error adding drive job",n),n}}addOperations(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueOperations(s,o,a)}async processOperations(e,t,r){const n=await this.resultIfExistingOperations(e,t);if(n)return n;let s;const o=[],a=[];let d;try{await this._addOperations(e,async w=>{const y=await this._processOperations(e,w,t);if(!y.document)throw this.logger.error("Invalid document"),y.error??new Error("Invalid document");return s=y.document,d=y.error,a.push(...y.signals),o.push(...y.operationsApplied),{operations:y.operationsApplied,document:y.document}});const l=new Array;if(s){this.cache.setDocument(e,s).catch(this.logger.error);for(const w of o){const y={documentId:e,documentType:s.header.documentType,scope:w.action.scope,branch:"main",revision:w.index+1,lastUpdated:w.timestampUtcMs};l.some(_=>_.documentId===y.documentId&&_.scope===y.scope&&_.branch===y.branch)||l.push(y)}}const f=o.find(w=>!t.find(y=>y.id===w.id&&y.index===w.index&&y.skip===w.skip&&y.hash===w.hash))?{type:"local"}:r?.source??{type:"local"},b=this.getOperationSource(f);if(l.length&&this.listenerManager.updateSynchronizationRevisions(l,f,()=>{this.synchronizationManager.updateSyncStatus(e,{[b]:"SYNCING"});for(const w of l)this.synchronizationManager.updateSyncStatus(w,{[b]:"SYNCING"})},this.handleListenerError.bind(this),r?.forceSync??f.type==="local").then(w=>{w.length&&this.synchronizationManager.updateSyncStatus(e,{[b]:"SUCCESS"});for(const y of l)this.synchronizationManager.updateSyncStatus(y,{[b]:"SUCCESS"})}).catch(w=>{this.logger.error("Non handled error updating sync revision",w),this.synchronizationManager.updateSyncStatus(e,{[b]:"ERROR"},w);for(const y of l)this.synchronizationManager.updateSyncStatus(y,{[b]:"ERROR"},w)}),d)throw d;return this.eventEmitter.emit("documentOperationsAdded",e,t),this.eventEmitter.emit("operationsAdded",e,t),{status:"SUCCESS",document:s,operations:o,signals:a}}catch(l){const m=l instanceof ie?l:new ie("ERROR",void 0,l.message,l.cause);return{status:m.status,error:m,document:s,operations:o,signals:a}}}addDriveOperation(e,t,r){return this.addDriveOperations(e,[t],r)}async _addDriveOperations(e,t){if(this.legacyStorage.addDriveOperationsWithTransaction)return this.legacyStorage.addDriveOperationsWithTransaction(e,t);{const r=await this.documentStorage.get(e),n=await t(r);return n.operations.length>0&&await this.legacyStorage.addDriveOperations(e,n.operations,n.document),n}}queueDriveOperation(e,t,r){return this.queueDriveOperations(e,[t],r)}async resultIfExistingDriveOperations(e,t){try{const r=await this.getDrive(e);return t.find(s=>{if(!s.id)return!0;const o=r.operations[s.action.scope];return o?!o.find(a=>a.id===s.id&&a.index===s.index&&a.action.type===s.action.type&&a.hash===s.hash):!0})?void 0:{status:"SUCCESS",document:r,operations:t,signals:[]}}catch(r){console.error(r);return}}async queueDriveOperations(e,t,r){const n=await this.resultIfExistingDriveOperations(e,t);if(n)return n;try{const s=await this.queueManager.addJob({documentId:e,operations:t,options:r});return await new Promise((o,a)=>{const d=this.queueManager.on("jobCompleted",(m,f)=>{m.jobId===s&&(d(),l(),o(f))}),l=this.queueManager.on("jobFailed",(m,f)=>{m.jobId===s&&(d(),l(),a(f))})})}catch(s){throw this.logger.error("Error adding drive job",s),s}}async addDriveOperations(e,t,r){return this.queueDriveOperations(e,t,r)}async processDriveOperations(e,t,r){let n;const s=[],o=[];let a;const d=await this.resultIfExistingDriveOperations(e,t);if(d)return d;try{if(await this._addDriveOperations(e,async m=>{const f=await this._processOperations(e,m,t.slice());return n=f.document,s.push(...f.operationsApplied),o.push(...f.signals),a=f.error,{operations:f.operationsApplied,document:f.document}}),!n||!ye(n))throw a??new Error("Invalid Document Drive document");this.cache.setDocument(e,n).catch(this.logger.error),this.cache.setDrive(e,n).catch(this.logger.error);const l=s.filter(m=>m.action.scope==="global").slice().pop();if(l){const f=s.find(w=>!t.find(y=>y.id===w.id&&y.index===w.index&&y.skip===w.skip&&y.hash===w.hash))?{type:"local"}:r?.source??{type:"local"},b=this.getOperationSource(f);this.listenerManager.updateSynchronizationRevisions([{documentId:e,documentType:n.header.documentType,scope:"global",branch:"main",lastUpdated:l.timestampUtcMs,revision:l.index}],f,()=>{this.synchronizationManager.updateSyncStatus(e,{[b]:"SYNCING"})},this.handleListenerError.bind(this),r?.forceSync??f.type==="local").then(w=>{w.length&&this.synchronizationManager.updateSyncStatus(e,{[b]:"SUCCESS"})}).catch(w=>{this.logger.error("Non handled error updating sync revision",w),this.synchronizationManager.updateSyncStatus(e,{[b]:"ERROR"},w)})}if(this.shouldSyncRemoteDrive(n)?this.startSyncRemoteDrive(e).catch(this.logger.error):this.stopSyncRemoteDrive(e).catch(this.logger.error),a)throw a;return this.eventEmitter.emit("driveOperationsAdded",e,t),this.eventEmitter.emit("operationsAdded",e,t),{status:"SUCCESS",document:n,operations:s,signals:o}}catch(l){const m=l instanceof ie?l:new ie("ERROR",void 0,l.message,l);return{status:m.status,error:m,document:n,operations:s,signals:o}}}_buildOperations(e,t){const r=[],{reducer:n}=this.getDocumentModelModule(e.header.documentType);for(const s of t){e=n(e,s);const o=e.operations[s.scope];if(!o)throw new Error(`No operations found for scope: ${s.scope}`);const a=o.slice().pop();if(!a)throw new Error("Error creating operations");r.push(a)}return r}addAction(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._addAction(s,o,a)}async _addAction(e,t,r){return this.addActions(e,[t],r)}addActions(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueActions(s,o,a)}async processActions(e,t,r){const n=await this.getDocument(e),s=this._buildOperations(n,t);return this.processOperations(e,s,r)}async addDriveAction(e,t,r){return"synchronizationUnits"in t.input?this._legacyAddFileAction(e,t,r):this.addDriveActions(e,[t],r)}async _legacyAddFileAction(e,t,r){const n=this.getDocumentModelModule(t.input.documentType).utils.createDocument(t.input.document?.state||void 0);n.header.id=t.input.id,n.header.name=t.input.name,n.header.documentType=t.input.documentType,await this.queueDocument({document:n},{source:r?.source||{type:"local"}});const s={...t,input:{id:t.input.id,documentType:n.header.documentType,name:t.input.name,parentFolder:t.input.parentFolder}};return await this.addAction(e,s,r)}async addDriveActions(e,t,r){return this.queueDriveActions(e,t,r)}async processDriveActions(e,t,r){const n=await this.getDrive(e),s=this._buildOperations(n,t);return this.processDriveOperations(e,s,r)}async detachDrive(e){const t=await this.getDrive(e),r=t.state.local.listeners||[],n=t.state.local.triggers||[];for(const s of r)await this.addDriveAction(e,en({listenerId:s.listenerId}));for(const s of n)await this.addDriveAction(e,tn({triggerId:s.id}));await this.addDriveAction(e,Zr({type:"LOCAL"}))}getSyncStatus(e,t,r){return this.synchronizationManager.getSyncStatus(e,t,r)}on(e,t){return this.eventEmitter.on(e,t)}emit(e,...t){return this.eventEmitter.emit(e,...t)}updateSyncStatus(e,t,r){this.synchronizationManager.updateSyncStatus(e,t,r)}initializeDriveSyncStatus(e,t){return this.synchronizationManager.initializeDriveSyncStatus(e,t)}getCombinedSyncUnitStatus(e){return this.synchronizationManager.getCombinedSyncUnitStatus(e)}async saveStrand(e,t){const r=!await this.documentStorage.exists(e.documentId);let n;r&&(n=await this.queueDocument({id:e.documentId,documentType:e.documentType}));const s=e.operations.map(o=>({...o,action:{id:o.actionId,timestampUtcMs:o.timestampUtcMs,type:o.type,input:o.input,context:o.context,scope:e.scope},scope:e.scope,branch:e.branch}));if((!r||n?.status==="SUCCESS")&&s.length)try{n=await this.queueOperations(e.documentId,s,{source:t})}catch(o){throw this.logger.error("Error queueing operations",o),o}if(!n)return this.logger.debug(`Document ${e.documentId} already exists`),{status:"SUCCESS",document:await this.getDocument(e.documentId),operations:[],signals:[]};if(n.status==="ERROR"){const o=this.getOperationSource(t);this.synchronizationManager.updateSyncStatus({documentId:e.documentId||e.driveId,scope:e.scope,branch:e.branch},{[o]:n.status},n.error)}return this.eventEmitter.emit("strandUpdate",e),n}setGenerateJwtHandler(e){this.generateJwtHandler=e,this.listenerManager.setGenerateJwtHandler(e)}removeJwtHandler(){this.generateJwtHandler=void 0,this.listenerManager.removeJwtHandler()}}const po=eo(go);class at extends Error{constructor(e){super(e||"Aborted"),this.name="AbortError"}}class mo{logger=pe(["MemoryStorage"]);documents;driveManifests;slugToDocumentId;constructor(){this.documents={},this.driveManifests={},this.slugToDocumentId={}}resolveIds(e,t){const r=[];for(const n of e){const s=this.slugToDocumentId[n];if(!s)throw new we(n);r.push(s)}if(t?.aborted)throw new at("Aborted");return Promise.resolve(r)}resolveSlugs(e,t){const r=[];for(const n of e){const s=this.documents[n];if(!s)throw new we(n);r.push(s.header.slug)}if(t?.aborted)throw new at("Aborted");return Promise.resolve(r)}exists(e){return Promise.resolve(!!this.documents[e])}create(e){const t=e.header.id;if(!tt(t))throw new et(t);if(this.documents[t])throw new ke(t);const r=e.header.slug?.length>0?e.header.slug:t;if(!nn(r))throw new rn(r);if(r&&this.slugToDocumentId[r])throw new ke(t,Fe.SLUG);return e.header.slug=r,this.documents[t]=e,r&&(this.slugToDocumentId[r]=t),e.header.documentType==="powerhouse/document-drive"&&this.updateDriveManifest(t,{documentIds:new Set}),Promise.resolve()}get(e){const t=this.documents[e];return t?Promise.resolve(t):Promise.reject(new we(e))}getBySlug(e){const t=this.slugToDocumentId[e];return t?this.get(t):Promise.reject(new we(e))}async findByType(e,t=100,r){const n=Object.entries(this.documents).filter(([d,l])=>l.header.documentType===e).map(([d,l])=>({id:d,document:l}));n.sort((d,l)=>{const m=new Date(d.document.header.createdAtUtcIso),f=new Date(l.document.header.createdAtUtcIso);if(m.getTime()===f.getTime()){const b=d.id,w=l.id;return b.localeCompare(w)}return m.getTime()-f.getTime()});let s=0;if(r){const d=n.findIndex(({id:l})=>l===r);d!==-1&&(s=d)}const o=Math.min(s+t,n.length);let a;return o<n.length&&(a=n[o].id),{documents:n.slice(s,o).map(({id:d})=>d),nextCursor:a}}async delete(e){const t=this.documents[e];if(t){const n=t.header.slug?.length>0?t.header.slug:e;n&&this.slugToDocumentId[n]===e&&delete this.slugToDocumentId[n]}const r=await this.getParents(e);for(const n of r)await this.removeChild(n,e);return delete this.driveManifests[e],this.documents[e]?(delete this.documents[e],Promise.resolve(!0)):Promise.resolve(!1)}async addChild(e,t){if(e===t)return Promise.reject(new Error("Cannot associate a document with itself"));if((await this.getChildren(t)).includes(e))return Promise.reject(new Error("Cannot associate a document with its child"));const n=this.getManifest(e);return n.documentIds.add(t),this.updateDriveManifest(e,n),Promise.resolve()}async removeChild(e,t){const r=this.getManifest(e);return r.documentIds.delete(t)?(this.updateDriveManifest(e,r),Promise.resolve(!0)):Promise.resolve(!1)}async getChildren(e){return[...this.getManifest(e).documentIds]}async getParents(e){const t=[];for(const[r,n]of Object.entries(this.driveManifests))n.documentIds.has(e)&&t.push(r);return t}async clear(){this.documents={},this.driveManifests={},this.slugToDocumentId={}}async addDocumentOperations(e,t,r){const n=await this.get(e);if(!r)return Promise.reject(new we(e));const s=st(n.operations,t),o={};for(const[a,d]of Object.entries(s))o[a]=Ie(d);this.documents[e]={...n,state:r.state,initialState:r.initialState,header:{...n.header,...r.header,revision:o},operations:s,clipboard:r.clipboard}}async addDriveOperations(e,t,r){const n=await this.get(e),s=st(n.operations,t),o={};for(const[a,d]of Object.entries(s))o[a]=Ie(d);this.documents[e]={...n,state:r.state,initialState:r.initialState,header:{...n.header,...r.header,revision:o},operations:s,clipboard:r.clipboard}}async getSynchronizationUnitsRevision(e){return(await Promise.allSettled(e.map(async r=>{try{const n=await this.get(r.documentId);if(!n||!Object.keys(n.state).includes(r.scope))return;const s=n.operations[r.scope];return s?{documentId:r.documentId,documentType:r.documentType,scope:r.scope,branch:r.branch,lastUpdated:s.at(-1)?.timestampUtcMs??n.header.createdAtUtcIso,revision:s.length>0?Ie(s):0}:void 0}catch(n){this.logger.error("Error getting synchronization units revision",n);return}}))).reduce((r,n)=>(n.status==="fulfilled"&&n.value!==void 0&&r.push(n.value),r),[])}async findStorageUnitsBy(e,t,r){const n=[],{parentId:s,documentId:o,documentModelType:a,scope:d}=sn(e);let l;if(s){const w=new Set;for(const y of s)(await this.getChildren(y)).forEach(_=>w.add(_));l=on(s,w)}else l=new Set(Object.keys(this.documents));l=o?an(o,l):l;for(const w of l){const y=this.documents[w];if(y&&!(a&&!a.has(y.header.documentType)))for(const[I]of Object.entries(y.state))d&&!d.has(I)||n.push({documentId:w,documentModelType:y.header.documentType,scope:I,branch:"main"})}let m=0;if(r){const w=n.findIndex(y=>y.documentId===r);w!==-1&&(m=w)}const f=Math.min(m+t,n.length),b=f<n.length?n[f].documentId:void 0;return{units:n.slice(m,f),nextCursor:b}}getManifest(e){return this.driveManifests[e]||(this.driveManifests[e]={documentIds:new Set}),this.driveManifests[e]}updateDriveManifest(e,t){this.driveManifests[e]=t}}class yo{emitter=hn();emit(e,...t){return this.emitter.emit(e,...t)}on(e,t){return this.emitter.on(e,t)}}class X{internalMap=new Map;static keySeparator="|";static escape(e){return e.replace(/\|/g,"\\|")}static unescape(e){return e.replace(/\\\|/g,"|")}static buildKey(e){return`${X.escape(e.documentId)}${X.keySeparator}${X.escape(e.scope)}${X.keySeparator}${X.escape(e.branch)}`}static parseKey(e){const t=e.split(new RegExp("(?<!\\\\)\\|")).map(o=>X.unescape(o)),[r,n,s]=t;return{documentId:r,scope:n,branch:s}}set(e,t){return this.internalMap.set(X.buildKey(e),t),this}get(e){return this.internalMap.get(X.buildKey(e))}has(e){return this.internalMap.has(X.buildKey(e))}delete(e){return this.internalMap.delete(X.buildKey(e))}clear(){this.internalMap.clear()}get size(){return this.internalMap.size}keys(e){const t=this.internalMap.keys();return{[Symbol.iterator](){return this},next(){for(;;){const r=t.next();if(r.done)return{done:!0,value:void 0};const n=r.value,s=X.parseKey(n);if(!(e&&(s.documentId!==e.documentId||e.scope!==void 0&&s.scope!==e.scope)))return{done:!1,value:s}}}}}values(e){const t=this.internalMap.entries();return{[Symbol.iterator](){return this},next(){for(;;){const r=t.next();if(r.done)return{done:!0,value:void 0};const[n,s]=r.value,o=X.parseKey(n);if(!(e&&(o.documentId!==e.documentId||e.scope!==void 0&&o.scope!==e.scope)))return{done:!1,value:s}}}}}entries(e){const t=this.internalMap.entries();return{[Symbol.iterator](){return this},next(){for(;;){const r=t.next();if(r.done)return{done:!0,value:void 0};const[n,s]=r.value,o=X.parseKey(n);if(!(e&&(o.documentId!==e.documentId||e.scope!==void 0&&o.scope!==e.scope)))return{done:!1,value:[o,s]}}}}}[Symbol.iterator](){return this.entries()}forEach(e,t){for(const[r,n]of this.entries())e.call(t,n,r,this)}deleteByDocumentId(e){for(const t of this.internalMap.keys())t.startsWith(e+X.keySeparator)&&this.internalMap.delete(t)}deleteByDocumentIdAndScope(e,t){const r=`${e}${X.keySeparator}${t}${X.keySeparator}`;for(const n of this.internalMap.keys())n.startsWith(r)&&this.internalMap.delete(n)}getAllByDocumentId(e){const t=[];for(const[r,n]of this.internalMap.entries())r.startsWith(e+X.keySeparator)&&t.push([X.parseKey(r),n]);return t}getAllByDocumentIdAndScope(e,t){const r=`${e}${X.keySeparator}${t}${X.keySeparator}`,n=[];for(const[s,o]of this.internalMap.entries())s.startsWith(r)&&n.push([X.parseKey(s),o]);return n}}function vo(i,e=250){let t;return(r=!1,...n)=>(t&&clearTimeout(t),new Promise((s,o)=>{r?i(...n).then(s).catch(o):t=setTimeout(()=>{i(...n).then(s).catch(o)},e)}))}class qt{static LISTENER_UPDATE_DELAY=250;logger=pe(["ListenerManager",Math.floor(Math.random()*999).toString()]);syncManager;options;generateJwtHandler;listenerStateByDriveId=new Map;constructor(e,t=ot){this.syncManager=e,this.options={...ot,...t},this.logger.verbose("constructor(...)")}setGenerateJwtHandler(e){this.generateJwtHandler=e}removeJwtHandler(){this.generateJwtHandler=void 0}async initialize(e){this.logger.verbose("initialize(...)"),typeof window<"u"&&window.addEventListener("online",()=>{this.triggerUpdate(!1,{type:"local"},void 0,e).catch(t=>{this.logger.error("Non handled error updating listeners",t)})})}driveHasListeners(e){return this.listenerStateByDriveId.has(e)}async setListener(e,t){if(this.logger.verbose(`setListener(drive: ${e}, listener: ${t.listenerId})`),e!==t.driveId)throw new Error("Drive ID mismatch");let r;try{r=this.getListenerState(e,t.listenerId)}catch{r={}}this.setListenerState(e,t.listenerId,{...r,block:t.block,driveId:t.driveId,pendingTimeout:"0",listener:t,listenerStatus:"CREATED",syncUnits:new X}),await this.triggerUpdate(!0,{type:"local"})}async removeListener(e,t){this.logger.verbose("setListener()");const r=this.listenerStateByDriveId.get(e);return r?Promise.resolve(r.delete(t)):!1}async removeSyncUnits(e,t){const r=this.listenerStateByDriveId.get(e);if(r){for(const[,n]of r)for(const s of t)n.syncUnits.delete(s);return Promise.resolve()}}async updateSynchronizationRevisions(e,t,r,n,s=!1){const o=this.listenerStateByDriveId.values(),a=[];for(const[[d,l]]of o)if(!(a.find(f=>f.listenerId===l.listener.listenerId)||!l.listener.transmitter?.transmit))for(const f of e){if(!this._checkFilter(l.listener.filter,f))continue;const b=l.syncUnits.get(f);if(!b||b.listenerRev<f.revision){a.push(l.listener);break}}return this.triggerUpdate(s,t,r,n)}async updateListenerRevision(e,t,r,n){const s=this.listenerStateByDriveId.get(t);if(!s)return;const o=s.get(e);if(!o)return;const a=new Date().toISOString();return o.syncUnits.set(r,{listenerRev:n,lastUpdated:a}),Promise.resolve()}triggerUpdate=vo(this._triggerUpdate.bind(this),qt.LISTENER_UPDATE_DELAY);async _triggerUpdate(e,t,r,n=500){if(this.logger.verbose(`_triggerUpdate(source: ${e.type}, maxContinues: ${n})`,this.listenerStateByDriveId),n<0)throw new Error("Maximum retries exhausted.");const s=[];for(const[o,a]of this.listenerStateByDriveId)for(const[d,l]of a){const m=l.listener.transmitter;if(!m?.transmit)continue;const f=await this.getListenerSyncUnits(o,d),b=[];this.logger.verbose("syncUnits",f);const w=f.map(y=>async()=>{const I=l.syncUnits.get(y);if(I&&I.listenerRev>=y.revision){this.logger.verbose(`Abandoning push for sync unit ${JSON.stringify(y)}: already up-to-date (${I.listenerRev} >= ${y.revision})`);return}else this.logger.verbose(`Listener out-of-date for sync unit (${y.scope}, ${y.documentId}): ${I?.listenerRev} < ${y.revision}`);const _=[];if(y.revision>0){try{const N=await this.syncManager.getOperationData(y,{fromRevision:I?.listenerRev});_.push(...N)}catch(N){this.logger.error(N)}if(!_.length){this.logger.verbose(`Abandoning push for ${JSON.stringify(y)}: no operations found`);return}}b.push({driveId:o,documentType:y.documentType,documentId:y.documentId,branch:y.branch,operations:_,scope:y.scope})});if(this.options.sequentialUpdates){this.logger.verbose(`Collecting ${w.length} syncUnit strandUpdates in sequence`);for(const y of w)await y()}else this.logger.verbose(`Collecting ${w.length} syncUnit strandUpdates in parallel`),await Promise.all(w.map(y=>y()));if(b.length==0){this.logger.verbose(`No strandUpdates needed for listener ${d}`);continue}l.pendingTimeout=new Date(new Date().getTime()/1e3+300).toISOString(),l.listenerStatus="PENDING";try{this.logger.verbose(`_triggerUpdate(source: ${e.type}) > transmitter.transmit`);const y=await m.transmit(b,e);this.logger.verbose(`_triggerUpdate(source: ${e.type}) > transmission succeeded`,y),l.pendingTimeout="0",l.listenerStatus="PENDING";const I=new Date().toISOString();let _=!1;for(const N of y){const C=f.find(U=>N.documentId===U.documentId&&N.scope===U.scope&&N.branch===U.branch);if(C){l.syncUnits.set(C,{lastUpdated:I,listenerRev:N.revision});const U=b.find(F=>F.driveId===N.driveId&&F.documentId===N.documentId&&F.scope===N.scope&&F.branch===N.branch);if(U&&U.operations.length>0){const F=U.operations.at(-1)?.index;F!==N.revision?(this.logger.verbose(`Revision still out-of-date for ${U.documentId}:${U.scope}:${U.branch} ${F} <> ${N.revision}`),_=!0):this.logger.verbose(`Revision match for ${U.documentId}:${U.scope}:${U.branch} ${F}`)}}else this.logger.warn(`Received revision for untracked unit for listener ${l.listener.listenerId}`,N)}for(const N of y){const C=N.status==="ERROR";if(N.error?.includes("Missing operations"))_=!0;else if(C)throw new ie(N.status,void 0,N.error,N.error)}if(!_)s.push({listenerId:l.listener.listenerId,listenerRevisions:y});else{const N=await this._triggerUpdate(e,t,r,n-1);s.push(...N)}l.listenerStatus="SUCCESS"}catch(y){r?.(y,o,l),l.listenerStatus=y instanceof ie?y.status:"ERROR"}}return this.logger.verbose(`Returning listener updates (maxContinues: ${n})`,s),s}_checkFilter(e,t){const{branch:r,documentId:n,scope:s,documentType:o}=t;return!!((!e.branch||e.branch.includes(r)||e.branch.includes("*"))&&(!e.documentId||e.documentId.includes(n)||e.documentId.includes("*"))&&(!e.scope||e.scope.includes(s)||e.scope.includes("*"))&&(!e.documentType||e.documentType.includes(o)||e.documentType.includes("*")))}getListenerSyncUnits(e,t){const r=this.listenerStateByDriveId.get(e)?.get(t);if(!r)return[];const n=r.listener.filter;return this.syncManager.getSynchronizationUnits(e,n.documentId??["*"],n.scope??["*"],n.branch??["*"],n.documentType??["*"])}async removeDrive(e){const t=this.listenerStateByDriveId.get(e);if(t){this.listenerStateByDriveId.delete(e);for(const[r,n]of t)try{await n.listener.transmitter?.disconnect?.()}catch(s){this.logger.error(s)}}}async getStrands(e,t,r){this.logger.verbose(`[SYNC DEBUG] ListenerManager.getStrands called for drive: ${e}, listener: ${t}, options: ${JSON.stringify(r||{})}`);let n;try{n=this.getListenerState(e,t),this.logger.verbose(`[SYNC DEBUG] Found listener state for drive: ${e}, listener: ${t}, status: ${n.listenerStatus}`)}catch(o){throw this.logger.error(`[SYNC DEBUG] Failed to find listener state for drive: ${e}, listener: ${t}. Error: ${o}`),o}const s=[];try{const o=await this.getListenerSyncUnits(e,t);this.logger.verbose(`[SYNC DEBUG] Retrieved ${o.length} sync units for drive: ${e}, listener: ${t}`);const a=r?.limit;let d=0;const l=o.map(m=>async()=>{if(a&&d>=a)return;if(m.revision<0){this.logger.verbose(`[SYNC DEBUG] Skipping sync unit with negative revision: ${JSON.stringify(m)}, revision: ${m.revision}`);return}const f=n.syncUnits.get(m);if(f&&f.listenerRev>=m.revision){this.logger.verbose(`[SYNC DEBUG] Skipping sync unit - listener already up to date: ${JSON.stringify(m)}, listenerRev: ${f.listenerRev}, revision: ${m.revision}`);return}const{documentId:b,scope:w,branch:y}=m;let I=[];try{m.revision>0&&(this.logger.verbose(`[SYNC DEBUG] Getting operations for syncUnit: ${JSON.stringify(m)}`),I=await this.syncManager.getOperationData(m,{since:r?.since,fromRevision:r?.fromRevision??f?.listenerRev,limit:a?a-d:void 0})),this.logger.verbose(`[SYNC DEBUG] Retrieved ${I.length} operations for syncUnit: ${JSON.stringify(m)}`),d+=I.length,s.push({driveId:e,documentId:b,documentType:m.documentType,scope:w,branch:y,operations:I}),this.logger.verbose(`[SYNC DEBUG] Added strand with ${I.length} operations for syncUnit: ${JSON.stringify(m)}`)}catch(_){this.logger.error(`Error getting operations for syncUnit: ${JSON.stringify(m)}, error: ${_}`);return}});if(this.options.sequentialUpdates){this.logger.verbose(`[SYNC DEBUG] Processing ${l.length} sync units sequentially`);for(const m of l)await m()}else this.logger.verbose(`[SYNC DEBUG] Processing ${l.length} sync units in parallel`),await Promise.all(l.map(m=>m()))}catch(o){this.logger.error(`Error in getStrands: ${o}`)}return this.logger.verbose(`ListenerManager.getStrands returning ${s.length} strands for drive: ${e}, listener: ${t}`),s}getListenerState(e,t){let r=this.listenerStateByDriveId.get(e);r||(r=new Map,this.listenerStateByDriveId.set(e,r));const n=r.get(t);if(!n)throw new Error("Listener not found");return n}setListenerState(e,t,r){let n=this.listenerStateByDriveId.get(e);n||(n=new Map,this.listenerStateByDriveId.set(e,n)),n.set(t,r)}}class wo{storage;documentStorage;cache;documentModelModules;eventEmitter;syncStatus=new X;logger=pe(["SynchronizationManager"]);constructor(e,t,r,n,s){this.storage=e,this.documentStorage=t,this.cache=r,this.documentModelModules=n,this.eventEmitter=s}async getSynchronizationUnits(e,t,r,n,s){const o=await this.getSynchronizationUnitsIds(e,t,r,n,s);return this.logger.verbose(`getSynchronizationUnits query: ${JSON.stringify(o)}`),(await this.getSynchronizationUnitsRevision(o)).filter(d=>typeof d<"u")}async getSynchronizationUnitsRevision(e){const t=await this.storage.getSynchronizationUnitsRevision(e);return this.logger.verbose(`getSynchronizationUnitsRevision: ${JSON.stringify(t)}`),e.map(r=>t.find(n=>n.documentId===r.documentId&&n.scope===r.scope&&n.branch===r.branch))}async getSynchronizationUnitsIds(e,t,r,n,s){const o={parentId:e?[e]:void 0,documentId:t,documentModelType:s,scope:r,branch:n};let a;const d=[];do{const{units:l,nextCursor:m}=await this.documentStorage.findStorageUnitsBy(o,100,a);d.push(...l),a=m}while(a);return d.reduce((l,{documentModelType:m,...f})=>f.scope==="local"?l:l.concat([{...f,documentType:m}]),new Array)}async getSynchronizationUnit(e){const{scope:t,branch:r,documentId:n}=e,s=await this.getDocument(n);if(!Object.keys(s.state).includes(t))return;const o=s.operations[t]??[],a=o.at(-1);return{scope:t,branch:r,documentId:n,documentType:s.header.documentType,lastUpdated:a?.timestampUtcMs??s.header.lastModifiedAtUtcIso,revision:Ie(o)}}async getOperationData(e,t){this.logger.verbose(`[SYNC DEBUG] SynchronizationManager.getOperationData called for syncId: ${JSON.stringify(e)}, filter: ${JSON.stringify(t)}`);const r=await this.getDocument(e.documentId);this.logger.verbose(`[SYNC DEBUG] Retrieved document ${r.header.id} with type: ${r.header.documentType}`);const n=r.operations[e.scope]??[];this.logger.verbose(`[SYNC DEBUG] Found ${n.length} total operations in scope ${e.scope}`);const s=n.filter(a=>Object.keys(t).length===0||(t.since===void 0||Ci(t.since,a.timestampUtcMs))&&(t.fromRevision===void 0||a.index>=t.fromRevision));this.logger.verbose(`[SYNC DEBUG] Filtered to ${s.length} operations based on filter criteria`+(t.fromRevision!==void 0?` (fromRevision: ${t.fromRevision})`:""));const o=t.limit?s.slice(0,t.limit):s;if(this.logger.verbose(`[SYNC DEBUG] Returning ${o.length} operations after applying limit`),o.length>0){const a=o[0],d=o[o.length-1];this.logger.verbose(`[SYNC DEBUG] First operation: index=${a.index}, type=${a.action.type}`),this.logger.verbose(`[SYNC DEBUG] Last operation: index=${d.index}, type=${d.action.type}`)}return o.map(a=>({actionId:a.action.id,hash:a.hash,index:a.index,timestampUtcMs:a.timestampUtcMs,type:a.action.type,input:a.action.input,skip:a.skip,context:a.action.context,id:a.id}))}async getDocument(e){try{const r=await this.cache.getDocument(e);if(r)return r}catch(r){this.logger.error("Error getting document from cache",r)}const t=await this.documentStorage.get(e);return this._buildDocument(t)}_buildDocument(e){const t=this.getDocumentModelModule(e.header.documentType),r=Ve(e.operations);return Cr(e.initialState,r,t.reducer,void 0,e.header,void 0,{checkHashes:!0,reuseOperationResultingState:!0})}setDocumentModelModules(e){this.documentModelModules=e}getDocumentModelModule(e){const t=this.documentModelModules.find(r=>r.documentModel.global.id===e);if(!t)throw new Error(`Document type ${e} not supported`);return t}getCombinedSyncUnitStatus(e){if(!e.pull&&!e.push||e.pull==="INITIAL_SYNC")return"INITIAL_SYNC";if(e.push==="INITIAL_SYNC")return e.pull||"INITIAL_SYNC";const t=["ERROR","MISSING","CONFLICT","SYNCING","SUCCESS"];return Object.values(e).sort((n,s)=>t.indexOf(n)-t.indexOf(s))[0]}getSyncStatus(e,t="global",r="main"){const n=typeof e=="string"?{documentId:e,scope:t,branch:r}:e,s=this.syncStatus.get(n);return s?this.getCombinedSyncUnitStatus(s):new fi(n)}updateSyncStatus(e,t,r,n="global",s="main"){const o=typeof e=="string"?{documentId:e,scope:n,branch:s}:e;if(t===null){this.syncStatus.delete(o);return}const a=this.syncStatus.get(o);if(!a){this.initSyncStatus(o,t);return}if(Object.entries(t).some(([l,m])=>a[l]!==m)){const l=Object.entries(t).reduce((b,[w,y])=>({...b,[w]:b[w]==="INITIAL_SYNC"&&y==="SYNCING"?"INITIAL_SYNC":y}),a),m=this.getCombinedSyncUnitStatus(a),f=this.getCombinedSyncUnitStatus(l);this.syncStatus.set(o,l),m!==f&&this.eventEmitter&&this.eventEmitter.emit("syncStatus",o.documentId,this.getCombinedSyncUnitStatus(l),r,l,o.scope,o.branch)}}initSyncStatus(e,t){const r=Object.entries(t).reduce((n,[s,o])=>({...n,[s]:o!=="SYNCING"?o:"INITIAL_SYNC"}),{});this.syncStatus.set(e,r),this.eventEmitter&&this.eventEmitter.emit("syncStatus",e.documentId,this.getCombinedSyncUnitStatus(r),void 0,r,e.scope,e.branch)}async initializeDriveSyncStatus(e,t){const r=await this.getSynchronizationUnitsIds(e),n={pull:t.state.local.triggers.length>0?"INITIAL_SYNC":void 0,push:t.state.local.listeners.length>0?"SUCCESS":void 0};if(!n.pull&&!n.push)return;const s=[{documentId:e,scope:"global",branch:"main"},...r];for(const o of s)this.initSyncStatus(o,n)}}class bo{listenerManager;constructor(e){this.listenerManager=e}instance(e,t,r){switch(e){case"SwitchboardPush":{if(!t.callInfo?.data)throw new Error("No call info data: "+JSON.stringify(t));return new pn(t.callInfo.data,this.listenerManager)}case"Internal":throw new Error("Internal transmitter not implemented");default:return new ce(t,this.listenerManager)}}}class Po{documentModelModules=[];storage;cache;queueManager;eventEmitter;options;synchronizationManager;listenerManager;transmitterFactory;constructor(e){this.documentModelModules=e}withStorage(e){return this.storage=e,this}withCache(e){return this.cache=e,this}withQueueManager(e){return this.queueManager=e,this}withEventEmitter(e){return this.eventEmitter=e,this}withSynchronizationManager(e){return this.synchronizationManager=e,this}withListenerManager(e){return this.listenerManager=e,this}withTransmitterFactory(e){return this.transmitterFactory=e,this}withOptions(e){return this.options=e,this}build(){if(this.storage||(this.storage=new mo),this.cache||(this.cache=new Us),this.queueManager||(this.queueManager=new Bi),this.eventEmitter||(this.eventEmitter=new yo),this.synchronizationManager||(this.synchronizationManager=new wo(this.storage,this.storage,this.cache,this.documentModelModules,this.eventEmitter)),!this.listenerManager){const e={...ot,...this.options?.listenerManager};this.listenerManager=new qt(this.synchronizationManager,e)}return this.transmitterFactory||(this.transmitterFactory=new bo(this.listenerManager)),new po(this.documentModelModules,this.storage,this.storage,this.cache,this.queueManager,this.eventEmitter,this.synchronizationManager,this.listenerManager,{...this.options,featureFlags:{enableDualActionCreate:!1,...this.options?.featureFlags}})}}function Or(i){let e=!1;const t=Object.entries(i.operations).reduce((r,[n,s])=>{const o=n;if(!s)return r;for(const a of s){const d=Do(a),l=r[o];l&&l.push(d),d!==a&&(e=!0)}return r},{global:[],local:[]});return e?{...i,operations:t}:i}function Do(i){let e=!1,t={...i};const r=i.context?.signer,n=i.action?.context?.signer;if(r){if("signature"in r){const s=r.signature;t={...t,context:{...t.context,signer:{user:r.user,app:r.app,signatures:s?.length?[s]:[]}}},e=!0}else if(r.signatures){const s=r.signatures.filter(o=>o&&o.length>0);s.length!==r.signatures.length&&(t={...t,context:{...t.context,signer:{...r,signatures:s}}},e=!0)}}if(n){if("signature"in n){const s=n.signature,o={...t.action.context,signer:{user:n.user,app:n.app,signatures:s?.length?[s]:[]}};t={...t,action:{...t.action,context:o},context:o},e=!0}else if(n.signatures){const s=n.signatures.filter(o=>o&&o.length>0);if(s.length!==n.signatures.length){const o={...t.action.context,signer:{...n,signatures:s}};t={...t,action:{...t.action,context:o},context:o},e=!0}}}return e?t:i}var xt={exports:{}};var _r;function So(){return _r||(_r=1,(function(i,e){(function(t){i.exports=t()})(function(){return(function t(r,n,s){function o(l,m){if(!n[l]){if(!r[l]){var f=typeof Je=="function"&&Je;if(!m&&f)return f(l,!0);if(a)return a(l,!0);var b=new Error("Cannot find module '"+l+"'");throw b.code="MODULE_NOT_FOUND",b}var w=n[l]={exports:{}};r[l][0].call(w.exports,function(y){var I=r[l][1][y];return o(I||y)},w,w.exports,t,r,n,s)}return n[l].exports}for(var a=typeof Je=="function"&&Je,d=0;d<s.length;d++)o(s[d]);return o})({1:[function(t,r,n){(function(s){var o=s.MutationObserver||s.WebKitMutationObserver,a;if(o){var d=0,l=new o(y),m=s.document.createTextNode("");l.observe(m,{characterData:!0}),a=function(){m.data=d=++d%2}}else if(!s.setImmediate&&typeof s.MessageChannel<"u"){var f=new s.MessageChannel;f.port1.onmessage=y,a=function(){f.port2.postMessage(0)}}else"document"in s&&"onreadystatechange"in s.document.createElement("script")?a=function(){var _=s.document.createElement("script");_.onreadystatechange=function(){y(),_.onreadystatechange=null,_.parentNode.removeChild(_),_=null},s.document.documentElement.appendChild(_)}:a=function(){setTimeout(y,0)};var b,w=[];function y(){b=!0;for(var _,N,C=w.length;C;){for(N=w,w=[],_=-1;++_<C;)N[_]();C=w.length}b=!1}r.exports=I;function I(_){w.push(_)===1&&!b&&a()}}).call(this,typeof Ee<"u"?Ee:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(t,r,n){var s=t(1);function o(){}var a={},d=["REJECTED"],l=["FULFILLED"],m=["PENDING"];r.exports=f;function f(E){if(typeof E!="function")throw new TypeError("resolver must be a function");this.state=m,this.queue=[],this.outcome=void 0,E!==o&&I(this,E)}f.prototype.catch=function(E){return this.then(null,E)},f.prototype.then=function(E,L){if(typeof E!="function"&&this.state===l||typeof L!="function"&&this.state===d)return this;var P=new this.constructor(o);if(this.state!==m){var j=this.state===l?E:L;w(P,j,this.outcome)}else this.queue.push(new b(P,E,L));return P};function b(E,L,P){this.promise=E,typeof L=="function"&&(this.onFulfilled=L,this.callFulfilled=this.otherCallFulfilled),typeof P=="function"&&(this.onRejected=P,this.callRejected=this.otherCallRejected)}b.prototype.callFulfilled=function(E){a.resolve(this.promise,E)},b.prototype.otherCallFulfilled=function(E){w(this.promise,this.onFulfilled,E)},b.prototype.callRejected=function(E){a.reject(this.promise,E)},b.prototype.otherCallRejected=function(E){w(this.promise,this.onRejected,E)};function w(E,L,P){s(function(){var j;try{j=L(P)}catch(H){return a.reject(E,H)}j===E?a.reject(E,new TypeError("Cannot resolve promise with itself")):a.resolve(E,j)})}a.resolve=function(E,L){var P=_(y,L);if(P.status==="error")return a.reject(E,P.value);var j=P.value;if(j)I(E,j);else{E.state=l,E.outcome=L;for(var H=-1,V=E.queue.length;++H<V;)E.queue[H].callFulfilled(L)}return E},a.reject=function(E,L){E.state=d,E.outcome=L;for(var P=-1,j=E.queue.length;++P<j;)E.queue[P].callRejected(L);return E};function y(E){var L=E&&E.then;if(E&&(typeof E=="object"||typeof E=="function")&&typeof L=="function")return function(){L.apply(E,arguments)}}function I(E,L){var P=!1;function j(Y){P||(P=!0,a.reject(E,Y))}function H(Y){P||(P=!0,a.resolve(E,Y))}function V(){L(H,j)}var Z=_(V);Z.status==="error"&&j(Z.value)}function _(E,L){var P={};try{P.value=E(L),P.status="success"}catch(j){P.status="error",P.value=j}return P}f.resolve=N;function N(E){return E instanceof this?E:a.resolve(new this(o),E)}f.reject=C;function C(E){var L=new this(o);return a.reject(L,E)}f.all=U;function U(E){var L=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var P=E.length,j=!1;if(!P)return this.resolve([]);for(var H=new Array(P),V=0,Z=-1,Y=new this(o);++Z<P;)se(E[Z],Z);return Y;function se(le,D){L.resolve(le).then(R,function(B){j||(j=!0,a.reject(Y,B))});function R(B){H[D]=B,++V===P&&!j&&(j=!0,a.resolve(Y,H))}}}f.race=F;function F(E){var L=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var P=E.length,j=!1;if(!P)return this.resolve([]);for(var H=-1,V=new this(o);++H<P;)Z(E[H]);return V;function Z(Y){L.resolve(Y).then(function(se){j||(j=!0,a.resolve(V,se))},function(se){j||(j=!0,a.reject(V,se))})}}},{1:1}],3:[function(t,r,n){(function(s){typeof s.Promise!="function"&&(s.Promise=t(2))}).call(this,typeof Ee<"u"?Ee:typeof self<"u"?self:typeof window<"u"?window:{})},{2:2}],4:[function(t,r,n){var s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(c){return typeof c}:function(c){return c&&typeof Symbol=="function"&&c.constructor===Symbol&&c!==Symbol.prototype?"symbol":typeof c};function o(c,h){if(!(c instanceof h))throw new TypeError("Cannot call a class as a function")}function a(){try{if(typeof indexedDB<"u")return indexedDB;if(typeof webkitIndexedDB<"u")return webkitIndexedDB;if(typeof mozIndexedDB<"u")return mozIndexedDB;if(typeof OIndexedDB<"u")return OIndexedDB;if(typeof msIndexedDB<"u")return msIndexedDB}catch{return}}var d=a();function l(){try{if(!d||!d.open)return!1;var c=typeof openDatabase<"u"&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),h=typeof fetch=="function"&&fetch.toString().indexOf("[native code")!==-1;return(!c||h)&&typeof indexedDB<"u"&&typeof IDBKeyRange<"u"}catch{return!1}}function m(c,h){c=c||[],h=h||{};try{return new Blob(c,h)}catch(g){if(g.name!=="TypeError")throw g;for(var u=typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder,p=new u,v=0;v<c.length;v+=1)p.append(c[v]);return p.getBlob(h.type)}}typeof Promise>"u"&&t(3);var f=Promise;function b(c,h){h&&c.then(function(u){h(null,u)},function(u){h(u)})}function w(c,h,u){typeof h=="function"&&c.then(h),typeof u=="function"&&c.catch(u)}function y(c){return typeof c!="string"&&(console.warn(c+" used as a key, but it is not a string."),c=String(c)),c}function I(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var _="local-forage-detect-blob-support",N=void 0,C={},U=Object.prototype.toString,F="readonly",E="readwrite";function L(c){for(var h=c.length,u=new ArrayBuffer(h),p=new Uint8Array(u),v=0;v<h;v++)p[v]=c.charCodeAt(v);return u}function P(c){return new f(function(h){var u=c.transaction(_,E),p=m([""]);u.objectStore(_).put(p,"key"),u.onabort=function(v){v.preventDefault(),v.stopPropagation(),h(!1)},u.oncomplete=function(){var v=navigator.userAgent.match(/Chrome\/(\d+)/),g=navigator.userAgent.match(/Edge\//);h(g||!v||parseInt(v[1],10)>=43)}}).catch(function(){return!1})}function j(c){return typeof N=="boolean"?f.resolve(N):P(c).then(function(h){return N=h,N})}function H(c){var h=C[c.name],u={};u.promise=new f(function(p,v){u.resolve=p,u.reject=v}),h.deferredOperations.push(u),h.dbReady?h.dbReady=h.dbReady.then(function(){return u.promise}):h.dbReady=u.promise}function V(c){var h=C[c.name],u=h.deferredOperations.pop();if(u)return u.resolve(),u.promise}function Z(c,h){var u=C[c.name],p=u.deferredOperations.pop();if(p)return p.reject(h),p.promise}function Y(c,h){return new f(function(u,p){if(C[c.name]=C[c.name]||_e(),c.db)if(h)H(c),c.db.close();else return u(c.db);var v=[c.name];h&&v.push(c.version);var g=d.open.apply(d,v);h&&(g.onupgradeneeded=function(S){var T=g.result;try{T.createObjectStore(c.storeName),S.oldVersion<=1&&T.createObjectStore(_)}catch(M){if(M.name==="ConstraintError")console.warn('The database "'+c.name+'" has been upgraded from version '+S.oldVersion+" to version "+S.newVersion+', but the storage "'+c.storeName+'" already exists.');else throw M}}),g.onerror=function(S){S.preventDefault(),p(g.error)},g.onsuccess=function(){var S=g.result;S.onversionchange=function(T){T.target.close()},u(S),V(c)}})}function se(c){return Y(c,!1)}function le(c){return Y(c,!0)}function D(c,h){if(!c.db)return!0;var u=!c.db.objectStoreNames.contains(c.storeName),p=c.version<c.db.version,v=c.version>c.db.version;if(p&&(c.version!==h&&console.warn('The database "'+c.name+`" can't be downgraded from version `+c.db.version+" to version "+c.version+"."),c.version=c.db.version),v||u){if(u){var g=c.db.version+1;g>c.version&&(c.version=g)}return!0}return!1}function R(c){return new f(function(h,u){var p=new FileReader;p.onerror=u,p.onloadend=function(v){var g=btoa(v.target.result||"");h({__local_forage_encoded_blob:!0,data:g,type:c.type})},p.readAsBinaryString(c)})}function B(c){var h=L(atob(c.data));return m([h],{type:c.type})}function G(c){return c&&c.__local_forage_encoded_blob}function K(c){var h=this,u=h._initReady().then(function(){var p=C[h._dbInfo.name];if(p&&p.dbReady)return p.dbReady});return w(u,c,c),u}function z(c){H(c);for(var h=C[c.name],u=h.forages,p=0;p<u.length;p++){var v=u[p];v._dbInfo.db&&(v._dbInfo.db.close(),v._dbInfo.db=null)}return c.db=null,se(c).then(function(g){return c.db=g,D(c)?le(c):g}).then(function(g){c.db=h.db=g;for(var S=0;S<u.length;S++)u[S]._dbInfo.db=g}).catch(function(g){throw Z(c,g),g})}function ae(c,h,u,p){p===void 0&&(p=1);try{var v=c.db.transaction(c.storeName,h);u(null,v)}catch(g){if(p>0&&(!c.db||g.name==="InvalidStateError"||g.name==="NotFoundError"))return f.resolve().then(function(){if(!c.db||g.name==="NotFoundError"&&!c.db.objectStoreNames.contains(c.storeName)&&c.version<=c.db.version)return c.db&&(c.version=c.db.version+1),le(c)}).then(function(){return z(c).then(function(){ae(c,h,u,p-1)})}).catch(u);u(g)}}function _e(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function qe(c){var h=this,u={db:null};if(c)for(var p in c)u[p]=c[p];var v=C[u.name];v||(v=_e(),C[u.name]=v),v.forages.push(h),h._initReady||(h._initReady=h.ready,h.ready=K);var g=[];function S(){return f.resolve()}for(var T=0;T<v.forages.length;T++){var M=v.forages[T];M!==h&&g.push(M._initReady().catch(S))}var O=v.forages.slice(0);return f.all(g).then(function(){return u.db=v.db,se(u)}).then(function(A){return u.db=A,D(u,h._defaultConfig.version)?le(u):A}).then(function(A){u.db=v.db=A,h._dbInfo=u;for(var x=0;x<O.length;x++){var k=O[x];k!==h&&(k._dbInfo.db=u.db,k._dbInfo.version=u.version)}})}function ne(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){ae(u._dbInfo,F,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=M.get(c);O.onsuccess=function(){var A=O.result;A===void 0&&(A=null),G(A)&&(A=B(A)),v(A)},O.onerror=function(){g(O.error)}}catch(A){g(A)}})}).catch(g)});return b(p,h),p}function me(c,h){var u=this,p=new f(function(v,g){u.ready().then(function(){ae(u._dbInfo,F,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=M.openCursor(),A=1;O.onsuccess=function(){var x=O.result;if(x){var k=x.value;G(k)&&(k=B(k));var J=c(k,x.key,A++);J!==void 0?v(J):x.continue()}else v()},O.onerror=function(){g(O.error)}}catch(x){g(x)}})}).catch(g)});return b(p,h),p}function mn(c,h,u){var p=this;c=y(c);var v=new f(function(g,S){var T;p.ready().then(function(){return T=p._dbInfo,U.call(h)==="[object Blob]"?j(T.db).then(function(M){return M?h:R(h)}):h}).then(function(M){ae(p._dbInfo,E,function(O,A){if(O)return S(O);try{var x=A.objectStore(p._dbInfo.storeName);M===null&&(M=void 0);var k=x.put(M,c);A.oncomplete=function(){M===void 0&&(M=null),g(M)},A.onabort=A.onerror=function(){var J=k.error?k.error:k.transaction.error;S(J)}}catch(J){S(J)}})}).catch(S)});return b(v,u),v}function yn(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){ae(u._dbInfo,E,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=M.delete(c);T.oncomplete=function(){v()},T.onerror=function(){g(O.error)},T.onabort=function(){var A=O.error?O.error:O.transaction.error;g(A)}}catch(A){g(A)}})}).catch(g)});return b(p,h),p}function vn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){ae(h._dbInfo,E,function(g,S){if(g)return v(g);try{var T=S.objectStore(h._dbInfo.storeName),M=T.clear();S.oncomplete=function(){p()},S.onabort=S.onerror=function(){var O=M.error?M.error:M.transaction.error;v(O)}}catch(O){v(O)}})}).catch(v)});return b(u,c),u}function wn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){ae(h._dbInfo,F,function(g,S){if(g)return v(g);try{var T=S.objectStore(h._dbInfo.storeName),M=T.count();M.onsuccess=function(){p(M.result)},M.onerror=function(){v(M.error)}}catch(O){v(O)}})}).catch(v)});return b(u,c),u}function bn(c,h){var u=this,p=new f(function(v,g){if(c<0){v(null);return}u.ready().then(function(){ae(u._dbInfo,F,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=!1,A=M.openKeyCursor();A.onsuccess=function(){var x=A.result;if(!x){v(null);return}c===0||O?v(x.key):(O=!0,x.advance(c))},A.onerror=function(){g(A.error)}}catch(x){g(x)}})}).catch(g)});return b(p,h),p}function Dn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){ae(h._dbInfo,F,function(g,S){if(g)return v(g);try{var T=S.objectStore(h._dbInfo.storeName),M=T.openKeyCursor(),O=[];M.onsuccess=function(){var A=M.result;if(!A){p(O);return}O.push(A.key),A.continue()},M.onerror=function(){v(M.error)}}catch(A){v(A)}})}).catch(v)});return b(u,c),u}function Sn(c,h){h=I.apply(this,arguments);var u=this.config();c=typeof c!="function"&&c||{},c.name||(c.name=c.name||u.name,c.storeName=c.storeName||u.storeName);var p=this,v;if(!c.name)v=f.reject("Invalid arguments");else{var g=c.name===u.name&&p._dbInfo.db,S=g?f.resolve(p._dbInfo.db):se(c).then(function(T){var M=C[c.name],O=M.forages;M.db=T;for(var A=0;A<O.length;A++)O[A]._dbInfo.db=T;return T});c.storeName?v=S.then(function(T){if(T.objectStoreNames.contains(c.storeName)){var M=T.version+1;H(c);var O=C[c.name],A=O.forages;T.close();for(var x=0;x<A.length;x++){var k=A[x];k._dbInfo.db=null,k._dbInfo.version=M}var J=new f(function(Q,re){var ee=d.open(c.name,M);ee.onerror=function(ue){var Pe=ee.result;Pe.close(),re(ue)},ee.onupgradeneeded=function(){var ue=ee.result;ue.deleteObjectStore(c.storeName)},ee.onsuccess=function(){var ue=ee.result;ue.close(),Q(ue)}});return J.then(function(Q){O.db=Q;for(var re=0;re<A.length;re++){var ee=A[re];ee._dbInfo.db=Q,V(ee._dbInfo)}}).catch(function(Q){throw(Z(c,Q)||f.resolve()).catch(function(){}),Q})}}):v=S.then(function(T){H(c);var M=C[c.name],O=M.forages;T.close();for(var A=0;A<O.length;A++){var x=O[A];x._dbInfo.db=null}var k=new f(function(J,Q){var re=d.deleteDatabase(c.name);re.onerror=function(){var ee=re.result;ee&&ee.close(),Q(re.error)},re.onblocked=function(){console.warn('dropInstance blocked for database "'+c.name+'" until all open connections are closed')},re.onsuccess=function(){var ee=re.result;ee&&ee.close(),J(ee)}});return k.then(function(J){M.db=J;for(var Q=0;Q<O.length;Q++){var re=O[Q];V(re._dbInfo)}}).catch(function(J){throw(Z(c,J)||f.resolve()).catch(function(){}),J})})}return b(v,h),v}var En={_driver:"asyncStorage",_initStorage:qe,_support:l(),iterate:me,getItem:ne,setItem:mn,removeItem:yn,clear:vn,length:wn,key:bn,keys:Dn,dropInstance:Sn};function In(){return typeof openDatabase=="function"}var be="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Tn="~~local_forage_type~",zt=/^~~local_forage_type~([^~]+)~/,ze="__lfsc__:",ht=ze.length,ft="arbf",gt="blob",jt="si08",Ht="ui08",Gt="uic8",Jt="si16",Yt="si32",Qt="ur16",Vt="ui32",Kt="fl32",Wt="fl64",Xt=ht+ft.length,Zt=Object.prototype.toString;function er(c){var h=c.length*.75,u=c.length,p,v=0,g,S,T,M;c[c.length-1]==="="&&(h--,c[c.length-2]==="="&&h--);var O=new ArrayBuffer(h),A=new Uint8Array(O);for(p=0;p<u;p+=4)g=be.indexOf(c[p]),S=be.indexOf(c[p+1]),T=be.indexOf(c[p+2]),M=be.indexOf(c[p+3]),A[v++]=g<<2|S>>4,A[v++]=(S&15)<<4|T>>2,A[v++]=(T&3)<<6|M&63;return O}function pt(c){var h=new Uint8Array(c),u="",p;for(p=0;p<h.length;p+=3)u+=be[h[p]>>2],u+=be[(h[p]&3)<<4|h[p+1]>>4],u+=be[(h[p+1]&15)<<2|h[p+2]>>6],u+=be[h[p+2]&63];return h.length%3===2?u=u.substring(0,u.length-1)+"=":h.length%3===1&&(u=u.substring(0,u.length-2)+"=="),u}function Rn(c,h){var u="";if(c&&(u=Zt.call(c)),c&&(u==="[object ArrayBuffer]"||c.buffer&&Zt.call(c.buffer)==="[object ArrayBuffer]")){var p,v=ze;c instanceof ArrayBuffer?(p=c,v+=ft):(p=c.buffer,u==="[object Int8Array]"?v+=jt:u==="[object Uint8Array]"?v+=Ht:u==="[object Uint8ClampedArray]"?v+=Gt:u==="[object Int16Array]"?v+=Jt:u==="[object Uint16Array]"?v+=Qt:u==="[object Int32Array]"?v+=Yt:u==="[object Uint32Array]"?v+=Vt:u==="[object Float32Array]"?v+=Kt:u==="[object Float64Array]"?v+=Wt:h(new Error("Failed to get type for BinaryArray"))),h(v+pt(p))}else if(u==="[object Blob]"){var g=new FileReader;g.onload=function(){var S=Tn+c.type+"~"+pt(this.result);h(ze+gt+S)},g.readAsArrayBuffer(c)}else try{h(JSON.stringify(c))}catch(S){console.error("Couldn't convert value into a JSON string: ",c),h(null,S)}}function Mn(c){if(c.substring(0,ht)!==ze)return JSON.parse(c);var h=c.substring(Xt),u=c.substring(ht,Xt),p;if(u===gt&&zt.test(h)){var v=h.match(zt);p=v[1],h=h.substring(v[0].length)}var g=er(h);switch(u){case ft:return g;case gt:return m([g],{type:p});case jt:return new Int8Array(g);case Ht:return new Uint8Array(g);case Gt:return new Uint8ClampedArray(g);case Jt:return new Int16Array(g);case Qt:return new Uint16Array(g);case Yt:return new Int32Array(g);case Vt:return new Uint32Array(g);case Kt:return new Float32Array(g);case Wt:return new Float64Array(g);default:throw new Error("Unkown type: "+u)}}var mt={serialize:Rn,deserialize:Mn,stringToBuffer:er,bufferToString:pt};function tr(c,h,u,p){c.executeSql("CREATE TABLE IF NOT EXISTS "+h.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],u,p)}function On(c){var h=this,u={db:null};if(c)for(var p in c)u[p]=typeof c[p]!="string"?c[p].toString():c[p];var v=new f(function(g,S){try{u.db=openDatabase(u.name,String(u.version),u.description,u.size)}catch(T){return S(T)}u.db.transaction(function(T){tr(T,u,function(){h._dbInfo=u,g()},function(M,O){S(O)})},S)});return u.serializer=mt,v}function De(c,h,u,p,v,g){c.executeSql(u,p,v,function(S,T){T.code===T.SYNTAX_ERR?S.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[h.storeName],function(M,O){O.rows.length?g(M,T):tr(M,h,function(){M.executeSql(u,p,v,g)},g)},g):g(S,T)},g)}function _n(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"SELECT * FROM "+S.storeName+" WHERE key = ? LIMIT 1",[c],function(M,O){var A=O.rows.length?O.rows.item(0).value:null;A&&(A=S.serializer.deserialize(A)),v(A)},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function An(c,h){var u=this,p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"SELECT * FROM "+S.storeName,[],function(M,O){for(var A=O.rows,x=A.length,k=0;k<x;k++){var J=A.item(k),Q=J.value;if(Q&&(Q=S.serializer.deserialize(Q)),Q=c(Q,J.key,k+1),Q!==void 0){v(Q);return}}v()},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function rr(c,h,u,p){var v=this;c=y(c);var g=new f(function(S,T){v.ready().then(function(){h===void 0&&(h=null);var M=h,O=v._dbInfo;O.serializer.serialize(h,function(A,x){x?T(x):O.db.transaction(function(k){De(k,O,"INSERT OR REPLACE INTO "+O.storeName+" (key, value) VALUES (?, ?)",[c,A],function(){S(M)},function(J,Q){T(Q)})},function(k){if(k.code===k.QUOTA_ERR){if(p>0){S(rr.apply(v,[c,M,u,p-1]));return}T(k)}})})}).catch(T)});return b(g,u),g}function Nn(c,h,u){return rr.apply(this,[c,h,u,1])}function Cn(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"DELETE FROM "+S.storeName+" WHERE key = ?",[c],function(){v()},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function xn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){var g=h._dbInfo;g.db.transaction(function(S){De(S,g,"DELETE FROM "+g.storeName,[],function(){p()},function(T,M){v(M)})})}).catch(v)});return b(u,c),u}function $n(c){var h=this,u=new f(function(p,v){h.ready().then(function(){var g=h._dbInfo;g.db.transaction(function(S){De(S,g,"SELECT COUNT(key) as c FROM "+g.storeName,[],function(T,M){var O=M.rows.item(0).c;p(O)},function(T,M){v(M)})})}).catch(v)});return b(u,c),u}function Pn(c,h){var u=this,p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"SELECT key FROM "+S.storeName+" WHERE id = ? LIMIT 1",[c+1],function(M,O){var A=O.rows.length?O.rows.item(0).key:null;v(A)},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function Ln(c){var h=this,u=new f(function(p,v){h.ready().then(function(){var g=h._dbInfo;g.db.transaction(function(S){De(S,g,"SELECT key FROM "+g.storeName,[],function(T,M){for(var O=[],A=0;A<M.rows.length;A++)O.push(M.rows.item(A).key);p(O)},function(T,M){v(M)})})}).catch(v)});return b(u,c),u}function Un(c){return new f(function(h,u){c.transaction(function(p){p.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(v,g){for(var S=[],T=0;T<g.rows.length;T++)S.push(g.rows.item(T).name);h({db:c,storeNames:S})},function(v,g){u(g)})},function(p){u(p)})})}function Bn(c,h){h=I.apply(this,arguments);var u=this.config();c=typeof c!="function"&&c||{},c.name||(c.name=c.name||u.name,c.storeName=c.storeName||u.storeName);var p=this,v;return c.name?v=new f(function(g){var S;c.name===u.name?S=p._dbInfo.db:S=openDatabase(c.name,"","",0),c.storeName?g({db:S,storeNames:[c.storeName]}):g(Un(S))}).then(function(g){return new f(function(S,T){g.db.transaction(function(M){function O(J){return new f(function(Q,re){M.executeSql("DROP TABLE IF EXISTS "+J,[],function(){Q()},function(ee,ue){re(ue)})})}for(var A=[],x=0,k=g.storeNames.length;x<k;x++)A.push(O(g.storeNames[x]));f.all(A).then(function(){S()}).catch(function(J){T(J)})},function(M){T(M)})})}):v=f.reject("Invalid arguments"),b(v,h),v}var Fn={_driver:"webSQLStorage",_initStorage:On,_support:In(),iterate:An,getItem:_n,setItem:Nn,removeItem:Cn,clear:xn,length:$n,key:Pn,keys:Ln,dropInstance:Bn};function kn(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}function nr(c,h){var u=c.name+"/";return c.storeName!==h.storeName&&(u+=c.storeName+"/"),u}function qn(){var c="_localforage_support_test";try{return localStorage.setItem(c,!0),localStorage.removeItem(c),!1}catch{return!0}}function zn(){return!qn()||localStorage.length>0}function jn(c){var h=this,u={};if(c)for(var p in c)u[p]=c[p];return u.keyPrefix=nr(c,h._defaultConfig),zn()?(h._dbInfo=u,u.serializer=mt,f.resolve()):f.reject()}function Hn(c){var h=this,u=h.ready().then(function(){for(var p=h._dbInfo.keyPrefix,v=localStorage.length-1;v>=0;v--){var g=localStorage.key(v);g.indexOf(p)===0&&localStorage.removeItem(g)}});return b(u,c),u}function Gn(c,h){var u=this;c=y(c);var p=u.ready().then(function(){var v=u._dbInfo,g=localStorage.getItem(v.keyPrefix+c);return g&&(g=v.serializer.deserialize(g)),g});return b(p,h),p}function Jn(c,h){var u=this,p=u.ready().then(function(){for(var v=u._dbInfo,g=v.keyPrefix,S=g.length,T=localStorage.length,M=1,O=0;O<T;O++){var A=localStorage.key(O);if(A.indexOf(g)===0){var x=localStorage.getItem(A);if(x&&(x=v.serializer.deserialize(x)),x=c(x,A.substring(S),M++),x!==void 0)return x}}});return b(p,h),p}function Yn(c,h){var u=this,p=u.ready().then(function(){var v=u._dbInfo,g;try{g=localStorage.key(c)}catch{g=null}return g&&(g=g.substring(v.keyPrefix.length)),g});return b(p,h),p}function Qn(c){var h=this,u=h.ready().then(function(){for(var p=h._dbInfo,v=localStorage.length,g=[],S=0;S<v;S++){var T=localStorage.key(S);T.indexOf(p.keyPrefix)===0&&g.push(T.substring(p.keyPrefix.length))}return g});return b(u,c),u}function Vn(c){var h=this,u=h.keys().then(function(p){return p.length});return b(u,c),u}function Kn(c,h){var u=this;c=y(c);var p=u.ready().then(function(){var v=u._dbInfo;localStorage.removeItem(v.keyPrefix+c)});return b(p,h),p}function Wn(c,h,u){var p=this;c=y(c);var v=p.ready().then(function(){h===void 0&&(h=null);var g=h;return new f(function(S,T){var M=p._dbInfo;M.serializer.serialize(h,function(O,A){if(A)T(A);else try{localStorage.setItem(M.keyPrefix+c,O),S(g)}catch(x){(x.name==="QuotaExceededError"||x.name==="NS_ERROR_DOM_QUOTA_REACHED")&&T(x),T(x)}})})});return b(v,u),v}function Xn(c,h){if(h=I.apply(this,arguments),c=typeof c!="function"&&c||{},!c.name){var u=this.config();c.name=c.name||u.name,c.storeName=c.storeName||u.storeName}var p=this,v;return c.name?v=new f(function(g){c.storeName?g(nr(c,p._defaultConfig)):g(c.name+"/")}).then(function(g){for(var S=localStorage.length-1;S>=0;S--){var T=localStorage.key(S);T.indexOf(g)===0&&localStorage.removeItem(T)}}):v=f.reject("Invalid arguments"),b(v,h),v}var Zn={_driver:"localStorageWrapper",_initStorage:jn,_support:kn(),iterate:Jn,getItem:Gn,setItem:Wn,removeItem:Kn,clear:Hn,length:Vn,key:Yn,keys:Qn,dropInstance:Xn},es=function(h,u){return h===u||typeof h=="number"&&typeof u=="number"&&isNaN(h)&&isNaN(u)},ts=function(h,u){for(var p=h.length,v=0;v<p;){if(es(h[v],u))return!0;v++}return!1},sr=Array.isArray||function(c){return Object.prototype.toString.call(c)==="[object Array]"},$e={},ir={},Ae={INDEXEDDB:En,WEBSQL:Fn,LOCALSTORAGE:Zn},rs=[Ae.INDEXEDDB._driver,Ae.WEBSQL._driver,Ae.LOCALSTORAGE._driver],je=["dropInstance"],yt=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(je),ns={description:"",driver:rs.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function ss(c,h){c[h]=function(){var u=arguments;return c.ready().then(function(){return c[h].apply(c,u)})}}function vt(){for(var c=1;c<arguments.length;c++){var h=arguments[c];if(h)for(var u in h)h.hasOwnProperty(u)&&(sr(h[u])?arguments[0][u]=h[u].slice():arguments[0][u]=h[u])}return arguments[0]}var is=(function(){function c(h){o(this,c);for(var u in Ae)if(Ae.hasOwnProperty(u)){var p=Ae[u],v=p._driver;this[u]=v,$e[v]||this.defineDriver(p)}this._defaultConfig=vt({},ns),this._config=vt({},this._defaultConfig,h),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return c.prototype.config=function(u){if((typeof u>"u"?"undefined":s(u))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var p in u){if(p==="storeName"&&(u[p]=u[p].replace(/\W/g,"_")),p==="version"&&typeof u[p]!="number")return new Error("Database version must be a number.");this._config[p]=u[p]}return"driver"in u&&u.driver?this.setDriver(this._config.driver):!0}else return typeof u=="string"?this._config[u]:this._config},c.prototype.defineDriver=function(u,p,v){var g=new f(function(S,T){try{var M=u._driver,O=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!u._driver){T(O);return}for(var A=yt.concat("_initStorage"),x=0,k=A.length;x<k;x++){var J=A[x],Q=!ts(je,J);if((Q||u[J])&&typeof u[J]!="function"){T(O);return}}var re=function(){for(var Pe=function(cs){return function(){var us=new Error("Method "+cs+" is not implemented by the current driver"),or=f.reject(us);return b(or,arguments[arguments.length-1]),or}},wt=0,as=je.length;wt<as;wt++){var bt=je[wt];u[bt]||(u[bt]=Pe(bt))}};re();var ee=function(Pe){$e[M]&&console.info("Redefining LocalForage driver: "+M),$e[M]=u,ir[M]=Pe,S()};"_support"in u?u._support&&typeof u._support=="function"?u._support().then(ee,T):ee(!!u._support):ee(!0)}catch(ue){T(ue)}});return w(g,p,v),g},c.prototype.driver=function(){return this._driver||null},c.prototype.getDriver=function(u,p,v){var g=$e[u]?f.resolve($e[u]):f.reject(new Error("Driver not found."));return w(g,p,v),g},c.prototype.getSerializer=function(u){var p=f.resolve(mt);return w(p,u),p},c.prototype.ready=function(u){var p=this,v=p._driverSet.then(function(){return p._ready===null&&(p._ready=p._initDriver()),p._ready});return w(v,u,u),v},c.prototype.setDriver=function(u,p,v){var g=this;sr(u)||(u=[u]);var S=this._getSupportedDrivers(u);function T(){g._config.driver=g.driver()}function M(x){return g._extend(x),T(),g._ready=g._initStorage(g._config),g._ready}function O(x){return function(){var k=0;function J(){for(;k<x.length;){var Q=x[k];return k++,g._dbInfo=null,g._ready=null,g.getDriver(Q).then(M).catch(J)}T();var re=new Error("No available storage method found.");return g._driverSet=f.reject(re),g._driverSet}return J()}}var A=this._driverSet!==null?this._driverSet.catch(function(){return f.resolve()}):f.resolve();return this._driverSet=A.then(function(){var x=S[0];return g._dbInfo=null,g._ready=null,g.getDriver(x).then(function(k){g._driver=k._driver,T(),g._wrapLibraryMethodsWithReady(),g._initDriver=O(S)})}).catch(function(){T();var x=new Error("No available storage method found.");return g._driverSet=f.reject(x),g._driverSet}),w(this._driverSet,p,v),this._driverSet},c.prototype.supports=function(u){return!!ir[u]},c.prototype._extend=function(u){vt(this,u)},c.prototype._getSupportedDrivers=function(u){for(var p=[],v=0,g=u.length;v<g;v++){var S=u[v];this.supports(S)&&p.push(S)}return p},c.prototype._wrapLibraryMethodsWithReady=function(){for(var u=0,p=yt.length;u<p;u++)ss(this,yt[u])},c.prototype.createInstance=function(u){return new c(u)},c})(),os=new is;r.exports=os},{3:3}]},{},[4])(4)})})(xt)),xt.exports}var Eo=So();const Ar=Pt(Eo);class te{logger=pe(["BrowserStorage"]);db;static DBName="DOCUMENT_DRIVES";static SEP=":";static DOCUMENT_KEY="DOCUMENT";static MANIFEST_KEY="MANIFEST";static SLUG_MANIFEST_KEY="SLUG_MANIFEST";constructor(e){this.db=Ar.ready().then(()=>Ar.createInstance({name:e?`${e}:${te.DBName}`:te.DBName}))}async findStorageUnitsBy(e,t,r){const n=[],{parentId:s,documentId:o,documentModelType:a,scope:d}=sn(e),f=(await(await this.db).keys()).filter(_=>_.startsWith(`${te.DOCUMENT_KEY}${te.SEP}`)).map(_=>_.slice(te.DOCUMENT_KEY.length+te.SEP.length));let b;if(s){const _=new Set;for(const N of s)(await this.getChildren(N)).forEach(U=>_.add(U));b=on(s,_)}else b=new Set(f);b=o?an(o,b):b;for(const _ of b){const N=await this.get(_).catch(()=>null);if(N&&!(a&&!a.has(N.header.documentType)))for(const[C]of Object.entries(N.state))d&&!d.has(C)||n.push({documentId:_,documentModelType:N.header.documentType,scope:C,branch:"main"})}let w=0;if(r){const _=n.findIndex(N=>N.documentId===r);_!==-1&&(w=_)}const y=Math.min(w+t,n.length),I=y<n.length?n[y].documentId:void 0;return{units:n.slice(w,y),nextCursor:I}}async resolveIds(e,t){const r=await this.getSlugManifest();if(t?.aborted)throw new at("Aborted");const n=[];for(const s of e){const o=r.slugToId[s];if(!o)throw new we(s);n.push(o)}return Promise.resolve(n)}async resolveSlugs(e,t){const r=await this.getSlugManifest();if(t?.aborted)throw new at("Aborted");const n=[];for(const s of e){let o=!1;for(const[a,d]of Object.entries(r.slugToId))if(d===s){n.push(a),o=!0;break}if(!o)throw new we(s)}return Promise.resolve(n)}async clear(){await(await this.db).clear()}async exists(e){return!!await(await this.db).getItem(this.buildDocumentKey(e))}async create(e){const t=e.header.id;if(!tt(t))throw new et(t);const r=await this.db;if(await this.exists(t))throw new ke(t);const n=e.header.slug&&e.header.slug.length>0?e.header.slug:t;if(!nn(n))throw new rn(n);if((await this.getSlugManifest()).slugToId[n])throw new ke(t,Fe.SLUG);if(e.header.slug=n,await r.setItem(this.buildDocumentKey(t),e),n){const o=await this.getSlugManifest();if(o.slugToId[n])throw new Error(`Document with slug ${n} already exists`);o.slugToId[n]=t,await this.updateSlugManifest(o)}e.header.documentType==="powerhouse/document-drive"&&this.updateDriveManifest(t,{documentIds:[]})}async get(e){const r=await(await this.db).getItem(this.buildDocumentKey(e));return r||Promise.reject(new we(e))}async getBySlug(e){const r=(await this.getSlugManifest()).slugToId[e];return r?this.get(r):Promise.reject(new we(e))}async findByType(e,t=100,r){const n=await this.db,o=(await n.keys()).filter(f=>f.startsWith(`${te.DOCUMENT_KEY}${te.SEP}`)),a=[];for(const f of o){const b=f.slice(te.DOCUMENT_KEY.length+te.SEP.length);try{const w=await n.getItem(f);if(!w||w.header.documentType!==e)continue;a.push({id:b,document:w})}catch{continue}}a.sort((f,b)=>{const w=new Date(f.document.header.createdAtUtcIso),y=new Date(b.document.header.createdAtUtcIso);return w.getTime()===y.getTime()?f.id.localeCompare(b.id):w.getTime()-y.getTime()});let d=0;if(r){const f=a.findIndex(({id:b})=>b===r);f!==-1&&(d=f)}const l=Math.min(d+t,a.length);let m;return l<a.length&&(m=a[l].id),{documents:a.slice(d,l).map(({id:f})=>f),nextCursor:m}}async delete(e){const t=await this.db,r=await t.getItem(this.buildDocumentKey(e));if(!r)return!1;const n=r.header.slug?.length>0?r.header.slug:e;try{if(n){const o=await this.getSlugManifest();o.slugToId[n]===e&&(delete o.slugToId[n],await this.updateSlugManifest(o))}}catch{}const s=await this.getParents(e);for(const o of s)await this.removeChild(o,e);return await t.removeItem(this.buildManifestKey(e)),await t.removeItem(this.buildDocumentKey(e)),!0}async removeChild(e,t){const r=await this.getManifest(e),n=r.documentIds.indexOf(t);return n!==-1?(r.documentIds.splice(n,1),await this.updateDriveManifest(e,r),!0):!1}async addChild(e,t){if(e===t)throw new Error("Cannot associate a document with itself");if((await this.getChildren(t)).includes(e))throw new Error("Cannot associate a document with its child");const n=await this.getManifest(e);n.documentIds.includes(t)||(n.documentIds.push(t),await this.updateDriveManifest(e,n))}async getChildren(e){return(await this.getManifest(e)).documentIds}async getParents(e){const r=await(await this.db).keys(),n=[],s=r.filter(o=>o.startsWith(`${te.MANIFEST_KEY}${te.SEP}`));for(const o of s){const a=o.slice(te.MANIFEST_KEY.length+te.SEP.length);(await this.getManifest(a)).documentIds.includes(e)&&n.push(a)}return n}async getManifest(e){return await(await this.db).getItem(this.buildManifestKey(e))||{documentIds:[]}}async updateDriveManifest(e,t){await(await this.db).setItem(this.buildManifestKey(e),t)}async getSlugManifest(){return await(await this.db).getItem(te.SLUG_MANIFEST_KEY)||{slugToId:{}}}async updateSlugManifest(e){await(await this.db).setItem(te.SLUG_MANIFEST_KEY,e)}async addDocumentOperations(e,t,r){const n=await this.get(e);if(!n)throw new Error(`Document with id ${e} not found`);const s=st(n.operations,t);await(await this.db).setItem(this.buildDocumentKey(e),{...n,...r,operations:s})}async addDriveOperations(e,t,r){const n=await this.get(e),s=st(n.operations,t);await(await this.db).setItem(this.buildDocumentKey(e),{...n,...r,operations:s})}async getSynchronizationUnitsRevision(e){return(await Promise.allSettled(e.map(async r=>{try{const n=await this.get(r.documentId);if(!n?.operations[r.scope])return;const s=n.operations[r.scope];return{documentId:r.documentId,documentType:r.documentType,scope:r.scope,branch:r.branch,lastUpdated:s.at(-1)?.timestampUtcMs??n.header.createdAtUtcIso,revision:s.length>0?Ie(s):0}}catch(n){this.logger.error("Error getting synchronization units revision",n);return}}))).reduce((r,n)=>(n.status==="fulfilled"&&n.value!==void 0&&r.push(n.value),r),[])}async migrateOperationSignatures(){let e;do{const{documents:t,nextCursor:r}=await this.findByType("powerhouse/document-drive",100,e);for(const n of t){await this.migrateDrive(n);const s=await this.getChildren(n);await Promise.all(s.map(async o=>this.migrateDocument(n,o)))}e=r}while(e)}async migrateDrive(e){const t=await this.get(e),r=Or(t);if(r!==t)return(await this.db).setItem(this.buildDocumentKey(e),r)}async migrateDocument(e,t){const r=await this.get(t),n=Or(r);if(n!==r)return(await this.db).setItem(this.buildDocumentKey(t),n)}buildDocumentKey(e){return`${te.DOCUMENT_KEY}${te.SEP}${e}`}buildManifestKey(e){return`${te.MANIFEST_KEY}${te.SEP}${e}`}}export{te as B,we as D,Bi as E,Us as I,ce as P,Po as R,fi as S,Ws as a,Xs as b,gi as c,Zs as d,ri as e,oi as f,No as g,Ne as h,lr as i,si as j,ci as k,fe as l,ni as m,li as n,$o as o,Ye as p,Ao as q,tn as r,Zr as s,pe as t,ti as u,Ni as v,Co as w,gn as x};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./sentry_react-cODD7zWc.js";import"./document_model_editor-
|
|
1
|
+
import"./sentry_react-cODD7zWc.js";import"./document_model_editor-lmHQ6HZy.js";import"./react-DQSxOgtG.js";
|
|
@@ -227,4 +227,4 @@ type DocumentModelGlobalState {
|
|
|
227
227
|
}`,template:"",reducer:"",examples:[],errors:[],scope:"global"},{name:"REORDER_STATE_EXAMPLES",id:"",description:"Changes the order of state examples for a document scope",schema:`input ReorderStateExamplesInput {
|
|
228
228
|
scope: String!
|
|
229
229
|
order: [ID!]!
|
|
230
|
-
}`,template:"",reducer:"",examples:[],errors:[],scope:"global"}],id:"",description:""}]}]},br="powerhouse/document-model",Is=ee({id:L(),name:L(),createdAtUtcIso:L(),lastModifiedAtUtcIso:L(),documentType:L()}),As=ee({global:sn()}),Rs=Is.extend({documentType:be(br)}),gt=As.extend({global:vo()}),yr=ee({header:Rs,state:gt,initialState:gt});function ks(e){return gt.safeParse(e).success}function Ts(e){gt.parse(e)}function Ds(e){return yr.safeParse(e).success}function Cs(e){yr.parse(e)}function tt(e){const t={};return e.forEach((n,r)=>t[n]=r),(n,r)=>(t[r.id]||999999)-(t[n.id]||999999)}const je={setModelNameOperation(e,t){e.name=t.input.name},setModelIdOperation(e,t){e.id=t.input.id},setModelExtensionOperation(e,t){e.extension=t.input.extension},setModelDescriptionOperation(e,t){e.description=t.input.description},setAuthorNameOperation(e,t){e.author=e.author||{name:"",website:null},e.author.name=t.input.authorName},setAuthorWebsiteOperation(e,t){e.author=e.author||{name:"",website:null},e.author.website=t.input.authorWebsite}},Xe={addModuleOperation(e,t){e.specifications[e.specifications.length-1].modules.push({id:t.input.id,name:t.input.name,description:t.input.description||"",operations:[]})},setModuleNameOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)n.modules[r].id===t.input.id&&(n.modules[r].name=t.input.name||"")},setModuleDescriptionOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)n.modules[r].id===t.input.id&&(n.modules[r].description=t.input.description||"")},deleteModuleOperation(e,t){const n=e.specifications[e.specifications.length-1];n.modules=n.modules.filter(r=>r.id!=t.input.id)},reorderModulesOperation(e,t){e.specifications[e.specifications.length-1].modules.sort(tt(t.input.order))}},ze={addOperationErrorOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.operationId&&n.modules[r].operations[i].errors.push({id:t.input.id,name:t.input.errorName||"",code:t.input.errorCode||"",description:t.input.errorDescription||"",template:t.input.errorTemplate||""})},setOperationErrorCodeOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)for(let s=0;s<n.modules[r].operations[i].errors.length;s++)n.modules[r].operations[i].errors[s].id==t.input.id&&(n.modules[r].operations[i].errors[s].code=t.input.errorCode||"")},setOperationErrorNameOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)for(let s=0;s<n.modules[r].operations[i].errors.length;s++)n.modules[r].operations[i].errors[s].id==t.input.id&&(n.modules[r].operations[i].errors[s].name=t.input.errorName||"")},setOperationErrorDescriptionOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)for(let s=0;s<n.modules[r].operations[i].errors.length;s++)n.modules[r].operations[i].errors[s].id==t.input.id&&(n.modules[r].operations[i].errors[s].description=t.input.errorDescription||"")},setOperationErrorTemplateOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)for(let s=0;s<n.modules[r].operations[i].errors.length;s++)n.modules[r].operations[i].errors[s].id==t.input.id&&(n.modules[r].operations[i].errors[s].template=t.input.errorTemplate||"")},deleteOperationErrorOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].errors=n.modules[r].operations[i].errors.filter(s=>s.id!=t.input.id)},reorderOperationErrorsOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.operationId&&n.modules[r].operations[i].errors.sort(tt(t.input.order))}},ut={addOperationExampleOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.operationId&&n.modules[r].operations[i].examples.push({id:t.input.id,value:t.input.example})},updateOperationExampleOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)for(let s=0;s<n.modules[r].operations[i].examples.length;s++)n.modules[r].operations[i].examples[s].id==t.input.id&&(n.modules[r].operations[i].examples[s].value=t.input.example)},deleteOperationExampleOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].examples=n.modules[r].operations[i].examples.filter(s=>s.id!=t.input.id)},reorderOperationExamplesOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.operationId&&n.modules[r].operations[i].examples.sort(tt(t.input.order))}},ve={addOperationOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)n.modules[r].id==t.input.moduleId&&n.modules[r].operations.push({id:t.input.id,name:t.input.name,description:t.input.description||"",schema:t.input.schema||"",template:t.input.template||t.input.description||"",reducer:t.input.reducer||"",errors:[],examples:[],scope:t.input.scope||"global"})},setOperationNameOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.id&&(n.modules[r].operations[i].name=t.input.name||"")},setOperationScopeOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.id&&(n.modules[r].operations[i].scope=t.input.scope||"global")},setOperationSchemaOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.id&&(n.modules[r].operations[i].schema=t.input.schema||"")},setOperationDescriptionOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.id&&(n.modules[r].operations[i].description=t.input.description||"")},setOperationTemplateOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.id&&(n.modules[r].operations[i].template=t.input.template||"")},setOperationReducerOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.id&&(n.modules[r].operations[i].reducer=t.input.reducer||"")},moveOperationOperation(e,t){const n=[],r=e.specifications[e.specifications.length-1];for(let i=0;i<r.modules.length;i++)r.modules[i].operations=r.modules[i].operations.filter(s=>s.id==t.input.operationId?(n.push(s),!1):!0);for(let i=0;i<r.modules.length;i++)r.modules[i].id==t.input.newModuleId&&r.modules[i].operations.push(...n)},deleteOperationOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)n.modules[r].operations=n.modules[r].operations.filter(i=>i.id!=t.input.id)},reorderModuleOperationsOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)n.modules[r].id==t.input.moduleId&&n.modules[r].operations.sort(tt(t.input.order))}},Be={setStateSchemaOperation(e,t){const n=e.specifications[e.specifications.length-1];if(Object.keys(n.state).includes(t.input.scope))n.state[t.input.scope].schema=t.input.schema;else throw new Error(`Invalid scope: ${t.input.scope}`)},setInitialStateOperation(e,t){const n=e.specifications[e.specifications.length-1];if(Object.keys(n.state).includes(t.input.scope))n.state[t.input.scope].initialValue=t.input.initialValue;else throw new Error(`Invalid scope: ${t.input.scope}`)},addStateExampleOperation(e,t){const n=e.specifications[e.specifications.length-1];if(Object.keys(n.state).includes(t.input.scope))n.state[t.input.scope].examples.push({id:t.input.id,value:t.input.example});else throw new Error(`Invalid scope: ${t.input.scope}`)},updateStateExampleOperation(e,t){const n=e.specifications[e.specifications.length-1];if(!Object.keys(n.state).includes(t.input.scope))throw new Error(`Invalid scope: ${t.input.scope}`);const r=n.state[t.input.scope].examples;for(let i=0;i<r.length;i++)r[i].id==t.input.id&&(r[i].value=t.input.newExample)},deleteStateExampleOperation(e,t){const n=e.specifications[e.specifications.length-1];if(Object.keys(n.state).includes(t.input.scope))n.state[t.input.scope].examples=n.state[t.input.scope].examples.filter(r=>r.id!=t.input.id);else throw new Error(`Invalid scope: ${t.input.scope}`)},reorderStateExamplesOperation(e,t){const n=e.specifications[e.specifications.length-1];if(Object.keys(n.state).includes(t.input.scope))n.state[t.input.scope].examples.sort(tt(t.input.order));else throw new Error(`Invalid scope: ${t.input.scope}`)}},Ke={addChangeLogItemOperation(e,t){throw new Error('Reducer "addChangeLogItemOperation" not yet implemented')},updateChangeLogItemOperation(e,t){throw new Error('Reducer "updateChangeLogItemOperation" not yet implemented')},deleteChangeLogItemOperation(e,t){throw new Error('Reducer "deleteChangeLogItemOperation" not yet implemented')},reorderChangeLogItemsOperation(e,t){throw new Error('Reducer "reorderChangeLogItemsOperation" not yet implemented')},releaseNewVersionOperation(e,t){throw new Error('Reducer "releaseNewVersionOperation" not yet implemented')}},Ms=(e,t)=>{if(_n(t))return e;switch(t.type){case"SET_MODEL_NAME":nr().parse(t.input),je.setModelNameOperation(e.global,t);break;case"SET_MODEL_ID":tr().parse(t.input),je.setModelIdOperation(e.global,t);break;case"SET_MODEL_EXTENSION":er().parse(t.input),je.setModelExtensionOperation(e.global,t);break;case"SET_MODEL_DESCRIPTION":Qn().parse(t.input),je.setModelDescriptionOperation(e.global,t);break;case"SET_AUTHOR_NAME":Jn().parse(t.input),je.setAuthorNameOperation(e.global,t);break;case"SET_AUTHOR_WEBSITE":qn().parse(t.input),je.setAuthorWebsiteOperation(e.global,t);break;case"ADD_CHANGE_LOG_ITEM":Mn().parse(t.input),Ke.addChangeLogItemOperation(e.global,t);break;case"UPDATE_CHANGE_LOG_ITEM":gr().parse(t.input),Ke.updateChangeLogItemOperation(e.global,t);break;case"DELETE_CHANGE_LOG_ITEM":jn().parse(t.input),Ke.deleteChangeLogItemOperation(e.global,t);break;case"REORDER_CHANGE_LOG_ITEMS":Zn().parse(t.input),Ke.reorderChangeLogItemsOperation(e.global,t);break;case"RELEASE_NEW_VERSION":if(Object.keys(t.input).length>0)throw new Error("Expected empty input for action RELEASE_NEW_VERSION");Ke.releaseNewVersionOperation(e.global,t);break;case"ADD_MODULE":Nn().parse(t.input),Xe.addModuleOperation(e.global,t);break;case"SET_MODULE_NAME":ir().parse(t.input),Xe.setModuleNameOperation(e.global,t);break;case"SET_MODULE_DESCRIPTION":rr().parse(t.input),Xe.setModuleDescriptionOperation(e.global,t);break;case"DELETE_MODULE":Bn().parse(t.input),Xe.deleteModuleOperation(e.global,t);break;case"REORDER_MODULES":Vn().parse(t.input),Xe.reorderModulesOperation(e.global,t);break;case"ADD_OPERATION_ERROR":zn().parse(t.input),ze.addOperationErrorOperation(e.global,t);break;case"SET_OPERATION_ERROR_CODE":sr().parse(t.input),ze.setOperationErrorCodeOperation(e.global,t);break;case"SET_OPERATION_ERROR_NAME":lr().parse(t.input),ze.setOperationErrorNameOperation(e.global,t);break;case"SET_OPERATION_ERROR_DESCRIPTION":ar().parse(t.input),ze.setOperationErrorDescriptionOperation(e.global,t);break;case"SET_OPERATION_ERROR_TEMPLATE":ur().parse(t.input),ze.setOperationErrorTemplateOperation(e.global,t);break;case"DELETE_OPERATION_ERROR":Fn().parse(t.input),ze.deleteOperationErrorOperation(e.global,t);break;case"REORDER_OPERATION_ERRORS":Xn().parse(t.input),ze.reorderOperationErrorsOperation(e.global,t);break;case"ADD_OPERATION_EXAMPLE":wo().parse(t.input),ut.addOperationExampleOperation(e.global,t);break;case"UPDATE_OPERATION_EXAMPLE":Co().parse(t.input),ut.updateOperationExampleOperation(e.global,t);break;case"DELETE_OPERATION_EXAMPLE":xo().parse(t.input),ut.deleteOperationExampleOperation(e.global,t);break;case"REORDER_OPERATION_EXAMPLES":To().parse(t.input),ut.reorderOperationExamplesOperation(e.global,t);break;case"ADD_OPERATION":Pn().parse(t.input),ve.addOperationOperation(e.global,t);break;case"SET_OPERATION_NAME":cr().parse(t.input),ve.setOperationNameOperation(e.global,t);break;case"SET_OPERATION_SCOPE":pr().parse(t.input),ve.setOperationScopeOperation(e.global,t);break;case"SET_OPERATION_SCHEMA":fr().parse(t.input),ve.setOperationSchemaOperation(e.global,t);break;case"SET_OPERATION_DESCRIPTION":or().parse(t.input),ve.setOperationDescriptionOperation(e.global,t);break;case"SET_OPERATION_TEMPLATE":hr().parse(t.input),ve.setOperationTemplateOperation(e.global,t);break;case"SET_OPERATION_REDUCER":dr().parse(t.input),ve.setOperationReducerOperation(e.global,t);break;case"MOVE_OPERATION":Hn().parse(t.input),ve.moveOperationOperation(e.global,t);break;case"DELETE_OPERATION":$n().parse(t.input),ve.deleteOperationOperation(e.global,t);break;case"REORDER_MODULE_OPERATIONS":Gn().parse(t.input),ve.reorderModuleOperationsOperation(e.global,t);break;case"SET_STATE_SCHEMA":mr().parse(t.input),Be.setStateSchemaOperation(e.global,t);break;case"SET_INITIAL_STATE":Yn().parse(t.input),Be.setInitialStateOperation(e.global,t);break;case"ADD_STATE_EXAMPLE":Ln().parse(t.input),Be.addStateExampleOperation(e.global,t);break;case"UPDATE_STATE_EXAMPLE":_r().parse(t.input),Be.updateStateExampleOperation(e.global,t);break;case"DELETE_STATE_EXAMPLE":Wn().parse(t.input),Be.deleteStateExampleOperation(e.global,t);break;case"REORDER_STATE_EXAMPLES":Kn().parse(t.input),Be.reorderStateExamplesOperation(e.global,t);break;default:return e}},Er=Tn(Ms),Ns=(e,t)=>Fi(e,t),zs=e=>$i(e,Er),Sr=e=>({...$t(),global:{...xs,...e?.global??{}},local:{...Os,...e?.local??{}}});function Ps(){return{...$t(),author:{name:"",website:""},description:"",extension:"",id:"",name:"",specifications:[]}}function Ls(){return{}}function Us(e){return{...Ps(),...e||{}}}function js(e){return{...Ls()}}function Bs(e,t,n){return{...So(e?.auth,e?.document),global:Us(t),local:js()}}function Fs(e){const t=bn(Sr,e);return t.header.documentType=br,t}const $s=e=>ks(e),Ws=e=>{Ts(e)},Hs=e=>Ds(e),Zs=e=>{Cs(e)},Gs={fileExtension:ws,createState:Sr,createDocument:Fs,loadFromInput:zs,saveToFileHandle:Ns,isStateOfType:$s,assertIsStateOfType:Ws,isDocumentOfType:Hs,assertIsDocumentOfType:Zs},pa={reducer:Er,documentModel:Bs($t(),vs),actions:Ss,utils:Gs},Vs=new RegExp("([\\p{Ll}\\d])(\\p{Lu})","gu"),Xs=new RegExp("(\\p{Lu})([\\p{Lu}][\\p{Ll}])","gu"),Ks=new RegExp("(\\d)\\p{Ll}|(\\p{L})\\d","u"),Js=/[^\p{L}\d]+/giu,nn="$1\0$2",rn="";function wr(e){let t=e.trim();t=t.replace(Vs,nn).replace(Xs,nn),t=t.replace(Js,"\0");let n=0,r=t.length;for(;t.charAt(n)==="\0";)n++;if(n===r)return[];for(;t.charAt(r-1)==="\0";)r--;return t.slice(n,r).split(/\0/g)}function qs(e){const t=wr(e);for(let n=0;n<t.length;n++){const r=t[n],i=Ks.exec(r);if(i){const s=i.index+(i[1]??i[2]).length;t.splice(n,1,r.slice(0,s),r.slice(s))}}return t}function Ys(e,t){const[n,r,i]=nt(e,t);return n+r.map(bt(t?.locale)).join(t?.delimiter??" ")+i}function on(e,t){const[n,r,i]=nt(e,t),s=bt(t?.locale),l=yt(t?.locale),o=t?.mergeAmbiguousCharacters?Wt(s,l):Qs(s,l);return n+r.map(o).join(t?.delimiter??"")+i}function da(e,t){const[n,r,i]=nt(e,t),s=bt(t?.locale),l=yt(t?.locale);return n+r.map(Wt(s,l)).join(" ")+i}function fa(e,t){const[n,r,i]=nt(e,t);return n+r.map(yt(t?.locale)).join("_")+i}function ha(e,t){const[n,r,i]=nt(e,t),s=bt(t?.locale),l=yt(t?.locale),o=Wt(s,l);return n+r.map((u,d)=>d===0?o(u):s(u)).join(" ")+i}function ma(e,t){return Ys(e,{delimiter:"_",...t})}function bt(e){return e===!1?t=>t.toLowerCase():t=>t.toLocaleLowerCase(e)}function yt(e){return e===!1?t=>t.toUpperCase():t=>t.toLocaleUpperCase(e)}function Wt(e,t){return n=>`${t(n[0])}${e(n.slice(1))}`}function Qs(e,t){return(n,r)=>{const i=n[0];return(r>0&&i>="0"&&i<="9"?"_"+i:t(i))+e(n.slice(1))}}function nt(e,t={}){const n=t.split??(t.separateNumbers?qs:wr),r=t.prefixCharacters??rn,i=t.suffixCharacters??rn;let s=0,l=e.length;for(;s<e.length;){const o=e.charAt(s);if(!r.includes(o))break;s++}for(;l>s;){const o=l-1,u=e.charAt(o);if(!i.includes(u))break;l=o}return[e.slice(0,s),n(e.slice(s,l)),e.slice(l)]}function ga(e,t=!1){const n=[];if(t&&e==="")return n;try{const r=JSON.parse(e);!t&&!Object.keys(r).length&&n.push({message:"Initial state cannot be empty",details:{initialState:e}})}catch{n.push({message:"Invalid initial state",details:{initialState:e}})}return n}function _a(e,t,n="",r=!0){const i=[];if(!r&&!e)return i.push({message:"State schema is required",details:{schema:e}}),i;if(r&&!e)return i;const s=`type ${on(t)}${on(n)}State`;return e.includes(s)||i.push({message:`Invalid state schema name. Expected ${s}`,details:{schema:e}}),i}function ba(e){const t=[];e.length||t.push({message:"Modules are required",details:{modules:e}});const n=e.reduce((r,i)=>[...r,...ea(i)],[]);return[...t,...n]}function ea(e){const t=[];e.name||t.push({message:"Module name is required",details:{module:e}}),e.operations.length||t.push({message:"Module operations are required",details:{module:e}});const n=e.operations.reduce((r,i)=>[...r,...ta(i)],[]);return[...t,...n]}function ta(e){const t=[];return e.name||t.push({message:"Operation name is required",details:{operation:e}}),e.schema||t.push({message:"Operation schema is required",details:{operation:e}}),t}export{da as $,lt as A,As as B,ma as C,fa as D,ha as E,No as F,ls as G,zo as H,Lo as I,Po as J,Uo as K,jo as L,us as M,Bo as N,Fo as O,Wo as P,Go as Q,Xo as R,Ko as S,Qo as T,ts as U,ss as V,rs as W,Zo as X,ia as Y,br as Z,Bi as _,Tn as a,ga as a0,_a as a1,ba as a2,di as a3,pi as a4,Ss as a5,pa as a6,Is as b,oe as c,Fi as d,$i as e,bn as f,Dt as g,$t as h,_n as i,Bs as j,xi as k,Ct as l,ua as m,Re as n,aa as o,on as p,la as q,ca as r,Te as s,Ri as t,dt as u,oa as v,yn as w,Di as x,Ni as y,sa as z};
|
|
230
|
+
}`,template:"",reducer:"",examples:[],errors:[],scope:"global"}],id:"",description:""}]}]},br="powerhouse/document-model",Is=ee({id:L(),name:L(),createdAtUtcIso:L(),lastModifiedAtUtcIso:L(),documentType:L()}),As=ee({global:sn()}),Rs=Is.extend({documentType:be(br)}),gt=As.extend({global:vo()}),yr=ee({header:Rs,state:gt,initialState:gt});function ks(e){return gt.safeParse(e).success}function Ts(e){gt.parse(e)}function Ds(e){return yr.safeParse(e).success}function Cs(e){yr.parse(e)}function tt(e){const t={};return e.forEach((n,r)=>t[n]=r),(n,r)=>(t[r.id]||999999)-(t[n.id]||999999)}const je={setModelNameOperation(e,t){e.name=t.input.name},setModelIdOperation(e,t){e.id=t.input.id},setModelExtensionOperation(e,t){e.extension=t.input.extension},setModelDescriptionOperation(e,t){e.description=t.input.description},setAuthorNameOperation(e,t){e.author=e.author||{name:"",website:null},e.author.name=t.input.authorName},setAuthorWebsiteOperation(e,t){e.author=e.author||{name:"",website:null},e.author.website=t.input.authorWebsite}},Xe={addModuleOperation(e,t){e.specifications[e.specifications.length-1].modules.push({id:t.input.id,name:t.input.name,description:t.input.description||"",operations:[]})},setModuleNameOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)n.modules[r].id===t.input.id&&(n.modules[r].name=t.input.name||"")},setModuleDescriptionOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)n.modules[r].id===t.input.id&&(n.modules[r].description=t.input.description||"")},deleteModuleOperation(e,t){const n=e.specifications[e.specifications.length-1];n.modules=n.modules.filter(r=>r.id!=t.input.id)},reorderModulesOperation(e,t){e.specifications[e.specifications.length-1].modules.sort(tt(t.input.order))}},ze={addOperationErrorOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.operationId&&n.modules[r].operations[i].errors.push({id:t.input.id,name:t.input.errorName||"",code:t.input.errorCode||"",description:t.input.errorDescription||"",template:t.input.errorTemplate||""})},setOperationErrorCodeOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)for(let s=0;s<n.modules[r].operations[i].errors.length;s++)n.modules[r].operations[i].errors[s].id==t.input.id&&(n.modules[r].operations[i].errors[s].code=t.input.errorCode||"")},setOperationErrorNameOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)for(let s=0;s<n.modules[r].operations[i].errors.length;s++)n.modules[r].operations[i].errors[s].id==t.input.id&&(n.modules[r].operations[i].errors[s].name=t.input.errorName||"")},setOperationErrorDescriptionOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)for(let s=0;s<n.modules[r].operations[i].errors.length;s++)n.modules[r].operations[i].errors[s].id==t.input.id&&(n.modules[r].operations[i].errors[s].description=t.input.errorDescription||"")},setOperationErrorTemplateOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)for(let s=0;s<n.modules[r].operations[i].errors.length;s++)n.modules[r].operations[i].errors[s].id==t.input.id&&(n.modules[r].operations[i].errors[s].template=t.input.errorTemplate||"")},deleteOperationErrorOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].errors=n.modules[r].operations[i].errors.filter(s=>s.id!=t.input.id)},reorderOperationErrorsOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.operationId&&n.modules[r].operations[i].errors.sort(tt(t.input.order))}},ut={addOperationExampleOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.operationId&&n.modules[r].operations[i].examples.push({id:t.input.id,value:t.input.example})},updateOperationExampleOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)for(let s=0;s<n.modules[r].operations[i].examples.length;s++)n.modules[r].operations[i].examples[s].id==t.input.id&&(n.modules[r].operations[i].examples[s].value=t.input.example)},deleteOperationExampleOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].examples=n.modules[r].operations[i].examples.filter(s=>s.id!=t.input.id)},reorderOperationExamplesOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.operationId&&n.modules[r].operations[i].examples.sort(tt(t.input.order))}},ve={addOperationOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)n.modules[r].id==t.input.moduleId&&n.modules[r].operations.push({id:t.input.id,name:t.input.name,description:t.input.description||"",schema:t.input.schema||"",template:t.input.template||t.input.description||"",reducer:t.input.reducer||"",errors:[],examples:[],scope:t.input.scope||"global"})},setOperationNameOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.id&&(n.modules[r].operations[i].name=t.input.name||"")},setOperationScopeOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.id&&(n.modules[r].operations[i].scope=t.input.scope||"global")},setOperationSchemaOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.id&&(n.modules[r].operations[i].schema=t.input.schema||"")},setOperationDescriptionOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.id&&(n.modules[r].operations[i].description=t.input.description||"")},setOperationTemplateOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.id&&(n.modules[r].operations[i].template=t.input.template||"")},setOperationReducerOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)for(let i=0;i<n.modules[r].operations.length;i++)n.modules[r].operations[i].id==t.input.id&&(n.modules[r].operations[i].reducer=t.input.reducer||"")},moveOperationOperation(e,t){const n=[],r=e.specifications[e.specifications.length-1];for(let i=0;i<r.modules.length;i++)r.modules[i].operations=r.modules[i].operations.filter(s=>s.id==t.input.operationId?(n.push(s),!1):!0);for(let i=0;i<r.modules.length;i++)r.modules[i].id==t.input.newModuleId&&r.modules[i].operations.push(...n)},deleteOperationOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)n.modules[r].operations=n.modules[r].operations.filter(i=>i.id!=t.input.id)},reorderModuleOperationsOperation(e,t){const n=e.specifications[e.specifications.length-1];for(let r=0;r<n.modules.length;r++)n.modules[r].id==t.input.moduleId&&n.modules[r].operations.sort(tt(t.input.order))}},Be={setStateSchemaOperation(e,t){const n=e.specifications[e.specifications.length-1];if(Object.keys(n.state).includes(t.input.scope))n.state[t.input.scope].schema=t.input.schema;else throw new Error(`Invalid scope: ${t.input.scope}`)},setInitialStateOperation(e,t){const n=e.specifications[e.specifications.length-1];if(Object.keys(n.state).includes(t.input.scope))n.state[t.input.scope].initialValue=t.input.initialValue;else throw new Error(`Invalid scope: ${t.input.scope}`)},addStateExampleOperation(e,t){const n=e.specifications[e.specifications.length-1];if(Object.keys(n.state).includes(t.input.scope))n.state[t.input.scope].examples.push({id:t.input.id,value:t.input.example});else throw new Error(`Invalid scope: ${t.input.scope}`)},updateStateExampleOperation(e,t){const n=e.specifications[e.specifications.length-1];if(!Object.keys(n.state).includes(t.input.scope))throw new Error(`Invalid scope: ${t.input.scope}`);const r=n.state[t.input.scope].examples;for(let i=0;i<r.length;i++)r[i].id==t.input.id&&(r[i].value=t.input.newExample)},deleteStateExampleOperation(e,t){const n=e.specifications[e.specifications.length-1];if(Object.keys(n.state).includes(t.input.scope))n.state[t.input.scope].examples=n.state[t.input.scope].examples.filter(r=>r.id!=t.input.id);else throw new Error(`Invalid scope: ${t.input.scope}`)},reorderStateExamplesOperation(e,t){const n=e.specifications[e.specifications.length-1];if(Object.keys(n.state).includes(t.input.scope))n.state[t.input.scope].examples.sort(tt(t.input.order));else throw new Error(`Invalid scope: ${t.input.scope}`)}},Ke={addChangeLogItemOperation(e,t){throw new Error('Reducer "addChangeLogItemOperation" not yet implemented')},updateChangeLogItemOperation(e,t){throw new Error('Reducer "updateChangeLogItemOperation" not yet implemented')},deleteChangeLogItemOperation(e,t){throw new Error('Reducer "deleteChangeLogItemOperation" not yet implemented')},reorderChangeLogItemsOperation(e,t){throw new Error('Reducer "reorderChangeLogItemsOperation" not yet implemented')},releaseNewVersionOperation(e,t){throw new Error('Reducer "releaseNewVersionOperation" not yet implemented')}},Ms=(e,t)=>{if(_n(t))return e;switch(t.type){case"SET_MODEL_NAME":nr().parse(t.input),je.setModelNameOperation(e.global,t);break;case"SET_MODEL_ID":tr().parse(t.input),je.setModelIdOperation(e.global,t);break;case"SET_MODEL_EXTENSION":er().parse(t.input),je.setModelExtensionOperation(e.global,t);break;case"SET_MODEL_DESCRIPTION":Qn().parse(t.input),je.setModelDescriptionOperation(e.global,t);break;case"SET_AUTHOR_NAME":Jn().parse(t.input),je.setAuthorNameOperation(e.global,t);break;case"SET_AUTHOR_WEBSITE":qn().parse(t.input),je.setAuthorWebsiteOperation(e.global,t);break;case"ADD_CHANGE_LOG_ITEM":Mn().parse(t.input),Ke.addChangeLogItemOperation(e.global,t);break;case"UPDATE_CHANGE_LOG_ITEM":gr().parse(t.input),Ke.updateChangeLogItemOperation(e.global,t);break;case"DELETE_CHANGE_LOG_ITEM":jn().parse(t.input),Ke.deleteChangeLogItemOperation(e.global,t);break;case"REORDER_CHANGE_LOG_ITEMS":Zn().parse(t.input),Ke.reorderChangeLogItemsOperation(e.global,t);break;case"RELEASE_NEW_VERSION":if(Object.keys(t.input).length>0)throw new Error("Expected empty input for action RELEASE_NEW_VERSION");Ke.releaseNewVersionOperation(e.global,t);break;case"ADD_MODULE":Nn().parse(t.input),Xe.addModuleOperation(e.global,t);break;case"SET_MODULE_NAME":ir().parse(t.input),Xe.setModuleNameOperation(e.global,t);break;case"SET_MODULE_DESCRIPTION":rr().parse(t.input),Xe.setModuleDescriptionOperation(e.global,t);break;case"DELETE_MODULE":Bn().parse(t.input),Xe.deleteModuleOperation(e.global,t);break;case"REORDER_MODULES":Vn().parse(t.input),Xe.reorderModulesOperation(e.global,t);break;case"ADD_OPERATION_ERROR":zn().parse(t.input),ze.addOperationErrorOperation(e.global,t);break;case"SET_OPERATION_ERROR_CODE":sr().parse(t.input),ze.setOperationErrorCodeOperation(e.global,t);break;case"SET_OPERATION_ERROR_NAME":lr().parse(t.input),ze.setOperationErrorNameOperation(e.global,t);break;case"SET_OPERATION_ERROR_DESCRIPTION":ar().parse(t.input),ze.setOperationErrorDescriptionOperation(e.global,t);break;case"SET_OPERATION_ERROR_TEMPLATE":ur().parse(t.input),ze.setOperationErrorTemplateOperation(e.global,t);break;case"DELETE_OPERATION_ERROR":Fn().parse(t.input),ze.deleteOperationErrorOperation(e.global,t);break;case"REORDER_OPERATION_ERRORS":Xn().parse(t.input),ze.reorderOperationErrorsOperation(e.global,t);break;case"ADD_OPERATION_EXAMPLE":wo().parse(t.input),ut.addOperationExampleOperation(e.global,t);break;case"UPDATE_OPERATION_EXAMPLE":Co().parse(t.input),ut.updateOperationExampleOperation(e.global,t);break;case"DELETE_OPERATION_EXAMPLE":xo().parse(t.input),ut.deleteOperationExampleOperation(e.global,t);break;case"REORDER_OPERATION_EXAMPLES":To().parse(t.input),ut.reorderOperationExamplesOperation(e.global,t);break;case"ADD_OPERATION":Pn().parse(t.input),ve.addOperationOperation(e.global,t);break;case"SET_OPERATION_NAME":cr().parse(t.input),ve.setOperationNameOperation(e.global,t);break;case"SET_OPERATION_SCOPE":pr().parse(t.input),ve.setOperationScopeOperation(e.global,t);break;case"SET_OPERATION_SCHEMA":fr().parse(t.input),ve.setOperationSchemaOperation(e.global,t);break;case"SET_OPERATION_DESCRIPTION":or().parse(t.input),ve.setOperationDescriptionOperation(e.global,t);break;case"SET_OPERATION_TEMPLATE":hr().parse(t.input),ve.setOperationTemplateOperation(e.global,t);break;case"SET_OPERATION_REDUCER":dr().parse(t.input),ve.setOperationReducerOperation(e.global,t);break;case"MOVE_OPERATION":Hn().parse(t.input),ve.moveOperationOperation(e.global,t);break;case"DELETE_OPERATION":$n().parse(t.input),ve.deleteOperationOperation(e.global,t);break;case"REORDER_MODULE_OPERATIONS":Gn().parse(t.input),ve.reorderModuleOperationsOperation(e.global,t);break;case"SET_STATE_SCHEMA":mr().parse(t.input),Be.setStateSchemaOperation(e.global,t);break;case"SET_INITIAL_STATE":Yn().parse(t.input),Be.setInitialStateOperation(e.global,t);break;case"ADD_STATE_EXAMPLE":Ln().parse(t.input),Be.addStateExampleOperation(e.global,t);break;case"UPDATE_STATE_EXAMPLE":_r().parse(t.input),Be.updateStateExampleOperation(e.global,t);break;case"DELETE_STATE_EXAMPLE":Wn().parse(t.input),Be.deleteStateExampleOperation(e.global,t);break;case"REORDER_STATE_EXAMPLES":Kn().parse(t.input),Be.reorderStateExamplesOperation(e.global,t);break;default:return e}},Er=Tn(Ms),Ns=(e,t)=>Fi(e,t),zs=e=>$i(e,Er),Sr=e=>({...$t(),global:{...xs,...e?.global??{}},local:{...Os,...e?.local??{}}});function Ps(){return{...$t(),author:{name:"",website:""},description:"",extension:"",id:"",name:"",specifications:[]}}function Ls(){return{}}function Us(e){return{...Ps(),...e||{}}}function js(e){return{...Ls()}}function Bs(e,t,n){return{...So(e?.auth,e?.document),global:Us(t),local:js()}}function Fs(e){const t=bn(Sr,e);return t.header.documentType=br,t}const $s=e=>ks(e),Ws=e=>{Ts(e)},Hs=e=>Ds(e),Zs=e=>{Cs(e)},Gs={fileExtension:ws,createState:Sr,createDocument:Fs,loadFromInput:zs,saveToFileHandle:Ns,isStateOfType:$s,assertIsStateOfType:Ws,isDocumentOfType:Hs,assertIsDocumentOfType:Zs},pa={reducer:Er,documentModel:Bs($t(),vs),actions:Ss,utils:Gs},Vs=new RegExp("([\\p{Ll}\\d])(\\p{Lu})","gu"),Xs=new RegExp("(\\p{Lu})([\\p{Lu}][\\p{Ll}])","gu"),Ks=new RegExp("(\\d)\\p{Ll}|(\\p{L})\\d","u"),Js=/[^\p{L}\d]+/giu,nn="$1\0$2",rn="";function wr(e){let t=e.trim();t=t.replace(Vs,nn).replace(Xs,nn),t=t.replace(Js,"\0");let n=0,r=t.length;for(;t.charAt(n)==="\0";)n++;if(n===r)return[];for(;t.charAt(r-1)==="\0";)r--;return t.slice(n,r).split(/\0/g)}function qs(e){const t=wr(e);for(let n=0;n<t.length;n++){const r=t[n],i=Ks.exec(r);if(i){const s=i.index+(i[1]??i[2]).length;t.splice(n,1,r.slice(0,s),r.slice(s))}}return t}function Ys(e,t){const[n,r,i]=nt(e,t);return n+r.map(bt(t?.locale)).join(t?.delimiter??" ")+i}function on(e,t){const[n,r,i]=nt(e,t),s=bt(t?.locale),l=yt(t?.locale),o=t?.mergeAmbiguousCharacters?Wt(s,l):Qs(s,l);return n+r.map(o).join(t?.delimiter??"")+i}function da(e,t){const[n,r,i]=nt(e,t),s=bt(t?.locale),l=yt(t?.locale);return n+r.map(Wt(s,l)).join(" ")+i}function fa(e,t){const[n,r,i]=nt(e,t);return n+r.map(yt(t?.locale)).join("_")+i}function ha(e,t){const[n,r,i]=nt(e,t),s=bt(t?.locale),l=yt(t?.locale),o=Wt(s,l);return n+r.map((u,d)=>d===0?o(u):s(u)).join(" ")+i}function ma(e,t){return Ys(e,{delimiter:"_",...t})}function bt(e){return e===!1?t=>t.toLowerCase():t=>t.toLocaleLowerCase(e)}function yt(e){return e===!1?t=>t.toUpperCase():t=>t.toLocaleUpperCase(e)}function Wt(e,t){return n=>`${t(n[0])}${e(n.slice(1))}`}function Qs(e,t){return(n,r)=>{const i=n[0];return(r>0&&i>="0"&&i<="9"?"_"+i:t(i))+e(n.slice(1))}}function nt(e,t={}){const n=t.split??(t.separateNumbers?qs:wr),r=t.prefixCharacters??rn,i=t.suffixCharacters??rn;let s=0,l=e.length;for(;s<e.length;){const o=e.charAt(s);if(!r.includes(o))break;s++}for(;l>s;){const o=l-1,u=e.charAt(o);if(!i.includes(u))break;l=o}return[e.slice(0,s),n(e.slice(s,l)),e.slice(l)]}function ga(e,t=!1){const n=[];if(t&&e==="")return n;try{const r=JSON.parse(e);!t&&!Object.keys(r).length&&n.push({message:"Initial state cannot be empty",details:{initialState:e}})}catch{n.push({message:"Invalid initial state",details:{initialState:e}})}return n}function _a(e,t,n="",r=!0){const i=[];if(!r&&!e)return i.push({message:"State schema is required",details:{schema:e}}),i;if(r&&!e)return i;const s=`type ${on(t)}${on(n)}State`;return e.includes(s)||i.push({message:`Invalid state schema name. Expected ${s}`,details:{schema:e}}),i}function ba(e){const t=[];e.length||t.push({message:"Modules are required",details:{modules:e}});const n=e.reduce((r,i)=>[...r,...ea(i)],[]);return[...t,...n]}function ea(e){const t=[];e.name||t.push({message:"Module name is required",details:{module:e}}),e.operations.length||t.push({message:"Module operations are required",details:{module:e}});const n=e.operations.reduce((r,i)=>[...r,...ta(i)],[]);return[...t,...n]}function ta(e){const t=[];return e.name||t.push({message:"Operation name is required",details:{operation:e}}),e.schema||t.push({message:"Operation schema is required",details:{operation:e}}),t}export{da as $,lt as A,As as B,ma as C,fa as D,ha as E,No as F,ls as G,zo as H,Lo as I,Po as J,Uo as K,jo as L,us as M,Bo as N,Fo as O,Wo as P,Go as Q,Xo as R,Ko as S,Qo as T,ts as U,ss as V,rs as W,Zo as X,ia as Y,br as Z,Bi as _,Tn as a,ga as a0,_a as a1,ba as a2,di as a3,pi as a4,pa as a5,Is as b,oe as c,Fi as d,$i as e,bn as f,Dt as g,$t as h,_n as i,Bs as j,xi as k,Ct as l,ua as m,Re as n,aa as o,on as p,la as q,ca as r,Te as s,Ri as t,dt as u,oa as v,yn as w,Di as x,Ni as y,sa as z};
|