@vite-hub/realtime 0.5.0 → 0.5.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.
Files changed (43) hide show
  1. package/README.md +2 -2
  2. package/dist/agent.d.ts +1 -1
  3. package/dist/agent.js +1 -2
  4. package/dist/{bus-Bsdanf5O.js → bus-DJ3dOQAZ.js} +4 -6
  5. package/dist/{bus-protocol-wXkXW28q.d.ts → bus-protocol-juNrVJDF.d.ts} +0 -2
  6. package/dist/bus.d.ts +1 -3
  7. package/dist/bus.js +1 -2
  8. package/dist/client/browser.js +3 -3
  9. package/dist/client.d.ts +2 -4
  10. package/dist/client.js +5 -6
  11. package/dist/{conflict-DYC_qXzM.js → conflict-BqdKFrkE.js} +3 -5
  12. package/dist/{conflict-CmZizTYl.d.ts → conflict-C5KRv-J1.d.ts} +0 -2
  13. package/dist/{document-b1ShR2S1.d.ts → document-CbqgNO_0.d.ts} +2 -4
  14. package/dist/document-CfrQbB03.js +1736 -0
  15. package/dist/durability.d.ts +1 -3
  16. package/dist/durability.js +1 -2
  17. package/dist/{editor-IL2jHqn8.js → editor-DzhKM4Gt.js} +2 -4
  18. package/dist/{error-diagnostics-Cd-XWNf7.js → error-diagnostics-we8V1O-X.js} +1 -2
  19. package/dist/index.d.ts +3 -7
  20. package/dist/index.js +3 -3
  21. package/dist/internal/runtime/unavailable.d.ts +1 -3
  22. package/dist/internal/runtime/unavailable.js +1 -2
  23. package/dist/internal/server.d.ts +6 -6
  24. package/dist/internal/server.js +5 -5
  25. package/dist/{keepalive-B4ONG6AD.js → keepalive-BYkk6Ax8.js} +3 -5
  26. package/dist/{layout-DNaxppTZ.js → layout-BQwRLTH0.js} +1 -2
  27. package/dist/{layout-VHjYWa-M.d.ts → layout-BZtKNqiC.d.ts} +1 -3
  28. package/dist/{log-E-cH6xkd.js → log-NlQi6kow.js} +2 -4
  29. package/dist/{object-BgPPDLDE.js → object-DfrneieE.js} +2 -4
  30. package/dist/{presence-B6rvkHqd.js → presence-DZ21pPKm.js} +3 -4
  31. package/dist/{request-kM5epeSd.js → request-DM6xHTaU.js} +5 -9
  32. package/dist/{request-DAodIqZ8.d.ts → request-PrMHOYFK.d.ts} +1 -3
  33. package/dist/{server-Covbc24E.d.ts → server-CLdYV7Md.d.ts} +6 -20
  34. package/dist/{server-BSXJP45b.js → server-yQp02XNp.js} +17 -24
  35. package/dist/server.d.ts +3 -3
  36. package/dist/server.js +2 -2
  37. package/dist/{types-DdY7Vo1H.d.ts → types-oUyN-CJR.d.ts} +1 -5
  38. package/dist/vite.d.ts +2 -15
  39. package/dist/vite.js +20 -27
  40. package/dist/vue.d.ts +2 -6
  41. package/dist/vue.js +47 -26
  42. package/package.json +39 -39
  43. package/dist/document-U5rzg2vG.js +0 -2041
package/README.md CHANGED
@@ -14,7 +14,7 @@ Realtime is for collaborative documents, presence, explicit Workspace checkpoint
14
14
  ## Install
15
15
 
16
16
  ```sh
17
- pnpm add @vite-hub/realtime @vite-hub/workspace @tiptap/vue-3 drizzle-orm@1.0.0-rc.5 h3 nitro vite vue
17
+ pnpm add @vite-hub/realtime @vite-hub/workspace @tiptap/vue-3 drizzle-orm@1.0.0-rc.6 h3 nitro vite vue
18
18
  ```
19
19
 
20
20
  ViteHub Realtime requires Node.js 24.15 or newer. The published client adapter is for Vue. The package declares `vite` and `vue` as optional peers so server-only integrations do not install unused framework tooling; this walkthrough uses both. It also declares `drizzle-orm` as a peer: Realtime depends on Auth, and Auth uses the app's copy of Drizzle.
@@ -167,7 +167,7 @@ const [error, answer] = await requestRealtimeRoom("tabs", tabId, { want: "title"
167
167
  - The Vue adapter connects to the generated same-origin `/_vitehub/realtime/**` WebSocket route. The Vite integration registers that route and discovers `server/realtime` definitions. In a component it prepares the editor extensions during setup and connects when the component mounts, so the server render and the first browser render both have `status` `disconnected`.
168
168
  - `driver: "memory"` is single-process and loses room state when the process stops. ViteHub rejects it for known distributed hosts. It retains at most 128 active rooms.
169
169
  - `driver: "cloudflare"` uses a SQLite-backed Cloudflare Durable Object. `driver: "auto"` selects it when a Cloudflare host or hosting environment can be resolved.
170
- - On a Node build, `driver: "auto"` picks when the server starts: `redis` with `REDIS_URL`, else `postgres` with `REALTIME_POSTGRES_URL` or the postgres.js client of a Postgres Default Database (`DATABASE_URL` is not read), else `memory`. A borrowed Database client is never closed. It prints the choice at boot. With `redis` or `postgres`, each instance holds its rooms in memory and shares Yjs updates and awareness with the other instances through Redis pub/sub or Postgres `LISTEN`/`NOTIFY`. The instances start each room from one shared record (`vitehub_realtime_rooms` on Postgres), and saves of one room run one at a time under a lock, so `ifDigest` stays correct across instances. `NOTIFY` payloads over 8,000 bytes go through the `vitehub_realtime_messages` table. Each app has its own namespace on the bus (`realtime.namespace`, else the app name; `REALTIME_NAMESPACE` replaces it at runtime), so two apps on one Redis or Postgres never share a room. Presence of a stopped instance leaves at once, and that of a crashed instance after the 30 second Yjs awareness timeout. Other production builds fail with `REALTIME_MISSING_DRIVER`.
170
+ - On a Node build, `driver: "auto"` picks when the server starts: `redis` with `REDIS_URL`, else `postgres` with `REALTIME_POSTGRES_URL` or the postgres.js client of a Postgres Default Database (`DATABASE_URL` is not read), else `memory`. A borrowed Database client is never closed. It prints the choice at boot. With `redis` or `postgres`, each instance holds its rooms in memory and shares Yjs updates and awareness with the other instances through Redis pub/sub (Redis 6 or later) or Postgres `LISTEN`/`NOTIFY`. The instances start each room from one shared record (`vitehub_realtime_rooms` on Postgres), and saves of one room run one at a time under a lock, so `ifDigest` stays correct across instances. `NOTIFY` payloads over 8,000 bytes go through the `vitehub_realtime_messages` table. Each app has its own namespace on the bus (`realtime.namespace`, else the app name; `REALTIME_NAMESPACE` replaces it at runtime), so two apps on one Redis or Postgres never share a room. Presence of a stopped instance leaves at once, and that of a crashed instance after the 30 second Yjs awareness timeout. Other production builds fail with `REALTIME_MISSING_DRIVER`.
171
171
  - Durable rooms do not make Workspace files durable. Production checkpoints need a durable Workspace Store with conditional writes; memory Workspace Stores are rejected for durable checkpoints.
172
172
  - Each Realtime Definition must set `authorize: true`, `authorize()`, or `access: "public"`. Otherwise the server rejects it with `REALTIME_MISSING_ACCESS`. `authorize()` allows only when it returns `true`; `undefined` and `false` deny. It also runs for signed-out callers, with `user: null`. `authorize: true` needs ViteHub Auth or `identify()`; it verifies the user and replaces client-supplied presence identity. `access: "public"` lets each person read and write each Realtime. Presence in a public definition is untrusted and must not authorize application actions.
173
173
  - Requests with an `Origin` other than the app's get 403 on each definition, unless `origins()` accepts the origin.
package/dist/agent.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as agentRealtime, t as AgentRealtime } from "./request-DAodIqZ8.js";
1
+ import { a as agentRealtime, t as AgentRealtime } from "./request-PrMHOYFK.js";
2
2
  export { type AgentRealtime, agentRealtime };
package/dist/agent.js CHANGED
@@ -1,2 +1 @@
1
- import { t as agentRealtime } from "./request-kM5epeSd.js";
2
- export { agentRealtime };
1
+ export { t as agentRealtime } from "./request-DM6xHTaU.js";
@@ -1,9 +1,9 @@
1
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cd-XWNf7.js";
2
- import { n as realtimeRoomFields, t as logRealtime } from "./log-E-cH6xkd.js";
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-we8V1O-X.js";
2
+ import { n as realtimeRoomFields, t as logRealtime } from "./log-NlQi6kow.js";
3
3
  import { createHash } from "node:crypto";
4
4
  import * as decoding from "lib0/decoding";
5
5
  import * as encoding from "lib0/encoding";
6
- //#region src/bus-protocol.ts
6
+ // src/bus-protocol.ts
7
7
  /**
8
8
  * What one instance tells the other instances about a room:
9
9
  * - `update`: a Yjs update of the room document.
@@ -53,8 +53,7 @@ function decodeRealtimeBusMessage(bytes) {
53
53
  return;
54
54
  }
55
55
  }
56
- //#endregion
57
- //#region src/bus.ts
56
+ // src/bus.ts
58
57
  /** The variable that points the Postgres bus at its own database, instead of the connection of the Default Database. */
59
58
  const realtimePostgresUrlVariable = "REALTIME_POSTGRES_URL";
60
59
  /** The variable that replaces the namespace of the build, such as to keep staging and production apart on one Redis. */
@@ -463,5 +462,4 @@ async function createRedisRealtimeBus(url, options = {}) {
463
462
  })
464
463
  };
465
464
  }
466
- //#endregion
467
465
  export { logRealtimeNodeDriver as a, resolveRealtimeNamespace as c, createRedisRealtimeBus as i, resolveRealtimeNodeDriver as l, createPostgresRealtimeBus as n, realtimeNamespaceVariable as o, createRealtimeNodeBus as r, realtimePostgresUrlVariable as s, closeRealtimeBuses as t, useRealtimeBus as u };
@@ -1,4 +1,3 @@
1
- //#region src/bus-protocol.d.ts
2
1
  /**
3
2
  * What one instance tells the other instances about a room:
4
3
  * - `update`: a Yjs update of the room document.
@@ -62,5 +61,4 @@ interface RealtimeBus {
62
61
  onClose(hook: () => Promise<void>): void;
63
62
  close(): Promise<void>;
64
63
  }
65
- //#endregion
66
64
  export { RealtimeBusMessage as n, RealtimeRoomRecord as r, RealtimeBus as t };
package/dist/bus.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { n as RealtimeBusMessage, r as RealtimeRoomRecord, t as RealtimeBus } from "./bus-protocol-wXkXW28q.js";
2
- //#region src/bus.d.ts
1
+ import { n as RealtimeBusMessage, r as RealtimeRoomRecord, t as RealtimeBus } from "./bus-protocol-juNrVJDF.js";
3
2
  /** The driver that a Node build asks for: `auto` reads the environment when the server starts. */
4
3
  export type RealtimeNodeDriver = "auto" | "postgres" | "redis";
5
4
  /** The variable that points the Postgres bus at its own database, instead of the connection of the Default Database. */
