@popmelt.com/core 0.26.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/claude-plugin/.claude-plugin/plugin.json +1 -1
- package/codex-plugin/.codex-plugin/plugin.json +1 -1
- package/dist/{ParticipantRuntime-5WM2XJT7.mjs → ParticipantRuntime-AD3YD4FW.mjs} +1 -1
- package/dist/{PopmeltTasteConnectedPane-IXJ2KAPX.mjs → PopmeltTasteConnectedPane-HLCTVPJP.mjs} +6 -6
- package/dist/{PreviewRuntime-ATSECGMB.mjs → PreviewRuntime-KGLZJGUN.mjs} +1 -1
- package/dist/adapter-react-three-fiber.d.mts +1 -1
- package/dist/adapter-three.d.mts +6 -0
- package/dist/bridge-entry.mjs +2 -2
- package/dist/{browser-runtime-O5GITMZB.mjs → browser-runtime-3JZGB3P2.mjs} +1 -1
- package/dist/browser.d.mts +4 -4
- package/dist/browser.mjs +1 -1
- package/dist/{chunk-FRHGK5ZV.mjs → chunk-7YCLSSQA.mjs} +1 -1
- package/dist/chunk-7YIQQYRU.mjs +77 -0
- package/dist/{chunk-7IVK4FEU.mjs → chunk-C5Q6LDAS.mjs} +1 -1
- package/dist/chunk-D7HY2EDH.mjs +2 -0
- package/dist/chunk-MDJYUX5S.mjs +370 -0
- package/dist/{chunk-MGIH5NQE.mjs → chunk-MTRUVFH7.mjs} +1 -1
- package/dist/chunk-TFPKDKDO.mjs +345 -0
- package/dist/{chunk-NXMPY7RX.mjs → chunk-TSY2K45H.mjs} +1 -1
- package/dist/cli.mjs +2 -2
- package/dist/index.d.mts +5 -5
- package/dist/index.mjs +1 -1
- package/dist/media.d.mts +3 -3
- package/dist/{participantBootstrap-BQHbHI4r.d.mts → participantBootstrap-QZ3wuqi1.d.mts} +2 -2
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-nuxt.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/{server-QHSVIUQW.mjs → server-MJF4KF26.mjs} +2 -2
- package/dist/server.mjs +30 -30
- package/dist/{subjects-BM3Smdow.d.mts → subjects-CG6UyWFr.d.mts} +6 -0
- package/dist/{video-adapter-Gm5gmoiz.d.mts → video-adapter-DrTI5cRl.d.mts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-CWVRJOGB.mjs +0 -370
- package/dist/chunk-EH5Y2F4E.mjs +0 -77
- package/dist/chunk-J2OX47QB.mjs +0 -345
- package/dist/chunk-ZJPPZLXU.mjs +0 -2
package/README.md
CHANGED
|
@@ -70,6 +70,14 @@ Paste images into a comment to attach visual references. An image-count chip kee
|
|
|
70
70
|
|
|
71
71
|
Double-click visible text to edit it directly. Popmelt records the text change so it can be handed off alongside comments and Steer changes.
|
|
72
72
|
|
|
73
|
+
#### Screens inside a canvas
|
|
74
|
+
|
|
75
|
+
Chat can target elements and edit visible DOM text inside **same-origin iframes**, including screens laid out in a translated/scaled canvas. Install Popmelt once in the outer page. Notes, text previews, and screenshot markers follow the selected screen through pan, zoom, and internal scrolling. Sent context includes the screen's URL, title, and frame label; identical element IDs in different screens remain distinct. Preview text edits affect only the selected screen instance, not the source code until handed off.
|
|
76
|
+
|
|
77
|
+
Give each iframe a stable, unique `id` or `data-testid` (for example, `id="passkey-success"`) and a descriptive `title`. Authored identity lets comments recover after a screen remount; without it Popmelt assigns a session-only frame ID. A frame that navigates to a different URL is not silently retargeted. Canvas fixtures may leave iframe `pointer-events: none` in their pan mode; Popmelt temporarily enables hit testing only while resolving a target and restores that setting immediately.
|
|
78
|
+
|
|
79
|
+
Cross-origin frames and sandboxed frames without same-origin access remain opaque. This support covers axis-aligned translation/scale, not rotated/skewed frame geometry, iframe Steer handles, or interaction recording inside frames. DOM-fallback screenshots include accessible frame content and scroll/clipping; native browser capture remains preferable for browser-rendered media and complex effects.
|
|
80
|
+
|
|
73
81
|
### Steer
|
|
74
82
|
|
|
75
83
|
Steer previews code-native design changes directly on the page. Point to an element, choose a family, narrow to a property, and choose a value. Click the target or press Enter at the value level to stage the preview.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{a as Jt}from"./chunk-FRHGK5ZV.mjs";import{Pb as Wt,vb as Ut,Yb as gt,gb as _t,nb as qt,ub as tt,jb as zt,mb as Ft,b as Vt,kb as Ht,ca as Xt,ib as Kt,lb as Yt,Ob as Bt,Kb as Zt,pb as Gt,Hb as Qt,Jb as er,Lb as tr,Nb as rr,Mb as yt,v as nr,fb as vt,hb as ir,ab as ar,tb as or,ob as sr,fc as lr,f as dr,d as wt}from"./chunk-J2OX47QB.mjs";import{xa as cr,va as rt,Z as ze,aa as ur,u as pr,Ea as fr,Ia as hr,H as mr}from"./chunk-EH5Y2F4E.mjs";import{d as je}from"./chunk-NXMPY7RX.mjs";import{h as gr,d as bt}from"./chunk-ZJPPZLXU.mjs";import{useState as U,useSyncExternalStore as It,useEffect as ee,useRef as K,useCallback as Je,useMemo as nt,useId as yr,useLayoutEffect as St}from"react";import{Link2 as vr,Ban as wr,Clock as br,X as Ir,Hand as Sr,SendHorizontal as kr,LoaderCircle as Er,RotateCcw as Pr,Check as xr,Copy as Ar}from"lucide-react";import{jsxs as B,jsx as S,Fragment as We}from"react/jsx-runtime";var Cr=class extends Error{constructor(){super("The saved draft changed in another runtime. Your local changes are preserved.")}},it=(e,t)=>e.revision===t.revision&&JSON.stringify(e.source)===JSON.stringify(t.source)&&JSON.stringify(e.state)===JSON.stringify(t.state);function Tr(e){let t=structuredClone(e.draft.state??je),r=structuredClone(e.source),i=e.draft.revision,n=0,a=0,s=null,d=!1,o=structuredClone(e.draft),f=null,l=null,u=!1,w=new Set,I=new Set,y=()=>{for(let c of[...I])c()},b={getSnapshot:()=>t,subscribe:c=>(w.add(c),()=>{w.delete(c)}),dispatch:c=>{if(u)throw new Error("Participant runtime is disposed");let p=wt(t,c);if(p!==t){t=p,n++;for(let x of[...w])x();y()}}},g=()=>u?Promise.reject(new Error("Participant runtime is disposed")):l||(s||d?Promise.reject(s??new Error("Draft sync paused")):n===a?Promise.resolve():(l=Promise.resolve().then(async()=>{for(;!u&&!d&&n!==a;){let c=n,p=structuredClone(r),x=structuredClone(t);f={generation:c,draft:{revision:i+1,source:p,state:x}};let A=await e.save(i,p,x);if(!it(A,f.draft))throw new Error("Unexpected saved draft revision; reconnect before writing");i=A.revision,a=c,o=structuredClone(A),f=null}}).catch(c=>{throw s=c instanceof Error?c:new Error(String(c)),s}).finally(()=>{l=null,y()}),l));return{binding:b,flush:g,getStatus:()=>({revision:i,unsaved:n!==a,error:s,disposed:u}),subscribeStatus(c){return I.add(c),()=>{I.delete(c)}},pause(c){d=!0,s=c,y()},async whenSettled(){await l?.catch(()=>{})},reconcile(c){if(u)throw new Error("Participant runtime is disposed");if(l)throw new Error("Wait for the pending save before reconciling");if(!it(c,o)){if(!f||!it(c,f.draft))throw new Cr;i=c.revision,a=f.generation,o=structuredClone(c)}f=null,s=null,d=!1,y()},retry(){return s=null,d=!1,g()},setSource(c){if(u)throw new Error("Participant runtime is disposed");if(c.sourceId!==r.sourceId)throw new Error("Changing source worlds requires a new participant runtime");c.revision!==r.revision&&(r=structuredClone(c),n++,y())},async revoke(){u=!0,d=!0,await l?.catch(()=>{}),t=structuredClone(je),f=null,o={revision:i,source:null,state:null};for(let c of[...w])c();y()},dispose(){u=!0,w.clear(),I.clear()}}}var kt=8192,at=8*1024*1024,jr=256,Fe=100,Ae=(...e)=>JSON.stringify(e),Ve=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Re=e=>structuredClone(e),Or=class extends Error{constructor(){super("This edit predates retained synchronization history"),this.name="PlaneHistoryExpiredError"}},Et=(e,t)=>Pt(e.stamp,t.stamp)||(e.id<t.id?-1:e.id>t.id?1:0);function He(e,t){let r=new Map([...e.checkpoint?.receipts??[],...e.events].map(a=>[a.id,a])),i=[],n=[];for(let a of t){let s=r.get(a.id);if(s){if(!Ve(s,a))throw new Error("Plane event identity was reused");continue}e.checkpoint&&Et(a,e.checkpoint.through)<=0?n.push(a):i.push(a)}return{pending:i,superseded:n}}function Mr(e,t){let r=He(e,t);if(r.superseded.length)throw new Or;return r.pending}function Pt(e,t){return e.time-t.time||e.counter-t.counter||(e.actor<t.actor?-1:e.actor>t.actor?1:0)}function Nr(e,t,r,i){let n=r.reduce((s,d)=>!s||Pt(d.stamp,s)>0?d.stamp:s,t),a=Math.max(Math.floor(i),n?.time??0);return{actor:e,time:a,counter:a===n?.time?n.counter+1:0}}function ot(e){let t=new Map;for(let r of e.annotations){t.set(Ae("annotation",r.id),!0);for(let[i,n]of Object.entries(r))i!=="id"&&n!==void 0&&t.set(Ae("annotation",r.id,i),n)}for(let r of e.styleModifications){let i=Ae(r.pathname??"/",r.selector),{changes:n,...a}=r;t.set(Ae("styleMeta",i),a);for(let s of n)t.set(Ae("style",i,s.property),s)}for(let r of e.textModifications)t.set(Ae("text",Ae(r.pathname??"/",r.selector,JSON.stringify(r.textNodePath))),r);for(let r of e.domModifications)t.set(Ae("dom",r.id),r);for(let r of e.spacingTokenChanges)t.set(Ae("spacing",r.tokenPath),r);for(let r of e.spacingTokenMods)t.set(Ae("spacingMod",r.tokenPath),r);return t}function st(e,t){let r=ot(e),i=ot(t);return[...new Set([...r.keys(),...i.keys()])].filter(n=>!(JSON.parse(n)[0]==="styleMeta"&&!i.has(n))).filter(n=>!Ve(r.get(n),i.get(n))).map(n=>({key:n,...i.has(n)?{value:Re(i.get(n))}:{}}))}function xt(e,t){let r={...t,annotations:[],styleModifications:[],textModifications:[],domModifications:[],spacingTokenChanges:[],spacingTokenMods:[]},i=new Map;for(let[a,s]of e){let[d,o,f]=JSON.parse(a);d==="annotation"&&!f&&s===!0&&i.set(o,{id:o})}let n=new Map;for(let[a,s]of e){let[d,o,f]=JSON.parse(a);if(d==="annotation"&&f&&i.has(o)&&Object.defineProperty(i.get(o),f,{value:s,enumerable:!0,configurable:!0,writable:!0}),d==="style"){let l=n.get(o),u=e.get(Ae("styleMeta",o));if(!u)continue;l||(l={...u,changes:[]},n.set(o,l)),l.changes.push(s)}d==="text"&&r.textModifications.push(s),d==="dom"&&r.domModifications.push(s),d==="spacing"&&r.spacingTokenChanges.push(s),d==="spacingMod"&&r.spacingTokenMods.push(s)}return r.annotations=[...i.values()],r.styleModifications=[...n.values()],r.selectedAnnotationIds=t.selectedAnnotationIds.filter(a=>i.has(a)),r.lastSelectedId=r.selectedAnnotationIds.includes(t.lastSelectedId??"")?t.lastSelectedId:null,r}var At=e=>({annotations:e.annotations,styleModifications:e.styleModifications,textModifications:e.textModifications,domModifications:e.domModifications,spacingTokenChanges:e.spacingTokenChanges,spacingTokenMods:e.spacingTokenMods});function lt(e=je){let t=[...e.undoStack.slice(-Fe),At(e)],r={...Re(e),...Re(t[0]),undoStack:[],redoStack:[]},i=[];for(let s=1;s<t.length;s++){let d=`migration:${s}`;i.push({id:d,stamp:{time:0,counter:s,actor:"migration"},kind:"edit",group:d,changes:st({...r,...t[s-1]},{...r,...t[s]})})}let n=e,a=[];for(let s of[...e.redoStack].reverse().slice(0,Fe)){let d=`migration:${i.length+1}`,o={...r,...s};i.push({id:d,stamp:{time:0,counter:i.length+1,actor:"migration"},kind:"edit",group:d,changes:st(n,o)}),a.push(d),n=o}for(let s of a.reverse()){let d=`migration:${i.length+1}`;i.push({id:d,stamp:{time:0,counter:i.length+1,actor:"migration"},kind:"undo",target:s})}return{version:1,base:r,events:i}}function dt(e){if(!Array.isArray(e)||e.length>kt||JSON.stringify(e).length>at)throw new Error("Plane history exceeds the local session limit");for(let t of e){let r=n=>typeof n=="string"&&n.length>0&&n.length<=256;if(!t||!r(t.id)||!t.stamp||!r(t.stamp.actor)||!Number.isSafeInteger(t.stamp.time)||t.stamp.time<0||!Number.isSafeInteger(t.stamp.counter)||t.stamp.counter<0||!["edit","undo","redo"].includes(t.kind))throw new Error("Invalid plane event");if(t.kind!=="edit"){if(!r(t.target))throw new Error("Invalid history target");continue}if(t.group!==void 0&&!r(t.group)||t.reset!==void 0&&typeof t.reset!="boolean"||!Array.isArray(t.changes)||t.changes.length>1e4)throw new Error("Invalid plane edit");let i=new Set;for(let n of t.changes){if(!n||typeof n.key!="string"||n.key.length>8192)throw new Error("Invalid property key");let a=JSON.parse(n.key);if(!Array.isArray(a)||a.length<2||a.length>3||a.some(s=>typeof s!="string"||!s.length)||!["annotation","style","styleMeta","text","dom","spacing","spacingMod"].includes(a[0])||a[0]==="style"&&a.length!==3||!["style","annotation"].includes(a[0])&&a.length!==2||a[0]==="annotation"&&a.length===2&&n.value!==void 0&&n.value!==!0||i.has(n.key))throw new Error("Invalid property key");i.add(n.key)}}return Re(e)}function ct(e,t){let r=new Map(e.events.map(i=>[i.id,i]));for(let i of Mr(e,t)){let n=r.get(i.id);if(n&&!Ve(n,i))throw new Error("Plane event identity was reused");r.set(i.id,i)}if(r.size>kt)throw new Error("Plane history exceeds the local session limit");return{...e,events:[...r.values()].sort(Et)}}function Rr(e){if(e.version!==1&&e.version!==2)throw new Error("Unsupported plane history version");if(e.version===2&&!e.checkpoint)throw new Error("Missing plane history checkpoint");let t=e.checkpoint,r=t?new Map(Re(t.cells)):ot(e.base),i=new Map(t?.writers??[]),n=Re(t?.undo??[]),a=Re(t?.redo??[]),s=(d,o)=>{let f=[],l=[...d].sort((u,w)=>JSON.parse(u.key).length-JSON.parse(w.key).length);for(let u of l){let[w,I,y]=JSON.parse(u.key);if(w==="styleMeta"&&u.value===void 0)continue;let b=i.get(u.key)??"base";if(u.guard!==void 0&&b!==u.guard||w==="annotation"&&y&&!r.has(Ae(w,I)))continue;let g=r.get(u.key);u.value===void 0?r.delete(u.key):r.set(u.key,u.value);let c=u.restoreWriter??o;if(i.set(u.key,c),f.push({key:u.key,before:g,after:u.value,beforeWriter:b,afterWriter:c}),w==="annotation"&&!y&&u.value===void 0)for(let p of[...r.keys()]){let[x,A]=JSON.parse(p);x===w&&A===I&&(f.push({key:p,before:r.get(p),after:void 0,beforeWriter:i.get(p)??"base",afterWriter:c}),r.delete(p),i.set(p,c))}}return f};for(let d of e.events)if(d.kind==="edit"){let o=s(d.changes,d.group??d.id);if(d.reset&&(n.length=0,a.length=0),!d.group||!o.length)continue;let f=n.find(l=>l.id===d.group);if(f)for(let l of o){let u=f.changes.find(w=>w.key===l.key);u?(u.after=l.after,u.afterWriter=l.afterWriter):f.changes.push(l)}else n.push({id:d.group,writer:d.group,changes:o});a.length=0,n.length>Fe&&n.shift()}else{let o=d.kind==="undo"?n:a,f=d.kind==="undo"?a:n,l=o.findIndex(I=>I.id===d.target);if(l<0)continue;let u=o.splice(l,1)[0],w=s(u.changes.map(I=>({key:I.key,value:I.before,guard:I.afterWriter,restoreWriter:I.beforeWriter})),d.id);w.length&&f.push({id:d.id,writer:d.id,changes:w}),f.length>Fe&&f.shift()}return{cells:r,writers:i,undo:n,redo:a}}function ut(e,t=e.base,r=!0){let{cells:i,writers:n,undo:a,redo:s}=Rr(e),d=xt(i,t);d.styleModifications=d.styleModifications.filter(I=>!e.hostStyleDeletions?.some(y=>dr(I,y)));let o=new Set(Object.keys(e.hostDeletions??{}));d.annotations=d.annotations.filter(I=>!o.has(I.id)),d.selectedAnnotationIds=d.selectedAnnotationIds.filter(I=>!o.has(I));let f=I=>{let y=new Map(i);for(let b of I.changes)(n.get(b.key)??"base")===b.afterWriter&&(b.before===void 0?y.delete(b.key):y.set(b.key,b.before));return At(xt(y,t))},l=I=>I.filter(y=>y.changes.some(b=>JSON.parse(b.key)[0]!=="styleMeta"&&(n.get(b.key)??"base")===b.afterWriter&&!Ve(b.before,i.get(b.key)))),u=l(a),w=l(s);return d.undoStack=r?u.map(f):[],d.redoStack=r?w.map(f):[],{state:Re(d),undo:u.map(I=>I.id),redo:w.map(I=>I.id)}}function $r(e){let t=structuredClone(e.draft.history??lt(e.draft.state??je)),r=He(t,e.pendingEvents??[]);t=ct(t,r.pending);let i=ut(t,{...structuredClone(e.draft.state??je),...e.view}),n=i.state,a=structuredClone(e.source),s=e.draft.revision,d=r.pending,o=structuredClone(e.draft),f=null,l=!!e.persist,u=0,w=0,I=Promise.resolve(),y=!1,b,g,c=null,p=null,x=!1,A=!1,P=new Set,C=new Set,O=()=>{for(let v of[...P])v()},M=()=>{for(let v of[...C])v()},j=()=>{i=ut(t,n),n=i.state},D=()=>{if(!e.persist||!l)return Promise.resolve();let v=structuredClone(o),te=structuredClone(a),z=structuredClone(d),F=u;return w++,I=I.then(()=>e.persist(v,te,z)).then(()=>{F===u&&(f=null)}).catch(R=>{F===u&&(f=R instanceof Error?R:new Error(String(R)))}).finally(()=>{F===u&&(w--,M())}),I},_=async()=>{do await I;while(w>0);if(f)throw f},ie=v=>{if(v.revision<s)return;if(v.source&&v.source.sourceId!==a.sourceId)throw new Error("Draft source world mismatch");if(!v.history)throw new Error("Shared history is unavailable; reconnect to an updated bridge");let te=He(v.history,d),z=ct(structuredClone(v.history),te.pending),F=JSON.stringify(z.hostStyleDeletions)!==JSON.stringify(t.hostStyleDeletions)||JSON.stringify(z.hostDeletions)!==JSON.stringify(t.hostDeletions)||z.checkpoint?.through.id!==t.checkpoint?.through.id||z.events.length!==t.events.length||z.events.some((R,$)=>R.id!==t.events[$]?.id);d=te.pending,te.superseded.length&&(g=void 0),t=z,s=v.revision,o=structuredClone(v),F&&j(),D()},H={getSnapshot:()=>n,subscribe(v){return P.add(v),()=>{P.delete(v)}},dispatch(v){if(A)throw new Error("Participant runtime is disposed");let te=n,z,F=()=>(b=Nr(e.actor,b,t.events,(e.now??Date.now)()),b),R=()=>crypto.randomUUID();if(v.type==="UNDO"||v.type==="REDO"){let $=(v.type==="UNDO"?i.undo:i.redo).at(-1);if(!$)return;z={id:R(),stamp:F(),kind:v.type==="UNDO"?"undo":"redo",target:$},g=void 0}else{let $=wt(n,v);if($===n)return;let L=v.type==="UPDATE_LINKED_POSITIONS"?[]:st(n,$),oe=$.undoStack.length>n.undoStack.length,me=["MODIFY_STYLE","MOVE_ANNOTATION","RESIZE_ANNOTATION","UPDATE_TEXT_SIZE","UPDATE_ANNOTATION_COLOR"].includes(v.type);if(L.length){let be=R(),pe=oe||me?!oe&&g&&g===i.undo.at(-1)?g:be:void 0;z={id:be,stamp:F(),kind:"edit",changes:L,...pe?{group:pe}:{},...v.type==="CLEAR"?{reset:!0}:{}},g=pe}n=$}if(z){try{t=ct(t,[z])}catch($){n=te,p=$ instanceof Error?$:new Error(String($)),x=!0,g=void 0,O(),M();return}d.push(z),j(),D()}O(),M(),e.saveView?.(n)}},ae=()=>A?Promise.reject(new Error("Participant runtime is disposed")):c||(p||x?Promise.reject(p??new Error("Draft sync paused")):!d.length&&!y&&!w&&!f?Promise.resolve():(c=Promise.resolve().then(async()=>{for(f&&await D(),await _();!A&&!x&&(d.length||y);){await _();let v=structuredClone(d.slice(0,jr)),te=structuredClone(a),z=await e.save(s,te,n,v);if(A)return;ie(z),await _(),a.revision===te.revision&&(y=!1),O()}}).catch(v=>{throw p=v instanceof Error?v:new Error(String(v)),p}).finally(()=>{c=null,M()}),c));return{binding:H,flush:ae,getStatus:()=>({revision:s,unsaved:d.length>0||y,error:p,localError:f,memoryOnly:!l,savingLocally:w>0,disposed:A}),subscribeStatus(v){return C.add(v),()=>{C.delete(v)}},pause(v){x=!0,p=v,M()},async whenSettled(){await c?.catch(()=>{}),await _().catch(()=>{})},whenDurable:_,async retryLocalSave(){if(A)throw new Error("Participant runtime is disposed");await D(),await _()},async clearLocalSpace(){if(x=!0,await c?.catch(()=>{}),await _().catch(()=>{}),A)throw new Error("Participant runtime is disposed");l=!1,d=[],y=!1,g=void 0,t=structuredClone(o.history??lt(o.state??je)),i=ut(t,{...structuredClone(je),activeColor:n.activeColor,isAnnotating:n.isAnnotating}),n=i.state,s=o.revision,f=null,p=null,O(),M()},async resumeLocalSaving(){if(!e.persist||A)return!1;l=!0;let v;try{return await Promise.race([D().then(_),new Promise((te,z)=>{v=setTimeout(()=>z(new Error("Local saving timed out")),2e3)})]),!A}catch{return u++,l=!1,w=0,I=Promise.resolve(),f=null,M(),!1}finally{clearTimeout(v)}},reconcile(v){if(A)throw new Error("Participant runtime is disposed");if(c)throw new Error("Wait for the pending save before reconciling");ie(v),p=null,x=!1,O(),M()},receive(v){A||x||c||v.revision<=s||(ie(v),O(),M())},retry(){return x=!1,p=null,ae()},setSource(v){if(v.sourceId!==a.sourceId)throw new Error("Changing source worlds requires a new participant runtime");v.revision===a.revision&&o.source?.revision===v.revision||(a=structuredClone(v),y=!0,M())},async revoke(){A=!0,x=!0,await c?.catch(()=>{}),await _().catch(()=>{}),d=[],t=lt(je),n=structuredClone(je),o={revision:s,source:null,state:null},O(),M()},dispose(){A=!0,P.clear(),C.clear()}}}function Lr(e,t){if(!t.reference.draft.history||t.reference.draft.source&&t.basis.sourceId!==t.reference.draft.source.sourceId)throw new Error("Offline recovery requires a matching shared-history source");if(e&&(e.version!==1||e.reference.author.id!==t.reference.author.id||e.reference.planeId!==t.reference.planeId||e.basis.sourceId!==t.basis.sourceId))throw new Error("Offline recovery belongs to a different plane");let r=e&&e.reference.draft.revision>t.reference.draft.revision?e.reference:t.reference,i=new Map;for(let o of[...dt(e?.pending??[]),...dt(t.pending)]){let f=i.get(o.id);if(f&&JSON.stringify(f)!==JSON.stringify(o))throw new Error("Offline operation identity was reused");i.set(o.id,o)}let n=He(r.draft.history,[...i.values()]),a=new Set(n.pending.map(o=>o.id)),s=e?.pending.some(o=>a.has(o.id)),d={version:1,reference:r,basis:s?e.basis:t.basis,pending:n.pending,...e?.superseded?{superseded:e.superseded}:{}};if(n.superseded.length){let o=n.superseded.slice(-128);for(;o.length&&new TextEncoder().encode(JSON.stringify(o)).length>256*1024;)o.shift();d.superseded={revision:r.draft.revision,events:o,omitted:n.superseded.length-o.length}}if(dt(d.pending),d.superseded&&new TextEncoder().encode(JSON.stringify(d)).length>at&&delete d.superseded,new TextEncoder().encode(JSON.stringify(d)).length>at)throw new Error("Offline recovery storage limit reached; pending work is preserved");return structuredClone(d)}function Dr(e,t,r,i=indexedDB){let n=JSON.stringify([new URL(e).origin,t,r]),a=!1,s=new Promise((o,f)=>{let l=i.open("popmelt-plane-recovery",1);l.onupgradeneeded=()=>l.result.createObjectStore("planes"),l.onerror=()=>f(new Error("Could not open local draft recovery",{cause:l.error})),l.onblocked=()=>f(new Error("Local draft recovery is blocked by another browser view")),l.onsuccess=()=>{if(a){l.result.close(),f(new Error("Local draft recovery is closed"));return}l.result.onversionchange=()=>l.result.close(),o(l.result)}});s.catch(()=>{});let d=async o=>{let f=await s;if(a)throw new Error("Local draft recovery is closed");return new Promise((l,u)=>{let w=f.transaction("planes",o?"readwrite":"readonly"),I=w.objectStore("planes"),y=null,b,g=I.get(n);g.onsuccess=()=>{try{if(y=g.result??null,y&&(y.version!==1||y.reference.author.id!==r||y.basis.sourceId!==t))throw new Error("Invalid local recovery record; it has been preserved");o&&(y=Lr(y,o),I.put(y,n))}catch(c){b=c,w.abort()}},w.oncomplete=()=>l(y),w.onabort=()=>u(b??new Error("Could not save local draft recovery",{cause:w.error})),w.onerror=()=>{}})};return{read:()=>d(),update:o=>d(structuredClone(o)),async clear(){let o=await s;if(a)throw new Error("Local draft recovery is closed");await new Promise((f,l)=>{let u=o.transaction("planes","readwrite");u.objectStore("planes").delete(n),u.oncomplete=()=>f(),u.onabort=()=>l(u.error??new Error("Could not clear local draft recovery"))})},close(){a=!0,s.then(o=>o.close()).catch(()=>{})}}}var ke=class extends Error{constructor(e,t,r){super(t),this.status=e,this.code=r}},Ct=class{constructor(e,t,r,i=(...n)=>fetch(...n)){this.projectId=t,this.transport=i;let n=new URL(e);if(n.protocol!=="http:"||!["localhost","127.0.0.1","[::1]"].includes(n.hostname)||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw new Error("Participant transport requires a local bridge origin");if(!t)throw new Error("Project identity required");this.base=n.origin,this.credential=r?{...r}:void 0}moderateStyles(e,t,r=!1){return this.rpc("moderate-styles",{participantId:e,styleModifications:t,restore:r})}moderateAnnotations(e,t,r=!1,i){return this.rpc("moderate-annotations",{participantId:e,annotationIds:t,restore:r,threadId:i})}async request(e,t,r={},i){let n=t instanceof FormData,a=await this.transport(this.base+e,{method:"POST",redirect:"error",credentials:"omit",signal:i??AbortSignal.timeout(3e4),headers:{...n?{}:{"Content-Type":"application/json"},"X-Popmelt-Project-Id":this.projectId,...this.credential?{"X-Popmelt-Participant-Id":this.credential.participantId,"X-Popmelt-Participant-Token":this.credential.token}:{},...r},body:n?t:JSON.stringify(t)}),s=await a.json().catch(()=>null);if(!a.ok)throw new ke(a.status,typeof s?.error=="string"?s.error:"Participant request failed",typeof s?.code=="string"?s.code:void 0);if(s===null)throw new Error("Invalid participant response");return{data:s,status:a.status}}async rpc(e,t={},r){return(await this.request("/participants/"+e,t,{},r)).data}mountRequestScope(e){if(!this.credential)throw new Error("Join before mounting a canvas");return pr(this.base,{"X-Popmelt-Project-Id":this.projectId,"X-Popmelt-Participant-Id":this.credential.participantId,"X-Popmelt-Participant-Token":this.credential.token,...e?{"X-Popmelt-Source-Revision":e.revision}:{}})}source(){return this.rpc("source")}snapshot(){return this.rpc("snapshot")}setHostModelSelection(e){return this.rpc("model-selection",{selection:e})}reserveAdmissionColor(e){return this.rpc("access-color",{receipt:e})}requestAdmission(e,t,r){return this.rpc("access-request",{receipt:e,name:t,colorIdentity:r})}admissionStatus(e){return this.rpc("access-status",{receipt:e})}cancelAdmission(e){return this.rpc("access-cancel",{receipt:e})}admissions(){return this.rpc("access-list")}decideAdmission(e,t){return this.rpc("access-decide",{id:e,decision:t})}attention(){return this.rpc("attention-read")}async reportAttention(e,t,r,i,n){return(await this.request("/participants/attention",{runtime:e,phase:t,operationId:r,location:i},{},n??AbortSignal.timeout(1500))).data}invite(){return this.rpc("invite")}revokeInvite(e){return this.rpc("revoke-invite",{invitation:e})}join(e,t,r){return this.rpc("join",{invitation:e,name:t,...r?{colorIdentity:r}:{}})}joinOrRequestAdmission(e,t,r){return this.rpc("join-or-request",{invitation:e,name:t,colorIdentity:r})}read(e,t){return this.rpc("read",{participantId:e,historyVersion:2},t)}connect(e,t){return this.rpc("connect",{runtimeId:e,previousToken:t})}renew(e,t){return this.rpc("renew",{runtime:e,activeColor:t})}disconnect(e){return this.rpc("disconnect",{runtime:e})}publish(e,t,r,i){return r.sourceId!==this.projectId?Promise.reject(new Error("Source world mismatch")):this.rpc("publish",{runtime:e,expectedRevision:t,sourceRevision:r.revision,state:i})}merge(e,t,r,i){return r.sourceId!==this.projectId?Promise.reject(new Error("Source world mismatch")):this.rpc("merge",{runtime:e,expectedRevision:t,sourceRevision:r.revision,events:i,historyVersion:2})}rename(e){return this.rpc("rename",{name:e})}setPermission(e,t){return this.rpc("permission",{participantId:e,permission:t})}revokeAccess(e){return this.rpc("revoke-access",{participantId:e})}pending(){return this.rpc("pending")}preview(e){return this.rpc("preview-read",{participantId:e})}previewWanted(e){return this.rpc("preview-demand",{runtime:e})}publishPreview(e,t,r){return this.rpc("preview-publish",{runtime:e,image:t,geometry:r})}review(e){return this.rpc("review",{id:e})}discard(e){return this.rpc("discard",{id:e})}submission(e,t){if(t===202&&e.pendingApproval===!0&&typeof e.submissionId=="string")return{status:"pending-approval",submissionId:e.submissionId,threadId:typeof e.threadId=="string"?e.threadId:void 0};if(t===200&&typeof e.jobId=="string"&&typeof e.threadId=="string"&&typeof e.position=="number")return{...e,status:"queued",jobId:e.jobId,threadId:e.threadId,position:e.position};throw new Error("Unexpected participant submission response")}async send(e,t,r){if(r.sourceId!==this.projectId)throw new Error("Source world mismatch");let i=await this.request("/send",e,{"X-Popmelt-Draft-Revision":String(t),"X-Popmelt-Source-Revision":r.revision});return this.submission(i.data,i.status)}contribute(e,t){return this.rpc("contribute",{threadId:e,text:t})}async approve(e,t){let r=await this.request("/participants/approve",{id:e,revision:t});return this.submission(r.data,r.status)}};function Jr(e){return[...new Set([...e.annotations.map(t=>t.linkedSelector),...e.styleModifications.map(t=>t.selector),...e.textModifications.map(t=>t.selector)].filter(t=>!!t))].slice(0,200)}function Wr(e,t,r){let i=Math.min(r.width/t.width,r.height/t.height),n=t.width*i,a=t.height*i;return{left:r.left+(r.width-n)/2+e.left*n,top:r.top+(r.height-a)/2+e.top*a,width:e.width*n,height:e.height*a}}function Xe(e){return e instanceof ke?e.status>=500||e.status===408||e.status===429||e.status===409&&(e.code==="runtime_expired"||e.code==="draft_conflict"):e instanceof TypeError||typeof e=="object"&&e!==null&&"name"in e&&(e.name==="TimeoutError"||e.name==="AbortError")}function pt(e,t=8e3){return Math.min(1e3*2**Math.min(Math.max(0,e-1),10),t)*(.5+Math.random()*.5)}function Ur(e,t,r){let i={selectedId:r};try{let a=JSON.parse(e.getItem(t)??"null");a?.version===1&&typeof a.selectedId=="string"&&a.selectedId&&(i={selectedId:a.selectedId,...typeof a.threadId=="string"&&a.threadId?{threadId:a.threadId}:{}})}catch{}let n=a=>{if(!(a.selectedId===i.selectedId&&a.threadId===i.threadId)){i=a;try{e.setItem(t,JSON.stringify({version:1,...i}))}catch{}}};return{read:()=>i,select(a){a!==i.selectedId&&n({selectedId:a})},rememberThread(a,s){a===i.selectedId&&n({selectedId:a,...s?{threadId:s}:{}})},clear(){i={selectedId:r};try{e.removeItem(t)}catch{}}}}async function _r(e){let{projectId:t,runtimeStorage:r}=e,i={...e.credential},n={...e.observedSource};if(n.sourceId!==t)throw new Error("The loaded source does not match this participant session");let a=new Ct(e.bridgeUrl,t,i),s=`popmelt-runtime:${t}:${i.participantId}`,d=`popmelt-view:${t}:${i.participantId}`,o=Ur(r,`popmelt-navigation:${t}:${i.participantId}`,i.participantId),f=sr(r,`popmelt-suggestion-views:${t}:${i.participantId}`),l;try{let h=JSON.parse(r.getItem(d)??"null");typeof h?.isAnnotating=="boolean"&&typeof h?.activeColor=="string"&&(l={isAnnotating:h.isAnnotating,activeColor:h.activeColor})}catch{}let u=null;try{u=JSON.parse(r.getItem(s)??"null"),(u?.participantId!==i.participantId||typeof u?.runtimeId!="string"||typeof u?.token!="string")&&(u=null)}catch{}let w=a.mountRequestScope(n),I=`popmelt-recovery-reset:${new URL(e.bridgeUrl).origin}:${t}:${i.participantId}`,y=!1;try{y=r.getItem(I)==="1"}catch{}let b=y?null:e.recoveryStore!==void 0?e.recoveryStore:typeof indexedDB<"u"?Dr(e.bridgeUrl,t,i.participantId):null,g=null,c=null,p,x;try{g=await b?.read()??null;try{x=await a.read(),p=await a.connect(x.draft.history?crypto.randomUUID():u?.runtimeId??crypto.randomUUID(),x.draft.history?void 0:u?.token),r.setItem(s,JSON.stringify(p))}catch(h){if(h instanceof ke&&h.status===403&&(await a.snapshot().catch(()=>[])).find(J=>J.identity.id===i.participantId)?.revokedAt!==void 0)throw await b?.clear?.(),new ke(403,"Your access was removed by the host","access_removed");if(!g||!(h instanceof Error)||!Xe(h))throw h;x=g.reference,p={participantId:i.participantId,runtimeId:crypto.randomUUID(),token:"",expiresAt:0},c=h}x.draft.history&&b&&(g=await b.update({reference:x,basis:n,pending:[]}),g&&(x=g.reference))}catch(h){throw b?.close(),w(),h}let A;try{A=x.draft.history?$r({draft:x.draft,source:n,actor:p.runtimeId,view:l,pendingEvents:g?.pending,persist:b?async(h,J,T)=>{await b.update({reference:{...x,draft:h},basis:J,pending:T})}:void 0,saveView:h=>{try{r.setItem(d,JSON.stringify({isAnnotating:h.isAnnotating,activeColor:h.activeColor}))}catch{}},save:(h,J,T,Q)=>a.merge(p,h,J,Q)}):null}catch(h){throw b?.close(),w(),h}let P=A??Tr({draft:x.draft,source:n,save:(h,J,T)=>a.publish(p,h,J,T)}),C=!1,O=!1,M=null,j="connected",D=null,_=null,ie=0,H,ae=1e3,v=-1,te=!1,z=!1,F=new Set,R=()=>{for(let h of F)h()},$=()=>{C||H||D||j!=="reconnecting"||(H=setTimeout(()=>{H=void 0,oe()},ae),ae=Math.min(ae*2,3e4))},L=h=>{if(!C){if(M=h instanceof Error?h:new Error(String(h)),P.pause(M),M instanceof ke&&M.status===401){j="paused",z=!0,ie++,clearTimeout(H),H=void 0,R();return}j=Xe(M)?"reconnecting":"paused",j==="paused"&&(ie++,clearTimeout(H),H=void 0),$(),R()}},oe=(h=!1)=>{if(C)return Promise.reject(new Error("Participant runtime is closed"));if(_&&!h)return _;if(D)return D;let J=++ie,T=()=>!C&&J===ie;return clearTimeout(H),H=void 0,j="reconnecting",P.pause(M??new Error("Reconnecting to the participant session")),R(),D=(async()=>{if(await P.whenSettled(),!T())return;let Q=await a.connect(p.runtimeId,p.token);if(C)return;p=Q;try{r.setItem(s,JSON.stringify(p))}catch(Oe){if(!A?.getStatus().memoryOnly)throw Oe}if(!T())return;let Te=await a.read();T()&&(P.reconcile(Te.draft),await P.flush(),T()&&(M=null,j="connected",ae=1e3,R()))})().catch(Q=>{T()&&L(Q)}).finally(()=>{D=null,$()}),D},me=P.binding.subscribe(()=>{j==="connected"&&P.flush().catch(L)}),be=A?.subscribeStatus(()=>{let h=A.getStatus().localError;h&&h!==M?L(h):R()}),pe,he=setInterval(()=>{if(C||O||j!=="connected")return;O=!0;let h=p,J=P.binding.getSnapshot().activeColor;a.renew(p,J!==pe?J:void 0).then(T=>{!C&&p===h&&(p=T,pe=J,r.setItem(s,JSON.stringify(T)))}).catch(T=>{pe=void 0,!(p!==h||j!=="connected")&&(L(T),T instanceof ke&&T.status===409&&T.code==="runtime_expired"&&oe())}).finally(()=>{O=!1})},4e3),de=!1,se=0,Ee=async h=>{if(C||j!=="connected"||!A||!h)return;let J=ie;if(h.draftRevision>P.getStatus().revision){let T=await a.read();!C&&j==="connected"&&J===ie&&A.receive(T.draft)}},ce=setInterval(()=>{C||de||j!=="connected"||!A||se||(de=!0,a.snapshot().then(async h=>{let J=h.find(T=>T.identity.id===i.participantId);await Ee(J)}).catch(L).finally(()=>{de=!1}))},1e3),ge=0,G=!1,q=()=>{let h=P.binding.getSnapshot();return JSON.stringify({annotations:h.annotations.map(J=>({...J,status:void 0})),styles:h.styleModifications,text:h.textModifications,dom:h.domModifications,spacing:h.spacingTokenChanges})},le=null,Ce=null,Y=!1,$e=setInterval(()=>{if(C||!le||Y||j!=="connected")return;let h=le,J=p;Y=!0,a.previewWanted(p).then(async({wanted:T})=>{if(!T||le!==h||C||j!=="connected")return;await P.flush();let Q=P.binding.getSnapshot(),Te=P.getStatus().revision,Oe=await h.frame(Jr(Q));Oe&&le===h&&!C&&j==="connected"&&J.token===p.token&&Q===P.binding.getSnapshot()&&await a.publishPreview(p,Oe.image,{draftRevision:Te,targets:Oe.targets})}).catch(T=>{if(!(C||j!=="connected")){if(T instanceof Error&&Xe(T)){L(T);return}le===h&&(Ce=T instanceof Error?T.message:"Preview unavailable",h.stop(),le=null,R())}}).finally(()=>{Y=!1})},1e3);c?L(c):g?.pending.length&&P.flush().catch(L);let re;return{client:a,credential:i,navigation:o,state:P,readViewedSuggestions:f.read,markSuggestionViewed:f.mark,markSuggestionsViewed:f.markMany,captureVersion:q,reportAttention(h,J,T,Q){return C||j!=="connected"?Promise.resolve(!1):a.reportAttention(p,h,J,T,Q)},bindSubjects(h){return re=h,()=>{re===h&&(re=void 0)}},getSubjects:()=>re,getStatus:()=>({error:M,phase:j,pendingCount:ge,sending:G,sharing:!!le,previewError:Ce,accessRemoved:z}),reconnect:()=>oe(),retainExternalMembershipPolling(){se++;let h=!1;return()=>{h||(h=!0,se--)}},async retryLocalSave(){if(_)return _;await A?.retryLocalSave(),await oe()},clearLocalSpace(){return _||(C||!A?Promise.reject(new Error("Local space is unavailable")):(_=Promise.resolve().then(async()=>{let h=D;if(ie++,clearTimeout(H),H=void 0,j="paused",P.pause(new Error("Clearing local space")),R(),await h,C)throw new Error("Participant runtime is closed");try{r.setItem(I,"1")}catch{}await A.clearLocalSpace();let J;try{if(await Promise.race([b?.clear?b.clear():Promise.reject(new Error("Local storage cannot be cleared")),new Promise((T,Q)=>{J=setTimeout(()=>Q(new Error("Local clear timed out")),2e3)})]),C)throw new Error("Participant runtime is closed");if(await A.resumeLocalSaving())try{r.removeItem(I)}catch{}}catch{}finally{clearTimeout(J)}if(C)throw new Error("Participant runtime is closed");if(await oe(!0),j!=="connected")throw M??new Error("Session remains unavailable")}).finally(()=>{_=null}),_))},observeMembership(h){if(!(C||h.identity.id!==i.participantId)){if(h.revokedAt!==void 0&&!te){te=!0,L(new ke(403,"Your access was removed by the host")),le?.stop(),le=null,r.removeItem(s),r.removeItem(d),o.clear(),P.revoke().then(()=>b?.clear?.()).then(()=>{z=!0,R()}).catch(J=>{M=J instanceof Error?J:new Error("Could not clear local draft"),R()});return}if(!te){if(h.permission!=="blocked"&&!de&&(de=!0,Ee(h).catch(L).finally(()=>{de=!1})),h.permission==="blocked")v=h.permissionEpoch,M instanceof ke&&M.status===403||L(new ke(403,"Participant access is blocked"));else if(j==="paused"&&M instanceof ke&&M.status===403&&h.permissionEpoch>v){v=h.permissionEpoch;let J=()=>{!C&&j==="paused"&&v===h.permissionEpoch&&M instanceof ke&&M.status===403&&oe()};D?D.then(J):J()}}}},sharePreview(h){if(C){h?.stop();return}le?.stop(),le=h,Ce=null,h||a.publishPreview(p,null).catch(()=>{}),R()},subscribe:h=>(F.add(h),()=>{F.delete(h)}),async send(h,J){if(C||j!=="connected")throw M??new Error("Participant runtime is closed");if(G)throw new Error("A submission is already in progress");G=!0,R();try{if(P.setSource(n),await P.flush(),j!=="connected")throw M??new Error("Draft sync paused");if(q()!==J)throw new Error("Draft changed during capture; send again to include your latest changes");let T=await a.send(mr(h),P.getStatus().revision,n);return T.status==="pending-approval"?(ge++,R(),{pendingApproval:!0,submissionId:T.submissionId,threadId:T.threadId}):T}finally{G=!1,R()}},dispose(){C||(C=!0,re=void 0,j="closed",clearTimeout(H),clearInterval(he),clearInterval(ce),clearInterval($e),le?.stop(),le=null,a.publishPreview(p,null).catch(()=>{}),me(),be?.(),w(),P.dispose(),P.whenSettled().finally(()=>b?.close()),F.clear())}}}function qr(e,t){e.removeItem(`popmelt-participant:${t}`);let r=`popmelt-admission:${t}`,i;try{i=JSON.parse(e.getItem(r)??"null")}catch{e.removeItem(r);return}i&&typeof i=="object"&&e.setItem(r,JSON.stringify({name:i.name,colorIdentity:i.colorIdentity??i.receipt}))}var ft="popmelt-join",Tt=/^[A-Za-z0-9_-]{43}$/;function zr(e,t){let r=new URL(e);if(!["http:","https:"].includes(r.protocol)||!["localhost","127.0.0.1","[::1]"].includes(r.hostname)||!Tt.test(t))throw new Error("A local page and valid invitation are required");let i=jt(r.href).cleanUrl,n=new URL(i);return n.hash=`${n.hash.slice(1)}${n.hash?"&":""}${ft}=${t}`,n.href}function jt(e){let t=new URL(e),r=null,i=t.hash.slice(1).split("&").filter(n=>{if(!n.startsWith(`${ft}=`))return!0;let a=n.slice(ft.length+1);return Tt.test(a)&&(r=a),!1});return t.hash=i.join("&"),{token:r,cleanUrl:t.href}}function Fr(e){let t={phase:"starting"},r=0,i=!1,n=!1,a=0,s,d=new Set,o=`popmelt-participant:${e.projectId}`,f=new Ct(e.url,e.projectId),l=g=>{if(!n){t=g;for(let c of d)c()}},u=async(g={})=>{let c=await fetch("/__popmelt/host",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify(g),redirect:"error"});if(c.status===403)return null;if(!c.ok)throw new Error(`Host entry unavailable (${c.status}).`);let p=`popmelt-before-participants:${e.projectId}`;return localStorage.getItem(p)===null&&localStorage.setItem(p,JSON.stringify(Object.fromEntries(Object.values(ar(e.projectId)).map(x=>[x,localStorage.getItem(x)])))),await c.json()},w=g=>_r({bridgeUrl:e.url,projectId:e.projectId,credential:g,runtimeStorage:sessionStorage,observedSource:{sourceId:e.projectId,revision:e.revision}}),I=async(g,c=a)=>{if(n||c!==a)return;let p=await w(g);if(n||c!==a){p.dispose();return}try{localStorage.setItem(o,JSON.stringify(g))}catch(x){throw p.dispose(),x}s?.dispose(),s=p,l({phase:"connected",connection:p}),u({credential:g}).catch(()=>{})},y=()=>{a++,s?.dispose(),s=void 0,qr(localStorage,e.projectId),l({phase:"entry",invitation:null})},b=async()=>{let g=jt(location.href),c=new URL(g.cleanUrl),p=new URLSearchParams(c.hash.slice(1)),x=p.get("popmelt-host");p.delete("popmelt-host"),x&&(c.hash=p.toString()),c.href!==location.href&&history.replaceState(history.state,"",c);let A=null;if(x){if(A=await u({token:x}),!A)throw new Error("Host entry expired. Use the current private host link.")}else if(!g.token){try{A=JSON.parse(localStorage.getItem(o)??"null")}catch{}A??(A=await u())}if(!n){if(!A){l({phase:"entry",invitation:g.token??null});return}try{await I(A)}catch(P){if(n)return;if(P.code==="access_removed"){y();return}if(P.status!==401)throw P;let C=await u();C?await I(C):y()}}};return{client:f,getSnapshot:()=>t,subscribe(g){return d.add(g),()=>{d.delete(g)}},retain(){if(n)throw new Error("Participant lifecycle is disposed");r++,i||(i=!0,b().catch(c=>l({phase:"error",message:c.message})));let g=!1;return()=>{g||(g=!0,r--,queueMicrotask(()=>{r||n||(n=!0,a++,s?.dispose(),s=void 0,d.clear())}))}},removed:y,async join(g,c){if(t.phase!=="entry"||!t.invitation||n)throw new Error("No active invitation");if(!c)throw new Error("Peer identity is not ready");let p=a,x=await f.joinOrRequestAdmission(t.invitation,g,c);if(!(n||p!==a)){if("admission"in x){localStorage.setItem(`popmelt-admission:${e.projectId}`,JSON.stringify({name:x.admission.name,receipt:c,colorIdentity:c})),l({phase:"entry",invitation:null});return}await I(x.joined.credential,p)}},admit:g=>I(g)}}function Ke(){let e=crypto.getRandomValues(new Uint8Array(32));return{id:crypto.randomUUID(),token:Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}}var Ue=360,_e=120,Ye=180,Ot=260;function Vr({client:e,storage:t,storageKey:r,onAdmitted:i,theme:n="light",themePreference:a=n,onThemePreferenceChange:s,onJoin:d}){let o=K(null),f=K(!1);if(!f.current){f.current=!0;try{o.current=JSON.parse(t.getItem(r)??"null")}catch{}}let[l,u]=U(o.current?.name??""),[w,I]=U(d?void 0:o.current?.receipt),[y,b]=U(null),[g,c]=U(),[p,x]=U(),A=K(null),[P,C]=U(!!d),[O,M]=U(!1),[j,D]=U(0),[_,ie]=U(),[H,ae]=U("idle"),[v,te]=U(),[z,F]=U(),R=K(!1),[$,L]=U(""),oe=K(null),me=K(null),be=K(null),pe=K(null),he=K(!1),de=K(0),se=K(!1),Ee=yr(),ce=K(!1),ge=K(0),G=K(i);G.current=i;let q=K(!1),le=K(null),Ce=K(()=>{});le.current||(le.current=new Promise(k=>{Ce.current=k}));let Y=rt[n],$e=P&&!g;ee(()=>{let k=!1,Z,X,V=()=>{k||(k=!0,q.current=!0,Ce.current())};typeof requestAnimationFrame=="function"&&(Z=requestAnimationFrame(()=>{X=requestAnimationFrame(V)}));let Ie=window.setTimeout(V,64);return()=>{Z!==void 0&&cancelAnimationFrame(Z),X!==void 0&&cancelAnimationFrame(X),window.clearTimeout(Ie),V()}},[]),ee(()=>ur(document),[]),St(()=>{let k=!0,Z=()=>{if(!k||!be.current)return;let X=getComputedStyle(be.current),V=document.createElement("span");Object.assign(V.style,{position:"fixed",visibility:"hidden",pointerEvents:"none",whiteSpace:"nowrap",fontFamily:X.fontFamily,fontSize:X.fontSize,fontWeight:X.fontWeight,lineHeight:X.lineHeight}),document.body.append(V);let Ie=Number.parseFloat(X.paddingLeft)+Number.parseFloat(X.paddingRight);V.textContent="Ask for access";let Pe=Ie+12+3+V.getBoundingClientRect().width;V.textContent="Request pending";let ye=Ie+12+3+V.getBoundingClientRect().width;V.textContent="Request declined";let Me=Ie+12+3+V.getBoundingClientRect().width;if(V.remove(),Pe>15&&ye>15&&Me>15&&te({ask:Math.ceil(Pe),pending:Math.ceil(ye),declined:Math.ceil(Me)}),pe.current){let xe=getComputedStyle(pe.current),ve=document.createElement("span");Object.assign(ve.style,{position:"fixed",visibility:"hidden",pointerEvents:"none",whiteSpace:"nowrap",fontFamily:xe.fontFamily,fontSize:xe.fontSize,fontWeight:xe.fontWeight,lineHeight:xe.lineHeight}),ve.textContent="Sending...",document.body.append(ve);let we=Number.parseFloat(xe.paddingLeft)+Number.parseFloat(xe.paddingRight);F({idle:Math.ceil(we+14),sending:Math.ceil(we+ve.getBoundingClientRect().width)}),ve.remove()}};return Z(),document.fonts?.ready.then(Z),()=>{k=!1}},[n,P]),ee(()=>{if(!j)return;let k=setTimeout(()=>D(0),Ue);return()=>clearTimeout(k)},[j]),ee(()=>{if(!_)return;let k=setTimeout(()=>ie(void 0),Ue);return()=>clearTimeout(k)},[_]),ee(()=>{if(H!=="in")return;let k=setTimeout(()=>ae("idle"),Ye);return()=>clearTimeout(k)},[H]),ee(()=>{o.current&&delete o.current.color;try{let k=JSON.parse(t.getItem(r)??"null");k&&typeof k=="object"&&"color"in k&&(delete k.color,t.setItem(r,JSON.stringify(k)))}catch{}},[t,r]);let re=!!(w&&(!y||y.status==="pending"||y.status==="granted")),h=(k,Z)=>{o.current={...o.current,name:k,receipt:Z},t.setItem(r,JSON.stringify(o.current))};ee(()=>{if(y?.status==="cancelled"){o.current={...o.current,name:l,receipt:void 0};try{t.setItem(r,JSON.stringify(o.current))}catch{}I(void 0),b(null)}},[y,l,t,r]);let J=()=>{if(A.current)return A.current;let k=async()=>{let Z=JSON.parse(t.getItem(r)??"null"),X=Z?.colorIdentity??Z?.receipt??Ke();o.current={name:l,receipt:Z?.receipt,colorIdentity:X},t.setItem(r,JSON.stringify(o.current));let V;try{V=await e.reserveAdmissionColor(X)}catch(Ie){let Pe=Ie.status;if(Pe!==400&&Pe!==401)throw Ie;X=Ke(),o.current={...o.current,colorIdentity:X},t.setItem(r,JSON.stringify(o.current)),V=await e.reserveAdmissionColor(X)}return c(V.color),x(or(V)),X};return A.current=k().finally(()=>{A.current=null}),A.current},T=()=>{C(!P),P||L("")},Q=K(J);Q.current=J;let Te=!!d;ee(()=>{if(!P||g)return;let k=!1,Z,X=0,V=async()=>{try{await Q.current()}catch{if(k)return;Z=setTimeout(()=>{V()},pt(++X))}};return V(),()=>{k=!0,clearTimeout(Z)}},[P,g,t,r]),ee(()=>{if(!P)return;me.current?.focus();let k=Z=>{Z.composedPath().includes(oe.current)||C(!1)};return document.addEventListener("pointerdown",k),()=>document.removeEventListener("pointerdown",k)},[P]),ee(()=>{if(!w)return;let k=!0,Z=!1,X=!1,V,Ie,Pe=()=>{ge.current+=1,o.current={...o.current,name:l,receipt:void 0};try{t.setItem(r,JSON.stringify(o.current))}catch{}I(void 0),b(null),C(!1),L("")},ye=()=>{X=!0;let ve=Ke(),we=0,Le=async()=>{if(k)try{let De=await Q.current();o.current={...o.current,name:l,receipt:ve,colorIdentity:De},t.setItem(r,JSON.stringify(o.current));let qe=await e.requestAdmission(ve,l,De);if(!k)return;ge.current+=1,I(ve),b(qe),L("")}catch{if(!k)return;Ie=setTimeout(()=>{Le()},pt(++we))}};Le()},Me=async()=>{if(Z||X||se.current||ce.current)return;Z=!0;let ve=ge.current;try{let we=await e.admissionStatus(w);if(!k||ve!==ge.current)return;if(we.status==="declined"){if(q.current||await le.current,!k||ve!==ge.current)return;X=!0;let Le=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches,De=()=>{k&&(ae("rejected"),D(qe=>qe+1),V=setTimeout(()=>{if(k){if(Le){Pe(),ae("idle");return}ae("rejected-out"),V=setTimeout(()=>{k&&(Pe(),ae("in"))},_e)}},Ue))};Le?De():(ae("pending-out"),V=setTimeout(De,_e));return}if(we.status==="expired"){ye();return}if(b(we),X=we.status==="cancelled",L(""),we.credential){se.current=!0;try{await G.current(we.credential),X=!0}finally{se.current=!1}}}catch(we){if(!k||ve!==ge.current)return;we.status===401&&ye()}finally{Z=!1}};Me();let xe=setInterval(Me,1500);return()=>{k=!1,clearInterval(xe),clearTimeout(V),clearTimeout(Ie)}},[e,w,l,t,r]);let Oe=async()=>{if(!(!w||O||ce.current)){ce.current=!0,ge.current+=1,M(!0),L("");try{let k=await e.cancelAdmission(w);b(k),C(!1)}catch{D(k=>k+1)}finally{ce.current=!1,M(!1)}}},et=async k=>{if(!l.trim()||O||re||R.current)return;if(R.current=!0,M(!0),L(""),ie(void 0),d){try{let X=await J();h(l.trim()),await d(l.trim(),X)}catch(X){L(X instanceof Error?X.message:"Could not join. Please try again.")}finally{R.current=!1,M(!1)}return}try{o.current=JSON.parse(t.getItem(r)??"null")}catch{}let Z=!y&&o.current?.receipt?o.current.receipt:Ke();try{let X=await J();h(l,Z),o.current={...o.current,name:l,receipt:Z};let V=await e.requestAdmission(Z,l.trim(),X);I(Z),u(V.name),b(V),C(!1)}catch{o.current={...o.current,name:l,receipt:Z},ie({target:k,pulse:++de.current})}finally{R.current=!1,M(!1)}};return B("div",{ref:oe,"data-devtools":"participant-admission","data-popmelt-font":"sans","data-popmelt-theme":n,style:{display:"contents"},onKeyDown:k=>{k.key==="Escape"&&(C(!1),k.stopPropagation())},children:[S("style",{children:`
|
|
2
|
+
import{a as Jt}from"./chunk-7YCLSSQA.mjs";import{Pb as Wt,vb as Ut,Yb as gt,gb as _t,nb as qt,ub as tt,jb as zt,mb as Ft,b as Vt,kb as Ht,ca as Xt,ib as Kt,lb as Yt,Ob as Bt,Kb as Zt,pb as Gt,Hb as Qt,Jb as er,Lb as tr,Nb as rr,Mb as yt,v as nr,fb as vt,hb as ir,ab as ar,tb as or,ob as sr,fc as lr,f as dr,d as wt}from"./chunk-TFPKDKDO.mjs";import{ya as cr,wa as rt,_ as ze,ba as ur,u as pr,Fa as fr,Ja as hr,H as mr}from"./chunk-7YIQQYRU.mjs";import{d as je}from"./chunk-TSY2K45H.mjs";import{s as gr,n as bt}from"./chunk-D7HY2EDH.mjs";import{useState as U,useSyncExternalStore as It,useEffect as ee,useRef as K,useCallback as Je,useMemo as nt,useId as yr,useLayoutEffect as St}from"react";import{Link2 as vr,Ban as wr,Clock as br,X as Ir,Hand as Sr,SendHorizontal as kr,LoaderCircle as Er,RotateCcw as Pr,Check as xr,Copy as Ar}from"lucide-react";import{jsxs as B,jsx as S,Fragment as We}from"react/jsx-runtime";var Cr=class extends Error{constructor(){super("The saved draft changed in another runtime. Your local changes are preserved.")}},it=(e,t)=>e.revision===t.revision&&JSON.stringify(e.source)===JSON.stringify(t.source)&&JSON.stringify(e.state)===JSON.stringify(t.state);function Tr(e){let t=structuredClone(e.draft.state??je),r=structuredClone(e.source),i=e.draft.revision,n=0,a=0,s=null,d=!1,o=structuredClone(e.draft),f=null,l=null,u=!1,w=new Set,I=new Set,y=()=>{for(let c of[...I])c()},b={getSnapshot:()=>t,subscribe:c=>(w.add(c),()=>{w.delete(c)}),dispatch:c=>{if(u)throw new Error("Participant runtime is disposed");let p=wt(t,c);if(p!==t){t=p,n++;for(let x of[...w])x();y()}}},g=()=>u?Promise.reject(new Error("Participant runtime is disposed")):l||(s||d?Promise.reject(s??new Error("Draft sync paused")):n===a?Promise.resolve():(l=Promise.resolve().then(async()=>{for(;!u&&!d&&n!==a;){let c=n,p=structuredClone(r),x=structuredClone(t);f={generation:c,draft:{revision:i+1,source:p,state:x}};let A=await e.save(i,p,x);if(!it(A,f.draft))throw new Error("Unexpected saved draft revision; reconnect before writing");i=A.revision,a=c,o=structuredClone(A),f=null}}).catch(c=>{throw s=c instanceof Error?c:new Error(String(c)),s}).finally(()=>{l=null,y()}),l));return{binding:b,flush:g,getStatus:()=>({revision:i,unsaved:n!==a,error:s,disposed:u}),subscribeStatus(c){return I.add(c),()=>{I.delete(c)}},pause(c){d=!0,s=c,y()},async whenSettled(){await l?.catch(()=>{})},reconcile(c){if(u)throw new Error("Participant runtime is disposed");if(l)throw new Error("Wait for the pending save before reconciling");if(!it(c,o)){if(!f||!it(c,f.draft))throw new Cr;i=c.revision,a=f.generation,o=structuredClone(c)}f=null,s=null,d=!1,y()},retry(){return s=null,d=!1,g()},setSource(c){if(u)throw new Error("Participant runtime is disposed");if(c.sourceId!==r.sourceId)throw new Error("Changing source worlds requires a new participant runtime");c.revision!==r.revision&&(r=structuredClone(c),n++,y())},async revoke(){u=!0,d=!0,await l?.catch(()=>{}),t=structuredClone(je),f=null,o={revision:i,source:null,state:null};for(let c of[...w])c();y()},dispose(){u=!0,w.clear(),I.clear()}}}var kt=8192,at=8*1024*1024,jr=256,Fe=100,Ae=(...e)=>JSON.stringify(e),Ve=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Re=e=>structuredClone(e),Or=class extends Error{constructor(){super("This edit predates retained synchronization history"),this.name="PlaneHistoryExpiredError"}},Et=(e,t)=>Pt(e.stamp,t.stamp)||(e.id<t.id?-1:e.id>t.id?1:0);function He(e,t){let r=new Map([...e.checkpoint?.receipts??[],...e.events].map(a=>[a.id,a])),i=[],n=[];for(let a of t){let s=r.get(a.id);if(s){if(!Ve(s,a))throw new Error("Plane event identity was reused");continue}e.checkpoint&&Et(a,e.checkpoint.through)<=0?n.push(a):i.push(a)}return{pending:i,superseded:n}}function Mr(e,t){let r=He(e,t);if(r.superseded.length)throw new Or;return r.pending}function Pt(e,t){return e.time-t.time||e.counter-t.counter||(e.actor<t.actor?-1:e.actor>t.actor?1:0)}function Nr(e,t,r,i){let n=r.reduce((s,d)=>!s||Pt(d.stamp,s)>0?d.stamp:s,t),a=Math.max(Math.floor(i),n?.time??0);return{actor:e,time:a,counter:a===n?.time?n.counter+1:0}}function ot(e){let t=new Map;for(let r of e.annotations){t.set(Ae("annotation",r.id),!0);for(let[i,n]of Object.entries(r))i!=="id"&&n!==void 0&&t.set(Ae("annotation",r.id,i),n)}for(let r of e.styleModifications){let i=Ae(r.pathname??"/",r.selector),{changes:n,...a}=r;t.set(Ae("styleMeta",i),a);for(let s of n)t.set(Ae("style",i,s.property),s)}for(let r of e.textModifications)t.set(Ae("text",Ae(r.pathname??"/",r.selector,JSON.stringify(r.textNodePath))),r);for(let r of e.domModifications)t.set(Ae("dom",r.id),r);for(let r of e.spacingTokenChanges)t.set(Ae("spacing",r.tokenPath),r);for(let r of e.spacingTokenMods)t.set(Ae("spacingMod",r.tokenPath),r);return t}function st(e,t){let r=ot(e),i=ot(t);return[...new Set([...r.keys(),...i.keys()])].filter(n=>!(JSON.parse(n)[0]==="styleMeta"&&!i.has(n))).filter(n=>!Ve(r.get(n),i.get(n))).map(n=>({key:n,...i.has(n)?{value:Re(i.get(n))}:{}}))}function xt(e,t){let r={...t,annotations:[],styleModifications:[],textModifications:[],domModifications:[],spacingTokenChanges:[],spacingTokenMods:[]},i=new Map;for(let[a,s]of e){let[d,o,f]=JSON.parse(a);d==="annotation"&&!f&&s===!0&&i.set(o,{id:o})}let n=new Map;for(let[a,s]of e){let[d,o,f]=JSON.parse(a);if(d==="annotation"&&f&&i.has(o)&&Object.defineProperty(i.get(o),f,{value:s,enumerable:!0,configurable:!0,writable:!0}),d==="style"){let l=n.get(o),u=e.get(Ae("styleMeta",o));if(!u)continue;l||(l={...u,changes:[]},n.set(o,l)),l.changes.push(s)}d==="text"&&r.textModifications.push(s),d==="dom"&&r.domModifications.push(s),d==="spacing"&&r.spacingTokenChanges.push(s),d==="spacingMod"&&r.spacingTokenMods.push(s)}return r.annotations=[...i.values()],r.styleModifications=[...n.values()],r.selectedAnnotationIds=t.selectedAnnotationIds.filter(a=>i.has(a)),r.lastSelectedId=r.selectedAnnotationIds.includes(t.lastSelectedId??"")?t.lastSelectedId:null,r}var At=e=>({annotations:e.annotations,styleModifications:e.styleModifications,textModifications:e.textModifications,domModifications:e.domModifications,spacingTokenChanges:e.spacingTokenChanges,spacingTokenMods:e.spacingTokenMods});function lt(e=je){let t=[...e.undoStack.slice(-Fe),At(e)],r={...Re(e),...Re(t[0]),undoStack:[],redoStack:[]},i=[];for(let s=1;s<t.length;s++){let d=`migration:${s}`;i.push({id:d,stamp:{time:0,counter:s,actor:"migration"},kind:"edit",group:d,changes:st({...r,...t[s-1]},{...r,...t[s]})})}let n=e,a=[];for(let s of[...e.redoStack].reverse().slice(0,Fe)){let d=`migration:${i.length+1}`,o={...r,...s};i.push({id:d,stamp:{time:0,counter:i.length+1,actor:"migration"},kind:"edit",group:d,changes:st(n,o)}),a.push(d),n=o}for(let s of a.reverse()){let d=`migration:${i.length+1}`;i.push({id:d,stamp:{time:0,counter:i.length+1,actor:"migration"},kind:"undo",target:s})}return{version:1,base:r,events:i}}function dt(e){if(!Array.isArray(e)||e.length>kt||JSON.stringify(e).length>at)throw new Error("Plane history exceeds the local session limit");for(let t of e){let r=n=>typeof n=="string"&&n.length>0&&n.length<=256;if(!t||!r(t.id)||!t.stamp||!r(t.stamp.actor)||!Number.isSafeInteger(t.stamp.time)||t.stamp.time<0||!Number.isSafeInteger(t.stamp.counter)||t.stamp.counter<0||!["edit","undo","redo"].includes(t.kind))throw new Error("Invalid plane event");if(t.kind!=="edit"){if(!r(t.target))throw new Error("Invalid history target");continue}if(t.group!==void 0&&!r(t.group)||t.reset!==void 0&&typeof t.reset!="boolean"||!Array.isArray(t.changes)||t.changes.length>1e4)throw new Error("Invalid plane edit");let i=new Set;for(let n of t.changes){if(!n||typeof n.key!="string"||n.key.length>8192)throw new Error("Invalid property key");let a=JSON.parse(n.key);if(!Array.isArray(a)||a.length<2||a.length>3||a.some(s=>typeof s!="string"||!s.length)||!["annotation","style","styleMeta","text","dom","spacing","spacingMod"].includes(a[0])||a[0]==="style"&&a.length!==3||!["style","annotation"].includes(a[0])&&a.length!==2||a[0]==="annotation"&&a.length===2&&n.value!==void 0&&n.value!==!0||i.has(n.key))throw new Error("Invalid property key");i.add(n.key)}}return Re(e)}function ct(e,t){let r=new Map(e.events.map(i=>[i.id,i]));for(let i of Mr(e,t)){let n=r.get(i.id);if(n&&!Ve(n,i))throw new Error("Plane event identity was reused");r.set(i.id,i)}if(r.size>kt)throw new Error("Plane history exceeds the local session limit");return{...e,events:[...r.values()].sort(Et)}}function Rr(e){if(e.version!==1&&e.version!==2)throw new Error("Unsupported plane history version");if(e.version===2&&!e.checkpoint)throw new Error("Missing plane history checkpoint");let t=e.checkpoint,r=t?new Map(Re(t.cells)):ot(e.base),i=new Map(t?.writers??[]),n=Re(t?.undo??[]),a=Re(t?.redo??[]),s=(d,o)=>{let f=[],l=[...d].sort((u,w)=>JSON.parse(u.key).length-JSON.parse(w.key).length);for(let u of l){let[w,I,y]=JSON.parse(u.key);if(w==="styleMeta"&&u.value===void 0)continue;let b=i.get(u.key)??"base";if(u.guard!==void 0&&b!==u.guard||w==="annotation"&&y&&!r.has(Ae(w,I)))continue;let g=r.get(u.key);u.value===void 0?r.delete(u.key):r.set(u.key,u.value);let c=u.restoreWriter??o;if(i.set(u.key,c),f.push({key:u.key,before:g,after:u.value,beforeWriter:b,afterWriter:c}),w==="annotation"&&!y&&u.value===void 0)for(let p of[...r.keys()]){let[x,A]=JSON.parse(p);x===w&&A===I&&(f.push({key:p,before:r.get(p),after:void 0,beforeWriter:i.get(p)??"base",afterWriter:c}),r.delete(p),i.set(p,c))}}return f};for(let d of e.events)if(d.kind==="edit"){let o=s(d.changes,d.group??d.id);if(d.reset&&(n.length=0,a.length=0),!d.group||!o.length)continue;let f=n.find(l=>l.id===d.group);if(f)for(let l of o){let u=f.changes.find(w=>w.key===l.key);u?(u.after=l.after,u.afterWriter=l.afterWriter):f.changes.push(l)}else n.push({id:d.group,writer:d.group,changes:o});a.length=0,n.length>Fe&&n.shift()}else{let o=d.kind==="undo"?n:a,f=d.kind==="undo"?a:n,l=o.findIndex(I=>I.id===d.target);if(l<0)continue;let u=o.splice(l,1)[0],w=s(u.changes.map(I=>({key:I.key,value:I.before,guard:I.afterWriter,restoreWriter:I.beforeWriter})),d.id);w.length&&f.push({id:d.id,writer:d.id,changes:w}),f.length>Fe&&f.shift()}return{cells:r,writers:i,undo:n,redo:a}}function ut(e,t=e.base,r=!0){let{cells:i,writers:n,undo:a,redo:s}=Rr(e),d=xt(i,t);d.styleModifications=d.styleModifications.filter(I=>!e.hostStyleDeletions?.some(y=>dr(I,y)));let o=new Set(Object.keys(e.hostDeletions??{}));d.annotations=d.annotations.filter(I=>!o.has(I.id)),d.selectedAnnotationIds=d.selectedAnnotationIds.filter(I=>!o.has(I));let f=I=>{let y=new Map(i);for(let b of I.changes)(n.get(b.key)??"base")===b.afterWriter&&(b.before===void 0?y.delete(b.key):y.set(b.key,b.before));return At(xt(y,t))},l=I=>I.filter(y=>y.changes.some(b=>JSON.parse(b.key)[0]!=="styleMeta"&&(n.get(b.key)??"base")===b.afterWriter&&!Ve(b.before,i.get(b.key)))),u=l(a),w=l(s);return d.undoStack=r?u.map(f):[],d.redoStack=r?w.map(f):[],{state:Re(d),undo:u.map(I=>I.id),redo:w.map(I=>I.id)}}function $r(e){let t=structuredClone(e.draft.history??lt(e.draft.state??je)),r=He(t,e.pendingEvents??[]);t=ct(t,r.pending);let i=ut(t,{...structuredClone(e.draft.state??je),...e.view}),n=i.state,a=structuredClone(e.source),s=e.draft.revision,d=r.pending,o=structuredClone(e.draft),f=null,l=!!e.persist,u=0,w=0,I=Promise.resolve(),y=!1,b,g,c=null,p=null,x=!1,A=!1,P=new Set,C=new Set,O=()=>{for(let v of[...P])v()},M=()=>{for(let v of[...C])v()},j=()=>{i=ut(t,n),n=i.state},D=()=>{if(!e.persist||!l)return Promise.resolve();let v=structuredClone(o),te=structuredClone(a),z=structuredClone(d),F=u;return w++,I=I.then(()=>e.persist(v,te,z)).then(()=>{F===u&&(f=null)}).catch(R=>{F===u&&(f=R instanceof Error?R:new Error(String(R)))}).finally(()=>{F===u&&(w--,M())}),I},_=async()=>{do await I;while(w>0);if(f)throw f},ie=v=>{if(v.revision<s)return;if(v.source&&v.source.sourceId!==a.sourceId)throw new Error("Draft source world mismatch");if(!v.history)throw new Error("Shared history is unavailable; reconnect to an updated bridge");let te=He(v.history,d),z=ct(structuredClone(v.history),te.pending),F=JSON.stringify(z.hostStyleDeletions)!==JSON.stringify(t.hostStyleDeletions)||JSON.stringify(z.hostDeletions)!==JSON.stringify(t.hostDeletions)||z.checkpoint?.through.id!==t.checkpoint?.through.id||z.events.length!==t.events.length||z.events.some((R,$)=>R.id!==t.events[$]?.id);d=te.pending,te.superseded.length&&(g=void 0),t=z,s=v.revision,o=structuredClone(v),F&&j(),D()},H={getSnapshot:()=>n,subscribe(v){return P.add(v),()=>{P.delete(v)}},dispatch(v){if(A)throw new Error("Participant runtime is disposed");let te=n,z,F=()=>(b=Nr(e.actor,b,t.events,(e.now??Date.now)()),b),R=()=>crypto.randomUUID();if(v.type==="UNDO"||v.type==="REDO"){let $=(v.type==="UNDO"?i.undo:i.redo).at(-1);if(!$)return;z={id:R(),stamp:F(),kind:v.type==="UNDO"?"undo":"redo",target:$},g=void 0}else{let $=wt(n,v);if($===n)return;let L=v.type==="UPDATE_LINKED_POSITIONS"?[]:st(n,$),oe=$.undoStack.length>n.undoStack.length,me=["MODIFY_STYLE","MOVE_ANNOTATION","RESIZE_ANNOTATION","UPDATE_TEXT_SIZE","UPDATE_ANNOTATION_COLOR"].includes(v.type);if(L.length){let be=R(),pe=oe||me?!oe&&g&&g===i.undo.at(-1)?g:be:void 0;z={id:be,stamp:F(),kind:"edit",changes:L,...pe?{group:pe}:{},...v.type==="CLEAR"?{reset:!0}:{}},g=pe}n=$}if(z){try{t=ct(t,[z])}catch($){n=te,p=$ instanceof Error?$:new Error(String($)),x=!0,g=void 0,O(),M();return}d.push(z),j(),D()}O(),M(),e.saveView?.(n)}},ae=()=>A?Promise.reject(new Error("Participant runtime is disposed")):c||(p||x?Promise.reject(p??new Error("Draft sync paused")):!d.length&&!y&&!w&&!f?Promise.resolve():(c=Promise.resolve().then(async()=>{for(f&&await D(),await _();!A&&!x&&(d.length||y);){await _();let v=structuredClone(d.slice(0,jr)),te=structuredClone(a),z=await e.save(s,te,n,v);if(A)return;ie(z),await _(),a.revision===te.revision&&(y=!1),O()}}).catch(v=>{throw p=v instanceof Error?v:new Error(String(v)),p}).finally(()=>{c=null,M()}),c));return{binding:H,flush:ae,getStatus:()=>({revision:s,unsaved:d.length>0||y,error:p,localError:f,memoryOnly:!l,savingLocally:w>0,disposed:A}),subscribeStatus(v){return C.add(v),()=>{C.delete(v)}},pause(v){x=!0,p=v,M()},async whenSettled(){await c?.catch(()=>{}),await _().catch(()=>{})},whenDurable:_,async retryLocalSave(){if(A)throw new Error("Participant runtime is disposed");await D(),await _()},async clearLocalSpace(){if(x=!0,await c?.catch(()=>{}),await _().catch(()=>{}),A)throw new Error("Participant runtime is disposed");l=!1,d=[],y=!1,g=void 0,t=structuredClone(o.history??lt(o.state??je)),i=ut(t,{...structuredClone(je),activeColor:n.activeColor,isAnnotating:n.isAnnotating}),n=i.state,s=o.revision,f=null,p=null,O(),M()},async resumeLocalSaving(){if(!e.persist||A)return!1;l=!0;let v;try{return await Promise.race([D().then(_),new Promise((te,z)=>{v=setTimeout(()=>z(new Error("Local saving timed out")),2e3)})]),!A}catch{return u++,l=!1,w=0,I=Promise.resolve(),f=null,M(),!1}finally{clearTimeout(v)}},reconcile(v){if(A)throw new Error("Participant runtime is disposed");if(c)throw new Error("Wait for the pending save before reconciling");ie(v),p=null,x=!1,O(),M()},receive(v){A||x||c||v.revision<=s||(ie(v),O(),M())},retry(){return x=!1,p=null,ae()},setSource(v){if(v.sourceId!==a.sourceId)throw new Error("Changing source worlds requires a new participant runtime");v.revision===a.revision&&o.source?.revision===v.revision||(a=structuredClone(v),y=!0,M())},async revoke(){A=!0,x=!0,await c?.catch(()=>{}),await _().catch(()=>{}),d=[],t=lt(je),n=structuredClone(je),o={revision:s,source:null,state:null},O(),M()},dispose(){A=!0,P.clear(),C.clear()}}}function Lr(e,t){if(!t.reference.draft.history||t.reference.draft.source&&t.basis.sourceId!==t.reference.draft.source.sourceId)throw new Error("Offline recovery requires a matching shared-history source");if(e&&(e.version!==1||e.reference.author.id!==t.reference.author.id||e.reference.planeId!==t.reference.planeId||e.basis.sourceId!==t.basis.sourceId))throw new Error("Offline recovery belongs to a different plane");let r=e&&e.reference.draft.revision>t.reference.draft.revision?e.reference:t.reference,i=new Map;for(let o of[...dt(e?.pending??[]),...dt(t.pending)]){let f=i.get(o.id);if(f&&JSON.stringify(f)!==JSON.stringify(o))throw new Error("Offline operation identity was reused");i.set(o.id,o)}let n=He(r.draft.history,[...i.values()]),a=new Set(n.pending.map(o=>o.id)),s=e?.pending.some(o=>a.has(o.id)),d={version:1,reference:r,basis:s?e.basis:t.basis,pending:n.pending,...e?.superseded?{superseded:e.superseded}:{}};if(n.superseded.length){let o=n.superseded.slice(-128);for(;o.length&&new TextEncoder().encode(JSON.stringify(o)).length>256*1024;)o.shift();d.superseded={revision:r.draft.revision,events:o,omitted:n.superseded.length-o.length}}if(dt(d.pending),d.superseded&&new TextEncoder().encode(JSON.stringify(d)).length>at&&delete d.superseded,new TextEncoder().encode(JSON.stringify(d)).length>at)throw new Error("Offline recovery storage limit reached; pending work is preserved");return structuredClone(d)}function Dr(e,t,r,i=indexedDB){let n=JSON.stringify([new URL(e).origin,t,r]),a=!1,s=new Promise((o,f)=>{let l=i.open("popmelt-plane-recovery",1);l.onupgradeneeded=()=>l.result.createObjectStore("planes"),l.onerror=()=>f(new Error("Could not open local draft recovery",{cause:l.error})),l.onblocked=()=>f(new Error("Local draft recovery is blocked by another browser view")),l.onsuccess=()=>{if(a){l.result.close(),f(new Error("Local draft recovery is closed"));return}l.result.onversionchange=()=>l.result.close(),o(l.result)}});s.catch(()=>{});let d=async o=>{let f=await s;if(a)throw new Error("Local draft recovery is closed");return new Promise((l,u)=>{let w=f.transaction("planes",o?"readwrite":"readonly"),I=w.objectStore("planes"),y=null,b,g=I.get(n);g.onsuccess=()=>{try{if(y=g.result??null,y&&(y.version!==1||y.reference.author.id!==r||y.basis.sourceId!==t))throw new Error("Invalid local recovery record; it has been preserved");o&&(y=Lr(y,o),I.put(y,n))}catch(c){b=c,w.abort()}},w.oncomplete=()=>l(y),w.onabort=()=>u(b??new Error("Could not save local draft recovery",{cause:w.error})),w.onerror=()=>{}})};return{read:()=>d(),update:o=>d(structuredClone(o)),async clear(){let o=await s;if(a)throw new Error("Local draft recovery is closed");await new Promise((f,l)=>{let u=o.transaction("planes","readwrite");u.objectStore("planes").delete(n),u.oncomplete=()=>f(),u.onabort=()=>l(u.error??new Error("Could not clear local draft recovery"))})},close(){a=!0,s.then(o=>o.close()).catch(()=>{})}}}var ke=class extends Error{constructor(e,t,r){super(t),this.status=e,this.code=r}},Ct=class{constructor(e,t,r,i=(...n)=>fetch(...n)){this.projectId=t,this.transport=i;let n=new URL(e);if(n.protocol!=="http:"||!["localhost","127.0.0.1","[::1]"].includes(n.hostname)||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw new Error("Participant transport requires a local bridge origin");if(!t)throw new Error("Project identity required");this.base=n.origin,this.credential=r?{...r}:void 0}moderateStyles(e,t,r=!1){return this.rpc("moderate-styles",{participantId:e,styleModifications:t,restore:r})}moderateAnnotations(e,t,r=!1,i){return this.rpc("moderate-annotations",{participantId:e,annotationIds:t,restore:r,threadId:i})}async request(e,t,r={},i){let n=t instanceof FormData,a=await this.transport(this.base+e,{method:"POST",redirect:"error",credentials:"omit",signal:i??AbortSignal.timeout(3e4),headers:{...n?{}:{"Content-Type":"application/json"},"X-Popmelt-Project-Id":this.projectId,...this.credential?{"X-Popmelt-Participant-Id":this.credential.participantId,"X-Popmelt-Participant-Token":this.credential.token}:{},...r},body:n?t:JSON.stringify(t)}),s=await a.json().catch(()=>null);if(!a.ok)throw new ke(a.status,typeof s?.error=="string"?s.error:"Participant request failed",typeof s?.code=="string"?s.code:void 0);if(s===null)throw new Error("Invalid participant response");return{data:s,status:a.status}}async rpc(e,t={},r){return(await this.request("/participants/"+e,t,{},r)).data}mountRequestScope(e){if(!this.credential)throw new Error("Join before mounting a canvas");return pr(this.base,{"X-Popmelt-Project-Id":this.projectId,"X-Popmelt-Participant-Id":this.credential.participantId,"X-Popmelt-Participant-Token":this.credential.token,...e?{"X-Popmelt-Source-Revision":e.revision}:{}})}source(){return this.rpc("source")}snapshot(){return this.rpc("snapshot")}setHostModelSelection(e){return this.rpc("model-selection",{selection:e})}reserveAdmissionColor(e){return this.rpc("access-color",{receipt:e})}requestAdmission(e,t,r){return this.rpc("access-request",{receipt:e,name:t,colorIdentity:r})}admissionStatus(e){return this.rpc("access-status",{receipt:e})}cancelAdmission(e){return this.rpc("access-cancel",{receipt:e})}admissions(){return this.rpc("access-list")}decideAdmission(e,t){return this.rpc("access-decide",{id:e,decision:t})}attention(){return this.rpc("attention-read")}async reportAttention(e,t,r,i,n){return(await this.request("/participants/attention",{runtime:e,phase:t,operationId:r,location:i},{},n??AbortSignal.timeout(1500))).data}invite(){return this.rpc("invite")}revokeInvite(e){return this.rpc("revoke-invite",{invitation:e})}join(e,t,r){return this.rpc("join",{invitation:e,name:t,...r?{colorIdentity:r}:{}})}joinOrRequestAdmission(e,t,r){return this.rpc("join-or-request",{invitation:e,name:t,colorIdentity:r})}read(e,t){return this.rpc("read",{participantId:e,historyVersion:2},t)}connect(e,t){return this.rpc("connect",{runtimeId:e,previousToken:t})}renew(e,t){return this.rpc("renew",{runtime:e,activeColor:t})}disconnect(e){return this.rpc("disconnect",{runtime:e})}publish(e,t,r,i){return r.sourceId!==this.projectId?Promise.reject(new Error("Source world mismatch")):this.rpc("publish",{runtime:e,expectedRevision:t,sourceRevision:r.revision,state:i})}merge(e,t,r,i){return r.sourceId!==this.projectId?Promise.reject(new Error("Source world mismatch")):this.rpc("merge",{runtime:e,expectedRevision:t,sourceRevision:r.revision,events:i,historyVersion:2})}rename(e){return this.rpc("rename",{name:e})}setPermission(e,t){return this.rpc("permission",{participantId:e,permission:t})}revokeAccess(e){return this.rpc("revoke-access",{participantId:e})}pending(){return this.rpc("pending")}preview(e){return this.rpc("preview-read",{participantId:e})}previewWanted(e){return this.rpc("preview-demand",{runtime:e})}publishPreview(e,t,r){return this.rpc("preview-publish",{runtime:e,image:t,geometry:r})}review(e){return this.rpc("review",{id:e})}discard(e){return this.rpc("discard",{id:e})}submission(e,t){if(t===202&&e.pendingApproval===!0&&typeof e.submissionId=="string")return{status:"pending-approval",submissionId:e.submissionId,threadId:typeof e.threadId=="string"?e.threadId:void 0};if(t===200&&typeof e.jobId=="string"&&typeof e.threadId=="string"&&typeof e.position=="number")return{...e,status:"queued",jobId:e.jobId,threadId:e.threadId,position:e.position};throw new Error("Unexpected participant submission response")}async send(e,t,r){if(r.sourceId!==this.projectId)throw new Error("Source world mismatch");let i=await this.request("/send",e,{"X-Popmelt-Draft-Revision":String(t),"X-Popmelt-Source-Revision":r.revision});return this.submission(i.data,i.status)}contribute(e,t){return this.rpc("contribute",{threadId:e,text:t})}async approve(e,t){let r=await this.request("/participants/approve",{id:e,revision:t});return this.submission(r.data,r.status)}};function Jr(e){return[...new Set([...e.annotations.map(t=>t.linkedSelector),...e.styleModifications.map(t=>t.selector),...e.textModifications.map(t=>t.selector)].filter(t=>!!t))].slice(0,200)}function Wr(e,t,r){let i=Math.min(r.width/t.width,r.height/t.height),n=t.width*i,a=t.height*i;return{left:r.left+(r.width-n)/2+e.left*n,top:r.top+(r.height-a)/2+e.top*a,width:e.width*n,height:e.height*a}}function Xe(e){return e instanceof ke?e.status>=500||e.status===408||e.status===429||e.status===409&&(e.code==="runtime_expired"||e.code==="draft_conflict"):e instanceof TypeError||typeof e=="object"&&e!==null&&"name"in e&&(e.name==="TimeoutError"||e.name==="AbortError")}function pt(e,t=8e3){return Math.min(1e3*2**Math.min(Math.max(0,e-1),10),t)*(.5+Math.random()*.5)}function Ur(e,t,r){let i={selectedId:r};try{let a=JSON.parse(e.getItem(t)??"null");a?.version===1&&typeof a.selectedId=="string"&&a.selectedId&&(i={selectedId:a.selectedId,...typeof a.threadId=="string"&&a.threadId?{threadId:a.threadId}:{}})}catch{}let n=a=>{if(!(a.selectedId===i.selectedId&&a.threadId===i.threadId)){i=a;try{e.setItem(t,JSON.stringify({version:1,...i}))}catch{}}};return{read:()=>i,select(a){a!==i.selectedId&&n({selectedId:a})},rememberThread(a,s){a===i.selectedId&&n({selectedId:a,...s?{threadId:s}:{}})},clear(){i={selectedId:r};try{e.removeItem(t)}catch{}}}}async function _r(e){let{projectId:t,runtimeStorage:r}=e,i={...e.credential},n={...e.observedSource};if(n.sourceId!==t)throw new Error("The loaded source does not match this participant session");let a=new Ct(e.bridgeUrl,t,i),s=`popmelt-runtime:${t}:${i.participantId}`,d=`popmelt-view:${t}:${i.participantId}`,o=Ur(r,`popmelt-navigation:${t}:${i.participantId}`,i.participantId),f=sr(r,`popmelt-suggestion-views:${t}:${i.participantId}`),l;try{let h=JSON.parse(r.getItem(d)??"null");typeof h?.isAnnotating=="boolean"&&typeof h?.activeColor=="string"&&(l={isAnnotating:h.isAnnotating,activeColor:h.activeColor})}catch{}let u=null;try{u=JSON.parse(r.getItem(s)??"null"),(u?.participantId!==i.participantId||typeof u?.runtimeId!="string"||typeof u?.token!="string")&&(u=null)}catch{}let w=a.mountRequestScope(n),I=`popmelt-recovery-reset:${new URL(e.bridgeUrl).origin}:${t}:${i.participantId}`,y=!1;try{y=r.getItem(I)==="1"}catch{}let b=y?null:e.recoveryStore!==void 0?e.recoveryStore:typeof indexedDB<"u"?Dr(e.bridgeUrl,t,i.participantId):null,g=null,c=null,p,x;try{g=await b?.read()??null;try{x=await a.read(),p=await a.connect(x.draft.history?crypto.randomUUID():u?.runtimeId??crypto.randomUUID(),x.draft.history?void 0:u?.token),r.setItem(s,JSON.stringify(p))}catch(h){if(h instanceof ke&&h.status===403&&(await a.snapshot().catch(()=>[])).find(J=>J.identity.id===i.participantId)?.revokedAt!==void 0)throw await b?.clear?.(),new ke(403,"Your access was removed by the host","access_removed");if(!g||!(h instanceof Error)||!Xe(h))throw h;x=g.reference,p={participantId:i.participantId,runtimeId:crypto.randomUUID(),token:"",expiresAt:0},c=h}x.draft.history&&b&&(g=await b.update({reference:x,basis:n,pending:[]}),g&&(x=g.reference))}catch(h){throw b?.close(),w(),h}let A;try{A=x.draft.history?$r({draft:x.draft,source:n,actor:p.runtimeId,view:l,pendingEvents:g?.pending,persist:b?async(h,J,T)=>{await b.update({reference:{...x,draft:h},basis:J,pending:T})}:void 0,saveView:h=>{try{r.setItem(d,JSON.stringify({isAnnotating:h.isAnnotating,activeColor:h.activeColor}))}catch{}},save:(h,J,T,Q)=>a.merge(p,h,J,Q)}):null}catch(h){throw b?.close(),w(),h}let P=A??Tr({draft:x.draft,source:n,save:(h,J,T)=>a.publish(p,h,J,T)}),C=!1,O=!1,M=null,j="connected",D=null,_=null,ie=0,H,ae=1e3,v=-1,te=!1,z=!1,F=new Set,R=()=>{for(let h of F)h()},$=()=>{C||H||D||j!=="reconnecting"||(H=setTimeout(()=>{H=void 0,oe()},ae),ae=Math.min(ae*2,3e4))},L=h=>{if(!C){if(M=h instanceof Error?h:new Error(String(h)),P.pause(M),M instanceof ke&&M.status===401){j="paused",z=!0,ie++,clearTimeout(H),H=void 0,R();return}j=Xe(M)?"reconnecting":"paused",j==="paused"&&(ie++,clearTimeout(H),H=void 0),$(),R()}},oe=(h=!1)=>{if(C)return Promise.reject(new Error("Participant runtime is closed"));if(_&&!h)return _;if(D)return D;let J=++ie,T=()=>!C&&J===ie;return clearTimeout(H),H=void 0,j="reconnecting",P.pause(M??new Error("Reconnecting to the participant session")),R(),D=(async()=>{if(await P.whenSettled(),!T())return;let Q=await a.connect(p.runtimeId,p.token);if(C)return;p=Q;try{r.setItem(s,JSON.stringify(p))}catch(Oe){if(!A?.getStatus().memoryOnly)throw Oe}if(!T())return;let Te=await a.read();T()&&(P.reconcile(Te.draft),await P.flush(),T()&&(M=null,j="connected",ae=1e3,R()))})().catch(Q=>{T()&&L(Q)}).finally(()=>{D=null,$()}),D},me=P.binding.subscribe(()=>{j==="connected"&&P.flush().catch(L)}),be=A?.subscribeStatus(()=>{let h=A.getStatus().localError;h&&h!==M?L(h):R()}),pe,he=setInterval(()=>{if(C||O||j!=="connected")return;O=!0;let h=p,J=P.binding.getSnapshot().activeColor;a.renew(p,J!==pe?J:void 0).then(T=>{!C&&p===h&&(p=T,pe=J,r.setItem(s,JSON.stringify(T)))}).catch(T=>{pe=void 0,!(p!==h||j!=="connected")&&(L(T),T instanceof ke&&T.status===409&&T.code==="runtime_expired"&&oe())}).finally(()=>{O=!1})},4e3),de=!1,se=0,Ee=async h=>{if(C||j!=="connected"||!A||!h)return;let J=ie;if(h.draftRevision>P.getStatus().revision){let T=await a.read();!C&&j==="connected"&&J===ie&&A.receive(T.draft)}},ce=setInterval(()=>{C||de||j!=="connected"||!A||se||(de=!0,a.snapshot().then(async h=>{let J=h.find(T=>T.identity.id===i.participantId);await Ee(J)}).catch(L).finally(()=>{de=!1}))},1e3),ge=0,G=!1,q=()=>{let h=P.binding.getSnapshot();return JSON.stringify({annotations:h.annotations.map(J=>({...J,status:void 0})),styles:h.styleModifications,text:h.textModifications,dom:h.domModifications,spacing:h.spacingTokenChanges})},le=null,Ce=null,Y=!1,$e=setInterval(()=>{if(C||!le||Y||j!=="connected")return;let h=le,J=p;Y=!0,a.previewWanted(p).then(async({wanted:T})=>{if(!T||le!==h||C||j!=="connected")return;await P.flush();let Q=P.binding.getSnapshot(),Te=P.getStatus().revision,Oe=await h.frame(Jr(Q));Oe&&le===h&&!C&&j==="connected"&&J.token===p.token&&Q===P.binding.getSnapshot()&&await a.publishPreview(p,Oe.image,{draftRevision:Te,targets:Oe.targets})}).catch(T=>{if(!(C||j!=="connected")){if(T instanceof Error&&Xe(T)){L(T);return}le===h&&(Ce=T instanceof Error?T.message:"Preview unavailable",h.stop(),le=null,R())}}).finally(()=>{Y=!1})},1e3);c?L(c):g?.pending.length&&P.flush().catch(L);let re;return{client:a,credential:i,navigation:o,state:P,readViewedSuggestions:f.read,markSuggestionViewed:f.mark,markSuggestionsViewed:f.markMany,captureVersion:q,reportAttention(h,J,T,Q){return C||j!=="connected"?Promise.resolve(!1):a.reportAttention(p,h,J,T,Q)},bindSubjects(h){return re=h,()=>{re===h&&(re=void 0)}},getSubjects:()=>re,getStatus:()=>({error:M,phase:j,pendingCount:ge,sending:G,sharing:!!le,previewError:Ce,accessRemoved:z}),reconnect:()=>oe(),retainExternalMembershipPolling(){se++;let h=!1;return()=>{h||(h=!0,se--)}},async retryLocalSave(){if(_)return _;await A?.retryLocalSave(),await oe()},clearLocalSpace(){return _||(C||!A?Promise.reject(new Error("Local space is unavailable")):(_=Promise.resolve().then(async()=>{let h=D;if(ie++,clearTimeout(H),H=void 0,j="paused",P.pause(new Error("Clearing local space")),R(),await h,C)throw new Error("Participant runtime is closed");try{r.setItem(I,"1")}catch{}await A.clearLocalSpace();let J;try{if(await Promise.race([b?.clear?b.clear():Promise.reject(new Error("Local storage cannot be cleared")),new Promise((T,Q)=>{J=setTimeout(()=>Q(new Error("Local clear timed out")),2e3)})]),C)throw new Error("Participant runtime is closed");if(await A.resumeLocalSaving())try{r.removeItem(I)}catch{}}catch{}finally{clearTimeout(J)}if(C)throw new Error("Participant runtime is closed");if(await oe(!0),j!=="connected")throw M??new Error("Session remains unavailable")}).finally(()=>{_=null}),_))},observeMembership(h){if(!(C||h.identity.id!==i.participantId)){if(h.revokedAt!==void 0&&!te){te=!0,L(new ke(403,"Your access was removed by the host")),le?.stop(),le=null,r.removeItem(s),r.removeItem(d),o.clear(),P.revoke().then(()=>b?.clear?.()).then(()=>{z=!0,R()}).catch(J=>{M=J instanceof Error?J:new Error("Could not clear local draft"),R()});return}if(!te){if(h.permission!=="blocked"&&!de&&(de=!0,Ee(h).catch(L).finally(()=>{de=!1})),h.permission==="blocked")v=h.permissionEpoch,M instanceof ke&&M.status===403||L(new ke(403,"Participant access is blocked"));else if(j==="paused"&&M instanceof ke&&M.status===403&&h.permissionEpoch>v){v=h.permissionEpoch;let J=()=>{!C&&j==="paused"&&v===h.permissionEpoch&&M instanceof ke&&M.status===403&&oe()};D?D.then(J):J()}}}},sharePreview(h){if(C){h?.stop();return}le?.stop(),le=h,Ce=null,h||a.publishPreview(p,null).catch(()=>{}),R()},subscribe:h=>(F.add(h),()=>{F.delete(h)}),async send(h,J){if(C||j!=="connected")throw M??new Error("Participant runtime is closed");if(G)throw new Error("A submission is already in progress");G=!0,R();try{if(P.setSource(n),await P.flush(),j!=="connected")throw M??new Error("Draft sync paused");if(q()!==J)throw new Error("Draft changed during capture; send again to include your latest changes");let T=await a.send(mr(h),P.getStatus().revision,n);return T.status==="pending-approval"?(ge++,R(),{pendingApproval:!0,submissionId:T.submissionId,threadId:T.threadId}):T}finally{G=!1,R()}},dispose(){C||(C=!0,re=void 0,j="closed",clearTimeout(H),clearInterval(he),clearInterval(ce),clearInterval($e),le?.stop(),le=null,a.publishPreview(p,null).catch(()=>{}),me(),be?.(),w(),P.dispose(),P.whenSettled().finally(()=>b?.close()),F.clear())}}}function qr(e,t){e.removeItem(`popmelt-participant:${t}`);let r=`popmelt-admission:${t}`,i;try{i=JSON.parse(e.getItem(r)??"null")}catch{e.removeItem(r);return}i&&typeof i=="object"&&e.setItem(r,JSON.stringify({name:i.name,colorIdentity:i.colorIdentity??i.receipt}))}var ft="popmelt-join",Tt=/^[A-Za-z0-9_-]{43}$/;function zr(e,t){let r=new URL(e);if(!["http:","https:"].includes(r.protocol)||!["localhost","127.0.0.1","[::1]"].includes(r.hostname)||!Tt.test(t))throw new Error("A local page and valid invitation are required");let i=jt(r.href).cleanUrl,n=new URL(i);return n.hash=`${n.hash.slice(1)}${n.hash?"&":""}${ft}=${t}`,n.href}function jt(e){let t=new URL(e),r=null,i=t.hash.slice(1).split("&").filter(n=>{if(!n.startsWith(`${ft}=`))return!0;let a=n.slice(ft.length+1);return Tt.test(a)&&(r=a),!1});return t.hash=i.join("&"),{token:r,cleanUrl:t.href}}function Fr(e){let t={phase:"starting"},r=0,i=!1,n=!1,a=0,s,d=new Set,o=`popmelt-participant:${e.projectId}`,f=new Ct(e.url,e.projectId),l=g=>{if(!n){t=g;for(let c of d)c()}},u=async(g={})=>{let c=await fetch("/__popmelt/host",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify(g),redirect:"error"});if(c.status===403)return null;if(!c.ok)throw new Error(`Host entry unavailable (${c.status}).`);let p=`popmelt-before-participants:${e.projectId}`;return localStorage.getItem(p)===null&&localStorage.setItem(p,JSON.stringify(Object.fromEntries(Object.values(ar(e.projectId)).map(x=>[x,localStorage.getItem(x)])))),await c.json()},w=g=>_r({bridgeUrl:e.url,projectId:e.projectId,credential:g,runtimeStorage:sessionStorage,observedSource:{sourceId:e.projectId,revision:e.revision}}),I=async(g,c=a)=>{if(n||c!==a)return;let p=await w(g);if(n||c!==a){p.dispose();return}try{localStorage.setItem(o,JSON.stringify(g))}catch(x){throw p.dispose(),x}s?.dispose(),s=p,l({phase:"connected",connection:p}),u({credential:g}).catch(()=>{})},y=()=>{a++,s?.dispose(),s=void 0,qr(localStorage,e.projectId),l({phase:"entry",invitation:null})},b=async()=>{let g=jt(location.href),c=new URL(g.cleanUrl),p=new URLSearchParams(c.hash.slice(1)),x=p.get("popmelt-host");p.delete("popmelt-host"),x&&(c.hash=p.toString()),c.href!==location.href&&history.replaceState(history.state,"",c);let A=null;if(x){if(A=await u({token:x}),!A)throw new Error("Host entry expired. Use the current private host link.")}else if(!g.token){try{A=JSON.parse(localStorage.getItem(o)??"null")}catch{}A??(A=await u())}if(!n){if(!A){l({phase:"entry",invitation:g.token??null});return}try{await I(A)}catch(P){if(n)return;if(P.code==="access_removed"){y();return}if(P.status!==401)throw P;let C=await u();C?await I(C):y()}}};return{client:f,getSnapshot:()=>t,subscribe(g){return d.add(g),()=>{d.delete(g)}},retain(){if(n)throw new Error("Participant lifecycle is disposed");r++,i||(i=!0,b().catch(c=>l({phase:"error",message:c.message})));let g=!1;return()=>{g||(g=!0,r--,queueMicrotask(()=>{r||n||(n=!0,a++,s?.dispose(),s=void 0,d.clear())}))}},removed:y,async join(g,c){if(t.phase!=="entry"||!t.invitation||n)throw new Error("No active invitation");if(!c)throw new Error("Peer identity is not ready");let p=a,x=await f.joinOrRequestAdmission(t.invitation,g,c);if(!(n||p!==a)){if("admission"in x){localStorage.setItem(`popmelt-admission:${e.projectId}`,JSON.stringify({name:x.admission.name,receipt:c,colorIdentity:c})),l({phase:"entry",invitation:null});return}await I(x.joined.credential,p)}},admit:g=>I(g)}}function Ke(){let e=crypto.getRandomValues(new Uint8Array(32));return{id:crypto.randomUUID(),token:Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}}var Ue=360,_e=120,Ye=180,Ot=260;function Vr({client:e,storage:t,storageKey:r,onAdmitted:i,theme:n="light",themePreference:a=n,onThemePreferenceChange:s,onJoin:d}){let o=K(null),f=K(!1);if(!f.current){f.current=!0;try{o.current=JSON.parse(t.getItem(r)??"null")}catch{}}let[l,u]=U(o.current?.name??""),[w,I]=U(d?void 0:o.current?.receipt),[y,b]=U(null),[g,c]=U(),[p,x]=U(),A=K(null),[P,C]=U(!!d),[O,M]=U(!1),[j,D]=U(0),[_,ie]=U(),[H,ae]=U("idle"),[v,te]=U(),[z,F]=U(),R=K(!1),[$,L]=U(""),oe=K(null),me=K(null),be=K(null),pe=K(null),he=K(!1),de=K(0),se=K(!1),Ee=yr(),ce=K(!1),ge=K(0),G=K(i);G.current=i;let q=K(!1),le=K(null),Ce=K(()=>{});le.current||(le.current=new Promise(k=>{Ce.current=k}));let Y=rt[n],$e=P&&!g;ee(()=>{let k=!1,Z,X,V=()=>{k||(k=!0,q.current=!0,Ce.current())};typeof requestAnimationFrame=="function"&&(Z=requestAnimationFrame(()=>{X=requestAnimationFrame(V)}));let Ie=window.setTimeout(V,64);return()=>{Z!==void 0&&cancelAnimationFrame(Z),X!==void 0&&cancelAnimationFrame(X),window.clearTimeout(Ie),V()}},[]),ee(()=>ur(document),[]),St(()=>{let k=!0,Z=()=>{if(!k||!be.current)return;let X=getComputedStyle(be.current),V=document.createElement("span");Object.assign(V.style,{position:"fixed",visibility:"hidden",pointerEvents:"none",whiteSpace:"nowrap",fontFamily:X.fontFamily,fontSize:X.fontSize,fontWeight:X.fontWeight,lineHeight:X.lineHeight}),document.body.append(V);let Ie=Number.parseFloat(X.paddingLeft)+Number.parseFloat(X.paddingRight);V.textContent="Ask for access";let Pe=Ie+12+3+V.getBoundingClientRect().width;V.textContent="Request pending";let ye=Ie+12+3+V.getBoundingClientRect().width;V.textContent="Request declined";let Me=Ie+12+3+V.getBoundingClientRect().width;if(V.remove(),Pe>15&&ye>15&&Me>15&&te({ask:Math.ceil(Pe),pending:Math.ceil(ye),declined:Math.ceil(Me)}),pe.current){let xe=getComputedStyle(pe.current),ve=document.createElement("span");Object.assign(ve.style,{position:"fixed",visibility:"hidden",pointerEvents:"none",whiteSpace:"nowrap",fontFamily:xe.fontFamily,fontSize:xe.fontSize,fontWeight:xe.fontWeight,lineHeight:xe.lineHeight}),ve.textContent="Sending...",document.body.append(ve);let we=Number.parseFloat(xe.paddingLeft)+Number.parseFloat(xe.paddingRight);F({idle:Math.ceil(we+14),sending:Math.ceil(we+ve.getBoundingClientRect().width)}),ve.remove()}};return Z(),document.fonts?.ready.then(Z),()=>{k=!1}},[n,P]),ee(()=>{if(!j)return;let k=setTimeout(()=>D(0),Ue);return()=>clearTimeout(k)},[j]),ee(()=>{if(!_)return;let k=setTimeout(()=>ie(void 0),Ue);return()=>clearTimeout(k)},[_]),ee(()=>{if(H!=="in")return;let k=setTimeout(()=>ae("idle"),Ye);return()=>clearTimeout(k)},[H]),ee(()=>{o.current&&delete o.current.color;try{let k=JSON.parse(t.getItem(r)??"null");k&&typeof k=="object"&&"color"in k&&(delete k.color,t.setItem(r,JSON.stringify(k)))}catch{}},[t,r]);let re=!!(w&&(!y||y.status==="pending"||y.status==="granted")),h=(k,Z)=>{o.current={...o.current,name:k,receipt:Z},t.setItem(r,JSON.stringify(o.current))};ee(()=>{if(y?.status==="cancelled"){o.current={...o.current,name:l,receipt:void 0};try{t.setItem(r,JSON.stringify(o.current))}catch{}I(void 0),b(null)}},[y,l,t,r]);let J=()=>{if(A.current)return A.current;let k=async()=>{let Z=JSON.parse(t.getItem(r)??"null"),X=Z?.colorIdentity??Z?.receipt??Ke();o.current={name:l,receipt:Z?.receipt,colorIdentity:X},t.setItem(r,JSON.stringify(o.current));let V;try{V=await e.reserveAdmissionColor(X)}catch(Ie){let Pe=Ie.status;if(Pe!==400&&Pe!==401)throw Ie;X=Ke(),o.current={...o.current,colorIdentity:X},t.setItem(r,JSON.stringify(o.current)),V=await e.reserveAdmissionColor(X)}return c(V.color),x(or(V)),X};return A.current=k().finally(()=>{A.current=null}),A.current},T=()=>{C(!P),P||L("")},Q=K(J);Q.current=J;let Te=!!d;ee(()=>{if(!P||g)return;let k=!1,Z,X=0,V=async()=>{try{await Q.current()}catch{if(k)return;Z=setTimeout(()=>{V()},pt(++X))}};return V(),()=>{k=!0,clearTimeout(Z)}},[P,g,t,r]),ee(()=>{if(!P)return;me.current?.focus();let k=Z=>{Z.composedPath().includes(oe.current)||C(!1)};return document.addEventListener("pointerdown",k),()=>document.removeEventListener("pointerdown",k)},[P]),ee(()=>{if(!w)return;let k=!0,Z=!1,X=!1,V,Ie,Pe=()=>{ge.current+=1,o.current={...o.current,name:l,receipt:void 0};try{t.setItem(r,JSON.stringify(o.current))}catch{}I(void 0),b(null),C(!1),L("")},ye=()=>{X=!0;let ve=Ke(),we=0,Le=async()=>{if(k)try{let De=await Q.current();o.current={...o.current,name:l,receipt:ve,colorIdentity:De},t.setItem(r,JSON.stringify(o.current));let qe=await e.requestAdmission(ve,l,De);if(!k)return;ge.current+=1,I(ve),b(qe),L("")}catch{if(!k)return;Ie=setTimeout(()=>{Le()},pt(++we))}};Le()},Me=async()=>{if(Z||X||se.current||ce.current)return;Z=!0;let ve=ge.current;try{let we=await e.admissionStatus(w);if(!k||ve!==ge.current)return;if(we.status==="declined"){if(q.current||await le.current,!k||ve!==ge.current)return;X=!0;let Le=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches,De=()=>{k&&(ae("rejected"),D(qe=>qe+1),V=setTimeout(()=>{if(k){if(Le){Pe(),ae("idle");return}ae("rejected-out"),V=setTimeout(()=>{k&&(Pe(),ae("in"))},_e)}},Ue))};Le?De():(ae("pending-out"),V=setTimeout(De,_e));return}if(we.status==="expired"){ye();return}if(b(we),X=we.status==="cancelled",L(""),we.credential){se.current=!0;try{await G.current(we.credential),X=!0}finally{se.current=!1}}}catch(we){if(!k||ve!==ge.current)return;we.status===401&&ye()}finally{Z=!1}};Me();let xe=setInterval(Me,1500);return()=>{k=!1,clearInterval(xe),clearTimeout(V),clearTimeout(Ie)}},[e,w,l,t,r]);let Oe=async()=>{if(!(!w||O||ce.current)){ce.current=!0,ge.current+=1,M(!0),L("");try{let k=await e.cancelAdmission(w);b(k),C(!1)}catch{D(k=>k+1)}finally{ce.current=!1,M(!1)}}},et=async k=>{if(!l.trim()||O||re||R.current)return;if(R.current=!0,M(!0),L(""),ie(void 0),d){try{let X=await J();h(l.trim()),await d(l.trim(),X)}catch(X){L(X instanceof Error?X.message:"Could not join. Please try again.")}finally{R.current=!1,M(!1)}return}try{o.current=JSON.parse(t.getItem(r)??"null")}catch{}let Z=!y&&o.current?.receipt?o.current.receipt:Ke();try{let X=await J();h(l,Z),o.current={...o.current,name:l,receipt:Z};let V=await e.requestAdmission(Z,l.trim(),X);I(Z),u(V.name),b(V),C(!1)}catch{o.current={...o.current,name:l,receipt:Z},ie({target:k,pulse:++de.current})}finally{R.current=!1,M(!1)}};return B("div",{ref:oe,"data-devtools":"participant-admission","data-popmelt-font":"sans","data-popmelt-theme":n,style:{display:"contents"},onKeyDown:k=>{k.key==="Escape"&&(C(!1),k.stopPropagation())},children:[S("style",{children:`
|
|
3
3
|
${Bt}
|
|
4
4
|
[data-popmelt-admission-ask] {
|
|
5
5
|
transition: box-shadow 120ms ease, width ${Ye}ms ease;
|