@steedos-widgets/liveblocks 6.3.12-beta.29 → 6.3.12-beta.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets.json +5 -5
- package/dist/liveblocks.umd.js +1 -1
- package/package.json +3 -3
package/dist/assets.json
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
{
|
|
4
4
|
"package": "@steedos-widgets/liveblocks",
|
|
5
5
|
"urls": [
|
|
6
|
-
"https://unpkg.com/@steedos-widgets/liveblocks@6.3.12-beta.
|
|
7
|
-
"https://unpkg.com/@steedos-widgets/liveblocks@6.3.12-beta.
|
|
6
|
+
"https://unpkg.com/@steedos-widgets/liveblocks@6.3.12-beta.30/dist/liveblocks.umd.js",
|
|
7
|
+
"https://unpkg.com/@steedos-widgets/liveblocks@6.3.12-beta.30/dist/liveblocks.umd.css"
|
|
8
8
|
],
|
|
9
9
|
"library": "BuilderLiveblocks"
|
|
10
10
|
}
|
|
@@ -15,10 +15,10 @@
|
|
|
15
15
|
"npm": {
|
|
16
16
|
"package": "@steedos-widgets/liveblocks"
|
|
17
17
|
},
|
|
18
|
-
"url": "https://unpkg.com/@steedos-widgets/liveblocks@6.3.12-beta.
|
|
18
|
+
"url": "https://unpkg.com/@steedos-widgets/liveblocks@6.3.12-beta.30/dist/meta.js",
|
|
19
19
|
"urls": {
|
|
20
|
-
"default": "https://unpkg.com/@steedos-widgets/liveblocks@6.3.12-beta.
|
|
21
|
-
"design": "https://unpkg.com/@steedos-widgets/liveblocks@6.3.12-beta.
|
|
20
|
+
"default": "https://unpkg.com/@steedos-widgets/liveblocks@6.3.12-beta.30/dist/meta.js",
|
|
21
|
+
"design": "https://unpkg.com/@steedos-widgets/liveblocks@6.3.12-beta.30/dist/meta.js"
|
|
22
22
|
}
|
|
23
23
|
}
|
|
24
24
|
]
|
package/dist/liveblocks.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["exports","react","react-dom"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BuilderLiveblocks={},e.React,e.ReactDOM)}(this,(function(e,t,n){const r=window;function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function a(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var i=a(t),s=o(t),u=a(n),c=o(n),l=Object.defineProperty,d="@liveblocks/core",f="2.12.0",h="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==r?r:{};function p(e){console.error(e)}function m(e,t,n){const r=Symbol.for(e),o=n?`${t||"dev"} (${n})`:t||"dev";if(h[r])if(h[r]===o);else{p(["Multiple copies of Liveblocks are being loaded in your project. This will cause issues! See https://liveblocks.io/docs/errors/dupes ","","Conflicts:",`- ${e} ${h[r]} (already loaded)`,`- ${e} ${o} (trying to load this now)`].join("\n"))}else h[r]=o;t&&t!==f&&p(["Cross-linked versions of Liveblocks found, which will cause issues! See https://liveblocks.io/docs/errors/cross-linked ","","Conflicts:",`- ${d} is at 2.12.0`,`- ${e} is at ${t}`,"","Always upgrade all Liveblocks packages to the same version number."].join("\n"))}function v(e,t){throw new Error(t)}function g(e,t="Expected value to be non-nullable"){return e}function y(){let e,t;return[new Promise(((n,r)=>{e=n,t=r})),e,t]}function b(){const[e,t,n]=y();return{promise:e,resolve:t,reject:n}}function E(){const e=new Set,t=new Set;let n=null;function r(e){return t.add(e),()=>t.delete(e)}function o(t){return e.add(t),()=>e.delete(t)}async function a(e){let t;return new Promise((n=>{t=r((t=>{(void 0===e||e(t))&&n(t)}))})).finally((()=>t?.()))}function i(n){e.forEach((e=>e(n))),e.clear(),t.forEach((e=>e(n)))}return{notify:function(e){null!==n?n.push(e):i(e)},subscribe:r,subscribeOnce:o,_forceClear:function(){e.clear(),t.clear()},count:function(){return e.size+t.size},waitUntil:a,pause:function(){n=[]},unpause:function(){if(null!==n){for(const e of n)i(e);n=null}},observable:{subscribe:r,subscribeOnce:o,waitUntil:a}}}var w={};((e,t)=>{for(var n in t)l(e,n,{get:t[n],enumerable:!0})})(w,{error:()=>A,errorWithTitle:()=>O,warn:()=>x,warnWithTitle:()=>B});var C="background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;";function D(e){return"undefined"==typeof window?console[e]:(t,...n)=>console[e]("%cLiveblocks",C,t,...n)}var x=D("warn"),A=D("error");function _(e){return"undefined"==typeof window?console[e]:(t,n,...r)=>console[e](`%cLiveblocks%c ${t}`,C,"font-weight:600",n,...r)}var B=_("warn"),O=_("error");var S=1,T=class{get initialState(){const e=this.states.values()[Symbol.iterator]().next();if(e.done)throw new Error("No states defined yet");return e.value}get currentState(){if(null===this.currentStateOrNull)throw 0===this.runningState?new Error("Not started yet"):new Error("Already stopped");return this.currentStateOrNull}start(){if(0!==this.runningState)throw new Error("State machine has already started");return this.runningState=1,this.currentStateOrNull=this.initialState,this.enter(null),this}stop(){if(1!==this.runningState)throw new Error("Cannot stop a state machine that hasn't started yet");this.exit(null),this.runningState=2,this.currentStateOrNull=null}constructor(e){this.id=S++,this.runningState=0,this.currentStateOrNull=null,this.states=new Set,this.enterFns=new Map,this.cleanupStack=[],this.knownEventTypes=new Set,this.allowedTransitions=new Map,this.currentContext=new class{constructor(e){this.curr=e}get current(){return this.curr}allowPatching(e){const t=this;let n=!0;e({...this.curr,patch(e){if(!n)throw new Error("Can no longer patch stale context");t.curr=Object.assign({},t.curr,e);for(const t of Object.entries(e)){const[e,n]=t;"patch"!==e&&(this[e]=n)}}}),n=!1}}(e),this.eventHub={didReceiveEvent:E(),willTransition:E(),didIgnoreEvent:E(),willExitState:E(),didEnterState:E()},this.events={didReceiveEvent:this.eventHub.didReceiveEvent.observable,willTransition:this.eventHub.willTransition.observable,didIgnoreEvent:this.eventHub.didIgnoreEvent.observable,willExitState:this.eventHub.willExitState.observable,didEnterState:this.eventHub.didEnterState.observable}}get context(){return this.currentContext.current}addState(e){if(0!==this.runningState)throw new Error("Already started");return this.states.add(e),this}onEnter(e,t){if(0!==this.runningState)throw new Error("Already started");if(this.enterFns.has(e))throw new Error(`enter/exit function for ${e} already exists`);return this.enterFns.set(e,t),this}onEnterAsync(e,t,n,r,o){return this.onEnter(e,(()=>{const e=new AbortController,a=e.signal,i=o?setTimeout((()=>{const e=new Error("Timed out");this.transition({type:"ASYNC_ERROR",reason:e},r)}),o):void 0;let s=!1;return t(this.currentContext.current,a).then((e=>{a.aborted||(s=!0,this.transition({type:"ASYNC_OK",data:e},n))}),(e=>{a.aborted||(s=!0,this.transition({type:"ASYNC_ERROR",reason:e},r))})),()=>{clearTimeout(i),s||e.abort()}}))}getStatesMatching(e){const t=[];if("*"===e)for(const e of this.states)t.push(e);else if(e.endsWith(".*")){const n=e.slice(0,-1);for(const e of this.states)e.startsWith(n)&&t.push(e)}else{const n=e;this.states.has(n)&&t.push(n)}if(0===t.length)throw new Error(`No states match ${JSON.stringify(e)}`);return t}addTransitions(e,t){if(0!==this.runningState)throw new Error("Already started");for(const n of this.getStatesMatching(e)){let r=this.allowedTransitions.get(n);void 0===r&&(r=new Map,this.allowedTransitions.set(n,r));for(const[o,a]of Object.entries(t)){if(r.has(o))throw new Error(`Trying to set transition "${o}" on "${n}" (via "${e}"), but a transition already exists there.`);const t=a;if(this.knownEventTypes.add(o),void 0!==t){const e="function"==typeof t?t:()=>t;r.set(o,e)}}}return this}addTimedTransition(e,t,n){return this.onEnter(e,(()=>{const e="function"==typeof t?t(this.currentContext.current):t,r=setTimeout((()=>{this.transition({type:"TIMER"},n)}),e);return()=>{clearTimeout(r)}}))}getTargetFn(e){return this.allowedTransitions.get(this.currentState)?.get(e)}exit(e){this.eventHub.willExitState.notify(this.currentState),this.currentContext.allowPatching((t=>{e=e??this.cleanupStack.length;for(let n=0;n<e;n++)this.cleanupStack.pop()?.(t)}))}enter(e){const t=function(e,t){const n=e.split(".");if(t<1||t>n.length+1)throw new Error("Invalid number of levels");const r=[];t>n.length&&r.push("*");for(let e=n.length-t+1;e<n.length;e++){const t=n.slice(0,e);t.length>0&&r.push(t.join(".")+".*")}return r.push(e),r}(this.currentState,e??this.currentState.split(".").length+1);this.currentContext.allowPatching((e=>{for(const n of t){const t=this.enterFns.get(n)?.(e);"function"==typeof t?this.cleanupStack.push(t):this.cleanupStack.push(null)}})),this.eventHub.didEnterState.notify(this.currentState)}send(e){if(!this.knownEventTypes.has(e.type))throw new Error(`Invalid event ${JSON.stringify(e.type)}`);if(2===this.runningState)return;const t=this.getTargetFn(e.type);if(void 0!==t)return this.transition(e,t);this.eventHub.didIgnoreEvent.notify(e)}transition(e,t){this.eventHub.didReceiveEvent.notify(e);const n=this.currentState,r=("function"==typeof t?t:()=>t)(e,this.currentContext.current);let o,a;if(null===r)return void this.eventHub.didIgnoreEvent.notify(e);if("string"==typeof r?o=r:(o=r.target,a=Array.isArray(r.effect)?r.effect:[r.effect]),!this.states.has(o))throw new Error(`Invalid next state name: ${JSON.stringify(o)}`);this.eventHub.willTransition.notify({from:n,to:o});const[i,s]=function(e,t){if(e===t)return[0,0];const n=e.split("."),r=t.split("."),o=Math.min(n.length,r.length);let a=0;for(;a<o&&n[a]===r[a];a++);return[n.length-a,r.length-a]}(this.currentState,o);if(i>0&&this.exit(i),this.currentStateOrNull=o,void 0!==a){const t=a;this.currentContext.allowPatching((n=>{for(const r of t)"function"==typeof r?r(n,e):n.patch(r)}))}s>0&&this.enter(s)}};function k(e){throw new Error(e)}function I(e){return null!==e&&"object"==typeof e&&"[object Object]"===Object.prototype.toString.call(e)}function F(e){return Object.entries(e)}function R(e){try{return JSON.parse(e)}catch(e){return}}function N(e){return JSON.parse(JSON.stringify(e))}function P(e){return e.filter((e=>null!=e))}function M(e){const t={...e};return Object.keys(e).forEach((e=>{const n=e;void 0===t[n]&&delete t[n]})),t}function j(e){return new Promise((t=>setTimeout(t,e)))}async function L(e,t,n){let r;const o=new Promise(((e,o)=>{r=setTimeout((()=>{o(new Error(n))}),t)}));return Promise.race([e,o]).finally((()=>clearTimeout(r)))}function z(e){let t=null;return()=>(null===t&&(t=e().catch((e=>{throw setTimeout((()=>{t=null}),5e3),e}))),t)}var H=(e=>(e[e.UPDATE_PRESENCE=100]="UPDATE_PRESENCE",e[e.USER_JOINED=101]="USER_JOINED",e[e.USER_LEFT=102]="USER_LEFT",e[e.BROADCASTED_EVENT=103]="BROADCASTED_EVENT",e[e.ROOM_STATE=104]="ROOM_STATE",e[e.INITIAL_STORAGE_STATE=200]="INITIAL_STORAGE_STATE",e[e.UPDATE_STORAGE=201]="UPDATE_STORAGE",e[e.REJECT_STORAGE_OP=299]="REJECT_STORAGE_OP",e[e.UPDATE_YDOC=300]="UPDATE_YDOC",e[e.THREAD_CREATED=400]="THREAD_CREATED",e[e.THREAD_DELETED=407]="THREAD_DELETED",e[e.THREAD_METADATA_UPDATED=401]="THREAD_METADATA_UPDATED",e[e.THREAD_UPDATED=408]="THREAD_UPDATED",e[e.COMMENT_CREATED=402]="COMMENT_CREATED",e[e.COMMENT_EDITED=403]="COMMENT_EDITED",e[e.COMMENT_DELETED=404]="COMMENT_DELETED",e[e.COMMENT_REACTION_ADDED=405]="COMMENT_REACTION_ADDED",e[e.COMMENT_REACTION_REMOVED=406]="COMMENT_REACTION_REMOVED",e))(H||{});function U(e){return 4999===e||e>=4e3&&e<4100}function W(e){return 1013===e||e>=4200&&e<4300}function V(e){const t=e.currentState;switch(t){case"@ok.connected":case"@ok.awaiting-pong":return"connected";case"@idle.initial":return"initial";case"@auth.busy":case"@auth.backoff":case"@connecting.busy":case"@connecting.backoff":case"@idle.zombie":return e.context.successCount>0?"reconnecting":"connecting";case"@idle.failed":return"disconnected";default:return v(0,"Unknown state")}}var $=[250,500,1e3,2e3,4e3,8e3,1e4],K=$[0]-1,q=[2e3,3e4,6e4,3e5],G=class extends Error{constructor(e){super(e)}},Z=class extends Error{constructor(e,t){super(e),this.code=t}};function X(e,t){return t.find((t=>t>e))??t[t.length-1]}function Y(e){e.patch({backoffDelay:X(e.backoffDelay,$)})}function J(e){e.patch({backoffDelay:X(e.backoffDelay,q)})}function Q(e){e.patch({successCount:0})}function ee(e,t){const n=2===e?A:1===e?x:()=>{};return()=>{n(t)}}function te(e){const t="Connection to Liveblocks websocket server";return n=>{e instanceof Error?x(`${t} could not be established. ${String(e)}`):x(oe(e)?`${t} closed prematurely (code: ${e.code}). Retrying in ${n.backoffDelay}ms.`:`${t} could not be established.`)}}function ne(e){const t=[`code: ${e.code}`];return e.reason&&t.push(`reason: ${e.reason}`),e=>{x(`Connection to Liveblocks websocket server closed (${t.join(", ")}). Retrying in ${e.backoffDelay}ms.`)}}var re=ee(1,"Connection to WebSocket closed permanently. Won't retry.");function oe(e){return!(e instanceof Error)&&"close"===e.type}var ae=e=>t=>t.patch(e);function ie(e,t){const n=E();n.pause();const r=E();function o(e,t){return()=>{const n=new Z(e,t);r.notify(n)}}const a=new T({successCount:0,authValue:null,socket:null,backoffDelay:K}).addState("@idle.initial").addState("@idle.failed").addState("@idle.zombie").addState("@auth.busy").addState("@auth.backoff").addState("@connecting.busy").addState("@connecting.backoff").addState("@ok.connected").addState("@ok.awaiting-pong");a.addTransitions("*",{RECONNECT:{target:"@auth.backoff",effect:[Y,Q]},DISCONNECT:"@idle.initial"}),a.onEnter("@idle.*",Q).addTransitions("@idle.*",{CONNECT:(e,t)=>null!==t.authValue?"@connecting.busy":"@auth.busy"}),a.addTransitions("@auth.backoff",{NAVIGATOR_ONLINE:{target:"@auth.busy",effect:ae({backoffDelay:K})}}).addTimedTransition("@auth.backoff",(e=>e.backoffDelay),"@auth.busy").onEnterAsync("@auth.busy",(()=>L(e.authenticate(),1e4,"Timed out during auth")),(e=>({target:"@connecting.busy",effect:ae({authValue:e.data})})),(e=>e.reason instanceof G?{target:"@idle.failed",effect:[ee(2,e.reason.message),o(e.reason.message,-1)]}:{target:"@auth.backoff",effect:[Y,ee(2,`Authentication failed: ${e.reason instanceof Error?e.reason.message:String(e.reason)}`)]}));const i=e=>a.send({type:"EXPLICIT_SOCKET_ERROR",event:e}),s=e=>a.send({type:"EXPLICIT_SOCKET_CLOSE",event:e}),u=e=>"pong"===e.data?a.send({type:"PONG"}):n.notify(e);function c(e){e&&(e.removeEventListener("error",i),e.removeEventListener("close",s),e.removeEventListener("message",u),e.close())}a.addTransitions("@connecting.backoff",{NAVIGATOR_ONLINE:{target:"@connecting.busy",effect:ae({backoffDelay:K})}}).addTimedTransition("@connecting.backoff",(e=>e.backoffDelay),"@connecting.busy").onEnterAsync("@connecting.busy",(async(n,r)=>{let o=null,a=null;return L(new Promise(((r,c)=>{if(null===n.authValue)throw new Error("No auth authValue");const l=e.createSocket(n.authValue);function d(e){o=e,l.removeEventListener("message",u),c(e)}a=l;const[f,h]=y();function p(e){104===R(e.data)?.type&&h()}t.waitForActorId||h(),l.addEventListener("message",u),t.waitForActorId&&l.addEventListener("message",p),l.addEventListener("error",d),l.addEventListener("close",d),l.addEventListener("open",(()=>{l.addEventListener("error",i),l.addEventListener("close",s);const e=()=>{l.removeEventListener("error",d),l.removeEventListener("close",d),l.removeEventListener("message",p)};f.then((()=>{r([l,e])}))}))})),1e4,"Timed out during websocket connection").then((([e,t])=>{if(t(),r.aborted)throw new Error("Aborted");if(o)throw o;return e})).catch((e=>{throw c(a),e}))}),(e=>({target:"@ok.connected",effect:ae({socket:e.data,backoffDelay:K})})),(e=>{const t=e.reason;if(t instanceof G)return{target:"@idle.failed",effect:[ee(2,t.message),o(t.message,-1)]};if(oe(t)){if(4109===t.code)return"@auth.busy";if(W(t.code))return{target:"@connecting.backoff",effect:[J,te(t)]};if(U(t.code))return{target:"@idle.failed",effect:[ee(2,t.reason),o(t.reason,t.code)]}}return{target:"@auth.backoff",effect:[Y,te(t)]}}));const l={target:"@ok.awaiting-pong",effect:e=>{e.socket?.send("ping")}},d=()=>"hidden"===("undefined"!=typeof document?document:void 0)?.visibilityState&&e.canZombie()?"@idle.zombie":l;if(a.addTimedTransition("@ok.connected",3e4,d).addTransitions("@ok.connected",{NAVIGATOR_OFFLINE:d,WINDOW_GOT_FOCUS:l}),a.addTransitions("@idle.zombie",{WINDOW_GOT_FOCUS:"@connecting.backoff"}),a.onEnter("@ok.*",(e=>{e.patch({successCount:e.successCount+1});const t=setTimeout(n.unpause,0);return e=>{c(e.socket),e.patch({socket:null}),clearTimeout(t),n.pause()}})).addTransitions("@ok.awaiting-pong",{PONG:"@ok.connected"}).addTimedTransition("@ok.awaiting-pong",2e3,{target:"@connecting.busy",effect:ee(1,"Received no pong from server, assume implicit connection loss.")}).addTransitions("@ok.*",{EXPLICIT_SOCKET_ERROR:(e,t)=>1===t.socket?.readyState?null:{target:"@connecting.backoff",effect:Y},EXPLICIT_SOCKET_CLOSE:e=>{return U(e.event.code)?{target:"@idle.failed",effect:[re,o(e.event.reason,e.event.code)]}:(t=e.event.code)>=4100&&t<4200?4109===e.event.code?"@auth.busy":{target:"@auth.backoff",effect:[Y,ne(e.event)]}:W(e.event.code)?{target:"@connecting.backoff",effect:[J,ne(e.event)]}:{target:"@connecting.backoff",effect:[Y,ne(e.event)]};var t}}),"undefined"!=typeof document){const e="undefined"!=typeof document?document:void 0,t="undefined"!=typeof window?window:void 0,n=t??e;a.onEnter("*",(r=>{function o(){a.send({type:"NAVIGATOR_OFFLINE"})}function i(){a.send({type:"NAVIGATOR_ONLINE"})}function s(){"visible"===e?.visibilityState&&a.send({type:"WINDOW_GOT_FOCUS"})}return t?.addEventListener("online",i),t?.addEventListener("offline",o),n?.addEventListener("visibilitychange",s),()=>{n?.removeEventListener("visibilitychange",s),t?.removeEventListener("online",i),t?.removeEventListener("offline",o),c(r.socket)}}))}const f=[],{statusDidChange:h,didConnect:p,didDisconnect:m,unsubscribe:v}=function(e){const t=E(),n=E(),r=E();let o=null;const a=e.events.didEnterState.subscribe((()=>{const a=V(e);a!==o&&t.notify(a),"connected"===o&&"connected"!==a?r.notify():"connected"!==o&&"connected"===a&&n.notify(),o=a}));return{statusDidChange:t.observable,didConnect:n.observable,didDisconnect:r.observable,unsubscribe:a}}(a);return f.push(v),t.enableDebugLogging&&f.push(function(e){const t=(new Date).getTime();function n(...n){x(`${(((new Date).getTime()-t)/1e3).toFixed(2)} [FSM #${e.id}]`,...n)}const r=[e.events.didReceiveEvent.subscribe((e=>n(`Event ${e.type}`))),e.events.willTransition.subscribe((({from:e,to:t})=>n("Transitioning",e,"→",t))),e.events.didIgnoreEvent.subscribe((e=>n("Ignored event",e.type,e,"(current state won't handle it)")))];return()=>{for(const e of r)e()}}(a)),a.start(),{machine:a,cleanups:f,events:{statusDidChange:h,didConnect:p,didDisconnect:m,onMessage:n.observable,onLiveblocksError:r.observable}}}function se(e){return e.includes("room:write")}function ue(e){return e.includes("comments:write")||e.includes("room:write")}function ce(e){const t=e.split(".");if(3!==t.length)throw new Error("Authentication error: invalid JWT token");const n=R(function(e){try{const t=e.replace(/-/g,"+").replace(/_/g,"/");return decodeURIComponent(atob(t).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""))}catch(t){return atob(e)}}(t[1]));if(!n||(!I(r=n)||"acc"!==r.k&&"id"!==r.k&&"sec-legacy"!==r.k))throw new Error("Authentication error: expected a valid token but did not get one. Hint: if you are using a callback, ensure the room is passed when creating the token. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientCallback");var r;return{raw:e,parsed:n}}function le(e){const t=function(e){const{publicApiKey:t,authEndpoint:n}=e;if(void 0!==n&&void 0!==t)throw new Error("You cannot simultaneously use `publicApiKey` and `authEndpoint` options. Please pick one and leave the other option unspecified. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient");if("string"==typeof t){if(t.startsWith("sk_"))throw new Error("Invalid `publicApiKey` option. The value you passed is a secret key, which should not be used from the client. Please only ever pass a public key here. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");if(!t.startsWith("pk_"))throw new Error("Invalid key. Please use the public key format: pk_<public key>. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");return{type:"public",publicApiKey:t}}if("string"==typeof n)return{type:"private",url:n};if("function"==typeof n)return{type:"custom",callback:n};if(void 0!==n)throw new Error("The `authEndpoint` option must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint");throw new Error("Invalid Liveblocks client options. Please provide either a `publicApiKey` or `authEndpoint` option. They cannot both be empty. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient")}(e),n=new Set,r=[],o=[],a=new Map;function i(e,t){return"comments:read"===e?t.includes("comments:read")||t.includes("comments:write")||t.includes("room:read")||t.includes("room:write"):"room:read"===e&&(t.includes("room:read")||t.includes("room:write"))}async function s(r){const o=e.polyfills?.fetch??("undefined"==typeof window?void 0:window.fetch);if("private"===t.type){if(void 0===o)throw new G("To use Liveblocks client in a non-DOM environment with a url as auth endpoint, you need to provide a fetch polyfill.");const e=ce((await async function(e,t,n){const r=await e(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const e=`${(await r.text()).trim()||"reason not provided in auth response"} (${r.status} returned by POST ${t})`;throw 401===r.status||403===r.status?new G(`Unauthorized: ${e}`):new Error(`Failed to authenticate: ${e}`)}let o;try{o=await r.json()}catch(e){throw new Error(`Expected a JSON response when doing a POST request on "${t}". ${String(e)}`)}if(!I(o)||"string"!=typeof o.token)throw new Error(`Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${t}", but got ${JSON.stringify(o)}`);const{token:a}=o;return{token:a}}(o,t.url,{room:r.roomId})).token);if(n.has(e.raw))throw new G("The same Liveblocks auth token was issued from the backend before. Caching Liveblocks tokens is not supported.");return e}if("custom"===t.type){const e=await t.callback(r.roomId);if(e&&"object"==typeof e){if("string"==typeof e.token){return ce(e.token)}if("string"==typeof e.error){const t=`Authentication failed: ${"reason"in e&&"string"==typeof e.reason?e.reason:"Forbidden"}`;throw"forbidden"===e.error?new G(t):new Error(t)}}throw new Error('Your authentication callback function should return a token, but it did not. Hint: the return value should look like: { token: "..." }')}throw new Error("Unexpected authentication type. Must be private or custom.")}return{reset:function(){n.clear(),r.length=0,o.length=0,a.clear()},getAuthValue:async function(e){if("public"===t.type)return{type:"public",publicApiKey:t.publicApiKey};const u=function(e){const t=Math.ceil(Date.now()/1e3);for(let n=r.length-1;n>=0;n--){const a=r[n];if(o[n]<=t)r.splice(n,1),o.splice(n,1);else{if("id"===a.parsed.k)return a;if("acc"===a.parsed.k){if(!e.roomId&&0===Object.entries(a.parsed.perms).length)return a;for(const[t,n]of Object.entries(a.parsed.perms))if(e.roomId){if(t.includes("*")&&e.roomId.startsWith(t.replace("*",""))||e.roomId===t&&i(e.requestedScope,n))return a}else if(t.includes("*")&&i(e.requestedScope,n))return a}}}}(e);if(void 0!==u)return{type:"secret",token:u};let c;e.roomId?(c=a.get(e.roomId),void 0===c&&(c=s(e),a.set(e.roomId,c))):(c=a.get("liveblocks-user-token"),void 0===c&&(c=s(e),a.set("liveblocks-user-token",c)));try{const t=await c,i=30,s=Math.floor(Date.now()/1e3)+(t.parsed.exp-t.parsed.iat)-i;return n.add(t.raw),"sec-legacy"!==t.parsed.k&&(r.push(t),o.push(s)),{type:"secret",token:t}}finally{e.roomId?a.delete(e.roomId):a.delete("liveblocks-user-token")}}}}var de=Symbol();function fe(e,...t){if("object"!=typeof e||null===e||Array.isArray(e))return JSON.stringify(e,...t);const n=Object.keys(e).sort().reduce(((t,n)=>(t[n]=e[n],t)),{});return JSON.stringify(n,...t)}E().observable;var he=class{constructor(e,t){this.queue=[],this.error=!1,this.callback=e,this.size=t.size??50,this.delay=t.delay}clearDelayTimeout(){void 0!==this.delayTimeoutId&&(clearTimeout(this.delayTimeoutId),this.delayTimeoutId=void 0)}schedule(){this.queue.length===this.size?this.flush():1===this.queue.length&&(this.clearDelayTimeout(),this.delayTimeoutId=setTimeout((()=>{this.flush()}),this.delay))}async flush(){if(0===this.queue.length)return;const e=this.queue.splice(0),t=e.map((e=>e.input));try{const n=await this.callback(t);this.error=!1,e.forEach(((t,r)=>{const o=n?.[r];Array.isArray(n)?e.length!==n.length?t.reject(new Error(`Callback must return an array of the same length as the number of provided items. Expected ${e.length}, but got ${n.length}.`)):o instanceof Error?t.reject(o):t.resolve(o):t.reject(new Error("Callback must return an array."))}))}catch(t){this.error=!0,e.forEach((e=>{e.reject(t)}))}}get(e){const t=this.queue.find((t=>fe(t.input)===fe(e)));if(t)return t.promise;const n=new class{constructor(e){this.input=e;const{promise:t,resolve:n,reject:r}=b();this.promise=t,this.resolve=n,this.reject=r}}(e);return this.queue.push(n),this.schedule(),n.promise}clear(){this.queue=[],this.error=!1,this.clearDelayTimeout()}};function pe(e){const t=new Map,n=E();function r(e){return fe(e)}function o(e,r){t.set(e,r),n.notify()}return{...n.observable,get:async function(n){const a=r(n);if(!t.has(a))try{o(a,{isLoading:!0});o(a,{isLoading:!1,data:await e.get(n)})}catch(e){o(a,{isLoading:!1,error:e})}},getState:function(e){const n=r(e);return t.get(n)},invalidate:function(e){if(Array.isArray(e))for(const n of e)t.delete(r(n));else t.clear();n.notify()},_cacheKeys:function(){return[...t.keys()]}}}function me(e){let t=!0,n=!1,r=e;const o=new Set;function a(){if(n){n=!1;for(const e of o)e(r)}}return{get:function(){return r},set:function(e){const o=r,i=e(o);i!==o&&(r=i,n=!0),t&&a()},batch:function(e){if(!1===t)return e();t=!1;try{e()}finally{t=!0,a()}},subscribe:function(e){return o.add(e),()=>{o.delete(e)}}}}function ve(e){const t=e.editedAt?new Date(e.editedAt):void 0,n=new Date(e.createdAt),r=e.reactions.map((e=>({...e,createdAt:new Date(e.createdAt)})));if(e.body)return{...e,reactions:r,createdAt:n,editedAt:t};{const o=new Date(e.deletedAt);return{...e,reactions:r,createdAt:n,editedAt:t,deletedAt:o}}}function ge(e){const t=new Date(e.createdAt),n=new Date(e.updatedAt),r=e.comments.map((e=>ve(e)));return{...e,createdAt:t,updatedAt:n,comments:r}}function ye(e){const t=new Date(e.notifiedAt),n=e.readAt?new Date(e.readAt):null;if("activities"in e){const r=e.activities.map((e=>({...e,createdAt:new Date(e.createdAt)})));return{...e,notifiedAt:t,readAt:n,activities:r}}return{...e,notifiedAt:t,readAt:n}}function be(e){const t=new Date(e.deletedAt);return{...e,deletedAt:t}}function Ee(e){const t=new Date(e.deletedAt);return{...e,deletedAt:t}}var we=class extends Error{constructor(e,t,n){super(e),this.message=e,this.status=t,this.details=n}},Ce=e=>e instanceof we&&e.status>=400&&e.status<500;async function De(e,t,n,r=Ce){const o=n.length>0?n[n.length-1]:0;let a=0;for(;;){a++;try{return await e()}catch(e){if(r(e))throw e;if(a>=t)throw new Error(`Failed after ${t} attempts: ${String(e)}`)}const i=n[a-1]??o;x(`Attempt ${a} was unsuccessful. Retrying in ${i} milliseconds.`),await j(i)}}function xe(e,t,n){const r=new URL(t,e);return void 0!==n&&(r.search=(n instanceof URLSearchParams?n:function(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))null!=r&&t.set(n,r.toString());return t}(n)).toString()),r.toString()}function Ae(e,...t){return e.reduce(((e,n,r)=>e+encodeURIComponent(t[r-1]??"")+n))}function _e(e){return"public"===e.type?e.publicApiKey:e.token.raw}var Be=class{constructor(e,t,n){this._baseUrl=e,this._fetchPolyfill=t,this._authCallback=n}async rawFetch(e,t,n){e.startsWith("/v2/c/")||k("This client can only be used to make /v2/c/* requests");const r=xe(this._baseUrl,e,n);return await this._fetchPolyfill(r,{...t,headers:{"Content-Type":"application/json; charset=utf-8",...t?.headers,Authorization:`Bearer ${_e(await this._authCallback())}`,"X-LB-Client":f}})}async fetch(e,t,n){const r=await this.rawFetch(e,t,n);if(!r.ok){let e;try{const t=await r.json();e=new we(t.message,r.status,t)}catch{e=new we(r.statusText,r.status)}throw e}let o;try{o=await r.json()}catch{o={}}return o}async rawGet(e,t,n){return await this.rawFetch(e,n,t)}async rawPost(e,t){return await this.rawFetch(e,{method:"POST",body:JSON.stringify(t)})}async rawDelete(e){return await this.rawFetch(e,{method:"DELETE"})}async get(e,t,n){return await this.fetch(e,n,t)}async post(e,t,n,r){return await this.fetch(e,{...n,method:"POST",body:JSON.stringify(t)},r)}async delete(e){return await this.fetch(e,{method:"DELETE"})}async putBlob(e,t,n,r){return await this.fetch(e,{...r,method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:t},n)}};function Oe({baseUrl:e,authManager:t,currentUserIdStore:n,fetchPolyfill:r}){const o=new Be(e,r,(async function(){const e=await t.getAuthValue({requestedScope:"comments:read"});if("secret"===e.type&&"acc"===e.token.parsed.k){const t=e.token.parsed.uid;n.set((()=>t))}return e}));const a=new he((async e=>{const t=e.flat();return await async function(e){await o.post(Ae`/v2/c/inbox-notifications/read`,{inboxNotificationIds:e})}(t),t}),{delay:50});return{getInboxNotifications:async function(e){const t=await o.get(Ae`/v2/c/inbox-notifications`,{cursor:e?.cursor,limit:50});return{inboxNotifications:t.inboxNotifications.map(ye),threads:t.threads.map(ge),nextCursor:t.meta.nextCursor,requestedAt:new Date(t.meta.requestedAt)}},getInboxNotificationsSince:async function(e){const t=await o.get(Ae`/v2/c/inbox-notifications/delta`,{since:e.since.toISOString()},{signal:e?.signal});return{inboxNotifications:{updated:t.inboxNotifications.map(ye),deleted:t.deletedInboxNotifications.map(Ee)},threads:{updated:t.threads.map(ge),deleted:t.deletedThreads.map(be)},requestedAt:new Date(t.meta.requestedAt)}},getUnreadInboxNotificationsCount:async function(){const{count:e}=await o.get(Ae`/v2/c/inbox-notifications/count`);return e},markAllInboxNotificationsAsRead:async function(){await o.post(Ae`/v2/c/inbox-notifications/read`,{inboxNotificationIds:"all"})},markInboxNotificationAsRead:async function(e){await a.get(e)},deleteAllInboxNotifications:async function(){await o.delete(Ae`/v2/c/inbox-notifications`)},deleteInboxNotification:async function(e){await o.delete(Ae`/v2/c/inbox-notifications/${e}`)},getUserThreads_experimental:async function(e){let t;e?.query&&(t=Dt(e.query));const n=await o.get(Ae`/v2/c/threads`,{cursor:e.cursor,query:t,limit:50});return{threads:n.threads.map(ge),inboxNotifications:n.inboxNotifications.map(ye),nextCursor:n.meta.nextCursor,requestedAt:new Date(n.meta.requestedAt)}},getUserThreadsSince_experimental:async function(e){const t=await o.get(Ae`/v2/c/threads/delta`,{since:e.since.toISOString()},{signal:e.signal});return{threads:{updated:t.threads.map(ge),deleted:t.deletedThreads.map(be)},inboxNotifications:{updated:t.inboxNotifications.map(ye),deleted:t.deletedInboxNotifications.map(Ee)},requestedAt:new Date(t.meta.requestedAt)}}}}function Se(e,t){let n=!1;const r={...e};return Object.keys(t).forEach((e=>{const o=e,a=t[o];r[o]!==a&&(void 0===a?delete r[o]:r[o]=a,n=!0)})),n?r:e}var Te=class{constructor(){this._ev=E()}get didInvalidate(){return this._ev.observable}invalidate(){null!==this._cache&&(this._cache=null,this._ev.notify())}get current(){return this._cache??(this._cache=this._toImmutable())}},ke=class extends Te{constructor(e){super(),this._value=e}_toImmutable(){return this._value}set(e){this._value!==e&&(this._value=e,this.invalidate())}},Ie=class extends Te{constructor(...e){super();const t=e.pop(),n=e;this._refs=n,this._refs.forEach((e=>{e.didInvalidate.subscribe((()=>this.invalidate()))})),this._transform=t}_toImmutable(){return this._transform(...this._refs.map((e=>e.current)))}},Fe=32,Re=126,Ne=je(0),Pe=je(1),Me=Ne+je(-1);function je(e){const t=Fe+(e<0?95+e:e);if(t<Fe||t>Re)throw new Error(`Invalid n value: ${e}`);return String.fromCharCode(t)}function Le(e,t){return void 0!==e&&void 0!==t?function(e,t){if(e<t)return ze(e,t);if(e>t)return ze(t,e);throw new Error("Cannot compute value between two equal positions")}(e,t):void 0!==e?function(e){for(let t=0;t<=e.length-1;t++){const n=e.charCodeAt(t);if(!(n>=Re))return e.substring(0,t)+String.fromCharCode(n+1)}return e+Pe}(e):void 0!==t?function(e){const t=e.length-1;for(let n=0;n<=t;n++){const r=e.charCodeAt(n);if(!(r<=Fe))return n===t?33===r?e.substring(0,n)+Me:e.substring(0,n)+String.fromCharCode(r-1):e.substring(0,n+1)}return Pe}(t):Pe}function ze(e,t){let n=0;const r=e.length,o=t.length;for(;;){const a=n<r?e.charCodeAt(n):Fe,i=n<o?t.charCodeAt(n):Re;if(a!==i){if(i-a==1){const t=n+1;let r=e.substring(0,t);r.length<t&&(r+=Ne.repeat(t-r.length));return r+ze(e.substring(t),"")}return He(e,n)+String.fromCharCode(i+a>>1)}n++}}function He(e,t){return t<e.length?e.substring(0,t):e+Ne.repeat(t-e.length)}function Ue(e){return function(e){if(""===e)return!1;const t=e.length-1,n=e.charCodeAt(t);if(n<33||n>Re)return!1;for(let n=0;n<t;n++){const t=e.charCodeAt(n);if(t<Fe||t>Re)return!1}return!0}(e)?e:function(e){const t=[];for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);t.push(r<Fe?Fe:r>Re?Re:r)}for(;t.length>0&&t[t.length-1]===Fe;)t.length--;return t.length>0?String.fromCharCode(...t):Pe}(e)}function We(e,t,n=Ue(t)){return Object.freeze({type:"HasParent",node:e,key:t,pos:n})}var Ve=Object.freeze({type:"NoParent"});var $e=class{constructor(){this._parent=Ve}_getParentKeyOrThrow(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":throw new Error("Parent key is missing");case"Orphaned":return this.parent.oldKey;default:return v(this.parent,"Unknown state")}}get _parentPos(){switch(this.parent.type){case"HasParent":return this.parent.pos;case"NoParent":throw new Error("Parent key is missing");case"Orphaned":return this.parent.oldPos;default:return v(this.parent,"Unknown state")}}get _pool(){return this.__pool}get roomId(){return this.__pool?this.__pool.roomId:null}get _id(){return this.__id}get parent(){return this._parent}get _parentKey(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":return null;case"Orphaned":return this.parent.oldKey;default:return v(this.parent,"Unknown state")}}_apply(e,t){return 5===e.type&&"HasParent"===this.parent.type?this.parent.node._detachChild(this):{modified:!1}}_setParentLink(e,t){switch(this.parent.type){case"HasParent":if(this.parent.node!==e)throw new Error("Cannot set parent: node already has a parent");return void(this._parent=We(e,t));case"Orphaned":case"NoParent":return void(this._parent=We(e,t));default:return v(this.parent,"Unknown state")}}_attach(e,t){if(this.__id||this.__pool)throw new Error("Cannot attach node: already attached");t.addNode(e,this),this.__id=e,this.__pool=t}_detach(){switch(this.__pool&&this.__id&&this.__pool.deleteNode(this.__id),this.parent.type){case"HasParent":this._parent=function(e,t=Ue(e)){return Object.freeze({type:"Orphaned",oldKey:e,oldPos:t})}(this.parent.key,this.parent.pos);break;case"NoParent":this._parent=Ve;break;case"Orphaned":break;default:v(this.parent,"Unknown state")}this.__pool=void 0}invalidate(){void 0===this._cachedImmutable&&void 0===this._cachedTreeNode||(this._cachedImmutable=void 0,this._cachedTreeNode=void 0,"HasParent"===this.parent.type&&this.parent.node.invalidate())}toTreeNode(e){return void 0!==this._cachedTreeNode&&this._cachedTreeNodeKey===e||(this._cachedTreeNodeKey=e,this._cachedTreeNode=this._toTreeNode(e)),this._cachedTreeNode}toImmutable(){return void 0===this._cachedImmutable&&(this._cachedImmutable=this._toImmutable()),this._cachedImmutable}};function Ke(e){return 0===e.type&&!function(e){return void 0!==e.parentId&&void 0!==e.parentKey}(e)}var qe=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce(((e,t)=>e+((t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t<63?"_":"-")),""),Ge=class e extends $e{constructor(e){super(),this._data=e}get data(){return this._data}static _deserialize([t,n],r,o){const a=new e(n.data);return a._attach(t,o),a}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize register if parentId or parentKey is undefined");return[{type:8,opId:n?.generateOpId(),id:this._id,parentId:e,parentKey:t,data:this.data}]}_serialize(){if("HasParent"!==this.parent.type)throw new Error("Cannot serialize LiveRegister if parent is missing");return{type:3,parentId:g(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key,data:this.data}}_attachChild(e){throw new Error("Method not implemented.")}_detachChild(e){throw new Error("Method not implemented.")}_apply(e,t){return super._apply(e,t)}_toTreeNode(e){return{type:"Json",id:this._id??qe(),key:e,payload:this._data}}_toImmutable(){return this._data}clone(){return N(this.data)}};function Ze(e,t){const n=e._parentPos,r=t._parentPos;return n===r?0:n<r?-1:1}var Xe=class e extends $e{constructor(e){let t;super(),this._items=[],this._implicitlyDeletedItems=new WeakSet,this._unacknowledgedSets=new Map;for(const n of e){const e=Le(t),r=mt(n);r._setParentLink(this,e),this._items.push(r),t=e}}static _deserialize([t],n,r){const o=new e([]);o._attach(t,r);const a=n.get(t);if(void 0===a)return o;for(const[e,t]of a){const a=ct([e,t],n,r);a._setParentLink(o,t.parentKey),o._insertAndSort(a)}return o}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize item is not attached");const r=[],o={id:this._id,opId:n?.generateOpId(),type:2,parentId:e,parentKey:t};r.push(o);for(const e of this._items){const t=e._getParentKeyOrThrow(),o=rt(e._toOps(this._id,t,n),void 0),a=o[0].opId;void 0!==a&&this._unacknowledgedSets.set(t,a),r.push(...o)}return r}_insertAndSort(e){this._items.push(e),this._sortItems()}_sortItems(){this._items.sort(Ze),this.invalidate()}_indexOfPosition(e){return this._items.findIndex((t=>t._getParentKeyOrThrow()===e))}_attach(e,t){super._attach(e,t);for(const e of this._items)e._attach(t.generateId(),t)}_detach(){super._detach();for(const e of this._items)e._detach()}_applySetRemote(e){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const{id:t,parentKey:n}=e,r=it(e);r._attach(t,this._pool),r._setParentLink(this,n);const o=e.deletedId,a=this._indexOfPosition(n);if(-1!==a){const t=this._items[a];if(t._id===o)return t._detach(),this._items[a]=r,{modified:Je(this,[Qe(a,r)]),reverse:[]};{this._implicitlyDeletedItems.add(t),this._items[a]=r;const n=[Qe(a,r)],o=this._detachItemAssociatedToSetOperation(e.deletedId);return o&&n.push(o),{modified:Je(this,n),reverse:[]}}}{const t=[],o=this._detachItemAssociatedToSetOperation(e.deletedId);return o&&t.push(o),this._insertAndSort(r),t.push(tt(this._indexOfPosition(n),r)),{reverse:[],modified:Je(this,t)}}}_applySetAck(e){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const t=[],n=this._detachItemAssociatedToSetOperation(e.deletedId);n&&t.push(n);const r=this._unacknowledgedSets.get(e.parentKey);if(void 0!==r){if(r!==e.opId)return 0===t.length?{modified:!1}:{modified:Je(this,t),reverse:[]};this._unacknowledgedSets.delete(e.parentKey)}const o=this._indexOfPosition(e.parentKey),a=this._items.find((t=>t._id===e.id));if(void 0!==a){if(a._parentKey===e.parentKey)return{modified:t.length>0&&Je(this,t),reverse:[]};if(-1!==o){this._implicitlyDeletedItems.add(this._items[o]);const[e]=this._items.splice(o,1);t.push(et(o,e))}const n=this._items.indexOf(a);a._setParentLink(this,e.parentKey),this._sortItems();const r=this._items.indexOf(a);return r!==n&&t.push(nt(n,r,a)),{modified:t.length>0&&Je(this,t),reverse:[]}}{const n=this._pool.getNode(e.id);if(n&&this._implicitlyDeletedItems.has(n)){n._setParentLink(this,e.parentKey),this._implicitlyDeletedItems.delete(n),this._insertAndSort(n);const r=this._items.indexOf(n);return{modified:Je(this,[-1===o?tt(r,n):Qe(r,n),...t]),reverse:[]}}{-1!==o&&this._items.splice(o,1);const{newItem:n,newIndex:r}=this._createAttachItemAndSort(e,e.parentKey);return{modified:Je(this,[-1===o?tt(r,n):Qe(r,n),...t]),reverse:[]}}}}_detachItemAssociatedToSetOperation(e){if(void 0===e||void 0===this._pool)return null;const t=this._pool.getNode(e);if(void 0===t)return null;const n=this._detachChild(t);return!1===n.modified?null:n.modified.updates[0]}_applyRemoteInsert(e){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const t=Ue(e.parentKey),n=this._indexOfPosition(t);-1!==n&&this._shiftItemPosition(n,t);const{newItem:r,newIndex:o}=this._createAttachItemAndSort(e,t);return{modified:Je(this,[tt(o,r)]),reverse:[]}}_applyInsertAck(e){const t=this._items.find((t=>t._id===e.id)),n=Ue(e.parentKey),r=this._indexOfPosition(n);if(t){if(t._parentKey===n)return{modified:!1};{const e=this._items.indexOf(t);-1!==r&&this._shiftItemPosition(r,n),t._setParentLink(this,n),this._sortItems();const o=this._indexOfPosition(n);return o===e?{modified:!1}:{modified:Je(this,[nt(e,o,t)]),reverse:[]}}}{const t=g(this._pool).getNode(e.id);if(t&&this._implicitlyDeletedItems.has(t)){t._setParentLink(this,n),this._implicitlyDeletedItems.delete(t),this._insertAndSort(t);return{modified:Je(this,[tt(this._indexOfPosition(n),t)]),reverse:[]}}{-1!==r&&this._shiftItemPosition(r,n);const{newItem:t,newIndex:o}=this._createAttachItemAndSort(e,n);return{modified:Je(this,[tt(o,t)]),reverse:[]}}}}_applyInsertUndoRedo(e){const{id:t,parentKey:n}=e,r=it(e);if(void 0!==this._pool?.getNode(t))return{modified:!1};r._attach(t,g(this._pool)),r._setParentLink(this,n);const o=this._indexOfPosition(n);let a=n;if(-1!==o){const e=this._items[o]?._parentPos,t=this._items[o+1]?._parentPos;a=Le(e,t),r._setParentLink(this,a)}this._insertAndSort(r);return{modified:Je(this,[tt(this._indexOfPosition(a),r)]),reverse:[{type:5,id:t}]}}_applySetUndoRedo(e){const{id:t,parentKey:n}=e,r=it(e);if(void 0!==this._pool?.getNode(t))return{modified:!1};this._unacknowledgedSets.set(n,g(e.opId));const o=this._indexOfPosition(n);r._attach(t,g(this._pool)),r._setParentLink(this,n);const a=n;if(-1!==o){const t=this._items[o];t._detach(),this._items[o]=r;const a=rt(t._toOps(g(this._id),n,this._pool),e.id),i=[Qe(o,r)],s=this._detachItemAssociatedToSetOperation(e.deletedId);return s&&i.push(s),{modified:Je(this,i),reverse:a}}this._insertAndSort(r),this._detachItemAssociatedToSetOperation(e.deletedId);return{reverse:[{type:5,id:t}],modified:Je(this,[tt(this._indexOfPosition(a),r)])}}_attachChild(e,t){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");let n;return n="set"===e.intent?1===t?this._applySetRemote(e):2===t?this._applySetAck(e):this._applySetUndoRedo(e):1===t?this._applyRemoteInsert(e):2===t?this._applyInsertAck(e):this._applyInsertUndoRedo(e),!1!==n.modified&&this.invalidate(),n}_detachChild(e){if(e){const t=g(e._parentKey),n=e._toOps(g(this._id),t,this._pool),r=this._items.indexOf(e);if(-1===r)return{modified:!1};const[o]=this._items.splice(r,1);return this.invalidate(),e._detach(),{modified:Je(this,[et(r,o)]),reverse:n}}return{modified:!1}}_applySetChildKeyRemote(e,t){if(this._implicitlyDeletedItems.has(t)){this._implicitlyDeletedItems.delete(t),t._setParentLink(this,e),this._insertAndSort(t);return{modified:Je(this,[tt(this._items.indexOf(t),t)]),reverse:[]}}if(e===t._parentKey)return{modified:!1};const n=this._indexOfPosition(e);if(-1===n){const n=this._items.indexOf(t);t._setParentLink(this,e),this._sortItems();const r=this._items.indexOf(t);return r===n?{modified:!1}:{modified:Je(this,[nt(n,r,t)]),reverse:[]}}{this._items[n]._setParentLink(this,Le(e,this._items[n+1]?._parentPos));const r=this._items.indexOf(t);t._setParentLink(this,e),this._sortItems();const o=this._items.indexOf(t);return o===r?{modified:!1}:{modified:Je(this,[nt(r,o,t)]),reverse:[]}}}_applySetChildKeyAck(e,t){const n=g(t._parentKey);if(this._implicitlyDeletedItems.has(t)){const n=this._indexOfPosition(e);return this._implicitlyDeletedItems.delete(t),-1!==n&&this._items[n]._setParentLink(this,Le(e,this._items[n+1]?._parentPos)),t._setParentLink(this,e),this._insertAndSort(t),{modified:!1}}{if(e===n)return{modified:!1};const r=this._items.indexOf(t),o=this._indexOfPosition(e);-1!==o&&this._items[o]._setParentLink(this,Le(e,this._items[o+1]?._parentPos)),t._setParentLink(this,e),this._sortItems();const a=this._items.indexOf(t);return r===a?{modified:!1}:{modified:Je(this,[nt(r,a,t)]),reverse:[]}}}_applySetChildKeyUndoRedo(e,t){const n=g(t._parentKey),r=this._items.indexOf(t),o=this._indexOfPosition(e);-1!==o&&this._items[o]._setParentLink(this,Le(e,this._items[o+1]?._parentPos)),t._setParentLink(this,e),this._sortItems();const a=this._items.indexOf(t);return r===a?{modified:!1}:{modified:Je(this,[nt(r,a,t)]),reverse:[{type:1,id:g(t._id),parentKey:n}]}}_setChildKey(e,t,n){return 1===n?this._applySetChildKeyRemote(e,t):2===n?this._applySetChildKeyAck(e,t):this._applySetChildKeyUndoRedo(e,t)}_apply(e,t){return super._apply(e,t)}_serialize(){if("HasParent"!==this.parent.type)throw new Error("Cannot serialize LiveList if parent is missing");return{type:1,parentId:g(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get length(){return this._items.length}push(e){return this._pool?.assertStorageIsWritable(),this.insert(e,this.length)}insert(e,t){if(this._pool?.assertStorageIsWritable(),t<0||t>this._items.length)throw new Error(`Cannot insert list item at index "${t}". index should be between 0 and ${this._items.length}`);const n=Le(this._items[t-1]?this._items[t-1]._parentPos:void 0,this._items[t]?this._items[t]._parentPos:void 0),r=mt(e);if(r._setParentLink(this,n),this._insertAndSort(r),this._pool&&this._id){const e=this._pool.generateId();r._attach(e,this._pool),this._pool.dispatch(r._toOps(this._id,n,this._pool),[{type:5,id:e}],new Map([[this._id,Je(this,[tt(t,r)])]]))}}move(e,t){if(this._pool?.assertStorageIsWritable(),t<0)throw new Error("targetIndex cannot be less than 0");if(t>=this._items.length)throw new Error("targetIndex cannot be greater or equal than the list length");if(e<0)throw new Error("index cannot be less than 0");if(e>=this._items.length)throw new Error("index cannot be greater or equal than the list length");let n=null,r=null;e<t?(r=t===this._items.length-1?void 0:this._items[t+1]._parentPos,n=this._items[t]._parentPos):(r=this._items[t]._parentPos,n=0===t?void 0:this._items[t-1]._parentPos);const o=Le(n,r),a=this._items[e],i=a._getParentKeyOrThrow();if(a._setParentLink(this,o),this._sortItems(),this._pool&&this._id){const n=new Map([[this._id,Je(this,[nt(e,t,a)])]]);this._pool.dispatch([{type:1,id:g(a._id),opId:this._pool.generateOpId(),parentKey:o}],[{type:1,id:g(a._id),parentKey:i}],n)}}delete(e){if(this._pool?.assertStorageIsWritable(),e<0||e>=this._items.length)throw new Error(`Cannot delete list item at index "${e}". index should be between 0 and ${this._items.length-1}`);const t=this._items[e];t._detach();const[n]=this._items.splice(e,1);if(this.invalidate(),this._pool){const r=t._id;if(r){const o=new Map;o.set(g(this._id),Je(this,[et(e,n)])),this._pool.dispatch([{id:r,opId:this._pool.generateOpId(),type:5}],t._toOps(g(this._id),t._getParentKeyOrThrow()),o)}}}clear(){if(this._pool?.assertStorageIsWritable(),this._pool){const e=[],t=[],n=[];for(const r of this._items){r._detach();const o=r._id;o&&(e.push({type:5,id:o,opId:this._pool.generateOpId()}),t.push(...r._toOps(g(this._id),r._getParentKeyOrThrow())),n.push(et(0,r)))}this._items=[],this.invalidate();const r=new Map;r.set(g(this._id),Je(this,n)),this._pool.dispatch(e,t,r)}else{for(const e of this._items)e._detach();this._items=[],this.invalidate()}}set(e,t){if(this._pool?.assertStorageIsWritable(),e<0||e>=this._items.length)throw new Error(`Cannot set list item at index "${e}". index should be between 0 and ${this._items.length-1}`);const n=this._items[e],r=n._getParentKeyOrThrow(),o=n._id;n._detach();const a=mt(t);if(a._setParentLink(this,r),this._items[e]=a,this.invalidate(),this._pool&&this._id){const t=this._pool.generateId();a._attach(t,this._pool);const i=new Map;i.set(this._id,Je(this,[Qe(e,a)]));const s=rt(a._toOps(this._id,r,this._pool),o);this._unacknowledgedSets.set(r,g(s[0].opId));const u=rt(n._toOps(this._id,r,void 0),t);this._pool.dispatch(s,u,i)}}toArray(){return this._items.map((e=>pt(e)))}every(e){return this.toArray().every(e)}filter(e){return this.toArray().filter(e)}find(e){return this.toArray().find(e)}findIndex(e){return this.toArray().findIndex(e)}forEach(e){return this.toArray().forEach(e)}get(e){if(!(e<0||e>=this._items.length))return pt(this._items[e])}indexOf(e,t){return this.toArray().indexOf(e,t)}lastIndexOf(e,t){return this.toArray().lastIndexOf(e,t)}map(e){return this._items.map(((t,n)=>e(pt(t),n)))}some(e){return this.toArray().some(e)}[Symbol.iterator](){return new Ye(this._items)}_createAttachItemAndSort(e,t){const n=it(e);n._attach(e.id,g(this._pool)),n._setParentLink(this,t),this._insertAndSort(n);return{newItem:n,newIndex:this._indexOfPosition(t)}}_shiftItemPosition(e,t){const n=Le(t,this._items.length>e+1?this._items[e+1]?._parentPos:void 0);this._items[e]._setParentLink(this,n)}_toTreeNode(e){return{type:"LiveList",id:this._id??qe(),key:e,payload:this._items.map(((e,t)=>e.toTreeNode(t.toString())))}}toImmutable(){return super.toImmutable()}_toImmutable(){const e=this._items.map((e=>e.toImmutable()));return e}clone(){return new e(this._items.map((e=>e.clone())))}},Ye=class{constructor(e){this._innerIterator=e[Symbol.iterator]()}[Symbol.iterator](){return this}next(){const e=this._innerIterator.next();if(e.done)return{done:!0,value:void 0};return{value:pt(e.value)}}};function Je(e,t){return{node:e,type:"LiveList",updates:t}}function Qe(e,t){return{index:e,type:"set",item:t instanceof Ge?t.data:t}}function et(e,t){return{type:"delete",index:e,deletedItem:t instanceof Ge?t.data:t}}function tt(e,t){return{index:e,type:"insert",item:t instanceof Ge?t.data:t}}function nt(e,t,n){return{type:"move",index:t,item:n instanceof Ge?n.data:n,previousIndex:e}}function rt(e,t){return e.map(((e,n)=>{if(0===n){return{...e,intent:"set",deletedId:t}}return e}))}var ot=class e extends $e{constructor(e){if(super(),this.unacknowledgedSet=new Map,e){const t=[];for(const[n,r]of e){const e=mt(r);e._setParentLink(this,n),t.push([n,e])}this._map=new Map(t)}else this._map=new Map}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize item is not attached");const r=[],o={id:this._id,opId:n?.generateOpId(),type:7,parentId:e,parentKey:t};r.push(o);for(const[e,t]of this._map)r.push(...t._toOps(this._id,e,n));return r}static _deserialize([t,n],r,o){const a=new e;a._attach(t,o);const i=r.get(t);if(void 0===i)return a;for(const[e,t]of i){const n=ct([e,t],r,o);n._setParentLink(a,t.parentKey),a._map.set(t.parentKey,n),a.invalidate()}return a}_attach(e,t){super._attach(e,t);for(const[e,n]of this._map)ft(n)&&n._attach(t.generateId(),t)}_attachChild(e,t){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const{id:n,parentKey:r,opId:o}=e,a=r,i=it(e);if(void 0!==this._pool.getNode(n))return{modified:!1};if(2===t){const e=this.unacknowledgedSet.get(a);if(e===o)return this.unacknowledgedSet.delete(a),{modified:!1};if(void 0!==e)return{modified:!1}}else 1===t&&this.unacknowledgedSet.delete(a);const s=this._map.get(a);let u;if(s){const e=g(this._id);u=s._toOps(e,a),s._detach()}else u=[{type:5,id:n}];return i._setParentLink(this,a),i._attach(n,this._pool),this._map.set(a,i),this.invalidate(),{modified:{node:this,type:"LiveMap",updates:{[a]:{type:"update"}}},reverse:u}}_detach(){super._detach();for(const e of this._map.values())e._detach()}_detachChild(e){const t=g(this._id),n=g(e._parentKey),r=e._toOps(t,n,this._pool);for(const[t,n]of this._map)n===e&&(this._map.delete(t),this.invalidate());e._detach();return{modified:{node:this,type:"LiveMap",updates:{[n]:{type:"delete"}}},reverse:r}}_serialize(){if("HasParent"!==this.parent.type)throw new Error("Cannot serialize LiveMap if parent is missing");return{type:2,parentId:g(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get(e){const t=this._map.get(e);if(void 0!==t)return pt(t)}set(e,t){this._pool?.assertStorageIsWritable();const n=this._map.get(e);n&&n._detach();const r=mt(t);if(r._setParentLink(this,e),this._map.set(e,r),this.invalidate(),this._pool&&this._id){const t=this._pool.generateId();r._attach(t,this._pool);const o=new Map;o.set(this._id,{node:this,type:"LiveMap",updates:{[e]:{type:"update"}}});const a=r._toOps(this._id,e,this._pool);this.unacknowledgedSet.set(e,g(a[0].opId)),this._pool.dispatch(r._toOps(this._id,e,this._pool),n?n._toOps(this._id,e):[{type:5,id:t}],o)}}get size(){return this._map.size}has(e){return this._map.has(e)}delete(e){this._pool?.assertStorageIsWritable();const t=this._map.get(e);if(void 0===t)return!1;if(t._detach(),this._map.delete(e),this.invalidate(),this._pool&&t._id){const n=g(this._id),r=new Map;r.set(n,{node:this,type:"LiveMap",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:5,id:t._id,opId:this._pool.generateOpId()}],t._toOps(n,e),r)}return!0}entries(){const e=this._map.entries();return{[Symbol.iterator](){return this},next(){const t=e.next();if(t.done)return{done:!0,value:void 0};return{value:[t.value[0],pt(t.value[1])]}}}}[Symbol.iterator](){return this.entries()}keys(){return this._map.keys()}values(){const e=this._map.values();return{[Symbol.iterator](){return this},next(){const t=e.next();if(t.done)return{done:!0,value:void 0};return{value:pt(t.value)}}}}forEach(e){for(const t of this)e(t[1],t[0],this)}_toTreeNode(e){return{type:"LiveMap",id:this._id??qe(),key:e,payload:Array.from(this._map.entries()).map((([e,t])=>t.toTreeNode(e)))}}toImmutable(){return super.toImmutable()}_toImmutable(){const e=new Map;for(const[t,n]of this._map)e.set(t,n.toImmutable());return e}clone(){return new e(Array.from(this._map).map((([e,t])=>[e,t.clone()])))}},at=class e extends $e{static _buildRootAndParentToChildren(e){const t=new Map;let n=null;for(const[r,o]of e)if(Ke(o))n=[r,o];else{const e=[r,o],n=t.get(o.parentId);void 0!==n?n.push(e):t.set(o.parentId,[e])}if(null===n)throw new Error("Root can't be null");return[n,t]}static _fromItems(t,n){const[r,o]=e._buildRootAndParentToChildren(t);return e._deserialize(r,o,n)}constructor(e={}){super(),this._propToLastUpdate=new Map;const t=M(e);for(const e of Object.keys(t)){const n=t[e];ft(n)&&n._setParentLink(this,e)}this._map=new Map(Object.entries(t))}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize item is not attached");const r=n?.generateOpId(),o=[],a={type:4,id:this._id,opId:r,parentId:e,parentKey:t,data:{}};o.push(a);for(const[e,t]of this._map)ft(t)?o.push(...t._toOps(this._id,e,n)):a.data[e]=t;return o}static _deserialize([t,n],r,o){const a=new e(n.data);return a._attach(t,o),this._deserializeChildren(a,r,o)}static _deserializeChildren(e,t,n){const r=t.get(g(e._id));if(void 0===r)return e;for(const[o,a]of r){const r=lt([o,a],t,n);dt(r)&&r._setParentLink(e,a.parentKey),e._map.set(a.parentKey,r),e.invalidate()}return e}_attach(e,t){super._attach(e,t);for(const[e,n]of this._map)ft(n)&&n._attach(t.generateId(),t)}_attachChild(e,t){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const{id:n,opId:r,parentKey:o}=e,a=st(e);if(void 0!==this._pool.getNode(n))return this._propToLastUpdate.get(o)===r&&this._propToLastUpdate.delete(o),{modified:!1};if(0===t)this._propToLastUpdate.set(o,g(r));else if(void 0!==this._propToLastUpdate.get(o))return this._propToLastUpdate.get(o)===r?(this._propToLastUpdate.delete(o),{modified:!1}):{modified:!1};const i=g(this._id),s=this._map.get(o);let u;return ft(s)?(u=s._toOps(i,o),s._detach()):u=void 0===s?[{type:6,id:i,key:o}]:[{type:3,id:i,data:{[o]:s}}],this._map.set(o,a),this.invalidate(),dt(a)&&(a._setParentLink(this,o),a._attach(n,this._pool)),{reverse:u,modified:{node:this,type:"LiveObject",updates:{[o]:{type:"update"}}}}}_detachChild(e){if(e){const t=g(this._id),n=g(e._parentKey),r=e._toOps(t,n,this._pool);for(const[t,n]of this._map)n===e&&(this._map.delete(t),this.invalidate());e._detach();return{modified:{node:this,type:"LiveObject",updates:{[n]:{type:"delete"}}},reverse:r}}return{modified:!1}}_detach(){super._detach();for(const e of this._map.values())ft(e)&&e._detach()}_apply(e,t){return 3===e.type?this._applyUpdate(e,t):6===e.type?this._applyDeleteObjectKey(e,t):super._apply(e,t)}_serialize(){const e={};for(const[t,n]of this._map)ft(n)||(e[t]=n);return"HasParent"===this.parent.type&&this.parent.node._id?{type:0,parentId:this.parent.node._id,parentKey:this.parent.key,data:e}:{type:0,data:e}}_applyUpdate(e,t){let n=!1;const r=g(this._id),o=[],a={type:3,id:r,data:{}};for(const t in e.data){const e=this._map.get(t);ft(e)?(o.push(...e._toOps(r,t)),e._detach()):void 0!==e?a.data[t]=e:void 0===e&&o.push({type:6,id:r,key:t})}const i={};for(const r in e.data){const o=e.data[r];if(void 0===o)continue;if(t)this._propToLastUpdate.set(r,g(e.opId));else{if(void 0!==this._propToLastUpdate.get(r)){if(this._propToLastUpdate.get(r)===e.opId){this._propToLastUpdate.delete(r);continue}continue}n=!0}const a=this._map.get(r);ft(a)&&a._detach(),n=!0,i[r]={type:"update"},this._map.set(r,o),this.invalidate()}return 0!==Object.keys(a.data).length&&o.unshift(a),n?{modified:{node:this,type:"LiveObject",updates:i},reverse:o}:{modified:!1}}_applyDeleteObjectKey(e,t){const n=e.key;if(!1===this._map.has(n))return{modified:!1};if(!t&&void 0!==this._propToLastUpdate.get(n))return{modified:!1};const r=this._map.get(n),o=g(this._id);let a=[];return ft(r)?(a=r._toOps(o,e.key),r._detach()):void 0!==r&&(a=[{type:3,id:o,data:{[n]:r}}]),this._map.delete(n),this.invalidate(),{modified:{node:this,type:"LiveObject",updates:{[e.key]:{type:"delete"}}},reverse:a}}toObject(){return Object.fromEntries(this._map)}set(e,t){this._pool?.assertStorageIsWritable(),this.update({[e]:t})}get(e){return this._map.get(e)}delete(e){this._pool?.assertStorageIsWritable();const t=e,n=this._map.get(t);if(void 0===n)return;if(void 0===this._pool||void 0===this._id)return ft(n)&&n._detach(),this._map.delete(t),void this.invalidate();let r;ft(n)?(n._detach(),r=n._toOps(this._id,t)):r=[{type:3,data:{[t]:n},id:this._id}],this._map.delete(t),this.invalidate();const o=new Map;o.set(this._id,{node:this,type:"LiveObject",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:6,key:t,id:this._id,opId:this._pool.generateOpId()}],r,o)}update(e){if(this._pool?.assertStorageIsWritable(),void 0===this._pool||void 0===this._id){for(const t in e){const n=e[t];if(void 0===n)continue;const r=this._map.get(t);ft(r)&&r._detach(),ft(n)&&n._setParentLink(this,t),this._map.set(t,n),this.invalidate()}return}const t=[],n=[],r=this._pool.generateOpId(),o={},a={id:this._id,type:3,data:{}},i={};for(const s in e){const u=e[s];if(void 0===u)continue;const c=this._map.get(s);if(ft(c)?(n.push(...c._toOps(this._id,s)),c._detach()):void 0===c?n.push({type:6,id:this._id,key:s}):a.data[s]=c,ft(u)){u._setParentLink(this,s),u._attach(this._pool.generateId(),this._pool);const e=u._toOps(this._id,s,this._pool),n=e.find((e=>e.parentId===this._id));n&&this._propToLastUpdate.set(s,g(n.opId)),t.push(...e)}else o[s]=u,this._propToLastUpdate.set(s,r);this._map.set(s,u),this.invalidate(),i[s]={type:"update"}}0!==Object.keys(a.data).length&&n.unshift(a),0!==Object.keys(o).length&&t.unshift({opId:r,id:this._id,type:3,data:o});const s=new Map;s.set(this._id,{node:this,type:"LiveObject",updates:i}),this._pool.dispatch(t,n,s)}toImmutable(){return super.toImmutable()}toTreeNode(e){return super.toTreeNode(e)}_toTreeNode(e){const t=this._id??qe();return{type:"LiveObject",id:t,key:e,payload:Array.from(this._map.entries()).map((([e,n])=>ft(n)?n.toTreeNode(e):{type:"Json",id:`${t}:${e}`,key:e,payload:n}))}}_toImmutable(){const e={};for(const[t,n]of this._map)e[t]=dt(n)?n.toImmutable():n;return e}clone(){return new e(Object.fromEntries(Array.from(this._map).map((([e,t])=>[e,dt(t)?t.clone():N(t)]))))}};function it(e){return mt(st(e))}function st(e){switch(e.type){case 8:return e.data;case 4:return new at(e.data);case 7:return new ot;case 2:return new Xe([]);default:return v(0,"Unknown creation Op")}}function ut(e,t){return e===t||"HasParent"===e.parent.type&&ut(e.parent.node,t)}function ct([e,t],n,r){switch(t.type){case 0:return at._deserialize([e,t],n,r);case 1:return Xe._deserialize([e,t],n,r);case 2:return ot._deserialize([e,t],n,r);case 3:return Ge._deserialize([e,t],n,r);default:throw new Error("Unexpected CRDT type")}}function lt([e,t],n,r){switch(t.type){case 0:return at._deserialize([e,t],n,r);case 1:return Xe._deserialize([e,t],n,r);case 2:return ot._deserialize([e,t],n,r);case 3:return t.data;default:throw new Error("Unexpected CRDT type")}}function dt(e){return ht(e)||function(e){return e instanceof ot}(e)||function(e){return e instanceof at}(e)}function ft(e){return dt(e)||function(e){return e instanceof Ge}(e)}function ht(e){return e instanceof Xe}function pt(e){return e instanceof Ge?e.data:e instanceof Xe||e instanceof ot||e instanceof at?e:v(0,"Unknown AbstractCrdt")}function mt(e){return e instanceof at||e instanceof ot||e instanceof Xe?e:new Ge(e)}function vt(e,t){return void 0===e?t:"LiveObject"===e.type&&"LiveObject"===t.type?function(e,t){const n=e.updates;for(const[e,r]of F(t.updates))n[e]=r;return{...t,updates:n}}(e,t):"LiveMap"===e.type&&"LiveMap"===t.type?function(e,t){const n=e.updates;for(const[e,r]of F(t.updates))n[e]=r;return{...t,updates:n}}(e,t):"LiveList"===e.type&&"LiveList"===t.type?function(e,t){const n=e.updates;return{...t,updates:n.concat(t.updates)}}(e,t):t}function gt(e,t){const n=[];for(let r=0,o=e.length;r<o;r+=t)n.push(e.slice(r,r+t));return n}function yt(e){return`${e}_${qe()}`}function bt(){return yt("th")}function Et(){return yt("cm")}function wt(e){return Array.isArray(e)}var Ct=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Dt(e){let t=[];const n=Object.entries(e),r=[],o=[],a=[];return n.forEach((([e,t])=>{if(!Ct.test(e))throw new Error("Key must only contain letters, numbers, _");_t(t)?r.push([e,t]):Bt(t)?o.push([e,t]):"object"!=typeof t||"startsWith"in t||a.push([e,t])})),t=[...xt(r),...At(o)],a.forEach((([e,n])=>{const r=Object.entries(n),o=[],a=[];r.forEach((([t,n])=>{if(kt(t))throw new Error("Key cannot be empty");_t(n)?o.push([St(e,t),n]):Bt(n)&&a.push([St(e,t),n])})),t=[...t,...xt(o),...At(a)]})),t.map((({key:e,operator:t,value:n})=>Ot(e,t,Tt(n)))).join(" AND ")}var xt=e=>{const t=[];return e.forEach((([e,n])=>{t.push({key:e,operator:":",value:n})})),t},At=e=>{const t=[];return e.forEach((([e,n])=>{"startsWith"in n&&"string"==typeof n.startsWith&&t.push({key:e,operator:"^",value:n.startsWith})})),t},_t=e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e,Bt=e=>"object"==typeof e&&null!==e&&"startsWith"in e,Ot=(e,t,n)=>`${e}${t}${n}`,St=(e,t)=>t?`${e}[${JSON.stringify(t)}]`:e,Tt=e=>{if("string"==typeof e){if(kt(e))throw new Error("Value cannot be empty");return JSON.stringify(e)}return e.toString()},kt=e=>!e||""===e.toString().trim();var It=class extends Te{constructor(){super(),this._connections=new Map,this._presences=new Map,this._users=new Map}connectionIds(){return this._connections.keys()}_toImmutable(){return P(Array.from(this._presences.keys()).map((e=>this.getUser(Number(e)))))}clearOthers(){this._connections=new Map,this._presences=new Map,this._users=new Map,this.invalidate()}_getUser(e){const t=this._connections.get(e),n=this._presences.get(e);if(void 0!==t&&void 0!==n)return function(e,t){const{connectionId:n,id:r,info:o}=e,a=se(e.scopes);return M({connectionId:n,id:r,info:o,canWrite:a,canComment:ue(e.scopes),isReadOnly:!a,presence:t})}(t,n)}getUser(e){const t=this._users.get(e);if(t)return t;const n=this._getUser(e);return n?(this._users.set(e,n),n):void 0}_invalidateUser(e){this._users.has(e)&&this._users.delete(e),this.invalidate()}setConnection(e,t,n,r){this._connections.set(e,{connectionId:e,id:t,info:n,scopes:r}),this._presences.has(e)&&this._invalidateUser(e)}removeConnection(e){this._connections.delete(e),this._presences.delete(e),this._invalidateUser(e)}setOther(e,t){this._presences.set(e,M(t)),this._connections.has(e)&&this._invalidateUser(e)}patchOther(e,t){const n=this._presences.get(e);if(void 0===n)return;const r=Se(n,t);n!==r&&(this._presences.set(e,r),this._invalidateUser(e))}},Ft=class extends Te{constructor(e){super(),this._data=M(e)}_toImmutable(){return this._data}patch(e){const t=this._data,n=Se(t,e);t!==n&&(this._data=n,this.invalidate())}};function Rt(e,t){return{type:"User",id:`${t.connectionId}`,key:e,payload:{connectionId:t.connectionId,id:t.id,info:t.info,presence:t.presence,isReadOnly:!t.canWrite}}}var Nt=52428800,Pt=[2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3];function Mt(e,t){const n=e.initialPresence,r=e.initialStorage,[o,a]=function(){const e="undefined"!=typeof document?document:void 0,t={current:null};function n(){t.current="hidden"===e?.visibilityState?t.current??Date.now():null}return e?.addEventListener("visibilitychange",n),[t,()=>{e?.removeEventListener("visibilitychange",n)}]}(),i={...t.delegates,canZombie:()=>void 0!==t.backgroundKeepAliveTimeout&&null!==o.current&&Date.now()>o.current+t.backgroundKeepAliveTimeout&&"synchronizing"!==ce()},s=new class{constructor(e,t=!1,n=!0){const{machine:r,events:o,cleanups:a}=ie(e,{waitForActorId:n,enableDebugLogging:t});this.machine=r,this.events=o,this.cleanups=a}getStatus(){try{return V(this.machine)}catch{return"initial"}}get authValue(){return this.machine.context.authValue}connect(){this.machine.send({type:"CONNECT"})}reconnect(){this.machine.send({type:"RECONNECT"})}disconnect(){this.machine.send({type:"DISCONNECT"})}destroy(){let e;for(this.machine.stop();e=this.cleanups.pop();)e()}send(e){const t=this.machine.context?.socket;null===t?x("Cannot send: not connected yet",e):1!==t.readyState?x("Cannot send: WebSocket no longer open",e):t.send(e)}_privateSendMachineEvent(e){this.machine.send(e)}}(i,t.enableDebugLogging),u={buffer:{flushTimerID:void 0,lastFlushedAt:0,presenceUpdates:{type:"full",data:n},messages:[],storageOperations:[]},staticSessionInfo:new ke(null),dynamicSessionInfo:new ke(null),myPresence:new Ft(n),others:new It,initialStorage:r,idFactory:null,yjsProvider:void 0,yjsProviderDidChange:E(),clock:0,opClock:0,nodes:new Map,root:void 0,undoStack:[],redoStack:[],pausedHistory:null,activeBatch:null,unacknowledgedOps:new Map,opStackTraces:void 0},c=e=>e(),l=t.unstable_batchedUpdates??c;let d,f;let h=!1;s.events.onMessage.subscribe((function(e){if("string"!=typeof e.data)return;const t=function(e){const t=R(e);return void 0===t?null:wt(t)?P(t.map((e=>Z(e)))):P([Z(t)])}(e.data);if(null===t||0===t.length)return;const n={storageUpdates:new Map,others:[]};l((()=>{for(const e of t)switch(e.type){case 101:{const t=G(e);t&&n.others.push(t);break}case 100:{const t=H(e);t&&n.others.push(t);break}case 103:{const t=u.others.current;m.customEvent.notify({connectionId:e.actor,user:e.actor<0?null:t.find((t=>t.connectionId===e.actor))??null,event:e.event});break}case 102:{const t=U(e);t&&n.others.push(t);break}case 300:m.ydoc.notify(e);break;case 104:n.others.push(W(e,c));break;case 200:ee(e);break;case 201:{const t=j(e.ops,!1);for(const[e,r]of t.updates.storageUpdates)n.storageUpdates.set(e,vt(n.storageUpdates.get(e),r));break}case 299:O("Storage mutation rejection error",e.reason);break;case 400:case 407:case 401:case 408:case 405:case 406:case 402:case 403:case 404:m.comments.notify(e)}F(n,c)}))})),s.events.statusDidChange.subscribe((function(e){const t=s.authValue;if(null!==t){const e=_e(t);if(e!==d)if(d=e,"secret"===t.type){const e=t.token.parsed;u.staticSessionInfo.set({userId:"sec-legacy"===e.k?e.id:e.uid,userInfo:"sec-legacy"===e.k?e.info:e.ui})}else u.staticSessionInfo.set({userId:void 0,userInfo:void 0})}l((()=>{m.status.notify(e),_(c)}))})),s.events.statusDidChange.subscribe((function(e){"reconnecting"===e?f=setTimeout((()=>{l((()=>{m.lostConnection.notify("lost"),h=!0,u.others.clearOthers(),F({others:[{type:"reset"}]},c)}))}),t.lostConnectionTimeout):(clearTimeout(f),h&&(l("disconnected"===e?()=>{m.lostConnection.notify("failed")}:()=>{m.lostConnection.notify("restored")}),h=!1))})),s.events.didConnect.subscribe((function(){u.buffer.presenceUpdates={type:"full",data:{...u.myPresence.current}},null!==J&&te({flush:!1}),X()})),s.events.didDisconnect.subscribe((function(){clearTimeout(u.buffer.flushTimerID)})),s.events.onLiveblocksError.subscribe((e=>{l((()=>{m.error.notify(e)}))}));const p={roomId:t.roomId,getNode:e=>u.nodes.get(e),addNode:(e,t)=>{u.nodes.set(e,t)},deleteNode:e=>{u.nodes.delete(e)},generateId:()=>`${M()}:${u.clock++}`,generateOpId:()=>`${M()}:${u.opClock++}`,dispatch(e,t,n){const r=u.activeBatch;if(r){for(const t of e)r.ops.push(t);for(const[e,t]of n)r.updates.storageUpdates.set(e,vt(r.updates.storageUpdates.get(e),t));r.reverseOps.unshift(...t)}else l((()=>{I(t,c),u.redoStack.length=0,Y(e),F({storageUpdates:n},c)}))},assertStorageIsWritable:()=>{const e=u.dynamicSessionInfo.current?.scopes;if(void 0===e)return;if(!se(e))throw new Error("Cannot write to storage with a read only user, please ensure the user has write permissions")}},m={status:E(),lostConnection:E(),customEvent:E(),self:E(),myPresence:E(),others:E(),error:E(),storageBatch:E(),history:E(),storageDidLoad:E(),storageStatus:E(),ydoc:E(),comments:E()},v=t.polyfills?.fetch||globalThis.fetch?.bind(globalThis),y=new Be(t.baseUrl,v,(()=>Promise.resolve(s.authValue??k("Not authorized")))),w=new Be(t.baseUrl,v,(()=>i.authenticate()));function C(e){const n=JSON.stringify(e),r=u.dynamicSessionInfo.current?.nonce;if(t.unstable_fallbackToHTTP&&r){if((new TextEncoder).encode(n).length>1047552)return y.rawPost(Ae`/v2/c/rooms/${t.roomId}/send-message`,{nonce:r,messages:e}).then((e=>{e.ok||403!==e.status||s.reconnect()})),void x("Message was too large for websockets and sent over HTTP instead")}s.send(n)}const D=new Ie(u.staticSessionInfo,u.dynamicSessionInfo,u.myPresence,((e,t,n)=>{if(null===e||null===t)return null;{const r=se(t.scopes);return{connectionId:t.actor,id:e.userId,info:e.userInfo,presence:n,canWrite:r,canComment:ue(t.scopes)}}}));let A;function _(e){const t=D.current;null!==t&&t!==A&&(e((()=>{m.self.notify(t)})),A=t)}const B=new Ie(D,(e=>null!==e?Rt("Me",e):null));function S(e,t){if(0===e.items.length)throw new Error("Internal error: cannot load storage without items");void 0!==u.root?function(e,t){if(void 0===u.root)return;const n=new Map;for(const[e,t]of u.nodes)n.set(e,t._serialize());const r=function(e,t){const n=[];return e.forEach(((e,r)=>{t.get(r)||n.push({type:5,id:r})})),t.forEach(((t,r)=>{const o=e.get(r);if(o)0===t.type&&(0===o.type&&JSON.stringify(t.data)===JSON.stringify(o.data)||n.push({type:3,id:r,data:t.data})),t.parentKey!==o.parentKey&&n.push({type:1,id:r,parentKey:g(t.parentKey,"Parent key must not be missing")});else switch(t.type){case 3:n.push({type:8,id:r,parentId:t.parentId,parentKey:t.parentKey,data:t.data});break;case 1:n.push({type:2,id:r,parentId:t.parentId,parentKey:t.parentKey});break;case 0:if(void 0===t.parentId||void 0===t.parentKey)throw new Error("Internal error. Cannot serialize storage root into an operation");n.push({type:4,id:r,parentId:t.parentId,parentKey:t.parentKey,data:t.data});break;case 2:n.push({type:7,id:r,parentId:t.parentId,parentKey:t.parentKey})}})),n}(n,new Map(e));F(j(r,!1).updates,t)}(e.items,t):u.root=at._fromItems(e.items,p);const n=D.current?.canWrite??!0,r=u.undoStack.length;for(const e in u.initialStorage)void 0===u.root.get(e)&&(n?u.root.set(e,void 0===(o=u.initialStorage[e])?void 0:dt(o)?o.clone():N(o)):x(`Attempted to populate missing storage key '${e}', but current user has no write access`));var o;u.undoStack.length=r}function T(e,t){u.undoStack.length>=50&&u.undoStack.shift(),u.undoStack.push(e),q(t)}function I(e,t){null!==u.pausedHistory?u.pausedHistory.unshift(...e):T(e,t)}function F(e,t){const n=e.storageUpdates,r=e.others;t((()=>{if(void 0!==r&&r.length>0){const e=u.others.current;for(const t of r)m.others.notify({...t,others:e})}if(e.presence&&(_(c),m.myPresence.notify(u.myPresence.current)),void 0!==n&&n.size>0){const e=Array.from(n.values());m.storageBatch.notify(e)}fe()}))}function M(){const e=u.dynamicSessionInfo.current;if(e)return e.actor;throw new Error("Internal. Tried to get connection id but connection was never open")}function j(e,t){const n={reverse:[],storageUpdates:new Map,presence:!1},r=new Set,o=e.map((e=>"presence"===e.type||e.opId?e:{...e,opId:p.generateOpId()}));for(const e of o)if("presence"===e.type){const t={type:"presence",data:{}};for(const n in e.data)t.data[n]=u.myPresence.current[n];if(u.myPresence.patch(e.data),null===u.buffer.presenceUpdates)u.buffer.presenceUpdates={type:"partial",data:e.data};else for(const t in e.data)u.buffer.presenceUpdates.data[t]=e.data[t];n.reverse.unshift(t),n.presence=!0}else{let o;if(t)o=0;else{const t=g(e.opId);o=u.unacknowledgedOps.delete(t)?2:1}const a=L(e,o);if(a.modified){const t=a.modified.node._id;t&&r.has(t)||(n.storageUpdates.set(g(a.modified.node._id),vt(n.storageUpdates.get(g(a.modified.node._id)),a.modified)),n.reverse.unshift(...a.reverse)),2!==e.type&&7!==e.type&&4!==e.type||r.add(g(e.id))}}return{ops:o,reverse:n.reverse,updates:{storageUpdates:n.storageUpdates,presence:n.presence}}}function L(e,t){if(function(e){return 5===e.type&&"ACK"===e.id}(e))return{modified:!1};switch(e.type){case 6:case 3:case 5:{const n=u.nodes.get(e.id);return void 0===n?{modified:!1}:n._apply(e,0===t)}case 1:{const n=u.nodes.get(e.id);return void 0===n?{modified:!1}:"HasParent"===n.parent.type&&ht(n.parent.node)?n.parent.node._setChildKey(Ue(e.parentKey),n,t):{modified:!1}}case 4:case 2:case 7:case 8:{if(void 0===e.parentId)return{modified:!1};const n=u.nodes.get(e.parentId);return void 0===n?{modified:!1}:n._attachChild(e,t)}}}function H(e){if(void 0!==e.targetActor){const t=u.others.getUser(e.actor);u.others.setOther(e.actor,e.data);const n=u.others.getUser(e.actor);if(void 0===t&&void 0!==n)return{type:"enter",user:n}}else u.others.patchOther(e.actor,e.data);const t=u.others.getUser(e.actor);return t?{type:"update",updates:e.data,user:t}:void 0}function U(e){const t=u.others.getUser(e.actor);return t?(u.others.removeConnection(e.actor),{type:"leave",user:t}):null}function W(e,t){u.dynamicSessionInfo.set({actor:e.actor,nonce:e.nonce,scopes:e.scopes}),u.idFactory=function(e){let t=0;return()=>`${e}:${t++}`}(e.actor),_(t);for(const t of u.others.connectionIds()){void 0===e.users[t]&&u.others.removeConnection(t)}for(const t in e.users){const n=e.users[t],r=Number(t);u.others.setConnection(r,n.id,n.info,n.scopes)}return{type:"reset"}}function $(){return u.undoStack.length>0}function K(){return u.redoStack.length>0}function q(e){e((()=>{m.history.notify({canUndo:$(),canRedo:K()})}))}function G(e){u.others.setConnection(e.actor,e.id,e.info,e.scopes),u.buffer.messages.push({type:100,data:u.myPresence.current,targetActor:e.actor}),X();const t=u.others.getUser(e.actor);return t?{type:"enter",user:t}:void 0}function Z(e){return function(e){return!function(e){return null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e}(e)&&!wt(e)}(e)?e:null}function X(){const e=u.buffer.storageOperations;if(e.length>0){for(const t of e)u.unacknowledgedOps.set(g(t.opId),t);fe()}if("connected"!==s.getStatus())return void(u.buffer.storageOperations=[]);const n=Date.now(),r=n-u.buffer.lastFlushedAt;if(r>=t.throttleDelay){const e=function(){const e=[];u.buffer.presenceUpdates&&e.push("full"===u.buffer.presenceUpdates.type?{type:100,targetActor:-1,data:u.buffer.presenceUpdates.data}:{type:100,data:u.buffer.presenceUpdates.data});for(const t of u.buffer.messages)e.push(t);u.buffer.storageOperations.length>0&&e.push({type:201,ops:u.buffer.storageOperations});return e}();if(0===e.length)return;C(e),u.buffer={flushTimerID:void 0,lastFlushedAt:n,messages:[],storageOperations:[],presenceUpdates:null}}else clearTimeout(u.buffer.flushTimerID),u.buffer.flushTimerID=setTimeout(X,t.throttleDelay-r)}function Y(e){const{storageOperations:t}=u.buffer;for(const n of e)t.push(n);X()}let J=null,Q=null;function ee(e){const t=new Map(u.unacknowledgedOps);S(e,c),function(e,t){if(0===e.size)return;const n=[],r=j(Array.from(e.values()),!0);n.push({type:201,ops:r.ops}),F(r.updates,t),C(n)}(t,c),Q?.(),fe(),m.storageDidLoad.notify()}function te(e){const n=u.buffer.messages;t.unstable_streamData?async function(){if(!s.authValue)return;const e=await y.rawGet(Ae`/v2/c/rooms/${t.roomId}/storage`);ee({type:200,items:await e.json()})}():n.some((e=>200===e.type))||n.push({type:200}),e.flush&&X()}function ne(){return null===J&&(te({flush:!0}),J=new Promise((e=>{Q=e})),fe()),J}function re(){const e=u.root;return void 0!==e?e:(ne(),null)}async function oe(){return void 0!==u.root?Promise.resolve({root:u.root}):(await ne(),{root:g(u.root)})}const ae=t.createSyncSource();function ce(){return void 0===u.root?null===J?"not-loaded":"loading":0===u.unacknowledgedOps.size?"synchronized":"synchronizing"}let le=ce();function fe(){const e=ce();le!==e&&(le=e,m.storageStatus.notify(e)),ae.setSyncStatus("synchronizing"===e?"synchronizing":"synchronized")}function me(){return null!==D.current}function Ce(){return null!==re()}const xe=new Ie(u.others,(e=>e.map(((e,t)=>Rt(`Other ${t}`,e))))),Oe={status:m.status.observable,lostConnection:m.lostConnection.observable,customEvent:m.customEvent.observable,others:m.others.observable,self:m.self.observable,myPresence:m.myPresence.observable,error:m.error.observable,storage:m.storageBatch.observable,storageBatch:m.storageBatch.observable,history:m.history.observable,storageDidLoad:m.storageDidLoad.observable,storageStatus:m.storageStatus.observable,ydoc:m.ydoc.observable,comments:m.comments.observable};const Se=new he((async e=>{const n=e.flat(),r=await async function(e){const{urls:n}=await w.post(Ae`/v2/c/rooms/${t.roomId}/attachments/presigned-urls`,{attachmentIds:e});return n}(n);return r.map((e=>e??new Error("There was an error while getting this attachment's URL")))}),{delay:50}),Te=pe(Se);async function Fe(e,t){return await w.get(e,void 0,t)}const Re=new he((async e=>{const n=e.flat();return await async function(e){await Fe(Ae`/v2/c/rooms/${t.roomId}/inbox-notifications/read`,{method:"POST",body:JSON.stringify({inboxNotificationIds:e})})}(n),n}),{delay:50});const Ne=t.createSyncSource();function Pe(e){return Ne.setSyncStatus("synchronizing"===e?"synchronizing":"synchronized")}return Object.defineProperty({[de]:{get presenceBuffer(){return N(u.buffer.presenceUpdates?.data??null)},get undoStack(){return N(u.undoStack)},get nodeCount(){return u.nodes.size},getYjsProvider:()=>u.yjsProvider,setYjsProvider(e){u.yjsProvider?.off("status",Pe),u.yjsProvider=e,e?.on("status",Pe),u.yjsProviderDidChange.notify()},yjsProviderDidChange:u.yjsProviderDidChange.observable,reportTextEditor:async function(e,n){await w.rawPost(Ae`/v2/c/rooms/${t.roomId}/text-metadata`,{type:e,rootKey:n})},createTextMention:async function(e,n){await y.rawPost(Ae`/v2/c/rooms/${t.roomId}/text-mentions`,{userId:e,mentionId:n})},deleteTextMention:async function(e){await y.rawDelete(Ae`/v2/c/rooms/${t.roomId}/text-mentions/${e}`)},listTextVersions:async function(){const e=await w.get(Ae`/v2/c/rooms/${t.roomId}/versions`);return{versions:e.versions.map((({createdAt:e,...t})=>({createdAt:new Date(e),...t}))),requestedAt:new Date(e.meta.requestedAt)}},listTextVersionsSince:async function(e){const n=await w.get(Ae`/v2/c/rooms/${t.roomId}/versions/delta`,{since:e.since.toISOString()},{signal:e.signal});return{versions:n.versions.map((({createdAt:e,...t})=>({createdAt:new Date(e),...t}))),requestedAt:new Date(n.meta.requestedAt)}},getTextVersion:async function(e){return w.rawGet(Ae`/v2/c/rooms/${t.roomId}/y-version/${e}`)},createTextVersion:async function(){await w.rawPost(Ae`/v2/c/rooms/${t.roomId}/version`)},getSelf_forDevTools:()=>B.current,getOthers_forDevTools:()=>xe.current,simulate:{explicitClose:e=>s._privateSendMachineEvent({type:"EXPLICIT_SOCKET_CLOSE",event:e}),rawSend:e=>s.send(e)},attachmentUrlsStore:Te},id:t.roomId,subscribe:jt(Oe),connect:()=>s.connect(),reconnect:()=>s.reconnect(),disconnect:()=>s.disconnect(),destroy:()=>{ae.destroy(),u.yjsProvider?.off("status",Pe),Ne.destroy(),a(),s.destroy()},updatePresence:function(e,t){const n={};null===u.buffer.presenceUpdates&&(u.buffer.presenceUpdates={type:"partial",data:{}});for(const t in e){const r=e[t];void 0!==r&&(u.buffer.presenceUpdates.data[t]=r,n[t]=u.myPresence.current[t])}u.myPresence.patch(e),u.activeBatch?(t?.addToHistory&&u.activeBatch.reverseOps.unshift({type:"presence",data:n}),u.activeBatch.updates.presence=!0):(X(),l((()=>{t?.addToHistory&&I([{type:"presence",data:n}],c),F({presence:!0},c)})))},updateYDoc:function(e,t){const n={type:301,update:e,guid:t};u.buffer.messages.push(n),m.ydoc.notify(n),X()},broadcastEvent:function(e,t={shouldQueueEventIfNotReady:!1}){("connected"===s.getStatus()||t.shouldQueueEventIfNotReady)&&(u.buffer.messages.push({type:103,event:e}),X())},batch:function(e){if(u.activeBatch)return e();let t;return l((()=>{u.activeBatch={ops:[],updates:{storageUpdates:new Map,presence:!1,others:[]},reverseOps:[]};try{t=e()}finally{const e=u.activeBatch;u.activeBatch=null,e.reverseOps.length>0&&I(e.reverseOps,c),e.ops.length>0&&(u.redoStack.length=0),e.ops.length>0&&Y(e.ops),F(e.updates,c),X()}})),t},history:{undo:function(){if(u.activeBatch)throw new Error("undo is not allowed during a batch");const e=u.undoStack.pop();if(void 0===e)return;u.pausedHistory=null;const t=j(e,!0);l((()=>{F(t.updates,c),u.redoStack.push(t.reverse),q(c)}));for(const e of t.ops)"presence"!==e.type&&u.buffer.storageOperations.push(e);X()},redo:function(){if(u.activeBatch)throw new Error("redo is not allowed during a batch");const e=u.redoStack.pop();if(void 0===e)return;u.pausedHistory=null;const t=j(e,!0);l((()=>{F(t.updates,c),u.undoStack.push(t.reverse),q(c)}));for(const e of t.ops)"presence"!==e.type&&u.buffer.storageOperations.push(e);X()},canUndo:$,canRedo:K,clear:function(){u.undoStack.length=0,u.redoStack.length=0},pause:function(){null===u.pausedHistory&&(u.pausedHistory=[])},resume:function(){const e=u.pausedHistory;u.pausedHistory=null,null!==e&&e.length>0&&T(e,l)}},fetchYDoc:function(e,t){u.buffer.messages.find((n=>300===n.type&&n.vector===e&&n.guid===t))||u.buffer.messages.push({type:300,vector:e,guid:t}),X()},getStorage:oe,getStorageSnapshot:re,getStorageStatus:ce,isPresenceReady:me,isStorageReady:Ce,waitUntilPresenceReady:z((async function(){for(;!me();){const{promise:e,resolve:t}=b(),n=Oe.self.subscribeOnce(t),r=Oe.status.subscribeOnce(t);await e,n(),r()}})),waitUntilStorageReady:z((async function(){for(;!Ce();)await oe()})),events:Oe,getStatus:()=>s.getStatus(),getSelf:()=>D.current,getPresence:()=>u.myPresence.current,getOthers:()=>u.others.current,getThreads:async function(e){let n;e?.query&&(n=Dt(e.query));try{const r=await w.get(Ae`/v2/c/rooms/${t.roomId}/threads`,{cursor:e?.cursor,query:n,limit:50});return{threads:r.data.map(ge),inboxNotifications:r.inboxNotifications.map(ye),nextCursor:r.meta.nextCursor,requestedAt:new Date(r.meta.requestedAt)}}catch(e){if(e instanceof we&&404===e.status)return{threads:[],inboxNotifications:[],nextCursor:null,requestedAt:new Date(Date.now()-216e5)};throw e}},getThreadsSince:async function(e){const n=await w.get(Ae`/v2/c/rooms/${t.roomId}/threads/delta`,{since:e?.since?.toISOString()},{signal:e.signal});return{threads:{updated:n.data.map(ge),deleted:n.deletedThreads.map(be)},inboxNotifications:{updated:n.inboxNotifications.map(ye),deleted:n.deletedInboxNotifications.map(Ee)},requestedAt:new Date(n.meta.requestedAt)}},getThread:async function(e){const n=await w.rawGet(Ae`/v2/c/rooms/${t.roomId}/thread-with-notification/${e}`);if(n.ok){const e=await n.json();return{thread:ge(e.thread),inboxNotification:e.inboxNotification?ye(e.inboxNotification):void 0}}if(404===n.status)return{thread:void 0,inboxNotification:void 0};throw new Error(`There was an error while getting thread ${e}.`)},createThread:async function({metadata:e,body:n,commentId:r=Et(),threadId:o=bt(),attachmentIds:a}){return ge(await w.post(Ae`/v2/c/rooms/${t.roomId}/threads`,{id:o,comment:{id:r,body:n,attachmentIds:a},metadata:e}))},deleteThread:async function(e){await w.delete(Ae`/v2/c/rooms/${t.roomId}/threads/${e}`)},editThreadMetadata:async function({metadata:e,threadId:n}){return await w.post(Ae`/v2/c/rooms/${t.roomId}/threads/${n}/metadata`,e)},markThreadAsResolved:async function(e){await w.post(Ae`/v2/c/rooms/${t.roomId}/threads/${e}/mark-as-resolved`)},markThreadAsUnresolved:async function(e){await w.post(Ae`/v2/c/rooms/${t.roomId}/threads/${e}/mark-as-unresolved`)},createComment:async function({threadId:e,commentId:n=Et(),body:r,attachmentIds:o}){return ve(await w.post(Ae`/v2/c/rooms/${t.roomId}/threads/${e}/comments`,{id:n,body:r,attachmentIds:o}))},editComment:async function({threadId:e,commentId:n,body:r,attachmentIds:o}){return ve(await w.post(Ae`/v2/c/rooms/${t.roomId}/threads/${e}/comments/${n}`,{body:r,attachmentIds:o}))},deleteComment:async function({threadId:e,commentId:n}){await w.delete(Ae`/v2/c/rooms/${t.roomId}/threads/${e}/comments/${n}`)},addReaction:async function({threadId:e,commentId:n,emoji:r}){const o=await w.post(Ae`/v2/c/rooms/${t.roomId}/threads/${e}/comments/${n}/reactions`,{emoji:r});return a=o,{...a,createdAt:new Date(a.createdAt)};var a},removeReaction:async function({threadId:e,commentId:n,emoji:r}){await w.delete(Ae`/v2/c/rooms/${t.roomId}/threads/${e}/comments/${n}/reactions/${r}`)},prepareAttachment:function(e){return{type:"localAttachment",status:"idle",id:yt("at"),name:e.name,size:e.size,mimeType:e.type,file:e}},uploadAttachment:async function(e,n={}){const r=n.signal,o=r?new DOMException(`Upload of attachment ${e.id} was aborted.`,"AbortError"):void 0;if(r?.aborted)throw o;const a=e=>{if(r?.aborted)throw o;if(e instanceof we&&413===e.status)throw e;return!1};if(e.size<=Nt)return De((()=>w.putBlob(Ae`/v2/c/rooms/${t.roomId}/attachments/${e.id}/upload/${encodeURIComponent(e.name)}`,e.file,{fileSize:e.size},{signal:r})),10,Pt,a);{let n;const i=[],s=await De((()=>w.post(Ae`/v2/c/rooms/${t.roomId}/attachments/${e.id}/multipart/${encodeURIComponent(e.name)}`,void 0,{signal:r},{fileSize:e.size})),10,Pt,a);try{n=s.uploadId;const u=function(e){const t=[];let n=0;for(;n<e.size;){const r=Math.min(n+Nt,e.size);t.push({partNumber:t.length+1,part:e.slice(n,r)}),n=r}return t}(e.file);if(r?.aborted)throw o;const c=gt(u,5);for(const n of c){const o=[];for(const{part:i,partNumber:u}of n)o.push(De((()=>w.putBlob(Ae`/v2/c/rooms/${t.roomId}/attachments/${e.id}/multipart/${s.uploadId}/${String(u)}`,i,void 0,{signal:r})),10,Pt,a));i.push(...await Promise.all(o))}if(r?.aborted)throw o;const l=i.sort(((e,t)=>e.partNumber-t.partNumber));return w.post(Ae`/v2/c/rooms/${t.roomId}/attachments/${e.id}/multipart/${n}/complete`,{parts:l},{signal:r})}catch(r){if(n&&r?.name&&("AbortError"===r.name||"TimeoutError"===r.name))try{await w.rawDelete(Ae`/v2/c/rooms/${t.roomId}/attachments/${e.id}/multipart/${n}`)}catch(e){}throw r}}},getAttachmentUrl:function(e){return Se.get(e)},getNotificationSettings:function(e){return Fe(Ae`/v2/c/rooms/${t.roomId}/notification-settings`,{signal:e?.signal})},updateNotificationSettings:function(e){return Fe(Ae`/v2/c/rooms/${t.roomId}/notification-settings`,{method:"POST",body:JSON.stringify(e)})},markInboxNotificationAsRead:async function(e){await Re.get(e)}},de,{enumerable:!1})}function jt(e){function t(t,n){return e.storageBatch.subscribe((e=>{const r=e.filter((e=>ut(e.node,t)));r.length>0&&n(r)}))}return function(n,r,o){if("string"==typeof n&&("my-presence"===(a=n)||"others"===a||"event"===a||"error"===a||"history"===a||"status"===a||"storage-status"===a||"lost-connection"===a||"connection"===a||"comments"===a)){if("function"!=typeof r)throw new Error("Second argument must be a callback function");const t=r;switch(n){case"event":return e.customEvent.subscribe(t);case"my-presence":return e.myPresence.subscribe(t);case"others":{const n=t;return e.others.subscribe((e=>{const{others:t,...r}=e;return n(t,r)}))}case"error":return e.error.subscribe(t);case"status":return e.status.subscribe(t);case"lost-connection":return e.lostConnection.subscribe(t);case"history":return e.history.subscribe(t);case"storage-status":return e.storageStatus.subscribe(t);case"comments":return e.comments.subscribe(t);default:return v(0,`"${String(n)}" is not a valid event name`)}}var a;if(void 0===r||"function"==typeof n){if("function"==typeof n){const t=n;return e.storageBatch.subscribe(t)}throw new Error("Please specify a listener callback")}if(ft(n)){const a=n;if(o?.isDeep){return t(a,r)}return function(t,n){return e.storageBatch.subscribe((e=>{for(const r of e)r.node._id===t._id&&n(r.node)}))}(a,r)}throw new Error(`${String(n)} is not a value that can be subscribed to.`)}}function Lt(e,t){return async()=>t.getAuthValue({requestedScope:"room:read",roomId:e})}function zt(e,t,n){return r=>{const o=n??("undefined"==typeof WebSocket?void 0:WebSocket);if(void 0===o)throw new G("To use Liveblocks client in a non-DOM environment, you need to provide a WebSocket polyfill.");const a=new URL(t);if(a.protocol="http:"===a.protocol?"ws":"wss",a.pathname="/v7",a.searchParams.set("roomId",e),"secret"===r.type)a.searchParams.set("tok",r.token.raw);else{if("public"!==r.type)return v(0,"Unhandled case");a.searchParams.set("pubkey",r.publicApiKey)}return a.searchParams.set("version",f),new o(a.toString())}}function Ht(e){const t=e,n=Ut("throttle",t.throttle??100,16,1e3);const o=function(e){return Ut("lostConnectionTimeout",e,200,3e4,1e3)}(t.lostConnectionTimeout??5e3),a=function(e){return void 0===e?void 0:Ut("backgroundKeepAliveTimeout",e,15e3)}(t.backgroundKeepAliveTimeout),i=function(e){return"string"==typeof e&&e.startsWith("http")?e:"https://api.liveblocks.io"}(t.baseUrl),s=le(e),u=new Map;function c(e){const t=()=>{const n=t;var r;e.unsubs.delete(n)?0===e.unsubs.size&&((r=e.room).id,u.delete(r.id),r.destroy()):x("This leave function was already called. Calling it more than once has no effect.")};return e.unsubs.add(t),{room:e.room,leave:t}}const l=me(null),d=t.polyfills?.fetch||globalThis.fetch?.bind(globalThis),f=Oe({baseUrl:i,fetchPolyfill:d,authManager:s,currentUserIdStore:l}),h=t.resolveUsers,p=Wt((()=>!h),"Set the resolveUsers option in createClient to specify user info."),m=pe(new he((async e=>{const t=e.flat(),n=await(h?.({userIds:t}));return p(),n??t.map((()=>{}))}),{delay:50}));const v=t.resolveRoomsInfo,g=Wt((()=>!v),"Set the resolveRoomsInfo option in createClient to specify room info."),y=pe(new he((async e=>{const t=e.flat(),n=await(v?.({roomIds:t}));return g(),n??t.map((()=>{}))}),{delay:50}));const b=new Map;const E=[],w=new ke("synchronized");function C(){w.set(E.some((e=>"synchronizing"===e.current))?"synchronizing":E.some((e=>"has-local-changes"===e.current))?"has-local-changes":"synchronized")}function D(){const e=new ke("synchronized");E.push(e);const t=e.didInvalidate.subscribe((()=>C()));return{setSyncStatus:function(t){e.set(t)},destroy:function(){t();const n=E.findIndex((t=>t===e));if(n>-1){const[e]=E.splice(n,1);"synchronized"!==e.current&&C()}}}}{const e=e=>{t.preventUnsavedChanges&&"synchronized"!==w.current&&e.preventDefault()};("undefined"!=typeof window?window:void 0)?.addEventListener("beforeunload",e)}const A=Object.defineProperty({enterRoom:function(e,...l){const d=u.get(e);if(void 0!==d)return c(d);const f=l[0]??{},h=Mt({initialPresence:("function"==typeof f.initialPresence?f.initialPresence(e):f.initialPresence)??{},initialStorage:("function"==typeof f.initialStorage?f.initialStorage(e):f.initialStorage)??{}},{roomId:e,throttleDelay:n,lostConnectionTimeout:o,backgroundKeepAliveTimeout:a,polyfills:t.polyfills,delegates:t.mockedDelegates??{createSocket:zt(e,i,t.polyfills?.WebSocket),authenticate:Lt(e,s)},enableDebugLogging:t.enableDebugLogging,unstable_batchedUpdates:f?.unstable_batchedUpdates,baseUrl:i,unstable_fallbackToHTTP:!!t.unstable_fallbackToHTTP,unstable_streamData:!!t.unstable_streamData,createSyncSource:D}),p={room:h,unsubs:new Set};if(u.set(e,p),f.autoConnect??!0){if("undefined"==typeof atob){if(void 0===t.polyfills?.atob)throw new Error("You need to polyfill atob to use the client in your environment. Please follow the instructions at https://liveblocks.io/docs/errors/liveblocks-client/atob-polyfill");r.atob=t.polyfills.atob}h.connect()}return c(p)},getRoom:function(e){const t=u.get(e)?.room;return t||null},logout:function(){s.reset();for(const{room:t}of u.values())"initial"!==(e=t.getStatus())&&"disconnected"!==e&&t.reconnect();var e},...f,resolvers:{invalidateUsers:function(e){m.invalidate(e)},invalidateRoomsInfo:function(e){y.invalidate(e)},invalidateMentionSuggestions:function(){b.clear()}},getSyncStatus:function(){const e=w.current;return"synchronizing"===e?e:"synchronized"},events:{syncStatus:w.didInvalidate},[de]:{currentUserIdStore:l,mentionSuggestionsCache:b,resolveMentionSuggestions:t.resolveMentionSuggestions,usersStore:m,roomsInfoStore:y,getRoomIds:()=>Array.from(u.keys()),getUserThreads_experimental:f.getUserThreads_experimental,getUserThreadsSince_experimental:f.getUserThreadsSince_experimental,as:()=>A,createSyncSource:D}},de,{enumerable:!1});return A}function Ut(e,t,n,r,o){if("number"!=typeof t||t<n||void 0!==r&&t>r)throw new Error(void 0!==r?`${e} should be between ${o??n} and ${r}.`:`${e} should be at least ${o??n}.`);return t}function Wt(e,...t){return()=>{}}var Vt={paragraph:function(e){return"type"in e&&"paragraph"===e.type},text:function(e){return!("type"in e)&&"text"in e&&"string"==typeof e.text},link:function(e){return"type"in e&&"link"===e.type},mention:function(e){return"type"in e&&"mention"===e.type}},$t={paragraph:"block",text:"inline",link:"inline",mention:"inline"};function Kt(e){const t=new Set;return function(e,t,n){if(!e||!e?.content)return;const r="string"==typeof t?t:void 0,o=r?$t[r]:"all",a=r?Vt[r]:()=>!0,i="function"==typeof t?t:n;for(const t of e.content)if("all"!==o&&"block"!==o||a(t)&&i?.(t),"all"===o||"inline"===o)for(const e of t.children)a(e)&&i?.(e)}(e,"mention",(e=>t.add(e.id))),Array.from(t)}new RegExp(Object.keys({"&":"&","<":"<",">":">",'"':""","'":"'"}).map((e=>`\\${e}`)).join("|"),"g");new RegExp(Object.keys({_:"\\_","*":"\\*","#":"\\#","`":"\\`","~":"\\~","!":"\\!","|":"\\|","(":"\\(",")":"\\)","{":"\\{","}":"\\}","[":"\\[","]":"\\]"}).map((e=>`\\${e}`)).join("|"),"g");var qt=[1e3,2e3,4e3,8e3,1e4];function Gt(e,t,n){const r=performance.now(),o="undefined"!=typeof document?document:void 0,a="undefined"!=typeof window?window:void 0,i=n?.maxStaleTimeMs??Number.POSITIVE_INFINITY,s={inForeground:"hidden"!==o?.visibilityState,lastSuccessfulPollAt:r,count:0,backoff:0};function u(){return s.count>0&&s.inForeground}const c=new T({}).addState("@idle").addState("@enabled").addState("@polling");function l(){u()?c.send({type:"START"}):c.send({type:"STOP"})}function d(){performance.now()-s.lastSuccessfulPollAt>i&&c.send({type:"POLL"})}function f(e){s.inForeground=e,l(),d()}function h(){f("hidden"!==o?.visibilityState)}return c.addTransitions("@idle",{START:"@enabled"}),c.addTransitions("@enabled",{STOP:"@idle",POLL:"@polling"}),c.addTimedTransition("@enabled",(()=>{const e=s.lastSuccessfulPollAt+t;return Math.max(0,e-performance.now())+s.backoff}),"@polling"),c.onEnterAsync("@polling",(async(t,n)=>{await e(n),n.aborted||(s.lastSuccessfulPollAt=performance.now())}),(()=>({target:u()?"@enabled":"@idle",effect:()=>{s.backoff=0}})),(()=>({target:u()?"@enabled":"@idle",effect:()=>{s.backoff=qt.find((e=>e>s.backoff))??qt[qt.length-1]}})),3e4),o?.addEventListener("visibilitychange",h),a?.addEventListener("online",h),c.start(),{inc:function(){s.count++,l()},dec:function(){s.count--,s.count<0&&(s.count=0),l()},pollNowIfStale:d,setInForeground:f}}function Zt(e,t){if(Object.is(e,t))return!0;const n=Array.isArray(e),r=Array.isArray(t);return n||r?!(!n||!r)&&function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0}(e,t):function(e,t){if(!I(e)||!I(t))return!1;const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every((n=>Object.prototype.hasOwnProperty.call(t,n)&&Object.is(e[n],t[n])))}(e,t)}var Xt=class e{constructor(e,t){this._lt=t,this._data=e}static from(t,n){const r=new e([],n);for(const e of t)r.add(e);return r}static fromAlreadySorted(t,n){return new e(t,n)}clone(){return new e(this._data.slice(),this._lt)}add(e){const t=function(e,t,n){let r=0,o=e.length;for(;r<o;){const a=r+(o-r>>1);n(t,e[a])?o=a:r=a+1}return r}(this._data,e,this._lt);this._data.splice(t,0,e)}remove(e){const t=this._data.indexOf(e);return t>=0&&(this._data.splice(t,1),!0)}get length(){return this._data.length}*filter(e){for(const t of this._data)e(t)&&(yield t)}[Symbol.iterator](){return this._data[Symbol.iterator]()}};m(d,f,"esm");var Yt="@liveblocks/react",Jt="2.12.0";function Qt(e){const[t,n]=i.useState(!1);return i.useEffect((()=>{n(!0)}),[]),i.createElement(i.Suspense,{fallback:e.fallback},t?"function"==typeof e.children?e.children():e.children:e.fallback)}var en,tn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==r?r:"undefined"!=typeof self?self:{},nn={exports:{}},rn={};!function(e){e.exports=function(){if(en)return rn;en=1;var e=s.default,t="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},n=e.useState,r=e.useEffect,o=e.useLayoutEffect,a=e.useDebugValue;function i(e){var n=e.getSnapshot;e=e.value;try{var r=n();return!t(e,r)}catch(e){return!0}}var u="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(e,t){var s=t(),u=n({inst:{value:s,getSnapshot:t}}),c=u[0].inst,l=u[1];return o((function(){c.value=s,c.getSnapshot=t,i(c)&&l({inst:c})}),[e,s,t]),r((function(){return i(c)&&l({inst:c}),e((function(){i(c)&&l({inst:c})}))}),[e]),a(s),s};return rn.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u,rn}()}(nn);var on,an={exports:{}},sn={};!function(e){e.exports=function(){if(on)return sn;on=1;var e=s.default,t=nn.exports,n="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=t.useSyncExternalStore,o=e.useRef,a=e.useEffect,i=e.useMemo,u=e.useDebugValue;return sn.useSyncExternalStoreWithSelector=function(e,t,s,c,l){var d=o(null);if(null===d.current){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=i((function(){function e(e){if(!a){if(a=!0,r=e,e=c(e),void 0!==l&&f.hasValue){var t=f.value;if(l(t,e))return o=t}return o=e}if(t=o,n(r,e))return t;var i=c(e);return void 0!==l&&l(t,i)?(r=e,t):(r=e,o=i)}var r,o,a=!1,i=void 0===s?null:s;return[function(){return e(t())},null===i?void 0:function(){return e(i())}]}),[t,s,c,l]);var h=r(e,d[0],d[1]);return a((function(){f.hasValue=!0,f.value=h}),[h]),u(h),h},sn}()}(an);m("@liveblocks/client","2.12.0","esm");var un=i.createContext(null);function cn(){return i.useContext(un)}var ln={SMOOTH_DELAY:1e3,NOTIFICATIONS_POLL_INTERVAL:6e4,NOTIFICATIONS_MAX_STALE_TIME:5e3,ROOM_THREADS_POLL_INTERVAL:3e5,ROOM_THREADS_MAX_STALE_TIME:5e3,USER_THREADS_POLL_INTERVAL:6e4,USER_THREADS_MAX_STALE_TIME:5e3,HISTORY_VERSIONS_POLL_INTERVAL:6e4,HISTORY_VERSIONS_MAX_STALE_TIME:5e3,NOTIFICATION_SETTINGS_POLL_INTERVAL:6e4,NOTIFICATION_SETTINGS_MAX_STALE_TIME:5e3};function dn(e,t){if(!I(e)||!I(t))return Zt(e,t);const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every((n=>Object.prototype.hasOwnProperty.call(t,n)&&Zt(e[n],t[n])))}var fn=e=>e;function hn(e){return t.useReducer(fn,e)[0]}function pn(e){const n=hn(e);if("function"==typeof n){const n=function(e){const n=t.useRef(e);return t.useEffect((()=>{n.current=e}),[e]),n}(e);return t.useCallback(((...e)=>n.current(...e)),[n])}return n}var mn=e=>{if("pending"===e.status)throw e;if("fulfilled"===e.status)return e.value;throw"rejected"===e.status?e.reason:(e.status="pending",e.then((t=>{e.status="fulfilled",e.value=t}),(t=>{e.status="rejected",e.reason=t})),e)};function vn(e){const t=new Set;t.add("constructor");let n=e.constructor.prototype;do{for(const r of Reflect.ownKeys(n)){if(t.has(r))continue;"function"==typeof Reflect.getOwnPropertyDescriptor(n,r)?.value&&(t.add(r),e[r]=e[r].bind(e))}}while((n=Reflect.getPrototypeOf(n))&&n!==Object.prototype)}function gn(e){return"string"==typeof e}function yn(e){return t=>function(e,t){return void 0===t.resolved||e.resolved===t.resolved}(t,e)&&function(e,t){const n=e.metadata;return void 0===t.metadata||Object.entries(t.metadata).every((([e,t])=>function(e,t){return n=t,I(n)&&gn(n.startsWith)?gn(e)&&e.startsWith(t.startsWith):e===t;var n}(n[e],t)))}(t,e)}function bn(e,t){return`${e}-${fe(t??{})}`}function En(e){return`USER_THREADS:${fe(e??{})}`}function wn(e){return`${e}:NOTIFICATION_SETTINGS`}function Cn(e){return`${e}-VERSIONS`}function Dn(e){if("status"in e)return e;const t=e;return t.status="pending",t.then((e=>{t.status="fulfilled",t.value=e}),(e=>{t.status="rejected",t.reason=e})),t}var xn=Promise.resolve(),An=Object.freeze({isLoading:!0}),_n=class{constructor(e){this._cachedPromise=null,this._paginationState=null,this._fetchPage=e,this._eventSource=E(),this._pendingFetchMore=null,this.observable=this._eventSource.observable,vn(this)}patchPaginationState(e){const t=this._paginationState;null!==t&&(this._paginationState={...t,...e},this._eventSource.notify())}async _fetchMore(){const e=this._paginationState;if(e?.cursor){this.patchPaginationState({isFetchingMore:!0});try{const t=await this._fetchPage(e.cursor);this.patchPaginationState({cursor:t,fetchMoreError:void 0,isFetchingMore:!1})}catch(e){this.patchPaginationState({isFetchingMore:!1,fetchMoreError:e})}}}fetchMore(){return null===this._paginationState?.cursor?xn:(this._pendingFetchMore||(this._pendingFetchMore=this._fetchMore().finally((()=>{this._pendingFetchMore=null}))),this._pendingFetchMore)}get(){const e=this._cachedPromise;if(null===e||"pending"===e.status)return An;if("rejected"===e.status)return{isLoading:!1,error:e.reason};const t=this._paginationState;return{isLoading:!1,data:{fetchMore:this.fetchMore,isFetchingMore:t.isFetchingMore,fetchMoreError:t.fetchMoreError,hasFetchedAll:null===t.cursor}}}waitUntilLoaded(){if(this._cachedPromise)return this._cachedPromise;const e=Dn(De((()=>this._fetchPage(void 0)),5,[5e3,5e3,1e4,15e3]).then((e=>{this._paginationState={cursor:e,isFetchingMore:!1,fetchMoreError:void 0}})));return e.then((()=>this._eventSource.notify()),(()=>{this._eventSource.notify(),setTimeout((()=>{this._cachedPromise=null,this._eventSource.notify()}),5e3)})),this._cachedPromise=e,e}},Bn=class{constructor(e){this._cachedPromise=null,this._fetchPage=e,this._eventSource=E(),this.observable=this._eventSource.observable,vn(this)}get(){const e=this._cachedPromise;return null===e||"pending"===e.status?An:"rejected"===e.status?{isLoading:!1,error:e.reason}:{isLoading:!1,data:void 0}}waitUntilLoaded(){if(this._cachedPromise)return this._cachedPromise;const e=Dn(De((()=>this._fetchPage()),5,[5e3,5e3,1e4,15e3]));return e.then((()=>this._eventSource.notify()),(()=>{this._eventSource.notify(),setTimeout((()=>{this._cachedPromise=null,this._eventSource.notify()}),5e3)})),this._cachedPromise=e,e}};function On(e,t){if(void 0!==e.deletedAt)return e;if(t.threadId!==e.id)return w.warn(`Comment ${t.id} does not belong to thread ${e.id}`),e;const n=e.comments.find((e=>e.id===t.id));if(void 0===n){const n=new Date(Math.max(e.updatedAt.getTime(),t.createdAt.getTime()));return{...e,updatedAt:n,comments:[...e.comments,t]}}if(void 0!==n.deletedAt)return e;if(void 0===n.editedAt||void 0===t.editedAt||n.editedAt<=t.editedAt){const n=e.comments.map((e=>e.id===t.id?t:e));return{...e,updatedAt:new Date(Math.max(e.updatedAt.getTime(),t.editedAt?.getTime()||t.createdAt.getTime())),comments:n}}return e}function Sn(e,t,n){if(void 0!==e.deletedAt)return e;const r=e.comments.find((e=>e.id===t));if(void 0===r)return e;if(void 0!==r.deletedAt)return e;const o=e.comments.map((e=>e.id===t?{...e,deletedAt:n,body:void 0,attachments:[]}:e));return o.every((e=>void 0!==e.deletedAt))?{...e,deletedAt:n,updatedAt:n}:{...e,updatedAt:n,comments:o}}function Tn(e,t,n){if(void 0!==e.deletedAt)return e;const r=e.comments.find((e=>e.id===t));if(void 0===r)return e;if(void 0!==r.deletedAt)return e;const o=e.comments.map((e=>e.id===t?{...e,reactions:In(e.reactions,n)}:e));return{...e,updatedAt:new Date(Math.max(n.createdAt.getTime(),e.updatedAt.getTime())),comments:o}}function kn(e,t,n,r,o){if(void 0!==e.deletedAt)return e;const a=e.comments.find((e=>e.id===t));if(void 0===a)return e;if(void 0!==a.deletedAt)return e;const i=e.comments.map((e=>e.id===t?{...e,reactions:e.reactions.map((e=>e.emoji===n?{...e,users:e.users.filter((e=>e.id!==r))}:e)).filter((e=>e.users.length>0))}:e));return{...e,updatedAt:new Date(Math.max(o.getTime(),e.updatedAt.getTime())),comments:i}}function In(e,t){const n=e.find((e=>e.emoji===t.emoji));return void 0===n?[...e,{emoji:t.emoji,createdAt:t.createdAt,users:[{id:t.userId}]}]:!1===n.users.some((e=>e.id===t.userId))?e.map((e=>e.emoji===t.emoji?{...e,users:[...e.users,{id:t.userId}]}:e)):e}var Fn=t.createContext(null);function Rn(e){return new Error(`resolveUsers didn't return anything for user '${e}'`)}function Nn(e){return new Error(`resolveRoomsInfo didn't return anything for room '${e}'`)}function Pn(e){return e}var Mn=new WeakMap,jn=new WeakMap;function Ln(e){let t=0;for(const n of e)(null===n.readAt||n.readAt<n.notifiedAt)&&t++;return t}function zn(e){return e.inboxNotifications?{isLoading:!1,count:Ln(e.inboxNotifications)}:e}function Hn(e){let t=Mn.get(e);return t||(t=new class{constructor(e){this._prevVersion=-1,this._prevState=null,this._stateCached=null,this._notificationsLastRequestedAt=null,this._roomThreadsLastRequestedAtByRoom=new Map,this._roomThreads=new Map,this._userThreadsLastRequestedAt=null,this._userThreads=new Map,this._roomVersions=new Map,this._roomVersionsLastRequestedAtByRoom=new Map,this._roomNotificationSettings=new Map,this._client=e[de].as(),this._syncSource=this._client[de].createSyncSource(),this._notifications=new _n((async e=>{const t=await this._client.getInboxNotifications({cursor:e});return this.updateThreadsAndNotifications(t.threads,t.inboxNotifications),null===this._notificationsLastRequestedAt&&(this._notificationsLastRequestedAt=t.requestedAt),t.nextCursor})),this._notifications.observable.subscribe((()=>this._store.set((e=>({...e}))))),this._rawThreadsDB=new class e{constructor(){this._asc=Xt.from([],((e,t)=>{const n=e.createdAt,r=t.createdAt;return n<r||n===r&&e.id<t.id})),this._desc=Xt.from([],((e,t)=>{const n=t.updatedAt,r=e.updatedAt;return n<r||n===r&&t.id<e.id})),this._byId=new Map,this._version=0}clone(){const t=new e;return t._byId=new Map(this._byId),t._asc=this._asc.clone(),t._desc=this._desc.clone(),t._version=this._version,t}get version(){return this._version}get(e){const t=this.getEvenIfDeleted(e);return t?.deletedAt?void 0:t}getEvenIfDeleted(e){return this._byId.get(e)}upsert(e){const t=(e=function(e){return e.deletedAt&&e.comments.length>0?{...e,comments:[]}:e.comments.some((e=>!e.deletedAt))?e:{...e,deletedAt:new Date,comments:[]}}(e)).id,n=this._byId.get(t);if(n){if(n.deletedAt)return;this._asc.remove(n),this._desc.remove(n)}e.deletedAt||(this._asc.add(e),this._desc.add(e)),this._byId.set(t,e),this.touch()}upsertIfNewer(e){const t=this.get(e.id);(!t||e.updatedAt>=t.updatedAt)&&this.upsert(e)}delete(e,t){const n=this._byId.get(e);n&&!n.deletedAt&&this.upsert({...n,deletedAt:t,updatedAt:t})}findMany(e,t,n){const r="desc"===n?this._desc:this._asc,o=[];return void 0!==e&&o.push((t=>t.roomId===e)),o.push(yn(t)),Array.from(r.filter((e=>o.every((t=>t(e))))))}touch(){++this._version}},this._store=me({optimisticUpdates:[],notificationsById:{},settingsByRoomId:{},versionsByRoomId:{}}),vn(this)}get(){const e=this._store.get();return this._prevVersion===this._rawThreadsDB.version&&this._prevState===e&&null!==this._stateCached||(this._stateCached=function(e,t){const n=t.clone(),r={notificationsById:{...e.notificationsById},settingsByRoomId:{...e.settingsByRoomId}};for(const t of e.optimisticUpdates)switch(t.type){case"create-thread":n.upsert(t.thread);break;case"edit-thread-metadata":{const e=n.get(t.threadId);if(void 0===e)break;if(e.updatedAt>t.updatedAt)break;n.upsert({...e,updatedAt:t.updatedAt,metadata:{...e.metadata,...t.metadata}});break}case"mark-thread-as-resolved":{const e=n.get(t.threadId);if(void 0===e)break;n.upsert({...e,resolved:!0});break}case"mark-thread-as-unresolved":{const e=n.get(t.threadId);if(void 0===e)break;n.upsert({...e,resolved:!1});break}case"create-comment":{const e=n.get(t.comment.threadId);if(void 0===e)break;n.upsert(On(e,t.comment));const o=Object.values(r.notificationsById).find((t=>"thread"===t.kind&&t.threadId===e.id));if(void 0===o)break;r.notificationsById[o.id]={...o,notifiedAt:t.comment.createdAt,readAt:t.comment.createdAt};break}case"edit-comment":{const e=n.get(t.comment.threadId);if(void 0===e)break;n.upsert(On(e,t.comment));break}case"delete-comment":{const e=n.get(t.threadId);if(void 0===e)break;n.upsert(Sn(e,t.commentId,t.deletedAt));break}case"delete-thread":{const e=n.get(t.threadId);if(void 0===e)break;n.upsert({...e,deletedAt:t.deletedAt,updatedAt:t.deletedAt,comments:[]});break}case"add-reaction":{const e=n.get(t.threadId);if(void 0===e)break;n.upsert(Tn(e,t.commentId,t.reaction));break}case"remove-reaction":{const e=n.get(t.threadId);if(void 0===e)break;n.upsert(kn(e,t.commentId,t.emoji,t.userId,t.removedAt));break}case"mark-inbox-notification-as-read":{const e=r.notificationsById[t.inboxNotificationId];if(void 0===e)break;r.notificationsById[t.inboxNotificationId]={...e,readAt:t.readAt};break}case"mark-all-inbox-notifications-as-read":for(const e in r.notificationsById){const n=r.notificationsById[e];if(void 0===n)break;r.notificationsById[e]={...n,readAt:t.readAt}}break;case"delete-inbox-notification":delete r.notificationsById[t.inboxNotificationId];break;case"delete-all-inbox-notifications":r.notificationsById={};break;case"update-notification-settings":{const e=r.settingsByRoomId[t.roomId];if(void 0===e)break;r.settingsByRoomId[t.roomId]={...e,...t.settings}}}return{cleanedNotifications:Object.values(r.notificationsById).filter((e=>"thread"!==e.kind||void 0!==n.get(e.threadId))).sort(((e,t)=>t.notifiedAt.getTime()-e.notifiedAt.getTime())),notificationsById:r.notificationsById,settingsByRoomId:r.settingsByRoomId,threadsDB:n,versionsByRoomId:e.versionsByRoomId}}(e,this._rawThreadsDB),this._prevState=e,this._prevVersion=this._rawThreadsDB.version),this._stateCached}batch(e){return this._store.batch(e)}getFullState(){return this.get()}getRoomThreadsLoadingState(e,t){const n=bn(e,t),r=this._roomThreads.get(n);if(void 0===r)return An;const o=r.get();if(o.isLoading||o.error)return o;const a=this.getFullState().threadsDB.findMany(e,t??{},"asc"),i=o.data;return{isLoading:!1,threads:a,hasFetchedAll:i.hasFetchedAll,isFetchingMore:i.isFetchingMore,fetchMoreError:i.fetchMoreError,fetchMore:i.fetchMore}}getUserThreadsLoadingState(e){const t=En(e),n=this._userThreads.get(t);if(void 0===n)return An;const r=n.get();if(r.isLoading||r.error)return r;const o=this.getFullState().threadsDB.findMany(void 0,e??{},"desc"),a=r.data;return{isLoading:!1,threads:o,hasFetchedAll:a.hasFetchedAll,isFetchingMore:a.isFetchingMore,fetchMoreError:a.fetchMoreError,fetchMore:a.fetchMore}}getInboxNotificationsLoadingState(){const e=this._notifications.get();if(e.isLoading||e.error)return e;const t=e.data;return{isLoading:!1,inboxNotifications:this.getFullState().cleanedNotifications,hasFetchedAll:t.hasFetchedAll,isFetchingMore:t.isFetchingMore,fetchMoreError:t.fetchMoreError,fetchMore:t.fetchMore}}getNotificationSettingsLoadingState(e){const t=wn(e),n=this._roomNotificationSettings.get(t);if(void 0===n)return An;const r=n.get();return r.isLoading||r.error?r:{isLoading:!1,settings:g(this.get().settingsByRoomId[e])}}getRoomVersionsLoadingState(e){const t=Cn(e),n=this._roomVersions.get(t);if(void 0===n)return An;const r=n.get();return r.isLoading||r.error?r:{isLoading:!1,versions:Object.values(this.get().versionsByRoomId[e]??{})}}subscribe(e){return this._store.subscribe(e)}mutateThreadsDB(e){const t=this._rawThreadsDB,n=t.version;e(t),n!==t.version&&this._store.set((e=>({...e})))}updateInboxNotificationsCache(e){this._store.set((t=>{const n=e(t.notificationsById);return n!==t.notificationsById?{...t,notificationsById:n}:t}))}setNotificationSettings(e,t){this._store.set((n=>({...n,settingsByRoomId:{...n.settingsByRoomId,[e]:t}})))}updateRoomVersions(e,t){this._store.set((n=>{const r=Object.fromEntries(t.map((e=>[e.id,e])));return{...n,versionsByRoomId:{...n.versionsByRoomId,[e]:{...n.versionsByRoomId[e]??{},...r}}}}))}updateOptimisticUpdatesCache(e){this._store.set((t=>{const n=e(t.optimisticUpdates);return this._syncSource.setSyncStatus(n.length>0?"synchronizing":"synchronized"),{...t,optimisticUpdates:n}}))}force_set(e){return this._store.set(e)}updateInboxNotification(e,t,n){this._store.batch((()=>{this.removeOptimisticUpdate(t),this.updateInboxNotificationsCache((t=>{const r=t[e];return r?{...t,[e]:n(r)}:t}))}))}updateAllInboxNotifications(e,t){this._store.batch((()=>{this.removeOptimisticUpdate(e),this.updateInboxNotificationsCache((e=>function(e,t){const n={};for(const r of Object.entries(e)){const e=r[0];if("__proto__"===e)continue;const o=r[1];n[e]=t(o,e)}return n}(e,t)))}))}deleteInboxNotification(e,t){this._store.batch((()=>{this.removeOptimisticUpdate(t),this.updateInboxNotificationsCache((t=>{const{[e]:n,...r}=t;return void 0===n?t:r}))}))}deleteAllInboxNotifications(e){this._store.batch((()=>{this.removeOptimisticUpdate(e),this.updateInboxNotificationsCache((()=>({})))}))}createThread(e,t){this._store.batch((()=>{this.removeOptimisticUpdate(e),this.mutateThreadsDB((e=>e.upsert(t)))}))}updateThread(e,t,n,r){this._store.batch((()=>{null!==t&&this.removeOptimisticUpdate(t),this.mutateThreadsDB((t=>{const o=t.get(e);o&&(r&&o.updatedAt>r||t.upsert(n(o)))}))}))}patchThread(e,t,n,r){return this.updateThread(e,t,(e=>({...e,...M(n)})),r)}addReaction(e,t,n,r,o){this.updateThread(e,t,(e=>Tn(e,n,r)),o)}removeReaction(e,t,n,r,o,a){this.updateThread(e,t,(e=>kn(e,n,r,o,a)),a)}deleteThread(e,t){return this.updateThread(e,t,(e=>({...e,updatedAt:new Date,deletedAt:new Date})))}createComment(e,t){this._store.batch((()=>{this.removeOptimisticUpdate(t);const n=this._rawThreadsDB.get(e.threadId);n&&(this.mutateThreadsDB((t=>t.upsert(On(n,e)))),this.updateInboxNotificationsCache((t=>{const n=Object.values(t).find((t=>"thread"===t.kind&&t.threadId===e.threadId));return n?{...t,[n.id]:{...n,notifiedAt:e.createdAt,readAt:e.createdAt}}:t})))}))}editComment(e,t,n){return this.updateThread(e,t,(e=>On(e,n)))}deleteComment(e,t,n,r){return this.updateThread(e,t,(e=>Sn(e,n,r)),r)}updateThreadAndNotification(e,t){this._store.batch((()=>{this.mutateThreadsDB((t=>t.upsertIfNewer(e))),void 0!==t&&this.updateInboxNotificationsCache((e=>({...e,[t.id]:t})))}))}updateThreadsAndNotifications(e,t,n=[],r=[]){this._store.batch((()=>{this.mutateThreadsDB((t=>function(e,t){t.newThreads.forEach((t=>e.upsertIfNewer(t))),t.deletedThreads.forEach((({id:t,deletedAt:n})=>{e.getEvenIfDeleted(t)&&e.delete(t,n)}))}(t,{newThreads:e,deletedThreads:n}))),this.updateInboxNotificationsCache((e=>function(e,t){const n={...e};return t.newInboxNotifications.forEach((e=>{const t=n[e.id];var r,o;t&&1==(o=e,(r=t).notifiedAt>o.notifiedAt?1:r.notifiedAt<o.notifiedAt?-1:r.readAt&&o.readAt?r.readAt>o.readAt?1:r.readAt<o.readAt?-1:0:r.readAt||o.readAt?r.readAt?1:-1:0)||(n[e.id]=e)})),t.deletedNotifications.forEach((({id:e})=>delete n[e])),n}(e,{newInboxNotifications:t,deletedNotifications:r})))}))}updateRoomNotificationSettings_confirmOptimisticUpdate(e,t,n){this._store.batch((()=>{this.removeOptimisticUpdate(t),this.setNotificationSettings(e,n)}))}addOptimisticUpdate(e){const t=qe(),n={...e,id:t};return this.updateOptimisticUpdatesCache((e=>[...e,n])),t}removeOptimisticUpdate(e){this.updateOptimisticUpdatesCache((t=>t.filter((t=>t.id!==e))))}async fetchNotificationsDeltaUpdate(e){const t=this._notificationsLastRequestedAt;if(null===t)return;const n=await this._client.getInboxNotificationsSince({since:t,signal:e});t<n.requestedAt&&(this._notificationsLastRequestedAt=n.requestedAt),this.updateThreadsAndNotifications(n.threads.updated,n.inboxNotifications.updated,n.threads.deleted,n.inboxNotifications.deleted)}waitUntilNotificationsLoaded(){return this._notifications.waitUntilLoaded()}waitUntilRoomThreadsLoaded(e,t){const n=async n=>{const r=this._client.getRoom(e);if(null===r)throw new we(`Room '${e}' is not available on client`,479);const o=await r.getThreads({cursor:n,query:t});this.updateThreadsAndNotifications(o.threads,o.inboxNotifications);const a=this._roomThreadsLastRequestedAtByRoom.get(e);return(void 0===a||a>o.requestedAt)&&this._roomThreadsLastRequestedAtByRoom.set(e,o.requestedAt),o.nextCursor},r=bn(e,t);let o=this._roomThreads.get(r);return void 0===o&&(o=new _n(n)),o.observable.subscribe((()=>this._store.set((e=>({...e}))))),this._roomThreads.set(r,o),o.waitUntilLoaded()}async fetchRoomThreadsDeltaUpdate(e,t){const n=this._roomThreadsLastRequestedAtByRoom.get(e);if(void 0===n)return;const r=g(this._client.getRoom(e),`Room with id ${e} is not available on client`),o=await r.getThreadsSince({since:n,signal:t});this.updateThreadsAndNotifications(o.threads.updated,o.inboxNotifications.updated,o.threads.deleted,o.inboxNotifications.deleted),n<o.requestedAt&&this._roomThreadsLastRequestedAtByRoom.set(e,o.requestedAt)}waitUntilUserThreadsLoaded(e){const t=En(e),n=async t=>{const n=await this._client[de].getUserThreads_experimental({cursor:t,query:e});return this.updateThreadsAndNotifications(n.threads,n.inboxNotifications),null===this._userThreadsLastRequestedAt&&(this._userThreadsLastRequestedAt=n.requestedAt),n.nextCursor};let r=this._userThreads.get(t);return void 0===r&&(r=new _n(n)),r.observable.subscribe((()=>this._store.set((e=>({...e}))))),this._userThreads.set(t,r),r.waitUntilLoaded()}async fetchUserThreadsDeltaUpdate(e){const t=this._userThreadsLastRequestedAt;if(null===t)return;const n=await this._client[de].getUserThreadsSince_experimental({since:t,signal:e});t<n.requestedAt&&(this._notificationsLastRequestedAt=n.requestedAt),this.updateThreadsAndNotifications(n.threads.updated,n.inboxNotifications.updated,n.threads.deleted,n.inboxNotifications.deleted)}waitUntilRoomVersionsLoaded(e){const t=Cn(e);let n=this._roomVersions.get(t);return void 0===n&&(n=new Bn((async()=>{const t=this._client.getRoom(e);if(null===t)throw new we(`Room '${e}' is not available on client`,479);const n=await t[de].listTextVersions();this.updateRoomVersions(e,n.versions);const r=this._roomVersionsLastRequestedAtByRoom.get(e);(void 0===r||r>n.requestedAt)&&this._roomVersionsLastRequestedAtByRoom.set(e,n.requestedAt)}))),n.observable.subscribe((()=>this._store.set((e=>({...e}))))),this._roomVersions.set(t,n),n.waitUntilLoaded()}async fetchRoomVersionsDeltaUpdate(e,t){const n=this._roomVersionsLastRequestedAtByRoom.get(e);if(void 0===n)return;const r=g(this._client.getRoom(e),`Room with id ${e} is not available on client`),o=await r[de].listTextVersionsSince({since:n,signal:t});this.updateRoomVersions(e,o.versions),n<o.requestedAt&&this._roomVersionsLastRequestedAtByRoom.set(e,o.requestedAt)}waitUntilRoomNotificationSettingsLoaded(e){const t=wn(e);let n=this._roomNotificationSettings.get(t);return void 0===n&&(n=new Bn((async()=>{const t=this._client.getRoom(e);if(null===t)throw new we(`Room '${e}' is not available on client`,479);const n=await t.getNotificationSettings();this.setNotificationSettings(e,n)}))),n.observable.subscribe((()=>this._store.set((e=>({...e}))))),this._roomNotificationSettings.set(t,n),n.waitUntilLoaded()}async refreshRoomNotificationSettings(e,t){const n=g(this._client.getRoom(e),`Room with id ${e} is not available on client`),r=await n.getNotificationSettings({signal:t});this.setNotificationSettings(e,r)}}(e),Mn.set(e,t)),t}function Un(e){let t=jn.get(e);return t||(t=function(e){const t=Hn(e),n=Gt((async e=>{try{return await t.fetchNotificationsDeltaUpdate(e)}catch(e){throw console.warn(`Polling new inbox notifications failed: ${String(e)}`),e}}),ln.NOTIFICATIONS_POLL_INTERVAL,{maxStaleTimeMs:ln.NOTIFICATIONS_MAX_STALE_TIME}),r=Gt((async e=>{try{return await t.fetchUserThreadsDeltaUpdate(e)}catch(e){throw console.warn(`Polling new user threads failed: ${String(e)}`),e}}),ln.USER_THREADS_POLL_INTERVAL,{maxStaleTimeMs:ln.USER_THREADS_MAX_STALE_TIME});return{store:t,notificationsPoller:n,userThreadsPoller:r}}(e),jn.set(e,t)),t}function Wn(e,n,r){const{store:o,notificationsPoller:a}=Un(e);return t.useEffect((()=>{o.waitUntilNotificationsLoaded()})),t.useEffect((()=>(a.inc(),a.pollNowIfStale(),()=>{a.dec()})),[a]),an.exports.useSyncExternalStoreWithSelector(o.subscribe,o.getInboxNotificationsLoadingState,o.getInboxNotificationsLoadingState,n,r)}function Vn(e){const t=Un(e).store;mn(t.waitUntilNotificationsLoaded());const n=function(e){return Wn(e,zn,Zt)}(e);return n.isLoading,n.error,n}function $n(e,n){const r=e[de].usersStore,o=t.useCallback((()=>r.getState(n)),[r,n]),a=t.useCallback((e=>function(e,t){return void 0===e||e?.isLoading?e??{isLoading:!0}:e.error?e:e.data?{isLoading:!1,user:e.data}:{isLoading:!1,error:Rn(t)}}(e,n)),[n]),i=an.exports.useSyncExternalStoreWithSelector(r.subscribe,o,o,a,Zt);return t.useEffect((()=>{r.get(n)}),[r,n,i]),i}function Kn(e,n){const r=e[de].roomsInfoStore,o=t.useCallback((()=>r.getState(n)),[r,n]),a=t.useCallback((e=>function(e,t){return void 0===e||e?.isLoading?e??{isLoading:!0}:e.error?e:e.data?{isLoading:!1,info:e.data}:{isLoading:!1,error:Nn(t)}}(e,n)),[n]),i=an.exports.useSyncExternalStoreWithSelector(r.subscribe,o,o,a,Zt);return t.useEffect((()=>{r.get(n)}),[r,n,i]),i}function qn(){return t.useContext(Fn)}function Gn(){return qn()??k("LiveblocksProvider is missing from the React tree.")}function Zn(e){return function(e){const t=qn();if(!e?.allowNesting&&null!==t)throw new Error("You cannot nest multiple LiveblocksProvider instances in the same React tree.")}(e),s.default.createElement(Fn.Provider,{value:e.client},e.children)}function Xn(e){const{children:n,...r}=e,o={publicApiKey:hn(r.publicApiKey),throttle:hn(r.throttle),lostConnectionTimeout:hn(r.lostConnectionTimeout),backgroundKeepAliveTimeout:hn(r.backgroundKeepAliveTimeout),polyfills:hn(r.polyfills),unstable_fallbackToHTTP:hn(r.unstable_fallbackToHTTP),unstable_streamData:hn(r.unstable_streamData),preventUnsavedChanges:hn(r.preventUnsavedChanges),authEndpoint:pn(r.authEndpoint),resolveMentionSuggestions:pn(r.resolveMentionSuggestions),resolveUsers:pn(r.resolveUsers),resolveRoomsInfo:pn(r.resolveRoomsInfo),baseUrl:hn(r.baseUrl),enableDebugLogging:hn(r.enableDebugLogging)},a=t.useMemo((()=>Ht(o)),[]);return s.default.createElement(Zn,{client:a},n)}function Yn(){return function(e){const t=Un(e).store;mn(t.waitUntilNotificationsLoaded());const n=Wn(e,Pn,Zt);return n.error,n.isLoading,n}(Gn())}function Jn(){return e=Gn(),t.useCallback((()=>{const{store:t}=Un(e),n=new Date,r=t.addOptimisticUpdate({type:"mark-all-inbox-notifications-as-read",readAt:n});e.markAllInboxNotificationsAsRead().then((()=>{t.updateAllInboxNotifications(r,(e=>({...e,readAt:n})))}),(()=>{t.removeOptimisticUpdate(r)}))}),[e]);var e}function Qn(){return e=Gn(),t.useCallback((t=>{const{store:n}=Un(e),r=new Date,o=n.addOptimisticUpdate({type:"mark-inbox-notification-as-read",inboxNotificationId:t,readAt:r});e.markInboxNotificationAsRead(t).then((()=>{n.updateInboxNotification(t,o,(e=>({...e,readAt:r})))}),(()=>{n.removeOptimisticUpdate(o)}))}),[e]);var e}function er(){return e=Gn(),t.useCallback((()=>{const{store:t}=Un(e),n=new Date,r=t.addOptimisticUpdate({type:"delete-all-inbox-notifications",deletedAt:n});e.deleteAllInboxNotifications().then((()=>{t.deleteAllInboxNotifications(r)}),(()=>{t.removeOptimisticUpdate(r)}))}),[e]);var e}function tr(){return e=Gn(),t.useCallback((t=>{const{store:n}=Un(e),r=new Date,o=n.addOptimisticUpdate({type:"delete-inbox-notification",inboxNotificationId:t,deletedAt:r});e.deleteInboxNotification(t).then((()=>{n.deleteInboxNotification(t,o)}),(()=>{n.removeOptimisticUpdate(o)}))}),[e]);var e}function nr(e){return Kn(Gn(),e)}var rr=function(e){return function(e,n){const{store:r}=Un(e),o=r.getFullState,a=t.useCallback((e=>{const t=e.notificationsById[n]??k(`Inbox notification with ID "${n}" not found`);return"thread"!==t.kind&&k(`Inbox notification with ID "${n}" is not of kind "thread"`),e.threadsDB.get(t.threadId)??k(`Thread with ID "${t.threadId}" not found, this inbox notification might not be of kind "thread"`)}),[n]);return an.exports.useSyncExternalStoreWithSelector(r.subscribe,o,o,a)}(Gn(),e)},or=function(e){return $n(Gn(),e)},ar=class extends Error{constructor(e,t){super("Create thread failed."),this.cause=e,this.context=t,this.name="CreateThreadError"}},ir=class extends Error{constructor(e,t){super("Mark thread as resolved failed."),this.cause=e,this.context=t,this.name="MarkThreadAsResolvedError"}},sr=class extends Error{constructor(e,t){super("Mark thread as unresolved failed."),this.cause=e,this.context=t,this.name="MarkThreadAsUnresolvedError"}},ur=class extends Error{constructor(e,t){super("Create comment failed."),this.cause=e,this.context=t,this.name="CreateCommentError"}},cr=class extends Error{constructor(e,t){super("Edit comment failed."),this.cause=e,this.context=t,this.name="EditCommentError"}},lr=class extends Error{constructor(e,t){super("Delete comment failed."),this.cause=e,this.context=t,this.name="DeleteCommentError"}},dr=class extends Error{constructor(e,t){super("Add reaction failed."),this.cause=e,this.context=t,this.name="AddReactionError"}},fr=class extends Error{constructor(e,t){super("Remove reaction failed."),this.cause=e,this.context=t,this.name="RemoveReactionError"}},hr=class extends Error{constructor(e,t){super("Mark inbox notification as read failed."),this.cause=e,this.context=t,this.name="MarkInboxNotificationAsReadError"}};function pr(e,t){i.useEffect((()=>{!function(e,t){if(!1===e)return;if(!t.threads)return;if("undefined"==typeof window)return;const n=window.location.hash.slice(1);if(!n.startsWith("cm_"))return;const r=document.getElementById(n);if(null===r)return;t.threads.flatMap((e=>e.comments)).some((e=>e.id===n))&&r.scrollIntoView()}(e,t)}),[t.isLoading])}var mr=e=>e;function vr(){return null}function gr(e){const t=e.getSelf();return null===t||void 0===t.id?"anonymous":t.id}function yr(e){const t=`Request failed with status ${e.status}: ${e.message}`;if("FORBIDDEN"===e.details?.error){const n=[t,e.details.suggestion,e.details.docs].filter(Boolean).join("\n");w.error(n)}return new Error(t)}Object.freeze([]);var br=new WeakMap;function Er(e){let t=br.get(e);return t||(t=function(e){const t=Hn(e),n=E();function r(e,r,o){if(t.removeOptimisticUpdate(r),e instanceof we){const t=yr(e);n.notify(o(t))}else{if(!(e instanceof we))throw e;yr(e)}}const o=new Map,a=new Map,i=new Map;function s(e){let n=o.get(e);return n||(n=Gt((async n=>{try{return await t.fetchRoomThreadsDeltaUpdate(e,n)}catch(t){throw w.warn(`Polling new threads for '${e}' failed: ${String(t)}`),t}}),ln.ROOM_THREADS_POLL_INTERVAL,{maxStaleTimeMs:ln.ROOM_THREADS_MAX_STALE_TIME}),o.set(e,n)),n}function u(e){let n=a.get(e);return n||(n=Gt((async n=>{try{return await t.fetchRoomVersionsDeltaUpdate(e,n)}catch(t){throw w.warn(`Polling new history versions for '${e}' failed: ${String(t)}`),t}}),ln.HISTORY_VERSIONS_POLL_INTERVAL,{maxStaleTimeMs:ln.HISTORY_VERSIONS_MAX_STALE_TIME}),a.set(e,n)),n}function c(e){let n=i.get(e);return n||(n=Gt((async n=>{try{return await t.refreshRoomNotificationSettings(e,n)}catch(t){throw w.warn(`Polling notification settings for '${e}' failed: ${String(t)}`),t}}),ln.NOTIFICATION_SETTINGS_POLL_INTERVAL,{maxStaleTimeMs:ln.NOTIFICATION_SETTINGS_MAX_STALE_TIME}),i.set(e,n)),n}return{store:t,commentsErrorEventSource:n.observable,onMutationFailure:r,getOrCreateThreadsPollerForRoomId:s,getOrCreateVersionsPollerForRoomId:u,getOrCreateNotificationsSettingsPollerForRoomId:c}}(e),br.set(e,t)),t}function wr(e){const t=Gn(),{id:n,stableEnterRoom:r}=e,o=hn({initialPresence:e.initialPresence,initialStorage:e.initialStorage,unstable_batchedUpdates:e.unstable_batchedUpdates,autoConnect:e.autoConnect??"undefined"!=typeof window}),[{room:a},s]=i.useState((()=>r(n,{...o,autoConnect:!1})));return i.useEffect((()=>{const{store:e}=Er(t);return a.events.comments.subscribe((t=>{!async function(t){if(t.type===H.THREAD_DELETED)return void e.deleteThread(t.threadId,null);const n=await a.getThread(t.threadId);if(!n.thread)return void e.deleteThread(t.threadId,null);const{thread:r,inboxNotification:o}=n,i=e.getFullState().threadsDB.getEvenIfDeleted(t.threadId);switch(t.type){case H.COMMENT_EDITED:case H.THREAD_METADATA_UPDATED:case H.THREAD_UPDATED:case H.COMMENT_REACTION_ADDED:case H.COMMENT_REACTION_REMOVED:case H.COMMENT_DELETED:if(!i)break;e.updateThreadAndNotification(r,o);break;case H.COMMENT_CREATED:e.updateThreadAndNotification(r,o)}}(t)}))}),[t,a]),i.useEffect((()=>{const e=r(n,o);s(e);const{room:t,leave:a}=e;return o.autoConnect&&t.connect(),()=>{a()}}),[n,o,r]),i.createElement(un.Provider,{value:a},e.children)}function Cr(){const e=cn();if(null===e)throw new Error("RoomProvider is missing from the React tree.");return e}function Dr(){const e=Gn(),t=Cr();return i.useCallback((({threadId:n,commentId:r,body:o,attachments:a})=>{const i=new Date,{store:s,onMutationFailure:u}=Er(e),c=s.getFullState().threadsDB.getEvenIfDeleted(n);if(void 0===c)return void w.warn(`Internal unexpected behavior. Cannot edit comment in thread "${n}" because the thread does not exist in the cache.`);const l=c.comments.find((e=>e.id===r));if(void 0===l||void 0!==l.deletedAt)return void w.warn(`Internal unexpected behavior. Cannot edit comment "${r}" in thread "${n}" because the comment does not exist in the cache.`);const d=s.addOptimisticUpdate({type:"edit-comment",comment:{...l,editedAt:i,body:o,attachments:a??[]}}),f=a?.map((e=>e.id));t.editComment({threadId:n,commentId:r,body:o,attachmentIds:f}).then((e=>{s.editComment(n,d,e)}),(e=>u(e,d,(e=>new cr(e,{roomId:t.id,threadId:n,commentId:r,body:o})))))}),[e,t])}function xr(){const e=Gn(),t=Cr();return i.useCallback((({threadId:n,commentId:r,emoji:o})=>{const a=gr(t),i=new Date,{store:s,onMutationFailure:u}=Er(e),c=s.addOptimisticUpdate({type:"remove-reaction",threadId:n,commentId:r,emoji:o,userId:a,removedAt:i});t.removeReaction({threadId:n,commentId:r,emoji:o}).then((()=>{s.removeReaction(n,c,r,o,a,i)}),(e=>u(e,c,(e=>new fr(e,{roomId:t.id,threadId:n,commentId:r,emoji:o})))))}),[e,t])}function Ar(e){return void 0===e||e?.isLoading?e??{isLoading:!0}:e.error?e:(e.data,{isLoading:!1,url:e.data})}function _r(e){const t=Cr(),{attachmentUrlsStore:n}=t[de],r=i.useCallback((()=>n.getState(e)),[n,e]);return i.useEffect((()=>{n.get(e)}),[n,e]),an.exports.useSyncExternalStoreWithSelector(n.subscribe,r,r,Ar,Zt)}var Br=function(e){const t=Gn(),[n]=i.useState((()=>new Map)),r=i.useCallback(((e,r)=>{const o=n.get(e);if(o)return o;const a=t.enterRoom(e,r),i=a.leave;return a.leave=()=>{i(),n.delete(e)},n.set(e,a),a}),[t,n]);return i.createElement(wr,{...e,stableEnterRoom:r})},Or=Cr,Sr=function(){return null!==cn()},Tr=function(){const e=Gn(),t=Cr();return i.useCallback((({threadId:n,commentId:r,emoji:o})=>{const a=new Date,i=gr(t),{store:s,onMutationFailure:u}=Er(e),c=s.addOptimisticUpdate({type:"add-reaction",threadId:n,commentId:r,reaction:{emoji:o,userId:i,createdAt:a}});t.addReaction({threadId:n,commentId:r,emoji:o}).then((e=>{s.addReaction(n,c,r,e,a)}),(e=>u(e,c,(e=>new dr(e,{roomId:t.id,threadId:n,commentId:r,emoji:o})))))}),[e,t])},kr=function(){const e=Gn(),t=Cr();return i.useCallback((n=>{const r=n.body,o=n.metadata??{},a=n.attachments,i=bt(),s=Et(),u=new Date,c={id:s,threadId:i,roomId:t.id,createdAt:u,type:"comment",userId:gr(t),body:r,reactions:[],attachments:a??[]},l={id:i,type:"thread",createdAt:u,updatedAt:u,roomId:t.id,metadata:o,comments:[c],resolved:!1},{store:d,onMutationFailure:f}=Er(e),h=d.addOptimisticUpdate({type:"create-thread",thread:l,roomId:t.id}),p=a?.map((e=>e.id));return t.createThread({threadId:i,commentId:s,body:r,metadata:o,attachmentIds:p}).then((e=>{d.createThread(h,e)}),(e=>f(e,h,(e=>new ar(e,{roomId:t.id,threadId:i,commentId:s,body:r,metadata:o}))))),l}),[e,t])},Ir=function(e={query:{metadata:{}}}){const t=Gn(),n=Cr(),{store:r}=Er(t);mn(r.waitUntilRoomThreadsLoaded(n.id,e.query));const o=function(e={query:{metadata:{}}}){const{scrollOnLoad:t=!0}=e,n=Gn(),r=Cr(),{store:o,getOrCreateThreadsPollerForRoomId:a}=Er(n),s=a(r.id);i.useEffect((()=>{o.waitUntilRoomThreadsLoaded(r.id,e.query)})),i.useEffect((()=>(s.inc(),s.pollNowIfStale(),()=>s.dec())),[s]);const u=i.useCallback((()=>o.getRoomThreadsLoadingState(r.id,e.query)),[o,r.id,e.query]),c=an.exports.useSyncExternalStoreWithSelector(o.subscribe,u,u,mr,dn);return pr(t,c),c}(e);return o.error,o.isLoading,o};function Fr(...e){return function(e,t){const n=Cr(),r=n.events.self.subscribe,o=n.getSelf,a=e??mr,s=i.useCallback((e=>null!==e?a(e):null),[a]),u=vr;return an.exports.useSyncExternalStoreWithSelector(r,o,u,s,t)}(...e)}function Rr(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),!1===n||!r.defaultPrevented)return t?.(r)}}function Nr(e){const t=i.useRef(e);return i.useEffect((()=>{t.current=e})),i.useMemo((()=>(...e)=>t.current?.(...e)),[])}function Pr({prop:e,defaultProp:t,onChange:n=(()=>{})}){const[r,o]=function({defaultProp:e,onChange:t}){const n=i.useState(e),[r]=n,o=i.useRef(r),a=Nr(t);return i.useEffect((()=>{o.current!==r&&(a(r),o.current=r)}),[r,o,a]),n}({defaultProp:t,onChange:n}),a=void 0!==e,s=a?e:r,u=Nr(n);return[s,i.useCallback((t=>{if(a){const n=t,r="function"==typeof t?n(e):t;r!==e&&u(r)}else o(t)}),[a,e,o,u])]}function Mr(...e){return t=>e.forEach((e=>function(e,t){"function"==typeof e?e(t):null!=e&&(e.current=t)}(e,t)))}function jr(...e){return i.useCallback(Mr(...e),e)}m(Yt,Jt,"esm");var Lr,zr={exports:{}},Hr={};!function(e){e.exports=function(){if(Lr)return Hr;Lr=1;var e=s.default,t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,a={key:!0,ref:!0,__self:!0,__source:!0};function i(e,n,i){var s,u={},c=null,l=null;for(s in void 0!==i&&(c=""+i),void 0!==n.key&&(c=""+n.key),void 0!==n.ref&&(l=n.ref),n)r.call(n,s)&&!a.hasOwnProperty(s)&&(u[s]=n[s]);if(e&&e.defaultProps)for(s in n=e.defaultProps)void 0===u[s]&&(u[s]=n[s]);return{$$typeof:t,type:e,key:c,ref:l,props:u,_owner:o.current}}return Hr.Fragment=n,Hr.jsx=i,Hr.jsxs=i,Hr}()}(zr);var Ur=i.forwardRef(((e,t)=>{const{children:n,...r}=e,o=i.Children.toArray(n),a=o.find($r);if(a){const e=a.props.children,n=o.map((t=>t===a?i.Children.count(e)>1?i.Children.only(null):i.isValidElement(e)?e.props.children:null:t));return zr.exports.jsx(Wr,{...r,ref:t,children:i.isValidElement(e)?i.cloneElement(e,void 0,n):null})}return zr.exports.jsx(Wr,{...r,ref:t,children:n})}));Ur.displayName="Slot";var Wr=i.forwardRef(((e,t)=>{const{children:n,...r}=e;if(i.isValidElement(n)){const e=function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;if(n)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n)return e.props.ref;return e.props.ref||e.ref}(n);return i.cloneElement(n,{...Kr(r,n.props),ref:t?Mr(t,e):e})}return i.Children.count(n)>1?i.Children.only(null):null}));Wr.displayName="SlotClone";var Vr=({children:e})=>zr.exports.jsx(zr.exports.Fragment,{children:e});function $r(e){return i.isValidElement(e)&&e.type===Vr}function Kr(e,t){const n={...t};for(const r in t){const o=e[r],a=t[r];/^on[A-Z]/.test(r)?o&&a?n[r]=(...e)=>{a(...e),o(...e)}:o&&(n[r]=o):"style"===r?n[r]={...o,...a}:"className"===r&&(n[r]=[o,a].filter(Boolean).join(" "))}return{...e,...n}}var qr=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"].reduce(((e,t)=>{const n=i.forwardRef(((e,n)=>{const{asChild:r,...o}=e,a=r?Ur:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),zr.exports.jsx(a,{...o,ref:n})}));return n.displayName=`Primitive.${t}`,{...e,[t]:n}}),{});function Gr(e,t){e&&u.flushSync((()=>e.dispatchEvent(t)))}var Zr=i.forwardRef(((e,t)=>{const{pressed:n,defaultPressed:r=!1,onPressedChange:o,...a}=e,[i=!1,s]=Pr({prop:n,onChange:o,defaultProp:r});return zr.exports.jsx(qr.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...a,ref:t,onClick:Rr(e.onClick,(()=>{e.disabled||s(!i)}))})}));Zr.displayName="Toggle";var Xr=Zr;function Yr(...e){return e.filter((e=>"string"==typeof e||"number"==typeof e)).join(" ")}function Jr({children:e,className:t,...n}){return s.default.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:20,height:20,viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",role:"presentation",className:Yr("lb-icon",t),...n},e)}function Qr(e){return s.default.createElement(Jr,{...e},s.default.createElement("path",{d:"M16 6L8 14L4 10"}))}function eo(e){return s.default.createElement(Jr,{...e},s.default.createElement("path",{d:"M15 5L5 15"}),s.default.createElement("path",{d:"M5 5L15 15"}))}function to(e){return s.default.createElement(Jr,{...e},s.default.createElement("path",{d:"M4.5 6.5h11M14 6.5V14a1.5 1.5 0 0 1-1.5 1.5h-5A1.5 1.5 0 0 1 6 14V6.5M7.5 6.5V5a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1.5"}))}function no(e){return s.default.createElement(Jr,{...e},s.default.createElement("path",{d:"m11.784 5.797-6.13 6.138a4 4 0 0 0-1.03 1.775L4 16l2.285-.624a4 4 0 0 0 1.776-1.032l6.145-6.152m-2.422-2.395 1.244-1.246c.608-.608 1.826-.81 2.53-.104.7.7.499 1.893-.122 2.515l-1.23 1.23m-2.422-2.395 2.422 2.395"}))}function ro(e){return s.default.createElement(Jr,{fill:"currentColor",...e},s.default.createElement("circle",{cx:5,cy:10,r:.75}),s.default.createElement("circle",{cx:10,cy:10,r:.75}),s.default.createElement("circle",{cx:15,cy:10,r:.75}))}function oo(e){return s.default.createElement(Jr,{...e},s.default.createElement("path",{d:"M11 3.07A7 7 0 1 0 16.93 9"}),s.default.createElement("path",{d:"M7.5 11.5S8.25 13 10 13s2.5-1.5 2.5-1.5M8 8h0"}),s.default.createElement("path",{d:"M12 8h0"}),s.default.createElement("path",{d:"M13 5h4m-2-2v4"}),s.default.createElement("circle",{cx:"8",cy:"8",r:".25"}),s.default.createElement("circle",{cx:"12",cy:"8",r:".25"}))}const ao="'Apple Color Emoji', 'Noto Color Emoji', 'Twemoji Mozilla', 'Android Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', EmojiSymbols, sans-serif",io=t.forwardRef((({emoji:e,style:t,asChild:n,...r},o)=>{const a=n?Ur:"span";return s.default.createElement(a,{role:"img","aria-label":e,"data-emoji":e,style:{...t,fontFamily:ao,display:"inline-flex",alignItems:"center",justifyContent:"center",width:"1em",whiteSpace:"nowrap"},...r,ref:o},e)})),so=t.forwardRef((({className:e,...t},n)=>s.default.createElement(io,{className:Yr("lb-emoji",e),...t,ref:n})));function uo(e,t,n){return 1===e?t:n??`${t}s`}const co={locale:"en",dir:"ltr",USER_SELF:"you",USER_UNKNOWN:"Anonymous",LIST_REMAINING:e=>`${e} more`,LIST_REMAINING_USERS:e=>`${e} ${uo(e,"other")}`,LIST_REMAINING_COMMENTS:e=>`${e} more ${uo(e,"comment")}`,EMOJI_PICKER_SEARCH_PLACEHOLDER:"Search…",EMOJI_PICKER_EMPTY:"No emoji found.",EMOJI_PICKER_ERROR:()=>"There was an error while getting the list of emoji.",ATTACHMENT_TOO_LARGE:e=>e?`The file is larger than ${e}`:"The file is too large",ATTACHMENT_ERROR:()=>"The file couldn’t be uploaded.",COMPOSER_INSERT_MENTION:"Mention someone",COMPOSER_INSERT_EMOJI:"Add emoji",COMPOSER_ATTACH_FILES:"Attach files",COMPOSER_REMOVE_ATTACHMENT:"Remove attachment",COMPOSER_PLACEHOLDER:"Write a comment…",COMPOSER_SEND:"Send",COMMENT_EDITED:"(edited)",COMMENT_DELETED:"This comment has been deleted.",COMMENT_MORE:"More",COMMENT_EDIT:"Edit comment",COMMENT_EDIT_COMPOSER_PLACEHOLDER:"Edit comment…",COMMENT_EDIT_COMPOSER_CANCEL:"Cancel",COMMENT_EDIT_COMPOSER_SAVE:"Save",COMMENT_DELETE:"Delete comment",COMMENT_DELETE_ATTACHMENT:"Delete attachment",COMMENT_ADD_REACTION:"Add reaction",COMMENT_REACTION_LIST:(e,t)=>i.createElement(i.Fragment,null,e," reacted with ",i.createElement(so,{emoji:t})),COMMENT_REACTION_DESCRIPTION:(e,t)=>`${t} ${uo(t,"reaction")}, react with ${e}`,THREAD_RESOLVE:"Resolve thread",THREAD_UNRESOLVE:"Re-open thread",THREAD_NEW_INDICATOR:"New",THREAD_NEW_INDICATOR_DESCRIPTION:"New comments",THREAD_COMPOSER_PLACEHOLDER:"Reply to thread…",THREAD_COMPOSER_SEND:"Reply",INBOX_NOTIFICATION_MORE:"More",INBOX_NOTIFICATION_MARK_AS_READ:"Mark as read",INBOX_NOTIFICATION_DELETE:"Delete notification",INBOX_NOTIFICATION_THREAD_COMMENTS_LIST:(e,t)=>i.createElement(i.Fragment,null,e," commented",t?i.createElement(i.Fragment,null," in ",t):i.createElement(i.Fragment,null," in a thread")),INBOX_NOTIFICATION_THREAD_MENTION:(e,t)=>i.createElement(i.Fragment,null,e," mentioned you",t?i.createElement(i.Fragment,null," in ",t):null),INBOX_NOTIFICATION_TEXT_MENTION:(e,t)=>i.createElement(i.Fragment,null,e," mentioned you",t?i.createElement(i.Fragment,null," in ",t):null),HISTORY_VERSION_PREVIEW_AUTHORS_LIST:e=>i.createElement(i.Fragment,null,"Edits from ",e),HISTORY_VERSION_PREVIEW_RESTORE:"Restore",HISTORY_VERSION_PREVIEW_EMPTY:"No content.",HISTORY_VERSION_PREVIEW_ERROR:()=>"There was an error while getting this version."},lo=t.createContext(void 0);function fo(e){const n=t.useContext(lo);return t.useMemo((()=>({...co,...n,...e})),[n,e])}
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["exports","react","react-dom"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BuilderLiveblocks={},e.React,e.ReactDOM)}(this,(function(e,t,n){const r=window;function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function a(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var i=a(t),s=o(t),u=a(n),c=o(n),l=Object.defineProperty,d="@liveblocks/core",f="2.12.0",h="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==r?r:{};function p(e){console.error(e)}function m(e,t,n){const r=Symbol.for(e),o=n?`${t||"dev"} (${n})`:t||"dev";if(h[r])if(h[r]===o);else{p(["Multiple copies of Liveblocks are being loaded in your project. This will cause issues! See https://liveblocks.io/docs/errors/dupes ","","Conflicts:",`- ${e} ${h[r]} (already loaded)`,`- ${e} ${o} (trying to load this now)`].join("\n"))}else h[r]=o;t&&t!==f&&p(["Cross-linked versions of Liveblocks found, which will cause issues! See https://liveblocks.io/docs/errors/cross-linked ","","Conflicts:",`- ${d} is at 2.12.0`,`- ${e} is at ${t}`,"","Always upgrade all Liveblocks packages to the same version number."].join("\n"))}function v(e,t){throw new Error(t)}function g(e,t="Expected value to be non-nullable"){return e}function y(){let e,t;return[new Promise(((n,r)=>{e=n,t=r})),e,t]}function b(){const[e,t,n]=y();return{promise:e,resolve:t,reject:n}}function E(){const e=new Set,t=new Set;let n=null;function r(e){return t.add(e),()=>t.delete(e)}function o(t){return e.add(t),()=>e.delete(t)}async function a(e){let t;return new Promise((n=>{t=r((t=>{(void 0===e||e(t))&&n(t)}))})).finally((()=>t?.()))}function i(n){e.forEach((e=>e(n))),e.clear(),t.forEach((e=>e(n)))}return{notify:function(e){null!==n?n.push(e):i(e)},subscribe:r,subscribeOnce:o,_forceClear:function(){e.clear(),t.clear()},count:function(){return e.size+t.size},waitUntil:a,pause:function(){n=[]},unpause:function(){if(null!==n){for(const e of n)i(e);n=null}},observable:{subscribe:r,subscribeOnce:o,waitUntil:a}}}var w={};((e,t)=>{for(var n in t)l(e,n,{get:t[n],enumerable:!0})})(w,{error:()=>A,errorWithTitle:()=>O,warn:()=>x,warnWithTitle:()=>B});var C="background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;";function D(e){return"undefined"==typeof window?console[e]:(t,...n)=>console[e]("%cLiveblocks",C,t,...n)}var x=D("warn"),A=D("error");function _(e){return"undefined"==typeof window?console[e]:(t,n,...r)=>console[e](`%cLiveblocks%c ${t}`,C,"font-weight:600",n,...r)}var B=_("warn"),O=_("error");var S=1,T=class{get initialState(){const e=this.states.values()[Symbol.iterator]().next();if(e.done)throw new Error("No states defined yet");return e.value}get currentState(){if(null===this.currentStateOrNull)throw 0===this.runningState?new Error("Not started yet"):new Error("Already stopped");return this.currentStateOrNull}start(){if(0!==this.runningState)throw new Error("State machine has already started");return this.runningState=1,this.currentStateOrNull=this.initialState,this.enter(null),this}stop(){if(1!==this.runningState)throw new Error("Cannot stop a state machine that hasn't started yet");this.exit(null),this.runningState=2,this.currentStateOrNull=null}constructor(e){this.id=S++,this.runningState=0,this.currentStateOrNull=null,this.states=new Set,this.enterFns=new Map,this.cleanupStack=[],this.knownEventTypes=new Set,this.allowedTransitions=new Map,this.currentContext=new class{constructor(e){this.curr=e}get current(){return this.curr}allowPatching(e){const t=this;let n=!0;e({...this.curr,patch(e){if(!n)throw new Error("Can no longer patch stale context");t.curr=Object.assign({},t.curr,e);for(const t of Object.entries(e)){const[e,n]=t;"patch"!==e&&(this[e]=n)}}}),n=!1}}(e),this.eventHub={didReceiveEvent:E(),willTransition:E(),didIgnoreEvent:E(),willExitState:E(),didEnterState:E()},this.events={didReceiveEvent:this.eventHub.didReceiveEvent.observable,willTransition:this.eventHub.willTransition.observable,didIgnoreEvent:this.eventHub.didIgnoreEvent.observable,willExitState:this.eventHub.willExitState.observable,didEnterState:this.eventHub.didEnterState.observable}}get context(){return this.currentContext.current}addState(e){if(0!==this.runningState)throw new Error("Already started");return this.states.add(e),this}onEnter(e,t){if(0!==this.runningState)throw new Error("Already started");if(this.enterFns.has(e))throw new Error(`enter/exit function for ${e} already exists`);return this.enterFns.set(e,t),this}onEnterAsync(e,t,n,r,o){return this.onEnter(e,(()=>{const e=new AbortController,a=e.signal,i=o?setTimeout((()=>{const e=new Error("Timed out");this.transition({type:"ASYNC_ERROR",reason:e},r)}),o):void 0;let s=!1;return t(this.currentContext.current,a).then((e=>{a.aborted||(s=!0,this.transition({type:"ASYNC_OK",data:e},n))}),(e=>{a.aborted||(s=!0,this.transition({type:"ASYNC_ERROR",reason:e},r))})),()=>{clearTimeout(i),s||e.abort()}}))}getStatesMatching(e){const t=[];if("*"===e)for(const e of this.states)t.push(e);else if(e.endsWith(".*")){const n=e.slice(0,-1);for(const e of this.states)e.startsWith(n)&&t.push(e)}else{const n=e;this.states.has(n)&&t.push(n)}if(0===t.length)throw new Error(`No states match ${JSON.stringify(e)}`);return t}addTransitions(e,t){if(0!==this.runningState)throw new Error("Already started");for(const n of this.getStatesMatching(e)){let r=this.allowedTransitions.get(n);void 0===r&&(r=new Map,this.allowedTransitions.set(n,r));for(const[o,a]of Object.entries(t)){if(r.has(o))throw new Error(`Trying to set transition "${o}" on "${n}" (via "${e}"), but a transition already exists there.`);const t=a;if(this.knownEventTypes.add(o),void 0!==t){const e="function"==typeof t?t:()=>t;r.set(o,e)}}}return this}addTimedTransition(e,t,n){return this.onEnter(e,(()=>{const e="function"==typeof t?t(this.currentContext.current):t,r=setTimeout((()=>{this.transition({type:"TIMER"},n)}),e);return()=>{clearTimeout(r)}}))}getTargetFn(e){return this.allowedTransitions.get(this.currentState)?.get(e)}exit(e){this.eventHub.willExitState.notify(this.currentState),this.currentContext.allowPatching((t=>{e=e??this.cleanupStack.length;for(let n=0;n<e;n++)this.cleanupStack.pop()?.(t)}))}enter(e){const t=function(e,t){const n=e.split(".");if(t<1||t>n.length+1)throw new Error("Invalid number of levels");const r=[];t>n.length&&r.push("*");for(let e=n.length-t+1;e<n.length;e++){const t=n.slice(0,e);t.length>0&&r.push(t.join(".")+".*")}return r.push(e),r}(this.currentState,e??this.currentState.split(".").length+1);this.currentContext.allowPatching((e=>{for(const n of t){const t=this.enterFns.get(n)?.(e);"function"==typeof t?this.cleanupStack.push(t):this.cleanupStack.push(null)}})),this.eventHub.didEnterState.notify(this.currentState)}send(e){if(!this.knownEventTypes.has(e.type))throw new Error(`Invalid event ${JSON.stringify(e.type)}`);if(2===this.runningState)return;const t=this.getTargetFn(e.type);if(void 0!==t)return this.transition(e,t);this.eventHub.didIgnoreEvent.notify(e)}transition(e,t){this.eventHub.didReceiveEvent.notify(e);const n=this.currentState,r=("function"==typeof t?t:()=>t)(e,this.currentContext.current);let o,a;if(null===r)return void this.eventHub.didIgnoreEvent.notify(e);if("string"==typeof r?o=r:(o=r.target,a=Array.isArray(r.effect)?r.effect:[r.effect]),!this.states.has(o))throw new Error(`Invalid next state name: ${JSON.stringify(o)}`);this.eventHub.willTransition.notify({from:n,to:o});const[i,s]=function(e,t){if(e===t)return[0,0];const n=e.split("."),r=t.split("."),o=Math.min(n.length,r.length);let a=0;for(;a<o&&n[a]===r[a];a++);return[n.length-a,r.length-a]}(this.currentState,o);if(i>0&&this.exit(i),this.currentStateOrNull=o,void 0!==a){const t=a;this.currentContext.allowPatching((n=>{for(const r of t)"function"==typeof r?r(n,e):n.patch(r)}))}s>0&&this.enter(s)}};function k(e){throw new Error(e)}function I(e){return null!==e&&"object"==typeof e&&"[object Object]"===Object.prototype.toString.call(e)}function F(e){return Object.entries(e)}function R(e){try{return JSON.parse(e)}catch(e){return}}function N(e){return JSON.parse(JSON.stringify(e))}function P(e){return e.filter((e=>null!=e))}function M(e){const t={...e};return Object.keys(e).forEach((e=>{const n=e;void 0===t[n]&&delete t[n]})),t}function j(e){return new Promise((t=>setTimeout(t,e)))}async function L(e,t,n){let r;const o=new Promise(((e,o)=>{r=setTimeout((()=>{o(new Error(n))}),t)}));return Promise.race([e,o]).finally((()=>clearTimeout(r)))}function z(e){let t=null;return()=>(null===t&&(t=e().catch((e=>{throw setTimeout((()=>{t=null}),5e3),e}))),t)}var H=(e=>(e[e.UPDATE_PRESENCE=100]="UPDATE_PRESENCE",e[e.USER_JOINED=101]="USER_JOINED",e[e.USER_LEFT=102]="USER_LEFT",e[e.BROADCASTED_EVENT=103]="BROADCASTED_EVENT",e[e.ROOM_STATE=104]="ROOM_STATE",e[e.INITIAL_STORAGE_STATE=200]="INITIAL_STORAGE_STATE",e[e.UPDATE_STORAGE=201]="UPDATE_STORAGE",e[e.REJECT_STORAGE_OP=299]="REJECT_STORAGE_OP",e[e.UPDATE_YDOC=300]="UPDATE_YDOC",e[e.THREAD_CREATED=400]="THREAD_CREATED",e[e.THREAD_DELETED=407]="THREAD_DELETED",e[e.THREAD_METADATA_UPDATED=401]="THREAD_METADATA_UPDATED",e[e.THREAD_UPDATED=408]="THREAD_UPDATED",e[e.COMMENT_CREATED=402]="COMMENT_CREATED",e[e.COMMENT_EDITED=403]="COMMENT_EDITED",e[e.COMMENT_DELETED=404]="COMMENT_DELETED",e[e.COMMENT_REACTION_ADDED=405]="COMMENT_REACTION_ADDED",e[e.COMMENT_REACTION_REMOVED=406]="COMMENT_REACTION_REMOVED",e))(H||{});function U(e){return 4999===e||e>=4e3&&e<4100}function W(e){return 1013===e||e>=4200&&e<4300}function V(e){const t=e.currentState;switch(t){case"@ok.connected":case"@ok.awaiting-pong":return"connected";case"@idle.initial":return"initial";case"@auth.busy":case"@auth.backoff":case"@connecting.busy":case"@connecting.backoff":case"@idle.zombie":return e.context.successCount>0?"reconnecting":"connecting";case"@idle.failed":return"disconnected";default:return v(0,"Unknown state")}}var $=[250,500,1e3,2e3,4e3,8e3,1e4],K=$[0]-1,q=[2e3,3e4,6e4,3e5],G=class extends Error{constructor(e){super(e)}},Z=class extends Error{constructor(e,t){super(e),this.code=t}};function X(e,t){return t.find((t=>t>e))??t[t.length-1]}function Y(e){e.patch({backoffDelay:X(e.backoffDelay,$)})}function J(e){e.patch({backoffDelay:X(e.backoffDelay,q)})}function Q(e){e.patch({successCount:0})}function ee(e,t){const n=2===e?A:1===e?x:()=>{};return()=>{n(t)}}function te(e){const t="Connection to Liveblocks websocket server";return n=>{e instanceof Error?x(`${t} could not be established. ${String(e)}`):x(oe(e)?`${t} closed prematurely (code: ${e.code}). Retrying in ${n.backoffDelay}ms.`:`${t} could not be established.`)}}function ne(e){const t=[`code: ${e.code}`];return e.reason&&t.push(`reason: ${e.reason}`),e=>{x(`Connection to Liveblocks websocket server closed (${t.join(", ")}). Retrying in ${e.backoffDelay}ms.`)}}var re=ee(1,"Connection to WebSocket closed permanently. Won't retry.");function oe(e){return!(e instanceof Error)&&"close"===e.type}var ae=e=>t=>t.patch(e);function ie(e,t){const n=E();n.pause();const r=E();function o(e,t){return()=>{const n=new Z(e,t);r.notify(n)}}const a=new T({successCount:0,authValue:null,socket:null,backoffDelay:K}).addState("@idle.initial").addState("@idle.failed").addState("@idle.zombie").addState("@auth.busy").addState("@auth.backoff").addState("@connecting.busy").addState("@connecting.backoff").addState("@ok.connected").addState("@ok.awaiting-pong");a.addTransitions("*",{RECONNECT:{target:"@auth.backoff",effect:[Y,Q]},DISCONNECT:"@idle.initial"}),a.onEnter("@idle.*",Q).addTransitions("@idle.*",{CONNECT:(e,t)=>null!==t.authValue?"@connecting.busy":"@auth.busy"}),a.addTransitions("@auth.backoff",{NAVIGATOR_ONLINE:{target:"@auth.busy",effect:ae({backoffDelay:K})}}).addTimedTransition("@auth.backoff",(e=>e.backoffDelay),"@auth.busy").onEnterAsync("@auth.busy",(()=>L(e.authenticate(),1e4,"Timed out during auth")),(e=>({target:"@connecting.busy",effect:ae({authValue:e.data})})),(e=>e.reason instanceof G?{target:"@idle.failed",effect:[ee(2,e.reason.message),o(e.reason.message,-1)]}:{target:"@auth.backoff",effect:[Y,ee(2,`Authentication failed: ${e.reason instanceof Error?e.reason.message:String(e.reason)}`)]}));const i=e=>a.send({type:"EXPLICIT_SOCKET_ERROR",event:e}),s=e=>a.send({type:"EXPLICIT_SOCKET_CLOSE",event:e}),u=e=>"pong"===e.data?a.send({type:"PONG"}):n.notify(e);function c(e){e&&(e.removeEventListener("error",i),e.removeEventListener("close",s),e.removeEventListener("message",u),e.close())}a.addTransitions("@connecting.backoff",{NAVIGATOR_ONLINE:{target:"@connecting.busy",effect:ae({backoffDelay:K})}}).addTimedTransition("@connecting.backoff",(e=>e.backoffDelay),"@connecting.busy").onEnterAsync("@connecting.busy",(async(n,r)=>{let o=null,a=null;return L(new Promise(((r,c)=>{if(null===n.authValue)throw new Error("No auth authValue");const l=e.createSocket(n.authValue);function d(e){o=e,l.removeEventListener("message",u),c(e)}a=l;const[f,h]=y();function p(e){104===R(e.data)?.type&&h()}t.waitForActorId||h(),l.addEventListener("message",u),t.waitForActorId&&l.addEventListener("message",p),l.addEventListener("error",d),l.addEventListener("close",d),l.addEventListener("open",(()=>{l.addEventListener("error",i),l.addEventListener("close",s);const e=()=>{l.removeEventListener("error",d),l.removeEventListener("close",d),l.removeEventListener("message",p)};f.then((()=>{r([l,e])}))}))})),1e4,"Timed out during websocket connection").then((([e,t])=>{if(t(),r.aborted)throw new Error("Aborted");if(o)throw o;return e})).catch((e=>{throw c(a),e}))}),(e=>({target:"@ok.connected",effect:ae({socket:e.data,backoffDelay:K})})),(e=>{const t=e.reason;if(t instanceof G)return{target:"@idle.failed",effect:[ee(2,t.message),o(t.message,-1)]};if(oe(t)){if(4109===t.code)return"@auth.busy";if(W(t.code))return{target:"@connecting.backoff",effect:[J,te(t)]};if(U(t.code))return{target:"@idle.failed",effect:[ee(2,t.reason),o(t.reason,t.code)]}}return{target:"@auth.backoff",effect:[Y,te(t)]}}));const l={target:"@ok.awaiting-pong",effect:e=>{e.socket?.send("ping")}},d=()=>"hidden"===("undefined"!=typeof document?document:void 0)?.visibilityState&&e.canZombie()?"@idle.zombie":l;if(a.addTimedTransition("@ok.connected",3e4,d).addTransitions("@ok.connected",{NAVIGATOR_OFFLINE:d,WINDOW_GOT_FOCUS:l}),a.addTransitions("@idle.zombie",{WINDOW_GOT_FOCUS:"@connecting.backoff"}),a.onEnter("@ok.*",(e=>{e.patch({successCount:e.successCount+1});const t=setTimeout(n.unpause,0);return e=>{c(e.socket),e.patch({socket:null}),clearTimeout(t),n.pause()}})).addTransitions("@ok.awaiting-pong",{PONG:"@ok.connected"}).addTimedTransition("@ok.awaiting-pong",2e3,{target:"@connecting.busy",effect:ee(1,"Received no pong from server, assume implicit connection loss.")}).addTransitions("@ok.*",{EXPLICIT_SOCKET_ERROR:(e,t)=>1===t.socket?.readyState?null:{target:"@connecting.backoff",effect:Y},EXPLICIT_SOCKET_CLOSE:e=>{return U(e.event.code)?{target:"@idle.failed",effect:[re,o(e.event.reason,e.event.code)]}:(t=e.event.code)>=4100&&t<4200?4109===e.event.code?"@auth.busy":{target:"@auth.backoff",effect:[Y,ne(e.event)]}:W(e.event.code)?{target:"@connecting.backoff",effect:[J,ne(e.event)]}:{target:"@connecting.backoff",effect:[Y,ne(e.event)]};var t}}),"undefined"!=typeof document){const e="undefined"!=typeof document?document:void 0,t="undefined"!=typeof window?window:void 0,n=t??e;a.onEnter("*",(r=>{function o(){a.send({type:"NAVIGATOR_OFFLINE"})}function i(){a.send({type:"NAVIGATOR_ONLINE"})}function s(){"visible"===e?.visibilityState&&a.send({type:"WINDOW_GOT_FOCUS"})}return t?.addEventListener("online",i),t?.addEventListener("offline",o),n?.addEventListener("visibilitychange",s),()=>{n?.removeEventListener("visibilitychange",s),t?.removeEventListener("online",i),t?.removeEventListener("offline",o),c(r.socket)}}))}const f=[],{statusDidChange:h,didConnect:p,didDisconnect:m,unsubscribe:v}=function(e){const t=E(),n=E(),r=E();let o=null;const a=e.events.didEnterState.subscribe((()=>{const a=V(e);a!==o&&t.notify(a),"connected"===o&&"connected"!==a?r.notify():"connected"!==o&&"connected"===a&&n.notify(),o=a}));return{statusDidChange:t.observable,didConnect:n.observable,didDisconnect:r.observable,unsubscribe:a}}(a);return f.push(v),t.enableDebugLogging&&f.push(function(e){const t=(new Date).getTime();function n(...n){x(`${(((new Date).getTime()-t)/1e3).toFixed(2)} [FSM #${e.id}]`,...n)}const r=[e.events.didReceiveEvent.subscribe((e=>n(`Event ${e.type}`))),e.events.willTransition.subscribe((({from:e,to:t})=>n("Transitioning",e,"→",t))),e.events.didIgnoreEvent.subscribe((e=>n("Ignored event",e.type,e,"(current state won't handle it)")))];return()=>{for(const e of r)e()}}(a)),a.start(),{machine:a,cleanups:f,events:{statusDidChange:h,didConnect:p,didDisconnect:m,onMessage:n.observable,onLiveblocksError:r.observable}}}function se(e){return e.includes("room:write")}function ue(e){return e.includes("comments:write")||e.includes("room:write")}function ce(e){const t=e.split(".");if(3!==t.length)throw new Error("Authentication error: invalid JWT token");const n=R(function(e){try{const t=e.replace(/-/g,"+").replace(/_/g,"/");return decodeURIComponent(atob(t).split("").map((function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)})).join(""))}catch(t){return atob(e)}}(t[1]));if(!n||(!I(r=n)||"acc"!==r.k&&"id"!==r.k&&"sec-legacy"!==r.k))throw new Error("Authentication error: expected a valid token but did not get one. Hint: if you are using a callback, ensure the room is passed when creating the token. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientCallback");var r;return{raw:e,parsed:n}}function le(e){const t=function(e){const{publicApiKey:t,authEndpoint:n}=e;if(void 0!==n&&void 0!==t)throw new Error("You cannot simultaneously use `publicApiKey` and `authEndpoint` options. Please pick one and leave the other option unspecified. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient");if("string"==typeof t){if(t.startsWith("sk_"))throw new Error("Invalid `publicApiKey` option. The value you passed is a secret key, which should not be used from the client. Please only ever pass a public key here. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");if(!t.startsWith("pk_"))throw new Error("Invalid key. Please use the public key format: pk_<public key>. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientPublicKey");return{type:"public",publicApiKey:t}}if("string"==typeof n)return{type:"private",url:n};if("function"==typeof n)return{type:"custom",callback:n};if(void 0!==n)throw new Error("The `authEndpoint` option must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint");throw new Error("Invalid Liveblocks client options. Please provide either a `publicApiKey` or `authEndpoint` option. They cannot both be empty. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClient")}(e),n=new Set,r=[],o=[],a=new Map;function i(e,t){return"comments:read"===e?t.includes("comments:read")||t.includes("comments:write")||t.includes("room:read")||t.includes("room:write"):"room:read"===e&&(t.includes("room:read")||t.includes("room:write"))}async function s(r){const o=e.polyfills?.fetch??("undefined"==typeof window?void 0:window.fetch);if("private"===t.type){if(void 0===o)throw new G("To use Liveblocks client in a non-DOM environment with a url as auth endpoint, you need to provide a fetch polyfill.");const e=ce((await async function(e,t,n){const r=await e(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const e=`${(await r.text()).trim()||"reason not provided in auth response"} (${r.status} returned by POST ${t})`;throw 401===r.status||403===r.status?new G(`Unauthorized: ${e}`):new Error(`Failed to authenticate: ${e}`)}let o;try{o=await r.json()}catch(e){throw new Error(`Expected a JSON response when doing a POST request on "${t}". ${String(e)}`)}if(!I(o)||"string"!=typeof o.token)throw new Error(`Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${t}", but got ${JSON.stringify(o)}`);const{token:a}=o;return{token:a}}(o,t.url,{room:r.roomId})).token);if(n.has(e.raw))throw new G("The same Liveblocks auth token was issued from the backend before. Caching Liveblocks tokens is not supported.");return e}if("custom"===t.type){const e=await t.callback(r.roomId);if(e&&"object"==typeof e){if("string"==typeof e.token){return ce(e.token)}if("string"==typeof e.error){const t=`Authentication failed: ${"reason"in e&&"string"==typeof e.reason?e.reason:"Forbidden"}`;throw"forbidden"===e.error?new G(t):new Error(t)}}throw new Error('Your authentication callback function should return a token, but it did not. Hint: the return value should look like: { token: "..." }')}throw new Error("Unexpected authentication type. Must be private or custom.")}return{reset:function(){n.clear(),r.length=0,o.length=0,a.clear()},getAuthValue:async function(e){if("public"===t.type)return{type:"public",publicApiKey:t.publicApiKey};const u=function(e){const t=Math.ceil(Date.now()/1e3);for(let n=r.length-1;n>=0;n--){const a=r[n];if(o[n]<=t)r.splice(n,1),o.splice(n,1);else{if("id"===a.parsed.k)return a;if("acc"===a.parsed.k){if(!e.roomId&&0===Object.entries(a.parsed.perms).length)return a;for(const[t,n]of Object.entries(a.parsed.perms))if(e.roomId){if(t.includes("*")&&e.roomId.startsWith(t.replace("*",""))||e.roomId===t&&i(e.requestedScope,n))return a}else if(t.includes("*")&&i(e.requestedScope,n))return a}}}}(e);if(void 0!==u)return{type:"secret",token:u};let c;e.roomId?(c=a.get(e.roomId),void 0===c&&(c=s(e),a.set(e.roomId,c))):(c=a.get("liveblocks-user-token"),void 0===c&&(c=s(e),a.set("liveblocks-user-token",c)));try{const t=await c,i=30,s=Math.floor(Date.now()/1e3)+(t.parsed.exp-t.parsed.iat)-i;return n.add(t.raw),"sec-legacy"!==t.parsed.k&&(r.push(t),o.push(s)),{type:"secret",token:t}}finally{e.roomId?a.delete(e.roomId):a.delete("liveblocks-user-token")}}}}var de=Symbol();function fe(e,...t){if("object"!=typeof e||null===e||Array.isArray(e))return JSON.stringify(e,...t);const n=Object.keys(e).sort().reduce(((t,n)=>(t[n]=e[n],t)),{});return JSON.stringify(n,...t)}E().observable;var he=class{constructor(e,t){this.queue=[],this.error=!1,this.callback=e,this.size=t.size??50,this.delay=t.delay}clearDelayTimeout(){void 0!==this.delayTimeoutId&&(clearTimeout(this.delayTimeoutId),this.delayTimeoutId=void 0)}schedule(){this.queue.length===this.size?this.flush():1===this.queue.length&&(this.clearDelayTimeout(),this.delayTimeoutId=setTimeout((()=>{this.flush()}),this.delay))}async flush(){if(0===this.queue.length)return;const e=this.queue.splice(0),t=e.map((e=>e.input));try{const n=await this.callback(t);this.error=!1,e.forEach(((t,r)=>{const o=n?.[r];Array.isArray(n)?e.length!==n.length?t.reject(new Error(`Callback must return an array of the same length as the number of provided items. Expected ${e.length}, but got ${n.length}.`)):o instanceof Error?t.reject(o):t.resolve(o):t.reject(new Error("Callback must return an array."))}))}catch(t){this.error=!0,e.forEach((e=>{e.reject(t)}))}}get(e){const t=this.queue.find((t=>fe(t.input)===fe(e)));if(t)return t.promise;const n=new class{constructor(e){this.input=e;const{promise:t,resolve:n,reject:r}=b();this.promise=t,this.resolve=n,this.reject=r}}(e);return this.queue.push(n),this.schedule(),n.promise}clear(){this.queue=[],this.error=!1,this.clearDelayTimeout()}};function pe(e){const t=new Map,n=E();function r(e){return fe(e)}function o(e,r){t.set(e,r),n.notify()}return{...n.observable,get:async function(n){const a=r(n);if(!t.has(a))try{o(a,{isLoading:!0});o(a,{isLoading:!1,data:await e.get(n)})}catch(e){o(a,{isLoading:!1,error:e})}},getState:function(e){const n=r(e);return t.get(n)},invalidate:function(e){if(Array.isArray(e))for(const n of e)t.delete(r(n));else t.clear();n.notify()},_cacheKeys:function(){return[...t.keys()]}}}function me(e){let t=!0,n=!1,r=e;const o=new Set;function a(){if(n){n=!1;for(const e of o)e(r)}}return{get:function(){return r},set:function(e){const o=r,i=e(o);i!==o&&(r=i,n=!0),t&&a()},batch:function(e){if(!1===t)return e();t=!1;try{e()}finally{t=!0,a()}},subscribe:function(e){return o.add(e),()=>{o.delete(e)}}}}function ve(e){const t=e.editedAt?new Date(e.editedAt):void 0,n=new Date(e.createdAt),r=e.reactions.map((e=>({...e,createdAt:new Date(e.createdAt)})));if(e.body)return{...e,reactions:r,createdAt:n,editedAt:t};{const o=new Date(e.deletedAt);return{...e,reactions:r,createdAt:n,editedAt:t,deletedAt:o}}}function ge(e){const t=new Date(e.createdAt),n=new Date(e.updatedAt),r=e.comments.map((e=>ve(e)));return{...e,createdAt:t,updatedAt:n,comments:r}}function ye(e){const t=new Date(e.notifiedAt),n=e.readAt?new Date(e.readAt):null;if("activities"in e){const r=e.activities.map((e=>({...e,createdAt:new Date(e.createdAt)})));return{...e,notifiedAt:t,readAt:n,activities:r}}return{...e,notifiedAt:t,readAt:n}}function be(e){const t=new Date(e.deletedAt);return{...e,deletedAt:t}}function Ee(e){const t=new Date(e.deletedAt);return{...e,deletedAt:t}}var we=class extends Error{constructor(e,t,n){super(e),this.message=e,this.status=t,this.details=n}},Ce=e=>e instanceof we&&e.status>=400&&e.status<500;async function De(e,t,n,r=Ce){const o=n.length>0?n[n.length-1]:0;let a=0;for(;;){a++;try{return await e()}catch(e){if(r(e))throw e;if(a>=t)throw new Error(`Failed after ${t} attempts: ${String(e)}`)}const i=n[a-1]??o;x(`Attempt ${a} was unsuccessful. Retrying in ${i} milliseconds.`),await j(i)}}function xe(e,t,n){const r=new URL(t,e);return void 0!==n&&(r.search=(n instanceof URLSearchParams?n:function(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))null!=r&&t.set(n,r.toString());return t}(n)).toString()),r.toString()}function Ae(e,...t){return e.reduce(((e,n,r)=>e+encodeURIComponent(t[r-1]??"")+n))}function _e(e){return"public"===e.type?e.publicApiKey:e.token.raw}var Be=class{constructor(e,t,n){this._baseUrl=e,this._fetchPolyfill=t,this._authCallback=n}async rawFetch(e,t,n){e.startsWith("/v2/c/")||k("This client can only be used to make /v2/c/* requests");const r=xe(this._baseUrl,e,n);return await this._fetchPolyfill(r,{...t,headers:{"Content-Type":"application/json; charset=utf-8",...t?.headers,Authorization:`Bearer ${_e(await this._authCallback())}`,"X-LB-Client":f}})}async fetch(e,t,n){const r=await this.rawFetch(e,t,n);if(!r.ok){let e;try{const t=await r.json();e=new we(t.message,r.status,t)}catch{e=new we(r.statusText,r.status)}throw e}let o;try{o=await r.json()}catch{o={}}return o}async rawGet(e,t,n){return await this.rawFetch(e,n,t)}async rawPost(e,t){return await this.rawFetch(e,{method:"POST",body:JSON.stringify(t)})}async rawDelete(e){return await this.rawFetch(e,{method:"DELETE"})}async get(e,t,n){return await this.fetch(e,n,t)}async post(e,t,n,r){return await this.fetch(e,{...n,method:"POST",body:JSON.stringify(t)},r)}async delete(e){return await this.fetch(e,{method:"DELETE"})}async putBlob(e,t,n,r){return await this.fetch(e,{...r,method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:t},n)}};function Oe({baseUrl:e,authManager:t,currentUserIdStore:n,fetchPolyfill:r}){const o=new Be(e,r,(async function(){const e=await t.getAuthValue({requestedScope:"comments:read"});if("secret"===e.type&&"acc"===e.token.parsed.k){const t=e.token.parsed.uid;n.set((()=>t))}return e}));const a=new he((async e=>{const t=e.flat();return await async function(e){await o.post(Ae`/v2/c/inbox-notifications/read`,{inboxNotificationIds:e})}(t),t}),{delay:50});return{getInboxNotifications:async function(e){const t=await o.get(Ae`/v2/c/inbox-notifications`,{cursor:e?.cursor,limit:50});return{inboxNotifications:t.inboxNotifications.map(ye),threads:t.threads.map(ge),nextCursor:t.meta.nextCursor,requestedAt:new Date(t.meta.requestedAt)}},getInboxNotificationsSince:async function(e){const t=await o.get(Ae`/v2/c/inbox-notifications/delta`,{since:e.since.toISOString()},{signal:e?.signal});return{inboxNotifications:{updated:t.inboxNotifications.map(ye),deleted:t.deletedInboxNotifications.map(Ee)},threads:{updated:t.threads.map(ge),deleted:t.deletedThreads.map(be)},requestedAt:new Date(t.meta.requestedAt)}},getUnreadInboxNotificationsCount:async function(){const{count:e}=await o.get(Ae`/v2/c/inbox-notifications/count`);return e},markAllInboxNotificationsAsRead:async function(){await o.post(Ae`/v2/c/inbox-notifications/read`,{inboxNotificationIds:"all"})},markInboxNotificationAsRead:async function(e){await a.get(e)},deleteAllInboxNotifications:async function(){await o.delete(Ae`/v2/c/inbox-notifications`)},deleteInboxNotification:async function(e){await o.delete(Ae`/v2/c/inbox-notifications/${e}`)},getUserThreads_experimental:async function(e){let t;e?.query&&(t=Dt(e.query));const n=await o.get(Ae`/v2/c/threads`,{cursor:e.cursor,query:t,limit:50});return{threads:n.threads.map(ge),inboxNotifications:n.inboxNotifications.map(ye),nextCursor:n.meta.nextCursor,requestedAt:new Date(n.meta.requestedAt)}},getUserThreadsSince_experimental:async function(e){const t=await o.get(Ae`/v2/c/threads/delta`,{since:e.since.toISOString()},{signal:e.signal});return{threads:{updated:t.threads.map(ge),deleted:t.deletedThreads.map(be)},inboxNotifications:{updated:t.inboxNotifications.map(ye),deleted:t.deletedInboxNotifications.map(Ee)},requestedAt:new Date(t.meta.requestedAt)}}}}function Se(e,t){let n=!1;const r={...e};return Object.keys(t).forEach((e=>{const o=e,a=t[o];r[o]!==a&&(void 0===a?delete r[o]:r[o]=a,n=!0)})),n?r:e}var Te=class{constructor(){this._ev=E()}get didInvalidate(){return this._ev.observable}invalidate(){null!==this._cache&&(this._cache=null,this._ev.notify())}get current(){return this._cache??(this._cache=this._toImmutable())}},ke=class extends Te{constructor(e){super(),this._value=e}_toImmutable(){return this._value}set(e){this._value!==e&&(this._value=e,this.invalidate())}},Ie=class extends Te{constructor(...e){super();const t=e.pop(),n=e;this._refs=n,this._refs.forEach((e=>{e.didInvalidate.subscribe((()=>this.invalidate()))})),this._transform=t}_toImmutable(){return this._transform(...this._refs.map((e=>e.current)))}},Fe=32,Re=126,Ne=je(0),Pe=je(1),Me=Ne+je(-1);function je(e){const t=Fe+(e<0?95+e:e);if(t<Fe||t>Re)throw new Error(`Invalid n value: ${e}`);return String.fromCharCode(t)}function Le(e,t){return void 0!==e&&void 0!==t?function(e,t){if(e<t)return ze(e,t);if(e>t)return ze(t,e);throw new Error("Cannot compute value between two equal positions")}(e,t):void 0!==e?function(e){for(let t=0;t<=e.length-1;t++){const n=e.charCodeAt(t);if(!(n>=Re))return e.substring(0,t)+String.fromCharCode(n+1)}return e+Pe}(e):void 0!==t?function(e){const t=e.length-1;for(let n=0;n<=t;n++){const r=e.charCodeAt(n);if(!(r<=Fe))return n===t?33===r?e.substring(0,n)+Me:e.substring(0,n)+String.fromCharCode(r-1):e.substring(0,n+1)}return Pe}(t):Pe}function ze(e,t){let n=0;const r=e.length,o=t.length;for(;;){const a=n<r?e.charCodeAt(n):Fe,i=n<o?t.charCodeAt(n):Re;if(a!==i){if(i-a==1){const t=n+1;let r=e.substring(0,t);r.length<t&&(r+=Ne.repeat(t-r.length));return r+ze(e.substring(t),"")}return He(e,n)+String.fromCharCode(i+a>>1)}n++}}function He(e,t){return t<e.length?e.substring(0,t):e+Ne.repeat(t-e.length)}function Ue(e){return function(e){if(""===e)return!1;const t=e.length-1,n=e.charCodeAt(t);if(n<33||n>Re)return!1;for(let n=0;n<t;n++){const t=e.charCodeAt(n);if(t<Fe||t>Re)return!1}return!0}(e)?e:function(e){const t=[];for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);t.push(r<Fe?Fe:r>Re?Re:r)}for(;t.length>0&&t[t.length-1]===Fe;)t.length--;return t.length>0?String.fromCharCode(...t):Pe}(e)}function We(e,t,n=Ue(t)){return Object.freeze({type:"HasParent",node:e,key:t,pos:n})}var Ve=Object.freeze({type:"NoParent"});var $e=class{constructor(){this._parent=Ve}_getParentKeyOrThrow(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":throw new Error("Parent key is missing");case"Orphaned":return this.parent.oldKey;default:return v(this.parent,"Unknown state")}}get _parentPos(){switch(this.parent.type){case"HasParent":return this.parent.pos;case"NoParent":throw new Error("Parent key is missing");case"Orphaned":return this.parent.oldPos;default:return v(this.parent,"Unknown state")}}get _pool(){return this.__pool}get roomId(){return this.__pool?this.__pool.roomId:null}get _id(){return this.__id}get parent(){return this._parent}get _parentKey(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":return null;case"Orphaned":return this.parent.oldKey;default:return v(this.parent,"Unknown state")}}_apply(e,t){return 5===e.type&&"HasParent"===this.parent.type?this.parent.node._detachChild(this):{modified:!1}}_setParentLink(e,t){switch(this.parent.type){case"HasParent":if(this.parent.node!==e)throw new Error("Cannot set parent: node already has a parent");return void(this._parent=We(e,t));case"Orphaned":case"NoParent":return void(this._parent=We(e,t));default:return v(this.parent,"Unknown state")}}_attach(e,t){if(this.__id||this.__pool)throw new Error("Cannot attach node: already attached");t.addNode(e,this),this.__id=e,this.__pool=t}_detach(){switch(this.__pool&&this.__id&&this.__pool.deleteNode(this.__id),this.parent.type){case"HasParent":this._parent=function(e,t=Ue(e)){return Object.freeze({type:"Orphaned",oldKey:e,oldPos:t})}(this.parent.key,this.parent.pos);break;case"NoParent":this._parent=Ve;break;case"Orphaned":break;default:v(this.parent,"Unknown state")}this.__pool=void 0}invalidate(){void 0===this._cachedImmutable&&void 0===this._cachedTreeNode||(this._cachedImmutable=void 0,this._cachedTreeNode=void 0,"HasParent"===this.parent.type&&this.parent.node.invalidate())}toTreeNode(e){return void 0!==this._cachedTreeNode&&this._cachedTreeNodeKey===e||(this._cachedTreeNodeKey=e,this._cachedTreeNode=this._toTreeNode(e)),this._cachedTreeNode}toImmutable(){return void 0===this._cachedImmutable&&(this._cachedImmutable=this._toImmutable()),this._cachedImmutable}};function Ke(e){return 0===e.type&&!function(e){return void 0!==e.parentId&&void 0!==e.parentKey}(e)}var qe=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce(((e,t)=>e+((t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t<63?"_":"-")),""),Ge=class e extends $e{constructor(e){super(),this._data=e}get data(){return this._data}static _deserialize([t,n],r,o){const a=new e(n.data);return a._attach(t,o),a}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize register if parentId or parentKey is undefined");return[{type:8,opId:n?.generateOpId(),id:this._id,parentId:e,parentKey:t,data:this.data}]}_serialize(){if("HasParent"!==this.parent.type)throw new Error("Cannot serialize LiveRegister if parent is missing");return{type:3,parentId:g(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key,data:this.data}}_attachChild(e){throw new Error("Method not implemented.")}_detachChild(e){throw new Error("Method not implemented.")}_apply(e,t){return super._apply(e,t)}_toTreeNode(e){return{type:"Json",id:this._id??qe(),key:e,payload:this._data}}_toImmutable(){return this._data}clone(){return N(this.data)}};function Ze(e,t){const n=e._parentPos,r=t._parentPos;return n===r?0:n<r?-1:1}var Xe=class e extends $e{constructor(e){let t;super(),this._items=[],this._implicitlyDeletedItems=new WeakSet,this._unacknowledgedSets=new Map;for(const n of e){const e=Le(t),r=mt(n);r._setParentLink(this,e),this._items.push(r),t=e}}static _deserialize([t],n,r){const o=new e([]);o._attach(t,r);const a=n.get(t);if(void 0===a)return o;for(const[e,t]of a){const a=ct([e,t],n,r);a._setParentLink(o,t.parentKey),o._insertAndSort(a)}return o}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize item is not attached");const r=[],o={id:this._id,opId:n?.generateOpId(),type:2,parentId:e,parentKey:t};r.push(o);for(const e of this._items){const t=e._getParentKeyOrThrow(),o=rt(e._toOps(this._id,t,n),void 0),a=o[0].opId;void 0!==a&&this._unacknowledgedSets.set(t,a),r.push(...o)}return r}_insertAndSort(e){this._items.push(e),this._sortItems()}_sortItems(){this._items.sort(Ze),this.invalidate()}_indexOfPosition(e){return this._items.findIndex((t=>t._getParentKeyOrThrow()===e))}_attach(e,t){super._attach(e,t);for(const e of this._items)e._attach(t.generateId(),t)}_detach(){super._detach();for(const e of this._items)e._detach()}_applySetRemote(e){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const{id:t,parentKey:n}=e,r=it(e);r._attach(t,this._pool),r._setParentLink(this,n);const o=e.deletedId,a=this._indexOfPosition(n);if(-1!==a){const t=this._items[a];if(t._id===o)return t._detach(),this._items[a]=r,{modified:Je(this,[Qe(a,r)]),reverse:[]};{this._implicitlyDeletedItems.add(t),this._items[a]=r;const n=[Qe(a,r)],o=this._detachItemAssociatedToSetOperation(e.deletedId);return o&&n.push(o),{modified:Je(this,n),reverse:[]}}}{const t=[],o=this._detachItemAssociatedToSetOperation(e.deletedId);return o&&t.push(o),this._insertAndSort(r),t.push(tt(this._indexOfPosition(n),r)),{reverse:[],modified:Je(this,t)}}}_applySetAck(e){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const t=[],n=this._detachItemAssociatedToSetOperation(e.deletedId);n&&t.push(n);const r=this._unacknowledgedSets.get(e.parentKey);if(void 0!==r){if(r!==e.opId)return 0===t.length?{modified:!1}:{modified:Je(this,t),reverse:[]};this._unacknowledgedSets.delete(e.parentKey)}const o=this._indexOfPosition(e.parentKey),a=this._items.find((t=>t._id===e.id));if(void 0!==a){if(a._parentKey===e.parentKey)return{modified:t.length>0&&Je(this,t),reverse:[]};if(-1!==o){this._implicitlyDeletedItems.add(this._items[o]);const[e]=this._items.splice(o,1);t.push(et(o,e))}const n=this._items.indexOf(a);a._setParentLink(this,e.parentKey),this._sortItems();const r=this._items.indexOf(a);return r!==n&&t.push(nt(n,r,a)),{modified:t.length>0&&Je(this,t),reverse:[]}}{const n=this._pool.getNode(e.id);if(n&&this._implicitlyDeletedItems.has(n)){n._setParentLink(this,e.parentKey),this._implicitlyDeletedItems.delete(n),this._insertAndSort(n);const r=this._items.indexOf(n);return{modified:Je(this,[-1===o?tt(r,n):Qe(r,n),...t]),reverse:[]}}{-1!==o&&this._items.splice(o,1);const{newItem:n,newIndex:r}=this._createAttachItemAndSort(e,e.parentKey);return{modified:Je(this,[-1===o?tt(r,n):Qe(r,n),...t]),reverse:[]}}}}_detachItemAssociatedToSetOperation(e){if(void 0===e||void 0===this._pool)return null;const t=this._pool.getNode(e);if(void 0===t)return null;const n=this._detachChild(t);return!1===n.modified?null:n.modified.updates[0]}_applyRemoteInsert(e){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const t=Ue(e.parentKey),n=this._indexOfPosition(t);-1!==n&&this._shiftItemPosition(n,t);const{newItem:r,newIndex:o}=this._createAttachItemAndSort(e,t);return{modified:Je(this,[tt(o,r)]),reverse:[]}}_applyInsertAck(e){const t=this._items.find((t=>t._id===e.id)),n=Ue(e.parentKey),r=this._indexOfPosition(n);if(t){if(t._parentKey===n)return{modified:!1};{const e=this._items.indexOf(t);-1!==r&&this._shiftItemPosition(r,n),t._setParentLink(this,n),this._sortItems();const o=this._indexOfPosition(n);return o===e?{modified:!1}:{modified:Je(this,[nt(e,o,t)]),reverse:[]}}}{const t=g(this._pool).getNode(e.id);if(t&&this._implicitlyDeletedItems.has(t)){t._setParentLink(this,n),this._implicitlyDeletedItems.delete(t),this._insertAndSort(t);return{modified:Je(this,[tt(this._indexOfPosition(n),t)]),reverse:[]}}{-1!==r&&this._shiftItemPosition(r,n);const{newItem:t,newIndex:o}=this._createAttachItemAndSort(e,n);return{modified:Je(this,[tt(o,t)]),reverse:[]}}}}_applyInsertUndoRedo(e){const{id:t,parentKey:n}=e,r=it(e);if(void 0!==this._pool?.getNode(t))return{modified:!1};r._attach(t,g(this._pool)),r._setParentLink(this,n);const o=this._indexOfPosition(n);let a=n;if(-1!==o){const e=this._items[o]?._parentPos,t=this._items[o+1]?._parentPos;a=Le(e,t),r._setParentLink(this,a)}this._insertAndSort(r);return{modified:Je(this,[tt(this._indexOfPosition(a),r)]),reverse:[{type:5,id:t}]}}_applySetUndoRedo(e){const{id:t,parentKey:n}=e,r=it(e);if(void 0!==this._pool?.getNode(t))return{modified:!1};this._unacknowledgedSets.set(n,g(e.opId));const o=this._indexOfPosition(n);r._attach(t,g(this._pool)),r._setParentLink(this,n);const a=n;if(-1!==o){const t=this._items[o];t._detach(),this._items[o]=r;const a=rt(t._toOps(g(this._id),n,this._pool),e.id),i=[Qe(o,r)],s=this._detachItemAssociatedToSetOperation(e.deletedId);return s&&i.push(s),{modified:Je(this,i),reverse:a}}this._insertAndSort(r),this._detachItemAssociatedToSetOperation(e.deletedId);return{reverse:[{type:5,id:t}],modified:Je(this,[tt(this._indexOfPosition(a),r)])}}_attachChild(e,t){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");let n;return n="set"===e.intent?1===t?this._applySetRemote(e):2===t?this._applySetAck(e):this._applySetUndoRedo(e):1===t?this._applyRemoteInsert(e):2===t?this._applyInsertAck(e):this._applyInsertUndoRedo(e),!1!==n.modified&&this.invalidate(),n}_detachChild(e){if(e){const t=g(e._parentKey),n=e._toOps(g(this._id),t,this._pool),r=this._items.indexOf(e);if(-1===r)return{modified:!1};const[o]=this._items.splice(r,1);return this.invalidate(),e._detach(),{modified:Je(this,[et(r,o)]),reverse:n}}return{modified:!1}}_applySetChildKeyRemote(e,t){if(this._implicitlyDeletedItems.has(t)){this._implicitlyDeletedItems.delete(t),t._setParentLink(this,e),this._insertAndSort(t);return{modified:Je(this,[tt(this._items.indexOf(t),t)]),reverse:[]}}if(e===t._parentKey)return{modified:!1};const n=this._indexOfPosition(e);if(-1===n){const n=this._items.indexOf(t);t._setParentLink(this,e),this._sortItems();const r=this._items.indexOf(t);return r===n?{modified:!1}:{modified:Je(this,[nt(n,r,t)]),reverse:[]}}{this._items[n]._setParentLink(this,Le(e,this._items[n+1]?._parentPos));const r=this._items.indexOf(t);t._setParentLink(this,e),this._sortItems();const o=this._items.indexOf(t);return o===r?{modified:!1}:{modified:Je(this,[nt(r,o,t)]),reverse:[]}}}_applySetChildKeyAck(e,t){const n=g(t._parentKey);if(this._implicitlyDeletedItems.has(t)){const n=this._indexOfPosition(e);return this._implicitlyDeletedItems.delete(t),-1!==n&&this._items[n]._setParentLink(this,Le(e,this._items[n+1]?._parentPos)),t._setParentLink(this,e),this._insertAndSort(t),{modified:!1}}{if(e===n)return{modified:!1};const r=this._items.indexOf(t),o=this._indexOfPosition(e);-1!==o&&this._items[o]._setParentLink(this,Le(e,this._items[o+1]?._parentPos)),t._setParentLink(this,e),this._sortItems();const a=this._items.indexOf(t);return r===a?{modified:!1}:{modified:Je(this,[nt(r,a,t)]),reverse:[]}}}_applySetChildKeyUndoRedo(e,t){const n=g(t._parentKey),r=this._items.indexOf(t),o=this._indexOfPosition(e);-1!==o&&this._items[o]._setParentLink(this,Le(e,this._items[o+1]?._parentPos)),t._setParentLink(this,e),this._sortItems();const a=this._items.indexOf(t);return r===a?{modified:!1}:{modified:Je(this,[nt(r,a,t)]),reverse:[{type:1,id:g(t._id),parentKey:n}]}}_setChildKey(e,t,n){return 1===n?this._applySetChildKeyRemote(e,t):2===n?this._applySetChildKeyAck(e,t):this._applySetChildKeyUndoRedo(e,t)}_apply(e,t){return super._apply(e,t)}_serialize(){if("HasParent"!==this.parent.type)throw new Error("Cannot serialize LiveList if parent is missing");return{type:1,parentId:g(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get length(){return this._items.length}push(e){return this._pool?.assertStorageIsWritable(),this.insert(e,this.length)}insert(e,t){if(this._pool?.assertStorageIsWritable(),t<0||t>this._items.length)throw new Error(`Cannot insert list item at index "${t}". index should be between 0 and ${this._items.length}`);const n=Le(this._items[t-1]?this._items[t-1]._parentPos:void 0,this._items[t]?this._items[t]._parentPos:void 0),r=mt(e);if(r._setParentLink(this,n),this._insertAndSort(r),this._pool&&this._id){const e=this._pool.generateId();r._attach(e,this._pool),this._pool.dispatch(r._toOps(this._id,n,this._pool),[{type:5,id:e}],new Map([[this._id,Je(this,[tt(t,r)])]]))}}move(e,t){if(this._pool?.assertStorageIsWritable(),t<0)throw new Error("targetIndex cannot be less than 0");if(t>=this._items.length)throw new Error("targetIndex cannot be greater or equal than the list length");if(e<0)throw new Error("index cannot be less than 0");if(e>=this._items.length)throw new Error("index cannot be greater or equal than the list length");let n=null,r=null;e<t?(r=t===this._items.length-1?void 0:this._items[t+1]._parentPos,n=this._items[t]._parentPos):(r=this._items[t]._parentPos,n=0===t?void 0:this._items[t-1]._parentPos);const o=Le(n,r),a=this._items[e],i=a._getParentKeyOrThrow();if(a._setParentLink(this,o),this._sortItems(),this._pool&&this._id){const n=new Map([[this._id,Je(this,[nt(e,t,a)])]]);this._pool.dispatch([{type:1,id:g(a._id),opId:this._pool.generateOpId(),parentKey:o}],[{type:1,id:g(a._id),parentKey:i}],n)}}delete(e){if(this._pool?.assertStorageIsWritable(),e<0||e>=this._items.length)throw new Error(`Cannot delete list item at index "${e}". index should be between 0 and ${this._items.length-1}`);const t=this._items[e];t._detach();const[n]=this._items.splice(e,1);if(this.invalidate(),this._pool){const r=t._id;if(r){const o=new Map;o.set(g(this._id),Je(this,[et(e,n)])),this._pool.dispatch([{id:r,opId:this._pool.generateOpId(),type:5}],t._toOps(g(this._id),t._getParentKeyOrThrow()),o)}}}clear(){if(this._pool?.assertStorageIsWritable(),this._pool){const e=[],t=[],n=[];for(const r of this._items){r._detach();const o=r._id;o&&(e.push({type:5,id:o,opId:this._pool.generateOpId()}),t.push(...r._toOps(g(this._id),r._getParentKeyOrThrow())),n.push(et(0,r)))}this._items=[],this.invalidate();const r=new Map;r.set(g(this._id),Je(this,n)),this._pool.dispatch(e,t,r)}else{for(const e of this._items)e._detach();this._items=[],this.invalidate()}}set(e,t){if(this._pool?.assertStorageIsWritable(),e<0||e>=this._items.length)throw new Error(`Cannot set list item at index "${e}". index should be between 0 and ${this._items.length-1}`);const n=this._items[e],r=n._getParentKeyOrThrow(),o=n._id;n._detach();const a=mt(t);if(a._setParentLink(this,r),this._items[e]=a,this.invalidate(),this._pool&&this._id){const t=this._pool.generateId();a._attach(t,this._pool);const i=new Map;i.set(this._id,Je(this,[Qe(e,a)]));const s=rt(a._toOps(this._id,r,this._pool),o);this._unacknowledgedSets.set(r,g(s[0].opId));const u=rt(n._toOps(this._id,r,void 0),t);this._pool.dispatch(s,u,i)}}toArray(){return this._items.map((e=>pt(e)))}every(e){return this.toArray().every(e)}filter(e){return this.toArray().filter(e)}find(e){return this.toArray().find(e)}findIndex(e){return this.toArray().findIndex(e)}forEach(e){return this.toArray().forEach(e)}get(e){if(!(e<0||e>=this._items.length))return pt(this._items[e])}indexOf(e,t){return this.toArray().indexOf(e,t)}lastIndexOf(e,t){return this.toArray().lastIndexOf(e,t)}map(e){return this._items.map(((t,n)=>e(pt(t),n)))}some(e){return this.toArray().some(e)}[Symbol.iterator](){return new Ye(this._items)}_createAttachItemAndSort(e,t){const n=it(e);n._attach(e.id,g(this._pool)),n._setParentLink(this,t),this._insertAndSort(n);return{newItem:n,newIndex:this._indexOfPosition(t)}}_shiftItemPosition(e,t){const n=Le(t,this._items.length>e+1?this._items[e+1]?._parentPos:void 0);this._items[e]._setParentLink(this,n)}_toTreeNode(e){return{type:"LiveList",id:this._id??qe(),key:e,payload:this._items.map(((e,t)=>e.toTreeNode(t.toString())))}}toImmutable(){return super.toImmutable()}_toImmutable(){const e=this._items.map((e=>e.toImmutable()));return e}clone(){return new e(this._items.map((e=>e.clone())))}},Ye=class{constructor(e){this._innerIterator=e[Symbol.iterator]()}[Symbol.iterator](){return this}next(){const e=this._innerIterator.next();if(e.done)return{done:!0,value:void 0};return{value:pt(e.value)}}};function Je(e,t){return{node:e,type:"LiveList",updates:t}}function Qe(e,t){return{index:e,type:"set",item:t instanceof Ge?t.data:t}}function et(e,t){return{type:"delete",index:e,deletedItem:t instanceof Ge?t.data:t}}function tt(e,t){return{index:e,type:"insert",item:t instanceof Ge?t.data:t}}function nt(e,t,n){return{type:"move",index:t,item:n instanceof Ge?n.data:n,previousIndex:e}}function rt(e,t){return e.map(((e,n)=>{if(0===n){return{...e,intent:"set",deletedId:t}}return e}))}var ot=class e extends $e{constructor(e){if(super(),this.unacknowledgedSet=new Map,e){const t=[];for(const[n,r]of e){const e=mt(r);e._setParentLink(this,n),t.push([n,e])}this._map=new Map(t)}else this._map=new Map}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize item is not attached");const r=[],o={id:this._id,opId:n?.generateOpId(),type:7,parentId:e,parentKey:t};r.push(o);for(const[e,t]of this._map)r.push(...t._toOps(this._id,e,n));return r}static _deserialize([t,n],r,o){const a=new e;a._attach(t,o);const i=r.get(t);if(void 0===i)return a;for(const[e,t]of i){const n=ct([e,t],r,o);n._setParentLink(a,t.parentKey),a._map.set(t.parentKey,n),a.invalidate()}return a}_attach(e,t){super._attach(e,t);for(const[e,n]of this._map)ft(n)&&n._attach(t.generateId(),t)}_attachChild(e,t){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const{id:n,parentKey:r,opId:o}=e,a=r,i=it(e);if(void 0!==this._pool.getNode(n))return{modified:!1};if(2===t){const e=this.unacknowledgedSet.get(a);if(e===o)return this.unacknowledgedSet.delete(a),{modified:!1};if(void 0!==e)return{modified:!1}}else 1===t&&this.unacknowledgedSet.delete(a);const s=this._map.get(a);let u;if(s){const e=g(this._id);u=s._toOps(e,a),s._detach()}else u=[{type:5,id:n}];return i._setParentLink(this,a),i._attach(n,this._pool),this._map.set(a,i),this.invalidate(),{modified:{node:this,type:"LiveMap",updates:{[a]:{type:"update"}}},reverse:u}}_detach(){super._detach();for(const e of this._map.values())e._detach()}_detachChild(e){const t=g(this._id),n=g(e._parentKey),r=e._toOps(t,n,this._pool);for(const[t,n]of this._map)n===e&&(this._map.delete(t),this.invalidate());e._detach();return{modified:{node:this,type:"LiveMap",updates:{[n]:{type:"delete"}}},reverse:r}}_serialize(){if("HasParent"!==this.parent.type)throw new Error("Cannot serialize LiveMap if parent is missing");return{type:2,parentId:g(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get(e){const t=this._map.get(e);if(void 0!==t)return pt(t)}set(e,t){this._pool?.assertStorageIsWritable();const n=this._map.get(e);n&&n._detach();const r=mt(t);if(r._setParentLink(this,e),this._map.set(e,r),this.invalidate(),this._pool&&this._id){const t=this._pool.generateId();r._attach(t,this._pool);const o=new Map;o.set(this._id,{node:this,type:"LiveMap",updates:{[e]:{type:"update"}}});const a=r._toOps(this._id,e,this._pool);this.unacknowledgedSet.set(e,g(a[0].opId)),this._pool.dispatch(r._toOps(this._id,e,this._pool),n?n._toOps(this._id,e):[{type:5,id:t}],o)}}get size(){return this._map.size}has(e){return this._map.has(e)}delete(e){this._pool?.assertStorageIsWritable();const t=this._map.get(e);if(void 0===t)return!1;if(t._detach(),this._map.delete(e),this.invalidate(),this._pool&&t._id){const n=g(this._id),r=new Map;r.set(n,{node:this,type:"LiveMap",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:5,id:t._id,opId:this._pool.generateOpId()}],t._toOps(n,e),r)}return!0}entries(){const e=this._map.entries();return{[Symbol.iterator](){return this},next(){const t=e.next();if(t.done)return{done:!0,value:void 0};return{value:[t.value[0],pt(t.value[1])]}}}}[Symbol.iterator](){return this.entries()}keys(){return this._map.keys()}values(){const e=this._map.values();return{[Symbol.iterator](){return this},next(){const t=e.next();if(t.done)return{done:!0,value:void 0};return{value:pt(t.value)}}}}forEach(e){for(const t of this)e(t[1],t[0],this)}_toTreeNode(e){return{type:"LiveMap",id:this._id??qe(),key:e,payload:Array.from(this._map.entries()).map((([e,t])=>t.toTreeNode(e)))}}toImmutable(){return super.toImmutable()}_toImmutable(){const e=new Map;for(const[t,n]of this._map)e.set(t,n.toImmutable());return e}clone(){return new e(Array.from(this._map).map((([e,t])=>[e,t.clone()])))}},at=class e extends $e{static _buildRootAndParentToChildren(e){const t=new Map;let n=null;for(const[r,o]of e)if(Ke(o))n=[r,o];else{const e=[r,o],n=t.get(o.parentId);void 0!==n?n.push(e):t.set(o.parentId,[e])}if(null===n)throw new Error("Root can't be null");return[n,t]}static _fromItems(t,n){const[r,o]=e._buildRootAndParentToChildren(t);return e._deserialize(r,o,n)}constructor(e={}){super(),this._propToLastUpdate=new Map;const t=M(e);for(const e of Object.keys(t)){const n=t[e];ft(n)&&n._setParentLink(this,e)}this._map=new Map(Object.entries(t))}_toOps(e,t,n){if(void 0===this._id)throw new Error("Cannot serialize item is not attached");const r=n?.generateOpId(),o=[],a={type:4,id:this._id,opId:r,parentId:e,parentKey:t,data:{}};o.push(a);for(const[e,t]of this._map)ft(t)?o.push(...t._toOps(this._id,e,n)):a.data[e]=t;return o}static _deserialize([t,n],r,o){const a=new e(n.data);return a._attach(t,o),this._deserializeChildren(a,r,o)}static _deserializeChildren(e,t,n){const r=t.get(g(e._id));if(void 0===r)return e;for(const[o,a]of r){const r=lt([o,a],t,n);dt(r)&&r._setParentLink(e,a.parentKey),e._map.set(a.parentKey,r),e.invalidate()}return e}_attach(e,t){super._attach(e,t);for(const[e,n]of this._map)ft(n)&&n._attach(t.generateId(),t)}_attachChild(e,t){if(void 0===this._pool)throw new Error("Can't attach child if managed pool is not present");const{id:n,opId:r,parentKey:o}=e,a=st(e);if(void 0!==this._pool.getNode(n))return this._propToLastUpdate.get(o)===r&&this._propToLastUpdate.delete(o),{modified:!1};if(0===t)this._propToLastUpdate.set(o,g(r));else if(void 0!==this._propToLastUpdate.get(o))return this._propToLastUpdate.get(o)===r?(this._propToLastUpdate.delete(o),{modified:!1}):{modified:!1};const i=g(this._id),s=this._map.get(o);let u;return ft(s)?(u=s._toOps(i,o),s._detach()):u=void 0===s?[{type:6,id:i,key:o}]:[{type:3,id:i,data:{[o]:s}}],this._map.set(o,a),this.invalidate(),dt(a)&&(a._setParentLink(this,o),a._attach(n,this._pool)),{reverse:u,modified:{node:this,type:"LiveObject",updates:{[o]:{type:"update"}}}}}_detachChild(e){if(e){const t=g(this._id),n=g(e._parentKey),r=e._toOps(t,n,this._pool);for(const[t,n]of this._map)n===e&&(this._map.delete(t),this.invalidate());e._detach();return{modified:{node:this,type:"LiveObject",updates:{[n]:{type:"delete"}}},reverse:r}}return{modified:!1}}_detach(){super._detach();for(const e of this._map.values())ft(e)&&e._detach()}_apply(e,t){return 3===e.type?this._applyUpdate(e,t):6===e.type?this._applyDeleteObjectKey(e,t):super._apply(e,t)}_serialize(){const e={};for(const[t,n]of this._map)ft(n)||(e[t]=n);return"HasParent"===this.parent.type&&this.parent.node._id?{type:0,parentId:this.parent.node._id,parentKey:this.parent.key,data:e}:{type:0,data:e}}_applyUpdate(e,t){let n=!1;const r=g(this._id),o=[],a={type:3,id:r,data:{}};for(const t in e.data){const e=this._map.get(t);ft(e)?(o.push(...e._toOps(r,t)),e._detach()):void 0!==e?a.data[t]=e:void 0===e&&o.push({type:6,id:r,key:t})}const i={};for(const r in e.data){const o=e.data[r];if(void 0===o)continue;if(t)this._propToLastUpdate.set(r,g(e.opId));else{if(void 0!==this._propToLastUpdate.get(r)){if(this._propToLastUpdate.get(r)===e.opId){this._propToLastUpdate.delete(r);continue}continue}n=!0}const a=this._map.get(r);ft(a)&&a._detach(),n=!0,i[r]={type:"update"},this._map.set(r,o),this.invalidate()}return 0!==Object.keys(a.data).length&&o.unshift(a),n?{modified:{node:this,type:"LiveObject",updates:i},reverse:o}:{modified:!1}}_applyDeleteObjectKey(e,t){const n=e.key;if(!1===this._map.has(n))return{modified:!1};if(!t&&void 0!==this._propToLastUpdate.get(n))return{modified:!1};const r=this._map.get(n),o=g(this._id);let a=[];return ft(r)?(a=r._toOps(o,e.key),r._detach()):void 0!==r&&(a=[{type:3,id:o,data:{[n]:r}}]),this._map.delete(n),this.invalidate(),{modified:{node:this,type:"LiveObject",updates:{[e.key]:{type:"delete"}}},reverse:a}}toObject(){return Object.fromEntries(this._map)}set(e,t){this._pool?.assertStorageIsWritable(),this.update({[e]:t})}get(e){return this._map.get(e)}delete(e){this._pool?.assertStorageIsWritable();const t=e,n=this._map.get(t);if(void 0===n)return;if(void 0===this._pool||void 0===this._id)return ft(n)&&n._detach(),this._map.delete(t),void this.invalidate();let r;ft(n)?(n._detach(),r=n._toOps(this._id,t)):r=[{type:3,data:{[t]:n},id:this._id}],this._map.delete(t),this.invalidate();const o=new Map;o.set(this._id,{node:this,type:"LiveObject",updates:{[e]:{type:"delete"}}}),this._pool.dispatch([{type:6,key:t,id:this._id,opId:this._pool.generateOpId()}],r,o)}update(e){if(this._pool?.assertStorageIsWritable(),void 0===this._pool||void 0===this._id){for(const t in e){const n=e[t];if(void 0===n)continue;const r=this._map.get(t);ft(r)&&r._detach(),ft(n)&&n._setParentLink(this,t),this._map.set(t,n),this.invalidate()}return}const t=[],n=[],r=this._pool.generateOpId(),o={},a={id:this._id,type:3,data:{}},i={};for(const s in e){const u=e[s];if(void 0===u)continue;const c=this._map.get(s);if(ft(c)?(n.push(...c._toOps(this._id,s)),c._detach()):void 0===c?n.push({type:6,id:this._id,key:s}):a.data[s]=c,ft(u)){u._setParentLink(this,s),u._attach(this._pool.generateId(),this._pool);const e=u._toOps(this._id,s,this._pool),n=e.find((e=>e.parentId===this._id));n&&this._propToLastUpdate.set(s,g(n.opId)),t.push(...e)}else o[s]=u,this._propToLastUpdate.set(s,r);this._map.set(s,u),this.invalidate(),i[s]={type:"update"}}0!==Object.keys(a.data).length&&n.unshift(a),0!==Object.keys(o).length&&t.unshift({opId:r,id:this._id,type:3,data:o});const s=new Map;s.set(this._id,{node:this,type:"LiveObject",updates:i}),this._pool.dispatch(t,n,s)}toImmutable(){return super.toImmutable()}toTreeNode(e){return super.toTreeNode(e)}_toTreeNode(e){const t=this._id??qe();return{type:"LiveObject",id:t,key:e,payload:Array.from(this._map.entries()).map((([e,n])=>ft(n)?n.toTreeNode(e):{type:"Json",id:`${t}:${e}`,key:e,payload:n}))}}_toImmutable(){const e={};for(const[t,n]of this._map)e[t]=dt(n)?n.toImmutable():n;return e}clone(){return new e(Object.fromEntries(Array.from(this._map).map((([e,t])=>[e,dt(t)?t.clone():N(t)]))))}};function it(e){return mt(st(e))}function st(e){switch(e.type){case 8:return e.data;case 4:return new at(e.data);case 7:return new ot;case 2:return new Xe([]);default:return v(0,"Unknown creation Op")}}function ut(e,t){return e===t||"HasParent"===e.parent.type&&ut(e.parent.node,t)}function ct([e,t],n,r){switch(t.type){case 0:return at._deserialize([e,t],n,r);case 1:return Xe._deserialize([e,t],n,r);case 2:return ot._deserialize([e,t],n,r);case 3:return Ge._deserialize([e,t],n,r);default:throw new Error("Unexpected CRDT type")}}function lt([e,t],n,r){switch(t.type){case 0:return at._deserialize([e,t],n,r);case 1:return Xe._deserialize([e,t],n,r);case 2:return ot._deserialize([e,t],n,r);case 3:return t.data;default:throw new Error("Unexpected CRDT type")}}function dt(e){return ht(e)||function(e){return e instanceof ot}(e)||function(e){return e instanceof at}(e)}function ft(e){return dt(e)||function(e){return e instanceof Ge}(e)}function ht(e){return e instanceof Xe}function pt(e){return e instanceof Ge?e.data:e instanceof Xe||e instanceof ot||e instanceof at?e:v(0,"Unknown AbstractCrdt")}function mt(e){return e instanceof at||e instanceof ot||e instanceof Xe?e:new Ge(e)}function vt(e,t){return void 0===e?t:"LiveObject"===e.type&&"LiveObject"===t.type?function(e,t){const n=e.updates;for(const[e,r]of F(t.updates))n[e]=r;return{...t,updates:n}}(e,t):"LiveMap"===e.type&&"LiveMap"===t.type?function(e,t){const n=e.updates;for(const[e,r]of F(t.updates))n[e]=r;return{...t,updates:n}}(e,t):"LiveList"===e.type&&"LiveList"===t.type?function(e,t){const n=e.updates;return{...t,updates:n.concat(t.updates)}}(e,t):t}function gt(e,t){const n=[];for(let r=0,o=e.length;r<o;r+=t)n.push(e.slice(r,r+t));return n}function yt(e){return`${e}_${qe()}`}function bt(){return yt("th")}function Et(){return yt("cm")}function wt(e){return Array.isArray(e)}var Ct=/^[a-zA-Z_][a-zA-Z0-9_]*$/;function Dt(e){let t=[];const n=Object.entries(e),r=[],o=[],a=[];return n.forEach((([e,t])=>{if(!Ct.test(e))throw new Error("Key must only contain letters, numbers, _");_t(t)?r.push([e,t]):Bt(t)?o.push([e,t]):"object"!=typeof t||"startsWith"in t||a.push([e,t])})),t=[...xt(r),...At(o)],a.forEach((([e,n])=>{const r=Object.entries(n),o=[],a=[];r.forEach((([t,n])=>{if(kt(t))throw new Error("Key cannot be empty");_t(n)?o.push([St(e,t),n]):Bt(n)&&a.push([St(e,t),n])})),t=[...t,...xt(o),...At(a)]})),t.map((({key:e,operator:t,value:n})=>Ot(e,t,Tt(n)))).join(" AND ")}var xt=e=>{const t=[];return e.forEach((([e,n])=>{t.push({key:e,operator:":",value:n})})),t},At=e=>{const t=[];return e.forEach((([e,n])=>{"startsWith"in n&&"string"==typeof n.startsWith&&t.push({key:e,operator:"^",value:n.startsWith})})),t},_t=e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e,Bt=e=>"object"==typeof e&&null!==e&&"startsWith"in e,Ot=(e,t,n)=>`${e}${t}${n}`,St=(e,t)=>t?`${e}[${JSON.stringify(t)}]`:e,Tt=e=>{if("string"==typeof e){if(kt(e))throw new Error("Value cannot be empty");return JSON.stringify(e)}return e.toString()},kt=e=>!e||""===e.toString().trim();var It=class extends Te{constructor(){super(),this._connections=new Map,this._presences=new Map,this._users=new Map}connectionIds(){return this._connections.keys()}_toImmutable(){return P(Array.from(this._presences.keys()).map((e=>this.getUser(Number(e)))))}clearOthers(){this._connections=new Map,this._presences=new Map,this._users=new Map,this.invalidate()}_getUser(e){const t=this._connections.get(e),n=this._presences.get(e);if(void 0!==t&&void 0!==n)return function(e,t){const{connectionId:n,id:r,info:o}=e,a=se(e.scopes);return M({connectionId:n,id:r,info:o,canWrite:a,canComment:ue(e.scopes),isReadOnly:!a,presence:t})}(t,n)}getUser(e){const t=this._users.get(e);if(t)return t;const n=this._getUser(e);return n?(this._users.set(e,n),n):void 0}_invalidateUser(e){this._users.has(e)&&this._users.delete(e),this.invalidate()}setConnection(e,t,n,r){this._connections.set(e,{connectionId:e,id:t,info:n,scopes:r}),this._presences.has(e)&&this._invalidateUser(e)}removeConnection(e){this._connections.delete(e),this._presences.delete(e),this._invalidateUser(e)}setOther(e,t){this._presences.set(e,M(t)),this._connections.has(e)&&this._invalidateUser(e)}patchOther(e,t){const n=this._presences.get(e);if(void 0===n)return;const r=Se(n,t);n!==r&&(this._presences.set(e,r),this._invalidateUser(e))}},Ft=class extends Te{constructor(e){super(),this._data=M(e)}_toImmutable(){return this._data}patch(e){const t=this._data,n=Se(t,e);t!==n&&(this._data=n,this.invalidate())}};function Rt(e,t){return{type:"User",id:`${t.connectionId}`,key:e,payload:{connectionId:t.connectionId,id:t.id,info:t.info,presence:t.presence,isReadOnly:!t.canWrite}}}var Nt=524288e3,Pt=[2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3];function Mt(e,t){const n=e.initialPresence,r=e.initialStorage,[o,a]=function(){const e="undefined"!=typeof document?document:void 0,t={current:null};function n(){t.current="hidden"===e?.visibilityState?t.current??Date.now():null}return e?.addEventListener("visibilitychange",n),[t,()=>{e?.removeEventListener("visibilitychange",n)}]}(),i={...t.delegates,canZombie:()=>void 0!==t.backgroundKeepAliveTimeout&&null!==o.current&&Date.now()>o.current+t.backgroundKeepAliveTimeout&&"synchronizing"!==ce()},s=new class{constructor(e,t=!1,n=!0){const{machine:r,events:o,cleanups:a}=ie(e,{waitForActorId:n,enableDebugLogging:t});this.machine=r,this.events=o,this.cleanups=a}getStatus(){try{return V(this.machine)}catch{return"initial"}}get authValue(){return this.machine.context.authValue}connect(){this.machine.send({type:"CONNECT"})}reconnect(){this.machine.send({type:"RECONNECT"})}disconnect(){this.machine.send({type:"DISCONNECT"})}destroy(){let e;for(this.machine.stop();e=this.cleanups.pop();)e()}send(e){const t=this.machine.context?.socket;null===t?x("Cannot send: not connected yet",e):1!==t.readyState?x("Cannot send: WebSocket no longer open",e):t.send(e)}_privateSendMachineEvent(e){this.machine.send(e)}}(i,t.enableDebugLogging),u={buffer:{flushTimerID:void 0,lastFlushedAt:0,presenceUpdates:{type:"full",data:n},messages:[],storageOperations:[]},staticSessionInfo:new ke(null),dynamicSessionInfo:new ke(null),myPresence:new Ft(n),others:new It,initialStorage:r,idFactory:null,yjsProvider:void 0,yjsProviderDidChange:E(),clock:0,opClock:0,nodes:new Map,root:void 0,undoStack:[],redoStack:[],pausedHistory:null,activeBatch:null,unacknowledgedOps:new Map,opStackTraces:void 0},c=e=>e(),l=t.unstable_batchedUpdates??c;let d,f;let h=!1;s.events.onMessage.subscribe((function(e){if("string"!=typeof e.data)return;const t=function(e){const t=R(e);return void 0===t?null:wt(t)?P(t.map((e=>Z(e)))):P([Z(t)])}(e.data);if(null===t||0===t.length)return;const n={storageUpdates:new Map,others:[]};l((()=>{for(const e of t)switch(e.type){case 101:{const t=G(e);t&&n.others.push(t);break}case 100:{const t=H(e);t&&n.others.push(t);break}case 103:{const t=u.others.current;m.customEvent.notify({connectionId:e.actor,user:e.actor<0?null:t.find((t=>t.connectionId===e.actor))??null,event:e.event});break}case 102:{const t=U(e);t&&n.others.push(t);break}case 300:m.ydoc.notify(e);break;case 104:n.others.push(W(e,c));break;case 200:ee(e);break;case 201:{const t=j(e.ops,!1);for(const[e,r]of t.updates.storageUpdates)n.storageUpdates.set(e,vt(n.storageUpdates.get(e),r));break}case 299:O("Storage mutation rejection error",e.reason);break;case 400:case 407:case 401:case 408:case 405:case 406:case 402:case 403:case 404:m.comments.notify(e)}F(n,c)}))})),s.events.statusDidChange.subscribe((function(e){const t=s.authValue;if(null!==t){const e=_e(t);if(e!==d)if(d=e,"secret"===t.type){const e=t.token.parsed;u.staticSessionInfo.set({userId:"sec-legacy"===e.k?e.id:e.uid,userInfo:"sec-legacy"===e.k?e.info:e.ui})}else u.staticSessionInfo.set({userId:void 0,userInfo:void 0})}l((()=>{m.status.notify(e),_(c)}))})),s.events.statusDidChange.subscribe((function(e){"reconnecting"===e?f=setTimeout((()=>{l((()=>{m.lostConnection.notify("lost"),h=!0,u.others.clearOthers(),F({others:[{type:"reset"}]},c)}))}),t.lostConnectionTimeout):(clearTimeout(f),h&&(l("disconnected"===e?()=>{m.lostConnection.notify("failed")}:()=>{m.lostConnection.notify("restored")}),h=!1))})),s.events.didConnect.subscribe((function(){u.buffer.presenceUpdates={type:"full",data:{...u.myPresence.current}},null!==J&&te({flush:!1}),X()})),s.events.didDisconnect.subscribe((function(){clearTimeout(u.buffer.flushTimerID)})),s.events.onLiveblocksError.subscribe((e=>{l((()=>{m.error.notify(e)}))}));const p={roomId:t.roomId,getNode:e=>u.nodes.get(e),addNode:(e,t)=>{u.nodes.set(e,t)},deleteNode:e=>{u.nodes.delete(e)},generateId:()=>`${M()}:${u.clock++}`,generateOpId:()=>`${M()}:${u.opClock++}`,dispatch(e,t,n){const r=u.activeBatch;if(r){for(const t of e)r.ops.push(t);for(const[e,t]of n)r.updates.storageUpdates.set(e,vt(r.updates.storageUpdates.get(e),t));r.reverseOps.unshift(...t)}else l((()=>{I(t,c),u.redoStack.length=0,Y(e),F({storageUpdates:n},c)}))},assertStorageIsWritable:()=>{const e=u.dynamicSessionInfo.current?.scopes;if(void 0===e)return;if(!se(e))throw new Error("Cannot write to storage with a read only user, please ensure the user has write permissions")}},m={status:E(),lostConnection:E(),customEvent:E(),self:E(),myPresence:E(),others:E(),error:E(),storageBatch:E(),history:E(),storageDidLoad:E(),storageStatus:E(),ydoc:E(),comments:E()},v=t.polyfills?.fetch||globalThis.fetch?.bind(globalThis),y=new Be(t.baseUrl,v,(()=>Promise.resolve(s.authValue??k("Not authorized")))),w=new Be(t.baseUrl,v,(()=>i.authenticate()));function C(e){const n=JSON.stringify(e),r=u.dynamicSessionInfo.current?.nonce;if(t.unstable_fallbackToHTTP&&r){if((new TextEncoder).encode(n).length>1047552)return y.rawPost(Ae`/v2/c/rooms/${t.roomId}/send-message`,{nonce:r,messages:e}).then((e=>{e.ok||403!==e.status||s.reconnect()})),void x("Message was too large for websockets and sent over HTTP instead")}s.send(n)}const D=new Ie(u.staticSessionInfo,u.dynamicSessionInfo,u.myPresence,((e,t,n)=>{if(null===e||null===t)return null;{const r=se(t.scopes);return{connectionId:t.actor,id:e.userId,info:e.userInfo,presence:n,canWrite:r,canComment:ue(t.scopes)}}}));let A;function _(e){const t=D.current;null!==t&&t!==A&&(e((()=>{m.self.notify(t)})),A=t)}const B=new Ie(D,(e=>null!==e?Rt("Me",e):null));function S(e,t){if(0===e.items.length)throw new Error("Internal error: cannot load storage without items");void 0!==u.root?function(e,t){if(void 0===u.root)return;const n=new Map;for(const[e,t]of u.nodes)n.set(e,t._serialize());const r=function(e,t){const n=[];return e.forEach(((e,r)=>{t.get(r)||n.push({type:5,id:r})})),t.forEach(((t,r)=>{const o=e.get(r);if(o)0===t.type&&(0===o.type&&JSON.stringify(t.data)===JSON.stringify(o.data)||n.push({type:3,id:r,data:t.data})),t.parentKey!==o.parentKey&&n.push({type:1,id:r,parentKey:g(t.parentKey,"Parent key must not be missing")});else switch(t.type){case 3:n.push({type:8,id:r,parentId:t.parentId,parentKey:t.parentKey,data:t.data});break;case 1:n.push({type:2,id:r,parentId:t.parentId,parentKey:t.parentKey});break;case 0:if(void 0===t.parentId||void 0===t.parentKey)throw new Error("Internal error. Cannot serialize storage root into an operation");n.push({type:4,id:r,parentId:t.parentId,parentKey:t.parentKey,data:t.data});break;case 2:n.push({type:7,id:r,parentId:t.parentId,parentKey:t.parentKey})}})),n}(n,new Map(e));F(j(r,!1).updates,t)}(e.items,t):u.root=at._fromItems(e.items,p);const n=D.current?.canWrite??!0,r=u.undoStack.length;for(const e in u.initialStorage)void 0===u.root.get(e)&&(n?u.root.set(e,void 0===(o=u.initialStorage[e])?void 0:dt(o)?o.clone():N(o)):x(`Attempted to populate missing storage key '${e}', but current user has no write access`));var o;u.undoStack.length=r}function T(e,t){u.undoStack.length>=50&&u.undoStack.shift(),u.undoStack.push(e),q(t)}function I(e,t){null!==u.pausedHistory?u.pausedHistory.unshift(...e):T(e,t)}function F(e,t){const n=e.storageUpdates,r=e.others;t((()=>{if(void 0!==r&&r.length>0){const e=u.others.current;for(const t of r)m.others.notify({...t,others:e})}if(e.presence&&(_(c),m.myPresence.notify(u.myPresence.current)),void 0!==n&&n.size>0){const e=Array.from(n.values());m.storageBatch.notify(e)}fe()}))}function M(){const e=u.dynamicSessionInfo.current;if(e)return e.actor;throw new Error("Internal. Tried to get connection id but connection was never open")}function j(e,t){const n={reverse:[],storageUpdates:new Map,presence:!1},r=new Set,o=e.map((e=>"presence"===e.type||e.opId?e:{...e,opId:p.generateOpId()}));for(const e of o)if("presence"===e.type){const t={type:"presence",data:{}};for(const n in e.data)t.data[n]=u.myPresence.current[n];if(u.myPresence.patch(e.data),null===u.buffer.presenceUpdates)u.buffer.presenceUpdates={type:"partial",data:e.data};else for(const t in e.data)u.buffer.presenceUpdates.data[t]=e.data[t];n.reverse.unshift(t),n.presence=!0}else{let o;if(t)o=0;else{const t=g(e.opId);o=u.unacknowledgedOps.delete(t)?2:1}const a=L(e,o);if(a.modified){const t=a.modified.node._id;t&&r.has(t)||(n.storageUpdates.set(g(a.modified.node._id),vt(n.storageUpdates.get(g(a.modified.node._id)),a.modified)),n.reverse.unshift(...a.reverse)),2!==e.type&&7!==e.type&&4!==e.type||r.add(g(e.id))}}return{ops:o,reverse:n.reverse,updates:{storageUpdates:n.storageUpdates,presence:n.presence}}}function L(e,t){if(function(e){return 5===e.type&&"ACK"===e.id}(e))return{modified:!1};switch(e.type){case 6:case 3:case 5:{const n=u.nodes.get(e.id);return void 0===n?{modified:!1}:n._apply(e,0===t)}case 1:{const n=u.nodes.get(e.id);return void 0===n?{modified:!1}:"HasParent"===n.parent.type&&ht(n.parent.node)?n.parent.node._setChildKey(Ue(e.parentKey),n,t):{modified:!1}}case 4:case 2:case 7:case 8:{if(void 0===e.parentId)return{modified:!1};const n=u.nodes.get(e.parentId);return void 0===n?{modified:!1}:n._attachChild(e,t)}}}function H(e){if(void 0!==e.targetActor){const t=u.others.getUser(e.actor);u.others.setOther(e.actor,e.data);const n=u.others.getUser(e.actor);if(void 0===t&&void 0!==n)return{type:"enter",user:n}}else u.others.patchOther(e.actor,e.data);const t=u.others.getUser(e.actor);return t?{type:"update",updates:e.data,user:t}:void 0}function U(e){const t=u.others.getUser(e.actor);return t?(u.others.removeConnection(e.actor),{type:"leave",user:t}):null}function W(e,t){u.dynamicSessionInfo.set({actor:e.actor,nonce:e.nonce,scopes:e.scopes}),u.idFactory=function(e){let t=0;return()=>`${e}:${t++}`}(e.actor),_(t);for(const t of u.others.connectionIds()){void 0===e.users[t]&&u.others.removeConnection(t)}for(const t in e.users){const n=e.users[t],r=Number(t);u.others.setConnection(r,n.id,n.info,n.scopes)}return{type:"reset"}}function $(){return u.undoStack.length>0}function K(){return u.redoStack.length>0}function q(e){e((()=>{m.history.notify({canUndo:$(),canRedo:K()})}))}function G(e){u.others.setConnection(e.actor,e.id,e.info,e.scopes),u.buffer.messages.push({type:100,data:u.myPresence.current,targetActor:e.actor}),X();const t=u.others.getUser(e.actor);return t?{type:"enter",user:t}:void 0}function Z(e){return function(e){return!function(e){return null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e}(e)&&!wt(e)}(e)?e:null}function X(){const e=u.buffer.storageOperations;if(e.length>0){for(const t of e)u.unacknowledgedOps.set(g(t.opId),t);fe()}if("connected"!==s.getStatus())return void(u.buffer.storageOperations=[]);const n=Date.now(),r=n-u.buffer.lastFlushedAt;if(r>=t.throttleDelay){const e=function(){const e=[];u.buffer.presenceUpdates&&e.push("full"===u.buffer.presenceUpdates.type?{type:100,targetActor:-1,data:u.buffer.presenceUpdates.data}:{type:100,data:u.buffer.presenceUpdates.data});for(const t of u.buffer.messages)e.push(t);u.buffer.storageOperations.length>0&&e.push({type:201,ops:u.buffer.storageOperations});return e}();if(0===e.length)return;C(e),u.buffer={flushTimerID:void 0,lastFlushedAt:n,messages:[],storageOperations:[],presenceUpdates:null}}else clearTimeout(u.buffer.flushTimerID),u.buffer.flushTimerID=setTimeout(X,t.throttleDelay-r)}function Y(e){const{storageOperations:t}=u.buffer;for(const n of e)t.push(n);X()}let J=null,Q=null;function ee(e){const t=new Map(u.unacknowledgedOps);S(e,c),function(e,t){if(0===e.size)return;const n=[],r=j(Array.from(e.values()),!0);n.push({type:201,ops:r.ops}),F(r.updates,t),C(n)}(t,c),Q?.(),fe(),m.storageDidLoad.notify()}function te(e){const n=u.buffer.messages;t.unstable_streamData?async function(){if(!s.authValue)return;const e=await y.rawGet(Ae`/v2/c/rooms/${t.roomId}/storage`);ee({type:200,items:await e.json()})}():n.some((e=>200===e.type))||n.push({type:200}),e.flush&&X()}function ne(){return null===J&&(te({flush:!0}),J=new Promise((e=>{Q=e})),fe()),J}function re(){const e=u.root;return void 0!==e?e:(ne(),null)}async function oe(){return void 0!==u.root?Promise.resolve({root:u.root}):(await ne(),{root:g(u.root)})}const ae=t.createSyncSource();function ce(){return void 0===u.root?null===J?"not-loaded":"loading":0===u.unacknowledgedOps.size?"synchronized":"synchronizing"}let le=ce();function fe(){const e=ce();le!==e&&(le=e,m.storageStatus.notify(e)),ae.setSyncStatus("synchronizing"===e?"synchronizing":"synchronized")}function me(){return null!==D.current}function Ce(){return null!==re()}const xe=new Ie(u.others,(e=>e.map(((e,t)=>Rt(`Other ${t}`,e))))),Oe={status:m.status.observable,lostConnection:m.lostConnection.observable,customEvent:m.customEvent.observable,others:m.others.observable,self:m.self.observable,myPresence:m.myPresence.observable,error:m.error.observable,storage:m.storageBatch.observable,storageBatch:m.storageBatch.observable,history:m.history.observable,storageDidLoad:m.storageDidLoad.observable,storageStatus:m.storageStatus.observable,ydoc:m.ydoc.observable,comments:m.comments.observable};const Se=new he((async e=>{const n=e.flat(),r=await async function(e){const{urls:n}=await w.post(Ae`/v2/c/rooms/${t.roomId}/attachments/presigned-urls`,{attachmentIds:e});return n}(n);return r.map((e=>e??new Error("There was an error while getting this attachment's URL")))}),{delay:50}),Te=pe(Se);async function Fe(e,t){return await w.get(e,void 0,t)}const Re=new he((async e=>{const n=e.flat();return await async function(e){await Fe(Ae`/v2/c/rooms/${t.roomId}/inbox-notifications/read`,{method:"POST",body:JSON.stringify({inboxNotificationIds:e})})}(n),n}),{delay:50});const Ne=t.createSyncSource();function Pe(e){return Ne.setSyncStatus("synchronizing"===e?"synchronizing":"synchronized")}return Object.defineProperty({[de]:{get presenceBuffer(){return N(u.buffer.presenceUpdates?.data??null)},get undoStack(){return N(u.undoStack)},get nodeCount(){return u.nodes.size},getYjsProvider:()=>u.yjsProvider,setYjsProvider(e){u.yjsProvider?.off("status",Pe),u.yjsProvider=e,e?.on("status",Pe),u.yjsProviderDidChange.notify()},yjsProviderDidChange:u.yjsProviderDidChange.observable,reportTextEditor:async function(e,n){await w.rawPost(Ae`/v2/c/rooms/${t.roomId}/text-metadata`,{type:e,rootKey:n})},createTextMention:async function(e,n){await y.rawPost(Ae`/v2/c/rooms/${t.roomId}/text-mentions`,{userId:e,mentionId:n})},deleteTextMention:async function(e){await y.rawDelete(Ae`/v2/c/rooms/${t.roomId}/text-mentions/${e}`)},listTextVersions:async function(){const e=await w.get(Ae`/v2/c/rooms/${t.roomId}/versions`);return{versions:e.versions.map((({createdAt:e,...t})=>({createdAt:new Date(e),...t}))),requestedAt:new Date(e.meta.requestedAt)}},listTextVersionsSince:async function(e){const n=await w.get(Ae`/v2/c/rooms/${t.roomId}/versions/delta`,{since:e.since.toISOString()},{signal:e.signal});return{versions:n.versions.map((({createdAt:e,...t})=>({createdAt:new Date(e),...t}))),requestedAt:new Date(n.meta.requestedAt)}},getTextVersion:async function(e){return w.rawGet(Ae`/v2/c/rooms/${t.roomId}/y-version/${e}`)},createTextVersion:async function(){await w.rawPost(Ae`/v2/c/rooms/${t.roomId}/version`)},getSelf_forDevTools:()=>B.current,getOthers_forDevTools:()=>xe.current,simulate:{explicitClose:e=>s._privateSendMachineEvent({type:"EXPLICIT_SOCKET_CLOSE",event:e}),rawSend:e=>s.send(e)},attachmentUrlsStore:Te},id:t.roomId,subscribe:jt(Oe),connect:()=>s.connect(),reconnect:()=>s.reconnect(),disconnect:()=>s.disconnect(),destroy:()=>{ae.destroy(),u.yjsProvider?.off("status",Pe),Ne.destroy(),a(),s.destroy()},updatePresence:function(e,t){const n={};null===u.buffer.presenceUpdates&&(u.buffer.presenceUpdates={type:"partial",data:{}});for(const t in e){const r=e[t];void 0!==r&&(u.buffer.presenceUpdates.data[t]=r,n[t]=u.myPresence.current[t])}u.myPresence.patch(e),u.activeBatch?(t?.addToHistory&&u.activeBatch.reverseOps.unshift({type:"presence",data:n}),u.activeBatch.updates.presence=!0):(X(),l((()=>{t?.addToHistory&&I([{type:"presence",data:n}],c),F({presence:!0},c)})))},updateYDoc:function(e,t){const n={type:301,update:e,guid:t};u.buffer.messages.push(n),m.ydoc.notify(n),X()},broadcastEvent:function(e,t={shouldQueueEventIfNotReady:!1}){("connected"===s.getStatus()||t.shouldQueueEventIfNotReady)&&(u.buffer.messages.push({type:103,event:e}),X())},batch:function(e){if(u.activeBatch)return e();let t;return l((()=>{u.activeBatch={ops:[],updates:{storageUpdates:new Map,presence:!1,others:[]},reverseOps:[]};try{t=e()}finally{const e=u.activeBatch;u.activeBatch=null,e.reverseOps.length>0&&I(e.reverseOps,c),e.ops.length>0&&(u.redoStack.length=0),e.ops.length>0&&Y(e.ops),F(e.updates,c),X()}})),t},history:{undo:function(){if(u.activeBatch)throw new Error("undo is not allowed during a batch");const e=u.undoStack.pop();if(void 0===e)return;u.pausedHistory=null;const t=j(e,!0);l((()=>{F(t.updates,c),u.redoStack.push(t.reverse),q(c)}));for(const e of t.ops)"presence"!==e.type&&u.buffer.storageOperations.push(e);X()},redo:function(){if(u.activeBatch)throw new Error("redo is not allowed during a batch");const e=u.redoStack.pop();if(void 0===e)return;u.pausedHistory=null;const t=j(e,!0);l((()=>{F(t.updates,c),u.undoStack.push(t.reverse),q(c)}));for(const e of t.ops)"presence"!==e.type&&u.buffer.storageOperations.push(e);X()},canUndo:$,canRedo:K,clear:function(){u.undoStack.length=0,u.redoStack.length=0},pause:function(){null===u.pausedHistory&&(u.pausedHistory=[])},resume:function(){const e=u.pausedHistory;u.pausedHistory=null,null!==e&&e.length>0&&T(e,l)}},fetchYDoc:function(e,t){u.buffer.messages.find((n=>300===n.type&&n.vector===e&&n.guid===t))||u.buffer.messages.push({type:300,vector:e,guid:t}),X()},getStorage:oe,getStorageSnapshot:re,getStorageStatus:ce,isPresenceReady:me,isStorageReady:Ce,waitUntilPresenceReady:z((async function(){for(;!me();){const{promise:e,resolve:t}=b(),n=Oe.self.subscribeOnce(t),r=Oe.status.subscribeOnce(t);await e,n(),r()}})),waitUntilStorageReady:z((async function(){for(;!Ce();)await oe()})),events:Oe,getStatus:()=>s.getStatus(),getSelf:()=>D.current,getPresence:()=>u.myPresence.current,getOthers:()=>u.others.current,getThreads:async function(e){let n;e?.query&&(n=Dt(e.query));try{const r=await w.get(Ae`/v2/c/rooms/${t.roomId}/threads`,{cursor:e?.cursor,query:n,limit:50});return{threads:r.data.map(ge),inboxNotifications:r.inboxNotifications.map(ye),nextCursor:r.meta.nextCursor,requestedAt:new Date(r.meta.requestedAt)}}catch(e){if(e instanceof we&&404===e.status)return{threads:[],inboxNotifications:[],nextCursor:null,requestedAt:new Date(Date.now()-216e5)};throw e}},getThreadsSince:async function(e){const n=await w.get(Ae`/v2/c/rooms/${t.roomId}/threads/delta`,{since:e?.since?.toISOString()},{signal:e.signal});return{threads:{updated:n.data.map(ge),deleted:n.deletedThreads.map(be)},inboxNotifications:{updated:n.inboxNotifications.map(ye),deleted:n.deletedInboxNotifications.map(Ee)},requestedAt:new Date(n.meta.requestedAt)}},getThread:async function(e){const n=await w.rawGet(Ae`/v2/c/rooms/${t.roomId}/thread-with-notification/${e}`);if(n.ok){const e=await n.json();return{thread:ge(e.thread),inboxNotification:e.inboxNotification?ye(e.inboxNotification):void 0}}if(404===n.status)return{thread:void 0,inboxNotification:void 0};throw new Error(`There was an error while getting thread ${e}.`)},createThread:async function({metadata:e,body:n,commentId:r=Et(),threadId:o=bt(),attachmentIds:a}){return ge(await w.post(Ae`/v2/c/rooms/${t.roomId}/threads`,{id:o,comment:{id:r,body:n,attachmentIds:a},metadata:e}))},deleteThread:async function(e){await w.delete(Ae`/v2/c/rooms/${t.roomId}/threads/${e}`)},editThreadMetadata:async function({metadata:e,threadId:n}){return await w.post(Ae`/v2/c/rooms/${t.roomId}/threads/${n}/metadata`,e)},markThreadAsResolved:async function(e){await w.post(Ae`/v2/c/rooms/${t.roomId}/threads/${e}/mark-as-resolved`)},markThreadAsUnresolved:async function(e){await w.post(Ae`/v2/c/rooms/${t.roomId}/threads/${e}/mark-as-unresolved`)},createComment:async function({threadId:e,commentId:n=Et(),body:r,attachmentIds:o}){return ve(await w.post(Ae`/v2/c/rooms/${t.roomId}/threads/${e}/comments`,{id:n,body:r,attachmentIds:o}))},editComment:async function({threadId:e,commentId:n,body:r,attachmentIds:o}){return ve(await w.post(Ae`/v2/c/rooms/${t.roomId}/threads/${e}/comments/${n}`,{body:r,attachmentIds:o}))},deleteComment:async function({threadId:e,commentId:n}){await w.delete(Ae`/v2/c/rooms/${t.roomId}/threads/${e}/comments/${n}`)},addReaction:async function({threadId:e,commentId:n,emoji:r}){const o=await w.post(Ae`/v2/c/rooms/${t.roomId}/threads/${e}/comments/${n}/reactions`,{emoji:r});return a=o,{...a,createdAt:new Date(a.createdAt)};var a},removeReaction:async function({threadId:e,commentId:n,emoji:r}){await w.delete(Ae`/v2/c/rooms/${t.roomId}/threads/${e}/comments/${n}/reactions/${r}`)},prepareAttachment:function(e){return{type:"localAttachment",status:"idle",id:yt("at"),name:e.name,size:e.size,mimeType:e.type,file:e}},uploadAttachment:async function(e,n={}){const r=n.signal,o=r?new DOMException(`Upload of attachment ${e.id} was aborted.`,"AbortError"):void 0;if(r?.aborted)throw o;const a=e=>{if(r?.aborted)throw o;if(e instanceof we&&413===e.status)throw e;return!1};if(e.size<=Nt)return De((()=>w.putBlob(Ae`/v2/c/rooms/${t.roomId}/attachments/${e.id}/upload/${encodeURIComponent(e.name)}`,e.file,{fileSize:e.size},{signal:r})),10,Pt,a);{let n;const i=[],s=await De((()=>w.post(Ae`/v2/c/rooms/${t.roomId}/attachments/${e.id}/multipart/${encodeURIComponent(e.name)}`,void 0,{signal:r},{fileSize:e.size})),10,Pt,a);try{n=s.uploadId;const u=function(e){const t=[];let n=0;for(;n<e.size;){const r=Math.min(n+Nt,e.size);t.push({partNumber:t.length+1,part:e.slice(n,r)}),n=r}return t}(e.file);if(r?.aborted)throw o;const c=gt(u,5);for(const n of c){const o=[];for(const{part:i,partNumber:u}of n)o.push(De((()=>w.putBlob(Ae`/v2/c/rooms/${t.roomId}/attachments/${e.id}/multipart/${s.uploadId}/${String(u)}`,i,void 0,{signal:r})),10,Pt,a));i.push(...await Promise.all(o))}if(r?.aborted)throw o;const l=i.sort(((e,t)=>e.partNumber-t.partNumber));return w.post(Ae`/v2/c/rooms/${t.roomId}/attachments/${e.id}/multipart/${n}/complete`,{parts:l},{signal:r})}catch(r){if(n&&r?.name&&("AbortError"===r.name||"TimeoutError"===r.name))try{await w.rawDelete(Ae`/v2/c/rooms/${t.roomId}/attachments/${e.id}/multipart/${n}`)}catch(e){}throw r}}},getAttachmentUrl:function(e){return Se.get(e)},getNotificationSettings:function(e){return Fe(Ae`/v2/c/rooms/${t.roomId}/notification-settings`,{signal:e?.signal})},updateNotificationSettings:function(e){return Fe(Ae`/v2/c/rooms/${t.roomId}/notification-settings`,{method:"POST",body:JSON.stringify(e)})},markInboxNotificationAsRead:async function(e){await Re.get(e)}},de,{enumerable:!1})}function jt(e){function t(t,n){return e.storageBatch.subscribe((e=>{const r=e.filter((e=>ut(e.node,t)));r.length>0&&n(r)}))}return function(n,r,o){if("string"==typeof n&&("my-presence"===(a=n)||"others"===a||"event"===a||"error"===a||"history"===a||"status"===a||"storage-status"===a||"lost-connection"===a||"connection"===a||"comments"===a)){if("function"!=typeof r)throw new Error("Second argument must be a callback function");const t=r;switch(n){case"event":return e.customEvent.subscribe(t);case"my-presence":return e.myPresence.subscribe(t);case"others":{const n=t;return e.others.subscribe((e=>{const{others:t,...r}=e;return n(t,r)}))}case"error":return e.error.subscribe(t);case"status":return e.status.subscribe(t);case"lost-connection":return e.lostConnection.subscribe(t);case"history":return e.history.subscribe(t);case"storage-status":return e.storageStatus.subscribe(t);case"comments":return e.comments.subscribe(t);default:return v(0,`"${String(n)}" is not a valid event name`)}}var a;if(void 0===r||"function"==typeof n){if("function"==typeof n){const t=n;return e.storageBatch.subscribe(t)}throw new Error("Please specify a listener callback")}if(ft(n)){const a=n;if(o?.isDeep){return t(a,r)}return function(t,n){return e.storageBatch.subscribe((e=>{for(const r of e)r.node._id===t._id&&n(r.node)}))}(a,r)}throw new Error(`${String(n)} is not a value that can be subscribed to.`)}}function Lt(e,t){return async()=>t.getAuthValue({requestedScope:"room:read",roomId:e})}function zt(e,t,n){return r=>{const o=n??("undefined"==typeof WebSocket?void 0:WebSocket);if(void 0===o)throw new G("To use Liveblocks client in a non-DOM environment, you need to provide a WebSocket polyfill.");const a=new URL(t);if(a.protocol="http:"===a.protocol?"ws":"wss",a.pathname="/v7",a.searchParams.set("roomId",e),"secret"===r.type)a.searchParams.set("tok",r.token.raw);else{if("public"!==r.type)return v(0,"Unhandled case");a.searchParams.set("pubkey",r.publicApiKey)}return a.searchParams.set("version",f),new o(a.toString())}}function Ht(e){const t=e,n=Ut("throttle",t.throttle??100,16,1e3);const o=function(e){return Ut("lostConnectionTimeout",e,200,3e4,1e3)}(t.lostConnectionTimeout??5e3),a=function(e){return void 0===e?void 0:Ut("backgroundKeepAliveTimeout",e,15e3)}(t.backgroundKeepAliveTimeout),i=function(e){return"string"==typeof e&&e.startsWith("http")?e:"https://api.liveblocks.io"}(t.baseUrl),s=le(e),u=new Map;function c(e){const t=()=>{const n=t;var r;e.unsubs.delete(n)?0===e.unsubs.size&&((r=e.room).id,u.delete(r.id),r.destroy()):x("This leave function was already called. Calling it more than once has no effect.")};return e.unsubs.add(t),{room:e.room,leave:t}}const l=me(null),d=t.polyfills?.fetch||globalThis.fetch?.bind(globalThis),f=Oe({baseUrl:i,fetchPolyfill:d,authManager:s,currentUserIdStore:l}),h=t.resolveUsers,p=Wt((()=>!h),"Set the resolveUsers option in createClient to specify user info."),m=pe(new he((async e=>{const t=e.flat(),n=await(h?.({userIds:t}));return p(),n??t.map((()=>{}))}),{delay:50}));const v=t.resolveRoomsInfo,g=Wt((()=>!v),"Set the resolveRoomsInfo option in createClient to specify room info."),y=pe(new he((async e=>{const t=e.flat(),n=await(v?.({roomIds:t}));return g(),n??t.map((()=>{}))}),{delay:50}));const b=new Map;const E=[],w=new ke("synchronized");function C(){w.set(E.some((e=>"synchronizing"===e.current))?"synchronizing":E.some((e=>"has-local-changes"===e.current))?"has-local-changes":"synchronized")}function D(){const e=new ke("synchronized");E.push(e);const t=e.didInvalidate.subscribe((()=>C()));return{setSyncStatus:function(t){e.set(t)},destroy:function(){t();const n=E.findIndex((t=>t===e));if(n>-1){const[e]=E.splice(n,1);"synchronized"!==e.current&&C()}}}}{const e=e=>{t.preventUnsavedChanges&&"synchronized"!==w.current&&e.preventDefault()};("undefined"!=typeof window?window:void 0)?.addEventListener("beforeunload",e)}const A=Object.defineProperty({enterRoom:function(e,...l){const d=u.get(e);if(void 0!==d)return c(d);const f=l[0]??{},h=Mt({initialPresence:("function"==typeof f.initialPresence?f.initialPresence(e):f.initialPresence)??{},initialStorage:("function"==typeof f.initialStorage?f.initialStorage(e):f.initialStorage)??{}},{roomId:e,throttleDelay:n,lostConnectionTimeout:o,backgroundKeepAliveTimeout:a,polyfills:t.polyfills,delegates:t.mockedDelegates??{createSocket:zt(e,i,t.polyfills?.WebSocket),authenticate:Lt(e,s)},enableDebugLogging:t.enableDebugLogging,unstable_batchedUpdates:f?.unstable_batchedUpdates,baseUrl:i,unstable_fallbackToHTTP:!!t.unstable_fallbackToHTTP,unstable_streamData:!!t.unstable_streamData,createSyncSource:D}),p={room:h,unsubs:new Set};if(u.set(e,p),f.autoConnect??!0){if("undefined"==typeof atob){if(void 0===t.polyfills?.atob)throw new Error("You need to polyfill atob to use the client in your environment. Please follow the instructions at https://liveblocks.io/docs/errors/liveblocks-client/atob-polyfill");r.atob=t.polyfills.atob}h.connect()}return c(p)},getRoom:function(e){const t=u.get(e)?.room;return t||null},logout:function(){s.reset();for(const{room:t}of u.values())"initial"!==(e=t.getStatus())&&"disconnected"!==e&&t.reconnect();var e},...f,resolvers:{invalidateUsers:function(e){m.invalidate(e)},invalidateRoomsInfo:function(e){y.invalidate(e)},invalidateMentionSuggestions:function(){b.clear()}},getSyncStatus:function(){const e=w.current;return"synchronizing"===e?e:"synchronized"},events:{syncStatus:w.didInvalidate},[de]:{currentUserIdStore:l,mentionSuggestionsCache:b,resolveMentionSuggestions:t.resolveMentionSuggestions,usersStore:m,roomsInfoStore:y,getRoomIds:()=>Array.from(u.keys()),getUserThreads_experimental:f.getUserThreads_experimental,getUserThreadsSince_experimental:f.getUserThreadsSince_experimental,as:()=>A,createSyncSource:D}},de,{enumerable:!1});return A}function Ut(e,t,n,r,o){if("number"!=typeof t||t<n||void 0!==r&&t>r)throw new Error(void 0!==r?`${e} should be between ${o??n} and ${r}.`:`${e} should be at least ${o??n}.`);return t}function Wt(e,...t){return()=>{}}var Vt={paragraph:function(e){return"type"in e&&"paragraph"===e.type},text:function(e){return!("type"in e)&&"text"in e&&"string"==typeof e.text},link:function(e){return"type"in e&&"link"===e.type},mention:function(e){return"type"in e&&"mention"===e.type}},$t={paragraph:"block",text:"inline",link:"inline",mention:"inline"};function Kt(e){const t=new Set;return function(e,t,n){if(!e||!e?.content)return;const r="string"==typeof t?t:void 0,o=r?$t[r]:"all",a=r?Vt[r]:()=>!0,i="function"==typeof t?t:n;for(const t of e.content)if("all"!==o&&"block"!==o||a(t)&&i?.(t),"all"===o||"inline"===o)for(const e of t.children)a(e)&&i?.(e)}(e,"mention",(e=>t.add(e.id))),Array.from(t)}new RegExp(Object.keys({"&":"&","<":"<",">":">",'"':""","'":"'"}).map((e=>`\\${e}`)).join("|"),"g");new RegExp(Object.keys({_:"\\_","*":"\\*","#":"\\#","`":"\\`","~":"\\~","!":"\\!","|":"\\|","(":"\\(",")":"\\)","{":"\\{","}":"\\}","[":"\\[","]":"\\]"}).map((e=>`\\${e}`)).join("|"),"g");var qt=[1e3,2e3,4e3,8e3,1e4];function Gt(e,t,n){const r=performance.now(),o="undefined"!=typeof document?document:void 0,a="undefined"!=typeof window?window:void 0,i=n?.maxStaleTimeMs??Number.POSITIVE_INFINITY,s={inForeground:"hidden"!==o?.visibilityState,lastSuccessfulPollAt:r,count:0,backoff:0};function u(){return s.count>0&&s.inForeground}const c=new T({}).addState("@idle").addState("@enabled").addState("@polling");function l(){u()?c.send({type:"START"}):c.send({type:"STOP"})}function d(){performance.now()-s.lastSuccessfulPollAt>i&&c.send({type:"POLL"})}function f(e){s.inForeground=e,l(),d()}function h(){f("hidden"!==o?.visibilityState)}return c.addTransitions("@idle",{START:"@enabled"}),c.addTransitions("@enabled",{STOP:"@idle",POLL:"@polling"}),c.addTimedTransition("@enabled",(()=>{const e=s.lastSuccessfulPollAt+t;return Math.max(0,e-performance.now())+s.backoff}),"@polling"),c.onEnterAsync("@polling",(async(t,n)=>{await e(n),n.aborted||(s.lastSuccessfulPollAt=performance.now())}),(()=>({target:u()?"@enabled":"@idle",effect:()=>{s.backoff=0}})),(()=>({target:u()?"@enabled":"@idle",effect:()=>{s.backoff=qt.find((e=>e>s.backoff))??qt[qt.length-1]}})),3e4),o?.addEventListener("visibilitychange",h),a?.addEventListener("online",h),c.start(),{inc:function(){s.count++,l()},dec:function(){s.count--,s.count<0&&(s.count=0),l()},pollNowIfStale:d,setInForeground:f}}function Zt(e,t){if(Object.is(e,t))return!0;const n=Array.isArray(e),r=Array.isArray(t);return n||r?!(!n||!r)&&function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0}(e,t):function(e,t){if(!I(e)||!I(t))return!1;const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every((n=>Object.prototype.hasOwnProperty.call(t,n)&&Object.is(e[n],t[n])))}(e,t)}var Xt=class e{constructor(e,t){this._lt=t,this._data=e}static from(t,n){const r=new e([],n);for(const e of t)r.add(e);return r}static fromAlreadySorted(t,n){return new e(t,n)}clone(){return new e(this._data.slice(),this._lt)}add(e){const t=function(e,t,n){let r=0,o=e.length;for(;r<o;){const a=r+(o-r>>1);n(t,e[a])?o=a:r=a+1}return r}(this._data,e,this._lt);this._data.splice(t,0,e)}remove(e){const t=this._data.indexOf(e);return t>=0&&(this._data.splice(t,1),!0)}get length(){return this._data.length}*filter(e){for(const t of this._data)e(t)&&(yield t)}[Symbol.iterator](){return this._data[Symbol.iterator]()}};m(d,f,"esm");var Yt="@liveblocks/react",Jt="2.12.0";function Qt(e){const[t,n]=i.useState(!1);return i.useEffect((()=>{n(!0)}),[]),i.createElement(i.Suspense,{fallback:e.fallback},t?"function"==typeof e.children?e.children():e.children:e.fallback)}var en,tn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==r?r:"undefined"!=typeof self?self:{},nn={exports:{}},rn={};!function(e){e.exports=function(){if(en)return rn;en=1;var e=s.default,t="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},n=e.useState,r=e.useEffect,o=e.useLayoutEffect,a=e.useDebugValue;function i(e){var n=e.getSnapshot;e=e.value;try{var r=n();return!t(e,r)}catch(e){return!0}}var u="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(e,t){var s=t(),u=n({inst:{value:s,getSnapshot:t}}),c=u[0].inst,l=u[1];return o((function(){c.value=s,c.getSnapshot=t,i(c)&&l({inst:c})}),[e,s,t]),r((function(){return i(c)&&l({inst:c}),e((function(){i(c)&&l({inst:c})}))}),[e]),a(s),s};return rn.useSyncExternalStore=void 0!==e.useSyncExternalStore?e.useSyncExternalStore:u,rn}()}(nn);var on,an={exports:{}},sn={};!function(e){e.exports=function(){if(on)return sn;on=1;var e=s.default,t=nn.exports,n="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=t.useSyncExternalStore,o=e.useRef,a=e.useEffect,i=e.useMemo,u=e.useDebugValue;return sn.useSyncExternalStoreWithSelector=function(e,t,s,c,l){var d=o(null);if(null===d.current){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=i((function(){function e(e){if(!a){if(a=!0,r=e,e=c(e),void 0!==l&&f.hasValue){var t=f.value;if(l(t,e))return o=t}return o=e}if(t=o,n(r,e))return t;var i=c(e);return void 0!==l&&l(t,i)?(r=e,t):(r=e,o=i)}var r,o,a=!1,i=void 0===s?null:s;return[function(){return e(t())},null===i?void 0:function(){return e(i())}]}),[t,s,c,l]);var h=r(e,d[0],d[1]);return a((function(){f.hasValue=!0,f.value=h}),[h]),u(h),h},sn}()}(an);m("@liveblocks/client","2.12.0","esm");var un=i.createContext(null);function cn(){return i.useContext(un)}var ln={SMOOTH_DELAY:1e3,NOTIFICATIONS_POLL_INTERVAL:6e4,NOTIFICATIONS_MAX_STALE_TIME:5e3,ROOM_THREADS_POLL_INTERVAL:3e5,ROOM_THREADS_MAX_STALE_TIME:5e3,USER_THREADS_POLL_INTERVAL:6e4,USER_THREADS_MAX_STALE_TIME:5e3,HISTORY_VERSIONS_POLL_INTERVAL:6e4,HISTORY_VERSIONS_MAX_STALE_TIME:5e3,NOTIFICATION_SETTINGS_POLL_INTERVAL:6e4,NOTIFICATION_SETTINGS_MAX_STALE_TIME:5e3};function dn(e,t){if(!I(e)||!I(t))return Zt(e,t);const n=Object.keys(e);return n.length===Object.keys(t).length&&n.every((n=>Object.prototype.hasOwnProperty.call(t,n)&&Zt(e[n],t[n])))}var fn=e=>e;function hn(e){return t.useReducer(fn,e)[0]}function pn(e){const n=hn(e);if("function"==typeof n){const n=function(e){const n=t.useRef(e);return t.useEffect((()=>{n.current=e}),[e]),n}(e);return t.useCallback(((...e)=>n.current(...e)),[n])}return n}var mn=e=>{if("pending"===e.status)throw e;if("fulfilled"===e.status)return e.value;throw"rejected"===e.status?e.reason:(e.status="pending",e.then((t=>{e.status="fulfilled",e.value=t}),(t=>{e.status="rejected",e.reason=t})),e)};function vn(e){const t=new Set;t.add("constructor");let n=e.constructor.prototype;do{for(const r of Reflect.ownKeys(n)){if(t.has(r))continue;"function"==typeof Reflect.getOwnPropertyDescriptor(n,r)?.value&&(t.add(r),e[r]=e[r].bind(e))}}while((n=Reflect.getPrototypeOf(n))&&n!==Object.prototype)}function gn(e){return"string"==typeof e}function yn(e){return t=>function(e,t){return void 0===t.resolved||e.resolved===t.resolved}(t,e)&&function(e,t){const n=e.metadata;return void 0===t.metadata||Object.entries(t.metadata).every((([e,t])=>function(e,t){return n=t,I(n)&&gn(n.startsWith)?gn(e)&&e.startsWith(t.startsWith):e===t;var n}(n[e],t)))}(t,e)}function bn(e,t){return`${e}-${fe(t??{})}`}function En(e){return`USER_THREADS:${fe(e??{})}`}function wn(e){return`${e}:NOTIFICATION_SETTINGS`}function Cn(e){return`${e}-VERSIONS`}function Dn(e){if("status"in e)return e;const t=e;return t.status="pending",t.then((e=>{t.status="fulfilled",t.value=e}),(e=>{t.status="rejected",t.reason=e})),t}var xn=Promise.resolve(),An=Object.freeze({isLoading:!0}),_n=class{constructor(e){this._cachedPromise=null,this._paginationState=null,this._fetchPage=e,this._eventSource=E(),this._pendingFetchMore=null,this.observable=this._eventSource.observable,vn(this)}patchPaginationState(e){const t=this._paginationState;null!==t&&(this._paginationState={...t,...e},this._eventSource.notify())}async _fetchMore(){const e=this._paginationState;if(e?.cursor){this.patchPaginationState({isFetchingMore:!0});try{const t=await this._fetchPage(e.cursor);this.patchPaginationState({cursor:t,fetchMoreError:void 0,isFetchingMore:!1})}catch(e){this.patchPaginationState({isFetchingMore:!1,fetchMoreError:e})}}}fetchMore(){return null===this._paginationState?.cursor?xn:(this._pendingFetchMore||(this._pendingFetchMore=this._fetchMore().finally((()=>{this._pendingFetchMore=null}))),this._pendingFetchMore)}get(){const e=this._cachedPromise;if(null===e||"pending"===e.status)return An;if("rejected"===e.status)return{isLoading:!1,error:e.reason};const t=this._paginationState;return{isLoading:!1,data:{fetchMore:this.fetchMore,isFetchingMore:t.isFetchingMore,fetchMoreError:t.fetchMoreError,hasFetchedAll:null===t.cursor}}}waitUntilLoaded(){if(this._cachedPromise)return this._cachedPromise;const e=Dn(De((()=>this._fetchPage(void 0)),5,[5e3,5e3,1e4,15e3]).then((e=>{this._paginationState={cursor:e,isFetchingMore:!1,fetchMoreError:void 0}})));return e.then((()=>this._eventSource.notify()),(()=>{this._eventSource.notify(),setTimeout((()=>{this._cachedPromise=null,this._eventSource.notify()}),5e3)})),this._cachedPromise=e,e}},Bn=class{constructor(e){this._cachedPromise=null,this._fetchPage=e,this._eventSource=E(),this.observable=this._eventSource.observable,vn(this)}get(){const e=this._cachedPromise;return null===e||"pending"===e.status?An:"rejected"===e.status?{isLoading:!1,error:e.reason}:{isLoading:!1,data:void 0}}waitUntilLoaded(){if(this._cachedPromise)return this._cachedPromise;const e=Dn(De((()=>this._fetchPage()),5,[5e3,5e3,1e4,15e3]));return e.then((()=>this._eventSource.notify()),(()=>{this._eventSource.notify(),setTimeout((()=>{this._cachedPromise=null,this._eventSource.notify()}),5e3)})),this._cachedPromise=e,e}};function On(e,t){if(void 0!==e.deletedAt)return e;if(t.threadId!==e.id)return w.warn(`Comment ${t.id} does not belong to thread ${e.id}`),e;const n=e.comments.find((e=>e.id===t.id));if(void 0===n){const n=new Date(Math.max(e.updatedAt.getTime(),t.createdAt.getTime()));return{...e,updatedAt:n,comments:[...e.comments,t]}}if(void 0!==n.deletedAt)return e;if(void 0===n.editedAt||void 0===t.editedAt||n.editedAt<=t.editedAt){const n=e.comments.map((e=>e.id===t.id?t:e));return{...e,updatedAt:new Date(Math.max(e.updatedAt.getTime(),t.editedAt?.getTime()||t.createdAt.getTime())),comments:n}}return e}function Sn(e,t,n){if(void 0!==e.deletedAt)return e;const r=e.comments.find((e=>e.id===t));if(void 0===r)return e;if(void 0!==r.deletedAt)return e;const o=e.comments.map((e=>e.id===t?{...e,deletedAt:n,body:void 0,attachments:[]}:e));return o.every((e=>void 0!==e.deletedAt))?{...e,deletedAt:n,updatedAt:n}:{...e,updatedAt:n,comments:o}}function Tn(e,t,n){if(void 0!==e.deletedAt)return e;const r=e.comments.find((e=>e.id===t));if(void 0===r)return e;if(void 0!==r.deletedAt)return e;const o=e.comments.map((e=>e.id===t?{...e,reactions:In(e.reactions,n)}:e));return{...e,updatedAt:new Date(Math.max(n.createdAt.getTime(),e.updatedAt.getTime())),comments:o}}function kn(e,t,n,r,o){if(void 0!==e.deletedAt)return e;const a=e.comments.find((e=>e.id===t));if(void 0===a)return e;if(void 0!==a.deletedAt)return e;const i=e.comments.map((e=>e.id===t?{...e,reactions:e.reactions.map((e=>e.emoji===n?{...e,users:e.users.filter((e=>e.id!==r))}:e)).filter((e=>e.users.length>0))}:e));return{...e,updatedAt:new Date(Math.max(o.getTime(),e.updatedAt.getTime())),comments:i}}function In(e,t){const n=e.find((e=>e.emoji===t.emoji));return void 0===n?[...e,{emoji:t.emoji,createdAt:t.createdAt,users:[{id:t.userId}]}]:!1===n.users.some((e=>e.id===t.userId))?e.map((e=>e.emoji===t.emoji?{...e,users:[...e.users,{id:t.userId}]}:e)):e}var Fn=t.createContext(null);function Rn(e){return new Error(`resolveUsers didn't return anything for user '${e}'`)}function Nn(e){return new Error(`resolveRoomsInfo didn't return anything for room '${e}'`)}function Pn(e){return e}var Mn=new WeakMap,jn=new WeakMap;function Ln(e){let t=0;for(const n of e)(null===n.readAt||n.readAt<n.notifiedAt)&&t++;return t}function zn(e){return e.inboxNotifications?{isLoading:!1,count:Ln(e.inboxNotifications)}:e}function Hn(e){let t=Mn.get(e);return t||(t=new class{constructor(e){this._prevVersion=-1,this._prevState=null,this._stateCached=null,this._notificationsLastRequestedAt=null,this._roomThreadsLastRequestedAtByRoom=new Map,this._roomThreads=new Map,this._userThreadsLastRequestedAt=null,this._userThreads=new Map,this._roomVersions=new Map,this._roomVersionsLastRequestedAtByRoom=new Map,this._roomNotificationSettings=new Map,this._client=e[de].as(),this._syncSource=this._client[de].createSyncSource(),this._notifications=new _n((async e=>{const t=await this._client.getInboxNotifications({cursor:e});return this.updateThreadsAndNotifications(t.threads,t.inboxNotifications),null===this._notificationsLastRequestedAt&&(this._notificationsLastRequestedAt=t.requestedAt),t.nextCursor})),this._notifications.observable.subscribe((()=>this._store.set((e=>({...e}))))),this._rawThreadsDB=new class e{constructor(){this._asc=Xt.from([],((e,t)=>{const n=e.createdAt,r=t.createdAt;return n<r||n===r&&e.id<t.id})),this._desc=Xt.from([],((e,t)=>{const n=t.updatedAt,r=e.updatedAt;return n<r||n===r&&t.id<e.id})),this._byId=new Map,this._version=0}clone(){const t=new e;return t._byId=new Map(this._byId),t._asc=this._asc.clone(),t._desc=this._desc.clone(),t._version=this._version,t}get version(){return this._version}get(e){const t=this.getEvenIfDeleted(e);return t?.deletedAt?void 0:t}getEvenIfDeleted(e){return this._byId.get(e)}upsert(e){const t=(e=function(e){return e.deletedAt&&e.comments.length>0?{...e,comments:[]}:e.comments.some((e=>!e.deletedAt))?e:{...e,deletedAt:new Date,comments:[]}}(e)).id,n=this._byId.get(t);if(n){if(n.deletedAt)return;this._asc.remove(n),this._desc.remove(n)}e.deletedAt||(this._asc.add(e),this._desc.add(e)),this._byId.set(t,e),this.touch()}upsertIfNewer(e){const t=this.get(e.id);(!t||e.updatedAt>=t.updatedAt)&&this.upsert(e)}delete(e,t){const n=this._byId.get(e);n&&!n.deletedAt&&this.upsert({...n,deletedAt:t,updatedAt:t})}findMany(e,t,n){const r="desc"===n?this._desc:this._asc,o=[];return void 0!==e&&o.push((t=>t.roomId===e)),o.push(yn(t)),Array.from(r.filter((e=>o.every((t=>t(e))))))}touch(){++this._version}},this._store=me({optimisticUpdates:[],notificationsById:{},settingsByRoomId:{},versionsByRoomId:{}}),vn(this)}get(){const e=this._store.get();return this._prevVersion===this._rawThreadsDB.version&&this._prevState===e&&null!==this._stateCached||(this._stateCached=function(e,t){const n=t.clone(),r={notificationsById:{...e.notificationsById},settingsByRoomId:{...e.settingsByRoomId}};for(const t of e.optimisticUpdates)switch(t.type){case"create-thread":n.upsert(t.thread);break;case"edit-thread-metadata":{const e=n.get(t.threadId);if(void 0===e)break;if(e.updatedAt>t.updatedAt)break;n.upsert({...e,updatedAt:t.updatedAt,metadata:{...e.metadata,...t.metadata}});break}case"mark-thread-as-resolved":{const e=n.get(t.threadId);if(void 0===e)break;n.upsert({...e,resolved:!0});break}case"mark-thread-as-unresolved":{const e=n.get(t.threadId);if(void 0===e)break;n.upsert({...e,resolved:!1});break}case"create-comment":{const e=n.get(t.comment.threadId);if(void 0===e)break;n.upsert(On(e,t.comment));const o=Object.values(r.notificationsById).find((t=>"thread"===t.kind&&t.threadId===e.id));if(void 0===o)break;r.notificationsById[o.id]={...o,notifiedAt:t.comment.createdAt,readAt:t.comment.createdAt};break}case"edit-comment":{const e=n.get(t.comment.threadId);if(void 0===e)break;n.upsert(On(e,t.comment));break}case"delete-comment":{const e=n.get(t.threadId);if(void 0===e)break;n.upsert(Sn(e,t.commentId,t.deletedAt));break}case"delete-thread":{const e=n.get(t.threadId);if(void 0===e)break;n.upsert({...e,deletedAt:t.deletedAt,updatedAt:t.deletedAt,comments:[]});break}case"add-reaction":{const e=n.get(t.threadId);if(void 0===e)break;n.upsert(Tn(e,t.commentId,t.reaction));break}case"remove-reaction":{const e=n.get(t.threadId);if(void 0===e)break;n.upsert(kn(e,t.commentId,t.emoji,t.userId,t.removedAt));break}case"mark-inbox-notification-as-read":{const e=r.notificationsById[t.inboxNotificationId];if(void 0===e)break;r.notificationsById[t.inboxNotificationId]={...e,readAt:t.readAt};break}case"mark-all-inbox-notifications-as-read":for(const e in r.notificationsById){const n=r.notificationsById[e];if(void 0===n)break;r.notificationsById[e]={...n,readAt:t.readAt}}break;case"delete-inbox-notification":delete r.notificationsById[t.inboxNotificationId];break;case"delete-all-inbox-notifications":r.notificationsById={};break;case"update-notification-settings":{const e=r.settingsByRoomId[t.roomId];if(void 0===e)break;r.settingsByRoomId[t.roomId]={...e,...t.settings}}}return{cleanedNotifications:Object.values(r.notificationsById).filter((e=>"thread"!==e.kind||void 0!==n.get(e.threadId))).sort(((e,t)=>t.notifiedAt.getTime()-e.notifiedAt.getTime())),notificationsById:r.notificationsById,settingsByRoomId:r.settingsByRoomId,threadsDB:n,versionsByRoomId:e.versionsByRoomId}}(e,this._rawThreadsDB),this._prevState=e,this._prevVersion=this._rawThreadsDB.version),this._stateCached}batch(e){return this._store.batch(e)}getFullState(){return this.get()}getRoomThreadsLoadingState(e,t){const n=bn(e,t),r=this._roomThreads.get(n);if(void 0===r)return An;const o=r.get();if(o.isLoading||o.error)return o;const a=this.getFullState().threadsDB.findMany(e,t??{},"asc"),i=o.data;return{isLoading:!1,threads:a,hasFetchedAll:i.hasFetchedAll,isFetchingMore:i.isFetchingMore,fetchMoreError:i.fetchMoreError,fetchMore:i.fetchMore}}getUserThreadsLoadingState(e){const t=En(e),n=this._userThreads.get(t);if(void 0===n)return An;const r=n.get();if(r.isLoading||r.error)return r;const o=this.getFullState().threadsDB.findMany(void 0,e??{},"desc"),a=r.data;return{isLoading:!1,threads:o,hasFetchedAll:a.hasFetchedAll,isFetchingMore:a.isFetchingMore,fetchMoreError:a.fetchMoreError,fetchMore:a.fetchMore}}getInboxNotificationsLoadingState(){const e=this._notifications.get();if(e.isLoading||e.error)return e;const t=e.data;return{isLoading:!1,inboxNotifications:this.getFullState().cleanedNotifications,hasFetchedAll:t.hasFetchedAll,isFetchingMore:t.isFetchingMore,fetchMoreError:t.fetchMoreError,fetchMore:t.fetchMore}}getNotificationSettingsLoadingState(e){const t=wn(e),n=this._roomNotificationSettings.get(t);if(void 0===n)return An;const r=n.get();return r.isLoading||r.error?r:{isLoading:!1,settings:g(this.get().settingsByRoomId[e])}}getRoomVersionsLoadingState(e){const t=Cn(e),n=this._roomVersions.get(t);if(void 0===n)return An;const r=n.get();return r.isLoading||r.error?r:{isLoading:!1,versions:Object.values(this.get().versionsByRoomId[e]??{})}}subscribe(e){return this._store.subscribe(e)}mutateThreadsDB(e){const t=this._rawThreadsDB,n=t.version;e(t),n!==t.version&&this._store.set((e=>({...e})))}updateInboxNotificationsCache(e){this._store.set((t=>{const n=e(t.notificationsById);return n!==t.notificationsById?{...t,notificationsById:n}:t}))}setNotificationSettings(e,t){this._store.set((n=>({...n,settingsByRoomId:{...n.settingsByRoomId,[e]:t}})))}updateRoomVersions(e,t){this._store.set((n=>{const r=Object.fromEntries(t.map((e=>[e.id,e])));return{...n,versionsByRoomId:{...n.versionsByRoomId,[e]:{...n.versionsByRoomId[e]??{},...r}}}}))}updateOptimisticUpdatesCache(e){this._store.set((t=>{const n=e(t.optimisticUpdates);return this._syncSource.setSyncStatus(n.length>0?"synchronizing":"synchronized"),{...t,optimisticUpdates:n}}))}force_set(e){return this._store.set(e)}updateInboxNotification(e,t,n){this._store.batch((()=>{this.removeOptimisticUpdate(t),this.updateInboxNotificationsCache((t=>{const r=t[e];return r?{...t,[e]:n(r)}:t}))}))}updateAllInboxNotifications(e,t){this._store.batch((()=>{this.removeOptimisticUpdate(e),this.updateInboxNotificationsCache((e=>function(e,t){const n={};for(const r of Object.entries(e)){const e=r[0];if("__proto__"===e)continue;const o=r[1];n[e]=t(o,e)}return n}(e,t)))}))}deleteInboxNotification(e,t){this._store.batch((()=>{this.removeOptimisticUpdate(t),this.updateInboxNotificationsCache((t=>{const{[e]:n,...r}=t;return void 0===n?t:r}))}))}deleteAllInboxNotifications(e){this._store.batch((()=>{this.removeOptimisticUpdate(e),this.updateInboxNotificationsCache((()=>({})))}))}createThread(e,t){this._store.batch((()=>{this.removeOptimisticUpdate(e),this.mutateThreadsDB((e=>e.upsert(t)))}))}updateThread(e,t,n,r){this._store.batch((()=>{null!==t&&this.removeOptimisticUpdate(t),this.mutateThreadsDB((t=>{const o=t.get(e);o&&(r&&o.updatedAt>r||t.upsert(n(o)))}))}))}patchThread(e,t,n,r){return this.updateThread(e,t,(e=>({...e,...M(n)})),r)}addReaction(e,t,n,r,o){this.updateThread(e,t,(e=>Tn(e,n,r)),o)}removeReaction(e,t,n,r,o,a){this.updateThread(e,t,(e=>kn(e,n,r,o,a)),a)}deleteThread(e,t){return this.updateThread(e,t,(e=>({...e,updatedAt:new Date,deletedAt:new Date})))}createComment(e,t){this._store.batch((()=>{this.removeOptimisticUpdate(t);const n=this._rawThreadsDB.get(e.threadId);n&&(this.mutateThreadsDB((t=>t.upsert(On(n,e)))),this.updateInboxNotificationsCache((t=>{const n=Object.values(t).find((t=>"thread"===t.kind&&t.threadId===e.threadId));return n?{...t,[n.id]:{...n,notifiedAt:e.createdAt,readAt:e.createdAt}}:t})))}))}editComment(e,t,n){return this.updateThread(e,t,(e=>On(e,n)))}deleteComment(e,t,n,r){return this.updateThread(e,t,(e=>Sn(e,n,r)),r)}updateThreadAndNotification(e,t){this._store.batch((()=>{this.mutateThreadsDB((t=>t.upsertIfNewer(e))),void 0!==t&&this.updateInboxNotificationsCache((e=>({...e,[t.id]:t})))}))}updateThreadsAndNotifications(e,t,n=[],r=[]){this._store.batch((()=>{this.mutateThreadsDB((t=>function(e,t){t.newThreads.forEach((t=>e.upsertIfNewer(t))),t.deletedThreads.forEach((({id:t,deletedAt:n})=>{e.getEvenIfDeleted(t)&&e.delete(t,n)}))}(t,{newThreads:e,deletedThreads:n}))),this.updateInboxNotificationsCache((e=>function(e,t){const n={...e};return t.newInboxNotifications.forEach((e=>{const t=n[e.id];var r,o;t&&1==(o=e,(r=t).notifiedAt>o.notifiedAt?1:r.notifiedAt<o.notifiedAt?-1:r.readAt&&o.readAt?r.readAt>o.readAt?1:r.readAt<o.readAt?-1:0:r.readAt||o.readAt?r.readAt?1:-1:0)||(n[e.id]=e)})),t.deletedNotifications.forEach((({id:e})=>delete n[e])),n}(e,{newInboxNotifications:t,deletedNotifications:r})))}))}updateRoomNotificationSettings_confirmOptimisticUpdate(e,t,n){this._store.batch((()=>{this.removeOptimisticUpdate(t),this.setNotificationSettings(e,n)}))}addOptimisticUpdate(e){const t=qe(),n={...e,id:t};return this.updateOptimisticUpdatesCache((e=>[...e,n])),t}removeOptimisticUpdate(e){this.updateOptimisticUpdatesCache((t=>t.filter((t=>t.id!==e))))}async fetchNotificationsDeltaUpdate(e){const t=this._notificationsLastRequestedAt;if(null===t)return;const n=await this._client.getInboxNotificationsSince({since:t,signal:e});t<n.requestedAt&&(this._notificationsLastRequestedAt=n.requestedAt),this.updateThreadsAndNotifications(n.threads.updated,n.inboxNotifications.updated,n.threads.deleted,n.inboxNotifications.deleted)}waitUntilNotificationsLoaded(){return this._notifications.waitUntilLoaded()}waitUntilRoomThreadsLoaded(e,t){const n=async n=>{const r=this._client.getRoom(e);if(null===r)throw new we(`Room '${e}' is not available on client`,479);const o=await r.getThreads({cursor:n,query:t});this.updateThreadsAndNotifications(o.threads,o.inboxNotifications);const a=this._roomThreadsLastRequestedAtByRoom.get(e);return(void 0===a||a>o.requestedAt)&&this._roomThreadsLastRequestedAtByRoom.set(e,o.requestedAt),o.nextCursor},r=bn(e,t);let o=this._roomThreads.get(r);return void 0===o&&(o=new _n(n)),o.observable.subscribe((()=>this._store.set((e=>({...e}))))),this._roomThreads.set(r,o),o.waitUntilLoaded()}async fetchRoomThreadsDeltaUpdate(e,t){const n=this._roomThreadsLastRequestedAtByRoom.get(e);if(void 0===n)return;const r=g(this._client.getRoom(e),`Room with id ${e} is not available on client`),o=await r.getThreadsSince({since:n,signal:t});this.updateThreadsAndNotifications(o.threads.updated,o.inboxNotifications.updated,o.threads.deleted,o.inboxNotifications.deleted),n<o.requestedAt&&this._roomThreadsLastRequestedAtByRoom.set(e,o.requestedAt)}waitUntilUserThreadsLoaded(e){const t=En(e),n=async t=>{const n=await this._client[de].getUserThreads_experimental({cursor:t,query:e});return this.updateThreadsAndNotifications(n.threads,n.inboxNotifications),null===this._userThreadsLastRequestedAt&&(this._userThreadsLastRequestedAt=n.requestedAt),n.nextCursor};let r=this._userThreads.get(t);return void 0===r&&(r=new _n(n)),r.observable.subscribe((()=>this._store.set((e=>({...e}))))),this._userThreads.set(t,r),r.waitUntilLoaded()}async fetchUserThreadsDeltaUpdate(e){const t=this._userThreadsLastRequestedAt;if(null===t)return;const n=await this._client[de].getUserThreadsSince_experimental({since:t,signal:e});t<n.requestedAt&&(this._notificationsLastRequestedAt=n.requestedAt),this.updateThreadsAndNotifications(n.threads.updated,n.inboxNotifications.updated,n.threads.deleted,n.inboxNotifications.deleted)}waitUntilRoomVersionsLoaded(e){const t=Cn(e);let n=this._roomVersions.get(t);return void 0===n&&(n=new Bn((async()=>{const t=this._client.getRoom(e);if(null===t)throw new we(`Room '${e}' is not available on client`,479);const n=await t[de].listTextVersions();this.updateRoomVersions(e,n.versions);const r=this._roomVersionsLastRequestedAtByRoom.get(e);(void 0===r||r>n.requestedAt)&&this._roomVersionsLastRequestedAtByRoom.set(e,n.requestedAt)}))),n.observable.subscribe((()=>this._store.set((e=>({...e}))))),this._roomVersions.set(t,n),n.waitUntilLoaded()}async fetchRoomVersionsDeltaUpdate(e,t){const n=this._roomVersionsLastRequestedAtByRoom.get(e);if(void 0===n)return;const r=g(this._client.getRoom(e),`Room with id ${e} is not available on client`),o=await r[de].listTextVersionsSince({since:n,signal:t});this.updateRoomVersions(e,o.versions),n<o.requestedAt&&this._roomVersionsLastRequestedAtByRoom.set(e,o.requestedAt)}waitUntilRoomNotificationSettingsLoaded(e){const t=wn(e);let n=this._roomNotificationSettings.get(t);return void 0===n&&(n=new Bn((async()=>{const t=this._client.getRoom(e);if(null===t)throw new we(`Room '${e}' is not available on client`,479);const n=await t.getNotificationSettings();this.setNotificationSettings(e,n)}))),n.observable.subscribe((()=>this._store.set((e=>({...e}))))),this._roomNotificationSettings.set(t,n),n.waitUntilLoaded()}async refreshRoomNotificationSettings(e,t){const n=g(this._client.getRoom(e),`Room with id ${e} is not available on client`),r=await n.getNotificationSettings({signal:t});this.setNotificationSettings(e,r)}}(e),Mn.set(e,t)),t}function Un(e){let t=jn.get(e);return t||(t=function(e){const t=Hn(e),n=Gt((async e=>{try{return await t.fetchNotificationsDeltaUpdate(e)}catch(e){throw console.warn(`Polling new inbox notifications failed: ${String(e)}`),e}}),ln.NOTIFICATIONS_POLL_INTERVAL,{maxStaleTimeMs:ln.NOTIFICATIONS_MAX_STALE_TIME}),r=Gt((async e=>{try{return await t.fetchUserThreadsDeltaUpdate(e)}catch(e){throw console.warn(`Polling new user threads failed: ${String(e)}`),e}}),ln.USER_THREADS_POLL_INTERVAL,{maxStaleTimeMs:ln.USER_THREADS_MAX_STALE_TIME});return{store:t,notificationsPoller:n,userThreadsPoller:r}}(e),jn.set(e,t)),t}function Wn(e,n,r){const{store:o,notificationsPoller:a}=Un(e);return t.useEffect((()=>{o.waitUntilNotificationsLoaded()})),t.useEffect((()=>(a.inc(),a.pollNowIfStale(),()=>{a.dec()})),[a]),an.exports.useSyncExternalStoreWithSelector(o.subscribe,o.getInboxNotificationsLoadingState,o.getInboxNotificationsLoadingState,n,r)}function Vn(e){const t=Un(e).store;mn(t.waitUntilNotificationsLoaded());const n=function(e){return Wn(e,zn,Zt)}(e);return n.isLoading,n.error,n}function $n(e,n){const r=e[de].usersStore,o=t.useCallback((()=>r.getState(n)),[r,n]),a=t.useCallback((e=>function(e,t){return void 0===e||e?.isLoading?e??{isLoading:!0}:e.error?e:e.data?{isLoading:!1,user:e.data}:{isLoading:!1,error:Rn(t)}}(e,n)),[n]),i=an.exports.useSyncExternalStoreWithSelector(r.subscribe,o,o,a,Zt);return t.useEffect((()=>{r.get(n)}),[r,n,i]),i}function Kn(e,n){const r=e[de].roomsInfoStore,o=t.useCallback((()=>r.getState(n)),[r,n]),a=t.useCallback((e=>function(e,t){return void 0===e||e?.isLoading?e??{isLoading:!0}:e.error?e:e.data?{isLoading:!1,info:e.data}:{isLoading:!1,error:Nn(t)}}(e,n)),[n]),i=an.exports.useSyncExternalStoreWithSelector(r.subscribe,o,o,a,Zt);return t.useEffect((()=>{r.get(n)}),[r,n,i]),i}function qn(){return t.useContext(Fn)}function Gn(){return qn()??k("LiveblocksProvider is missing from the React tree.")}function Zn(e){return function(e){const t=qn();if(!e?.allowNesting&&null!==t)throw new Error("You cannot nest multiple LiveblocksProvider instances in the same React tree.")}(e),s.default.createElement(Fn.Provider,{value:e.client},e.children)}function Xn(e){const{children:n,...r}=e,o={publicApiKey:hn(r.publicApiKey),throttle:hn(r.throttle),lostConnectionTimeout:hn(r.lostConnectionTimeout),backgroundKeepAliveTimeout:hn(r.backgroundKeepAliveTimeout),polyfills:hn(r.polyfills),unstable_fallbackToHTTP:hn(r.unstable_fallbackToHTTP),unstable_streamData:hn(r.unstable_streamData),preventUnsavedChanges:hn(r.preventUnsavedChanges),authEndpoint:pn(r.authEndpoint),resolveMentionSuggestions:pn(r.resolveMentionSuggestions),resolveUsers:pn(r.resolveUsers),resolveRoomsInfo:pn(r.resolveRoomsInfo),baseUrl:hn(r.baseUrl),enableDebugLogging:hn(r.enableDebugLogging)},a=t.useMemo((()=>Ht(o)),[]);return s.default.createElement(Zn,{client:a},n)}function Yn(){return function(e){const t=Un(e).store;mn(t.waitUntilNotificationsLoaded());const n=Wn(e,Pn,Zt);return n.error,n.isLoading,n}(Gn())}function Jn(){return e=Gn(),t.useCallback((()=>{const{store:t}=Un(e),n=new Date,r=t.addOptimisticUpdate({type:"mark-all-inbox-notifications-as-read",readAt:n});e.markAllInboxNotificationsAsRead().then((()=>{t.updateAllInboxNotifications(r,(e=>({...e,readAt:n})))}),(()=>{t.removeOptimisticUpdate(r)}))}),[e]);var e}function Qn(){return e=Gn(),t.useCallback((t=>{const{store:n}=Un(e),r=new Date,o=n.addOptimisticUpdate({type:"mark-inbox-notification-as-read",inboxNotificationId:t,readAt:r});e.markInboxNotificationAsRead(t).then((()=>{n.updateInboxNotification(t,o,(e=>({...e,readAt:r})))}),(()=>{n.removeOptimisticUpdate(o)}))}),[e]);var e}function er(){return e=Gn(),t.useCallback((()=>{const{store:t}=Un(e),n=new Date,r=t.addOptimisticUpdate({type:"delete-all-inbox-notifications",deletedAt:n});e.deleteAllInboxNotifications().then((()=>{t.deleteAllInboxNotifications(r)}),(()=>{t.removeOptimisticUpdate(r)}))}),[e]);var e}function tr(){return e=Gn(),t.useCallback((t=>{const{store:n}=Un(e),r=new Date,o=n.addOptimisticUpdate({type:"delete-inbox-notification",inboxNotificationId:t,deletedAt:r});e.deleteInboxNotification(t).then((()=>{n.deleteInboxNotification(t,o)}),(()=>{n.removeOptimisticUpdate(o)}))}),[e]);var e}function nr(e){return Kn(Gn(),e)}var rr=function(e){return function(e,n){const{store:r}=Un(e),o=r.getFullState,a=t.useCallback((e=>{const t=e.notificationsById[n]??k(`Inbox notification with ID "${n}" not found`);return"thread"!==t.kind&&k(`Inbox notification with ID "${n}" is not of kind "thread"`),e.threadsDB.get(t.threadId)??k(`Thread with ID "${t.threadId}" not found, this inbox notification might not be of kind "thread"`)}),[n]);return an.exports.useSyncExternalStoreWithSelector(r.subscribe,o,o,a)}(Gn(),e)},or=function(e){return $n(Gn(),e)},ar=class extends Error{constructor(e,t){super("Create thread failed."),this.cause=e,this.context=t,this.name="CreateThreadError"}},ir=class extends Error{constructor(e,t){super("Mark thread as resolved failed."),this.cause=e,this.context=t,this.name="MarkThreadAsResolvedError"}},sr=class extends Error{constructor(e,t){super("Mark thread as unresolved failed."),this.cause=e,this.context=t,this.name="MarkThreadAsUnresolvedError"}},ur=class extends Error{constructor(e,t){super("Create comment failed."),this.cause=e,this.context=t,this.name="CreateCommentError"}},cr=class extends Error{constructor(e,t){super("Edit comment failed."),this.cause=e,this.context=t,this.name="EditCommentError"}},lr=class extends Error{constructor(e,t){super("Delete comment failed."),this.cause=e,this.context=t,this.name="DeleteCommentError"}},dr=class extends Error{constructor(e,t){super("Add reaction failed."),this.cause=e,this.context=t,this.name="AddReactionError"}},fr=class extends Error{constructor(e,t){super("Remove reaction failed."),this.cause=e,this.context=t,this.name="RemoveReactionError"}},hr=class extends Error{constructor(e,t){super("Mark inbox notification as read failed."),this.cause=e,this.context=t,this.name="MarkInboxNotificationAsReadError"}};function pr(e,t){i.useEffect((()=>{!function(e,t){if(!1===e)return;if(!t.threads)return;if("undefined"==typeof window)return;const n=window.location.hash.slice(1);if(!n.startsWith("cm_"))return;const r=document.getElementById(n);if(null===r)return;t.threads.flatMap((e=>e.comments)).some((e=>e.id===n))&&r.scrollIntoView()}(e,t)}),[t.isLoading])}var mr=e=>e;function vr(){return null}function gr(e){const t=e.getSelf();return null===t||void 0===t.id?"anonymous":t.id}function yr(e){const t=`Request failed with status ${e.status}: ${e.message}`;if("FORBIDDEN"===e.details?.error){const n=[t,e.details.suggestion,e.details.docs].filter(Boolean).join("\n");w.error(n)}return new Error(t)}Object.freeze([]);var br=new WeakMap;function Er(e){let t=br.get(e);return t||(t=function(e){const t=Hn(e),n=E();function r(e,r,o){if(t.removeOptimisticUpdate(r),e instanceof we){const t=yr(e);n.notify(o(t))}else{if(!(e instanceof we))throw e;yr(e)}}const o=new Map,a=new Map,i=new Map;function s(e){let n=o.get(e);return n||(n=Gt((async n=>{try{return await t.fetchRoomThreadsDeltaUpdate(e,n)}catch(t){throw w.warn(`Polling new threads for '${e}' failed: ${String(t)}`),t}}),ln.ROOM_THREADS_POLL_INTERVAL,{maxStaleTimeMs:ln.ROOM_THREADS_MAX_STALE_TIME}),o.set(e,n)),n}function u(e){let n=a.get(e);return n||(n=Gt((async n=>{try{return await t.fetchRoomVersionsDeltaUpdate(e,n)}catch(t){throw w.warn(`Polling new history versions for '${e}' failed: ${String(t)}`),t}}),ln.HISTORY_VERSIONS_POLL_INTERVAL,{maxStaleTimeMs:ln.HISTORY_VERSIONS_MAX_STALE_TIME}),a.set(e,n)),n}function c(e){let n=i.get(e);return n||(n=Gt((async n=>{try{return await t.refreshRoomNotificationSettings(e,n)}catch(t){throw w.warn(`Polling notification settings for '${e}' failed: ${String(t)}`),t}}),ln.NOTIFICATION_SETTINGS_POLL_INTERVAL,{maxStaleTimeMs:ln.NOTIFICATION_SETTINGS_MAX_STALE_TIME}),i.set(e,n)),n}return{store:t,commentsErrorEventSource:n.observable,onMutationFailure:r,getOrCreateThreadsPollerForRoomId:s,getOrCreateVersionsPollerForRoomId:u,getOrCreateNotificationsSettingsPollerForRoomId:c}}(e),br.set(e,t)),t}function wr(e){const t=Gn(),{id:n,stableEnterRoom:r}=e,o=hn({initialPresence:e.initialPresence,initialStorage:e.initialStorage,unstable_batchedUpdates:e.unstable_batchedUpdates,autoConnect:e.autoConnect??"undefined"!=typeof window}),[{room:a},s]=i.useState((()=>r(n,{...o,autoConnect:!1})));return i.useEffect((()=>{const{store:e}=Er(t);return a.events.comments.subscribe((t=>{!async function(t){if(t.type===H.THREAD_DELETED)return void e.deleteThread(t.threadId,null);const n=await a.getThread(t.threadId);if(!n.thread)return void e.deleteThread(t.threadId,null);const{thread:r,inboxNotification:o}=n,i=e.getFullState().threadsDB.getEvenIfDeleted(t.threadId);switch(t.type){case H.COMMENT_EDITED:case H.THREAD_METADATA_UPDATED:case H.THREAD_UPDATED:case H.COMMENT_REACTION_ADDED:case H.COMMENT_REACTION_REMOVED:case H.COMMENT_DELETED:if(!i)break;e.updateThreadAndNotification(r,o);break;case H.COMMENT_CREATED:e.updateThreadAndNotification(r,o)}}(t)}))}),[t,a]),i.useEffect((()=>{const e=r(n,o);s(e);const{room:t,leave:a}=e;return o.autoConnect&&t.connect(),()=>{a()}}),[n,o,r]),i.createElement(un.Provider,{value:a},e.children)}function Cr(){const e=cn();if(null===e)throw new Error("RoomProvider is missing from the React tree.");return e}function Dr(){const e=Gn(),t=Cr();return i.useCallback((({threadId:n,commentId:r,body:o,attachments:a})=>{const i=new Date,{store:s,onMutationFailure:u}=Er(e),c=s.getFullState().threadsDB.getEvenIfDeleted(n);if(void 0===c)return void w.warn(`Internal unexpected behavior. Cannot edit comment in thread "${n}" because the thread does not exist in the cache.`);const l=c.comments.find((e=>e.id===r));if(void 0===l||void 0!==l.deletedAt)return void w.warn(`Internal unexpected behavior. Cannot edit comment "${r}" in thread "${n}" because the comment does not exist in the cache.`);const d=s.addOptimisticUpdate({type:"edit-comment",comment:{...l,editedAt:i,body:o,attachments:a??[]}}),f=a?.map((e=>e.id));t.editComment({threadId:n,commentId:r,body:o,attachmentIds:f}).then((e=>{s.editComment(n,d,e)}),(e=>u(e,d,(e=>new cr(e,{roomId:t.id,threadId:n,commentId:r,body:o})))))}),[e,t])}function xr(){const e=Gn(),t=Cr();return i.useCallback((({threadId:n,commentId:r,emoji:o})=>{const a=gr(t),i=new Date,{store:s,onMutationFailure:u}=Er(e),c=s.addOptimisticUpdate({type:"remove-reaction",threadId:n,commentId:r,emoji:o,userId:a,removedAt:i});t.removeReaction({threadId:n,commentId:r,emoji:o}).then((()=>{s.removeReaction(n,c,r,o,a,i)}),(e=>u(e,c,(e=>new fr(e,{roomId:t.id,threadId:n,commentId:r,emoji:o})))))}),[e,t])}function Ar(e){return void 0===e||e?.isLoading?e??{isLoading:!0}:e.error?e:(e.data,{isLoading:!1,url:e.data})}function _r(e){const t=Cr(),{attachmentUrlsStore:n}=t[de],r=i.useCallback((()=>n.getState(e)),[n,e]);return i.useEffect((()=>{n.get(e)}),[n,e]),an.exports.useSyncExternalStoreWithSelector(n.subscribe,r,r,Ar,Zt)}var Br=function(e){const t=Gn(),[n]=i.useState((()=>new Map)),r=i.useCallback(((e,r)=>{const o=n.get(e);if(o)return o;const a=t.enterRoom(e,r),i=a.leave;return a.leave=()=>{i(),n.delete(e)},n.set(e,a),a}),[t,n]);return i.createElement(wr,{...e,stableEnterRoom:r})},Or=Cr,Sr=function(){return null!==cn()},Tr=function(){const e=Gn(),t=Cr();return i.useCallback((({threadId:n,commentId:r,emoji:o})=>{const a=new Date,i=gr(t),{store:s,onMutationFailure:u}=Er(e),c=s.addOptimisticUpdate({type:"add-reaction",threadId:n,commentId:r,reaction:{emoji:o,userId:i,createdAt:a}});t.addReaction({threadId:n,commentId:r,emoji:o}).then((e=>{s.addReaction(n,c,r,e,a)}),(e=>u(e,c,(e=>new dr(e,{roomId:t.id,threadId:n,commentId:r,emoji:o})))))}),[e,t])},kr=function(){const e=Gn(),t=Cr();return i.useCallback((n=>{const r=n.body,o=n.metadata??{},a=n.attachments,i=bt(),s=Et(),u=new Date,c={id:s,threadId:i,roomId:t.id,createdAt:u,type:"comment",userId:gr(t),body:r,reactions:[],attachments:a??[]},l={id:i,type:"thread",createdAt:u,updatedAt:u,roomId:t.id,metadata:o,comments:[c],resolved:!1},{store:d,onMutationFailure:f}=Er(e),h=d.addOptimisticUpdate({type:"create-thread",thread:l,roomId:t.id}),p=a?.map((e=>e.id));return t.createThread({threadId:i,commentId:s,body:r,metadata:o,attachmentIds:p}).then((e=>{d.createThread(h,e)}),(e=>f(e,h,(e=>new ar(e,{roomId:t.id,threadId:i,commentId:s,body:r,metadata:o}))))),l}),[e,t])},Ir=function(e={query:{metadata:{}}}){const t=Gn(),n=Cr(),{store:r}=Er(t);mn(r.waitUntilRoomThreadsLoaded(n.id,e.query));const o=function(e={query:{metadata:{}}}){const{scrollOnLoad:t=!0}=e,n=Gn(),r=Cr(),{store:o,getOrCreateThreadsPollerForRoomId:a}=Er(n),s=a(r.id);i.useEffect((()=>{o.waitUntilRoomThreadsLoaded(r.id,e.query)})),i.useEffect((()=>(s.inc(),s.pollNowIfStale(),()=>s.dec())),[s]);const u=i.useCallback((()=>o.getRoomThreadsLoadingState(r.id,e.query)),[o,r.id,e.query]),c=an.exports.useSyncExternalStoreWithSelector(o.subscribe,u,u,mr,dn);return pr(t,c),c}(e);return o.error,o.isLoading,o};function Fr(...e){return function(e,t){const n=Cr(),r=n.events.self.subscribe,o=n.getSelf,a=e??mr,s=i.useCallback((e=>null!==e?a(e):null),[a]),u=vr;return an.exports.useSyncExternalStoreWithSelector(r,o,u,s,t)}(...e)}function Rr(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),!1===n||!r.defaultPrevented)return t?.(r)}}function Nr(e){const t=i.useRef(e);return i.useEffect((()=>{t.current=e})),i.useMemo((()=>(...e)=>t.current?.(...e)),[])}function Pr({prop:e,defaultProp:t,onChange:n=(()=>{})}){const[r,o]=function({defaultProp:e,onChange:t}){const n=i.useState(e),[r]=n,o=i.useRef(r),a=Nr(t);return i.useEffect((()=>{o.current!==r&&(a(r),o.current=r)}),[r,o,a]),n}({defaultProp:t,onChange:n}),a=void 0!==e,s=a?e:r,u=Nr(n);return[s,i.useCallback((t=>{if(a){const n=t,r="function"==typeof t?n(e):t;r!==e&&u(r)}else o(t)}),[a,e,o,u])]}function Mr(...e){return t=>e.forEach((e=>function(e,t){"function"==typeof e?e(t):null!=e&&(e.current=t)}(e,t)))}function jr(...e){return i.useCallback(Mr(...e),e)}m(Yt,Jt,"esm");var Lr,zr={exports:{}},Hr={};!function(e){e.exports=function(){if(Lr)return Hr;Lr=1;var e=s.default,t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,a={key:!0,ref:!0,__self:!0,__source:!0};function i(e,n,i){var s,u={},c=null,l=null;for(s in void 0!==i&&(c=""+i),void 0!==n.key&&(c=""+n.key),void 0!==n.ref&&(l=n.ref),n)r.call(n,s)&&!a.hasOwnProperty(s)&&(u[s]=n[s]);if(e&&e.defaultProps)for(s in n=e.defaultProps)void 0===u[s]&&(u[s]=n[s]);return{$$typeof:t,type:e,key:c,ref:l,props:u,_owner:o.current}}return Hr.Fragment=n,Hr.jsx=i,Hr.jsxs=i,Hr}()}(zr);var Ur=i.forwardRef(((e,t)=>{const{children:n,...r}=e,o=i.Children.toArray(n),a=o.find($r);if(a){const e=a.props.children,n=o.map((t=>t===a?i.Children.count(e)>1?i.Children.only(null):i.isValidElement(e)?e.props.children:null:t));return zr.exports.jsx(Wr,{...r,ref:t,children:i.isValidElement(e)?i.cloneElement(e,void 0,n):null})}return zr.exports.jsx(Wr,{...r,ref:t,children:n})}));Ur.displayName="Slot";var Wr=i.forwardRef(((e,t)=>{const{children:n,...r}=e;if(i.isValidElement(n)){const e=function(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;if(n)return e.ref;if(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n)return e.props.ref;return e.props.ref||e.ref}(n);return i.cloneElement(n,{...Kr(r,n.props),ref:t?Mr(t,e):e})}return i.Children.count(n)>1?i.Children.only(null):null}));Wr.displayName="SlotClone";var Vr=({children:e})=>zr.exports.jsx(zr.exports.Fragment,{children:e});function $r(e){return i.isValidElement(e)&&e.type===Vr}function Kr(e,t){const n={...t};for(const r in t){const o=e[r],a=t[r];/^on[A-Z]/.test(r)?o&&a?n[r]=(...e)=>{a(...e),o(...e)}:o&&(n[r]=o):"style"===r?n[r]={...o,...a}:"className"===r&&(n[r]=[o,a].filter(Boolean).join(" "))}return{...e,...n}}var qr=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"].reduce(((e,t)=>{const n=i.forwardRef(((e,n)=>{const{asChild:r,...o}=e,a=r?Ur:t;return"undefined"!=typeof window&&(window[Symbol.for("radix-ui")]=!0),zr.exports.jsx(a,{...o,ref:n})}));return n.displayName=`Primitive.${t}`,{...e,[t]:n}}),{});function Gr(e,t){e&&u.flushSync((()=>e.dispatchEvent(t)))}var Zr=i.forwardRef(((e,t)=>{const{pressed:n,defaultPressed:r=!1,onPressedChange:o,...a}=e,[i=!1,s]=Pr({prop:n,onChange:o,defaultProp:r});return zr.exports.jsx(qr.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...a,ref:t,onClick:Rr(e.onClick,(()=>{e.disabled||s(!i)}))})}));Zr.displayName="Toggle";var Xr=Zr;function Yr(...e){return e.filter((e=>"string"==typeof e||"number"==typeof e)).join(" ")}function Jr({children:e,className:t,...n}){return s.default.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:20,height:20,viewBox:"0 0 20 20",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",role:"presentation",className:Yr("lb-icon",t),...n},e)}function Qr(e){return s.default.createElement(Jr,{...e},s.default.createElement("path",{d:"M16 6L8 14L4 10"}))}function eo(e){return s.default.createElement(Jr,{...e},s.default.createElement("path",{d:"M15 5L5 15"}),s.default.createElement("path",{d:"M5 5L15 15"}))}function to(e){return s.default.createElement(Jr,{...e},s.default.createElement("path",{d:"M4.5 6.5h11M14 6.5V14a1.5 1.5 0 0 1-1.5 1.5h-5A1.5 1.5 0 0 1 6 14V6.5M7.5 6.5V5a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1.5"}))}function no(e){return s.default.createElement(Jr,{...e},s.default.createElement("path",{d:"m11.784 5.797-6.13 6.138a4 4 0 0 0-1.03 1.775L4 16l2.285-.624a4 4 0 0 0 1.776-1.032l6.145-6.152m-2.422-2.395 1.244-1.246c.608-.608 1.826-.81 2.53-.104.7.7.499 1.893-.122 2.515l-1.23 1.23m-2.422-2.395 2.422 2.395"}))}function ro(e){return s.default.createElement(Jr,{fill:"currentColor",...e},s.default.createElement("circle",{cx:5,cy:10,r:.75}),s.default.createElement("circle",{cx:10,cy:10,r:.75}),s.default.createElement("circle",{cx:15,cy:10,r:.75}))}function oo(e){return s.default.createElement(Jr,{...e},s.default.createElement("path",{d:"M11 3.07A7 7 0 1 0 16.93 9"}),s.default.createElement("path",{d:"M7.5 11.5S8.25 13 10 13s2.5-1.5 2.5-1.5M8 8h0"}),s.default.createElement("path",{d:"M12 8h0"}),s.default.createElement("path",{d:"M13 5h4m-2-2v4"}),s.default.createElement("circle",{cx:"8",cy:"8",r:".25"}),s.default.createElement("circle",{cx:"12",cy:"8",r:".25"}))}const ao="'Apple Color Emoji', 'Noto Color Emoji', 'Twemoji Mozilla', 'Android Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', EmojiSymbols, sans-serif",io=t.forwardRef((({emoji:e,style:t,asChild:n,...r},o)=>{const a=n?Ur:"span";return s.default.createElement(a,{role:"img","aria-label":e,"data-emoji":e,style:{...t,fontFamily:ao,display:"inline-flex",alignItems:"center",justifyContent:"center",width:"1em",whiteSpace:"nowrap"},...r,ref:o},e)})),so=t.forwardRef((({className:e,...t},n)=>s.default.createElement(io,{className:Yr("lb-emoji",e),...t,ref:n})));function uo(e,t,n){return 1===e?t:n??`${t}s`}const co={locale:"en",dir:"ltr",USER_SELF:"you",USER_UNKNOWN:"Anonymous",LIST_REMAINING:e=>`${e} more`,LIST_REMAINING_USERS:e=>`${e} ${uo(e,"other")}`,LIST_REMAINING_COMMENTS:e=>`${e} more ${uo(e,"comment")}`,EMOJI_PICKER_SEARCH_PLACEHOLDER:"Search…",EMOJI_PICKER_EMPTY:"No emoji found.",EMOJI_PICKER_ERROR:()=>"There was an error while getting the list of emoji.",ATTACHMENT_TOO_LARGE:e=>e?`The file is larger than ${e}`:"The file is too large",ATTACHMENT_ERROR:()=>"The file couldn’t be uploaded.",COMPOSER_INSERT_MENTION:"Mention someone",COMPOSER_INSERT_EMOJI:"Add emoji",COMPOSER_ATTACH_FILES:"Attach files",COMPOSER_REMOVE_ATTACHMENT:"Remove attachment",COMPOSER_PLACEHOLDER:"Write a comment…",COMPOSER_SEND:"Send",COMMENT_EDITED:"(edited)",COMMENT_DELETED:"This comment has been deleted.",COMMENT_MORE:"More",COMMENT_EDIT:"Edit comment",COMMENT_EDIT_COMPOSER_PLACEHOLDER:"Edit comment…",COMMENT_EDIT_COMPOSER_CANCEL:"Cancel",COMMENT_EDIT_COMPOSER_SAVE:"Save",COMMENT_DELETE:"Delete comment",COMMENT_DELETE_ATTACHMENT:"Delete attachment",COMMENT_ADD_REACTION:"Add reaction",COMMENT_REACTION_LIST:(e,t)=>i.createElement(i.Fragment,null,e," reacted with ",i.createElement(so,{emoji:t})),COMMENT_REACTION_DESCRIPTION:(e,t)=>`${t} ${uo(t,"reaction")}, react with ${e}`,THREAD_RESOLVE:"Resolve thread",THREAD_UNRESOLVE:"Re-open thread",THREAD_NEW_INDICATOR:"New",THREAD_NEW_INDICATOR_DESCRIPTION:"New comments",THREAD_COMPOSER_PLACEHOLDER:"Reply to thread…",THREAD_COMPOSER_SEND:"Reply",INBOX_NOTIFICATION_MORE:"More",INBOX_NOTIFICATION_MARK_AS_READ:"Mark as read",INBOX_NOTIFICATION_DELETE:"Delete notification",INBOX_NOTIFICATION_THREAD_COMMENTS_LIST:(e,t)=>i.createElement(i.Fragment,null,e," commented",t?i.createElement(i.Fragment,null," in ",t):i.createElement(i.Fragment,null," in a thread")),INBOX_NOTIFICATION_THREAD_MENTION:(e,t)=>i.createElement(i.Fragment,null,e," mentioned you",t?i.createElement(i.Fragment,null," in ",t):null),INBOX_NOTIFICATION_TEXT_MENTION:(e,t)=>i.createElement(i.Fragment,null,e," mentioned you",t?i.createElement(i.Fragment,null," in ",t):null),HISTORY_VERSION_PREVIEW_AUTHORS_LIST:e=>i.createElement(i.Fragment,null,"Edits from ",e),HISTORY_VERSION_PREVIEW_RESTORE:"Restore",HISTORY_VERSION_PREVIEW_EMPTY:"No content.",HISTORY_VERSION_PREVIEW_ERROR:()=>"There was an error while getting this version."},lo=t.createContext(void 0);function fo(e){const n=t.useContext(lo);return t.useMemo((()=>({...co,...n,...e})),[n,e])}
|
|
2
2
|
/*!
|
|
3
3
|
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
|
|
4
4
|
*
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@steedos-widgets/liveblocks",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "6.3.12-beta.
|
|
4
|
+
"version": "6.3.12-beta.30",
|
|
5
5
|
"main": "dist/liveblocks.cjs.js",
|
|
6
6
|
"module": "dist/liveblocks.esm.js",
|
|
7
7
|
"unpkg": "dist/liveblocks.umd.js",
|
|
@@ -55,9 +55,9 @@
|
|
|
55
55
|
"@liveblocks/react": "2.12.0",
|
|
56
56
|
"@liveblocks/react-ui": "2.12.0",
|
|
57
57
|
"@rollup/plugin-replace": "^5.0.2",
|
|
58
|
-
"@steedos-widgets/amis-lib": "6.3.12-beta.
|
|
58
|
+
"@steedos-widgets/amis-lib": "6.3.12-beta.30",
|
|
59
59
|
"emojibase-data": "^16.0.2",
|
|
60
60
|
"react-error-boundary": "^4.1.2"
|
|
61
61
|
},
|
|
62
|
-
"gitHead": "
|
|
62
|
+
"gitHead": "4d14d7a6192e0d236f503072aa0ebb5374fc9563"
|
|
63
63
|
}
|