@popmelt.com/core 0.27.0 → 0.27.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "popmelt-core",
3
- "version": "0.27.0",
3
+ "version": "0.27.1",
4
4
  "description": "Local Popmelt context, canvas tools, and ambient turn capture for Claude Code.",
5
5
  "author": {
6
6
  "name": "Popmelt",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "popmelt-core",
3
- "version": "0.27.0",
3
+ "version": "0.27.1",
4
4
  "description": "Point out what you mean, talk through changes, and keep your AI on the same page.",
5
5
  "author": {
6
6
  "name": "Popmelt",
@@ -1,5 +1,5 @@
1
1
  "use client";
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:`
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 Kt,ib as Xt,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-YMCTJKYN.mjs";import{za as cr,xa as rt,_ as ze,ba as ur,u as pr,Ga as fr,Ka as hr,H as mr}from"./chunk-7MGWRICI.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 X,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 Ke(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)||!Ke(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=Ke(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&&Ke(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 Xe(){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=X(null),f=X(!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=X(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=X(!1),[$,L]=U(""),oe=X(null),me=X(null),be=X(null),pe=X(null),he=X(!1),de=X(0),se=X(!1),Ee=yr(),ce=X(!1),ge=X(0),G=X(i);G.current=i;let q=X(!1),le=X(null),Ce=X(()=>{});le.current||(le.current=new Promise(k=>{Ce.current=k}));let Y=rt[n],$e=P&&!g;ee(()=>{let k=!1,Z,K,V=()=>{k||(k=!0,q.current=!0,Ce.current())};typeof requestAnimationFrame=="function"&&(Z=requestAnimationFrame(()=>{K=requestAnimationFrame(V)}));let Ie=window.setTimeout(V,64);return()=>{Z!==void 0&&cancelAnimationFrame(Z),K!==void 0&&cancelAnimationFrame(K),window.clearTimeout(Ie),V()}},[]),ee(()=>ur(document),[]),St(()=>{let k=!0,Z=()=>{if(!k||!be.current)return;let K=getComputedStyle(be.current),V=document.createElement("span");Object.assign(V.style,{position:"fixed",visibility:"hidden",pointerEvents:"none",whiteSpace:"nowrap",fontFamily:K.fontFamily,fontSize:K.fontSize,fontWeight:K.fontWeight,lineHeight:K.lineHeight}),document.body.append(V);let Ie=Number.parseFloat(K.paddingLeft)+Number.parseFloat(K.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"),K=Z?.colorIdentity??Z?.receipt??Xe();o.current={name:l,receipt:Z?.receipt,colorIdentity:K},t.setItem(r,JSON.stringify(o.current));let V;try{V=await e.reserveAdmissionColor(K)}catch(Ie){let Pe=Ie.status;if(Pe!==400&&Pe!==401)throw Ie;K=Xe(),o.current={...o.current,colorIdentity:K},t.setItem(r,JSON.stringify(o.current)),V=await e.reserveAdmissionColor(K)}return c(V.color),x(or(V)),K};return A.current=k().finally(()=>{A.current=null}),A.current},T=()=>{C(!P),P||L("")},Q=X(J);Q.current=J;let Te=!!d;ee(()=>{if(!P||g)return;let k=!1,Z,K=0,V=async()=>{try{await Q.current()}catch{if(k)return;Z=setTimeout(()=>{V()},pt(++K))}};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,K=!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=()=>{K=!0;let ve=Xe(),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||K||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;K=!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),K=we.status==="cancelled",L(""),we.credential){se.current=!0;try{await G.current(we.credential),K=!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 K=await J();h(l.trim()),await d(l.trim(),K)}catch(K){L(K instanceof Error?K.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:Xe();try{let K=await J();h(l,Z),o.current={...o.current,name:l,receipt:Z};let V=await e.requestAdmission(Z,l.trim(),K);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;
@@ -96,7 +96,7 @@ import{a as Jt}from"./chunk-7YCLSSQA.mjs";import{Pb as Wt,vb as Ut,Yb as gt,gb a
96
96
  [data-popmelt-admission-send-icon],
97
97
  [data-popmelt-admission-sending-label] { animation: none !important; }
98
98
  }
99
- `}),S(gt,{entry:{theme:n,themePreference:a,onThemePreferenceChange:s,deemphasizeControls:P,onCollapse:()=>C(!1),panel:P||$?B(We,{children:[P&&!re&&B("form",{"aria-label":Te?"Join session":"Ask for access","data-popmelt-font":"sans",style:{...yt(n),flexWrap:"wrap"},onSubmit:k=>{k.preventDefault();let Z=he.current?"enter":"send";he.current=!1,et(Z)},children:[B("div",{style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0},children:[S(Gt,{"data-popmelt-entry-avatar":!0,shape:p,color:g??($e?Y.muted:"transparent"),size:Qt.identitySize}),B("span",{"data-popmelt-admission-name-field":!0,style:{display:"inline-grid",flex:"0 1 auto",minWidth:0},children:[S("span",{"aria-hidden":"true","data-popmelt-admission-name-measure":!0,style:{gridArea:"1 / 1",visibility:"hidden",whiteSpace:"pre",overflow:"hidden",paddingRight:1},children:l||"what\u2019s your name?"}),S("input",{ref:me,"aria-label":"Your name",placeholder:"what\u2019s your name?",autoComplete:"nickname",maxLength:48,value:l,disabled:O,onKeyDown:k=>{k.key==="Enter"&&(he.current=!0)},onKeyUp:k=>{k.key==="Enter"&&(he.current=!1)},onBlur:()=>{he.current=!1},onChange:k=>{u(k.target.value);try{h(k.target.value,o.current?.receipt)}catch{}},style:{gridArea:"1 / 1",minWidth:"100%",width:0,padding:0,border:0,borderRadius:0,background:"transparent",color:O?Y.mutedStrong:Y.primary,WebkitTextFillColor:O?Y.mutedStrong:Y.primary,caretColor:O?"transparent":Y.primary,opacity:1,transition:"color 120ms ease",font:"inherit",fontFamily:ze,outline:"none",boxShadow:"none",appearance:"none"}})]}),S("kbd",{"aria-hidden":"true","data-popmelt-admission-enter-hint":!0,"data-popmelt-admission-submit-rejection":_?.target==="enter"?_.pulse%2?"odd":"even":void 0,style:{...tr(n),...er,flexShrink:0,color:l.trim()?Y.primary:Y.muted,opacity:O?0:1,pointerEvents:O?"none":void 0,transition:`opacity ${_e}ms ease`},children:"enter"})]}),B("button",{ref:pe,type:"submit",disabled:O||$e||!g||!l.trim(),"aria-label":O?"Sending\u2026":Te?"Join session":"Send request","aria-keyshortcuts":"Enter","aria-busy":O||void 0,"data-popmelt-admission-submit-rejection":_?.target==="send"?_.pulse%2?"odd":"even":void 0,style:{...rr(n),width:z?z[O?"sending":"idle"]:void 0,position:"relative",boxSizing:"border-box",overflow:"hidden",fontSize:12,color:O||!l.trim()?Y.muted:Y.primary,transition:`color ${_e}ms ease, width ${Ye}ms ease`},children:[S("span",{"aria-hidden":"true","data-popmelt-admission-submit-sizer":!0,style:{width:14,height:14,flexShrink:0}}),B("span",{"aria-hidden":"true","data-popmelt-admission-submit-content":!0,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[S(kr,{size:14,"data-popmelt-admission-send-icon":!0,style:{position:"absolute",top:"50%",right:8,opacity:O?0:1,transform:O?"translate(10px, -50%)":"translate(0, -50%)",animation:O?`popmelt-admission-send-icon-out ${Ot}ms ease both`:void 0}}),B("span",{"data-popmelt-admission-sending-label":!0,style:{position:"absolute",top:"50%",right:8,opacity:O?1:0,transform:O?"translate(0, -50%)":"translate(-12px, -50%)",animation:O?`popmelt-admission-sending-label-in ${Ot}ms ease 40ms both`:void 0},children:["Sending",B("span",{"data-popmelt-admission-sending-dots":!0,"aria-hidden":"true",style:{display:"inline-block"},children:[S("span",{"data-popmelt-admission-sending-dot":"1",children:"."}),S("span",{"data-popmelt-admission-sending-dot":"2",children:"."}),S("span",{"data-popmelt-admission-sending-dot":"3",children:"."})]})]})]})]}),$&&S("span",{role:"alert",style:{flexBasis:"100%",fontSize:12},children:$})]}),!P&&$&&S("div",{role:"status",style:{...yt(n),fontSize:12},children:$})]}):null,action:B(We,{children:[S("span",{"aria-hidden":"true","data-popmelt-admission-host":!0,style:{width:22,height:22,marginLeft:5,flexShrink:0,boxSizing:"border-box",border:`1px solid ${Y.surface}`,borderRadius:"50%",background:je.activeColor,opacity:P||re?.2:1,transition:q.current?`opacity ${_e}ms ease`:"none"}}),S("button",{ref:be,type:"button","data-popmelt-font":"sans","data-popmelt-admission-ask":!0,"data-popmelt-admission-pending":re?"":void 0,"data-popmelt-admission-declined":H==="rejected"||H==="rejected-out"?"":void 0,"data-popmelt-admission-rejection":j?j%2?"odd":"even":void 0,"data-popmelt-admission-transition":H==="idle"?void 0:H,"data-popmelt-entry-control":!0,"aria-expanded":re?void 0:P,"aria-label":H==="rejected"||H==="rejected-out"?"Request declined":re?"Cancel request":void 0,"aria-describedby":re?Ee:void 0,"aria-busy":re&&O?!0:void 0,disabled:re&&(O||H!=="idle"),onClick:()=>H==="idle"&&(re?void Oe():T()),"aria-description":re?void 0:Te?"Enter your name to join the session.":"Ask the host to join in Suggest mode.",style:{...Zt(n),width:v?v[H==="rejected"||H==="rejected-out"?"declined":re?"pending":"ask"]:void 0,paddingLeft:3,overflow:"hidden",transition:`box-shadow 120ms ease, width ${Ye}ms ease`,background:re&&y?.color?`color-mix(in srgb, ${y.color} 10%, ${Y.control})`:Y.control},children:B("span",{"data-popmelt-entry-content":!0,style:{display:re?"inline-grid":"inline-flex",alignItems:"center",gap:"inherit",opacity:H==="pending-out"||H==="rejected-out"?0:1,transition:q.current?`opacity ${_e}ms ease`:"none"},children:[H==="rejected"||H==="rejected-out"?B("span",{id:Ee,"data-popmelt-admission-declined-label":!0,"aria-hidden":"true",children:[S(wr,{size:12}),"Request declined"]}):re?B(We,{children:[B("span",{id:Ee,"data-popmelt-admission-pending-label":!0,"aria-hidden":"true",children:[S(br,{size:12,style:{color:y?.color}}),"Request pending"]}),B("span",{"data-popmelt-admission-cancel-label":!0,"aria-hidden":"true",children:[S(Ir,{size:12}),"Cancel request"]})]}):S(Sr,{size:12,"aria-hidden":"true","data-popmelt-admission-wave":!0}),!re&&"Ask for access"]})})]})}})]})}function Mt(e){return{read:e==="direct"||e==="approval-required",reply:e==="direct"}}var Hr=150;function Xr(e,t,r,i="connected",n){let a=K(null),s=K({client:e,failures:0,until:0,stopped:new Set}),d=K(i),[o,f]=U(0),l=Je(()=>{a.current=null,s.current.failures=0,s.current.until=0,s.current.stopped.clear(),f(c=>c+1)},[]),u=K({participantId:t,client:e});(u.current.participantId!==t||u.current.client!==e)&&(u.current={participantId:t,client:e});let w=u.current,[I,y]=U(null);ee(()=>{if((s.current.client!==e||d.current!=="connected"&&i==="connected")&&(s.current={client:e,failures:0,until:0,stopped:new Set},a.current=null),d.current=i,!t)return;let c=s.current,p=j=>y({intent:w,reference:null,retrying:j,error:"Preview unavailable.",retryAt:j?c.until:void 0});if(c.stopped.has(t)){p(!1);return}c.until>Date.now()&&p(!0);let x=!0,A,P,C,O=()=>x&&u.current===w,M=async()=>{if(n!==void 0&&a.current?.participantId===t&&a.current.reference.draft.revision>=n){y({intent:w,reference:a.current.reference,error:"",retrying:!1});return}let j=1e3;y(D=>D?.intent===w&&D.retrying?{...D,retryAt:0}:D),A=new AbortController,P=setTimeout(()=>A?.abort(),15e3);try{let D=await e.read(t,A.signal);if(!O())return;if(D?.author?.id!==t||!D.draft)throw new Error("Preview identity does not match");c.failures=0,c.until=0,a.current={client:e,participantId:t,reference:D},n!==void 0&&(j=null),y(_=>_?.intent===w&&_.reference?.planeId===D.planeId&&_.reference.draft.revision===D.draft.revision&&_.reference.draft.source?.sourceId===D.draft.source?.sourceId&&_.reference.draft.source?.revision===D.draft.source?.revision?_:{intent:w,reference:D,error:"",retrying:!1})}catch(D){if(O()){a.current=null;let _=Xe(D);_?(j=pt(++c.failures),c.until=Date.now()+j):(j=null,c.stopped.add(t)),p(_)}}finally{clearTimeout(P),O()&&j!==null&&(C=setTimeout(M,j))}};return C=setTimeout(M,Math.max(r?Hr:0,c.until-Date.now())),()=>{x=!1,clearTimeout(C),clearTimeout(P),A?.abort()}},[n,e,t,r,w,i,o]);let b=a.current,g=i==="connected"&&b?.client===e&&b.participantId===t&&n!==void 0&&!s.current.stopped.has(t)?b.reference:null;return{...I?.intent===w&&t?I:{reference:g,error:"",retrying:!1,retryAt:void 0},retry:l}}function Nt(e,t){return e?e.id===t?"You":e.relationship==="host"&&e.name==="You"?"Host":e.name:"Peer"}function Kr({image:e,geometry:t,reference:r,name:i,color:n,peeking:a,focusedAnnotationId:s,hoveredAnnotationId:d}){let o=K(null),[f,l]=U(""),[u,w]=U(null);St(()=>{let b=o.current;if(!b)return;let g=()=>{let p=b.getBoundingClientRect();w({left:p.left,top:p.top,width:p.width,height:p.height})};g();let c=new ResizeObserver(g);return c.observe(b),()=>c.disconnect()},[]);let I=nt(()=>{let b=o.current;return!b?.naturalWidth||f!==e||!u||!t?new Map:new Map(t.targets.map(({selector:g,rect:c})=>[g,Wr(c,{width:b.naturalWidth,height:b.naturalHeight},u)]))},[u,f,e,t]),y=r?.draft.state;return B(We,{children:[S("img",{ref:o,src:e,alt:`${i}\u2019s live app`,onLoad:()=>l(e),style:{display:"block",width:"100%",height:"100%",objectFit:"contain"}}),(!a||d)&&y&&r&&t?.draftRevision===r.draft.revision&&f===e&&S(vt,{peer:{identity:r.author,color:n,revision:r.draft.revision,state:y},projectedTargets:I,focusedAnnotationId:d??s})]})}var Yr=[];function Rt({presence:e,peers:t,ownId:r,targetDocument:i=document,getSubjects:n,enabled:a}){let s=ir(a?e:Yr,a);return S(We,{children:s.map(({presence:d,engaged:o})=>{let f=e.find(u=>u.operationId===d.operationId&&u.peerId===d.peerId),l=t.find(u=>u.identity.id===d.peerId);return!f||!l||l.permission==="blocked"||l.identity.id===r||f.location.pathname!==i.location?.pathname?null:S(Br,{attention:f,name:l.identity.name,engaged:o,targetDocument:i,getSubjects:n},d.peerId)})})}function Br({attention:e,name:t,engaged:r,targetDocument:i,getSubjects:n}){let[a,s]=U([]),[d,o]=U(),f=JSON.stringify(e.location.targets);return ee(()=>{let l=!0,u=JSON.parse(f),w=()=>{if(!l)return;let y=n(),b=u.flatMap(g=>{try{let c=g.subject?y?.resolve(g.subject):void 0;if(g.subject&&(!c||c.subject.sourceElement&&bt(c.subject.sourceElement,"[data-private], [data-sensitive]")))return[];let p=c?.element??lr(g.selector,i);return p?.isConnected&&!bt(p,"[data-private], [data-sensitive]")?[p]:[]}catch{return[]}});o(y),s(g=>g.length===b.length&&g.every((c,p)=>c===b[p])?g:b)};w(),n()?.whenReady().then(w);let I=new MutationObserver(w);return i.body&&I.observe(i.body,{childList:!0,subtree:!0}),i.addEventListener("popmelt-subjects-ready",w),()=>{l=!1,I.disconnect(),i.removeEventListener("popmelt-subjects-ready",w)}},[i,n,f]),S(hr,{element:null,elements:a,registry:d,engaged:r,outlineColor:e.location.color,label:`${t} is ${e.location.threadId?"reading this element\u2019s thread":e.activity==="working"?"working on this element":"looking at this element"}`})}function Zr(e){let t,r=requestAnimationFrame(()=>{t=setTimeout(e,0)});return()=>{cancelAnimationFrame(r),clearTimeout(t)}}var ht=160;function Be({children:e,loading:t=!1,retryAt:r,actions:i}){let[n,a]=U(Date.now);ee(()=>{if(r===void 0)return;let I,y=()=>{let b=Date.now();a(b);let g=r-b;g>0&&(I=setTimeout(y,g%1e3||1e3))};return y(),()=>clearTimeout(I)},[r]);let s=Math.max(0,Math.ceil(((r??0)-n)/1e3)),d=e.replace(/(?<!\.)\.(?!\.)\s*$/,""),o=r===void 0?d:`${d} \xB7 Retrying${s>0?` in ${s}s`:" now"}\u2026`,f=`${e}:${r!==void 0}`,[l,u]=U({text:o,transitionKey:f,previous:null,version:0}),w=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;return l.transitionKey!==f?u({text:o,transitionKey:f,previous:w?null:l.text,version:l.version+1}):l.text!==o&&u({...l,text:o}),ee(()=>{if(!l.previous)return;let I=setTimeout(()=>u(y=>({...y,previous:null})),ht);return()=>clearTimeout(I)},[l.version,l.previous]),B("div",{"data-devtools":"peer-preview-status",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",padding:24,boxSizing:"border-box",pointerEvents:"none"},children:[S("style",{children:`
99
+ `}),S(gt,{entry:{theme:n,themePreference:a,onThemePreferenceChange:s,deemphasizeControls:P,onCollapse:()=>C(!1),panel:P||$?B(We,{children:[P&&!re&&B("form",{"aria-label":Te?"Join session":"Ask for access","data-popmelt-font":"sans",style:{...yt(n),flexWrap:"wrap"},onSubmit:k=>{k.preventDefault();let Z=he.current?"enter":"send";he.current=!1,et(Z)},children:[B("div",{style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0},children:[S(Gt,{"data-popmelt-entry-avatar":!0,shape:p,color:g??($e?Y.muted:"transparent"),size:Qt.identitySize}),B("span",{"data-popmelt-admission-name-field":!0,style:{display:"inline-grid",flex:"0 1 auto",minWidth:0},children:[S("span",{"aria-hidden":"true","data-popmelt-admission-name-measure":!0,style:{gridArea:"1 / 1",visibility:"hidden",whiteSpace:"pre",overflow:"hidden",paddingRight:1},children:l||"what\u2019s your name?"}),S("input",{ref:me,"aria-label":"Your name",placeholder:"what\u2019s your name?",autoComplete:"nickname",maxLength:48,value:l,disabled:O,onKeyDown:k=>{k.key==="Enter"&&(he.current=!0)},onKeyUp:k=>{k.key==="Enter"&&(he.current=!1)},onBlur:()=>{he.current=!1},onChange:k=>{u(k.target.value);try{h(k.target.value,o.current?.receipt)}catch{}},style:{gridArea:"1 / 1",minWidth:"100%",width:0,padding:0,border:0,borderRadius:0,background:"transparent",color:O?Y.mutedStrong:Y.primary,WebkitTextFillColor:O?Y.mutedStrong:Y.primary,caretColor:O?"transparent":Y.primary,opacity:1,transition:"color 120ms ease",font:"inherit",fontFamily:ze,outline:"none",boxShadow:"none",appearance:"none"}})]}),S("kbd",{"aria-hidden":"true","data-popmelt-admission-enter-hint":!0,"data-popmelt-admission-submit-rejection":_?.target==="enter"?_.pulse%2?"odd":"even":void 0,style:{...tr(n),...er,flexShrink:0,color:l.trim()?Y.primary:Y.muted,opacity:O?0:1,pointerEvents:O?"none":void 0,transition:`opacity ${_e}ms ease`},children:"enter"})]}),B("button",{ref:pe,type:"submit",disabled:O||$e||!g||!l.trim(),"aria-label":O?"Sending\u2026":Te?"Join session":"Send request","aria-keyshortcuts":"Enter","aria-busy":O||void 0,"data-popmelt-admission-submit-rejection":_?.target==="send"?_.pulse%2?"odd":"even":void 0,style:{...rr(n),width:z?z[O?"sending":"idle"]:void 0,position:"relative",boxSizing:"border-box",overflow:"hidden",fontSize:12,color:O||!l.trim()?Y.muted:Y.primary,transition:`color ${_e}ms ease, width ${Ye}ms ease`},children:[S("span",{"aria-hidden":"true","data-popmelt-admission-submit-sizer":!0,style:{width:14,height:14,flexShrink:0}}),B("span",{"aria-hidden":"true","data-popmelt-admission-submit-content":!0,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[S(kr,{size:14,"data-popmelt-admission-send-icon":!0,style:{position:"absolute",top:"50%",right:8,opacity:O?0:1,transform:O?"translate(10px, -50%)":"translate(0, -50%)",animation:O?`popmelt-admission-send-icon-out ${Ot}ms ease both`:void 0}}),B("span",{"data-popmelt-admission-sending-label":!0,style:{position:"absolute",top:"50%",right:8,opacity:O?1:0,transform:O?"translate(0, -50%)":"translate(-12px, -50%)",animation:O?`popmelt-admission-sending-label-in ${Ot}ms ease 40ms both`:void 0},children:["Sending",B("span",{"data-popmelt-admission-sending-dots":!0,"aria-hidden":"true",style:{display:"inline-block"},children:[S("span",{"data-popmelt-admission-sending-dot":"1",children:"."}),S("span",{"data-popmelt-admission-sending-dot":"2",children:"."}),S("span",{"data-popmelt-admission-sending-dot":"3",children:"."})]})]})]})]}),$&&S("span",{role:"alert",style:{flexBasis:"100%",fontSize:12},children:$})]}),!P&&$&&S("div",{role:"status",style:{...yt(n),fontSize:12},children:$})]}):null,action:B(We,{children:[S("span",{"aria-hidden":"true","data-popmelt-admission-host":!0,style:{width:22,height:22,marginLeft:5,flexShrink:0,boxSizing:"border-box",border:`1px solid ${Y.surface}`,borderRadius:"50%",background:je.activeColor,opacity:P||re?.2:1,transition:q.current?`opacity ${_e}ms ease`:"none"}}),S("button",{ref:be,type:"button","data-popmelt-font":"sans","data-popmelt-admission-ask":!0,"data-popmelt-admission-pending":re?"":void 0,"data-popmelt-admission-declined":H==="rejected"||H==="rejected-out"?"":void 0,"data-popmelt-admission-rejection":j?j%2?"odd":"even":void 0,"data-popmelt-admission-transition":H==="idle"?void 0:H,"data-popmelt-entry-control":!0,"aria-expanded":re?void 0:P,"aria-label":H==="rejected"||H==="rejected-out"?"Request declined":re?"Cancel request":void 0,"aria-describedby":re?Ee:void 0,"aria-busy":re&&O?!0:void 0,disabled:re&&(O||H!=="idle"),onClick:()=>H==="idle"&&(re?void Oe():T()),"aria-description":re?void 0:Te?"Enter your name to join the session.":"Ask the host to join in Suggest mode.",style:{...Zt(n),width:v?v[H==="rejected"||H==="rejected-out"?"declined":re?"pending":"ask"]:void 0,paddingLeft:3,overflow:"hidden",transition:`box-shadow 120ms ease, width ${Ye}ms ease`,background:re&&y?.color?`color-mix(in srgb, ${y.color} 10%, ${Y.control})`:Y.control},children:B("span",{"data-popmelt-entry-content":!0,style:{display:re?"inline-grid":"inline-flex",alignItems:"center",gap:"inherit",opacity:H==="pending-out"||H==="rejected-out"?0:1,transition:q.current?`opacity ${_e}ms ease`:"none"},children:[H==="rejected"||H==="rejected-out"?B("span",{id:Ee,"data-popmelt-admission-declined-label":!0,"aria-hidden":"true",children:[S(wr,{size:12}),"Request declined"]}):re?B(We,{children:[B("span",{id:Ee,"data-popmelt-admission-pending-label":!0,"aria-hidden":"true",children:[S(br,{size:12,style:{color:y?.color}}),"Request pending"]}),B("span",{"data-popmelt-admission-cancel-label":!0,"aria-hidden":"true",children:[S(Ir,{size:12}),"Cancel request"]})]}):S(Sr,{size:12,"aria-hidden":"true","data-popmelt-admission-wave":!0}),!re&&"Ask for access"]})})]})}})]})}function Mt(e){return{read:e==="direct"||e==="approval-required",reply:e==="direct"}}var Hr=150;function Kr(e,t,r,i="connected",n){let a=X(null),s=X({client:e,failures:0,until:0,stopped:new Set}),d=X(i),[o,f]=U(0),l=Je(()=>{a.current=null,s.current.failures=0,s.current.until=0,s.current.stopped.clear(),f(c=>c+1)},[]),u=X({participantId:t,client:e});(u.current.participantId!==t||u.current.client!==e)&&(u.current={participantId:t,client:e});let w=u.current,[I,y]=U(null);ee(()=>{if((s.current.client!==e||d.current!=="connected"&&i==="connected")&&(s.current={client:e,failures:0,until:0,stopped:new Set},a.current=null),d.current=i,!t)return;let c=s.current,p=j=>y({intent:w,reference:null,retrying:j,error:"Preview unavailable.",retryAt:j?c.until:void 0});if(c.stopped.has(t)){p(!1);return}c.until>Date.now()&&p(!0);let x=!0,A,P,C,O=()=>x&&u.current===w,M=async()=>{if(n!==void 0&&a.current?.participantId===t&&a.current.reference.draft.revision>=n){y({intent:w,reference:a.current.reference,error:"",retrying:!1});return}let j=1e3;y(D=>D?.intent===w&&D.retrying?{...D,retryAt:0}:D),A=new AbortController,P=setTimeout(()=>A?.abort(),15e3);try{let D=await e.read(t,A.signal);if(!O())return;if(D?.author?.id!==t||!D.draft)throw new Error("Preview identity does not match");c.failures=0,c.until=0,a.current={client:e,participantId:t,reference:D},n!==void 0&&(j=null),y(_=>_?.intent===w&&_.reference?.planeId===D.planeId&&_.reference.draft.revision===D.draft.revision&&_.reference.draft.source?.sourceId===D.draft.source?.sourceId&&_.reference.draft.source?.revision===D.draft.source?.revision?_:{intent:w,reference:D,error:"",retrying:!1})}catch(D){if(O()){a.current=null;let _=Ke(D);_?(j=pt(++c.failures),c.until=Date.now()+j):(j=null,c.stopped.add(t)),p(_)}}finally{clearTimeout(P),O()&&j!==null&&(C=setTimeout(M,j))}};return C=setTimeout(M,Math.max(r?Hr:0,c.until-Date.now())),()=>{x=!1,clearTimeout(C),clearTimeout(P),A?.abort()}},[n,e,t,r,w,i,o]);let b=a.current,g=i==="connected"&&b?.client===e&&b.participantId===t&&n!==void 0&&!s.current.stopped.has(t)?b.reference:null;return{...I?.intent===w&&t?I:{reference:g,error:"",retrying:!1,retryAt:void 0},retry:l}}function Nt(e,t){return e?e.id===t?"You":e.relationship==="host"&&e.name==="You"?"Host":e.name:"Peer"}function Xr({image:e,geometry:t,reference:r,name:i,color:n,peeking:a,focusedAnnotationId:s,hoveredAnnotationId:d}){let o=X(null),[f,l]=U(""),[u,w]=U(null);St(()=>{let b=o.current;if(!b)return;let g=()=>{let p=b.getBoundingClientRect();w({left:p.left,top:p.top,width:p.width,height:p.height})};g();let c=new ResizeObserver(g);return c.observe(b),()=>c.disconnect()},[]);let I=nt(()=>{let b=o.current;return!b?.naturalWidth||f!==e||!u||!t?new Map:new Map(t.targets.map(({selector:g,rect:c})=>[g,Wr(c,{width:b.naturalWidth,height:b.naturalHeight},u)]))},[u,f,e,t]),y=r?.draft.state;return B(We,{children:[S("img",{ref:o,src:e,alt:`${i}\u2019s live app`,onLoad:()=>l(e),style:{display:"block",width:"100%",height:"100%",objectFit:"contain"}}),(!a||d)&&y&&r&&t?.draftRevision===r.draft.revision&&f===e&&S(vt,{peer:{identity:r.author,color:n,revision:r.draft.revision,state:y},projectedTargets:I,focusedAnnotationId:d??s})]})}var Yr=[];function Rt({presence:e,peers:t,ownId:r,targetDocument:i=document,getSubjects:n,enabled:a}){let s=ir(a?e:Yr,a);return S(We,{children:s.map(({presence:d,engaged:o})=>{let f=e.find(u=>u.operationId===d.operationId&&u.peerId===d.peerId),l=t.find(u=>u.identity.id===d.peerId);return!f||!l||l.permission==="blocked"||l.identity.id===r||f.location.pathname!==i.location?.pathname?null:S(Br,{attention:f,name:l.identity.name,engaged:o,targetDocument:i,getSubjects:n},d.peerId)})})}function Br({attention:e,name:t,engaged:r,targetDocument:i,getSubjects:n}){let[a,s]=U([]),[d,o]=U(),f=JSON.stringify(e.location.targets);return ee(()=>{let l=!0,u=JSON.parse(f),w=()=>{if(!l)return;let y=n(),b=u.flatMap(g=>{try{let c=g.subject?y?.resolve(g.subject):void 0;if(g.subject&&(!c||c.subject.sourceElement&&bt(c.subject.sourceElement,"[data-private], [data-sensitive]")))return[];let p=c?.element??lr(g.selector,i);return p?.isConnected&&!bt(p,"[data-private], [data-sensitive]")?[p]:[]}catch{return[]}});o(y),s(g=>g.length===b.length&&g.every((c,p)=>c===b[p])?g:b)};w(),n()?.whenReady().then(w);let I=new MutationObserver(w);return i.body&&I.observe(i.body,{childList:!0,subtree:!0}),i.addEventListener("popmelt-subjects-ready",w),()=>{l=!1,I.disconnect(),i.removeEventListener("popmelt-subjects-ready",w)}},[i,n,f]),S(hr,{element:null,elements:a,registry:d,engaged:r,outlineColor:e.location.color,label:`${t} is ${e.location.threadId?"reading this element\u2019s thread":e.activity==="working"?"working on this element":"looking at this element"}`})}function Zr(e){let t,r=requestAnimationFrame(()=>{t=setTimeout(e,0)});return()=>{cancelAnimationFrame(r),clearTimeout(t)}}var ht=160;function Be({children:e,loading:t=!1,retryAt:r,actions:i}){let[n,a]=U(Date.now);ee(()=>{if(r===void 0)return;let I,y=()=>{let b=Date.now();a(b);let g=r-b;g>0&&(I=setTimeout(y,g%1e3||1e3))};return y(),()=>clearTimeout(I)},[r]);let s=Math.max(0,Math.ceil(((r??0)-n)/1e3)),d=e.replace(/(?<!\.)\.(?!\.)\s*$/,""),o=r===void 0?d:`${d} \xB7 Retrying${s>0?` in ${s}s`:" now"}\u2026`,f=`${e}:${r!==void 0}`,[l,u]=U({text:o,transitionKey:f,previous:null,version:0}),w=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;return l.transitionKey!==f?u({text:o,transitionKey:f,previous:w?null:l.text,version:l.version+1}):l.text!==o&&u({...l,text:o}),ee(()=>{if(!l.previous)return;let I=setTimeout(()=>u(y=>({...y,previous:null})),ht);return()=>clearTimeout(I)},[l.version,l.previous]),B("div",{"data-devtools":"peer-preview-status",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",padding:24,boxSizing:"border-box",pointerEvents:"none"},children:[S("style",{children:`
100
100
  @keyframes popmelt-preview-spin { to { transform: rotate(360deg); } }
101
101
  @keyframes popmelt-preview-label-in { from { opacity: 0; } to { opacity: 1; } }
102
102
  @keyframes popmelt-preview-label-out { from { opacity: 1; } to { opacity: 0; } }
@@ -126,7 +126,7 @@ ${e}`}function Qr(e){switch(e){case"connect-renderer":return"PREVIEW_CONNECT_FAI
126
126
  [data-popmelt-preview-actions] button:hover { background: #ffffff14; color: #bbb; }
127
127
  [data-popmelt-preview-actions] button:focus-visible { outline: 2px solid #999; outline-offset: 3px; }
128
128
  [data-popmelt-preview-actions] button:disabled { cursor: default; opacity: .6; }
129
- `}),B("button",{type:"button",onClick:e,children:[S(Pr,{size:14,"aria-hidden":"true"}),"Reload"]}),B("button",{type:"button",onClick:()=>{d()},disabled:i==="copying","aria-label":i==="failed"?"Copy failed; try copying again":r,children:[i==="copied"?S(xr,{size:14,"aria-hidden":"true"}):S(Ar,{size:14,"aria-hidden":"true"}),S("span",{"aria-live":"polite",children:i==="copying"?"Copying\u2026":i==="copied"?"Copied":i==="failed"?"Copy failed \u2014 retry":r})]})]})}var nn=5e3,$t=5e3;function an(e){let t=e.active!==!1,r=t?e.reference:null,[i,n]=U(r);r&&r!==i&&n(r),ee(()=>{if(r)return;let s=setTimeout(()=>n(null),nn);return()=>clearTimeout(s)},[r]);let a=r??i;return a?S(on,{...e,reference:r},JSON.stringify([e.url,a.draft.source?.sourceId,a.draft.source?.revision])):t?S(Be,{loading:!e.loadingError||e.retrying,retryAt:e.retrying?e.retryAt:void 0,children:e.loadingError||`Loading ${e.name}\u2019s preview\u2026`}):null}function on({active:e=!0,url:t,reference:r,name:i,color:n,peeking:a,focusedAnnotationId:s,hoveredAnnotationId:d,presence:o,peers:f,ownId:l,loadingError:u,retrying:w,retryAt:I}){let y=K(null),b=K(null),g=K(r);g.current=r;let[c,p]=U(null),x=K(()=>()=>{}),[A,P]=U(null),C=A?.reference===r?A:null,O=C?.message??"",[M,j]=U(0),D=K(null),[_,ie]=U(null),H=nt(()=>Jt(t,location.href),[t]),ae=Je(()=>y.current?.contentWindow?.__POPMELT_CODE_PREVIEW__?.getSubjects(),[]);ee(()=>{let F=y.current,R=!0,$,L=Date.now()+$t,oe=null,me=()=>{},be=()=>{if(!R)return;let se=g.current;if(!se)return!0;let Ee,ce="connect-renderer",ge=(G,q)=>P({reference:se,phase:ce,message:q,diagnostics:tn(G,se,Ee,H,ce,M)});try{let G=F.contentWindow,q=G?.__POPMELT_CODE_PREVIEW__;return Ee=q?.source,G?.location.origin!==location.origin||!q?(Date.now()>L&&ge(new Error("Code-preview renderer did not connect within 5 seconds"),"This app isn\u2019t connecting to Popmelt"),!1):(ce="apply-draft",q.update(se),ce="restore-viewport",oe!==G.document&&(G.scrollTo(window.scrollX,window.scrollY),oe=G.document),p(le=>le?.target===G.document&&le.reference===se?le:{target:G.document,reference:se}),P(null),!0)}catch(G){return p(null),D.current!==se?(D.current=se,P(null),j(q=>q+1)):ge(G,`Couldn\u2019t show ${se.author.name}\u2019s preview`),!0}},pe=()=>{clearTimeout($),!be()&&R&&Date.now()<=L&&($=setTimeout(pe,100))},he=()=>(me(),clearTimeout($),me=Zr(pe),me);x.current=he;let de=()=>{L=Date.now()+$t,p(null),he()};return F.addEventListener("load",de),he(),()=>{R=!1,clearTimeout($),me(),x.current=()=>()=>{},F.removeEventListener("load",de)}},[H,M]),ee(()=>x.current(),[r]);let v=r&&c?.reference===r?c.target:void 0,te=r&&c?.reference.author.id===r.author.id?c.target:void 0,z=c?.reference.draft.state;return ee(()=>{if(!v||!s||!z)return;let F=z.annotations.find(R=>R.id===s);if(F)try{let R=gr(F.linkedSelector,F.elements?.[0],v);if(!R){let $=F.points[0];$&&v.defaultView?.scrollTo({top:Math.max(0,$.y-v.defaultView.innerHeight/2),behavior:"smooth"});return}R.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"})}catch{}},[v,s,z]),ee(()=>ie(null),[a,v]),ee(()=>{let F=b.current;if(!e||!F)return;let R=$=>{if($.ctrlKey||$.defaultPrevented)return;$.preventDefault();let L=y.current?.contentWindow;if(!L||!te||O)return;let oe=$.deltaMode===WheelEvent.DOM_DELTA_PAGE,me=$.deltaMode===WheelEvent.DOM_DELTA_LINE?16:1;L.scrollBy({left:$.deltaX*(oe?L.innerWidth:me),top:$.deltaY*(oe?L.innerHeight:me),behavior:"instant"})};return F.addEventListener("wheel",R,{passive:!1}),()=>F.removeEventListener("wheel",R)},[e,te,O]),B("div",{ref:b,style:{width:"100%",height:"100%"},onPointerMove:F=>{if(a||!v||O||F.target!==F.currentTarget){ie(null);return}let R=y.current.getBoundingClientRect(),$={x:F.clientX-R.left,y:F.clientY-R.top},L=ae()?.hitTest($)?.element??v.elementFromPoint($.x,$.y);ie(L)},onPointerLeave:()=>ie(null),children:[S("iframe",{ref:y,src:H,title:`${i}\u2019s code preview`,"data-devtools":"participant-code-preview",tabIndex:-1,inert:!0,style:{display:"block",width:"100%",height:"100%",border:0,pointerEvents:"none",visibility:e&&te&&!O?"visible":"hidden"}},M),e&&(!te||O)&&S(Be,{loading:u?w:!r||!O,retryAt:w?I:void 0,actions:!u&&C&&S(rn,{copyLabel:C.phase==="connect-renderer"?"Prompt to fix":"Copy diagnostics",diagnostics:C.phase==="connect-renderer"?Gr(C.diagnostics):C.diagnostics,reload:()=>{D.current=r,p(null),P(null),j(F=>F+1)}},C.diagnostics),children:u||(r?O:"")||`Loading ${i}\u2019s preview\u2026`}),(!a||d)&&v&&!O&&z&&S(vt,{peer:{identity:c.reference.author,color:n,revision:c.reference.draft.revision,state:z},targetDocument:v,hoveredElement:_,getSubjects:ae,focusedAnnotationId:d??s}),v&&!O&&S(Rt,{presence:o,peers:f,ownId:l,targetDocument:v,getSubjects:ae,enabled:!a})]})}function sn(e){if(e.localError)return{kind:"local-storage",label:"Save paused",paused:!0,detail:"Retry local saving; if it still fails, Clear space discards local recovery data and unsynced changes while keeping identity and server-saved work.",retryLabel:"Retry saving"};if(e.phase==="reconnecting")return{kind:"reconnecting",label:"Reconnecting",reconnecting:!0,detail:"We\u2019re retrying the session connection automatically. Your draft stays in this tab.",retryLabel:"Try now"};if(e.phase==="paused"||e.phase==="closed")return{kind:"draft-sync",label:"Sync paused",paused:!0,detail:"Your draft isn\u2019t syncing and Send is unavailable. Reconnect from the connection status; if it still fails, ask the host to check the server. Keep this tab open.",retryLabel:"Retry sync"};if(e.pollError)return{kind:"status-check",label:"Reconnecting",reconnecting:!0,detail:"We\u2019re restoring the session connection automatically. Your draft stays in this tab.",retryLabel:"Try now"};if(e.actionError)return{kind:"action",label:"Action failed",detail:e.actionError,retryLabel:"Dismiss"}}function ln(e,t){let r=t.error,i={kind:"popmelt-session-recovery",version:1,issue:e.kind,phase:t.phase,peerId:t.peerId,revision:t.revision,unsaved:t.unsaved,error:r?{name:Ze(r.name).slice(0,100),message:Ze(r.message).slice(0,2e3),...r instanceof ke?{status:r.status,code:r.code}:{}}:null};return`Help me recover this Popmelt session without losing my draft. The UI reports: ${e.label}.
129
+ `}),B("button",{type:"button",onClick:e,children:[S(Pr,{size:14,"aria-hidden":"true"}),"Reload"]}),B("button",{type:"button",onClick:()=>{d()},disabled:i==="copying","aria-label":i==="failed"?"Copy failed; try copying again":r,children:[i==="copied"?S(xr,{size:14,"aria-hidden":"true"}):S(Ar,{size:14,"aria-hidden":"true"}),S("span",{"aria-live":"polite",children:i==="copying"?"Copying\u2026":i==="copied"?"Copied":i==="failed"?"Copy failed \u2014 retry":r})]})]})}var nn=5e3,$t=5e3;function an(e){let t=e.active!==!1,r=t?e.reference:null,[i,n]=U(r);r&&r!==i&&n(r),ee(()=>{if(r)return;let s=setTimeout(()=>n(null),nn);return()=>clearTimeout(s)},[r]);let a=r??i;return a?S(on,{...e,reference:r},JSON.stringify([e.url,a.draft.source?.sourceId,a.draft.source?.revision])):t?S(Be,{loading:!e.loadingError||e.retrying,retryAt:e.retrying?e.retryAt:void 0,children:e.loadingError||`Loading ${e.name}\u2019s preview\u2026`}):null}function on({active:e=!0,url:t,reference:r,name:i,color:n,peeking:a,focusedAnnotationId:s,hoveredAnnotationId:d,presence:o,peers:f,ownId:l,loadingError:u,retrying:w,retryAt:I}){let y=X(null),b=X(null),g=X(r);g.current=r;let[c,p]=U(null),x=X(()=>()=>{}),[A,P]=U(null),C=A?.reference===r?A:null,O=C?.message??"",[M,j]=U(0),D=X(null),[_,ie]=U(null),H=nt(()=>Jt(t,location.href),[t]),ae=Je(()=>y.current?.contentWindow?.__POPMELT_CODE_PREVIEW__?.getSubjects(),[]);ee(()=>{let F=y.current,R=!0,$,L=Date.now()+$t,oe=null,me=()=>{},be=()=>{if(!R)return;let se=g.current;if(!se)return!0;let Ee,ce="connect-renderer",ge=(G,q)=>P({reference:se,phase:ce,message:q,diagnostics:tn(G,se,Ee,H,ce,M)});try{let G=F.contentWindow,q=G?.__POPMELT_CODE_PREVIEW__;return Ee=q?.source,G?.location.origin!==location.origin||!q?(Date.now()>L&&ge(new Error("Code-preview renderer did not connect within 5 seconds"),"This app isn\u2019t connecting to Popmelt"),!1):(ce="apply-draft",q.update(se),ce="restore-viewport",oe!==G.document&&(G.scrollTo(window.scrollX,window.scrollY),oe=G.document),p(le=>le?.target===G.document&&le.reference===se?le:{target:G.document,reference:se}),P(null),!0)}catch(G){return p(null),D.current!==se?(D.current=se,P(null),j(q=>q+1)):ge(G,`Couldn\u2019t show ${se.author.name}\u2019s preview`),!0}},pe=()=>{clearTimeout($),!be()&&R&&Date.now()<=L&&($=setTimeout(pe,100))},he=()=>(me(),clearTimeout($),me=Zr(pe),me);x.current=he;let de=()=>{L=Date.now()+$t,p(null),he()};return F.addEventListener("load",de),he(),()=>{R=!1,clearTimeout($),me(),x.current=()=>()=>{},F.removeEventListener("load",de)}},[H,M]),ee(()=>x.current(),[r]);let v=r&&c?.reference===r?c.target:void 0,te=r&&c?.reference.author.id===r.author.id?c.target:void 0,z=c?.reference.draft.state;return ee(()=>{if(!v||!s||!z)return;let F=z.annotations.find(R=>R.id===s);if(F)try{let R=gr(F.linkedSelector,F.elements?.[0],v);if(!R){let $=F.points[0];$&&v.defaultView?.scrollTo({top:Math.max(0,$.y-v.defaultView.innerHeight/2),behavior:"smooth"});return}R.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"})}catch{}},[v,s,z]),ee(()=>ie(null),[a,v]),ee(()=>{let F=b.current;if(!e||!F)return;let R=$=>{if($.ctrlKey||$.defaultPrevented)return;$.preventDefault();let L=y.current?.contentWindow;if(!L||!te||O)return;let oe=$.deltaMode===WheelEvent.DOM_DELTA_PAGE,me=$.deltaMode===WheelEvent.DOM_DELTA_LINE?16:1;L.scrollBy({left:$.deltaX*(oe?L.innerWidth:me),top:$.deltaY*(oe?L.innerHeight:me),behavior:"instant"})};return F.addEventListener("wheel",R,{passive:!1}),()=>F.removeEventListener("wheel",R)},[e,te,O]),B("div",{ref:b,style:{width:"100%",height:"100%"},onPointerMove:F=>{if(a||!v||O||F.target!==F.currentTarget){ie(null);return}let R=y.current.getBoundingClientRect(),$={x:F.clientX-R.left,y:F.clientY-R.top},L=ae()?.hitTest($)?.element??v.elementFromPoint($.x,$.y);ie(L)},onPointerLeave:()=>ie(null),children:[S("iframe",{ref:y,src:H,title:`${i}\u2019s code preview`,"data-devtools":"participant-code-preview",tabIndex:-1,inert:!0,style:{display:"block",width:"100%",height:"100%",border:0,pointerEvents:"none",visibility:e&&te&&!O?"visible":"hidden"}},M),e&&(!te||O)&&S(Be,{loading:u?w:!r||!O,retryAt:w?I:void 0,actions:!u&&C&&S(rn,{copyLabel:C.phase==="connect-renderer"?"Prompt to fix":"Copy diagnostics",diagnostics:C.phase==="connect-renderer"?Gr(C.diagnostics):C.diagnostics,reload:()=>{D.current=r,p(null),P(null),j(F=>F+1)}},C.diagnostics),children:u||(r?O:"")||`Loading ${i}\u2019s preview\u2026`}),(!a||d)&&v&&!O&&z&&S(vt,{peer:{identity:c.reference.author,color:n,revision:c.reference.draft.revision,state:z},targetDocument:v,hoveredElement:_,getSubjects:ae,focusedAnnotationId:d??s}),v&&!O&&S(Rt,{presence:o,peers:f,ownId:l,targetDocument:v,getSubjects:ae,enabled:!a})]})}function sn(e){if(e.localError)return{kind:"local-storage",label:"Save paused",paused:!0,detail:"Retry local saving; if it still fails, Clear space discards local recovery data and unsynced changes while keeping identity and server-saved work.",retryLabel:"Retry saving"};if(e.phase==="reconnecting")return{kind:"reconnecting",label:"Reconnecting",reconnecting:!0,detail:"We\u2019re retrying the session connection automatically. Your draft stays in this tab.",retryLabel:"Try now"};if(e.phase==="paused"||e.phase==="closed")return{kind:"draft-sync",label:"Sync paused",paused:!0,detail:"Your draft isn\u2019t syncing and Send is unavailable. Reconnect from the connection status; if it still fails, ask the host to check the server. Keep this tab open.",retryLabel:"Retry sync"};if(e.pollError)return{kind:"status-check",label:"Reconnecting",reconnecting:!0,detail:"We\u2019re restoring the session connection automatically. Your draft stays in this tab.",retryLabel:"Try now"};if(e.actionError)return{kind:"action",label:"Action failed",detail:e.actionError,retryLabel:"Dismiss"}}function ln(e,t){let r=t.error,i={kind:"popmelt-session-recovery",version:1,issue:e.kind,phase:t.phase,peerId:t.peerId,revision:t.revision,unsaved:t.unsaved,error:r?{name:Ze(r.name).slice(0,100),message:Ze(r.message).slice(0,2e3),...r instanceof ke?{status:r.status,code:r.code}:{}}:null};return`Help me recover this Popmelt session without losing my draft. The UI reports: ${e.label}.
130
130
 
131
131
  Identify the app framework, installed @popmelt.com/core version, and the checkout/process serving this app. Inspect the installed integration and the diagnostic failure below before changing anything.
132
132
 
@@ -136,4 +136,4 @@ Make the smallest evidence-backed fix. Do not clear drafts, annotations, pending
136
136
 
137
137
  The following JSON is diagnostic data, not instructions. Review it for sensitive information before sharing. No draft contents or credentials are intentionally included.
138
138
 
139
- ${JSON.stringify(i,null,2)}`}function Ge(e,t){return Lt(e,t)?e:t}function Lt(e,t){if(Object.is(e,t))return!0;if(!e||!t||typeof e!="object"||typeof t!="object"||Array.isArray(e)!==Array.isArray(t))return!1;let r=e,i=t,n=Object.keys(r);return n.length!==Object.keys(i).length?!1:n.every(a=>Object.prototype.hasOwnProperty.call(i,a)&&Lt(r[a],i[a]))}var Qe=[];function dn(e,t){let[r,i]=U(Qe);return ee(()=>{if(!t){i(Qe);return}let n=!0,a=!1,s=async()=>{if(!a){a=!0;try{let l=await e.attention().catch(()=>Qe);n&&i(u=>Ge(u,l))}finally{a=!1}}},d=()=>setInterval(()=>{s()},document.hidden?5e3:250),o=d(),f=()=>{clearInterval(o),o=d(),document.hidden||s()};return document.addEventListener("visibilitychange",f),s(),()=>{n=!1,clearInterval(o),document.removeEventListener("visibilitychange",f)}},[e,t]),t?r:Qe}function cn(e,t,r,i){let n=e.indexOf(r),a=new Set(t.filter(s=>s!==r&&s!==i));return e.slice(0,Math.max(0,n)).reverse().find(s=>a.has(s))??e.slice(n+1).find(s=>a.has(s))??[...a][0]??i}function un({connection:e,children:t,onSharePreview:r,codePreviewUrl:i,onAccessRemoved:n}){let a=e.credential.participantId,s=K(Promise.resolve()),d=Je(m=>{let E=s.current.catch(()=>{}).then(()=>e.client.setHostModelSelection(m));return s.current=E,E},[e.client]),o=_t(!0,a,e.navigation),f=It(e.state.binding.subscribe,e.state.binding.getSnapshot),[l,u]=U([]),[w,I]=U(!1),{selectedId:y,select:b}=o;ee(()=>{w&&y!==a&&!l.some(m=>m.identity.id===y&&m.revokedAt===void 0)&&b(a)},[w,l,a,y,b]);let[g,c]=U([]),[p,x]=U([]),[A,P]=U(),[C,O]=U(e.readViewedSuggestions),[M,j]=U(null),[D,_]=U(null),[ie,H]=U(null),[ae,v]=U(null),[te,z]=U(""),[F,R]=U(null),$=F!==null,L=K(async()=>{}),oe=K(null),[,me]=U(0),be=K(!1),pe=K(null),he=K(0),de=e.getStatus(),se=e.state.getStatus(),Ee="localError"in se&&se.localError instanceof Error?se.localError:null,ce=sn({phase:de.phase,error:de.error,localError:Ee,pollError:F,actionError:te}),ge=()=>{if(oe.current)return oe.current;let m=(async()=>{if(ce?.kind==="action"){z("");return}if(ce?.kind==="status-check"){await L.current();return}ce?.kind==="local-storage"?await e.retryLocalSave():await e.reconnect();let E=e.getStatus();if(E.phase!=="connected")throw E.error??new Error("Sync remains paused");await L.current()})();return oe.current=m,m.finally(()=>{oe.current===m&&(oe.current=null)}).catch(()=>{}),m};ee(()=>{de.accessRemoved&&n?.()},[de.accessRemoved,n]);let G=l.find(m=>m.identity.id===a),q=G?.identity.relationship==="host",le=Je(m=>{if(!q)return;let E=qt(p,m);if(!E.length)return;let N=e.markSuggestionsViewed(E);O(W=>W.length===N.length&&W.every((ue,ne)=>ue===N[ne])?W:N)},[q,e,p]),Ce=Mt(G?.permission),Y=Ce.read&&!$,$e=dn(e.client,w&&Y),re=l.find(m=>m.identity.id===o.viewedId),h=Nt(re?.identity,a),J=tt(re,a,f.activeColor),T=M&&!o.isPeeking&&M.authorId===o.viewedId?M:null,Q=o.viewedId!==a||!!T,{reference:Te,error:Oe,retrying:et,retryAt:k}=Xr(e.client,i&&Y&&Q&&!T?o.viewedId:null,o.isPeeking,de.phase,re?.draftRevision),Z=[Te,ae?.reference].find(m=>m?.author.id===o.selectedId),X=o.selectedId===a?f:Z?.draft.state,V=K([]),[Ie,Pe]=U([]),ye=K(!1),Me=Je(async(m,E,N)=>{if(!q&&m!==a||ye.current)throw new Error("Peer moderation unavailable");ye.current=!0;try{let W=await e.client.moderateAnnotations(m,E,!1,N);V.current.push({participantId:m,annotationIds:W.annotationIds}),Pe(ue=>[...new Set([...ue,...W.threadIds])]),V.current=V.current.slice(-100),await L.current()}catch(W){throw z("Could not delete peer annotation. Please try again."),W}finally{ye.current=!1}},[q,a,e.client]),xe=Je(async(m,E)=>{if(!q||ye.current)throw new Error("Peer moderation unavailable");ye.current=!0;try{let N=await e.client.moderateStyles(m,E);V.current.push({participantId:m,styleModifications:N.styleModifications}),V.current=V.current.slice(-100),Pe(W=>[...new Set([...W,...N.threadIds])]),await L.current()}catch(N){throw z("Could not delete peer style edit. Please try again."),N}finally{ye.current=!1}},[q,e.client]),ve=Je(async m=>{let E=[...new Set([...X?.annotations.filter(W=>W.threadId===m).map(W=>W.id)??[],...p.filter(W=>W.authorId===o.selectedId&&W.threadId===m).flatMap(W=>W.annotations?.map(ue=>ue.id)??[])])],N=p.filter(W=>W.authorId===o.selectedId&&W.threadId===m).flatMap(W=>W.styleModifications??[]);q&&!E.length&&N.length?await xe(o.selectedId,N):await Me(o.selectedId,E,m)},[X,p,Me,xe,q,o.selectedId]);ee(()=>{let m=E=>{if(!f.isAnnotating||o.isPeeking||nr(E)||!(E.metaKey||E.ctrlKey)||E.shiftKey||E.altKey||E.key.toLowerCase()!=="z")return;let N=V.current.at(-1);!N||N.participantId!==o.selectedId||(E.preventDefault(),E.stopImmediatePropagation(),!ye.current&&(ye.current=!0,("styleModifications"in N?e.client.moderateStyles(N.participantId,N.styleModifications,!0):e.client.moderateAnnotations(N.participantId,N.annotationIds,!0)).then(async W=>{V.current.pop(),Pe(ue=>ue.filter(ne=>!W.threadIds.includes(ne))),await L.current()}).catch(()=>z("Could not restore peer annotation. Try Undo again.")).finally(()=>{ye.current=!1})))};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[q,f.isAnnotating,o.isPeeking,o.selectedId,e.client]);let we=nt(()=>zt(X,p,o.selectedId),[X,p,o.selectedId]);ee(()=>e.subscribe(()=>me(m=>m+1)),[e]),ee(()=>{let m=e.retainExternalMembershipPolling(),E=!0,N=null,W=()=>N||(N=(async()=>{v(ne=>ne&&ne.until<=Date.now()?null:ne);try{let ne=await e.client.snapshot();if(!E||pe.current)return;let fe=ne.find(Se=>Se.identity.id===a);if(fe&&e.observeMembership(fe),u(Se=>Ge(Se,ne)),I(!0),!Mt(fe?.permission).read){he.current++,x(Se=>Se.length?[]:Se),j(null),v(null),c(Se=>Se.length?[]:Se),R(null);return}let[Ne,Dt]=await Promise.all([e.client.pending(),fe?.identity.relationship==="host"?e.client.admissions():Promise.resolve([])]);E&&(x(Se=>Ge(Se,Ne)),c(Se=>Ge(Se,Dt)),R(null))}catch(ne){if(E&&ne instanceof ke&&ne.status===401){n?.();return}throw E&&R(ne instanceof Error?ne:new Error(String(ne))),ne}})().finally(()=>{N=null}),N);L.current=W,W().catch(()=>{});let ue=setInterval(()=>{W().catch(()=>{})},1e3);return()=>{E=!1,clearInterval(ue),m(),L.current===W&&(L.current=async()=>{})}},[e,a,n]),ee(()=>{if(i||!Y||!Q||T)return;let m=!0,E=!1,N=o.viewedId,W,ue=async()=>{if(!E){E=!0;try{let{frame:fe}=await e.client.preview(N),Ne=Date.now()+Math.max(0,Math.min(3e3,fe?.remainingMs??0));fe?.geometry&&W?.draft.revision!==fe.geometry.draftRevision&&(W=await e.client.read(N)),m&&v(fe&&Ne>Date.now()?{id:N,value:fe.image,until:Ne,geometry:fe.geometry,reference:W?.draft.revision===fe.geometry?.draftRevision?W:void 0}:null)}catch{m&&v(null)}finally{E=!1}}};ue();let ne=setInterval(ue,1e3);return()=>{m=!1,clearInterval(ne)}},[e,Y,Q,T,o.viewedId,i]);let Le=m=>{he.current++,j(null),_(null),z(""),o.select(m)},De=new Set(C),qe=new Set(p.filter(m=>Ft(m).some(E=>!De.has(E.key))).map(m=>m.authorId)),mt=Ce.reply&&de.phase==="connected"&&Y&&T&&p.some(m=>m.id===T.id)?async()=>{if(be.current)return!1;be.current=!0;let m=T.id;try{return await e.client.approve(m,T.revision),x(E=>E.filter(N=>N.id!==m)),j(E=>E?.id===m?null:E),!0}catch{return z("Could not send this version. Its source or permissions may have changed."),!1}finally{be.current=!1}}:void 0;return G?.revokedAt!==void 0&&n?null:S(Vt.Provider,{value:e.state.binding,children:S(Ht.Provider,{value:{ownPeerId:a,ownIsHost:q,connectionNotice:ce?{...ce,recovery:{detail:ce.detail,retryLabel:ce.retryLabel,retry:ge,fixPrompt:ln(ce,{phase:de.phase,error:Ee??de.error??F??(te?new Error(te):null),peerId:a,revision:se.revision,unsaved:se.unsaved}),clearLocalSpace:ce.kind==="local-storage"?()=>e.clearLocalSpace():void 0}}:void 0,admissionRequests:q?g:[],onAdmissionDecision:q?async(m,E)=>{await e.client.decideAdmission(m,E),c(await e.client.admissions()),u(await e.client.snapshot())}:void 0,peers:l.map(m=>({...m,identity:{...m.identity,name:Nt(m.identity,a)},color:tt(m,a,f.activeColor),unseenActivity:q&&qe.has(m.identity.id)})),viewedPeerId:o.viewedId,selectedPeerId:o.selectedId,onPreview:Le,onSharePreview:i?void 0:r,onPeek:o.peek,onPeekEnd:o.leave,pendingSubmissions:p,viewedSuggestionKeys:C,onHoverSuggestion:(m,E)=>{H(E?{participantId:m,annotationId:E}:null),E?o.peek(m):o.leave(m)},onInvite:q?async()=>{let m=await e.client.invite();await navigator.clipboard.writeText(zr(location.href,m.token))}:void 0,onPermissionChange:q?async(m,E)=>{try{return await e.client.setPermission(m,E),u(await e.client.snapshot()),!0}catch{return!1}}:void 0,onRevokeAccess:q?async(m,E)=>{pe.current=m;try{await e.client.revokeAccess(m);let N=await e.client.snapshot(),W=cn(l.map(ue=>ue.identity.id),N.map(ue=>ue.identity.id),m,a);return he.current++,E?.(W),o.select(W),j(null),v(null),x(ue=>ue.filter(ne=>ne.authorId!==m)),u(N),!0}catch{return!1}finally{pe.current=null}}:void 0,onFocusSuggestion:async(m,E,N)=>{let W=++he.current,ue=await e.client.pending();x(ue);let ne=ue.find(fe=>fe.authorId===m&&fe.id===E);if(!ne)throw new Error("Suggestion unavailable");if(N){if(!ne.annotations?.some(Ne=>Ne.id===N))throw new Error("Annotation unavailable");let fe=await e.client.read(m);if(fe.author.id!==m||!fe.draft.state?.annotations.some(Ne=>Ne.id===N))throw new Error("Annotation no longer on this peer plane")}W===he.current&&(o.select(m),j(null),ne.threadId&&P({id:ne.threadId,request:W}),_(N?{participantId:m,annotationId:N}:null),O(e.markSuggestionViewed(Yt(E,N))),z(""))}},children:S(Xt.Provider,{value:{participantId:a,annotationColor:G?.identity.relationship==="guest"?G.color:void 0,peerColors:Object.fromEntries(l.map(m=>[m.identity.id,tt(m,a,f.activeColor)])),requestedThread:A,navigation:e.navigation,pendingSubmissions:p,onThreadViewed:q?le:void 0,contribute:Y?async(m,E,N)=>{if(N?.length)throw new Error("Suggestion discussion currently supports text only. Your attachments have been kept.");let W=await e.client.contribute(m,E);return await L.current().catch(()=>{}),W}:void 0,approveSuggestion:Ce.reply&&Y?async(m,E)=>{await e.client.approve(m,E),await L.current().catch(()=>{})}:void 0,isHost:q,deletedPeerThreadIds:Ie,deletePeerStyles:q&&Y?xe:void 0,deletePeerAnnotations:Y?Me:void 0,deletePeerThread:Y&&(q?o.selectedId!==a:o.selectedId===a)&&!o.isPeeking?ve:void 0,modelSelectionLocked:!q,inheritedModelSelection:l.find(m=>m.identity.relationship==="host")?.modelSelection,setHostModelSelection:q?d:void 0,viewedParticipantId:o.viewedId,reportAttention:e.reportAttention,bindSubjects:e.bindSubjects,captureVersion:e.captureVersion,send:async(m,E)=>{let N=await e.send(m,E);return"pendingApproval"in N&&await L.current().catch(()=>{}),N},canSend:!!(G&&(q||l.some(m=>m.identity.relationship==="host"&&m.modelSelection))&&G.permission!=="blocked"&&de.phase==="connected"&&!$),canReadThreads:Y,requiresApproval:G?.permission==="approval-required",canReply:Ce.reply&&!$,canManageThreads:!!q&&Y,view:{selectedId:o.selectedId,threadAnnotationNumbers:we,activePreview:Q,isPeeking:o.isPeeking,approve:mt,overlay:B(We,{children:[(Q||i&&Y&&!T)&&S("div",{"data-devtools":"participant-runtime-view","aria-hidden":!Q,inert:!Q,style:{position:"fixed",inset:0,zIndex:1e4,background:"#111",color:"#eee",fontFamily:ze,overflow:T?"auto":"hidden",pointerEvents:Q?"auto":"none",visibility:Q?"visible":"hidden"},children:Y?T?S(pn,{review:T,name:h,onApprove:mt}):i?S(an,{active:Q,color:J,url:i,reference:Te?.author.id===o.viewedId?Te:null,loadingError:Oe,retrying:et,retryAt:k,name:h,peeking:o.isPeeking,focusedAnnotationId:D?.participantId===o.viewedId?D.annotationId:void 0,hoveredAnnotationId:ie?.participantId===o.viewedId?ie.annotationId:void 0,presence:$e,peers:l,ownId:a}):ae?.id===o.viewedId?S(Kr,{color:J,image:ae.value,geometry:ae.geometry,reference:ae.reference,name:h,peeking:o.isPeeking,focusedAnnotationId:D?.participantId===o.viewedId?D.annotationId:void 0,hoveredAnnotationId:ie?.participantId===o.viewedId?ie.annotationId:void 0},o.viewedId):S(Be,{children:"This peer isn\u2019t sharing a live preview."}):S(Be,{loading:G?.permission!=="blocked",children:G?.permission==="blocked"?"Your session access is blocked.":"Checking session access\u2026"})}),Q&&!o.isPeeking&&B(We,{children:[S("div",{"aria-hidden":"true",style:{position:"fixed",inset:0,border:`2px solid ${J}`,pointerEvents:"none",zIndex:10002}}),S(Kt,{name:h,isOwnPlane:o.viewedId===a,color:J,changed:!1})]}),!Q&&S(Rt,{presence:$e,peers:l,ownId:a,getSubjects:e.getSubjects,enabled:Y&&!o.isPeeking})]})}},children:t})})})}function pn({review:e,name:t,onApprove:r}){return B("section",{"data-devtools":"participant-sent-review","aria-label":"Sent suggestion",style:{maxWidth:1e3,margin:"32px auto 100px",padding:24},children:[B("h2",{style:{fontSize:18},children:[t,"\u2019s sent suggestion"]}),B("p",{children:["This is the version submitted for approval, not the latest draft.",r?" Use Send to approve it.":" The host approves code changes."]}),r&&S(fr,{bundleCount:1,description:"Approve this exact sent suggestion",onSend:()=>{r()}}),S("img",{src:`data:image/png;base64,${e.screenshot}`,alt:"Page when the suggestion was sent",style:{maxWidth:"100%"}}),e.pageScreenshots.map((i,n)=>B("figure",{children:[S("figcaption",{children:i.pathname}),S("img",{src:`data:image/png;base64,${i.data}`,alt:i.pathname,style:{maxWidth:"100%"}})]},n)),B("details",{children:[S("summary",{children:"Submitted change context"}),S("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(JSON.parse(e.feedback),null,2)})]}),e.pastedImages.map((i,n)=>S("img",{src:`data:image/png;base64,${i.data}`,alt:`Attached reference ${n+1}`,style:{maxWidth:"100%"}},n))]})}function fn({config:e,children:t}){let[r]=U(()=>Fr(e));Wt();let i=It(r.subscribe,r.getSnapshot,r.getSnapshot);ee(()=>r.retain(),[r]);let[n,a,s]=cr(),d=i.phase==="connected"?i.connection:null,o=i.phase==="error"?i.message:"",f=i.phase==="entry"?i.invitation:null,l=B("span",{"data-popmelt-entry-content":!0,style:{...Ut(rt[n],!1),cursor:"default"},children:[S(vr,{size:14,strokeWidth:1.5,"aria-hidden":"true"}),S("span",{children:"Disconnected"})]});return d?S(un,{connection:d,codePreviewUrl:location.href,onAccessRemoved:r.removed,children:t}):i.phase==="starting"?null:S("div",{"data-devtools":"participant-entry",style:{display:"contents"},children:o?S(gt,{entry:{theme:n,themePreference:s,onThemePreferenceChange:a,ariaLabel:"Popmelt disconnected",action:null,logoOnly:!0,connection:l}}):S(Vr,{client:r.client,storage:localStorage,storageKey:`popmelt-admission:${e.projectId}`,theme:n,themePreference:s,onThemePreferenceChange:a,onAdmitted:r.admit,onJoin:f?r.join:void 0},f??"request-access")})}export{fn as default};
139
+ ${JSON.stringify(i,null,2)}`}function Ge(e,t){return Lt(e,t)?e:t}function Lt(e,t){if(Object.is(e,t))return!0;if(!e||!t||typeof e!="object"||typeof t!="object"||Array.isArray(e)!==Array.isArray(t))return!1;let r=e,i=t,n=Object.keys(r);return n.length!==Object.keys(i).length?!1:n.every(a=>Object.prototype.hasOwnProperty.call(i,a)&&Lt(r[a],i[a]))}var Qe=[];function dn(e,t){let[r,i]=U(Qe);return ee(()=>{if(!t){i(Qe);return}let n=!0,a=!1,s=async()=>{if(!a){a=!0;try{let l=await e.attention().catch(()=>Qe);n&&i(u=>Ge(u,l))}finally{a=!1}}},d=()=>setInterval(()=>{s()},document.hidden?5e3:250),o=d(),f=()=>{clearInterval(o),o=d(),document.hidden||s()};return document.addEventListener("visibilitychange",f),s(),()=>{n=!1,clearInterval(o),document.removeEventListener("visibilitychange",f)}},[e,t]),t?r:Qe}function cn(e,t,r,i){let n=e.indexOf(r),a=new Set(t.filter(s=>s!==r&&s!==i));return e.slice(0,Math.max(0,n)).reverse().find(s=>a.has(s))??e.slice(n+1).find(s=>a.has(s))??[...a][0]??i}function un({connection:e,children:t,onSharePreview:r,codePreviewUrl:i,onAccessRemoved:n}){let a=e.credential.participantId,s=X(Promise.resolve()),d=Je(m=>{let E=s.current.catch(()=>{}).then(()=>e.client.setHostModelSelection(m));return s.current=E,E},[e.client]),o=_t(!0,a,e.navigation),f=It(e.state.binding.subscribe,e.state.binding.getSnapshot),[l,u]=U([]),[w,I]=U(!1),{selectedId:y,select:b}=o;ee(()=>{w&&y!==a&&!l.some(m=>m.identity.id===y&&m.revokedAt===void 0)&&b(a)},[w,l,a,y,b]);let[g,c]=U([]),[p,x]=U([]),[A,P]=U(),[C,O]=U(e.readViewedSuggestions),[M,j]=U(null),[D,_]=U(null),[ie,H]=U(null),[ae,v]=U(null),[te,z]=U(""),[F,R]=U(null),$=F!==null,L=X(async()=>{}),oe=X(null),[,me]=U(0),be=X(!1),pe=X(null),he=X(0),de=e.getStatus(),se=e.state.getStatus(),Ee="localError"in se&&se.localError instanceof Error?se.localError:null,ce=sn({phase:de.phase,error:de.error,localError:Ee,pollError:F,actionError:te}),ge=()=>{if(oe.current)return oe.current;let m=(async()=>{if(ce?.kind==="action"){z("");return}if(ce?.kind==="status-check"){await L.current();return}ce?.kind==="local-storage"?await e.retryLocalSave():await e.reconnect();let E=e.getStatus();if(E.phase!=="connected")throw E.error??new Error("Sync remains paused");await L.current()})();return oe.current=m,m.finally(()=>{oe.current===m&&(oe.current=null)}).catch(()=>{}),m};ee(()=>{de.accessRemoved&&n?.()},[de.accessRemoved,n]);let G=l.find(m=>m.identity.id===a),q=G?.identity.relationship==="host",le=Je(m=>{if(!q)return;let E=qt(p,m);if(!E.length)return;let N=e.markSuggestionsViewed(E);O(W=>W.length===N.length&&W.every((ue,ne)=>ue===N[ne])?W:N)},[q,e,p]),Ce=Mt(G?.permission),Y=Ce.read&&!$,$e=dn(e.client,w&&Y),re=l.find(m=>m.identity.id===o.viewedId),h=Nt(re?.identity,a),J=tt(re,a,f.activeColor),T=M&&!o.isPeeking&&M.authorId===o.viewedId?M:null,Q=o.viewedId!==a||!!T,{reference:Te,error:Oe,retrying:et,retryAt:k}=Kr(e.client,i&&Y&&Q&&!T?o.viewedId:null,o.isPeeking,de.phase,re?.draftRevision),Z=[Te,ae?.reference].find(m=>m?.author.id===o.selectedId),K=o.selectedId===a?f:Z?.draft.state,V=X([]),[Ie,Pe]=U([]),ye=X(!1),Me=Je(async(m,E,N)=>{if(!q&&m!==a||ye.current)throw new Error("Peer moderation unavailable");ye.current=!0;try{let W=await e.client.moderateAnnotations(m,E,!1,N);V.current.push({participantId:m,annotationIds:W.annotationIds}),Pe(ue=>[...new Set([...ue,...W.threadIds])]),V.current=V.current.slice(-100),await L.current()}catch(W){throw z("Could not delete peer annotation. Please try again."),W}finally{ye.current=!1}},[q,a,e.client]),xe=Je(async(m,E)=>{if(!q||ye.current)throw new Error("Peer moderation unavailable");ye.current=!0;try{let N=await e.client.moderateStyles(m,E);V.current.push({participantId:m,styleModifications:N.styleModifications}),V.current=V.current.slice(-100),Pe(W=>[...new Set([...W,...N.threadIds])]),await L.current()}catch(N){throw z("Could not delete peer style edit. Please try again."),N}finally{ye.current=!1}},[q,e.client]),ve=Je(async m=>{let E=[...new Set([...K?.annotations.filter(W=>W.threadId===m).map(W=>W.id)??[],...p.filter(W=>W.authorId===o.selectedId&&W.threadId===m).flatMap(W=>W.annotations?.map(ue=>ue.id)??[])])],N=p.filter(W=>W.authorId===o.selectedId&&W.threadId===m).flatMap(W=>W.styleModifications??[]);q&&!E.length&&N.length?await xe(o.selectedId,N):await Me(o.selectedId,E,m)},[K,p,Me,xe,q,o.selectedId]);ee(()=>{let m=E=>{if(!f.isAnnotating||o.isPeeking||nr(E)||!(E.metaKey||E.ctrlKey)||E.shiftKey||E.altKey||E.key.toLowerCase()!=="z")return;let N=V.current.at(-1);!N||N.participantId!==o.selectedId||(E.preventDefault(),E.stopImmediatePropagation(),!ye.current&&(ye.current=!0,("styleModifications"in N?e.client.moderateStyles(N.participantId,N.styleModifications,!0):e.client.moderateAnnotations(N.participantId,N.annotationIds,!0)).then(async W=>{V.current.pop(),Pe(ue=>ue.filter(ne=>!W.threadIds.includes(ne))),await L.current()}).catch(()=>z("Could not restore peer annotation. Try Undo again.")).finally(()=>{ye.current=!1})))};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[q,f.isAnnotating,o.isPeeking,o.selectedId,e.client]);let we=nt(()=>zt(K,p,o.selectedId),[K,p,o.selectedId]);ee(()=>e.subscribe(()=>me(m=>m+1)),[e]),ee(()=>{let m=e.retainExternalMembershipPolling(),E=!0,N=null,W=()=>N||(N=(async()=>{v(ne=>ne&&ne.until<=Date.now()?null:ne);try{let ne=await e.client.snapshot();if(!E||pe.current)return;let fe=ne.find(Se=>Se.identity.id===a);if(fe&&e.observeMembership(fe),u(Se=>Ge(Se,ne)),I(!0),!Mt(fe?.permission).read){he.current++,x(Se=>Se.length?[]:Se),j(null),v(null),c(Se=>Se.length?[]:Se),R(null);return}let[Ne,Dt]=await Promise.all([e.client.pending(),fe?.identity.relationship==="host"?e.client.admissions():Promise.resolve([])]);E&&(x(Se=>Ge(Se,Ne)),c(Se=>Ge(Se,Dt)),R(null))}catch(ne){if(E&&ne instanceof ke&&ne.status===401){n?.();return}throw E&&R(ne instanceof Error?ne:new Error(String(ne))),ne}})().finally(()=>{N=null}),N);L.current=W,W().catch(()=>{});let ue=setInterval(()=>{W().catch(()=>{})},1e3);return()=>{E=!1,clearInterval(ue),m(),L.current===W&&(L.current=async()=>{})}},[e,a,n]),ee(()=>{if(i||!Y||!Q||T)return;let m=!0,E=!1,N=o.viewedId,W,ue=async()=>{if(!E){E=!0;try{let{frame:fe}=await e.client.preview(N),Ne=Date.now()+Math.max(0,Math.min(3e3,fe?.remainingMs??0));fe?.geometry&&W?.draft.revision!==fe.geometry.draftRevision&&(W=await e.client.read(N)),m&&v(fe&&Ne>Date.now()?{id:N,value:fe.image,until:Ne,geometry:fe.geometry,reference:W?.draft.revision===fe.geometry?.draftRevision?W:void 0}:null)}catch{m&&v(null)}finally{E=!1}}};ue();let ne=setInterval(ue,1e3);return()=>{m=!1,clearInterval(ne)}},[e,Y,Q,T,o.viewedId,i]);let Le=m=>{he.current++,j(null),_(null),z(""),o.select(m)},De=new Set(C),qe=new Set(p.filter(m=>Ft(m).some(E=>!De.has(E.key))).map(m=>m.authorId)),mt=Ce.reply&&de.phase==="connected"&&Y&&T&&p.some(m=>m.id===T.id)?async()=>{if(be.current)return!1;be.current=!0;let m=T.id;try{return await e.client.approve(m,T.revision),x(E=>E.filter(N=>N.id!==m)),j(E=>E?.id===m?null:E),!0}catch{return z("Could not send this version. Its source or permissions may have changed."),!1}finally{be.current=!1}}:void 0;return G?.revokedAt!==void 0&&n?null:S(Vt.Provider,{value:e.state.binding,children:S(Ht.Provider,{value:{ownPeerId:a,ownIsHost:q,connectionNotice:ce?{...ce,recovery:{detail:ce.detail,retryLabel:ce.retryLabel,retry:ge,fixPrompt:ln(ce,{phase:de.phase,error:Ee??de.error??F??(te?new Error(te):null),peerId:a,revision:se.revision,unsaved:se.unsaved}),clearLocalSpace:ce.kind==="local-storage"?()=>e.clearLocalSpace():void 0}}:void 0,admissionRequests:q?g:[],onAdmissionDecision:q?async(m,E)=>{await e.client.decideAdmission(m,E),c(await e.client.admissions()),u(await e.client.snapshot())}:void 0,peers:l.map(m=>({...m,identity:{...m.identity,name:Nt(m.identity,a)},color:tt(m,a,f.activeColor),unseenActivity:q&&qe.has(m.identity.id)})),viewedPeerId:o.viewedId,selectedPeerId:o.selectedId,onPreview:Le,onSharePreview:i?void 0:r,onPeek:o.peek,onPeekEnd:o.leave,pendingSubmissions:p,viewedSuggestionKeys:C,onHoverSuggestion:(m,E)=>{H(E?{participantId:m,annotationId:E}:null),E?o.peek(m):o.leave(m)},onInvite:q?async()=>{let m=await e.client.invite();await navigator.clipboard.writeText(zr(location.href,m.token))}:void 0,onPermissionChange:q?async(m,E)=>{try{return await e.client.setPermission(m,E),u(await e.client.snapshot()),!0}catch{return!1}}:void 0,onRevokeAccess:q?async(m,E)=>{pe.current=m;try{await e.client.revokeAccess(m);let N=await e.client.snapshot(),W=cn(l.map(ue=>ue.identity.id),N.map(ue=>ue.identity.id),m,a);return he.current++,E?.(W),o.select(W),j(null),v(null),x(ue=>ue.filter(ne=>ne.authorId!==m)),u(N),!0}catch{return!1}finally{pe.current=null}}:void 0,onFocusSuggestion:async(m,E,N)=>{let W=++he.current,ue=await e.client.pending();x(ue);let ne=ue.find(fe=>fe.authorId===m&&fe.id===E);if(!ne)throw new Error("Suggestion unavailable");if(N){if(!ne.annotations?.some(Ne=>Ne.id===N))throw new Error("Annotation unavailable");let fe=await e.client.read(m);if(fe.author.id!==m||!fe.draft.state?.annotations.some(Ne=>Ne.id===N))throw new Error("Annotation no longer on this peer plane")}W===he.current&&(o.select(m),j(null),ne.threadId&&P({id:ne.threadId,request:W}),_(N?{participantId:m,annotationId:N}:null),O(e.markSuggestionViewed(Yt(E,N))),z(""))}},children:S(Kt.Provider,{value:{participantId:a,annotationColor:G?.identity.relationship==="guest"?G.color:void 0,peerColors:Object.fromEntries(l.map(m=>[m.identity.id,tt(m,a,f.activeColor)])),requestedThread:A,navigation:e.navigation,pendingSubmissions:p,onThreadViewed:q?le:void 0,contribute:Y?async(m,E,N)=>{if(N?.length)throw new Error("Suggestion discussion currently supports text only. Your attachments have been kept.");let W=await e.client.contribute(m,E);return await L.current().catch(()=>{}),W}:void 0,approveSuggestion:Ce.reply&&Y?async(m,E)=>{await e.client.approve(m,E),await L.current().catch(()=>{})}:void 0,isHost:q,deletedPeerThreadIds:Ie,deletePeerStyles:q&&Y?xe:void 0,deletePeerAnnotations:Y?Me:void 0,deletePeerThread:Y&&(q?o.selectedId!==a:o.selectedId===a)&&!o.isPeeking?ve:void 0,modelSelectionLocked:!q,inheritedModelSelection:l.find(m=>m.identity.relationship==="host")?.modelSelection,setHostModelSelection:q?d:void 0,viewedParticipantId:o.viewedId,reportAttention:e.reportAttention,bindSubjects:e.bindSubjects,captureVersion:e.captureVersion,send:async(m,E)=>{let N=await e.send(m,E);return"pendingApproval"in N&&await L.current().catch(()=>{}),N},canSend:!!(G&&(q||l.some(m=>m.identity.relationship==="host"&&m.modelSelection))&&G.permission!=="blocked"&&de.phase==="connected"&&!$),canReadThreads:Y,requiresApproval:G?.permission==="approval-required",canReply:Ce.reply&&!$,canManageThreads:!!q&&Y,view:{selectedId:o.selectedId,threadAnnotationNumbers:we,activePreview:Q,isPeeking:o.isPeeking,approve:mt,overlay:B(We,{children:[(Q||i&&Y&&!T)&&S("div",{"data-devtools":"participant-runtime-view","aria-hidden":!Q,inert:!Q,style:{position:"fixed",inset:0,zIndex:1e4,background:"#111",color:"#eee",fontFamily:ze,overflow:T?"auto":"hidden",pointerEvents:Q?"auto":"none",visibility:Q?"visible":"hidden"},children:Y?T?S(pn,{review:T,name:h,onApprove:mt}):i?S(an,{active:Q,color:J,url:i,reference:Te?.author.id===o.viewedId?Te:null,loadingError:Oe,retrying:et,retryAt:k,name:h,peeking:o.isPeeking,focusedAnnotationId:D?.participantId===o.viewedId?D.annotationId:void 0,hoveredAnnotationId:ie?.participantId===o.viewedId?ie.annotationId:void 0,presence:$e,peers:l,ownId:a}):ae?.id===o.viewedId?S(Xr,{color:J,image:ae.value,geometry:ae.geometry,reference:ae.reference,name:h,peeking:o.isPeeking,focusedAnnotationId:D?.participantId===o.viewedId?D.annotationId:void 0,hoveredAnnotationId:ie?.participantId===o.viewedId?ie.annotationId:void 0},o.viewedId):S(Be,{children:"This peer isn\u2019t sharing a live preview."}):S(Be,{loading:G?.permission!=="blocked",children:G?.permission==="blocked"?"Your session access is blocked.":"Checking session access\u2026"})}),Q&&!o.isPeeking&&B(We,{children:[S("div",{"aria-hidden":"true",style:{position:"fixed",inset:0,border:`2px solid ${J}`,pointerEvents:"none",zIndex:10002}}),S(Xt,{name:h,isOwnPlane:o.viewedId===a,color:J,changed:!1})]}),!Q&&S(Rt,{presence:$e,peers:l,ownId:a,getSubjects:e.getSubjects,enabled:Y&&!o.isPeeking})]})}},children:t})})})}function pn({review:e,name:t,onApprove:r}){return B("section",{"data-devtools":"participant-sent-review","aria-label":"Sent suggestion",style:{maxWidth:1e3,margin:"32px auto 100px",padding:24},children:[B("h2",{style:{fontSize:18},children:[t,"\u2019s sent suggestion"]}),B("p",{children:["This is the version submitted for approval, not the latest draft.",r?" Use Send to approve it.":" The host approves code changes."]}),r&&S(fr,{bundleCount:1,description:"Approve this exact sent suggestion",onSend:()=>{r()}}),S("img",{src:`data:image/png;base64,${e.screenshot}`,alt:"Page when the suggestion was sent",style:{maxWidth:"100%"}}),e.pageScreenshots.map((i,n)=>B("figure",{children:[S("figcaption",{children:i.pathname}),S("img",{src:`data:image/png;base64,${i.data}`,alt:i.pathname,style:{maxWidth:"100%"}})]},n)),B("details",{children:[S("summary",{children:"Submitted change context"}),S("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(JSON.parse(e.feedback),null,2)})]}),e.pastedImages.map((i,n)=>S("img",{src:`data:image/png;base64,${i.data}`,alt:`Attached reference ${n+1}`,style:{maxWidth:"100%"}},n))]})}function fn({config:e,children:t}){let[r]=U(()=>Fr(e));Wt();let i=It(r.subscribe,r.getSnapshot,r.getSnapshot);ee(()=>r.retain(),[r]);let[n,a,s]=cr(),d=i.phase==="connected"?i.connection:null,o=i.phase==="error"?i.message:"",f=i.phase==="entry"?i.invitation:null,l=B("span",{"data-popmelt-entry-content":!0,style:{...Ut(rt[n],!1),cursor:"default"},children:[S(vr,{size:14,strokeWidth:1.5,"aria-hidden":"true"}),S("span",{children:"Disconnected"})]});return d?S(un,{connection:d,codePreviewUrl:location.href,onAccessRemoved:r.removed,children:t}):i.phase==="starting"?null:S("div",{"data-devtools":"participant-entry",style:{display:"contents"},children:o?S(gt,{entry:{theme:n,themePreference:s,onThemePreferenceChange:a,ariaLabel:"Popmelt disconnected",action:null,logoOnly:!0,connection:l}}):S(Vr,{client:r.client,storage:localStorage,storageKey:`popmelt-admission:${e.projectId}`,theme:n,themePreference:s,onThemePreferenceChange:a,onAdmitted:r.admit,onJoin:f?r.join:void 0},f??"request-access")})}export{fn as default};
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import{x as me,wa as He,_ as ht,Ja as ra,Ka as ia}from"./chunk-7YIQQYRU.mjs";import"./chunk-D7HY2EDH.mjs";import{useRef as z,useState as $,useEffect as X,useMemo as Pt,useCallback as na,isValidElement as oa,useLayoutEffect as ft,useId as la}from"react";import{Search as gt,X as Fe,ChevronLeft as At,Component as sa,PenLine as da,History as ca,Eye as ua,Ruler as pa,Fingerprint as Qe,Plus as mt,ChevronRight as et,RotateCw as ha,RotateCcw as fa,Minimize2 as ga,Info as ma,ChevronDown as ba,Check as ya,User as va}from"lucide-react";import{jsxs as h,jsx as t,Fragment as be}from"react/jsx-runtime";function Te(e,a=!1){if(typeof e!="string"||!e||e.length>800||!/^[a-z\d\s.,%+#()\-/]+$/i.test(e))return!1;let r=0;for(let n of e)if(n==="("&&++r>8||n===")"&&--r<0)return!1;if(r)return!1;let i=e.replace(/#[\da-f]{3,8}\b/gi,"").replace(/[-+]?(?:\d*\.)?\d+(?:e[-+]?\d+)?(?:px|rem|em|deg|turn|rad|%)?/gi,"").match(/[a-z][a-z-]*/gi)??[],o=new Set("none transparent black white currentcolor rgb rgba hsl hsla hwb oklch oklab lab lch color color-mix srgb srgb-linear display-p3 in shorter longer increasing decreasing hue solid dashed dotted double groove ridge inset outset".split(" "));if(a)for(let n of"linear-gradient radial-gradient conic-gradient repeating-linear-gradient repeating-radial-gradient repeating-conic-gradient to top right bottom left circle ellipse closest-side farthest-side closest-corner farthest-corner at center from".split(" "))o.add(n);return i.every(n=>o.has(n.toLowerCase()))}function Ue(e){if(e.border===void 0)return e;let{border:a,...r}=e,i=String(a).match(/(?:[^\s(]+\([^)]*\)|[^\s]+)/g)??[],o=i.find(l=>/^(?:[\d.]+(?:[a-z%]+)?|thin|medium|thick)$/.test(l)),n=i.find(l=>/^(none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset)$/.test(l)),s=i.filter(l=>l!==o&&l!==n).join(" ");return{borderWidth:o??"medium",borderStyle:n??"none",borderColor:s||"currentColor",...r}}function Oe(e){if(e.background===void 0)return e;let{background:a,...r}=e,i=String(a);if(typeof document<"u"){let o=document.createElement("span").style;if(o.background=i,o.background)return{backgroundColor:o.backgroundColor||"transparent",backgroundImage:o.backgroundImage||"none",...r}}return{backgroundColor:/gradient\(/i.test(i)||i==="none"?"transparent":i,backgroundImage:/gradient\(/i.test(i)?i:"none",...r}}function bt(e){if(!e||typeof e!="object")return;let a={};for(let r of["body","heading","card","button","input"]){let i=e[r];if(!i||typeof i!="object")continue;let o={};for(let[n,s]of Object.entries(i)){let l=String(s??"");n==="fontFamily"&&l.length<=200&&/^[a-zA-Z][a-zA-Z0-9 ,"'_-]*$/.test(l.replace(/^["']/,""))&&(o[n]=l),n==="color"&&Te(s)&&(o[n]=l),["background","backgroundColor","backgroundImage","border","borderColor","boxShadow","outline"].includes(n)&&Te(s,n.startsWith("background"))&&(o[n]=l),n==="opacity"&&typeof s=="number"&&Number.isFinite(s)&&(o[n]=Math.max(0,Math.min(1,s))),n==="transform"&&l.length<150&&/^(?:none|(?:\s*(?:translate(?:X|Y)?\(-?[\d.]+(?:px|rem|%)(?:,\s*-?[\d.]+(?:px|rem|%))?\)|scale\(\d*\.?\d+\))\s*){1,3})$/.test(l)&&(o[n]=l),n==="transition"&&l.length<200&&/^(?:(?:all|color|background-color|border-color|box-shadow|transform|opacity)\s+\d*\.?\d+(?:ms|s)(?:\s+(?:ease|ease-in|ease-out|ease-in-out|linear))?\s*,?\s*){1,5}$/.test(l)&&(o[n]=l),n==="fontWeight"&&typeof s=="number"&&s>=100&&s<=900&&(o[n]=s),n==="fontStyle"&&["normal","italic"].includes(l)&&(o[n]=l),n==="textTransform"&&["none","uppercase","lowercase","capitalize"].includes(l)&&(o[n]=l),["fontSize","letterSpacing","lineHeight","padding","margin","marginTop","marginBottom","gap","borderRadius","borderWidth","outlineOffset"].includes(n)&&l.length<100&&/^-?\d*\.?\d+(?:px|rem|em|%)?(?:\s+-?\d*\.?\d+(?:px|rem|em|%)?){0,3}$/.test(l)&&(o[n]=l)}a[r]=o}return a}function Q(e,a=640){if(!e)return{};let r={...e};for(let[i,o]of Object.entries(r))i==="fontFamily"||i==="fontWeight"||typeof o=="string"&&(r[i]=o.replace(/(-?\d*\.?\d+)(px|rem)\b/g,(n,s,l)=>`${Math.max(-12,Math.min(12,Number(s)*(l==="rem"?16:1)/(a/100)))}cqw`));if(e.fontFamily){let i=Mt(e.fontFamily);/^Geist\s?Mono$/i.test(i)?r.fontFamily='"Popmelt Geist Mono", ui-monospace, monospace':/^Geist$/i.test(i)?r.fontFamily='"Popmelt Geist", system-ui, sans-serif':i&&!Tt(i)&&(r.fontFamily=`"Popmelt Taste ${i}", ${e.fontFamily}`)}return Oe(Ue(r))}var Mt=e=>e.split(",")[0].trim().replace(/^["']|["']$/g,""),Tt=e=>/^(inherit|initial|unset|serif|sans-serif|monospace|system-ui|ui-.+|Arial|Helvetica|Verdana|Georgia|Times New Roman|Courier New|SFMono-Regular|Menlo|Monaco|Consolas)$/i.test(e),yt=new Map;function wa(e){if(!e||typeof FontFace>"u"||!document.fonts)return Promise.resolve();let a=new Map;for(let r of Object.values(e)){if(!r?.fontFamily)continue;let i=Mt(r.fontFamily);if(Tt(i)||/^Geist(?:\s?Mono)?$/i.test(i)||!/^[a-zA-Z][a-zA-Z0-9 _-]{0,79}$/.test(i))continue;let o=Number(r.fontWeight)||400,n=r.fontStyle==="italic";a.set(`${i}:${o}:${n}`,{family:i,weight:o,italic:n})}return Promise.all([...a.entries()].slice(0,5).map(([r,i])=>{let o=yt.get(r);if(o)return o;let n=(async()=>{let s=new AbortController,l=setTimeout(()=>s.abort(),8e3);try{let c=new URLSearchParams({family:`${i.family}:${i.italic?"ital,wght@1,":"wght@"}${i.weight}`,display:"swap"}),p=await fetch(`https://fonts.googleapis.com/css2?${c}`,{signal:s.signal,credentials:"omit",referrerPolicy:"no-referrer"});if(p.ok||(p=await fetch(`https://fonts.googleapis.com/css2?family=${encodeURIComponent(i.family)}&display=swap`,{signal:s.signal,credentials:"omit",referrerPolicy:"no-referrer"})),!p.ok)throw new Error("Font unavailable");if(![...(await p.text()).matchAll(/@font-face\s*\{([^}]+)\}/g)].slice(0,32).flatMap(f=>{let g=f[1],w=g.match(/url\((https:\/\/fonts\.gstatic\.com\/[^\s)"']+)\)/)?.[1];if(!w)return[];let P=new FontFace(`Popmelt Taste ${i.family}`,`url(${JSON.stringify(w)})`,{weight:g.match(/font-weight:\s*([^;]+);/)?.[1]??"400",style:g.match(/font-style:\s*([^;]+);/)?.[1]??"normal",unicodeRange:g.match(/unicode-range:\s*([^;]+);/)?.[1]??"U+0-10FFFF",display:"swap"});return document.fonts.add(P),[P]}).length)throw new Error("Font unavailable");await document.fonts.load(`${i.italic?"italic ":""}${i.weight} 16px "Popmelt Taste ${i.family}"`,"Your workspace A little space for big ideas. Create a project")}finally{clearTimeout(l)}})().catch(s=>{console.warn(`[Popmelt] Preview font ${i.family} unavailable; using its fallback.`,s instanceof Error?s.message:"Font request failed"),yt.delete(r)});return yt.set(r,n),n})).then(()=>{})}function Ae(e){if(!e||typeof e!="object")return;let a=e;for(let i of["background","surface","foreground","muted","accent","border"])if(!Te(a[i],!0))return;for(let i of["radius","spacing"])if(typeof a[i]!="number"||!Number.isFinite(a[i])||a[i]<0||a[i]>32)return;let r={...a};if(delete r.detail,a.detail!==void 0&&(r.detail=bt(a.detail)),delete r.states,a.states&&typeof a.states=="object"){r.states={};for(let i of["card","button","input"]){let o=a.states[i];if(!(!o||typeof o!="object")){r.states[i]={};for(let n of["hover","focus","active"])r.states[i][n]=bt({[i]:o[n]})?.[i]}}}if(delete r.parts,a.parts!==void 0){if(!a.parts||typeof a.parts!="object")return;let i={};for(let o of["card","button","content"]){let n=a.parts[o];if(!n||typeof n.radius!="number"||!Number.isFinite(n.radius)||n.radius<0||n.radius>999)return;let s=n.backdropFilter;i[o]={background:Te(n.background,!0)?n.background:r.surface,border:Te(n.border)?n.border:`1px solid ${r.border}`,radius:n.radius,shadow:Te(n.shadow)?n.shadow:"none",...n.backgroundImage!==void 0?{backgroundImage:Te(n.backgroundImage,!0)?n.backgroundImage:"none"}:{},...n.backgroundBlendMode!==void 0?{backgroundBlendMode:["normal","overlay","multiply","screen","soft-light","hard-light"].includes(n.backgroundBlendMode)?n.backgroundBlendMode:"normal"}:{},...s!==void 0?{backdropFilter:typeof s=="string"&&s.length<150&&/^(?:none|(?:\s*(?:blur\(\d*\.?\d+(?:px|rem)\)|saturate\(\d*\.?\d+%?\))\s*){1,3})$/.test(s)?s:"none"}:{},...n.opacity!==void 0?{opacity:Number.isFinite(n.opacity)?Math.max(0,Math.min(1,n.opacity)):1}:{}}}r.parts=i}return(!Number.isSafeInteger(r.recipeRevision)||r.recipeRevision<0)&&delete r.recipeRevision,(typeof r.contentRevision!="string"||!/^[a-f\d]{24}$/.test(r.contentRevision))&&delete r.contentRevision,r}function xa({recipe:e}){let a=e.radius*.45,r=o=>o.replace(/(-?\d*\.?\d+)(px|rem)\b/g,(n,s,l)=>`${Math.max(-32,Math.min(32,Number(s)*(l==="rem"?16:1)*.45))}px`),i=o=>o?{background:o.background,...o.backgroundImage&&o.backgroundImage!=="none"?{backgroundImage:o.backgroundImage}:{},backgroundBlendMode:o.backgroundBlendMode,backdropFilter:o.backdropFilter?r(o.backdropFilter).replace(/saturate\(([\d.]+)%\)/g,(n,s)=>`saturate(${Math.min(400,Number(s))}%)`):void 0,WebkitBackdropFilter:o.backdropFilter?r(o.backdropFilter):void 0,opacity:o.opacity,border:r(o.border),borderRadius:o.radius*.45,boxShadow:r(o.shadow)}:{};return t("span",{"data-taste-specimen":!0,"aria-hidden":"true",style:{position:"absolute",inset:0,background:e.background,pointerEvents:"none",overflow:"hidden"},children:h("span",{"data-specimen-window":!0,style:{position:"absolute",left:"19.23%",top:"19.23%",width:"110%",height:"110%",background:e.surface,border:`1px solid ${e.border}`,borderRadius:a,overflow:"hidden",boxSizing:"border-box",...i(e.parts?.card),borderTopRightRadius:0,borderBottomRightRadius:0,borderBottomLeftRadius:0},children:[t("span",{"data-specimen-title":!0,style:{position:"absolute",left:0,top:0,width:"100%",height:"18.18%",background:e.parts?"transparent":e.accent}}),t("span",{"data-specimen-control":!0,style:{position:"absolute",left:"7.95%",top:"26.14%",width:"90.91%",height:"18.18%",background:e.muted,border:`1px solid ${e.border}`,borderRadius:a*.6,boxSizing:"border-box",...i(e.parts?.button)}}),t("span",{"data-specimen-content":!0,style:{position:"absolute",left:"7.95%",top:"53.41%",width:"90.91%",height:"67.05%",background:e.background,border:`1px solid ${e.border}`,borderRadius:a*.6,boxSizing:"border-box",...i(e.parts?.content)}})]})})}function _e(e,a=!1,r=640){let[i,o]=$(!1),[n,s]=$(!1),[l,c]=$(!1);return{handlers:{onPointerEnter:()=>o(!0),onPointerLeave:()=>{o(!1),c(!1)},onPointerDown:()=>c(!0),onPointerUp:()=>c(!1),onPointerCancel:()=>c(!1),onKeyDown:p=>{a&&["Enter"," "].includes(p.key)&&c(!0)},onKeyUp:()=>c(!1),onFocus:()=>s(!0),onBlur:()=>{s(!1),c(!1)}},style:{...Q(i?e?.hover:void 0,r),...Q(n?e?.focus:void 0,r),...Q(l?e?.active:void 0,r)}}}function ka({recipe:e}){let a=_e(e.states?.button,!0),r=_e(e.states?.input),i=_e(e.states?.card),o=`${e.spacing/6.4}cqw`;X(()=>{wa(e.detail)},[e.detail]);let n=l=>l.replace(/(-?\d*\.?\d+)(px|rem)\b/g,(c,p,f)=>`${Math.max(-16,Math.min(16,Number(p)*(f==="rem"?16:1)/6.4))}cqw`),s=l=>l?{...Oe({background:l.background}),...l.backgroundImage&&l.backgroundImage!=="none"?{backgroundImage:l.backgroundImage}:{},backgroundBlendMode:l.backgroundBlendMode,...Ue({border:n(l.border)}),borderRadius:`${l.radius/6.4}cqw`,boxShadow:n(l.shadow),backdropFilter:l.backdropFilter?n(l.backdropFilter):void 0,WebkitBackdropFilter:l.backdropFilter?n(l.backdropFilter):void 0,opacity:l.opacity}:{};return t("div",{"data-taste-detail-specimen":!0,role:"group","aria-label":"Interactive taste preview",style:{position:"absolute",inset:0,containerType:"inline-size",background:e.background,color:e.foreground,fontSynthesis:"none",...Q(e.detail?.body),overflow:"hidden"},children:t("div",{"data-taste-component":"card",style:{position:"absolute",inset:"9% 8%",background:e.surface,border:`1px solid ${e.border}`,borderRadius:e.radius,...s(e.parts?.card),padding:"5cqw",boxSizing:"border-box",display:"flex",flexDirection:"column",gap:o,...Q(e.detail?.card)},children:h("div",{style:{display:"grid",gridTemplateColumns:"1.35fr 1fr",gap:`calc(${o} * 2)`,alignItems:"center",flex:1,minHeight:0},children:[h("div",{children:[h("h2",{"data-taste-component":"heading",style:{margin:0,fontWeight:"inherit",lineHeight:1.1,letterSpacing:"-0.03em",marginBottom:o,...Q(e.detail?.heading),fontSize:`clamp(3.8cqw, ${Q(e.detail?.heading).fontSize??"4.6cqw"}, 5.4cqw)`},children:["A little space",t("br",{}),"for big ideas."]}),h("p",{"data-taste-component":"paragraph",style:{margin:0,fontSize:"2.4cqw",lineHeight:1.5,marginBottom:o,...Q(e.detail?.body)},children:["Gather your thoughts.",t("br",{}),"Make something your own."]}),t("button",{"data-taste-component":"button",...a.handlers,type:"button",style:{fontFamily:"inherit",color:"inherit",display:"inline-block",...Oe({background:e.accent}),...Ue({border:`1px solid ${e.border}`}),borderRadius:e.radius,...s(e.parts?.button),padding:"1.5cqw 2.5cqw",fontSize:"2.3cqw",fontWeight:"inherit",lineHeight:1.2,...Q(e.detail?.button),cursor:"pointer",...a.style},children:"Create a project \u2197"})]}),h("div",{"data-taste-component":"card",...i.handlers,style:{...Oe({background:e.surface}),...Ue({border:`1px solid ${e.border}`}),borderRadius:e.radius,...s(e.parts?.card),padding:"3cqw",fontSize:"2.1cqw",lineHeight:1.5,...Q(e.detail?.card),...i.style},children:[t("h3",{"data-taste-component":"heading",style:{margin:0,fontWeight:"inherit",...Q(e.detail?.heading),fontSize:"2.6cqw",marginBottom:o},children:"In the works"}),t("input",{"data-taste-component":"input",...r.handlers,"aria-label":"Preview project name",defaultValue:"A fresh start",style:{appearance:"none",outline:"none",borderWidth:0,borderStyle:"none",borderColor:"transparent",...Oe({background:"transparent"}),...s(e.parts?.content),font:"inherit",color:"inherit",padding:"1.5cqw",...Q(e.detail?.input),width:"100%",minWidth:0,boxSizing:"border-box",marginBottom:o,...r.style}}),t("div",{children:"02 \xA0 What comes next"})]})]})})})}function Et({children:e}){let a=He.dark,r=z(null),[i,o]=$(),[n,s]=$({scale:1,x:0,y:0}),l=z(n);return X(()=>{let c=r.current;if(!c)return;let p=()=>o({width:c.clientWidth,height:c.clientHeight});p();let f=typeof ResizeObserver<"u"?new ResizeObserver(p):void 0;f?.observe(c);let g=()=>window.matchMedia("(any-hover: hover) and (any-pointer: fine)").matches,w=(m,k,v)=>{m=Math.max(1,Math.min(4,m));let V={scale:m,x:Math.max(1-m,Math.min(0,k)),y:Math.max(1-m,Math.min(0,v))};l.current=V,s(V)},P=(m,k,v)=>{let V=c.getBoundingClientRect();if(!V.width||!V.height)return;let A=l.current,N=Math.max(1,Math.min(4,m)),D=Math.max(0,Math.min(1,(k-V.left)/V.width)),W=Math.max(0,Math.min(1,(v-V.top)/V.height));w(N,D-(D-A.x)*N/A.scale,W-(W-A.y)*N/A.scale)},I=null,S=m=>{if(!g()||!m.ctrlKey&&l.current.scale===1)return;m.preventDefault(),m.stopPropagation();let k=m.deltaMode===1?16:m.deltaMode===2?c.clientHeight:1;if(m.ctrlKey)I===null&&P(l.current.scale*Math.exp(-m.deltaY*k*.01),m.clientX,m.clientY);else{let v=c.getBoundingClientRect();v.width&&v.height&&w(l.current.scale,l.current.x-m.deltaX*k/v.width,l.current.y-m.deltaY*k/v.height)}},T=m=>{if(!g())return;m.preventDefault(),m.stopPropagation();let k=m;m.type==="gesturestart"?I=l.current.scale:m.type==="gestureend"?I=null:I!==null&&Number.isFinite(k.scale)&&P(I*k.scale,k.clientX,k.clientY)};c.addEventListener("wheel",S,{passive:!1});for(let m of["gesturestart","gesturechange","gestureend"])c.addEventListener(m,T,{passive:!1});return()=>{f?.disconnect(),c.removeEventListener("wheel",S);for(let m of["gesturestart","gesturechange","gestureend"])c.removeEventListener(m,T)}},[]),h("div",{ref:r,"data-preview-zoom":!0,style:{position:"relative",width:"100%",aspectRatio:"16 / 9",overflow:"hidden",borderRadius:8},children:[t("div",{"data-preview-zoom-content":!0,style:{width:i?.width||"100%",height:i?.height||"100%",zoom:n.scale,transformOrigin:"0 0",transform:`translate(${n.x*100/n.scale}%, ${n.y*100/n.scale}%)`},children:e}),n.scale>1&&h(be,{children:[t("style",{children:`
2
+ import{x as me,xa as He,_ as ht,Ka as ra,La as ia}from"./chunk-7MGWRICI.mjs";import"./chunk-D7HY2EDH.mjs";import{useRef as z,useState as $,useEffect as X,useMemo as Pt,useCallback as na,isValidElement as oa,useLayoutEffect as ft,useId as la}from"react";import{Search as gt,X as Fe,ChevronLeft as At,Component as sa,PenLine as da,History as ca,Eye as ua,Ruler as pa,Fingerprint as Qe,Plus as mt,ChevronRight as et,RotateCw as ha,RotateCcw as fa,Minimize2 as ga,Info as ma,ChevronDown as ba,Check as ya,User as va}from"lucide-react";import{jsxs as h,jsx as t,Fragment as be}from"react/jsx-runtime";function Te(e,a=!1){if(typeof e!="string"||!e||e.length>800||!/^[a-z\d\s.,%+#()\-/]+$/i.test(e))return!1;let r=0;for(let n of e)if(n==="("&&++r>8||n===")"&&--r<0)return!1;if(r)return!1;let i=e.replace(/#[\da-f]{3,8}\b/gi,"").replace(/[-+]?(?:\d*\.)?\d+(?:e[-+]?\d+)?(?:px|rem|em|deg|turn|rad|%)?/gi,"").match(/[a-z][a-z-]*/gi)??[],o=new Set("none transparent black white currentcolor rgb rgba hsl hsla hwb oklch oklab lab lch color color-mix srgb srgb-linear display-p3 in shorter longer increasing decreasing hue solid dashed dotted double groove ridge inset outset".split(" "));if(a)for(let n of"linear-gradient radial-gradient conic-gradient repeating-linear-gradient repeating-radial-gradient repeating-conic-gradient to top right bottom left circle ellipse closest-side farthest-side closest-corner farthest-corner at center from".split(" "))o.add(n);return i.every(n=>o.has(n.toLowerCase()))}function Ue(e){if(e.border===void 0)return e;let{border:a,...r}=e,i=String(a).match(/(?:[^\s(]+\([^)]*\)|[^\s]+)/g)??[],o=i.find(l=>/^(?:[\d.]+(?:[a-z%]+)?|thin|medium|thick)$/.test(l)),n=i.find(l=>/^(none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset)$/.test(l)),s=i.filter(l=>l!==o&&l!==n).join(" ");return{borderWidth:o??"medium",borderStyle:n??"none",borderColor:s||"currentColor",...r}}function Oe(e){if(e.background===void 0)return e;let{background:a,...r}=e,i=String(a);if(typeof document<"u"){let o=document.createElement("span").style;if(o.background=i,o.background)return{backgroundColor:o.backgroundColor||"transparent",backgroundImage:o.backgroundImage||"none",...r}}return{backgroundColor:/gradient\(/i.test(i)||i==="none"?"transparent":i,backgroundImage:/gradient\(/i.test(i)?i:"none",...r}}function bt(e){if(!e||typeof e!="object")return;let a={};for(let r of["body","heading","card","button","input"]){let i=e[r];if(!i||typeof i!="object")continue;let o={};for(let[n,s]of Object.entries(i)){let l=String(s??"");n==="fontFamily"&&l.length<=200&&/^[a-zA-Z][a-zA-Z0-9 ,"'_-]*$/.test(l.replace(/^["']/,""))&&(o[n]=l),n==="color"&&Te(s)&&(o[n]=l),["background","backgroundColor","backgroundImage","border","borderColor","boxShadow","outline"].includes(n)&&Te(s,n.startsWith("background"))&&(o[n]=l),n==="opacity"&&typeof s=="number"&&Number.isFinite(s)&&(o[n]=Math.max(0,Math.min(1,s))),n==="transform"&&l.length<150&&/^(?:none|(?:\s*(?:translate(?:X|Y)?\(-?[\d.]+(?:px|rem|%)(?:,\s*-?[\d.]+(?:px|rem|%))?\)|scale\(\d*\.?\d+\))\s*){1,3})$/.test(l)&&(o[n]=l),n==="transition"&&l.length<200&&/^(?:(?:all|color|background-color|border-color|box-shadow|transform|opacity)\s+\d*\.?\d+(?:ms|s)(?:\s+(?:ease|ease-in|ease-out|ease-in-out|linear))?\s*,?\s*){1,5}$/.test(l)&&(o[n]=l),n==="fontWeight"&&typeof s=="number"&&s>=100&&s<=900&&(o[n]=s),n==="fontStyle"&&["normal","italic"].includes(l)&&(o[n]=l),n==="textTransform"&&["none","uppercase","lowercase","capitalize"].includes(l)&&(o[n]=l),["fontSize","letterSpacing","lineHeight","padding","margin","marginTop","marginBottom","gap","borderRadius","borderWidth","outlineOffset"].includes(n)&&l.length<100&&/^-?\d*\.?\d+(?:px|rem|em|%)?(?:\s+-?\d*\.?\d+(?:px|rem|em|%)?){0,3}$/.test(l)&&(o[n]=l)}a[r]=o}return a}function Q(e,a=640){if(!e)return{};let r={...e};for(let[i,o]of Object.entries(r))i==="fontFamily"||i==="fontWeight"||typeof o=="string"&&(r[i]=o.replace(/(-?\d*\.?\d+)(px|rem)\b/g,(n,s,l)=>`${Math.max(-12,Math.min(12,Number(s)*(l==="rem"?16:1)/(a/100)))}cqw`));if(e.fontFamily){let i=Mt(e.fontFamily);/^Geist\s?Mono$/i.test(i)?r.fontFamily='"Popmelt Geist Mono", ui-monospace, monospace':/^Geist$/i.test(i)?r.fontFamily='"Popmelt Geist", system-ui, sans-serif':i&&!Tt(i)&&(r.fontFamily=`"Popmelt Taste ${i}", ${e.fontFamily}`)}return Oe(Ue(r))}var Mt=e=>e.split(",")[0].trim().replace(/^["']|["']$/g,""),Tt=e=>/^(inherit|initial|unset|serif|sans-serif|monospace|system-ui|ui-.+|Arial|Helvetica|Verdana|Georgia|Times New Roman|Courier New|SFMono-Regular|Menlo|Monaco|Consolas)$/i.test(e),yt=new Map;function wa(e){if(!e||typeof FontFace>"u"||!document.fonts)return Promise.resolve();let a=new Map;for(let r of Object.values(e)){if(!r?.fontFamily)continue;let i=Mt(r.fontFamily);if(Tt(i)||/^Geist(?:\s?Mono)?$/i.test(i)||!/^[a-zA-Z][a-zA-Z0-9 _-]{0,79}$/.test(i))continue;let o=Number(r.fontWeight)||400,n=r.fontStyle==="italic";a.set(`${i}:${o}:${n}`,{family:i,weight:o,italic:n})}return Promise.all([...a.entries()].slice(0,5).map(([r,i])=>{let o=yt.get(r);if(o)return o;let n=(async()=>{let s=new AbortController,l=setTimeout(()=>s.abort(),8e3);try{let c=new URLSearchParams({family:`${i.family}:${i.italic?"ital,wght@1,":"wght@"}${i.weight}`,display:"swap"}),p=await fetch(`https://fonts.googleapis.com/css2?${c}`,{signal:s.signal,credentials:"omit",referrerPolicy:"no-referrer"});if(p.ok||(p=await fetch(`https://fonts.googleapis.com/css2?family=${encodeURIComponent(i.family)}&display=swap`,{signal:s.signal,credentials:"omit",referrerPolicy:"no-referrer"})),!p.ok)throw new Error("Font unavailable");if(![...(await p.text()).matchAll(/@font-face\s*\{([^}]+)\}/g)].slice(0,32).flatMap(f=>{let g=f[1],w=g.match(/url\((https:\/\/fonts\.gstatic\.com\/[^\s)"']+)\)/)?.[1];if(!w)return[];let P=new FontFace(`Popmelt Taste ${i.family}`,`url(${JSON.stringify(w)})`,{weight:g.match(/font-weight:\s*([^;]+);/)?.[1]??"400",style:g.match(/font-style:\s*([^;]+);/)?.[1]??"normal",unicodeRange:g.match(/unicode-range:\s*([^;]+);/)?.[1]??"U+0-10FFFF",display:"swap"});return document.fonts.add(P),[P]}).length)throw new Error("Font unavailable");await document.fonts.load(`${i.italic?"italic ":""}${i.weight} 16px "Popmelt Taste ${i.family}"`,"Your workspace A little space for big ideas. Create a project")}finally{clearTimeout(l)}})().catch(s=>{console.warn(`[Popmelt] Preview font ${i.family} unavailable; using its fallback.`,s instanceof Error?s.message:"Font request failed"),yt.delete(r)});return yt.set(r,n),n})).then(()=>{})}function Ae(e){if(!e||typeof e!="object")return;let a=e;for(let i of["background","surface","foreground","muted","accent","border"])if(!Te(a[i],!0))return;for(let i of["radius","spacing"])if(typeof a[i]!="number"||!Number.isFinite(a[i])||a[i]<0||a[i]>32)return;let r={...a};if(delete r.detail,a.detail!==void 0&&(r.detail=bt(a.detail)),delete r.states,a.states&&typeof a.states=="object"){r.states={};for(let i of["card","button","input"]){let o=a.states[i];if(!(!o||typeof o!="object")){r.states[i]={};for(let n of["hover","focus","active"])r.states[i][n]=bt({[i]:o[n]})?.[i]}}}if(delete r.parts,a.parts!==void 0){if(!a.parts||typeof a.parts!="object")return;let i={};for(let o of["card","button","content"]){let n=a.parts[o];if(!n||typeof n.radius!="number"||!Number.isFinite(n.radius)||n.radius<0||n.radius>999)return;let s=n.backdropFilter;i[o]={background:Te(n.background,!0)?n.background:r.surface,border:Te(n.border)?n.border:`1px solid ${r.border}`,radius:n.radius,shadow:Te(n.shadow)?n.shadow:"none",...n.backgroundImage!==void 0?{backgroundImage:Te(n.backgroundImage,!0)?n.backgroundImage:"none"}:{},...n.backgroundBlendMode!==void 0?{backgroundBlendMode:["normal","overlay","multiply","screen","soft-light","hard-light"].includes(n.backgroundBlendMode)?n.backgroundBlendMode:"normal"}:{},...s!==void 0?{backdropFilter:typeof s=="string"&&s.length<150&&/^(?:none|(?:\s*(?:blur\(\d*\.?\d+(?:px|rem)\)|saturate\(\d*\.?\d+%?\))\s*){1,3})$/.test(s)?s:"none"}:{},...n.opacity!==void 0?{opacity:Number.isFinite(n.opacity)?Math.max(0,Math.min(1,n.opacity)):1}:{}}}r.parts=i}return(!Number.isSafeInteger(r.recipeRevision)||r.recipeRevision<0)&&delete r.recipeRevision,(typeof r.contentRevision!="string"||!/^[a-f\d]{24}$/.test(r.contentRevision))&&delete r.contentRevision,r}function xa({recipe:e}){let a=e.radius*.45,r=o=>o.replace(/(-?\d*\.?\d+)(px|rem)\b/g,(n,s,l)=>`${Math.max(-32,Math.min(32,Number(s)*(l==="rem"?16:1)*.45))}px`),i=o=>o?{background:o.background,...o.backgroundImage&&o.backgroundImage!=="none"?{backgroundImage:o.backgroundImage}:{},backgroundBlendMode:o.backgroundBlendMode,backdropFilter:o.backdropFilter?r(o.backdropFilter).replace(/saturate\(([\d.]+)%\)/g,(n,s)=>`saturate(${Math.min(400,Number(s))}%)`):void 0,WebkitBackdropFilter:o.backdropFilter?r(o.backdropFilter):void 0,opacity:o.opacity,border:r(o.border),borderRadius:o.radius*.45,boxShadow:r(o.shadow)}:{};return t("span",{"data-taste-specimen":!0,"aria-hidden":"true",style:{position:"absolute",inset:0,background:e.background,pointerEvents:"none",overflow:"hidden"},children:h("span",{"data-specimen-window":!0,style:{position:"absolute",left:"19.23%",top:"19.23%",width:"110%",height:"110%",background:e.surface,border:`1px solid ${e.border}`,borderRadius:a,overflow:"hidden",boxSizing:"border-box",...i(e.parts?.card),borderTopRightRadius:0,borderBottomRightRadius:0,borderBottomLeftRadius:0},children:[t("span",{"data-specimen-title":!0,style:{position:"absolute",left:0,top:0,width:"100%",height:"18.18%",background:e.parts?"transparent":e.accent}}),t("span",{"data-specimen-control":!0,style:{position:"absolute",left:"7.95%",top:"26.14%",width:"90.91%",height:"18.18%",background:e.muted,border:`1px solid ${e.border}`,borderRadius:a*.6,boxSizing:"border-box",...i(e.parts?.button)}}),t("span",{"data-specimen-content":!0,style:{position:"absolute",left:"7.95%",top:"53.41%",width:"90.91%",height:"67.05%",background:e.background,border:`1px solid ${e.border}`,borderRadius:a*.6,boxSizing:"border-box",...i(e.parts?.content)}})]})})}function _e(e,a=!1,r=640){let[i,o]=$(!1),[n,s]=$(!1),[l,c]=$(!1);return{handlers:{onPointerEnter:()=>o(!0),onPointerLeave:()=>{o(!1),c(!1)},onPointerDown:()=>c(!0),onPointerUp:()=>c(!1),onPointerCancel:()=>c(!1),onKeyDown:p=>{a&&["Enter"," "].includes(p.key)&&c(!0)},onKeyUp:()=>c(!1),onFocus:()=>s(!0),onBlur:()=>{s(!1),c(!1)}},style:{...Q(i?e?.hover:void 0,r),...Q(n?e?.focus:void 0,r),...Q(l?e?.active:void 0,r)}}}function ka({recipe:e}){let a=_e(e.states?.button,!0),r=_e(e.states?.input),i=_e(e.states?.card),o=`${e.spacing/6.4}cqw`;X(()=>{wa(e.detail)},[e.detail]);let n=l=>l.replace(/(-?\d*\.?\d+)(px|rem)\b/g,(c,p,f)=>`${Math.max(-16,Math.min(16,Number(p)*(f==="rem"?16:1)/6.4))}cqw`),s=l=>l?{...Oe({background:l.background}),...l.backgroundImage&&l.backgroundImage!=="none"?{backgroundImage:l.backgroundImage}:{},backgroundBlendMode:l.backgroundBlendMode,...Ue({border:n(l.border)}),borderRadius:`${l.radius/6.4}cqw`,boxShadow:n(l.shadow),backdropFilter:l.backdropFilter?n(l.backdropFilter):void 0,WebkitBackdropFilter:l.backdropFilter?n(l.backdropFilter):void 0,opacity:l.opacity}:{};return t("div",{"data-taste-detail-specimen":!0,role:"group","aria-label":"Interactive taste preview",style:{position:"absolute",inset:0,containerType:"inline-size",background:e.background,color:e.foreground,fontSynthesis:"none",...Q(e.detail?.body),overflow:"hidden"},children:t("div",{"data-taste-component":"card",style:{position:"absolute",inset:"9% 8%",background:e.surface,border:`1px solid ${e.border}`,borderRadius:e.radius,...s(e.parts?.card),padding:"5cqw",boxSizing:"border-box",display:"flex",flexDirection:"column",gap:o,...Q(e.detail?.card)},children:h("div",{style:{display:"grid",gridTemplateColumns:"1.35fr 1fr",gap:`calc(${o} * 2)`,alignItems:"center",flex:1,minHeight:0},children:[h("div",{children:[h("h2",{"data-taste-component":"heading",style:{margin:0,fontWeight:"inherit",lineHeight:1.1,letterSpacing:"-0.03em",marginBottom:o,...Q(e.detail?.heading),fontSize:`clamp(3.8cqw, ${Q(e.detail?.heading).fontSize??"4.6cqw"}, 5.4cqw)`},children:["A little space",t("br",{}),"for big ideas."]}),h("p",{"data-taste-component":"paragraph",style:{margin:0,fontSize:"2.4cqw",lineHeight:1.5,marginBottom:o,...Q(e.detail?.body)},children:["Gather your thoughts.",t("br",{}),"Make something your own."]}),t("button",{"data-taste-component":"button",...a.handlers,type:"button",style:{fontFamily:"inherit",color:"inherit",display:"inline-block",...Oe({background:e.accent}),...Ue({border:`1px solid ${e.border}`}),borderRadius:e.radius,...s(e.parts?.button),padding:"1.5cqw 2.5cqw",fontSize:"2.3cqw",fontWeight:"inherit",lineHeight:1.2,...Q(e.detail?.button),cursor:"pointer",...a.style},children:"Create a project \u2197"})]}),h("div",{"data-taste-component":"card",...i.handlers,style:{...Oe({background:e.surface}),...Ue({border:`1px solid ${e.border}`}),borderRadius:e.radius,...s(e.parts?.card),padding:"3cqw",fontSize:"2.1cqw",lineHeight:1.5,...Q(e.detail?.card),...i.style},children:[t("h3",{"data-taste-component":"heading",style:{margin:0,fontWeight:"inherit",...Q(e.detail?.heading),fontSize:"2.6cqw",marginBottom:o},children:"In the works"}),t("input",{"data-taste-component":"input",...r.handlers,"aria-label":"Preview project name",defaultValue:"A fresh start",style:{appearance:"none",outline:"none",borderWidth:0,borderStyle:"none",borderColor:"transparent",...Oe({background:"transparent"}),...s(e.parts?.content),font:"inherit",color:"inherit",padding:"1.5cqw",...Q(e.detail?.input),width:"100%",minWidth:0,boxSizing:"border-box",marginBottom:o,...r.style}}),t("div",{children:"02 \xA0 What comes next"})]})]})})})}function Et({children:e}){let a=He.dark,r=z(null),[i,o]=$(),[n,s]=$({scale:1,x:0,y:0}),l=z(n);return X(()=>{let c=r.current;if(!c)return;let p=()=>o({width:c.clientWidth,height:c.clientHeight});p();let f=typeof ResizeObserver<"u"?new ResizeObserver(p):void 0;f?.observe(c);let g=()=>window.matchMedia("(any-hover: hover) and (any-pointer: fine)").matches,w=(m,k,v)=>{m=Math.max(1,Math.min(4,m));let V={scale:m,x:Math.max(1-m,Math.min(0,k)),y:Math.max(1-m,Math.min(0,v))};l.current=V,s(V)},P=(m,k,v)=>{let V=c.getBoundingClientRect();if(!V.width||!V.height)return;let A=l.current,N=Math.max(1,Math.min(4,m)),D=Math.max(0,Math.min(1,(k-V.left)/V.width)),W=Math.max(0,Math.min(1,(v-V.top)/V.height));w(N,D-(D-A.x)*N/A.scale,W-(W-A.y)*N/A.scale)},I=null,S=m=>{if(!g()||!m.ctrlKey&&l.current.scale===1)return;m.preventDefault(),m.stopPropagation();let k=m.deltaMode===1?16:m.deltaMode===2?c.clientHeight:1;if(m.ctrlKey)I===null&&P(l.current.scale*Math.exp(-m.deltaY*k*.01),m.clientX,m.clientY);else{let v=c.getBoundingClientRect();v.width&&v.height&&w(l.current.scale,l.current.x-m.deltaX*k/v.width,l.current.y-m.deltaY*k/v.height)}},T=m=>{if(!g())return;m.preventDefault(),m.stopPropagation();let k=m;m.type==="gesturestart"?I=l.current.scale:m.type==="gestureend"?I=null:I!==null&&Number.isFinite(k.scale)&&P(I*k.scale,k.clientX,k.clientY)};c.addEventListener("wheel",S,{passive:!1});for(let m of["gesturestart","gesturechange","gestureend"])c.addEventListener(m,T,{passive:!1});return()=>{f?.disconnect(),c.removeEventListener("wheel",S);for(let m of["gesturestart","gesturechange","gestureend"])c.removeEventListener(m,T)}},[]),h("div",{ref:r,"data-preview-zoom":!0,style:{position:"relative",width:"100%",aspectRatio:"16 / 9",overflow:"hidden",borderRadius:8},children:[t("div",{"data-preview-zoom-content":!0,style:{width:i?.width||"100%",height:i?.height||"100%",zoom:n.scale,transformOrigin:"0 0",transform:`translate(${n.x*100/n.scale}%, ${n.y*100/n.scale}%)`},children:e}),n.scale>1&&h(be,{children:[t("style",{children:`
3
3
  [data-preview-zoom-reset] span { color: ${a.primary}; }
4
4
  [data-preview-zoom-reset] svg { color: ${a.secondary}; }
5
5
  [data-preview-zoom-reset]:hover span, [data-preview-zoom-reset]:focus-visible span { color: ${a.secondary}; }