@powerhousedao/connect 5.1.0 → 5.2.0-staging.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 (124) hide show
  1. package/.env +1 -0
  2. package/dist/assets/AddDriveModal-2J4OkOKe.js +1 -0
  3. package/dist/assets/ClearStorageModal-D-Trm4Bv.js +1 -0
  4. package/dist/assets/CookiesPolicyModal-TR7WVoSA.js +1 -0
  5. package/dist/assets/CreateDocumentModal-Cs-4k9rW.js +1 -0
  6. package/dist/assets/{DebugSettingsModal-CooFY-Go.js → DebugSettingsModal-Bp_xYviw.js} +1 -1
  7. package/dist/assets/{DeleteDriveModal-BOdu1bg5.js → DeleteDriveModal-CeCAWL_i.js} +1 -1
  8. package/dist/assets/DeleteItemModal-BLqrxHHr.js +1 -0
  9. package/dist/assets/DisclaimerModal-DV4OXJI1.js +1 -0
  10. package/dist/assets/DriveSettingsModal-BJJf_xXi.js +1 -0
  11. package/dist/assets/{ExportDocumentWithErrorsModal-BzgGSmxg.js → ExportDocumentWithErrorsModal-tuPYLvIE.js} +1 -1
  12. package/dist/assets/SettingsModal-CU5Mio6y.js +1 -0
  13. package/dist/assets/UpgradeDriveModal-CpKl7cbN.js +1 -0
  14. package/dist/assets/{design_system-DGYPpUGa.js → design_system-WuKyHXQN.js} +1 -1
  15. package/dist/assets/design_system_connect-DKWQSjBv.js +45 -0
  16. package/dist/assets/design_system_ui-DvlEeqfu.js +1 -0
  17. package/dist/assets/{document_drive-BEIKnuGM.js → document_drive-BuVpBb4l.js} +25 -14
  18. package/dist/assets/{document_engineering-B49PhCDR.js → document_engineering-C2PWdZDH.js} +1 -1
  19. package/dist/assets/{document_model-DXcLJEjZ.js → document_model-DB4SzBSe.js} +3 -3
  20. package/dist/assets/document_model_editor-Dxf_uko8.js +23 -0
  21. package/dist/assets/{drive_explorer-d0kn77Nx.js → drive_explorer-iLZp-dwy.js} +2 -2
  22. package/dist/assets/{graphql-editor-CSkqTexL.js → graphql-editor-BycuWm1l.js} +2 -2
  23. package/dist/assets/{hooks-D4Uas2SG.js → hooks-BdgCwg49.js} +1 -1
  24. package/dist/assets/index-BilHslhO.css +1 -0
  25. package/dist/assets/index-CS9DBC13.js +20 -0
  26. package/dist/assets/index-VIbDz3Cl.js +25 -0
  27. package/dist/assets/json-editor-BjVnk0-0.js +1 -0
  28. package/dist/assets/nodefs-Dk4wkJJa.js +1 -0
  29. package/dist/assets/opfs-ahp-BSB41eck.js +3 -0
  30. package/dist/assets/pg_dump-CW0pN9tG.wasm +0 -0
  31. package/dist/assets/postgres-CkP7QCDB.data +0 -0
  32. package/dist/assets/postgres-CyuUVpXN.wasm +0 -0
  33. package/dist/assets/reactor_browser-CmbGGv54.js +127 -0
  34. package/dist/assets/state-schemas-DS3WhvAN.js +2 -0
  35. package/dist/assets/zod-BpTyxkjy.js +20 -0
  36. package/dist/index.html +11 -11
  37. package/heroku/Dockerfile +4 -1
  38. package/lib/package.copy.json +14 -8
  39. package/lib/src/components/app-skeleton.js +1 -1
  40. package/lib/src/components/app-skeleton.js.map +1 -1
  41. package/lib/src/components/modal/modals/AddDriveModal.d.ts.map +1 -1
  42. package/lib/src/components/modal/modals/AddDriveModal.js +35 -27
  43. package/lib/src/components/modal/modals/AddDriveModal.js.map +1 -1
  44. package/lib/src/components/modal/modals/InspectorModal/InspectorModal.d.ts +2 -0
  45. package/lib/src/components/modal/modals/InspectorModal/InspectorModal.d.ts.map +1 -0
  46. package/lib/src/components/modal/modals/InspectorModal/InspectorModal.js +26 -0
  47. package/lib/src/components/modal/modals/InspectorModal/InspectorModal.js.map +1 -0
  48. package/lib/src/components/modal/modals/InspectorModal/index.d.ts +2 -0
  49. package/lib/src/components/modal/modals/InspectorModal/index.d.ts.map +1 -0
  50. package/lib/src/components/modal/modals/InspectorModal/index.js +2 -0
  51. package/lib/src/components/modal/modals/InspectorModal/index.js.map +1 -0
  52. package/lib/src/components/modal/modals/InspectorModal/useDbExplorer.d.ts +32 -0
  53. package/lib/src/components/modal/modals/InspectorModal/useDbExplorer.d.ts.map +1 -0
  54. package/lib/src/components/modal/modals/InspectorModal/useDbExplorer.js +108 -0
  55. package/lib/src/components/modal/modals/InspectorModal/useDbExplorer.js.map +1 -0
  56. package/lib/src/components/modal/modals/InspectorModal/useRemotesInspector.d.ts +4 -0
  57. package/lib/src/components/modal/modals/InspectorModal/useRemotesInspector.d.ts.map +1 -0
  58. package/lib/src/components/modal/modals/InspectorModal/useRemotesInspector.js +12 -0
  59. package/lib/src/components/modal/modals/InspectorModal/useRemotesInspector.js.map +1 -0
  60. package/lib/src/components/modal/modals-container.d.ts.map +1 -1
  61. package/lib/src/components/modal/modals-container.js +4 -0
  62. package/lib/src/components/modal/modals-container.js.map +1 -1
  63. package/lib/src/components/root.js +1 -1
  64. package/lib/src/components/root.js.map +1 -1
  65. package/lib/src/components/sidebar.d.ts.map +1 -1
  66. package/lib/src/components/sidebar.js +6 -2
  67. package/lib/src/components/sidebar.js.map +1 -1
  68. package/lib/src/connect.config.d.ts +2 -0
  69. package/lib/src/connect.config.d.ts.map +1 -1
  70. package/lib/src/connect.config.js +1 -0
  71. package/lib/src/connect.config.js.map +1 -1
  72. package/lib/src/feature-flags.d.ts +22 -3
  73. package/lib/src/feature-flags.d.ts.map +1 -1
  74. package/lib/src/feature-flags.js +48 -3
  75. package/lib/src/feature-flags.js.map +1 -1
  76. package/lib/src/hooks/useClientErrorHandler.d.ts.map +1 -1
  77. package/lib/src/hooks/useClientErrorHandler.js +13 -2
  78. package/lib/src/hooks/useClientErrorHandler.js.map +1 -1
  79. package/lib/src/pages/demo/atlas-import.js +2 -2
  80. package/lib/src/pages/demo/atlas-import.js.map +1 -1
  81. package/lib/src/store/reactor.d.ts.map +1 -1
  82. package/lib/src/store/reactor.js +102 -51
  83. package/lib/src/store/reactor.js.map +1 -1
  84. package/lib/src/utils/reactor.d.ts +7 -0
  85. package/lib/src/utils/reactor.d.ts.map +1 -1
  86. package/lib/src/utils/reactor.js +35 -2
  87. package/lib/src/utils/reactor.js.map +1 -1
  88. package/lib/src/utils/signer.d.ts +18 -0
  89. package/lib/src/utils/signer.d.ts.map +1 -0
  90. package/lib/src/utils/signer.js +215 -0
  91. package/lib/src/utils/signer.js.map +1 -0
  92. package/lib/test/utils/signer.test.d.ts +2 -0
  93. package/lib/test/utils/signer.test.d.ts.map +1 -0
  94. package/lib/test/utils/signer.test.js +319 -0
  95. package/lib/test/utils/signer.test.js.map +1 -0
  96. package/lib/tsconfig.tsbuildinfo +1 -1
  97. package/lib/vite.config.d.ts.map +1 -1
  98. package/lib/vite.config.js +4 -0
  99. package/lib/vite.config.js.map +1 -1
  100. package/lib/vitest.config.d.ts +3 -0
  101. package/lib/vitest.config.d.ts.map +1 -0
  102. package/lib/vitest.config.js +8 -0
  103. package/lib/vitest.config.js.map +1 -0
  104. package/nginx.conf +7 -0
  105. package/package.copy.json +14 -8
  106. package/package.json +21 -15
  107. package/dist/assets/AddDriveModal-_XSf2ZlN.js +0 -1
  108. package/dist/assets/ClearStorageModal-CbfJTlAo.js +0 -1
  109. package/dist/assets/CookiesPolicyModal-DTRuUeM_.js +0 -1
  110. package/dist/assets/CreateDocumentModal-DUTbfZYr.js +0 -1
  111. package/dist/assets/DeleteItemModal-D8MlQS3W.js +0 -1
  112. package/dist/assets/DisclaimerModal-RBBaiKyO.js +0 -1
  113. package/dist/assets/DriveSettingsModal-BHBZfzaY.js +0 -1
  114. package/dist/assets/SettingsModal-BXDXscnR.js +0 -1
  115. package/dist/assets/UpgradeDriveModal-15TBzq11.js +0 -1
  116. package/dist/assets/design_system_connect-Vb8XBnLs.js +0 -45
  117. package/dist/assets/design_system_ui-Dnwc_Xm9.js +0 -1
  118. package/dist/assets/document_model_editor-lmHQ6HZy.js +0 -23
  119. package/dist/assets/index-Br7E7qjt.css +0 -1
  120. package/dist/assets/index-CK2Jk_ho.js +0 -18
  121. package/dist/assets/json-editor-CQKAVxat.js +0 -1
  122. package/dist/assets/reactor_browser-BGn_P-dn.js +0 -25
  123. package/dist/assets/state-schemas-36mF-wEI.js +0 -2
  124. package/dist/assets/zod-C6yxFxyo.js +0 -1
