@xauyxau/hnch 1.10.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +12 -12
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,21 +1,21 @@
1
1
  #!/usr/bin/env node
2
- import Is from'yargs';import {hideBin}from'yargs/helpers';import Et,{useState,useEffect,useCallback,useMemo,useRef}from'react';import {render,useApp,useInput,Box,Text}from'ink';import*as Me from'yjs';import {Awareness}from'y-protocols/awareness';import {mkdirSync,chmodSync,writeFileSync,unlinkSync,existsSync,readFileSync}from'fs';import {homedir}from'os';import {join}from'path';import {randomUUID}from'crypto';import {createInterface}from'readline';import {WebsocketProvider}from'y-websocket';import Pr from'ws';import Ro from'clipboardy';import {jsxs,jsx,Fragment}from'react/jsx-runtime';var sr="https://hnch.dev";function _e(){let t=process.env.XDG_CONFIG_HOME||join(homedir(),".config");return join(t,"hnch")}function Ht(){return join(_e(),"config.json")}function gn(){let e=_e();existsSync(e)||mkdirSync(e,{recursive:true});}function Re(){let e=Ht();if(!existsSync(e))return {};try{return JSON.parse(readFileSync(e,"utf-8"))}catch{return {}}}function J(e){gn();let o={...Re(),...e};writeFileSync(Ht(),JSON.stringify(o,null,2)+`
3
- `,"utf-8");}async function ir(e){let t=createInterface({input:process.stdin,output:process.stderr});return new Promise(o=>{t.question(e,n=>{t.close(),o(n.trim());});})}function ar(e){return e.startsWith("wss://")?"https://"+e.slice(6):e.startsWith("ws://")?"http://"+e.slice(5):e}async function Ve(){let e=Re(),t=false;if(e.participantId||(e.participantId=randomUUID(),t=true),!e.displayName){let n=await ir("Enter your display name: ");e.displayName=n||`user-${e.participantId.slice(0,6)}`,t=true;}e.relayUrl||(e.relayUrl=sr,t=true),t&&J(e);let o=process.env.HNCH_RELAY_URL||e.relayUrl;return o=ar(o),{participantId:e.participantId,displayName:e.displayName,relayUrl:o,defaultScale:e.defaultScale,defaultSessionName:e.defaultSessionName,defaultPassword:e.defaultPassword,presetOverrides:e.presetOverrides,customScales:e.customScales}}function Fe(e){gn();let o={...Re()};for(let[n,r]of Object.entries(e))r===""?delete o[n]:r!==void 0&&(o[n]=r);writeFileSync(Ht(),JSON.stringify(o,null,2)+`
4
- `,"utf-8");}var rt="hnch_abstain";function pe(e){return e===rt}var cr={"unknown-room":4001,"wrong-password":4002,"invalid-invite":4003,"expired-invite":4004,"invite-already-redeemed":4005,"room-full":4006,"malformed-credentials":4010},hn=new Map(Object.entries(cr).map(([e,t])=>[t,e]));function Ie(e){return e.role??"voter"}function W(e){let{revealedAt:t,skippedAt:o}=e;return t===void 0&&o===void 0?null:t===void 0?"skipped":o===void 0||t<=o?"revealed":"skipped"}var st={id:"fibonacci",cards:["0","1","2","3","5","8","13","21"]},Sn={id:"t-shirt",cards:["XS","S","M","L","XL"]},xn={id:"powers-of-2",cards:["1","2","4","8","16","32","64"]},wn={id:"linear",cards:["1","2","3","4","5","6","7","8","9","10"]},yn={id:"risk",cards:["Low","Medium","High","Critical"]},se={[st.id]:st,[Sn.id]:Sn,[xn.id]:xn,[wn.id]:wn,[yn.id]:yn},vn={fibonacci:"Fibonacci","t-shirt":"T-shirt","powers-of-2":"Powers of 2",linear:"Linear (1\u201310)",risk:"Risk"};function Cn(e){return e in vn?vn[e]:e.length===0?e:(e.startsWith("custom-")?e.slice(7):e).split("-").map(o=>o.length===0?o:o.charAt(0).toUpperCase()+o.slice(1)).join(" ")}var dr="meta",Ye="settings",lr="participants",ur="rounds",pr=["roomUuid","createdAt","createdBy","sessionEndedAt"],fr=["name","defaultScale","hostParticipantId"],mr=["displayName","joinedAt","role","leftAt","removedBy"],gr=["id","title","description","ticketId","parentRoundId","scale","timerStartedAt","revealedAt","skippedAt","createdBy","createdAt"];function it(e){return e.getMap(dr)}function at(e){return e.getMap(Ye)}function ct(e){return e.getMap(lr)}function Ut(e){return e.getArray(ur)}function dt(e,t){let o={};for(let n of t){let r=e.get(n);r!==void 0&&(o[n]=r);}return o}function hr(e){return dt(it(e),pr)}function Sr(e){return dt(at(e),fr)}function xr(e){let t=ct(e),o=[];return t.forEach((n,r)=>{let s=dt(n,mr);o.push({id:r,...s});}),o.sort((n,r)=>n.joinedAt-r.joinedAt||n.id.localeCompare(r.id)),o}function wr(e){let t={};return e.forEach((o,n)=>{t[n]=o;}),t}function yr(e){let t=dt(e,gr),o=e.get("votes"),n=o?wr(o):{};return {...t,votes:n}}function vr(e){let t=Ut(e),o=[];return t.forEach(n=>{o.push(yr(n));}),o}function Q(e){return {meta:hr(e),settings:Sr(e),participants:xr(e),rounds:vr(e)}}function bn(e,t){if(it(e).has("roomUuid"))throw new Error("initDoc: doc already seeded");e.transact(()=>{let o=it(e);o.set("roomUuid",t.roomUuid),o.set("createdAt",t.createdAt),o.set("createdBy",t.participantId);let n=at(e);t.sessionName!==void 0&&n.set("name",t.sessionName),n.set("defaultScale",t.defaultScale),n.set("hostParticipantId",t.participantId);let r=new Me.Map;r.set("displayName",t.displayName),r.set("joinedAt",t.createdAt),ct(e).set(t.participantId,r);});}function lt(e,t){e.transact(()=>{let o=ct(e),n=o.get(t.participantId),r=n??new Me.Map;r.set("displayName",t.displayName),n===void 0&&r.set("joinedAt",Date.now()),r.delete("leftAt"),r.delete("removedBy"),n===void 0&&o.set(t.participantId,r);});}function $e(e,t){e.transact(()=>{let o=at(e);for(let[n,r]of Object.entries(t))r===void 0?o.delete(n):o.set(n,r);});}function Lt(e,t,o){e.transact(()=>{let n=ct(e),r=n.get(t),s=r??new Me.Map;s.set("displayName",o.displayName),s.set("joinedAt",o.joinedAt),o.role!==void 0&&s.set("role",o.role),r===void 0&&n.set(t,s);});}function jt(e,t){let o=t.scale??at(e).get("defaultScale");if(!o)throw new Error("appendRound: no scale (settings.defaultScale missing)");return e.transact(()=>{let n=new Me.Map;n.set("id",t.id),n.set("createdAt",t.createdAt),n.set("createdBy",t.createdBy),n.set("scale",o),t.title!==void 0&&n.set("title",t.title),t.description!==void 0&&n.set("description",t.description),t.ticketId!==void 0&&n.set("ticketId",t.ticketId),t.parentRoundId!==void 0&&n.set("parentRoundId",t.parentRoundId),n.set("timerStartedAt",t.createdAt),n.set("votes",new Me.Map),Ut(e).push([n]);}),t.id}function Rn(e,t,o){let n=Je(e,t);if(!n)throw new Error(`patchRoundDescriptor: round ${t} not found`);e.transact(()=>{o.title!==void 0&&n.set("title",o.title),o.description!==void 0&&n.set("description",o.description);});}function Je(e,t){let o=Ut(e);for(let n=0;n<o.length;n+=1){let r=o.get(n);if(r.get("id")===t)return r}}function In(e,t,o,n){let r=Je(e,t);if(!r)throw new Error(`castVote: round ${t} not found`);r.get("revealedAt")===void 0&&e.transact(()=>{r.get("votes").set(o,n);});}function Tn(e,t,o){let n=Je(e,t);if(!n)throw new Error(`clearVote: round ${t} not found`);n.get("revealedAt")===void 0&&e.transact(()=>{n.get("votes").delete(o);});}function _t(e,t,o){let n=Je(e,t);if(!n)throw new Error(`revealRound: round ${t} not found`);if(n.get("skippedAt")!==void 0)throw new Error(`revealRound: round ${t} already skipped`);e.transact(()=>{n.set("revealedAt",o);});}function En(e,t,o){let n=Je(e,t);if(!n)throw new Error(`skipRound: round ${t} not found`);if(n.get("revealedAt")!==void 0)throw new Error(`skipRound: round ${t} already revealed`);if(n.get("skippedAt")!==void 0)throw new Error(`skipRound: round ${t} already skipped`);e.transact(()=>{n.set("skippedAt",o);});}function An(e){e.transact(()=>{it(e).set("sessionEndedAt",Date.now());});}function ee(e){let{rounds:t}=e;if(t.length===0)return null;for(let o=t.length-1;o>=0;o-=1){let n=t[o];if(n.revealedAt===void 0)return n}return t.at(-1)}function Nn(e){let t=Object.values(e.votes);return t.length<2?false:t.every(o=>o===t[0])}function Pn(e){let t=Math.max(0,Math.floor(e/1e3)),o=Math.floor(t/60),n=t%60;return `${o}:${n.toString().padStart(2,"0")}`}function Dn(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}}function kn(e,t){let o=new Map;for(let i of t)o.set(i.id,i);let n=o.get(e);if(n===void 0||n.parentRoundId===void 0)return null;let r=new Set([n.id]),s=n,c=1;for(;s.parentRoundId!==void 0;){let i=o.get(s.parentRoundId);if(i===void 0||r.has(i.id))return null;r.add(i.id),s=i,c+=1;}let a=s,u=new Map;for(let i of t){if(i.parentRoundId===void 0)continue;let p=u.get(i.parentRoundId);p===void 0?u.set(i.parentRoundId,[i]):p.push(i);}let l=0,d=[a];for(;d.length>0;){let i=d.shift();l+=1;let p=u.get(i.id);p!==void 0&&d.push(...p);}return {chainRoot:a,depth:c,total:l}}var On="PBKDF2",Cr="SHA-256",Mn=new TextEncoder;function br(e){return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Te(e,t){let o=await crypto.subtle.importKey("raw",Mn.encode(e),On,false,["deriveBits"]),n=await crypto.subtle.deriveBits({name:On,salt:Mn.encode(t),iterations:1e5,hash:Cr},o,256);return br(n)}var $n="ABCDEFGHJKMNPQRSTUVWXYZ23456789";if($n.length!==31)throw new Error(`Room code alphabet must be 31 characters, got ${$n.length}`);function Vt(e){return e.trim().replaceAll(/-/g,"").toUpperCase()}function Bn(e,t=true){let o=Vt(e);return !t||o.length!==6?o:`${o.slice(0,3)}-${o.slice(3)}`}function Rr(e,t){let o=new Map;t.forEach((s,c)=>o.set(s,c));let n=[...new Set(e.filter(s=>!o.has(s)))].toSorted(),r=new Map;return n.forEach((s,c)=>r.set(s,t.length+c)),s=>o.get(s)??r.get(s)??Number.MAX_SAFE_INTEGER}function Ft(e,t){let o=new Map;for(let c of e)o.set(c,(o.get(c)??0)+1);let n=null,r=0,s=[...o.keys()].toSorted((c,a)=>t(c)-t(a));for(let c of s){let a=o.get(c);a>r&&(r=a,n=c);}return n}function Hn(e,t){let o=Object.values(e);if(o.length===0)return null;let n=Rr(o,t.cards);if(t.cards.every(c=>Number.isFinite(parseFloat(c)))){let c=o.map(parseFloat).filter(Number.isFinite);if(c.length===0)return {kind:"categorical",mode:Ft(o,n)};let a=c.reduce((b,A)=>b+A,0)/c.length,u=[...c].toSorted((b,A)=>b-A),l=Math.floor(u.length/2),d=u.length%2===1?u[l]:(u[l-1]+u[l])/2,i=Ft(o,n),p;if(new Set(o).size===1)p="unanimous";else {let b=o.map(R=>n(R)),A=Math.min(...b);p=Math.max(...b)-A<=1?"close":"spread";}return {kind:"numeric",mean:a,median:d,mode:i,spread:p}}return {kind:"categorical",mode:Ft(o,n)}}function Un(e){return e.replaceAll(/\|/g,"\\|")}function Ir(e){return e.replaceAll(/\\/g,"\\\\").replaceAll(/]/g,"\\]")}function Tr(e){let o=(e.match(/`+/g)??[]).reduce((n,r)=>Math.max(n,r.length),0);return "`".repeat(o+1)}function Yt(e){if(!e)return "";if(Dn(e))return ` ([${Ir(e)}](<${e}>))`;let t=Tr(e);return ` (${t}${e}${t})`}function Er(e){return e instanceof Map?e:new Map(Object.entries(e))}function Ar(e){let t=new Map;for(let r of e)t.set(r.id,r);function o(r){if(!r.parentRoundId)return r;let s=t.get(r.parentRoundId);return s?o(s):r}let n=new Map;for(let r of e){let s=o(r),c=n.get(s.id);c?c.push(r):n.set(s.id,[r]);}return n}function Ln(e,t){let o=new Map;e.scale.cards.forEach((c,a)=>o.set(c,a));let n=new Map;for(let[c,a]of Object.entries(e.votes)){let u=t.get(c)??c,l=n.get(a);l?l.push(u):n.set(a,[u]);}let r=[...n.entries()].map(([c,a])=>({card:c,scaleIndex:o.get(c)??Number.MAX_SAFE_INTEGER,voters:[...a].toSorted().map(Un)}));return r.sort((c,a)=>{let u=a.voters.length-c.voters.length;return u!==0?u:c.scaleIndex-a.scaleIndex}),["| Vote | Voters |","|------|--------|",...r.map(c=>`| ${Un(c.card)} | ${c.voters.join(", ")} |`)].join(`
5
- `)}function jn(e){let t=Hn(e.votes,e.scale),o=e.timerStartedAt!=null&&e.revealedAt!=null?Pn(e.revealedAt-e.timerStartedAt):null,n=[];return t?.kind==="numeric"?n.push(`Avg ${t.mean.toFixed(1)} \xB7 Med ${t.median}`):t?.kind==="categorical"&&n.push(`Most common: ${t.mode}`),o!=null&&n.push(`Elapsed ${o}`),n.join(" \xB7 ")}function _n(e){let{rounds:t}=e,o=Er(e.participants),n=new Map;for(let[d,i]of o)n.set(d,i.displayName);let r=t.filter(d=>d.revealedAt!=null);if(r.length===0)return "";let s=new Map;t.forEach((d,i)=>s.set(d.id,i+1));let c=Ar(r),a=new Set,u=[];for(let d of r)for(let[i,p]of c)if(p.includes(d)&&!a.has(i)){a.add(i),u.push(i);break}let l=[];for(let d of u){let i=c.get(d),p=i.find(m=>m.id===d),b=i.filter(m=>m.id!==d),A=s.get(p.id)??0,E=p.title?`## Round ${A} \u2014 ${p.title}${Yt(p.ticketId)}`:`## Round ${A}${Yt(p.ticketId)}`,R=Ln(p,n),$=jn(p),f=$?`${E}
2
+ import As from'yargs';import {hideBin}from'yargs/helpers';import Wt,{useState,useEffect,useCallback,useMemo,useRef}from'react';import {render,useApp,useInput,Box,Text}from'ink';import*as De from'yjs';import {Awareness}from'y-protocols/awareness';import {mkdirSync,chmodSync,writeFileSync,unlinkSync,existsSync,readFileSync}from'fs';import {homedir}from'os';import {join}from'path';import {randomUUID}from'crypto';import {createInterface}from'readline';import {WebsocketProvider}from'y-websocket';import bi from'ws';import Qo from'clipboardy';import {jsxs,jsx,Fragment}from'react/jsx-runtime';var Yr="https://hnch.dev";function nt(){let t=process.env.XDG_CONFIG_HOME||join(homedir(),".config");return join(t,"hnch")}function an(){return join(nt(),"config.json")}function jn(){let e=nt();existsSync(e)||mkdirSync(e,{recursive:true});}function Ne(){let e=an();if(!existsSync(e))return {};try{return JSON.parse(readFileSync(e,"utf-8"))}catch{return {}}}function G(e){jn();let n={...Ne(),...e};writeFileSync(an(),JSON.stringify(n,null,2)+`
3
+ `,"utf-8");}async function Jr(e){let t=createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.question(e,o=>{t.close(),n(o.trim());});})}function Gr(e){return e.startsWith("wss://")?"https://"+e.slice(6):e.startsWith("ws://")?"http://"+e.slice(5):e}async function se(){let e=Ne(),t=false;if(e.participantId||(e.participantId=randomUUID(),t=true),!e.displayName){let o=await Jr("Enter your display name: ");e.displayName=o||`user-${e.participantId.slice(0,6)}`,t=true;}e.relayUrl||(e.relayUrl=Yr,t=true),t&&G(e);let n=process.env.HNCH_RELAY_URL||e.relayUrl;return n=Gr(n),{participantId:e.participantId,displayName:e.displayName,relayUrl:n,defaultScale:e.defaultScale,defaultSessionName:e.defaultSessionName,defaultPassword:e.defaultPassword,presetOverrides:e.presetOverrides,customScales:e.customScales}}function ot(e){jn();let n={...Ne()};for(let[o,r]of Object.entries(e))r===""?delete n[o]:r!==void 0&&(n[o]=r);writeFileSync(an(),JSON.stringify(n,null,2)+`
4
+ `,"utf-8");}var vt="hnch_abstain";function fe(e){return e===vt}var Wr={"unknown-room":4001,"wrong-password":4002,"invalid-invite":4003,"expired-invite":4004,"invite-already-redeemed":4005,"room-full":4006,"malformed-credentials":4010},_n=new Map(Object.entries(Wr).map(([e,t])=>[t,e]));function Pe(e){return e.role??"voter"}function W(e){let{revealedAt:t,skippedAt:n}=e;return t===void 0&&n===void 0?null:t===void 0?"skipped":n===void 0||t<=n?"revealed":"skipped"}var Ct={id:"fibonacci",cards:["0","1","2","3","5","8","13","21"]},Fn={id:"t-shirt",cards:["XS","S","M","L","XL"]},Vn={id:"powers-of-2",cards:["1","2","4","8","16","32","64"]},Yn={id:"linear",cards:["1","2","3","4","5","6","7","8","9","10"]},Jn={id:"risk",cards:["Low","Medium","High","Critical"]},ae={[Ct.id]:Ct,[Fn.id]:Fn,[Vn.id]:Vn,[Yn.id]:Yn,[Jn.id]:Jn},Gn={fibonacci:"Fibonacci","t-shirt":"T-shirt","powers-of-2":"Powers of 2",linear:"Linear (1\u201310)",risk:"Risk"};function Wn(e){return e in Gn?Gn[e]:e.length===0?e:(e.startsWith("custom-")?e.slice(7):e).split("-").map(n=>n.length===0?n:n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}var Ie="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",It=Ie.length,dn=Math.floor(It/2);function rt(e){let t=Ie.indexOf(e);if(t===-1)throw new Error(`fractional-index: invalid character '${e}'`);return t}function qn(e,t){return e.length>=t?e:e+"0".repeat(t-e.length)}function qr(e){let t=e.length-1;for(;t>0&&e[t]==="0";)t--;return e.slice(0,t+1)}function Kr(e,t){let n=e.length,o=Array.from({length:n+1}).fill(0),r=0;for(let s=n-1;s>=0;s--){let l=e[s]+t[s]+r;o[s+1]=l%It,r=Math.floor(l/It);}o[0]=r;let i=Array.from({length:n+1}).fill(0),a=0;for(let s=0;s<=n;s++){let l=o[s]+a*It;i[s]=Math.floor(l/2),a=l%2;}return i.slice(1)}function cn(e,t){let n=Ie[dn];if(e===null&&t===null)return n+n;if(t===null)return e+n+n+n+n;if(e===null)return zr(t);if(e>=t)throw new Error(`keyBetween: a must be < b (a='${e}', b='${t}')`);return Xr(e,t)}function zr(e){for(let t=e.length-1;t>=0;t--){let n=rt(e[t]);if(n>0)return e.slice(0,t)+Ie[n-1]+Ie[dn]}if(e.length>1)return e.slice(0,-1);throw new Error(`keyBetween: cannot generate key before '${e}' \u2014 use keyBetween(null, null) for the initial key`)}function Xr(e,t){let n=Math.max(e.length,t.length),o=qn(e,n).split("").map(l=>rt(l)),r=qn(t,n).split("").map(l=>rt(l)),a=Kr(o,r).map(l=>Ie[l]).join(""),s=qr(a);return s>e&&s<t?s:a>e&&a<t?a:Qr(e,t)}function Qr(e,t){for(let n=0;n<t.length;n++){let o=n<e.length?rt(e[n]):0;if(rt(t[n])===o+1)return (n<e.length?e.slice(0,n+1):e+Ie[0])+Ie[dn]}throw new Error(`keyBetween: space exhausted between '${e}' and '${t}'`)}var Zr="meta",it="settings",ei="participants",ti="rounds",ni="agenda",oi=["roomUuid","createdAt","createdBy","sessionEndedAt"],ri=["name","defaultScale","hostParticipantId"],ii=["displayName","joinedAt","role","leftAt","removedBy"],si=["id","title","description","ticketId","state","source","externalId","sortKey","createdAt","consumedAt","consumedByRoundId"],ai=["id","title","description","ticketId","parentRoundId","scale","timerStartedAt","revealedAt","skippedAt","createdBy","createdAt","agendaItemId"];function bt(e){return e.getMap(Zr)}function Tt(e){return e.getMap(it)}function Rt(e){return e.getMap(ei)}function ln(e){return e.getArray(ti)}function At(e){return e.getArray(ni)}function st(e,t){let n={};for(let o of t){let r=e.get(o);r!==void 0&&(n[o]=r);}return n}function di(e){return st(bt(e),oi)}function ci(e){return st(Tt(e),ri)}function li(e){let t=Rt(e),n=[];return t.forEach((o,r)=>{let i=st(o,ii);n.push({id:r,...i});}),n.sort((o,r)=>o.joinedAt-r.joinedAt||o.id.localeCompare(r.id)),n}function ui(e){let t={};return e.forEach((n,o)=>{t[o]=n;}),t}function pi(e){let t=st(e,ai),n=e.get("votes"),o=n?ui(n):{};return {...t,votes:o}}function mi(e){let t=ln(e),n=[];return t.forEach(o=>{n.push(pi(o));}),n}function fi(e){return st(e,si)}function gi(e){let t=At(e),n=[];return t.forEach(o=>{n.push(fi(o));}),n.sort((o,r)=>o.sortKey.localeCompare(r.sortKey)),n}function q(e){return {meta:di(e),settings:ci(e),participants:li(e),rounds:mi(e),agenda:gi(e)}}function Kn(e,t){if(bt(e).has("roomUuid"))throw new Error("initDoc: doc already seeded");e.transact(()=>{let n=bt(e);n.set("roomUuid",t.roomUuid),n.set("createdAt",t.createdAt),n.set("createdBy",t.participantId);let o=Tt(e);t.sessionName!==void 0&&o.set("name",t.sessionName),o.set("defaultScale",t.defaultScale),o.set("hostParticipantId",t.participantId);let r=new De.Map;r.set("displayName",t.displayName),r.set("joinedAt",t.createdAt),Rt(e).set(t.participantId,r);});}function Ye(e,t){e.transact(()=>{let n=Rt(e),o=n.get(t.participantId),r=o??new De.Map;r.set("displayName",t.displayName),o===void 0&&r.set("joinedAt",Date.now()),r.delete("leftAt"),r.delete("removedBy"),o===void 0&&n.set(t.participantId,r);});}function Je(e,t){e.transact(()=>{let n=Tt(e);for(let[o,r]of Object.entries(t))r===void 0?n.delete(o):n.set(o,r);});}function un(e,t,n){e.transact(()=>{let o=Rt(e),r=o.get(t),i=r??new De.Map;i.set("displayName",n.displayName),i.set("joinedAt",n.joinedAt),n.role!==void 0&&i.set("role",n.role),r===void 0&&o.set(t,i);});}function pn(e,t){let n=t.scale??Tt(e).get("defaultScale");if(!n)throw new Error("appendRound: no scale (settings.defaultScale missing)");return e.transact(()=>{let o=new De.Map;o.set("id",t.id),o.set("createdAt",t.createdAt),o.set("createdBy",t.createdBy),o.set("scale",n),t.title!==void 0&&o.set("title",t.title),t.description!==void 0&&o.set("description",t.description),t.ticketId!==void 0&&o.set("ticketId",t.ticketId),t.parentRoundId!==void 0&&o.set("parentRoundId",t.parentRoundId),t.agendaItemId!==void 0&&o.set("agendaItemId",t.agendaItemId),o.set("timerStartedAt",t.createdAt),o.set("votes",new De.Map),ln(e).push([o]);}),t.id}function zn(e,t,n){let o=at(e,t);if(!o)throw new Error(`patchRoundDescriptor: round ${t} not found`);e.transact(()=>{n.title!==void 0&&o.set("title",n.title),n.description!==void 0&&o.set("description",n.description);});}function at(e,t){let n=ln(e);for(let o=0;o<n.length;o+=1){let r=n.get(o);if(r.get("id")===t)return r}}function Xn(e,t,n,o){let r=at(e,t);if(!r)throw new Error(`castVote: round ${t} not found`);r.get("revealedAt")===void 0&&e.transact(()=>{r.get("votes").set(n,o);});}function Qn(e,t,n){let o=at(e,t);if(!o)throw new Error(`clearVote: round ${t} not found`);o.get("revealedAt")===void 0&&e.transact(()=>{o.get("votes").delete(n);});}function mn(e,t,n){let o=at(e,t);if(!o)throw new Error(`revealRound: round ${t} not found`);if(o.get("skippedAt")!==void 0)throw new Error(`revealRound: round ${t} already skipped`);e.transact(()=>{o.set("revealedAt",n);});}function Zn(e,t,n){let o=at(e,t);if(!o)throw new Error(`skipRound: round ${t} not found`);if(o.get("revealedAt")!==void 0)throw new Error(`skipRound: round ${t} already revealed`);if(o.get("skippedAt")!==void 0)throw new Error(`skipRound: round ${t} already skipped`);e.transact(()=>{o.set("skippedAt",n);});}function eo(e){e.transact(()=>{bt(e).set("sessionEndedAt",Date.now());});}function te(e){let{rounds:t}=e;if(t.length===0)return null;for(let n=t.length-1;n>=0;n-=1){let o=t[n];if(o.revealedAt===void 0)return o}return t.at(-1)}function to(e){let t=Object.values(e.votes);return t.length<2?false:t.every(n=>n===t[0])}function no(e,t){let n=At(e);for(let o=0;o<n.length;o++){let r=n.get(o);if(r.get("id")===t)return r}}function Et(e,t){if(!t.title?.trim()&&!t.ticketId?.trim())throw new Error("appendAgendaItem: at least one of {title, ticketId} is required");let n=crypto.randomUUID(),o=At(e),r=null;o.forEach(a=>{if(a.get("state")==="pending"){let s=a.get("sortKey");s!==void 0&&(r===null||s>r)&&(r=s);}});let i=cn(r,null);return e.transact(()=>{let a=new De.Map;a.set("id",n),a.set("state","pending"),a.set("source",t.source??"manual"),a.set("sortKey",i),a.set("createdAt",t.createdAt),t.title!==void 0&&a.set("title",t.title),t.description!==void 0&&a.set("description",t.description),t.ticketId!==void 0&&a.set("ticketId",t.ticketId),t.externalId!==void 0&&a.set("externalId",t.externalId),At(e).push([a]);}),n}function kt(e,t,n,o={}){let r=no(e,t);if(!r)throw new Error(`setAgendaItemState: item ${t} not found`);let i=r.get("state");if(!(i===n&&n==="consumed")){if(i!=="pending")throw new Error(`setAgendaItemState: invalid transition '${i}' \u2192 '${n}' for item ${t}`);e.transact(()=>{r.set("state",n),n==="consumed"&&(r.set("consumedAt",o.timestamp??Date.now()),o.consumedByRoundId!==void 0&&r.set("consumedByRoundId",o.consumedByRoundId));});}}function oo(e,t,n,o){kt(e,t,"consumed",{consumedByRoundId:n,timestamp:o});}function ro(e,t,n,o){let r=no(e,t);if(!r)throw new Error(`reorderAgendaItem: item ${t} not found`);let i=r.get("state");if(i!=="pending")throw new Error(`reorderAgendaItem: item ${t} is ${i}; only pending items may be reordered`);let a=cn(n??null,o??null);e.transact(()=>{r.set("sortKey",a);});}function Ge(e){for(let t of e.agenda)if(t.state==="pending")return t;return null}function io(e){let t=Math.max(0,Math.floor(e/1e3)),n=Math.floor(t/60),o=t%60;return `${n}:${o.toString().padStart(2,"0")}`}function so(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return false}}function ao(e,t){let n=new Map;for(let d of t)n.set(d.id,d);let o=n.get(e);if(o===void 0||o.parentRoundId===void 0)return null;let r=new Set([o.id]),i=o,a=1;for(;i.parentRoundId!==void 0;){let d=n.get(i.parentRoundId);if(d===void 0||r.has(d.id))return null;r.add(d.id),i=d,a+=1;}let s=i,l=new Map;for(let d of t){if(d.parentRoundId===void 0)continue;let p=l.get(d.parentRoundId);p===void 0?l.set(d.parentRoundId,[d]):p.push(d);}let u=0,c=[s];for(;c.length>0;){let d=c.shift();u+=1;let p=l.get(d.id);p!==void 0&&c.push(...p);}return {chainRoot:s,depth:a,total:u}}var co="PBKDF2",hi="SHA-256",lo=new TextEncoder;function Si(e){return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Oe(e,t){let n=await crypto.subtle.importKey("raw",lo.encode(e),co,false,["deriveBits"]),o=await crypto.subtle.deriveBits({name:co,salt:lo.encode(t),iterations:1e5,hash:hi},n,256);return Si(o)}var uo="ABCDEFGHJKMNPQRSTUVWXYZ23456789";if(uo.length!==31)throw new Error(`Room code alphabet must be 31 characters, got ${uo.length}`);function fn(e){return e.trim().replaceAll(/-/g,"").toUpperCase()}function po(e,t=true){let n=fn(e);return !t||n.length!==6?n:`${n.slice(0,3)}-${n.slice(3)}`}function xi(e,t){let n=new Map;t.forEach((i,a)=>n.set(i,a));let o=[...new Set(e.filter(i=>!n.has(i)))].toSorted(),r=new Map;return o.forEach((i,a)=>r.set(i,t.length+a)),i=>n.get(i)??r.get(i)??Number.MAX_SAFE_INTEGER}function gn(e,t){let n=new Map;for(let a of e)n.set(a,(n.get(a)??0)+1);let o=null,r=0,i=[...n.keys()].toSorted((a,s)=>t(a)-t(s));for(let a of i){let s=n.get(a);s>r&&(r=s,o=a);}return o}function mo(e,t){let n=Object.values(e);if(n.length===0)return null;let o=xi(n,t.cards);if(t.cards.every(a=>Number.isFinite(parseFloat(a)))){let a=n.map(parseFloat).filter(Number.isFinite);if(a.length===0)return {kind:"categorical",mode:gn(n,o)};let s=a.reduce((b,E)=>b+E,0)/a.length,l=[...a].toSorted((b,E)=>b-E),u=Math.floor(l.length/2),c=l.length%2===1?l[u]:(l[u-1]+l[u])/2,d=gn(n,o),p;if(new Set(n).size===1)p="unanimous";else {let b=n.map(A=>o(A)),E=Math.min(...b);p=Math.max(...b)-E<=1?"close":"spread";}return {kind:"numeric",mean:s,median:c,mode:d,spread:p}}return {kind:"categorical",mode:gn(n,o)}}function fo(e){return e.replaceAll(/\|/g,"\\|")}function wi(e){return e.replaceAll(/\\/g,"\\\\").replaceAll(/]/g,"\\]")}function yi(e){let n=(e.match(/`+/g)??[]).reduce((o,r)=>Math.max(o,r.length),0);return "`".repeat(n+1)}function hn(e){if(!e)return "";if(so(e))return ` ([${wi(e)}](<${e}>))`;let t=yi(e);return ` (${t}${e}${t})`}function vi(e){return e instanceof Map?e:new Map(Object.entries(e))}function Ci(e){let t=new Map;for(let r of e)t.set(r.id,r);function n(r){if(!r.parentRoundId)return r;let i=t.get(r.parentRoundId);return i?n(i):r}let o=new Map;for(let r of e){let i=n(r),a=o.get(i.id);a?a.push(r):o.set(i.id,[r]);}return o}function go(e,t){let n=new Map;e.scale.cards.forEach((a,s)=>n.set(a,s));let o=new Map;for(let[a,s]of Object.entries(e.votes)){let l=t.get(a)??a,u=o.get(s);u?u.push(l):o.set(s,[l]);}let r=[...o.entries()].map(([a,s])=>({card:a,scaleIndex:n.get(a)??Number.MAX_SAFE_INTEGER,voters:[...s].toSorted().map(fo)}));return r.sort((a,s)=>{let l=s.voters.length-a.voters.length;return l!==0?l:a.scaleIndex-s.scaleIndex}),["| Vote | Voters |","|------|--------|",...r.map(a=>`| ${fo(a.card)} | ${a.voters.join(", ")} |`)].join(`
5
+ `)}function ho(e){let t=mo(e.votes,e.scale),n=e.timerStartedAt!=null&&e.revealedAt!=null?io(e.revealedAt-e.timerStartedAt):null,o=[];return t?.kind==="numeric"?o.push(`Avg ${t.mean.toFixed(1)} \xB7 Med ${t.median}`):t?.kind==="categorical"&&o.push(`Most common: ${t.mode}`),n!=null&&o.push(`Elapsed ${n}`),o.join(" \xB7 ")}function So(e){let{rounds:t}=e,n=vi(e.participants),o=new Map;for(let[c,d]of n)o.set(c,d.displayName);let r=t.filter(c=>c.revealedAt!=null);if(r.length===0)return "";let i=new Map;t.forEach((c,d)=>i.set(c.id,d+1));let a=Ci(r),s=new Set,l=[];for(let c of r)for(let[d,p]of a)if(p.includes(c)&&!s.has(d)){s.add(d),l.push(d);break}let u=[];for(let c of l){let d=a.get(c),p=d.find(f=>f.id===c),b=d.filter(f=>f.id!==c),E=i.get(p.id)??0,R=p.title?`## Round ${E} \u2014 ${p.title}${hn(p.ticketId)}`:`## Round ${E}${hn(p.ticketId)}`,A=go(p,o),H=ho(p),m=H?`${R}
6
6
 
7
- ${R}
7
+ ${A}
8
8
 
9
- ${$}`:`${E}
9
+ ${H}`:`${R}
10
10
 
11
- ${R}`;l.push(f);for(let m of b){let v=`### Re-vote ${s.get(m.id)??0}${Yt(m.ticketId)}`,k=Ln(m,n),h=jn(m),P=h?`${v}
11
+ ${A}`;u.push(m);for(let f of b){let v=`### Re-vote ${i.get(f.id)??0}${hn(f.ticketId)}`,N=go(f,o),w=ho(f),D=w?`${v}
12
12
 
13
- ${k}
13
+ ${N}
14
14
 
15
- ${h}`:`${v}
15
+ ${w}`:`${v}
16
16
 
17
- ${k}`;l.push(P);}}return l.join(`
17
+ ${N}`;u.push(D);}}return u.join(`
18
18
 
19
19
  `)+`
20
- `}function ut(e,t,o){if(e.startsWith("custom-")){let r=(o??[]).find(s=>s.id===e);return r?{id:r.id,cards:r.cards}:void 0}let n=se[e];if(n){let r=(t??{})[e]??[];if(r.length===0)return n;let s=n.cards.filter((c,a)=>!r.includes(a));return s.length===0?void 0:{id:e,cards:s}}}function pt(e,t){let o=Object.keys(se).map(r=>ut(r,e,t)).filter(r=>r!==void 0),n=(t??[]).map(r=>({id:r.id,cards:r.cards}));return [...o,...n]}function Ee(e,t){if(e.startsWith("custom-")){let o=(t??[]).find(n=>n.id===e);if(o&&o.label.trim().length>0)return o.label}return Cn(e)}async function Vn(e,t){let o=await fetch(`${e}/rooms`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({})});if(!o.ok)throw new Error(`POST /rooms failed: ${o.status}`);return await o.json()}async function We(e,t){let o=await fetch(`${e}/rooms/${encodeURIComponent(t)}`);if(o.status===404){let n=await o.json().catch(()=>null);throw new Error(`Room not found: ${n?.reason??"unknown-room"}`)}if(!o.ok)throw new Error(`GET /rooms/:code failed: ${o.status}`);return await o.json()}async function Jt(e,t,o){let n=await fetch(`${e}/rooms/${t}/access`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({passwordHash:o})});if(!n.ok)throw new Error(`PATCH /rooms/:uuid/access failed: ${n.status}`)}function Fn(e){let o=`${e.wsBaseUrl.replace(/^http/,"ws")}/ws`,n={did:e.deviceId};e.passwordHash!==void 0&&(n.pw=e.passwordHash);let r=new WebsocketProvider(o,e.roomUuid,e.doc,{params:n,connect:true,...e.awareness!==void 0&&{awareness:e.awareness},WebSocketPolyfill:Pr}),s=l=>{e.onStatusChange?.(l.status);},c=l=>{if(l===null)return;let d=hn.get(l.code);d!==void 0&&(e.onRejection?.(d),r.shouldConnect=false,r.disconnect());};r.on("status",s),r.on("connection-close",c);let a=false,u=e.passwordHash;return {doc:e.doc,awareness:r.awareness,updateCredentials(l){if(l.passwordHash===u)return;u=l.passwordHash??void 0,r.shouldConnect=false,r.disconnect();let i={did:r.params.did??""};u!==void 0&&(i.pw=u),r.params=i,r.connect();},disconnect(){a||(a=true,r.off("status",s),r.off("connection-close",c),r.shouldConnect=false,r.disconnect(),r.destroy());}}}var Dr=5e3;function Yn(e,t,o){let n=null,r=null;function s(){let d=new Set;return t.getStates().forEach(i=>{let p=i.participantId;typeof p=="string"&&d.add(p);}),d}function c(){return e.getMap(Ye).get("hostParticipantId")}function a(){r!==null&&(clearTimeout(r),r=null),n=null;}function u(){let d=c(),i=n;if(n=null,!i||d!==i)return;let p=s();if(p.has(d))return;let b=[...p].toSorted();if(b.length===0)return;let A=b[0];A===o&&$e(e,{hostParticipantId:A});}function l(){let d=c();if(!d)return;if(s().has(d)){a();return}n!==d&&(a(),n=d,r=setTimeout(()=>{r=null,u();},Dr));}return t.on("change",l),e.getMap(Ye).observe(l),l(),{stop(){a(),t.off("change",l),e.getMap(Ye).unobserve(l);}}}async function qn(e){let t,o=await Vn(e.relayUrl);e.password&&(t=await Te(e.password,o.uuid),await Jt(e.relayUrl,o.uuid,t));let n=new Me.Doc,r=new Awareness(n),s=Date.now();return bn(n,{roomUuid:o.uuid,createdAt:s,participantId:e.participantId,displayName:e.displayName,defaultScale:e.defaultScale??st,...e.sessionName!==void 0&&{sessionName:e.sessionName}}),r.setLocalStateField("participantId",e.participantId),ft({doc:n,awareness:r,roomCode:o.code,roomUuid:o.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t})}async function Gn(e){let t=await We(e.relayUrl,e.roomCode),o;if(t.accessMode==="password"){if(!e.password)throw new Error("Room requires a password");o=await Te(e.password,t.uuid);}let n=new Me.Doc,r=new Awareness(n);return lt(n,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId),ft({doc:n,awareness:r,roomCode:e.roomCode,roomUuid:t.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:o,onRejection:e.onRejection})}function ft(e){let{doc:t,awareness:o,participantId:n,relayUrl:r,roomUuid:s}=e,c=new Set,a=new Set,u=new Set,l=Fn({wsBaseUrl:e.relayUrl,roomUuid:e.roomUuid,doc:t,deviceId:n,passwordHash:e.passwordHash,awareness:o,onStatusChange(f){c.forEach(m=>m(f));},onRejection(f){console.error(`Connection rejected: ${f}`),e.onRejection?.(f);}}),d=Yn(t,o,n),i=()=>{a.forEach(f=>f());};t.getMap("meta").observeDeep(i),t.getMap("settings").observeDeep(i),t.getMap("participants").observeDeep(i),t.getArray("rounds").observeDeep(i);function p(){let f=new Set;return o.getStates().forEach(m=>{let y=m.participantId;typeof y=="string"&&f.add(y);}),f}let b=new Set,A=setInterval(()=>{let f=Q(t),m=ee(f);if(!m||m.revealedAt!==void 0||b.has(m.id))return;let y=p();if(y.size===0)return;let v=f.participants.filter(h=>y.has(h.id)&&Ie(h)==="voter");if(v.length===0)return;v.filter(h=>h.id in m.votes).length>=v.length&&(b.add(m.id),_t(t,m.id,Date.now()));},250),E=t.getMap("settings").get("hostParticipantId"),R=()=>{let f=t.getMap("settings").get("hostParticipantId");f!==E&&f!==void 0&&u.forEach(m=>m(f)),E=f;};t.getMap("settings").observe(R);let $=false;return {doc:t,awareness:o,roomCode:e.roomCode,roomUuid:e.roomUuid,projection(){return Q(t)},current(){return ee(Q(t))},isHost(){return Q(t).settings.hostParticipantId===n},onlineIds:p,vote(f){let m=ee(Q(t));m&&In(t,m.id,n,f);},unvote(){let f=ee(Q(t));f&&Tn(t,f.id,n);},reveal(){let f=ee(Q(t));f&&_t(t,f.id,Date.now());},skip(){let f=ee(Q(t));f&&En(t,f.id,Date.now());},newRound(f,m){let y=randomUUID();return jt(t,{id:y,createdAt:Date.now(),createdBy:n,...f!==void 0&&{title:f},...m!==void 0&&{ticketId:m}}),y},revote(){let f=ee(Q(t)),m=randomUUID();return jt(t,{id:m,createdAt:Date.now(),createdBy:n,...f?.id!==void 0&&{parentRoundId:f.id},...f?.title!==void 0&&{title:f.title},...f?.description!==void 0&&{description:f.description},...f?.ticketId!==void 0&&{ticketId:f.ticketId}}),m},updateRoundDescriptor(f,m){Rn(t,f,m);},updateName(f){$e(t,{name:f});},updateScale(f){$e(t,{defaultScale:f});},updateDisplayName(f){let v=Q(t).participants.find(k=>k.id===n)?.joinedAt??Date.now();Lt(t,n,{displayName:f,joinedAt:v});},async updateAccess(f,m){let y=null;if(f==="password"){if(!m)throw new Error("Password required for password mode");y=await Te(m,s);}await Jt(r,s,y),l.updateCredentials({passwordHash:y});},handoffHost(f){if(!this.isHost())throw new Error("Only the current host can hand off");if(!p().has(f))throw new Error("Target participant is not online");if(!Q(t).participants.some(k=>k.id===f))throw new Error("Target participant does not exist");$e(t,{hostParticipantId:f});},toggleRole(){let m=Q(t).participants.find(h=>h.id===n),v=Ie(m??{})==="viewer"?"voter":"viewer",k=m?.joinedAt??Date.now();Lt(t,n,{displayName:m?.displayName??"",joinedAt:k,role:v});},endSessionForEveryone(){if(!this.isHost())throw new Error("Only the current host can end the session");An(t);},onChange(f){return a.add(f),()=>a.delete(f)},onStatusChange(f){return c.add(f),()=>c.delete(f)},onHostChange(f){return u.add(f),()=>u.delete(f)},disconnect(){$||($=true,clearInterval(A),d.stop(),t.getMap("meta").unobserveDeep(i),t.getMap("settings").unobserveDeep(i),t.getMap("settings").unobserve(R),t.getMap("participants").unobserveDeep(i),t.getArray("rounds").unobserveDeep(i),l.disconnect());}}}function zn(e){let t=Vt(e);return t===""?null:t}var Ur=1440*60*1e3;function qt(){return join(_e(),"last-session.json")}function Lr(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.roomCode=="string"&&typeof t.roomUuid=="string"&&typeof t.lastSeenAt=="number"&&(t.passwordHash===void 0||typeof t.passwordHash=="string")}function Qn(){let e=qt();if(!existsSync(e))return null;try{let t=JSON.parse(readFileSync(e,"utf-8"));return !Lr(t)||Date.now()-t.lastSeenAt>Ur?(V(),null):t}catch{return V(),null}}function mt(e){let t=_e();mkdirSync(t,{recursive:true,mode:448}),chmodSync(t,448);let o=qt();writeFileSync(o,JSON.stringify(e,null,2)+`
21
- `,{encoding:"utf-8",mode:384}),chmodSync(o,384);}function V(){let e=qt();try{unlinkSync(e);}catch(t){if(t.code!=="ENOENT")throw t}}async function gt(e){let t=true;try{await e.clearLastSession();}catch(o){t=false,e.logger.error(`Failed to clear cached session: ${o instanceof Error?o.message:String(o)}`);}return t?e.logger.error("Session expired (room no longer exists). Cached session cleared."):e.logger.error("Session expired. Could not delete ~/.config/hnch/last-session.json \u2014 please remove it manually."),e.exit(1)}function ht(e){let t=e.doc.getMap("meta"),o=null,n=false;function r(){if(n)return;let s=t.get("sessionEndedAt");if(s==null||s===o)return;o=s;let c=t.get("createdBy"),a=c===e.localParticipantId,u=e.doc.getMap("participants"),l=e.doc.getMap("settings").get("hostParticipantId")??c,d="host";if(l){let p=u.get(l)?.get("displayName");typeof p=="string"&&p.length>0&&(d=p);}setImmediate(()=>{n||e.onEnded({isLocal:a,hostName:d,timestamp:s});});}return t.observe(r),r(),()=>{n=true,t.unobserve(r);}}var jr="@xauyxau/hnch";function St(e){return Bn(e)}function xt(e){return `${process.env.HNCH_SHARE_ORIGIN??"https://hnch.dev"}/join?code=${e}`}function wt(e){return `npx ${jr} join ${e}`}function Gt(e){let t=e.trim();return t===""?void 0:t}function Kn(e,t){return [e,Gt(t)]}var _r={connecting:"yellow",connected:"green",disconnected:"red"};function to({roomCode:e,sessionName:t,status:o,isHost:n}){let r=t?`${e} \xB7 ${t}`:e;return jsxs(Box,{borderStyle:"single",borderColor:"gray",paddingX:1,justifyContent:"space-between",children:[jsxs(Text,{bold:true,children:["hnch \xB7 ",r]}),jsxs(Box,{gap:2,children:[n&&jsx(Text,{color:"yellow",children:"[host]"}),jsx(Text,{color:_r[o],children:o})]})]})}function me({items:e,onSelect:t,onClose:o,title:n}){if(e.length===0)return jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Text,{bold:true,children:n}),jsx(Text,{dimColor:true,children:"(no items)"})]});let r=e.findIndex(a=>!a.disabled),[s,c]=useState(Math.max(r,0));return useInput((a,u)=>{if(u.upArrow)c(l=>{let d=(l-1+e.length)%e.length,i=0;for(;e[d]?.disabled&&i<e.length;)d=(d-1+e.length)%e.length,i++;return d});else if(u.downArrow)c(l=>{let d=(l+1)%e.length,i=0;for(;e[d]?.disabled&&i<e.length;)d=(d+1)%e.length,i++;return d});else if(u.return){let l=e[s];l&&!l.disabled&&t(l.value);}else u.escape&&o?.();}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Text,{bold:true,children:n}),jsx(Box,{flexDirection:"column",children:e.map((a,u)=>{let l=u===s,d=a.disabled??false;return jsxs(Box,{gap:1,children:[jsx(Text,{...l&&{color:"cyan"},dimColor:d,children:l?">":" "}),jsx(Text,{bold:l,dimColor:d,children:a.label}),a.detail&&jsx(Text,{dimColor:true,children:a.detail})]},a.value)})}),jsx(Text,{dimColor:true,children:"\u2191\u2193 select \u23CE confirm esc close"})]})}function q({value:e,onChange:t,onSubmit:o,onCancel:n,placeholder:r,isActive:s=true,mask:c=false}){useInput((d,i)=>{i.escape?n?.():i.return?o(e):i.backspace||i.delete?t(e.slice(0,-1)):d&&!i.ctrl&&!i.meta&&t(e+d);},{isActive:s});let a=c&&e.length>0?"*".repeat(e.length):e,u=a.length>0?a:r??"",l=e.length===0&&r!==void 0;return jsxs(Text,{children:[jsx(Text,{dimColor:l,children:u}),jsx(Text,{inverse:true,children:" "})]})}function so({mode:e,password:t,onModeChange:o,onPasswordChange:n,onClose:r}){let[s,c]=useState(e==="open"?0:1),[a,u]=useState(false);return useEffect(()=>{c(e==="open"?0:1);},[e]),useInput((l,d)=>{if(d.leftArrow)c(i=>Math.max(0,i-1));else if(d.rightArrow)c(i=>Math.min(1,i+1));else if(d.return){let i=s===0?"open":"password";i!==e&&o(i),i==="password"&&u(true);}else d.escape&&r?.();},{isActive:!a}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:["open","password"].map((l,d)=>{let i=d===s,p=l===e,b=l==="open"?"Open":"Password";return jsx(Text,{inverse:i,bold:p,...p&&{color:"cyan"},children:p?`[${b}]`:` ${b} `},l)})}),e==="password"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Password: "}),jsx(q,{value:t,onChange:n,onSubmit:()=>u(false),onCancel:()=>u(false),placeholder:"(required to join)",isActive:a,mask:true}),!a&&jsx(Text,{dimColor:true,children:"\u23CE edit \u2190 \u2192 switch mode esc close"}),a&&jsx(Text,{dimColor:true,children:"\u23CE done esc cancel"})]}),e==="open"&&jsx(Text,{dimColor:true,children:"\u2190\u2192 toggle \u23CE confirm esc close"})]})}function co({scaleId:e,cards:t,disabledIndices:o,onOverrideChange:n,onClose:r}){let s=useMemo(()=>new Set(o),[o]),[c,a]=useState(0),u=l=>{let d=new Set(s);if(d.has(l))d.delete(l);else {if(d.size>=t.length-1)return;d.add(l);}let i=Array.from(d).toSorted((p,b)=>p-b);n(e,i);};return useInput((l,d)=>{d.leftArrow?a(i=>Math.max(0,i-1)):d.rightArrow?a(i=>Math.min(t.length-1,i+1)):l===" "?u(c):(d.return||d.escape)&&r();}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:t.map((l,d)=>{let i=d===c,p=s.has(d);return jsx(Text,{inverse:i,bold:!p,...!p&&{color:"cyan"},strikethrough:p,dimColor:p,children:l},l)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate space toggle \u23CE/esc done"})]})}function nn({initialName:e="",initialCards:t=[],onSave:o,onCancel:n}){let r=e.length>0,[s,c]=useState(e),[a,u]=useState(t.length>0?t:[""]),[l,d]=useState(0),[i,p]=useState("editing-name"),[b,A]=useState(""),E=()=>{let f=s.trim();if(f.length===0||f.length>40){A("Name must be 1-40 characters");return}c(f),A(""),p("editing-cards");},R=()=>{let f=s.trim();if(f.length===0||f.length>40){A("Name must be 1-40 characters");return}let m=a.map(v=>v.trim()).filter(v=>v.length>0),y=Array.from(new Set(m));if(y.length<2){A("Need at least 2 unique non-empty cards");return}A(""),o(f,y);};return useInput((f,m)=>{if(i==="editing-cards"){if(m.leftArrow)d(y=>Math.max(0,y-1));else if(m.rightArrow)d(y=>{let v=y+1;return v>=a.length&&a.length<25?(u(k=>[...k,""]),v):Math.min(v,a.length-1)});else if(m.return)R();else if(m.escape)n();else if(m.tab)p("editing-name");else if(m.backspace){let y=a[l]||"";if(y.length===0){if(a.length>2){let v=a.filter((k,h)=>h!==l);u(v),d(Math.max(0,l-1));}}else {let v=[...a];v[l]=y.slice(0,-1),u(v);}}else if(f&&!m.ctrl&&!m.meta){let y=a[l]||"";if(y.length<10){let v=[...a];v[l]=y+f,u(v);}}}},{isActive:i==="editing-cards"}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:r?"\u2500\u2500 Edit Custom Scale \u2500\u2500":"\u2500\u2500 Create Custom Scale \u2500\u2500"}),jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Text,{children:"Name:"}),jsx(q,{value:s,onChange:c,onSubmit:E,onCancel:n,placeholder:"Scale name",isActive:i==="editing-name"})]}),i==="editing-cards"&&jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Text,{children:"Cards:"}),jsx(Box,{gap:1,flexWrap:"wrap",children:a.map((f,m)=>{let y=m===l;return jsx(Text,{inverse:y,...!y&&{color:"cyan"},children:f.length>0?f:"\xB7"},m)})})]}),b&&jsx(Text,{color:"red",children:b}),jsx(Text,{dimColor:true,children:i==="editing-name"?"\u23CE next esc cancel":"\u2190\u2192 navigate typing adds card bsp delete \u23CE save tab name esc cancel"})]})}function Ct({scales:e,selectedScaleId:t,presetOverrides:o,customScales:n=[],onSelect:r,onOverrideChange:s,onCustomScaleCreate:c,onCustomScaleEdit:a,onCustomScaleDelete:u,onClose:l,showNoneOption:d=false}){let[i,p]=useState(0),[b,A]=useState(null),[E,R]=useState("browsing"),[$,f]=useState(null),[m,y]=useState(null),v=c?[...e,{id:"__create-custom__",cards:[]}]:e,k=v.length;if(useInput((h,P)=>{if(E==="browsing"){if(P.escape){l();return}if(k===0)return;if(P.upArrow)p(g=>(g-1+k)%k);else if(P.downArrow)p(g=>(g+1)%k);else if(P.return){let g=v[i];if(!g)return;if(g.id==="__create-custom__"){R("creating");return}g.id in se?A(b===g.id?null:g.id):r(g.id);}else if(h===" "){let g=v[i];g&&g.id!=="__create-custom__"&&r(g.id);}else if(h==="e"||h==="E"){let g=v[i];a&&g?.id.startsWith("custom-")&&(f(g.id),R("editing"));}else if(h==="d"||h==="D"){let g=v[i];u&&g?.id.startsWith("custom-")&&(y(g.id),R("confirming-delete"));}}else E==="confirming-delete"&&(h==="y"||h==="Y"?(m&&u&&u(m),y(null),R("browsing")):(h==="n"||h==="N"||P.escape)&&(y(null),R("browsing")));},{isActive:E==="browsing"&&b===null||E==="confirming-delete"}),E==="creating")return jsx(nn,{onSave:(h,P)=>{c&&c(h,P),R("browsing");},onCancel:()=>R("browsing")});if(E==="editing"&&$){let h=n?.find(g=>g.id===$);if(e.find(g=>g.id===$)&&h)return jsx(nn,{initialName:h.label,initialCards:h.cards,onSave:(g,L)=>{a&&a($,g,L),f(null),R("browsing");},onCancel:()=>{f(null),R("browsing");}})}if(E==="confirming-delete"&&m){let h=v.find(g=>g.id===m),P=h?Ee(h.id,n):"Unknown";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Text,{children:["Delete ",P,"? "]}),jsx(Text,{children:"[y] yes [n] no esc cancel"})]})}return v.length===0?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{dimColor:true,children:"(no scales available)"}),jsx(Text,{dimColor:true,children:"esc back"})]}):jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{flexDirection:"column",children:v.map((h,P)=>{let g=P===i,L=h.id===t,de=b===h.id,ne=h.id in se,oe=h.id==="__create-custom__",Y=h.cards.join(", "),C=d&&h.id==="",T=C?"(none)":oe?"[+ Create custom scale]":Ee(h.id,n);return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{...g&&{color:"cyan"},children:g?">":" "}),jsx(Text,{bold:g,children:T}),!C&&!oe&&jsx(Text,{dimColor:true,children:Y}),L&&jsx(Text,{color:"cyan",children:"[current]"})]}),de&&!C&&!oe&&jsx(Box,{paddingLeft:2,children:ne?jsx(co,{scaleId:h.id,cards:se[h.id]?.cards??[],disabledIndices:o?.[h.id]??[],onOverrideChange:s,onClose:()=>A(null)}):null})]},h.id||"none")})}),jsx(Text,{dimColor:true,children:(()=>{let h=i<v.length?v[i]:null;return h?.id.startsWith("custom-")?`\u2191\u2193 navigate space select${a?" [e] edit":""}${u?" [d] delete":""} esc back`:h&&h.id in se?"\u2191\u2193 navigate \u23CE customize space select esc back":"\u2191\u2193 navigate \u23CE/space select esc back"})()})]})}function ts(e,t){return t?[...e]:e.filter(o=>o.value==="display-name")}function lo({sessionName:e,displayName:t,currentScale:o,accessMode:n,presetOverrides:r,customScales:s,isHost:c=true,onChangeName:a,onChangeScale:u,onChangeDisplayName:l,onChangeAccess:d,onClose:i}){let[p,b]=useState(r??{}),A=useMemo(()=>pt(p,s),[p,s]),[E,R]=useState("main-menu"),[$,f]=useState(e??""),[m,y]=useState(t),[v,k]=useState(n==="password"?"password":"open"),[h,P]=useState(""),[g,L]=useState(false),de=[{label:"Room name",value:"room-name",detail:`[${e??"(none)"}]`},{label:"Scale",value:"scale",detail:`[${Ee(o.id,s)}]`},{label:"Access",value:"access",detail:`[${n==="open"?"Open":"Password"}]`},{label:"Display name",value:"display-name",detail:`[${t}]`}],ne=ts(de,c);function oe(O){!c&&O!=="display-name"||(O==="room-name"?(f(e??""),R("editing-room-name")):O==="scale"?R("picking-scale"):O==="access"?R("picking-access"):O==="display-name"&&(y(t),R("editing-display-name")));}function Y(O){let B=O.trim()===""?void 0:O.trim();a(B),R("main-menu");}function C(O){let B=O.trim();B.length>0&&(l(B),process.nextTick(()=>J({displayName:B}))),R("main-menu");}function T(O){let B=A.find(z=>z.id===O);B&&u(B),R("main-menu");}function D(O,B){let z={...p};B.length===0?delete z[O]:z[O]=B,b(z),J({presetOverrides:Object.keys(z).length>0?z:void 0});}async function j(O,B){L(true);try{await d(O,B),k(O),P(O==="password"?B??"":"");}catch(z){console.error(`Failed to update access: ${z}`);}finally{L(false),R("main-menu");}}return E==="main-menu"?jsx(me,{title:"\u2500\u2500 Settings \u2500\u2500",items:ne,onSelect:oe,onClose:i}):E==="editing-room-name"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(Text,{children:"Room name: "}),jsx(q,{value:$,onChange:f,onSubmit:Y,onCancel:()=>R("main-menu"),placeholder:"(leave empty to remove)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]}):E==="editing-display-name"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(Text,{children:"Display name: "}),jsx(q,{value:m,onChange:y,onSubmit:C,onCancel:()=>R("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]}):E==="picking-scale"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(Ct,{scales:A,selectedScaleId:o.id,presetOverrides:p,onSelect:T,onOverrideChange:D,onClose:()=>R("main-menu")})]}):E==="picking-access"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),g&&jsx(Text,{dimColor:true,children:"Updating access..."}),!g&&jsx(so,{mode:v,password:h,onModeChange:O=>{O==="open"&&j("open");},onPasswordChange:P,onClose:()=>R("main-menu")})]}):jsx(Box,{})}function It({participants:e,onlineIds:t,hostId:o,votes:n,revealed:r,participantId:s}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{bold:true,children:["Participants (",e.length,")"]}),e.map(c=>{let a=t.has(c.id),u=a?"\u25CF":"\u25CB",l=a?"green":"gray",d=c.id===o,i=Ie(c)==="viewer",p=c.id===s,b=c.id in n,A=i?" (viewer)":r?n[c.id]?` \u2192 ${n[c.id]}`:"":b?" \u2713":" \xB7",E=p&&!i&&!(r&&n[c.id]);return jsxs(Box,{gap:1,children:[jsx(Text,{color:l,children:u}),jsxs(Text,{children:[c.displayName,d?" (host)":""]}),E?jsx(Text,{color:"cyan",children:"(voter)"}):jsx(Text,{color:i?"gray":b?"green":"gray",children:A})]},c.id)})]})}var ns=[{label:"End session for everyone",value:"end-session",detail:"Disconnects all participants. Cannot be undone."}];function po({onPick:e,onClose:t}){return jsx(me,{title:"Host Actions",items:ns,onSelect:e,onClose:t})}function Tt({roomCode:e,onPick:t,onClose:o}){let n=[{label:"Copy code",value:"code",detail:St(e)},{label:"Copy share link",value:"url",detail:xt(e)},{label:"Copy npx command",value:"npx",detail:wt(e)}];return jsx(me,{title:"Share",items:n,onSelect:r=>t(r),onClose:o})}function ss(e){let t=e.rounds.filter(n=>W(n)!==null),o=Object.fromEntries(e.participants.map(n=>[n.id,n]));return _n({rounds:t,participants:o})}async function fo(e,t,o){let n=ss(e);try{await t(n),o("Results copied to clipboard");}catch{o("Clipboard write failed");}}function mo(e,t,o){let n=kn(e.id,o);return n===null?`Round ${t}`:`Round ${n.depth}/${n.total} [re-vote]`}function go(e,t,o){let n=mo(e,t,o),r=e.title?` \u2014 ${e.title}`:"",s=e.ticketId?` [${e.ticketId}]`:"",c=W(e)==="skipped"?" \u2014 Skipped":" \u2014 Results";return `${n}${r}${s}${c}`}function ho(e){let t=Object.values(e).filter(d=>!pe(d)).map(d=>parseFloat(d)).filter(d=>!isNaN(d)).toSorted((d,i)=>d-i);if(t.length===0)return {average:"-",median:"-",agreement:"-"};let n=t.reduce((d,i)=>d+i,0)/t.length,r=Math.floor(t.length/2),s=t.length%2===0?(t[r-1]+t[r])/2:t[r],c=Object.values(e).filter(d=>!pe(d)),a=new Map;for(let d of c)a.set(d,(a.get(d)??0)+1);let u=Math.max(...a.values()),l=c.length>0?Math.round(u/c.length*100):0;return {average:n.toFixed(1),median:s.toFixed(1),agreement:`${l}%`}}function rn(e,t){let o=Math.floor((t-e)/1e3),n=Math.floor(o/60),r=o%60;return `${n}:${r.toString().padStart(2,"0")}`}function So(e,t,o=[]){let n=mo(e,t,o);if(W(e)==="skipped"){let i=e.title?` ${e.title}`:"",p=e.ticketId?` [${e.ticketId}]`:"";return `${n}:${i}${p} \u2014 Skipped`}let r=new Map;for(let i of Object.values(e.votes))pe(i)||r.set(i,(r.get(i)??0)+1);let s=[...r.entries()].toSorted((i,p)=>p[1]-i[1]||i[0].localeCompare(p[0])).map(([i,p])=>`${i}\xD7${p}`).join(", "),c=Object.values(e.votes).filter(pe).length,a=c>0?` (${c} abstained)`:"",u=e.title?` ${e.title}`:"",l=e.ticketId?` [${e.ticketId}]`:"",d=e.timerStartedAt!==void 0&&e.revealedAt!==void 0?` \u2014 ${rn(e.timerStartedAt,e.revealedAt)}`:"";return `${n}:${u}${l} \u2014 ${s||"(no votes)"}${a}${d}`}function xo({projection:e,onlineIds:t,isHost:o,participantId:n,rounds:r,currentRound:s,settingsOpen:c,onStartRound:a,onNewRound:u,onRevote:l,onOpenSettings:d,onHandoffHost:i,onEndSession:p,onShare:b,shareOpen:A,onSetShareOpen:E,roomCode:R,confirmingQuit:$,myRole:f,onToggleRole:m,roundTitlePromptActive:y,roundTitleInput:v,onRoundTitleChange:k,onRoundTitleSubmit:h,onRoundTitleCancel:P,roundTicketIdPromptActive:g,roundTicketIdInput:L,onRoundTicketIdChange:de,onRoundTicketIdSubmit:ne,onRoundTicketIdCancel:oe,descriptorPromptActive:Y,descriptorInput:C,onDescriptorChange:T,onDescriptorSubmit:D,onDescriptorCancel:j,onEditDescriptor:O,canExport:B,onExportResults:z}){let[X,re]=Et.useState("idle"),[xe,ve]=Et.useState(null),[fe,le]=Et.useState(false),[Ce,be]=Et.useState(false);useEffect(()=>{o||(re("idle"),ve(null),le(false),be(false));},[o]),useInput(w=>{if(w==="c"||w==="C"){E(true);return}if(w==="w"||w==="W"){m();return}if((w==="x"||w==="X")&&B){z();return}o&&((w==="e"||w==="E")&&d(),(w==="s"||w==="S")&&a(),(w==="h"||w==="H")&&re("picking"),(w==="m"||w==="M")&&le(true),s!==null&&W(s)!==null&&((w==="n"||w==="N")&&u(),(w==="v"||w==="V")&&W(s)!=="skipped"&&l(),(w==="t"||w==="T")&&O()));},{isActive:!c&&!$&&X==="idle"&&!y&&!g&&!fe&&!Ce&&!A&&!Y}),useInput((w,Z)=>{w==="y"||w==="Y"?(p(),be(false)):(w==="n"||w==="N"||Z.escape)&&be(false);},{isActive:Ce});let ue=e.participants.filter(w=>w.id!==n&&t.has(w.id));useInput(w=>{if(X==="picking"){let Z=parseInt(w,10);!isNaN(Z)&&Z>=1&&Z<=ue.length?(ve(ue[Z-1].id),re("confirming")):(w==="Escape"||w==="q"||w==="Q")&&re("idle");}},{isActive:X==="picking"}),useInput(w=>{X==="confirming"&&xe&&(w==="y"||w==="Y"?(i(xe),re("idle"),ve(null)):(w==="n"||w==="N"||w==="Escape")&&(re("idle"),ve(null)));},{isActive:X==="confirming"});let et=r.length>0,je=r.filter(w=>W(w)!==null),tt=s!==null?je.slice(0,-1):je;return fe?jsx(po,{onPick:w=>{le(false),w==="end-session"&&be(true);},onClose:()=>le(false)}):A?jsx(Tt,{roomCode:R,onPick:w=>{E(false),b(w);},onClose:()=>E(false)}):jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:et?"Session":"Waiting for participants..."}),!et&&jsx(Text,{dimColor:true,children:"No rounds started yet."}),jsx(It,{participants:e.participants,onlineIds:t,hostId:e.settings.hostParticipantId,votes:{},revealed:false,participantId:n}),s!==null&&W(s)!==null&&jsx(as,{projection:e,round:s,rounds:r}),tt.length>0&&jsxs(Box,{flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"\u2500\u2500 History \u2500\u2500"}),tt.map(w=>{let Z=r.indexOf(w)+1;return jsx(Text,{dimColor:true,children:So(w,Z,r)},w.id)})]}),X==="picking"&&ue.length>0&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Hand off to:"}),ue.map((w,Z)=>jsxs(Text,{children:["[",Z+1,"] ",w.displayName]},w.id)),jsx(Text,{dimColor:true,children:"[q] Cancel"})]}),X==="picking"&&ue.length===0&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{dimColor:true,children:"No other online participants"}),jsx(Text,{dimColor:true,children:"[q] Cancel"})]}),X==="confirming"&&xe&&jsx(Box,{flexDirection:"column",children:jsxs(Text,{children:["Hand off to ",e.participants.find(w=>w.id===xe)?.displayName,"? [y/n]"]})}),y&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Round title (optional, Enter to skip):"}),jsx(q,{value:v,onChange:k,onSubmit:h,onCancel:P,placeholder:"Enter to skip",isActive:y})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),g&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Ticket ID (optional, Enter to skip):"}),jsx(q,{value:L,onChange:de,onSubmit:ne,onCancel:oe,placeholder:"e.g. PROJ-1234",isActive:g})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),Y&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Edit round title:"}),jsx(q,{value:C,onChange:T,onSubmit:D,onCancel:j,placeholder:"Enter to save",isActive:Y})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel \xB7 empty submit cancels"})]}),Ce&&jsxs(Box,{children:[jsx(Text,{color:"red",children:"End session for everyone? This cannot be undone. "}),jsx(Text,{dimColor:true,children:"y/n [Esc] Cancel"})]}),X==="idle"&&!y&&!g&&!Y&&!Ce&&jsxs(Box,{gap:2,children:[o?jsx(Fragment,{children:s!==null&&W(s)!==null?jsxs(Fragment,{children:[W(s)!=="skipped"&&jsx(Text,{color:"yellow",children:"[v] Revote"}),jsx(Text,{color:"yellow",children:"[n] Next"}),jsx(Text,{color:"yellow",children:"[t] Edit title"}),jsx(Text,{color:"yellow",children:"[h] Handoff"}),jsx(Text,{color:"yellow",children:"[e] Settings"}),jsx(Text,{color:"yellow",children:"[c] Share"}),B&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",f==="viewer"?"Vote":"Observe"]}),jsx(Text,{color:"yellow",children:"[m] Menu"})]}):jsxs(Fragment,{children:[jsx(Text,{color:"yellow",children:"[s] Start round"}),jsx(Text,{color:"yellow",children:"[h] Handoff"}),jsx(Text,{color:"yellow",children:"[e] Settings"}),jsx(Text,{color:"yellow",children:"[c] Share"}),B&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",f==="viewer"?"Vote":"Observe"]}),jsx(Text,{color:"yellow",children:"[m] Menu"})]})}):jsxs(Fragment,{children:[jsx(Text,{dimColor:true,children:"Waiting for host to start a round..."}),jsx(Text,{children:"[c] Share"}),B&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",f==="viewer"?"Vote":"Observe"]})]}),jsx(Text,{children:"[q] Quit"})]})]})}function as({projection:e,round:t,rounds:o}){let n=o.indexOf(t)+1,r=go(t,n,o);if(W(t)==="skipped")return jsx(Box,{flexDirection:"column",gap:1,children:jsx(Text,{bold:true,children:r})});let s=ho(t.votes),c=new Map(e.participants.map(p=>[p.id,p.displayName])),a=t.timerStartedAt!==void 0&&t.revealedAt!==void 0?rn(t.timerStartedAt,t.revealedAt):null,u=Object.entries(t.votes),l=u.filter(([,p])=>!pe(p)),d=u.filter(([,p])=>pe(p)).map(([p])=>p),i=l[0]?.[1];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:r}),Nn(t)&&i!==void 0&&jsxs(Text,{bold:true,color:"green",children:["Consensus! Everyone voted ",i]}),jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:2,children:[jsx(Text,{bold:true,underline:true,children:"Name".padEnd(20)}),jsx(Text,{bold:true,underline:true,children:"Estimate".padEnd(10)})]}),l.map(([p,b])=>jsxs(Box,{gap:2,children:[jsx(Text,{children:(c.get(p)??p).padEnd(20)}),jsx(Text,{color:"cyan",bold:true,children:b.padEnd(10)})]},p)),d.map(p=>jsxs(Box,{gap:2,children:[jsx(Text,{dimColor:true,children:(c.get(p)??p).padEnd(20)}),jsx(Text,{dimColor:true,children:"(abstained)".padEnd(10)})]},p)),e.participants.filter(p=>!(p.id in t.votes)).map(p=>jsxs(Box,{gap:2,children:[jsx(Text,{dimColor:true,children:p.displayName.padEnd(20)}),jsx(Text,{dimColor:true,children:"(no vote)".padEnd(10)})]},p.id))]}),jsxs(Box,{gap:2,children:[jsxs(Text,{children:["Avg: ",jsx(Text,{bold:true,children:s.average})]}),jsxs(Text,{children:["Med: ",jsx(Text,{bold:true,children:s.median})]}),jsxs(Text,{children:["Agreement: ",jsx(Text,{bold:true,children:s.agreement})]}),a!==null&&jsxs(Text,{dimColor:true,children:["\u23F1 ",a]})]})]})}function vo({scale:e,selected:t,onSelect:o,onClear:n,disabled:r}){let[s,c]=useState(0);return useInput((a,u)=>{if(!r)if(u.leftArrow)c(l=>Math.max(0,l-1));else if(u.rightArrow)c(l=>Math.min(e.cards.length-1,l+1));else if(u.return){let l=e.cards[s];l===t?n():o(l);}else (u.backspace||u.delete)&&n();}),jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Box,{gap:1,children:e.cards.map((a,u)=>{let l=u===s,d=a===t;return jsx(Text,{inverse:l,bold:d,...d&&{color:"cyan"},children:d?`[${a}]`:` ${a} `},a)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate \u23CE select \u232B clear"})]})}function ps(e){let t=Math.floor(e/1e3),o=Math.floor(t/60),n=t%60;return `${o}:${n.toString().padStart(2,"0")}`}function Co({projection:e,round:t,onlineIds:o,isHost:n,myId:r,myRole:s,elapsedMs:c,roomCode:a,shareOpen:u,settingsOpen:l,onVote:d,onClearVote:i,onReveal:p,onSkip:b,onToggleRole:A,onShare:E,onSetShareOpen:R,onOpenSettings:$,confirmingQuit:f}){let m=t.votes[r],y=m!==void 0&&pe(m);if(useInput(g=>{if(g==="e"||g==="E"){$();return}if(g==="c"||g==="C"){R(true);return}if(s==="voter"&&(g==="a"||g==="A")){y?i():d(rt);return}n&&(g==="r"||g==="R")&&p(),n&&(g==="s"||g==="S")&&b(),(g==="w"||g==="W")&&A();},{isActive:!f&&!l&&!u}),u)return jsx(Tt,{roomCode:a,onPick:g=>{R(false),E(g);},onClose:()=>R(false)});let v=m,k=e.rounds.indexOf(t)+1,h=t.title?` \u2014 ${t.title}`:"",P=t.ticketId?` [${t.ticketId}]`:"";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Box,{gap:2,children:[jsxs(Text,{bold:true,children:["Round ",k,h,P]}),c!==void 0&&jsxs(Text,{dimColor:true,children:["\u23F1 ",ps(c)]})]}),jsxs(Box,{gap:4,children:[jsx(It,{participants:e.participants,onlineIds:o,hostId:e.settings.hostParticipantId,votes:t.votes,revealed:false}),s==="viewer"?jsx(Box,{flexDirection:"column",children:jsx(Text,{dimColor:true,children:"You're observing"})}):jsxs(Box,{flexDirection:"column",gap:1,children:[y&&jsx(Text,{dimColor:true,children:"(abstaining this round \u2014 press [a] to vote)"}),jsx(vo,{scale:t.scale,selected:y?void 0:v,onSelect:d,onClear:i,disabled:f||y})]})]}),jsxs(Box,{gap:2,children:[n&&jsx(Text,{color:"yellow",children:"[r] Reveal"}),n&&jsx(Text,{color:"yellow",children:"[s] Skip"}),s==="voter"&&jsxs(Text,{color:"yellow",children:["[a] ",y?"Vote":"Abstain"]}),jsxs(Text,{color:"yellow",children:["[w] ",s==="viewer"?"Vote":"Observe"]}),jsx(Text,{children:"[e] Settings"}),jsx(Text,{children:"[c] Share"}),jsx(Text,{children:"[q] Quit"})]})]})}var hs=3e3;function Pt(e=hs){let[t,o]=useState(null),n=useRef(null),r=useCallback(()=>{n.current!==null&&(clearTimeout(n.current),n.current=null);},[]),s=useCallback(a=>{r(),o(a),n.current=setTimeout(()=>{o(null),n.current=null;},e);},[r,e]),c=useCallback(()=>{r(),o(null);},[r]);return useEffect(()=>()=>{r();},[r]),{notice:t,show:s,dismiss:c}}function ws(e){let t=ee(e);return !t||W(t)!==null?"lobby":"voting"}function kt({session:e,participantId:t,displayName:o,accessMode:n,presetOverrides:r,customScales:s}){let{exit:c}=useApp(),[a,u]=useState(e.projection()),[l,d]=useState("connecting"),[i,p]=useState(e.onlineIds()),[b,A]=useState(),[E,R]=useState(false),[$,f]=useState(n==="password"?"password":"open"),[m,y]=useState(o),[v,k]=useState(false),[h,P]=useState(false),[g,L]=useState(""),[de,ne]=useState(false),[oe,Y]=useState(""),[C,T]=useState(),[D,j]=useState(false),[O,B]=useState(""),[z,X]=useState(null),re=Pt(3e3),[xe,ve]=useState(false),fe=Pt(3e3),le=Pt(3e3);useEffect(()=>{let I=e.onChange(()=>{u(e.projection()),p(e.onlineIds());}),_=e.onStatusChange(d),Oe=e.onHostChange(nt=>{let Qo=e.projection().participants.find(Zo=>Zo.id===nt),Ko=nt===t?"You are now the host":`${Qo?.displayName||"Unknown"} is now the host`;re.show(Ko);}),Xo=setInterval(()=>{p(e.onlineIds());let nt=e.projection(),ot=ee(nt);ot?.timerStartedAt!==void 0&&ot.revealedAt===void 0?A(Date.now()-ot.timerStartedAt):A(void 0);},1e3);return ()=>{I(),_(),Oe(),clearInterval(Xo);}},[e,t,re.show]),useInput(I=>{(I==="q"||I==="Q")&&k(true);},{isActive:!E&&!v&&!h&&!de&&!D&&!xe}),useInput((I,_)=>{I==="y"||I==="Y"?(e.disconnect(),c()):(I==="n"||I==="N"||_.escape)&&k(false);},{isActive:v});let Ce=ws(a),be=ee(a),ue=a.settings.hostParticipantId===t,et=a.participants.find(I=>I.id===t),je=Ie(et??{}),tt=useCallback(()=>{L(""),P(true);},[]),w=useCallback(I=>{P(false),L(""),T(Gt(I)),Y(""),ne(true);},[]),Z=useCallback(()=>{P(false),L(""),T(void 0);},[]),No=useCallback(I=>{ne(false),Y("");let[_,Oe]=Kn(C,I);e.newRound(_,Oe),T(void 0);},[e,C]),Po=useCallback(()=>{ne(false),Y(""),T(void 0);},[]),Do=useCallback(()=>{let I=e.current();!I||I.revealedAt===void 0||(X(I.id),B(I.title??""),j(true));},[e]),ko=useCallback(I=>{let _=z;if(j(false),X(null),!_)return;let Oe=I.trim();Oe!==""&&e.updateRoundDescriptor(_,{title:Oe});},[e,z]),Oo=useCallback(()=>{j(false),X(null);},[]),Mo=useCallback(I=>{e.vote(I);},[e]),$o=useCallback(()=>{e.unvote();},[e]),Bo=useCallback(()=>{e.reveal();},[e]),Ho=useCallback(()=>{e.skip();},[e]),Uo=useCallback(()=>{L(""),P(true);},[]),Lo=useCallback(()=>{e.revote();},[e]),ln=useCallback(()=>{e.toggleRole();},[e]),jo=useCallback(I=>{e.updateName(I);},[e]),_o=useCallback(I=>{e.updateScale(I);},[e]),Vo=useCallback(I=>{e.updateDisplayName(I),y(I);},[e]),Fo=useCallback(async(I,_)=>{await e.updateAccess(I,_),f(I);},[e]),Yo=useCallback(I=>{try{e.handoffHost(I);}catch(_){console.error(`Handoff failed: ${_ instanceof Error?_.message:String(_)}`);}},[e]),un=useCallback(()=>{R(true);},[]),Jo=useCallback(()=>{R(false);},[]),Wo=useCallback(()=>{e.endSessionForEveryone();},[e]),pn=useCallback(async I=>{let _=I==="code"?St(e.roomCode):I==="url"?xt(e.roomCode):wt(e.roomCode);try{await Ro.write(_),fe.show("Copied!");}catch{fe.show(`Copy failed \u2014 ${_}`);}},[e.roomCode,fe]),$t=a.rounds.filter(I=>W(I)!==null),qo=$t.length>0?$t.at(-1):null,Go=$t.length>0,zo=useCallback(()=>fo(a,I=>Ro.write(I),le.show),[a,le.show]);return jsxs(Box,{flexDirection:"column",children:[jsx(to,{roomCode:e.roomCode,sessionName:a.settings.name,status:l,isHost:ue}),re.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:re.notice})}),fe.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:fe.notice.startsWith("Copy failed")?"red":"green",children:fe.notice})}),le.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:le.notice.startsWith("Clipboard write failed")?"red":"green",children:le.notice})}),E?jsx(lo,{sessionName:a.settings.name,displayName:m,currentScale:a.settings.defaultScale,accessMode:$,presetOverrides:r,customScales:s,isHost:ue,onChangeName:jo,onChangeScale:_o,onChangeDisplayName:Vo,onChangeAccess:Fo,onClose:Jo}):Ce==="lobby"?jsx(xo,{projection:a,onlineIds:i,isHost:ue,participantId:t,rounds:a.rounds,currentRound:qo,settingsOpen:E,onStartRound:tt,onNewRound:Uo,roundTitlePromptActive:h,roundTitleInput:g,onRoundTitleChange:L,onRoundTitleSubmit:w,onRoundTitleCancel:Z,roundTicketIdPromptActive:de,roundTicketIdInput:oe,onRoundTicketIdChange:Y,onRoundTicketIdSubmit:No,onRoundTicketIdCancel:Po,onRevote:Lo,onOpenSettings:un,onHandoffHost:Yo,onEndSession:Wo,onShare:pn,shareOpen:xe,onSetShareOpen:ve,roomCode:e.roomCode,confirmingQuit:v,myRole:je,onToggleRole:ln,descriptorPromptActive:D,descriptorInput:O,onDescriptorChange:B,onDescriptorSubmit:ko,onDescriptorCancel:Oo,onEditDescriptor:Do,canExport:Go,onExportResults:zo}):Ce==="voting"&&be?jsx(Co,{projection:a,round:be,onlineIds:i,isHost:ue,myId:t,myRole:je,elapsedMs:b,onVote:Mo,onClearVote:$o,onReveal:Bo,onSkip:Ho,onToggleRole:ln,onShare:pn,onSetShareOpen:ve,shareOpen:xe,settingsOpen:E,onOpenSettings:un,roomCode:e.roomCode,confirmingQuit:v}):null,v&&jsx(Box,{children:jsx(Text,{dimColor:true,children:"Leave session? y/n"})})]})}function Io({presetOverrides:e,customScales:t}){let{exit:o}=useApp(),[n,r]=useState("main-menu"),[s,c]=useState(Re()),[a,u]=useState(s.displayName??""),[l,d]=useState(s.relayUrl??""),[i,p]=useState(s.defaultSessionName??""),[b,A]=useState(t??[]),[E,R]=useState(e??{});useInput(C=>{(C==="q"||C==="Q")&&o();},{isActive:n==="main-menu"});let $=useMemo(()=>pt(E,b),[E,b]),f=s.defaultScale,m=f?$.find(C=>C.id===f):void 0,y=[{label:"Display name",value:"display-name",detail:`[${s.displayName??"(none)"}]`},{label:"Relay URL",value:"relay-url",detail:`[${s.relayUrl??"(none)"}]`},{label:"Default scale",value:"default-scale",detail:`[${m?Ee(m.id,b):"(none)"}]`},{label:"Default session name",value:"default-session-name",detail:`[${s.defaultSessionName??"(none)"}]`},{label:"Default password",value:"default-password",detail:`[${s.defaultPassword?"on":"off"}]`}];function v(C){C==="display-name"?(u(s.displayName??""),r("editing-display-name")):C==="relay-url"?(d(s.relayUrl??""),r("editing-relay-url")):C==="default-scale"?r("picking-scale"):C==="default-session-name"?(p(s.defaultSessionName??""),r("editing-session-name")):C==="default-password"&&r("picking-default-password");}function k(C){let T=C.trim();if(T.length>0){let D={...s,displayName:T};c(D),J({displayName:T});}r("main-menu");}function h(C){let T=C.trim();if(T.length>0){let D={...s,relayUrl:T};c(D),J({relayUrl:T});}r("main-menu");}function P(C){let T=C.trim(),D=T.length>0?{...s,defaultSessionName:T}:{...s};T.length===0?(delete D.defaultSessionName,c(D),Fe({defaultSessionName:""})):(c(D),J({defaultSessionName:T})),r("main-menu");}function g(C){let T=C.length>0?{...s,defaultScale:C}:{...s};C.length===0?(delete T.defaultScale,c(T),Fe({defaultScale:""})):(c(T),J({defaultScale:C})),r("main-menu");}function L(C,T){let D={...E};T.length===0?delete D[C]:D[C]=T,R(D),J({presetOverrides:Object.keys(D).length>0?D:void 0});}function de(C){let T=C==="on",D={...s,defaultPassword:T};c(D),J({defaultPassword:T}),r("main-menu");}function ne(C,T){let D=`custom-${randomUUID()}`,j=[...b,{id:D,label:C,cards:T}];A(j),c({...s,customScales:j}),J({customScales:j});}function oe(C,T,D){let j=b.map(O=>O.id===C?{id:C,label:T,cards:D}:O);A(j),c({...s,customScales:j}),J({customScales:j});}function Y(C){let T=b.filter(j=>j.id!==C);A(T);let D={...s,customScales:T};s.defaultScale===C?(D.defaultScale="fibonacci",J({customScales:T,defaultScale:"fibonacci"})):J({customScales:T}),c(D);}if(n==="main-menu")return jsx(me,{title:"\u2500\u2500 Config Settings \u2500\u2500",items:y,onSelect:v,onClose:()=>o()});if(n==="editing-display-name")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Display name: "}),jsx(q,{value:a,onChange:u,onSubmit:k,onCancel:()=>r("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(n==="editing-relay-url")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Relay URL: "}),jsx(q,{value:l,onChange:d,onSubmit:h,onCancel:()=>r("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(n==="editing-session-name")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Default session name: "}),jsx(q,{value:i,onChange:p,onSubmit:P,onCancel:()=>r("main-menu"),placeholder:"(leave empty to clear)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(n==="picking-scale"){let C=[{id:"",cards:[]},...$];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Ct,{scales:C,selectedScaleId:f??"",presetOverrides:E,customScales:b,onSelect:g,onOverrideChange:L,onCustomScaleCreate:ne,onCustomScaleEdit:oe,onCustomScaleDelete:Y,onClose:()=>r("main-menu"),showNoneOption:true})]})}if(n==="picking-default-password"){let C=[{label:"On",value:"on",detail:s.defaultPassword?"[current]":void 0},{label:"Off",value:"off",detail:s.defaultPassword?void 0:"[current]"}];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(me,{title:"Default password:",items:C,onSelect:de,onClose:()=>r("main-menu")})]})}return jsx(Box,{})}async function dn(){return new Promise(e=>{let t=createInterface({input:process.stdin,output:process.stderr});process.stderr.write("Password: "),t.question("",o=>{t.close(),e(o);});})}async function As(e){let t=await Ve(),o=e.scale??t.defaultScale??"fibonacci",n=e.name??t.defaultSessionName,r=e.password??t.defaultPassword??false,s;r&&(s=await dn());let c=ut(o,t.presetOverrides,t.customScales);if(!c){let i=Object.keys(se).join(", ");console.error(`Unknown or fully-disabled scale: "${o}". Builtin IDs: ${i}`),process.exit(1);}let a=await qn({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,sessionName:n,password:s,defaultScale:c}),u;s&&(u=await Te(s,a.roomUuid)),mt({roomCode:a.roomCode,roomUuid:a.roomUuid,passwordHash:u,lastSeenAt:Date.now()}),console.error(`Room created: ${a.roomCode}`),console.error(`Share: hnch join ${a.roomCode}`),console.error("");let{waitUntilExit:l,unmount:d}=render(Et.createElement(kt,{session:a,participantId:t.participantId,displayName:t.displayName,accessMode:s?"password":"open",presetOverrides:t.presetOverrides,customScales:t.customScales}));ht({doc:a.doc,localParticipantId:t.participantId,onEnded:async i=>{console.error(i.isLocal?"Session ended.":`Session ended by ${i.hostName}.`),d();try{await V();}catch(p){console.error(`Failed to clear cached session: ${p instanceof Error?p.message:String(p)}`);}a.disconnect(),process.exit(0);}}),await l(),a.disconnect(),V(),process.exit(0);}async function Ns(e){let t=await Ve(),o=zn(e.code);o===null&&(console.error("invalid room code"),process.exit(1));let n;e.password&&(n=await dn());let r=await We(t.relayUrl,o),s;r.accessMode==="password"&&!e.password?s=await dn():e.password&&(s=n);let c,a=false,u=await Gn({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,roomCode:o,password:s,onRejection(i){if(i==="unknown-room"){gt({clearLastSession:V,logger:console,exit:process.exit});return}i==="room-full"&&(a=true,c?.());}}),l;s&&(l=await Te(s,u.roomUuid)),mt({roomCode:u.roomCode,roomUuid:u.roomUuid,passwordHash:l,lastSeenAt:Date.now()}),console.error(`Joined room: ${u.roomCode}`),console.error("");let d=render(Et.createElement(kt,{session:u,participantId:t.participantId,displayName:t.displayName,accessMode:r.accessMode,presetOverrides:t.presetOverrides,customScales:t.customScales}));c=d.unmount,ht({doc:u.doc,localParticipantId:t.participantId,onEnded:async i=>{console.error(i.isLocal?"Session ended.":`Session ended by ${i.hostName}.`),c?.();try{await V();}catch(p){console.error(`Failed to clear cached session: ${p instanceof Error?p.message:String(p)}`);}u.disconnect(),process.exit(0);}}),await d.waitUntilExit(),a&&(console.error("This room is full (max 20 participants)."),u.disconnect(),V(),process.exit(1)),u.disconnect(),V(),process.exit(0);}async function Ps(){let e=await Ve(),t=Qn();t||(console.error("No recent session to resume."),process.exit(0));let o;try{o=await We(e.relayUrl,t.roomCode);}catch(d){if((d instanceof Error?d.message:String(d)).includes("Room not found"))return await gt({clearLastSession:V,logger:console,exit:process.exit});console.error("Could not reach relay \u2014 try again later."),process.exit(0);}o.accessMode==="password"&&!t.passwordHash&&(console.error(`Password changed \u2014 rejoin with: hnch join ${t.roomCode} --password`),V(),process.exit(0)),console.error(`Rejoining room ${t.roomCode}\u2026`),console.error("");let n=new Me.Doc,r=new Awareness(n);lt(n,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId);let s=false,c=false,a,u=ft({doc:n,awareness:r,roomCode:t.roomCode,roomUuid:t.roomUuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t.passwordHash,onRejection(d){if(d==="unknown-room"){gt({clearLastSession:V,logger:console,exit:process.exit});return}d==="wrong-password"&&(s=true,a?.()),d==="room-full"&&(c=true,a?.());}});mt({roomCode:u.roomCode,roomUuid:u.roomUuid,passwordHash:t.passwordHash,lastSeenAt:Date.now()});let l=render(Et.createElement(kt,{session:u,participantId:e.participantId,displayName:e.displayName,accessMode:o.accessMode,presetOverrides:e.presetOverrides,customScales:e.customScales}));a=l.unmount,ht({doc:u.doc,localParticipantId:e.participantId,onEnded:async d=>{console.error(d.isLocal?"Session ended.":`Session ended by ${d.hostName}.`),a?.();try{await V();}catch(i){console.error(`Failed to clear cached session: ${i instanceof Error?i.message:String(i)}`);}u.disconnect(),process.exit(0);}}),await l.waitUntilExit(),c&&(console.error("This room is full (max 20 participants)."),V(),process.exit(1)),s&&(console.error(`Password changed \u2014 rejoin with: hnch join ${t.roomCode} --password`),V(),process.exit(0)),u.disconnect(),V(),process.exit(0);}async function Ds(e){if(!(e.name!==void 0||e.relayUrl!==void 0||e.scale!==void 0||e.sessionName!==void 0||e.password!==void 0)){let n=await Ve(),{waitUntilExit:r}=render(Et.createElement(Io,{presetOverrides:n.presetOverrides,customScales:n.customScales}));await r(),process.exit(0);}let o={};if(e.name!==void 0&&(o.displayName=e.name),e.relayUrl!==void 0&&(o.relayUrl=e.relayUrl),e.scale!==void 0){if(e.scale!==""){let n=Re();if(!ut(e.scale,n.presetOverrides,n.customScales)){console.error(`Unknown scale: "${e.scale}". Builtin IDs: ${Object.keys(se).join(", ")}`);return}}o.defaultScale=e.scale;}e.sessionName!==void 0&&(o.defaultSessionName=e.sessionName),e.password!==void 0&&(o.defaultPassword=e.password),Fe(o),console.log("Config updated.");}var Ao=Is(hideBin(process.argv)).scriptName("hnch").usage("$0 <command> \u2014 terminal pointing poker").command("create","Create a new room",e=>e.option("name",{type:"string",describe:"Session name"}).option("password",{type:"boolean",describe:"Protect room with a password"}).option("scale",{type:"string",describe:"Estimation scale ID (fibonacci, t-shirt, powers-of-2, linear, risk, or custom-<id>)"}),e=>{As(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("join <code>","Join an existing room",e=>e.positional("code",{type:"string",demandOption:true,describe:"6-character room code"}).option("password",{type:"boolean",describe:"Room requires a password",default:false}),e=>{Ns(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("resume","Rejoin your last session",e=>e,()=>{Ps().catch(e=>{console.error(e instanceof Error?e.message:e),process.exit(1);});}).command("config","View or update CLI config",e=>e.option("name",{type:"string",describe:"Set display name"}).option("relay-url",{type:"string",describe:"Set relay URL"}).option("scale",{type:"string",describe:"Set default estimation scale ID (empty string clears)"}).option("session-name",{type:"string",describe:"Set default session name (empty string clears)"}).option("password",{type:"boolean",describe:"Set default password prompt on (--password) or off (--no-password)"}),e=>{Ds(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).demandCommand(1,"Specify a command: create, join, resume, or config").strict().help(),cn=hideBin(process.argv);(cn.length===0||cn.length===1&&cn[0]==="--")&&(Ao.showHelp(),process.exit(0));Ao.parse();
20
+ `}function Nt(e,t,n){if(e.startsWith("custom-")){let r=(n??[]).find(i=>i.id===e);return r?{id:r.id,cards:r.cards}:void 0}let o=ae[e];if(o){let r=(t??{})[e]??[];if(r.length===0)return o;let i=o.cards.filter((a,s)=>!r.includes(s));return i.length===0?void 0:{id:e,cards:i}}}function Pt(e,t){let n=Object.keys(ae).map(r=>Nt(r,e,t)).filter(r=>r!==void 0),o=(t??[]).map(r=>({id:r.id,cards:r.cards}));return [...n,...o]}function Me(e,t){if(e.startsWith("custom-")){let n=(t??[]).find(o=>o.id===e);if(n&&n.label.trim().length>0)return n.label}return Wn(e)}async function xo(e,t){let n=await fetch(`${e}/rooms`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({})});if(!n.ok)throw new Error(`POST /rooms failed: ${n.status}`);return await n.json()}async function de(e,t){let n=await fetch(`${e}/rooms/${encodeURIComponent(t)}`);if(n.status===404){let o=await n.json().catch(()=>null);throw new Error(`Room not found: ${o?.reason??"unknown-room"}`)}if(!n.ok)throw new Error(`GET /rooms/:code failed: ${n.status}`);return await n.json()}async function Sn(e,t,n){let o=await fetch(`${e}/rooms/${t}/access`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify({passwordHash:n})});if(!o.ok)throw new Error(`PATCH /rooms/:uuid/access failed: ${o.status}`)}function wo(e){let n=`${e.wsBaseUrl.replace(/^http/,"ws")}/ws`,o={did:e.deviceId};e.passwordHash!==void 0&&(o.pw=e.passwordHash);let r=new WebsocketProvider(n,e.roomUuid,e.doc,{params:o,connect:true,...e.awareness!==void 0&&{awareness:e.awareness},WebSocketPolyfill:bi}),i=u=>{e.onStatusChange?.(u.status);},a=u=>{if(u===null)return;let c=_n.get(u.code);c!==void 0&&(e.onRejection?.(c),r.shouldConnect=false,r.disconnect());};r.on("status",i),r.on("connection-close",a);let s=false,l=e.passwordHash;return {doc:e.doc,awareness:r.awareness,updateCredentials(u){if(u.passwordHash===l)return;l=u.passwordHash??void 0,r.shouldConnect=false,r.disconnect();let d={did:r.params.did??""};l!==void 0&&(d.pw=l),r.params=d,r.connect();},disconnect(){s||(s=true,r.off("status",i),r.off("connection-close",a),r.shouldConnect=false,r.disconnect(),r.destroy());}}}var Ai=5e3;function yo(e,t,n){let o=null,r=null;function i(){let c=new Set;return t.getStates().forEach(d=>{let p=d.participantId;typeof p=="string"&&c.add(p);}),c}function a(){return e.getMap(it).get("hostParticipantId")}function s(){r!==null&&(clearTimeout(r),r=null),o=null;}function l(){let c=a(),d=o;if(o=null,!d||c!==d)return;let p=i();if(p.has(c))return;let b=[...p].toSorted();if(b.length===0)return;let E=b[0];E===n&&Je(e,{hostParticipantId:E});}function u(){let c=a();if(!c)return;if(i().has(c)){s();return}o!==c&&(s(),o=c,r=setTimeout(()=>{r=null,l();},Ai));}return t.on("change",u),e.getMap(it).observe(u),u(),{stop(){s(),t.off("change",u),e.getMap(it).unobserve(u);}}}async function Io(e){let t,n=await xo(e.relayUrl);e.password&&(t=await Oe(e.password,n.uuid),await Sn(e.relayUrl,n.uuid,t));let o=new De.Doc,r=new Awareness(o),i=Date.now();return Kn(o,{roomUuid:n.uuid,createdAt:i,participantId:e.participantId,displayName:e.displayName,defaultScale:e.defaultScale??Ct,...e.sessionName!==void 0&&{sessionName:e.sessionName}}),r.setLocalStateField("participantId",e.participantId),We({doc:o,awareness:r,roomCode:n.code,roomUuid:n.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t})}async function bo(e){let t=await de(e.relayUrl,e.roomCode),n;if(t.accessMode==="password"){if(!e.password)throw new Error("Room requires a password");n=await Oe(e.password,t.uuid);}let o=new De.Doc,r=new Awareness(o);return Ye(o,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId),We({doc:o,awareness:r,roomCode:e.roomCode,roomUuid:t.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:n,onRejection:e.onRejection})}function We(e){let{doc:t,awareness:n,participantId:o,relayUrl:r,roomUuid:i}=e,a=new Set,s=new Set,l=new Set,u=wo({wsBaseUrl:e.relayUrl,roomUuid:e.roomUuid,doc:t,deviceId:o,passwordHash:e.passwordHash,awareness:n,onStatusChange(m){a.forEach(f=>f(m));},onRejection(m){console.error(`Connection rejected: ${m}`),e.onRejection?.(m);}}),c=yo(t,n,o),d=()=>{s.forEach(m=>m());};t.getMap("meta").observeDeep(d),t.getMap("settings").observeDeep(d),t.getMap("participants").observeDeep(d),t.getArray("rounds").observeDeep(d);function p(){let m=new Set;return n.getStates().forEach(f=>{let y=f.participantId;typeof y=="string"&&m.add(y);}),m}let b=new Set,E=setInterval(()=>{let m=q(t),f=te(m);if(!f||f.revealedAt!==void 0||b.has(f.id))return;let y=p();if(y.size===0)return;let v=m.participants.filter(w=>y.has(w.id)&&Pe(w)==="voter");if(v.length===0)return;v.filter(w=>w.id in f.votes).length>=v.length&&(b.add(f.id),mn(t,f.id,Date.now()));},250),R=t.getMap("settings").get("hostParticipantId"),A=()=>{let m=t.getMap("settings").get("hostParticipantId");m!==R&&m!==void 0&&l.forEach(f=>f(m)),R=m;};t.getMap("settings").observe(A);let H=false;return {doc:t,awareness:n,roomCode:e.roomCode,roomUuid:e.roomUuid,projection(){return q(t)},current(){return te(q(t))},isHost(){return q(t).settings.hostParticipantId===o},onlineIds:p,vote(m){let f=te(q(t));f&&Xn(t,f.id,o,m);},unvote(){let m=te(q(t));m&&Qn(t,m.id,o);},reveal(){let m=te(q(t));m&&mn(t,m.id,Date.now());},skip(){let m=te(q(t));m&&Zn(t,m.id,Date.now());},newRound(m,f,y){let v=randomUUID(),N=Date.now();return t.transact(()=>{pn(t,{id:v,createdAt:N,createdBy:o,...m!==void 0&&{title:m},...f!==void 0&&{ticketId:f},...y!==void 0&&{agendaItemId:y}}),y!==void 0&&oo(t,y,v,N);}),v},revote(){let m=te(q(t)),f=randomUUID();return pn(t,{id:f,createdAt:Date.now(),createdBy:o,...m?.id!==void 0&&{parentRoundId:m.id},...m?.title!==void 0&&{title:m.title},...m?.description!==void 0&&{description:m.description},...m?.ticketId!==void 0&&{ticketId:m.ticketId},...m?.agendaItemId!==void 0&&{agendaItemId:m.agendaItemId}}),f},updateRoundDescriptor(m,f){zn(t,m,f);},updateName(m){Je(t,{name:m});},updateScale(m){Je(t,{defaultScale:m});},updateDisplayName(m){let v=q(t).participants.find(N=>N.id===o)?.joinedAt??Date.now();un(t,o,{displayName:m,joinedAt:v});},async updateAccess(m,f){let y=null;if(m==="password"){if(!f)throw new Error("Password required for password mode");y=await Oe(f,i);}await Sn(r,i,y),u.updateCredentials({passwordHash:y});},handoffHost(m){if(!this.isHost())throw new Error("Only the current host can hand off");if(!p().has(m))throw new Error("Target participant is not online");if(!q(t).participants.some(N=>N.id===m))throw new Error("Target participant does not exist");Je(t,{hostParticipantId:m});},toggleRole(){let f=q(t).participants.find(w=>w.id===o),v=Pe(f??{})==="viewer"?"voter":"viewer",N=f?.joinedAt??Date.now();un(t,o,{displayName:f?.displayName??"",joinedAt:N,role:v});},endSessionForEveryone(){if(!this.isHost())throw new Error("Only the current host can end the session");eo(t);},onChange(m){return s.add(m),()=>s.delete(m)},onStatusChange(m){return a.add(m),()=>a.delete(m)},onHostChange(m){return l.add(m),()=>l.delete(m)},disconnect(){H||(H=true,clearInterval(E),c.stop(),t.getMap("meta").unobserveDeep(d),t.getMap("settings").unobserveDeep(d),t.getMap("settings").unobserve(A),t.getMap("participants").unobserveDeep(d),t.getArray("rounds").unobserveDeep(d),u.disconnect());}}}function Ao(e){let t=fn(e);return t===""?null:t}var Di=1440*60*1e3;function wn(){return join(nt(),"last-session.json")}function Oi(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.roomCode=="string"&&typeof t.roomUuid=="string"&&typeof t.lastSeenAt=="number"&&(t.passwordHash===void 0||typeof t.passwordHash=="string")}function Dt(){let e=wn();if(!existsSync(e))return null;try{let t=JSON.parse(readFileSync(e,"utf-8"));return !Oi(t)||Date.now()-t.lastSeenAt>Di?(V(),null):t}catch{return V(),null}}function Ot(e){let t=nt();mkdirSync(t,{recursive:true,mode:448}),chmodSync(t,448);let n=wn();writeFileSync(n,JSON.stringify(e,null,2)+`
21
+ `,{encoding:"utf-8",mode:384}),chmodSync(n,384);}function V(){let e=wn();try{unlinkSync(e);}catch(t){if(t.code!=="ENOENT")throw t}}async function Mt(e){let t=true;try{await e.clearLastSession();}catch(n){t=false,e.logger.error(`Failed to clear cached session: ${n instanceof Error?n.message:String(n)}`);}return t?e.logger.error("Session expired (room no longer exists). Cached session cleared."):e.logger.error("Session expired. Could not delete ~/.config/hnch/last-session.json \u2014 please remove it manually."),e.exit(1)}function $t(e){let t=e.doc.getMap("meta"),n=null,o=false;function r(){if(o)return;let i=t.get("sessionEndedAt");if(i==null||i===n)return;n=i;let a=t.get("createdBy"),s=a===e.localParticipantId,l=e.doc.getMap("participants"),u=e.doc.getMap("settings").get("hostParticipantId")??a,c="host";if(u){let p=l.get(u)?.get("displayName");typeof p=="string"&&p.length>0&&(c=p);}setImmediate(()=>{o||e.onEnded({isLocal:s,hostName:c,timestamp:i});});}return t.observe(r),r(),()=>{o=true,t.unobserve(r);}}var Mi="@xauyxau/hnch";function Ut(e){return po(e)}function Bt(e){return `${process.env.HNCH_SHARE_ORIGIN??"https://hnch.dev"}/join?code=${e}`}function Ht(e){return `npx ${Mi} join ${e}`}function yn(e){let t=e.trim();return t===""?void 0:t}function Lt(e){return e?{title:e.title??"",ticketId:e.ticketId??"",agendaItemId:e.id}:{title:"",ticketId:"",agendaItemId:void 0}}function Ro(e,t,n){return [e,yn(t),n]}var $i={connecting:"yellow",connected:"green",disconnected:"red"};function No({roomCode:e,sessionName:t,status:n,isHost:o}){let r=t?`${e} \xB7 ${t}`:e;return jsxs(Box,{borderStyle:"single",borderColor:"gray",paddingX:1,justifyContent:"space-between",children:[jsxs(Text,{bold:true,children:["hnch \xB7 ",r]}),jsxs(Box,{gap:2,children:[o&&jsx(Text,{color:"yellow",children:"[host]"}),jsx(Text,{color:$i[n],children:n})]})]})}function he({items:e,onSelect:t,onClose:n,title:o}){if(e.length===0)return jsxs(Box,{flexDirection:"column",gap:1,children:[o&&jsx(Text,{bold:true,children:o}),jsx(Text,{dimColor:true,children:"(no items)"})]});let r=e.findIndex(s=>!s.disabled),[i,a]=useState(Math.max(r,0));return useInput((s,l)=>{if(l.upArrow)a(u=>{let c=(u-1+e.length)%e.length,d=0;for(;e[c]?.disabled&&d<e.length;)c=(c-1+e.length)%e.length,d++;return c});else if(l.downArrow)a(u=>{let c=(u+1)%e.length,d=0;for(;e[c]?.disabled&&d<e.length;)c=(c+1)%e.length,d++;return c});else if(l.return){let u=e[i];u&&!u.disabled&&t(u.value);}else l.escape&&n?.();}),jsxs(Box,{flexDirection:"column",gap:1,children:[o&&jsx(Text,{bold:true,children:o}),jsx(Box,{flexDirection:"column",children:e.map((s,l)=>{let u=l===i,c=s.disabled??false;return jsxs(Box,{gap:1,children:[jsx(Text,{...u&&{color:"cyan"},dimColor:c,children:u?">":" "}),jsx(Text,{bold:u,dimColor:c,children:s.label}),s.detail&&jsx(Text,{dimColor:true,children:s.detail})]},s.value)})}),jsx(Text,{dimColor:true,children:"\u2191\u2193 select \u23CE confirm esc close"})]})}function Y({value:e,onChange:t,onSubmit:n,onCancel:o,placeholder:r,isActive:i=true,mask:a=false}){useInput((c,d)=>{d.escape?o?.():d.return?n(e):d.backspace||d.delete?t(e.slice(0,-1)):c&&!d.ctrl&&!d.meta&&t(e+c);},{isActive:i});let s=a&&e.length>0?"*".repeat(e.length):e,l=s.length>0?s:r??"",u=e.length===0&&r!==void 0;return jsxs(Text,{children:[jsx(Text,{dimColor:u,children:l}),jsx(Text,{inverse:true,children:" "})]})}function Mo({mode:e,password:t,onModeChange:n,onPasswordChange:o,onClose:r}){let[i,a]=useState(e==="open"?0:1),[s,l]=useState(false);return useEffect(()=>{a(e==="open"?0:1);},[e]),useInput((u,c)=>{if(c.leftArrow)a(d=>Math.max(0,d-1));else if(c.rightArrow)a(d=>Math.min(1,d+1));else if(c.return){let d=i===0?"open":"password";d!==e&&n(d),d==="password"&&l(true);}else c.escape&&r?.();},{isActive:!s}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:["open","password"].map((u,c)=>{let d=c===i,p=u===e,b=u==="open"?"Open":"Password";return jsx(Text,{inverse:d,bold:p,...p&&{color:"cyan"},children:p?`[${b}]`:` ${b} `},u)})}),e==="password"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Password: "}),jsx(Y,{value:t,onChange:o,onSubmit:()=>l(false),onCancel:()=>l(false),placeholder:"(required to join)",isActive:s,mask:true}),!s&&jsx(Text,{dimColor:true,children:"\u23CE edit \u2190 \u2192 switch mode esc close"}),s&&jsx(Text,{dimColor:true,children:"\u23CE done esc cancel"})]}),e==="open"&&jsx(Text,{dimColor:true,children:"\u2190\u2192 toggle \u23CE confirm esc close"})]})}function Bo({scaleId:e,cards:t,disabledIndices:n,onOverrideChange:o,onClose:r}){let i=useMemo(()=>new Set(n),[n]),[a,s]=useState(0),l=u=>{let c=new Set(i);if(c.has(u))c.delete(u);else {if(c.size>=t.length-1)return;c.add(u);}let d=Array.from(c).toSorted((p,b)=>p-b);o(e,d);};return useInput((u,c)=>{c.leftArrow?s(d=>Math.max(0,d-1)):c.rightArrow?s(d=>Math.min(t.length-1,d+1)):u===" "?l(a):(c.return||c.escape)&&r();}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:t.map((u,c)=>{let d=c===a,p=i.has(c);return jsx(Text,{inverse:d,bold:!p,...!p&&{color:"cyan"},strikethrough:p,dimColor:p,children:u},u)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate space toggle \u23CE/esc done"})]})}function En({initialName:e="",initialCards:t=[],onSave:n,onCancel:o}){let r=e.length>0,[i,a]=useState(e),[s,l]=useState(t.length>0?t:[""]),[u,c]=useState(0),[d,p]=useState("editing-name"),[b,E]=useState(""),R=()=>{let m=i.trim();if(m.length===0||m.length>40){E("Name must be 1-40 characters");return}a(m),E(""),p("editing-cards");},A=()=>{let m=i.trim();if(m.length===0||m.length>40){E("Name must be 1-40 characters");return}let f=s.map(v=>v.trim()).filter(v=>v.length>0),y=Array.from(new Set(f));if(y.length<2){E("Need at least 2 unique non-empty cards");return}E(""),n(m,y);};return useInput((m,f)=>{if(d==="editing-cards"){if(f.leftArrow)c(y=>Math.max(0,y-1));else if(f.rightArrow)c(y=>{let v=y+1;return v>=s.length&&s.length<25?(l(N=>[...N,""]),v):Math.min(v,s.length-1)});else if(f.return)A();else if(f.escape)o();else if(f.tab)p("editing-name");else if(f.backspace){let y=s[u]||"";if(y.length===0){if(s.length>2){let v=s.filter((N,w)=>w!==u);l(v),c(Math.max(0,u-1));}}else {let v=[...s];v[u]=y.slice(0,-1),l(v);}}else if(m&&!f.ctrl&&!f.meta){let y=s[u]||"";if(y.length<10){let v=[...s];v[u]=y+m,l(v);}}}},{isActive:d==="editing-cards"}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:r?"\u2500\u2500 Edit Custom Scale \u2500\u2500":"\u2500\u2500 Create Custom Scale \u2500\u2500"}),jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Text,{children:"Name:"}),jsx(Y,{value:i,onChange:a,onSubmit:R,onCancel:o,placeholder:"Scale name",isActive:d==="editing-name"})]}),d==="editing-cards"&&jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Text,{children:"Cards:"}),jsx(Box,{gap:1,flexWrap:"wrap",children:s.map((m,f)=>{let y=f===u;return jsx(Text,{inverse:y,...!y&&{color:"cyan"},children:m.length>0?m:"\xB7"},f)})})]}),b&&jsx(Text,{color:"red",children:b}),jsx(Text,{dimColor:true,children:d==="editing-name"?"\u23CE next esc cancel":"\u2190\u2192 navigate typing adds card bsp delete \u23CE save tab name esc cancel"})]})}function Ft({scales:e,selectedScaleId:t,presetOverrides:n,customScales:o=[],onSelect:r,onOverrideChange:i,onCustomScaleCreate:a,onCustomScaleEdit:s,onCustomScaleDelete:l,onClose:u,showNoneOption:c=false}){let[d,p]=useState(0),[b,E]=useState(null),[R,A]=useState("browsing"),[H,m]=useState(null),[f,y]=useState(null),v=a?[...e,{id:"__create-custom__",cards:[]}]:e,N=v.length;if(useInput((w,D)=>{if(R==="browsing"){if(D.escape){u();return}if(N===0)return;if(D.upArrow)p(S=>(S-1+N)%N);else if(D.downArrow)p(S=>(S+1)%N);else if(D.return){let S=v[d];if(!S)return;if(S.id==="__create-custom__"){A("creating");return}S.id in ae?E(b===S.id?null:S.id):r(S.id);}else if(w===" "){let S=v[d];S&&S.id!=="__create-custom__"&&r(S.id);}else if(w==="e"||w==="E"){let S=v[d];s&&S?.id.startsWith("custom-")&&(m(S.id),A("editing"));}else if(w==="d"||w==="D"){let S=v[d];l&&S?.id.startsWith("custom-")&&(y(S.id),A("confirming-delete"));}}else R==="confirming-delete"&&(w==="y"||w==="Y"?(f&&l&&l(f),y(null),A("browsing")):(w==="n"||w==="N"||D.escape)&&(y(null),A("browsing")));},{isActive:R==="browsing"&&b===null||R==="confirming-delete"}),R==="creating")return jsx(En,{onSave:(w,D)=>{a&&a(w,D),A("browsing");},onCancel:()=>A("browsing")});if(R==="editing"&&H){let w=o?.find(S=>S.id===H);if(e.find(S=>S.id===H)&&w)return jsx(En,{initialName:w.label,initialCards:w.cards,onSave:(S,_)=>{s&&s(H,S,_),m(null),A("browsing");},onCancel:()=>{m(null),A("browsing");}})}if(R==="confirming-delete"&&f){let w=v.find(S=>S.id===f),D=w?Me(w.id,o):"Unknown";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Text,{children:["Delete ",D,"? "]}),jsx(Text,{children:"[y] yes [n] no esc cancel"})]})}return v.length===0?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{dimColor:true,children:"(no scales available)"}),jsx(Text,{dimColor:true,children:"esc back"})]}):jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{flexDirection:"column",children:v.map((w,D)=>{let S=D===d,_=w.id===t,pe=b===w.id,oe=w.id in ae,re=w.id==="__create-custom__",J=w.cards.join(", "),I=c&&w.id==="",T=I?"(none)":re?"[+ Create custom scale]":Me(w.id,o);return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{...S&&{color:"cyan"},children:S?">":" "}),jsx(Text,{bold:S,children:T}),!I&&!re&&jsx(Text,{dimColor:true,children:J}),_&&jsx(Text,{color:"cyan",children:"[current]"})]}),pe&&!I&&!re&&jsx(Box,{paddingLeft:2,children:oe?jsx(Bo,{scaleId:w.id,cards:ae[w.id]?.cards??[],disabledIndices:n?.[w.id]??[],onOverrideChange:i,onClose:()=>E(null)}):null})]},w.id||"none")})}),jsx(Text,{dimColor:true,children:(()=>{let w=d<v.length?v[d]:null;return w?.id.startsWith("custom-")?`\u2191\u2193 navigate space select${s?" [e] edit":""}${l?" [d] delete":""} esc back`:w&&w.id in ae?"\u2191\u2193 navigate \u23CE customize space select esc back":"\u2191\u2193 navigate \u23CE/space select esc back"})()})]})}function Ki(e,t){return t?[...e]:e.filter(n=>n.value==="display-name")}function Ho({sessionName:e,displayName:t,currentScale:n,accessMode:o,presetOverrides:r,customScales:i,isHost:a=true,onChangeName:s,onChangeScale:l,onChangeDisplayName:u,onChangeAccess:c,onClose:d}){let[p,b]=useState(r??{}),E=useMemo(()=>Pt(p,i),[p,i]),[R,A]=useState("main-menu"),[H,m]=useState(e??""),[f,y]=useState(t),[v,N]=useState(o==="password"?"password":"open"),[w,D]=useState(""),[S,_]=useState(false),pe=[{label:"Room name",value:"room-name",detail:`[${e??"(none)"}]`},{label:"Scale",value:"scale",detail:`[${Me(n.id,i)}]`},{label:"Access",value:"access",detail:`[${o==="open"?"Open":"Password"}]`},{label:"Display name",value:"display-name",detail:`[${t}]`}],oe=Ki(pe,a);function re(M){!a&&M!=="display-name"||(M==="room-name"?(m(e??""),A("editing-room-name")):M==="scale"?A("picking-scale"):M==="access"?A("picking-access"):M==="display-name"&&(y(t),A("editing-display-name")));}function J(M){let L=M.trim()===""?void 0:M.trim();s(L),A("main-menu");}function I(M){let L=M.trim();L.length>0&&(u(L),process.nextTick(()=>G({displayName:L}))),A("main-menu");}function T(M){let L=E.find(z=>z.id===M);L&&l(L),A("main-menu");}function O(M,L){let z={...p};L.length===0?delete z[M]:z[M]=L,b(z),G({presetOverrides:Object.keys(z).length>0?z:void 0});}async function F(M,L){_(true);try{await c(M,L),N(M),D(M==="password"?L??"":"");}catch(z){console.error(`Failed to update access: ${z}`);}finally{_(false),A("main-menu");}}return R==="main-menu"?jsx(he,{title:"\u2500\u2500 Settings \u2500\u2500",items:oe,onSelect:re,onClose:d}):R==="editing-room-name"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(Text,{children:"Room name: "}),jsx(Y,{value:H,onChange:m,onSubmit:J,onCancel:()=>A("main-menu"),placeholder:"(leave empty to remove)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]}):R==="editing-display-name"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(Text,{children:"Display name: "}),jsx(Y,{value:f,onChange:y,onSubmit:I,onCancel:()=>A("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]}):R==="picking-scale"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),jsx(Ft,{scales:E,selectedScaleId:n.id,presetOverrides:p,onSelect:T,onOverrideChange:O,onClose:()=>A("main-menu")})]}):R==="picking-access"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),S&&jsx(Text,{dimColor:true,children:"Updating access..."}),!S&&jsx(Mo,{mode:v,password:w,onModeChange:M=>{M==="open"&&F("open");},onPasswordChange:D,onClose:()=>A("main-menu")})]}):jsx(Box,{})}function Jt({participants:e,onlineIds:t,hostId:n,votes:o,revealed:r,participantId:i}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{bold:true,children:["Participants (",e.length,")"]}),e.map(a=>{let s=t.has(a.id),l=s?"\u25CF":"\u25CB",u=s?"green":"gray",c=a.id===n,d=Pe(a)==="viewer",p=a.id===i,b=a.id in o,E=d?" (viewer)":r?o[a.id]?` \u2192 ${o[a.id]}`:"":b?" \u2713":" \xB7",R=p&&!d&&!(r&&o[a.id]);return jsxs(Box,{gap:1,children:[jsx(Text,{color:u,children:l}),jsxs(Text,{children:[a.displayName,c?" (host)":""]}),R?jsx(Text,{color:"cyan",children:"(voter)"}):jsx(Text,{color:d?"gray":b?"green":"gray",children:E})]},a.id)})]})}var zi=[{label:"End session for everyone",value:"end-session",detail:"Disconnects all participants. Cannot be undone."}];function jo({onPick:e,onClose:t}){return jsx(he,{title:"Host Actions",items:zi,onSelect:e,onClose:t})}function Gt({roomCode:e,onPick:t,onClose:n}){let o=[{label:"Copy code",value:"code",detail:Ut(e)},{label:"Copy share link",value:"url",detail:Bt(e)},{label:"Copy npx command",value:"npx",detail:Ht(e)}];return jsx(he,{title:"Share",items:o,onSelect:r=>t(r),onClose:n})}function Zi(e){let t=e.rounds.filter(o=>W(o)!==null),n=Object.fromEntries(e.participants.map(o=>[o.id,o]));return So({rounds:t,participants:n})}async function _o(e,t,n){let o=Zi(e);try{await t(o),n("Results copied to clipboard");}catch{n("Clipboard write failed");}}function Fo(e,t,n){let o=ao(e.id,n);return o===null?`Round ${t}`:`Round ${o.depth}/${o.total} [re-vote]`}function Vo(e,t,n){let o=Fo(e,t,n),r=e.title?` \u2014 ${e.title}`:"",i=e.ticketId?` [${e.ticketId}]`:"",a=W(e)==="skipped"?" \u2014 Skipped":" \u2014 Results";return `${o}${r}${i}${a}`}function Yo(e){let t=Object.values(e).filter(c=>!fe(c)).map(c=>parseFloat(c)).filter(c=>!isNaN(c)).toSorted((c,d)=>c-d);if(t.length===0)return {average:"-",median:"-",agreement:"-"};let o=t.reduce((c,d)=>c+d,0)/t.length,r=Math.floor(t.length/2),i=t.length%2===0?(t[r-1]+t[r])/2:t[r],a=Object.values(e).filter(c=>!fe(c)),s=new Map;for(let c of a)s.set(c,(s.get(c)??0)+1);let l=Math.max(...s.values()),u=a.length>0?Math.round(l/a.length*100):0;return {average:o.toFixed(1),median:i.toFixed(1),agreement:`${u}%`}}function Nn(e,t){let n=Math.floor((t-e)/1e3),o=Math.floor(n/60),r=n%60;return `${o}:${r.toString().padStart(2,"0")}`}function Jo(e,t,n=[]){let o=Fo(e,t,n);if(W(e)==="skipped"){let d=e.title?` ${e.title}`:"",p=e.ticketId?` [${e.ticketId}]`:"";return `${o}:${d}${p} \u2014 Skipped`}let r=new Map;for(let d of Object.values(e.votes))fe(d)||r.set(d,(r.get(d)??0)+1);let i=[...r.entries()].toSorted((d,p)=>p[1]-d[1]||d[0].localeCompare(p[0])).map(([d,p])=>`${d}\xD7${p}`).join(", "),a=Object.values(e.votes).filter(fe).length,s=a>0?` (${a} abstained)`:"",l=e.title?` ${e.title}`:"",u=e.ticketId?` [${e.ticketId}]`:"",c=e.timerStartedAt!==void 0&&e.revealedAt!==void 0?` \u2014 ${Nn(e.timerStartedAt,e.revealedAt)}`:"";return `${o}:${l}${u} \u2014 ${i||"(no votes)"}${s}${c}`}function Go({projection:e,onlineIds:t,isHost:n,participantId:o,rounds:r,currentRound:i,settingsOpen:a,onStartRound:s,onNewRound:l,onRevote:u,onOpenSettings:c,onHandoffHost:d,onEndSession:p,onShare:b,shareOpen:E,onSetShareOpen:R,roomCode:A,confirmingQuit:H,myRole:m,onToggleRole:f,roundTitlePromptActive:y,roundTitleInput:v,onRoundTitleChange:N,onRoundTitleSubmit:w,onRoundTitleCancel:D,roundTicketIdPromptActive:S,roundTicketIdInput:_,onRoundTicketIdChange:pe,onRoundTicketIdSubmit:oe,onRoundTicketIdCancel:re,descriptorPromptActive:J,descriptorInput:I,onDescriptorChange:T,onDescriptorSubmit:O,onDescriptorCancel:F,onEditDescriptor:M,canExport:L,onExportResults:z,onAgendaAdd:Qe,agendaAddPromptActive:Te,agendaAddTitleInput:Ze,onAgendaAddTitleChange:tn,onAgendaAddTitleSubmit:je,onAgendaAddTitleCancel:St,agendaAddTicketIdPromptActive:ye,agendaAddTicketIdInput:nn,onAgendaAddTicketIdChange:_e,onAgendaAddTicketIdSubmit:Fe,onAgendaAddTicketIdCancel:Re}){let[Q,Z]=Wt.useState("idle"),[ge,ve]=Wt.useState(null),[et,ie]=Wt.useState(false),[me,Ee]=Wt.useState(false);useEffect(()=>{n||(Z("idle"),ve(null),ie(false),Ee(false));},[n]),useInput(x=>{if(x==="c"||x==="C"){R(true);return}if(x==="w"||x==="W"){f();return}if((x==="x"||x==="X")&&L){z();return}if(n){if(x==="a"||x==="A"){Qe();return}(x==="e"||x==="E")&&c(),(x==="s"||x==="S")&&s(),(x==="h"||x==="H")&&Z("picking"),(x==="m"||x==="M")&&ie(true),i!==null&&W(i)!==null&&((x==="n"||x==="N")&&l(),(x==="v"||x==="V")&&W(i)!=="skipped"&&u(),(x==="t"||x==="T")&&M());}},{isActive:!a&&!H&&Q==="idle"&&!y&&!S&&!et&&!me&&!E&&!J&&!Te&&!ye}),useInput((x,ee)=>{x==="y"||x==="Y"?(p(),Ee(false)):(x==="n"||x==="N"||ee.escape)&&Ee(false);},{isActive:me});let Ce=e.participants.filter(x=>x.id!==o&&t.has(x.id));useInput(x=>{if(Q==="picking"){let ee=parseInt(x,10);!isNaN(ee)&&ee>=1&&ee<=Ce.length?(ve(Ce[ee-1].id),Z("confirming")):(x==="Escape"||x==="q"||x==="Q")&&Z("idle");}},{isActive:Q==="picking"}),useInput(x=>{Q==="confirming"&&ge&&(x==="y"||x==="Y"?(d(ge),Z("idle"),ve(null)):(x==="n"||x==="N"||x==="Escape")&&(Z("idle"),ve(null)));},{isActive:Q==="confirming"});let ke=r.length>0,xt=r.filter(x=>W(x)!==null),tt=i!==null?xt.slice(0,-1):xt;return et?jsx(jo,{onPick:x=>{ie(false),x==="end-session"&&Ee(true);},onClose:()=>ie(false)}):E?jsx(Gt,{roomCode:A,onPick:x=>{R(false),b(x);},onClose:()=>R(false)}):jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:ke?"Session":"Waiting for participants..."}),!ke&&jsx(Text,{dimColor:true,children:"No rounds started yet."}),jsx(Jt,{participants:e.participants,onlineIds:t,hostId:e.settings.hostParticipantId,votes:{},revealed:false,participantId:o}),e.agenda.length>0&&jsx(rs,{items:e.agenda,nextPending:Ge(e)}),i!==null&&W(i)!==null&&jsx(ts,{projection:e,round:i,rounds:r}),tt.length>0&&jsxs(Box,{flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"\u2500\u2500 History \u2500\u2500"}),tt.map(x=>{let ee=r.indexOf(x)+1;return jsx(Text,{dimColor:true,children:Jo(x,ee,r)},x.id)})]}),Q==="picking"&&Ce.length>0&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Hand off to:"}),Ce.map((x,ee)=>jsxs(Text,{children:["[",ee+1,"] ",x.displayName]},x.id)),jsx(Text,{dimColor:true,children:"[q] Cancel"})]}),Q==="picking"&&Ce.length===0&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{dimColor:true,children:"No other online participants"}),jsx(Text,{dimColor:true,children:"[q] Cancel"})]}),Q==="confirming"&&ge&&jsx(Box,{flexDirection:"column",children:jsxs(Text,{children:["Hand off to ",e.participants.find(x=>x.id===ge)?.displayName,"? [y/n]"]})}),y&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Round title (optional, Enter to skip):"}),jsx(Y,{value:v,onChange:N,onSubmit:w,onCancel:D,placeholder:"Enter to skip",isActive:y})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),S&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Ticket ID (optional, Enter to skip):"}),jsx(Y,{value:_,onChange:pe,onSubmit:oe,onCancel:re,placeholder:"e.g. PROJ-1234",isActive:S})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),J&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Edit round title:"}),jsx(Y,{value:I,onChange:T,onSubmit:O,onCancel:F,placeholder:"Enter to save",isActive:J})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel \xB7 empty submit cancels"})]}),me&&jsxs(Box,{children:[jsx(Text,{color:"red",children:"End session for everyone? This cannot be undone. "}),jsx(Text,{dimColor:true,children:"y/n [Esc] Cancel"})]}),Te&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Agenda title (optional, Enter to skip):"}),jsx(Y,{value:Ze,onChange:tn,onSubmit:je,onCancel:St,placeholder:"Enter to skip",isActive:Te})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),ye&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Agenda ticket ID (optional, Enter to skip):"}),jsx(Y,{value:nn,onChange:_e,onSubmit:Fe,onCancel:Re,placeholder:"e.g. PROJ-1234",isActive:ye})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),Q==="idle"&&!y&&!S&&!J&&!me&&!Te&&!ye&&jsxs(Box,{gap:2,children:[n?jsx(Fragment,{children:i!==null&&W(i)!==null?jsxs(Fragment,{children:[W(i)!=="skipped"&&jsx(Text,{color:"yellow",children:"[v] Revote"}),jsx(Text,{color:"yellow",children:"[n] Next"}),jsx(Text,{color:"yellow",children:"[t] Edit title"}),jsx(Text,{color:"yellow",children:"[h] Handoff"}),jsx(Text,{color:"yellow",children:"[e] Settings"}),jsx(Text,{color:"yellow",children:"[c] Share"}),L&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",m==="viewer"?"Vote":"Observe"]}),jsx(Text,{color:"yellow",children:"[m] Menu"})]}):jsxs(Fragment,{children:[jsx(Text,{color:"yellow",children:"[s] Start round"}),jsx(Text,{color:"yellow",children:"[a] Agenda"}),jsx(Text,{color:"yellow",children:"[h] Handoff"}),jsx(Text,{color:"yellow",children:"[e] Settings"}),jsx(Text,{color:"yellow",children:"[c] Share"}),L&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",m==="viewer"?"Vote":"Observe"]}),jsx(Text,{color:"yellow",children:"[m] Menu"})]})}):jsxs(Fragment,{children:[jsx(Text,{dimColor:true,children:"Waiting for host to start a round..."}),jsx(Text,{children:"[c] Share"}),L&&jsx(Text,{color:"yellow",children:"[x] Export"}),jsxs(Text,{color:"yellow",children:["[w] ",m==="viewer"?"Vote":"Observe"]})]}),jsx(Text,{children:"[q] Quit"})]})]})}function ts({projection:e,round:t,rounds:n}){let o=n.indexOf(t)+1,r=Vo(t,o,n);if(W(t)==="skipped")return jsx(Box,{flexDirection:"column",gap:1,children:jsx(Text,{bold:true,children:r})});let i=Yo(t.votes),a=new Map(e.participants.map(p=>[p.id,p.displayName])),s=t.timerStartedAt!==void 0&&t.revealedAt!==void 0?Nn(t.timerStartedAt,t.revealedAt):null,l=Object.entries(t.votes),u=l.filter(([,p])=>!fe(p)),c=l.filter(([,p])=>fe(p)).map(([p])=>p),d=u[0]?.[1];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:r}),to(t)&&d!==void 0&&jsxs(Text,{bold:true,color:"green",children:["Consensus! Everyone voted ",d]}),jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:2,children:[jsx(Text,{bold:true,underline:true,children:"Name".padEnd(20)}),jsx(Text,{bold:true,underline:true,children:"Estimate".padEnd(10)})]}),u.map(([p,b])=>jsxs(Box,{gap:2,children:[jsx(Text,{children:(a.get(p)??p).padEnd(20)}),jsx(Text,{color:"cyan",bold:true,children:b.padEnd(10)})]},p)),c.map(p=>jsxs(Box,{gap:2,children:[jsx(Text,{dimColor:true,children:(a.get(p)??p).padEnd(20)}),jsx(Text,{dimColor:true,children:"(abstained)".padEnd(10)})]},p)),e.participants.filter(p=>!(p.id in t.votes)).map(p=>jsxs(Box,{gap:2,children:[jsx(Text,{dimColor:true,children:p.displayName.padEnd(20)}),jsx(Text,{dimColor:true,children:"(no vote)".padEnd(10)})]},p.id))]}),jsxs(Box,{gap:2,children:[jsxs(Text,{children:["Avg: ",jsx(Text,{bold:true,children:i.average})]}),jsxs(Text,{children:["Med: ",jsx(Text,{bold:true,children:i.median})]}),jsxs(Text,{children:["Agreement: ",jsx(Text,{bold:true,children:i.agreement})]}),s!==null&&jsxs(Text,{dimColor:true,children:["\u23F1 ",s]})]})]})}var ns={pending:"\u2022",consumed:"\u2713",skipped:"~",cancelled:"\u2717"},os={consumed:"green",skipped:"yellow",cancelled:"red"};function rs({items:e,nextPending:t}){let n=e.filter(o=>o.state!=="cancelled");return jsxs(Box,{flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"\u2500\u2500 Agenda \u2500\u2500"}),n.map(o=>{let r=ns[o.state]??"?",i=os[o.state],a=t!==null&&o.id===t.id,s=[o.ticketId?`[${o.ticketId}]`:"",o.title??""].filter(Boolean).join(" ").trim()||o.id;return jsxs(Box,{gap:1,children:[i!==void 0?jsx(Text,{color:i,children:r}):jsx(Text,{children:r}),i!==void 0?jsx(Text,{color:i,children:s}):jsx(Text,{children:s}),a&&jsx(Text,{color:"cyan",children:"(next)"})]},o.id)}),n.length===0&&jsx(Text,{dimColor:true,children:"No pending items."})]})}function Ko({scale:e,selected:t,onSelect:n,onClear:o,disabled:r}){let[i,a]=useState(0);return useInput((s,l)=>{if(!r)if(l.leftArrow)a(u=>Math.max(0,u-1));else if(l.rightArrow)a(u=>Math.min(e.cards.length-1,u+1));else if(l.return){let u=e.cards[i];u===t?o():n(u);}else (l.backspace||l.delete)&&o();}),jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Box,{gap:1,children:e.cards.map((s,l)=>{let u=l===i,c=s===t;return jsx(Text,{inverse:u,bold:c,...c&&{color:"cyan"},children:c?`[${s}]`:` ${s} `},s)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate \u23CE select \u232B clear"})]})}function cs(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),o=t%60;return `${n}:${o.toString().padStart(2,"0")}`}function zo({projection:e,round:t,onlineIds:n,isHost:o,myId:r,myRole:i,elapsedMs:a,roomCode:s,shareOpen:l,settingsOpen:u,onVote:c,onClearVote:d,onReveal:p,onSkip:b,onToggleRole:E,onShare:R,onSetShareOpen:A,onOpenSettings:H,confirmingQuit:m}){let f=t.votes[r],y=f!==void 0&&fe(f);if(useInput(S=>{if(S==="e"||S==="E"){H();return}if(S==="c"||S==="C"){A(true);return}if(i==="voter"&&(S==="a"||S==="A")){y?d():c(vt);return}o&&(S==="r"||S==="R")&&p(),o&&(S==="s"||S==="S")&&b(),(S==="w"||S==="W")&&E();},{isActive:!m&&!u&&!l}),l)return jsx(Gt,{roomCode:s,onPick:S=>{A(false),R(S);},onClose:()=>A(false)});let v=f,N=e.rounds.indexOf(t)+1,w=t.title?` \u2014 ${t.title}`:"",D=t.ticketId?` [${t.ticketId}]`:"";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Box,{gap:2,children:[jsxs(Text,{bold:true,children:["Round ",N,w,D]}),a!==void 0&&jsxs(Text,{dimColor:true,children:["\u23F1 ",cs(a)]})]}),jsxs(Box,{gap:4,children:[jsx(Jt,{participants:e.participants,onlineIds:n,hostId:e.settings.hostParticipantId,votes:t.votes,revealed:false}),i==="viewer"?jsx(Box,{flexDirection:"column",children:jsx(Text,{dimColor:true,children:"You're observing"})}):jsxs(Box,{flexDirection:"column",gap:1,children:[y&&jsx(Text,{dimColor:true,children:"(abstaining this round \u2014 press [a] to vote)"}),jsx(Ko,{scale:t.scale,selected:y?void 0:v,onSelect:c,onClear:d,disabled:m||y})]})]}),jsxs(Box,{gap:2,children:[o&&jsx(Text,{color:"yellow",children:"[r] Reveal"}),o&&jsx(Text,{color:"yellow",children:"[s] Skip"}),i==="voter"&&jsxs(Text,{color:"yellow",children:["[a] ",y?"Vote":"Abstain"]}),jsxs(Text,{color:"yellow",children:["[w] ",i==="viewer"?"Vote":"Observe"]}),jsx(Text,{children:"[e] Settings"}),jsx(Text,{children:"[c] Share"}),jsx(Text,{children:"[q] Quit"})]})]})}var ms=3e3;function zt(e=ms){let[t,n]=useState(null),o=useRef(null),r=useCallback(()=>{o.current!==null&&(clearTimeout(o.current),o.current=null);},[]),i=useCallback(s=>{r(),n(s),o.current=setTimeout(()=>{n(null),o.current=null;},e);},[r,e]),a=useCallback(()=>{r(),n(null);},[r]);return useEffect(()=>()=>{r();},[r]),{notice:t,show:i,dismiss:a}}function hs(e){let t=te(e);return !t||W(t)!==null?"lobby":"voting"}function Qt({session:e,participantId:t,displayName:n,accessMode:o,presetOverrides:r,customScales:i}){let{exit:a}=useApp(),[s,l]=useState(e.projection()),[u,c]=useState("connecting"),[d,p]=useState(e.onlineIds()),[b,E]=useState(),[R,A]=useState(false),[H,m]=useState(o==="password"?"password":"open"),[f,y]=useState(n),[v,N]=useState(false),[w,D]=useState(false),[S,_]=useState(""),[pe,oe]=useState(false),[re,J]=useState(""),[I,T]=useState(),[O,F]=useState(false),[M,L]=useState(""),[z,Qe]=useState(null),[Te,Ze]=useState(false),[tn,je]=useState(""),[St,ye]=useState(false),[nn,_e]=useState(""),[Fe,Re]=useState(),[Q,Z]=useState(),ge=zt(3e3),[ve,et]=useState(false),ie=zt(3e3),me=zt(3e3);useEffect(()=>{let C=e.onChange(()=>{l(e.projection()),p(e.onlineIds());}),U=e.onStatusChange(c),Ve=e.onHostChange(wt=>{let Ur=e.projection().participants.find(Hr=>Hr.id===wt),Br=wt===t?"You are now the host":`${Ur?.displayName||"Unknown"} is now the host`;ge.show(Br);}),rn=setInterval(()=>{p(e.onlineIds());let wt=e.projection(),yt=te(wt);yt?.timerStartedAt!==void 0&&yt.revealedAt===void 0?E(Date.now()-yt.timerStartedAt):E(void 0);},1e3);return ()=>{C(),U(),Ve(),clearInterval(rn);}},[e,t,ge.show]),useInput(C=>{(C==="q"||C==="Q")&&N(true);},{isActive:!R&&!v&&!w&&!pe&&!O&&!ve&&!Te&&!St}),useInput((C,U)=>{C==="y"||C==="Y"?(e.disconnect(),a()):(C==="n"||C==="N"||U.escape)&&N(false);},{isActive:v});let Ee=hs(s),Ce=te(s),ke=s.settings.hostParticipantId===t,xt=s.participants.find(C=>C.id===t),tt=Pe(xt??{}),x=useCallback(()=>{let C=Lt(Ge(s));_(C.title),Z(C.agendaItemId),D(true);},[s]),ee=useCallback(C=>{D(false),_(""),T(yn(C));let U=Lt(Ge(s));J(U.ticketId),oe(true);},[s]),cr=useCallback(()=>{D(false),_(""),T(void 0),Z(void 0);},[]),lr=useCallback(C=>{oe(false),J("");let[U,Ve,rn]=Ro(I,C,Q);e.newRound(U,Ve,rn),T(void 0),Z(void 0);},[e,I,Q]),ur=useCallback(()=>{oe(false),J(""),T(void 0),Z(void 0);},[]),pr=useCallback(()=>{let C=e.current();!C||C.revealedAt===void 0||(Qe(C.id),L(C.title??""),F(true));},[e]),mr=useCallback(C=>{let U=z;if(F(false),Qe(null),!U)return;let Ve=C.trim();Ve!==""&&e.updateRoundDescriptor(U,{title:Ve});},[e,z]),fr=useCallback(()=>{F(false),Qe(null);},[]),gr=useCallback(C=>{e.vote(C);},[e]),hr=useCallback(()=>{e.unvote();},[e]),Sr=useCallback(()=>{e.reveal();},[e]),xr=useCallback(()=>{e.skip();},[e]),wr=useCallback(()=>{let C=Lt(Ge(s));_(C.title),Z(C.agendaItemId),D(true);},[s]),yr=useCallback(()=>{e.revote();},[e]),$n=useCallback(()=>{e.toggleRole();},[e]),vr=useCallback(C=>{e.updateName(C);},[e]),Cr=useCallback(C=>{e.updateScale(C);},[e]),Ir=useCallback(C=>{e.updateDisplayName(C),y(C);},[e]),br=useCallback(async(C,U)=>{await e.updateAccess(C,U),m(C);},[e]),Ar=useCallback(C=>{try{e.handoffHost(C);}catch(U){console.error(`Handoff failed: ${U instanceof Error?U.message:String(U)}`);}},[e]),Un=useCallback(()=>{A(true);},[]),Tr=useCallback(()=>{A(false);},[]),Rr=useCallback(()=>{e.endSessionForEveryone();},[e]),Bn=useCallback(async C=>{let U=C==="code"?Ut(e.roomCode):C==="url"?Bt(e.roomCode):Ht(e.roomCode);try{await Qo.write(U),ie.show("Copied!");}catch{ie.show(`Copy failed \u2014 ${U}`);}},[e.roomCode,ie]),on=s.rounds.filter(C=>W(C)!==null),Er=on.length>0?on.at(-1):null,kr=on.length>0,Nr=useCallback(()=>_o(s,C=>Qo.write(C),me.show),[s,me.show]),Pr=useCallback(()=>{je(""),Ze(true);},[]),Dr=useCallback(C=>{Ze(false),je("");let U=C.trim()===""?void 0:C.trim();Re(U),_e(""),ye(true);},[]),Or=useCallback(()=>{Ze(false),je(""),Re(void 0);},[]),Mr=useCallback(C=>{ye(false),_e("");let U=C.trim()===""?void 0:C.trim();if(!Fe&&!U){Re(void 0);return}Et(e.doc,{...Fe!==void 0&&{title:Fe},...U!==void 0&&{ticketId:U},createdAt:Date.now()}),Re(void 0);},[e.doc,Fe]),$r=useCallback(()=>{ye(false),_e(""),Re(void 0);},[]);return jsxs(Box,{flexDirection:"column",children:[jsx(No,{roomCode:e.roomCode,sessionName:s.settings.name,status:u,isHost:ke}),ge.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:ge.notice})}),ie.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:ie.notice.startsWith("Copy failed")?"red":"green",children:ie.notice})}),me.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:me.notice.startsWith("Clipboard write failed")?"red":"green",children:me.notice})}),R?jsx(Ho,{sessionName:s.settings.name,displayName:f,currentScale:s.settings.defaultScale,accessMode:H,presetOverrides:r,customScales:i,isHost:ke,onChangeName:vr,onChangeScale:Cr,onChangeDisplayName:Ir,onChangeAccess:br,onClose:Tr}):Ee==="lobby"?jsx(Go,{projection:s,onlineIds:d,isHost:ke,participantId:t,rounds:s.rounds,currentRound:Er,settingsOpen:R,onStartRound:x,onNewRound:wr,roundTitlePromptActive:w,roundTitleInput:S,onRoundTitleChange:_,onRoundTitleSubmit:ee,onRoundTitleCancel:cr,roundTicketIdPromptActive:pe,roundTicketIdInput:re,onRoundTicketIdChange:J,onRoundTicketIdSubmit:lr,onRoundTicketIdCancel:ur,onRevote:yr,onOpenSettings:Un,onHandoffHost:Ar,onEndSession:Rr,onShare:Bn,shareOpen:ve,onSetShareOpen:et,roomCode:e.roomCode,confirmingQuit:v,myRole:tt,onToggleRole:$n,descriptorPromptActive:O,descriptorInput:M,onDescriptorChange:L,onDescriptorSubmit:mr,onDescriptorCancel:fr,onEditDescriptor:pr,canExport:kr,onExportResults:Nr,onAgendaAdd:Pr,agendaAddPromptActive:Te,agendaAddTitleInput:tn,onAgendaAddTitleChange:je,onAgendaAddTitleSubmit:Dr,onAgendaAddTitleCancel:Or,agendaAddTicketIdPromptActive:St,agendaAddTicketIdInput:nn,onAgendaAddTicketIdChange:_e,onAgendaAddTicketIdSubmit:Mr,onAgendaAddTicketIdCancel:$r}):Ee==="voting"&&Ce?jsx(zo,{projection:s,round:Ce,onlineIds:d,isHost:ke,myId:t,myRole:tt,elapsedMs:b,onVote:gr,onClearVote:hr,onReveal:Sr,onSkip:xr,onToggleRole:$n,onShare:Bn,onSetShareOpen:et,shareOpen:ve,settingsOpen:R,onOpenSettings:Un,roomCode:e.roomCode,confirmingQuit:v}):null,v&&jsx(Box,{children:jsx(Text,{dimColor:true,children:"Leave session? y/n"})})]})}function Zo({presetOverrides:e,customScales:t}){let{exit:n}=useApp(),[o,r]=useState("main-menu"),[i,a]=useState(Ne()),[s,l]=useState(i.displayName??""),[u,c]=useState(i.relayUrl??""),[d,p]=useState(i.defaultSessionName??""),[b,E]=useState(t??[]),[R,A]=useState(e??{});useInput(I=>{(I==="q"||I==="Q")&&n();},{isActive:o==="main-menu"});let H=useMemo(()=>Pt(R,b),[R,b]),m=i.defaultScale,f=m?H.find(I=>I.id===m):void 0,y=[{label:"Display name",value:"display-name",detail:`[${i.displayName??"(none)"}]`},{label:"Relay URL",value:"relay-url",detail:`[${i.relayUrl??"(none)"}]`},{label:"Default scale",value:"default-scale",detail:`[${f?Me(f.id,b):"(none)"}]`},{label:"Default session name",value:"default-session-name",detail:`[${i.defaultSessionName??"(none)"}]`},{label:"Default password",value:"default-password",detail:`[${i.defaultPassword?"on":"off"}]`}];function v(I){I==="display-name"?(l(i.displayName??""),r("editing-display-name")):I==="relay-url"?(c(i.relayUrl??""),r("editing-relay-url")):I==="default-scale"?r("picking-scale"):I==="default-session-name"?(p(i.defaultSessionName??""),r("editing-session-name")):I==="default-password"&&r("picking-default-password");}function N(I){let T=I.trim();if(T.length>0){let O={...i,displayName:T};a(O),G({displayName:T});}r("main-menu");}function w(I){let T=I.trim();if(T.length>0){let O={...i,relayUrl:T};a(O),G({relayUrl:T});}r("main-menu");}function D(I){let T=I.trim(),O=T.length>0?{...i,defaultSessionName:T}:{...i};T.length===0?(delete O.defaultSessionName,a(O),ot({defaultSessionName:""})):(a(O),G({defaultSessionName:T})),r("main-menu");}function S(I){let T=I.length>0?{...i,defaultScale:I}:{...i};I.length===0?(delete T.defaultScale,a(T),ot({defaultScale:""})):(a(T),G({defaultScale:I})),r("main-menu");}function _(I,T){let O={...R};T.length===0?delete O[I]:O[I]=T,A(O),G({presetOverrides:Object.keys(O).length>0?O:void 0});}function pe(I){let T=I==="on",O={...i,defaultPassword:T};a(O),G({defaultPassword:T}),r("main-menu");}function oe(I,T){let O=`custom-${randomUUID()}`,F=[...b,{id:O,label:I,cards:T}];E(F),a({...i,customScales:F}),G({customScales:F});}function re(I,T,O){let F=b.map(M=>M.id===I?{id:I,label:T,cards:O}:M);E(F),a({...i,customScales:F}),G({customScales:F});}function J(I){let T=b.filter(F=>F.id!==I);E(T);let O={...i,customScales:T};i.defaultScale===I?(O.defaultScale="fibonacci",G({customScales:T,defaultScale:"fibonacci"})):G({customScales:T}),a(O);}if(o==="main-menu")return jsx(he,{title:"\u2500\u2500 Config Settings \u2500\u2500",items:y,onSelect:v,onClose:()=>n()});if(o==="editing-display-name")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Display name: "}),jsx(Y,{value:s,onChange:l,onSubmit:N,onCancel:()=>r("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(o==="editing-relay-url")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Relay URL: "}),jsx(Y,{value:u,onChange:c,onSubmit:w,onCancel:()=>r("main-menu"),placeholder:"(required)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(o==="editing-session-name")return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Text,{children:"Default session name: "}),jsx(Y,{value:d,onChange:p,onSubmit:D,onCancel:()=>r("main-menu"),placeholder:"(leave empty to clear)",isActive:true}),jsx(Text,{dimColor:true,children:"\u23CE confirm esc back"})]});if(o==="picking-scale"){let I=[{id:"",cards:[]},...H];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(Ft,{scales:I,selectedScaleId:m??"",presetOverrides:R,customScales:b,onSelect:S,onOverrideChange:_,onCustomScaleCreate:oe,onCustomScaleEdit:re,onCustomScaleDelete:J,onClose:()=>r("main-menu"),showNoneOption:true})]})}if(o==="picking-default-password"){let I=[{label:"On",value:"on",detail:i.defaultPassword?"[current]":void 0},{label:"Off",value:"off",detail:i.defaultPassword?void 0:"[current]"}];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(he,{title:"Default password:",items:I,onSelect:pe,onClose:()=>r("main-menu")})]})}return jsx(Box,{})}var Is={pending:"\u2022",consumed:"\u2713",skipped:"~",cancelled:"\u2717"};function bs(e){let t=Is[e.state]??"?",n=[];e.ticketId&&n.push(`[${e.ticketId}]`),e.title&&n.push(e.title);let o=n.join(" ")||e.id;return `${t} ${o}`}async function gt(e){let t=new De.Doc,n=new Awareness(t);Ye(t,{participantId:e.participantId,displayName:e.displayName}),n.setLocalStateField("participantId",e.participantId);let o=We({doc:t,awareness:n,roomCode:e.roomCode,roomUuid:e.roomUuid,participantId:e.participantId,relayUrl:e.relayUrl,...e.passwordHash!==void 0&&{passwordHash:e.passwordHash}});return await new Promise(r=>{let i=setTimeout(r,2e3),a=o.onStatusChange(s=>{s==="connected"&&setTimeout(()=>{clearTimeout(i),a(),r();},200);});}),{doc:t,disconnect:()=>o.disconnect()}}async function ht(){let e=Dt();return e||(console.error("No active session. Join a room first with: hnch join <code>"),process.exit(1)),{roomCode:e.roomCode,roomUuid:e.roomUuid,...e.passwordHash!==void 0&&{passwordHash:e.passwordHash}}}async function tr(e){!e.title?.trim()&&!e.ticket?.trim()&&(console.error("At least one of --title or --ticket is required"),process.exit(1));let t=await se(),n=await ht();try{await de(t.relayUrl,n.roomCode);}catch{console.error(`Room ${n.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:o,disconnect:r}=await gt({relayUrl:t.relayUrl,participantId:t.participantId,displayName:t.displayName,roomCode:n.roomCode,roomUuid:n.roomUuid,...n.passwordHash!==void 0&&{passwordHash:n.passwordHash}});try{let i=Et(o,{...e.title?.trim()?{title:e.title.trim()}:{},...e.ticket?.trim()?{ticketId:e.ticket.trim()}:{},...e.description?.trim()?{description:e.description.trim()}:{},createdAt:Date.now()});await new Promise(a=>{setTimeout(a,300);}),console.log(`Added agenda item: ${i}`);}finally{r();}}async function nr(){let e=await se(),t=await ht();try{await de(e.relayUrl,t.roomCode);}catch{console.error(`Room ${t.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:n,disconnect:o}=await gt({relayUrl:e.relayUrl,participantId:e.participantId,displayName:e.displayName,roomCode:t.roomCode,roomUuid:t.roomUuid,...t.passwordHash!==void 0&&{passwordHash:t.passwordHash}});try{let i=q(n).agenda;if(i.length===0){console.log("No agenda items.");return}i.forEach((a,s)=>{console.log(`${String(s+1).padStart(2)}. ${bs(a)}`);});}finally{o();}}async function or(e){let t=await se(),n=await ht();try{await de(t.relayUrl,n.roomCode);}catch{console.error(`Room ${n.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:o,disconnect:r}=await gt({relayUrl:t.relayUrl,participantId:t.participantId,displayName:t.displayName,roomCode:n.roomCode,roomUuid:n.roomUuid,...n.passwordHash!==void 0&&{passwordHash:n.passwordHash}});try{kt(o,e.id,"skipped",{timestamp:Date.now()}),await new Promise(i=>{setTimeout(i,300);}),console.log(`Skipped agenda item: ${e.id}`);}catch(i){console.error(`Skip failed: ${i instanceof Error?i.message:String(i)}`),process.exit(1);}finally{r();}}async function rr(e){let t=await se(),n=await ht();try{await de(t.relayUrl,n.roomCode);}catch{console.error(`Room ${n.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:o,disconnect:r}=await gt({relayUrl:t.relayUrl,participantId:t.participantId,displayName:t.displayName,roomCode:n.roomCode,roomUuid:n.roomUuid,...n.passwordHash!==void 0&&{passwordHash:n.passwordHash}});try{kt(o,e.id,"cancelled",{timestamp:Date.now()}),await new Promise(i=>{setTimeout(i,300);}),console.log(`Cancelled agenda item: ${e.id}`);}catch(i){console.error(`Cancel failed: ${i instanceof Error?i.message:String(i)}`),process.exit(1);}finally{r();}}async function ir(e){let t=await se(),n=await ht();try{await de(t.relayUrl,n.roomCode);}catch{console.error(`Room ${n.roomCode} not found on relay \u2014 session may have expired.`),process.exit(1);}let{doc:o,disconnect:r}=await gt({relayUrl:t.relayUrl,participantId:t.participantId,displayName:t.displayName,roomCode:n.roomCode,roomUuid:n.roomUuid,...n.passwordHash!==void 0&&{passwordHash:n.passwordHash}});try{ro(o,e.id,e.before,e.after),await new Promise(i=>{setTimeout(i,300);}),console.log(`Reordered agenda item: ${e.id}`);}catch(i){console.error(`Move failed: ${i instanceof Error?i.message:String(i)}`),process.exit(1);}finally{r();}}async function Mn(){return new Promise(e=>{let t=createInterface({input:process.stdin,output:process.stderr});process.stderr.write("Password: "),t.question("",n=>{t.close(),e(n);});})}async function Es(e){let t=await se(),n=e.scale??t.defaultScale??"fibonacci",o=e.name??t.defaultSessionName,r=e.password??t.defaultPassword??false,i;r&&(i=await Mn());let a=Nt(n,t.presetOverrides,t.customScales);if(!a){let d=Object.keys(ae).join(", ");console.error(`Unknown or fully-disabled scale: "${n}". Builtin IDs: ${d}`),process.exit(1);}let s=await Io({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,sessionName:o,password:i,defaultScale:a}),l;i&&(l=await Oe(i,s.roomUuid)),Ot({roomCode:s.roomCode,roomUuid:s.roomUuid,passwordHash:l,lastSeenAt:Date.now()}),console.error(`Room created: ${s.roomCode}`),console.error(`Share: hnch join ${s.roomCode}`),console.error("");let{waitUntilExit:u,unmount:c}=render(Wt.createElement(Qt,{session:s,participantId:t.participantId,displayName:t.displayName,accessMode:i?"password":"open",presetOverrides:t.presetOverrides,customScales:t.customScales}));$t({doc:s.doc,localParticipantId:t.participantId,onEnded:async d=>{console.error(d.isLocal?"Session ended.":`Session ended by ${d.hostName}.`),c();try{await V();}catch(p){console.error(`Failed to clear cached session: ${p instanceof Error?p.message:String(p)}`);}s.disconnect(),process.exit(0);}}),await u(),s.disconnect(),V(),process.exit(0);}async function ks(e){let t=await se(),n=Ao(e.code);n===null&&(console.error("invalid room code"),process.exit(1));let o;e.password&&(o=await Mn());let r=await de(t.relayUrl,n),i;r.accessMode==="password"&&!e.password?i=await Mn():e.password&&(i=o);let a,s=false,l=await bo({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,roomCode:n,password:i,onRejection(d){if(d==="unknown-room"){Mt({clearLastSession:V,logger:console,exit:process.exit});return}d==="room-full"&&(s=true,a?.());}}),u;i&&(u=await Oe(i,l.roomUuid)),Ot({roomCode:l.roomCode,roomUuid:l.roomUuid,passwordHash:u,lastSeenAt:Date.now()}),console.error(`Joined room: ${l.roomCode}`),console.error("");let c=render(Wt.createElement(Qt,{session:l,participantId:t.participantId,displayName:t.displayName,accessMode:r.accessMode,presetOverrides:t.presetOverrides,customScales:t.customScales}));a=c.unmount,$t({doc:l.doc,localParticipantId:t.participantId,onEnded:async d=>{console.error(d.isLocal?"Session ended.":`Session ended by ${d.hostName}.`),a?.();try{await V();}catch(p){console.error(`Failed to clear cached session: ${p instanceof Error?p.message:String(p)}`);}l.disconnect(),process.exit(0);}}),await c.waitUntilExit(),s&&(console.error("This room is full (max 20 participants)."),l.disconnect(),V(),process.exit(1)),l.disconnect(),V(),process.exit(0);}async function Ns(){let e=await se(),t=Dt();t||(console.error("No recent session to resume."),process.exit(0));let n;try{n=await de(e.relayUrl,t.roomCode);}catch(c){if((c instanceof Error?c.message:String(c)).includes("Room not found"))return await Mt({clearLastSession:V,logger:console,exit:process.exit});console.error("Could not reach relay \u2014 try again later."),process.exit(0);}n.accessMode==="password"&&!t.passwordHash&&(console.error(`Password changed \u2014 rejoin with: hnch join ${t.roomCode} --password`),V(),process.exit(0)),console.error(`Rejoining room ${t.roomCode}\u2026`),console.error("");let o=new De.Doc,r=new Awareness(o);Ye(o,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId);let i=false,a=false,s,l=We({doc:o,awareness:r,roomCode:t.roomCode,roomUuid:t.roomUuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t.passwordHash,onRejection(c){if(c==="unknown-room"){Mt({clearLastSession:V,logger:console,exit:process.exit});return}c==="wrong-password"&&(i=true,s?.()),c==="room-full"&&(a=true,s?.());}});Ot({roomCode:l.roomCode,roomUuid:l.roomUuid,passwordHash:t.passwordHash,lastSeenAt:Date.now()});let u=render(Wt.createElement(Qt,{session:l,participantId:e.participantId,displayName:e.displayName,accessMode:n.accessMode,presetOverrides:e.presetOverrides,customScales:e.customScales}));s=u.unmount,$t({doc:l.doc,localParticipantId:e.participantId,onEnded:async c=>{console.error(c.isLocal?"Session ended.":`Session ended by ${c.hostName}.`),s?.();try{await V();}catch(d){console.error(`Failed to clear cached session: ${d instanceof Error?d.message:String(d)}`);}l.disconnect(),process.exit(0);}}),await u.waitUntilExit(),a&&(console.error("This room is full (max 20 participants)."),V(),process.exit(1)),i&&(console.error(`Password changed \u2014 rejoin with: hnch join ${t.roomCode} --password`),V(),process.exit(0)),l.disconnect(),V(),process.exit(0);}async function Ps(e){if(!(e.name!==void 0||e.relayUrl!==void 0||e.scale!==void 0||e.sessionName!==void 0||e.password!==void 0)){let o=await se(),{waitUntilExit:r}=render(Wt.createElement(Zo,{presetOverrides:o.presetOverrides,customScales:o.customScales}));await r(),process.exit(0);}let n={};if(e.name!==void 0&&(n.displayName=e.name),e.relayUrl!==void 0&&(n.relayUrl=e.relayUrl),e.scale!==void 0){if(e.scale!==""){let o=Ne();if(!Nt(e.scale,o.presetOverrides,o.customScales)){console.error(`Unknown scale: "${e.scale}". Builtin IDs: ${Object.keys(ae).join(", ")}`);return}}n.defaultScale=e.scale;}e.sessionName!==void 0&&(n.defaultSessionName=e.sessionName),e.password!==void 0&&(n.defaultPassword=e.password),ot(n),console.log("Config updated.");}var dr=As(hideBin(process.argv)).scriptName("hnch").usage("$0 <command> \u2014 terminal pointing poker").command("create","Create a new room",e=>e.option("name",{type:"string",describe:"Session name"}).option("password",{type:"boolean",describe:"Protect room with a password"}).option("scale",{type:"string",describe:"Estimation scale ID (fibonacci, t-shirt, powers-of-2, linear, risk, or custom-<id>)"}),e=>{Es(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("join <code>","Join an existing room",e=>e.positional("code",{type:"string",demandOption:true,describe:"6-character room code"}).option("password",{type:"boolean",describe:"Room requires a password",default:false}),e=>{ks(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("resume","Rejoin your last session",e=>e,()=>{Ns().catch(e=>{console.error(e instanceof Error?e.message:e),process.exit(1);});}).command("config","View or update CLI config",e=>e.option("name",{type:"string",describe:"Set display name"}).option("relay-url",{type:"string",describe:"Set relay URL"}).option("scale",{type:"string",describe:"Set default estimation scale ID (empty string clears)"}).option("session-name",{type:"string",describe:"Set default session name (empty string clears)"}).option("password",{type:"boolean",describe:"Set default password prompt on (--password) or off (--no-password)"}),e=>{Ps(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("agenda","Manage the pre-session story agenda",e=>e.command("add","Add an agenda item",t=>t.option("title",{type:"string",describe:"Story title"}).option("ticket",{type:"string",describe:"Issue tracker reference (e.g. PROJ-123)"}).option("description",{type:"string",describe:"Story description"}).check(n=>{if(!n.title?.trim()&&!n.ticket?.trim())throw new Error("At least one of --title or --ticket is required");return true}),t=>{tr(t).catch(n=>{console.error(n instanceof Error?n.message:n),process.exit(1);});}).command("list","List agenda items in order",t=>t,()=>{nr().catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("skip <id>","Mark an agenda item as skipped",t=>t.positional("id",{type:"string",demandOption:true,describe:"Agenda item ID"}),t=>{or(t).catch(n=>{console.error(n instanceof Error?n.message:n),process.exit(1);});}).command("cancel <id>","Soft-delete (cancel) an agenda item",t=>t.positional("id",{type:"string",demandOption:true,describe:"Agenda item ID"}),t=>{rr(t).catch(n=>{console.error(n instanceof Error?n.message:n),process.exit(1);});}).command("mv <id>","Reorder an agenda item (--before <id> | --after <id>)",t=>t.positional("id",{type:"string",demandOption:true,describe:"Agenda item ID to move"}).option("before",{type:"string",describe:"sortKey of item that should come before the moved item"}).option("after",{type:"string",describe:"sortKey of item that should come after the moved item"}).check(n=>{if(n.before!==void 0&&n.after!==void 0)throw new Error("--before and --after are mutually exclusive");if(n.before===void 0&&n.after===void 0)throw new Error("Specify either --before <id> or --after <id>");return true}),t=>{ir(t).catch(n=>{console.error(n instanceof Error?n.message:n),process.exit(1);});}).demandCommand(1,"Specify an agenda subcommand: add, list, skip, cancel, mv").strict().help(),()=>{}).demandCommand(1,"Specify a command: create, join, resume, config, or agenda").strict().help(),On=hideBin(process.argv);(On.length===0||On.length===1&&On[0]==="--")&&(dr.showHelp(),process.exit(0));dr.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xauyxau/hnch",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
4
4
  "description": "Pointing poker CLI for agile teams",
5
5
  "keywords": [
6
6
  "pointing-poker",