@xauyxau/hnch 1.8.0 → 1.10.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 +20 -4
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,21 @@
1
1
  #!/usr/bin/env node
2
- import rs from'yargs';import {hideBin}from'yargs/helpers';import Ct,{useState,useEffect,useCallback,useMemo,useRef}from'react';import {render,useApp,useInput,Box,Text}from'ink';import*as ke 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 dr from'ws';import Kr from'clipboardy';import {jsxs,jsx,Fragment}from'react/jsx-runtime';var Vo="https://hnch.dev";function Ue(){let t=process.env.XDG_CONFIG_HOME||join(homedir(),".config");return join(t,"hnch")}function Pt(){return join(Ue(),"config.json")}function dn(){let e=Ue();existsSync(e)||mkdirSync(e,{recursive:true});}function ye(){let e=Pt();if(!existsSync(e))return {};try{return JSON.parse(readFileSync(e,"utf-8"))}catch{return {}}}function W(e){dn();let o={...ye(),...e};writeFileSync(Pt(),JSON.stringify(o,null,2)+`
3
- `,"utf-8");}async function Yo(e){let t=createInterface({input:process.stdin,output:process.stderr});return new Promise(o=>{t.question(e,n=>{t.close(),o(n.trim());});})}function Jo(e){return e.startsWith("wss://")?"https://"+e.slice(6):e.startsWith("ws://")?"http://"+e.slice(5):e}async function Le(){let e=ye(),t=false;if(e.participantId||(e.participantId=randomUUID(),t=true),!e.displayName){let n=await Yo("Enter your display name: ");e.displayName=n||`user-${e.participantId.slice(0,6)}`,t=true;}e.relayUrl||(e.relayUrl=Vo,t=true),t&&W(e);let o=process.env.HNCH_RELAY_URL||e.relayUrl;return o=Jo(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 je(e){dn();let o={...ye()};for(let[n,r]of Object.entries(e))r===""?delete o[n]:r!==void 0&&(o[n]=r);writeFileSync(Pt(),JSON.stringify(o,null,2)+`
4
- `,"utf-8");}var Wo={"unknown-room":4001,"wrong-password":4002,"invalid-invite":4003,"expired-invite":4004,"invite-already-redeemed":4005,"room-full":4006,"malformed-credentials":4010},ln=new Map(Object.entries(Wo).map(([e,t])=>[t,e]));function ve(e){return e.role??"voter"}function z(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 et={id:"fibonacci",cards:["0","1","2","3","5","8","13","21"]},un={id:"t-shirt",cards:["XS","S","M","L","XL"]},pn={id:"powers-of-2",cards:["1","2","4","8","16","32","64"]},fn={id:"linear",cards:["1","2","3","4","5","6","7","8","9","10"]},mn={id:"risk",cards:["Low","Medium","High","Critical"]},oe={[et.id]:et,[un.id]:un,[pn.id]:pn,[fn.id]:fn,[mn.id]:mn},gn={fibonacci:"Fibonacci","t-shirt":"T-shirt","powers-of-2":"Powers of 2",linear:"Linear (1\u201310)",risk:"Risk"};function hn(e){return e in gn?gn[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 qo="meta",_e="settings",Go="participants",zo="rounds",Qo=["roomUuid","createdAt","createdBy","sessionEndedAt"],Ko=["name","defaultScale","hostParticipantId"],Xo=["displayName","joinedAt","role","leftAt","removedBy"],Zo=["id","title","description","ticketId","parentRoundId","scale","timerStartedAt","revealedAt","skippedAt","createdBy","createdAt"];function tt(e){return e.getMap(qo)}function nt(e){return e.getMap(_e)}function ot(e){return e.getMap(Go)}function Ot(e){return e.getArray(zo)}function rt(e,t){let o={};for(let n of t){let r=e.get(n);r!==void 0&&(o[n]=r);}return o}function er(e){return rt(tt(e),Qo)}function tr(e){return rt(nt(e),Ko)}function nr(e){let t=ot(e),o=[];return t.forEach((n,r)=>{let s=rt(n,Xo);o.push({id:r,...s});}),o.sort((n,r)=>n.joinedAt-r.joinedAt||n.id.localeCompare(r.id)),o}function or(e){let t={};return e.forEach((o,n)=>{t[n]=o;}),t}function rr(e){let t=rt(e,Zo),o=e.get("votes"),n=o?or(o):{};return {...t,votes:n}}function sr(e){let t=Ot(e),o=[];return t.forEach(n=>{o.push(rr(n));}),o}function Q(e){return {meta:er(e),settings:tr(e),participants:nr(e),rounds:sr(e)}}function Sn(e,t){if(tt(e).has("roomUuid"))throw new Error("initDoc: doc already seeded");e.transact(()=>{let o=tt(e);o.set("roomUuid",t.roomUuid),o.set("createdAt",t.createdAt),o.set("createdBy",t.participantId);let n=nt(e);t.sessionName!==void 0&&n.set("name",t.sessionName),n.set("defaultScale",t.defaultScale),n.set("hostParticipantId",t.participantId);let r=new ke.Map;r.set("displayName",t.displayName),r.set("joinedAt",t.createdAt),ot(e).set(t.participantId,r);});}function st(e,t){e.transact(()=>{let o=ot(e),n=o.get(t.participantId),r=n??new ke.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 De(e,t){e.transact(()=>{let o=nt(e);for(let[n,r]of Object.entries(t))r===void 0?o.delete(n):o.set(n,r);});}function kt(e,t,o){e.transact(()=>{let n=ot(e),r=n.get(t),s=r??new ke.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 Dt(e,t){let o=t.scale??nt(e).get("defaultScale");if(!o)throw new Error("appendRound: no scale (settings.defaultScale missing)");return e.transact(()=>{let n=new ke.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 ke.Map),Ot(e).push([n]);}),t.id}function xn(e,t,o){let n=Fe(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 Fe(e,t){let o=Ot(e);for(let n=0;n<o.length;n+=1){let r=o.get(n);if(r.get("id")===t)return r}}function wn(e,t,o,n){let r=Fe(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 yn(e,t,o){let n=Fe(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 Mt(e,t,o){let n=Fe(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 vn(e,t,o){let n=Fe(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 Cn(e){e.transact(()=>{tt(e).set("sessionEndedAt",Date.now());});}function Z(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 bn(e){let t=Object.values(e.votes);return t.length<2?false:t.every(o=>o===t[0])}function Rn(e,t){let o=new Map;for(let a of t)o.set(a.id,a);let n=o.get(e);if(n===void 0||n.parentRoundId===void 0)return null;let r=new Set([n.id]),s=n,u=1;for(;s.parentRoundId!==void 0;){let a=o.get(s.parentRoundId);if(a===void 0||r.has(a.id))return null;r.add(a.id),s=a,u+=1;}let d=s,p=new Map;for(let a of t){if(a.parentRoundId===void 0)continue;let g=p.get(a.parentRoundId);g===void 0?p.set(a.parentRoundId,[a]):g.push(a);}let c=0,i=[d];for(;i.length>0;){let a=i.shift();c+=1;let g=p.get(a.id);g!==void 0&&i.push(...g);}return {chainRoot:d,depth:u,total:c}}var In="PBKDF2",ir="SHA-256",Tn=new TextEncoder;function ar(e){return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function Ce(e,t){let o=await crypto.subtle.importKey("raw",Tn.encode(e),In,false,["deriveBits"]),n=await crypto.subtle.deriveBits({name:In,salt:Tn.encode(t),iterations:1e5,hash:ir},o,256);return ar(n)}var En="ABCDEFGHJKMNPQRSTUVWXYZ23456789";if(En.length!==31)throw new Error(`Room code alphabet must be 31 characters, got ${En.length}`);function $t(e){return e.trim().replaceAll(/-/g,"").toUpperCase()}function An(e,t=true){let o=$t(e);return !t||o.length!==6?o:`${o.slice(0,3)}-${o.slice(3)}`}function it(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=oe[e];if(n){let r=(t??{})[e]??[];if(r.length===0)return n;let s=n.cards.filter((u,d)=>!r.includes(d));return s.length===0?void 0:{id:e,cards:s}}}function at(e,t){let o=Object.keys(oe).map(r=>it(r,e,t)).filter(r=>r!==void 0),n=(t??[]).map(r=>({id:r.id,cards:r.cards}));return [...o,...n]}function be(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 hn(e)}async function Nn(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 Ve(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 Bt(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 Pn(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:dr}),s=c=>{e.onStatusChange?.(c.status);},u=c=>{if(c===null)return;let i=ln.get(c.code);i!==void 0&&(e.onRejection?.(i),r.shouldConnect=false,r.disconnect());};r.on("status",s),r.on("connection-close",u);let d=false,p=e.passwordHash;return {doc:e.doc,awareness:r.awareness,updateCredentials(c){if(c.passwordHash===p)return;p=c.passwordHash??void 0,r.shouldConnect=false,r.disconnect();let a={did:r.params.did??""};p!==void 0&&(a.pw=p),r.params=a,r.connect();},disconnect(){d||(d=true,r.off("status",s),r.off("connection-close",u),r.shouldConnect=false,r.disconnect(),r.destroy());}}}var lr=5e3;function On(e,t,o){let n=null,r=null;function s(){let i=new Set;return t.getStates().forEach(a=>{let g=a.participantId;typeof g=="string"&&i.add(g);}),i}function u(){return e.getMap(_e).get("hostParticipantId")}function d(){r!==null&&(clearTimeout(r),r=null),n=null;}function p(){let i=u(),a=n;if(n=null,!a||i!==a)return;let g=s();if(g.has(i))return;let T=[...g].toSorted();if(T.length===0)return;let N=T[0];N===o&&De(e,{hostParticipantId:N});}function c(){let i=u();if(!i)return;if(s().has(i)){d();return}n!==i&&(d(),n=i,r=setTimeout(()=>{r=null,p();},lr));}return t.on("change",c),e.getMap(_e).observe(c),c(),{stop(){d(),t.off("change",c),e.getMap(_e).unobserve(c);}}}async function Mn(e){let t,o=await Nn(e.relayUrl);e.password&&(t=await Ce(e.password,o.uuid),await Bt(e.relayUrl,o.uuid,t));let n=new ke.Doc,r=new Awareness(n),s=Date.now();return Sn(n,{roomUuid:o.uuid,createdAt:s,participantId:e.participantId,displayName:e.displayName,defaultScale:e.defaultScale??et,...e.sessionName!==void 0&&{sessionName:e.sessionName}}),r.setLocalStateField("participantId",e.participantId),ct({doc:n,awareness:r,roomCode:o.code,roomUuid:o.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t})}async function $n(e){let t=await Ve(e.relayUrl,e.roomCode),o;if(t.accessMode==="password"){if(!e.password)throw new Error("Room requires a password");o=await Ce(e.password,t.uuid);}let n=new ke.Doc,r=new Awareness(n);return st(n,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId),ct({doc:n,awareness:r,roomCode:e.roomCode,roomUuid:t.uuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:o,onRejection:e.onRejection})}function ct(e){let{doc:t,awareness:o,participantId:n,relayUrl:r,roomUuid:s}=e,u=new Set,d=new Set,p=new Set,c=Pn({wsBaseUrl:e.relayUrl,roomUuid:e.roomUuid,doc:t,deviceId:n,passwordHash:e.passwordHash,awareness:o,onStatusChange(l){u.forEach(m=>m(l));},onRejection(l){console.error(`Connection rejected: ${l}`),e.onRejection?.(l);}}),i=On(t,o,n),a=()=>{d.forEach(l=>l());};t.getMap("meta").observeDeep(a),t.getMap("settings").observeDeep(a),t.getMap("participants").observeDeep(a),t.getArray("rounds").observeDeep(a);function g(){let l=new Set;return o.getStates().forEach(m=>{let w=m.participantId;typeof w=="string"&&l.add(w);}),l}let T=new Set,N=setInterval(()=>{let l=Q(t),m=Z(l);if(!m||m.revealedAt!==void 0||T.has(m.id))return;let w=g();if(w.size===0)return;let y=l.participants.filter(f=>w.has(f.id)&&ve(f)==="voter");if(y.length===0)return;y.filter(f=>f.id in m.votes).length>=y.length&&(T.add(m.id),Mt(t,m.id,Date.now()));},250),E=t.getMap("settings").get("hostParticipantId"),I=()=>{let l=t.getMap("settings").get("hostParticipantId");l!==E&&l!==void 0&&p.forEach(m=>m(l)),E=l;};t.getMap("settings").observe(I);let H=false;return {doc:t,awareness:o,roomCode:e.roomCode,roomUuid:e.roomUuid,projection(){return Q(t)},current(){return Z(Q(t))},isHost(){return Q(t).settings.hostParticipantId===n},onlineIds:g,vote(l){let m=Z(Q(t));m&&wn(t,m.id,n,l);},unvote(){let l=Z(Q(t));l&&yn(t,l.id,n);},reveal(){let l=Z(Q(t));l&&Mt(t,l.id,Date.now());},skip(){let l=Z(Q(t));l&&vn(t,l.id,Date.now());},newRound(l,m){let w=randomUUID();return Dt(t,{id:w,createdAt:Date.now(),createdBy:n,...l!==void 0&&{title:l},...m!==void 0&&{ticketId:m}}),w},revote(){let l=Z(Q(t)),m=randomUUID();return Dt(t,{id:m,createdAt:Date.now(),createdBy:n,...l?.id!==void 0&&{parentRoundId:l.id},...l?.title!==void 0&&{title:l.title},...l?.description!==void 0&&{description:l.description},...l?.ticketId!==void 0&&{ticketId:l.ticketId}}),m},updateRoundDescriptor(l,m){xn(t,l,m);},updateName(l){De(t,{name:l});},updateScale(l){De(t,{defaultScale:l});},updateDisplayName(l){let y=Q(t).participants.find(D=>D.id===n)?.joinedAt??Date.now();kt(t,n,{displayName:l,joinedAt:y});},async updateAccess(l,m){let w=null;if(l==="password"){if(!m)throw new Error("Password required for password mode");w=await Ce(m,s);}await Bt(r,s,w),c.updateCredentials({passwordHash:w});},handoffHost(l){if(!this.isHost())throw new Error("Only the current host can hand off");if(!g().has(l))throw new Error("Target participant is not online");if(!Q(t).participants.some(D=>D.id===l))throw new Error("Target participant does not exist");De(t,{hostParticipantId:l});},toggleRole(){let m=Q(t).participants.find(f=>f.id===n),y=ve(m??{})==="viewer"?"voter":"viewer",D=m?.joinedAt??Date.now();kt(t,n,{displayName:m?.displayName??"",joinedAt:D,role:y});},endSessionForEveryone(){if(!this.isHost())throw new Error("Only the current host can end the session");Cn(t);},onChange(l){return d.add(l),()=>d.delete(l)},onStatusChange(l){return u.add(l),()=>u.delete(l)},onHostChange(l){return p.add(l),()=>p.delete(l)},disconnect(){H||(H=true,clearInterval(N),i.stop(),t.getMap("meta").unobserveDeep(a),t.getMap("settings").unobserveDeep(a),t.getMap("settings").unobserve(I),t.getMap("participants").unobserveDeep(a),t.getArray("rounds").unobserveDeep(a),c.disconnect());}}}function Bn(e){let t=$t(e);return t===""?null:t}var Sr=1440*60*1e3;function Ut(){return join(Ue(),"last-session.json")}function xr(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 Un(){let e=Ut();if(!existsSync(e))return null;try{let t=JSON.parse(readFileSync(e,"utf-8"));return !xr(t)||Date.now()-t.lastSeenAt>Sr?(V(),null):t}catch{return V(),null}}function dt(e){let t=Ue();mkdirSync(t,{recursive:true,mode:448}),chmodSync(t,448);let o=Ut();writeFileSync(o,JSON.stringify(e,null,2)+`
5
- `,{encoding:"utf-8",mode:384}),chmodSync(o,384);}function V(){let e=Ut();try{unlinkSync(e);}catch(t){if(t.code!=="ENOENT")throw t}}async function lt(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 ut(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 u=t.get("createdBy"),d=u===e.localParticipantId,p=e.doc.getMap("participants"),c=e.doc.getMap("settings").get("hostParticipantId")??u,i="host";if(c){let g=p.get(c)?.get("displayName");typeof g=="string"&&g.length>0&&(i=g);}setImmediate(()=>{n||e.onEnded({isLocal:d,hostName:i,timestamp:s});});}return t.observe(r),r(),()=>{n=true,t.unobserve(r);}}var wr="@xauyxau/hnch";function pt(e){return An(e)}function ft(e){return `${process.env.HNCH_SHARE_ORIGIN??"https://hnch.dev"}/join?code=${e}`}function mt(e){return `npx ${wr} join ${e}`}function Lt(e){let t=e.trim();return t===""?void 0:t}function Ln(e,t){return [e,Lt(t)]}var yr={connecting:"yellow",connected:"green",disconnected:"red"};function Fn({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:yr[o],children:o})]})]})}function de({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(d=>!d.disabled),[s,u]=useState(Math.max(r,0));return useInput((d,p)=>{if(p.upArrow)u(c=>{let i=(c-1+e.length)%e.length,a=0;for(;e[i]?.disabled&&a<e.length;)i=(i-1+e.length)%e.length,a++;return i});else if(p.downArrow)u(c=>{let i=(c+1)%e.length,a=0;for(;e[i]?.disabled&&a<e.length;)i=(i+1)%e.length,a++;return i});else if(p.return){let c=e[s];c&&!c.disabled&&t(c.value);}else p.escape&&o?.();}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Text,{bold:true,children:n}),jsx(Box,{flexDirection:"column",children:e.map((d,p)=>{let c=p===s,i=d.disabled??false;return jsxs(Box,{gap:1,children:[jsx(Text,{...c&&{color:"cyan"},dimColor:i,children:c?">":" "}),jsx(Text,{bold:c,dimColor:i,children:d.label}),d.detail&&jsx(Text,{dimColor:true,children:d.detail})]},d.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:u=false}){useInput((i,a)=>{a.escape?n?.():a.return?o(e):a.backspace||a.delete?t(e.slice(0,-1)):i&&!a.ctrl&&!a.meta&&t(e+i);},{isActive:s});let d=u&&e.length>0?"*".repeat(e.length):e,p=d.length>0?d:r??"",c=e.length===0&&r!==void 0;return jsxs(Text,{children:[jsx(Text,{dimColor:c,children:p}),jsx(Text,{inverse:true,children:" "})]})}function Wn({mode:e,password:t,onModeChange:o,onPasswordChange:n,onClose:r}){let[s,u]=useState(e==="open"?0:1),[d,p]=useState(false);return useEffect(()=>{u(e==="open"?0:1);},[e]),useInput((c,i)=>{if(i.leftArrow)u(a=>Math.max(0,a-1));else if(i.rightArrow)u(a=>Math.min(1,a+1));else if(i.return){let a=s===0?"open":"password";a!==e&&o(a),a==="password"&&p(true);}else i.escape&&r?.();},{isActive:!d}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:["open","password"].map((c,i)=>{let a=i===s,g=c===e,T=c==="open"?"Open":"Password";return jsx(Text,{inverse:a,bold:g,...g&&{color:"cyan"},children:g?`[${T}]`:` ${T} `},c)})}),e==="password"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Password: "}),jsx(q,{value:t,onChange:n,onSubmit:()=>p(false),onCancel:()=>p(false),placeholder:"(required to join)",isActive:d,mask:true}),!d&&jsx(Text,{dimColor:true,children:"\u23CE edit \u2190 \u2192 switch mode esc close"}),d&&jsx(Text,{dimColor:true,children:"\u23CE done esc cancel"})]}),e==="open"&&jsx(Text,{dimColor:true,children:"\u2190\u2192 toggle \u23CE confirm esc close"})]})}function zn({scaleId:e,cards:t,disabledIndices:o,onOverrideChange:n,onClose:r}){let s=useMemo(()=>new Set(o),[o]),[u,d]=useState(0),p=c=>{let i=new Set(s);if(i.has(c))i.delete(c);else {if(i.size>=t.length-1)return;i.add(c);}let a=Array.from(i).toSorted((g,T)=>g-T);n(e,a);};return useInput((c,i)=>{i.leftArrow?d(a=>Math.max(0,a-1)):i.rightArrow?d(a=>Math.min(t.length-1,a+1)):c===" "?p(u):(i.return||i.escape)&&r();}),jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Box,{gap:1,children:t.map((c,i)=>{let a=i===u,g=s.has(i);return jsx(Text,{inverse:a,bold:!g,...!g&&{color:"cyan"},strikethrough:g,dimColor:g,children:c},c)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate space toggle \u23CE/esc done"})]})}function qt({initialName:e="",initialCards:t=[],onSave:o,onCancel:n}){let r=e.length>0,[s,u]=useState(e),[d,p]=useState(t.length>0?t:[""]),[c,i]=useState(0),[a,g]=useState("editing-name"),[T,N]=useState(""),E=()=>{let l=s.trim();if(l.length===0||l.length>40){N("Name must be 1-40 characters");return}u(l),N(""),g("editing-cards");},I=()=>{let l=s.trim();if(l.length===0||l.length>40){N("Name must be 1-40 characters");return}let m=d.map(y=>y.trim()).filter(y=>y.length>0),w=Array.from(new Set(m));if(w.length<2){N("Need at least 2 unique non-empty cards");return}N(""),o(l,w);};return useInput((l,m)=>{if(a==="editing-cards"){if(m.leftArrow)i(w=>Math.max(0,w-1));else if(m.rightArrow)i(w=>{let y=w+1;return y>=d.length&&d.length<25?(p(D=>[...D,""]),y):Math.min(y,d.length-1)});else if(m.return)I();else if(m.escape)n();else if(m.tab)g("editing-name");else if(m.backspace){let w=d[c]||"";if(w.length===0){if(d.length>2){let y=d.filter((D,f)=>f!==c);p(y),i(Math.max(0,c-1));}}else {let y=[...d];y[c]=w.slice(0,-1),p(y);}}else if(l&&!m.ctrl&&!m.meta){let w=d[c]||"";if(w.length<10){let y=[...d];y[c]=w+l,p(y);}}}},{isActive:a==="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:u,onSubmit:E,onCancel:n,placeholder:"Scale name",isActive:a==="editing-name"})]}),a==="editing-cards"&&jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Text,{children:"Cards:"}),jsx(Box,{gap:1,flexWrap:"wrap",children:d.map((l,m)=>{let w=m===c;return jsx(Text,{inverse:w,...!w&&{color:"cyan"},children:l.length>0?l:"\xB7"},m)})})]}),T&&jsx(Text,{color:"red",children:T}),jsx(Text,{dimColor:true,children:a==="editing-name"?"\u23CE next esc cancel":"\u2190\u2192 navigate typing adds card bsp delete \u23CE save tab name esc cancel"})]})}function St({scales:e,selectedScaleId:t,presetOverrides:o,customScales:n=[],onSelect:r,onOverrideChange:s,onCustomScaleCreate:u,onCustomScaleEdit:d,onCustomScaleDelete:p,onClose:c,showNoneOption:i=false}){let[a,g]=useState(0),[T,N]=useState(null),[E,I]=useState("browsing"),[H,l]=useState(null),[m,w]=useState(null),y=u?[...e,{id:"__create-custom__",cards:[]}]:e,D=y.length;if(useInput((f,M)=>{if(E==="browsing"){if(M.escape){c();return}if(D===0)return;if(M.upArrow)g(C=>(C-1+D)%D);else if(M.downArrow)g(C=>(C+1)%D);else if(M.return){let C=y[a];if(!C)return;if(C.id==="__create-custom__"){I("creating");return}C.id in oe?N(T===C.id?null:C.id):r(C.id);}else if(f===" "){let C=y[a];C&&C.id!=="__create-custom__"&&r(C.id);}else if(f==="e"||f==="E"){let C=y[a];d&&C?.id.startsWith("custom-")&&(l(C.id),I("editing"));}else if(f==="d"||f==="D"){let C=y[a];p&&C?.id.startsWith("custom-")&&(w(C.id),I("confirming-delete"));}}else E==="confirming-delete"&&(f==="y"||f==="Y"?(m&&p&&p(m),w(null),I("browsing")):(f==="n"||f==="N"||M.escape)&&(w(null),I("browsing")));},{isActive:E==="browsing"&&T===null||E==="confirming-delete"}),E==="creating")return jsx(qt,{onSave:(f,M)=>{u&&u(f,M),I("browsing");},onCancel:()=>I("browsing")});if(E==="editing"&&H){let f=n?.find(C=>C.id===H);if(e.find(C=>C.id===H)&&f)return jsx(qt,{initialName:f.label,initialCards:f.cards,onSave:(C,j)=>{d&&d(H,C,j),l(null),I("browsing");},onCancel:()=>{l(null),I("browsing");}})}if(E==="confirming-delete"&&m){let f=y.find(C=>C.id===m),M=f?be(f.id,n):"Unknown";return jsxs(Box,{flexDirection:"column",gap:1,children:[jsxs(Text,{children:["Delete ",M,"? "]}),jsx(Text,{children:"[y] yes [n] no esc cancel"})]})}return y.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:y.map((f,M)=>{let C=M===a,j=f.id===t,se=T===f.id,ee=f.id in oe,te=f.id==="__create-custom__",J=f.cards.join(", "),v=i&&f.id==="",b=v?"(none)":te?"[+ Create custom scale]":be(f.id,n);return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{...C&&{color:"cyan"},children:C?">":" "}),jsx(Text,{bold:C,children:b}),!v&&!te&&jsx(Text,{dimColor:true,children:J}),j&&jsx(Text,{color:"cyan",children:"[current]"})]}),se&&!v&&!te&&jsx(Box,{paddingLeft:2,children:ee?jsx(zn,{scaleId:f.id,cards:oe[f.id]?.cards??[],disabledIndices:o?.[f.id]??[],onOverrideChange:s,onClose:()=>N(null)}):null})]},f.id||"none")})}),jsx(Text,{dimColor:true,children:(()=>{let f=a<y.length?y[a]:null;return f?.id.startsWith("custom-")?`\u2191\u2193 navigate space select${d?" [e] edit":""}${p?" [d] delete":""} esc back`:f&&f.id in oe?"\u2191\u2193 navigate \u23CE customize space select esc back":"\u2191\u2193 navigate \u23CE/space select esc back"})()})]})}function Mr(e,t){return t?[...e]:e.filter(o=>o.value==="display-name")}function Qn({sessionName:e,displayName:t,currentScale:o,accessMode:n,presetOverrides:r,customScales:s,isHost:u=true,onChangeName:d,onChangeScale:p,onChangeDisplayName:c,onChangeAccess:i,onClose:a}){let[g,T]=useState(r??{}),N=useMemo(()=>at(g,s),[g,s]),[E,I]=useState("main-menu"),[H,l]=useState(e??""),[m,w]=useState(t),[y,D]=useState(n==="password"?"password":"open"),[f,M]=useState(""),[C,j]=useState(false),se=[{label:"Room name",value:"room-name",detail:`[${e??"(none)"}]`},{label:"Scale",value:"scale",detail:`[${be(o.id,s)}]`},{label:"Access",value:"access",detail:`[${n==="open"?"Open":"Password"}]`},{label:"Display name",value:"display-name",detail:`[${t}]`}],ee=Mr(se,u);function te(O){!u&&O!=="display-name"||(O==="room-name"?(l(e??""),I("editing-room-name")):O==="scale"?I("picking-scale"):O==="access"?I("picking-access"):O==="display-name"&&(w(t),I("editing-display-name")));}function J(O){let k=O.trim()===""?void 0:O.trim();d(k),I("main-menu");}function v(O){let k=O.trim();k.length>0&&(c(k),process.nextTick(()=>W({displayName:k}))),I("main-menu");}function b(O){let k=N.find(U=>U.id===O);k&&p(k),I("main-menu");}function P(O,k){let U={...g};k.length===0?delete U[O]:U[O]=k,T(U),W({presetOverrides:Object.keys(U).length>0?U:void 0});}async function _(O,k){j(true);try{await i(O,k),D(O),M(O==="password"?k??"":"");}catch(U){console.error(`Failed to update access: ${U}`);}finally{j(false),I("main-menu");}}return E==="main-menu"?jsx(de,{title:"\u2500\u2500 Settings \u2500\u2500",items:ee,onSelect:te,onClose:a}):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:H,onChange:l,onSubmit:J,onCancel:()=>I("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:w,onSubmit:v,onCancel:()=>I("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(St,{scales:N,selectedScaleId:o.id,presetOverrides:g,onSelect:b,onOverrideChange:P,onClose:()=>I("main-menu")})]}):E==="picking-access"?jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Settings \u2500\u2500"}),C&&jsx(Text,{dimColor:true,children:"Updating access..."}),!C&&jsx(Wn,{mode:y,password:f,onModeChange:O=>{O==="open"&&_("open");},onPasswordChange:M,onClose:()=>I("main-menu")})]}):jsx(Box,{})}function yt({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(u=>{let d=t.has(u.id),p=d?"\u25CF":"\u25CB",c=d?"green":"gray",i=u.id===o,a=ve(u)==="viewer",g=u.id===s,T=u.id in n,N=a?" (viewer)":r?n[u.id]?` \u2192 ${n[u.id]}`:"":T?" \u2713":" \xB7",E=g&&!a&&!(r&&n[u.id]);return jsxs(Box,{gap:1,children:[jsx(Text,{color:c,children:p}),jsxs(Text,{children:[u.displayName,i?" (host)":""]}),E?jsx(Text,{color:"cyan",children:"(voter)"}):jsx(Text,{color:a?"gray":T?"green":"gray",children:N})]},u.id)})]})}var $r=[{label:"End session for everyone",value:"end-session",detail:"Disconnects all participants. Cannot be undone."}];function Xn({onPick:e,onClose:t}){return jsx(de,{title:"Host Actions",items:$r,onSelect:e,onClose:t})}function vt({roomCode:e,onPick:t,onClose:o}){let n=[{label:"Copy code",value:"code",detail:pt(e)},{label:"Copy share link",value:"url",detail:ft(e)},{label:"Copy npx command",value:"npx",detail:mt(e)}];return jsx(de,{title:"Share",items:n,onSelect:r=>t(r),onClose:o})}function Zn(e,t,o){let n=Rn(e.id,o);return n===null?`Round ${t}`:`Round ${n.depth}/${n.total} [re-vote]`}function eo(e,t,o){let n=Zn(e,t,o),r=e.title?` \u2014 ${e.title}`:"",s=e.ticketId?` [${e.ticketId}]`:"",u=z(e)==="skipped"?" \u2014 Skipped":" \u2014 Results";return `${n}${r}${s}${u}`}function to(e){let t=Object.values(e).map(i=>parseFloat(i)).filter(i=>!isNaN(i)).toSorted((i,a)=>i-a);if(t.length===0)return {average:"-",median:"-",agreement:"-"};let n=t.reduce((i,a)=>i+a,0)/t.length,r=Math.floor(t.length/2),s=t.length%2===0?(t[r-1]+t[r])/2:t[r],u=Object.values(e),d=new Map;for(let i of u)d.set(i,(d.get(i)??0)+1);let p=Math.max(...d.values()),c=u.length>0?Math.round(p/u.length*100):0;return {average:n.toFixed(1),median:s.toFixed(1),agreement:`${c}%`}}function zt(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 no(e,t,o=[]){let n=Zn(e,t,o);if(z(e)==="skipped"){let c=e.title?` ${e.title}`:"",i=e.ticketId?` [${e.ticketId}]`:"";return `${n}:${c}${i} \u2014 Skipped`}let r=new Map;for(let c of Object.values(e.votes))r.set(c,(r.get(c)??0)+1);let s=[...r.entries()].toSorted((c,i)=>i[1]-c[1]||c[0].localeCompare(i[0])).map(([c,i])=>`${c}\xD7${i}`).join(", "),u=e.title?` ${e.title}`:"",d=e.ticketId?` [${e.ticketId}]`:"",p=e.timerStartedAt!==void 0&&e.revealedAt!==void 0?` \u2014 ${zt(e.timerStartedAt,e.revealedAt)}`:"";return `${n}:${u}${d} \u2014 ${s||"(no votes)"}${p}`}function oo({projection:e,onlineIds:t,isHost:o,participantId:n,rounds:r,currentRound:s,settingsOpen:u,onStartRound:d,onNewRound:p,onRevote:c,onOpenSettings:i,onHandoffHost:a,onEndSession:g,onShare:T,shareOpen:N,onSetShareOpen:E,roomCode:I,confirmingQuit:H,myRole:l,onToggleRole:m,roundTitlePromptActive:w,roundTitleInput:y,onRoundTitleChange:D,onRoundTitleSubmit:f,onRoundTitleCancel:M,roundTicketIdPromptActive:C,roundTicketIdInput:j,onRoundTicketIdChange:se,onRoundTicketIdSubmit:ee,onRoundTicketIdCancel:te,descriptorPromptActive:J,descriptorInput:v,onDescriptorChange:b,onDescriptorSubmit:P,onDescriptorCancel:_,onEditDescriptor:O}){let[k,U]=Ct.useState("idle"),[fe,ce]=Ct.useState(null),[Pe,Se]=Ct.useState(false),[ne,xe]=Ct.useState(false);useEffect(()=>{o||(U("idle"),ce(null),Se(false),xe(false));},[o]),useInput(h=>{if(h==="c"||h==="C"){E(true);return}if(h==="w"||h==="W"){m();return}o&&((h==="e"||h==="E")&&i(),(h==="s"||h==="S")&&d(),(h==="h"||h==="H")&&U("picking"),(h==="m"||h==="M")&&Se(true),s!==null&&z(s)!==null&&((h==="n"||h==="N")&&p(),(h==="v"||h==="V")&&z(s)!=="skipped"&&c(),(h==="t"||h==="T")&&O()));},{isActive:!u&&!H&&k==="idle"&&!w&&!C&&!Pe&&!ne&&!N&&!J}),useInput((h,X)=>{h==="y"||h==="Y"?(g(),xe(false)):(h==="n"||h==="N"||X.escape)&&xe(false);},{isActive:ne});let me=e.participants.filter(h=>h.id!==n&&t.has(h.id));useInput(h=>{if(k==="picking"){let X=parseInt(h,10);!isNaN(X)&&X>=1&&X<=me.length?(ce(me[X-1].id),U("confirming")):(h==="Escape"||h==="q"||h==="Q")&&U("idle");}},{isActive:k==="picking"}),useInput(h=>{k==="confirming"&&fe&&(h==="y"||h==="Y"?(a(fe),U("idle"),ce(null)):(h==="n"||h==="N"||h==="Escape")&&(U("idle"),ce(null)));},{isActive:k==="confirming"});let we=r.length>0,Ke=r.filter(h=>z(h)!==null),He=s!==null?Ke.slice(0,-1):Ke;return Pe?jsx(Xn,{onPick:h=>{Se(false),h==="end-session"&&xe(true);},onClose:()=>Se(false)}):N?jsx(vt,{roomCode:I,onPick:h=>{E(false),T(h);},onClose:()=>E(false)}):jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:we?"Session":"Waiting for participants..."}),!we&&jsx(Text,{dimColor:true,children:"No rounds started yet."}),jsx(yt,{participants:e.participants,onlineIds:t,hostId:e.settings.hostParticipantId,votes:{},revealed:false,participantId:n}),s!==null&&z(s)!==null&&jsx(Lr,{projection:e,round:s,rounds:r}),He.length>0&&jsxs(Box,{flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"\u2500\u2500 History \u2500\u2500"}),He.map(h=>{let X=r.indexOf(h)+1;return jsx(Text,{dimColor:true,children:no(h,X,r)},h.id)})]}),k==="picking"&&me.length>0&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Hand off to:"}),me.map((h,X)=>jsxs(Text,{children:["[",X+1,"] ",h.displayName]},h.id)),jsx(Text,{dimColor:true,children:"[q] Cancel"})]}),k==="picking"&&me.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"})]}),k==="confirming"&&fe&&jsx(Box,{flexDirection:"column",children:jsxs(Text,{children:["Hand off to ",e.participants.find(h=>h.id===fe)?.displayName,"? [y/n]"]})}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Round title (optional, Enter to skip):"}),jsx(q,{value:y,onChange:D,onSubmit:f,onCancel:M,placeholder:"Enter to skip",isActive:w})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel"})]}),C&&jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{gap:1,children:[jsx(Text,{children:"Ticket ID (optional, Enter to skip):"}),jsx(q,{value:j,onChange:se,onSubmit:ee,onCancel:te,placeholder:"e.g. PROJ-1234",isActive:C})]}),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(q,{value:v,onChange:b,onSubmit:P,onCancel:_,placeholder:"Enter to save",isActive:J})]}),jsx(Text,{dimColor:true,children:"[Esc] Cancel \xB7 empty submit cancels"})]}),ne&&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"})]}),k==="idle"&&!w&&!C&&!J&&!ne&&jsxs(Box,{gap:2,children:[o?jsx(Fragment,{children:s!==null&&z(s)!==null?jsxs(Fragment,{children:[z(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"}),jsxs(Text,{color:"yellow",children:["[w] ",l==="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"}),jsxs(Text,{color:"yellow",children:["[w] ",l==="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"}),jsxs(Text,{color:"yellow",children:["[w] ",l==="viewer"?"Vote":"Observe"]})]}),jsx(Text,{children:"[q] Quit"})]})]})}function Lr({projection:e,round:t,rounds:o}){let n=o.indexOf(t)+1,r=eo(t,n,o);if(z(t)==="skipped")return jsx(Box,{flexDirection:"column",gap:1,children:jsx(Text,{bold:true,children:r})});let s=to(t.votes),u=new Map(e.participants.map(c=>[c.id,c.displayName])),d=t.timerStartedAt!==void 0&&t.revealedAt!==void 0?zt(t.timerStartedAt,t.revealedAt):null,p=Object.values(t.votes)[0];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:r}),bn(t)&&jsxs(Text,{bold:true,color:"green",children:["Consensus! Everyone voted ",p]}),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)})]}),Object.entries(t.votes).map(([c,i])=>jsxs(Box,{gap:2,children:[jsx(Text,{children:(u.get(c)??c).padEnd(20)}),jsx(Text,{color:"cyan",bold:true,children:i.padEnd(10)})]},c)),e.participants.filter(c=>!(c.id in t.votes)).map(c=>jsxs(Box,{gap:2,children:[jsx(Text,{dimColor:true,children:c.displayName.padEnd(20)}),jsx(Text,{dimColor:true,children:"(no vote)".padEnd(10)})]},c.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})]}),d!==null&&jsxs(Text,{dimColor:true,children:["\u23F1 ",d]})]})]})}function io({scale:e,selected:t,onSelect:o,onClear:n,disabled:r}){let[s,u]=useState(0);return useInput((d,p)=>{if(!r)if(p.leftArrow)u(c=>Math.max(0,c-1));else if(p.rightArrow)u(c=>Math.min(e.cards.length-1,c+1));else if(p.return){let c=e.cards[s];c===t?n():o(c);}else (p.backspace||p.delete)&&n();}),jsxs(Box,{flexDirection:"column",gap:0,children:[jsx(Box,{gap:1,children:e.cards.map((d,p)=>{let c=p===s,i=d===t;return jsx(Text,{inverse:c,bold:i,...i&&{color:"cyan"},children:i?`[${d}]`:` ${d} `},d)})}),jsx(Text,{dimColor:true,children:" \u2190\u2192 navigate \u23CE select \u232B clear"})]})}function Yr(e){let t=Math.floor(e/1e3),o=Math.floor(t/60),n=t%60;return `${o}:${n.toString().padStart(2,"0")}`}function ao({projection:e,round:t,onlineIds:o,isHost:n,myId:r,myRole:s,elapsedMs:u,roomCode:d,shareOpen:p,settingsOpen:c,onVote:i,onClearVote:a,onReveal:g,onSkip:T,onToggleRole:N,onShare:E,onSetShareOpen:I,onOpenSettings:H,confirmingQuit:l}){if(useInput(f=>{if(f==="e"||f==="E"){H();return}if(f==="c"||f==="C"){I(true);return}n&&(f==="r"||f==="R")&&g(),n&&(f==="s"||f==="S")&&T(),(f==="w"||f==="W")&&N();},{isActive:!l&&!c&&!p}),p)return jsx(vt,{roomCode:d,onPick:f=>{I(false),E(f);},onClose:()=>I(false)});let m=t.votes[r],w=e.rounds.indexOf(t)+1,y=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 ",w,y,D]}),u!==void 0&&jsxs(Text,{dimColor:true,children:["\u23F1 ",Yr(u)]})]}),jsxs(Box,{gap:4,children:[jsx(yt,{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"})}):jsx(io,{scale:t.scale,selected:m,onSelect:i,onClear:a,disabled:l})]}),jsxs(Box,{gap:2,children:[n&&jsx(Text,{color:"yellow",children:"[r] Reveal"}),n&&jsx(Text,{color:"yellow",children:"[s] Skip"}),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 Gr=3e3;function Xt(e=Gr){let[t,o]=useState(null),n=useRef(null),r=useCallback(()=>{n.current!==null&&(clearTimeout(n.current),n.current=null);},[]),s=useCallback(d=>{r(),o(d),n.current=setTimeout(()=>{o(null),n.current=null;},e);},[r,e]),u=useCallback(()=>{r(),o(null);},[r]);return useEffect(()=>()=>{r();},[r]),{notice:t,show:s,dismiss:u}}function Xr(e){let t=Z(e);return !t||z(t)!==null?"lobby":"voting"}function Tt({session:e,participantId:t,displayName:o,accessMode:n,presetOverrides:r,customScales:s}){let{exit:u}=useApp(),[d,p]=useState(e.projection()),[c,i]=useState("connecting"),[a,g]=useState(e.onlineIds()),[T,N]=useState(),[E,I]=useState(false),[H,l]=useState(n==="password"?"password":"open"),[m,w]=useState(o),[y,D]=useState(false),[f,M]=useState(false),[C,j]=useState(""),[se,ee]=useState(false),[te,J]=useState(""),[v,b]=useState(),[P,_]=useState(false),[O,k]=useState(""),[U,fe]=useState(null),ce=Xt(3e3),[Pe,Se]=useState(false),ne=Xt(3e3);useEffect(()=>{let R=e.onChange(()=>{p(e.projection()),g(e.onlineIds());}),F=e.onStatusChange(i),Oe=e.onHostChange(Xe=>{let $o=e.projection().participants.find(Ho=>Ho.id===Xe),Bo=Xe===t?"You are now the host":`${$o?.displayName||"Unknown"} is now the host`;ce.show(Bo);}),Mo=setInterval(()=>{g(e.onlineIds());let Xe=e.projection(),Ze=Z(Xe);Ze?.timerStartedAt!==void 0&&Ze.revealedAt===void 0?N(Date.now()-Ze.timerStartedAt):N(void 0);},1e3);return ()=>{R(),F(),Oe(),clearInterval(Mo);}},[e,t,ce.show]),useInput(R=>{(R==="q"||R==="Q")&&D(true);},{isActive:!E&&!y&&!f&&!se&&!P&&!Pe}),useInput((R,F)=>{R==="y"||R==="Y"?(e.disconnect(),u()):(R==="n"||R==="N"||F.escape)&&D(false);},{isActive:y});let xe=Xr(d),me=Z(d),we=d.settings.hostParticipantId===t,Ke=d.participants.find(R=>R.id===t),He=ve(Ke??{}),h=useCallback(()=>{j(""),M(true);},[]),X=useCallback(R=>{M(false),j(""),b(Lt(R)),J(""),ee(true);},[]),mo=useCallback(()=>{M(false),j(""),b(void 0);},[]),go=useCallback(R=>{ee(false),J("");let[F,Oe]=Ln(v,R);e.newRound(F,Oe),b(void 0);},[e,v]),ho=useCallback(()=>{ee(false),J(""),b(void 0);},[]),So=useCallback(()=>{let R=e.current();!R||R.revealedAt===void 0||(fe(R.id),k(R.title??""),_(true));},[e]),xo=useCallback(R=>{let F=U;if(_(false),fe(null),!F)return;let Oe=R.trim();Oe!==""&&e.updateRoundDescriptor(F,{title:Oe});},[e,U]),wo=useCallback(()=>{_(false),fe(null);},[]),yo=useCallback(R=>{e.vote(R);},[e]),vo=useCallback(()=>{e.unvote();},[e]),Co=useCallback(()=>{e.reveal();},[e]),bo=useCallback(()=>{e.skip();},[e]),Ro=useCallback(()=>{j(""),M(true);},[]),Io=useCallback(()=>{e.revote();},[e]),nn=useCallback(()=>{e.toggleRole();},[e]),To=useCallback(R=>{e.updateName(R);},[e]),Eo=useCallback(R=>{e.updateScale(R);},[e]),Ao=useCallback(R=>{e.updateDisplayName(R),w(R);},[e]),No=useCallback(async(R,F)=>{await e.updateAccess(R,F),l(R);},[e]),Po=useCallback(R=>{try{e.handoffHost(R);}catch(F){console.error(`Handoff failed: ${F instanceof Error?F.message:String(F)}`);}},[e]),on=useCallback(()=>{I(true);},[]),Oo=useCallback(()=>{I(false);},[]),ko=useCallback(()=>{e.endSessionForEveryone();},[e]),rn=useCallback(async R=>{let F=R==="code"?pt(e.roomCode):R==="url"?ft(e.roomCode):mt(e.roomCode);try{await Kr.write(F),ne.show("Copied!");}catch{ne.show(`Copy failed \u2014 ${F}`);}},[e.roomCode,ne]),sn=d.rounds.filter(R=>z(R)!==null),Do=sn.length>0?sn.at(-1):null;return jsxs(Box,{flexDirection:"column",children:[jsx(Fn,{roomCode:e.roomCode,sessionName:d.settings.name,status:c,isHost:we}),ce.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:ce.notice})}),ne.notice&&jsx(Box,{paddingX:1,children:jsx(Text,{color:ne.notice.startsWith("Copy failed")?"red":"green",children:ne.notice})}),E?jsx(Qn,{sessionName:d.settings.name,displayName:m,currentScale:d.settings.defaultScale,accessMode:H,presetOverrides:r,customScales:s,isHost:we,onChangeName:To,onChangeScale:Eo,onChangeDisplayName:Ao,onChangeAccess:No,onClose:Oo}):xe==="lobby"?jsx(oo,{projection:d,onlineIds:a,isHost:we,participantId:t,rounds:d.rounds,currentRound:Do,settingsOpen:E,onStartRound:h,onNewRound:Ro,roundTitlePromptActive:f,roundTitleInput:C,onRoundTitleChange:j,onRoundTitleSubmit:X,onRoundTitleCancel:mo,roundTicketIdPromptActive:se,roundTicketIdInput:te,onRoundTicketIdChange:J,onRoundTicketIdSubmit:go,onRoundTicketIdCancel:ho,onRevote:Io,onOpenSettings:on,onHandoffHost:Po,onEndSession:ko,onShare:rn,shareOpen:Pe,onSetShareOpen:Se,roomCode:e.roomCode,confirmingQuit:y,myRole:He,onToggleRole:nn,descriptorPromptActive:P,descriptorInput:O,onDescriptorChange:k,onDescriptorSubmit:xo,onDescriptorCancel:wo,onEditDescriptor:So}):xe==="voting"&&me?jsx(ao,{projection:d,round:me,onlineIds:a,isHost:we,myId:t,myRole:He,elapsedMs:T,onVote:yo,onClearVote:vo,onReveal:Co,onSkip:bo,onToggleRole:nn,onShare:rn,onSetShareOpen:Se,shareOpen:Pe,settingsOpen:E,onOpenSettings:on,roomCode:e.roomCode,confirmingQuit:y}):null,y&&jsx(Box,{children:jsx(Text,{dimColor:true,children:"Leave session? y/n"})})]})}function lo({presetOverrides:e,customScales:t}){let{exit:o}=useApp(),[n,r]=useState("main-menu"),[s,u]=useState(ye()),[d,p]=useState(s.displayName??""),[c,i]=useState(s.relayUrl??""),[a,g]=useState(s.defaultSessionName??""),[T,N]=useState(t??[]),[E,I]=useState(e??{});useInput(v=>{(v==="q"||v==="Q")&&o();},{isActive:n==="main-menu"});let H=useMemo(()=>at(E,T),[E,T]),l=s.defaultScale,m=l?H.find(v=>v.id===l):void 0,w=[{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?be(m.id,T):"(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 y(v){v==="display-name"?(p(s.displayName??""),r("editing-display-name")):v==="relay-url"?(i(s.relayUrl??""),r("editing-relay-url")):v==="default-scale"?r("picking-scale"):v==="default-session-name"?(g(s.defaultSessionName??""),r("editing-session-name")):v==="default-password"&&r("picking-default-password");}function D(v){let b=v.trim();if(b.length>0){let P={...s,displayName:b};u(P),W({displayName:b});}r("main-menu");}function f(v){let b=v.trim();if(b.length>0){let P={...s,relayUrl:b};u(P),W({relayUrl:b});}r("main-menu");}function M(v){let b=v.trim(),P=b.length>0?{...s,defaultSessionName:b}:{...s};b.length===0?(delete P.defaultSessionName,u(P),je({defaultSessionName:""})):(u(P),W({defaultSessionName:b})),r("main-menu");}function C(v){let b=v.length>0?{...s,defaultScale:v}:{...s};v.length===0?(delete b.defaultScale,u(b),je({defaultScale:""})):(u(b),W({defaultScale:v})),r("main-menu");}function j(v,b){let P={...E};b.length===0?delete P[v]:P[v]=b,I(P),W({presetOverrides:Object.keys(P).length>0?P:void 0});}function se(v){let b=v==="on",P={...s,defaultPassword:b};u(P),W({defaultPassword:b}),r("main-menu");}function ee(v,b){let P=`custom-${randomUUID()}`,_=[...T,{id:P,label:v,cards:b}];N(_),u({...s,customScales:_}),W({customScales:_});}function te(v,b,P){let _=T.map(O=>O.id===v?{id:v,label:b,cards:P}:O);N(_),u({...s,customScales:_}),W({customScales:_});}function J(v){let b=T.filter(_=>_.id!==v);N(b);let P={...s,customScales:b};s.defaultScale===v?(P.defaultScale="fibonacci",W({customScales:b,defaultScale:"fibonacci"})):W({customScales:b}),u(P);}if(n==="main-menu")return jsx(de,{title:"\u2500\u2500 Config Settings \u2500\u2500",items:w,onSelect:y,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:d,onChange:p,onSubmit:D,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:c,onChange:i,onSubmit:f,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:a,onChange:g,onSubmit:M,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 v=[{id:"",cards:[]},...H];return jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{bold:true,children:"\u2500\u2500 Config Settings \u2500\u2500"}),jsx(St,{scales:v,selectedScaleId:l??"",presetOverrides:E,customScales:T,onSelect:C,onOverrideChange:j,onCustomScaleCreate:ee,onCustomScaleEdit:te,onCustomScaleDelete:J,onClose:()=>r("main-menu"),showNoneOption:true})]})}if(n==="picking-default-password"){let v=[{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(de,{title:"Default password:",items:v,onSelect:se,onClose:()=>r("main-menu")})]})}return jsx(Box,{})}async function tn(){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 Le(),o=e.scale??t.defaultScale??"fibonacci",n=e.name??t.defaultSessionName,r=e.password??t.defaultPassword??false,s;r&&(s=await tn());let u=it(o,t.presetOverrides,t.customScales);if(!u){let a=Object.keys(oe).join(", ");console.error(`Unknown or fully-disabled scale: "${o}". Builtin IDs: ${a}`),process.exit(1);}let d=await Mn({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,sessionName:n,password:s,defaultScale:u}),p;s&&(p=await Ce(s,d.roomUuid)),dt({roomCode:d.roomCode,roomUuid:d.roomUuid,passwordHash:p,lastSeenAt:Date.now()}),console.error(`Room created: ${d.roomCode}`),console.error(`Share: hnch join ${d.roomCode}`),console.error("");let{waitUntilExit:c,unmount:i}=render(Ct.createElement(Tt,{session:d,participantId:t.participantId,displayName:t.displayName,accessMode:s?"password":"open",presetOverrides:t.presetOverrides,customScales:t.customScales}));ut({doc:d.doc,localParticipantId:t.participantId,onEnded:async a=>{console.error(a.isLocal?"Session ended.":`Session ended by ${a.hostName}.`),i();try{await V();}catch(g){console.error(`Failed to clear cached session: ${g instanceof Error?g.message:String(g)}`);}d.disconnect(),process.exit(0);}}),await c(),d.disconnect(),V(),process.exit(0);}async function cs(e){let t=await Le(),o=Bn(e.code);o===null&&(console.error("invalid room code"),process.exit(1));let n;e.password&&(n=await tn());let r=await Ve(t.relayUrl,o),s;r.accessMode==="password"&&!e.password?s=await tn():e.password&&(s=n);let u,d=false,p=await $n({participantId:t.participantId,displayName:t.displayName,relayUrl:t.relayUrl,roomCode:o,password:s,onRejection(a){if(a==="unknown-room"){lt({clearLastSession:V,logger:console,exit:process.exit});return}a==="room-full"&&(d=true,u?.());}}),c;s&&(c=await Ce(s,p.roomUuid)),dt({roomCode:p.roomCode,roomUuid:p.roomUuid,passwordHash:c,lastSeenAt:Date.now()}),console.error(`Joined room: ${p.roomCode}`),console.error("");let i=render(Ct.createElement(Tt,{session:p,participantId:t.participantId,displayName:t.displayName,accessMode:r.accessMode,presetOverrides:t.presetOverrides,customScales:t.customScales}));u=i.unmount,ut({doc:p.doc,localParticipantId:t.participantId,onEnded:async a=>{console.error(a.isLocal?"Session ended.":`Session ended by ${a.hostName}.`),u?.();try{await V();}catch(g){console.error(`Failed to clear cached session: ${g instanceof Error?g.message:String(g)}`);}p.disconnect(),process.exit(0);}}),await i.waitUntilExit(),d&&(console.error("This room is full (max 20 participants)."),p.disconnect(),V(),process.exit(1)),p.disconnect(),V(),process.exit(0);}async function ds(){let e=await Le(),t=Un();t||(console.error("No recent session to resume."),process.exit(0));let o;try{o=await Ve(e.relayUrl,t.roomCode);}catch(i){if((i instanceof Error?i.message:String(i)).includes("Room not found"))return await lt({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 ke.Doc,r=new Awareness(n);st(n,{participantId:e.participantId,displayName:e.displayName}),r.setLocalStateField("participantId",e.participantId);let s=false,u=false,d,p=ct({doc:n,awareness:r,roomCode:t.roomCode,roomUuid:t.roomUuid,participantId:e.participantId,relayUrl:e.relayUrl,passwordHash:t.passwordHash,onRejection(i){if(i==="unknown-room"){lt({clearLastSession:V,logger:console,exit:process.exit});return}i==="wrong-password"&&(s=true,d?.()),i==="room-full"&&(u=true,d?.());}});dt({roomCode:p.roomCode,roomUuid:p.roomUuid,passwordHash:t.passwordHash,lastSeenAt:Date.now()});let c=render(Ct.createElement(Tt,{session:p,participantId:e.participantId,displayName:e.displayName,accessMode:o.accessMode,presetOverrides:e.presetOverrides,customScales:e.customScales}));d=c.unmount,ut({doc:p.doc,localParticipantId:e.participantId,onEnded:async i=>{console.error(i.isLocal?"Session ended.":`Session ended by ${i.hostName}.`),d?.();try{await V();}catch(a){console.error(`Failed to clear cached session: ${a instanceof Error?a.message:String(a)}`);}p.disconnect(),process.exit(0);}}),await c.waitUntilExit(),u&&(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)),p.disconnect(),V(),process.exit(0);}async function ls(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 Le(),{waitUntilExit:r}=render(Ct.createElement(lo,{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=ye();if(!it(e.scale,n.presetOverrides,n.customScales)){console.error(`Unknown scale: "${e.scale}". Builtin IDs: ${Object.keys(oe).join(", ")}`);return}}o.defaultScale=e.scale;}e.sessionName!==void 0&&(o.defaultSessionName=e.sessionName),e.password!==void 0&&(o.defaultPassword=e.password),je(o),console.log("Config updated.");}var fo=rs(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=>{cs(e).catch(t=>{console.error(t instanceof Error?t.message:t),process.exit(1);});}).command("resume","Rejoin your last session",e=>e,()=>{ds().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=>{ls(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(),en=hideBin(process.argv);(en.length===0||en.length===1&&en[0]==="--")&&(fo.showHelp(),process.exit(0));fo.parse();
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}
6
+
7
+ ${R}
8
+
9
+ ${$}`:`${E}
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}
12
+
13
+ ${k}
14
+
15
+ ${h}`:`${v}
16
+
17
+ ${k}`;l.push(P);}}return l.join(`
18
+
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();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xauyxau/hnch",
3
- "version": "1.8.0",
3
+ "version": "1.10.0",
4
4
  "description": "Pointing poker CLI for agile teams",
5
5
  "keywords": [
6
6
  "pointing-poker",