@powerhousedao/connect 5.3.0-staging.1 → 6.0.0-dev.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/assets/{AddDriveModal-BaGIi8vQ.js → AddDriveModal-_x1y6p4m.js} +1 -1
  2. package/dist/assets/{ClearStorageModal-CScB4u-p.js → ClearStorageModal-BcTd6IC1.js} +1 -1
  3. package/dist/assets/{CookiesPolicyModal-DulYZ5bm.js → CookiesPolicyModal-BfdRVCA5.js} +1 -1
  4. package/dist/assets/CreateDocumentModal-DzXIA0Er.js +1 -0
  5. package/dist/assets/{DebugSettingsModal-X0kJfQAa.js → DebugSettingsModal-D_aRTwuB.js} +1 -1
  6. package/dist/assets/{DeleteDriveModal-D6ii7XTq.js → DeleteDriveModal-CqFSjMMh.js} +1 -1
  7. package/dist/assets/{DeleteItemModal-DkwcYMp2.js → DeleteItemModal-CDZUTtlh.js} +1 -1
  8. package/dist/assets/DisclaimerModal-SsfIjXst.js +1 -0
  9. package/dist/assets/{DriveSettingsModal-dYjQYZro.js → DriveSettingsModal-Bu7CPXJ4.js} +1 -1
  10. package/dist/assets/{ExportDocumentWithErrorsModal-vxemnGJT.js → ExportDocumentWithErrorsModal-CEoe5qUC.js} +1 -1
  11. package/dist/assets/SettingsModal-BVnu4BKJ.js +1 -0
  12. package/dist/assets/UpgradeDriveModal-CCcnoZmg.js +1 -0
  13. package/dist/assets/{design_system-_b6SoDrj.js → design_system-oL0zkmXl.js} +1 -1
  14. package/dist/assets/design_system_connect-Chmc_T62.js +47 -0
  15. package/dist/assets/{design_system_ui-CDriTbBJ.js → design_system_ui-DunNjQjs.js} +1 -1
  16. package/dist/assets/{document_drive-BJsaRH1s.js → document_drive-CwpHvdiT.js} +5 -5
  17. package/dist/assets/{document_engineering-qm7xrxNm.js → document_engineering-BCLQ2KL7.js} +1 -1
  18. package/dist/assets/document_model-_oCbt5YE.js +230 -0
  19. package/dist/assets/document_model_editor-DIDAkfrS.js +25 -0
  20. package/dist/assets/{drive_explorer-DWwFzk6h.js → drive_explorer-B87HG3LQ.js} +2 -2
  21. package/dist/assets/{graphql-editor-4pzWaFSe.js → graphql-editor-BQIGoOZV.js} +1 -1
  22. package/dist/assets/{hooks-Cjt8t5rh.js → hooks-DgFoMbwM.js} +1 -1
  23. package/dist/assets/{index-DvZTwJrp.js → index-D7v8KZ6u.js} +2 -2
  24. package/dist/assets/index-DNce0SAe.css +1 -0
  25. package/dist/assets/index-DSJKsIl8.js +18 -0
  26. package/dist/assets/{json-editor-pFQ5xjc9.js → json-editor-DHdm2UYU.js} +1 -1
  27. package/dist/assets/{nodefs-Cy7Dibn2.js → nodefs-z9lzKpzj.js} +1 -1
  28. package/dist/assets/{opfs-ahp-DEHvPLFW.js → opfs-ahp-BkjTKCfd.js} +1 -1
  29. package/dist/assets/{reactor_browser-BlK2TQJE.js → reactor_browser-BxF5zzU5.js} +7 -7
  30. package/dist/assets/{state-schemas-DJRajivH.js → state-schemas-DY2BYnhP.js} +2 -2
  31. package/dist/assets/zod-9j67vCAu.js +39 -0
  32. package/dist/index.html +11 -11
  33. package/lib/package.copy.json +4 -4
  34. package/lib/src/components/sidebar.d.ts.map +1 -1
  35. package/lib/src/components/sidebar.js +1 -3
  36. package/lib/src/components/sidebar.js.map +1 -1
  37. package/lib/src/feature-flags.d.ts.map +1 -1
  38. package/lib/src/feature-flags.js +12 -8
  39. package/lib/src/feature-flags.js.map +1 -1
  40. package/lib/src/store/document-model.d.ts.map +1 -1
  41. package/lib/src/store/document-model.js +1 -0
  42. package/lib/src/store/document-model.js.map +1 -1
  43. package/lib/src/store/reactor.d.ts.map +1 -1
  44. package/lib/src/store/reactor.js +28 -4
  45. package/lib/src/store/reactor.js.map +1 -1
  46. package/lib/src/utils/reactor.d.ts +2 -2
  47. package/lib/src/utils/reactor.d.ts.map +1 -1
  48. package/lib/src/utils/reactor.js +2 -1
  49. package/lib/src/utils/reactor.js.map +1 -1
  50. package/lib/style.css +4 -17
  51. package/lib/tsconfig.tsbuildinfo +1 -1
  52. package/package.copy.json +4 -4
  53. package/package.json +13 -13
  54. package/dist/assets/CreateDocumentModal-BFEO-_3C.js +0 -1
  55. package/dist/assets/DisclaimerModal-KCxDVSG6.js +0 -1
  56. package/dist/assets/SettingsModal-BFoKkqXU.js +0 -1
  57. package/dist/assets/UpgradeDriveModal-nmnDh0_f.js +0 -1
  58. package/dist/assets/design_system_connect-DbWBZgB6.js +0 -47
  59. package/dist/assets/document_model-ZlYfiMj0.js +0 -230
  60. package/dist/assets/document_model_editor-oMof2yfF.js +0 -25
  61. package/dist/assets/index-DGEkQuau.css +0 -1
  62. package/dist/assets/index-nUEwQ7yX.js +0 -18
  63. package/dist/assets/zod-BpTyxkjy.js +0 -20