@@ -81,5 +80,4 @@ export declare function createPostgresRealtimeBus(connection: ({
81
80
  export declare function createRedisRealtimeBus(url: string, options?: {
82
81
  namespace?: string;
83
82
  }): Promise<RealtimeBus>;
84
- //#endregion
85
83
  export type { RealtimeBus, RealtimeBusMessage, RealtimeRoomRecord };
package/dist/bus.js CHANGED
@@ -1,2 +1 @@
1
- import { a as logRealtimeNodeDriver, c as resolveRealtimeNamespace, i as createRedisRealtimeBus, l as resolveRealtimeNodeDriver, n as createPostgresRealtimeBus, o as realtimeNamespaceVariable, r as createRealtimeNodeBus, s as realtimePostgresUrlVariable, t as closeRealtimeBuses, u as useRealtimeBus } from "./bus-Bsdanf5O.js";
2
- export { closeRealtimeBuses, createPostgresRealtimeBus, createRealtimeNodeBus, createRedisRealtimeBus, logRealtimeNodeDriver, realtimeNamespaceVariable, realtimePostgresUrlVariable, resolveRealtimeNamespace, resolveRealtimeNodeDriver, useRealtimeBus };
1
+ export { t as closeRealtimeBuses, n as createPostgresRealtimeBus, r as createRealtimeNodeBus, i as createRedisRealtimeBus, a as logRealtimeNodeDriver, o as realtimeNamespaceVariable, s as realtimePostgresUrlVariable, c as resolveRealtimeNamespace, l as resolveRealtimeNodeDriver, u as useRealtimeBus } from "./bus-DJ3dOQAZ.js";
@@ -18,7 +18,7 @@ const wt=e=>e===void 0?null:e;
18
18
  /* c8 ignore stop */
19
19
  let Tt=new class{constructor(){this.map=/* @__PURE__ */ new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},Et=!0;
20
20
  /* c8 ignore start */
21
- try{typeof localStorage<`u`&&localStorage&&(Tt=localStorage,Et=!1)}catch{}
21
+ try{typeof window<`u`&&typeof localStorage<`u`&&localStorage&&(Tt=localStorage,Et=!1)}catch{}
22
22
  /* c8 ignore stop */
23
23
  /* c8 ignore next */
24
24
  const Dt=Tt,Ot=e=>Et||addEventListener(`storage`,e),kt=e=>Et||removeEventListener(`storage`,e),A=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,At=typeof window<`u`&&typeof document<`u`&&!A;typeof navigator<`u`&&/Mac/.test(navigator.platform);let j;const jt=[],Mt=()=>{if(j===void 0){if(A){j=O();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&j.set(t,``),t=r):t===null?jt.push(r):(j.set(t,r),t=null)}t!==null&&j.set(t,``)}else typeof location==`object`?(j=O(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);j.set(`--${ce(t,`-`)}`,n),j.set(`-${ce(t,`-`)}`,n)}})):j=O()}return j},Nt=e=>Mt().has(e),Pt=e=>wt(A?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:Dt.getItem(e)),Ft=e=>Nt(`--`+e)||Pt(e)!==null,It=Ft(`production`),Lt=A&&yt(process.env.FORCE_COLOR,[`true`,`1`,`2`])||!Nt(`--no-colors`)&&!Ft(`no-color`)&&(!A||process.stdout.isTTY)&&(!A||Nt(`--color`)||Pt(`COLORTERM`)!==null||(Pt(`TERM`)||``).includes(`color`)),Rt=e=>new Uint8Array(e),zt=e=>new Uint8Array(e),Bt=e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=p(e[n]);return btoa(t)},Vt=e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),Ht=e=>{let t=atob(e),n=Rt(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},Ut=e=>new Uint8Array(Buffer.from(e,`base64`)),Wt=At?Bt:Vt,Gt=At?Ht:Ut,Kt=e=>{let t=Rt(e.byteLength);return t.set(e),t};var qt=class{constructor(e,t){this.left=e,this.right=t}};const M=(e,t)=>new qt(e,t),Jt=e=>e.next()>=.5,Yt=(t,n,r)=>e(t.next()*(r+1-n)+n),Xt=(t,n,r)=>e(t.next()*(r+1-n)+n),Zt=(e,t,n)=>Xt(e,t,n),Qt=e=>p(Zt(e,97,122)),$t=(e,t=0,n=20)=>{let r=Zt(e,t,n),i=``;for(let t=0;t<r;t++)i+=Qt(e);return i},en=(e,t)=>t[Zt(e,0,t.length-1)],tn=Symbol(`0schema`);var nn=class{constructor(){this._rerrs=[]}extend(e,t,n,r=null){this._rerrs.push({path:e,expected:t,has:n,message:r})}toString(){let e=[];for(let t=this._rerrs.length-1;t>0;t--){let n=this._rerrs[t];
@@ -42,7 +42,7 @@ const I=Symbol,ur=I(),dr=I(),fr=I(),pr=I(),mr=I(),hr=I(),gr=I(),_r=I(),vr=I(),yr
42
42
  /* c8 ignore stop */
43
43
  const br={[ur]:M(`font-weight`,`bold`),[dr]:M(`font-weight`,`normal`),[fr]:M(`color`,`blue`),[mr]:M(`color`,`green`),[pr]:M(`color`,`grey`),[hr]:M(`color`,`red`),[gr]:M(`color`,`purple`),[_r]:M(`color`,`orange`),[vr]:M(`color`,`black`)},xr=Lt?e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=O(),i=[],a=0;for(;a<e.length;a++){let i=e[a],o=br[i];if(o!==void 0)r.set(o.left,o.right);else{if(i===void 0)break;if(i.constructor===String||i.constructor===Number){let e=ar(r);a>0||e.length>0?(t.push(`%c`+i),n.push(e)):t.push(i)}else break}}for(a>0&&(i=n,i.unshift(t.join(``)));a<e.length;a++){let t=e[a];t instanceof Symbol||i.push(t)}return i}:yr,Sr=(...e)=>{
44
44
  /* c8 ignore next */
45
- console.log(...xr(e)),wr.forEach(t=>t.print(e))},Cr=(...e)=>{console.warn(...xr(e)),e.unshift(_r),wr.forEach(t=>t.print(e))},wr=l(),Tr=e=>({[Symbol.iterator](){return this},next:e}),Er=(e,t)=>Tr(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),Dr=(e,t)=>Tr(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});var Or=class{constructor(e,t){this.clock=e,this.len=t}},kr=class{constructor(){this.clients=/* @__PURE__ */ new Map}};const Ar=(e,t,n)=>t.clients.forEach((t,r)=>{let i=e.doc.store.clients.get(r);if(i!=null){let r=i[i.length-1],a=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<a;o=t[++r])Mi(e,i,o.clock,o.len,n)}}),jr=(t,n)=>{let r=0,i=t.length-1;for(;r<=i;){let a=e((r+i)/2),o=t[a],s=o.clock;if(s<=n){if(n<s+o.len)return a;r=a+1}else i=a-1}return null},Mr=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&jr(n,t.clock)!==null},Nr=e=>{e.clients.forEach(e=>{e.sort((e,t)=>e.clock-t.clock);let t,n;for(t=1,n=1;t<e.length;t++){let i=e[n-1],a=e[t];i.clock+i.len>=a.clock?e[n-1]=new Or(i.clock,r(i.len,a.clock+a.len-i.clock)):(n<t&&(e[n]=a),n++)}e.length=n})},Pr=e=>{let t=new kr;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){let a=r.slice();for(let t=n+1;t<e.length;t++)d(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return Nr(t),t},Fr=(e,t,n,r)=>{k(e.clients,t,()=>[]).push(new Or(n,r))},Ir=()=>new kr,Lr=e=>{let t=Ir();return e.clients.forEach((e,n)=>{let r=[];for(let t=0;t<e.length;t++){let n=e[t];if(n.deleted){let i=n.id.clock,a=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[++t+1])a+=n.length;r.push(new Or(i,a))}}r.length>0&&t.clients.set(n,r)}),t},Rr=(e,t)=>{b(e.restEncoder,t.clients.size),f(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),b(e.restEncoder,t);let r=n.length;b(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},zr=e=>{let t=new kr,n=T(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=T(e.restDecoder),r=T(e.restDecoder);if(r>0){let i=k(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new Or(e.readDsClock(),e.readDsLen()))}}return t},Br=(e,t,n)=>{let r=new kr,i=T(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=T(e.restDecoder),a=T(e.restDecoder),o=n.clients.get(i)||[],s=R(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&Fr(r,i,s,a-s);let e=z(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,Po(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<a);)c.deleted||(a<c.id.clock+c.length&&o.splice(e,0,Po(t,c,a-c.id.clock)),c.delete(t))}else Fr(r,i,n,a-n)}}if(r.clients.size>0){let e=new Xr;return b(e.restEncoder,0),Rr(e,r),e.toUint8Array()}return null},Vr=xt;var Hr=class e extends et{constructor({guid:e=St(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:a=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=Vr(),this.guid=e,this.collectionid=t,this.share=/* @__PURE__ */ new Map,this.store=new Ti,this._transaction=null,this._transactionCleanups=[],this.subdocs=/* @__PURE__ */ new Set,this._item=null,this.shouldLoad=o,this.autoLoad=a,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Ct(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>Ct(e=>{let t=n=>{(n===void 0||n===!0)&&(this.off(`sync`,t),e())};this.on(`sync`,t)});this.on(`sync`,e=>{e===!1&&this.isSynced&&(this.whenSynced=s()),this.isSynced=e===void 0||e===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=s()}load(){let e=this._item;e!==null&&!this.shouldLoad&&V(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(f(this.subdocs).map(e=>e.guid))}transact(e,t=null){return V(this,e,t)}get(e,t=W){let n=k(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==W&&r!==t){if(r===W){let r=new t;r._map=n._map,n._map.forEach(e=>{for(;e!==null;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;e!==null;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}throw Error(`Type with the name ${e} has already been defined with a different constructor`)}return n}getArray(e=``){return this.get(e,Da)}getText(e=``){return this.get(e,qa)}getMap(e=``){return this.get(e,Aa)}getXmlElement(e=``){return this.get(e,Qa)}getXmlFragment(e=``){return this.get(e,Xa)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,f(this.subdocs).forEach(e=>e.destroy());let t=this._item;if(t!==null){this._item=null;let n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,V(t.parent.doc,e=>{let r=n.doc;t.deleted||e.subdocsAdded.add(r),e.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}},Ur=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return T(this.restDecoder)}readDsLen(){return T(this.restDecoder)}},Wr=class extends Ur{readLeftID(){return L(T(this.restDecoder),T(this.restDecoder))}readRightID(){return L(T(this.restDecoder),T(this.restDecoder))}readClient(){return T(this.restDecoder)}readInfo(){return He(this.restDecoder)}readString(){return E(this.restDecoder)}readParentInfo(){return T(this.restDecoder)===1}readTypeRef(){return T(this.restDecoder)}readLen(){return T(this.restDecoder)}readAny(){return Ke(this.restDecoder)}readBuf(){return Kt(w(this.restDecoder))}readJSON(){return JSON.parse(E(this.restDecoder))}readKey(){return E(this.restDecoder)}},Gr=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=T(this.restDecoder),this.dsCurrVal}readDsLen(){let e=T(this.restDecoder)+1;return this.dsCurrVal+=e,e}},Kr=class extends Gr{constructor(e){super(e),this.keys=[],T(e),this.keyClockDecoder=new Ye(w(e)),this.clientDecoder=new Je(w(e)),this.leftClockDecoder=new Ye(w(e)),this.rightClockDecoder=new Ye(w(e)),this.infoDecoder=new qe(w(e),He),this.stringDecoder=new Xe(w(e)),this.parentInfoDecoder=new qe(w(e),He),this.typeRefDecoder=new Je(w(e)),this.lenDecoder=new Je(w(e))}readLeftID(){return new yi(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new yi(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ke(this.restDecoder)}readBuf(){return w(this.restDecoder)}readJSON(){return Ke(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{let e=this.stringDecoder.read();return this.keys.push(e),e}}},qr=class{constructor(){this.restEncoder=_()}toUint8Array(){return v(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){b(this.restEncoder,e)}writeDsLen(e){b(this.restEncoder,e)}},Jr=class extends qr{writeLeftID(e){b(this.restEncoder,e.client),b(this.restEncoder,e.clock)}writeRightID(e){b(this.restEncoder,e.client),b(this.restEncoder,e.clock)}writeClient(e){b(this.restEncoder,e)}writeInfo(e){_e(this.restEncoder,e)}writeString(e){x(this.restEncoder,e)}writeParentInfo(e){b(this.restEncoder,+!!e)}writeTypeRef(e){b(this.restEncoder,e)}writeLen(e){b(this.restEncoder,e)}writeAny(e){Oe(this.restEncoder,e)}writeBuf(e){S(this.restEncoder,e)}writeJSON(e){x(this.restEncoder,JSON.stringify(e))}writeKey(e){x(this.restEncoder,e)}},Yr=class{constructor(){this.restEncoder=_(),this.dsCurrVal=0}toUint8Array(){return v(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,b(this.restEncoder,t)}writeDsLen(e){e===0&&g(),b(this.restEncoder,e-1),this.dsCurrVal+=e}},Xr=class extends Yr{constructor(){super(),this.keyMap=/* @__PURE__ */ new Map,this.keyClock=0,this.keyClockEncoder=new Ne,this.clientEncoder=new je,this.leftClockEncoder=new Ne,this.rightClockEncoder=new Ne,this.infoEncoder=new ke(_e),this.stringEncoder=new Pe,this.parentInfoEncoder=new ke(_e),this.typeRefEncoder=new je,this.lenEncoder=new je}toUint8Array(){let e=_();return b(e,0),S(e,this.keyClockEncoder.toUint8Array()),S(e,this.clientEncoder.toUint8Array()),S(e,this.leftClockEncoder.toUint8Array()),S(e,this.rightClockEncoder.toUint8Array()),S(e,v(this.infoEncoder)),S(e,this.stringEncoder.toUint8Array()),S(e,v(this.parentInfoEncoder)),S(e,this.typeRefEncoder.toUint8Array()),S(e,this.lenEncoder.toUint8Array()),xe(e,v(this.restEncoder)),v(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(+!!e)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Oe(this.restEncoder,e)}writeBuf(e){S(this.restEncoder,e)}writeJSON(e){Oe(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}};const Zr=(e,t,n,i)=>{i=r(i,t[0].id.clock);let a=z(t,i);b(e.restEncoder,t.length-a),e.writeClient(n),b(e.restEncoder,i);let o=t[a];o.write(e,i-o.id.clock);for(let n=a+1;n<t.length;n++)t[n].write(e,0)},Qr=(e,t,n)=>{let r=/* @__PURE__ */ new Map;n.forEach((e,n)=>{R(t,n)>e&&r.set(n,e)}),Ei(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),b(e.restEncoder,r.size),f(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{Zr(e,t.clients.get(n),n,r)})},$r=(e,t)=>{let n=O(),r=T(e.restDecoder);for(let i=0;i<r;i++){let r=T(e.restDecoder),i=Array(r),a=e.readClient(),o=T(e.restDecoder);n.set(a,{i:0,refs:i});for(let n=0;n<r;n++){let r=e.readInfo();switch(31&r){case 0:{let t=e.readLen();i[n]=new K(L(a,o),t),o+=t;break}case 10:{let t=T(e.restDecoder);i[n]=new Y(L(a,o),t),o+=t;break}default:{let s=!(r&192),c=new J(L(a,o),null,(r&128)==128?e.readLeftID():null,null,(r&64)==64?e.readRightID():null,s?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,s&&(r&32)==32?e.readString():null,Fo(e,r));i[n]=c,o+=c.length}}}}return n},ei=(e,t,n)=>{let r=[],i=f(n.keys()).sort((e,t)=>e-t);if(i.length===0)return null;let a=()=>{if(i.length===0)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;)if(i.pop(),i.length>0)e=n.get(i[i.length-1]);else return null;return e},o=a();if(o===null)return null;let s=new Ti,c=/* @__PURE__ */ new Map,l=(e,t)=>{let n=c.get(e);(n==null||n>t)&&c.set(e,t)},u=o.refs[o.i++],d=/* @__PURE__ */ new Map,ee=()=>{for(let e of r){let t=e.id.client,r=n.get(t);r?(r.i--,s.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):s.clients.set(t,[e]),i=i.filter(e=>e!==t)}r.length=0};for(;;){if(u.constructor!==Y){let i=k(d,u.id.client,()=>R(t,u.id.client))-u.id.clock;if(i<0)r.push(u),l(u.id.client,u.id.clock-1),ee();else{let a=u.getMissing(e,t);if(a!==null){r.push(u);let e=n.get(a)||{refs:[],i:0};if(e.refs.length===e.i)l(a,R(t,a)),ee();else{u=e.refs[e.i++];continue}}else(i===0||i<u.length)&&(u.integrate(e,i),d.set(u.id.client,u.id.clock+u.length))}}if(r.length>0)u=r.pop();else if(o!==null&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=a(),o===null)break;u=o.refs[o.i++]}}if(s.clients.size>0){let e=new Xr;return Qr(e,s,/* @__PURE__ */ new Map),b(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},ti=(e,t)=>Qr(e,t.doc.store,t.beforeState),ni=(e,t,n,r=new Kr(e))=>V(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=$r(r,n),o=ei(e,i,a),s=i.pendingStructs;if(s){for(let[e,n]of s.missing)if(n<R(i,e)){t=!0;break}if(o){for(let[e,t]of o.missing){let n=s.missing.get(e);(n==null||n>t)&&s.missing.set(e,t)}s.update=Gi([s.update,o.update])}}else i.pendingStructs=o;let c=Br(r,e,i);if(i.pendingDs){let t=new Kr(C(i.pendingDs));T(t.restDecoder);let n=Br(t,e,i);i.pendingDs=c&&n?Gi([c,n]):c||n}else i.pendingDs=c;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,ri(e.doc,t)}},n,!1),ri=(e,t,n,r=Kr)=>{let i=C(t);ni(i,e,n,new r(i))},ii=(e,t,n)=>ri(e,t,n,Wr),ai=(e,t,n=/* @__PURE__ */ new Map)=>{Qr(e,t.store,n),Rr(e,Lr(t.store))},oi=(e,t=new Uint8Array([0]),n=new Xr)=>{let r=li(t);ai(n,e,r);let i=[n.toUint8Array()];if(e.store.pendingDs&&i.push(e.store.pendingDs),e.store.pendingStructs&&i.push(Ki(e.store.pendingStructs.update,t)),i.length>1){if(n.constructor===Jr)return Ui(i.map((e,t)=>t===0?e:Xi(e)));if(n.constructor===Xr)return Gi(i)}return i[0]},si=(e,t)=>oi(e,t,new Jr),ci=e=>{let t=/* @__PURE__ */ new Map,n=T(e.restDecoder);for(let r=0;r<n;r++){let n=T(e.restDecoder),r=T(e.restDecoder);t.set(n,r)}return t},li=e=>ci(new Ur(C(e))),ui=(e,t)=>(b(e.restEncoder,t.size),f(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{b(e.restEncoder,t),b(e.restEncoder,n)}),e),di=(e,t)=>ui(e,Ei(t.store)),fi=(e,t=new Yr)=>(e instanceof Map?ui(t,e):di(t,e),t.toUint8Array()),pi=e=>fi(e,new qr);var mi=class{constructor(){this.l=[]}};const hi=()=>new mi,gi=(e,t)=>e.l.push(t),_i=(e,t)=>{let n=e.l,r=n.length;e.l=n.filter(e=>t!==e),r===e.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},vi=(e,t,n)=>gt(e.l,[t,n]);var yi=class{constructor(e,t){this.client=e,this.clock=t}};const bi=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,L=(e,t)=>new yi(e,t),xi=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw g()};var Si=class{constructor(e,t){this.ds=e,this.sv=t}};((e,t)=>new Si(e,t))(Ir(),/* @__PURE__ */ new Map);const Ci=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Mr(t.ds,e.id),wi=(e,t)=>{let n=k(e.meta,wi,l),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<R(r,n)&&B(e,L(n,t))}),Ar(e,t.ds,e=>{}),n.add(t))};var Ti=class{constructor(){this.clients=/* @__PURE__ */ new Map,this.pendingStructs=null,this.pendingDs=null}};const Ei=e=>{let t=/* @__PURE__ */ new Map;return e.clients.forEach((e,n)=>{let r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},R=(e,t)=>{let n=e.clients.get(t);if(n===void 0)return 0;let r=n[n.length-1];return r.id.clock+r.length},Di=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{let e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw g()}n.push(t)},z=(t,n)=>{let r=0,i=t.length-1,a=t[i],o=a.id.clock;if(o===n)return i;let s=e(n/(o+a.length-1)*i);for(;r<=i;){if(a=t[s],o=a.id.clock,o<=n){if(n<o+a.length)return s;r=s+1}else i=s-1;s=e((r+i)/2)}throw g()},Oi=(e,t)=>{let n=e.clients.get(t.client);return n[z(n,t.clock)]},ki=(e,t,n)=>{let r=z(t,n),i=t[r];return i.id.clock<n&&i instanceof J?(t.splice(r+1,0,Po(e,i,n-i.id.clock)),r+1):r},B=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[ki(e,n,t.clock)]},Ai=(e,t,n)=>{let r=t.clients.get(n.client),i=z(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==K&&r.splice(i+1,0,Po(e,a,n.clock-a.id.clock+1)),a},ji=(e,t,n)=>{let r=e.clients.get(t.id.client);r[z(r,t.id.clock)]=n},Mi=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=ki(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&ki(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)};var Ni=class{constructor(e,t,n){this.doc=e,this.deleteSet=new kr,this.beforeState=Ei(e.store),this.afterState=/* @__PURE__ */ new Map,this.changed=/* @__PURE__ */ new Map,this.changedParentTypes=/* @__PURE__ */ new Map,this._mergeStructs=[],this.origin=t,this.meta=/* @__PURE__ */ new Map,this.local=n,this.subdocsAdded=/* @__PURE__ */ new Set,this.subdocsRemoved=/* @__PURE__ */ new Set,this.subdocsLoaded=/* @__PURE__ */ new Set,this._needFormattingCleanup=!1}};const Pi=(e,t)=>t.deleteSet.clients.size===0&&!$e(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(Nr(t.deleteSet),ti(e,t),Rr(e,t.deleteSet),!0),Fi=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&k(e.changed,t,l).add(n)},Ii=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0;n=r,r=e[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof J&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}let a=t-i;return a&&e.splice(t+1-a,a),a},Li=(e,t,n)=>{for(let[r,i]of e.clients.entries()){let e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){let a=i[r],o=a.clock+a.len;for(let r=z(e,a.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){let i=e[r];if(a.clock+a.len<=i.id.clock)break;i instanceof J&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},Ri=(e,t)=>{e.clients.forEach((e,r)=>{let i=t.clients.get(r);for(let t=e.length-1;t>=0;t--){let r=e[t],a=n(i.length-1,1+z(i,r.clock+r.len-1));for(let e=a,t=i[e];e>0&&t.id.clock>=r.clock;t=i[e])e-=1+Ii(i,e)}})},zi=(e,t)=>{if(t<e.length){let n=e[t],i=n.doc,a=i.store,o=n.deleteSet,s=n._mergeStructs;try{Nr(o),n.afterState=Ei(n.doc.store),i.emit(`beforeObserverCalls`,[n,i]);let e=[];n.changed.forEach((t,r)=>e.push(()=>{(r._item===null||!r._item.deleted)&&r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(r._item===null||!r._item.deleted)&&e.push(()=>{t=t.filter(e=>e.target._item===null||!e.target._item.deleted),t.forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),vi(r._dEH,t,n)})}),e.push(()=>i.emit(`afterTransaction`,[n,i])),e.push(()=>{n._needFormattingCleanup&&Wa(n)})}),gt(e,[])}finally{i.gc&&Li(o,a,i.gcFilter),Ri(o,a),n.afterState.forEach((e,t)=>{let i=n.beforeState.get(t)||0;if(i!==e){let e=a.clients.get(t),n=r(z(e,i),1);for(let t=e.length-1;t>=n;)t-=1+Ii(e,t)}});for(let e=s.length-1;e>=0;e--){let{client:t,clock:n}=s[e].id,r=a.clients.get(t),i=z(r,n);i+1<r.length&&Ii(r,i+1)>1||i>0&&Ii(r,i)}if(!n.local&&n.afterState.get(i.clientID)!==n.beforeState.get(i.clientID)&&(Sr(_r,ur,`[yjs] `,dr,hr,`Changed the client-id because another client seems to be using it.`),i.clientID=Vr()),i.emit(`afterTransactionCleanup`,[n,i]),i._observers.has(`update`)){let e=new Jr;Pi(e,n)&&i.emit(`update`,[e.toUint8Array(),n.origin,i,n])}if(i._observers.has(`updateV2`)){let e=new Xr;Pi(e,n)&&i.emit(`updateV2`,[e.toUint8Array(),n.origin,i,n])}let{subdocsAdded:c,subdocsLoaded:l,subdocsRemoved:u}=n;(c.size>0||u.size>0||l.size>0)&&(c.forEach(e=>{e.clientID=i.clientID,e.collectionid??=i.collectionid,i.subdocs.add(e)}),u.forEach(e=>i.subdocs.delete(e)),i.emit(`subdocs`,[{loaded:l,added:c,removed:u},i,n]),u.forEach(e=>e.destroy())),e.length<=t+1?(i._transactionCleanups=[],i.emit(`afterAllTransactions`,[i,e])):zi(e,t+1)}}},V=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new Ni(e,n,r),i.push(e._transaction),i.length===1&&e.emit(`beforeAllTransactions`,[e]),e.emit(`beforeTransaction`,[e._transaction,e]));try{o=t(e._transaction)}finally{if(a){let t=e._transaction===i[0];e._transaction=null,t&&zi(i,0)}}return o};function*Bi(e){let t=T(e.restDecoder);for(let n=0;n<t;n++){let t=T(e.restDecoder),n=e.readClient(),r=T(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=T(e.restDecoder);yield new Y(L(n,r),t),r+=t}else if(31&t){let i=!(t&192),a=new J(L(n,r),null,(t&128)==128?e.readLeftID():null,null,(t&64)==64?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&(t&32)==32?e.readString():null,Fo(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new K(L(n,r),t),r+=t}}}}var Vi=class{constructor(e,t){this.gen=Bi(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===Y);return this.curr}},Hi=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const Ui=e=>Gi(e,Wr,Jr),Wi=(e,t)=>{if(e.constructor===K){let{client:n,clock:r}=e.id;return new K(L(n,r+t),e.length-t)}if(e.constructor===Y){let{client:n,clock:r}=e.id;return new Y(L(n,r+t),e.length-t)}{let n=e,{client:r,clock:i}=n.id;return new J(L(r,i+t),null,L(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Gi=(e,t=Kr,n=Xr)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(C(e))),i=r.map(e=>new Vi(e,!0)),a=null,o=new n,s=new Hi(o);for(;i=i.filter(e=>e.curr!==null),i.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){let n=e.curr.id.clock-t.curr.id.clock;return n===0?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===Y?1:-1:n}return t.curr.id.client-e.curr.id.client}),i.length!==0;){let e=i[0],t=e.curr.id.client;if(a!==null){let n=e.curr,r=!1;for(;n!==null&&n.id.clock+n.length<=a.struct.id.clock+a.struct.length&&n.id.client>=a.struct.id.client;)n=e.next(),r=!0;if(n===null||n.id.client!==t||r&&n.id.clock>a.struct.id.clock+a.struct.length)continue;if(t!==a.struct.id.client)H(s,a.struct,a.offset),a={struct:n,offset:0},e.next();else if(a.struct.id.clock+a.struct.length<n.id.clock){if(a.struct.constructor===Y)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{H(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new Y(L(t,a.struct.id.clock+a.struct.length),e),offset:0}}}else{let t=a.struct.id.clock+a.struct.length-n.id.clock;t>0&&(a.struct.constructor===Y?a.struct.length-=t:n=Wi(n,t)),a.struct.mergeWith(n)||(H(s,a.struct,a.offset),a={struct:n,offset:0},e.next())}}else a={struct:e.curr,offset:0},e.next();for(let n=e.curr;n!==null&&n.id.client===t&&n.id.clock===a.struct.id.clock+a.struct.length&&n.constructor!==Y;n=e.next())H(s,a.struct,a.offset),a={struct:n,offset:0}}a!==null&&(H(s,a.struct,a.offset),a=null),Ji(s);let c=r.map(e=>zr(e)),l=Pr(c);return Rr(o,l),o.toUint8Array()},Ki=(e,t,n=Kr,i=Xr)=>{let a=li(t),o=new i,s=new Hi(o),c=new n(C(e)),l=new Vi(c,!1);for(;l.curr;){let e=l.curr,t=e.id.client,n=a.get(t)||0;if(l.curr.constructor===Y){l.next();continue}if(e.id.clock+e.length>n)for(H(s,e,r(n-e.id.clock,0)),l.next();l.curr&&l.curr.id.client===t;)H(s,l.curr,0),l.next();else for(;l.curr&&l.curr.id.client===t&&l.curr.id.clock+l.curr.length<=n;)l.next()}Ji(s);let u=zr(c);return Rr(o,u),o.toUint8Array()},qi=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:v(e.encoder.restEncoder)}),e.encoder.restEncoder=_(),e.written=0)},H=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&qi(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),b(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Ji=e=>{qi(e);let t=e.encoder.restEncoder;b(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];b(t,r.written),xe(t,r.restEncoder)}},Yi=(e,t,n,r)=>{let i=new n(C(e)),a=new Vi(i,!1),o=new r,s=new Hi(o);for(let e=a.curr;e!==null;e=a.next())H(s,t(e),0);Ji(s);let c=zr(i);return Rr(o,c),o.toUint8Array()},Xi=e=>Yi(e,_t,Kr,Jr),Zi=`You must not compute changes after the event-handler fired.`;var Qi=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||=$i(this.currentTarget,this.target)}deletes(e){return Mr(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw m(Zi);let e=/* @__PURE__ */ new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(n!==null){let r=t._map.get(n),i,a;if(this.adds(r)){let e=r.left;for(;e!==null&&this.adds(e);)e=e.left;if(this.deletes(r)){if(e!==null&&this.deletes(e))i=`delete`,a=u(e.content.getContent());else return}else e!==null&&this.deletes(e)?(i=`update`,a=u(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=u(r.content.getContent());else return;e.set(n,{action:i,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw m(Zi);let t=this.target,n=l(),r=l(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null,a=()=>{e&&i.push(e)};for(let i=t._start;i!==null;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&((e===null||e.delete===void 0)&&(a(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?((e===null||e.insert===void 0)&&(a(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):((e===null||e.retain===void 0)&&(a(),e={retain:0}),e.retain+=i.length);e!==null&&e.retain===void 0&&a()}this._changes=e}return e}};const $i=(e,t)=>{let n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},U=()=>{Cr(`Invalid access: Add Yjs type to a document before reading data.`)};let ea=0;var ta=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=ea++}};const na=e=>{e.timestamp=ea++},ra=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ea++},ia=(e,t,n)=>{if(e.length>=80){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return ra(r,t,n),r}{let r=new ta(t,n);return e.push(r),r}},aa=(e,n)=>{if(e._start===null||n===0||e._searchMarker===null)return null;let r=e._searchMarker.length===0?null:e._searchMarker.reduce((e,r)=>t(n-e.index)<t(n-r.index)?e:r),i=e._start,a=0;for(r!==null&&(i=r.p,a=r.index,na(r));i.right!==null&&a<n;){if(!i.deleted&&i.countable){if(n<a+i.length)break;a+=i.length}i=i.right}for(;i.left!==null&&a>n;)i=i.left,!i.deleted&&i.countable&&(a-=i.length);for(;i.left!==null&&i.left.id.client===i.id.client&&i.left.id.clock+i.left.length===i.id.clock;)i=i.left,!i.deleted&&i.countable&&(a-=i.length);return r!==null&&t(r.index-a)<i.parent.length/80?(ra(r,i,a),r):ia(e._searchMarker,i,a)},oa=(e,t,n)=>{for(let i=e.length-1;i>=0;i--){let a=e[i];if(n>0){let t=a.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(a.index-=t.length);if(t===null||t.marker===!0){e.splice(i,1);continue}a.p=t,t.marker=!0}(t<a.index||n>0&&t===a.index)&&(a.index=r(t,a.index+n))}},sa=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;k(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;vi(r._eH,n,t)};var W=class{constructor(){this._item=null,this._map=/* @__PURE__ */ new Map,this._start=null,this.doc=null,this._length=0,this._eH=hi(),this._dEH=hi(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw h()}clone(){throw h()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){gi(this._eH,e)}observeDeep(e){gi(this._dEH,e)}unobserve(e){_i(this._eH,e)}unobserveDeep(e){_i(this._dEH,e)}toJSON(){}};const ca=(e,t,n)=>{e.doc??U(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t,i=[],a=e._start;for(;a!==null&&r>0;){if(a.countable&&!a.deleted){let e=a.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}a=a.right}return i},la=e=>{e.doc??U();let t=[],n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){let e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},ua=(e,t)=>{let n=0,r=e._start;for(e.doc??U();r!==null;){if(r.countable&&!r.deleted){let i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},da=(e,t)=>{let n=[];return ua(e,(r,i)=>{n.push(t(r,i,e))}),n},fa=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}let e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},pa=(e,t)=>{e.doc??U();let n=aa(e,t),r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},ma=(e,t,n,r)=>{let i=n,a=e.doc,o=a.clientID,s=a.store,c=n===null?t._start:n.right,l=[],u=()=>{l.length>0&&(i=new J(L(o,R(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new bo(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(n===null)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(u(),n.constructor){case Uint8Array:case ArrayBuffer:i=new J(L(o,R(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new oo(new Uint8Array(n))),i.integrate(e,0);break;case Hr:i=new J(L(o,R(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new fo(n)),i.integrate(e,0);break;default:if(n instanceof W)i=new J(L(o,R(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Mo(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},ha=()=>m(`Length exceeded!`),ga=(e,t,n,r)=>{if(n>t._length)throw ha();if(n===0)return t._searchMarker&&oa(t._searchMarker,n,r.length),ma(e,t,null,r);let i=n,a=aa(t,n),o=t._start;for(a!==null&&(o=a.p,n-=a.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&B(e,L(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&oa(t._searchMarker,i,r.length),ma(e,t,o,r)},_a=(e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return ma(e,t,r,n)},va=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=aa(t,n),s=t._start;for(o!==null&&(s=o.p,n-=o.index);s!==null&&n>0;s=s.right)!s.deleted&&s.countable&&(n<s.length&&B(e,L(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&B(e,L(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw ha();t._searchMarker&&oa(t._searchMarker,i,-a+r)},ya=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},ba=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new bo([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new bo([r]);break;case Uint8Array:s=new oo(r);break;case Hr:s=new fo(r);break;default:if(r instanceof W)s=new Mo(r);else throw Error(`Unexpected content type`)}new J(L(o,R(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},xa=(e,t)=>{e.doc??U();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Sa=e=>{let t={};return e.doc??U(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},Ca=(e,t)=>{e.doc??U();let n=e._map.get(t);return n!==void 0&&!n.deleted},wa=(e,t)=>{let n={};return e._map.forEach((e,r)=>{let i=e;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&Ci(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Ta=e=>(e.doc??U(),Er(e._map.entries(),e=>!e[1].deleted));var Ea=class extends Qi{},Da=class e extends W{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let n=new e;return n.push(t),n}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof W?e.clone():e)),t}get length(){return this.doc??U(),this._length}_callObserver(e,t){super._callObserver(e,t),sa(this,e,new Ea(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):V(this.doc,n=>{ga(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):V(this.doc,t=>{_a(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):V(this.doc,n=>{va(n,this,e,t)})}get(e){return pa(this,e)}toArray(){return la(this)}slice(e=0,t=this.length){return ca(this,e,t)}toJSON(){return this.map(e=>e instanceof W?e.toJSON():e)}map(e){return da(this,e)}forEach(e){ua(this,e)}[Symbol.iterator](){return fa(this)}_write(e){e.writeTypeRef(To)}};const Oa=e=>new Da;var ka=class extends Qi{constructor(e,t,n){super(e,t),this.keysChanged=n}},Aa=class e extends W{constructor(e){super(),this._prelimContent=null,this._prelimContent=e===void 0?/* @__PURE__ */ new Map:new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof W?e.clone():e)}),t}_callObserver(e,t){sa(this,e,new ka(this,e,t))}toJSON(){this.doc??U();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof W?r.toJSON():r}}),e}get size(){return[...Ta(this)].length}keys(){return Dr(Ta(this),e=>e[0])}values(){return Dr(Ta(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return Dr(Ta(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??U(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc===null?this._prelimContent.delete(e):V(this.doc,t=>{ya(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):V(this.doc,n=>{ba(n,this,e,t)}),t}get(e){return xa(this,e)}has(e){return Ca(this,e)}clear(){this.doc===null?this._prelimContent.clear():V(this.doc,e=>{this.forEach(function(t,n,r){ya(e,r,n)})})}_write(e){e.writeTypeRef(Eo)}};const ja=e=>new Aa,G=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&pt(e,t);var Ma=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&g(),this.right.content.constructor){case q:this.right.deleted||Ia(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length)}this.left=this.right,this.right=this.right.right}};const Na=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case q:t.right.deleted||Ia(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&B(e,L(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length)}t.left=t.right,t.right=t.right.right}return t},Pa=(e,t,n,r)=>{let i=/* @__PURE__ */ new Map,a=r?aa(t,n):null;if(a){let t=new Ma(a.p.left,a.p,a.index,i);return Na(e,t,n-a.index)}{let r=new Ma(null,t._start,0,i);return Na(e,r,n)}},Fa=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===q&&G(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();let i=e.doc,a=i.clientID;r.forEach((r,o)=>{let s=n.left,c=n.right,l=new J(L(a,R(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new q(o,r));l.integrate(e,0),n.right=l,n.forward()})},Ia=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},La=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===q&&G(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Ra=(e,t,n,r)=>{let i=e.doc,a=i.clientID,o=/* @__PURE__ */ new Map;for(let s in r){let c=r[s],l=n.currentAttributes.get(s)??null;if(!G(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new J(L(a,R(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new q(s,c)),n.right.integrate(e,0),n.forward()}}return o},za=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;La(n,i);let s=Ra(e,t,n,i),c=r.constructor===String?new So(r):r instanceof W?new Mo(r):new mo(r),{left:l,right:u,index:d}=n;t._searchMarker&&oa(t._searchMarker,n.index,c.getLength()),u=new J(L(o,R(a.store,o)),l,l&&l.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=d,n.forward(),Fa(e,t,n,s)},Ba=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;La(n,i);let s=Ra(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===q));){if(!n.right.deleted)switch(n.right.content.constructor){case q:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(G(o,a))s.delete(t);else{if(r===0)break iterationLoop;s.set(t,a)}n.right.delete(e)}else n.currentAttributes.set(t,a);break}default:r<n.right.length&&B(e,L(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let i=``;for(;r>0;r--)i+=`
45
+ console.log(...xr(e)),wr.forEach(t=>t.print(e))},Cr=(...e)=>{console.warn(...xr(e)),e.unshift(_r),wr.forEach(t=>t.print(e))},wr=l(),Tr=e=>({[Symbol.iterator](){return this},next:e}),Er=(e,t)=>Tr(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),Dr=(e,t)=>Tr(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});var Or=class{constructor(e,t){this.clock=e,this.len=t}},kr=class{constructor(){this.clients=/* @__PURE__ */ new Map}};const Ar=(e,t,n)=>t.clients.forEach((t,r)=>{let i=e.doc.store.clients.get(r);if(i!=null){let r=i[i.length-1],a=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<a;o=t[++r])Mi(e,i,o.clock,o.len,n)}}),jr=(t,n)=>{let r=0,i=t.length-1;for(;r<=i;){let a=e((r+i)/2),o=t[a],s=o.clock;if(s<=n){if(n<s+o.len)return a;r=a+1}else i=a-1}return null},Mr=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&jr(n,t.clock)!==null},Nr=e=>{e.clients.forEach(e=>{e.sort((e,t)=>e.clock-t.clock);let t,n;for(t=1,n=1;t<e.length;t++){let i=e[n-1],a=e[t];i.clock+i.len>=a.clock?e[n-1]=new Or(i.clock,r(i.len,a.clock+a.len-i.clock)):(n<t&&(e[n]=a),n++)}e.length=n})},Pr=e=>{let t=new kr;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){let a=r.slice();for(let t=n+1;t<e.length;t++)d(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return Nr(t),t},Fr=(e,t,n,r)=>{k(e.clients,t,()=>[]).push(new Or(n,r))},Ir=()=>new kr,Lr=e=>{let t=Ir();return e.clients.forEach((e,n)=>{let r=[];for(let t=0;t<e.length;t++){let n=e[t];if(n.deleted){let i=n.id.clock,a=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[++t+1])a+=n.length;r.push(new Or(i,a))}}r.length>0&&t.clients.set(n,r)}),t},Rr=(e,t)=>{b(e.restEncoder,t.clients.size),f(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),b(e.restEncoder,t);let r=n.length;b(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},zr=e=>{let t=new kr,n=T(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=T(e.restDecoder),r=T(e.restDecoder);if(r>0){let i=k(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new Or(e.readDsClock(),e.readDsLen()))}}return t},Br=(e,t,n)=>{let r=new kr,i=T(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=T(e.restDecoder),a=T(e.restDecoder),o=n.clients.get(i)||[],s=R(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&Fr(r,i,s,a-s);let e=z(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,Po(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<a);)c.deleted||(a<c.id.clock+c.length&&o.splice(e,0,Po(t,c,a-c.id.clock)),c.delete(t))}else Fr(r,i,n,a-n)}}if(r.clients.size>0){let e=new Xr;return b(e.restEncoder,0),Rr(e,r),e.toUint8Array()}return null},Vr=xt;var Hr=class e extends et{constructor({guid:e=St(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:a=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=Vr(),this.guid=e,this.collectionid=t,this.share=/* @__PURE__ */ new Map,this.store=new Ti,this._transaction=null,this._transactionCleanups=[],this.subdocs=/* @__PURE__ */ new Set,this._item=null,this.shouldLoad=o,this.autoLoad=a,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Ct(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>Ct(e=>{let t=n=>{(n===void 0||n===!0)&&(this.off(`sync`,t),e())};this.on(`sync`,t)});this.on(`sync`,e=>{e===!1&&this.isSynced&&(this.whenSynced=s()),this.isSynced=e===void 0||e===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=s()}load(){let e=this._item;e!==null&&!this.shouldLoad&&V(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(f(this.subdocs).map(e=>e.guid))}transact(e,t=null){return V(this,e,t)}get(e,t=W){let n=k(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==W&&r!==t){if(r===W){let r=new t;r._map=n._map,n._map.forEach(e=>{for(;e!==null;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;e!==null;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}throw Error(`Type with the name ${e} has already been defined with a different constructor`)}return n}getArray(e=``){return this.get(e,Da)}getText(e=``){return this.get(e,qa)}getMap(e=``){return this.get(e,Aa)}getXmlElement(e=``){return this.get(e,Qa)}getXmlFragment(e=``){return this.get(e,Xa)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,f(this.subdocs).forEach(e=>e.destroy());let t=this._item;if(t!==null){this._item=null;let n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,V(t.parent.doc,e=>{let r=n.doc;t.deleted||e.subdocsAdded.add(r),e.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}},Ur=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return T(this.restDecoder)}readDsLen(){return T(this.restDecoder)}},Wr=class extends Ur{readLeftID(){return L(T(this.restDecoder),T(this.restDecoder))}readRightID(){return L(T(this.restDecoder),T(this.restDecoder))}readClient(){return T(this.restDecoder)}readInfo(){return He(this.restDecoder)}readString(){return E(this.restDecoder)}readParentInfo(){return T(this.restDecoder)===1}readTypeRef(){return T(this.restDecoder)}readLen(){return T(this.restDecoder)}readAny(){return Ke(this.restDecoder)}readBuf(){return Kt(w(this.restDecoder))}readJSON(){return JSON.parse(E(this.restDecoder))}readKey(){return E(this.restDecoder)}},Gr=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=T(this.restDecoder),this.dsCurrVal}readDsLen(){let e=T(this.restDecoder)+1;return this.dsCurrVal+=e,e}},Kr=class extends Gr{constructor(e){super(e),this.keys=[],T(e),this.keyClockDecoder=new Ye(w(e)),this.clientDecoder=new Je(w(e)),this.leftClockDecoder=new Ye(w(e)),this.rightClockDecoder=new Ye(w(e)),this.infoDecoder=new qe(w(e),He),this.stringDecoder=new Xe(w(e)),this.parentInfoDecoder=new qe(w(e),He),this.typeRefDecoder=new Je(w(e)),this.lenDecoder=new Je(w(e))}readLeftID(){return new yi(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new yi(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Ke(this.restDecoder)}readBuf(){return w(this.restDecoder)}readJSON(){return Ke(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{let e=this.stringDecoder.read();return this.keys.push(e),e}}},qr=class{constructor(){this.restEncoder=_()}toUint8Array(){return v(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){b(this.restEncoder,e)}writeDsLen(e){b(this.restEncoder,e)}},Jr=class extends qr{writeLeftID(e){b(this.restEncoder,e.client),b(this.restEncoder,e.clock)}writeRightID(e){b(this.restEncoder,e.client),b(this.restEncoder,e.clock)}writeClient(e){b(this.restEncoder,e)}writeInfo(e){_e(this.restEncoder,e)}writeString(e){x(this.restEncoder,e)}writeParentInfo(e){b(this.restEncoder,+!!e)}writeTypeRef(e){b(this.restEncoder,e)}writeLen(e){b(this.restEncoder,e)}writeAny(e){Oe(this.restEncoder,e)}writeBuf(e){S(this.restEncoder,e)}writeJSON(e){x(this.restEncoder,JSON.stringify(e))}writeKey(e){x(this.restEncoder,e)}},Yr=class{constructor(){this.restEncoder=_(),this.dsCurrVal=0}toUint8Array(){return v(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,b(this.restEncoder,t)}writeDsLen(e){e===0&&g(),b(this.restEncoder,e-1),this.dsCurrVal+=e}},Xr=class extends Yr{constructor(){super(),this.keyMap=/* @__PURE__ */ new Map,this.keyClock=0,this.keyClockEncoder=new Ne,this.clientEncoder=new je,this.leftClockEncoder=new Ne,this.rightClockEncoder=new Ne,this.infoEncoder=new ke(_e),this.stringEncoder=new Pe,this.parentInfoEncoder=new ke(_e),this.typeRefEncoder=new je,this.lenEncoder=new je}toUint8Array(){let e=_();return b(e,0),S(e,this.keyClockEncoder.toUint8Array()),S(e,this.clientEncoder.toUint8Array()),S(e,this.leftClockEncoder.toUint8Array()),S(e,this.rightClockEncoder.toUint8Array()),S(e,v(this.infoEncoder)),S(e,this.stringEncoder.toUint8Array()),S(e,v(this.parentInfoEncoder)),S(e,this.typeRefEncoder.toUint8Array()),S(e,this.lenEncoder.toUint8Array()),xe(e,v(this.restEncoder)),v(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(+!!e)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Oe(this.restEncoder,e)}writeBuf(e){S(this.restEncoder,e)}writeJSON(e){Oe(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}};const Zr=(e,t,n,i)=>{i=r(i,t[0].id.clock);let a=z(t,i);b(e.restEncoder,t.length-a),e.writeClient(n),b(e.restEncoder,i);let o=t[a];o.write(e,i-o.id.clock);for(let n=a+1;n<t.length;n++)t[n].write(e,0)},Qr=(e,t,n)=>{let r=/* @__PURE__ */ new Map;n.forEach((e,n)=>{R(t,n)>e&&r.set(n,e)}),Ei(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),b(e.restEncoder,r.size),f(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{Zr(e,t.clients.get(n),n,r)})},$r=(e,t)=>{let n=O(),r=T(e.restDecoder);for(let i=0;i<r;i++){let r=T(e.restDecoder),i=Array(r),a=e.readClient(),o=T(e.restDecoder);n.set(a,{i:0,refs:i});for(let n=0;n<r;n++){let r=e.readInfo();switch(31&r){case 0:{let t=e.readLen();i[n]=new K(L(a,o),t),o+=t;break}case 10:{let t=T(e.restDecoder);i[n]=new Y(L(a,o),t),o+=t;break}default:{let s=!(r&192),c=new J(L(a,o),null,(r&128)==128?e.readLeftID():null,null,(r&64)==64?e.readRightID():null,s?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,s&&(r&32)==32?e.readString():null,Fo(e,r));i[n]=c,o+=c.length}}}}return n},ei=(e,t,n)=>{let r=[],i=f(n.keys()).sort((e,t)=>e-t);if(i.length===0)return null;let a=()=>{if(i.length===0)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;)if(i.pop(),i.length>0)e=n.get(i[i.length-1]);else return null;return e},o=a();if(o===null)return null;let s=new Ti,c=/* @__PURE__ */ new Map,l=(e,t)=>{let n=c.get(e);(n==null||n>t)&&c.set(e,t)},u=o.refs[o.i++],d=/* @__PURE__ */ new Map,ee=()=>{for(let e of r){let t=e.id.client,r=n.get(t);r?(r.i--,s.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):s.clients.set(t,[e]),i=i.filter(e=>e!==t)}r.length=0};for(;;){if(u.constructor!==Y){let i=k(d,u.id.client,()=>R(t,u.id.client))-u.id.clock;if(i<0)r.push(u),l(u.id.client,u.id.clock-1),ee();else{let a=u.getMissing(e,t);if(a!==null){r.push(u);let e=n.get(a)||{refs:[],i:0};if(e.refs.length===e.i)l(a,R(t,a)),ee();else{u=e.refs[e.i++];continue}}else(i===0||i<u.length)&&(u.integrate(e,i),d.set(u.id.client,u.id.clock+u.length))}}if(r.length>0)u=r.pop();else if(o!==null&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=a(),o===null)break;u=o.refs[o.i++]}}if(s.clients.size>0){let e=new Xr;return Qr(e,s,/* @__PURE__ */ new Map),b(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},ti=(e,t)=>Qr(e,t.doc.store,t.beforeState),ni=(e,t,n,r=new Kr(e))=>V(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=$r(r,n),o=ei(e,i,a),s=i.pendingStructs;if(s){for(let[e,n]of s.missing)if(n<R(i,e)){t=!0;break}if(o){for(let[e,t]of o.missing){let n=s.missing.get(e);(n==null||n>t)&&s.missing.set(e,t)}s.update=Gi([s.update,o.update])}}else i.pendingStructs=o;let c=Br(r,e,i);if(i.pendingDs){let t=new Kr(C(i.pendingDs));T(t.restDecoder);let n=Br(t,e,i);i.pendingDs=c&&n?Gi([c,n]):c||n}else i.pendingDs=c;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,ri(e.doc,t)}},n,!1),ri=(e,t,n,r=Kr)=>{let i=C(t);ni(i,e,n,new r(i))},ii=(e,t,n)=>ri(e,t,n,Wr),ai=(e,t,n=/* @__PURE__ */ new Map)=>{Qr(e,t.store,n),Rr(e,Lr(t.store))},oi=(e,t=new Uint8Array([0]),n=new Xr)=>{let r=li(t);ai(n,e,r);let i=[n.toUint8Array()];if(e.store.pendingDs&&i.push(e.store.pendingDs),e.store.pendingStructs&&i.push(Ki(e.store.pendingStructs.update,t)),i.length>1){if(n.constructor===Jr)return Ui(i.map((e,t)=>t===0?e:Xi(e)));if(n.constructor===Xr)return Gi(i)}return i[0]},si=(e,t)=>oi(e,t,new Jr),ci=e=>{let t=/* @__PURE__ */ new Map,n=T(e.restDecoder);for(let r=0;r<n;r++){let n=T(e.restDecoder),r=T(e.restDecoder);t.set(n,r)}return t},li=e=>ci(new Ur(C(e))),ui=(e,t)=>(b(e.restEncoder,t.size),f(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{b(e.restEncoder,t),b(e.restEncoder,n)}),e),di=(e,t)=>ui(e,Ei(t.store)),fi=(e,t=new Yr)=>(e instanceof Map?ui(t,e):di(t,e),t.toUint8Array()),pi=e=>fi(e,new qr);var mi=class{constructor(){this.l=[]}};const hi=()=>new mi,gi=(e,t)=>e.l.push(t),_i=(e,t)=>{let n=e.l,r=n.length;e.l=n.filter(e=>t!==e),r===e.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},vi=(e,t,n)=>gt(e.l,[t,n]);var yi=class{constructor(e,t){this.client=e,this.clock=t}};const bi=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,L=(e,t)=>new yi(e,t),xi=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw g()};var Si=class{constructor(e,t){this.ds=e,this.sv=t}};((e,t)=>new Si(e,t))(Ir(),/* @__PURE__ */ new Map);const Ci=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Mr(t.ds,e.id),wi=(e,t)=>{let n=k(e.meta,wi,l),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<R(r,n)&&B(e,L(n,t))}),Ar(e,t.ds,e=>{}),n.add(t))};var Ti=class{constructor(){this.clients=/* @__PURE__ */ new Map,this.pendingStructs=null,this.pendingDs=null}};const Ei=e=>{let t=/* @__PURE__ */ new Map;return e.clients.forEach((e,n)=>{let r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},R=(e,t)=>{let n=e.clients.get(t);if(n===void 0)return 0;let r=n[n.length-1];return r.id.clock+r.length},Di=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{let e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw g()}n.push(t)},z=(t,n)=>{let r=0,i=t.length-1,a=t[i],o=a.id.clock;if(o===n)return i;let s=e(n/(o+a.length-1)*i);for(;r<=i;){if(a=t[s],o=a.id.clock,o<=n){if(n<o+a.length)return s;r=s+1}else i=s-1;s=e((r+i)/2)}throw g()},Oi=(e,t)=>{let n=e.clients.get(t.client);return n[z(n,t.clock)]},ki=(e,t,n)=>{let r=z(t,n),i=t[r];return i.id.clock<n&&i instanceof J?(t.splice(r+1,0,Po(e,i,n-i.id.clock)),r+1):r},B=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[ki(e,n,t.clock)]},Ai=(e,t,n)=>{let r=t.clients.get(n.client),i=z(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==K&&r.splice(i+1,0,Po(e,a,n.clock-a.id.clock+1)),a},ji=(e,t,n)=>{let r=e.clients.get(t.id.client);r[z(r,t.id.clock)]=n},Mi=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=ki(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&ki(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)};var Ni=class{constructor(e,t,n){this.doc=e,this.deleteSet=new kr,this.beforeState=Ei(e.store),this.afterState=/* @__PURE__ */ new Map,this.changed=/* @__PURE__ */ new Map,this.changedParentTypes=/* @__PURE__ */ new Map,this._mergeStructs=[],this.origin=t,this.meta=/* @__PURE__ */ new Map,this.local=n,this.subdocsAdded=/* @__PURE__ */ new Set,this.subdocsRemoved=/* @__PURE__ */ new Set,this.subdocsLoaded=/* @__PURE__ */ new Set,this._needFormattingCleanup=!1}};const Pi=(e,t)=>t.deleteSet.clients.size===0&&!$e(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(Nr(t.deleteSet),ti(e,t),Rr(e,t.deleteSet),!0),Fi=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&k(e.changed,t,l).add(n)},Ii=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0&&r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n);n=r,r=e[--i-1])n instanceof J&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);let a=t-i;return a&&e.splice(t+1-a,a),a},Li=(e,t,n)=>{for(let[r,i]of e.clients.entries()){let e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){let a=i[r],o=a.clock+a.len;for(let r=z(e,a.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){let i=e[r];if(a.clock+a.len<=i.id.clock)break;i instanceof J&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},Ri=(e,t)=>{e.clients.forEach((e,r)=>{let i=t.clients.get(r);for(let t=e.length-1;t>=0;t--){let r=e[t],a=n(i.length-1,1+z(i,r.clock+r.len-1));for(let e=a,t=i[e];e>0&&t.id.clock>=r.clock;t=i[e])e-=1+Ii(i,e)}})},zi=(e,t)=>{if(t<e.length){let n=e[t],i=n.doc,a=i.store,o=n.deleteSet,s=n._mergeStructs;try{Nr(o),n.afterState=Ei(n.doc.store),i.emit(`beforeObserverCalls`,[n,i]);let e=[];n.changed.forEach((t,r)=>e.push(()=>{r._item!==null&&r._item.deleted||r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(r._item===null||!r._item.deleted)&&e.push(()=>{t=t.filter(e=>e.target._item===null||!e.target._item.deleted),t.forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),vi(r._dEH,t,n)})}),e.push(()=>i.emit(`afterTransaction`,[n,i])),e.push(()=>{n._needFormattingCleanup&&Wa(n)})}),gt(e,[])}finally{i.gc&&Li(o,a,i.gcFilter),Ri(o,a),n.afterState.forEach((e,t)=>{let i=n.beforeState.get(t)||0;if(i!==e){let e=a.clients.get(t),n=r(z(e,i),1);for(let t=e.length-1;t>=n;)t-=1+Ii(e,t)}});for(let e=s.length-1;e>=0;e--){let{client:t,clock:n}=s[e].id,r=a.clients.get(t),i=z(r,n);i+1<r.length&&Ii(r,i+1)>1||i>0&&Ii(r,i)}if(!n.local&&n.afterState.get(i.clientID)!==n.beforeState.get(i.clientID)&&(Sr(_r,ur,`[yjs] `,dr,hr,`Changed the client-id because another client seems to be using it.`),i.clientID=Vr()),i.emit(`afterTransactionCleanup`,[n,i]),i._observers.has(`update`)){let e=new Jr;Pi(e,n)&&i.emit(`update`,[e.toUint8Array(),n.origin,i,n])}if(i._observers.has(`updateV2`)){let e=new Xr;Pi(e,n)&&i.emit(`updateV2`,[e.toUint8Array(),n.origin,i,n])}let{subdocsAdded:c,subdocsLoaded:l,subdocsRemoved:u}=n;(c.size>0||u.size>0||l.size>0)&&(c.forEach(e=>{e.clientID=i.clientID,e.collectionid??=i.collectionid,i.subdocs.add(e)}),u.forEach(e=>i.subdocs.delete(e)),i.emit(`subdocs`,[{loaded:l,added:c,removed:u},i,n]),u.forEach(e=>e.destroy())),e.length<=t+1?(i._transactionCleanups=[],i.emit(`afterAllTransactions`,[i,e])):zi(e,t+1)}}},V=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new Ni(e,n,r),i.push(e._transaction),i.length===1&&e.emit(`beforeAllTransactions`,[e]),e.emit(`beforeTransaction`,[e._transaction,e]));try{o=t(e._transaction)}finally{if(a){let t=e._transaction===i[0];e._transaction=null,t&&zi(i,0)}}return o};function*Bi(e){let t=T(e.restDecoder);for(let n=0;n<t;n++){let t=T(e.restDecoder),n=e.readClient(),r=T(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=T(e.restDecoder);yield new Y(L(n,r),t),r+=t}else if(31&t){let i=!(t&192),a=new J(L(n,r),null,(t&128)==128?e.readLeftID():null,null,(t&64)==64?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&(t&32)==32?e.readString():null,Fo(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new K(L(n,r),t),r+=t}}}}var Vi=class{constructor(e,t){this.gen=Bi(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===Y);return this.curr}},Hi=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const Ui=e=>Gi(e,Wr,Jr),Wi=(e,t)=>{if(e.constructor===K){let{client:n,clock:r}=e.id;return new K(L(n,r+t),e.length-t)}if(e.constructor===Y){let{client:n,clock:r}=e.id;return new Y(L(n,r+t),e.length-t)}{let n=e,{client:r,clock:i}=n.id;return new J(L(r,i+t),null,L(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Gi=(e,t=Kr,n=Xr)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(C(e))),i=r.map(e=>new Vi(e,!0)),a=null,o=new n,s=new Hi(o);for(;i=i.filter(e=>e.curr!==null),i.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){let n=e.curr.id.clock-t.curr.id.clock;return n===0?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===Y?1:-1:n}return t.curr.id.client-e.curr.id.client}),i.length!==0;){let e=i[0],t=e.curr.id.client;if(a!==null){let n=e.curr,r=!1;for(;n!==null&&n.id.clock+n.length<=a.struct.id.clock+a.struct.length&&n.id.client>=a.struct.id.client;)n=e.next(),r=!0;if(n===null||n.id.client!==t||r&&n.id.clock>a.struct.id.clock+a.struct.length)continue;if(t!==a.struct.id.client)H(s,a.struct,a.offset),a={struct:n,offset:0},e.next();else if(a.struct.id.clock+a.struct.length<n.id.clock){if(a.struct.constructor===Y)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{H(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new Y(L(t,a.struct.id.clock+a.struct.length),e),offset:0}}}else{let t=a.struct.id.clock+a.struct.length-n.id.clock;t>0&&(a.struct.constructor===Y?a.struct.length-=t:n=Wi(n,t)),a.struct.mergeWith(n)||(H(s,a.struct,a.offset),a={struct:n,offset:0},e.next())}}else a={struct:e.curr,offset:0},e.next();for(let n=e.curr;n!==null&&n.id.client===t&&n.id.clock===a.struct.id.clock+a.struct.length&&n.constructor!==Y;n=e.next())H(s,a.struct,a.offset),a={struct:n,offset:0}}a!==null&&(H(s,a.struct,a.offset),a=null),Ji(s);let c=r.map(e=>zr(e)),l=Pr(c);return Rr(o,l),o.toUint8Array()},Ki=(e,t,n=Kr,i=Xr)=>{let a=li(t),o=new i,s=new Hi(o),c=new n(C(e)),l=new Vi(c,!1);for(;l.curr;){let e=l.curr,t=e.id.client,n=a.get(t)||0;if(l.curr.constructor===Y)l.next();else if(e.id.clock+e.length>n)for(H(s,e,r(n-e.id.clock,0)),l.next();l.curr&&l.curr.id.client===t;)H(s,l.curr,0),l.next();else for(;l.curr&&l.curr.id.client===t&&l.curr.id.clock+l.curr.length<=n;)l.next()}Ji(s);let u=zr(c);return Rr(o,u),o.toUint8Array()},qi=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:v(e.encoder.restEncoder)}),e.encoder.restEncoder=_(),e.written=0)},H=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&qi(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),b(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Ji=e=>{qi(e);let t=e.encoder.restEncoder;b(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];b(t,r.written),xe(t,r.restEncoder)}},Yi=(e,t,n,r)=>{let i=new n(C(e)),a=new Vi(i,!1),o=new r,s=new Hi(o);for(let e=a.curr;e!==null;e=a.next())H(s,t(e),0);Ji(s);let c=zr(i);return Rr(o,c),o.toUint8Array()},Xi=e=>Yi(e,_t,Kr,Jr),Zi=`You must not compute changes after the event-handler fired.`;var Qi=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||=$i(this.currentTarget,this.target)}deletes(e){return Mr(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw m(Zi);let e=/* @__PURE__ */ new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(n!==null){let r=t._map.get(n),i,a;if(this.adds(r)){let e=r.left;for(;e!==null&&this.adds(e);)e=e.left;if(this.deletes(r)){if(e!==null&&this.deletes(e))i=`delete`,a=u(e.content.getContent());else return}else e!==null&&this.deletes(e)?(i=`update`,a=u(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=u(r.content.getContent());else return;e.set(n,{action:i,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw m(Zi);let t=this.target,n=l(),r=l(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null,a=()=>{e&&i.push(e)};for(let i=t._start;i!==null;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&((e===null||e.delete===void 0)&&(a(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?((e===null||e.insert===void 0)&&(a(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):((e===null||e.retain===void 0)&&(a(),e={retain:0}),e.retain+=i.length);e!==null&&e.retain===void 0&&a()}this._changes=e}return e}};const $i=(e,t)=>{let n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},U=()=>{Cr(`Invalid access: Add Yjs type to a document before reading data.`)};let ea=0;var ta=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=ea++}};const na=e=>{e.timestamp=ea++},ra=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ea++},ia=(e,t,n)=>{if(e.length>=80){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return ra(r,t,n),r}{let r=new ta(t,n);return e.push(r),r}},aa=(e,n)=>{if(e._start===null||n===0||e._searchMarker===null)return null;let r=e._searchMarker.length===0?null:e._searchMarker.reduce((e,r)=>t(n-e.index)<t(n-r.index)?e:r),i=e._start,a=0;for(r!==null&&(i=r.p,a=r.index,na(r));i.right!==null&&a<n;){if(!i.deleted&&i.countable){if(n<a+i.length)break;a+=i.length}i=i.right}for(;i.left!==null&&a>n;)i=i.left,!i.deleted&&i.countable&&(a-=i.length);for(;i.left!==null&&i.left.id.client===i.id.client&&i.left.id.clock+i.left.length===i.id.clock;)i=i.left,!i.deleted&&i.countable&&(a-=i.length);return r!==null&&t(r.index-a)<i.parent.length/80?(ra(r,i,a),r):ia(e._searchMarker,i,a)},oa=(e,t,n)=>{for(let i=e.length-1;i>=0;i--){let a=e[i];if(n>0){let t=a.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(a.index-=t.length);if(t===null||t.marker===!0){e.splice(i,1);continue}a.p=t,t.marker=!0}(t<a.index||n>0&&t===a.index)&&(a.index=r(t,a.index+n))}},sa=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;k(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;vi(r._eH,n,t)};var W=class{constructor(){this._item=null,this._map=/* @__PURE__ */ new Map,this._start=null,this.doc=null,this._length=0,this._eH=hi(),this._dEH=hi(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw h()}clone(){throw h()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){gi(this._eH,e)}observeDeep(e){gi(this._dEH,e)}unobserve(e){_i(this._eH,e)}unobserveDeep(e){_i(this._dEH,e)}toJSON(){}};const ca=(e,t,n)=>{e.doc??U(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t,i=[],a=e._start;for(;a!==null&&r>0;){if(a.countable&&!a.deleted){let e=a.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}a=a.right}return i},la=e=>{e.doc??U();let t=[],n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){let e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},ua=(e,t)=>{let n=0,r=e._start;for(e.doc??U();r!==null;){if(r.countable&&!r.deleted){let i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},da=(e,t)=>{let n=[];return ua(e,(r,i)=>{n.push(t(r,i,e))}),n},fa=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}let e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},pa=(e,t)=>{e.doc??U();let n=aa(e,t),r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},ma=(e,t,n,r)=>{let i=n,a=e.doc,o=a.clientID,s=a.store,c=n===null?t._start:n.right,l=[],u=()=>{l.length>0&&(i=new J(L(o,R(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new bo(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(n===null)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(u(),n.constructor){case Uint8Array:case ArrayBuffer:i=new J(L(o,R(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new oo(new Uint8Array(n))),i.integrate(e,0);break;case Hr:i=new J(L(o,R(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new fo(n)),i.integrate(e,0);break;default:if(n instanceof W)i=new J(L(o,R(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Mo(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},ha=()=>m(`Length exceeded!`),ga=(e,t,n,r)=>{if(n>t._length)throw ha();if(n===0)return t._searchMarker&&oa(t._searchMarker,n,r.length),ma(e,t,null,r);let i=n,a=aa(t,n),o=t._start;for(a!==null&&(o=a.p,n-=a.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&B(e,L(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&oa(t._searchMarker,i,r.length),ma(e,t,o,r)},_a=(e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return ma(e,t,r,n)},va=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=aa(t,n),s=t._start;for(o!==null&&(s=o.p,n-=o.index);s!==null&&n>0;s=s.right)!s.deleted&&s.countable&&(n<s.length&&B(e,L(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&B(e,L(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw ha();t._searchMarker&&oa(t._searchMarker,i,-a+r)},ya=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},ba=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new bo([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new bo([r]);break;case Uint8Array:s=new oo(r);break;case Hr:s=new fo(r);break;default:if(r instanceof W)s=new Mo(r);else throw Error(`Unexpected content type`)}new J(L(o,R(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},xa=(e,t)=>{e.doc??U();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Sa=e=>{let t={};return e.doc??U(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},Ca=(e,t)=>{e.doc??U();let n=e._map.get(t);return n!==void 0&&!n.deleted},wa=(e,t)=>{let n={};return e._map.forEach((e,r)=>{let i=e;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&Ci(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Ta=e=>(e.doc??U(),Er(e._map.entries(),e=>!e[1].deleted));var Ea=class extends Qi{},Da=class e extends W{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let n=new e;return n.push(t),n}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof W?e.clone():e)),t}get length(){return this.doc??U(),this._length}_callObserver(e,t){super._callObserver(e,t),sa(this,e,new Ea(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):V(this.doc,n=>{ga(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):V(this.doc,t=>{_a(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):V(this.doc,n=>{va(n,this,e,t)})}get(e){return pa(this,e)}toArray(){return la(this)}slice(e=0,t=this.length){return ca(this,e,t)}toJSON(){return this.map(e=>e instanceof W?e.toJSON():e)}map(e){return da(this,e)}forEach(e){ua(this,e)}[Symbol.iterator](){return fa(this)}_write(e){e.writeTypeRef(To)}};const Oa=e=>new Da;var ka=class extends Qi{constructor(e,t,n){super(e,t),this.keysChanged=n}},Aa=class e extends W{constructor(e){super(),this._prelimContent=null,this._prelimContent=e===void 0?/* @__PURE__ */ new Map:new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof W?e.clone():e)}),t}_callObserver(e,t){sa(this,e,new ka(this,e,t))}toJSON(){this.doc??U();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof W?r.toJSON():r}}),e}get size(){return[...Ta(this)].length}keys(){return Dr(Ta(this),e=>e[0])}values(){return Dr(Ta(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return Dr(Ta(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??U(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc===null?this._prelimContent.delete(e):V(this.doc,t=>{ya(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):V(this.doc,n=>{ba(n,this,e,t)}),t}get(e){return xa(this,e)}has(e){return Ca(this,e)}clear(){this.doc===null?this._prelimContent.clear():V(this.doc,e=>{this.forEach(function(t,n,r){ya(e,r,n)})})}_write(e){e.writeTypeRef(Eo)}};const ja=e=>new Aa,G=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&pt(e,t);var Ma=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&g(),this.right.content.constructor){case q:this.right.deleted||Ia(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length)}this.left=this.right,this.right=this.right.right}};const Na=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case q:t.right.deleted||Ia(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&B(e,L(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length)}t.left=t.right,t.right=t.right.right}return t},Pa=(e,t,n,r)=>{let i=/* @__PURE__ */ new Map,a=r?aa(t,n):null;if(a){let t=new Ma(a.p.left,a.p,a.index,i);return Na(e,t,n-a.index)}{let r=new Ma(null,t._start,0,i);return Na(e,r,n)}},Fa=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===q&&G(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();let i=e.doc,a=i.clientID;r.forEach((r,o)=>{let s=n.left,c=n.right,l=new J(L(a,R(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new q(o,r));l.integrate(e,0),n.right=l,n.forward()})},Ia=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},La=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===q&&G(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Ra=(e,t,n,r)=>{let i=e.doc,a=i.clientID,o=/* @__PURE__ */ new Map;for(let s in r){let c=r[s],l=n.currentAttributes.get(s)??null;if(!G(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new J(L(a,R(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new q(s,c)),n.right.integrate(e,0),n.forward()}}return o},za=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;La(n,i);let s=Ra(e,t,n,i),c=r.constructor===String?new So(r):r instanceof W?new Mo(r):new mo(r),{left:l,right:u,index:d}=n;t._searchMarker&&oa(t._searchMarker,n.index,c.getLength()),u=new J(L(o,R(a.store,o)),l,l&&l.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=d,n.forward(),Fa(e,t,n,s)},Ba=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;La(n,i);let s=Ra(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===q));){if(!n.right.deleted)switch(n.right.content.constructor){case q:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(G(o,a))s.delete(t);else{if(r===0)break iterationLoop;s.set(t,a)}n.right.delete(e)}else n.currentAttributes.set(t,a);break}default:r<n.right.length&&B(e,L(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let i=``;for(;r>0;r--)i+=`
46
46
  `;n.right=new J(L(o,R(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new So(i)),n.right.integrate(e,0),n.forward()}Fa(e,t,n,s)},Va=(e,t,n,r,i)=>{let a=t,o=O();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===q){let e=a.content;o.set(e.key,e)}a=a.right}let s=0,c=!1;for(;t!==a;){if(n===t&&(c=!0),!t.deleted){let n=t.content;switch(n.constructor){case q:{let{key:a,value:l}=n,u=r.get(a)??null;(o.get(a)!==n||u===l)&&(t.delete(e),s++,!c&&(i.get(a)??null)===l&&u!==l&&(u===null?i.delete(a):i.set(a,u))),!c&&!t.deleted&&Ia(i,n);break}}}t=t.right}return s},Ha=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let n=/* @__PURE__ */ new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===q){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},Ua=e=>{let t=0;return V(e.doc,n=>{let r=e._start,i=e._start,a=O(),o=Ze(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case q:Ia(o,i.content);break;default:t+=Va(n,r,i,a,o),a=Ze(o),r=i}i=i.right}}),t},Wa=e=>{let t=/* @__PURE__ */ new Set,n=e.doc;for(let[r,i]of e.afterState.entries()){let a=e.beforeState.get(r)||0;i!==a&&Mi(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===q&&e.constructor!==K&&t.add(e.parent)})}V(n,n=>{Ar(e,e.deleteSet,e=>{if(e instanceof K||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===q?t.add(r):Ha(n,e)});for(let e of t)Ua(e)})},Ga=(e,t,n)=>{let r=n,i=Ze(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Mo:case mo:case So:n<t.right.length&&B(e,L(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}a&&Va(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&oa(o._searchMarker,t.index,-r+n),t};var Ka=class extends Qi{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=/* @__PURE__ */ new Set,n.forEach(e=>{e===null?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(this._changes===null){let e={keys:this.keys,delta:this.delta,added:/* @__PURE__ */ new Set,deleted:/* @__PURE__ */ new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];V(e,e=>{let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=this.target._start,a=null,o={},s=``,c=0,l=0,u=()=>{if(a!==null){let e=null;switch(a){case`delete`:l>0&&(e={delete:l}),l=0;break;case`insert`:(typeof s==`object`||s.length>0)&&(e={insert:s},n.size>0&&(e.attributes={},n.forEach((t,n)=>{t!==null&&(e.attributes[n]=t)}))),s=``;break;case`retain`:c>0&&(e={retain:c},ut(o)||(e.attributes=at({},o))),c=0}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case Mo:case mo:this.adds(i)?this.deletes(i)||(u(),a=`insert`,s=i.content.getContent()[0],u()):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=1):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=1);break;case So:this.adds(i)?this.deletes(i)||(a!==`insert`&&(u(),a=`insert`),s+=i.content.str):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=i.length):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=i.length);break;case q:{let{key:t,value:s}=i.content;if(this.adds(i)){if(!this.deletes(i)){let c=n.get(t)??null;G(c,s)?s!==null&&i.delete(e):(a===`retain`&&u(),G(s,r.get(t)??null)?delete o[t]:o[t]=s)}}else if(this.deletes(i)){r.set(t,s);let e=n.get(t)??null;G(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(G(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),Ia(n,i.content));break}}i=i.right}for(u();t.length>0;){let e=t[t.length-1];if(e.retain!==void 0&&e.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},qa=class e extends W{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??U(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){console.error(e)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);let n=new Ka(this,e,t);sa(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??U();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===So&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc===null?this._pending.push(()=>this.applyDelta(e)):V(this.doc,n=>{let r=new Ma(null,this._start,0,/* @__PURE__ */ new Map);for(let i=0;i<e.length;i++){let a=e[i];if(a.insert!==void 0){let o=!t&&typeof a.insert==`string`&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
47
47
  `?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&za(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&Ga(n,r,a.delete):Ba(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??U();let r=[],i=/* @__PURE__ */ new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(Ci(s,e)||t!==void 0&&Ci(s,t))switch(s.content.constructor){case So:{let r=i.get(`ychange`);e!==void 0&&!Ci(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!Ci(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case Mo:case mo:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case q:Ci(s,e)&&(c(),Ia(i,s.content))}s=s.right}c()};return e||t?V(a,n=>{e&&wi(n,e),t&&wi(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):V(r,r=>{let i=Pa(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),za(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):V(r,r=>{let i=Pa(r,this,e,!n);za(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):V(n,n=>{Ga(n,Pa(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):V(r,r=>{let i=Pa(r,this,e,!1);i.right!==null&&Ba(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):V(this.doc,t=>{ya(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):V(this.doc,n=>{ba(n,this,e,t)})}getAttribute(e){return xa(this,e)}getAttributes(){return Sa(this)}_write(e){e.writeTypeRef(Do)}};const Ja=e=>new qa;var Ya=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??U()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===Qa||t.constructor===Xa)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},Xa=class e extends W{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof W?e.clone():e)),t}get length(){return this.doc??U(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Ya(this,e)}querySelector(e){e=e.toUpperCase();let t=new Ya(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),f(new Ya(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){sa(this,e,new eo(this,t,e))}toString(){return da(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),ua(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):V(this.doc,n=>{ga(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)V(this.doc,n=>{let r=e&&e instanceof W?e._item:e;ma(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw m(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):V(this.doc,n=>{va(n,this,e,t)})}toArray(){return la(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return pa(this,e)}slice(e=0,t=this.length){return ca(this,e,t)}forEach(e){ua(this,e)}_write(e){e.writeTypeRef(ko)}};const Za=e=>new Xa;var Qa=class e extends Xa{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=/* @__PURE__ */ new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName),n=this.getAttributes();return st(n,(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof W?e.clone():e)),t}toString(){let e=this.getAttributes(),t=[],n=[];for(let t in e)n.push(t);n.sort();let r=n.length;for(let i=0;i<r;i++){let r=n[i];t.push(r+`="`+e[r]+`"`)}let i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?` `+t.join(` `):``}>${super.toString()}</${i}>`}removeAttribute(e){this.doc===null?this._prelimAttrs.delete(e):V(this.doc,t=>{ya(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):V(this.doc,n=>{ba(n,this,e,t)})}getAttribute(e){return xa(this,e)}hasAttribute(e){return Ca(this,e)}getAttributes(e){return e?wa(this,e):Sa(this)}toDOM(e=document,t={},n){let r=e.createElement(this.nodeName),i=this.getAttributes();for(let e in i){let t=i[e];typeof t==`string`&&r.setAttribute(e,t)}return ua(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Oo),e.writeKey(this.nodeName)}};const $a=e=>new Qa(e.readKey());var eo=class extends Qi{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=/* @__PURE__ */ new Set,t.forEach(e=>{e===null?this.childListChanged=!0:this.attributesChanged.add(e)})}},to=class e extends Aa{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){let t=new e(this.hookName);return this.forEach((e,n)=>{t.set(n,e)}),t}toDOM(e=document,t={},n){let r=t[this.hookName],i;return i=r===void 0?document.createElement(this.hookName):r.createDom(this),i.setAttribute(`data-yjs-hook`,this.hookName),n!==void 0&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(Ao),e.writeKey(this.hookName)}};const no=e=>new to(e.readKey());var ro=class e extends qa{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,n){let r=e.createTextNode(this.toString());return n!==void 0&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{let t=[];for(let n in e.attributes){let r=[];for(let t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:n,attrs:r})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n=``;for(let e=0;e<t.length;e++){let r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){let t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=`>`}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n}).join(``)}toJSON(){return this.toString()}_write(e){e.writeTypeRef(jo)}};const io=e=>new ro;var ao=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw h()}mergeWith(e){return!1}write(e,t,n){throw h()}integrate(e,t){throw h()}},K=class extends ao{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Di(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},oo=class e{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(e){throw h()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}};const so=e=>new oo(e.readBuf());var co=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){let n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Fr(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}};const lo=e=>new co(e.readLen()),uo=(e,t)=>new Hr({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});var fo=class e{constructor(e){e._item&&console.error(`This document was already integrated as a sub-document. You should create a second instance instead with the same guid.`),this.doc=e;let t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(uo(this.doc.guid,this.opts))}splice(e){throw h()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}};const po=e=>new fo(uo(e.readString(),e.readAny()));var mo=class e{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(e){throw h()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}};const ho=e=>new mo(e.readJSON());var q=class e{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(e){throw h()}mergeWith(e){return!1}integrate(e,t){let n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}};const go=e=>new q(e.readKey(),e.readJSON());var _o=class e{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeString(t===void 0?`undefined`:JSON.stringify(t))}}getRef(){return 2}};const vo=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++){let t=e.readString();t===`undefined`?n.push(void 0):n.push(JSON.parse(t))}return new _o(n)},yo=Pt(`node_env`)===`development`;var bo=class e{constructor(e){this.arr=e,yo&&ht(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeAny(t)}}getRef(){return 8}};const xo=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new bo(n)};var So=class e{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split(``)}isCountable(){return!0}copy(){return new e(this.str)}splice(t){let n=new e(this.str.slice(t));this.str=this.str.slice(0,t);let r=this.str.charCodeAt(t-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+`�`,n.str=`�`+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}};const Co=e=>new So(e.readString()),wo=[Oa,ja,Ja,$a,Za,no,io],To=0,Eo=1,Do=2,Oo=3,ko=4,Ao=5,jo=6;var Mo=class e{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(e){throw h()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;t!==null;)t.gc(e,!0),t=t.left}),this.type._map=/* @__PURE__ */ new Map}write(e,t){this.type._write(e)}getRef(){return 7}};const No=e=>new Mo(wo[e.readTypeRef()](e)),Po=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new J(L(r,i+n),t,L(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&a.markDeleted(),t.keep&&(a.keep=!0),t.redone!==null&&(a.redone=L(t.redone.client,t.redone.clock+n)),t.right=a,a.right!==null&&(a.right.left=a),e._mergeStructs.push(a),a.parentSub!==null&&a.right===null&&a.parent._map.set(a.parentSub,a),t.length=n,a};var J=class e extends ao{constructor(e,t,n,r,i,a,o,s){super(e,s.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=a,this.parentSub=o,this.redone=null,this.content=s,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=R(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=R(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===yi&&this.id.client!==this.parent.client&&this.parent.clock>=R(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=Ai(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=B(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===K||this.right&&this.right.constructor===K)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===yi){let e=Oi(n,this.parent);this.parent=e.constructor===K?null:e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Ai(e,e.doc.store,L(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let t=this.left,n;if(t!==null)n=t.right;else if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start;let r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set;for(;n!==null&&n!==this.right;){if(i.add(n),r.add(n),bi(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(bi(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(Oi(e.doc.store,n.origin)))r.has(Oi(e.doc.store,n.origin))||(t=n,r.clear());else break;n=n.right}this.left=t}if(this.left!==null){let e=this.left.right;this.right=e,this.left.right=this}else{let e;if(this.parentSub!==null)for(e=this.parent._map.get(this.parentSub)||null;e!==null&&e.left!==null;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}this.right===null?this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)):this.right.left=this,this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Di(e.doc.store,this),this.content.integrate(e,this),Fi(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new K(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:L(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&bi(e.origin,this.lastId)&&this.right===e&&bi(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){let t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),Fr(e.deleteSet,this.id.client,this.id.clock,this.length),Fi(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw g();this.content.gc(e),t?ji(e,this,new K(this.id,this.length)):this.content=new co(this.length)}write(e,t){let n=t>0?L(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,a=this.content.getRef()&31|(n===null?0:128)|(r===null?0:64)|(i===null?0:32);if(e.writeInfo(a),n!==null&&e.writeLeftID(n),r!==null&&e.writeRightID(r),n===null&&r===null){let t=this.parent;if(t._item!==void 0){let n=t._item;if(n===null){let n=xi(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===yi?(e.writeParentInfo(!1),e.writeLeftID(t)):g();i!==null&&e.writeString(i)}this.content.write(e,t)}};const Fo=(e,t)=>Io[t&31](e),Io=[()=>{g()},lo,vo,so,Co,ho,go,No,xo,po,()=>{g()}];var Y=class extends ao{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){g()}write(e,t){e.writeInfo(10),b(e.restEncoder,this.length-t)}getMissing(e,t){return null}};const Lo=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},Ro=`__ $YJS$ __`;Lo[Ro]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),Lo[Ro]=!0;var zo=class extends tt{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=/* @__PURE__ */ new Map,this.meta=/* @__PURE__ */ new Map,this._checkInterval=setInterval(()=>{let e=D();this.getLocalState()!==null&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&Bo(this,t,`timeout`)},e(3e3)),t.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:D()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),vt(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}};const Bo=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:D()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},Vo=(e,t,n=e.states)=>{let r=t.length,i=_();b(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;b(i,r),b(i,s),x(i,JSON.stringify(o))}return v(i)},Ho=(e,t,n)=>{let r=C(t),i=D(),a=[],o=[],s=[],c=[],l=T(r);for(let t=0;t<l;t++){let t=T(r),n=T(r),l=JSON.parse(E(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(vt(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},Uo=/* @__PURE__ */ new Map;
48
48
  /* c8 ignore start */
@@ -50,4 +50,4 @@ var Wo=class{constructor(e){this.room=e,this.onmessage=null,this._onChange=t=>t.
50
50
  /* c8 ignore stop */
51
51
  /* c8 ignore next */
52
52
  const Go=typeof BroadcastChannel>`u`?Wo:BroadcastChannel,Ko=e=>k(Uo,e,()=>{let t=l(),n=new Go(e);return n.onmessage=e=>t.forEach(t=>t(e.data,`broadcastchannel`)),{bc:n,subs:t}}),qo=(e,t)=>(Ko(e).subs.add(t),t),Jo=(e,t)=>{let n=Ko(e),r=n.subs.delete(t);return r&&n.subs.size===0&&(n.bc.close(),Uo.delete(e)),r},Yo=(e,t,n=null)=>{let r=Ko(e);r.bc.postMessage(t),r.subs.forEach(e=>e(t,n))},Xo=(e,t)=>{b(e,0);let n=pi(t);S(e,n)},Zo=(e,t,n)=>{b(e,1),S(e,si(t,n))},Qo=(e,t,n)=>Zo(t,n,w(e)),$o=(e,t,n,r)=>{try{ii(t,w(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},es=(e,t)=>{b(e,2),S(e,t)},ts=$o,ns=(e,t,n,r,i)=>{let a=T(e);switch(a){case 0:Qo(e,t,n);break;case 1:$o(e,n,r,i);break;case 2:ts(e,n,r,i);break;default:throw Error(`Unknown message type`)}return a},rs=(e,t,n)=>{T(e)===0&&n(t,E(e))},is=e=>ct(e,(e,t)=>`${encodeURIComponent(t)}=${encodeURIComponent(e)}`).join(`&`),as=[];as[0]=(e,t,n,r,i)=>{b(e,0);let a=ns(t,e,n.doc,n);r&&a===1&&!n.synced&&(n.synced=!0)},as[3]=(e,t,n,r,i)=>{b(e,1),S(e,Vo(n.awareness,Array.from(n.awareness.getStates().keys())))},as[1]=(e,t,n,r,i)=>{Ho(n.awareness,w(t),n)},as[2]=(e,t,n,r,i)=>{rs(t,n.doc,(e,t)=>ss(n,t))};const os=3e4,ss=(e,t)=>console.warn(`Permission denied to access ${e.url}.\n${t}`),cs=(e,t,n)=>{let r=C(t),i=_(),a=T(r),o=e.messageHandlers[a];return o?o(i,r,e,n,a):console.error(`Unable to compute message`),i},ls=e=>!(e.code>=4400&&e.code<4500),us=(e,t,r)=>{if(t!==null&&t===e.ws){e.emit(`connection-close`,[r,e]),e.ws=null,t.onmessage=null,t.onopen=null,t.onclose=null,t.onerror=()=>{},t.close(),e.wsconnecting=!1,e.wsconnected&&(e.wsconnected=!1,e.synced=!1,Bo(e.awareness,Array.from(e.awareness.getStates().keys()).filter(t=>t!==e.doc.clientID),e),e.emit(`status`,[{status:`disconnected`}])),e.wsUnsuccessfulReconnects++;let a=null;r!=null&&!e.shouldReconnect(r,e)&&(e.shouldConnect=!1,a={code:r.code,reason:r.reason}),setTimeout(ds,n(i(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e),a!==null&&e.emit(`closed`,[a,e])}},ds=e=>{if(e.shouldConnect&&e.ws===null){let t=new e._WS(e.url,e.protocols);t.binaryType=`arraybuffer`,e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{if(e.ws!==t)return;e.wsLastMessageReceived=D();let r=cs(e,new Uint8Array(n.data),!0);he(r)>1&&t.send(v(r))},t.onerror=n=>{e.ws===t&&e.emit(`connection-error`,[n,e])},t.onclose=n=>{us(e,t,n)},t.onopen=()=>{if(e.ws!==t)return;e.wsLastMessageReceived=D(),e.wsconnecting=!1,e.wsconnected=!0,e.emit(`status`,[{status:`connected`}]);let n=_();if(b(n,0),Xo(n,e.doc),t.send(v(n)),e.awareness.getLocalState()!==null){let n=_();b(n,1),S(n,Vo(e.awareness,[e.doc.clientID])),t.send(v(n))}},e.emit(`status`,[{status:`connecting`}])}},fs=(e,t)=>{let n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&Yo(e.bcChannel,t,e)};var ps=class extends et{constructor(e,t,n,{connect:r=!0,awareness:i=new zo(n),params:a={},protocols:o=[],WebSocketPolyfill:s=WebSocket,resyncInterval:c=-1,maxBackoffTime:l=2500,disableBc:u=!1,shouldReconnect:d=ls}={}){for(super();e[e.length-1]===`/`;)e=e.slice(0,e.length-1);this.serverUrl=e,this.bcChannel=e+`/`+t,this.maxBackoffTime=l,this.shouldReconnect=d,this.params=a,this.protocols=o,this.roomname=t,this.doc=n,this._WS=s,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=as.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,c>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){let e=_();b(e,0),Xo(e,n),this.ws.send(v(e))}},c)),this._bcSubscriber=(e,t)=>{if(t!==this){let t=cs(this,new Uint8Array(e),!1);he(t)>1&&Yo(this.bcChannel,v(t),this)}},this._updateHandler=(e,t)=>{if(t!==this){let t=_();b(t,0),es(t,e),fs(this,v(t))}},this.doc.on(`update`,this._updateHandler),this._awarenessUpdateHandler=({added:e,updated:t,removed:n},r)=>{let a=e.concat(t).concat(n),o=_();b(o,1),S(o,Vo(i,a)),fs(this,v(o))},this._exitHandler=()=>{Bo(this.awareness,[n.clientID],`app closed`)},A&&typeof process<`u`&&process.on(`exit`,this._exitHandler),i.on(`update`,this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&os<D()-this.wsLastMessageReceived&&us(this,this.ws,null)},os/10),r&&this.connect()}get url(){let e=is(this.params);return this.serverUrl+`/`+this.roomname+(e.length===0?``:`?`+e)}get synced(){return this._synced}set synced(e){this._synced!==e&&(this._synced=e,e&&(this.wsUnsuccessfulReconnects=0),this.emit(`synced`,[e]),this.emit(`sync`,[e]))}destroy(){this._resyncInterval!==0&&clearInterval(this._resyncInterval),clearInterval(this._checkInterval),this.disconnect(),A&&typeof process<`u`&&process.off(`exit`,this._exitHandler),this.awareness.off(`update`,this._awarenessUpdateHandler),this.doc.off(`update`,this._updateHandler),super.destroy()}connectBc(){if(this.disableBc)return;this.bcconnected||=(qo(this.bcChannel,this._bcSubscriber),!0);let e=_();b(e,0),Xo(e,this.doc),Yo(this.bcChannel,v(e),this);let t=_();b(t,0),Zo(t,this.doc),Yo(this.bcChannel,v(t),this);let n=_();b(n,3),Yo(this.bcChannel,v(n),this);let r=_();b(r,1),S(r,Vo(this.awareness,[this.doc.clientID])),Yo(this.bcChannel,v(r),this)}disconnectBc(){let e=_();b(e,1),S(e,Vo(this.awareness,[this.doc.clientID],/* @__PURE__ */ new Map)),fs(this,v(e)),this.bcconnected&&=(Jo(this.bcChannel,this._bcSubscriber),!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&us(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(ds(this),this.connectBc())}};function ms(e,t=typeof __VITEHUB_APP_BASE_URL__>`u`?`/`:__VITEHUB_APP_BASE_URL__){return t===`/`?e:`${t.replace(/\/+$/,``)}${e}`}function hs(e,...t){return typeof e==`function`?e(...t):e}const gs=Error.captureStackTrace;var _s=class e extends Error{get why(){return this.message}constructor(t,n=e){super(t.why,{cause:t.cause}),this.code=this.name=t.code,this.docs=t.docs,this.fix=t.fix,this.sources=t.sources,this.data=t.data,gs?.(this,n)}toJSON(){return{name:this.name,why:this.why,fix:this.fix,docs:this.docs,sources:this.sources,cause:this.cause,data:this.data,stack:this.stack}}};function vs(e,t){return typeof e==`string`?`${e}/${t.toLowerCase()}`:e?.(t)}const ys=e=>t=>t instanceof _s&&e in t;/* @__NO_SIDE_EFFECTS__ */
53
- function bs(e){let t=e.reporters??[],n=Symbol(),r=Object.defineProperty({},"is",{value:ys(n)}),{docsBase:i}=e;for(let a of Object.keys(e.codes)){let o=e.codes[a],s=o.docs===!1?void 0:o.docs||vs(i,a),c=(e={},r={})=>{let i=new _s({code:a,why:hs(o.why,e),fix:hs(o.fix,e),docs:s,cause:e.cause,sources:e.sources,data:hs(o.data,e)},c);i[n]=1;for(let e of t)e(i,r);return i};c.is=e=>r.is(e)&&e.code===a,r[a]=c}return r}const X={why:({message:e})=>e===void 0?``:String(e)},xs=/*#__PURE__*/ bs({docsBase:`https://vitehub.dev/docs/runtime/diagnostics`,codes:{RUNTIME_R0001:{...X,fix:"Pass `maxDepth` to `normalizeRuntimeDiagnosticError()` as an integer of 0 or more, or remove it to use the default."},RUNTIME_R0002:{...X,fix:"Pass `maxErrors` to `normalizeRuntimeDiagnosticError()` as an integer of 1 or more, or remove it to use the default."},RUNTIME_R0003:{...X,fix:"Pass `maxStringLength` to `normalizeRuntimeDiagnosticError()` as an integer of 64 or more, or remove it to use the default."},RUNTIME_R0004:{...X,fix:"Read the logs of the process that `vitehub drain` waited for to find why its drain failed, then fix that failure and run `vitehub drain` again."},RUNTIME_R0005:{...X,fix:"Read the logs of the process that the message names to find why it stopped, then start it again before you run `vitehub drain`."},RUNTIME_R0006:{...X,fix:"Pass `new ViteHubError()` a nonempty `code` and `message` string within the length limits, and plain JSON `details`."},RUNTIME_R0007:{...X,fix:"Give the execution authority a valid value for each of `credentials`, `environment`, `filesystem.access`, `filesystem.scope`, `isolation`, `network`, and `processes`."},RUNTIME_R0009:{...X,fix:"Set `intervalMs` of the process reconciler to a number of milliseconds from 1 to 2147483647."},RUNTIME_R0010:{...X,fix:"Give the process reconciler a `signal` other than `SIGKILL` or `SIGSTOP`, or set `signal: false`."},RUNTIME_R0011:{...X,fix:"Call `drain()` of the process reconciler after its callback returns, not from inside the callback."},RUNTIME_R0015:{...X,fix:"Pass the `Request` of a Fetchable handler, or the event of an H3 or Nitro route, to `getStandardContext()`."},RUNTIME_R0016:{...X,fix:"Return the body or a `Response` from the handler, in place of setting `~standard.res.body`."},RUNTIME_R0017:X,RUNTIME_R0018:X,RUNTIME_CONSOLE_PATH_INVALID:{why:({value:e})=>`${e} is not a Console path. Use a path that starts with one /, such as /agents/<agent>.`,fix:"Pass `hostedConsoleUrl()` a Console path that starts with one `/`, such as `/kv` or `/agents/<agent>/invocations/<id>`."},RUNTIME_CONSOLE_PROJECT_URL_INVALID:{why:({value:e})=>`${e} is not a project URL. Use the https:// origin of the app, with its base path if it has one.`,fix:"Pass `hostedConsoleUrl()` the `https://` origin of the app, or `http://localhost` in development, with its base path and without a user name or password."},RUNTIME_DURATION_INVALID:{why:({option:e,value:t})=>`${e?`\`${e}\``:`The value`} is ${t}, which is not a duration. A duration is a string with a number of 0 or more and a unit, such as "30s", "5m", or "1 day".`,fix:({suggestion:e,unit:t=`milliseconds`,value:n})=>e?`Write the time as a string with a unit: ${n} ${t} is ${e}.`:'Write a number of 0 or more and one unit: `ms`, `s`, `m`, `h`, `d`, or `w`, or a long name such as `minutes` or `days`. For example `"30s"`, `"5m"`, or `"1 day"`.'},RUNTIME_EXECUTION_BUDGET_AMOUNT_INVALID:{why:({counter:e})=>`[vitehub] Execution budget ${e} amount must be a finite non-negative number.`,fix:"Pass `consume()` and the `record*()` methods of the execution budget a finite number of 0 or more."},RUNTIME_EXECUTION_BUDGET_EXCEEDED:{why:({counter:e})=>`[vitehub] Execution budget exhausted for ${e}.`,fix:"Raise the `executionBudget` limit that `error.counter` names, such as `maxToolCalls`, `maxRetries`, `maxInputBytes`, or `maxOutputBytes`, or give the run less work."},RUNTIME_EXECUTION_BUDGET_LIMIT_INVALID:{why:()=>`[vitehub] Execution budget limits must be finite non-negative numbers.`,fix:"Set each limit of `executionBudget`, such as `maxToolCalls` or `maxOutputBytes`, to a finite number of 0 or more, or remove it."},RUNTIME_HIDDEN_ERROR:{why:()=>`The server failed. The error is not a ViteHub error, so its message and stack stay on the server.`,fix:"Read the server logs for the error. To send a code, a why, and a fix to the client, return a `ResultError` from `defineErrors()` and pass it to `toResponse()`."},RUNTIME_SERIALIZED_RESPONSE_INVALID:{why:()=>`Invalid serialized Response`,fix:"Pass `deserializeResponse()` the record that `serializeResponse()` returned, unchanged. Check it first with `isSerializedResponse()`."}}});function Ss(e){return e!==null&&Object(e)===e}const Cs=/* @__PURE__ */ new WeakMap;function Z(){throw xs.RUNTIME_R0006({message:`[vitehub] ViteHubError requires a valid public error contract.`})}function ws(e){try{return Array.isArray(e)}catch{Z()}}function Q(e,t,n=!1){try{let r=Object.getOwnPropertyDescriptor(e,t);return r===void 0?void 0:((!(`value`in r)||n&&!r.enumerable)&&Z(),r.value)}catch{Z()}}function Ts(e,t,n,r){if(t.nodes+=1,t.nodes>1024&&Z(),e===void 0&&r)return;if(e===null||typeof e==`boolean`||typeof e==`string`&&e.length<=16384||typeof e==`number`&&Number.isFinite(e))return e;(typeof e!=`object`||n>8||t.ancestors.has(e))&&Z();let i,a;try{i=Object.getPrototypeOf(e),a=Reflect.ownKeys(e)}catch{Z()}t.ancestors.add(e);try{if(ws(e)){let r=Q(e,`length`);(!Number.isSafeInteger(r)||r<0||r>128||a.length!==r+1||!a.includes(`length`))&&Z();let i=[];for(let o=0;o<r;o+=1){let r=String(o);a.includes(r)||Z(),i.push(Ts(Q(e,r,!0),t,n+1,!1))}return Object.freeze(i)}i!==Object.prototype&&i!==null&&Z(),(a.length>128||a.some(e=>typeof e!=`string`))&&Z();let r={};for(let i of a)(i.length===0||i.length>128)&&Z(),Object.defineProperty(r,i,{enumerable:!0,value:Ts(Q(e,i,!0),t,n+1,!0),writable:!0});return Object.freeze(r)}finally{t.ancestors.delete(e)}}function Es(e){if(e!==void 0)return(typeof e!=`object`||!e||ws(e))&&Z(),Ts(e,{ancestors:/* @__PURE__ */ new Set,nodes:0},0,!1)}function Ds(e,t,n){(typeof e!=`string`||e.length===0||e.length>128)&&Z(),(typeof t!=`string`||t.length===0||t.length>16384)&&Z(),(typeof n!=`object`||!n||ws(n))&&Z();let r=Q(n,`cause`),i=Es(Q(n,`details`)),a=Q(n,`requestId`);return a!==void 0&&(typeof a!=`string`||a.length===0||a.length>256)&&Z(),{cause:r,code:e,details:i,message:t,name:`ViteHubError`,requestId:a,shape:Object.freeze({code:e,...i===void 0?{}:{details:i},message:t,name:`ViteHubError`,...a===void 0?{}:{requestId:a}})}}var Os=class extends Error{code;details;requestId;constructor(e,t,n={}){let r=Ds(e,t,n);super(r.message,r.cause===void 0?void 0:{cause:r.cause}),this.name=`ViteHubError`,this.code=r.code,this.details=r.details,this.requestId=r.requestId;let i=this.toJSON.bind(this);Object.defineProperties(this,{code:{configurable:!0,enumerable:!0,value:r.code,writable:!1},details:{configurable:!0,enumerable:!0,value:r.details,writable:!1},message:{configurable:!0,enumerable:!1,value:r.message,writable:!1},name:{configurable:!1,enumerable:!1,value:r.name,writable:!1},requestId:{configurable:!0,enumerable:!0,value:r.requestId,writable:!1},toJSON:{configurable:!1,enumerable:!1,value:i,writable:!1}}),Cs.set(this,r.shape)}toJSON(){let e=Cs.get(this);if(e)return e;let t=Ds(Q(this,`code`),Q(this,`message`),{details:Q(this,`details`),requestId:Q(this,`requestId`)});return Cs.set(this,t.shape),t.shape}};function ks(e){if(!Ss(e))return!1;try{let t=Reflect.get(Error,`isError`);return typeof t==`function`?t(e)===!0:e instanceof Error||!(Symbol.toStringTag in e)&&Object.prototype.toString.call(e)===`[object Error]`}catch{return!1}}function As(e){if(!ks(e))return!1;try{let t=Reflect.get(e,`message`),n=Reflect.get(e,`code`),r=Reflect.get(e,`name`),i=Reflect.get(e,`why`),a=Reflect.get(e,`fix`),o=Reflect.get(e,`docs`),s=Reflect.get(e,`sources`);return typeof n==`string`&&n.length>0&&typeof r==`string`&&typeof t==`string`&&i===t&&(a===void 0||typeof a==`string`)&&(o===void 0||typeof o==`string`)&&(s===void 0||Array.isArray(s)&&s.every(e=>typeof e==`string`))&&typeof Reflect.get(e,`toJSON`)==`function`}catch{return!1}}const js=Symbol.for(`vitehub.runtime.resultError`);function Ms(e){let t=t=>{let n=Object.getOwnPropertyDescriptor(e,t);return n?n.configurable===!0:Object.isExtensible(e)},n=t(`name`)&&t(`toJSON`)&&(Object.hasOwn(e,js)||Object.isExtensible(e))?e:new _s({code:e.code,why:e.why,fix:e.fix,docs:e.docs,cause:e.cause,data:e.data,sources:e.sources});if(n!==e){n.stack=e.stack;let t=Reflect.get(e,`status`);typeof t==`number`&&Object.defineProperty(n,"status",{configurable:!0,value:t})}return Object.defineProperty(n,"name",{configurable:!0,value:n.code,writable:!0}),Object.defineProperty(n,js,{value:!0}),Object.defineProperty(n,"toJSON",{configurable:!0,value:()=>({code:n.code,docs:n.docs,fix:n.fix,name:n.name,why:n.why})}),n}function Ns(e){let t=/* @__PURE__ */ bs({codes:e.codes,docsBase:e.docs}),n=new Set(Object.keys(e.codes)),r=Object.defineProperty({},"is",{value:e=>As(e)&&n.has(e.code)});for(let i of n){let n=t[i],a=e.codes[i]?.status;r[i]=Object.assign(e=>{let t=Ms(n(e));return a!==void 0&&Object.defineProperty(t,"status",{configurable:!0,enumerable:!1,value:a}),t},{is:e=>As(e)&&e.code===i})}return r}function Ps(e){let t=e.slice(0,4096);return new Os(`WORKSPACE_PATH_INVALID`,`[vitehub] Workspace path escapes the workspace root: ${JSON.stringify(t)}.`,{details:{path:t}})}function Fs(e){let t=e.toLowerCase().split(`:`,1)[0];return{normalized:t.replace(/[ .]+$/,``),isTraversal:/^(?:\.(?: +[. ]*)?|\.\.(?: +[. ]*)?)$/.test(t)}}function Is(e=``,t={}){let n=e.replace(/\\/g,`/`),r=n.replace(/^\/+/,``).replace(/\/+$/,``),i=r.split(`/`).filter(Boolean);if(!t.allowEmpty&&!r||n.startsWith(`/`)||/^[a-z]:/i.test(n)||n.includes(`\0`)||i.some((e,n)=>{let r=e.toLowerCase(),i=Fs(e),a=i.normalized===`.git`||/^git~\d+$/.test(i.normalized)||n===0&&i.normalized===`.vitehub`||n===0&&/^vitehu~\d+$/.test(i.normalized),o=(i.normalized===`.git`||n===0&&i.normalized===`.vitehub`)&&r===i.normalized;return i.isTraversal||a&&(!t.allowReserved||!o)}))throw Ps(e);return r}const Ls=/*#__PURE__*/ Ns({docs:`https://vitehub.dev/docs/realtime/diagnostics`,codes:{REALTIME_DISABLED:{why:({action:e})=>`Realtime is disabled, so \`${e}()\` cannot run.`,fix:"Set `enabled` to `true` on `useRealtimeTiptap()` before you call the method."},REALTIME_DISCONNECTED:{why:({action:e})=>`The realtime document disconnected or changed during \`${e}()\`.`,fix:"Call the method again after the new document connects. Read `synced` to know when it is ready."},REALTIME_INVALID_DOCUMENT:{why:({action:e})=>`The room body does not fit the editor schema, so \`${e}()\` did not write it. Writing it would lose content.`,fix:`Keep editing until the document fits the editor extensions of the Realtime Definition, then call the method again. The room keeps the edits.`},REALTIME_INVALID_RESPONSE:{why:({action:e})=>`The realtime server answered \`${e}()\` with a response that the client cannot use.`,fix:"Use the same `@vite-hub/realtime` version on the client and the server, and build again."},REALTIME_MISSING_DOCUMENT:{why:({action:e})=>`\`${e}()\` needs a document, and \`documentId\` is empty.`,fix:"Pass a document path to `useRealtimeTiptap(definition, documentId)` before you call the method."},REALTIME_READ_ONLY:{why:({action:e})=>`The room is read-only, so \`${e}()\` cannot write the document.`,fix:"Read `readOnlyReason` of `useRealtimeTiptap()` for the reason. Do not offer save or publish while it is set."},REALTIME_REQUEST_FAILED:{why:({action:e,message:t,status:n})=>`The realtime \`${e}()\` request failed${n===void 0?``:` with HTTP ${n}`}${t?`: ${t}`:`.`}`,fix:"Read `error.why` for the server message, `error.data.status` for the HTTP status, and `error.cause` for a network error. Retry when the server is available again.",data:({status:e})=>({status:e})},REALTIME_SOURCE_CHANGED:{why:({action:e})=>`The server refused \`${e}()\` because the stored document changed outside the room.`,fix:"Tell the person that the stored document changed. Use `onReset()` to detect a room reset and read unsaved edits from the event's `previous` document."},REALTIME_SYNC_PENDING:{why:({action:e})=>`The room did not receive every edit of this client in time, so \`${e}()\` did not run. The composable tried 20 times.`,fix:"Call the method again when `synced` is true. When it keeps failing, check that the WebSocket stays connected."},REALTIME_ROOM_ABORTED:{why:`The request to the room stopped because its signal aborted.`,fix:`Nothing to fix when the caller stopped on purpose, such as a cancelled Agent run. Call again to ask once more.`},REALTIME_ROOM_CROWDED:{why:({count:e})=>`${e} browsers are in the room, and a request goes to one browser only.`,fix:`Give each browser its own room, such as a random id for each tab, so that one browser answers.`},REALTIME_ROOM_ELSEWHERE:{why:`No browser in this instance is in the room. With Redis or Postgres, the browser can be connected to another instance, and requests reach only the browsers of the same instance.`,fix:`Route the browser and the caller to the same instance, such as with sticky sessions, or run one Node instance.`},REALTIME_ROOM_EMPTY:{why:`No browser is in the room. The page is closed, or it has not joined yet.`,fix:`Open the page again. The request waits a few seconds for a browser to join before it gives up.`},REALTIME_ROOM_REFUSED:{why:({reason:e})=>`The browser could not answer: ${e}`,fix:"Read the reason. Add `room.onRequest(handler)` on the page, and keep each answer under 1 MiB."},REALTIME_ROOM_REQUESTS_OFF:{why:({definition:e})=>`The Realtime Definition "${e}" does not take requests.`,fix:'Define it with `defineRealtime({ access: "public", document: false, requests: true })`.'},REALTIME_ROOM_TIMEOUT:{why:({timeout:e})=>`The browser did not answer in ${e/1e3} seconds.`,fix:"Make the page answer sooner, or pass a longer `timeout` to `requestRealtimeRoom()`."},REALTIME_AWARENESS_OWNERSHIP_CONFLICT:{why:`A realtime awareness client id belongs to another peer.`,fix:`Let each editor tab use its own Yjs awareness client. Do not reuse a client id on two connections.`},REALTIME_AWARENESS_TOO_LARGE:{why:`Realtime awareness state exceeds the 8 MiB room quota.`,fix:`Keep less data in awareness state. Store large values in the document or in Workspace.`},REALTIME_DOCUMENT_TOO_LARGE:{why:`The realtime document exceeds the 8 MiB room quota.`,fix:`Split the document into smaller documents, or keep large assets in Workspace or Blob.`},REALTIME_INVALID_AWARENESS:{why:`A realtime awareness update has a state that is not a plain object.`,fix:"Set awareness state to a plain object, for example `awareness.setLocalStateField('user', { name })`."},REALTIME_TOO_MANY_AWARENESS_CLIENTS:{why:`One realtime peer sent more than 1,024 awareness clients.`,fix:`Use one awareness client for each editor tab.`},REALTIME_ROOM_WRITE_CONFLICT:{why:`Realtime room record compare-and-set failed.`,fix:`Connect again. Another Realtime instance changed the room at the same time. If it keeps failing, check that every instance uses the same Realtime bus.`},REALTIME_WRITE_REJECTED:{why:({problem:e,readOnly:t})=>e===`missing-state`?`Realtime update depends on state this room does not have.`:e===`status`?`Realtime document status is written by the server.`:t??`This realtime connection is read-only.`,fix:"Write only through a writable connection, and do not change the `status` map, which the server writes. A client that misses room state connects again to sync it."},REALTIME_DOCUMENT_CONFLICT:{why:({problem:e})=>e??`The stored document changed since the realtime room loaded it.`,fix:"Realtime re-seeds the room from the stored document. Listen to `onReset()` to recover text that the room did not save."},REALTIME_BLOB_ETAG_MISSING:{why:({pathname:e})=>`The Blob store returned no \`httpEtag\` for ${e}, so \`blobDocument()\` cannot save the file only if it is unchanged.`,fix:"Pass a ViteHub Blob store, such as `blob` from `vite-hub/blob`, whose `head()` returns `httpEtag` on every driver. A store of your own must return `httpEtag` from `head()` and accept `ifMatch` in `put()`."},REALTIME_INVALID_PERSISTENCE:{why:({name:e,reason:t})=>t===`below-debounce`?"Realtime `persistence.maxWait` must be at least `persistence.debounce`.":`Realtime \`persistence.${e}\` must be a non-negative number of milliseconds.`,fix:"Set `persistence: { debounce: 2_000, maxWait: 10_000 }`, or remove the option to use these defaults."},REALTIME_MISSING_ACCESS:{why:`The Realtime definition sets no access rule, so it does not say who can read and write its rooms.`,fix:'Set `authorize: true` to require a signed-in user, set `authorize()` to decide each request, or set `access: "public"` to let anyone read and write.'},REALTIME_INVALID_ACCESS:{why:({reason:e})=>e===`auth`?"The Realtime definition sets `auth`. Realtime replaced it with `authorize: true`, and an `authorize()` callback now also runs for signed-out callers.":e===`public-with-rule`?'The Realtime definition sets `access: "public"` together with `authorize`, so its access rule is not clear.':e===`not-public`?'The Realtime definition sets `access` to a value other than "public".':e===`not-authorize`?"The Realtime definition sets `authorize` to a value that is not `true` or a function.":"The Realtime definition sets `origins()` with `authorize: true` and no `identify()`. Only the Auth trusted-origin policy can allow a different origin to use the ViteHub Auth session.",fix:({reason:e})=>e===`auth`?"Replace `auth: true` with `authorize: true`. With an `authorize()` callback, remove `auth` and return `false` from the callback when `user` is `null`.":e===`origins-without-identify`?"Remove `origins()`, or add `identify()` that reads a credential the page sends on purpose, such as a ticket in `params`.":e===`not-authorize`?"Set `authorize: true` to require a signed-in user, or set `authorize()` to a function that returns `true` to allow.":'Use `access: "public"` alone for open rooms. To limit access, remove `access` and set `authorize`.'},REALTIME_CHECKPOINT_UNSUPPORTED:{why:"The Realtime definition sets `history.checkpoint`, but its document adapter has no `checkpoint()` method, so `history.checkpoint()` could never run.",fix:"Add `checkpoint(context, { digest, message, user })` to the document adapter, use `document: { workspace }`, or remove `history`."},REALTIME_INVALID_USER:{why:"The realtime identity needs a user `id` that is a non-empty string of at most 256 characters.",fix:"Return a user with an `id` from the Auth session or from `authorize()`."},REALTIME_MISSING_DIGEST:{why:({operation:e})=>e===`save`?`Realtime saves need Workspace file digests, and the Workspace Store did not return one.`:`Realtime checkpoints need a stored document, and the save returned no digest.`,fix:"Use a Workspace Store that returns file digests, or return `digest` from the document adapter `save()`."},REALTIME_INVALID_POSTGRES_URL:{why:"REALTIME_POSTGRES_URL is set, and it is not a `postgres://` or `postgresql://` URL.",fix:`Set REALTIME_POSTGRES_URL to a Postgres URL, or remove it so that Realtime uses the connection of the Default Database.`},REALTIME_MISSING_BUS_CONNECTION:{why:({driver:e})=>e===`redis`?`Realtime driver "redis" shares rooms through Redis, and REDIS_URL is not set.`:`Realtime driver "postgres" shares rooms through Postgres, and the app has no Postgres Default Database and no REALTIME_POSTGRES_URL.`,fix:'Set REDIS_URL for Redis. For Postgres, define the Default Database with `dialect: "postgresql"`, or set REALTIME_POSTGRES_URL. Or set `realtime.driver` to "auto".'},REALTIME_ROOM_LOCK_TIMEOUT:{why:`Realtime waited 30 seconds for the save lock of a room, and another instance still holds it.`,fix:"Make the document adapter `save()` finish in less than 30 seconds. Realtime tries the save again."},REALTIME_DRIVER_CONFLICT:{why:({driver:e,host:t})=>e===`memory`?`Realtime driver "memory" is single-process only, and the ${t} host runs more than one process.`:e===`cloudflare`?`Realtime driver "cloudflare" does not work with the ${t} host.`:`Realtime driver "${e}" needs a Node.js server, and the ${t} host does not run one.`,fix:'Set `realtime.driver` to "cloudflare" with a Cloudflare host. With the Node host, use "auto", "postgres", "redis", or "memory".'},REALTIME_MISSING_DRIVER:{why:`Realtime production builds need one room driver, and ViteHub cannot select one for this deployment.`,fix:`Deploy with a Cloudflare host to use Durable Objects, or with the Node host to share rooms through Postgres or Redis.`},REALTIME_RENAMED_AUTHORITY_KEY:{why:({value:e})=>`\`realtime.authority\` is ${e}. ViteHub renamed this key to \`driver\`, and it does not read \`authority\`, so Realtime would not use the driver you chose.`,fix:({value:e})=>`Set \`realtime: { driver: ${e} }\`, or run \`npx @vite-hub/codemods driver-key\` to rename it in every config file.`}}});function Rs(e){try{let t=JSON.parse(E(e));if(!t||typeof t!=`object`||!(`epoch`in t)||!(`type`in t)||typeof t.epoch!=`string`||!t.epoch)return;if(t.type===`session`&&`access`in t&&(t.access===`read`||t.access===`write`))return t.access===`read`&&`reason`in t&&(t.reason===`access`||t.reason===`document`||t.reason===`version`)?{type:`session`,access:t.access,epoch:t.epoch,reason:t.reason}:{type:`session`,access:t.access,epoch:t.epoch};if(t.type===`reset`&&`reason`in t&&(t.reason===`source-changed`||t.reason===`stale`))return{type:`reset`,epoch:t.epoch,reason:t.reason}}catch{}}function zs(e){if(typeof e!=`string`||e.length===0||e.length>4096||e.includes(`\0`)||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`\\`)||e.includes(`//`)||/^[a-z]:/i.test(e))return!1;try{return Is(e)===e}catch{return!1}}function Bs(e){try{let t=JSON.parse(E(e));if((t.operation===`create`||t.operation===`delete`||t.operation===`update`)&&zs(t.path))return{operation:t.operation,path:t.path};if(t.operation===`move`&&zs(t.from)&&zs(t.to))return{operation:t.operation,from:t.from,to:t.to}}catch{}}function Vs(e){let t=_();return b(t,4),x(t,JSON.stringify(e)),v(t)}function Hs(e){let t=_();return b(t,6),x(t,JSON.stringify(e)),v(t)}function Us(e){try{let t=JSON.parse(E(e));if(!t||typeof t!=`object`||!(`id`in t)||typeof t.id!=`string`||!t.id||t.id.length>128||!(`kind`in t))return;if(t.kind===`request`)return{kind:`request`,id:t.id,body:`body`in t?t.body:void 0};if(t.kind!==`answer`||!(`ok`in t))return;if(t.ok===!0)return{kind:`answer`,id:t.id,ok:!0,body:`body`in t?t.body:void 0};if(t.ok===!1&&`why`in t&&typeof t.why==`string`)return{kind:`answer`,id:t.id,ok:!1,why:t.why}}catch{}}function Ws(e){let t;e.on(`status`,({status:n})=>{clearInterval(t),t=void 0;let r=e.ws;if(n!==`connected`||!r)return;let i=r.onmessage;r.onmessage=function(t){if(t.data!==`pong`)return i?.call(this,t);e.ws===r&&(e.wsLastMessageReceived=D())},t=setInterval(()=>{e.ws===r&&r.readyState===r.OPEN&&r.send(`ping`)},15e3)})}const Gs=Object.freeze({body:`body`,fields:`fields`,status:`status`});function Ks(e){return typeof e==`string`?e:null}function qs(e){let t=e.getMap(Gs.status),n=t.get(`issues`),r=t.get(`savedBy`),i={issues:Array.isArray(n)?n:[],savedBy:r&&!Array.isArray(r)&&r instanceof Object?r:null};return{digest:Ks(t.get(`digest`)),error:Ks(t.get(`error`)),issues:i.issues,savedAt:Ks(t.get(`savedAt`)),savedBy:i.savedBy}}function Js(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ys=[`#E11D48`,`#D97706`,`#059669`,`#0891B2`,`#2563EB`,`#7C3AED`,`#C026D3`];function $(e){try{return String(e)===e}catch{return!1}}function Xs(e){if(!$(e.id)||!e.id||e.id.length>256)throw Ls.REALTIME_INVALID_USER();let t=0;for(let n=0;n<e.id.length;n++)t=Math.imul(31,t)+e.id.charCodeAt(n)|0;let n=($(e.name)&&e.name||$(e.email)&&e.email||`Anonymous`).slice(0,256),r={color:Ys[Math.abs(t)%Ys.length],id:e.id,name:n};return $(e.image)&&e.image&&e.image.length<=2048&&(r.image=e.image),r}function Zs(e){return Js(e)?$(e.id)&&e.id.length>0&&e.id.length<=256&&$(e.name)&&e.name.length>0&&e.name.length<=256&&$(e.color)&&/^#[\da-f]{6}$/i.test(e.color)&&(e.image===void 0||$(e.image)&&e.image.length<=2048):!1}function Qs(e){let t=[];for(let[n,r]of e)if(Zs(r.user)){let{color:e,id:i,image:a,name:o}=r.user,s={color:e,id:i,name:o,clientId:n};a!==void 0&&(s.image=a),t.push(s)}return t}function $s(e,t,n={}){let r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=[],o,s=`connecting`,c=!1,l=!1,u,d,f=()=>{for(let e of r)e()},ee=()=>{let t=n.origin?new URL(n.origin):window.location;return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}${ms(`/_vitehub/realtime/${encodeURIComponent(e)}`,n.baseURL)}`},te=t.split(`/`).map(encodeURIComponent).join(`/`),ne={};function re(){c=!1,u=new Hr,d=new ps(ee(),te,u,{disableBc:!0,params:{...n.params,clientId:String(u.clientID)}});let e=d;Ws(e),e.messageHandlers[5]=(t,n)=>{let r=Rs(n);if(r){if(r.type===`session`){e.params.epoch=r.epoch;return}e.destroy(),u.destroy(),!l&&(re(),f())}},e.messageHandlers[6]=(t,n)=>{let r=Us(n);r?.kind===`request`&&ie(e,r.id,r.body)},e.awareness.off(`update`,e._awarenessUpdateHandler),e.awareness.on(`update`,({added:t,removed:n,updated:r})=>{let i=[...t,...r,...n].filter(t=>t===e.doc.clientID),a=e.ws;if(!i.length||!e.wsconnected||!a||a.readyState!==a.OPEN)return;let o=_();b(o,1),S(o,Vo(e.awareness,i)),a.send(v(o))});let t=n.identity??{id:`guest:${u.clientID}`};e.awareness.setLocalState({...ne,user:Xs({...t,id:t.id||`guest:${u.clientID}`})}),e.awareness.on(`change`,f),u.getMap(Gs.status).observe(f),e.on(`sync`,t=>{d===e&&(c=t,f())}),e.on(`status`,e=>{s=e.status,f()})}re();let p;n.changes&&(p=new ps(ee(),`%40workspace`,new Hr,{disableBc:!0,params:{...n.params,workspace:`events`}}),p.awareness.setLocalState(null),Ws(p),p.messageHandlers[4]=(e,t)=>{let n=Bs(t);if(n)for(let e of i)e(n)},p.on(`status`,e=>{e.status===`connected`&&ae()}));async function ie(e,t,n){let r=e=>Hs({kind:`answer`,id:t,ok:!1,why:e}),i;try{i=o?Hs({kind:`answer`,id:t,ok:!0,body:await o(n)}):r(`This page does not answer requests.`),i.byteLength>1047552&&(i=r(`The answer has ${i.byteLength} bytes, over the 1 MiB limit.`))}catch(e){i=r(e instanceof Error?e.message:String(e))}let a=e.ws;e.wsconnected&&a&&a.readyState===a.OPEN&&a.send(Uint8Array.from(i))}function ae(){let e=p?.ws;if(p?.wsconnected&&e&&e.readyState===e.OPEN)for(;a.length;)e.send(Uint8Array.from(Vs(a.shift())))}return{get awareness(){return d.awareness},get clientId(){return u.clientID},people:()=>Qs(d.awareness.getStates()),states:()=>{let e=new Map(d.awareness.getStates());return e.delete(u.clientID),e},status:()=>s,saveStatus:()=>c?qs(u):void 0,setLocal(e,t){if(t!==null){ne[e]=t,d.awareness.setLocalStateField(e,t);return}delete ne[e];let n=d.awareness.getLocalState();if(!n||!Object.hasOwn(n,e))return;let{[e]:r,...i}=n;d.awareness.setLocalState(i)},notify(e){p&&(a.push(e),ae())},onUpdate(e){return r.add(e),()=>r.delete(e)},onChange(e){return i.add(e),()=>i.delete(e)},onRequest(e){return o=e,()=>{o===e&&(o=void 0)}},destroy(){l=!0,d.destroy(),u.destroy(),p?.destroy(),p?.doc.destroy(),r.clear(),i.clear(),o=void 0}}}export{$s as connectRealtimeRoom};
53
+ function bs(e){let t=e.reporters??[],n=Symbol(),r=Object.defineProperty({},"is",{value:ys(n)}),{docsBase:i}=e;for(let a of Object.keys(e.codes)){let o=e.codes[a],s=o.docs===!1?void 0:o.docs||vs(i,a),c=(e={},r={})=>{let i=new _s({code:a,why:hs(o.why,e),fix:hs(o.fix,e),docs:s,cause:e.cause,sources:e.sources,data:hs(o.data,e)},c);i[n]=1;for(let e of t)e(i,r);return i};c.is=e=>r.is(e)&&e.code===a,r[a]=c}return r}const X={why:({message:e})=>e===void 0?``:String(e)},xs=/*#__PURE__*/ bs({docsBase:`https://vitehub.dev/docs/runtime/diagnostics`,codes:{RUNTIME_R0001:{...X,fix:"Pass `maxDepth` to `normalizeRuntimeDiagnosticError()` as an integer of 0 or more, or remove it to use the default."},RUNTIME_R0002:{...X,fix:"Pass `maxErrors` to `normalizeRuntimeDiagnosticError()` as an integer of 1 or more, or remove it to use the default."},RUNTIME_R0003:{...X,fix:"Pass `maxStringLength` to `normalizeRuntimeDiagnosticError()` as an integer of 64 or more, or remove it to use the default."},RUNTIME_R0004:{...X,fix:"Read the logs of the process that `vitehub drain` waited for to find why its drain failed, then fix that failure and run `vitehub drain` again."},RUNTIME_R0005:{...X,fix:"Read the logs of the process that the message names to find why it stopped, then start it again before you run `vitehub drain`."},RUNTIME_R0006:{...X,fix:"Pass `new ViteHubError()` a nonempty `code` and `message` string within the length limits, and plain JSON `details`."},RUNTIME_R0007:{...X,fix:"Give the execution authority a valid value for each of `credentials`, `environment`, `filesystem.access`, `filesystem.scope`, `isolation`, `network`, and `processes`."},RUNTIME_R0009:{...X,fix:"Set `intervalMs` of the process reconciler to a number of milliseconds from 1 to 2147483647."},RUNTIME_R0010:{...X,fix:"Give the process reconciler a `signal` other than `SIGKILL` or `SIGSTOP`, or set `signal: false`."},RUNTIME_R0011:{...X,fix:"Call `drain()` of the process reconciler after its callback returns, not from inside the callback."},RUNTIME_R0015:{...X,fix:"Pass the `Request` of a Fetchable handler, or the event of an H3 or Nitro route, to `getStandardContext()`."},RUNTIME_R0016:{...X,fix:"Return the body or a `Response` from the handler, in place of setting `~standard.res.body`."},RUNTIME_R0017:X,RUNTIME_R0018:X,RUNTIME_CONSOLE_PATH_INVALID:{why:({value:e})=>`${e} is not a Console path. Use a path that starts with one /, such as /agents/<agent>.`,fix:"Pass `hostedConsoleUrl()` a Console path that starts with one `/`, such as `/kv` or `/agents/<agent>/invocations/<id>`."},RUNTIME_CONSOLE_PROJECT_URL_INVALID:{why:({value:e})=>`${e} is not a project URL. Use the https:// origin of the app, with its base path if it has one.`,fix:"Pass `hostedConsoleUrl()` the `https://` origin of the app, or `http://localhost` in development, with its base path and without a user name or password."},RUNTIME_DURATION_INVALID:{why:({option:e,value:t})=>`${e?`\`${e}\``:`The value`} is ${t}, which is not a duration. A duration is a string with a number of 0 or more and a unit, such as "30s", "5m", or "1 day".`,fix:({suggestion:e,unit:t=`milliseconds`,value:n})=>e?`Write the time as a string with a unit: ${n} ${t} is ${e}.`:'Write a number of 0 or more and one unit: `ms`, `s`, `m`, `h`, `d`, or `w`, or a long name such as `minutes` or `days`. For example `"30s"`, `"5m"`, or `"1 day"`.'},RUNTIME_EXECUTION_BUDGET_AMOUNT_INVALID:{why:({counter:e})=>`[vitehub] Execution budget ${e} amount must be a finite non-negative number.`,fix:"Pass `consume()` and the `record*()` methods of the execution budget a finite number of 0 or more."},RUNTIME_EXECUTION_BUDGET_EXCEEDED:{why:({counter:e})=>`[vitehub] Execution budget exhausted for ${e}.`,fix:"Raise the `executionBudget` limit that `error.counter` names, such as `maxToolCalls`, `maxRetries`, `maxInputBytes`, or `maxOutputBytes`, or give the run less work."},RUNTIME_EXECUTION_BUDGET_LIMIT_INVALID:{why:()=>`[vitehub] Execution budget limits must be finite non-negative numbers.`,fix:"Set each limit of `executionBudget`, such as `maxToolCalls` or `maxOutputBytes`, to a finite number of 0 or more, or remove it."},RUNTIME_HIDDEN_ERROR:{why:()=>`The server failed. The error is not a ViteHub error, so its message and stack stay on the server.`,fix:"Read the server logs for the error. To send a code, a why, and a fix to the client, return a `ResultError` from `defineErrors()` and pass it to `toResponse()`."},RUNTIME_SERIALIZED_RESPONSE_INVALID:{why:()=>`Invalid serialized Response`,fix:"Pass `deserializeResponse()` the record that `serializeResponse()` returned, unchanged. Check it first with `isSerializedResponse()`."}}});function Ss(e){return e!==null&&Object(e)===e}const Cs=/* @__PURE__ */ new WeakMap;function Z(){throw xs.RUNTIME_R0006({message:`[vitehub] ViteHubError requires a valid public error contract.`})}function ws(e){try{return Array.isArray(e)}catch{Z()}}function Q(e,t,n=!1){try{let r=Object.getOwnPropertyDescriptor(e,t);return r===void 0?void 0:((!(`value`in r)||n&&!r.enumerable)&&Z(),r.value)}catch{Z()}}function Ts(e,t,n,r){if(t.nodes+=1,t.nodes>1024&&Z(),e===void 0&&r)return;if(e===null||typeof e==`boolean`||typeof e==`string`&&e.length<=16384||typeof e==`number`&&Number.isFinite(e))return e;(typeof e!=`object`||n>8||t.ancestors.has(e))&&Z();let i,a;try{i=Object.getPrototypeOf(e),a=Reflect.ownKeys(e)}catch{Z()}t.ancestors.add(e);try{if(ws(e)){let r=Q(e,`length`);(!Number.isSafeInteger(r)||r<0||r>128||a.length!==r+1||!a.includes(`length`))&&Z();let i=[];for(let o=0;o<r;o+=1){let r=String(o);a.includes(r)||Z(),i.push(Ts(Q(e,r,!0),t,n+1,!1))}return Object.freeze(i)}i!==Object.prototype&&i!==null&&Z(),(a.length>128||a.some(e=>typeof e!=`string`))&&Z();let r={};for(let i of a)(i.length===0||i.length>128)&&Z(),Object.defineProperty(r,i,{enumerable:!0,value:Ts(Q(e,i,!0),t,n+1,!0),writable:!0});return Object.freeze(r)}finally{t.ancestors.delete(e)}}function Es(e){if(e!==void 0)return(typeof e!=`object`||!e||ws(e))&&Z(),Ts(e,{ancestors:/* @__PURE__ */ new Set,nodes:0},0,!1)}function Ds(e,t,n){(typeof e!=`string`||e.length===0||e.length>128)&&Z(),(typeof t!=`string`||t.length===0||t.length>16384)&&Z(),(typeof n!=`object`||!n||ws(n))&&Z();let r=Q(n,`cause`),i=Es(Q(n,`details`)),a=Q(n,`requestId`);return a!==void 0&&(typeof a!=`string`||a.length===0||a.length>256)&&Z(),{cause:r,code:e,details:i,message:t,name:`ViteHubError`,requestId:a,shape:Object.freeze({code:e,...i===void 0?{}:{details:i},message:t,name:`ViteHubError`,...a===void 0?{}:{requestId:a}})}}var Os=class extends Error{code;details;requestId;constructor(e,t,n={}){let r=Ds(e,t,n);super(r.message,r.cause===void 0?void 0:{cause:r.cause}),this.name=`ViteHubError`,this.code=r.code,this.details=r.details,this.requestId=r.requestId;let i=this.toJSON.bind(this);Object.defineProperties(this,{code:{configurable:!0,enumerable:!0,value:r.code,writable:!1},details:{configurable:!0,enumerable:!0,value:r.details,writable:!1},message:{configurable:!0,enumerable:!1,value:r.message,writable:!1},name:{configurable:!1,enumerable:!1,value:r.name,writable:!1},requestId:{configurable:!0,enumerable:!0,value:r.requestId,writable:!1},toJSON:{configurable:!1,enumerable:!1,value:i,writable:!1}}),Cs.set(this,r.shape)}toJSON(){let e=Cs.get(this);if(e)return e;let t=Ds(Q(this,`code`),Q(this,`message`),{details:Q(this,`details`),requestId:Q(this,`requestId`)});return Cs.set(this,t.shape),t.shape}};function ks(e){if(!Ss(e))return!1;try{let t=Reflect.get(Error,`isError`);return typeof t==`function`?t(e)===!0:e instanceof Error||!(Symbol.toStringTag in e)&&Object.prototype.toString.call(e)===`[object Error]`}catch{return!1}}function As(e){if(!ks(e))return!1;try{let t=Reflect.get(e,`message`),n=Reflect.get(e,`code`),r=Reflect.get(e,`name`),i=Reflect.get(e,`why`),a=Reflect.get(e,`fix`),o=Reflect.get(e,`docs`),s=Reflect.get(e,`sources`);return typeof n==`string`&&n.length>0&&typeof r==`string`&&typeof t==`string`&&i===t&&(a===void 0||typeof a==`string`)&&(o===void 0||typeof o==`string`)&&(s===void 0||Array.isArray(s)&&s.every(e=>typeof e==`string`))&&typeof Reflect.get(e,`toJSON`)==`function`}catch{return!1}}const js=Symbol.for(`vitehub.runtime.resultError`);function Ms(e){let t=t=>{let n=Object.getOwnPropertyDescriptor(e,t);return n?n.configurable===!0:Object.isExtensible(e)},n=t(`name`)&&t(`toJSON`)&&(Object.hasOwn(e,js)||Object.isExtensible(e))?e:new _s({code:e.code,why:e.why,fix:e.fix,docs:e.docs,cause:e.cause,data:e.data,sources:e.sources});if(n!==e){n.stack=e.stack;let t=Reflect.get(e,`status`);typeof t==`number`&&Object.defineProperty(n,"status",{configurable:!0,value:t})}return Object.defineProperty(n,"name",{configurable:!0,value:n.code,writable:!0}),Object.defineProperty(n,js,{value:!0}),Object.defineProperty(n,"toJSON",{configurable:!0,value:()=>({code:n.code,docs:n.docs,fix:n.fix,name:n.name,why:n.why})}),n}function Ns(e){let t=/* @__PURE__ */ bs({codes:e.codes,docsBase:e.docs}),n=new Set(Object.keys(e.codes)),r=Object.defineProperty({},"is",{value:e=>As(e)&&n.has(e.code)});for(let i of n){let n=t[i],a=e.codes[i]?.status;r[i]=Object.assign(e=>{let t=Ms(n(e));return a!==void 0&&Object.defineProperty(t,"status",{configurable:!0,enumerable:!1,value:a}),t},{is:e=>As(e)&&e.code===i})}return r}function Ps(e){let t=e.slice(0,4096);return new Os(`WORKSPACE_PATH_INVALID`,`[vitehub] Workspace path escapes the workspace root: ${JSON.stringify(t)}.`,{details:{path:t}})}function Fs(e){let t=e.toLowerCase().split(`:`,1)[0];return{normalized:t.replace(/[ .]+$/,``),isTraversal:/^(?:\.(?: +[. ]*)?|\.\.(?: +[. ]*)?)$/.test(t)}}function Is(e=``,t={}){let n=e.replace(/\\/g,`/`),r=n.replace(/^\/+/,``).replace(/\/+$/,``),i=r.split(`/`).filter(Boolean);if(!t.allowEmpty&&!r||n.startsWith(`/`)||/^[a-z]:/i.test(n)||n.includes(`\0`)||i.some((e,n)=>{let r=e.toLowerCase(),i=Fs(e),a=i.normalized===`.git`||/^git~\d+$/.test(i.normalized)||n===0&&i.normalized===`.vitehub`||n===0&&/^vitehu~\d+$/.test(i.normalized),o=(i.normalized===`.git`||n===0&&i.normalized===`.vitehub`)&&r===i.normalized;return i.isTraversal||a&&(!t.allowReserved||!o)}))throw Ps(e);return r}const Ls=/*#__PURE__*/ Ns({docs:`https://vitehub.dev/docs/realtime/diagnostics`,codes:{REALTIME_DISABLED:{why:({action:e})=>`Realtime is disabled, so \`${e}()\` cannot run.`,fix:"Set `enabled` to `true` on `useRealtimeTiptap()` before you call the method."},REALTIME_DISCONNECTED:{why:({action:e})=>`The realtime document disconnected or changed during \`${e}()\`.`,fix:"Call the method again after the new document connects. Read `synced` to know when it is ready."},REALTIME_INVALID_DOCUMENT:{why:({action:e})=>`The room body does not fit the editor schema, so \`${e}()\` did not write it. Writing it would lose content.`,fix:`Keep editing until the document fits the editor extensions of the Realtime Definition, then call the method again. The room keeps the edits.`},REALTIME_INVALID_RESPONSE:{why:({action:e})=>`The realtime server answered \`${e}()\` with a response that the client cannot use.`,fix:"Use the same `@vite-hub/realtime` version on the client and the server, and build again."},REALTIME_MISSING_DOCUMENT:{why:({action:e})=>`\`${e}()\` needs a document, and \`documentId\` is empty.`,fix:"Pass a document path to `useRealtimeTiptap(definition, documentId)` before you call the method."},REALTIME_READ_ONLY:{why:({action:e})=>`The room is read-only, so \`${e}()\` cannot write the document.`,fix:"Read `readOnlyReason` of `useRealtimeTiptap()` for the reason. Do not offer save or publish while it is set."},REALTIME_REQUEST_FAILED:{why:({action:e,message:t,status:n})=>`The realtime \`${e}()\` request failed${n===void 0?``:` with HTTP ${n}`}${t?`: ${t}`:`.`}`,fix:"Read `error.why` for the server message, `error.data.status` for the HTTP status, and `error.cause` for a network error. Retry when the server is available again.",data:({status:e})=>({status:e})},REALTIME_SOURCE_CHANGED:{why:({action:e})=>`The server refused \`${e}()\` because the stored document changed outside the room.`,fix:"Tell the person that the stored document changed. Use `onReset()` to detect a room reset and read unsaved edits from the event's `previous` document."},REALTIME_SYNC_PENDING:{why:({action:e})=>`The room did not receive every edit of this client in time, so \`${e}()\` did not run. The composable tried 20 times.`,fix:"Call the method again when `synced` is true. When it keeps failing, check that the WebSocket stays connected."},REALTIME_ROOM_ABORTED:{why:`The request to the room stopped because its signal aborted.`,fix:`Nothing to fix when the caller stopped on purpose, such as a cancelled Agent run. Call again to ask once more.`},REALTIME_ROOM_CROWDED:{why:({count:e})=>`${e} browsers are in the room, and a request goes to one browser only.`,fix:`Give each browser its own room, such as a random id for each tab, so that one browser answers.`},REALTIME_ROOM_ELSEWHERE:{why:`No browser in this instance is in the room. With Redis or Postgres, the browser can be connected to another instance, and requests reach only the browsers of the same instance.`,fix:`Route the browser and the caller to the same instance, such as with sticky sessions, or run one Node instance.`},REALTIME_ROOM_EMPTY:{why:`No browser is in the room. The page is closed, or it has not joined yet.`,fix:`Open the page again. The request waits a few seconds for a browser to join before it gives up.`},REALTIME_ROOM_REFUSED:{why:({reason:e})=>`The browser could not answer: ${e}`,fix:"Read the reason. Add `room.onRequest(handler)` on the page, and keep each answer under 1 MiB."},REALTIME_ROOM_REQUESTS_OFF:{why:({definition:e})=>`The Realtime Definition "${e}" does not take requests.`,fix:'Define it with `defineRealtime({ access: "public", document: false, requests: true })`.'},REALTIME_ROOM_TIMEOUT:{why:({timeout:e})=>`The browser did not answer in ${e/1e3} seconds.`,fix:"Make the page answer sooner, or pass a longer `timeout` to `requestRealtimeRoom()`."},REALTIME_AWARENESS_OWNERSHIP_CONFLICT:{why:`A realtime awareness client id belongs to another peer.`,fix:`Let each editor tab use its own Yjs awareness client. Do not reuse a client id on two connections.`},REALTIME_AWARENESS_TOO_LARGE:{why:`Realtime awareness state exceeds the 8 MiB room quota.`,fix:`Keep less data in awareness state. Store large values in the document or in Workspace.`},REALTIME_DOCUMENT_TOO_LARGE:{why:`The realtime document exceeds the 8 MiB room quota.`,fix:`Split the document into smaller documents, or keep large assets in Workspace or Blob.`},REALTIME_INVALID_AWARENESS:{why:`A realtime awareness update has a state that is not a plain object.`,fix:"Set awareness state to a plain object, for example `awareness.setLocalStateField('user', { name })`."},REALTIME_TOO_MANY_AWARENESS_CLIENTS:{why:`One realtime peer sent more than 1,024 awareness clients.`,fix:`Use one awareness client for each editor tab.`},REALTIME_ROOM_WRITE_CONFLICT:{why:`Realtime room record compare-and-set failed.`,fix:`Connect again. Another Realtime instance changed the room at the same time. If it keeps failing, check that every instance uses the same Realtime bus.`},REALTIME_WRITE_REJECTED:{why:({problem:e,readOnly:t})=>e===`missing-state`?`Realtime update depends on state this room does not have.`:e===`status`?`Realtime document status is written by the server.`:t??`This realtime connection is read-only.`,fix:"Write only through a writable connection, and do not change the `status` map, which the server writes. A client that misses room state connects again to sync it."},REALTIME_DOCUMENT_CONFLICT:{why:({problem:e})=>e??`The stored document changed since the realtime room loaded it.`,fix:"Realtime re-seeds the room from the stored document. Listen to `onReset()` to recover text that the room did not save."},REALTIME_BLOB_ETAG_MISSING:{why:({pathname:e})=>`The Blob store returned no \`httpEtag\` for ${e}, so \`blobDocument()\` cannot save the file only if it is unchanged.`,fix:"Pass a ViteHub Blob store, such as `blob` from `vite-hub/blob`, whose `head()` returns `httpEtag` on every driver. A store of your own must return `httpEtag` from `head()` and accept `ifMatch` in `put()`."},REALTIME_INVALID_PERSISTENCE:{why:({name:e,reason:t})=>t===`below-debounce`?"Realtime `persistence.maxWait` must be at least `persistence.debounce`.":`Realtime \`persistence.${e}\` must be a non-negative number of milliseconds.`,fix:"Set `persistence: { debounce: 2_000, maxWait: 10_000 }`, or remove the option to use these defaults."},REALTIME_MISSING_ACCESS:{why:`The Realtime definition sets no access rule, so it does not say who can read and write its rooms.`,fix:'Set `authorize: true` to require a signed-in user, set `authorize()` to decide each request, or set `access: "public"` to let anyone read and write.'},REALTIME_INVALID_ACCESS:{why:({reason:e})=>e===`auth`?"The Realtime definition sets `auth`. Realtime replaced it with `authorize: true`, and an `authorize()` callback now also runs for signed-out callers.":e===`public-with-rule`?'The Realtime definition sets `access: "public"` together with `authorize`, so its access rule is not clear.':e===`not-public`?'The Realtime definition sets `access` to a value other than "public".':e===`not-authorize`?"The Realtime definition sets `authorize` to a value that is not `true` or a function.":"The Realtime definition sets `origins()` with `authorize: true` and no `identify()`. Only the Auth trusted-origin policy can allow a different origin to use the ViteHub Auth session.",fix:({reason:e})=>e===`auth`?"Replace `auth: true` with `authorize: true`. With an `authorize()` callback, remove `auth` and return `false` from the callback when `user` is `null`.":e===`origins-without-identify`?"Remove `origins()`, or add `identify()` that reads a credential the page sends on purpose, such as a ticket in `params`.":e===`not-authorize`?"Set `authorize: true` to require a signed-in user, or set `authorize()` to a function that returns `true` to allow.":'Use `access: "public"` alone for open rooms. To limit access, remove `access` and set `authorize`.'},REALTIME_CHECKPOINT_UNSUPPORTED:{why:"The Realtime definition sets `history.checkpoint`, but its document adapter has no `checkpoint()` method, so `history.checkpoint()` could never run.",fix:"Add `checkpoint(context, { digest, message, user })` to the document adapter, use `document: { workspace }`, or remove `history`."},REALTIME_INVALID_USER:{why:"The realtime identity needs a user `id` that is a non-empty string of at most 256 characters.",fix:"Return a user with an `id` from the Auth session or from `authorize()`."},REALTIME_MISSING_DIGEST:{why:({operation:e})=>e===`save`?`Realtime saves need Workspace file digests, and the Workspace Store did not return one.`:`Realtime checkpoints need a stored document, and the save returned no digest.`,fix:"Use a Workspace Store that returns file digests, or return `digest` from the document adapter `save()`."},REALTIME_INVALID_POSTGRES_URL:{why:"REALTIME_POSTGRES_URL is set, and it is not a `postgres://` or `postgresql://` URL.",fix:`Set REALTIME_POSTGRES_URL to a Postgres URL, or remove it so that Realtime uses the connection of the Default Database.`},REALTIME_MISSING_BUS_CONNECTION:{why:({driver:e})=>e===`redis`?`Realtime driver "redis" shares rooms through Redis, and REDIS_URL is not set.`:`Realtime driver "postgres" shares rooms through Postgres, and the app has no Postgres Default Database and no REALTIME_POSTGRES_URL.`,fix:'Set REDIS_URL for Redis. For Postgres, define the Default Database with `dialect: "postgresql"`, or set REALTIME_POSTGRES_URL. Or set `realtime.driver` to "auto".'},REALTIME_ROOM_LOCK_TIMEOUT:{why:`Realtime waited 30 seconds for the save lock of a room, and another instance still holds it.`,fix:"Make the document adapter `save()` finish in less than 30 seconds. Realtime tries the save again."},REALTIME_DRIVER_CONFLICT:{why:({driver:e,host:t})=>e===`memory`?`Realtime driver "memory" is single-process only, and the ${t} host runs more than one process.`:e===`cloudflare`?`Realtime driver "cloudflare" does not work with the ${t} host.`:`Realtime driver "${e}" needs a Node.js server, and the ${t} host does not run one.`,fix:'Set `realtime.driver` to "cloudflare" with a Cloudflare host. With the Node host, use "auto", "postgres", "redis", or "memory".'},REALTIME_MISSING_DRIVER:{why:`Realtime production builds need one room driver, and ViteHub cannot select one for this deployment.`,fix:`Deploy with a Cloudflare host to use Durable Objects, or with the Node host to share rooms through Postgres or Redis.`},REALTIME_RENAMED_AUTHORITY_KEY:{why:({value:e})=>`\`realtime.authority\` is ${e}. ViteHub renamed this key to \`driver\`, and it does not read \`authority\`, so Realtime would not use the driver you chose.`,fix:({value:e})=>`Set \`realtime: { driver: ${e} }\`, or run \`npx @vite-hub/codemods driver-key\` to rename it in every config file.`}}});function Rs(e){try{let t=JSON.parse(E(e));if(!t||typeof t!=`object`||!(`epoch`in t)||!(`type`in t)||typeof t.epoch!=`string`||!t.epoch)return;if(t.type===`session`&&`access`in t&&(t.access===`read`||t.access===`write`))return t.access===`read`&&`reason`in t&&(t.reason===`access`||t.reason===`document`||t.reason===`version`)?{type:`session`,access:t.access,epoch:t.epoch,reason:t.reason}:{type:`session`,access:t.access,epoch:t.epoch};if(t.type===`reset`&&`reason`in t&&(t.reason===`source-changed`||t.reason===`stale`))return{type:`reset`,epoch:t.epoch,reason:t.reason}}catch{}}function zs(e){if(typeof e!=`string`||e.length===0||e.length>4096||e.includes(`\0`)||e.startsWith(`/`)||e.endsWith(`/`)||e.includes(`\\`)||e.includes(`//`)||/^[a-z]:/i.test(e))return!1;try{return Is(e)===e}catch{return!1}}function Bs(e){try{let t=JSON.parse(E(e));if((t.operation===`create`||t.operation===`delete`||t.operation===`update`)&&zs(t.path))return{operation:t.operation,path:t.path};if(t.operation===`move`&&zs(t.from)&&zs(t.to))return{operation:t.operation,from:t.from,to:t.to}}catch{}}function Vs(e){let t=_();return b(t,4),x(t,JSON.stringify(e)),v(t)}function Hs(e){let t=_();return b(t,6),x(t,JSON.stringify(e)),v(t)}function Us(e){try{let t=JSON.parse(E(e));if(!t||typeof t!=`object`||!(`id`in t)||typeof t.id!=`string`||!t.id||t.id.length>128||!(`kind`in t))return;if(t.kind===`request`)return{kind:`request`,id:t.id,body:`body`in t?t.body:void 0};if(t.kind!==`answer`||!(`ok`in t))return;if(t.ok===!0)return{kind:`answer`,id:t.id,ok:!0,body:`body`in t?t.body:void 0};if(t.ok===!1&&`why`in t&&typeof t.why==`string`)return{kind:`answer`,id:t.id,ok:!1,why:t.why}}catch{}}function Ws(e){let t;e.on(`status`,({status:n})=>{clearInterval(t),t=void 0;let r=e.ws;if(n!==`connected`||!r)return;let i=r.onmessage;r.onmessage=function(t){if(t.data!==`pong`)return i?.call(this,t);e.ws===r&&(e.wsLastMessageReceived=D())},t=setInterval(()=>{e.ws===r&&r.readyState===r.OPEN&&r.send(`ping`)},15e3)})}const Gs=Object.freeze({body:`body`,fields:`fields`,status:`status`});function Ks(e){return typeof e==`string`?e:null}function qs(e){let t=e.getMap(Gs.status),n=t.get(`issues`),r=t.get(`savedBy`),i={issues:Array.isArray(n)?n:[],savedBy:r&&!Array.isArray(r)&&r instanceof Object?r:null};return{digest:Ks(t.get(`digest`)),error:Ks(t.get(`error`)),issues:i.issues,savedAt:Ks(t.get(`savedAt`)),savedBy:i.savedBy}}function Js(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ys=[`#E11D48`,`#D97706`,`#059669`,`#0891B2`,`#2563EB`,`#7C3AED`,`#C026D3`];function $(e){try{return String(e)===e}catch{return!1}}function Xs(e){if(!$(e.id)||!e.id||e.id.length>256)throw Ls.REALTIME_INVALID_USER();let t=0;for(let n=0;n<e.id.length;n++)t=Math.imul(31,t)+e.id.charCodeAt(n)|0;let n=($(e.name)&&e.name||$(e.email)&&e.email||`Anonymous`).slice(0,256),r={color:Ys[Math.abs(t)%Ys.length],id:e.id,name:n};return $(e.image)&&e.image&&e.image.length<=2048&&(r.image=e.image),r}function Zs(e){return Js(e)?$(e.id)&&e.id.length>0&&e.id.length<=256&&$(e.name)&&e.name.length>0&&e.name.length<=256&&$(e.color)&&/^#[\da-f]{6}$/i.test(e.color)&&(e.image===void 0||$(e.image)&&e.image.length<=2048):!1}function Qs(e){let t=[];for(let[n,r]of e)if(Zs(r.user)){let{color:e,id:i,image:a,name:o}=r.user,s={color:e,id:i,name:o,clientId:n};a!==void 0&&(s.image=a),t.push(s)}return t}function $s(e,t,n={}){let r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=[],o,s=`connecting`,c=!1,l=!1,u,d,f=()=>{for(let e of r)e()},ee=()=>{let t=n.origin?new URL(n.origin):window.location;return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}${ms(`/_vitehub/realtime/${encodeURIComponent(e)}`,n.baseURL)}`},te=t.split(`/`).map(encodeURIComponent).join(`/`),ne={};function re(){c=!1,u=new Hr,d=new ps(ee(),te,u,{disableBc:!0,params:{...n.params,clientId:String(u.clientID)}});let e=d;Ws(e),e.messageHandlers[5]=(t,n)=>{let r=Rs(n);r&&(r.type===`session`?e.params.epoch=r.epoch:(e.destroy(),u.destroy(),l||(re(),f())))},e.messageHandlers[6]=(t,n)=>{let r=Us(n);r?.kind===`request`&&ie(e,r.id,r.body)},e.awareness.off(`update`,e._awarenessUpdateHandler),e.awareness.on(`update`,({added:t,removed:n,updated:r})=>{let i=[...t,...r,...n].filter(t=>t===e.doc.clientID),a=e.ws;if(!i.length||!e.wsconnected||!a||a.readyState!==a.OPEN)return;let o=_();b(o,1),S(o,Vo(e.awareness,i)),a.send(v(o))});let t=n.identity??{id:`guest:${u.clientID}`};e.awareness.setLocalState({...ne,user:Xs({...t,id:t.id||`guest:${u.clientID}`})}),e.awareness.on(`change`,f),u.getMap(Gs.status).observe(f),e.on(`sync`,t=>{d===e&&(c=t,f())}),e.on(`status`,e=>{s=e.status,f()})}re();let p;n.changes&&(p=new ps(ee(),`%40workspace`,new Hr,{disableBc:!0,params:{...n.params,workspace:`events`}}),p.awareness.setLocalState(null),Ws(p),p.messageHandlers[4]=(e,t)=>{let n=Bs(t);if(n)for(let e of i)e(n)},p.on(`status`,e=>{e.status===`connected`&&ae()}));async function ie(e,t,n){let r=e=>Hs({kind:`answer`,id:t,ok:!1,why:e}),i;try{i=o?Hs({kind:`answer`,id:t,ok:!0,body:await o(n)}):r(`This page does not answer requests.`),i.byteLength>1047552&&(i=r(`The answer has ${i.byteLength} bytes, over the 1 MiB limit.`))}catch(e){i=r(e instanceof Error?e.message:String(e))}let a=e.ws;e.wsconnected&&a&&a.readyState===a.OPEN&&a.send(Uint8Array.from(i))}function ae(){let e=p?.ws;if(p?.wsconnected&&e&&e.readyState===e.OPEN)for(;a.length;)e.send(Uint8Array.from(Vs(a.shift())))}return{get awareness(){return d.awareness},get clientId(){return u.clientID},people:()=>Qs(d.awareness.getStates()),states:()=>{let e=new Map(d.awareness.getStates());return e.delete(u.clientID),e},status:()=>s,saveStatus:()=>c?qs(u):void 0,setLocal(e,t){if(t!==null){ne[e]=t,d.awareness.setLocalStateField(e,t);return}delete ne[e];let n=d.awareness.getLocalState();if(!n||!Object.hasOwn(n,e))return;let{[e]:r,...i}=n;d.awareness.setLocalState(i)},notify(e){p&&(a.push(e),ae())},onUpdate(e){return r.add(e),()=>r.delete(e)},onChange(e){return i.add(e),()=>i.delete(e)},onRequest(e){return o=e,()=>{o===e&&(o=void 0)}},destroy(){l=!0,d.destroy(),u.destroy(),p?.destroy(),p?.doc.destroy(),r.clear(),i.clear(),o=void 0}}}export{$s as connectRealtimeRoom};
package/dist/client.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { L as RealtimeWorkspaceChange, d as RealtimeDocumentStatus, x as RealtimePerson } from "./types-DdY7Vo1H.js";
1
+ import { L as RealtimeWorkspaceChange, d as RealtimeDocumentStatus, x as RealtimePerson } from "./types-oUyN-CJR.js";
2
2
  import * as awarenessProtocol from "y-protocols/awareness";
3
- //#region src/client.d.ts
4
3
  export type RealtimeRoomStatus = "connected" | "connecting" | "disconnected";
5
4
  /** Answers one request from the server. Its value goes back as JSON. */
6
5
  export type RealtimeRequestHandler = (body: unknown) => unknown;
@@ -63,5 +62,4 @@ export interface RealtimeRoom {
63
62
  * the room document and loads no editor. Use it outside Vue, or when a page needs presence or the save status without
64
63
  * an editor; `useRealtimeTiptap()` from `@vite-hub/realtime/vue` is the editor client.
65
64
  */
66
- export declare function connectRealtimeRoom(definition: string, documentId: string, options?: RealtimeRoomOptions): RealtimeRoom;
67
- //#endregion
65
+ export declare function connectRealtimeRoom(definition: string, documentId: string, options?: RealtimeRoomOptions): RealtimeRoom;
package/dist/client.js CHANGED
@@ -1,13 +1,13 @@
1
- import { n as resolveRealtimeApplicationPath, t as keepRealtimeSocketAlive } from "./keepalive-B4ONG6AD.js";
2
- import { a as decodeRealtimeRequestFramePayload, c as encodeRealtimeRequestFrame, i as decodeRealtimeControlPayload, l as encodeWorkspaceChange, o as decodeWorkspaceChangePayload, x as workspaceRoomId } from "./object-BgPPDLDE.js";
3
- import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-DNaxppTZ.js";
4
- import { n as getRealtimePeople, t as createRealtimeIdentity } from "./presence-B6rvkHqd.js";
1
+ import { n as resolveRealtimeApplicationPath, t as keepRealtimeSocketAlive } from "./keepalive-BYkk6Ax8.js";
2
+ import { n as realtimeDocumentLayout, t as readRealtimeStatus } from "./layout-BQwRLTH0.js";
3
+ import { n as getRealtimePeople, t as createRealtimeIdentity } from "./presence-DZ21pPKm.js";
4
+ import { a as decodeRealtimeRequestFramePayload, c as encodeRealtimeRequestFrame, i as decodeRealtimeControlPayload, l as encodeWorkspaceChange, o as decodeWorkspaceChangePayload, x as workspaceRoomId } from "./object-DfrneieE.js";
5
5
  import "lib0/decoding";
6
6
  import * as encoding from "lib0/encoding";
7
7
  import * as awarenessProtocol from "y-protocols/awareness";
8
8
  import { WebsocketProvider } from "y-websocket";
9
9
  import * as Y from "yjs";
10
- //#region src/client.ts
10
+ // src/client.ts
11
11
  const maxAnswerBytes = 1047552;
12
12
  /**
13
13
  * Joins one room of a Realtime Definition for presence: who is there and what each person shares through awareness,
@@ -203,5 +203,4 @@ function connectRealtimeRoom(definition, documentId, options = {}) {
203
203
  }
204
204
  };
205
205
  }
206
- //#endregion
207
206
  export { connectRealtimeRoom };
@@ -1,6 +1,6 @@
1
- import { t as realtimeErrorDiagnostics } from "./error-diagnostics-Cd-XWNf7.js";
1
+ import { t as realtimeErrorDiagnostics } from "./error-diagnostics-we8V1O-X.js";
2
2
  import { Diagnostic } from "nostics";
3
- //#region src/definition.ts
3
+ // src/definition.ts
4
4
  /**
5
5
  * Checks a definition when the server loads it. A definition must say who can use its rooms: `authorize: true`,
6
6
  * `authorize()`, or `access: "public"`. `history.checkpoint` needs a document that can record history: a Workspace
@@ -28,8 +28,7 @@ function assertRealtimeCheckpoint(definition) {
28
28
  const document = definition.document;
29
29
  if ("load" in document && typeof document.checkpoint !== "function") throw realtimeErrorDiagnostics.REALTIME_CHECKPOINT_UNSUPPORTED();
30
30
  }
31
- //#endregion
32
- //#region src/conflict.ts
31
+ // src/conflict.ts
33
32
  const conflictCode = "REALTIME_DOCUMENT_CONFLICT";
34
33
  /** Thrown by a document adapter when the stored digest no longer matches `ifDigest`. */
35
34
  var RealtimeDocumentConflict = class RealtimeDocumentConflict extends Diagnostic {
@@ -59,5 +58,4 @@ function isRealtimeDocumentConflict(error) {
59
58
  if (!error || typeof error !== "object" || !("code" in error)) return false;
60
59
  return error.code === conflictCode;
61
60
  }
62
- //#endregion
63
61
  export { defineRealtime as a, assertRealtimeCheckpoint as i, isRealtimeDocumentConflict as n, assertRealtimeAccess as r, RealtimeDocumentConflict as t };
@@ -1,5 +1,4 @@
1
1
  import { Diagnostic } from "nostics";
2
- //#region src/conflict.d.ts
3
2
  /** Thrown by a document adapter when the stored digest no longer matches `ifDigest`. */
4
3
  declare class RealtimeDocumentConflict extends Diagnostic {
5
4
  constructor(why?: string);
@@ -13,5 +12,4 @@ declare class RealtimeDocumentConflict extends Diagnostic {
13
12
  };
14
13
  }
15
14
  declare function isRealtimeDocumentConflict(error: unknown): boolean;
16
- //#endregion
17
15
  export { isRealtimeDocumentConflict as n, RealtimeDocumentConflict as t };