@@ -1,5 +1,5 @@
1
- import{c as Ee,g as Pt}from"./react-DQSxOgtG.js";import{c as oe,a as ds,i as ls,B as hs,b as fs,d as gs,e as ps,f as ms,g as ct,h as Lt,j as ys,p as Nr,k as Le,v as He,l as ar,m as cr,r as vs,n as Dt,s as Ge,o as ws,q as bs,t as Ds,u as Ve,w as Cr,x as Ss,y as Es,z as Is,A as Je}from"./document_model-DXcLJEjZ.js";import{a as Ts,p as Rs,G as Ms,b as Os,c as St,d as ur,e as Et,f as _s,g as As}from"./graphql-BS4Brs_E.js";import{o as W,s as $,f as Ze,b as ge,e as xr,d as Oe,a as Ns,c as Cs}from"./zod-C6yxFxyo.js";import{i as xs,L as he}from"./config-CU-aFfVJ.js";function $s(i,e){for(var t=0;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const n in r)if(n!=="default"&&!(n in i)){const s=Object.getOwnPropertyDescriptor(r,n);s&&Object.defineProperty(i,n,s.get?s:{enumerable:!0,get:()=>r[n]})}}}return Object.freeze(Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}))}var Ps={};class $r{#e;#t="env";#r;constructor(e,t){this.#e=(e||[]).map(r=>`[${r}]`),this.#r=t,this.log=this.log.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.debug=this.debug.bind(this),this.verbose=this.verbose.bind(this)}get level(){return this.#t}set level(e){if(e!=="env"&&!xs(e))throw new Error(`Invalid log level: ${JSON.stringify(e)}.
2
- Must be one of ${Object.keys(he).concat(["env"]).join(", ")}.`);this.#t=e}get errorHandler(){return this.#r}set errorHandler(e){this.#r=e}get#n(){if(this.#t==="env"){const e=typeof globalThis<"u"&&globalThis.process&&"env"in globalThis.process?Ps.LOG_LEVEL:void 0;return e?e in he?he[e]:he.info:he.info}return he[this.#t]}log(...e){return this.debug(...e)}verbose(...e){if(!(this.#n>he.verbose))return this.debug(...e)}debug(...e){if(!(this.#n>he.debug))return console.debug(...this.#e,...e)}info(...e){if(!(this.#n>he.info))return console.info(...this.#e,...e)}warn(...e){if(!(this.#n>he.warn))return console.warn(...this.#e,...e)}error(...e){if(!(this.#n>he.error))return this.#r&&this.#r(...e),console.error(...this.#e,...e)}}const ut=new $r;let Ut="env",Pr;ut.level=Ut;ut.errorHandler=Pr;const fe=ut,Ao=i=>{Ut=i,ut.level=i},pe=i=>{const e=new $r(i);return e.level=Ut,e.errorHandler=Pr,e},dr=i=>{const e={};for(const[t,r]of Object.entries(i.operations))r&&(e[t]=r.map(n=>(delete n.resultingState,n)));return{...i,operations:e}};class Ls{index=0;cache;constructor(e){this.cache=e}createStorage(){const e=this.index;this.index+=1;function t(n){return`${e}-${n}`}const r={get:n=>this.cache.get(t(n)),set:(n,s)=>(this.cache.set(t(n),s),r),delete:n=>this.cache.delete(t(n)),clear:()=>{this.cache.clear()}};return r}}class Us{cache;cacheStorageManager;idToDocument;idToDrive;slugToDriveId;constructor(e=new Map){this.cache=e,this.cacheStorageManager=new Ls(e),this.idToDocument=this.cacheStorageManager.createStorage(),this.idToDrive=this.cacheStorageManager.createStorage(),this.slugToDriveId=this.cacheStorageManager.createStorage()}clear(){this.idToDocument.clear(),this.idToDrive.clear(),this.slugToDriveId.clear()}async setDocument(e,t){const r=dr(t);this.idToDocument.set(e,r)}async getDocument(e){return this.idToDocument.get(e)}async deleteDocument(e){return this.idToDocument.delete(e)}async setDrive(e,t){const r=dr(t);this.idToDrive.set(e,r)}async getDrive(e){return this.idToDrive.get(e)}async deleteDrive(e){const t=this.idToDrive.get(e);if(!t)return!1;const r=t.header.slug.length>0?t.header.slug:e;return r&&this.slugToDriveId.delete(r),this.idToDrive.delete(e)}async setDriveBySlug(e,t){const r=t.header.id;this.slugToDriveId.set(e,r),this.setDrive(r,t)}async getDriveBySlug(e){const t=this.slugToDriveId.get(e);if(t)return this.getDrive(t)}async deleteDriveBySlug(e){const t=this.slugToDriveId.get(e);return t?(this.slugToDriveId.delete(e),this.deleteDrive(t)):!1}}const Bs="phdd",Fs=i=>i!=null;Cs().refine(i=>Fs(i));const ks=xr(["Internal","MatrixConnect","PullResponder","RESTWebhook","SecureConnect","SwitchboardPush"]),qs=xr(["PullResponder"]);function Lr(){return W({documentType:$(),id:$(),name:$(),parentFolder:$().nullish()})}function Ur(){return W({id:$(),name:$(),parentFolder:$().nullish()})}function Br(){return W({listener:zr()})}function Fr(){return W({trigger:Kr()})}function kr(){return W({srcId:$(),targetId:$(),targetName:$().nullish(),targetParentFolder:$().nullish()})}function qr(){return W({id:$()})}function zs(){return W({__typename:ge("DocumentDriveLocalState").optional(),availableOffline:Ze(),listeners:Oe(zr()),sharingType:$().nullable(),triggers:Oe(Kr())})}function js(){return W({__typename:ge("DocumentDriveState").optional(),icon:$().nullable(),name:$(),nodes:Oe(Qs())})}function Hs(){return W({__typename:ge("FileNode").optional(),documentType:$(),id:$(),kind:$(),name:$(),parentFolder:$().nullable()})}function Gs(){return W({__typename:ge("FolderNode").optional(),id:$(),kind:$(),name:$(),parentFolder:$().nullable()})}function zr(){return W({__typename:ge("Listener").optional(),block:Ze(),callInfo:Js().nullable(),filter:Ys(),label:$().nullable(),listenerId:$(),system:Ze()})}function Js(){return W({__typename:ge("ListenerCallInfo").optional(),data:$().nullable(),name:$().nullable(),transmitterType:ks.nullable()})}function Ys(){return W({__typename:ge("ListenerFilter").optional(),branch:Oe($()).nullable(),documentId:Oe($()).nullable(),documentType:Oe($()),scope:Oe($()).nullable()})}function jr(){return W({srcFolder:$(),targetParentFolder:$().nullish()})}function Qs(){return Ns([Hs(),Gs()])}function Vs(){return W({__typename:ge("PullResponderTriggerData").optional(),interval:$(),listenerId:$(),url:$()})}function Hr(){return W({listenerId:$()})}function Gr(){return W({triggerId:$()})}function Jr(){return W({availableOffline:Ze()})}function Yr(){return W({icon:$()})}function Qr(){return W({name:$()})}function Vr(){return W({type:$()})}function Kr(){return W({__typename:ge("Trigger").optional(),data:Ks().nullable(),id:$(),type:qs})}function Ks(){return Vs()}function Wr(){return W({documentType:$().nullish(),id:$(),name:$().nullish(),parentFolder:$().nullish()})}function Xr(){return W({id:$(),name:$().nullish(),parentFolder:$().nullish()})}function Ws(i){return i&&typeof i=="object"&&"synchronizationUnits"in i?oe("ADD_FILE",{...i},void 0,void 0,"global"):oe("ADD_FILE",{...i},void 0,Lr,"global")}const Xs=i=>oe("ADD_FOLDER",{...i},void 0,Ur,"global"),Zs=i=>oe("DELETE_NODE",{...i},void 0,qr,"global"),ei=i=>oe("UPDATE_FILE",{...i},void 0,Wr,"global"),ti=i=>oe("UPDATE_NODE",{...i},void 0,Xr,"global"),ri=i=>oe("COPY_NODE",{...i},void 0,kr,"global"),ni=i=>oe("MOVE_NODE",{...i},void 0,jr,"global"),si=i=>oe("SET_DRIVE_NAME",{...i},void 0,Qr,"global"),ii=i=>oe("SET_DRIVE_ICON",{...i},void 0,Yr,"global"),Zr=i=>oe("SET_SHARING_TYPE",{...i},void 0,Vr,"local"),oi=i=>oe("SET_AVAILABLE_OFFLINE",{...i},void 0,Jr,"local"),ai=i=>oe("ADD_LISTENER",{...i},void 0,Br,"local"),en=i=>oe("REMOVE_LISTENER",{...i},void 0,Hr,"local"),ci=i=>oe("ADD_TRIGGER",{...i},void 0,Fr,"local"),tn=i=>oe("REMOVE_TRIGGER",{...i},void 0,Gr,"local"),ui=Object.freeze(Object.defineProperty({__proto__:null,addFile:Ws,addFolder:Xs,addListener:ai,addTrigger:ci,copyNode:ri,deleteNode:Zs,moveNode:ni,removeListener:en,removeTrigger:tn,setAvailableOffline:oi,setDriveIcon:ii,setDriveName:si,setSharingType:Zr,updateFile:ei,updateNode:ti},Symbol.toStringTag,{value:"Module"})),di={id:"powerhouse/document-drive",name:"DocumentDrive",extension:"phdd",description:"",author:{name:"Powerhouse Inc",website:"https://www.powerhouse.inc/"},specifications:[{version:1,changeLog:[],state:{global:{schema:`type FolderNode {
1
+ import{c as Ee,g as Pt}from"./react-DQSxOgtG.js";import{c as oe,a as ds,i as ls,B as hs,b as fs,d as gs,e as ps,f as ms,g as ct,h as Lt,j as ys,p as Nr,k as Le,v as He,l as ar,m as cr,r as vs,n as Dt,s as Ge,o as ws,q as bs,t as Ds,u as Ve,w as Cr,x as Ss,y as Es,z as Is,A as Je}from"./document_model-DB4SzBSe.js";import{a as Ts,p as Rs,G as Ms,b as Os,c as St,d as ur,e as Et,f as _s,g as As}from"./graphql-BS4Brs_E.js";import{o as W,s as $,e as Ze,a as pe,_ as xr,d as Oe,u as Ns,b as Cs}from"./zod-BpTyxkjy.js";import{i as xs,L as he}from"./config-CU-aFfVJ.js";function $s(i,e){for(var t=0;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const n in r)if(n!=="default"&&!(n in i)){const s=Object.getOwnPropertyDescriptor(r,n);s&&Object.defineProperty(i,n,s.get?s:{enumerable:!0,get:()=>r[n]})}}}return Object.freeze(Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}))}var Ps={};class $r{#e;#t="env";#r;constructor(e,t){this.#e=(e||[]).map(r=>`[${r}]`),this.#r=t,this.log=this.log.bind(this),this.info=this.info.bind(this),this.warn=this.warn.bind(this),this.error=this.error.bind(this),this.debug=this.debug.bind(this),this.verbose=this.verbose.bind(this)}get level(){return this.#t}set level(e){if(e!=="env"&&!xs(e))throw new Error(`Invalid log level: ${JSON.stringify(e)}.
2
+ Must be one of ${Object.keys(he).concat(["env"]).join(", ")}.`);this.#t=e}get errorHandler(){return this.#r}set errorHandler(e){this.#r=e}get#n(){if(this.#t==="env"){const e=typeof globalThis<"u"&&globalThis.process&&"env"in globalThis.process?Ps.LOG_LEVEL:void 0;return e?e in he?he[e]:he.info:he.info}return he[this.#t]}log(...e){return this.debug(...e)}verbose(...e){if(!(this.#n>he.verbose))return this.debug(...e)}debug(...e){if(!(this.#n>he.debug))return console.debug(...this.#e,...e)}info(...e){if(!(this.#n>he.info))return console.info(...this.#e,...e)}warn(...e){if(!(this.#n>he.warn))return console.warn(...this.#e,...e)}error(...e){if(!(this.#n>he.error))return this.#r&&this.#r(...e),console.error(...this.#e,...e)}}const ut=new $r;let Ut="env",Pr;ut.level=Ut;ut.errorHandler=Pr;const fe=ut,Ao=i=>{Ut=i,ut.level=i},me=i=>{const e=new $r(i);return e.level=Ut,e.errorHandler=Pr,e},dr=i=>{const e={};for(const[t,r]of Object.entries(i.operations))r&&(e[t]=r.map(n=>(delete n.resultingState,n)));return{...i,operations:e}};class Ls{index=0;cache;constructor(e){this.cache=e}createStorage(){const e=this.index;this.index+=1;function t(n){return`${e}-${n}`}const r={get:n=>this.cache.get(t(n)),set:(n,s)=>(this.cache.set(t(n),s),r),delete:n=>this.cache.delete(t(n)),clear:()=>{this.cache.clear()}};return r}}class Us{cache;cacheStorageManager;idToDocument;idToDrive;slugToDriveId;constructor(e=new Map){this.cache=e,this.cacheStorageManager=new Ls(e),this.idToDocument=this.cacheStorageManager.createStorage(),this.idToDrive=this.cacheStorageManager.createStorage(),this.slugToDriveId=this.cacheStorageManager.createStorage()}clear(){this.idToDocument.clear(),this.idToDrive.clear(),this.slugToDriveId.clear()}async setDocument(e,t){const r=dr(t);this.idToDocument.set(e,r)}async getDocument(e){return this.idToDocument.get(e)}async deleteDocument(e){return this.idToDocument.delete(e)}async setDrive(e,t){const r=dr(t);this.idToDrive.set(e,r)}async getDrive(e){return this.idToDrive.get(e)}async deleteDrive(e){const t=this.idToDrive.get(e);if(!t)return!1;const r=t.header.slug.length>0?t.header.slug:e;return r&&this.slugToDriveId.delete(r),this.idToDrive.delete(e)}async setDriveBySlug(e,t){const r=t.header.id;this.slugToDriveId.set(e,r),this.setDrive(r,t)}async getDriveBySlug(e){const t=this.slugToDriveId.get(e);if(t)return this.getDrive(t)}async deleteDriveBySlug(e){const t=this.slugToDriveId.get(e);return t?(this.slugToDriveId.delete(e),this.deleteDrive(t)):!1}}const Bs="phdd",Fs=i=>i!=null;Cs().refine(i=>Fs(i));const ks=xr(["Internal","MatrixConnect","PullResponder","RESTWebhook","SecureConnect","SwitchboardPush"]),qs=xr(["PullResponder"]);function Lr(){return W({documentType:$(),id:$(),name:$(),parentFolder:$().nullish()})}function Ur(){return W({id:$(),name:$(),parentFolder:$().nullish()})}function Br(){return W({listener:zr()})}function Fr(){return W({trigger:Kr()})}function kr(){return W({srcId:$(),targetId:$(),targetName:$().nullish(),targetParentFolder:$().nullish()})}function qr(){return W({id:$()})}function zs(){return W({__typename:pe("DocumentDriveLocalState").optional(),availableOffline:Ze(),listeners:Oe(zr()),sharingType:$().nullable(),triggers:Oe(Kr())})}function js(){return W({__typename:pe("DocumentDriveState").optional(),icon:$().nullable(),name:$(),nodes:Oe(Qs())})}function Hs(){return W({__typename:pe("FileNode").optional(),documentType:$(),id:$(),kind:$(),name:$(),parentFolder:$().nullable()})}function Gs(){return W({__typename:pe("FolderNode").optional(),id:$(),kind:$(),name:$(),parentFolder:$().nullable()})}function zr(){return W({__typename:pe("Listener").optional(),block:Ze(),callInfo:Js().nullable(),filter:Ys(),label:$().nullable(),listenerId:$(),system:Ze()})}function Js(){return W({__typename:pe("ListenerCallInfo").optional(),data:$().nullable(),name:$().nullable(),transmitterType:ks.nullable()})}function Ys(){return W({__typename:pe("ListenerFilter").optional(),branch:Oe($()).nullable(),documentId:Oe($()).nullable(),documentType:Oe($()),scope:Oe($()).nullable()})}function jr(){return W({srcFolder:$(),targetParentFolder:$().nullish()})}function Qs(){return Ns([Hs(),Gs()])}function Vs(){return W({__typename:pe("PullResponderTriggerData").optional(),interval:$(),listenerId:$(),url:$()})}function Hr(){return W({listenerId:$()})}function Gr(){return W({triggerId:$()})}function Jr(){return W({availableOffline:Ze()})}function Yr(){return W({icon:$()})}function Qr(){return W({name:$()})}function Vr(){return W({type:$()})}function Kr(){return W({__typename:pe("Trigger").optional(),data:Ks().nullable(),id:$(),type:qs})}function Ks(){return Vs()}function Wr(){return W({documentType:$().nullish(),id:$(),name:$().nullish(),parentFolder:$().nullish()})}function Xr(){return W({id:$(),name:$().nullish(),parentFolder:$().nullish()})}function Ws(i){return i&&typeof i=="object"&&"synchronizationUnits"in i?oe("ADD_FILE",{...i},void 0,void 0,"global"):oe("ADD_FILE",{...i},void 0,Lr,"global")}const Xs=i=>oe("ADD_FOLDER",{...i},void 0,Ur,"global"),Zs=i=>oe("DELETE_NODE",{...i},void 0,qr,"global"),ei=i=>oe("UPDATE_FILE",{...i},void 0,Wr,"global"),ti=i=>oe("UPDATE_NODE",{...i},void 0,Xr,"global"),ri=i=>oe("COPY_NODE",{...i},void 0,kr,"global"),ni=i=>oe("MOVE_NODE",{...i},void 0,jr,"global"),si=i=>oe("SET_DRIVE_NAME",{...i},void 0,Qr,"global"),ii=i=>oe("SET_DRIVE_ICON",{...i},void 0,Yr,"global"),Zr=i=>oe("SET_SHARING_TYPE",{...i},void 0,Vr,"local"),oi=i=>oe("SET_AVAILABLE_OFFLINE",{...i},void 0,Jr,"local"),ai=i=>oe("ADD_LISTENER",{...i},void 0,Br,"local"),en=i=>oe("REMOVE_LISTENER",{...i},void 0,Hr,"local"),ci=i=>oe("ADD_TRIGGER",{...i},void 0,Fr,"local"),tn=i=>oe("REMOVE_TRIGGER",{...i},void 0,Gr,"local"),ui=Object.freeze(Object.defineProperty({__proto__:null,addFile:Ws,addFolder:Xs,addListener:ai,addTrigger:ci,copyNode:ri,deleteNode:Zs,moveNode:ni,removeListener:en,removeTrigger:tn,setAvailableOffline:oi,setDriveIcon:ii,setDriveName:si,setSharingType:Zr,updateFile:ei,updateNode:ti},Symbol.toStringTag,{value:"Module"})),di={id:"powerhouse/document-drive",name:"DocumentDrive",extension:"phdd",description:"",author:{name:"Powerhouse Inc",website:"https://www.powerhouse.inc/"},specifications:[{version:1,changeLog:[],state:{global:{schema:`type FolderNode {
3
3
  id: String!
4
4
  name: String!
5
5
  kind: String!
@@ -118,8 +118,8 @@ type DocumentDriveLocalState{
118
118
  trigger: Trigger!
119
119
  }`,template:"",reducer:"",errors:[],examples:[],scope:"local"},{id:"qGCiPGpTt/cyz3HzyrBn92z30dsU=",name:"REMOVE_TRIGGER",description:"",schema:`input RemoveTriggerInput {
120
120
  triggerId: String!
121
- }`,template:"",reducer:"",errors:[],examples:[],scope:"local"}]}]}]},dt="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)}};class li 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 hi extends ie{constructor(e,t){super("CONFLICT",t,`Conflicting operation on index ${t.index}`,{existingOperation:e,newOperation:t})}}class et extends Error{constructor(e){super(`Invalid document id: ${e}`)}}class rn extends Error{constructor(e){super(`Invalid slug: ${e}`)}}var Fe;(function(i){i.ID="id",i.SLUG="slug"})(Fe||(Fe={}));class ke extends Error{documentId;constructor(e,t=Fe.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 fi extends Error{syncUnitId;constructor(e){super(`Sync unit ${JSON.stringify(e)} not found`),this.syncUnitId=e}}const tt=i=>i&&i.length>0&&/^[a-zA-Z0-9_-]+$/.test(i),nn=i=>i&&i.length>0&&/^[a-zA-Z0-9_-]+$/.test(i),Ue=i=>i&&i.length>0&&!i.includes("*")?new Set(i):null,sn=i=>({parentId:Ue(i.parentId),documentId:Ue(i.documentId),documentModelType:Ue(i.documentModelType),scope:Ue(i.scope),branch:Ue(i.branch)}),on=(i,...e)=>{const t=new Set(i);for(const r of e)for(const n of r)t.add(n);return t},an=(i,e)=>{const t=new Set;for(const r of i)e.has(r)&&t.add(r);return t};function lr(i){return i.kind==="file"}function gi(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 No(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 m=d.id;l=e(d),s[m]=l}return l};return n.map(d=>({srcId:d.id,targetId:o(d),targetName:d.name,targetParentFolder:d.parentFolder?s[d.parentFolder]:null}))}function pi(i,e){let t=0;const r=new RegExp(`^${mi(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 mi(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) ${pi(n,r)}`:r}const Ye=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(!tt(e.input.id))throw new et(e.input.id);if(!Ye(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(!Ye(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=>lr(s)).forEach(s=>{t?.({type:"DELETE_CHILD_DOCUMENT",input:{id:s.id}})})},updateFileOperation(i,e){if(e.input.name&&!Ye(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&&!Ye(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(!tt(e.input.targetId))throw new et(e.input.targetId);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),lr(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(gi(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)}},yi=(i,e,t)=>{if(ls(e))return i;const r=e;switch(r.type){case"ADD_FILE":Lr().parse(r.input),Te.addFileOperation(i[r.scope],e,t);break;case"ADD_FOLDER":Ur().parse(r.input),Te.addFolderOperation(i[r.scope],e,t);break;case"DELETE_NODE":qr().parse(r.input),Te.deleteNodeOperation(i[r.scope],e,t);break;case"UPDATE_FILE":Wr().parse(r.input),Te.updateFileOperation(i[r.scope],e,t);break;case"UPDATE_NODE":Xr().parse(r.input),Te.updateNodeOperation(i[r.scope],e,t);break;case"COPY_NODE":kr().parse(r.input),Te.copyNodeOperation(i[r.scope],e,t);break;case"MOVE_NODE":jr().parse(r.input),Te.moveNodeOperation(i[r.scope],e,t);break;case"SET_DRIVE_NAME":Qr().parse(r.input),Se.setDriveNameOperation(i[r.scope],e,t);break;case"SET_DRIVE_ICON":Yr().parse(r.input),Se.setDriveIconOperation(i[r.scope],e,t);break;case"SET_SHARING_TYPE":Vr().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":Br().parse(r.input),Se.addListenerOperation(i[r.scope],e,t);break;case"REMOVE_LISTENER":Hr().parse(r.input),Se.removeListenerOperation(i[r.scope],e,t);break;case"ADD_TRIGGER":Fr().parse(r.input),Se.addTriggerOperation(i[r.scope],e,t);break;case"REMOVE_TRIGGER":Gr().parse(r.input),Se.removeTriggerOperation(i[r.scope],e,t);break;default:return i}},cn=ds(yi),vi=fs.extend({documentType:ge(dt)}),nt=hs.extend({global:js(),local:zs()}),un=W({header:vi,state:nt,initialState:nt});function wi(i){return nt.safeParse(i).success}function bi(i){nt.parse(i)}function Di(i){return un.safeParse(i).success}function Si(i){un.parse(i)}const Ei={name:"",nodes:[],icon:null},Ii={listeners:[],triggers:[],sharingType:"private",availableOffline:!1},Bt=i=>({...Lt(),global:{...Ei,...i?.global},local:{...Ii,...i?.local}}),dn=i=>{const e=ms(Bt,i);return e.header.documentType=dt,e.header.id=ct(),e},Ti=(i,e)=>gs(i,e),Ri=i=>ps(i,cn),Mi=i=>wi(i),Oi=i=>{bi(i)},_i=i=>Di(i),Ai=i=>{Si(i)},Ni={actions:ui,reducer:cn,documentModel:ys(Lt(),di),utils:{fileExtension:Bs,createState:Bt,createDocument:dn,loadFromInput:Ri,saveToFileHandle:Ti,isStateOfType:Mi,assertIsStateOfType:Oi,isDocumentOfType:_i,assertIsDocumentOfType:Ai}};function ye(i){return i.header.documentType===dt}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 Ci(i,e){return new Date(i)<new Date(e)}function Ie(i){const e=i?.at(-1);return e?e.index+1:0}const hr=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()},fr=(()=>{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,m=r.get(l);m&&(m(),r.delete(l))},!1),o=>{const a=n();return r.set(a,o),e.postMessage(s+":"+a,{targetOrigin:"*"}),()=>{r.delete(a)}}})(),gr=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)},xi=i=>{const e=setTimeout(i,0);return()=>clearTimeout(e)};function Ft(i){return gr instanceof Error?hr instanceof Error?fr instanceof Error?xi(i):fr(i):hr(i):gr(i)}function $t(i,e=Ft){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 $i{drive;processor;taskQueueMethod;transmitQueue;constructor(e,t,r){this.drive=e,this.processor=t,this.taskQueueMethod=r===void 0?Ft: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?$t(o,this.taskQueueMethod):o()),d=()=>n(s.index-1),l=await(this.taskQueueMethod?$t(d,this.taskQueueMethod):d()),m={id:s.actionId,timestampUtcMs:s.timestampUtcMs,type:s.type,input:s.input,context:s.context,scope:e.scope};t.push({...s,state:a,previousState:l,action:m})}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 ln(i){return{selectFrom:i.selectFrom.bind(i),selectNoFrom:i.selectNoFrom.bind(i),with:i.with.bind(i),withRecursive:i.withRecursive.bind(i),withSchema:e=>ln(i.withSchema(e))}}const pr=Symbol.for("ph.IS_RELATIONAL_DB_PROCESSOR");class Pi{_namespace;_filter;relationalDb;constructor(e,t,r){this._namespace=e,this._filter=t,this.relationalDb=r}static[pr]=!0;static is(e){let t=Object.getPrototypeOf(e);for(;t;){if(t.constructor?.[pr])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 ln(this.relationalDb)}}function mr(i){return Pi.is(i)}class Co{listeners;drive;logger=pe(["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 m=mr(l);if(m&&o.some(w=>mr(w.processor)&&w.processor.namespace===l.namespace)){this.logger.debug(`Processor with namespace '${l.namespace}' already registered for drive '${e}'.`);continue}m&&await l.initAndUpgrade();const f=ct(),b={driveId:e,listenerId:f,block:!1,system:!1,filter:d,callInfo:void 0,transmitter:new $i(this.drive,l)};await this.listeners.setListener(e,b),s.push(b),o.push({filter:d,processor:l})}}}class Li{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 hn=()=>({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 Ke(i){return"documentType"in i}function fn(i){return"operations"in i}function Ui(i){return"actions"in i}class Bi{logger=pe(["EventQueueManager"]);emitter=hn();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=ct(),r=Ke(e),n=Ke(e)?void 0:fn(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(!Ke(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 Li(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 lt extends Error{}class Re extends lt{constructor(e){super(`Read drive ${e} not found.`)}}class Fi extends lt{constructor(e){super(`Read drive with slug ${e} not found.`)}}class yr extends lt{constructor(e,t){super(`Document with id ${t} not found on read drive ${e}.`)}}const kt=JSON,ki=i=>i.toUpperCase(),qi=i=>{const e={};return i.forEach((t,r)=>{e[r]=t}),e},zi=(i,e,t)=>i.document?i:{document:i,variables:e,requestHeaders:t,signal:void 0},ji=(i,e,t)=>i.query?i:{query:i,variables:e,requestHeaders:t,signal:void 0},Hi=(i,e)=>i.documents?i:{documents:i,requestHeaders:e,signal:void 0},vr=i=>{let e;const t=i.definitions.filter(r=>r.kind==="OperationDefinition");return t.length===1&&(e=t[0]?.name?.value),e},It=i=>{if(typeof i=="string"){let t;try{const r=Ts(i);t=vr(r)}catch{}return{query:i,operationName:t}}const e=vr(i);return{query:Rs(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 Qe={exports:{}},wr;function Gi(){return wr||(wr=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 m=["[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&&m.indexOf(Object.prototype.toString.call(D))>-1};function b(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 w(D){return typeof D!="string"&&(D=String(D)),D}function y(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 I(D){this.map={},D instanceof I?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)}I.prototype.append=function(D,R){D=b(D),R=w(R);var B=this.map[D];this.map[D]=B?B+", "+R:R},I.prototype.delete=function(D){delete this.map[b(D)]},I.prototype.get=function(D){return D=b(D),this.has(D)?this.map[D]:null},I.prototype.has=function(D){return this.map.hasOwnProperty(b(D))},I.prototype.set=function(D,R){this.map[b(D)]=w(R)},I.prototype.forEach=function(D,R){for(var B in this.map)this.map.hasOwnProperty(B)&&D.call(R,this.map[B],B,this)},I.prototype.keys=function(){var D=[];return this.forEach(function(R,B){D.push(B)}),y(D)},I.prototype.values=function(){var D=[];return this.forEach(function(R){D.push(R)}),y(D)},I.prototype.entries=function(){var D=[];return this.forEach(function(R,B){D.push([B,R])}),y(D)},d.iterable&&(I.prototype[Symbol.iterator]=I.prototype.entries);function _(D){if(!D._noBody){if(D.bodyUsed)return Promise.reject(new TypeError("Already read"));D.bodyUsed=!0}}function N(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=N(R);return R.readAsArrayBuffer(D),B}function U(D){var R=new FileReader,B=N(R),G=/charset=([A-Za-z0-9_-]+)/.exec(D.type),K=G?G[1]:"utf-8";return R.readAsText(D,K),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 E(D){if(D.slice)return D.slice(0);var R=new Uint8Array(D.byteLength);return R.set(new Uint8Array(D)),R.buffer}function L(){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=E(D.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):d.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(D)||f(D))?this._bodyArrayBuffer=E(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(V)}),this.json=function(){return this.text().then(JSON.parse)},this}var P=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function j(D){var R=D.toUpperCase();return P.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 I(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 I(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 K=/\?/;this.url+=(K.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}H.prototype.clone=function(){return new H(this,{body:this._bodyInit})};function V(D){var R=new FormData;return D.trim().split("&").forEach(function(B){if(B){var G=B.split("="),K=G.shift().replace(/\+/g," "),z=G.join("=").replace(/\+/g," ");R.append(decodeURIComponent(K),decodeURIComponent(z))}}),R}function Z(D){var R=new I,B=D.replace(/\r?\n[\t ]+/g," ");return B.split("\r").map(function(G){return G.indexOf(`
122
- `)===0?G.substr(1,G.length):G}).forEach(function(G){var K=G.split(":"),z=K.shift().trim();if(z){var ae=K.join(":").trim();try{R.append(z,ae)}catch(_e){console.warn("Response "+_e.message)}}}),R}L.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 I(R.headers),this.url=R.url||"",this._initBody(D)}L.call(Y.prototype),Y.prototype.clone=function(){return new Y(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new I(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 K=new H(D,R);if(K.signal&&K.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()||"")};K.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 me="response"in z?z.response:z.responseText;setTimeout(function(){B(new Y(me,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(K.method,_e(K.url),!0),K.credentials==="include"?z.withCredentials=!0:K.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 I||a.Headers&&R.headers instanceof a.Headers)){var qe=[];Object.getOwnPropertyNames(R.headers).forEach(function(ne){qe.push(b(ne)),z.setRequestHeader(ne,w(R.headers[ne]))}),K.headers.forEach(function(ne,me){qe.indexOf(me)===-1&&z.setRequestHeader(me,ne)})}else K.headers.forEach(function(ne,me){z.setRequestHeader(me,ne)});K.signal&&(K.signal.addEventListener("abort",ae),z.onreadystatechange=function(){z.readyState===4&&K.signal.removeEventListener("abort",ae)}),z.send(typeof K._bodyInit>"u"?null:K._bodyInit)})}return le.polyfill=!0,a.fetch||(a.fetch=le,a.Headers=I,a.Request=H,a.Response=Y),o.Headers=I,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})(Qe,Qe.exports)),Qe.exports}var it=Gi();const We=Pt(it),Ji=$s({__proto__:null,default:We},[it]),Ce=i=>{let e={};return i&&(typeof Headers<"u"&&i instanceof Headers||Ji&&it.Headers&&i instanceof it.Headers?e=qi(i):Array.isArray(i)?i.forEach(([t,r])=>{t&&r!==void 0&&(e[t]=r)}):e=i),e},br=i=>i.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),Yi=i=>{if(!Array.isArray(i.query)){const r=i,n=[`query=${encodeURIComponent(br(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:br(n),variables:e.variables?e.jsonSerializer.stringify(e.variables[s]):void 0}),r),[]);return`query=${encodeURIComponent(e.jsonSerializer.stringify(t))}`},Qi=i=>async e=>{const{url:t,query:r,variables:n,operationName:s,fetch:o,fetchOptions:a,middleware:d}=e,l={...e.headers};let m="",f;i==="POST"?(f=Ki(r,n,s,a.jsonSerializer),typeof f=="string"&&(l["Content-Type"]="application/json")):m=Yi({query:r,variables:n,operationName:s,jsonSerializer:a.jsonSerializer??kt});const b={method:i,headers:l,body:f,...a};let w=t,y=b;if(d){const I=await Promise.resolve(d({...b,url:t,operationName:s,variables:n})),{url:_,...N}=I;w=_,y=N}return m&&(w=`${w}?${m}`),await o(w,y)};class Vi{constructor(e,t={}){this.url=e,this.requestConfig=t,this.rawRequest=async(...r)=>{const[n,s,o]=r,a=ji(n,s,o),{headers:d,fetch:l=We,method:m="POST",requestMiddleware:f,responseMiddleware:b,...w}=this.requestConfig,{url:y}=this;a.signal!==void 0&&(w.signal=a.signal);const{operationName:I}=It(a.query);return Tt({url:y,query:a.query,variables:a.variables,headers:{...Ce(Rt(d)),...Ce(a.requestHeaders)},operationName:I,fetch:l,method:m,fetchOptions:w,middleware:f}).then(_=>(b&&b(_),_)).catch(_=>{throw b&&b(_),_})}}async request(e,...t){const[r,n]=t,s=zi(e,r,n),{headers:o,fetch:a=We,method:d="POST",requestMiddleware:l,responseMiddleware:m,...f}=this.requestConfig,{url:b}=this;s.signal!==void 0&&(f.signal=s.signal);const{query:w,operationName:y}=It(s.document);return Tt({url:b,query:w,variables:s.variables,headers:{...Ce(Rt(o)),...Ce(s.requestHeaders)},operationName:y,fetch:a,method:d,fetchOptions:f,middleware:l}).then(I=>(m&&m(I),I.data)).catch(I=>{throw m&&m(I),I})}batchRequests(e,t){const r=Hi(e,t),{headers:n,...s}=this.requestConfig;r.signal!==void 0&&(s.signal=r.signal);const o=r.documents.map(({document:d})=>It(d).query),a=r.documents.map(({variables:d})=>d);return Tt({url:this.url,query:o,variables:a,headers:{...Ce(Rt(n)),...Ce(r.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??We,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 Tt=async i=>{const{query:e,variables:t,fetchOptions:r}=i,n=Qi(ki(i.method??"post")),s=Array.isArray(i.query),o=await n(i),a=await Wi(o,r.jsonSerializer??kt),d=Array.isArray(a)?!a.some(({data:m})=>!m):!!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:m,...f}=(Array.isArray(a),a),b=r.errorPolicy==="ignore"?f:a;return{...s?{data:b}:b,headers:o.headers,status:o.status}}else{const m=typeof a=="string"?{error:a}:a;throw new xe({...m,status:o.status,headers:o.headers},{query:e,variables:t})}},Ki=(i,e,t,r)=>{const n=r??kt;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)},Wi=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()},Rt=i=>typeof i=="function"?i():i,ve=(i,...e)=>i.reduce((t,r,n)=>`${t}${r}${n in e?String(e[n]):""}`,"");async function de(i,e,t,r){const n=new Vi(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 Ms(d,l))),a}function Xe(i,e){return i instanceof St?Object.entries(i.getFields()).map(([t,r])=>{const n=r.type instanceof ur?r.type.ofType:r.type;if(n instanceof St||n instanceof Et)return`${t} { ${Xe(n,e)} }`;if(n instanceof _s){const s=n.ofType instanceof ur?n.ofType.ofType:n.ofType;if(s instanceof As)return t;if(s instanceof St||s instanceof Et)return`${t} { ${Xe(s,e)} }`;throw new Error(`List item type ${s.toString()} is not handled`)}return t}).join(" "):i instanceof Et?i.getTypes().map(t=>`... on ${e?`${e}_`:""}${t.name} { ${Xe(t,e)} }`).join(" "):""}function Xi(i,e,t){const r=Nr(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=Os(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 Xe(l.type,e)}async function Be(i,e){const t=await e.generateJwtHandler?.(i),r=t?{Authorization:`Bearer ${t}`}:{};return gn(i,r)}async function gn(i,e){let t;try{const r=await de(i,ve`
121
+ }`,template:"",reducer:"",errors:[],examples:[],scope:"local"}]}]}]},dt="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)}};class li 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 hi extends ie{constructor(e,t){super("CONFLICT",t,`Conflicting operation on index ${t.index}`,{existingOperation:e,newOperation:t})}}class et extends Error{constructor(e){super(`Invalid document id: ${e}`)}}class rn extends Error{constructor(e){super(`Invalid slug: ${e}`)}}var Fe;(function(i){i.ID="id",i.SLUG="slug"})(Fe||(Fe={}));class ke extends Error{documentId;constructor(e,t=Fe.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 fi extends Error{syncUnitId;constructor(e){super(`Sync unit ${JSON.stringify(e)} not found`),this.syncUnitId=e}}const tt=i=>i&&i.length>0&&/^[a-zA-Z0-9_-]+$/.test(i),nn=i=>i&&i.length>0&&/^[a-zA-Z0-9_-]+$/.test(i),Ue=i=>i&&i.length>0&&!i.includes("*")?new Set(i):null,sn=i=>({parentId:Ue(i.parentId),documentId:Ue(i.documentId),documentModelType:Ue(i.documentModelType),scope:Ue(i.scope),branch:Ue(i.branch)}),on=(i,...e)=>{const t=new Set(i);for(const r of e)for(const n of r)t.add(n);return t},an=(i,e)=>{const t=new Set;for(const r of i)e.has(r)&&t.add(r);return t};function lr(i){return i.kind==="file"}function gi(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 No(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 m=d.id;l=e(d),s[m]=l}return l};return n.map(d=>({srcId:d.id,targetId:o(d),targetName:d.name,targetParentFolder:d.parentFolder?s[d.parentFolder]:null}))}function pi(i,e){let t=0;const r=new RegExp(`^${mi(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 mi(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) ${pi(n,r)}`:r}const Ye=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(!tt(e.input.id))throw new et(e.input.id);if(!Ye(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(!Ye(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=>lr(s)).forEach(s=>{t?.({type:"DELETE_CHILD_DOCUMENT",input:{id:s.id}})})},updateFileOperation(i,e){if(e.input.name&&!Ye(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&&!Ye(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(!tt(e.input.targetId))throw new et(e.input.targetId);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),lr(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(gi(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)}},yi=(i,e,t)=>{if(ls(e))return i;const r=e;switch(r.type){case"ADD_FILE":Lr().parse(r.input),Te.addFileOperation(i[r.scope],e,t);break;case"ADD_FOLDER":Ur().parse(r.input),Te.addFolderOperation(i[r.scope],e,t);break;case"DELETE_NODE":qr().parse(r.input),Te.deleteNodeOperation(i[r.scope],e,t);break;case"UPDATE_FILE":Wr().parse(r.input),Te.updateFileOperation(i[r.scope],e,t);break;case"UPDATE_NODE":Xr().parse(r.input),Te.updateNodeOperation(i[r.scope],e,t);break;case"COPY_NODE":kr().parse(r.input),Te.copyNodeOperation(i[r.scope],e,t);break;case"MOVE_NODE":jr().parse(r.input),Te.moveNodeOperation(i[r.scope],e,t);break;case"SET_DRIVE_NAME":Qr().parse(r.input),Se.setDriveNameOperation(i[r.scope],e,t);break;case"SET_DRIVE_ICON":Yr().parse(r.input),Se.setDriveIconOperation(i[r.scope],e,t);break;case"SET_SHARING_TYPE":Vr().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":Br().parse(r.input),Se.addListenerOperation(i[r.scope],e,t);break;case"REMOVE_LISTENER":Hr().parse(r.input),Se.removeListenerOperation(i[r.scope],e,t);break;case"ADD_TRIGGER":Fr().parse(r.input),Se.addTriggerOperation(i[r.scope],e,t);break;case"REMOVE_TRIGGER":Gr().parse(r.input),Se.removeTriggerOperation(i[r.scope],e,t);break;default:return i}},cn=ds(yi),vi=fs.extend({documentType:pe(dt)}),nt=hs.extend({global:js(),local:zs()}),un=W({header:vi,state:nt,initialState:nt});function wi(i){return nt.safeParse(i).success}function bi(i){nt.parse(i)}function Di(i){return un.safeParse(i).success}function Si(i){un.parse(i)}const Ei={name:"",nodes:[],icon:null},Ii={listeners:[],triggers:[],sharingType:"private",availableOffline:!1},Bt=i=>({...Lt(),global:{...Ei,...i?.global},local:{...Ii,...i?.local}}),dn=i=>{const e=ms(Bt,i);return e.header.documentType=dt,e.header.id=ct(),e},Ti=(i,e)=>gs(i,e),Ri=i=>ps(i,cn),Mi=i=>wi(i),Oi=i=>{bi(i)},_i=i=>Di(i),Ai=i=>{Si(i)},Ni={actions:ui,reducer:cn,documentModel:ys(Lt(),di),utils:{fileExtension:Bs,createState:Bt,createDocument:dn,loadFromInput:Ri,saveToFileHandle:Ti,isStateOfType:Mi,assertIsStateOfType:Oi,isDocumentOfType:_i,assertIsDocumentOfType:Ai}};function ve(i){return i.header.documentType===dt}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 Ci(i,e){return new Date(i)<new Date(e)}function Ie(i){const e=i?.at(-1);return e?e.index+1:0}const hr=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()},fr=(()=>{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,m=r.get(l);m&&(m(),r.delete(l))},!1),o=>{const a=n();return r.set(a,o),e.postMessage(s+":"+a,{targetOrigin:"*"}),()=>{r.delete(a)}}})(),gr=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)},xi=i=>{const e=setTimeout(i,0);return()=>clearTimeout(e)};function Ft(i){return gr instanceof Error?hr instanceof Error?fr instanceof Error?xi(i):fr(i):hr(i):gr(i)}function $t(i,e=Ft){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 $i{drive;processor;taskQueueMethod;transmitQueue;constructor(e,t,r){this.drive=e,this.processor=t,this.taskQueueMethod=r===void 0?Ft: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?$t(o,this.taskQueueMethod):o()),d=()=>n(s.index-1),l=await(this.taskQueueMethod?$t(d,this.taskQueueMethod):d()),m={id:s.actionId,timestampUtcMs:s.timestampUtcMs,type:s.type,input:s.input,context:s.context,scope:e.scope};t.push({...s,state:a,previousState:l,action:m})}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 ln(i){return{selectFrom:i.selectFrom.bind(i),selectNoFrom:i.selectNoFrom.bind(i),with:i.with.bind(i),withRecursive:i.withRecursive.bind(i),withSchema:e=>ln(i.withSchema(e))}}const pr=Symbol.for("ph.IS_RELATIONAL_DB_PROCESSOR");class Pi{_namespace;_filter;relationalDb;constructor(e,t,r){this._namespace=e,this._filter=t,this.relationalDb=r}static[pr]=!0;static is(e){let t=Object.getPrototypeOf(e);for(;t;){if(t.constructor?.[pr])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 ln(this.relationalDb)}}function mr(i){return Pi.is(i)}class Co{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 m=mr(l);if(m&&o.some(w=>mr(w.processor)&&w.processor.namespace===l.namespace)){this.logger.debug(`Processor with namespace '${l.namespace}' already registered for drive '${e}'.`);continue}m&&await l.initAndUpgrade();const f=ct(),b={driveId:e,listenerId:f,block:!1,system:!1,filter:d,callInfo:void 0,transmitter:new $i(this.drive,l)};await this.listeners.setListener(e,b),s.push(b),o.push({filter:d,processor:l})}}}class Li{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 hn=()=>({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 Ke(i){return"documentType"in i}function fn(i){return"operations"in i}function Ui(i){return"actions"in i}class Bi{logger=me(["EventQueueManager"]);emitter=hn();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=ct(),r=Ke(e),n=Ke(e)?void 0:fn(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(!Ke(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 Li(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 lt extends Error{}class Re extends lt{constructor(e){super(`Read drive ${e} not found.`)}}class Fi extends lt{constructor(e){super(`Read drive with slug ${e} not found.`)}}class yr extends lt{constructor(e,t){super(`Document with id ${t} not found on read drive ${e}.`)}}const kt=JSON,ki=i=>i.toUpperCase(),qi=i=>{const e={};return i.forEach((t,r)=>{e[r]=t}),e},zi=(i,e,t)=>i.document?i:{document:i,variables:e,requestHeaders:t,signal:void 0},ji=(i,e,t)=>i.query?i:{query:i,variables:e,requestHeaders:t,signal:void 0},Hi=(i,e)=>i.documents?i:{documents:i,requestHeaders:e,signal:void 0},vr=i=>{let e;const t=i.definitions.filter(r=>r.kind==="OperationDefinition");return t.length===1&&(e=t[0]?.name?.value),e},It=i=>{if(typeof i=="string"){let t;try{const r=Ts(i);t=vr(r)}catch{}return{query:i,operationName:t}}const e=vr(i);return{query:Rs(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 Qe={exports:{}},wr;function Gi(){return wr||(wr=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 m=["[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&&m.indexOf(Object.prototype.toString.call(D))>-1};function b(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 w(D){return typeof D!="string"&&(D=String(D)),D}function y(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 I(D){this.map={},D instanceof I?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)}I.prototype.append=function(D,R){D=b(D),R=w(R);var B=this.map[D];this.map[D]=B?B+", "+R:R},I.prototype.delete=function(D){delete this.map[b(D)]},I.prototype.get=function(D){return D=b(D),this.has(D)?this.map[D]:null},I.prototype.has=function(D){return this.map.hasOwnProperty(b(D))},I.prototype.set=function(D,R){this.map[b(D)]=w(R)},I.prototype.forEach=function(D,R){for(var B in this.map)this.map.hasOwnProperty(B)&&D.call(R,this.map[B],B,this)},I.prototype.keys=function(){var D=[];return this.forEach(function(R,B){D.push(B)}),y(D)},I.prototype.values=function(){var D=[];return this.forEach(function(R){D.push(R)}),y(D)},I.prototype.entries=function(){var D=[];return this.forEach(function(R,B){D.push([B,R])}),y(D)},d.iterable&&(I.prototype[Symbol.iterator]=I.prototype.entries);function _(D){if(!D._noBody){if(D.bodyUsed)return Promise.reject(new TypeError("Already read"));D.bodyUsed=!0}}function N(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=N(R);return R.readAsArrayBuffer(D),B}function U(D){var R=new FileReader,B=N(R),G=/charset=([A-Za-z0-9_-]+)/.exec(D.type),K=G?G[1]:"utf-8";return R.readAsText(D,K),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 E(D){if(D.slice)return D.slice(0);var R=new Uint8Array(D.byteLength);return R.set(new Uint8Array(D)),R.buffer}function L(){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=E(D.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):d.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(D)||f(D))?this._bodyArrayBuffer=E(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(V)}),this.json=function(){return this.text().then(JSON.parse)},this}var P=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function j(D){var R=D.toUpperCase();return P.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 I(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 I(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 K=/\?/;this.url+=(K.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}H.prototype.clone=function(){return new H(this,{body:this._bodyInit})};function V(D){var R=new FormData;return D.trim().split("&").forEach(function(B){if(B){var G=B.split("="),K=G.shift().replace(/\+/g," "),z=G.join("=").replace(/\+/g," ");R.append(decodeURIComponent(K),decodeURIComponent(z))}}),R}function Z(D){var R=new I,B=D.replace(/\r?\n[\t ]+/g," ");return B.split("\r").map(function(G){return G.indexOf(`
122
+ `)===0?G.substr(1,G.length):G}).forEach(function(G){var K=G.split(":"),z=K.shift().trim();if(z){var ae=K.join(":").trim();try{R.append(z,ae)}catch(_e){console.warn("Response "+_e.message)}}}),R}L.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 I(R.headers),this.url=R.url||"",this._initBody(D)}L.call(Y.prototype),Y.prototype.clone=function(){return new Y(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new I(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 K=new H(D,R);if(K.signal&&K.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()||"")};K.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(K.method,_e(K.url),!0),K.credentials==="include"?z.withCredentials=!0:K.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 I||a.Headers&&R.headers instanceof a.Headers)){var qe=[];Object.getOwnPropertyNames(R.headers).forEach(function(ne){qe.push(b(ne)),z.setRequestHeader(ne,w(R.headers[ne]))}),K.headers.forEach(function(ne,ye){qe.indexOf(ye)===-1&&z.setRequestHeader(ye,ne)})}else K.headers.forEach(function(ne,ye){z.setRequestHeader(ye,ne)});K.signal&&(K.signal.addEventListener("abort",ae),z.onreadystatechange=function(){z.readyState===4&&K.signal.removeEventListener("abort",ae)}),z.send(typeof K._bodyInit>"u"?null:K._bodyInit)})}return le.polyfill=!0,a.fetch||(a.fetch=le,a.Headers=I,a.Request=H,a.Response=Y),o.Headers=I,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})(Qe,Qe.exports)),Qe.exports}var it=Gi();const We=Pt(it),Ji=$s({__proto__:null,default:We},[it]),Ce=i=>{let e={};return i&&(typeof Headers<"u"&&i instanceof Headers||Ji&&it.Headers&&i instanceof it.Headers?e=qi(i):Array.isArray(i)?i.forEach(([t,r])=>{t&&r!==void 0&&(e[t]=r)}):e=i),e},br=i=>i.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),Yi=i=>{if(!Array.isArray(i.query)){const r=i,n=[`query=${encodeURIComponent(br(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:br(n),variables:e.variables?e.jsonSerializer.stringify(e.variables[s]):void 0}),r),[]);return`query=${encodeURIComponent(e.jsonSerializer.stringify(t))}`},Qi=i=>async e=>{const{url:t,query:r,variables:n,operationName:s,fetch:o,fetchOptions:a,middleware:d}=e,l={...e.headers};let m="",f;i==="POST"?(f=Ki(r,n,s,a.jsonSerializer),typeof f=="string"&&(l["Content-Type"]="application/json")):m=Yi({query:r,variables:n,operationName:s,jsonSerializer:a.jsonSerializer??kt});const b={method:i,headers:l,body:f,...a};let w=t,y=b;if(d){const I=await Promise.resolve(d({...b,url:t,operationName:s,variables:n})),{url:_,...N}=I;w=_,y=N}return m&&(w=`${w}?${m}`),await o(w,y)};class Vi{constructor(e,t={}){this.url=e,this.requestConfig=t,this.rawRequest=async(...r)=>{const[n,s,o]=r,a=ji(n,s,o),{headers:d,fetch:l=We,method:m="POST",requestMiddleware:f,responseMiddleware:b,...w}=this.requestConfig,{url:y}=this;a.signal!==void 0&&(w.signal=a.signal);const{operationName:I}=It(a.query);return Tt({url:y,query:a.query,variables:a.variables,headers:{...Ce(Rt(d)),...Ce(a.requestHeaders)},operationName:I,fetch:l,method:m,fetchOptions:w,middleware:f}).then(_=>(b&&b(_),_)).catch(_=>{throw b&&b(_),_})}}async request(e,...t){const[r,n]=t,s=zi(e,r,n),{headers:o,fetch:a=We,method:d="POST",requestMiddleware:l,responseMiddleware:m,...f}=this.requestConfig,{url:b}=this;s.signal!==void 0&&(f.signal=s.signal);const{query:w,operationName:y}=It(s.document);return Tt({url:b,query:w,variables:s.variables,headers:{...Ce(Rt(o)),...Ce(s.requestHeaders)},operationName:y,fetch:a,method:d,fetchOptions:f,middleware:l}).then(I=>(m&&m(I),I.data)).catch(I=>{throw m&&m(I),I})}batchRequests(e,t){const r=Hi(e,t),{headers:n,...s}=this.requestConfig;r.signal!==void 0&&(s.signal=r.signal);const o=r.documents.map(({document:d})=>It(d).query),a=r.documents.map(({variables:d})=>d);return Tt({url:this.url,query:o,variables:a,headers:{...Ce(Rt(n)),...Ce(r.requestHeaders)},operationName:void 0,fetch:this.requestConfig.fetch??We,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 Tt=async i=>{const{query:e,variables:t,fetchOptions:r}=i,n=Qi(ki(i.method??"post")),s=Array.isArray(i.query),o=await n(i),a=await Wi(o,r.jsonSerializer??kt),d=Array.isArray(a)?!a.some(({data:m})=>!m):!!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:m,...f}=(Array.isArray(a),a),b=r.errorPolicy==="ignore"?f:a;return{...s?{data:b}:b,headers:o.headers,status:o.status}}else{const m=typeof a=="string"?{error:a}:a;throw new xe({...m,status:o.status,headers:o.headers},{query:e,variables:t})}},Ki=(i,e,t,r)=>{const n=r??kt;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)},Wi=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()},Rt=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 Vi(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 Ms(d,l))),a}function Xe(i,e){return i instanceof St?Object.entries(i.getFields()).map(([t,r])=>{const n=r.type instanceof ur?r.type.ofType:r.type;if(n instanceof St||n instanceof Et)return`${t} { ${Xe(n,e)} }`;if(n instanceof _s){const s=n.ofType instanceof ur?n.ofType.ofType:n.ofType;if(s instanceof As)return t;if(s instanceof St||s instanceof Et)return`${t} { ${Xe(s,e)} }`;throw new Error(`List item type ${s.toString()} is not handled`)}return t}).join(" "):i instanceof Et?i.getTypes().map(t=>`... on ${e?`${e}_`:""}${t.name} { ${Xe(t,e)} }`).join(" "):""}function Xi(i,e,t){const r=Nr(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=Os(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 Xe(l.type,e)}async function Be(i,e){const t=await e.generateJwtHandler?.(i),r=t?{Authorization:`Bearer ${t}`}:{};return gn(i,r)}async function gn(i,e){let t;try{const r=await ce(i,ge`
123
123
  query getDrive {
124
124
  drive {
125
125
  id
@@ -131,7 +131,18 @@ type DocumentDriveLocalState{
131
131
  }
132
132
  }
133
133
  }
134
- `,void 0,e);if(r.errors?.length||!r.drive)throw r.errors?.at(0)??new Error("Drive not found");t=r.drive}catch(r){throw fe.error(r),new Error("Couldn't find drive info")}return t}async function Dr(i,e,t){const{documentModel:r}=t,n=Nr(r.global.name),s=Xi(r.global,n),o=await de(i,ve`
134
+ `,void 0,e);if(r.errors?.length||!r.drive)throw r.errors?.at(0)??new Error("Drive not found");t=r.drive}catch(r){throw fe.error(r),new Error("Couldn't find drive info")}return t}async function xo(i,e){const t=i.split("/").pop()??"",r=new URL(i),n=`${r.protocol}//${r.host}/graphql/r`;let s;try{const o=await ce(n,ge`
135
+ query getDocument($identifier: String!) {
136
+ document(identifier: $identifier) {
137
+ document {
138
+ id
139
+ name
140
+ slug
141
+ state
142
+ }
143
+ }
144
+ }
145
+ `,{identifier:t},e);if(o.errors?.length||!o.document?.document)throw o.errors?.at(0)??new Error("Drive not found");const a=o.document.document,d=a.state.global;s={id:a.id,name:a.name,slug:a.slug??"",icon:d?.icon,meta:d?.meta}}catch(o){throw fe.error(o),new Error("Couldn't find drive info")}return s}async function Dr(i,e,t){const{documentModel:r}=t,n=Nr(r.global.name),s=Xi(r.global,n),o=await ce(i,ge`
135
146
  query ($id: String!) {
136
147
  document(id: $id) {
137
148
  id
@@ -174,7 +185,7 @@ type DocumentDriveLocalState{
174
185
  }
175
186
  }
176
187
  }
177
- `,{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 Zi{#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 yr(t,r)}const n=e.at(0);if(n)return n}async#n(e,t){const{errors:r,document:n}=await Dr(t,e,Ni);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,dt);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 li(r,l)}const{url:o}=n.context,{errors:a,document:d}=await Dr(o,t,s);if(a){const l=this.#r(a,e,t);if(l instanceof lt)return l;if(l)throw l}return d||new yr(e,t)}async addReadDrive(e,t){let r;t?.expectedDriveInfo?r=t.expectedDriveInfo.id:r=(await gn(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 Fi(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 eo(i){return class extends i{#e;#t=new Set;constructor(...t){super(...t),this.#e=new Zi(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 to(i){return typeof i.getReadDrives=="function"}class ro{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=>Be(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=>Be(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=>Be(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=to(this.server)?this.server:void 0,n=await r?.getReadDrives();for(const s of e){let o={...s};try{const a=s.metadata??await Be(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),m=s.options.accessLevel!==void 0,f=r&&s.options.accessLevel==="READ",b=f?l:d;if(m&&(f?d:l))try{await(f?this.server.deleteDrive(a.id):r?.deleteReadDrive(a.id))}catch(y){fe.error(y)}if(b){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},no=1500,Sr=100,so=50;let Mt;const q=()=>(Mt||(Mt=pe(["PullResponderTransmitter","static"])),Mt);class ce{logger=pe(["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 ce.getAuthHeaders(e,this.manager),s=await de(e,t,r,n);if(s.errors?.at(0)?.message.includes("Unauthorized")){const a=await ce.getAuthHeaders(e,this.manager);return de(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 de(t,ve`
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 Zi{#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 yr(t,r)}const n=e.at(0);if(n)return n}async#n(e,t){const{errors:r,document:n}=await Dr(t,e,Ni);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,dt);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 li(r,l)}const{url:o}=n.context,{errors:a,document:d}=await Dr(o,t,s);if(a){const l=this.#r(a,e,t);if(l instanceof lt)return l;if(l)throw l}return d||new yr(e,t)}async addReadDrive(e,t){let r;t?.expectedDriveInfo?r=t.expectedDriveInfo.id:r=(await gn(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 Fi(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 eo(i){return class extends i{#e;#t=new Set;constructor(...t){super(...t),this.#e=new Zi(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 to(i){return typeof i.getReadDrives=="function"}class ro{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=>Be(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=>Be(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=>Be(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=to(this.server)?this.server:void 0,n=await r?.getReadDrives();for(const s of e){let o={...s};try{const a=s.metadata??await Be(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),m=s.options.accessLevel!==void 0,f=r&&s.options.accessLevel==="READ",b=f?l:d;if(m&&(f?d:l))try{await(f?this.server.deleteDrive(a.id):r?.deleteReadDrive(a.id))}catch(y){fe.error(y)}if(b){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},no=1500,Sr=100,so=50;let Mt;const q=()=>(Mt||(Mt=me(["PullResponderTransmitter","static"])),Mt);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`
178
189
  mutation registerPullResponderListener(
179
190
  $filter: InputListenerFilter!
180
191
  $listenerId: String
@@ -186,7 +197,7 @@ type DocumentDriveLocalState{
186
197
  listenerId
187
198
  }
188
199
  }
189
- `,{filter:r,listenerId:n},o),d=a.errors?.at(0);if(d){if(d.message.includes("Unauthorized")){const l=await this.getAuthHeaders(t,s),m=await de(t,ve`
200
+ `,{filter:r,listenerId:n},o),d=a.errors?.at(0);if(d){if(d.message.includes("Unauthorized")){const l=await this.getAuthHeaders(t,s),m=await ce(t,ge`
190
201
  mutation registerPullResponderListener(
191
202
  $filter: InputListenerFilter!
192
203
  $listenerId: String
@@ -198,7 +209,7 @@ type DocumentDriveLocalState{
198
209
  listenerId
199
210
  }
200
211
  }
201
- `,{filter:r,listenerId:n},l);if(m.errors?.at(0))throw m.errors[0];if(!m.registerPullResponderListener)throw new Error("Error registering listener");return m.registerPullResponderListener.listenerId}throw d}if(!a.registerPullResponderListener)throw new Error("Error registering listener");return a.registerPullResponderListener.listenerId}static async pullStrands(e,t,r,n,s){q().verbose(`[SYNC DEBUG] PullResponderTransmitter.pullStrands called for drive: ${e}, url: ${t}, listener: ${r}, options: ${JSON.stringify(n||{})}`);const o=await this.getAuthHeaders(t,s),a=await de(t,ve`
212
+ `,{filter:r,listenerId:n},l);if(m.errors?.at(0))throw m.errors[0];if(!m.registerPullResponderListener)throw new Error("Error registering listener");return m.registerPullResponderListener.listenerId}throw d}if(!a.registerPullResponderListener)throw new Error("Error registering listener");return a.registerPullResponderListener.listenerId}static async pullStrands(e,t,r,n,s){q().verbose(`[SYNC DEBUG] PullResponderTransmitter.pullStrands called for drive: ${e}, url: ${t}, listener: ${r}, options: ${JSON.stringify(n||{})}`);const o=await this.getAuthHeaders(t,s),a=await ce(t,ge`
202
213
  query strands($listenerId: ID!) {
203
214
  system {
204
215
  sync {
@@ -236,7 +247,7 @@ type DocumentDriveLocalState{
236
247
  }
237
248
  }
238
249
  }
239
- `,{listenerId:r},o),d=a.errors?.at(0);if(d){if(d.message.includes("Unauthorized")){const m=await this.getAuthHeaders(t,s),f=await de(t,ve`
250
+ `,{listenerId:r},o),d=a.errors?.at(0);if(d){if(d.message.includes("Unauthorized")){const m=await this.getAuthHeaders(t,s),f=await ce(t,ge`
240
251
  query strands($listenerId: ID!) {
241
252
  system {
242
253
  sync {
@@ -274,22 +285,22 @@ type DocumentDriveLocalState{
274
285
  }
275
286
  }
276
287
  }
277
- `,{listenerId:r},m);if(f.errors?.at(0))throw f.errors[0];return f.system?f.system.sync.strands.map(b=>({...b,operations:b.operations.map(w=>({...w,input:JSON.parse(w.input)}))})):[]}throw d}if(!a.system)return q().verbose(`[SYNC DEBUG] No system data returned when pulling strands for drive: ${e}, listener: ${r}`),[];const l=a.system.sync.strands.map(m=>({...m,operations:m.operations.map(f=>({...f,input:JSON.parse(f.input)}))}));return q().verbose(`[SYNC DEBUG] PullResponderTransmitter.pullStrands returning ${l.length} strands for drive: ${e}, listener: ${r}`),l.length>0&&q().verbose(`[SYNC DEBUG] Strands being returned: ${l.map(m=>`${m.documentId}:${m.scope}`).join(", ")}`),l}static async acknowledgeStrands(e,t,r,n){q().verbose(`acknowledgeStrands(url: ${e}, listener: ${t})`,r);const s=[];for(let l=0;l<r.length;l+=Sr)s.push(r.slice(l,l+Sr));s.length>1&&q().verbose(`Breaking strand acknowledgement into ${s.length} chunks...`);const o=await this.getAuthHeaders(e,n);if((await Promise.allSettled(s.map(async l=>{const m=await de(e,ve`
288
+ `,{listenerId:r},m);if(f.errors?.at(0))throw f.errors[0];return f.system?f.system.sync.strands.map(b=>({...b,operations:b.operations.map(w=>({...w,input:JSON.parse(w.input)}))})):[]}throw d}if(!a.system)return q().verbose(`[SYNC DEBUG] No system data returned when pulling strands for drive: ${e}, listener: ${r}`),[];const l=a.system.sync.strands.map(m=>({...m,operations:m.operations.map(f=>({...f,input:JSON.parse(f.input)}))}));return q().verbose(`[SYNC DEBUG] PullResponderTransmitter.pullStrands returning ${l.length} strands for drive: ${e}, listener: ${r}`),l.length>0&&q().verbose(`[SYNC DEBUG] Strands being returned: ${l.map(m=>`${m.documentId}:${m.scope}`).join(", ")}`),l}static async acknowledgeStrands(e,t,r,n){q().verbose(`acknowledgeStrands(url: ${e}, listener: ${t})`,r);const s=[];for(let l=0;l<r.length;l+=Sr)s.push(r.slice(l,l+Sr));s.length>1&&q().verbose(`Breaking strand acknowledgement into ${s.length} chunks...`);const o=await this.getAuthHeaders(e,n);if((await Promise.allSettled(s.map(async l=>{const m=await ce(e,ge`
278
289
  mutation acknowledge(
279
290
  $listenerId: String!
280
291
  $revisions: [ListenerRevisionInput]
281
292
  ) {
282
293
  acknowledge(listenerId: $listenerId, revisions: $revisions)
283
294
  }
284
- `,{listenerId:t,revisions:l},o),f=m.errors?.at(0);if(f){if(f.message.includes("Unauthorized")){const b=await this.getAuthHeaders(e,n),w=await de(e,ve`
295
+ `,{listenerId:t,revisions:l},o),f=m.errors?.at(0);if(f){if(f.message.includes("Unauthorized")){const b=await this.getAuthHeaders(e,n),w=await ce(e,ge`
285
296
  mutation acknowledge(
286
297
  $listenerId: String!
287
298
  $revisions: [ListenerRevisionInput]
288
299
  ) {
289
300
  acknowledge(listenerId: $listenerId, revisions: $revisions)
290
301
  }
291
- `,{listenerId:t,revisions:l},b);if(w.errors?.at(0))throw w.errors[0];if(w.acknowledge===null||!w.acknowledge)throw new Error("Error acknowledging strands");return}throw f}if(m.acknowledge===null||!m.acknowledge)throw new Error("Error acknowledging strands")}))).filter(l=>l.status==="rejected").length>0)throw new Error("Error acknowledging strands")}static async executePull(e,t,r,n,s,o,a){q().verbose(`executePull(driveId: ${e}), trigger:`,t),q().verbose(`[SYNC DEBUG] PullResponderTransmitter.executePull starting for drive: ${e}, listenerId: ${t.data.listenerId}`);const{url:d}=t.data;let l,m;const f=t.data.listenerId;try{l=await ce.pullStrands(e,d,f,void 0,a)}catch(y){m=y;const _=m.response?.errors??[];for(const N of _)if(N.message==="Listener not found"){q().verbose(`[SYNC DEBUG] Auto-registering pull responder for drive: ${e}`),await ce.registerPullResponder(t.driveId,d,t.filter,f);try{l=await ce.pullStrands(e,d,f,void 0,a),q().verbose(`Successfully auto-registered and pulled strands for drive: ${e}, listenerId: ${f}`)}catch(C){return q().error(`Could not resolve 'Listener not found' error by registering a new pull responder for drive: ${e}, listenerId: ${f}: ${C}`),n(C),!1}break}}if(!l)return q().error(`Error pulling strands for drive, and could not auto-register: ${e}, listenerId: ${t.data.listenerId}: ${m}`),n(m),!1;if(!l.length){q().verbose(`[SYNC DEBUG] No strands returned in pull cycle for drive: ${e}, listenerId: ${t.data.listenerId}`);try{s?.([])}catch(y){q().error(`Error calling onRevisions for drive: ${e}, listenerId: ${t.data.listenerId}: ${y}`),n(y)}return!1}q().verbose(`[SYNC DEBUG] Processing ${l.length} strands in pull cycle for drive: ${e}, listenerId: ${t.data.listenerId}`);const b=[];for(const y of l){const I=y.operations.map(N=>({...N,scope:y.scope,branch:y.branch}));q().verbose(`[SYNC DEBUG] Processing strand for drive: ${y.driveId}, document: ${y.documentId}, scope: ${y.scope}, with ${I.length} operations`);let _;try{const N=await r(y,{type:"trigger",trigger:t});if(N.error)throw N.error}catch(N){q().error(`Error processing strand for drive: ${y.driveId}, document: ${y.documentId}, scope: ${y.scope}, with ${I.length} operations: ${N}`),_=N,n(_)}b.push({branch:y.branch,documentId:y.documentId||"",documentType:y.documentType,driveId:y.driveId,revision:Ie(I),scope:y.scope,status:_?_ instanceof ie?_.status:"ERROR":"SUCCESS",error:_})}q().verbose("Processed strands...");try{s?.(b)}catch(y){q().error(`Error calling onRevisions for drive: ${e}, listenerId: ${t.data.listenerId}: ${y}`),n(y)}q().verbose(`[SYNC DEBUG] Acknowledging ${b.length} strands for drive: ${e}, listenerId: ${t.data.listenerId}`);let w=!1;try{await ce.acknowledgeStrands(d,t.data.listenerId,b.map(y=>{const{error:I,..._}=y;return _}),a),w=!0}catch(y){q().error(`Error acknowledging strands for drive: ${e}, listenerId: ${t.data.listenerId}: ${y}`),n(y)}w?q().verbose(`[SYNC DEBUG] Successfully acknowledged strands for drive: ${e}, listenerId: ${t.data.listenerId}`):q().error("Failed to acknowledge strands");try{o?.(w)}catch(y){q().error(`Error calling onAcknowledge for drive: ${e}, listenerId: ${t.data.listenerId}: ${y}`),n(y)}return l.length>0}static setupPull(e,t,r,n,s,o,a){q().verbose(`[SYNC DEBUG] PullResponderTransmitter.setupPull initiated for drive: ${e}, listenerId: ${t.data.listenerId}`);const{interval:d}=t.data;let l=no;if(d)try{const w=parseInt(d);w&&(l=w)}catch{}q().verbose(`[SYNC DEBUG] Pull interval set to ${l}ms for drive: ${e}, listenerId: ${t.data.listenerId}`);let m=!1,f;return(async()=>{for(;!m;){q().verbose(`[SYNC DEBUG] Starting pull cycle for drive: ${e}, listenerId: ${t.data.listenerId}`);let w=0,y=!0;for(;y&&!m&&w<so;)w++,y=await this.executePull(e,t,r,n,s,o,a),y&&q().verbose(`[SYNC DEBUG] More strands available, continuing pull cycle for drive: ${e}, listenerId: ${t.data.listenerId}`);q().verbose(`[SYNC DEBUG] Completed pull cycle for drive: ${e}, listenerId: ${t.data.listenerId}, waiting ${l}ms for next cycle`),await new Promise(I=>{q().verbose(`Scheduling next pull in ${l} ms`),f=setTimeout(I,l)})}})().catch(w=>{q().error(`Error in executeLoop for drive: ${e}, listenerId: ${t.data.listenerId}: ${w}`)}),()=>{q().verbose(`[SYNC DEBUG] Cancelling pull loop for drive: ${e}, listenerId: ${t.data.listenerId}`),m=!0,f!==void 0&&clearTimeout(f)}}static async createPullResponderTrigger(e,t,r,n){q().verbose(`createPullResponderTrigger(drive: ${e}, url: ${t})`);const{pullFilter:s,pullInterval:o}=r,a=s??{documentId:["*"],documentType:["*"],branch:["*"],scope:["*"]},d=await ce.registerPullResponder(e,t,a,void 0,n);return{id:ct(),type:"PullResponder",driveId:e,filter:a,data:{url:t,listenerId:d,interval:o?.toString()??""}}}static isPullResponderTrigger(e){return e.type==="PullResponder"}}var Ot,Er;function io(){return Er||(Er=1,Ot={space:"",cycles:!1,replacer:(i,e)=>e,stringify:JSON.stringify}),Ot}var _t,Ir;function Me(){return Ir||(Ir=1,_t={isArray:Array.isArray,assign:Object.assign,isObject:i=>typeof i=="object",isFunction:i=>typeof i=="function",isBoolean:i=>typeof i=="boolean",isRegex:i=>i instanceof RegExp,keys:Object.keys}),_t}var At,Tr;function oo(){if(Tr)return At;Tr=1;const i=io(),e=Me().isFunction,t=Me().isBoolean,r=Me().isObject,n=Me().isArray,s=Me().isRegex,o=Me().assign,a=Me().keys;function d(m){return m==null?m:s(m)?m.toString():m.toJSON?m.toJSON():m}function l(m,f){f=f||o({},i),e(f)&&(f={compare:f});const b=f.space||i.space,w=t(f.cycles)?f.cycles:i.cycles,y=f.replacer||i.replacer,I=f.stringify||i.stringify,_=f.compare&&(function(C){return function(U){return function(F,E){const L={key:F,value:U[F]},P={key:E,value:U[E]};return C(L,P)}}})(f.compare);w||I(m);const N=[];return(function C(U,F,E,L){const P=b?`
292
- `+new Array(L+1).join(b):"",j=b?": ":":";if(E=d(E),E=y.call(U,F,E),E!==void 0){if(!r(E)||E===null)return I(E);if(n(E)){const H=[];for(let V=0;V<E.length;V++){const Z=C(E,V,E[V],L+1)||I(null);H.push(P+b+Z)}return"["+H.join(",")+P+"]"}else{if(w){if(N.indexOf(E)!==-1)return I("[Circular]");N.push(E)}const H=a(E).sort(_&&_(E)),V=[];for(let Z=0;Z<H.length;Z++){const Y=H[Z],se=C(E,Y,E[Y],L+1);if(!se)continue;const le=I(Y)+j+se;V.push(P+b+le)}return N.splice(N.indexOf(E),1),"{"+V.join(",")+P+"}"}}})({"":m},"",m,0)}return At=l,At}var ao=oo();const co=Pt(ao),Rr=10;class pn{targetURL;manager;logger=pe(["SwitchboardPushTransmitter",Math.floor(Math.random()*999).toString()]);constructor(e,t){this.targetURL=e,this.manager=t}async getAuthHeaders(){if(!this.manager?.generateJwtHandler)return this.logger.verbose(`No JWT handler available for ${this.targetURL}`),{};try{const e=await this.manager.generateJwtHandler(this.targetURL);return e?{Authorization:`Bearer ${e}`}:(this.logger.verbose(`No JWT generated for ${this.targetURL}`),{})}catch(e){return this.logger.error(`Error generating JWT for ${this.targetURL}:`,e),{}}}async requestWithAuth(e,t){const r=await this.getAuthHeaders(),n=await de(this.targetURL,e,t,r);if(n.errors?.at(0)?.message.includes("Unauthorized")){const o=await this.getAuthHeaders();return de(this.targetURL,e,t,o)}return n}async transmit(e,t){if(t.type==="trigger"&&t.trigger.data?.url===this.targetURL)return this.logger.verbose(`Cutting trigger loop from ${this.targetURL}.`),e.map(s=>({driveId:s.driveId,documentId:s.documentId,documentType:s.documentType,scope:s.scope,branch:s.branch,status:"SUCCESS",revision:Ie(s.operations)}));const r=[];let n=0;for(let s=0;n<=Rr&&s<e.length;s++){const o=e.at(s);if(!o)break;const a=Math.min(Rr-n,o.operations.length);r.push({...o,operations:o.operations.slice(0,a)}),n+=a}this.logger.verbose(` Total update: [${e.map(s=>s.operations.length).join(", ")}] operations`),this.logger.verbose(`Culled update: [${r.map(s=>s.operations.length).join(", ")}] operations`);try{const s=await this.requestWithAuth(ve`
302
+ `,{listenerId:t,revisions:l},b);if(w.errors?.at(0))throw w.errors[0];if(w.acknowledge===null||!w.acknowledge)throw new Error("Error acknowledging strands");return}throw f}if(m.acknowledge===null||!m.acknowledge)throw new Error("Error acknowledging strands")}))).filter(l=>l.status==="rejected").length>0)throw new Error("Error acknowledging strands")}static async executePull(e,t,r,n,s,o,a){q().verbose(`executePull(driveId: ${e}), trigger:`,t),q().verbose(`[SYNC DEBUG] PullResponderTransmitter.executePull starting for drive: ${e}, listenerId: ${t.data.listenerId}`);const{url:d}=t.data;let l,m;const f=t.data.listenerId;try{l=await ue.pullStrands(e,d,f,void 0,a)}catch(y){m=y;const _=m.response?.errors??[];for(const N of _)if(N.message==="Listener not found"){q().verbose(`[SYNC DEBUG] Auto-registering pull responder for drive: ${e}`),await ue.registerPullResponder(t.driveId,d,t.filter,f);try{l=await ue.pullStrands(e,d,f,void 0,a),q().verbose(`Successfully auto-registered and pulled strands for drive: ${e}, listenerId: ${f}`)}catch(C){return q().error(`Could not resolve 'Listener not found' error by registering a new pull responder for drive: ${e}, listenerId: ${f}: ${C}`),n(C),!1}break}}if(!l)return q().error(`Error pulling strands for drive, and could not auto-register: ${e}, listenerId: ${t.data.listenerId}: ${m}`),n(m),!1;if(!l.length){q().verbose(`[SYNC DEBUG] No strands returned in pull cycle for drive: ${e}, listenerId: ${t.data.listenerId}`);try{s?.([])}catch(y){q().error(`Error calling onRevisions for drive: ${e}, listenerId: ${t.data.listenerId}: ${y}`),n(y)}return!1}q().verbose(`[SYNC DEBUG] Processing ${l.length} strands in pull cycle for drive: ${e}, listenerId: ${t.data.listenerId}`);const b=[];for(const y of l){const I=y.operations.map(N=>({...N,scope:y.scope,branch:y.branch}));q().verbose(`[SYNC DEBUG] Processing strand for drive: ${y.driveId}, document: ${y.documentId}, scope: ${y.scope}, with ${I.length} operations`);let _;try{const N=await r(y,{type:"trigger",trigger:t});if(N.error)throw N.error}catch(N){q().error(`Error processing strand for drive: ${y.driveId}, document: ${y.documentId}, scope: ${y.scope}, with ${I.length} operations: ${N}`),_=N,n(_)}b.push({branch:y.branch,documentId:y.documentId||"",documentType:y.documentType,driveId:y.driveId,revision:Ie(I),scope:y.scope,status:_?_ instanceof ie?_.status:"ERROR":"SUCCESS",error:_})}q().verbose("Processed strands...");try{s?.(b)}catch(y){q().error(`Error calling onRevisions for drive: ${e}, listenerId: ${t.data.listenerId}: ${y}`),n(y)}q().verbose(`[SYNC DEBUG] Acknowledging ${b.length} strands for drive: ${e}, listenerId: ${t.data.listenerId}`);let w=!1;try{await ue.acknowledgeStrands(d,t.data.listenerId,b.map(y=>{const{error:I,..._}=y;return _}),a),w=!0}catch(y){q().error(`Error acknowledging strands for drive: ${e}, listenerId: ${t.data.listenerId}: ${y}`),n(y)}w?q().verbose(`[SYNC DEBUG] Successfully acknowledged strands for drive: ${e}, listenerId: ${t.data.listenerId}`):q().error("Failed to acknowledge strands");try{o?.(w)}catch(y){q().error(`Error calling onAcknowledge for drive: ${e}, listenerId: ${t.data.listenerId}: ${y}`),n(y)}return l.length>0}static setupPull(e,t,r,n,s,o,a){q().verbose(`[SYNC DEBUG] PullResponderTransmitter.setupPull initiated for drive: ${e}, listenerId: ${t.data.listenerId}`);const{interval:d}=t.data;let l=no;if(d)try{const w=parseInt(d);w&&(l=w)}catch{}q().verbose(`[SYNC DEBUG] Pull interval set to ${l}ms for drive: ${e}, listenerId: ${t.data.listenerId}`);let m=!1,f;return(async()=>{for(;!m;){q().verbose(`[SYNC DEBUG] Starting pull cycle for drive: ${e}, listenerId: ${t.data.listenerId}`);let w=0,y=!0;for(;y&&!m&&w<so;)w++,y=await this.executePull(e,t,r,n,s,o,a),y&&q().verbose(`[SYNC DEBUG] More strands available, continuing pull cycle for drive: ${e}, listenerId: ${t.data.listenerId}`);q().verbose(`[SYNC DEBUG] Completed pull cycle for drive: ${e}, listenerId: ${t.data.listenerId}, waiting ${l}ms for next cycle`),await new Promise(I=>{q().verbose(`Scheduling next pull in ${l} ms`),f=setTimeout(I,l)})}})().catch(w=>{q().error(`Error in executeLoop for drive: ${e}, listenerId: ${t.data.listenerId}: ${w}`)}),()=>{q().verbose(`[SYNC DEBUG] Cancelling pull loop for drive: ${e}, listenerId: ${t.data.listenerId}`),m=!0,f!==void 0&&clearTimeout(f)}}static async createPullResponderTrigger(e,t,r,n){q().verbose(`createPullResponderTrigger(drive: ${e}, url: ${t})`);const{pullFilter:s,pullInterval:o}=r,a=s??{documentId:["*"],documentType:["*"],branch:["*"],scope:["*"]},d=await ue.registerPullResponder(e,t,a,void 0,n);return{id:ct(),type:"PullResponder",driveId:e,filter:a,data:{url:t,listenerId:d,interval:o?.toString()??""}}}static isPullResponderTrigger(e){return e.type==="PullResponder"}}var Ot,Er;function io(){return Er||(Er=1,Ot={space:"",cycles:!1,replacer:(i,e)=>e,stringify:JSON.stringify}),Ot}var _t,Ir;function Me(){return Ir||(Ir=1,_t={isArray:Array.isArray,assign:Object.assign,isObject:i=>typeof i=="object",isFunction:i=>typeof i=="function",isBoolean:i=>typeof i=="boolean",isRegex:i=>i instanceof RegExp,keys:Object.keys}),_t}var At,Tr;function oo(){if(Tr)return At;Tr=1;const i=io(),e=Me().isFunction,t=Me().isBoolean,r=Me().isObject,n=Me().isArray,s=Me().isRegex,o=Me().assign,a=Me().keys;function d(m){return m==null?m:s(m)?m.toString():m.toJSON?m.toJSON():m}function l(m,f){f=f||o({},i),e(f)&&(f={compare:f});const b=f.space||i.space,w=t(f.cycles)?f.cycles:i.cycles,y=f.replacer||i.replacer,I=f.stringify||i.stringify,_=f.compare&&(function(C){return function(U){return function(F,E){const L={key:F,value:U[F]},P={key:E,value:U[E]};return C(L,P)}}})(f.compare);w||I(m);const N=[];return(function C(U,F,E,L){const P=b?`
303
+ `+new Array(L+1).join(b):"",j=b?": ":":";if(E=d(E),E=y.call(U,F,E),E!==void 0){if(!r(E)||E===null)return I(E);if(n(E)){const H=[];for(let V=0;V<E.length;V++){const Z=C(E,V,E[V],L+1)||I(null);H.push(P+b+Z)}return"["+H.join(",")+P+"]"}else{if(w){if(N.indexOf(E)!==-1)return I("[Circular]");N.push(E)}const H=a(E).sort(_&&_(E)),V=[];for(let Z=0;Z<H.length;Z++){const Y=H[Z],se=C(E,Y,E[Y],L+1);if(!se)continue;const le=I(Y)+j+se;V.push(P+b+le)}return N.splice(N.indexOf(E),1),"{"+V.join(",")+P+"}"}}})({"":m},"",m,0)}return At=l,At}var ao=oo();const co=Pt(ao),Rr=10;class pn{targetURL;manager;logger=me(["SwitchboardPushTransmitter",Math.floor(Math.random()*999).toString()]);constructor(e,t){this.targetURL=e,this.manager=t}async getAuthHeaders(){if(!this.manager?.generateJwtHandler)return this.logger.verbose(`No JWT handler available for ${this.targetURL}`),{};try{const e=await this.manager.generateJwtHandler(this.targetURL);return e?{Authorization:`Bearer ${e}`}:(this.logger.verbose(`No JWT generated for ${this.targetURL}`),{})}catch(e){return this.logger.error(`Error generating JWT for ${this.targetURL}:`,e),{}}}async requestWithAuth(e,t){const r=await this.getAuthHeaders(),n=await ce(this.targetURL,e,t,r);if(n.errors?.at(0)?.message.includes("Unauthorized")){const o=await this.getAuthHeaders();return ce(this.targetURL,e,t,o)}return n}async transmit(e,t){if(t.type==="trigger"&&t.trigger.data?.url===this.targetURL)return this.logger.verbose(`Cutting trigger loop from ${this.targetURL}.`),e.map(s=>({driveId:s.driveId,documentId:s.documentId,documentType:s.documentType,scope:s.scope,branch:s.branch,status:"SUCCESS",revision:Ie(s.operations)}));const r=[];let n=0;for(let s=0;n<=Rr&&s<e.length;s++){const o=e.at(s);if(!o)break;const a=Math.min(Rr-n,o.operations.length);r.push({...o,operations:o.operations.slice(0,a)}),n+=a}this.logger.verbose(` Total update: [${e.map(s=>s.operations.length).join(", ")}] operations`),this.logger.verbose(`Culled update: [${r.map(s=>s.operations.length).join(", ")}] operations`);try{const s=await this.requestWithAuth(ge`
293
304
  mutation pushUpdates($strands: [InputStrandUpdate!]) {
294
305
  pushUpdates(strands: $strands) {
295
306
  driveId
@@ -302,4 +313,4 @@ type DocumentDriveLocalState{
302
313
  error
303
314
  }
304
315
  }
305
- `,{strands:r.map(o=>({driveId:o.driveId,documentId:o.documentId,documentType:o.documentType,scope:o.scope,branch:o.branch,operations:o.operations.map(a=>({index:a.index,skip:a.skip,type:a.type,id:a.id??void 0,actionId:a.actionId,input:co(a.input),hash:a.hash,timestampUtcMs:a.timestampUtcMs,context:a.context?{signer:a.context.signer}:void 0}))}))});if(!s.pushUpdates)throw new Error("Couldn't update listener revision");return s.pushUpdates}catch(s){throw this.logger.error(s),s}}}function Mr(i,e){return e?Object.keys(i).reduce((t,r)=>{const n=e[r];if(n!==void 0){const s=i[r];s&&(t[r]=s.filter(o=>o.index<=n))}return t},{global:[],local:[]}):i}function Nt(i,e){return!e||Object.entries(e).find(([t,r])=>{const n=i.operations[t]?.at(-1);return r===-1?n!==void 0:n?.index!==r})===void 0}function Ct(i){return{id:uo(i),documentType:lo(i),document:ho(i)}}function uo(i){return"id"in i?i.id:"header"in i?i.header.id:"document"in i?i.document.header.id:void 0}function lo(i){return"documentType"in i?i.documentType:"header"in i?i.header.documentType:i.document.header.documentType}function ho(i){return"document"in i?i.document:void 0}function fo(i){return["LOCAL","CLOUD","PUBLIC"].includes(i)}function $o(i){if(typeof i!="object")return"LOCAL";const e="readContext"in i,{sharingType:t}=e?{sharingType:"PUBLIC"}:i.state.local,r=t?.toUpperCase();return!r||r==="PRIVATE"||!fo(r)?"LOCAL":r}class go{logger=pe(["BaseDocumentDriveServer"]);documentModelModules;legacyStorage;documentStorage;cache;queueManager;eventEmitter;options;listenerManager;synchronizationManager;generateJwtHandler;defaultDrivesManager;defaultDrivesManagerDelegate={detachDrive:this.detachDrive.bind(this),emit:(...e)=>this.eventEmitter.emit("defaultRemoteDrive",...e)};queueDelegate={exists:e=>this.documentStorage.exists(e),processOperationJob:async({documentId:e,operations:t,options:r})=>{const n=await this.getDocument(e);return ye(n)?this.processDriveOperations(e,t,r):this.processOperations(e,t,r)},processActionJob:async({documentId:e,actions:t,options:r})=>{const n=await this.getDocument(e);return ye(n)?this.processDriveActions(e,t,r):this.processActions(e,t,r)},processDocumentJob:async({documentId:e,documentType:t,header:r,initialState:n,options:s})=>{const a=this.getDocumentModelModule(t).utils.createDocument(n),d=Le(e,t);a.header.id=e,a.header.sig=d.sig,a.header.documentType=t,r&&(a.header.meta=r.meta);try{const l=await this.createDocument({document:a},s?.source??{type:"local"},a.header.meta);return{status:"SUCCESS",operations:[],document:l,signals:[]}}catch(l){const m=l instanceof Error?l:new Error(JSON.stringify(l));return{status:"ERROR",error:new ie("ERROR",void 0,`Error creating document: ${m.message}`,m),operations:[],document:void 0,signals:[]}}},processJob:async e=>{if(fn(e))return this.queueDelegate.processOperationJob(e);if(Ui(e))return this.queueDelegate.processActionJob(e);if(Ke(e))return this.queueDelegate.processDocumentJob(e);throw new Error("Unknown job type",e)}};triggerMap=new Map;initializePromise;enableDualActionCreate;constructor(e,t,r,n,s,o,a,d,l){this.documentModelModules=e,this.legacyStorage=t,this.documentStorage=r,this.cache=n,this.queueManager=s,this.eventEmitter=o,this.synchronizationManager=a,this.listenerManager=d,this.options={...l,defaultDrives:{...l?.defaultDrives},listenerManager:{...ot,...l?.listenerManager},jwtHandler:l?.jwtHandler===void 0?()=>Promise.resolve(""):l.jwtHandler,taskQueueMethod:l?.taskQueueMethod===void 0?Ft:l.taskQueueMethod,featureFlags:{...l?.featureFlags}},this.enableDualActionCreate=l?.featureFlags?.enableDualActionCreate??!1,this.enableDualActionCreate&&this.logger.warn("Dual action create is enabled."),this.defaultDrivesManager=new ro(this,this.defaultDrivesManagerDelegate,l),this.initializePromise=this._initialize()}get listeners(){return this.listenerManager}initialize(){return this.initializePromise}async _initialize(){await this.listenerManager.initialize(this.handleListenerError.bind(this)),await this.queueManager.init(this.queueDelegate,r=>{this.logger.error("Error initializing queue manager",r)});try{await this.defaultDrivesManager.removeOldremoteDrives()}catch(r){this.logger.error(r)}const e=[],t=await this.getDrives();for(const r of t)await this._initializeDrive(r).catch(n=>{this.logger.error(`Error initializing drive ${r}`,n),e.push(n)});return this.options.defaultDrives.loadOnInit!==!1&&await this.defaultDrivesManager.initializeDefaultRemoteDrives(),e.length===0?null:e}setDocumentModelModules(e){this.documentModelModules=[...e],this.synchronizationManager.setDocumentModelModules([...e]),this.eventEmitter.emit("documentModelModules",[...e])}initializeDefaultRemoteDrives(){return this.defaultDrivesManager.initializeDefaultRemoteDrives()}getDefaultRemoteDrives(){return this.defaultDrivesManager.getDefaultRemoteDrives()}setDefaultDriveAccessLevel(e,t){return this.defaultDrivesManager.setDefaultDriveAccessLevel(e,t)}setAllDefaultDrivesAccessLevel(e){return this.defaultDrivesManager.setAllDefaultDrivesAccessLevel(e)}getOperationSource(e){return e.type==="local"?"push":"pull"}handleListenerError(e,t,r){this.logger.error(`Listener ${r.listener.label??r.listener.listenerId} error:`,e);const n=e instanceof ie?e.status:"ERROR";this.synchronizationManager.updateSyncStatus(t,{push:n},e)}shouldSyncRemoteDrive(e){return e.state.local.availableOffline&&e.state.local.triggers.length>0}async startSyncRemoteDrive(e){let t=this.triggerMap.get(e);const r=await this.synchronizationManager.getSynchronizationUnitsIds(e),n=await this.getDrive(e);for(const s of n.state.local.triggers)if(!t?.get(s.id)){t||(t=new Map),this.synchronizationManager.updateSyncStatus(e,{pull:"SYNCING"});for(const o of r)this.synchronizationManager.updateSyncStatus(o,{pull:"SYNCING"});if(ce.isPullResponderTrigger(s)){let o=!0;const a=ce.setupPull(e,s,this.saveStrand.bind(this),d=>{const l=d instanceof ie?d.status:"ERROR";this.synchronizationManager.updateSyncStatus(e,{pull:l},d),d instanceof xe&&this.eventEmitter.emit("clientStrandsError",e,s,d.response.status,d.message)},async d=>{d.filter(m=>m.status!=="SUCCESS").length<1&&this.synchronizationManager.updateSyncStatus(e,{pull:"SUCCESS"});for(const m of d){const{documentId:f,scope:b,branch:w,status:y,error:I}=m;this.synchronizationManager.updateSyncStatus({documentId:f,scope:b,branch:w},{pull:y},I)}if(o){o=!1,(await this.synchronizationManager.getSynchronizationUnitsIds(e)).filter(w=>!d.find(y=>y.documentId===w.documentId&&y.scope===w.scope&&y.branch===w.branch)).forEach(w=>{this.synchronizationManager.updateSyncStatus(w,{pull:"SUCCESS"})});const b=n.state.local.listeners.find(w=>s.data.url===w.callInfo?.data);if(b)for(const w of d){const{documentId:y,scope:I,branch:_}=w;this.listenerManager.updateListenerRevision(b.listenerId,e,{documentId:y,scope:I,branch:_},w.revision).catch(this.logger.error)}}},void 0,this.listeners);t.set(s.id,a),this.triggerMap.set(e,t)}}}async stopSyncRemoteDrive(e){this.triggerMap.get(e)?.forEach(n=>n()),this.synchronizationManager.updateSyncStatus(e,null);const r=await this.synchronizationManager.getSynchronizationUnitsIds(e);for(const n of r)this.synchronizationManager.updateSyncStatus(n,null);return this.triggerMap.delete(e)}async _initializeDrive(e){const t=await this.getDrive(e);this.logger.verbose(`[SYNC DEBUG] Initializing drive ${e} with slug "${t.header.slug}"`),await this.synchronizationManager.initializeDriveSyncStatus(e,t),this.shouldSyncRemoteDrive(t)&&(this.logger.verbose(`[SYNC DEBUG] Starting sync for remote drive ${e}`),await this.startSyncRemoteDrive(e)),this.logger.verbose(`[SYNC DEBUG] Processing ${t.state.local.listeners.length} listeners for drive ${e}`);for(const r of t.state.local.listeners)if(r.callInfo?.transmitterType==="SwitchboardPush"){this.logger.verbose(`[SYNC DEBUG] Setting up SwitchboardPush listener ${r.listenerId} for drive ${e}`);const n=new pn(r.callInfo.data??"",this.listeners);this.logger.verbose(`[SYNC DEBUG] Created SwitchboardPush transmitter with URL: ${r.callInfo.data||"none"}`),await this.listenerManager.setListener(e,{block:r.block,driveId:t.header.id,filter:{branch:r.filter.branch??[],documentId:r.filter.documentId??[],documentType:r.filter.documentType??[],scope:r.filter.scope??[]},listenerId:r.listenerId,callInfo:r.callInfo,system:r.system,label:r.label??"",transmitter:n}).then(()=>{this.logger.verbose(`[SYNC DEBUG] Successfully set up listener ${r.listenerId} for drive ${e}`)})}else if(r.callInfo?.transmitterType==="PullResponder"){this.logger.verbose(`[SYNC DEBUG] Setting up PullResponder listener ${r.listenerId} for drive ${e}`);const n={driveId:e,listenerId:r.listenerId,block:!1,filter:r.filter,system:!1,label:`PullResponder #${r.listenerId}`,callInfo:{data:"",name:"PullResponder",transmitterType:"PullResponder"}},s=new ce(n,this.listenerManager);n.transmitter=s,await this.listenerManager.setListener(e,n)}else this.logger.error(`Skipping listener ${r.listenerId} with unsupported type ${r.callInfo?.transmitterType||"unknown"}`)}getDocumentModelModule(e){const t=this.documentModelModules.find(r=>r.documentModel.global.id===e);if(!t)throw new Error(`Document type ${e} not supported`);return t}getDocumentModelModules(){return[...this.documentModelModules]}addDocument(e,t){const r=typeof e=="string"?{documentType:e}:{document:e};return this.createDocument(r,{type:"local"},t)}async addDrive(e,t){const{global:r}=Bt(),n=dn({global:{...r,name:e.global.name??r.name,icon:e.global.icon??r.icon},local:{availableOffline:e.local?.availableOffline??!1,sharingType:e.local?.sharingType??"public",listeners:e.local?.listeners??[],triggers:e.local?.triggers??[]}});e.id&&e.id.length>0&&(n.header.id=e.id),e.slug&&e.slug.length>0&&(n.header.slug=e.slug),e.global.name&&(n.header.name=e.global.name);const s=e.preferredEditor||t;return s&&(n.header.meta={preferredEditor:s}),await this.documentStorage.create(n),e.slug&&e.slug.length>0&&await this.cache.deleteDriveBySlug(e.slug),await this._initializeDrive(n.header.id),this.eventEmitter.emit("driveAdded",n),n}async addRemoteDrive(e,t){await this.generateJwtHandler?.(e);const{id:r,name:n,slug:s,icon:o,meta:a}=t.expectedDriveInfo||await Be(e,this),{pullFilter:d,pullInterval:l,availableOffline:m,sharingType:f,listeners:b,triggers:w}=t,y=await ce.createPullResponderTrigger(r,e,{pullFilter:d,pullInterval:l},this.listeners);return await this.addDrive({id:r,slug:s,global:{name:n,icon:o},local:{triggers:[...w,y],listeners:b,availableOffline:m,sharingType:f}},a?.preferredEditor)}async deleteDrive(e){const t=await Promise.allSettled([this.stopSyncRemoteDrive(e),this.listenerManager.removeDrive(e),this.cache.deleteDrive(e),this.documentStorage.delete(e)]);this.eventEmitter.emit("driveDeleted",e),t.forEach(r=>{if(r.status==="rejected")throw r.reason})}async getDrives(){const e=[];let t;do{const{documents:r,nextCursor:n}=await this.documentStorage.findByType("powerhouse/document-drive",100,t);e.push(...r),t=n}while(t);return e}async getDrivesSlugs(){const e=await this.getDrives();return this.documentStorage.resolveSlugs(e)}async getDrive(e,t){let r;try{const o=await this.cache.getDrive(e);if(o&&ye(o)&&(r=o,Nt(r,t?.revisions)))return r}catch(o){this.logger.error("Error getting drive from cache",o)}const n=r??await this.documentStorage.get(e),s=this._buildDocument(n,t);if(ye(s))return t?.revisions||(this.cache.setDocument(e,s).catch(this.logger.error),this.cache.setDrive(e,s).catch(this.logger.error)),s;throw new Error(`Document with id ${e} is not a Document Drive`)}async getDriveBySlug(e,t){try{const s=await this.cache.getDriveBySlug(e);if(s)return s}catch(s){this.logger.error("Error getting drive from cache",s)}const r=await this.documentStorage.getBySlug(e),n=this._buildDocument(r,t);if(ye(n))return this.cache.setDriveBySlug(e,n).catch(this.logger.error),n;throw new Error(`Document with slug ${e} is not a Document Drive`)}async getDriveIdBySlug(e){try{const r=await this.cache.getDriveBySlug(e);if(r)return r.header.id}catch(r){this.logger.error("Error getting drive from cache",r)}return(await this.documentStorage.getBySlug(e)).header.id}getDocument(e,t,r){const n=typeof t=="string"?t:e,s=typeof t=="object"?t:r;return this._getDocument(n,s)}async _getDocument(e,t){let r;try{if(r=await this.cache.getDocument(e),r&&Nt(r,t?.revisions))return r}catch(o){this.logger.error("Error getting document from cache",o)}const n=r??await this.documentStorage.get(e),s=this._buildDocument(n,t);return t?.revisions||this.cache.setDocument(e,s).catch(this.logger.error),s}getDocuments(e){return this.documentStorage.getChildren(e)}async addChild(e,t){try{await this.documentStorage.addChild(e,t)}catch(r){throw this.logger.error("Error adding child document",r),r}}async removeChild(e,t){try{const r=await this.synchronizationManager.getSynchronizationUnitsIds(e,[t]);await this.listenerManager.removeSyncUnits(e,r)}catch(r){this.logger.warn("Error removing sync units of child",r)}try{await this.documentStorage.removeChild(e,t)}catch(r){throw this.logger.error("Error adding child document",r),r}}async createDocument(e,t,r){return this.enableDualActionCreate?this.createDocumentDualAction(e,t,r):this.createDocumentLegacy(e,t,r)}async createDocumentLegacy(e,t,r){const{documentType:n,document:s}=Ct(e);let o;if(s){if("documentType"in e&&n!==s.header.documentType)throw new Error(`Provided document is not ${n}`);o=this._buildDocument(s).state}const a=s??this.getDocumentModelModule(n).utils.createDocument(o);let d;if("id"in e&&e.id)s?(d=a.header,a.header.id=e.id,this.logger.warn("Assigning an id to a document is deprecated. Use the header field instead.")):(this.logger.warn("Creating a document with an id is deprecated. Use the header field instead."),d=Le(e.id,n));else if("header"in e)await He(e.header),d=e.header;else if(s?.header){if(!s.header.id)throw new Error("Document header id is required");if(!s.header.documentType)throw new Error("Document header documentType is required");if(!s.header.createdAtUtcIso)throw new Error("Document header createdAtUtcIso is required");s.header.sig.nonce?await He(s.header):this.logger.warn("Creating a document with an unsigned id is deprecated. Use createSignedHeaderForSigner."),d=s.header}else d=Le(void 0,n);r&&(d.meta={...d.meta,...r});const l={header:d,operations:{global:[],local:[]},initialState:a.initialState,clipboard:[],state:o??a.state};await this.documentStorage.create(l);const m=Object.values(a.operations).flat();m.length&&(ye(a)?await this.legacyStorage.addDriveOperations(d.id,m,a):await this.legacyStorage.addDocumentOperations(d.id,m,a));const f=await this.getDocument(l.header.id);return this.eventEmitter.emit("documentAdded",f),f}async createDocumentDualAction(e,t,r){const{documentType:n,document:s}=Ct(e);let o;if(s){if("documentType"in e&&n!==s.header.documentType)throw new Error(`Provided document is not ${n}`);o=this._buildDocument(s).state}const a=s??this.getDocumentModelModule(n).utils.createDocument(o);let d,l=!1;if("id"in e&&e.id)s?(d=a.header,a.header.id=e.id,this.logger.warn("Assigning an id to a document is deprecated. Use the header field instead.")):(this.logger.warn("Creating a document with an id is deprecated. Use the header field instead."),d=Le(e.id,n));else if("header"in e)await He(e.header),l=!0,d=e.header;else if(s?.header){if(!s.header.id)throw new Error("Document header id is required");if(!s.header.documentType)throw new Error("Document header documentType is required");if(!s.header.createdAtUtcIso)throw new Error("Document header createdAtUtcIso is required");s.header.sig.nonce?(await He(s.header),l=!0):this.logger.warn("Creating a document with an unsigned id is deprecated. Use createSignedHeaderForSigner."),d=s.header}else d=Le(void 0,n),l=!1;r&&(d.meta={...d.meta,...r});const m="0.1.0",f=o??a.state,b=Object.values(a.operations).flat(),w=b.length===0;let y=[];if(w){const U=new Date().toISOString(),F=l?{signature:d.id,publicKey:d.sig.publicKey,nonce:d.sig.nonce,createdAtUtcIso:d.createdAtUtcIso,documentType:d.documentType}:void 0,E={model:n,version:"0.0.0",documentId:d.id,signing:F},L={id:`${d.id}-create`,type:"CREATE_DOCUMENT",timestampUtcMs:U,input:E,scope:"document"},P={model:n,fromVersion:"0.0.0",toVersion:m,documentId:d.id,initialState:f},j={id:`${d.id}-upgrade`,type:"UPGRADE_DOCUMENT",timestampUtcMs:U,input:P,scope:"document"},V={state:Lt()},Z=ar(V,"document"),se=ar({state:f},"document");y=[{index:0,skip:0,hash:Z,timestampUtcMs:U,action:L},{index:1,skip:0,hash:se,timestampUtcMs:U,action:j}]}else y=b;const I=cr(y);I.header||(I.header=[]),I.document||(I.document=[]),I.global||(I.global=[]),I.local||(I.local=[]);const N={header:d,operations:I,initialState:f,clipboard:[],state:f};await this.documentStorage.create(N);const C=await this.getDocument(N.header.id,{checkHashes:!0});return this.eventEmitter.emit("documentAdded",C),C}async deleteDocument(e){try{const t=await this.synchronizationManager.getSynchronizationUnitsIds(void 0,[e]);for(const n of t)this.synchronizationManager.updateSyncStatus(n,null);const r=await this.documentStorage.getParents(e);for(const n of r)this.listenerManager.removeSyncUnits(n,t).catch(this.logger.warn)}catch(t){this.logger.warn("Error deleting document",t)}await Promise.allSettled([this.cache.deleteDocument(e).catch(this.logger.warn),this.documentStorage.delete(e).catch(this.logger.warn)]),this.eventEmitter.emit("documentDeleted",e)}async _processOperations(e,t,r){const n=[],s=[],o=await this._addDocumentResultingStage(t,e);let a=this._buildDocument(o),d;const l=cr(r);for(const m of Object.keys(l)){const f=t.operations[m]||[],b=vs(l[m]||[],f);if(b.length<1)continue;const w=Dt(Ge(f)),[y,I]=ws(w,b),N=(I.length<1?y:bs(w,y,Is)).filter(C=>w.length<1||Ds(w[w.length-1],C));for(const C of N){let U=!1;if(I.length>0){const F=r.find(E=>E.hash===C.hash);U=!F||F.index!==C.index||F.skip!==C.skip}try{const F=this.options.taskQueueMethod,E=()=>this._performOperation(e,a,C,U),L=await(F?$t(E,F):E());a=L.document,s.push(...L.signals),n.push(L.operation)}catch(F){d=F instanceof ie?F:new ie("ERROR",C,F.message,F.cause);break}}}return{document:a,operationsApplied:n,signals:s,error:d}}async _addDocumentResultingStage(e,t,r){const n=r?.revisions!==void 0?Mr(e.operations,r.revisions):e.operations,s=Ve(n);for(const o of Object.keys(s)){const a=s[o];if(!a)continue;const d=a.at(-1);d&&!d.resultingState&&(d.resultingState=await(ye(e)?this.legacyStorage.getOperationResultingState?.(t,d.index,d.action.scope,"main"):this.legacyStorage.getDriveOperationResultingState?.(t,d.index,d.action.scope,"main")))}return{...e,operations:s}}_buildDocument(e,t){if(e.state&&(!t||t.checkHashes===!1)&&Nt(e,t?.revisions))return e;const r=this.getDocumentModelModule(e.header.documentType),n=t?.revisions!==void 0?Mr(e.operations,t.revisions):e.operations,s=Ve(n),o=Object.keys(s),a=new Set([...o,"global","local"]),d={},l={};for(const w of a)d[w]=[],l[w]=[];for(const[w,y]of Object.entries(s))if(y)for(const I of y)if(I.action.type==="CREATE_DOCUMENT"||I.action.type==="UPGRADE_DOCUMENT"){const _=d[w];_&&_.push(I)}else{const _=l[w];_&&_.push(I)}const m=Cr(e.initialState,l,r.reducer,void 0,e.header,void 0,{...t,checkHashes:t?.checkHashes??!0,reuseOperationResultingState:t?.checkHashes??!0}),f=new Set([...Object.keys(s),...Object.keys(d),...Object.keys(m.operations)]),b={};for(const w of f)b[w]=[...d[w]||[],...m.operations[w]||[]];return{...m,operations:b}}async _performOperation(e,t,r,n=!1){const s=this.getDocumentModelModule(t.header.documentType),o=[];let a=t;const d=r.action.scope,l=t.operations[d]||[],b=Ve({...t.operations,[d]:Ss(l,r)})[d]?.at(-1);b&&!b.resultingState&&(b.resultingState=await(ye(t)?this.legacyStorage.getOperationResultingState?.(e,b.index,b.action.scope,"main"):this.legacyStorage.getDriveOperationResultingState?.(e,b.index,b.action.scope,"main")));const w=a.operations[d]||[],y=[];if(a=s.reducer(a,r.action,C=>{let U;switch(C.type){case"CREATE_CHILD_DOCUMENT":U=()=>this.addChild(e,C.input.id);break;case"DELETE_CHILD_DOCUMENT":U=()=>this.removeChild(e,C.input.id);break;case"COPY_CHILD_DOCUMENT":U=()=>this.addChild(e,C.input.newId);break}U&&y.push(()=>U().then(F=>({signal:C,result:F})))},{skip:r.skip,reuseOperationResultingState:!0,replayOptions:{operation:r}}),r.action.type==="NOOP"&&r.skip>0&&a.clipboard.length===0){const C=a.operations[d]||[],U=Dt(Ge(C)),F=Dt(Ge(w)),E=Es(F,U);a={...a,clipboard:Ge(E.filter(L=>L.action.type!=="NOOP")).reverse()}}const I=a.operations[r.action.scope];if(!I)throw new ie("ERROR",r,`No operations found for scope: ${r.action.scope}`);const N=I.filter(C=>C.index==r.index&&C.skip==r.skip).at(0);if(!N)throw new ie("ERROR",r,`Operation with index ${r.index}:${r.skip} was not applied.`);if(!N.error&&N.hash!==r.hash&&!n)throw this.logger.warn(JSON.stringify(N,null,2)),new hi(r,N);for(const C of y){const U=await C();o.push(U)}return{document:a,signals:o,operation:N}}addOperation(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this.addOperations(s,[o],a)}async _addOperations(e,t){if(this.legacyStorage.addDocumentOperationsWithTransaction)await this.legacyStorage.addDocumentOperationsWithTransaction(e,t);else{const r=await this.documentStorage.get(e),n=await t(r);n.operations.length>0&&await this.legacyStorage.addDocumentOperations(e,n.operations,n.document)}}async queueDocument(e,t){const{id:r,documentType:n,document:s}=Ct(e);if(!r)throw new Error("Document id is required",{cause:e});if(!n)throw new Error("Document type is required",{cause:e});if(await this.documentStorage.exists(r))throw new ke(r);let a;const d=new Promise((l,m)=>{const f=this.queueManager.on("jobCompleted",(w,y)=>{w.jobId===a&&(f(),b(),l(y))}),b=this.queueManager.on("jobFailed",(w,y)=>{w.jobId===a&&(f(),b(),m(y))})});try{a=await this.queueManager.addJob({documentId:r,documentType:n,initialState:s?.state,header:s?.header,options:t})}catch(l){throw this.logger.error("Error adding job",l),l}return d}queueOperation(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueOperations(s,[o],a)}async resultIfExistingOperations(e,t){try{const r=await this.getDocument(e);return t.find(s=>{if(!s.id)return!0;const o=r.operations[s.action.scope];return o?!o.find(a=>a.id===s.id&&a.index===s.index&&a.action.type===s.action.type&&a.hash===s.hash):!0})?void 0:{status:"SUCCESS",document:r,operations:t,signals:[]}}catch(r){r.message.includes(`Document with id ${e} not found`)||console.error(r);return}}queueOperations(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueOperations(s,o,a)}async _queueOperations(e,t,r){const n=await this.resultIfExistingOperations(e,t);if(n)return n;let s;const o=new Promise((a,d)=>{const l=this.queueManager.on("jobCompleted",(f,b)=>{f.jobId===s&&(l(),m(),a(b))}),m=this.queueManager.on("jobFailed",(f,b)=>{f.jobId===s&&(l(),m(),d(b))})});try{s=await this.queueManager.addJob({documentId:e,operations:t,options:r})}catch(a){throw this.logger.error("Error adding job",a),a}return o}queueAction(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueActions(s,[o],a)}queueActions(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueActions(s,o,a)}async _queueActions(e,t,r){try{const n=await this.queueManager.addJob({documentId:e,actions:t,options:r});return await new Promise((s,o)=>{const a=this.queueManager.on("jobCompleted",(l,m)=>{l.jobId===n&&(a(),d(),s(m))}),d=this.queueManager.on("jobFailed",(l,m)=>{l.jobId===n&&(a(),d(),o(m))})})}catch(n){throw this.logger.error("Error adding job",n),n}}async queueDriveAction(e,t,r){return this.queueDriveActions(e,[t],r)}async queueDriveActions(e,t,r){try{const n=await this.queueManager.addJob({documentId:e,actions:t,options:r});return await new Promise((s,o)=>{const a=this.queueManager.on("jobCompleted",(l,m)=>{l.jobId===n&&(a(),d(),s(m))}),d=this.queueManager.on("jobFailed",(l,m)=>{l.jobId===n&&(a(),d(),o(m))})})}catch(n){throw this.logger.error("Error adding drive job",n),n}}addOperations(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueOperations(s,o,a)}async processOperations(e,t,r){const n=await this.resultIfExistingOperations(e,t);if(n)return n;let s;const o=[],a=[];let d;try{await this._addOperations(e,async w=>{const y=await this._processOperations(e,w,t);if(!y.document)throw this.logger.error("Invalid document"),y.error??new Error("Invalid document");return s=y.document,d=y.error,a.push(...y.signals),o.push(...y.operationsApplied),{operations:y.operationsApplied,document:y.document}});const l=new Array;if(s){this.cache.setDocument(e,s).catch(this.logger.error);for(const w of o){const y={documentId:e,documentType:s.header.documentType,scope:w.action.scope,branch:"main",revision:w.index+1,lastUpdated:w.timestampUtcMs};l.some(_=>_.documentId===y.documentId&&_.scope===y.scope&&_.branch===y.branch)||l.push(y)}}const f=o.find(w=>!t.find(y=>y.id===w.id&&y.index===w.index&&y.skip===w.skip&&y.hash===w.hash))?{type:"local"}:r?.source??{type:"local"},b=this.getOperationSource(f);if(l.length&&this.listenerManager.updateSynchronizationRevisions(l,f,()=>{this.synchronizationManager.updateSyncStatus(e,{[b]:"SYNCING"});for(const w of l)this.synchronizationManager.updateSyncStatus(w,{[b]:"SYNCING"})},this.handleListenerError.bind(this),r?.forceSync??f.type==="local").then(w=>{w.length&&this.synchronizationManager.updateSyncStatus(e,{[b]:"SUCCESS"});for(const y of l)this.synchronizationManager.updateSyncStatus(y,{[b]:"SUCCESS"})}).catch(w=>{this.logger.error("Non handled error updating sync revision",w),this.synchronizationManager.updateSyncStatus(e,{[b]:"ERROR"},w);for(const y of l)this.synchronizationManager.updateSyncStatus(y,{[b]:"ERROR"},w)}),d)throw d;return this.eventEmitter.emit("documentOperationsAdded",e,t),this.eventEmitter.emit("operationsAdded",e,t),{status:"SUCCESS",document:s,operations:o,signals:a}}catch(l){const m=l instanceof ie?l:new ie("ERROR",void 0,l.message,l.cause);return{status:m.status,error:m,document:s,operations:o,signals:a}}}addDriveOperation(e,t,r){return this.addDriveOperations(e,[t],r)}async _addDriveOperations(e,t){if(this.legacyStorage.addDriveOperationsWithTransaction)return this.legacyStorage.addDriveOperationsWithTransaction(e,t);{const r=await this.documentStorage.get(e),n=await t(r);return n.operations.length>0&&await this.legacyStorage.addDriveOperations(e,n.operations,n.document),n}}queueDriveOperation(e,t,r){return this.queueDriveOperations(e,[t],r)}async resultIfExistingDriveOperations(e,t){try{const r=await this.getDrive(e);return t.find(s=>{if(!s.id)return!0;const o=r.operations[s.action.scope];return o?!o.find(a=>a.id===s.id&&a.index===s.index&&a.action.type===s.action.type&&a.hash===s.hash):!0})?void 0:{status:"SUCCESS",document:r,operations:t,signals:[]}}catch(r){console.error(r);return}}async queueDriveOperations(e,t,r){const n=await this.resultIfExistingDriveOperations(e,t);if(n)return n;try{const s=await this.queueManager.addJob({documentId:e,operations:t,options:r});return await new Promise((o,a)=>{const d=this.queueManager.on("jobCompleted",(m,f)=>{m.jobId===s&&(d(),l(),o(f))}),l=this.queueManager.on("jobFailed",(m,f)=>{m.jobId===s&&(d(),l(),a(f))})})}catch(s){throw this.logger.error("Error adding drive job",s),s}}async addDriveOperations(e,t,r){return this.queueDriveOperations(e,t,r)}async processDriveOperations(e,t,r){let n;const s=[],o=[];let a;const d=await this.resultIfExistingDriveOperations(e,t);if(d)return d;try{if(await this._addDriveOperations(e,async m=>{const f=await this._processOperations(e,m,t.slice());return n=f.document,s.push(...f.operationsApplied),o.push(...f.signals),a=f.error,{operations:f.operationsApplied,document:f.document}}),!n||!ye(n))throw a??new Error("Invalid Document Drive document");this.cache.setDocument(e,n).catch(this.logger.error),this.cache.setDrive(e,n).catch(this.logger.error);const l=s.filter(m=>m.action.scope==="global").slice().pop();if(l){const f=s.find(w=>!t.find(y=>y.id===w.id&&y.index===w.index&&y.skip===w.skip&&y.hash===w.hash))?{type:"local"}:r?.source??{type:"local"},b=this.getOperationSource(f);this.listenerManager.updateSynchronizationRevisions([{documentId:e,documentType:n.header.documentType,scope:"global",branch:"main",lastUpdated:l.timestampUtcMs,revision:l.index}],f,()=>{this.synchronizationManager.updateSyncStatus(e,{[b]:"SYNCING"})},this.handleListenerError.bind(this),r?.forceSync??f.type==="local").then(w=>{w.length&&this.synchronizationManager.updateSyncStatus(e,{[b]:"SUCCESS"})}).catch(w=>{this.logger.error("Non handled error updating sync revision",w),this.synchronizationManager.updateSyncStatus(e,{[b]:"ERROR"},w)})}if(this.shouldSyncRemoteDrive(n)?this.startSyncRemoteDrive(e).catch(this.logger.error):this.stopSyncRemoteDrive(e).catch(this.logger.error),a)throw a;return this.eventEmitter.emit("driveOperationsAdded",e,t),this.eventEmitter.emit("operationsAdded",e,t),{status:"SUCCESS",document:n,operations:s,signals:o}}catch(l){const m=l instanceof ie?l:new ie("ERROR",void 0,l.message,l);return{status:m.status,error:m,document:n,operations:s,signals:o}}}_buildOperations(e,t){const r=[],{reducer:n}=this.getDocumentModelModule(e.header.documentType);for(const s of t){e=n(e,s);const o=e.operations[s.scope];if(!o)throw new Error(`No operations found for scope: ${s.scope}`);const a=o.slice().pop();if(!a)throw new Error("Error creating operations");r.push(a)}return r}addAction(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._addAction(s,o,a)}async _addAction(e,t,r){return this.addActions(e,[t],r)}addActions(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueActions(s,o,a)}async processActions(e,t,r){const n=await this.getDocument(e),s=this._buildOperations(n,t);return this.processOperations(e,s,r)}async addDriveAction(e,t,r){return"synchronizationUnits"in t.input?this._legacyAddFileAction(e,t,r):this.addDriveActions(e,[t],r)}async _legacyAddFileAction(e,t,r){const n=this.getDocumentModelModule(t.input.documentType).utils.createDocument(t.input.document?.state||void 0);n.header.id=t.input.id,n.header.name=t.input.name,n.header.documentType=t.input.documentType,await this.queueDocument({document:n},{source:r?.source||{type:"local"}});const s={...t,input:{id:t.input.id,documentType:n.header.documentType,name:t.input.name,parentFolder:t.input.parentFolder}};return await this.addAction(e,s,r)}async addDriveActions(e,t,r){return this.queueDriveActions(e,t,r)}async processDriveActions(e,t,r){const n=await this.getDrive(e),s=this._buildOperations(n,t);return this.processDriveOperations(e,s,r)}async detachDrive(e){const t=await this.getDrive(e),r=t.state.local.listeners||[],n=t.state.local.triggers||[];for(const s of r)await this.addDriveAction(e,en({listenerId:s.listenerId}));for(const s of n)await this.addDriveAction(e,tn({triggerId:s.id}));await this.addDriveAction(e,Zr({type:"LOCAL"}))}getSyncStatus(e,t,r){return this.synchronizationManager.getSyncStatus(e,t,r)}on(e,t){return this.eventEmitter.on(e,t)}emit(e,...t){return this.eventEmitter.emit(e,...t)}updateSyncStatus(e,t,r){this.synchronizationManager.updateSyncStatus(e,t,r)}initializeDriveSyncStatus(e,t){return this.synchronizationManager.initializeDriveSyncStatus(e,t)}getCombinedSyncUnitStatus(e){return this.synchronizationManager.getCombinedSyncUnitStatus(e)}async saveStrand(e,t){const r=!await this.documentStorage.exists(e.documentId);let n;r&&(n=await this.queueDocument({id:e.documentId,documentType:e.documentType}));const s=e.operations.map(o=>({...o,action:{id:o.actionId,timestampUtcMs:o.timestampUtcMs,type:o.type,input:o.input,context:o.context,scope:e.scope},scope:e.scope,branch:e.branch}));if((!r||n?.status==="SUCCESS")&&s.length)try{n=await this.queueOperations(e.documentId,s,{source:t})}catch(o){throw this.logger.error("Error queueing operations",o),o}if(!n)return this.logger.debug(`Document ${e.documentId} already exists`),{status:"SUCCESS",document:await this.getDocument(e.documentId),operations:[],signals:[]};if(n.status==="ERROR"){const o=this.getOperationSource(t);this.synchronizationManager.updateSyncStatus({documentId:e.documentId||e.driveId,scope:e.scope,branch:e.branch},{[o]:n.status},n.error)}return this.eventEmitter.emit("strandUpdate",e),n}setGenerateJwtHandler(e){this.generateJwtHandler=e,this.listenerManager.setGenerateJwtHandler(e)}removeJwtHandler(){this.generateJwtHandler=void 0,this.listenerManager.removeJwtHandler()}}const po=eo(go);class at extends Error{constructor(e){super(e||"Aborted"),this.name="AbortError"}}class mo{logger=pe(["MemoryStorage"]);documents;driveManifests;slugToDocumentId;constructor(){this.documents={},this.driveManifests={},this.slugToDocumentId={}}resolveIds(e,t){const r=[];for(const n of e){const s=this.slugToDocumentId[n];if(!s)throw new we(n);r.push(s)}if(t?.aborted)throw new at("Aborted");return Promise.resolve(r)}resolveSlugs(e,t){const r=[];for(const n of e){const s=this.documents[n];if(!s)throw new we(n);r.push(s.header.slug)}if(t?.aborted)throw new at("Aborted");return Promise.resolve(r)}exists(e){return Promise.resolve(!!this.documents[e])}create(e){const t=e.header.id;if(!tt(t))throw new et(t);if(this.documents[t])throw new ke(t);const r=e.header.slug?.length>0?e.header.slug:t;if(!nn(r))throw new rn(r);if(r&&this.slugToDocumentId[r])throw new ke(t,Fe.SLUG);return e.header.slug=r,this.documents[t]=e,r&&(this.slugToDocumentId[r]=t),e.header.documentType==="powerhouse/document-drive"&&this.updateDriveManifest(t,{documentIds:new Set}),Promise.resolve()}get(e){const t=this.documents[e];return t?Promise.resolve(t):Promise.reject(new we(e))}getBySlug(e){const t=this.slugToDocumentId[e];return t?this.get(t):Promise.reject(new we(e))}async findByType(e,t=100,r){const n=Object.entries(this.documents).filter(([d,l])=>l.header.documentType===e).map(([d,l])=>({id:d,document:l}));n.sort((d,l)=>{const m=new Date(d.document.header.createdAtUtcIso),f=new Date(l.document.header.createdAtUtcIso);if(m.getTime()===f.getTime()){const b=d.id,w=l.id;return b.localeCompare(w)}return m.getTime()-f.getTime()});let s=0;if(r){const d=n.findIndex(({id:l})=>l===r);d!==-1&&(s=d)}const o=Math.min(s+t,n.length);let a;return o<n.length&&(a=n[o].id),{documents:n.slice(s,o).map(({id:d})=>d),nextCursor:a}}async delete(e){const t=this.documents[e];if(t){const n=t.header.slug?.length>0?t.header.slug:e;n&&this.slugToDocumentId[n]===e&&delete this.slugToDocumentId[n]}const r=await this.getParents(e);for(const n of r)await this.removeChild(n,e);return delete this.driveManifests[e],this.documents[e]?(delete this.documents[e],Promise.resolve(!0)):Promise.resolve(!1)}async addChild(e,t){if(e===t)return Promise.reject(new Error("Cannot associate a document with itself"));if((await this.getChildren(t)).includes(e))return Promise.reject(new Error("Cannot associate a document with its child"));const n=this.getManifest(e);return n.documentIds.add(t),this.updateDriveManifest(e,n),Promise.resolve()}async removeChild(e,t){const r=this.getManifest(e);return r.documentIds.delete(t)?(this.updateDriveManifest(e,r),Promise.resolve(!0)):Promise.resolve(!1)}async getChildren(e){return[...this.getManifest(e).documentIds]}async getParents(e){const t=[];for(const[r,n]of Object.entries(this.driveManifests))n.documentIds.has(e)&&t.push(r);return t}async clear(){this.documents={},this.driveManifests={},this.slugToDocumentId={}}async addDocumentOperations(e,t,r){const n=await this.get(e);if(!r)return Promise.reject(new we(e));const s=st(n.operations,t),o={};for(const[a,d]of Object.entries(s))o[a]=Ie(d);this.documents[e]={...n,state:r.state,initialState:r.initialState,header:{...n.header,...r.header,revision:o},operations:s,clipboard:r.clipboard}}async addDriveOperations(e,t,r){const n=await this.get(e),s=st(n.operations,t),o={};for(const[a,d]of Object.entries(s))o[a]=Ie(d);this.documents[e]={...n,state:r.state,initialState:r.initialState,header:{...n.header,...r.header,revision:o},operations:s,clipboard:r.clipboard}}async getSynchronizationUnitsRevision(e){return(await Promise.allSettled(e.map(async r=>{try{const n=await this.get(r.documentId);if(!n||!Object.keys(n.state).includes(r.scope))return;const s=n.operations[r.scope];return s?{documentId:r.documentId,documentType:r.documentType,scope:r.scope,branch:r.branch,lastUpdated:s.at(-1)?.timestampUtcMs??n.header.createdAtUtcIso,revision:s.length>0?Ie(s):0}:void 0}catch(n){this.logger.error("Error getting synchronization units revision",n);return}}))).reduce((r,n)=>(n.status==="fulfilled"&&n.value!==void 0&&r.push(n.value),r),[])}async findStorageUnitsBy(e,t,r){const n=[],{parentId:s,documentId:o,documentModelType:a,scope:d}=sn(e);let l;if(s){const w=new Set;for(const y of s)(await this.getChildren(y)).forEach(_=>w.add(_));l=on(s,w)}else l=new Set(Object.keys(this.documents));l=o?an(o,l):l;for(const w of l){const y=this.documents[w];if(y&&!(a&&!a.has(y.header.documentType)))for(const[I]of Object.entries(y.state))d&&!d.has(I)||n.push({documentId:w,documentModelType:y.header.documentType,scope:I,branch:"main"})}let m=0;if(r){const w=n.findIndex(y=>y.documentId===r);w!==-1&&(m=w)}const f=Math.min(m+t,n.length),b=f<n.length?n[f].documentId:void 0;return{units:n.slice(m,f),nextCursor:b}}getManifest(e){return this.driveManifests[e]||(this.driveManifests[e]={documentIds:new Set}),this.driveManifests[e]}updateDriveManifest(e,t){this.driveManifests[e]=t}}class yo{emitter=hn();emit(e,...t){return this.emitter.emit(e,...t)}on(e,t){return this.emitter.on(e,t)}}class X{internalMap=new Map;static keySeparator="|";static escape(e){return e.replace(/\|/g,"\\|")}static unescape(e){return e.replace(/\\\|/g,"|")}static buildKey(e){return`${X.escape(e.documentId)}${X.keySeparator}${X.escape(e.scope)}${X.keySeparator}${X.escape(e.branch)}`}static parseKey(e){const t=e.split(new RegExp("(?<!\\\\)\\|")).map(o=>X.unescape(o)),[r,n,s]=t;return{documentId:r,scope:n,branch:s}}set(e,t){return this.internalMap.set(X.buildKey(e),t),this}get(e){return this.internalMap.get(X.buildKey(e))}has(e){return this.internalMap.has(X.buildKey(e))}delete(e){return this.internalMap.delete(X.buildKey(e))}clear(){this.internalMap.clear()}get size(){return this.internalMap.size}keys(e){const t=this.internalMap.keys();return{[Symbol.iterator](){return this},next(){for(;;){const r=t.next();if(r.done)return{done:!0,value:void 0};const n=r.value,s=X.parseKey(n);if(!(e&&(s.documentId!==e.documentId||e.scope!==void 0&&s.scope!==e.scope)))return{done:!1,value:s}}}}}values(e){const t=this.internalMap.entries();return{[Symbol.iterator](){return this},next(){for(;;){const r=t.next();if(r.done)return{done:!0,value:void 0};const[n,s]=r.value,o=X.parseKey(n);if(!(e&&(o.documentId!==e.documentId||e.scope!==void 0&&o.scope!==e.scope)))return{done:!1,value:s}}}}}entries(e){const t=this.internalMap.entries();return{[Symbol.iterator](){return this},next(){for(;;){const r=t.next();if(r.done)return{done:!0,value:void 0};const[n,s]=r.value,o=X.parseKey(n);if(!(e&&(o.documentId!==e.documentId||e.scope!==void 0&&o.scope!==e.scope)))return{done:!1,value:[o,s]}}}}}[Symbol.iterator](){return this.entries()}forEach(e,t){for(const[r,n]of this.entries())e.call(t,n,r,this)}deleteByDocumentId(e){for(const t of this.internalMap.keys())t.startsWith(e+X.keySeparator)&&this.internalMap.delete(t)}deleteByDocumentIdAndScope(e,t){const r=`${e}${X.keySeparator}${t}${X.keySeparator}`;for(const n of this.internalMap.keys())n.startsWith(r)&&this.internalMap.delete(n)}getAllByDocumentId(e){const t=[];for(const[r,n]of this.internalMap.entries())r.startsWith(e+X.keySeparator)&&t.push([X.parseKey(r),n]);return t}getAllByDocumentIdAndScope(e,t){const r=`${e}${X.keySeparator}${t}${X.keySeparator}`,n=[];for(const[s,o]of this.internalMap.entries())s.startsWith(r)&&n.push([X.parseKey(s),o]);return n}}function vo(i,e=250){let t;return(r=!1,...n)=>(t&&clearTimeout(t),new Promise((s,o)=>{r?i(...n).then(s).catch(o):t=setTimeout(()=>{i(...n).then(s).catch(o)},e)}))}class qt{static LISTENER_UPDATE_DELAY=250;logger=pe(["ListenerManager",Math.floor(Math.random()*999).toString()]);syncManager;options;generateJwtHandler;listenerStateByDriveId=new Map;constructor(e,t=ot){this.syncManager=e,this.options={...ot,...t},this.logger.verbose("constructor(...)")}setGenerateJwtHandler(e){this.generateJwtHandler=e}removeJwtHandler(){this.generateJwtHandler=void 0}async initialize(e){this.logger.verbose("initialize(...)"),typeof window<"u"&&window.addEventListener("online",()=>{this.triggerUpdate(!1,{type:"local"},void 0,e).catch(t=>{this.logger.error("Non handled error updating listeners",t)})})}driveHasListeners(e){return this.listenerStateByDriveId.has(e)}async setListener(e,t){if(this.logger.verbose(`setListener(drive: ${e}, listener: ${t.listenerId})`),e!==t.driveId)throw new Error("Drive ID mismatch");let r;try{r=this.getListenerState(e,t.listenerId)}catch{r={}}this.setListenerState(e,t.listenerId,{...r,block:t.block,driveId:t.driveId,pendingTimeout:"0",listener:t,listenerStatus:"CREATED",syncUnits:new X}),await this.triggerUpdate(!0,{type:"local"})}async removeListener(e,t){this.logger.verbose("setListener()");const r=this.listenerStateByDriveId.get(e);return r?Promise.resolve(r.delete(t)):!1}async removeSyncUnits(e,t){const r=this.listenerStateByDriveId.get(e);if(r){for(const[,n]of r)for(const s of t)n.syncUnits.delete(s);return Promise.resolve()}}async updateSynchronizationRevisions(e,t,r,n,s=!1){const o=this.listenerStateByDriveId.values(),a=[];for(const[[d,l]]of o)if(!(a.find(f=>f.listenerId===l.listener.listenerId)||!l.listener.transmitter?.transmit))for(const f of e){if(!this._checkFilter(l.listener.filter,f))continue;const b=l.syncUnits.get(f);if(!b||b.listenerRev<f.revision){a.push(l.listener);break}}return this.triggerUpdate(s,t,r,n)}async updateListenerRevision(e,t,r,n){const s=this.listenerStateByDriveId.get(t);if(!s)return;const o=s.get(e);if(!o)return;const a=new Date().toISOString();return o.syncUnits.set(r,{listenerRev:n,lastUpdated:a}),Promise.resolve()}triggerUpdate=vo(this._triggerUpdate.bind(this),qt.LISTENER_UPDATE_DELAY);async _triggerUpdate(e,t,r,n=500){if(this.logger.verbose(`_triggerUpdate(source: ${e.type}, maxContinues: ${n})`,this.listenerStateByDriveId),n<0)throw new Error("Maximum retries exhausted.");const s=[];for(const[o,a]of this.listenerStateByDriveId)for(const[d,l]of a){const m=l.listener.transmitter;if(!m?.transmit)continue;const f=await this.getListenerSyncUnits(o,d),b=[];this.logger.verbose("syncUnits",f);const w=f.map(y=>async()=>{const I=l.syncUnits.get(y);if(I&&I.listenerRev>=y.revision){this.logger.verbose(`Abandoning push for sync unit ${JSON.stringify(y)}: already up-to-date (${I.listenerRev} >= ${y.revision})`);return}else this.logger.verbose(`Listener out-of-date for sync unit (${y.scope}, ${y.documentId}): ${I?.listenerRev} < ${y.revision}`);const _=[];if(y.revision>0){try{const N=await this.syncManager.getOperationData(y,{fromRevision:I?.listenerRev});_.push(...N)}catch(N){this.logger.error(N)}if(!_.length){this.logger.verbose(`Abandoning push for ${JSON.stringify(y)}: no operations found`);return}}b.push({driveId:o,documentType:y.documentType,documentId:y.documentId,branch:y.branch,operations:_,scope:y.scope})});if(this.options.sequentialUpdates){this.logger.verbose(`Collecting ${w.length} syncUnit strandUpdates in sequence`);for(const y of w)await y()}else this.logger.verbose(`Collecting ${w.length} syncUnit strandUpdates in parallel`),await Promise.all(w.map(y=>y()));if(b.length==0){this.logger.verbose(`No strandUpdates needed for listener ${d}`);continue}l.pendingTimeout=new Date(new Date().getTime()/1e3+300).toISOString(),l.listenerStatus="PENDING";try{this.logger.verbose(`_triggerUpdate(source: ${e.type}) > transmitter.transmit`);const y=await m.transmit(b,e);this.logger.verbose(`_triggerUpdate(source: ${e.type}) > transmission succeeded`,y),l.pendingTimeout="0",l.listenerStatus="PENDING";const I=new Date().toISOString();let _=!1;for(const N of y){const C=f.find(U=>N.documentId===U.documentId&&N.scope===U.scope&&N.branch===U.branch);if(C){l.syncUnits.set(C,{lastUpdated:I,listenerRev:N.revision});const U=b.find(F=>F.driveId===N.driveId&&F.documentId===N.documentId&&F.scope===N.scope&&F.branch===N.branch);if(U&&U.operations.length>0){const F=U.operations.at(-1)?.index;F!==N.revision?(this.logger.verbose(`Revision still out-of-date for ${U.documentId}:${U.scope}:${U.branch} ${F} <> ${N.revision}`),_=!0):this.logger.verbose(`Revision match for ${U.documentId}:${U.scope}:${U.branch} ${F}`)}}else this.logger.warn(`Received revision for untracked unit for listener ${l.listener.listenerId}`,N)}for(const N of y){const C=N.status==="ERROR";if(N.error?.includes("Missing operations"))_=!0;else if(C)throw new ie(N.status,void 0,N.error,N.error)}if(!_)s.push({listenerId:l.listener.listenerId,listenerRevisions:y});else{const N=await this._triggerUpdate(e,t,r,n-1);s.push(...N)}l.listenerStatus="SUCCESS"}catch(y){r?.(y,o,l),l.listenerStatus=y instanceof ie?y.status:"ERROR"}}return this.logger.verbose(`Returning listener updates (maxContinues: ${n})`,s),s}_checkFilter(e,t){const{branch:r,documentId:n,scope:s,documentType:o}=t;return!!((!e.branch||e.branch.includes(r)||e.branch.includes("*"))&&(!e.documentId||e.documentId.includes(n)||e.documentId.includes("*"))&&(!e.scope||e.scope.includes(s)||e.scope.includes("*"))&&(!e.documentType||e.documentType.includes(o)||e.documentType.includes("*")))}getListenerSyncUnits(e,t){const r=this.listenerStateByDriveId.get(e)?.get(t);if(!r)return[];const n=r.listener.filter;return this.syncManager.getSynchronizationUnits(e,n.documentId??["*"],n.scope??["*"],n.branch??["*"],n.documentType??["*"])}async removeDrive(e){const t=this.listenerStateByDriveId.get(e);if(t){this.listenerStateByDriveId.delete(e);for(const[r,n]of t)try{await n.listener.transmitter?.disconnect?.()}catch(s){this.logger.error(s)}}}async getStrands(e,t,r){this.logger.verbose(`[SYNC DEBUG] ListenerManager.getStrands called for drive: ${e}, listener: ${t}, options: ${JSON.stringify(r||{})}`);let n;try{n=this.getListenerState(e,t),this.logger.verbose(`[SYNC DEBUG] Found listener state for drive: ${e}, listener: ${t}, status: ${n.listenerStatus}`)}catch(o){throw this.logger.error(`[SYNC DEBUG] Failed to find listener state for drive: ${e}, listener: ${t}. Error: ${o}`),o}const s=[];try{const o=await this.getListenerSyncUnits(e,t);this.logger.verbose(`[SYNC DEBUG] Retrieved ${o.length} sync units for drive: ${e}, listener: ${t}`);const a=r?.limit;let d=0;const l=o.map(m=>async()=>{if(a&&d>=a)return;if(m.revision<0){this.logger.verbose(`[SYNC DEBUG] Skipping sync unit with negative revision: ${JSON.stringify(m)}, revision: ${m.revision}`);return}const f=n.syncUnits.get(m);if(f&&f.listenerRev>=m.revision){this.logger.verbose(`[SYNC DEBUG] Skipping sync unit - listener already up to date: ${JSON.stringify(m)}, listenerRev: ${f.listenerRev}, revision: ${m.revision}`);return}const{documentId:b,scope:w,branch:y}=m;let I=[];try{m.revision>0&&(this.logger.verbose(`[SYNC DEBUG] Getting operations for syncUnit: ${JSON.stringify(m)}`),I=await this.syncManager.getOperationData(m,{since:r?.since,fromRevision:r?.fromRevision??f?.listenerRev,limit:a?a-d:void 0})),this.logger.verbose(`[SYNC DEBUG] Retrieved ${I.length} operations for syncUnit: ${JSON.stringify(m)}`),d+=I.length,s.push({driveId:e,documentId:b,documentType:m.documentType,scope:w,branch:y,operations:I}),this.logger.verbose(`[SYNC DEBUG] Added strand with ${I.length} operations for syncUnit: ${JSON.stringify(m)}`)}catch(_){this.logger.error(`Error getting operations for syncUnit: ${JSON.stringify(m)}, error: ${_}`);return}});if(this.options.sequentialUpdates){this.logger.verbose(`[SYNC DEBUG] Processing ${l.length} sync units sequentially`);for(const m of l)await m()}else this.logger.verbose(`[SYNC DEBUG] Processing ${l.length} sync units in parallel`),await Promise.all(l.map(m=>m()))}catch(o){this.logger.error(`Error in getStrands: ${o}`)}return this.logger.verbose(`ListenerManager.getStrands returning ${s.length} strands for drive: ${e}, listener: ${t}`),s}getListenerState(e,t){let r=this.listenerStateByDriveId.get(e);r||(r=new Map,this.listenerStateByDriveId.set(e,r));const n=r.get(t);if(!n)throw new Error("Listener not found");return n}setListenerState(e,t,r){let n=this.listenerStateByDriveId.get(e);n||(n=new Map,this.listenerStateByDriveId.set(e,n)),n.set(t,r)}}class wo{storage;documentStorage;cache;documentModelModules;eventEmitter;syncStatus=new X;logger=pe(["SynchronizationManager"]);constructor(e,t,r,n,s){this.storage=e,this.documentStorage=t,this.cache=r,this.documentModelModules=n,this.eventEmitter=s}async getSynchronizationUnits(e,t,r,n,s){const o=await this.getSynchronizationUnitsIds(e,t,r,n,s);return this.logger.verbose(`getSynchronizationUnits query: ${JSON.stringify(o)}`),(await this.getSynchronizationUnitsRevision(o)).filter(d=>typeof d<"u")}async getSynchronizationUnitsRevision(e){const t=await this.storage.getSynchronizationUnitsRevision(e);return this.logger.verbose(`getSynchronizationUnitsRevision: ${JSON.stringify(t)}`),e.map(r=>t.find(n=>n.documentId===r.documentId&&n.scope===r.scope&&n.branch===r.branch))}async getSynchronizationUnitsIds(e,t,r,n,s){const o={parentId:e?[e]:void 0,documentId:t,documentModelType:s,scope:r,branch:n};let a;const d=[];do{const{units:l,nextCursor:m}=await this.documentStorage.findStorageUnitsBy(o,100,a);d.push(...l),a=m}while(a);return d.reduce((l,{documentModelType:m,...f})=>f.scope==="local"?l:l.concat([{...f,documentType:m}]),new Array)}async getSynchronizationUnit(e){const{scope:t,branch:r,documentId:n}=e,s=await this.getDocument(n);if(!Object.keys(s.state).includes(t))return;const o=s.operations[t]??[],a=o.at(-1);return{scope:t,branch:r,documentId:n,documentType:s.header.documentType,lastUpdated:a?.timestampUtcMs??s.header.lastModifiedAtUtcIso,revision:Ie(o)}}async getOperationData(e,t){this.logger.verbose(`[SYNC DEBUG] SynchronizationManager.getOperationData called for syncId: ${JSON.stringify(e)}, filter: ${JSON.stringify(t)}`);const r=await this.getDocument(e.documentId);this.logger.verbose(`[SYNC DEBUG] Retrieved document ${r.header.id} with type: ${r.header.documentType}`);const n=r.operations[e.scope]??[];this.logger.verbose(`[SYNC DEBUG] Found ${n.length} total operations in scope ${e.scope}`);const s=n.filter(a=>Object.keys(t).length===0||(t.since===void 0||Ci(t.since,a.timestampUtcMs))&&(t.fromRevision===void 0||a.index>=t.fromRevision));this.logger.verbose(`[SYNC DEBUG] Filtered to ${s.length} operations based on filter criteria`+(t.fromRevision!==void 0?` (fromRevision: ${t.fromRevision})`:""));const o=t.limit?s.slice(0,t.limit):s;if(this.logger.verbose(`[SYNC DEBUG] Returning ${o.length} operations after applying limit`),o.length>0){const a=o[0],d=o[o.length-1];this.logger.verbose(`[SYNC DEBUG] First operation: index=${a.index}, type=${a.action.type}`),this.logger.verbose(`[SYNC DEBUG] Last operation: index=${d.index}, type=${d.action.type}`)}return o.map(a=>({actionId:a.action.id,hash:a.hash,index:a.index,timestampUtcMs:a.timestampUtcMs,type:a.action.type,input:a.action.input,skip:a.skip,context:a.action.context,id:a.id}))}async getDocument(e){try{const r=await this.cache.getDocument(e);if(r)return r}catch(r){this.logger.error("Error getting document from cache",r)}const t=await this.documentStorage.get(e);return this._buildDocument(t)}_buildDocument(e){const t=this.getDocumentModelModule(e.header.documentType),r=Ve(e.operations);return Cr(e.initialState,r,t.reducer,void 0,e.header,void 0,{checkHashes:!0,reuseOperationResultingState:!0})}setDocumentModelModules(e){this.documentModelModules=e}getDocumentModelModule(e){const t=this.documentModelModules.find(r=>r.documentModel.global.id===e);if(!t)throw new Error(`Document type ${e} not supported`);return t}getCombinedSyncUnitStatus(e){if(!e.pull&&!e.push||e.pull==="INITIAL_SYNC")return"INITIAL_SYNC";if(e.push==="INITIAL_SYNC")return e.pull||"INITIAL_SYNC";const t=["ERROR","MISSING","CONFLICT","SYNCING","SUCCESS"];return Object.values(e).sort((n,s)=>t.indexOf(n)-t.indexOf(s))[0]}getSyncStatus(e,t="global",r="main"){const n=typeof e=="string"?{documentId:e,scope:t,branch:r}:e,s=this.syncStatus.get(n);return s?this.getCombinedSyncUnitStatus(s):new fi(n)}updateSyncStatus(e,t,r,n="global",s="main"){const o=typeof e=="string"?{documentId:e,scope:n,branch:s}:e;if(t===null){this.syncStatus.delete(o);return}const a=this.syncStatus.get(o);if(!a){this.initSyncStatus(o,t);return}if(Object.entries(t).some(([l,m])=>a[l]!==m)){const l=Object.entries(t).reduce((b,[w,y])=>({...b,[w]:b[w]==="INITIAL_SYNC"&&y==="SYNCING"?"INITIAL_SYNC":y}),a),m=this.getCombinedSyncUnitStatus(a),f=this.getCombinedSyncUnitStatus(l);this.syncStatus.set(o,l),m!==f&&this.eventEmitter&&this.eventEmitter.emit("syncStatus",o.documentId,this.getCombinedSyncUnitStatus(l),r,l,o.scope,o.branch)}}initSyncStatus(e,t){const r=Object.entries(t).reduce((n,[s,o])=>({...n,[s]:o!=="SYNCING"?o:"INITIAL_SYNC"}),{});this.syncStatus.set(e,r),this.eventEmitter&&this.eventEmitter.emit("syncStatus",e.documentId,this.getCombinedSyncUnitStatus(r),void 0,r,e.scope,e.branch)}async initializeDriveSyncStatus(e,t){const r=await this.getSynchronizationUnitsIds(e),n={pull:t.state.local.triggers.length>0?"INITIAL_SYNC":void 0,push:t.state.local.listeners.length>0?"SUCCESS":void 0};if(!n.pull&&!n.push)return;const s=[{documentId:e,scope:"global",branch:"main"},...r];for(const o of s)this.initSyncStatus(o,n)}}class bo{listenerManager;constructor(e){this.listenerManager=e}instance(e,t,r){switch(e){case"SwitchboardPush":{if(!t.callInfo?.data)throw new Error("No call info data: "+JSON.stringify(t));return new pn(t.callInfo.data,this.listenerManager)}case"Internal":throw new Error("Internal transmitter not implemented");default:return new ce(t,this.listenerManager)}}}class Po{documentModelModules=[];storage;cache;queueManager;eventEmitter;options;synchronizationManager;listenerManager;transmitterFactory;constructor(e){this.documentModelModules=e}withStorage(e){return this.storage=e,this}withCache(e){return this.cache=e,this}withQueueManager(e){return this.queueManager=e,this}withEventEmitter(e){return this.eventEmitter=e,this}withSynchronizationManager(e){return this.synchronizationManager=e,this}withListenerManager(e){return this.listenerManager=e,this}withTransmitterFactory(e){return this.transmitterFactory=e,this}withOptions(e){return this.options=e,this}build(){if(this.storage||(this.storage=new mo),this.cache||(this.cache=new Us),this.queueManager||(this.queueManager=new Bi),this.eventEmitter||(this.eventEmitter=new yo),this.synchronizationManager||(this.synchronizationManager=new wo(this.storage,this.storage,this.cache,this.documentModelModules,this.eventEmitter)),!this.listenerManager){const e={...ot,...this.options?.listenerManager};this.listenerManager=new qt(this.synchronizationManager,e)}return this.transmitterFactory||(this.transmitterFactory=new bo(this.listenerManager)),new po(this.documentModelModules,this.storage,this.storage,this.cache,this.queueManager,this.eventEmitter,this.synchronizationManager,this.listenerManager,{...this.options,featureFlags:{enableDualActionCreate:!1,...this.options?.featureFlags}})}}function Or(i){let e=!1;const t=Object.entries(i.operations).reduce((r,[n,s])=>{const o=n;if(!s)return r;for(const a of s){const d=Do(a),l=r[o];l&&l.push(d),d!==a&&(e=!0)}return r},{global:[],local:[]});return e?{...i,operations:t}:i}function Do(i){let e=!1,t={...i};const r=i.context?.signer,n=i.action?.context?.signer;if(r){if("signature"in r){const s=r.signature;t={...t,context:{...t.context,signer:{user:r.user,app:r.app,signatures:s?.length?[s]:[]}}},e=!0}else if(r.signatures){const s=r.signatures.filter(o=>o&&o.length>0);s.length!==r.signatures.length&&(t={...t,context:{...t.context,signer:{...r,signatures:s}}},e=!0)}}if(n){if("signature"in n){const s=n.signature,o={...t.action.context,signer:{user:n.user,app:n.app,signatures:s?.length?[s]:[]}};t={...t,action:{...t.action,context:o},context:o},e=!0}else if(n.signatures){const s=n.signatures.filter(o=>o&&o.length>0);if(s.length!==n.signatures.length){const o={...t.action.context,signer:{...n,signatures:s}};t={...t,action:{...t.action,context:o},context:o},e=!0}}}return e?t:i}var xt={exports:{}};var _r;function So(){return _r||(_r=1,(function(i,e){(function(t){i.exports=t()})(function(){return(function t(r,n,s){function o(l,m){if(!n[l]){if(!r[l]){var f=typeof Je=="function"&&Je;if(!m&&f)return f(l,!0);if(a)return a(l,!0);var b=new Error("Cannot find module '"+l+"'");throw b.code="MODULE_NOT_FOUND",b}var w=n[l]={exports:{}};r[l][0].call(w.exports,function(y){var I=r[l][1][y];return o(I||y)},w,w.exports,t,r,n,s)}return n[l].exports}for(var a=typeof Je=="function"&&Je,d=0;d<s.length;d++)o(s[d]);return o})({1:[function(t,r,n){(function(s){var o=s.MutationObserver||s.WebKitMutationObserver,a;if(o){var d=0,l=new o(y),m=s.document.createTextNode("");l.observe(m,{characterData:!0}),a=function(){m.data=d=++d%2}}else if(!s.setImmediate&&typeof s.MessageChannel<"u"){var f=new s.MessageChannel;f.port1.onmessage=y,a=function(){f.port2.postMessage(0)}}else"document"in s&&"onreadystatechange"in s.document.createElement("script")?a=function(){var _=s.document.createElement("script");_.onreadystatechange=function(){y(),_.onreadystatechange=null,_.parentNode.removeChild(_),_=null},s.document.documentElement.appendChild(_)}:a=function(){setTimeout(y,0)};var b,w=[];function y(){b=!0;for(var _,N,C=w.length;C;){for(N=w,w=[],_=-1;++_<C;)N[_]();C=w.length}b=!1}r.exports=I;function I(_){w.push(_)===1&&!b&&a()}}).call(this,typeof Ee<"u"?Ee:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(t,r,n){var s=t(1);function o(){}var a={},d=["REJECTED"],l=["FULFILLED"],m=["PENDING"];r.exports=f;function f(E){if(typeof E!="function")throw new TypeError("resolver must be a function");this.state=m,this.queue=[],this.outcome=void 0,E!==o&&I(this,E)}f.prototype.catch=function(E){return this.then(null,E)},f.prototype.then=function(E,L){if(typeof E!="function"&&this.state===l||typeof L!="function"&&this.state===d)return this;var P=new this.constructor(o);if(this.state!==m){var j=this.state===l?E:L;w(P,j,this.outcome)}else this.queue.push(new b(P,E,L));return P};function b(E,L,P){this.promise=E,typeof L=="function"&&(this.onFulfilled=L,this.callFulfilled=this.otherCallFulfilled),typeof P=="function"&&(this.onRejected=P,this.callRejected=this.otherCallRejected)}b.prototype.callFulfilled=function(E){a.resolve(this.promise,E)},b.prototype.otherCallFulfilled=function(E){w(this.promise,this.onFulfilled,E)},b.prototype.callRejected=function(E){a.reject(this.promise,E)},b.prototype.otherCallRejected=function(E){w(this.promise,this.onRejected,E)};function w(E,L,P){s(function(){var j;try{j=L(P)}catch(H){return a.reject(E,H)}j===E?a.reject(E,new TypeError("Cannot resolve promise with itself")):a.resolve(E,j)})}a.resolve=function(E,L){var P=_(y,L);if(P.status==="error")return a.reject(E,P.value);var j=P.value;if(j)I(E,j);else{E.state=l,E.outcome=L;for(var H=-1,V=E.queue.length;++H<V;)E.queue[H].callFulfilled(L)}return E},a.reject=function(E,L){E.state=d,E.outcome=L;for(var P=-1,j=E.queue.length;++P<j;)E.queue[P].callRejected(L);return E};function y(E){var L=E&&E.then;if(E&&(typeof E=="object"||typeof E=="function")&&typeof L=="function")return function(){L.apply(E,arguments)}}function I(E,L){var P=!1;function j(Y){P||(P=!0,a.reject(E,Y))}function H(Y){P||(P=!0,a.resolve(E,Y))}function V(){L(H,j)}var Z=_(V);Z.status==="error"&&j(Z.value)}function _(E,L){var P={};try{P.value=E(L),P.status="success"}catch(j){P.status="error",P.value=j}return P}f.resolve=N;function N(E){return E instanceof this?E:a.resolve(new this(o),E)}f.reject=C;function C(E){var L=new this(o);return a.reject(L,E)}f.all=U;function U(E){var L=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var P=E.length,j=!1;if(!P)return this.resolve([]);for(var H=new Array(P),V=0,Z=-1,Y=new this(o);++Z<P;)se(E[Z],Z);return Y;function se(le,D){L.resolve(le).then(R,function(B){j||(j=!0,a.reject(Y,B))});function R(B){H[D]=B,++V===P&&!j&&(j=!0,a.resolve(Y,H))}}}f.race=F;function F(E){var L=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var P=E.length,j=!1;if(!P)return this.resolve([]);for(var H=-1,V=new this(o);++H<P;)Z(E[H]);return V;function Z(Y){L.resolve(Y).then(function(se){j||(j=!0,a.resolve(V,se))},function(se){j||(j=!0,a.reject(V,se))})}}},{1:1}],3:[function(t,r,n){(function(s){typeof s.Promise!="function"&&(s.Promise=t(2))}).call(this,typeof Ee<"u"?Ee:typeof self<"u"?self:typeof window<"u"?window:{})},{2:2}],4:[function(t,r,n){var s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(c){return typeof c}:function(c){return c&&typeof Symbol=="function"&&c.constructor===Symbol&&c!==Symbol.prototype?"symbol":typeof c};function o(c,h){if(!(c instanceof h))throw new TypeError("Cannot call a class as a function")}function a(){try{if(typeof indexedDB<"u")return indexedDB;if(typeof webkitIndexedDB<"u")return webkitIndexedDB;if(typeof mozIndexedDB<"u")return mozIndexedDB;if(typeof OIndexedDB<"u")return OIndexedDB;if(typeof msIndexedDB<"u")return msIndexedDB}catch{return}}var d=a();function l(){try{if(!d||!d.open)return!1;var c=typeof openDatabase<"u"&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),h=typeof fetch=="function"&&fetch.toString().indexOf("[native code")!==-1;return(!c||h)&&typeof indexedDB<"u"&&typeof IDBKeyRange<"u"}catch{return!1}}function m(c,h){c=c||[],h=h||{};try{return new Blob(c,h)}catch(g){if(g.name!=="TypeError")throw g;for(var u=typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder,p=new u,v=0;v<c.length;v+=1)p.append(c[v]);return p.getBlob(h.type)}}typeof Promise>"u"&&t(3);var f=Promise;function b(c,h){h&&c.then(function(u){h(null,u)},function(u){h(u)})}function w(c,h,u){typeof h=="function"&&c.then(h),typeof u=="function"&&c.catch(u)}function y(c){return typeof c!="string"&&(console.warn(c+" used as a key, but it is not a string."),c=String(c)),c}function I(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var _="local-forage-detect-blob-support",N=void 0,C={},U=Object.prototype.toString,F="readonly",E="readwrite";function L(c){for(var h=c.length,u=new ArrayBuffer(h),p=new Uint8Array(u),v=0;v<h;v++)p[v]=c.charCodeAt(v);return u}function P(c){return new f(function(h){var u=c.transaction(_,E),p=m([""]);u.objectStore(_).put(p,"key"),u.onabort=function(v){v.preventDefault(),v.stopPropagation(),h(!1)},u.oncomplete=function(){var v=navigator.userAgent.match(/Chrome\/(\d+)/),g=navigator.userAgent.match(/Edge\//);h(g||!v||parseInt(v[1],10)>=43)}}).catch(function(){return!1})}function j(c){return typeof N=="boolean"?f.resolve(N):P(c).then(function(h){return N=h,N})}function H(c){var h=C[c.name],u={};u.promise=new f(function(p,v){u.resolve=p,u.reject=v}),h.deferredOperations.push(u),h.dbReady?h.dbReady=h.dbReady.then(function(){return u.promise}):h.dbReady=u.promise}function V(c){var h=C[c.name],u=h.deferredOperations.pop();if(u)return u.resolve(),u.promise}function Z(c,h){var u=C[c.name],p=u.deferredOperations.pop();if(p)return p.reject(h),p.promise}function Y(c,h){return new f(function(u,p){if(C[c.name]=C[c.name]||_e(),c.db)if(h)H(c),c.db.close();else return u(c.db);var v=[c.name];h&&v.push(c.version);var g=d.open.apply(d,v);h&&(g.onupgradeneeded=function(S){var T=g.result;try{T.createObjectStore(c.storeName),S.oldVersion<=1&&T.createObjectStore(_)}catch(M){if(M.name==="ConstraintError")console.warn('The database "'+c.name+'" has been upgraded from version '+S.oldVersion+" to version "+S.newVersion+', but the storage "'+c.storeName+'" already exists.');else throw M}}),g.onerror=function(S){S.preventDefault(),p(g.error)},g.onsuccess=function(){var S=g.result;S.onversionchange=function(T){T.target.close()},u(S),V(c)}})}function se(c){return Y(c,!1)}function le(c){return Y(c,!0)}function D(c,h){if(!c.db)return!0;var u=!c.db.objectStoreNames.contains(c.storeName),p=c.version<c.db.version,v=c.version>c.db.version;if(p&&(c.version!==h&&console.warn('The database "'+c.name+`" can't be downgraded from version `+c.db.version+" to version "+c.version+"."),c.version=c.db.version),v||u){if(u){var g=c.db.version+1;g>c.version&&(c.version=g)}return!0}return!1}function R(c){return new f(function(h,u){var p=new FileReader;p.onerror=u,p.onloadend=function(v){var g=btoa(v.target.result||"");h({__local_forage_encoded_blob:!0,data:g,type:c.type})},p.readAsBinaryString(c)})}function B(c){var h=L(atob(c.data));return m([h],{type:c.type})}function G(c){return c&&c.__local_forage_encoded_blob}function K(c){var h=this,u=h._initReady().then(function(){var p=C[h._dbInfo.name];if(p&&p.dbReady)return p.dbReady});return w(u,c,c),u}function z(c){H(c);for(var h=C[c.name],u=h.forages,p=0;p<u.length;p++){var v=u[p];v._dbInfo.db&&(v._dbInfo.db.close(),v._dbInfo.db=null)}return c.db=null,se(c).then(function(g){return c.db=g,D(c)?le(c):g}).then(function(g){c.db=h.db=g;for(var S=0;S<u.length;S++)u[S]._dbInfo.db=g}).catch(function(g){throw Z(c,g),g})}function ae(c,h,u,p){p===void 0&&(p=1);try{var v=c.db.transaction(c.storeName,h);u(null,v)}catch(g){if(p>0&&(!c.db||g.name==="InvalidStateError"||g.name==="NotFoundError"))return f.resolve().then(function(){if(!c.db||g.name==="NotFoundError"&&!c.db.objectStoreNames.contains(c.storeName)&&c.version<=c.db.version)return c.db&&(c.version=c.db.version+1),le(c)}).then(function(){return z(c).then(function(){ae(c,h,u,p-1)})}).catch(u);u(g)}}function _e(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function qe(c){var h=this,u={db:null};if(c)for(var p in c)u[p]=c[p];var v=C[u.name];v||(v=_e(),C[u.name]=v),v.forages.push(h),h._initReady||(h._initReady=h.ready,h.ready=K);var g=[];function S(){return f.resolve()}for(var T=0;T<v.forages.length;T++){var M=v.forages[T];M!==h&&g.push(M._initReady().catch(S))}var O=v.forages.slice(0);return f.all(g).then(function(){return u.db=v.db,se(u)}).then(function(A){return u.db=A,D(u,h._defaultConfig.version)?le(u):A}).then(function(A){u.db=v.db=A,h._dbInfo=u;for(var x=0;x<O.length;x++){var k=O[x];k!==h&&(k._dbInfo.db=u.db,k._dbInfo.version=u.version)}})}function ne(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){ae(u._dbInfo,F,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=M.get(c);O.onsuccess=function(){var A=O.result;A===void 0&&(A=null),G(A)&&(A=B(A)),v(A)},O.onerror=function(){g(O.error)}}catch(A){g(A)}})}).catch(g)});return b(p,h),p}function me(c,h){var u=this,p=new f(function(v,g){u.ready().then(function(){ae(u._dbInfo,F,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=M.openCursor(),A=1;O.onsuccess=function(){var x=O.result;if(x){var k=x.value;G(k)&&(k=B(k));var J=c(k,x.key,A++);J!==void 0?v(J):x.continue()}else v()},O.onerror=function(){g(O.error)}}catch(x){g(x)}})}).catch(g)});return b(p,h),p}function mn(c,h,u){var p=this;c=y(c);var v=new f(function(g,S){var T;p.ready().then(function(){return T=p._dbInfo,U.call(h)==="[object Blob]"?j(T.db).then(function(M){return M?h:R(h)}):h}).then(function(M){ae(p._dbInfo,E,function(O,A){if(O)return S(O);try{var x=A.objectStore(p._dbInfo.storeName);M===null&&(M=void 0);var k=x.put(M,c);A.oncomplete=function(){M===void 0&&(M=null),g(M)},A.onabort=A.onerror=function(){var J=k.error?k.error:k.transaction.error;S(J)}}catch(J){S(J)}})}).catch(S)});return b(v,u),v}function yn(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){ae(u._dbInfo,E,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=M.delete(c);T.oncomplete=function(){v()},T.onerror=function(){g(O.error)},T.onabort=function(){var A=O.error?O.error:O.transaction.error;g(A)}}catch(A){g(A)}})}).catch(g)});return b(p,h),p}function vn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){ae(h._dbInfo,E,function(g,S){if(g)return v(g);try{var T=S.objectStore(h._dbInfo.storeName),M=T.clear();S.oncomplete=function(){p()},S.onabort=S.onerror=function(){var O=M.error?M.error:M.transaction.error;v(O)}}catch(O){v(O)}})}).catch(v)});return b(u,c),u}function wn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){ae(h._dbInfo,F,function(g,S){if(g)return v(g);try{var T=S.objectStore(h._dbInfo.storeName),M=T.count();M.onsuccess=function(){p(M.result)},M.onerror=function(){v(M.error)}}catch(O){v(O)}})}).catch(v)});return b(u,c),u}function bn(c,h){var u=this,p=new f(function(v,g){if(c<0){v(null);return}u.ready().then(function(){ae(u._dbInfo,F,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=!1,A=M.openKeyCursor();A.onsuccess=function(){var x=A.result;if(!x){v(null);return}c===0||O?v(x.key):(O=!0,x.advance(c))},A.onerror=function(){g(A.error)}}catch(x){g(x)}})}).catch(g)});return b(p,h),p}function Dn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){ae(h._dbInfo,F,function(g,S){if(g)return v(g);try{var T=S.objectStore(h._dbInfo.storeName),M=T.openKeyCursor(),O=[];M.onsuccess=function(){var A=M.result;if(!A){p(O);return}O.push(A.key),A.continue()},M.onerror=function(){v(M.error)}}catch(A){v(A)}})}).catch(v)});return b(u,c),u}function Sn(c,h){h=I.apply(this,arguments);var u=this.config();c=typeof c!="function"&&c||{},c.name||(c.name=c.name||u.name,c.storeName=c.storeName||u.storeName);var p=this,v;if(!c.name)v=f.reject("Invalid arguments");else{var g=c.name===u.name&&p._dbInfo.db,S=g?f.resolve(p._dbInfo.db):se(c).then(function(T){var M=C[c.name],O=M.forages;M.db=T;for(var A=0;A<O.length;A++)O[A]._dbInfo.db=T;return T});c.storeName?v=S.then(function(T){if(T.objectStoreNames.contains(c.storeName)){var M=T.version+1;H(c);var O=C[c.name],A=O.forages;T.close();for(var x=0;x<A.length;x++){var k=A[x];k._dbInfo.db=null,k._dbInfo.version=M}var J=new f(function(Q,re){var ee=d.open(c.name,M);ee.onerror=function(ue){var Pe=ee.result;Pe.close(),re(ue)},ee.onupgradeneeded=function(){var ue=ee.result;ue.deleteObjectStore(c.storeName)},ee.onsuccess=function(){var ue=ee.result;ue.close(),Q(ue)}});return J.then(function(Q){O.db=Q;for(var re=0;re<A.length;re++){var ee=A[re];ee._dbInfo.db=Q,V(ee._dbInfo)}}).catch(function(Q){throw(Z(c,Q)||f.resolve()).catch(function(){}),Q})}}):v=S.then(function(T){H(c);var M=C[c.name],O=M.forages;T.close();for(var A=0;A<O.length;A++){var x=O[A];x._dbInfo.db=null}var k=new f(function(J,Q){var re=d.deleteDatabase(c.name);re.onerror=function(){var ee=re.result;ee&&ee.close(),Q(re.error)},re.onblocked=function(){console.warn('dropInstance blocked for database "'+c.name+'" until all open connections are closed')},re.onsuccess=function(){var ee=re.result;ee&&ee.close(),J(ee)}});return k.then(function(J){M.db=J;for(var Q=0;Q<O.length;Q++){var re=O[Q];V(re._dbInfo)}}).catch(function(J){throw(Z(c,J)||f.resolve()).catch(function(){}),J})})}return b(v,h),v}var En={_driver:"asyncStorage",_initStorage:qe,_support:l(),iterate:me,getItem:ne,setItem:mn,removeItem:yn,clear:vn,length:wn,key:bn,keys:Dn,dropInstance:Sn};function In(){return typeof openDatabase=="function"}var be="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Tn="~~local_forage_type~",zt=/^~~local_forage_type~([^~]+)~/,ze="__lfsc__:",ht=ze.length,ft="arbf",gt="blob",jt="si08",Ht="ui08",Gt="uic8",Jt="si16",Yt="si32",Qt="ur16",Vt="ui32",Kt="fl32",Wt="fl64",Xt=ht+ft.length,Zt=Object.prototype.toString;function er(c){var h=c.length*.75,u=c.length,p,v=0,g,S,T,M;c[c.length-1]==="="&&(h--,c[c.length-2]==="="&&h--);var O=new ArrayBuffer(h),A=new Uint8Array(O);for(p=0;p<u;p+=4)g=be.indexOf(c[p]),S=be.indexOf(c[p+1]),T=be.indexOf(c[p+2]),M=be.indexOf(c[p+3]),A[v++]=g<<2|S>>4,A[v++]=(S&15)<<4|T>>2,A[v++]=(T&3)<<6|M&63;return O}function pt(c){var h=new Uint8Array(c),u="",p;for(p=0;p<h.length;p+=3)u+=be[h[p]>>2],u+=be[(h[p]&3)<<4|h[p+1]>>4],u+=be[(h[p+1]&15)<<2|h[p+2]>>6],u+=be[h[p+2]&63];return h.length%3===2?u=u.substring(0,u.length-1)+"=":h.length%3===1&&(u=u.substring(0,u.length-2)+"=="),u}function Rn(c,h){var u="";if(c&&(u=Zt.call(c)),c&&(u==="[object ArrayBuffer]"||c.buffer&&Zt.call(c.buffer)==="[object ArrayBuffer]")){var p,v=ze;c instanceof ArrayBuffer?(p=c,v+=ft):(p=c.buffer,u==="[object Int8Array]"?v+=jt:u==="[object Uint8Array]"?v+=Ht:u==="[object Uint8ClampedArray]"?v+=Gt:u==="[object Int16Array]"?v+=Jt:u==="[object Uint16Array]"?v+=Qt:u==="[object Int32Array]"?v+=Yt:u==="[object Uint32Array]"?v+=Vt:u==="[object Float32Array]"?v+=Kt:u==="[object Float64Array]"?v+=Wt:h(new Error("Failed to get type for BinaryArray"))),h(v+pt(p))}else if(u==="[object Blob]"){var g=new FileReader;g.onload=function(){var S=Tn+c.type+"~"+pt(this.result);h(ze+gt+S)},g.readAsArrayBuffer(c)}else try{h(JSON.stringify(c))}catch(S){console.error("Couldn't convert value into a JSON string: ",c),h(null,S)}}function Mn(c){if(c.substring(0,ht)!==ze)return JSON.parse(c);var h=c.substring(Xt),u=c.substring(ht,Xt),p;if(u===gt&&zt.test(h)){var v=h.match(zt);p=v[1],h=h.substring(v[0].length)}var g=er(h);switch(u){case ft:return g;case gt:return m([g],{type:p});case jt:return new Int8Array(g);case Ht:return new Uint8Array(g);case Gt:return new Uint8ClampedArray(g);case Jt:return new Int16Array(g);case Qt:return new Uint16Array(g);case Yt:return new Int32Array(g);case Vt:return new Uint32Array(g);case Kt:return new Float32Array(g);case Wt:return new Float64Array(g);default:throw new Error("Unkown type: "+u)}}var mt={serialize:Rn,deserialize:Mn,stringToBuffer:er,bufferToString:pt};function tr(c,h,u,p){c.executeSql("CREATE TABLE IF NOT EXISTS "+h.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],u,p)}function On(c){var h=this,u={db:null};if(c)for(var p in c)u[p]=typeof c[p]!="string"?c[p].toString():c[p];var v=new f(function(g,S){try{u.db=openDatabase(u.name,String(u.version),u.description,u.size)}catch(T){return S(T)}u.db.transaction(function(T){tr(T,u,function(){h._dbInfo=u,g()},function(M,O){S(O)})},S)});return u.serializer=mt,v}function De(c,h,u,p,v,g){c.executeSql(u,p,v,function(S,T){T.code===T.SYNTAX_ERR?S.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[h.storeName],function(M,O){O.rows.length?g(M,T):tr(M,h,function(){M.executeSql(u,p,v,g)},g)},g):g(S,T)},g)}function _n(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"SELECT * FROM "+S.storeName+" WHERE key = ? LIMIT 1",[c],function(M,O){var A=O.rows.length?O.rows.item(0).value:null;A&&(A=S.serializer.deserialize(A)),v(A)},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function An(c,h){var u=this,p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"SELECT * FROM "+S.storeName,[],function(M,O){for(var A=O.rows,x=A.length,k=0;k<x;k++){var J=A.item(k),Q=J.value;if(Q&&(Q=S.serializer.deserialize(Q)),Q=c(Q,J.key,k+1),Q!==void 0){v(Q);return}}v()},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function rr(c,h,u,p){var v=this;c=y(c);var g=new f(function(S,T){v.ready().then(function(){h===void 0&&(h=null);var M=h,O=v._dbInfo;O.serializer.serialize(h,function(A,x){x?T(x):O.db.transaction(function(k){De(k,O,"INSERT OR REPLACE INTO "+O.storeName+" (key, value) VALUES (?, ?)",[c,A],function(){S(M)},function(J,Q){T(Q)})},function(k){if(k.code===k.QUOTA_ERR){if(p>0){S(rr.apply(v,[c,M,u,p-1]));return}T(k)}})})}).catch(T)});return b(g,u),g}function Nn(c,h,u){return rr.apply(this,[c,h,u,1])}function Cn(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"DELETE FROM "+S.storeName+" WHERE key = ?",[c],function(){v()},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function xn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){var g=h._dbInfo;g.db.transaction(function(S){De(S,g,"DELETE FROM "+g.storeName,[],function(){p()},function(T,M){v(M)})})}).catch(v)});return b(u,c),u}function $n(c){var h=this,u=new f(function(p,v){h.ready().then(function(){var g=h._dbInfo;g.db.transaction(function(S){De(S,g,"SELECT COUNT(key) as c FROM "+g.storeName,[],function(T,M){var O=M.rows.item(0).c;p(O)},function(T,M){v(M)})})}).catch(v)});return b(u,c),u}function Pn(c,h){var u=this,p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"SELECT key FROM "+S.storeName+" WHERE id = ? LIMIT 1",[c+1],function(M,O){var A=O.rows.length?O.rows.item(0).key:null;v(A)},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function Ln(c){var h=this,u=new f(function(p,v){h.ready().then(function(){var g=h._dbInfo;g.db.transaction(function(S){De(S,g,"SELECT key FROM "+g.storeName,[],function(T,M){for(var O=[],A=0;A<M.rows.length;A++)O.push(M.rows.item(A).key);p(O)},function(T,M){v(M)})})}).catch(v)});return b(u,c),u}function Un(c){return new f(function(h,u){c.transaction(function(p){p.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(v,g){for(var S=[],T=0;T<g.rows.length;T++)S.push(g.rows.item(T).name);h({db:c,storeNames:S})},function(v,g){u(g)})},function(p){u(p)})})}function Bn(c,h){h=I.apply(this,arguments);var u=this.config();c=typeof c!="function"&&c||{},c.name||(c.name=c.name||u.name,c.storeName=c.storeName||u.storeName);var p=this,v;return c.name?v=new f(function(g){var S;c.name===u.name?S=p._dbInfo.db:S=openDatabase(c.name,"","",0),c.storeName?g({db:S,storeNames:[c.storeName]}):g(Un(S))}).then(function(g){return new f(function(S,T){g.db.transaction(function(M){function O(J){return new f(function(Q,re){M.executeSql("DROP TABLE IF EXISTS "+J,[],function(){Q()},function(ee,ue){re(ue)})})}for(var A=[],x=0,k=g.storeNames.length;x<k;x++)A.push(O(g.storeNames[x]));f.all(A).then(function(){S()}).catch(function(J){T(J)})},function(M){T(M)})})}):v=f.reject("Invalid arguments"),b(v,h),v}var Fn={_driver:"webSQLStorage",_initStorage:On,_support:In(),iterate:An,getItem:_n,setItem:Nn,removeItem:Cn,clear:xn,length:$n,key:Pn,keys:Ln,dropInstance:Bn};function kn(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}function nr(c,h){var u=c.name+"/";return c.storeName!==h.storeName&&(u+=c.storeName+"/"),u}function qn(){var c="_localforage_support_test";try{return localStorage.setItem(c,!0),localStorage.removeItem(c),!1}catch{return!0}}function zn(){return!qn()||localStorage.length>0}function jn(c){var h=this,u={};if(c)for(var p in c)u[p]=c[p];return u.keyPrefix=nr(c,h._defaultConfig),zn()?(h._dbInfo=u,u.serializer=mt,f.resolve()):f.reject()}function Hn(c){var h=this,u=h.ready().then(function(){for(var p=h._dbInfo.keyPrefix,v=localStorage.length-1;v>=0;v--){var g=localStorage.key(v);g.indexOf(p)===0&&localStorage.removeItem(g)}});return b(u,c),u}function Gn(c,h){var u=this;c=y(c);var p=u.ready().then(function(){var v=u._dbInfo,g=localStorage.getItem(v.keyPrefix+c);return g&&(g=v.serializer.deserialize(g)),g});return b(p,h),p}function Jn(c,h){var u=this,p=u.ready().then(function(){for(var v=u._dbInfo,g=v.keyPrefix,S=g.length,T=localStorage.length,M=1,O=0;O<T;O++){var A=localStorage.key(O);if(A.indexOf(g)===0){var x=localStorage.getItem(A);if(x&&(x=v.serializer.deserialize(x)),x=c(x,A.substring(S),M++),x!==void 0)return x}}});return b(p,h),p}function Yn(c,h){var u=this,p=u.ready().then(function(){var v=u._dbInfo,g;try{g=localStorage.key(c)}catch{g=null}return g&&(g=g.substring(v.keyPrefix.length)),g});return b(p,h),p}function Qn(c){var h=this,u=h.ready().then(function(){for(var p=h._dbInfo,v=localStorage.length,g=[],S=0;S<v;S++){var T=localStorage.key(S);T.indexOf(p.keyPrefix)===0&&g.push(T.substring(p.keyPrefix.length))}return g});return b(u,c),u}function Vn(c){var h=this,u=h.keys().then(function(p){return p.length});return b(u,c),u}function Kn(c,h){var u=this;c=y(c);var p=u.ready().then(function(){var v=u._dbInfo;localStorage.removeItem(v.keyPrefix+c)});return b(p,h),p}function Wn(c,h,u){var p=this;c=y(c);var v=p.ready().then(function(){h===void 0&&(h=null);var g=h;return new f(function(S,T){var M=p._dbInfo;M.serializer.serialize(h,function(O,A){if(A)T(A);else try{localStorage.setItem(M.keyPrefix+c,O),S(g)}catch(x){(x.name==="QuotaExceededError"||x.name==="NS_ERROR_DOM_QUOTA_REACHED")&&T(x),T(x)}})})});return b(v,u),v}function Xn(c,h){if(h=I.apply(this,arguments),c=typeof c!="function"&&c||{},!c.name){var u=this.config();c.name=c.name||u.name,c.storeName=c.storeName||u.storeName}var p=this,v;return c.name?v=new f(function(g){c.storeName?g(nr(c,p._defaultConfig)):g(c.name+"/")}).then(function(g){for(var S=localStorage.length-1;S>=0;S--){var T=localStorage.key(S);T.indexOf(g)===0&&localStorage.removeItem(T)}}):v=f.reject("Invalid arguments"),b(v,h),v}var Zn={_driver:"localStorageWrapper",_initStorage:jn,_support:kn(),iterate:Jn,getItem:Gn,setItem:Wn,removeItem:Kn,clear:Hn,length:Vn,key:Yn,keys:Qn,dropInstance:Xn},es=function(h,u){return h===u||typeof h=="number"&&typeof u=="number"&&isNaN(h)&&isNaN(u)},ts=function(h,u){for(var p=h.length,v=0;v<p;){if(es(h[v],u))return!0;v++}return!1},sr=Array.isArray||function(c){return Object.prototype.toString.call(c)==="[object Array]"},$e={},ir={},Ae={INDEXEDDB:En,WEBSQL:Fn,LOCALSTORAGE:Zn},rs=[Ae.INDEXEDDB._driver,Ae.WEBSQL._driver,Ae.LOCALSTORAGE._driver],je=["dropInstance"],yt=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(je),ns={description:"",driver:rs.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function ss(c,h){c[h]=function(){var u=arguments;return c.ready().then(function(){return c[h].apply(c,u)})}}function vt(){for(var c=1;c<arguments.length;c++){var h=arguments[c];if(h)for(var u in h)h.hasOwnProperty(u)&&(sr(h[u])?arguments[0][u]=h[u].slice():arguments[0][u]=h[u])}return arguments[0]}var is=(function(){function c(h){o(this,c);for(var u in Ae)if(Ae.hasOwnProperty(u)){var p=Ae[u],v=p._driver;this[u]=v,$e[v]||this.defineDriver(p)}this._defaultConfig=vt({},ns),this._config=vt({},this._defaultConfig,h),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return c.prototype.config=function(u){if((typeof u>"u"?"undefined":s(u))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var p in u){if(p==="storeName"&&(u[p]=u[p].replace(/\W/g,"_")),p==="version"&&typeof u[p]!="number")return new Error("Database version must be a number.");this._config[p]=u[p]}return"driver"in u&&u.driver?this.setDriver(this._config.driver):!0}else return typeof u=="string"?this._config[u]:this._config},c.prototype.defineDriver=function(u,p,v){var g=new f(function(S,T){try{var M=u._driver,O=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!u._driver){T(O);return}for(var A=yt.concat("_initStorage"),x=0,k=A.length;x<k;x++){var J=A[x],Q=!ts(je,J);if((Q||u[J])&&typeof u[J]!="function"){T(O);return}}var re=function(){for(var Pe=function(cs){return function(){var us=new Error("Method "+cs+" is not implemented by the current driver"),or=f.reject(us);return b(or,arguments[arguments.length-1]),or}},wt=0,as=je.length;wt<as;wt++){var bt=je[wt];u[bt]||(u[bt]=Pe(bt))}};re();var ee=function(Pe){$e[M]&&console.info("Redefining LocalForage driver: "+M),$e[M]=u,ir[M]=Pe,S()};"_support"in u?u._support&&typeof u._support=="function"?u._support().then(ee,T):ee(!!u._support):ee(!0)}catch(ue){T(ue)}});return w(g,p,v),g},c.prototype.driver=function(){return this._driver||null},c.prototype.getDriver=function(u,p,v){var g=$e[u]?f.resolve($e[u]):f.reject(new Error("Driver not found."));return w(g,p,v),g},c.prototype.getSerializer=function(u){var p=f.resolve(mt);return w(p,u),p},c.prototype.ready=function(u){var p=this,v=p._driverSet.then(function(){return p._ready===null&&(p._ready=p._initDriver()),p._ready});return w(v,u,u),v},c.prototype.setDriver=function(u,p,v){var g=this;sr(u)||(u=[u]);var S=this._getSupportedDrivers(u);function T(){g._config.driver=g.driver()}function M(x){return g._extend(x),T(),g._ready=g._initStorage(g._config),g._ready}function O(x){return function(){var k=0;function J(){for(;k<x.length;){var Q=x[k];return k++,g._dbInfo=null,g._ready=null,g.getDriver(Q).then(M).catch(J)}T();var re=new Error("No available storage method found.");return g._driverSet=f.reject(re),g._driverSet}return J()}}var A=this._driverSet!==null?this._driverSet.catch(function(){return f.resolve()}):f.resolve();return this._driverSet=A.then(function(){var x=S[0];return g._dbInfo=null,g._ready=null,g.getDriver(x).then(function(k){g._driver=k._driver,T(),g._wrapLibraryMethodsWithReady(),g._initDriver=O(S)})}).catch(function(){T();var x=new Error("No available storage method found.");return g._driverSet=f.reject(x),g._driverSet}),w(this._driverSet,p,v),this._driverSet},c.prototype.supports=function(u){return!!ir[u]},c.prototype._extend=function(u){vt(this,u)},c.prototype._getSupportedDrivers=function(u){for(var p=[],v=0,g=u.length;v<g;v++){var S=u[v];this.supports(S)&&p.push(S)}return p},c.prototype._wrapLibraryMethodsWithReady=function(){for(var u=0,p=yt.length;u<p;u++)ss(this,yt[u])},c.prototype.createInstance=function(u){return new c(u)},c})(),os=new is;r.exports=os},{3:3}]},{},[4])(4)})})(xt)),xt.exports}var Eo=So();const Ar=Pt(Eo);class te{logger=pe(["BrowserStorage"]);db;static DBName="DOCUMENT_DRIVES";static SEP=":";static DOCUMENT_KEY="DOCUMENT";static MANIFEST_KEY="MANIFEST";static SLUG_MANIFEST_KEY="SLUG_MANIFEST";constructor(e){this.db=Ar.ready().then(()=>Ar.createInstance({name:e?`${e}:${te.DBName}`:te.DBName}))}async findStorageUnitsBy(e,t,r){const n=[],{parentId:s,documentId:o,documentModelType:a,scope:d}=sn(e),f=(await(await this.db).keys()).filter(_=>_.startsWith(`${te.DOCUMENT_KEY}${te.SEP}`)).map(_=>_.slice(te.DOCUMENT_KEY.length+te.SEP.length));let b;if(s){const _=new Set;for(const N of s)(await this.getChildren(N)).forEach(U=>_.add(U));b=on(s,_)}else b=new Set(f);b=o?an(o,b):b;for(const _ of b){const N=await this.get(_).catch(()=>null);if(N&&!(a&&!a.has(N.header.documentType)))for(const[C]of Object.entries(N.state))d&&!d.has(C)||n.push({documentId:_,documentModelType:N.header.documentType,scope:C,branch:"main"})}let w=0;if(r){const _=n.findIndex(N=>N.documentId===r);_!==-1&&(w=_)}const y=Math.min(w+t,n.length),I=y<n.length?n[y].documentId:void 0;return{units:n.slice(w,y),nextCursor:I}}async resolveIds(e,t){const r=await this.getSlugManifest();if(t?.aborted)throw new at("Aborted");const n=[];for(const s of e){const o=r.slugToId[s];if(!o)throw new we(s);n.push(o)}return Promise.resolve(n)}async resolveSlugs(e,t){const r=await this.getSlugManifest();if(t?.aborted)throw new at("Aborted");const n=[];for(const s of e){let o=!1;for(const[a,d]of Object.entries(r.slugToId))if(d===s){n.push(a),o=!0;break}if(!o)throw new we(s)}return Promise.resolve(n)}async clear(){await(await this.db).clear()}async exists(e){return!!await(await this.db).getItem(this.buildDocumentKey(e))}async create(e){const t=e.header.id;if(!tt(t))throw new et(t);const r=await this.db;if(await this.exists(t))throw new ke(t);const n=e.header.slug&&e.header.slug.length>0?e.header.slug:t;if(!nn(n))throw new rn(n);if((await this.getSlugManifest()).slugToId[n])throw new ke(t,Fe.SLUG);if(e.header.slug=n,await r.setItem(this.buildDocumentKey(t),e),n){const o=await this.getSlugManifest();if(o.slugToId[n])throw new Error(`Document with slug ${n} already exists`);o.slugToId[n]=t,await this.updateSlugManifest(o)}e.header.documentType==="powerhouse/document-drive"&&this.updateDriveManifest(t,{documentIds:[]})}async get(e){const r=await(await this.db).getItem(this.buildDocumentKey(e));return r||Promise.reject(new we(e))}async getBySlug(e){const r=(await this.getSlugManifest()).slugToId[e];return r?this.get(r):Promise.reject(new we(e))}async findByType(e,t=100,r){const n=await this.db,o=(await n.keys()).filter(f=>f.startsWith(`${te.DOCUMENT_KEY}${te.SEP}`)),a=[];for(const f of o){const b=f.slice(te.DOCUMENT_KEY.length+te.SEP.length);try{const w=await n.getItem(f);if(!w||w.header.documentType!==e)continue;a.push({id:b,document:w})}catch{continue}}a.sort((f,b)=>{const w=new Date(f.document.header.createdAtUtcIso),y=new Date(b.document.header.createdAtUtcIso);return w.getTime()===y.getTime()?f.id.localeCompare(b.id):w.getTime()-y.getTime()});let d=0;if(r){const f=a.findIndex(({id:b})=>b===r);f!==-1&&(d=f)}const l=Math.min(d+t,a.length);let m;return l<a.length&&(m=a[l].id),{documents:a.slice(d,l).map(({id:f})=>f),nextCursor:m}}async delete(e){const t=await this.db,r=await t.getItem(this.buildDocumentKey(e));if(!r)return!1;const n=r.header.slug?.length>0?r.header.slug:e;try{if(n){const o=await this.getSlugManifest();o.slugToId[n]===e&&(delete o.slugToId[n],await this.updateSlugManifest(o))}}catch{}const s=await this.getParents(e);for(const o of s)await this.removeChild(o,e);return await t.removeItem(this.buildManifestKey(e)),await t.removeItem(this.buildDocumentKey(e)),!0}async removeChild(e,t){const r=await this.getManifest(e),n=r.documentIds.indexOf(t);return n!==-1?(r.documentIds.splice(n,1),await this.updateDriveManifest(e,r),!0):!1}async addChild(e,t){if(e===t)throw new Error("Cannot associate a document with itself");if((await this.getChildren(t)).includes(e))throw new Error("Cannot associate a document with its child");const n=await this.getManifest(e);n.documentIds.includes(t)||(n.documentIds.push(t),await this.updateDriveManifest(e,n))}async getChildren(e){return(await this.getManifest(e)).documentIds}async getParents(e){const r=await(await this.db).keys(),n=[],s=r.filter(o=>o.startsWith(`${te.MANIFEST_KEY}${te.SEP}`));for(const o of s){const a=o.slice(te.MANIFEST_KEY.length+te.SEP.length);(await this.getManifest(a)).documentIds.includes(e)&&n.push(a)}return n}async getManifest(e){return await(await this.db).getItem(this.buildManifestKey(e))||{documentIds:[]}}async updateDriveManifest(e,t){await(await this.db).setItem(this.buildManifestKey(e),t)}async getSlugManifest(){return await(await this.db).getItem(te.SLUG_MANIFEST_KEY)||{slugToId:{}}}async updateSlugManifest(e){await(await this.db).setItem(te.SLUG_MANIFEST_KEY,e)}async addDocumentOperations(e,t,r){const n=await this.get(e);if(!n)throw new Error(`Document with id ${e} not found`);const s=st(n.operations,t);await(await this.db).setItem(this.buildDocumentKey(e),{...n,...r,operations:s})}async addDriveOperations(e,t,r){const n=await this.get(e),s=st(n.operations,t);await(await this.db).setItem(this.buildDocumentKey(e),{...n,...r,operations:s})}async getSynchronizationUnitsRevision(e){return(await Promise.allSettled(e.map(async r=>{try{const n=await this.get(r.documentId);if(!n?.operations[r.scope])return;const s=n.operations[r.scope];return{documentId:r.documentId,documentType:r.documentType,scope:r.scope,branch:r.branch,lastUpdated:s.at(-1)?.timestampUtcMs??n.header.createdAtUtcIso,revision:s.length>0?Ie(s):0}}catch(n){this.logger.error("Error getting synchronization units revision",n);return}}))).reduce((r,n)=>(n.status==="fulfilled"&&n.value!==void 0&&r.push(n.value),r),[])}async migrateOperationSignatures(){let e;do{const{documents:t,nextCursor:r}=await this.findByType("powerhouse/document-drive",100,e);for(const n of t){await this.migrateDrive(n);const s=await this.getChildren(n);await Promise.all(s.map(async o=>this.migrateDocument(n,o)))}e=r}while(e)}async migrateDrive(e){const t=await this.get(e),r=Or(t);if(r!==t)return(await this.db).setItem(this.buildDocumentKey(e),r)}async migrateDocument(e,t){const r=await this.get(t),n=Or(r);if(n!==r)return(await this.db).setItem(this.buildDocumentKey(t),n)}buildDocumentKey(e){return`${te.DOCUMENT_KEY}${te.SEP}${e}`}buildManifestKey(e){return`${te.MANIFEST_KEY}${te.SEP}${e}`}}export{te as B,we as D,Bi as E,Us as I,ce as P,Po as R,fi as S,Ws as a,Xs as b,gi as c,Zs as d,ri as e,oi as f,No as g,Ne as h,lr as i,si as j,ci as k,fe as l,ni as m,li as n,$o as o,Ye as p,Ao as q,tn as r,Zr as s,pe as t,ti as u,Ni as v,Co as w,gn as x};
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:co(a.input),hash:a.hash,timestampUtcMs:a.timestampUtcMs,context:a.context?{signer:a.context.signer}:void 0}))}))});if(!s.pushUpdates)throw new Error("Couldn't update listener revision");return s.pushUpdates}catch(s){throw this.logger.error(s),s}}}function Mr(i,e){return e?Object.keys(i).reduce((t,r)=>{const n=e[r];if(n!==void 0){const s=i[r];s&&(t[r]=s.filter(o=>o.index<=n))}return t},{global:[],local:[]}):i}function Nt(i,e){return!e||Object.entries(e).find(([t,r])=>{const n=i.operations[t]?.at(-1);return r===-1?n!==void 0:n?.index!==r})===void 0}function Ct(i){return{id:uo(i),documentType:lo(i),document:ho(i)}}function uo(i){return"id"in i?i.id:"header"in i?i.header.id:"document"in i?i.document.header.id:void 0}function lo(i){return"documentType"in i?i.documentType:"header"in i?i.header.documentType:i.document.header.documentType}function ho(i){return"document"in i?i.document:void 0}function fo(i){return["LOCAL","CLOUD","PUBLIC"].includes(i)}function Po(i){if(typeof i!="object")return"LOCAL";const e="readContext"in i,{sharingType:t}=e?{sharingType:"PUBLIC"}:i.state.local,r=t?.toUpperCase();return!r||r==="PRIVATE"||!fo(r)?"LOCAL":r}class go{logger=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=Le(e,t);a.header.id=e,a.header.sig=d.sig,a.header.documentType=t,r&&(a.header.meta=r.meta);try{const l=await this.createDocument({document:a},s?.source??{type:"local"},a.header.meta);return{status:"SUCCESS",operations:[],document:l,signals:[]}}catch(l){const m=l instanceof Error?l:new Error(JSON.stringify(l));return{status:"ERROR",error:new ie("ERROR",void 0,`Error creating document: ${m.message}`,m),operations:[],document:void 0,signals:[]}}},processJob:async e=>{if(fn(e))return this.queueDelegate.processOperationJob(e);if(Ui(e))return this.queueDelegate.processActionJob(e);if(Ke(e))return this.queueDelegate.processDocumentJob(e);throw new Error("Unknown job type",e)}};triggerMap=new Map;initializePromise;enableDualActionCreate;constructor(e,t,r,n,s,o,a,d,l){this.documentModelModules=e,this.legacyStorage=t,this.documentStorage=r,this.cache=n,this.queueManager=s,this.eventEmitter=o,this.synchronizationManager=a,this.listenerManager=d,this.options={...l,defaultDrives:{...l?.defaultDrives},listenerManager:{...ot,...l?.listenerManager},jwtHandler:l?.jwtHandler===void 0?()=>Promise.resolve(""):l.jwtHandler,taskQueueMethod:l?.taskQueueMethod===void 0?Ft:l.taskQueueMethod,featureFlags:{...l?.featureFlags}},this.enableDualActionCreate=l?.featureFlags?.enableDualActionCreate??!1,this.enableDualActionCreate&&this.logger.warn("Dual action create is enabled."),this.defaultDrivesManager=new ro(this,this.defaultDrivesManagerDelegate,l),this.initializePromise=this._initialize()}get listeners(){return this.listenerManager}initialize(){return this.initializePromise}async _initialize(){await this.listenerManager.initialize(this.handleListenerError.bind(this)),await this.queueManager.init(this.queueDelegate,r=>{this.logger.error("Error initializing queue manager",r)});try{await this.defaultDrivesManager.removeOldremoteDrives()}catch(r){this.logger.error(r)}const e=[],t=await this.getDrives();for(const r of t)await this._initializeDrive(r).catch(n=>{this.logger.error(`Error initializing drive ${r}`,n),e.push(n)});return this.options.defaultDrives.loadOnInit!==!1&&await this.defaultDrivesManager.initializeDefaultRemoteDrives(),e.length===0?null:e}setDocumentModelModules(e){this.documentModelModules=[...e],this.synchronizationManager.setDocumentModelModules([...e]),this.eventEmitter.emit("documentModelModules",[...e])}initializeDefaultRemoteDrives(){return this.defaultDrivesManager.initializeDefaultRemoteDrives()}getDefaultRemoteDrives(){return this.defaultDrivesManager.getDefaultRemoteDrives()}setDefaultDriveAccessLevel(e,t){return this.defaultDrivesManager.setDefaultDriveAccessLevel(e,t)}setAllDefaultDrivesAccessLevel(e){return this.defaultDrivesManager.setAllDefaultDrivesAccessLevel(e)}getOperationSource(e){return e.type==="local"?"push":"pull"}handleListenerError(e,t,r){this.logger.error(`Listener ${r.listener.label??r.listener.listenerId} error:`,e);const n=e instanceof ie?e.status:"ERROR";this.synchronizationManager.updateSyncStatus(t,{push:n},e)}shouldSyncRemoteDrive(e){return e.state.local.availableOffline&&e.state.local.triggers.length>0}async startSyncRemoteDrive(e){let t=this.triggerMap.get(e);const r=await this.synchronizationManager.getSynchronizationUnitsIds(e),n=await this.getDrive(e);for(const s of n.state.local.triggers)if(!t?.get(s.id)){t||(t=new Map),this.synchronizationManager.updateSyncStatus(e,{pull:"SYNCING"});for(const o of r)this.synchronizationManager.updateSyncStatus(o,{pull:"SYNCING"});if(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(m=>m.status!=="SUCCESS").length<1&&this.synchronizationManager.updateSyncStatus(e,{pull:"SUCCESS"});for(const m of d){const{documentId:f,scope:b,branch:w,status:y,error:I}=m;this.synchronizationManager.updateSyncStatus({documentId:f,scope:b,branch:w},{pull:y},I)}if(o){o=!1,(await this.synchronizationManager.getSynchronizationUnitsIds(e)).filter(w=>!d.find(y=>y.documentId===w.documentId&&y.scope===w.scope&&y.branch===w.branch)).forEach(w=>{this.synchronizationManager.updateSyncStatus(w,{pull:"SUCCESS"})});const b=n.state.local.listeners.find(w=>s.data.url===w.callInfo?.data);if(b)for(const w of d){const{documentId:y,scope:I,branch:_}=w;this.listenerManager.updateListenerRevision(b.listenerId,e,{documentId:y,scope:I,branch:_},w.revision).catch(this.logger.error)}}},void 0,this.listeners);t.set(s.id,a),this.triggerMap.set(e,t)}}}async stopSyncRemoteDrive(e){this.triggerMap.get(e)?.forEach(n=>n()),this.synchronizationManager.updateSyncStatus(e,null);const r=await this.synchronizationManager.getSynchronizationUnitsIds(e);for(const n of r)this.synchronizationManager.updateSyncStatus(n,null);return this.triggerMap.delete(e)}async _initializeDrive(e){const t=await this.getDrive(e);this.logger.verbose(`[SYNC DEBUG] Initializing drive ${e} with slug "${t.header.slug}"`),await this.synchronizationManager.initializeDriveSyncStatus(e,t),this.shouldSyncRemoteDrive(t)&&(this.logger.verbose(`[SYNC DEBUG] Starting sync for remote drive ${e}`),await this.startSyncRemoteDrive(e)),this.logger.verbose(`[SYNC DEBUG] Processing ${t.state.local.listeners.length} listeners for drive ${e}`);for(const r of t.state.local.listeners)if(r.callInfo?.transmitterType==="SwitchboardPush"){this.logger.verbose(`[SYNC DEBUG] Setting up SwitchboardPush listener ${r.listenerId} for drive ${e}`);const n=new pn(r.callInfo.data??"",this.listeners);this.logger.verbose(`[SYNC DEBUG] Created SwitchboardPush transmitter with URL: ${r.callInfo.data||"none"}`),await this.listenerManager.setListener(e,{block:r.block,driveId:t.header.id,filter:{branch:r.filter.branch??[],documentId:r.filter.documentId??[],documentType:r.filter.documentType??[],scope:r.filter.scope??[]},listenerId:r.listenerId,callInfo:r.callInfo,system:r.system,label:r.label??"",transmitter:n}).then(()=>{this.logger.verbose(`[SYNC DEBUG] Successfully set up listener ${r.listenerId} for drive ${e}`)})}else if(r.callInfo?.transmitterType==="PullResponder"){this.logger.verbose(`[SYNC DEBUG] Setting up PullResponder listener ${r.listenerId} for drive ${e}`);const n={driveId:e,listenerId:r.listenerId,block:!1,filter:r.filter,system:!1,label:`PullResponder #${r.listenerId}`,callInfo:{data:"",name:"PullResponder",transmitterType:"PullResponder"}},s=new 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}=Bt(),n=dn({global:{...r,name:e.global.name??r.name,icon:e.global.icon??r.icon},local:{availableOffline:e.local?.availableOffline??!1,sharingType:e.local?.sharingType??"public",listeners:e.local?.listeners??[],triggers:e.local?.triggers??[]}});e.id&&e.id.length>0&&(n.header.id=e.id),e.slug&&e.slug.length>0&&(n.header.slug=e.slug),e.global.name&&(n.header.name=e.global.name);const s=e.preferredEditor||t;return s&&(n.header.meta={preferredEditor:s}),await this.documentStorage.create(n),e.slug&&e.slug.length>0&&await this.cache.deleteDriveBySlug(e.slug),await this._initializeDrive(n.header.id),this.eventEmitter.emit("driveAdded",n),n}async addRemoteDrive(e,t){await this.generateJwtHandler?.(e);const{id:r,name:n,slug:s,icon:o,meta:a}=t.expectedDriveInfo||await Be(e,this),{pullFilter:d,pullInterval:l,availableOffline:m,sharingType:f,listeners:b,triggers:w}=t,y=await 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:[...w,y],listeners:b,availableOffline:m,sharingType:f}},a?.preferredEditor)}async deleteDrive(e){const t=await Promise.allSettled([this.stopSyncRemoteDrive(e),this.listenerManager.removeDrive(e),this.cache.deleteDrive(e),this.documentStorage.delete(e)]);this.eventEmitter.emit("driveDeleted",e),t.forEach(r=>{if(r.status==="rejected")throw r.reason})}async getDrives(){const e=[];let t;do{const{documents:r,nextCursor:n}=await this.documentStorage.findByType("powerhouse/document-drive",100,t);e.push(...r),t=n}while(t);return e}async getDrivesSlugs(){const e=await this.getDrives();return this.documentStorage.resolveSlugs(e)}async getDrive(e,t){let r;try{const o=await this.cache.getDrive(e);if(o&&ve(o)&&(r=o,Nt(r,t?.revisions)))return r}catch(o){this.logger.error("Error getting drive from cache",o)}const n=r??await this.documentStorage.get(e),s=this._buildDocument(n,t);if(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&&Nt(r,t?.revisions))return r}catch(o){this.logger.error("Error getting document from cache",o)}const n=r??await this.documentStorage.get(e),s=this._buildDocument(n,t);return t?.revisions||this.cache.setDocument(e,s).catch(this.logger.error),s}getDocuments(e){return this.documentStorage.getChildren(e)}async addChild(e,t){try{await this.documentStorage.addChild(e,t)}catch(r){throw this.logger.error("Error adding child document",r),r}}async removeChild(e,t){try{const r=await this.synchronizationManager.getSynchronizationUnitsIds(e,[t]);await this.listenerManager.removeSyncUnits(e,r)}catch(r){this.logger.warn("Error removing sync units of child",r)}try{await this.documentStorage.removeChild(e,t)}catch(r){throw this.logger.error("Error adding child document",r),r}}async createDocument(e,t,r){return this.enableDualActionCreate?this.createDocumentDualAction(e,t,r):this.createDocumentLegacy(e,t,r)}async createDocumentLegacy(e,t,r){const{documentType:n,document:s}=Ct(e);let o;if(s){if("documentType"in e&&n!==s.header.documentType)throw new Error(`Provided document is not ${n}`);o=this._buildDocument(s).state}const a=s??this.getDocumentModelModule(n).utils.createDocument(o);let d;if("id"in e&&e.id)s?(d=a.header,a.header.id=e.id,this.logger.warn("Assigning an id to a document is deprecated. Use the header field instead.")):(this.logger.warn("Creating a document with an id is deprecated. Use the header field instead."),d=Le(e.id,n));else if("header"in e)await He(e.header),d=e.header;else if(s?.header){if(!s.header.id)throw new Error("Document header id is required");if(!s.header.documentType)throw new Error("Document header documentType is required");if(!s.header.createdAtUtcIso)throw new Error("Document header createdAtUtcIso is required");s.header.sig.nonce?await He(s.header):this.logger.warn("Creating a document with an unsigned id is deprecated. Use createSignedHeaderForSigner."),d=s.header}else d=Le(void 0,n);r&&(d.meta={...d.meta,...r});const l={header:d,operations:{global:[],local:[]},initialState:a.initialState,clipboard:[],state:o??a.state};await this.documentStorage.create(l);const m=Object.values(a.operations).flat();m.length&&(ve(a)?await this.legacyStorage.addDriveOperations(d.id,m,a):await this.legacyStorage.addDocumentOperations(d.id,m,a));const f=await this.getDocument(l.header.id);return this.eventEmitter.emit("documentAdded",f),f}async createDocumentDualAction(e,t,r){const{documentType:n,document:s}=Ct(e);let o;if(s){if("documentType"in e&&n!==s.header.documentType)throw new Error(`Provided document is not ${n}`);o=this._buildDocument(s).state}const a=s??this.getDocumentModelModule(n).utils.createDocument(o);let d,l=!1;if("id"in e&&e.id)s?(d=a.header,a.header.id=e.id,this.logger.warn("Assigning an id to a document is deprecated. Use the header field instead.")):(this.logger.warn("Creating a document with an id is deprecated. Use the header field instead."),d=Le(e.id,n));else if("header"in e)await He(e.header),l=!0,d=e.header;else if(s?.header){if(!s.header.id)throw new Error("Document header id is required");if(!s.header.documentType)throw new Error("Document header documentType is required");if(!s.header.createdAtUtcIso)throw new Error("Document header createdAtUtcIso is required");s.header.sig.nonce?(await He(s.header),l=!0):this.logger.warn("Creating a document with an unsigned id is deprecated. Use createSignedHeaderForSigner."),d=s.header}else d=Le(void 0,n),l=!1;r&&(d.meta={...d.meta,...r});const m="0.1.0",f=o??a.state,b=Object.values(a.operations).flat(),w=b.length===0;let y=[];if(w){const U=new Date().toISOString(),F=l?{signature:d.id,publicKey:d.sig.publicKey,nonce:d.sig.nonce,createdAtUtcIso:d.createdAtUtcIso,documentType:d.documentType}:void 0,E={model:n,version:"0.0.0",documentId:d.id,signing:F},L={id:`${d.id}-create`,type:"CREATE_DOCUMENT",timestampUtcMs:U,input:E,scope:"document"},P={model:n,fromVersion:"0.0.0",toVersion:m,documentId:d.id,initialState:f},j={id:`${d.id}-upgrade`,type:"UPGRADE_DOCUMENT",timestampUtcMs:U,input:P,scope:"document"},V={state:Lt()},Z=ar(V,"document"),se=ar({state:f},"document");y=[{id:`${d.id}-create`,index:0,skip:0,hash:Z,timestampUtcMs:U,action:L},{id:`${d.id}-upgrade`,index:1,skip:0,hash:se,timestampUtcMs:U,action:j}]}else y=b;const I=cr(y);I.header||(I.header=[]),I.document||(I.document=[]),I.global||(I.global=[]),I.local||(I.local=[]);const N={header:d,operations:I,initialState:f,clipboard:[],state:f};await this.documentStorage.create(N);const C=await this.getDocument(N.header.id,{checkHashes:!0});return this.eventEmitter.emit("documentAdded",C),C}async deleteDocument(e){try{const t=await this.synchronizationManager.getSynchronizationUnitsIds(void 0,[e]);for(const n of t)this.synchronizationManager.updateSyncStatus(n,null);const r=await this.documentStorage.getParents(e);for(const n of r)this.listenerManager.removeSyncUnits(n,t).catch(this.logger.warn)}catch(t){this.logger.warn("Error deleting document",t)}await Promise.allSettled([this.cache.deleteDocument(e).catch(this.logger.warn),this.documentStorage.delete(e).catch(this.logger.warn)]),this.eventEmitter.emit("documentDeleted",e)}async _processOperations(e,t,r){const n=[],s=[],o=await this._addDocumentResultingStage(t,e);let a=this._buildDocument(o),d;const l=cr(r);for(const m of Object.keys(l)){const f=t.operations[m]||[],b=vs(l[m]||[],f);if(b.length<1)continue;const w=Dt(Ge(f)),[y,I]=ws(w,b),N=(I.length<1?y:bs(w,y,Is)).filter(C=>w.length<1||Ds(w[w.length-1],C));for(const C of N){let U=!1;if(I.length>0){const F=r.find(E=>E.hash===C.hash);U=!F||F.index!==C.index||F.skip!==C.skip}try{const F=this.options.taskQueueMethod,E=()=>this._performOperation(e,a,C,U),L=await(F?$t(E,F):E());a=L.document,s.push(...L.signals),n.push(L.operation)}catch(F){d=F instanceof ie?F:new ie("ERROR",C,F.message,F.cause);break}}}return{document:a,operationsApplied:n,signals:s,error:d}}async _addDocumentResultingStage(e,t,r){const n=r?.revisions!==void 0?Mr(e.operations,r.revisions):e.operations,s=Ve(n);for(const o of Object.keys(s)){const a=s[o];if(!a)continue;const d=a.at(-1);d&&!d.resultingState&&(d.resultingState=await(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)&&Nt(e,t?.revisions))return e;const r=this.getDocumentModelModule(e.header.documentType),n=t?.revisions!==void 0?Mr(e.operations,t.revisions):e.operations,s=Ve(n),o=Object.keys(s),a=new Set([...o,"global","local"]),d={},l={};for(const w of a)d[w]=[],l[w]=[];for(const[w,y]of Object.entries(s))if(y)for(const I of y)if(I.action.type==="CREATE_DOCUMENT"||I.action.type==="UPGRADE_DOCUMENT"){const _=d[w];_&&_.push(I)}else{const _=l[w];_&&_.push(I)}const m=Cr(e.initialState,l,r.reducer,void 0,e.header,void 0,{...t,checkHashes:t?.checkHashes??!0,reuseOperationResultingState:t?.checkHashes??!0}),f=new Set([...Object.keys(s),...Object.keys(d),...Object.keys(m.operations)]),b={};for(const w of f)b[w]=[...d[w]||[],...m.operations[w]||[]];return{...m,operations:b}}async _performOperation(e,t,r,n=!1){const s=this.getDocumentModelModule(t.header.documentType),o=[];let a=t;const d=r.action.scope,l=t.operations[d]||[],b=Ve({...t.operations,[d]:Ss(l,r)})[d]?.at(-1);b&&!b.resultingState&&(b.resultingState=await(ve(t)?this.legacyStorage.getOperationResultingState?.(e,b.index,b.action.scope,"main"):this.legacyStorage.getDriveOperationResultingState?.(e,b.index,b.action.scope,"main")));const w=a.operations[d]||[],y=[];if(a=s.reducer(a,r.action,C=>{let U;switch(C.type){case"CREATE_CHILD_DOCUMENT":U=()=>this.addChild(e,C.input.id);break;case"DELETE_CHILD_DOCUMENT":U=()=>this.removeChild(e,C.input.id);break;case"COPY_CHILD_DOCUMENT":U=()=>this.addChild(e,C.input.newId);break}U&&y.push(()=>U().then(F=>({signal:C,result:F})))},{skip:r.skip,reuseOperationResultingState:!0,replayOptions:{operation:r}}),r.action.type==="NOOP"&&r.skip>0&&a.clipboard.length===0){const C=a.operations[d]||[],U=Dt(Ge(C)),F=Dt(Ge(w)),E=Es(F,U);a={...a,clipboard:Ge(E.filter(L=>L.action.type!=="NOOP")).reverse()}}const I=a.operations[r.action.scope];if(!I)throw new ie("ERROR",r,`No operations found for scope: ${r.action.scope}`);const N=I.filter(C=>C.index==r.index&&C.skip==r.skip).at(0);if(!N)throw new ie("ERROR",r,`Operation with index ${r.index}:${r.skip} was not applied.`);if(!N.error&&N.hash!==r.hash&&!n)throw this.logger.warn(JSON.stringify(N,null,2)),new hi(r,N);for(const C of y){const U=await C();o.push(U)}return{document:a,signals:o,operation:N}}addOperation(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this.addOperations(s,[o],a)}async _addOperations(e,t){if(this.legacyStorage.addDocumentOperationsWithTransaction)await this.legacyStorage.addDocumentOperationsWithTransaction(e,t);else{const r=await this.documentStorage.get(e),n=await t(r);n.operations.length>0&&await this.legacyStorage.addDocumentOperations(e,n.operations,n.document)}}async queueDocument(e,t){const{id:r,documentType:n,document:s}=Ct(e);if(!r)throw new Error("Document id is required",{cause:e});if(!n)throw new Error("Document type is required",{cause:e});if(await this.documentStorage.exists(r))throw new ke(r);let a;const d=new Promise((l,m)=>{const f=this.queueManager.on("jobCompleted",(w,y)=>{w.jobId===a&&(f(),b(),l(y))}),b=this.queueManager.on("jobFailed",(w,y)=>{w.jobId===a&&(f(),b(),m(y))})});try{a=await this.queueManager.addJob({documentId:r,documentType:n,initialState:s?.state,header:s?.header,options:t})}catch(l){throw this.logger.error("Error adding job",l),l}return d}queueOperation(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueOperations(s,[o],a)}async resultIfExistingOperations(e,t){try{const r=await this.getDocument(e);return t.find(s=>{if(!s.id)return!0;const o=r.operations[s.action.scope];return o?!o.find(a=>a.id===s.id&&a.index===s.index&&a.action.type===s.action.type&&a.hash===s.hash):!0})?void 0:{status:"SUCCESS",document:r,operations:t,signals:[]}}catch(r){r.message.includes(`Document with id ${e} not found`)||console.error(r);return}}queueOperations(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueOperations(s,o,a)}async _queueOperations(e,t,r){const n=await this.resultIfExistingOperations(e,t);if(n)return n;let s;const o=new Promise((a,d)=>{const l=this.queueManager.on("jobCompleted",(f,b)=>{f.jobId===s&&(l(),m(),a(b))}),m=this.queueManager.on("jobFailed",(f,b)=>{f.jobId===s&&(l(),m(),d(b))})});try{s=await this.queueManager.addJob({documentId:e,operations:t,options:r})}catch(a){throw this.logger.error("Error adding job",a),a}return o}queueAction(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueActions(s,[o],a)}queueActions(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueActions(s,o,a)}async _queueActions(e,t,r){try{const n=await this.queueManager.addJob({documentId:e,actions:t,options:r});return await new Promise((s,o)=>{const a=this.queueManager.on("jobCompleted",(l,m)=>{l.jobId===n&&(a(),d(),s(m))}),d=this.queueManager.on("jobFailed",(l,m)=>{l.jobId===n&&(a(),d(),o(m))})})}catch(n){throw this.logger.error("Error adding job",n),n}}async queueDriveAction(e,t,r){return this.queueDriveActions(e,[t],r)}async queueDriveActions(e,t,r){try{const n=await this.queueManager.addJob({documentId:e,actions:t,options:r});return await new Promise((s,o)=>{const a=this.queueManager.on("jobCompleted",(l,m)=>{l.jobId===n&&(a(),d(),s(m))}),d=this.queueManager.on("jobFailed",(l,m)=>{l.jobId===n&&(a(),d(),o(m))})})}catch(n){throw this.logger.error("Error adding drive job",n),n}}addOperations(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueOperations(s,o,a)}async processOperations(e,t,r){const n=await this.resultIfExistingOperations(e,t);if(n)return n;let s;const o=[],a=[];let d;try{await this._addOperations(e,async w=>{const y=await this._processOperations(e,w,t);if(!y.document)throw this.logger.error("Invalid document"),y.error??new Error("Invalid document");return s=y.document,d=y.error,a.push(...y.signals),o.push(...y.operationsApplied),{operations:y.operationsApplied,document:y.document}});const l=new Array;if(s){this.cache.setDocument(e,s).catch(this.logger.error);for(const w of o){const y={documentId:e,documentType:s.header.documentType,scope:w.action.scope,branch:"main",revision:w.index+1,lastUpdated:w.timestampUtcMs};l.some(_=>_.documentId===y.documentId&&_.scope===y.scope&&_.branch===y.branch)||l.push(y)}}const f=o.find(w=>!t.find(y=>y.id===w.id&&y.index===w.index&&y.skip===w.skip&&y.hash===w.hash))?{type:"local"}:r?.source??{type:"local"},b=this.getOperationSource(f);if(l.length&&this.listenerManager.updateSynchronizationRevisions(l,f,()=>{this.synchronizationManager.updateSyncStatus(e,{[b]:"SYNCING"});for(const w of l)this.synchronizationManager.updateSyncStatus(w,{[b]:"SYNCING"})},this.handleListenerError.bind(this),r?.forceSync??f.type==="local").then(w=>{w.length&&this.synchronizationManager.updateSyncStatus(e,{[b]:"SUCCESS"});for(const y of l)this.synchronizationManager.updateSyncStatus(y,{[b]:"SUCCESS"})}).catch(w=>{this.logger.error("Non handled error updating sync revision",w),this.synchronizationManager.updateSyncStatus(e,{[b]:"ERROR"},w);for(const y of l)this.synchronizationManager.updateSyncStatus(y,{[b]:"ERROR"},w)}),d)throw d;return this.eventEmitter.emit("documentOperationsAdded",e,t),this.eventEmitter.emit("operationsAdded",e,t),{status:"SUCCESS",document:s,operations:o,signals:a}}catch(l){const m=l instanceof ie?l:new ie("ERROR",void 0,l.message,l.cause);return{status:m.status,error:m,document:s,operations:o,signals:a}}}addDriveOperation(e,t,r){return this.addDriveOperations(e,[t],r)}async _addDriveOperations(e,t){if(this.legacyStorage.addDriveOperationsWithTransaction)return this.legacyStorage.addDriveOperationsWithTransaction(e,t);{const r=await this.documentStorage.get(e),n=await t(r);return n.operations.length>0&&await this.legacyStorage.addDriveOperations(e,n.operations,n.document),n}}queueDriveOperation(e,t,r){return this.queueDriveOperations(e,[t],r)}async resultIfExistingDriveOperations(e,t){try{const r=await this.getDrive(e);return t.find(s=>{if(!s.id)return!0;const o=r.operations[s.action.scope];return o?!o.find(a=>a.id===s.id&&a.index===s.index&&a.action.type===s.action.type&&a.hash===s.hash):!0})?void 0:{status:"SUCCESS",document:r,operations:t,signals:[]}}catch(r){console.error(r);return}}async queueDriveOperations(e,t,r){const n=await this.resultIfExistingDriveOperations(e,t);if(n)return n;try{const s=await this.queueManager.addJob({documentId:e,operations:t,options:r});return await new Promise((o,a)=>{const d=this.queueManager.on("jobCompleted",(m,f)=>{m.jobId===s&&(d(),l(),o(f))}),l=this.queueManager.on("jobFailed",(m,f)=>{m.jobId===s&&(d(),l(),a(f))})})}catch(s){throw this.logger.error("Error adding drive job",s),s}}async addDriveOperations(e,t,r){return this.queueDriveOperations(e,t,r)}async processDriveOperations(e,t,r){let n;const s=[],o=[];let a;const d=await this.resultIfExistingDriveOperations(e,t);if(d)return d;try{if(await this._addDriveOperations(e,async m=>{const f=await this._processOperations(e,m,t.slice());return n=f.document,s.push(...f.operationsApplied),o.push(...f.signals),a=f.error,{operations:f.operationsApplied,document:f.document}}),!n||!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(m=>m.action.scope==="global").slice().pop();if(l){const f=s.find(w=>!t.find(y=>y.id===w.id&&y.index===w.index&&y.skip===w.skip&&y.hash===w.hash))?{type:"local"}:r?.source??{type:"local"},b=this.getOperationSource(f);this.listenerManager.updateSynchronizationRevisions([{documentId:e,documentType:n.header.documentType,scope:"global",branch:"main",lastUpdated:l.timestampUtcMs,revision:l.index}],f,()=>{this.synchronizationManager.updateSyncStatus(e,{[b]:"SYNCING"})},this.handleListenerError.bind(this),r?.forceSync??f.type==="local").then(w=>{w.length&&this.synchronizationManager.updateSyncStatus(e,{[b]:"SUCCESS"})}).catch(w=>{this.logger.error("Non handled error updating sync revision",w),this.synchronizationManager.updateSyncStatus(e,{[b]:"ERROR"},w)})}if(this.shouldSyncRemoteDrive(n)?this.startSyncRemoteDrive(e).catch(this.logger.error):this.stopSyncRemoteDrive(e).catch(this.logger.error),a)throw a;return this.eventEmitter.emit("driveOperationsAdded",e,t),this.eventEmitter.emit("operationsAdded",e,t),{status:"SUCCESS",document:n,operations:s,signals:o}}catch(l){const m=l instanceof ie?l:new ie("ERROR",void 0,l.message,l);return{status:m.status,error:m,document:n,operations:s,signals:o}}}_buildOperations(e,t){const r=[],{reducer:n}=this.getDocumentModelModule(e.header.documentType);for(const s of t){e=n(e,s);const o=e.operations[s.scope];if(!o)throw new Error(`No operations found for scope: ${s.scope}`);const a=o.slice().pop();if(!a)throw new Error("Error creating operations");r.push(a)}return r}addAction(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._addAction(s,o,a)}async _addAction(e,t,r){return this.addActions(e,[t],r)}addActions(e,t,r,n){let s,o,a;return typeof t=="string"?(s=t,o=r,a=n):(s=e,o=t,a=r),this._queueActions(s,o,a)}async processActions(e,t,r){const n=await this.getDocument(e),s=this._buildOperations(n,t);return this.processOperations(e,s,r)}async addDriveAction(e,t,r){return"synchronizationUnits"in t.input?this._legacyAddFileAction(e,t,r):this.addDriveActions(e,[t],r)}async _legacyAddFileAction(e,t,r){const n=this.getDocumentModelModule(t.input.documentType).utils.createDocument(t.input.document?.state||void 0);n.header.id=t.input.id,n.header.name=t.input.name,n.header.documentType=t.input.documentType,await this.queueDocument({document:n},{source:r?.source||{type:"local"}});const s={...t,input:{id:t.input.id,documentType:n.header.documentType,name:t.input.name,parentFolder:t.input.parentFolder}};return await this.addAction(e,s,r)}async addDriveActions(e,t,r){return this.queueDriveActions(e,t,r)}async processDriveActions(e,t,r){const n=await this.getDrive(e),s=this._buildOperations(n,t);return this.processDriveOperations(e,s,r)}async detachDrive(e){const t=await this.getDrive(e),r=t.state.local.listeners||[],n=t.state.local.triggers||[];for(const s of r)await this.addDriveAction(e,en({listenerId:s.listenerId}));for(const s of n)await this.addDriveAction(e,tn({triggerId:s.id}));await this.addDriveAction(e,Zr({type:"LOCAL"}))}getSyncStatus(e,t,r){return this.synchronizationManager.getSyncStatus(e,t,r)}on(e,t){return this.eventEmitter.on(e,t)}emit(e,...t){return this.eventEmitter.emit(e,...t)}updateSyncStatus(e,t,r){this.synchronizationManager.updateSyncStatus(e,t,r)}initializeDriveSyncStatus(e,t){return this.synchronizationManager.initializeDriveSyncStatus(e,t)}getCombinedSyncUnitStatus(e){return this.synchronizationManager.getCombinedSyncUnitStatus(e)}async saveStrand(e,t){const r=!await this.documentStorage.exists(e.documentId);let n;r&&(n=await this.queueDocument({id:e.documentId,documentType:e.documentType}));const s=e.operations.map(o=>({...o,action:{id:o.actionId,timestampUtcMs:o.timestampUtcMs,type:o.type,input:o.input,context:o.context,scope:e.scope},scope:e.scope,branch:e.branch}));if((!r||n?.status==="SUCCESS")&&s.length)try{n=await this.queueOperations(e.documentId,s,{source:t})}catch(o){throw this.logger.error("Error queueing operations",o),o}if(!n)return this.logger.debug(`Document ${e.documentId} already exists`),{status:"SUCCESS",document:await this.getDocument(e.documentId),operations:[],signals:[]};if(n.status==="ERROR"){const o=this.getOperationSource(t);this.synchronizationManager.updateSyncStatus({documentId:e.documentId||e.driveId,scope:e.scope,branch:e.branch},{[o]:n.status},n.error)}return this.eventEmitter.emit("strandUpdate",e),n}setGenerateJwtHandler(e){this.generateJwtHandler=e,this.listenerManager.setGenerateJwtHandler(e)}removeJwtHandler(){this.generateJwtHandler=void 0,this.listenerManager.removeJwtHandler()}}const po=eo(go);class at extends Error{constructor(e){super(e||"Aborted"),this.name="AbortError"}}class mo{logger=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(!tt(t))throw new et(t);if(this.documents[t])throw new ke(t);const r=e.header.slug?.length>0?e.header.slug:t;if(!nn(r))throw new rn(r);if(r&&this.slugToDocumentId[r])throw new ke(t,Fe.SLUG);return e.header.slug=r,this.documents[t]=e,r&&(this.slugToDocumentId[r]=t),e.header.documentType==="powerhouse/document-drive"&&this.updateDriveManifest(t,{documentIds:new Set}),Promise.resolve()}get(e){const t=this.documents[e];return t?Promise.resolve(t):Promise.reject(new we(e))}getBySlug(e){const t=this.slugToDocumentId[e];return t?this.get(t):Promise.reject(new we(e))}async findByType(e,t=100,r){const n=Object.entries(this.documents).filter(([d,l])=>l.header.documentType===e).map(([d,l])=>({id:d,document:l}));n.sort((d,l)=>{const m=new Date(d.document.header.createdAtUtcIso),f=new Date(l.document.header.createdAtUtcIso);if(m.getTime()===f.getTime()){const b=d.id,w=l.id;return b.localeCompare(w)}return m.getTime()-f.getTime()});let s=0;if(r){const d=n.findIndex(({id:l})=>l===r);d!==-1&&(s=d)}const o=Math.min(s+t,n.length);let a;return o<n.length&&(a=n[o].id),{documents:n.slice(s,o).map(({id:d})=>d),nextCursor:a}}async delete(e){const t=this.documents[e];if(t){const n=t.header.slug?.length>0?t.header.slug:e;n&&this.slugToDocumentId[n]===e&&delete this.slugToDocumentId[n]}const r=await this.getParents(e);for(const n of r)await this.removeChild(n,e);return delete this.driveManifests[e],this.documents[e]?(delete this.documents[e],Promise.resolve(!0)):Promise.resolve(!1)}async addChild(e,t){if(e===t)return Promise.reject(new Error("Cannot associate a document with itself"));if((await this.getChildren(t)).includes(e))return Promise.reject(new Error("Cannot associate a document with its child"));const n=this.getManifest(e);return n.documentIds.add(t),this.updateDriveManifest(e,n),Promise.resolve()}async removeChild(e,t){const r=this.getManifest(e);return r.documentIds.delete(t)?(this.updateDriveManifest(e,r),Promise.resolve(!0)):Promise.resolve(!1)}async getChildren(e){return[...this.getManifest(e).documentIds]}async getParents(e){const t=[];for(const[r,n]of Object.entries(this.driveManifests))n.documentIds.has(e)&&t.push(r);return t}async clear(){this.documents={},this.driveManifests={},this.slugToDocumentId={}}async addDocumentOperations(e,t,r){const n=await this.get(e);if(!r)return Promise.reject(new we(e));const s=st(n.operations,t),o={};for(const[a,d]of Object.entries(s))o[a]=Ie(d);this.documents[e]={...n,state:r.state,initialState:r.initialState,header:{...n.header,...r.header,revision:o},operations:s,clipboard:r.clipboard}}async addDriveOperations(e,t,r){const n=await this.get(e),s=st(n.operations,t),o={};for(const[a,d]of Object.entries(s))o[a]=Ie(d);this.documents[e]={...n,state:r.state,initialState:r.initialState,header:{...n.header,...r.header,revision:o},operations:s,clipboard:r.clipboard}}async getSynchronizationUnitsRevision(e){return(await Promise.allSettled(e.map(async r=>{try{const n=await this.get(r.documentId);if(!n||!Object.keys(n.state).includes(r.scope))return;const s=n.operations[r.scope];return s?{documentId:r.documentId,documentType:r.documentType,scope:r.scope,branch:r.branch,lastUpdated:s.at(-1)?.timestampUtcMs??n.header.createdAtUtcIso,revision:s.length>0?Ie(s):0}:void 0}catch(n){this.logger.error("Error getting synchronization units revision",n);return}}))).reduce((r,n)=>(n.status==="fulfilled"&&n.value!==void 0&&r.push(n.value),r),[])}async findStorageUnitsBy(e,t,r){const n=[],{parentId:s,documentId:o,documentModelType:a,scope:d}=sn(e);let l;if(s){const w=new Set;for(const y of s)(await this.getChildren(y)).forEach(_=>w.add(_));l=on(s,w)}else l=new Set(Object.keys(this.documents));l=o?an(o,l):l;for(const w of l){const y=this.documents[w];if(y&&!(a&&!a.has(y.header.documentType)))for(const[I]of Object.entries(y.state))d&&!d.has(I)||n.push({documentId:w,documentModelType:y.header.documentType,scope:I,branch:"main"})}let m=0;if(r){const w=n.findIndex(y=>y.documentId===r);w!==-1&&(m=w)}const f=Math.min(m+t,n.length),b=f<n.length?n[f].documentId:void 0;return{units:n.slice(m,f),nextCursor:b}}getManifest(e){return this.driveManifests[e]||(this.driveManifests[e]={documentIds:new Set}),this.driveManifests[e]}updateDriveManifest(e,t){this.driveManifests[e]=t}}class yo{emitter=hn();emit(e,...t){return this.emitter.emit(e,...t)}on(e,t){return this.emitter.on(e,t)}}class X{internalMap=new Map;static keySeparator="|";static escape(e){return e.replace(/\|/g,"\\|")}static unescape(e){return e.replace(/\\\|/g,"|")}static buildKey(e){return`${X.escape(e.documentId)}${X.keySeparator}${X.escape(e.scope)}${X.keySeparator}${X.escape(e.branch)}`}static parseKey(e){const t=e.split(new RegExp("(?<!\\\\)\\|")).map(o=>X.unescape(o)),[r,n,s]=t;return{documentId:r,scope:n,branch:s}}set(e,t){return this.internalMap.set(X.buildKey(e),t),this}get(e){return this.internalMap.get(X.buildKey(e))}has(e){return this.internalMap.has(X.buildKey(e))}delete(e){return this.internalMap.delete(X.buildKey(e))}clear(){this.internalMap.clear()}get size(){return this.internalMap.size}keys(e){const t=this.internalMap.keys();return{[Symbol.iterator](){return this},next(){for(;;){const r=t.next();if(r.done)return{done:!0,value:void 0};const n=r.value,s=X.parseKey(n);if(!(e&&(s.documentId!==e.documentId||e.scope!==void 0&&s.scope!==e.scope)))return{done:!1,value:s}}}}}values(e){const t=this.internalMap.entries();return{[Symbol.iterator](){return this},next(){for(;;){const r=t.next();if(r.done)return{done:!0,value:void 0};const[n,s]=r.value,o=X.parseKey(n);if(!(e&&(o.documentId!==e.documentId||e.scope!==void 0&&o.scope!==e.scope)))return{done:!1,value:s}}}}}entries(e){const t=this.internalMap.entries();return{[Symbol.iterator](){return this},next(){for(;;){const r=t.next();if(r.done)return{done:!0,value:void 0};const[n,s]=r.value,o=X.parseKey(n);if(!(e&&(o.documentId!==e.documentId||e.scope!==void 0&&o.scope!==e.scope)))return{done:!1,value:[o,s]}}}}}[Symbol.iterator](){return this.entries()}forEach(e,t){for(const[r,n]of this.entries())e.call(t,n,r,this)}deleteByDocumentId(e){for(const t of this.internalMap.keys())t.startsWith(e+X.keySeparator)&&this.internalMap.delete(t)}deleteByDocumentIdAndScope(e,t){const r=`${e}${X.keySeparator}${t}${X.keySeparator}`;for(const n of this.internalMap.keys())n.startsWith(r)&&this.internalMap.delete(n)}getAllByDocumentId(e){const t=[];for(const[r,n]of this.internalMap.entries())r.startsWith(e+X.keySeparator)&&t.push([X.parseKey(r),n]);return t}getAllByDocumentIdAndScope(e,t){const r=`${e}${X.keySeparator}${t}${X.keySeparator}`,n=[];for(const[s,o]of this.internalMap.entries())s.startsWith(r)&&n.push([X.parseKey(s),o]);return n}}function vo(i,e=250){let t;return(r=!1,...n)=>(t&&clearTimeout(t),new Promise((s,o)=>{r?i(...n).then(s).catch(o):t=setTimeout(()=>{i(...n).then(s).catch(o)},e)}))}class qt{static LISTENER_UPDATE_DELAY=250;logger=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 b=l.syncUnits.get(f);if(!b||b.listenerRev<f.revision){a.push(l.listener);break}}return this.triggerUpdate(s,t,r,n)}async updateListenerRevision(e,t,r,n){const s=this.listenerStateByDriveId.get(t);if(!s)return;const o=s.get(e);if(!o)return;const a=new Date().toISOString();return o.syncUnits.set(r,{listenerRev:n,lastUpdated:a}),Promise.resolve()}triggerUpdate=vo(this._triggerUpdate.bind(this),qt.LISTENER_UPDATE_DELAY);async _triggerUpdate(e,t,r,n=500){if(this.logger.verbose(`_triggerUpdate(source: ${e.type}, maxContinues: ${n})`,this.listenerStateByDriveId),n<0)throw new Error("Maximum retries exhausted.");const s=[];for(const[o,a]of this.listenerStateByDriveId)for(const[d,l]of a){const m=l.listener.transmitter;if(!m?.transmit)continue;const f=await this.getListenerSyncUnits(o,d),b=[];this.logger.verbose("syncUnits",f);const w=f.map(y=>async()=>{const I=l.syncUnits.get(y);if(I&&I.listenerRev>=y.revision){this.logger.verbose(`Abandoning push for sync unit ${JSON.stringify(y)}: already up-to-date (${I.listenerRev} >= ${y.revision})`);return}else this.logger.verbose(`Listener out-of-date for sync unit (${y.scope}, ${y.documentId}): ${I?.listenerRev} < ${y.revision}`);const _=[];if(y.revision>0){try{const N=await this.syncManager.getOperationData(y,{fromRevision:I?.listenerRev});_.push(...N)}catch(N){this.logger.error(N)}if(!_.length){this.logger.verbose(`Abandoning push for ${JSON.stringify(y)}: no operations found`);return}}b.push({driveId:o,documentType:y.documentType,documentId:y.documentId,branch:y.branch,operations:_,scope:y.scope})});if(this.options.sequentialUpdates){this.logger.verbose(`Collecting ${w.length} syncUnit strandUpdates in sequence`);for(const y of w)await y()}else this.logger.verbose(`Collecting ${w.length} syncUnit strandUpdates in parallel`),await Promise.all(w.map(y=>y()));if(b.length==0){this.logger.verbose(`No strandUpdates needed for listener ${d}`);continue}l.pendingTimeout=new Date(new Date().getTime()/1e3+300).toISOString(),l.listenerStatus="PENDING";try{this.logger.verbose(`_triggerUpdate(source: ${e.type}) > transmitter.transmit`);const y=await m.transmit(b,e);this.logger.verbose(`_triggerUpdate(source: ${e.type}) > transmission succeeded`,y),l.pendingTimeout="0",l.listenerStatus="PENDING";const I=new Date().toISOString();let _=!1;for(const N of y){const C=f.find(U=>N.documentId===U.documentId&&N.scope===U.scope&&N.branch===U.branch);if(C){l.syncUnits.set(C,{lastUpdated:I,listenerRev:N.revision});const U=b.find(F=>F.driveId===N.driveId&&F.documentId===N.documentId&&F.scope===N.scope&&F.branch===N.branch);if(U&&U.operations.length>0){const F=U.operations.at(-1)?.index;F!==N.revision?(this.logger.verbose(`Revision still out-of-date for ${U.documentId}:${U.scope}:${U.branch} ${F} <> ${N.revision}`),_=!0):this.logger.verbose(`Revision match for ${U.documentId}:${U.scope}:${U.branch} ${F}`)}}else this.logger.warn(`Received revision for untracked unit for listener ${l.listener.listenerId}`,N)}for(const N of y){const C=N.status==="ERROR";if(N.error?.includes("Missing operations"))_=!0;else if(C)throw new ie(N.status,void 0,N.error,N.error)}if(!_)s.push({listenerId:l.listener.listenerId,listenerRevisions:y});else{const N=await this._triggerUpdate(e,t,r,n-1);s.push(...N)}l.listenerStatus="SUCCESS"}catch(y){r?.(y,o,l),l.listenerStatus=y instanceof ie?y.status:"ERROR"}}return this.logger.verbose(`Returning listener updates (maxContinues: ${n})`,s),s}_checkFilter(e,t){const{branch:r,documentId:n,scope:s,documentType:o}=t;return!!((!e.branch||e.branch.includes(r)||e.branch.includes("*"))&&(!e.documentId||e.documentId.includes(n)||e.documentId.includes("*"))&&(!e.scope||e.scope.includes(s)||e.scope.includes("*"))&&(!e.documentType||e.documentType.includes(o)||e.documentType.includes("*")))}getListenerSyncUnits(e,t){const r=this.listenerStateByDriveId.get(e)?.get(t);if(!r)return[];const n=r.listener.filter;return this.syncManager.getSynchronizationUnits(e,n.documentId??["*"],n.scope??["*"],n.branch??["*"],n.documentType??["*"])}async removeDrive(e){const t=this.listenerStateByDriveId.get(e);if(t){this.listenerStateByDriveId.delete(e);for(const[r,n]of t)try{await n.listener.transmitter?.disconnect?.()}catch(s){this.logger.error(s)}}}async getStrands(e,t,r){this.logger.verbose(`[SYNC DEBUG] ListenerManager.getStrands called for drive: ${e}, listener: ${t}, options: ${JSON.stringify(r||{})}`);let n;try{n=this.getListenerState(e,t),this.logger.verbose(`[SYNC DEBUG] Found listener state for drive: ${e}, listener: ${t}, status: ${n.listenerStatus}`)}catch(o){throw this.logger.error(`[SYNC DEBUG] Failed to find listener state for drive: ${e}, listener: ${t}. Error: ${o}`),o}const s=[];try{const o=await this.getListenerSyncUnits(e,t);this.logger.verbose(`[SYNC DEBUG] Retrieved ${o.length} sync units for drive: ${e}, listener: ${t}`);const a=r?.limit;let d=0;const l=o.map(m=>async()=>{if(a&&d>=a)return;if(m.revision<0){this.logger.verbose(`[SYNC DEBUG] Skipping sync unit with negative revision: ${JSON.stringify(m)}, revision: ${m.revision}`);return}const f=n.syncUnits.get(m);if(f&&f.listenerRev>=m.revision){this.logger.verbose(`[SYNC DEBUG] Skipping sync unit - listener already up to date: ${JSON.stringify(m)}, listenerRev: ${f.listenerRev}, revision: ${m.revision}`);return}const{documentId:b,scope:w,branch:y}=m;let I=[];try{m.revision>0&&(this.logger.verbose(`[SYNC DEBUG] Getting operations for syncUnit: ${JSON.stringify(m)}`),I=await this.syncManager.getOperationData(m,{since:r?.since,fromRevision:r?.fromRevision??f?.listenerRev,limit:a?a-d:void 0})),this.logger.verbose(`[SYNC DEBUG] Retrieved ${I.length} operations for syncUnit: ${JSON.stringify(m)}`),d+=I.length,s.push({driveId:e,documentId:b,documentType:m.documentType,scope:w,branch:y,operations:I}),this.logger.verbose(`[SYNC DEBUG] Added strand with ${I.length} operations for syncUnit: ${JSON.stringify(m)}`)}catch(_){this.logger.error(`Error getting operations for syncUnit: ${JSON.stringify(m)}, error: ${_}`);return}});if(this.options.sequentialUpdates){this.logger.verbose(`[SYNC DEBUG] Processing ${l.length} sync units sequentially`);for(const m of l)await m()}else this.logger.verbose(`[SYNC DEBUG] Processing ${l.length} sync units in parallel`),await Promise.all(l.map(m=>m()))}catch(o){this.logger.error(`Error in getStrands: ${o}`)}return this.logger.verbose(`ListenerManager.getStrands returning ${s.length} strands for drive: ${e}, listener: ${t}`),s}getListenerState(e,t){let r=this.listenerStateByDriveId.get(e);r||(r=new Map,this.listenerStateByDriveId.set(e,r));const n=r.get(t);if(!n)throw new Error("Listener not found");return n}setListenerState(e,t,r){let n=this.listenerStateByDriveId.get(e);n||(n=new Map,this.listenerStateByDriveId.set(e,n)),n.set(t,r)}}class wo{storage;documentStorage;cache;documentModelModules;eventEmitter;syncStatus=new X;logger=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:m}=await this.documentStorage.findStorageUnitsBy(o,100,a);d.push(...l),a=m}while(a);return d.reduce((l,{documentModelType:m,...f})=>f.scope==="local"?l:l.concat([{...f,documentType:m}]),new Array)}async getSynchronizationUnit(e){const{scope:t,branch:r,documentId:n}=e,s=await this.getDocument(n);if(!Object.keys(s.state).includes(t))return;const o=s.operations[t]??[],a=o.at(-1);return{scope:t,branch:r,documentId:n,documentType:s.header.documentType,lastUpdated:a?.timestampUtcMs??s.header.lastModifiedAtUtcIso,revision:Ie(o)}}async getOperationData(e,t){this.logger.verbose(`[SYNC DEBUG] SynchronizationManager.getOperationData called for syncId: ${JSON.stringify(e)}, filter: ${JSON.stringify(t)}`);const r=await this.getDocument(e.documentId);this.logger.verbose(`[SYNC DEBUG] Retrieved document ${r.header.id} with type: ${r.header.documentType}`);const n=r.operations[e.scope]??[];this.logger.verbose(`[SYNC DEBUG] Found ${n.length} total operations in scope ${e.scope}`);const s=n.filter(a=>Object.keys(t).length===0||(t.since===void 0||Ci(t.since,a.timestampUtcMs))&&(t.fromRevision===void 0||a.index>=t.fromRevision));this.logger.verbose(`[SYNC DEBUG] Filtered to ${s.length} operations based on filter criteria`+(t.fromRevision!==void 0?` (fromRevision: ${t.fromRevision})`:""));const o=t.limit?s.slice(0,t.limit):s;if(this.logger.verbose(`[SYNC DEBUG] Returning ${o.length} operations after applying limit`),o.length>0){const a=o[0],d=o[o.length-1];this.logger.verbose(`[SYNC DEBUG] First operation: index=${a.index}, type=${a.action.type}`),this.logger.verbose(`[SYNC DEBUG] Last operation: index=${d.index}, type=${d.action.type}`)}return o.map(a=>({actionId:a.action.id,hash:a.hash,index:a.index,timestampUtcMs:a.timestampUtcMs,type:a.action.type,input:a.action.input,skip:a.skip,context:a.action.context,id:a.id??""}))}async getDocument(e){try{const r=await this.cache.getDocument(e);if(r)return r}catch(r){this.logger.error("Error getting document from cache",r)}const t=await this.documentStorage.get(e);return this._buildDocument(t)}_buildDocument(e){const t=this.getDocumentModelModule(e.header.documentType),r=Ve(e.operations);return Cr(e.initialState,r,t.reducer,void 0,e.header,void 0,{checkHashes:!0,reuseOperationResultingState:!0})}setDocumentModelModules(e){this.documentModelModules=e}getDocumentModelModule(e){const t=this.documentModelModules.find(r=>r.documentModel.global.id===e);if(!t)throw new Error(`Document type ${e} not supported`);return t}getCombinedSyncUnitStatus(e){if(!e.pull&&!e.push||e.pull==="INITIAL_SYNC")return"INITIAL_SYNC";if(e.push==="INITIAL_SYNC")return e.pull||"INITIAL_SYNC";const t=["ERROR","MISSING","CONFLICT","SYNCING","SUCCESS"];return Object.values(e).sort((n,s)=>t.indexOf(n)-t.indexOf(s))[0]}getSyncStatus(e,t="global",r="main"){const n=typeof e=="string"?{documentId:e,scope:t,branch:r}:e,s=this.syncStatus.get(n);return s?this.getCombinedSyncUnitStatus(s):new fi(n)}updateSyncStatus(e,t,r,n="global",s="main"){const o=typeof e=="string"?{documentId:e,scope:n,branch:s}:e;if(t===null){this.syncStatus.delete(o);return}const a=this.syncStatus.get(o);if(!a){this.initSyncStatus(o,t);return}if(Object.entries(t).some(([l,m])=>a[l]!==m)){const l=Object.entries(t).reduce((b,[w,y])=>({...b,[w]:b[w]==="INITIAL_SYNC"&&y==="SYNCING"?"INITIAL_SYNC":y}),a),m=this.getCombinedSyncUnitStatus(a),f=this.getCombinedSyncUnitStatus(l);this.syncStatus.set(o,l),m!==f&&this.eventEmitter&&this.eventEmitter.emit("syncStatus",o.documentId,this.getCombinedSyncUnitStatus(l),r,l,o.scope,o.branch)}}initSyncStatus(e,t){const r=Object.entries(t).reduce((n,[s,o])=>({...n,[s]:o!=="SYNCING"?o:"INITIAL_SYNC"}),{});this.syncStatus.set(e,r),this.eventEmitter&&this.eventEmitter.emit("syncStatus",e.documentId,this.getCombinedSyncUnitStatus(r),void 0,r,e.scope,e.branch)}async initializeDriveSyncStatus(e,t){const r=await this.getSynchronizationUnitsIds(e),n={pull:t.state.local.triggers.length>0?"INITIAL_SYNC":void 0,push:t.state.local.listeners.length>0?"SUCCESS":void 0};if(!n.pull&&!n.push)return;const s=[{documentId:e,scope:"global",branch:"main"},...r];for(const o of s)this.initSyncStatus(o,n)}}class bo{listenerManager;constructor(e){this.listenerManager=e}instance(e,t,r){switch(e){case"SwitchboardPush":{if(!t.callInfo?.data)throw new Error("No call info data: "+JSON.stringify(t));return new pn(t.callInfo.data,this.listenerManager)}case"Internal":throw new Error("Internal transmitter not implemented");default:return new ue(t,this.listenerManager)}}}let Lo=class{documentModelModules=[];storage;cache;queueManager;eventEmitter;options;synchronizationManager;listenerManager;transmitterFactory;constructor(e){this.documentModelModules=e}withStorage(e){return this.storage=e,this}withCache(e){return this.cache=e,this}withQueueManager(e){return this.queueManager=e,this}withEventEmitter(e){return this.eventEmitter=e,this}withSynchronizationManager(e){return this.synchronizationManager=e,this}withListenerManager(e){return this.listenerManager=e,this}withTransmitterFactory(e){return this.transmitterFactory=e,this}withOptions(e){return this.options=e,this}build(){if(this.storage||(this.storage=new mo),this.cache||(this.cache=new Us),this.queueManager||(this.queueManager=new Bi),this.eventEmitter||(this.eventEmitter=new yo),this.synchronizationManager||(this.synchronizationManager=new wo(this.storage,this.storage,this.cache,this.documentModelModules,this.eventEmitter)),!this.listenerManager){const e={...ot,...this.options?.listenerManager};this.listenerManager=new qt(this.synchronizationManager,e)}return this.transmitterFactory||(this.transmitterFactory=new bo(this.listenerManager)),new po(this.documentModelModules,this.storage,this.storage,this.cache,this.queueManager,this.eventEmitter,this.synchronizationManager,this.listenerManager,{...this.options,featureFlags:{enableDualActionCreate:!1,...this.options?.featureFlags}})}};function Or(i){let e=!1;const t=Object.entries(i.operations).reduce((r,[n,s])=>{const o=n;if(!s)return r;for(const a of s){const d=Do(a),l=r[o];l&&l.push(d),d!==a&&(e=!0)}return r},{global:[],local:[]});return e?{...i,operations:t}:i}function Do(i){let e=!1,t={...i};const r=i.context?.signer,n=i.action?.context?.signer;if(r){if("signature"in r){const s=r.signature;t={...t,context:{...t.context,signer:{user:r.user,app:r.app,signatures:s?.length?[s]:[]}}},e=!0}else if(r.signatures){const s=r.signatures.filter(o=>o&&o.length>0);s.length!==r.signatures.length&&(t={...t,context:{...t.context,signer:{...r,signatures:s}}},e=!0)}}if(n){if("signature"in n){const s=n.signature,o={...t.action.context,signer:{user:n.user,app:n.app,signatures:s?.length?[s]:[]}};t={...t,action:{...t.action,context:o},context:o},e=!0}else if(n.signatures){const s=n.signatures.filter(o=>o&&o.length>0);if(s.length!==n.signatures.length){const o={...t.action.context,signer:{...n,signatures:s}};t={...t,action:{...t.action,context:o},context:o},e=!0}}}return e?t:i}var xt={exports:{}};var _r;function So(){return _r||(_r=1,(function(i,e){(function(t){i.exports=t()})(function(){return(function t(r,n,s){function o(l,m){if(!n[l]){if(!r[l]){var f=typeof Je=="function"&&Je;if(!m&&f)return f(l,!0);if(a)return a(l,!0);var b=new Error("Cannot find module '"+l+"'");throw b.code="MODULE_NOT_FOUND",b}var w=n[l]={exports:{}};r[l][0].call(w.exports,function(y){var I=r[l][1][y];return o(I||y)},w,w.exports,t,r,n,s)}return n[l].exports}for(var a=typeof Je=="function"&&Je,d=0;d<s.length;d++)o(s[d]);return o})({1:[function(t,r,n){(function(s){var o=s.MutationObserver||s.WebKitMutationObserver,a;if(o){var d=0,l=new o(y),m=s.document.createTextNode("");l.observe(m,{characterData:!0}),a=function(){m.data=d=++d%2}}else if(!s.setImmediate&&typeof s.MessageChannel<"u"){var f=new s.MessageChannel;f.port1.onmessage=y,a=function(){f.port2.postMessage(0)}}else"document"in s&&"onreadystatechange"in s.document.createElement("script")?a=function(){var _=s.document.createElement("script");_.onreadystatechange=function(){y(),_.onreadystatechange=null,_.parentNode.removeChild(_),_=null},s.document.documentElement.appendChild(_)}:a=function(){setTimeout(y,0)};var b,w=[];function y(){b=!0;for(var _,N,C=w.length;C;){for(N=w,w=[],_=-1;++_<C;)N[_]();C=w.length}b=!1}r.exports=I;function I(_){w.push(_)===1&&!b&&a()}}).call(this,typeof Ee<"u"?Ee:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(t,r,n){var s=t(1);function o(){}var a={},d=["REJECTED"],l=["FULFILLED"],m=["PENDING"];r.exports=f;function f(E){if(typeof E!="function")throw new TypeError("resolver must be a function");this.state=m,this.queue=[],this.outcome=void 0,E!==o&&I(this,E)}f.prototype.catch=function(E){return this.then(null,E)},f.prototype.then=function(E,L){if(typeof E!="function"&&this.state===l||typeof L!="function"&&this.state===d)return this;var P=new this.constructor(o);if(this.state!==m){var j=this.state===l?E:L;w(P,j,this.outcome)}else this.queue.push(new b(P,E,L));return P};function b(E,L,P){this.promise=E,typeof L=="function"&&(this.onFulfilled=L,this.callFulfilled=this.otherCallFulfilled),typeof P=="function"&&(this.onRejected=P,this.callRejected=this.otherCallRejected)}b.prototype.callFulfilled=function(E){a.resolve(this.promise,E)},b.prototype.otherCallFulfilled=function(E){w(this.promise,this.onFulfilled,E)},b.prototype.callRejected=function(E){a.reject(this.promise,E)},b.prototype.otherCallRejected=function(E){w(this.promise,this.onRejected,E)};function w(E,L,P){s(function(){var j;try{j=L(P)}catch(H){return a.reject(E,H)}j===E?a.reject(E,new TypeError("Cannot resolve promise with itself")):a.resolve(E,j)})}a.resolve=function(E,L){var P=_(y,L);if(P.status==="error")return a.reject(E,P.value);var j=P.value;if(j)I(E,j);else{E.state=l,E.outcome=L;for(var H=-1,V=E.queue.length;++H<V;)E.queue[H].callFulfilled(L)}return E},a.reject=function(E,L){E.state=d,E.outcome=L;for(var P=-1,j=E.queue.length;++P<j;)E.queue[P].callRejected(L);return E};function y(E){var L=E&&E.then;if(E&&(typeof E=="object"||typeof E=="function")&&typeof L=="function")return function(){L.apply(E,arguments)}}function I(E,L){var P=!1;function j(Y){P||(P=!0,a.reject(E,Y))}function H(Y){P||(P=!0,a.resolve(E,Y))}function V(){L(H,j)}var Z=_(V);Z.status==="error"&&j(Z.value)}function _(E,L){var P={};try{P.value=E(L),P.status="success"}catch(j){P.status="error",P.value=j}return P}f.resolve=N;function N(E){return E instanceof this?E:a.resolve(new this(o),E)}f.reject=C;function C(E){var L=new this(o);return a.reject(L,E)}f.all=U;function U(E){var L=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var P=E.length,j=!1;if(!P)return this.resolve([]);for(var H=new Array(P),V=0,Z=-1,Y=new this(o);++Z<P;)se(E[Z],Z);return Y;function se(le,D){L.resolve(le).then(R,function(B){j||(j=!0,a.reject(Y,B))});function R(B){H[D]=B,++V===P&&!j&&(j=!0,a.resolve(Y,H))}}}f.race=F;function F(E){var L=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var P=E.length,j=!1;if(!P)return this.resolve([]);for(var H=-1,V=new this(o);++H<P;)Z(E[H]);return V;function Z(Y){L.resolve(Y).then(function(se){j||(j=!0,a.resolve(V,se))},function(se){j||(j=!0,a.reject(V,se))})}}},{1:1}],3:[function(t,r,n){(function(s){typeof s.Promise!="function"&&(s.Promise=t(2))}).call(this,typeof Ee<"u"?Ee:typeof self<"u"?self:typeof window<"u"?window:{})},{2:2}],4:[function(t,r,n){var s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(c){return typeof c}:function(c){return c&&typeof Symbol=="function"&&c.constructor===Symbol&&c!==Symbol.prototype?"symbol":typeof c};function o(c,h){if(!(c instanceof h))throw new TypeError("Cannot call a class as a function")}function a(){try{if(typeof indexedDB<"u")return indexedDB;if(typeof webkitIndexedDB<"u")return webkitIndexedDB;if(typeof mozIndexedDB<"u")return mozIndexedDB;if(typeof OIndexedDB<"u")return OIndexedDB;if(typeof msIndexedDB<"u")return msIndexedDB}catch{return}}var d=a();function l(){try{if(!d||!d.open)return!1;var c=typeof openDatabase<"u"&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),h=typeof fetch=="function"&&fetch.toString().indexOf("[native code")!==-1;return(!c||h)&&typeof indexedDB<"u"&&typeof IDBKeyRange<"u"}catch{return!1}}function m(c,h){c=c||[],h=h||{};try{return new Blob(c,h)}catch(g){if(g.name!=="TypeError")throw g;for(var u=typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder,p=new u,v=0;v<c.length;v+=1)p.append(c[v]);return p.getBlob(h.type)}}typeof Promise>"u"&&t(3);var f=Promise;function b(c,h){h&&c.then(function(u){h(null,u)},function(u){h(u)})}function w(c,h,u){typeof h=="function"&&c.then(h),typeof u=="function"&&c.catch(u)}function y(c){return typeof c!="string"&&(console.warn(c+" used as a key, but it is not a string."),c=String(c)),c}function I(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var _="local-forage-detect-blob-support",N=void 0,C={},U=Object.prototype.toString,F="readonly",E="readwrite";function L(c){for(var h=c.length,u=new ArrayBuffer(h),p=new Uint8Array(u),v=0;v<h;v++)p[v]=c.charCodeAt(v);return u}function P(c){return new f(function(h){var u=c.transaction(_,E),p=m([""]);u.objectStore(_).put(p,"key"),u.onabort=function(v){v.preventDefault(),v.stopPropagation(),h(!1)},u.oncomplete=function(){var v=navigator.userAgent.match(/Chrome\/(\d+)/),g=navigator.userAgent.match(/Edge\//);h(g||!v||parseInt(v[1],10)>=43)}}).catch(function(){return!1})}function j(c){return typeof N=="boolean"?f.resolve(N):P(c).then(function(h){return N=h,N})}function H(c){var h=C[c.name],u={};u.promise=new f(function(p,v){u.resolve=p,u.reject=v}),h.deferredOperations.push(u),h.dbReady?h.dbReady=h.dbReady.then(function(){return u.promise}):h.dbReady=u.promise}function V(c){var h=C[c.name],u=h.deferredOperations.pop();if(u)return u.resolve(),u.promise}function Z(c,h){var u=C[c.name],p=u.deferredOperations.pop();if(p)return p.reject(h),p.promise}function Y(c,h){return new f(function(u,p){if(C[c.name]=C[c.name]||_e(),c.db)if(h)H(c),c.db.close();else return u(c.db);var v=[c.name];h&&v.push(c.version);var g=d.open.apply(d,v);h&&(g.onupgradeneeded=function(S){var T=g.result;try{T.createObjectStore(c.storeName),S.oldVersion<=1&&T.createObjectStore(_)}catch(M){if(M.name==="ConstraintError")console.warn('The database "'+c.name+'" has been upgraded from version '+S.oldVersion+" to version "+S.newVersion+', but the storage "'+c.storeName+'" already exists.');else throw M}}),g.onerror=function(S){S.preventDefault(),p(g.error)},g.onsuccess=function(){var S=g.result;S.onversionchange=function(T){T.target.close()},u(S),V(c)}})}function se(c){return Y(c,!1)}function le(c){return Y(c,!0)}function D(c,h){if(!c.db)return!0;var u=!c.db.objectStoreNames.contains(c.storeName),p=c.version<c.db.version,v=c.version>c.db.version;if(p&&(c.version!==h&&console.warn('The database "'+c.name+`" can't be downgraded from version `+c.db.version+" to version "+c.version+"."),c.version=c.db.version),v||u){if(u){var g=c.db.version+1;g>c.version&&(c.version=g)}return!0}return!1}function R(c){return new f(function(h,u){var p=new FileReader;p.onerror=u,p.onloadend=function(v){var g=btoa(v.target.result||"");h({__local_forage_encoded_blob:!0,data:g,type:c.type})},p.readAsBinaryString(c)})}function B(c){var h=L(atob(c.data));return m([h],{type:c.type})}function G(c){return c&&c.__local_forage_encoded_blob}function K(c){var h=this,u=h._initReady().then(function(){var p=C[h._dbInfo.name];if(p&&p.dbReady)return p.dbReady});return w(u,c,c),u}function z(c){H(c);for(var h=C[c.name],u=h.forages,p=0;p<u.length;p++){var v=u[p];v._dbInfo.db&&(v._dbInfo.db.close(),v._dbInfo.db=null)}return c.db=null,se(c).then(function(g){return c.db=g,D(c)?le(c):g}).then(function(g){c.db=h.db=g;for(var S=0;S<u.length;S++)u[S]._dbInfo.db=g}).catch(function(g){throw Z(c,g),g})}function ae(c,h,u,p){p===void 0&&(p=1);try{var v=c.db.transaction(c.storeName,h);u(null,v)}catch(g){if(p>0&&(!c.db||g.name==="InvalidStateError"||g.name==="NotFoundError"))return f.resolve().then(function(){if(!c.db||g.name==="NotFoundError"&&!c.db.objectStoreNames.contains(c.storeName)&&c.version<=c.db.version)return c.db&&(c.version=c.db.version+1),le(c)}).then(function(){return z(c).then(function(){ae(c,h,u,p-1)})}).catch(u);u(g)}}function _e(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function qe(c){var h=this,u={db:null};if(c)for(var p in c)u[p]=c[p];var v=C[u.name];v||(v=_e(),C[u.name]=v),v.forages.push(h),h._initReady||(h._initReady=h.ready,h.ready=K);var g=[];function S(){return f.resolve()}for(var T=0;T<v.forages.length;T++){var M=v.forages[T];M!==h&&g.push(M._initReady().catch(S))}var O=v.forages.slice(0);return f.all(g).then(function(){return u.db=v.db,se(u)}).then(function(A){return u.db=A,D(u,h._defaultConfig.version)?le(u):A}).then(function(A){u.db=v.db=A,h._dbInfo=u;for(var x=0;x<O.length;x++){var k=O[x];k!==h&&(k._dbInfo.db=u.db,k._dbInfo.version=u.version)}})}function ne(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){ae(u._dbInfo,F,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=M.get(c);O.onsuccess=function(){var A=O.result;A===void 0&&(A=null),G(A)&&(A=B(A)),v(A)},O.onerror=function(){g(O.error)}}catch(A){g(A)}})}).catch(g)});return b(p,h),p}function ye(c,h){var u=this,p=new f(function(v,g){u.ready().then(function(){ae(u._dbInfo,F,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=M.openCursor(),A=1;O.onsuccess=function(){var x=O.result;if(x){var k=x.value;G(k)&&(k=B(k));var J=c(k,x.key,A++);J!==void 0?v(J):x.continue()}else v()},O.onerror=function(){g(O.error)}}catch(x){g(x)}})}).catch(g)});return b(p,h),p}function mn(c,h,u){var p=this;c=y(c);var v=new f(function(g,S){var T;p.ready().then(function(){return T=p._dbInfo,U.call(h)==="[object Blob]"?j(T.db).then(function(M){return M?h:R(h)}):h}).then(function(M){ae(p._dbInfo,E,function(O,A){if(O)return S(O);try{var x=A.objectStore(p._dbInfo.storeName);M===null&&(M=void 0);var k=x.put(M,c);A.oncomplete=function(){M===void 0&&(M=null),g(M)},A.onabort=A.onerror=function(){var J=k.error?k.error:k.transaction.error;S(J)}}catch(J){S(J)}})}).catch(S)});return b(v,u),v}function yn(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){ae(u._dbInfo,E,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=M.delete(c);T.oncomplete=function(){v()},T.onerror=function(){g(O.error)},T.onabort=function(){var A=O.error?O.error:O.transaction.error;g(A)}}catch(A){g(A)}})}).catch(g)});return b(p,h),p}function vn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){ae(h._dbInfo,E,function(g,S){if(g)return v(g);try{var T=S.objectStore(h._dbInfo.storeName),M=T.clear();S.oncomplete=function(){p()},S.onabort=S.onerror=function(){var O=M.error?M.error:M.transaction.error;v(O)}}catch(O){v(O)}})}).catch(v)});return b(u,c),u}function wn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){ae(h._dbInfo,F,function(g,S){if(g)return v(g);try{var T=S.objectStore(h._dbInfo.storeName),M=T.count();M.onsuccess=function(){p(M.result)},M.onerror=function(){v(M.error)}}catch(O){v(O)}})}).catch(v)});return b(u,c),u}function bn(c,h){var u=this,p=new f(function(v,g){if(c<0){v(null);return}u.ready().then(function(){ae(u._dbInfo,F,function(S,T){if(S)return g(S);try{var M=T.objectStore(u._dbInfo.storeName),O=!1,A=M.openKeyCursor();A.onsuccess=function(){var x=A.result;if(!x){v(null);return}c===0||O?v(x.key):(O=!0,x.advance(c))},A.onerror=function(){g(A.error)}}catch(x){g(x)}})}).catch(g)});return b(p,h),p}function Dn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){ae(h._dbInfo,F,function(g,S){if(g)return v(g);try{var T=S.objectStore(h._dbInfo.storeName),M=T.openKeyCursor(),O=[];M.onsuccess=function(){var A=M.result;if(!A){p(O);return}O.push(A.key),A.continue()},M.onerror=function(){v(M.error)}}catch(A){v(A)}})}).catch(v)});return b(u,c),u}function Sn(c,h){h=I.apply(this,arguments);var u=this.config();c=typeof c!="function"&&c||{},c.name||(c.name=c.name||u.name,c.storeName=c.storeName||u.storeName);var p=this,v;if(!c.name)v=f.reject("Invalid arguments");else{var g=c.name===u.name&&p._dbInfo.db,S=g?f.resolve(p._dbInfo.db):se(c).then(function(T){var M=C[c.name],O=M.forages;M.db=T;for(var A=0;A<O.length;A++)O[A]._dbInfo.db=T;return T});c.storeName?v=S.then(function(T){if(T.objectStoreNames.contains(c.storeName)){var M=T.version+1;H(c);var O=C[c.name],A=O.forages;T.close();for(var x=0;x<A.length;x++){var k=A[x];k._dbInfo.db=null,k._dbInfo.version=M}var J=new f(function(Q,re){var ee=d.open(c.name,M);ee.onerror=function(de){var Pe=ee.result;Pe.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<A.length;re++){var ee=A[re];ee._dbInfo.db=Q,V(ee._dbInfo)}}).catch(function(Q){throw(Z(c,Q)||f.resolve()).catch(function(){}),Q})}}):v=S.then(function(T){H(c);var M=C[c.name],O=M.forages;T.close();for(var A=0;A<O.length;A++){var x=O[A];x._dbInfo.db=null}var k=new f(function(J,Q){var re=d.deleteDatabase(c.name);re.onerror=function(){var ee=re.result;ee&&ee.close(),Q(re.error)},re.onblocked=function(){console.warn('dropInstance blocked for database "'+c.name+'" until all open connections are closed')},re.onsuccess=function(){var ee=re.result;ee&&ee.close(),J(ee)}});return k.then(function(J){M.db=J;for(var Q=0;Q<O.length;Q++){var re=O[Q];V(re._dbInfo)}}).catch(function(J){throw(Z(c,J)||f.resolve()).catch(function(){}),J})})}return b(v,h),v}var En={_driver:"asyncStorage",_initStorage:qe,_support:l(),iterate:ye,getItem:ne,setItem:mn,removeItem:yn,clear:vn,length:wn,key:bn,keys:Dn,dropInstance:Sn};function In(){return typeof openDatabase=="function"}var be="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Tn="~~local_forage_type~",zt=/^~~local_forage_type~([^~]+)~/,ze="__lfsc__:",ht=ze.length,ft="arbf",gt="blob",jt="si08",Ht="ui08",Gt="uic8",Jt="si16",Yt="si32",Qt="ur16",Vt="ui32",Kt="fl32",Wt="fl64",Xt=ht+ft.length,Zt=Object.prototype.toString;function er(c){var h=c.length*.75,u=c.length,p,v=0,g,S,T,M;c[c.length-1]==="="&&(h--,c[c.length-2]==="="&&h--);var O=new ArrayBuffer(h),A=new Uint8Array(O);for(p=0;p<u;p+=4)g=be.indexOf(c[p]),S=be.indexOf(c[p+1]),T=be.indexOf(c[p+2]),M=be.indexOf(c[p+3]),A[v++]=g<<2|S>>4,A[v++]=(S&15)<<4|T>>2,A[v++]=(T&3)<<6|M&63;return O}function pt(c){var h=new Uint8Array(c),u="",p;for(p=0;p<h.length;p+=3)u+=be[h[p]>>2],u+=be[(h[p]&3)<<4|h[p+1]>>4],u+=be[(h[p+1]&15)<<2|h[p+2]>>6],u+=be[h[p+2]&63];return h.length%3===2?u=u.substring(0,u.length-1)+"=":h.length%3===1&&(u=u.substring(0,u.length-2)+"=="),u}function Rn(c,h){var u="";if(c&&(u=Zt.call(c)),c&&(u==="[object ArrayBuffer]"||c.buffer&&Zt.call(c.buffer)==="[object ArrayBuffer]")){var p,v=ze;c instanceof ArrayBuffer?(p=c,v+=ft):(p=c.buffer,u==="[object Int8Array]"?v+=jt:u==="[object Uint8Array]"?v+=Ht:u==="[object Uint8ClampedArray]"?v+=Gt:u==="[object Int16Array]"?v+=Jt:u==="[object Uint16Array]"?v+=Qt:u==="[object Int32Array]"?v+=Yt:u==="[object Uint32Array]"?v+=Vt:u==="[object Float32Array]"?v+=Kt:u==="[object Float64Array]"?v+=Wt:h(new Error("Failed to get type for BinaryArray"))),h(v+pt(p))}else if(u==="[object Blob]"){var g=new FileReader;g.onload=function(){var S=Tn+c.type+"~"+pt(this.result);h(ze+gt+S)},g.readAsArrayBuffer(c)}else try{h(JSON.stringify(c))}catch(S){console.error("Couldn't convert value into a JSON string: ",c),h(null,S)}}function Mn(c){if(c.substring(0,ht)!==ze)return JSON.parse(c);var h=c.substring(Xt),u=c.substring(ht,Xt),p;if(u===gt&&zt.test(h)){var v=h.match(zt);p=v[1],h=h.substring(v[0].length)}var g=er(h);switch(u){case ft:return g;case gt:return m([g],{type:p});case jt:return new Int8Array(g);case Ht:return new Uint8Array(g);case Gt:return new Uint8ClampedArray(g);case Jt:return new Int16Array(g);case Qt:return new Uint16Array(g);case Yt:return new Int32Array(g);case Vt:return new Uint32Array(g);case Kt:return new Float32Array(g);case Wt:return new Float64Array(g);default:throw new Error("Unkown type: "+u)}}var mt={serialize:Rn,deserialize:Mn,stringToBuffer:er,bufferToString:pt};function tr(c,h,u,p){c.executeSql("CREATE TABLE IF NOT EXISTS "+h.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],u,p)}function On(c){var h=this,u={db:null};if(c)for(var p in c)u[p]=typeof c[p]!="string"?c[p].toString():c[p];var v=new f(function(g,S){try{u.db=openDatabase(u.name,String(u.version),u.description,u.size)}catch(T){return S(T)}u.db.transaction(function(T){tr(T,u,function(){h._dbInfo=u,g()},function(M,O){S(O)})},S)});return u.serializer=mt,v}function De(c,h,u,p,v,g){c.executeSql(u,p,v,function(S,T){T.code===T.SYNTAX_ERR?S.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[h.storeName],function(M,O){O.rows.length?g(M,T):tr(M,h,function(){M.executeSql(u,p,v,g)},g)},g):g(S,T)},g)}function _n(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"SELECT * FROM "+S.storeName+" WHERE key = ? LIMIT 1",[c],function(M,O){var A=O.rows.length?O.rows.item(0).value:null;A&&(A=S.serializer.deserialize(A)),v(A)},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function An(c,h){var u=this,p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"SELECT * FROM "+S.storeName,[],function(M,O){for(var A=O.rows,x=A.length,k=0;k<x;k++){var J=A.item(k),Q=J.value;if(Q&&(Q=S.serializer.deserialize(Q)),Q=c(Q,J.key,k+1),Q!==void 0){v(Q);return}}v()},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function rr(c,h,u,p){var v=this;c=y(c);var g=new f(function(S,T){v.ready().then(function(){h===void 0&&(h=null);var M=h,O=v._dbInfo;O.serializer.serialize(h,function(A,x){x?T(x):O.db.transaction(function(k){De(k,O,"INSERT OR REPLACE INTO "+O.storeName+" (key, value) VALUES (?, ?)",[c,A],function(){S(M)},function(J,Q){T(Q)})},function(k){if(k.code===k.QUOTA_ERR){if(p>0){S(rr.apply(v,[c,M,u,p-1]));return}T(k)}})})}).catch(T)});return b(g,u),g}function Nn(c,h,u){return rr.apply(this,[c,h,u,1])}function Cn(c,h){var u=this;c=y(c);var p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"DELETE FROM "+S.storeName+" WHERE key = ?",[c],function(){v()},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function xn(c){var h=this,u=new f(function(p,v){h.ready().then(function(){var g=h._dbInfo;g.db.transaction(function(S){De(S,g,"DELETE FROM "+g.storeName,[],function(){p()},function(T,M){v(M)})})}).catch(v)});return b(u,c),u}function $n(c){var h=this,u=new f(function(p,v){h.ready().then(function(){var g=h._dbInfo;g.db.transaction(function(S){De(S,g,"SELECT COUNT(key) as c FROM "+g.storeName,[],function(T,M){var O=M.rows.item(0).c;p(O)},function(T,M){v(M)})})}).catch(v)});return b(u,c),u}function Pn(c,h){var u=this,p=new f(function(v,g){u.ready().then(function(){var S=u._dbInfo;S.db.transaction(function(T){De(T,S,"SELECT key FROM "+S.storeName+" WHERE id = ? LIMIT 1",[c+1],function(M,O){var A=O.rows.length?O.rows.item(0).key:null;v(A)},function(M,O){g(O)})})}).catch(g)});return b(p,h),p}function Ln(c){var h=this,u=new f(function(p,v){h.ready().then(function(){var g=h._dbInfo;g.db.transaction(function(S){De(S,g,"SELECT key FROM "+g.storeName,[],function(T,M){for(var O=[],A=0;A<M.rows.length;A++)O.push(M.rows.item(A).key);p(O)},function(T,M){v(M)})})}).catch(v)});return b(u,c),u}function Un(c){return new f(function(h,u){c.transaction(function(p){p.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(v,g){for(var S=[],T=0;T<g.rows.length;T++)S.push(g.rows.item(T).name);h({db:c,storeNames:S})},function(v,g){u(g)})},function(p){u(p)})})}function Bn(c,h){h=I.apply(this,arguments);var u=this.config();c=typeof c!="function"&&c||{},c.name||(c.name=c.name||u.name,c.storeName=c.storeName||u.storeName);var p=this,v;return c.name?v=new f(function(g){var S;c.name===u.name?S=p._dbInfo.db:S=openDatabase(c.name,"","",0),c.storeName?g({db:S,storeNames:[c.storeName]}):g(Un(S))}).then(function(g){return new f(function(S,T){g.db.transaction(function(M){function O(J){return new f(function(Q,re){M.executeSql("DROP TABLE IF EXISTS "+J,[],function(){Q()},function(ee,de){re(de)})})}for(var A=[],x=0,k=g.storeNames.length;x<k;x++)A.push(O(g.storeNames[x]));f.all(A).then(function(){S()}).catch(function(J){T(J)})},function(M){T(M)})})}):v=f.reject("Invalid arguments"),b(v,h),v}var Fn={_driver:"webSQLStorage",_initStorage:On,_support:In(),iterate:An,getItem:_n,setItem:Nn,removeItem:Cn,clear:xn,length:$n,key:Pn,keys:Ln,dropInstance:Bn};function kn(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}function nr(c,h){var u=c.name+"/";return c.storeName!==h.storeName&&(u+=c.storeName+"/"),u}function qn(){var c="_localforage_support_test";try{return localStorage.setItem(c,!0),localStorage.removeItem(c),!1}catch{return!0}}function zn(){return!qn()||localStorage.length>0}function jn(c){var h=this,u={};if(c)for(var p in c)u[p]=c[p];return u.keyPrefix=nr(c,h._defaultConfig),zn()?(h._dbInfo=u,u.serializer=mt,f.resolve()):f.reject()}function Hn(c){var h=this,u=h.ready().then(function(){for(var p=h._dbInfo.keyPrefix,v=localStorage.length-1;v>=0;v--){var g=localStorage.key(v);g.indexOf(p)===0&&localStorage.removeItem(g)}});return b(u,c),u}function Gn(c,h){var u=this;c=y(c);var p=u.ready().then(function(){var v=u._dbInfo,g=localStorage.getItem(v.keyPrefix+c);return g&&(g=v.serializer.deserialize(g)),g});return b(p,h),p}function Jn(c,h){var u=this,p=u.ready().then(function(){for(var v=u._dbInfo,g=v.keyPrefix,S=g.length,T=localStorage.length,M=1,O=0;O<T;O++){var A=localStorage.key(O);if(A.indexOf(g)===0){var x=localStorage.getItem(A);if(x&&(x=v.serializer.deserialize(x)),x=c(x,A.substring(S),M++),x!==void 0)return x}}});return b(p,h),p}function Yn(c,h){var u=this,p=u.ready().then(function(){var v=u._dbInfo,g;try{g=localStorage.key(c)}catch{g=null}return g&&(g=g.substring(v.keyPrefix.length)),g});return b(p,h),p}function Qn(c){var h=this,u=h.ready().then(function(){for(var p=h._dbInfo,v=localStorage.length,g=[],S=0;S<v;S++){var T=localStorage.key(S);T.indexOf(p.keyPrefix)===0&&g.push(T.substring(p.keyPrefix.length))}return g});return b(u,c),u}function Vn(c){var h=this,u=h.keys().then(function(p){return p.length});return b(u,c),u}function Kn(c,h){var u=this;c=y(c);var p=u.ready().then(function(){var v=u._dbInfo;localStorage.removeItem(v.keyPrefix+c)});return b(p,h),p}function Wn(c,h,u){var p=this;c=y(c);var v=p.ready().then(function(){h===void 0&&(h=null);var g=h;return new f(function(S,T){var M=p._dbInfo;M.serializer.serialize(h,function(O,A){if(A)T(A);else try{localStorage.setItem(M.keyPrefix+c,O),S(g)}catch(x){(x.name==="QuotaExceededError"||x.name==="NS_ERROR_DOM_QUOTA_REACHED")&&T(x),T(x)}})})});return b(v,u),v}function Xn(c,h){if(h=I.apply(this,arguments),c=typeof c!="function"&&c||{},!c.name){var u=this.config();c.name=c.name||u.name,c.storeName=c.storeName||u.storeName}var p=this,v;return c.name?v=new f(function(g){c.storeName?g(nr(c,p._defaultConfig)):g(c.name+"/")}).then(function(g){for(var S=localStorage.length-1;S>=0;S--){var T=localStorage.key(S);T.indexOf(g)===0&&localStorage.removeItem(T)}}):v=f.reject("Invalid arguments"),b(v,h),v}var Zn={_driver:"localStorageWrapper",_initStorage:jn,_support:kn(),iterate:Jn,getItem:Gn,setItem:Wn,removeItem:Kn,clear:Hn,length:Vn,key:Yn,keys:Qn,dropInstance:Xn},es=function(h,u){return h===u||typeof h=="number"&&typeof u=="number"&&isNaN(h)&&isNaN(u)},ts=function(h,u){for(var p=h.length,v=0;v<p;){if(es(h[v],u))return!0;v++}return!1},sr=Array.isArray||function(c){return Object.prototype.toString.call(c)==="[object Array]"},$e={},ir={},Ae={INDEXEDDB:En,WEBSQL:Fn,LOCALSTORAGE:Zn},rs=[Ae.INDEXEDDB._driver,Ae.WEBSQL._driver,Ae.LOCALSTORAGE._driver],je=["dropInstance"],yt=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(je),ns={description:"",driver:rs.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function ss(c,h){c[h]=function(){var u=arguments;return c.ready().then(function(){return c[h].apply(c,u)})}}function vt(){for(var c=1;c<arguments.length;c++){var h=arguments[c];if(h)for(var u in h)h.hasOwnProperty(u)&&(sr(h[u])?arguments[0][u]=h[u].slice():arguments[0][u]=h[u])}return arguments[0]}var is=(function(){function c(h){o(this,c);for(var u in Ae)if(Ae.hasOwnProperty(u)){var p=Ae[u],v=p._driver;this[u]=v,$e[v]||this.defineDriver(p)}this._defaultConfig=vt({},ns),this._config=vt({},this._defaultConfig,h),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return c.prototype.config=function(u){if((typeof u>"u"?"undefined":s(u))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var p in u){if(p==="storeName"&&(u[p]=u[p].replace(/\W/g,"_")),p==="version"&&typeof u[p]!="number")return new Error("Database version must be a number.");this._config[p]=u[p]}return"driver"in u&&u.driver?this.setDriver(this._config.driver):!0}else return typeof u=="string"?this._config[u]:this._config},c.prototype.defineDriver=function(u,p,v){var g=new f(function(S,T){try{var M=u._driver,O=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!u._driver){T(O);return}for(var A=yt.concat("_initStorage"),x=0,k=A.length;x<k;x++){var J=A[x],Q=!ts(je,J);if((Q||u[J])&&typeof u[J]!="function"){T(O);return}}var re=function(){for(var Pe=function(cs){return function(){var us=new Error("Method "+cs+" is not implemented by the current driver"),or=f.reject(us);return b(or,arguments[arguments.length-1]),or}},wt=0,as=je.length;wt<as;wt++){var bt=je[wt];u[bt]||(u[bt]=Pe(bt))}};re();var ee=function(Pe){$e[M]&&console.info("Redefining LocalForage driver: "+M),$e[M]=u,ir[M]=Pe,S()};"_support"in u?u._support&&typeof u._support=="function"?u._support().then(ee,T):ee(!!u._support):ee(!0)}catch(de){T(de)}});return w(g,p,v),g},c.prototype.driver=function(){return this._driver||null},c.prototype.getDriver=function(u,p,v){var g=$e[u]?f.resolve($e[u]):f.reject(new Error("Driver not found."));return w(g,p,v),g},c.prototype.getSerializer=function(u){var p=f.resolve(mt);return w(p,u),p},c.prototype.ready=function(u){var p=this,v=p._driverSet.then(function(){return p._ready===null&&(p._ready=p._initDriver()),p._ready});return w(v,u,u),v},c.prototype.setDriver=function(u,p,v){var g=this;sr(u)||(u=[u]);var S=this._getSupportedDrivers(u);function T(){g._config.driver=g.driver()}function M(x){return g._extend(x),T(),g._ready=g._initStorage(g._config),g._ready}function O(x){return function(){var k=0;function J(){for(;k<x.length;){var Q=x[k];return k++,g._dbInfo=null,g._ready=null,g.getDriver(Q).then(M).catch(J)}T();var re=new Error("No available storage method found.");return g._driverSet=f.reject(re),g._driverSet}return J()}}var A=this._driverSet!==null?this._driverSet.catch(function(){return f.resolve()}):f.resolve();return this._driverSet=A.then(function(){var x=S[0];return g._dbInfo=null,g._ready=null,g.getDriver(x).then(function(k){g._driver=k._driver,T(),g._wrapLibraryMethodsWithReady(),g._initDriver=O(S)})}).catch(function(){T();var x=new Error("No available storage method found.");return g._driverSet=f.reject(x),g._driverSet}),w(this._driverSet,p,v),this._driverSet},c.prototype.supports=function(u){return!!ir[u]},c.prototype._extend=function(u){vt(this,u)},c.prototype._getSupportedDrivers=function(u){for(var p=[],v=0,g=u.length;v<g;v++){var S=u[v];this.supports(S)&&p.push(S)}return p},c.prototype._wrapLibraryMethodsWithReady=function(){for(var u=0,p=yt.length;u<p;u++)ss(this,yt[u])},c.prototype.createInstance=function(u){return new c(u)},c})(),os=new is;r.exports=os},{3:3}]},{},[4])(4)})})(xt)),xt.exports}var Eo=So();const Ar=Pt(Eo);class te{logger=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=Ar.ready().then(()=>Ar.createInstance({name:e?`${e}:${te.DBName}`:te.DBName}))}async findStorageUnitsBy(e,t,r){const n=[],{parentId:s,documentId:o,documentModelType:a,scope:d}=sn(e),f=(await(await this.db).keys()).filter(_=>_.startsWith(`${te.DOCUMENT_KEY}${te.SEP}`)).map(_=>_.slice(te.DOCUMENT_KEY.length+te.SEP.length));let b;if(s){const _=new Set;for(const N of s)(await this.getChildren(N)).forEach(U=>_.add(U));b=on(s,_)}else b=new Set(f);b=o?an(o,b):b;for(const _ of b){const N=await this.get(_).catch(()=>null);if(N&&!(a&&!a.has(N.header.documentType)))for(const[C]of Object.entries(N.state))d&&!d.has(C)||n.push({documentId:_,documentModelType:N.header.documentType,scope:C,branch:"main"})}let w=0;if(r){const _=n.findIndex(N=>N.documentId===r);_!==-1&&(w=_)}const y=Math.min(w+t,n.length),I=y<n.length?n[y].documentId:void 0;return{units:n.slice(w,y),nextCursor:I}}async resolveIds(e,t){const r=await this.getSlugManifest();if(t?.aborted)throw new at("Aborted");const n=[];for(const s of e){const o=r.slugToId[s];if(!o)throw new we(s);n.push(o)}return Promise.resolve(n)}async resolveSlugs(e,t){const r=await this.getSlugManifest();if(t?.aborted)throw new at("Aborted");const n=[];for(const s of e){let o=!1;for(const[a,d]of Object.entries(r.slugToId))if(d===s){n.push(a),o=!0;break}if(!o)throw new we(s)}return Promise.resolve(n)}async clear(){await(await this.db).clear()}async exists(e){return!!await(await this.db).getItem(this.buildDocumentKey(e))}async create(e){const t=e.header.id;if(!tt(t))throw new et(t);const r=await this.db;if(await this.exists(t))throw new ke(t);const n=e.header.slug&&e.header.slug.length>0?e.header.slug:t;if(!nn(n))throw new rn(n);if((await this.getSlugManifest()).slugToId[n])throw new ke(t,Fe.SLUG);if(e.header.slug=n,await r.setItem(this.buildDocumentKey(t),e),n){const o=await this.getSlugManifest();if(o.slugToId[n])throw new Error(`Document with slug ${n} already exists`);o.slugToId[n]=t,await this.updateSlugManifest(o)}e.header.documentType==="powerhouse/document-drive"&&this.updateDriveManifest(t,{documentIds:[]})}async get(e){const r=await(await this.db).getItem(this.buildDocumentKey(e));return r||Promise.reject(new we(e))}async getBySlug(e){const r=(await this.getSlugManifest()).slugToId[e];return r?this.get(r):Promise.reject(new we(e))}async findByType(e,t=100,r){const n=await this.db,o=(await n.keys()).filter(f=>f.startsWith(`${te.DOCUMENT_KEY}${te.SEP}`)),a=[];for(const f of o){const b=f.slice(te.DOCUMENT_KEY.length+te.SEP.length);try{const w=await n.getItem(f);if(!w||w.header.documentType!==e)continue;a.push({id:b,document:w})}catch{continue}}a.sort((f,b)=>{const w=new Date(f.document.header.createdAtUtcIso),y=new Date(b.document.header.createdAtUtcIso);return w.getTime()===y.getTime()?f.id.localeCompare(b.id):w.getTime()-y.getTime()});let d=0;if(r){const f=a.findIndex(({id:b})=>b===r);f!==-1&&(d=f)}const l=Math.min(d+t,a.length);let m;return l<a.length&&(m=a[l].id),{documents:a.slice(d,l).map(({id:f})=>f),nextCursor:m}}async delete(e){const t=await this.db,r=await t.getItem(this.buildDocumentKey(e));if(!r)return!1;const n=r.header.slug?.length>0?r.header.slug:e;try{if(n){const o=await this.getSlugManifest();o.slugToId[n]===e&&(delete o.slugToId[n],await this.updateSlugManifest(o))}}catch{}const s=await this.getParents(e);for(const o of s)await this.removeChild(o,e);return await t.removeItem(this.buildManifestKey(e)),await t.removeItem(this.buildDocumentKey(e)),!0}async removeChild(e,t){const r=await this.getManifest(e),n=r.documentIds.indexOf(t);return n!==-1?(r.documentIds.splice(n,1),await this.updateDriveManifest(e,r),!0):!1}async addChild(e,t){if(e===t)throw new Error("Cannot associate a document with itself");if((await this.getChildren(t)).includes(e))throw new Error("Cannot associate a document with its child");const n=await this.getManifest(e);n.documentIds.includes(t)||(n.documentIds.push(t),await this.updateDriveManifest(e,n))}async getChildren(e){return(await this.getManifest(e)).documentIds}async getParents(e){const r=await(await this.db).keys(),n=[],s=r.filter(o=>o.startsWith(`${te.MANIFEST_KEY}${te.SEP}`));for(const o of s){const a=o.slice(te.MANIFEST_KEY.length+te.SEP.length);(await this.getManifest(a)).documentIds.includes(e)&&n.push(a)}return n}async getManifest(e){return await(await this.db).getItem(this.buildManifestKey(e))||{documentIds:[]}}async updateDriveManifest(e,t){await(await this.db).setItem(this.buildManifestKey(e),t)}async getSlugManifest(){return await(await this.db).getItem(te.SLUG_MANIFEST_KEY)||{slugToId:{}}}async updateSlugManifest(e){await(await this.db).setItem(te.SLUG_MANIFEST_KEY,e)}async addDocumentOperations(e,t,r){const n=await this.get(e);if(!n)throw new Error(`Document with id ${e} not found`);const s=st(n.operations,t);await(await this.db).setItem(this.buildDocumentKey(e),{...n,...r,operations:s})}async addDriveOperations(e,t,r){const n=await this.get(e),s=st(n.operations,t);await(await this.db).setItem(this.buildDocumentKey(e),{...n,...r,operations:s})}async getSynchronizationUnitsRevision(e){return(await Promise.allSettled(e.map(async r=>{try{const n=await this.get(r.documentId);if(!n?.operations[r.scope])return;const s=n.operations[r.scope];return{documentId:r.documentId,documentType:r.documentType,scope:r.scope,branch:r.branch,lastUpdated:s.at(-1)?.timestampUtcMs??n.header.createdAtUtcIso,revision:s.length>0?Ie(s):0}}catch(n){this.logger.error("Error getting synchronization units revision",n);return}}))).reduce((r,n)=>(n.status==="fulfilled"&&n.value!==void 0&&r.push(n.value),r),[])}async migrateOperationSignatures(){let e;do{const{documents:t,nextCursor:r}=await this.findByType("powerhouse/document-drive",100,e);for(const n of t){await this.migrateDrive(n);const s=await this.getChildren(n);await Promise.all(s.map(async o=>this.migrateDocument(n,o)))}e=r}while(e)}async migrateDrive(e){const t=await this.get(e),r=Or(t);if(r!==t)return(await this.db).setItem(this.buildDocumentKey(e),r)}async migrateDocument(e,t){const r=await this.get(t),n=Or(r);if(n!==r)return(await this.db).setItem(this.buildDocumentKey(t),n)}buildDocumentKey(e){return`${te.DOCUMENT_KEY}${te.SEP}${e}`}buildManifestKey(e){return`${te.MANIFEST_KEY}${te.SEP}${e}`}}export{at as A,te as B,we as D,Bi as E,Us as I,mo as M,ue as P,Lo as R,fi as S,Ws as a,Xs as b,gi as c,Zs as d,ri as e,oi as f,No as g,Ne as h,lr as i,si as j,ci as k,fe as l,ni as m,li as n,Po as o,Ye as p,Ao as q,tn as r,Zr as s,me as t,ti as u,Ni as v,Co as w,gn as x,xo as y};