@@ -1,4 +1,5 @@
1
- import{c as oe,a as as,i as cs,B as us,b as ds,d as ls,e as hs,f as fs,g as $e,h as $t,j as gs,k as Ve,p as Ar,l as Ue,v as Ge,m as or,n as ar,r as ps,o as bt,s as Je,q as ms,t as ys,u as vs,w as We,x as Nr,y as ws,z as bs,A as Ds,C as Ye}from"./document_model-ZlYfiMj0.js";import{a as Ss,p as Es,G as Is,b as Ts,c as Dt,d as cr,e as St,f as Rs,g as Ms}from"./graphql-AKTCpY7l.js";import{c as Ee,g as Pt}from"./react-DQSxOgtG.js";import{o as W,s as $,e as tt,a as pe,_ as Cr,d as Oe,u as Os,b as _s}from"./zod-BpTyxkjy.js";import{i as As,L as he}from"./config-CU-aFfVJ.js";function Ns(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"}))}const ur=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 Cs{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 xs{cache;cacheStorageManager;idToDocument;idToDrive;slugToDriveId;constructor(e=new Map){this.cache=e,this.cacheStorageManager=new Cs(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=ur(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=ur(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 $s="phdd",Ps=i=>i!=null;_s().refine(i=>Ps(i));const Ls=Cr(["Internal","MatrixConnect","PullResponder","RESTWebhook","SecureConnect","SwitchboardPush"]),Us=Cr(["PullResponder"]);function xr(){return W({documentType:$(),id:$(),name:$(),parentFolder:$().nullish()})}function $r(){return W({id:$(),name:$(),parentFolder:$().nullish()})}function Pr(){return W({listener:Fr()})}function Lr(){return W({trigger:Yr()})}function Ur(){return W({srcId:$(),targetId:$(),targetName:$().nullish(),targetParentFolder:$().nullish()})}function Br(){return W({id:$()})}function Bs(){return W({__typename:pe("DocumentDriveLocalState").optional(),availableOffline:tt(),listeners:Oe(Fr()),sharingType:$().nullable(),triggers:Oe(Yr())})}function Fs(){return W({__typename:pe("DocumentDriveState").optional(),icon:$().nullable(),name:$(),nodes:Oe(Hs())})}function ks(){return W({__typename:pe("FileNode").optional(),documentType:$(),id:$(),kind:$(),name:$(),parentFolder:$().nullable()})}function qs(){return W({__typename:pe("FolderNode").optional(),id:$(),kind:$(),name:$(),parentFolder:$().nullable()})}function Fr(){return W({__typename:pe("Listener").optional(),block:tt(),callInfo:zs().nullable(),filter:js(),label:$().nullable(),listenerId:$(),system:tt()})}function zs(){return W({__typename:pe("ListenerCallInfo").optional(),data:$().nullable(),name:$().nullable(),transmitterType:Ls.nullable()})}function js(){return W({__typename:pe("ListenerFilter").optional(),branch:Oe($()).nullable(),documentId:Oe($()).nullable(),documentType:Oe($()),scope:Oe($()).nullable()})}function kr(){return W({srcFolder:$(),targetParentFolder:$().nullish()})}function Hs(){return Os([ks(),qs()])}function Gs(){return W({__typename:pe("PullResponderTriggerData").optional(),interval:$(),listenerId:$(),url:$()})}function qr(){return W({listenerId:$()})}function zr(){return W({triggerId:$()})}function jr(){return W({availableOffline:tt()})}function Hr(){return W({icon:$()})}function Gr(){return W({name:$()})}function Jr(){return W({type:$()})}function Yr(){return W({__typename:pe("Trigger").optional(),data:Js().nullable(),id:$(),type:Us})}function Js(){return Gs()}function Qr(){return W({documentType:$().nullish(),id:$(),name:$().nullish(),parentFolder:$().nullish()})}function Kr(){return W({id:$(),name:$().nullish(),parentFolder:$().nullish()})}function Ys(i){return i&&typeof i=="object"&&"synchronizationUnits"in i?oe("ADD_FILE",{...i},void 0,void 0,"global"):oe("ADD_FILE",{...i},void 0,xr,"global")}const Qs=i=>oe("ADD_FOLDER",{...i},void 0,$r,"global"),Ks=i=>oe("DELETE_NODE",{...i},void 0,Br,"global"),Vs=i=>oe("UPDATE_FILE",{...i},void 0,Qr,"global"),Ws=i=>oe("UPDATE_NODE",{...i},void 0,Kr,"global"),Xs=i=>oe("COPY_NODE",{...i},void 0,Ur,"global"),Zs=i=>oe("MOVE_NODE",{...i},void 0,kr,"global"),ei=i=>oe("SET_DRIVE_NAME",{...i},void 0,Gr,"global"),ti=i=>oe("SET_DRIVE_ICON",{...i},void 0,Hr,"global"),Vr=i=>oe("SET_SHARING_TYPE",{...i},void 0,Jr,"local"),ri=i=>oe("SET_AVAILABLE_OFFLINE",{...i},void 0,jr,"local"),ni=i=>oe("ADD_LISTENER",{...i},void 0,Pr,"local"),Wr=i=>oe("REMOVE_LISTENER",{...i},void 0,qr,"local"),si=i=>oe("ADD_TRIGGER",{...i},void 0,Lr,"local"),Xr=i=>oe("REMOVE_TRIGGER",{...i},void 0,zr,"local"),ii=Object.freeze(Object.defineProperty({__proto__:null,addFile:Ys,addFolder:Qs,addListener:ni,addTrigger:si,copyNode:Xs,deleteNode:Ks,moveNode:Zs,removeListener:Wr,removeTrigger:Xr,setAvailableOffline:ri,setDriveIcon:ti,setDriveName:ei,setSharingType:Vr,updateFile:Vs,updateNode:Ws},Symbol.toStringTag,{value:"Module"})),oi={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 {
1
+ import{c as oe,a as as,i as cs,B as us,b as ds,d as ls,e as hs,f as fs,g as $e,h as $t,j as gs,k as Ve,p as Ar,l as Ue,v as Ge,m as or,n as ar,r as ps,o as bt,s as Je,q as ms,t as ys,u as vs,w as We,x as Nr,y as ws,z as bs,A as Ds,C as Ye}from"./document_model-_oCbt5YE.js";import{a as Ss,p as Es,G as Is,b as Ts,c as Dt,d as cr,e as St,f as Rs,g as Ms}from"./graphql-AKTCpY7l.js";import{c as Ee,g as Pt}from"./react-DQSxOgtG.js";import{o as W,s as $,e as tt,a as pe,_ as Cr,d as Oe,u as Os,b as _s}from"./zod-9j67vCAu.js";import{i as As,L as he}from"./config-CU-aFfVJ.js";function Ns(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"}))}const ur=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 Cs{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 xs{cache;cacheStorageManager;idToDocument;idToDrive;slugToDriveId;constructor(e=new Map){this.cache=e,this.cacheStorageManager=new Cs(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=ur(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=ur(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}}var $s={};class xr{#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"&&!As(e))throw new Error(`Invalid log level: ${JSON.stringify(e)}.
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?$s.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 ct=new xr;let Lt="env",$r;ct.level=Lt;ct.errorHandler=$r;const fe=ct,Mo=i=>{Lt=i,ct.level=i},me=i=>{const e=new xr(i);return e.level=Lt,e.errorHandler=$r,e},Ps="phdd",Ls=i=>i!=null;_s().refine(i=>Ls(i));const Us=Cr(["Internal","MatrixConnect","PullResponder","RESTWebhook","SecureConnect","SwitchboardPush"]),Bs=Cr(["PullResponder"]);function Pr(){return W({documentType:$(),id:$(),name:$(),parentFolder:$().nullish()})}function Lr(){return W({id:$(),name:$(),parentFolder:$().nullish()})}function Ur(){return W({listener:qr()})}function Br(){return W({trigger:Kr()})}function Fr(){return W({srcId:$(),targetId:$(),targetName:$().nullish(),targetParentFolder:$().nullish()})}function kr(){return W({id:$()})}function Fs(){return W({__typename:pe("DocumentDriveLocalState").optional(),availableOffline:tt(),listeners:Oe(qr()),sharingType:$().nullable(),triggers:Oe(Kr())})}function ks(){return W({__typename:pe("DocumentDriveState").optional(),icon:$().nullable(),name:$(),nodes:Oe(Gs())})}function qs(){return W({__typename:pe("FileNode").optional(),documentType:$(),id:$(),kind:$(),name:$(),parentFolder:$().nullable()})}function zs(){return W({__typename:pe("FolderNode").optional(),id:$(),kind:$(),name:$(),parentFolder:$().nullable()})}function qr(){return W({__typename:pe("Listener").optional(),block:tt(),callInfo:js().nullable(),filter:Hs(),label:$().nullable(),listenerId:$(),system:tt()})}function js(){return W({__typename:pe("ListenerCallInfo").optional(),data:$().nullable(),name:$().nullable(),transmitterType:Us.nullable()})}function Hs(){return W({__typename:pe("ListenerFilter").optional(),branch:Oe($()).nullable(),documentId:Oe($()).nullable(),documentType:Oe($()),scope:Oe($()).nullable()})}function zr(){return W({srcFolder:$(),targetParentFolder:$().nullish()})}function Gs(){return Os([qs(),zs()])}function Js(){return W({__typename:pe("PullResponderTriggerData").optional(),interval:$(),listenerId:$(),url:$()})}function jr(){return W({listenerId:$()})}function Hr(){return W({triggerId:$()})}function Gr(){return W({availableOffline:tt()})}function Jr(){return W({icon:$()})}function Yr(){return W({name:$()})}function Qr(){return W({type:$()})}function Kr(){return W({__typename:pe("Trigger").optional(),data:Ys().nullable(),id:$(),type:Bs})}function Ys(){return Js()}function Vr(){return W({documentType:$().nullish(),id:$(),name:$().nullish(),parentFolder:$().nullish()})}function Wr(){return W({id:$(),name:$().nullish(),parentFolder:$().nullish()})}function Qs(i){return i&&typeof i=="object"&&"synchronizationUnits"in i?oe("ADD_FILE",{...i},void 0,void 0,"global"):oe("ADD_FILE",{...i},void 0,Pr,"global")}const Ks=i=>oe("ADD_FOLDER",{...i},void 0,Lr,"global"),Vs=i=>oe("DELETE_NODE",{...i},void 0,kr,"global"),Ws=i=>oe("UPDATE_FILE",{...i},void 0,Vr,"global"),Xs=i=>oe("UPDATE_NODE",{...i},void 0,Wr,"global"),Zs=i=>oe("COPY_NODE",{...i},void 0,Fr,"global"),ei=i=>oe("MOVE_NODE",{...i},void 0,zr,"global"),ti=i=>oe("SET_DRIVE_NAME",{...i},void 0,Yr,"global"),ri=i=>oe("SET_DRIVE_ICON",{...i},void 0,Jr,"global"),Xr=i=>oe("SET_SHARING_TYPE",{...i},void 0,Qr,"local"),ni=i=>oe("SET_AVAILABLE_OFFLINE",{...i},void 0,Gr,"local"),si=i=>oe("ADD_LISTENER",{...i},void 0,Ur,"local"),Zr=i=>oe("REMOVE_LISTENER",{...i},void 0,jr,"local"),ii=i=>oe("ADD_TRIGGER",{...i},void 0,Br,"local"),en=i=>oe("REMOVE_TRIGGER",{...i},void 0,Hr,"local"),oi=Object.freeze(Object.defineProperty({__proto__:null,addFile:Qs,addFolder:Ks,addListener:si,addTrigger:ii,copyNode:Zs,deleteNode:Vs,moveNode:ei,removeListener:Zr,removeTrigger:en,setAvailableOffline:ni,setDriveIcon:ri,setDriveName:ti,setSharingType:Xr,updateFile:Ws,updateNode:Xs},Symbol.toStringTag,{value:"Module"})),ai={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 {
2
3
  id: String!
3
4
  name: String!
4
5
  kind: String!
@@ -117,8 +118,7 @@ type DocumentDriveLocalState{
117
118
  trigger: Trigger!
118
119
  }`,template:"",reducer:"",errors:[],examples:[],scope:"local"},{id:"qGCiPGpTt/cyz3HzyrBn92z30dsU=",name:"REMOVE_TRIGGER",description:"",schema:`input RemoveTriggerInput {
119
120
  triggerId: String!
120
- }`,template:"",reducer:"",errors:[],examples:[],scope:"local"}]}]}]},ct="powerhouse/document-drive",Se={setDriveNameOperation(i,e,t){i.name=e.input.name},setDriveIconOperation(i,e,t){i.icon=e.input.icon},setSharingTypeOperation(i,e,t){i.sharingType=e.input.type},setAvailableOfflineOperation(i,e,t){i.availableOffline=e.input.availableOffline},addListenerOperation(i,e,t){if(i.listeners.find(r=>r.listenerId===e.input.listener.listenerId))throw new Error(`A listener with Id: ${e.input.listener.listenerId} already exists`);i.listeners.push(e.input.listener)},removeListenerOperation(i,e,t){i.listeners=i.listeners.filter(r=>r.listenerId!==e.input.listenerId)},addTriggerOperation(i,e,t){if(i.triggers.find(r=>r.id===e.input.trigger.id))throw new Error(`A trigger with Id: ${e.input.trigger.id} already exists`);i.triggers.push(e.input.trigger)},removeTriggerOperation(i,e,t){i.triggers=i.triggers.filter(r=>r.id!==e.input.triggerId)}};function dr(i){return i.kind==="file"}function ai(i){return i.kind==="folder"}function rt(i,e){const t=e.filter(n=>n.parentFolder===i.id),r=t.map(n=>rt(n,e));return[...t,...r.flat()]}function Mo(i,e,t){const r=t.find(d=>d.id===i.srcId);if(!r)throw new Error(`Node with id ${i.srcId} not found`);const n=[{...r,name:i.targetName||r.name,parentFolder:i.targetParentFolder||null},...rt(r,t)],s={};i.targetParentFolder&&(s[i.targetParentFolder]=i.targetParentFolder);const o=d=>{let l=s[d.id];if(!l){const y=d.id;l=e(d),s[y]=l}return l};return n.map(d=>({srcId:d.id,targetId:o(d),targetName:d.name,targetParentFolder:d.parentFolder?s[d.parentFolder]:null}))}function ci(i,e){let t=0;const r=new RegExp(`^${ui(e)} \\(copy\\)(?: (\\d+))?$`);for(const n of i){const s=n.match(r);if(s){const o=s[1]?parseInt(s[1],10):1;o>t&&(t=o)}}return t+1}function ui(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ne(i){const{nodes:e,targetParentFolder:t,srcName:r}=i,n=e.filter(a=>t===""?a.parentFolder===null:a.parentFolder===t).map(a=>a.name);return n.includes(r)?`${r} (copy) ${ci(n,r)}`:r}const Qe=i=>/^[a-zA-Z0-9-_.\s()]+$/.test(i),Te={addFileOperation(i,e,t){if(i.nodes.find(s=>s.id===e.input.id))throw new Error(`Node with id ${e.input.id} already exists!`);if(!Qe(e.input.name))throw new Error(`Invalid name: '${e.input.name}'. Names must be valid URL characters.`);const r=Ne({nodes:i.nodes,srcName:e.input.name,targetParentFolder:e.input.parentFolder||null}),n={id:e.input.id,name:r,kind:"file",parentFolder:e.input.parentFolder??null,documentType:e.input.documentType};i.nodes.push(n),t?.({type:"CREATE_CHILD_DOCUMENT",input:{id:e.input.id,documentType:e.input.documentType}})},addFolderOperation(i,e){if(i.nodes.find(r=>r.id===e.input.id))throw new Error(`Node with id ${e.input.id} already exists!`);if(!Qe(e.input.name))throw new Error(`Invalid name: '${e.input.name}'. Names must be valid URL characters.`);const t=Ne({nodes:i.nodes,srcName:e.input.name,targetParentFolder:e.input.parentFolder||null});i.nodes.push({...e.input,name:t,kind:"folder",parentFolder:e.input.parentFolder??null})},deleteNodeOperation(i,e,t){const r=i.nodes.find(s=>s.id===e.input.id);if(!r)throw new Error(`Node with id ${e.input.id} not found`);const n=rt(r,i.nodes);i.nodes=i.nodes.filter(s=>s.id!==e.input.id&&!n.find(o=>o.id===s.id)),[r,...n].filter(s=>dr(s)).forEach(s=>{t?.({type:"DELETE_CHILD_DOCUMENT",input:{id:s.id}})})},updateFileOperation(i,e){if(e.input.name&&!Qe(e.input.name))throw new Error(`Invalid name: '${e.input.name}'. Names must be valid URL characters.`);i.nodes=i.nodes.map(t=>t.id===e.input.id?{...t,name:Ne({nodes:i.nodes,srcName:e.input.name??t.name,targetParentFolder:e.input.parentFolder||null}),documentType:e.input.documentType??t.documentType}:t)},updateNodeOperation(i,e){if(e.input.name&&!Qe(e.input.name))throw new Error(`Invalid name: '${e.input.name}'. Names must be valid URL characters.`);i.nodes=i.nodes.map(t=>t.id===e.input.id?{...t,name:Ne({nodes:i.nodes,srcName:e.input.name??t.name,targetParentFolder:e.input.parentFolder||null}),parentFolder:e.input.parentFolder===null?null:t.parentFolder}:t)},copyNodeOperation(i,e,t){const r=i.nodes.find(d=>d.id===e.input.srcId);if(!r)throw new Error(`Node with id ${e.input.srcId} not found`);if(i.nodes.find(d=>d.id===e.input.targetId))throw new Error(`Node with id ${e.input.targetId} already exists`);const s=Ne({nodes:i.nodes,srcName:e.input.targetName||r.name,targetParentFolder:e.input.targetParentFolder||null}),o={...r,id:e.input.targetId,slug:e.input.targetId,name:s,parentFolder:e.input.targetParentFolder||null};i.nodes.push(o),dr(o)&&t?.({type:"COPY_CHILD_DOCUMENT",input:{id:e.input.srcId,newId:e.input.targetId}})},moveNodeOperation(i,e){if(e.input.srcFolder===e.input.targetParentFolder)throw new Error("Circular Reference Error: Attempting to move a node to its current parent folder");const t=i.nodes.find(n=>n.id===e.input.srcFolder);if(!t)throw new Error(`Node with id ${e.input.srcFolder} not found`);const r=Ne({nodes:i.nodes,srcName:t.name,targetParentFolder:e.input.targetParentFolder||null});if(ai(t)&&rt(t,i.nodes).find(s=>s.id===e.input.targetParentFolder))throw new Error("Circular Reference Error: Cannot move a folder to one of its descendants");i.nodes=i.nodes.map(n=>n.id===e.input.srcFolder?{...n,name:r,parentFolder:e.input.targetParentFolder||null}:n)}},di=(i,e,t)=>{if(cs(e))return i;const r=e;switch(r.type){case"ADD_FILE":xr().parse(r.input),Te.addFileOperation(i[r.scope],e,t);break;case"ADD_FOLDER":$r().parse(r.input),Te.addFolderOperation(i[r.scope],e,t);break;case"DELETE_NODE":Br().parse(r.input),Te.deleteNodeOperation(i[r.scope],e,t);break;case"UPDATE_FILE":Qr().parse(r.input),Te.updateFileOperation(i[r.scope],e,t);break;case"UPDATE_NODE":Kr().parse(r.input),Te.updateNodeOperation(i[r.scope],e,t);break;case"COPY_NODE":Ur().parse(r.input),Te.copyNodeOperation(i[r.scope],e,t);break;case"MOVE_NODE":kr().parse(r.input),Te.moveNodeOperation(i[r.scope],e,t);break;case"SET_DRIVE_NAME":Gr().parse(r.input),Se.setDriveNameOperation(i[r.scope],e,t);break;case"SET_DRIVE_ICON":Hr().parse(r.input),Se.setDriveIconOperation(i[r.scope],e,t);break;case"SET_SHARING_TYPE":Jr().parse(r.input),Se.setSharingTypeOperation(i[r.scope],e,t);break;case"SET_AVAILABLE_OFFLINE":jr().parse(r.input),Se.setAvailableOfflineOperation(i[r.scope],e,t);break;case"ADD_LISTENER":Pr().parse(r.input),Se.addListenerOperation(i[r.scope],e,t);break;case"REMOVE_LISTENER":qr().parse(r.input),Se.removeListenerOperation(i[r.scope],e,t);break;case"ADD_TRIGGER":Lr().parse(r.input),Se.addTriggerOperation(i[r.scope],e,t);break;case"REMOVE_TRIGGER":zr().parse(r.input),Se.removeTriggerOperation(i[r.scope],e,t);break;default:return i}},Zr=as(di),li=ds.extend({documentType:pe(ct)}),nt=us.extend({global:Fs(),local:Bs()}),en=W({header:li,state:nt,initialState:nt});function hi(i){return nt.safeParse(i).success}function fi(i){nt.parse(i)}function gi(i){return en.safeParse(i).success}function pi(i){en.parse(i)}const mi={name:"",nodes:[],icon:null},yi={listeners:[],triggers:[],sharingType:"private",availableOffline:!1},Lt=i=>({...$t(),global:{...mi,...i?.global},local:{...yi,...i?.local}}),tn=i=>{const e=fs(Lt,i);return e.header.documentType=ct,e.header.id=$e(),e},vi=(i,e)=>ls(i,e),wi=i=>hs(i,Zr),bi=i=>hi(i),Di=i=>{fi(i)},Si=i=>gi(i),Ei=i=>{pi(i)},Ii={actions:ii,reducer:Zr,documentModel:gs($t(),oi),utils:{fileExtension:$s,createState:Lt,createDocument:tn,loadFromInput:wi,saveToFileHandle:vi,isStateOfType:bi,assertIsStateOfType:Di,isDocumentOfType:Si,assertIsDocumentOfType:Ei}};var Ti={};class rn{#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"&&!As(e))throw new Error(`Invalid log level: ${JSON.stringify(e)}.
121
- 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?Ti.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 rn;let Ut="env",nn;ut.level=Ut;ut.errorHandler=nn;const fe=ut,Oo=i=>{Ut=i,ut.level=i},me=i=>{const e=new rn(i);return e.level=Ut,e.errorHandler=nn,e};class Ri extends Error{id;constructor(e,t){super(`Document model "${e}" not found`,{cause:t}),this.id=e}}class ie extends Error{status;operation;constructor(e,t,r,n){super(r,{cause:n??t}),this.status=e,this.operation=t,n instanceof Error&&(this.stack=n.stack)}}class Mi extends ie{constructor(e,t){super("CONFLICT",t,`Conflicting operation on index ${t.index}`,{existingOperation:e,newOperation:t})}}var ke;(function(i){i.ID="id",i.SLUG="slug"})(ke||(ke={}));class qe extends Error{documentId;constructor(e,t=ke.ID){super(`Document (${e}) uses ${t} that already exists`),this.documentId=e}}class we extends Error{documentId;constructor(e){super(`Document with id ${e} not found`),this.documentId=e}}class Oi extends Error{syncUnitId;constructor(e){super(`Sync unit ${JSON.stringify(e)} not found`),this.syncUnitId=e}}function ve(i){return i.header.documentType===ct}function st(i,e){const t=Object.keys(i).reduce((n,s)=>{const o=s,a=i[o];return n[o]=a?.at(-1)?.index??0,n},{}),r=e.find(n=>n.index<(t[n.action.scope]??0));if(r)throw new ie("ERROR",r,`Tried to add operation with index ${r.index} and document is at index ${t[r.action.scope]}`);return e.sort((n,s)=>n.index-s.index).reduce((n,s)=>{const o=n[s.action.scope]||[];return{...n,[s.action.scope]:[...o,s]}},i)}function _i(i,e){return new Date(i)<new Date(e)}function Ie(i){const e=i?.at(-1);return e?e.index+1:0}const lr=typeof MessageChannel>"u"?new Error("MessageChannel is not supported"):i=>{const e=new AbortController,t=e.signal,r=new MessageChannel;return r.port1.postMessage(null),r.port2.addEventListener("message",()=>{i(),r.port1.close(),r.port2.close()},{once:!0,signal:t}),r.port2.start(),()=>e.abort()},hr=(()=>{const i=typeof window=="object"&&window||typeof global=="object"&&global||typeof self=="object"&&self;if(!i)return new Error("No global object found");const e=i;if(!e.postMessage||!e.addEventListener||e.importScripts)return new Error("postMessage is not supported");let t=0;const r=new Map;function n(){return t===9007199254740991?0:++t}const s="com.usePostMessage"+Math.random();return e.addEventListener("message",o=>{const a=o;if(typeof a.data!="string"||a.source!==e||!a.data.startsWith(s))return;const d=a.data.split(":").at(1);if(d===void 0)return;const l=+d,y=r.get(l);y&&(y(),r.delete(l))},!1),o=>{const a=n();return r.set(a,o),e.postMessage(s+":"+a,{targetOrigin:"*"}),()=>{r.delete(a)}}})(),fr=typeof window<"u"?new Error("setImmediate is not supported on the browser"):typeof setImmediate>"u"?new Error("setImmediate is not supported"):i=>{const e=setImmediate(i);return()=>clearImmediate(e)},Ai=i=>{const e=setTimeout(i,0);return()=>clearTimeout(e)};function Bt(i){return fr instanceof Error?lr instanceof Error?hr instanceof Error?Ai(i):hr(i):lr(i):fr(i)}function xt(i,e=Bt){if(e instanceof Error)throw new Error("queueMethod is not supported",{cause:e});return new Promise((t,r)=>{e(()=>{i().then(t).catch(r)})})}class Ni{drive;processor;taskQueueMethod;transmitQueue;constructor(e,t,r){this.drive=e,this.processor=t,this.taskQueueMethod=r===void 0?Bt:r}async#e(e){const t=[],r=new Map,n=async s=>{const o=r.get(s);if(o)return o;const a={revisions:{[e.scope]:s},checkHashes:!1},d=await(e.documentId===e.driveId?this.drive.getDrive(e.driveId,a):this.drive.getDocument(e.documentId,a));return s<0?r.set(s,d.initialState[e.scope]):r.set(s,d.state[e.scope]),r.get(s)};for(const s of e.operations){const o=()=>n(s.index),a=await(this.taskQueueMethod?xt(o,this.taskQueueMethod):o()),d=()=>n(s.index-1),l=await(this.taskQueueMethod?xt(d,this.taskQueueMethod):d()),y={id:s.actionId,timestampUtcMs:s.timestampUtcMs,type:s.type,input:s.input,context:s.context,scope:e.scope};t.push({...s,id:s.id??Ve(e.documentId,e.scope,e.branch,s.actionId),state:a,previousState:l,action:y})}return t}async transmit(e,t){const r=async()=>{const n=[];for(const s of e){const o=await this.#e(s),a=await this.drive.getDocument(s.documentId),d=o.at(-1)?.state??a.initialState[s.scope];n.push({...s,documentType:a.header.documentType,operations:o,state:d,document:a})}try{return await this.processor.onStrands(n),e.map(({operations:s,...o})=>({...o,status:"SUCCESS",revision:Ie(s)}))}catch(s){return fe.error(s),e.map(({operations:o,...a})=>({...a,status:"ERROR",revision:o.at(0)?.index??0}))}};return this.transmitQueue=this.transmitQueue?.then(()=>r())??r(),this.transmitQueue}async disconnect(){await this.processor.onDisconnect()}}function sn(i){return{selectFrom:i.selectFrom.bind(i),selectNoFrom:i.selectNoFrom.bind(i),with:i.with.bind(i),withRecursive:i.withRecursive.bind(i),withSchema:e=>sn(i.withSchema(e))}}const gr=Symbol.for("ph.IS_RELATIONAL_DB_PROCESSOR");class Ci{_namespace;_filter;relationalDb;constructor(e,t,r){this._namespace=e,this._filter=t,this.relationalDb=r}static[gr]=!0;static is(e){let t=Object.getPrototypeOf(e);for(;t;){if(t.constructor?.[gr])return!0;t=Object.getPrototypeOf(t)}return!1}static getNamespace(e){return`${this.name}_${e.replaceAll("-","_")}`}static query(e,t){return t.queryNamespace(this.getNamespace(e))}get filter(){return this._filter}get namespace(){return this._namespace}get query(){return sn(this.relationalDb)}}function pr(i){return Ci.is(i)}class _o{listeners;drive;logger=me(["document-drive","processor-manager"]);processorsByDrive=new Map;idToFactory=new Map;identifierToListeners=new Map;constructor(e,t){this.listeners=e,this.drive=t}async registerFactory(e,t){this.logger.debug(`Registering factory '${e}'.`),this.idToFactory.set(e,t);const r=await this.drive.getDrives();for(const n of r)await this.createProcessors(n,e,t)}async unregisterFactory(e){const t=this.identifierToListeners.get(e)??[];for(const r of t)await this.listeners.removeListener(r.driveId,r.listenerId).catch(this.logger.error),r.transmitter?.disconnect&&await r.transmitter.disconnect();this.identifierToListeners.set(e,[])}async registerDrive(e){this.logger.debug(`Registering drive '${e}'.`);for(const[t,r]of this.idToFactory)await this.createProcessors(e,t,r)}async createProcessors(e,t,r){const n=await this.drive.getDrive(e);let s=this.identifierToListeners.get(t);s||(s=[],this.identifierToListeners.set(t,s));let o=this.processorsByDrive.get(e);o||(o=[],this.processorsByDrive.set(e,o));let a=[];try{a=await r(n.header)}catch(d){this.logger.error(`Error creating processors for drive ${e}:`,d);return}for(const{filter:d,processor:l}of a){const y=pr(l);if(y&&o.some(b=>pr(b.processor)&&b.processor.namespace===l.namespace)){this.logger.debug(`Processor with namespace '${l.namespace}' already registered for drive '${e}'.`);continue}y&&await l.initAndUpgrade();const f=$e(),w={driveId:e,listenerId:f,block:!1,system:!1,filter:d,callInfo:void 0,transmitter:new Ni(this.drive,l)};await this.listeners.setListener(e,w),s.push(w),o.push({filter:d,processor:l})}}}class xi{id;running=!1;deleted=!1;items=[];dependencies=new Array;constructor(e){this.id=e}async isRunning(){return this.running}async setRunning(e){this.running=e}async setDeleted(e){this.deleted=e}async isDeleted(){return this.deleted}async addJob(e){return this.items.push(e),Promise.resolve()}async getNextJob(){const e=this.items.shift();return Promise.resolve(e)}async amountOfJobs(){return Promise.resolve(this.items.length)}getId(){return this.id}async isBlocked(){return this.running||this.deleted||this.dependencies.length>0}async getJobs(){return this.items}async addDependency(e){this.dependencies.includes(e.jobId)||this.dependencies.push(e.jobId)}async removeDependency(e){const t=this.dependencies.indexOf(e.jobId);t>-1&&this.dependencies.splice(t,1)}}let on=()=>({emit(i,...e){for(let t=this.events[i]||[],r=0,n=t.length;r<n;r++)t[r](...e)},events:{},on(i,e){return(this.events[i]||=[]).push(e),()=>{this.events[i]=this.events[i]?.filter(t=>e!==t)}}});function Xe(i){return"documentType"in i}function an(i){return"operations"in i}function $i(i){return"actions"in i}class Pi{logger=me(["EventQueueManager"]);emitter=on();queues=new Map;globalQueue=new Array;isFindingJob=!1;maxWorkers;workers;runningJobs=new Array;timeout;delegate;onError;constructor(e=1,t=0){this.maxWorkers=e,this.workers=0,this.timeout=t}async init(e,t){this.delegate=e,this.onError=t;function r(n){return(async(...s)=>{try{await n(...s)}catch(o){throw o instanceof Error?o:new Error(JSON.stringify(o))}})}return this.emitter.on("jobAdded",r(async n=>{this.logger.verbose("Added job",n),await this.processNextJob()})),this.emitter.on("jobStarted",r(async n=>{this.logger.verbose("Started job",n.jobId),this.runningJobs.push(n),await this.processNextJob()})),this.emitter.on("jobCompleted",r(async(n,s)=>{this.logger.verbose("Completed job",n.jobId),await this.handleJobCompleted(n,s)})),this.emitter.on("jobFailed",r(async(n,s)=>{this.logger.error("Failed job",n,s),this.removeJob(n),t(s),await this.processNextJob()})),Promise.resolve()}async addJob(e){if(!this.delegate)throw new Error("No server delegate defined");const t=$e(),r=Xe(e),n=Xe(e)?void 0:an(e)?e.operations:e.actions;if(!r&&!n?.length)throw new Error("Job has no operations or actions: "+JSON.stringify(e));const s=n?.at(0),o=s?"action"in s?s.action.scope:s.scope:"global";if(n?.find(l=>("action"in l?l.action.scope:l.scope)!==o))throw new Error("Job has actions with different scopes");const a=this.getQueue(e.documentId,o);if(!Xe(e)&&await a.isDeleted())throw new Error("Job has operations for deleted document");const d=Object.freeze({jobId:t,...e});return await a.addJob(d),this.globalQueue.push({jobId:t,documentId:e.documentId,scope:o,timestampUtcMs:new Date().toUTCString()}),this.emit("jobAdded",d),t}getQueue(e,t){let r=this.queues.get(e);r||(r=new Map,this.queues.set(e,r));let n=r.get(t);return n||(n=new xi(t),r.set(t,n)),n}getDocumentQueues(e){return this.queues.get(e)}removeQueue(e,t){const n=this.queues.get(e)?.delete(t);return n&&this.emit("queueRemoved",{documentId:e,scope:t}),n}removeDocumentQueues(e){this.queues.get(e)?.keys().forEach(r=>{this.removeQueue(e,r)})}removeJob(e){const t=this.runningJobs.findIndex(n=>n.jobId===e.jobId);t===-1&&this.logger.warn("Running job not found",e.jobId),this.runningJobs.splice(t,1);const r=this.globalQueue.findIndex(n=>n.jobId===e.jobId);r===-1&&this.logger.warn("Job not found on global queue",e.jobId),this.globalQueue.splice(r,1)}async handleJobCompleted(e,t){return this.removeJob(e),this.processNextJob()}isBusy(){return this.workers>=this.maxWorkers}async processNextJob(){if(this.isFindingJob)return;if(!this.delegate)throw new Error("No server delegate defined");if(this.globalQueue.length===0||this.isBusy())return;this.isFindingJob=!0,this.workers++;let e,t;try{const r=await this.findNextJob();e=r?.queue,t=r?.job}catch(r){fe.error("Error finding next job",r)}if(!e||!t){this.workers--,this.isFindingJob=!1;return}try{await e.setRunning(!0),this.isFindingJob=!1,this.emit("jobStarted",t);const r=await this.delegate.processJob(t);this.workers--,await e.setRunning(!1),this.emit("jobCompleted",t,r)}catch(r){fe.error("Job failed",r),this.workers--,this.isFindingJob=!1,await e.setRunning(!1),this.emit("jobFailed",t,r instanceof Error?r:new Error(JSON.stringify(r)))}}async findNextJob(){const e=new Set;for(const t of this.globalQueue){const r=this.getQueue(t.documentId,t.scope),n=r.getId();if(e.has(n))continue;if(await r.isBlocked()){e.add(r.getId());continue}const s=await r.getNextJob();if(s?.jobId!==t.jobId){fe.warn("Queue has different job waiting to be picked up"),fe.error(t,s);continue}return{queue:r,job:s}}}emit(e,...t){this.emitter.emit(e,...t)}on(e,t){return this.emitter.on(e,t)}}class dt extends Error{}class Re extends dt{constructor(e){super(`Read drive ${e} not found.`)}}class Li extends dt{constructor(e){super(`Read drive with slug ${e} not found.`)}}class mr extends dt{constructor(e,t){super(`Document with id ${t} not found on read drive ${e}.`)}}const Ft=JSON,Ui=i=>i.toUpperCase(),Bi=i=>{const e={};return i.forEach((t,r)=>{e[r]=t}),e},Fi=(i,e,t)=>i.document?i:{document:i,variables:e,requestHeaders:t,signal:void 0},ki=(i,e,t)=>i.query?i:{query:i,variables:e,requestHeaders:t,signal:void 0},qi=(i,e)=>i.documents?i:{documents:i,requestHeaders:e,signal:void 0},yr=i=>{let e;const t=i.definitions.filter(r=>r.kind==="OperationDefinition");return t.length===1&&(e=t[0]?.name?.value),e},Et=i=>{if(typeof i=="string"){let t;try{const r=Ss(i);t=yr(r)}catch{}return{query:i,operationName:t}}const e=yr(i);return{query:Es(i),operationName:e}};class xe extends Error{constructor(e,t){const r=`${xe.extractMessage(e)}: ${JSON.stringify({response:e,request:t})}`;super(r),Object.setPrototypeOf(this,xe.prototype),this.response=e,this.request=t,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,xe)}static extractMessage(e){return e.errors?.[0]?.message??`GraphQL Error (Code: ${e.status})`}}var Ke={exports:{}},vr;function zi(){return vr||(vr=1,(function(i,e){var t=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Ee<"u"&&Ee,r=(function(){function s(){this.fetch=!1,this.DOMException=t.DOMException}return s.prototype=t,new s})();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof Ee<"u"&&Ee||{},d={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function l(D){return D&&DataView.prototype.isPrototypeOf(D)}if(d.arrayBuffer)var y=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],f=ArrayBuffer.isView||function(D){return D&&y.indexOf(Object.prototype.toString.call(D))>-1};function w(D){if(typeof D!="string"&&(D=String(D)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(D)||D==="")throw new TypeError('Invalid character in header field name: "'+D+'"');return D.toLowerCase()}function b(D){return typeof D!="string"&&(D=String(D)),D}function p(D){var R={next:function(){var B=D.shift();return{done:B===void 0,value:B}}};return d.iterable&&(R[Symbol.iterator]=function(){return R}),R}function E(D){this.map={},D instanceof E?D.forEach(function(R,B){this.append(B,R)},this):Array.isArray(D)?D.forEach(function(R){if(R.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+R.length);this.append(R[0],R[1])},this):D&&Object.getOwnPropertyNames(D).forEach(function(R){this.append(R,D[R])},this)}E.prototype.append=function(D,R){D=w(D),R=b(R);var B=this.map[D];this.map[D]=B?B+", "+R:R},E.prototype.delete=function(D){delete this.map[w(D)]},E.prototype.get=function(D){return D=w(D),this.has(D)?this.map[D]:null},E.prototype.has=function(D){return this.map.hasOwnProperty(w(D))},E.prototype.set=function(D,R){this.map[w(D)]=b(R)},E.prototype.forEach=function(D,R){for(var B in this.map)this.map.hasOwnProperty(B)&&D.call(R,this.map[B],B,this)},E.prototype.keys=function(){var D=[];return this.forEach(function(R,B){D.push(B)}),p(D)},E.prototype.values=function(){var D=[];return this.forEach(function(R){D.push(R)}),p(D)},E.prototype.entries=function(){var D=[];return this.forEach(function(R,B){D.push([B,R])}),p(D)},d.iterable&&(E.prototype[Symbol.iterator]=E.prototype.entries);function _(D){if(!D._noBody){if(D.bodyUsed)return Promise.reject(new TypeError("Already read"));D.bodyUsed=!0}}function A(D){return new Promise(function(R,B){D.onload=function(){R(D.result)},D.onerror=function(){B(D.error)}})}function C(D){var R=new FileReader,B=A(R);return R.readAsArrayBuffer(D),B}function U(D){var R=new FileReader,B=A(R),G=/charset=([A-Za-z0-9_-]+)/.exec(D.type),V=G?G[1]:"utf-8";return R.readAsText(D,V),B}function F(D){for(var R=new Uint8Array(D),B=new Array(R.length),G=0;G<R.length;G++)B[G]=String.fromCharCode(R[G]);return B.join("")}function I(D){if(D.slice)return D.slice(0);var R=new Uint8Array(D.byteLength);return R.set(new Uint8Array(D)),R.buffer}function P(){return this.bodyUsed=!1,this._initBody=function(D){this.bodyUsed=this.bodyUsed,this._bodyInit=D,D?typeof D=="string"?this._bodyText=D:d.blob&&Blob.prototype.isPrototypeOf(D)?this._bodyBlob=D:d.formData&&FormData.prototype.isPrototypeOf(D)?this._bodyFormData=D:d.searchParams&&URLSearchParams.prototype.isPrototypeOf(D)?this._bodyText=D.toString():d.arrayBuffer&&d.blob&&l(D)?(this._bodyArrayBuffer=I(D.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):d.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(D)||f(D))?this._bodyArrayBuffer=I(D):this._bodyText=D=Object.prototype.toString.call(D):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof D=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):d.searchParams&&URLSearchParams.prototype.isPrototypeOf(D)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},d.blob&&(this.blob=function(){var D=_(this);if(D)return D;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var D=_(this);return D||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(d.blob)return this.blob().then(C);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var D=_(this);if(D)return D;if(this._bodyBlob)return U(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(F(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},d.formData&&(this.formData=function(){return this.text().then(K)}),this.json=function(){return this.text().then(JSON.parse)},this}var L=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function j(D){var R=D.toUpperCase();return L.indexOf(R)>-1?R:D}function H(D,R){if(!(this instanceof H))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');R=R||{};var B=R.body;if(D instanceof H){if(D.bodyUsed)throw new TypeError("Already read");this.url=D.url,this.credentials=D.credentials,R.headers||(this.headers=new E(D.headers)),this.method=D.method,this.mode=D.mode,this.signal=D.signal,!B&&D._bodyInit!=null&&(B=D._bodyInit,D.bodyUsed=!0)}else this.url=String(D);if(this.credentials=R.credentials||this.credentials||"same-origin",(R.headers||!this.headers)&&(this.headers=new E(R.headers)),this.method=j(R.method||this.method||"GET"),this.mode=R.mode||this.mode||null,this.signal=R.signal||this.signal||(function(){if("AbortController"in a){var z=new AbortController;return z.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&B)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(B),(this.method==="GET"||this.method==="HEAD")&&(R.cache==="no-store"||R.cache==="no-cache")){var G=/([?&])_=[^&]*/;if(G.test(this.url))this.url=this.url.replace(G,"$1_="+new Date().getTime());else{var V=/\?/;this.url+=(V.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}H.prototype.clone=function(){return new H(this,{body:this._bodyInit})};function K(D){var R=new FormData;return D.trim().split("&").forEach(function(B){if(B){var G=B.split("="),V=G.shift().replace(/\+/g," "),z=G.join("=").replace(/\+/g," ");R.append(decodeURIComponent(V),decodeURIComponent(z))}}),R}function Z(D){var R=new E,B=D.replace(/\r?\n[\t ]+/g," ");return B.split("\r").map(function(G){return G.indexOf(`
121
+ }`,template:"",reducer:"",errors:[],examples:[],scope:"local"}]}]}]},ut="powerhouse/document-drive",Se={setDriveNameOperation(i,e,t){i.name=e.input.name},setDriveIconOperation(i,e,t){i.icon=e.input.icon},setSharingTypeOperation(i,e,t){i.sharingType=e.input.type},setAvailableOfflineOperation(i,e,t){i.availableOffline=e.input.availableOffline},addListenerOperation(i,e,t){if(i.listeners.find(r=>r.listenerId===e.input.listener.listenerId))throw new Error(`A listener with Id: ${e.input.listener.listenerId} already exists`);i.listeners.push(e.input.listener)},removeListenerOperation(i,e,t){i.listeners=i.listeners.filter(r=>r.listenerId!==e.input.listenerId)},addTriggerOperation(i,e,t){if(i.triggers.find(r=>r.id===e.input.trigger.id))throw new Error(`A trigger with Id: ${e.input.trigger.id} already exists`);i.triggers.push(e.input.trigger)},removeTriggerOperation(i,e,t){i.triggers=i.triggers.filter(r=>r.id!==e.input.triggerId)}};function dr(i){return i.kind==="file"}function ci(i){return i.kind==="folder"}function rt(i,e){const t=e.filter(n=>n.parentFolder===i.id),r=t.map(n=>rt(n,e));return[...t,...r.flat()]}function Oo(i,e,t){const r=t.find(d=>d.id===i.srcId);if(!r)throw new Error(`Node with id ${i.srcId} not found`);const n=[{...r,name:i.targetName||r.name,parentFolder:i.targetParentFolder||null},...rt(r,t)],s={};i.targetParentFolder&&(s[i.targetParentFolder]=i.targetParentFolder);const o=d=>{let l=s[d.id];if(!l){const y=d.id;l=e(d),s[y]=l}return l};return n.map(d=>({srcId:d.id,targetId:o(d),targetName:d.name,targetParentFolder:d.parentFolder?s[d.parentFolder]:null}))}function ui(i,e){let t=0;const r=new RegExp(`^${di(e)} \\(copy\\)(?: (\\d+))?$`);for(const n of i){const s=n.match(r);if(s){const o=s[1]?parseInt(s[1],10):1;o>t&&(t=o)}}return t+1}function di(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ne(i){const{nodes:e,targetParentFolder:t,srcName:r}=i,n=e.filter(a=>t===""?a.parentFolder===null:a.parentFolder===t).map(a=>a.name);return n.includes(r)?`${r} (copy) ${ui(n,r)}`:r}const Qe=i=>/^[a-zA-Z0-9-_.\s()]+$/.test(i),Te={addFileOperation(i,e,t){if(i.nodes.find(s=>s.id===e.input.id))throw new Error(`Node with id ${e.input.id} already exists!`);if(!Qe(e.input.name))throw new Error(`Invalid name: '${e.input.name}'. Names must be valid URL characters.`);const r=Ne({nodes:i.nodes,srcName:e.input.name,targetParentFolder:e.input.parentFolder||null}),n={id:e.input.id,name:r,kind:"file",parentFolder:e.input.parentFolder??null,documentType:e.input.documentType};i.nodes.push(n),t?.({type:"CREATE_CHILD_DOCUMENT",input:{id:e.input.id,documentType:e.input.documentType}})},addFolderOperation(i,e){if(i.nodes.find(r=>r.id===e.input.id))throw new Error(`Node with id ${e.input.id} already exists!`);if(!Qe(e.input.name))throw new Error(`Invalid name: '${e.input.name}'. Names must be valid URL characters.`);const t=Ne({nodes:i.nodes,srcName:e.input.name,targetParentFolder:e.input.parentFolder||null});i.nodes.push({...e.input,name:t,kind:"folder",parentFolder:e.input.parentFolder??null})},deleteNodeOperation(i,e,t){const r=i.nodes.find(s=>s.id===e.input.id);if(!r)throw new Error(`Node with id ${e.input.id} not found`);const n=rt(r,i.nodes);i.nodes=i.nodes.filter(s=>s.id!==e.input.id&&!n.find(o=>o.id===s.id)),[r,...n].filter(s=>dr(s)).forEach(s=>{t?.({type:"DELETE_CHILD_DOCUMENT",input:{id:s.id}})})},updateFileOperation(i,e){if(e.input.name&&!Qe(e.input.name))throw new Error(`Invalid name: '${e.input.name}'. Names must be valid URL characters.`);i.nodes=i.nodes.map(t=>t.id===e.input.id?{...t,name:Ne({nodes:i.nodes,srcName:e.input.name??t.name,targetParentFolder:e.input.parentFolder||null}),documentType:e.input.documentType??t.documentType}:t)},updateNodeOperation(i,e){if(e.input.name&&!Qe(e.input.name))throw new Error(`Invalid name: '${e.input.name}'. Names must be valid URL characters.`);i.nodes=i.nodes.map(t=>t.id===e.input.id?{...t,name:Ne({nodes:i.nodes,srcName:e.input.name??t.name,targetParentFolder:e.input.parentFolder||null}),parentFolder:e.input.parentFolder===null?null:t.parentFolder}:t)},copyNodeOperation(i,e,t){const r=i.nodes.find(d=>d.id===e.input.srcId);if(!r)throw new Error(`Node with id ${e.input.srcId} not found`);if(i.nodes.find(d=>d.id===e.input.targetId))throw new Error(`Node with id ${e.input.targetId} already exists`);const s=Ne({nodes:i.nodes,srcName:e.input.targetName||r.name,targetParentFolder:e.input.targetParentFolder||null}),o={...r,id:e.input.targetId,slug:e.input.targetId,name:s,parentFolder:e.input.targetParentFolder||null};i.nodes.push(o),dr(o)&&t?.({type:"COPY_CHILD_DOCUMENT",input:{id:e.input.srcId,newId:e.input.targetId}})},moveNodeOperation(i,e){if(e.input.srcFolder===e.input.targetParentFolder)throw new Error("Circular Reference Error: Attempting to move a node to its current parent folder");const t=i.nodes.find(n=>n.id===e.input.srcFolder);if(!t)throw new Error(`Node with id ${e.input.srcFolder} not found`);const r=Ne({nodes:i.nodes,srcName:t.name,targetParentFolder:e.input.targetParentFolder||null});if(ci(t)&&rt(t,i.nodes).find(s=>s.id===e.input.targetParentFolder))throw new Error("Circular Reference Error: Cannot move a folder to one of its descendants");i.nodes=i.nodes.map(n=>n.id===e.input.srcFolder?{...n,name:r,parentFolder:e.input.targetParentFolder||null}:n)}},li=(i,e,t)=>{if(cs(e))return i;const r=e;switch(r.type){case"ADD_FILE":Pr().parse(r.input),Te.addFileOperation(i[r.scope],e,t);break;case"ADD_FOLDER":Lr().parse(r.input),Te.addFolderOperation(i[r.scope],e,t);break;case"DELETE_NODE":kr().parse(r.input),Te.deleteNodeOperation(i[r.scope],e,t);break;case"UPDATE_FILE":Vr().parse(r.input),Te.updateFileOperation(i[r.scope],e,t);break;case"UPDATE_NODE":Wr().parse(r.input),Te.updateNodeOperation(i[r.scope],e,t);break;case"COPY_NODE":Fr().parse(r.input),Te.copyNodeOperation(i[r.scope],e,t);break;case"MOVE_NODE":zr().parse(r.input),Te.moveNodeOperation(i[r.scope],e,t);break;case"SET_DRIVE_NAME":Yr().parse(r.input),Se.setDriveNameOperation(i[r.scope],e,t);break;case"SET_DRIVE_ICON":Jr().parse(r.input),Se.setDriveIconOperation(i[r.scope],e,t);break;case"SET_SHARING_TYPE":Qr().parse(r.input),Se.setSharingTypeOperation(i[r.scope],e,t);break;case"SET_AVAILABLE_OFFLINE":Gr().parse(r.input),Se.setAvailableOfflineOperation(i[r.scope],e,t);break;case"ADD_LISTENER":Ur().parse(r.input),Se.addListenerOperation(i[r.scope],e,t);break;case"REMOVE_LISTENER":jr().parse(r.input),Se.removeListenerOperation(i[r.scope],e,t);break;case"ADD_TRIGGER":Br().parse(r.input),Se.addTriggerOperation(i[r.scope],e,t);break;case"REMOVE_TRIGGER":Hr().parse(r.input),Se.removeTriggerOperation(i[r.scope],e,t);break;default:return i}},tn=as(li),hi=ds.extend({documentType:pe(ut)}),nt=us.extend({global:ks(),local:Fs()}),rn=W({header:hi,state:nt,initialState:nt});function fi(i){return nt.safeParse(i).success}function gi(i){nt.parse(i)}function pi(i){return rn.safeParse(i).success}function mi(i){rn.parse(i)}const yi={name:"",nodes:[],icon:null},vi={listeners:[],triggers:[],sharingType:"private",availableOffline:!1},Ut=i=>({...$t(),global:{...yi,...i?.global},local:{...vi,...i?.local}}),nn=i=>{const e=fs(Ut,i);return e.header.documentType=ut,e.header.id=$e(),e},wi=(i,e)=>ls(i,e),bi=i=>hs(i,tn),Di=i=>fi(i),Si=i=>{gi(i)},Ei=i=>pi(i),Ii=i=>{mi(i)},Ti={actions:oi,reducer:tn,documentModel:gs($t(),ai),utils:{fileExtension:Ps,createState:Ut,createDocument:nn,loadFromInput:bi,saveToFileHandle:wi,isStateOfType:Di,assertIsStateOfType:Si,isDocumentOfType:Ei,assertIsDocumentOfType:Ii}};class Ri extends Error{id;constructor(e,t){super(`Document model "${e}" not found`,{cause:t}),this.id=e}}class ie extends Error{status;operation;constructor(e,t,r,n){super(r,{cause:n??t}),this.status=e,this.operation=t,n instanceof Error&&(this.stack=n.stack)}}class Mi extends ie{constructor(e,t){super("CONFLICT",t,`Conflicting operation on index ${t.index}`,{existingOperation:e,newOperation:t})}}var ke;(function(i){i.ID="id",i.SLUG="slug"})(ke||(ke={}));class qe extends Error{documentId;constructor(e,t=ke.ID){super(`Document (${e}) uses ${t} that already exists`),this.documentId=e}}class we extends Error{documentId;constructor(e){super(`Document with id ${e} not found`),this.documentId=e}}class Oi extends Error{syncUnitId;constructor(e){super(`Sync unit ${JSON.stringify(e)} not found`),this.syncUnitId=e}}function ve(i){return i.header.documentType===ut}function st(i,e){const t=Object.keys(i).reduce((n,s)=>{const o=s,a=i[o];return n[o]=a?.at(-1)?.index??0,n},{}),r=e.find(n=>n.index<(t[n.action.scope]??0));if(r)throw new ie("ERROR",r,`Tried to add operation with index ${r.index} and document is at index ${t[r.action.scope]}`);return e.sort((n,s)=>n.index-s.index).reduce((n,s)=>{const o=n[s.action.scope]||[];return{...n,[s.action.scope]:[...o,s]}},i)}function _i(i,e){return new Date(i)<new Date(e)}function Ie(i){const e=i?.at(-1);return e?e.index+1:0}const lr=typeof MessageChannel>"u"?new Error("MessageChannel is not supported"):i=>{const e=new AbortController,t=e.signal,r=new MessageChannel;return r.port1.postMessage(null),r.port2.addEventListener("message",()=>{i(),r.port1.close(),r.port2.close()},{once:!0,signal:t}),r.port2.start(),()=>e.abort()},hr=(()=>{const i=typeof window=="object"&&window||typeof global=="object"&&global||typeof self=="object"&&self;if(!i)return new Error("No global object found");const e=i;if(!e.postMessage||!e.addEventListener||e.importScripts)return new Error("postMessage is not supported");let t=0;const r=new Map;function n(){return t===9007199254740991?0:++t}const s="com.usePostMessage"+Math.random();return e.addEventListener("message",o=>{const a=o;if(typeof a.data!="string"||a.source!==e||!a.data.startsWith(s))return;const d=a.data.split(":").at(1);if(d===void 0)return;const l=+d,y=r.get(l);y&&(y(),r.delete(l))},!1),o=>{const a=n();return r.set(a,o),e.postMessage(s+":"+a,{targetOrigin:"*"}),()=>{r.delete(a)}}})(),fr=typeof window<"u"?new Error("setImmediate is not supported on the browser"):typeof setImmediate>"u"?new Error("setImmediate is not supported"):i=>{const e=setImmediate(i);return()=>clearImmediate(e)},Ai=i=>{const e=setTimeout(i,0);return()=>clearTimeout(e)};function Bt(i){return fr instanceof Error?lr instanceof Error?hr instanceof Error?Ai(i):hr(i):lr(i):fr(i)}function xt(i,e=Bt){if(e instanceof Error)throw new Error("queueMethod is not supported",{cause:e});return new Promise((t,r)=>{e(()=>{i().then(t).catch(r)})})}class Ni{drive;processor;taskQueueMethod;transmitQueue;constructor(e,t,r){this.drive=e,this.processor=t,this.taskQueueMethod=r===void 0?Bt:r}async#e(e){const t=[],r=new Map,n=async s=>{const o=r.get(s);if(o)return o;const a={revisions:{[e.scope]:s},checkHashes:!1},d=await(e.documentId===e.driveId?this.drive.getDrive(e.driveId,a):this.drive.getDocument(e.documentId,a));return s<0?r.set(s,d.initialState[e.scope]):r.set(s,d.state[e.scope]),r.get(s)};for(const s of e.operations){const o=()=>n(s.index),a=await(this.taskQueueMethod?xt(o,this.taskQueueMethod):o()),d=()=>n(s.index-1),l=await(this.taskQueueMethod?xt(d,this.taskQueueMethod):d()),y={id:s.actionId,timestampUtcMs:s.timestampUtcMs,type:s.type,input:s.input,context:s.context,scope:e.scope};t.push({...s,id:s.id??Ve(e.documentId,e.scope,e.branch,s.actionId),state:a,previousState:l,action:y})}return t}async transmit(e,t){const r=async()=>{const n=[];for(const s of e){const o=await this.#e(s),a=await this.drive.getDocument(s.documentId),d=o.at(-1)?.state??a.initialState[s.scope];n.push({...s,documentType:a.header.documentType,operations:o,state:d,document:a})}try{return await this.processor.onStrands(n),e.map(({operations:s,...o})=>({...o,status:"SUCCESS",revision:Ie(s)}))}catch(s){return fe.error(s),e.map(({operations:o,...a})=>({...a,status:"ERROR",revision:o.at(0)?.index??0}))}};return this.transmitQueue=this.transmitQueue?.then(()=>r())??r(),this.transmitQueue}async disconnect(){await this.processor.onDisconnect()}}function sn(i){return{selectFrom:i.selectFrom.bind(i),selectNoFrom:i.selectNoFrom.bind(i),with:i.with.bind(i),withRecursive:i.withRecursive.bind(i),withSchema:e=>sn(i.withSchema(e))}}const gr=Symbol.for("ph.IS_RELATIONAL_DB_PROCESSOR");class Ci{_namespace;_filter;relationalDb;constructor(e,t,r){this._namespace=e,this._filter=t,this.relationalDb=r}static[gr]=!0;static is(e){let t=Object.getPrototypeOf(e);for(;t;){if(t.constructor?.[gr])return!0;t=Object.getPrototypeOf(t)}return!1}static getNamespace(e){return`${this.name}_${e.replaceAll("-","_")}`}static query(e,t){return t.queryNamespace(this.getNamespace(e))}get filter(){return this._filter}get namespace(){return this._namespace}get query(){return sn(this.relationalDb)}}function pr(i){return Ci.is(i)}class _o{listeners;drive;logger=me(["document-drive","processor-manager"]);processorsByDrive=new Map;idToFactory=new Map;identifierToListeners=new Map;constructor(e,t){this.listeners=e,this.drive=t}async registerFactory(e,t){this.logger.debug(`Registering factory '${e}'.`),this.idToFactory.set(e,t);const r=await this.drive.getDrives();for(const n of r)await this.createProcessors(n,e,t)}async unregisterFactory(e){const t=this.identifierToListeners.get(e)??[];for(const r of t)await this.listeners.removeListener(r.driveId,r.listenerId).catch(this.logger.error),r.transmitter?.disconnect&&await r.transmitter.disconnect();this.identifierToListeners.set(e,[])}async registerDrive(e){this.logger.debug(`Registering drive '${e}'.`);for(const[t,r]of this.idToFactory)await this.createProcessors(e,t,r)}async createProcessors(e,t,r){const n=await this.drive.getDrive(e);let s=this.identifierToListeners.get(t);s||(s=[],this.identifierToListeners.set(t,s));let o=this.processorsByDrive.get(e);o||(o=[],this.processorsByDrive.set(e,o));let a=[];try{a=await r(n.header)}catch(d){this.logger.error(`Error creating processors for drive ${e}:`,d);return}for(const{filter:d,processor:l}of a){const y=pr(l);if(y&&o.some(b=>pr(b.processor)&&b.processor.namespace===l.namespace)){this.logger.debug(`Processor with namespace '${l.namespace}' already registered for drive '${e}'.`);continue}y&&await l.initAndUpgrade();const f=$e(),w={driveId:e,listenerId:f,block:!1,system:!1,filter:d,callInfo:void 0,transmitter:new Ni(this.drive,l)};await this.listeners.setListener(e,w),s.push(w),o.push({filter:d,processor:l})}}}class xi{id;running=!1;deleted=!1;items=[];dependencies=new Array;constructor(e){this.id=e}async isRunning(){return this.running}async setRunning(e){this.running=e}async setDeleted(e){this.deleted=e}async isDeleted(){return this.deleted}async addJob(e){return this.items.push(e),Promise.resolve()}async getNextJob(){const e=this.items.shift();return Promise.resolve(e)}async amountOfJobs(){return Promise.resolve(this.items.length)}getId(){return this.id}async isBlocked(){return this.running||this.deleted||this.dependencies.length>0}async getJobs(){return this.items}async addDependency(e){this.dependencies.includes(e.jobId)||this.dependencies.push(e.jobId)}async removeDependency(e){const t=this.dependencies.indexOf(e.jobId);t>-1&&this.dependencies.splice(t,1)}}let on=()=>({emit(i,...e){for(let t=this.events[i]||[],r=0,n=t.length;r<n;r++)t[r](...e)},events:{},on(i,e){return(this.events[i]||=[]).push(e),()=>{this.events[i]=this.events[i]?.filter(t=>e!==t)}}});function Xe(i){return"documentType"in i}function an(i){return"operations"in i}function $i(i){return"actions"in i}class Pi{logger=me(["EventQueueManager"]);emitter=on();queues=new Map;globalQueue=new Array;isFindingJob=!1;maxWorkers;workers;runningJobs=new Array;timeout;delegate;onError;constructor(e=1,t=0){this.maxWorkers=e,this.workers=0,this.timeout=t}async init(e,t){this.delegate=e,this.onError=t;function r(n){return(async(...s)=>{try{await n(...s)}catch(o){throw o instanceof Error?o:new Error(JSON.stringify(o))}})}return this.emitter.on("jobAdded",r(async n=>{this.logger.verbose("Added job",n),await this.processNextJob()})),this.emitter.on("jobStarted",r(async n=>{this.logger.verbose("Started job",n.jobId),this.runningJobs.push(n),await this.processNextJob()})),this.emitter.on("jobCompleted",r(async(n,s)=>{this.logger.verbose("Completed job",n.jobId),await this.handleJobCompleted(n,s)})),this.emitter.on("jobFailed",r(async(n,s)=>{this.logger.error("Failed job",n,s),this.removeJob(n),t(s),await this.processNextJob()})),Promise.resolve()}async addJob(e){if(!this.delegate)throw new Error("No server delegate defined");const t=$e(),r=Xe(e),n=Xe(e)?void 0:an(e)?e.operations:e.actions;if(!r&&!n?.length)throw new Error("Job has no operations or actions: "+JSON.stringify(e));const s=n?.at(0),o=s?"action"in s?s.action.scope:s.scope:"global";if(n?.find(l=>("action"in l?l.action.scope:l.scope)!==o))throw new Error("Job has actions with different scopes");const a=this.getQueue(e.documentId,o);if(!Xe(e)&&await a.isDeleted())throw new Error("Job has operations for deleted document");const d=Object.freeze({jobId:t,...e});return await a.addJob(d),this.globalQueue.push({jobId:t,documentId:e.documentId,scope:o,timestampUtcMs:new Date().toUTCString()}),this.emit("jobAdded",d),t}getQueue(e,t){let r=this.queues.get(e);r||(r=new Map,this.queues.set(e,r));let n=r.get(t);return n||(n=new xi(t),r.set(t,n)),n}getDocumentQueues(e){return this.queues.get(e)}removeQueue(e,t){const n=this.queues.get(e)?.delete(t);return n&&this.emit("queueRemoved",{documentId:e,scope:t}),n}removeDocumentQueues(e){this.queues.get(e)?.keys().forEach(r=>{this.removeQueue(e,r)})}removeJob(e){const t=this.runningJobs.findIndex(n=>n.jobId===e.jobId);t===-1&&this.logger.warn("Running job not found",e.jobId),this.runningJobs.splice(t,1);const r=this.globalQueue.findIndex(n=>n.jobId===e.jobId);r===-1&&this.logger.warn("Job not found on global queue",e.jobId),this.globalQueue.splice(r,1)}async handleJobCompleted(e,t){return this.removeJob(e),this.processNextJob()}isBusy(){return this.workers>=this.maxWorkers}async processNextJob(){if(this.isFindingJob)return;if(!this.delegate)throw new Error("No server delegate defined");if(this.globalQueue.length===0||this.isBusy())return;this.isFindingJob=!0,this.workers++;let e,t;try{const r=await this.findNextJob();e=r?.queue,t=r?.job}catch(r){fe.error("Error finding next job",r)}if(!e||!t){this.workers--,this.isFindingJob=!1;return}try{await e.setRunning(!0),this.isFindingJob=!1,this.emit("jobStarted",t);const r=await this.delegate.processJob(t);this.workers--,await e.setRunning(!1),this.emit("jobCompleted",t,r)}catch(r){fe.error("Job failed",r),this.workers--,this.isFindingJob=!1,await e.setRunning(!1),this.emit("jobFailed",t,r instanceof Error?r:new Error(JSON.stringify(r)))}}async findNextJob(){const e=new Set;for(const t of this.globalQueue){const r=this.getQueue(t.documentId,t.scope),n=r.getId();if(e.has(n))continue;if(await r.isBlocked()){e.add(r.getId());continue}const s=await r.getNextJob();if(s?.jobId!==t.jobId){fe.warn("Queue has different job waiting to be picked up"),fe.error(t,s);continue}return{queue:r,job:s}}}emit(e,...t){this.emitter.emit(e,...t)}on(e,t){return this.emitter.on(e,t)}}class dt extends Error{}class Re extends dt{constructor(e){super(`Read drive ${e} not found.`)}}class Li extends dt{constructor(e){super(`Read drive with slug ${e} not found.`)}}class mr extends dt{constructor(e,t){super(`Document with id ${t} not found on read drive ${e}.`)}}const Ft=JSON,Ui=i=>i.toUpperCase(),Bi=i=>{const e={};return i.forEach((t,r)=>{e[r]=t}),e},Fi=(i,e,t)=>i.document?i:{document:i,variables:e,requestHeaders:t,signal:void 0},ki=(i,e,t)=>i.query?i:{query:i,variables:e,requestHeaders:t,signal:void 0},qi=(i,e)=>i.documents?i:{documents:i,requestHeaders:e,signal:void 0},yr=i=>{let e;const t=i.definitions.filter(r=>r.kind==="OperationDefinition");return t.length===1&&(e=t[0]?.name?.value),e},Et=i=>{if(typeof i=="string"){let t;try{const r=Ss(i);t=yr(r)}catch{}return{query:i,operationName:t}}const e=yr(i);return{query:Es(i),operationName:e}};class xe extends Error{constructor(e,t){const r=`${xe.extractMessage(e)}: ${JSON.stringify({response:e,request:t})}`;super(r),Object.setPrototypeOf(this,xe.prototype),this.response=e,this.request=t,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,xe)}static extractMessage(e){return e.errors?.[0]?.message??`GraphQL Error (Code: ${e.status})`}}var Ke={exports:{}},vr;function zi(){return vr||(vr=1,(function(i,e){var t=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof Ee<"u"&&Ee,r=(function(){function s(){this.fetch=!1,this.DOMException=t.DOMException}return s.prototype=t,new s})();(function(s){(function(o){var a=typeof s<"u"&&s||typeof self<"u"&&self||typeof Ee<"u"&&Ee||{},d={searchParams:"URLSearchParams"in a,iterable:"Symbol"in a&&"iterator"in Symbol,blob:"FileReader"in a&&"Blob"in a&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in a,arrayBuffer:"ArrayBuffer"in a};function l(D){return D&&DataView.prototype.isPrototypeOf(D)}if(d.arrayBuffer)var y=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],f=ArrayBuffer.isView||function(D){return D&&y.indexOf(Object.prototype.toString.call(D))>-1};function w(D){if(typeof D!="string"&&(D=String(D)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(D)||D==="")throw new TypeError('Invalid character in header field name: "'+D+'"');return D.toLowerCase()}function b(D){return typeof D!="string"&&(D=String(D)),D}function p(D){var R={next:function(){var B=D.shift();return{done:B===void 0,value:B}}};return d.iterable&&(R[Symbol.iterator]=function(){return R}),R}function E(D){this.map={},D instanceof E?D.forEach(function(R,B){this.append(B,R)},this):Array.isArray(D)?D.forEach(function(R){if(R.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+R.length);this.append(R[0],R[1])},this):D&&Object.getOwnPropertyNames(D).forEach(function(R){this.append(R,D[R])},this)}E.prototype.append=function(D,R){D=w(D),R=b(R);var B=this.map[D];this.map[D]=B?B+", "+R:R},E.prototype.delete=function(D){delete this.map[w(D)]},E.prototype.get=function(D){return D=w(D),this.has(D)?this.map[D]:null},E.prototype.has=function(D){return this.map.hasOwnProperty(w(D))},E.prototype.set=function(D,R){this.map[w(D)]=b(R)},E.prototype.forEach=function(D,R){for(var B in this.map)this.map.hasOwnProperty(B)&&D.call(R,this.map[B],B,this)},E.prototype.keys=function(){var D=[];return this.forEach(function(R,B){D.push(B)}),p(D)},E.prototype.values=function(){var D=[];return this.forEach(function(R){D.push(R)}),p(D)},E.prototype.entries=function(){var D=[];return this.forEach(function(R,B){D.push([B,R])}),p(D)},d.iterable&&(E.prototype[Symbol.iterator]=E.prototype.entries);function _(D){if(!D._noBody){if(D.bodyUsed)return Promise.reject(new TypeError("Already read"));D.bodyUsed=!0}}function A(D){return new Promise(function(R,B){D.onload=function(){R(D.result)},D.onerror=function(){B(D.error)}})}function C(D){var R=new FileReader,B=A(R);return R.readAsArrayBuffer(D),B}function U(D){var R=new FileReader,B=A(R),G=/charset=([A-Za-z0-9_-]+)/.exec(D.type),V=G?G[1]:"utf-8";return R.readAsText(D,V),B}function F(D){for(var R=new Uint8Array(D),B=new Array(R.length),G=0;G<R.length;G++)B[G]=String.fromCharCode(R[G]);return B.join("")}function I(D){if(D.slice)return D.slice(0);var R=new Uint8Array(D.byteLength);return R.set(new Uint8Array(D)),R.buffer}function P(){return this.bodyUsed=!1,this._initBody=function(D){this.bodyUsed=this.bodyUsed,this._bodyInit=D,D?typeof D=="string"?this._bodyText=D:d.blob&&Blob.prototype.isPrototypeOf(D)?this._bodyBlob=D:d.formData&&FormData.prototype.isPrototypeOf(D)?this._bodyFormData=D:d.searchParams&&URLSearchParams.prototype.isPrototypeOf(D)?this._bodyText=D.toString():d.arrayBuffer&&d.blob&&l(D)?(this._bodyArrayBuffer=I(D.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):d.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(D)||f(D))?this._bodyArrayBuffer=I(D):this._bodyText=D=Object.prototype.toString.call(D):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof D=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):d.searchParams&&URLSearchParams.prototype.isPrototypeOf(D)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},d.blob&&(this.blob=function(){var D=_(this);if(D)return D;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var D=_(this);return D||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(d.blob)return this.blob().then(C);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var D=_(this);if(D)return D;if(this._bodyBlob)return U(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(F(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},d.formData&&(this.formData=function(){return this.text().then(K)}),this.json=function(){return this.text().then(JSON.parse)},this}var L=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function j(D){var R=D.toUpperCase();return L.indexOf(R)>-1?R:D}function H(D,R){if(!(this instanceof H))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');R=R||{};var B=R.body;if(D instanceof H){if(D.bodyUsed)throw new TypeError("Already read");this.url=D.url,this.credentials=D.credentials,R.headers||(this.headers=new E(D.headers)),this.method=D.method,this.mode=D.mode,this.signal=D.signal,!B&&D._bodyInit!=null&&(B=D._bodyInit,D.bodyUsed=!0)}else this.url=String(D);if(this.credentials=R.credentials||this.credentials||"same-origin",(R.headers||!this.headers)&&(this.headers=new E(R.headers)),this.method=j(R.method||this.method||"GET"),this.mode=R.mode||this.mode||null,this.signal=R.signal||this.signal||(function(){if("AbortController"in a){var z=new AbortController;return z.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&B)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(B),(this.method==="GET"||this.method==="HEAD")&&(R.cache==="no-store"||R.cache==="no-cache")){var G=/([?&])_=[^&]*/;if(G.test(this.url))this.url=this.url.replace(G,"$1_="+new Date().getTime());else{var V=/\?/;this.url+=(V.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}H.prototype.clone=function(){return new H(this,{body:this._bodyInit})};function K(D){var R=new FormData;return D.trim().split("&").forEach(function(B){if(B){var G=B.split("="),V=G.shift().replace(/\+/g," "),z=G.join("=").replace(/\+/g," ");R.append(decodeURIComponent(V),decodeURIComponent(z))}}),R}function Z(D){var R=new E,B=D.replace(/\r?\n[\t ]+/g," ");return B.split("\r").map(function(G){return G.indexOf(`
122
122
  `)===0?G.substr(1,G.length):G}).forEach(function(G){var V=G.split(":"),z=V.shift().trim();if(z){var ae=V.join(":").trim();try{R.append(z,ae)}catch(_e){console.warn("Response "+_e.message)}}}),R}P.call(H.prototype);function Y(D,R){if(!(this instanceof Y))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(R||(R={}),this.type="default",this.status=R.status===void 0?200:R.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=R.statusText===void 0?"":""+R.statusText,this.headers=new E(R.headers),this.url=R.url||"",this._initBody(D)}P.call(Y.prototype),Y.prototype.clone=function(){return new Y(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new E(this.headers),url:this.url})},Y.error=function(){var D=new Y(null,{status:200,statusText:""});return D.ok=!1,D.status=0,D.type="error",D};var se=[301,302,303,307,308];Y.redirect=function(D,R){if(se.indexOf(R)===-1)throw new RangeError("Invalid status code");return new Y(null,{status:R,headers:{location:D}})},o.DOMException=a.DOMException;try{new o.DOMException}catch{o.DOMException=function(R,B){this.message=R,this.name=B;var G=Error(R);this.stack=G.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function le(D,R){return new Promise(function(B,G){var V=new H(D,R);if(V.signal&&V.signal.aborted)return G(new o.DOMException("Aborted","AbortError"));var z=new XMLHttpRequest;function ae(){z.abort()}z.onload=function(){var ne={statusText:z.statusText,headers:Z(z.getAllResponseHeaders()||"")};V.url.indexOf("file://")===0&&(z.status<200||z.status>599)?ne.status=200:ne.status=z.status,ne.url="responseURL"in z?z.responseURL:ne.headers.get("X-Request-URL");var ye="response"in z?z.response:z.responseText;setTimeout(function(){B(new Y(ye,ne))},0)},z.onerror=function(){setTimeout(function(){G(new TypeError("Network request failed"))},0)},z.ontimeout=function(){setTimeout(function(){G(new TypeError("Network request timed out"))},0)},z.onabort=function(){setTimeout(function(){G(new o.DOMException("Aborted","AbortError"))},0)};function _e(ne){try{return ne===""&&a.location.href?a.location.href:ne}catch{return ne}}if(z.open(V.method,_e(V.url),!0),V.credentials==="include"?z.withCredentials=!0:V.credentials==="omit"&&(z.withCredentials=!1),"responseType"in z&&(d.blob?z.responseType="blob":d.arrayBuffer&&(z.responseType="arraybuffer")),R&&typeof R.headers=="object"&&!(R.headers instanceof E||a.Headers&&R.headers instanceof a.Headers)){var ze=[];Object.getOwnPropertyNames(R.headers).forEach(function(ne){ze.push(w(ne)),z.setRequestHeader(ne,b(R.headers[ne]))}),V.headers.forEach(function(ne,ye){ze.indexOf(ye)===-1&&z.setRequestHeader(ye,ne)})}else V.headers.forEach(function(ne,ye){z.setRequestHeader(ye,ne)});V.signal&&(V.signal.addEventListener("abort",ae),z.onreadystatechange=function(){z.readyState===4&&V.signal.removeEventListener("abort",ae)}),z.send(typeof V._bodyInit>"u"?null:V._bodyInit)})}return le.polyfill=!0,a.fetch||(a.fetch=le,a.Headers=E,a.Request=H,a.Response=Y),o.Headers=E,o.Request=H,o.Response=Y,o.fetch=le,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var n=t.fetch?t:r;e=n.fetch,e.default=n.fetch,e.fetch=n.fetch,e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response,i.exports=e})(Ke,Ke.exports)),Ke.exports}var it=zi();const Ze=Pt(it),ji=Ns({__proto__:null,default:Ze},[it]),Ce=i=>{let e={};return i&&(typeof Headers<"u"&&i instanceof Headers||ji&&it.Headers&&i instanceof it.Headers?e=Bi(i):Array.isArray(i)?i.forEach(([t,r])=>{t&&r!==void 0&&(e[t]=r)}):e=i),e},wr=i=>i.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),Hi=i=>{if(!Array.isArray(i.query)){const r=i,n=[`query=${encodeURIComponent(wr(r.query))}`];return i.variables&&n.push(`variables=${encodeURIComponent(r.jsonSerializer.stringify(r.variables))}`),r.operationName&&n.push(`operationName=${encodeURIComponent(r.operationName)}`),n.join("&")}if(typeof i.variables<"u"&&!Array.isArray(i.variables))throw new Error("Cannot create query with given variable type, array expected");const e=i,t=i.query.reduce((r,n,s)=>(r.push({query:wr(n),variables:e.variables?e.jsonSerializer.stringify(e.variables[s]):void 0}),r),[]);return`query=${encodeURIComponent(e.jsonSerializer.stringify(t))}`},Gi=i=>async e=>{const{url:t,query:r,variables:n,operationName:s,fetch:o,fetchOptions:a,middleware:d}=e,l={...e.headers};let y="",f;i==="POST"?(f=Yi(r,n,s,a.jsonSerializer),typeof f=="string"&&(l["Content-Type"]="application/json")):y=Hi({query:r,variables:n,operationName:s,jsonSerializer:a.jsonSerializer??Ft});const w={method:i,headers:l,body:f,...a};let b=t,p=w;if(d){const E=await Promise.resolve(d({...w,url:t,operationName:s,variables:n})),{url:_,...A}=E;b=_,p=A}return y&&(b=`${b}?${y}`),await o(b,p)};class Ji{constructor(e,t={}){this.url=e,this.requestConfig=t,this.rawRequest=async(...r)=>{const[n,s,o]=r,a=ki(n,s,o),{headers:d,fetch:l=Ze,method:y="POST",requestMiddleware:f,responseMiddleware:w,...b}=this.requestConfig,{url:p}=this;a.signal!==void 0&&(b.signal=a.signal);const{operationName:E}=Et(a.query);return It({url:p,query:a.query,variables:a.variables,headers:{...Ce(Tt(d)),...Ce(a.requestHeaders)},operationName:E,fetch:l,method:y,fetchOptions:b,middleware:f}).then(_=>(w&&w(_),_)).catch(_=>{throw w&&w(_),_})}}async request(e,...t){const[r,n]=t,s=Fi(e,r,n),{headers:o,fetch:a=Ze,method:d="POST",requestMiddleware:l,responseMiddleware:y,...f}=this.requestConfig,{url:w}=this;s.signal!==void 0&&(f.signal=s.signal);const{query:b,operationName:p}=Et(s.document);return It({url:w,query:b,variables:s.variables,headers:{...Ce(Tt(o)),...Ce(s.requestHeaders)},operationName:p,fetch:a,method:d,fetchOptions:f,middleware:l}).then(E=>(y&&y(E),E.data)).catch(E=>{throw y&&y(E),E})}batchRequests(e,t){const r=qi(e,t),{headers:n,...s}=this.requestConfig;r.signal!==void 0&&(s.signal=r.signal);const o=r.documents.map(({document:d})=>Et(d).query),a=r.documents.map(({variables:d})=>d);return It({url:this.url,query:o,variables:a,headers:{...Ce(Tt(n)),...Ce(r.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??Ze,method:this.requestConfig.method||"POST",fetchOptions:s,middleware:this.requestConfig.requestMiddleware}).then(d=>(this.requestConfig.responseMiddleware&&this.requestConfig.responseMiddleware(d),d.data)).catch(d=>{throw this.requestConfig.responseMiddleware&&this.requestConfig.responseMiddleware(d),d})}setHeaders(e){return this.requestConfig.headers=e,this}setHeader(e,t){const{headers:r}=this.requestConfig;return r?r[e]=t:this.requestConfig.headers={[e]:t},this}setEndpoint(e){return this.url=e,this}}const It=async i=>{const{query:e,variables:t,fetchOptions:r}=i,n=Gi(Ui(i.method??"post")),s=Array.isArray(i.query),o=await n(i),a=await Qi(o,r.jsonSerializer??Ft),d=Array.isArray(a)?!a.some(({data:y})=>!y):!!a.data,l=Array.isArray(a)||!a.errors||Array.isArray(a.errors)&&!a.errors.length||r.errorPolicy==="all"||r.errorPolicy==="ignore";if(o.ok&&l&&d){const{errors:y,...f}=(Array.isArray(a),a),w=r.errorPolicy==="ignore"?f:a;return{...s?{data:w}:w,headers:o.headers,status:o.status}}else{const y=typeof a=="string"?{error:a}:a;throw new xe({...y,status:o.status,headers:o.headers},{query:e,variables:t})}},Yi=(i,e,t,r)=>{const n=r??Ft;if(!Array.isArray(i))return n.stringify({query:i,variables:e,operationName:t});if(typeof e<"u"&&!Array.isArray(e))throw new Error("Cannot create request body with given variable type, array expected");const s=i.reduce((o,a,d)=>(o.push({query:a,variables:e?e[d]:void 0}),o),[]);return n.stringify(s)},Qi=async(i,e)=>{let t;return i.headers.forEach((r,n)=>{n.toLowerCase()==="content-type"&&(t=r)}),t&&(t.toLowerCase().startsWith("application/json")||t.toLowerCase().startsWith("application/graphql+json")||t.toLowerCase().startsWith("application/graphql-response+json"))?e.parse(await i.text()):i.text()},Tt=i=>typeof i=="function"?i():i,ge=(i,...e)=>i.reduce((t,r,n)=>`${t}${r}${n in e?String(e[n]):""}`,"");async function ce(i,e,t,r){const n=new Ji(i,{fetch,headers:r||{}}),{errors:s,...o}=await n.request(e,t),a={...o};return s?.length&&(a.errors=s.map(({message:d,...l})=>new Is(d,l))),a}function et(i,e){return i instanceof Dt?Object.entries(i.getFields()).map(([t,r])=>{const n=r.type instanceof cr?r.type.ofType:r.type;if(n instanceof Dt||n instanceof St)return`${t} { ${et(n,e)} }`;if(n instanceof Rs){const s=n.ofType instanceof cr?n.ofType.ofType:n.ofType;if(s instanceof Ms)return t;if(s instanceof Dt||s instanceof St)return`${t} { ${et(s,e)} }`;throw new Error(`List item type ${s.toString()} is not handled`)}return t}).join(" "):i instanceof St?i.getTypes().map(t=>`... on ${e?`${e}_`:""}${t.name} { ${et(t,e)} }`).join(" "):""}function Ki(i,e,t){const r=Ar(i.name),n=i.specifications.at(-1);if(!n)throw new Error("No document model specification found");const s=`${n.state.global.schema} type Query { ${r}: ${r}State }`,a=Ts(s).getQueryType();if(!a)throw new Error("No query type found");const l=a.getFields()[r];if(!l)throw new Error("No state query found");return et(l.type,e)}async function Fe(i,e){const t=await e.generateJwtHandler?.(i),r=t?{Authorization:`Bearer ${t}`}:{};return cn(i,r)}async function cn(i,e){let t;try{const r=await ce(i,ge`
123
123
  query getDrive {
124
124
  drive {
@@ -185,7 +185,7 @@ type DocumentDriveLocalState{
185
185
  }
186
186
  }
187
187
  }
188
- `,{id:e});if(!o.document)return{...o,document:null};const a={clipboard:o.document.clipboard,header:o.document.header,initialState:o.document.initialState,operations:{global:o.document.operations.map(({inputText:d,...l})=>({...l,error:l.error??void 0,scope:"global",input:JSON.parse(d)})),local:[]},state:o.document.state};return{...o,document:a}}class Vi{#e;#t=new Map;constructor(e){this.#e=e}#r(e,t,r){for(const s of e){if(s.message===`Drive with id ${t} not found`)return new Re(t);if(r&&s.message===`Document with id ${r} not found`)return new mr(t,r)}const n=e.at(0);if(n)return n}async#n(e,t){const{errors:r,document:n}=await br(t,e,Ii);return(r?this.#r(r,e):void 0)||n}async fetchDrive(e){const t=this.#t.get(e);if(!t)return new Re(e);const r=await this.fetchDocument(e,e,ct);if(r instanceof Error)return r;const n={...r,readContext:t.context};return t.drive=n,n}async fetchDocument(e,t,r){const n=this.#t.get(e);if(!n)return new Re(e);let s;try{s=this.#e(r)}catch(l){return new Ri(r,l)}const{url:o}=n.context,{errors:a,document:d}=await br(o,t,s);if(a){const l=this.#r(a,e,t);if(l instanceof dt)return l;if(l)throw l}return d||new mr(e,t)}async addReadDrive(e,t){let r;t?.expectedDriveInfo?r=t.expectedDriveInfo.id:r=(await cn(e)).id;const n=await this.#n(r,e);if(n instanceof Error)throw n;if(!n)throw new Re(r);this.#t.set(r,{drive:n,context:{...t,url:e}})}async getReadDrives(){return Promise.resolve([...this.#t.keys()])}async getReadDrive(e){const t=this.#t.get(e);return Promise.resolve(t?{...t.drive,readContext:t.context}:new Re(e))}async getReadDriveBySlug(e){const t=[...this.#t.values()].find(({drive:r})=>r.header.slug===e);return Promise.resolve(t?{...t.drive,readContext:t.context}:new Li(e))}getReadDriveContext(e){return Promise.resolve(this.#t.get(e)?.context??new Re(e))}deleteReadDrive(e){const t=this.#t.delete(e);return Promise.resolve(t?void 0:new Re(e))}}function Wi(i){return class extends i{#e;#t=new Set;constructor(...t){super(...t),this.#e=new Vi(this.getDocumentModelModule.bind(this)),this.#r().then(r=>{r.length&&this.#n(r,"add")}).catch(fe.error)}async#r(){const t=await this.getReadDrives();return(await Promise.all(t.map(n=>this.getReadDrive(n)))).filter(n=>!(n instanceof Error))}#n(t,r){this.#t.forEach(n=>n(t,r))}getReadDrives(){return this.#e.getReadDrives()}getReadDrive(t){return this.#e.getReadDrive(t)}getReadDriveBySlug(t){return this.#e.getReadDriveBySlug(t)}getReadDriveContext(t){return this.#e.getReadDriveContext(t)}async addReadDrive(t,r){await this.#e.addReadDrive(t,r),this.#n(await this.#r(),"add")}fetchDrive(t){return this.#e.fetchDrive(t)}fetchDocument(t,r,n){return this.#e.fetchDocument(t,r,n)}async deleteReadDrive(t){const r=await this.#e.deleteReadDrive(t);if(r)return r;this.#n(await this.#r(),"delete")}async migrateReadDrive(t,r){const n=await this.getReadDriveContext(t);if(n instanceof Error)return n;const{url:s,...o}=n;try{return await this.addRemoteDrive(s,r)}catch(a){throw fe.error(a),await this.addReadDrive(n.url,o),a}}onReadDrivesUpdate(t){return this.#t.add(t),Promise.resolve(()=>this.#t.delete(t))}}}function Xi(i){return typeof i.getReadDrives=="function"}class Zi{server;delegate;defaultRemoteDrives=new Map;removeOldRemoteDrivesConfig;constructor(e,t,r){if(this.server=e,this.delegate=t,r?.defaultDrives?.remoteDrives)for(const n of r.defaultDrives.remoteDrives)this.defaultRemoteDrives.set(n.url,{...n,status:"PENDING"});this.removeOldRemoteDrivesConfig=r?.defaultDrives?.removeOldRemoteDrives||{strategy:"preserve-all"}}getDefaultRemoteDrives(){return new Map(JSON.parse(JSON.stringify(Array.from(this.defaultRemoteDrives))))}async deleteDriveById(e){try{await this.server.deleteDrive(e)}catch(t){fe.error(t)}}async preserveDrivesById(e,t,r="detach"){const n=t.map(a=>this.server.getDrive(a)),o=(await Promise.all(n)).filter(a=>a.state.local.listeners.length>0||a.state.local.triggers.length>0).filter(a=>!e.includes(a.header.id)).map(a=>a.header.id);r==="detach"?await this.detachDrivesById(o):await this.removeDrivesById(o)}async removeDrivesById(e){for(const t of e)await this.deleteDriveById(t)}async detachDrivesById(e){const t=e.map(r=>this.delegate.detachDrive(r));await Promise.all(t)}async removeOldremoteDrives(){const e=await this.server.getDrives();switch(this.removeOldRemoteDrivesConfig.strategy){case"preserve-by-id-and-detach":case"preserve-by-id":{const t=this.removeOldRemoteDrivesConfig.strategy==="preserve-by-id-and-detach"?"detach":"remove";await this.preserveDrivesById(this.removeOldRemoteDrivesConfig.ids,e,t);break}case"preserve-by-url-and-detach":case"preserve-by-url":{const t=this.removeOldRemoteDrivesConfig.strategy==="preserve-by-url-and-detach"?"detach":"remove",r=this.removeOldRemoteDrivesConfig.urls.map(s=>Fe(s,this.server)),n=(await Promise.all(r)).map(s=>s.id);await this.preserveDrivesById(n,e,t);break}case"remove-by-id":{const t=this.removeOldRemoteDrivesConfig.ids.filter(r=>e.includes(r));await this.removeDrivesById(t);break}case"remove-by-url":{const t=this.removeOldRemoteDrivesConfig.urls.map(s=>Fe(s,this.server)),n=(await Promise.all(t)).map(s=>s.id).filter(s=>e.includes(s));await this.removeDrivesById(n);break}case"remove-all":{const t=e.map(s=>this.server.getDrive(s)),n=(await Promise.all(t)).filter(s=>s.state.local.listeners.length>0||s.state.local.triggers.length>0).map(s=>s.header.id);await this.removeDrivesById(n);break}case"detach-by-id":{const r=this.removeOldRemoteDrivesConfig.ids.filter(n=>e.includes(n)).map(n=>this.delegate.detachDrive(n));await Promise.all(r);break}case"detach-by-url":{const t=this.removeOldRemoteDrivesConfig.urls.map(o=>Fe(o,this.server)),s=(await Promise.all(t)).map(o=>o.id).filter(o=>e.includes(o)).map(o=>this.delegate.detachDrive(o));await Promise.all(s);break}}}async setAllDefaultDrivesAccessLevel(e){const t=this.defaultRemoteDrives.values();for(const r of t)await this.setDefaultDriveAccessLevel(r.url,e)}async setDefaultDriveAccessLevel(e,t){const r=this.defaultRemoteDrives.get(e);if(r&&r.options.accessLevel!==t){const n={...r,options:{...r.options,accessLevel:t}};this.defaultRemoteDrives.set(e,n),await this.initializeDefaultRemoteDrives([n])}}async initializeDefaultRemoteDrives(e=Array.from(this.defaultRemoteDrives.values())){const t=await this.server.getDrives(),r=Xi(this.server)?this.server:void 0,n=await r?.getReadDrives();for(const s of e){let o={...s};try{const a=s.metadata??await Fe(s.url,this.server);o={...s,metadata:a},this.defaultRemoteDrives.set(s.url,o);const d=t.includes(a.id),l=n?.includes(a.id),y=s.options.accessLevel!==void 0,f=r&&s.options.accessLevel==="READ",w=f?l:d;if(y&&(f?d:l))try{await(f?this.server.deleteDrive(a.id):r?.deleteReadDrive(a.id))}catch(p){fe.error(p)}if(w){o.status="ALREADY_ADDED",this.defaultRemoteDrives.set(s.url,o),this.delegate.emit("ALREADY_ADDED",this.defaultRemoteDrives,o,a.id,a.name);continue}o.status="ADDING",this.defaultRemoteDrives.set(s.url,o),this.delegate.emit("ADDING",this.defaultRemoteDrives,o),s.options.accessLevel==="READ"&&r||f?await r.addReadDrive(s.url,{...s.options,expectedDriveInfo:a}):await this.server.addRemoteDrive(s.url,{...s.options,expectedDriveInfo:a}),o.status="SUCCESS",this.defaultRemoteDrives.set(s.url,o),this.delegate.emit("SUCCESS",this.defaultRemoteDrives,o,a.id,a.name)}catch(a){o.status="ERROR",this.defaultRemoteDrives.set(s.url,o),this.delegate.emit("ERROR",this.defaultRemoteDrives,o,void 0,void 0,a)}}}}const ot={sequentialUpdates:!0},eo=1500,Dr=100,to=50;let Rt;const q=()=>(Rt||(Rt=me(["PullResponderTransmitter","static"])),Rt);class ue{logger=me(["PullResponderTransmitter",Math.floor(Math.random()*999).toString()]);listener;manager;constructor(e,t){this.listener=e,this.manager=t,this.logger.verbose(`constructor(listener: ${e.listenerId})`)}static async getAuthHeaders(e,t){if(!t?.generateJwtHandler)return q().verbose(`No JWT handler available for ${e}`),{};try{const r=await t.generateJwtHandler(e);return r?{Authorization:`Bearer ${r}`}:(q().verbose(`No JWT generated for ${e}`),{})}catch(r){return q().error(`Error generating JWT for ${e}:`,r),{}}}async requestWithAuth(e,t,r){const n=await ue.getAuthHeaders(e,this.manager),s=await ce(e,t,r,n);if(s.errors?.at(0)?.message.includes("Unauthorized")){const a=await ue.getAuthHeaders(e,this.manager);return ce(e,t,r,a)}return s}getStrands(e){return this.logger.verbose(`[SYNC DEBUG] PullResponderTransmitter.getStrands called for drive: ${this.listener.driveId}, listener: ${this.listener.listenerId}, options: ${JSON.stringify(e||{})}`),this.manager.getStrands(this.listener.driveId,this.listener.listenerId,e).then(t=>{if(this.logger.verbose(`[SYNC DEBUG] PullResponderTransmitter.getStrands returning ${t.length} strands for drive: ${this.listener.driveId}, listener: ${this.listener.listenerId}`),t.length===0)this.logger.verbose(`[SYNC DEBUG] No strands returned for drive: ${this.listener.driveId}, listener: ${this.listener.listenerId}`);else for(const r of t)this.logger.verbose(`[SYNC DEBUG] Strand for drive: ${r.driveId}, document: ${r.documentId}, scope: ${r.scope}, operations: ${r.operations.length}`);return t})}disconnect(){return Promise.resolve()}async processAcknowledge(e,t,r){this.logger.verbose(`processAcknowledge(drive: ${e}, listener: ${t})`,r);let n=!0;for(const s of r)try{await this.manager.updateListenerRevision(t,e,{documentId:s.documentId,scope:s.scope,branch:s.branch},s.revision)}catch(o){this.logger.warn("Error acknowledging sync unit",o,s),n=!1;continue}return n}static async registerPullResponder(e,t,r,n,s){q().verbose(`registerPullResponder(url: ${t})`,r);const o=await this.getAuthHeaders(t,s),a=await ce(t,ge`
188
+ `,{id:e});if(!o.document)return{...o,document:null};const a={clipboard:o.document.clipboard,header:o.document.header,initialState:o.document.initialState,operations:{global:o.document.operations.map(({inputText:d,...l})=>({...l,error:l.error??void 0,scope:"global",input:JSON.parse(d)})),local:[]},state:o.document.state};return{...o,document:a}}class Vi{#e;#t=new Map;constructor(e){this.#e=e}#r(e,t,r){for(const s of e){if(s.message===`Drive with id ${t} not found`)return new Re(t);if(r&&s.message===`Document with id ${r} not found`)return new mr(t,r)}const n=e.at(0);if(n)return n}async#n(e,t){const{errors:r,document:n}=await br(t,e,Ti);return(r?this.#r(r,e):void 0)||n}async fetchDrive(e){const t=this.#t.get(e);if(!t)return new Re(e);const r=await this.fetchDocument(e,e,ut);if(r instanceof Error)return r;const n={...r,readContext:t.context};return t.drive=n,n}async fetchDocument(e,t,r){const n=this.#t.get(e);if(!n)return new Re(e);let s;try{s=this.#e(r)}catch(l){return new Ri(r,l)}const{url:o}=n.context,{errors:a,document:d}=await br(o,t,s);if(a){const l=this.#r(a,e,t);if(l instanceof dt)return l;if(l)throw l}return d||new mr(e,t)}async addReadDrive(e,t){let r;t?.expectedDriveInfo?r=t.expectedDriveInfo.id:r=(await cn(e)).id;const n=await this.#n(r,e);if(n instanceof Error)throw n;if(!n)throw new Re(r);this.#t.set(r,{drive:n,context:{...t,url:e}})}async getReadDrives(){return Promise.resolve([...this.#t.keys()])}async getReadDrive(e){const t=this.#t.get(e);return Promise.resolve(t?{...t.drive,readContext:t.context}:new Re(e))}async getReadDriveBySlug(e){const t=[...this.#t.values()].find(({drive:r})=>r.header.slug===e);return Promise.resolve(t?{...t.drive,readContext:t.context}:new Li(e))}getReadDriveContext(e){return Promise.resolve(this.#t.get(e)?.context??new Re(e))}deleteReadDrive(e){const t=this.#t.delete(e);return Promise.resolve(t?void 0:new Re(e))}}function Wi(i){return class extends i{#e;#t=new Set;constructor(...t){super(...t),this.#e=new Vi(this.getDocumentModelModule.bind(this)),this.#r().then(r=>{r.length&&this.#n(r,"add")}).catch(fe.error)}async#r(){const t=await this.getReadDrives();return(await Promise.all(t.map(n=>this.getReadDrive(n)))).filter(n=>!(n instanceof Error))}#n(t,r){this.#t.forEach(n=>n(t,r))}getReadDrives(){return this.#e.getReadDrives()}getReadDrive(t){return this.#e.getReadDrive(t)}getReadDriveBySlug(t){return this.#e.getReadDriveBySlug(t)}getReadDriveContext(t){return this.#e.getReadDriveContext(t)}async addReadDrive(t,r){await this.#e.addReadDrive(t,r),this.#n(await this.#r(),"add")}fetchDrive(t){return this.#e.fetchDrive(t)}fetchDocument(t,r,n){return this.#e.fetchDocument(t,r,n)}async deleteReadDrive(t){const r=await this.#e.deleteReadDrive(t);if(r)return r;this.#n(await this.#r(),"delete")}async migrateReadDrive(t,r){const n=await this.getReadDriveContext(t);if(n instanceof Error)return n;const{url:s,...o}=n;try{return await this.addRemoteDrive(s,r)}catch(a){throw fe.error(a),await this.addReadDrive(n.url,o),a}}onReadDrivesUpdate(t){return this.#t.add(t),Promise.resolve(()=>this.#t.delete(t))}}}function Xi(i){return typeof i.getReadDrives=="function"}class Zi{server;delegate;defaultRemoteDrives=new Map;removeOldRemoteDrivesConfig;constructor(e,t,r){if(this.server=e,this.delegate=t,r?.defaultDrives?.remoteDrives)for(const n of r.defaultDrives.remoteDrives)this.defaultRemoteDrives.set(n.url,{...n,status:"PENDING"});this.removeOldRemoteDrivesConfig=r?.defaultDrives?.removeOldRemoteDrives||{strategy:"preserve-all"}}getDefaultRemoteDrives(){return new Map(JSON.parse(JSON.stringify(Array.from(this.defaultRemoteDrives))))}async deleteDriveById(e){try{await this.server.deleteDrive(e)}catch(t){fe.error(t)}}async preserveDrivesById(e,t,r="detach"){const n=t.map(a=>this.server.getDrive(a)),o=(await Promise.all(n)).filter(a=>a.state.local.listeners.length>0||a.state.local.triggers.length>0).filter(a=>!e.includes(a.header.id)).map(a=>a.header.id);r==="detach"?await this.detachDrivesById(o):await this.removeDrivesById(o)}async removeDrivesById(e){for(const t of e)await this.deleteDriveById(t)}async detachDrivesById(e){const t=e.map(r=>this.delegate.detachDrive(r));await Promise.all(t)}async removeOldremoteDrives(){const e=await this.server.getDrives();switch(this.removeOldRemoteDrivesConfig.strategy){case"preserve-by-id-and-detach":case"preserve-by-id":{const t=this.removeOldRemoteDrivesConfig.strategy==="preserve-by-id-and-detach"?"detach":"remove";await this.preserveDrivesById(this.removeOldRemoteDrivesConfig.ids,e,t);break}case"preserve-by-url-and-detach":case"preserve-by-url":{const t=this.removeOldRemoteDrivesConfig.strategy==="preserve-by-url-and-detach"?"detach":"remove",r=this.removeOldRemoteDrivesConfig.urls.map(s=>Fe(s,this.server)),n=(await Promise.all(r)).map(s=>s.id);await this.preserveDrivesById(n,e,t);break}case"remove-by-id":{const t=this.removeOldRemoteDrivesConfig.ids.filter(r=>e.includes(r));await this.removeDrivesById(t);break}case"remove-by-url":{const t=this.removeOldRemoteDrivesConfig.urls.map(s=>Fe(s,this.server)),n=(await Promise.all(t)).map(s=>s.id).filter(s=>e.includes(s));await this.removeDrivesById(n);break}case"remove-all":{const t=e.map(s=>this.server.getDrive(s)),n=(await Promise.all(t)).filter(s=>s.state.local.listeners.length>0||s.state.local.triggers.length>0).map(s=>s.header.id);await this.removeDrivesById(n);break}case"detach-by-id":{const r=this.removeOldRemoteDrivesConfig.ids.filter(n=>e.includes(n)).map(n=>this.delegate.detachDrive(n));await Promise.all(r);break}case"detach-by-url":{const t=this.removeOldRemoteDrivesConfig.urls.map(o=>Fe(o,this.server)),s=(await Promise.all(t)).map(o=>o.id).filter(o=>e.includes(o)).map(o=>this.delegate.detachDrive(o));await Promise.all(s);break}}}async setAllDefaultDrivesAccessLevel(e){const t=this.defaultRemoteDrives.values();for(const r of t)await this.setDefaultDriveAccessLevel(r.url,e)}async setDefaultDriveAccessLevel(e,t){const r=this.defaultRemoteDrives.get(e);if(r&&r.options.accessLevel!==t){const n={...r,options:{...r.options,accessLevel:t}};this.defaultRemoteDrives.set(e,n),await this.initializeDefaultRemoteDrives([n])}}async initializeDefaultRemoteDrives(e=Array.from(this.defaultRemoteDrives.values())){const t=await this.server.getDrives(),r=Xi(this.server)?this.server:void 0,n=await r?.getReadDrives();for(const s of e){let o={...s};try{const a=s.metadata??await Fe(s.url,this.server);o={...s,metadata:a},this.defaultRemoteDrives.set(s.url,o);const d=t.includes(a.id),l=n?.includes(a.id),y=s.options.accessLevel!==void 0,f=r&&s.options.accessLevel==="READ",w=f?l:d;if(y&&(f?d:l))try{await(f?this.server.deleteDrive(a.id):r?.deleteReadDrive(a.id))}catch(p){fe.error(p)}if(w){o.status="ALREADY_ADDED",this.defaultRemoteDrives.set(s.url,o),this.delegate.emit("ALREADY_ADDED",this.defaultRemoteDrives,o,a.id,a.name);continue}o.status="ADDING",this.defaultRemoteDrives.set(s.url,o),this.delegate.emit("ADDING",this.defaultRemoteDrives,o),s.options.accessLevel==="READ"&&r||f?await r.addReadDrive(s.url,{...s.options,expectedDriveInfo:a}):await this.server.addRemoteDrive(s.url,{...s.options,expectedDriveInfo:a}),o.status="SUCCESS",this.defaultRemoteDrives.set(s.url,o),this.delegate.emit("SUCCESS",this.defaultRemoteDrives,o,a.id,a.name)}catch(a){o.status="ERROR",this.defaultRemoteDrives.set(s.url,o),this.delegate.emit("ERROR",this.defaultRemoteDrives,o,void 0,void 0,a)}}}}const ot={sequentialUpdates:!0},eo=1500,Dr=100,to=50;let Rt;const q=()=>(Rt||(Rt=me(["PullResponderTransmitter","static"])),Rt);class ue{logger=me(["PullResponderTransmitter",Math.floor(Math.random()*999).toString()]);listener;manager;constructor(e,t){this.listener=e,this.manager=t,this.logger.verbose(`constructor(listener: ${e.listenerId})`)}static async getAuthHeaders(e,t){if(!t?.generateJwtHandler)return q().verbose(`No JWT handler available for ${e}`),{};try{const r=await t.generateJwtHandler(e);return r?{Authorization:`Bearer ${r}`}:(q().verbose(`No JWT generated for ${e}`),{})}catch(r){return q().error(`Error generating JWT for ${e}:`,r),{}}}async requestWithAuth(e,t,r){const n=await ue.getAuthHeaders(e,this.manager),s=await ce(e,t,r,n);if(s.errors?.at(0)?.message.includes("Unauthorized")){const a=await ue.getAuthHeaders(e,this.manager);return ce(e,t,r,a)}return s}getStrands(e){return this.logger.verbose(`[SYNC DEBUG] PullResponderTransmitter.getStrands called for drive: ${this.listener.driveId}, listener: ${this.listener.listenerId}, options: ${JSON.stringify(e||{})}`),this.manager.getStrands(this.listener.driveId,this.listener.listenerId,e).then(t=>{if(this.logger.verbose(`[SYNC DEBUG] PullResponderTransmitter.getStrands returning ${t.length} strands for drive: ${this.listener.driveId}, listener: ${this.listener.listenerId}`),t.length===0)this.logger.verbose(`[SYNC DEBUG] No strands returned for drive: ${this.listener.driveId}, listener: ${this.listener.listenerId}`);else for(const r of t)this.logger.verbose(`[SYNC DEBUG] Strand for drive: ${r.driveId}, document: ${r.documentId}, scope: ${r.scope}, operations: ${r.operations.length}`);return t})}disconnect(){return Promise.resolve()}async processAcknowledge(e,t,r){this.logger.verbose(`processAcknowledge(drive: ${e}, listener: ${t})`,r);let n=!0;for(const s of r)try{await this.manager.updateListenerRevision(t,e,{documentId:s.documentId,scope:s.scope,branch:s.branch},s.revision)}catch(o){this.logger.warn("Error acknowledging sync unit",o,s),n=!1;continue}return n}static async registerPullResponder(e,t,r,n,s){q().verbose(`registerPullResponder(url: ${t})`,r);const o=await this.getAuthHeaders(t,s),a=await ce(t,ge`
189
189
  mutation registerPullResponderListener(
190
190
  $filter: InputListenerFilter!
191
191
  $listenerId: String
@@ -313,4 +313,4 @@ type DocumentDriveLocalState{
313
313
  error
314
314
  }
315
315
  }
316
- `,{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:io(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 Rr(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 At(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 Nt(i){return{id:oo(i),documentType:ao(i),document:co(i)}}function oo(i){return"id"in i?i.id:"header"in i?i.header.id:"document"in i?i.document.header.id:void 0}function ao(i){return"documentType"in i?i.documentType:"header"in i?i.header.documentType:i.document.header.documentType}function co(i){return"document"in i?i.document:void 0}function uo(i){return["LOCAL","CLOUD","PUBLIC"].includes(i)}function Co(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"||!uo(r)?"LOCAL":r}class lo{logger=me(["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 ve(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 ve(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=Ue(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 y=l instanceof Error?l:new Error(JSON.stringify(l));return{status:"ERROR",error:new ie("ERROR",void 0,`Error creating document: ${y.message}`,y),operations:[],document:void 0,signals:[]}}},processJob:async e=>{if(an(e))return this.queueDelegate.processOperationJob(e);if($i(e))return this.queueDelegate.processActionJob(e);if(Xe(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?Bt:l.taskQueueMethod,featureFlags:{...l?.featureFlags}},this.enableDualActionCreate=l?.featureFlags?.enableDualActionCreate??!1,this.enableDualActionCreate&&this.logger.warn("Dual action create is enabled."),this.defaultDrivesManager=new Zi(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(ue.isPullResponderTrigger(s)){let o=!0;const a=ue.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(y=>y.status!=="SUCCESS").length<1&&this.synchronizationManager.updateSyncStatus(e,{pull:"SUCCESS"});for(const y of d){const{documentId:f,scope:w,branch:b,status:p,error:E}=y;this.synchronizationManager.updateSyncStatus({documentId:f,scope:w,branch:b},{pull:p},E)}if(o){o=!1,(await this.synchronizationManager.getSynchronizationUnitsIds(e)).filter(b=>!d.find(p=>p.documentId===b.documentId&&p.scope===b.scope&&p.branch===b.branch)).forEach(b=>{this.synchronizationManager.updateSyncStatus(b,{pull:"SUCCESS"})});const w=n.state.local.listeners.find(b=>s.data.url===b.callInfo?.data);if(w)for(const b of d){const{documentId:p,scope:E,branch:_}=b;this.listenerManager.updateListenerRevision(w.listenerId,e,{documentId:p,scope:E,branch:_},b.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 un(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 ue(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}=Lt(),n=tn({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 Fe(e,this),{pullFilter:d,pullInterval:l,availableOffline:y,sharingType:f,listeners:w,triggers:b}=t,p=await ue.createPullResponderTrigger(r,e,{pullFilter:d,pullInterval:l},this.listeners);return await this.addDrive({id:r,slug:s,global:{name:n,icon:o},local:{triggers:[...b,p],listeners:w,availableOffline:y,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&&ve(o)&&(r=o,At(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(ve(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(ve(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&&At(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}=Nt(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=Ue(e.id,n));else if("header"in e)await Ge(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 Ge(s.header):this.logger.warn("Creating a document with an unsigned id is deprecated. Use createSignedHeaderForSigner."),d=s.header}else d=Ue(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 y=Object.values(a.operations).flat();y.length&&(ve(a)?await this.legacyStorage.addDriveOperations(d.id,y,a):await this.legacyStorage.addDocumentOperations(d.id,y,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}=Nt(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=Ue(e.id,n));else if("header"in e)await Ge(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 Ge(s.header),l=!0):this.logger.warn("Creating a document with an unsigned id is deprecated. Use createSignedHeaderForSigner."),d=s.header}else d=Ue(void 0,n),l=!1;r&&(d.meta={...d.meta,...r});const y=1,f=o??a.state,w=Object.values(a.operations).flat(),b=w.length===0;let p=[];if(b){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,I={model:n,version:0,documentId:d.id,signing:F},P={id:$e(),type:"CREATE_DOCUMENT",timestampUtcMs:U,input:I,scope:"document"},L={model:n,fromVersion:0,toVersion:y,documentId:d.id,initialState:f},j={id:$e(),type:"UPGRADE_DOCUMENT",timestampUtcMs:U,input:L,scope:"document"},K={state:$t()},Z=or(K,"document"),se=or({state:f},"document");p=[{id:Ve(d.id,"document","main",P.id),index:0,skip:0,hash:Z,timestampUtcMs:U,action:P},{id:Ve(d.id,"document","main",j.id),index:1,skip:0,hash:se,timestampUtcMs:U,action:j}]}else p=w;const E=ar(p);E.header||(E.header=[]),E.document||(E.document=[]),E.global||(E.global=[]),E.local||(E.local=[]);const A={header:d,operations:E,initialState:f,clipboard:[],state:f};await this.documentStorage.create(A);const C=await this.getDocument(A.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=ar(r);for(const y of Object.keys(l)){const f=t.operations[y]||[],w=ps(l[y]||[],f);if(w.length<1)continue;const b=bt(Je(f)),[p,E]=ms(b,w),A=(E.length<1?p:ys(b,p,Ds)).filter(C=>b.length<1||vs(b[b.length-1],C));for(const C of A){let U=!1;if(E.length>0){const F=r.find(I=>I.hash===C.hash);U=!F||F.index!==C.index||F.skip!==C.skip}try{const F=this.options.taskQueueMethod,I=()=>this._performOperation(e,a,C,U),P=await(F?xt(I,F):I());a=P.document,s.push(...P.signals),n.push(P.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?Rr(e.operations,r.revisions):e.operations,s=We(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(ve(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)&&At(e,t?.revisions))return e;const r=this.getDocumentModelModule(e.header.documentType),n=t?.revisions!==void 0?Rr(e.operations,t.revisions):e.operations,s=We(n),o=Object.keys(s),a=new Set([...o,"global","local"]),d={},l={};for(const p of a)d[p]=[],l[p]=[];for(const[p,E]of Object.entries(s))if(E)for(const _ of E)if(_.action.type==="CREATE_DOCUMENT"||_.action.type==="UPGRADE_DOCUMENT"){const A=d[p];A&&A.push(_)}else{const A=l[p];A&&A.push(_)}let y=e.header;if(t?.revisions){const p={...e.header.revision};for(const E of Object.keys(t.revisions)){const _=s[E]??[];if(_.length===0)delete p[E];else{const A=_.at(-1);p[E]=A?A.index+1:0}}y={...e.header,revision:p}}const f=Nr(e.initialState,l,r.reducer,y,void 0,{},{...t,checkHashes:t?.checkHashes??!0,reuseOperationResultingState:t?.checkHashes??!0}),w=new Set([...Object.keys(s),...Object.keys(d),...Object.keys(f.operations)]),b={};for(const p of w)b[p]=[...d[p]||[],...f.operations[p]||[]];return{...f,operations:b,clipboard:e.clipboard??[]}}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]||[],w=We({...t.operations,[d]:ws(l,r)})[d]?.at(-1);w&&!w.resultingState&&(w.resultingState=await(ve(t)?this.legacyStorage.getOperationResultingState?.(e,w.index,w.action.scope,"main"):this.legacyStorage.getDriveOperationResultingState?.(e,w.index,w.action.scope,"main")));const b=a.operations[d]||[],p=[];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&&p.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=bt(Je(C)),F=bt(Je(b)),I=bs(F,U);a={...a,clipboard:Je(I.filter(P=>P.action.type!=="NOOP")).reverse()}}const E=a.operations[r.action.scope];if(!E)throw new ie("ERROR",r,`No operations found for scope: ${r.action.scope}`);const A=E.filter(C=>C.index==r.index&&C.skip==r.skip).at(0);if(!A)throw new ie("ERROR",r,`Operation with index ${r.index}:${r.skip} was not applied.`);if(!A.error&&A.hash!==r.hash&&!n)throw this.logger.warn(JSON.stringify(A,null,2)),new Mi(r,A);for(const C of p){const U=await C();o.push(U)}return{document:a,signals:o,operation:A}}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}=Nt(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 qe(r);let a;const d=new Promise((l,y)=>{const f=this.queueManager.on("jobCompleted",(b,p)=>{b.jobId===a&&(f(),w(),l(p))}),w=this.queueManager.on("jobFailed",(b,p)=>{b.jobId===a&&(f(),w(),y(p))})});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,w)=>{f.jobId===s&&(l(),y(),a(w))}),y=this.queueManager.on("jobFailed",(f,w)=>{f.jobId===s&&(l(),y(),d(w))})});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,y)=>{l.jobId===n&&(a(),d(),s(y))}),d=this.queueManager.on("jobFailed",(l,y)=>{l.jobId===n&&(a(),d(),o(y))})})}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,y)=>{l.jobId===n&&(a(),d(),s(y))}),d=this.queueManager.on("jobFailed",(l,y)=>{l.jobId===n&&(a(),d(),o(y))})})}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 b=>{const p=await this._processOperations(e,b,t);if(!p.document)throw this.logger.error("Invalid document"),p.error??new Error("Invalid document");return s=p.document,d=p.error,a.push(...p.signals),o.push(...p.operationsApplied),{operations:p.operationsApplied,document:p.document}});const l=new Array;if(s){this.cache.setDocument(e,s).catch(this.logger.error);for(const b of o){const p={documentId:e,documentType:s.header.documentType,scope:b.action.scope,branch:"main",revision:b.index+1,lastUpdated:b.timestampUtcMs};l.some(_=>_.documentId===p.documentId&&_.scope===p.scope&&_.branch===p.branch)||l.push(p)}}const f=o.find(b=>!t.find(p=>p.id===b.id&&p.index===b.index&&p.skip===b.skip&&p.hash===b.hash))?{type:"local"}:r?.source??{type:"local"},w=this.getOperationSource(f);if(l.length&&this.listenerManager.updateSynchronizationRevisions(l,f,()=>{this.synchronizationManager.updateSyncStatus(e,{[w]:"SYNCING"});for(const b of l)this.synchronizationManager.updateSyncStatus(b,{[w]:"SYNCING"})},this.handleListenerError.bind(this),r?.forceSync??f.type==="local").then(b=>{b.length&&this.synchronizationManager.updateSyncStatus(e,{[w]:"SUCCESS"});for(const p of l)this.synchronizationManager.updateSyncStatus(p,{[w]:"SUCCESS"})}).catch(b=>{this.logger.error("Non handled error updating sync revision",b),this.synchronizationManager.updateSyncStatus(e,{[w]:"ERROR"},b);for(const p of l)this.synchronizationManager.updateSyncStatus(p,{[w]:"ERROR"},b)}),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 y=l instanceof ie?l:new ie("ERROR",void 0,l.message,l.cause);return{status:y.status,error:y,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",(y,f)=>{y.jobId===s&&(d(),l(),o(f))}),l=this.queueManager.on("jobFailed",(y,f)=>{y.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 y=>{const f=await this._processOperations(e,y,t.slice());return n=f.document,s.push(...f.operationsApplied),o.push(...f.signals),a=f.error,{operations:f.operationsApplied,document:f.document}}),!n||!ve(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(y=>y.action.scope==="global").slice().pop();if(l){const f=s.find(b=>!t.find(p=>p.id===b.id&&p.index===b.index&&p.skip===b.skip&&p.hash===b.hash))?{type:"local"}:r?.source??{type:"local"},w=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,{[w]:"SYNCING"})},this.handleListenerError.bind(this),r?.forceSync??f.type==="local").then(b=>{b.length&&this.synchronizationManager.updateSyncStatus(e,{[w]:"SUCCESS"})}).catch(b=>{this.logger.error("Non handled error updating sync revision",b),this.synchronizationManager.updateSyncStatus(e,{[w]:"ERROR"},b)})}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 y=l instanceof ie?l:new ie("ERROR",void 0,l.message,l);return{status:y.status,error:y,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,Wr({listenerId:s.listenerId}));for(const s of n)await this.addDriveAction(e,Xr({triggerId:s.id}));await this.addDriveAction(e,Vr({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,id:o.id??Ve(e.documentId,e.scope,e.branch,o.actionId),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 ho=Wi(lo);class at extends Error{constructor(e){super(e||"Aborted"),this.name="AbortError"}}const Be=i=>i&&i.length>0&&!i.includes("*")?new Set(i):null,dn=i=>({parentId:Be(i.parentId),documentId:Be(i.documentId),documentModelType:Be(i.documentModelType),scope:Be(i.scope),branch:Be(i.branch)}),ln=(i,...e)=>{const t=new Set(i);for(const r of e)for(const n of r)t.add(n);return t},hn=(i,e)=>{const t=new Set;for(const r of i)e.has(r)&&t.add(r);return t};class fo{logger=me(["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(this.documents[t])throw new qe(t);const r=e.header.slug?.length>0?e.header.slug:t;if(r&&this.slugToDocumentId[r])throw new qe(t,ke.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 y=new Date(d.document.header.createdAtUtcIso),f=new Date(l.document.header.createdAtUtcIso);if(y.getTime()===f.getTime()){const w=d.id,b=l.id;return w.localeCompare(b)}return y.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}=dn(e);let l;if(s){const b=new Set;for(const p of s)(await this.getChildren(p)).forEach(_=>b.add(_));l=ln(s,b)}else l=new Set(Object.keys(this.documents));l=o?hn(o,l):l;for(const b of l){const p=this.documents[b];if(p&&!(a&&!a.has(p.header.documentType)))for(const[E]of Object.entries(p.state))d&&!d.has(E)||n.push({documentId:b,documentModelType:p.header.documentType,scope:E,branch:"main"})}let y=0;if(r){const b=n.findIndex(p=>p.documentId===r);b!==-1&&(y=b)}const f=Math.min(y+t,n.length),w=f<n.length?n[f].documentId:void 0;return{units:n.slice(y,f),nextCursor:w}}getManifest(e){return this.driveManifests[e]||(this.driveManifests[e]={documentIds:new Set}),this.driveManifests[e]}updateDriveManifest(e,t){this.driveManifests[e]=t}}class go{emitter=on();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 po(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 kt{static LISTENER_UPDATE_DELAY=250;logger=me(["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 w=l.syncUnits.get(f);if(!w||w.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=po(this._triggerUpdate.bind(this),kt.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 y=l.listener.transmitter;if(!y?.transmit)continue;const f=await this.getListenerSyncUnits(o,d),w=[];this.logger.verbose("syncUnits",f);const b=f.map(p=>async()=>{const E=l.syncUnits.get(p);if(E&&E.listenerRev>=p.revision){this.logger.verbose(`Abandoning push for sync unit ${JSON.stringify(p)}: already up-to-date (${E.listenerRev} >= ${p.revision})`);return}else this.logger.verbose(`Listener out-of-date for sync unit (${p.scope}, ${p.documentId}): ${E?.listenerRev} < ${p.revision}`);const _=[];if(p.revision>0){try{const A=await this.syncManager.getOperationData(p,{fromRevision:E?.listenerRev});_.push(...A)}catch(A){this.logger.error(A)}if(!_.length){this.logger.verbose(`Abandoning push for ${JSON.stringify(p)}: no operations found`);return}}w.push({driveId:o,documentType:p.documentType,documentId:p.documentId,branch:p.branch,operations:_,scope:p.scope})});if(this.options.sequentialUpdates){this.logger.verbose(`Collecting ${b.length} syncUnit strandUpdates in sequence`);for(const p of b)await p()}else this.logger.verbose(`Collecting ${b.length} syncUnit strandUpdates in parallel`),await Promise.all(b.map(p=>p()));if(w.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 p=await y.transmit(w,e);this.logger.verbose(`_triggerUpdate(source: ${e.type}) > transmission succeeded`,p),l.pendingTimeout="0",l.listenerStatus="PENDING";const E=new Date().toISOString();let _=!1;for(const A of p){const C=f.find(U=>A.documentId===U.documentId&&A.scope===U.scope&&A.branch===U.branch);if(C){l.syncUnits.set(C,{lastUpdated:E,listenerRev:A.revision});const U=w.find(F=>F.driveId===A.driveId&&F.documentId===A.documentId&&F.scope===A.scope&&F.branch===A.branch);if(U&&U.operations.length>0){const F=U.operations.at(-1)?.index;F!==A.revision?(this.logger.verbose(`Revision still out-of-date for ${U.documentId}:${U.scope}:${U.branch} ${F} <> ${A.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}`,A)}for(const A of p){const C=A.status==="ERROR";if(A.error?.includes("Missing operations"))_=!0;else if(C)throw new ie(A.status,void 0,A.error,A.error)}if(!_)s.push({listenerId:l.listener.listenerId,listenerRevisions:p});else{const A=await this._triggerUpdate(e,t,r,n-1);s.push(...A)}l.listenerStatus="SUCCESS"}catch(p){r?.(p,o,l),l.listenerStatus=p instanceof ie?p.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(y=>async()=>{if(a&&d>=a)return;if(y.revision<0){this.logger.verbose(`[SYNC DEBUG] Skipping sync unit with negative revision: ${JSON.stringify(y)}, revision: ${y.revision}`);return}const f=n.syncUnits.get(y);if(f&&f.listenerRev>=y.revision){this.logger.verbose(`[SYNC DEBUG] Skipping sync unit - listener already up to date: ${JSON.stringify(y)}, listenerRev: ${f.listenerRev}, revision: ${y.revision}`);return}const{documentId:w,scope:b,branch:p}=y;let E=[];try{y.revision>0&&(this.logger.verbose(`[SYNC DEBUG] Getting operations for syncUnit: ${JSON.stringify(y)}`),E=await this.syncManager.getOperationData(y,{since:r?.since,fromRevision:r?.fromRevision??f?.listenerRev,limit:a?a-d:void 0})),this.logger.verbose(`[SYNC DEBUG] Retrieved ${E.length} operations for syncUnit: ${JSON.stringify(y)}`),d+=E.length,s.push({driveId:e,documentId:w,documentType:y.documentType,scope:b,branch:p,operations:E}),this.logger.verbose(`[SYNC DEBUG] Added strand with ${E.length} operations for syncUnit: ${JSON.stringify(y)}`)}catch(_){this.logger.error(`Error getting operations for syncUnit: ${JSON.stringify(y)}, error: ${_}`);return}});if(this.options.sequentialUpdates){this.logger.verbose(`[SYNC DEBUG] Processing ${l.length} sync units sequentially`);for(const y of l)await y()}else this.logger.verbose(`[SYNC DEBUG] Processing ${l.length} sync units in parallel`),await Promise.all(l.map(y=>y()))}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 mo{storage;documentStorage;cache;documentModelModules;eventEmitter;syncStatus=new X;logger=me(["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:y}=await this.documentStorage.findStorageUnitsBy(o,100,a);d.push(...l),a=y}while(a);return d.reduce((l,{documentModelType:y,...f})=>f.scope==="local"?l:l.concat([{...f,documentType:y}]),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||_i(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=We(e.operations);return Nr(e.initialState,r,t.reducer,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 Oi(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,y])=>a[l]!==y)){const l=Object.entries(t).reduce((w,[b,p])=>({...w,[b]:w[b]==="INITIAL_SYNC"&&p==="SYNCING"?"INITIAL_SYNC":p}),a),y=this.getCombinedSyncUnitStatus(a),f=this.getCombinedSyncUnitStatus(l);this.syncStatus.set(o,l),y!==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 yo{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 un(t.callInfo.data,this.listenerManager)}case"Internal":throw new Error("Internal transmitter not implemented");default:return new ue(t,this.listenerManager)}}}let xo=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 fo),this.cache||(this.cache=new xs),this.queueManager||(this.queueManager=new Pi),this.eventEmitter||(this.eventEmitter=new go),this.synchronizationManager||(this.synchronizationManager=new mo(this.storage,this.storage,this.cache,this.documentModelModules,this.eventEmitter)),!this.listenerManager){const e={...ot,...this.options?.listenerManager};this.listenerManager=new kt(this.synchronizationManager,e)}return this.transmitterFactory||(this.transmitterFactory=new yo(this.listenerManager)),new ho(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 Mr(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=vo(a),l=r[o];l&&l.push(d),d!==a&&(e=!0)}return r},{global:[],local:[]});return e?{...i,operations:t}:i}function vo(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 Ct={exports:{}};var Or;function wo(){return Or||(Or=1,(function(i,e){(function(t){i.exports=t()})(function(){return(function t(r,n,s){function o(l,y){if(!n[l]){if(!r[l]){var f=typeof Ye=="function"&&Ye;if(!y&&f)return f(l,!0);if(a)return a(l,!0);var w=new Error("Cannot find module '"+l+"'");throw w.code="MODULE_NOT_FOUND",w}var b=n[l]={exports:{}};r[l][0].call(b.exports,function(p){var E=r[l][1][p];return o(E||p)},b,b.exports,t,r,n,s)}return n[l].exports}for(var a=typeof Ye=="function"&&Ye,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(p),y=s.document.createTextNode("");l.observe(y,{characterData:!0}),a=function(){y.data=d=++d%2}}else if(!s.setImmediate&&typeof s.MessageChannel<"u"){var f=new s.MessageChannel;f.port1.onmessage=p,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(){p(),_.onreadystatechange=null,_.parentNode.removeChild(_),_=null},s.document.documentElement.appendChild(_)}:a=function(){setTimeout(p,0)};var w,b=[];function p(){w=!0;for(var _,A,C=b.length;C;){for(A=b,b=[],_=-1;++_<C;)A[_]();C=b.length}w=!1}r.exports=E;function E(_){b.push(_)===1&&!w&&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"],y=["PENDING"];r.exports=f;function f(I){if(typeof I!="function")throw new TypeError("resolver must be a function");this.state=y,this.queue=[],this.outcome=void 0,I!==o&&E(this,I)}f.prototype.catch=function(I){return this.then(null,I)},f.prototype.then=function(I,P){if(typeof I!="function"&&this.state===l||typeof P!="function"&&this.state===d)return this;var L=new this.constructor(o);if(this.state!==y){var j=this.state===l?I:P;b(L,j,this.outcome)}else this.queue.push(new w(L,I,P));return L};function w(I,P,L){this.promise=I,typeof P=="function"&&(this.onFulfilled=P,this.callFulfilled=this.otherCallFulfilled),typeof L=="function"&&(this.onRejected=L,this.callRejected=this.otherCallRejected)}w.prototype.callFulfilled=function(I){a.resolve(this.promise,I)},w.prototype.otherCallFulfilled=function(I){b(this.promise,this.onFulfilled,I)},w.prototype.callRejected=function(I){a.reject(this.promise,I)},w.prototype.otherCallRejected=function(I){b(this.promise,this.onRejected,I)};function b(I,P,L){s(function(){var j;try{j=P(L)}catch(H){return a.reject(I,H)}j===I?a.reject(I,new TypeError("Cannot resolve promise with itself")):a.resolve(I,j)})}a.resolve=function(I,P){var L=_(p,P);if(L.status==="error")return a.reject(I,L.value);var j=L.value;if(j)E(I,j);else{I.state=l,I.outcome=P;for(var H=-1,K=I.queue.length;++H<K;)I.queue[H].callFulfilled(P)}return I},a.reject=function(I,P){I.state=d,I.outcome=P;for(var L=-1,j=I.queue.length;++L<j;)I.queue[L].callRejected(P);return I};function p(I){var P=I&&I.then;if(I&&(typeof I=="object"||typeof I=="function")&&typeof P=="function")return function(){P.apply(I,arguments)}}function E(I,P){var L=!1;function j(Y){L||(L=!0,a.reject(I,Y))}function H(Y){L||(L=!0,a.resolve(I,Y))}function K(){P(H,j)}var Z=_(K);Z.status==="error"&&j(Z.value)}function _(I,P){var L={};try{L.value=I(P),L.status="success"}catch(j){L.status="error",L.value=j}return L}f.resolve=A;function A(I){return I instanceof this?I:a.resolve(new this(o),I)}f.reject=C;function C(I){var P=new this(o);return a.reject(P,I)}f.all=U;function U(I){var P=this;if(Object.prototype.toString.call(I)!=="[object Array]")return this.reject(new TypeError("must be an array"));var L=I.length,j=!1;if(!L)return this.resolve([]);for(var H=new Array(L),K=0,Z=-1,Y=new this(o);++Z<L;)se(I[Z],Z);return Y;function se(le,D){P.resolve(le).then(R,function(B){j||(j=!0,a.reject(Y,B))});function R(B){H[D]=B,++K===L&&!j&&(j=!0,a.resolve(Y,H))}}}f.race=F;function F(I){var P=this;if(Object.prototype.toString.call(I)!=="[object Array]")return this.reject(new TypeError("must be an array"));var L=I.length,j=!1;if(!L)return this.resolve([]);for(var H=-1,K=new this(o);++H<L;)Z(I[H]);return K;function Z(Y){P.resolve(Y).then(function(se){j||(j=!0,a.resolve(K,se))},function(se){j||(j=!0,a.reject(K,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 y(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,m=new u,v=0;v<c.length;v+=1)m.append(c[v]);return m.getBlob(h.type)}}typeof Promise>"u"&&t(3);var f=Promise;function w(c,h){h&&c.then(function(u){h(null,u)},function(u){h(u)})}function b(c,h,u){typeof h=="function"&&c.then(h),typeof u=="function"&&c.catch(u)}function p(c){return typeof c!="string"&&(console.warn(c+" used as a key, but it is not a string."),c=String(c)),c}function E(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var _="local-forage-detect-blob-support",A=void 0,C={},U=Object.prototype.toString,F="readonly",I="readwrite";function P(c){for(var h=c.length,u=new ArrayBuffer(h),m=new Uint8Array(u),v=0;v<h;v++)m[v]=c.charCodeAt(v);return u}function L(c){return new f(function(h){var u=c.transaction(_,I),m=y([""]);u.objectStore(_).put(m,"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 A=="boolean"?f.resolve(A):L(c).then(function(h){return A=h,A})}function H(c){var h=C[c.name],u={};u.promise=new f(function(m,v){u.resolve=m,u.reject=v}),h.deferredOperations.push(u),h.dbReady?h.dbReady=h.dbReady.then(function(){return u.promise}):h.dbReady=u.promise}function K(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],m=u.deferredOperations.pop();if(m)return m.reject(h),m.promise}function Y(c,h){return new f(function(u,m){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(),m(g.error)},g.onsuccess=function(){var S=g.result;S.onversionchange=function(T){T.target.close()},u(S),K(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),m=c.version<c.db.version,v=c.version>c.db.version;if(m&&(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 m=new FileReader;m.onerror=u,m.onloadend=function(v){var g=btoa(v.target.result||"");h({__local_forage_encoded_blob:!0,data:g,type:c.type})},m.readAsBinaryString(c)})}function B(c){var h=P(atob(c.data));return y([h],{type:c.type})}function G(c){return c&&c.__local_forage_encoded_blob}function V(c){var h=this,u=h._initReady().then(function(){var m=C[h._dbInfo.name];if(m&&m.dbReady)return m.dbReady});return b(u,c,c),u}function z(c){H(c);for(var h=C[c.name],u=h.forages,m=0;m<u.length;m++){var v=u[m];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,m){m===void 0&&(m=1);try{var v=c.db.transaction(c.storeName,h);u(null,v)}catch(g){if(m>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,m-1)})}).catch(u);u(g)}}function _e(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function ze(c){var h=this,u={db:null};if(c)for(var m in c)u[m]=c[m];var v=C[u.name];v||(v=_e(),C[u.name]=v),v.forages.push(h),h._initReady||(h._initReady=h.ready,h.ready=V);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(N){return u.db=N,D(u,h._defaultConfig.version)?le(u):N}).then(function(N){u.db=v.db=N,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=p(c);var m=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 N=O.result;N===void 0&&(N=null),G(N)&&(N=B(N)),v(N)},O.onerror=function(){g(O.error)}}catch(N){g(N)}})}).catch(g)});return w(m,h),m}function ye(c,h){var u=this,m=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(),N=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,N++);J!==void 0?v(J):x.continue()}else v()},O.onerror=function(){g(O.error)}}catch(x){g(x)}})}).catch(g)});return w(m,h),m}function fn(c,h,u){var m=this;c=p(c);var v=new f(function(g,S){var T;m.ready().then(function(){return T=m._dbInfo,U.call(h)==="[object Blob]"?j(T.db).then(function(M){return M?h:R(h)}):h}).then(function(M){ae(m._dbInfo,I,function(O,N){if(O)return S(O);try{var x=N.objectStore(m._dbInfo.storeName);M===null&&(M=void 0);var k=x.put(M,c);N.oncomplete=function(){M===void 0&&(M=null),g(M)},N.onabort=N.onerror=function(){var J=k.error?k.error:k.transaction.error;S(J)}}catch(J){S(J)}})}).catch(S)});return w(v,u),v}function gn(c,h){var u=this;c=p(c);var m=new f(function(v,g){u.ready().then(function(){ae(u._dbInfo,I,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 N=O.error?O.error:O.transaction.error;g(N)}}catch(N){g(N)}})}).catch(g)});return w(m,h),m}function pn(c){var h=this,u=new f(function(m,v){h.ready().then(function(){ae(h._dbInfo,I,function(g,S){if(g)return v(g);try{var T=S.objectStore(h._dbInfo.storeName),M=T.clear();S.oncomplete=function(){m()},S.onabort=S.onerror=function(){var O=M.error?M.error:M.transaction.error;v(O)}}catch(O){v(O)}})}).catch(v)});return w(u,c),u}function mn(c){var h=this,u=new f(function(m,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(){m(M.result)},M.onerror=function(){v(M.error)}}catch(O){v(O)}})}).catch(v)});return w(u,c),u}function yn(c,h){var u=this,m=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,N=M.openKeyCursor();N.onsuccess=function(){var x=N.result;if(!x){v(null);return}c===0||O?v(x.key):(O=!0,x.advance(c))},N.onerror=function(){g(N.error)}}catch(x){g(x)}})}).catch(g)});return w(m,h),m}function vn(c){var h=this,u=new f(function(m,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 N=M.result;if(!N){m(O);return}O.push(N.key),N.continue()},M.onerror=function(){v(M.error)}}catch(N){v(N)}})}).catch(v)});return w(u,c),u}function wn(c,h){h=E.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 m=this,v;if(!c.name)v=f.reject("Invalid arguments");else{var g=c.name===u.name&&m._dbInfo.db,S=g?f.resolve(m._dbInfo.db):se(c).then(function(T){var M=C[c.name],O=M.forages;M.db=T;for(var N=0;N<O.length;N++)O[N]._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],N=O.forages;T.close();for(var x=0;x<N.length;x++){var k=N[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(de){var Le=ee.result;Le.close(),re(de)},ee.onupgradeneeded=function(){var de=ee.result;de.deleteObjectStore(c.storeName)},ee.onsuccess=function(){var de=ee.result;de.close(),Q(de)}});return J.then(function(Q){O.db=Q;for(var re=0;re<N.length;re++){var ee=N[re];ee._dbInfo.db=Q,K(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 N=0;N<O.length;N++){var x=O[N];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];K(re._dbInfo)}}).catch(function(J){throw(Z(c,J)||f.resolve()).catch(function(){}),J})})}return w(v,h),v}var bn={_driver:"asyncStorage",_initStorage:ze,_support:l(),iterate:ye,getItem:ne,setItem:fn,removeItem:gn,clear:pn,length:mn,key:yn,keys:vn,dropInstance:wn};function Dn(){return typeof openDatabase=="function"}var be="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Sn="~~local_forage_type~",qt=/^~~local_forage_type~([^~]+)~/,je="__lfsc__:",lt=je.length,ht="arbf",ft="blob",zt="si08",jt="ui08",Ht="uic8",Gt="si16",Jt="si32",Yt="ur16",Qt="ui32",Kt="fl32",Vt="fl64",Wt=lt+ht.length,Xt=Object.prototype.toString;function Zt(c){var h=c.length*.75,u=c.length,m,v=0,g,S,T,M;c[c.length-1]==="="&&(h--,c[c.length-2]==="="&&h--);var O=new ArrayBuffer(h),N=new Uint8Array(O);for(m=0;m<u;m+=4)g=be.indexOf(c[m]),S=be.indexOf(c[m+1]),T=be.indexOf(c[m+2]),M=be.indexOf(c[m+3]),N[v++]=g<<2|S>>4,N[v++]=(S&15)<<4|T>>2,N[v++]=(T&3)<<6|M&63;return O}function gt(c){var h=new Uint8Array(c),u="",m;for(m=0;m<h.length;m+=3)u+=be[h[m]>>2],u+=be[(h[m]&3)<<4|h[m+1]>>4],u+=be[(h[m+1]&15)<<2|h[m+2]>>6],u+=be[h[m+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 En(c,h){var u="";if(c&&(u=Xt.call(c)),c&&(u==="[object ArrayBuffer]"||c.buffer&&Xt.call(c.buffer)==="[object ArrayBuffer]")){var m,v=je;c instanceof ArrayBuffer?(m=c,v+=ht):(m=c.buffer,u==="[object Int8Array]"?v+=zt:u==="[object Uint8Array]"?v+=jt:u==="[object Uint8ClampedArray]"?v+=Ht:u==="[object Int16Array]"?v+=Gt:u==="[object Uint16Array]"?v+=Yt:u==="[object Int32Array]"?v+=Jt:u==="[object Uint32Array]"?v+=Qt:u==="[object Float32Array]"?v+=Kt:u==="[object Float64Array]"?v+=Vt:h(new Error("Failed to get type for BinaryArray"))),h(v+gt(m))}else if(u==="[object Blob]"){var g=new FileReader;g.onload=function(){var S=Sn+c.type+"~"+gt(this.result);h(je+ft+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 In(c){if(c.substring(0,lt)!==je)return JSON.parse(c);var h=c.substring(Wt),u=c.substring(lt,Wt),m;if(u===ft&&qt.test(h)){var v=h.match(qt);m=v[1],h=h.substring(v[0].length)}var g=Zt(h);switch(u){case ht:return g;case ft:return y([g],{type:m});case zt:return new Int8Array(g);case jt:return new Uint8Array(g);case Ht:return new Uint8ClampedArray(g);case Gt:return new Int16Array(g);case Yt:return new Uint16Array(g);case Jt:return new Int32Array(g);case Qt:return new Uint32Array(g);case Kt:return new Float32Array(g);case Vt:return new Float64Array(g);default:throw new Error("Unkown type: "+u)}}var pt={serialize:En,deserialize:In,stringToBuffer:Zt,bufferToString:gt};function er(c,h,u,m){c.executeSql("CREATE TABLE IF NOT EXISTS "+h.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],u,m)}function Tn(c){var h=this,u={db:null};if(c)for(var m in c)u[m]=typeof c[m]!="string"?c[m].toString():c[m];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){er(T,u,function(){h._dbInfo=u,g()},function(M,O){S(O)})},S)});return u.serializer=pt,v}function De(c,h,u,m,v,g){c.executeSql(u,m,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):er(M,h,function(){M.executeSql(u,m,v,g)},g)},g):g(S,T)},g)}function Rn(c,h){var u=this;c=p(c);var m=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 N=O.rows.length?O.rows.item(0).value:null;N&&(N=S.serializer.deserialize(N)),v(N)},function(M,O){g(O)})})}).catch(g)});return w(m,h),m}function Mn(c,h){var u=this,m=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 N=O.rows,x=N.length,k=0;k<x;k++){var J=N.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 w(m,h),m}function tr(c,h,u,m){var v=this;c=p(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(N,x){x?T(x):O.db.transaction(function(k){De(k,O,"INSERT OR REPLACE INTO "+O.storeName+" (key, value) VALUES (?, ?)",[c,N],function(){S(M)},function(J,Q){T(Q)})},function(k){if(k.code===k.QUOTA_ERR){if(m>0){S(tr.apply(v,[c,M,u,m-1]));return}T(k)}})})}).catch(T)});return w(g,u),g}function On(c,h,u){return tr.apply(this,[c,h,u,1])}function _n(c,h){var u=this;c=p(c);var m=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 w(m,h),m}function An(c){var h=this,u=new f(function(m,v){h.ready().then(function(){var g=h._dbInfo;g.db.transaction(function(S){De(S,g,"DELETE FROM "+g.storeName,[],function(){m()},function(T,M){v(M)})})}).catch(v)});return w(u,c),u}function Nn(c){var h=this,u=new f(function(m,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;m(O)},function(T,M){v(M)})})}).catch(v)});return w(u,c),u}function Cn(c,h){var u=this,m=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 N=O.rows.length?O.rows.item(0).key:null;v(N)},function(M,O){g(O)})})}).catch(g)});return w(m,h),m}function xn(c){var h=this,u=new f(function(m,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=[],N=0;N<M.rows.length;N++)O.push(M.rows.item(N).key);m(O)},function(T,M){v(M)})})}).catch(v)});return w(u,c),u}function $n(c){return new f(function(h,u){c.transaction(function(m){m.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(m){u(m)})})}function Pn(c,h){h=E.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 m=this,v;return c.name?v=new f(function(g){var S;c.name===u.name?S=m._dbInfo.db:S=openDatabase(c.name,"","",0),c.storeName?g({db:S,storeNames:[c.storeName]}):g($n(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,de){re(de)})})}for(var N=[],x=0,k=g.storeNames.length;x<k;x++)N.push(O(g.storeNames[x]));f.all(N).then(function(){S()}).catch(function(J){T(J)})},function(M){T(M)})})}):v=f.reject("Invalid arguments"),w(v,h),v}var Ln={_driver:"webSQLStorage",_initStorage:Tn,_support:Dn(),iterate:Mn,getItem:Rn,setItem:On,removeItem:_n,clear:An,length:Nn,key:Cn,keys:xn,dropInstance:Pn};function Un(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}function rr(c,h){var u=c.name+"/";return c.storeName!==h.storeName&&(u+=c.storeName+"/"),u}function Bn(){var c="_localforage_support_test";try{return localStorage.setItem(c,!0),localStorage.removeItem(c),!1}catch{return!0}}function Fn(){return!Bn()||localStorage.length>0}function kn(c){var h=this,u={};if(c)for(var m in c)u[m]=c[m];return u.keyPrefix=rr(c,h._defaultConfig),Fn()?(h._dbInfo=u,u.serializer=pt,f.resolve()):f.reject()}function qn(c){var h=this,u=h.ready().then(function(){for(var m=h._dbInfo.keyPrefix,v=localStorage.length-1;v>=0;v--){var g=localStorage.key(v);g.indexOf(m)===0&&localStorage.removeItem(g)}});return w(u,c),u}function zn(c,h){var u=this;c=p(c);var m=u.ready().then(function(){var v=u._dbInfo,g=localStorage.getItem(v.keyPrefix+c);return g&&(g=v.serializer.deserialize(g)),g});return w(m,h),m}function jn(c,h){var u=this,m=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 N=localStorage.key(O);if(N.indexOf(g)===0){var x=localStorage.getItem(N);if(x&&(x=v.serializer.deserialize(x)),x=c(x,N.substring(S),M++),x!==void 0)return x}}});return w(m,h),m}function Hn(c,h){var u=this,m=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 w(m,h),m}function Gn(c){var h=this,u=h.ready().then(function(){for(var m=h._dbInfo,v=localStorage.length,g=[],S=0;S<v;S++){var T=localStorage.key(S);T.indexOf(m.keyPrefix)===0&&g.push(T.substring(m.keyPrefix.length))}return g});return w(u,c),u}function Jn(c){var h=this,u=h.keys().then(function(m){return m.length});return w(u,c),u}function Yn(c,h){var u=this;c=p(c);var m=u.ready().then(function(){var v=u._dbInfo;localStorage.removeItem(v.keyPrefix+c)});return w(m,h),m}function Qn(c,h,u){var m=this;c=p(c);var v=m.ready().then(function(){h===void 0&&(h=null);var g=h;return new f(function(S,T){var M=m._dbInfo;M.serializer.serialize(h,function(O,N){if(N)T(N);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 w(v,u),v}function Kn(c,h){if(h=E.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 m=this,v;return c.name?v=new f(function(g){c.storeName?g(rr(c,m._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"),w(v,h),v}var Vn={_driver:"localStorageWrapper",_initStorage:kn,_support:Un(),iterate:jn,getItem:zn,setItem:Qn,removeItem:Yn,clear:qn,length:Jn,key:Hn,keys:Gn,dropInstance:Kn},Wn=function(h,u){return h===u||typeof h=="number"&&typeof u=="number"&&isNaN(h)&&isNaN(u)},Xn=function(h,u){for(var m=h.length,v=0;v<m;){if(Wn(h[v],u))return!0;v++}return!1},nr=Array.isArray||function(c){return Object.prototype.toString.call(c)==="[object Array]"},Pe={},sr={},Ae={INDEXEDDB:bn,WEBSQL:Ln,LOCALSTORAGE:Vn},Zn=[Ae.INDEXEDDB._driver,Ae.WEBSQL._driver,Ae.LOCALSTORAGE._driver],He=["dropInstance"],mt=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(He),es={description:"",driver:Zn.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function ts(c,h){c[h]=function(){var u=arguments;return c.ready().then(function(){return c[h].apply(c,u)})}}function yt(){for(var c=1;c<arguments.length;c++){var h=arguments[c];if(h)for(var u in h)h.hasOwnProperty(u)&&(nr(h[u])?arguments[0][u]=h[u].slice():arguments[0][u]=h[u])}return arguments[0]}var rs=(function(){function c(h){o(this,c);for(var u in Ae)if(Ae.hasOwnProperty(u)){var m=Ae[u],v=m._driver;this[u]=v,Pe[v]||this.defineDriver(m)}this._defaultConfig=yt({},es),this._config=yt({},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 m in u){if(m==="storeName"&&(u[m]=u[m].replace(/\W/g,"_")),m==="version"&&typeof u[m]!="number")return new Error("Database version must be a number.");this._config[m]=u[m]}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,m,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 N=mt.concat("_initStorage"),x=0,k=N.length;x<k;x++){var J=N[x],Q=!Xn(He,J);if((Q||u[J])&&typeof u[J]!="function"){T(O);return}}var re=function(){for(var Le=function(is){return function(){var os=new Error("Method "+is+" is not implemented by the current driver"),ir=f.reject(os);return w(ir,arguments[arguments.length-1]),ir}},vt=0,ss=He.length;vt<ss;vt++){var wt=He[vt];u[wt]||(u[wt]=Le(wt))}};re();var ee=function(Le){Pe[M]&&console.info("Redefining LocalForage driver: "+M),Pe[M]=u,sr[M]=Le,S()};"_support"in u?u._support&&typeof u._support=="function"?u._support().then(ee,T):ee(!!u._support):ee(!0)}catch(de){T(de)}});return b(g,m,v),g},c.prototype.driver=function(){return this._driver||null},c.prototype.getDriver=function(u,m,v){var g=Pe[u]?f.resolve(Pe[u]):f.reject(new Error("Driver not found."));return b(g,m,v),g},c.prototype.getSerializer=function(u){var m=f.resolve(pt);return b(m,u),m},c.prototype.ready=function(u){var m=this,v=m._driverSet.then(function(){return m._ready===null&&(m._ready=m._initDriver()),m._ready});return b(v,u,u),v},c.prototype.setDriver=function(u,m,v){var g=this;nr(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 N=this._driverSet!==null?this._driverSet.catch(function(){return f.resolve()}):f.resolve();return this._driverSet=N.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}),b(this._driverSet,m,v),this._driverSet},c.prototype.supports=function(u){return!!sr[u]},c.prototype._extend=function(u){yt(this,u)},c.prototype._getSupportedDrivers=function(u){for(var m=[],v=0,g=u.length;v<g;v++){var S=u[v];this.supports(S)&&m.push(S)}return m},c.prototype._wrapLibraryMethodsWithReady=function(){for(var u=0,m=mt.length;u<m;u++)ts(this,mt[u])},c.prototype.createInstance=function(u){return new c(u)},c})(),ns=new rs;r.exports=ns},{3:3}]},{},[4])(4)})})(Ct)),Ct.exports}var bo=wo();const _r=Pt(bo);class te{logger=me(["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=_r.ready().then(()=>_r.createInstance({name:e?`${e}:${te.DBName}`:te.DBName}))}async findStorageUnitsBy(e,t,r){const n=[],{parentId:s,documentId:o,documentModelType:a,scope:d}=dn(e),f=(await(await this.db).keys()).filter(_=>_.startsWith(`${te.DOCUMENT_KEY}${te.SEP}`)).map(_=>_.slice(te.DOCUMENT_KEY.length+te.SEP.length));let w;if(s){const _=new Set;for(const A of s)(await this.getChildren(A)).forEach(U=>_.add(U));w=ln(s,_)}else w=new Set(f);w=o?hn(o,w):w;for(const _ of w){const A=await this.get(_).catch(()=>null);if(A&&!(a&&!a.has(A.header.documentType)))for(const[C]of Object.entries(A.state))d&&!d.has(C)||n.push({documentId:_,documentModelType:A.header.documentType,scope:C,branch:"main"})}let b=0;if(r){const _=n.findIndex(A=>A.documentId===r);_!==-1&&(b=_)}const p=Math.min(b+t,n.length),E=p<n.length?n[p].documentId:void 0;return{units:n.slice(b,p),nextCursor:E}}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,r=await this.db;if(await this.exists(t))throw new qe(t);const n=e.header.slug&&e.header.slug.length>0?e.header.slug:t;if((await this.getSlugManifest()).slugToId[n])throw new qe(t,ke.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 w=f.slice(te.DOCUMENT_KEY.length+te.SEP.length);try{const b=await n.getItem(f);if(!b||b.header.documentType!==e)continue;a.push({id:w,document:b})}catch{continue}}a.sort((f,w)=>{const b=new Date(f.document.header.createdAtUtcIso),p=new Date(w.document.header.createdAtUtcIso);return b.getTime()===p.getTime()?f.id.localeCompare(w.id):b.getTime()-p.getTime()});let d=0;if(r){const f=a.findIndex(({id:w})=>w===r);f!==-1&&(d=f)}const l=Math.min(d+t,a.length);let y;return l<a.length&&(y=a[l].id),{documents:a.slice(d,l).map(({id:f})=>f),nextCursor:y}}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=Mr(t);if(r!==t)return(await this.db).setItem(this.buildDocumentKey(e),r)}async migrateDocument(e,t){const r=await this.get(t),n=Mr(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,Pi as E,xs as I,fo as M,ue as P,xo as R,Oi as S,Ys as a,Qs as b,ai as c,Ks as d,Xs as e,ri as f,Mo as g,Ne as h,dr as i,ei as j,si as k,fe as l,Zs as m,Ri as n,Co as o,Qe as p,Oo as q,Xr as r,Vr as s,me as t,Ws as u,Ii as v,_o as w,cn as x,Ao as y};
316
+ `,{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:io(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 Rr(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 At(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 Nt(i){return{id:oo(i),documentType:ao(i),document:co(i)}}function oo(i){return"id"in i?i.id:"header"in i?i.header.id:"document"in i?i.document.header.id:void 0}function ao(i){return"documentType"in i?i.documentType:"header"in i?i.header.documentType:i.document.header.documentType}function co(i){return"document"in i?i.document:void 0}function uo(i){return["LOCAL","CLOUD","PUBLIC"].includes(i)}function Co(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"||!uo(r)?"LOCAL":r}class lo{logger=me(["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 ve(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 ve(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=Ue(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 y=l instanceof Error?l:new Error(JSON.stringify(l));return{status:"ERROR",error:new ie("ERROR",void 0,`Error creating document: ${y.message}`,y),operations:[],document:void 0,signals:[]}}},processJob:async e=>{if(an(e))return this.queueDelegate.processOperationJob(e);if($i(e))return this.queueDelegate.processActionJob(e);if(Xe(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?Bt:l.taskQueueMethod,featureFlags:{...l?.featureFlags}},this.enableDualActionCreate=l?.featureFlags?.enableDualActionCreate??!1,this.enableDualActionCreate&&this.logger.warn("Dual action create is enabled."),this.defaultDrivesManager=new Zi(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(ue.isPullResponderTrigger(s)){let o=!0;const a=ue.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(y=>y.status!=="SUCCESS").length<1&&this.synchronizationManager.updateSyncStatus(e,{pull:"SUCCESS"});for(const y of d){const{documentId:f,scope:w,branch:b,status:p,error:E}=y;this.synchronizationManager.updateSyncStatus({documentId:f,scope:w,branch:b},{pull:p},E)}if(o){o=!1,(await this.synchronizationManager.getSynchronizationUnitsIds(e)).filter(b=>!d.find(p=>p.documentId===b.documentId&&p.scope===b.scope&&p.branch===b.branch)).forEach(b=>{this.synchronizationManager.updateSyncStatus(b,{pull:"SUCCESS"})});const w=n.state.local.listeners.find(b=>s.data.url===b.callInfo?.data);if(w)for(const b of d){const{documentId:p,scope:E,branch:_}=b;this.listenerManager.updateListenerRevision(w.listenerId,e,{documentId:p,scope:E,branch:_},b.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 un(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 ue(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}=Ut(),n=nn({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 Fe(e,this),{pullFilter:d,pullInterval:l,availableOffline:y,sharingType:f,listeners:w,triggers:b}=t,p=await ue.createPullResponderTrigger(r,e,{pullFilter:d,pullInterval:l},this.listeners);return await this.addDrive({id:r,slug:s,global:{name:n,icon:o},local:{triggers:[...b,p],listeners:w,availableOffline:y,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&&ve(o)&&(r=o,At(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(ve(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(ve(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&&At(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}=Nt(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=Ue(e.id,n));else if("header"in e)await Ge(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 Ge(s.header):this.logger.warn("Creating a document with an unsigned id is deprecated. Use createSignedHeaderForSigner."),d=s.header}else d=Ue(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 y=Object.values(a.operations).flat();y.length&&(ve(a)?await this.legacyStorage.addDriveOperations(d.id,y,a):await this.legacyStorage.addDocumentOperations(d.id,y,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}=Nt(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=Ue(e.id,n));else if("header"in e)await Ge(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 Ge(s.header),l=!0):this.logger.warn("Creating a document with an unsigned id is deprecated. Use createSignedHeaderForSigner."),d=s.header}else d=Ue(void 0,n),l=!1;r&&(d.meta={...d.meta,...r});const y=1,f=o??a.state,w=Object.values(a.operations).flat(),b=w.length===0;let p=[];if(b){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,I={model:n,version:0,documentId:d.id,signing:F},P={id:$e(),type:"CREATE_DOCUMENT",timestampUtcMs:U,input:I,scope:"document"},L={model:n,fromVersion:0,toVersion:y,documentId:d.id,initialState:f},j={id:$e(),type:"UPGRADE_DOCUMENT",timestampUtcMs:U,input:L,scope:"document"},K={state:$t()},Z=or(K,"document"),se=or({state:f},"document");p=[{id:Ve(d.id,"document","main",P.id),index:0,skip:0,hash:Z,timestampUtcMs:U,action:P},{id:Ve(d.id,"document","main",j.id),index:1,skip:0,hash:se,timestampUtcMs:U,action:j}]}else p=w;const E=ar(p);E.header||(E.header=[]),E.document||(E.document=[]),E.global||(E.global=[]),E.local||(E.local=[]);const A={header:d,operations:E,initialState:f,clipboard:[],state:f};await this.documentStorage.create(A);const C=await this.getDocument(A.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=ar(r);for(const y of Object.keys(l)){const f=t.operations[y]||[],w=ps(l[y]||[],f);if(w.length<1)continue;const b=bt(Je(f)),[p,E]=ms(b,w),A=(E.length<1?p:ys(b,p,Ds)).filter(C=>b.length<1||vs(b[b.length-1],C));for(const C of A){let U=!1;if(E.length>0){const F=r.find(I=>I.hash===C.hash);U=!F||F.index!==C.index||F.skip!==C.skip}try{const F=this.options.taskQueueMethod,I=()=>this._performOperation(e,a,C,U),P=await(F?xt(I,F):I());a=P.document,s.push(...P.signals),n.push(P.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?Rr(e.operations,r.revisions):e.operations,s=We(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(ve(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)&&At(e,t?.revisions))return e;const r=this.getDocumentModelModule(e.header.documentType),n=t?.revisions!==void 0?Rr(e.operations,t.revisions):e.operations,s=We(n),o=Object.keys(s),a=new Set([...o,"global","local"]),d={},l={};for(const p of a)d[p]=[],l[p]=[];for(const[p,E]of Object.entries(s))if(E)for(const _ of E)if(_.action.type==="CREATE_DOCUMENT"||_.action.type==="UPGRADE_DOCUMENT"){const A=d[p];A&&A.push(_)}else{const A=l[p];A&&A.push(_)}let y=e.header;if(t?.revisions){const p={...e.header.revision};for(const E of Object.keys(t.revisions)){const _=s[E]??[];if(_.length===0)delete p[E];else{const A=_.at(-1);p[E]=A?A.index+1:0}}y={...e.header,revision:p}}const f=Nr(e.initialState,l,r.reducer,y,void 0,{},{...t,checkHashes:t?.checkHashes??!0,reuseOperationResultingState:t?.checkHashes??!0}),w=new Set([...Object.keys(s),...Object.keys(d),...Object.keys(f.operations)]),b={};for(const p of w)b[p]=[...d[p]||[],...f.operations[p]||[]];return{...f,operations:b,clipboard:e.clipboard??[]}}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]||[],w=We({...t.operations,[d]:ws(l,r)})[d]?.at(-1);w&&!w.resultingState&&(w.resultingState=await(ve(t)?this.legacyStorage.getOperationResultingState?.(e,w.index,w.action.scope,"main"):this.legacyStorage.getDriveOperationResultingState?.(e,w.index,w.action.scope,"main")));const b=a.operations[d]||[],p=[];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&&p.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=bt(Je(C)),F=bt(Je(b)),I=bs(F,U);a={...a,clipboard:Je(I.filter(P=>P.action.type!=="NOOP")).reverse()}}const E=a.operations[r.action.scope];if(!E)throw new ie("ERROR",r,`No operations found for scope: ${r.action.scope}`);const A=E.filter(C=>C.index==r.index&&C.skip==r.skip).at(0);if(!A)throw new ie("ERROR",r,`Operation with index ${r.index}:${r.skip} was not applied.`);if(!A.error&&A.hash!==r.hash&&!n)throw this.logger.warn(JSON.stringify(A,null,2)),new Mi(r,A);for(const C of p){const U=await C();o.push(U)}return{document:a,signals:o,operation:A}}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}=Nt(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 qe(r);let a;const d=new Promise((l,y)=>{const f=this.queueManager.on("jobCompleted",(b,p)=>{b.jobId===a&&(f(),w(),l(p))}),w=this.queueManager.on("jobFailed",(b,p)=>{b.jobId===a&&(f(),w(),y(p))})});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,w)=>{f.jobId===s&&(l(),y(),a(w))}),y=this.queueManager.on("jobFailed",(f,w)=>{f.jobId===s&&(l(),y(),d(w))})});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,y)=>{l.jobId===n&&(a(),d(),s(y))}),d=this.queueManager.on("jobFailed",(l,y)=>{l.jobId===n&&(a(),d(),o(y))})})}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,y)=>{l.jobId===n&&(a(),d(),s(y))}),d=this.queueManager.on("jobFailed",(l,y)=>{l.jobId===n&&(a(),d(),o(y))})})}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 b=>{const p=await this._processOperations(e,b,t);if(!p.document)throw this.logger.error("Invalid document"),p.error??new Error("Invalid document");return s=p.document,d=p.error,a.push(...p.signals),o.push(...p.operationsApplied),{operations:p.operationsApplied,document:p.document}});const l=new Array;if(s){this.cache.setDocument(e,s).catch(this.logger.error);for(const b of o){const p={documentId:e,documentType:s.header.documentType,scope:b.action.scope,branch:"main",revision:b.index+1,lastUpdated:b.timestampUtcMs};l.some(_=>_.documentId===p.documentId&&_.scope===p.scope&&_.branch===p.branch)||l.push(p)}}const f=o.find(b=>!t.find(p=>p.id===b.id&&p.index===b.index&&p.skip===b.skip&&p.hash===b.hash))?{type:"local"}:r?.source??{type:"local"},w=this.getOperationSource(f);if(l.length&&this.listenerManager.updateSynchronizationRevisions(l,f,()=>{this.synchronizationManager.updateSyncStatus(e,{[w]:"SYNCING"});for(const b of l)this.synchronizationManager.updateSyncStatus(b,{[w]:"SYNCING"})},this.handleListenerError.bind(this),r?.forceSync??f.type==="local").then(b=>{b.length&&this.synchronizationManager.updateSyncStatus(e,{[w]:"SUCCESS"});for(const p of l)this.synchronizationManager.updateSyncStatus(p,{[w]:"SUCCESS"})}).catch(b=>{this.logger.error("Non handled error updating sync revision",b),this.synchronizationManager.updateSyncStatus(e,{[w]:"ERROR"},b);for(const p of l)this.synchronizationManager.updateSyncStatus(p,{[w]:"ERROR"},b)}),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 y=l instanceof ie?l:new ie("ERROR",void 0,l.message,l.cause);return{status:y.status,error:y,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",(y,f)=>{y.jobId===s&&(d(),l(),o(f))}),l=this.queueManager.on("jobFailed",(y,f)=>{y.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 y=>{const f=await this._processOperations(e,y,t.slice());return n=f.document,s.push(...f.operationsApplied),o.push(...f.signals),a=f.error,{operations:f.operationsApplied,document:f.document}}),!n||!ve(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(y=>y.action.scope==="global").slice().pop();if(l){const f=s.find(b=>!t.find(p=>p.id===b.id&&p.index===b.index&&p.skip===b.skip&&p.hash===b.hash))?{type:"local"}:r?.source??{type:"local"},w=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,{[w]:"SYNCING"})},this.handleListenerError.bind(this),r?.forceSync??f.type==="local").then(b=>{b.length&&this.synchronizationManager.updateSyncStatus(e,{[w]:"SUCCESS"})}).catch(b=>{this.logger.error("Non handled error updating sync revision",b),this.synchronizationManager.updateSyncStatus(e,{[w]:"ERROR"},b)})}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 y=l instanceof ie?l:new ie("ERROR",void 0,l.message,l);return{status:y.status,error:y,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,Zr({listenerId:s.listenerId}));for(const s of n)await this.addDriveAction(e,en({triggerId:s.id}));await this.addDriveAction(e,Xr({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,id:o.id??Ve(e.documentId,e.scope,e.branch,o.actionId),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 ho=Wi(lo);class at extends Error{constructor(e){super(e||"Aborted"),this.name="AbortError"}}const Be=i=>i&&i.length>0&&!i.includes("*")?new Set(i):null,dn=i=>({parentId:Be(i.parentId),documentId:Be(i.documentId),documentModelType:Be(i.documentModelType),scope:Be(i.scope),branch:Be(i.branch)}),ln=(i,...e)=>{const t=new Set(i);for(const r of e)for(const n of r)t.add(n);return t},hn=(i,e)=>{const t=new Set;for(const r of i)e.has(r)&&t.add(r);return t};class fo{logger=me(["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(this.documents[t])throw new qe(t);const r=e.header.slug?.length>0?e.header.slug:t;if(r&&this.slugToDocumentId[r])throw new qe(t,ke.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 y=new Date(d.document.header.createdAtUtcIso),f=new Date(l.document.header.createdAtUtcIso);if(y.getTime()===f.getTime()){const w=d.id,b=l.id;return w.localeCompare(b)}return y.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}=dn(e);let l;if(s){const b=new Set;for(const p of s)(await this.getChildren(p)).forEach(_=>b.add(_));l=ln(s,b)}else l=new Set(Object.keys(this.documents));l=o?hn(o,l):l;for(const b of l){const p=this.documents[b];if(p&&!(a&&!a.has(p.header.documentType)))for(const[E]of Object.entries(p.state))d&&!d.has(E)||n.push({documentId:b,documentModelType:p.header.documentType,scope:E,branch:"main"})}let y=0;if(r){const b=n.findIndex(p=>p.documentId===r);b!==-1&&(y=b)}const f=Math.min(y+t,n.length),w=f<n.length?n[f].documentId:void 0;return{units:n.slice(y,f),nextCursor:w}}getManifest(e){return this.driveManifests[e]||(this.driveManifests[e]={documentIds:new Set}),this.driveManifests[e]}updateDriveManifest(e,t){this.driveManifests[e]=t}}class go{emitter=on();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 po(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 kt{static LISTENER_UPDATE_DELAY=250;logger=me(["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 w=l.syncUnits.get(f);if(!w||w.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=po(this._triggerUpdate.bind(this),kt.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 y=l.listener.transmitter;if(!y?.transmit)continue;const f=await this.getListenerSyncUnits(o,d),w=[];this.logger.verbose("syncUnits",f);const b=f.map(p=>async()=>{const E=l.syncUnits.get(p);if(E&&E.listenerRev>=p.revision){this.logger.verbose(`Abandoning push for sync unit ${JSON.stringify(p)}: already up-to-date (${E.listenerRev} >= ${p.revision})`);return}else this.logger.verbose(`Listener out-of-date for sync unit (${p.scope}, ${p.documentId}): ${E?.listenerRev} < ${p.revision}`);const _=[];if(p.revision>0){try{const A=await this.syncManager.getOperationData(p,{fromRevision:E?.listenerRev});_.push(...A)}catch(A){this.logger.error(A)}if(!_.length){this.logger.verbose(`Abandoning push for ${JSON.stringify(p)}: no operations found`);return}}w.push({driveId:o,documentType:p.documentType,documentId:p.documentId,branch:p.branch,operations:_,scope:p.scope})});if(this.options.sequentialUpdates){this.logger.verbose(`Collecting ${b.length} syncUnit strandUpdates in sequence`);for(const p of b)await p()}else this.logger.verbose(`Collecting ${b.length} syncUnit strandUpdates in parallel`),await Promise.all(b.map(p=>p()));if(w.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 p=await y.transmit(w,e);this.logger.verbose(`_triggerUpdate(source: ${e.type}) > transmission succeeded`,p),l.pendingTimeout="0",l.listenerStatus="PENDING";const E=new Date().toISOString();let _=!1;for(const A of p){const C=f.find(U=>A.documentId===U.documentId&&A.scope===U.scope&&A.branch===U.branch);if(C){l.syncUnits.set(C,{lastUpdated:E,listenerRev:A.revision});const U=w.find(F=>F.driveId===A.driveId&&F.documentId===A.documentId&&F.scope===A.scope&&F.branch===A.branch);if(U&&U.operations.length>0){const F=U.operations.at(-1)?.index;F!==A.revision?(this.logger.verbose(`Revision still out-of-date for ${U.documentId}:${U.scope}:${U.branch} ${F} <> ${A.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}`,A)}for(const A of p){const C=A.status==="ERROR";if(A.error?.includes("Missing operations"))_=!0;else if(C)throw new ie(A.status,void 0,A.error,A.error)}if(!_)s.push({listenerId:l.listener.listenerId,listenerRevisions:p});else{const A=await this._triggerUpdate(e,t,r,n-1);s.push(...A)}l.listenerStatus="SUCCESS"}catch(p){r?.(p,o,l),l.listenerStatus=p instanceof ie?p.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(y=>async()=>{if(a&&d>=a)return;if(y.revision<0){this.logger.verbose(`[SYNC DEBUG] Skipping sync unit with negative revision: ${JSON.stringify(y)}, revision: ${y.revision}`);return}const f=n.syncUnits.get(y);if(f&&f.listenerRev>=y.revision){this.logger.verbose(`[SYNC DEBUG] Skipping sync unit - listener already up to date: ${JSON.stringify(y)}, listenerRev: ${f.listenerRev}, revision: ${y.revision}`);return}const{documentId:w,scope:b,branch:p}=y;let E=[];try{y.revision>0&&(this.logger.verbose(`[SYNC DEBUG] Getting operations for syncUnit: ${JSON.stringify(y)}`),E=await this.syncManager.getOperationData(y,{since:r?.since,fromRevision:r?.fromRevision??f?.listenerRev,limit:a?a-d:void 0})),this.logger.verbose(`[SYNC DEBUG] Retrieved ${E.length} operations for syncUnit: ${JSON.stringify(y)}`),d+=E.length,s.push({driveId:e,documentId:w,documentType:y.documentType,scope:b,branch:p,operations:E}),this.logger.verbose(`[SYNC DEBUG] Added strand with ${E.length} operations for syncUnit: ${JSON.stringify(y)}`)}catch(_){this.logger.error(`Error getting operations for syncUnit: ${JSON.stringify(y)}, error: ${_}`);return}});if(this.options.sequentialUpdates){this.logger.verbose(`[SYNC DEBUG] Processing ${l.length} sync units sequentially`);for(const y of l)await y()}else this.logger.verbose(`[SYNC DEBUG] Processing ${l.length} sync units in parallel`),await Promise.all(l.map(y=>y()))}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 mo{storage;documentStorage;cache;documentModelModules;eventEmitter;syncStatus=new X;logger=me(["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:y}=await this.documentStorage.findStorageUnitsBy(o,100,a);d.push(...l),a=y}while(a);return d.reduce((l,{documentModelType:y,...f})=>f.scope==="local"?l:l.concat([{...f,documentType:y}]),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||_i(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=We(e.operations);return Nr(e.initialState,r,t.reducer,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 Oi(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,y])=>a[l]!==y)){const l=Object.entries(t).reduce((w,[b,p])=>({...w,[b]:w[b]==="INITIAL_SYNC"&&p==="SYNCING"?"INITIAL_SYNC":p}),a),y=this.getCombinedSyncUnitStatus(a),f=this.getCombinedSyncUnitStatus(l);this.syncStatus.set(o,l),y!==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 yo{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 un(t.callInfo.data,this.listenerManager)}case"Internal":throw new Error("Internal transmitter not implemented");default:return new ue(t,this.listenerManager)}}}let xo=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 fo),this.cache||(this.cache=new xs),this.queueManager||(this.queueManager=new Pi),this.eventEmitter||(this.eventEmitter=new go),this.synchronizationManager||(this.synchronizationManager=new mo(this.storage,this.storage,this.cache,this.documentModelModules,this.eventEmitter)),!this.listenerManager){const e={...ot,...this.options?.listenerManager};this.listenerManager=new kt(this.synchronizationManager,e)}return this.transmitterFactory||(this.transmitterFactory=new yo(this.listenerManager)),new ho(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 Mr(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=vo(a),l=r[o];l&&l.push(d),d!==a&&(e=!0)}return r},{global:[],local:[]});return e?{...i,operations:t}:i}function vo(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 Ct={exports:{}};var Or;function wo(){return Or||(Or=1,(function(i,e){(function(t){i.exports=t()})(function(){return(function t(r,n,s){function o(l,y){if(!n[l]){if(!r[l]){var f=typeof Ye=="function"&&Ye;if(!y&&f)return f(l,!0);if(a)return a(l,!0);var w=new Error("Cannot find module '"+l+"'");throw w.code="MODULE_NOT_FOUND",w}var b=n[l]={exports:{}};r[l][0].call(b.exports,function(p){var E=r[l][1][p];return o(E||p)},b,b.exports,t,r,n,s)}return n[l].exports}for(var a=typeof Ye=="function"&&Ye,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(p),y=s.document.createTextNode("");l.observe(y,{characterData:!0}),a=function(){y.data=d=++d%2}}else if(!s.setImmediate&&typeof s.MessageChannel<"u"){var f=new s.MessageChannel;f.port1.onmessage=p,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(){p(),_.onreadystatechange=null,_.parentNode.removeChild(_),_=null},s.document.documentElement.appendChild(_)}:a=function(){setTimeout(p,0)};var w,b=[];function p(){w=!0;for(var _,A,C=b.length;C;){for(A=b,b=[],_=-1;++_<C;)A[_]();C=b.length}w=!1}r.exports=E;function E(_){b.push(_)===1&&!w&&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"],y=["PENDING"];r.exports=f;function f(I){if(typeof I!="function")throw new TypeError("resolver must be a function");this.state=y,this.queue=[],this.outcome=void 0,I!==o&&E(this,I)}f.prototype.catch=function(I){return this.then(null,I)},f.prototype.then=function(I,P){if(typeof I!="function"&&this.state===l||typeof P!="function"&&this.state===d)return this;var L=new this.constructor(o);if(this.state!==y){var j=this.state===l?I:P;b(L,j,this.outcome)}else this.queue.push(new w(L,I,P));return L};function w(I,P,L){this.promise=I,typeof P=="function"&&(this.onFulfilled=P,this.callFulfilled=this.otherCallFulfilled),typeof L=="function"&&(this.onRejected=L,this.callRejected=this.otherCallRejected)}w.prototype.callFulfilled=function(I){a.resolve(this.promise,I)},w.prototype.otherCallFulfilled=function(I){b(this.promise,this.onFulfilled,I)},w.prototype.callRejected=function(I){a.reject(this.promise,I)},w.prototype.otherCallRejected=function(I){b(this.promise,this.onRejected,I)};function b(I,P,L){s(function(){var j;try{j=P(L)}catch(H){return a.reject(I,H)}j===I?a.reject(I,new TypeError("Cannot resolve promise with itself")):a.resolve(I,j)})}a.resolve=function(I,P){var L=_(p,P);if(L.status==="error")return a.reject(I,L.value);var j=L.value;if(j)E(I,j);else{I.state=l,I.outcome=P;for(var H=-1,K=I.queue.length;++H<K;)I.queue[H].callFulfilled(P)}return I},a.reject=function(I,P){I.state=d,I.outcome=P;for(var L=-1,j=I.queue.length;++L<j;)I.queue[L].callRejected(P);return I};function p(I){var P=I&&I.then;if(I&&(typeof I=="object"||typeof I=="function")&&typeof P=="function")return function(){P.apply(I,arguments)}}function E(I,P){var L=!1;function j(Y){L||(L=!0,a.reject(I,Y))}function H(Y){L||(L=!0,a.resolve(I,Y))}function K(){P(H,j)}var Z=_(K);Z.status==="error"&&j(Z.value)}function _(I,P){var L={};try{L.value=I(P),L.status="success"}catch(j){L.status="error",L.value=j}return L}f.resolve=A;function A(I){return I instanceof this?I:a.resolve(new this(o),I)}f.reject=C;function C(I){var P=new this(o);return a.reject(P,I)}f.all=U;function U(I){var P=this;if(Object.prototype.toString.call(I)!=="[object Array]")return this.reject(new TypeError("must be an array"));var L=I.length,j=!1;if(!L)return this.resolve([]);for(var H=new Array(L),K=0,Z=-1,Y=new this(o);++Z<L;)se(I[Z],Z);return Y;function se(le,D){P.resolve(le).then(R,function(B){j||(j=!0,a.reject(Y,B))});function R(B){H[D]=B,++K===L&&!j&&(j=!0,a.resolve(Y,H))}}}f.race=F;function F(I){var P=this;if(Object.prototype.toString.call(I)!=="[object Array]")return this.reject(new TypeError("must be an array"));var L=I.length,j=!1;if(!L)return this.resolve([]);for(var H=-1,K=new this(o);++H<L;)Z(I[H]);return K;function Z(Y){P.resolve(Y).then(function(se){j||(j=!0,a.resolve(K,se))},function(se){j||(j=!0,a.reject(K,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 y(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,m=new u,v=0;v<c.length;v+=1)m.append(c[v]);return m.getBlob(h.type)}}typeof Promise>"u"&&t(3);var f=Promise;function w(c,h){h&&c.then(function(u){h(null,u)},function(u){h(u)})}function b(c,h,u){typeof h=="function"&&c.then(h),typeof u=="function"&&c.catch(u)}function p(c){return typeof c!="string"&&(console.warn(c+" used as a key, but it is not a string."),c=String(c)),c}function E(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var _="local-forage-detect-blob-support",A=void 0,C={},U=Object.prototype.toString,F="readonly",I="readwrite";function P(c){for(var h=c.length,u=new ArrayBuffer(h),m=new Uint8Array(u),v=0;v<h;v++)m[v]=c.charCodeAt(v);return u}function L(c){return new f(function(h){var u=c.transaction(_,I),m=y([""]);u.objectStore(_).put(m,"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 A=="boolean"?f.resolve(A):L(c).then(function(h){return A=h,A})}function H(c){var h=C[c.name],u={};u.promise=new f(function(m,v){u.resolve=m,u.reject=v}),h.deferredOperations.push(u),h.dbReady?h.dbReady=h.dbReady.then(function(){return u.promise}):h.dbReady=u.promise}function K(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],m=u.deferredOperations.pop();if(m)return m.reject(h),m.promise}function Y(c,h){return new f(function(u,m){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(),m(g.error)},g.onsuccess=function(){var S=g.result;S.onversionchange=function(T){T.target.close()},u(S),K(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),m=c.version<c.db.version,v=c.version>c.db.version;if(m&&(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 m=new FileReader;m.onerror=u,m.onloadend=function(v){var g=btoa(v.target.result||"");h({__local_forage_encoded_blob:!0,data:g,type:c.type})},m.readAsBinaryString(c)})}function B(c){var h=P(atob(c.data));return y([h],{type:c.type})}function G(c){return c&&c.__local_forage_encoded_blob}function V(c){var h=this,u=h._initReady().then(function(){var m=C[h._dbInfo.name];if(m&&m.dbReady)return m.dbReady});return b(u,c,c),u}function z(c){H(c);for(var h=C[c.name],u=h.forages,m=0;m<u.length;m++){var v=u[m];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,m){m===void 0&&(m=1);try{var v=c.db.transaction(c.storeName,h);u(null,v)}catch(g){if(m>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,m-1)})}).catch(u);u(g)}}function _e(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function ze(c){var h=this,u={db:null};if(c)for(var m in c)u[m]=c[m];var v=C[u.name];v||(v=_e(),C[u.name]=v),v.forages.push(h),h._initReady||(h._initReady=h.ready,h.ready=V);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(N){return u.db=N,D(u,h._defaultConfig.version)?le(u):N}).then(function(N){u.db=v.db=N,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=p(c);var m=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 N=O.result;N===void 0&&(N=null),G(N)&&(N=B(N)),v(N)},O.onerror=function(){g(O.error)}}catch(N){g(N)}})}).catch(g)});return w(m,h),m}function ye(c,h){var u=this,m=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(),N=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,N++);J!==void 0?v(J):x.continue()}else v()},O.onerror=function(){g(O.error)}}catch(x){g(x)}})}).catch(g)});return w(m,h),m}function fn(c,h,u){var m=this;c=p(c);var v=new f(function(g,S){var T;m.ready().then(function(){return T=m._dbInfo,U.call(h)==="[object Blob]"?j(T.db).then(function(M){return M?h:R(h)}):h}).then(function(M){ae(m._dbInfo,I,function(O,N){if(O)return S(O);try{var x=N.objectStore(m._dbInfo.storeName);M===null&&(M=void 0);var k=x.put(M,c);N.oncomplete=function(){M===void 0&&(M=null),g(M)},N.onabort=N.onerror=function(){var J=k.error?k.error:k.transaction.error;S(J)}}catch(J){S(J)}})}).catch(S)});return w(v,u),v}function gn(c,h){var u=this;c=p(c);var m=new f(function(v,g){u.ready().then(function(){ae(u._dbInfo,I,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 N=O.error?O.error:O.transaction.error;g(N)}}catch(N){g(N)}})}).catch(g)});return w(m,h),m}function pn(c){var h=this,u=new f(function(m,v){h.ready().then(function(){ae(h._dbInfo,I,function(g,S){if(g)return v(g);try{var T=S.objectStore(h._dbInfo.storeName),M=T.clear();S.oncomplete=function(){m()},S.onabort=S.onerror=function(){var O=M.error?M.error:M.transaction.error;v(O)}}catch(O){v(O)}})}).catch(v)});return w(u,c),u}function mn(c){var h=this,u=new f(function(m,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(){m(M.result)},M.onerror=function(){v(M.error)}}catch(O){v(O)}})}).catch(v)});return w(u,c),u}function yn(c,h){var u=this,m=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,N=M.openKeyCursor();N.onsuccess=function(){var x=N.result;if(!x){v(null);return}c===0||O?v(x.key):(O=!0,x.advance(c))},N.onerror=function(){g(N.error)}}catch(x){g(x)}})}).catch(g)});return w(m,h),m}function vn(c){var h=this,u=new f(function(m,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 N=M.result;if(!N){m(O);return}O.push(N.key),N.continue()},M.onerror=function(){v(M.error)}}catch(N){v(N)}})}).catch(v)});return w(u,c),u}function wn(c,h){h=E.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 m=this,v;if(!c.name)v=f.reject("Invalid arguments");else{var g=c.name===u.name&&m._dbInfo.db,S=g?f.resolve(m._dbInfo.db):se(c).then(function(T){var M=C[c.name],O=M.forages;M.db=T;for(var N=0;N<O.length;N++)O[N]._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],N=O.forages;T.close();for(var x=0;x<N.length;x++){var k=N[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(de){var Le=ee.result;Le.close(),re(de)},ee.onupgradeneeded=function(){var de=ee.result;de.deleteObjectStore(c.storeName)},ee.onsuccess=function(){var de=ee.result;de.close(),Q(de)}});return J.then(function(Q){O.db=Q;for(var re=0;re<N.length;re++){var ee=N[re];ee._dbInfo.db=Q,K(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 N=0;N<O.length;N++){var x=O[N];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];K(re._dbInfo)}}).catch(function(J){throw(Z(c,J)||f.resolve()).catch(function(){}),J})})}return w(v,h),v}var bn={_driver:"asyncStorage",_initStorage:ze,_support:l(),iterate:ye,getItem:ne,setItem:fn,removeItem:gn,clear:pn,length:mn,key:yn,keys:vn,dropInstance:wn};function Dn(){return typeof openDatabase=="function"}var be="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Sn="~~local_forage_type~",qt=/^~~local_forage_type~([^~]+)~/,je="__lfsc__:",lt=je.length,ht="arbf",ft="blob",zt="si08",jt="ui08",Ht="uic8",Gt="si16",Jt="si32",Yt="ur16",Qt="ui32",Kt="fl32",Vt="fl64",Wt=lt+ht.length,Xt=Object.prototype.toString;function Zt(c){var h=c.length*.75,u=c.length,m,v=0,g,S,T,M;c[c.length-1]==="="&&(h--,c[c.length-2]==="="&&h--);var O=new ArrayBuffer(h),N=new Uint8Array(O);for(m=0;m<u;m+=4)g=be.indexOf(c[m]),S=be.indexOf(c[m+1]),T=be.indexOf(c[m+2]),M=be.indexOf(c[m+3]),N[v++]=g<<2|S>>4,N[v++]=(S&15)<<4|T>>2,N[v++]=(T&3)<<6|M&63;return O}function gt(c){var h=new Uint8Array(c),u="",m;for(m=0;m<h.length;m+=3)u+=be[h[m]>>2],u+=be[(h[m]&3)<<4|h[m+1]>>4],u+=be[(h[m+1]&15)<<2|h[m+2]>>6],u+=be[h[m+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 En(c,h){var u="";if(c&&(u=Xt.call(c)),c&&(u==="[object ArrayBuffer]"||c.buffer&&Xt.call(c.buffer)==="[object ArrayBuffer]")){var m,v=je;c instanceof ArrayBuffer?(m=c,v+=ht):(m=c.buffer,u==="[object Int8Array]"?v+=zt:u==="[object Uint8Array]"?v+=jt:u==="[object Uint8ClampedArray]"?v+=Ht:u==="[object Int16Array]"?v+=Gt:u==="[object Uint16Array]"?v+=Yt:u==="[object Int32Array]"?v+=Jt:u==="[object Uint32Array]"?v+=Qt:u==="[object Float32Array]"?v+=Kt:u==="[object Float64Array]"?v+=Vt:h(new Error("Failed to get type for BinaryArray"))),h(v+gt(m))}else if(u==="[object Blob]"){var g=new FileReader;g.onload=function(){var S=Sn+c.type+"~"+gt(this.result);h(je+ft+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 In(c){if(c.substring(0,lt)!==je)return JSON.parse(c);var h=c.substring(Wt),u=c.substring(lt,Wt),m;if(u===ft&&qt.test(h)){var v=h.match(qt);m=v[1],h=h.substring(v[0].length)}var g=Zt(h);switch(u){case ht:return g;case ft:return y([g],{type:m});case zt:return new Int8Array(g);case jt:return new Uint8Array(g);case Ht:return new Uint8ClampedArray(g);case Gt:return new Int16Array(g);case Yt:return new Uint16Array(g);case Jt:return new Int32Array(g);case Qt:return new Uint32Array(g);case Kt:return new Float32Array(g);case Vt:return new Float64Array(g);default:throw new Error("Unkown type: "+u)}}var pt={serialize:En,deserialize:In,stringToBuffer:Zt,bufferToString:gt};function er(c,h,u,m){c.executeSql("CREATE TABLE IF NOT EXISTS "+h.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],u,m)}function Tn(c){var h=this,u={db:null};if(c)for(var m in c)u[m]=typeof c[m]!="string"?c[m].toString():c[m];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){er(T,u,function(){h._dbInfo=u,g()},function(M,O){S(O)})},S)});return u.serializer=pt,v}function De(c,h,u,m,v,g){c.executeSql(u,m,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):er(M,h,function(){M.executeSql(u,m,v,g)},g)},g):g(S,T)},g)}function Rn(c,h){var u=this;c=p(c);var m=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 N=O.rows.length?O.rows.item(0).value:null;N&&(N=S.serializer.deserialize(N)),v(N)},function(M,O){g(O)})})}).catch(g)});return w(m,h),m}function Mn(c,h){var u=this,m=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 N=O.rows,x=N.length,k=0;k<x;k++){var J=N.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 w(m,h),m}function tr(c,h,u,m){var v=this;c=p(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(N,x){x?T(x):O.db.transaction(function(k){De(k,O,"INSERT OR REPLACE INTO "+O.storeName+" (key, value) VALUES (?, ?)",[c,N],function(){S(M)},function(J,Q){T(Q)})},function(k){if(k.code===k.QUOTA_ERR){if(m>0){S(tr.apply(v,[c,M,u,m-1]));return}T(k)}})})}).catch(T)});return w(g,u),g}function On(c,h,u){return tr.apply(this,[c,h,u,1])}function _n(c,h){var u=this;c=p(c);var m=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 w(m,h),m}function An(c){var h=this,u=new f(function(m,v){h.ready().then(function(){var g=h._dbInfo;g.db.transaction(function(S){De(S,g,"DELETE FROM "+g.storeName,[],function(){m()},function(T,M){v(M)})})}).catch(v)});return w(u,c),u}function Nn(c){var h=this,u=new f(function(m,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;m(O)},function(T,M){v(M)})})}).catch(v)});return w(u,c),u}function Cn(c,h){var u=this,m=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 N=O.rows.length?O.rows.item(0).key:null;v(N)},function(M,O){g(O)})})}).catch(g)});return w(m,h),m}function xn(c){var h=this,u=new f(function(m,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=[],N=0;N<M.rows.length;N++)O.push(M.rows.item(N).key);m(O)},function(T,M){v(M)})})}).catch(v)});return w(u,c),u}function $n(c){return new f(function(h,u){c.transaction(function(m){m.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(m){u(m)})})}function Pn(c,h){h=E.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 m=this,v;return c.name?v=new f(function(g){var S;c.name===u.name?S=m._dbInfo.db:S=openDatabase(c.name,"","",0),c.storeName?g({db:S,storeNames:[c.storeName]}):g($n(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,de){re(de)})})}for(var N=[],x=0,k=g.storeNames.length;x<k;x++)N.push(O(g.storeNames[x]));f.all(N).then(function(){S()}).catch(function(J){T(J)})},function(M){T(M)})})}):v=f.reject("Invalid arguments"),w(v,h),v}var Ln={_driver:"webSQLStorage",_initStorage:Tn,_support:Dn(),iterate:Mn,getItem:Rn,setItem:On,removeItem:_n,clear:An,length:Nn,key:Cn,keys:xn,dropInstance:Pn};function Un(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}function rr(c,h){var u=c.name+"/";return c.storeName!==h.storeName&&(u+=c.storeName+"/"),u}function Bn(){var c="_localforage_support_test";try{return localStorage.setItem(c,!0),localStorage.removeItem(c),!1}catch{return!0}}function Fn(){return!Bn()||localStorage.length>0}function kn(c){var h=this,u={};if(c)for(var m in c)u[m]=c[m];return u.keyPrefix=rr(c,h._defaultConfig),Fn()?(h._dbInfo=u,u.serializer=pt,f.resolve()):f.reject()}function qn(c){var h=this,u=h.ready().then(function(){for(var m=h._dbInfo.keyPrefix,v=localStorage.length-1;v>=0;v--){var g=localStorage.key(v);g.indexOf(m)===0&&localStorage.removeItem(g)}});return w(u,c),u}function zn(c,h){var u=this;c=p(c);var m=u.ready().then(function(){var v=u._dbInfo,g=localStorage.getItem(v.keyPrefix+c);return g&&(g=v.serializer.deserialize(g)),g});return w(m,h),m}function jn(c,h){var u=this,m=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 N=localStorage.key(O);if(N.indexOf(g)===0){var x=localStorage.getItem(N);if(x&&(x=v.serializer.deserialize(x)),x=c(x,N.substring(S),M++),x!==void 0)return x}}});return w(m,h),m}function Hn(c,h){var u=this,m=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 w(m,h),m}function Gn(c){var h=this,u=h.ready().then(function(){for(var m=h._dbInfo,v=localStorage.length,g=[],S=0;S<v;S++){var T=localStorage.key(S);T.indexOf(m.keyPrefix)===0&&g.push(T.substring(m.keyPrefix.length))}return g});return w(u,c),u}function Jn(c){var h=this,u=h.keys().then(function(m){return m.length});return w(u,c),u}function Yn(c,h){var u=this;c=p(c);var m=u.ready().then(function(){var v=u._dbInfo;localStorage.removeItem(v.keyPrefix+c)});return w(m,h),m}function Qn(c,h,u){var m=this;c=p(c);var v=m.ready().then(function(){h===void 0&&(h=null);var g=h;return new f(function(S,T){var M=m._dbInfo;M.serializer.serialize(h,function(O,N){if(N)T(N);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 w(v,u),v}function Kn(c,h){if(h=E.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 m=this,v;return c.name?v=new f(function(g){c.storeName?g(rr(c,m._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"),w(v,h),v}var Vn={_driver:"localStorageWrapper",_initStorage:kn,_support:Un(),iterate:jn,getItem:zn,setItem:Qn,removeItem:Yn,clear:qn,length:Jn,key:Hn,keys:Gn,dropInstance:Kn},Wn=function(h,u){return h===u||typeof h=="number"&&typeof u=="number"&&isNaN(h)&&isNaN(u)},Xn=function(h,u){for(var m=h.length,v=0;v<m;){if(Wn(h[v],u))return!0;v++}return!1},nr=Array.isArray||function(c){return Object.prototype.toString.call(c)==="[object Array]"},Pe={},sr={},Ae={INDEXEDDB:bn,WEBSQL:Ln,LOCALSTORAGE:Vn},Zn=[Ae.INDEXEDDB._driver,Ae.WEBSQL._driver,Ae.LOCALSTORAGE._driver],He=["dropInstance"],mt=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(He),es={description:"",driver:Zn.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function ts(c,h){c[h]=function(){var u=arguments;return c.ready().then(function(){return c[h].apply(c,u)})}}function yt(){for(var c=1;c<arguments.length;c++){var h=arguments[c];if(h)for(var u in h)h.hasOwnProperty(u)&&(nr(h[u])?arguments[0][u]=h[u].slice():arguments[0][u]=h[u])}return arguments[0]}var rs=(function(){function c(h){o(this,c);for(var u in Ae)if(Ae.hasOwnProperty(u)){var m=Ae[u],v=m._driver;this[u]=v,Pe[v]||this.defineDriver(m)}this._defaultConfig=yt({},es),this._config=yt({},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 m in u){if(m==="storeName"&&(u[m]=u[m].replace(/\W/g,"_")),m==="version"&&typeof u[m]!="number")return new Error("Database version must be a number.");this._config[m]=u[m]}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,m,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 N=mt.concat("_initStorage"),x=0,k=N.length;x<k;x++){var J=N[x],Q=!Xn(He,J);if((Q||u[J])&&typeof u[J]!="function"){T(O);return}}var re=function(){for(var Le=function(is){return function(){var os=new Error("Method "+is+" is not implemented by the current driver"),ir=f.reject(os);return w(ir,arguments[arguments.length-1]),ir}},vt=0,ss=He.length;vt<ss;vt++){var wt=He[vt];u[wt]||(u[wt]=Le(wt))}};re();var ee=function(Le){Pe[M]&&console.info("Redefining LocalForage driver: "+M),Pe[M]=u,sr[M]=Le,S()};"_support"in u?u._support&&typeof u._support=="function"?u._support().then(ee,T):ee(!!u._support):ee(!0)}catch(de){T(de)}});return b(g,m,v),g},c.prototype.driver=function(){return this._driver||null},c.prototype.getDriver=function(u,m,v){var g=Pe[u]?f.resolve(Pe[u]):f.reject(new Error("Driver not found."));return b(g,m,v),g},c.prototype.getSerializer=function(u){var m=f.resolve(pt);return b(m,u),m},c.prototype.ready=function(u){var m=this,v=m._driverSet.then(function(){return m._ready===null&&(m._ready=m._initDriver()),m._ready});return b(v,u,u),v},c.prototype.setDriver=function(u,m,v){var g=this;nr(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 N=this._driverSet!==null?this._driverSet.catch(function(){return f.resolve()}):f.resolve();return this._driverSet=N.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}),b(this._driverSet,m,v),this._driverSet},c.prototype.supports=function(u){return!!sr[u]},c.prototype._extend=function(u){yt(this,u)},c.prototype._getSupportedDrivers=function(u){for(var m=[],v=0,g=u.length;v<g;v++){var S=u[v];this.supports(S)&&m.push(S)}return m},c.prototype._wrapLibraryMethodsWithReady=function(){for(var u=0,m=mt.length;u<m;u++)ts(this,mt[u])},c.prototype.createInstance=function(u){return new c(u)},c})(),ns=new rs;r.exports=ns},{3:3}]},{},[4])(4)})})(Ct)),Ct.exports}var bo=wo();const _r=Pt(bo);class te{logger=me(["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=_r.ready().then(()=>_r.createInstance({name:e?`${e}:${te.DBName}`:te.DBName}))}async findStorageUnitsBy(e,t,r){const n=[],{parentId:s,documentId:o,documentModelType:a,scope:d}=dn(e),f=(await(await this.db).keys()).filter(_=>_.startsWith(`${te.DOCUMENT_KEY}${te.SEP}`)).map(_=>_.slice(te.DOCUMENT_KEY.length+te.SEP.length));let w;if(s){const _=new Set;for(const A of s)(await this.getChildren(A)).forEach(U=>_.add(U));w=ln(s,_)}else w=new Set(f);w=o?hn(o,w):w;for(const _ of w){const A=await this.get(_).catch(()=>null);if(A&&!(a&&!a.has(A.header.documentType)))for(const[C]of Object.entries(A.state))d&&!d.has(C)||n.push({documentId:_,documentModelType:A.header.documentType,scope:C,branch:"main"})}let b=0;if(r){const _=n.findIndex(A=>A.documentId===r);_!==-1&&(b=_)}const p=Math.min(b+t,n.length),E=p<n.length?n[p].documentId:void 0;return{units:n.slice(b,p),nextCursor:E}}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,r=await this.db;if(await this.exists(t))throw new qe(t);const n=e.header.slug&&e.header.slug.length>0?e.header.slug:t;if((await this.getSlugManifest()).slugToId[n])throw new qe(t,ke.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 w=f.slice(te.DOCUMENT_KEY.length+te.SEP.length);try{const b=await n.getItem(f);if(!b||b.header.documentType!==e)continue;a.push({id:w,document:b})}catch{continue}}a.sort((f,w)=>{const b=new Date(f.document.header.createdAtUtcIso),p=new Date(w.document.header.createdAtUtcIso);return b.getTime()===p.getTime()?f.id.localeCompare(w.id):b.getTime()-p.getTime()});let d=0;if(r){const f=a.findIndex(({id:w})=>w===r);f!==-1&&(d=f)}const l=Math.min(d+t,a.length);let y;return l<a.length&&(y=a[l].id),{documents:a.slice(d,l).map(({id:f})=>f),nextCursor:y}}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=Mr(t);if(r!==t)return(await this.db).setItem(this.buildDocumentKey(e),r)}async migrateDocument(e,t){const r=await this.get(t),n=Mr(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,Pi as E,xs as I,fo as M,ue as P,xo as R,Oi as S,Qs as a,Ks as b,ci as c,Vs as d,Zs as e,ni as f,Oo as g,Ne as h,dr as i,ti as j,ii as k,fe as l,ei as m,Ri as n,Co as o,Qe as p,Mo as q,en as r,Xr as s,me as t,Xs as u,Ti as v,_o as w,cn as x,Ao as y};