@unhingged/vizu-core 0.1.0 → 0.1.1
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/auto.cjs +62 -4
- package/dist/auto.cjs.map +1 -1
- package/dist/auto.js +62 -4
- package/dist/auto.js.map +1 -1
- package/dist/index.cjs +62 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +29 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.js +62 -4
- package/dist/index.js.map +1 -1
- package/dist/vizu.min.js +11 -11
- package/dist/vizu.min.js.map +1 -1
- package/package.json +1 -1
package/dist/vizu.min.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var VIZU=(()=>{var
|
|
1
|
+
"use strict";var VIZU=(()=>{var Qr=Object.defineProperty;var Jc=Object.getOwnPropertyDescriptor;var Wc=Object.getOwnPropertyNames;var Gc=Object.prototype.hasOwnProperty;var Bs=n=>{throw TypeError(n)};var Yc=(n,e,t)=>e in n?Qr(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var vn=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ks=(n,e)=>{for(var t in e)Qr(n,t,{get:e[t],enumerable:!0})},Xc=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Wc(e))!Gc.call(n,i)&&i!==t&&Qr(n,i,{get:()=>e[i],enumerable:!(r=Jc(e,i))||r.enumerable});return n};var Zc=n=>Xc(Qr({},"__esModule",{value:!0}),n);var ke=(n,e,t)=>Yc(n,typeof e!="symbol"?e+"":e,t),$i=(n,e,t)=>e.has(n)||Bs("Cannot "+t);var a=(n,e,t)=>($i(n,e,"read from private field"),t?t.call(n):e.get(n)),T=(n,e,t)=>e.has(n)?Bs("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),b=(n,e,t,r)=>($i(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t),S=(n,e,t)=>($i(n,e,"access private method"),t);var yn=(n,e,t,r)=>({set _(i){b(n,e,i,t)},get _(){return a(n,e,r)}});function Xs(n){let e=[],t=n,r=0;for(;t&&t!==document.documentElement&&r<8;){let i=t.tagName.toLowerCase();if(t.id){e.unshift("#"+CSS.escape(t.id));break}let s=Array.from(t.classList).filter(c=>!c.startsWith("vz-")&&!c.startsWith("vizu-")).slice(0,2);s.length&&(i+="."+s.map(c=>CSS.escape(c)).join("."));let o=t.parentElement;if(o){let c=Array.from(o.children).filter(u=>u.tagName===t.tagName);if(c.length>1){let u=c.indexOf(t);i+=":nth-of-type("+(u+1)+")"}}e.unshift(i),t=o,r++}return e.join(" > ")}function Jn(n){let e=n.innerText||n.textContent||"",t=n.parentElement,r=0;return t&&(r=Array.from(t.children).indexOf(n)),{selector:Xs(n),parentSelector:t?Xs(t):"",tagName:n.tagName,textSnippet:e.trim().slice(0,80),siblingIndex:r,attributes:{id:n.id||void 0,classList:Array.from(n.classList).filter(i=>!i.startsWith("vz-")&&!i.startsWith("vizu-")),role:n.getAttribute("role")||void 0,ariaLabel:n.getAttribute("aria-label")||void 0,dataKey:n.getAttribute("data-vizu-key")||void 0},ancestorChain:il(n,4),algorithmVersion:2}}function il(n,e){let t=[],r=n.parentElement;for(;r&&t.length<e;){let i=r.parentElement,s=1;i&&(s=Array.from(i.children).filter(c=>c.tagName===r.tagName).indexOf(r)+1),t.push({tag:r.tagName,nthOfType:s}),r=i}return t.length>0?{steps:t}:void 0}function Wn(n,e=document){if(n.attributes.dataKey){try{let o=e.querySelector(`[data-vizu-key="${CSS.escape(n.attributes.dataKey)}"]`);if(o)return{element:o,confidence:"exact"}}catch{}return{element:null,confidence:"orphaned"}}if(n.attributes.id)try{let o=e.querySelector("#"+CSS.escape(n.attributes.id));if(o)return{element:o,confidence:"exact"}}catch{}let t=[],r=n.attributes.classList;if(r&&r.length>0){let o=sl(e,n.tagName,r);o?.element&&t.push({el:o.element,rung:"class"})}try{let o=e.querySelector(n.selector);o&&t.push({el:o,rung:"selector"})}catch{}if(n.ancestorChain&&n.ancestorChain.steps.length>0){let o=ol(e,n.tagName,n.ancestorChain.steps);o?.element&&t.push({el:o.element,rung:"chain"})}else try{let o=n.parentSelector?e.querySelector(n.parentSelector):e;if(o){let c=o.children[n.siblingIndex];c&&c.tagName===n.tagName&&t.push({el:c,rung:"chain"})}}catch{}if(n.textSnippet){let o=cl(e,n.tagName,n.textSnippet);o?.element&&t.push({el:o.element,rung:"text"})}if(t.length===0)return{element:null,confidence:"orphaned"};let i=new Map;for(let o of t){let c=i.get(o.el);c||(c=new Set,i.set(o.el,c)),c.add(o.rung)}let s=null;for(let[o,c]of i)(!s||c.size>s.rungs.size)&&(s={el:o,rungs:c});return s?s.rungs.size>=3?{element:s.el,confidence:"likely"}:s.rungs.size>=2?{element:s.el,confidence:"drifted"}:s.rungs.has("class")||s.rungs.has("chain")?{element:s.el,confidence:"drifted"}:{element:null,confidence:"orphaned"}:{element:null,confidence:"orphaned"}}function sl(n,e,t){let r=new Set(t.filter(c=>!c.startsWith("vz-")&&!c.startsWith("vizu-")));if(r.size===0)return null;let i=n.querySelectorAll(e.toLowerCase()),s=null,o=0;for(let c of i){let u=new Set(Array.from(c.classList).filter(l=>!l.startsWith("vz-")&&!l.startsWith("vizu-")));if(u.size===0)continue;let h=hl(r,u);h<.6||(!s||h>s.score?(o=s?.score??0,s={el:c,score:h}):h>o&&(o=h))}return!s||s.score-o<.1?null:{element:s.el,confidence:"likely"}}function ol(n,e,t){let r=n.querySelectorAll(e.toLowerCase()),i=null;for(let s of r){let o=al(s,t.length+3),c=ul(o,t,3);c<2||(!i||c>i.score)&&(i={el:s,score:c})}return i?{element:i.el,confidence:i.score===t.length?"likely":"drifted"}:null}function al(n,e){let t=[],r=n.parentElement;for(;r&&t.length<e;){let i=r.parentElement,s=1;i&&(s=Array.from(i.children).filter(c=>c.tagName===r.tagName).indexOf(r)+1),t.push({tag:r.tagName,nthOfType:s}),r=i}return t}function cl(n,e,t){let r=Zs(t);if(!r)return null;let i=n.querySelectorAll(e.toLowerCase()),s=null;for(let o of i){let c=o.innerText||o.textContent||"",u=Zs(c.slice(0,160));if(!u)continue;let h=ll(r,u);h<.75||(!s||h>s.score)&&(s={el:o,score:h})}return s?{element:s.el,confidence:"drifted"}:null}function Zs(n){return n.toLowerCase().replace(/\s+/g," ").trim()}function ll(n,e){if(n===e)return 1;if(n.length===0||e.length===0)return n.length===e.length?1:0;let t=Math.max(n.length,e.length);return 1-dl(n,e)/t}function dl(n,e){if(n.length>e.length){let i=n;n=e,e=i}let t=new Array(n.length+1),r=new Array(n.length+1);for(let i=0;i<=n.length;i++)t[i]=i;for(let i=1;i<=e.length;i++){r[0]=i;for(let s=1;s<=n.length;s++){let o=n.charCodeAt(s-1)===e.charCodeAt(i-1)?0:1;r[s]=Math.min(r[s-1]+1,t[s]+1,t[s-1]+o)}for(let s=0;s<=n.length;s++)t[s]=r[s]}return t[n.length]}function ul(n,e,t){let r=0;for(let i=0;i<=t;i++){let s=0;for(let o=0;o<e.length;o++){let c=n[o+i];if(!c)break;c.tag===e[o].tag&&c.nthOfType===e[o].nthOfType&&s++}s>r&&(r=s)}return r}function hl(n,e){if(n.size===0&&e.size===0)return 1;let t=0;for(let i of n)e.has(i)&&t++;let r=n.size+e.size-t;return r===0?0:t/r}function Gn(n,e){return Wn(n,e).element}function de(n){return n.selector+"|"+n.textSnippet}function Yn(n){let e=n.tagName.toLowerCase();if(n.textSnippet){let t=n.textSnippet.length>24?n.textSnippet.slice(0,24)+"\u2026":n.textSnippet;return e+": "+t}return n.attributes.id?e+"#"+n.attributes.id:n.attributes.classList&&n.attributes.classList.length?e+"."+n.attributes.classList[0]:e}var Xn=vn(()=>{"use strict"});function io(n){if(process.env.NODE_ENV==="production")console.error(n);else throw new Error(n)}function vs(n,e,t){let r=Symbol.for(n),i=t?`${e||"dev"} (${t})`:e||"dev";if(!ci[r])ci[r]=i;else if(ci[r]!==i){let s=[`Multiple copies of Liveblocks are being loaded in your project. This will cause issues! See ${xl+ro}`,"","Conflicts:",`- ${n} ${ci[r]} (already loaded)`,`- ${n} ${i} (trying to load this now)`].join(`
|
|
2
2
|
`);io(s)}e&&ln&&e!==ln&&io([`Cross-linked versions of Liveblocks found, which will cause issues! See ${Cl+ro}`,"","Conflicts:",`- ${Xo} is at ${ln}`,`- ${n} is at ${e}`,"","Always upgrade all Liveblocks packages to the same version number."].join(`
|
|
3
|
-
`))}function ne(){let n=new Set;function e(o){return n.add(o),()=>n.delete(o)}function t(o){let c=e(u=>(c(),o(u)));return c}async function r(o){let c;return new Promise(u=>{c=e(h=>{(o===void 0||o(h))&&u(h)})}).finally(()=>c?.())}function i(o){let c=!1;for(let u of n)u(o),c=!0;return c}function s(){return n.size}return{notify:i,subscribe:e,subscribeOnce:t,count:s,waitUntil:r,dispose(){n.clear()},observable:{subscribe:e,subscribeOnce:t,waitUntil:r}}}function Al(){let n=ne(),e=null;function t(){e=[]}function r(){if(e!==null){for(let s of e)n.notify(s);e=null}}function i(s){return e!==null?(e.push(s),!1):n.notify(s)}return{...n,notify:i,pause:t,unpause:r,dispose(){n.dispose(),e!==null&&(e.length=0)}}}function St(n){throw new Error(n)}function Zo(n){return Object.entries(n)}function Tl(n,e){return typeof e<"u"?Object.create(n,e):Object.create(n)}function Nt(n){try{return JSON.parse(n)}catch{return}}function yr(n){return JSON.parse(JSON.stringify(n))}function kl(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/");return decodeURIComponent(atob(e).split("").map(function(r){return"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)}).join(""))}catch{return atob(n)}}function ns(n){return n.filter(e=>e!=null)}function Si(n){let e={...n};return Object.keys(n).forEach(t=>{let r=t;e[r]===void 0&&delete e[r]}),e}function _l(n){return new Promise(e=>setTimeout(e,n))}async function so(n,e,t){let r,i=new Promise((s,o)=>{r=setTimeout(()=>{o(new Error(t))},e)});return Promise.race([n,i]).finally(()=>clearTimeout(r))}function oo(n){let e=null;return()=>(e===null&&(e=n().catch(t=>{throw setTimeout(()=>{e=null},5e3),t})),e)}function zl(n,e){for(let t=n.length-1;t>=0;t--)if(e(n[t],t,n))return t;return-1}function Il(n,e){let t=[],r=[],i=0;for(let s of n)e(s,i++)?t.push(s):r.push(s);return[t,r]}function dn(n){if(sr!==null){n();return}sr=new Set;try{n()}finally{for(let e of sr)e[gi]();sr=null}}function ys(n){sr||St("Expected to be in an active batch"),sr.add(n)}function Qo(n,e){let t=!1,r={...n};return Object.keys(e).forEach(i=>{let s=i,o=e[s];r[s]!==o&&(o===void 0?delete r[s]:r[s]=o,t=!0)}),t?r:n}function Ll(n,e,t){let r=0,i=n.length;for(;r<i;){let s=r+(i-r>>1);t(e,n[s])?i=s:r=s+1}return r}function is(n){let e=n.editedAt?new Date(n.editedAt):void 0,t=new Date(n.createdAt),r=n.reactions.map(i=>({...i,createdAt:new Date(i.createdAt)}));if(n.body)return{...n,reactions:r,createdAt:t,editedAt:e};{let i=new Date(n.deletedAt);return{...n,reactions:r,createdAt:t,editedAt:e,deletedAt:i}}}function Kt(n){let e=new Date(n.createdAt),t=new Date(n.updatedAt),r=n.comments.map(i=>is(i));return{...n,createdAt:e,updatedAt:t,comments:r}}function Ml(n){return{...n,createdAt:new Date(n.createdAt)}}function Sn(n){let e=new Date(n.notifiedAt),t=n.readAt?new Date(n.readAt):null;if("activities"in n){let r=n.activities.map(i=>({...i,createdAt:new Date(i.createdAt)}));return{...n,notifiedAt:e,readAt:t,activities:r}}return{...n,notifiedAt:e,readAt:t}}function jt(n){let e=new Date(n.createdAt);return{...n,createdAt:e}}function Bi(n){let e=new Date(n.deletedAt);return{...n,deletedAt:e}}function Ki(n){let e=new Date(n.deletedAt);return{...n,deletedAt:e}}function ji(n){let e=new Date(n.deletedAt);return{...n,deletedAt:e}}function ao(n){let e=new Date(n.createdAt),t=new Date(n.updatedAt),r=n.members.map(i=>({...i,addedAt:new Date(i.addedAt)}));return{...n,createdAt:e,updatedAt:t,members:r}}function Re(n,e){throw new Error(e)}function Pl(n,e){if(process.env.NODE_ENV!=="production"&&!n){let t=new Error(e);throw t.name="Assertion failure",t}}function q(n,e="Expected value to be non-nullable"){return Pl(n!=null,e),n}function ta(n){return typeof window>"u"||process.env.NODE_ENV==="test"?console[n]:((e,...t)=>console[n]("%cLiveblocks",ea,e,...t))}function na(n){return typeof window>"u"||process.env.NODE_ENV==="test"?console[n]:((e,t,...r)=>console[n](`%cLiveblocks%c ${e}`,ea,Ul,t,...r))}function Fl(n){return n!=null}function Ce(n){return n!==null&&typeof n=="object"&&Object.prototype.toString.call(n)==="[object Object]"}function co(n){return Ce(n)&&typeof n.startsWith=="string"}function lo(n){return Ce(n)&&(typeof n.lt=="number"||typeof n.gt=="number"||typeof n.lte=="number"||typeof n.gte=="number")}async function qi(n,e,t,r=Vl){let i=t.length>0?t[t.length-1]:0,s=0;for(;;){s++;try{return await n()}catch(c){if(r(c))throw c;if(s>=e)throw new Error(`Failed after ${e} attempts: ${String(c)}`)}let o=t[s-1]??i;xe(`Attempt ${s} was unsuccessful. Retrying in ${o} milliseconds.`),await _l(o)}}function sa(){let n,e;return[new Promise((r,i)=>{n=r,e=i}),n,e]}function ar(){let[n,e,t]=sa();return{promise:n,resolve:e,reject:t}}function Hl(n,e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).sort().reduce((t,r)=>(t[r]=e[r],t),{}):e}function ss(n){return JSON.stringify(n,Hl)}function Un(n){try{return JSON.stringify(n)}catch(e){throw console.error(`Could not stringify: ${e.message}`),console.error(n),e}}function cr(n){let e=new Dr(new Map);function t(l){return ss(l)}function r(l){e.mutate(m=>{if(Array.isArray(l))for(let k of l)m.set(k.key,k.state);else m.set(l.key,l.state)})}function i(l){e.mutate(m=>{if(Array.isArray(l))for(let k of l)m.delete(t(k));else m.clear()})}async function s(l){let m=t(l);if(!e.get().has(m))try{r({key:m,state:{isLoading:!0}});let O=await n.get(l);r({key:m,state:{isLoading:!1,data:O}})}catch(O){r({key:m,state:{isLoading:!1,error:O}})}}function o(l){r(l.map(m=>({key:t(m[0]),state:{isLoading:!1,data:m[1]}})))}function c(l){let m=t(l);return e.get().get(m)}function u(l){let m=t(l);return e.get().get(m)?.data}function h(){return[...e.get().keys()]}return{subscribe:e.subscribe,enqueue:s,setData:o,getItemState:c,getData:u,invalidate:i,batch:n,_cacheKeys:h}}function jl(n,e){let t=[];for(let r=0,i=n.length;r<i;r+=e)t.push(n.slice(r,r+e));return t}function Es(n){return`${n}_${ze()}`}function Gl(){return Es(ql)}function uo(){return Es(Jl)}function Yl(){return Es(Wl)}function Zn(n){let e=[],t=Object.entries(n),r=[],i=[],s=[];return t.forEach(([o,c])=>{if(!Xl.test(o))throw new Error("Key must only contain letters, numbers, _");fo(c)?r.push([o,c]):Ce(c)&&(co(c)||lo(c)?i.push([o,c]):s.push([o,c]))}),e=[...ho(r),...po(i)],s.forEach(([o,c])=>{let u=Object.entries(c),h=[],l=[];u.forEach(([m,k])=>{if(Zl(m))throw new Error("Key cannot be empty");fo(k)?h.push([mo(o,m),k]):(co(k)||lo(k))&&l.push([mo(o,m),k])}),e=[...e,...ho(h),...po(l)]}),e.map(({key:o,operator:c,value:u})=>`${o}${c}${aa(u)}`).join(" ")}function aa(n){let e=JSON.stringify(n);return typeof n!="string"||e.includes("'")?e:`'${e.slice(1,-1).replace(/\\"/g,'"')}'`}function Ql(n){let e=new URLSearchParams;for(let[t,r]of Object.entries(n))r!=null&&e.set(t,r.toString());return e}function ed(n,e,t){let r=new URL(e,n);return t!==void 0&&(r.search=(t instanceof URLSearchParams?t:Ql(t)).toString()),r.toString()}function $(n,...e){return n.reduce((t,r,i)=>t+encodeURIComponent(e[i-1]??"")+r)}function td({baseUrl:n,authManager:e,currentUserId:t,fetchPolyfill:r}){let i=new nd(n,r);async function s(p){let w=await i.get($`/v2/c/rooms/${p.roomId}/threads/delta`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{since:p.since.toISOString()},{signal:p.signal});return{threads:{updated:w.data.map(Kt),deleted:w.deletedThreads.map(Bi)},inboxNotifications:{updated:w.inboxNotifications.map(Sn),deleted:w.deletedInboxNotifications.map(Ki)},subscriptions:{updated:w.subscriptions.map(jt),deleted:w.deletedSubscriptions.map(ji)},requestedAt:new Date(w.meta.requestedAt),permissionHints:w.meta.permissionHints}}async function o(p){let w;p.query&&(w=Zn(p.query));let L=50;try{let N=await i.get($`/v2/c/rooms/${p.roomId}/threads`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{cursor:p.cursor,query:w,limit:L});return{threads:N.data.map(Kt),inboxNotifications:N.inboxNotifications.map(Sn),subscriptions:N.subscriptions.map(jt),nextCursor:N.meta.nextCursor,requestedAt:new Date(N.meta.requestedAt),permissionHints:N.meta.permissionHints}}catch(N){if(N instanceof vi&&N.status===404)return{threads:[],inboxNotifications:[],subscriptions:[],nextCursor:null,requestedAt:new Date(Date.now()-360*60*1e3),permissionHints:{}};throw N}}async function c(p,w){return await i.get($`/v2/c/rooms/${p.roomId}/threads/comments/search`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{text:p.query.text,query:Zn({threadMetadata:p.query.threadMetadata,threadResolved:p.query.threadResolved,hasAttachments:p.query.hasAttachments,hasMentions:p.query.hasMentions})},{signal:w?.signal})}async function u(p){let w=p.commentId??uo(),L=p.threadId??Gl(),N=await i.post($`/v2/c/rooms/${p.roomId}/threads`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{id:L,comment:{id:w,body:p.body,metadata:p.commentMetadata,attachmentIds:p.attachmentIds},metadata:p.metadata});return Kt(N)}async function h(p){await i.delete($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function l(p){let w=await i.rawGet($`/v2/c/rooms/${p.roomId}/thread-with-notification/${p.threadId}`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}));if(w.ok){let L=await w.json();return{thread:Kt(L.thread),inboxNotification:L.inboxNotification?Sn(L.inboxNotification):void 0,subscription:L.subscription?jt(L.subscription):void 0}}else{if(w.status===404)return{thread:void 0,inboxNotification:void 0,subscription:void 0};throw new Error(`There was an error while getting thread ${p.threadId}.`)}}async function m(p){return await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/metadata`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),p.metadata)}async function k(p){return await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/comments/${p.commentId}/metadata`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),p.metadata)}async function O(p){let w=p.commentId??uo(),L=await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/comments`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{id:w,body:p.body,metadata:p.metadata,attachmentIds:p.attachmentIds});return is(L)}async function z(p){let w=await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/comments/${p.commentId}`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{body:p.body,attachmentIds:p.attachmentIds,metadata:p.metadata});return is(w)}async function B(p){await i.delete($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/comments/${p.commentId}`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function J(p){let w=await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/comments/${p.commentId}/reactions`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{emoji:p.emoji});return Ml(w)}async function se(p){await i.delete($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/comments/${p.commentId}/reactions/${p.emoji}`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function _(p){await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/mark-as-resolved`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function P(p){await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/mark-as-unresolved`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function C(p){let w=await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/subscribe`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}));return jt(w)}async function R(p){await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/unsubscribe`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function y(p){let w=p.roomId,L=p.signal,N=p.attachment,be=L?new DOMException(`Upload of attachment ${p.attachment.id} was aborted.`,"AbortError"):void 0;if(L?.aborted)throw be;let pe=ae=>{if(L?.aborted)throw be;if(ae instanceof vi&&ae.status===413)throw ae;return!1},Ie=5*1024*1024,ge=10,Fe=[2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3];function Oe(ae){let Te=[],lt=0;for(;lt<ae.size;){let et=Math.min(lt+Ie,ae.size);Te.push({partNumber:Te.length+1,part:ae.slice(lt,et)}),lt=et}return Te}if(N.size<=Ie)return qi(async()=>i.putBlob($`/v2/c/rooms/${w}/attachments/${N.id}/upload/${encodeURIComponent(N.name)}`,await e.getAuthValue({requestedScope:"comments:read",roomId:w}),N.file,{fileSize:N.size},{signal:L}),ge,Fe,pe);{let ae,Te=[],lt=await qi(async()=>i.post($`/v2/c/rooms/${w}/attachments/${N.id}/multipart/${encodeURIComponent(N.name)}`,await e.getAuthValue({requestedScope:"comments:read",roomId:w}),void 0,{signal:L},{fileSize:N.size}),ge,Fe,pe);try{ae=lt.uploadId;let et=Oe(N.file);if(L?.aborted)throw be;let Wr=jl(et,5);for(let Bn of Wr){let gn=[];for(let{part:Di,partNumber:Mi}of Bn)gn.push(qi(async()=>i.putBlob($`/v2/c/rooms/${w}/attachments/${N.id}/multipart/${lt.uploadId}/${String(Mi)}`,await e.getAuthValue({requestedScope:"comments:read",roomId:w}),Di,void 0,{signal:L}),ge,Fe,pe));Te.push(...await Promise.all(gn))}if(L?.aborted)throw be;let Gr=Te.sort((Bn,gn)=>Bn.partNumber-gn.partNumber);return i.post($`/v2/c/rooms/${w}/attachments/${N.id}/multipart/${ae}/complete`,await e.getAuthValue({requestedScope:"comments:read",roomId:w}),{parts:Gr},{signal:L})}catch(et){if(ae&&et?.name&&(et.name==="AbortError"||et.name==="TimeoutError"))try{await i.rawDelete($`/v2/c/rooms/${w}/attachments/${N.id}/multipart/${ae}`,await e.getAuthValue({requestedScope:"comments:read",roomId:w}))}catch{}throw et}}}let F=new Qe(p=>{let w=new Wt(async L=>{let N=L.flat(),{urls:be}=await i.post($`/v2/c/rooms/${p}/attachments/presigned-urls`,await e.getAuthValue({requestedScope:"comments:read",roomId:p}),{attachmentIds:N});return be.map(pe=>pe??new Error("There was an error while getting this attachment's URL"))},{delay:50});return cr(w)});function G(p){return F.getOrCreate(p)}function oe(p){return G(p.roomId).batch.get(p.attachmentId)}async function re(p){let{chatId:w,attachment:L,signal:N}=p;if(t.get()===void 0)throw new Error("Attachment upload requires an authenticated user.");let pe=5*1024*1024;if(p.attachment.file.size<=pe)await i.putBlob($`/v2/c/chats/${w}/attachments/${L.id}/upload/${encodeURIComponent(L.file.name)}`,await e.getAuthValue({requestedScope:"comments:read"}),L.file,{fileSize:L.file.size},{signal:N});else{let Ie=await i.post($`/v2/c/chats/${w}/attachments/${L.id}/multipart/${encodeURIComponent(L.file.name)}`,await e.getAuthValue({requestedScope:"comments:read"}),void 0,{signal:N},{fileSize:L.file.size});try{let ge=[],Fe=[],Oe=0;for(;Oe<L.file.size;){let ae=Math.min(Oe+pe,L.file.size);Fe.push({number:Fe.length+1,part:L.file.slice(Oe,ae)}),Oe=ae}ge.push(...await Promise.all(Fe.map(async({number:ae,part:Te})=>await i.putBlob($`/v2/c/chats/${w}/attachments/${L.id}/multipart/${Ie.uploadId}/${String(ae)}`,await e.getAuthValue({requestedScope:"comments:read"}),Te,void 0,{signal:N})))),await i.post($`/v2/c/chats/${w}/attachments/${L.id}/multipart/${Ie.uploadId}/complete`,await e.getAuthValue({requestedScope:"comments:read"}),{parts:ge.sort((ae,Te)=>ae.number-Te.number)},{signal:N})}catch(ge){try{await i.delete($`/v2/c/chats/${w}/attachments/${L.id}/multipart/${Ie.uploadId}`,await e.getAuthValue({requestedScope:"comments:read"}))}catch{}throw ge}}}let Q=new Qe(p=>{let w=new Wt(async L=>{let N=L.flat(),{urls:be}=await i.post($`/v2/c/chats/${p}/attachments/presigned-urls`,await e.getAuthValue({requestedScope:"comments:read"}),{attachmentIds:N});return be.map(pe=>pe??new Error("There was an error while getting this attachment's URL"))},{delay:50});return cr(w)});function me(p){return Q.getOrCreate(p)}function Ne(p){return me(p.chatId).batch.get(p.attachmentId)}async function U(p){return i.get($`/v2/c/rooms/${p.roomId}/subscription-settings`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),void 0,{signal:p.signal})}async function A(p){return i.post($`/v2/c/rooms/${p.roomId}/subscription-settings`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),p.settings)}let j=new Qe(p=>new Wt(async w=>{let L=w.flat();return await i.post($`/v2/c/rooms/${p}/inbox-notifications/read`,await e.getAuthValue({requestedScope:"comments:read",roomId:p}),{inboxNotificationIds:L}),L},{delay:50}));async function Y(p){return j.getOrCreate(p.roomId).get(p.inboxNotificationId)}async function te(p){if(p.mention.kind!=="user"&&p.mention.kind!=="group")return Re(p.mention,"Unexpected mention kind");await i.rawPost($`/v2/c/rooms/${p.roomId}/text-mentions`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{userId:p.mention.kind==="user"?p.mention.id:void 0,groupId:p.mention.kind==="group"?p.mention.id:void 0,userIds:p.mention.kind==="group"?p.mention.userIds:void 0,mentionId:p.mentionId})}async function Ae(p){await i.rawDelete($`/v2/c/rooms/${p.roomId}/text-mentions/${p.mentionId}`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function De(p){return i.rawGet($`/v2/c/rooms/${p.roomId}/y-version/${p.versionId}`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function qe(p){await i.rawPost($`/v2/c/rooms/${p.roomId}/version`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function Vt(p){await i.rawPost($`/v2/c/rooms/${p.roomId}/text-metadata`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{type:p.type,rootKey:p.rootKey})}async function Ue(p){let w=await i.post($`/v2/c/rooms/${p.roomId}/ai/contextual-prompt`,await e.getAuthValue({requestedScope:"room:read",roomId:p.roomId}),{prompt:p.prompt,context:{beforeSelection:p.context.beforeSelection,selection:p.context.selection,afterSelection:p.context.afterSelection},previous:p.previous},{signal:p.signal});if(!w||w.content.length===0)throw new Error("No content returned from server");return w.content[0].text}async function M(p){let w=await i.get($`/v2/c/rooms/${p.roomId}/versions`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}));return{versions:w.versions.map(({createdAt:L,...N})=>({createdAt:new Date(L),...N})),requestedAt:new Date(w.meta.requestedAt)}}async function X(p){let w=await i.get($`/v2/c/rooms/${p.roomId}/versions/delta`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{since:p.since.toISOString()},{signal:p.signal});return{versions:w.versions.map(({createdAt:L,...N})=>({createdAt:new Date(L),...N})),requestedAt:new Date(w.meta.requestedAt)}}async function ue(p){return await(await i.rawGet($`/v2/c/rooms/${p.roomId}/storage`,await e.getAuthValue({requestedScope:"room:read",roomId:p.roomId}))).json()}async function Me(p){let L;p?.query&&(L=Zn(p.query));let N=await i.get($`/v2/c/inbox-notifications`,await e.getAuthValue({requestedScope:"comments:read"}),{cursor:p?.cursor,limit:50,query:L}),be=N.groups.map(ao);return wr.setData(be.map(pe=>[pe.id,pe])),{inboxNotifications:N.inboxNotifications.map(Sn),threads:N.threads.map(Kt),subscriptions:N.subscriptions.map(jt),nextCursor:N.meta.nextCursor,requestedAt:new Date(N.meta.requestedAt)}}async function ct(p){let w;p?.query&&(w=Zn(p.query));let L=await i.get($`/v2/c/inbox-notifications/delta`,await e.getAuthValue({requestedScope:"comments:read"}),{since:p.since.toISOString(),query:w},{signal:p.signal});return{inboxNotifications:{updated:L.inboxNotifications.map(Sn),deleted:L.deletedInboxNotifications.map(Ki)},threads:{updated:L.threads.map(Kt),deleted:L.deletedThreads.map(Bi)},subscriptions:{updated:L.subscriptions.map(jt),deleted:L.deletedSubscriptions.map(ji)},requestedAt:new Date(L.meta.requestedAt)}}async function Je(p){let w;p?.query&&(w=Zn(p.query));let{count:L}=await i.get($`/v2/c/inbox-notifications/count`,await e.getAuthValue({requestedScope:"comments:read"}),{query:w},{signal:p?.signal});return L}async function Ht(){await i.post($`/v2/c/inbox-notifications/read`,await e.getAuthValue({requestedScope:"comments:read"}),{inboxNotificationIds:"all"})}async function fn(p){await i.post($`/v2/c/inbox-notifications/read`,await e.getAuthValue({requestedScope:"comments:read"}),{inboxNotificationIds:p})}let Hn=new Wt(async p=>{let w=p.flat();return await fn(w),w},{delay:50});async function Er(p){await Hn.get(p)}async function mn(){await i.delete($`/v2/c/inbox-notifications`,await e.getAuthValue({requestedScope:"comments:read"}))}async function Bt(p){await i.delete($`/v2/c/inbox-notifications/${p}`,await e.getAuthValue({requestedScope:"comments:read"}))}async function Ii(p){return i.get($`/v2/c/notification-settings`,await e.getAuthValue({requestedScope:"comments:read"}),void 0,{signal:p?.signal})}async function qr(p){return i.post($`/v2/c/notification-settings`,await e.getAuthValue({requestedScope:"comments:read"}),p)}async function Oi(p){let w;p?.query&&(w=Zn(p.query));let N=await i.get($`/v2/c/threads`,await e.getAuthValue({requestedScope:"comments:read"}),{cursor:p?.cursor,query:w,limit:50});return{threads:N.threads.map(Kt),inboxNotifications:N.inboxNotifications.map(Sn),subscriptions:N.subscriptions.map(jt),nextCursor:N.meta.nextCursor,requestedAt:new Date(N.meta.requestedAt),permissionHints:N.meta.permissionHints}}async function Ri(p){let w=await i.get($`/v2/c/threads/delta`,await e.getAuthValue({requestedScope:"comments:read"}),{since:p.since.toISOString()},{signal:p.signal});return{threads:{updated:w.threads.map(Kt),deleted:w.deletedThreads.map(Bi)},inboxNotifications:{updated:w.inboxNotifications.map(Sn),deleted:w.deletedInboxNotifications.map(Ki)},subscriptions:{updated:w.subscriptions.map(jt),deleted:w.deletedSubscriptions.map(ji)},requestedAt:new Date(w.meta.requestedAt),permissionHints:w.meta.permissionHints}}let Jr=new Wt(async p=>{let w=p.flat(),{groups:L}=await i.post($`/v2/c/groups/find`,await e.getAuthValue({requestedScope:"comments:read"}),{groupIds:w}),N=new Map;for(let be of L)N.set(be.id,ao(be));return w.map(be=>N.get(be))},{delay:50}),wr=cr(Jr);function fe(p){return Jr.get(p)}async function Li(p){let{metadata:w}=await i.get($`/v2/c/urls/metadata`,await e.getAuthValue({requestedScope:"comments:read"}),{url:p});return w}return{getThreads:o,getThreadsSince:s,searchComments:c,createThread:u,getThread:l,deleteThread:h,editThreadMetadata:m,createComment:O,editComment:z,editCommentMetadata:k,deleteComment:B,addReaction:J,removeReaction:se,markThreadAsResolved:_,markThreadAsUnresolved:P,subscribeToThread:C,unsubscribeFromThread:R,markRoomInboxNotificationAsRead:Y,getSubscriptionSettings:U,updateSubscriptionSettings:A,createTextMention:te,deleteTextMention:Ae,getTextVersion:De,createTextVersion:qe,reportTextEditor:Vt,listTextVersions:M,listTextVersionsSince:X,getAttachmentUrl:oe,uploadAttachment:y,getOrCreateAttachmentUrlsStore:G,uploadChatAttachment:re,getOrCreateChatAttachmentUrlsStore:me,getChatAttachmentUrl:Ne,streamStorage:ue,getInboxNotifications:Me,getInboxNotificationsSince:ct,getUnreadInboxNotificationsCount:Je,markAllInboxNotificationsAsRead:Ht,markInboxNotificationAsRead:Er,deleteAllInboxNotifications:mn,deleteInboxNotification:Bt,getNotificationSettings:Ii,updateNotificationSettings:qr,getUserThreads_experimental:Oi,getUserThreadsSince_experimental:Ri,groupsStore:wr,getGroup:fe,executeContextualPrompt:Ue,getUrlMetadata:Li}}function ws(n){return n.type==="public"?n.publicApiKey:n.token.raw}function rd(n,e){if(n===e)return[0,0];let t=n.split("."),r=e.split("."),i=Math.min(t.length,r.length),s=0;for(;s<i&&t[s]===r[s];s++);let o=t.length-s,c=r.length-s;return[o,c]}function id(n,e){let t=n.split(".");if(e<1||e>t.length+1)throw new Error("Invalid number of levels");let r=[];e>t.length&&r.push("*");for(let i=t.length-e+1;i<t.length;i++){let s=t.slice(0,i);s.length>0&&r.push(s.join(".")+".*")}return r.push(n),r}function go(n){return n===4999||n>=4e3&&n<4100}function cd(n){return n>=4100&&n<4200}function vo(n){return n===1013||n>=4200&&n<4300}function ld(n){return n==="initial"||n==="disconnected"}function ua(n){let e=n.currentState;switch(e){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 n.context.successCount>0?"reconnecting":"connecting";case"@idle.failed":return"disconnected";default:return Re(e,"Unknown state")}}function pa(n,e){return e.find(t=>t>n)??e[e.length-1]}function Qn(n){n.patch({backoffDelay:pa(n.backoffDelay,ha)})}function yo(n){n.patch({backoffDelay:pa(n.backoffDelay,dd)})}function bo(n){n.patch({successCount:0})}function nr(n,e){let t=n===2?wt:n===1?xe:(()=>{});return()=>{t(e)}}function Eo(n){let e="Connection to Liveblocks websocket server";return t=>{fa(n)?xe(`${e} closed prematurely (code: ${n.code}). Retrying in ${t.backoffDelay}ms.`):xe(`${e} could not be established.`,n)}}function Ji(n){let e=[`code: ${n.code}`];return n.reason&&e.push(`reason: ${n.reason}`),t=>{xe(`Connection to Liveblocks websocket server closed (${e.join(", ")}). Retrying in ${t.backoffDelay}ms.`)}}function fa(n){return!(n instanceof Error)&&n.type==="close"}function gd(n){function e(...r){xe(`[FSM #${n.id}]`,...r)}let t=[n.events.didReceiveEvent.subscribe(r=>e(`Event ${r.type}`)),n.events.willTransition.subscribe(({from:r,to:i})=>e("Transitioning",r,"\u2192",i)),n.events.didExitState.subscribe(({state:r,durationMs:i})=>e(`Exited ${r} after ${i.toFixed(0)}ms`)),n.events.didIgnoreEvent.subscribe(r=>e("Ignored event",r.type,r,"(current state won't handle it)"))];return()=>{for(let r of t)r()}}function vd(n){let e=ne(),t=ne(),r=ne(),i=null,s=n.events.didEnterState.subscribe(()=>{let o=ua(n);o!==i&&e.notify(o),i==="connected"&&o!=="connected"?r.notify():i!=="connected"&&o==="connected"&&t.notify(),i=o});return{statusDidChange:e.observable,didConnect:t.observable,didDisconnect:r.observable,unsubscribe:s}}function yd(n,e){let t=Al();t.pause();let r=ne();function i(_,P){return()=>{r.notify({message:_,code:P})}}let s={successCount:0,authValue:null,socket:null,backoffDelay:li},o=new ad(s).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");o.addTransitions("*",{RECONNECT:{target:"@auth.backoff",effect:[Qn,bo]},DISCONNECT:"@idle.initial"}),o.onEnter("@idle.*",bo).addTransitions("@idle.*",{CONNECT:(_,P)=>P.authValue!==null?"@connecting.busy":"@auth.busy"}),o.addTransitions("@auth.backoff",{NAVIGATOR_ONLINE:{target:"@auth.busy",effect:di({backoffDelay:li})}}).addTimedTransition("@auth.backoff",_=>_.backoffDelay,"@auth.busy").onEnterAsync("@auth.busy",()=>so(n.authenticate(),pd,"Timed out during auth"),_=>({target:"@connecting.busy",effect:di({authValue:_.data})}),_=>_.reason instanceof Ut?{target:"@idle.failed",effect:[nr(2,_.reason.message),i(_.reason.message,-1)]}:{target:"@auth.backoff",effect:[Qn,nr(2,`Authentication failed: ${_.reason instanceof Error?_.reason.message:String(_.reason)}`)]});let c=_=>o.send({type:"EXPLICIT_SOCKET_ERROR",event:_}),u=_=>o.send({type:"EXPLICIT_SOCKET_CLOSE",event:_}),h=_=>_.data==="pong"?o.send({type:"PONG"}):t.notify(_);function l(_){_&&(_.removeEventListener("error",c),_.removeEventListener("close",u),_.removeEventListener("message",h),_.close())}o.addTransitions("@connecting.backoff",{NAVIGATOR_ONLINE:{target:"@connecting.busy",effect:di({backoffDelay:li})}}).addTimedTransition("@connecting.backoff",_=>_.backoffDelay,"@connecting.busy").onEnterAsync("@connecting.busy",async(_,P)=>{let C=performance.now(),R=null,y=null,F=null,G=new Promise((oe,re)=>{if(_.authValue===null)throw new Error("No auth authValue");let Q=n.createSocket(_.authValue);F=Q;function me(j){y=j,Q.removeEventListener("message",h),re(j)}let[Ne,U]=sa();e.waitForActorId||U();function A(j){if(Nt(j.data)?.type===W.ROOM_STATE){if(e.enableDebugLogging&&R!==null){let te=performance.now()-R;xe(`[FSM #${o.id}] Socket open \u2192 ROOM_STATE: ${te.toFixed(0)}ms`)}U()}}Q.addEventListener("message",h),e.waitForActorId&&Q.addEventListener("message",A),Q.addEventListener("error",me),Q.addEventListener("close",me),Q.addEventListener("open",()=>{if(R=performance.now(),e.enableDebugLogging){let Y=R-C;xe(`[FSM #${o.id}] Socket epoch \u2192 open: ${Y.toFixed(0)}ms`)}Q.addEventListener("error",c),Q.addEventListener("close",u);let j=()=>{Q.removeEventListener("error",me),Q.removeEventListener("close",me),Q.removeEventListener("message",A)};Ne.then(()=>{oe([Q,j])})})});return so(G,fd,"Timed out during websocket connection").then(([oe,re])=>{if(re(),P.aborted)throw new Error("Aborted");if(y)throw y;return oe}).catch(oe=>{throw l(F),oe})},_=>({target:"@ok.connected",effect:di({socket:_.data,backoffDelay:li})}),_=>{let P=_.reason;if(P instanceof Ut)return{target:"@idle.failed",effect:[nr(2,P.message),i(P.message,-1)]};if(fa(P)){if(P.code===4109)return"@auth.busy";if(vo(P.code))return{target:"@connecting.backoff",effect:[yo,Eo(P)]};if(go(P.code))return{target:"@idle.failed",effect:[nr(2,P.reason),i(P.reason,P.code)]}}return{target:"@auth.backoff",effect:[Qn,Eo(P)]}});let m={target:"@ok.awaiting-pong",effect:_=>{_.socket?.send("ping")}},k=()=>(typeof document<"u"?document:void 0)?.visibilityState==="hidden"&&n.canZombie()?"@idle.zombie":m;if(o.addTimedTransition("@ok.connected",ud,k).addTransitions("@ok.connected",{NAVIGATOR_OFFLINE:k,WINDOW_GOT_FOCUS:m}),o.addTransitions("@idle.zombie",{WINDOW_GOT_FOCUS:"@connecting.backoff"}),o.onEnter("@ok.*",_=>{_.patch({successCount:_.successCount+1});let P=setTimeout(t.unpause,0);return C=>{l(C.socket),C.patch({socket:null}),clearTimeout(P),t.pause()}}).addTransitions("@ok.awaiting-pong",{PONG:"@ok.connected"}).addTimedTransition("@ok.awaiting-pong",hd,{target:"@connecting.busy",effect:nr(1,"Received no pong from server, assume implicit connection loss.")}).addTransitions("@ok.*",{EXPLICIT_SOCKET_ERROR:(_,P)=>P.socket?.readyState===1?null:{target:"@connecting.backoff",effect:Qn},EXPLICIT_SOCKET_CLOSE:_=>go(_.event.code)?{target:"@idle.failed",effect:[md,i(_.event.reason,_.event.code)]}:cd(_.event.code)?_.event.code===4109?"@auth.busy":{target:"@auth.backoff",effect:[Qn,Ji(_.event)]}:vo(_.event.code)?{target:"@connecting.backoff",effect:[yo,Ji(_.event)]}:{target:"@connecting.backoff",effect:[Qn,Ji(_.event)]}}),typeof document<"u"){let _=typeof document<"u"?document:void 0,P=typeof window<"u"?window:void 0,C=P??_;o.onEnter("*",R=>{function y(){o.send({type:"NAVIGATOR_OFFLINE"})}function F(){o.send({type:"NAVIGATOR_ONLINE"})}function G(){_?.visibilityState==="visible"&&o.send({type:"WINDOW_GOT_FOCUS"})}return P?.addEventListener("online",F),P?.addEventListener("offline",y),C?.addEventListener("visibilitychange",G),()=>{C?.removeEventListener("visibilitychange",G),P?.removeEventListener("online",F),P?.removeEventListener("offline",y),l(R.socket)}})}let O=[],{statusDidChange:z,didConnect:B,didDisconnect:J,unsubscribe:se}=vd(o);return O.push(se),e.enableDebugLogging&&O.push(gd(o)),o.start(),{machine:o,cleanups:O,events:{statusDidChange:z,didConnect:B,didDisconnect:J,onMessage:t.observable,onConnectionError:r.observable}}}function Wi(n,e){let t=n[n.length-1];return e.includes(t)?n.slice(0,-1):n}function xd(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!Object.is(n[t],e[t]))return!1;return!0}function Ad(n,e){if(!Ce(n)||!Ce(e))return!1;let t=Object.keys(n);return t.length!==Object.keys(e).length?!1:t.every(r=>Object.prototype.hasOwnProperty.call(e,r)&&Object.is(n[r],e[r]))}function yi(n,e){if(Object.is(n,e))return!0;let t=Array.isArray(n),r=Array.isArray(e);return t||r?!t||!r?!1:xd(n,e):Ad(n,e)}function Td(n,e){if(!Ce(n)||!Ce(e))return yi(n,e);let t=Object.keys(n);return t.length!==Object.keys(e).length?!1:t.every(r=>Object.prototype.hasOwnProperty.call(e,r)&&yi(n[r],e[r]))}function Id(){let n=new Qe(r=>new zd);function e(r){return n.getOrCreate(r??Lr)}function t(r){let i=n.getOrCreate(Lr).get(),s=n.get(r)?.get()??[];return[...i,...s]}return{getKnowledgeStack:e,getKnowledgeForChat:t}}function Gi(){return new Date().toISOString()}function Od(){let n=new Qe(o=>new Qe(c=>new Et(void 0))),e=new Qe(o=>{let[c,u]=Nt(o);return Dn.from(()=>(u!==void 0?n.getOrCreate(u).getOrCreate(c):void 0)?.get()??n.getOrCreate(Lr).getOrCreate(c).get())});function t(o,c){let u=JSON.stringify(c!==void 0?[o,c]:[o]);return e.getOrCreate(u)}function r(o,c,u){if(!c.execute&&!c.render)throw new Error("A tool definition must have an execute() function, a render() function, or both.");let h=u??Lr;return n.getOrCreate(h).getOrCreate(o).set(c),()=>i(h,o)}function i(o,c){let u=n.get(o);if(u===void 0)return;let h=u.get(c);h!==void 0&&h.set(void 0)}function s(o){let c=n.get(Lr),u=n.get(o);return Array.from([...c?.entries()??[],...u?.entries()??[]]).flatMap(([h,l])=>{let m=l.get();return m&&(m.enabled??!0)?[{name:h,description:m.description,parameters:m.parameters}]:[]})}return{getToolDescriptions:s,getTool\u03A3:t,registerTool:r}}function Rd(n,e){let t=new Set,r=new Set,i=new Qe(C=>new Dr(new kd(R=>R.id,R=>R.parentId,(R,y)=>R.createdAt<y.createdAt))),s=new Dr(new Map);function o(C,R,y,F){let G=`ms_${ze()}`,oe=Gi();return l(R==="user"?{id:G,chatId:C,role:R,parentId:y,createdAt:oe,content:F,_optimistic:!0}:{id:G,chatId:C,role:R,parentId:y,createdAt:oe,status:"generating",contentSoFar:[],copilotId:F,_optimistic:!0}),G}function c(C){dn(()=>{for(let R of C)l(R)})}function u(C,R){let y=i.get(C);if(!y)return;let F=y.get().get(R);!F||F.deletedAt||(F.role==="assistant"&&F.status!=="completed"?l({...F,deletedAt:Gi(),contentSoFar:[]}):l({...F,deletedAt:Gi(),content:[]}))}function h(C){let R=i.get(C);R!==void 0&&R.mutate(y=>y.clear())}function l(C){dn(()=>{if(i.getOrCreate(C.chatId).mutate(y=>y.upsert(C)),C.role==="assistant"&&C.status==="generating"?s.mutate(y=>{y.set(C.id,structuredClone(C))}):s.mutate(y=>{y.delete(C.id)}),C.role==="assistant"&&C.status==="awaiting-tool"){if(t.has(C.id))for(let y of C.contentSoFar.filter(F=>F.type==="tool-invocation"&&F.stage==="executing")){if(!r.has(y.invocationId))r.add(y.invocationId);else continue;let F=n.getTool\u03A3(y.name,C.chatId).get()?.execute;F&&(async()=>{let G=await F(y.args,{name:y.name,invocationId:y.invocationId});return await e(C.chatId,C.id,y.invocationId,G??{data:{}},{copilotId:C.copilotId})})().catch(G=>{wt(`Error trying to respond to tool-call: ${String(G)} (in execute())`)})}}else C.role==="assistant"&&C.status==="generating"||t.delete(C.id)})}function m(C,R){s.mutate(y=>{let F=y.get(C);return F===void 0?!1:(Pd(F.contentSoFar,R),y.set(C,F),!0)})}function*k(){for(let C of i.values())for(let R of C.get())R.role==="assistant"&&R.status==="generating"&&!R._optimistic&&(yield R)}function O(){dn(()=>{s.mutate(C=>{let R=!1;for(let[y,F]of C)F._optimistic||(C.delete(y),R=!0);return R}),c(Array.from(k()).map(C=>({...C,status:"failed",errorReason:"Lost connection"})))})}function z(C){for(let R of i.values()){let y=R.get().get(C);if(y)return y}}function B(C){let R=C.next();return R.done?void 0:R.value}function J(C,R){function y(re){if(!re.deletedAt)return!0;for(let Q of C.walkDown(re.id,me=>!me.deletedAt))return!0;return!1}function F(re){let Q=[],me=null;for(let Ne of C.walkUp(re.id)){let U=B(C.walkLeft(Ne.id,y))?.id??null,A=B(C.walkRight(Ne.id,y))?.id??null;if(!Ne.deletedAt||U||A){let j={...Ne,navigation:{parent:null,prev:U,next:A}};me!==null&&(me.navigation.parent=j.id),me=j,Q.push(j)}}return Q.reverse()}function G(){let re=C.sorted.findRight(Q=>!Q.deletedAt);return re?F(re):[]}if(R===null)return G();let oe=C.get(R);if(!oe)return G();for(let re of C.walkUp(oe.id)){for(let Q of C.walkDown(re.id,me=>!me.deletedAt))return F(Q);if(!re.deletedAt)return F(re)}return G()}let se=new Qe(C=>new Qe(R=>{let y=Dn.from(()=>{let F=i.getOrCreate(C).get();return J(F,R)},Td);return Dn.from(()=>{let F=s.get();return y.get().map(G=>{if(G.role!=="assistant"||G.status!=="generating")return G;let oe=F.get(G.id);return oe===void 0?G:{...G,contentSoFar:oe.contentSoFar}})},yi)}));function _(C,R){return se.getOrCreate(C).getOrCreate(R||null)}function P(C){return i.getOrCreate(C).get().sorted.findRight(F=>F.role==="assistant"&&!F.deletedAt)?.copilotId}return{getMessageById:z,getChatMessagesForBranch\u03A3:_,getLastUsedCopilotId:P,createOptimistically:o,upsert:l,upsertMany:c,remove:u,removeByChatId:h,addDelta:m,failAllPending:O,markMine(C){t.add(C)},*getAutoExecutingMessageIds(){for(let C of t){let R=z(C);R?.role==="assistant"&&R.status==="awaiting-tool"&&R.contentSoFar.some(F=>F.type==="tool-invocation"&&F.stage==="executing"?typeof n.getTool\u03A3(F.name,R.chatId).get()?.execute=="function":!1)&&(yield R.id)}}}}function Ld(){let n=new Dl;function e(o){dn(()=>{for(let c of o)n.upsert(c)})}function t(o){n.upsert(o)}function r(o){n.markDeleted(o)}function i(o){return n.getEvenIfDeleted(o)}function s(o){return n.signal.get().findMany(o)}return{getChatById:i,findMany:s,upsert:t,upsertMany:e,markDeleted:r}}function Dd(n){let e=new ma(n.delegates,n.enableDebugLogging,!1),t=Ld(),r=Od(),i=Id(),s=Rd(r,Q),o={staticSessionInfoSig:new Et(null),dynamicSessionInfoSig:new Et(null),pendingCmds:new Map,chatsStore:t,messagesStore:s,toolsStore:r,knowledgeStore:i},c=new Et("initial"),u=25,h=[],l=null;function m(){let U=h;h=[],l!==null&&(clearTimeout(l),l=null),dn(()=>{for(let{id:A,delta:j}of U)o.messagesStore.addDelta(A,j)})}function k(U,A){h.push({id:U,delta:A}),l===null&&(l=setTimeout(m,u))}let O;function z(U){let A=e.authValue;if(A!==null){let j=ws(A);if(j!==O)if(O=j,A.type==="secret"){let Y=A.token.parsed;o.staticSessionInfoSig.set({userId:Y.uid,userInfo:Y.ui})}else o.staticSessionInfoSig.set({userId:void 0,userInfo:void 0})}c.set(U)}let B,J=!1;function se(U){U==="reconnecting"?B=setTimeout(()=>{J=!0},n.lostConnectionTimeout):(clearTimeout(B),J&&(J=!1))}function _(){}function P(){m()}function C(U){if(typeof U.data!="string")return;let A=Nt(U.data);if(!A)return;let j="cmdId"in A?A.cmdId:A.event==="cmd-failed"?A.failedCmdId:void 0,Y=o.pendingCmds.get(j);if(j&&!Y){xe("Ignoring unexpected command response. Already timed out, or not for us?",A);return}if("event"in A)if(A.event==="delta"){let{id:te,delta:Ae}=A;k(te,Ae)}else dn(()=>{switch(m(),A.event){case"cmd-failed":Y?.reject(new Error(A.error));break;case"settle":{o.messagesStore.upsert(A.message);break}case"warning":xe(A.message);break;case"error":wt(A.error);break;case"rebooted":o.messagesStore.failAllPending();break;case"sync":for(let te of A["-messages"]??[])o.messagesStore.remove(te.chatId,te.id);for(let te of A["-chats"]??[])o.chatsStore.markDeleted(te),o.messagesStore.removeByChatId(te);for(let te of A.clear??[])o.messagesStore.removeByChatId(te);A.chats&&o.chatsStore.upsertMany(A.chats),A.messages&&o.messagesStore.upsertMany(A.messages);break;default:return Re(A,"Unhandled case")}});else switch(A.cmd){case"get-chats":o.chatsStore.upsertMany(A.chats);break;case"get-or-create-chat":o.chatsStore.upsert(A.chat);break;case"delete-chat":o.chatsStore.markDeleted(A.chatId),o.messagesStore.removeByChatId(A.chatId);break;case"get-message-tree":o.chatsStore.upsert(A.chat),o.messagesStore.upsertMany(A.messages);break;case"delete-message":o.messagesStore.remove(A.chatId,A.messageId);break;case"clear-chat":o.messagesStore.removeByChatId(A.chatId);break;case"ask-in-chat":A.sourceMessage&&o.messagesStore.upsert(A.sourceMessage),o.messagesStore.upsert(A.targetMessage);break;case"abort-ai":break;case"set-tool-result":A.ok&&o.messagesStore.upsert(A.message);break;default:return Re(A,"Unhandled case")}Y?.resolve(A)}e.events.onMessage.subscribe(C),e.events.statusDidChange.subscribe(z),e.events.statusDidChange.subscribe(se),e.events.didConnect.subscribe(_),e.events.didDisconnect.subscribe(P),e.events.onConnectionError.subscribe(({message:U,code:A})=>{process.env.NODE_ENV!=="production"&&wt(`Connection to websocket server closed. Reason: ${U} (code: ${A}).`)});function R(){e.getStatus()==="initial"&&e.connect()}async function y(U){R(),e.getStatus()!=="connected"&&await e.events.didConnect.waitUntil();let{promise:A,resolve:j,reject:Y}=ar(),te=AbortSignal.timeout(_d);te.addEventListener("abort",()=>Y(te.reason),{once:!0});let Ae=ze(7);return o.pendingCmds.set(Ae,{resolve:j,reject:Y}),F({...U,cmdId:Ae}),A.finally(()=>{o.pendingCmds.delete(Ae)}).catch(De=>{throw wt(De.message),De})}function F(U){e.send(JSON.stringify({...U}))}function G(U={}){return y({cmd:"get-chats",cursor:U.cursor,query:U.query})}function oe(U,A){return y({cmd:"get-or-create-chat",id:U,options:A})}function re(U){return y({cmd:"get-message-tree",chatId:U})}async function Q(U,A,j,Y,te){let Ae=o.knowledgeStore.getKnowledgeForChat(U),De=o.toolsStore.getToolDescriptions(U),qe=await y({cmd:"set-tool-result",chatId:U,messageId:A,invocationId:j,result:Y,generationOptions:{copilotId:te?.copilotId,stream:te?.stream,timeout:te?.timeout,knowledge:Ae.length>0?Ae:void 0,tools:De.length>0?De:void 0}});qe.ok&&s.markMine(qe.message.id)}function me(){for(let U of o.messagesStore.getAutoExecutingMessageIds())y({cmd:"abort-ai",messageId:U}).catch(()=>{})}return(typeof window<"u"?window:void 0)?.addEventListener("beforeunload",me,{once:!0}),Object.defineProperty({[Ct]:{context:o},connectInitially:R,disconnect:()=>e.disconnect(),getChats:G,getOrCreateChat:oe,deleteChat:U=>y({cmd:"delete-chat",chatId:U}),getMessageTree:re,deleteMessage:(U,A)=>y({cmd:"delete-message",chatId:U,messageId:A}),clearChat:U=>y({cmd:"clear-chat",chatId:U}),askUserMessageInChat:async(U,A,j,Y)=>{let te=o.knowledgeStore.getKnowledgeForChat(U),Ae=Y?.knowledge||[],De=[...te,...Ae],qe=o.toolsStore.getToolDescriptions(U);return s.markMine(j),await y({cmd:"ask-in-chat",chatId:U,sourceMessage:A,targetMessageId:j,generationOptions:{copilotId:Y?.copilotId,stream:Y?.stream,timeout:Y?.timeout,knowledge:De.length>0?De:void 0,tools:qe.length>0?qe:void 0}})},abort:U=>y({cmd:"abort-ai",messageId:U}),setToolResult:Q,getStatus:()=>e.getStatus(),signals:{getChatMessagesForBranch\u03A3:o.messagesStore.getChatMessagesForBranch\u03A3,getTool\u03A3:o.toolsStore.getTool\u03A3,status\u03A3:c},getChatById:o.chatsStore.getChatById,queryChats:o.chatsStore.findMany,getLastUsedCopilotId:o.messagesStore.getLastUsedCopilotId,registerKnowledgeLayer:(U,A)=>{let j=o.knowledgeStore.getKnowledgeStack(A),Y=j.registerLayer(U);return{layerKey:Y,deregister:()=>j.deregisterLayer(Y)}},updateKnowledge:(U,A,j,Y)=>{o.knowledgeStore.getKnowledgeStack(Y).updateKnowledge(U,j??ze(),A)},registerTool:o.toolsStore.registerTool},Ct,{enumerable:!1})}function Md(n,e){return t=>{let r=e??(typeof WebSocket>"u"?void 0:WebSocket);if(r===void 0)throw new Ut("To use Liveblocks client in a non-DOM environment, you need to provide a WebSocket polyfill.");let i=new URL(n);if(i.protocol=i.protocol==="http:"?"ws":"wss",i.pathname="/ai/v7",t.type==="secret")i.searchParams.set("tok",t.token.raw);else{if(t.type==="public")throw new Error("Public key not supported with AI Copilots");return Re(t,"Unhandled case")}return i.searchParams.set("version",ln||"dev"),new r(i.toString())}}function So(n,e,t,r){let i=zl(n,s=>s.type===e.type&&t(s)===t(e));i>-1?n[i]=e:(ds(n[n.length-1],r),n.push(e))}function ds(n,e){n?.type==="reasoning"&&(n.endedAt??(n.endedAt=e))}function Pd(n,e){if(e===null)return;let t=n.filter(o=>o.type!=="sources"),r=n.filter(o=>o.type==="sources").flatMap(o=>o.sources),i=new Date().toISOString(),s=t[t.length-1];switch(e.type){case"text-delta":s?.type==="text"?s.text+=e.textDelta:(ds(s,i),t.push({type:"text",text:e.textDelta}));break;case"reasoning-delta":s?.type==="reasoning"?s.text+=e.textDelta:(ds(s,i),t.push({type:"reasoning",text:e.textDelta,startedAt:i}));break;case"tool-stream":{let o=Nd(e.invocationId,e.name);t.push(o);break}case"tool-delta":{s?.type==="tool-invocation"&&s.stage==="receiving"&&s.__appendDelta?.(e.delta);break}case"tool-invocation":So(t,e,o=>o.invocationId,i);break;case"retrieval":So(t,e,o=>o.id,i);break;case"source":{r.push(e);break}default:return Re(e,"Unhandled case")}r.length>0&&t.push({type:"sources",sources:r}),n.length=0,n.push(...t)}function Nd(n,e,t=""){let r=new Cd(t);return{type:"tool-invocation",stage:"receiving",invocationId:n,name:e,get partialArgsText(){return r.source},get partialArgs(){return r.json},__appendDelta(i){r.append(i)}}}function us(n){return n.includes("room:write")}function Ea(n){return n.includes("comments:write")||n.includes("room:write")}function Ud(n){return Ce(n)&&(n.k==="acc"||n.k==="id")}function Co(n){let e=n.split(".");if(e.length!==3)throw new Error("Authentication error: invalid JWT token");let t=Nt(kl(e[1]));if(!(t&&Ud(t)))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");return{raw:n,parsed:t}}function Fd(n,e){let t=Vd(n),r=new Set,i=[],s=[],o=new Map;function c(){r.clear(),i.length=0,s.length=0,o.clear()}function u(k,O){return k==="comments:read"?O.includes("comments:read")||O.includes("comments:write")||O.includes("room:read")||O.includes("room:write"):k==="room:read"?O.includes("room:read")||O.includes("room:write"):!1}function h(k){let O=Math.ceil(Date.now()/1e3);for(let z=i.length-1;z>=0;z--){let B=i[z];if(s[z]<=O){i.splice(z,1),s.splice(z,1);continue}if(B.parsed.k==="id")return B;if(B.parsed.k==="acc"){if(!k.roomId&&Object.entries(B.parsed.perms).length===0)return B;for(let[se,_]of Object.entries(B.parsed.perms))if(k.roomId){if(se.includes("*")&&k.roomId.startsWith(se.replace("*",""))||k.roomId===se&&u(k.requestedScope,_))return B}else if(se.includes("*")&&u(k.requestedScope,_))return B}}}async function l(k){let O=n.polyfills?.fetch??(typeof window>"u"?void 0:window.fetch);if(t.type==="private"){if(O===void 0)throw new Ut("To use Liveblocks client in a non-DOM environment with a url as auth endpoint, you need to provide a fetch polyfill.");let z=await Hd(O,t.url,{room:k.roomId}),B=Co(z.token);if(r.has(B.raw))throw new Ut("The same Liveblocks auth token was issued from the backend before. Caching Liveblocks tokens is not supported.");return e?.(B.parsed),B}if(t.type==="custom"){let z=await t.callback(k.roomId);if(z&&typeof z=="object"){if(typeof z.token=="string"){let B=Co(z.token);return e?.(B.parsed),B}else if(typeof z.error=="string"){let B=`Authentication failed: ${"reason"in z&&typeof z.reason=="string"?z.reason:"Forbidden"}`;throw z.error==="forbidden"?new Ut(B):new Error(B)}}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.")}async function m(k){if(t.type==="public")return{type:"public",publicApiKey:t.publicApiKey};let O=h(k);if(O!==void 0)return{type:"secret",token:O};let z;k.roomId?(z=o.get(k.roomId),z===void 0&&(z=l(k),o.set(k.roomId,z))):(z=o.get("liveblocks-user-token"),z===void 0&&(z=l(k),o.set("liveblocks-user-token",z)));try{let B=await z,se=Math.floor(Date.now()/1e3)+(B.parsed.exp-B.parsed.iat)-30;return r.add(B.raw),i.push(B),s.push(se),{type:"secret",token:B}}finally{k.roomId?o.delete(k.roomId):o.delete("liveblocks-user-token")}}return{reset:c,getAuthValue:m}}function Vd(n){let{publicApiKey:e,authEndpoint:t}=n;if(t!==void 0&&e!==void 0)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(typeof e=="string"){if(e.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(!e.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:e}}if(typeof t=="string")return{type:"private",url:t};if(typeof t=="function")return{type:"custom",callback:t};throw t!==void 0?new Error("The `authEndpoint` option must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint"):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")}async function Hd(n,e,t){let r=await n(e,{method:"POST",headers:{"Content-Type":"application/json"},body:Un(t)});if(!r.ok){let o=`${(await r.text()).trim()||"reason not provided in auth response"} (${r.status} returned by POST ${e})`;throw $d.includes(r.status)?new Ut(`Unauthorized: ${o}`):new Error(`Failed to authenticate: ${o}`)}let i;try{i=await r.json()}catch(o){throw new Error(`Expected a JSON response when doing a POST request on "${e}". ${String(o)}`)}if(!Ce(i)||typeof i.token!="string")throw new Error(`Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${e}", but got ${Un(i)}`);let{token:s}=i;return{token:s}}function Kd(n){return n.type===H.DELETE_CRDT&&n.id==="ACK"}function jd(n){return n[0]==="root"}function wa(n){return n[1].type===he.OBJECT}function Sa(n){return n[1].type===he.LIST}function Ca(n){return n[1].type===he.MAP}function xa(n){return n[1].type===he.REGISTER}function qd(n){return n[0]==="root"}function*Jd(n){for(let e of n){if(qd(e)){yield[e[0],{type:he.OBJECT,data:e[1]}];continue}switch(e[1]){case he.OBJECT:yield[e[0],{type:he.OBJECT,parentId:e[2],parentKey:e[3],data:e[4]}];break;case he.LIST:yield[e[0],{type:he.LIST,parentId:e[2],parentKey:e[3]}];break;case he.MAP:yield[e[0],{type:he.MAP,parentId:e[2],parentKey:e[3]}];break;case he.REGISTER:yield[e[0],{type:he.REGISTER,parentId:e[2],parentKey:e[3],data:e[4]}];break;default:}}}function Ss(n){let e=Le+(n<0?Aa+n:n);if(e<Le||e>un)throw new Error(`Invalid n value: ${n}`);return String.fromCharCode(e)}function kt(n,e){return n!==void 0&&e!==void 0?Xd(n,e):n!==void 0?Yd(n):e!==void 0?Gd(e):lr}function Gd(n){let e=n.length-1;for(let t=0;t<=e;t++){let r=n.charCodeAt(t);if(!(r<=Le))return t===e?r===Le+1?n.substring(0,t)+Wd:n.substring(0,t)+String.fromCharCode(r-1):n.substring(0,t+1)}return lr}function Yd(n){for(let i=0;i<n.length;i++){let s=n.charCodeAt(i);if(s<Le||s>un)return n+lr}for(;n.length>1&&n.charCodeAt(n.length-1)===Le;)n=n.slice(0,-1);if(n.length===0||n===Ci)return lr;let e=ui;n.length>ui&&(e=ui+Math.ceil((n.length-ui)/Yi)*Yi);let t=xo(n,e);if(t!==null)return t;e+=Yi;let r=xo(n,e);return r!==null?r:n+lr}function xo(n,e){let t=[];for(let s=0;s<e;s++)s<n.length?t.push(n.charCodeAt(s)-Le):t.push(0);let r=1;for(let s=e-1;s>=0&&r;s--){let o=t[s]+r;o>=Aa?(t[s]=0,r=1):(t[s]=o,r=0)}if(r)return null;let i="";for(let s of t)i+=String.fromCharCode(s+Le);for(;i.length>1&&i.charCodeAt(i.length-1)===Le;)i=i.slice(0,-1);return i}function Xd(n,e){if(n<e)return hs(n,e);if(n>e)return hs(e,n);throw new Error("Cannot compute value between two equal positions")}function hs(n,e){let t=0,r=n.length,i=e.length;for(;;){let s=t<r?n.charCodeAt(t):Le,o=t<i?e.charCodeAt(t):un;if(s===o){t++;continue}if(o-s===1){let c=t+1,u=n.substring(0,c);u.length<c&&(u+=Ci.repeat(c-u.length));let h=n.substring(c);return u+hs(h,"")}else return Zd(n,t)+String.fromCharCode(o+s>>1)}}function Zd(n,e){return e<n.length?n.substring(0,e):n+Ci.repeat(e-n.length)}function eu(n){if(n==="")return!1;let e=n.length-1,t=n.charCodeAt(e);if(t<Qd||t>un)return!1;for(let r=0;r<e;r++){let i=n.charCodeAt(r);if(i<Le||i>un)return!1}return!0}function tu(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);e.push(r<Le?Le:r>un?un:r)}for(;e.length>0&&e[e.length-1]===Le;)e.length--;return e.length>0?String.fromCharCode(...e):lr}function Mr(n){return eu(n)?n:tu(n)}function nu(n,e){let{getCurrentConnectionId:t,onDispatch:r,isStorageWritable:i=()=>!0}=e,s=0,o=0,c=new Map;return{roomId:n,nodes:c,getNode:u=>c.get(u),addNode:(u,h)=>{c.set(u,h)},deleteNode:u=>{c.delete(u)},generateId:()=>`${t()}:${s++}`,generateOpId:()=>`${t()}:${o++}`,dispatch(u,h,l){r?.(u,h,l)},assertStorageIsWritable:()=>{if(!i())throw new Error("Cannot write to storage with a read only user, please ensure the user has write permissions")}}}function Ao(n,e,t=Mr(e)){return Object.freeze({type:"HasParent",node:n,key:e,pos:t})}function ru(n,e=Mr(n)){return Object.freeze({type:"Orphaned",oldKey:n,oldPos:e})}function iu(n,e){return n._parentPos<e._parentPos}function ie(n,e){return{node:n,type:"LiveList",updates:e}}function er(n,e){return{index:n,type:"set",item:e instanceof hn?e.data:e}}function hi(n,e){return{type:"delete",index:n,deletedItem:e instanceof hn?e.data:e}}function tt(n,e){return{index:n,type:"insert",item:e instanceof hn?e.data:e}}function Cn(n,e,t){return{type:"move",index:e,item:t instanceof hn?t.data:t,previousIndex:n}}function pi(n,e){return n.map((t,r)=>r===0?{...t,intent:"set",deletedId:e}:t)}function $n(n,e){if(Array.isArray(n))return new pn(n.map(t=>$n(t,e)));if(Ce(n)){let t={},r={};for(let s in n){let o=n[s];if(o===void 0)continue;let c=Ce(e)?e[s]:e;c===!1?r[s]=o:c==="atomic"?t[s]=o:t[s]=$n(o,c)}let i=new Ft(t);for(let s in r)i.setLocal(s,r[s]);return i}else return n}function Ma(n,e,t){return xs(n)&&Ce(e)?ps(n,e,"full",t):Cs(n)&&Array.isArray(e)?ou(n,e,t):Ha(n)&&Ce(e)?su(n,t):$n(e,t)}function su(n,e){throw new Error("Reconciling a LiveMap is not supported yet")}function ps(n,e,t,r){let i=n.keys();for(let s in e){i.delete(s);let o=e[s];if(o===void 0){t==="full"&&n.delete(s);continue}let c=Ce(r)?r[s]:r;if(c===!1)n.setLocal(s,o);else if(c==="atomic")n.get(s)!==o&&n.set(s,o);else{let u=n.get(s);if(u===void 0)n.set(s,$n(o,c));else if(cn(u)){let h=Ma(u,o,c);h!==u&&n.set(s,h)}else u!==o&&n.set(s,$n(o,c))}}if(t==="full")for(let s of i)n.delete(s);return n}function ou(n,e,t){let r=n.length,i=e.length;for(let s=0;s<Math.min(r,i);s++){let o=n.get(s),c=e[s];if(cn(o)){let u=Ma(o,c,t);u!==o&&n.set(s,u)}else o!==c&&n.set(s,$n(c,t))}for(let s=r;s<i;s++)n.push($n(e[s],t));for(let s=r-1;s>=i;s--)n.delete(s);return n}function Or(n){return dr($a(n))}function $a(n){switch(n.type){case H.CREATE_REGISTER:return n.data;case H.CREATE_OBJECT:return new Ft(n.data);case H.CREATE_MAP:return new Fn;case H.CREATE_LIST:return new pn([]);default:return Re(n,"Unknown creation Op")}}function Fa(n,e){return n===e?!0:n.parent.type==="HasParent"?Fa(n.parent.node,e):!1}function Va(n,e,t){if(wa(n))return Ft._deserialize(n,e,t);if(Sa(n))return pn._deserialize(n,e,t);if(Ca(n))return Fn._deserialize(n,e,t);if(xa(n))return hn._deserialize(n,e,t);throw new Error("Unexpected CRDT type")}function au(n,e,t){if(wa(n))return Ft._deserialize(n,e,t);if(Sa(n))return pn._deserialize(n,e,t);if(Ca(n))return Fn._deserialize(n,e,t);if(xa(n))return n[1].data;throw new Error("Unexpected CRDT type")}function cn(n){return Cs(n)||Ha(n)||xs(n)}function ve(n){return cn(n)||cu(n)}function Cs(n){return n instanceof pn}function Ha(n){return n instanceof Fn}function xs(n){return n instanceof Ft}function cu(n){return n instanceof hn}function lu(n){return n===void 0?void 0:cn(n)?n.clone():yr(n)}function ir(n){return n instanceof hn?n.data:n instanceof pn||n instanceof Fn||n instanceof Ft?n:Re(n,"Unknown AbstractCrdt")}function dr(n){return n instanceof Ft||n instanceof Fn||n instanceof pn?n:new hn(n)}function du(n,e){let t=[];return n.forEach((r,i)=>{e.get(i)||t.push({type:H.DELETE_CRDT,id:i})}),e.forEach((r,i)=>{let s=n.get(i);if(s)r.type===he.OBJECT&&(s.type!==he.OBJECT||Un(r.data)!==Un(s.data))&&t.push({type:H.UPDATE_OBJECT,id:i,data:r.data}),r.parentKey!==s.parentKey&&t.push({type:H.SET_PARENT_KEY,id:i,parentKey:q(r.parentKey,"Parent key must not be missing")});else switch(r.type){case he.REGISTER:t.push({type:H.CREATE_REGISTER,id:i,parentId:r.parentId,parentKey:r.parentKey,data:r.data});break;case he.LIST:t.push({type:H.CREATE_LIST,id:i,parentId:r.parentId,parentKey:r.parentKey});break;case he.OBJECT:if(r.parentId===void 0||r.parentKey===void 0)throw new Error("Internal error. Cannot serialize storage root into an operation");t.push({type:H.CREATE_OBJECT,id:i,parentId:r.parentId,parentKey:r.parentKey,data:r.data});break;case he.MAP:t.push({type:H.CREATE_MAP,id:i,parentId:r.parentId,parentKey:r.parentKey});break}}),t}function uu(n,e){let t=n.updates;for(let[r,i]of Zo(e.updates))t[r]=i;return{...e,updates:t}}function hu(n,e){let t=n.updates;for(let[r,i]of Zo(e.updates))t[r]=i;return{...e,updates:t}}function pu(n,e){let t=n.updates;return{...e,updates:t.concat(e.updates)}}function Zi(n,e){return n===void 0?e:n.type==="LiveObject"&&e.type==="LiveObject"?uu(n,e):n.type==="LiveMap"&&e.type==="LiveMap"?hu(n,e):n.type==="LiveList"&&e.type==="LiveList"?pu(n,e):e}function fu(n){Ba=n}function at(n,e){if(process.env.NODE_ENV==="production"||typeof window>"u")return;let t={...n,source:"liveblocks-devtools-client"};(e?.force||Ba)&&window.postMessage(t,"*")}function mu(n){process.env.NODE_ENV==="production"||typeof window>"u"||ko||(ko=!0,ja.subscribe(e=>{switch(e.msg){case"connect":{fu(!0);for(let t of n())at({msg:"room::available",roomId:t,clientVersion:qa});break}}}),at({msg:"wake-up-devtools"},{force:!0}))}function As(n){let e=ms.get(n)??[];ms.delete(n);for(let t of e)t()}function gu(n){As(n.id),Au(n),ms.set(n.id,[n.events.status.subscribe(()=>Su(n)),n.events.storageDidLoad.subscribeOnce(()=>_o(n)),n.events.storageBatch.subscribe(()=>_o(n)),n.events.self.subscribe(()=>Cu(n)),n.events.others.subscribe(()=>xu(n)),n.events.ydoc.subscribe(e=>vu(n,e)),n.events.customEvent.subscribe(e=>wu(n,e))])}function vu(n,e){at({msg:"room::sync::ydoc",roomId:n.id,update:e})}function Eu(){return`event-${yu}-${bu++}`}function wu(n,e){at({msg:"room::events::custom-event",roomId:n.id,event:{type:"CustomEvent",id:Eu(),key:"Event",connectionId:e.connectionId,payload:e.event}})}function Su(n){at({msg:"room::sync::partial",roomId:n.id,status:n.getStatus()})}function _o(n){let e=n.getStorageSnapshot();e&&at({msg:"room::sync::partial",roomId:n.id,storage:e.toTreeNode("root").payload})}function Cu(n){let e=n[Ct].getSelf_forDevTools();e&&at({msg:"room::sync::partial",roomId:n.id,me:e})}function xu(n){let e=n[Ct].getOthers_forDevTools();e&&at({msg:"room::sync::partial",roomId:n.id,others:e})}function Au(n){let e=n.getStorageSnapshot(),t=n[Ct].getSelf_forDevTools(),r=n[Ct].getOthers_forDevTools();n.fetchYDoc(""),at({msg:"room::sync::full",roomId:n.id,status:n.getStatus(),storage:e?.toTreeNode("root").payload??null,me:t,others:r})}function Ja(n){let e=gs.get(n);gs.delete(n),e&&e()}function Tu(n,e){process.env.NODE_ENV==="production"||typeof window>"u"||(at({msg:"room::available",roomId:n,clientVersion:qa}),Ja(n),gs.set(n,ja.subscribe(t=>{switch(t.msg){case"room::subscribe":{t.roomId===n&&gu(e);break}case"room::unsubscribe":{t.roomId===n&&As(n);break}}})))}function ku(n){process.env.NODE_ENV==="production"||typeof window>"u"||(As(n),Ja(n),at({msg:"room::unavailable",roomId:n}))}function _u(n,e=n){process.env.NODE_ENV!=="production"&&(zo.has(e)||(zo.add(e),xe(n)))}function Qi(n,e,t=e){(typeof n=="function"?n():n)&&_u(e,t)}function Oo(n){let e=["email","slack","teams","webPush"],t={[Io]:{value:n,enumerable:!1}};for(let r of e)t[r]={enumerable:!0,get(){let i=this[Io][r];return typeof i>"u"?(wt(`In order to use the '${r}' channel, please set up your project first. For more information: https://liveblocks.io/docs/errors/enable-a-notification-channel`),null):i}};return Tl(null,t)}function Iu(n){return n===null||typeof n=="string"||typeof n=="number"||typeof n=="boolean"}function Wa(n){return Array.isArray(n)}function Ou(n){return!Iu(n)&&!Wa(n)}function Ru(){let n=0,e=0,t;function r(){t=[],n=performance.now(),e=n}function i(o=performance.now()){t.push(o-e),e=o}function s(){let o=performance.now();return i(o),{total:o-n,laps:t}}return{start:r,lap:i,stop:s}}function Lu(n,e){let{connectionId:t,id:r,info:i}=n,s=us(n.scopes);return bt(Si({connectionId:t,id:r,info:i,canWrite:s,canComment:Ea(n.scopes),isReadOnly:!s,presence:e}))}function Mu(n){switch(n.type){case"ROOM_CONNECTION_ERROR":switch(n.code){case 4001:return"Not allowed to connect to the room";case 4005:return"Room is already full";case 4006:return"Kicked out of the room, because the room ID changed";default:return"Could not connect to the room"}case"AI_CONNECTION_ERROR":return n.code===4001?"Not allowed to connect to ai":"Could not connect to the room";case"CREATE_THREAD_ERROR":return"Could not create new thread";case"DELETE_THREAD_ERROR":return"Could not delete thread";case"EDIT_THREAD_METADATA_ERROR":return"Could not edit thread metadata";case"EDIT_COMMENT_METADATA_ERROR":return"Could not edit comment metadata";case"MARK_THREAD_AS_RESOLVED_ERROR":return"Could not mark thread as resolved";case"MARK_THREAD_AS_UNRESOLVED_ERROR":return"Could not mark thread as unresolved";case"SUBSCRIBE_TO_THREAD_ERROR":return"Could not subscribe to thread";case"UNSUBSCRIBE_FROM_THREAD_ERROR":return"Could not unsubscribe from thread";case"CREATE_COMMENT_ERROR":return"Could not create new comment";case"EDIT_COMMENT_ERROR":return"Could not edit comment";case"DELETE_COMMENT_ERROR":return"Could not delete comment";case"ADD_REACTION_ERROR":return"Could not add reaction";case"REMOVE_REACTION_ERROR":return"Could not remove reaction";case"MARK_INBOX_NOTIFICATION_AS_READ_ERROR":return"Could not mark inbox notification as read";case"DELETE_INBOX_NOTIFICATION_ERROR":return"Could not delete inbox notification";case"MARK_ALL_INBOX_NOTIFICATIONS_AS_READ_ERROR":return"Could not mark all inbox notifications as read";case"DELETE_ALL_INBOX_NOTIFICATIONS_ERROR":return"Could not delete all inbox notifications";case"UPDATE_ROOM_SUBSCRIPTION_SETTINGS_ERROR":return"Could not update room subscription settings";case"UPDATE_NOTIFICATION_SETTINGS_ERROR":return"Could not update notification settings";case"LARGE_MESSAGE_ERROR":return"Could not send large message";case"FEED_REQUEST_ERROR":return n.reason??"Feed request failed";default:return Re(n,"Unhandled case")}}function Pu(n){let e=0;return()=>`${n}:${e++}`}function Ro(n,e){return{type:"User",id:`${e.connectionId}`,key:n,payload:{connectionId:e.connectionId,id:e.id,info:e.info,presence:e.presence,isReadOnly:!e.canWrite}}}function Nu(){let n=typeof document<"u"?document:void 0,e={current:null};function t(){n?.visibilityState==="hidden"?e.current=e.current??Date.now():e.current=null}return n?.addEventListener("visibilitychange",t),[e,()=>{n?.removeEventListener("visibilitychange",t)}]}function Uu(){let n=new Map;return{append(e){for(let[t,r]of e)n.set(t,r)},take(){let e=n;return n=new Map,e}}}function $u(n,e){let t=e.roomId,r=n.initialPresence,i=n.initialStorage,s=e.roomHttpClient,[o,c]=Nu(),u={...e.delegates,canZombie(){return e.backgroundKeepAliveTimeout!==void 0&&o.current!==null&&Date.now()>o.current+e.backgroundKeepAliveTimeout&&Yr()!=="synchronizing"}},h=new ma(u,e.enableDebugLogging),l={buffer:{flushTimerID:void 0,lastFlushedAt:0,presenceUpdates:{type:"full",data:r},messages:[],storageOperations:[]},staticSessionInfoSig:new Et(null),dynamicSessionInfoSig:new Et(null),myPresence:new Ol(r),others:new Du,initialStorage:i,idFactory:null,yjsProvider:void 0,yjsProviderDidChange:ne(),pool:nu(t,{getCurrentConnectionId:M,onDispatch:C,isStorageWritable:R}),root:void 0,undoStack:[],redoStack:[],pausedHistory:null,activeBatch:null,unacknowledgedOps:new Map},m=Uu(),k=e.enableDebugLogging?Ru():void 0,O;function z(d){let f=h.authValue;if(f!==null){let v=ws(f);if(v!==O)if(O=v,f.type==="secret"){let g=f.token.parsed;l.staticSessionInfoSig.set({userId:g.uid,userInfo:g.ui})}else l.staticSessionInfoSig.set({userId:void 0,userInfo:void 0})}y.status.notify(d),te()}let B,J=!1;function se(d){d==="reconnecting"?B=setTimeout(()=>{y.lostConnection.notify("lost"),J=!0,l.others.clearOthers(),Ue({others:[{type:"reset"}]})},e.lostConnectionTimeout):(clearTimeout(B),J&&(d==="disconnected"?y.lostConnection.notify("failed"):y.lostConnection.notify("restored"),J=!1))}function _(){l.buffer.presenceUpdates={type:"full",data:{...l.myPresence.get()}},N!==null&&Wr({flush:!1}),fe()}function P(){clearTimeout(l.buffer.flushTimerID)}h.events.onMessage.subscribe(wr),h.events.statusDidChange.subscribe(z),h.events.statusDidChange.subscribe(se),h.events.didConnect.subscribe(_),h.events.didDisconnect.subscribe(P),h.events.onConnectionError.subscribe(({message:d,code:f})=>{let v="ROOM_CONNECTION_ERROR",g=new bi(d,{type:v,code:f,roomId:t});e.errorEventSource.notify(g)||process.env.NODE_ENV!=="production"&&wt(`Connection to websocket server closed. Reason: ${d} (code: ${f}).`)});function C(d,f,v){if(l.activeBatch){for(let g of d)l.activeBatch.ops.push(g);for(let[g,E]of v)l.activeBatch.updates.storageUpdates.set(g,Zi(l.activeBatch.updates.storageUpdates.get(g),E));l.activeBatch.reverseOps.pushLeft(f)}else f.length>0&&Vt(f),d.length>0&&(l.redoStack.length=0,L(d)),Ue({storageUpdates:v})}function R(){let d=l.dynamicSessionInfoSig.get()?.scopes;return d!==void 0?us(d):!0}let y={status:ne(),lostConnection:ne(),customEvent:ne(),self:ne(),myPresence:ne(),others:ne(),storageBatch:ne(),history:ne(),storageDidLoad:ne(),storageStatus:ne(),ydoc:ne(),comments:ne(),feeds:ne(),roomWillDestroy:ne()};async function F(d,f){return s.createTextMention({roomId:t,mentionId:d,mention:f})}async function G(d){return s.deleteTextMention({roomId:t,mentionId:d})}async function oe(d,f){await s.reportTextEditor({roomId:t,type:d,rootKey:f})}async function re(){return s.listTextVersions({roomId:t})}async function Q(d){return s.listTextVersionsSince({roomId:t,since:d.since,signal:d.signal})}async function me(d){return s.getTextVersion({roomId:t,versionId:d})}async function Ne(){return s.createTextVersion({roomId:t})}async function U(d){return s.executeContextualPrompt({roomId:t,...d})}function A(d){h.send(Un(d))}let j=Dn.from(l.staticSessionInfoSig,l.dynamicSessionInfoSig,l.myPresence,(d,f,v)=>{if(d===null||f===null)return null;{let g=us(f.scopes);return{connectionId:f.actor,id:d.userId,info:d.userInfo,presence:v,canWrite:g,canComment:Ea(f.scopes)}}}),Y;function te(){let d=j.get();d!==null&&d!==Y&&(y.self.notify(d),Y=d)}let Ae=Dn.from(j,d=>d!==null?Ro("Me",d):null);function De(d){if(d.size===0)throw new Error("Internal error: cannot load storage without items");if(l.root!==void 0){let g=new Map;for(let[ee,ce]of l.pool.nodes)g.set(ee,ce._serialize());let E=du(g,d),V=ue(E);Ue(V.updates)}else l.root=Ft._fromItems(d,l.pool);let f=j.get()?.canWrite??!0,v=l.root;Ms(()=>{for(let g in l.initialStorage)v.get(g)===void 0&&(f?v.set(g,lu(l.initialStorage[g])):xe(`Attempted to populate missing storage key '${g}', but current user has no write access`))})}function qe(d){l.undoStack.length>=50&&l.undoStack.shift(),l.undoStack.push(d),Bt()}function Vt(d){l.pausedHistory!==null?l.pausedHistory.pushLeft(d):qe(d)}function Ue(d){let f=d.storageUpdates,v=d.others;if(v!==void 0&&v.length>0){let g=l.others.get();for(let E of v)y.others.notify({...E,others:g})}if((d.presence??!1)&&(te(),y.myPresence.notify(l.myPresence.get())),f!==void 0&&f.size>0){let g=Array.from(f.values());y.storageBatch.notify(g)}Xr()}function M(){let d=l.dynamicSessionInfoSig.get();if(d)return d.actor;throw new Error("Internal. Tried to get connection id but connection was never open")}function X(d){let[f,v]=Il(d,ee=>ee.type==="presence"),g=v.map(ee=>ee.opId===void 0?{...ee,opId:l.pool.generateOpId()}:ee),{reverse:E,updates:V}=Me(f,g,!0);return{opsToEmit:g,reverse:E,updates:V}}function ue(d){return Me([],d,!1)}function Me(d,f,v){let g={reverse:new es,storageUpdates:new Map,presence:!1};for(let V of d){let ee={type:"presence",data:{}};for(let ce in V.data)ee.data[ce]=l.myPresence.get()[ce];if(l.myPresence.patch(V.data),l.buffer.presenceUpdates===null)l.buffer.presenceUpdates={type:"partial",data:V.data};else for(let ce in V.data)l.buffer.presenceUpdates.data[ce]=V.data[ce];g.reverse.pushLeft(ee),g.presence=!0}let E=new Set;for(let V of f){let ee;v?ee=0:V.opId!==void 0?(l.unacknowledgedOps.delete(V.opId),ee=2):ee=1;let ce=ct(V,ee);if(ce.modified){let Ve=ce.modified.node._id;Ve&&E.has(Ve)||(g.storageUpdates.set(q(ce.modified.node._id),Zi(g.storageUpdates.get(q(ce.modified.node._id)),ce.modified)),g.reverse.pushLeft(ce.reverse)),(V.type===H.CREATE_LIST||V.type===H.CREATE_MAP||V.type===H.CREATE_OBJECT)&&E.add(V.id)}}return{reverse:Array.from(g.reverse),updates:{storageUpdates:g.storageUpdates,presence:g.presence}}}function ct(d,f){if(Kd(d))return{modified:!1};switch(d.type){case H.DELETE_OBJECT_KEY:case H.UPDATE_OBJECT:case H.DELETE_CRDT:{let v=l.pool.nodes.get(d.id);return v===void 0?{modified:!1}:v._apply(d,f===0)}case H.SET_PARENT_KEY:{let v=l.pool.nodes.get(d.id);return v===void 0?{modified:!1}:v.parent.type==="HasParent"&&Cs(v.parent.node)?v.parent.node._setChildKey(Mr(d.parentKey),v,f):{modified:!1}}case H.CREATE_OBJECT:case H.CREATE_LIST:case H.CREATE_MAP:case H.CREATE_REGISTER:{if(d.parentId===void 0)return{modified:!1};let v=l.pool.nodes.get(d.parentId);return v===void 0?{modified:!1}:v._attachChild(d,f)}}}function Je(d,f){let v={};l.buffer.presenceUpdates===null&&(l.buffer.presenceUpdates={type:"partial",data:{}});for(let g in d){let E=d[g];E!==void 0&&(l.buffer.presenceUpdates.data[g]=E,v[g]=l.myPresence.get()[g])}l.myPresence.patch(d),l.activeBatch?(f?.addToHistory&&l.activeBatch.reverseOps.pushLeft({type:"presence",data:v}),l.activeBatch.updates.presence=!0):(fe(),f?.addToHistory&&Vt([{type:"presence",data:v}]),Ue({presence:!0}))}function Ht(d){if(d.targetActor!==void 0){let v=l.others.getUser(d.actor);l.others.setOther(d.actor,d.data);let g=l.others.getUser(d.actor);if(v===void 0&&g!==void 0)return{type:"enter",user:g}}else l.others.patchOther(d.actor,d.data);let f=l.others.getUser(d.actor);if(f)return{type:"update",updates:d.data,user:f}}function fn(d){let f=l.others.getUser(d.actor);return f?(l.others.removeConnection(d.actor),{type:"leave",user:f}):null}function Hn(d){l.dynamicSessionInfoSig.set({actor:d.actor,nonce:d.nonce,scopes:d.scopes,meta:d.meta}),l.idFactory=Pu(d.actor),te(),d.meta.showBrand===!0&&zu(e.badgeLocation??"bottom-right");for(let f of l.others.connectionIds())d.users[f]===void 0&&l.others.removeConnection(f);for(let f in d.users){let v=d.users[f],g=Number(f);l.others.setConnection(g,v.id,v.info,v.scopes)}return{type:"reset"}}function Er(){return l.undoStack.length>0}function mn(){return l.redoStack.length>0}function Bt(){Pi>0||y.history.notify({canUndo:Er(),canRedo:mn()})}function Ii(d){l.others.setConnection(d.actor,d.id,d.info,d.scopes),l.buffer.messages.push({type:Ee.UPDATE_PRESENCE,data:l.myPresence.get(),targetActor:d.actor}),fe();let f=l.others.getUser(d.actor);return f?{type:"enter",user:f}:void 0}function qr(d){return Ou(d)?d:null}function Oi(d){let f=Nt(d);return f===void 0?null:Wa(f)?ns(f.map(v=>qr(v))):ns([qr(f)])}function Ri(d){if(d.size===0)return;let f=[],v=Array.from(d.values()),g=X(v);f.push({type:Ee.UPDATE_STORAGE,ops:g.opsToEmit}),Ue(g.updates),A(f)}function Jr(d){return d.type===W.FEED_REQUEST_FAILED}function wr(d){if(typeof d.data!="string")return;let f=Oi(d.data);if(f===null||f.length===0)return;let v={storageUpdates:new Map,others:[]};for(let g of f)switch(g.type){case W.USER_JOINED:{let E=Ii(g);E&&v.others.push(E);break}case W.UPDATE_PRESENCE:{let E=Ht(g);E&&v.others.push(E);break}case W.BROADCASTED_EVENT:{let E=l.others.get();y.customEvent.notify({connectionId:g.actor,user:g.actor<0?null:E.find(V=>V.connectionId===g.actor)??null,event:g.event});break}case W.USER_LEFT:{let E=fn(g);E&&v.others.push(E);break}case W.UPDATE_YDOC:{y.ydoc.notify(g);break}case W.ROOM_STATE:{v.others.push(Hn(g));break}case W.STORAGE_CHUNK:k?.lap(),m.append(Jd(g.nodes));break;case W.STORAGE_STREAM_END:{let E=k?.stop();if(E){let V=ce=>`${ce.toFixed(1)}ms`,ee=E.laps.slice(1);xe(`Storage chunk arrival: ${[`total=${V(E.total)}`,`first=${V(E.laps[0])}`,`rest.n=${ee.length}`,`rest.avg=${V(ee.reduce((ce,Ve)=>ce+Ve,0)/ee.length)}`,`rest.max=${V(ee.reduce((ce,Ve)=>Math.max(ce,Ve),0))}`].join(", ")}`)}lt(m.take());break}case W.UPDATE_STORAGE:{let E=ue(g.ops);for(let[V,ee]of E.updates.storageUpdates)v.storageUpdates.set(V,Zi(v.storageUpdates.get(V),ee));break}case W.REJECT_STORAGE_OP:{if(ra("Storage mutation rejection error",g.reason),process.env.NODE_ENV!=="production")throw new Error(`Storage mutations rejected by server: ${g.reason}`);break}case W.THREAD_CREATED:case W.THREAD_DELETED:case W.THREAD_METADATA_UPDATED:case W.THREAD_UPDATED:case W.COMMENT_REACTION_ADDED:case W.COMMENT_REACTION_REMOVED:case W.COMMENT_CREATED:case W.COMMENT_EDITED:case W.COMMENT_DELETED:case W.COMMENT_METADATA_UPDATED:{y.comments.notify(g);break}case W.FEEDS_LIST:{let E=g,V=pe.get(E.requestId);V&&(V.resolve({feeds:E.feeds,nextCursor:E.nextCursor}),pe.delete(E.requestId)),y.feeds.notify(E);break}case W.FEEDS_ADDED:{let E=g;y.feeds.notify(E),Te(E);break}case W.FEEDS_UPDATED:{let E=g;y.feeds.notify(E),Te(E);break}case W.FEED_DELETED:{y.feeds.notify(g),Te(g);break}case W.FEED_MESSAGES_LIST:{let E=g,V=Ie.get(E.requestId);V&&(V.resolve({messages:E.messages,nextCursor:E.nextCursor}),Ie.delete(E.requestId)),y.feeds.notify(E);break}case W.FEED_MESSAGES_ADDED:{let E=g;y.feeds.notify(E),Te(E);break}case W.FEED_MESSAGES_UPDATED:{let E=g;y.feeds.notify(E),Te(E);break}case W.FEED_MESSAGES_DELETED:{y.feeds.notify(g),Te(g);break}case W.FEED_REQUEST_FAILED:{if(!Jr(g))break;let{requestId:E,code:V,reason:ee}=g,ce=new bi(ee??"Feed request failed",{type:"FEED_REQUEST_ERROR",roomId:t,requestId:E,code:V,reason:ee});if(ge.has(E))Oe(E,"error",ce);else if(pe.has(E)){let Ve=pe.get(E);pe.delete(E),Ve?.reject(ce)}else if(Ie.has(E)){let Ve=Ie.get(E);Ie.delete(E),Ve?.reject(ce)}y.feeds.notify(g);break}case W.STORAGE_STATE_V7:default:break}Ue(v)}function fe(){let d=l.buffer.storageOperations;if(d.length>0){for(let g of d)l.unacknowledgedOps.set(g.opId,g);Xr()}if(h.getStatus()!=="connected"){l.buffer.storageOperations=[];return}let f=Date.now(),v=f-l.buffer.lastFlushedAt;if(v>=e.throttleDelay){let g=Li();if(g.length===0)return;A(g),l.buffer={flushTimerID:void 0,lastFlushedAt:f,messages:[],storageOperations:[],presenceUpdates:null}}else clearTimeout(l.buffer.flushTimerID),l.buffer.flushTimerID=setTimeout(fe,e.throttleDelay-v)}function Li(){let d=[];l.buffer.presenceUpdates&&d.push(l.buffer.presenceUpdates.type==="full"?{type:Ee.UPDATE_PRESENCE,targetActor:-1,data:l.buffer.presenceUpdates.data}:{type:Ee.UPDATE_PRESENCE,data:l.buffer.presenceUpdates.data});for(let f of l.buffer.messages)d.push(f);return l.buffer.storageOperations.length>0&&d.push({type:Ee.UPDATE_STORAGE,ops:l.buffer.storageOperations}),d}function p(d,f,v){let g={type:Ee.UPDATE_YDOC,update:d,guid:f,v2:v};l.buffer.messages.push(g),y.ydoc.notify(g),fe()}function w(d,f={shouldQueueEventIfNotReady:!1}){h.getStatus()!=="connected"&&!f.shouldQueueEventIfNotReady||(l.buffer.messages.push({type:Ee.BROADCAST_EVENT,event:d}),fe())}function L(d){let{storageOperations:f}=l.buffer;for(let v of d)f.push(v);fe()}let N=null,be=null,pe=new Map,Ie=new Map,ge=new Map,Fe=new Map;function Oe(d,f,v){let g=ge.get(d);if(g!==void 0){if(clearTimeout(g.timeoutId),ge.delete(d),g.kind==="add-message"&&!g.expectedClientMessageId){let E=Fe.get(g.feedId);if(E!==void 0){let V=E.indexOf(d);V>=0&&E.splice(V,1),E.length===0&&Fe.delete(g.feedId)}}f==="ok"?g.resolve():g.reject(v??new Error("Feed mutation failed"))}}function ae(d,f,v,g){let{promise:E,resolve:V,reject:ee}=ar(),ce=setTimeout(()=>{ge.has(d)&&Oe(d,"error",new Error("Feed mutation timeout"))},ts);if(ge.set(d,{resolve:V,reject:ee,timeoutId:ce,kind:f,feedId:v,messageId:g?.messageId,expectedClientMessageId:g?.expectedClientMessageId}),f==="add-message"&&g?.expectedClientMessageId===void 0){let Ve=Fe.get(v)??[];Ve.push(d),Fe.set(v,Ve)}return E}function Te(d){switch(d.type){case W.FEEDS_ADDED:{for(let f of d.feeds)for(let[v,g]of[...ge])if(g.kind==="add-feed"&&g.feedId===f.feedId){Oe(v,"ok");break}break}case W.FEEDS_UPDATED:{for(let f of d.feeds)for(let[v,g]of[...ge])g.kind==="update-feed"&&g.feedId===f.feedId&&Oe(v,"ok");break}case W.FEED_DELETED:{for(let[f,v]of[...ge])if(v.kind==="delete-feed"&&v.feedId===d.feedId){Oe(f,"ok");break}break}case W.FEED_MESSAGES_ADDED:{for(let f of d.messages){let v=!1;for(let[g,E]of[...ge])if(E.kind==="add-message"&&E.feedId===d.feedId&&E.expectedClientMessageId===f.id){Oe(g,"ok"),v=!0;break}if(!v){let E=Fe.get(d.feedId)?.[0];if(E!==void 0){let V=ge.get(E);V?.kind==="add-message"&&V.expectedClientMessageId===void 0&&Oe(E,"ok")}}}break}case W.FEED_MESSAGES_UPDATED:{for(let f of d.messages)for(let[v,g]of[...ge])g.kind==="update-message"&&g.feedId===d.feedId&&g.messageId===f.id&&Oe(v,"ok");break}case W.FEED_MESSAGES_DELETED:{for(let f of d.messageIds)for(let[v,g]of[...ge])g.kind==="delete-message"&&g.feedId===d.feedId&&g.messageId===f&&Oe(v,"ok");break}default:break}}function lt(d){let f=new Map(l.unacknowledgedOps);De(d),Ri(f),be?.(),Xr(),y.storageDidLoad.notify()}async function et(){if(!h.authValue)return;let d=new Map(await s.streamStorage({roomId:t}));lt(d)}function Wr(d){let f=l.buffer.messages;e.unstable_streamData?et():f.some(v=>v.type===Ee.FETCH_STORAGE)||(f.push({type:Ee.FETCH_STORAGE}),m.take(),k?.start()),d.flush&&fe()}function Gr(){return N===null&&(Wr({flush:!0}),N=new Promise(d=>{be=d}),Xr()),N}function Bn(){let d=l.root;return d!==void 0?d:(Gr(),null)}async function gn(){return l.root!==void 0?Promise.resolve({root:l.root}):(await Gr(),{root:q(l.root)})}function Di(d,f,v){l.buffer.messages.find(g=>g.type===Ee.FETCH_YDOC&&g.vector===d&&g.guid===f&&g.v2===v)||l.buffer.messages.push({type:Ee.FETCH_YDOC,vector:d,guid:f,v2:v}),fe()}async function Mi(d){let f=ze(),{promise:v,resolve:g,reject:E}=ar();pe.set(f,{resolve:g,reject:E});let V={type:Ee.FETCH_FEEDS,requestId:f,cursor:d?.cursor,since:d?.since,limit:d?.limit,metadata:d?.metadata};return l.buffer.messages.push(V),fe(),setTimeout(()=>{pe.has(f)&&(pe.delete(f),E(new Error("Feeds fetch timeout")))},ts),v}async function uc(d,f){let v=ze(),{promise:g,resolve:E,reject:V}=ar();Ie.set(v,{resolve:E,reject:V});let ee={type:Ee.FETCH_FEED_MESSAGES,requestId:v,feedId:d,cursor:f?.cursor,since:f?.since,limit:f?.limit};return l.buffer.messages.push(ee),fe(),setTimeout(()=>{Ie.has(v)&&(Ie.delete(v),V(new Error("Feed messages fetch timeout")))},ts),g}function hc(d,f){let v=ze(),g=ae(v,"add-feed",d),E={type:Ee.ADD_FEED,requestId:v,feedId:d,metadata:f?.metadata,createdAt:f?.createdAt};return l.buffer.messages.push(E),fe(),g}function pc(d,f){let v=ze(),g=ae(v,"update-feed",d),E={type:Ee.UPDATE_FEED,requestId:v,feedId:d,metadata:f};return l.buffer.messages.push(E),fe(),g}function fc(d){let f=ze(),v=ae(f,"delete-feed",d),g={type:Ee.DELETE_FEED,requestId:f,feedId:d};return l.buffer.messages.push(g),fe(),v}function mc(d,f,v){let g=ze(),E=ae(g,"add-message",d,{expectedClientMessageId:v?.id}),V={type:Ee.ADD_FEED_MESSAGE,requestId:g,feedId:d,data:f,id:v?.id,createdAt:v?.createdAt};return l.buffer.messages.push(V),fe(),E}function gc(d,f,v,g){let E=ze(),V=ae(E,"update-message",d,{messageId:f}),ee={type:Ee.UPDATE_FEED_MESSAGE,requestId:E,feedId:d,messageId:f,data:v,updatedAt:g?.updatedAt};return l.buffer.messages.push(ee),fe(),V}function vc(d,f){let v=ze(),g=ae(v,"delete-message",d,{messageId:f}),E={type:Ee.DELETE_FEED_MESSAGE,requestId:v,feedId:d,messageId:f};return l.buffer.messages.push(E),fe(),g}function yc(){if(l.activeBatch)throw new Error("undo is not allowed during a batch");let d=l.undoStack.pop();if(d===void 0)return;l.pausedHistory=null;let f=X(d);Ue(f.updates),l.redoStack.push(f.reverse),Bt();for(let v of f.opsToEmit)l.buffer.storageOperations.push(v);fe()}function bc(){if(l.activeBatch)throw new Error("redo is not allowed during a batch");let d=l.redoStack.pop();if(d===void 0)return;l.pausedHistory=null;let f=X(d);Ue(f.updates),l.undoStack.push(f.reverse),Bt();for(let v of f.opsToEmit)l.buffer.storageOperations.push(v);fe()}function Ec(){l.undoStack.length=0,l.redoStack.length=0}function wc(d){if(l.activeBatch)return d();let f;l.activeBatch={ops:[],updates:{storageUpdates:new Map,presence:!1,others:[]},reverseOps:new es,scheduleHistoryResume:!1};try{f=d()}finally{let v=l.activeBatch;l.activeBatch=null,v.reverseOps.length>0&&Vt(Array.from(v.reverseOps)),v.scheduleHistoryResume&&Ds(),v.ops.length>0&&(l.redoStack.length=0),v.ops.length>0&&L(v.ops),Ue(v.updates),fe()}return f}function Sc(){l.pausedHistory===null&&(l.pausedHistory=new es)}function Ds(){let d=l.pausedHistory;l.pausedHistory=null,d!==null&&d.length>0&&qe(Array.from(d))}function Cc(){if(l.activeBatch!==null){l.activeBatch.scheduleHistoryResume=!0;return}Ds()}let Pi=0;function Ms(d){let f=l.undoStack,v=l.redoStack,g=[],E=[];l.undoStack=g,l.redoStack=E,Pi++;try{return d()}finally{if(Pi--,l.undoStack!==g||l.redoStack!==E)throw new Error("unexpected stack swap during history.disable()");l.undoStack=f,l.redoStack=v}}let Ps=e.createSyncSource();function Yr(){return l.root===void 0?N===null?"not-loaded":"loading":l.unacknowledgedOps.size===0?"synchronized":"synchronizing"}let Ns=Yr();function Xr(){let d=Yr();Ns!==d&&(Ns=d,y.storageStatus.notify(d)),Ps.setSyncStatus(d==="synchronizing"?"synchronizing":"synchronized")}function Us(){return j.get()!==null}async function xc(){for(;!Us();){let{promise:d,resolve:f}=ar(),v=Ni.self.subscribeOnce(f),g=Ni.status.subscribeOnce(f);await d,v(),g()}}function $s(){return Bn()!==null}async function Ac(){for(;!$s();)await gn()}let Tc=Dn.from(l.others.signal,d=>d.map((f,v)=>Ro(`Other ${v}`,f))),Ni={status:y.status.observable,lostConnection:y.lostConnection.observable,customEvent:y.customEvent.observable,others:y.others.observable,self:y.self.observable,myPresence:y.myPresence.observable,storageBatch:y.storageBatch.observable,history:y.history.observable,storageDidLoad:y.storageDidLoad.observable,storageStatus:y.storageStatus.observable,ydoc:y.ydoc.observable,comments:y.comments.observable,feeds:y.feeds.observable,roomWillDestroy:y.roomWillDestroy.observable};async function kc(d){return s.getThreadsSince({roomId:t,since:d.since,signal:d.signal})}async function _c(d){return s.getThreads({roomId:t,query:d?.query,cursor:d?.cursor})}async function zc(d){return s.getThread({roomId:t,threadId:d})}async function Ic(d){return s.createThread({roomId:t,threadId:d.threadId,commentId:d.commentId,metadata:d.metadata,body:d.body,commentMetadata:d.commentMetadata,attachmentIds:d.attachmentIds})}async function Oc(d){return s.deleteThread({roomId:t,threadId:d})}async function Rc({metadata:d,threadId:f}){return s.editThreadMetadata({roomId:t,threadId:f,metadata:d})}async function Lc({threadId:d,commentId:f,metadata:v}){return s.editCommentMetadata({roomId:t,threadId:d,commentId:f,metadata:v})}async function Dc(d){return s.markThreadAsResolved({roomId:t,threadId:d})}async function Mc(d){return s.markThreadAsUnresolved({roomId:t,threadId:d})}async function Pc(d){return s.subscribeToThread({roomId:t,threadId:d})}async function Nc(d){return s.unsubscribeFromThread({roomId:t,threadId:d})}async function Uc(d){return s.createComment({roomId:t,threadId:d.threadId,commentId:d.commentId,body:d.body,metadata:d.metadata,attachmentIds:d.attachmentIds})}async function $c(d){return s.editComment({roomId:t,threadId:d.threadId,commentId:d.commentId,body:d.body,metadata:d.metadata,attachmentIds:d.attachmentIds})}async function Fc({threadId:d,commentId:f}){return s.deleteComment({roomId:t,threadId:d,commentId:f})}async function Vc({threadId:d,commentId:f,emoji:v}){return s.addReaction({roomId:t,threadId:d,commentId:f,emoji:v})}async function Hc({threadId:d,commentId:f,emoji:v}){return await s.removeReaction({roomId:t,threadId:d,commentId:f,emoji:v})}function Bc(d){return{type:"localAttachment",status:"idle",id:Yl(),name:d.name,size:d.size,mimeType:d.type,file:d}}async function Kc(d,f={}){return s.uploadAttachment({roomId:t,attachment:d,signal:f.signal})}function jc(d){return s.getAttachmentUrl({roomId:t,attachmentId:d})}function Fs(d){return s.getSubscriptionSettings({roomId:t,signal:d?.signal})}function Vs(d){return s.updateSubscriptionSettings({roomId:t,settings:d})}async function qc(d){await s.markRoomInboxNotificationAsRead({roomId:t,inboxNotificationId:d})}let Hs=e.createSyncSource();function Ui(d){return Hs.setSyncStatus(d==="synchronizing"||d==="loading"?"synchronizing":"synchronized")}return Object.defineProperty({[Ct]:{get presenceBuffer(){return yr(l.buffer.presenceUpdates?.data??null)},get undoStack(){return yr(l.undoStack)},get nodeCount(){return l.pool.nodes.size},getYjsProvider(){return l.yjsProvider},setYjsProvider(d){l.yjsProvider?.off("status",Ui),l.yjsProvider=d,d?.on("status",Ui),l.yjsProviderDidChange.notify()},yjsProviderDidChange:l.yjsProviderDidChange.observable,reportTextEditor:oe,createTextMention:F,deleteTextMention:G,listTextVersions:re,listTextVersionsSince:Q,getTextVersion:me,createTextVersion:Ne,executeContextualPrompt:U,getSelf_forDevTools:()=>Ae.get(),getOthers_forDevTools:()=>Tc.get(),simulate:{explicitClose:d=>h._privateSendMachineEvent({type:"EXPLICIT_SOCKET_CLOSE",event:d}),rawSend:d=>h.send(d),incomingMessage:d=>wr(new MessageEvent("message",{data:d}))},attachmentUrlsStore:s.getOrCreateAttachmentUrlsStore(t)},id:t,subscribe:Fu(t,y,e.errorEventSource),connect:()=>h.connect(),reconnect:()=>h.reconnect(),disconnect:()=>h.disconnect(),destroy:()=>{pe.forEach(v=>v.reject(new Error("Room destroyed"))),Ie.forEach(v=>v.reject(new Error("Room destroyed")));let{roomWillDestroy:d,...f}=y;for(let v of Object.values(f))v.dispose();y.roomWillDestroy.notify(),l.yjsProvider?.off("status",Ui),Ps.destroy(),Hs.destroy(),c(),h.destroy(),d.dispose()},updatePresence:Je,updateYDoc:p,broadcastEvent:w,batch:wc,history:{undo:yc,redo:bc,canUndo:Er,canRedo:mn,clear:Ec,pause:Sc,resume:Cc,disable:Ms},fetchYDoc:Di,fetchFeeds:Mi,fetchFeedMessages:uc,addFeed:hc,updateFeed:pc,deleteFeed:fc,addFeedMessage:mc,updateFeedMessage:gc,deleteFeedMessage:vc,getStorage:gn,getStorageSnapshot:Bn,getStorageStatus:Yr,isPresenceReady:Us,isStorageReady:$s,waitUntilPresenceReady:oo(xc),waitUntilStorageReady:oo(Ac),events:Ni,getStatus:()=>h.getStatus(),getSelf:()=>j.get(),getPresence:()=>l.myPresence.get(),getOthers:()=>l.others.get(),getThreads:_c,getThreadsSince:kc,getThread:zc,createThread:Ic,deleteThread:Oc,editThreadMetadata:Rc,markThreadAsResolved:Dc,markThreadAsUnresolved:Mc,subscribeToThread:Pc,unsubscribeFromThread:Nc,createComment:Uc,editComment:$c,editCommentMetadata:Lc,deleteComment:Fc,addReaction:Vc,removeReaction:Hc,prepareAttachment:Bc,uploadAttachment:Kc,getAttachmentUrl:jc,getNotificationSettings:Fs,getSubscriptionSettings:Fs,updateNotificationSettings:Vs,updateSubscriptionSettings:Vs,markInboxNotificationAsRead:qc},Ct,{enumerable:!1})}function Fu(n,e,t){function r(o,c){return e.storageBatch.subscribe(u=>{let h=u.filter(l=>Fa(l.node,o));h.length>0&&c(h)})}function i(o,c){return e.storageBatch.subscribe(u=>{for(let h of u)h.node._id===o._id&&c(h.node)})}function s(o,c,u){if(typeof o=="string"&&Vu(o)){if(typeof c!="function")throw new Error("Second argument must be a callback function");let h=c;switch(o){case"event":return e.customEvent.subscribe(h);case"my-presence":return e.myPresence.subscribe(h);case"others":{let l=h;return e.others.subscribe(m=>{let{others:k,...O}=m;return l(k,O)})}case"error":return t.subscribe(l=>{if(l.roomId===n)return h(l)});case"status":return e.status.subscribe(h);case"lost-connection":return e.lostConnection.subscribe(h);case"history":return e.history.subscribe(h);case"storage-status":return e.storageStatus.subscribe(h);case"comments":return e.comments.subscribe(h);default:return Re(o,`"${String(o)}" is not a valid event name`)}}if(c===void 0||typeof o=="function")if(typeof o=="function"){let h=o;return e.storageBatch.subscribe(h)}else throw new Error("Please specify a listener callback");if(ve(o)){let h=o;return u?.isDeep?r(h,c):i(h,c)}throw new Error(`${String(o)} is not a value that can be subscribed to.`)}return s}function Vu(n){return n==="my-presence"||n==="others"||n==="event"||n==="error"||n==="history"||n==="status"||n==="storage-status"||n==="lost-connection"||n==="connection"||n==="comments"}function Hu(n,e){return async()=>e.getAuthValue({requestedScope:"room:read",roomId:n})}function Bu(n,e,t){return r=>{let i=t??(typeof WebSocket>"u"?void 0:WebSocket);if(i===void 0)throw new Ut("To use Liveblocks client in a non-DOM environment, you need to provide a WebSocket polyfill.");let s=new URL(e);if(s.protocol=s.protocol==="http:"?"ws":"wss",s.pathname="/v8",s.searchParams.set("roomId",n),r.type==="secret")s.searchParams.set("tok",r.token.raw);else if(r.type==="public")s.searchParams.set("pubkey",r.publicApiKey);else return Re(r,"Unhandled case");return s.searchParams.set("version",ln||"dev"),new i(s.toString())}}function th(n){return typeof n=="string"&&n.startsWith("http")?n:Bd}function nh(n){try{return new URL(n).hostname==="localhost"}catch{return!1}}function Ts(n){let e=n,t=th(e.baseUrl),r=process.env.NODE_ENV!=="production"&&nh(t)&&e.__DANGEROUSLY_disableThrottling?0:rh(e.throttle??qu),i=ih(e.lostConnectionTimeout??Xu),s=Lo(e.backgroundKeepAliveTimeout),o=new Et(void 0),c=Fd(n,M=>{o.set(()=>M.uid)}),u=e.polyfills?.fetch||globalThis.fetch?.bind(globalThis),h=td({baseUrl:t,fetchPolyfill:u,currentUserId:o,authManager:c}),l=new Map,m=Dd({userId:o.get(),lostConnectionTimeout:i,backgroundKeepAliveTimeout:Lo(e.backgroundKeepAliveTimeout),polyfills:e.polyfills,delegates:{createSocket:Md(t,e.polyfills?.WebSocket),authenticate:async()=>{let M=await c.getAuthValue({requestedScope:"room:read"});if(M.type==="public")throw new Ut("Cannot use AI Copilots with a public API key");return M},canZombie:()=>!1}});function k(M){ku(M.id),l.delete(M.id),M.destroy()}function O(M){let X=()=>{let ue=X;M.unsubs.delete(ue)?M.unsubs.size===0&&k(M.room):xe("This leave function was already called. Calling it more than once has no effect.")};return M.unsubs.add(X),{room:M.room,leave:X}}function z(M,...X){let ue=l.get(M);if(ue!==void 0)return O(ue);let Me=X[0]??{},ct=(typeof Me.initialPresence=="function"?Me.initialPresence(M):Me.initialPresence)??{},Je=(typeof Me.initialStorage=="function"?Me.initialStorage(M):Me.initialStorage)??{},Ht;if(xs(Je)){let mn={};for(let Bt of Je.keys())mn[Bt]=Je.get(Bt);Ht=mn}else Ht=Je;let fn=$u({initialPresence:ct,initialStorage:Ht},{roomId:M,throttleDelay:r,lostConnectionTimeout:i,backgroundKeepAliveTimeout:s,polyfills:e.polyfills,delegates:e.mockedDelegates??{createSocket:Bu(M,t,e.polyfills?.WebSocket),authenticate:Hu(M,c)},enableDebugLogging:e.enableDebugLogging,baseUrl:t,errorEventSource:Y,unstable_streamData:!!e.unstable_streamData,roomHttpClient:h,createSyncSource:De,badgeLocation:e.badgeLocation??"bottom-right"}),Hn={room:fn,unsubs:new Set};if(l.set(M,Hn),mu(()=>Array.from(l.keys())),Tu(M,fn),Me.autoConnect??!0){if(typeof atob>"u"){if(e.polyfills?.atob===void 0)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");global.atob=e.polyfills.atob}fn.connect()}return O(Hn)}function B(M){let X=l.get(M)?.room;return X||null}function J(){c.reset(),o.set(()=>{});for(let{room:M}of l.values())ld(M.getStatus())||M.reconnect()}let se=e.resolveUsers,_=new Wt(async M=>{let X=M.flat(),ue=await se?.({userIds:X});return Qi(!se,"Set the resolveUsers option in createClient to specify user info."),ue??X.map(()=>{})},{delay:Zu}),P=cr(_);function C(M){P.invalidate(M)}let R=e.resolveRoomsInfo,y=new Wt(async M=>{let X=M.flat(),ue=await R?.({roomIds:X});return Qi(!R,"Set the resolveRoomsInfo option in createClient to specify room info."),ue??X.map(()=>{})},{delay:Qu}),F=cr(y);function G(M){F.invalidate(M)}let oe=e.resolveGroupsInfo,re=new Wt(async M=>{let X=M.flat(),ue=await oe?.({groupIds:X});return Qi(!oe,"Set the resolveGroupsInfo option in createClient to specify group info."),ue??X.map(()=>{})},{delay:eh}),Q=cr(re);function me(M){Q.invalidate(M)}let Ne=new Map;function U(){Ne.clear()}let A=[],j=new Et("synchronized"),Y=ne();function te(){let M=j.get();return M==="synchronizing"?M:"synchronized"}function Ae(){j.set(A.some(M=>M.get()==="synchronizing")?"synchronizing":A.some(M=>M.get()==="has-local-changes")?"has-local-changes":"synchronized")}function De(){let M=new Et("synchronized");A.push(M);let X=M.subscribe(()=>Ae());function ue(ct){M.set(ct)}function Me(){X();let ct=A.findIndex(Je=>Je===M);if(ct>-1){let[Je]=A.splice(ct,1);Je.get()!=="synchronized"&&Ae()}}return{setSyncStatus:ue,destroy:Me}}{let M=ue=>{e.preventUnsavedChanges&&j.get()!=="synchronized"&&ue.preventDefault()};(typeof window<"u"?window:void 0)?.addEventListener("beforeunload",M)}async function qe(M){let X=await h.getNotificationSettings(M);return Oo(X)}async function Vt(M){let X=await h.updateNotificationSettings(M);return Oo(X)}let Ue=Object.defineProperty({enterRoom:z,getRoom:B,logout:J,getInboxNotifications:h.getInboxNotifications,getInboxNotificationsSince:h.getInboxNotificationsSince,getUnreadInboxNotificationsCount:h.getUnreadInboxNotificationsCount,markAllInboxNotificationsAsRead:h.markAllInboxNotificationsAsRead,markInboxNotificationAsRead:h.markInboxNotificationAsRead,deleteAllInboxNotifications:h.deleteAllInboxNotifications,deleteInboxNotification:h.deleteInboxNotification,getNotificationSettings:qe,updateNotificationSettings:Vt,resolvers:{invalidateUsers:C,invalidateRoomsInfo:G,invalidateGroupsInfo:me,invalidateMentionSuggestions:U},getSyncStatus:te,events:{error:Y,syncStatus:j},[Ct]:{currentUserId:o,mentionSuggestionsCache:Ne,ai:m,resolveMentionSuggestions:e.resolveMentionSuggestions,usersStore:P,roomsInfoStore:F,groupsInfoStore:Q,getRoomIds(){return Array.from(l.keys())},httpClient:h,as:()=>Ue,createSyncSource:De,emitError:(M,X)=>{let ue=bi.from(M,X);Y.notify(ue)||wt(ue.message)}}},Ct,{enumerable:!1});return Ue}function ks(n,e,t,r,i){if(typeof e!="number"||e<t||r!==void 0&&e>r)throw new Error(r!==void 0?`${n} should be between ${i??t} and ${r}.`:`${n} should be at least ${i??t}.`);return e}function Lo(n){if(n!==void 0)return ks("backgroundKeepAliveTimeout",n,Ju)}function rh(n){return ks("throttle",n,Ku,ju)}function ih(n){return ks("lostConnectionTimeout",n,Wu,Yu,Gu)}var El,wl,Xo,ln,Sl,ci,Cl,xl,ro,bt,wn,gi,sr,xn,Do,dt,Mo,bs,_t,Po,Et,Ol,Rl,Gt,zt,ut,ur,hr,Pr,rs,Mn,Dn,An,No,Dr,K,ht,Mt,or,It,Tn,Uo,Dl,Nl,ea,Ul,xe,wt,$l,ra,vi,Vl,Bl,Kl,pt,Nr,Ur,$r,kn,xt,os,oa,as,$o,Wt,ze,ql,Jl,Wl,Fr,Fo,Qe,Xl,ho,po,fo,mo,Zl,Vr,Hr,Ze,kr,_r,Vo,nd,Yt,Ho,sd,od,He,rt,ft,Ot,_n,Se,Xt,zn,In,pr,ye,ca,la,da,cs,ls,tr,Bo,ad,W,ha,li,dd,ud,hd,pd,fd,Ut,md,di,Ge,Br,Ko,ma,Ct,wo,bd,Ed,wd,Sd,Rt,On,fr,Rn,Zt,Kr,$e,je,zr,ga,va,ya,jo,Cd,Ye,it,mt,mr,gt,Lt,qo,kd,_d,Qt,en,gr,Ei,ba,Jo,zd,Lr,$d,Bd,H,he,Le,un,Aa,Ci,lr,Wd,ui,Yi,Qd,To,st,tn,nn,vt,jr,rn,Wo,xi,Ln,vr,hn,x,Pe,sn,I,nt,Jt,Ir,Ta,ka,rr,_a,za,Ia,Oa,Ra,La,Da,We,fi,mi,Pn,pn,le,on,Nn,Fn,Xi,Z,we,_e,Ke,wi,Pa,$t,Na,Ua,fs,Ft,Ba,Ka,ja,qa,ko,ms,yu,bu,gs,zo,Io,qt,zu,ot,yt,Dt,Xe,Go,es,Ee,Be,an,Pt,Ga,Rr,Yo,Du,bi,ts,Ku,ju,qu,Ju,Wu,Gu,Yu,Xu,Zu,Qu,eh,sh,Xh,oh,Zh,_s=vn(()=>{"use strict";El=Object.defineProperty,wl=(n,e)=>{for(var t in e)El(n,t,{get:e[t],enumerable:!0})},Xo="@liveblocks/core",ln="3.19.1",Sl="esm",ci=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Cl="https://liveblocks.io/docs/errors/cross-linked",xl="https://liveblocks.io/docs/errors/dupes",ro=" ";bt=process.env.NODE_ENV==="production"?(n=>n):Object.freeze;wn=Symbol("kSinks"),gi=Symbol("kTrigger"),sr=null,xn=null;bs=(Mo=class{constructor(n){ke(this,"equals");T(this,dt);ke(this,Do);this.equals=n??Object.is,b(this,dt,ne()),this[wn]=new Set,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this),this.subscribeOnce=this.subscribeOnce.bind(this)}dispose(){a(this,dt).dispose(),b(this,dt,"(disposed)"),this.equals="(disposed)"}get hasWatchers(){if(a(this,dt).count()>0)return!0;for(let n of this[wn])if(n.hasWatchers)return!0;return!1}[(Do=wn,gi)](){a(this,dt).notify();for(let n of this[wn])ys(n)}subscribe(n){return a(this,dt).count()===0&&this.get(),a(this,dt).subscribe(n)}subscribeOnce(n){let e=this.subscribe(()=>(e(),n()));return e}waitUntil(){throw new Error("waitUntil not supported on Signals")}markSinksDirty(){for(let n of this[wn])n.markDirty()}addSink(n){this[wn].add(n)}removeSink(n){this[wn].delete(n)}asReadonly(){return this}},dt=new WeakMap,Mo),Et=(Po=class extends bs{constructor(e,t){super(t);T(this,_t);b(this,_t,bt(e))}dispose(){super.dispose(),b(this,_t,"(disposed)")}get(){return xn?.add(this),a(this,_t)}set(e){dn(()=>{typeof e=="function"&&(e=e(a(this,_t))),this.equals(a(this,_t),e)||(b(this,_t,bt(e)),this.markSinksDirty(),ys(this))})}},_t=new WeakMap,Po),Ol=class extends Et{constructor(n){super(bt(Si(n)))}set(){throw new Error("Don't call .set() directly, use .patch()")}patch(n){super.set(e=>Qo(e,n))}},Rl=Symbol(),Dn=(Mn=class extends bs{constructor(t,r,i){super(i);T(this,Pr);T(this,Gt);T(this,zt);T(this,ut);T(this,ur);T(this,hr);b(this,zt,!0),b(this,Gt,Rl),b(this,ur,t),b(this,ut,new Set),b(this,hr,r)}static from(...t){let r=t.pop();if(typeof r!="function"&&St("Invalid .from() call, last argument expected to be a function"),typeof t[t.length-1]=="function"){let i=r,s=t.pop();return new Mn(t,s,i)}else{let i=r;return new Mn(t,i)}}dispose(){for(let t of a(this,ut))t.removeSink(this);b(this,Gt,"(disposed)"),b(this,ut,"(disposed)"),b(this,ur,"(disposed)"),b(this,hr,"(disposed)")}get isDirty(){return a(this,zt)}markDirty(){a(this,zt)||(b(this,zt,!0),this.markSinksDirty())}get(){return a(this,zt)&&S(this,Pr,rs).call(this),xn?.add(this),a(this,Gt)}[gi](){if(!this.hasWatchers)return;S(this,Pr,rs).call(this)&&super[gi]()}},Gt=new WeakMap,zt=new WeakMap,ut=new WeakMap,ur=new WeakMap,hr=new WeakMap,Pr=new WeakSet,rs=function(){let t=xn,r;xn=new Set;try{r=a(this,hr).call(this,...a(this,ur).map(i=>i.get()))}finally{let i=a(this,ut);b(this,ut,new Set);for(let s of xn)a(this,ut).add(s),i.delete(s);for(let s of i)s.removeSink(this);for(let s of a(this,ut))s.addSink(this);xn=t}return b(this,zt,!1),this.equals(a(this,Gt),r)?!1:(b(this,Gt,r),!0)},Mn),Dr=(No=class extends bs{constructor(e){super();T(this,An);b(this,An,e)}dispose(){super.dispose(),b(this,An,"(disposed)")}get(){return xn?.add(this),a(this,An)}mutate(e){dn(()=>{let t=e?e(a(this,An)):!0;t!==null&&typeof t=="object"&&"then"in t&&St("MutableSignal.mutate() does not support async callbacks"),t!==!1&&(this.markSinksDirty(),ys(this))})}},An=new WeakMap,No);or=(Mt=class{constructor(e,t){T(this,K);T(this,ht);b(this,ht,t),b(this,K,e)}static with(e){return Mt.fromAlreadySorted([],e)}static from(e,t){let r=new Mt([],t);for(let i of e)r.add(i);return r}static fromAlreadySorted(e,t){return new Mt(e,t)}clone(){return new Mt(a(this,K).slice(),a(this,ht))}add(e){let t=Ll(a(this,K),e,a(this,ht));return a(this,K).splice(t,0,e),t}clear(){let e=a(this,K).length>0;return a(this,K).length=0,e}removeBy(e,t=Number.POSITIVE_INFINITY){let r=0;for(let i=0;i<a(this,K).length;i++)if(e(a(this,K)[i])){if(a(this,K).splice(i,1),r++,r>=t)break;i--}return r>0}remove(e){let t=a(this,K).indexOf(e);return t>=0?(a(this,K).splice(t,1),!0):!1}removeAt(e){if(e<0||e>=a(this,K).length)return;let[t]=a(this,K).splice(e,1);return t}reposition(e){let t=a(this,K).indexOf(e);if(t<0)throw new Error("Cannot reposition item that is not in the list");let r=a(this,K)[t-1],i=a(this,K)[t+1],s=r===void 0||a(this,ht).call(this,r,e),o=i===void 0||a(this,ht).call(this,e,i);if(s&&o)return t;let c=t;for(;c>0&&a(this,ht).call(this,e,a(this,K)[c-1]);)a(this,K)[c]=a(this,K)[c-1],c--;if(c<t)return a(this,K)[c]=e,c;for(;c<a(this,K).length-1&&!a(this,ht).call(this,e,a(this,K)[c+1]);)a(this,K)[c]=a(this,K)[c+1],c++;return c!==t&&(a(this,K)[c]=e),c}at(e){return a(this,K)[e]}get length(){return a(this,K).length}*filter(e){for(let t of a(this,K))e(t)&&(yield t)}*findAllRight(e){for(let t=a(this,K).length-1;t>=0;t--){let r=a(this,K)[t];e(r,t)&&(yield r)}}[Symbol.iterator](){return a(this,K)[Symbol.iterator]()}*iterReversed(){for(let e=a(this,K).length-1;e>=0;e--)yield a(this,K)[e]}find(e,t){let r=this.findIndex(e,t);return r>-1?a(this,K).at(r):void 0}findIndex(e,t=0){for(let r=Math.max(0,t);r<a(this,K).length;r++)if(e(a(this,K)[r],r))return r;return-1}findRight(e,t){let r=this.findIndexRight(e,t);return r>-1?a(this,K).at(r):void 0}findIndexRight(e,t=a(this,K).length-1){for(let r=Math.min(t,a(this,K).length-1);r>=0;r--)if(e(a(this,K)[r],r))return r;return-1}get rawArray(){return a(this,K)}},K=new WeakMap,ht=new WeakMap,Mt),Dl=(Uo=class{constructor(){T(this,It);T(this,Tn);ke(this,"signal");b(this,It,new Map),b(this,Tn,or.from([],(n,e)=>{let t=e.lastMessageAt??e.createdAt,r=n.lastMessageAt??n.createdAt;return t<r?!0:t===r?e.id<n.id:!1})),this.signal=new Dr(this)}getEvenIfDeleted(n){return this.signal.get(),a(this,It).get(n)}markDeleted(n){let e=a(this,It).get(n);e===void 0||e.deletedAt!==void 0||this.upsert({...e,deletedAt:new Date().toISOString()})}upsert(n){this.signal.mutate(()=>{let e=a(this,It).get(n.id);if(e!==void 0){if(e.deletedAt!==void 0)return!1;a(this,Tn).remove(e),a(this,It).delete(e.id)}return n.deletedAt===void 0&&a(this,Tn).add(n),a(this,It).set(n.id,n),!0})}findMany(n){return Array.from(a(this,Tn).filter(e=>{if(n.metadata===void 0)return!0;for(let[t,r]of Object.entries(n.metadata))if(r===null){if(t in e.metadata)return!1}else if(typeof r=="string"){if(e.metadata[t]!==r)return!1}else{let i=e.metadata[t];if(!Array.isArray(i)||!r.every(s=>i.includes(s)))return!1}return!0}))}},It=new WeakMap,Tn=new WeakMap,Uo);Nl={};wl(Nl,{error:()=>wt,errorWithTitle:()=>ra,warn:()=>xe,warnWithTitle:()=>$l});ea="background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;",Ul="font-weight:600";xe=ta("warn"),wt=ta("error");$l=na("warn"),ra=na("error");vi=class ia extends Error{constructor(t,r,i){super(t);ke(this,"response");ke(this,"details");this.name="HttpError",this.response=r,this.details=i}static async fromResponse(t){let r;try{r=await t.text()}catch{}let i=r?Nt(r):void 0,s;Ce(i)&&(s=i);let o="";o||(o=typeof s?.message=="string"?s.message:""),o||(o=typeof s?.error=="string"?s.error:""),i===void 0&&(o||(o=r||"")),o||(o=t.statusText);let c;try{c=new URL(t.url).pathname}catch{}o+=c!==void 0?` (got status ${t.status} from ${c})`:` (got status ${t.status})`;let u=s;return new ia(o,t,u)}get status(){return this.response.status}},Vl=n=>n instanceof vi&&n.status>=400&&n.status<500;Bl=50,Kl=class{constructor(n){ke(this,"input");ke(this,"resolve");ke(this,"reject");ke(this,"promise");this.input=n;let{promise:e,resolve:t,reject:r}=ar();this.promise=e,this.resolve=t,this.reject=r}},Wt=($o=class{constructor(n,e){T(this,xt);T(this,pt,[]);T(this,Nr);T(this,Ur);T(this,$r);T(this,kn);ke(this,"error",!1);b(this,Nr,n),b(this,Ur,e.size??Bl),b(this,$r,e.delay)}get(n){let e=a(this,pt).find(r=>ss(r.input)===ss(n));if(e)return e.promise;let t=new Kl(n);return a(this,pt).push(t),S(this,xt,oa).call(this),t.promise}clear(){b(this,pt,[]),this.error=!1,S(this,xt,os).call(this)}},pt=new WeakMap,Nr=new WeakMap,Ur=new WeakMap,$r=new WeakMap,kn=new WeakMap,xt=new WeakSet,os=function(){a(this,kn)!==void 0&&(clearTimeout(a(this,kn)),b(this,kn,void 0))},oa=function(){a(this,pt).length===a(this,Ur)?S(this,xt,as).call(this):a(this,pt).length===1&&(S(this,xt,os).call(this),b(this,kn,setTimeout(()=>{S(this,xt,as).call(this)},a(this,$r))))},as=async function(){if(a(this,pt).length===0)return;let n=a(this,pt).splice(0),e=n.map(t=>t.input);try{let t=await a(this,Nr).call(this,e);this.error=!1,n.forEach((r,i)=>{let s=t?.[i];Array.isArray(t)?n.length!==t.length?r.reject(new Error(`Callback must return an array of the same length as the number of provided items. Expected ${n.length}, but got ${t.length}.`)):s instanceof Error?r.reject(s):r.resolve(s):r.reject(new Error("Callback must return an array."))})}catch(t){this.error=!0,n.forEach(r=>{r.reject(t)})}},$o);ze=(n=21)=>crypto.getRandomValues(new Uint8Array(n)).reduce((e,t)=>e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t<63?"_":"-",""),ql="th",Jl="cm",Wl="at";Qe=(Fo=class extends Map{constructor(e,t){super(t);T(this,Fr);b(this,Fr,e)}getOrCreate(e,t){if(super.has(e))return super.get(e);{let i=(t??a(this,Fr)??St("DefaultMap used without a factory function"))(e);return this.set(e,i),i}}},Fr=new WeakMap,Fo),Xl=/^[a-zA-Z_][a-zA-Z0-9_]*$/;ho=n=>{let e=[];return n.forEach(([t,r])=>{e.push({key:t,operator:":",value:r})}),e},po=n=>{let e=[];return n.forEach(([t,r])=>{"startsWith"in r&&typeof r.startsWith=="string"&&e.push({key:t,operator:"^",value:r.startsWith}),"lt"in r&&typeof r.lt=="number"&&e.push({key:t,operator:"<",value:r.lt}),"gt"in r&&typeof r.gt=="number"&&e.push({key:t,operator:">",value:r.gt}),"gte"in r&&typeof r.gte=="number"&&e.push({key:t,operator:">=",value:r.gte}),"lte"in r&&typeof r.lte=="number"&&e.push({key:t,operator:"<=",value:r.lte})}),e},fo=n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null,mo=(n,e)=>e?`${n}[${aa(e)}]`:n,Zl=n=>!n||n.toString().trim()==="";nd=(Vo=class{constructor(n,e){T(this,Ze);T(this,Vr);T(this,Hr);b(this,Vr,n),b(this,Hr,e)}async rawGet(n,e,t,r){return await S(this,Ze,kr).call(this,n,e,r,t)}async rawPost(n,e,t){return await S(this,Ze,kr).call(this,n,e,{method:"POST",body:Un(t)})}async rawDelete(n,e){return await S(this,Ze,kr).call(this,n,e,{method:"DELETE"})}async get(n,e,t,r){return await S(this,Ze,_r).call(this,n,e,r,t)}async post(n,e,t,r,i){return await S(this,Ze,_r).call(this,n,e,{...r,method:"POST",body:Un(t)},i)}async delete(n,e){return await S(this,Ze,_r).call(this,n,e,{method:"DELETE"})}async putBlob(n,e,t,r,i){return await S(this,Ze,_r).call(this,n,e,{...i,method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:t},r)}},Vr=new WeakMap,Hr=new WeakMap,Ze=new WeakSet,kr=async function(n,e,t,r){n.startsWith("/v2/c/")||St("This client can only be used to make /v2/c/* requests");let i=ed(a(this,Vr),n,r),s=await a(this,Hr).call(this,i,{...t,headers:{"Content-Type":"application/json; charset=utf-8",...t?.headers,Authorization:`Bearer ${ws(e)}`,"X-LB-Client":ln||"dev"}}),o=s.headers.get("X-LB-Warn");if(o){let c=t?.method?.toUpperCase()??"GET",u=`${o} (${c} ${n})`;s.ok?xe(u):wt(u)}return s},_r=async function(n,e,t,r){let i=await S(this,Ze,kr).call(this,n,e,t,r);if(!i.ok)throw await vi.fromResponse(i);let s;try{s=await i.json()}catch{s={}}return s},Vo);sd=(Ho=class{constructor(n){T(this,Yt);b(this,Yt,n)}get current(){return a(this,Yt)}allowPatching(n){let e=this,t=!0,r={...a(this,Yt),patch(i){if(t){b(e,Yt,Object.assign({},a(e,Yt),i));for(let s of Object.entries(i)){let[o,c]=s;o!=="patch"&&(this[o]=c)}}else throw new Error("Can no longer patch stale context")}};n(r),t=!1}},Yt=new WeakMap,Ho),od=1,ad=(Bo=class{constructor(n){T(this,ye);ke(this,"id");T(this,He);T(this,rt);T(this,ft);T(this,Ot);T(this,_n);T(this,Se);ke(this,"events");T(this,Xt);T(this,zn);T(this,In);T(this,pr);this.id=od++,b(this,He,0),b(this,Ot,null),b(this,ft,new Set),b(this,In,new Map),b(this,Xt,[]),b(this,zn,[]),b(this,pr,new Set),b(this,_n,new Map),b(this,rt,new sd(n)),b(this,Se,{didReceiveEvent:ne(),willTransition:ne(),didIgnoreEvent:ne(),willExitState:ne(),didEnterState:ne(),didExitState:ne()}),this.events={didReceiveEvent:a(this,Se).didReceiveEvent.observable,willTransition:a(this,Se).willTransition.observable,didIgnoreEvent:a(this,Se).didIgnoreEvent.observable,willExitState:a(this,Se).willExitState.observable,didEnterState:a(this,Se).didEnterState.observable,didExitState:a(this,Se).didExitState.observable}}get currentState(){if(a(this,Ot)===null)throw a(this,He)===0?new Error("Not started yet"):new Error("Already stopped");return a(this,Ot)}start(){if(a(this,He)!==0)throw new Error("State machine has already started");return b(this,He,1),b(this,Ot,a(this,ye,ca)),S(this,ye,ls).call(this,null),this}stop(){if(a(this,He)!==1)throw new Error("Cannot stop a state machine that hasn't started yet");S(this,ye,cs).call(this,null),b(this,He,2),b(this,Ot,null)}get context(){return a(this,rt).current}addState(n){if(a(this,He)!==0)throw new Error("Already started");return a(this,ft).add(n),this}onEnter(n,e){if(a(this,He)!==0)throw new Error("Already started");if(a(this,In).has(n))throw new Error(`enter/exit function for ${n} already exists`);return a(this,In).set(n,e),this}onEnterAsync(n,e,t,r,i){return this.onEnter(n,()=>{let s=new AbortController,o=s.signal,c=i?setTimeout(()=>{let h=new Error("Timed out");S(this,ye,tr).call(this,{type:"ASYNC_ERROR",reason:h},r)},i):void 0,u=!1;return e(a(this,rt).current,o).then(h=>{o.aborted||(u=!0,S(this,ye,tr).call(this,{type:"ASYNC_OK",data:h},t))},h=>{o.aborted||(u=!0,S(this,ye,tr).call(this,{type:"ASYNC_ERROR",reason:h},r))}),()=>{clearTimeout(c),u||s.abort()}})}addTransitions(n,e){if(a(this,He)!==0)throw new Error("Already started");for(let t of S(this,ye,la).call(this,n)){let r=a(this,_n).get(t);r===void 0&&(r=new Map,a(this,_n).set(t,r));for(let[i,s]of Object.entries(e)){if(r.has(i))throw new Error(`Trying to set transition "${i}" on "${t}" (via "${n}"), but a transition already exists there.`);let o=s;if(a(this,pr).add(i),o!==void 0){let c=typeof o=="function"?o:()=>o;r.set(i,c)}}}return this}addTimedTransition(n,e,t){return this.onEnter(n,()=>{let r=typeof e=="function"?e(a(this,rt).current):e,i=setTimeout(()=>{S(this,ye,tr).call(this,{type:"TIMER"},t)},r);return()=>{clearTimeout(i)}})}send(n){if(!a(this,pr).has(n.type))throw new Error(`Invalid event ${JSON.stringify(n.type)}`);if(a(this,He)===2)return;let e=S(this,ye,da).call(this,n.type);if(e!==void 0)return S(this,ye,tr).call(this,n,e);a(this,Se).didIgnoreEvent.notify(n)}},He=new WeakMap,rt=new WeakMap,ft=new WeakMap,Ot=new WeakMap,_n=new WeakMap,Se=new WeakMap,Xt=new WeakMap,zn=new WeakMap,In=new WeakMap,pr=new WeakMap,ye=new WeakSet,ca=function(){let n=a(this,ft).values()[Symbol.iterator]().next();if(n.done)throw new Error("No states defined yet");return n.value},la=function(n){let e=[];if(n==="*")for(let t of a(this,ft))e.push(t);else if(n.endsWith(".*")){let t=n.slice(0,-1);for(let r of a(this,ft))r.startsWith(t)&&e.push(r)}else{let t=n;a(this,ft).has(t)&&e.push(t)}if(e.length===0)throw new Error(`No states match ${JSON.stringify(n)}`);return e},da=function(n){return a(this,_n).get(this.currentState)?.get(n)},cs=function(n){a(this,Se).willExitState.notify(this.currentState);let e=performance.now(),t=this.currentState.split(".");a(this,rt).allowPatching(r=>{n=n??a(this,Xt).length;for(let i=0;i<n;i++){a(this,Xt).pop()?.(r);let s=a(this,zn).pop();if(s!==void 0&&a(this,Se).didExitState.count()>0){let o=a(this,zn).length;if(o===0)continue;let c=o===t.length?this.currentState:`${t.slice(0,o).join(".")}.*`;a(this,Se).didExitState.notify({state:c,durationMs:e-s})}}})},ls=function(n){let e=id(this.currentState,n??this.currentState.split(".").length+1),t=performance.now();a(this,rt).allowPatching(r=>{for(let i of e){let o=a(this,In).get(i)?.(r);typeof o=="function"?a(this,Xt).push(o):a(this,Xt).push(null),a(this,zn).push(t)}}),a(this,Se).didEnterState.notify(this.currentState)},tr=function(n,e){a(this,Se).didReceiveEvent.notify(n);let t=this.currentState,i=(typeof e=="function"?e:()=>e)(n,a(this,rt).current),s,o;if(i===null){a(this,Se).didIgnoreEvent.notify(n);return}if(typeof i=="string"?s=i:(s=i.target,o=Array.isArray(i.effect)?i.effect:[i.effect]),!a(this,ft).has(s))throw new Error(`Invalid next state name: ${JSON.stringify(s)}`);a(this,Se).willTransition.notify({from:t,to:s});let[c,u]=rd(this.currentState,s);if(c>0&&S(this,ye,cs).call(this,c),b(this,Ot,s),o!==void 0){let h=o;a(this,rt).allowPatching(l=>{for(let m of h)typeof m=="function"?m(l,n):l.patch(m)})}u>0&&S(this,ye,ls).call(this,u)},Bo),W=Object.freeze({UPDATE_PRESENCE:100,USER_JOINED:101,USER_LEFT:102,BROADCASTED_EVENT:103,ROOM_STATE:104,STORAGE_STATE_V7:200,STORAGE_CHUNK:210,STORAGE_STREAM_END:211,UPDATE_STORAGE:201,UPDATE_YDOC:300,THREAD_CREATED:400,THREAD_DELETED:407,THREAD_METADATA_UPDATED:401,THREAD_UPDATED:408,COMMENT_CREATED:402,COMMENT_EDITED:403,COMMENT_DELETED:404,COMMENT_REACTION_ADDED:405,COMMENT_REACTION_REMOVED:406,COMMENT_METADATA_UPDATED:409,FEEDS_LIST:500,FEEDS_ADDED:501,FEEDS_UPDATED:502,FEED_DELETED:503,FEED_MESSAGES_LIST:504,FEED_MESSAGES_ADDED:505,FEED_MESSAGES_UPDATED:506,FEED_MESSAGES_DELETED:507,FEED_REQUEST_FAILED:508,REJECT_STORAGE_OP:299});ha=[250,500,1e3,2e3,4e3,8e3,1e4],li=ha[0]-1,dd=[2e3,3e4,6e4,3e5],ud=3e4,hd=2e3,pd=1e4,fd=2e4,Ut=class extends Error{constructor(n){super(n)}};md=nr(1,"Connection to WebSocket closed permanently. Won't retry.");di=n=>e=>e.patch(n);ma=(Ko=class{constructor(n,e=!1,t=!0){T(this,Ge);T(this,Br);ke(this,"events");let{machine:r,events:i,cleanups:s}=yd(n,{waitForActorId:t,enableDebugLogging:e});b(this,Ge,r),this.events=i,b(this,Br,s)}getStatus(){try{return ua(a(this,Ge))}catch{return"initial"}}get authValue(){return a(this,Ge).context.authValue}connect(){a(this,Ge).send({type:"CONNECT"})}reconnect(){a(this,Ge).send({type:"RECONNECT"})}disconnect(){a(this,Ge).send({type:"DISCONNECT"})}destroy(){a(this,Ge).stop();let n;for(;n=a(this,Br).pop();)n()}send(n){let e=a(this,Ge).context?.socket;e===null?xe("Cannot send: not connected yet",n):e.readyState!==1?xe("Cannot send: WebSocket no longer open",n):e.send(n)}_privateSendMachineEvent(n){a(this,Ge).send(n)}},Ge=new WeakMap,Br=new WeakMap,Ko),Ct=Symbol(),wo=Object.freeze({}),bd=Array.from(new Set("null")),Ed=Array.from(new Set("true")),wd=Array.from(new Set("false")),Sd=Array.from(new Set("nulltruefalse"));Cd=(jo=class{constructor(n=""){T(this,je);T(this,Rt,"");T(this,On);T(this,fr,0);T(this,Rn,!1);T(this,Zt,-1);T(this,Kr,-1);T(this,$e,[]);this.append(n)}get source(){return a(this,Rt)}get json(){return a(this,On)===void 0&&b(this,On,S(this,je,ya).call(this)),a(this,On)}append(n){n&&(a(this,Rt)===""&&(n=n.trimStart()),b(this,Rt,a(this,Rt)+n),b(this,On,void 0))}},Rt=new WeakMap,On=new WeakMap,fr=new WeakMap,Rn=new WeakMap,Zt=new WeakMap,Kr=new WeakMap,$e=new WeakMap,je=new WeakSet,zr=function(){return a(this,Zt)>=0},ga=function(n){if(a(this,je,zr))return"";let e=n.charAt(n.length-1);if(e==="")return"";if(e==="-")return"0";if(!Sd.includes(e))return"";if(bd.includes(e)){if(n.endsWith("nul"))return"l";if(n.endsWith("nu"))return"ll";if(n.endsWith("n"))return"ull"}if(Ed.includes(e)){if(n.endsWith("tru"))return"e";if(n.endsWith("tr"))return"ue";if(n.endsWith("t"))return"rue"}if(wd.includes(e)){if(n.endsWith("fals"))return"e";if(n.endsWith("fal"))return"se";if(n.endsWith("fa"))return"lse";if(n.endsWith("f"))return"alse"}return""},va=function(){let n=a(this,Rt).slice(a(this,fr));for(let e=0;e<n.length;e++){let t=n[e],r=a(this,fr)+e;a(this,je,zr)?a(this,Rn)?b(this,Rn,!1):t==="\\"?b(this,Rn,!0):t==='"'&&(b(this,Kr,a(this,Zt)),b(this,Zt,-1)):t==='"'?b(this,Zt,r):t==="{"?a(this,$e).push("}"):t==="["?a(this,$e).push("]"):t==="}"&&a(this,$e).length>0&&a(this,$e)[a(this,$e).length-1]==="}"?a(this,$e).pop():t==="]"&&a(this,$e).length>0&&a(this,$e)[a(this,$e).length-1]==="]"&&a(this,$e).pop()}b(this,fr,a(this,Rt).length)},ya=function(){S(this,je,va).call(this);let n=a(this,Rt);if(n.charAt(0)!=="{")return wo;if(n.endsWith("}")){let t=Nt(n);if(t)return t}a(this,je,zr)&&(a(this,Rn)&&(n=n.slice(0,-1)),n+='"'),n=n.trimEnd(),n=Wi(n,",."),n=n+S(this,je,ga).call(this,n);let e=a(this,$e).reduceRight((t,r)=>t+r,"");{let t=Nt(n+e);if(t)return t}return a(this,je,zr)?n=n.slice(0,a(this,Zt)):(n=Wi(n,":"),n.endsWith('"')&&(n=n.slice(0,a(this,Kr)))),n=Wi(n,","),n+=e,Nt(n)??wo},jo);kd=(qo=class{constructor(n,e,t){T(this,Ye);T(this,it);T(this,mt);T(this,mr);T(this,gt);T(this,Lt);b(this,mr,n),b(this,gt,e),b(this,Lt,t),b(this,Ye,new Map),b(this,it,new Qe(()=>new Set)),b(this,mt,or.with(t))}get(n){return a(this,Ye).get(n)}getOrThrow(n){return this.get(n)??St(`Item with id ${n} not found`)}get sorted(){return a(this,mt)}getParentId(n){let e=this.getOrThrow(n);return a(this,gt).call(this,e)}getParent(n){let e=this.getParentId(n);return e?this.getOrThrow(e):null}getChildren(n){let e=a(this,it).get(n);return e?Array.from(e).map(t=>a(this,Ye).get(t)):[]}*walkUp(n,e){let r=n;do{let i=this.getOrThrow(r);(!e||e(i))&&(yield i),r=a(this,gt).call(this,i)}while(r!==null)}*walkLeft(n,e){let t=this.getOrThrow(n),r=or.from(this.getSiblings(n),a(this,Lt));for(let i of r.iterReversed())a(this,Lt).call(this,t,i)||(!e||e(i))&&(yield i)}*walkRight(n,e){let t=this.getOrThrow(n),r=or.from(this.getSiblings(n),a(this,Lt));for(let i of r)a(this,Lt).call(this,i,t)||(!e||e(i))&&(yield i)}*walkDown(n,e){let t=or.from(this.getChildren(n),a(this,Lt)).rawArray;for(let r=t.length-1;r>=0;r--){let i=t[r];yield*this.walkDown(a(this,mr).call(this,i),e),(!e||e(i))&&(yield i)}}getSiblings(n){let e=this.getOrThrow(n),t=this.getParentId(n);return this.getChildren(t).filter(r=>r!==e)}[Symbol.iterator](){return a(this,mt)[Symbol.iterator]()}upsert(n){let e=a(this,mr).call(this,n),t=a(this,Ye).get(e);if(t){if(a(this,gt).call(this,t)!==a(this,gt).call(this,n))throw new Error("Cannot upsert parent ID changes that change the tree structure. Remove the entry first, and recreate it");a(this,mt).remove(t)}a(this,Ye).set(e,n),a(this,mt).add(n);let r=a(this,gt).call(this,n);a(this,it).getOrCreate(r).add(e)}remove(n){let e=a(this,Ye).get(n);if(!e)return!1;if(a(this,it).get(n))throw new Error(`Cannot remove item '${n}' while it still has children. Remove children first.`);let r=a(this,gt).call(this,e),i=a(this,it).get(r);return i&&(i.delete(n),i.size===0&&a(this,it).delete(r)),a(this,mt).remove(e),a(this,it).delete(n),a(this,Ye).delete(n),!0}clear(){return a(this,Ye).size===0?!1:(a(this,it).clear(),a(this,Ye).clear(),a(this,mt).clear(),!0)}},Ye=new WeakMap,it=new WeakMap,mt=new WeakMap,mr=new WeakMap,gt=new WeakMap,Lt=new WeakMap,qo),_d=4e3,zd=(Jo=class{constructor(){T(this,Ei);T(this,Qt);T(this,en);T(this,gr);b(this,Qt,new Set),b(this,en,new Qe(()=>new Map)),b(this,gr,void 0)}registerLayer(n){let e=n;return a(this,Qt).has(e)&&St(`Layer '${e}' already exists, provide a unique layer id`),a(this,Qt).add(e),e}deregisterLayer(n){a(this,Qt).delete(n);let e=!1;for(let[t,r]of a(this,en))r.delete(n)&&(e=!0),r.size===0&&a(this,en).delete(t);e&&this.invalidate()}get(){return a(this,gr)??b(this,gr,S(this,Ei,ba).call(this))}invalidate(){b(this,gr,void 0)}updateKnowledge(n,e,t){a(this,Qt).has(n)||St(`Unknown layer key: ${n}`),a(this,en).getOrCreate(e).set(n,t),this.invalidate()}},Qt=new WeakMap,en=new WeakMap,gr=new WeakMap,Ei=new WeakSet,ba=function(){return Array.from(a(this,en).values()).flatMap(n=>Array.from(n.values()).slice(-1).filter(Fl))},Jo);Lr=Symbol("*");$d=[400,401,403,404,405,410,412,414,422,431,451];Bd="https://api.liveblocks.io",H=Object.freeze({INIT:0,SET_PARENT_KEY:1,CREATE_LIST:2,UPDATE_OBJECT:3,CREATE_OBJECT:4,DELETE_CRDT:5,DELETE_OBJECT_KEY:6,CREATE_MAP:7,CREATE_REGISTER:8});he=Object.freeze({OBJECT:0,LIST:1,MAP:2,REGISTER:3});Le=32,un=126,Aa=un-Le+1,Ci=Ss(0),lr=Ss(1),Wd=Ci+Ss(-1);ui=2,Yi=3;Qd=Le+1;To=Object.freeze({type:"NoParent"});xi=(Wo=class{constructor(){T(this,st);T(this,tn);T(this,nn,To);T(this,vt);T(this,jr);T(this,rn)}_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 Re(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 Re(this.parent,"Unknown state")}}get _pool(){return a(this,st)}get roomId(){return a(this,st)?a(this,st).roomId:null}get _id(){return a(this,tn)}get parent(){return a(this,nn)}get _parentKey(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":return null;case"Orphaned":return this.parent.oldKey;default:return Re(this.parent,"Unknown state")}}_apply(n,e){return n.type===H.DELETE_CRDT?this.parent.type==="HasParent"?this.parent.node._detachChild(this):{modified:!1}:{modified:!1}}_setParentLink(n,e){switch(this.parent.type){case"HasParent":if(this.parent.node!==n)throw new Error("Cannot set parent: node already has a parent");b(this,nn,Ao(n,e));return;case"Orphaned":case"NoParent":{b(this,nn,Ao(n,e));return}default:return Re(this.parent,"Unknown state")}}_attach(n,e){if(a(this,tn)||a(this,st))throw new Error("Cannot attach node: already attached");e.addNode(n,this),b(this,tn,n),b(this,st,e)}_detach(){switch(a(this,st)&&a(this,tn)&&a(this,st).deleteNode(a(this,tn)),this.parent.type){case"HasParent":{b(this,nn,ru(this.parent.key,this.parent.pos));break}case"NoParent":{b(this,nn,To);break}case"Orphaned":break;default:Re(this.parent,"Unknown state")}b(this,st,void 0)}_toOpsWithOpId(n,e,t){return this._toOps(n,e).map(r=>({opId:t.generateOpId(),...r}))}invalidate(){(a(this,vt)!==void 0||a(this,rn)!==void 0)&&(b(this,vt,void 0),b(this,rn,void 0),this.parent.type==="HasParent"&&this.parent.node.invalidate())}toTreeNode(n){return(a(this,rn)===void 0||a(this,jr)!==n)&&(b(this,jr,n),b(this,rn,this._toTreeNode(n))),a(this,rn)}hasCache(n){return a(this,vt)!==void 0&&a(this,vt)===n}toJSON(){return a(this,vt)===void 0&&b(this,vt,this._toJSON()),a(this,vt)}},st=new WeakMap,tn=new WeakMap,nn=new WeakMap,vt=new WeakMap,jr=new WeakMap,rn=new WeakMap,Wo),hn=(vr=class extends xi{constructor(t){super();T(this,Ln);b(this,Ln,t)}get data(){return a(this,Ln)}static _deserialize([t,r],i,s){let o=new vr(r.data);return o._attach(t,s),o}_toOps(t,r){if(this._id===void 0)throw new Error("Cannot serialize register if parentId or parentKey is undefined");return[{type:H.CREATE_REGISTER,id:this._id,parentId:t,parentKey:r,data:this.data}]}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveRegister if parent is missing");return{type:he.REGISTER,parentId:q(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key,data:this.data}}_attachChild(t){throw new Error("Method not implemented.")}_detachChild(t){throw new Error("Method not implemented.")}_apply(t,r){return super._apply(t,r)}_toTreeNode(t){return{type:"Json",id:this._id??ze(),key:t,payload:a(this,Ln)}}_toJSON(){return a(this,Ln)}clone(){return yr(this.data)}},Ln=new WeakMap,vr);pn=(Pn=class extends xi{constructor(t){super();T(this,I);T(this,x);T(this,Pe);T(this,sn);b(this,Pe,new WeakSet),b(this,sn,new Map);let r=[],i;for(let s of t){let o=kt(i),c=dr(s);c._setParentLink(this,o),r.push(c),i=o}b(this,x,or.fromAlreadySorted(r,iu))}static _deserialize([t,r],i,s){var u;let o=new Pn([]);o._attach(t,s);let c=i.get(t);if(c===void 0)return o;for(let h of c){let l=h[1],m=Va(h,i,s);m._setParentLink(o,l.parentKey),S(u=o,I,nt).call(u,m)}return o}_toOps(t,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=[],s={id:this._id,type:H.CREATE_LIST,parentId:t,parentKey:r};i.push(s);for(let o of a(this,x)){let c=o._getParentKeyOrThrow(),u=pi(o._toOps(this._id,c),void 0);for(let h of u)i.push(h)}return i}_indexOfPosition(t){return a(this,x).findIndex(r=>r._getParentKeyOrThrow()===t)}_attach(t,r){super._attach(t,r);for(let i of a(this,x))i._attach(r.generateId(),r)}_detach(){super._detach();for(let t of a(this,x))t._detach()}_attachChild(t,r){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let i;return t.intent==="set"?r===1?i=S(this,I,Ta).call(this,t):r===2?i=S(this,I,ka).call(this,t):i=S(this,I,Oa).call(this,t):r===1?i=S(this,I,_a).call(this,t):r===2?i=S(this,I,za).call(this,t):i=S(this,I,Ia).call(this,t),i.modified!==!1&&this.invalidate(),i}_detachChild(t){if(t){let r=q(t._parentKey),i=t._toOps(q(this._id),r),s=a(this,x).findIndex(c=>c===t);if(s===-1)return{modified:!1};let o=a(this,x).at(s);return a(this,x).remove(t),this.invalidate(),t._detach(),{modified:ie(this,[hi(s,o)]),reverse:i}}return{modified:!1}}_setChildKey(t,r,i){return i===1?S(this,I,Ra).call(this,t,r):i===2?S(this,I,La).call(this,t,r):S(this,I,Da).call(this,t,r)}_apply(t,r){return super._apply(t,r)}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveList if parent is missing");return{type:he.LIST,parentId:q(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get length(){return a(this,x).length}push(t){return this._pool?.assertStorageIsWritable(),this.insert(t,this.length)}insert(t,r){if(this._pool?.assertStorageIsWritable(),r<0||r>a(this,x).length)throw new Error(`Cannot insert list item at index "${r}". index should be between 0 and ${a(this,x).length}`);let i=a(this,x).at(r-1)?._parentPos,s=a(this,x).at(r)?._parentPos,o=kt(i,s),c=dr(t);if(c._setParentLink(this,o),S(this,I,nt).call(this,c),this._pool&&this._id){let u=this._pool.generateId();c._attach(u,this._pool),this._pool.dispatch(c._toOpsWithOpId(this._id,o,this._pool),[{type:H.DELETE_CRDT,id:u}],new Map([[this._id,ie(this,[tt(r,c)])]]))}}move(t,r){if(this._pool?.assertStorageIsWritable(),r<0)throw new Error("targetIndex cannot be less than 0");if(r>=a(this,x).length)throw new Error("targetIndex cannot be greater or equal than the list length");if(t<0)throw new Error("index cannot be less than 0");if(t>=a(this,x).length)throw new Error("index cannot be greater or equal than the list length");let i=null,s=null;t<r?(s=r===a(this,x).length-1?void 0:a(this,x).at(r+1)?._parentPos,i=a(this,x).at(r)._parentPos):(s=a(this,x).at(r)._parentPos,i=r===0?void 0:a(this,x).at(r-1)?._parentPos);let o=kt(i,s),c=a(this,x).at(t),u=c._getParentKeyOrThrow();if(S(this,I,Ir).call(this,t,o),this._pool&&this._id){let h=new Map([[this._id,ie(this,[Cn(t,r,c)])]]);this._pool.dispatch([{type:H.SET_PARENT_KEY,id:q(c._id),opId:this._pool.generateOpId(),parentKey:o}],[{type:H.SET_PARENT_KEY,id:q(c._id),parentKey:u}],h)}}delete(t){if(this._pool?.assertStorageIsWritable(),t<0||t>=a(this,x).length)throw new Error(`Cannot delete list item at index "${t}". index should be between 0 and ${a(this,x).length-1}`);let r=a(this,x).at(t);if(r._detach(),a(this,x).remove(r),this.invalidate(),this._pool){let i=r._id;if(i){let s=new Map;s.set(q(this._id),ie(this,[hi(t,r)])),this._pool.dispatch([{id:i,opId:this._pool.generateOpId(),type:H.DELETE_CRDT}],r._toOps(q(this._id),r._getParentKeyOrThrow()),s)}}}clear(){if(this._pool?.assertStorageIsWritable(),this._pool){let t=[],r=[],i=[];for(let o of a(this,x)){o._detach();let c=o._id;c&&(t.push({type:H.DELETE_CRDT,id:c,opId:this._pool.generateOpId()}),r.push(...o._toOps(q(this._id),o._getParentKeyOrThrow())),i.push(hi(0,o)))}a(this,x).clear(),this.invalidate();let s=new Map;s.set(q(this._id),ie(this,i)),this._pool.dispatch(t,r,s)}else{for(let t of a(this,x))t._detach();a(this,x).clear(),this.invalidate()}}set(t,r){if(this._pool?.assertStorageIsWritable(),t<0||t>=a(this,x).length)throw new Error(`Cannot set list item at index "${t}". index should be between 0 and ${a(this,x).length-1}`);let i=a(this,x).at(t),s=i._getParentKeyOrThrow(),o=i._id;i._detach();let c=dr(r);if(c._setParentLink(this,s),a(this,x).remove(i),a(this,x).add(c),this.invalidate(),this._pool&&this._id){let u=this._pool.generateId();c._attach(u,this._pool);let h=new Map;h.set(this._id,ie(this,[er(t,c)]));let l=pi(c._toOpsWithOpId(this._id,s,this._pool),o);a(this,sn).set(s,q(l[0].opId));let m=pi(i._toOps(this._id,s),u);this._pool.dispatch(l,m,h)}}every(t){return a(this,x).rawArray.every((r,i)=>t(S(this,I,We).call(this,r),i))}filter(t){let r=[];return a(this,x).rawArray.forEach((i,s)=>{let o=S(this,I,We).call(this,i);t(o,s)&&r.push(o)}),r}find(t){for(let[r,i]of a(this,x).rawArray.entries()){let s=S(this,I,We).call(this,i);if(t(s,r))return s}}findIndex(t){return a(this,x).rawArray.findIndex((r,i)=>t(S(this,I,We).call(this,r),i))}forEach(t){a(this,x).rawArray.forEach((r,i)=>t(S(this,I,We).call(this,r),i))}get(t){let r=a(this,x).at(t);return r!==void 0?S(this,I,We).call(this,r):void 0}indexOf(t,r){return a(this,x).rawArray.findIndex((i,s)=>s>=(r??0)&&S(this,I,We).call(this,i)===t)}lastIndexOf(t,r){let i=a(this,x).rawArray;for(let s=r??i.length-1;s>=0;s--)if(S(this,I,We).call(this,i[s])===t)return s;return-1}map(t){return a(this,x).rawArray.map((r,i)=>t(S(this,I,We).call(this,r),i))}some(t){return a(this,x).rawArray.some((r,i)=>t(S(this,I,We).call(this,r),i))}*[Symbol.iterator](){for(let t of a(this,x))yield S(this,I,We).call(this,t)}_toTreeNode(t){let r=[],i=0;for(let s of a(this,x))r.push(s.toTreeNode(i.toString())),i++;return{type:"LiveList",id:this._id??ze(),key:t,payload:r}}toJSON(){return super.toJSON()}_toJSON(){let t=Array.from(a(this,x),r=>r.toJSON());return bt(t)}clone(){return new Pn(Array.from(a(this,x),t=>t.clone()))}},x=new WeakMap,Pe=new WeakMap,sn=new WeakMap,I=new WeakSet,nt=function(t){let r=a(this,x).add(t);return this.invalidate(),r},Jt=function(t,r){t._setParentLink(this,r),a(this,x).reposition(t),this.invalidate()},Ir=function(t,r){let i=q(a(this,x).at(t));S(this,I,Jt).call(this,i,r)},Ta=function(t){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:r,parentKey:i}=t,s=Or(t);s._attach(r,this._pool),s._setParentLink(this,i);let o=t.deletedId,c=this._indexOfPosition(i);if(c!==-1){let u=q(a(this,x).removeAt(c));if(u._id===o)return u._detach(),a(this,x).add(s),{modified:ie(this,[er(c,s)]),reverse:[]};{a(this,Pe).add(u),a(this,x).remove(u),a(this,x).add(s);let h=[er(c,s)],l=S(this,I,rr).call(this,t.deletedId);return l&&h.push(l),{modified:ie(this,h),reverse:[]}}}else{let u=[],h=S(this,I,rr).call(this,t.deletedId);return h&&u.push(h),S(this,I,nt).call(this,s),u.push(tt(this._indexOfPosition(i),s)),{reverse:[],modified:ie(this,u)}}},ka=function(t){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let r=[],i=S(this,I,rr).call(this,t.deletedId);i&&r.push(i);let s=a(this,sn).get(t.parentKey);if(s!==void 0){if(s!==t.opId)return r.length===0?{modified:!1}:{modified:ie(this,r),reverse:[]};a(this,sn).delete(t.parentKey)}let o=this._indexOfPosition(t.parentKey),c=a(this,x).find(u=>u._id===t.id);if(c!==void 0){if(c._parentKey===t.parentKey)return{modified:r.length>0?ie(this,r):!1,reverse:[]};if(o!==-1){let l=q(a(this,x).removeAt(o));a(this,Pe).add(l),r.push(hi(o,l))}let u=a(this,x).findIndex(l=>l===c);S(this,I,Jt).call(this,c,t.parentKey);let h=a(this,x).findIndex(l=>l===c);return h!==u&&r.push(Cn(u,h,c)),{modified:r.length>0?ie(this,r):!1,reverse:[]}}else{let u=this._pool.getNode(t.id);if(u&&a(this,Pe).has(u)){u._setParentLink(this,t.parentKey),a(this,Pe).delete(u);let h=S(this,I,nt).call(this,u);return{modified:ie(this,[o===-1?tt(h,u):er(h,u),...r]),reverse:[]}}else{if(o!==-1){let m=q(a(this,x).removeAt(o));a(this,Pe).add(m)}let{newItem:h,newIndex:l}=S(this,I,fi).call(this,t,t.parentKey);return{modified:ie(this,[o===-1?tt(l,h):er(l,h),...r]),reverse:[]}}}},rr=function(t){if(t===void 0||this._pool===void 0)return null;let r=this._pool.getNode(t);if(r===void 0)return null;let i=this._detachChild(r);return i.modified===!1?null:i.modified.updates[0]},_a=function(t){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let r=Mr(t.parentKey),i=this._indexOfPosition(r);i!==-1&&S(this,I,mi).call(this,i,r);let{newItem:s,newIndex:o}=S(this,I,fi).call(this,t,r);return{modified:ie(this,[tt(o,s)]),reverse:[]}},za=function(t){let r=a(this,x).find(o=>o._id===t.id),i=Mr(t.parentKey),s=this._indexOfPosition(i);if(r){if(r._parentKey===i)return{modified:!1};{let o=a(this,x).findIndex(u=>u===r);s!==-1&&S(this,I,mi).call(this,s,i),S(this,I,Jt).call(this,r,i);let c=this._indexOfPosition(i);return c===o?{modified:!1}:{modified:ie(this,[Cn(o,c,r)]),reverse:[]}}}else{let o=q(this._pool).getNode(t.id);if(o&&a(this,Pe).has(o)){o._setParentLink(this,i),a(this,Pe).delete(o),S(this,I,nt).call(this,o);let c=this._indexOfPosition(i);return{modified:ie(this,[tt(c,o)]),reverse:[]}}else{s!==-1&&S(this,I,mi).call(this,s,i);let{newItem:c,newIndex:u}=S(this,I,fi).call(this,t,i);return{modified:ie(this,[tt(u,c)]),reverse:[]}}}},Ia=function(t){let{id:r,parentKey:i}=t,s=Or(t);if(this._pool?.getNode(r)!==void 0)return{modified:!1};s._attach(r,q(this._pool)),s._setParentLink(this,i);let o=this._indexOfPosition(i),c=i;if(o!==-1){let h=a(this,x).at(o)?._parentPos,l=a(this,x).at(o+1)?._parentPos;c=kt(h,l),s._setParentLink(this,c)}S(this,I,nt).call(this,s);let u=this._indexOfPosition(c);return{modified:ie(this,[tt(u,s)]),reverse:[{type:H.DELETE_CRDT,id:r}]}},Oa=function(t){let{id:r,parentKey:i}=t,s=Or(t);if(this._pool?.getNode(r)!==void 0)return{modified:!1};a(this,sn).set(i,q(t.opId));let o=this._indexOfPosition(i);s._attach(r,q(this._pool)),s._setParentLink(this,i);let c=i;if(o!==-1){let u=a(this,x).at(o);u._detach(),a(this,x).remove(u),a(this,x).add(s);let h=pi(u._toOps(q(this._id),i),t.id),l=[er(o,s)],m=S(this,I,rr).call(this,t.deletedId);return m&&l.push(m),{modified:ie(this,l),reverse:h}}else{S(this,I,nt).call(this,s),S(this,I,rr).call(this,t.deletedId);let u=this._indexOfPosition(c);return{reverse:[{type:H.DELETE_CRDT,id:r}],modified:ie(this,[tt(u,s)])}}},Ra=function(t,r){if(a(this,Pe).has(r)){a(this,Pe).delete(r),r._setParentLink(this,t);let o=S(this,I,nt).call(this,r);return{modified:ie(this,[tt(o,r)]),reverse:[]}}let i=r._parentKey;if(t===i)return{modified:!1};let s=this._indexOfPosition(t);if(s===-1){let o=a(this,x).findIndex(u=>u===r);S(this,I,Jt).call(this,r,t);let c=a(this,x).findIndex(u=>u===r);return c===o?{modified:!1}:{modified:ie(this,[Cn(o,c,r)]),reverse:[]}}else{S(this,I,Ir).call(this,s,kt(t,a(this,x).at(s+1)?._parentPos));let o=a(this,x).findIndex(u=>u===r);S(this,I,Jt).call(this,r,t);let c=a(this,x).findIndex(u=>u===r);return c===o?{modified:!1}:{modified:ie(this,[Cn(o,c,r)]),reverse:[]}}},La=function(t,r){let i=q(r._parentKey);if(a(this,Pe).has(r)){let s=this._indexOfPosition(t);if(a(this,Pe).delete(r),s!==-1){let c=a(this,x).at(s);c._setParentLink(this,kt(t,a(this,x).at(s+1)?._parentPos)),a(this,x).reposition(c)}r._setParentLink(this,t);let o=S(this,I,nt).call(this,r);return{modified:ie(this,[tt(o,r)]),reverse:[]}}else{if(t===i)return{modified:!1};let s=a(this,x).findIndex(u=>u===r),o=this._indexOfPosition(t);o!==-1&&S(this,I,Ir).call(this,o,kt(t,a(this,x).at(o+1)?._parentPos)),S(this,I,Jt).call(this,r,t);let c=a(this,x).findIndex(u=>u===r);return s===c?{modified:!1}:{modified:ie(this,[Cn(s,c,r)]),reverse:[]}}},Da=function(t,r){let i=q(r._parentKey),s=a(this,x).findIndex(h=>h===r),o=this._indexOfPosition(t),c=t;o!==-1&&(c=kt(t,a(this,x).at(o+1)?._parentPos)),S(this,I,Jt).call(this,r,c);let u=a(this,x).findIndex(h=>h===r);return s===u?{modified:!1}:{modified:ie(this,[Cn(s,u,r)]),reverse:[{type:H.SET_PARENT_KEY,id:q(r._id),parentKey:i}]}},We=function(t){return ir(t)},fi=function(t,r){let i=Or(t);i._attach(t.id,q(this._pool)),i._setParentLink(this,r),S(this,I,nt).call(this,i);let s=this._indexOfPosition(r);return{newItem:i,newIndex:s}},mi=function(t,r){let i=kt(r,a(this,x).length>t+1?a(this,x).at(t+1)?._parentPos:void 0);S(this,I,Ir).call(this,t,i)},Pn);Fn=(Nn=class extends xi{constructor(t){super();T(this,le);T(this,on);if(b(this,on,new Map),t){let r=[];for(let[i,s]of t){let o=dr(s);o._setParentLink(this,i),r.push([i,o])}b(this,le,new Map(r))}else b(this,le,new Map)}_toOps(t,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=[],s={id:this._id,type:H.CREATE_MAP,parentId:t,parentKey:r};i.push(s);for(let[o,c]of a(this,le))for(let u of c._toOps(this._id,o))i.push(u);return i}static _deserialize([t,r],i,s){let o=new Nn;o._attach(t,s);let c=i.get(t);if(c===void 0)return o;for(let u of c){let h=u[1],l=Va(u,i,s);l._setParentLink(o,h.parentKey),a(o,le).set(h.parentKey,l),o.invalidate()}return o}_attach(t,r){super._attach(t,r);for(let[i,s]of a(this,le))ve(s)&&s._attach(r.generateId(),r)}_attachChild(t,r){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:i,parentKey:s,opId:o}=t,c=s,u=Or(t);if(this._pool.getNode(i)!==void 0)return{modified:!1};if(r===2){let m=a(this,on).get(c);if(m===o)return a(this,on).delete(c),{modified:!1};if(m!==void 0)return{modified:!1}}else r===1&&a(this,on).delete(c);let h=a(this,le).get(c),l;if(h){let m=q(this._id);l=h._toOps(m,c),h._detach()}else l=[{type:H.DELETE_CRDT,id:i}];return u._setParentLink(this,c),u._attach(i,this._pool),a(this,le).set(c,u),this.invalidate(),{modified:{node:this,type:"LiveMap",updates:{[c]:{type:"update"}}},reverse:l}}_detach(){super._detach();for(let t of a(this,le).values())t._detach()}_detachChild(t){let r=q(this._id),i=q(t._parentKey),s=t._toOps(r,i);for(let[c,u]of a(this,le))u===t&&(a(this,le).delete(c),this.invalidate());return t._detach(),{modified:{node:this,type:"LiveMap",updates:{[i]:{type:"delete",deletedItem:ir(t)}}},reverse:s}}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveMap if parent is missing");return{type:he.MAP,parentId:q(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get(t){let r=a(this,le).get(t);if(r!==void 0)return ir(r)}set(t,r){this._pool?.assertStorageIsWritable();let i=a(this,le).get(t);i&&i._detach();let s=dr(r);if(s._setParentLink(this,t),a(this,le).set(t,s),this.invalidate(),this._pool&&this._id){let o=this._pool.generateId();s._attach(o,this._pool);let c=new Map;c.set(this._id,{node:this,type:"LiveMap",updates:{[t]:{type:"update"}}});let u=s._toOpsWithOpId(this._id,t,this._pool);a(this,on).set(t,q(u[0].opId)),this._pool.dispatch(u,i?i._toOps(this._id,t):[{type:H.DELETE_CRDT,id:o}],c)}}get size(){return a(this,le).size}has(t){return a(this,le).has(t)}delete(t){this._pool?.assertStorageIsWritable();let r=a(this,le).get(t);if(r===void 0)return!1;if(r._detach(),a(this,le).delete(t),this.invalidate(),this._pool&&r._id){let i=q(this._id),s=new Map;s.set(i,{node:this,type:"LiveMap",updates:{[t]:{type:"delete",deletedItem:ir(r)}}}),this._pool.dispatch([{type:H.DELETE_CRDT,id:r._id,opId:this._pool.generateOpId()}],r._toOps(i,t),s)}return!0}entries(){let t=a(this,le).entries();return{[Symbol.iterator](){return this},next(){let r=t.next();if(r.done)return{done:!0,value:void 0};let s=r.value[0],o=ir(r.value[1]);return{value:[s,o]}}}}[Symbol.iterator](){return this.entries()}keys(){return a(this,le).keys()}values(){let t=a(this,le).values();return{[Symbol.iterator](){return this},next(){let r=t.next();return r.done?{done:!0,value:void 0}:{value:ir(r.value)}}}}forEach(t){for(let r of this)t(r[1],r[0],this)}_toTreeNode(t){return{type:"LiveMap",id:this._id??ze(),key:t,payload:Array.from(a(this,le).entries()).map(([r,i])=>i.toTreeNode(r))}}toJSON(){return super.toJSON()}_toJSON(){let t={};for(let[r,i]of a(this,le))t[r]=i.toJSON();return bt(t)}clone(){return new Nn(Array.from(a(this,le)).map(([t,r])=>[t,r.clone()]))}},le=new WeakMap,on=new WeakMap,Nn);Xi=128*1024,Ft=(Ke=class extends xi{constructor(t={}){super();T(this,$t);T(this,Z);T(this,we,new Map);T(this,_e);b(this,_e,new Map);let r=Si(t);for(let i of Object.keys(r)){let s=r[i];ve(s)&&s._setParentLink(this,i)}b(this,Z,new Map(Object.entries(r)))}static _fromItems(t,r){var o;let[i,s]=S(o=Ke,wi,Pa).call(o,t);return Ke._deserialize(["root",i],s,r)}_toOps(t,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=[],s={type:H.CREATE_OBJECT,id:this._id,parentId:t,parentKey:r,data:{}};i.push(s);for(let[o,c]of a(this,Z))if(ve(c))for(let u of c._toOps(this._id,o))i.push(u);else s.data[o]=c;return i}static _deserialize([t,r],i,s){let o=new Ke(r.data);return o._attach(t,s),this._deserializeChildren(o,i,s)}static _deserializeChildren(t,r,i){let s=r.get(q(t._id));if(s===void 0)return t;for(let o of s){let c=au(o,r,i),u=o[1];cn(c)&&c._setParentLink(t,u.parentKey),a(t,Z).set(u.parentKey,c),t.invalidate()}return t}_attach(t,r){super._attach(t,r);for(let[i,s]of a(this,Z))ve(s)&&s._attach(r.generateId(),r)}_attachChild(t,r){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:i,opId:s,parentKey:o}=t,c=$a(t);if(this._pool.getNode(i)!==void 0)return a(this,_e).get(o)===s&&a(this,_e).delete(o),{modified:!1};if(r===0)a(this,_e).set(o,q(s));else if(a(this,_e).get(o)!==void 0)return a(this,_e).get(o)===s?(a(this,_e).delete(o),{modified:!1}):{modified:!1};let u=q(this._id),h=a(this,Z).get(o),l;return ve(h)?(l=h._toOps(u,o),h._detach()):h===void 0?l=[{type:H.DELETE_OBJECT_KEY,id:u,key:o}]:l=[{type:H.UPDATE_OBJECT,id:u,data:{[o]:h}}],a(this,we).delete(o),a(this,Z).set(o,c),this.invalidate(),cn(c)&&(c._setParentLink(this,o),c._attach(i,this._pool)),{reverse:l,modified:{node:this,type:"LiveObject",updates:{[o]:{type:"update"}}}}}_detachChild(t){if(t){let r=q(this._id),i=q(t._parentKey),s=t._toOps(r,i);for(let[c,u]of a(this,Z))u===t&&(a(this,Z).delete(c),this.invalidate());return t._detach(),{modified:{node:this,type:"LiveObject",updates:{[i]:{type:"delete"}}},reverse:s}}return{modified:!1}}_detach(){super._detach();for(let t of a(this,Z).values())ve(t)&&t._detach()}_apply(t,r){return t.type===H.UPDATE_OBJECT?S(this,$t,Na).call(this,t,r):t.type===H.DELETE_OBJECT_KEY?S(this,$t,Ua).call(this,t,r):super._apply(t,r)}_serialize(){let t={};for(let[r,i]of a(this,Z))ve(i)||(t[r]=i);return this.parent.type==="HasParent"&&this.parent.node._id?{type:he.OBJECT,parentId:this.parent.node._id,parentKey:this.parent.key,data:t}:{type:he.OBJECT,data:t}}keys(){let t=new Set(a(this,Z).keys());for(let r of a(this,we).keys())t.add(r);return t}set(t,r){this.update({[t]:r})}setLocal(t,r){this._pool?.assertStorageIsWritable();let i=S(this,$t,fs).call(this,t);if(a(this,we).set(t,r),this.invalidate(),this._pool!==void 0&&this._id!==void 0){let s=i?.[0]??[],o=i?.[1]??[],c=i?.[2]??new Map,u=c.get(this._id);c.set(this._id,{node:this,type:"LiveObject",updates:{...u?.updates,[t]:{type:"update"}}}),this._pool.dispatch(s,o,c)}}get(t){return a(this,we).has(t)?a(this,we).get(t):a(this,Z).get(t)}delete(t){let r=S(this,$t,fs).call(this,t);if(r){let[i,s,o]=r;this._pool?.dispatch(i,s,o)}}update(t){if(this._pool?.assertStorageIsWritable(),Ke.detectLargeObjects){let l={};for(let[O,z]of a(this,Z))ve(z)||(l[O]=z);for(let O of Object.keys(t)){let z=t[O];z!==void 0&&(ve(z)||(l[O]=z))}let m=JSON.stringify(l);if(m.length*4>Xi){let O=new TextEncoder().encode(m).length;if(O>Xi)throw new Error(`LiveObject size exceeded limit: ${O} bytes > ${Xi} bytes. See https://liveblocks.io/docs/platform/limits#Liveblocks-Storage-limits`)}}if(this._pool===void 0||this._id===void 0){for(let l in t){let m=t[l];if(m===void 0)continue;let k=a(this,Z).get(l);ve(k)&&k._detach(),ve(m)&&m._setParentLink(this,l),a(this,we).delete(l),a(this,Z).set(l,m),this.invalidate()}return}let r=[],i=[],s=this._pool.generateOpId(),o={},c={id:this._id,type:H.UPDATE_OBJECT,data:{}},u={};for(let l in t){let m=t[l];if(m===void 0)continue;let k=a(this,Z).get(l);if(k!==m){if(ve(k)){for(let O of k._toOps(this._id,l))i.push(O);k._detach()}else k===void 0?i.push({type:H.DELETE_OBJECT_KEY,id:this._id,key:l}):c.data[l]=k;if(ve(m)){m._setParentLink(this,l),m._attach(this._pool.generateId(),this._pool);let O=m._toOpsWithOpId(this._id,l,this._pool),z=O.find(B=>B.parentId===this._id);z&&a(this,_e).set(l,q(z.opId));for(let B of O)r.push(B)}else o[l]=m,a(this,_e).set(l,s);a(this,we).delete(l),a(this,Z).set(l,m),this.invalidate(),u[l]={type:"update"}}}if(Object.keys(c.data).length!==0&&i.unshift(c),Object.keys(o).length!==0&&r.unshift({opId:s,id:this._id,type:H.UPDATE_OBJECT,data:o}),r.length===0&&i.length===0&&Object.keys(u).length===0)return;let h=new Map;h.set(this._id,{node:this,type:"LiveObject",updates:u}),this._pool.dispatch(r,i,h)}static from(t,r){if(!Ce(t))throw new Error("Expected a JSON object");let i=new Ke({});return i.reconcile(t,r),i}reconcile(t,r){if(!this.hasCache(t)){if(!Ce(t))throw new Error("Reconciling the document root expects a plain object value");ps(this,t,"full",r)}}reconcilePartially(t,r){if(!Ce(t))throw new Error("Reconciling the document root expects a plain object value");ps(this,t,"partial",r)}toTreeNode(t){return super.toTreeNode(t)}_toTreeNode(t){let r=this._id??ze();return{type:"LiveObject",id:r,key:t,payload:Array.from(a(this,Z).entries()).map(([i,s])=>ve(s)?s.toTreeNode(i):{type:"Json",id:`${r}:${i}`,key:i,payload:s})}}toJSON(){return super.toJSON()}_toJSON(){let t={};for(let[r,i]of a(this,Z))t[r]=cn(i)?i.toJSON():i;for(let[r,i]of a(this,we))t[r]=i;return bt(t)}clone(){let t=new Ke(Object.fromEntries(Array.from(a(this,Z)).map(([r,i])=>[r,cn(i)?i.clone():yr(i)])));for(let[r,i]of a(this,we))a(t,we).set(r,yr(i));return t}},Z=new WeakMap,we=new WeakMap,_e=new WeakMap,wi=new WeakSet,Pa=function(t){let r=new Map,i=null;for(let s of t)if(jd(s))i=s[1];else{let o=s[1],c=r.get(o.parentId);c!==void 0?c.push(s):r.set(o.parentId,[s])}if(i===null)throw new Error("Root can't be null");return[i,r]},$t=new WeakSet,Na=function(t,r){let i=!1,s=q(this._id),o=[],c={type:H.UPDATE_OBJECT,id:s,data:{}};for(let h in t.data){let l=a(this,Z).get(h);if(ve(l)){for(let m of l._toOps(s,h))o.push(m);l._detach()}else l!==void 0?c.data[h]=l:l===void 0&&o.push({type:H.DELETE_OBJECT_KEY,id:s,key:h})}let u={};for(let h in t.data){let l=t.data[h];if(l===void 0)continue;if(r)a(this,_e).set(h,q(t.opId));else if(a(this,_e).get(h)===void 0)i=!0;else if(a(this,_e).get(h)===t.opId){a(this,_e).delete(h);continue}else continue;let m=a(this,Z).get(h);ve(m)&&m._detach(),i=!0,u[h]={type:"update"},a(this,we).delete(h),a(this,Z).set(h,l),this.invalidate()}return Object.keys(c.data).length!==0&&o.unshift(c),i?{modified:{node:this,type:"LiveObject",updates:u},reverse:o}:{modified:!1}},Ua=function(t,r){let i=t.key,s=a(this,Z).get(i);if(s===void 0)return{modified:!1};if(!r&&a(this,_e).get(i)!==void 0)return{modified:!1};let o=q(this._id),c=[];return ve(s)?(c=s._toOps(o,t.key),s._detach()):s!==void 0&&(c=[{type:H.UPDATE_OBJECT,id:o,data:{[i]:s}}]),a(this,we).delete(i),a(this,Z).delete(i),this.invalidate(),{modified:{node:this,type:"LiveObject",updates:{[t.key]:{type:"delete",deletedItem:s}}},reverse:c}},fs=function(t){this._pool?.assertStorageIsWritable();let r=t;if(a(this,we).has(r)&&!a(this,Z).has(r)){let u=a(this,we).get(r);if(a(this,we).delete(r),this.invalidate(),this._pool!==void 0&&this._id!==void 0){let h=new Map;return h.set(this._id,{node:this,type:"LiveObject",updates:{[r]:{type:"delete",deletedItem:u}}}),[[],[],h]}return null}a(this,we).delete(r);let i=a(this,Z).get(r);if(i===void 0)return null;if(this._pool===void 0||this._id===void 0)return ve(i)&&i._detach(),a(this,Z).delete(r),this.invalidate(),null;let s=[{type:H.DELETE_OBJECT_KEY,key:r,id:this._id,opId:this._pool.generateOpId()}],o;ve(i)?(i._detach(),o=i._toOps(this._id,r)):o=[{type:H.UPDATE_OBJECT,data:{[r]:i},id:this._id}],a(this,Z).delete(r),this.invalidate();let c=new Map;return c.set(this._id,{node:this,type:"LiveObject",updates:{[t]:{type:"delete",deletedItem:i}}}),[s,o,c]},T(Ke,wi),ke(Ke,"detectLargeObjects",!1),Ke);Ba=!1;Ka=ne();process.env.NODE_ENV!=="production"&&typeof window<"u"&&window.addEventListener("message",n=>{n.source===window&&n.data?.source==="liveblocks-devtools-panel"&&Ka.notify(n.data)});ja=Ka.observable,qa=ln||"dev",ko=!1;ms=new Map;yu=Date.now(),bu=0;gs=new Map;zo=new Set;Io=Symbol("notification-settings-plain");qt="12px",zu=(n="bottom-right")=>{if(typeof document>"u"||document.getElementById("liveblocks-badge"))return;let e=document.createElement("div");switch(e.id="liveblocks-badge",e.style.position="fixed",e.style.opacity="0",e.style.transition="opacity 300ms",e.style.zIndex="9999",n){case"top-right":e.style.top=qt,e.style.right=qt;break;case"bottom-right":e.style.bottom=qt,e.style.right=qt;break;case"bottom-left":e.style.bottom=qt,e.style.left=qt;break;case"top-left":e.style.top=qt,e.style.left=qt;break}e.onmouseenter=()=>{let z=document.getElementById("liveblocks-badge-hide-button");z&&(z.style.opacity="0.3")},e.onmouseleave=()=>{let z=document.getElementById("liveblocks-badge-hide-button");z&&(z.style.opacity="0")};let t=document.createElement("a");t.href="https://lblcks.io/badge",t.target="_blank",t.rel="noopener noreferrer",t.title="Liveblocks";let r=document.createElementNS("http://www.w3.org/2000/svg","svg");r.setAttribute("width","111"),r.setAttribute("height","38"),r.setAttribute("viewBox","0 0 111 38"),r.setAttribute("fill","none");let i=document.createElementNS("http://www.w3.org/2000/svg","rect");i.setAttribute("x","1"),i.setAttribute("y","1"),i.setAttribute("width","109"),i.setAttribute("height","36"),i.setAttribute("rx","8"),i.setAttribute("fill","white"),r.appendChild(i);let s=document.createElementNS("http://www.w3.org/2000/svg","rect");s.setAttribute("x","0.5"),s.setAttribute("y","0.5"),s.setAttribute("width","110"),s.setAttribute("height","37"),s.setAttribute("rx","8.5"),s.setAttribute("stroke","black"),s.setAttribute("stroke-opacity","0.1"),r.appendChild(s);let o=document.createElementNS("http://www.w3.org/2000/svg","path");o.setAttribute("d","M39.8256 18.0832H38L38.0005 28.9009H39.8256V18.0832ZM43.213 21.1757H41.3879V28.9009H43.213V21.1757ZM43.213 18H41.3879V19.9688H43.213V18ZM45.8916 21.1757H43.9302L46.6915 28.9009H48.7283L51.4896 21.1757H49.5581L48.4039 24.8348C48.3739 24.93 48.2657 25.3024 48.0795 25.9511L47.7099 27.1959C47.4914 26.406 47.2626 25.6189 47.0237 24.8348L45.8916 21.1757ZM58.9659 23.59C58.8147 23.0721 58.5934 22.6317 58.3014 22.2694C57.9743 21.8628 57.5598 21.5482 57.0571 21.3268C56.5589 21.1004 56.0058 20.9877 55.3973 20.9877C54.2407 20.9877 53.3152 21.3495 52.6212 22.0735C52.275 22.4476 52.0103 22.8896 51.844 23.3715C51.6731 23.8691 51.5876 24.4199 51.5876 25.0233C51.5876 26.3157 51.9322 27.3142 52.6217 28.0184C53.3203 28.7323 54.2509 29.0894 55.4125 29.0894C56.4083 29.0894 57.2151 28.8658 57.8342 28.4181C58.453 27.9704 58.8628 27.3068 59.0638 26.4266L57.2834 26.2908C57.198 26.7685 57.0016 27.1257 56.6948 27.3618C56.3879 27.5933 55.9555 27.7093 55.3973 27.7093C54.1201 27.7093 53.4663 26.9899 53.4363 25.5514H59.1844L59.1922 25.295C59.1922 24.6763 59.1165 24.108 58.9659 23.59ZM53.8434 23.0471C54.1654 22.5943 54.6834 22.3679 55.3973 22.3679C55.7443 22.3679 56.0363 22.4155 56.2725 22.5111C56.509 22.6067 56.7128 22.7601 56.8837 22.9713C57.0167 23.1352 57.1189 23.3218 57.1855 23.5221C57.2605 23.731 57.3062 23.9493 57.3213 24.1708H53.451C53.4964 23.7231 53.6271 23.3484 53.8434 23.0471ZM66.2836 21.4779C65.7656 21.1406 65.1673 20.9724 64.4885 20.9724H64.4875C63.995 20.9724 63.5449 21.0727 63.1374 21.2742C62.7364 21.4696 62.3931 21.7659 62.1412 22.1341V18.0832H60.316V28.9009H62.1416V27.8373C62.373 28.2195 62.7008 28.5342 63.0921 28.7499C63.4996 28.9763 63.9497 29.0894 64.4422 29.0894C65.1266 29.0894 65.7324 28.9259 66.2614 28.5992C66.7891 28.2726 67.1989 27.8045 67.4905 27.1959C67.7871 26.5823 67.9359 25.8634 67.9359 25.0386C67.9359 24.2337 67.7895 23.5248 67.4984 22.9113C67.2115 22.2926 66.8066 21.8148 66.2836 21.4779ZM65.5064 27.0828C65.2148 27.5254 64.7172 27.7463 64.0125 27.7463C63.3786 27.7463 62.9013 27.5175 62.5797 27.0601C62.2576 26.6026 62.0968 25.9336 62.0968 25.0534C62.0968 24.2032 62.24 23.5397 62.5265 23.0619C62.8185 22.579 63.3088 22.3378 63.9978 22.3378C64.7019 22.3378 65.2023 22.5592 65.499 23.0013C65.7961 23.4389 65.944 24.1181 65.944 25.0386C65.944 25.9585 65.7985 26.6401 65.5064 27.0828ZM70.901 18.0832H69.0754V28.9009H70.901V18.0832ZM73.8582 28.6066C74.452 28.9286 75.1558 29.0894 75.9708 29.0894C76.7554 29.0894 77.4444 28.9208 78.0377 28.5844C78.6268 28.2569 79.1068 27.7637 79.4183 27.1659C79.745 26.5523 79.9086 25.843 79.9086 25.0386C79.9086 24.2642 79.7478 23.5697 79.4257 22.9565C79.117 22.3516 78.6404 21.8487 78.0529 21.508C77.4592 21.161 76.7652 20.9872 75.9708 20.9872C75.171 20.9872 74.4719 21.161 73.8735 21.508C73.2876 21.8472 72.811 22.3471 72.5002 22.9486C72.1837 23.5572 72.0252 24.254 72.0252 25.0386C72.0252 25.8735 72.181 26.5948 72.4929 27.2033C72.7962 27.798 73.2722 28.2871 73.8582 28.6066ZM77.4869 27.0906C77.18 27.5231 76.6746 27.7393 75.9708 27.7393C75.493 27.7393 75.1082 27.6437 74.8166 27.4524C74.5246 27.2565 74.3134 26.9621 74.1826 26.5699C74.0518 26.1725 73.9867 25.6619 73.9867 25.0381C73.9867 24.1029 74.1401 23.419 74.4469 22.9866C74.7588 22.5541 75.2667 22.3378 75.9708 22.3378C76.6699 22.3378 77.1727 22.5541 77.4795 22.9866C77.7914 23.419 77.9471 24.1029 77.9471 25.0386C77.9471 25.9738 77.7937 26.6576 77.4869 27.0906ZM82.3982 28.6066C82.9869 28.9286 83.6883 29.0894 84.5033 29.0894C85.1369 29.0894 85.7029 28.9791 86.2005 28.7577C86.6989 28.5364 87.1031 28.2272 87.4152 27.8299C87.7279 27.4249 87.9329 26.9471 88.0109 26.4414L86.2534 26.2607C86.1328 26.7431 85.9316 27.1031 85.6497 27.3392C85.3683 27.5757 84.9857 27.694 84.5033 27.694C84.0103 27.694 83.6232 27.5933 83.3413 27.3918C83.0598 27.1858 82.8635 26.8919 82.7531 26.5093C82.6422 26.1221 82.5872 25.6318 82.5872 25.0386C82.5872 24.455 82.6422 23.9722 82.7531 23.59C82.8635 23.2028 83.0571 22.9062 83.3339 22.6997C83.6157 22.4884 84.0053 22.3831 84.5033 22.3831C85.0362 22.3831 85.4312 22.5314 85.6877 22.8281C85.949 23.1196 86.1354 23.5193 86.2456 24.0276L87.9735 23.718C87.8078 22.8932 87.4326 22.232 86.8491 21.7344C86.2708 21.2363 85.489 20.9877 84.5033 20.9877C83.6985 20.9877 83.0021 21.1587 82.4134 21.5006C81.8322 21.8351 81.3625 22.3337 81.0633 22.9339C80.7514 23.5424 80.5952 24.2439 80.5952 25.0386C80.5952 25.8781 80.7486 26.6026 81.0554 27.2112C81.3673 27.8197 81.8151 28.285 82.3982 28.6066ZM90.8104 26.0343L91.6627 25.2192L93.9257 28.9009H96.0308L92.8999 24.0498L95.9328 21.1757H93.5634L90.8104 23.9976V18.0832H88.9845V28.9009H90.8104V26.0343ZM97.6304 28.8103C98.1436 28.9965 98.7142 29.0894 99.3428 29.0894C100.303 29.0894 101.095 28.8981 101.719 28.5165C102.348 28.1339 102.663 27.5101 102.663 26.6451C102.663 26.0818 102.516 25.6392 102.225 25.3176C101.933 24.9905 101.586 24.7566 101.184 24.6157C100.786 24.4702 100.245 24.3219 99.562 24.1707C99.1642 24.0853 98.8502 24.0049 98.6188 23.9295C98.3873 23.8538 98.201 23.7558 98.0604 23.6352C97.925 23.5141 97.8567 23.3584 97.8567 23.1676C97.8567 22.8858 97.9824 22.6723 98.2338 22.5263C98.4853 22.3803 98.7973 22.3073 99.1694 22.3073C99.6619 22.3073 100.047 22.4255 100.324 22.6621C100.605 22.8987 100.756 23.2531 100.776 23.7258L102.466 23.4467C102.385 22.5817 102.046 21.9556 101.447 21.568C100.854 21.1812 100.095 20.9872 99.1694 20.9872C98.6258 20.9872 98.1236 21.0699 97.6607 21.2362C97.2029 21.397 96.8335 21.6511 96.5517 21.9986C96.27 22.3451 96.1294 22.7827 96.1294 23.3109C96.1294 23.7988 96.25 24.1934 96.4911 24.4951C96.7368 24.8001 97.0527 25.0408 97.4118 25.1965C97.7838 25.3578 98.2512 25.5112 98.8147 25.6567L99.2828 25.7699C99.5949 25.844 99.9044 25.9295 100.211 26.0264C100.421 26.092 100.595 26.1826 100.731 26.2981C100.867 26.4136 100.935 26.5647 100.935 26.7509C100.935 27.0776 100.799 27.3294 100.527 27.505C100.261 27.6815 99.8708 27.7693 99.3583 27.7693C98.8347 27.7693 98.4176 27.6385 98.1055 27.377C97.7941 27.1154 97.6355 26.7384 97.6304 26.2454L95.9109 26.4413C95.9302 27.0351 96.094 27.5304 96.4009 27.9278C96.7129 28.3252 97.1223 28.619 97.6304 28.8103Z"),o.setAttribute("fill","black"),r.appendChild(o);let c=document.createElementNS("http://www.w3.org/2000/svg","path");c.setAttribute("d","M37.6392 15V9.18182H39.7131C40.1657 9.18182 40.5407 9.2642 40.8381 9.42898C41.1354 9.59375 41.358 9.81913 41.5057 10.1051C41.6534 10.3892 41.7273 10.7093 41.7273 11.0653C41.7273 11.4233 41.6525 11.7453 41.5028 12.0312C41.3551 12.3153 41.1316 12.5407 40.8324 12.7074C40.535 12.8722 40.161 12.9545 39.7102 12.9545H38.2841V12.2102H39.6307C39.9167 12.2102 40.1487 12.161 40.3267 12.0625C40.5047 11.9621 40.6354 11.8258 40.7188 11.6534C40.8021 11.4811 40.8438 11.285 40.8438 11.0653C40.8438 10.8456 40.8021 10.6506 40.7188 10.4801C40.6354 10.3097 40.5038 10.1761 40.3239 10.0795C40.1458 9.98295 39.911 9.93466 39.6193 9.93466H38.517V15H37.6392ZM44.4716 15.0881C44.0625 15.0881 43.7055 14.9943 43.4006 14.8068C43.0956 14.6193 42.8589 14.357 42.6903 14.0199C42.5218 13.6828 42.4375 13.2888 42.4375 12.8381C42.4375 12.3854 42.5218 11.9896 42.6903 11.6506C42.8589 11.3116 43.0956 11.0483 43.4006 10.8608C43.7055 10.6733 44.0625 10.5795 44.4716 10.5795C44.8807 10.5795 45.2377 10.6733 45.5426 10.8608C45.8475 11.0483 46.0843 11.3116 46.2528 11.6506C46.4214 11.9896 46.5057 12.3854 46.5057 12.8381C46.5057 13.2888 46.4214 13.6828 46.2528 14.0199C46.0843 14.357 45.8475 14.6193 45.5426 14.8068C45.2377 14.9943 44.8807 15.0881 44.4716 15.0881ZM44.4744 14.375C44.7396 14.375 44.9593 14.3049 45.1335 14.1648C45.3078 14.0246 45.4366 13.8381 45.5199 13.6051C45.6051 13.3722 45.6477 13.1155 45.6477 12.8352C45.6477 12.5568 45.6051 12.3011 45.5199 12.0682C45.4366 11.8333 45.3078 11.6449 45.1335 11.5028C44.9593 11.3608 44.7396 11.2898 44.4744 11.2898C44.2074 11.2898 43.9858 11.3608 43.8097 11.5028C43.6354 11.6449 43.5057 11.8333 43.4205 12.0682C43.3371 12.3011 43.2955 12.5568 43.2955 12.8352C43.2955 13.1155 43.3371 13.3722 43.4205 13.6051C43.5057 13.8381 43.6354 14.0246 43.8097 14.1648C43.9858 14.3049 44.2074 14.375 44.4744 14.375ZM48.267 15L46.983 10.6364H47.8608L48.7159 13.8409H48.7585L49.6165 10.6364H50.4943L51.3466 13.8267H51.3892L52.2386 10.6364H53.1165L51.8352 15H50.9688L50.0824 11.8494H50.017L49.1307 15H48.267ZM55.6705 15.0881C55.2405 15.0881 54.8703 14.9962 54.5597 14.8125C54.2509 14.6269 54.0123 14.3665 53.8438 14.0312C53.6771 13.6941 53.5938 13.2992 53.5938 12.8466C53.5938 12.3996 53.6771 12.0057 53.8438 11.6648C54.0123 11.3239 54.2472 11.0578 54.5483 10.8665C54.8513 10.6752 55.2055 10.5795 55.6108 10.5795C55.857 10.5795 56.0956 10.6203 56.3267 10.7017C56.5578 10.7831 56.7652 10.911 56.9489 11.0852C57.1326 11.2595 57.2775 11.4858 57.3835 11.7642C57.4896 12.0407 57.5426 12.3769 57.5426 12.7727V13.0739H54.0739V12.4375H56.7102C56.7102 12.214 56.6648 12.0161 56.5739 11.8438C56.483 11.6695 56.3551 11.5322 56.1903 11.4318C56.0275 11.3314 55.8362 11.2812 55.6165 11.2812C55.3778 11.2812 55.1695 11.34 54.9915 11.4574C54.8153 11.5729 54.679 11.7244 54.5824 11.9119C54.4877 12.0975 54.4403 12.2992 54.4403 12.517V13.0142C54.4403 13.3059 54.4915 13.554 54.5938 13.7585C54.6979 13.9631 54.8428 14.1193 55.0284 14.2273C55.214 14.3333 55.4309 14.3864 55.679 14.3864C55.84 14.3864 55.9867 14.3636 56.1193 14.3182C56.2519 14.2708 56.3665 14.2008 56.4631 14.108C56.5597 14.0152 56.6335 13.9006 56.6847 13.7642L57.4886 13.9091C57.4242 14.1458 57.3087 14.3532 57.142 14.5312C56.9773 14.7074 56.7699 14.8447 56.5199 14.9432C56.2718 15.0398 55.9886 15.0881 55.6705 15.0881ZM58.4851 15V10.6364H59.3061V11.3295H59.3516C59.4311 11.0947 59.5713 10.91 59.772 10.7756C59.9747 10.6392 60.2038 10.571 60.4595 10.571C60.5125 10.571 60.575 10.5729 60.647 10.5767C60.7209 10.5805 60.7786 10.5852 60.8203 10.5909V11.4034C60.7862 11.3939 60.7256 11.3835 60.6385 11.3722C60.5514 11.3589 60.4643 11.3523 60.3771 11.3523C60.1764 11.3523 59.9974 11.3949 59.8402 11.4801C59.6849 11.5634 59.5618 11.6799 59.4709 11.8295C59.38 11.9773 59.3345 12.1458 59.3345 12.3352V15H58.4851ZM63.2798 15.0881C62.8499 15.0881 62.4796 14.9962 62.169 14.8125C61.8603 14.6269 61.6217 14.3665 61.4531 14.0312C61.2865 13.6941 61.2031 13.2992 61.2031 12.8466C61.2031 12.3996 61.2865 12.0057 61.4531 11.6648C61.6217 11.3239 61.8565 11.0578 62.1577 10.8665C62.4607 10.6752 62.8149 10.5795 63.2202 10.5795C63.4664 10.5795 63.705 10.6203 63.9361 10.7017C64.1671 10.7831 64.3745 10.911 64.5582 11.0852C64.742 11.2595 64.8868 11.4858 64.9929 11.7642C65.099 12.0407 65.152 12.3769 65.152 12.7727V13.0739H61.6832V12.4375H64.3196C64.3196 12.214 64.2741 12.0161 64.1832 11.8438C64.0923 11.6695 63.9645 11.5322 63.7997 11.4318C63.6368 11.3314 63.4455 11.2812 63.2259 11.2812C62.9872 11.2812 62.7789 11.34 62.6009 11.4574C62.4247 11.5729 62.2884 11.7244 62.1918 11.9119C62.0971 12.0975 62.0497 12.2992 62.0497 12.517V13.0142C62.0497 13.3059 62.1009 13.554 62.2031 13.7585C62.3073 13.9631 62.4522 14.1193 62.6378 14.2273C62.8234 14.3333 63.0402 14.3864 63.2884 14.3864C63.4493 14.3864 63.5961 14.3636 63.7287 14.3182C63.8613 14.2708 63.9759 14.2008 64.0724 14.108C64.169 14.0152 64.2429 13.9006 64.294 13.7642L65.098 13.9091C65.0336 14.1458 64.9181 14.3532 64.7514 14.5312C64.5866 14.7074 64.3793 14.8447 64.1293 14.9432C63.8812 15.0398 63.598 15.0881 63.2798 15.0881ZM67.728 15.0852C67.3757 15.0852 67.0613 14.9953 66.7848 14.8153C66.5102 14.6335 66.2943 14.375 66.1371 14.0398C65.9818 13.7027 65.9041 13.2983 65.9041 12.8267C65.9041 12.3551 65.9827 11.9517 66.1399 11.6165C66.299 11.2812 66.5168 11.0246 66.7933 10.8466C67.0698 10.6686 67.3833 10.5795 67.7337 10.5795C68.0045 10.5795 68.2223 10.625 68.3871 10.7159C68.5537 10.8049 68.6825 10.9091 68.7734 11.0284C68.8662 11.1477 68.9382 11.2528 68.9893 11.3438H69.0405V9.18182H69.8899V15H69.0604V14.321H68.9893C68.9382 14.4138 68.8643 14.5199 68.7678 14.6392C68.6731 14.7585 68.5424 14.8627 68.3757 14.9517C68.209 15.0407 67.9931 15.0852 67.728 15.0852ZM67.9155 14.3608C68.1598 14.3608 68.3662 14.2964 68.5348 14.1676C68.7053 14.0369 68.834 13.8561 68.9212 13.625C69.0102 13.3939 69.0547 13.125 69.0547 12.8182C69.0547 12.5152 69.0111 12.25 68.924 12.0227C68.8369 11.7955 68.709 11.6184 68.5405 11.4915C68.3719 11.3646 68.1636 11.3011 67.9155 11.3011C67.6598 11.3011 67.4467 11.3674 67.2763 11.5C67.1058 11.6326 66.977 11.8134 66.8899 12.0426C66.8047 12.2718 66.7621 12.5303 66.7621 12.8182C66.7621 13.1098 66.8056 13.3722 66.8928 13.6051C66.9799 13.8381 67.1087 14.0227 67.2791 14.1591C67.4515 14.2936 67.6636 14.3608 67.9155 14.3608ZM73.2876 15V9.18182H74.1371V11.3438H74.1882C74.2375 11.2528 74.3085 11.1477 74.4013 11.0284C74.4941 10.9091 74.6229 10.8049 74.7876 10.7159C74.9524 10.625 75.1702 10.5795 75.4411 10.5795C75.7933 10.5795 76.1077 10.6686 76.3842 10.8466C76.6607 11.0246 76.8776 11.2812 77.0348 11.6165C77.1939 11.9517 77.2734 12.3551 77.2734 12.8267C77.2734 13.2983 77.1948 13.7027 77.0376 14.0398C76.8804 14.375 76.6645 14.6335 76.3899 14.8153C76.1153 14.9953 75.8018 15.0852 75.4496 15.0852C75.1844 15.0852 74.9676 15.0407 74.799 14.9517C74.6323 14.8627 74.5017 14.7585 74.407 14.6392C74.3123 14.5199 74.2393 14.4138 74.1882 14.321H74.1172V15H73.2876ZM74.12 12.8182C74.12 13.125 74.1645 13.3939 74.2536 13.625C74.3426 13.8561 74.4714 14.0369 74.6399 14.1676C74.8085 14.2964 75.0149 14.3608 75.2592 14.3608C75.513 14.3608 75.7251 14.2936 75.8956 14.1591C76.0661 14.0227 76.1948 13.8381 76.282 13.6051C76.371 13.3722 76.4155 13.1098 76.4155 12.8182C76.4155 12.5303 76.3719 12.2718 76.2848 12.0426C76.1996 11.8134 76.0708 11.6326 75.8984 11.5C75.728 11.3674 75.5149 11.3011 75.2592 11.3011C75.013 11.3011 74.8047 11.3646 74.6342 11.4915C74.4657 11.6184 74.3378 11.7955 74.2507 12.0227C74.1636 12.25 74.12 12.5152 74.12 12.8182ZM78.6158 16.6364C78.4889 16.6364 78.3733 16.6259 78.2692 16.6051C78.165 16.5862 78.0874 16.5653 78.0362 16.5426L78.2408 15.8466C78.3961 15.8883 78.5343 15.9063 78.6555 15.9006C78.7768 15.8949 78.8838 15.8494 78.9766 15.7642C79.0713 15.679 79.1546 15.5398 79.2266 15.3466L79.3317 15.0568L77.7351 10.6364H78.6442L79.7493 14.0227H79.7947L80.8999 10.6364H81.8118L80.0135 15.5824C79.9302 15.8097 79.8241 16.0019 79.6953 16.1591C79.5665 16.3182 79.4131 16.4375 79.2351 16.517C79.0571 16.5966 78.8506 16.6364 78.6158 16.6364Z"),c.setAttribute("fill","black"),c.setAttribute("fill-opacity","0.5"),r.appendChild(c);let u=document.createElementNS("http://www.w3.org/2000/svg","rect");u.setAttribute("x","7"),u.setAttribute("y","7"),u.setAttribute("width","24"),u.setAttribute("height","24"),u.setAttribute("rx","3"),u.setAttribute("fill","black"),r.appendChild(u);let h=document.createElementNS("http://www.w3.org/2000/svg","path");h.setAttribute("fill-rule","evenodd"),h.setAttribute("clip-rule","evenodd"),h.setAttribute("d","M22.0455 15H12.2273L15.1364 17.9091V21.9091L22.0455 15Z"),h.setAttribute("fill","white"),r.appendChild(h);let l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("fill-rule","evenodd"),l.setAttribute("clip-rule","evenodd"),l.setAttribute("d","M16.9546 22.9999H26.7728L23.8637 20.0908V16.0908L16.9546 22.9999Z"),l.setAttribute("fill","white"),r.appendChild(l),t.appendChild(r),e.appendChild(t);let m=document.createElement("button");m.id="liveblocks-badge-hide-button",m.style.position="absolute",m.style.top="0",m.style.right="0",m.style.border="none",m.style.padding="0",m.style.margin="0",m.style.background="none",m.style.font="inherit",m.style.cursor="pointer",m.style.outline="none",m.style.setProperty("-webkit-appearance","none"),m.style.setProperty("-moz-appearance","none"),m.style.setProperty("appearance","none"),m.style.opacity="0",m.onclick=()=>{let z=document.getElementById("liveblocks-badge");z&&(z.style.display="none")},m.onmouseenter=()=>{m.style.opacity="0.5"},m.onmouseleave=()=>{m.style.opacity="0.3"};let k=document.createElementNS("http://www.w3.org/2000/svg","svg");k.setAttribute("width","18"),k.setAttribute("height","18"),k.setAttribute("viewBox","0 0 18 18"),k.setAttribute("fill","none");let O=document.createElementNS("http://www.w3.org/2000/svg","path");O.setAttribute("d","M6 6L9 9M12 12L9 9M9 9L12 6M9 9L6 12"),O.setAttribute("stroke","black"),k.appendChild(O),m.appendChild(k),e.appendChild(m),document.body.appendChild(e),requestAnimationFrame(()=>{requestAnimationFrame(()=>{e.style.opacity="1"})})},es=(Go=class{constructor(){T(this,ot);T(this,yt);T(this,Dt);T(this,Xe);b(this,ot,{}),b(this,yt,0),b(this,Dt,1),b(this,Xe,0)}get length(){return a(this,Xe)}*[Symbol.iterator](){let n=a(this,Xe),e=a(this,yt);for(let t=0;t<n;t++)yield a(this,ot)[e+t]}push(n){let e=Array.isArray(n)?n:[n];a(this,Dt)>Number.MAX_SAFE_INTEGER-e.length-1&&St("Deque full");for(let t of e)a(this,ot)[yn(this,Dt)._++-1]=t;b(this,Xe,a(this,Xe)+e.length)}pop(){if(a(this,Xe)<1)return;yn(this,Dt)._--;let n=a(this,ot)[a(this,Dt)-1];return delete a(this,ot)[a(this,Dt)-1],yn(this,Xe)._--,n}pushLeft(n){let e=Array.isArray(n)?n:[n];a(this,yt)<Number.MIN_SAFE_INTEGER+e.length&&St("Deque full");for(let t=e.length-1;t>=0;t--)a(this,ot)[--yn(this,yt)._]=e[t];b(this,Xe,a(this,Xe)+e.length)}popLeft(){if(a(this,Xe)<1)return;let n=a(this,ot)[a(this,yt)];return delete a(this,ot)[a(this,yt)],yn(this,yt)._++,yn(this,Xe)._--,n}},ot=new WeakMap,yt=new WeakMap,Dt=new WeakMap,Xe=new WeakMap,Go);Ee=Object.freeze({UPDATE_PRESENCE:100,BROADCAST_EVENT:103,FETCH_STORAGE:200,UPDATE_STORAGE:201,FETCH_YDOC:300,UPDATE_YDOC:301,FETCH_FEEDS:510,FETCH_FEED_MESSAGES:511,ADD_FEED:512,UPDATE_FEED:513,DELETE_FEED:514,ADD_FEED_MESSAGE:515,UPDATE_FEED_MESSAGE:516,DELETE_FEED_MESSAGE:517});Du=(Yo=class{constructor(){T(this,Pt);T(this,Be);T(this,an);ke(this,"signal");b(this,Be,new Dr({connections:new Map,presences:new Map})),this.signal=Dn.from(a(this,Be),n=>ns(Array.from(a(this,Be).get().presences.keys()).map(e=>this.getUser(Number(e))))),b(this,an,new Map)}get(){return this.signal.get()}connectionIds(){return a(this,Be).get().connections.keys()}clearOthers(){a(this,Be).mutate(n=>{n.connections.clear(),n.presences.clear(),a(this,an).clear()})}getUser(n){let e=a(this,an).get(n);if(e)return e;let t=S(this,Pt,Ga).call(this,n);if(t)return a(this,an).set(n,t),t}setConnection(n,e,t,r){a(this,Be).mutate(i=>(i.connections.set(n,bt({connectionId:n,id:e,info:t,scopes:r})),i.presences.has(n)?S(this,Pt,Rr).call(this,n):!1))}removeConnection(n){a(this,Be).mutate(e=>{e.connections.delete(n),e.presences.delete(n),S(this,Pt,Rr).call(this,n)})}setOther(n,e){a(this,Be).mutate(t=>(t.presences.set(n,bt(Si(e))),t.connections.has(n)?S(this,Pt,Rr).call(this,n):!1))}patchOther(n,e){a(this,Be).mutate(t=>{let r=t.presences.get(n);if(r===void 0)return!1;let i=Qo(r,e);return r===i?!1:(t.presences.set(n,bt(i)),S(this,Pt,Rr).call(this,n))})}},Be=new WeakMap,an=new WeakMap,Pt=new WeakSet,Ga=function(n){let e=a(this,Be).get(),t=e.connections.get(n),r=e.presences.get(n);if(t!==void 0&&r!==void 0)return Lu(t,r)},Rr=function(n){a(this,an).delete(n)},Yo),bi=class Ya extends Error{constructor(t,r,i){super(t,{cause:i});ke(this,"context");this.context=r,this.name="LiveblocksError"}get roomId(){return this.context.roomId}get code(){return this.context.code}static from(t,r){return new Ya(Mu(t),t,r)}};ts=5e3;Ku=16,ju=1e3,qu=100,Ju=15e3,Wu=200,Gu=1e3,Yu=3e4,Xu=5e3,Zu=50,Qu=50,eh=50;sh={"&":"&","<":"<",">":">",'"':""","'":"'"},Xh=new RegExp(Object.keys(sh).map(n=>`\\${n}`).join("|"),"g"),oh={_:"\\_","*":"\\*","#":"\\#","`":"\\`","~":"\\~","!":"\\!","|":"\\|","(":"\\(",")":"\\)","{":"\\{","}":"\\}","[":"\\[","]":"\\]"},Zh=new RegExp(Object.keys(oh).map(n=>`\\${n}`).join("|"),"g");vs(Xo,ln,Sl)});var ah,ch,lh,Xa=vn(()=>{"use strict";_s();_s();ah="@liveblocks/client",ch="3.19.1",lh="esm";vs(ah,ch,lh)});function Ai(n){let e=0;for(let t=0;t<n.length;t++)e=e*31+n.charCodeAt(t)|0;return Za[Math.abs(e)%Za.length]}function br(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}var Za,Ti=vn(()=>{"use strict";Za=["#4F46E5","#15803D","#C2410C","#BE185D","#0E7490","#7E22CE","#DC2626","#0F766E"]});function hh(n,e){let t=document.createElement("div");t.setAttribute("data-vizu-presence-avatar",n.id),t.setAttribute("data-vizu-presence-name",n.name),t.setAttribute("data-vizu-presence-color",n.color),n.avatar&&t.setAttribute("data-vizu-presence-img",n.avatar);let r=br(),i=r?"none":"transform 130ms cubic-bezier(0.16, 1, 0.3, 1), box-shadow 130ms ease-out";t.style.cssText=`
|
|
3
|
+
`))}function ne(){let n=new Set;function e(o){return n.add(o),()=>n.delete(o)}function t(o){let c=e(u=>(c(),o(u)));return c}async function r(o){let c;return new Promise(u=>{c=e(h=>{(o===void 0||o(h))&&u(h)})}).finally(()=>c?.())}function i(o){let c=!1;for(let u of n)u(o),c=!0;return c}function s(){return n.size}return{notify:i,subscribe:e,subscribeOnce:t,count:s,waitUntil:r,dispose(){n.clear()},observable:{subscribe:e,subscribeOnce:t,waitUntil:r}}}function Al(){let n=ne(),e=null;function t(){e=[]}function r(){if(e!==null){for(let s of e)n.notify(s);e=null}}function i(s){return e!==null?(e.push(s),!1):n.notify(s)}return{...n,notify:i,pause:t,unpause:r,dispose(){n.dispose(),e!==null&&(e.length=0)}}}function St(n){throw new Error(n)}function Zo(n){return Object.entries(n)}function Tl(n,e){return typeof e<"u"?Object.create(n,e):Object.create(n)}function Nt(n){try{return JSON.parse(n)}catch{return}}function yr(n){return JSON.parse(JSON.stringify(n))}function kl(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/");return decodeURIComponent(atob(e).split("").map(function(r){return"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)}).join(""))}catch{return atob(n)}}function ns(n){return n.filter(e=>e!=null)}function Si(n){let e={...n};return Object.keys(n).forEach(t=>{let r=t;e[r]===void 0&&delete e[r]}),e}function _l(n){return new Promise(e=>setTimeout(e,n))}async function so(n,e,t){let r,i=new Promise((s,o)=>{r=setTimeout(()=>{o(new Error(t))},e)});return Promise.race([n,i]).finally(()=>clearTimeout(r))}function oo(n){let e=null;return()=>(e===null&&(e=n().catch(t=>{throw setTimeout(()=>{e=null},5e3),t})),e)}function zl(n,e){for(let t=n.length-1;t>=0;t--)if(e(n[t],t,n))return t;return-1}function Il(n,e){let t=[],r=[],i=0;for(let s of n)e(s,i++)?t.push(s):r.push(s);return[t,r]}function dn(n){if(sr!==null){n();return}sr=new Set;try{n()}finally{for(let e of sr)e[gi]();sr=null}}function ys(n){sr||St("Expected to be in an active batch"),sr.add(n)}function Qo(n,e){let t=!1,r={...n};return Object.keys(e).forEach(i=>{let s=i,o=e[s];r[s]!==o&&(o===void 0?delete r[s]:r[s]=o,t=!0)}),t?r:n}function Ll(n,e,t){let r=0,i=n.length;for(;r<i;){let s=r+(i-r>>1);t(e,n[s])?i=s:r=s+1}return r}function is(n){let e=n.editedAt?new Date(n.editedAt):void 0,t=new Date(n.createdAt),r=n.reactions.map(i=>({...i,createdAt:new Date(i.createdAt)}));if(n.body)return{...n,reactions:r,createdAt:t,editedAt:e};{let i=new Date(n.deletedAt);return{...n,reactions:r,createdAt:t,editedAt:e,deletedAt:i}}}function Kt(n){let e=new Date(n.createdAt),t=new Date(n.updatedAt),r=n.comments.map(i=>is(i));return{...n,createdAt:e,updatedAt:t,comments:r}}function Ml(n){return{...n,createdAt:new Date(n.createdAt)}}function Sn(n){let e=new Date(n.notifiedAt),t=n.readAt?new Date(n.readAt):null;if("activities"in n){let r=n.activities.map(i=>({...i,createdAt:new Date(i.createdAt)}));return{...n,notifiedAt:e,readAt:t,activities:r}}return{...n,notifiedAt:e,readAt:t}}function jt(n){let e=new Date(n.createdAt);return{...n,createdAt:e}}function Bi(n){let e=new Date(n.deletedAt);return{...n,deletedAt:e}}function Ki(n){let e=new Date(n.deletedAt);return{...n,deletedAt:e}}function ji(n){let e=new Date(n.deletedAt);return{...n,deletedAt:e}}function ao(n){let e=new Date(n.createdAt),t=new Date(n.updatedAt),r=n.members.map(i=>({...i,addedAt:new Date(i.addedAt)}));return{...n,createdAt:e,updatedAt:t,members:r}}function Re(n,e){throw new Error(e)}function Pl(n,e){if(process.env.NODE_ENV!=="production"&&!n){let t=new Error(e);throw t.name="Assertion failure",t}}function J(n,e="Expected value to be non-nullable"){return Pl(n!=null,e),n}function ta(n){return typeof window>"u"||process.env.NODE_ENV==="test"?console[n]:((e,...t)=>console[n]("%cLiveblocks",ea,e,...t))}function na(n){return typeof window>"u"||process.env.NODE_ENV==="test"?console[n]:((e,t,...r)=>console[n](`%cLiveblocks%c ${e}`,ea,Ul,t,...r))}function Fl(n){return n!=null}function Ce(n){return n!==null&&typeof n=="object"&&Object.prototype.toString.call(n)==="[object Object]"}function co(n){return Ce(n)&&typeof n.startsWith=="string"}function lo(n){return Ce(n)&&(typeof n.lt=="number"||typeof n.gt=="number"||typeof n.lte=="number"||typeof n.gte=="number")}async function qi(n,e,t,r=Vl){let i=t.length>0?t[t.length-1]:0,s=0;for(;;){s++;try{return await n()}catch(c){if(r(c))throw c;if(s>=e)throw new Error(`Failed after ${e} attempts: ${String(c)}`)}let o=t[s-1]??i;xe(`Attempt ${s} was unsuccessful. Retrying in ${o} milliseconds.`),await _l(o)}}function sa(){let n,e;return[new Promise((r,i)=>{n=r,e=i}),n,e]}function ar(){let[n,e,t]=sa();return{promise:n,resolve:e,reject:t}}function Hl(n,e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).sort().reduce((t,r)=>(t[r]=e[r],t),{}):e}function ss(n){return JSON.stringify(n,Hl)}function Un(n){try{return JSON.stringify(n)}catch(e){throw console.error(`Could not stringify: ${e.message}`),console.error(n),e}}function cr(n){let e=new Mr(new Map);function t(l){return ss(l)}function r(l){e.mutate(m=>{if(Array.isArray(l))for(let k of l)m.set(k.key,k.state);else m.set(l.key,l.state)})}function i(l){e.mutate(m=>{if(Array.isArray(l))for(let k of l)m.delete(t(k));else m.clear()})}async function s(l){let m=t(l);if(!e.get().has(m))try{r({key:m,state:{isLoading:!0}});let O=await n.get(l);r({key:m,state:{isLoading:!1,data:O}})}catch(O){r({key:m,state:{isLoading:!1,error:O}})}}function o(l){r(l.map(m=>({key:t(m[0]),state:{isLoading:!1,data:m[1]}})))}function c(l){let m=t(l);return e.get().get(m)}function u(l){let m=t(l);return e.get().get(m)?.data}function h(){return[...e.get().keys()]}return{subscribe:e.subscribe,enqueue:s,setData:o,getItemState:c,getData:u,invalidate:i,batch:n,_cacheKeys:h}}function jl(n,e){let t=[];for(let r=0,i=n.length;r<i;r+=e)t.push(n.slice(r,r+e));return t}function Es(n){return`${n}_${ze()}`}function Gl(){return Es(ql)}function uo(){return Es(Jl)}function Yl(){return Es(Wl)}function Zn(n){let e=[],t=Object.entries(n),r=[],i=[],s=[];return t.forEach(([o,c])=>{if(!Xl.test(o))throw new Error("Key must only contain letters, numbers, _");fo(c)?r.push([o,c]):Ce(c)&&(co(c)||lo(c)?i.push([o,c]):s.push([o,c]))}),e=[...ho(r),...po(i)],s.forEach(([o,c])=>{let u=Object.entries(c),h=[],l=[];u.forEach(([m,k])=>{if(Zl(m))throw new Error("Key cannot be empty");fo(k)?h.push([mo(o,m),k]):(co(k)||lo(k))&&l.push([mo(o,m),k])}),e=[...e,...ho(h),...po(l)]}),e.map(({key:o,operator:c,value:u})=>`${o}${c}${aa(u)}`).join(" ")}function aa(n){let e=JSON.stringify(n);return typeof n!="string"||e.includes("'")?e:`'${e.slice(1,-1).replace(/\\"/g,'"')}'`}function Ql(n){let e=new URLSearchParams;for(let[t,r]of Object.entries(n))r!=null&&e.set(t,r.toString());return e}function ed(n,e,t){let r=new URL(e,n);return t!==void 0&&(r.search=(t instanceof URLSearchParams?t:Ql(t)).toString()),r.toString()}function $(n,...e){return n.reduce((t,r,i)=>t+encodeURIComponent(e[i-1]??"")+r)}function td({baseUrl:n,authManager:e,currentUserId:t,fetchPolyfill:r}){let i=new nd(n,r);async function s(p){let w=await i.get($`/v2/c/rooms/${p.roomId}/threads/delta`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{since:p.since.toISOString()},{signal:p.signal});return{threads:{updated:w.data.map(Kt),deleted:w.deletedThreads.map(Bi)},inboxNotifications:{updated:w.inboxNotifications.map(Sn),deleted:w.deletedInboxNotifications.map(Ki)},subscriptions:{updated:w.subscriptions.map(jt),deleted:w.deletedSubscriptions.map(ji)},requestedAt:new Date(w.meta.requestedAt),permissionHints:w.meta.permissionHints}}async function o(p){let w;p.query&&(w=Zn(p.query));let L=50;try{let N=await i.get($`/v2/c/rooms/${p.roomId}/threads`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{cursor:p.cursor,query:w,limit:L});return{threads:N.data.map(Kt),inboxNotifications:N.inboxNotifications.map(Sn),subscriptions:N.subscriptions.map(jt),nextCursor:N.meta.nextCursor,requestedAt:new Date(N.meta.requestedAt),permissionHints:N.meta.permissionHints}}catch(N){if(N instanceof vi&&N.status===404)return{threads:[],inboxNotifications:[],subscriptions:[],nextCursor:null,requestedAt:new Date(Date.now()-360*60*1e3),permissionHints:{}};throw N}}async function c(p,w){return await i.get($`/v2/c/rooms/${p.roomId}/threads/comments/search`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{text:p.query.text,query:Zn({threadMetadata:p.query.threadMetadata,threadResolved:p.query.threadResolved,hasAttachments:p.query.hasAttachments,hasMentions:p.query.hasMentions})},{signal:w?.signal})}async function u(p){let w=p.commentId??uo(),L=p.threadId??Gl(),N=await i.post($`/v2/c/rooms/${p.roomId}/threads`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{id:L,comment:{id:w,body:p.body,metadata:p.commentMetadata,attachmentIds:p.attachmentIds},metadata:p.metadata});return Kt(N)}async function h(p){await i.delete($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function l(p){let w=await i.rawGet($`/v2/c/rooms/${p.roomId}/thread-with-notification/${p.threadId}`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}));if(w.ok){let L=await w.json();return{thread:Kt(L.thread),inboxNotification:L.inboxNotification?Sn(L.inboxNotification):void 0,subscription:L.subscription?jt(L.subscription):void 0}}else{if(w.status===404)return{thread:void 0,inboxNotification:void 0,subscription:void 0};throw new Error(`There was an error while getting thread ${p.threadId}.`)}}async function m(p){return await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/metadata`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),p.metadata)}async function k(p){return await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/comments/${p.commentId}/metadata`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),p.metadata)}async function O(p){let w=p.commentId??uo(),L=await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/comments`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{id:w,body:p.body,metadata:p.metadata,attachmentIds:p.attachmentIds});return is(L)}async function _(p){let w=await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/comments/${p.commentId}`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{body:p.body,attachmentIds:p.attachmentIds,metadata:p.metadata});return is(w)}async function F(p){await i.delete($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/comments/${p.commentId}`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function K(p){let w=await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/comments/${p.commentId}/reactions`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{emoji:p.emoji});return Ml(w)}async function se(p){await i.delete($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/comments/${p.commentId}/reactions/${p.emoji}`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function z(p){await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/mark-as-resolved`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function P(p){await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/mark-as-unresolved`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function C(p){let w=await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/subscribe`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}));return jt(w)}async function R(p){await i.post($`/v2/c/rooms/${p.roomId}/threads/${p.threadId}/unsubscribe`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function y(p){let w=p.roomId,L=p.signal,N=p.attachment,be=L?new DOMException(`Upload of attachment ${p.attachment.id} was aborted.`,"AbortError"):void 0;if(L?.aborted)throw be;let pe=ae=>{if(L?.aborted)throw be;if(ae instanceof vi&&ae.status===413)throw ae;return!1},Ie=5*1024*1024,ge=10,Fe=[2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3,2e3];function Oe(ae){let Te=[],lt=0;for(;lt<ae.size;){let et=Math.min(lt+Ie,ae.size);Te.push({partNumber:Te.length+1,part:ae.slice(lt,et)}),lt=et}return Te}if(N.size<=Ie)return qi(async()=>i.putBlob($`/v2/c/rooms/${w}/attachments/${N.id}/upload/${encodeURIComponent(N.name)}`,await e.getAuthValue({requestedScope:"comments:read",roomId:w}),N.file,{fileSize:N.size},{signal:L}),ge,Fe,pe);{let ae,Te=[],lt=await qi(async()=>i.post($`/v2/c/rooms/${w}/attachments/${N.id}/multipart/${encodeURIComponent(N.name)}`,await e.getAuthValue({requestedScope:"comments:read",roomId:w}),void 0,{signal:L},{fileSize:N.size}),ge,Fe,pe);try{ae=lt.uploadId;let et=Oe(N.file);if(L?.aborted)throw be;let Gr=jl(et,5);for(let Bn of Gr){let gn=[];for(let{part:Di,partNumber:Mi}of Bn)gn.push(qi(async()=>i.putBlob($`/v2/c/rooms/${w}/attachments/${N.id}/multipart/${lt.uploadId}/${String(Mi)}`,await e.getAuthValue({requestedScope:"comments:read",roomId:w}),Di,void 0,{signal:L}),ge,Fe,pe));Te.push(...await Promise.all(gn))}if(L?.aborted)throw be;let Yr=Te.sort((Bn,gn)=>Bn.partNumber-gn.partNumber);return i.post($`/v2/c/rooms/${w}/attachments/${N.id}/multipart/${ae}/complete`,await e.getAuthValue({requestedScope:"comments:read",roomId:w}),{parts:Yr},{signal:L})}catch(et){if(ae&&et?.name&&(et.name==="AbortError"||et.name==="TimeoutError"))try{await i.rawDelete($`/v2/c/rooms/${w}/attachments/${N.id}/multipart/${ae}`,await e.getAuthValue({requestedScope:"comments:read",roomId:w}))}catch{}throw et}}}let V=new Qe(p=>{let w=new Wt(async L=>{let N=L.flat(),{urls:be}=await i.post($`/v2/c/rooms/${p}/attachments/presigned-urls`,await e.getAuthValue({requestedScope:"comments:read",roomId:p}),{attachmentIds:N});return be.map(pe=>pe??new Error("There was an error while getting this attachment's URL"))},{delay:50});return cr(w)});function G(p){return V.getOrCreate(p)}function oe(p){return G(p.roomId).batch.get(p.attachmentId)}async function re(p){let{chatId:w,attachment:L,signal:N}=p;if(t.get()===void 0)throw new Error("Attachment upload requires an authenticated user.");let pe=5*1024*1024;if(p.attachment.file.size<=pe)await i.putBlob($`/v2/c/chats/${w}/attachments/${L.id}/upload/${encodeURIComponent(L.file.name)}`,await e.getAuthValue({requestedScope:"comments:read"}),L.file,{fileSize:L.file.size},{signal:N});else{let Ie=await i.post($`/v2/c/chats/${w}/attachments/${L.id}/multipart/${encodeURIComponent(L.file.name)}`,await e.getAuthValue({requestedScope:"comments:read"}),void 0,{signal:N},{fileSize:L.file.size});try{let ge=[],Fe=[],Oe=0;for(;Oe<L.file.size;){let ae=Math.min(Oe+pe,L.file.size);Fe.push({number:Fe.length+1,part:L.file.slice(Oe,ae)}),Oe=ae}ge.push(...await Promise.all(Fe.map(async({number:ae,part:Te})=>await i.putBlob($`/v2/c/chats/${w}/attachments/${L.id}/multipart/${Ie.uploadId}/${String(ae)}`,await e.getAuthValue({requestedScope:"comments:read"}),Te,void 0,{signal:N})))),await i.post($`/v2/c/chats/${w}/attachments/${L.id}/multipart/${Ie.uploadId}/complete`,await e.getAuthValue({requestedScope:"comments:read"}),{parts:ge.sort((ae,Te)=>ae.number-Te.number)},{signal:N})}catch(ge){try{await i.delete($`/v2/c/chats/${w}/attachments/${L.id}/multipart/${Ie.uploadId}`,await e.getAuthValue({requestedScope:"comments:read"}))}catch{}throw ge}}}let Q=new Qe(p=>{let w=new Wt(async L=>{let N=L.flat(),{urls:be}=await i.post($`/v2/c/chats/${p}/attachments/presigned-urls`,await e.getAuthValue({requestedScope:"comments:read"}),{attachmentIds:N});return be.map(pe=>pe??new Error("There was an error while getting this attachment's URL"))},{delay:50});return cr(w)});function me(p){return Q.getOrCreate(p)}function Ne(p){return me(p.chatId).batch.get(p.attachmentId)}async function U(p){return i.get($`/v2/c/rooms/${p.roomId}/subscription-settings`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),void 0,{signal:p.signal})}async function A(p){return i.post($`/v2/c/rooms/${p.roomId}/subscription-settings`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),p.settings)}let q=new Qe(p=>new Wt(async w=>{let L=w.flat();return await i.post($`/v2/c/rooms/${p}/inbox-notifications/read`,await e.getAuthValue({requestedScope:"comments:read",roomId:p}),{inboxNotificationIds:L}),L},{delay:50}));async function Y(p){return q.getOrCreate(p.roomId).get(p.inboxNotificationId)}async function te(p){if(p.mention.kind!=="user"&&p.mention.kind!=="group")return Re(p.mention,"Unexpected mention kind");await i.rawPost($`/v2/c/rooms/${p.roomId}/text-mentions`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{userId:p.mention.kind==="user"?p.mention.id:void 0,groupId:p.mention.kind==="group"?p.mention.id:void 0,userIds:p.mention.kind==="group"?p.mention.userIds:void 0,mentionId:p.mentionId})}async function Ae(p){await i.rawDelete($`/v2/c/rooms/${p.roomId}/text-mentions/${p.mentionId}`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function De(p){return i.rawGet($`/v2/c/rooms/${p.roomId}/y-version/${p.versionId}`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function qe(p){await i.rawPost($`/v2/c/rooms/${p.roomId}/version`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}))}async function Vt(p){await i.rawPost($`/v2/c/rooms/${p.roomId}/text-metadata`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{type:p.type,rootKey:p.rootKey})}async function Ue(p){let w=await i.post($`/v2/c/rooms/${p.roomId}/ai/contextual-prompt`,await e.getAuthValue({requestedScope:"room:read",roomId:p.roomId}),{prompt:p.prompt,context:{beforeSelection:p.context.beforeSelection,selection:p.context.selection,afterSelection:p.context.afterSelection},previous:p.previous},{signal:p.signal});if(!w||w.content.length===0)throw new Error("No content returned from server");return w.content[0].text}async function M(p){let w=await i.get($`/v2/c/rooms/${p.roomId}/versions`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}));return{versions:w.versions.map(({createdAt:L,...N})=>({createdAt:new Date(L),...N})),requestedAt:new Date(w.meta.requestedAt)}}async function X(p){let w=await i.get($`/v2/c/rooms/${p.roomId}/versions/delta`,await e.getAuthValue({requestedScope:"comments:read",roomId:p.roomId}),{since:p.since.toISOString()},{signal:p.signal});return{versions:w.versions.map(({createdAt:L,...N})=>({createdAt:new Date(L),...N})),requestedAt:new Date(w.meta.requestedAt)}}async function ue(p){return await(await i.rawGet($`/v2/c/rooms/${p.roomId}/storage`,await e.getAuthValue({requestedScope:"room:read",roomId:p.roomId}))).json()}async function Me(p){let L;p?.query&&(L=Zn(p.query));let N=await i.get($`/v2/c/inbox-notifications`,await e.getAuthValue({requestedScope:"comments:read"}),{cursor:p?.cursor,limit:50,query:L}),be=N.groups.map(ao);return wr.setData(be.map(pe=>[pe.id,pe])),{inboxNotifications:N.inboxNotifications.map(Sn),threads:N.threads.map(Kt),subscriptions:N.subscriptions.map(jt),nextCursor:N.meta.nextCursor,requestedAt:new Date(N.meta.requestedAt)}}async function ct(p){let w;p?.query&&(w=Zn(p.query));let L=await i.get($`/v2/c/inbox-notifications/delta`,await e.getAuthValue({requestedScope:"comments:read"}),{since:p.since.toISOString(),query:w},{signal:p.signal});return{inboxNotifications:{updated:L.inboxNotifications.map(Sn),deleted:L.deletedInboxNotifications.map(Ki)},threads:{updated:L.threads.map(Kt),deleted:L.deletedThreads.map(Bi)},subscriptions:{updated:L.subscriptions.map(jt),deleted:L.deletedSubscriptions.map(ji)},requestedAt:new Date(L.meta.requestedAt)}}async function Je(p){let w;p?.query&&(w=Zn(p.query));let{count:L}=await i.get($`/v2/c/inbox-notifications/count`,await e.getAuthValue({requestedScope:"comments:read"}),{query:w},{signal:p?.signal});return L}async function Ht(){await i.post($`/v2/c/inbox-notifications/read`,await e.getAuthValue({requestedScope:"comments:read"}),{inboxNotificationIds:"all"})}async function fn(p){await i.post($`/v2/c/inbox-notifications/read`,await e.getAuthValue({requestedScope:"comments:read"}),{inboxNotificationIds:p})}let Hn=new Wt(async p=>{let w=p.flat();return await fn(w),w},{delay:50});async function Er(p){await Hn.get(p)}async function mn(){await i.delete($`/v2/c/inbox-notifications`,await e.getAuthValue({requestedScope:"comments:read"}))}async function Bt(p){await i.delete($`/v2/c/inbox-notifications/${p}`,await e.getAuthValue({requestedScope:"comments:read"}))}async function Ii(p){return i.get($`/v2/c/notification-settings`,await e.getAuthValue({requestedScope:"comments:read"}),void 0,{signal:p?.signal})}async function Jr(p){return i.post($`/v2/c/notification-settings`,await e.getAuthValue({requestedScope:"comments:read"}),p)}async function Oi(p){let w;p?.query&&(w=Zn(p.query));let N=await i.get($`/v2/c/threads`,await e.getAuthValue({requestedScope:"comments:read"}),{cursor:p?.cursor,query:w,limit:50});return{threads:N.threads.map(Kt),inboxNotifications:N.inboxNotifications.map(Sn),subscriptions:N.subscriptions.map(jt),nextCursor:N.meta.nextCursor,requestedAt:new Date(N.meta.requestedAt),permissionHints:N.meta.permissionHints}}async function Ri(p){let w=await i.get($`/v2/c/threads/delta`,await e.getAuthValue({requestedScope:"comments:read"}),{since:p.since.toISOString()},{signal:p.signal});return{threads:{updated:w.threads.map(Kt),deleted:w.deletedThreads.map(Bi)},inboxNotifications:{updated:w.inboxNotifications.map(Sn),deleted:w.deletedInboxNotifications.map(Ki)},subscriptions:{updated:w.subscriptions.map(jt),deleted:w.deletedSubscriptions.map(ji)},requestedAt:new Date(w.meta.requestedAt),permissionHints:w.meta.permissionHints}}let Wr=new Wt(async p=>{let w=p.flat(),{groups:L}=await i.post($`/v2/c/groups/find`,await e.getAuthValue({requestedScope:"comments:read"}),{groupIds:w}),N=new Map;for(let be of L)N.set(be.id,ao(be));return w.map(be=>N.get(be))},{delay:50}),wr=cr(Wr);function fe(p){return Wr.get(p)}async function Li(p){let{metadata:w}=await i.get($`/v2/c/urls/metadata`,await e.getAuthValue({requestedScope:"comments:read"}),{url:p});return w}return{getThreads:o,getThreadsSince:s,searchComments:c,createThread:u,getThread:l,deleteThread:h,editThreadMetadata:m,createComment:O,editComment:_,editCommentMetadata:k,deleteComment:F,addReaction:K,removeReaction:se,markThreadAsResolved:z,markThreadAsUnresolved:P,subscribeToThread:C,unsubscribeFromThread:R,markRoomInboxNotificationAsRead:Y,getSubscriptionSettings:U,updateSubscriptionSettings:A,createTextMention:te,deleteTextMention:Ae,getTextVersion:De,createTextVersion:qe,reportTextEditor:Vt,listTextVersions:M,listTextVersionsSince:X,getAttachmentUrl:oe,uploadAttachment:y,getOrCreateAttachmentUrlsStore:G,uploadChatAttachment:re,getOrCreateChatAttachmentUrlsStore:me,getChatAttachmentUrl:Ne,streamStorage:ue,getInboxNotifications:Me,getInboxNotificationsSince:ct,getUnreadInboxNotificationsCount:Je,markAllInboxNotificationsAsRead:Ht,markInboxNotificationAsRead:Er,deleteAllInboxNotifications:mn,deleteInboxNotification:Bt,getNotificationSettings:Ii,updateNotificationSettings:Jr,getUserThreads_experimental:Oi,getUserThreadsSince_experimental:Ri,groupsStore:wr,getGroup:fe,executeContextualPrompt:Ue,getUrlMetadata:Li}}function ws(n){return n.type==="public"?n.publicApiKey:n.token.raw}function rd(n,e){if(n===e)return[0,0];let t=n.split("."),r=e.split("."),i=Math.min(t.length,r.length),s=0;for(;s<i&&t[s]===r[s];s++);let o=t.length-s,c=r.length-s;return[o,c]}function id(n,e){let t=n.split(".");if(e<1||e>t.length+1)throw new Error("Invalid number of levels");let r=[];e>t.length&&r.push("*");for(let i=t.length-e+1;i<t.length;i++){let s=t.slice(0,i);s.length>0&&r.push(s.join(".")+".*")}return r.push(n),r}function go(n){return n===4999||n>=4e3&&n<4100}function cd(n){return n>=4100&&n<4200}function vo(n){return n===1013||n>=4200&&n<4300}function ld(n){return n==="initial"||n==="disconnected"}function ua(n){let e=n.currentState;switch(e){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 n.context.successCount>0?"reconnecting":"connecting";case"@idle.failed":return"disconnected";default:return Re(e,"Unknown state")}}function pa(n,e){return e.find(t=>t>n)??e[e.length-1]}function Qn(n){n.patch({backoffDelay:pa(n.backoffDelay,ha)})}function yo(n){n.patch({backoffDelay:pa(n.backoffDelay,dd)})}function bo(n){n.patch({successCount:0})}function nr(n,e){let t=n===2?wt:n===1?xe:(()=>{});return()=>{t(e)}}function Eo(n){let e="Connection to Liveblocks websocket server";return t=>{fa(n)?xe(`${e} closed prematurely (code: ${n.code}). Retrying in ${t.backoffDelay}ms.`):xe(`${e} could not be established.`,n)}}function Ji(n){let e=[`code: ${n.code}`];return n.reason&&e.push(`reason: ${n.reason}`),t=>{xe(`Connection to Liveblocks websocket server closed (${e.join(", ")}). Retrying in ${t.backoffDelay}ms.`)}}function fa(n){return!(n instanceof Error)&&n.type==="close"}function gd(n){function e(...r){xe(`[FSM #${n.id}]`,...r)}let t=[n.events.didReceiveEvent.subscribe(r=>e(`Event ${r.type}`)),n.events.willTransition.subscribe(({from:r,to:i})=>e("Transitioning",r,"\u2192",i)),n.events.didExitState.subscribe(({state:r,durationMs:i})=>e(`Exited ${r} after ${i.toFixed(0)}ms`)),n.events.didIgnoreEvent.subscribe(r=>e("Ignored event",r.type,r,"(current state won't handle it)"))];return()=>{for(let r of t)r()}}function vd(n){let e=ne(),t=ne(),r=ne(),i=null,s=n.events.didEnterState.subscribe(()=>{let o=ua(n);o!==i&&e.notify(o),i==="connected"&&o!=="connected"?r.notify():i!=="connected"&&o==="connected"&&t.notify(),i=o});return{statusDidChange:e.observable,didConnect:t.observable,didDisconnect:r.observable,unsubscribe:s}}function yd(n,e){let t=Al();t.pause();let r=ne();function i(z,P){return()=>{r.notify({message:z,code:P})}}let s={successCount:0,authValue:null,socket:null,backoffDelay:li},o=new ad(s).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");o.addTransitions("*",{RECONNECT:{target:"@auth.backoff",effect:[Qn,bo]},DISCONNECT:"@idle.initial"}),o.onEnter("@idle.*",bo).addTransitions("@idle.*",{CONNECT:(z,P)=>P.authValue!==null?"@connecting.busy":"@auth.busy"}),o.addTransitions("@auth.backoff",{NAVIGATOR_ONLINE:{target:"@auth.busy",effect:di({backoffDelay:li})}}).addTimedTransition("@auth.backoff",z=>z.backoffDelay,"@auth.busy").onEnterAsync("@auth.busy",()=>so(n.authenticate(),pd,"Timed out during auth"),z=>({target:"@connecting.busy",effect:di({authValue:z.data})}),z=>z.reason instanceof Ut?{target:"@idle.failed",effect:[nr(2,z.reason.message),i(z.reason.message,-1)]}:{target:"@auth.backoff",effect:[Qn,nr(2,`Authentication failed: ${z.reason instanceof Error?z.reason.message:String(z.reason)}`)]});let c=z=>o.send({type:"EXPLICIT_SOCKET_ERROR",event:z}),u=z=>o.send({type:"EXPLICIT_SOCKET_CLOSE",event:z}),h=z=>z.data==="pong"?o.send({type:"PONG"}):t.notify(z);function l(z){z&&(z.removeEventListener("error",c),z.removeEventListener("close",u),z.removeEventListener("message",h),z.close())}o.addTransitions("@connecting.backoff",{NAVIGATOR_ONLINE:{target:"@connecting.busy",effect:di({backoffDelay:li})}}).addTimedTransition("@connecting.backoff",z=>z.backoffDelay,"@connecting.busy").onEnterAsync("@connecting.busy",async(z,P)=>{let C=performance.now(),R=null,y=null,V=null,G=new Promise((oe,re)=>{if(z.authValue===null)throw new Error("No auth authValue");let Q=n.createSocket(z.authValue);V=Q;function me(q){y=q,Q.removeEventListener("message",h),re(q)}let[Ne,U]=sa();e.waitForActorId||U();function A(q){if(Nt(q.data)?.type===W.ROOM_STATE){if(e.enableDebugLogging&&R!==null){let te=performance.now()-R;xe(`[FSM #${o.id}] Socket open \u2192 ROOM_STATE: ${te.toFixed(0)}ms`)}U()}}Q.addEventListener("message",h),e.waitForActorId&&Q.addEventListener("message",A),Q.addEventListener("error",me),Q.addEventListener("close",me),Q.addEventListener("open",()=>{if(R=performance.now(),e.enableDebugLogging){let Y=R-C;xe(`[FSM #${o.id}] Socket epoch \u2192 open: ${Y.toFixed(0)}ms`)}Q.addEventListener("error",c),Q.addEventListener("close",u);let q=()=>{Q.removeEventListener("error",me),Q.removeEventListener("close",me),Q.removeEventListener("message",A)};Ne.then(()=>{oe([Q,q])})})});return so(G,fd,"Timed out during websocket connection").then(([oe,re])=>{if(re(),P.aborted)throw new Error("Aborted");if(y)throw y;return oe}).catch(oe=>{throw l(V),oe})},z=>({target:"@ok.connected",effect:di({socket:z.data,backoffDelay:li})}),z=>{let P=z.reason;if(P instanceof Ut)return{target:"@idle.failed",effect:[nr(2,P.message),i(P.message,-1)]};if(fa(P)){if(P.code===4109)return"@auth.busy";if(vo(P.code))return{target:"@connecting.backoff",effect:[yo,Eo(P)]};if(go(P.code))return{target:"@idle.failed",effect:[nr(2,P.reason),i(P.reason,P.code)]}}return{target:"@auth.backoff",effect:[Qn,Eo(P)]}});let m={target:"@ok.awaiting-pong",effect:z=>{z.socket?.send("ping")}},k=()=>(typeof document<"u"?document:void 0)?.visibilityState==="hidden"&&n.canZombie()?"@idle.zombie":m;if(o.addTimedTransition("@ok.connected",ud,k).addTransitions("@ok.connected",{NAVIGATOR_OFFLINE:k,WINDOW_GOT_FOCUS:m}),o.addTransitions("@idle.zombie",{WINDOW_GOT_FOCUS:"@connecting.backoff"}),o.onEnter("@ok.*",z=>{z.patch({successCount:z.successCount+1});let P=setTimeout(t.unpause,0);return C=>{l(C.socket),C.patch({socket:null}),clearTimeout(P),t.pause()}}).addTransitions("@ok.awaiting-pong",{PONG:"@ok.connected"}).addTimedTransition("@ok.awaiting-pong",hd,{target:"@connecting.busy",effect:nr(1,"Received no pong from server, assume implicit connection loss.")}).addTransitions("@ok.*",{EXPLICIT_SOCKET_ERROR:(z,P)=>P.socket?.readyState===1?null:{target:"@connecting.backoff",effect:Qn},EXPLICIT_SOCKET_CLOSE:z=>go(z.event.code)?{target:"@idle.failed",effect:[md,i(z.event.reason,z.event.code)]}:cd(z.event.code)?z.event.code===4109?"@auth.busy":{target:"@auth.backoff",effect:[Qn,Ji(z.event)]}:vo(z.event.code)?{target:"@connecting.backoff",effect:[yo,Ji(z.event)]}:{target:"@connecting.backoff",effect:[Qn,Ji(z.event)]}}),typeof document<"u"){let z=typeof document<"u"?document:void 0,P=typeof window<"u"?window:void 0,C=P??z;o.onEnter("*",R=>{function y(){o.send({type:"NAVIGATOR_OFFLINE"})}function V(){o.send({type:"NAVIGATOR_ONLINE"})}function G(){z?.visibilityState==="visible"&&o.send({type:"WINDOW_GOT_FOCUS"})}return P?.addEventListener("online",V),P?.addEventListener("offline",y),C?.addEventListener("visibilitychange",G),()=>{C?.removeEventListener("visibilitychange",G),P?.removeEventListener("online",V),P?.removeEventListener("offline",y),l(R.socket)}})}let O=[],{statusDidChange:_,didConnect:F,didDisconnect:K,unsubscribe:se}=vd(o);return O.push(se),e.enableDebugLogging&&O.push(gd(o)),o.start(),{machine:o,cleanups:O,events:{statusDidChange:_,didConnect:F,didDisconnect:K,onMessage:t.observable,onConnectionError:r.observable}}}function Wi(n,e){let t=n[n.length-1];return e.includes(t)?n.slice(0,-1):n}function xd(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!Object.is(n[t],e[t]))return!1;return!0}function Ad(n,e){if(!Ce(n)||!Ce(e))return!1;let t=Object.keys(n);return t.length!==Object.keys(e).length?!1:t.every(r=>Object.prototype.hasOwnProperty.call(e,r)&&Object.is(n[r],e[r]))}function yi(n,e){if(Object.is(n,e))return!0;let t=Array.isArray(n),r=Array.isArray(e);return t||r?!t||!r?!1:xd(n,e):Ad(n,e)}function Td(n,e){if(!Ce(n)||!Ce(e))return yi(n,e);let t=Object.keys(n);return t.length!==Object.keys(e).length?!1:t.every(r=>Object.prototype.hasOwnProperty.call(e,r)&&yi(n[r],e[r]))}function Id(){let n=new Qe(r=>new zd);function e(r){return n.getOrCreate(r??Dr)}function t(r){let i=n.getOrCreate(Dr).get(),s=n.get(r)?.get()??[];return[...i,...s]}return{getKnowledgeStack:e,getKnowledgeForChat:t}}function Gi(){return new Date().toISOString()}function Od(){let n=new Qe(o=>new Qe(c=>new Et(void 0))),e=new Qe(o=>{let[c,u]=Nt(o);return Dn.from(()=>(u!==void 0?n.getOrCreate(u).getOrCreate(c):void 0)?.get()??n.getOrCreate(Dr).getOrCreate(c).get())});function t(o,c){let u=JSON.stringify(c!==void 0?[o,c]:[o]);return e.getOrCreate(u)}function r(o,c,u){if(!c.execute&&!c.render)throw new Error("A tool definition must have an execute() function, a render() function, or both.");let h=u??Dr;return n.getOrCreate(h).getOrCreate(o).set(c),()=>i(h,o)}function i(o,c){let u=n.get(o);if(u===void 0)return;let h=u.get(c);h!==void 0&&h.set(void 0)}function s(o){let c=n.get(Dr),u=n.get(o);return Array.from([...c?.entries()??[],...u?.entries()??[]]).flatMap(([h,l])=>{let m=l.get();return m&&(m.enabled??!0)?[{name:h,description:m.description,parameters:m.parameters}]:[]})}return{getToolDescriptions:s,getTool\u03A3:t,registerTool:r}}function Rd(n,e){let t=new Set,r=new Set,i=new Qe(C=>new Mr(new kd(R=>R.id,R=>R.parentId,(R,y)=>R.createdAt<y.createdAt))),s=new Mr(new Map);function o(C,R,y,V){let G=`ms_${ze()}`,oe=Gi();return l(R==="user"?{id:G,chatId:C,role:R,parentId:y,createdAt:oe,content:V,_optimistic:!0}:{id:G,chatId:C,role:R,parentId:y,createdAt:oe,status:"generating",contentSoFar:[],copilotId:V,_optimistic:!0}),G}function c(C){dn(()=>{for(let R of C)l(R)})}function u(C,R){let y=i.get(C);if(!y)return;let V=y.get().get(R);!V||V.deletedAt||(V.role==="assistant"&&V.status!=="completed"?l({...V,deletedAt:Gi(),contentSoFar:[]}):l({...V,deletedAt:Gi(),content:[]}))}function h(C){let R=i.get(C);R!==void 0&&R.mutate(y=>y.clear())}function l(C){dn(()=>{if(i.getOrCreate(C.chatId).mutate(y=>y.upsert(C)),C.role==="assistant"&&C.status==="generating"?s.mutate(y=>{y.set(C.id,structuredClone(C))}):s.mutate(y=>{y.delete(C.id)}),C.role==="assistant"&&C.status==="awaiting-tool"){if(t.has(C.id))for(let y of C.contentSoFar.filter(V=>V.type==="tool-invocation"&&V.stage==="executing")){if(!r.has(y.invocationId))r.add(y.invocationId);else continue;let V=n.getTool\u03A3(y.name,C.chatId).get()?.execute;V&&(async()=>{let G=await V(y.args,{name:y.name,invocationId:y.invocationId});return await e(C.chatId,C.id,y.invocationId,G??{data:{}},{copilotId:C.copilotId})})().catch(G=>{wt(`Error trying to respond to tool-call: ${String(G)} (in execute())`)})}}else C.role==="assistant"&&C.status==="generating"||t.delete(C.id)})}function m(C,R){s.mutate(y=>{let V=y.get(C);return V===void 0?!1:(Pd(V.contentSoFar,R),y.set(C,V),!0)})}function*k(){for(let C of i.values())for(let R of C.get())R.role==="assistant"&&R.status==="generating"&&!R._optimistic&&(yield R)}function O(){dn(()=>{s.mutate(C=>{let R=!1;for(let[y,V]of C)V._optimistic||(C.delete(y),R=!0);return R}),c(Array.from(k()).map(C=>({...C,status:"failed",errorReason:"Lost connection"})))})}function _(C){for(let R of i.values()){let y=R.get().get(C);if(y)return y}}function F(C){let R=C.next();return R.done?void 0:R.value}function K(C,R){function y(re){if(!re.deletedAt)return!0;for(let Q of C.walkDown(re.id,me=>!me.deletedAt))return!0;return!1}function V(re){let Q=[],me=null;for(let Ne of C.walkUp(re.id)){let U=F(C.walkLeft(Ne.id,y))?.id??null,A=F(C.walkRight(Ne.id,y))?.id??null;if(!Ne.deletedAt||U||A){let q={...Ne,navigation:{parent:null,prev:U,next:A}};me!==null&&(me.navigation.parent=q.id),me=q,Q.push(q)}}return Q.reverse()}function G(){let re=C.sorted.findRight(Q=>!Q.deletedAt);return re?V(re):[]}if(R===null)return G();let oe=C.get(R);if(!oe)return G();for(let re of C.walkUp(oe.id)){for(let Q of C.walkDown(re.id,me=>!me.deletedAt))return V(Q);if(!re.deletedAt)return V(re)}return G()}let se=new Qe(C=>new Qe(R=>{let y=Dn.from(()=>{let V=i.getOrCreate(C).get();return K(V,R)},Td);return Dn.from(()=>{let V=s.get();return y.get().map(G=>{if(G.role!=="assistant"||G.status!=="generating")return G;let oe=V.get(G.id);return oe===void 0?G:{...G,contentSoFar:oe.contentSoFar}})},yi)}));function z(C,R){return se.getOrCreate(C).getOrCreate(R||null)}function P(C){return i.getOrCreate(C).get().sorted.findRight(V=>V.role==="assistant"&&!V.deletedAt)?.copilotId}return{getMessageById:_,getChatMessagesForBranch\u03A3:z,getLastUsedCopilotId:P,createOptimistically:o,upsert:l,upsertMany:c,remove:u,removeByChatId:h,addDelta:m,failAllPending:O,markMine(C){t.add(C)},*getAutoExecutingMessageIds(){for(let C of t){let R=_(C);R?.role==="assistant"&&R.status==="awaiting-tool"&&R.contentSoFar.some(V=>V.type==="tool-invocation"&&V.stage==="executing"?typeof n.getTool\u03A3(V.name,R.chatId).get()?.execute=="function":!1)&&(yield R.id)}}}}function Ld(){let n=new Dl;function e(o){dn(()=>{for(let c of o)n.upsert(c)})}function t(o){n.upsert(o)}function r(o){n.markDeleted(o)}function i(o){return n.getEvenIfDeleted(o)}function s(o){return n.signal.get().findMany(o)}return{getChatById:i,findMany:s,upsert:t,upsertMany:e,markDeleted:r}}function Dd(n){let e=new ma(n.delegates,n.enableDebugLogging,!1),t=Ld(),r=Od(),i=Id(),s=Rd(r,Q),o={staticSessionInfoSig:new Et(null),dynamicSessionInfoSig:new Et(null),pendingCmds:new Map,chatsStore:t,messagesStore:s,toolsStore:r,knowledgeStore:i},c=new Et("initial"),u=25,h=[],l=null;function m(){let U=h;h=[],l!==null&&(clearTimeout(l),l=null),dn(()=>{for(let{id:A,delta:q}of U)o.messagesStore.addDelta(A,q)})}function k(U,A){h.push({id:U,delta:A}),l===null&&(l=setTimeout(m,u))}let O;function _(U){let A=e.authValue;if(A!==null){let q=ws(A);if(q!==O)if(O=q,A.type==="secret"){let Y=A.token.parsed;o.staticSessionInfoSig.set({userId:Y.uid,userInfo:Y.ui})}else o.staticSessionInfoSig.set({userId:void 0,userInfo:void 0})}c.set(U)}let F,K=!1;function se(U){U==="reconnecting"?F=setTimeout(()=>{K=!0},n.lostConnectionTimeout):(clearTimeout(F),K&&(K=!1))}function z(){}function P(){m()}function C(U){if(typeof U.data!="string")return;let A=Nt(U.data);if(!A)return;let q="cmdId"in A?A.cmdId:A.event==="cmd-failed"?A.failedCmdId:void 0,Y=o.pendingCmds.get(q);if(q&&!Y){xe("Ignoring unexpected command response. Already timed out, or not for us?",A);return}if("event"in A)if(A.event==="delta"){let{id:te,delta:Ae}=A;k(te,Ae)}else dn(()=>{switch(m(),A.event){case"cmd-failed":Y?.reject(new Error(A.error));break;case"settle":{o.messagesStore.upsert(A.message);break}case"warning":xe(A.message);break;case"error":wt(A.error);break;case"rebooted":o.messagesStore.failAllPending();break;case"sync":for(let te of A["-messages"]??[])o.messagesStore.remove(te.chatId,te.id);for(let te of A["-chats"]??[])o.chatsStore.markDeleted(te),o.messagesStore.removeByChatId(te);for(let te of A.clear??[])o.messagesStore.removeByChatId(te);A.chats&&o.chatsStore.upsertMany(A.chats),A.messages&&o.messagesStore.upsertMany(A.messages);break;default:return Re(A,"Unhandled case")}});else switch(A.cmd){case"get-chats":o.chatsStore.upsertMany(A.chats);break;case"get-or-create-chat":o.chatsStore.upsert(A.chat);break;case"delete-chat":o.chatsStore.markDeleted(A.chatId),o.messagesStore.removeByChatId(A.chatId);break;case"get-message-tree":o.chatsStore.upsert(A.chat),o.messagesStore.upsertMany(A.messages);break;case"delete-message":o.messagesStore.remove(A.chatId,A.messageId);break;case"clear-chat":o.messagesStore.removeByChatId(A.chatId);break;case"ask-in-chat":A.sourceMessage&&o.messagesStore.upsert(A.sourceMessage),o.messagesStore.upsert(A.targetMessage);break;case"abort-ai":break;case"set-tool-result":A.ok&&o.messagesStore.upsert(A.message);break;default:return Re(A,"Unhandled case")}Y?.resolve(A)}e.events.onMessage.subscribe(C),e.events.statusDidChange.subscribe(_),e.events.statusDidChange.subscribe(se),e.events.didConnect.subscribe(z),e.events.didDisconnect.subscribe(P),e.events.onConnectionError.subscribe(({message:U,code:A})=>{process.env.NODE_ENV!=="production"&&wt(`Connection to websocket server closed. Reason: ${U} (code: ${A}).`)});function R(){e.getStatus()==="initial"&&e.connect()}async function y(U){R(),e.getStatus()!=="connected"&&await e.events.didConnect.waitUntil();let{promise:A,resolve:q,reject:Y}=ar(),te=AbortSignal.timeout(_d);te.addEventListener("abort",()=>Y(te.reason),{once:!0});let Ae=ze(7);return o.pendingCmds.set(Ae,{resolve:q,reject:Y}),V({...U,cmdId:Ae}),A.finally(()=>{o.pendingCmds.delete(Ae)}).catch(De=>{throw wt(De.message),De})}function V(U){e.send(JSON.stringify({...U}))}function G(U={}){return y({cmd:"get-chats",cursor:U.cursor,query:U.query})}function oe(U,A){return y({cmd:"get-or-create-chat",id:U,options:A})}function re(U){return y({cmd:"get-message-tree",chatId:U})}async function Q(U,A,q,Y,te){let Ae=o.knowledgeStore.getKnowledgeForChat(U),De=o.toolsStore.getToolDescriptions(U),qe=await y({cmd:"set-tool-result",chatId:U,messageId:A,invocationId:q,result:Y,generationOptions:{copilotId:te?.copilotId,stream:te?.stream,timeout:te?.timeout,knowledge:Ae.length>0?Ae:void 0,tools:De.length>0?De:void 0}});qe.ok&&s.markMine(qe.message.id)}function me(){for(let U of o.messagesStore.getAutoExecutingMessageIds())y({cmd:"abort-ai",messageId:U}).catch(()=>{})}return(typeof window<"u"?window:void 0)?.addEventListener("beforeunload",me,{once:!0}),Object.defineProperty({[Ct]:{context:o},connectInitially:R,disconnect:()=>e.disconnect(),getChats:G,getOrCreateChat:oe,deleteChat:U=>y({cmd:"delete-chat",chatId:U}),getMessageTree:re,deleteMessage:(U,A)=>y({cmd:"delete-message",chatId:U,messageId:A}),clearChat:U=>y({cmd:"clear-chat",chatId:U}),askUserMessageInChat:async(U,A,q,Y)=>{let te=o.knowledgeStore.getKnowledgeForChat(U),Ae=Y?.knowledge||[],De=[...te,...Ae],qe=o.toolsStore.getToolDescriptions(U);return s.markMine(q),await y({cmd:"ask-in-chat",chatId:U,sourceMessage:A,targetMessageId:q,generationOptions:{copilotId:Y?.copilotId,stream:Y?.stream,timeout:Y?.timeout,knowledge:De.length>0?De:void 0,tools:qe.length>0?qe:void 0}})},abort:U=>y({cmd:"abort-ai",messageId:U}),setToolResult:Q,getStatus:()=>e.getStatus(),signals:{getChatMessagesForBranch\u03A3:o.messagesStore.getChatMessagesForBranch\u03A3,getTool\u03A3:o.toolsStore.getTool\u03A3,status\u03A3:c},getChatById:o.chatsStore.getChatById,queryChats:o.chatsStore.findMany,getLastUsedCopilotId:o.messagesStore.getLastUsedCopilotId,registerKnowledgeLayer:(U,A)=>{let q=o.knowledgeStore.getKnowledgeStack(A),Y=q.registerLayer(U);return{layerKey:Y,deregister:()=>q.deregisterLayer(Y)}},updateKnowledge:(U,A,q,Y)=>{o.knowledgeStore.getKnowledgeStack(Y).updateKnowledge(U,q??ze(),A)},registerTool:o.toolsStore.registerTool},Ct,{enumerable:!1})}function Md(n,e){return t=>{let r=e??(typeof WebSocket>"u"?void 0:WebSocket);if(r===void 0)throw new Ut("To use Liveblocks client in a non-DOM environment, you need to provide a WebSocket polyfill.");let i=new URL(n);if(i.protocol=i.protocol==="http:"?"ws":"wss",i.pathname="/ai/v7",t.type==="secret")i.searchParams.set("tok",t.token.raw);else{if(t.type==="public")throw new Error("Public key not supported with AI Copilots");return Re(t,"Unhandled case")}return i.searchParams.set("version",ln||"dev"),new r(i.toString())}}function So(n,e,t,r){let i=zl(n,s=>s.type===e.type&&t(s)===t(e));i>-1?n[i]=e:(ds(n[n.length-1],r),n.push(e))}function ds(n,e){n?.type==="reasoning"&&(n.endedAt??(n.endedAt=e))}function Pd(n,e){if(e===null)return;let t=n.filter(o=>o.type!=="sources"),r=n.filter(o=>o.type==="sources").flatMap(o=>o.sources),i=new Date().toISOString(),s=t[t.length-1];switch(e.type){case"text-delta":s?.type==="text"?s.text+=e.textDelta:(ds(s,i),t.push({type:"text",text:e.textDelta}));break;case"reasoning-delta":s?.type==="reasoning"?s.text+=e.textDelta:(ds(s,i),t.push({type:"reasoning",text:e.textDelta,startedAt:i}));break;case"tool-stream":{let o=Nd(e.invocationId,e.name);t.push(o);break}case"tool-delta":{s?.type==="tool-invocation"&&s.stage==="receiving"&&s.__appendDelta?.(e.delta);break}case"tool-invocation":So(t,e,o=>o.invocationId,i);break;case"retrieval":So(t,e,o=>o.id,i);break;case"source":{r.push(e);break}default:return Re(e,"Unhandled case")}r.length>0&&t.push({type:"sources",sources:r}),n.length=0,n.push(...t)}function Nd(n,e,t=""){let r=new Cd(t);return{type:"tool-invocation",stage:"receiving",invocationId:n,name:e,get partialArgsText(){return r.source},get partialArgs(){return r.json},__appendDelta(i){r.append(i)}}}function us(n){return n.includes("room:write")}function Ea(n){return n.includes("comments:write")||n.includes("room:write")}function Ud(n){return Ce(n)&&(n.k==="acc"||n.k==="id")}function Co(n){let e=n.split(".");if(e.length!==3)throw new Error("Authentication error: invalid JWT token");let t=Nt(kl(e[1]));if(!(t&&Ud(t)))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");return{raw:n,parsed:t}}function Fd(n,e){let t=Vd(n),r=new Set,i=[],s=[],o=new Map;function c(){r.clear(),i.length=0,s.length=0,o.clear()}function u(k,O){return k==="comments:read"?O.includes("comments:read")||O.includes("comments:write")||O.includes("room:read")||O.includes("room:write"):k==="room:read"?O.includes("room:read")||O.includes("room:write"):!1}function h(k){let O=Math.ceil(Date.now()/1e3);for(let _=i.length-1;_>=0;_--){let F=i[_];if(s[_]<=O){i.splice(_,1),s.splice(_,1);continue}if(F.parsed.k==="id")return F;if(F.parsed.k==="acc"){if(!k.roomId&&Object.entries(F.parsed.perms).length===0)return F;for(let[se,z]of Object.entries(F.parsed.perms))if(k.roomId){if(se.includes("*")&&k.roomId.startsWith(se.replace("*",""))||k.roomId===se&&u(k.requestedScope,z))return F}else if(se.includes("*")&&u(k.requestedScope,z))return F}}}async function l(k){let O=n.polyfills?.fetch??(typeof window>"u"?void 0:window.fetch);if(t.type==="private"){if(O===void 0)throw new Ut("To use Liveblocks client in a non-DOM environment with a url as auth endpoint, you need to provide a fetch polyfill.");let _=await Hd(O,t.url,{room:k.roomId}),F=Co(_.token);if(r.has(F.raw))throw new Ut("The same Liveblocks auth token was issued from the backend before. Caching Liveblocks tokens is not supported.");return e?.(F.parsed),F}if(t.type==="custom"){let _=await t.callback(k.roomId);if(_&&typeof _=="object"){if(typeof _.token=="string"){let F=Co(_.token);return e?.(F.parsed),F}else if(typeof _.error=="string"){let F=`Authentication failed: ${"reason"in _&&typeof _.reason=="string"?_.reason:"Forbidden"}`;throw _.error==="forbidden"?new Ut(F):new Error(F)}}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.")}async function m(k){if(t.type==="public")return{type:"public",publicApiKey:t.publicApiKey};let O=h(k);if(O!==void 0)return{type:"secret",token:O};let _;k.roomId?(_=o.get(k.roomId),_===void 0&&(_=l(k),o.set(k.roomId,_))):(_=o.get("liveblocks-user-token"),_===void 0&&(_=l(k),o.set("liveblocks-user-token",_)));try{let F=await _,se=Math.floor(Date.now()/1e3)+(F.parsed.exp-F.parsed.iat)-30;return r.add(F.raw),i.push(F),s.push(se),{type:"secret",token:F}}finally{k.roomId?o.delete(k.roomId):o.delete("liveblocks-user-token")}}return{reset:c,getAuthValue:m}}function Vd(n){let{publicApiKey:e,authEndpoint:t}=n;if(t!==void 0&&e!==void 0)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(typeof e=="string"){if(e.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(!e.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:e}}if(typeof t=="string")return{type:"private",url:t};if(typeof t=="function")return{type:"custom",callback:t};throw t!==void 0?new Error("The `authEndpoint` option must be a string or a function. For more information: https://liveblocks.io/docs/api-reference/liveblocks-client#createClientAuthEndpoint"):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")}async function Hd(n,e,t){let r=await n(e,{method:"POST",headers:{"Content-Type":"application/json"},body:Un(t)});if(!r.ok){let o=`${(await r.text()).trim()||"reason not provided in auth response"} (${r.status} returned by POST ${e})`;throw $d.includes(r.status)?new Ut(`Unauthorized: ${o}`):new Error(`Failed to authenticate: ${o}`)}let i;try{i=await r.json()}catch(o){throw new Error(`Expected a JSON response when doing a POST request on "${e}". ${String(o)}`)}if(!Ce(i)||typeof i.token!="string")throw new Error(`Expected a JSON response of the form \`{ token: "..." }\` when doing a POST request on "${e}", but got ${Un(i)}`);let{token:s}=i;return{token:s}}function Kd(n){return n.type===B.DELETE_CRDT&&n.id==="ACK"}function jd(n){return n[0]==="root"}function wa(n){return n[1].type===he.OBJECT}function Sa(n){return n[1].type===he.LIST}function Ca(n){return n[1].type===he.MAP}function xa(n){return n[1].type===he.REGISTER}function qd(n){return n[0]==="root"}function*Jd(n){for(let e of n){if(qd(e)){yield[e[0],{type:he.OBJECT,data:e[1]}];continue}switch(e[1]){case he.OBJECT:yield[e[0],{type:he.OBJECT,parentId:e[2],parentKey:e[3],data:e[4]}];break;case he.LIST:yield[e[0],{type:he.LIST,parentId:e[2],parentKey:e[3]}];break;case he.MAP:yield[e[0],{type:he.MAP,parentId:e[2],parentKey:e[3]}];break;case he.REGISTER:yield[e[0],{type:he.REGISTER,parentId:e[2],parentKey:e[3],data:e[4]}];break;default:}}}function Ss(n){let e=Le+(n<0?Aa+n:n);if(e<Le||e>un)throw new Error(`Invalid n value: ${n}`);return String.fromCharCode(e)}function kt(n,e){return n!==void 0&&e!==void 0?Xd(n,e):n!==void 0?Yd(n):e!==void 0?Gd(e):lr}function Gd(n){let e=n.length-1;for(let t=0;t<=e;t++){let r=n.charCodeAt(t);if(!(r<=Le))return t===e?r===Le+1?n.substring(0,t)+Wd:n.substring(0,t)+String.fromCharCode(r-1):n.substring(0,t+1)}return lr}function Yd(n){for(let i=0;i<n.length;i++){let s=n.charCodeAt(i);if(s<Le||s>un)return n+lr}for(;n.length>1&&n.charCodeAt(n.length-1)===Le;)n=n.slice(0,-1);if(n.length===0||n===Ci)return lr;let e=ui;n.length>ui&&(e=ui+Math.ceil((n.length-ui)/Yi)*Yi);let t=xo(n,e);if(t!==null)return t;e+=Yi;let r=xo(n,e);return r!==null?r:n+lr}function xo(n,e){let t=[];for(let s=0;s<e;s++)s<n.length?t.push(n.charCodeAt(s)-Le):t.push(0);let r=1;for(let s=e-1;s>=0&&r;s--){let o=t[s]+r;o>=Aa?(t[s]=0,r=1):(t[s]=o,r=0)}if(r)return null;let i="";for(let s of t)i+=String.fromCharCode(s+Le);for(;i.length>1&&i.charCodeAt(i.length-1)===Le;)i=i.slice(0,-1);return i}function Xd(n,e){if(n<e)return hs(n,e);if(n>e)return hs(e,n);throw new Error("Cannot compute value between two equal positions")}function hs(n,e){let t=0,r=n.length,i=e.length;for(;;){let s=t<r?n.charCodeAt(t):Le,o=t<i?e.charCodeAt(t):un;if(s===o){t++;continue}if(o-s===1){let c=t+1,u=n.substring(0,c);u.length<c&&(u+=Ci.repeat(c-u.length));let h=n.substring(c);return u+hs(h,"")}else return Zd(n,t)+String.fromCharCode(o+s>>1)}}function Zd(n,e){return e<n.length?n.substring(0,e):n+Ci.repeat(e-n.length)}function eu(n){if(n==="")return!1;let e=n.length-1,t=n.charCodeAt(e);if(t<Qd||t>un)return!1;for(let r=0;r<e;r++){let i=n.charCodeAt(r);if(i<Le||i>un)return!1}return!0}function tu(n){let e=[];for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);e.push(r<Le?Le:r>un?un:r)}for(;e.length>0&&e[e.length-1]===Le;)e.length--;return e.length>0?String.fromCharCode(...e):lr}function Pr(n){return eu(n)?n:tu(n)}function nu(n,e){let{getCurrentConnectionId:t,onDispatch:r,isStorageWritable:i=()=>!0}=e,s=0,o=0,c=new Map;return{roomId:n,nodes:c,getNode:u=>c.get(u),addNode:(u,h)=>{c.set(u,h)},deleteNode:u=>{c.delete(u)},generateId:()=>`${t()}:${s++}`,generateOpId:()=>`${t()}:${o++}`,dispatch(u,h,l){r?.(u,h,l)},assertStorageIsWritable:()=>{if(!i())throw new Error("Cannot write to storage with a read only user, please ensure the user has write permissions")}}}function Ao(n,e,t=Pr(e)){return Object.freeze({type:"HasParent",node:n,key:e,pos:t})}function ru(n,e=Pr(n)){return Object.freeze({type:"Orphaned",oldKey:n,oldPos:e})}function iu(n,e){return n._parentPos<e._parentPos}function ie(n,e){return{node:n,type:"LiveList",updates:e}}function er(n,e){return{index:n,type:"set",item:e instanceof hn?e.data:e}}function hi(n,e){return{type:"delete",index:n,deletedItem:e instanceof hn?e.data:e}}function tt(n,e){return{index:n,type:"insert",item:e instanceof hn?e.data:e}}function Cn(n,e,t){return{type:"move",index:e,item:t instanceof hn?t.data:t,previousIndex:n}}function pi(n,e){return n.map((t,r)=>r===0?{...t,intent:"set",deletedId:e}:t)}function $n(n,e){if(Array.isArray(n))return new pn(n.map(t=>$n(t,e)));if(Ce(n)){let t={},r={};for(let s in n){let o=n[s];if(o===void 0)continue;let c=Ce(e)?e[s]:e;c===!1?r[s]=o:c==="atomic"?t[s]=o:t[s]=$n(o,c)}let i=new Ft(t);for(let s in r)i.setLocal(s,r[s]);return i}else return n}function Ma(n,e,t){return xs(n)&&Ce(e)?ps(n,e,"full",t):Cs(n)&&Array.isArray(e)?ou(n,e,t):Ha(n)&&Ce(e)?su(n,t):$n(e,t)}function su(n,e){throw new Error("Reconciling a LiveMap is not supported yet")}function ps(n,e,t,r){let i=n.keys();for(let s in e){i.delete(s);let o=e[s];if(o===void 0){t==="full"&&n.delete(s);continue}let c=Ce(r)?r[s]:r;if(c===!1)n.setLocal(s,o);else if(c==="atomic")n.get(s)!==o&&n.set(s,o);else{let u=n.get(s);if(u===void 0)n.set(s,$n(o,c));else if(cn(u)){let h=Ma(u,o,c);h!==u&&n.set(s,h)}else u!==o&&n.set(s,$n(o,c))}}if(t==="full")for(let s of i)n.delete(s);return n}function ou(n,e,t){let r=n.length,i=e.length;for(let s=0;s<Math.min(r,i);s++){let o=n.get(s),c=e[s];if(cn(o)){let u=Ma(o,c,t);u!==o&&n.set(s,u)}else o!==c&&n.set(s,$n(c,t))}for(let s=r;s<i;s++)n.push($n(e[s],t));for(let s=r-1;s>=i;s--)n.delete(s);return n}function Rr(n){return dr($a(n))}function $a(n){switch(n.type){case B.CREATE_REGISTER:return n.data;case B.CREATE_OBJECT:return new Ft(n.data);case B.CREATE_MAP:return new Fn;case B.CREATE_LIST:return new pn([]);default:return Re(n,"Unknown creation Op")}}function Fa(n,e){return n===e?!0:n.parent.type==="HasParent"?Fa(n.parent.node,e):!1}function Va(n,e,t){if(wa(n))return Ft._deserialize(n,e,t);if(Sa(n))return pn._deserialize(n,e,t);if(Ca(n))return Fn._deserialize(n,e,t);if(xa(n))return hn._deserialize(n,e,t);throw new Error("Unexpected CRDT type")}function au(n,e,t){if(wa(n))return Ft._deserialize(n,e,t);if(Sa(n))return pn._deserialize(n,e,t);if(Ca(n))return Fn._deserialize(n,e,t);if(xa(n))return n[1].data;throw new Error("Unexpected CRDT type")}function cn(n){return Cs(n)||Ha(n)||xs(n)}function ve(n){return cn(n)||cu(n)}function Cs(n){return n instanceof pn}function Ha(n){return n instanceof Fn}function xs(n){return n instanceof Ft}function cu(n){return n instanceof hn}function lu(n){return n===void 0?void 0:cn(n)?n.clone():yr(n)}function ir(n){return n instanceof hn?n.data:n instanceof pn||n instanceof Fn||n instanceof Ft?n:Re(n,"Unknown AbstractCrdt")}function dr(n){return n instanceof Ft||n instanceof Fn||n instanceof pn?n:new hn(n)}function du(n,e){let t=[];return n.forEach((r,i)=>{e.get(i)||t.push({type:B.DELETE_CRDT,id:i})}),e.forEach((r,i)=>{let s=n.get(i);if(s)r.type===he.OBJECT&&(s.type!==he.OBJECT||Un(r.data)!==Un(s.data))&&t.push({type:B.UPDATE_OBJECT,id:i,data:r.data}),r.parentKey!==s.parentKey&&t.push({type:B.SET_PARENT_KEY,id:i,parentKey:J(r.parentKey,"Parent key must not be missing")});else switch(r.type){case he.REGISTER:t.push({type:B.CREATE_REGISTER,id:i,parentId:r.parentId,parentKey:r.parentKey,data:r.data});break;case he.LIST:t.push({type:B.CREATE_LIST,id:i,parentId:r.parentId,parentKey:r.parentKey});break;case he.OBJECT:if(r.parentId===void 0||r.parentKey===void 0)throw new Error("Internal error. Cannot serialize storage root into an operation");t.push({type:B.CREATE_OBJECT,id:i,parentId:r.parentId,parentKey:r.parentKey,data:r.data});break;case he.MAP:t.push({type:B.CREATE_MAP,id:i,parentId:r.parentId,parentKey:r.parentKey});break}}),t}function uu(n,e){let t=n.updates;for(let[r,i]of Zo(e.updates))t[r]=i;return{...e,updates:t}}function hu(n,e){let t=n.updates;for(let[r,i]of Zo(e.updates))t[r]=i;return{...e,updates:t}}function pu(n,e){let t=n.updates;return{...e,updates:t.concat(e.updates)}}function Zi(n,e){return n===void 0?e:n.type==="LiveObject"&&e.type==="LiveObject"?uu(n,e):n.type==="LiveMap"&&e.type==="LiveMap"?hu(n,e):n.type==="LiveList"&&e.type==="LiveList"?pu(n,e):e}function fu(n){Ba=n}function at(n,e){if(process.env.NODE_ENV==="production"||typeof window>"u")return;let t={...n,source:"liveblocks-devtools-client"};(e?.force||Ba)&&window.postMessage(t,"*")}function mu(n){process.env.NODE_ENV==="production"||typeof window>"u"||ko||(ko=!0,ja.subscribe(e=>{switch(e.msg){case"connect":{fu(!0);for(let t of n())at({msg:"room::available",roomId:t,clientVersion:qa});break}}}),at({msg:"wake-up-devtools"},{force:!0}))}function As(n){let e=ms.get(n)??[];ms.delete(n);for(let t of e)t()}function gu(n){As(n.id),Au(n),ms.set(n.id,[n.events.status.subscribe(()=>Su(n)),n.events.storageDidLoad.subscribeOnce(()=>_o(n)),n.events.storageBatch.subscribe(()=>_o(n)),n.events.self.subscribe(()=>Cu(n)),n.events.others.subscribe(()=>xu(n)),n.events.ydoc.subscribe(e=>vu(n,e)),n.events.customEvent.subscribe(e=>wu(n,e))])}function vu(n,e){at({msg:"room::sync::ydoc",roomId:n.id,update:e})}function Eu(){return`event-${yu}-${bu++}`}function wu(n,e){at({msg:"room::events::custom-event",roomId:n.id,event:{type:"CustomEvent",id:Eu(),key:"Event",connectionId:e.connectionId,payload:e.event}})}function Su(n){at({msg:"room::sync::partial",roomId:n.id,status:n.getStatus()})}function _o(n){let e=n.getStorageSnapshot();e&&at({msg:"room::sync::partial",roomId:n.id,storage:e.toTreeNode("root").payload})}function Cu(n){let e=n[Ct].getSelf_forDevTools();e&&at({msg:"room::sync::partial",roomId:n.id,me:e})}function xu(n){let e=n[Ct].getOthers_forDevTools();e&&at({msg:"room::sync::partial",roomId:n.id,others:e})}function Au(n){let e=n.getStorageSnapshot(),t=n[Ct].getSelf_forDevTools(),r=n[Ct].getOthers_forDevTools();n.fetchYDoc(""),at({msg:"room::sync::full",roomId:n.id,status:n.getStatus(),storage:e?.toTreeNode("root").payload??null,me:t,others:r})}function Ja(n){let e=gs.get(n);gs.delete(n),e&&e()}function Tu(n,e){process.env.NODE_ENV==="production"||typeof window>"u"||(at({msg:"room::available",roomId:n,clientVersion:qa}),Ja(n),gs.set(n,ja.subscribe(t=>{switch(t.msg){case"room::subscribe":{t.roomId===n&&gu(e);break}case"room::unsubscribe":{t.roomId===n&&As(n);break}}})))}function ku(n){process.env.NODE_ENV==="production"||typeof window>"u"||(As(n),Ja(n),at({msg:"room::unavailable",roomId:n}))}function _u(n,e=n){process.env.NODE_ENV!=="production"&&(zo.has(e)||(zo.add(e),xe(n)))}function Qi(n,e,t=e){(typeof n=="function"?n():n)&&_u(e,t)}function Oo(n){let e=["email","slack","teams","webPush"],t={[Io]:{value:n,enumerable:!1}};for(let r of e)t[r]={enumerable:!0,get(){let i=this[Io][r];return typeof i>"u"?(wt(`In order to use the '${r}' channel, please set up your project first. For more information: https://liveblocks.io/docs/errors/enable-a-notification-channel`),null):i}};return Tl(null,t)}function Iu(n){return n===null||typeof n=="string"||typeof n=="number"||typeof n=="boolean"}function Wa(n){return Array.isArray(n)}function Ou(n){return!Iu(n)&&!Wa(n)}function Ru(){let n=0,e=0,t;function r(){t=[],n=performance.now(),e=n}function i(o=performance.now()){t.push(o-e),e=o}function s(){let o=performance.now();return i(o),{total:o-n,laps:t}}return{start:r,lap:i,stop:s}}function Lu(n,e){let{connectionId:t,id:r,info:i}=n,s=us(n.scopes);return bt(Si({connectionId:t,id:r,info:i,canWrite:s,canComment:Ea(n.scopes),isReadOnly:!s,presence:e}))}function Mu(n){switch(n.type){case"ROOM_CONNECTION_ERROR":switch(n.code){case 4001:return"Not allowed to connect to the room";case 4005:return"Room is already full";case 4006:return"Kicked out of the room, because the room ID changed";default:return"Could not connect to the room"}case"AI_CONNECTION_ERROR":return n.code===4001?"Not allowed to connect to ai":"Could not connect to the room";case"CREATE_THREAD_ERROR":return"Could not create new thread";case"DELETE_THREAD_ERROR":return"Could not delete thread";case"EDIT_THREAD_METADATA_ERROR":return"Could not edit thread metadata";case"EDIT_COMMENT_METADATA_ERROR":return"Could not edit comment metadata";case"MARK_THREAD_AS_RESOLVED_ERROR":return"Could not mark thread as resolved";case"MARK_THREAD_AS_UNRESOLVED_ERROR":return"Could not mark thread as unresolved";case"SUBSCRIBE_TO_THREAD_ERROR":return"Could not subscribe to thread";case"UNSUBSCRIBE_FROM_THREAD_ERROR":return"Could not unsubscribe from thread";case"CREATE_COMMENT_ERROR":return"Could not create new comment";case"EDIT_COMMENT_ERROR":return"Could not edit comment";case"DELETE_COMMENT_ERROR":return"Could not delete comment";case"ADD_REACTION_ERROR":return"Could not add reaction";case"REMOVE_REACTION_ERROR":return"Could not remove reaction";case"MARK_INBOX_NOTIFICATION_AS_READ_ERROR":return"Could not mark inbox notification as read";case"DELETE_INBOX_NOTIFICATION_ERROR":return"Could not delete inbox notification";case"MARK_ALL_INBOX_NOTIFICATIONS_AS_READ_ERROR":return"Could not mark all inbox notifications as read";case"DELETE_ALL_INBOX_NOTIFICATIONS_ERROR":return"Could not delete all inbox notifications";case"UPDATE_ROOM_SUBSCRIPTION_SETTINGS_ERROR":return"Could not update room subscription settings";case"UPDATE_NOTIFICATION_SETTINGS_ERROR":return"Could not update notification settings";case"LARGE_MESSAGE_ERROR":return"Could not send large message";case"FEED_REQUEST_ERROR":return n.reason??"Feed request failed";default:return Re(n,"Unhandled case")}}function Pu(n){let e=0;return()=>`${n}:${e++}`}function Ro(n,e){return{type:"User",id:`${e.connectionId}`,key:n,payload:{connectionId:e.connectionId,id:e.id,info:e.info,presence:e.presence,isReadOnly:!e.canWrite}}}function Nu(){let n=typeof document<"u"?document:void 0,e={current:null};function t(){n?.visibilityState==="hidden"?e.current=e.current??Date.now():e.current=null}return n?.addEventListener("visibilitychange",t),[e,()=>{n?.removeEventListener("visibilitychange",t)}]}function Uu(){let n=new Map;return{append(e){for(let[t,r]of e)n.set(t,r)},take(){let e=n;return n=new Map,e}}}function $u(n,e){let t=e.roomId,r=n.initialPresence,i=n.initialStorage,s=e.roomHttpClient,[o,c]=Nu(),u={...e.delegates,canZombie(){return e.backgroundKeepAliveTimeout!==void 0&&o.current!==null&&Date.now()>o.current+e.backgroundKeepAliveTimeout&&Xr()!=="synchronizing"}},h=new ma(u,e.enableDebugLogging),l={buffer:{flushTimerID:void 0,lastFlushedAt:0,presenceUpdates:{type:"full",data:r},messages:[],storageOperations:[]},staticSessionInfoSig:new Et(null),dynamicSessionInfoSig:new Et(null),myPresence:new Ol(r),others:new Du,initialStorage:i,idFactory:null,yjsProvider:void 0,yjsProviderDidChange:ne(),pool:nu(t,{getCurrentConnectionId:M,onDispatch:C,isStorageWritable:R}),root:void 0,undoStack:[],redoStack:[],pausedHistory:null,activeBatch:null,unacknowledgedOps:new Map},m=Uu(),k=e.enableDebugLogging?Ru():void 0,O;function _(d){let f=h.authValue;if(f!==null){let v=ws(f);if(v!==O)if(O=v,f.type==="secret"){let g=f.token.parsed;l.staticSessionInfoSig.set({userId:g.uid,userInfo:g.ui})}else l.staticSessionInfoSig.set({userId:void 0,userInfo:void 0})}y.status.notify(d),te()}let F,K=!1;function se(d){d==="reconnecting"?F=setTimeout(()=>{y.lostConnection.notify("lost"),K=!0,l.others.clearOthers(),Ue({others:[{type:"reset"}]})},e.lostConnectionTimeout):(clearTimeout(F),K&&(d==="disconnected"?y.lostConnection.notify("failed"):y.lostConnection.notify("restored"),K=!1))}function z(){l.buffer.presenceUpdates={type:"full",data:{...l.myPresence.get()}},N!==null&&Gr({flush:!1}),fe()}function P(){clearTimeout(l.buffer.flushTimerID)}h.events.onMessage.subscribe(wr),h.events.statusDidChange.subscribe(_),h.events.statusDidChange.subscribe(se),h.events.didConnect.subscribe(z),h.events.didDisconnect.subscribe(P),h.events.onConnectionError.subscribe(({message:d,code:f})=>{let v="ROOM_CONNECTION_ERROR",g=new bi(d,{type:v,code:f,roomId:t});e.errorEventSource.notify(g)||process.env.NODE_ENV!=="production"&&wt(`Connection to websocket server closed. Reason: ${d} (code: ${f}).`)});function C(d,f,v){if(l.activeBatch){for(let g of d)l.activeBatch.ops.push(g);for(let[g,E]of v)l.activeBatch.updates.storageUpdates.set(g,Zi(l.activeBatch.updates.storageUpdates.get(g),E));l.activeBatch.reverseOps.pushLeft(f)}else f.length>0&&Vt(f),d.length>0&&(l.redoStack.length=0,L(d)),Ue({storageUpdates:v})}function R(){let d=l.dynamicSessionInfoSig.get()?.scopes;return d!==void 0?us(d):!0}let y={status:ne(),lostConnection:ne(),customEvent:ne(),self:ne(),myPresence:ne(),others:ne(),storageBatch:ne(),history:ne(),storageDidLoad:ne(),storageStatus:ne(),ydoc:ne(),comments:ne(),feeds:ne(),roomWillDestroy:ne()};async function V(d,f){return s.createTextMention({roomId:t,mentionId:d,mention:f})}async function G(d){return s.deleteTextMention({roomId:t,mentionId:d})}async function oe(d,f){await s.reportTextEditor({roomId:t,type:d,rootKey:f})}async function re(){return s.listTextVersions({roomId:t})}async function Q(d){return s.listTextVersionsSince({roomId:t,since:d.since,signal:d.signal})}async function me(d){return s.getTextVersion({roomId:t,versionId:d})}async function Ne(){return s.createTextVersion({roomId:t})}async function U(d){return s.executeContextualPrompt({roomId:t,...d})}function A(d){h.send(Un(d))}let q=Dn.from(l.staticSessionInfoSig,l.dynamicSessionInfoSig,l.myPresence,(d,f,v)=>{if(d===null||f===null)return null;{let g=us(f.scopes);return{connectionId:f.actor,id:d.userId,info:d.userInfo,presence:v,canWrite:g,canComment:Ea(f.scopes)}}}),Y;function te(){let d=q.get();d!==null&&d!==Y&&(y.self.notify(d),Y=d)}let Ae=Dn.from(q,d=>d!==null?Ro("Me",d):null);function De(d){if(d.size===0)throw new Error("Internal error: cannot load storage without items");if(l.root!==void 0){let g=new Map;for(let[ee,ce]of l.pool.nodes)g.set(ee,ce._serialize());let E=du(g,d),H=ue(E);Ue(H.updates)}else l.root=Ft._fromItems(d,l.pool);let f=q.get()?.canWrite??!0,v=l.root;Ms(()=>{for(let g in l.initialStorage)v.get(g)===void 0&&(f?v.set(g,lu(l.initialStorage[g])):xe(`Attempted to populate missing storage key '${g}', but current user has no write access`))})}function qe(d){l.undoStack.length>=50&&l.undoStack.shift(),l.undoStack.push(d),Bt()}function Vt(d){l.pausedHistory!==null?l.pausedHistory.pushLeft(d):qe(d)}function Ue(d){let f=d.storageUpdates,v=d.others;if(v!==void 0&&v.length>0){let g=l.others.get();for(let E of v)y.others.notify({...E,others:g})}if((d.presence??!1)&&(te(),y.myPresence.notify(l.myPresence.get())),f!==void 0&&f.size>0){let g=Array.from(f.values());y.storageBatch.notify(g)}Zr()}function M(){let d=l.dynamicSessionInfoSig.get();if(d)return d.actor;throw new Error("Internal. Tried to get connection id but connection was never open")}function X(d){let[f,v]=Il(d,ee=>ee.type==="presence"),g=v.map(ee=>ee.opId===void 0?{...ee,opId:l.pool.generateOpId()}:ee),{reverse:E,updates:H}=Me(f,g,!0);return{opsToEmit:g,reverse:E,updates:H}}function ue(d){return Me([],d,!1)}function Me(d,f,v){let g={reverse:new es,storageUpdates:new Map,presence:!1};for(let H of d){let ee={type:"presence",data:{}};for(let ce in H.data)ee.data[ce]=l.myPresence.get()[ce];if(l.myPresence.patch(H.data),l.buffer.presenceUpdates===null)l.buffer.presenceUpdates={type:"partial",data:H.data};else for(let ce in H.data)l.buffer.presenceUpdates.data[ce]=H.data[ce];g.reverse.pushLeft(ee),g.presence=!0}let E=new Set;for(let H of f){let ee;v?ee=0:H.opId!==void 0?(l.unacknowledgedOps.delete(H.opId),ee=2):ee=1;let ce=ct(H,ee);if(ce.modified){let Ve=ce.modified.node._id;Ve&&E.has(Ve)||(g.storageUpdates.set(J(ce.modified.node._id),Zi(g.storageUpdates.get(J(ce.modified.node._id)),ce.modified)),g.reverse.pushLeft(ce.reverse)),(H.type===B.CREATE_LIST||H.type===B.CREATE_MAP||H.type===B.CREATE_OBJECT)&&E.add(H.id)}}return{reverse:Array.from(g.reverse),updates:{storageUpdates:g.storageUpdates,presence:g.presence}}}function ct(d,f){if(Kd(d))return{modified:!1};switch(d.type){case B.DELETE_OBJECT_KEY:case B.UPDATE_OBJECT:case B.DELETE_CRDT:{let v=l.pool.nodes.get(d.id);return v===void 0?{modified:!1}:v._apply(d,f===0)}case B.SET_PARENT_KEY:{let v=l.pool.nodes.get(d.id);return v===void 0?{modified:!1}:v.parent.type==="HasParent"&&Cs(v.parent.node)?v.parent.node._setChildKey(Pr(d.parentKey),v,f):{modified:!1}}case B.CREATE_OBJECT:case B.CREATE_LIST:case B.CREATE_MAP:case B.CREATE_REGISTER:{if(d.parentId===void 0)return{modified:!1};let v=l.pool.nodes.get(d.parentId);return v===void 0?{modified:!1}:v._attachChild(d,f)}}}function Je(d,f){let v={};l.buffer.presenceUpdates===null&&(l.buffer.presenceUpdates={type:"partial",data:{}});for(let g in d){let E=d[g];E!==void 0&&(l.buffer.presenceUpdates.data[g]=E,v[g]=l.myPresence.get()[g])}l.myPresence.patch(d),l.activeBatch?(f?.addToHistory&&l.activeBatch.reverseOps.pushLeft({type:"presence",data:v}),l.activeBatch.updates.presence=!0):(fe(),f?.addToHistory&&Vt([{type:"presence",data:v}]),Ue({presence:!0}))}function Ht(d){if(d.targetActor!==void 0){let v=l.others.getUser(d.actor);l.others.setOther(d.actor,d.data);let g=l.others.getUser(d.actor);if(v===void 0&&g!==void 0)return{type:"enter",user:g}}else l.others.patchOther(d.actor,d.data);let f=l.others.getUser(d.actor);if(f)return{type:"update",updates:d.data,user:f}}function fn(d){let f=l.others.getUser(d.actor);return f?(l.others.removeConnection(d.actor),{type:"leave",user:f}):null}function Hn(d){l.dynamicSessionInfoSig.set({actor:d.actor,nonce:d.nonce,scopes:d.scopes,meta:d.meta}),l.idFactory=Pu(d.actor),te(),d.meta.showBrand===!0&&zu(e.badgeLocation??"bottom-right");for(let f of l.others.connectionIds())d.users[f]===void 0&&l.others.removeConnection(f);for(let f in d.users){let v=d.users[f],g=Number(f);l.others.setConnection(g,v.id,v.info,v.scopes)}return{type:"reset"}}function Er(){return l.undoStack.length>0}function mn(){return l.redoStack.length>0}function Bt(){Pi>0||y.history.notify({canUndo:Er(),canRedo:mn()})}function Ii(d){l.others.setConnection(d.actor,d.id,d.info,d.scopes),l.buffer.messages.push({type:Ee.UPDATE_PRESENCE,data:l.myPresence.get(),targetActor:d.actor}),fe();let f=l.others.getUser(d.actor);return f?{type:"enter",user:f}:void 0}function Jr(d){return Ou(d)?d:null}function Oi(d){let f=Nt(d);return f===void 0?null:Wa(f)?ns(f.map(v=>Jr(v))):ns([Jr(f)])}function Ri(d){if(d.size===0)return;let f=[],v=Array.from(d.values()),g=X(v);f.push({type:Ee.UPDATE_STORAGE,ops:g.opsToEmit}),Ue(g.updates),A(f)}function Wr(d){return d.type===W.FEED_REQUEST_FAILED}function wr(d){if(typeof d.data!="string")return;let f=Oi(d.data);if(f===null||f.length===0)return;let v={storageUpdates:new Map,others:[]};for(let g of f)switch(g.type){case W.USER_JOINED:{let E=Ii(g);E&&v.others.push(E);break}case W.UPDATE_PRESENCE:{let E=Ht(g);E&&v.others.push(E);break}case W.BROADCASTED_EVENT:{let E=l.others.get();y.customEvent.notify({connectionId:g.actor,user:g.actor<0?null:E.find(H=>H.connectionId===g.actor)??null,event:g.event});break}case W.USER_LEFT:{let E=fn(g);E&&v.others.push(E);break}case W.UPDATE_YDOC:{y.ydoc.notify(g);break}case W.ROOM_STATE:{v.others.push(Hn(g));break}case W.STORAGE_CHUNK:k?.lap(),m.append(Jd(g.nodes));break;case W.STORAGE_STREAM_END:{let E=k?.stop();if(E){let H=ce=>`${ce.toFixed(1)}ms`,ee=E.laps.slice(1);xe(`Storage chunk arrival: ${[`total=${H(E.total)}`,`first=${H(E.laps[0])}`,`rest.n=${ee.length}`,`rest.avg=${H(ee.reduce((ce,Ve)=>ce+Ve,0)/ee.length)}`,`rest.max=${H(ee.reduce((ce,Ve)=>Math.max(ce,Ve),0))}`].join(", ")}`)}lt(m.take());break}case W.UPDATE_STORAGE:{let E=ue(g.ops);for(let[H,ee]of E.updates.storageUpdates)v.storageUpdates.set(H,Zi(v.storageUpdates.get(H),ee));break}case W.REJECT_STORAGE_OP:{if(ra("Storage mutation rejection error",g.reason),process.env.NODE_ENV!=="production")throw new Error(`Storage mutations rejected by server: ${g.reason}`);break}case W.THREAD_CREATED:case W.THREAD_DELETED:case W.THREAD_METADATA_UPDATED:case W.THREAD_UPDATED:case W.COMMENT_REACTION_ADDED:case W.COMMENT_REACTION_REMOVED:case W.COMMENT_CREATED:case W.COMMENT_EDITED:case W.COMMENT_DELETED:case W.COMMENT_METADATA_UPDATED:{y.comments.notify(g);break}case W.FEEDS_LIST:{let E=g,H=pe.get(E.requestId);H&&(H.resolve({feeds:E.feeds,nextCursor:E.nextCursor}),pe.delete(E.requestId)),y.feeds.notify(E);break}case W.FEEDS_ADDED:{let E=g;y.feeds.notify(E),Te(E);break}case W.FEEDS_UPDATED:{let E=g;y.feeds.notify(E),Te(E);break}case W.FEED_DELETED:{y.feeds.notify(g),Te(g);break}case W.FEED_MESSAGES_LIST:{let E=g,H=Ie.get(E.requestId);H&&(H.resolve({messages:E.messages,nextCursor:E.nextCursor}),Ie.delete(E.requestId)),y.feeds.notify(E);break}case W.FEED_MESSAGES_ADDED:{let E=g;y.feeds.notify(E),Te(E);break}case W.FEED_MESSAGES_UPDATED:{let E=g;y.feeds.notify(E),Te(E);break}case W.FEED_MESSAGES_DELETED:{y.feeds.notify(g),Te(g);break}case W.FEED_REQUEST_FAILED:{if(!Wr(g))break;let{requestId:E,code:H,reason:ee}=g,ce=new bi(ee??"Feed request failed",{type:"FEED_REQUEST_ERROR",roomId:t,requestId:E,code:H,reason:ee});if(ge.has(E))Oe(E,"error",ce);else if(pe.has(E)){let Ve=pe.get(E);pe.delete(E),Ve?.reject(ce)}else if(Ie.has(E)){let Ve=Ie.get(E);Ie.delete(E),Ve?.reject(ce)}y.feeds.notify(g);break}case W.STORAGE_STATE_V7:default:break}Ue(v)}function fe(){let d=l.buffer.storageOperations;if(d.length>0){for(let g of d)l.unacknowledgedOps.set(g.opId,g);Zr()}if(h.getStatus()!=="connected"){l.buffer.storageOperations=[];return}let f=Date.now(),v=f-l.buffer.lastFlushedAt;if(v>=e.throttleDelay){let g=Li();if(g.length===0)return;A(g),l.buffer={flushTimerID:void 0,lastFlushedAt:f,messages:[],storageOperations:[],presenceUpdates:null}}else clearTimeout(l.buffer.flushTimerID),l.buffer.flushTimerID=setTimeout(fe,e.throttleDelay-v)}function Li(){let d=[];l.buffer.presenceUpdates&&d.push(l.buffer.presenceUpdates.type==="full"?{type:Ee.UPDATE_PRESENCE,targetActor:-1,data:l.buffer.presenceUpdates.data}:{type:Ee.UPDATE_PRESENCE,data:l.buffer.presenceUpdates.data});for(let f of l.buffer.messages)d.push(f);return l.buffer.storageOperations.length>0&&d.push({type:Ee.UPDATE_STORAGE,ops:l.buffer.storageOperations}),d}function p(d,f,v){let g={type:Ee.UPDATE_YDOC,update:d,guid:f,v2:v};l.buffer.messages.push(g),y.ydoc.notify(g),fe()}function w(d,f={shouldQueueEventIfNotReady:!1}){h.getStatus()!=="connected"&&!f.shouldQueueEventIfNotReady||(l.buffer.messages.push({type:Ee.BROADCAST_EVENT,event:d}),fe())}function L(d){let{storageOperations:f}=l.buffer;for(let v of d)f.push(v);fe()}let N=null,be=null,pe=new Map,Ie=new Map,ge=new Map,Fe=new Map;function Oe(d,f,v){let g=ge.get(d);if(g!==void 0){if(clearTimeout(g.timeoutId),ge.delete(d),g.kind==="add-message"&&!g.expectedClientMessageId){let E=Fe.get(g.feedId);if(E!==void 0){let H=E.indexOf(d);H>=0&&E.splice(H,1),E.length===0&&Fe.delete(g.feedId)}}f==="ok"?g.resolve():g.reject(v??new Error("Feed mutation failed"))}}function ae(d,f,v,g){let{promise:E,resolve:H,reject:ee}=ar(),ce=setTimeout(()=>{ge.has(d)&&Oe(d,"error",new Error("Feed mutation timeout"))},ts);if(ge.set(d,{resolve:H,reject:ee,timeoutId:ce,kind:f,feedId:v,messageId:g?.messageId,expectedClientMessageId:g?.expectedClientMessageId}),f==="add-message"&&g?.expectedClientMessageId===void 0){let Ve=Fe.get(v)??[];Ve.push(d),Fe.set(v,Ve)}return E}function Te(d){switch(d.type){case W.FEEDS_ADDED:{for(let f of d.feeds)for(let[v,g]of[...ge])if(g.kind==="add-feed"&&g.feedId===f.feedId){Oe(v,"ok");break}break}case W.FEEDS_UPDATED:{for(let f of d.feeds)for(let[v,g]of[...ge])g.kind==="update-feed"&&g.feedId===f.feedId&&Oe(v,"ok");break}case W.FEED_DELETED:{for(let[f,v]of[...ge])if(v.kind==="delete-feed"&&v.feedId===d.feedId){Oe(f,"ok");break}break}case W.FEED_MESSAGES_ADDED:{for(let f of d.messages){let v=!1;for(let[g,E]of[...ge])if(E.kind==="add-message"&&E.feedId===d.feedId&&E.expectedClientMessageId===f.id){Oe(g,"ok"),v=!0;break}if(!v){let E=Fe.get(d.feedId)?.[0];if(E!==void 0){let H=ge.get(E);H?.kind==="add-message"&&H.expectedClientMessageId===void 0&&Oe(E,"ok")}}}break}case W.FEED_MESSAGES_UPDATED:{for(let f of d.messages)for(let[v,g]of[...ge])g.kind==="update-message"&&g.feedId===d.feedId&&g.messageId===f.id&&Oe(v,"ok");break}case W.FEED_MESSAGES_DELETED:{for(let f of d.messageIds)for(let[v,g]of[...ge])g.kind==="delete-message"&&g.feedId===d.feedId&&g.messageId===f&&Oe(v,"ok");break}default:break}}function lt(d){let f=new Map(l.unacknowledgedOps);De(d),Ri(f),be?.(),Zr(),y.storageDidLoad.notify()}async function et(){if(!h.authValue)return;let d=new Map(await s.streamStorage({roomId:t}));lt(d)}function Gr(d){let f=l.buffer.messages;e.unstable_streamData?et():f.some(v=>v.type===Ee.FETCH_STORAGE)||(f.push({type:Ee.FETCH_STORAGE}),m.take(),k?.start()),d.flush&&fe()}function Yr(){return N===null&&(Gr({flush:!0}),N=new Promise(d=>{be=d}),Zr()),N}function Bn(){let d=l.root;return d!==void 0?d:(Yr(),null)}async function gn(){return l.root!==void 0?Promise.resolve({root:l.root}):(await Yr(),{root:J(l.root)})}function Di(d,f,v){l.buffer.messages.find(g=>g.type===Ee.FETCH_YDOC&&g.vector===d&&g.guid===f&&g.v2===v)||l.buffer.messages.push({type:Ee.FETCH_YDOC,vector:d,guid:f,v2:v}),fe()}async function Mi(d){let f=ze(),{promise:v,resolve:g,reject:E}=ar();pe.set(f,{resolve:g,reject:E});let H={type:Ee.FETCH_FEEDS,requestId:f,cursor:d?.cursor,since:d?.since,limit:d?.limit,metadata:d?.metadata};return l.buffer.messages.push(H),fe(),setTimeout(()=>{pe.has(f)&&(pe.delete(f),E(new Error("Feeds fetch timeout")))},ts),v}async function uc(d,f){let v=ze(),{promise:g,resolve:E,reject:H}=ar();Ie.set(v,{resolve:E,reject:H});let ee={type:Ee.FETCH_FEED_MESSAGES,requestId:v,feedId:d,cursor:f?.cursor,since:f?.since,limit:f?.limit};return l.buffer.messages.push(ee),fe(),setTimeout(()=>{Ie.has(v)&&(Ie.delete(v),H(new Error("Feed messages fetch timeout")))},ts),g}function hc(d,f){let v=ze(),g=ae(v,"add-feed",d),E={type:Ee.ADD_FEED,requestId:v,feedId:d,metadata:f?.metadata,createdAt:f?.createdAt};return l.buffer.messages.push(E),fe(),g}function pc(d,f){let v=ze(),g=ae(v,"update-feed",d),E={type:Ee.UPDATE_FEED,requestId:v,feedId:d,metadata:f};return l.buffer.messages.push(E),fe(),g}function fc(d){let f=ze(),v=ae(f,"delete-feed",d),g={type:Ee.DELETE_FEED,requestId:f,feedId:d};return l.buffer.messages.push(g),fe(),v}function mc(d,f,v){let g=ze(),E=ae(g,"add-message",d,{expectedClientMessageId:v?.id}),H={type:Ee.ADD_FEED_MESSAGE,requestId:g,feedId:d,data:f,id:v?.id,createdAt:v?.createdAt};return l.buffer.messages.push(H),fe(),E}function gc(d,f,v,g){let E=ze(),H=ae(E,"update-message",d,{messageId:f}),ee={type:Ee.UPDATE_FEED_MESSAGE,requestId:E,feedId:d,messageId:f,data:v,updatedAt:g?.updatedAt};return l.buffer.messages.push(ee),fe(),H}function vc(d,f){let v=ze(),g=ae(v,"delete-message",d,{messageId:f}),E={type:Ee.DELETE_FEED_MESSAGE,requestId:v,feedId:d,messageId:f};return l.buffer.messages.push(E),fe(),g}function yc(){if(l.activeBatch)throw new Error("undo is not allowed during a batch");let d=l.undoStack.pop();if(d===void 0)return;l.pausedHistory=null;let f=X(d);Ue(f.updates),l.redoStack.push(f.reverse),Bt();for(let v of f.opsToEmit)l.buffer.storageOperations.push(v);fe()}function bc(){if(l.activeBatch)throw new Error("redo is not allowed during a batch");let d=l.redoStack.pop();if(d===void 0)return;l.pausedHistory=null;let f=X(d);Ue(f.updates),l.undoStack.push(f.reverse),Bt();for(let v of f.opsToEmit)l.buffer.storageOperations.push(v);fe()}function Ec(){l.undoStack.length=0,l.redoStack.length=0}function wc(d){if(l.activeBatch)return d();let f;l.activeBatch={ops:[],updates:{storageUpdates:new Map,presence:!1,others:[]},reverseOps:new es,scheduleHistoryResume:!1};try{f=d()}finally{let v=l.activeBatch;l.activeBatch=null,v.reverseOps.length>0&&Vt(Array.from(v.reverseOps)),v.scheduleHistoryResume&&Ds(),v.ops.length>0&&(l.redoStack.length=0),v.ops.length>0&&L(v.ops),Ue(v.updates),fe()}return f}function Sc(){l.pausedHistory===null&&(l.pausedHistory=new es)}function Ds(){let d=l.pausedHistory;l.pausedHistory=null,d!==null&&d.length>0&&qe(Array.from(d))}function Cc(){if(l.activeBatch!==null){l.activeBatch.scheduleHistoryResume=!0;return}Ds()}let Pi=0;function Ms(d){let f=l.undoStack,v=l.redoStack,g=[],E=[];l.undoStack=g,l.redoStack=E,Pi++;try{return d()}finally{if(Pi--,l.undoStack!==g||l.redoStack!==E)throw new Error("unexpected stack swap during history.disable()");l.undoStack=f,l.redoStack=v}}let Ps=e.createSyncSource();function Xr(){return l.root===void 0?N===null?"not-loaded":"loading":l.unacknowledgedOps.size===0?"synchronized":"synchronizing"}let Ns=Xr();function Zr(){let d=Xr();Ns!==d&&(Ns=d,y.storageStatus.notify(d)),Ps.setSyncStatus(d==="synchronizing"?"synchronizing":"synchronized")}function Us(){return q.get()!==null}async function xc(){for(;!Us();){let{promise:d,resolve:f}=ar(),v=Ni.self.subscribeOnce(f),g=Ni.status.subscribeOnce(f);await d,v(),g()}}function $s(){return Bn()!==null}async function Ac(){for(;!$s();)await gn()}let Tc=Dn.from(l.others.signal,d=>d.map((f,v)=>Ro(`Other ${v}`,f))),Ni={status:y.status.observable,lostConnection:y.lostConnection.observable,customEvent:y.customEvent.observable,others:y.others.observable,self:y.self.observable,myPresence:y.myPresence.observable,storageBatch:y.storageBatch.observable,history:y.history.observable,storageDidLoad:y.storageDidLoad.observable,storageStatus:y.storageStatus.observable,ydoc:y.ydoc.observable,comments:y.comments.observable,feeds:y.feeds.observable,roomWillDestroy:y.roomWillDestroy.observable};async function kc(d){return s.getThreadsSince({roomId:t,since:d.since,signal:d.signal})}async function _c(d){return s.getThreads({roomId:t,query:d?.query,cursor:d?.cursor})}async function zc(d){return s.getThread({roomId:t,threadId:d})}async function Ic(d){return s.createThread({roomId:t,threadId:d.threadId,commentId:d.commentId,metadata:d.metadata,body:d.body,commentMetadata:d.commentMetadata,attachmentIds:d.attachmentIds})}async function Oc(d){return s.deleteThread({roomId:t,threadId:d})}async function Rc({metadata:d,threadId:f}){return s.editThreadMetadata({roomId:t,threadId:f,metadata:d})}async function Lc({threadId:d,commentId:f,metadata:v}){return s.editCommentMetadata({roomId:t,threadId:d,commentId:f,metadata:v})}async function Dc(d){return s.markThreadAsResolved({roomId:t,threadId:d})}async function Mc(d){return s.markThreadAsUnresolved({roomId:t,threadId:d})}async function Pc(d){return s.subscribeToThread({roomId:t,threadId:d})}async function Nc(d){return s.unsubscribeFromThread({roomId:t,threadId:d})}async function Uc(d){return s.createComment({roomId:t,threadId:d.threadId,commentId:d.commentId,body:d.body,metadata:d.metadata,attachmentIds:d.attachmentIds})}async function $c(d){return s.editComment({roomId:t,threadId:d.threadId,commentId:d.commentId,body:d.body,metadata:d.metadata,attachmentIds:d.attachmentIds})}async function Fc({threadId:d,commentId:f}){return s.deleteComment({roomId:t,threadId:d,commentId:f})}async function Vc({threadId:d,commentId:f,emoji:v}){return s.addReaction({roomId:t,threadId:d,commentId:f,emoji:v})}async function Hc({threadId:d,commentId:f,emoji:v}){return await s.removeReaction({roomId:t,threadId:d,commentId:f,emoji:v})}function Bc(d){return{type:"localAttachment",status:"idle",id:Yl(),name:d.name,size:d.size,mimeType:d.type,file:d}}async function Kc(d,f={}){return s.uploadAttachment({roomId:t,attachment:d,signal:f.signal})}function jc(d){return s.getAttachmentUrl({roomId:t,attachmentId:d})}function Fs(d){return s.getSubscriptionSettings({roomId:t,signal:d?.signal})}function Vs(d){return s.updateSubscriptionSettings({roomId:t,settings:d})}async function qc(d){await s.markRoomInboxNotificationAsRead({roomId:t,inboxNotificationId:d})}let Hs=e.createSyncSource();function Ui(d){return Hs.setSyncStatus(d==="synchronizing"||d==="loading"?"synchronizing":"synchronized")}return Object.defineProperty({[Ct]:{get presenceBuffer(){return yr(l.buffer.presenceUpdates?.data??null)},get undoStack(){return yr(l.undoStack)},get nodeCount(){return l.pool.nodes.size},getYjsProvider(){return l.yjsProvider},setYjsProvider(d){l.yjsProvider?.off("status",Ui),l.yjsProvider=d,d?.on("status",Ui),l.yjsProviderDidChange.notify()},yjsProviderDidChange:l.yjsProviderDidChange.observable,reportTextEditor:oe,createTextMention:V,deleteTextMention:G,listTextVersions:re,listTextVersionsSince:Q,getTextVersion:me,createTextVersion:Ne,executeContextualPrompt:U,getSelf_forDevTools:()=>Ae.get(),getOthers_forDevTools:()=>Tc.get(),simulate:{explicitClose:d=>h._privateSendMachineEvent({type:"EXPLICIT_SOCKET_CLOSE",event:d}),rawSend:d=>h.send(d),incomingMessage:d=>wr(new MessageEvent("message",{data:d}))},attachmentUrlsStore:s.getOrCreateAttachmentUrlsStore(t)},id:t,subscribe:Fu(t,y,e.errorEventSource),connect:()=>h.connect(),reconnect:()=>h.reconnect(),disconnect:()=>h.disconnect(),destroy:()=>{pe.forEach(v=>v.reject(new Error("Room destroyed"))),Ie.forEach(v=>v.reject(new Error("Room destroyed")));let{roomWillDestroy:d,...f}=y;for(let v of Object.values(f))v.dispose();y.roomWillDestroy.notify(),l.yjsProvider?.off("status",Ui),Ps.destroy(),Hs.destroy(),c(),h.destroy(),d.dispose()},updatePresence:Je,updateYDoc:p,broadcastEvent:w,batch:wc,history:{undo:yc,redo:bc,canUndo:Er,canRedo:mn,clear:Ec,pause:Sc,resume:Cc,disable:Ms},fetchYDoc:Di,fetchFeeds:Mi,fetchFeedMessages:uc,addFeed:hc,updateFeed:pc,deleteFeed:fc,addFeedMessage:mc,updateFeedMessage:gc,deleteFeedMessage:vc,getStorage:gn,getStorageSnapshot:Bn,getStorageStatus:Xr,isPresenceReady:Us,isStorageReady:$s,waitUntilPresenceReady:oo(xc),waitUntilStorageReady:oo(Ac),events:Ni,getStatus:()=>h.getStatus(),getSelf:()=>q.get(),getPresence:()=>l.myPresence.get(),getOthers:()=>l.others.get(),getThreads:_c,getThreadsSince:kc,getThread:zc,createThread:Ic,deleteThread:Oc,editThreadMetadata:Rc,markThreadAsResolved:Dc,markThreadAsUnresolved:Mc,subscribeToThread:Pc,unsubscribeFromThread:Nc,createComment:Uc,editComment:$c,editCommentMetadata:Lc,deleteComment:Fc,addReaction:Vc,removeReaction:Hc,prepareAttachment:Bc,uploadAttachment:Kc,getAttachmentUrl:jc,getNotificationSettings:Fs,getSubscriptionSettings:Fs,updateNotificationSettings:Vs,updateSubscriptionSettings:Vs,markInboxNotificationAsRead:qc},Ct,{enumerable:!1})}function Fu(n,e,t){function r(o,c){return e.storageBatch.subscribe(u=>{let h=u.filter(l=>Fa(l.node,o));h.length>0&&c(h)})}function i(o,c){return e.storageBatch.subscribe(u=>{for(let h of u)h.node._id===o._id&&c(h.node)})}function s(o,c,u){if(typeof o=="string"&&Vu(o)){if(typeof c!="function")throw new Error("Second argument must be a callback function");let h=c;switch(o){case"event":return e.customEvent.subscribe(h);case"my-presence":return e.myPresence.subscribe(h);case"others":{let l=h;return e.others.subscribe(m=>{let{others:k,...O}=m;return l(k,O)})}case"error":return t.subscribe(l=>{if(l.roomId===n)return h(l)});case"status":return e.status.subscribe(h);case"lost-connection":return e.lostConnection.subscribe(h);case"history":return e.history.subscribe(h);case"storage-status":return e.storageStatus.subscribe(h);case"comments":return e.comments.subscribe(h);default:return Re(o,`"${String(o)}" is not a valid event name`)}}if(c===void 0||typeof o=="function")if(typeof o=="function"){let h=o;return e.storageBatch.subscribe(h)}else throw new Error("Please specify a listener callback");if(ve(o)){let h=o;return u?.isDeep?r(h,c):i(h,c)}throw new Error(`${String(o)} is not a value that can be subscribed to.`)}return s}function Vu(n){return n==="my-presence"||n==="others"||n==="event"||n==="error"||n==="history"||n==="status"||n==="storage-status"||n==="lost-connection"||n==="connection"||n==="comments"}function Hu(n,e){return async()=>e.getAuthValue({requestedScope:"room:read",roomId:n})}function Bu(n,e,t){return r=>{let i=t??(typeof WebSocket>"u"?void 0:WebSocket);if(i===void 0)throw new Ut("To use Liveblocks client in a non-DOM environment, you need to provide a WebSocket polyfill.");let s=new URL(e);if(s.protocol=s.protocol==="http:"?"ws":"wss",s.pathname="/v8",s.searchParams.set("roomId",n),r.type==="secret")s.searchParams.set("tok",r.token.raw);else if(r.type==="public")s.searchParams.set("pubkey",r.publicApiKey);else return Re(r,"Unhandled case");return s.searchParams.set("version",ln||"dev"),new i(s.toString())}}function th(n){return typeof n=="string"&&n.startsWith("http")?n:Bd}function nh(n){try{return new URL(n).hostname==="localhost"}catch{return!1}}function Ts(n){let e=n,t=th(e.baseUrl),r=process.env.NODE_ENV!=="production"&&nh(t)&&e.__DANGEROUSLY_disableThrottling?0:rh(e.throttle??qu),i=ih(e.lostConnectionTimeout??Xu),s=Lo(e.backgroundKeepAliveTimeout),o=new Et(void 0),c=Fd(n,M=>{o.set(()=>M.uid)}),u=e.polyfills?.fetch||globalThis.fetch?.bind(globalThis),h=td({baseUrl:t,fetchPolyfill:u,currentUserId:o,authManager:c}),l=new Map,m=Dd({userId:o.get(),lostConnectionTimeout:i,backgroundKeepAliveTimeout:Lo(e.backgroundKeepAliveTimeout),polyfills:e.polyfills,delegates:{createSocket:Md(t,e.polyfills?.WebSocket),authenticate:async()=>{let M=await c.getAuthValue({requestedScope:"room:read"});if(M.type==="public")throw new Ut("Cannot use AI Copilots with a public API key");return M},canZombie:()=>!1}});function k(M){ku(M.id),l.delete(M.id),M.destroy()}function O(M){let X=()=>{let ue=X;M.unsubs.delete(ue)?M.unsubs.size===0&&k(M.room):xe("This leave function was already called. Calling it more than once has no effect.")};return M.unsubs.add(X),{room:M.room,leave:X}}function _(M,...X){let ue=l.get(M);if(ue!==void 0)return O(ue);let Me=X[0]??{},ct=(typeof Me.initialPresence=="function"?Me.initialPresence(M):Me.initialPresence)??{},Je=(typeof Me.initialStorage=="function"?Me.initialStorage(M):Me.initialStorage)??{},Ht;if(xs(Je)){let mn={};for(let Bt of Je.keys())mn[Bt]=Je.get(Bt);Ht=mn}else Ht=Je;let fn=$u({initialPresence:ct,initialStorage:Ht},{roomId:M,throttleDelay:r,lostConnectionTimeout:i,backgroundKeepAliveTimeout:s,polyfills:e.polyfills,delegates:e.mockedDelegates??{createSocket:Bu(M,t,e.polyfills?.WebSocket),authenticate:Hu(M,c)},enableDebugLogging:e.enableDebugLogging,baseUrl:t,errorEventSource:Y,unstable_streamData:!!e.unstable_streamData,roomHttpClient:h,createSyncSource:De,badgeLocation:e.badgeLocation??"bottom-right"}),Hn={room:fn,unsubs:new Set};if(l.set(M,Hn),mu(()=>Array.from(l.keys())),Tu(M,fn),Me.autoConnect??!0){if(typeof atob>"u"){if(e.polyfills?.atob===void 0)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");global.atob=e.polyfills.atob}fn.connect()}return O(Hn)}function F(M){let X=l.get(M)?.room;return X||null}function K(){c.reset(),o.set(()=>{});for(let{room:M}of l.values())ld(M.getStatus())||M.reconnect()}let se=e.resolveUsers,z=new Wt(async M=>{let X=M.flat(),ue=await se?.({userIds:X});return Qi(!se,"Set the resolveUsers option in createClient to specify user info."),ue??X.map(()=>{})},{delay:Zu}),P=cr(z);function C(M){P.invalidate(M)}let R=e.resolveRoomsInfo,y=new Wt(async M=>{let X=M.flat(),ue=await R?.({roomIds:X});return Qi(!R,"Set the resolveRoomsInfo option in createClient to specify room info."),ue??X.map(()=>{})},{delay:Qu}),V=cr(y);function G(M){V.invalidate(M)}let oe=e.resolveGroupsInfo,re=new Wt(async M=>{let X=M.flat(),ue=await oe?.({groupIds:X});return Qi(!oe,"Set the resolveGroupsInfo option in createClient to specify group info."),ue??X.map(()=>{})},{delay:eh}),Q=cr(re);function me(M){Q.invalidate(M)}let Ne=new Map;function U(){Ne.clear()}let A=[],q=new Et("synchronized"),Y=ne();function te(){let M=q.get();return M==="synchronizing"?M:"synchronized"}function Ae(){q.set(A.some(M=>M.get()==="synchronizing")?"synchronizing":A.some(M=>M.get()==="has-local-changes")?"has-local-changes":"synchronized")}function De(){let M=new Et("synchronized");A.push(M);let X=M.subscribe(()=>Ae());function ue(ct){M.set(ct)}function Me(){X();let ct=A.findIndex(Je=>Je===M);if(ct>-1){let[Je]=A.splice(ct,1);Je.get()!=="synchronized"&&Ae()}}return{setSyncStatus:ue,destroy:Me}}{let M=ue=>{e.preventUnsavedChanges&&q.get()!=="synchronized"&&ue.preventDefault()};(typeof window<"u"?window:void 0)?.addEventListener("beforeunload",M)}async function qe(M){let X=await h.getNotificationSettings(M);return Oo(X)}async function Vt(M){let X=await h.updateNotificationSettings(M);return Oo(X)}let Ue=Object.defineProperty({enterRoom:_,getRoom:F,logout:K,getInboxNotifications:h.getInboxNotifications,getInboxNotificationsSince:h.getInboxNotificationsSince,getUnreadInboxNotificationsCount:h.getUnreadInboxNotificationsCount,markAllInboxNotificationsAsRead:h.markAllInboxNotificationsAsRead,markInboxNotificationAsRead:h.markInboxNotificationAsRead,deleteAllInboxNotifications:h.deleteAllInboxNotifications,deleteInboxNotification:h.deleteInboxNotification,getNotificationSettings:qe,updateNotificationSettings:Vt,resolvers:{invalidateUsers:C,invalidateRoomsInfo:G,invalidateGroupsInfo:me,invalidateMentionSuggestions:U},getSyncStatus:te,events:{error:Y,syncStatus:q},[Ct]:{currentUserId:o,mentionSuggestionsCache:Ne,ai:m,resolveMentionSuggestions:e.resolveMentionSuggestions,usersStore:P,roomsInfoStore:V,groupsInfoStore:Q,getRoomIds(){return Array.from(l.keys())},httpClient:h,as:()=>Ue,createSyncSource:De,emitError:(M,X)=>{let ue=bi.from(M,X);Y.notify(ue)||wt(ue.message)}}},Ct,{enumerable:!1});return Ue}function ks(n,e,t,r,i){if(typeof e!="number"||e<t||r!==void 0&&e>r)throw new Error(r!==void 0?`${n} should be between ${i??t} and ${r}.`:`${n} should be at least ${i??t}.`);return e}function Lo(n){if(n!==void 0)return ks("backgroundKeepAliveTimeout",n,Ju)}function rh(n){return ks("throttle",n,Ku,ju)}function ih(n){return ks("lostConnectionTimeout",n,Wu,Yu,Gu)}var El,wl,Xo,ln,Sl,ci,Cl,xl,ro,bt,wn,gi,sr,xn,Do,dt,Mo,bs,_t,Po,Et,Ol,Rl,Gt,zt,ut,ur,hr,Nr,rs,Mn,Dn,An,No,Mr,j,ht,Mt,or,It,Tn,Uo,Dl,Nl,ea,Ul,xe,wt,$l,ra,vi,Vl,Bl,Kl,pt,Ur,$r,Fr,kn,xt,os,oa,as,$o,Wt,ze,ql,Jl,Wl,Vr,Fo,Qe,Xl,ho,po,fo,mo,Zl,Hr,Br,Ze,_r,zr,Vo,nd,Yt,Ho,sd,od,He,rt,ft,Ot,_n,Se,Xt,zn,In,pr,ye,ca,la,da,cs,ls,tr,Bo,ad,W,ha,li,dd,ud,hd,pd,fd,Ut,md,di,Ge,Kr,Ko,ma,Ct,wo,bd,Ed,wd,Sd,Rt,On,fr,Rn,Zt,jr,$e,je,Ir,ga,va,ya,jo,Cd,Ye,it,mt,mr,gt,Lt,qo,kd,_d,Qt,en,gr,Ei,ba,Jo,zd,Dr,$d,Bd,B,he,Le,un,Aa,Ci,lr,Wd,ui,Yi,Qd,To,st,tn,nn,vt,qr,rn,Wo,xi,Ln,vr,hn,x,Pe,sn,I,nt,Jt,Or,Ta,ka,rr,_a,za,Ia,Oa,Ra,La,Da,We,fi,mi,Pn,pn,le,on,Nn,Fn,Xi,Z,we,_e,Ke,wi,Pa,$t,Na,Ua,fs,Ft,Ba,Ka,ja,qa,ko,ms,yu,bu,gs,zo,Io,qt,zu,ot,yt,Dt,Xe,Go,es,Ee,Be,an,Pt,Ga,Lr,Yo,Du,bi,ts,Ku,ju,qu,Ju,Wu,Gu,Yu,Xu,Zu,Qu,eh,sh,Xh,oh,Zh,_s=vn(()=>{"use strict";El=Object.defineProperty,wl=(n,e)=>{for(var t in e)El(n,t,{get:e[t],enumerable:!0})},Xo="@liveblocks/core",ln="3.19.1",Sl="esm",ci=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Cl="https://liveblocks.io/docs/errors/cross-linked",xl="https://liveblocks.io/docs/errors/dupes",ro=" ";bt=process.env.NODE_ENV==="production"?(n=>n):Object.freeze;wn=Symbol("kSinks"),gi=Symbol("kTrigger"),sr=null,xn=null;bs=(Mo=class{constructor(n){ke(this,"equals");T(this,dt);ke(this,Do);this.equals=n??Object.is,b(this,dt,ne()),this[wn]=new Set,this.get=this.get.bind(this),this.subscribe=this.subscribe.bind(this),this.subscribeOnce=this.subscribeOnce.bind(this)}dispose(){a(this,dt).dispose(),b(this,dt,"(disposed)"),this.equals="(disposed)"}get hasWatchers(){if(a(this,dt).count()>0)return!0;for(let n of this[wn])if(n.hasWatchers)return!0;return!1}[(Do=wn,gi)](){a(this,dt).notify();for(let n of this[wn])ys(n)}subscribe(n){return a(this,dt).count()===0&&this.get(),a(this,dt).subscribe(n)}subscribeOnce(n){let e=this.subscribe(()=>(e(),n()));return e}waitUntil(){throw new Error("waitUntil not supported on Signals")}markSinksDirty(){for(let n of this[wn])n.markDirty()}addSink(n){this[wn].add(n)}removeSink(n){this[wn].delete(n)}asReadonly(){return this}},dt=new WeakMap,Mo),Et=(Po=class extends bs{constructor(e,t){super(t);T(this,_t);b(this,_t,bt(e))}dispose(){super.dispose(),b(this,_t,"(disposed)")}get(){return xn?.add(this),a(this,_t)}set(e){dn(()=>{typeof e=="function"&&(e=e(a(this,_t))),this.equals(a(this,_t),e)||(b(this,_t,bt(e)),this.markSinksDirty(),ys(this))})}},_t=new WeakMap,Po),Ol=class extends Et{constructor(n){super(bt(Si(n)))}set(){throw new Error("Don't call .set() directly, use .patch()")}patch(n){super.set(e=>Qo(e,n))}},Rl=Symbol(),Dn=(Mn=class extends bs{constructor(t,r,i){super(i);T(this,Nr);T(this,Gt);T(this,zt);T(this,ut);T(this,ur);T(this,hr);b(this,zt,!0),b(this,Gt,Rl),b(this,ur,t),b(this,ut,new Set),b(this,hr,r)}static from(...t){let r=t.pop();if(typeof r!="function"&&St("Invalid .from() call, last argument expected to be a function"),typeof t[t.length-1]=="function"){let i=r,s=t.pop();return new Mn(t,s,i)}else{let i=r;return new Mn(t,i)}}dispose(){for(let t of a(this,ut))t.removeSink(this);b(this,Gt,"(disposed)"),b(this,ut,"(disposed)"),b(this,ur,"(disposed)"),b(this,hr,"(disposed)")}get isDirty(){return a(this,zt)}markDirty(){a(this,zt)||(b(this,zt,!0),this.markSinksDirty())}get(){return a(this,zt)&&S(this,Nr,rs).call(this),xn?.add(this),a(this,Gt)}[gi](){if(!this.hasWatchers)return;S(this,Nr,rs).call(this)&&super[gi]()}},Gt=new WeakMap,zt=new WeakMap,ut=new WeakMap,ur=new WeakMap,hr=new WeakMap,Nr=new WeakSet,rs=function(){let t=xn,r;xn=new Set;try{r=a(this,hr).call(this,...a(this,ur).map(i=>i.get()))}finally{let i=a(this,ut);b(this,ut,new Set);for(let s of xn)a(this,ut).add(s),i.delete(s);for(let s of i)s.removeSink(this);for(let s of a(this,ut))s.addSink(this);xn=t}return b(this,zt,!1),this.equals(a(this,Gt),r)?!1:(b(this,Gt,r),!0)},Mn),Mr=(No=class extends bs{constructor(e){super();T(this,An);b(this,An,e)}dispose(){super.dispose(),b(this,An,"(disposed)")}get(){return xn?.add(this),a(this,An)}mutate(e){dn(()=>{let t=e?e(a(this,An)):!0;t!==null&&typeof t=="object"&&"then"in t&&St("MutableSignal.mutate() does not support async callbacks"),t!==!1&&(this.markSinksDirty(),ys(this))})}},An=new WeakMap,No);or=(Mt=class{constructor(e,t){T(this,j);T(this,ht);b(this,ht,t),b(this,j,e)}static with(e){return Mt.fromAlreadySorted([],e)}static from(e,t){let r=new Mt([],t);for(let i of e)r.add(i);return r}static fromAlreadySorted(e,t){return new Mt(e,t)}clone(){return new Mt(a(this,j).slice(),a(this,ht))}add(e){let t=Ll(a(this,j),e,a(this,ht));return a(this,j).splice(t,0,e),t}clear(){let e=a(this,j).length>0;return a(this,j).length=0,e}removeBy(e,t=Number.POSITIVE_INFINITY){let r=0;for(let i=0;i<a(this,j).length;i++)if(e(a(this,j)[i])){if(a(this,j).splice(i,1),r++,r>=t)break;i--}return r>0}remove(e){let t=a(this,j).indexOf(e);return t>=0?(a(this,j).splice(t,1),!0):!1}removeAt(e){if(e<0||e>=a(this,j).length)return;let[t]=a(this,j).splice(e,1);return t}reposition(e){let t=a(this,j).indexOf(e);if(t<0)throw new Error("Cannot reposition item that is not in the list");let r=a(this,j)[t-1],i=a(this,j)[t+1],s=r===void 0||a(this,ht).call(this,r,e),o=i===void 0||a(this,ht).call(this,e,i);if(s&&o)return t;let c=t;for(;c>0&&a(this,ht).call(this,e,a(this,j)[c-1]);)a(this,j)[c]=a(this,j)[c-1],c--;if(c<t)return a(this,j)[c]=e,c;for(;c<a(this,j).length-1&&!a(this,ht).call(this,e,a(this,j)[c+1]);)a(this,j)[c]=a(this,j)[c+1],c++;return c!==t&&(a(this,j)[c]=e),c}at(e){return a(this,j)[e]}get length(){return a(this,j).length}*filter(e){for(let t of a(this,j))e(t)&&(yield t)}*findAllRight(e){for(let t=a(this,j).length-1;t>=0;t--){let r=a(this,j)[t];e(r,t)&&(yield r)}}[Symbol.iterator](){return a(this,j)[Symbol.iterator]()}*iterReversed(){for(let e=a(this,j).length-1;e>=0;e--)yield a(this,j)[e]}find(e,t){let r=this.findIndex(e,t);return r>-1?a(this,j).at(r):void 0}findIndex(e,t=0){for(let r=Math.max(0,t);r<a(this,j).length;r++)if(e(a(this,j)[r],r))return r;return-1}findRight(e,t){let r=this.findIndexRight(e,t);return r>-1?a(this,j).at(r):void 0}findIndexRight(e,t=a(this,j).length-1){for(let r=Math.min(t,a(this,j).length-1);r>=0;r--)if(e(a(this,j)[r],r))return r;return-1}get rawArray(){return a(this,j)}},j=new WeakMap,ht=new WeakMap,Mt),Dl=(Uo=class{constructor(){T(this,It);T(this,Tn);ke(this,"signal");b(this,It,new Map),b(this,Tn,or.from([],(n,e)=>{let t=e.lastMessageAt??e.createdAt,r=n.lastMessageAt??n.createdAt;return t<r?!0:t===r?e.id<n.id:!1})),this.signal=new Mr(this)}getEvenIfDeleted(n){return this.signal.get(),a(this,It).get(n)}markDeleted(n){let e=a(this,It).get(n);e===void 0||e.deletedAt!==void 0||this.upsert({...e,deletedAt:new Date().toISOString()})}upsert(n){this.signal.mutate(()=>{let e=a(this,It).get(n.id);if(e!==void 0){if(e.deletedAt!==void 0)return!1;a(this,Tn).remove(e),a(this,It).delete(e.id)}return n.deletedAt===void 0&&a(this,Tn).add(n),a(this,It).set(n.id,n),!0})}findMany(n){return Array.from(a(this,Tn).filter(e=>{if(n.metadata===void 0)return!0;for(let[t,r]of Object.entries(n.metadata))if(r===null){if(t in e.metadata)return!1}else if(typeof r=="string"){if(e.metadata[t]!==r)return!1}else{let i=e.metadata[t];if(!Array.isArray(i)||!r.every(s=>i.includes(s)))return!1}return!0}))}},It=new WeakMap,Tn=new WeakMap,Uo);Nl={};wl(Nl,{error:()=>wt,errorWithTitle:()=>ra,warn:()=>xe,warnWithTitle:()=>$l});ea="background:#0e0d12;border-radius:9999px;color:#fff;padding:3px 7px;font-family:sans-serif;font-weight:600;",Ul="font-weight:600";xe=ta("warn"),wt=ta("error");$l=na("warn"),ra=na("error");vi=class ia extends Error{constructor(t,r,i){super(t);ke(this,"response");ke(this,"details");this.name="HttpError",this.response=r,this.details=i}static async fromResponse(t){let r;try{r=await t.text()}catch{}let i=r?Nt(r):void 0,s;Ce(i)&&(s=i);let o="";o||(o=typeof s?.message=="string"?s.message:""),o||(o=typeof s?.error=="string"?s.error:""),i===void 0&&(o||(o=r||"")),o||(o=t.statusText);let c;try{c=new URL(t.url).pathname}catch{}o+=c!==void 0?` (got status ${t.status} from ${c})`:` (got status ${t.status})`;let u=s;return new ia(o,t,u)}get status(){return this.response.status}},Vl=n=>n instanceof vi&&n.status>=400&&n.status<500;Bl=50,Kl=class{constructor(n){ke(this,"input");ke(this,"resolve");ke(this,"reject");ke(this,"promise");this.input=n;let{promise:e,resolve:t,reject:r}=ar();this.promise=e,this.resolve=t,this.reject=r}},Wt=($o=class{constructor(n,e){T(this,xt);T(this,pt,[]);T(this,Ur);T(this,$r);T(this,Fr);T(this,kn);ke(this,"error",!1);b(this,Ur,n),b(this,$r,e.size??Bl),b(this,Fr,e.delay)}get(n){let e=a(this,pt).find(r=>ss(r.input)===ss(n));if(e)return e.promise;let t=new Kl(n);return a(this,pt).push(t),S(this,xt,oa).call(this),t.promise}clear(){b(this,pt,[]),this.error=!1,S(this,xt,os).call(this)}},pt=new WeakMap,Ur=new WeakMap,$r=new WeakMap,Fr=new WeakMap,kn=new WeakMap,xt=new WeakSet,os=function(){a(this,kn)!==void 0&&(clearTimeout(a(this,kn)),b(this,kn,void 0))},oa=function(){a(this,pt).length===a(this,$r)?S(this,xt,as).call(this):a(this,pt).length===1&&(S(this,xt,os).call(this),b(this,kn,setTimeout(()=>{S(this,xt,as).call(this)},a(this,Fr))))},as=async function(){if(a(this,pt).length===0)return;let n=a(this,pt).splice(0),e=n.map(t=>t.input);try{let t=await a(this,Ur).call(this,e);this.error=!1,n.forEach((r,i)=>{let s=t?.[i];Array.isArray(t)?n.length!==t.length?r.reject(new Error(`Callback must return an array of the same length as the number of provided items. Expected ${n.length}, but got ${t.length}.`)):s instanceof Error?r.reject(s):r.resolve(s):r.reject(new Error("Callback must return an array."))})}catch(t){this.error=!0,n.forEach(r=>{r.reject(t)})}},$o);ze=(n=21)=>crypto.getRandomValues(new Uint8Array(n)).reduce((e,t)=>e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t<63?"_":"-",""),ql="th",Jl="cm",Wl="at";Qe=(Fo=class extends Map{constructor(e,t){super(t);T(this,Vr);b(this,Vr,e)}getOrCreate(e,t){if(super.has(e))return super.get(e);{let i=(t??a(this,Vr)??St("DefaultMap used without a factory function"))(e);return this.set(e,i),i}}},Vr=new WeakMap,Fo),Xl=/^[a-zA-Z_][a-zA-Z0-9_]*$/;ho=n=>{let e=[];return n.forEach(([t,r])=>{e.push({key:t,operator:":",value:r})}),e},po=n=>{let e=[];return n.forEach(([t,r])=>{"startsWith"in r&&typeof r.startsWith=="string"&&e.push({key:t,operator:"^",value:r.startsWith}),"lt"in r&&typeof r.lt=="number"&&e.push({key:t,operator:"<",value:r.lt}),"gt"in r&&typeof r.gt=="number"&&e.push({key:t,operator:">",value:r.gt}),"gte"in r&&typeof r.gte=="number"&&e.push({key:t,operator:">=",value:r.gte}),"lte"in r&&typeof r.lte=="number"&&e.push({key:t,operator:"<=",value:r.lte})}),e},fo=n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null,mo=(n,e)=>e?`${n}[${aa(e)}]`:n,Zl=n=>!n||n.toString().trim()==="";nd=(Vo=class{constructor(n,e){T(this,Ze);T(this,Hr);T(this,Br);b(this,Hr,n),b(this,Br,e)}async rawGet(n,e,t,r){return await S(this,Ze,_r).call(this,n,e,r,t)}async rawPost(n,e,t){return await S(this,Ze,_r).call(this,n,e,{method:"POST",body:Un(t)})}async rawDelete(n,e){return await S(this,Ze,_r).call(this,n,e,{method:"DELETE"})}async get(n,e,t,r){return await S(this,Ze,zr).call(this,n,e,r,t)}async post(n,e,t,r,i){return await S(this,Ze,zr).call(this,n,e,{...r,method:"POST",body:Un(t)},i)}async delete(n,e){return await S(this,Ze,zr).call(this,n,e,{method:"DELETE"})}async putBlob(n,e,t,r,i){return await S(this,Ze,zr).call(this,n,e,{...i,method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:t},r)}},Hr=new WeakMap,Br=new WeakMap,Ze=new WeakSet,_r=async function(n,e,t,r){n.startsWith("/v2/c/")||St("This client can only be used to make /v2/c/* requests");let i=ed(a(this,Hr),n,r),s=await a(this,Br).call(this,i,{...t,headers:{"Content-Type":"application/json; charset=utf-8",...t?.headers,Authorization:`Bearer ${ws(e)}`,"X-LB-Client":ln||"dev"}}),o=s.headers.get("X-LB-Warn");if(o){let c=t?.method?.toUpperCase()??"GET",u=`${o} (${c} ${n})`;s.ok?xe(u):wt(u)}return s},zr=async function(n,e,t,r){let i=await S(this,Ze,_r).call(this,n,e,t,r);if(!i.ok)throw await vi.fromResponse(i);let s;try{s=await i.json()}catch{s={}}return s},Vo);sd=(Ho=class{constructor(n){T(this,Yt);b(this,Yt,n)}get current(){return a(this,Yt)}allowPatching(n){let e=this,t=!0,r={...a(this,Yt),patch(i){if(t){b(e,Yt,Object.assign({},a(e,Yt),i));for(let s of Object.entries(i)){let[o,c]=s;o!=="patch"&&(this[o]=c)}}else throw new Error("Can no longer patch stale context")}};n(r),t=!1}},Yt=new WeakMap,Ho),od=1,ad=(Bo=class{constructor(n){T(this,ye);ke(this,"id");T(this,He);T(this,rt);T(this,ft);T(this,Ot);T(this,_n);T(this,Se);ke(this,"events");T(this,Xt);T(this,zn);T(this,In);T(this,pr);this.id=od++,b(this,He,0),b(this,Ot,null),b(this,ft,new Set),b(this,In,new Map),b(this,Xt,[]),b(this,zn,[]),b(this,pr,new Set),b(this,_n,new Map),b(this,rt,new sd(n)),b(this,Se,{didReceiveEvent:ne(),willTransition:ne(),didIgnoreEvent:ne(),willExitState:ne(),didEnterState:ne(),didExitState:ne()}),this.events={didReceiveEvent:a(this,Se).didReceiveEvent.observable,willTransition:a(this,Se).willTransition.observable,didIgnoreEvent:a(this,Se).didIgnoreEvent.observable,willExitState:a(this,Se).willExitState.observable,didEnterState:a(this,Se).didEnterState.observable,didExitState:a(this,Se).didExitState.observable}}get currentState(){if(a(this,Ot)===null)throw a(this,He)===0?new Error("Not started yet"):new Error("Already stopped");return a(this,Ot)}start(){if(a(this,He)!==0)throw new Error("State machine has already started");return b(this,He,1),b(this,Ot,a(this,ye,ca)),S(this,ye,ls).call(this,null),this}stop(){if(a(this,He)!==1)throw new Error("Cannot stop a state machine that hasn't started yet");S(this,ye,cs).call(this,null),b(this,He,2),b(this,Ot,null)}get context(){return a(this,rt).current}addState(n){if(a(this,He)!==0)throw new Error("Already started");return a(this,ft).add(n),this}onEnter(n,e){if(a(this,He)!==0)throw new Error("Already started");if(a(this,In).has(n))throw new Error(`enter/exit function for ${n} already exists`);return a(this,In).set(n,e),this}onEnterAsync(n,e,t,r,i){return this.onEnter(n,()=>{let s=new AbortController,o=s.signal,c=i?setTimeout(()=>{let h=new Error("Timed out");S(this,ye,tr).call(this,{type:"ASYNC_ERROR",reason:h},r)},i):void 0,u=!1;return e(a(this,rt).current,o).then(h=>{o.aborted||(u=!0,S(this,ye,tr).call(this,{type:"ASYNC_OK",data:h},t))},h=>{o.aborted||(u=!0,S(this,ye,tr).call(this,{type:"ASYNC_ERROR",reason:h},r))}),()=>{clearTimeout(c),u||s.abort()}})}addTransitions(n,e){if(a(this,He)!==0)throw new Error("Already started");for(let t of S(this,ye,la).call(this,n)){let r=a(this,_n).get(t);r===void 0&&(r=new Map,a(this,_n).set(t,r));for(let[i,s]of Object.entries(e)){if(r.has(i))throw new Error(`Trying to set transition "${i}" on "${t}" (via "${n}"), but a transition already exists there.`);let o=s;if(a(this,pr).add(i),o!==void 0){let c=typeof o=="function"?o:()=>o;r.set(i,c)}}}return this}addTimedTransition(n,e,t){return this.onEnter(n,()=>{let r=typeof e=="function"?e(a(this,rt).current):e,i=setTimeout(()=>{S(this,ye,tr).call(this,{type:"TIMER"},t)},r);return()=>{clearTimeout(i)}})}send(n){if(!a(this,pr).has(n.type))throw new Error(`Invalid event ${JSON.stringify(n.type)}`);if(a(this,He)===2)return;let e=S(this,ye,da).call(this,n.type);if(e!==void 0)return S(this,ye,tr).call(this,n,e);a(this,Se).didIgnoreEvent.notify(n)}},He=new WeakMap,rt=new WeakMap,ft=new WeakMap,Ot=new WeakMap,_n=new WeakMap,Se=new WeakMap,Xt=new WeakMap,zn=new WeakMap,In=new WeakMap,pr=new WeakMap,ye=new WeakSet,ca=function(){let n=a(this,ft).values()[Symbol.iterator]().next();if(n.done)throw new Error("No states defined yet");return n.value},la=function(n){let e=[];if(n==="*")for(let t of a(this,ft))e.push(t);else if(n.endsWith(".*")){let t=n.slice(0,-1);for(let r of a(this,ft))r.startsWith(t)&&e.push(r)}else{let t=n;a(this,ft).has(t)&&e.push(t)}if(e.length===0)throw new Error(`No states match ${JSON.stringify(n)}`);return e},da=function(n){return a(this,_n).get(this.currentState)?.get(n)},cs=function(n){a(this,Se).willExitState.notify(this.currentState);let e=performance.now(),t=this.currentState.split(".");a(this,rt).allowPatching(r=>{n=n??a(this,Xt).length;for(let i=0;i<n;i++){a(this,Xt).pop()?.(r);let s=a(this,zn).pop();if(s!==void 0&&a(this,Se).didExitState.count()>0){let o=a(this,zn).length;if(o===0)continue;let c=o===t.length?this.currentState:`${t.slice(0,o).join(".")}.*`;a(this,Se).didExitState.notify({state:c,durationMs:e-s})}}})},ls=function(n){let e=id(this.currentState,n??this.currentState.split(".").length+1),t=performance.now();a(this,rt).allowPatching(r=>{for(let i of e){let o=a(this,In).get(i)?.(r);typeof o=="function"?a(this,Xt).push(o):a(this,Xt).push(null),a(this,zn).push(t)}}),a(this,Se).didEnterState.notify(this.currentState)},tr=function(n,e){a(this,Se).didReceiveEvent.notify(n);let t=this.currentState,i=(typeof e=="function"?e:()=>e)(n,a(this,rt).current),s,o;if(i===null){a(this,Se).didIgnoreEvent.notify(n);return}if(typeof i=="string"?s=i:(s=i.target,o=Array.isArray(i.effect)?i.effect:[i.effect]),!a(this,ft).has(s))throw new Error(`Invalid next state name: ${JSON.stringify(s)}`);a(this,Se).willTransition.notify({from:t,to:s});let[c,u]=rd(this.currentState,s);if(c>0&&S(this,ye,cs).call(this,c),b(this,Ot,s),o!==void 0){let h=o;a(this,rt).allowPatching(l=>{for(let m of h)typeof m=="function"?m(l,n):l.patch(m)})}u>0&&S(this,ye,ls).call(this,u)},Bo),W=Object.freeze({UPDATE_PRESENCE:100,USER_JOINED:101,USER_LEFT:102,BROADCASTED_EVENT:103,ROOM_STATE:104,STORAGE_STATE_V7:200,STORAGE_CHUNK:210,STORAGE_STREAM_END:211,UPDATE_STORAGE:201,UPDATE_YDOC:300,THREAD_CREATED:400,THREAD_DELETED:407,THREAD_METADATA_UPDATED:401,THREAD_UPDATED:408,COMMENT_CREATED:402,COMMENT_EDITED:403,COMMENT_DELETED:404,COMMENT_REACTION_ADDED:405,COMMENT_REACTION_REMOVED:406,COMMENT_METADATA_UPDATED:409,FEEDS_LIST:500,FEEDS_ADDED:501,FEEDS_UPDATED:502,FEED_DELETED:503,FEED_MESSAGES_LIST:504,FEED_MESSAGES_ADDED:505,FEED_MESSAGES_UPDATED:506,FEED_MESSAGES_DELETED:507,FEED_REQUEST_FAILED:508,REJECT_STORAGE_OP:299});ha=[250,500,1e3,2e3,4e3,8e3,1e4],li=ha[0]-1,dd=[2e3,3e4,6e4,3e5],ud=3e4,hd=2e3,pd=1e4,fd=2e4,Ut=class extends Error{constructor(n){super(n)}};md=nr(1,"Connection to WebSocket closed permanently. Won't retry.");di=n=>e=>e.patch(n);ma=(Ko=class{constructor(n,e=!1,t=!0){T(this,Ge);T(this,Kr);ke(this,"events");let{machine:r,events:i,cleanups:s}=yd(n,{waitForActorId:t,enableDebugLogging:e});b(this,Ge,r),this.events=i,b(this,Kr,s)}getStatus(){try{return ua(a(this,Ge))}catch{return"initial"}}get authValue(){return a(this,Ge).context.authValue}connect(){a(this,Ge).send({type:"CONNECT"})}reconnect(){a(this,Ge).send({type:"RECONNECT"})}disconnect(){a(this,Ge).send({type:"DISCONNECT"})}destroy(){a(this,Ge).stop();let n;for(;n=a(this,Kr).pop();)n()}send(n){let e=a(this,Ge).context?.socket;e===null?xe("Cannot send: not connected yet",n):e.readyState!==1?xe("Cannot send: WebSocket no longer open",n):e.send(n)}_privateSendMachineEvent(n){a(this,Ge).send(n)}},Ge=new WeakMap,Kr=new WeakMap,Ko),Ct=Symbol(),wo=Object.freeze({}),bd=Array.from(new Set("null")),Ed=Array.from(new Set("true")),wd=Array.from(new Set("false")),Sd=Array.from(new Set("nulltruefalse"));Cd=(jo=class{constructor(n=""){T(this,je);T(this,Rt,"");T(this,On);T(this,fr,0);T(this,Rn,!1);T(this,Zt,-1);T(this,jr,-1);T(this,$e,[]);this.append(n)}get source(){return a(this,Rt)}get json(){return a(this,On)===void 0&&b(this,On,S(this,je,ya).call(this)),a(this,On)}append(n){n&&(a(this,Rt)===""&&(n=n.trimStart()),b(this,Rt,a(this,Rt)+n),b(this,On,void 0))}},Rt=new WeakMap,On=new WeakMap,fr=new WeakMap,Rn=new WeakMap,Zt=new WeakMap,jr=new WeakMap,$e=new WeakMap,je=new WeakSet,Ir=function(){return a(this,Zt)>=0},ga=function(n){if(a(this,je,Ir))return"";let e=n.charAt(n.length-1);if(e==="")return"";if(e==="-")return"0";if(!Sd.includes(e))return"";if(bd.includes(e)){if(n.endsWith("nul"))return"l";if(n.endsWith("nu"))return"ll";if(n.endsWith("n"))return"ull"}if(Ed.includes(e)){if(n.endsWith("tru"))return"e";if(n.endsWith("tr"))return"ue";if(n.endsWith("t"))return"rue"}if(wd.includes(e)){if(n.endsWith("fals"))return"e";if(n.endsWith("fal"))return"se";if(n.endsWith("fa"))return"lse";if(n.endsWith("f"))return"alse"}return""},va=function(){let n=a(this,Rt).slice(a(this,fr));for(let e=0;e<n.length;e++){let t=n[e],r=a(this,fr)+e;a(this,je,Ir)?a(this,Rn)?b(this,Rn,!1):t==="\\"?b(this,Rn,!0):t==='"'&&(b(this,jr,a(this,Zt)),b(this,Zt,-1)):t==='"'?b(this,Zt,r):t==="{"?a(this,$e).push("}"):t==="["?a(this,$e).push("]"):t==="}"&&a(this,$e).length>0&&a(this,$e)[a(this,$e).length-1]==="}"?a(this,$e).pop():t==="]"&&a(this,$e).length>0&&a(this,$e)[a(this,$e).length-1]==="]"&&a(this,$e).pop()}b(this,fr,a(this,Rt).length)},ya=function(){S(this,je,va).call(this);let n=a(this,Rt);if(n.charAt(0)!=="{")return wo;if(n.endsWith("}")){let t=Nt(n);if(t)return t}a(this,je,Ir)&&(a(this,Rn)&&(n=n.slice(0,-1)),n+='"'),n=n.trimEnd(),n=Wi(n,",."),n=n+S(this,je,ga).call(this,n);let e=a(this,$e).reduceRight((t,r)=>t+r,"");{let t=Nt(n+e);if(t)return t}return a(this,je,Ir)?n=n.slice(0,a(this,Zt)):(n=Wi(n,":"),n.endsWith('"')&&(n=n.slice(0,a(this,jr)))),n=Wi(n,","),n+=e,Nt(n)??wo},jo);kd=(qo=class{constructor(n,e,t){T(this,Ye);T(this,it);T(this,mt);T(this,mr);T(this,gt);T(this,Lt);b(this,mr,n),b(this,gt,e),b(this,Lt,t),b(this,Ye,new Map),b(this,it,new Qe(()=>new Set)),b(this,mt,or.with(t))}get(n){return a(this,Ye).get(n)}getOrThrow(n){return this.get(n)??St(`Item with id ${n} not found`)}get sorted(){return a(this,mt)}getParentId(n){let e=this.getOrThrow(n);return a(this,gt).call(this,e)}getParent(n){let e=this.getParentId(n);return e?this.getOrThrow(e):null}getChildren(n){let e=a(this,it).get(n);return e?Array.from(e).map(t=>a(this,Ye).get(t)):[]}*walkUp(n,e){let r=n;do{let i=this.getOrThrow(r);(!e||e(i))&&(yield i),r=a(this,gt).call(this,i)}while(r!==null)}*walkLeft(n,e){let t=this.getOrThrow(n),r=or.from(this.getSiblings(n),a(this,Lt));for(let i of r.iterReversed())a(this,Lt).call(this,t,i)||(!e||e(i))&&(yield i)}*walkRight(n,e){let t=this.getOrThrow(n),r=or.from(this.getSiblings(n),a(this,Lt));for(let i of r)a(this,Lt).call(this,i,t)||(!e||e(i))&&(yield i)}*walkDown(n,e){let t=or.from(this.getChildren(n),a(this,Lt)).rawArray;for(let r=t.length-1;r>=0;r--){let i=t[r];yield*this.walkDown(a(this,mr).call(this,i),e),(!e||e(i))&&(yield i)}}getSiblings(n){let e=this.getOrThrow(n),t=this.getParentId(n);return this.getChildren(t).filter(r=>r!==e)}[Symbol.iterator](){return a(this,mt)[Symbol.iterator]()}upsert(n){let e=a(this,mr).call(this,n),t=a(this,Ye).get(e);if(t){if(a(this,gt).call(this,t)!==a(this,gt).call(this,n))throw new Error("Cannot upsert parent ID changes that change the tree structure. Remove the entry first, and recreate it");a(this,mt).remove(t)}a(this,Ye).set(e,n),a(this,mt).add(n);let r=a(this,gt).call(this,n);a(this,it).getOrCreate(r).add(e)}remove(n){let e=a(this,Ye).get(n);if(!e)return!1;if(a(this,it).get(n))throw new Error(`Cannot remove item '${n}' while it still has children. Remove children first.`);let r=a(this,gt).call(this,e),i=a(this,it).get(r);return i&&(i.delete(n),i.size===0&&a(this,it).delete(r)),a(this,mt).remove(e),a(this,it).delete(n),a(this,Ye).delete(n),!0}clear(){return a(this,Ye).size===0?!1:(a(this,it).clear(),a(this,Ye).clear(),a(this,mt).clear(),!0)}},Ye=new WeakMap,it=new WeakMap,mt=new WeakMap,mr=new WeakMap,gt=new WeakMap,Lt=new WeakMap,qo),_d=4e3,zd=(Jo=class{constructor(){T(this,Ei);T(this,Qt);T(this,en);T(this,gr);b(this,Qt,new Set),b(this,en,new Qe(()=>new Map)),b(this,gr,void 0)}registerLayer(n){let e=n;return a(this,Qt).has(e)&&St(`Layer '${e}' already exists, provide a unique layer id`),a(this,Qt).add(e),e}deregisterLayer(n){a(this,Qt).delete(n);let e=!1;for(let[t,r]of a(this,en))r.delete(n)&&(e=!0),r.size===0&&a(this,en).delete(t);e&&this.invalidate()}get(){return a(this,gr)??b(this,gr,S(this,Ei,ba).call(this))}invalidate(){b(this,gr,void 0)}updateKnowledge(n,e,t){a(this,Qt).has(n)||St(`Unknown layer key: ${n}`),a(this,en).getOrCreate(e).set(n,t),this.invalidate()}},Qt=new WeakMap,en=new WeakMap,gr=new WeakMap,Ei=new WeakSet,ba=function(){return Array.from(a(this,en).values()).flatMap(n=>Array.from(n.values()).slice(-1).filter(Fl))},Jo);Dr=Symbol("*");$d=[400,401,403,404,405,410,412,414,422,431,451];Bd="https://api.liveblocks.io",B=Object.freeze({INIT:0,SET_PARENT_KEY:1,CREATE_LIST:2,UPDATE_OBJECT:3,CREATE_OBJECT:4,DELETE_CRDT:5,DELETE_OBJECT_KEY:6,CREATE_MAP:7,CREATE_REGISTER:8});he=Object.freeze({OBJECT:0,LIST:1,MAP:2,REGISTER:3});Le=32,un=126,Aa=un-Le+1,Ci=Ss(0),lr=Ss(1),Wd=Ci+Ss(-1);ui=2,Yi=3;Qd=Le+1;To=Object.freeze({type:"NoParent"});xi=(Wo=class{constructor(){T(this,st);T(this,tn);T(this,nn,To);T(this,vt);T(this,qr);T(this,rn)}_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 Re(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 Re(this.parent,"Unknown state")}}get _pool(){return a(this,st)}get roomId(){return a(this,st)?a(this,st).roomId:null}get _id(){return a(this,tn)}get parent(){return a(this,nn)}get _parentKey(){switch(this.parent.type){case"HasParent":return this.parent.key;case"NoParent":return null;case"Orphaned":return this.parent.oldKey;default:return Re(this.parent,"Unknown state")}}_apply(n,e){return n.type===B.DELETE_CRDT?this.parent.type==="HasParent"?this.parent.node._detachChild(this):{modified:!1}:{modified:!1}}_setParentLink(n,e){switch(this.parent.type){case"HasParent":if(this.parent.node!==n)throw new Error("Cannot set parent: node already has a parent");b(this,nn,Ao(n,e));return;case"Orphaned":case"NoParent":{b(this,nn,Ao(n,e));return}default:return Re(this.parent,"Unknown state")}}_attach(n,e){if(a(this,tn)||a(this,st))throw new Error("Cannot attach node: already attached");e.addNode(n,this),b(this,tn,n),b(this,st,e)}_detach(){switch(a(this,st)&&a(this,tn)&&a(this,st).deleteNode(a(this,tn)),this.parent.type){case"HasParent":{b(this,nn,ru(this.parent.key,this.parent.pos));break}case"NoParent":{b(this,nn,To);break}case"Orphaned":break;default:Re(this.parent,"Unknown state")}b(this,st,void 0)}_toOpsWithOpId(n,e,t){return this._toOps(n,e).map(r=>({opId:t.generateOpId(),...r}))}invalidate(){(a(this,vt)!==void 0||a(this,rn)!==void 0)&&(b(this,vt,void 0),b(this,rn,void 0),this.parent.type==="HasParent"&&this.parent.node.invalidate())}toTreeNode(n){return(a(this,rn)===void 0||a(this,qr)!==n)&&(b(this,qr,n),b(this,rn,this._toTreeNode(n))),a(this,rn)}hasCache(n){return a(this,vt)!==void 0&&a(this,vt)===n}toJSON(){return a(this,vt)===void 0&&b(this,vt,this._toJSON()),a(this,vt)}},st=new WeakMap,tn=new WeakMap,nn=new WeakMap,vt=new WeakMap,qr=new WeakMap,rn=new WeakMap,Wo),hn=(vr=class extends xi{constructor(t){super();T(this,Ln);b(this,Ln,t)}get data(){return a(this,Ln)}static _deserialize([t,r],i,s){let o=new vr(r.data);return o._attach(t,s),o}_toOps(t,r){if(this._id===void 0)throw new Error("Cannot serialize register if parentId or parentKey is undefined");return[{type:B.CREATE_REGISTER,id:this._id,parentId:t,parentKey:r,data:this.data}]}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveRegister if parent is missing");return{type:he.REGISTER,parentId:J(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key,data:this.data}}_attachChild(t){throw new Error("Method not implemented.")}_detachChild(t){throw new Error("Method not implemented.")}_apply(t,r){return super._apply(t,r)}_toTreeNode(t){return{type:"Json",id:this._id??ze(),key:t,payload:a(this,Ln)}}_toJSON(){return a(this,Ln)}clone(){return yr(this.data)}},Ln=new WeakMap,vr);pn=(Pn=class extends xi{constructor(t){super();T(this,I);T(this,x);T(this,Pe);T(this,sn);b(this,Pe,new WeakSet),b(this,sn,new Map);let r=[],i;for(let s of t){let o=kt(i),c=dr(s);c._setParentLink(this,o),r.push(c),i=o}b(this,x,or.fromAlreadySorted(r,iu))}static _deserialize([t,r],i,s){var u;let o=new Pn([]);o._attach(t,s);let c=i.get(t);if(c===void 0)return o;for(let h of c){let l=h[1],m=Va(h,i,s);m._setParentLink(o,l.parentKey),S(u=o,I,nt).call(u,m)}return o}_toOps(t,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=[],s={id:this._id,type:B.CREATE_LIST,parentId:t,parentKey:r};i.push(s);for(let o of a(this,x)){let c=o._getParentKeyOrThrow(),u=pi(o._toOps(this._id,c),void 0);for(let h of u)i.push(h)}return i}_indexOfPosition(t){return a(this,x).findIndex(r=>r._getParentKeyOrThrow()===t)}_attach(t,r){super._attach(t,r);for(let i of a(this,x))i._attach(r.generateId(),r)}_detach(){super._detach();for(let t of a(this,x))t._detach()}_attachChild(t,r){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let i;return t.intent==="set"?r===1?i=S(this,I,Ta).call(this,t):r===2?i=S(this,I,ka).call(this,t):i=S(this,I,Oa).call(this,t):r===1?i=S(this,I,_a).call(this,t):r===2?i=S(this,I,za).call(this,t):i=S(this,I,Ia).call(this,t),i.modified!==!1&&this.invalidate(),i}_detachChild(t){if(t){let r=J(t._parentKey),i=t._toOps(J(this._id),r),s=a(this,x).findIndex(c=>c===t);if(s===-1)return{modified:!1};let o=a(this,x).at(s);return a(this,x).remove(t),this.invalidate(),t._detach(),{modified:ie(this,[hi(s,o)]),reverse:i}}return{modified:!1}}_setChildKey(t,r,i){return i===1?S(this,I,Ra).call(this,t,r):i===2?S(this,I,La).call(this,t,r):S(this,I,Da).call(this,t,r)}_apply(t,r){return super._apply(t,r)}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveList if parent is missing");return{type:he.LIST,parentId:J(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get length(){return a(this,x).length}push(t){return this._pool?.assertStorageIsWritable(),this.insert(t,this.length)}insert(t,r){if(this._pool?.assertStorageIsWritable(),r<0||r>a(this,x).length)throw new Error(`Cannot insert list item at index "${r}". index should be between 0 and ${a(this,x).length}`);let i=a(this,x).at(r-1)?._parentPos,s=a(this,x).at(r)?._parentPos,o=kt(i,s),c=dr(t);if(c._setParentLink(this,o),S(this,I,nt).call(this,c),this._pool&&this._id){let u=this._pool.generateId();c._attach(u,this._pool),this._pool.dispatch(c._toOpsWithOpId(this._id,o,this._pool),[{type:B.DELETE_CRDT,id:u}],new Map([[this._id,ie(this,[tt(r,c)])]]))}}move(t,r){if(this._pool?.assertStorageIsWritable(),r<0)throw new Error("targetIndex cannot be less than 0");if(r>=a(this,x).length)throw new Error("targetIndex cannot be greater or equal than the list length");if(t<0)throw new Error("index cannot be less than 0");if(t>=a(this,x).length)throw new Error("index cannot be greater or equal than the list length");let i=null,s=null;t<r?(s=r===a(this,x).length-1?void 0:a(this,x).at(r+1)?._parentPos,i=a(this,x).at(r)._parentPos):(s=a(this,x).at(r)._parentPos,i=r===0?void 0:a(this,x).at(r-1)?._parentPos);let o=kt(i,s),c=a(this,x).at(t),u=c._getParentKeyOrThrow();if(S(this,I,Or).call(this,t,o),this._pool&&this._id){let h=new Map([[this._id,ie(this,[Cn(t,r,c)])]]);this._pool.dispatch([{type:B.SET_PARENT_KEY,id:J(c._id),opId:this._pool.generateOpId(),parentKey:o}],[{type:B.SET_PARENT_KEY,id:J(c._id),parentKey:u}],h)}}delete(t){if(this._pool?.assertStorageIsWritable(),t<0||t>=a(this,x).length)throw new Error(`Cannot delete list item at index "${t}". index should be between 0 and ${a(this,x).length-1}`);let r=a(this,x).at(t);if(r._detach(),a(this,x).remove(r),this.invalidate(),this._pool){let i=r._id;if(i){let s=new Map;s.set(J(this._id),ie(this,[hi(t,r)])),this._pool.dispatch([{id:i,opId:this._pool.generateOpId(),type:B.DELETE_CRDT}],r._toOps(J(this._id),r._getParentKeyOrThrow()),s)}}}clear(){if(this._pool?.assertStorageIsWritable(),this._pool){let t=[],r=[],i=[];for(let o of a(this,x)){o._detach();let c=o._id;c&&(t.push({type:B.DELETE_CRDT,id:c,opId:this._pool.generateOpId()}),r.push(...o._toOps(J(this._id),o._getParentKeyOrThrow())),i.push(hi(0,o)))}a(this,x).clear(),this.invalidate();let s=new Map;s.set(J(this._id),ie(this,i)),this._pool.dispatch(t,r,s)}else{for(let t of a(this,x))t._detach();a(this,x).clear(),this.invalidate()}}set(t,r){if(this._pool?.assertStorageIsWritable(),t<0||t>=a(this,x).length)throw new Error(`Cannot set list item at index "${t}". index should be between 0 and ${a(this,x).length-1}`);let i=a(this,x).at(t),s=i._getParentKeyOrThrow(),o=i._id;i._detach();let c=dr(r);if(c._setParentLink(this,s),a(this,x).remove(i),a(this,x).add(c),this.invalidate(),this._pool&&this._id){let u=this._pool.generateId();c._attach(u,this._pool);let h=new Map;h.set(this._id,ie(this,[er(t,c)]));let l=pi(c._toOpsWithOpId(this._id,s,this._pool),o);a(this,sn).set(s,J(l[0].opId));let m=pi(i._toOps(this._id,s),u);this._pool.dispatch(l,m,h)}}every(t){return a(this,x).rawArray.every((r,i)=>t(S(this,I,We).call(this,r),i))}filter(t){let r=[];return a(this,x).rawArray.forEach((i,s)=>{let o=S(this,I,We).call(this,i);t(o,s)&&r.push(o)}),r}find(t){for(let[r,i]of a(this,x).rawArray.entries()){let s=S(this,I,We).call(this,i);if(t(s,r))return s}}findIndex(t){return a(this,x).rawArray.findIndex((r,i)=>t(S(this,I,We).call(this,r),i))}forEach(t){a(this,x).rawArray.forEach((r,i)=>t(S(this,I,We).call(this,r),i))}get(t){let r=a(this,x).at(t);return r!==void 0?S(this,I,We).call(this,r):void 0}indexOf(t,r){return a(this,x).rawArray.findIndex((i,s)=>s>=(r??0)&&S(this,I,We).call(this,i)===t)}lastIndexOf(t,r){let i=a(this,x).rawArray;for(let s=r??i.length-1;s>=0;s--)if(S(this,I,We).call(this,i[s])===t)return s;return-1}map(t){return a(this,x).rawArray.map((r,i)=>t(S(this,I,We).call(this,r),i))}some(t){return a(this,x).rawArray.some((r,i)=>t(S(this,I,We).call(this,r),i))}*[Symbol.iterator](){for(let t of a(this,x))yield S(this,I,We).call(this,t)}_toTreeNode(t){let r=[],i=0;for(let s of a(this,x))r.push(s.toTreeNode(i.toString())),i++;return{type:"LiveList",id:this._id??ze(),key:t,payload:r}}toJSON(){return super.toJSON()}_toJSON(){let t=Array.from(a(this,x),r=>r.toJSON());return bt(t)}clone(){return new Pn(Array.from(a(this,x),t=>t.clone()))}},x=new WeakMap,Pe=new WeakMap,sn=new WeakMap,I=new WeakSet,nt=function(t){let r=a(this,x).add(t);return this.invalidate(),r},Jt=function(t,r){t._setParentLink(this,r),a(this,x).reposition(t),this.invalidate()},Or=function(t,r){let i=J(a(this,x).at(t));S(this,I,Jt).call(this,i,r)},Ta=function(t){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:r,parentKey:i}=t,s=Rr(t);s._attach(r,this._pool),s._setParentLink(this,i);let o=t.deletedId,c=this._indexOfPosition(i);if(c!==-1){let u=J(a(this,x).removeAt(c));if(u._id===o)return u._detach(),a(this,x).add(s),{modified:ie(this,[er(c,s)]),reverse:[]};{a(this,Pe).add(u),a(this,x).remove(u),a(this,x).add(s);let h=[er(c,s)],l=S(this,I,rr).call(this,t.deletedId);return l&&h.push(l),{modified:ie(this,h),reverse:[]}}}else{let u=[],h=S(this,I,rr).call(this,t.deletedId);return h&&u.push(h),S(this,I,nt).call(this,s),u.push(tt(this._indexOfPosition(i),s)),{reverse:[],modified:ie(this,u)}}},ka=function(t){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let r=[],i=S(this,I,rr).call(this,t.deletedId);i&&r.push(i);let s=a(this,sn).get(t.parentKey);if(s!==void 0){if(s!==t.opId)return r.length===0?{modified:!1}:{modified:ie(this,r),reverse:[]};a(this,sn).delete(t.parentKey)}let o=this._indexOfPosition(t.parentKey),c=a(this,x).find(u=>u._id===t.id);if(c!==void 0){if(c._parentKey===t.parentKey)return{modified:r.length>0?ie(this,r):!1,reverse:[]};if(o!==-1){let l=J(a(this,x).removeAt(o));a(this,Pe).add(l),r.push(hi(o,l))}let u=a(this,x).findIndex(l=>l===c);S(this,I,Jt).call(this,c,t.parentKey);let h=a(this,x).findIndex(l=>l===c);return h!==u&&r.push(Cn(u,h,c)),{modified:r.length>0?ie(this,r):!1,reverse:[]}}else{let u=this._pool.getNode(t.id);if(u&&a(this,Pe).has(u)){u._setParentLink(this,t.parentKey),a(this,Pe).delete(u);let h=S(this,I,nt).call(this,u);return{modified:ie(this,[o===-1?tt(h,u):er(h,u),...r]),reverse:[]}}else{if(o!==-1){let m=J(a(this,x).removeAt(o));a(this,Pe).add(m)}let{newItem:h,newIndex:l}=S(this,I,fi).call(this,t,t.parentKey);return{modified:ie(this,[o===-1?tt(l,h):er(l,h),...r]),reverse:[]}}}},rr=function(t){if(t===void 0||this._pool===void 0)return null;let r=this._pool.getNode(t);if(r===void 0)return null;let i=this._detachChild(r);return i.modified===!1?null:i.modified.updates[0]},_a=function(t){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let r=Pr(t.parentKey),i=this._indexOfPosition(r);i!==-1&&S(this,I,mi).call(this,i,r);let{newItem:s,newIndex:o}=S(this,I,fi).call(this,t,r);return{modified:ie(this,[tt(o,s)]),reverse:[]}},za=function(t){let r=a(this,x).find(o=>o._id===t.id),i=Pr(t.parentKey),s=this._indexOfPosition(i);if(r){if(r._parentKey===i)return{modified:!1};{let o=a(this,x).findIndex(u=>u===r);s!==-1&&S(this,I,mi).call(this,s,i),S(this,I,Jt).call(this,r,i);let c=this._indexOfPosition(i);return c===o?{modified:!1}:{modified:ie(this,[Cn(o,c,r)]),reverse:[]}}}else{let o=J(this._pool).getNode(t.id);if(o&&a(this,Pe).has(o)){o._setParentLink(this,i),a(this,Pe).delete(o),S(this,I,nt).call(this,o);let c=this._indexOfPosition(i);return{modified:ie(this,[tt(c,o)]),reverse:[]}}else{s!==-1&&S(this,I,mi).call(this,s,i);let{newItem:c,newIndex:u}=S(this,I,fi).call(this,t,i);return{modified:ie(this,[tt(u,c)]),reverse:[]}}}},Ia=function(t){let{id:r,parentKey:i}=t,s=Rr(t);if(this._pool?.getNode(r)!==void 0)return{modified:!1};s._attach(r,J(this._pool)),s._setParentLink(this,i);let o=this._indexOfPosition(i),c=i;if(o!==-1){let h=a(this,x).at(o)?._parentPos,l=a(this,x).at(o+1)?._parentPos;c=kt(h,l),s._setParentLink(this,c)}S(this,I,nt).call(this,s);let u=this._indexOfPosition(c);return{modified:ie(this,[tt(u,s)]),reverse:[{type:B.DELETE_CRDT,id:r}]}},Oa=function(t){let{id:r,parentKey:i}=t,s=Rr(t);if(this._pool?.getNode(r)!==void 0)return{modified:!1};a(this,sn).set(i,J(t.opId));let o=this._indexOfPosition(i);s._attach(r,J(this._pool)),s._setParentLink(this,i);let c=i;if(o!==-1){let u=a(this,x).at(o);u._detach(),a(this,x).remove(u),a(this,x).add(s);let h=pi(u._toOps(J(this._id),i),t.id),l=[er(o,s)],m=S(this,I,rr).call(this,t.deletedId);return m&&l.push(m),{modified:ie(this,l),reverse:h}}else{S(this,I,nt).call(this,s),S(this,I,rr).call(this,t.deletedId);let u=this._indexOfPosition(c);return{reverse:[{type:B.DELETE_CRDT,id:r}],modified:ie(this,[tt(u,s)])}}},Ra=function(t,r){if(a(this,Pe).has(r)){a(this,Pe).delete(r),r._setParentLink(this,t);let o=S(this,I,nt).call(this,r);return{modified:ie(this,[tt(o,r)]),reverse:[]}}let i=r._parentKey;if(t===i)return{modified:!1};let s=this._indexOfPosition(t);if(s===-1){let o=a(this,x).findIndex(u=>u===r);S(this,I,Jt).call(this,r,t);let c=a(this,x).findIndex(u=>u===r);return c===o?{modified:!1}:{modified:ie(this,[Cn(o,c,r)]),reverse:[]}}else{S(this,I,Or).call(this,s,kt(t,a(this,x).at(s+1)?._parentPos));let o=a(this,x).findIndex(u=>u===r);S(this,I,Jt).call(this,r,t);let c=a(this,x).findIndex(u=>u===r);return c===o?{modified:!1}:{modified:ie(this,[Cn(o,c,r)]),reverse:[]}}},La=function(t,r){let i=J(r._parentKey);if(a(this,Pe).has(r)){let s=this._indexOfPosition(t);if(a(this,Pe).delete(r),s!==-1){let c=a(this,x).at(s);c._setParentLink(this,kt(t,a(this,x).at(s+1)?._parentPos)),a(this,x).reposition(c)}r._setParentLink(this,t);let o=S(this,I,nt).call(this,r);return{modified:ie(this,[tt(o,r)]),reverse:[]}}else{if(t===i)return{modified:!1};let s=a(this,x).findIndex(u=>u===r),o=this._indexOfPosition(t);o!==-1&&S(this,I,Or).call(this,o,kt(t,a(this,x).at(o+1)?._parentPos)),S(this,I,Jt).call(this,r,t);let c=a(this,x).findIndex(u=>u===r);return s===c?{modified:!1}:{modified:ie(this,[Cn(s,c,r)]),reverse:[]}}},Da=function(t,r){let i=J(r._parentKey),s=a(this,x).findIndex(h=>h===r),o=this._indexOfPosition(t),c=t;o!==-1&&(c=kt(t,a(this,x).at(o+1)?._parentPos)),S(this,I,Jt).call(this,r,c);let u=a(this,x).findIndex(h=>h===r);return s===u?{modified:!1}:{modified:ie(this,[Cn(s,u,r)]),reverse:[{type:B.SET_PARENT_KEY,id:J(r._id),parentKey:i}]}},We=function(t){return ir(t)},fi=function(t,r){let i=Rr(t);i._attach(t.id,J(this._pool)),i._setParentLink(this,r),S(this,I,nt).call(this,i);let s=this._indexOfPosition(r);return{newItem:i,newIndex:s}},mi=function(t,r){let i=kt(r,a(this,x).length>t+1?a(this,x).at(t+1)?._parentPos:void 0);S(this,I,Or).call(this,t,i)},Pn);Fn=(Nn=class extends xi{constructor(t){super();T(this,le);T(this,on);if(b(this,on,new Map),t){let r=[];for(let[i,s]of t){let o=dr(s);o._setParentLink(this,i),r.push([i,o])}b(this,le,new Map(r))}else b(this,le,new Map)}_toOps(t,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=[],s={id:this._id,type:B.CREATE_MAP,parentId:t,parentKey:r};i.push(s);for(let[o,c]of a(this,le))for(let u of c._toOps(this._id,o))i.push(u);return i}static _deserialize([t,r],i,s){let o=new Nn;o._attach(t,s);let c=i.get(t);if(c===void 0)return o;for(let u of c){let h=u[1],l=Va(u,i,s);l._setParentLink(o,h.parentKey),a(o,le).set(h.parentKey,l),o.invalidate()}return o}_attach(t,r){super._attach(t,r);for(let[i,s]of a(this,le))ve(s)&&s._attach(r.generateId(),r)}_attachChild(t,r){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:i,parentKey:s,opId:o}=t,c=s,u=Rr(t);if(this._pool.getNode(i)!==void 0)return{modified:!1};if(r===2){let m=a(this,on).get(c);if(m===o)return a(this,on).delete(c),{modified:!1};if(m!==void 0)return{modified:!1}}else r===1&&a(this,on).delete(c);let h=a(this,le).get(c),l;if(h){let m=J(this._id);l=h._toOps(m,c),h._detach()}else l=[{type:B.DELETE_CRDT,id:i}];return u._setParentLink(this,c),u._attach(i,this._pool),a(this,le).set(c,u),this.invalidate(),{modified:{node:this,type:"LiveMap",updates:{[c]:{type:"update"}}},reverse:l}}_detach(){super._detach();for(let t of a(this,le).values())t._detach()}_detachChild(t){let r=J(this._id),i=J(t._parentKey),s=t._toOps(r,i);for(let[c,u]of a(this,le))u===t&&(a(this,le).delete(c),this.invalidate());return t._detach(),{modified:{node:this,type:"LiveMap",updates:{[i]:{type:"delete",deletedItem:ir(t)}}},reverse:s}}_serialize(){if(this.parent.type!=="HasParent")throw new Error("Cannot serialize LiveMap if parent is missing");return{type:he.MAP,parentId:J(this.parent.node._id,"Parent node expected to have ID"),parentKey:this.parent.key}}get(t){let r=a(this,le).get(t);if(r!==void 0)return ir(r)}set(t,r){this._pool?.assertStorageIsWritable();let i=a(this,le).get(t);i&&i._detach();let s=dr(r);if(s._setParentLink(this,t),a(this,le).set(t,s),this.invalidate(),this._pool&&this._id){let o=this._pool.generateId();s._attach(o,this._pool);let c=new Map;c.set(this._id,{node:this,type:"LiveMap",updates:{[t]:{type:"update"}}});let u=s._toOpsWithOpId(this._id,t,this._pool);a(this,on).set(t,J(u[0].opId)),this._pool.dispatch(u,i?i._toOps(this._id,t):[{type:B.DELETE_CRDT,id:o}],c)}}get size(){return a(this,le).size}has(t){return a(this,le).has(t)}delete(t){this._pool?.assertStorageIsWritable();let r=a(this,le).get(t);if(r===void 0)return!1;if(r._detach(),a(this,le).delete(t),this.invalidate(),this._pool&&r._id){let i=J(this._id),s=new Map;s.set(i,{node:this,type:"LiveMap",updates:{[t]:{type:"delete",deletedItem:ir(r)}}}),this._pool.dispatch([{type:B.DELETE_CRDT,id:r._id,opId:this._pool.generateOpId()}],r._toOps(i,t),s)}return!0}entries(){let t=a(this,le).entries();return{[Symbol.iterator](){return this},next(){let r=t.next();if(r.done)return{done:!0,value:void 0};let s=r.value[0],o=ir(r.value[1]);return{value:[s,o]}}}}[Symbol.iterator](){return this.entries()}keys(){return a(this,le).keys()}values(){let t=a(this,le).values();return{[Symbol.iterator](){return this},next(){let r=t.next();return r.done?{done:!0,value:void 0}:{value:ir(r.value)}}}}forEach(t){for(let r of this)t(r[1],r[0],this)}_toTreeNode(t){return{type:"LiveMap",id:this._id??ze(),key:t,payload:Array.from(a(this,le).entries()).map(([r,i])=>i.toTreeNode(r))}}toJSON(){return super.toJSON()}_toJSON(){let t={};for(let[r,i]of a(this,le))t[r]=i.toJSON();return bt(t)}clone(){return new Nn(Array.from(a(this,le)).map(([t,r])=>[t,r.clone()]))}},le=new WeakMap,on=new WeakMap,Nn);Xi=128*1024,Ft=(Ke=class extends xi{constructor(t={}){super();T(this,$t);T(this,Z);T(this,we,new Map);T(this,_e);b(this,_e,new Map);let r=Si(t);for(let i of Object.keys(r)){let s=r[i];ve(s)&&s._setParentLink(this,i)}b(this,Z,new Map(Object.entries(r)))}static _fromItems(t,r){var o;let[i,s]=S(o=Ke,wi,Pa).call(o,t);return Ke._deserialize(["root",i],s,r)}_toOps(t,r){if(this._id===void 0)throw new Error("Cannot serialize item is not attached");let i=[],s={type:B.CREATE_OBJECT,id:this._id,parentId:t,parentKey:r,data:{}};i.push(s);for(let[o,c]of a(this,Z))if(ve(c))for(let u of c._toOps(this._id,o))i.push(u);else s.data[o]=c;return i}static _deserialize([t,r],i,s){let o=new Ke(r.data);return o._attach(t,s),this._deserializeChildren(o,i,s)}static _deserializeChildren(t,r,i){let s=r.get(J(t._id));if(s===void 0)return t;for(let o of s){let c=au(o,r,i),u=o[1];cn(c)&&c._setParentLink(t,u.parentKey),a(t,Z).set(u.parentKey,c),t.invalidate()}return t}_attach(t,r){super._attach(t,r);for(let[i,s]of a(this,Z))ve(s)&&s._attach(r.generateId(),r)}_attachChild(t,r){if(this._pool===void 0)throw new Error("Can't attach child if managed pool is not present");let{id:i,opId:s,parentKey:o}=t,c=$a(t);if(this._pool.getNode(i)!==void 0)return a(this,_e).get(o)===s&&a(this,_e).delete(o),{modified:!1};if(r===0)a(this,_e).set(o,J(s));else if(a(this,_e).get(o)!==void 0)return a(this,_e).get(o)===s?(a(this,_e).delete(o),{modified:!1}):{modified:!1};let u=J(this._id),h=a(this,Z).get(o),l;return ve(h)?(l=h._toOps(u,o),h._detach()):h===void 0?l=[{type:B.DELETE_OBJECT_KEY,id:u,key:o}]:l=[{type:B.UPDATE_OBJECT,id:u,data:{[o]:h}}],a(this,we).delete(o),a(this,Z).set(o,c),this.invalidate(),cn(c)&&(c._setParentLink(this,o),c._attach(i,this._pool)),{reverse:l,modified:{node:this,type:"LiveObject",updates:{[o]:{type:"update"}}}}}_detachChild(t){if(t){let r=J(this._id),i=J(t._parentKey),s=t._toOps(r,i);for(let[c,u]of a(this,Z))u===t&&(a(this,Z).delete(c),this.invalidate());return t._detach(),{modified:{node:this,type:"LiveObject",updates:{[i]:{type:"delete"}}},reverse:s}}return{modified:!1}}_detach(){super._detach();for(let t of a(this,Z).values())ve(t)&&t._detach()}_apply(t,r){return t.type===B.UPDATE_OBJECT?S(this,$t,Na).call(this,t,r):t.type===B.DELETE_OBJECT_KEY?S(this,$t,Ua).call(this,t,r):super._apply(t,r)}_serialize(){let t={};for(let[r,i]of a(this,Z))ve(i)||(t[r]=i);return this.parent.type==="HasParent"&&this.parent.node._id?{type:he.OBJECT,parentId:this.parent.node._id,parentKey:this.parent.key,data:t}:{type:he.OBJECT,data:t}}keys(){let t=new Set(a(this,Z).keys());for(let r of a(this,we).keys())t.add(r);return t}set(t,r){this.update({[t]:r})}setLocal(t,r){this._pool?.assertStorageIsWritable();let i=S(this,$t,fs).call(this,t);if(a(this,we).set(t,r),this.invalidate(),this._pool!==void 0&&this._id!==void 0){let s=i?.[0]??[],o=i?.[1]??[],c=i?.[2]??new Map,u=c.get(this._id);c.set(this._id,{node:this,type:"LiveObject",updates:{...u?.updates,[t]:{type:"update"}}}),this._pool.dispatch(s,o,c)}}get(t){return a(this,we).has(t)?a(this,we).get(t):a(this,Z).get(t)}delete(t){let r=S(this,$t,fs).call(this,t);if(r){let[i,s,o]=r;this._pool?.dispatch(i,s,o)}}update(t){if(this._pool?.assertStorageIsWritable(),Ke.detectLargeObjects){let l={};for(let[O,_]of a(this,Z))ve(_)||(l[O]=_);for(let O of Object.keys(t)){let _=t[O];_!==void 0&&(ve(_)||(l[O]=_))}let m=JSON.stringify(l);if(m.length*4>Xi){let O=new TextEncoder().encode(m).length;if(O>Xi)throw new Error(`LiveObject size exceeded limit: ${O} bytes > ${Xi} bytes. See https://liveblocks.io/docs/platform/limits#Liveblocks-Storage-limits`)}}if(this._pool===void 0||this._id===void 0){for(let l in t){let m=t[l];if(m===void 0)continue;let k=a(this,Z).get(l);ve(k)&&k._detach(),ve(m)&&m._setParentLink(this,l),a(this,we).delete(l),a(this,Z).set(l,m),this.invalidate()}return}let r=[],i=[],s=this._pool.generateOpId(),o={},c={id:this._id,type:B.UPDATE_OBJECT,data:{}},u={};for(let l in t){let m=t[l];if(m===void 0)continue;let k=a(this,Z).get(l);if(k!==m){if(ve(k)){for(let O of k._toOps(this._id,l))i.push(O);k._detach()}else k===void 0?i.push({type:B.DELETE_OBJECT_KEY,id:this._id,key:l}):c.data[l]=k;if(ve(m)){m._setParentLink(this,l),m._attach(this._pool.generateId(),this._pool);let O=m._toOpsWithOpId(this._id,l,this._pool),_=O.find(F=>F.parentId===this._id);_&&a(this,_e).set(l,J(_.opId));for(let F of O)r.push(F)}else o[l]=m,a(this,_e).set(l,s);a(this,we).delete(l),a(this,Z).set(l,m),this.invalidate(),u[l]={type:"update"}}}if(Object.keys(c.data).length!==0&&i.unshift(c),Object.keys(o).length!==0&&r.unshift({opId:s,id:this._id,type:B.UPDATE_OBJECT,data:o}),r.length===0&&i.length===0&&Object.keys(u).length===0)return;let h=new Map;h.set(this._id,{node:this,type:"LiveObject",updates:u}),this._pool.dispatch(r,i,h)}static from(t,r){if(!Ce(t))throw new Error("Expected a JSON object");let i=new Ke({});return i.reconcile(t,r),i}reconcile(t,r){if(!this.hasCache(t)){if(!Ce(t))throw new Error("Reconciling the document root expects a plain object value");ps(this,t,"full",r)}}reconcilePartially(t,r){if(!Ce(t))throw new Error("Reconciling the document root expects a plain object value");ps(this,t,"partial",r)}toTreeNode(t){return super.toTreeNode(t)}_toTreeNode(t){let r=this._id??ze();return{type:"LiveObject",id:r,key:t,payload:Array.from(a(this,Z).entries()).map(([i,s])=>ve(s)?s.toTreeNode(i):{type:"Json",id:`${r}:${i}`,key:i,payload:s})}}toJSON(){return super.toJSON()}_toJSON(){let t={};for(let[r,i]of a(this,Z))t[r]=cn(i)?i.toJSON():i;for(let[r,i]of a(this,we))t[r]=i;return bt(t)}clone(){let t=new Ke(Object.fromEntries(Array.from(a(this,Z)).map(([r,i])=>[r,cn(i)?i.clone():yr(i)])));for(let[r,i]of a(this,we))a(t,we).set(r,yr(i));return t}},Z=new WeakMap,we=new WeakMap,_e=new WeakMap,wi=new WeakSet,Pa=function(t){let r=new Map,i=null;for(let s of t)if(jd(s))i=s[1];else{let o=s[1],c=r.get(o.parentId);c!==void 0?c.push(s):r.set(o.parentId,[s])}if(i===null)throw new Error("Root can't be null");return[i,r]},$t=new WeakSet,Na=function(t,r){let i=!1,s=J(this._id),o=[],c={type:B.UPDATE_OBJECT,id:s,data:{}};for(let h in t.data){let l=a(this,Z).get(h);if(ve(l)){for(let m of l._toOps(s,h))o.push(m);l._detach()}else l!==void 0?c.data[h]=l:l===void 0&&o.push({type:B.DELETE_OBJECT_KEY,id:s,key:h})}let u={};for(let h in t.data){let l=t.data[h];if(l===void 0)continue;if(r)a(this,_e).set(h,J(t.opId));else if(a(this,_e).get(h)===void 0)i=!0;else if(a(this,_e).get(h)===t.opId){a(this,_e).delete(h);continue}else continue;let m=a(this,Z).get(h);ve(m)&&m._detach(),i=!0,u[h]={type:"update"},a(this,we).delete(h),a(this,Z).set(h,l),this.invalidate()}return Object.keys(c.data).length!==0&&o.unshift(c),i?{modified:{node:this,type:"LiveObject",updates:u},reverse:o}:{modified:!1}},Ua=function(t,r){let i=t.key,s=a(this,Z).get(i);if(s===void 0)return{modified:!1};if(!r&&a(this,_e).get(i)!==void 0)return{modified:!1};let o=J(this._id),c=[];return ve(s)?(c=s._toOps(o,t.key),s._detach()):s!==void 0&&(c=[{type:B.UPDATE_OBJECT,id:o,data:{[i]:s}}]),a(this,we).delete(i),a(this,Z).delete(i),this.invalidate(),{modified:{node:this,type:"LiveObject",updates:{[t.key]:{type:"delete",deletedItem:s}}},reverse:c}},fs=function(t){this._pool?.assertStorageIsWritable();let r=t;if(a(this,we).has(r)&&!a(this,Z).has(r)){let u=a(this,we).get(r);if(a(this,we).delete(r),this.invalidate(),this._pool!==void 0&&this._id!==void 0){let h=new Map;return h.set(this._id,{node:this,type:"LiveObject",updates:{[r]:{type:"delete",deletedItem:u}}}),[[],[],h]}return null}a(this,we).delete(r);let i=a(this,Z).get(r);if(i===void 0)return null;if(this._pool===void 0||this._id===void 0)return ve(i)&&i._detach(),a(this,Z).delete(r),this.invalidate(),null;let s=[{type:B.DELETE_OBJECT_KEY,key:r,id:this._id,opId:this._pool.generateOpId()}],o;ve(i)?(i._detach(),o=i._toOps(this._id,r)):o=[{type:B.UPDATE_OBJECT,data:{[r]:i},id:this._id}],a(this,Z).delete(r),this.invalidate();let c=new Map;return c.set(this._id,{node:this,type:"LiveObject",updates:{[t]:{type:"delete",deletedItem:i}}}),[s,o,c]},T(Ke,wi),ke(Ke,"detectLargeObjects",!1),Ke);Ba=!1;Ka=ne();process.env.NODE_ENV!=="production"&&typeof window<"u"&&window.addEventListener("message",n=>{n.source===window&&n.data?.source==="liveblocks-devtools-panel"&&Ka.notify(n.data)});ja=Ka.observable,qa=ln||"dev",ko=!1;ms=new Map;yu=Date.now(),bu=0;gs=new Map;zo=new Set;Io=Symbol("notification-settings-plain");qt="12px",zu=(n="bottom-right")=>{if(typeof document>"u"||document.getElementById("liveblocks-badge"))return;let e=document.createElement("div");switch(e.id="liveblocks-badge",e.style.position="fixed",e.style.opacity="0",e.style.transition="opacity 300ms",e.style.zIndex="9999",n){case"top-right":e.style.top=qt,e.style.right=qt;break;case"bottom-right":e.style.bottom=qt,e.style.right=qt;break;case"bottom-left":e.style.bottom=qt,e.style.left=qt;break;case"top-left":e.style.top=qt,e.style.left=qt;break}e.onmouseenter=()=>{let _=document.getElementById("liveblocks-badge-hide-button");_&&(_.style.opacity="0.3")},e.onmouseleave=()=>{let _=document.getElementById("liveblocks-badge-hide-button");_&&(_.style.opacity="0")};let t=document.createElement("a");t.href="https://lblcks.io/badge",t.target="_blank",t.rel="noopener noreferrer",t.title="Liveblocks";let r=document.createElementNS("http://www.w3.org/2000/svg","svg");r.setAttribute("width","111"),r.setAttribute("height","38"),r.setAttribute("viewBox","0 0 111 38"),r.setAttribute("fill","none");let i=document.createElementNS("http://www.w3.org/2000/svg","rect");i.setAttribute("x","1"),i.setAttribute("y","1"),i.setAttribute("width","109"),i.setAttribute("height","36"),i.setAttribute("rx","8"),i.setAttribute("fill","white"),r.appendChild(i);let s=document.createElementNS("http://www.w3.org/2000/svg","rect");s.setAttribute("x","0.5"),s.setAttribute("y","0.5"),s.setAttribute("width","110"),s.setAttribute("height","37"),s.setAttribute("rx","8.5"),s.setAttribute("stroke","black"),s.setAttribute("stroke-opacity","0.1"),r.appendChild(s);let o=document.createElementNS("http://www.w3.org/2000/svg","path");o.setAttribute("d","M39.8256 18.0832H38L38.0005 28.9009H39.8256V18.0832ZM43.213 21.1757H41.3879V28.9009H43.213V21.1757ZM43.213 18H41.3879V19.9688H43.213V18ZM45.8916 21.1757H43.9302L46.6915 28.9009H48.7283L51.4896 21.1757H49.5581L48.4039 24.8348C48.3739 24.93 48.2657 25.3024 48.0795 25.9511L47.7099 27.1959C47.4914 26.406 47.2626 25.6189 47.0237 24.8348L45.8916 21.1757ZM58.9659 23.59C58.8147 23.0721 58.5934 22.6317 58.3014 22.2694C57.9743 21.8628 57.5598 21.5482 57.0571 21.3268C56.5589 21.1004 56.0058 20.9877 55.3973 20.9877C54.2407 20.9877 53.3152 21.3495 52.6212 22.0735C52.275 22.4476 52.0103 22.8896 51.844 23.3715C51.6731 23.8691 51.5876 24.4199 51.5876 25.0233C51.5876 26.3157 51.9322 27.3142 52.6217 28.0184C53.3203 28.7323 54.2509 29.0894 55.4125 29.0894C56.4083 29.0894 57.2151 28.8658 57.8342 28.4181C58.453 27.9704 58.8628 27.3068 59.0638 26.4266L57.2834 26.2908C57.198 26.7685 57.0016 27.1257 56.6948 27.3618C56.3879 27.5933 55.9555 27.7093 55.3973 27.7093C54.1201 27.7093 53.4663 26.9899 53.4363 25.5514H59.1844L59.1922 25.295C59.1922 24.6763 59.1165 24.108 58.9659 23.59ZM53.8434 23.0471C54.1654 22.5943 54.6834 22.3679 55.3973 22.3679C55.7443 22.3679 56.0363 22.4155 56.2725 22.5111C56.509 22.6067 56.7128 22.7601 56.8837 22.9713C57.0167 23.1352 57.1189 23.3218 57.1855 23.5221C57.2605 23.731 57.3062 23.9493 57.3213 24.1708H53.451C53.4964 23.7231 53.6271 23.3484 53.8434 23.0471ZM66.2836 21.4779C65.7656 21.1406 65.1673 20.9724 64.4885 20.9724H64.4875C63.995 20.9724 63.5449 21.0727 63.1374 21.2742C62.7364 21.4696 62.3931 21.7659 62.1412 22.1341V18.0832H60.316V28.9009H62.1416V27.8373C62.373 28.2195 62.7008 28.5342 63.0921 28.7499C63.4996 28.9763 63.9497 29.0894 64.4422 29.0894C65.1266 29.0894 65.7324 28.9259 66.2614 28.5992C66.7891 28.2726 67.1989 27.8045 67.4905 27.1959C67.7871 26.5823 67.9359 25.8634 67.9359 25.0386C67.9359 24.2337 67.7895 23.5248 67.4984 22.9113C67.2115 22.2926 66.8066 21.8148 66.2836 21.4779ZM65.5064 27.0828C65.2148 27.5254 64.7172 27.7463 64.0125 27.7463C63.3786 27.7463 62.9013 27.5175 62.5797 27.0601C62.2576 26.6026 62.0968 25.9336 62.0968 25.0534C62.0968 24.2032 62.24 23.5397 62.5265 23.0619C62.8185 22.579 63.3088 22.3378 63.9978 22.3378C64.7019 22.3378 65.2023 22.5592 65.499 23.0013C65.7961 23.4389 65.944 24.1181 65.944 25.0386C65.944 25.9585 65.7985 26.6401 65.5064 27.0828ZM70.901 18.0832H69.0754V28.9009H70.901V18.0832ZM73.8582 28.6066C74.452 28.9286 75.1558 29.0894 75.9708 29.0894C76.7554 29.0894 77.4444 28.9208 78.0377 28.5844C78.6268 28.2569 79.1068 27.7637 79.4183 27.1659C79.745 26.5523 79.9086 25.843 79.9086 25.0386C79.9086 24.2642 79.7478 23.5697 79.4257 22.9565C79.117 22.3516 78.6404 21.8487 78.0529 21.508C77.4592 21.161 76.7652 20.9872 75.9708 20.9872C75.171 20.9872 74.4719 21.161 73.8735 21.508C73.2876 21.8472 72.811 22.3471 72.5002 22.9486C72.1837 23.5572 72.0252 24.254 72.0252 25.0386C72.0252 25.8735 72.181 26.5948 72.4929 27.2033C72.7962 27.798 73.2722 28.2871 73.8582 28.6066ZM77.4869 27.0906C77.18 27.5231 76.6746 27.7393 75.9708 27.7393C75.493 27.7393 75.1082 27.6437 74.8166 27.4524C74.5246 27.2565 74.3134 26.9621 74.1826 26.5699C74.0518 26.1725 73.9867 25.6619 73.9867 25.0381C73.9867 24.1029 74.1401 23.419 74.4469 22.9866C74.7588 22.5541 75.2667 22.3378 75.9708 22.3378C76.6699 22.3378 77.1727 22.5541 77.4795 22.9866C77.7914 23.419 77.9471 24.1029 77.9471 25.0386C77.9471 25.9738 77.7937 26.6576 77.4869 27.0906ZM82.3982 28.6066C82.9869 28.9286 83.6883 29.0894 84.5033 29.0894C85.1369 29.0894 85.7029 28.9791 86.2005 28.7577C86.6989 28.5364 87.1031 28.2272 87.4152 27.8299C87.7279 27.4249 87.9329 26.9471 88.0109 26.4414L86.2534 26.2607C86.1328 26.7431 85.9316 27.1031 85.6497 27.3392C85.3683 27.5757 84.9857 27.694 84.5033 27.694C84.0103 27.694 83.6232 27.5933 83.3413 27.3918C83.0598 27.1858 82.8635 26.8919 82.7531 26.5093C82.6422 26.1221 82.5872 25.6318 82.5872 25.0386C82.5872 24.455 82.6422 23.9722 82.7531 23.59C82.8635 23.2028 83.0571 22.9062 83.3339 22.6997C83.6157 22.4884 84.0053 22.3831 84.5033 22.3831C85.0362 22.3831 85.4312 22.5314 85.6877 22.8281C85.949 23.1196 86.1354 23.5193 86.2456 24.0276L87.9735 23.718C87.8078 22.8932 87.4326 22.232 86.8491 21.7344C86.2708 21.2363 85.489 20.9877 84.5033 20.9877C83.6985 20.9877 83.0021 21.1587 82.4134 21.5006C81.8322 21.8351 81.3625 22.3337 81.0633 22.9339C80.7514 23.5424 80.5952 24.2439 80.5952 25.0386C80.5952 25.8781 80.7486 26.6026 81.0554 27.2112C81.3673 27.8197 81.8151 28.285 82.3982 28.6066ZM90.8104 26.0343L91.6627 25.2192L93.9257 28.9009H96.0308L92.8999 24.0498L95.9328 21.1757H93.5634L90.8104 23.9976V18.0832H88.9845V28.9009H90.8104V26.0343ZM97.6304 28.8103C98.1436 28.9965 98.7142 29.0894 99.3428 29.0894C100.303 29.0894 101.095 28.8981 101.719 28.5165C102.348 28.1339 102.663 27.5101 102.663 26.6451C102.663 26.0818 102.516 25.6392 102.225 25.3176C101.933 24.9905 101.586 24.7566 101.184 24.6157C100.786 24.4702 100.245 24.3219 99.562 24.1707C99.1642 24.0853 98.8502 24.0049 98.6188 23.9295C98.3873 23.8538 98.201 23.7558 98.0604 23.6352C97.925 23.5141 97.8567 23.3584 97.8567 23.1676C97.8567 22.8858 97.9824 22.6723 98.2338 22.5263C98.4853 22.3803 98.7973 22.3073 99.1694 22.3073C99.6619 22.3073 100.047 22.4255 100.324 22.6621C100.605 22.8987 100.756 23.2531 100.776 23.7258L102.466 23.4467C102.385 22.5817 102.046 21.9556 101.447 21.568C100.854 21.1812 100.095 20.9872 99.1694 20.9872C98.6258 20.9872 98.1236 21.0699 97.6607 21.2362C97.2029 21.397 96.8335 21.6511 96.5517 21.9986C96.27 22.3451 96.1294 22.7827 96.1294 23.3109C96.1294 23.7988 96.25 24.1934 96.4911 24.4951C96.7368 24.8001 97.0527 25.0408 97.4118 25.1965C97.7838 25.3578 98.2512 25.5112 98.8147 25.6567L99.2828 25.7699C99.5949 25.844 99.9044 25.9295 100.211 26.0264C100.421 26.092 100.595 26.1826 100.731 26.2981C100.867 26.4136 100.935 26.5647 100.935 26.7509C100.935 27.0776 100.799 27.3294 100.527 27.505C100.261 27.6815 99.8708 27.7693 99.3583 27.7693C98.8347 27.7693 98.4176 27.6385 98.1055 27.377C97.7941 27.1154 97.6355 26.7384 97.6304 26.2454L95.9109 26.4413C95.9302 27.0351 96.094 27.5304 96.4009 27.9278C96.7129 28.3252 97.1223 28.619 97.6304 28.8103Z"),o.setAttribute("fill","black"),r.appendChild(o);let c=document.createElementNS("http://www.w3.org/2000/svg","path");c.setAttribute("d","M37.6392 15V9.18182H39.7131C40.1657 9.18182 40.5407 9.2642 40.8381 9.42898C41.1354 9.59375 41.358 9.81913 41.5057 10.1051C41.6534 10.3892 41.7273 10.7093 41.7273 11.0653C41.7273 11.4233 41.6525 11.7453 41.5028 12.0312C41.3551 12.3153 41.1316 12.5407 40.8324 12.7074C40.535 12.8722 40.161 12.9545 39.7102 12.9545H38.2841V12.2102H39.6307C39.9167 12.2102 40.1487 12.161 40.3267 12.0625C40.5047 11.9621 40.6354 11.8258 40.7188 11.6534C40.8021 11.4811 40.8438 11.285 40.8438 11.0653C40.8438 10.8456 40.8021 10.6506 40.7188 10.4801C40.6354 10.3097 40.5038 10.1761 40.3239 10.0795C40.1458 9.98295 39.911 9.93466 39.6193 9.93466H38.517V15H37.6392ZM44.4716 15.0881C44.0625 15.0881 43.7055 14.9943 43.4006 14.8068C43.0956 14.6193 42.8589 14.357 42.6903 14.0199C42.5218 13.6828 42.4375 13.2888 42.4375 12.8381C42.4375 12.3854 42.5218 11.9896 42.6903 11.6506C42.8589 11.3116 43.0956 11.0483 43.4006 10.8608C43.7055 10.6733 44.0625 10.5795 44.4716 10.5795C44.8807 10.5795 45.2377 10.6733 45.5426 10.8608C45.8475 11.0483 46.0843 11.3116 46.2528 11.6506C46.4214 11.9896 46.5057 12.3854 46.5057 12.8381C46.5057 13.2888 46.4214 13.6828 46.2528 14.0199C46.0843 14.357 45.8475 14.6193 45.5426 14.8068C45.2377 14.9943 44.8807 15.0881 44.4716 15.0881ZM44.4744 14.375C44.7396 14.375 44.9593 14.3049 45.1335 14.1648C45.3078 14.0246 45.4366 13.8381 45.5199 13.6051C45.6051 13.3722 45.6477 13.1155 45.6477 12.8352C45.6477 12.5568 45.6051 12.3011 45.5199 12.0682C45.4366 11.8333 45.3078 11.6449 45.1335 11.5028C44.9593 11.3608 44.7396 11.2898 44.4744 11.2898C44.2074 11.2898 43.9858 11.3608 43.8097 11.5028C43.6354 11.6449 43.5057 11.8333 43.4205 12.0682C43.3371 12.3011 43.2955 12.5568 43.2955 12.8352C43.2955 13.1155 43.3371 13.3722 43.4205 13.6051C43.5057 13.8381 43.6354 14.0246 43.8097 14.1648C43.9858 14.3049 44.2074 14.375 44.4744 14.375ZM48.267 15L46.983 10.6364H47.8608L48.7159 13.8409H48.7585L49.6165 10.6364H50.4943L51.3466 13.8267H51.3892L52.2386 10.6364H53.1165L51.8352 15H50.9688L50.0824 11.8494H50.017L49.1307 15H48.267ZM55.6705 15.0881C55.2405 15.0881 54.8703 14.9962 54.5597 14.8125C54.2509 14.6269 54.0123 14.3665 53.8438 14.0312C53.6771 13.6941 53.5938 13.2992 53.5938 12.8466C53.5938 12.3996 53.6771 12.0057 53.8438 11.6648C54.0123 11.3239 54.2472 11.0578 54.5483 10.8665C54.8513 10.6752 55.2055 10.5795 55.6108 10.5795C55.857 10.5795 56.0956 10.6203 56.3267 10.7017C56.5578 10.7831 56.7652 10.911 56.9489 11.0852C57.1326 11.2595 57.2775 11.4858 57.3835 11.7642C57.4896 12.0407 57.5426 12.3769 57.5426 12.7727V13.0739H54.0739V12.4375H56.7102C56.7102 12.214 56.6648 12.0161 56.5739 11.8438C56.483 11.6695 56.3551 11.5322 56.1903 11.4318C56.0275 11.3314 55.8362 11.2812 55.6165 11.2812C55.3778 11.2812 55.1695 11.34 54.9915 11.4574C54.8153 11.5729 54.679 11.7244 54.5824 11.9119C54.4877 12.0975 54.4403 12.2992 54.4403 12.517V13.0142C54.4403 13.3059 54.4915 13.554 54.5938 13.7585C54.6979 13.9631 54.8428 14.1193 55.0284 14.2273C55.214 14.3333 55.4309 14.3864 55.679 14.3864C55.84 14.3864 55.9867 14.3636 56.1193 14.3182C56.2519 14.2708 56.3665 14.2008 56.4631 14.108C56.5597 14.0152 56.6335 13.9006 56.6847 13.7642L57.4886 13.9091C57.4242 14.1458 57.3087 14.3532 57.142 14.5312C56.9773 14.7074 56.7699 14.8447 56.5199 14.9432C56.2718 15.0398 55.9886 15.0881 55.6705 15.0881ZM58.4851 15V10.6364H59.3061V11.3295H59.3516C59.4311 11.0947 59.5713 10.91 59.772 10.7756C59.9747 10.6392 60.2038 10.571 60.4595 10.571C60.5125 10.571 60.575 10.5729 60.647 10.5767C60.7209 10.5805 60.7786 10.5852 60.8203 10.5909V11.4034C60.7862 11.3939 60.7256 11.3835 60.6385 11.3722C60.5514 11.3589 60.4643 11.3523 60.3771 11.3523C60.1764 11.3523 59.9974 11.3949 59.8402 11.4801C59.6849 11.5634 59.5618 11.6799 59.4709 11.8295C59.38 11.9773 59.3345 12.1458 59.3345 12.3352V15H58.4851ZM63.2798 15.0881C62.8499 15.0881 62.4796 14.9962 62.169 14.8125C61.8603 14.6269 61.6217 14.3665 61.4531 14.0312C61.2865 13.6941 61.2031 13.2992 61.2031 12.8466C61.2031 12.3996 61.2865 12.0057 61.4531 11.6648C61.6217 11.3239 61.8565 11.0578 62.1577 10.8665C62.4607 10.6752 62.8149 10.5795 63.2202 10.5795C63.4664 10.5795 63.705 10.6203 63.9361 10.7017C64.1671 10.7831 64.3745 10.911 64.5582 11.0852C64.742 11.2595 64.8868 11.4858 64.9929 11.7642C65.099 12.0407 65.152 12.3769 65.152 12.7727V13.0739H61.6832V12.4375H64.3196C64.3196 12.214 64.2741 12.0161 64.1832 11.8438C64.0923 11.6695 63.9645 11.5322 63.7997 11.4318C63.6368 11.3314 63.4455 11.2812 63.2259 11.2812C62.9872 11.2812 62.7789 11.34 62.6009 11.4574C62.4247 11.5729 62.2884 11.7244 62.1918 11.9119C62.0971 12.0975 62.0497 12.2992 62.0497 12.517V13.0142C62.0497 13.3059 62.1009 13.554 62.2031 13.7585C62.3073 13.9631 62.4522 14.1193 62.6378 14.2273C62.8234 14.3333 63.0402 14.3864 63.2884 14.3864C63.4493 14.3864 63.5961 14.3636 63.7287 14.3182C63.8613 14.2708 63.9759 14.2008 64.0724 14.108C64.169 14.0152 64.2429 13.9006 64.294 13.7642L65.098 13.9091C65.0336 14.1458 64.9181 14.3532 64.7514 14.5312C64.5866 14.7074 64.3793 14.8447 64.1293 14.9432C63.8812 15.0398 63.598 15.0881 63.2798 15.0881ZM67.728 15.0852C67.3757 15.0852 67.0613 14.9953 66.7848 14.8153C66.5102 14.6335 66.2943 14.375 66.1371 14.0398C65.9818 13.7027 65.9041 13.2983 65.9041 12.8267C65.9041 12.3551 65.9827 11.9517 66.1399 11.6165C66.299 11.2812 66.5168 11.0246 66.7933 10.8466C67.0698 10.6686 67.3833 10.5795 67.7337 10.5795C68.0045 10.5795 68.2223 10.625 68.3871 10.7159C68.5537 10.8049 68.6825 10.9091 68.7734 11.0284C68.8662 11.1477 68.9382 11.2528 68.9893 11.3438H69.0405V9.18182H69.8899V15H69.0604V14.321H68.9893C68.9382 14.4138 68.8643 14.5199 68.7678 14.6392C68.6731 14.7585 68.5424 14.8627 68.3757 14.9517C68.209 15.0407 67.9931 15.0852 67.728 15.0852ZM67.9155 14.3608C68.1598 14.3608 68.3662 14.2964 68.5348 14.1676C68.7053 14.0369 68.834 13.8561 68.9212 13.625C69.0102 13.3939 69.0547 13.125 69.0547 12.8182C69.0547 12.5152 69.0111 12.25 68.924 12.0227C68.8369 11.7955 68.709 11.6184 68.5405 11.4915C68.3719 11.3646 68.1636 11.3011 67.9155 11.3011C67.6598 11.3011 67.4467 11.3674 67.2763 11.5C67.1058 11.6326 66.977 11.8134 66.8899 12.0426C66.8047 12.2718 66.7621 12.5303 66.7621 12.8182C66.7621 13.1098 66.8056 13.3722 66.8928 13.6051C66.9799 13.8381 67.1087 14.0227 67.2791 14.1591C67.4515 14.2936 67.6636 14.3608 67.9155 14.3608ZM73.2876 15V9.18182H74.1371V11.3438H74.1882C74.2375 11.2528 74.3085 11.1477 74.4013 11.0284C74.4941 10.9091 74.6229 10.8049 74.7876 10.7159C74.9524 10.625 75.1702 10.5795 75.4411 10.5795C75.7933 10.5795 76.1077 10.6686 76.3842 10.8466C76.6607 11.0246 76.8776 11.2812 77.0348 11.6165C77.1939 11.9517 77.2734 12.3551 77.2734 12.8267C77.2734 13.2983 77.1948 13.7027 77.0376 14.0398C76.8804 14.375 76.6645 14.6335 76.3899 14.8153C76.1153 14.9953 75.8018 15.0852 75.4496 15.0852C75.1844 15.0852 74.9676 15.0407 74.799 14.9517C74.6323 14.8627 74.5017 14.7585 74.407 14.6392C74.3123 14.5199 74.2393 14.4138 74.1882 14.321H74.1172V15H73.2876ZM74.12 12.8182C74.12 13.125 74.1645 13.3939 74.2536 13.625C74.3426 13.8561 74.4714 14.0369 74.6399 14.1676C74.8085 14.2964 75.0149 14.3608 75.2592 14.3608C75.513 14.3608 75.7251 14.2936 75.8956 14.1591C76.0661 14.0227 76.1948 13.8381 76.282 13.6051C76.371 13.3722 76.4155 13.1098 76.4155 12.8182C76.4155 12.5303 76.3719 12.2718 76.2848 12.0426C76.1996 11.8134 76.0708 11.6326 75.8984 11.5C75.728 11.3674 75.5149 11.3011 75.2592 11.3011C75.013 11.3011 74.8047 11.3646 74.6342 11.4915C74.4657 11.6184 74.3378 11.7955 74.2507 12.0227C74.1636 12.25 74.12 12.5152 74.12 12.8182ZM78.6158 16.6364C78.4889 16.6364 78.3733 16.6259 78.2692 16.6051C78.165 16.5862 78.0874 16.5653 78.0362 16.5426L78.2408 15.8466C78.3961 15.8883 78.5343 15.9063 78.6555 15.9006C78.7768 15.8949 78.8838 15.8494 78.9766 15.7642C79.0713 15.679 79.1546 15.5398 79.2266 15.3466L79.3317 15.0568L77.7351 10.6364H78.6442L79.7493 14.0227H79.7947L80.8999 10.6364H81.8118L80.0135 15.5824C79.9302 15.8097 79.8241 16.0019 79.6953 16.1591C79.5665 16.3182 79.4131 16.4375 79.2351 16.517C79.0571 16.5966 78.8506 16.6364 78.6158 16.6364Z"),c.setAttribute("fill","black"),c.setAttribute("fill-opacity","0.5"),r.appendChild(c);let u=document.createElementNS("http://www.w3.org/2000/svg","rect");u.setAttribute("x","7"),u.setAttribute("y","7"),u.setAttribute("width","24"),u.setAttribute("height","24"),u.setAttribute("rx","3"),u.setAttribute("fill","black"),r.appendChild(u);let h=document.createElementNS("http://www.w3.org/2000/svg","path");h.setAttribute("fill-rule","evenodd"),h.setAttribute("clip-rule","evenodd"),h.setAttribute("d","M22.0455 15H12.2273L15.1364 17.9091V21.9091L22.0455 15Z"),h.setAttribute("fill","white"),r.appendChild(h);let l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("fill-rule","evenodd"),l.setAttribute("clip-rule","evenodd"),l.setAttribute("d","M16.9546 22.9999H26.7728L23.8637 20.0908V16.0908L16.9546 22.9999Z"),l.setAttribute("fill","white"),r.appendChild(l),t.appendChild(r),e.appendChild(t);let m=document.createElement("button");m.id="liveblocks-badge-hide-button",m.style.position="absolute",m.style.top="0",m.style.right="0",m.style.border="none",m.style.padding="0",m.style.margin="0",m.style.background="none",m.style.font="inherit",m.style.cursor="pointer",m.style.outline="none",m.style.setProperty("-webkit-appearance","none"),m.style.setProperty("-moz-appearance","none"),m.style.setProperty("appearance","none"),m.style.opacity="0",m.onclick=()=>{let _=document.getElementById("liveblocks-badge");_&&(_.style.display="none")},m.onmouseenter=()=>{m.style.opacity="0.5"},m.onmouseleave=()=>{m.style.opacity="0.3"};let k=document.createElementNS("http://www.w3.org/2000/svg","svg");k.setAttribute("width","18"),k.setAttribute("height","18"),k.setAttribute("viewBox","0 0 18 18"),k.setAttribute("fill","none");let O=document.createElementNS("http://www.w3.org/2000/svg","path");O.setAttribute("d","M6 6L9 9M12 12L9 9M9 9L12 6M9 9L6 12"),O.setAttribute("stroke","black"),k.appendChild(O),m.appendChild(k),e.appendChild(m),document.body.appendChild(e),requestAnimationFrame(()=>{requestAnimationFrame(()=>{e.style.opacity="1"})})},es=(Go=class{constructor(){T(this,ot);T(this,yt);T(this,Dt);T(this,Xe);b(this,ot,{}),b(this,yt,0),b(this,Dt,1),b(this,Xe,0)}get length(){return a(this,Xe)}*[Symbol.iterator](){let n=a(this,Xe),e=a(this,yt);for(let t=0;t<n;t++)yield a(this,ot)[e+t]}push(n){let e=Array.isArray(n)?n:[n];a(this,Dt)>Number.MAX_SAFE_INTEGER-e.length-1&&St("Deque full");for(let t of e)a(this,ot)[yn(this,Dt)._++-1]=t;b(this,Xe,a(this,Xe)+e.length)}pop(){if(a(this,Xe)<1)return;yn(this,Dt)._--;let n=a(this,ot)[a(this,Dt)-1];return delete a(this,ot)[a(this,Dt)-1],yn(this,Xe)._--,n}pushLeft(n){let e=Array.isArray(n)?n:[n];a(this,yt)<Number.MIN_SAFE_INTEGER+e.length&&St("Deque full");for(let t=e.length-1;t>=0;t--)a(this,ot)[--yn(this,yt)._]=e[t];b(this,Xe,a(this,Xe)+e.length)}popLeft(){if(a(this,Xe)<1)return;let n=a(this,ot)[a(this,yt)];return delete a(this,ot)[a(this,yt)],yn(this,yt)._++,yn(this,Xe)._--,n}},ot=new WeakMap,yt=new WeakMap,Dt=new WeakMap,Xe=new WeakMap,Go);Ee=Object.freeze({UPDATE_PRESENCE:100,BROADCAST_EVENT:103,FETCH_STORAGE:200,UPDATE_STORAGE:201,FETCH_YDOC:300,UPDATE_YDOC:301,FETCH_FEEDS:510,FETCH_FEED_MESSAGES:511,ADD_FEED:512,UPDATE_FEED:513,DELETE_FEED:514,ADD_FEED_MESSAGE:515,UPDATE_FEED_MESSAGE:516,DELETE_FEED_MESSAGE:517});Du=(Yo=class{constructor(){T(this,Pt);T(this,Be);T(this,an);ke(this,"signal");b(this,Be,new Mr({connections:new Map,presences:new Map})),this.signal=Dn.from(a(this,Be),n=>ns(Array.from(a(this,Be).get().presences.keys()).map(e=>this.getUser(Number(e))))),b(this,an,new Map)}get(){return this.signal.get()}connectionIds(){return a(this,Be).get().connections.keys()}clearOthers(){a(this,Be).mutate(n=>{n.connections.clear(),n.presences.clear(),a(this,an).clear()})}getUser(n){let e=a(this,an).get(n);if(e)return e;let t=S(this,Pt,Ga).call(this,n);if(t)return a(this,an).set(n,t),t}setConnection(n,e,t,r){a(this,Be).mutate(i=>(i.connections.set(n,bt({connectionId:n,id:e,info:t,scopes:r})),i.presences.has(n)?S(this,Pt,Lr).call(this,n):!1))}removeConnection(n){a(this,Be).mutate(e=>{e.connections.delete(n),e.presences.delete(n),S(this,Pt,Lr).call(this,n)})}setOther(n,e){a(this,Be).mutate(t=>(t.presences.set(n,bt(Si(e))),t.connections.has(n)?S(this,Pt,Lr).call(this,n):!1))}patchOther(n,e){a(this,Be).mutate(t=>{let r=t.presences.get(n);if(r===void 0)return!1;let i=Qo(r,e);return r===i?!1:(t.presences.set(n,bt(i)),S(this,Pt,Lr).call(this,n))})}},Be=new WeakMap,an=new WeakMap,Pt=new WeakSet,Ga=function(n){let e=a(this,Be).get(),t=e.connections.get(n),r=e.presences.get(n);if(t!==void 0&&r!==void 0)return Lu(t,r)},Lr=function(n){a(this,an).delete(n)},Yo),bi=class Ya extends Error{constructor(t,r,i){super(t,{cause:i});ke(this,"context");this.context=r,this.name="LiveblocksError"}get roomId(){return this.context.roomId}get code(){return this.context.code}static from(t,r){return new Ya(Mu(t),t,r)}};ts=5e3;Ku=16,ju=1e3,qu=100,Ju=15e3,Wu=200,Gu=1e3,Yu=3e4,Xu=5e3,Zu=50,Qu=50,eh=50;sh={"&":"&","<":"<",">":">",'"':""","'":"'"},Xh=new RegExp(Object.keys(sh).map(n=>`\\${n}`).join("|"),"g"),oh={_:"\\_","*":"\\*","#":"\\#","`":"\\`","~":"\\~","!":"\\!","|":"\\|","(":"\\(",")":"\\)","{":"\\{","}":"\\}","[":"\\[","]":"\\]"},Zh=new RegExp(Object.keys(oh).map(n=>`\\${n}`).join("|"),"g");vs(Xo,ln,Sl)});var ah,ch,lh,Xa=vn(()=>{"use strict";_s();_s();ah="@liveblocks/client",ch="3.19.1",lh="esm";vs(ah,ch,lh)});function Ai(n){let e=0;for(let t=0;t<n.length;t++)e=e*31+n.charCodeAt(t)|0;return Za[Math.abs(e)%Za.length]}function br(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}var Za,Ti=vn(()=>{"use strict";Za=["#4F46E5","#15803D","#C2410C","#BE185D","#0E7490","#7E22CE","#DC2626","#0F766E"]});function hh(n,e){let t=document.createElement("div");t.setAttribute("data-vizu-presence-avatar",n.id),t.setAttribute("data-vizu-presence-name",n.name),t.setAttribute("data-vizu-presence-color",n.color),n.avatar&&t.setAttribute("data-vizu-presence-img",n.avatar);let r=br(),i=r?"none":"transform 130ms cubic-bezier(0.16, 1, 0.3, 1), box-shadow 130ms ease-out";t.style.cssText=`
|
|
4
4
|
position: relative;
|
|
5
5
|
width: ${ki}px;
|
|
6
6
|
height: ${ki}px;
|
|
@@ -126,7 +126,7 @@
|
|
|
126
126
|
pointer-events: none;
|
|
127
127
|
z-index: ${Rs};
|
|
128
128
|
contain: strict;
|
|
129
|
-
`,document.body.appendChild(this.container)}attachMouseListener(){this.mouseListener=e=>{let t=e.clientX/window.innerWidth*100,r=e.clientY/window.innerHeight*100;this.pendingCursor={xPct:t,yPct:r},this.flushThrottled()},window.addEventListener("mousemove",this.mouseListener,{passive:!0})}attachScrollListener(){this.scrollListener=()=>{let t=performance.now()-this.lastScrollBroadcast;if(t>=oc){this.flushScroll();return}this.scrollThrottleTimer==null&&(this.scrollThrottleTimer=window.setTimeout(()=>{this.scrollThrottleTimer=null,this.flushScroll()},oc-t))},window.addEventListener("scroll",this.scrollListener,{passive:!0})}flushScroll(){this.room&&(this.room.updatePresence({scrollY:window.scrollY}),this.lastScrollBroadcast=performance.now())}attachVisibilityListener(){this.visibilityListener=()=>{document.hidden&&this.room&&this.room.updatePresence({cursor:null})},document.addEventListener("visibilitychange",this.visibilityListener)}attachKeyboardListener(){this.keydownListener=e=>{e.key==="Escape"&&this.followingUserId&&this.setFollowing(null)},document.addEventListener("keydown",this.keydownListener)}subscribeStatus(){if(!this.room)return;this.statusIndicator?.setStatus(this.room.getStatus());let e=this.room.subscribe("status",t=>{this.statusIndicator?.setStatus(t)});this.unsubscribers.push(e)}flushThrottled(){let t=performance.now()-this.lastBroadcast;if(t>=sc){this.flush();return}this.throttleTimer==null&&(this.throttleTimer=window.setTimeout(()=>{this.throttleTimer=null,this.flush()},sc-t))}flush(){!this.pendingCursor||!this.room||(this.room.updatePresence({cursor:this.pendingCursor}),this.pendingCursor=null,this.lastBroadcast=performance.now())}subscribeOthers(){if(!this.room)return;let e=this.room.subscribe("others",t=>{let r=new Set,i=new Map,s=[],o=null,c=!1;for(let u of t){r.add(u.connectionId);let h=u,l=h.id??`c${u.connectionId}`,m=h.info?.name??"Anonymous",k=Ai(l);i.has(l)||i.set(l,{id:l,name:m,color:k,avatar:h.info?.avatar});let O=u.presence;if(this.followingUserId===l&&o===null&&(c=!0,typeof O.scrollY=="number"&&(o=O.scrollY)),O.selecting&&!s.find(
|
|
129
|
+
`,document.body.appendChild(this.container)}attachMouseListener(){this.mouseListener=e=>{let t=e.clientX/window.innerWidth*100,r=e.clientY/window.innerHeight*100;this.pendingCursor={xPct:t,yPct:r},this.flushThrottled()},window.addEventListener("mousemove",this.mouseListener,{passive:!0})}attachScrollListener(){this.scrollListener=()=>{let t=performance.now()-this.lastScrollBroadcast;if(t>=oc){this.flushScroll();return}this.scrollThrottleTimer==null&&(this.scrollThrottleTimer=window.setTimeout(()=>{this.scrollThrottleTimer=null,this.flushScroll()},oc-t))},window.addEventListener("scroll",this.scrollListener,{passive:!0})}flushScroll(){this.room&&(this.room.updatePresence({scrollY:window.scrollY}),this.lastScrollBroadcast=performance.now())}attachVisibilityListener(){this.visibilityListener=()=>{document.hidden&&this.room&&this.room.updatePresence({cursor:null})},document.addEventListener("visibilitychange",this.visibilityListener)}attachKeyboardListener(){this.keydownListener=e=>{e.key==="Escape"&&this.followingUserId&&this.setFollowing(null)},document.addEventListener("keydown",this.keydownListener)}subscribeStatus(){if(!this.room)return;this.statusIndicator?.setStatus(this.room.getStatus());let e=this.room.subscribe("status",t=>{this.statusIndicator?.setStatus(t)});this.unsubscribers.push(e)}flushThrottled(){let t=performance.now()-this.lastBroadcast;if(t>=sc){this.flush();return}this.throttleTimer==null&&(this.throttleTimer=window.setTimeout(()=>{this.throttleTimer=null,this.flush()},sc-t))}flush(){!this.pendingCursor||!this.room||(this.room.updatePresence({cursor:this.pendingCursor}),this.pendingCursor=null,this.lastBroadcast=performance.now())}subscribeOthers(){if(!this.room)return;let e=this.room.subscribe("others",t=>{let r=new Set,i=new Map,s=[],o=null,c=!1;for(let u of t){r.add(u.connectionId);let h=u,l=h.id??`c${u.connectionId}`,m=h.info?.name??"Anonymous",k=Ai(l);i.has(l)||i.set(l,{id:l,name:m,color:k,avatar:h.info?.avatar});let O=u.presence;if(this.followingUserId===l&&o===null&&(c=!0,typeof O.scrollY=="number"&&(o=O.scrollY)),O.selecting&&!s.find(_=>_.id===l))try{let _=JSON.parse(O.selecting.fingerprintJson);s.push({id:l,name:m,color:k,fingerprint:_})}catch{}if(!O.cursor){this.removeCursor(u.connectionId);continue}this.upsertCursor(u.connectionId,l,m,O.cursor)}for(let u of Array.from(this.cursors.keys()))r.has(u)||this.removeCursor(u);this.presenceStack?.setOthers(Array.from(i.values())),this.selectionOverlay?.setSelections(s),this.followingUserId&&(c?o!==null&&this.followScrollTo(o):this.setFollowing(null))});this.unsubscribers.push(e)}upsertCursor(e,t,r,i){if(!this.container)return;let s=this.cursors.get(e);if(!s){let h=Ai(t),l=Ch(r,h);this.container.appendChild(l),s={el:l,fadeTimer:null},this.cursors.set(e,s)}if(!(i.xPct>=0&&i.xPct<=100&&i.yPct>=0&&i.yPct<=100)){s.el.style.opacity="0";return}let c=window.innerWidth*i.xPct/100,u=window.innerHeight*i.yPct/100;s.el.style.transform=`translate(${c}px, ${u}px)`,s.el.style.opacity="1",s.fadeTimer!=null&&window.clearTimeout(s.fadeTimer),s.fadeTimer=window.setTimeout(()=>{s&&(s.el.style.opacity="0")},bh)}removeCursor(e){let t=this.cursors.get(e);t&&(t.fadeTimer!=null&&window.clearTimeout(t.fadeTimer),t.el.style.opacity="0",window.setTimeout(()=>t.el.remove(),220),this.cursors.delete(e))}};Is=class{constructor(){this.el=null;this.label=null}mount(){if(typeof document>"u"||this.el)return;this.el=document.createElement("div"),this.el.setAttribute("data-vizu-connection-status",""),this.el.style.cssText=`
|
|
130
130
|
position: fixed;
|
|
131
131
|
top: 18px;
|
|
132
132
|
right: 200px;
|
|
@@ -188,7 +188,7 @@
|
|
|
188
188
|
<span class="vz-attachment-icon" aria-hidden="true">\u{1F4C4}</span>
|
|
189
189
|
<span class="vz-attachment-filename">${D(i)}</span>
|
|
190
190
|
</a>
|
|
191
|
-
`}).join("")}</div>`}function bn(n){if(!n||typeof n!="object")return n;let e={...n};return(!Array.isArray(e.fingerprints)||e.fingerprints.length===0)&&e.fingerprint&&(e.fingerprints=[e.fingerprint]),delete e.fingerprint,e.url&&!e.pageUrl&&(e.pageUrl=e.url),(!("status"in e)||!nl(e.status))&&(e.status="open"),Array.isArray(e.replies)||(e.replies=[]),Array.isArray(e.attachments)||(e.attachments=[]),Array.isArray(e.mentions)||(e.mentions=[]),"fingerprintsRefreshedAt"in e||(e.fingerprintsRefreshedAt=null),e.schemaVersion=2,e}function nl(n){return n==="open"||n==="resolved"||n==="wontfix"}function En(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)!t||typeof t!="object"||e.push(bn(t));return e}function Js(n){if(!Array.isArray(n))return!1;for(let e of n){if(!e||typeof e!="object")continue;let t=e;if(t.schemaVersion!==2||"fingerprint"in t||!Array.isArray(t.replies)||!Array.isArray(t.attachments)||!Array.isArray(t.mentions))return!0}return!1}var Vi=n=>`vizu:comments:${n}`,Ar=class{async load(e){return jn(e)}async addComment(e,t){let r=jn(e);r.push(t),qn(e,r)}async updateComment(e,t,r){let i=jn(e),s=i.findIndex(c=>c.id===t);if(s===-1)return null;let o={...i[s],...r,id:i[s].id};return i[s]=o,qn(e,i),o}async removeComment(e,t){let r=jn(e);qn(e,r.filter(i=>i.id!==t))}async setAll(e,t){qn(e,t)}async clear(e){typeof localStorage>"u"||localStorage.removeItem(Vi(e))}async addReply(e,t,r){let i=jn(e),s=i.findIndex(c=>c.id===t);if(s===-1)return null;let o={...i[s],replies:[...i[s].replies??[],r]};return i[s]=o,qn(e,i),o}async removeReply(e,t,r){let i=jn(e),s=i.findIndex(c=>c.id===t);if(s===-1)return null;let o={...i[s],replies:(i[s].replies??[]).filter(c=>c.id!==r)};return i[s]=o,qn(e,i),o}};function jn(n){if(typeof localStorage>"u")return[];let e=localStorage.getItem(Vi(n));if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?En(t):[]}catch{return[]}}function qn(n,e){typeof localStorage>"u"||localStorage.setItem(Vi(n),JSON.stringify(e))}var Tr=class{constructor(){this.store=new Map}async load(e){return[...this.store.get(e)||[]]}async addComment(e,t){let r=this.store.get(e)??[];this.store.set(e,[...r,t])}async updateComment(e,t,r){let i=this.store.get(e)??[],s=i.findIndex(u=>u.id===t);if(s===-1)return null;let o={...i[s],...r,id:i[s].id},c=[...i];return c[s]=o,this.store.set(e,c),o}async removeComment(e,t){let r=this.store.get(e)??[];this.store.set(e,r.filter(i=>i.id!==t))}async setAll(e,t){this.store.set(e,[...t])}async clear(e){this.store.delete(e)}async addReply(e,t,r){let i=this.store.get(e)??[],s=i.findIndex(u=>u.id===t);if(s===-1)return null;let o={...i[s],replies:[...i[s].replies??[],r]},c=[...i];return c[s]=o,this.store.set(e,c),o}async removeReply(e,t,r){let i=this.store.get(e)??[],s=i.findIndex(u=>u.id===t);if(s===-1)return null;let o={...i[s],replies:(i[s].replies??[]).filter(u=>u.id!==r)},c=[...i];return c[s]=o,this.store.set(e,c),o}},ei=class{async load(){return[]}async addComment(){}async updateComment(){return null}async removeComment(){}async setAll(){}async clear(){}};function Hi(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.load=="function"&&typeof e.save=="function"&&typeof e.clear=="function"&&typeof e.addComment!="function"}function Ws(n){if(!Hi(n))return n;let e=!1,t=()=>{e||(e=!0,typeof console<"u"&&console.warn("[vizu] StorageAdapter v1 detected. Per-comment ops are emulated via full-array rewrites \u2014 upgrade your adapter to the v2 interface (addComment / updateComment / removeComment / setAll / load / clear) when you can."))};return{async load(r){return t(),n.load(r)},async addComment(r,i){t();let s=await n.load(r);s.push(i),await n.save(r,s)},async updateComment(r,i,s){t();let o=await n.load(r),c=o.findIndex(h=>h.id===i);if(c===-1)return null;let u={...o[c],...s,id:o[c].id};return o[c]=u,await n.save(r,o),u},async removeComment(r,i){t();let s=await n.load(r);await n.save(r,s.filter(o=>o.id!==i))},async setAll(r,i){t(),await n.save(r,i)},async clear(r){await n.clear(r)}}}var rl="https://vizu.unhingged.com",Gs=480,Ys=640,ni=class{constructor(e){this.cachedToken=null;this.pendingAuth=null;this.workspace=e.workspace,this.apiUrl=(e.apiUrl??rl).replace(/\/$/,""),this.autoSignIn=e.autoSignIn!==!1,this.cachedToken=this.readStoredToken()}async load(e){let t=[],r=null;do{let i=new URL(this.apiUrl+"/api/comments");i.searchParams.set("workspace",this.workspace),i.searchParams.set("limit","100"),r&&i.searchParams.set("cursor",r);let s=await this.fetchAuthed(i.toString(),{method:"GET"}),o=await this.parseJson(s);if(!s.ok)throw Tt(s.status,o);let c=Array.isArray(o.comments)?o.comments:[];t.push(...En(c)),r=typeof o.nextCursor=="string"?o.nextCursor:null}while(r);return t}async addComment(e,t){let r=await this.fetchAuthed(this.apiUrl+"/api/comments",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({workspace:this.workspace,comment:t})}),i=await this.parseJson(r);if(!r.ok)throw Tt(r.status,i)}async updateComment(e,t,r){let i=new URL(this.apiUrl+"/api/comments/"+encodeURIComponent(t));i.searchParams.set("workspace",this.workspace);let s=await this.fetchAuthed(i.toString(),{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(r)});if(s.status===404)return null;let o=await this.parseJson(s);if(!s.ok)throw Tt(s.status,o);return bn(o.comment)}async removeComment(e,t){let r=new URL(this.apiUrl+"/api/comments/"+encodeURIComponent(t));r.searchParams.set("workspace",this.workspace);let i=await this.fetchAuthed(r.toString(),{method:"DELETE"});if(i.status!==404&&!i.ok){let s=await this.parseJson(i);throw Tt(i.status,s)}}async setAll(e,t){await this.clear(e);for(let r of t)await this.addComment(e,r)}async clear(e){let t=new URL(this.apiUrl+"/api/comments");t.searchParams.set("workspace",this.workspace),t.searchParams.set("all","true");let r=await this.fetchAuthed(t.toString(),{method:"DELETE"});if(r.status!==404&&!r.ok){let i=await this.parseJson(r);throw Tt(r.status,i)}}async addReply(e,t,r){let i=new URL(this.apiUrl+"/api/comments/"+encodeURIComponent(t)+"/replies");i.searchParams.set("workspace",this.workspace);let s=await this.fetchAuthed(i.toString(),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)});if(s.status===404)return null;let o=await this.parseJson(s);if(!s.ok)throw Tt(s.status,o);return o?.comment?bn(o.comment):null}async removeReply(e,t,r){let i=new URL(this.apiUrl+"/api/comments/"+encodeURIComponent(t)+"/replies/"+encodeURIComponent(r));i.searchParams.set("workspace",this.workspace);let s=await this.fetchAuthed(i.toString(),{method:"DELETE"});if(s.status===404)return null;if(!s.ok){let o=await this.parseJson(s);throw Tt(s.status,o)}return null}async uploadAttachment(e,t){let r=new FormData;r.append("file",t,t.name);let i=new URL(this.apiUrl+"/api/uploads");i.searchParams.set("workspace",this.workspace);let s=await this.fetchAuthed(i.toString(),{method:"POST",body:r}),o=await this.parseJson(s);if(!s.ok)throw Tt(s.status,o);if(!o?.url||typeof o.url!="string")throw Tt(500,{error:"upload_failed",message:"Backend did not return a URL."});return{id:Sr(),url:o.url,mimeType:t.type||"application/octet-stream",sizeBytes:t.size,uploadedAt:Date.now(),filename:t.name}}getAuthContext(){return this.cachedToken?{userId:this.cachedToken.userId,token:this.cachedToken.token,expiresAt:this.cachedToken.expiresAt}:null}isExpired(e){if(!e)return!0;let t=new Date(e.expiresAt).getTime();return!Number.isFinite(t)||t-Date.now()<3e4}readStoredToken(){if(typeof sessionStorage>"u")return null;let e=sessionStorage.getItem(this.sessionKey());if(!e)return null;try{let t=JSON.parse(e);return this.isExpired(t)?(sessionStorage.removeItem(this.sessionKey()),null):t}catch{return null}}writeStoredToken(e){this.cachedToken=e,typeof sessionStorage<"u"&&sessionStorage.setItem(this.sessionKey(),JSON.stringify(e))}clearStoredToken(){this.cachedToken=null,typeof sessionStorage<"u"&&sessionStorage.removeItem(this.sessionKey())}sessionKey(){return`vizu:cloud-token:${this.workspace}`}async resolveToken(){if(this.cachedToken&&!this.isExpired(this.cachedToken))return this.cachedToken;let e=this.readStoredToken();if(e)return this.cachedToken=e,e;if(!this.autoSignIn)throw ti("auth_required","Sign-in required; autoSignIn is disabled.");return this.pendingAuth||(this.pendingAuth=this.openSignInPopup().then(t=>(this.writeStoredToken(t),t)).finally(()=>{this.pendingAuth=null})),this.pendingAuth}openSignInPopup(){return new Promise((e,t)=>{if(typeof window>"u")return t(ti("auth_unavailable","Sign-in requires a browser environment."));let r=new URL(this.apiUrl).origin,i=window.location.origin,s=this.apiUrl+"/connect?workspace="+encodeURIComponent(this.workspace)+"&origin="+encodeURIComponent(i),o=Math.max(0,Math.round((window.screen.width-Gs)/2)),c=Math.max(0,Math.round((window.screen.height-Ys)/2)),u=window.open(s,"vizu-connect",`width=${Gs},height=${Ys},left=${o},top=${c},noopener=no,popup=yes`);if(!u)return t(ti("popup_blocked","Sign-in popup was blocked by the browser. Allow popups for this site and try again."));let h=!1,l=O=>{if(O.origin!==r)return;let z=O.data;!z||z.type!=="vizu:auth"||z.workspace===this.workspace&&(typeof z.token!="string"||typeof z.expiresAt!="string"||typeof z.userId!="string"||(h=!0,k(),e({token:z.token,expiresAt:z.expiresAt,userId:z.userId})))},m=window.setInterval(()=>{u.closed&&(h||(k(),t(ti("auth_canceled","Sign-in popup was closed before completing."))))},500);function k(){window.clearInterval(m),window.removeEventListener("message",l)}window.addEventListener("message",l)})}async fetchAuthed(e,t,r=!1){let i=await this.resolveToken(),s=new Headers(t.headers);s.set("authorization",`Bearer ${i.token}`);let o=await fetch(e,{...t,headers:s,credentials:"omit"});return o.status===401&&!r?(this.clearStoredToken(),this.fetchAuthed(e,t,!0)):o}async parseJson(e){try{let t=await e.text();return t?JSON.parse(t):null}catch{return null}}};function ti(n,e){let t=new Error(e);return t.code=n,t}function Tt(n,e){let t=e?.error==="origin_not_allowed"?"origin_not_allowed":e?.error==="not_found"?"workspace_not_found":"http_error",r=new Error(e?.message??`HTTP ${n}`);return r.code=t,r.status=n,r.body=e,r}Xn();var pl="[data-vizu-root], [data-vizu-ignore], script, style, link, meta, head",ri=class{constructor(e,t,r,i){this.current=null;this.active=!1;this.paused=!1;this.handleMove=e=>{if(this.paused){this.setCurrent(null),this.overlay.style.display="none";return}let t=document.elementFromPoint(e.clientX,e.clientY);if(!(!t||t===this.current)){if(this.shouldIgnore(t)){this.setCurrent(null),this.overlay.style.display="none";return}this.setCurrent(t),this.updateOverlay()}};this.handleClick=e=>{let t=document.elementFromPoint(e.clientX,e.clientY);t&&(this.shouldIgnore(t)||(e.preventDefault(),e.stopPropagation(),this.onClick(t,e)))};this.handleScroll=()=>{this.current&&this.updateOverlay()};this.root=e,this.extraIgnore=t,this.onClick=r,this.onCurrentChange=i??null,this.overlay=document.createElement("div"),this.overlay.className="vz-highlight",this.overlay.style.display="none",this.root.appendChild(this.overlay)}setCurrent(e){this.current!==e&&(this.current=e,this.onCurrentChange?.(e))}start(){this.active||(this.active=!0,document.addEventListener("mousemove",this.handleMove,!0),document.addEventListener("click",this.handleClick,!0),document.addEventListener("scroll",this.handleScroll,!0),window.addEventListener("resize",this.handleScroll))}stop(){this.active&&(this.active=!1,document.removeEventListener("mousemove",this.handleMove,!0),document.removeEventListener("click",this.handleClick,!0),document.removeEventListener("scroll",this.handleScroll,!0),window.removeEventListener("resize",this.handleScroll),this.overlay.style.display="none",this.setCurrent(null))}shouldIgnore(e){if(e===document.documentElement||e===document.body||Fi(e,pl))return!0;for(let t of this.extraIgnore)try{if(Fi(e,t))return!0}catch{}return!1}setPaused(e){this.paused=e,e&&(this.setCurrent(null),this.overlay.style.display="none")}isPaused(){return this.paused}updateOverlay(){if(!this.current)return;let e=this.current.getBoundingClientRect();if(e.width===0||e.height===0){this.overlay.style.display="none";return}this.overlay.style.display="block",this.overlay.style.left=e.left+"px",this.overlay.style.top=e.top+"px",this.overlay.style.width=e.width+"px",this.overlay.style.height=e.height+"px"}destroy(){this.stop(),this.overlay.remove()}};Xn();function Qs(n){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(n):n.replace(/["\\]/g,"\\$&")}function fl(n){let t=(n.replies??[]).map(r=>`
|
|
191
|
+
`}).join("")}</div>`}function bn(n){if(!n||typeof n!="object")return n;let e={...n};return(!Array.isArray(e.fingerprints)||e.fingerprints.length===0)&&e.fingerprint&&(e.fingerprints=[e.fingerprint]),delete e.fingerprint,e.url&&!e.pageUrl&&(e.pageUrl=e.url),(!("status"in e)||!nl(e.status))&&(e.status="open"),Array.isArray(e.replies)||(e.replies=[]),Array.isArray(e.attachments)||(e.attachments=[]),Array.isArray(e.mentions)||(e.mentions=[]),"fingerprintsRefreshedAt"in e||(e.fingerprintsRefreshedAt=null),e.schemaVersion=2,e}function nl(n){return n==="open"||n==="resolved"||n==="wontfix"}function En(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)!t||typeof t!="object"||e.push(bn(t));return e}function Js(n){if(!Array.isArray(n))return!1;for(let e of n){if(!e||typeof e!="object")continue;let t=e;if(t.schemaVersion!==2||"fingerprint"in t||!Array.isArray(t.replies)||!Array.isArray(t.attachments)||!Array.isArray(t.mentions))return!0}return!1}var Vi=n=>`vizu:comments:${n}`,Ar=class{async load(e){return jn(e)}async addComment(e,t){let r=jn(e);r.push(t),qn(e,r)}async updateComment(e,t,r){let i=jn(e),s=i.findIndex(c=>c.id===t);if(s===-1)return null;let o={...i[s],...r,id:i[s].id};return i[s]=o,qn(e,i),o}async removeComment(e,t){let r=jn(e);qn(e,r.filter(i=>i.id!==t))}async setAll(e,t){qn(e,t)}async clear(e){typeof localStorage>"u"||localStorage.removeItem(Vi(e))}async addReply(e,t,r){let i=jn(e),s=i.findIndex(c=>c.id===t);if(s===-1)return null;let o={...i[s],replies:[...i[s].replies??[],r]};return i[s]=o,qn(e,i),o}async removeReply(e,t,r){let i=jn(e),s=i.findIndex(c=>c.id===t);if(s===-1)return null;let o={...i[s],replies:(i[s].replies??[]).filter(c=>c.id!==r)};return i[s]=o,qn(e,i),o}};function jn(n){if(typeof localStorage>"u")return[];let e=localStorage.getItem(Vi(n));if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?En(t):[]}catch{return[]}}function qn(n,e){typeof localStorage>"u"||localStorage.setItem(Vi(n),JSON.stringify(e))}var Tr=class{constructor(){this.store=new Map}async load(e){return[...this.store.get(e)||[]]}async addComment(e,t){let r=this.store.get(e)??[];this.store.set(e,[...r,t])}async updateComment(e,t,r){let i=this.store.get(e)??[],s=i.findIndex(u=>u.id===t);if(s===-1)return null;let o={...i[s],...r,id:i[s].id},c=[...i];return c[s]=o,this.store.set(e,c),o}async removeComment(e,t){let r=this.store.get(e)??[];this.store.set(e,r.filter(i=>i.id!==t))}async setAll(e,t){this.store.set(e,[...t])}async clear(e){this.store.delete(e)}async addReply(e,t,r){let i=this.store.get(e)??[],s=i.findIndex(u=>u.id===t);if(s===-1)return null;let o={...i[s],replies:[...i[s].replies??[],r]},c=[...i];return c[s]=o,this.store.set(e,c),o}async removeReply(e,t,r){let i=this.store.get(e)??[],s=i.findIndex(u=>u.id===t);if(s===-1)return null;let o={...i[s],replies:(i[s].replies??[]).filter(u=>u.id!==r)},c=[...i];return c[s]=o,this.store.set(e,c),o}},ti=class{async load(){return[]}async addComment(){}async updateComment(){return null}async removeComment(){}async setAll(){}async clear(){}};function Hi(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.load=="function"&&typeof e.save=="function"&&typeof e.clear=="function"&&typeof e.addComment!="function"}function Ws(n){if(!Hi(n))return n;let e=!1,t=()=>{e||(e=!0,typeof console<"u"&&console.warn("[vizu] StorageAdapter v1 detected. Per-comment ops are emulated via full-array rewrites \u2014 upgrade your adapter to the v2 interface (addComment / updateComment / removeComment / setAll / load / clear) when you can."))};return{async load(r){return t(),n.load(r)},async addComment(r,i){t();let s=await n.load(r);s.push(i),await n.save(r,s)},async updateComment(r,i,s){t();let o=await n.load(r),c=o.findIndex(h=>h.id===i);if(c===-1)return null;let u={...o[c],...s,id:o[c].id};return o[c]=u,await n.save(r,o),u},async removeComment(r,i){t();let s=await n.load(r);await n.save(r,s.filter(o=>o.id!==i))},async setAll(r,i){t(),await n.save(r,i)},async clear(r){await n.clear(r)}}}var rl="https://vizu.unhingged.com",Gs=480,Ys=640,kr=class{constructor(e){this.cachedToken=null;this.pendingAuth=null;this.lastNotifiedTokenId=null;this.workspace=e.workspace,this.apiUrl=(e.apiUrl??rl).replace(/\/$/,""),this.autoSignIn=e.autoSignIn!==!1,this.onAuthChanged=e.onAuthChanged,this.cachedToken=this.readStoredToken(),this.cachedToken&&!this.isExpired(this.cachedToken)&&this.fireAuthChanged(this.cachedToken)}async preflightAuth(){await this.resolveToken()}async load(e){let t=[],r=null;do{let i=new URL(this.apiUrl+"/api/comments");i.searchParams.set("workspace",this.workspace),i.searchParams.set("limit","100"),r&&i.searchParams.set("cursor",r);let s=await this.fetchAuthed(i.toString(),{method:"GET"}),o=await this.parseJson(s);if(!s.ok)throw Tt(s.status,o);let c=Array.isArray(o.comments)?o.comments:[];t.push(...En(c)),r=typeof o.nextCursor=="string"?o.nextCursor:null}while(r);return t}async addComment(e,t){let r=await this.fetchAuthed(this.apiUrl+"/api/comments",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({workspace:this.workspace,comment:t})}),i=await this.parseJson(r);if(!r.ok)throw Tt(r.status,i)}async updateComment(e,t,r){let i=new URL(this.apiUrl+"/api/comments/"+encodeURIComponent(t));i.searchParams.set("workspace",this.workspace);let s=await this.fetchAuthed(i.toString(),{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(r)});if(s.status===404)return null;let o=await this.parseJson(s);if(!s.ok)throw Tt(s.status,o);return bn(o.comment)}async removeComment(e,t){let r=new URL(this.apiUrl+"/api/comments/"+encodeURIComponent(t));r.searchParams.set("workspace",this.workspace);let i=await this.fetchAuthed(r.toString(),{method:"DELETE"});if(i.status!==404&&!i.ok){let s=await this.parseJson(i);throw Tt(i.status,s)}}async setAll(e,t){await this.clear(e);for(let r of t)await this.addComment(e,r)}async clear(e){let t=new URL(this.apiUrl+"/api/comments");t.searchParams.set("workspace",this.workspace),t.searchParams.set("all","true");let r=await this.fetchAuthed(t.toString(),{method:"DELETE"});if(r.status!==404&&!r.ok){let i=await this.parseJson(r);throw Tt(r.status,i)}}async addReply(e,t,r){let i=new URL(this.apiUrl+"/api/comments/"+encodeURIComponent(t)+"/replies");i.searchParams.set("workspace",this.workspace);let s=await this.fetchAuthed(i.toString(),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r)});if(s.status===404)return null;let o=await this.parseJson(s);if(!s.ok)throw Tt(s.status,o);return o?.comment?bn(o.comment):null}async removeReply(e,t,r){let i=new URL(this.apiUrl+"/api/comments/"+encodeURIComponent(t)+"/replies/"+encodeURIComponent(r));i.searchParams.set("workspace",this.workspace);let s=await this.fetchAuthed(i.toString(),{method:"DELETE"});if(s.status===404)return null;if(!s.ok){let o=await this.parseJson(s);throw Tt(s.status,o)}return null}async uploadAttachment(e,t){let r=new FormData;r.append("file",t,t.name);let i=new URL(this.apiUrl+"/api/uploads");i.searchParams.set("workspace",this.workspace);let s=await this.fetchAuthed(i.toString(),{method:"POST",body:r}),o=await this.parseJson(s);if(!s.ok)throw Tt(s.status,o);if(!o?.url||typeof o.url!="string")throw Tt(500,{error:"upload_failed",message:"Backend did not return a URL."});return{id:Sr(),url:o.url,mimeType:t.type||"application/octet-stream",sizeBytes:t.size,uploadedAt:Date.now(),filename:t.name}}getAuthContext(){return this.cachedToken?{userId:this.cachedToken.userId,token:this.cachedToken.token,expiresAt:this.cachedToken.expiresAt}:null}isExpired(e){if(!e)return!0;let t=new Date(e.expiresAt).getTime();return!Number.isFinite(t)||t-Date.now()<3e4}readStoredToken(){if(typeof sessionStorage>"u")return null;let e=sessionStorage.getItem(this.sessionKey());if(!e)return null;try{let t=JSON.parse(e);return this.isExpired(t)?(sessionStorage.removeItem(this.sessionKey()),null):t}catch{return null}}writeStoredToken(e){this.cachedToken=e,typeof sessionStorage<"u"&&sessionStorage.setItem(this.sessionKey(),JSON.stringify(e))}clearStoredToken(){this.cachedToken=null,typeof sessionStorage<"u"&&sessionStorage.removeItem(this.sessionKey())}sessionKey(){return`vizu:cloud-token:${this.workspace}`}async resolveToken(){if(this.cachedToken&&!this.isExpired(this.cachedToken))return this.cachedToken;let e=this.readStoredToken();if(e)return this.cachedToken=e,this.fireAuthChanged(e),e;if(!this.autoSignIn)throw ni("auth_required","Sign-in required; autoSignIn is disabled.");return this.pendingAuth||(this.pendingAuth=this.openSignInPopup().then(t=>(this.writeStoredToken(t),this.fireAuthChanged(t),t)).finally(()=>{this.pendingAuth=null})),this.pendingAuth}fireAuthChanged(e){if(this.lastNotifiedTokenId!==e.token){this.lastNotifiedTokenId=e.token;try{this.onAuthChanged?.({userId:e.userId,user:e.user})}catch(t){typeof console<"u"&&console.warn("[vizu/cloud] onAuthChanged callback threw",t)}}}openSignInPopup(){return new Promise((e,t)=>{if(typeof window>"u")return t(ni("auth_unavailable","Sign-in requires a browser environment."));let r=new URL(this.apiUrl).origin,i=window.location.origin,s=this.apiUrl+"/connect?workspace="+encodeURIComponent(this.workspace)+"&origin="+encodeURIComponent(i),o=Math.max(0,Math.round((window.screen.width-Gs)/2)),c=Math.max(0,Math.round((window.screen.height-Ys)/2)),u=window.open(s,"vizu-connect",`width=${Gs},height=${Ys},left=${o},top=${c},noopener=no,popup=yes`);if(!u)return t(ni("popup_blocked","Sign-in popup was blocked by the browser. Allow popups for this site and try again."));let h=!1,l=O=>{if(O.origin!==r)return;let _=O.data;if(!_||_.type!=="vizu:auth"||_.workspace!==this.workspace||typeof _.token!="string"||typeof _.expiresAt!="string"||typeof _.userId!="string")return;h=!0,k();let F=_.user,K=F&&typeof F.name=="string"?{id:typeof F.id=="string"?F.id:_.userId,name:F.name,avatarUrl:typeof F.avatarUrl=="string"?F.avatarUrl:void 0}:null;e({token:_.token,expiresAt:_.expiresAt,userId:_.userId,user:K})},m=window.setInterval(()=>{u.closed&&(h||(k(),t(ni("auth_canceled","Sign-in popup was closed before completing."))))},500);function k(){window.clearInterval(m),window.removeEventListener("message",l)}window.addEventListener("message",l)})}async fetchAuthed(e,t,r=!1){let i=await this.resolveToken(),s=new Headers(t.headers);s.set("authorization",`Bearer ${i.token}`);let o=await fetch(e,{...t,headers:s,credentials:"omit"});return o.status===401&&!r?(this.clearStoredToken(),this.fetchAuthed(e,t,!0)):o}async parseJson(e){try{let t=await e.text();return t?JSON.parse(t):null}catch{return null}}};function ni(n,e){let t=new Error(e);return t.code=n,t}function Tt(n,e){let t=e?.error==="origin_not_allowed"?"origin_not_allowed":e?.error==="not_found"?"workspace_not_found":"http_error",r=new Error(e?.message??`HTTP ${n}`);return r.code=t,r.status=n,r.body=e,r}Xn();var pl="[data-vizu-root], [data-vizu-ignore], script, style, link, meta, head",ri=class{constructor(e,t,r,i){this.current=null;this.active=!1;this.paused=!1;this.handleMove=e=>{if(this.paused){this.setCurrent(null),this.overlay.style.display="none";return}let t=document.elementFromPoint(e.clientX,e.clientY);if(!(!t||t===this.current)){if(this.shouldIgnore(t)){this.setCurrent(null),this.overlay.style.display="none";return}this.setCurrent(t),this.updateOverlay()}};this.handleClick=e=>{let t=document.elementFromPoint(e.clientX,e.clientY);t&&(this.shouldIgnore(t)||(e.preventDefault(),e.stopPropagation(),this.onClick(t,e)))};this.handleScroll=()=>{this.current&&this.updateOverlay()};this.root=e,this.extraIgnore=t,this.onClick=r,this.onCurrentChange=i??null,this.overlay=document.createElement("div"),this.overlay.className="vz-highlight",this.overlay.style.display="none",this.root.appendChild(this.overlay)}setCurrent(e){this.current!==e&&(this.current=e,this.onCurrentChange?.(e))}start(){this.active||(this.active=!0,document.addEventListener("mousemove",this.handleMove,!0),document.addEventListener("click",this.handleClick,!0),document.addEventListener("scroll",this.handleScroll,!0),window.addEventListener("resize",this.handleScroll))}stop(){this.active&&(this.active=!1,document.removeEventListener("mousemove",this.handleMove,!0),document.removeEventListener("click",this.handleClick,!0),document.removeEventListener("scroll",this.handleScroll,!0),window.removeEventListener("resize",this.handleScroll),this.overlay.style.display="none",this.setCurrent(null))}shouldIgnore(e){if(e===document.documentElement||e===document.body||Fi(e,pl))return!0;for(let t of this.extraIgnore)try{if(Fi(e,t))return!0}catch{}return!1}setPaused(e){this.paused=e,e&&(this.setCurrent(null),this.overlay.style.display="none")}isPaused(){return this.paused}updateOverlay(){if(!this.current)return;let e=this.current.getBoundingClientRect();if(e.width===0||e.height===0){this.overlay.style.display="none";return}this.overlay.style.display="block",this.overlay.style.left=e.left+"px",this.overlay.style.top=e.top+"px",this.overlay.style.width=e.width+"px",this.overlay.style.height=e.height+"px"}destroy(){this.stop(),this.overlay.remove()}};Xn();function Qs(n){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(n):n.replace(/["\\]/g,"\\$&")}function fl(n){let t=(n.replies??[]).map(r=>`
|
|
192
192
|
<div class="vz-reply" data-reply-id="${D(r.id)}">
|
|
193
193
|
${r.author?`<div class="vz-comment-author">${At(r.author)} <span class="vz-comment-author-name">${D(r.author.name)}</span></div>`:""}
|
|
194
194
|
<div class="vz-reply-text">${D(r.text)}</div>
|
|
@@ -271,18 +271,18 @@
|
|
|
271
271
|
<svg viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.6"><rect x="1" y="1" width="5" height="5"/><rect x="8" y="1" width="5" height="5"/><rect x="1" y="8" width="5" height="5"/><rect x="8" y="8" width="5" height="5"/></svg>
|
|
272
272
|
</button>
|
|
273
273
|
<button class="vz-pill-icon-btn" data-vz="disable" title="Disable Vizu (toggle with shortcut)" aria-label="Disable">\xD7</button>
|
|
274
|
-
`}toast(e){let t=document.createElement("div");t.className="vz-toast",t.textContent=e,this.root.appendChild(t),setTimeout(()=>t.remove(),1800)}destroy(){this.el.removeEventListener("click",this.handleClick),this.el.remove()}};Xn();var oi=class{constructor(e,t){this.open=!1;this.filter="open";this.lastComments=[];this.lastConfidence=new Map;this.handleClick=e=>{let t=e.target,r=t.closest('[data-vz="ref"]');if(r){e.stopPropagation();let h=r.getAttribute("data-comment-id"),l=r.getAttribute("data-ref-id");h&&l&&this.callbacks.onJumpToReference(h,l);return}let i=t.closest('[data-vz="filter"]');if(i){e.stopPropagation();let h=i.getAttribute("data-filter");h&&h!==this.filter&&(this.filter=h,this.render(this.lastComments));return}let s=t.closest('[data-vz="status"]');if(s){e.stopPropagation();let h=s.getAttribute("data-id"),l=s.getAttribute("data-status");h&&l&&this.callbacks.onUpdateStatus(h,l);return}let o=t.closest('[data-vz="delete"]');if(o){e.stopPropagation();let h=o.getAttribute("data-id");h&&this.callbacks.onDelete(h);return}if(t.closest('[data-vz="close"]')){this.callbacks.onClose();return}let c=t.closest('[data-vz="jump-fp"]');if(c&&c.__fp){e.stopPropagation(),this.callbacks.onJumpTo(c.__fp);return}let u=t.closest('[data-vz="jump"]');u&&u.__group&&this.callbacks.onJumpTo(u.__group.fp)};this.root=e,this.callbacks=t,this.el=document.createElement("div"),this.el.className="vz-sidebar",this.el.addEventListener("click",this.handleClick),this.root.appendChild(this.el)}toggle(e,t){this.open?this.close():this.show(e,t)}show(e,t){this.render(e,t),requestAnimationFrame(()=>this.el.classList.add("is-open")),this.open=!0}update(e,t){this.open&&this.render(e,t)}close(){this.el.classList.remove("is-open"),this.open=!1}isOpen(){return this.open}render(e,t){this.lastComments=e,t&&(this.lastConfidence=new Map(t));let r=this.lastConfidence,i=e.filter(
|
|
274
|
+
`}toast(e){let t=document.createElement("div");t.className="vz-toast",t.textContent=e,this.root.appendChild(t),setTimeout(()=>t.remove(),1800)}destroy(){this.el.removeEventListener("click",this.handleClick),this.el.remove()}};Xn();var oi=class{constructor(e,t){this.open=!1;this.filter="open";this.lastComments=[];this.lastConfidence=new Map;this.handleClick=e=>{let t=e.target,r=t.closest('[data-vz="ref"]');if(r){e.stopPropagation();let h=r.getAttribute("data-comment-id"),l=r.getAttribute("data-ref-id");h&&l&&this.callbacks.onJumpToReference(h,l);return}let i=t.closest('[data-vz="filter"]');if(i){e.stopPropagation();let h=i.getAttribute("data-filter");h&&h!==this.filter&&(this.filter=h,this.render(this.lastComments));return}let s=t.closest('[data-vz="status"]');if(s){e.stopPropagation();let h=s.getAttribute("data-id"),l=s.getAttribute("data-status");h&&l&&this.callbacks.onUpdateStatus(h,l);return}let o=t.closest('[data-vz="delete"]');if(o){e.stopPropagation();let h=o.getAttribute("data-id");h&&this.callbacks.onDelete(h);return}if(t.closest('[data-vz="close"]')){this.callbacks.onClose();return}let c=t.closest('[data-vz="jump-fp"]');if(c&&c.__fp){e.stopPropagation(),this.callbacks.onJumpTo(c.__fp);return}let u=t.closest('[data-vz="jump"]');u&&u.__group&&this.callbacks.onJumpTo(u.__group.fp)};this.root=e,this.callbacks=t,this.el=document.createElement("div"),this.el.className="vz-sidebar",this.el.addEventListener("click",this.handleClick),this.root.appendChild(this.el)}toggle(e,t){this.open?this.close():this.show(e,t)}show(e,t){this.render(e,t),requestAnimationFrame(()=>this.el.classList.add("is-open")),this.open=!0}update(e,t){this.open&&this.render(e,t)}close(){this.el.classList.remove("is-open"),this.open=!1}isOpen(){return this.open}render(e,t){this.lastComments=e,t&&(this.lastConfidence=new Map(t));let r=this.lastConfidence,i=e.filter(K=>r.get(K.id)==="orphaned"),s=e.filter(K=>r.get(K.id)!=="orphaned"),o=this.filter==="open"?s.filter(K=>(K.status??"open")==="open"):s,c=this.filter==="open"?[]:i,u=ml(e);if(o.length===0&&c.length===0){let K=this.filter==="open"&&e.length>0?`<strong>Nothing open.</strong>${u.resolved+u.wontfix} closed comment${u.resolved+u.wontfix===1?"":"s"} hidden. Switch to <em>All</em> to see them.`:"<strong>No comments yet</strong>Click any element on the page to leave one.";this.el.innerHTML=`
|
|
275
275
|
${this.headerHtml(e.length,u)}
|
|
276
276
|
<div class="vz-sidebar-body">
|
|
277
|
-
<div class="vz-sidebar-empty">${
|
|
277
|
+
<div class="vz-sidebar-empty">${K}</div>
|
|
278
278
|
</div>
|
|
279
|
-
`;return}let h=new Map;for(let
|
|
279
|
+
`;return}let h=new Map;for(let K of o){let z=(K.fingerprints||[])[0];if(!z)continue;let P=de(z),C=h.get(P);C?C.comments.push(K):h.set(P,{fp:z,comments:[K]})}let l=[],m=0;for(let K of h.values()){let se=K.fp.tagName.toLowerCase()+(K.fp.attributes.id?"#"+K.fp.attributes.id:""),z=K.fp.textSnippet.slice(0,60);l.push(`
|
|
280
280
|
<div class="vz-sidebar-group" data-group="${m}">
|
|
281
281
|
<div class="vz-sidebar-group-head">
|
|
282
282
|
${D(se)}
|
|
283
|
-
${
|
|
283
|
+
${z?`<div class="vz-sidebar-group-text">“${D(z)}${K.fp.textSnippet.length>60?"\u2026":""}”</div>`:""}
|
|
284
284
|
</div>
|
|
285
|
-
${
|
|
285
|
+
${K.comments.map(P=>{let C=P.status??"open",R=(P.fingerprints||[]).slice(1),y=R.length?`<div class="vz-anchor-list" style="margin-top:6px">${R.map((oe,re)=>`<span class="vz-anchor-chip" data-vz="jump-fp" data-fp-key="${D(de(oe))}" title="Jump to this element">+${re+2}/${(P.fingerprints||[]).length} ${D(Yn(oe))}</span>`).join("")}</div>`:"",G=r.get(P.id)==="drifted"?'<span class="vz-status-pill vz-status-drifted" title="Anchored via a fallback match \u2014 the original element may have moved or changed.">drifted</span>':"";return`
|
|
286
286
|
<div class="vz-sidebar-item ${C!=="open"?"vz-sidebar-item-dim":""}" data-comment-id="${D(P.id)}" data-vz="jump" data-group="${m}" role="button" tabindex="0">
|
|
287
287
|
<div class="vz-sidebar-item-row">
|
|
288
288
|
${P.author?`<div class="vz-sidebar-item-author">${At(P.author)} <span class="vz-sidebar-item-author-name">${D(P.author.name)}</span></div>`:""}
|
|
@@ -308,7 +308,7 @@
|
|
|
308
308
|
${l.join("")}
|
|
309
309
|
${k}
|
|
310
310
|
</div>
|
|
311
|
-
`;let O=this.el.querySelectorAll('[data-vz="jump"]'),
|
|
311
|
+
`;let O=this.el.querySelectorAll('[data-vz="jump"]'),_=[...h.values()];for(let K of O){let se=Number(K.dataset.group);K.__group=_[se]}let F=this.el.querySelectorAll('[data-vz="jump-fp"]');for(let K of F){let se=K.getAttribute("data-fp-key"),z=yl(o,se||"");K.__fp=z}}headerHtml(e,t){return`
|
|
312
312
|
<div class="vz-sidebar-header">
|
|
313
313
|
<div class="vz-sidebar-title">
|
|
314
314
|
Comments
|
|
@@ -1270,7 +1270,7 @@
|
|
|
1270
1270
|
from { opacity: 0; transform: translateX(-50%) translateY(8px); }
|
|
1271
1271
|
to { opacity: 1; transform: translateX(-50%) translateY(0); }
|
|
1272
1272
|
}
|
|
1273
|
-
`;function eo(){if(typeof document>"u"||document.getElementById("vizu-styles"))return;let n=document.createElement("style");n.id="vizu-styles",n.textContent=bl,(document.head||document.documentElement).appendChild(n)}function to(n){let e=n.toLowerCase().split("+").map(r=>r.trim());return{key:e.pop()||"",mod:e.includes("mod")||e.includes("cmdorctrl"),shift:e.includes("shift"),alt:e.includes("alt")||e.includes("option"),ctrl:e.includes("ctrl")||e.includes("control")}}function no(n,e){let t=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);if(n.key.toLowerCase()!==e.key)return!1;if(e.mod){if(!(t?n.metaKey:n.ctrlKey))return!1}else if(e.ctrl&&!n.ctrlKey)return!1;return!(e.shift!==n.shiftKey||e.alt!==n.altKey)}var ai=class{constructor(){this.listeners=new Map}on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){let r=this.listeners.get(e);if(r)for(let i of[...r])try{i(t)}catch(s){console.error("[vizu] event handler error for",e,s)}}clear(){this.listeners.clear()}};Xn();var Ls={shortcut:"mod+shift+e",namespace:"default",accent:"#FF6647"};function Ah(n,e,t){return e?(n&&typeof console<"u"&&console.warn("[vizu] Both `cloud` and `storage` set; `cloud` wins. Drop `storage` to silence this."),new ni({workspace:e.workspace,apiUrl:e.apiUrl,autoSignIn:e.autoSignIn})):n?n==="local"?new Ar:n==="memory"?new Tr:n==="none"?new ei:Hi(n)?Ws(n):n:t==="local"?new Ar:new Tr}var Vn=class{constructor(e={},t="memory"){this.root=null;this.highlighter=null;this.popover=null;this.pill=null;this.sidebar=null;this.markers=new Map;this.outlines=new Map;this.activeAnchorOutlines=new Map;this.spotlights=new Set;this.comments=[];this.resolvedConfidence=new Map;this.selfHealedThisSession=new Set;this.actions=[];this.user=null;this.liveCollab=null;this.enabled=!1;this.rafScheduled=!1;this.bus=new ai;this.picking=null;this.pickingBanner=null;this.multiSelectMode=!1;this.pendingFingerprints=[];this.pendingTargets=[];this.unsubscribeStorage=null;this.onKeyDown=e=>{if(this.picking&&e.key==="Escape"){e.preventDefault(),this.cancelPicking();return}if(this.pendingFingerprints.length>0&&e.key==="Escape"&&!this.popover?.isOpen()){e.preventDefault(),this.clearSelection();return}no(e,this.parsedShortcut)&&(e.preventDefault(),this.toggle())};this.scheduleReposition=()=>{this.rafScheduled||(this.rafScheduled=!0,requestAnimationFrame(()=>{this.rafScheduled=!1;for(let[,e]of this.outlines)e.target&&this.positionOutline(e.outline,e.target);for(let[,e]of this.markers)e.target&&this.positionMarker(e.marker,e.target);for(let[,e]of this.activeAnchorOutlines){let t=Gn(e.fp);t&&this.positionOutline(e.el,t)}for(let e of this.spotlights)e.target&&this.positionOutline(e.el,e.target);this.popover?.reposition()}))};if(this.opts={...e},this.opts.shortcut=e.shortcut??Ls.shortcut,this.opts.namespace=e.namespace??Ls.namespace,this.opts.accent=e.accent??Ls.accent,this.parsedShortcut=to(this.opts.shortcut),this.storage=Ah(e.storage,e.cloud,t),this.user=e.user??null,e.actions&&(this.actions=[...e.actions]),e.onCommentAdded&&this.bus.on("comment:added",r=>e.onCommentAdded(r.comment)),e.onCommentRemoved&&this.bus.on("comment:removed",r=>e.onCommentRemoved(r.id)),e.liveblocks&&e.cloud){let r=e.liveblocks,i=e.cloud;Promise.resolve().then(()=>(lc(),cc)).then(({LiveCollab:s})=>{this.liveCollab=new s({publicKey:r.publicKey,authEndpoint:r.authEndpoint,workspaceSlug:i.workspace}),this.liveCollab.start()})}typeof window<"u"&&(window.addEventListener("keydown",this.onKeyDown),this.loadComments().then(()=>this.subscribeStorage()),e.startEnabled&&this.deferred(()=>this.enable()))}on(e,t){return this.bus.on(e,t)}off(e,t){this.bus.off(e,t)}setUser(e){this.user=e,this.popover?.setUser(e),this.pill?.setUser(e),this.bus.emit("user:changed",{user:e})}getUser(){return this.user}enable(){this.enabled||(this.enabled=!0,this.bus.emit("enabled",{}),this.deferred(()=>this.mount()))}disable(){this.enabled&&(this.enabled=!1,this.unmount(),this.bus.emit("disabled",{}))}toggle(){this.enabled?this.disable():this.enable()}isEnabled(){return this.enabled}destroy(){this.disable(),typeof window<"u"&&window.removeEventListener("keydown",this.onKeyDown),this.unsubscribeStorage?.(),this.unsubscribeStorage=null,this.selfHealedThisSession.clear(),this.liveCollab?.destroy(),this.liveCollab=null,this.bus.clear()}addAction(e){let t=this.actions.findIndex(r=>r.id===e.id);t>=0?this.actions[t]=e:this.actions.push(e),this.pill?.setActions(this.actions)}removeAction(e){this.actions=this.actions.filter(t=>t.id!==e),this.pill?.setActions(this.actions)}getActions(){return[...this.actions]}invokeAction(e){let t=this.actions.find(i=>i.id===e);if(!t)return;let r=this.actionContext();this.bus.emit("action:invoked",{id:e}),t.onClick(r)}getComments(){return[...this.comments]}async setComments(e,t){this.comments=En(e),t?.persist!==!1&&await this.storage.setAll(this.opts.namespace,this.comments),this.bus.emit("comments:set",{comments:this.getComments()}),this.refreshUi()}async updateComment(e,t){let r=this.comments.findIndex(h=>h.id===e);if(r===-1)return null;let{id:i,schemaVersion:s,...o}=t,c={...this.comments[r],...o};this.comments[r]=c;let u=await this.storage.updateComment(this.opts.namespace,e,o);return this.bus.emit("comment:updated",{comment:u??c}),this.refreshUi(),c}getAuthContext(){return this.storage.getAuthContext?.()??null}async selfHealComment(e,t){this.selfHealedThisSession.add(e.id);let r=[],i=!1;for(let c of e.fingerprints||[]){let u=t.get(de(c));if(u?.target){let h=Jn(u.target);r.push(h),!i&&de(h)!==de(c)&&(i=!0)}else r.push(c)}if(!i)return;let s={fingerprints:r,fingerprintsRefreshedAt:Date.now()},o=this.comments.findIndex(c=>c.id===e.id);o!==-1&&(this.comments[o]={...this.comments[o],...s});try{await this.storage.updateComment(this.opts.namespace,e.id,s)}catch(c){typeof console<"u"&&console.warn("[vizu] self-heal write failed for",e.id,c)}}getCommentConfidence(e){return this.resolvedConfidence.get(e)}getResolvedConfidence(){return new Map(this.resolvedConfidence)}canUploadAttachments(){return typeof this.storage.uploadAttachment=="function"}async uploadAttachment(e){if(!this.storage.uploadAttachment)throw new Error("[vizu] active storage adapter does not support uploadAttachment; only the CloudStorageAdapter does in v1");return this.storage.uploadAttachment(this.opts.namespace,e)}async addReply(e,t,r){let i=this.comments.findIndex(c=>c.id===e);if(i===-1)return null;let s={id:Sr(),text:t.trim(),createdAt:Date.now(),author:this.user??void 0,authorId:this.user?.id,mentions:r&&r.length?r:void 0};if(!s.text)return null;let o={...this.comments[i],replies:[...this.comments[i].replies??[],s]};if(this.comments[i]=o,this.storage.addReply?await this.storage.addReply(this.opts.namespace,e,s):await this.storage.updateComment(this.opts.namespace,e,{replies:o.replies}),this.bus.emit("comment:updated",{comment:o}),this.refreshUi(),this.popover?.isOpen()){let c=this.popover.getAnchors();c[0]&&this.popover.update(this.commentsForElement(c[0]))}return o}async removeReply(e,t){let r=this.comments.findIndex(o=>o.id===e);if(r===-1)return null;let i=(this.comments[r].replies??[]).filter(o=>o.id!==t);if(i.length===(this.comments[r].replies??[]).length)return null;let s={...this.comments[r],replies:i};if(this.comments[r]=s,this.storage.removeReply?await this.storage.removeReply(this.opts.namespace,e,t):await this.storage.updateComment(this.opts.namespace,e,{replies:i}),this.bus.emit("comment:updated",{comment:s}),this.refreshUi(),this.popover?.isOpen()){let o=this.popover.getAnchors();o[0]&&this.popover.update(this.commentsForElement(o[0]))}return s}async clearAll(){let e=this.comments;this.comments=[],await this.storage.clear(this.opts.namespace),this.bus.emit("comments:cleared",{previous:e}),this.refreshUi(),this.popover?.close(),this.clearActiveAnchorOutlines(),this.highlighter?.setPaused(!1)}toggleMultiSelectMode(){this.multiSelectMode=!this.multiSelectMode,this.multiSelectMode||this.clearSelection(),this.pill?.setMultiSelectState(this.multiSelectMode,this.pendingFingerprints.length)}clearSelection(){this.pendingFingerprints=[],this.pendingTargets=[],this.multiSelectMode=!1,this.clearActiveAnchorOutlines(),this.pill?.setMultiSelectState(!1,0)}commitSelection(){if(this.pendingFingerprints.length===0)return;let e=[...this.pendingTargets],t=[...this.pendingFingerprints];this.pendingFingerprints=[],this.pendingTargets=[],this.multiSelectMode=!1,this.pill?.setMultiSelectState(!1,0),(e.find(i=>!!i)??Gn(t[0]))&&this.openPopoverFor(e.filter(Boolean),t)}getSelection(){return[...this.pendingFingerprints]}async loadComments(){let e=await this.storage.load(this.opts.namespace);this.comments=En(e),Js(e)&&this.storage.setAll(this.opts.namespace,this.comments).catch(()=>{}),this.bus.emit("comments:loaded",{comments:this.getComments()}),this.enabled&&this.refreshUi()}subscribeStorage(){this.unsubscribeStorage||this.storage.subscribe&&(this.unsubscribeStorage=this.storage.subscribe(this.opts.namespace,e=>{if(e.type==="added"){let t=bn(e.comment);this.comments.some(r=>r.id===t.id)||(this.comments.push(t),this.bus.emit("comment:added",{comment:t}),this.refreshUi())}else if(e.type==="updated"){let t=this.comments.findIndex(i=>i.id===e.comment.id),r=bn(e.comment);t>=0&&(this.comments[t]=r,this.bus.emit("comment:updated",{comment:r}),this.refreshUi())}else if(e.type==="removed"){let t=this.comments.findIndex(r=>r.id===e.id);if(t>=0){let[r]=this.comments.splice(t,1);this.bus.emit("comment:removed",{id:e.id,comment:r}),this.refreshUi()}}else if(e.type==="cleared"){let t=this.comments;this.comments=[],this.bus.emit("comments:cleared",{previous:t}),this.refreshUi()}}))}deferred(e){typeof document>"u"||(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e())}mount(){this.root||(eo(),this.root=document.createElement("div"),this.root.setAttribute("data-vizu-root",""),this.root.style.setProperty("--vz-accent",this.opts.accent),document.body.appendChild(this.root),this.popover=new ii(this.root,{onAdd:(e,t,r,i,s)=>{this.addCommentFromPopover(e,t,r,i,s)},onUploadAttachment:e=>this.uploadAttachment(e),canUploadAttachments:()=>this.canUploadAttachments(),onDelete:e=>{this.removeComment(e)},onAddReply:(e,t)=>{this.addReply(e,t)},onDeleteReply:(e,t)=>{this.removeReply(e,t)},onClose:()=>this.closePopover(),onStartReferencePick:(e,t)=>this.startPicking(e,t),onJumpToReference:(e,t)=>this.jumpToReference(e,t),onAnchorsChanged:e=>this.syncActiveAnchorOutlines(e)}),this.popover.setUser(this.user),this.sidebar=new oi(this.root,{onJumpTo:e=>this.jumpToFingerprint(e),onJumpToReference:(e,t)=>this.jumpToReference(e,t),onDelete:e=>{this.removeComment(e)},onUpdateStatus:(e,t)=>{this.updateComment(e,{status:t})},onClose:()=>this.closeSidebar()}),this.pill=new si(this.root,{onToggleSidebar:()=>this.toggleSidebar(),onDisable:()=>this.disable(),onAction:e=>this.invokeAction(e),onToggleMultiSelect:()=>this.toggleMultiSelectMode(),onCommitSelection:()=>this.commitSelection(),onClearSelection:()=>this.clearSelection()}),this.pill.setActions(this.actions),this.pill.setUser(this.user),this.pill.setComments(this.comments),this.pill.setMultiSelectState(this.multiSelectMode,this.pendingFingerprints.length),this.pill.show(),this.highlighter=new ri(this.root,this.opts.ignoreSelectors??[],(e,t)=>this.onElementClick(e,t),e=>{this.liveCollab&&this.liveCollab.setLocalSelection(e?Jn(e):null)}),this.highlighter.start(),this.renderAllMarkers(),window.addEventListener("scroll",this.scheduleReposition,!0),window.addEventListener("resize",this.scheduleReposition),this.bus.emit("mounted",{}))}unmount(){window.removeEventListener("scroll",this.scheduleReposition,!0),window.removeEventListener("resize",this.scheduleReposition),this.highlighter?.destroy(),this.popover?.destroy(),this.pill?.destroy(),this.sidebar?.destroy(),this.root?.remove(),this.root=null,this.highlighter=null,this.popover=null,this.pill=null,this.sidebar=null,this.markers.clear(),this.outlines.clear(),this.activeAnchorOutlines.clear();for(let e of this.spotlights)e.el.remove();this.spotlights.clear(),this.pendingFingerprints=[],this.pendingTargets=[],this.bus.emit("unmounted",{})}onElementClick(e,t){if(this.picking){let s=Jn(e),o=this.picking;this.picking=null,this.hidePickingBanner(),this.highlighter?.setPaused(this.popover?.isOpen()??!1),o.onSelect(s);return}let r=Jn(e);if(this.popover?.isOpen()&&t.shiftKey){this.popover.addAnchor(r,e);return}if(!this.popover?.isOpen()&&(this.multiSelectMode||t.shiftKey)){this.addToSelection(r,e);return}this.bus.emit("element:selected",{target:e,fingerprint:r});let i=this.commentsForElement(r);this.openPopoverFor([e],[r],i)}openPopoverFor(e,t,r){if(!this.popover)return;let i=r??this.commentsForElement(t[0]);this.popover.open(e,t,i),this.syncActiveAnchorOutlines(t),this.highlighter?.setPaused(!0)}closePopover(){this.popover?.close(),this.clearActiveAnchorOutlines(),this.highlighter?.setPaused(!1),this.bus.emit("element:deselected",{})}addToSelection(e,t){let r=de(e);this.pendingFingerprints.some(i=>de(i)===r)?(this.pendingFingerprints=this.pendingFingerprints.filter(i=>de(i)!==r),this.pendingTargets=this.pendingTargets.filter(i=>i!==t)):(this.pendingFingerprints.push(e),this.pendingTargets.push(t)),this.syncActiveAnchorOutlines(this.pendingFingerprints),this.pill?.setMultiSelectState(!0,this.pendingFingerprints.length),this.pendingFingerprints.length>0?this.multiSelectMode=!0:this.multiSelectMode=!1}commentsForElement(e){let t=de(e);return this.comments.filter(r=>(r.fingerprints||[]).some(i=>de(i)===t))}async addCommentFromPopover(e,t,r,i,s){if(t.length===0)return;let o=typeof location<"u"?location.href:void 0,c={id:Sr(),schemaVersion:2,fingerprints:t,text:e,createdAt:Date.now(),pageVersion:this.opts.pageVersion,pageUrl:o,author:this.user??void 0,authorId:this.user?.id,references:r&&Object.keys(r).length?r:void 0,status:"open",replies:[],attachments:s??[],mentions:i??[]};this.comments.push(c),await this.storage.addComment(this.opts.namespace,c),this.bus.emit("comment:added",{comment:c}),this.popover?.update(this.commentsForElement(t[0])),this.refreshUi()}async removeComment(e){let t=this.comments.find(r=>r.id===e);if(t){if(this.comments=this.comments.filter(r=>r.id!==e),await this.storage.removeComment(this.opts.namespace,e),this.bus.emit("comment:removed",{id:e,comment:t}),this.popover?.isOpen()){let r=this.popover.getAnchors();r[0]&&this.popover.update(this.commentsForElement(r[0]))}this.refreshUi()}}refreshUi(){this.pill?.setComments(this.comments),this.renderAllMarkers(),this.sidebar?.update(this.comments,this.resolvedConfidence)}toggleSidebar(){if(!this.sidebar)return;this.sidebar.isOpen()||this.renderAllMarkers(),this.sidebar.toggle(this.comments,this.resolvedConfidence);let e=this.sidebar.isOpen();this.pill?.setSidebarOpen(e),this.bus.emit(e?"sidebar:opened":"sidebar:closed",{})}closeSidebar(){this.sidebar?.close(),this.pill?.setSidebarOpen(!1),this.bus.emit("sidebar:closed",{})}startPicking(e,t){this.picking&&this.picking.onCancel(),this.picking={onSelect:e,onCancel:t},this.highlighter?.setPaused(!1),this.showPickingBanner()}cancelPicking(){if(!this.picking)return;let e=this.picking;this.picking=null,this.hidePickingBanner(),this.highlighter?.setPaused(this.popover?.isOpen()??!1),e.onCancel()}showPickingBanner(){this.root&&(this.pickingBanner=document.createElement("div"),this.pickingBanner.className="vz-picking-banner",this.pickingBanner.innerHTML=`
|
|
1273
|
+
`;function eo(){if(typeof document>"u"||document.getElementById("vizu-styles"))return;let n=document.createElement("style");n.id="vizu-styles",n.textContent=bl,(document.head||document.documentElement).appendChild(n)}function to(n){let e=n.toLowerCase().split("+").map(r=>r.trim());return{key:e.pop()||"",mod:e.includes("mod")||e.includes("cmdorctrl"),shift:e.includes("shift"),alt:e.includes("alt")||e.includes("option"),ctrl:e.includes("ctrl")||e.includes("control")}}function no(n,e){let t=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);if(n.key.toLowerCase()!==e.key)return!1;if(e.mod){if(!(t?n.metaKey:n.ctrlKey))return!1}else if(e.ctrl&&!n.ctrlKey)return!1;return!(e.shift!==n.shiftKey||e.alt!==n.altKey)}var ai=class{constructor(){this.listeners=new Map}on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){let r=this.listeners.get(e);if(r)for(let i of[...r])try{i(t)}catch(s){console.error("[vizu] event handler error for",e,s)}}clear(){this.listeners.clear()}};Xn();var Ls={shortcut:"mod+shift+e",namespace:"default",accent:"#FF6647"};function Ah(n,e,t,r){return e?(n&&typeof console<"u"&&console.warn("[vizu] Both `cloud` and `storage` set; `cloud` wins. Drop `storage` to silence this."),new kr({workspace:e.workspace,apiUrl:e.apiUrl,autoSignIn:e.autoSignIn,onAuthChanged:r})):n?n==="local"?new Ar:n==="memory"?new Tr:n==="none"?new ti:Hi(n)?Ws(n):n:t==="local"?new Ar:new Tr}var Vn=class{constructor(e={},t="memory"){this.root=null;this.highlighter=null;this.popover=null;this.pill=null;this.sidebar=null;this.markers=new Map;this.outlines=new Map;this.activeAnchorOutlines=new Map;this.spotlights=new Set;this.comments=[];this.resolvedConfidence=new Map;this.selfHealedThisSession=new Set;this.actions=[];this.user=null;this.liveCollab=null;this.enabled=!1;this.rafScheduled=!1;this.bus=new ai;this.picking=null;this.pickingBanner=null;this.multiSelectMode=!1;this.pendingFingerprints=[];this.pendingTargets=[];this.unsubscribeStorage=null;this.onKeyDown=e=>{if(this.picking&&e.key==="Escape"){e.preventDefault(),this.cancelPicking();return}if(this.pendingFingerprints.length>0&&e.key==="Escape"&&!this.popover?.isOpen()){e.preventDefault(),this.clearSelection();return}no(e,this.parsedShortcut)&&(e.preventDefault(),this.toggle())};this.scheduleReposition=()=>{this.rafScheduled||(this.rafScheduled=!0,requestAnimationFrame(()=>{this.rafScheduled=!1;for(let[,e]of this.outlines)e.target&&this.positionOutline(e.outline,e.target);for(let[,e]of this.markers)e.target&&this.positionMarker(e.marker,e.target);for(let[,e]of this.activeAnchorOutlines){let t=Gn(e.fp);t&&this.positionOutline(e.el,t)}for(let e of this.spotlights)e.target&&this.positionOutline(e.el,e.target);this.popover?.reposition()}))};if(this.opts={...e},this.opts.shortcut=e.shortcut??Ls.shortcut,this.opts.namespace=e.namespace??Ls.namespace,this.opts.accent=e.accent??Ls.accent,this.parsedShortcut=to(this.opts.shortcut),this.storage=Ah(e.storage,e.cloud,t,r=>{r.user&&this.setUser(r.user)}),this.user=e.user??null,e.actions&&(this.actions=[...e.actions]),e.onCommentAdded&&this.bus.on("comment:added",r=>e.onCommentAdded(r.comment)),e.onCommentRemoved&&this.bus.on("comment:removed",r=>e.onCommentRemoved(r.id)),e.liveblocks&&e.cloud){let r=e.liveblocks,i=e.cloud;Promise.resolve().then(()=>(lc(),cc)).then(({LiveCollab:s})=>{this.liveCollab=new s({publicKey:r.publicKey,authEndpoint:r.authEndpoint,workspaceSlug:i.workspace}),this.liveCollab.start()})}typeof window<"u"&&(window.addEventListener("keydown",this.onKeyDown),this.loadComments().then(()=>this.subscribeStorage()),e.startEnabled&&this.deferred(()=>this.enable()))}on(e,t){return this.bus.on(e,t)}off(e,t){this.bus.off(e,t)}setUser(e){this.user=e,this.popover?.setUser(e),this.pill?.setUser(e),this.bus.emit("user:changed",{user:e})}getUser(){return this.user}enable(){this.enabled||(this.enabled=!0,this.bus.emit("enabled",{}),this.deferred(()=>this.mount()),this.storage instanceof kr&&this.storage.preflightAuth().catch(e=>{e?.code==="auth_canceled"||e?.code==="popup_blocked"||typeof console<"u"&&console.warn("[vizu] preflight auth failed:",e)}))}disable(){this.enabled&&(this.enabled=!1,this.unmount(),this.bus.emit("disabled",{}))}toggle(){this.enabled?this.disable():this.enable()}isEnabled(){return this.enabled}destroy(){this.disable(),typeof window<"u"&&window.removeEventListener("keydown",this.onKeyDown),this.unsubscribeStorage?.(),this.unsubscribeStorage=null,this.selfHealedThisSession.clear(),this.liveCollab?.destroy(),this.liveCollab=null,this.bus.clear()}addAction(e){let t=this.actions.findIndex(r=>r.id===e.id);t>=0?this.actions[t]=e:this.actions.push(e),this.pill?.setActions(this.actions)}removeAction(e){this.actions=this.actions.filter(t=>t.id!==e),this.pill?.setActions(this.actions)}getActions(){return[...this.actions]}invokeAction(e){let t=this.actions.find(i=>i.id===e);if(!t)return;let r=this.actionContext();this.bus.emit("action:invoked",{id:e}),t.onClick(r)}getComments(){return[...this.comments]}async setComments(e,t){this.comments=En(e),t?.persist!==!1&&await this.storage.setAll(this.opts.namespace,this.comments),this.bus.emit("comments:set",{comments:this.getComments()}),this.refreshUi()}async updateComment(e,t){let r=this.comments.findIndex(h=>h.id===e);if(r===-1)return null;let{id:i,schemaVersion:s,...o}=t,c={...this.comments[r],...o};this.comments[r]=c;let u=await this.storage.updateComment(this.opts.namespace,e,o);return this.bus.emit("comment:updated",{comment:u??c}),this.refreshUi(),c}getAuthContext(){return this.storage.getAuthContext?.()??null}async selfHealComment(e,t){this.selfHealedThisSession.add(e.id);let r=[],i=!1;for(let c of e.fingerprints||[]){let u=t.get(de(c));if(u?.target){let h=Jn(u.target);r.push(h),!i&&de(h)!==de(c)&&(i=!0)}else r.push(c)}if(!i)return;let s={fingerprints:r,fingerprintsRefreshedAt:Date.now()},o=this.comments.findIndex(c=>c.id===e.id);o!==-1&&(this.comments[o]={...this.comments[o],...s});try{await this.storage.updateComment(this.opts.namespace,e.id,s)}catch(c){typeof console<"u"&&console.warn("[vizu] self-heal write failed for",e.id,c)}}getCommentConfidence(e){return this.resolvedConfidence.get(e)}getResolvedConfidence(){return new Map(this.resolvedConfidence)}canUploadAttachments(){return typeof this.storage.uploadAttachment=="function"}async uploadAttachment(e){if(!this.storage.uploadAttachment)throw new Error("[vizu] active storage adapter does not support uploadAttachment; only the CloudStorageAdapter does in v1");return this.storage.uploadAttachment(this.opts.namespace,e)}async addReply(e,t,r){let i=this.comments.findIndex(c=>c.id===e);if(i===-1)return null;let s={id:Sr(),text:t.trim(),createdAt:Date.now(),author:this.user??void 0,authorId:this.user?.id,mentions:r&&r.length?r:void 0};if(!s.text)return null;let o={...this.comments[i],replies:[...this.comments[i].replies??[],s]};if(this.comments[i]=o,this.storage.addReply?await this.storage.addReply(this.opts.namespace,e,s):await this.storage.updateComment(this.opts.namespace,e,{replies:o.replies}),this.bus.emit("comment:updated",{comment:o}),this.refreshUi(),this.popover?.isOpen()){let c=this.popover.getAnchors();c[0]&&this.popover.update(this.commentsForElement(c[0]))}return o}async removeReply(e,t){let r=this.comments.findIndex(o=>o.id===e);if(r===-1)return null;let i=(this.comments[r].replies??[]).filter(o=>o.id!==t);if(i.length===(this.comments[r].replies??[]).length)return null;let s={...this.comments[r],replies:i};if(this.comments[r]=s,this.storage.removeReply?await this.storage.removeReply(this.opts.namespace,e,t):await this.storage.updateComment(this.opts.namespace,e,{replies:i}),this.bus.emit("comment:updated",{comment:s}),this.refreshUi(),this.popover?.isOpen()){let o=this.popover.getAnchors();o[0]&&this.popover.update(this.commentsForElement(o[0]))}return s}async clearAll(){let e=this.comments;this.comments=[],await this.storage.clear(this.opts.namespace),this.bus.emit("comments:cleared",{previous:e}),this.refreshUi(),this.popover?.close(),this.clearActiveAnchorOutlines(),this.highlighter?.setPaused(!1)}toggleMultiSelectMode(){this.multiSelectMode=!this.multiSelectMode,this.multiSelectMode||this.clearSelection(),this.pill?.setMultiSelectState(this.multiSelectMode,this.pendingFingerprints.length)}clearSelection(){this.pendingFingerprints=[],this.pendingTargets=[],this.multiSelectMode=!1,this.clearActiveAnchorOutlines(),this.pill?.setMultiSelectState(!1,0)}commitSelection(){if(this.pendingFingerprints.length===0)return;let e=[...this.pendingTargets],t=[...this.pendingFingerprints];this.pendingFingerprints=[],this.pendingTargets=[],this.multiSelectMode=!1,this.pill?.setMultiSelectState(!1,0),(e.find(i=>!!i)??Gn(t[0]))&&this.openPopoverFor(e.filter(Boolean),t)}getSelection(){return[...this.pendingFingerprints]}async loadComments(){let e=await this.storage.load(this.opts.namespace);this.comments=En(e),Js(e)&&this.storage.setAll(this.opts.namespace,this.comments).catch(()=>{}),this.bus.emit("comments:loaded",{comments:this.getComments()}),this.enabled&&this.refreshUi()}subscribeStorage(){this.unsubscribeStorage||this.storage.subscribe&&(this.unsubscribeStorage=this.storage.subscribe(this.opts.namespace,e=>{if(e.type==="added"){let t=bn(e.comment);this.comments.some(r=>r.id===t.id)||(this.comments.push(t),this.bus.emit("comment:added",{comment:t}),this.refreshUi())}else if(e.type==="updated"){let t=this.comments.findIndex(i=>i.id===e.comment.id),r=bn(e.comment);t>=0&&(this.comments[t]=r,this.bus.emit("comment:updated",{comment:r}),this.refreshUi())}else if(e.type==="removed"){let t=this.comments.findIndex(r=>r.id===e.id);if(t>=0){let[r]=this.comments.splice(t,1);this.bus.emit("comment:removed",{id:e.id,comment:r}),this.refreshUi()}}else if(e.type==="cleared"){let t=this.comments;this.comments=[],this.bus.emit("comments:cleared",{previous:t}),this.refreshUi()}}))}deferred(e){typeof document>"u"||(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e())}mount(){this.root||(eo(),this.root=document.createElement("div"),this.root.setAttribute("data-vizu-root",""),this.root.style.setProperty("--vz-accent",this.opts.accent),document.body.appendChild(this.root),this.popover=new ii(this.root,{onAdd:(e,t,r,i,s)=>{this.addCommentFromPopover(e,t,r,i,s)},onUploadAttachment:e=>this.uploadAttachment(e),canUploadAttachments:()=>this.canUploadAttachments(),onDelete:e=>{this.removeComment(e)},onAddReply:(e,t)=>{this.addReply(e,t)},onDeleteReply:(e,t)=>{this.removeReply(e,t)},onClose:()=>this.closePopover(),onStartReferencePick:(e,t)=>this.startPicking(e,t),onJumpToReference:(e,t)=>this.jumpToReference(e,t),onAnchorsChanged:e=>this.syncActiveAnchorOutlines(e)}),this.popover.setUser(this.user),this.sidebar=new oi(this.root,{onJumpTo:e=>this.jumpToFingerprint(e),onJumpToReference:(e,t)=>this.jumpToReference(e,t),onDelete:e=>{this.removeComment(e)},onUpdateStatus:(e,t)=>{this.updateComment(e,{status:t})},onClose:()=>this.closeSidebar()}),this.pill=new si(this.root,{onToggleSidebar:()=>this.toggleSidebar(),onDisable:()=>this.disable(),onAction:e=>this.invokeAction(e),onToggleMultiSelect:()=>this.toggleMultiSelectMode(),onCommitSelection:()=>this.commitSelection(),onClearSelection:()=>this.clearSelection()}),this.pill.setActions(this.actions),this.pill.setUser(this.user),this.pill.setComments(this.comments),this.pill.setMultiSelectState(this.multiSelectMode,this.pendingFingerprints.length),this.pill.show(),this.highlighter=new ri(this.root,this.opts.ignoreSelectors??[],(e,t)=>this.onElementClick(e,t),e=>{this.liveCollab&&this.liveCollab.setLocalSelection(e?Jn(e):null)}),this.highlighter.start(),this.renderAllMarkers(),window.addEventListener("scroll",this.scheduleReposition,!0),window.addEventListener("resize",this.scheduleReposition),this.bus.emit("mounted",{}))}unmount(){window.removeEventListener("scroll",this.scheduleReposition,!0),window.removeEventListener("resize",this.scheduleReposition),this.highlighter?.destroy(),this.popover?.destroy(),this.pill?.destroy(),this.sidebar?.destroy(),this.root?.remove(),this.root=null,this.highlighter=null,this.popover=null,this.pill=null,this.sidebar=null,this.markers.clear(),this.outlines.clear(),this.activeAnchorOutlines.clear();for(let e of this.spotlights)e.el.remove();this.spotlights.clear(),this.pendingFingerprints=[],this.pendingTargets=[],this.bus.emit("unmounted",{})}onElementClick(e,t){if(this.picking){let s=Jn(e),o=this.picking;this.picking=null,this.hidePickingBanner(),this.highlighter?.setPaused(this.popover?.isOpen()??!1),o.onSelect(s);return}let r=Jn(e);if(this.popover?.isOpen()&&t.shiftKey){this.popover.addAnchor(r,e);return}if(!this.popover?.isOpen()&&(this.multiSelectMode||t.shiftKey)){this.addToSelection(r,e);return}this.bus.emit("element:selected",{target:e,fingerprint:r});let i=this.commentsForElement(r);this.openPopoverFor([e],[r],i)}openPopoverFor(e,t,r){if(!this.popover)return;let i=r??this.commentsForElement(t[0]);this.popover.open(e,t,i),this.syncActiveAnchorOutlines(t),this.highlighter?.setPaused(!0)}closePopover(){this.popover?.close(),this.clearActiveAnchorOutlines(),this.highlighter?.setPaused(!1),this.bus.emit("element:deselected",{})}addToSelection(e,t){let r=de(e);this.pendingFingerprints.some(i=>de(i)===r)?(this.pendingFingerprints=this.pendingFingerprints.filter(i=>de(i)!==r),this.pendingTargets=this.pendingTargets.filter(i=>i!==t)):(this.pendingFingerprints.push(e),this.pendingTargets.push(t)),this.syncActiveAnchorOutlines(this.pendingFingerprints),this.pill?.setMultiSelectState(!0,this.pendingFingerprints.length),this.pendingFingerprints.length>0?this.multiSelectMode=!0:this.multiSelectMode=!1}commentsForElement(e){let t=de(e);return this.comments.filter(r=>(r.fingerprints||[]).some(i=>de(i)===t))}async addCommentFromPopover(e,t,r,i,s){if(t.length===0)return;let o=typeof location<"u"?location.href:void 0,c={id:Sr(),schemaVersion:2,fingerprints:t,text:e,createdAt:Date.now(),pageVersion:this.opts.pageVersion,pageUrl:o,author:this.user??void 0,authorId:this.user?.id,references:r&&Object.keys(r).length?r:void 0,status:"open",replies:[],attachments:s??[],mentions:i??[]};this.comments.push(c),await this.storage.addComment(this.opts.namespace,c),this.bus.emit("comment:added",{comment:c}),this.popover?.update(this.commentsForElement(t[0])),this.refreshUi()}async removeComment(e){let t=this.comments.find(r=>r.id===e);if(t){if(this.comments=this.comments.filter(r=>r.id!==e),await this.storage.removeComment(this.opts.namespace,e),this.bus.emit("comment:removed",{id:e,comment:t}),this.popover?.isOpen()){let r=this.popover.getAnchors();r[0]&&this.popover.update(this.commentsForElement(r[0]))}this.refreshUi()}}refreshUi(){this.pill?.setComments(this.comments),this.renderAllMarkers(),this.sidebar?.update(this.comments,this.resolvedConfidence)}toggleSidebar(){if(!this.sidebar)return;this.sidebar.isOpen()||this.renderAllMarkers(),this.sidebar.toggle(this.comments,this.resolvedConfidence);let e=this.sidebar.isOpen();this.pill?.setSidebarOpen(e),this.bus.emit(e?"sidebar:opened":"sidebar:closed",{})}closeSidebar(){this.sidebar?.close(),this.pill?.setSidebarOpen(!1),this.bus.emit("sidebar:closed",{})}startPicking(e,t){this.picking&&this.picking.onCancel(),this.picking={onSelect:e,onCancel:t},this.highlighter?.setPaused(!1),this.showPickingBanner()}cancelPicking(){if(!this.picking)return;let e=this.picking;this.picking=null,this.hidePickingBanner(),this.highlighter?.setPaused(this.popover?.isOpen()??!1),e.onCancel()}showPickingBanner(){this.root&&(this.pickingBanner=document.createElement("div"),this.pickingBanner.className="vz-picking-banner",this.pickingBanner.innerHTML=`
|
|
1274
1274
|
<span>Click any element to reference</span>
|
|
1275
1275
|
<span class="vz-picking-banner-hint">or press <span class="vz-picking-banner-kbd">Esc</span></span>
|
|
1276
1276
|
<button class="vz-picking-banner-cancel" data-vz="cancel-pick">Cancel</button>
|