@promptctl/cc-candybar 1.158.0 → 1.159.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i,pathToFileURL as a}from"node:url";import{json as o}from"node:stream/consumers";import s,{basename as c,dirname as l,isAbsolute as u,join as d,sep as f}from"node:path";import p,{closeSync as m,constants as h,existsSync as g,fstatSync as _,openSync as v,readSync as y,realpathSync as b,statSync as ee,watch as x}from"node:fs";import S,{createHash as te,createHmac as ne,randomBytes as re,randomUUID as ie,timingSafeEqual as ae}from"node:crypto";import C,{homedir as w}from"node:os";import{spawn as oe,spawnSync as se}from"node:child_process";import{inspect as T,parseArgs as ce,types as le}from"node:util";import ue from"node:net";import de from"node:v8";import{open as fe,readFile as pe,readdir as me,stat as he}from"node:fs/promises";import{clearInterval as ge,setImmediate as _e,setInterval as ve}from"node:timers";import{get as ye}from"node:https";import{setTimeout as be}from"node:timers/promises";import{WriteStream as xe}from"node:tty";import{createInterface as Se}from"node:readline";var Ce=Object.create,we=Object.defineProperty,Te=Object.getOwnPropertyDescriptor,Ee=Object.getOwnPropertyNames,De=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty,ke=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ae=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ee(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Oe.call(e,s)&&s!==n&&we(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Te(t,s))||r.enumerable});return e},je=(e,t,n)=>(n=e==null?{}:Ce(De(e)),Ae(t||!e||!e.__esModule?we(n,`default`,{value:e,enumerable:!0}):n,e));function E(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const Me=(e,t)=>E(t),Ne=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Pe(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Fe(e){return Ne.test(e)?e:Pe(e)}function Ie(e){return`${e.dir===void 0?``:`cd ${Fe(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Fe(t)} `).join(``)}${[e.program,...e.args].map(Fe).join(` `)}`}const Le=`cc-extra`;function Re(e){return s.join(s.dirname(e),Le,`src`,`bun-attach.js`)}function ze(e){return s.join(s.dirname(e),`bun-graph.js`)}const Be=`attach-preload.cjs`;function Ve(e){return s.join(s.dirname(e),Be)}function He(e,t){return Ie({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Ue=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function We(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function Ge(e,t,n=Ue){return p.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=p.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?Ge(e,r):[[s.relative(e,r).split(s.sep).join(`/`),We(r,i)]]})}function Ke(e){let t=S.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function qe(e){return Ke(Ge(e,e))}const Je=[`Cargo.toml`,`Cargo.lock`,`src`];function Ye(e){return Ke(Ge(e,e,e=>Je.includes(e)))}const Xe=e=>e.slice(0,7),Ze=`1.158.0`;function Qe(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function $e(){let e=et();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Ze,digest:e}}function et(){return`688b4dc3f21b65922b73cbabc03fb46def20d767d18b8f61e0498528fe1f7bd3`}function tt(e){let t=JSON.parse(p.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function nt(e,t){try{let n=Qe(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=qe(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:tt(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function rt(e,t){return le.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const it={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},at=new Map;function ot(e){let t=it[e];if(t===void 0)return{allowed:!0};let n=at.get(e);if(n===void 0)return{allowed:!0};let r=Date.now()-n;return r>=t?{allowed:!0}:{allowed:!1,minIntervalMs:t,sinceLastMs:r}}function st(e){at.set(e,Date.now())}function ct(e){return e.env??process.env}function lt(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${n}ms ago`}}let ut=null;function dt(e){ut=e}function ft(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function pt(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();return ut?.onStart(e.category),new Promise(t=>{let r;try{r=oe(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ut?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(r,e.cwd)});return}let i=``,a=``,o=!1,s=null,c=null,l=null,u=()=>m(`aborted`),d=t=>{o||(o=!0,s&&clearTimeout(s),c&&clearTimeout(c),e.signal?.removeEventListener(`abort`,u),ut?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{ft(e,t)}catch(e){f({ok:!1,reason:`signal-refused`,stdout:i,stderr:a,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)})}},m=t=>{l=t,s&&clearTimeout(s),e.signal?.removeEventListener(`abort`,u);let n=r.pid;n!==void 0&&(c=setTimeout(()=>p(n,`SIGKILL`),250),p(n,`SIGTERM`))};r.stdout?.on(`data`,e=>{i+=e.toString(`utf8`)}),r.stderr?.on(`data`,e=>{a+=e.toString(`utf8`)}),r.on(`error`,t=>{f({ok:!1,reason:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:null,error:rt(t,e.cwd)})}),r.on(`close`,(e,t)=>{if(l!==null){f({ok:!1,reason:l,stdout:i,stderr:a,exitCode:e,signal:t});return}if(e===0){f({ok:!0,stdout:i,stderr:a,exitCode:e});return}f({ok:!1,reason:t?`signal`:`non-zero`,stdout:i,stderr:a,exitCode:e,signal:t})}),e.timeoutMs&&e.timeoutMs>0&&(s=setTimeout(()=>m(`timeout`),e.timeoutMs)),e.signal?.addEventListener(`abort`,u,{once:!0}),e.stdinInput!==void 0&&r.stdin?r.stdin.end(e.stdinInput):r.stdin&&r.stdin.end()})}function D(e){let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();ut?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=se(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ut?.onEnd(e.category,Date.now()-n);let i=typeof t.stdout==`string`?t.stdout:``,a=typeof t.stderr==`string`?t.stderr:``;if(t.error)return{ok:!1,reason:t.error.code===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:t.signal??null,error:rt(t.error,e.cwd)};if(t.status===0)return{ok:!0,stdout:i,stderr:a,exitCode:t.status};let o=e.timeoutMs!==void 0&&e.timeoutMs>0;return{ok:!1,reason:t.signal?o&&t.signal===`SIGTERM`?`timeout`:`signal`:`non-zero`,stdout:i,stderr:a,exitCode:t.status,signal:t.signal??null}}catch(t){return ut?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(t,e.cwd)}}}function mt(e){let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();ut?.onStart(e.category);let r=ht(e);return ut?.onEnd(e.category,Date.now()-n),r}function ht(e){let t;try{t=oe(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(t,e.cwd)}}return t.once(`error`,()=>{}),t.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${e.bin}): no pid (binary not found or unexecutable)`}:(t.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}function gt(e,t,n){let r=_t(e);p.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??p.statSync(r,{throwIfNoEntry:!1})?.mode;try{p.writeFileSync(i,t,a===void 0?{}:{mode:a}),p.renameSync(i,r)}catch(e){throw p.rmSync(i,{force:!0}),e}}function _t(e){let t=e;for(let e=0;e<O;e++){let e;try{e=p.lstatSync(t)}catch(e){if(e.code===`ENOENT`)return t;throw e}if(!e.isSymbolicLink())return t;t=s.resolve(p.realpathSync(s.dirname(t)),p.readlinkSync(t))}throw Error(`${e}: more than ${O} symbolic links`)}const O=40;function vt(e,t){let n=e[t];return n&&n.length>0?n:void 0}function yt(e=process.env){let t=vt(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function bt(){let e=vt(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function xt(){return yt()}function St(){return process.env.CC_CANDYBAR_SOCKET||Ct()}function Ct(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function wt(e){p.mkdirSync(e,{recursive:!0,mode:448});let t=p.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=C.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function Tt(e){wt(s.dirname(e));for(let t of[e,Et(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Et(e){return`${e}.lease`}function Dt(){return Et(St())}function Ot(){return s.join(yt(),`session-state.json`)}function kt(){return s.join(yt(),`settings-history.json`)}function At(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function jt(){return s.join(yt(),`spawn.lock`)}function Mt(){return s.join(yt(),`spawn.cooldown`)}function Nt(){return s.join(yt(),`spawn.backoff`)}function Pt(){return s.join(yt(),`diagnostics`)}function Ft(e=process.env){return s.join(yt(e),`daemon.log`)}const It=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Lt(e){return Object.fromEntries(It.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const Rt=[`native`,`node`,`frames`];function zt(e,t){return{kind:e,bundle:t,source:null}}const Bt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function Vt(e){let t=Yt(e.termCols),n=Yt(e.termRows),r=Xt(e.ssh),i=qt(e.tmux),a=Kt(e.configEnv),o=Kt(e.claudeConfigDir),s=k(e.terminalEnv),c=nn(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function Ht(e,t){return Bt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Ut(e){return e.length===0?null:`Client hints refused: ${e.map(({hint:e,sent:t})=>`${e}=${JSON.stringify(t)}`).join(`, `)} — is the statusline client older than the daemon? Reinstall it (\`cc-candybar install\`, or \`just install-rust\` in a checkout).`}const Wt={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Gt(e){let t=Object.keys(Wt).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Wt[t](n.join(`, `))]});return t.length===0?null:t.join(`
2
+ import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i,pathToFileURL as a}from"node:url";import{json as o}from"node:stream/consumers";import s,{basename as c,dirname as l,isAbsolute as u,join as d,sep as f}from"node:path";import p,{closeSync as m,constants as h,existsSync as g,fstatSync as _,openSync as v,readSync as y,realpathSync as b,statSync as ee,watch as x}from"node:fs";import S,{createHash as te,createHmac as ne,randomBytes as re,randomUUID as ie,timingSafeEqual as ae}from"node:crypto";import C,{homedir as w}from"node:os";import{spawn as oe,spawnSync as se}from"node:child_process";import{inspect as T,parseArgs as ce,types as le}from"node:util";import ue from"node:net";import de from"node:v8";import{open as fe,readFile as pe,readdir as me,stat as he}from"node:fs/promises";import{clearInterval as ge,setImmediate as _e,setInterval as ve}from"node:timers";import{get as ye}from"node:https";import{setTimeout as be}from"node:timers/promises";import{WriteStream as xe}from"node:tty";import{createInterface as Se}from"node:readline";var Ce=Object.create,we=Object.defineProperty,Te=Object.getOwnPropertyDescriptor,Ee=Object.getOwnPropertyNames,De=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty,ke=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ae=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ee(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Oe.call(e,s)&&s!==n&&we(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Te(t,s))||r.enumerable});return e},je=(e,t,n)=>(n=e==null?{}:Ce(De(e)),Ae(t||!e||!e.__esModule?we(n,`default`,{value:e,enumerable:!0}):n,e));function E(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const Me=(e,t)=>E(t),Ne=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Pe(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Fe(e){return Ne.test(e)?e:Pe(e)}function Ie(e){return`${e.dir===void 0?``:`cd ${Fe(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Fe(t)} `).join(``)}${[e.program,...e.args].map(Fe).join(` `)}`}const Le=`cc-extra`;function Re(e){return s.join(s.dirname(e),Le,`src`,`bun-attach.js`)}function ze(e){return s.join(s.dirname(e),`bun-graph.js`)}const Be=`attach-preload.cjs`;function Ve(e){return s.join(s.dirname(e),Be)}function He(e,t){return Ie({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Ue=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function We(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function Ge(e,t,n=Ue){return p.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=p.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?Ge(e,r):[[s.relative(e,r).split(s.sep).join(`/`),We(r,i)]]})}function Ke(e){let t=S.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function qe(e){return Ke(Ge(e,e))}const Je=[`Cargo.toml`,`Cargo.lock`,`src`];function Ye(e){return Ke(Ge(e,e,e=>Je.includes(e)))}const Xe=e=>e.slice(0,7),Ze=`1.159.0`;function Qe(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function $e(){let e=et();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Ze,digest:e}}function et(){return`ecd32a680979d751323e860dea79678ad23e0c19c188d0d1468d70bba7a630d4`}function tt(e){let t=JSON.parse(p.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function nt(e,t){try{let n=Qe(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=qe(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:tt(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function rt(e,t){return le.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const it={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},at=new Map;function ot(e){let t=it[e];if(t===void 0)return{allowed:!0};let n=at.get(e);if(n===void 0)return{allowed:!0};let r=Date.now()-n;return r>=t?{allowed:!0}:{allowed:!1,minIntervalMs:t,sinceLastMs:r}}function st(e){at.set(e,Date.now())}function ct(e){return e.env??process.env}function lt(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${n}ms ago`}}let ut=null;function dt(e){ut=e}function ft(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function pt(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();return ut?.onStart(e.category),new Promise(t=>{let r;try{r=oe(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ut?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(r,e.cwd)});return}let i=``,a=``,o=!1,s=null,c=null,l=null,u=()=>m(`aborted`),d=t=>{o||(o=!0,s&&clearTimeout(s),c&&clearTimeout(c),e.signal?.removeEventListener(`abort`,u),ut?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{ft(e,t)}catch(e){f({ok:!1,reason:`signal-refused`,stdout:i,stderr:a,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)})}},m=t=>{l=t,s&&clearTimeout(s),e.signal?.removeEventListener(`abort`,u);let n=r.pid;n!==void 0&&(c=setTimeout(()=>p(n,`SIGKILL`),250),p(n,`SIGTERM`))};r.stdout?.on(`data`,e=>{i+=e.toString(`utf8`)}),r.stderr?.on(`data`,e=>{a+=e.toString(`utf8`)}),r.on(`error`,t=>{f({ok:!1,reason:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:null,error:rt(t,e.cwd)})}),r.on(`close`,(e,t)=>{if(l!==null){f({ok:!1,reason:l,stdout:i,stderr:a,exitCode:e,signal:t});return}if(e===0){f({ok:!0,stdout:i,stderr:a,exitCode:e});return}f({ok:!1,reason:t?`signal`:`non-zero`,stdout:i,stderr:a,exitCode:e,signal:t})}),e.timeoutMs&&e.timeoutMs>0&&(s=setTimeout(()=>m(`timeout`),e.timeoutMs)),e.signal?.addEventListener(`abort`,u,{once:!0}),e.stdinInput!==void 0&&r.stdin?r.stdin.end(e.stdinInput):r.stdin&&r.stdin.end()})}function D(e){let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();ut?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=se(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ut?.onEnd(e.category,Date.now()-n);let i=typeof t.stdout==`string`?t.stdout:``,a=typeof t.stderr==`string`?t.stderr:``;if(t.error)return{ok:!1,reason:t.error.code===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:t.signal??null,error:rt(t.error,e.cwd)};if(t.status===0)return{ok:!0,stdout:i,stderr:a,exitCode:t.status};let o=e.timeoutMs!==void 0&&e.timeoutMs>0;return{ok:!1,reason:t.signal?o&&t.signal===`SIGTERM`?`timeout`:`signal`:`non-zero`,stdout:i,stderr:a,exitCode:t.status,signal:t.signal??null}}catch(t){return ut?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(t,e.cwd)}}}function mt(e){let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();ut?.onStart(e.category);let r=ht(e);return ut?.onEnd(e.category,Date.now()-n),r}function ht(e){let t;try{t=oe(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(t,e.cwd)}}return t.once(`error`,()=>{}),t.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${e.bin}): no pid (binary not found or unexecutable)`}:(t.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}function gt(e,t,n){let r=_t(e);p.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??p.statSync(r,{throwIfNoEntry:!1})?.mode;try{p.writeFileSync(i,t,a===void 0?{}:{mode:a}),p.renameSync(i,r)}catch(e){throw p.rmSync(i,{force:!0}),e}}function _t(e){let t=e;for(let e=0;e<O;e++){let e;try{e=p.lstatSync(t)}catch(e){if(e.code===`ENOENT`)return t;throw e}if(!e.isSymbolicLink())return t;t=s.resolve(p.realpathSync(s.dirname(t)),p.readlinkSync(t))}throw Error(`${e}: more than ${O} symbolic links`)}const O=40;function vt(e,t){let n=e[t];return n&&n.length>0?n:void 0}function yt(e=process.env){let t=vt(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function bt(){let e=vt(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function xt(){return yt()}function St(){return process.env.CC_CANDYBAR_SOCKET||Ct()}function Ct(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function wt(e){p.mkdirSync(e,{recursive:!0,mode:448});let t=p.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=C.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function Tt(e){wt(s.dirname(e));for(let t of[e,Et(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Et(e){return`${e}.lease`}function Dt(){return Et(St())}function Ot(){return s.join(yt(),`session-state.json`)}function kt(){return s.join(yt(),`settings-history.json`)}function At(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function jt(){return s.join(yt(),`spawn.lock`)}function Mt(){return s.join(yt(),`spawn.cooldown`)}function Nt(){return s.join(yt(),`spawn.backoff`)}function Pt(){return s.join(yt(),`diagnostics`)}function Ft(e=process.env){return s.join(yt(e),`daemon.log`)}const It=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Lt(e){return Object.fromEntries(It.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const Rt=[`native`,`node`,`frames`];function zt(e,t){return{kind:e,bundle:t,source:null}}const Bt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function Vt(e){let t=Yt(e.termCols),n=Yt(e.termRows),r=Xt(e.ssh),i=qt(e.tmux),a=Kt(e.configEnv),o=Kt(e.claudeConfigDir),s=k(e.terminalEnv),c=nn(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function Ht(e,t){return Bt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Ut(e){return e.length===0?null:`Client hints refused: ${e.map(({hint:e,sent:t})=>`${e}=${JSON.stringify(t)}`).join(`, `)} — is the statusline client older than the daemon? Reinstall it (\`cc-candybar install\`, or \`just install-rust\` in a checkout).`}const Wt={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Gt(e){let t=Object.keys(Wt).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Wt[t](n.join(`, `))]});return t.length===0?null:t.join(`
3
3
  `)}function k(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=It.filter(e=>t[e]!==void 0);return n.every(e=>typeof t[e]==`string`&&t[e]!==``)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function Kt(e){return typeof e==`string`&&s.isAbsolute(e)?e:void 0}function qt(e){if(e===null)return null;if(typeof e!=`object`)return;let{socket:t,pane:n,truecolor:r}=e;if(!(typeof t!=`string`||t===``)&&!(typeof n!=`string`||n===``)&&!(r!==null&&(typeof r!=`string`||r===``)))return{socket:t,pane:n,truecolor:r}}const Jt=1e4;function Yt(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>Jt?Jt:t}function Xt(e){return typeof e==`boolean`?e:void 0}function Zt(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var A=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Qt(e){return $t(JSON.stringify(e))}function $t(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function en(e,t){let n=Buffer.alloc(0);return function(r){for(n=Buffer.concat([n,r]);n.length>=4;){let r=n.readUInt32BE(0);if(r>16777216){t(new A(`frame too large: ${r}`));return}if(n.length<4+r)return;let i=n.subarray(4,4+r);n=n.subarray(4+r);try{e(JSON.parse(i.toString(`utf8`)))}catch(e){let n=new A(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function tn(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.removeAllListeners();try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n-Date.now()),c=en(e=>o(()=>r(e)),e=>o(()=>i(e)));e.on(`data`,c),e.on(`error`,e=>o(()=>i(e))),e.on(`close`,()=>o(()=>i(Error(`socket closed before response`)))),e.write(Qt(t))})}function nn(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Kt(n);return Rt.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function rn(e,t,n){let r=null;try{r=await ln(St(),t.connectMs);let i=Date.now()+t.budgetMs,a=e(i),o=await tn(r,{v:3,...a},i);return sn(a.kind,o,n)}catch(e){return cn(e)}finally{r&&r.destroy()}}function an(e,t){return typeof e==`string`?e:t}function on(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function sn(e,t,n){let r=t;if(r.ok===!0){let r=n(t);return r===void 0?{kind:`permanent`,cause:`malformed_response`,message:`ok response without payload for "${e}" request`}:{kind:`ok`,value:r}}let i=an(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:on(r.daemonV)};case`TIMEOUT`:return{kind:`transient`,cause:`timeout`,message:i};case`BAD_REQUEST`:return{kind:`permanent`,cause:`bad_request`,message:i};case`RENDER_FAILED`:return{kind:`permanent`,cause:`render_failed`,message:i};case`SWITCHED_OFF`:return{kind:`permanent`,cause:`switched_off`,message:i};default:return{kind:`permanent`,cause:`malformed_response`,message:`unknown error code: ${String(r.code)}`}}}function cn(e){if(e instanceof A||e instanceof SyntaxError)return{kind:`permanent`,cause:`malformed_response`,message:e instanceof Error?e.message:String(e)};let t=e instanceof Error?e.message:String(e);return t===`CONNECT_TIMEOUT`||t===`TIMEOUT`?{kind:`transient`,cause:`timeout`,message:t}:t.includes(`ECONNREFUSED`)||t.includes(`ENOENT`)||t.includes(`ENOTSOCK`)?{kind:`transient`,cause:`unreachable`,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function ln(e,t){return new Promise((n,r)=>{let i=ue.createConnection({path:e}),a=setTimeout(()=>{i.destroy(),r(Error(`CONNECT_TIMEOUT`))},t);i.once(`connect`,()=>{clearTimeout(a),n(i)}),i.once(`error`,e=>{clearTimeout(a),r(e)})})}function un(e){if(e.kind===`transient`)return`daemon unavailable (${e.cause}: ${e.message})\nHint: daemon may not be running. Run \`cc-candybar\` once to spawn it.`;switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`daemon protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:case`render_failed`:case`switched_off`:case`malformed_response`:return`daemon error (${e.cause}): ${e.message}`}}const dn={connectMs:50,budgetMs:150},fn={connectMs:50,budgetMs:200};function pn(e){let t=e.output;return typeof t==`string`?t:void 0}function mn(e){return sn(`render`,e,pn)}function hn(e,t,n,r){return rn(i=>({kind:`render`,hookData:e,args:t,cwd:n,deadline:i,...r}),dn,pn)}function gn(e,t){return rn(()=>({kind:`pane-session`,socket:e,pane:t}),fn,e=>`paneSession`in e?e.paneSession:void 0)}function _n(e,t){return rn(()=>({kind:`click`,verb:e,value:t,clientVersion:Ze}),fn,pn)}let vn=null;function yn(){if(vn!==null){try{p.closeSync(vn.fd)}catch{}vn=null}}async function bn(e){let t=await p.promises.stat(e).catch(()=>null);if(vn!==null&&vn.path===e&&t!==null&&vn.id===xn(t))return{held:vn,size:t.size};yn(),await p.promises.mkdir(s.dirname(e),{recursive:!0});let n=await new Promise((t,n)=>p.open(e,`a`,(e,r)=>e===null?t(r):n(e))),r=await new Promise((e,t)=>p.fstat(n,(n,r)=>n===null?e(r):t(n)));return vn={path:e,fd:n,id:xn(r)},{held:vn,size:r.size}}function xn(e){return`${e.dev}:${e.ino}`}function Sn(e,t){return new Promise((n,r)=>p.write(e,t,(e,t)=>e===null?n(t):r(e)))}async function Cn(e){for(let t=2;t>=1;t--)await p.promises.rename(`${e}.${t}`,`${e}.${t+1}`).catch(()=>{});await p.promises.rename(e,`${e}.1`).catch(()=>{})}let wn=[],Tn=0,En=0,Dn=0,j=null,On=!1;const kn=[];let An=!1,jn=!1;function M(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;if(jn||(jn=!0,process.on(`exit`,()=>{An=!0,Rn(!0,In)})),wn.push(n),Tn+=Buffer.byteLength(n),Tn>4194304){let e=0;for(;Tn>4194304/2&&e<wn.length-1;){let t=Buffer.byteLength(wn[e]);Tn-=t,Dn+=t,e++}wn.splice(0,e),En+=e}An?Rn(!0,In):On||Nn()}function Mn(){Rn(!1,Ln)}async function Nn(){On=!0;try{for(;wn.length>0;){let e=Pn();j={bytes:Buffer.from(e),state:{kind:`taken`}};try{await Fn(Ft(),j)}catch(t){yn(),j.state.kind!==`landed`&&Bn(e,t)}finally{j=null}}}finally{On=!1;for(let e of kn.splice(0))e()}}function Pn(){let e=(En===0?``:`${new Date().toISOString()} [warn] log: ${En} earlier line(s) dropped (${Dn} bytes): more than 4194304 bytes were waiting for the disk\n`)+wn.join(``);return wn=[],Tn=0,En=0,Dn=0,e}async function Fn(e,t){let{held:n,size:r}=await bn(e);if(t.state.kind===`landed`)return;let{bytes:i}=t,a=r+i.length;t.state={kind:`issued`,fd:n.fd,endsAt:a};for(let e=0;e<i.length;){let t=await Sn(n.fd,i.subarray(e));if(t===0)throw Error(`the disk took 0 bytes of a write`);e+=t}if(t.state={kind:`landed`},a>=5242880){yn();let e=await p.promises.stat(n.path).catch(()=>null);e!==null&&xn(e)===n.id&&await Cn(n.path)}}const In=1e3,Ln=2e3;function Rn(e,t){let n=j,r=Buffer.alloc(0);n!==null&&n.state.kind===`taken`&&(r=n.bytes,n.state={kind:`landed`});let i=null;if(n!==null&&n.state.kind===`issued`){let{fd:a,endsAt:o}=n.state;try{let s=zn(a,o,t);s<o&&e?(r=n.bytes.subarray(Math.max(0,s-(o-n.bytes.length))),n.state={kind:`landed`}):s<o&&(i={fd:a,endsAt:o})}catch(t){e&&(r=n.bytes,n.state={kind:`landed`}),Bn(n.bytes.toString(),t)}}if(r.length===0&&wn.length===0)return;let a=Buffer.concat([r,Buffer.from(Pn())]);try{let e=Ft();p.mkdirSync(s.dirname(e),{recursive:!0}),p.appendFileSync(e,a),i!==null&&n!==null&&xn(p.fstatSync(i.fd))===xn(p.statSync(e))&&(n.state={kind:`issued`,fd:i.fd,endsAt:i.endsAt+a.length})}catch(e){Bn(a.toString(),e)}}function zn(e,t,n){let r=performance.now()+n,i=new Int32Array(new SharedArrayBuffer(4));for(;;){let{size:n}=p.fstatSync(e);if(n>=t||performance.now()>=r)return n;Atomics.wait(i,0,0,1)}}function Bn(e,t){try{process.stderr.write(`${e}cc-candybar: daemon.log unwritable: ${t.message}\n`)}catch{}}const Vn=5e3;function Hn(e){let t=[];for(let n of e){let e=n.read();if(e.kind===`text`)return`# memory report from: ${n.name}\n${e.text}`;t.push(`# ${n.name}: unavailable — ${e.reason}`)}return[`# memory report: no probe answered`,...t.length>0?t:[`# no probe is known for this platform`]].join(`
4
4
  `)}const Un=`/usr/bin/footprint`;function Wn(e,t){return e===`darwin`?[Jn(Un,[`-p`,String(t)]),Jn(`/usr/bin/vmmap`,[`--summary`,String(t)])]:e===`linux`?[Yn(`/proc/self/smaps_rollup`),Yn(`/proc/self/status`)]:[]}function Gn(e,t){return e===`darwin`?Kn(t,e=>pt({bin:Un,args:e,timeoutMs:Vn,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function Kn(e,t){return async n=>{let r=await t([`-p`,String(e),`--noCategories`,`-f`,`bytes`]);if(!r.ok)return{kind:`stand-in`,bytes:n,unread:`footprint ${r.reason}${r.error===void 0?``:`: ${r.error}`}${Xn(r.stderr)}`};let i=qn(r.stdout);return i===null?{kind:`stand-in`,bytes:n,unread:`footprint printed no phys_footprint line`}:{kind:`charged`,measure:`phys_footprint`,bytes:i}}}function qn(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function Jn(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=D({bin:e,args:[...t],timeoutMs:Vn,category:`limits.memory-report`});return n.ok?n.stdout.trim().length>0?{kind:`text`,text:n.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${n.reason}${n.error===void 0?``:`: ${n.error}`}${Xn(n.stderr)}`}}}}function Yn(e){return{name:e,read:()=>{try{let t=p.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}function Xn(e){let t=e.split(`
5
5
  `).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const Zn=`CC_CANDYBAR_RSS_LIMIT_MB`;function Qn(e){let t=e[Zn];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${Zn} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function $n(e){return Qn(e)*2}const er=1024*1024,tr=e=>Math.round(e/er);function nr(e){return Qn(e)*er}const rr={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function ir(e,t){return e>t}function ar(e,t){if(e.kind===`charged`)return e;let n=t.kind===`unmeasured`?0:t.charge.kind===`charged`?t.rss-t.charge.bytes:t.charge.gap;return{...e,bytes:e.bytes-n,gap:n}}const or=.75;function sr(e,t){return e>t*or}function cr(e,t,n){let{prefix:r,suffix:i}=rr[t];return s.join(e,`${r}${n}${i}`)}function lr(e){for(let t of Object.keys(rr)){let{prefix:n,suffix:r}=rr[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function ur(e){let t=e.limitBytes??1024*er,n=e.snapshotsKeep??3,r=!1,i={kind:`unmeasured`},a=null;function o(){return a??=s().finally(()=>{a=null}),a}async function s(){if(r)return!0;let{rss:a,heapTotal:o}=e.memoryBytes(),s=ar(await e.memoryCharge(a),i),c={kind:`measured`,charge:s,rss:a,heapTotal:o};if(i=c,e.log(`info`,`memory ${pr(c,t)}`),s.bytes<=t)return!1;r=!0,e.log(`warn`,`${dr(s)} > limit ${tr(t)} MB (rss ${tr(a)} MB, v8 heap ${tr(o)} MB); recording memory then shutting down`);let l=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return mr(e.log,`memory report`,()=>{let t=cr(e.snapshotDir,`memoryReport`,l);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),mr(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=cr(e.snapshotDir,`heapSnapshot`,l);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),mr(e.log,`artifact rotation`,()=>{for(let{artifacts:t}of hr(e.listArtifacts()).slice(n))for(let n of Object.values(t))mr(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0}function c(){return i.kind===`measured`&&sr(i.charge.bytes,t)?`${dr(i.charge)} approaching limit ${tr(t)} MB (v8 heap ${tr(i.heapTotal)} MB)`:null}function l(){let n;try{n={kind:`ok`,value:hr(e.listArtifacts())}}catch(e){n={kind:`failed`,reason:e.message}}return{pid:e.pid,memory:i,limit:t,postMortems:n}}function u(t=6e4){let n,r=!0,i=async()=>{try{if(await o())return}catch(t){e.log(`warn`,`memory check failed: ${t.message}`)}r&&(n=setTimeout(()=>void i(),t),n.unref())};return i(),{disarm:()=>{r=!1,clearTimeout(n)}}}return{check:o,describeNextRestart:c,serving:l,arm:u}}function dr(e){return e.kind===`charged`?`${e.measure} ${tr(e.bytes)} MB`:`rss ${tr(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${tr(e.gap)} MB gap`} (standing in: ${e.unread})`}function fr(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function pr({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${tr(e.gap)}MB`:``;return`measure=${fr(e)} charge=${tr(e.bytes)}MB rss=${tr(t)}MB heap=${tr(n)}MB limit=${tr(r)}MB${i}`}function mr(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function hr(e){let t=new Map;for(let n of e){let e=s.basename(n),r=lr(e);if(r===null)continue;let{prefix:i,suffix:a}=rr[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(rr);return[...t].sort(([e],[t])=>ir(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function gr(e,t,n={}){let r=xt();return{now:()=>Date.now(),pid:process.pid,snapshotDir:r,log:M,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},memoryCharge:Gn(process.platform,process.pid),captureMemoryReport:()=>Hn(Wn(process.platform,process.pid)),writeMemoryReport:(e,t)=>p.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>de.writeHeapSnapshot(e),writeLogNow:Mn,listArtifacts:()=>{let e;try{e=p.readdirSync(r)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>lr(e)!==null).map(e=>s.join(r,e))},removeFile:e=>p.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function _r(e={}){if(Nr()!==null)return;let n=e.spawn??Fr,r=Ar();if(r.kind===`contended`){let e=yr();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),vr(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),vr(n);return}try{vr(n)}finally{Mr()}}function vr(e){Er()&&br(e)}function yr(){try{let e=p.statSync(jt());return Date.now()-e.mtimeMs}catch{return null}}function br(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
@@ -57,26 +57,26 @@ import{createRequire as e}from"node:module";import t from"node:process";import{U
57
57
  `)}function Cb(e,t,n,r){if(t===null)return e;let i=Eb(r),a=Tb(t,i),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[Ob(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
58
58
  `);return e?`${l}\n${e}`:l}function wb(e,t){return Tb(e,Eb(t)).join(`
59
59
  `)}function Tb(e,t){return e.channels.flatMap(e=>Db(e,t))}function Eb(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,colorCompatibility:e.colorCompatibility}}function Db(e,t){let n=new V({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=Ws(Math.max(2,t.width-1)),i=(e,t)=>new W(`${e} `,{style:t,end:``,overflow:`ignore`});return e.lines.flatMap((a,o)=>pb([i(o===0?e.severity.glyph:` `,n.withLink(a[0].link)),...a.flatMap(e=>{let t=n.withLink(e.link);return e.text.split(` `).flatMap(e=>Ys(e,r)).map(e=>i(e,t))})],t).split(`
60
- `))}function Ob(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:o,failedConfigFile:s}=t,c=new V({bgcolor:i.bg,color:i.fg}),l=(e,t)=>new W(e,{style:t,end:``,overflow:`ignore`}),u=n>0?[l(`${n} more rows · `,c),o.kind===`file`?l(`open full text`,c.withLink(a(o.path).href)):l(`full text unavailable: ${Ny(o.reason)}`,c)]:[],d=s===null?[]:[l(`${u.length>0?` · `:``}open `,c),l(Ny(s),c.withLink(a(s).href))],f=[l(`↳ `,c),...u,...d.slice(0,-1)],p=f.reduce((e,t)=>e+t.cellLength,0),m=d.slice(-1).map(e=>e.truncate(Math.max(1,r.width-p),{mode:`middle`})),h=W.fromFragments([...f,...m]).truncate(r.width);return h.overflow=`ignore`,pb([h],r)}var q=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};const kb=new Map;function Ab(e){let t=Mb(e);if(t===null)throw Error(`Palette "${e}" did not resolve in the theme registry — allowed names and the registry are inconsistent`);return t}function jb(e,t){return e===`bar`?t:Ab(e)}function Mb(e){let t=kb.get(e);if(t!==void 0)return t;let n=au(e);return n===null?null:(kb.set(e,n),n)}function Nb(e,t){return Pb(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>_u(e,t))}const Pb=uh();function Fb(e){let t=Mb(e);return t===null?null:{kind:`decided`,name:e,value:t}}function Ib(e,t,n){let r=Fb(e);return r===null?(n(Qg(t,`palette`,`"${e}" names no installed theme${Fg(e)}`)),Rb()):r}function Lb(e,t,n){return Gg(e,t,n,Rb(),Fb)}function Rb(){return{kind:`decided`,name:Ig,value:Ab(Ig)}}const zb=/^[A-Za-z_][A-Za-z0-9_]*$/;function Bb(e){return`#${e+1}`}const Vb={rows:{}};function Hb(e){return`rows`in e}function Ub(e){return Object.fromEntries(e.map((e,t)=>[Bb(t),e]))}function Wb(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:Ub(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:Ub([n])}}function Gb(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function Kb(e){return Hb(e)?Gb(e):e}function*qb(e,t){if(!Hb(e)){yield*k_(e,t);return}yield[Gb(e),t];for(let[n,r]of Object.entries(e.rows))yield*k_(r,`${t}.rows.${n}`)}function Jb(e,t){return Hb(e)?{...t,...e,rows:{...t.rows,...e.rows}}:Wb(e)}function Yb(e){if(!Hb(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const Xb=`default`,Zb={};function Qb(e){return[...new Set([Xb,...Object.keys(e)])]}function $b(e,t,n){return Hg(void 0,e,t,Xb,n)}function ex(e,t){let n={[Xb]:Zb,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${Xb}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function tx(e,t){let n=ex(e.presets,t).root??Vb;return{node:Gb(Jb(n,e.root)),path:Yb(n)?`presets.${t}.root`:`root`}}function nx(e,t){return{...e.globals,...ex(e.presets,t).globals}}const rx=new Map;function ix(e,t,n){rx.set(e,{permanent:!0,resolve:t,paletteOf:n})}ix(`themes`,()=>Rg(),e=>Ab(e));const ax=`placementThemes`;ix(ax,zg,(e,t)=>jb(e,t.palette));for(let{name:e,members:t}of gy)ix(e,()=>t);function ox(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>Nb(n.basePalette,e.styles[t])}],[`presets`,{members:Qb(e.presets)}]])}function sx(e){return[...new Set([...rx.keys(),...e.keys()])]}function cx(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=rx.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf};throw Error(ux(e,t))}const lx=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function ux(e,t){let n=lx.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${sx(t).join(`, `)})`}const dx=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`slash`,`run`,`do`];function fx(e){return JSON.stringify([e.run,Object.entries(e.env),e.cwd,e.refreshes])}function*px(e){if(`copy`in e&&(yield[`copy`,e.copy]),`open`in e&&(yield[`open`,e.open]),`preset`in e&&e.preset===`delete`&&(yield[`name`,e.name]),`run`in e){for(let[t,n]of e.run.entries())yield[`run.${t}`,n];for(let[t,n]of Object.entries(e.env))yield[`env.${t}`,n]}}function mx(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}const hx=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*gx(e){let t=e.indexOf(`{{`);for(;t!==-1;){let n=``,r=t+2;for(;r<e.length&&!e.startsWith(`}}`,r);){if(e.startsWith(`/*`,r)){let t=e.indexOf(`*/`,r+2);r=t===-1?e.length:t+2;continue}let t=r,i=e[r];if(r+=1,i===`"`||i===`'`||i==="`"){for(;r<e.length&&e[r]!==i;)r+=e[r]===`\\`&&i!=="`"?2:1;r+=1}n+=e.slice(t,r)}if(r>=e.length)return;yield n,t=e.indexOf(`{{`,r+2)}}const _x=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,vx=RegExp(`^(?:(\\$)(?:\\.(${_x}))?|\\.(${_x})?)(?=[\\s)]|$)`);function yx(e,t,n){let r=vx.exec(e.trimStart());if(r===null)return null;let[i,a]=r[1]===void 0?[t,r[3]]:[n,r[2]];return i===null?null:a===void 0?i:`${i}${a}.`}const bx=/^(\w+)\b\s*([\s\S]*)$/;function*xx(e,t){let n=[t];for(let r of gx(e)){let e=r.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=bx.exec(e)??[],o=n[n.length-1],s=n.length>1?n[n.length-2]:o;if(i===`end`){n.length>1&&n.pop();continue}if(i===`else`){yield{code:e,dot:s};let r=/^with\b([\s\S]*)$/.exec(a);n[n.length-1]=r===null?s:yx(r[1],s,t);continue}yield{code:e,dot:o},i===`if`&&n.push(o),i===`with`&&n.push(yx(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const Sx=/(?<![.$])\btemplate\s+$/;function*Cx(e,t,n){let r=0;for(let i of[...e.matchAll(hx)]){let a=i.index+i[0].length;Sx.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:yx(e.slice(a),t,n)}),r=a}}function*wx(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...xx(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...Cx(s,c,i)]){let i=Object.hasOwn(t,e.name)?t[e.name]:void 0,a=`${e.name}\0${e.at??`\0`}`;i===void 0||o.has(e.name)||n.has(a)||(n.add(a),yield*r(i,e.at,e.name,new Set([...o,e.name])))}}}yield*r(e,``,null,new Set)}const Tx=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${_x})`,`g`);function*Ex({code:e,dot:t,root:n}){let r=e.replace(hx,``);for(let e of[...r.matchAll(Tx)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function Dx(e,t){let n=new Map;for(let r of wx(e,t))for(let e of Ex(r))n.has(e)||n.set(e,r.via);return n}const Ox=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,kx={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*Ax(e){let t=0,n=0,r=0,i=`action`;for(let a of[...e.matchAll(hx)]){let o=e.slice(t,a.index),s=Ox.exec(o);if(s!==null)n=kx[s[1]],r=0,i=s[1]===`action`?`action`:`options`;else for(let e of o)e===`(`&&r++,e===`)`&&r--,(r<0||e===`|`&&r===0)&&(n=0);n>0&&r===0&&(yield{name:a[0].slice(1,-1),site:i},n--),t=a.index+a[0].length}}function jx(e,t){let n=new Map;for(let{code:r,via:i}of wx(e,t))for(let{name:e,site:t}of Ax(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}const Mx=/(?<![\w.$])(?:action|picker|menu|carousel|swatches|swatch|themePreview)\s+(?=[^\s"`)|}])/;function Nx(e,t){for(let{code:n}of wx(e,t))if(Mx.test(n.replace(hx,`""`)))return!0;return!1}const Px=/(?<![\w.$])[A-Za-z_]\w*/g;function Fx(e,t){let n=new Set;for(let{code:r}of wx(e,t))for(let[e]of r.replace(hx,``).matchAll(Px))n.add(e);return n}function Ix(e,t){return new Set([...Lx(e,t)].filter(e=>Object.hasOwn(t,e)))}function Lx(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of wx(e,t))for(let{name:e}of Cx(r,i,a))n.add(e);return n}function*Rx(e){for(let[t,n]of Object.entries(e.variables))yield[t,n,[`variables`,t]];for(let[t,n]of Object.entries(e.segments))for(let[e,r]of Object.entries(n.vars??{}))yield[`${t}.${e}`,r,[`segments`,t,`vars`,e]]}function*zx(e){for(let[t,n]of Rx(e))yield[t,n]}function Bx(e,t){let n=e.split(`.`);for(let e=n.length;e>0;e--){let r=n.slice(0,e).join(`.`);if(t.has(r))return[r]}let r=`${e}.`;return[...t].filter(e=>e.startsWith(r))}function Vx(e,t){return Bx(e,t.names).some(n=>!e.startsWith(`${n}.`)||t.documents.has(n))}function Hx(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),Ux(r)&&n.add(e)};for(let[t,n]of zx(e))r(t,n);return{names:t,documents:n,helpers:e.helpers}}function Ux(e){return e.kind===`dropped`||e.kind===`source`||(e.kind===`shell`||e.kind===`file`)&&j_(e.parse)===`json`}function Wx(e){let t=s.basename(e),n=s.dirname(e);for(;;){let r=Gx(n);if(r!==null)return{dir:r,name:t,leaf:n===s.dirname(e)};t=s.basename(n),n=s.dirname(n)}}function Gx(e){try{return p.statSync(e).isDirectory()?p.realpathSync(e):null}catch{return null}}var Kx=ke((e=>{function t(e,...t){throw Error(`[MobX] minified error nr: ${e}${t.length?` `+t.map(String).join(`,`):``}. See mobx.js.org/errors`)}function n(e){let t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function r(e){return typeof e==`function`}function i(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function a(e){return typeof e==`object`&&!!e}function o(e){if(!a(e))return!1;let t=Object.getPrototypeOf(e);if(t==null)return!0;let n=p(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===Ht}function s(e){let t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function c(e,t,n){Rt(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function l(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return a(e)&&!0===e[n]}}function u(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function d(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function f(e){return e===null?null:typeof e==`object`?``+e:e}function p(e,t){return zt.hasOwnProperty.call(e,t)}function m(e,t){return!!(e&t)}function h(e,t,n){return n?e|=t:e&=~t,e}function g(e,t=Ut,n=Ut){let r=new Kt(e);return t!==Ut&&(r.onBOL=new Set([t])),n!==Ut&&(r.onBUOL=new Set([n])),r}function _(e,t){return jt(e,t)}function v(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||nt(e)?e:Array.isArray(e)?ln.array(e,{name:n}):o(e)?ln.object(e,void 0,{name:n}):u(e)?ln.map(e,{name:n}):d(e)?ln.set(e,{name:n}):typeof e!=`function`||Ge(e)||$e(e)?e:s(e)?Kn(e):Rn(n,e)}function y(e){return e}function b(e,t){return{t:e,i:t,o:ee,u:x}}function ee(e,t,n,r){var i;return(i=this.i)!=null&&i.bound?this.u(e,t,n,!1)===null?0:1:r===e.h?this.u(e,t,n,!1)===null?0:2:Ge(n.value)?1:(Rt(r,t,te(e,this,t,n,!1)),2)}function x(e,t,n,r){let i=te(e,this,t,n);return e.l(t,i,r)}function S(e,n,r){let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>{var t;return be(s.i?.name??a.toString(),e,(t=s.i?.autoAction)!=null&&t)};return i==`field`?function(e){var t;let n=e;return Ge(n)||(n=c(n)),(t=s.i)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n}:i==`method`?(Ge(n)||(n=c(n)),(l=s.i)!=null&&l.bound&&o(function(){let e=this,t=e[a].bind(e);t.isMobxAction=!0,e[a]=t}),n):void t(43,s.t,String(a),i);var l}function te(e,t,n,r,i=j.safeDescriptors){var a,o,s;let{value:c}=r;return(a=t.i)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:be(t.i?.name??n.toString(),c,(o=t.i?.autoAction)!=null&&o,(s=t.i)!=null&&s.bound?e.v??e.h:void 0),configurable:!i||e.p,enumerable:!1,writable:!i}}function ne(e,t){return{t:e,i:t,o:re,u:ie}}function re(e,t,n,r){var i;return r===e.h?this.u(e,t,n,!1)===null?0:2:(i=this.i)!=null&&i.bound&&(!p(e.h,t)||!$e(e.h[t]))&&this.u(e,t,n,!1)===null?0:$e(n.value)?1:(Rt(r,t,C(e,0,0,n,!1,!1)),2)}function ie(e,t,n,r){let i=C(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function ae(e,t,n){var r;let{name:i,addInitializer:a}=n;return $e(t)||(t=Kn(t)),(r=e.i)!=null&&r.bound&&a(function(){let e=this,t=e[i].bind(e);t.isMobXFlow=!0,e[i]=t}),t}function C(e,t,n,r,i,a=j.safeDescriptors){let{value:o}=r;return $e(o)||(o=Kn(o)),i&&(o=o.bind(e.v??e.h),o.isMobXFlow=!0),{value:o,configurable:!a||e.p,enumerable:!1,writable:!a}}function w(e,t){return{t:e,i:t,o:oe,u:se}}function oe(e,t,n){return this.u(e,t,n,!1)===null?0:1}function se(e,t,n,r){return e.m(t,It({},this.i,{get:n.get,set:n.set}),r)}function T(e,t,n){function r(e){let n=It({},i.i,{get:t,context:e});return n.name||=`ObservableObject.${a.toString()}`,new xn(n)}let i=e,{name:a,addInitializer:o}=n,s;return o(function(){let e=wt(this)[k],n=this,i=e.j.get(a);i instanceof xn&&i.derivation!==t&&e.j.delete(a),(e.O??=new Map).set(a,()=>r(n))}),function(){let e=this[k],n=e.j.get(a);if(n instanceof xn&&n.derivation!==t){let e=s?.get(this);return e||(e=r(this),(s??=new WeakMap).set(this,e)),e.get()}return e._(a)}}function ce(e,t){return{t:e,i:t,o:le,u:ue}}function le(e,t,n){return this.u(e,t,n,!1)===null?0:1}function ue(e,t,n,r){return e.S(t,n.value,this.i?.A??v,r)}function de(e,t,n){function r(e,t){let n=wt(e)[k];return(n.V??=new Map).set(o,()=>new yn(t,i.i?.A??v,`ObservableObject.${o.toString()}`,!1)),n}let i=e,{kind:a,name:o}=n;if(a===`accessor`)return{get(){return(this[k]??r(this,t.get.call(this)))._(o)},set(e){return(this[k]??r(this,e)).M(o,e)},init(e){return r(this,e),e}}}function fe(e){return{t:Xt,i:e,o:pe,u:me}}function pe(e,t,n,r){var i,a,o;if(n.get)return pn.o(e,t,n,r);if(n.set){let i=Ge(n.set)?n.set:be(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!j.safeDescriptors||e.p,set:i})===null?0:2:(Rt(r,t,{configurable:!0,set:i}),2)}if(r!==e.h&&typeof n.value==`function`)return s(n.value)?((o=this.i)!=null&&o.autoBind?qn:Kn).o(e,t,n,r):((a=this.i)!=null&&a.autoBind?Bn:Rn).o(e,t,n,r);let c=!1===this.i?.deep?an:ln;return typeof n.value==`function`&&(i=this.i)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),c.o(e,t,n,r)}function me(e,t,n,r){var i;return n.get?pn.u(e,t,n,r):n.set?e.l(t,{configurable:!j.safeDescriptors||e.p,set:be(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.i)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),(!1===this.i?.deep?an:ln).u(e,t,n,r))}function he(e,t){return It(function(n,r){if(r&&typeof r.kind==`string`)return t(e,n,r)},e)}function ge(e){return e||Qt}function _e(e){return he(e,de)}function ve(e){return!0===e.deep?v:!1===e.deep?y:(t=e.defaultDecorator)&&(n=(r=t.i)?.A)!=null?n:v;var t,n,r}function ye(e){return he(e,T)}function be(e,t,n=!1,r){function i(){return xe(0,n,t,r||this,arguments)}return i.isMobxAction=!0,i.toString=()=>t.toString(),_n&&(vn.value=e,Rt(i,`name`,vn)),i}function xe(e,t,n,r,i){let a=Se(0,t);try{return n.apply(r,i)}catch(e){throw a.N=e,e}finally{Ce(a)}}function Se(e,t){let n=j.trackingDerivation,r=!t||!n;Fe();let i=j.allowStateChanges;r&&Ae();let a={R:r,k:n,C:i,I:j.allowStateReads,P:!1,T:0,B:gn++,D:hn};return hn=a.B,a}function Ce(e){hn!==e.B&&t(30),hn=e.D,e.N!==void 0&&(j.suppressReactionErrors=!0),Ie(),e.R&&je(e.k),j.suppressReactionErrors=!1}function we(e,t){let n=function(e){let t=j.allowStateChanges;return j.allowStateChanges=e,t}(e);try{return t()}finally{(function(e){j.allowStateChanges=e})(n)}}function Te(e){return e instanceof Cn}function Ee(e){switch(e.K){case 0:return!1;case-1:case 2:return!0;case 1:{let t=Ae(),n=e.L,r=n.length;for(let i=0;i<r;i++){let r=n[i];if(Sn(r)){if(j.disableErrorBoundaries)r.get();else try{r.get()}catch{return je(t),!0}if(e.K===2)return je(t),!0}}return E(e),je(t),!1}}}function De(e,t,n){E(e),e.$=Array(e.U===0?100:e.L.length),e.W=0,e.U=++j.runId;let r=j.trackingDerivation,i;if(j.trackingDerivation=e,j.inBatch++,!0===j.disableErrorBoundaries)i=t.call(n);else try{i=t.call(n)}catch(e){i=new Cn(e)}return j.inBatch--,j.trackingDerivation=r,function(e){let t=e.L,n=e.L=e.$,r=0,i=0,a=e.W;for(let e=0;e<a;e++){let t=n[e];t.diffValue===0&&(t.diffValue=1,i!==e&&(n[i]=t),i++),t.K>r&&(r=t.K)}for(n.length=i,e.$=null,a=t.length;a--;){let n=t[a];n.diffValue===0&&Ne(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,Me(t,e))}r!==0&&(e.K=r,e.q())}(e),i}function Oe(e){let t=e.L;e.L=[];let n=t.length;for(;n--;)Ne(t[n],e);e.K=-1}function ke(e){let t=Ae();try{return e()}finally{je(t)}}function Ae(){let e=j.trackingDerivation;return j.trackingDerivation=null,e}function je(e){j.trackingDerivation=e}function E(e){if(e.K===0)return;e.K=0;let t=e.L,n=t.length;for(;n--;)t[n].F=0}function Me(e,t){(e.H??=new Set).add(t),e.F>t.K&&(e.F=t.K)}function Ne(e,t){let n=e.H;n&&(n.delete(t),n.size===0&&Pe(e))}function Pe(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,j.pendingUnobservations.push(e))}function Fe(){j.inBatch++}function Ie(){--j.inBatch===0&&(Be(),!j.isRunningUnobservations&&j.pendingUnobservations.length>0&&function(){j.isRunningUnobservations=!0;try{let e=j.pendingUnobservations;for(let t=0;t<e.length;t++){let n=e[t];n.isPendingUnobservation=!1,n.H&&n.H.size!==0||(n.H=null,n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof xn&&n.G())}j.pendingUnobservations=[]}finally{j.isRunningUnobservations=!1}}())}function Le(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.L)==null||t.forEach(Le))}function Re(e){let t=j.trackingDerivation;return t===null?((!e.H||e.H.size===0)&&j.inBatch>0&&Pe(e),!1):(t.U!==e.J&&(e.J=t.U,t.$[t.W++]=e,!e.isBeingObserved&&j.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function ze(e){var t;e.F!==2&&(e.F=2,(t=e.H)==null||t.forEach(e=>{e.K===0&&e.q(),e.K=2}))}function Be(){j.inBatch>0||j.isRunningReactions||An(Ve)}function Ve(){j.isRunningReactions=!0;let e=j.pendingReactions,t=0;for(;e.length>0;){++t===kn&&(console.error(`[mobx] cycle in reaction: ${e[0]}`),e.splice(0));let n=e.splice(0);for(let e=0,t=n.length;e<t;e++)n[e].X()}j.isRunningReactions=!1}function He(e){return he(e,S)}function Ue(e){return function(t,n){return n&&typeof n.kind==`string`?S(e?Fn:Nn,t,n):r(t)?be(t.name||`<unnamed action>`,t,e):r(n)?be(t,n,e):i(t)?He(b(e?Mn:M,{name:t,autoAction:e})):void 0}}function We(e){return xe(0,!1,e,this,void 0)}function Ge(e){return r(e)&&!0===e.isMobxAction}function Ke(e,t=Vt){function n(){e(a)}var r;let i=t?.name??`Autorun`,a;if(t.scheduler||t.delay){let e=qe(t),r=!1;a=new On(i,()=>{r||(r=!0,e(()=>{r=!1,a.isDisposed||a.track(n)}))},t.onError,t.requiresObservable)}else a=new On(i,function(){this.track(n)},t.onError,t.requiresObservable);return t!=null&&(r=t.signal)!=null&&r.aborted||a.Y(),a.Z(t?.signal)}function qe(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Vn}function Je(e,t,n,i){let a=typeof i==`function`?Dt(t,n):Dt(t),o=r(i)?i:n,s=`${e}L`;return a[s]?a[s].add(o):a[s]=new Set([o]),function(){let e=a[s];e&&(e.delete(o),e.size===0&&delete a[s])}}function Ye(e,t,n,r){let i=Gt(t);return At(()=>{let t=wt(e,r)[k];Wt(i).forEach(e=>{t.u(e,i[e],!n||!(e in n)||n[e])})}),e}function Xe(e){let t={name:e.tt};var n;return e.L&&e.L.length>0&&(t.dependencies=(n=e.L,Array.from(new Set(n))).map(Xe)),t}function Ze(e){let t={name:e.tt};return function(e){return!!e.H&&e.H.size>0}(e)&&(t.observers=Array.from(function(e){return e.H??new Set}(e),Ze)),t}function Qe(e){r(e.cancel)&&e.cancel()}function $e(e){return!0===e?.isMobXFlow}function et(e,t){var n;if(t===void 0)return Sn(e);if(!1===Et(e))return!1;let r=e[k];return(n=r.O)!=null&&n.has(t)?!0:r.j.has(t)?Sn(Dt(e,t)):!1}function tt(e,t){if(!e)return!1;if(t!==void 0){if(Et(e)){var n,r;let i=e[k];return i.j.has(t)||!((n=i.O)==null||!n.has(t))||!((r=i.V)==null||!r.has(t))}return!1}return Et(e)||!!e[k]||qt(e)||jn(e)||Sn(e)}function nt(e){return tt(e)}function rt(e){return Et(e)?e[k].nt():ar(e)||cr(e)?Array.from(e.keys()):xt(e)?e.map((e,t)=>t):void t(5)}function it(e,n){return Et(e)?e[k].et(n):ar(e)||cr(e)?e.has(n):xt(e)?n>=0&&n<e.length:void t(10)}function at(e){if(Et(e))return e[k].it();t(38)}function ot(e,t,n){if(Sn(e)){let r,i=!0;return Ke(()=>{let a=e.get();if(!i||n){let n=Ae();t({observableKind:`computed`,debugObjectName:e.tt,type:Zn,object:e,newValue:a,oldValue:r}),je(n)}i=!1,r=a})}return n&&t({observableKind:`value`,debugObjectName:e.tt,object:e,type:Zn,newValue:e.rt,oldValue:void 0}),ht(e,t)}function st(e,t,n){return e.set(t,n),n}function ct(e,t){if(typeof e!=`object`||!e||e instanceof Date||!nt(e))return e;if(bn(e)||Sn(e))return ct(e.get(),t);if(t.has(e))return t.get(e);if(xt(e)){let n=st(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=ct(e,t)}),n}if(cr(e)){let n=st(t,e,new Set);return e.forEach(e=>{n.add(ct(e,t))}),n}if(ar(e)){let n=st(t,e,new Map);return e.forEach((e,r)=>{n.set(r,ct(e,t))}),n}{let n=st(t,e,{});return at(e).forEach(r=>{zt.propertyIsEnumerable.call(e,r)&&(n[r]=ct(e[r],t))}),n}}function lt(e,t){Fe();try{return e.apply(t)}finally{Ie()}}function ut(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[k].isDisposed){if(a(),!n.onError)throw e;n.onError(e)}},n.timeout)}n.name=`When`;let i=be(`When-effect`,t);var a=Ke(t=>{we(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function dt(e){return e[k]}function ft(e){return e.st!==void 0&&e.st.length>0}function pt(e,t){let r=e.st;return r?r.push(t):r=e.st=[t],n(()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)})}function D(e,n){let r=Ae();try{let r=[...e.st||[]];for(let e=0,i=r.length;e<i&&((n=r[e](n))&&!n.type&&t(14),n);e++);return n}finally{je(r)}}function mt(e){return e.ot!==void 0&&e.ot.length>0}function ht(e,t){let r=e.ot;return r?r.push(t):r=e.ot=[t],n(()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)})}function gt(e,t){let n=Ae(),r=e.ot;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);je(n)}}function _t(e,n,r){if(!0===r&&(r=e.ut),!1===r)return;n in e.h||t(1,r.t,`${e.tt}.${n.toString()}`);let i=e.h;for(;i&&i!==zt;){let t=Lt(i,n);if(t){let a=r.o(e,n,t,i);if(a===0)return;if(a===1)break}i=Object.getPrototypeOf(i)}}function O(e,t){typeof Array.prototype[e]==`function`&&(er[e]=t(e))}function vt(e){return function(){let t=this[k];t.ct.reportObserved();let n=t.ht(t.j);return n[e].apply(n,arguments)}}function yt(e){return function(t,n){let r=this[k];return r.ct.reportObserved(),r.ht(r.j)[e]((e,r)=>t.call(n,e,r,this))}}function bt(e){return function(){let t=this[k];t.ct.reportObserved();let n=t.ht(t.j),r=arguments[0];return arguments[0]=(e,t,n)=>r(e,t,n,this),n[e].apply(n,arguments)}}function xt(e){return a(e)&&tr(e[k])}function St(e){return e[Symbol.toStringTag]=`MapIterator`,Pt(e)}function Ct(e){return e[Symbol.toStringTag]=`SetIterator`,Pt(e)}function wt(e,t){if(p(e,k))return e;let n=t?.name??`ObservableObject`;return c(e,k,new dr(e,new Map,String(n),function(e){return e?e.defaultDecorator??function(e){let t=!1!==e.deep,n=!!e.autoBind,r=!t|(n?2:0);return A[r]??(A[r]=fe({deep:t,autoBind:n}))}(e):void 0}(t))),e}function Tt(e){return lr[e]||(lr[e]={get(){return this[k]._(e)},set(t){return this[k].M(e,t)}})}function Et(e){return!!a(e)&&fr(e[k])}function Dt(e,n){if(typeof e==`object`&&e){if(xt(e))return n!==void 0&&t(23),e[k].ct;if(cr(e))return e.ct;if(ar(e)){if(n===void 0)return e.lt;let r=e.ft.get(n)||e.dt.get(n);return r||t(25,n,kt(e)),r}if(Et(e)){if(!n)return t(26);let r=e[k],i=r.j.get(n)??r.vt(n)??r.bt(n);return i||t(27,n,kt(e)),i}if(qt(e)||Sn(e)||jn(e))return e}else if(r(e)&&jn(e[k]))return e[k];t(28)}function Ot(e,n){return e||t(29),n===void 0?qt(e)||Sn(e)||jn(e)||ar(e)||cr(e)?e:e[k]?e[k]:void t(24,e):Ot(Dt(e,n))}function kt(e,t){let n;if(t!==void 0)n=Dt(e,t);else{if(Ge(e))return e.name;n=Et(e)||ar(e)||cr(e)?Ot(e):Dt(e)}return n.tt}function At(e){let t=Ae();Fe();try{return e()}finally{Ie(),je(t)}}function jt(e,t,n=-1){return Mt(e,t,n)}function Mt(e,t,n,i,a){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!=e)return t!=t;let o=typeof e;if(o!==`function`&&o!==`object`&&typeof t!=`object`)return!1;let s=pr.call(e);if(s!==pr.call(t))return!1;switch(s){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++}e=Nt(e),t=Nt(t);let c=s===`[object Array]`;if(!c){if(typeof e!=`object`||typeof t!=`object`)return!1;let n=e.constructor,i=t.constructor;if(n!==i&&!(r(n)&&n instanceof n&&r(i)&&i instanceof i)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),a||=[];let l=(i||=[]).length;for(;l--;)if(i[l]===e)return a[l]===t;if(i.push(e),a.push(t),c){if(l=e.length,l!==t.length)return!1;for(;l--;)if(!Mt(e[l],t[l],n-1,i,a))return!1}else{let r=Object.keys(e),o=r.length;if(Object.keys(t).length!==o)return!1;for(let s=0;s<o;s++){let o=r[s];if(!p(t,o)||!Mt(e[o],t[o],n-1,i,a))return!1}}return i.pop(),a.pop(),!0}function Nt(e){return xt(e)?e.slice():u(e)||ar(e)||d(e)||cr(e)?Array.from(e.entries()):e}function Pt(e){return e[Symbol.iterator]=Ft,It(Object.create(mr),e)}function Ft(){return this}Object.defineProperty(e,`__esModule`,{value:!0});let It=Object.assign,Lt=Object.getOwnPropertyDescriptor,Rt=Object.defineProperty,zt=Object.prototype,Bt=[];Object.freeze(Bt);let Vt={};Object.freeze(Vt);let Ht=Object.toString(),Ut=()=>{},Wt=Reflect.ownKeys,Gt=Object.getOwnPropertyDescriptors,k=Symbol(`mobx administration`);var Kt=class{constructor(e=`Atom`){this.tt=void 0,this.yt=0,this.H=null,this.J=0,this.F=-1,this.onBOL=void 0,this.onBUOL=void 0,this.tt=e}get isBeingObserved(){return m(this.yt,1)}set isBeingObserved(e){this.yt=h(this.yt,1,e)}get isPendingUnobservation(){return m(this.yt,2)}set isPendingUnobservation(e){this.yt=h(this.yt,2,e)}get diffValue(){return+!!m(this.yt,4)}set diffValue(e){this.yt=h(this.yt,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return Re(this)}reportChanged(){Fe(),ze(this),Ie()}toString(){return this.tt}};let qt=l(`Atom`,Kt),Jt=Object.is,Yt={t:`override`,o:function(){return 0},u:function(){t(44,this.t)}},Xt=`true`,Zt=fe(),A=[Zt],Qt={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Qt);let $t=ce(`observable`),en=ce(`observable.ref`,{A:y}),tn=ce(`observable.shallow`,{A:function(e,t,n){return e==null||Et(e)||xt(e)||ar(e)||cr(e)?e:Array.isArray(e)?ln.array(e,{name:n,deep:!1}):o(e)?ln.object(e,void 0,{name:n,deep:!1}):u(e)?ln.map(e,{name:n,deep:!1}):d(e)?ln.set(e,{name:n,deep:!1}):void 0}}),nn=ce(`observable.struct`,{A:function(e,t){return jt(e,t)?t:e}}),rn={box(e,t){let n=ge(t);return new yn(e,ve(n),n.name,!0,n.equals)},array(e,t){let n=ge(t);return function(e,t,n=`ObservableArray`,r=!1){return At(()=>{let i=new $n(n,t,r);Rt(i.j,k,{enumerable:!1,writable:!1,configurable:!0,value:i});let a=new Proxy(i.j,Qn);return i.v=a,e&&e.length&&i.wt(0,0,e),a})}(e,ve(n),n.name)},map(e,t){let n=ge(t);return new ir(e,ve(n),n.name)},set(e,t){let n=ge(t);return new sr(e,ve(n),n.name)},object:(e,t,n)=>At(()=>Ye(function(e,t){var n;return(n=(e=wt(e,t))[k]).v??(n.v=new Proxy(e,Jn))}({},n),e,t))},an=_e(en),on=_e(tn),sn=_e($t),cn=_e(nn);var ln=It(function(e,t,n){return t&&typeof t.kind==`string`?de($t,e,t):nt(e)?e:o(e)?ln.object(e,t,n):Array.isArray(e)?ln.array(e,t):u(e)?ln.map(e,t):d(e)?ln.set(e,t):typeof e==`object`&&e?e:ln.box(e,t)},$t,rn);let un=`computed`,dn=w(un),fn=ye(w(`computed.struct`,{equals:_})),pn=function(e,t){if(t&&typeof t.kind==`string`)return T(dn,e,t);if(o(e))return ye(w(un,e));let n=o(t)?t:{};return n.get=e,n.name||=e.name||``,new xn(n)};var mn;It(pn,dn);let hn=0,gn=1,_n=(mn=Lt(()=>{},`name`)?.configurable)!=null&&mn,vn={value:`action`,configurable:!0,writable:!1,enumerable:!1};var yn=class extends Kt{constructor(e,t,n=`ObservableValue`,r=!0,i=Jt){super(n),this.A=void 0,this.tt=void 0,this.xt=void 0,this.gt=!1,this.st=void 0,this.ot=void 0,this.rt=void 0,this.dehancer=void 0,this.A=t,this.tt=n,this.xt=i,this.rt=t(e,void 0,n)}dehanceValue(e){return this.dehancer===void 0?e:this.dehancer(e)}set(e){(e=this.jt(e))!==j.UNCHANGED&&this.Ot(e)}jt(e){if(ft(this)){let t=D(this,{object:this,type:Zn,newValue:e});if(!t)return j.UNCHANGED;e=t.newValue}return e=this.A(e,this.rt,this.tt),this.xt(this.rt,e)?j.UNCHANGED:e}Ot(e){let t=this.rt;this.rt=e,this.reportChanged(),mt(this)&&gt(this,{type:Zn,object:this,newValue:e,oldValue:t})}get(){return this.reportObserved(),this.dehanceValue(this.rt)}raw(){return this.rt}toJSON(){return this.get()}toString(){return`${this.tt}[${this.rt}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let bn=l(`ObservableValue`,yn);var xn=class{constructor(e){this.K=-1,this.L=[],this.$=null,this.H=null,this.U=0,this.J=0,this.F=0,this.W=0,this.rt=new Cn(null),this.tt=void 0,this._t=void 0,this.yt=0,this.derivation=void 0,this.St=void 0,this.At=void 0,this.xt=void 0,this.Vt=void 0,this.Mt=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||t(31),this.derivation=e.get,this.tt=e.name||`ComputedValue`,e.set&&(this.St=be(`ComputedValue-setter`,e.set)),this.xt=e.equals||Jt,this.At=e.context,this.Vt=e.requiresReaction,this.Mt=!!e.keepAlive}q(){(function(e){var t;e.F===0&&(e.F=1,(t=e.H)==null||t.forEach(e=>{e.K===0&&(e.K=1,e.q())}))})(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return m(this.yt,1)}set isComputing(e){this.yt=h(this.yt,1,e)}get isRunningSetter(){return m(this.yt,2)}set isRunningSetter(e){this.yt=h(this.yt,2,e)}get isBeingObserved(){return m(this.yt,4)}set isBeingObserved(e){this.yt=h(this.yt,4,e)}get isPendingUnobservation(){return m(this.yt,8)}set isPendingUnobservation(e){this.yt=h(this.yt,8,e)}get diffValue(){return+!!m(this.yt,16)}set diffValue(e){this.yt=h(this.yt,16,e===1)}get(){if(this.isComputing&&t(32,this.tt,this.derivation),j.inBatch!==0||this.H&&this.H.size!==0||this.Mt){let e=this.isBeingObserved;if(Re(this),Ee(this)){let e=j.trackingContext;e||!this.Mt&&!this.isBeingObserved||(j.trackingContext=this),this.trackAndCompute()&&function(e){var t;e.F!==2&&(e.F=2,(t=e.H)==null||t.forEach(t=>{t.K===1?t.K=2:t.K===0&&(e.F=0)}))}(this),j.trackingContext=e}else !e&&this.isBeingObserved&&this.L.forEach(Le)}else Ee(this)&&(this.Nt(),Fe(),this.rt=this.Rt(!1),Ie());let e=this.rt;if(Te(e))throw e.cause;return e}set(e){if(this.St){this.isRunningSetter&&t(33,this.tt),this.isRunningSetter=!0;try{this.St.call(this.At,e)}finally{this.isRunningSetter=!1}}else t(34,this.tt)}trackAndCompute(){let e=this.rt,t=this.K===-1,n=this.Rt(!0),r=t||Te(e)||Te(n)||!this.xt(e,n);return r&&(this.rt=n),r}Rt(e){let t;if(this.isComputing=!0,e)t=De(this,this.derivation,this.At);else if(!0===j.disableErrorBoundaries)t=this.derivation.call(this.At);else try{t=this.derivation.call(this.At)}catch(e){t=new Cn(e)}return this.isComputing=!1,t}G(){this.Mt||(Oe(this),this.rt=void 0)}Nt(){}toString(){return`${this.tt}[${this.derivation.toString()}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let Sn=l(`ComputedValue`,xn);var Cn=class{constructor(e){this.cause=void 0,this.cause=e}};let wn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Tn=class{constructor(){this.version=7,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.isRunningUnobservations=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.safeDescriptors=!0}};let En=!0,Dn=!1,j=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(En=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(En=!1),En?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Tn):(setTimeout(()=>{Dn||t(35)},1),new Tn)}();var On=class{constructor(e=`Reaction`,t,n,r){this.tt=void 0,this.Et=void 0,this.kt=void 0,this.Ct=void 0,this.L=[],this.$=[],this.K=-1,this.U=0,this.W=0,this.yt=0,this.It=void 0,this.tt=e,this.Et=t,this.kt=n,this.Ct=r}get isDisposed(){return m(this.yt,1)}set isDisposed(e){this.yt=h(this.yt,1,e)}get isScheduled(){return m(this.yt,2)}set isScheduled(e){this.yt=h(this.yt,2,e)}get isTrackPending(){return m(this.yt,4)}set isTrackPending(e){this.yt=h(this.yt,4,e)}get isRunning(){return m(this.yt,8)}set isRunning(e){this.yt=h(this.yt,8,e)}get diffValue(){return+!!m(this.yt,16)}set diffValue(e){this.yt=h(this.yt,16,e===1)}q(){this.Y()}Y(){this.isScheduled||(this.isScheduled=!0,j.pendingReactions.push(this),Be())}X(){if(!this.isDisposed){Fe(),this.isScheduled=!1;let e=j.trackingContext;if(j.trackingContext=this,Ee(this)){this.isTrackPending=!0;try{this.Et()}catch(e){this.Pt(e)}}j.trackingContext=e,Ie()}}track(e){if(this.isDisposed)return;Fe(),this.isRunning=!0;let t=j.trackingContext;j.trackingContext=this;let n=De(this,e,void 0);j.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Oe(this),Te(n)&&this.Pt(n.cause),Ie()}Pt(e){if(this.kt)this.kt(e,this);else{if(j.disableErrorBoundaries)throw e;j.suppressReactionErrors||console.error(`[mobx] uncaught error in '${this}'`,e),j.globalReactionErrorHandlers.forEach(t=>t(e,this))}}dispose(){var e;this.isDisposed||(this.isDisposed=!0,(e=this.It)==null||e.call(this),this.isRunning||(Fe(),Oe(this),Ie()))}Z(e){let t=()=>this.dispose();return e!=null&&e.addEventListener&&!this.isDisposed&&(e.addEventListener(`abort`,t),this.It=()=>e.removeEventListener==null?void 0:e.removeEventListener(`abort`,t)),t[k]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.tt}]`}};let kn=100,An=e=>e(),jn=l(`Reaction`,On),M=`action`,Mn=`autoAction`,Nn=b(M),Pn=b(`action.bound`,{bound:!0}),Fn=b(Mn,{autoAction:!0}),In=b(`autoAction.bound`,{autoAction:!0,bound:!0}),Ln=Ue(!1);It(Ln,Nn);let Rn=Ue(!0);It(Rn,Fn);let zn=He(Pn),Bn=He(In),Vn=e=>e(),Hn=`always`;var Un=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};let Wn=ne(`flow`),Gn=ne(`flow.bound`,{bound:!0}),Kn=It(function(e,t){if(t&&typeof t.kind==`string`)return ae(Wn,e,t);let n=e,i=n.name||`flow`,a=function(){let e=arguments,t=Ln(i,n).apply(this,e),a,o,s=new Promise(function(e,n){function s(e){let r;o=void 0;try{r=Ln(i,t.next).call(t,e)}catch(e){return n(e)}l(r)}function c(e){let r;o=void 0;try{r=Ln(i,t.throw).call(t,e)}catch(e){return n(e)}l(r)}function l(t){if(!r(t?.then))return t.done?e(t.value):(o=Promise.resolve(t.value),o.then(s,c));t.then(l,n)}a=n,s(void 0)});return s.cancel=Ln(i,function(){try{o&&Qe(o);let e=t.return(void 0),n=Promise.resolve(e.value);n.then(Ut,Ut),Qe(n),a(new Un)}catch(e){a(e)}}),s};return a.isMobXFlow=!0,a},Wn),qn=he(Gn,ae),Jn={has:(e,t)=>dt(e).et(t),get:(e,t)=>dt(e).Tt(t),set(e,t,n){var r;return!!i(t)&&((r=dt(e).Bt(t,n,!0))==null||r)},deleteProperty(e,t){var n;return!!i(t)&&((n=dt(e).Dt(t,!0))==null||n)},defineProperty(e,t,n){var r;return(r=dt(e).l(t,n))==null||r},ownKeys:e=>dt(e).it(),preventExtensions(e){t(13)}},Yn=Symbol(`mobx-keys`),Xn=`splice`,Zn=`update`,Qn={get(e,t){let n=e[k];return t===k?n:t===`length`?n.Kt():typeof t!=`string`||isNaN(t)?p(er,t)?er[t]:e[t]:n.Tt(parseInt(t))},set(e,t,n){let r=e[k];return t===`length`?r.Lt(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.Bt(parseInt(t),n),!0},preventExtensions(){t(15)}};var $n=class{constructor(e=`ObservableArray`,t,n){this.$t=void 0,this.ct=void 0,this.j=[],this.st=void 0,this.ot=void 0,this.A=void 0,this.dehancer=void 0,this.v=void 0,this.Ut=0,this.$t=n,this.ct=new Kt(e),this.A=(e,n)=>t(e,n,`ObservableArray[..]`)}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}ht(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e}Kt(){return this.ct.reportObserved(),this.j.length}Lt(e){(!Number.isInteger(e)||e<0)&&t(40,e);let n=this.j.length;if(e!==n)if(e>n){let t=Array.from({length:e-n});this.wt(n,0,t)}else this.wt(e,n-e)}zt(e,n){e!==this.Ut&&t(16),this.Ut+=n}wt(e,t,n){let r=this.j.length;if(e===void 0?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=arguments.length===1?r-e:t==null?0:Math.max(0,Math.min(t,r-e)),n===void 0&&(n=Bt),ft(this)){let r=D(this,{object:this.v,type:Xn,index:e,removedCount:t,added:n});if(!r)return Bt;t=r.removedCount,n=r.added}n=n.length===0?n:n.map(e=>this.A(e,void 0));let i=this.qt(e,t,n);return t===0&&n.length===0||this.Ft(e,n,i),this.ht(i)}qt(e,t,n){if(n.length<1e4)return this.j.splice(e,t,...n);{let r=this.j.slice(e,e+t),i=this.j.slice(e+t);this.j.length+=n.length-t;for(let t=0;t<n.length;t++)this.j[e+t]=n[t];for(let t=0;t<i.length;t++)this.j[e+n.length+t]=i[t];return r}}Ht(e,t,n){let r=mt(this),i=r?{observableKind:`array`,object:this.v,type:Zn,debugObjectName:this.ct.tt,index:e,newValue:t,oldValue:n}:null;this.ct.reportChanged(),r&&gt(this,i)}Ft(e,t,n){let r=mt(this),i=r?{observableKind:`array`,object:this.v,debugObjectName:this.ct.tt,type:Xn,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;this.ct.reportChanged(),r&&gt(this,i)}Tt(e){return this.ct.reportObserved(),this.Wt(this.j[e])}Bt(e,t){let n=this.j;if(e<n.length){let r=n[e];if(ft(this)){let n=D(this,{type:Zn,object:this.v,index:e,newValue:t});if(!n)return;t=n.newValue}(t=this.A(t,r))!==r&&(n[e]=t,this.Ht(e,t,r))}else{let r=Array.from({length:e+1-n.length});r[r.length-1]=t,this.wt(n.length,0,r)}}},er={clear(){return this.splice(0)},replace(e){let t=this[k];return t.wt(0,t.j.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[k];switch(arguments.length){case 0:return[];case 1:return r.wt(e);case 2:return r.wt(e,t)}return r.wt(e,t,n)},spliceWithArray(e,t,n){return this[k].wt(e,t,n)},push(...e){let t=this[k];return t.wt(t.j.length,0,e),t.j.length},pop(){return this.splice(Math.max(this[k].j.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[k];return t.wt(0,0,e),t.j.length},reverse(){return j.trackingDerivation&&t(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){j.trackingDerivation&&t(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[k],n=t.ht(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};O(`at`,vt),O(`concat`,vt),O(`flat`,vt),O(`includes`,vt),O(`indexOf`,vt),O(`join`,vt),O(`lastIndexOf`,vt),O(`slice`,vt),O(`toString`,vt),O(`toLocaleString`,vt),O(`toSorted`,vt),O(`toSpliced`,vt),O(`with`,vt),O(`every`,yt),O(`filter`,yt),O(`find`,yt),O(`findIndex`,yt),O(`findLast`,yt),O(`findLastIndex`,yt),O(`flatMap`,yt),O(`forEach`,yt),O(`map`,yt),O(`some`,yt),O(`toReversed`,yt),O(`reduce`,bt),O(`reduceRight`,bt);let tr=l(`ObservableArrayAdministration`,$n),nr={},rr=`delete`;var ir=class{constructor(e,t=v,n=`ObservableMap`){this.A=void 0,this.tt=void 0,this[k]=nr,this.ft=void 0,this.dt=void 0,this.lt=void 0,this.st=void 0,this.ot=void 0,this.dehancer=void 0,this.A=t,this.tt=n,At(()=>{this.lt=g(`ObservableMap.keys()`),this.ft=new Map,this.dt=new Map,e&&this.merge(e)})}et(e){return this.ft.has(e)}has(e){if(!j.trackingDerivation)return this.et(e);let t=this.dt.get(e);if(!t){let n=t=new yn(this.et(e),y,`ObservableMap.key?`,!1);this.dt.set(e,n),n.onBUOL=new Set([()=>this.dt.delete(e)])}return t.get()}set(e,t){let n=this.et(e);if(ft(this)){let r=D(this,{type:n?Zn:`add`,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.Gt(e,t):this.Jt(e,t),this}delete(e){if(ft(this)&&!D(this,{type:rr,object:this,name:e}))return!1;if(this.et(e)){let t=mt(this),n=t?{observableKind:`map`,debugObjectName:this.tt,type:rr,object:this,oldValue:this.ft.get(e).rt,name:e}:null;return lt(()=>{var t;this.lt.reportChanged(),(t=this.dt.get(e))==null||t.Ot(!1),this.ft.get(e).Ot(void 0),this.ft.delete(e)}),t&&gt(this,n),!0}return!1}Gt(e,t){let n=this.ft.get(e);if((t=n.jt(t))!==j.UNCHANGED){let r=mt(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:Zn,object:this,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&gt(this,i)}}Jt(e,t){lt(()=>{var n;let r=new yn(t,this.A,`ObservableMap.key`,!1);this.ft.set(e,r),t=r.rt,(n=this.dt.get(e))==null||n.Ot(!0),this.lt.reportChanged()});let n=mt(this);n&&gt(this,n?{observableKind:`map`,debugObjectName:this.tt,type:`add`,object:this,name:e,newValue:t}:null)}get(e){return this.has(e)?this.Wt(this.ft.get(e).get()):this.Wt(void 0)}getOrInsert(e,t){return this.has(e)||this.set(e,t),this.get(e)}getOrInsertComputed(e,t){return this.has(e)||this.set(e,t(e)),this.get(e)}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}keys(){return this.lt.reportObserved(),this.ft.keys()}values(){let e=this,t=this.keys();return St({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:e.get(r)}}})}entries(){let e=this,t=this.keys();return St({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:[r,e.get(r)]}}})}[Symbol.iterator](){return this.entries()}forEach(e,t){for(let[n,r]of this)e.call(t,r,n,this)}merge(e){return ar(e)&&(e=new Map(e)),lt(()=>{o(e)?function(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>zt.propertyIsEnumerable.call(e,t))]:t}(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):u(e)?(function(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}(e)||t(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&t(20,e)}),this}clear(){lt(()=>{ke(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return lt(()=>{let n=function(e){if(u(e)||ar(e))return e;if(Array.isArray(e))return new Map(e);if(o(e)){let t=new Map;for(let n in e)t.set(n,e[n]);return t}return t(21,e)}(e),r=new Map,i=!1;for(let e of this.ft.keys())if(!n.has(e))if(this.delete(e))i=!0;else{let t=this.ft.get(e);r.set(e,t)}for(let[e,t]of n.entries()){let n=this.ft.has(e);if(this.set(e,t),this.ft.has(e)){let t=this.ft.get(e);r.set(e,t),n||(i=!0)}}if(!i)if(this.ft.size!==r.size)this.lt.reportChanged();else{let e=this.ft.keys(),t=r.keys(),n=e.next(),i=t.next();for(;!n.done;){if(n.value!==i.value){this.lt.reportChanged();break}n=e.next(),i=t.next()}}this.ft=r}),this}get size(){return this.lt.reportObserved(),this.ft.size}toString(){return`[object ObservableMap]`}toJSON(){return Array.from(this)}get[Symbol.toStringTag](){return`Map`}},ar=l(`ObservableMap`,ir);let or={};var sr=class{constructor(e,t=v,n=`ObservableSet`){this.tt=void 0,this[k]=or,this.ft=new Set,this.ct=void 0,this.ot=void 0,this.st=void 0,this.dehancer=void 0,this.A=void 0,this.tt=n,this.A=(e,r)=>t(e,r,n),At(()=>{this.ct=g(this.tt),e&&this.replace(e)})}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){lt(()=>{ke(()=>{for(let e of this.ft.values())this.delete(e)})})}forEach(e,t){for(let n of this)e.call(t,n,n,this)}get size(){return this.ct.reportObserved(),this.ft.size}add(e){if(ft(this)){let t=D(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){lt(()=>{e=this.A(e,void 0),this.ft.add(e),this.ct.reportChanged()});let t=mt(this);t&&gt(this,t?{observableKind:`set`,debugObjectName:this.tt,type:`add`,object:this,newValue:e}:null)}return this}delete(e){if(ft(this)&&!D(this,{type:rr,object:this,oldValue:e}))return!1;if(this.has(e)){let t=mt(this),n=t?{observableKind:`set`,debugObjectName:this.tt,type:rr,object:this,oldValue:e}:null;return lt(()=>{this.ct.reportChanged(),this.ft.delete(e)}),t&&gt(this,n),!0}return!1}has(e){return this.ct.reportObserved(),this.ft.has(this.Wt(e))}entries(){let e=this.values();return Ct({next(){let{value:t,done:n}=e.next();return n?{value:void 0,done:n}:{value:[t,t],done:n}}})}keys(){return this.values()}values(){this.ct.reportObserved();let e=this,t=this.ft.values();return Ct({next(){let{value:n,done:r}=t.next();return r?{value:void 0,done:r}:{value:e.Wt(n),done:r}}})}intersection(e){return new Set(this).intersection(e)}union(e){return new Set(this).union(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}replace(e){return cr(e)&&(e=new Set(e)),Array.isArray(e)||d(e)?lt(()=>{let t=d(e)?e:new Set(e);if(t.size!==0)if(this.ft.size!==0){for(let e of this.ft.values())t.has(this.Wt(e))||this.delete(e);t.forEach(e=>this.add(e))}else t.forEach(e=>this.add(e));else this.clear()}):e!=null&&t(41,e),this}toJSON(){return Array.from(this)}toString(){return`[object ObservableSet]`}[Symbol.iterator](){return this.values()}get[Symbol.toStringTag](){return`Set`}},cr=l(`ObservableSet`,sr);let lr=Object.create(null),ur=`remove`;var dr=class{constructor(e,t=new Map,n,r=Zt){this.h=void 0,this.j=void 0,this.tt=void 0,this.ut=void 0,this.lt=void 0,this.ot=void 0,this.st=void 0,this.v=void 0,this.p=void 0,this.Xt=void 0,this.Qt=void 0,this.O=void 0,this.V=void 0,this.h=e,this.j=t,this.tt=n,this.ut=r,this.lt=new Kt(`ObservableObject.keys`),this.p=o(this.h)}_(e){return(this.j.get(e)??this.vt(e)??this.bt(e)).get()}vt(e){let t=this.O?.get(e);if(!t)return;this.O.delete(e),this.O.size===0&&(this.O=void 0);let n=t();return this.j.set(e,n),n}bt(e){let t=this.V?.get(e);if(!t)return;this.V.delete(e),this.V.size===0&&(this.V=void 0);let n=t();return this.j.set(e,n),n}M(e,t){let n=this.j.get(e)??this.vt(e)??this.bt(e);if(n instanceof xn)return n.set(t),!0;if(ft(this)){let n=D(this,{type:Zn,object:this.v||this.h,name:e,newValue:t});if(!n)return null;t=n.newValue}if((t=n.jt(t))!==j.UNCHANGED){let r=mt(this),i=r?{type:Zn,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&gt(this,i)}return!0}Tt(e){return j.trackingDerivation&&!p(this.h,e)&&this.et(e),this.h[e]}Bt(e,t,n=!1){return p(this.h,e)?this.j.has(e)?this.M(e,t):n?Reflect.set(this.h,e,t):(this.h[e]=t,!0):this.u(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.ut,n)}et(e){if(!j.trackingDerivation)return e in this.h;this.Qt||=new Map;let t=this.Qt.get(e);return t||(t=new yn(e in this.h,y,`ObservableObject.key?`,!1),this.Qt.set(e,t)),t.get()}u(e,t,n,r=!1){return!0===n&&(n=this.ut),!1===n?this.l(e,t,r):n.u(this,e,t,r)}l(e,t,n=!1){try{Fe();let r=this.Dt(e);if(!r)return r;if(ft(this)){let n=D(this,{object:this.v||this.h,name:e,type:`add`,newValue:t.value});if(!n)return null;let{newValue:r}=n;t.value!==r&&(t=It({},t,{value:r}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else Rt(this.h,e,t);this.Yt(e,t.value)}finally{Ie()}return!0}S(e,t,n,r=!1){try{Fe();let i=this.Dt(e);if(!i)return i;if(ft(this)){let n=D(this,{object:this.v||this.h,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let a=Tt(e),o={configurable:!j.safeDescriptors||this.p,enumerable:!0,get:a.get,set:a.set};if(r){if(!Reflect.defineProperty(this.h,e,o))return!1}else Rt(this.h,e,o);let s=new yn(t,n,`ObservableObject.key`,!1);this.j.set(e,s),this.Yt(e,s.rt)}finally{Ie()}return!0}m(e,t,n=!1){try{Fe();let r=this.Dt(e);if(!r)return r;if(ft(this)&&!D(this,{object:this.v||this.h,name:e,type:`add`,newValue:void 0}))return null;t.name||=`ObservableObject.key`,t.context=this.v||this.h;let i=Tt(e),a={configurable:!j.safeDescriptors||this.p,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.h,e,a))return!1}else Rt(this.h,e,a);this.j.set(e,new xn(t)),this.Yt(e,void 0)}finally{Ie()}return!0}Dt(e,t=!1){if(!p(this.h,e))return!0;if(ft(this)&&!D(this,{object:this.v||this.h,name:e,type:ur}))return null;try{var n;Fe();let r=mt(this),i=this.j.get(e),a;if(i||!r||(a=Lt(this.h,e)?.value),t){if(!Reflect.deleteProperty(this.h,e))return!1}else delete this.h[e];i&&(this.j.delete(e),i instanceof yn&&(a=i.rt),ze(i)),this.lt.reportChanged(),(n=this.Qt)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&gt(this,{type:ur,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{Ie()}return!0}Yt(e,t){var n;let r=mt(this);r&&r&&gt(this,r?{type:`add`,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,name:e,newValue:t}:null),(n=this.Qt)==null||(n=n.get(e))==null||n.set(!0),this.lt.reportChanged()}it(){return this.lt.reportObserved(),Wt(this.h)}nt(){return this.lt.reportObserved(),Object.keys(this.h)}};let fr=l(`ObservableObjectAdministration`,dr),pr=zt.toString,mr=globalThis.Iterator?.prototype||{};e.$mobx=k,e.FlowCancellationError=Un,e.ObservableMap=ir,e.ObservableSet=sr,e.Reaction=On,e._allowStateChanges=we,e._allowStateChangesInsideComputed=We,e._allowStateReadsEnd=function(e){j.allowStateReads=e},e._allowStateReadsStart=function(e){let t=j.allowStateReads;return j.allowStateReads=e,t},e._autoAction=Rn,e._autoActionBound=Bn,e._endAction=Ce,e._getAdministration=Ot,e._getGlobalState=function(){return j},e._interceptReads=function(e,t,n){let r;return ar(e)||xt(e)||bn(e)?r=Ot(e):Et(e)&&(r=Ot(e,t)),r.dehancer=typeof t==`function`?t:n,()=>{r.dehancer=void 0}},e._isComputingDerivation=function(){return j.trackingDerivation!==null},e._resetGlobalState=function(){let e=new Tn;for(let t in e)wn.indexOf(t)===-1&&(j[t]=e[t]);j.allowStateChanges=!j.enforceActions},e._startAction=Se,e.action=Ln,e.actionBound=zn,e.autorun=Ke,e.compareDefault=Jt,e.compareIdentity=function(e,t){return e===t},e.compareShallow=function(e,t){return jt(e,t,1)},e.compareStructural=_,e.computed=pn,e.computedStruct=fn,e.configure=function(e){!0===e.isolateGlobalState&&function(){if((j.pendingReactions.length||j.inBatch||j.isRunningReactions)&&t(36),Dn=!0,En){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),j=new Tn}}();let{enforceActions:n}=e;if(n!==void 0){let e=n===Hn?Hn:n===`observed`;j.enforceActions=e,j.allowStateChanges=!0!==e&&e!==Hn}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(j[t]=!!e[t])}),j.allowStateReads=!j.observableRequiresReaction,e.reactionScheduler&&function(e){let t=An;An=n=>e(()=>t(n))}(e.reactionScheduler)},e.createAtom=g,e.defineProperty=function(e,n,r){if(Et(e))return e[k].l(n,r);t(39)},e.entries=function(e){return Et(e)?rt(e).map(t=>[t,e[t]]):ar(e)?rt(e).map(t=>[t,e.get(t)]):cr(e)?Array.from(e.entries()):xt(e)?e.map((e,t)=>[t,e]):void t(7)},e.extendObservable=Ye,e.flow=Kn,e.flowBound=qn,e.flowResult=function(e){return e},e.get=function(e,n){if(it(e,n))return Et(e)?e[k].Tt(n):ar(e)?e.get(n):xt(e)?e[n]:void t(11)},e.getAtom=Dt,e.getDebugName=kt,e.getDependencyTree=function(e,t){return Xe(Dt(e,t))},e.getObserverTree=function(e,t){return Ze(Dt(e,t))},e.has=it,e.intercept=function(e,t,n){return r(n)?function(e,t,n){return pt(Ot(e,t),n)}(e,t,n):function(e,t){return pt(Ot(e),t)}(e,t)},e.isAction=Ge,e.isBoxedObservable=bn,e.isComputed=function(e){return et(e)},e.isComputedProp=function(e,t){return et(e,t)},e.isFlow=$e,e.isFlowCancellationError=function(e){return e instanceof Un},e.isObservable=nt,e.isObservableArray=xt,e.isObservableMap=ar,e.isObservableObject=Et,e.isObservableProp=function(e,t){return tt(e,t)},e.isObservableSet=cr,e.keys=rt,e.makeAutoObservable=function(e,t,n){return o(e)?Ye(e,e,t,n):(At(()=>{let r=wt(e,n)[k];if(!e[Yn]){let t=Object.getPrototypeOf(e),n=new Set([...Wt(e),...Wt(t)]);n.delete(`constructor`),n.delete(k),c(t,Yn,n)}e[Yn].forEach(e=>_t(r,e,!t||!(e in t)||t[e]))}),e)},e.makeObservable=function(e,t,n){return At(()=>{let r=wt(e,n)[k];Wt(t).forEach(e=>_t(r,e,t[e]))}),e},e.observable=ln,e.observableDeep=sn,e.observableRef=an,e.observableShallow=on,e.observableStruct=cn,e.observe=function(e,t,n,i){return r(n)?function(e,t,n,r){return ot(Ot(e,t),n,r)}(e,t,n,i):function(e,t,n){let r=Ot(e);if(xt(e))n&&t({observableKind:`array`,object:r.v,debugObjectName:r.ct.tt,type:`splice`,index:0,added:r.j.slice(),addedCount:r.j.length,removed:[],removedCount:0});else if(!ar(e)&&!cr(e)&&!Et(e))return ot(r,t,n);return ht(r,t)}(e,t,n)},e.onBecomeObserved=function(e,t,n){return Je(`onBO`,e,t,n)},e.onBecomeUnobserved=function(e,t,n){return Je(`onBUO`,e,t,n)},e.onReactionError=function(e){return j.globalReactionErrorHandlers.push(e),()=>{let t=j.globalReactionErrorHandlers.indexOf(e);t>=0&&j.globalReactionErrorHandlers.splice(t,1)}},e.override=Yt,e.ownKeys=at,e.reaction=function(e,t,n=Vt){function r(){if(p=!1,h.isDisposed)return;let t=!1,r=d;h.track(()=>{let n=we(!1,()=>e(h));t=f||!m(d,n),d=n}),(f&&n.fireImmediately||!f&&t)&&o(d,r,h),f=!1}var i;let a=n.name??`Reaction`,o=Ln(a,n.onError?(s=n.onError,c=t,function(){try{return c.apply(this,arguments)}catch(e){s.call(this,e)}}):t);var s,c;let l=!n.scheduler&&!n.delay,u=qe(n),d,f=!0,p=!1,m=n.equals||Jt,h=new On(a,()=>{f||l?r():p||(p=!0,u(r))},n.onError,n.requiresObservable);return n!=null&&(i=n.signal)!=null&&i.aborted||h.Y(),h.Z(n?.signal)},e.remove=function(e,n){Et(e)?e[k].Dt(n):ar(e)||cr(e)?e.delete(n):xt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=We,e.set=function e(n,r,i){if(arguments.length===2&&!cr(n)){Fe();let t=r;try{for(let r in t)e(n,r,t[r])}finally{Ie()}return}Et(n)?n[k].Bt(r,i):ar(n)?n.set(r,i):cr(n)?n.add(r):xt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(42,r),Fe(),r>=n.length&&(n.length=r+1),n[r]=i,Ie()):t(8)},e.spy=function(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}},e.toJS=function(e){return ct(e,new Map)},e.transaction=lt,e.untracked=ke,e.values=function(e){return Et(e)?rt(e).map(t=>e[t]):ar(e)?rt(e).map(t=>e.get(t)):cr(e)?Array.from(e.values()):xt(e)?e.slice():void t(6)},e.when=function(e,t,n){return arguments.length===1||t&&typeof t==`object`?function(e,t){var n;if(t!=null&&(n=t.signal)!=null&&n.aborted)return It(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let r,i,a=new Promise((n,a)=>{var o;let s=ut(e,n,It({},t,{onError:a}));r=()=>{s(),a(Error(`WHEN_CANCELLED`))},i=()=>{s(),a(Error(`WHEN_ABORTED`))},t==null||(o=t.signal)==null||o.addEventListener==null||o.addEventListener(`abort`,i)}).finally(()=>{var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,i)});return a.cancel=r,a}(e,t):ut(e,t,n||{})}})),qx=ke((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t={0:`Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'`,1(e,t){return`Cannot apply '${e}' to '${t.toString()}': Field not found.`},5:`'keys()' can only be used on observable objects, arrays, sets and maps`,6:`'values()' can only be used on observable objects, arrays, sets and maps`,7:`'entries()' can only be used on observable objects, arrays and maps`,8:`'set()' can only be used on observable objects, arrays and maps`,9:`'remove()' can only be used on observable objects, arrays and maps`,10:`'has()' can only be used on observable objects, arrays and maps`,11:`'get()' can only be used on observable objects, arrays and maps`,12:`Invalid annotation`,13:`Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,14:`Intercept handlers should return nothing or a change object`,15:`Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,16:`Modification exception: the internal structure of an observable array was changed.`,19(e){return`Cannot initialize from classes that inherit from Map: `+e.constructor.name},20(e){return`Cannot initialize map from `+e},21(e){return`Cannot convert to map from '${e}'`},23:`It is not possible to get index atoms from arrays`,24(e){return`Cannot obtain administration from `+e},25(e,t){return`the entry '${e}' does not exist in the observable map '${t}'`},26:`please specify a property`,27(e,t){return`no observable property '${e.toString()}' found on the observable object '${t}'`},28(e){return`Cannot obtain atom from `+e},29:`Expecting some object`,30:`invalid action stack. did you forget to finish an action?`,31:`missing option for computed: get`,32(e,t){return`Cycle detected in computation ${e}: ${t}`},33(e){return`The setter of computed value '${e}' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?`},34(e){return`[ComputedValue '${e}'] It is not possible to assign a new value to a computed value.`},35:"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`",36:`isolateGlobalState should be called before MobX is running any reactions`,37(e){return`[mobx] \`observableArray.${e}()\` mutates the array in-place, which is not allowed inside a derivation. Use \`array.slice().${e}()\` instead`},38:`'ownKeys()' can only be used on observable objects`,39:`'defineProperty()' can only be used on observable objects`,40(e){return`Out of range: `+e},41(e){return`Cannot initialize set from `+e},42(e){return`Invalid index: '${e}'`},43(e,t,n){return`Cannot apply '${e}' to '${t}' (kind: ${n}):\n'${e}' can only be used on properties with a function value.`},44(e){return`'${e}' can only be used with 'makeObservable'`}};function n(e,...n){{let r=typeof e==`string`?e:t[e];throw typeof r==`function`&&(r=r.apply(null,n)),Error(`[MobX] ${r}`)}}let r=Object.assign,i=Object.getOwnPropertyDescriptor,a=Object.defineProperty,o=Object.prototype,s=[];Object.freeze(s);let c={};Object.freeze(c);let l=Object.toString();function u(){return++A.mobxGuid}function d(e){let t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}let f=()=>{};function p(e){return typeof e==`function`}function m(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function h(e){return typeof e==`object`&&!!e}function g(e){if(!h(e))return!1;let t=Object.getPrototypeOf(e);if(t==null)return!0;let n=ae(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===l}function _(e){let t=e?.constructor;return t?t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`:!1}function v(e,t,n){a(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function y(e,t,n){a(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function b(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return h(e)&&e[n]===!0}}function ee(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function x(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function S(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function te(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let ne=Reflect.ownKeys;function re(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function ie(e){return e===null?null:typeof e==`object`?``+e:e}function ae(e,t){return o.hasOwnProperty.call(e,t)}let C=Object.getOwnPropertyDescriptors;function w(e,t){return!!(e&t)}function oe(e,t,n){return n?e|=t:e&=~t,e}function se(e,t){t.includes(e.kind)||n(`The decorator applied to '${String(e.name)}' cannot be used on a ${e.kind} element`)}let T=Symbol(`mobx administration`);var ce=class{constructor(e=`Atom@`+u()){this.name_=void 0,this.flags_=0,this.observers_=null,this.lastAccessedBy_=0,this.lowestObserverState_=-1,this.onBOL=void 0,this.onBUOL=void 0,this.name_=e}get isBeingObserved(){return w(this.flags_,1)}set isBeingObserved(e){this.flags_=oe(this.flags_,1,e)}get isPendingUnobservation(){return w(this.flags_,2)}set isPendingUnobservation(e){this.flags_=oe(this.flags_,2,e)}get diffValue(){return+!!w(this.flags_,4)}set diffValue(e){this.flags_=oe(this.flags_,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return dn(this)}reportChanged(){sn(),fn(this),cn()}toString(){return this.name_}};let le=b(`Atom`,ce);function ue(e,t=f,n=f){let r=new ce(e);return t!==f&&(r.onBOL=new Set([t])),n!==f&&(r.onBUOL=new Set([n])),r}function de(e,t){return e===t}function fe(e,t){return Ri(e,t)}function pe(e,t){return Ri(e,t,1)}let me=Object.is;function he(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||Sr(e)?e:Array.isArray(e)?D.array(e,{name:n}):g(e)?D.object(e,void 0,{name:n}):ee(e)?D.map(e,{name:n}):S(e)?D.set(e,{name:n}):typeof e==`function`&&!Bn(e)&&!pr(e)?_(e)?lr(e):In(n,e):e}function ge(e,t,r){if(e==null||N(e)||mi(e)||vi(e)||Ci(e))return e;if(Array.isArray(e))return D.array(e,{name:r,deep:!1});if(g(e))return D.object(e,void 0,{name:r,deep:!1});if(ee(e))return D.map(e,{name:r,deep:!1});if(S(e))return D.set(e,{name:r,deep:!1});n(`The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets`)}function _e(e){return e}function ve(e,t){return Sr(e)&&n(`observable.struct should not be used with observable values`),Ri(e,t)?t:e}let ye=`override`,be={annotationType_:ye,make_:Se,extend_:Ce};function xe(e){return e.annotationType_===ye}function Se(e,t){return e.isPlainObject_&&n(`Cannot apply '${this.annotationType_}' to '${e.name_}.${t.toString()}':\n'${this.annotationType_}' cannot be used on plain objects.`),ae(e.appliedAnnotations_,t)||n(`'${e.name_}.${t.toString()}' is annotated with '${this.annotationType_}', but no such annotated member was found on prototype.`),0}function Ce(e,t,r,i){n(44,this.annotationType_)}function we(e,t){return{annotationType_:e,options_:t,make_:Te,extend_:Ee}}function Te(e,t,n,r){var i;return(i=this.options_)!=null&&i.bound?this.extend_(e,t,n,!1)===null?0:1:r===e.target_?this.extend_(e,t,n,!1)===null?0:2:Bn(n.value)?1:(a(r,t,ke(e,this,t,n,!1)),2)}function Ee(e,t,n,r){let i=ke(e,this,t,n);return e.defineProperty_(t,i,r)}function De(e,t,r){se(r,[`method`,`field`]);let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>St(s.options_?.name??a.toString(),e,s.options_?.autoAction??!1);if(i==`field`)return function(e){var t;let n=e;return Bn(n)||(n=c(n)),(t=s.options_)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n};if(i==`method`){var l;return Bn(t)||(t=c(t)),(l=s.options_)!=null&&l.bound&&o(function(){let e=this,t=e[a].bind(e);t.isMobxAction=!0,e[a]=t}),t}n(43,s.annotationType_,String(a),i)}function Oe(e,{annotationType_:t},r,{value:i}){p(i)||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on properties with a function value.`)}function ke(e,t,n,r,i=A.safeDescriptors){var a,o;Oe(e,t,n,r);let{value:s}=r;return(a=t.options_)!=null&&a.bound&&(s=s.bind(e.proxy_??e.target_)),{value:St(t.options_?.name??n.toString(),s,t.options_?.autoAction??!1,(o=t.options_)!=null&&o.bound?e.proxy_??e.target_:void 0),configurable:i?e.isPlainObject_:!0,enumerable:!1,writable:!i}}function Ae(e,t){return{annotationType_:e,options_:t,make_:je,extend_:E}}function je(e,t,n,r){var i;return r===e.target_?this.extend_(e,t,n,!1)===null?0:2:(i=this.options_)!=null&&i.bound&&(!ae(e.target_,t)||!pr(e.target_[t]))&&this.extend_(e,t,n,!1)===null?0:pr(n.value)?1:(a(r,t,Pe(e,this,t,n,!1,!1)),2)}function E(e,t,n,r){let i=Pe(e,this,t,n,this.options_?.bound);return e.defineProperty_(t,i,r)}function Me(e,t,n){var r;se(n,[`method`]);let{name:i,addInitializer:a}=n;return pr(t)||(t=lr(t)),(r=e.options_)!=null&&r.bound&&a(function(){let e=this,t=e[i].bind(e);t.isMobXFlow=!0,e[i]=t}),t}function Ne(e,{annotationType_:t},r,{value:i}){p(i)||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on properties with a generator function value.`)}function Pe(e,t,n,r,i,a=A.safeDescriptors){Ne(e,t,n,r);let{value:o}=r;return pr(o)||(o=lr(o)),i&&(o=o.bind(e.proxy_??e.target_),o.isMobXFlow=!0),{value:o,configurable:a?e.isPlainObject_:!0,enumerable:!1,writable:!a}}function Fe(e,t){return{annotationType_:e,options_:t,make_:Ie,extend_:Le}}function Ie(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Le(e,t,n,i){return ze(e,this,t,n),e.defineComputedProperty_(t,r({},this.options_,{get:n.get,set:n.set}),i)}function Re(e,t,n){se(n,[`getter`]);let i=e,{name:a,addInitializer:o}=n,s;function c(e,n){let o=r({},i.options_,{get:t,context:e});return o.name||=`${n.name_}.${a.toString()}`,new jt(o)}return o(function(){let e=Oi(this)[T],n=this,r=e.values_.get(a);r instanceof jt&&r.derivation!==t&&e.values_.delete(a),(e.lazyComputedKeys_??=new Map).set(a,()=>c(n,e))}),function(){let e=this[T],n=e.values_.get(a);if(n instanceof jt&&n.derivation!==t){let t=s?.get(this);return t||(t=c(this,e),(s??=new WeakMap).set(this,t)),t.get()}return e.getObservablePropValue_(a)}}function ze(e,{annotationType_:t},r,{get:i}){i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on getter(+setter) properties.`)}function Be(e,t){return{annotationType_:e,options_:t,make_:Ve,extend_:He}}function Ve(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function He(e,t,n,r){return We(e,this,t,n),e.defineObservableProperty_(t,n.value,this.options_?.enhancer_??he,r)}function Ue(e,t,r){if(r.kind===`field`)throw n(`Please use \`@observable accessor ${String(r.name)}\` instead of \`@observable ${String(r.name)}\``);se(r,[`accessor`]);let i=e,{kind:a,name:o}=r;if(a!==`accessor`)return;function s(e,t){let n=Oi(e)[T];return(n.lazyObservableKeys_??=new Map).set(o,()=>new kt(t,i.options_?.enhancer_??he,`${n.name_}.${o.toString()}`,!1)),n}return{get(){return(this[T]??s(this,t.get.call(this))).getObservablePropValue_(o)},set(e){return(this[T]??s(this,e)).setObservablePropValue_(o,e)},init(e){return s(this,e),e}}}function We(e,{annotationType_:t},r,i){`value`in i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' cannot be used on getter/setter properties`)}let Ge=Ke();function Ke(e){return{annotationType_:`true`,options_:e,make_:Ye,extend_:Xe}}let qe=[Ge];function Je(e){let t=e.deep!==!1,n=!!e.autoBind,r=!t|(n?2:0);return qe[r]??(qe[r]=Ke({deep:t,autoBind:n}))}function Ye(e,t,n,r){var i;if(n.get)return O.make_(e,t,n,r);if(n.set){let i=Bn(n.set)?n.set:St(t.toString(),n.set);return r===e.target_?e.defineProperty_(t,{configurable:A.safeDescriptors?e.isPlainObject_:!0,set:i})===null?0:2:(a(r,t,{configurable:!0,set:i}),2)}if(r!==e.target_&&typeof n.value==`function`){var o;if(_(n.value)){var s;return((s=this.options_)!=null&&s.autoBind?ur:lr).make_(e,t,n,r)}return((o=this.options_)!=null&&o.autoBind?Rn:In).make_(e,t,n,r)}let c=this.options_?.deep===!1?ut:D;return typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),c.make_(e,t,n,r)}function Xe(e,t,n,r){var i;return n.get?O.extend_(e,t,n,r):n.set?e.defineProperty_(t,{configurable:A.safeDescriptors?e.isPlainObject_:!0,set:St(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),(this.options_?.deep===!1?ut:D).extend_(e,t,n,r))}function Ze(e,t){return r(function(r,i){if(i&&typeof i.kind==`string`)return t(e,r,i);n(`Invalid arguments for \`${e.annotationType_}\``)},e)}let Qe={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Qe);function $e(e){return e||Qe}let et=Be(`observable`),tt=Be(`observable.ref`,{enhancer_:_e}),nt=Be(`observable.shallow`,{enhancer_:ge}),rt=Be(`observable.struct`,{enhancer_:ve});function it(e){return Ze(e,Ue)}function at(e){return e.deep===!0?he:e.deep===!1?_e:st(e.defaultDecorator)}function ot(e){return e?e.defaultDecorator??Je(e):void 0}function st(e){return e?e.options_?.enhancer_??he:he}function ct(e,t,n){return t&&typeof t.kind==`string`?Ue(et,e,t):Sr(e)?e:g(e)?D.object(e,t,n):Array.isArray(e)?D.array(e,t):ee(e)?D.map(e,t):S(e)?D.set(e,t):typeof e==`object`&&e?e:D.box(e,t)}let lt={box(e,t){let n=$e(t);return new kt(e,at(n),n.name,!0,n.equals)},array(e,t){let n=$e(t);return si(e,at(n),n.name)},map(e,t){let n=$e(t);return new _i(e,at(n),n.name)},set(e,t){let n=$e(t);return new Si(e,at(n),n.name)},object(e,t,n){return Ii(()=>Zn(Kr({},n),e,t))}},ut=it(tt),dt=it(nt),ft=it(et),pt=it(rt);var D=r(ct,et,lt);let mt=`computed`;function ht(e){return Ze(e,Re)}let gt=Fe(mt),_t=ht(Fe(`computed.struct`,{equals:fe})),O=function(e,t){if(t&&typeof t.kind==`string`)return Re(gt,e,t);if(g(e))return ht(Fe(mt,e));p(e)||n("First argument to `computed` should be an expression."),p(t)&&n("A setter as second argument is no longer supported, use `{ set: fn }` option instead");let r=g(t)?t:{};return r.get=e,r.name||=e.name||``,new jt(r)};r(O,gt);let vt=0,yt=1,bt=i(()=>{},`name`)?.configurable??!1,xt={value:`action`,configurable:!0,writable:!1,enumerable:!1};function St(e,t,r=!1,i){p(t)||n("`action` can only be invoked on functions"),(typeof e!=`string`||!e)&&n(`actions should have valid names, got: '${e}'`);function o(){return Ct(e,r,t,i||this,arguments)}return o.isMobxAction=!0,o.toString=()=>t.toString(),bt&&(xt.value=e,a(o,`name`,xt)),o}function Ct(e,t,n,r,i){let a=wt(e,t,r,i);try{return n.apply(r,i)}catch(e){throw a.error_=e,e}finally{Tt(a)}}function wt(e,t,n,r){let i=Sn()&&!!e,a=0;i&&(a=Date.now(),wn({type:j,name:e,object:n,arguments:r?Array.from(r):s}));let o=A.trackingDerivation,c=!t||!o;sn();let l=A.allowStateChanges;c&&(Wt(),l=Dt(!0));let u=A.allowStateReads;k(!0);let d={runAsAction_:c,prevDerivation_:o,prevAllowStateChanges_:l,prevAllowStateReads_:u,notifySpy_:i,startTime_:a,actionId_:yt++,parentActionId_:vt};return vt=d.actionId_,d}function Tt(e){vt!==e.actionId_&&n(30),vt=e.parentActionId_,e.error_!==void 0&&(A.suppressReactionErrors=!0),Ot(e.prevAllowStateChanges_),Kt(e.prevAllowStateReads_),cn(),e.runAsAction_&&Gt(e.prevDerivation_),e.notifySpy_&&En({time:Date.now()-e.startTime_}),A.suppressReactionErrors=!1}function Et(e,t){let n=Dt(e);try{return t()}finally{Ot(n)}}function Dt(e){let t=A.allowStateChanges;return A.allowStateChanges=e,t}function Ot(e){A.allowStateChanges=e}var kt=class extends ce{constructor(e,t,n=`ObservableValue@`+u(),r=!0,i=me){super(n),this.enhancer_=void 0,this.name_=void 0,this.equals_=void 0,this.hasUnreportedChange_=!1,this.interceptors_=void 0,this.changeListeners_=void 0,this.value_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,this.equals_=i,this.value_=t(e,void 0,n),r&&Sn()&&Cn({type:`create`,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:this.value_})}dehanceValue(e){return this.dehancer===void 0?e:this.dehancer(e)}set(e){let t=this.value_;if(e=this.prepareNewValue_(e),e!==A.UNCHANGED){let n=Sn();n&&wn({type:ii,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:e,oldValue:t}),this.setNewValue_(e),n&&En()}}prepareNewValue_(e){if(Lt(this),qr(this)){let t=Yr(this,{object:this,type:ii,newValue:e});if(!t)return A.UNCHANGED;e=t.newValue}return e=this.enhancer_(e,this.value_,this.name_),this.equals_(this.value_,e)?A.UNCHANGED:e}setNewValue_(e){let t=this.value_;this.value_=e,this.reportChanged(),Xr(this)&&Qr(this,{type:ii,object:this,newValue:e,oldValue:t})}get(){return this.reportObserved(),this.dehanceValue(this.value_)}raw(){return this.value_}toJSON(){return this.get()}toString(){return`${this.name_}[${this.value_}]`}valueOf(){return ie(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let At=b(`ObservableValue`,kt);var jt=class{constructor(e){this.dependenciesState_=-1,this.observing_=[],this.newObserving_=null,this.observers_=null,this.runId_=0,this.lastAccessedBy_=0,this.lowestObserverState_=0,this.unboundDepsCount_=0,this.value_=new Nt(null),this.name_=void 0,this.triggeredBy_=void 0,this.flags_=0,this.derivation=void 0,this.setter_=void 0,this.scope_=void 0,this.equals_=void 0,this.requiresReaction_=void 0,this.keepAlive_=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||n(31),this.derivation=e.get,this.name_=e.name||`ComputedValue@`+u(),e.set&&(this.setter_=St(this.name_+`-setter`,e.set)),this.equals_=e.equals||me,this.scope_=e.context,this.requiresReaction_=e.requiresReaction,this.keepAlive_=!!e.keepAlive}onBecomeStale_(){mn(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return w(this.flags_,1)}set isComputing(e){this.flags_=oe(this.flags_,1,e)}get isRunningSetter(){return w(this.flags_,2)}set isRunningSetter(e){this.flags_=oe(this.flags_,2,e)}get isBeingObserved(){return w(this.flags_,4)}set isBeingObserved(e){this.flags_=oe(this.flags_,4,e)}get isPendingUnobservation(){return w(this.flags_,8)}set isPendingUnobservation(e){this.flags_=oe(this.flags_,8,e)}get diffValue(){return+!!w(this.flags_,16)}set diffValue(e){this.flags_=oe(this.flags_,16,e===1)}get(){if(this.isComputing&&n(32,this.name_,this.derivation),A.inBatch===0&&(!this.observers_||this.observers_.size===0)&&!this.keepAlive_)Ft(this)&&(this.warnAboutUntrackedRead_(),sn(),this.value_=this.computeValue_(!1),cn());else{let e=this.isBeingObserved;if(dn(this),Ft(this)){let e=A.trackingContext;!e&&(this.keepAlive_||this.isBeingObserved)&&(A.trackingContext=this),this.trackAndCompute()&&pn(this),A.trackingContext=e}else !e&&this.isBeingObserved&&this.observing_.forEach(un)}let e=this.value_;if(Pt(e))throw e.cause;return e}set(e){if(this.setter_){this.isRunningSetter&&n(33,this.name_),this.isRunningSetter=!0;try{this.setter_.call(this.scope_,e)}finally{this.isRunningSetter=!1}}else n(34,this.name_)}trackAndCompute(){let e=this.value_,t=this.dependenciesState_===-1,n=this.computeValue_(!0),r=t||Pt(e)||Pt(n)||!this.equals_(e,n);return r&&(this.value_=n,Sn()&&Cn({observableKind:`computed`,debugObjectName:this.name_,object:this.scope_,type:`update`,oldValue:e,newValue:n})),r}computeValue_(e){this.isComputing=!0;let t=Dt(!1),n;if(e)n=zt(this,this.derivation,this.scope_);else if(A.disableErrorBoundaries===!0)n=this.derivation.call(this.scope_);else try{n=this.derivation.call(this.scope_)}catch(e){n=new Nt(e)}return Ot(t),this.isComputing=!1,n}suspend_(){this.keepAlive_||(Ht(this),this.value_=void 0)}warnAboutUntrackedRead_(){(typeof this.requiresReaction_==`boolean`?this.requiresReaction_:A.computedRequiresReaction)&&console.warn(`[mobx] Computed value '${this.name_}' is being read outside a reactive context. Doing a full recompute.`)}toString(){return`${this.name_}[${this.derivation.toString()}]`}valueOf(){return ie(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let Mt=b(`ComputedValue`,jt);var Nt=class{constructor(e){this.cause=void 0,this.cause=e}};function Pt(e){return e instanceof Nt}function Ft(e){switch(e.dependenciesState_){case 0:return!1;case-1:case 2:return!0;case 1:{let t=k(!0),n=Wt(),r=e.observing_,i=r.length;for(let a=0;a<i;a++){let i=r[a];if(Mt(i)){if(A.disableErrorBoundaries)i.get();else try{i.get()}catch{return Gt(n),Kt(t),!0}if(e.dependenciesState_===2)return Gt(n),Kt(t),!0}}return qt(e),Gt(n),Kt(t),!1}}}function It(){return A.trackingDerivation!==null}function Lt(e){let t=!!e.observers_&&e.observers_.size>0;!A.allowStateChanges&&(t||A.enforceActions===`always`)&&console.warn(`[MobX] `+(A.enforceActions?`Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: `:`Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: `)+e.name_)}function Rt(e){!A.allowStateReads&&A.observableRequiresReaction&&console.warn(`[mobx] Observable '${e.name_}' being read outside a reactive context.`)}function zt(e,t,n){let r=k(!0);qt(e),e.newObserving_=Array(e.runId_===0?100:e.observing_.length),e.unboundDepsCount_=0,e.runId_=++A.runId;let i=A.trackingDerivation;A.trackingDerivation=e,A.inBatch++;let a;if(A.disableErrorBoundaries===!0)a=t.call(n);else try{a=t.call(n)}catch(e){a=new Nt(e)}return A.inBatch--,A.trackingDerivation=i,Vt(e),Bt(e),Kt(r),a}function Bt(e){e.observing_.length===0&&(typeof e.requiresObservable_==`boolean`?e.requiresObservable_:A.reactionRequiresObservable)&&console.warn(`[mobx] Derivation '${e.name_}' is created/updated without reading any observable value.`)}function Vt(e){let t=e.observing_,n=e.observing_=e.newObserving_,r=0,i=0,a=e.unboundDepsCount_;for(let e=0;e<a;e++){let t=n[e];t.diffValue===0&&(t.diffValue=1,i!==e&&(n[i]=t),i++),t.dependenciesState_>r&&(r=t.dependenciesState_)}for(n.length=i,e.newObserving_=null,a=t.length;a--;){let n=t[a];n.diffValue===0&&an(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,rn(t,e))}r!==0&&(e.dependenciesState_=r,e.onBecomeStale_())}function Ht(e){let t=e.observing_;e.observing_=[];let n=t.length;for(;n--;)an(t[n],e);e.dependenciesState_=-1}function Ut(e){let t=Wt();try{return e()}finally{Gt(t)}}function Wt(){let e=A.trackingDerivation;return A.trackingDerivation=null,e}function Gt(e){A.trackingDerivation=e}function k(e){let t=A.allowStateReads;return A.allowStateReads=e,t}function Kt(e){A.allowStateReads=e}function qt(e){if(e.dependenciesState_===0)return;e.dependenciesState_=0;let t=e.observing_,n=t.length;for(;n--;)t[n].lowestObserverState_=0}let Jt=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Yt=class{constructor(){this.version=7,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.isRunningUnobservations=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.safeDescriptors=!0}};let Xt=!0,Zt=!1,A=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Xt=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(Xt=!1),Xt?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Yt):(setTimeout(()=>{Zt||n(35)},1),new Yt)}();function Qt(){if((A.pendingReactions.length||A.inBatch||A.isRunningReactions)&&n(36),Zt=!0,Xt){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),A=new Yt}}function $t(){return A}function en(){let e=new Yt;for(let t in e)Jt.indexOf(t)===-1&&(A[t]=e[t]);A.allowStateChanges=!A.enforceActions}function tn(e){return!!e.observers_&&e.observers_.size>0}function nn(e){return e.observers_??new Set}function rn(e,t){(e.observers_??=new Set).add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function an(e,t){let n=e.observers_;n&&(n.delete(t),n.size===0&&on(e))}function on(e){e.isPendingUnobservation===!1&&(e.isPendingUnobservation=!0,A.pendingUnobservations.push(e))}function sn(){A.inBatch++}function cn(){--A.inBatch===0&&(vn(),!A.isRunningUnobservations&&A.pendingUnobservations.length>0&&ln())}function ln(){A.isRunningUnobservations=!0;try{let e=A.pendingUnobservations;for(let t=0;t<e.length;t++){let n=e[t];n.isPendingUnobservation=!1,(!n.observers_||n.observers_.size===0)&&(n.observers_=null,n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof jt&&n.suspend_())}A.pendingUnobservations=[]}finally{A.isRunningUnobservations=!1}}function un(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.observing_)==null||t.forEach(un))}function dn(e){Rt(e);let t=A.trackingDerivation;return t===null?((!e.observers_||e.observers_.size===0)&&A.inBatch>0&&on(e),!1):(t.runId_!==e.lastAccessedBy_&&(e.lastAccessedBy_=t.runId_,t.newObserving_[t.unboundDepsCount_++]=e,!e.isBeingObserved&&A.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function fn(e){var t;e.lowestObserverState_!==2&&(e.lowestObserverState_=2,(t=e.observers_)==null||t.forEach(e=>{e.dependenciesState_===0&&e.onBecomeStale_(),e.dependenciesState_=2}))}function pn(e){var t;e.lowestObserverState_!==2&&(e.lowestObserverState_=2,(t=e.observers_)==null||t.forEach(t=>{t.dependenciesState_===1?t.dependenciesState_=2:t.dependenciesState_===0&&(e.lowestObserverState_=0)}))}function mn(e){var t;e.lowestObserverState_===0&&(e.lowestObserverState_=1,(t=e.observers_)==null||t.forEach(e=>{e.dependenciesState_===0&&(e.dependenciesState_=1,e.onBecomeStale_())}))}var hn=class{constructor(e=`Reaction@`+u(),t,n,r){this.name_=void 0,this.onInvalidate_=void 0,this.errorHandler_=void 0,this.requiresObservable_=void 0,this.observing_=[],this.newObserving_=[],this.dependenciesState_=-1,this.runId_=0,this.unboundDepsCount_=0,this.flags_=0,this.removeAbortListener_=void 0,this.name_=e,this.onInvalidate_=t,this.errorHandler_=n,this.requiresObservable_=r}get isDisposed(){return w(this.flags_,1)}set isDisposed(e){this.flags_=oe(this.flags_,1,e)}get isScheduled(){return w(this.flags_,2)}set isScheduled(e){this.flags_=oe(this.flags_,2,e)}get isTrackPending(){return w(this.flags_,4)}set isTrackPending(e){this.flags_=oe(this.flags_,4,e)}get isRunning(){return w(this.flags_,8)}set isRunning(e){this.flags_=oe(this.flags_,8,e)}get diffValue(){return+!!w(this.flags_,16)}set diffValue(e){this.flags_=oe(this.flags_,16,e===1)}onBecomeStale_(){this.schedule_()}schedule_(){this.isScheduled||(this.isScheduled=!0,A.pendingReactions.push(this),vn())}runReaction_(){if(!this.isDisposed){sn(),this.isScheduled=!1;let e=A.trackingContext;if(A.trackingContext=this,Ft(this)){this.isTrackPending=!0;try{this.onInvalidate_(),this.isTrackPending&&Sn()&&Cn({name:this.name_,type:`scheduled-reaction`})}catch(e){this.reportExceptionInDerivation_(e)}}A.trackingContext=e,cn()}}track(e){if(this.isDisposed)return;sn();let t=Sn(),n;t&&(n=Date.now(),wn({name:this.name_,type:`reaction`})),this.isRunning=!0;let r=A.trackingContext;A.trackingContext=this;let i=zt(this,e,void 0);A.trackingContext=r,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Ht(this),Pt(i)&&this.reportExceptionInDerivation_(i.cause),t&&En({time:Date.now()-n}),cn()}reportExceptionInDerivation_(e){if(this.errorHandler_){this.errorHandler_(e,this);return}if(A.disableErrorBoundaries)throw e;let t=`[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '${this}'`;A.suppressReactionErrors?console.warn(`[mobx] (error in reaction '${this.name_}' suppressed, fix error of causing action below)`):console.error(t,e),Sn()&&Cn({type:`error`,name:this.name_,message:t,error:``+e}),A.globalReactionErrorHandlers.forEach(t=>t(e,this))}dispose(){if(!this.isDisposed){var e;this.isDisposed=!0,(e=this.removeAbortListener_)==null||e.call(this),this.isRunning||(sn(),Ht(this),cn())}}getDisposer_(e){let t=()=>this.dispose();return e!=null&&e.addEventListener&&!this.isDisposed&&(e.addEventListener(`abort`,t),this.removeAbortListener_=()=>e.removeEventListener==null?void 0:e.removeEventListener(`abort`,t)),t[T]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.name_}]`}};function gn(e){return A.globalReactionErrorHandlers.push(e),()=>{let t=A.globalReactionErrorHandlers.indexOf(e);t>=0&&A.globalReactionErrorHandlers.splice(t,1)}}let _n=e=>e();function vn(){A.inBatch>0||A.isRunningReactions||_n(yn)}function yn(){A.isRunningReactions=!0;let e=A.pendingReactions,t=0;for(;e.length>0;){++t===100&&(console.error(`Reaction doesn't converge to a stable state after 100 iterations. Probably there is a cycle in the reactive function: ${e[0]}`),e.splice(0));let n=e.splice(0);for(let e=0,t=n.length;e<t;e++)n[e].runReaction_()}A.isRunningReactions=!1}let bn=b(`Reaction`,hn);function xn(e){let t=_n;_n=n=>e(()=>t(n))}function Sn(){return!!A.spyListeners.length}function Cn(e){if(!A.spyListeners.length)return;let t=A.spyListeners;for(let n=0,r=t.length;n<r;n++)t[n](e)}function wn(e){Cn(r({},e,{spyReportStart:!0}))}let Tn={type:`report-end`,spyReportEnd:!0};function En(e){Cn(e?r({},e,{type:`report-end`,spyReportEnd:!0}):Tn)}function Dn(e){return A.spyListeners.push(e),d(()=>{A.spyListeners=A.spyListeners.filter(t=>t!==e)})}let j=`action`,On=`autoAction`,kn=`<unnamed action>`,An=we(j),jn=we(`action.bound`,{bound:!0}),M=we(On,{autoAction:!0}),Mn=we(`autoAction.bound`,{autoAction:!0,bound:!0});function Nn(e){return Ze(e,De)}function Pn(e){return function(t,r){if(r&&typeof r.kind==`string`)return De(e?M:An,t,r);if(p(t))return St(t.name||kn,t,e);if(p(r))return St(t,r,e);if(m(t))return Nn(we(e?On:j,{name:t,autoAction:e}));n("Invalid arguments for `action`")}}let Fn=Pn(!1);r(Fn,An);let In=Pn(!0);r(In,M);let Ln=Nn(jn),Rn=Nn(Mn);function zn(e){return Ct(e.name||kn,!1,e,this,void 0)}function Bn(e){return p(e)&&e.isMobxAction===!0}function Vn(e,t=c){var r;p(e)||n(`Autorun expects a function as first argument`),Bn(e)&&n(`Autorun does not accept actions since actions are untrackable`);let i=t?.name??(e.name||`Autorun@`+u()),a=!t.scheduler&&!t.delay,o;if(a)o=new hn(i,function(){this.track(s)},t.onError,t.requiresObservable);else{let e=Un(t),n=!1;o=new hn(i,()=>{n||(n=!0,e(()=>{n=!1,o.isDisposed||o.track(s)}))},t.onError,t.requiresObservable)}function s(){e(o)}return t!=null&&(r=t.signal)!=null&&r.aborted||o.schedule_(),o.getDisposer_(t?.signal)}let Hn=e=>e();function Un(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Hn}function Wn(e,t,r=c){var i;(!p(e)||!p(t))&&n(`First and second argument to reaction should be functions`),g(r)||n(`Third argument of reactions should be an object`);let a=r.name??`Reaction@`+u(),o=Fn(a,r.onError?Gn(r.onError,t):t),s=!r.scheduler&&!r.delay,l=Un(r),d=!0,f=!1,m,h=r.equals||me,_=new hn(a,()=>{d||s?v():f||(f=!0,l(v))},r.onError,r.requiresObservable);function v(){if(f=!1,_.isDisposed)return;let t=!1,n=m;_.track(()=>{let n=Et(!1,()=>e(_));t=d||!h(m,n),m=n}),(d&&r.fireImmediately||!d&&t)&&o(m,n,_),d=!1}return r!=null&&(i=r.signal)!=null&&i.aborted||_.schedule_(),_.getDisposer_(r?.signal)}function Gn(e,t){return function(){try{return t.apply(this,arguments)}catch(t){e.call(this,t)}}}function Kn(e,t,n){return Jn(`onBO`,e,t,n)}function qn(e,t,n){return Jn(`onBUO`,e,t,n)}function Jn(e,t,n,r){let i=typeof r==`function`?Ni(t,n):Ni(t),a=p(r)?r:n,o=`${e}L`;return i[o]?i[o].add(a):i[o]=new Set([a]),function(){let e=i[o];e&&(e.delete(a),e.size===0&&delete i[o])}}let Yn=`always`;function Xn(e){e.isolateGlobalState===!0&&Qt();let{enforceActions:t}=e;if(t!==void 0){let e=t===Yn?Yn:t===`observed`;A.enforceActions=e,A.allowStateChanges=!(e===!0||e===Yn)}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(A[t]=!!e[t])}),A.allowStateReads=!A.observableRequiresReaction,A.disableErrorBoundaries===!0&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),e.reactionScheduler&&xn(e.reactionScheduler)}function Zn(e,t,r,i){arguments.length>4&&n(`'extendObservable' expected 2-4 arguments`),typeof e!=`object`&&n(`'extendObservable' expects an object as first argument`),vi(e)&&n(`'extendObservable' should not be used on maps, use map.merge instead`),g(t)||n(`'extendObservable' only accepts plain objects as second argument`),(Sr(t)||Sr(r))&&n(`Extending an object with another observable (object) is not supported`);let a=C(t);return Ii(()=>{let t=Oi(e,i)[T];ne(a).forEach(e=>{t.extend_(e,a[e],r&&e in r?r[e]:!0)})}),e}function Qn(e,t){return $n(Ni(e,t))}function $n(e){let t={name:e.name_};return e.observing_&&e.observing_.length>0&&(t.dependencies=nr(e.observing_).map($n)),t}function er(e,t){return tr(Ni(e,t))}function tr(e){let t={name:e.name_};return tn(e)&&(t.observers=Array.from(nn(e),tr)),t}function nr(e){return Array.from(new Set(e))}let rr=0;var ir=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};function ar(e){return e instanceof ir}function or(e){return Ze(e,Me)}let sr=Ae(`flow`),cr=Ae(`flow.bound`,{bound:!0}),lr=r(function(e,t){if(t&&typeof t.kind==`string`)return Me(sr,e,t);arguments.length!==1&&n(`Flow expects single argument with generator function`);let r=e,i=r.name||`<unnamed flow>`,a=function(){let e=this,t=arguments,n=++rr,a=Fn(`${i} - runid: ${n} - init`,r).apply(e,t),o,s,c=new Promise(function(e,t){let r=0;o=t;function c(e){s=void 0;let o;try{o=Fn(`${i} - runid: ${n} - yield ${r++}`,a.next).call(a,e)}catch(e){return t(e)}u(o)}function l(e){s=void 0;let o;try{o=Fn(`${i} - runid: ${n} - yield ${r++}`,a.throw).call(a,e)}catch(e){return t(e)}u(o)}function u(n){if(p(n?.then)){n.then(u,t);return}return n.done?e(n.value):(s=Promise.resolve(n.value),s.then(c,l))}c(void 0)});return c.cancel=Fn(`${i} - runid: ${n} - cancel`,function(){try{s&&dr(s);let e=a.return(void 0),t=Promise.resolve(e.value);t.then(f,f),dr(t),o(new ir)}catch(e){o(e)}}),c};return a.isMobXFlow=!0,a},sr),ur=or(cr);function dr(e){p(e.cancel)&&e.cancel()}function fr(e){return e}function pr(e){return e?.isMobXFlow===!0}function mr(e,t,r){let i;if(vi(e)||mi(e)||At(e))i=Pi(e);else if(N(e)){if(!m(t))return n(`InterceptReads can only be used with a specific property, not with an object in general`);i=Pi(e,t)}else return n(`Expected observable map, object or array as first array`);return i.dehancer===void 0?(i.dehancer=typeof t==`function`?t:r,()=>{i.dehancer=void 0}):n(`An intercept reader was already established`)}function hr(e,t,n){return p(n)?_r(e,t,n):gr(e,t)}function gr(e,t){return Jr(Pi(e),t)}function _r(e,t,n){return Jr(Pi(e,t),n)}function vr(e,t){var n;if(t===void 0)return Mt(e);if(N(e)===!1)return!1;let r=e[T];return(n=r.lazyComputedKeys_)!=null&&n.has(t)?!0:r.values_.has(t)?Mt(Ni(e,t)):!1}function yr(e){return arguments.length>1?n(`isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property`):vr(e)}function br(e,t){return m(t)?vr(e,t):n(`isComputed expected a property name as second argument`)}function xr(e,t){if(!e)return!1;if(t!==void 0){if(vi(e)||mi(e))return n(`isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.`);if(N(e)){var r,i;let n=e[T];return n.values_.has(t)||!!((r=n.lazyComputedKeys_)!=null&&r.has(t))||!!((i=n.lazyObservableKeys_)!=null&&i.has(t))}return!1}return N(e)||!!e[T]||le(e)||bn(e)||Mt(e)}function Sr(e){return arguments.length!==1&&n(`isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property`),xr(e)}function Cr(e,t){return m(t)?xr(e,t):n(`expected a property name as second argument`)}function wr(e){if(N(e))return e[T].keys_();if(vi(e)||Ci(e))return Array.from(e.keys());if(mi(e))return e.map((e,t)=>t);n(5)}function Tr(e){if(N(e))return wr(e).map(t=>e[t]);if(vi(e))return wr(e).map(t=>e.get(t));if(Ci(e))return Array.from(e.values());if(mi(e))return e.slice();n(6)}function Er(e){if(N(e))return wr(e).map(t=>[t,e[t]]);if(vi(e))return wr(e).map(t=>[t,e.get(t)]);if(Ci(e))return Array.from(e.entries());if(mi(e))return e.map((e,t)=>[t,e]);n(7)}function Dr(e,t,r){if(arguments.length===2&&!Ci(e)){sn();let n=t;try{for(let t in n)Dr(e,t,n[t])}finally{cn()}return}N(e)?e[T].set_(t,r):vi(e)?e.set(t,r):Ci(e)?e.add(t):mi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),t<0&&n(42,t),sn(),t>=e.length&&(e.length=t+1),e[t]=r,cn()):n(8)}function Or(e,t){N(e)?e[T].delete_(t):vi(e)||Ci(e)?e.delete(t):mi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),e.splice(t,1)):n(9)}function kr(e,t){if(N(e))return e[T].has_(t);if(vi(e)||Ci(e))return e.has(t);if(mi(e))return t>=0&&t<e.length;n(10)}function Ar(e,t){if(kr(e,t)){if(N(e))return e[T].get_(t);if(vi(e))return e.get(t);if(mi(e))return e[t];n(11)}}function jr(e,t,r){if(N(e))return e[T].defineProperty_(t,r);n(39)}function Mr(e){if(N(e))return e[T].ownKeys_();n(38)}function Nr(e,t,n,r){return p(n)?Fr(e,t,n,r):Pr(e,t,n)}function Pr(e,t,r){let i=Pi(e);if(mi(e))r&&t({observableKind:`array`,object:i.proxy_,debugObjectName:i.atom_.name_,type:`splice`,index:0,added:i.values_.slice(),addedCount:i.values_.length,removed:[],removedCount:0});else if(vi(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with maps.");else if(Ci(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with sets.");else if(N(e))r===!0&&n("`observe` doesn't support the fire immediately property for observable objects.");else return Ir(i,t,r);return Zr(i,t)}function Fr(e,t,n,r){return Ir(Pi(e,t),n,r)}function Ir(e,t,n){if(Mt(e)){let r=!0,i;return Vn(()=>{let a=e.get();if(!r||n){let n=Wt();t({observableKind:`computed`,debugObjectName:e.name_,type:ii,object:e,newValue:a,oldValue:i}),Gt(n)}r=!1,i=a})}return n&&t({observableKind:`value`,debugObjectName:e.name_,object:e,type:ii,newValue:e.value_,oldValue:void 0}),Zr(e,t)}function Lr(e,t,n){return e.set(t,n),n}function Rr(e,t){if(typeof e!=`object`||!e||e instanceof Date||!Sr(e))return e;if(At(e)||Mt(e))return Rr(e.get(),t);if(t.has(e))return t.get(e);if(mi(e)){let n=Lr(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=Rr(e,t)}),n}if(Ci(e)){let n=Lr(t,e,new Set);return e.forEach(e=>{n.add(Rr(e,t))}),n}if(vi(e)){let n=Lr(t,e,new Map);return e.forEach((e,r)=>{n.set(r,Rr(e,t))}),n}else{let n=Lr(t,e,{});return Mr(e).forEach(r=>{o.propertyIsEnumerable.call(e,r)&&(n[r]=Rr(e[r],t))}),n}}function zr(e,t){return t&&n(`toJS no longer supports options`),Rr(e,new Map)}function Br(e,t=void 0){sn();try{return e.apply(t)}finally{cn()}}function Vr(e,t,n){return arguments.length===1||t&&typeof t==`object`?Ur(e,t):Hr(e,t,n||{})}function Hr(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[T].isDisposed)if(a(),n.onError)n.onError(e);else throw e},n.timeout)}n.name=n.name||`When@`+u();let i=St(n.name+`-effect`,t);var a=Vn(t=>{Et(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function Ur(e,t){var i;if(t&&t.onError)return n(`the options 'onError' and 'promise' cannot be combined`);if(t!=null&&(i=t.signal)!=null&&i.aborted)return r(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let a,o,s=new Promise((n,i)=>{var s;let c=Hr(e,n,r({},t,{onError:i}));a=()=>{c(),i(Error(`WHEN_CANCELLED`))},o=()=>{c(),i(Error(`WHEN_ABORTED`))},t==null||(s=t.signal)==null||s.addEventListener==null||s.addEventListener(`abort`,o)}).finally(()=>{var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,o)});return s.cancel=a,s}function Wr(e){return e[T]}let Gr={has(e,t){return Wr(e).has_(t)},get(e,t){return Wr(e).get_(t)},set(e,t,n){return m(t)?Wr(e).set_(t,n,!0)??!0:!1},deleteProperty(e,t){return m(t)?Wr(e).delete_(t,!0)??!0:!1},defineProperty(e,t,n){return Wr(e).defineProperty_(t,n)??!0},ownKeys(e){return Wr(e).ownKeys_()},preventExtensions(e){n(13)}};function Kr(e,t){var n;return e=Oi(e,t),(n=e[T]).proxy_??(n.proxy_=new Proxy(e,Gr))}function qr(e){return e.interceptors_!==void 0&&e.interceptors_.length>0}function Jr(e,t){let n=e.interceptors_;return n?n.push(t):n=e.interceptors_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Yr(e,t){let r=Wt();try{let r=[...e.interceptors_||[]];for(let e=0,i=r.length;e<i&&(t=r[e](t),t&&!t.type&&n(14),t);e++);return t}finally{Gt(r)}}function Xr(e){return e.changeListeners_!==void 0&&e.changeListeners_.length>0}function Zr(e,t){let n=e.changeListeners_;return n?n.push(t):n=e.changeListeners_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Qr(e,t){let n=Wt(),r=e.changeListeners_;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Gt(n)}}function $r(e,t,n){return Ii(()=>{let r=Oi(e,n)[T];ne(t).forEach(e=>ni(r,e,t[e]))}),e}let ei=Symbol(`mobx-keys`);function ti(e,t,r){return!g(e)&&!g(Object.getPrototypeOf(e))&&n(`'makeAutoObservable' can only be used for classes that don't have a superclass`),N(e)&&n(`makeAutoObservable can only be used on objects not already made observable`),g(e)?Zn(e,e,t,r):(Ii(()=>{let n=Oi(e,r)[T];if(!e[ei]){let t=Object.getPrototypeOf(e),n=new Set([...ne(e),...ne(t)]);n.delete(`constructor`),n.delete(T),v(t,ei,n)}e[ei].forEach(e=>ni(n,e,t&&e in t?t[e]:!0))}),e)}function ni(e,t,r){if(r===!0&&(r=e.defaultAnnotation_),r===!1)return;Mi(e,r,t),t in e.target_||n(1,r.annotationType_,`${e.name_}.${t.toString()}`);let a=e.target_;for(;a&&a!==o;){let n=i(a,t);if(n){let i=r.make_(e,t,n,a);if(i===0)return;if(i===1)break}a=Object.getPrototypeOf(a)}ji(e,r,t)}let ri=`splice`,ii=`update`,ai={get(e,t){let n=e[T];return t===T?n:t===`length`?n.getArrayLength_():typeof t==`string`&&!isNaN(t)?n.get_(parseInt(t)):ae(ci,t)?ci[t]:e[t]},set(e,t,n){let r=e[T];return t===`length`?r.setArrayLength_(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.set_(parseInt(t),n),!0},preventExtensions(){n(15)}};var oi=class{constructor(e=`ObservableArray@`+u(),t,n){this.owned_=void 0,this.atom_=void 0,this.values_=[],this.interceptors_=void 0,this.changeListeners_=void 0,this.enhancer_=void 0,this.dehancer=void 0,this.proxy_=void 0,this.lastKnownLength_=0,this.owned_=n,this.atom_=new ce(e),this.enhancer_=(n,r)=>t(n,r,e+`[..]`)}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}dehanceValues_(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e}getArrayLength_(){return this.atom_.reportObserved(),this.values_.length}setArrayLength_(e){(!Number.isInteger(e)||e<0)&&n(40,e);let t=this.values_.length;if(e!==t)if(e>t){let n=Array.from({length:e-t});this.spliceWithArray_(t,0,n)}else this.spliceWithArray_(e,t-e)}updateArrayLength_(e,t){e!==this.lastKnownLength_&&n(16),this.lastKnownLength_+=t}spliceWithArray_(e,t,n){Lt(this.atom_);let r=this.values_.length;if(e===void 0?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=arguments.length===1?r-e:t==null?0:Math.max(0,Math.min(t,r-e)),n===void 0&&(n=s),qr(this)){let r=Yr(this,{object:this.proxy_,type:ri,index:e,removedCount:t,added:n});if(!r)return s;t=r.removedCount,n=r.added}n=n.length===0?n:n.map(e=>this.enhancer_(e,void 0));{let e=n.length-t;this.updateArrayLength_(r,e)}let i=this.spliceItemsIntoValues_(e,t,n);return(t!==0||n.length!==0)&&this.notifyArraySplice_(e,n,i),this.dehanceValues_(i)}spliceItemsIntoValues_(e,t,n){if(n.length<1e4)return this.values_.splice(e,t,...n);{let r=this.values_.slice(e,e+t),i=this.values_.slice(e+t);this.values_.length+=n.length-t;for(let t=0;t<n.length;t++)this.values_[e+t]=n[t];for(let t=0;t<i.length;t++)this.values_[e+n.length+t]=i[t];return r}}notifyArrayChildUpdate_(e,t,n){let r=!this.owned_&&Sn(),i=Xr(this),a=i||r?{observableKind:`array`,object:this.proxy_,type:ii,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&wn(a),this.atom_.reportChanged(),i&&Qr(this,a),r&&En()}notifyArraySplice_(e,t,n){let r=!this.owned_&&Sn(),i=Xr(this),a=i||r?{observableKind:`array`,object:this.proxy_,debugObjectName:this.atom_.name_,type:ri,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&wn(a),this.atom_.reportChanged(),i&&Qr(this,a),r&&En()}get_(e){return this.atom_.reportObserved(),this.dehanceValue_(this.values_[e])}set_(e,t){let n=this.values_;if(e<n.length){Lt(this.atom_);let r=n[e];if(qr(this)){let n=Yr(this,{type:ii,object:this.proxy_,index:e,newValue:t});if(!n)return;t=n.newValue}t=this.enhancer_(t,r),t!==r&&(n[e]=t,this.notifyArrayChildUpdate_(e,t,r))}else{let r=Array.from({length:e+1-n.length});r[r.length-1]=t,this.spliceWithArray_(n.length,0,r)}}};function si(e,t,n=`ObservableArray@`+u(),r=!1){return Ii(()=>{let i=new oi(n,t,r);y(i.values_,T,i);let a=new Proxy(i.values_,ai);return i.proxy_=a,e&&e.length&&i.spliceWithArray_(0,0,e),a})}var ci={clear(){return this.splice(0)},replace(e){let t=this[T];return t.spliceWithArray_(0,t.values_.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[T];switch(arguments.length){case 0:return[];case 1:return r.spliceWithArray_(e);case 2:return r.spliceWithArray_(e,t)}return r.spliceWithArray_(e,t,n)},spliceWithArray(e,t,n){return this[T].spliceWithArray_(e,t,n)},push(...e){let t=this[T];return t.spliceWithArray_(t.values_.length,0,e),t.values_.length},pop(){return this.splice(Math.max(this[T].values_.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[T];return t.spliceWithArray_(0,0,e),t.values_.length},reverse(){return A.trackingDerivation&&n(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){A.trackingDerivation&&n(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[T],n=t.dehanceValues_(t.values_).indexOf(e);return n>-1?(this.splice(n,1),!0):!1}};li(`at`,ui),li(`concat`,ui),li(`flat`,ui),li(`includes`,ui),li(`indexOf`,ui),li(`join`,ui),li(`lastIndexOf`,ui),li(`slice`,ui),li(`toString`,ui),li(`toLocaleString`,ui),li(`toSorted`,ui),li(`toSpliced`,ui),li(`with`,ui),li(`every`,di),li(`filter`,di),li(`find`,di),li(`findIndex`,di),li(`findLast`,di),li(`findLastIndex`,di),li(`flatMap`,di),li(`forEach`,di),li(`map`,di),li(`some`,di),li(`toReversed`,di),li(`reduce`,fi),li(`reduceRight`,fi);function li(e,t){typeof Array.prototype[e]==`function`&&(ci[e]=t(e))}function ui(e){return function(){let t=this[T];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_);return n[e].apply(n,arguments)}}function di(e){return function(t,n){let r=this[T];return r.atom_.reportObserved(),r.dehanceValues_(r.values_)[e]((e,r)=>t.call(n,e,r,this))}}function fi(e){return function(){let t=this[T];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_),r=arguments[0];return arguments[0]=(e,t,n)=>r(e,t,n,this),n[e].apply(n,arguments)}}let pi=b(`ObservableArrayAdministration`,oi);function mi(e){return h(e)&&pi(e[T])}let hi={},gi=`delete`;var _i=class{constructor(e,t=he,n=`ObservableMap@`+u()){this.enhancer_=void 0,this.name_=void 0,this[T]=hi,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,Ii(()=>{this.keysAtom_=ue(`${this.name_}.keys()`),this.data_=new Map,this.hasMap_=new Map,e&&this.merge(e)})}has_(e){return this.data_.has(e)}has(e){if(!A.trackingDerivation)return this.has_(e);let t=this.hasMap_.get(e);if(!t){let n=t=new kt(this.has_(e),_e,`${this.name_}.${re(e)}?`,!1);this.hasMap_.set(e,n),n.onBUOL=new Set([()=>this.hasMap_.delete(e)])}return t.get()}set(e,t){let n=this.has_(e);if(qr(this)){let r=Yr(this,{type:n?ii:`add`,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.updateValue_(e,t):this.addValue_(e,t),this}delete(e){if(Lt(this.keysAtom_),qr(this)&&!Yr(this,{type:gi,object:this,name:e}))return!1;if(this.has_(e)){let t=Sn(),n=Xr(this),r=n||t?{observableKind:`map`,debugObjectName:this.name_,type:gi,object:this,oldValue:this.data_.get(e).value_,name:e}:null;return t&&wn(r),Br(()=>{var t;this.keysAtom_.reportChanged(),(t=this.hasMap_.get(e))==null||t.setNewValue_(!1),this.data_.get(e).setNewValue_(void 0),this.data_.delete(e)}),n&&Qr(this,r),t&&En(),!0}return!1}updateValue_(e,t){let n=this.data_.get(e);if(t=n.prepareNewValue_(t),t!==A.UNCHANGED){let r=Sn(),i=Xr(this),a=i||r?{observableKind:`map`,debugObjectName:this.name_,type:ii,object:this,oldValue:n.value_,name:e,newValue:t}:null;r&&wn(a),n.setNewValue_(t),i&&Qr(this,a),r&&En()}}addValue_(e,t){Lt(this.keysAtom_),Br(()=>{var n;let r=new kt(t,this.enhancer_,`${this.name_}.${re(e)}`,!1);this.data_.set(e,r),t=r.value_,(n=this.hasMap_.get(e))==null||n.setNewValue_(!0),this.keysAtom_.reportChanged()});let n=Sn(),r=Xr(this),i=r||n?{observableKind:`map`,debugObjectName:this.name_,type:`add`,object:this,name:e,newValue:t}:null;n&&wn(i),r&&Qr(this,i),n&&En()}get(e){return this.has(e)?this.dehanceValue_(this.data_.get(e).get()):this.dehanceValue_(void 0)}getOrInsert(e,t){return this.has(e)||this.set(e,t),this.get(e)}getOrInsertComputed(e,t){return this.has(e)||this.set(e,t(e)),this.get(e)}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}keys(){return this.keysAtom_.reportObserved(),this.data_.keys()}values(){let e=this,t=this.keys();return yi({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:e.get(r)}}})}entries(){let e=this,t=this.keys();return yi({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:[r,e.get(r)]}}})}[Symbol.iterator](){return this.entries()}forEach(e,t){for(let[n,r]of this)e.call(t,r,n,this)}merge(e){return vi(e)&&(e=new Map(e)),Br(()=>{g(e)?te(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):ee(e)?(x(e)||n(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&n(20,e)}),this}clear(){Br(()=>{Ut(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return Br(()=>{let t=bi(e),n=new Map,r=!1;for(let e of this.data_.keys())if(!t.has(e))if(this.delete(e))r=!0;else{let t=this.data_.get(e);n.set(e,t)}for(let[e,i]of t.entries()){let t=this.data_.has(e);if(this.set(e,i),this.data_.has(e)){let i=this.data_.get(e);n.set(e,i),t||(r=!0)}}if(!r)if(this.data_.size!==n.size)this.keysAtom_.reportChanged();else{let e=this.data_.keys(),t=n.keys(),r=e.next(),i=t.next();for(;!r.done;){if(r.value!==i.value){this.keysAtom_.reportChanged();break}r=e.next(),i=t.next()}}this.data_=n}),this}get size(){return this.keysAtom_.reportObserved(),this.data_.size}toString(){return`[object ObservableMap]`}toJSON(){return Array.from(this)}get[Symbol.toStringTag](){return`Map`}},vi=b(`ObservableMap`,_i);function yi(e){return e[Symbol.toStringTag]=`MapIterator`,Hi(e)}function bi(e){if(ee(e)||vi(e))return e;if(Array.isArray(e))return new Map(e);if(g(e)){let t=new Map;for(let n in e)t.set(n,e[n]);return t}else return n(21,e)}let xi={};var Si=class{constructor(e,t=he,n=`ObservableSet@`+u()){this.name_=void 0,this[T]=xi,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,this.enhancer_=(e,r)=>t(e,r,n),Ii(()=>{this.atom_=ue(this.name_),e&&this.replace(e)})}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){Br(()=>{Ut(()=>{for(let e of this.data_.values())this.delete(e)})})}forEach(e,t){for(let n of this)e.call(t,n,n,this)}get size(){return this.atom_.reportObserved(),this.data_.size}add(e){if(Lt(this.atom_),qr(this)){let t=Yr(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){Br(()=>{e=this.enhancer_(e,void 0),this.data_.add(e),this.atom_.reportChanged()});let t=Sn(),n=Xr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:`add`,object:this,newValue:e}:null;t&&wn(r),n&&Qr(this,r),t&&En()}return this}delete(e){if(qr(this)&&!Yr(this,{type:gi,object:this,oldValue:e}))return!1;if(this.has(e)){let t=Sn(),n=Xr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:gi,object:this,oldValue:e}:null;return t&&wn(r),Br(()=>{this.atom_.reportChanged(),this.data_.delete(e)}),n&&Qr(this,r),t&&En(),!0}return!1}has(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))}entries(){let e=this.values();return wi({next(){let{value:t,done:n}=e.next();return n?{value:void 0,done:n}:{value:[t,t],done:n}}})}keys(){return this.values()}values(){this.atom_.reportObserved();let e=this,t=this.data_.values();return wi({next(){let{value:n,done:r}=t.next();return r?{value:void 0,done:r}:{value:e.dehanceValue_(n),done:r}}})}intersection(e){return new Set(this).intersection(e)}union(e){return new Set(this).union(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}replace(e){return Ci(e)&&(e=new Set(e)),Array.isArray(e)||S(e)?Br(()=>{let t=S(e)?e:new Set(e);if(t.size===0){this.clear();return}if(this.data_.size===0){t.forEach(e=>this.add(e));return}for(let e of this.data_.values())t.has(this.dehanceValue_(e))||this.delete(e);t.forEach(e=>this.add(e))}):e!=null&&n(41,e),this}toJSON(){return Array.from(this)}toString(){return`[object ObservableSet]`}[Symbol.iterator](){return this.values()}get[Symbol.toStringTag](){return`Set`}},Ci=b(`ObservableSet`,Si);function wi(e){return e[Symbol.toStringTag]=`SetIterator`,Hi(e)}let Ti=Object.create(null),Ei=`remove`;var Di=class{constructor(e,t=new Map,r,i=Ge){this.target_=void 0,this.values_=void 0,this.name_=void 0,this.defaultAnnotation_=void 0,this.keysAtom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.proxy_=void 0,this.isPlainObject_=void 0,this.appliedAnnotations_=void 0,this.pendingKeys_=void 0,this.lazyComputedKeys_=void 0,this.lazyObservableKeys_=void 0,this.target_=e,this.values_=t,this.name_=r,this.defaultAnnotation_=i,this.keysAtom_=new ce(`${this.name_}.keys`),this.isPlainObject_=g(this.target_),Wi(this.defaultAnnotation_)||n(`defaultAnnotation must be valid annotation`),this.appliedAnnotations_={}}getObservablePropValue_(e){return(this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e)).get()}materializeLazyComputed_(e){let t=this.lazyComputedKeys_?.get(e);if(!t)return;this.lazyComputedKeys_.delete(e),this.lazyComputedKeys_.size===0&&(this.lazyComputedKeys_=void 0);let n=t();return this.values_.set(e,n),n}materializeLazyObservable_(e){let t=this.lazyObservableKeys_?.get(e);if(!t)return;this.lazyObservableKeys_.delete(e),this.lazyObservableKeys_.size===0&&(this.lazyObservableKeys_=void 0);let n=t();return this.values_.set(e,n),n}setObservablePropValue_(e,t){let n=this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e);if(n instanceof jt)return n.set(t),!0;if(qr(this)){let n=Yr(this,{type:ii,object:this.proxy_||this.target_,name:e,newValue:t});if(!n)return null;t=n.newValue}if(t=n.prepareNewValue_(t),t!==A.UNCHANGED){let r=Xr(this),i=Sn(),a=r||i?{type:ii,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,oldValue:n.value_,name:e,newValue:t}:null;i&&wn(a),n.setNewValue_(t),r&&Qr(this,a),i&&En()}return!0}get_(e){return A.trackingDerivation&&!ae(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return ae(this.target_,e)?this.values_.has(e)?this.setObservablePropValue_(e,t):n?Reflect.set(this.target_,e,t):(this.target_[e]=t,!0):this.extend_(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.defaultAnnotation_,n)}has_(e){if(!A.trackingDerivation)return e in this.target_;this.pendingKeys_||=new Map;let t=this.pendingKeys_.get(e);return t||(t=new kt(e in this.target_,_e,`${this.name_}.${re(e)}?`,!1),this.pendingKeys_.set(e,t)),t.get()}extend_(e,t,n,r=!1){if(n===!0&&(n=this.defaultAnnotation_),n===!1)return this.defineProperty_(e,t,r);Mi(this,n,e);let i=n.extend_(this,e,t,r);return i&&ji(this,n,e),i}defineProperty_(e,t,n=!1){Lt(this.keysAtom_);try{sn();let i=this.delete_(e);if(!i)return i;if(qr(this)){let n=Yr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t.value});if(!n)return null;let{newValue:i}=n;t.value!==i&&(t=r({},t,{value:i}))}if(n){if(!Reflect.defineProperty(this.target_,e,t))return!1}else a(this.target_,e,t);this.notifyPropertyAddition_(e,t.value)}finally{cn()}return!0}defineObservableProperty_(e,t,n,r=!1){Lt(this.keysAtom_);try{sn();let i=this.delete_(e);if(!i)return i;if(qr(this)){let n=Yr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let o=Ai(e),s={configurable:A.safeDescriptors?this.isPlainObject_:!0,enumerable:!0,get:o.get,set:o.set};if(r){if(!Reflect.defineProperty(this.target_,e,s))return!1}else a(this.target_,e,s);let c=new kt(t,n,`${this.name_}.${e.toString()}`,!1);this.values_.set(e,c),this.notifyPropertyAddition_(e,c.value_)}finally{cn()}return!0}defineComputedProperty_(e,t,n=!1){Lt(this.keysAtom_);try{sn();let r=this.delete_(e);if(!r)return r;if(qr(this)&&!Yr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:void 0}))return null;t.name||=`${this.name_}.${e.toString()}`,t.context=this.proxy_||this.target_;let i=Ai(e),o={configurable:A.safeDescriptors?this.isPlainObject_:!0,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.target_,e,o))return!1}else a(this.target_,e,o);this.values_.set(e,new jt(t)),this.notifyPropertyAddition_(e,void 0)}finally{cn()}return!0}delete_(e,t=!1){if(Lt(this.keysAtom_),!ae(this.target_,e))return!0;if(qr(this)&&!Yr(this,{object:this.proxy_||this.target_,name:e,type:Ei}))return null;try{var n;sn();let r=Xr(this),a=Sn(),o=this.values_.get(e),s;if(!o&&(r||a)&&(s=i(this.target_,e)?.value),t){if(!Reflect.deleteProperty(this.target_,e))return!1}else delete this.target_[e];if(delete this.appliedAnnotations_[e],o&&(this.values_.delete(e),o instanceof kt&&(s=o.value_),fn(o)),this.keysAtom_.reportChanged(),(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(e in this.target_),r||a){let t={type:Ei,observableKind:`object`,object:this.proxy_||this.target_,debugObjectName:this.name_,oldValue:s,name:e};a&&wn(t),r&&Qr(this,t),a&&En()}}finally{cn()}return!0}notifyPropertyAddition_(e,t){var n;let r=Xr(this),i=Sn();if(r||i){let n=r||i?{type:`add`,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,name:e,newValue:t}:null;i&&wn(n),r&&Qr(this,n),i&&En()}(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(!0),this.keysAtom_.reportChanged()}ownKeys_(){return this.keysAtom_.reportObserved(),ne(this.target_)}keys_(){return this.keysAtom_.reportObserved(),Object.keys(this.target_)}};function Oi(e,t){if(t&&N(e)&&n(`Options can't be provided for already observable objects.`),ae(e,T))return Pi(e)instanceof Di||n(`Cannot convert '${Fi(e)}' into observable object:\nThe target is already observable of different type.\nExtending builtins is not supported.`),e;Object.isExtensible(e)||n(`Cannot make the designated object observable; it is not extensible`);let r=t?.name??`${g(e)?`ObservableObject`:e.constructor.name}@${u()}`;return v(e,T,new Di(e,new Map,String(r),ot(t))),e}let ki=b(`ObservableObjectAdministration`,Di);function Ai(e){return Ti[e]||(Ti[e]={get(){return this[T].getObservablePropValue_(e)},set(t){return this[T].setObservablePropValue_(e,t)}})}function N(e){return h(e)?ki(e[T]):!1}function ji(e,t,n){e.appliedAnnotations_[n]=t}function Mi(e,t,r){if(Wi(t)||n(`Cannot annotate '${e.name_}.${r.toString()}': Invalid annotation.`),!xe(t)&&ae(e.appliedAnnotations_,r)){let i=`${e.name_}.${r.toString()}`,a=e.appliedAnnotations_[r].annotationType_,o=t.annotationType_;n(`Cannot apply '${o}' to '${i}':\nThe field is already annotated with '${a}'.\nRe-annotating fields is not allowed.\nUse 'override' annotation for methods overridden by subclass.`)}}function Ni(e,t){if(typeof e==`object`&&e){if(mi(e))return t!==void 0&&n(23),e[T].atom_;if(Ci(e))return e.atom_;if(vi(e)){if(t===void 0)return e.keysAtom_;let r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,Fi(e)),r}if(N(e)){if(!t)return n(26);let r=e[T],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,Fi(e)),i}if(le(e)||Mt(e)||bn(e))return e}else if(p(e)&&bn(e[T]))return e[T];n(28)}function Pi(e,t){if(e||n(29),t!==void 0)return Pi(Ni(e,t));if(le(e)||Mt(e)||bn(e)||vi(e)||Ci(e))return e;if(e[T])return e[T];n(24,e)}function Fi(e,t){let n;if(t!==void 0)n=Ni(e,t);else if(Bn(e))return e.name;else n=N(e)||vi(e)||Ci(e)?Pi(e):Ni(e);return n.name_}function Ii(e){let t=Wt(),n=Dt(!0);sn();try{return e()}finally{cn(),Ot(n),Gt(t)}}let Li=o.toString;function Ri(e,t,n=-1){return zi(e,t,n)}function zi(e,t,n,r,i){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!==e)return t!==t;let a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;let o=Li.call(e);if(o!==Li.call(t))return!1;switch(o){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++;break}e=Bi(e),t=Bi(t);let s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;let n=e.constructor,r=t.constructor;if(n!==r&&!(p(n)&&n instanceof n&&p(r)&&r instanceof r)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];let c=r.length;for(;c--;)if(r[c]===e)return i[c]===t;if(r.push(e),i.push(t),s){if(c=e.length,c!==t.length)return!1;for(;c--;)if(!zi(e[c],t[c],n-1,r,i))return!1}else{let a=Object.keys(e),o=a.length;if(Object.keys(t).length!==o)return!1;for(let s=0;s<o;s++){let o=a[s];if(!(ae(t,o)&&zi(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function Bi(e){return mi(e)?e.slice():ee(e)||vi(e)||S(e)||Ci(e)?Array.from(e.entries()):e}let Vi=globalThis.Iterator?.prototype||{};function Hi(e){return e[Symbol.iterator]=Ui,r(Object.create(Vi),e)}function Ui(){return this}function Wi(e){return e instanceof Object&&typeof e.annotationType_==`string`&&p(e.make_)&&p(e.extend_)}{let e=globalThis;[`Symbol`,`Map`,`Set`,`Proxy`].forEach(t=>{e[t]===void 0&&n(`MobX requires global '${t}' to be available or polyfilled`)})}typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Dn,extras:{getDebugName:Fi},$mobx:T}),e.$mobx=T,e.FlowCancellationError=ir,e.ObservableMap=_i,e.ObservableSet=Si,e.Reaction=hn,e._allowStateChanges=Et,e._allowStateChangesInsideComputed=zn,e._allowStateReadsEnd=Kt,e._allowStateReadsStart=k,e._autoAction=In,e._autoActionBound=Rn,e._endAction=Tt,e._getAdministration=Pi,e._getGlobalState=$t,e._interceptReads=mr,e._isComputingDerivation=It,e._resetGlobalState=en,e._startAction=wt,e.action=Fn,e.actionBound=Ln,e.autorun=Vn,e.compareDefault=me,e.compareIdentity=de,e.compareShallow=pe,e.compareStructural=fe,e.computed=O,e.computedStruct=_t,e.configure=Xn,e.createAtom=ue,e.defineProperty=jr,e.entries=Er,e.extendObservable=Zn,e.flow=lr,e.flowBound=ur,e.flowResult=fr,e.get=Ar,e.getAtom=Ni,e.getDebugName=Fi,e.getDependencyTree=Qn,e.getObserverTree=er,e.has=kr,e.intercept=hr,e.isAction=Bn,e.isBoxedObservable=At,e.isComputed=yr,e.isComputedProp=br,e.isFlow=pr,e.isFlowCancellationError=ar,e.isObservable=Sr,e.isObservableArray=mi,e.isObservableMap=vi,e.isObservableObject=N,e.isObservableProp=Cr,e.isObservableSet=Ci,e.keys=wr,e.makeAutoObservable=ti,e.makeObservable=$r,e.observable=D,e.observableDeep=ft,e.observableRef=ut,e.observableShallow=dt,e.observableStruct=pt,e.observe=Nr,e.onBecomeObserved=Kn,e.onBecomeUnobserved=qn,e.onReactionError=gn,e.override=be,e.ownKeys=Mr,e.reaction=Wn,e.remove=Or,e.runInAction=zn,e.set=Dr,e.spy=Dn,e.toJS=zr,e.transaction=Br,e.untracked=Ut,e.values=Tr,e.when=Vr})),J=ke(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=Kx():t.exports=qx()}))();function Jx(e){if(Array.isArray(e))return Object.freeze(e.map(Jx));if(typeof e==`object`&&e){let t=Object.create(null),n=Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t));for(let[e,r]of n)t[e]=Jx(r);return Object.freeze(t)}return e}function Yx(e){let t=typeof e;if(t===`string`||t===`number`||t===`boolean`)return t;throw TypeError(`Variable values must be string|number|boolean (got ${t})`)}function Xx(e){return typeof e==`string`?e:String(e)}function Zx(e){if(typeof e==`number`)return e;if(typeof e==`boolean`)return+!!e;let t=e.trim();if(t===``)throw TypeError(`Cannot cast empty string to number`);let n=Number(t);if(!Number.isFinite(n))throw TypeError(`Cannot cast ${JSON.stringify(e)} to number`);return n}function Qx(e){if(typeof e==`boolean`)return e;if(typeof e==`number`){if(e===0||e===1)return e===1;throw TypeError(`Cannot cast number ${e} to bool (only 0 and 1 are accepted)`)}if(e===`true`)return!0;if(e===`false`)return!1;throw TypeError(`Cannot cast ${JSON.stringify(e)} to bool (expected "true" or "false")`)}var $x=class extends Error{constructor(e,t){super(t),this.variable=e}};function eS(e){return e instanceof $x?e:e instanceof Error&&e.cause!==void 0?eS(e.cause):void 0}const tS=e=>e===Oa;var nS=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,tS(n)||fS(e,t,n,`initial value`),this.cell=J.observable.box(n,{deep:!1}),this.lastChangedAt=tS(n)?null:Date.now()}read(){let e=this.cell.get();if(tS(e))throw new $x(this.name,`variable "${this.name}" has no value yet: nothing has written it`);return e}set(e){tS(e)||fS(this.name,this.type,e,`set value`),!Object.is(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}stored(){return this.cell.get()}},rS=class{cell;constructor(e,t,n){if(this.cell=(0,J.computed)(t,{keepAlive:!0,...n!==void 0&&{equals:n}}),typeof this.cell.suspend_!=`function`)throw TypeError(`${e}: this MobX's computed has no suspend_; release() cannot unsubscribe it`);if(typeof this.cell.keepAlive_!=`boolean`)throw TypeError(`${e}: this MobX's computed has no keepAlive_ flag; release() cannot lift it`)}read(){return this.cell.get()}release(){this.cell.keepAlive_=!1,this.cell.suspend_()}},iS=class{constructor(e){this.deriver=e}read(){return this.deriver()}},aS=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new rS(`Variable "${e}"`,()=>{let e=n();return fS(this.name,this.type,e,`computed result`),e})}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}},oS=class{kind=`projection`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new iS(()=>{let e=n();return fS(this.name,this.type,e,`projection result`),e})}read(){return this.cell.read()}lastUpdatedMs(){return null}},sS=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=J.observable.box(dS(t),{deep:!1}),this.lastChangedAt=t.kind===`pending`?null:Date.now()}read(){return this.cell.get()}set(e){let t=dS(e);uS(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}},cS=class{kind=`document`;cell;constructor(e,t){this.name=e,this.cell=new rS(`Variable "${e}"`,()=>dS(t()),uS)}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}};function lS(e){return JSON.stringify(e)}function uS(e,t){return lS(e)===lS(t)}function dS(e){return e.kind===`ok`?{kind:`ok`,value:Jx(e.value)}:e}function fS(e,t,n,r){let i=Yx(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var pS=class{constructor(e=null){this.parent=e}nodes=J.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new nS(e,t,n))}defineDocument(e,t){this.declare(e,new sS(e,t))}defineDerivedDocument(e,t){this.declare(e,new cS(e,t))}defineComputed(e,t,n){this.defineDerived(e,t,`computed`,n)}defineDerived(e,t,n,r){let i=e=>this.read(e),a=n===`computed`?aS:oS;this.declare(e,new a(e,t,()=>r(i)))}derive(e,t,n){if(this.refuseDisposed(`Derived value "${e}"`),t===`projection`)return new iS(n);let r=new rS(`Derived value "${e}"`,n);return this.kept.push(r),r}kept=[];read(e){return this.requireVar(e).read()}readDocument(e){let t=this.requireNode(e);if(t.kind!==`document`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a document`);return t.read()}stored(e){let t=this.requireNode(e);if(t.kind===`document`)return t.read();if(t.kind!==`box`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a written node`);return t.stored()}setDocument(e,t){let n=this.requireOwn(e);if(!(n instanceof sS))throw TypeError(n.kind===`document`?`Variable "${e}" is a derived document: what it reads decides it, and nothing writes it`:`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,J.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireOwn(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,J.runInAction)(()=>n.set(t))}runInAction(e){(0,J.runInAction)(e)}has(e){return this.nodes.has(e)||(this.parent?.has(e)??!1)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`){let e=t.read();return e.kind===`pending`?Oa:P(lS(e))}try{return P(String(t.read()))}catch(e){return eS(e)===void 0?P(` failed:${e instanceof Error?e.message:String(e)}`):Oa}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.parent?.names()??[],...this.nodes.keys()]}dispose(){if(this.disposed)return 0;this.disposed=!0;let e=0;return(0,J.runInAction)(()=>{for(let t of this.nodes.values())(t instanceof aS||t instanceof cS)&&(t.release(),e++);for(let e of this.kept)e.release()}),e+this.kept.length}disposed=!1;requireNode(e){let t=this.nodes.get(e)??this.parent?.requireNode(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireOwn(e){let t=this.nodes.get(e);if(t!==void 0)return t;throw this.parent?.has(e)?Error(`Variable "${e}" lives in the directory's store; a session's view cannot write it`):ReferenceError(`Unknown variable "${e}"`)}requireVar(e){let t=this.requireNode(e);if(t.kind===`document`)throw TypeError(`Variable "${e}" is a document; read its fields by path (.${e}.<field>)`);return t}refuseDisposed(e){if(this.disposed)throw Error(`${e}: cannot declare on a disposed store`)}declare(e,t){if(this.refuseDisposed(`Variable "${e}"`),this.has(e))throw Error(`Variable "${e}" is already declared`);(0,J.runInAction)(()=>this.nodes.set(e,t))}},mS=class extends Error{name=`TemplateError`;kind=`EvalError`;pos;source;constructor(e,t,n={}){super(e,{cause:n.cause}),this.pos=t,this.source=n.source}get sourceSnippet(){return this.source?CS(this.source,this.pos):``}toString(){let e=`${this.name}: ${this.message}\n at line ${this.pos.line}, column ${this.pos.column}`,t=this.sourceSnippet;return t?`${e}\n\n${t}`:e}},hS=class extends mS{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},gS=class extends mS{name=`EvalError`;kind=`EvalError`},_S=class extends gS{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=wS(e,n.available??[]),i=r.length===0?``:` (did you mean: ${r.join(`, `)}?)`;super(`function ${JSON.stringify(e)} is not registered${i}`,t,n),this.funcName=e,this.suggestions=r}},vS=class extends gS{name=`ArgCountError`;kind=`ArgCountError`;funcName;accepted;got;constructor(e,t,n,r,i={}){let a=t.minimum===t.maximum?`${t.minimum}`:`at least ${t.minimum}`;super(`wrong number of args for ${e}: want ${a} got ${n}`,r,i),this.funcName=e,this.accepted=t,this.got=n}},yS=class extends gS{name=`TypeMismatchError`;kind=`TypeMismatchError`;funcName;argIndex;expected;receivedSummary;constructor(e,t,n,r,i,a={}){super(`function ${JSON.stringify(e)} arg ${t}: expected ${n}, but a ${r} flowed in. Pass it through \`unstyled\` (or your engine's flatten function) to convert.`,i,a),this.funcName=e,this.argIndex=t,this.expected=n,this.receivedSummary=r}},bS=class extends yS{constructor(e,t,n,r,i={}){super(e,t,`integer`,String(n),r,i),this.message=Number.isInteger(Number(n))?`integer out of range: ${String(n)}`:`expected integer; found ${String(n)}`}},xS=class extends gS{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},SS=class extends gS{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function CS(e,t){let n=e.split(`
60
+ `))}function Ob(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:o,failedConfigFile:s}=t,c=new V({bgcolor:i.bg,color:i.fg}),l=(e,t)=>new W(e,{style:t,end:``,overflow:`ignore`}),u=n>0?[l(`${n} more rows · `,c),o.kind===`file`?l(`open full text`,c.withLink(a(o.path).href)):l(`full text unavailable: ${Ny(o.reason)}`,c)]:[],d=s===null?[]:[l(`${u.length>0?` · `:``}open `,c),l(Ny(s),c.withLink(a(s).href))],f=[l(`↳ `,c),...u,...d.slice(0,-1)],p=f.reduce((e,t)=>e+t.cellLength,0),m=d.slice(-1).map(e=>e.truncate(Math.max(1,r.width-p),{mode:`middle`})),h=W.fromFragments([...f,...m]).truncate(r.width);return h.overflow=`ignore`,pb([h],r)}var q=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};function kb(e){try{return e()}catch(e){throw e instanceof URIError?new q(`malformed wire encoding: ${e.message}`):e}}const Ab=new Map;function jb(e){let t=Nb(e);if(t===null)throw Error(`Palette "${e}" did not resolve in the theme registry — allowed names and the registry are inconsistent`);return t}function Mb(e,t){return e===`bar`?t:jb(e)}function Nb(e){let t=Ab.get(e);if(t!==void 0)return t;let n=au(e);return n===null?null:(Ab.set(e,n),n)}function Pb(e,t){return Fb(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>_u(e,t))}const Fb=uh();function Ib(e){let t=Nb(e);return t===null?null:{kind:`decided`,name:e,value:t}}function Lb(e,t,n){let r=Ib(e);return r===null?(n(Qg(t,`palette`,`"${e}" names no installed theme${Fg(e)}`)),zb()):r}function Rb(e,t,n){return Gg(e,t,n,zb(),Ib)}function zb(){return{kind:`decided`,name:Ig,value:jb(Ig)}}const Bb=/^[A-Za-z_][A-Za-z0-9_]*$/;function Vb(e){return`#${e+1}`}const Hb={rows:{}};function Ub(e){return`rows`in e}function Wb(e){return Object.fromEntries(e.map((e,t)=>[Vb(t),e]))}function Gb(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:Wb(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:Wb([n])}}function Kb(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function qb(e){return Ub(e)?Kb(e):e}function*Jb(e,t){if(!Ub(e)){yield*k_(e,t);return}yield[Kb(e),t];for(let[n,r]of Object.entries(e.rows))yield*k_(r,`${t}.rows.${n}`)}function Yb(e,t){return Ub(e)?{...t,...e,rows:{...t.rows,...e.rows}}:Gb(e)}function Xb(e){if(!Ub(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const Zb=`default`,Qb={};function $b(e){return[...new Set([Zb,...Object.keys(e)])]}function ex(e,t,n){return Hg(void 0,e,t,Zb,n)}function tx(e,t){let n={[Zb]:Qb,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${Zb}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function nx(e,t){let n=tx(e.presets,t).root??Hb;return{node:Kb(Yb(n,e.root)),path:Xb(n)?`presets.${t}.root`:`root`}}function rx(e,t){return{...e.globals,...tx(e.presets,t).globals}}const ix=new Map;function ax(e,t,n){ix.set(e,{permanent:!0,resolve:t,paletteOf:n})}ax(`themes`,()=>Rg(),e=>jb(e));const ox=`placementThemes`;ax(ox,zg,(e,t)=>Mb(e,t.palette));for(let{name:e,members:t}of gy)ax(e,()=>t);function sx(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>Pb(n.basePalette,e.styles[t])}],[`presets`,{members:$b(e.presets)}]])}function cx(e){return[...new Set([...ix.keys(),...e.keys()])]}function lx(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=ix.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf};throw Error(dx(e,t))}const ux=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function dx(e,t){let n=ux.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${cx(t).join(`, `)})`}const fx=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`slash`,`run`,`do`];function px(e){return JSON.stringify([e.run,Object.entries(e.env),e.cwd,e.refreshes])}function*mx(e){if(`copy`in e&&(yield[`copy`,e.copy]),`open`in e&&(yield[`open`,e.open]),`preset`in e&&e.preset===`delete`&&(yield[`name`,e.name]),`run`in e){for(let[t,n]of e.run.entries())yield[`run.${t}`,n];for(let[t,n]of Object.entries(e.env))yield[`env.${t}`,n]}}function hx(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}const gx=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*_x(e){let t=e.indexOf(`{{`);for(;t!==-1;){let n=``,r=t+2;for(;r<e.length&&!e.startsWith(`}}`,r);){if(e.startsWith(`/*`,r)){let t=e.indexOf(`*/`,r+2);r=t===-1?e.length:t+2;continue}let t=r,i=e[r];if(r+=1,i===`"`||i===`'`||i==="`"){for(;r<e.length&&e[r]!==i;)r+=e[r]===`\\`&&i!=="`"?2:1;r+=1}n+=e.slice(t,r)}if(r>=e.length)return;yield n,t=e.indexOf(`{{`,r+2)}}const vx=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,yx=RegExp(`^(?:(\\$)(?:\\.(${vx}))?|\\.(${vx})?)(?=[\\s)]|$)`);function bx(e,t,n){let r=yx.exec(e.trimStart());if(r===null)return null;let[i,a]=r[1]===void 0?[t,r[3]]:[n,r[2]];return i===null?null:a===void 0?i:`${i}${a}.`}const xx=/^(\w+)\b\s*([\s\S]*)$/;function*Sx(e,t){let n=[t];for(let r of _x(e)){let e=r.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=xx.exec(e)??[],o=n[n.length-1],s=n.length>1?n[n.length-2]:o;if(i===`end`){n.length>1&&n.pop();continue}if(i===`else`){yield{code:e,dot:s};let r=/^with\b([\s\S]*)$/.exec(a);n[n.length-1]=r===null?s:bx(r[1],s,t);continue}yield{code:e,dot:o},i===`if`&&n.push(o),i===`with`&&n.push(bx(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const Cx=/(?<![.$])\btemplate\s+$/;function*wx(e,t,n){let r=0;for(let i of[...e.matchAll(gx)]){let a=i.index+i[0].length;Cx.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:bx(e.slice(a),t,n)}),r=a}}function*Tx(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...Sx(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...wx(s,c,i)]){let i=Object.hasOwn(t,e.name)?t[e.name]:void 0,a=`${e.name}\0${e.at??`\0`}`;i===void 0||o.has(e.name)||n.has(a)||(n.add(a),yield*r(i,e.at,e.name,new Set([...o,e.name])))}}}yield*r(e,``,null,new Set)}const Ex=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${vx})`,`g`);function*Dx({code:e,dot:t,root:n}){let r=e.replace(gx,``);for(let e of[...r.matchAll(Ex)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function Ox(e,t){let n=new Map;for(let r of Tx(e,t))for(let e of Dx(r))n.has(e)||n.set(e,r.via);return n}const kx=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,Ax={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*jx(e){let t=0,n=0,r=0,i=`action`;for(let a of[...e.matchAll(gx)]){let o=e.slice(t,a.index),s=kx.exec(o);if(s!==null)n=Ax[s[1]],r=0,i=s[1]===`action`?`action`:`options`;else for(let e of o)e===`(`&&r++,e===`)`&&r--,(r<0||e===`|`&&r===0)&&(n=0);n>0&&r===0&&(yield{name:a[0].slice(1,-1),site:i},n--),t=a.index+a[0].length}}function Mx(e,t){let n=new Map;for(let{code:r,via:i}of Tx(e,t))for(let{name:e,site:t}of jx(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}const Nx=/(?<![\w.$])(?:action|picker|menu|carousel|swatches|swatch|themePreview)\s+(?=[^\s"`)|}])/;function Px(e,t){for(let{code:n}of Tx(e,t))if(Nx.test(n.replace(gx,`""`)))return!0;return!1}const Fx=/(?<![\w.$])[A-Za-z_]\w*/g;function Ix(e,t){let n=new Set;for(let{code:r}of Tx(e,t))for(let[e]of r.replace(gx,``).matchAll(Fx))n.add(e);return n}function Lx(e,t){return new Set([...Rx(e,t)].filter(e=>Object.hasOwn(t,e)))}function Rx(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of Tx(e,t))for(let{name:e}of wx(r,i,a))n.add(e);return n}function*zx(e){for(let[t,n]of Object.entries(e.variables))yield[t,n,[`variables`,t]];for(let[t,n]of Object.entries(e.segments))for(let[e,r]of Object.entries(n.vars??{}))yield[`${t}.${e}`,r,[`segments`,t,`vars`,e]]}function*Bx(e){for(let[t,n]of zx(e))yield[t,n]}function Vx(e,t){let n=e.split(`.`);for(let e=n.length;e>0;e--){let r=n.slice(0,e).join(`.`);if(t.has(r))return[r]}let r=`${e}.`;return[...t].filter(e=>e.startsWith(r))}function Hx(e,t){return Vx(e,t.names).some(n=>!e.startsWith(`${n}.`)||t.documents.has(n))}function Ux(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),Wx(r)&&n.add(e)};for(let[t,n]of Bx(e))r(t,n);return{names:t,documents:n,helpers:e.helpers}}function Wx(e){return e.kind===`dropped`||e.kind===`source`||(e.kind===`shell`||e.kind===`file`)&&j_(e.parse)===`json`}function Gx(e){let t=s.basename(e),n=s.dirname(e);for(;;){let r=Kx(n);if(r!==null)return{dir:r,name:t,leaf:n===s.dirname(e)};t=s.basename(n),n=s.dirname(n)}}function Kx(e){try{return p.statSync(e).isDirectory()?p.realpathSync(e):null}catch{return null}}var qx=ke((e=>{function t(e,...t){throw Error(`[MobX] minified error nr: ${e}${t.length?` `+t.map(String).join(`,`):``}. See mobx.js.org/errors`)}function n(e){let t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function r(e){return typeof e==`function`}function i(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function a(e){return typeof e==`object`&&!!e}function o(e){if(!a(e))return!1;let t=Object.getPrototypeOf(e);if(t==null)return!0;let n=p(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===Ht}function s(e){let t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function c(e,t,n){Rt(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function l(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return a(e)&&!0===e[n]}}function u(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function d(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function f(e){return e===null?null:typeof e==`object`?``+e:e}function p(e,t){return zt.hasOwnProperty.call(e,t)}function m(e,t){return!!(e&t)}function h(e,t,n){return n?e|=t:e&=~t,e}function g(e,t=Ut,n=Ut){let r=new Kt(e);return t!==Ut&&(r.onBOL=new Set([t])),n!==Ut&&(r.onBUOL=new Set([n])),r}function _(e,t){return jt(e,t)}function v(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||nt(e)?e:Array.isArray(e)?ln.array(e,{name:n}):o(e)?ln.object(e,void 0,{name:n}):u(e)?ln.map(e,{name:n}):d(e)?ln.set(e,{name:n}):typeof e!=`function`||Ge(e)||$e(e)?e:s(e)?Kn(e):Rn(n,e)}function y(e){return e}function b(e,t){return{t:e,i:t,o:ee,u:x}}function ee(e,t,n,r){var i;return(i=this.i)!=null&&i.bound?this.u(e,t,n,!1)===null?0:1:r===e.h?this.u(e,t,n,!1)===null?0:2:Ge(n.value)?1:(Rt(r,t,te(e,this,t,n,!1)),2)}function x(e,t,n,r){let i=te(e,this,t,n);return e.l(t,i,r)}function S(e,n,r){let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>{var t;return be(s.i?.name??a.toString(),e,(t=s.i?.autoAction)!=null&&t)};return i==`field`?function(e){var t;let n=e;return Ge(n)||(n=c(n)),(t=s.i)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n}:i==`method`?(Ge(n)||(n=c(n)),(l=s.i)!=null&&l.bound&&o(function(){let e=this,t=e[a].bind(e);t.isMobxAction=!0,e[a]=t}),n):void t(43,s.t,String(a),i);var l}function te(e,t,n,r,i=j.safeDescriptors){var a,o,s;let{value:c}=r;return(a=t.i)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:be(t.i?.name??n.toString(),c,(o=t.i?.autoAction)!=null&&o,(s=t.i)!=null&&s.bound?e.v??e.h:void 0),configurable:!i||e.p,enumerable:!1,writable:!i}}function ne(e,t){return{t:e,i:t,o:re,u:ie}}function re(e,t,n,r){var i;return r===e.h?this.u(e,t,n,!1)===null?0:2:(i=this.i)!=null&&i.bound&&(!p(e.h,t)||!$e(e.h[t]))&&this.u(e,t,n,!1)===null?0:$e(n.value)?1:(Rt(r,t,C(e,0,0,n,!1,!1)),2)}function ie(e,t,n,r){let i=C(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function ae(e,t,n){var r;let{name:i,addInitializer:a}=n;return $e(t)||(t=Kn(t)),(r=e.i)!=null&&r.bound&&a(function(){let e=this,t=e[i].bind(e);t.isMobXFlow=!0,e[i]=t}),t}function C(e,t,n,r,i,a=j.safeDescriptors){let{value:o}=r;return $e(o)||(o=Kn(o)),i&&(o=o.bind(e.v??e.h),o.isMobXFlow=!0),{value:o,configurable:!a||e.p,enumerable:!1,writable:!a}}function w(e,t){return{t:e,i:t,o:oe,u:se}}function oe(e,t,n){return this.u(e,t,n,!1)===null?0:1}function se(e,t,n,r){return e.m(t,It({},this.i,{get:n.get,set:n.set}),r)}function T(e,t,n){function r(e){let n=It({},i.i,{get:t,context:e});return n.name||=`ObservableObject.${a.toString()}`,new xn(n)}let i=e,{name:a,addInitializer:o}=n,s;return o(function(){let e=wt(this)[k],n=this,i=e.j.get(a);i instanceof xn&&i.derivation!==t&&e.j.delete(a),(e.O??=new Map).set(a,()=>r(n))}),function(){let e=this[k],n=e.j.get(a);if(n instanceof xn&&n.derivation!==t){let e=s?.get(this);return e||(e=r(this),(s??=new WeakMap).set(this,e)),e.get()}return e._(a)}}function ce(e,t){return{t:e,i:t,o:le,u:ue}}function le(e,t,n){return this.u(e,t,n,!1)===null?0:1}function ue(e,t,n,r){return e.S(t,n.value,this.i?.A??v,r)}function de(e,t,n){function r(e,t){let n=wt(e)[k];return(n.V??=new Map).set(o,()=>new yn(t,i.i?.A??v,`ObservableObject.${o.toString()}`,!1)),n}let i=e,{kind:a,name:o}=n;if(a===`accessor`)return{get(){return(this[k]??r(this,t.get.call(this)))._(o)},set(e){return(this[k]??r(this,e)).M(o,e)},init(e){return r(this,e),e}}}function fe(e){return{t:Xt,i:e,o:pe,u:me}}function pe(e,t,n,r){var i,a,o;if(n.get)return pn.o(e,t,n,r);if(n.set){let i=Ge(n.set)?n.set:be(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!j.safeDescriptors||e.p,set:i})===null?0:2:(Rt(r,t,{configurable:!0,set:i}),2)}if(r!==e.h&&typeof n.value==`function`)return s(n.value)?((o=this.i)!=null&&o.autoBind?qn:Kn).o(e,t,n,r):((a=this.i)!=null&&a.autoBind?Bn:Rn).o(e,t,n,r);let c=!1===this.i?.deep?an:ln;return typeof n.value==`function`&&(i=this.i)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),c.o(e,t,n,r)}function me(e,t,n,r){var i;return n.get?pn.u(e,t,n,r):n.set?e.l(t,{configurable:!j.safeDescriptors||e.p,set:be(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.i)!=null&&i.autoBind&&(n.value=n.value.bind(e.v??e.h)),(!1===this.i?.deep?an:ln).u(e,t,n,r))}function he(e,t){return It(function(n,r){if(r&&typeof r.kind==`string`)return t(e,n,r)},e)}function ge(e){return e||Qt}function _e(e){return he(e,de)}function ve(e){return!0===e.deep?v:!1===e.deep?y:(t=e.defaultDecorator)&&(n=(r=t.i)?.A)!=null?n:v;var t,n,r}function ye(e){return he(e,T)}function be(e,t,n=!1,r){function i(){return xe(0,n,t,r||this,arguments)}return i.isMobxAction=!0,i.toString=()=>t.toString(),_n&&(vn.value=e,Rt(i,`name`,vn)),i}function xe(e,t,n,r,i){let a=Se(0,t);try{return n.apply(r,i)}catch(e){throw a.N=e,e}finally{Ce(a)}}function Se(e,t){let n=j.trackingDerivation,r=!t||!n;Fe();let i=j.allowStateChanges;r&&Ae();let a={R:r,k:n,C:i,I:j.allowStateReads,P:!1,T:0,B:gn++,D:hn};return hn=a.B,a}function Ce(e){hn!==e.B&&t(30),hn=e.D,e.N!==void 0&&(j.suppressReactionErrors=!0),Ie(),e.R&&je(e.k),j.suppressReactionErrors=!1}function we(e,t){let n=function(e){let t=j.allowStateChanges;return j.allowStateChanges=e,t}(e);try{return t()}finally{(function(e){j.allowStateChanges=e})(n)}}function Te(e){return e instanceof Cn}function Ee(e){switch(e.K){case 0:return!1;case-1:case 2:return!0;case 1:{let t=Ae(),n=e.L,r=n.length;for(let i=0;i<r;i++){let r=n[i];if(Sn(r)){if(j.disableErrorBoundaries)r.get();else try{r.get()}catch{return je(t),!0}if(e.K===2)return je(t),!0}}return E(e),je(t),!1}}}function De(e,t,n){E(e),e.$=Array(e.U===0?100:e.L.length),e.W=0,e.U=++j.runId;let r=j.trackingDerivation,i;if(j.trackingDerivation=e,j.inBatch++,!0===j.disableErrorBoundaries)i=t.call(n);else try{i=t.call(n)}catch(e){i=new Cn(e)}return j.inBatch--,j.trackingDerivation=r,function(e){let t=e.L,n=e.L=e.$,r=0,i=0,a=e.W;for(let e=0;e<a;e++){let t=n[e];t.diffValue===0&&(t.diffValue=1,i!==e&&(n[i]=t),i++),t.K>r&&(r=t.K)}for(n.length=i,e.$=null,a=t.length;a--;){let n=t[a];n.diffValue===0&&Ne(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,Me(t,e))}r!==0&&(e.K=r,e.q())}(e),i}function Oe(e){let t=e.L;e.L=[];let n=t.length;for(;n--;)Ne(t[n],e);e.K=-1}function ke(e){let t=Ae();try{return e()}finally{je(t)}}function Ae(){let e=j.trackingDerivation;return j.trackingDerivation=null,e}function je(e){j.trackingDerivation=e}function E(e){if(e.K===0)return;e.K=0;let t=e.L,n=t.length;for(;n--;)t[n].F=0}function Me(e,t){(e.H??=new Set).add(t),e.F>t.K&&(e.F=t.K)}function Ne(e,t){let n=e.H;n&&(n.delete(t),n.size===0&&Pe(e))}function Pe(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,j.pendingUnobservations.push(e))}function Fe(){j.inBatch++}function Ie(){--j.inBatch===0&&(Be(),!j.isRunningUnobservations&&j.pendingUnobservations.length>0&&function(){j.isRunningUnobservations=!0;try{let e=j.pendingUnobservations;for(let t=0;t<e.length;t++){let n=e[t];n.isPendingUnobservation=!1,n.H&&n.H.size!==0||(n.H=null,n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof xn&&n.G())}j.pendingUnobservations=[]}finally{j.isRunningUnobservations=!1}}())}function Le(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.L)==null||t.forEach(Le))}function Re(e){let t=j.trackingDerivation;return t===null?((!e.H||e.H.size===0)&&j.inBatch>0&&Pe(e),!1):(t.U!==e.J&&(e.J=t.U,t.$[t.W++]=e,!e.isBeingObserved&&j.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function ze(e){var t;e.F!==2&&(e.F=2,(t=e.H)==null||t.forEach(e=>{e.K===0&&e.q(),e.K=2}))}function Be(){j.inBatch>0||j.isRunningReactions||An(Ve)}function Ve(){j.isRunningReactions=!0;let e=j.pendingReactions,t=0;for(;e.length>0;){++t===kn&&(console.error(`[mobx] cycle in reaction: ${e[0]}`),e.splice(0));let n=e.splice(0);for(let e=0,t=n.length;e<t;e++)n[e].X()}j.isRunningReactions=!1}function He(e){return he(e,S)}function Ue(e){return function(t,n){return n&&typeof n.kind==`string`?S(e?Fn:Nn,t,n):r(t)?be(t.name||`<unnamed action>`,t,e):r(n)?be(t,n,e):i(t)?He(b(e?Mn:M,{name:t,autoAction:e})):void 0}}function We(e){return xe(0,!1,e,this,void 0)}function Ge(e){return r(e)&&!0===e.isMobxAction}function Ke(e,t=Vt){function n(){e(a)}var r;let i=t?.name??`Autorun`,a;if(t.scheduler||t.delay){let e=qe(t),r=!1;a=new On(i,()=>{r||(r=!0,e(()=>{r=!1,a.isDisposed||a.track(n)}))},t.onError,t.requiresObservable)}else a=new On(i,function(){this.track(n)},t.onError,t.requiresObservable);return t!=null&&(r=t.signal)!=null&&r.aborted||a.Y(),a.Z(t?.signal)}function qe(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Vn}function Je(e,t,n,i){let a=typeof i==`function`?Dt(t,n):Dt(t),o=r(i)?i:n,s=`${e}L`;return a[s]?a[s].add(o):a[s]=new Set([o]),function(){let e=a[s];e&&(e.delete(o),e.size===0&&delete a[s])}}function Ye(e,t,n,r){let i=Gt(t);return At(()=>{let t=wt(e,r)[k];Wt(i).forEach(e=>{t.u(e,i[e],!n||!(e in n)||n[e])})}),e}function Xe(e){let t={name:e.tt};var n;return e.L&&e.L.length>0&&(t.dependencies=(n=e.L,Array.from(new Set(n))).map(Xe)),t}function Ze(e){let t={name:e.tt};return function(e){return!!e.H&&e.H.size>0}(e)&&(t.observers=Array.from(function(e){return e.H??new Set}(e),Ze)),t}function Qe(e){r(e.cancel)&&e.cancel()}function $e(e){return!0===e?.isMobXFlow}function et(e,t){var n;if(t===void 0)return Sn(e);if(!1===Et(e))return!1;let r=e[k];return(n=r.O)!=null&&n.has(t)?!0:r.j.has(t)?Sn(Dt(e,t)):!1}function tt(e,t){if(!e)return!1;if(t!==void 0){if(Et(e)){var n,r;let i=e[k];return i.j.has(t)||!((n=i.O)==null||!n.has(t))||!((r=i.V)==null||!r.has(t))}return!1}return Et(e)||!!e[k]||qt(e)||jn(e)||Sn(e)}function nt(e){return tt(e)}function rt(e){return Et(e)?e[k].nt():ar(e)||cr(e)?Array.from(e.keys()):xt(e)?e.map((e,t)=>t):void t(5)}function it(e,n){return Et(e)?e[k].et(n):ar(e)||cr(e)?e.has(n):xt(e)?n>=0&&n<e.length:void t(10)}function at(e){if(Et(e))return e[k].it();t(38)}function ot(e,t,n){if(Sn(e)){let r,i=!0;return Ke(()=>{let a=e.get();if(!i||n){let n=Ae();t({observableKind:`computed`,debugObjectName:e.tt,type:Zn,object:e,newValue:a,oldValue:r}),je(n)}i=!1,r=a})}return n&&t({observableKind:`value`,debugObjectName:e.tt,object:e,type:Zn,newValue:e.rt,oldValue:void 0}),ht(e,t)}function st(e,t,n){return e.set(t,n),n}function ct(e,t){if(typeof e!=`object`||!e||e instanceof Date||!nt(e))return e;if(bn(e)||Sn(e))return ct(e.get(),t);if(t.has(e))return t.get(e);if(xt(e)){let n=st(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=ct(e,t)}),n}if(cr(e)){let n=st(t,e,new Set);return e.forEach(e=>{n.add(ct(e,t))}),n}if(ar(e)){let n=st(t,e,new Map);return e.forEach((e,r)=>{n.set(r,ct(e,t))}),n}{let n=st(t,e,{});return at(e).forEach(r=>{zt.propertyIsEnumerable.call(e,r)&&(n[r]=ct(e[r],t))}),n}}function lt(e,t){Fe();try{return e.apply(t)}finally{Ie()}}function ut(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[k].isDisposed){if(a(),!n.onError)throw e;n.onError(e)}},n.timeout)}n.name=`When`;let i=be(`When-effect`,t);var a=Ke(t=>{we(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function dt(e){return e[k]}function ft(e){return e.st!==void 0&&e.st.length>0}function pt(e,t){let r=e.st;return r?r.push(t):r=e.st=[t],n(()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)})}function D(e,n){let r=Ae();try{let r=[...e.st||[]];for(let e=0,i=r.length;e<i&&((n=r[e](n))&&!n.type&&t(14),n);e++);return n}finally{je(r)}}function mt(e){return e.ot!==void 0&&e.ot.length>0}function ht(e,t){let r=e.ot;return r?r.push(t):r=e.ot=[t],n(()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)})}function gt(e,t){let n=Ae(),r=e.ot;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);je(n)}}function _t(e,n,r){if(!0===r&&(r=e.ut),!1===r)return;n in e.h||t(1,r.t,`${e.tt}.${n.toString()}`);let i=e.h;for(;i&&i!==zt;){let t=Lt(i,n);if(t){let a=r.o(e,n,t,i);if(a===0)return;if(a===1)break}i=Object.getPrototypeOf(i)}}function O(e,t){typeof Array.prototype[e]==`function`&&(er[e]=t(e))}function vt(e){return function(){let t=this[k];t.ct.reportObserved();let n=t.ht(t.j);return n[e].apply(n,arguments)}}function yt(e){return function(t,n){let r=this[k];return r.ct.reportObserved(),r.ht(r.j)[e]((e,r)=>t.call(n,e,r,this))}}function bt(e){return function(){let t=this[k];t.ct.reportObserved();let n=t.ht(t.j),r=arguments[0];return arguments[0]=(e,t,n)=>r(e,t,n,this),n[e].apply(n,arguments)}}function xt(e){return a(e)&&tr(e[k])}function St(e){return e[Symbol.toStringTag]=`MapIterator`,Pt(e)}function Ct(e){return e[Symbol.toStringTag]=`SetIterator`,Pt(e)}function wt(e,t){if(p(e,k))return e;let n=t?.name??`ObservableObject`;return c(e,k,new dr(e,new Map,String(n),function(e){return e?e.defaultDecorator??function(e){let t=!1!==e.deep,n=!!e.autoBind,r=!t|(n?2:0);return A[r]??(A[r]=fe({deep:t,autoBind:n}))}(e):void 0}(t))),e}function Tt(e){return lr[e]||(lr[e]={get(){return this[k]._(e)},set(t){return this[k].M(e,t)}})}function Et(e){return!!a(e)&&fr(e[k])}function Dt(e,n){if(typeof e==`object`&&e){if(xt(e))return n!==void 0&&t(23),e[k].ct;if(cr(e))return e.ct;if(ar(e)){if(n===void 0)return e.lt;let r=e.ft.get(n)||e.dt.get(n);return r||t(25,n,kt(e)),r}if(Et(e)){if(!n)return t(26);let r=e[k],i=r.j.get(n)??r.vt(n)??r.bt(n);return i||t(27,n,kt(e)),i}if(qt(e)||Sn(e)||jn(e))return e}else if(r(e)&&jn(e[k]))return e[k];t(28)}function Ot(e,n){return e||t(29),n===void 0?qt(e)||Sn(e)||jn(e)||ar(e)||cr(e)?e:e[k]?e[k]:void t(24,e):Ot(Dt(e,n))}function kt(e,t){let n;if(t!==void 0)n=Dt(e,t);else{if(Ge(e))return e.name;n=Et(e)||ar(e)||cr(e)?Ot(e):Dt(e)}return n.tt}function At(e){let t=Ae();Fe();try{return e()}finally{Ie(),je(t)}}function jt(e,t,n=-1){return Mt(e,t,n)}function Mt(e,t,n,i,a){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!=e)return t!=t;let o=typeof e;if(o!==`function`&&o!==`object`&&typeof t!=`object`)return!1;let s=pr.call(e);if(s!==pr.call(t))return!1;switch(s){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++}e=Nt(e),t=Nt(t);let c=s===`[object Array]`;if(!c){if(typeof e!=`object`||typeof t!=`object`)return!1;let n=e.constructor,i=t.constructor;if(n!==i&&!(r(n)&&n instanceof n&&r(i)&&i instanceof i)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),a||=[];let l=(i||=[]).length;for(;l--;)if(i[l]===e)return a[l]===t;if(i.push(e),a.push(t),c){if(l=e.length,l!==t.length)return!1;for(;l--;)if(!Mt(e[l],t[l],n-1,i,a))return!1}else{let r=Object.keys(e),o=r.length;if(Object.keys(t).length!==o)return!1;for(let s=0;s<o;s++){let o=r[s];if(!p(t,o)||!Mt(e[o],t[o],n-1,i,a))return!1}}return i.pop(),a.pop(),!0}function Nt(e){return xt(e)?e.slice():u(e)||ar(e)||d(e)||cr(e)?Array.from(e.entries()):e}function Pt(e){return e[Symbol.iterator]=Ft,It(Object.create(mr),e)}function Ft(){return this}Object.defineProperty(e,`__esModule`,{value:!0});let It=Object.assign,Lt=Object.getOwnPropertyDescriptor,Rt=Object.defineProperty,zt=Object.prototype,Bt=[];Object.freeze(Bt);let Vt={};Object.freeze(Vt);let Ht=Object.toString(),Ut=()=>{},Wt=Reflect.ownKeys,Gt=Object.getOwnPropertyDescriptors,k=Symbol(`mobx administration`);var Kt=class{constructor(e=`Atom`){this.tt=void 0,this.yt=0,this.H=null,this.J=0,this.F=-1,this.onBOL=void 0,this.onBUOL=void 0,this.tt=e}get isBeingObserved(){return m(this.yt,1)}set isBeingObserved(e){this.yt=h(this.yt,1,e)}get isPendingUnobservation(){return m(this.yt,2)}set isPendingUnobservation(e){this.yt=h(this.yt,2,e)}get diffValue(){return+!!m(this.yt,4)}set diffValue(e){this.yt=h(this.yt,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return Re(this)}reportChanged(){Fe(),ze(this),Ie()}toString(){return this.tt}};let qt=l(`Atom`,Kt),Jt=Object.is,Yt={t:`override`,o:function(){return 0},u:function(){t(44,this.t)}},Xt=`true`,Zt=fe(),A=[Zt],Qt={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Qt);let $t=ce(`observable`),en=ce(`observable.ref`,{A:y}),tn=ce(`observable.shallow`,{A:function(e,t,n){return e==null||Et(e)||xt(e)||ar(e)||cr(e)?e:Array.isArray(e)?ln.array(e,{name:n,deep:!1}):o(e)?ln.object(e,void 0,{name:n,deep:!1}):u(e)?ln.map(e,{name:n,deep:!1}):d(e)?ln.set(e,{name:n,deep:!1}):void 0}}),nn=ce(`observable.struct`,{A:function(e,t){return jt(e,t)?t:e}}),rn={box(e,t){let n=ge(t);return new yn(e,ve(n),n.name,!0,n.equals)},array(e,t){let n=ge(t);return function(e,t,n=`ObservableArray`,r=!1){return At(()=>{let i=new $n(n,t,r);Rt(i.j,k,{enumerable:!1,writable:!1,configurable:!0,value:i});let a=new Proxy(i.j,Qn);return i.v=a,e&&e.length&&i.wt(0,0,e),a})}(e,ve(n),n.name)},map(e,t){let n=ge(t);return new ir(e,ve(n),n.name)},set(e,t){let n=ge(t);return new sr(e,ve(n),n.name)},object:(e,t,n)=>At(()=>Ye(function(e,t){var n;return(n=(e=wt(e,t))[k]).v??(n.v=new Proxy(e,Jn))}({},n),e,t))},an=_e(en),on=_e(tn),sn=_e($t),cn=_e(nn);var ln=It(function(e,t,n){return t&&typeof t.kind==`string`?de($t,e,t):nt(e)?e:o(e)?ln.object(e,t,n):Array.isArray(e)?ln.array(e,t):u(e)?ln.map(e,t):d(e)?ln.set(e,t):typeof e==`object`&&e?e:ln.box(e,t)},$t,rn);let un=`computed`,dn=w(un),fn=ye(w(`computed.struct`,{equals:_})),pn=function(e,t){if(t&&typeof t.kind==`string`)return T(dn,e,t);if(o(e))return ye(w(un,e));let n=o(t)?t:{};return n.get=e,n.name||=e.name||``,new xn(n)};var mn;It(pn,dn);let hn=0,gn=1,_n=(mn=Lt(()=>{},`name`)?.configurable)!=null&&mn,vn={value:`action`,configurable:!0,writable:!1,enumerable:!1};var yn=class extends Kt{constructor(e,t,n=`ObservableValue`,r=!0,i=Jt){super(n),this.A=void 0,this.tt=void 0,this.xt=void 0,this.gt=!1,this.st=void 0,this.ot=void 0,this.rt=void 0,this.dehancer=void 0,this.A=t,this.tt=n,this.xt=i,this.rt=t(e,void 0,n)}dehanceValue(e){return this.dehancer===void 0?e:this.dehancer(e)}set(e){(e=this.jt(e))!==j.UNCHANGED&&this.Ot(e)}jt(e){if(ft(this)){let t=D(this,{object:this,type:Zn,newValue:e});if(!t)return j.UNCHANGED;e=t.newValue}return e=this.A(e,this.rt,this.tt),this.xt(this.rt,e)?j.UNCHANGED:e}Ot(e){let t=this.rt;this.rt=e,this.reportChanged(),mt(this)&&gt(this,{type:Zn,object:this,newValue:e,oldValue:t})}get(){return this.reportObserved(),this.dehanceValue(this.rt)}raw(){return this.rt}toJSON(){return this.get()}toString(){return`${this.tt}[${this.rt}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let bn=l(`ObservableValue`,yn);var xn=class{constructor(e){this.K=-1,this.L=[],this.$=null,this.H=null,this.U=0,this.J=0,this.F=0,this.W=0,this.rt=new Cn(null),this.tt=void 0,this._t=void 0,this.yt=0,this.derivation=void 0,this.St=void 0,this.At=void 0,this.xt=void 0,this.Vt=void 0,this.Mt=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||t(31),this.derivation=e.get,this.tt=e.name||`ComputedValue`,e.set&&(this.St=be(`ComputedValue-setter`,e.set)),this.xt=e.equals||Jt,this.At=e.context,this.Vt=e.requiresReaction,this.Mt=!!e.keepAlive}q(){(function(e){var t;e.F===0&&(e.F=1,(t=e.H)==null||t.forEach(e=>{e.K===0&&(e.K=1,e.q())}))})(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return m(this.yt,1)}set isComputing(e){this.yt=h(this.yt,1,e)}get isRunningSetter(){return m(this.yt,2)}set isRunningSetter(e){this.yt=h(this.yt,2,e)}get isBeingObserved(){return m(this.yt,4)}set isBeingObserved(e){this.yt=h(this.yt,4,e)}get isPendingUnobservation(){return m(this.yt,8)}set isPendingUnobservation(e){this.yt=h(this.yt,8,e)}get diffValue(){return+!!m(this.yt,16)}set diffValue(e){this.yt=h(this.yt,16,e===1)}get(){if(this.isComputing&&t(32,this.tt,this.derivation),j.inBatch!==0||this.H&&this.H.size!==0||this.Mt){let e=this.isBeingObserved;if(Re(this),Ee(this)){let e=j.trackingContext;e||!this.Mt&&!this.isBeingObserved||(j.trackingContext=this),this.trackAndCompute()&&function(e){var t;e.F!==2&&(e.F=2,(t=e.H)==null||t.forEach(t=>{t.K===1?t.K=2:t.K===0&&(e.F=0)}))}(this),j.trackingContext=e}else !e&&this.isBeingObserved&&this.L.forEach(Le)}else Ee(this)&&(this.Nt(),Fe(),this.rt=this.Rt(!1),Ie());let e=this.rt;if(Te(e))throw e.cause;return e}set(e){if(this.St){this.isRunningSetter&&t(33,this.tt),this.isRunningSetter=!0;try{this.St.call(this.At,e)}finally{this.isRunningSetter=!1}}else t(34,this.tt)}trackAndCompute(){let e=this.rt,t=this.K===-1,n=this.Rt(!0),r=t||Te(e)||Te(n)||!this.xt(e,n);return r&&(this.rt=n),r}Rt(e){let t;if(this.isComputing=!0,e)t=De(this,this.derivation,this.At);else if(!0===j.disableErrorBoundaries)t=this.derivation.call(this.At);else try{t=this.derivation.call(this.At)}catch(e){t=new Cn(e)}return this.isComputing=!1,t}G(){this.Mt||(Oe(this),this.rt=void 0)}Nt(){}toString(){return`${this.tt}[${this.derivation.toString()}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let Sn=l(`ComputedValue`,xn);var Cn=class{constructor(e){this.cause=void 0,this.cause=e}};let wn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Tn=class{constructor(){this.version=7,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.isRunningUnobservations=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.safeDescriptors=!0}};let En=!0,Dn=!1,j=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(En=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(En=!1),En?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Tn):(setTimeout(()=>{Dn||t(35)},1),new Tn)}();var On=class{constructor(e=`Reaction`,t,n,r){this.tt=void 0,this.Et=void 0,this.kt=void 0,this.Ct=void 0,this.L=[],this.$=[],this.K=-1,this.U=0,this.W=0,this.yt=0,this.It=void 0,this.tt=e,this.Et=t,this.kt=n,this.Ct=r}get isDisposed(){return m(this.yt,1)}set isDisposed(e){this.yt=h(this.yt,1,e)}get isScheduled(){return m(this.yt,2)}set isScheduled(e){this.yt=h(this.yt,2,e)}get isTrackPending(){return m(this.yt,4)}set isTrackPending(e){this.yt=h(this.yt,4,e)}get isRunning(){return m(this.yt,8)}set isRunning(e){this.yt=h(this.yt,8,e)}get diffValue(){return+!!m(this.yt,16)}set diffValue(e){this.yt=h(this.yt,16,e===1)}q(){this.Y()}Y(){this.isScheduled||(this.isScheduled=!0,j.pendingReactions.push(this),Be())}X(){if(!this.isDisposed){Fe(),this.isScheduled=!1;let e=j.trackingContext;if(j.trackingContext=this,Ee(this)){this.isTrackPending=!0;try{this.Et()}catch(e){this.Pt(e)}}j.trackingContext=e,Ie()}}track(e){if(this.isDisposed)return;Fe(),this.isRunning=!0;let t=j.trackingContext;j.trackingContext=this;let n=De(this,e,void 0);j.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Oe(this),Te(n)&&this.Pt(n.cause),Ie()}Pt(e){if(this.kt)this.kt(e,this);else{if(j.disableErrorBoundaries)throw e;j.suppressReactionErrors||console.error(`[mobx] uncaught error in '${this}'`,e),j.globalReactionErrorHandlers.forEach(t=>t(e,this))}}dispose(){var e;this.isDisposed||(this.isDisposed=!0,(e=this.It)==null||e.call(this),this.isRunning||(Fe(),Oe(this),Ie()))}Z(e){let t=()=>this.dispose();return e!=null&&e.addEventListener&&!this.isDisposed&&(e.addEventListener(`abort`,t),this.It=()=>e.removeEventListener==null?void 0:e.removeEventListener(`abort`,t)),t[k]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.tt}]`}};let kn=100,An=e=>e(),jn=l(`Reaction`,On),M=`action`,Mn=`autoAction`,Nn=b(M),Pn=b(`action.bound`,{bound:!0}),Fn=b(Mn,{autoAction:!0}),In=b(`autoAction.bound`,{autoAction:!0,bound:!0}),Ln=Ue(!1);It(Ln,Nn);let Rn=Ue(!0);It(Rn,Fn);let zn=He(Pn),Bn=He(In),Vn=e=>e(),Hn=`always`;var Un=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};let Wn=ne(`flow`),Gn=ne(`flow.bound`,{bound:!0}),Kn=It(function(e,t){if(t&&typeof t.kind==`string`)return ae(Wn,e,t);let n=e,i=n.name||`flow`,a=function(){let e=arguments,t=Ln(i,n).apply(this,e),a,o,s=new Promise(function(e,n){function s(e){let r;o=void 0;try{r=Ln(i,t.next).call(t,e)}catch(e){return n(e)}l(r)}function c(e){let r;o=void 0;try{r=Ln(i,t.throw).call(t,e)}catch(e){return n(e)}l(r)}function l(t){if(!r(t?.then))return t.done?e(t.value):(o=Promise.resolve(t.value),o.then(s,c));t.then(l,n)}a=n,s(void 0)});return s.cancel=Ln(i,function(){try{o&&Qe(o);let e=t.return(void 0),n=Promise.resolve(e.value);n.then(Ut,Ut),Qe(n),a(new Un)}catch(e){a(e)}}),s};return a.isMobXFlow=!0,a},Wn),qn=he(Gn,ae),Jn={has:(e,t)=>dt(e).et(t),get:(e,t)=>dt(e).Tt(t),set(e,t,n){var r;return!!i(t)&&((r=dt(e).Bt(t,n,!0))==null||r)},deleteProperty(e,t){var n;return!!i(t)&&((n=dt(e).Dt(t,!0))==null||n)},defineProperty(e,t,n){var r;return(r=dt(e).l(t,n))==null||r},ownKeys:e=>dt(e).it(),preventExtensions(e){t(13)}},Yn=Symbol(`mobx-keys`),Xn=`splice`,Zn=`update`,Qn={get(e,t){let n=e[k];return t===k?n:t===`length`?n.Kt():typeof t!=`string`||isNaN(t)?p(er,t)?er[t]:e[t]:n.Tt(parseInt(t))},set(e,t,n){let r=e[k];return t===`length`?r.Lt(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.Bt(parseInt(t),n),!0},preventExtensions(){t(15)}};var $n=class{constructor(e=`ObservableArray`,t,n){this.$t=void 0,this.ct=void 0,this.j=[],this.st=void 0,this.ot=void 0,this.A=void 0,this.dehancer=void 0,this.v=void 0,this.Ut=0,this.$t=n,this.ct=new Kt(e),this.A=(e,n)=>t(e,n,`ObservableArray[..]`)}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}ht(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e}Kt(){return this.ct.reportObserved(),this.j.length}Lt(e){(!Number.isInteger(e)||e<0)&&t(40,e);let n=this.j.length;if(e!==n)if(e>n){let t=Array.from({length:e-n});this.wt(n,0,t)}else this.wt(e,n-e)}zt(e,n){e!==this.Ut&&t(16),this.Ut+=n}wt(e,t,n){let r=this.j.length;if(e===void 0?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=arguments.length===1?r-e:t==null?0:Math.max(0,Math.min(t,r-e)),n===void 0&&(n=Bt),ft(this)){let r=D(this,{object:this.v,type:Xn,index:e,removedCount:t,added:n});if(!r)return Bt;t=r.removedCount,n=r.added}n=n.length===0?n:n.map(e=>this.A(e,void 0));let i=this.qt(e,t,n);return t===0&&n.length===0||this.Ft(e,n,i),this.ht(i)}qt(e,t,n){if(n.length<1e4)return this.j.splice(e,t,...n);{let r=this.j.slice(e,e+t),i=this.j.slice(e+t);this.j.length+=n.length-t;for(let t=0;t<n.length;t++)this.j[e+t]=n[t];for(let t=0;t<i.length;t++)this.j[e+n.length+t]=i[t];return r}}Ht(e,t,n){let r=mt(this),i=r?{observableKind:`array`,object:this.v,type:Zn,debugObjectName:this.ct.tt,index:e,newValue:t,oldValue:n}:null;this.ct.reportChanged(),r&&gt(this,i)}Ft(e,t,n){let r=mt(this),i=r?{observableKind:`array`,object:this.v,debugObjectName:this.ct.tt,type:Xn,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;this.ct.reportChanged(),r&&gt(this,i)}Tt(e){return this.ct.reportObserved(),this.Wt(this.j[e])}Bt(e,t){let n=this.j;if(e<n.length){let r=n[e];if(ft(this)){let n=D(this,{type:Zn,object:this.v,index:e,newValue:t});if(!n)return;t=n.newValue}(t=this.A(t,r))!==r&&(n[e]=t,this.Ht(e,t,r))}else{let r=Array.from({length:e+1-n.length});r[r.length-1]=t,this.wt(n.length,0,r)}}},er={clear(){return this.splice(0)},replace(e){let t=this[k];return t.wt(0,t.j.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[k];switch(arguments.length){case 0:return[];case 1:return r.wt(e);case 2:return r.wt(e,t)}return r.wt(e,t,n)},spliceWithArray(e,t,n){return this[k].wt(e,t,n)},push(...e){let t=this[k];return t.wt(t.j.length,0,e),t.j.length},pop(){return this.splice(Math.max(this[k].j.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[k];return t.wt(0,0,e),t.j.length},reverse(){return j.trackingDerivation&&t(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){j.trackingDerivation&&t(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[k],n=t.ht(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};O(`at`,vt),O(`concat`,vt),O(`flat`,vt),O(`includes`,vt),O(`indexOf`,vt),O(`join`,vt),O(`lastIndexOf`,vt),O(`slice`,vt),O(`toString`,vt),O(`toLocaleString`,vt),O(`toSorted`,vt),O(`toSpliced`,vt),O(`with`,vt),O(`every`,yt),O(`filter`,yt),O(`find`,yt),O(`findIndex`,yt),O(`findLast`,yt),O(`findLastIndex`,yt),O(`flatMap`,yt),O(`forEach`,yt),O(`map`,yt),O(`some`,yt),O(`toReversed`,yt),O(`reduce`,bt),O(`reduceRight`,bt);let tr=l(`ObservableArrayAdministration`,$n),nr={},rr=`delete`;var ir=class{constructor(e,t=v,n=`ObservableMap`){this.A=void 0,this.tt=void 0,this[k]=nr,this.ft=void 0,this.dt=void 0,this.lt=void 0,this.st=void 0,this.ot=void 0,this.dehancer=void 0,this.A=t,this.tt=n,At(()=>{this.lt=g(`ObservableMap.keys()`),this.ft=new Map,this.dt=new Map,e&&this.merge(e)})}et(e){return this.ft.has(e)}has(e){if(!j.trackingDerivation)return this.et(e);let t=this.dt.get(e);if(!t){let n=t=new yn(this.et(e),y,`ObservableMap.key?`,!1);this.dt.set(e,n),n.onBUOL=new Set([()=>this.dt.delete(e)])}return t.get()}set(e,t){let n=this.et(e);if(ft(this)){let r=D(this,{type:n?Zn:`add`,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.Gt(e,t):this.Jt(e,t),this}delete(e){if(ft(this)&&!D(this,{type:rr,object:this,name:e}))return!1;if(this.et(e)){let t=mt(this),n=t?{observableKind:`map`,debugObjectName:this.tt,type:rr,object:this,oldValue:this.ft.get(e).rt,name:e}:null;return lt(()=>{var t;this.lt.reportChanged(),(t=this.dt.get(e))==null||t.Ot(!1),this.ft.get(e).Ot(void 0),this.ft.delete(e)}),t&&gt(this,n),!0}return!1}Gt(e,t){let n=this.ft.get(e);if((t=n.jt(t))!==j.UNCHANGED){let r=mt(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:Zn,object:this,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&gt(this,i)}}Jt(e,t){lt(()=>{var n;let r=new yn(t,this.A,`ObservableMap.key`,!1);this.ft.set(e,r),t=r.rt,(n=this.dt.get(e))==null||n.Ot(!0),this.lt.reportChanged()});let n=mt(this);n&&gt(this,n?{observableKind:`map`,debugObjectName:this.tt,type:`add`,object:this,name:e,newValue:t}:null)}get(e){return this.has(e)?this.Wt(this.ft.get(e).get()):this.Wt(void 0)}getOrInsert(e,t){return this.has(e)||this.set(e,t),this.get(e)}getOrInsertComputed(e,t){return this.has(e)||this.set(e,t(e)),this.get(e)}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}keys(){return this.lt.reportObserved(),this.ft.keys()}values(){let e=this,t=this.keys();return St({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:e.get(r)}}})}entries(){let e=this,t=this.keys();return St({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:[r,e.get(r)]}}})}[Symbol.iterator](){return this.entries()}forEach(e,t){for(let[n,r]of this)e.call(t,r,n,this)}merge(e){return ar(e)&&(e=new Map(e)),lt(()=>{o(e)?function(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>zt.propertyIsEnumerable.call(e,t))]:t}(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):u(e)?(function(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}(e)||t(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&t(20,e)}),this}clear(){lt(()=>{ke(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return lt(()=>{let n=function(e){if(u(e)||ar(e))return e;if(Array.isArray(e))return new Map(e);if(o(e)){let t=new Map;for(let n in e)t.set(n,e[n]);return t}return t(21,e)}(e),r=new Map,i=!1;for(let e of this.ft.keys())if(!n.has(e))if(this.delete(e))i=!0;else{let t=this.ft.get(e);r.set(e,t)}for(let[e,t]of n.entries()){let n=this.ft.has(e);if(this.set(e,t),this.ft.has(e)){let t=this.ft.get(e);r.set(e,t),n||(i=!0)}}if(!i)if(this.ft.size!==r.size)this.lt.reportChanged();else{let e=this.ft.keys(),t=r.keys(),n=e.next(),i=t.next();for(;!n.done;){if(n.value!==i.value){this.lt.reportChanged();break}n=e.next(),i=t.next()}}this.ft=r}),this}get size(){return this.lt.reportObserved(),this.ft.size}toString(){return`[object ObservableMap]`}toJSON(){return Array.from(this)}get[Symbol.toStringTag](){return`Map`}},ar=l(`ObservableMap`,ir);let or={};var sr=class{constructor(e,t=v,n=`ObservableSet`){this.tt=void 0,this[k]=or,this.ft=new Set,this.ct=void 0,this.ot=void 0,this.st=void 0,this.dehancer=void 0,this.A=void 0,this.tt=n,this.A=(e,r)=>t(e,r,n),At(()=>{this.ct=g(this.tt),e&&this.replace(e)})}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){lt(()=>{ke(()=>{for(let e of this.ft.values())this.delete(e)})})}forEach(e,t){for(let n of this)e.call(t,n,n,this)}get size(){return this.ct.reportObserved(),this.ft.size}add(e){if(ft(this)){let t=D(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){lt(()=>{e=this.A(e,void 0),this.ft.add(e),this.ct.reportChanged()});let t=mt(this);t&&gt(this,t?{observableKind:`set`,debugObjectName:this.tt,type:`add`,object:this,newValue:e}:null)}return this}delete(e){if(ft(this)&&!D(this,{type:rr,object:this,oldValue:e}))return!1;if(this.has(e)){let t=mt(this),n=t?{observableKind:`set`,debugObjectName:this.tt,type:rr,object:this,oldValue:e}:null;return lt(()=>{this.ct.reportChanged(),this.ft.delete(e)}),t&&gt(this,n),!0}return!1}has(e){return this.ct.reportObserved(),this.ft.has(this.Wt(e))}entries(){let e=this.values();return Ct({next(){let{value:t,done:n}=e.next();return n?{value:void 0,done:n}:{value:[t,t],done:n}}})}keys(){return this.values()}values(){this.ct.reportObserved();let e=this,t=this.ft.values();return Ct({next(){let{value:n,done:r}=t.next();return r?{value:void 0,done:r}:{value:e.Wt(n),done:r}}})}intersection(e){return new Set(this).intersection(e)}union(e){return new Set(this).union(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}replace(e){return cr(e)&&(e=new Set(e)),Array.isArray(e)||d(e)?lt(()=>{let t=d(e)?e:new Set(e);if(t.size!==0)if(this.ft.size!==0){for(let e of this.ft.values())t.has(this.Wt(e))||this.delete(e);t.forEach(e=>this.add(e))}else t.forEach(e=>this.add(e));else this.clear()}):e!=null&&t(41,e),this}toJSON(){return Array.from(this)}toString(){return`[object ObservableSet]`}[Symbol.iterator](){return this.values()}get[Symbol.toStringTag](){return`Set`}},cr=l(`ObservableSet`,sr);let lr=Object.create(null),ur=`remove`;var dr=class{constructor(e,t=new Map,n,r=Zt){this.h=void 0,this.j=void 0,this.tt=void 0,this.ut=void 0,this.lt=void 0,this.ot=void 0,this.st=void 0,this.v=void 0,this.p=void 0,this.Xt=void 0,this.Qt=void 0,this.O=void 0,this.V=void 0,this.h=e,this.j=t,this.tt=n,this.ut=r,this.lt=new Kt(`ObservableObject.keys`),this.p=o(this.h)}_(e){return(this.j.get(e)??this.vt(e)??this.bt(e)).get()}vt(e){let t=this.O?.get(e);if(!t)return;this.O.delete(e),this.O.size===0&&(this.O=void 0);let n=t();return this.j.set(e,n),n}bt(e){let t=this.V?.get(e);if(!t)return;this.V.delete(e),this.V.size===0&&(this.V=void 0);let n=t();return this.j.set(e,n),n}M(e,t){let n=this.j.get(e)??this.vt(e)??this.bt(e);if(n instanceof xn)return n.set(t),!0;if(ft(this)){let n=D(this,{type:Zn,object:this.v||this.h,name:e,newValue:t});if(!n)return null;t=n.newValue}if((t=n.jt(t))!==j.UNCHANGED){let r=mt(this),i=r?{type:Zn,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&gt(this,i)}return!0}Tt(e){return j.trackingDerivation&&!p(this.h,e)&&this.et(e),this.h[e]}Bt(e,t,n=!1){return p(this.h,e)?this.j.has(e)?this.M(e,t):n?Reflect.set(this.h,e,t):(this.h[e]=t,!0):this.u(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.ut,n)}et(e){if(!j.trackingDerivation)return e in this.h;this.Qt||=new Map;let t=this.Qt.get(e);return t||(t=new yn(e in this.h,y,`ObservableObject.key?`,!1),this.Qt.set(e,t)),t.get()}u(e,t,n,r=!1){return!0===n&&(n=this.ut),!1===n?this.l(e,t,r):n.u(this,e,t,r)}l(e,t,n=!1){try{Fe();let r=this.Dt(e);if(!r)return r;if(ft(this)){let n=D(this,{object:this.v||this.h,name:e,type:`add`,newValue:t.value});if(!n)return null;let{newValue:r}=n;t.value!==r&&(t=It({},t,{value:r}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else Rt(this.h,e,t);this.Yt(e,t.value)}finally{Ie()}return!0}S(e,t,n,r=!1){try{Fe();let i=this.Dt(e);if(!i)return i;if(ft(this)){let n=D(this,{object:this.v||this.h,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let a=Tt(e),o={configurable:!j.safeDescriptors||this.p,enumerable:!0,get:a.get,set:a.set};if(r){if(!Reflect.defineProperty(this.h,e,o))return!1}else Rt(this.h,e,o);let s=new yn(t,n,`ObservableObject.key`,!1);this.j.set(e,s),this.Yt(e,s.rt)}finally{Ie()}return!0}m(e,t,n=!1){try{Fe();let r=this.Dt(e);if(!r)return r;if(ft(this)&&!D(this,{object:this.v||this.h,name:e,type:`add`,newValue:void 0}))return null;t.name||=`ObservableObject.key`,t.context=this.v||this.h;let i=Tt(e),a={configurable:!j.safeDescriptors||this.p,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.h,e,a))return!1}else Rt(this.h,e,a);this.j.set(e,new xn(t)),this.Yt(e,void 0)}finally{Ie()}return!0}Dt(e,t=!1){if(!p(this.h,e))return!0;if(ft(this)&&!D(this,{object:this.v||this.h,name:e,type:ur}))return null;try{var n;Fe();let r=mt(this),i=this.j.get(e),a;if(i||!r||(a=Lt(this.h,e)?.value),t){if(!Reflect.deleteProperty(this.h,e))return!1}else delete this.h[e];i&&(this.j.delete(e),i instanceof yn&&(a=i.rt),ze(i)),this.lt.reportChanged(),(n=this.Qt)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&gt(this,{type:ur,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{Ie()}return!0}Yt(e,t){var n;let r=mt(this);r&&r&&gt(this,r?{type:`add`,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,name:e,newValue:t}:null),(n=this.Qt)==null||(n=n.get(e))==null||n.set(!0),this.lt.reportChanged()}it(){return this.lt.reportObserved(),Wt(this.h)}nt(){return this.lt.reportObserved(),Object.keys(this.h)}};let fr=l(`ObservableObjectAdministration`,dr),pr=zt.toString,mr=globalThis.Iterator?.prototype||{};e.$mobx=k,e.FlowCancellationError=Un,e.ObservableMap=ir,e.ObservableSet=sr,e.Reaction=On,e._allowStateChanges=we,e._allowStateChangesInsideComputed=We,e._allowStateReadsEnd=function(e){j.allowStateReads=e},e._allowStateReadsStart=function(e){let t=j.allowStateReads;return j.allowStateReads=e,t},e._autoAction=Rn,e._autoActionBound=Bn,e._endAction=Ce,e._getAdministration=Ot,e._getGlobalState=function(){return j},e._interceptReads=function(e,t,n){let r;return ar(e)||xt(e)||bn(e)?r=Ot(e):Et(e)&&(r=Ot(e,t)),r.dehancer=typeof t==`function`?t:n,()=>{r.dehancer=void 0}},e._isComputingDerivation=function(){return j.trackingDerivation!==null},e._resetGlobalState=function(){let e=new Tn;for(let t in e)wn.indexOf(t)===-1&&(j[t]=e[t]);j.allowStateChanges=!j.enforceActions},e._startAction=Se,e.action=Ln,e.actionBound=zn,e.autorun=Ke,e.compareDefault=Jt,e.compareIdentity=function(e,t){return e===t},e.compareShallow=function(e,t){return jt(e,t,1)},e.compareStructural=_,e.computed=pn,e.computedStruct=fn,e.configure=function(e){!0===e.isolateGlobalState&&function(){if((j.pendingReactions.length||j.inBatch||j.isRunningReactions)&&t(36),Dn=!0,En){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),j=new Tn}}();let{enforceActions:n}=e;if(n!==void 0){let e=n===Hn?Hn:n===`observed`;j.enforceActions=e,j.allowStateChanges=!0!==e&&e!==Hn}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(j[t]=!!e[t])}),j.allowStateReads=!j.observableRequiresReaction,e.reactionScheduler&&function(e){let t=An;An=n=>e(()=>t(n))}(e.reactionScheduler)},e.createAtom=g,e.defineProperty=function(e,n,r){if(Et(e))return e[k].l(n,r);t(39)},e.entries=function(e){return Et(e)?rt(e).map(t=>[t,e[t]]):ar(e)?rt(e).map(t=>[t,e.get(t)]):cr(e)?Array.from(e.entries()):xt(e)?e.map((e,t)=>[t,e]):void t(7)},e.extendObservable=Ye,e.flow=Kn,e.flowBound=qn,e.flowResult=function(e){return e},e.get=function(e,n){if(it(e,n))return Et(e)?e[k].Tt(n):ar(e)?e.get(n):xt(e)?e[n]:void t(11)},e.getAtom=Dt,e.getDebugName=kt,e.getDependencyTree=function(e,t){return Xe(Dt(e,t))},e.getObserverTree=function(e,t){return Ze(Dt(e,t))},e.has=it,e.intercept=function(e,t,n){return r(n)?function(e,t,n){return pt(Ot(e,t),n)}(e,t,n):function(e,t){return pt(Ot(e),t)}(e,t)},e.isAction=Ge,e.isBoxedObservable=bn,e.isComputed=function(e){return et(e)},e.isComputedProp=function(e,t){return et(e,t)},e.isFlow=$e,e.isFlowCancellationError=function(e){return e instanceof Un},e.isObservable=nt,e.isObservableArray=xt,e.isObservableMap=ar,e.isObservableObject=Et,e.isObservableProp=function(e,t){return tt(e,t)},e.isObservableSet=cr,e.keys=rt,e.makeAutoObservable=function(e,t,n){return o(e)?Ye(e,e,t,n):(At(()=>{let r=wt(e,n)[k];if(!e[Yn]){let t=Object.getPrototypeOf(e),n=new Set([...Wt(e),...Wt(t)]);n.delete(`constructor`),n.delete(k),c(t,Yn,n)}e[Yn].forEach(e=>_t(r,e,!t||!(e in t)||t[e]))}),e)},e.makeObservable=function(e,t,n){return At(()=>{let r=wt(e,n)[k];Wt(t).forEach(e=>_t(r,e,t[e]))}),e},e.observable=ln,e.observableDeep=sn,e.observableRef=an,e.observableShallow=on,e.observableStruct=cn,e.observe=function(e,t,n,i){return r(n)?function(e,t,n,r){return ot(Ot(e,t),n,r)}(e,t,n,i):function(e,t,n){let r=Ot(e);if(xt(e))n&&t({observableKind:`array`,object:r.v,debugObjectName:r.ct.tt,type:`splice`,index:0,added:r.j.slice(),addedCount:r.j.length,removed:[],removedCount:0});else if(!ar(e)&&!cr(e)&&!Et(e))return ot(r,t,n);return ht(r,t)}(e,t,n)},e.onBecomeObserved=function(e,t,n){return Je(`onBO`,e,t,n)},e.onBecomeUnobserved=function(e,t,n){return Je(`onBUO`,e,t,n)},e.onReactionError=function(e){return j.globalReactionErrorHandlers.push(e),()=>{let t=j.globalReactionErrorHandlers.indexOf(e);t>=0&&j.globalReactionErrorHandlers.splice(t,1)}},e.override=Yt,e.ownKeys=at,e.reaction=function(e,t,n=Vt){function r(){if(p=!1,h.isDisposed)return;let t=!1,r=d;h.track(()=>{let n=we(!1,()=>e(h));t=f||!m(d,n),d=n}),(f&&n.fireImmediately||!f&&t)&&o(d,r,h),f=!1}var i;let a=n.name??`Reaction`,o=Ln(a,n.onError?(s=n.onError,c=t,function(){try{return c.apply(this,arguments)}catch(e){s.call(this,e)}}):t);var s,c;let l=!n.scheduler&&!n.delay,u=qe(n),d,f=!0,p=!1,m=n.equals||Jt,h=new On(a,()=>{f||l?r():p||(p=!0,u(r))},n.onError,n.requiresObservable);return n!=null&&(i=n.signal)!=null&&i.aborted||h.Y(),h.Z(n?.signal)},e.remove=function(e,n){Et(e)?e[k].Dt(n):ar(e)||cr(e)?e.delete(n):xt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=We,e.set=function e(n,r,i){if(arguments.length===2&&!cr(n)){Fe();let t=r;try{for(let r in t)e(n,r,t[r])}finally{Ie()}return}Et(n)?n[k].Bt(r,i):ar(n)?n.set(r,i):cr(n)?n.add(r):xt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(42,r),Fe(),r>=n.length&&(n.length=r+1),n[r]=i,Ie()):t(8)},e.spy=function(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}},e.toJS=function(e){return ct(e,new Map)},e.transaction=lt,e.untracked=ke,e.values=function(e){return Et(e)?rt(e).map(t=>e[t]):ar(e)?rt(e).map(t=>e.get(t)):cr(e)?Array.from(e.values()):xt(e)?e.slice():void t(6)},e.when=function(e,t,n){return arguments.length===1||t&&typeof t==`object`?function(e,t){var n;if(t!=null&&(n=t.signal)!=null&&n.aborted)return It(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let r,i,a=new Promise((n,a)=>{var o;let s=ut(e,n,It({},t,{onError:a}));r=()=>{s(),a(Error(`WHEN_CANCELLED`))},i=()=>{s(),a(Error(`WHEN_ABORTED`))},t==null||(o=t.signal)==null||o.addEventListener==null||o.addEventListener(`abort`,i)}).finally(()=>{var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,i)});return a.cancel=r,a}(e,t):ut(e,t,n||{})}})),Jx=ke((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t={0:`Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'`,1(e,t){return`Cannot apply '${e}' to '${t.toString()}': Field not found.`},5:`'keys()' can only be used on observable objects, arrays, sets and maps`,6:`'values()' can only be used on observable objects, arrays, sets and maps`,7:`'entries()' can only be used on observable objects, arrays and maps`,8:`'set()' can only be used on observable objects, arrays and maps`,9:`'remove()' can only be used on observable objects, arrays and maps`,10:`'has()' can only be used on observable objects, arrays and maps`,11:`'get()' can only be used on observable objects, arrays and maps`,12:`Invalid annotation`,13:`Dynamic observable objects cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,14:`Intercept handlers should return nothing or a change object`,15:`Observable arrays cannot be frozen. If you're passing observables to 3rd party component/function that calls Object.freeze, pass copy instead: toJS(observable)`,16:`Modification exception: the internal structure of an observable array was changed.`,19(e){return`Cannot initialize from classes that inherit from Map: `+e.constructor.name},20(e){return`Cannot initialize map from `+e},21(e){return`Cannot convert to map from '${e}'`},23:`It is not possible to get index atoms from arrays`,24(e){return`Cannot obtain administration from `+e},25(e,t){return`the entry '${e}' does not exist in the observable map '${t}'`},26:`please specify a property`,27(e,t){return`no observable property '${e.toString()}' found on the observable object '${t}'`},28(e){return`Cannot obtain atom from `+e},29:`Expecting some object`,30:`invalid action stack. did you forget to finish an action?`,31:`missing option for computed: get`,32(e,t){return`Cycle detected in computation ${e}: ${t}`},33(e){return`The setter of computed value '${e}' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?`},34(e){return`[ComputedValue '${e}'] It is not possible to assign a new value to a computed value.`},35:"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`",36:`isolateGlobalState should be called before MobX is running any reactions`,37(e){return`[mobx] \`observableArray.${e}()\` mutates the array in-place, which is not allowed inside a derivation. Use \`array.slice().${e}()\` instead`},38:`'ownKeys()' can only be used on observable objects`,39:`'defineProperty()' can only be used on observable objects`,40(e){return`Out of range: `+e},41(e){return`Cannot initialize set from `+e},42(e){return`Invalid index: '${e}'`},43(e,t,n){return`Cannot apply '${e}' to '${t}' (kind: ${n}):\n'${e}' can only be used on properties with a function value.`},44(e){return`'${e}' can only be used with 'makeObservable'`}};function n(e,...n){{let r=typeof e==`string`?e:t[e];throw typeof r==`function`&&(r=r.apply(null,n)),Error(`[MobX] ${r}`)}}let r=Object.assign,i=Object.getOwnPropertyDescriptor,a=Object.defineProperty,o=Object.prototype,s=[];Object.freeze(s);let c={};Object.freeze(c);let l=Object.toString();function u(){return++A.mobxGuid}function d(e){let t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}let f=()=>{};function p(e){return typeof e==`function`}function m(e){switch(typeof e){case`string`:case`symbol`:case`number`:return!0}return!1}function h(e){return typeof e==`object`&&!!e}function g(e){if(!h(e))return!1;let t=Object.getPrototypeOf(e);if(t==null)return!0;let n=ae(t,`constructor`)&&t.constructor;return typeof n==`function`&&n.toString()===l}function _(e){let t=e?.constructor;return t?t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`:!1}function v(e,t,n){a(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function y(e,t,n){a(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function b(e,t){let n=`isMobX`+e;return t.prototype[n]=!0,function(e){return h(e)&&e[n]===!0}}function ee(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function x(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function S(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function te(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let ne=Reflect.ownKeys;function re(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function ie(e){return e===null?null:typeof e==`object`?``+e:e}function ae(e,t){return o.hasOwnProperty.call(e,t)}let C=Object.getOwnPropertyDescriptors;function w(e,t){return!!(e&t)}function oe(e,t,n){return n?e|=t:e&=~t,e}function se(e,t){t.includes(e.kind)||n(`The decorator applied to '${String(e.name)}' cannot be used on a ${e.kind} element`)}let T=Symbol(`mobx administration`);var ce=class{constructor(e=`Atom@`+u()){this.name_=void 0,this.flags_=0,this.observers_=null,this.lastAccessedBy_=0,this.lowestObserverState_=-1,this.onBOL=void 0,this.onBUOL=void 0,this.name_=e}get isBeingObserved(){return w(this.flags_,1)}set isBeingObserved(e){this.flags_=oe(this.flags_,1,e)}get isPendingUnobservation(){return w(this.flags_,2)}set isPendingUnobservation(e){this.flags_=oe(this.flags_,2,e)}get diffValue(){return+!!w(this.flags_,4)}set diffValue(e){this.flags_=oe(this.flags_,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return dn(this)}reportChanged(){sn(),fn(this),cn()}toString(){return this.name_}};let le=b(`Atom`,ce);function ue(e,t=f,n=f){let r=new ce(e);return t!==f&&(r.onBOL=new Set([t])),n!==f&&(r.onBUOL=new Set([n])),r}function de(e,t){return e===t}function fe(e,t){return Ri(e,t)}function pe(e,t){return Ri(e,t,1)}let me=Object.is;function he(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||Sr(e)?e:Array.isArray(e)?D.array(e,{name:n}):g(e)?D.object(e,void 0,{name:n}):ee(e)?D.map(e,{name:n}):S(e)?D.set(e,{name:n}):typeof e==`function`&&!Bn(e)&&!pr(e)?_(e)?lr(e):In(n,e):e}function ge(e,t,r){if(e==null||N(e)||mi(e)||vi(e)||Ci(e))return e;if(Array.isArray(e))return D.array(e,{name:r,deep:!1});if(g(e))return D.object(e,void 0,{name:r,deep:!1});if(ee(e))return D.map(e,{name:r,deep:!1});if(S(e))return D.set(e,{name:r,deep:!1});n(`The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets`)}function _e(e){return e}function ve(e,t){return Sr(e)&&n(`observable.struct should not be used with observable values`),Ri(e,t)?t:e}let ye=`override`,be={annotationType_:ye,make_:Se,extend_:Ce};function xe(e){return e.annotationType_===ye}function Se(e,t){return e.isPlainObject_&&n(`Cannot apply '${this.annotationType_}' to '${e.name_}.${t.toString()}':\n'${this.annotationType_}' cannot be used on plain objects.`),ae(e.appliedAnnotations_,t)||n(`'${e.name_}.${t.toString()}' is annotated with '${this.annotationType_}', but no such annotated member was found on prototype.`),0}function Ce(e,t,r,i){n(44,this.annotationType_)}function we(e,t){return{annotationType_:e,options_:t,make_:Te,extend_:Ee}}function Te(e,t,n,r){var i;return(i=this.options_)!=null&&i.bound?this.extend_(e,t,n,!1)===null?0:1:r===e.target_?this.extend_(e,t,n,!1)===null?0:2:Bn(n.value)?1:(a(r,t,ke(e,this,t,n,!1)),2)}function Ee(e,t,n,r){let i=ke(e,this,t,n);return e.defineProperty_(t,i,r)}function De(e,t,r){se(r,[`method`,`field`]);let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>St(s.options_?.name??a.toString(),e,s.options_?.autoAction??!1);if(i==`field`)return function(e){var t;let n=e;return Bn(n)||(n=c(n)),(t=s.options_)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n};if(i==`method`){var l;return Bn(t)||(t=c(t)),(l=s.options_)!=null&&l.bound&&o(function(){let e=this,t=e[a].bind(e);t.isMobxAction=!0,e[a]=t}),t}n(43,s.annotationType_,String(a),i)}function Oe(e,{annotationType_:t},r,{value:i}){p(i)||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on properties with a function value.`)}function ke(e,t,n,r,i=A.safeDescriptors){var a,o;Oe(e,t,n,r);let{value:s}=r;return(a=t.options_)!=null&&a.bound&&(s=s.bind(e.proxy_??e.target_)),{value:St(t.options_?.name??n.toString(),s,t.options_?.autoAction??!1,(o=t.options_)!=null&&o.bound?e.proxy_??e.target_:void 0),configurable:i?e.isPlainObject_:!0,enumerable:!1,writable:!i}}function Ae(e,t){return{annotationType_:e,options_:t,make_:je,extend_:E}}function je(e,t,n,r){var i;return r===e.target_?this.extend_(e,t,n,!1)===null?0:2:(i=this.options_)!=null&&i.bound&&(!ae(e.target_,t)||!pr(e.target_[t]))&&this.extend_(e,t,n,!1)===null?0:pr(n.value)?1:(a(r,t,Pe(e,this,t,n,!1,!1)),2)}function E(e,t,n,r){let i=Pe(e,this,t,n,this.options_?.bound);return e.defineProperty_(t,i,r)}function Me(e,t,n){var r;se(n,[`method`]);let{name:i,addInitializer:a}=n;return pr(t)||(t=lr(t)),(r=e.options_)!=null&&r.bound&&a(function(){let e=this,t=e[i].bind(e);t.isMobXFlow=!0,e[i]=t}),t}function Ne(e,{annotationType_:t},r,{value:i}){p(i)||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on properties with a generator function value.`)}function Pe(e,t,n,r,i,a=A.safeDescriptors){Ne(e,t,n,r);let{value:o}=r;return pr(o)||(o=lr(o)),i&&(o=o.bind(e.proxy_??e.target_),o.isMobXFlow=!0),{value:o,configurable:a?e.isPlainObject_:!0,enumerable:!1,writable:!a}}function Fe(e,t){return{annotationType_:e,options_:t,make_:Ie,extend_:Le}}function Ie(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Le(e,t,n,i){return ze(e,this,t,n),e.defineComputedProperty_(t,r({},this.options_,{get:n.get,set:n.set}),i)}function Re(e,t,n){se(n,[`getter`]);let i=e,{name:a,addInitializer:o}=n,s;function c(e,n){let o=r({},i.options_,{get:t,context:e});return o.name||=`${n.name_}.${a.toString()}`,new jt(o)}return o(function(){let e=Oi(this)[T],n=this,r=e.values_.get(a);r instanceof jt&&r.derivation!==t&&e.values_.delete(a),(e.lazyComputedKeys_??=new Map).set(a,()=>c(n,e))}),function(){let e=this[T],n=e.values_.get(a);if(n instanceof jt&&n.derivation!==t){let t=s?.get(this);return t||(t=c(this,e),(s??=new WeakMap).set(this,t)),t.get()}return e.getObservablePropValue_(a)}}function ze(e,{annotationType_:t},r,{get:i}){i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' can only be used on getter(+setter) properties.`)}function Be(e,t){return{annotationType_:e,options_:t,make_:Ve,extend_:He}}function Ve(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function He(e,t,n,r){return We(e,this,t,n),e.defineObservableProperty_(t,n.value,this.options_?.enhancer_??he,r)}function Ue(e,t,r){if(r.kind===`field`)throw n(`Please use \`@observable accessor ${String(r.name)}\` instead of \`@observable ${String(r.name)}\``);se(r,[`accessor`]);let i=e,{kind:a,name:o}=r;if(a!==`accessor`)return;function s(e,t){let n=Oi(e)[T];return(n.lazyObservableKeys_??=new Map).set(o,()=>new kt(t,i.options_?.enhancer_??he,`${n.name_}.${o.toString()}`,!1)),n}return{get(){return(this[T]??s(this,t.get.call(this))).getObservablePropValue_(o)},set(e){return(this[T]??s(this,e)).setObservablePropValue_(o,e)},init(e){return s(this,e),e}}}function We(e,{annotationType_:t},r,i){`value`in i||n(`Cannot apply '${t}' to '${e.name_}.${r.toString()}':\n'${t}' cannot be used on getter/setter properties`)}let Ge=Ke();function Ke(e){return{annotationType_:`true`,options_:e,make_:Ye,extend_:Xe}}let qe=[Ge];function Je(e){let t=e.deep!==!1,n=!!e.autoBind,r=!t|(n?2:0);return qe[r]??(qe[r]=Ke({deep:t,autoBind:n}))}function Ye(e,t,n,r){var i;if(n.get)return O.make_(e,t,n,r);if(n.set){let i=Bn(n.set)?n.set:St(t.toString(),n.set);return r===e.target_?e.defineProperty_(t,{configurable:A.safeDescriptors?e.isPlainObject_:!0,set:i})===null?0:2:(a(r,t,{configurable:!0,set:i}),2)}if(r!==e.target_&&typeof n.value==`function`){var o;if(_(n.value)){var s;return((s=this.options_)!=null&&s.autoBind?ur:lr).make_(e,t,n,r)}return((o=this.options_)!=null&&o.autoBind?Rn:In).make_(e,t,n,r)}let c=this.options_?.deep===!1?ut:D;return typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),c.make_(e,t,n,r)}function Xe(e,t,n,r){var i;return n.get?O.extend_(e,t,n,r):n.set?e.defineProperty_(t,{configurable:A.safeDescriptors?e.isPlainObject_:!0,set:St(t.toString(),n.set)},r):(typeof n.value==`function`&&(i=this.options_)!=null&&i.autoBind&&(n.value=n.value.bind(e.proxy_??e.target_)),(this.options_?.deep===!1?ut:D).extend_(e,t,n,r))}function Ze(e,t){return r(function(r,i){if(i&&typeof i.kind==`string`)return t(e,r,i);n(`Invalid arguments for \`${e.annotationType_}\``)},e)}let Qe={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Qe);function $e(e){return e||Qe}let et=Be(`observable`),tt=Be(`observable.ref`,{enhancer_:_e}),nt=Be(`observable.shallow`,{enhancer_:ge}),rt=Be(`observable.struct`,{enhancer_:ve});function it(e){return Ze(e,Ue)}function at(e){return e.deep===!0?he:e.deep===!1?_e:st(e.defaultDecorator)}function ot(e){return e?e.defaultDecorator??Je(e):void 0}function st(e){return e?e.options_?.enhancer_??he:he}function ct(e,t,n){return t&&typeof t.kind==`string`?Ue(et,e,t):Sr(e)?e:g(e)?D.object(e,t,n):Array.isArray(e)?D.array(e,t):ee(e)?D.map(e,t):S(e)?D.set(e,t):typeof e==`object`&&e?e:D.box(e,t)}let lt={box(e,t){let n=$e(t);return new kt(e,at(n),n.name,!0,n.equals)},array(e,t){let n=$e(t);return si(e,at(n),n.name)},map(e,t){let n=$e(t);return new _i(e,at(n),n.name)},set(e,t){let n=$e(t);return new Si(e,at(n),n.name)},object(e,t,n){return Ii(()=>Zn(Kr({},n),e,t))}},ut=it(tt),dt=it(nt),ft=it(et),pt=it(rt);var D=r(ct,et,lt);let mt=`computed`;function ht(e){return Ze(e,Re)}let gt=Fe(mt),_t=ht(Fe(`computed.struct`,{equals:fe})),O=function(e,t){if(t&&typeof t.kind==`string`)return Re(gt,e,t);if(g(e))return ht(Fe(mt,e));p(e)||n("First argument to `computed` should be an expression."),p(t)&&n("A setter as second argument is no longer supported, use `{ set: fn }` option instead");let r=g(t)?t:{};return r.get=e,r.name||=e.name||``,new jt(r)};r(O,gt);let vt=0,yt=1,bt=i(()=>{},`name`)?.configurable??!1,xt={value:`action`,configurable:!0,writable:!1,enumerable:!1};function St(e,t,r=!1,i){p(t)||n("`action` can only be invoked on functions"),(typeof e!=`string`||!e)&&n(`actions should have valid names, got: '${e}'`);function o(){return Ct(e,r,t,i||this,arguments)}return o.isMobxAction=!0,o.toString=()=>t.toString(),bt&&(xt.value=e,a(o,`name`,xt)),o}function Ct(e,t,n,r,i){let a=wt(e,t,r,i);try{return n.apply(r,i)}catch(e){throw a.error_=e,e}finally{Tt(a)}}function wt(e,t,n,r){let i=Sn()&&!!e,a=0;i&&(a=Date.now(),wn({type:j,name:e,object:n,arguments:r?Array.from(r):s}));let o=A.trackingDerivation,c=!t||!o;sn();let l=A.allowStateChanges;c&&(Wt(),l=Dt(!0));let u=A.allowStateReads;k(!0);let d={runAsAction_:c,prevDerivation_:o,prevAllowStateChanges_:l,prevAllowStateReads_:u,notifySpy_:i,startTime_:a,actionId_:yt++,parentActionId_:vt};return vt=d.actionId_,d}function Tt(e){vt!==e.actionId_&&n(30),vt=e.parentActionId_,e.error_!==void 0&&(A.suppressReactionErrors=!0),Ot(e.prevAllowStateChanges_),Kt(e.prevAllowStateReads_),cn(),e.runAsAction_&&Gt(e.prevDerivation_),e.notifySpy_&&En({time:Date.now()-e.startTime_}),A.suppressReactionErrors=!1}function Et(e,t){let n=Dt(e);try{return t()}finally{Ot(n)}}function Dt(e){let t=A.allowStateChanges;return A.allowStateChanges=e,t}function Ot(e){A.allowStateChanges=e}var kt=class extends ce{constructor(e,t,n=`ObservableValue@`+u(),r=!0,i=me){super(n),this.enhancer_=void 0,this.name_=void 0,this.equals_=void 0,this.hasUnreportedChange_=!1,this.interceptors_=void 0,this.changeListeners_=void 0,this.value_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,this.equals_=i,this.value_=t(e,void 0,n),r&&Sn()&&Cn({type:`create`,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:this.value_})}dehanceValue(e){return this.dehancer===void 0?e:this.dehancer(e)}set(e){let t=this.value_;if(e=this.prepareNewValue_(e),e!==A.UNCHANGED){let n=Sn();n&&wn({type:ii,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:e,oldValue:t}),this.setNewValue_(e),n&&En()}}prepareNewValue_(e){if(Lt(this),qr(this)){let t=Yr(this,{object:this,type:ii,newValue:e});if(!t)return A.UNCHANGED;e=t.newValue}return e=this.enhancer_(e,this.value_,this.name_),this.equals_(this.value_,e)?A.UNCHANGED:e}setNewValue_(e){let t=this.value_;this.value_=e,this.reportChanged(),Xr(this)&&Qr(this,{type:ii,object:this,newValue:e,oldValue:t})}get(){return this.reportObserved(),this.dehanceValue(this.value_)}raw(){return this.value_}toJSON(){return this.get()}toString(){return`${this.name_}[${this.value_}]`}valueOf(){return ie(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let At=b(`ObservableValue`,kt);var jt=class{constructor(e){this.dependenciesState_=-1,this.observing_=[],this.newObserving_=null,this.observers_=null,this.runId_=0,this.lastAccessedBy_=0,this.lowestObserverState_=0,this.unboundDepsCount_=0,this.value_=new Nt(null),this.name_=void 0,this.triggeredBy_=void 0,this.flags_=0,this.derivation=void 0,this.setter_=void 0,this.scope_=void 0,this.equals_=void 0,this.requiresReaction_=void 0,this.keepAlive_=void 0,this.onBOL=void 0,this.onBUOL=void 0,e.get||n(31),this.derivation=e.get,this.name_=e.name||`ComputedValue@`+u(),e.set&&(this.setter_=St(this.name_+`-setter`,e.set)),this.equals_=e.equals||me,this.scope_=e.context,this.requiresReaction_=e.requiresReaction,this.keepAlive_=!!e.keepAlive}onBecomeStale_(){mn(this)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}get isComputing(){return w(this.flags_,1)}set isComputing(e){this.flags_=oe(this.flags_,1,e)}get isRunningSetter(){return w(this.flags_,2)}set isRunningSetter(e){this.flags_=oe(this.flags_,2,e)}get isBeingObserved(){return w(this.flags_,4)}set isBeingObserved(e){this.flags_=oe(this.flags_,4,e)}get isPendingUnobservation(){return w(this.flags_,8)}set isPendingUnobservation(e){this.flags_=oe(this.flags_,8,e)}get diffValue(){return+!!w(this.flags_,16)}set diffValue(e){this.flags_=oe(this.flags_,16,e===1)}get(){if(this.isComputing&&n(32,this.name_,this.derivation),A.inBatch===0&&(!this.observers_||this.observers_.size===0)&&!this.keepAlive_)Ft(this)&&(this.warnAboutUntrackedRead_(),sn(),this.value_=this.computeValue_(!1),cn());else{let e=this.isBeingObserved;if(dn(this),Ft(this)){let e=A.trackingContext;!e&&(this.keepAlive_||this.isBeingObserved)&&(A.trackingContext=this),this.trackAndCompute()&&pn(this),A.trackingContext=e}else !e&&this.isBeingObserved&&this.observing_.forEach(un)}let e=this.value_;if(Pt(e))throw e.cause;return e}set(e){if(this.setter_){this.isRunningSetter&&n(33,this.name_),this.isRunningSetter=!0;try{this.setter_.call(this.scope_,e)}finally{this.isRunningSetter=!1}}else n(34,this.name_)}trackAndCompute(){let e=this.value_,t=this.dependenciesState_===-1,n=this.computeValue_(!0),r=t||Pt(e)||Pt(n)||!this.equals_(e,n);return r&&(this.value_=n,Sn()&&Cn({observableKind:`computed`,debugObjectName:this.name_,object:this.scope_,type:`update`,oldValue:e,newValue:n})),r}computeValue_(e){this.isComputing=!0;let t=Dt(!1),n;if(e)n=zt(this,this.derivation,this.scope_);else if(A.disableErrorBoundaries===!0)n=this.derivation.call(this.scope_);else try{n=this.derivation.call(this.scope_)}catch(e){n=new Nt(e)}return Ot(t),this.isComputing=!1,n}suspend_(){this.keepAlive_||(Ht(this),this.value_=void 0)}warnAboutUntrackedRead_(){(typeof this.requiresReaction_==`boolean`?this.requiresReaction_:A.computedRequiresReaction)&&console.warn(`[mobx] Computed value '${this.name_}' is being read outside a reactive context. Doing a full recompute.`)}toString(){return`${this.name_}[${this.derivation.toString()}]`}valueOf(){return ie(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let Mt=b(`ComputedValue`,jt);var Nt=class{constructor(e){this.cause=void 0,this.cause=e}};function Pt(e){return e instanceof Nt}function Ft(e){switch(e.dependenciesState_){case 0:return!1;case-1:case 2:return!0;case 1:{let t=k(!0),n=Wt(),r=e.observing_,i=r.length;for(let a=0;a<i;a++){let i=r[a];if(Mt(i)){if(A.disableErrorBoundaries)i.get();else try{i.get()}catch{return Gt(n),Kt(t),!0}if(e.dependenciesState_===2)return Gt(n),Kt(t),!0}}return qt(e),Gt(n),Kt(t),!1}}}function It(){return A.trackingDerivation!==null}function Lt(e){let t=!!e.observers_&&e.observers_.size>0;!A.allowStateChanges&&(t||A.enforceActions===`always`)&&console.warn(`[MobX] `+(A.enforceActions?`Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: `:`Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: `)+e.name_)}function Rt(e){!A.allowStateReads&&A.observableRequiresReaction&&console.warn(`[mobx] Observable '${e.name_}' being read outside a reactive context.`)}function zt(e,t,n){let r=k(!0);qt(e),e.newObserving_=Array(e.runId_===0?100:e.observing_.length),e.unboundDepsCount_=0,e.runId_=++A.runId;let i=A.trackingDerivation;A.trackingDerivation=e,A.inBatch++;let a;if(A.disableErrorBoundaries===!0)a=t.call(n);else try{a=t.call(n)}catch(e){a=new Nt(e)}return A.inBatch--,A.trackingDerivation=i,Vt(e),Bt(e),Kt(r),a}function Bt(e){e.observing_.length===0&&(typeof e.requiresObservable_==`boolean`?e.requiresObservable_:A.reactionRequiresObservable)&&console.warn(`[mobx] Derivation '${e.name_}' is created/updated without reading any observable value.`)}function Vt(e){let t=e.observing_,n=e.observing_=e.newObserving_,r=0,i=0,a=e.unboundDepsCount_;for(let e=0;e<a;e++){let t=n[e];t.diffValue===0&&(t.diffValue=1,i!==e&&(n[i]=t),i++),t.dependenciesState_>r&&(r=t.dependenciesState_)}for(n.length=i,e.newObserving_=null,a=t.length;a--;){let n=t[a];n.diffValue===0&&an(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,rn(t,e))}r!==0&&(e.dependenciesState_=r,e.onBecomeStale_())}function Ht(e){let t=e.observing_;e.observing_=[];let n=t.length;for(;n--;)an(t[n],e);e.dependenciesState_=-1}function Ut(e){let t=Wt();try{return e()}finally{Gt(t)}}function Wt(){let e=A.trackingDerivation;return A.trackingDerivation=null,e}function Gt(e){A.trackingDerivation=e}function k(e){let t=A.allowStateReads;return A.allowStateReads=e,t}function Kt(e){A.allowStateReads=e}function qt(e){if(e.dependenciesState_===0)return;e.dependenciesState_=0;let t=e.observing_,n=t.length;for(;n--;)t[n].lowestObserverState_=0}let Jt=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Yt=class{constructor(){this.version=7,this.UNCHANGED={},this.trackingDerivation=null,this.trackingContext=null,this.runId=0,this.mobxGuid=0,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.isRunningReactions=!1,this.isRunningUnobservations=!1,this.allowStateChanges=!1,this.allowStateReads=!0,this.enforceActions=!0,this.spyListeners=[],this.globalReactionErrorHandlers=[],this.computedRequiresReaction=!1,this.reactionRequiresObservable=!1,this.observableRequiresReaction=!1,this.disableErrorBoundaries=!1,this.suppressReactionErrors=!1,this.safeDescriptors=!0}};let Xt=!0,Zt=!1,A=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Xt=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(Xt=!1),Xt?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Yt):(setTimeout(()=>{Zt||n(35)},1),new Yt)}();function Qt(){if((A.pendingReactions.length||A.inBatch||A.isRunningReactions)&&n(36),Zt=!0,Xt){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),A=new Yt}}function $t(){return A}function en(){let e=new Yt;for(let t in e)Jt.indexOf(t)===-1&&(A[t]=e[t]);A.allowStateChanges=!A.enforceActions}function tn(e){return!!e.observers_&&e.observers_.size>0}function nn(e){return e.observers_??new Set}function rn(e,t){(e.observers_??=new Set).add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function an(e,t){let n=e.observers_;n&&(n.delete(t),n.size===0&&on(e))}function on(e){e.isPendingUnobservation===!1&&(e.isPendingUnobservation=!0,A.pendingUnobservations.push(e))}function sn(){A.inBatch++}function cn(){--A.inBatch===0&&(vn(),!A.isRunningUnobservations&&A.pendingUnobservations.length>0&&ln())}function ln(){A.isRunningUnobservations=!0;try{let e=A.pendingUnobservations;for(let t=0;t<e.length;t++){let n=e[t];n.isPendingUnobservation=!1,(!n.observers_||n.observers_.size===0)&&(n.observers_=null,n.isBeingObserved&&(n.isBeingObserved=!1,n.onBUO()),n instanceof jt&&n.suspend_())}A.pendingUnobservations=[]}finally{A.isRunningUnobservations=!1}}function un(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.observing_)==null||t.forEach(un))}function dn(e){Rt(e);let t=A.trackingDerivation;return t===null?((!e.observers_||e.observers_.size===0)&&A.inBatch>0&&on(e),!1):(t.runId_!==e.lastAccessedBy_&&(e.lastAccessedBy_=t.runId_,t.newObserving_[t.unboundDepsCount_++]=e,!e.isBeingObserved&&A.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function fn(e){var t;e.lowestObserverState_!==2&&(e.lowestObserverState_=2,(t=e.observers_)==null||t.forEach(e=>{e.dependenciesState_===0&&e.onBecomeStale_(),e.dependenciesState_=2}))}function pn(e){var t;e.lowestObserverState_!==2&&(e.lowestObserverState_=2,(t=e.observers_)==null||t.forEach(t=>{t.dependenciesState_===1?t.dependenciesState_=2:t.dependenciesState_===0&&(e.lowestObserverState_=0)}))}function mn(e){var t;e.lowestObserverState_===0&&(e.lowestObserverState_=1,(t=e.observers_)==null||t.forEach(e=>{e.dependenciesState_===0&&(e.dependenciesState_=1,e.onBecomeStale_())}))}var hn=class{constructor(e=`Reaction@`+u(),t,n,r){this.name_=void 0,this.onInvalidate_=void 0,this.errorHandler_=void 0,this.requiresObservable_=void 0,this.observing_=[],this.newObserving_=[],this.dependenciesState_=-1,this.runId_=0,this.unboundDepsCount_=0,this.flags_=0,this.removeAbortListener_=void 0,this.name_=e,this.onInvalidate_=t,this.errorHandler_=n,this.requiresObservable_=r}get isDisposed(){return w(this.flags_,1)}set isDisposed(e){this.flags_=oe(this.flags_,1,e)}get isScheduled(){return w(this.flags_,2)}set isScheduled(e){this.flags_=oe(this.flags_,2,e)}get isTrackPending(){return w(this.flags_,4)}set isTrackPending(e){this.flags_=oe(this.flags_,4,e)}get isRunning(){return w(this.flags_,8)}set isRunning(e){this.flags_=oe(this.flags_,8,e)}get diffValue(){return+!!w(this.flags_,16)}set diffValue(e){this.flags_=oe(this.flags_,16,e===1)}onBecomeStale_(){this.schedule_()}schedule_(){this.isScheduled||(this.isScheduled=!0,A.pendingReactions.push(this),vn())}runReaction_(){if(!this.isDisposed){sn(),this.isScheduled=!1;let e=A.trackingContext;if(A.trackingContext=this,Ft(this)){this.isTrackPending=!0;try{this.onInvalidate_(),this.isTrackPending&&Sn()&&Cn({name:this.name_,type:`scheduled-reaction`})}catch(e){this.reportExceptionInDerivation_(e)}}A.trackingContext=e,cn()}}track(e){if(this.isDisposed)return;sn();let t=Sn(),n;t&&(n=Date.now(),wn({name:this.name_,type:`reaction`})),this.isRunning=!0;let r=A.trackingContext;A.trackingContext=this;let i=zt(this,e,void 0);A.trackingContext=r,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Ht(this),Pt(i)&&this.reportExceptionInDerivation_(i.cause),t&&En({time:Date.now()-n}),cn()}reportExceptionInDerivation_(e){if(this.errorHandler_){this.errorHandler_(e,this);return}if(A.disableErrorBoundaries)throw e;let t=`[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '${this}'`;A.suppressReactionErrors?console.warn(`[mobx] (error in reaction '${this.name_}' suppressed, fix error of causing action below)`):console.error(t,e),Sn()&&Cn({type:`error`,name:this.name_,message:t,error:``+e}),A.globalReactionErrorHandlers.forEach(t=>t(e,this))}dispose(){if(!this.isDisposed){var e;this.isDisposed=!0,(e=this.removeAbortListener_)==null||e.call(this),this.isRunning||(sn(),Ht(this),cn())}}getDisposer_(e){let t=()=>this.dispose();return e!=null&&e.addEventListener&&!this.isDisposed&&(e.addEventListener(`abort`,t),this.removeAbortListener_=()=>e.removeEventListener==null?void 0:e.removeEventListener(`abort`,t)),t[T]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.name_}]`}};function gn(e){return A.globalReactionErrorHandlers.push(e),()=>{let t=A.globalReactionErrorHandlers.indexOf(e);t>=0&&A.globalReactionErrorHandlers.splice(t,1)}}let _n=e=>e();function vn(){A.inBatch>0||A.isRunningReactions||_n(yn)}function yn(){A.isRunningReactions=!0;let e=A.pendingReactions,t=0;for(;e.length>0;){++t===100&&(console.error(`Reaction doesn't converge to a stable state after 100 iterations. Probably there is a cycle in the reactive function: ${e[0]}`),e.splice(0));let n=e.splice(0);for(let e=0,t=n.length;e<t;e++)n[e].runReaction_()}A.isRunningReactions=!1}let bn=b(`Reaction`,hn);function xn(e){let t=_n;_n=n=>e(()=>t(n))}function Sn(){return!!A.spyListeners.length}function Cn(e){if(!A.spyListeners.length)return;let t=A.spyListeners;for(let n=0,r=t.length;n<r;n++)t[n](e)}function wn(e){Cn(r({},e,{spyReportStart:!0}))}let Tn={type:`report-end`,spyReportEnd:!0};function En(e){Cn(e?r({},e,{type:`report-end`,spyReportEnd:!0}):Tn)}function Dn(e){return A.spyListeners.push(e),d(()=>{A.spyListeners=A.spyListeners.filter(t=>t!==e)})}let j=`action`,On=`autoAction`,kn=`<unnamed action>`,An=we(j),jn=we(`action.bound`,{bound:!0}),M=we(On,{autoAction:!0}),Mn=we(`autoAction.bound`,{autoAction:!0,bound:!0});function Nn(e){return Ze(e,De)}function Pn(e){return function(t,r){if(r&&typeof r.kind==`string`)return De(e?M:An,t,r);if(p(t))return St(t.name||kn,t,e);if(p(r))return St(t,r,e);if(m(t))return Nn(we(e?On:j,{name:t,autoAction:e}));n("Invalid arguments for `action`")}}let Fn=Pn(!1);r(Fn,An);let In=Pn(!0);r(In,M);let Ln=Nn(jn),Rn=Nn(Mn);function zn(e){return Ct(e.name||kn,!1,e,this,void 0)}function Bn(e){return p(e)&&e.isMobxAction===!0}function Vn(e,t=c){var r;p(e)||n(`Autorun expects a function as first argument`),Bn(e)&&n(`Autorun does not accept actions since actions are untrackable`);let i=t?.name??(e.name||`Autorun@`+u()),a=!t.scheduler&&!t.delay,o;if(a)o=new hn(i,function(){this.track(s)},t.onError,t.requiresObservable);else{let e=Un(t),n=!1;o=new hn(i,()=>{n||(n=!0,e(()=>{n=!1,o.isDisposed||o.track(s)}))},t.onError,t.requiresObservable)}function s(){e(o)}return t!=null&&(r=t.signal)!=null&&r.aborted||o.schedule_(),o.getDisposer_(t?.signal)}let Hn=e=>e();function Un(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Hn}function Wn(e,t,r=c){var i;(!p(e)||!p(t))&&n(`First and second argument to reaction should be functions`),g(r)||n(`Third argument of reactions should be an object`);let a=r.name??`Reaction@`+u(),o=Fn(a,r.onError?Gn(r.onError,t):t),s=!r.scheduler&&!r.delay,l=Un(r),d=!0,f=!1,m,h=r.equals||me,_=new hn(a,()=>{d||s?v():f||(f=!0,l(v))},r.onError,r.requiresObservable);function v(){if(f=!1,_.isDisposed)return;let t=!1,n=m;_.track(()=>{let n=Et(!1,()=>e(_));t=d||!h(m,n),m=n}),(d&&r.fireImmediately||!d&&t)&&o(m,n,_),d=!1}return r!=null&&(i=r.signal)!=null&&i.aborted||_.schedule_(),_.getDisposer_(r?.signal)}function Gn(e,t){return function(){try{return t.apply(this,arguments)}catch(t){e.call(this,t)}}}function Kn(e,t,n){return Jn(`onBO`,e,t,n)}function qn(e,t,n){return Jn(`onBUO`,e,t,n)}function Jn(e,t,n,r){let i=typeof r==`function`?Ni(t,n):Ni(t),a=p(r)?r:n,o=`${e}L`;return i[o]?i[o].add(a):i[o]=new Set([a]),function(){let e=i[o];e&&(e.delete(a),e.size===0&&delete i[o])}}let Yn=`always`;function Xn(e){e.isolateGlobalState===!0&&Qt();let{enforceActions:t}=e;if(t!==void 0){let e=t===Yn?Yn:t===`observed`;A.enforceActions=e,A.allowStateChanges=!(e===!0||e===Yn)}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(A[t]=!!e[t])}),A.allowStateReads=!A.observableRequiresReaction,A.disableErrorBoundaries===!0&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),e.reactionScheduler&&xn(e.reactionScheduler)}function Zn(e,t,r,i){arguments.length>4&&n(`'extendObservable' expected 2-4 arguments`),typeof e!=`object`&&n(`'extendObservable' expects an object as first argument`),vi(e)&&n(`'extendObservable' should not be used on maps, use map.merge instead`),g(t)||n(`'extendObservable' only accepts plain objects as second argument`),(Sr(t)||Sr(r))&&n(`Extending an object with another observable (object) is not supported`);let a=C(t);return Ii(()=>{let t=Oi(e,i)[T];ne(a).forEach(e=>{t.extend_(e,a[e],r&&e in r?r[e]:!0)})}),e}function Qn(e,t){return $n(Ni(e,t))}function $n(e){let t={name:e.name_};return e.observing_&&e.observing_.length>0&&(t.dependencies=nr(e.observing_).map($n)),t}function er(e,t){return tr(Ni(e,t))}function tr(e){let t={name:e.name_};return tn(e)&&(t.observers=Array.from(nn(e),tr)),t}function nr(e){return Array.from(new Set(e))}let rr=0;var ir=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};function ar(e){return e instanceof ir}function or(e){return Ze(e,Me)}let sr=Ae(`flow`),cr=Ae(`flow.bound`,{bound:!0}),lr=r(function(e,t){if(t&&typeof t.kind==`string`)return Me(sr,e,t);arguments.length!==1&&n(`Flow expects single argument with generator function`);let r=e,i=r.name||`<unnamed flow>`,a=function(){let e=this,t=arguments,n=++rr,a=Fn(`${i} - runid: ${n} - init`,r).apply(e,t),o,s,c=new Promise(function(e,t){let r=0;o=t;function c(e){s=void 0;let o;try{o=Fn(`${i} - runid: ${n} - yield ${r++}`,a.next).call(a,e)}catch(e){return t(e)}u(o)}function l(e){s=void 0;let o;try{o=Fn(`${i} - runid: ${n} - yield ${r++}`,a.throw).call(a,e)}catch(e){return t(e)}u(o)}function u(n){if(p(n?.then)){n.then(u,t);return}return n.done?e(n.value):(s=Promise.resolve(n.value),s.then(c,l))}c(void 0)});return c.cancel=Fn(`${i} - runid: ${n} - cancel`,function(){try{s&&dr(s);let e=a.return(void 0),t=Promise.resolve(e.value);t.then(f,f),dr(t),o(new ir)}catch(e){o(e)}}),c};return a.isMobXFlow=!0,a},sr),ur=or(cr);function dr(e){p(e.cancel)&&e.cancel()}function fr(e){return e}function pr(e){return e?.isMobXFlow===!0}function mr(e,t,r){let i;if(vi(e)||mi(e)||At(e))i=Pi(e);else if(N(e)){if(!m(t))return n(`InterceptReads can only be used with a specific property, not with an object in general`);i=Pi(e,t)}else return n(`Expected observable map, object or array as first array`);return i.dehancer===void 0?(i.dehancer=typeof t==`function`?t:r,()=>{i.dehancer=void 0}):n(`An intercept reader was already established`)}function hr(e,t,n){return p(n)?_r(e,t,n):gr(e,t)}function gr(e,t){return Jr(Pi(e),t)}function _r(e,t,n){return Jr(Pi(e,t),n)}function vr(e,t){var n;if(t===void 0)return Mt(e);if(N(e)===!1)return!1;let r=e[T];return(n=r.lazyComputedKeys_)!=null&&n.has(t)?!0:r.values_.has(t)?Mt(Ni(e,t)):!1}function yr(e){return arguments.length>1?n(`isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property`):vr(e)}function br(e,t){return m(t)?vr(e,t):n(`isComputed expected a property name as second argument`)}function xr(e,t){if(!e)return!1;if(t!==void 0){if(vi(e)||mi(e))return n(`isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.`);if(N(e)){var r,i;let n=e[T];return n.values_.has(t)||!!((r=n.lazyComputedKeys_)!=null&&r.has(t))||!!((i=n.lazyObservableKeys_)!=null&&i.has(t))}return!1}return N(e)||!!e[T]||le(e)||bn(e)||Mt(e)}function Sr(e){return arguments.length!==1&&n(`isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property`),xr(e)}function Cr(e,t){return m(t)?xr(e,t):n(`expected a property name as second argument`)}function wr(e){if(N(e))return e[T].keys_();if(vi(e)||Ci(e))return Array.from(e.keys());if(mi(e))return e.map((e,t)=>t);n(5)}function Tr(e){if(N(e))return wr(e).map(t=>e[t]);if(vi(e))return wr(e).map(t=>e.get(t));if(Ci(e))return Array.from(e.values());if(mi(e))return e.slice();n(6)}function Er(e){if(N(e))return wr(e).map(t=>[t,e[t]]);if(vi(e))return wr(e).map(t=>[t,e.get(t)]);if(Ci(e))return Array.from(e.entries());if(mi(e))return e.map((e,t)=>[t,e]);n(7)}function Dr(e,t,r){if(arguments.length===2&&!Ci(e)){sn();let n=t;try{for(let t in n)Dr(e,t,n[t])}finally{cn()}return}N(e)?e[T].set_(t,r):vi(e)?e.set(t,r):Ci(e)?e.add(t):mi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),t<0&&n(42,t),sn(),t>=e.length&&(e.length=t+1),e[t]=r,cn()):n(8)}function Or(e,t){N(e)?e[T].delete_(t):vi(e)||Ci(e)?e.delete(t):mi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),e.splice(t,1)):n(9)}function kr(e,t){if(N(e))return e[T].has_(t);if(vi(e)||Ci(e))return e.has(t);if(mi(e))return t>=0&&t<e.length;n(10)}function Ar(e,t){if(kr(e,t)){if(N(e))return e[T].get_(t);if(vi(e))return e.get(t);if(mi(e))return e[t];n(11)}}function jr(e,t,r){if(N(e))return e[T].defineProperty_(t,r);n(39)}function Mr(e){if(N(e))return e[T].ownKeys_();n(38)}function Nr(e,t,n,r){return p(n)?Fr(e,t,n,r):Pr(e,t,n)}function Pr(e,t,r){let i=Pi(e);if(mi(e))r&&t({observableKind:`array`,object:i.proxy_,debugObjectName:i.atom_.name_,type:`splice`,index:0,added:i.values_.slice(),addedCount:i.values_.length,removed:[],removedCount:0});else if(vi(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with maps.");else if(Ci(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with sets.");else if(N(e))r===!0&&n("`observe` doesn't support the fire immediately property for observable objects.");else return Ir(i,t,r);return Zr(i,t)}function Fr(e,t,n,r){return Ir(Pi(e,t),n,r)}function Ir(e,t,n){if(Mt(e)){let r=!0,i;return Vn(()=>{let a=e.get();if(!r||n){let n=Wt();t({observableKind:`computed`,debugObjectName:e.name_,type:ii,object:e,newValue:a,oldValue:i}),Gt(n)}r=!1,i=a})}return n&&t({observableKind:`value`,debugObjectName:e.name_,object:e,type:ii,newValue:e.value_,oldValue:void 0}),Zr(e,t)}function Lr(e,t,n){return e.set(t,n),n}function Rr(e,t){if(typeof e!=`object`||!e||e instanceof Date||!Sr(e))return e;if(At(e)||Mt(e))return Rr(e.get(),t);if(t.has(e))return t.get(e);if(mi(e)){let n=Lr(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=Rr(e,t)}),n}if(Ci(e)){let n=Lr(t,e,new Set);return e.forEach(e=>{n.add(Rr(e,t))}),n}if(vi(e)){let n=Lr(t,e,new Map);return e.forEach((e,r)=>{n.set(r,Rr(e,t))}),n}else{let n=Lr(t,e,{});return Mr(e).forEach(r=>{o.propertyIsEnumerable.call(e,r)&&(n[r]=Rr(e[r],t))}),n}}function zr(e,t){return t&&n(`toJS no longer supports options`),Rr(e,new Map)}function Br(e,t=void 0){sn();try{return e.apply(t)}finally{cn()}}function Vr(e,t,n){return arguments.length===1||t&&typeof t==`object`?Ur(e,t):Hr(e,t,n||{})}function Hr(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[T].isDisposed)if(a(),n.onError)n.onError(e);else throw e},n.timeout)}n.name=n.name||`When@`+u();let i=St(n.name+`-effect`,t);var a=Vn(t=>{Et(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function Ur(e,t){var i;if(t&&t.onError)return n(`the options 'onError' and 'promise' cannot be combined`);if(t!=null&&(i=t.signal)!=null&&i.aborted)return r(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let a,o,s=new Promise((n,i)=>{var s;let c=Hr(e,n,r({},t,{onError:i}));a=()=>{c(),i(Error(`WHEN_CANCELLED`))},o=()=>{c(),i(Error(`WHEN_ABORTED`))},t==null||(s=t.signal)==null||s.addEventListener==null||s.addEventListener(`abort`,o)}).finally(()=>{var e;return t==null||(e=t.signal)==null||e.removeEventListener==null?void 0:e.removeEventListener(`abort`,o)});return s.cancel=a,s}function Wr(e){return e[T]}let Gr={has(e,t){return Wr(e).has_(t)},get(e,t){return Wr(e).get_(t)},set(e,t,n){return m(t)?Wr(e).set_(t,n,!0)??!0:!1},deleteProperty(e,t){return m(t)?Wr(e).delete_(t,!0)??!0:!1},defineProperty(e,t,n){return Wr(e).defineProperty_(t,n)??!0},ownKeys(e){return Wr(e).ownKeys_()},preventExtensions(e){n(13)}};function Kr(e,t){var n;return e=Oi(e,t),(n=e[T]).proxy_??(n.proxy_=new Proxy(e,Gr))}function qr(e){return e.interceptors_!==void 0&&e.interceptors_.length>0}function Jr(e,t){let n=e.interceptors_;return n?n.push(t):n=e.interceptors_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Yr(e,t){let r=Wt();try{let r=[...e.interceptors_||[]];for(let e=0,i=r.length;e<i&&(t=r[e](t),t&&!t.type&&n(14),t);e++);return t}finally{Gt(r)}}function Xr(e){return e.changeListeners_!==void 0&&e.changeListeners_.length>0}function Zr(e,t){let n=e.changeListeners_;return n?n.push(t):n=e.changeListeners_=[t],d(()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Qr(e,t){let n=Wt(),r=e.changeListeners_;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Gt(n)}}function $r(e,t,n){return Ii(()=>{let r=Oi(e,n)[T];ne(t).forEach(e=>ni(r,e,t[e]))}),e}let ei=Symbol(`mobx-keys`);function ti(e,t,r){return!g(e)&&!g(Object.getPrototypeOf(e))&&n(`'makeAutoObservable' can only be used for classes that don't have a superclass`),N(e)&&n(`makeAutoObservable can only be used on objects not already made observable`),g(e)?Zn(e,e,t,r):(Ii(()=>{let n=Oi(e,r)[T];if(!e[ei]){let t=Object.getPrototypeOf(e),n=new Set([...ne(e),...ne(t)]);n.delete(`constructor`),n.delete(T),v(t,ei,n)}e[ei].forEach(e=>ni(n,e,t&&e in t?t[e]:!0))}),e)}function ni(e,t,r){if(r===!0&&(r=e.defaultAnnotation_),r===!1)return;Mi(e,r,t),t in e.target_||n(1,r.annotationType_,`${e.name_}.${t.toString()}`);let a=e.target_;for(;a&&a!==o;){let n=i(a,t);if(n){let i=r.make_(e,t,n,a);if(i===0)return;if(i===1)break}a=Object.getPrototypeOf(a)}ji(e,r,t)}let ri=`splice`,ii=`update`,ai={get(e,t){let n=e[T];return t===T?n:t===`length`?n.getArrayLength_():typeof t==`string`&&!isNaN(t)?n.get_(parseInt(t)):ae(ci,t)?ci[t]:e[t]},set(e,t,n){let r=e[T];return t===`length`?r.setArrayLength_(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.set_(parseInt(t),n),!0},preventExtensions(){n(15)}};var oi=class{constructor(e=`ObservableArray@`+u(),t,n){this.owned_=void 0,this.atom_=void 0,this.values_=[],this.interceptors_=void 0,this.changeListeners_=void 0,this.enhancer_=void 0,this.dehancer=void 0,this.proxy_=void 0,this.lastKnownLength_=0,this.owned_=n,this.atom_=new ce(e),this.enhancer_=(n,r)=>t(n,r,e+`[..]`)}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}dehanceValues_(e){return this.dehancer!==void 0&&e.length>0?e.map(this.dehancer):e}getArrayLength_(){return this.atom_.reportObserved(),this.values_.length}setArrayLength_(e){(!Number.isInteger(e)||e<0)&&n(40,e);let t=this.values_.length;if(e!==t)if(e>t){let n=Array.from({length:e-t});this.spliceWithArray_(t,0,n)}else this.spliceWithArray_(e,t-e)}updateArrayLength_(e,t){e!==this.lastKnownLength_&&n(16),this.lastKnownLength_+=t}spliceWithArray_(e,t,n){Lt(this.atom_);let r=this.values_.length;if(e===void 0?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=arguments.length===1?r-e:t==null?0:Math.max(0,Math.min(t,r-e)),n===void 0&&(n=s),qr(this)){let r=Yr(this,{object:this.proxy_,type:ri,index:e,removedCount:t,added:n});if(!r)return s;t=r.removedCount,n=r.added}n=n.length===0?n:n.map(e=>this.enhancer_(e,void 0));{let e=n.length-t;this.updateArrayLength_(r,e)}let i=this.spliceItemsIntoValues_(e,t,n);return(t!==0||n.length!==0)&&this.notifyArraySplice_(e,n,i),this.dehanceValues_(i)}spliceItemsIntoValues_(e,t,n){if(n.length<1e4)return this.values_.splice(e,t,...n);{let r=this.values_.slice(e,e+t),i=this.values_.slice(e+t);this.values_.length+=n.length-t;for(let t=0;t<n.length;t++)this.values_[e+t]=n[t];for(let t=0;t<i.length;t++)this.values_[e+n.length+t]=i[t];return r}}notifyArrayChildUpdate_(e,t,n){let r=!this.owned_&&Sn(),i=Xr(this),a=i||r?{observableKind:`array`,object:this.proxy_,type:ii,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&wn(a),this.atom_.reportChanged(),i&&Qr(this,a),r&&En()}notifyArraySplice_(e,t,n){let r=!this.owned_&&Sn(),i=Xr(this),a=i||r?{observableKind:`array`,object:this.proxy_,debugObjectName:this.atom_.name_,type:ri,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&wn(a),this.atom_.reportChanged(),i&&Qr(this,a),r&&En()}get_(e){return this.atom_.reportObserved(),this.dehanceValue_(this.values_[e])}set_(e,t){let n=this.values_;if(e<n.length){Lt(this.atom_);let r=n[e];if(qr(this)){let n=Yr(this,{type:ii,object:this.proxy_,index:e,newValue:t});if(!n)return;t=n.newValue}t=this.enhancer_(t,r),t!==r&&(n[e]=t,this.notifyArrayChildUpdate_(e,t,r))}else{let r=Array.from({length:e+1-n.length});r[r.length-1]=t,this.spliceWithArray_(n.length,0,r)}}};function si(e,t,n=`ObservableArray@`+u(),r=!1){return Ii(()=>{let i=new oi(n,t,r);y(i.values_,T,i);let a=new Proxy(i.values_,ai);return i.proxy_=a,e&&e.length&&i.spliceWithArray_(0,0,e),a})}var ci={clear(){return this.splice(0)},replace(e){let t=this[T];return t.spliceWithArray_(0,t.values_.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[T];switch(arguments.length){case 0:return[];case 1:return r.spliceWithArray_(e);case 2:return r.spliceWithArray_(e,t)}return r.spliceWithArray_(e,t,n)},spliceWithArray(e,t,n){return this[T].spliceWithArray_(e,t,n)},push(...e){let t=this[T];return t.spliceWithArray_(t.values_.length,0,e),t.values_.length},pop(){return this.splice(Math.max(this[T].values_.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[T];return t.spliceWithArray_(0,0,e),t.values_.length},reverse(){return A.trackingDerivation&&n(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){A.trackingDerivation&&n(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[T],n=t.dehanceValues_(t.values_).indexOf(e);return n>-1?(this.splice(n,1),!0):!1}};li(`at`,ui),li(`concat`,ui),li(`flat`,ui),li(`includes`,ui),li(`indexOf`,ui),li(`join`,ui),li(`lastIndexOf`,ui),li(`slice`,ui),li(`toString`,ui),li(`toLocaleString`,ui),li(`toSorted`,ui),li(`toSpliced`,ui),li(`with`,ui),li(`every`,di),li(`filter`,di),li(`find`,di),li(`findIndex`,di),li(`findLast`,di),li(`findLastIndex`,di),li(`flatMap`,di),li(`forEach`,di),li(`map`,di),li(`some`,di),li(`toReversed`,di),li(`reduce`,fi),li(`reduceRight`,fi);function li(e,t){typeof Array.prototype[e]==`function`&&(ci[e]=t(e))}function ui(e){return function(){let t=this[T];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_);return n[e].apply(n,arguments)}}function di(e){return function(t,n){let r=this[T];return r.atom_.reportObserved(),r.dehanceValues_(r.values_)[e]((e,r)=>t.call(n,e,r,this))}}function fi(e){return function(){let t=this[T];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_),r=arguments[0];return arguments[0]=(e,t,n)=>r(e,t,n,this),n[e].apply(n,arguments)}}let pi=b(`ObservableArrayAdministration`,oi);function mi(e){return h(e)&&pi(e[T])}let hi={},gi=`delete`;var _i=class{constructor(e,t=he,n=`ObservableMap@`+u()){this.enhancer_=void 0,this.name_=void 0,this[T]=hi,this.data_=void 0,this.hasMap_=void 0,this.keysAtom_=void 0,this.interceptors_=void 0,this.changeListeners_=void 0,this.dehancer=void 0,this.enhancer_=t,this.name_=n,Ii(()=>{this.keysAtom_=ue(`${this.name_}.keys()`),this.data_=new Map,this.hasMap_=new Map,e&&this.merge(e)})}has_(e){return this.data_.has(e)}has(e){if(!A.trackingDerivation)return this.has_(e);let t=this.hasMap_.get(e);if(!t){let n=t=new kt(this.has_(e),_e,`${this.name_}.${re(e)}?`,!1);this.hasMap_.set(e,n),n.onBUOL=new Set([()=>this.hasMap_.delete(e)])}return t.get()}set(e,t){let n=this.has_(e);if(qr(this)){let r=Yr(this,{type:n?ii:`add`,object:this,newValue:t,name:e});if(!r)return this;t=r.newValue}return n?this.updateValue_(e,t):this.addValue_(e,t),this}delete(e){if(Lt(this.keysAtom_),qr(this)&&!Yr(this,{type:gi,object:this,name:e}))return!1;if(this.has_(e)){let t=Sn(),n=Xr(this),r=n||t?{observableKind:`map`,debugObjectName:this.name_,type:gi,object:this,oldValue:this.data_.get(e).value_,name:e}:null;return t&&wn(r),Br(()=>{var t;this.keysAtom_.reportChanged(),(t=this.hasMap_.get(e))==null||t.setNewValue_(!1),this.data_.get(e).setNewValue_(void 0),this.data_.delete(e)}),n&&Qr(this,r),t&&En(),!0}return!1}updateValue_(e,t){let n=this.data_.get(e);if(t=n.prepareNewValue_(t),t!==A.UNCHANGED){let r=Sn(),i=Xr(this),a=i||r?{observableKind:`map`,debugObjectName:this.name_,type:ii,object:this,oldValue:n.value_,name:e,newValue:t}:null;r&&wn(a),n.setNewValue_(t),i&&Qr(this,a),r&&En()}}addValue_(e,t){Lt(this.keysAtom_),Br(()=>{var n;let r=new kt(t,this.enhancer_,`${this.name_}.${re(e)}`,!1);this.data_.set(e,r),t=r.value_,(n=this.hasMap_.get(e))==null||n.setNewValue_(!0),this.keysAtom_.reportChanged()});let n=Sn(),r=Xr(this),i=r||n?{observableKind:`map`,debugObjectName:this.name_,type:`add`,object:this,name:e,newValue:t}:null;n&&wn(i),r&&Qr(this,i),n&&En()}get(e){return this.has(e)?this.dehanceValue_(this.data_.get(e).get()):this.dehanceValue_(void 0)}getOrInsert(e,t){return this.has(e)||this.set(e,t),this.get(e)}getOrInsertComputed(e,t){return this.has(e)||this.set(e,t(e)),this.get(e)}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}keys(){return this.keysAtom_.reportObserved(),this.data_.keys()}values(){let e=this,t=this.keys();return yi({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:e.get(r)}}})}entries(){let e=this,t=this.keys();return yi({next(){let{done:n,value:r}=t.next();return{done:n,value:n?void 0:[r,e.get(r)]}}})}[Symbol.iterator](){return this.entries()}forEach(e,t){for(let[n,r]of this)e.call(t,r,n,this)}merge(e){return vi(e)&&(e=new Map(e)),Br(()=>{g(e)?te(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):ee(e)?(x(e)||n(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&n(20,e)}),this}clear(){Br(()=>{Ut(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return Br(()=>{let t=bi(e),n=new Map,r=!1;for(let e of this.data_.keys())if(!t.has(e))if(this.delete(e))r=!0;else{let t=this.data_.get(e);n.set(e,t)}for(let[e,i]of t.entries()){let t=this.data_.has(e);if(this.set(e,i),this.data_.has(e)){let i=this.data_.get(e);n.set(e,i),t||(r=!0)}}if(!r)if(this.data_.size!==n.size)this.keysAtom_.reportChanged();else{let e=this.data_.keys(),t=n.keys(),r=e.next(),i=t.next();for(;!r.done;){if(r.value!==i.value){this.keysAtom_.reportChanged();break}r=e.next(),i=t.next()}}this.data_=n}),this}get size(){return this.keysAtom_.reportObserved(),this.data_.size}toString(){return`[object ObservableMap]`}toJSON(){return Array.from(this)}get[Symbol.toStringTag](){return`Map`}},vi=b(`ObservableMap`,_i);function yi(e){return e[Symbol.toStringTag]=`MapIterator`,Hi(e)}function bi(e){if(ee(e)||vi(e))return e;if(Array.isArray(e))return new Map(e);if(g(e)){let t=new Map;for(let n in e)t.set(n,e[n]);return t}else return n(21,e)}let xi={};var Si=class{constructor(e,t=he,n=`ObservableSet@`+u()){this.name_=void 0,this[T]=xi,this.data_=new Set,this.atom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.dehancer=void 0,this.enhancer_=void 0,this.name_=n,this.enhancer_=(e,r)=>t(e,r,n),Ii(()=>{this.atom_=ue(this.name_),e&&this.replace(e)})}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){Br(()=>{Ut(()=>{for(let e of this.data_.values())this.delete(e)})})}forEach(e,t){for(let n of this)e.call(t,n,n,this)}get size(){return this.atom_.reportObserved(),this.data_.size}add(e){if(Lt(this.atom_),qr(this)){let t=Yr(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){Br(()=>{e=this.enhancer_(e,void 0),this.data_.add(e),this.atom_.reportChanged()});let t=Sn(),n=Xr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:`add`,object:this,newValue:e}:null;t&&wn(r),n&&Qr(this,r),t&&En()}return this}delete(e){if(qr(this)&&!Yr(this,{type:gi,object:this,oldValue:e}))return!1;if(this.has(e)){let t=Sn(),n=Xr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:gi,object:this,oldValue:e}:null;return t&&wn(r),Br(()=>{this.atom_.reportChanged(),this.data_.delete(e)}),n&&Qr(this,r),t&&En(),!0}return!1}has(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))}entries(){let e=this.values();return wi({next(){let{value:t,done:n}=e.next();return n?{value:void 0,done:n}:{value:[t,t],done:n}}})}keys(){return this.values()}values(){this.atom_.reportObserved();let e=this,t=this.data_.values();return wi({next(){let{value:n,done:r}=t.next();return r?{value:void 0,done:r}:{value:e.dehanceValue_(n),done:r}}})}intersection(e){return new Set(this).intersection(e)}union(e){return new Set(this).union(e)}difference(e){return new Set(this).difference(e)}symmetricDifference(e){return new Set(this).symmetricDifference(e)}isSubsetOf(e){return new Set(this).isSubsetOf(e)}isSupersetOf(e){return new Set(this).isSupersetOf(e)}isDisjointFrom(e){return new Set(this).isDisjointFrom(e)}replace(e){return Ci(e)&&(e=new Set(e)),Array.isArray(e)||S(e)?Br(()=>{let t=S(e)?e:new Set(e);if(t.size===0){this.clear();return}if(this.data_.size===0){t.forEach(e=>this.add(e));return}for(let e of this.data_.values())t.has(this.dehanceValue_(e))||this.delete(e);t.forEach(e=>this.add(e))}):e!=null&&n(41,e),this}toJSON(){return Array.from(this)}toString(){return`[object ObservableSet]`}[Symbol.iterator](){return this.values()}get[Symbol.toStringTag](){return`Set`}},Ci=b(`ObservableSet`,Si);function wi(e){return e[Symbol.toStringTag]=`SetIterator`,Hi(e)}let Ti=Object.create(null),Ei=`remove`;var Di=class{constructor(e,t=new Map,r,i=Ge){this.target_=void 0,this.values_=void 0,this.name_=void 0,this.defaultAnnotation_=void 0,this.keysAtom_=void 0,this.changeListeners_=void 0,this.interceptors_=void 0,this.proxy_=void 0,this.isPlainObject_=void 0,this.appliedAnnotations_=void 0,this.pendingKeys_=void 0,this.lazyComputedKeys_=void 0,this.lazyObservableKeys_=void 0,this.target_=e,this.values_=t,this.name_=r,this.defaultAnnotation_=i,this.keysAtom_=new ce(`${this.name_}.keys`),this.isPlainObject_=g(this.target_),Wi(this.defaultAnnotation_)||n(`defaultAnnotation must be valid annotation`),this.appliedAnnotations_={}}getObservablePropValue_(e){return(this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e)).get()}materializeLazyComputed_(e){let t=this.lazyComputedKeys_?.get(e);if(!t)return;this.lazyComputedKeys_.delete(e),this.lazyComputedKeys_.size===0&&(this.lazyComputedKeys_=void 0);let n=t();return this.values_.set(e,n),n}materializeLazyObservable_(e){let t=this.lazyObservableKeys_?.get(e);if(!t)return;this.lazyObservableKeys_.delete(e),this.lazyObservableKeys_.size===0&&(this.lazyObservableKeys_=void 0);let n=t();return this.values_.set(e,n),n}setObservablePropValue_(e,t){let n=this.values_.get(e)??this.materializeLazyComputed_(e)??this.materializeLazyObservable_(e);if(n instanceof jt)return n.set(t),!0;if(qr(this)){let n=Yr(this,{type:ii,object:this.proxy_||this.target_,name:e,newValue:t});if(!n)return null;t=n.newValue}if(t=n.prepareNewValue_(t),t!==A.UNCHANGED){let r=Xr(this),i=Sn(),a=r||i?{type:ii,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,oldValue:n.value_,name:e,newValue:t}:null;i&&wn(a),n.setNewValue_(t),r&&Qr(this,a),i&&En()}return!0}get_(e){return A.trackingDerivation&&!ae(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return ae(this.target_,e)?this.values_.has(e)?this.setObservablePropValue_(e,t):n?Reflect.set(this.target_,e,t):(this.target_[e]=t,!0):this.extend_(e,{value:t,enumerable:!0,writable:!0,configurable:!0},this.defaultAnnotation_,n)}has_(e){if(!A.trackingDerivation)return e in this.target_;this.pendingKeys_||=new Map;let t=this.pendingKeys_.get(e);return t||(t=new kt(e in this.target_,_e,`${this.name_}.${re(e)}?`,!1),this.pendingKeys_.set(e,t)),t.get()}extend_(e,t,n,r=!1){if(n===!0&&(n=this.defaultAnnotation_),n===!1)return this.defineProperty_(e,t,r);Mi(this,n,e);let i=n.extend_(this,e,t,r);return i&&ji(this,n,e),i}defineProperty_(e,t,n=!1){Lt(this.keysAtom_);try{sn();let i=this.delete_(e);if(!i)return i;if(qr(this)){let n=Yr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t.value});if(!n)return null;let{newValue:i}=n;t.value!==i&&(t=r({},t,{value:i}))}if(n){if(!Reflect.defineProperty(this.target_,e,t))return!1}else a(this.target_,e,t);this.notifyPropertyAddition_(e,t.value)}finally{cn()}return!0}defineObservableProperty_(e,t,n,r=!1){Lt(this.keysAtom_);try{sn();let i=this.delete_(e);if(!i)return i;if(qr(this)){let n=Yr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let o=Ai(e),s={configurable:A.safeDescriptors?this.isPlainObject_:!0,enumerable:!0,get:o.get,set:o.set};if(r){if(!Reflect.defineProperty(this.target_,e,s))return!1}else a(this.target_,e,s);let c=new kt(t,n,`${this.name_}.${e.toString()}`,!1);this.values_.set(e,c),this.notifyPropertyAddition_(e,c.value_)}finally{cn()}return!0}defineComputedProperty_(e,t,n=!1){Lt(this.keysAtom_);try{sn();let r=this.delete_(e);if(!r)return r;if(qr(this)&&!Yr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:void 0}))return null;t.name||=`${this.name_}.${e.toString()}`,t.context=this.proxy_||this.target_;let i=Ai(e),o={configurable:A.safeDescriptors?this.isPlainObject_:!0,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.target_,e,o))return!1}else a(this.target_,e,o);this.values_.set(e,new jt(t)),this.notifyPropertyAddition_(e,void 0)}finally{cn()}return!0}delete_(e,t=!1){if(Lt(this.keysAtom_),!ae(this.target_,e))return!0;if(qr(this)&&!Yr(this,{object:this.proxy_||this.target_,name:e,type:Ei}))return null;try{var n;sn();let r=Xr(this),a=Sn(),o=this.values_.get(e),s;if(!o&&(r||a)&&(s=i(this.target_,e)?.value),t){if(!Reflect.deleteProperty(this.target_,e))return!1}else delete this.target_[e];if(delete this.appliedAnnotations_[e],o&&(this.values_.delete(e),o instanceof kt&&(s=o.value_),fn(o)),this.keysAtom_.reportChanged(),(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(e in this.target_),r||a){let t={type:Ei,observableKind:`object`,object:this.proxy_||this.target_,debugObjectName:this.name_,oldValue:s,name:e};a&&wn(t),r&&Qr(this,t),a&&En()}}finally{cn()}return!0}notifyPropertyAddition_(e,t){var n;let r=Xr(this),i=Sn();if(r||i){let n=r||i?{type:`add`,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,name:e,newValue:t}:null;i&&wn(n),r&&Qr(this,n),i&&En()}(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(!0),this.keysAtom_.reportChanged()}ownKeys_(){return this.keysAtom_.reportObserved(),ne(this.target_)}keys_(){return this.keysAtom_.reportObserved(),Object.keys(this.target_)}};function Oi(e,t){if(t&&N(e)&&n(`Options can't be provided for already observable objects.`),ae(e,T))return Pi(e)instanceof Di||n(`Cannot convert '${Fi(e)}' into observable object:\nThe target is already observable of different type.\nExtending builtins is not supported.`),e;Object.isExtensible(e)||n(`Cannot make the designated object observable; it is not extensible`);let r=t?.name??`${g(e)?`ObservableObject`:e.constructor.name}@${u()}`;return v(e,T,new Di(e,new Map,String(r),ot(t))),e}let ki=b(`ObservableObjectAdministration`,Di);function Ai(e){return Ti[e]||(Ti[e]={get(){return this[T].getObservablePropValue_(e)},set(t){return this[T].setObservablePropValue_(e,t)}})}function N(e){return h(e)?ki(e[T]):!1}function ji(e,t,n){e.appliedAnnotations_[n]=t}function Mi(e,t,r){if(Wi(t)||n(`Cannot annotate '${e.name_}.${r.toString()}': Invalid annotation.`),!xe(t)&&ae(e.appliedAnnotations_,r)){let i=`${e.name_}.${r.toString()}`,a=e.appliedAnnotations_[r].annotationType_,o=t.annotationType_;n(`Cannot apply '${o}' to '${i}':\nThe field is already annotated with '${a}'.\nRe-annotating fields is not allowed.\nUse 'override' annotation for methods overridden by subclass.`)}}function Ni(e,t){if(typeof e==`object`&&e){if(mi(e))return t!==void 0&&n(23),e[T].atom_;if(Ci(e))return e.atom_;if(vi(e)){if(t===void 0)return e.keysAtom_;let r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,Fi(e)),r}if(N(e)){if(!t)return n(26);let r=e[T],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,Fi(e)),i}if(le(e)||Mt(e)||bn(e))return e}else if(p(e)&&bn(e[T]))return e[T];n(28)}function Pi(e,t){if(e||n(29),t!==void 0)return Pi(Ni(e,t));if(le(e)||Mt(e)||bn(e)||vi(e)||Ci(e))return e;if(e[T])return e[T];n(24,e)}function Fi(e,t){let n;if(t!==void 0)n=Ni(e,t);else if(Bn(e))return e.name;else n=N(e)||vi(e)||Ci(e)?Pi(e):Ni(e);return n.name_}function Ii(e){let t=Wt(),n=Dt(!0);sn();try{return e()}finally{cn(),Ot(n),Gt(t)}}let Li=o.toString;function Ri(e,t,n=-1){return zi(e,t,n)}function zi(e,t,n,r,i){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!==e)return t!==t;let a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;let o=Li.call(e);if(o!==Li.call(t))return!1;switch(o){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++;break}e=Bi(e),t=Bi(t);let s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;let n=e.constructor,r=t.constructor;if(n!==r&&!(p(n)&&n instanceof n&&p(r)&&r instanceof r)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];let c=r.length;for(;c--;)if(r[c]===e)return i[c]===t;if(r.push(e),i.push(t),s){if(c=e.length,c!==t.length)return!1;for(;c--;)if(!zi(e[c],t[c],n-1,r,i))return!1}else{let a=Object.keys(e),o=a.length;if(Object.keys(t).length!==o)return!1;for(let s=0;s<o;s++){let o=a[s];if(!(ae(t,o)&&zi(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function Bi(e){return mi(e)?e.slice():ee(e)||vi(e)||S(e)||Ci(e)?Array.from(e.entries()):e}let Vi=globalThis.Iterator?.prototype||{};function Hi(e){return e[Symbol.iterator]=Ui,r(Object.create(Vi),e)}function Ui(){return this}function Wi(e){return e instanceof Object&&typeof e.annotationType_==`string`&&p(e.make_)&&p(e.extend_)}{let e=globalThis;[`Symbol`,`Map`,`Set`,`Proxy`].forEach(t=>{e[t]===void 0&&n(`MobX requires global '${t}' to be available or polyfilled`)})}typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Dn,extras:{getDebugName:Fi},$mobx:T}),e.$mobx=T,e.FlowCancellationError=ir,e.ObservableMap=_i,e.ObservableSet=Si,e.Reaction=hn,e._allowStateChanges=Et,e._allowStateChangesInsideComputed=zn,e._allowStateReadsEnd=Kt,e._allowStateReadsStart=k,e._autoAction=In,e._autoActionBound=Rn,e._endAction=Tt,e._getAdministration=Pi,e._getGlobalState=$t,e._interceptReads=mr,e._isComputingDerivation=It,e._resetGlobalState=en,e._startAction=wt,e.action=Fn,e.actionBound=Ln,e.autorun=Vn,e.compareDefault=me,e.compareIdentity=de,e.compareShallow=pe,e.compareStructural=fe,e.computed=O,e.computedStruct=_t,e.configure=Xn,e.createAtom=ue,e.defineProperty=jr,e.entries=Er,e.extendObservable=Zn,e.flow=lr,e.flowBound=ur,e.flowResult=fr,e.get=Ar,e.getAtom=Ni,e.getDebugName=Fi,e.getDependencyTree=Qn,e.getObserverTree=er,e.has=kr,e.intercept=hr,e.isAction=Bn,e.isBoxedObservable=At,e.isComputed=yr,e.isComputedProp=br,e.isFlow=pr,e.isFlowCancellationError=ar,e.isObservable=Sr,e.isObservableArray=mi,e.isObservableMap=vi,e.isObservableObject=N,e.isObservableProp=Cr,e.isObservableSet=Ci,e.keys=wr,e.makeAutoObservable=ti,e.makeObservable=$r,e.observable=D,e.observableDeep=ft,e.observableRef=ut,e.observableShallow=dt,e.observableStruct=pt,e.observe=Nr,e.onBecomeObserved=Kn,e.onBecomeUnobserved=qn,e.onReactionError=gn,e.override=be,e.ownKeys=Mr,e.reaction=Wn,e.remove=Or,e.runInAction=zn,e.set=Dr,e.spy=Dn,e.toJS=zr,e.transaction=Br,e.untracked=Ut,e.values=Tr,e.when=Vr})),J=ke(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=qx():t.exports=Jx()}))();function Yx(e){if(Array.isArray(e))return Object.freeze(e.map(Yx));if(typeof e==`object`&&e){let t=Object.create(null),n=Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t));for(let[e,r]of n)t[e]=Yx(r);return Object.freeze(t)}return e}function Xx(e){let t=typeof e;if(t===`string`||t===`number`||t===`boolean`)return t;throw TypeError(`Variable values must be string|number|boolean (got ${t})`)}function Zx(e){return typeof e==`string`?e:String(e)}function Qx(e){if(typeof e==`number`)return e;if(typeof e==`boolean`)return+!!e;let t=e.trim();if(t===``)throw TypeError(`Cannot cast empty string to number`);let n=Number(t);if(!Number.isFinite(n))throw TypeError(`Cannot cast ${JSON.stringify(e)} to number`);return n}function $x(e){if(typeof e==`boolean`)return e;if(typeof e==`number`){if(e===0||e===1)return e===1;throw TypeError(`Cannot cast number ${e} to bool (only 0 and 1 are accepted)`)}if(e===`true`)return!0;if(e===`false`)return!1;throw TypeError(`Cannot cast ${JSON.stringify(e)} to bool (expected "true" or "false")`)}var eS=class extends Error{constructor(e,t){super(t),this.variable=e}};function tS(e){return e instanceof eS?e:e instanceof Error&&e.cause!==void 0?tS(e.cause):void 0}const nS=e=>e===Oa;var rS=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,nS(n)||pS(e,t,n,`initial value`),this.cell=J.observable.box(n,{deep:!1}),this.lastChangedAt=nS(n)?null:Date.now()}read(){let e=this.cell.get();if(nS(e))throw new eS(this.name,`variable "${this.name}" has no value yet: nothing has written it`);return e}set(e){nS(e)||pS(this.name,this.type,e,`set value`),!Object.is(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}stored(){return this.cell.get()}},iS=class{cell;constructor(e,t,n){if(this.cell=(0,J.computed)(t,{keepAlive:!0,...n!==void 0&&{equals:n}}),typeof this.cell.suspend_!=`function`)throw TypeError(`${e}: this MobX's computed has no suspend_; release() cannot unsubscribe it`);if(typeof this.cell.keepAlive_!=`boolean`)throw TypeError(`${e}: this MobX's computed has no keepAlive_ flag; release() cannot lift it`)}read(){return this.cell.get()}release(){this.cell.keepAlive_=!1,this.cell.suspend_()}},aS=class{constructor(e){this.deriver=e}read(){return this.deriver()}},oS=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new iS(`Variable "${e}"`,()=>{let e=n();return pS(this.name,this.type,e,`computed result`),e})}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}},sS=class{kind=`projection`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=new aS(()=>{let e=n();return pS(this.name,this.type,e,`projection result`),e})}read(){return this.cell.read()}lastUpdatedMs(){return null}},cS=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=J.observable.box(fS(t),{deep:!1}),this.lastChangedAt=t.kind===`pending`?null:Date.now()}read(){return this.cell.get()}set(e){let t=fS(e);dS(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}},lS=class{kind=`document`;cell;constructor(e,t){this.name=e,this.cell=new iS(`Variable "${e}"`,()=>fS(t()),dS)}read(){return this.cell.read()}release(){this.cell.release()}lastUpdatedMs(){return null}};function uS(e){return JSON.stringify(e)}function dS(e,t){return uS(e)===uS(t)}function fS(e){return e.kind===`ok`?{kind:`ok`,value:Yx(e.value)}:e}function pS(e,t,n,r){let i=Xx(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var mS=class{constructor(e=null){this.parent=e}nodes=J.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new rS(e,t,n))}defineDocument(e,t){this.declare(e,new cS(e,t))}defineDerivedDocument(e,t){this.declare(e,new lS(e,t))}defineComputed(e,t,n){this.defineDerived(e,t,`computed`,n)}defineDerived(e,t,n,r){let i=e=>this.read(e),a=n===`computed`?oS:sS;this.declare(e,new a(e,t,()=>r(i)))}derive(e,t,n){if(this.refuseDisposed(`Derived value "${e}"`),t===`projection`)return new aS(n);let r=new iS(`Derived value "${e}"`,n);return this.kept.push(r),r}kept=[];read(e){return this.requireVar(e).read()}readDocument(e){let t=this.requireNode(e);if(t.kind!==`document`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a document`);return t.read()}stored(e){let t=this.requireNode(e);if(t.kind===`document`)return t.read();if(t.kind!==`box`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a written node`);return t.stored()}setDocument(e,t){let n=this.requireOwn(e);if(!(n instanceof cS))throw TypeError(n.kind===`document`?`Variable "${e}" is a derived document: what it reads decides it, and nothing writes it`:`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,J.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireOwn(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,J.runInAction)(()=>n.set(t))}runInAction(e){(0,J.runInAction)(e)}has(e){return this.nodes.has(e)||(this.parent?.has(e)??!1)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`){let e=t.read();return e.kind===`pending`?Oa:P(uS(e))}try{return P(String(t.read()))}catch(e){return tS(e)===void 0?P(` failed:${e instanceof Error?e.message:String(e)}`):Oa}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.parent?.names()??[],...this.nodes.keys()]}dispose(){if(this.disposed)return 0;this.disposed=!0;let e=0;return(0,J.runInAction)(()=>{for(let t of this.nodes.values())(t instanceof oS||t instanceof lS)&&(t.release(),e++);for(let e of this.kept)e.release()}),e+this.kept.length}disposed=!1;requireNode(e){let t=this.nodes.get(e)??this.parent?.requireNode(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireOwn(e){let t=this.nodes.get(e);if(t!==void 0)return t;throw this.parent?.has(e)?Error(`Variable "${e}" lives in the directory's store; a session's view cannot write it`):ReferenceError(`Unknown variable "${e}"`)}requireVar(e){let t=this.requireNode(e);if(t.kind===`document`)throw TypeError(`Variable "${e}" is a document; read its fields by path (.${e}.<field>)`);return t}refuseDisposed(e){if(this.disposed)throw Error(`${e}: cannot declare on a disposed store`)}declare(e,t){if(this.refuseDisposed(`Variable "${e}"`),this.has(e))throw Error(`Variable "${e}" is already declared`);(0,J.runInAction)(()=>this.nodes.set(e,t))}},hS=class extends Error{name=`TemplateError`;kind=`EvalError`;pos;source;constructor(e,t,n={}){super(e,{cause:n.cause}),this.pos=t,this.source=n.source}get sourceSnippet(){return this.source?wS(this.source,this.pos):``}toString(){let e=`${this.name}: ${this.message}\n at line ${this.pos.line}, column ${this.pos.column}`,t=this.sourceSnippet;return t?`${e}\n\n${t}`:e}},gS=class extends hS{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},_S=class extends hS{name=`EvalError`;kind=`EvalError`},vS=class extends _S{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=TS(e,n.available??[]),i=r.length===0?``:` (did you mean: ${r.join(`, `)}?)`;super(`function ${JSON.stringify(e)} is not registered${i}`,t,n),this.funcName=e,this.suggestions=r}},yS=class extends _S{name=`ArgCountError`;kind=`ArgCountError`;funcName;accepted;got;constructor(e,t,n,r,i={}){let a=t.minimum===t.maximum?`${t.minimum}`:`at least ${t.minimum}`;super(`wrong number of args for ${e}: want ${a} got ${n}`,r,i),this.funcName=e,this.accepted=t,this.got=n}},bS=class extends _S{name=`TypeMismatchError`;kind=`TypeMismatchError`;funcName;argIndex;expected;receivedSummary;constructor(e,t,n,r,i,a={}){super(`function ${JSON.stringify(e)} arg ${t}: expected ${n}, but a ${r} flowed in. Pass it through \`unstyled\` (or your engine's flatten function) to convert.`,i,a),this.funcName=e,this.argIndex=t,this.expected=n,this.receivedSummary=r}},xS=class extends bS{constructor(e,t,n,r,i={}){super(e,t,`integer`,String(n),r,i),this.message=Number.isInteger(Number(n))?`integer out of range: ${String(n)}`:`expected integer; found ${String(n)}`}},SS=class extends _S{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},CS=class extends _S{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function wS(e,t){let n=e.split(`
61
61
  `),r=t.line-1,i=[];if(r-1>=0&&r-1<n.length&&i.push({num:r,text:n[r-1]??``}),r>=0&&r<n.length&&i.push({num:r+1,text:n[r]??``}),r+1<n.length&&i.push({num:r+2,text:n[r+1]??``}),i.length===0)return``;let a=String(i[i.length-1]?.num??1).length,o=[];for(let e of i)if(o.push(` ${String(e.num).padStart(a,` `)} | ${e.text}`),e.num===t.line){let e=` ${` `.repeat(a)} | `,n=` `.repeat(Math.max(0,t.column-1));o.push(`${e}${n}^`)}return o.join(`
62
- `)}function wS(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:TS(e,t)})).sort((e,t)=>e.dist-t.dist),r=Math.max(2,Math.floor(e.length/2));return n.filter(e=>e.dist<=r).slice(0,3).map(e=>e.name)}function TS(e,t){if(e===t)return 0;let n=e.length,r=t.length;if(n===0)return r;if(r===0)return n;let i=Array(r+1),a=Array(r+1);for(let e=0;e<=r;e++)i[e]=e;for(let o=1;o<=n;o++){a[0]=o;for(let n=1;n<=r;n++){let r=e[o-1]===t[n-1]?0:1;a[n]=Math.min((a[n-1]??0)+1,(i[n]??0)+1,(i[n-1]??0)+r)}for(let e=0;e<=r;e++)i[e]=a[e]??0}return i[r]??0}function ES(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const DS=new Map([[`if`,`If`],[`else`,`Else`],[`end`,`End`],[`range`,`Range`],[`with`,`With`],[`break`,`Break`],[`continue`,`Continue`],[`define`,`Define`],[`template`,`Template`],[`block`,`Block`],[`true`,`Bool`],[`false`,`Bool`],[`nil`,`Nil`]]),OS={left:`{{`,right:`}}`};var kS=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=OS){this.src=e,this.leftDelim=t.left,this.rightDelim=t.right}pos(){return{line:this.line,column:this.column,offset:this.offset}}err(e,t,n={}){return new hS(e,t,{...n,source:this.src})}next(){if(this.pending){let e=this.pending;return this.pending=void 0,e}return this.read()}peek(){return this.pending||=this.read(),this.pending}read(){switch(this.mode){case`text`:return this.readText();case`action`:return this.readAction();case`done`:return this.makeToken(`EOF`,``,this.pos())}}readText(){if(this.offset>=this.src.length)return this.mode=`done`,this.makeToken(`EOF`,``,this.pos());let e=this.pos(),t=this.offset;for(;t<this.src.length&&!this.src.startsWith(this.leftDelim,t);)t+=1;let n=t<this.src.length&&this.src[t+this.leftDelim.length]===`-`,r=t;if(n)for(;r>this.offset&&AS(this.src[r-1]??``);)--r;if(r>this.offset){let t=this.src.slice(this.offset,r);return this.advanceTo(r),this.makeToken(`Text`,t,e)}return this.advanceTo(t),this.emitLeftDelim(n)}emitLeftDelim(e){let t=this.pos();if(this.advanceBy(this.leftDelim.length),e)for(this.advanceBy(1);AS(this.src[this.offset]??``);)this.advanceBy(1);return this.mode=`action`,this.src.startsWith(`/*`,this.offset)?this.readComment(t,e):this.makeToken(`LeftDelim`,e?`${this.leftDelim}-`:this.leftDelim,t,e?{trimLeft:!0}:{})}readComment(e,t){this.advanceBy(2);let n=this.offset,r=this.src.indexOf(`*/`,this.offset);if(r===-1)throw this.err(`unclosed comment`,e,{expected:`*/${this.rightDelim}`,found:`end of input`});this.advanceTo(r);let i=this.src.slice(n,r).trim();for(this.advanceBy(2);AS(this.src[this.offset]??``);)this.advanceBy(1);let a=!1;if(this.src[this.offset]===`-`&&(a=!0,this.advanceBy(1)),!this.src.startsWith(this.rightDelim,this.offset))throw this.err(`expected \`${this.rightDelim}\` to close comment`,this.pos(),{expected:this.rightDelim,found:this.src[this.offset]??`end of input`});if(this.advanceBy(this.rightDelim.length),a)for(;AS(this.src[this.offset]??``);)this.advanceBy(1);return this.mode=`text`,this.makeToken(`Comment`,i,e,{...t?{trimLeft:!0}:{},...a?{trimRight:!0}:{}})}readAction(){if(this.skipActionSpaces(),this.src.startsWith(`-${this.rightDelim}`,this.offset)){let e=this.pos();for(this.advanceBy(1+this.rightDelim.length),this.mode=`text`;AS(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`RightDelim`,`-${this.rightDelim}`,e,{trimRight:!0})}if(this.src.startsWith(this.rightDelim,this.offset)){let e=this.pos();return this.advanceBy(this.rightDelim.length),this.mode=`text`,this.makeToken(`RightDelim`,this.rightDelim,e)}if(this.offset>=this.src.length)throw this.err(`unclosed action`,this.pos(),{expected:this.rightDelim,found:`end of input`});let e=this.src[this.offset],t=this.pos();switch(e){case`(`:return this.advanceBy(1),this.makeToken(`LeftParen`,`(`,t);case`)`:return this.advanceBy(1),this.makeToken(`RightParen`,`)`,t);case`|`:return this.advanceBy(1),this.makeToken(`Pipe`,`|`,t);case`,`:return this.advanceBy(1),this.makeToken(`Comma`,`,`,t);case`:`:if(this.src[this.offset+1]===`=`)return this.advanceBy(2),this.makeToken(`Declare`,`:=`,t);throw this.err("expected `:=`",t,{expected:`:=`,found:`:`});case`=`:return this.advanceBy(1),this.makeToken(`Assign`,`=`,t);case`"`:return this.readQuotedString(t);case"`":return this.readRawString(t);case`'`:return this.readChar(t)}if(e===`$`)return this.readVariable(t);if(e!==void 0&&(MS(e)||jS(e)&&MS(this.src[this.offset+1]??``)||e===`.`&&MS(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&LS(e))return this.readIdentifier(t);throw this.err(`unexpected character ${JSON.stringify(e)}`,t,{found:e??`end of input`})}readQuotedString(e){let t=this.offset;for(this.advanceBy(1);this.offset<this.src.length;){let n=this.src[this.offset];if(n===`\\`){this.advanceBy(1),this.offset<this.src.length&&this.advanceBy(1);continue}if(n===`
62
+ `)}function TS(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:ES(e,t)})).sort((e,t)=>e.dist-t.dist),r=Math.max(2,Math.floor(e.length/2));return n.filter(e=>e.dist<=r).slice(0,3).map(e=>e.name)}function ES(e,t){if(e===t)return 0;let n=e.length,r=t.length;if(n===0)return r;if(r===0)return n;let i=Array(r+1),a=Array(r+1);for(let e=0;e<=r;e++)i[e]=e;for(let o=1;o<=n;o++){a[0]=o;for(let n=1;n<=r;n++){let r=e[o-1]===t[n-1]?0:1;a[n]=Math.min((a[n-1]??0)+1,(i[n]??0)+1,(i[n-1]??0)+r)}for(let e=0;e<=r;e++)i[e]=a[e]??0}return i[r]??0}function DS(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const OS=new Map([[`if`,`If`],[`else`,`Else`],[`end`,`End`],[`range`,`Range`],[`with`,`With`],[`break`,`Break`],[`continue`,`Continue`],[`define`,`Define`],[`template`,`Template`],[`block`,`Block`],[`true`,`Bool`],[`false`,`Bool`],[`nil`,`Nil`]]),kS={left:`{{`,right:`}}`};var AS=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=kS){this.src=e,this.leftDelim=t.left,this.rightDelim=t.right}pos(){return{line:this.line,column:this.column,offset:this.offset}}err(e,t,n={}){return new gS(e,t,{...n,source:this.src})}next(){if(this.pending){let e=this.pending;return this.pending=void 0,e}return this.read()}peek(){return this.pending||=this.read(),this.pending}read(){switch(this.mode){case`text`:return this.readText();case`action`:return this.readAction();case`done`:return this.makeToken(`EOF`,``,this.pos())}}readText(){if(this.offset>=this.src.length)return this.mode=`done`,this.makeToken(`EOF`,``,this.pos());let e=this.pos(),t=this.offset;for(;t<this.src.length&&!this.src.startsWith(this.leftDelim,t);)t+=1;let n=t<this.src.length&&this.src[t+this.leftDelim.length]===`-`,r=t;if(n)for(;r>this.offset&&jS(this.src[r-1]??``);)--r;if(r>this.offset){let t=this.src.slice(this.offset,r);return this.advanceTo(r),this.makeToken(`Text`,t,e)}return this.advanceTo(t),this.emitLeftDelim(n)}emitLeftDelim(e){let t=this.pos();if(this.advanceBy(this.leftDelim.length),e)for(this.advanceBy(1);jS(this.src[this.offset]??``);)this.advanceBy(1);return this.mode=`action`,this.src.startsWith(`/*`,this.offset)?this.readComment(t,e):this.makeToken(`LeftDelim`,e?`${this.leftDelim}-`:this.leftDelim,t,e?{trimLeft:!0}:{})}readComment(e,t){this.advanceBy(2);let n=this.offset,r=this.src.indexOf(`*/`,this.offset);if(r===-1)throw this.err(`unclosed comment`,e,{expected:`*/${this.rightDelim}`,found:`end of input`});this.advanceTo(r);let i=this.src.slice(n,r).trim();for(this.advanceBy(2);jS(this.src[this.offset]??``);)this.advanceBy(1);let a=!1;if(this.src[this.offset]===`-`&&(a=!0,this.advanceBy(1)),!this.src.startsWith(this.rightDelim,this.offset))throw this.err(`expected \`${this.rightDelim}\` to close comment`,this.pos(),{expected:this.rightDelim,found:this.src[this.offset]??`end of input`});if(this.advanceBy(this.rightDelim.length),a)for(;jS(this.src[this.offset]??``);)this.advanceBy(1);return this.mode=`text`,this.makeToken(`Comment`,i,e,{...t?{trimLeft:!0}:{},...a?{trimRight:!0}:{}})}readAction(){if(this.skipActionSpaces(),this.src.startsWith(`-${this.rightDelim}`,this.offset)){let e=this.pos();for(this.advanceBy(1+this.rightDelim.length),this.mode=`text`;jS(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`RightDelim`,`-${this.rightDelim}`,e,{trimRight:!0})}if(this.src.startsWith(this.rightDelim,this.offset)){let e=this.pos();return this.advanceBy(this.rightDelim.length),this.mode=`text`,this.makeToken(`RightDelim`,this.rightDelim,e)}if(this.offset>=this.src.length)throw this.err(`unclosed action`,this.pos(),{expected:this.rightDelim,found:`end of input`});let e=this.src[this.offset],t=this.pos();switch(e){case`(`:return this.advanceBy(1),this.makeToken(`LeftParen`,`(`,t);case`)`:return this.advanceBy(1),this.makeToken(`RightParen`,`)`,t);case`|`:return this.advanceBy(1),this.makeToken(`Pipe`,`|`,t);case`,`:return this.advanceBy(1),this.makeToken(`Comma`,`,`,t);case`:`:if(this.src[this.offset+1]===`=`)return this.advanceBy(2),this.makeToken(`Declare`,`:=`,t);throw this.err("expected `:=`",t,{expected:`:=`,found:`:`});case`=`:return this.advanceBy(1),this.makeToken(`Assign`,`=`,t);case`"`:return this.readQuotedString(t);case"`":return this.readRawString(t);case`'`:return this.readChar(t)}if(e===`$`)return this.readVariable(t);if(e!==void 0&&(NS(e)||MS(e)&&NS(this.src[this.offset+1]??``)||e===`.`&&NS(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&RS(e))return this.readIdentifier(t);throw this.err(`unexpected character ${JSON.stringify(e)}`,t,{found:e??`end of input`})}readQuotedString(e){let t=this.offset;for(this.advanceBy(1);this.offset<this.src.length;){let n=this.src[this.offset];if(n===`\\`){this.advanceBy(1),this.offset<this.src.length&&this.advanceBy(1);continue}if(n===`
63
63
  `)throw this.err(`newline in interpreted string`,e,{found:`\\n`});if(n===`"`)return this.advanceBy(1),this.makeToken(`String`,this.src.slice(t,this.offset),e);this.advanceBy(1)}throw this.err(`unterminated string literal`,e,{expected:`"`,found:`end of input`})}readRawString(e){let t=this.offset;for(this.advanceBy(1);this.offset<this.src.length;){if(this.src[this.offset]==="`")return this.advanceBy(1),this.makeToken(`String`,this.src.slice(t,this.offset),e);this.advanceBy(1)}throw this.err(`unterminated raw string literal`,e,{expected:"`",found:`end of input`})}readChar(e){let t=this.offset;for(this.advanceBy(1);this.offset<this.src.length;){let n=this.src[this.offset];if(n===`\\`){this.advanceBy(1),this.offset<this.src.length&&this.advanceBy(1);continue}if(n===`
64
- `)throw this.err(`newline in rune literal`,e,{found:`\\n`});if(n===`'`)return this.advanceBy(1),this.makeToken(`Char`,this.src.slice(t,this.offset),e);this.advanceBy(1)}throw this.err(`unterminated rune literal`,e,{expected:`'`,found:`end of input`})}readNumber(e){let t=this.offset;if(jS(this.src[this.offset]??``)&&this.advanceBy(1),this.src[this.offset]===`0`&&this.offset+1<this.src.length){let n=this.src[this.offset+1];if(n===`x`||n===`X`){for(this.advanceBy(2);NS(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`||this.src[this.offset]===`p`||this.src[this.offset]===`P`)for(;this.isHexFloatTail(this.src[this.offset]??``);)this.advanceBy(1);return this.finishNumber(t,e)}if(n===`o`||n===`O`){for(this.advanceBy(2);PS(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}if(n===`b`||n===`B`){for(this.advanceBy(2);FS(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;MS(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);MS(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`e`||this.src[this.offset]===`E`)for(this.advanceBy(1),jS(this.src[this.offset]??``)&&this.advanceBy(1);MS(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return NS(e)||e===`.`||e===`p`||e===`P`||e===`+`||e===`-`||e===`_`}finishNumber(e,t){if(this.offset===e)throw this.err(`expected number`,t,{expected:`digit`});return this.makeToken(`Number`,this.src.slice(e,this.offset),t)}readVariable(e){let t=this.offset;for(this.advanceBy(1);RS(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&LS(this.src[this.offset+1]??``);)for(this.advanceBy(1);RS(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`Variable`,this.src.slice(t,this.offset),e)}readDotOrField(e){let t=this.offset;if(this.advanceBy(1),!LS(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;RS(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&LS(this.src[this.offset+1]??``);)for(this.advanceBy(1);RS(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`Field`,this.src.slice(t,this.offset),e)}readIdentifier(e){let t=this.offset;for(;RS(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=DS.get(n);return r?this.makeToken(r,n,e):this.makeToken(`Identifier`,n,e)}skipActionSpaces(){for(;this.offset<this.src.length;){let e=this.src[this.offset];if(e===` `||e===` `||e===`\r`||e===`
64
+ `)throw this.err(`newline in rune literal`,e,{found:`\\n`});if(n===`'`)return this.advanceBy(1),this.makeToken(`Char`,this.src.slice(t,this.offset),e);this.advanceBy(1)}throw this.err(`unterminated rune literal`,e,{expected:`'`,found:`end of input`})}readNumber(e){let t=this.offset;if(MS(this.src[this.offset]??``)&&this.advanceBy(1),this.src[this.offset]===`0`&&this.offset+1<this.src.length){let n=this.src[this.offset+1];if(n===`x`||n===`X`){for(this.advanceBy(2);PS(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`||this.src[this.offset]===`p`||this.src[this.offset]===`P`)for(;this.isHexFloatTail(this.src[this.offset]??``);)this.advanceBy(1);return this.finishNumber(t,e)}if(n===`o`||n===`O`){for(this.advanceBy(2);FS(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}if(n===`b`||n===`B`){for(this.advanceBy(2);IS(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;NS(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);NS(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`e`||this.src[this.offset]===`E`)for(this.advanceBy(1),MS(this.src[this.offset]??``)&&this.advanceBy(1);NS(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return PS(e)||e===`.`||e===`p`||e===`P`||e===`+`||e===`-`||e===`_`}finishNumber(e,t){if(this.offset===e)throw this.err(`expected number`,t,{expected:`digit`});return this.makeToken(`Number`,this.src.slice(e,this.offset),t)}readVariable(e){let t=this.offset;for(this.advanceBy(1);zS(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&RS(this.src[this.offset+1]??``);)for(this.advanceBy(1);zS(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`Variable`,this.src.slice(t,this.offset),e)}readDotOrField(e){let t=this.offset;if(this.advanceBy(1),!RS(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;zS(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&RS(this.src[this.offset+1]??``);)for(this.advanceBy(1);zS(this.src[this.offset]??``);)this.advanceBy(1);return this.makeToken(`Field`,this.src.slice(t,this.offset),e)}readIdentifier(e){let t=this.offset;for(;zS(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=OS.get(n);return r?this.makeToken(r,n,e):this.makeToken(`Identifier`,n,e)}skipActionSpaces(){for(;this.offset<this.src.length;){let e=this.src[this.offset];if(e===` `||e===` `||e===`\r`||e===`
65
65
  `)this.advanceBy(1);else return}}advanceBy(e){for(let t=0;t<e;t++){let e=this.src[this.offset];this.offset+=1,e===`
66
- `?(this.line+=1,this.column=1):this.column+=1}}advanceTo(e){for(;this.offset<e;)this.advanceBy(1)}makeToken(e,t,n,r={}){return Object.freeze({type:e,value:t,pos:n,...r.trimLeft===void 0?{}:{trimLeft:r.trimLeft},...r.trimRight===void 0?{}:{trimRight:r.trimRight}})}};function AS(e){return e===` `||e===` `||e===`\r`||e===`
67
- `}function jS(e){return e===`+`||e===`-`}function MS(e){return e>=`0`&&e<=`9`}function NS(e){return MS(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function PS(e){return e>=`0`&&e<=`7`}function FS(e){return e===`0`||e===`1`}function IS(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function LS(e){return IS(e)||e===`_`}function RS(e){return LS(e)||MS(e)}let zS,BS;function VS(e,t){return BS(e,t)}var HS=class e{static EMPTY=new e(new Map,void 0);#e;#t;constructor(e,t){this.#e=e,this.#t=t}static{zS=(t,n)=>new e(t,n),BS=(e,t)=>e.#e.get(t)??(e.#t&&BS(e.#t,t))}has(e){return BS(this,e)!==void 0}};function US(e,t,n=HS.EMPTY){return new WS(e,t,n).parseTemplate()}var WS=class{lex;buf=[];defines=new Map;inherit;source;rangeDepth=0;constructor(e,t,n){this.source=e,this.inherit=n,this.lex=t?new kS(e,t):new kS(e)}peek(e=0){for(;this.buf.length<=e;)this.buf.push(this.lex.next());return this.buf[e]}next(){return this.buf.length>0?this.buf.shift():this.lex.next()}expect(e,t){let n=this.next();if(n.type!==e)throw this.errAt(n,`expected ${t}`,{expected:t,found:qS(n)});return n}errAt(e,t,n={}){return new hS(t,e.pos,{...n,source:this.source})}parseTemplate(){let e=this.parseList();if(this.peek().type!==`EOF`){let e=this.peek(),t=this.peek(1);if(e.type===`LeftDelim`&&(t.type===`Else`||t.type===`End`)){let n=t.type===`Else`?`else`:`end`;throw this.errAt(e,`unexpected \`{{${n}}}\` outside of \`if\`, \`range\`, \`with\`, or \`block\``,{found:`{{${n}}}`})}throw this.errAt(e,`unexpected ${qS(e)}`,{found:qS(e)})}return{root:e,defines:zS(this.defines,this.inherit),ownDefines:this.defines,source:this.source}}parseList(){let e=this.peek().pos,t=[];for(;;){let n=this.peek();if(n.type===`EOF`)break;if(n.type===`Text`){this.next(),t.push({type:`Text`,pos:n.pos,text:n.value});continue}if(n.type===`Comment`){this.next();let e=KS(n);t.push({type:`Comment`,pos:n.pos,text:n.value,trim:e});continue}if(n.type===`LeftDelim`){let n=this.peek(1).type;if(n===`Else`||n===`End`)return GS(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${qS(n)} at top level`,{found:qS(n)})}return GS(e,t)}parseAction(){let e=this.expect(`LeftDelim`,"`{{`"),t=e.trimLeft===!0,n=this.peek();switch(n.type){case`If`:return this.next(),this.parseBranch(`If`,e.pos,t);case`Range`:return this.next(),this.parseBranch(`Range`,e.pos,t);case`With`:return this.next(),this.parseBranch(`With`,e.pos,t);case`Break`:return this.next(),this.parseBreakOrContinue(`Break`,e.pos,t);case`Continue`:return this.next(),this.parseBreakOrContinue(`Continue`,e.pos,t);case`Template`:return this.next(),this.parseTemplateInvocation(e.pos,t);case`Block`:return this.next(),this.parseBlock(e.pos,t);case`Define`:return this.next(),this.parseDefine(e.pos,t),null;case`RightDelim`:throw this.errAt(n,`empty action`,{expected:`pipeline`});default:{let n=this.parsePipeline(),r=this.expect(`RightDelim`,"`}}`");return{type:`Action`,pos:e.pos,pipe:n,trim:{trimLeft:t,trimRight:r.trimRight===!0}}}}}parseBranch(e,t,n){let r=this.parsePipeline();this.expect(`RightDelim`,"`}}`"),e===`Range`&&(this.rangeDepth+=1);let i=this.parseList();e===`Range`&&--this.rangeDepth;let a=this.parseElsePart(),o={trimLeft:n,trimRight:a.endConsumed?a.endRight:this.consumeEnd()},s=a.list?{pipe:r,list:i,elseList:a.list,trim:o}:{pipe:r,list:i,trim:o};switch(e){case`If`:return{type:`If`,pos:t,...s};case`Range`:return{type:`Range`,pos:t,...s};case`With`:return{type:`With`,pos:t,...s}}}parseBreakOrContinue(e,t,n){if(this.rangeDepth===0)throw new hS(`{{${e===`Break`?`break`:`continue`}}} outside of {{range}}`,t,{source:this.source});let r={trimLeft:n,trimRight:this.expect(`RightDelim`,"`}}`").trimRight===!0};return e===`Break`?{type:`Break`,pos:t,trim:r}:{type:`Continue`,pos:t,trim:r}}parseElsePart(){if(this.peek().type!==`LeftDelim`||this.peek(1).type!==`Else`)return{list:void 0,endRight:!1,endConsumed:!1};let e=this.next();if(this.next(),this.peek().type===`If`){this.next();let t=this.parseBranch(`If`,e.pos,e.trimLeft===!0);return{list:{type:`List`,pos:e.pos,nodes:[t]},endRight:t.trim.trimRight,endConsumed:!0}}return this.expect(`RightDelim`,"`}}`"),{list:this.parseList(),endRight:!1,endConsumed:!1}}consumeEnd(){return this.expect(`LeftDelim`,"`{{end}}`"),this.expect(`End`,"`end`"),this.expect(`RightDelim`,"`}}`").trimRight===!0}parseTemplateInvocation(e,t){let n=this.parseQuotedName(),r=this.peek().type===`RightDelim`?void 0:this.parsePipeline(),i={trimLeft:t,trimRight:this.expect(`RightDelim`,"`}}`").trimRight===!0};return r?{type:`Template`,pos:e,name:n,pipe:r,trim:i}:{type:`Template`,pos:e,name:n,trim:i}}parseBlock(e,t){let n=this.parseQuotedName(),r=this.peek().type===`RightDelim`?void 0:this.parsePipeline();this.expect(`RightDelim`,"`}}`");let i=this.rangeDepth;this.rangeDepth=0;let a=this.parseList();this.rangeDepth=i;let o={trimLeft:t,trimRight:this.consumeEnd()};return!this.defines.has(n)&&!this.inherit.has(n)&&this.defines.set(n,{list:a,source:this.source}),r?{type:`Block`,pos:e,name:n,pipe:r,list:a,trim:o}:{type:`Block`,pos:e,name:n,list:a,trim:o}}parseDefine(e,t){let n=this.parseQuotedName();this.expect(`RightDelim`,"`}}`");let r=this.rangeDepth;this.rangeDepth=0;let i=this.parseList();if(this.rangeDepth=r,this.consumeEnd(),this.defines.has(n)||this.inherit.has(n))throw new hS(`redefinition of template ${JSON.stringify(n)}`,i.pos,{source:this.source});this.defines.set(n,{list:i,source:this.source})}parseQuotedName(){let e=this.next();if(e.type!==`String`)throw this.errAt(e,`expected template name (quoted string)`,{expected:`string`,found:qS(e)});return tC(e.value,e.pos,this.source)}parsePipeline(){let e=this.peek().pos,t=this.tryParseDecls(),n=[this.parseCommand()];for(;this.peek().type===`Pipe`;){this.next();let e=this.peek();if(!JS(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:qS(e)});n.push(this.parseCommand())}return{type:`Pipe`,pos:e,decls:t?.vars??[],isAssign:t?.isAssign??!1,cmds:n}}tryParseDecls(){if(this.peek().type!==`Variable`)return;let e=1;for(;this.peek(e).type===`Comma`;){if(this.peek(e+1).type!==`Variable`)return;e+=2}let t=this.peek(e).type;if(t!==`Declare`&&t!==`Assign`)return;let n=[YS(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(YS(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;JS(this.peek().type);)t.push(this.parsePrimary());return{type:`Command`,pos:e,args:t}}parsePrimary(){let e=this.next();switch(e.type){case`Dot`:return{type:`Dot`,pos:e.pos};case`Field`:return{type:`Field`,pos:e.pos,idents:e.value.slice(1).split(`.`)};case`Variable`:return YS(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:tC(e.value,e.pos,this.source)};case`Number`:return ZS(e);case`Char`:return QS(e,this.source);case`Bool`:return{type:`Bool`,pos:e.pos,value:e.value===`true`};case`Nil`:return{type:`Nil`,pos:e.pos};case`LeftParen`:return this.parseChainOrPipe(e.pos);default:throw this.errAt(e,`expected command argument, found ${qS(e)}`,{expected:`command argument`,found:qS(e)})}}parseChainOrPipe(e){let t=this.parsePipeline(),n=this.expect(`RightParen`,"`)`"),r=[],i=n.pos.offset+1,a=this.peek();return a.type===`Field`&&a.pos.offset===i&&(this.next(),r.push(...a.value.slice(1).split(`.`))),r.length===0?t:{type:`Chain`,pos:e,node:t,fields:r}}};function GS(e,t){return{type:`List`,pos:e,nodes:t}}function KS(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function qS(e){return e.type===`EOF`?`end of input`:e.value||e.type}function JS(e){switch(e){case`Dot`:case`Field`:case`Variable`:case`Identifier`:case`String`:case`Number`:case`Char`:case`Bool`:case`Nil`:case`LeftParen`:return!0;default:return!1}}function YS(e){return{type:`Variable`,pos:e.pos,idents:XS(e.value)}}function XS(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function ZS(e){let t=e.value,n=t.replace(/_/g,``),r=n.toLowerCase().endsWith(`i`),i=r?n.slice(0,-1):n,a=!r&&(i.includes(`.`)||!i.startsWith(`0x`)&&!i.startsWith(`0X`)&&/[eE]/.test(i)||(i.startsWith(`0x`)||i.startsWith(`0X`))&&/[pP]/.test(i)),o=!r&&!a,s={type:`Number`,pos:e.pos,text:t,isInt:o,isUint:!1,isFloat:a,isComplex:r};if(o){let e=$S(i);return{...s,intValue:e}}if(a){let e=eC(i);return{...s,floatValue:e}}let c=eC(i);return{...s,complexValue:[0,c]}}function QS(e,t){let n=nC(e.value,e.pos,t);return{type:`Number`,pos:e.pos,text:e.value,isInt:!0,isUint:!1,isFloat:!1,isComplex:!1,intValue:BigInt(n)}}function $S(e){let t=1n,n=e;return n.startsWith(`+`)?n=n.slice(1):n.startsWith(`-`)&&(t=-1n,n=n.slice(1)),t*BigInt(n)}function eC(e){return Number(e)}function tC(e,t,n){if(e.startsWith("`"))return e.slice(1,-1);let r=``;for(let i=1;i<e.length-1;i++){let a=e[i];if(a!==`\\`){r+=a;continue}let o=e[++i];switch(o){case`n`:r+=`
68
- `;break;case`t`:r+=` `;break;case`r`:r+=`\r`;break;case`\\`:r+=`\\`;break;case`"`:r+=`"`;break;case`'`:r+=`'`;break;case`a`:r+=`\x07`;break;case`b`:r+=`\b`;break;case`f`:r+=`\f`;break;case`v`:r+=`\v`;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:{let t=o+(e[i+1]??``)+(e[i+2]??``);i+=2,r+=String.fromCodePoint(Number.parseInt(t,8));break}case`x`:{let t=(e[i+1]??``)+(e[i+2]??``);i+=2,r+=String.fromCodePoint(Number.parseInt(t,16));break}case`u`:{let t=e.slice(i+1,i+5);i+=4,r+=String.fromCodePoint(Number.parseInt(t,16));break}case`U`:{let t=e.slice(i+1,i+9);i+=8,r+=String.fromCodePoint(Number.parseInt(t,16));break}default:throw new hS(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function nC(e,t,n){let r=tC(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new hS(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function rC(e,t){if(t(e)!==!1)for(let n of iC(e))rC(n,t)}function iC(e){switch(e.type){case`Text`:case`Comment`:case`Dot`:case`Nil`:case`Bool`:case`Number`:case`String`:case`Identifier`:case`Field`:case`Variable`:case`Break`:case`Continue`:return[];case`List`:return e.nodes;case`Chain`:return[e.node];case`Command`:return e.args;case`Pipe`:return[...e.decls,...e.cmds];case`Action`:return[e.pipe];case`If`:case`Range`:case`With`:return e.elseList?[e.pipe,e.list,e.elseList]:[e.pipe,e.list];case`Template`:return e.pipe?[e.pipe]:[];case`Block`:return e.pipe?[e.pipe,e.list]:[e.list];default:return ES(e)}}const aC=Symbol(`go-template-js.MISSING`);function oC(e,t){if(e==null)return aC;if(e instanceof Map)return e.has(t)?e.get(t):aC;if(Array.isArray(e))return aC;if(typeof e==`object`){let n=e;return t in n?n[t]:aC}return aC}function sC(e,t){let n=e;for(let e of t){if(n===aC)return aC;n=oC(n,e)}return n}function cC(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||e===void 0||t===void 0||typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length?e.every((e,n)=>cC(e,t[n])):!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!cC(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}if(typeof e==`object`&&typeof t==`object`){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length?n.every(n=>cC(e[n],t[n])):!1}return!1}const lC=new WeakSet;function uC(e){return lC.add(e),e}function dC(e){return lC.has(e)}function fC(e){return e==null||e===!1?!1:typeof e==`number`?e!==0&&!Number.isNaN(e):typeof e==`bigint`?e!==0n:typeof e==`string`||Array.isArray(e)?e.length>0:e instanceof Map||e instanceof Set?e.size>0:typeof e==`object`?Object.keys(e).length>0:!!e}function pC(e,t){return{eq:{fn:(e,...t)=>t.some(t=>gC(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!gC(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>_C(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>_C(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>_C(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>_C(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>vC(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=yC(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>xC(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>wC(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${wC(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>NC(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>IC(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>IC(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>DC(wC(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>AC(wC(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>MC(wC(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!fC(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function mC(){return{and:uC({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!fC(t))return t;return t}}),or:uC({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),fC(t))return t;return t}})}}function hC(e,t){return{...pC(e,t),...mC()}}function gC(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):cC(e,t)}function _C(e,t){if(typeof e==`bigint`&&typeof t==`bigint`)return e===t?0:e<t?-1:1;if(typeof e==`bigint`||typeof t==`bigint`){let n=typeof e==`bigint`?e:BigInt(Math.trunc(Number(e))),r=typeof t==`bigint`?t:BigInt(Math.trunc(Number(t)));return n===r?0:n<r?-1:1}let n=e,r=t;return n===r?0:n<r?-1:1}function vC(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function yC(e,t){if(Array.isArray(e)||typeof e==`string`){let n=bC(t,e.length);if(n===e.length)throw Error(`index out of range: ${n}`);return e[n]}if(e instanceof Map)return e.get(t);if(typeof e==`object`&&e){if(typeof t!=`string`)throw Error(`index: object index must be string, got ${SC(t)}`);return e[t]}throw Error(`index: cannot index ${SC(e)}`)}function bC(e,t){let n=typeof e==`bigint`?Number(e):e;if(typeof n!=`number`||!Number.isInteger(n))throw Error(`cannot index slice/array with type ${CC(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function xC(e,t){if(t.length>3)throw Error(`too many slice indexes: ${t.length}`);if(typeof e==`string`&&t.length>2)throw Error(`cannot 3-index slice a string`);let n=e.length,r=[0,n,n];t.forEach((e,t)=>{r[t]=bC(e,n)});let[i,a,o]=r;if(i>a)throw Error(`invalid slice index: ${i} > ${a}`);if(a>o)throw Error(`invalid slice index: ${a} > ${o}`);return e.slice(i,a)}function SC(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function CC(e){return e==null?`<nil>`:typeof e==`string`?`string`:typeof e==`boolean`?`bool`:typeof e==`bigint`?`int64`:typeof e==`number`?Number.isInteger(e)?`int`:`float64`:Array.isArray(e)?`[]interface {}`:e instanceof Map||typeof e==`object`?`map[string]interface {}`:typeof e}function wC(e,t){let n=``,r=!1;for(let i=0;i<e.length;i++){let a=e[i],o=typeof a==`string`;i>0&&!r&&!o&&(n+=` `),n+=TC(a,t),r=o}return n}function TC(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const EC={"\0":`�`,'"':`&#34;`,"'":`&#39;`,"&":`&amp;`,"<":`&lt;`,">":`&gt;`};function DC(e){return e.replace(/[\0"'&<>]/g,e=>EC[e]??e)}const OC={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},kC=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function AC(e){let t=``;for(let n of e){let e=OC[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!kC.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const jC=new TextEncoder;function MC(e){let t=``,n=jC.encode(e);for(let e of n)e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===45||e===46||e===95||e===126?t+=String.fromCharCode(e):e===32?t+=`+`:t+=`%${e.toString(16).toUpperCase().padStart(2,`0`)}`;return t}function NC(e,t,n,r){let i=``,a=0,o=0;for(;o<e.length;){let s=e[o];if(s!==`%`){i+=s,o+=1;continue}if(e[o+1]===`%`){i+=`%`,o+=2;continue}let c=o+1;for(;c<e.length&&`+-# 0`.includes(e[c]??``);)c+=1;for(;c<e.length&&e[c]!==void 0&&/[0-9]/.test(e[c]);)c+=1;if(e[c]===`.`)for(c+=1;c<e.length&&e[c]!==void 0&&/[0-9]/.test(e[c]);)c+=1;let l=e[c],u=e.slice(o+1,c),d=t[a++];i+=PC(l??``,u,d,n,r),o=c+1}return i}function PC(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?FC(t,n):FC(t,TC(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${CC(n)}=${TC(n,r)})`:FC(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return FC(t,IC(n,r,i));case`q`:return FC(t,JSON.stringify(TC(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${CC(n)}=${TC(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return FC(t,Number(n).toFixed(i))}case`t`:return FC(t,fC(n)?`true`:`false`);case`x`:if(typeof n==`string`){let e=new TextEncoder().encode(n),r=``;for(let t of e)r+=t.toString(16).padStart(2,`0`);return FC(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${CC(n)}=${TC(n,r)})`:typeof n==`bigint`?FC(t,n.toString(16)):FC(t,Math.trunc(n).toString(16));default:return`%!${e}(${CC(n)}=${TC(n,r)})`}}function FC(e,t){let n=e.match(/^([+\-# 0]*)/)?.[1]??``,r=e.slice(n.length).match(/^(\d+)/);if(!r)return t;let i=Number(r[1]);if(t.length>=i)return t;let a=` `.repeat(i-t.length);return n.includes(`-`)?t+a:a+t}function IC(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>IC(e,t,n)).join(` `)}]`:e instanceof Map?LC([...e.entries()],t,n):RC(e)?LC(Object.entries(e),t,n):String(e)}function LC(e,t,n){let r=e=>IC(e,t,n),i=e=>typeof e==`number`||typeof e==`bigint`,a=([e],[t])=>{if(i(e)&&i(t))return e<t?-1:+(e>t);if(i(e)!==i(t))return i(e)?-1:1;let[n,a]=[r(e),r(t)];return n<a?-1:+(n>a)};return`map[${[...e].sort(a).map(([e,t])=>`${r(e)}:${r(t)}`).join(` `)}]`}function RC(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Map||e instanceof Set)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function zC(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function BC(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function VC(e,t){let n=e;for(;n!==void 0;){if(n.vars.has(t))return{found:!0,value:n.vars.get(t)};n=n.parent}return{found:!1}}function HC(e,t,n){e.vars.set(t,n)}const UC=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],WC=new Set([`default`,`zero`,`error`]);function GC(e){if(e===void 0)return`default`;if(WC.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${KC(e)}`)}function KC(e){return typeof e==`string`?JSON.stringify(e):e===null?`null`:e===void 0?`undefined`:typeof e==`bigint`?`${e}n`:typeof e==`number`||typeof e==`boolean`?String(e):typeof e==`symbol`?e.toString():typeof e==`function`?`[Function]`:`[${typeof e}]`}function qC(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${KC(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${KC(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${KC(e.right)}`);return{left:e.left,right:e.right}}}function JC(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function YC(e){let t=new Set(UC);for(let[n,r]of Object.entries(e)){if(r.argTypes.forEach((e,r)=>{if(!t.has(e))throw Error(`EngineConfig.funcs.${n}: argTypes[${r}] is ${JSON.stringify(e)}, which is not an ArgType; declare one of ${UC.join(`, `)}`)}),JC(r.arity)&&r.argTypes.length===0)throw Error(`EngineConfig.funcs.${n}: arity ${JSON.stringify(r.arity.kind)} needs at least one declared argType (it reads its repeating slot from the end of argTypes); declare the slots the Go signature has, or use { kind: "exact" }`);if(r.arity.kind===`alternating`&&(!Number.isSafeInteger(r.arity.minimum)||r.arity.minimum<0))throw Error(`EngineConfig.funcs.${n}: arity "alternating" needs a non-negative integer minimum, got ${String(r.arity.minimum)}; the gate rejects every count below it, so a negative or non-finite minimum would disable the lower bound`)}return e}const XC=Object.freeze({kind:`break`}),ZC=Object.freeze({kind:`continue`}),QC={kind:`none`};let $C;(class e{source;_evaluate;_defines;_referencedFunctions;_referencedCalls;constructor(e,t,n,r,i){this.source=e,this._evaluate=t,this._defines=n,this._referencedFunctions=r,this._referencedCalls=i}static{$C=(t,n,r,i,a)=>new e(t,n,r,i,a)}defines(){return this._defines}evaluate(e){return this._evaluate(e)}referencedFunctions(){return this._referencedFunctions}referencedCalls(){return this._referencedCalls}});function ew(e){let t=new Set,n=e=>{rC(e,e=>{e.type===`Identifier`&&t.add(e.ident)})};n(e.root);for(let t of e.ownDefines.values())n(t.list);return t}const tw={kind:`dynamic`};function nw(e){switch(e.type){case`String`:return{kind:`literal`,value:e.value};case`Bool`:return{kind:`literal`,value:e.value};case`Nil`:return{kind:`literal`,value:null};case`Number`:{let t=Cw(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:tw}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return tw;let t=e.cmds[0];if(t===void 0)return tw;let n=t.args[0];return n===void 0||n.type!==`Identifier`?tw:{kind:`call`,name:n.ident,args:t.args.slice(1).map(nw)}}default:return tw}}function rw(e){let t=[],n=e=>{rC(e,e=>{if(e.type!==`Command`)return;let n=e.args[0];if(n===void 0||n.type!==`Identifier`)return;let r=e.args.slice(1).map(nw);t.push({name:n.ident,args:r.map(e=>e.kind===`literal`&&typeof e.value==`string`?e.value:null),argExprs:r})})};n(e.root);for(let t of e.ownDefines.values())n(t.list);return t}var iw=class{fromString;toString;isT;funcs;missingKey;delims;constructor(e){this.fromString=e.fromString;let t=Object.hasOwn(e,`toString`)?e.toString:void 0;this.toString=t??fw,this.isT=e.isT??aw,this.missingKey=GC(e.missingKey),this.delims=qC(e.delims),this.funcs=YC({...hC(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=US(e,this.delims,t);return $C(n.source,e=>this.evalParsed(n,e),n.defines,ew(n),rw(n))}compile(e){let t=this.parse(e);return e=>t.evaluate(e)}evaluate(e,t){return e.evaluate(t)}evalParsed(e,t){let n=[],r=zC(t),i={out:n,defines:e.defines,source:e.source};return this.evalList(e.root,r,i),n}evalList(e,t,n){for(let r of e.nodes)this.evalNode(r,t,n)}evalNode(e,t,n){switch(e.type){case`Text`:n.out.push(this.fromString(e.text));return;case`Comment`:return;case`Action`:{let r=this.evalAction(e,t,n);e.pipe.decls.length===0&&this.emitFromValue(r,n);return}case`List`:this.evalList(e,t,n);return;case`If`:this.evalIf(e,t,n);return;case`Range`:this.evalRange(e,t,n);return;case`With`:this.evalWith(e,t,n);return;case`Break`:throw XC;case`Continue`:throw ZC;case`Template`:this.evalTemplateInvoke(e,t,n);return;case`Block`:this.evalBlock(e,t,n);return;case`Pipe`:case`Command`:case`Identifier`:case`Field`:case`Variable`:case`Chain`:case`Dot`:case`Nil`:case`Bool`:case`Number`:case`String`:throw new gS(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:ES(e)}}evalIf(e,t,n){fC(this.evalPipe(e.pipe,t,n))?this.evalList(e.list,t,n):e.elseList&&this.evalList(e.elseList,t,n)}evalWith(e,t,n){let r=this.evalPipe(e.pipe,t,n);if(fC(r)){let i=BC(t,r);this.evalList(e.list,i,n)}else e.elseList&&this.evalList(e.elseList,t,n)}evalRange(e,t,n){let r=this.evalPipeWithoutDecls(e.pipe,t,n),i=e.pipe.decls,a=bw(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=BC(t,o);if(i.length===1)HC(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;HC(a,e,r),HC(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===ZC)continue;throw e}}}catch(e){if(e===XC)return;throw e}}evalTemplateInvoke(e,t,n){let r=VS(n.defines,e.name);if(!r)throw new gS(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=BC(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot);this.evalList(r.list,i,{out:n.out,defines:n.defines,source:r.source})}evalBlock(e,t,n){let r=BC(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=VS(n.defines,e.name)??{list:e.list,source:n.source};this.evalList(i.list,r,{out:n.out,defines:n.defines,source:i.source})}evalAction(e,t,n){return this.evalPipe(e.pipe,t,n)}evalPipe(e,t,n){if(e.cmds.length===0)throw new gS(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,QC);for(let i=1;i<e.cmds.length;i++){let a=e.cmds[i];r=this.evalCommand(a,t,n,{kind:`value`,value:r})}if(e.decls.length>0)for(let n of e.decls)HC(t,n.idents[0]??`$`,r);return r}evalPipeWithoutDecls(e,t,n){let r={type:`Pipe`,pos:e.pos,decls:[],isAssign:!1,cmds:e.cmds};return this.evalPipe(r,t,n)}evalCommand(e,t,n,r){if(e.args.length===0)throw new gS(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new gS(`cannot apply arguments to a ${i.type} primary; only functions take arguments`,e.pos,{source:n.source});return this.evalPrimary(i,t,n)}let a=this.funcs[i.ident];if(!a)throw new _S(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=dC(a),c=o.map(e=>s?()=>this.evalPrimary(e,t,n):this.evalPrimary(e,t,n));if(r.kind===`value`){let e=r.value;c.push(s?()=>e:e)}return this.invoke(i.ident,a,c,e.pos,n)}invoke(e,t,n,r,i){sw(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof yS?new yS(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof SS?new SS(t.message,r,{source:i.source}):t instanceof mS?t:new gS(`error calling ${e}: ${vw(t)}`,r,{source:i.source,cause:t})}}evalPrimary(e,t,n){switch(e.type){case`Dot`:return t.dot;case`Nil`:return null;case`Bool`:return e.value;case`Number`:return Cw(e);case`String`:return e.value;case`Field`:return this.resolveFieldChain(t.dot,e.idents,e.pos,n);case`Variable`:return this.resolveVariable(e.idents,t,e.pos,n);case`Identifier`:{let t=this.funcs[e.ident];if(!t)throw new _S(e.ident,e.pos,{source:n.source,available:Object.keys(this.funcs)});return this.invoke(e.ident,t,[],e.pos,n)}case`Chain`:return this.resolveFieldChain(this.evalPrimary(e.node,t,n),e.fields,e.pos,n);case`Pipe`:return this.evalPipe(e,t,n);default:throw new gS(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=sC(e,t);if(i!==aC)return i;if(this.missingKey===`error`)throw new xS(t,n,{source:r.source})}resolveVariable(e,t,n,r){let i=e[0]??`$`;if(i===`$`){let i=e.slice(1);return i.length===0?t.root:this.resolveFieldChain(t.root,i,n,r)}let a=VC(t,i);if(!a.found)throw new gS(`undefined variable ${i}`,n,{source:r.source});let o=e.slice(1);return o.length===0?a.value:this.resolveFieldChain(a.value,o,n,r)}emitFromValue(e,t){if(e==null){t.out.push(this.fromString(`<no value>`));return}if(typeof e==`string`){t.out.push(this.fromString(e));return}if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`){t.out.push(this.fromString(String(e)));return}if(this.isT(e)){t.out.push(e);return}t.out.push(this.fromString(IC(e,this.toString,this.isT)))}};const aw=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function ow(e){return new iw(e)}function sw(e,t,n,r,i,a=fw,o=dw,s=aw){let{argTypes:c,arity:l}=t,u=cw(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new vS(e,u,n.length,r,{source:i});let d=lw(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!uw(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new bS(e,t+1,l,r,{source:i}):new yS(e,t+1,_w(c),yw(l),r,{source:i});if(c===`liftable`&&typeof l==`string`&&(n[t]=o(l)),c===`truncating-int`?n[t]=Math.trunc(Number(l)):(c===`int`||c===`float`)&&(n[t]=Number(l)),c===`ordered`){if(f===-1)f=t;else if(!mw(n[f],l))throw new yS(e,t+1,`${_w(`ordered`)} of the same kind as ${yw(n[f])}`,yw(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!hw(n[p],l))throw new yS(e,t+1,`${_w(`comparable`)} of the same kind as ${yw(n[p])}`,yw(l),r,{source:i})}}}function cw(e,t){switch(t.kind){case`exact`:return{minimum:e.length,maximum:e.length};case`variadic`:return{minimum:e.length-1,maximum:1/0};case`alternating`:return{minimum:t.minimum,maximum:1/0}}}function lw(e,t){let n=e.length;switch(t.kind){case`exact`:return t=>e[t];case`variadic`:return t=>e[Math.min(t,n-1)];case`alternating`:return t=>e[t%n]}}function uw(e,t,n,r){switch(e){case`truthy`:case`reflective`:case`value`:return!0;case`string`:return typeof t==`string`;case`int`:return typeof t==`number`&&Number.isSafeInteger(t)||typeof t==`bigint`&&Number.isSafeInteger(Number(t));case`truncating-int`:return typeof t==`number`&&Number.isFinite(t)||typeof t==`bigint`&&Number.isSafeInteger(Number(t));case`float`:return typeof t==`number`||typeof t==`bigint`&&Number.isFinite(Number(t));case`bool`:return typeof t==`boolean`;case`ordered`:return typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`;case`T`:return r(t);case`list`:return Array.isArray(t);case`dict`:return RC(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||RC(t);case`comparable`:return t==null||typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`||Array.isArray(t)||t instanceof Map||t instanceof Set||RC(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||RC(t);case`index-key`:return typeof t==`string`||typeof t==`number`||typeof t==`bigint`;case`sliceable`:return typeof t==`string`||Array.isArray(t);case`stringifiable`:if(typeof t==`string`)return!0;try{return n(t),!0}catch{return!1}case`liftable`:return typeof t==`string`||r(t);case`serializable`:return pw(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function dw(e){return e}function fw(e){if(typeof e==`string`)return e;if(e==null)return`<nil>`;if(typeof e==`number`||typeof e==`bigint`||typeof e==`boolean`)return String(e);throw new yS(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,yw(e),{line:0,column:0,offset:0})}function pw(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function mw(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function hw(e,t){let n=gw(e),r=gw(t);return n===`nil`||r===`nil`?!0:n===r}function gw(e){return e==null?`nil`:typeof e==`string`?`string`:typeof e==`number`||typeof e==`bigint`?`number`:typeof e==`boolean`?`boolean`:Array.isArray(e)?`array`:e instanceof Map?`map`:e instanceof Set?`set`:`object`}function _w(e){switch(e){case`int`:return`integer (safe-integer number or bigint)`;case`truncating-int`:return`integer (finite number, truncated toward zero, or safe-integer bigint)`;case`float`:return`float (number, including NaN/Infinity, or finite-convertible bigint)`;case`T`:return`T (consumer-defined fragment)`;case`ordered`:return`orderable primitive`;case`list`:return`list`;case`dict`:return`dict (plain object)`;case`sized`:return`sized value (string, list, map, set, or dict)`;case`comparable`:return`comparable value (orderable primitive, nil, list, dict, Map, or Set)`;case`stringifiable`:return`stringifiable value (string or convertible via the engine's toString)`;case`liftable`:return`liftable value (T or string, the latter lifted via the engine's fromString)`;case`callable`:return`callable (function value)`;case`collection`:return`collection (string, array, Map, or dict)`;case`index-key`:return`index key (number, bigint, or string)`;case`sliceable`:return`sliceable value (string or array)`;case`serializable`:return`JSON-serializable value`;case`truthy`:case`reflective`:case`value`:case`string`:case`bool`:return e;default:throw Error(`invalid ArgType: ${String(e)}`)}}function vw(e){return e instanceof Error?e.message:String(e)}function yw(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function bw(e){return e==null?[]:Array.isArray(e)?e.map((e,t)=>[t,e]):typeof e==`string`?[...e].map((e,t)=>[t,e]):e instanceof Map?xw([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?xw(Object.entries(e)):[]}function xw(e){return[...e].sort((e,t)=>Sw(e[0],t[0]))}function Sw(e,t){if((typeof e==`number`||typeof e==`bigint`)&&(typeof t==`number`||typeof t==`bigint`)){let n=typeof e==`bigint`?Number(e):e,r=typeof t==`bigint`?Number(t):t;return n===r?0:n<r?-1:1}let n=String(e),r=String(t);return n===r?0:n<r?-1:1}function Cw(e){if(e.intValue!==void 0){let t=e.intValue;return t>=BigInt(-(2**53-1))&&t<=BigInt(2**53-1)?Number(t):t}if(e.floatValue!==void 0)return e.floatValue;if(e.complexValue!==void 0)return e.complexValue;throw Error(`internal: NumberNode has none of intValue/floatValue/complexValue — parser invariant violated`)}function ww(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function Tw(e){if(typeof e==`number`)return e;if(typeof e==`bigint`)return Number(e);if(typeof e==`string`){let t=Number.parseFloat(e);return Number.isNaN(t)?0:t}return typeof e==`boolean`?+!!e:0}function Ew(e){if(e===``)return null;let t=1,n=e;return n[0]===`+`?n=n.slice(1):n[0]===`-`&&(t=-1,n=n.slice(1)),n===``?null:/^0x[0-9a-fA-F]+$/i.test(n)?{sign:t,digits:n.slice(2),base:16}:/^0b[01]+$/i.test(n)?{sign:t,digits:n.slice(2),base:2}:/^0o[0-7]+$/i.test(n)?{sign:t,digits:n.slice(2),base:8}:n===`0`?{sign:t,digits:`0`,base:10}:n[0]===`0`?/^0[0-7]+$/.test(n)?{sign:t,digits:n.slice(1),base:8}:null:/^[0-9]+$/.test(n)?{sign:t,digits:n,base:10}:null}function Dw(e){if(typeof e==`number`){let t=Math.trunc(e);return Number.isSafeInteger(t)?t:0}if(typeof e==`bigint`){let t=Number(e);return Number.isSafeInteger(t)?t:0}if(typeof e==`string`){let t=Ew(e);if(t===null)return 0;let n=t.sign*Number.parseInt(t.digits,t.base);return Number.isSafeInteger(n)?n:0}return typeof e==`boolean`?+!!e:0}function Ow(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=Ew(e);if(t===null)return 0n;let n=t.base===16?`0x`:t.base===2?`0b`:t.base===8?`0o`:``,r=BigInt(n+t.digits);return t.sign===-1?-r:r}return typeof e==`boolean`&&e?1n:0n}function kw(e){if(!/^[+-]?[0-7]+$/.test(e))return 0;let t=e[0]===`-`?-1:1,n=e[0]===`+`||e[0]===`-`?e.slice(1):e,r=t*Number.parseInt(n,8);return Number.isSafeInteger(r)?r:0}function Aw(e){return JSON.stringify(e)??`null`}function jw(){return{atoi:{fn:e=>ww(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>Dw(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>Ow(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>Tw(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>kw(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>Aw(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const Mw={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function Nw(e){if(e===`0`)return 0;let t=!1,n=e;if(n.startsWith(`-`)?(t=!0,n=n.slice(1)):n.startsWith(`+`)&&(n=n.slice(1)),!n)return NaN;let r=0,i=/^(\d+(?:\.\d+)?)(ns|µs|us|ms|[smh])/;for(;n.length>0;){let e=i.exec(n);if(!e)return NaN;let t=parseFloat(e[1]??`0`),a=e[2];r+=t*Mw[a],n=n.slice(e[0].length)}return t?-r:r}function Pw(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<Mw.us?`${Math.floor(n)}ns`:n<Mw.ms?Fw(n,Mw.us,3,`µs`):n<Mw.s?Fw(n,Mw.ms,6,`ms`):Iw(n),t?`-${r}`:r}function Fw(e,t,n,r){let i=Math.floor(e/t),a=Math.round(e%t);return a===0?`${i}${r}`:`${i}.${String(a).padStart(n,`0`).replace(/0+$/,``)}${r}`}function Iw(e){let t=Math.floor(e/Mw.h);e-=t*Mw.h;let n=Math.floor(e/Mw.m);e-=n*Mw.m;let r=Math.floor(e/Mw.s),i=e-r*Mw.s,a=i===0?`${r}s`:`${r}.${String(Math.round(i)).padStart(9,`0`).replace(/0+$/,``)}s`;return t>0?`${t}h${n}m${a}`:n>0?`${n}m${a}`:a}function Lw(e){return e*Mw.s}function Rw(e){if(e instanceof Date)return e;if(typeof e==`bigint`)return new Date(Number(e)*1e3);if(typeof e==`number`)return new Date(e*1e3);if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t;throw Error(`sprig: cannot parse date value ${JSON.stringify(e)}`)}throw Error(`sprig: unsupported date type: ${typeof e}`)}function zw(e,t){let n=t().getTime()-Rw(e).getTime();return Pw(Math.round(n/1e3)*1e9)}const Bw=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Vw=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Hw=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],Uw=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function Ww(e){return e<10?`0${e}`:String(e)}function Gw(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function Kw(e){return e<10?` ${e}`:String(e)}function qw(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${Ww(Math.floor(n/60))}${Ww(n%60)}`}function Jw(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${Ww(Math.floor(n/60))}:${Ww(n%60)}`}function Yw(e){return`${e>=0?`+`:`-`}${Ww(Math.floor(Math.abs(e)/60))}`}function Xw(e){return e===0?`Z`:qw(e)}function Zw(e){return e===0?`Z`:Jw(e)}function Qw(e){return e===0?`Z`:Yw(e)}function $w(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const eT=[[`.000000000`,e=>`.${$w(e.ms,9,!1)}`],[`.999999999`,e=>{let t=$w(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${$w(e.ms,6,!1)}`],[`.999999`,e=>{let t=$w(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${Gw(e.ms)}`],[`.999`,e=>{let t=Gw(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>Bw[e.month-1]??`January`],[`Monday`,e=>Hw[e.weekday]??`Monday`],[`Z07:00`,e=>Zw(e.offsetMinutes)],[`-07:00`,e=>Jw(e.offsetMinutes)],[`Z0700`,e=>Xw(e.offsetMinutes)],[`-0700`,e=>qw(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>Vw[e.month-1]??`Jan`],[`Mon`,e=>Uw[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>Yw(e.offsetMinutes)],[`Z07`,e=>Qw(e.offsetMinutes)],[`15`,e=>Ww(e.hour)],[`01`,e=>Ww(e.month)],[`02`,e=>Ww(e.day)],[`_2`,e=>Kw(e.day)],[`03`,e=>Ww(e.hour12)],[`04`,e=>Ww(e.minute)],[`05`,e=>Ww(e.second)],[`06`,e=>Ww(e.year%100)],[`PM`,e=>e.hour>=12?`PM`:`AM`],[`pm`,e=>e.hour>=12?`pm`:`am`],[`1`,e=>String(e.month)],[`2`,e=>String(e.day)],[`3`,e=>String(e.hour12)],[`4`,e=>String(e.minute)],[`5`,e=>String(e.second)]];function tT(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of eT)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const nT={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function rT(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const iT=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function aT(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=rT(new Intl.DateTimeFormat(`en-US`,{...nT,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=rT(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=oT(rT(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=iT.indexOf(r.get(`weekday`)??`Sunday`);return{year:parseInt(r.get(`year`)??`2000`,10),month:parseInt(r.get(`month`)??`1`,10),day:parseInt(r.get(`day`)??`1`,10),weekday:s===-1?0:s,hour:i,hour12:i%12||12,minute:parseInt(r.get(`minute`)??`0`,10),second:parseInt(r.get(`second`)??`0`,10),ms:e.getUTCMilliseconds(),tzAbbr:a,offsetMinutes:o}}function oT(e){if(e===`GMT`||e===`UTC`)return 0;let t=e.match(/^GMT([+-])(\d{1,2})(?::(\d{2}))?$/);if(!t)return 0;let n=t[1]===`+`?1:-1,r=parseInt(t[2]??`0`,10),i=parseInt(t[3]??`0`,10);return n*(r*60+i)}function sT(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function cT(e,t){return tT(e,aT(Rw(t),sT()))}function lT(e,t,n){return tT(e,aT(Rw(t),n))}function uT(e,t){let n=Rw(t),r=Nw(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function dT(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:Pw(Lw(t))}return typeof e==`bigint`?Pw(Lw(Number(e))):typeof e==`number`?Pw(Lw(e)):`0s`}const fT=36e11*24*365,pT=36e11*24*30,mT=36e11*24,hT=36e11,gT=6e10,_T=1e9;function vT(e){let t=Nw(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>fT?`${Math.floor(n/fT)}y`:n>pT?`${Math.floor(n/pT)}mo`:n>mT?`${Math.floor(n/mT)}d`:n>hT?`${Math.floor(n/hT)}h`:n>gT?`${Math.floor(n/gT)}m`:n>_T?`${Math.floor(n/_T)}s`:`0s`}function yT(e){let t=aT(Rw(e),sT());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function bT(e,t){let n=aT(Rw(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function xT(e){return e()}const ST=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],CT=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function wT(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function TT(e,t,n){return[e.slice(t,t+n),t+n]}function ET(e,t,n,r){let i=t;for(;i<e.length&&i-t<r&&e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57;)i++;if(i-t<n)throw Error(`sprig toDate: expected ${n}-${r} digits at pos ${t}`);return[parseInt(e.slice(t,i),10),i]}function DT(e,t){for(let[n,r]of ST.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function OT(e,t){for(let[n,r]of CT.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function kT(e,t){for(let n of[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`])if(e.startsWith(n,t))return t+n.length;throw Error(`sprig toDate: expected weekday name at pos ${t}`)}function AT(e,t){for(let n of[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`])if(e.startsWith(n,t))return t+n.length;throw Error(`sprig toDate: expected short weekday name at pos ${t}`)}function jT(e,t){if(e[t]===` `){let[n,r]=ET(e,t+1,1,1);return[n,r]}return ET(e,t,1,2)}function MT(e,t,n){let r=e[t]===`+`?1:e[t]===`-`?-1:0;if(r===0)throw Error(`sprig toDate: expected +/- at pos ${t}`);let i=t+1,[a,o]=ET(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=ET(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=ET(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function NT(e,t,n,r){if(e[t]===`Z`)return[0,t+1];if(r){let n=e[t]===`+`?1:e[t]===`-`?-1:0;if(n===0)throw Error(`sprig toDate: expected Z or +/- at pos ${t}`);let[r,i]=ET(e,t+1,2,2);return[n*r*60,i]}return MT(e,t,n)}function PT(e,t){let n=t;for(;n<e.length&&e.charCodeAt(n)>=65&&e.charCodeAt(n)<=90;)n++;if(n===t)throw Error(`sprig toDate: expected timezone abbreviation at pos ${t}`);return n}function FT(e,t,n){let[r,i]=TT(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function IT(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=DT(t,n);return i.month=e,[r,i]}case`Monday`:return[kT(t,n),i];case`Jan`:{let[e,r]=OT(t,n);return i.month=e,[r,i]}case`Mon`:return[AT(t,n),i];case`2006`:{let[e,r]=ET(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=ET(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=ET(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=ET(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=jT(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=ET(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=ET(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=ET(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=ET(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=ET(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=ET(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=ET(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=ET(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=ET(t,n,1,2);return i.second=e,[r,i]}case`PM`:case`pm`:{let e=t.slice(n,n+2).toLowerCase();if(e!==`am`&&e!==`pm`)throw Error(`sprig toDate: expected AM/PM at pos ${n}, got ${JSON.stringify(t.slice(n,n+2))}`);return i.isPM=e===`pm`,i.hour12=!0,[n+2,i]}case`MST`:return[PT(t,n),i];case`-0700`:{let[e,r]=MT(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=MT(t,n,!0);return i.offsetMinutes=e,[r,i]}case`-07`:{let e=t[n]===`+`?1:t[n]===`-`?-1:0;if(e===0)throw Error(`sprig toDate: expected +/- at pos ${n}`);let[r,a]=ET(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=NT(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=NT(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=NT(t,n,!1,!0);return i.offsetMinutes=e,[r,i]}case`.000000000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=FT(t,n+1,9);return i.ms=e,[r,i]}case`.999999999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(9,`0`);return i.ms=Math.round(parseInt(a,10)/1e6),[r,i]}case`.000000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=FT(t,n+1,6);return i.ms=e,[r,i]}case`.999999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(9,`0`);return i.ms=Math.round(parseInt(a,10)/1e6),[r,i]}case`.000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=FT(t,n+1,3);return i.ms=e,[r,i]}case`.999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(3,`0`);return i.ms=parseInt(a,10),[r,i]}}throw Error(`sprig toDate: unhandled token ${e}`)}const LT=`.000000000,.999999999,.000000,.999999,.000,.999,January,Monday,Z07:00,-07:00,Z0700,-0700,2006,Jan,Mon,MST,-07,Z07,15,01,02,_2,03,04,05,06,PM,pm,1,2,3,4,5`.split(`,`);function RT(e,t){let n=0,r=0,i=wT();for(;n<e.length;){let a=!1;for(let o of LT)if(e.startsWith(o,n)){let[e,s]=IT(o,t,r,i);r=e,i=s,n+=o.length,a=!0;break}if(!a){let i=e.charAt(n);if(t[r]!==i)throw Error(`sprig toDate: expected ${JSON.stringify(i)} at pos ${r}, got ${JSON.stringify(t[r])}`);n++,r++}}if(r!==t.length)throw Error(`sprig toDate: extra characters at pos ${r}: ${JSON.stringify(t.slice(r))}`);if(i.hour12){let e=i.hour%12;i.hour=i.isPM?e+12:e}let a=Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second,i.ms)-i.offsetMinutes*60*1e3;return new Date(a)}function zT(e,t){return RT(e,t)}function BT(e){return String(Math.floor(Rw(e).getTime()/1e3))}function VT(e=()=>new Date){return{now:{fn:()=>xT(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>cT(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>lT(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>uT(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>yT(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>bT(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>dT(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>vT(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>zT(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>zw(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>BT(e),argTypes:[`value`],arity:{kind:`exact`}}}}function HT(e){return e==null||e===!1?!0:typeof e==`number`?e===0||Number.isNaN(e):typeof e==`bigint`?e===0n:typeof e==`string`||Array.isArray(e)?e.length===0:e instanceof Map||e instanceof Set?e.size===0:typeof e==`object`?Object.keys(e).length===0:!1}function UT(...e){for(let t of e)if(!HT(t))return t}function WT(e,t){return HT(t)?e:t}function GT(e){return JSON.parse(e)}function KT(e,t,n){return fC(n)?e:t}function qT(e){return JSON.stringify(e)??`null`}function JT(e){return JSON.stringify(e,null,2)??`null`}function YT(){return{default:{fn:(e,t)=>WT(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>HT(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>UT(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>KT(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>GT(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>qT(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>JT(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function XT(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function ZT(e){if(e.kind!==`call`||e.name!==`dict`||e.args.length%2!=0)return null;let t=[];for(let[n,r]of e.args.entries()){if(r.kind!==`literal`||n%2==0&&typeof r.value!=`string`)return null;t.push(r.value)}return XT(...t)}function QT(e,t){return e[t]}function $T(e,t){return t in e}function eE(e){return Object.keys(e)}function tE(e,...t){let n={...e};for(let e of t)for(let[t,r]of Object.entries(e))t in n||(n[t]=r);return n}function nE(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function rE(e,...t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e))n.has(t)||(r[t]=i);return r}function iE(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function aE(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function oE(e,t,n){return e[t]=n,e}function sE(e,t){return delete e[t],e}function cE(e){return Object.values(e)}function lE(){return{dict:{fn:(...e)=>XT(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>QT(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>oE(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>sE(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>eE(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>cE(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>aE(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>iE(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>rE(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>$T(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>tE(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>nE(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function uE(e){throw new SS(e)}function dE(){return{fail:{fn:e=>uE(e),argTypes:[`string`],arity:{kind:`exact`}}}}new TextEncoder,new Map(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`).map((e,t)=>[e,t])),new TextDecoder,new TextEncoder,new TextDecoder,new TextEncoder;function fE(...e){for(let t of e)if(HT(t))return!1;return!0}function pE(...e){for(let t of e)if(!HT(t))return!0;return!1}function mE(e,t){return[...e,t]}function hE(e,t){let n=Math.max(1,e),r=[];for(let e=0;e<t.length;e+=n)r.push(t.slice(e,e+n));return r}function gE(e){return e.filter(e=>!HT(e))}function _E(...e){let t=[];for(let n of e)t.push(...n);return t}const vE={line:0,column:0,offset:0};function yE(e,t,n,r){return new yS(e,t,n,r,vE)}function bE(...e){if(e.length<3)throw yE(`dig`,0,`at least 3 arguments (...keys, default, dict)`,`${e.length} argument${e.length===1?``:`s`}`);let t=e[e.length-1],n=e[e.length-2],r=e.slice(0,-2);if(!SE(t))throw yE(`dig`,e.length-1,`dict`,CE(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw yE(`dig`,e,`string`,CE(r[e]));return xE(t,n,r,e.length)}function xE(e,t,n,r){let i=n[0];if(!Object.hasOwn(e,i))return t;let a=e[i];if(n.length===1)return a;if(!SE(a))throw yE(`dig`,r-1,`dict at intermediate key`,CE(a));return xE(a,t,n.slice(1),r)}function SE(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function CE(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function wE(e){return e[0]}function TE(e,t){return t.some(t=>cC(t,e))}function EE(e){return e.slice(0,-1)}function DE(e){return e[e.length-1]}function OE(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function kE(...e){return e}function AE(e,t){return[t,...e]}function jE(e){return e.slice(1)}function ME(e){return[...e].reverse()}function NE(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function PE(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function FE(e){let t=[];for(let n of e)t.some(e=>cC(e,n))||t.push(n);return t}function IE(e,...t){return e.filter(e=>!t.some(t=>cC(t,e)))}function LE(){return{list:{fn:(...e)=>kE(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>wE(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>DE(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>jE(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>EE(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>OE(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>ME(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>FE(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>IE(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>TE(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>gE(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>NE(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>_E(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>hE(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>AE(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>mE(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>PE(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>mE(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>kE(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>bE(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>fE(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>pE(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function RE(...e){return e.reduce((e,t)=>e+t,0)}function zE(e){return e+1}function BE(e){return e+1}function VE(...e){return e.reduce((e,t)=>e+t,0)}function HE(e){return Math.ceil(e)}function UE(e,t){return Math.trunc(e/t)}function WE(e,...t){return t.reduce((e,t)=>e/t,e)}function GE(e){return Math.floor(e)}function KE(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function qE(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function JE(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function YE(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function XE(e,t){return e%t}function ZE(...e){return e.reduce((e,t)=>e*t,1)}function QE(...e){return e.reduce((e,t)=>e*t,1)}function $E(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function eD(e,t,n){let r=[];if(t<e){if(n>=0)return r;for(let i=e;i>t;i+=n)r.push(i);return r}if(n<=0)return r;for(let i=e;i<t;i+=n)r.push(i);return r}function tD(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),eD(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return eD(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:eD(n,i+t,r).join(` `)}default:return``}}function nD(e,t){return e-t}function rD(e,...t){return t.reduce((e,t)=>e-t,e)}function iD(e){return eD(0,e,e<0?-1:1)}function aD(){return{add:{fn:(...e)=>RE(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>nD(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>ZE(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>UE(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>XE(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>JE(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>KE(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>GE(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>HE(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>$E(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>VE(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>rD(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>QE(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>WE(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>zE(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>BE(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>qE(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>YE(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>KE(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>tD(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>iD(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>eD(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function oD(e){return Array.from(e)}function sD(e,t){return e===``?oD(t):t.split(e)}function cD(e,t){let n=oD(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function lD(e,t,n){let r=oD(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const Y={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},uD=/^[-_\s]$/,dD=/^\p{P}$/u,fD=/^\p{L}$/u,pD=/^\p{Lu}$/u,mD=/^\p{N}$/u;function hD(e){return e!==void 0&&uD.test(e)}function gD(e){return e!==void 0&&fD.test(e)}function _D(e){return e!==void 0&&pD.test(e)}function vD(e){return e!==void 0&&mD.test(e)}function yD(e){return e!==void 0&&dD.test(e)}function bD(e,t){if(t>=e.length)return{word:{wt:Y.Invalid,text:``},next:t};let n=e[t],r=t+1;if(hD(n)){for(;r<e.length&&hD(e[r]);)r++;return{word:{wt:Y.Connector,text:e.slice(t,r).join(``)},next:r}}if(yD(n)){for(;r<e.length&&yD(e[r]);)r++;return{word:{wt:Y.Punct,text:e.slice(t,r).join(``)},next:r}}if(_D(n)){if(r>=e.length)return{word:{wt:Y.UpperCase,text:n},next:r};if(_D(e[r])){let n=r;for(;n<e.length&&_D(e[n]);)n++;return n<e.length&&gD(e[n])?{word:{wt:Y.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:Y.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(gD(e[r])){let n=r+1;for(;n<e.length&&gD(e[n])&&!_D(e[n]);)n++;return{word:{wt:Y.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:Y.UpperCase,text:n},next:r}}if(gD(n)){for(;r<e.length&&gD(e[r])&&!_D(e[r]);)r++;return{word:{wt:Y.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(vD(n)){for(;r<e.length&&vD(e[r]);)r++;return{word:{wt:Y.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!hD(e[r])&&!gD(e[r])&&!vD(e[r])&&!yD(e[r]);)r++;return{word:{wt:Y.Other,text:e.slice(t,r).join(``)},next:r}}function xD(e,t,n){if(t.wt!==Y.UpperCase&&t.wt!==Y.Connector){e.push(t.text);return}for(let r of t.text)hD(r)?e.push(n):_D(r)?e.push(r.toLowerCase()):e.push(r)}function SD(e,t){if(e.length===0)return``;let n=oD(e),r=[],{word:i,next:a}=bD(n,0);for(;a<n.length;){i.wt!==Y.Connector&&xD(r,i,t);let e=i,o=i;if({word:i,next:a}=bD(n,a),e.wt===Y.Number){for(;i.wt===Y.Alphabet||i.wt===Y.Number;)xD(r,i,t),{word:i,next:a}=bD(n,a);i.wt!==Y.Invalid&&i.wt!==Y.Punct&&i.wt!==Y.Connector&&r.push(t);continue}if(e.wt===Y.Connector){xD(r,o,t);continue}if(e.wt===Y.Punct)continue;if(i.wt!==Y.Number){i.wt!==Y.Connector&&i.wt!==Y.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=bD(n,a),i.wt!==Y.Alphabet){xD(r,s,t),i.wt!==Y.Connector&&i.wt!==Y.Punct&&r.push(t);continue}for(r.push(t),xD(r,s,t);i.wt===Y.Alphabet||i.wt===Y.Number;)xD(r,i,t),{word:i,next:a}=bD(n,a);i.wt!==Y.Invalid&&i.wt!==Y.Connector&&i.wt!==Y.Punct&&r.push(t)}return xD(r,i,t),r.join(``).toLowerCase()}function CD(e){if(e.length===0)return``;let t=oD(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!hD(i)){i=i.toUpperCase();break}n.push(i)}if(r>=t.length)return t.length>0&&n.push(i),n.join(``);for(;r<t.length;){let e=i;if(i=t[r],r++,hD(i)&&hD(e)){n.push(e);continue}hD(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function wD(e){return CD(e)}function TD(...e){return e.join(` `)}function ED(e,t){return t.includes(e)}function DD(e,t){return t.startsWith(e)}function OD(e,t){return t.endsWith(e)}function kD(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
66
+ `?(this.line+=1,this.column=1):this.column+=1}}advanceTo(e){for(;this.offset<e;)this.advanceBy(1)}makeToken(e,t,n,r={}){return Object.freeze({type:e,value:t,pos:n,...r.trimLeft===void 0?{}:{trimLeft:r.trimLeft},...r.trimRight===void 0?{}:{trimRight:r.trimRight}})}};function jS(e){return e===` `||e===` `||e===`\r`||e===`
67
+ `}function MS(e){return e===`+`||e===`-`}function NS(e){return e>=`0`&&e<=`9`}function PS(e){return NS(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function FS(e){return e>=`0`&&e<=`7`}function IS(e){return e===`0`||e===`1`}function LS(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function RS(e){return LS(e)||e===`_`}function zS(e){return RS(e)||NS(e)}let BS,VS;function HS(e,t){return VS(e,t)}var US=class e{static EMPTY=new e(new Map,void 0);#e;#t;constructor(e,t){this.#e=e,this.#t=t}static{BS=(t,n)=>new e(t,n),VS=(e,t)=>e.#e.get(t)??(e.#t&&VS(e.#t,t))}has(e){return VS(this,e)!==void 0}};function WS(e,t,n=US.EMPTY){return new GS(e,t,n).parseTemplate()}var GS=class{lex;buf=[];defines=new Map;inherit;source;rangeDepth=0;constructor(e,t,n){this.source=e,this.inherit=n,this.lex=t?new AS(e,t):new AS(e)}peek(e=0){for(;this.buf.length<=e;)this.buf.push(this.lex.next());return this.buf[e]}next(){return this.buf.length>0?this.buf.shift():this.lex.next()}expect(e,t){let n=this.next();if(n.type!==e)throw this.errAt(n,`expected ${t}`,{expected:t,found:JS(n)});return n}errAt(e,t,n={}){return new gS(t,e.pos,{...n,source:this.source})}parseTemplate(){let e=this.parseList();if(this.peek().type!==`EOF`){let e=this.peek(),t=this.peek(1);if(e.type===`LeftDelim`&&(t.type===`Else`||t.type===`End`)){let n=t.type===`Else`?`else`:`end`;throw this.errAt(e,`unexpected \`{{${n}}}\` outside of \`if\`, \`range\`, \`with\`, or \`block\``,{found:`{{${n}}}`})}throw this.errAt(e,`unexpected ${JS(e)}`,{found:JS(e)})}return{root:e,defines:BS(this.defines,this.inherit),ownDefines:this.defines,source:this.source}}parseList(){let e=this.peek().pos,t=[];for(;;){let n=this.peek();if(n.type===`EOF`)break;if(n.type===`Text`){this.next(),t.push({type:`Text`,pos:n.pos,text:n.value});continue}if(n.type===`Comment`){this.next();let e=qS(n);t.push({type:`Comment`,pos:n.pos,text:n.value,trim:e});continue}if(n.type===`LeftDelim`){let n=this.peek(1).type;if(n===`Else`||n===`End`)return KS(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${JS(n)} at top level`,{found:JS(n)})}return KS(e,t)}parseAction(){let e=this.expect(`LeftDelim`,"`{{`"),t=e.trimLeft===!0,n=this.peek();switch(n.type){case`If`:return this.next(),this.parseBranch(`If`,e.pos,t);case`Range`:return this.next(),this.parseBranch(`Range`,e.pos,t);case`With`:return this.next(),this.parseBranch(`With`,e.pos,t);case`Break`:return this.next(),this.parseBreakOrContinue(`Break`,e.pos,t);case`Continue`:return this.next(),this.parseBreakOrContinue(`Continue`,e.pos,t);case`Template`:return this.next(),this.parseTemplateInvocation(e.pos,t);case`Block`:return this.next(),this.parseBlock(e.pos,t);case`Define`:return this.next(),this.parseDefine(e.pos,t),null;case`RightDelim`:throw this.errAt(n,`empty action`,{expected:`pipeline`});default:{let n=this.parsePipeline(),r=this.expect(`RightDelim`,"`}}`");return{type:`Action`,pos:e.pos,pipe:n,trim:{trimLeft:t,trimRight:r.trimRight===!0}}}}}parseBranch(e,t,n){let r=this.parsePipeline();this.expect(`RightDelim`,"`}}`"),e===`Range`&&(this.rangeDepth+=1);let i=this.parseList();e===`Range`&&--this.rangeDepth;let a=this.parseElsePart(),o={trimLeft:n,trimRight:a.endConsumed?a.endRight:this.consumeEnd()},s=a.list?{pipe:r,list:i,elseList:a.list,trim:o}:{pipe:r,list:i,trim:o};switch(e){case`If`:return{type:`If`,pos:t,...s};case`Range`:return{type:`Range`,pos:t,...s};case`With`:return{type:`With`,pos:t,...s}}}parseBreakOrContinue(e,t,n){if(this.rangeDepth===0)throw new gS(`{{${e===`Break`?`break`:`continue`}}} outside of {{range}}`,t,{source:this.source});let r={trimLeft:n,trimRight:this.expect(`RightDelim`,"`}}`").trimRight===!0};return e===`Break`?{type:`Break`,pos:t,trim:r}:{type:`Continue`,pos:t,trim:r}}parseElsePart(){if(this.peek().type!==`LeftDelim`||this.peek(1).type!==`Else`)return{list:void 0,endRight:!1,endConsumed:!1};let e=this.next();if(this.next(),this.peek().type===`If`){this.next();let t=this.parseBranch(`If`,e.pos,e.trimLeft===!0);return{list:{type:`List`,pos:e.pos,nodes:[t]},endRight:t.trim.trimRight,endConsumed:!0}}return this.expect(`RightDelim`,"`}}`"),{list:this.parseList(),endRight:!1,endConsumed:!1}}consumeEnd(){return this.expect(`LeftDelim`,"`{{end}}`"),this.expect(`End`,"`end`"),this.expect(`RightDelim`,"`}}`").trimRight===!0}parseTemplateInvocation(e,t){let n=this.parseQuotedName(),r=this.peek().type===`RightDelim`?void 0:this.parsePipeline(),i={trimLeft:t,trimRight:this.expect(`RightDelim`,"`}}`").trimRight===!0};return r?{type:`Template`,pos:e,name:n,pipe:r,trim:i}:{type:`Template`,pos:e,name:n,trim:i}}parseBlock(e,t){let n=this.parseQuotedName(),r=this.peek().type===`RightDelim`?void 0:this.parsePipeline();this.expect(`RightDelim`,"`}}`");let i=this.rangeDepth;this.rangeDepth=0;let a=this.parseList();this.rangeDepth=i;let o={trimLeft:t,trimRight:this.consumeEnd()};return!this.defines.has(n)&&!this.inherit.has(n)&&this.defines.set(n,{list:a,source:this.source}),r?{type:`Block`,pos:e,name:n,pipe:r,list:a,trim:o}:{type:`Block`,pos:e,name:n,list:a,trim:o}}parseDefine(e,t){let n=this.parseQuotedName();this.expect(`RightDelim`,"`}}`");let r=this.rangeDepth;this.rangeDepth=0;let i=this.parseList();if(this.rangeDepth=r,this.consumeEnd(),this.defines.has(n)||this.inherit.has(n))throw new gS(`redefinition of template ${JSON.stringify(n)}`,i.pos,{source:this.source});this.defines.set(n,{list:i,source:this.source})}parseQuotedName(){let e=this.next();if(e.type!==`String`)throw this.errAt(e,`expected template name (quoted string)`,{expected:`string`,found:JS(e)});return nC(e.value,e.pos,this.source)}parsePipeline(){let e=this.peek().pos,t=this.tryParseDecls(),n=[this.parseCommand()];for(;this.peek().type===`Pipe`;){this.next();let e=this.peek();if(!YS(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:JS(e)});n.push(this.parseCommand())}return{type:`Pipe`,pos:e,decls:t?.vars??[],isAssign:t?.isAssign??!1,cmds:n}}tryParseDecls(){if(this.peek().type!==`Variable`)return;let e=1;for(;this.peek(e).type===`Comma`;){if(this.peek(e+1).type!==`Variable`)return;e+=2}let t=this.peek(e).type;if(t!==`Declare`&&t!==`Assign`)return;let n=[XS(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(XS(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;YS(this.peek().type);)t.push(this.parsePrimary());return{type:`Command`,pos:e,args:t}}parsePrimary(){let e=this.next();switch(e.type){case`Dot`:return{type:`Dot`,pos:e.pos};case`Field`:return{type:`Field`,pos:e.pos,idents:e.value.slice(1).split(`.`)};case`Variable`:return XS(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:nC(e.value,e.pos,this.source)};case`Number`:return QS(e);case`Char`:return $S(e,this.source);case`Bool`:return{type:`Bool`,pos:e.pos,value:e.value===`true`};case`Nil`:return{type:`Nil`,pos:e.pos};case`LeftParen`:return this.parseChainOrPipe(e.pos);default:throw this.errAt(e,`expected command argument, found ${JS(e)}`,{expected:`command argument`,found:JS(e)})}}parseChainOrPipe(e){let t=this.parsePipeline(),n=this.expect(`RightParen`,"`)`"),r=[],i=n.pos.offset+1,a=this.peek();return a.type===`Field`&&a.pos.offset===i&&(this.next(),r.push(...a.value.slice(1).split(`.`))),r.length===0?t:{type:`Chain`,pos:e,node:t,fields:r}}};function KS(e,t){return{type:`List`,pos:e,nodes:t}}function qS(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function JS(e){return e.type===`EOF`?`end of input`:e.value||e.type}function YS(e){switch(e){case`Dot`:case`Field`:case`Variable`:case`Identifier`:case`String`:case`Number`:case`Char`:case`Bool`:case`Nil`:case`LeftParen`:return!0;default:return!1}}function XS(e){return{type:`Variable`,pos:e.pos,idents:ZS(e.value)}}function ZS(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function QS(e){let t=e.value,n=t.replace(/_/g,``),r=n.toLowerCase().endsWith(`i`),i=r?n.slice(0,-1):n,a=!r&&(i.includes(`.`)||!i.startsWith(`0x`)&&!i.startsWith(`0X`)&&/[eE]/.test(i)||(i.startsWith(`0x`)||i.startsWith(`0X`))&&/[pP]/.test(i)),o=!r&&!a,s={type:`Number`,pos:e.pos,text:t,isInt:o,isUint:!1,isFloat:a,isComplex:r};if(o){let e=eC(i);return{...s,intValue:e}}if(a){let e=tC(i);return{...s,floatValue:e}}let c=tC(i);return{...s,complexValue:[0,c]}}function $S(e,t){let n=rC(e.value,e.pos,t);return{type:`Number`,pos:e.pos,text:e.value,isInt:!0,isUint:!1,isFloat:!1,isComplex:!1,intValue:BigInt(n)}}function eC(e){let t=1n,n=e;return n.startsWith(`+`)?n=n.slice(1):n.startsWith(`-`)&&(t=-1n,n=n.slice(1)),t*BigInt(n)}function tC(e){return Number(e)}function nC(e,t,n){if(e.startsWith("`"))return e.slice(1,-1);let r=``;for(let i=1;i<e.length-1;i++){let a=e[i];if(a!==`\\`){r+=a;continue}let o=e[++i];switch(o){case`n`:r+=`
68
+ `;break;case`t`:r+=` `;break;case`r`:r+=`\r`;break;case`\\`:r+=`\\`;break;case`"`:r+=`"`;break;case`'`:r+=`'`;break;case`a`:r+=`\x07`;break;case`b`:r+=`\b`;break;case`f`:r+=`\f`;break;case`v`:r+=`\v`;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:{let t=o+(e[i+1]??``)+(e[i+2]??``);i+=2,r+=String.fromCodePoint(Number.parseInt(t,8));break}case`x`:{let t=(e[i+1]??``)+(e[i+2]??``);i+=2,r+=String.fromCodePoint(Number.parseInt(t,16));break}case`u`:{let t=e.slice(i+1,i+5);i+=4,r+=String.fromCodePoint(Number.parseInt(t,16));break}case`U`:{let t=e.slice(i+1,i+9);i+=8,r+=String.fromCodePoint(Number.parseInt(t,16));break}default:throw new gS(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function rC(e,t,n){let r=nC(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new gS(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function iC(e,t){if(t(e)!==!1)for(let n of aC(e))iC(n,t)}function aC(e){switch(e.type){case`Text`:case`Comment`:case`Dot`:case`Nil`:case`Bool`:case`Number`:case`String`:case`Identifier`:case`Field`:case`Variable`:case`Break`:case`Continue`:return[];case`List`:return e.nodes;case`Chain`:return[e.node];case`Command`:return e.args;case`Pipe`:return[...e.decls,...e.cmds];case`Action`:return[e.pipe];case`If`:case`Range`:case`With`:return e.elseList?[e.pipe,e.list,e.elseList]:[e.pipe,e.list];case`Template`:return e.pipe?[e.pipe]:[];case`Block`:return e.pipe?[e.pipe,e.list]:[e.list];default:return DS(e)}}const oC=Symbol(`go-template-js.MISSING`);function sC(e,t){if(e==null)return oC;if(e instanceof Map)return e.has(t)?e.get(t):oC;if(Array.isArray(e))return oC;if(typeof e==`object`){let n=e;return t in n?n[t]:oC}return oC}function cC(e,t){let n=e;for(let e of t){if(n===oC)return oC;n=sC(n,e)}return n}function lC(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||e===void 0||t===void 0||typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length?e.every((e,n)=>lC(e,t[n])):!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!lC(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}if(typeof e==`object`&&typeof t==`object`){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length?n.every(n=>lC(e[n],t[n])):!1}return!1}const uC=new WeakSet;function dC(e){return uC.add(e),e}function fC(e){return uC.has(e)}function pC(e){return e==null||e===!1?!1:typeof e==`number`?e!==0&&!Number.isNaN(e):typeof e==`bigint`?e!==0n:typeof e==`string`||Array.isArray(e)?e.length>0:e instanceof Map||e instanceof Set?e.size>0:typeof e==`object`?Object.keys(e).length>0:!!e}function mC(e,t){return{eq:{fn:(e,...t)=>t.some(t=>_C(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!_C(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>vC(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>vC(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>vC(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>vC(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>yC(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=bC(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>SC(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>TC(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${TC(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>PC(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>LC(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>LC(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>OC(TC(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>jC(TC(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>NC(TC(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!pC(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function hC(){return{and:dC({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!pC(t))return t;return t}}),or:dC({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),pC(t))return t;return t}})}}function gC(e,t){return{...mC(e,t),...hC()}}function _C(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):lC(e,t)}function vC(e,t){if(typeof e==`bigint`&&typeof t==`bigint`)return e===t?0:e<t?-1:1;if(typeof e==`bigint`||typeof t==`bigint`){let n=typeof e==`bigint`?e:BigInt(Math.trunc(Number(e))),r=typeof t==`bigint`?t:BigInt(Math.trunc(Number(t)));return n===r?0:n<r?-1:1}let n=e,r=t;return n===r?0:n<r?-1:1}function yC(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function bC(e,t){if(Array.isArray(e)||typeof e==`string`){let n=xC(t,e.length);if(n===e.length)throw Error(`index out of range: ${n}`);return e[n]}if(e instanceof Map)return e.get(t);if(typeof e==`object`&&e){if(typeof t!=`string`)throw Error(`index: object index must be string, got ${CC(t)}`);return e[t]}throw Error(`index: cannot index ${CC(e)}`)}function xC(e,t){let n=typeof e==`bigint`?Number(e):e;if(typeof n!=`number`||!Number.isInteger(n))throw Error(`cannot index slice/array with type ${wC(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function SC(e,t){if(t.length>3)throw Error(`too many slice indexes: ${t.length}`);if(typeof e==`string`&&t.length>2)throw Error(`cannot 3-index slice a string`);let n=e.length,r=[0,n,n];t.forEach((e,t)=>{r[t]=xC(e,n)});let[i,a,o]=r;if(i>a)throw Error(`invalid slice index: ${i} > ${a}`);if(a>o)throw Error(`invalid slice index: ${a} > ${o}`);return e.slice(i,a)}function CC(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function wC(e){return e==null?`<nil>`:typeof e==`string`?`string`:typeof e==`boolean`?`bool`:typeof e==`bigint`?`int64`:typeof e==`number`?Number.isInteger(e)?`int`:`float64`:Array.isArray(e)?`[]interface {}`:e instanceof Map||typeof e==`object`?`map[string]interface {}`:typeof e}function TC(e,t){let n=``,r=!1;for(let i=0;i<e.length;i++){let a=e[i],o=typeof a==`string`;i>0&&!r&&!o&&(n+=` `),n+=EC(a,t),r=o}return n}function EC(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const DC={"\0":`�`,'"':`&#34;`,"'":`&#39;`,"&":`&amp;`,"<":`&lt;`,">":`&gt;`};function OC(e){return e.replace(/[\0"'&<>]/g,e=>DC[e]??e)}const kC={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},AC=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function jC(e){let t=``;for(let n of e){let e=kC[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!AC.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const MC=new TextEncoder;function NC(e){let t=``,n=MC.encode(e);for(let e of n)e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===45||e===46||e===95||e===126?t+=String.fromCharCode(e):e===32?t+=`+`:t+=`%${e.toString(16).toUpperCase().padStart(2,`0`)}`;return t}function PC(e,t,n,r){let i=``,a=0,o=0;for(;o<e.length;){let s=e[o];if(s!==`%`){i+=s,o+=1;continue}if(e[o+1]===`%`){i+=`%`,o+=2;continue}let c=o+1;for(;c<e.length&&`+-# 0`.includes(e[c]??``);)c+=1;for(;c<e.length&&e[c]!==void 0&&/[0-9]/.test(e[c]);)c+=1;if(e[c]===`.`)for(c+=1;c<e.length&&e[c]!==void 0&&/[0-9]/.test(e[c]);)c+=1;let l=e[c],u=e.slice(o+1,c),d=t[a++];i+=FC(l??``,u,d,n,r),o=c+1}return i}function FC(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?IC(t,n):IC(t,EC(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${wC(n)}=${EC(n,r)})`:IC(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return IC(t,LC(n,r,i));case`q`:return IC(t,JSON.stringify(EC(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${wC(n)}=${EC(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return IC(t,Number(n).toFixed(i))}case`t`:return IC(t,pC(n)?`true`:`false`);case`x`:if(typeof n==`string`){let e=new TextEncoder().encode(n),r=``;for(let t of e)r+=t.toString(16).padStart(2,`0`);return IC(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${wC(n)}=${EC(n,r)})`:typeof n==`bigint`?IC(t,n.toString(16)):IC(t,Math.trunc(n).toString(16));default:return`%!${e}(${wC(n)}=${EC(n,r)})`}}function IC(e,t){let n=e.match(/^([+\-# 0]*)/)?.[1]??``,r=e.slice(n.length).match(/^(\d+)/);if(!r)return t;let i=Number(r[1]);if(t.length>=i)return t;let a=` `.repeat(i-t.length);return n.includes(`-`)?t+a:a+t}function LC(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>LC(e,t,n)).join(` `)}]`:e instanceof Map?RC([...e.entries()],t,n):zC(e)?RC(Object.entries(e),t,n):String(e)}function RC(e,t,n){let r=e=>LC(e,t,n),i=e=>typeof e==`number`||typeof e==`bigint`,a=([e],[t])=>{if(i(e)&&i(t))return e<t?-1:+(e>t);if(i(e)!==i(t))return i(e)?-1:1;let[n,a]=[r(e),r(t)];return n<a?-1:+(n>a)};return`map[${[...e].sort(a).map(([e,t])=>`${r(e)}:${r(t)}`).join(` `)}]`}function zC(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof Map||e instanceof Set)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function BC(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function VC(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function HC(e,t){let n=e;for(;n!==void 0;){if(n.vars.has(t))return{found:!0,value:n.vars.get(t)};n=n.parent}return{found:!1}}function UC(e,t,n){e.vars.set(t,n)}const WC=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],GC=new Set([`default`,`zero`,`error`]);function KC(e){if(e===void 0)return`default`;if(GC.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${qC(e)}`)}function qC(e){return typeof e==`string`?JSON.stringify(e):e===null?`null`:e===void 0?`undefined`:typeof e==`bigint`?`${e}n`:typeof e==`number`||typeof e==`boolean`?String(e):typeof e==`symbol`?e.toString():typeof e==`function`?`[Function]`:`[${typeof e}]`}function JC(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${qC(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${qC(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${qC(e.right)}`);return{left:e.left,right:e.right}}}function YC(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function XC(e){let t=new Set(WC);for(let[n,r]of Object.entries(e)){if(r.argTypes.forEach((e,r)=>{if(!t.has(e))throw Error(`EngineConfig.funcs.${n}: argTypes[${r}] is ${JSON.stringify(e)}, which is not an ArgType; declare one of ${WC.join(`, `)}`)}),YC(r.arity)&&r.argTypes.length===0)throw Error(`EngineConfig.funcs.${n}: arity ${JSON.stringify(r.arity.kind)} needs at least one declared argType (it reads its repeating slot from the end of argTypes); declare the slots the Go signature has, or use { kind: "exact" }`);if(r.arity.kind===`alternating`&&(!Number.isSafeInteger(r.arity.minimum)||r.arity.minimum<0))throw Error(`EngineConfig.funcs.${n}: arity "alternating" needs a non-negative integer minimum, got ${String(r.arity.minimum)}; the gate rejects every count below it, so a negative or non-finite minimum would disable the lower bound`)}return e}const ZC=Object.freeze({kind:`break`}),QC=Object.freeze({kind:`continue`}),$C={kind:`none`};let ew;(class e{source;_evaluate;_defines;_referencedFunctions;_referencedCalls;constructor(e,t,n,r,i){this.source=e,this._evaluate=t,this._defines=n,this._referencedFunctions=r,this._referencedCalls=i}static{ew=(t,n,r,i,a)=>new e(t,n,r,i,a)}defines(){return this._defines}evaluate(e){return this._evaluate(e)}referencedFunctions(){return this._referencedFunctions}referencedCalls(){return this._referencedCalls}});function tw(e){let t=new Set,n=e=>{iC(e,e=>{e.type===`Identifier`&&t.add(e.ident)})};n(e.root);for(let t of e.ownDefines.values())n(t.list);return t}const nw={kind:`dynamic`};function rw(e){switch(e.type){case`String`:return{kind:`literal`,value:e.value};case`Bool`:return{kind:`literal`,value:e.value};case`Nil`:return{kind:`literal`,value:null};case`Number`:{let t=ww(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:nw}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return nw;let t=e.cmds[0];if(t===void 0)return nw;let n=t.args[0];return n===void 0||n.type!==`Identifier`?nw:{kind:`call`,name:n.ident,args:t.args.slice(1).map(rw)}}default:return nw}}function iw(e){let t=[],n=e=>{iC(e,e=>{if(e.type!==`Command`)return;let n=e.args[0];if(n===void 0||n.type!==`Identifier`)return;let r=e.args.slice(1).map(rw);t.push({name:n.ident,args:r.map(e=>e.kind===`literal`&&typeof e.value==`string`?e.value:null),argExprs:r})})};n(e.root);for(let t of e.ownDefines.values())n(t.list);return t}var aw=class{fromString;toString;isT;funcs;missingKey;delims;constructor(e){this.fromString=e.fromString;let t=Object.hasOwn(e,`toString`)?e.toString:void 0;this.toString=t??pw,this.isT=e.isT??ow,this.missingKey=KC(e.missingKey),this.delims=JC(e.delims),this.funcs=XC({...gC(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=WS(e,this.delims,t);return ew(n.source,e=>this.evalParsed(n,e),n.defines,tw(n),iw(n))}compile(e){let t=this.parse(e);return e=>t.evaluate(e)}evaluate(e,t){return e.evaluate(t)}evalParsed(e,t){let n=[],r=BC(t),i={out:n,defines:e.defines,source:e.source};return this.evalList(e.root,r,i),n}evalList(e,t,n){for(let r of e.nodes)this.evalNode(r,t,n)}evalNode(e,t,n){switch(e.type){case`Text`:n.out.push(this.fromString(e.text));return;case`Comment`:return;case`Action`:{let r=this.evalAction(e,t,n);e.pipe.decls.length===0&&this.emitFromValue(r,n);return}case`List`:this.evalList(e,t,n);return;case`If`:this.evalIf(e,t,n);return;case`Range`:this.evalRange(e,t,n);return;case`With`:this.evalWith(e,t,n);return;case`Break`:throw ZC;case`Continue`:throw QC;case`Template`:this.evalTemplateInvoke(e,t,n);return;case`Block`:this.evalBlock(e,t,n);return;case`Pipe`:case`Command`:case`Identifier`:case`Field`:case`Variable`:case`Chain`:case`Dot`:case`Nil`:case`Bool`:case`Number`:case`String`:throw new _S(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:DS(e)}}evalIf(e,t,n){pC(this.evalPipe(e.pipe,t,n))?this.evalList(e.list,t,n):e.elseList&&this.evalList(e.elseList,t,n)}evalWith(e,t,n){let r=this.evalPipe(e.pipe,t,n);if(pC(r)){let i=VC(t,r);this.evalList(e.list,i,n)}else e.elseList&&this.evalList(e.elseList,t,n)}evalRange(e,t,n){let r=this.evalPipeWithoutDecls(e.pipe,t,n),i=e.pipe.decls,a=xw(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=VC(t,o);if(i.length===1)UC(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;UC(a,e,r),UC(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===QC)continue;throw e}}}catch(e){if(e===ZC)return;throw e}}evalTemplateInvoke(e,t,n){let r=HS(n.defines,e.name);if(!r)throw new _S(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=VC(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot);this.evalList(r.list,i,{out:n.out,defines:n.defines,source:r.source})}evalBlock(e,t,n){let r=VC(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=HS(n.defines,e.name)??{list:e.list,source:n.source};this.evalList(i.list,r,{out:n.out,defines:n.defines,source:i.source})}evalAction(e,t,n){return this.evalPipe(e.pipe,t,n)}evalPipe(e,t,n){if(e.cmds.length===0)throw new _S(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,$C);for(let i=1;i<e.cmds.length;i++){let a=e.cmds[i];r=this.evalCommand(a,t,n,{kind:`value`,value:r})}if(e.decls.length>0)for(let n of e.decls)UC(t,n.idents[0]??`$`,r);return r}evalPipeWithoutDecls(e,t,n){let r={type:`Pipe`,pos:e.pos,decls:[],isAssign:!1,cmds:e.cmds};return this.evalPipe(r,t,n)}evalCommand(e,t,n,r){if(e.args.length===0)throw new _S(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new _S(`cannot apply arguments to a ${i.type} primary; only functions take arguments`,e.pos,{source:n.source});return this.evalPrimary(i,t,n)}let a=this.funcs[i.ident];if(!a)throw new vS(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=fC(a),c=o.map(e=>s?()=>this.evalPrimary(e,t,n):this.evalPrimary(e,t,n));if(r.kind===`value`){let e=r.value;c.push(s?()=>e:e)}return this.invoke(i.ident,a,c,e.pos,n)}invoke(e,t,n,r,i){cw(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof bS?new bS(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof CS?new CS(t.message,r,{source:i.source}):t instanceof hS?t:new _S(`error calling ${e}: ${yw(t)}`,r,{source:i.source,cause:t})}}evalPrimary(e,t,n){switch(e.type){case`Dot`:return t.dot;case`Nil`:return null;case`Bool`:return e.value;case`Number`:return ww(e);case`String`:return e.value;case`Field`:return this.resolveFieldChain(t.dot,e.idents,e.pos,n);case`Variable`:return this.resolveVariable(e.idents,t,e.pos,n);case`Identifier`:{let t=this.funcs[e.ident];if(!t)throw new vS(e.ident,e.pos,{source:n.source,available:Object.keys(this.funcs)});return this.invoke(e.ident,t,[],e.pos,n)}case`Chain`:return this.resolveFieldChain(this.evalPrimary(e.node,t,n),e.fields,e.pos,n);case`Pipe`:return this.evalPipe(e,t,n);default:throw new _S(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=cC(e,t);if(i!==oC)return i;if(this.missingKey===`error`)throw new SS(t,n,{source:r.source})}resolveVariable(e,t,n,r){let i=e[0]??`$`;if(i===`$`){let i=e.slice(1);return i.length===0?t.root:this.resolveFieldChain(t.root,i,n,r)}let a=HC(t,i);if(!a.found)throw new _S(`undefined variable ${i}`,n,{source:r.source});let o=e.slice(1);return o.length===0?a.value:this.resolveFieldChain(a.value,o,n,r)}emitFromValue(e,t){if(e==null){t.out.push(this.fromString(`<no value>`));return}if(typeof e==`string`){t.out.push(this.fromString(e));return}if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`){t.out.push(this.fromString(String(e)));return}if(this.isT(e)){t.out.push(e);return}t.out.push(this.fromString(LC(e,this.toString,this.isT)))}};const ow=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function sw(e){return new aw(e)}function cw(e,t,n,r,i,a=pw,o=fw,s=ow){let{argTypes:c,arity:l}=t,u=lw(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new yS(e,u,n.length,r,{source:i});let d=uw(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!dw(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new xS(e,t+1,l,r,{source:i}):new bS(e,t+1,vw(c),bw(l),r,{source:i});if(c===`liftable`&&typeof l==`string`&&(n[t]=o(l)),c===`truncating-int`?n[t]=Math.trunc(Number(l)):(c===`int`||c===`float`)&&(n[t]=Number(l)),c===`ordered`){if(f===-1)f=t;else if(!hw(n[f],l))throw new bS(e,t+1,`${vw(`ordered`)} of the same kind as ${bw(n[f])}`,bw(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!gw(n[p],l))throw new bS(e,t+1,`${vw(`comparable`)} of the same kind as ${bw(n[p])}`,bw(l),r,{source:i})}}}function lw(e,t){switch(t.kind){case`exact`:return{minimum:e.length,maximum:e.length};case`variadic`:return{minimum:e.length-1,maximum:1/0};case`alternating`:return{minimum:t.minimum,maximum:1/0}}}function uw(e,t){let n=e.length;switch(t.kind){case`exact`:return t=>e[t];case`variadic`:return t=>e[Math.min(t,n-1)];case`alternating`:return t=>e[t%n]}}function dw(e,t,n,r){switch(e){case`truthy`:case`reflective`:case`value`:return!0;case`string`:return typeof t==`string`;case`int`:return typeof t==`number`&&Number.isSafeInteger(t)||typeof t==`bigint`&&Number.isSafeInteger(Number(t));case`truncating-int`:return typeof t==`number`&&Number.isFinite(t)||typeof t==`bigint`&&Number.isSafeInteger(Number(t));case`float`:return typeof t==`number`||typeof t==`bigint`&&Number.isFinite(Number(t));case`bool`:return typeof t==`boolean`;case`ordered`:return typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`;case`T`:return r(t);case`list`:return Array.isArray(t);case`dict`:return zC(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||zC(t);case`comparable`:return t==null||typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`||Array.isArray(t)||t instanceof Map||t instanceof Set||zC(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||zC(t);case`index-key`:return typeof t==`string`||typeof t==`number`||typeof t==`bigint`;case`sliceable`:return typeof t==`string`||Array.isArray(t);case`stringifiable`:if(typeof t==`string`)return!0;try{return n(t),!0}catch{return!1}case`liftable`:return typeof t==`string`||r(t);case`serializable`:return mw(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function fw(e){return e}function pw(e){if(typeof e==`string`)return e;if(e==null)return`<nil>`;if(typeof e==`number`||typeof e==`bigint`||typeof e==`boolean`)return String(e);throw new bS(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,bw(e),{line:0,column:0,offset:0})}function mw(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function hw(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function gw(e,t){let n=_w(e),r=_w(t);return n===`nil`||r===`nil`?!0:n===r}function _w(e){return e==null?`nil`:typeof e==`string`?`string`:typeof e==`number`||typeof e==`bigint`?`number`:typeof e==`boolean`?`boolean`:Array.isArray(e)?`array`:e instanceof Map?`map`:e instanceof Set?`set`:`object`}function vw(e){switch(e){case`int`:return`integer (safe-integer number or bigint)`;case`truncating-int`:return`integer (finite number, truncated toward zero, or safe-integer bigint)`;case`float`:return`float (number, including NaN/Infinity, or finite-convertible bigint)`;case`T`:return`T (consumer-defined fragment)`;case`ordered`:return`orderable primitive`;case`list`:return`list`;case`dict`:return`dict (plain object)`;case`sized`:return`sized value (string, list, map, set, or dict)`;case`comparable`:return`comparable value (orderable primitive, nil, list, dict, Map, or Set)`;case`stringifiable`:return`stringifiable value (string or convertible via the engine's toString)`;case`liftable`:return`liftable value (T or string, the latter lifted via the engine's fromString)`;case`callable`:return`callable (function value)`;case`collection`:return`collection (string, array, Map, or dict)`;case`index-key`:return`index key (number, bigint, or string)`;case`sliceable`:return`sliceable value (string or array)`;case`serializable`:return`JSON-serializable value`;case`truthy`:case`reflective`:case`value`:case`string`:case`bool`:return e;default:throw Error(`invalid ArgType: ${String(e)}`)}}function yw(e){return e instanceof Error?e.message:String(e)}function bw(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function xw(e){return e==null?[]:Array.isArray(e)?e.map((e,t)=>[t,e]):typeof e==`string`?[...e].map((e,t)=>[t,e]):e instanceof Map?Sw([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?Sw(Object.entries(e)):[]}function Sw(e){return[...e].sort((e,t)=>Cw(e[0],t[0]))}function Cw(e,t){if((typeof e==`number`||typeof e==`bigint`)&&(typeof t==`number`||typeof t==`bigint`)){let n=typeof e==`bigint`?Number(e):e,r=typeof t==`bigint`?Number(t):t;return n===r?0:n<r?-1:1}let n=String(e),r=String(t);return n===r?0:n<r?-1:1}function ww(e){if(e.intValue!==void 0){let t=e.intValue;return t>=BigInt(-(2**53-1))&&t<=BigInt(2**53-1)?Number(t):t}if(e.floatValue!==void 0)return e.floatValue;if(e.complexValue!==void 0)return e.complexValue;throw Error(`internal: NumberNode has none of intValue/floatValue/complexValue — parser invariant violated`)}function Tw(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function Ew(e){if(typeof e==`number`)return e;if(typeof e==`bigint`)return Number(e);if(typeof e==`string`){let t=Number.parseFloat(e);return Number.isNaN(t)?0:t}return typeof e==`boolean`?+!!e:0}function Dw(e){if(e===``)return null;let t=1,n=e;return n[0]===`+`?n=n.slice(1):n[0]===`-`&&(t=-1,n=n.slice(1)),n===``?null:/^0x[0-9a-fA-F]+$/i.test(n)?{sign:t,digits:n.slice(2),base:16}:/^0b[01]+$/i.test(n)?{sign:t,digits:n.slice(2),base:2}:/^0o[0-7]+$/i.test(n)?{sign:t,digits:n.slice(2),base:8}:n===`0`?{sign:t,digits:`0`,base:10}:n[0]===`0`?/^0[0-7]+$/.test(n)?{sign:t,digits:n.slice(1),base:8}:null:/^[0-9]+$/.test(n)?{sign:t,digits:n,base:10}:null}function Ow(e){if(typeof e==`number`){let t=Math.trunc(e);return Number.isSafeInteger(t)?t:0}if(typeof e==`bigint`){let t=Number(e);return Number.isSafeInteger(t)?t:0}if(typeof e==`string`){let t=Dw(e);if(t===null)return 0;let n=t.sign*Number.parseInt(t.digits,t.base);return Number.isSafeInteger(n)?n:0}return typeof e==`boolean`?+!!e:0}function kw(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=Dw(e);if(t===null)return 0n;let n=t.base===16?`0x`:t.base===2?`0b`:t.base===8?`0o`:``,r=BigInt(n+t.digits);return t.sign===-1?-r:r}return typeof e==`boolean`&&e?1n:0n}function Aw(e){if(!/^[+-]?[0-7]+$/.test(e))return 0;let t=e[0]===`-`?-1:1,n=e[0]===`+`||e[0]===`-`?e.slice(1):e,r=t*Number.parseInt(n,8);return Number.isSafeInteger(r)?r:0}function jw(e){return JSON.stringify(e)??`null`}function Mw(){return{atoi:{fn:e=>Tw(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>Ow(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>kw(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>Ew(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>Aw(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>jw(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const Nw={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function Pw(e){if(e===`0`)return 0;let t=!1,n=e;if(n.startsWith(`-`)?(t=!0,n=n.slice(1)):n.startsWith(`+`)&&(n=n.slice(1)),!n)return NaN;let r=0,i=/^(\d+(?:\.\d+)?)(ns|µs|us|ms|[smh])/;for(;n.length>0;){let e=i.exec(n);if(!e)return NaN;let t=parseFloat(e[1]??`0`),a=e[2];r+=t*Nw[a],n=n.slice(e[0].length)}return t?-r:r}function Fw(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<Nw.us?`${Math.floor(n)}ns`:n<Nw.ms?Iw(n,Nw.us,3,`µs`):n<Nw.s?Iw(n,Nw.ms,6,`ms`):Lw(n),t?`-${r}`:r}function Iw(e,t,n,r){let i=Math.floor(e/t),a=Math.round(e%t);return a===0?`${i}${r}`:`${i}.${String(a).padStart(n,`0`).replace(/0+$/,``)}${r}`}function Lw(e){let t=Math.floor(e/Nw.h);e-=t*Nw.h;let n=Math.floor(e/Nw.m);e-=n*Nw.m;let r=Math.floor(e/Nw.s),i=e-r*Nw.s,a=i===0?`${r}s`:`${r}.${String(Math.round(i)).padStart(9,`0`).replace(/0+$/,``)}s`;return t>0?`${t}h${n}m${a}`:n>0?`${n}m${a}`:a}function Rw(e){return e*Nw.s}function zw(e){if(e instanceof Date)return e;if(typeof e==`bigint`)return new Date(Number(e)*1e3);if(typeof e==`number`)return new Date(e*1e3);if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t;throw Error(`sprig: cannot parse date value ${JSON.stringify(e)}`)}throw Error(`sprig: unsupported date type: ${typeof e}`)}function Bw(e,t){let n=t().getTime()-zw(e).getTime();return Fw(Math.round(n/1e3)*1e9)}const Vw=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Hw=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Uw=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],Ww=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function Gw(e){return e<10?`0${e}`:String(e)}function Kw(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function qw(e){return e<10?` ${e}`:String(e)}function Jw(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${Gw(Math.floor(n/60))}${Gw(n%60)}`}function Yw(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${Gw(Math.floor(n/60))}:${Gw(n%60)}`}function Xw(e){return`${e>=0?`+`:`-`}${Gw(Math.floor(Math.abs(e)/60))}`}function Zw(e){return e===0?`Z`:Jw(e)}function Qw(e){return e===0?`Z`:Yw(e)}function $w(e){return e===0?`Z`:Xw(e)}function eT(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const tT=[[`.000000000`,e=>`.${eT(e.ms,9,!1)}`],[`.999999999`,e=>{let t=eT(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${eT(e.ms,6,!1)}`],[`.999999`,e=>{let t=eT(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${Kw(e.ms)}`],[`.999`,e=>{let t=Kw(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>Vw[e.month-1]??`January`],[`Monday`,e=>Uw[e.weekday]??`Monday`],[`Z07:00`,e=>Qw(e.offsetMinutes)],[`-07:00`,e=>Yw(e.offsetMinutes)],[`Z0700`,e=>Zw(e.offsetMinutes)],[`-0700`,e=>Jw(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>Hw[e.month-1]??`Jan`],[`Mon`,e=>Ww[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>Xw(e.offsetMinutes)],[`Z07`,e=>$w(e.offsetMinutes)],[`15`,e=>Gw(e.hour)],[`01`,e=>Gw(e.month)],[`02`,e=>Gw(e.day)],[`_2`,e=>qw(e.day)],[`03`,e=>Gw(e.hour12)],[`04`,e=>Gw(e.minute)],[`05`,e=>Gw(e.second)],[`06`,e=>Gw(e.year%100)],[`PM`,e=>e.hour>=12?`PM`:`AM`],[`pm`,e=>e.hour>=12?`pm`:`am`],[`1`,e=>String(e.month)],[`2`,e=>String(e.day)],[`3`,e=>String(e.hour12)],[`4`,e=>String(e.minute)],[`5`,e=>String(e.second)]];function nT(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of tT)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const rT={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function iT(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const aT=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function oT(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=iT(new Intl.DateTimeFormat(`en-US`,{...rT,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=iT(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=sT(iT(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=aT.indexOf(r.get(`weekday`)??`Sunday`);return{year:parseInt(r.get(`year`)??`2000`,10),month:parseInt(r.get(`month`)??`1`,10),day:parseInt(r.get(`day`)??`1`,10),weekday:s===-1?0:s,hour:i,hour12:i%12||12,minute:parseInt(r.get(`minute`)??`0`,10),second:parseInt(r.get(`second`)??`0`,10),ms:e.getUTCMilliseconds(),tzAbbr:a,offsetMinutes:o}}function sT(e){if(e===`GMT`||e===`UTC`)return 0;let t=e.match(/^GMT([+-])(\d{1,2})(?::(\d{2}))?$/);if(!t)return 0;let n=t[1]===`+`?1:-1,r=parseInt(t[2]??`0`,10),i=parseInt(t[3]??`0`,10);return n*(r*60+i)}function cT(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function lT(e,t){return nT(e,oT(zw(t),cT()))}function uT(e,t,n){return nT(e,oT(zw(t),n))}function dT(e,t){let n=zw(t),r=Pw(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function fT(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:Fw(Rw(t))}return typeof e==`bigint`?Fw(Rw(Number(e))):typeof e==`number`?Fw(Rw(e)):`0s`}const pT=36e11*24*365,mT=36e11*24*30,hT=36e11*24,gT=36e11,_T=6e10,vT=1e9;function yT(e){let t=Pw(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>pT?`${Math.floor(n/pT)}y`:n>mT?`${Math.floor(n/mT)}mo`:n>hT?`${Math.floor(n/hT)}d`:n>gT?`${Math.floor(n/gT)}h`:n>_T?`${Math.floor(n/_T)}m`:n>vT?`${Math.floor(n/vT)}s`:`0s`}function bT(e){let t=oT(zw(e),cT());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function xT(e,t){let n=oT(zw(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function ST(e){return e()}const CT=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],wT=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function TT(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function ET(e,t,n){return[e.slice(t,t+n),t+n]}function DT(e,t,n,r){let i=t;for(;i<e.length&&i-t<r&&e.charCodeAt(i)>=48&&e.charCodeAt(i)<=57;)i++;if(i-t<n)throw Error(`sprig toDate: expected ${n}-${r} digits at pos ${t}`);return[parseInt(e.slice(t,i),10),i]}function OT(e,t){for(let[n,r]of CT.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function kT(e,t){for(let[n,r]of wT.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function AT(e,t){for(let n of[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`])if(e.startsWith(n,t))return t+n.length;throw Error(`sprig toDate: expected weekday name at pos ${t}`)}function jT(e,t){for(let n of[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`])if(e.startsWith(n,t))return t+n.length;throw Error(`sprig toDate: expected short weekday name at pos ${t}`)}function MT(e,t){if(e[t]===` `){let[n,r]=DT(e,t+1,1,1);return[n,r]}return DT(e,t,1,2)}function NT(e,t,n){let r=e[t]===`+`?1:e[t]===`-`?-1:0;if(r===0)throw Error(`sprig toDate: expected +/- at pos ${t}`);let i=t+1,[a,o]=DT(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=DT(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=DT(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function PT(e,t,n,r){if(e[t]===`Z`)return[0,t+1];if(r){let n=e[t]===`+`?1:e[t]===`-`?-1:0;if(n===0)throw Error(`sprig toDate: expected Z or +/- at pos ${t}`);let[r,i]=DT(e,t+1,2,2);return[n*r*60,i]}return NT(e,t,n)}function FT(e,t){let n=t;for(;n<e.length&&e.charCodeAt(n)>=65&&e.charCodeAt(n)<=90;)n++;if(n===t)throw Error(`sprig toDate: expected timezone abbreviation at pos ${t}`);return n}function IT(e,t,n){let[r,i]=ET(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function LT(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=OT(t,n);return i.month=e,[r,i]}case`Monday`:return[AT(t,n),i];case`Jan`:{let[e,r]=kT(t,n);return i.month=e,[r,i]}case`Mon`:return[jT(t,n),i];case`2006`:{let[e,r]=DT(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=DT(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=DT(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=DT(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=MT(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=DT(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=DT(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=DT(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=DT(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=DT(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=DT(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=DT(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=DT(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=DT(t,n,1,2);return i.second=e,[r,i]}case`PM`:case`pm`:{let e=t.slice(n,n+2).toLowerCase();if(e!==`am`&&e!==`pm`)throw Error(`sprig toDate: expected AM/PM at pos ${n}, got ${JSON.stringify(t.slice(n,n+2))}`);return i.isPM=e===`pm`,i.hour12=!0,[n+2,i]}case`MST`:return[FT(t,n),i];case`-0700`:{let[e,r]=NT(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=NT(t,n,!0);return i.offsetMinutes=e,[r,i]}case`-07`:{let e=t[n]===`+`?1:t[n]===`-`?-1:0;if(e===0)throw Error(`sprig toDate: expected +/- at pos ${n}`);let[r,a]=DT(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=PT(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=PT(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=PT(t,n,!1,!0);return i.offsetMinutes=e,[r,i]}case`.000000000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=IT(t,n+1,9);return i.ms=e,[r,i]}case`.999999999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(9,`0`);return i.ms=Math.round(parseInt(a,10)/1e6),[r,i]}case`.000000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=IT(t,n+1,6);return i.ms=e,[r,i]}case`.999999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(9,`0`);return i.ms=Math.round(parseInt(a,10)/1e6),[r,i]}case`.000`:{if(t[n]!==`.`)throw Error(`sprig toDate: expected . at pos ${n}`);let[e,r]=IT(t,n+1,3);return i.ms=e,[r,i]}case`.999`:{if(t[n]!==`.`)return[n,i];let e=n+1,r=e;for(;r<t.length&&t.charCodeAt(r)>=48&&t.charCodeAt(r)<=57;)r++;let a=t.slice(e,r).padEnd(3,`0`);return i.ms=parseInt(a,10),[r,i]}}throw Error(`sprig toDate: unhandled token ${e}`)}const RT=`.000000000,.999999999,.000000,.999999,.000,.999,January,Monday,Z07:00,-07:00,Z0700,-0700,2006,Jan,Mon,MST,-07,Z07,15,01,02,_2,03,04,05,06,PM,pm,1,2,3,4,5`.split(`,`);function zT(e,t){let n=0,r=0,i=TT();for(;n<e.length;){let a=!1;for(let o of RT)if(e.startsWith(o,n)){let[e,s]=LT(o,t,r,i);r=e,i=s,n+=o.length,a=!0;break}if(!a){let i=e.charAt(n);if(t[r]!==i)throw Error(`sprig toDate: expected ${JSON.stringify(i)} at pos ${r}, got ${JSON.stringify(t[r])}`);n++,r++}}if(r!==t.length)throw Error(`sprig toDate: extra characters at pos ${r}: ${JSON.stringify(t.slice(r))}`);if(i.hour12){let e=i.hour%12;i.hour=i.isPM?e+12:e}let a=Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second,i.ms)-i.offsetMinutes*60*1e3;return new Date(a)}function BT(e,t){return zT(e,t)}function VT(e){return String(Math.floor(zw(e).getTime()/1e3))}function HT(e=()=>new Date){return{now:{fn:()=>ST(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>lT(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>uT(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>dT(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>bT(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>xT(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>fT(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>yT(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>BT(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>Bw(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>VT(e),argTypes:[`value`],arity:{kind:`exact`}}}}function UT(e){return e==null||e===!1?!0:typeof e==`number`?e===0||Number.isNaN(e):typeof e==`bigint`?e===0n:typeof e==`string`||Array.isArray(e)?e.length===0:e instanceof Map||e instanceof Set?e.size===0:typeof e==`object`?Object.keys(e).length===0:!1}function WT(...e){for(let t of e)if(!UT(t))return t}function GT(e,t){return UT(t)?e:t}function KT(e){return JSON.parse(e)}function qT(e,t,n){return pC(n)?e:t}function JT(e){return JSON.stringify(e)??`null`}function YT(e){return JSON.stringify(e,null,2)??`null`}function XT(){return{default:{fn:(e,t)=>GT(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>UT(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>WT(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>qT(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>KT(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>JT(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>YT(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function ZT(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function QT(e){if(e.kind!==`call`||e.name!==`dict`||e.args.length%2!=0)return null;let t=[];for(let[n,r]of e.args.entries()){if(r.kind!==`literal`||n%2==0&&typeof r.value!=`string`)return null;t.push(r.value)}return ZT(...t)}function $T(e,t){return e[t]}function eE(e,t){return t in e}function tE(e){return Object.keys(e)}function nE(e,...t){let n={...e};for(let e of t)for(let[t,r]of Object.entries(e))t in n||(n[t]=r);return n}function rE(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function iE(e,...t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e))n.has(t)||(r[t]=i);return r}function aE(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function oE(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function sE(e,t,n){return e[t]=n,e}function cE(e,t){return delete e[t],e}function lE(e){return Object.values(e)}function uE(){return{dict:{fn:(...e)=>ZT(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>$T(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>sE(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>cE(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>tE(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>lE(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>oE(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>aE(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>iE(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>eE(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>nE(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>rE(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function dE(e){throw new CS(e)}function fE(){return{fail:{fn:e=>dE(e),argTypes:[`string`],arity:{kind:`exact`}}}}new TextEncoder,new Map(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`).map((e,t)=>[e,t])),new TextDecoder,new TextEncoder,new TextDecoder,new TextEncoder;function pE(...e){for(let t of e)if(UT(t))return!1;return!0}function mE(...e){for(let t of e)if(!UT(t))return!0;return!1}function hE(e,t){return[...e,t]}function gE(e,t){let n=Math.max(1,e),r=[];for(let e=0;e<t.length;e+=n)r.push(t.slice(e,e+n));return r}function _E(e){return e.filter(e=>!UT(e))}function vE(...e){let t=[];for(let n of e)t.push(...n);return t}const yE={line:0,column:0,offset:0};function bE(e,t,n,r){return new bS(e,t,n,r,yE)}function xE(...e){if(e.length<3)throw bE(`dig`,0,`at least 3 arguments (...keys, default, dict)`,`${e.length} argument${e.length===1?``:`s`}`);let t=e[e.length-1],n=e[e.length-2],r=e.slice(0,-2);if(!CE(t))throw bE(`dig`,e.length-1,`dict`,wE(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw bE(`dig`,e,`string`,wE(r[e]));return SE(t,n,r,e.length)}function SE(e,t,n,r){let i=n[0];if(!Object.hasOwn(e,i))return t;let a=e[i];if(n.length===1)return a;if(!CE(a))throw bE(`dig`,r-1,`dict at intermediate key`,wE(a));return SE(a,t,n.slice(1),r)}function CE(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function wE(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function TE(e){return e[0]}function EE(e,t){return t.some(t=>lC(t,e))}function DE(e){return e.slice(0,-1)}function OE(e){return e[e.length-1]}function kE(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function AE(...e){return e}function jE(e,t){return[t,...e]}function ME(e){return e.slice(1)}function NE(e){return[...e].reverse()}function PE(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function FE(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function IE(e){let t=[];for(let n of e)t.some(e=>lC(e,n))||t.push(n);return t}function LE(e,...t){return e.filter(e=>!t.some(t=>lC(t,e)))}function RE(){return{list:{fn:(...e)=>AE(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>TE(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>OE(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>ME(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>DE(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>kE(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>NE(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>IE(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>LE(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>EE(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>_E(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>PE(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>vE(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>gE(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>jE(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>hE(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>FE(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>hE(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>AE(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>xE(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>pE(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>mE(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function zE(...e){return e.reduce((e,t)=>e+t,0)}function BE(e){return e+1}function VE(e){return e+1}function HE(...e){return e.reduce((e,t)=>e+t,0)}function UE(e){return Math.ceil(e)}function WE(e,t){return Math.trunc(e/t)}function GE(e,...t){return t.reduce((e,t)=>e/t,e)}function KE(e){return Math.floor(e)}function qE(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function JE(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function YE(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function XE(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function ZE(e,t){return e%t}function QE(...e){return e.reduce((e,t)=>e*t,1)}function $E(...e){return e.reduce((e,t)=>e*t,1)}function eD(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function tD(e,t,n){let r=[];if(t<e){if(n>=0)return r;for(let i=e;i>t;i+=n)r.push(i);return r}if(n<=0)return r;for(let i=e;i<t;i+=n)r.push(i);return r}function nD(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),tD(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return tD(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:tD(n,i+t,r).join(` `)}default:return``}}function rD(e,t){return e-t}function iD(e,...t){return t.reduce((e,t)=>e-t,e)}function aD(e){return tD(0,e,e<0?-1:1)}function oD(){return{add:{fn:(...e)=>zE(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>rD(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>QE(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>WE(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>ZE(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>YE(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>qE(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>KE(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>UE(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>eD(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>HE(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>iD(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>$E(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>GE(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>BE(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>VE(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>JE(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>XE(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>qE(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>nD(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>aD(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>tD(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function sD(e){return Array.from(e)}function cD(e,t){return e===``?sD(t):t.split(e)}function lD(e,t){let n=sD(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function uD(e,t,n){let r=sD(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const Y={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},dD=/^[-_\s]$/,fD=/^\p{P}$/u,pD=/^\p{L}$/u,mD=/^\p{Lu}$/u,hD=/^\p{N}$/u;function gD(e){return e!==void 0&&dD.test(e)}function _D(e){return e!==void 0&&pD.test(e)}function vD(e){return e!==void 0&&mD.test(e)}function yD(e){return e!==void 0&&hD.test(e)}function bD(e){return e!==void 0&&fD.test(e)}function xD(e,t){if(t>=e.length)return{word:{wt:Y.Invalid,text:``},next:t};let n=e[t],r=t+1;if(gD(n)){for(;r<e.length&&gD(e[r]);)r++;return{word:{wt:Y.Connector,text:e.slice(t,r).join(``)},next:r}}if(bD(n)){for(;r<e.length&&bD(e[r]);)r++;return{word:{wt:Y.Punct,text:e.slice(t,r).join(``)},next:r}}if(vD(n)){if(r>=e.length)return{word:{wt:Y.UpperCase,text:n},next:r};if(vD(e[r])){let n=r;for(;n<e.length&&vD(e[n]);)n++;return n<e.length&&_D(e[n])?{word:{wt:Y.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:Y.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(_D(e[r])){let n=r+1;for(;n<e.length&&_D(e[n])&&!vD(e[n]);)n++;return{word:{wt:Y.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:Y.UpperCase,text:n},next:r}}if(_D(n)){for(;r<e.length&&_D(e[r])&&!vD(e[r]);)r++;return{word:{wt:Y.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(yD(n)){for(;r<e.length&&yD(e[r]);)r++;return{word:{wt:Y.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!gD(e[r])&&!_D(e[r])&&!yD(e[r])&&!bD(e[r]);)r++;return{word:{wt:Y.Other,text:e.slice(t,r).join(``)},next:r}}function SD(e,t,n){if(t.wt!==Y.UpperCase&&t.wt!==Y.Connector){e.push(t.text);return}for(let r of t.text)gD(r)?e.push(n):vD(r)?e.push(r.toLowerCase()):e.push(r)}function CD(e,t){if(e.length===0)return``;let n=sD(e),r=[],{word:i,next:a}=xD(n,0);for(;a<n.length;){i.wt!==Y.Connector&&SD(r,i,t);let e=i,o=i;if({word:i,next:a}=xD(n,a),e.wt===Y.Number){for(;i.wt===Y.Alphabet||i.wt===Y.Number;)SD(r,i,t),{word:i,next:a}=xD(n,a);i.wt!==Y.Invalid&&i.wt!==Y.Punct&&i.wt!==Y.Connector&&r.push(t);continue}if(e.wt===Y.Connector){SD(r,o,t);continue}if(e.wt===Y.Punct)continue;if(i.wt!==Y.Number){i.wt!==Y.Connector&&i.wt!==Y.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=xD(n,a),i.wt!==Y.Alphabet){SD(r,s,t),i.wt!==Y.Connector&&i.wt!==Y.Punct&&r.push(t);continue}for(r.push(t),SD(r,s,t);i.wt===Y.Alphabet||i.wt===Y.Number;)SD(r,i,t),{word:i,next:a}=xD(n,a);i.wt!==Y.Invalid&&i.wt!==Y.Connector&&i.wt!==Y.Punct&&r.push(t)}return SD(r,i,t),r.join(``).toLowerCase()}function wD(e){if(e.length===0)return``;let t=sD(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!gD(i)){i=i.toUpperCase();break}n.push(i)}if(r>=t.length)return t.length>0&&n.push(i),n.join(``);for(;r<t.length;){let e=i;if(i=t[r],r++,gD(i)&&gD(e)){n.push(e);continue}gD(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function TD(e){return wD(e)}function ED(...e){return e.join(` `)}function DD(e,t){return t.includes(e)}function OD(e,t){return t.startsWith(e)}function kD(e,t){return t.endsWith(e)}function AD(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
69
69
  `).map(e=>n+e).join(`
70
- `)}function AD(e){let t=new TextEncoder;return e.split(/\s+/).filter(e=>e.length>0).map(e=>String.fromCharCode(...t.encode(e).slice(0,1))).join(``)}function jD(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw yE(`join`,2,`list of strings/primitives`,`list element of type ${MD(e)}`);n.push(String(e))}return n.join(e)}function MD(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function ND(e){return SD(e,`-`)}function PD(e){return e.toLowerCase()}function FD(e,t){return`\n${kD(e,t)}`}function ID(e){return e.replace(/\s+/g,``)}function LD(e,t,n){return n===1?e:t}function RD(...e){return e.map(e=>`"${e}"`).join(` `)}function zD(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function BD(e,t){return t.repeat(Math.max(0,e))}function VD(e,t,n){return sD(e,n).join(t)}function HD(e){return SD(e,`_`)}function UD(e,t){let n=sD(e,t),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function WD(e,t){return sD(e,t)}function GD(e,t,n){let r=KD(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function KD(e,t,n){if(n===0)return[];let r=sD(t,e);if(n<0||r.length<=n)return r;let i=r.slice(0,n-1),a=r.slice(n-1).join(t);return[...i,a]}function qD(...e){return e.map(e=>`'${e}'`).join(` `)}function JD(e,t,n){let r=oD(n),i=t<0||t>r.length?r.length:t,a=Math.min(Math.max(0,e),i);return r.slice(a,i).join(``)}function YD(e){let t=``;for(let n of e)XD(n)?t+=n.toLowerCase():ZD(n)?t+=n.toUpperCase():t+=n;return t}function XD(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function ZD(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function QD(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function $D(e){return e.trim()}function eO(e,t){if(e.length===0)return t;let n=new Set(oD(e)),r=oD(t),i=0;for(;i<r.length&&n.has(r[i]);)i+=1;let a=r.length;for(;a>i&&n.has(r[a-1]);)--a;return r.slice(i,a).join(``)}function tO(e,t){return t.startsWith(e)?t.slice(e.length):t}function nO(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function rO(e,t){let n=oD(t);if(e<0){let r=-e;return r>=n.length?t:n.slice(n.length-r).join(``)}return e>=n.length?t:n.slice(0,e).join(``)}function iO(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function aO(e){return e.toUpperCase()}function oO(e,t){return sO(e,`
71
- `,t)}function sO(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
72
- `)){let n=``;for(let i of t.split(/\s+/))i.length!==0&&(n.length===0?n=i:n.length+1+i.length<=e?n+=` ${i}`:(r.push(n),n=i));n.length>0&&r.push(n)}return r.join(t)}function cO(e,t,n){return sO(e,t,n)}function lO(){return{abbrev:{fn:(e,t)=>cD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>lD(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>wD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>TD(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>ED(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>DD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>OD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>kD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>AD(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>jD(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>ND(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>PD(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>FD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>ID(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>LD(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>RD(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>zD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>BD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>VD(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>HD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>UD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>WD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>GD(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>qD(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>JD(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>YD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>QD(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>$D(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>eO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>tO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>nO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>rO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>iO(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>aO(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>oO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>cO(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function uO(e,t){let n=dO(e),r=n.copy();return r.style=md(n.style,t),r}function dO(e){if(!(e instanceof W))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function fO(e){return{fn:(t=>uO(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function pO(e){return{fn:((t,n)=>uO(n,new V({[e]:z.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function mO(e,t){return new V({[e]:t})}function hO(){let e={};for(let t of cd)e[t]=fO(mO(t,!0)),e[`not_${t}`]=fO(mO(t,!1));for(let[t,n]of Object.entries(ud))e[t]=fO(mO(n,!0));return e}const gO={fn:((e,t)=>uO(t,V.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},_O={fn:((e,t)=>uO(t,new V({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function vO(){return{fg:pO(`color`),bg:pO(`bgcolor`),...hO(),link:_O,style:gO}}function yO(e,t){let n;try{n=Yc(e.trim())}catch(n){throw n instanceof jc?TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`,{cause:n}):n}return bO(n,t,JSON.stringify(e))}function bO(e,t,n){if(e.alpha===0)throw RangeError(`${t} got ${n}, which is fully transparent: it draws no colour of its own, so there is nothing to compute with — use the colour of the surface it sits on, e.g. (color "background")`);return e}function xO(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function SO(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`)}return e}const CO=xO([`string`,`int`],((e,t)=>Ml(yO(e,`darken`),t).hex)),wO=xO([`string`,`int`],((e,t)=>Ml(yO(e,`lighten`),-t).hex)),TO={min:0,max:100,note:`0 = from, 100 = toward`},EO=xO([`string`,`string`,`float`],((e,t,n)=>Xc(yO(e,`mix`),yO(t,`mix`),SO(n,`mix`,`percentage`,TO)/100).hex)),DO={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},OO=xO([`string`],(e=>Pl(yO(e,`contrastOn`)).hex)),kO={depth:R.TRUECOLOR},AO=e=>xO([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return Fl(yO(t,`readableOn`),yO(n,`readableOn`),SO(r,`readableOn`,`ratio`,DO),i,void 0,a).hex})),jO={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function MO(){let e={};for(let[t,n]of Object.entries(jO)){let r=t;e[n]=xO([`string`,`float`],((e,t)=>{let i={...ml,[r]:SO(t,n,`amount`)};return B.fromRgba(yO(e,n)).applyKey(i).toRgba().hex}))}return e}function NO(e=()=>kO){return{darken:CO,lighten:wO,mix:EO,contrastOn:OO,readableOn:AO(e),...MO()}}function PO(e,t){if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:bO(El(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function FO(e){return{color:{fn:(t=>El(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new $u(Bu(n),PO(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}function IO(e,t,n){if(t.length%2!=0)throw RangeError(`last hold (${String(t[t.length-1])} s) has no ${e} — the arguments are <seconds> <${e}> pairs`);let r=[];for(let e=0;e<t.length;e+=2){let i=t[e];if(!Number.isFinite(i)||i<=0)throw RangeError(`hold ${e/2} must be a positive number of seconds, got ${i}`);r.push({seconds:i,value:n(t[e+1])})}return r}function LO(e){return{frames:{fn:((...t)=>rh(new nh(IO(`frame`,t,dO).map(({seconds:e,value:t})=>({seconds:e,text:t}))),e())),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...t)=>{let n=IO(`color`,t,e=>yO(e,`stepped`));return n[Yu(n.map(e=>e.seconds)).at(e())].value.hex}),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:2},returnType:`string`}}}function RO(e){return{...vO(),...NO(e)}}new V({color:`red`,dim:!0});const zO=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i,BO=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function VO(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(zO);if(n?.groups){let{family:e,newMajor:t,newMinor:r,oldMajor:i,oldMinor:a,oldFamily:o}=n.groups,s=e||o,c=t||i,l=r||a;if(s&&c)return`${s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()} ${l?`${c}.${l}`:c}`}let r=t.match(BO);if(r?.groups){let e=r.groups.family,t=r.groups.major,n=r.groups.minor;return`${e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()} ${n?`${t}.${n}`:t}`}return t||e}function HO(e){let t=e.match(BO);if(!t?.groups)return e;let n=t.groups.family,r=t.groups.major,i=t.groups.minor;return`${n.charAt(0).toUpperCase()}${i?`${r}.${i}`:r}`}function UO(e){let t=e.split(`/`),n=t.length-1;return t.map((e,t)=>{if(t===n)return e;let r=e.match(/^\.*./);return r?r[0]:e}).join(`/`)}function WO(e){return e.toLocaleString()}function GO(e){if(e.length===0)throw Error(`a cascade needs at least one stop, e.g. "0:calm"`);let t=[];for(let[n,r]of e.entries()){let e=r.indexOf(`:`),i=e<0?NaN:Number(r.slice(0,e));if(!Number.isFinite(i))throw Error(`cascade stop ${n} ("${r}") must be "<position>:<result>", e.g. "80:hot" — the position must be a number`);let a=t[n-1];if(a!==void 0&&i<a.at)throw Error(`cascade stops must be in ascending position order; stop ${n} at ${i} follows stop ${n-1} at ${a.at}`);t.push({at:i,text:r.slice(e+1)})}return t}function KO(e,t){if(!Number.isFinite(e))throw Error(`a cascade needs a finite value, got ${e}`);let n=-1;for(;n+1<t.length&&t[n+1].at<=e;)n++;return(n<0?t[0]:t[n]).text}const qO=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],JO=qO.length;function YO(e,t){let n=t===void 0?e:t<=0?[]:e.slice(-t);if(n.length===0)return``;let r=n[0],i=n[0];for(let e of n)e<r&&(r=e),e>i&&(i=e);let a=i-r,o=``;for(let e of n){let t=a===0?0:Math.round((e-r)/a*(JO-1));o+=qO[t]}return o}function XO(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(e===``)continue;let r=Number(e);if(!Number.isFinite(r))throw TypeError(`sparkline: non-numeric series element ${JSON.stringify(n)}`);t.push(r)}return t}function ZO(e,t,n){if(n.length!==0)throw Error(`${e}: takes at most ${t.length} optional argument${t.length===1?``:`s`} (${t.join(`, `)}), got ${t.length+n.length}`)}const QO=Rg(),$O=[...o_];function ek(){return{basename:{fn:e=>c(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>l(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>UO(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(Zx(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>Xx(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>Qx(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>QO,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>$O,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(ZO(`sparkline`,[`width`],n),YO(XO(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>KO(e,GO(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function tk(e,t,n,r){let i=n*6e4-(t*1e3-r);if(i<3e5||e<=0)return-1;let a=e/i;return Math.max(0,Math.round((100-e)/a/6e4))}const nk=e=>({minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e.now().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},etaMinutes:{fn:(t,n,r)=>tk(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function rk(){return{formatInteger:{fn:e=>WO(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>VO(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>HO(e),argTypes:[`string`],arity:{kind:`exact`}}}}const ik=e=>e.getTime()/1e3,ak=e=>new Date(e*1e3);let ok=null;function sk(e,t){if(ok!==null)throw Error(`a draw is already in progress: draws do not nest`);return ok={at:e,anim:t},{[Symbol.dispose]:()=>{ok=null}}}function ck(e){if((0,J._isComputingDerivation)())throw Error(`the clock was read by a value that keeps its answer (${e}): a template reaching a time variable or a clock function by a name it does not spell (index, get) is not known to read the instant — name it: {{ .clock }}`);if(ok===null)throw Error(`the clock was read outside a draw (${e})`);return ok}const lk={now:()=>ak(ck(`now`).at),animatedAt:()=>ck(`animatedAt`).anim},uk=new Set([`now`,`ago`]);function dk(e,t){return Object.fromEntries(Object.entries(VT(e)).filter(([e])=>uk.has(e)===t))}const fk=dk(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),pk=[e=>dk(e.now,!0),e=>LO(e.animatedAt),e=>Object.fromEntries(Object.entries(LO(()=>e.now().getTime()/1e3)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),nk];function mk(e){return Object.assign({},...e.map(e=>e(lk)))}const hk=new Set(Object.keys(mk(pk)));function gk(e){return new Set([...hk,...Object.keys(mk(e))])}const _k={readableOn:AO},vk=new Set(Object.keys(_k));function yk(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return ow({fromString:e=>new W(e),toString:e=>e.plain,isT:e=>e instanceof W,missingKey:`error`,funcs:{...YT(),...lO(),...LE(),...aD(),...jw(),...dE(),...lE(),...fk,...RO(r),...Object.fromEntries(Object.entries(_k).map(([e,t])=>[e,t(r)])),...mk([...pk,...e.clockFuncs??[]]),...ek(),...rk(),...n??{}}})}function bk(e){return xk(e,new Set(e.names()),``)}function xk(e,t,n){return new Proxy(Object.create(null),{has(r,i){if(typeof i!=`string`)return!1;let a=n?`${n}.${i}`:i;if(t.has(a))return!Ck(e,a);let o=`${a}.`;for(let e of t)if(e.startsWith(o))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a)){if(e.getKind(a)!==`document`)return e.read(a);let t=e.readDocument(a);return t.kind===`absent`?void 0:wk(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return xk(e,t,a)}})}function Sk(e,t){return new Proxy(e,{has:(e,t)=>t===`settings`||Reflect.has(e,t),get:(e,n)=>n===`settings`?t:Reflect.get(e,n)})}function Ck(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function wk(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new $x(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}const Tk=/\r\n|\r|\n/g,Ek=e=>P(e.replace(Tk,` `).trim());function Dk(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?I(`regex no-match`):P(n.replace(Tk,` `))}}const Ok=e=>{try{return P(JSON.parse(e))}catch(e){return I(`JSON parse failed: ${e.message}`)}};var kk=class{running=new Map;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:{kind:`started`,done:this.start(e,t)}}share(e,t){let n=this.running.get(e);return n===void 0?(this.again.add(e),this.start(e,t)):n}start(e,t){let n=this.loop(e,t);return this.running.set(e,n),n}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const Ak=[`first`,`period`,`change`,`request`,`supersede`];var jk=class{tallies=new Map;constructor(e=Me){this.logger=e}declare(e){let t=`${e.scope}/${e.name}`,n=this.tallies.get(t)??{name:e.name,scope:e.scope,refreshes:{},failures:0,lastMs:null};for(let t of e.refresh)n.refreshes[t]??=0;return this.tallies.set(t,n),new Nk(n,this.logger)}snapshot(){return[...this.tallies.entries()].sort(([e],[t])=>e<t?-1:+(e>t)).map(([,e])=>({...e,refreshes:{...e.refreshes}}))}totals(){let e=Object.fromEntries(Ak.map(e=>[e,0]));for(let t of this.tallies.values())for(let n of Ak)e[n]+=t.refreshes[n]??0;return e}};const Mk={first:!0,period:!0,change:!0,request:!1,supersede:!0};var Nk=class{constructor(e,t){this.tally=e,this.logger=t}record(){return{...this.tally,refreshes:{...this.tally.refreshes}}}recorded(e,t,n,r){this.tally.refreshes[t]=(this.tally.refreshes[t]??0)+1,this.tally.lastMs=r,n.kind===`failed`&&this.tally.failures++;let i=n.kind===`failed`;if(!i&&!Mk[t])return;let a=i?` reason=${JSON.stringify(n.reason)}`:``;this.logger(i?`warn`:`info`,`${this.tally.name} refresh ${e} by=${t} outcome=${n.kind}${a} took=${r}ms`)}};function Pk(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(E(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function Fk(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const Ik=`session.id`;function Lk(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await pt({bin:`/bin/sh`,args:[`-c`,e],cwd:t,category:`user-shell`,signal:n});if(!r.ok&&r.reason===`aborted`)throw n.reason;return r.ok?P(r.stdout):I(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function Rk(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await pe(e,{encoding:`utf8`,signal:n});return P(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return I(`file unreadable: ${e}`)}}}}function zk(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?I(`${r.reason} in ${n}`):r}function Bk(e){switch(e.kind){case`never`:return[`first`];case`ttl`:return[`first`,`period`];case`watch_file`:case`key`:case`depends_on`:return[`first`,`change`]}}function Vk(e){let t=!1;return()=>{e(`new-key`,t?`change`:`first`),t=!0}}function Hk(e){try{return b(e)}catch{return e}}function Uk(e){try{return ee(e).isDirectory()}catch{return!1}}function Wk(e){let t=Hk(e);return Uk(t)?{dir:t,name:null,leaf:!0}:Wx(t)}const Gk=e=>`${e.dir}\0${e.name??``}`;var Kk=class{watchers=new Map;subscribe(e,t,n){let r=this.watchers.get(e)??this.arm(e);return r.subscribers.set(t,n),r.watcher===null&&n(r.failure),()=>this.unsubscribe(e,t)}arm(e){let t={watcher:null,failure:``,target:Wk(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=Wk(e);if(t.watcher!==null&&Gk(n)===Gk(t.target))return;let r=this.open(e,t,n);r!==null&&(t.watcher?.close(),t.watcher=r,t.target=n)}open(e,t,n){let{dir:r,name:i}=n,a=s.basename(r);try{return x(r,(n,r)=>{if(!(r===null||i===null||r===i)&&r!==a)return;let o=t.target.leaf;if(this.rearm(e,t),!(!o&&!t.target.leaf))for(let e of t.subscribers.keys())e()})}catch(n){let i=`watch_file ${e}: cannot watch ${r} — ${n instanceof Error?n.message:String(n)}`;t.failure=i;for(let e of t.subscribers.values())e(i);return null}}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.watcher?.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e?.close();this.watchers.clear()}size(){return this.watchers.size}},qk=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:ve(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(ge(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())ge(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};const Jk={read:()=>Oa,drawnAt:()=>{throw new $x(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}};function Yk(e,t){let n=e;for(let e of t.split(`.`)){if(n===Oa)return Oa;if(typeof n!=`object`||!n)return;n=n[e]}return n}function Xk(e,t){if(t===Oa)return Oa;if(t===void 0)return I(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the preset reads`);switch(typeof t==`object`&&t?t.kind:void 0){case`ok`:case`absent`:case`failed`:return t;default:return I(`variable "${e}": the view's payload holds no source reading at "${e}"`)}}function Zk(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?Xx(e):t===`number`?Zx(e):Qx(e)}function Qk(e){return e===`number`?0:e===`boolean`?!1:``}var $k=class e{lastErrors=new Map;policyFaults=J.observable.map(void 0,{deep:!1});watchMgr=new Kk;ttlMgr=new qk;cleanups=[];runs=new Map;newKeys=J.observable.set();reads=new kk;askedBy=new Map;abort=new AbortController;inputs=J.observable.box(Jk,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=yk({drawnAt:this.drawnAt});sourceNames=J.observable.array([],{deep:!1});publishedNow=(0,J.computed)(()=>({values:this.sourceNames.map(e=>this.store.stored(e)),faults:[...this.policyFaults.values()]}));published(){return this.publishedNow.get()}sessionState;constructor(e,t=``,n,r=null,i=new jk){this.store=e,this.defaultEmptyValue=t,this.parent=r,this.ledger=i,this.sessionState=n}view(){return new e(new pS(this.store),this.defaultEmptyValue,this.sessionState,this,this.ledger)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Yx(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,I(t))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>Xk(e,this.inputs.get().read(e)))}own(e){this.cleanups.push(e)}declareInput(e,t,n,r,i){this.store.defineDerived(e,n,i,()=>this.inputAt(e,t,n,r))}inputAt(e,t,n,r){let i=this.inputs.get().read(t);if(i===Oa)throw this.lastErrors.delete(e),new $x(e,`variable "${e}" has no value yet: its source has not answered`);if(i===void 0)return this.fallbackOf(e,n,r,`input path "${t}" not found in payload`);try{let t=Zk(i,n);return this.lastErrors.delete(e),t}catch(t){return this.fallbackOf(e,n,r,t instanceof Error?t.message:String(t))}}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,Lk(t,n.cwd,this.abort.signal),Pk(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,Rk(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where);(0,J.runInAction)(()=>this.sourceNames.push(e));let a=this.ledger.declare({name:`var.${e}`,scope:this.parent===null?`directory`:`view`,refresh:Bk(n)});this.registerCachePolicy(e,n,(n,r)=>this.runSource(e,t,i,n,r,a))}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,Ek,t.default,n);case`regex`:return this.scalarPublisher(e,Dk(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=zk(n,t,r);return this.noteOutcome(e,a),this.store.setBox(e,Da(a,i)),a}}documentPublisher(e,t,n){let r=t===void 0?Oa:P(t);this.store.defineDocument(e,r);let i,a=!1;return this.cleanups.push(()=>clearTimeout(i)),o=>{clearTimeout(i);let s=o.kind===`ok`&&o.value.trim()===``?F:o,c=zk(s,Ok,n);this.noteOutcome(e,c);let l=c.kind===`ok`||s.kind===`ok`||t===void 0?c:r,u=a&&s.kind===`ok`&&c.kind!==`ok`,d=()=>{a=c.kind===`ok`,this.store.setDocument(e,l)};return u?i=setTimeout(d,250):d(),c}}runSource(e,t,n,r,i,a){this.askedBy.set(e,i);let o=this.reads.run(e,()=>{let r=this.askedBy.get(e)??i,o=Date.now();return t.read().then(e=>a.recorded(`where=${as(t.where)}`,r,n(e),Date.now()-o),e=>{if(e!==this.abort.signal.reason)throw e})});this.track(e,o,r)}track(e,t,n){if((0,J.runInAction)(()=>{t.kind===`started`&&(this.runs.set(e,t.done),this.newKeys.delete(e)),n===`new-key`&&this.newKeys.add(e)}),t.kind===`queued`)return;let r=t.done;r.finally(()=>(0,J.runInAction)(()=>{this.runs.get(e)===r&&(this.runs.delete(e),this.newKeys.delete(e))}))}async inFlight(e){try{await(0,J.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}}awaited(){return[...this.newKeys,...this.parent?.awaited()??[]]}async settled(e){return await this.inFlight(AbortSignal.timeout(e)),this.awaited()}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(bk(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){let n=this.engine.parse(`{{ date .layout now }}`),r={layout:t.format};this.declareDerived(e,`string`,`projection`,()=>n.evaluate(r).map(e=>e.plain).join(``),t.varDefault)}declareDerived(e,t,n,r,i){this.store.defineDerived(e,t,n,()=>{try{let n=Zk(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=eS(t);if(n!==void 0)throw this.lastErrors.delete(e),n;let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),i===void 0)throw Error(`variable "${e}": ${r}`);return i}})}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(Ik);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}stateRevision(){let e=this.store.has(`session.id`)?this.store.read(Ik):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}bindInputs(e){(0,J.runInAction)(()=>this.inputs.set(e))}getLastError(e){if(!this.declaredHere(e))return this.parent?.getLastError(e);let t=this.lastErrors.get(e),n=this.policyFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){return new Map([...this.parent?.cachePolicyFaults()??[],...this.policyFaults])}declaredHere(e){return this.store.has(e)&&!(this.parent?.store.has(e)??!1)}dispose(){this.abort.abort();for(let e of this.cleanups)e();return this.cleanups.length=0,this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:n(`new-key`,`first`);break;case`ttl`:{n(`new-key`,`first`);let e=this.ttlMgr.subscribe(t.durationMs,()=>n(`re-read`,`period`));this.cleanups.push(e);break}case`watch_file`:{n(`new-key`,`first`);let r=this.watchMgr.subscribe(t.path,()=>n(`re-read`,`change`),t=>this.notePolicy(e,I(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template);this.onReads(e,()=>{try{return P(r.evaluate(bk(this.store)).map(e=>e.plain).join(``))}catch(e){return eS(e)===void 0?I(`cache key: ${e instanceof Error?e.message:String(e)}`):Oa}},Vk(n));break}case`depends_on`:this.onReads(e,()=>{let e=t.varNames.map(e=>this.store.changeKey(e));return e.every(e=>e.kind===`ok`)?P(e.map(e=>e.value).join(`,`)):Oa},Vk(n));break}}onReads(e,t,n){let r,i=(0,J.reaction)(t,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===r)&&(r=t.value,n())},{fireImmediately:!0});this.cleanups.push(i)}fallbackOf(e,t,n,r){if(this.recordError(e,r),n!==void 0)return n;try{return Zk(this.defaultEmptyValue,t)}catch{return Qk(t)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}notePolicy(e,t){(0,J.runInAction)(()=>{t.kind===`failed`?this.policyFaults.get(e)?.message!==t.reason&&this.policyFaults.set(e,{timestamp:Date.now(),message:t.reason}):this.policyFaults.delete(e)})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function eA(e,t){let n=dy[e],r=yy(e),i=n.kind===`session`||n.kind===`config`?n.floor:``;return r===`string`?{kind:`input`,path:t,default:``}:{kind:`input`,path:t,type:r,default:i}}const tA=Object.fromEntries([...Dy].map(([e,t])=>[t,eA(e,t)])),nA={subscribers:`number`,fps:`number`,shown:`boolean`},rA=Object.keys(nA),iA={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[Ik]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`,default:``},config_path:{kind:`input`,path:`configPath`,default:``},...tA,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(Fv.flatMap(e=>rA.map(t=>[zv(e,t),{kind:`input`,path:zv(e,t),type:nA[t],default:Rv[t]}]))),[Lv(`by`)]:{kind:`input`,path:Lv(`by`),default:Iv.by},[Lv(`fps`)]:{kind:`input`,path:Lv(`fps`),type:`number`,default:0},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"tmux.pane":{kind:`input`,path:`tmux.pane`,default:``},"autocompact.window":{kind:`input`,path:`autocompact.window`,type:`number`,default:-1},...Object.fromEntries([`applied`,`lower`,`higher`].map(e=>[`autocompact.${e}`,{kind:`input`,path:`autocompact.${e}`,type:`number`,default:0}])),"autocompact.error":{kind:`input`,path:`autocompact.error`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},aA={today:`the day the draw is at`,feeds:`the frames a lane was sent up to the draw's instant`,drawing:`who the draw is for`};function oA(e){let t=e.split(`.`,1)[0];return Object.hasOwn(aA,t)?t:void 0}const sA=Object.fromEntries(Ug.map(e=>[e,Dy.get(e)]));function cA(e){return Ug.find(t=>sA[t]===e)}const lA=`ne .tmux.pane ""`;function uA(e,t,n){let r=new Set,i=e=>{for(let t of Dx(e??``,n).keys())r.add(t)};for(let t of Object.values(e.segments))i(t.template),i(t.bg),i(t.fg),i(t.when);for(let e of t)for(let t of E_(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(Ik);for(let t of Object.values(e.actions)){r.add(Ik);for(let[,e]of px(t))i(e);let e=`set`in t?Oy.get(t.set):void 0,n=`persist`in t?Dy.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function dA(e,t,n){let r=Hx({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of uA(e,t,n.helpers)){if(Vx(a,r))continue;let e=iA[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function fA(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const pA=`groups.`,mA=`menus.`,hA=`menupages.`,gA=`edit.`,X=`candybar.`,_A=[pA,mA,hA,gA,X];function vA(e){return _A.some(t=>e.startsWith(t))}function yA(e){let t=fA(e);return _A.find(e=>t.startsWith(fA(e)))}function bA(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:G(e.source,[`root`])})}function xA(e){return e}function SA(e,t,n){return n===void 0?mA+fA(e)+`.`+fA(t):CA(n)}function CA(e){return mA+fA(e)}function wA(e,t){return e+`.`+t}function TA(e){return hA+e}const EA=[`closeOnPick`,`paged`,`key`,`distribution`],DA=e=>EA.includes(e),OA=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${Eh.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function kA(e){for(let t of Object.keys(e))if(!DA(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${OA}`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);let r=e.distribution;if(r!==void 0&&!Dh(r))throw Error(`{{ menu }} option "distribution" must be one of: ${Eh.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:kh(r)}}const AA=e=>`from`in e?e.from:e.themes;function jA(e,t,n){return e===`bool`?v_(t)!==null:`min`in e?y_(t,e)!==null:cx(AA(e),n).members.includes(t)}function MA(e,t){if(e===`bool`)return g_.join(` or `);if(!(`min`in e)){let n=AA(e),{members:r}=cx(n,t),i=r.map(e=>JSON.stringify(e));if(r.length<=8)return`one of ${i.join(`, `)}`;let a=typeof n==`string`?` "${n}"`:``;return`one of the ${r.length}${a} names, such as ${i.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function NA(e){return{label:e.label,domain:PA(e.domain)}}function PA(e){return e===`theme`?{themes:ax}:e===`bool`||`min`in e?e:{from:e}}function FA(e,t,n,r,i){let a=Ci(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...g_]}},variables:{}};if(`from`in o)return IA(t,r,i,o.from,e=>({template:`{{ "${a}" }} {{ carousel "${e.apply}" 0 "${e.open}" }}`,rows:[`{{ picker "${e.apply}" "${e.page}" false true true }}`]}));if(`themes`in o)return IA(t,r,i,o.themes,e=>({template:`{{ action "${e.open}" "${a}" .${n} }} {{ action "${e.open}" (swatch "${e.apply}") }}`,rows:[`{{ swatches "${e.apply}" "${e.page}" }}`,`{{ themePreview "${e.apply}" }}`]}));let s=e=>({set:t,min:o.min,max:o.max,by:e});return{kind:`inline`,template:`{{ action "${r}.down" "◀" }} {{ "${a}" }} {{ .${n} }} {{ action "${r}.up" "▶" }}`,actions:{[`${r}.down`]:s(-o.step),[`${r}.up`]:s(o.step)},variables:{}}}function IA(e,t,n,r,i){let a={variable:n,key:n,member:t},o=wA(n,t),s=`${t}.open`,c=TA(n),l=`${c}.current`,{template:u,rows:d}=i({apply:t,open:s,page:c});return{kind:`picker`,template:u,actions:{[t]:{set:e,from:r},[o]:N(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:Ai(n,yi),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const LA=Object.fromEntries(Object.entries(dy).map(([e,t])=>[e,t.spec]));function RA(e){return dy[e].domain}function zA(e,t){return{required:!1,json:{not:{},description:`not allowed here — ${e}`},parse:(e,n,r,i)=>{i[r]!==void 0&&e.issues.push({path:`${n}.${r}`,message:t(`${n}.${r}`),line:G(e.source,[...n.split(`.`),r])})}}}function BA(e){return zA(`${e} cannot select a preset`,t=>`${t}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`)}function VA(e){return zA(`${e} cannot change the settings menu glyph`,t=>`${t}: ${e} cannot change the settings menu glyph — one menu is shared by every preset. Set it in the top-level globals.menuGlyph instead.`)}function HA(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Wg(s)){r.issues.push({path:`${i}.${a}`,message:`${i}.${a}: a rule is not allowed here — ${t} ${n}, so it names a value. Write the rule in globals.${a} (or a preset's globals.${a}) instead.`,line:G(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const UA={default_bg:"nothing reads it — a segment with no `bg:` wears the decoration tint of its place in the bar. Delete the key, and author `bg:` on the segments that need a fixed colour.",default_fg:"nothing reads it — a segment with no `fg:` wears text chosen for contrast against its background. Delete the key, and author `fg:` on the segments that need a fixed colour.",default_truncate_marker:'nothing reads it — a segment clipped to its `width:` always ends in "…". Delete the key.',look:`it was renamed "style" — write the same name as style: "<name>"`,progression:`it was renamed "variation", and its values with it: accent (was secondary-accent), duo (was primary-secondary), mono (was primary)`,charset:"the bar always draws Nerd Font glyphs. Delete the key; `cc-candybar doctor` names what your terminal's font is missing."},WA={noun:`globals key`,fields:LA,removed:UA},GA={preset:BA(`a preset`),menuGlyph:VA(`a preset`)},KA={noun:`preset globals key`,fields:{...LA,...GA},removed:UA};function qA(e){return rj(e)&&!(e in GA)}const JA=`is decided later than any rule could be settled`,YA={noun:`editGlobals key`,removed:UA,fields:{...LA,preset:BA(`the editGlobals fragment`),menuGlyph:VA(`the editGlobals fragment`),palette:HA(LA.palette,`the editGlobals fragment`,JA),style:HA(LA.style,`the editGlobals fragment`,JA),effect:HA(LA.effect,`the editGlobals fragment`,JA)}},XA={noun:`theme default key`,fields:{...Object.fromEntries(hy.map(e=>[e,LA[e]])),style:HA(LA.style,`a theme's default`,`is the look that theme wears by name`)}};function ZA(e,t){if(!sv(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${cv(t)}`,line:G(e.source,[`themeDefaults`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=`themeDefaults.${r}`;if(!e.allowedPalettes.has(r)){e.issues.push({path:t,message:`${t}: "${r}" is not an installed theme${Fg(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:G(e.source,[`themeDefaults`,r])});continue}let a=lv(e,XA,t,i);a!==null&&(n[r]=a)}return n}function QA(e,t,n){return n===void 0?{}:lv(e,WA,t,n)??{}}function $A(e,t,n){return lv(e,KA,t,n)??{}}function ej(){return Av(KA)}function tj(e,t,n){return lv(e,YA,t,n)??{}}const nj=new Set(Object.keys(LA));function rj(e){return nj.has(e)}function ij(e){return Object.hasOwn(UA,e)?UA[e]:void 0}function aj(){return[...nj]}const oj=new Map(Object.entries(dy).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function sj(e){let t=new Map;for(let[n,r]of oj){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const cj=/^segments\.([^.]+)\.palette$/,lj=/^presets\.(.+)\.root$/,uj=/^presets\.(.+)\.globals\.([^.]+)$/,dj=/^themeDefaults\.(.+)\.([^.]+)$/;function fj(e){return`presets.${e}.root`}function pj(e,t){return`themeDefaults.${e}.${t}`}const mj=e=>hy.includes(e);function hj(e,t){return`presets.${e}.globals.${t}`}function gj(e){if(rj(e))return{scope:`globals`,field:e};let t=cj.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=uj.exec(e);if(n&&qA(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=dj.exec(e);if(r&&mj(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=lj.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function _j(e){switch(e.scope){case`globals`:return[`globals`,e.field];case`preset-globals`:return[`presets`,e.preset,`globals`,e.field];case`segment-palette`:return[`segments`,e.segment,`palette`];case`theme-default`:return[`themeDefaults`,e.theme,e.field]}}const vj=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],yj=[...vj,`other`],bj={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},xj=ow({fromString:e=>e}),Sj=`${X}menu`,Cj=`open`,wj={variable:Sj,key:Sj,member:Cj},Tj=`edit.mode`,Ej=`edit.configure`,Dj=`edit.toggle`,Oj=`arrange`,kj=`${gA}draft.`;function Aj(e,t){return`${e}:${t}`}const jj={variable:Tj,key:Tj,member:Oj},Mj=Ti(jj);function Nj(e){try{return xj.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function Pj(e){if(Object.values(e.actions??{}).some(e=>`do`in e&&e.do.includes(`edit.toggle`)))return!0;for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&Nj(e))return!0;return!1}function Fj(e,t){if(bA(e,t,gA,`edit mode`),!Pj(t))return;let{variables:n,actions:r}=Ij();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function Ij(){return{variables:{[Tj]:{...Ai(Tj,yi),within:[wj]},[Ej]:{...Ai(Ej,yi),within:[jj]}},actions:{[Dj]:N(Tj,Oj),"edit.unconfigure":{set:Ej,to:yi}}}}const Lj=`open`;function Rj(e,t,n,r){let i={variable:e,key:e,member:Lj};return r.variables[e]={...Ai(e,yi),...n.length>0&&{within:n}},r.actions[e]=N(e,Lj),r.segments[e]={template:Di(e,`(?)`,`✕`),...zj(n)},wi(e,i,{kind:`container`,direction:`horizontal`,children:t.map((t,n)=>{let i=`${e}.${n}`;return r.segments[i]={template:t},{kind:`segment`,name:i}})},`drop`)}function zj(e){let[t,...n]=e;return t===void 0?{}:{when:Ti(t,...n)}}const Bj=`none`;function Vj(e){return El(e,`background`)}var Hj=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function Uj(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=Wj(n,i),l=c!==Bj,u=l?c===void 0?o:Gj(a,c,`bg`):Vj(a);e.bg=u;let d=Wj(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:Xh(a,e,t))(u):void 0:Gj(a,d,`fg`);return new V({...l&&{bgcolor:z.fromRgba(u)},...f!==void 0&&{color:z.fromRgba(f)}})}function Wj(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function Gj(e,t,n){try{return El(e,t)}catch(e){throw e instanceof Tl?new Hj(t,n,e.message):e}}const Kj=`🔧`,qj={help:[`-h`,`--help`],version:[`-V`,`--version`]},Jj=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],Yj=Object.fromEntries(Jj.map(e=>[e.member,e.label])),Xj={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},Zj=Object.keys(Xj),Qj=ky(e=>Sy[e].place),$j=e=>Object.hasOwn(Xj,e),eM=(e,t)=>e===t||$j(e)&&eM(Qj[Xj[e].beside],t),tM=e=>$j(e)?`${tM(Qj[Xj[e].beside])} › ${Xj[e].trigger}`:e===`door`?`first line`:Yj[e],nM=e=>tM(Qj[e]),rM=()=>[`door`,...Jj.map(e=>e.member)].flatMap(e=>[e,...Zj.filter(t=>eM(t,e))]).map(e=>({path:tM(e),names:Cy.filter(t=>Qj[t]===e)})).filter(({names:e})=>e.length>0),iM=e=>`${Pv[e].label} is off — turn it on in the settings menu's ${nM(Pv[e].setting)}, or set globals.${Pv[e].setting}: true`,aM=[...new Set(Object.values(Pv).map(e=>nM(e.setting)))].join(` or `),oM=Math.max(...Object.values(Sy).map(e=>e.configKey.length))+2,sM=[`✚ inserts`,`✖ removes`,`${Kj} configures`,`↺ resets layout`],cM={band:[`animates the bar in the band above the prompt, through a Claude Code mod`,`on: installs the candybar-band mod from this checkout and types /reload-plugins`],statusline:[`animates the statusline itself, through the attach launcher shipped with cc-candybar`,`on: exits this Claude Code and starts it again under that launcher, on this session`,`or start one yourself: cc-candybar --help prints the line to type`],pane:[`animates the bar in a tmux pane under this session's`,`on: opens that pane · off: closes it`],tmuxStatus:[`animates the bar in the tmux status line, while this session's pane is the one it shows`,`on: the daemon draws it there · off: puts the status line back as it was`]},lM=`
70
+ `)}function jD(e){let t=new TextEncoder;return e.split(/\s+/).filter(e=>e.length>0).map(e=>String.fromCharCode(...t.encode(e).slice(0,1))).join(``)}function MD(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw bE(`join`,2,`list of strings/primitives`,`list element of type ${ND(e)}`);n.push(String(e))}return n.join(e)}function ND(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function PD(e){return CD(e,`-`)}function FD(e){return e.toLowerCase()}function ID(e,t){return`\n${AD(e,t)}`}function LD(e){return e.replace(/\s+/g,``)}function RD(e,t,n){return n===1?e:t}function zD(...e){return e.map(e=>`"${e}"`).join(` `)}function BD(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function VD(e,t){return t.repeat(Math.max(0,e))}function HD(e,t,n){return cD(e,n).join(t)}function UD(e){return CD(e,`_`)}function WD(e,t){let n=cD(e,t),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function GD(e,t){return cD(e,t)}function KD(e,t,n){let r=qD(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function qD(e,t,n){if(n===0)return[];let r=cD(t,e);if(n<0||r.length<=n)return r;let i=r.slice(0,n-1),a=r.slice(n-1).join(t);return[...i,a]}function JD(...e){return e.map(e=>`'${e}'`).join(` `)}function YD(e,t,n){let r=sD(n),i=t<0||t>r.length?r.length:t,a=Math.min(Math.max(0,e),i);return r.slice(a,i).join(``)}function XD(e){let t=``;for(let n of e)ZD(n)?t+=n.toLowerCase():QD(n)?t+=n.toUpperCase():t+=n;return t}function ZD(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function QD(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function $D(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function eO(e){return e.trim()}function tO(e,t){if(e.length===0)return t;let n=new Set(sD(e)),r=sD(t),i=0;for(;i<r.length&&n.has(r[i]);)i+=1;let a=r.length;for(;a>i&&n.has(r[a-1]);)--a;return r.slice(i,a).join(``)}function nO(e,t){return t.startsWith(e)?t.slice(e.length):t}function rO(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function iO(e,t){let n=sD(t);if(e<0){let r=-e;return r>=n.length?t:n.slice(n.length-r).join(``)}return e>=n.length?t:n.slice(0,e).join(``)}function aO(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function oO(e){return e.toUpperCase()}function sO(e,t){return cO(e,`
71
+ `,t)}function cO(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
72
+ `)){let n=``;for(let i of t.split(/\s+/))i.length!==0&&(n.length===0?n=i:n.length+1+i.length<=e?n+=` ${i}`:(r.push(n),n=i));n.length>0&&r.push(n)}return r.join(t)}function lO(e,t,n){return cO(e,t,n)}function uO(){return{abbrev:{fn:(e,t)=>lD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>uD(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>TD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>ED(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>DD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>OD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>kD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>AD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>jD(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>MD(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>PD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>FD(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>ID(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>LD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>RD(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>zD(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>BD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>VD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>HD(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>UD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>WD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>GD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>KD(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>JD(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>YD(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>XD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>$D(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>eO(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>tO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>nO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>rO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>iO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>aO(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>oO(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>sO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>lO(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function dO(e,t){let n=fO(e),r=n.copy();return r.style=md(n.style,t),r}function fO(e){if(!(e instanceof W))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function pO(e){return{fn:(t=>dO(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function mO(e){return{fn:((t,n)=>dO(n,new V({[e]:z.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function hO(e,t){return new V({[e]:t})}function gO(){let e={};for(let t of cd)e[t]=pO(hO(t,!0)),e[`not_${t}`]=pO(hO(t,!1));for(let[t,n]of Object.entries(ud))e[t]=pO(hO(n,!0));return e}const _O={fn:((e,t)=>dO(t,V.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},vO={fn:((e,t)=>dO(t,new V({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function yO(){return{fg:mO(`color`),bg:mO(`bgcolor`),...gO(),link:vO,style:_O}}function bO(e,t){let n;try{n=Yc(e.trim())}catch(n){throw n instanceof jc?TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`,{cause:n}):n}return xO(n,t,JSON.stringify(e))}function xO(e,t,n){if(e.alpha===0)throw RangeError(`${t} got ${n}, which is fully transparent: it draws no colour of its own, so there is nothing to compute with — use the colour of the surface it sits on, e.g. (color "background")`);return e}function SO(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function CO(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`)}return e}const wO=SO([`string`,`int`],((e,t)=>Ml(bO(e,`darken`),t).hex)),TO=SO([`string`,`int`],((e,t)=>Ml(bO(e,`lighten`),-t).hex)),EO={min:0,max:100,note:`0 = from, 100 = toward`},DO=SO([`string`,`string`,`float`],((e,t,n)=>Xc(bO(e,`mix`),bO(t,`mix`),CO(n,`mix`,`percentage`,EO)/100).hex)),OO={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},kO=SO([`string`],(e=>Pl(bO(e,`contrastOn`)).hex)),AO={depth:R.TRUECOLOR},jO=e=>SO([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return Fl(bO(t,`readableOn`),bO(n,`readableOn`),CO(r,`readableOn`,`ratio`,OO),i,void 0,a).hex})),MO={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function NO(){let e={};for(let[t,n]of Object.entries(MO)){let r=t;e[n]=SO([`string`,`float`],((e,t)=>{let i={...ml,[r]:CO(t,n,`amount`)};return B.fromRgba(bO(e,n)).applyKey(i).toRgba().hex}))}return e}function PO(e=()=>AO){return{darken:wO,lighten:TO,mix:DO,contrastOn:kO,readableOn:jO(e),...NO()}}function FO(e,t){if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:xO(El(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function IO(e){return{color:{fn:(t=>El(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new $u(Bu(n),FO(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}function LO(e,t,n){if(t.length%2!=0)throw RangeError(`last hold (${String(t[t.length-1])} s) has no ${e} — the arguments are <seconds> <${e}> pairs`);let r=[];for(let e=0;e<t.length;e+=2){let i=t[e];if(!Number.isFinite(i)||i<=0)throw RangeError(`hold ${e/2} must be a positive number of seconds, got ${i}`);r.push({seconds:i,value:n(t[e+1])})}return r}function RO(e){return{frames:{fn:((...t)=>rh(new nh(LO(`frame`,t,fO).map(({seconds:e,value:t})=>({seconds:e,text:t}))),e())),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...t)=>{let n=LO(`color`,t,e=>bO(e,`stepped`));return n[Yu(n.map(e=>e.seconds)).at(e())].value.hex}),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:2},returnType:`string`}}}function zO(e){return{...yO(),...PO(e)}}new V({color:`red`,dim:!0});const BO=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i,VO=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function HO(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(BO);if(n?.groups){let{family:e,newMajor:t,newMinor:r,oldMajor:i,oldMinor:a,oldFamily:o}=n.groups,s=e||o,c=t||i,l=r||a;if(s&&c)return`${s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()} ${l?`${c}.${l}`:c}`}let r=t.match(VO);if(r?.groups){let e=r.groups.family,t=r.groups.major,n=r.groups.minor;return`${e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()} ${n?`${t}.${n}`:t}`}return t||e}function UO(e){let t=e.match(VO);if(!t?.groups)return e;let n=t.groups.family,r=t.groups.major,i=t.groups.minor;return`${n.charAt(0).toUpperCase()}${i?`${r}.${i}`:r}`}function WO(e){let t=e.split(`/`),n=t.length-1;return t.map((e,t)=>{if(t===n)return e;let r=e.match(/^\.*./);return r?r[0]:e}).join(`/`)}function GO(e){return e.toLocaleString()}function KO(e){if(e.length===0)throw Error(`a cascade needs at least one stop, e.g. "0:calm"`);let t=[];for(let[n,r]of e.entries()){let e=r.indexOf(`:`),i=e<0?NaN:Number(r.slice(0,e));if(!Number.isFinite(i))throw Error(`cascade stop ${n} ("${r}") must be "<position>:<result>", e.g. "80:hot" — the position must be a number`);let a=t[n-1];if(a!==void 0&&i<a.at)throw Error(`cascade stops must be in ascending position order; stop ${n} at ${i} follows stop ${n-1} at ${a.at}`);t.push({at:i,text:r.slice(e+1)})}return t}function qO(e,t){if(!Number.isFinite(e))throw Error(`a cascade needs a finite value, got ${e}`);let n=-1;for(;n+1<t.length&&t[n+1].at<=e;)n++;return(n<0?t[0]:t[n]).text}const JO=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],YO=JO.length;function XO(e,t){let n=t===void 0?e:t<=0?[]:e.slice(-t);if(n.length===0)return``;let r=n[0],i=n[0];for(let e of n)e<r&&(r=e),e>i&&(i=e);let a=i-r,o=``;for(let e of n){let t=a===0?0:Math.round((e-r)/a*(YO-1));o+=JO[t]}return o}function ZO(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(e===``)continue;let r=Number(e);if(!Number.isFinite(r))throw TypeError(`sparkline: non-numeric series element ${JSON.stringify(n)}`);t.push(r)}return t}function QO(e,t,n){if(n.length!==0)throw Error(`${e}: takes at most ${t.length} optional argument${t.length===1?``:`s`} (${t.join(`, `)}), got ${t.length+n.length}`)}const $O=Rg(),ek=[...o_];function tk(){return{basename:{fn:e=>c(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>l(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>WO(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(Qx(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>Zx(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>$x(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>$O,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>ek,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(QO(`sparkline`,[`width`],n),XO(ZO(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>qO(e,KO(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function nk(e,t,n,r){let i=n*6e4-(t*1e3-r);if(i<3e5||e<=0)return-1;let a=e/i;return Math.max(0,Math.round((100-e)/a/6e4))}const rk=e=>({minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e.now().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},etaMinutes:{fn:(t,n,r)=>nk(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function ik(){return{formatInteger:{fn:e=>GO(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>HO(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>UO(e),argTypes:[`string`],arity:{kind:`exact`}}}}const ak=e=>e.getTime()/1e3,ok=e=>new Date(e*1e3);let sk=null;function ck(e,t){if(sk!==null)throw Error(`a draw is already in progress: draws do not nest`);return sk={at:e,anim:t},{[Symbol.dispose]:()=>{sk=null}}}function lk(e){if((0,J._isComputingDerivation)())throw Error(`the clock was read by a value that keeps its answer (${e}): a template reaching a time variable or a clock function by a name it does not spell (index, get) is not known to read the instant — name it: {{ .clock }}`);if(sk===null)throw Error(`the clock was read outside a draw (${e})`);return sk}const uk={now:()=>ok(lk(`now`).at),animatedAt:()=>lk(`animatedAt`).anim},dk=new Set([`now`,`ago`]);function fk(e,t){return Object.fromEntries(Object.entries(HT(e)).filter(([e])=>dk.has(e)===t))}const pk=fk(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),mk=[e=>fk(e.now,!0),e=>RO(e.animatedAt),e=>Object.fromEntries(Object.entries(RO(()=>e.now().getTime()/1e3)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),rk];function hk(e){return Object.assign({},...e.map(e=>e(uk)))}const gk=new Set(Object.keys(hk(mk)));function _k(e){return new Set([...gk,...Object.keys(hk(e))])}const vk={readableOn:jO},yk=new Set(Object.keys(vk));function bk(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return sw({fromString:e=>new W(e),toString:e=>e.plain,isT:e=>e instanceof W,missingKey:`error`,funcs:{...XT(),...uO(),...RE(),...oD(),...Mw(),...fE(),...uE(),...pk,...zO(r),...Object.fromEntries(Object.entries(vk).map(([e,t])=>[e,t(r)])),...hk([...mk,...e.clockFuncs??[]]),...tk(),...ik(),...n??{}}})}function xk(e){return Sk(e,new Set(e.names()),``)}function Sk(e,t,n){return new Proxy(Object.create(null),{has(r,i){if(typeof i!=`string`)return!1;let a=n?`${n}.${i}`:i;if(t.has(a))return!wk(e,a);let o=`${a}.`;for(let e of t)if(e.startsWith(o))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a)){if(e.getKind(a)!==`document`)return e.read(a);let t=e.readDocument(a);return t.kind===`absent`?void 0:Tk(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return Sk(e,t,a)}})}function Ck(e,t){return new Proxy(e,{has:(e,t)=>t===`settings`||Reflect.has(e,t),get:(e,n)=>n===`settings`?t:Reflect.get(e,n)})}function wk(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function Tk(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new eS(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}const Ek=/\r\n|\r|\n/g,Dk=e=>P(e.replace(Ek,` `).trim());function Ok(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?I(`regex no-match`):P(n.replace(Ek,` `))}}const kk=e=>{try{return P(JSON.parse(e))}catch(e){return I(`JSON parse failed: ${e.message}`)}};var Ak=class{running=new Map;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:{kind:`started`,done:this.start(e,t)}}share(e,t){let n=this.running.get(e);return n===void 0?(this.again.add(e),this.start(e,t)):n}start(e,t){let n=this.loop(e,t);return this.running.set(e,n),n}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const jk=[`first`,`period`,`change`,`request`,`supersede`];var Mk=class{tallies=new Map;constructor(e=Me){this.logger=e}declare(e){let t=`${e.scope}/${e.name}`,n=this.tallies.get(t)??{name:e.name,scope:e.scope,refreshes:{},failures:0,lastMs:null};for(let t of e.refresh)n.refreshes[t]??=0;return this.tallies.set(t,n),new Pk(n,this.logger)}snapshot(){return[...this.tallies.entries()].sort(([e],[t])=>e<t?-1:+(e>t)).map(([,e])=>({...e,refreshes:{...e.refreshes}}))}totals(){let e=Object.fromEntries(jk.map(e=>[e,0]));for(let t of this.tallies.values())for(let n of jk)e[n]+=t.refreshes[n]??0;return e}};const Nk={first:!0,period:!0,change:!0,request:!1,supersede:!0};var Pk=class{constructor(e,t){this.tally=e,this.logger=t}record(){return{...this.tally,refreshes:{...this.tally.refreshes}}}recorded(e,t,n,r){this.tally.refreshes[t]=(this.tally.refreshes[t]??0)+1,this.tally.lastMs=r,n.kind===`failed`&&this.tally.failures++;let i=n.kind===`failed`;if(!i&&!Nk[t])return;let a=i?` reason=${JSON.stringify(n.reason)}`:``;this.logger(i?`warn`:`info`,`${this.tally.name} refresh ${e} by=${t} outcome=${n.kind}${a} took=${r}ms`)}};function Fk(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(E(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function Ik(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const Lk=`session.id`;function Rk(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await pt({bin:`/bin/sh`,args:[`-c`,e],cwd:t,category:`user-shell`,signal:n});if(!r.ok&&r.reason===`aborted`)throw n.reason;return r.ok?P(r.stdout):I(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function zk(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await pe(e,{encoding:`utf8`,signal:n});return P(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return I(`file unreadable: ${e}`)}}}}function Bk(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?I(`${r.reason} in ${n}`):r}function Vk(e){switch(e.kind){case`never`:return[`first`];case`ttl`:return[`first`,`period`];case`watch_file`:case`key`:case`depends_on`:return[`first`,`change`]}}function Hk(e){let t=!1;return()=>{e(`new-key`,t?`change`:`first`),t=!0}}function Uk(e){try{return b(e)}catch{return e}}function Wk(e){try{return ee(e).isDirectory()}catch{return!1}}function Gk(e){let t=Uk(e);return Wk(t)?{dir:t,name:null,leaf:!0}:Gx(t)}const Kk=e=>`${e.dir}\0${e.name??``}`;var qk=class{watchers=new Map;subscribe(e,t,n){let r=this.watchers.get(e)??this.arm(e);return r.subscribers.set(t,n),r.watcher===null&&n(r.failure),()=>this.unsubscribe(e,t)}arm(e){let t={watcher:null,failure:``,target:Gk(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=Gk(e);if(t.watcher!==null&&Kk(n)===Kk(t.target))return;let r=this.open(e,t,n);r!==null&&(t.watcher?.close(),t.watcher=r,t.target=n)}open(e,t,n){let{dir:r,name:i}=n,a=s.basename(r);try{return x(r,(n,r)=>{if(!(r===null||i===null||r===i)&&r!==a)return;let o=t.target.leaf;if(this.rearm(e,t),!(!o&&!t.target.leaf))for(let e of t.subscribers.keys())e()})}catch(n){let i=`watch_file ${e}: cannot watch ${r} — ${n instanceof Error?n.message:String(n)}`;t.failure=i;for(let e of t.subscribers.values())e(i);return null}}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.watcher?.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e?.close();this.watchers.clear()}size(){return this.watchers.size}},Jk=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:ve(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(ge(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())ge(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};const Yk={read:()=>Oa,drawnAt:()=>{throw new eS(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}};function Xk(e,t){let n=e;for(let e of t.split(`.`)){if(n===Oa)return Oa;if(typeof n!=`object`||!n)return;n=n[e]}return n}function Zk(e,t){if(t===Oa)return Oa;if(t===void 0)return I(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the preset reads`);switch(typeof t==`object`&&t?t.kind:void 0){case`ok`:case`absent`:case`failed`:return t;default:return I(`variable "${e}": the view's payload holds no source reading at "${e}"`)}}function Qk(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?Zx(e):t===`number`?Qx(e):$x(e)}function $k(e){return e===`number`?0:e===`boolean`?!1:``}var eA=class e{lastErrors=new Map;policyFaults=J.observable.map(void 0,{deep:!1});watchMgr=new qk;ttlMgr=new Jk;cleanups=[];runs=new Map;newKeys=J.observable.set();reads=new Ak;askedBy=new Map;abort=new AbortController;inputs=J.observable.box(Yk,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=bk({drawnAt:this.drawnAt});sourceNames=J.observable.array([],{deep:!1});publishedNow=(0,J.computed)(()=>({values:this.sourceNames.map(e=>this.store.stored(e)),faults:[...this.policyFaults.values()]}));published(){return this.publishedNow.get()}sessionState;constructor(e,t=``,n,r=null,i=new Mk){this.store=e,this.defaultEmptyValue=t,this.parent=r,this.ledger=i,this.sessionState=n}view(){return new e(new mS(this.store),this.defaultEmptyValue,this.sessionState,this,this.ledger)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Xx(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,I(t))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>Zk(e,this.inputs.get().read(e)))}own(e){this.cleanups.push(e)}declareInput(e,t,n,r,i){this.store.defineDerived(e,n,i,()=>this.inputAt(e,t,n,r))}inputAt(e,t,n,r){let i=this.inputs.get().read(t);if(i===Oa)throw this.lastErrors.delete(e),new eS(e,`variable "${e}" has no value yet: its source has not answered`);if(i===void 0)return this.fallbackOf(e,n,r,`input path "${t}" not found in payload`);try{let t=Qk(i,n);return this.lastErrors.delete(e),t}catch(t){return this.fallbackOf(e,n,r,t instanceof Error?t.message:String(t))}}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,Rk(t,n.cwd,this.abort.signal),Fk(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,zk(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where);(0,J.runInAction)(()=>this.sourceNames.push(e));let a=this.ledger.declare({name:`var.${e}`,scope:this.parent===null?`directory`:`view`,refresh:Vk(n)});this.registerCachePolicy(e,n,(n,r)=>this.runSource(e,t,i,n,r,a))}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,Dk,t.default,n);case`regex`:return this.scalarPublisher(e,Ok(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=Bk(n,t,r);return this.noteOutcome(e,a),this.store.setBox(e,Da(a,i)),a}}documentPublisher(e,t,n){let r=t===void 0?Oa:P(t);this.store.defineDocument(e,r);let i,a=!1;return this.cleanups.push(()=>clearTimeout(i)),o=>{clearTimeout(i);let s=o.kind===`ok`&&o.value.trim()===``?F:o,c=Bk(s,kk,n);this.noteOutcome(e,c);let l=c.kind===`ok`||s.kind===`ok`||t===void 0?c:r,u=a&&s.kind===`ok`&&c.kind!==`ok`,d=()=>{a=c.kind===`ok`,this.store.setDocument(e,l)};return u?i=setTimeout(d,250):d(),c}}runSource(e,t,n,r,i,a){this.askedBy.set(e,i);let o=this.reads.run(e,()=>{let r=this.askedBy.get(e)??i,o=Date.now();return t.read().then(e=>a.recorded(`where=${as(t.where)}`,r,n(e),Date.now()-o),e=>{if(e!==this.abort.signal.reason)throw e})});this.track(e,o,r)}track(e,t,n){if((0,J.runInAction)(()=>{t.kind===`started`&&(this.runs.set(e,t.done),this.newKeys.delete(e)),n===`new-key`&&this.newKeys.add(e)}),t.kind===`queued`)return;let r=t.done;r.finally(()=>(0,J.runInAction)(()=>{this.runs.get(e)===r&&(this.runs.delete(e),this.newKeys.delete(e))}))}async inFlight(e){try{await(0,J.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}}awaited(){return[...this.newKeys,...this.parent?.awaited()??[]]}async settled(e){return await this.inFlight(AbortSignal.timeout(e)),this.awaited()}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(xk(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){let n=this.engine.parse(`{{ date .layout now }}`),r={layout:t.format};this.declareDerived(e,`string`,`projection`,()=>n.evaluate(r).map(e=>e.plain).join(``),t.varDefault)}declareDerived(e,t,n,r,i){this.store.defineDerived(e,t,n,()=>{try{let n=Qk(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=tS(t);if(n!==void 0)throw this.lastErrors.delete(e),n;let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),i===void 0)throw Error(`variable "${e}": ${r}`);return i}})}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(Lk);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}stateRevision(){let e=this.store.has(`session.id`)?this.store.read(Lk):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}bindInputs(e){(0,J.runInAction)(()=>this.inputs.set(e))}getLastError(e){if(!this.declaredHere(e))return this.parent?.getLastError(e);let t=this.lastErrors.get(e),n=this.policyFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){return new Map([...this.parent?.cachePolicyFaults()??[],...this.policyFaults])}declaredHere(e){return this.store.has(e)&&!(this.parent?.store.has(e)??!1)}dispose(){this.abort.abort();for(let e of this.cleanups)e();return this.cleanups.length=0,this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:n(`new-key`,`first`);break;case`ttl`:{n(`new-key`,`first`);let e=this.ttlMgr.subscribe(t.durationMs,()=>n(`re-read`,`period`));this.cleanups.push(e);break}case`watch_file`:{n(`new-key`,`first`);let r=this.watchMgr.subscribe(t.path,()=>n(`re-read`,`change`),t=>this.notePolicy(e,I(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template);this.onReads(e,()=>{try{return P(r.evaluate(xk(this.store)).map(e=>e.plain).join(``))}catch(e){return tS(e)===void 0?I(`cache key: ${e instanceof Error?e.message:String(e)}`):Oa}},Hk(n));break}case`depends_on`:this.onReads(e,()=>{let e=t.varNames.map(e=>this.store.changeKey(e));return e.every(e=>e.kind===`ok`)?P(e.map(e=>e.value).join(`,`)):Oa},Hk(n));break}}onReads(e,t,n){let r,i=(0,J.reaction)(t,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===r)&&(r=t.value,n())},{fireImmediately:!0});this.cleanups.push(i)}fallbackOf(e,t,n,r){if(this.recordError(e,r),n!==void 0)return n;try{return Qk(this.defaultEmptyValue,t)}catch{return $k(t)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}notePolicy(e,t){(0,J.runInAction)(()=>{t.kind===`failed`?this.policyFaults.get(e)?.message!==t.reason&&this.policyFaults.set(e,{timestamp:Date.now(),message:t.reason}):this.policyFaults.delete(e)})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function tA(e,t){let n=dy[e],r=yy(e),i=n.kind===`session`||n.kind===`config`?n.floor:``;return r===`string`?{kind:`input`,path:t,default:``}:{kind:`input`,path:t,type:r,default:i}}const nA=Object.fromEntries([...Dy].map(([e,t])=>[t,tA(e,t)])),rA={subscribers:`number`,fps:`number`,shown:`boolean`},iA=Object.keys(rA),aA={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[Lk]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`,default:``},config_path:{kind:`input`,path:`configPath`,default:``},...nA,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(Fv.flatMap(e=>iA.map(t=>[zv(e,t),{kind:`input`,path:zv(e,t),type:rA[t],default:Rv[t]}]))),[Lv(`by`)]:{kind:`input`,path:Lv(`by`),default:Iv.by},[Lv(`fps`)]:{kind:`input`,path:Lv(`fps`),type:`number`,default:0},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"tmux.pane":{kind:`input`,path:`tmux.pane`,default:``},"autocompact.window":{kind:`input`,path:`autocompact.window`,type:`number`,default:-1},...Object.fromEntries([`applied`,`lower`,`higher`].map(e=>[`autocompact.${e}`,{kind:`input`,path:`autocompact.${e}`,type:`number`,default:0}])),"autocompact.error":{kind:`input`,path:`autocompact.error`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},oA={today:`the day the draw is at`,feeds:`the frames a lane was sent up to the draw's instant`,drawing:`who the draw is for`};function sA(e){let t=e.split(`.`,1)[0];return Object.hasOwn(oA,t)?t:void 0}const cA=Object.fromEntries(Ug.map(e=>[e,Dy.get(e)]));function lA(e){return Ug.find(t=>cA[t]===e)}const uA=`ne .tmux.pane ""`;function dA(e,t,n){let r=new Set,i=e=>{for(let t of Ox(e??``,n).keys())r.add(t)};for(let t of Object.values(e.segments))i(t.template),i(t.bg),i(t.fg),i(t.when);for(let e of t)for(let t of E_(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(Lk);for(let t of Object.values(e.actions)){r.add(Lk);for(let[,e]of mx(t))i(e);let e=`set`in t?Oy.get(t.set):void 0,n=`persist`in t?Dy.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function fA(e,t,n){let r=Ux({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of dA(e,t,n.helpers)){if(Hx(a,r))continue;let e=aA[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function pA(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const mA=`groups.`,hA=`menus.`,gA=`menupages.`,_A=`edit.`,X=`candybar.`,vA=[mA,hA,gA,_A,X];function yA(e){return vA.some(t=>e.startsWith(t))}function bA(e){let t=pA(e);return vA.find(e=>t.startsWith(pA(e)))}function xA(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:G(e.source,[`root`])})}function SA(e){return e}function CA(e,t,n){return n===void 0?hA+pA(e)+`.`+pA(t):wA(n)}function wA(e){return hA+pA(e)}function TA(e,t){return e+`.`+t}function EA(e){return gA+e}const DA=[`closeOnPick`,`paged`,`key`,`distribution`],OA=e=>DA.includes(e),kA=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${Eh.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function AA(e){for(let t of Object.keys(e))if(!OA(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${kA}`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);let r=e.distribution;if(r!==void 0&&!Dh(r))throw Error(`{{ menu }} option "distribution" must be one of: ${Eh.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:kh(r)}}const jA=e=>`from`in e?e.from:e.themes;function MA(e,t,n){return e===`bool`?v_(t)!==null:`min`in e?y_(t,e)!==null:lx(jA(e),n).members.includes(t)}function NA(e,t){if(e===`bool`)return g_.join(` or `);if(!(`min`in e)){let n=jA(e),{members:r}=lx(n,t),i=r.map(e=>JSON.stringify(e));if(r.length<=8)return`one of ${i.join(`, `)}`;let a=typeof n==`string`?` "${n}"`:``;return`one of the ${r.length}${a} names, such as ${i.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function PA(e){return{label:e.label,domain:FA(e.domain)}}function FA(e){return e===`theme`?{themes:ox}:e===`bool`||`min`in e?e:{from:e}}function IA(e,t,n,r,i){let a=Ci(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...g_]}},variables:{}};if(`from`in o)return LA(t,r,i,o.from,e=>({template:`{{ "${a}" }} {{ carousel "${e.apply}" 0 "${e.open}" }}`,rows:[`{{ picker "${e.apply}" "${e.page}" false true true }}`]}));if(`themes`in o)return LA(t,r,i,o.themes,e=>({template:`{{ action "${e.open}" "${a}" .${n} }} {{ action "${e.open}" (swatch "${e.apply}") }}`,rows:[`{{ swatches "${e.apply}" "${e.page}" }}`,`{{ themePreview "${e.apply}" }}`]}));let s=e=>({set:t,min:o.min,max:o.max,by:e});return{kind:`inline`,template:`{{ action "${r}.down" "◀" }} {{ "${a}" }} {{ .${n} }} {{ action "${r}.up" "▶" }}`,actions:{[`${r}.down`]:s(-o.step),[`${r}.up`]:s(o.step)},variables:{}}}function LA(e,t,n,r,i){let a={variable:n,key:n,member:t},o=TA(n,t),s=`${t}.open`,c=EA(n),l=`${c}.current`,{template:u,rows:d}=i({apply:t,open:s,page:c});return{kind:`picker`,template:u,actions:{[t]:{set:e,from:r},[o]:N(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:Ai(n,yi),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const RA=Object.fromEntries(Object.entries(dy).map(([e,t])=>[e,t.spec]));function zA(e){return dy[e].domain}function BA(e,t){return{required:!1,json:{not:{},description:`not allowed here — ${e}`},parse:(e,n,r,i)=>{i[r]!==void 0&&e.issues.push({path:`${n}.${r}`,message:t(`${n}.${r}`),line:G(e.source,[...n.split(`.`),r])})}}}function VA(e){return BA(`${e} cannot select a preset`,t=>`${t}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`)}function HA(e){return BA(`${e} cannot change the settings menu glyph`,t=>`${t}: ${e} cannot change the settings menu glyph — one menu is shared by every preset. Set it in the top-level globals.menuGlyph instead.`)}function UA(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Wg(s)){r.issues.push({path:`${i}.${a}`,message:`${i}.${a}: a rule is not allowed here — ${t} ${n}, so it names a value. Write the rule in globals.${a} (or a preset's globals.${a}) instead.`,line:G(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const WA={default_bg:"nothing reads it — a segment with no `bg:` wears the decoration tint of its place in the bar. Delete the key, and author `bg:` on the segments that need a fixed colour.",default_fg:"nothing reads it — a segment with no `fg:` wears text chosen for contrast against its background. Delete the key, and author `fg:` on the segments that need a fixed colour.",default_truncate_marker:'nothing reads it — a segment clipped to its `width:` always ends in "…". Delete the key.',look:`it was renamed "style" — write the same name as style: "<name>"`,progression:`it was renamed "variation", and its values with it: accent (was secondary-accent), duo (was primary-secondary), mono (was primary)`,charset:"the bar always draws Nerd Font glyphs. Delete the key; `cc-candybar doctor` names what your terminal's font is missing."},GA={noun:`globals key`,fields:RA,removed:WA},KA={preset:VA(`a preset`),menuGlyph:HA(`a preset`)},qA={noun:`preset globals key`,fields:{...RA,...KA},removed:WA};function JA(e){return ij(e)&&!(e in KA)}const YA=`is decided later than any rule could be settled`,XA={noun:`editGlobals key`,removed:WA,fields:{...RA,preset:VA(`the editGlobals fragment`),menuGlyph:HA(`the editGlobals fragment`),palette:UA(RA.palette,`the editGlobals fragment`,YA),style:UA(RA.style,`the editGlobals fragment`,YA),effect:UA(RA.effect,`the editGlobals fragment`,YA)}},ZA={noun:`theme default key`,fields:{...Object.fromEntries(hy.map(e=>[e,RA[e]])),style:UA(RA.style,`a theme's default`,`is the look that theme wears by name`)}};function QA(e,t){if(!sv(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${cv(t)}`,line:G(e.source,[`themeDefaults`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=`themeDefaults.${r}`;if(!e.allowedPalettes.has(r)){e.issues.push({path:t,message:`${t}: "${r}" is not an installed theme${Fg(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:G(e.source,[`themeDefaults`,r])});continue}let a=lv(e,ZA,t,i);a!==null&&(n[r]=a)}return n}function $A(e,t,n){return n===void 0?{}:lv(e,GA,t,n)??{}}function ej(e,t,n){return lv(e,qA,t,n)??{}}function tj(){return Av(qA)}function nj(e,t,n){return lv(e,XA,t,n)??{}}const rj=new Set(Object.keys(RA));function ij(e){return rj.has(e)}function aj(e){return Object.hasOwn(WA,e)?WA[e]:void 0}function oj(){return[...rj]}const sj=new Map(Object.entries(dy).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function cj(e){let t=new Map;for(let[n,r]of sj){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const lj=/^segments\.([^.]+)\.palette$/,uj=/^presets\.(.+)\.root$/,dj=/^presets\.(.+)\.globals\.([^.]+)$/,fj=/^themeDefaults\.(.+)\.([^.]+)$/;function pj(e){return`presets.${e}.root`}function mj(e,t){return`themeDefaults.${e}.${t}`}const hj=e=>hy.includes(e);function gj(e,t){return`presets.${e}.globals.${t}`}function _j(e){if(ij(e))return{scope:`globals`,field:e};let t=lj.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=dj.exec(e);if(n&&JA(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=fj.exec(e);if(r&&hj(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=uj.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function vj(e){switch(e.scope){case`globals`:return[`globals`,e.field];case`preset-globals`:return[`presets`,e.preset,`globals`,e.field];case`segment-palette`:return[`segments`,e.segment,`palette`];case`theme-default`:return[`themeDefaults`,e.theme,e.field]}}const yj=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],bj=[...yj,`other`],xj={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},Sj=sw({fromString:e=>e}),Cj=`${X}menu`,wj=`open`,Tj={variable:Cj,key:Cj,member:wj},Ej=`edit.mode`,Dj=`edit.configure`,Oj=`edit.toggle`,kj=`arrange`,Aj=`${_A}draft.`;function jj(e,t){return`${e}:${t}`}const Mj={variable:Ej,key:Ej,member:kj},Nj=Ti(Mj);function Pj(e){try{return Sj.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function Fj(e){if(Object.values(e.actions??{}).some(e=>`do`in e&&e.do.includes(`edit.toggle`)))return!0;for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&Pj(e))return!0;return!1}function Ij(e,t){if(xA(e,t,_A,`edit mode`),!Fj(t))return;let{variables:n,actions:r}=Lj();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function Lj(){return{variables:{[Ej]:{...Ai(Ej,yi),within:[Tj]},[Dj]:{...Ai(Dj,yi),within:[Mj]}},actions:{[Oj]:N(Ej,kj),"edit.unconfigure":{set:Dj,to:yi}}}}const Rj=`open`;function zj(e,t,n,r){let i={variable:e,key:e,member:Rj};return r.variables[e]={...Ai(e,yi),...n.length>0&&{within:n}},r.actions[e]=N(e,Rj),r.segments[e]={template:Di(e,`(?)`,`✕`),...Bj(n)},wi(e,i,{kind:`container`,direction:`horizontal`,children:t.map((t,n)=>{let i=`${e}.${n}`;return r.segments[i]={template:t},{kind:`segment`,name:i}})},`drop`)}function Bj(e){let[t,...n]=e;return t===void 0?{}:{when:Ti(t,...n)}}const Vj=`none`;function Hj(e){return El(e,`background`)}var Uj=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function Wj(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=Gj(n,i),l=c!==Vj,u=l?c===void 0?o:Kj(a,c,`bg`):Hj(a);e.bg=u;let d=Gj(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:Xh(a,e,t))(u):void 0:Kj(a,d,`fg`);return new V({...l&&{bgcolor:z.fromRgba(u)},...f!==void 0&&{color:z.fromRgba(f)}})}function Gj(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function Kj(e,t,n){try{return El(e,t)}catch(e){throw e instanceof Tl?new Uj(t,n,e.message):e}}const qj=`🔧`,Jj={help:[`-h`,`--help`],version:[`-V`,`--version`]},Yj=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],Xj=Object.fromEntries(Yj.map(e=>[e.member,e.label])),Zj={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},Qj=Object.keys(Zj),$j=ky(e=>Sy[e].place),eM=e=>Object.hasOwn(Zj,e),tM=(e,t)=>e===t||eM(e)&&tM($j[Zj[e].beside],t),nM=e=>eM(e)?`${nM($j[Zj[e].beside])} › ${Zj[e].trigger}`:e===`door`?`first line`:Xj[e],rM=e=>nM($j[e]),iM=()=>[`door`,...Yj.map(e=>e.member)].flatMap(e=>[e,...Qj.filter(t=>tM(t,e))]).map(e=>({path:nM(e),names:Cy.filter(t=>$j[t]===e)})).filter(({names:e})=>e.length>0),aM=e=>`${Pv[e].label} is off — turn it on in the settings menu's ${rM(Pv[e].setting)}, or set globals.${Pv[e].setting}: true`,oM=[...new Set(Object.values(Pv).map(e=>rM(e.setting)))].join(` or `),sM=Math.max(...Object.values(Sy).map(e=>e.configKey.length))+2,cM=[`✚ inserts`,`✖ removes`,`${qj} configures`,`↺ resets layout`],lM={band:[`animates the bar in the band above the prompt, through a Claude Code mod`,`on: installs the candybar-band mod from this checkout and types /reload-plugins`],statusline:[`animates the statusline itself, through the attach launcher shipped with cc-candybar`,`on: exits this Claude Code and starts it again under that launcher, on this session`,`or start one yourself: cc-candybar --help prints the line to type`],pane:[`animates the bar in a tmux pane under this session's`,`on: opens that pane · off: closes it`],tmuxStatus:[`animates the bar in the tmux status line, while this session's pane is the one it shows`,`on: the daemon draws it there · off: puts the status line back as it was`]},uM=`
73
73
  cc-candybar - Beautiful powerline statusline for Claude Code
74
74
 
75
75
  Usage: cc-candybar [options]
76
76
 
77
77
  Standalone Commands:
78
- ${qj.help.join(`, `).padEnd(25)}Show this help
79
- ${qj.version.join(`, `).padEnd(25)}Print the version of this runtime (cc-candybar <version>)
78
+ ${Jj.help.join(`, `).padEnd(25)}Show this help
79
+ ${Jj.version.join(`, `).padEnd(25)}Print the version of this runtime (cc-candybar <version>)
80
80
 
81
81
  Debugging:
82
82
  CC_CANDYBAR_DEBUG=1 Enable debug logging for troubleshooting
@@ -93,21 +93,21 @@ Configuration:
93
93
  the settings listed below, its first line holds ◁ back, ✎ arrange (edit mode)
94
94
  and 💾 save, which appears while you have unsaved changes and writes them to
95
95
  your config file. Under it are its
96
- tabs, ${Jj.map(e=>e.label).join(`, `)};
97
- ${Yj.session} holds quick actions and commands, ${Yj.layout} a new preset.
96
+ tabs, ${Yj.map(e=>e.label).join(`, `)};
97
+ ${Xj.session} holds quick actions and commands, ${Xj.layout} a new preset.
98
98
  A change applies to this session at once.
99
99
  Where each setting is in the menu: the globals field that sets it in a
100
100
  config file, then the control's label.
101
- ${rM().flatMap(({path:e,names:t})=>[` ${e}`,...t.map(e=>` ${Sy[e].configKey.padEnd(oM)}${Sy[e].label}`)]).join(`
101
+ ${iM().flatMap(({path:e,names:t})=>[` ${e}`,...t.map(e=>` ${Sy[e].configKey.padEnd(sM)}${Sy[e].label}`)]).join(`
102
102
  `)}
103
103
  The 🧰 tools tab holds 🩺 doctor: click it to check your setup, and click a
104
104
  failed row's [fix] to repair it (the same checks \`cc-candybar doctor\` runs).
105
105
 
106
106
  Anywhere the bar shows (?), clicking it reveals these same instructions
107
- in place. In edit mode: ${sM.join(`, `)}.
107
+ in place. In edit mode: ${cM.join(`, `)}.
108
108
 
109
- Animation lanes (experimental; toggles in the settings menu's ${aM}):
110
- ${Fv.map(e=>` ${Pv[e].label}\n${cM[e].map(e=>` ${e}`).join(`
109
+ Animation lanes (experimental; toggles in the settings menu's ${oM}):
110
+ ${Fv.map(e=>` ${Pv[e].label}\n${lM[e].map(e=>` ${e}`).join(`
111
111
  `)}`).join(`
112
112
  `)}
113
113
 
@@ -141,14 +141,14 @@ Subcommands:
141
141
  ${Fv.join(`, `)}:
142
142
  the experimental lane this stream serves,
143
143
  which streams only while its toggle in the settings
144
- menu's ${aM} is on.
144
+ menu's ${oM} is on.
145
145
  bar-pane PANE Draw the bar of the Claude Code session in tmux
146
146
  pane PANE (e.g. %3) in this pane, as the daemon
147
147
  pushes it, while this pane is shown. The bar is
148
148
  drawn at PANE's width, so split PANE with -v for a
149
149
  pane under it that fits. Experimental:
150
150
  runs while ${Pv.pane.label} is on in the settings
151
- menu's ${nM(Pv.pane.setting)}.
151
+ menu's ${rM(Pv.pane.setting)}.
152
152
 
153
153
  Config tooling:
154
154
  doctor [file] Check your setup the way the bar's 🩺 doctor does —
@@ -174,31 +174,31 @@ Config tooling:
174
174
  config [--json] The effective merged config. (All three query the
175
175
  running daemon; none spawn one.)
176
176
 
177
- `,uM=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`,dM={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function fM(e){let t=e[dM.socket]??``,n=e[dM.pane]??``;if(t===``||n===``)return null;let r=e[dM.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const pM=[`moves`,`can-move`,`still`];function mM(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const hM=[`carried`,`missing`,`unanswered`];function gM(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:mM(e)===`no`?`unanswered`:`missing`}function _M(e){return{path:e.transcript_path,answered:mM(e)===`yes`}}const vM=[...pM,`failed`,`drawing`],yM=[`statusline`,`frames`],bM=e=>e?.kind===`frames`?`frames`:`statusline`;var xM=class{seen=new Map;see(e,t,n,r){let i=bM(t.client),a=JSON.stringify([e,i]),o=this.seen.get(a);o!==void 0&&o.order>r||(this.seen.delete(a),this.seen.set(a,{sessionId:e,said:{...t,role:i},at:n,order:r}),this.seen.size>64&&this.seen.delete(this.seen.keys().next().value))}list(e){return[...this.seen.values()].map(({sessionId:t,said:n,at:r})=>({...n,sessionId:t,ago:e-r}))}ofSession(e,t){return this.list(t).filter(t=>t.sessionId===e)}};const SM={kitty:{label:`kitty`,xtversion:`kitty`,program:null,programVersion:!0,term:`xterm-kitty`,links:{since:`0.19.0`},glyphs:{kind:`bundled`,since:`0.36.0`}},wezterm:{label:`WezTerm`,xtversion:`WezTerm`,program:`WezTerm`,programVersion:!0,term:`wezterm`,links:{since:null},glyphs:{kind:`bundled`,since:`20230712`}},ghostty:{label:`Ghostty`,xtversion:`ghostty`,program:`ghostty`,programVersion:!0,term:`xterm-ghostty`,links:{since:null},glyphs:{kind:`bundled`,since:null}},iterm2:{label:`iTerm2`,xtversion:`iTerm2`,program:`iTerm.app`,programVersion:!0,term:null,links:{since:`3.1`},glyphs:{kind:`configured`}},alacritty:{label:`Alacritty`,xtversion:`alacritty`,program:null,programVersion:!0,term:`alacritty`,links:{since:`0.11.0`},glyphs:{kind:`configured`}},"apple-terminal":{label:`Terminal`,xtversion:null,program:`Apple_Terminal`,programVersion:!0,term:null,links:null,glyphs:{kind:`unread`}},vscode:{label:`VS Code`,xtversion:null,program:`vscode`,programVersion:!1,term:null,links:{since:`1.72`},glyphs:{kind:`unread`}}},CM=e=>SM[e];function wM(e){return CM(e).glyphs.kind===`bundled`}function TM(e){return CM(e).glyphs.kind===`configured`}const EM=e=>CM(e).label,DM=[{since:`3.5.0`,from:57504,to:57507},{since:`3.5.0`,from:57520,to:57554},{since:`3.5.0`,from:57556,to:57556},{since:`3.5.6`,from:57558,to:57559}];function OM(e,t){let n=t.codePointAt(0);return DM.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&jM(e,t)===!0)}const kM=Object.keys(SM);function AM(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function jM(e,t){let n=AM(e),r=AM(t);if(n===null)return null;for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t>i}return!0}function MM(e){for(let t of kM){let n=CM(t).xtversion;if(n!==null&&e.toLowerCase().startsWith(n.toLowerCase())){let r=e.slice(n.length).replace(/^[\s(]+/,``);return{name:t,version:/^[^\s)]+/.exec(r)?.[0]??null}}}return null}function NM(e){let t=kM.find(t=>CM(t).term===e);return t===void 0?null:{name:t,version:null}}function PM(e){let t=MM(e.termtype)??NM(e.termname);if(t!==null)return{kind:`known`,terminal:t};let n=/^[^\s(]*/.exec(e.termtype)[0];return n===``?{kind:`unnamed`,term:e.termname}:{kind:`unknown`,called:n}}function FM(e){let t=e.TERM_PROGRAM,n=kM.find(e=>CM(e).program===t),r=n===void 0?NM(e.TERM):{name:n,version:CM(n).programVersion?e.TERM_PROGRAM_VERSION??null:null};return r===null?t===void 0||t===`tmux`?{kind:`unnamed`,term:e.TERM??``}:{kind:`unknown`,called:t}:{kind:`known`,terminal:r}}function IM(e){switch(e.kind){case`known`:return EM(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function LM(e){switch(e.kind){case`known`:return EM(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function RM({name:e,version:t}){let n=CM(e).links;if(n===null)return{kind:`none`};if(n.since===null)return{kind:`draws`};if(t===null)return{kind:`unsaid`,since:n.since};let r=jM(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const zM=kM.filter(e=>CM(e).links!==null).map(EM).join(`, `);function BM(e){if(e.kind===`failed`)return{kind:`unread`,reason:e.reason};let t=e.value.flatMap(({scope:e,path:t,settings:n})=>`statusLine`in n?[{from:{scope:e,path:t},line:n.statusLine}]:[]),n=t[0];if(n===void 0)return{kind:`absent`,read:e.value.map(e=>e.path)};if(!oo(n.line))return{kind:`not-an-object`,value:n.line,from:n.from};for(let{from:e,line:r}of t){if(e.scope!==n.from.scope||!oo(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function VM(e,t){if(e.kind===`failed`)return e;let n=e.value.find(e=>Object.hasOwn(e.env,t));return{kind:`ok`,value:n===void 0?{kind:`unset`}:{kind:`set`,value:n.env[t],from:{scope:n.scope,path:n.path}}}}const HM=[`managed`,`project`],UM=e=>!HM.includes(e.scope),WM={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:ro(t.projectDir)}),user:e=>({scope:`user`,path:e})},GM=[`drawn`,`boxes`],KM=1024*1024,qM=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function JM(e){switch(e.kind){case`claude-settings`:return`${e.kind} ${e.path.join(`.`)}=${JSON.stringify(e.value)} file=${JSON.stringify(e.file.path)} scope=${e.file.scope}`;case`post-mortems-read`:return`${e.kind} through=${e.through}`}}function YM(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const XM=dM.truecolor;function ZM(e,t){switch(e.kind){case`unreported`:return{ok:!1,reason:"the client reported no tmux facts — re-run `cc-candybar install` to stage a current client"};case`outside`:return{ok:!0};case`inside`:return e.client.kind===`failed`?{ok:!1,reason:`tmux could not be asked: ${e.client.reason}`}:e.client.value===null?{ok:!0}:t(e.client.value,e.hint)}}const QM={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>ZM(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=VM(t.sources,XM);if(r.kind===`failed`)return{ok:!1,reason:r.reason};let i=r.value;if(i.kind===`set`&&typeof i.value==`string`&&i.value!==``)return{ok:!1,reason:`${XM} is set in ${i.from.path} — restart Claude Code to apply`};let a=`Claude Code renders the bar in 256 colours inside tmux`,o=e=>({ok:!1,reason:a,fix:{kind:`claude-settings`,file:e,path:[`env`,XM],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=WM[i.from.scope](i.from.path,t.at);return s===null?{ok:!1,reason:`${a} — the value that counts is in managed settings, ${i.from.path}: set ${XM} to "1" there`}:o(s)})},$M={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>ZM(e,e=>e.utf8?{ok:!0}:{ok:!1,reason:"tmux draws this terminal without UTF-8, so every glyph on the bar arrives as `_` — attach with `tmux -u`, or set a UTF-8 LC_ALL/LC_CTYPE/LANG in the shell that runs tmux"})},eN={name:`termWidth`,label:`terminal width`,takesMark:!1,probe:({width:e})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.columns===null?{ok:!1,reason:`${qM(e.value.of)} measured no width (no COLUMNS, and no terminal to ask — or the daemon refused the width sent, which the bar's red strip names), so the bar is laid out as if the terminal were 120 columns wide`}:{ok:!0,note:`${e.value.columns} columns, as ${qM(e.value.of)} measured`}},tN={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},nN={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{switch(e.kind){case`failed`:{let[t=`the config failed to load`,...n]=[...e.error.split(`
178
- `).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return YM([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${tN[e]}`)])}}},rN="re-run `cc-candybar install`";function iN(e){if(e.kind===`failed`)return[`Launch Services could not be asked which app opens cc-candybar:// — ${e.reason}`];if(e.value===null)return[`no app is registered for cc-candybar:// — ${rN}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${rN}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${rN}`)}const aN={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${rN}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${rN}`};case`lost`:return YM([...iN(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}};function oN({bundle:e,checkout:t},n){return{bundle:n.bundle.kind===`failed`?{kind:`unresolved`,reason:n.bundle.reason}:n.bundle.value===e?{kind:`same`}:{kind:`other`,path:n.bundle.value},source:n.client!==`native`||t===null?{kind:`uncompared`}:t.rustSource.kind===`failed`?{kind:`unreadable`,root:t.root,reason:t.rustSource.reason}:n.source===null?{kind:`unstamped`}:n.source===t.rustSource.value?{kind:`same`}:{kind:`other`,root:t.root}}}function sN(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${Fv.join(`|`)}>\``:e.checkout===null?rN:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function cN(e,t,n){let{checkout:r}=e;if(n.kind===`unreported`)return[`the bar is drawn by a statusline client too old to say what it is — ${sN(e,`native`)}`];let{bundle:i,source:a}=oN(e,n);switch(i.kind){case`unresolved`:return[`the statusline client's bundle cannot be resolved: ${i.reason}`];case`other`:return[`the statusline client runs ${i.path}, not the daemon's ${e.bundle} — ${sN(e,n.client)}`];case`same`:break}if(n.client===`node`&&(t||r!==null))return[`the bar is drawn by the Node fallback, which starts node on every render — ${sN(e,`native`)}`];switch(a.kind){case`uncompared`:case`same`:return[];case`unreadable`:return[`${a.root}/rust-client could not be read: ${a.reason}`];case`unstamped`:return["the native client carries no source stamp, so which source it was built from is unknown — run `just install-rust`"];case`other`:return[`the native client was built from other source than ${a.root}/rust-client holds — run \`just install-rust\``]}}const lN=e=>{let t=`restarted since the bar was drawn, or has served 64 newer sessions`;return e.kind===`clicked`?`this daemon holds no render of this bar (it ${t})`:`this daemon holds no render of session ${e.sessionId}'s bar (its statusLine does not run cc-candybar — a \`claude -p\` session draws none — or the daemon ${t}; unset CLAUDE_CODE_SESSION_ID to judge every bar drawn recently)`},uN={name:`install`,label:`install`,takesMark:!1,probe:({install:e,sighted:t})=>{if(e.kind===`failed`)return{ok:!1,reason:`the daemon could not be asked which clients draw the bar: ${e.reason}`};let{daemon:n,nativeShipped:r,clients:i}=e.value;return i.length===0?{ok:!1,reason:t.kind===`recent`?`no statusline client has drawn a bar for this daemon in the last ${300/60} minutes — run the doctor again once the bar has redrawn; if it never does, the statusLine command does not run cc-candybar`:`${lN(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:YM([...new Set(i.flatMap(e=>cN(n,r,e)))])}};function dN({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||ir(e.identity,t.value.through)):[]}function fN(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const pN={name:`daemon`,label:`daemon`,takesMark:!1,probe:({daemon:{serving:e,processes:t,read:n}})=>{let r=t.kind===`failed`?[`the process table could not be read: ${t.reason}`]:[],i=t.kind===`ok`?fN(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return YM([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=dN(e.value,n),u=YM([...l.map(e=>`the daemon ran out of memory and restarted (${e.identity}) — post-mortem: ${Object.values(e.artifacts).join(`, `)}`),...c.kind===`failed`?[`the daemon's post-mortems could not be listed: ${c.reason}`]:[],...n.kind===`failed`&&!(c.kind===`ok`&&c.value.length===0)?[`which post-mortems were read could not be read: ${n.reason}`]:[],...r,...i.map(e=>`daemon ${e.pid} (started ${e.started}, rss ${tr(e.rss)} MB${e.ppid===1?``:`, child of ${e.ppid}`}) runs beside the one serving the bar (${a}) — \`kill ${e.pid}\``),...o.kind===`measured`&&o.charge.kind===`stand-in`?[`the daemon could not read what macOS charges it (${o.charge.unread}), so its memory limit judges ${o.charge.gap===0?`RSS, which counts pages macOS has reclaimed`:`RSS less the ${tr(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&sr(o.charge.bytes,s)?[`the daemon holds ${dr(o.charge)} of its ${tr(s)} MB limit — at the limit it records a post-mortem and restarts`]:[]]);if(u.ok&&o.kind===`unmeasured`)return{ok:!0,note:`the daemon has not measured its memory yet`};let d=l[0];return u.ok||d===void 0?u:{...u,fix:{kind:`post-mortems-read`,through:d.identity}}}},mN=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function hN(e,t){let n=IM(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?RM(e.terminal):{kind:`unknown`}}function gN({identified:e,tmuxClient:t},n){let r=LM(e),i=hN(e,n),a=IM(e)===null?mN:`${mN}, and the doctor remembers it for this terminal`,o=(()=>{switch(i.kind){case`draws`:return[];case`none`:return[`${r} draws no links (OSC 8), so nothing on the bar can be clicked — run Claude Code in a terminal that draws them: ${zM}`];case`older`:return[`${r} ${i.version} draws no links (OSC 8 came in ${i.since}) — update ${r}`];case`unsaid`:return[`${r} draws links (OSC 8) since ${i.since}, and did not say which release this is — ${a}`];case`unknown`:return[`the doctor does not know whether ${r} draws links (OSC 8) — ${a}`]}})(),s=n.kind===`failed`&&i.kind!==`draws`?[`the terminals a doctor click came back from could not be read: ${n.reason}`]:[],c=i.kind===`none`||t===null||t.features.includes(`hyperlinks`)?[]:[`tmux does not pass links through to ${r} — add \`set -as terminal-features ",${t.termname}:hyperlinks"\` to tmux.conf, then detach and reattach (tmux 3.4 or later)`];return[...o,...s,...c]}const _N={name:`links`,label:`links`,takesMark:!1,probe:({sighted:e,terminal:t,clicked:n})=>{if(e.kind===`clicked`&&e.via===`link`)return{ok:!0};switch(t.kind){case`unreported`:return{ok:!1,reason:"the client reported no terminal — re-run `cc-candybar install` to stage a current client"};case`unasked`:return{ok:!1,reason:`tmux could not be asked which terminal is attached: ${t.reason}`};case`seen`:return YM(gN(t,n))}}},vN=e=>e.filter(e=>e.role===`statusline`),yN={name:`effectRefresh`,label:`effect refresh`,takesMark:!1,probe:({frames:e,claudeSettings:{origin:t,elsewhere:n},sighted:r})=>{let i=[t,...n].flatMap(({sources:e,bars:t})=>SN(e,bN(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:xN(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:lN(r));let[o,...s]=i.flatMap(e=>e.ok?[]:[e]);if(o===void 0)return a;let c=[...new Set(s.map(e=>e.reason))].filter(e=>e!==o.reason);return c.length===0?o:{...o,more:c}}},bN=e=>{let t=vN(e).map(e=>e.frame);return t.includes(`moves`)?{kind:`moving`,wearing:`the bar moves (an effect, a fade, or an animated segment)`}:t.includes(`can-move`)?{kind:`moving`,wearing:`the bar can start moving (an open menu, which flashes and closes on its own, a globals.effect rule, placements that fade in and out, or a placement with an effect of its own that is not drawn now)`}:t.includes(`still`)?{kind:`still`}:t.includes(`drawing`)?{kind:`unknown`,unseen:`the bar's latest render has not finished`}:t.length>0?{kind:`unknown`,unseen:`the bar's recent renders failed`}:e.length>0?{kind:`unknown`,unseen:"only a `cc-candybar frames` display has drawn this bar, not Claude Code's statusline"}:{kind:`none`}},xN=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function SN(e,t){let n=BM(e);if(n.kind===`present`&&n.refreshInterval===1)return{ok:!0,note:`statusLine.refreshInterval is 1 in ${n.from.path}`};switch(t.kind){case`none`:return null;case`still`:return{ok:!0};case`unknown`:return xN(t.unseen);case`moving`:break}let{wearing:r}=t;switch(n.kind){case`unread`:return{ok:!1,reason:`${r}, and Claude Code's settings could not be read: ${n.reason}`};case`absent`:return{ok:!1,reason:`${r}, and no settings file Claude Code reads here sets a statusLine (read: ${n.read.join(`, `)||`none`}) — the one that runs the bar comes from --settings, MDM or server-managed settings, which the doctor cannot read; set "refreshInterval": 1 beside its command there`};case`not-an-object`:return{ok:!1,reason:`${r}, and ${n.from.path} sets statusLine to ${JSON.stringify(n.value)}, not a statusLine object — ${n.from.scope===`user`?"re-run `cc-candybar install` to write one":`replace it there with the statusLine object that runs cc-candybar`}`};case`present`:{let{from:e,refreshInterval:t}=n,i=t===void 0?`its statusLine sets no refreshInterval, so Claude Code redraws it only on events`:typeof t==`number`&&t>1?`its statusLine redraws it only every ${t} s`:`its statusLine.refreshInterval is ${JSON.stringify(t)}, not a number of seconds Claude Code accepts (its minimum is 1)`;return UM(e)?{ok:!1,reason:`${r}, but ${i} (statusLine from ${e.path})`,fix:{kind:`claude-settings`,file:e,path:[`statusLine`,`refreshInterval`],value:1}}:{ok:!1,reason:`${r}, but ${i} — its statusLine is in ${e.scope===`managed`?`managed settings`:`the project's shared settings`}, ${e.path}: set "refreshInterval": 1 there`}}}}const CN=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function wN(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return LM(e);case`bundling`:case`unread`:case`configured`:return[EM(e.name),e.version].filter(e=>e!==null).join(` `)}}function TN(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return IM(e);case`bundling`:case`unread`:return EM(e.name);case`configured`:{let t=EM(e.name);return e.font.kind===`ok`?`${t} with ${e.font.value.font} (${e.font.value.from})`:`${t}, its font unread: ${e.font.reason}`}}}function EN(e){let t=TN(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${CN(e.glyphs)}`}}const DN={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=EN(e),r=e=>t.kind===`failed`&&n!==void 0?{ok:!1,reason:e,more:[`the mark book could not be read: ${t.reason}`]}:{ok:!1,reason:e,...n!==void 0&&{sighting:n}},i=e.terminal,a=wN(i);switch(n===void 0||t.kind===`failed`?null:t.value.nerdFont?.[n.id]??null){case`drawn`:return{ok:!0};case`boxes`:return r(`${a} draws ${CN(e.glyphs)} as boxes — set a Nerd Font as its font`);case null:break}switch(i.kind){case`unreported`:return r("the client reported no terminal — re-run `cc-candybar install` to stage a current client");case`unasked`:return r(`tmux could not be asked which terminal is attached: ${i.reason}`);case`unknown`:case`unnamed`:case`unread`:return r(`the doctor cannot read ${a}'s font`);case`bundling`:{let e=SM[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:jM(i.version,e);if(t===!0)return{ok:!0};let n=EM(i.name);return r(t===null?`${n} ships Nerd Font symbols since ${e}, and did not say which release this is`:`${a} ships no Nerd Font symbols (they came in ${e}) — update ${n}, or set a Nerd Font as its font`)}case`configured`:{if(i.font.kind===`failed`)return r(`the doctor cannot read ${a}'s font: ${i.font.reason}`);let{font:e,from:t,lacks:n}=i.font.value;return n===null?r(`${a} is set to ${e} (${t}), which is not installed — install it or set a Nerd Font`):n.length===0?{ok:!0}:r(`${a} draws with ${e} (${t}), which has no ${CN(n)} — set a Nerd Font as its font`)}}}};function ON(e){return e.join(`, `)}function kN(e){return`or set missingData: "ignore" on ${ON(e)}`}function AN(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${ON(t)}: whether the forge CLI is ready could not be asked: ${n.reason}`];if(n.value===null)return[];let{cli:r,host:i,status:a}=n.value;return a===`ready`?[]:a===`missing`?[`${ON(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${kN(t)}`]:[`${ON(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${kN(t)}`]}function jN(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${ON(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${ON(n)}: no session of this Claude Code has drawn a bar for this daemon in the last ${300/60} minutes, so whether it sends rate_limits is unseen — run the doctor again once the bar has redrawn`:`${ON(n)}: ${lN(t)}, so whether Claude Code sends rate_limits is unseen — run the doctor again once the bar has redrawn`]:r.value.includes(`missing`)&&!r.value.includes(`carried`)?[`${ON(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${ON(n)}`]:[]}const MN={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>YM([...AN(e.pullRequests),...jN(e.rateLimits,t)])};function NN({path:e,answered:t,read:n}){switch(n.kind){case`absent`:return t?[`the transcript ${e} does not exist, though Claude Code has answered in its session — the bar's session cost, metrics and activity read nothing`]:[];case`failed`:return[`the transcript ${e} cannot be read: ${n.reason}`];case`ok`:{let{lines:t,unparsed:r,whole:i}=n.value;return r===0?[]:[`${r} of the ${t} lines ${i?`in`:`in the last ${KM/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const PN=[nN,uN,pN,aN,_N,QM,$M,eN,yN,DN,MN,{name:`sessionData`,label:`session data`,takesMark:!1,probe:({transcripts:e,sighted:t})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.length===0?{ok:!1,reason:t.kind===`recent`?`no session has drawn a bar for this daemon in the last ${300/60} minutes, so no transcript was named — run the doctor again once the bar has redrawn`:`${lN(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:YM(e.value.flatMap(NN))}],FN=PN.filter(e=>e.takesMark);function IN(e){return PN.map(t=>({check:t,verdict:t.probe(e)}))}function LN(e){return PN.find(t=>t.name===e)}const RN=`${X}doctor.`;function zN(e){let t=`${RN}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function BN(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?IM(e.identified):null,i=t.kind===`failed`?`unread`:r===null?`-`:t.value.includes(r)?`yes`:`no`;return`tmuxLinks=${n===null?`-`:n.features.includes(`hyperlinks`)?`yes`:`no`} clicked=${i}`}function VN(e,t){let n=e.kind===`seen`?e.tmuxClient:null;return`cols=${t.kind===`failed`?`failed widthOf=-`:`${t.value.columns??`-`} widthOf=${t.value.of.kind}`} clientUtf8=${n===null?`-`:n.utf8?`yes`:`no`}`}function HN(e){if(e.kind===`failed`)return`clients=unasked`;let{daemon:t,clients:n}=e.value;return`clients=${n.map(e=>{if(e.kind===`unreported`)return`unreported/-/-`;let{bundle:n,source:r}=oN(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const UN=e=>`${e>=0?`+`:``}${tr(e)}`;function WN({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${fN(e,t.value).map(e=>e.pid).join(`,`)||`-`}`;if(e.kind===`failed`)return`${r} memory=unasked postMortems=unasked`;let{memory:i,limit:a,postMortems:o}=e.value,s=o.kind===`failed`||n.kind===`failed`?`unread`:`${dN(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${fr(i.charge)}${i.charge.kind===`stand-in`?`(${UN(-i.charge.gap)})`:``}:${tr(i.charge.bytes)}`}/${tr(a)} postMortems=${s}`}function GN(e){return`data=pr:${(()=>{if(e.pullRequests.kind===`unneeded`)return`-`;let t=e.pullRequests.fact;if(t.kind===`failed`)return`failed`;if(t.value===null)return`no-forge`;let{status:n}=t.value;return typeof n==`string`?n:`logged-out`})()},rateLimits:${(()=>{if(e.rateLimits.kind===`unneeded`)return`-`;let t=e.rateLimits.fact;if(t.kind===`failed`)return`failed`;let n=e=>t.value.filter(t=>t===e).length;return`${n(`carried`)}/${n(`missing`)}/${n(`unanswered`)}`})()}`}function KN(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>qN(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${as(i)}`;let a=vN(r.flatMap(e=>e.bars));return`frames=${vM.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${as(i)}`}function qN(e){let t=BM(e);switch(t.kind){case`unread`:return`failed`;case`absent`:case`not-an-object`:return t.kind;case`present`:return`${t.from.scope}:${t.refreshInterval===void 0?`-`:JSON.stringify(t.refreshInterval)}`}}function JN(e){let t=VM(e,XM);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${as(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function YN(e){if(e.kind===`failed`)return`transcripts=failed`;let t=t=>e.value.filter(e=>e.read.kind===t).length,n=e.value.reduce((e,t)=>e+(t.read.kind===`ok`?t.read.value.unparsed:0),0);return`transcripts=${t(`ok`)}/${t(`absent`)}/${t(`failed`)} unparsed=${n}`}function XN(e,t){if(e.kind===`none`)return`glyphs=- terminal=- font=- mark=-`;let{glyphs:n,terminal:r}=e,i=[...n].map(e=>e.codePointAt(0).toString(16)),a=(()=>{switch(r.kind){case`unreported`:case`unasked`:return r.kind;case`unknown`:return`unknown:${JSON.stringify(r.called)}`;case`unnamed`:return`unnamed:${JSON.stringify(r.term)}`;case`bundling`:case`unread`:case`configured`:return`${r.name}@${r.version??`-`}`}})(),o=(()=>{if(r.kind!==`configured`)return`-`;if(r.font.kind===`failed`)return`failed`;let{font:e,lacks:t}=r.font.value;return`${JSON.stringify(e)}:${t===null?`not-installed`:`lacks${t.length}`}`})(),s=EN(e),c=t.kind===`failed`?`unread`:s===void 0?`-`:t.value.nerdFont?.[s.id]??`-`;return`glyphs=${i.join(`,`)} terminal=${a} font=${o} mark=${c}`}function ZN(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function QN(e){return e.flatMap(({check:e,verdict:t})=>{let n=zN(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:h_},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:ZN(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?h_:m_},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const $N={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function eP(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries($N).map(([t,n])=>[`${e}${t}`,n]))}}const tP=`armed`,nP=`disarmed`,rP=`.armed`,iP=e=>e.endsWith(rP);function aP(e,t,n){let r=`${e}${rP}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${tP}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:tP},[a]:{set:r,to:nP},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:nP}},disarm:a}}const oP=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function sP(e){return typeof e==`string`&&oP.test(e)?{kind:`line`,line:e}:{kind:`refused`,reason:`a slash command is "/" then its name, e.g. "/compact" or "/model opus", on one line with no control characters, got ${JSON.stringify(e)}`}}function cP(e){let t=sP(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const lP=[`/compact`,`/model`],uP=`/clear`;function dP(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=aP(`${e}clear`,{arm:uP,confirm:`${uP} ✓ confirm`},[n]);return{template:lP.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${lA} }}`,actions:{...Object.fromEntries(lP.map(e=>[t(e),{slash:cP(e)}])),...r.actions,[n]:{slash:cP(uP)}},variables:r.variables,disarm:r.disarm}}const fP=Array.from({length:10},(e,t)=>(t+1)*1e5),pP=fP[0],mP=fP[fP.length-1];function hP(e){let t;try{t=eo(e)}catch(e){return I(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?P(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=pP&&n<=mP?P(n):I(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${pP}–${mP} tokens)`)}function gP(e,t){let n=Math.min(t??mP,mP),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:fP.filter(e=>e<r).at(-1)??0,higher:fP.find(e=>e>r&&e<=n)??0}}function _P(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${lA} }}{{ if gt .autocompact.lower 0 }} {{ action (printf "${e}%d" .autocompact.lower) "−" }}{{ end }}{{ if gt .autocompact.higher 0 }} {{ action (printf "${e}%d" .autocompact.higher) "+" }}{{ end }}{{ if gt .autocompact.window 0 }} {{ action "${e}auto" "↺" }}{{ end }}{{ end }}{{ end }}`,bg:`{{ if ne .autocompact.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .autocompact.window 0) (ne .autocompact.error "") }}`,actions:{[`${e}auto`]:{slash:cP(`/autocompact auto`)},...Object.fromEntries(fP.map(t=>[`${e}${t}`,{slash:cP(`/autocompact ${t}`)}]))}}}const vP=e=>`{{ if ge ${e} 1000000 }}{{ printf "%.1f" (divf ${e} 1000000) }}M{{ else if ge ${e} 1000 }}{{ printf "%.1f" (divf ${e} 1000) }}K{{ else }}{{ ${e} }}{{ end }}`,yP=`${X}edit`,bP=`${X}toolbar`,xP=eP(X),SP=`${X}commands`,CP=dP(`${SP}.`),wP=`${X}autocompact`,TP=_P(`${wP}.`,vP),EP=e=>({kind:`segment`,name:e}),DP=`${X}tab`,OP=e=>`${DP}.${e}`,kP=e=>`${OP(e)}.toggle`,AP=e=>({variable:DP,key:DP,member:e}),jP=`${X}save`,MP=`${X}preset.save`,NP=`${X}preset.delete`,PP=e=>`${X}${e}`,FP=e=>`${X}apply.${e}`,IP=e=>`${X}reset.${e}`,LP=`${X}themeDefault.save`,RP=`${X}themeDefault.differs`,zP=`${X}themeDefault.theme`,BP={when:`{{ .${RP} }}`,template:`{{ action "${LP}" (printf "⤓ default for %s" .${zP}) }} {{ swatch "${FP(`theme`)}" .${zP} }}`},VP=`${X}resetAll`,HP=`${Sj}.toggle`,UP=`${X}undo`,WP=`${X}back`,GP=`${WP}.step`,KP=`${X}navigation.back`,qP=WP,JP={template:`{{ if gt .${KP} 0 }}{{ action "${WP}" "◁" }}{{ else }}{{ fg (${uM}) "◁" }}{{ end }}`},YP=`${X}redo`,XP=`${X}doctor`,ZP=`${XP}.run`,QP=e=>`${XP}.fix.${e}`,$P=(e,t)=>`${XP}.mark.${e}.${t}`,eF=e=>`${XP}.${e}`,tF={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},nF=CA(`${X}pickers`),rF=e=>`${X}${e}`,iF=e=>`${rF(e)}.toggle`,aF=e=>$j(e)?CA(`${X}${e}Pickers`):nF,oF=e=>{let t=aF(Qj[Xj[e].beside]);return{variable:t,key:t,member:e}},sF={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${NP}" (printf "🚮 delete %s" .${Sy.preset.effectiveVar}) }}`}},cF=(e,t)=>`${X}list.${e}.${t}`,lF=e=>`${X}resettable.${e}`,uF=e=>e.length===0?`false`:`(or ${e.map(e=>`.${lF(e)}`).join(` `)})`,dF=Fv.map(e=>[Pv[e].setting,e]),fF={variables:{},actions:{},segments:{}},pF=Object.fromEntries(dF.map(([e,t])=>[e,Rj(`${X}help.${e}`,cM[t],[],fF)])),mF=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],hF=e=>{let t=t=>`.${zv(e,t)}`,n=mF.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if .${Sy[Pv[e].setting].effectiveVar} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},gF=`{{ if eq .${Lv(`by`)} "feed" }} {{ printf "%2d" (int .${Lv(`fps`)}) }} fps{{ end }}`,_F=Object.fromEntries(dF.map(([e,t])=>[e,hF(t)])),vF=Object.keys(Sy).map(e=>{let t=Sy[e],n=RA(t.configKey),r=FA({label:t.label,domain:n},t.sessionKey,t.effectiveVar,FP(e),aF(Qj[e]));return{...t,name:e,control:r,beneath:t.previews.map(e=>sF[e])}}),yF=e=>vF.filter(t=>Qj[t.name]===e),bF=e=>vF.filter(t=>eM(Qj[t.name],e)),xF=e=>t=>`(print ${ki(t)} (ternary ${ki(` •`)} "" ${uF(bF(e).map(e=>e.name))}))`,SF=e=>Zj.filter(t=>Xj[t].beside===e),CF=e=>yF(e).flatMap(e=>[FF(e),...[pF[e.name]].filter(e=>e!==void 0),...SF(e.name).map(e=>wi(rF(e),oF(e),HF(e),`drop`))]);new Set(vF.flatMap(e=>[e.sessionKey,e.configKey]));const wF=aP(VP,{arm:`⟲`,confirm:`⟲ reset all?`},vF.map(e=>IP(e.name))),TF=[`unsaved`,`history.undo`,`history.redo`],EF=e=>`${X}${e}`,DF=EF(`unsaved`),OF=(e,t)=>({body:t,shown:`(gt .${EF(e)} 0)`}),kF=[OF(`unsaved`,`{{ action "${jP}" (printf "💾 save %d" .${DF}) }}`),OF(`history.undo`,`{{ action "${UP}" "↶" }}`),OF(`history.redo`,`{{ action "${YP}" "↷" }}`),{body:wF.template,shown:`(or ${uF(vF.map(e=>e.name))} ${wF.armed})`}],AF={when:`{{ or ${kF.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+kF.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},jF=[{step:wF,place:`door`},{step:CP,place:`session`}],MF=e=>e.map(e=>e.step.disarm),NF=MF(jF),PF=MF(jF.filter(e=>e.place!==`door`));function FF(e){let t=PP(e.name);return e.control.kind===`inline`?EP(t):wi(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>EP(cF(e.name,n)))},`drop`)}function IF(e){return e===Sj}function LF(e){let t=EP(Sj);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[LF(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}return e.kind===`container`&&e.when===void 0?{...e,children:[t,...e.children]}:{kind:`container`,direction:`horizontal`,children:[t,e]}}function RF(e){return zF(e)>0?e:LF(e)}function zF(e){let t=0;for(let n of E_(e))n.kind===`segment`&&IF(n.name)&&(t+=1);return t}function BF(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&IF(e.name)||e.opens!==void 0&&BF(e.opens.body,!0):e.children.some(e=>BF(e,n))}const VF={door:{direction:`horizontal`,content:[EP(qP)],after:[EP(yP),EP(jP)]},session:{direction:`vertical`,content:[EP(bP),{kind:`container`,direction:`horizontal`,children:[EP(SP),EP(wP)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[EP(MP)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[EP(XP),...PN.map(e=>EP(eF(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[EP(LP)]},toggles:{direction:`horizontal`,content:[],after:[]}};function HF(e){let{direction:t,content:n,after:r}=VF[e];return{kind:`container`,direction:t,children:[...n,...CF(e),...r]}}function UF(e){return e.kind===`segment`?IF(e.name)?wi(e.name,wj,GF,`above`):e:KF(e)}function WF(){return{kind:`container`,direction:`vertical`,children:[HF(`door`),{kind:`container`,direction:`horizontal`,children:Jj.map(({member:e})=>wi(OP(e),AP(e),HF(e),`drop`))}]}}const GF=WF();function KF(e){return{...e,children:e.children.map(e=>UF(e))}}function qF(e){let t={variables:{[Sj]:Ai(Sj,yi)},actions:{[HP]:N(Sj,Cj),[Sj]:{do:[HP,...NF]},[ZP]:{doctor:`run`},...xP.actions,...CP.actions,...TP.actions,[jP]:{save:!0},[UP]:{undo:!0},[GP]:{back:!0},[WP]:{do:[GP,...NF]},[YP]:{redo:!0},[MP]:{preset:`save`},[LP]:{themeDefault:`save`},[NP]:{preset:`delete`,name:`{{ .${Sy.preset.effectiveVar} }}`}},segments:{[Sj]:{template:`{{ $door := ${Oi(Sj,ki(e),ki(`✖`))} }}{{ if ${Ei(wj)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+gF},[bP]:{template:xP.template},[SP]:{template:CP.template,when:CP.when},[wP]:{template:TP.template,bg:TP.bg,when:TP.when},[qP]:JP,[jP]:AF,[LP]:BP,[MP]:{template:`{{ action "${MP}" "+ preset" }}`},[XP]:{template:`{{ action "${ZP}" "🩺 doctor" }}`},[yP]:{template:`{{ action "${Dj}" "✎ arrange" "✎ done" }}`}}};t.variables[RP]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[zP]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[KP]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of TF)t.variables[EF(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[DP]=Ai(DP,`session`);for(let{member:e,label:n}of Jj){t.actions[kP(e)]=N(DP,e),t.actions[OP(e)]={do:[kP(e),...PF]};let r=xF(e);t.segments[OP(e)]={template:`{{ ${Oi(OP(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,CP.variables,wF.variables),YF(t),JF(t),t}function JF(e){for(let t of PN){let n=zN(t.name),r=QP(t.name);for(let t of Object.values(n))e.variables[t]={kind:`state`,key:t,default:``};e.actions[r]={doctor:`fix`,check:t.name};let i=t.takesMark?GM:[];for(let n of i)e.actions[$P(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${$P(t.name,e)}" "${tF[e]}" }}`).join(``);e.segments[eF(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ if ne .${n.reason} "" }} — {{ .${n.reason} }}{{ end }}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${m_}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function YF(e){for(let t of vF){Object.assign(e.actions,t.control.actions);let n=IP(t.name);e.actions[n]={reset:t.configKey},e.variables[lF(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${lF(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[PP(t.name)]={template:`${t.control.template}${_F[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[cF(t.name,r)]=n})}Object.assign(e.actions,wF.actions),Object.assign(e.variables,fF.variables),Object.assign(e.actions,fF.actions),Object.assign(e.segments,fF.segments);for(let t of Zj){let n=oF(t);e.actions[iF(t)]=N(n.key,n.member),e.segments[rF(t)]={template:`{{ action "${iF(t)}" ${xF(t)(Xj[t].trigger)} }}`}}}function XF(e){let{variables:t,actions:n}=Ij();Object.assign(e.variables,t),Object.assign(e.actions,n)}function ZF(e){let t=qF(e.globals.menuGlyph??`🍫`);XF(t);let n={...e.presets},r=[];for(let t of Qb(e.presets)){let{node:i}=tx(e,t),a=UF(RF(i));r.push(a),n[t]={...ex(e.presets,t),root:a}}let i=dA(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const QF=`${gA}live`,$F=[`☐ live`,`☑ live`],eI=`${gA}done`,tI=`${gA}cancel`,nI=`${gA}rewind`,rI=`${gA}changes`,iI=`(gt .${rI} 0)`,aI=`(or ${iI} (gt .${DF} 0))`,oI={variable:QF,key:QF,member:`open`};function sI(e){return`${gA}configuring.p${e}`}function cI(e){return`and ${Ei(jj)} (not ${Ei(oI)}) (ne .${sI(e)} "true")`}function lI(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${Ej} "${Ci(e)}")`).join(` `)} false }}`}}function uI(e,t,n){return`{{ if ${cI(e)} }}${t}{{ else }}${n}{{ end }}`}const dI=`{{ and ${Ei(jj)} .preset.customized }}`,fI=vA;function pI(e){return new Map([...ox(e),...hI(e)])}const mI=`${gA}addable`;function hI(e){return new Map([[mI,{members:Object.keys(e.segments).filter(e=>!fI(e)),library:{groups:yj.map(e=>({id:e,label:bj[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function gI(e,t,n){return n.segments[e]={template:t,when:Mj,bg:Bj},{kind:`segment`,name:e}}function _I(e,t,n){let r=`${gA}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Yh}`}) (action "${r}" "✖") }}`}function vI(e){return`{{ if ${Ei(jj)} }}${e}{{ end }}`}function yI(e,t){return e.reduce((e,t)=>`{{ if and ${Ei(jj)} ${Ei(t)} }}true{{ else }}${e}{{ end }}`,t)}function bI(e){return e.flatMap(e=>[...E_(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function xI(e,t,n){return`${kj}${e}.${t}.${n}`}function SI(e,t,n,r){let i=S_(n),a=`${gA}${e.presetIdent}`,o=Aj(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=CA(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:yi},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:Ej,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=xI(e.presetIdent,i,r),l=`${kj}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:G_(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=FA(NA(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};e.artifacts.segments[d]={template:f.template};let p=f.list.rows.map((t,n)=>{let r=`${d}.list.${n}`;return e.artifacts.segments[r]={template:t},{kind:`segment`,name:r}});return wi(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${Kj}" }}`,ref:{variable:Ej,key:Ej,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const CI=`${gA}label:`;function wI(e){if(e.startsWith(CI)){let t=e.slice(CI.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function TI(e,t,n,r){let{artifacts:i}=n,a=S_(e),o=`${CI}${a}:${e.name}`;i.segments[o]={template:`{{ "${Ci(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=Object.fromEntries(B_.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...wi(o,r.ref,r.body,`drop`,yI([r.ref],`{{ ${cI(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(B_.map(e=>[e,r.drafts[e]]))}}function EI(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${gA}${i}.insert.${t}`,s=`${gA}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:mI,anchor:n,relation:r};let c=xA(o),l=SA(s,o,void 0),u=TA(l),d=wA(l,c);return a.variables[l]={...Ai(l,yi),within:[jj]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=N(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${Ei({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Yh}`}) $m }}{{ end }}`}}function DI(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!fI(e.name)),i=e=>DI(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=T_(o,i);if(fI(o.name)){n.push(s);continue}let c=S_(o),l=a===r?[EI(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=EI(t,u,c,`after`),f=_I(t,u,c),p=t.segments[o.name],m=SI(t,u,o,V_(p)),h=vI(f),g=vI(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>gI(e.host,e.template,t.artifacts)),{...TI(o,p,t,m),lead:h,trail:g},{...s,when:uI(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},gI(d.host,d.template,t.artifacts)]};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[_]}:_)}return{...e,children:n,...e.when!==void 0&&{when:yI(bI(n),uI(t.presetIdent,`true`,e.when))}}}function OI(e,t,n,r,i,a,o){let s=`${gA}${t}.resetLayout`,c=`${gA}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:dI},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},kI(e,o)]}}function kI(e,t){if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t]};let n=e.children.at(-1);return e.direction===`vertical`&&n!==void 0&&(n.kind===`segment`||n.when===void 0)?{...e,children:[...e.children.slice(0,-1),kI(n,t)]}:{...e,children:[...e.children,t]}}function AI(e,t,n,r,i,a){let{node:o}=tx(e,t),s={presetIdent:fA(t),rootKey:fj(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=DI(o,s);return n.variables[sI(s.presetIdent)]=lI(s.configured),OI(c,s.presetIdent,s.rootKey,n,r,i,a)}function jI(e){let t={variables:{},actions:{},segments:{}},n=Rj(`${gA}help`,sM,[jj],t);t.variables[QF]=Ai(QF,yi),t.actions[QF]=N(QF,oI.member),t.segments[QF]={template:Di(QF,...$F),when:Mj};let r={kind:`segment`,name:QF},i=n;t.variables[rI]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[eI]={do:[jP,Dj]},t.segments[eI]={template:`{{ if ${aI} }}{{ action "${eI}" "✓ save" }}{{ else }}{{ action "${eI}" "✓ done" }}{{ end }}`,when:Mj},t.actions[nI]={rewind:!0},t.actions[tI]={do:[nI,Dj]},t.segments[tI]={template:`{{ action "${tI}" "↩ cancel" }}`,when:`{{ and ${Ei(jj)} ${iI} }}`};let a=[{kind:`segment`,name:eI},{kind:`segment`,name:tI}],o={...e.presets},s=[];for(let n of Qb(e.presets)){let c=AI(e,n,t,a,r,i);s.push(c),o[n]={...ex(e.presets,n),root:c}}let c=dA(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function MI(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function NI(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function PI(e,t,n){let r=w_(e,new Set(n.map(C_).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const FI=/^-?\d+$/;function II(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function LI(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!FI.test(t))return{ok:!1,reason:`${e} must be an integer, got "${t}"`};let n=t[0]===`-`,r=(n?t.slice(1):t).replace(/^0+/,``);return r===``?{ok:!0,value:`0`}:{ok:!0,value:n?`-${r}`:r}}}function RI(e,t,n){return r=>r?FI.test(r)?{ok:!0,value:String(Math.max(e,Math.min(t,parseInt(r,10))))}:{ok:!1,reason:`${n} must be an integer, got "${r}"`}:{ok:!1,reason:`${n} value is required`}}function zI(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!FI.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i}}return{kind:`int`}}function BI(e){return e===`config`?`set-config`:`set-state`}function VI(e,t,n){return t.kind===`int`?LI(`menu page "${e}"`):t.kind===`range`?RI(t.min,t.max,`${n} stepper "${e}"`):II(t.allowed,`${n} "${e}"`,BI(n))}function HI(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:zI(e,n,t)}))}function UI(e,t,n,r){let i=new Map(Object.entries(e)),a=new Map,o=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of n)if(o.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let s=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...n];for(let{key:t,spec:n}of HI(s,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,VI(t,n,r)),n.kind===`range`&&a.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>a.get(e)??null}}function WI(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};UI(e,[o],[],t),r.push(o),i++;let s=!0;return()=>{s&&(s=!1,r.splice(r.indexOf(o),1),i++)}},gateFor(o){let s=a.get(o);if(s?.epoch===i)return s.gate;let c=UI(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const GI=WI({},`config`,QI);function KI(e,t){return GI.register(e,t)}function qI(e){return GI.gateFor(e)}function JI(e,t){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:cx(e.from,t).members}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[MI({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[MI({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:cx(e.insertSegmentFrom,t).members.map(t=>MI({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function YI(e,t){let n=sj(e).get(t);return n===void 0?null:String(n)}function XI(e){let t=new Set;for(let n of Object.values(e.actions)){`reset`in n&&t.add(n.reset);let e=`persist`in n?gj(n.persist):null;e?.scope===`preset-root`&&t.add(fj(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function ZI(e){let t=pI(e);return[...XI(e),...Object.values(e.actions).flatMap(e=>JI(e,t))]}function QI(e){return HI(ZI(e),`config`)}function $I(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:nL(t.segments,eL(t.segments,e.segments??{})),root:Jb(e.root??Vb,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:nL(t.presets,tL(t.presets,e.presets??{})),themeDefaults:nL(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function eL(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.settings===void 0?n:{...n,settings:{...e[t]?.settings,...n.settings}}]))}function tL(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.globals===void 0?n:{...n,globals:{...e[t]?.globals,...n.globals}}]))}function nL(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function rL(e,t,n,r){return n.cache===void 0?(e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${M_.join(`, `)})`,line:G(e.source,t.split(`.`))}),null):oL(e,`${t}.cache`,n.cache)}function iL(e){return{required:!0,json:sL(),parse:(t,n,r,i)=>rL(t,n,i,e)??void 0}}const aL={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&lL(n)?{ttl:n}:mv(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${K(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return mv(e,t,`cache.watch_file must be a path string, got ${K(n)}`);let r=Ev(`cache.watch_file`,n);return r===null?{watch_file:n}:mv(e,t,r)}},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:mv(e,t,`cache.depends_on must be an array of variable-name strings, got ${K(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:mv(e,t,`cache.key must be a non-empty template string, got ${K(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:mv(e,t,`cache.never must be the literal boolean true, got ${K(n)}`)}}};function oL(e,t,n){return hv(e,aL,t,n)}function sL(){return Nv(aL)}const cL=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function lL(e){return cL.test(e)}const uL=new Map([[`session.budget.amount`,{segment:`session`,setting:`budget`}],[`session.budget.warningThreshold`,{segment:`session`,setting:`warnAt`}],[`today.budget.amount`,{segment:`today`,setting:`budget`}],[`today.budget.warningThreshold`,{segment:`today`,setting:`warnAt`}],[`block.budget.heatThreshold`,{segment:`block`,setting:`warnAt`}],[`block.budget.warningThreshold`,{segment:`block`,setting:`errorAt`}],[`weekly.budget.heatThreshold`,{segment:`weekly`,setting:`warnAt`}],[`weekly.budget.warningThreshold`,{segment:`weekly`,setting:`errorAt`}],[`burn.eta.errorMinutes`,{segment:`burnrate`,setting:`errorWithin`}],[`burn.eta.warnMinutes`,{segment:`burnrate`,setting:`warnWithin`}]]);function dL(e){return`it became the "${e.setting}" setting of each "${e.segment}" placement — set it on the placement where a row places "${e.segment}" ({ seg: "${e.segment}", settings: { ${e.setting}: <value> } }), or redeclare segments.${e.segment}.settings.${e.setting} with the default every placement should start from`}function fL(e){let t=uL.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${dL(t)}`}function pL(e){let t=uL.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${dL(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const mL=new Map([[`git.timeSinceCommit`,`the payload stores the commit's date as "git.committedAt" (epoch seconds), and the bundled template variable "git.timeSinceCommit" computes its age at the draw: drop this declaration`],[`block.etaMinutes`,`the bundled template variable "block.etaMinutes" computes it at the draw: drop this declaration`],[`weekly.etaMinutes`,`the bundled template variable "weekly.etaMinutes" computes it at the draw: drop this declaration`]]),hL=new Map([[`branch`,{read:`.git.branch`,declare:{kind:`input`,path:`git.branch`,default:``},note:`when HEAD is on no branch it reads "detached", where this kind read ""`}],[`sha`,{read:`.git.sha`,declare:{kind:`input`,path:`git.sha`,default:``}}],[`dirty`,{read:`(ne .git.status "clean")`,declare:{kind:`template`,template:`{{ ne .git.status "clean" }}`,type:`boolean`}}],...[`ahead`,`behind`,`stash`].map(e=>[e,{read:`.git.${e}`,declare:{kind:`input`,path:`git.${e}`,type:`number`,default:0}}])]);function gL(e){let t=e=>typeof e==`string`&&e.includes(`"`)&&!e.includes(`'`)?`'${e}'`:JSON.stringify(e);return`{ ${Object.entries(e).map(([e,n])=>`${e}: ${t(n)}`).join(`, `)} }`}function _L(e){let t=`kind "git" is retired: every git fact is an input over the payload's git lane, which the bundled default already declares — drop this declaration and`,n=typeof e.field==`string`?hL.get(e.field):void 0;if(n===void 0){let e=[...hL.values()].map(({read:e})=>e);return`${t} read whichever of ${e.slice(0,-1).join(`, `)} or ${e.at(-1)} it stood for, where it was read`}let r=n.note===void 0?``:` (${n.note})`;return`${t} read ${n.read} where it was read${r}, or declare ${gL(n.declare)} under a name of your own`}function vL(e,t,n){if(n===void 0)return{};if(!sv(n))return e.issues.push({path:t,message:`${t} must be an object, got ${cv(n)}`,line:G(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=gv(e,HL,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function yL(){return{required:!0,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.value;if(typeof i!=`string`&&typeof i!=`number`&&typeof i!=`boolean`){e.issues.push({path:`${t}.value`,message:`literal value must be string|number|boolean, got ${cv(i)}`,line:G(e.source,t.split(`.`))});return}return i}}}function bL(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return rv(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const xL={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:mv(e,t,`parse.text must be the literal boolean true, got ${K(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?SL(e,t,n):mv(e,t,`parse.regex must be a pattern string, got ${K(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:mv(e,t,`parse.json must be the literal boolean true, got ${K(n)}`)}}};function SL(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return mv(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:mv(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function CL(){return{required:!1,json:Nv(xL),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:G(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:hv(e,xL,`${t}.parse`,r.parse)??void 0)}}function wL(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>sv(r.parse)&&`json`in r.parse?TL(e,t,r.default):iv(e,t,r,`default`)}}function TL(e,t,n){if(n!==void 0)return EL(n)?n:mv(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${K(n)}`)??void 0}function EL(e){return e!==null&&DL(e)}function DL(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(DL);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(DL)}default:return!1}}const OL={value:yL(),default:bv()};function kL(){let e=Tv();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:mL.get(a);return o===void 0?a:mv(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const AL={path:kL(),type:Ov([`string`,`number`,`boolean`]),default:bL()},jL={name:Tv(),default:bv()},ML={path:Dv(),readMode:Ov([`whole`,`first-line`]),parse:CL(),cache:iL(`file`),default:wL()},NL={command:Tv(),parse:CL(),cache:iL(`shell`),default:wL()};function PL(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const FL={template:Tv(),type:Ov([`string`,`number`,`boolean`]),default:bL()},IL=PL(`a template variable recomputes whenever a variable it reads changes`),LL={layout:Tv(),default:bv()},RL=PL(`a time variable reads the instant its render is drawn at`),zL={key:Tv(),default:bv()},BL=`kind`;function VL(e,t,n={}){return{..._v(BL,e,t),parse:(r,i,a)=>{uv(r,n,i,a);let o=dv(r,t,i,a);return o===null?null:{kind:e,...o}}}}const HL={tag:BL,noun:`source kind`,memberNoun:`variable`,arms:{literal:VL(`literal`,OL),input:VL(`input`,AL),env:VL(`env`,jL),file:VL(`file`,ML),shell:VL(`shell`,NL),template:VL(`template`,FL,IL),time:VL(`time`,LL,RL),state:VL(`state`,zL)},retired:{git:_L}};function UL(){return Mv(HL)}function WL(){return{type:`object`,additionalProperties:UL()}}const GL=new Map([[`gitTaculous`,{kind:`built-in`,to:`gitaculous`}],[`git`,{kind:`built-in`,to:`gitaculous`}],[`settings.menu`,{kind:`built-in`,to:`candybar.menu`}],[`ticket`,{kind:`plugin`,to:`plugins.lit.ticket`,source:`promptctl/links-issue-tracker`}],[`ceiling`,{kind:`removed`}]]);function KL(e){let t=GL.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`;case`removed`:return` (the built-in segment "${e}" was removed: the program it showed draws it through a cc-candybar plugin of its own now — delete this reference, or place that plugin's segment)`}}const qL=/^[A-Za-z_][A-Za-z0-9_]*$/,JL={pattern:qL.source},YL={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},XL={type:`object`,additionalProperties:!1,required:[`label`,`domain`,`default`],properties:{label:{type:`string`,pattern:`^[^\\n\\r]+$`},domain:{anyOf:[{const:`bool`},{type:`array`,items:{type:`string`,pattern:`^[^/\\n\\r]+$`},minItems:1,uniqueItems:!0},{type:`object`,additionalProperties:!1,required:[`min`,`max`],properties:{min:{type:`integer`},max:{type:`integer`},step:{type:`integer`,minimum:1},atLeast:{type:`string`,...JL}}}]},default:YL}},ZL=[`label`,`domain`,`default`],QL=[`min`,`max`,`step`,`atLeast`];function $L(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function eR(e,t,n){if(n===`bool`)return`bool`;if(Array.isArray(n)){let r=n.filter(e=>typeof e==`string`);if(n.length===0||r.length!==n.length)return $L(e,t,`a list domain must be a non-empty list of words, got ${JSON.stringify(n)}`);if(new Set(r).size!==r.length)return $L(e,t,`a list domain names each word once, got ${JSON.stringify(n)}`);let i=r.filter(e=>e===``||e.includes(`/`)||/[\n\r]/.test(e));return i.length>0?$L(e,t,`a list domain's words must be non-empty, slash-free, and newline-free — configure mode writes each on the set-state wire — got ${JSON.stringify(i)}`):r}if(sv(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!QL.includes(e)).length===0&&Number.isInteger(r)&&Number.isInteger(i)&&r<=i&&Number.isInteger(a)&&a>=1&&(o===void 0||typeof o==`string`)?{min:r,max:i,step:a,...o!==void 0&&{atLeast:o}}:$L(e,t,`a range domain is { min, max, step?, atLeast? } with integers min ≤ max, a whole step ≥ 1, and atLeast naming another range setting, got ${JSON.stringify(n)}`)}return $L(e,t,`domain must be "bool", a list of words, or { min, max }, got ${K(n)}`)}function tR(e,t,n){if(!sv(n))return $L(e,t,`${t} must be { label, domain, default }, got ${cv(n)}`);for(let r of Object.keys(n))ZL.includes(r)||$L(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${ZL.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||$L(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${K(r)}`);let a=eR(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!nR(n.default)||!W_(o,n.default)?$L(e,`${t}.default`,`default must be ${J_(o)}, got ${K(n.default)}`):o}function nR(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const rR={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${R_}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function iR(e){return B_.includes(e)}function aR(){return{required:!1,json:{type:`object`,propertyNames:{...JL,not:{enum:[...B_]}},additionalProperties:XL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!sv(i))return $L(e,a,`${a} must be an object of name → { label, domain, default }, got ${cv(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!qL.test(t)){$L(e,`${a}.${t}`,`setting name "${t}" is read as .settings.${t} in a template, so it must be an identifier (letters, digits, _; not starting with a digit)`);continue}if(iR(t)){$L(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${rR[t]}`);continue}let r=tR(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const oR=_A.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function sR(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${oR})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!vA(i)?i:$L(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${_A.map(e=>`"${e}"`).join(`, `)} namespaces, got ${K(i)}`)}}}function cR(){return{required:!1,json:{type:`object`,propertyNames:JL,additionalProperties:YL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!sv(i))return $L(e,a,`a placement's "settings" must be an object of setting name → value, got ${cv(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))nR(n)?o[t]=n:$L(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${cv(n)}`);return o}}}function lR(e){return new Set(Object.keys(e.segments).filter(e=>!vA(e)))}function uR(e,t,n){if(t===void 0)return{};if(!sv(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${cv(t)}`,line:G(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=lv(e,n.has(i)?gR:hR,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function dR(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?mv(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own${KL(t.slice(9))}`)??void 0:nv(e,t,r,n)??void 0}}function fR(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${K(i)}`,line:G(e.source,[...t.split(`.`),n])})}}}}function pR(){return{required:!1,json:WL(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return vL(e,`${t}.${n}`,i)}}}const mR={template:dR(),description:bv(),group:Ov(vj),width:fR(),justify:Ov(Y_),truncate:Ov(X_),bg:bv(),fg:bv(),when:bv(),palette:wv(),vars:pR(),settings:aR(),missingData:Ov(F_)},hR={noun:`segment key`,fields:mR},gR={noun:`segment key`,fields:{...mR,template:bv()}},_R=`#/definitions/LayoutNode`,vR={kind:`container`,direction:`vertical`,children:[]};function yR(e){return{required:!0,json:{const:e},parse:()=>e}}function bR(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${K(i)}`,line:G(e.source,[`root`])}),``)}}}function xR(){return{required:!0,json:{enum:[...b_]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&b_.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${b_.join(`, `)} (got ${JSON.stringify(i)})`,line:G(e.source,[`root`])}),`vertical`)}}}function SR(e){return{required:!0,json:{type:`array`,items:{$ref:_R}},parse:(t,n,r,i)=>{let a=i[r];return Array.isArray(a)?a.map((i,a)=>e(t,`${n}.${r}[${a}]`,i)):(t.issues.push({path:`${n}.${r}`,message:`a container must have a "children" array of layout nodes, got ${cv(a)}`,line:G(t.source,[`root`])}),[])}}}const CR={noun:`layout-node key`,fields:{kind:yR(`segment`),name:bR(),when:bv(),id:sR(),settings:cR()}},wR=()=>Ov(Eh),TR={noun:`layout-node key`,fields:{kind:yR(`container`),direction:xR(),children:SR(vv(()=>AR)),when:bv(),distribution:wR()}};function ER(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${K(i)}`,line:G(e.source,[`root`])}),``)}}}const DR={noun:`layout-node key`,fields:{seg:ER(),when:bv(),id:sR(),settings:cR()}},OR={noun:`layout-node key`,fields:{h:SR(vv(()=>AR)),when:bv(),distribution:wR()}},kR={noun:`layout-node key`,fields:{v:SR(vv(()=>AR)),when:bv(),distribution:wR()}},AR=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:G(e.source,[`root`])}),vR):{kind:`segment`,name:n};if(!sv(n))return e.issues.push({path:t,message:`a layout node must be a string (segment name) or an object with "kind" / "seg" / "h" / "v", got ${cv(n)}`,line:G(e.source,[`root`])}),vR;if(n.kind===`container`)return lv(e,TR,t,n)??vR;if(n.kind===`segment`)return lv(e,CR,t,n)??vR;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
177
+ `,dM=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`,fM={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function pM(e){let t=e[fM.socket]??``,n=e[fM.pane]??``;if(t===``||n===``)return null;let r=e[fM.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const mM=[`moves`,`can-move`,`still`];function hM(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const gM=[`carried`,`missing`,`unanswered`];function _M(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:hM(e)===`no`?`unanswered`:`missing`}function vM(e){return{path:e.transcript_path,answered:hM(e)===`yes`}}const yM=[...mM,`failed`,`drawing`],bM=[`statusline`,`frames`],xM=e=>e?.kind===`frames`?`frames`:`statusline`;var SM=class{seen=new Map;see(e,t,n,r){let i=xM(t.client),a=JSON.stringify([e,i]),o=this.seen.get(a);o!==void 0&&o.order>r||(this.seen.delete(a),this.seen.set(a,{sessionId:e,said:{...t,role:i},at:n,order:r}),this.seen.size>64&&this.seen.delete(this.seen.keys().next().value))}list(e){return[...this.seen.values()].map(({sessionId:t,said:n,at:r})=>({...n,sessionId:t,ago:e-r}))}ofSession(e,t){return this.list(t).filter(t=>t.sessionId===e)}};const CM={kitty:{label:`kitty`,xtversion:`kitty`,program:null,programVersion:!0,term:`xterm-kitty`,links:{since:`0.19.0`},glyphs:{kind:`bundled`,since:`0.36.0`}},wezterm:{label:`WezTerm`,xtversion:`WezTerm`,program:`WezTerm`,programVersion:!0,term:`wezterm`,links:{since:null},glyphs:{kind:`bundled`,since:`20230712`}},ghostty:{label:`Ghostty`,xtversion:`ghostty`,program:`ghostty`,programVersion:!0,term:`xterm-ghostty`,links:{since:null},glyphs:{kind:`bundled`,since:null}},iterm2:{label:`iTerm2`,xtversion:`iTerm2`,program:`iTerm.app`,programVersion:!0,term:null,links:{since:`3.1`},glyphs:{kind:`configured`}},alacritty:{label:`Alacritty`,xtversion:`alacritty`,program:null,programVersion:!0,term:`alacritty`,links:{since:`0.11.0`},glyphs:{kind:`configured`}},"apple-terminal":{label:`Terminal`,xtversion:null,program:`Apple_Terminal`,programVersion:!0,term:null,links:null,glyphs:{kind:`unread`}},vscode:{label:`VS Code`,xtversion:null,program:`vscode`,programVersion:!1,term:null,links:{since:`1.72`},glyphs:{kind:`unread`}}},wM=e=>CM[e];function TM(e){return wM(e).glyphs.kind===`bundled`}function EM(e){return wM(e).glyphs.kind===`configured`}const DM=e=>wM(e).label,OM=[{since:`3.5.0`,from:57504,to:57507},{since:`3.5.0`,from:57520,to:57554},{since:`3.5.0`,from:57556,to:57556},{since:`3.5.6`,from:57558,to:57559}];function kM(e,t){let n=t.codePointAt(0);return OM.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&MM(e,t)===!0)}const AM=Object.keys(CM);function jM(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function MM(e,t){let n=jM(e),r=jM(t);if(n===null)return null;for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t>i}return!0}function NM(e){for(let t of AM){let n=wM(t).xtversion;if(n!==null&&e.toLowerCase().startsWith(n.toLowerCase())){let r=e.slice(n.length).replace(/^[\s(]+/,``);return{name:t,version:/^[^\s)]+/.exec(r)?.[0]??null}}}return null}function PM(e){let t=AM.find(t=>wM(t).term===e);return t===void 0?null:{name:t,version:null}}function FM(e){let t=NM(e.termtype)??PM(e.termname);if(t!==null)return{kind:`known`,terminal:t};let n=/^[^\s(]*/.exec(e.termtype)[0];return n===``?{kind:`unnamed`,term:e.termname}:{kind:`unknown`,called:n}}function IM(e){let t=e.TERM_PROGRAM,n=AM.find(e=>wM(e).program===t),r=n===void 0?PM(e.TERM):{name:n,version:wM(n).programVersion?e.TERM_PROGRAM_VERSION??null:null};return r===null?t===void 0||t===`tmux`?{kind:`unnamed`,term:e.TERM??``}:{kind:`unknown`,called:t}:{kind:`known`,terminal:r}}function LM(e){switch(e.kind){case`known`:return DM(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function RM(e){switch(e.kind){case`known`:return DM(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function zM({name:e,version:t}){let n=wM(e).links;if(n===null)return{kind:`none`};if(n.since===null)return{kind:`draws`};if(t===null)return{kind:`unsaid`,since:n.since};let r=MM(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const BM=AM.filter(e=>wM(e).links!==null).map(DM).join(`, `);function VM(e){if(e.kind===`failed`)return{kind:`unread`,reason:e.reason};let t=e.value.flatMap(({scope:e,path:t,settings:n})=>`statusLine`in n?[{from:{scope:e,path:t},line:n.statusLine}]:[]),n=t[0];if(n===void 0)return{kind:`absent`,read:e.value.map(e=>e.path)};if(!oo(n.line))return{kind:`not-an-object`,value:n.line,from:n.from};for(let{from:e,line:r}of t){if(e.scope!==n.from.scope||!oo(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function HM(e,t){if(e.kind===`failed`)return e;let n=e.value.find(e=>Object.hasOwn(e.env,t));return{kind:`ok`,value:n===void 0?{kind:`unset`}:{kind:`set`,value:n.env[t],from:{scope:n.scope,path:n.path}}}}const UM=[`managed`,`project`],WM=e=>!UM.includes(e.scope),GM={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:ro(t.projectDir)}),user:e=>({scope:`user`,path:e})},KM=[`drawn`,`boxes`],qM=1024*1024,JM=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function YM(e){switch(e.kind){case`claude-settings`:return`${e.kind} ${e.path.join(`.`)}=${JSON.stringify(e.value)} file=${JSON.stringify(e.file.path)} scope=${e.file.scope}`;case`post-mortems-read`:return`${e.kind} through=${e.through}`}}function XM(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const ZM=fM.truecolor;function QM(e,t){switch(e.kind){case`unreported`:return{ok:!1,reason:"the client reported no tmux facts — re-run `cc-candybar install` to stage a current client"};case`outside`:return{ok:!0};case`inside`:return e.client.kind===`failed`?{ok:!1,reason:`tmux could not be asked: ${e.client.reason}`}:e.client.value===null?{ok:!0}:t(e.client.value,e.hint)}}const $M={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>QM(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=HM(t.sources,ZM);if(r.kind===`failed`)return{ok:!1,reason:r.reason};let i=r.value;if(i.kind===`set`&&typeof i.value==`string`&&i.value!==``)return{ok:!1,reason:`${ZM} is set in ${i.from.path} — restart Claude Code to apply`};let a=`Claude Code renders the bar in 256 colours inside tmux`,o=e=>({ok:!1,reason:a,fix:{kind:`claude-settings`,file:e,path:[`env`,ZM],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=GM[i.from.scope](i.from.path,t.at);return s===null?{ok:!1,reason:`${a} — the value that counts is in managed settings, ${i.from.path}: set ${ZM} to "1" there`}:o(s)})},eN={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>QM(e,e=>e.utf8?{ok:!0}:{ok:!1,reason:"tmux draws this terminal without UTF-8, so every glyph on the bar arrives as `_` — attach with `tmux -u`, or set a UTF-8 LC_ALL/LC_CTYPE/LANG in the shell that runs tmux"})},tN={name:`termWidth`,label:`terminal width`,takesMark:!1,probe:({width:e})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.columns===null?{ok:!1,reason:`${JM(e.value.of)} measured no width (no COLUMNS, and no terminal to ask — or the daemon refused the width sent, which the bar's red strip names), so the bar is laid out as if the terminal were 120 columns wide`}:{ok:!0,note:`${e.value.columns} columns, as ${JM(e.value.of)} measured`}},nN={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},rN={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{switch(e.kind){case`failed`:{let[t=`the config failed to load`,...n]=[...e.error.split(`
178
+ `).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return XM([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${nN[e]}`)])}}},iN="re-run `cc-candybar install`";function aN(e){if(e.kind===`failed`)return[`Launch Services could not be asked which app opens cc-candybar:// — ${e.reason}`];if(e.value===null)return[`no app is registered for cc-candybar:// — ${iN}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${iN}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${iN}`)}const oN={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${iN}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${iN}`};case`lost`:return XM([...aN(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}};function sN({bundle:e,checkout:t},n){return{bundle:n.bundle.kind===`failed`?{kind:`unresolved`,reason:n.bundle.reason}:n.bundle.value===e?{kind:`same`}:{kind:`other`,path:n.bundle.value},source:n.client!==`native`||t===null?{kind:`uncompared`}:t.rustSource.kind===`failed`?{kind:`unreadable`,root:t.root,reason:t.rustSource.reason}:n.source===null?{kind:`unstamped`}:n.source===t.rustSource.value?{kind:`same`}:{kind:`other`,root:t.root}}}function cN(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${Fv.join(`|`)}>\``:e.checkout===null?iN:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function lN(e,t,n){let{checkout:r}=e;if(n.kind===`unreported`)return[`the bar is drawn by a statusline client too old to say what it is — ${cN(e,`native`)}`];let{bundle:i,source:a}=sN(e,n);switch(i.kind){case`unresolved`:return[`the statusline client's bundle cannot be resolved: ${i.reason}`];case`other`:return[`the statusline client runs ${i.path}, not the daemon's ${e.bundle} — ${cN(e,n.client)}`];case`same`:break}if(n.client===`node`&&(t||r!==null))return[`the bar is drawn by the Node fallback, which starts node on every render — ${cN(e,`native`)}`];switch(a.kind){case`uncompared`:case`same`:return[];case`unreadable`:return[`${a.root}/rust-client could not be read: ${a.reason}`];case`unstamped`:return["the native client carries no source stamp, so which source it was built from is unknown — run `just install-rust`"];case`other`:return[`the native client was built from other source than ${a.root}/rust-client holds — run \`just install-rust\``]}}const uN=e=>{let t=`restarted since the bar was drawn, or has served 64 newer sessions`;return e.kind===`clicked`?`this daemon holds no render of this bar (it ${t})`:`this daemon holds no render of session ${e.sessionId}'s bar (its statusLine does not run cc-candybar — a \`claude -p\` session draws none — or the daemon ${t}; unset CLAUDE_CODE_SESSION_ID to judge every bar drawn recently)`},dN={name:`install`,label:`install`,takesMark:!1,probe:({install:e,sighted:t})=>{if(e.kind===`failed`)return{ok:!1,reason:`the daemon could not be asked which clients draw the bar: ${e.reason}`};let{daemon:n,nativeShipped:r,clients:i}=e.value;return i.length===0?{ok:!1,reason:t.kind===`recent`?`no statusline client has drawn a bar for this daemon in the last ${300/60} minutes — run the doctor again once the bar has redrawn; if it never does, the statusLine command does not run cc-candybar`:`${uN(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:XM([...new Set(i.flatMap(e=>lN(n,r,e)))])}};function fN({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||ir(e.identity,t.value.through)):[]}function pN(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const mN={name:`daemon`,label:`daemon`,takesMark:!1,probe:({daemon:{serving:e,processes:t,read:n}})=>{let r=t.kind===`failed`?[`the process table could not be read: ${t.reason}`]:[],i=t.kind===`ok`?pN(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return XM([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=fN(e.value,n),u=XM([...l.map(e=>`the daemon ran out of memory and restarted (${e.identity}) — post-mortem: ${Object.values(e.artifacts).join(`, `)}`),...c.kind===`failed`?[`the daemon's post-mortems could not be listed: ${c.reason}`]:[],...n.kind===`failed`&&!(c.kind===`ok`&&c.value.length===0)?[`which post-mortems were read could not be read: ${n.reason}`]:[],...r,...i.map(e=>`daemon ${e.pid} (started ${e.started}, rss ${tr(e.rss)} MB${e.ppid===1?``:`, child of ${e.ppid}`}) runs beside the one serving the bar (${a}) — \`kill ${e.pid}\``),...o.kind===`measured`&&o.charge.kind===`stand-in`?[`the daemon could not read what macOS charges it (${o.charge.unread}), so its memory limit judges ${o.charge.gap===0?`RSS, which counts pages macOS has reclaimed`:`RSS less the ${tr(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&sr(o.charge.bytes,s)?[`the daemon holds ${dr(o.charge)} of its ${tr(s)} MB limit — at the limit it records a post-mortem and restarts`]:[]]);if(u.ok&&o.kind===`unmeasured`)return{ok:!0,note:`the daemon has not measured its memory yet`};let d=l[0];return u.ok||d===void 0?u:{...u,fix:{kind:`post-mortems-read`,through:d.identity}}}},hN=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function gN(e,t){let n=LM(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?zM(e.terminal):{kind:`unknown`}}function _N({identified:e,tmuxClient:t},n){let r=RM(e),i=gN(e,n),a=LM(e)===null?hN:`${hN}, and the doctor remembers it for this terminal`,o=(()=>{switch(i.kind){case`draws`:return[];case`none`:return[`${r} draws no links (OSC 8), so nothing on the bar can be clicked — run Claude Code in a terminal that draws them: ${BM}`];case`older`:return[`${r} ${i.version} draws no links (OSC 8 came in ${i.since}) — update ${r}`];case`unsaid`:return[`${r} draws links (OSC 8) since ${i.since}, and did not say which release this is — ${a}`];case`unknown`:return[`the doctor does not know whether ${r} draws links (OSC 8) — ${a}`]}})(),s=n.kind===`failed`&&i.kind!==`draws`?[`the terminals a doctor click came back from could not be read: ${n.reason}`]:[],c=i.kind===`none`||t===null||t.features.includes(`hyperlinks`)?[]:[`tmux does not pass links through to ${r} — add \`set -as terminal-features ",${t.termname}:hyperlinks"\` to tmux.conf, then detach and reattach (tmux 3.4 or later)`];return[...o,...s,...c]}const vN={name:`links`,label:`links`,takesMark:!1,probe:({sighted:e,terminal:t,clicked:n})=>{if(e.kind===`clicked`&&e.via===`link`)return{ok:!0};switch(t.kind){case`unreported`:return{ok:!1,reason:"the client reported no terminal — re-run `cc-candybar install` to stage a current client"};case`unasked`:return{ok:!1,reason:`tmux could not be asked which terminal is attached: ${t.reason}`};case`seen`:return XM(_N(t,n))}}},yN=e=>e.filter(e=>e.role===`statusline`),bN={name:`effectRefresh`,label:`effect refresh`,takesMark:!1,probe:({frames:e,claudeSettings:{origin:t,elsewhere:n},sighted:r})=>{let i=[t,...n].flatMap(({sources:e,bars:t})=>CN(e,xN(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:SN(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:uN(r));let[o,...s]=i.flatMap(e=>e.ok?[]:[e]);if(o===void 0)return a;let c=[...new Set(s.map(e=>e.reason))].filter(e=>e!==o.reason);return c.length===0?o:{...o,more:c}}},xN=e=>{let t=yN(e).map(e=>e.frame);return t.includes(`moves`)?{kind:`moving`,wearing:`the bar moves (an effect, a fade, or an animated segment)`}:t.includes(`can-move`)?{kind:`moving`,wearing:`the bar can start moving (an open menu, which flashes and closes on its own, a globals.effect rule, placements that fade in and out, or a placement with an effect of its own that is not drawn now)`}:t.includes(`still`)?{kind:`still`}:t.includes(`drawing`)?{kind:`unknown`,unseen:`the bar's latest render has not finished`}:t.length>0?{kind:`unknown`,unseen:`the bar's recent renders failed`}:e.length>0?{kind:`unknown`,unseen:"only a `cc-candybar frames` display has drawn this bar, not Claude Code's statusline"}:{kind:`none`}},SN=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function CN(e,t){let n=VM(e);if(n.kind===`present`&&n.refreshInterval===1)return{ok:!0,note:`statusLine.refreshInterval is 1 in ${n.from.path}`};switch(t.kind){case`none`:return null;case`still`:return{ok:!0};case`unknown`:return SN(t.unseen);case`moving`:break}let{wearing:r}=t;switch(n.kind){case`unread`:return{ok:!1,reason:`${r}, and Claude Code's settings could not be read: ${n.reason}`};case`absent`:return{ok:!1,reason:`${r}, and no settings file Claude Code reads here sets a statusLine (read: ${n.read.join(`, `)||`none`}) — the one that runs the bar comes from --settings, MDM or server-managed settings, which the doctor cannot read; set "refreshInterval": 1 beside its command there`};case`not-an-object`:return{ok:!1,reason:`${r}, and ${n.from.path} sets statusLine to ${JSON.stringify(n.value)}, not a statusLine object — ${n.from.scope===`user`?"re-run `cc-candybar install` to write one":`replace it there with the statusLine object that runs cc-candybar`}`};case`present`:{let{from:e,refreshInterval:t}=n,i=t===void 0?`its statusLine sets no refreshInterval, so Claude Code redraws it only on events`:typeof t==`number`&&t>1?`its statusLine redraws it only every ${t} s`:`its statusLine.refreshInterval is ${JSON.stringify(t)}, not a number of seconds Claude Code accepts (its minimum is 1)`;return WM(e)?{ok:!1,reason:`${r}, but ${i} (statusLine from ${e.path})`,fix:{kind:`claude-settings`,file:e,path:[`statusLine`,`refreshInterval`],value:1}}:{ok:!1,reason:`${r}, but ${i} — its statusLine is in ${e.scope===`managed`?`managed settings`:`the project's shared settings`}, ${e.path}: set "refreshInterval": 1 there`}}}}const wN=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function TN(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return RM(e);case`bundling`:case`unread`:case`configured`:return[DM(e.name),e.version].filter(e=>e!==null).join(` `)}}function EN(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return LM(e);case`bundling`:case`unread`:return DM(e.name);case`configured`:{let t=DM(e.name);return e.font.kind===`ok`?`${t} with ${e.font.value.font} (${e.font.value.from})`:`${t}, its font unread: ${e.font.reason}`}}}function DN(e){let t=EN(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${wN(e.glyphs)}`}}const ON={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=DN(e),r=e=>t.kind===`failed`&&n!==void 0?{ok:!1,reason:e,more:[`the mark book could not be read: ${t.reason}`]}:{ok:!1,reason:e,...n!==void 0&&{sighting:n}},i=e.terminal,a=TN(i);switch(n===void 0||t.kind===`failed`?null:t.value.nerdFont?.[n.id]??null){case`drawn`:return{ok:!0};case`boxes`:return r(`${a} draws ${wN(e.glyphs)} as boxes — set a Nerd Font as its font`);case null:break}switch(i.kind){case`unreported`:return r("the client reported no terminal — re-run `cc-candybar install` to stage a current client");case`unasked`:return r(`tmux could not be asked which terminal is attached: ${i.reason}`);case`unknown`:case`unnamed`:case`unread`:return r(`the doctor cannot read ${a}'s font`);case`bundling`:{let e=CM[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:MM(i.version,e);if(t===!0)return{ok:!0};let n=DM(i.name);return r(t===null?`${n} ships Nerd Font symbols since ${e}, and did not say which release this is`:`${a} ships no Nerd Font symbols (they came in ${e}) — update ${n}, or set a Nerd Font as its font`)}case`configured`:{if(i.font.kind===`failed`)return r(`the doctor cannot read ${a}'s font: ${i.font.reason}`);let{font:e,from:t,lacks:n}=i.font.value;return n===null?r(`${a} is set to ${e} (${t}), which is not installed — install it or set a Nerd Font`):n.length===0?{ok:!0}:r(`${a} draws with ${e} (${t}), which has no ${wN(n)} — set a Nerd Font as its font`)}}}};function kN(e){return e.join(`, `)}function AN(e){return`or set missingData: "ignore" on ${kN(e)}`}function jN(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${kN(t)}: whether the forge CLI is ready could not be asked: ${n.reason}`];if(n.value===null)return[];let{cli:r,host:i,status:a}=n.value;return a===`ready`?[]:a===`missing`?[`${kN(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${AN(t)}`]:[`${kN(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${AN(t)}`]}function MN(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${kN(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${kN(n)}: no session of this Claude Code has drawn a bar for this daemon in the last ${300/60} minutes, so whether it sends rate_limits is unseen — run the doctor again once the bar has redrawn`:`${kN(n)}: ${uN(t)}, so whether Claude Code sends rate_limits is unseen — run the doctor again once the bar has redrawn`]:r.value.includes(`missing`)&&!r.value.includes(`carried`)?[`${kN(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${kN(n)}`]:[]}const NN={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>XM([...jN(e.pullRequests),...MN(e.rateLimits,t)])};function PN({path:e,answered:t,read:n}){switch(n.kind){case`absent`:return t?[`the transcript ${e} does not exist, though Claude Code has answered in its session — the bar's session cost, metrics and activity read nothing`]:[];case`failed`:return[`the transcript ${e} cannot be read: ${n.reason}`];case`ok`:{let{lines:t,unparsed:r,whole:i}=n.value;return r===0?[]:[`${r} of the ${t} lines ${i?`in`:`in the last ${qM/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const FN=[rN,dN,mN,oN,vN,$M,eN,tN,bN,ON,NN,{name:`sessionData`,label:`session data`,takesMark:!1,probe:({transcripts:e,sighted:t})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.length===0?{ok:!1,reason:t.kind===`recent`?`no session has drawn a bar for this daemon in the last ${300/60} minutes, so no transcript was named — run the doctor again once the bar has redrawn`:`${uN(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:XM(e.value.flatMap(PN))}],IN=FN.filter(e=>e.takesMark);function LN(e){return FN.map(t=>({check:t,verdict:t.probe(e)}))}function RN(e){return FN.find(t=>t.name===e)}const zN=`${X}doctor.`;function BN(e){let t=`${zN}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function VN(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?LM(e.identified):null,i=t.kind===`failed`?`unread`:r===null?`-`:t.value.includes(r)?`yes`:`no`;return`tmuxLinks=${n===null?`-`:n.features.includes(`hyperlinks`)?`yes`:`no`} clicked=${i}`}function HN(e,t){let n=e.kind===`seen`?e.tmuxClient:null;return`cols=${t.kind===`failed`?`failed widthOf=-`:`${t.value.columns??`-`} widthOf=${t.value.of.kind}`} clientUtf8=${n===null?`-`:n.utf8?`yes`:`no`}`}function UN(e){if(e.kind===`failed`)return`clients=unasked`;let{daemon:t,clients:n}=e.value;return`clients=${n.map(e=>{if(e.kind===`unreported`)return`unreported/-/-`;let{bundle:n,source:r}=sN(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const WN=e=>`${e>=0?`+`:``}${tr(e)}`;function GN({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${pN(e,t.value).map(e=>e.pid).join(`,`)||`-`}`;if(e.kind===`failed`)return`${r} memory=unasked postMortems=unasked`;let{memory:i,limit:a,postMortems:o}=e.value,s=o.kind===`failed`||n.kind===`failed`?`unread`:`${fN(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${fr(i.charge)}${i.charge.kind===`stand-in`?`(${WN(-i.charge.gap)})`:``}:${tr(i.charge.bytes)}`}/${tr(a)} postMortems=${s}`}function KN(e){return`data=pr:${(()=>{if(e.pullRequests.kind===`unneeded`)return`-`;let t=e.pullRequests.fact;if(t.kind===`failed`)return`failed`;if(t.value===null)return`no-forge`;let{status:n}=t.value;return typeof n==`string`?n:`logged-out`})()},rateLimits:${(()=>{if(e.rateLimits.kind===`unneeded`)return`-`;let t=e.rateLimits.fact;if(t.kind===`failed`)return`failed`;let n=e=>t.value.filter(t=>t===e).length;return`${n(`carried`)}/${n(`missing`)}/${n(`unanswered`)}`})()}`}function qN(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>JN(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${as(i)}`;let a=yN(r.flatMap(e=>e.bars));return`frames=${yM.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${as(i)}`}function JN(e){let t=VM(e);switch(t.kind){case`unread`:return`failed`;case`absent`:case`not-an-object`:return t.kind;case`present`:return`${t.from.scope}:${t.refreshInterval===void 0?`-`:JSON.stringify(t.refreshInterval)}`}}function YN(e){let t=HM(e,ZM);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${as(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function XN(e){if(e.kind===`failed`)return`transcripts=failed`;let t=t=>e.value.filter(e=>e.read.kind===t).length,n=e.value.reduce((e,t)=>e+(t.read.kind===`ok`?t.read.value.unparsed:0),0);return`transcripts=${t(`ok`)}/${t(`absent`)}/${t(`failed`)} unparsed=${n}`}function ZN(e,t){if(e.kind===`none`)return`glyphs=- terminal=- font=- mark=-`;let{glyphs:n,terminal:r}=e,i=[...n].map(e=>e.codePointAt(0).toString(16)),a=(()=>{switch(r.kind){case`unreported`:case`unasked`:return r.kind;case`unknown`:return`unknown:${JSON.stringify(r.called)}`;case`unnamed`:return`unnamed:${JSON.stringify(r.term)}`;case`bundling`:case`unread`:case`configured`:return`${r.name}@${r.version??`-`}`}})(),o=(()=>{if(r.kind!==`configured`)return`-`;if(r.font.kind===`failed`)return`failed`;let{font:e,lacks:t}=r.font.value;return`${JSON.stringify(e)}:${t===null?`not-installed`:`lacks${t.length}`}`})(),s=DN(e),c=t.kind===`failed`?`unread`:s===void 0?`-`:t.value.nerdFont?.[s.id]??`-`;return`glyphs=${i.join(`,`)} terminal=${a} font=${o} mark=${c}`}function QN(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function $N(e){return e.flatMap(({check:e,verdict:t})=>{let n=BN(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:h_},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:QN(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?h_:m_},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const eP={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function tP(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries(eP).map(([t,n])=>[`${e}${t}`,n]))}}const nP=`armed`,rP=`disarmed`,iP=`.armed`,aP=e=>e.endsWith(iP);function oP(e,t,n){let r=`${e}${iP}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${nP}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:nP},[a]:{set:r,to:rP},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:rP}},disarm:a}}const sP=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function cP(e){return typeof e==`string`&&sP.test(e)?{kind:`line`,line:e}:{kind:`refused`,reason:`a slash command is "/" then its name, e.g. "/compact" or "/model opus", on one line with no control characters, got ${JSON.stringify(e)}`}}function lP(e){let t=cP(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const uP=[`/compact`,`/model`],dP=`/clear`;function fP(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=oP(`${e}clear`,{arm:dP,confirm:`${dP} ✓ confirm`},[n]);return{template:uP.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${uA} }}`,actions:{...Object.fromEntries(uP.map(e=>[t(e),{slash:lP(e)}])),...r.actions,[n]:{slash:lP(dP)}},variables:r.variables,disarm:r.disarm}}const pP=Array.from({length:10},(e,t)=>(t+1)*1e5),mP=pP[0],hP=pP[pP.length-1];function gP(e){let t;try{t=eo(e)}catch(e){return I(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?P(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=mP&&n<=hP?P(n):I(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${mP}–${hP} tokens)`)}function _P(e,t){let n=Math.min(t??hP,hP),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:pP.filter(e=>e<r).at(-1)??0,higher:pP.find(e=>e>r&&e<=n)??0}}function vP(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${uA} }}{{ if gt .autocompact.lower 0 }} {{ action (printf "${e}%d" .autocompact.lower) "−" }}{{ end }}{{ if gt .autocompact.higher 0 }} {{ action (printf "${e}%d" .autocompact.higher) "+" }}{{ end }}{{ if gt .autocompact.window 0 }} {{ action "${e}auto" "↺" }}{{ end }}{{ end }}{{ end }}`,bg:`{{ if ne .autocompact.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .autocompact.window 0) (ne .autocompact.error "") }}`,actions:{[`${e}auto`]:{slash:lP(`/autocompact auto`)},...Object.fromEntries(pP.map(t=>[`${e}${t}`,{slash:lP(`/autocompact ${t}`)}]))}}}const yP=e=>`{{ if ge ${e} 1000000 }}{{ printf "%.1f" (divf ${e} 1000000) }}M{{ else if ge ${e} 1000 }}{{ printf "%.1f" (divf ${e} 1000) }}K{{ else }}{{ ${e} }}{{ end }}`,bP=`${X}edit`,xP=`${X}toolbar`,SP=tP(X),CP=`${X}commands`,wP=fP(`${CP}.`),TP=`${X}autocompact`,EP=vP(`${TP}.`,yP),DP=e=>({kind:`segment`,name:e}),OP=`${X}tab`,kP=e=>`${OP}.${e}`,AP=e=>`${kP(e)}.toggle`,jP=e=>({variable:OP,key:OP,member:e}),MP=`${X}save`,NP=`${X}preset.save`,PP=`${X}preset.delete`,FP=e=>`${X}${e}`,IP=e=>`${X}apply.${e}`,LP=e=>`${X}reset.${e}`,RP=`${X}themeDefault.save`,zP=`${X}themeDefault.differs`,BP=`${X}themeDefault.theme`,VP={when:`{{ .${zP} }}`,template:`{{ action "${RP}" (printf "⤓ default for %s" .${BP}) }} {{ swatch "${IP(`theme`)}" .${BP} }}`},HP=`${X}resetAll`,UP=`${Cj}.toggle`,WP=`${X}undo`,GP=`${X}back`,KP=`${GP}.step`,qP=`${X}navigation.back`,JP=GP,YP={template:`{{ if gt .${qP} 0 }}{{ action "${GP}" "◁" }}{{ else }}{{ fg (${dM}) "◁" }}{{ end }}`},XP=`${X}redo`,ZP=`${X}doctor`,QP=`${ZP}.run`,$P=e=>`${ZP}.fix.${e}`,eF=(e,t)=>`${ZP}.mark.${e}.${t}`,tF=e=>`${ZP}.${e}`,nF={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},rF=wA(`${X}pickers`),iF=e=>`${X}${e}`,aF=e=>`${iF(e)}.toggle`,oF=e=>eM(e)?wA(`${X}${e}Pickers`):rF,sF=e=>{let t=oF($j[Zj[e].beside]);return{variable:t,key:t,member:e}},cF={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${PP}" (printf "🚮 delete %s" .${Sy.preset.effectiveVar}) }}`}},lF=(e,t)=>`${X}list.${e}.${t}`,uF=e=>`${X}resettable.${e}`,dF=e=>e.length===0?`false`:`(or ${e.map(e=>`.${uF(e)}`).join(` `)})`,fF=Fv.map(e=>[Pv[e].setting,e]),pF={variables:{},actions:{},segments:{}},mF=Object.fromEntries(fF.map(([e,t])=>[e,zj(`${X}help.${e}`,lM[t],[],pF)])),hF=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],gF=e=>{let t=t=>`.${zv(e,t)}`,n=hF.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if .${Sy[Pv[e].setting].effectiveVar} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},_F=`${X}fps`,vF=`{{ if eq .${Lv(`by`)} "feed" }}{{ printf "%2d" (int .${Lv(`fps`)}) }} fps{{ else }}${`polled`.padStart(6)}{{ end }}`,yF=Object.fromEntries(fF.map(([e,t])=>[e,gF(t)])),bF=Object.keys(Sy).map(e=>{let t=Sy[e],n=zA(t.configKey),r=IA({label:t.label,domain:n},t.sessionKey,t.effectiveVar,IP(e),oF($j[e]));return{...t,name:e,control:r,beneath:t.previews.map(e=>cF[e])}}),xF=e=>bF.filter(t=>$j[t.name]===e),SF=e=>bF.filter(t=>tM($j[t.name],e)),CF=e=>t=>`(print ${ki(t)} (ternary ${ki(` •`)} "" ${dF(SF(e).map(e=>e.name))}))`,wF=e=>Qj.filter(t=>Zj[t].beside===e),TF=e=>xF(e).flatMap(e=>[LF(e),...[mF[e.name]].filter(e=>e!==void 0),...wF(e.name).map(e=>wi(iF(e),sF(e),WF(e),`drop`))]);new Set(bF.flatMap(e=>[e.sessionKey,e.configKey]));const EF=oP(HP,{arm:`⟲`,confirm:`⟲ reset all?`},bF.map(e=>LP(e.name))),DF=[`unsaved`,`history.undo`,`history.redo`],OF=e=>`${X}${e}`,kF=OF(`unsaved`),AF=(e,t)=>({body:t,shown:`(gt .${OF(e)} 0)`}),jF=[AF(`unsaved`,`{{ action "${MP}" (printf "💾 save %d" .${kF}) }}`),AF(`history.undo`,`{{ action "${WP}" "↶" }}`),AF(`history.redo`,`{{ action "${XP}" "↷" }}`),{body:EF.template,shown:`(or ${dF(bF.map(e=>e.name))} ${EF.armed})`}],MF={when:`{{ or ${jF.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+jF.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},NF=[{step:EF,place:`door`},{step:wP,place:`session`}],PF=e=>e.map(e=>e.step.disarm),FF=PF(NF),IF=PF(NF.filter(e=>e.place!==`door`));function LF(e){let t=FP(e.name);return e.control.kind===`inline`?DP(t):wi(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>DP(lF(e.name,n)))},`drop`)}function RF(e){return e===Cj}function zF(e){let t=DP(Cj);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[zF(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}return e.kind===`container`&&e.when===void 0?{...e,children:[t,...e.children]}:{kind:`container`,direction:`horizontal`,children:[t,e]}}function BF(e){return VF(e)>0?e:zF(e)}function VF(e){let t=0;for(let n of E_(e))n.kind===`segment`&&RF(n.name)&&(t+=1);return t}function HF(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&RF(e.name)||e.opens!==void 0&&HF(e.opens.body,!0):e.children.some(e=>HF(e,n))}const UF={door:{direction:`horizontal`,content:[DP(JP)],after:[DP(bP),DP(MP)]},session:{direction:`vertical`,content:[DP(xP),{kind:`container`,direction:`horizontal`,children:[DP(CP),DP(TP)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[DP(NP)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[DP(ZP),...FN.map(e=>DP(tF(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[DP(RP)]},toggles:{direction:`horizontal`,content:[],after:[]}};function WF(e){let{direction:t,content:n,after:r}=UF[e];return{kind:`container`,direction:t,children:[...n,...TF(e),...r]}}function GF(e){return e.kind===`segment`?RF(e.name)?{kind:`container`,direction:`horizontal`,children:[wi(e.name,Tj,qF,`above`),DP(_F)]}:e:JF(e)}function KF(){return{kind:`container`,direction:`vertical`,children:[WF(`door`),{kind:`container`,direction:`horizontal`,children:Yj.map(({member:e})=>wi(kP(e),jP(e),WF(e),`drop`))}]}}const qF=KF();function JF(e){return{...e,children:e.children.map(e=>GF(e))}}function YF(e){let t={variables:{[Cj]:Ai(Cj,yi)},actions:{[UP]:N(Cj,wj),[Cj]:{do:[UP,...FF]},[QP]:{doctor:`run`},...SP.actions,...wP.actions,...EP.actions,[MP]:{save:!0},[WP]:{undo:!0},[KP]:{back:!0},[GP]:{do:[KP,...FF]},[XP]:{redo:!0},[NP]:{preset:`save`},[RP]:{themeDefault:`save`},[PP]:{preset:`delete`,name:`{{ .${Sy.preset.effectiveVar} }}`}},segments:{[Cj]:{template:`{{ $door := ${Oi(Cj,ki(e),ki(`✖`))} }}{{ if ${Ei(Tj)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`},[_F]:{template:vF},[xP]:{template:SP.template},[CP]:{template:wP.template,when:wP.when},[TP]:{template:EP.template,bg:EP.bg,when:EP.when},[JP]:YP,[MP]:MF,[RP]:VP,[NP]:{template:`{{ action "${NP}" "+ preset" }}`},[ZP]:{template:`{{ action "${QP}" "🩺 doctor" }}`},[bP]:{template:`{{ action "${Oj}" "✎ arrange" "✎ done" }}`}}};t.variables[zP]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[BP]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[qP]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of DF)t.variables[OF(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[OP]=Ai(OP,`session`);for(let{member:e,label:n}of Yj){t.actions[AP(e)]=N(OP,e),t.actions[kP(e)]={do:[AP(e),...IF]};let r=CF(e);t.segments[kP(e)]={template:`{{ ${Oi(kP(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,wP.variables,EF.variables),ZF(t),XF(t),t}function XF(e){for(let t of FN){let n=BN(t.name),r=$P(t.name);for(let t of Object.values(n))e.variables[t]={kind:`state`,key:t,default:``};e.actions[r]={doctor:`fix`,check:t.name};let i=t.takesMark?KM:[];for(let n of i)e.actions[eF(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${eF(t.name,e)}" "${nF[e]}" }}`).join(``);e.segments[tF(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ if ne .${n.reason} "" }} — {{ .${n.reason} }}{{ end }}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${m_}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function ZF(e){for(let t of bF){Object.assign(e.actions,t.control.actions);let n=LP(t.name);e.actions[n]={reset:t.configKey},e.variables[uF(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${uF(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[FP(t.name)]={template:`${t.control.template}${yF[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[lF(t.name,r)]=n})}Object.assign(e.actions,EF.actions),Object.assign(e.variables,pF.variables),Object.assign(e.actions,pF.actions),Object.assign(e.segments,pF.segments);for(let t of Qj){let n=sF(t);e.actions[aF(t)]=N(n.key,n.member),e.segments[iF(t)]={template:`{{ action "${aF(t)}" ${CF(t)(Zj[t].trigger)} }}`}}}function QF(e){let{variables:t,actions:n}=Lj();Object.assign(e.variables,t),Object.assign(e.actions,n)}function $F(e){let t=YF(e.globals.menuGlyph??`🍫`);QF(t);let n={...e.presets},r=[];for(let t of $b(e.presets)){let{node:i}=nx(e,t),a=GF(BF(i));r.push(a),n[t]={...tx(e.presets,t),root:a}}let i=fA(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const eI=`${_A}live`,tI=[`☐ live`,`☑ live`],nI=`${_A}done`,rI=`${_A}cancel`,iI=`${_A}rewind`,aI=`${_A}changes`,oI=`(gt .${aI} 0)`,sI=`(or ${oI} (gt .${kF} 0))`,cI={variable:eI,key:eI,member:`open`};function lI(e){return`${_A}configuring.p${e}`}function uI(e){return`and ${Ei(Mj)} (not ${Ei(cI)}) (ne .${lI(e)} "true")`}function dI(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${Dj} "${Ci(e)}")`).join(` `)} false }}`}}function fI(e,t,n){return`{{ if ${uI(e)} }}${t}{{ else }}${n}{{ end }}`}const pI=`{{ and ${Ei(Mj)} .preset.customized }}`,mI=yA;function hI(e){return new Map([...sx(e),..._I(e)])}const gI=`${_A}addable`;function _I(e){return new Map([[gI,{members:Object.keys(e.segments).filter(e=>!mI(e)),library:{groups:bj.map(e=>({id:e,label:xj[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function vI(e,t,n){return n.segments[e]={template:t,when:Nj,bg:Vj},{kind:`segment`,name:e}}function yI(e,t,n){let r=`${_A}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Yh}`}) (action "${r}" "✖") }}`}function bI(e){return`{{ if ${Ei(Mj)} }}${e}{{ end }}`}function xI(e,t){return e.reduce((e,t)=>`{{ if and ${Ei(Mj)} ${Ei(t)} }}true{{ else }}${e}{{ end }}`,t)}function SI(e){return e.flatMap(e=>[...E_(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function CI(e,t,n){return`${Aj}${e}.${t}.${n}`}function wI(e,t,n,r){let i=S_(n),a=`${_A}${e.presetIdent}`,o=jj(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=wA(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:yi},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:Dj,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=CI(e.presetIdent,i,r),l=`${Aj}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:G_(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=IA(PA(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};e.artifacts.segments[d]={template:f.template};let p=f.list.rows.map((t,n)=>{let r=`${d}.list.${n}`;return e.artifacts.segments[r]={template:t},{kind:`segment`,name:r}});return wi(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${qj}" }}`,ref:{variable:Dj,key:Dj,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const TI=`${_A}label:`;function EI(e){if(e.startsWith(TI)){let t=e.slice(TI.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function DI(e,t,n,r){let{artifacts:i}=n,a=S_(e),o=`${TI}${a}:${e.name}`;i.segments[o]={template:`{{ "${Ci(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=Object.fromEntries(B_.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...wi(o,r.ref,r.body,`drop`,xI([r.ref],`{{ ${uI(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(B_.map(e=>[e,r.drafts[e]]))}}function OI(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${_A}${i}.insert.${t}`,s=`${_A}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:gI,anchor:n,relation:r};let c=SA(o),l=CA(s,o,void 0),u=EA(l),d=TA(l,c);return a.variables[l]={...Ai(l,yi),within:[Mj]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=N(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${Ei({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Yh}`}) $m }}{{ end }}`}}function kI(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!mI(e.name)),i=e=>kI(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=T_(o,i);if(mI(o.name)){n.push(s);continue}let c=S_(o),l=a===r?[OI(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=OI(t,u,c,`after`),f=yI(t,u,c),p=t.segments[o.name],m=wI(t,u,o,V_(p)),h=bI(f),g=bI(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>vI(e.host,e.template,t.artifacts)),{...DI(o,p,t,m),lead:h,trail:g},{...s,when:fI(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},vI(d.host,d.template,t.artifacts)]};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[_]}:_)}return{...e,children:n,...e.when!==void 0&&{when:xI(SI(n),fI(t.presetIdent,`true`,e.when))}}}function AI(e,t,n,r,i,a,o){let s=`${_A}${t}.resetLayout`,c=`${_A}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:pI},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},jI(e,o)]}}function jI(e,t){if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t]};let n=e.children.at(-1);return e.direction===`vertical`&&n!==void 0&&(n.kind===`segment`||n.when===void 0)?{...e,children:[...e.children.slice(0,-1),jI(n,t)]}:{...e,children:[...e.children,t]}}function MI(e,t,n,r,i,a){let{node:o}=nx(e,t),s={presetIdent:pA(t),rootKey:pj(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=kI(o,s);return n.variables[lI(s.presetIdent)]=dI(s.configured),AI(c,s.presetIdent,s.rootKey,n,r,i,a)}function NI(e){let t={variables:{},actions:{},segments:{}},n=zj(`${_A}help`,cM,[Mj],t);t.variables[eI]=Ai(eI,yi),t.actions[eI]=N(eI,cI.member),t.segments[eI]={template:Di(eI,...tI),when:Nj};let r={kind:`segment`,name:eI},i=n;t.variables[aI]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[nI]={do:[MP,Oj]},t.segments[nI]={template:`{{ if ${sI} }}{{ action "${nI}" "✓ save" }}{{ else }}{{ action "${nI}" "✓ done" }}{{ end }}`,when:Nj},t.actions[iI]={rewind:!0},t.actions[rI]={do:[iI,Oj]},t.segments[rI]={template:`{{ action "${rI}" "↩ cancel" }}`,when:`{{ and ${Ei(Mj)} ${oI} }}`};let a=[{kind:`segment`,name:nI},{kind:`segment`,name:rI}],o={...e.presets},s=[];for(let n of $b(e.presets)){let c=MI(e,n,t,a,r,i);s.push(c),o[n]={...tx(e.presets,n),root:c}}let c=fA(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function PI(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function FI(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function II(e,t,n){let r=w_(e,new Set(n.map(C_).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const LI=/^-?\d+$/;function RI(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function zI(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!LI.test(t))return{ok:!1,reason:`${e} must be an integer, got "${t}"`};let n=t[0]===`-`,r=(n?t.slice(1):t).replace(/^0+/,``);return r===``?{ok:!0,value:`0`}:{ok:!0,value:n?`-${r}`:r}}}function BI(e,t,n){return r=>r?LI.test(r)?{ok:!0,value:String(Math.max(e,Math.min(t,parseInt(r,10))))}:{ok:!1,reason:`${n} must be an integer, got "${r}"`}:{ok:!1,reason:`${n} value is required`}}function VI(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!LI.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i}}return{kind:`int`}}function HI(e){return e===`config`?`set-config`:`set-state`}function UI(e,t,n){return t.kind===`int`?zI(`menu page "${e}"`):t.kind===`range`?BI(t.min,t.max,`${n} stepper "${e}"`):RI(t.allowed,`${n} "${e}"`,HI(n))}function WI(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:VI(e,n,t)}))}function GI(e,t,n,r){let i=new Map(Object.entries(e)),a=new Map,o=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of n)if(o.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let s=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...n];for(let{key:t,spec:n}of WI(s,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,UI(t,n,r)),n.kind===`range`&&a.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>a.get(e)??null}}function KI(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};GI(e,[o],[],t),r.push(o),i++;let s=!0;return()=>{s&&(s=!1,r.splice(r.indexOf(o),1),i++)}},gateFor(o){let s=a.get(o);if(s?.epoch===i)return s.gate;let c=GI(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const qI=KI({},`config`,eL);function JI(e,t){return qI.register(e,t)}function YI(e){return qI.gateFor(e)}function XI(e,t){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:lx(e.from,t).members}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[PI({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[PI({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:lx(e.insertSegmentFrom,t).members.map(t=>PI({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function ZI(e,t){let n=cj(e).get(t);return n===void 0?null:String(n)}function QI(e){let t=new Set;for(let n of Object.values(e.actions)){`reset`in n&&t.add(n.reset);let e=`persist`in n?_j(n.persist):null;e?.scope===`preset-root`&&t.add(pj(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function $I(e){let t=hI(e);return[...QI(e),...Object.values(e.actions).flatMap(e=>XI(e,t))]}function eL(e){return WI($I(e),`config`)}function tL(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:iL(t.segments,nL(t.segments,e.segments??{})),root:Yb(e.root??Hb,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:iL(t.presets,rL(t.presets,e.presets??{})),themeDefaults:iL(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function nL(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.settings===void 0?n:{...n,settings:{...e[t]?.settings,...n.settings}}]))}function rL(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.globals===void 0?n:{...n,globals:{...e[t]?.globals,...n.globals}}]))}function iL(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function aL(e,t,n,r){return n.cache===void 0?(e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${M_.join(`, `)})`,line:G(e.source,t.split(`.`))}),null):cL(e,`${t}.cache`,n.cache)}function oL(e){return{required:!0,json:lL(),parse:(t,n,r,i)=>aL(t,n,i,e)??void 0}}const sL={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&dL(n)?{ttl:n}:mv(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${K(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return mv(e,t,`cache.watch_file must be a path string, got ${K(n)}`);let r=Ev(`cache.watch_file`,n);return r===null?{watch_file:n}:mv(e,t,r)}},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:mv(e,t,`cache.depends_on must be an array of variable-name strings, got ${K(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:mv(e,t,`cache.key must be a non-empty template string, got ${K(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:mv(e,t,`cache.never must be the literal boolean true, got ${K(n)}`)}}};function cL(e,t,n){return hv(e,sL,t,n)}function lL(){return Nv(sL)}const uL=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function dL(e){return uL.test(e)}const fL=new Map([[`session.budget.amount`,{segment:`session`,setting:`budget`}],[`session.budget.warningThreshold`,{segment:`session`,setting:`warnAt`}],[`today.budget.amount`,{segment:`today`,setting:`budget`}],[`today.budget.warningThreshold`,{segment:`today`,setting:`warnAt`}],[`block.budget.heatThreshold`,{segment:`block`,setting:`warnAt`}],[`block.budget.warningThreshold`,{segment:`block`,setting:`errorAt`}],[`weekly.budget.heatThreshold`,{segment:`weekly`,setting:`warnAt`}],[`weekly.budget.warningThreshold`,{segment:`weekly`,setting:`errorAt`}],[`burn.eta.errorMinutes`,{segment:`burnrate`,setting:`errorWithin`}],[`burn.eta.warnMinutes`,{segment:`burnrate`,setting:`warnWithin`}]]);function pL(e){return`it became the "${e.setting}" setting of each "${e.segment}" placement — set it on the placement where a row places "${e.segment}" ({ seg: "${e.segment}", settings: { ${e.setting}: <value> } }), or redeclare segments.${e.segment}.settings.${e.setting} with the default every placement should start from`}function mL(e){let t=fL.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${pL(t)}`}function hL(e){let t=fL.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${pL(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const gL=new Map([[`git.timeSinceCommit`,`the payload stores the commit's date as "git.committedAt" (epoch seconds), and the bundled template variable "git.timeSinceCommit" computes its age at the draw: drop this declaration`],[`block.etaMinutes`,`the bundled template variable "block.etaMinutes" computes it at the draw: drop this declaration`],[`weekly.etaMinutes`,`the bundled template variable "weekly.etaMinutes" computes it at the draw: drop this declaration`]]),_L=new Map([[`branch`,{read:`.git.branch`,declare:{kind:`input`,path:`git.branch`,default:``},note:`when HEAD is on no branch it reads "detached", where this kind read ""`}],[`sha`,{read:`.git.sha`,declare:{kind:`input`,path:`git.sha`,default:``}}],[`dirty`,{read:`(ne .git.status "clean")`,declare:{kind:`template`,template:`{{ ne .git.status "clean" }}`,type:`boolean`}}],...[`ahead`,`behind`,`stash`].map(e=>[e,{read:`.git.${e}`,declare:{kind:`input`,path:`git.${e}`,type:`number`,default:0}}])]);function vL(e){let t=e=>typeof e==`string`&&e.includes(`"`)&&!e.includes(`'`)?`'${e}'`:JSON.stringify(e);return`{ ${Object.entries(e).map(([e,n])=>`${e}: ${t(n)}`).join(`, `)} }`}function yL(e){let t=`kind "git" is retired: every git fact is an input over the payload's git lane, which the bundled default already declares — drop this declaration and`,n=typeof e.field==`string`?_L.get(e.field):void 0;if(n===void 0){let e=[..._L.values()].map(({read:e})=>e);return`${t} read whichever of ${e.slice(0,-1).join(`, `)} or ${e.at(-1)} it stood for, where it was read`}let r=n.note===void 0?``:` (${n.note})`;return`${t} read ${n.read} where it was read${r}, or declare ${vL(n.declare)} under a name of your own`}function bL(e,t,n){if(n===void 0)return{};if(!sv(n))return e.issues.push({path:t,message:`${t} must be an object, got ${cv(n)}`,line:G(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=gv(e,WL,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function xL(){return{required:!0,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.value;if(typeof i!=`string`&&typeof i!=`number`&&typeof i!=`boolean`){e.issues.push({path:`${t}.value`,message:`literal value must be string|number|boolean, got ${cv(i)}`,line:G(e.source,t.split(`.`))});return}return i}}}function SL(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return rv(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const CL={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:mv(e,t,`parse.text must be the literal boolean true, got ${K(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?wL(e,t,n):mv(e,t,`parse.regex must be a pattern string, got ${K(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:mv(e,t,`parse.json must be the literal boolean true, got ${K(n)}`)}}};function wL(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return mv(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:mv(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function TL(){return{required:!1,json:Nv(CL),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:G(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:hv(e,CL,`${t}.parse`,r.parse)??void 0)}}function EL(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>sv(r.parse)&&`json`in r.parse?DL(e,t,r.default):iv(e,t,r,`default`)}}function DL(e,t,n){if(n!==void 0)return OL(n)?n:mv(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${K(n)}`)??void 0}function OL(e){return e!==null&&kL(e)}function kL(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(kL);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(kL)}default:return!1}}const AL={value:xL(),default:bv()};function jL(){let e=Tv();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:gL.get(a);return o===void 0?a:mv(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const ML={path:jL(),type:Ov([`string`,`number`,`boolean`]),default:SL()},NL={name:Tv(),default:bv()},PL={path:Dv(),readMode:Ov([`whole`,`first-line`]),parse:TL(),cache:oL(`file`),default:EL()},FL={command:Tv(),parse:TL(),cache:oL(`shell`),default:EL()};function IL(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const LL={template:Tv(),type:Ov([`string`,`number`,`boolean`]),default:SL()},RL=IL(`a template variable recomputes whenever a variable it reads changes`),zL={layout:Tv(),default:bv()},BL=IL(`a time variable reads the instant its render is drawn at`),VL={key:Tv(),default:bv()},HL=`kind`;function UL(e,t,n={}){return{..._v(HL,e,t),parse:(r,i,a)=>{uv(r,n,i,a);let o=dv(r,t,i,a);return o===null?null:{kind:e,...o}}}}const WL={tag:HL,noun:`source kind`,memberNoun:`variable`,arms:{literal:UL(`literal`,AL),input:UL(`input`,ML),env:UL(`env`,NL),file:UL(`file`,PL),shell:UL(`shell`,FL),template:UL(`template`,LL,RL),time:UL(`time`,zL,BL),state:UL(`state`,VL)},retired:{git:yL}};function GL(){return Mv(WL)}function KL(){return{type:`object`,additionalProperties:GL()}}const qL=new Map([[`gitTaculous`,{kind:`built-in`,to:`gitaculous`}],[`git`,{kind:`built-in`,to:`gitaculous`}],[`settings.menu`,{kind:`built-in`,to:`candybar.menu`}],[`ticket`,{kind:`plugin`,to:`plugins.lit.ticket`,source:`promptctl/links-issue-tracker`}],[`ceiling`,{kind:`removed`}]]);function JL(e){let t=qL.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`;case`removed`:return` (the built-in segment "${e}" was removed: the program it showed draws it through a cc-candybar plugin of its own now — delete this reference, or place that plugin's segment)`}}const YL=/^[A-Za-z_][A-Za-z0-9_]*$/,XL={pattern:YL.source},ZL={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},QL={type:`object`,additionalProperties:!1,required:[`label`,`domain`,`default`],properties:{label:{type:`string`,pattern:`^[^\\n\\r]+$`},domain:{anyOf:[{const:`bool`},{type:`array`,items:{type:`string`,pattern:`^[^/\\n\\r]+$`},minItems:1,uniqueItems:!0},{type:`object`,additionalProperties:!1,required:[`min`,`max`],properties:{min:{type:`integer`},max:{type:`integer`},step:{type:`integer`,minimum:1},atLeast:{type:`string`,...XL}}}]},default:ZL}},$L=[`label`,`domain`,`default`],eR=[`min`,`max`,`step`,`atLeast`];function tR(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function nR(e,t,n){if(n===`bool`)return`bool`;if(Array.isArray(n)){let r=n.filter(e=>typeof e==`string`);if(n.length===0||r.length!==n.length)return tR(e,t,`a list domain must be a non-empty list of words, got ${JSON.stringify(n)}`);if(new Set(r).size!==r.length)return tR(e,t,`a list domain names each word once, got ${JSON.stringify(n)}`);let i=r.filter(e=>e===``||e.includes(`/`)||/[\n\r]/.test(e));return i.length>0?tR(e,t,`a list domain's words must be non-empty, slash-free, and newline-free — configure mode writes each on the set-state wire — got ${JSON.stringify(i)}`):r}if(sv(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!eR.includes(e)).length===0&&Number.isInteger(r)&&Number.isInteger(i)&&r<=i&&Number.isInteger(a)&&a>=1&&(o===void 0||typeof o==`string`)?{min:r,max:i,step:a,...o!==void 0&&{atLeast:o}}:tR(e,t,`a range domain is { min, max, step?, atLeast? } with integers min ≤ max, a whole step ≥ 1, and atLeast naming another range setting, got ${JSON.stringify(n)}`)}return tR(e,t,`domain must be "bool", a list of words, or { min, max }, got ${K(n)}`)}function rR(e,t,n){if(!sv(n))return tR(e,t,`${t} must be { label, domain, default }, got ${cv(n)}`);for(let r of Object.keys(n))$L.includes(r)||tR(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${$L.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||tR(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${K(r)}`);let a=nR(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!iR(n.default)||!W_(o,n.default)?tR(e,`${t}.default`,`default must be ${J_(o)}, got ${K(n.default)}`):o}function iR(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const aR={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${R_}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function oR(e){return B_.includes(e)}function sR(){return{required:!1,json:{type:`object`,propertyNames:{...XL,not:{enum:[...B_]}},additionalProperties:QL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!sv(i))return tR(e,a,`${a} must be an object of name → { label, domain, default }, got ${cv(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!YL.test(t)){tR(e,`${a}.${t}`,`setting name "${t}" is read as .settings.${t} in a template, so it must be an identifier (letters, digits, _; not starting with a digit)`);continue}if(oR(t)){tR(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${aR[t]}`);continue}let r=rR(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const cR=vA.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function lR(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${cR})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!yA(i)?i:tR(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${vA.map(e=>`"${e}"`).join(`, `)} namespaces, got ${K(i)}`)}}}function uR(){return{required:!1,json:{type:`object`,propertyNames:XL,additionalProperties:ZL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!sv(i))return tR(e,a,`a placement's "settings" must be an object of setting name → value, got ${cv(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))iR(n)?o[t]=n:tR(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${cv(n)}`);return o}}}function dR(e){return new Set(Object.keys(e.segments).filter(e=>!yA(e)))}function fR(e,t,n){if(t===void 0)return{};if(!sv(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${cv(t)}`,line:G(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=lv(e,n.has(i)?vR:_R,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function pR(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?mv(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own${JL(t.slice(9))}`)??void 0:nv(e,t,r,n)??void 0}}function mR(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${K(i)}`,line:G(e.source,[...t.split(`.`),n])})}}}}function hR(){return{required:!1,json:KL(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return bL(e,`${t}.${n}`,i)}}}const gR={template:pR(),description:bv(),group:Ov(yj),width:mR(),justify:Ov(Y_),truncate:Ov(X_),bg:bv(),fg:bv(),when:bv(),palette:wv(),vars:hR(),settings:sR(),missingData:Ov(F_)},_R={noun:`segment key`,fields:gR},vR={noun:`segment key`,fields:{...gR,template:bv()}},yR=`#/definitions/LayoutNode`,bR={kind:`container`,direction:`vertical`,children:[]};function xR(e){return{required:!0,json:{const:e},parse:()=>e}}function SR(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${K(i)}`,line:G(e.source,[`root`])}),``)}}}function CR(){return{required:!0,json:{enum:[...b_]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&b_.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${b_.join(`, `)} (got ${JSON.stringify(i)})`,line:G(e.source,[`root`])}),`vertical`)}}}function wR(e){return{required:!0,json:{type:`array`,items:{$ref:yR}},parse:(t,n,r,i)=>{let a=i[r];return Array.isArray(a)?a.map((i,a)=>e(t,`${n}.${r}[${a}]`,i)):(t.issues.push({path:`${n}.${r}`,message:`a container must have a "children" array of layout nodes, got ${cv(a)}`,line:G(t.source,[`root`])}),[])}}}const TR={noun:`layout-node key`,fields:{kind:xR(`segment`),name:SR(),when:bv(),id:lR(),settings:uR()}},ER=()=>Ov(Eh),DR={noun:`layout-node key`,fields:{kind:xR(`container`),direction:CR(),children:wR(vv(()=>MR)),when:bv(),distribution:ER()}};function OR(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${K(i)}`,line:G(e.source,[`root`])}),``)}}}const kR={noun:`layout-node key`,fields:{seg:OR(),when:bv(),id:lR(),settings:uR()}},AR={noun:`layout-node key`,fields:{h:wR(vv(()=>MR)),when:bv(),distribution:ER()}},jR={noun:`layout-node key`,fields:{v:wR(vv(()=>MR)),when:bv(),distribution:ER()}},MR=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:G(e.source,[`root`])}),bR):{kind:`segment`,name:n};if(!sv(n))return e.issues.push({path:t,message:`a layout node must be a string (segment name) or an object with "kind" / "seg" / "h" / "v", got ${cv(n)}`,line:G(e.source,[`root`])}),bR;if(n.kind===`container`)return lv(e,DR,t,n)??bR;if(n.kind===`segment`)return lv(e,TR,t,n)??bR;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
179
179
  Old: { kind: "cells", segments: ["seg1", "seg2"] }
180
- New: { h: ["seg1", "seg2"] }`,line:G(e.source,[`root`])}),vR;if(n.kind===`group`){let r=lv(e,LR,t,n);return r===null?vR:(e.groups.push({name:r.name,label:r.label,...r.open!==void 0&&{open:r.open},...r.direction!==void 0&&{direction:r.direction},...r.key!==void 0&&{key:r.key},...r.bg!==void 0&&{bg:r.bg},...r.fg!==void 0&&{fg:r.fg},...r.when!==void 0&&{when:r.when},path:t}),zR(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:G(e.source,[`root`])}),vR}if(a){let r=lv(e,DR,t,n);return r===null?vR:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when},...r.id!==void 0&&{id:r.id},...r.settings!==void 0&&{settings:r.settings}}}if(r){let r=lv(e,OR,t,n);return r===null?vR:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}if(i){let r=lv(e,kR,t,n);return r===null?vR:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:G(e.source,[`root`])}),vR};function jR(){return{required:!0,json:{type:`object`,propertyNames:{pattern:zb.source},additionalProperties:{$ref:_R}},parse:(e,t,n,r)=>{let i=r[n];if(!sv(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${cv(i)}`,line:G(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!zb.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:G(e.source,[...t.split(`.`),n,r])});continue}a[r]=AR(e,`${t}.${n}.${r}`,o)}return a}}}const MR={noun:`root key`,fields:{rows:jR(),when:bv(),distribution:wR()}};function NR(e,t,n){return sv(n)&&`rows`in n?lv(e,MR,t,n)??{rows:{}}:AR(e,t,n)}function PR(){return{required:!0,json:{type:`string`,pattern:zb.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!zb.test(i)||i===`closed`){e.issues.push({path:`${t}.${n}`,message:`a group "name" must be an identifier (letters, digits, _; not starting with a digit) and not the reserved "${yi}", got ${K(i)}`,line:G(e.source,[`root`])});return}return i}}}function FR(){return{required:!1,json:{type:`string`,minLength:1},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`string`||i===``||i.includes(`/`)){e.issues.push({path:`${t}.${n}`,message:`a group "key" must be a non-empty, slash-free SessionState key, got ${K(i)}`,line:G(e.source,[`root`])});return}return i}}}}function IR(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=nv(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:G(e.source,[...t.split(`.`),n])});return}return i}}}}const LR={noun:`layout-node key`,fields:{kind:yR(`group`),name:PR(),label:IR(),open:xv(),direction:Ov(b_),key:FR(),bg:bv(),fg:bv(),when:bv(),distribution:wR(),children:SR(vv(()=>AR))}};function RR(e){return e.key??`groups.`+e.name}function zR(e){let t=pA+e.name;return wi(t,{variable:t,key:RR(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function BR(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function VR(e,t){bA(e,t,pA,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&BR(e,t.path,`duplicate group name "${t.name}" — group names must be unique (they name the synthesized state var, action, and toggle segment)`),r.add(t.name);for(let t of n)for(let r of n)t!==r&&t.path.startsWith(`${r.path}.`)&&RR(t)===RR(r)&&BR(e,t.path,`group "${t.name}" shares key "${RR(t)}" with its ancestor group "${r.name}" — a shared key holds ONE open group, so an ancestor and a descendant cannot share one. Sibling accordions share a key; nested groups use distinct keys.`);let i=new Map;for(let t of n){let n=RR(t);if(i.has(n)||i.set(n,yi),t.open===!0){let r=i.get(n);r!==`closed`&&BR(e,t.path,`groups "${r}" and "${t.name}" share key "${n}" and both declare open: true — a shared key holds one open group; pick one`),i.set(n,t.name)}}let a={},o={},s={};for(let e of n){let t=pA+e.name,r=RR(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=Ai(r,i.get(r)),o[t]=N(r,e.name),s[t]={template:Di(t,`${l}${e.label} ▸`,`${l}${e.label} ▾`),...e.bg!==void 0&&{bg:e.bg},...e.fg!==void 0&&{fg:e.fg}}}t.variables={...t.variables??{},...a},t.actions={...t.actions??{},...o},t.segments={...t.segments??{},...s}}const HR=`menu`,UR=`a menu binds its trigger text the way a cycle action binds a display — write {{ menu "applyTheme" "▸" "▾" }} (one per state) or {{ menu "insertHere" "+" }} (one static display for both), with the rare knobs in ONE trailing dict: {{ menu "applyTheme" "▸" "▾" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key). The renderer no longer appends ▸/▾ of its own (candybar-settings-ui-aok.4), and the older positional tail ("pageAction" closeOnPick paged "key") was removed — the page cursor is synthesized from the menu's identity`,WR=e=>e.kind===`call`&&e.name===`dict`,GR=e=>e.kind===`literal`&&typeof e.value!=`object`,KR=e=>xi(``,e,2)===void 0;function qR(e){let t=e=>({kind:`issue`,message:e}),[n,...r]=e.argExprs;if(n===void 0)return t(`with no arguments — it takes an apply-action name and its trigger text (e.g. {{ menu "applyTheme" "▸" "▾" }})`);if(n.kind!==`literal`||typeof n.value!=`string`)return t(`whose apply action is not a string literal — a menu's identity is its apply-action name, which must be a literal so it can be gated at load (e.g. {{ menu "applyTheme" "▸" "▾" }})`);let i=r[r.length-1],a=i!==void 0&&WR(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(WR))return t(`whose options (dict …) is not its last argument — ${UR}`);if(i!==void 0&&a===void 0&&!GR(i)&&KR(o.length-1))return t(`whose last argument is neither a literal nor a literal (dict …) — the renderer tells a display from the options dict by the value it evaluates to, so this call could be read as ${o.length} displays or as ${o.length-1} plus options, and both are legal. Make the options explicit as a trailing (dict …) — {{ menu "${n.value}" (printf "…") (printf "…") (dict) }} binds dynamic displays unambiguously — or bind the trigger text as literals`);let s=xi(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${UR}`);let c=a===void 0?{}:ZT(a);if(c===null)return t(`whose options (dict …) is not fully literal — every option value must be a literal so the menu can be gated at load (a dynamic entry like (dict "key" .x) cannot)`);let l;try{l=kA(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=yA(u);if(e!==void 0)return t(`whose accordion key "${u}" lands in the reserved "${e}" namespace — a key is collapsed to an identifier (${JSON.stringify(u)} becomes "${CA(u)}"), so it would share one open-state key with the synthesized accordion that owns that namespace instead of grouping only your own menus. Name the group without the reserved prefix`)}return{kind:`ok`,apply:n.value,options:l}}function JR(e){let t=ow({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===HR).map(qR)}catch{return`parse-failed`}}function YR(e,t){let n=JR(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:SA(t,e.apply,e.options.key),member:xA(e.apply)}]:[])}function XR(e){let t=ow({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(HR)}catch{return!1}}function ZR(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function QR(e,t){bA(e,t,mA,`{{ menu }} helpers`),bA(e,t,hA,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))XR(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:G(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&XR(i)&&ZR(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}if(t.root!==void 0)for(let n of E_(Kb(t.root)))typeof n.when==`string`&&XR(n.when)&&ZR(e,`root`,`a layout node's "when" predicate uses {{ menu }} — a menu is only valid in a segment's "template", not a node predicate. Move it into a segment.`);for(let[t,{template:r}]of Object.entries(n)){if(r===void 0||!XR(r))continue;let n=JR(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:$R(r.apply);n!==void 0&&ZR(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function $R(e){if(e===``)return`with an empty apply-action name — an empty member aliases the absent-state sentinel ("") so the menu would render open before any click. Name the apply action`;if(xA(e)===`closed`)return`whose apply action is named "${yi}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function ez(e,t){let n={},r={},i=new Map,a=new Set,o=(e,n)=>{let r=`segments.${e}`;a.has(`${r}\0${n}`)||(a.add(`${r}\0${n}`),t.push({path:r,message:n}))};for(let t of Qb(e.presets)){let a=new Map,s=new Map;for(let c of E_(tx(e,t).node)){if(c.kind!==`segment`)continue;let t=e.segments[c.name];if(t===void 0)continue;i.has(c.name)||i.set(c.name,JR(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=S_(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||$R(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=xA(i),f=SA(u,i,l.key),p=TA(f),m=l.key===void 0?`ind ${u} ${i}`:`key ${l.key}`,h=[f,p].find(e=>{let t=a.get(e);return t!==void 0&&t!==m});if(h!==void 0){o(c.name,`two {{ menu }} disclosures normalize to the same state key ("${h}") but were declared differently — distinct names that differ only by non-alphanumeric characters (e.g. "a-b" vs "a_b") collapse to one key and would silently share open-state. Rename so they don't collide.`);continue}a.set(f,m),a.set(p,m);let g=wA(f,d),_=`${c.name}\0${e}`,v=s.get(g);if(v!==void 0&&v!==_){o(c.name,`two {{ menu }} disclosures resolve to the same identity ("${g}") — ${l.key===void 0?`a segment cannot contain two menus over the same apply action "${i}"`:`menus sharing key "${l.key}" must have distinct apply actions`}.`);continue}s.set(g,_),r[g]=N(f,d),n[f]=Ai(f,yi),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}function tz(e,t,n){if(t===void 0)return{};if(!sv(t))return Z(e,`actions`,`actions must be an object, got ${cv(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=nz(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function Z(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function nz(e,t,n,r){if(!sv(n))return Z(e,t,`${t} must be an action object, got ${cv(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let i=dx.filter(e=>e in n);return i.length===1?iz(r)[i[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${dx.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function rz(e){return s.isAbsolute(e)?{dir:s.dirname(e)}:{text:e}}const iz=e=>({set:(e,t,n)=>Bz(e,t,n,`set`,Iz),persist:(e,t,n)=>Bz(e,t,n,`persist`,Lz),copy:az(`copy`),open:az(`open`),reset:oz,undo:cz(`undo`),redo:cz(`redo`),back:cz(`back`),rewind:cz(`rewind`),save:cz(`save`),preset:lz,themeDefault:uz,doctor:fz,slash:pz,run:gz(e),do:_z});function az(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=nv(t,n,r,e);return i===null?null:{[e]:i}}}function oz(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=vz(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}const sz={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,back:`it steps the session's navigation history`,rewind:`it steps the session's settings history back to where edit mode opened`,save:`it saves the session's unsaved settings`};function cz(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Z(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${sz[e]}), got ${K(r[e])}`),null)}}function lz(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${K(r)}`),null;if(r===`save`)return{preset:`save`};let a=nv(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function uz(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Z(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${K(n.themeDefault)}`),null)}const dz={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function fz(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(dz,r),a=i?dz[r]:[...new Set(Object.values(dz).flat())];for(let r of Object.keys(n))a.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Z(e,`${t}.doctor`,`doctor must be ${Object.keys(dz).map(e=>`"${e}"`).join(`, `)}, got ${K(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?FN:PN;if(typeof o!=`string`||!s.some(e=>e.name===o))return Z(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${K(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return GM.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${GM.map(e=>`"${e}"`).join(` or `)}, got ${K(c)}`),null)}function pz(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=sP(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}const mz=[`run`,`env`,`refreshes`],hz=/^[A-Za-z_][A-Za-z0-9_]*$/;function gz(e){return(t,n,r)=>{for(let e of Object.keys(r))mz.includes(e)||Z(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${mz.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&Z(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${K(a)}`);let o=r.env??{};(!sv(o)||Object.entries(o).some(([e,t])=>!hz.test(e)||typeof t!=`string`))&&Z(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${K(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&Z(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${K(s)}`),`dir`in e||Z(t,`${n}.run`,`a run action runs in the directory of the file that declares it, and ${e.text} is no file`),t.issues.length>i||!(`dir`in e)?null:{run:a,env:o,refreshes:s,cwd:e.dir}}}hz.source;function _z(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${K(r)}`),null):{do:r}}function vz(e,t,n,r,i,a){let o=nv(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Z(e,s,i),null):o.includes(`/`)?(Z(e,s,a(o)),null):o}const yz={set:`the SessionState key to write`,persist:`the config globals field to write`};function bz(e,t,n,r){let i=yz[r],a=vz(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);return a===null?null:{[r]:a}}function xz(e){return e===`set`?`set-state`:`set-config`}const Sz={to:Vz(`set`)},Cz={to:Vz(`persist`)},wz={from:Hz(`set`)},Tz={from:Hz(`persist`)},Ez={min:qz(),max:qz(),by:qz()},Dz={int:Wz()},Oz={cycle:Uz(`set`)},kz={cycle:Uz(`persist`)},Az={removeSegment:Gz(`removeSegment`)},jz={insertSegment:Gz(`insertSegment`),anchor:Gz(`anchor`),relation:Kz()},Mz={insertSegmentFrom:Hz(`persist`),anchor:Gz(`anchor`),relation:Kz()},Nz={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},Pz={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function Fz(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>dv(e,t,n,r),c=kv(t);return{detect:a,allowed:[...o,...i],label:i.join(`/`),json:{type:`object`,properties:{...Object.fromEntries(o.map(e=>[e,{type:`string`}])),...c.properties},required:[...o,...c.required??[]],additionalProperties:!1},parse:n.length?yv(s,...n):s}}const Iz=[Fz(`set`,Sz),Fz(`set`,wz),Fz(`set`,Ez,[Nz,Pz]),Fz(`set`,Dz),Fz(`set`,Oz)],Lz=[Fz(`persist`,Cz),Fz(`persist`,Tz),Fz(`persist`,Ez,[Nz,Pz]),Fz(`persist`,kz),Fz(`persist`,Az),Fz(`persist`,jz,[],[`insertSegment`]),Fz(`persist`,Mz,[],[`insertSegmentFrom`])];function Rz(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"endcaps"/"styles", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function zz(e){let t=Rz(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function Bz(e,t,n,r,i){let a=bz(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${zz(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Z(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function Vz(e){let t=xz(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>vz(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function Hz(e){let t=xz(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${K(o)}`)}}}function Uz(e){let t=xz(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Z(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${cv(o)}`);return}let c=o;if(c.length<2){Z(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Z(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Z(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Z(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function Wz(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${K(r[n])}`);return}return!0}}}function Gz(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=nv(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Z(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Z(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function Kz(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${K(i)}`);return}return i}}}function qz(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${K(i)}`);return}return i}}}function Jz(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const Yz={noun:`style key`,fields:{hueShift:Cv(),chromaScale:Cv({min:0}),lightnessScale:Cv(),lightnessShift:Cv()}};function Xz(e,t){if(!sv(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${cv(t)}`,line:G(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:G(e.source,[`styles`,r])});continue}if(c_(r)){e.issues.push({path:`styles.${r}`,message:Jz(`styles.${r}`,r,`globals.endcaps`),line:G(e.source,[`styles`,r])});continue}let t=lv(e,Yz,`styles.${r}`,i);t!==null&&(n[r]={...ml,...t})}return n}const Zz={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:NR(e,`${t}.${n}`,r[n])},globals:{required:!1,json:ej(),parse:(e,t,n,r)=>r[n]===void 0?void 0:$A(e,`${t}.${n}`,r[n])}}};function Qz(e,t){if(!sv(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${cv(t)}`,line:G(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:G(e.source,[`presets`,r])});continue}let t=lv(e,Zz,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function $z(e,t){if(t===void 0)return{};if(!sv(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${cv(t)}`,line:G(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${K(i)}`,line:G(e.source,[`helpers`,r])});continue}n[r]=i}return n}function eB({names:e,helpers:t,actions:n}){let r=(e,t)=>{let i=Object.hasOwn(n,e)?n[e]:void 0;return i===void 0||t.has(e)?[]:(t.add(e),[...[...px(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=e=>{let i=Nx(e,t)?Object.keys(n):jx(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]},a=nB(n=>i(n).flatMap(n=>[...Dx(n,t).keys()].map(t=>({path:t,reaches:Bx(t,e)}))));return{ofTemplate:a,calls:nB(e=>new Set(i(e).flatMap(e=>[...Fx(e,t)]))),ofVariable:t=>[...P_(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...N_(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function tB(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}function nB(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const rB=new WeakMap;function iB(e){let t=rB.get(e);return t===void 0&&(t=eB({names:new Set([...zx(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),rB.set(e,t)),t}function aB(e,t){for(let n of t.reads.calls(e))if(t.clock.has(n))return`calls "${n}"`;for(let{reaches:n}of t.reads.ofTemplate(e))for(let e of n){let n=t.projections.get(e);if(n!==void 0)return`reads "${e}", which ${n}`}return null}const oB=new WeakMap;function sB(e){let t=oB.get(e);return t===void 0&&(t=lB(e),oB.set(e,t)),t}function cB(e){return sB(e).projections}function lB(e){let t=new Map(zx(e)),n=new Map,r={reads:iB(e),projections:n,clock:hk};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=tB(e,r),i=t===void 0?null:oA(t);i&&n.set(e,`reads the draw's "${i}" (${aA[i]})`)}let i=dB(e),a=new Map;for(let e=!0;e;){e=!1;for(let[i,a]of t){if(a.kind!==`template`||n.has(i))continue;let t=aB(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of Ug)if(!a.has(t))for(let n of i[t]){let i=aB(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=tB(r,i);if(t===void 0||n.has(r))continue;let o=cA(t),s=o===void 0?void 0:a.get(o);s!==void 0&&(n.set(r,`reads the ${o} rule, which ${s}`),e=!0)}}return r}function uB(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>Ug.flatMap(n=>{let r=t[n];return Wg(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function dB(e){let t=uB(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function fB(e,t){return aB(e,sB(t))}function pB(e){return t=>aB(t,e)!==null}const mB={cell:e=>`${e} sets "distribution" on a container inside a cell — everything inside a cell wears that cell's colour, so it would place nothing. Set it on the row whose children are the cells (the horizontal container), or, on the bar, on the root, which places the rows.`,bar:e=>`${e} sets "distribution" on a vertical container none of whose children is a segment or a horizontal container — a bar row's hue is placed by the innermost vertical container it stacks through, so it would place nothing. Set it on that container, or on the row whose children are the cells (the horizontal container).`,band:e=>`${e} sets "distribution" on a vertical container in a disclosure body — a body's items are placed along their rows, never by which row they sit on, so it would place nothing. Set it on the row whose children are the items (the horizontal container), or give a group \`direction: 'horizontal'\`.`};function hB(e,t){let n=new Map;for(let e of Object.keys(t)){let t=fA(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:G(e.source,[`presets`])})}function gB(e,t,n){let r=[[[`globals`],t.globals.style,`globals.endcaps`],[[`editGlobals`],t.editGlobals.style,`editGlobals.endcaps`],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style,`presets.${e}.globals.endcaps`]),...Object.entries(t.themeDefaults).map(([e,t])=>[[`themeDefaults`,e],t.style,`globals.endcaps`])];for(let[n,i,a]of r){if(i===void 0||Wg(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:c_(i)?Jz(r,i,a):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:G(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:G(e.source,[`globals`,`preset`])}),hB(e,t.presets);let i=Hx(t);for(let t of i.names)t!==`settings`&&!t.startsWith(yB)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:G(e.source,[`variables`,t])});let a=(t,n,r)=>{zF(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Sj}" ${zF(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:r}),BF(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Sj}" under a \`when\` or inside a disclosure body — the menu is visible under every condition, so its placement may not be gated. Move it to an ungated position, or remove it to put the menu at its default position.`,line:r});let i=o(t,`bar`);i!==void 0&&e.issues.push({path:n,message:mB[i](n),line:r});let a=new Map;for(let e of E_(t)){if(e.kind!==`segment`)continue;let t=S_(e);a.set(t,[...a.get(t)??[],e])}for(let[t,i]of a){if(i.length<2)continue;let o=i[1].name,s=w_(o,new Set(a.keys()));e.issues.push({path:n,message:`${n} has ${i.length} placements with the id "${t}" — an id names one placement (its settings, its menus' open state, and edit mode all address it), so give each its own: { seg: "${o}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:r})}};function o(e,t){if(e.kind===`segment`||e.distribution===void 0)return;if(t===`cell`)return`cell`;let n=t===`bar`&&e.children.some(e=>e.kind===`segment`||x_[e.direction]===`cell`);return x_[e.direction]===`row`&&!n?t:void 0}let s=(e,t)=>e.kind===`segment`?`band`:x_[e.direction]===`cell`?`cell`:t,c=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,D_(t,n)]):e.opens===void 0?[]:[[e.opens.body,O_(t)]];function*l(e,t){for(let[n,r]of e){let e=o(n,t);e!==void 0&&(yield[e,r]),yield*l(c(n,r),s(n,t))}}let u=(n,r)=>{let a=Kb(n),o=Hb(n)?Object.entries(n.rows).map(([e,t])=>[t,`${r}.rows.${e}`]):c(a,r);for(let[t,n]of l(o,s(a,`bar`)))e.issues.push({path:n,message:mB[t](n),line:G(e.source,n.split(`.`))});for(let[a,o]of qb(n,r)){let n=G(e.source,o.split(`.`));if(a.when!==void 0&&(FB(e,`${o}.when`,a.when,i,{line:n}),NB(e,`${o}.when`,a.when,n),PB(e,t,`${o}.when`,a.when,n)),a.kind===`segment`){if(IF(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${Sj}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${Sj}"`,line:n});continue}Object.prototype.hasOwnProperty.call(t.segments,a.name)||e.issues.push({path:o,message:`${r} entry "${a.name}" does not match any declared segment${KL(a.name)}`,line:n}),DB(e,t,a,o,n)}}};n.root!==void 0&&u(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&u(t.root,`presets.${e}.root`);let d=new Map([[`root`,Gb(t.root)]]);for(let e of Qb(t.presets)){let{node:n,path:r}=tx(t,e);d.set(r,n)}for(let[t,n]of d)a(n,t,G(e.source,t.split(`.`)));HB(e,t,i,()=>!0)}const _B=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function vB(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=G(e.source,[`actions`,n,r]);if(!Qb(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Qb(t.presets).join(`, `)})`,line:c});return}if(r===`reset`)return;let l=`removeSegment`in o,u=`insertSegment`in o,d=`insertSegmentFrom`in o;if(!l&&!u&&!d){e.issues.push({path:s,message:`actions.${n}: "${i}" is a "presets.<name>.root" target and can only be paired with "removeSegment", "insertSegment", or "insertSegmentFrom" (not "to"/"from"/"cycle"/bounded — those have no meaning as a tree op)`,line:c});return}let f=(r,i)=>{Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})${KL(i)}`,line:c})},p=new Set(C_(tx(t,a).node)),m=(r,i)=>{!GL.has(i)||p.has(i)||Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" names no placement${KL(i)}`,line:c})};`removeSegment`in o&&m(`removeSegment`,o.removeSegment),`insertSegment`in o&&f(`insertSegment`,o.insertSegment),(`insertSegment`in o||`insertSegmentFrom`in o)&&m(`anchor`,o.anchor)}const yB=`settings.`;function bB(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>yB+e)])}}function xB(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:G(e.source,[`segments`,t,`settings`,n])})},a=wB(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of U_(n,CB(n)))i(e,`the defaults do not stand together: ${t}`)}function SB(e){return wB(e).length>0||U_(e,CB(e)).length>0}function CB(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function wB(e){let t=t=>H_(TB(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||H_(TB(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${EB(e,n).join(`, `)||`none`})`}];let i=[n];for(let e=r;e!==void 0;e=t(e)){if(e===n)return i.every(e=>n<=e)?[{setting:n,message:`atLeast closes a cycle (${[...i,n].join(` ≥ `)}) — every setting on it could only ever equal the rest`}]:[];if(i.includes(e))return[];i.push(e)}return[]})}function TB(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function EB(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&H_(n)!==void 0).map(([e])=>e)}function DB(e,t,n,r,i){let a=Object.prototype.hasOwnProperty.call(t.segments,n.name)?t.segments[n.name]:void 0;if(a===void 0)return;let o=V_(a),s=`${r}: placement "${S_(n)}" of segment "${n.name}"`;for(let[t,a]of Object.entries(n.settings??{})){let c=Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0,l=c===void 0?`sets "${t}", which segment "${n.name}" does not declare (it has: ${Object.keys(o).join(`, `)})`:W_(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Fg(a):``}, but it must be ${J_(c)}`;l!==void 0&&e.issues.push({path:r,message:`${s} ${l}`,line:i})}let c=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,n.settings?.[e]??t.default]));if(!(!Object.entries(c).every(([e,t])=>W_(o[e],t))||SB(o)))for(let{message:t}of U_(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function OB(e,t,n,r,i){for(let[a,o]of P_(n))FB(e,`${t}.${a}`,o,r,{segCtx:i})}function kB(e,t,n,r,i){if(!(!N_(n)||!(`depends_on`in n.cache)))for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:G(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const AB=`it reads the instant a frame is drawn at, which changes every frame, and a cache policy re-runs its source when a stored value changes — re-run it on a period instead: cache: { ttl: "<duration>" }`;function jB(e,t,n,r){if(!N_(n))return;let i=n=>G(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=fB(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${AB}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=cB(r);n.cache.depends_on.forEach((n,r)=>{let o=a.get(n);o!==void 0&&e.issues.push({path:`${t}.cache.depends_on[${r}]`,message:`cache.depends_on names "${n}", which ${o}: ${AB}`,line:i(`depends_on`)})})}}function MB(e,t){let n=new Map(zx(t)),r=iB(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=Ug.find(e=>sA[e]===n||sA[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${sA[e]}", the ${e}'s own name`;for(let e of r){let n=a(e,t);if(n!==null)return n}}return null},a=(e,t)=>{if(t.has(e))return null;t.add(e);let a=n.get(e),o=tB(e,a),s=o===void 0?void 0:cA(o);if(s!==void 0)return`reads "${e}", the ${s}'s own name`;for(let n of r.ofVariable(a)){let r=i([n],t);if(r!==null)return n.field===`template`?`reads "${e}", which ${r}`:`reads "${e}", whose ${n.field} ${r}`}return null};for(let{at:n,rule:a}of uB(t)){let t=i(r.ofTemplate(a),new Set);if(t===null)continue;let o=n.join(`.`);e.issues.push({path:o,message:`${o} ${t}: a rule decides that name, so it cannot read it — read the data the rule is about instead`,line:G(e.source,[...n])})}}function NB(e,t,n,r){try{xj.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function PB(e,t,n,r,i){let a=n.slice(n.lastIndexOf(`.`)+1);for(let{name:o,site:s,via:c}of jx(r,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,o))continue;let r=s===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(c!==null){IB(e,c,`Template references unknown action "${o}"${r}`);continue}e.issues.push({path:n,message:`${a} references unknown action "${o}"${r}`,line:i})}}function FB(e,t,n,r,i){for(let[a,o]of Dx(n,r.helpers)){if(Vx(a,r))continue;if(a.startsWith(yB)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??G(e.source,t.split(`.`))});continue}if(o!==null){IB(e,o,`Template references unknown variable ".${a}"${pL(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&Vx(n,r)?` (segment-local vars are namespaced — write ".${n}")`:pL(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??G(e.source,t.split(`.`))})}}function IB(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:G(e.source,[`helpers`,t])})}function LB(e,t,n,r,i){let a=n.set,o=RA(Sy[r].configKey),s=`${a} takes ${MA(o,i)}`;if(`min`in n&&(o===`bool`||!(`min`in o))){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:G(e.source,[`actions`,t,`min`])});return}let c=BB(n,i);if(c===zB){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:G(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!jA(o,e.value,i));if(l.length!==0){if(a===Sy.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>c_(e.value)))){let r=Sy.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:Jz(`actions.${t}.to`,n.to,`set: "${r}", to`),line:G(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:G(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=RB?r.join(`, `):`${r.slice(0,RB).join(`, `)} and ${r.length-RB} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:G(e.source,[`actions`,t,n])})}}}const RB=3,zB=Symbol(`any integer`);function BB(e,t){return`to`in e?[{field:`to`,value:e.to}]:`cycle`in e?e.cycle.map(e=>({field:`cycle`,value:e})):`from`in e?cx(e.from,t).members.map(e=>({field:`from`,value:e})):`min`in e?[{field:`min`,value:String(e.min)},{field:`max`,value:String(e.max)}]:zB}function VB(e,t){return Object.entries(e).filter(([e])=>t(e))}function HB(e,t,n,r){let i=pI(t),a=sx(i);for(let[n,o]of VB(t.actions,r)){let[t,r]=`from`in o?[`from`,o.from]:`insertSegmentFrom`in o?[`insertSegmentFrom`,o.insertSegmentFrom]:[null,null];if(t!==null&&typeof r==`string`&&!a.includes(r)){e.issues.push({path:`actions.${n}.${t}`,message:`actions.${n} ${t}: references ${ux(r,i)}`,line:G(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;Ey.has(o.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${o.set}", which has no session pick — globals.${o.set} is set in the config file only, so a click would change nothing; write it with { persist: "${o.set}", … } instead`,line:G(e.source,[`actions`,n,`set`])});let s=Ay.get(o.set);s!==void 0&&LB(e,n,o,s,i)}for(let[n,i]of VB(t.actions,r))`do`in i&&i.do.forEach((r,a)=>{let o=Object.prototype.hasOwnProperty.call(t.actions,r)?t.actions[r]:void 0,s=o===void 0?`references unknown action "${r}"`:`do`in o?`"${r}" is itself a do action — list its members here instead`:i.do.indexOf(r)===a?a>0&&mx(o)?`"${r}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${r}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:G(e.source,[`actions`,n,`do`])})});for(let[n,i]of VB(t.actions,r))if(`run`in i)for(let r of i.refreshes){let i=Object.hasOwn(t.variables,r)?t.variables[r]:void 0;i?.kind!==`source`&&e.issues.push({path:`actions.${n}.refreshes`,message:`actions.${n} refreshes "${r}", which ${i===void 0?`is not declared`:`is a ${i.kind} variable`}: a run refreshes only a declared source (by its full name, plugins.<plugin>.<source>; a plugin names its own sources bare)`,line:G(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of VB(t.actions,r)){let r=`persist`in i?i.persist:`reset`in i?i.reset:null;if(r===null)continue;let a=`persist`in i?`persist`:`reset`,o=gj(r);if(o===null){let t=ij(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${aj().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, a "themeDefaults.<theme>.<shade|variation|style>" target, or a "presets.<name>.root" target`:`actions.${n}: the globals field "${r}" was removed: ${t}`,line:G(e.source,[`actions`,n,a])});continue}let s=_B.filter(e=>e in i);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){vB(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Qb(t.presets).includes(o.preset)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names preset "${o.preset}" which is not declared (have: ${Qb(t.presets).join(`, `)})`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`theme-default`&&!e.allowedPalettes.has(o.theme)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names theme "${o.theme}" which is not installed${Fg(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${KL(o.segment)}`,line:G(e.source,[`actions`,n,a])});continue}`min`in i&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:G(e.source,[`actions`,n,a])})}}for(let[i,a]of VB(t.variables,r)){OB(e,`variables.${i}`,a,n);let t=fL(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:G(e.source,[`variables`,i])})}for(let[i,a]of VB(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))OB(e,`segments.${i}.vars.${t}`,r,n,i);let r=V_(a);xB(e,i,r);let o=bB(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];typeof s==`string`&&(FB(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r}),PB(e,t,`segments.${i}.${n}`,s,G(e.source,[`segments`,i,n])))}}for(let[i,a]of VB(t.variables,r))kB(e,`variables.${i}`,a,n),jB(e,`variables.${i}`,a,t);MB(e,t);for(let[i,a]of VB(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))kB(e,`segments.${i}.vars.${r}`,o,n,i),jB(e,`segments.${i}.vars.${r}`,o,t)}function UB(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=WB(t),a=new Map,o=[];for(let e of r.keys())a.set(e,0);for(let e of r.keys())if(!(!n(e)||a.get(e)!==0)&&s(e))return;function s(t){a.set(t,1),o.push(t);for(let c of r.get(t)??[]){if(!n(c))continue;let t=a.get(c);if(t===1){let t=o.indexOf(c),n=[...o.slice(t),c],r=n[0],a=i.get(r);return e.issues.push({path:a?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:G(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function WB(e){let t=new Map,n=new Map,r=iB(e),i=(e,i,a)=>{t.set(e,{declarationPath:a.join(`.`),linePathParts:a}),n.set(e,new Set(r.ofVariable(i).flatMap(({reaches:e})=>e)))};for(let[t,n]of Object.entries(e.variables))i(t,n,[`variables`,t]);for(let[t,n]of Object.entries(e.segments))for(let[e,r]of Object.entries(n.vars??{}))i(`${t}.${e}`,r,[`segments`,t,`vars`,e]);return{graph:n,nodeInfo:t}}function GB(e,t,n){let r=new Map([...Rx(t)].map(([e,,t])=>[e,t]));for(let[t,i]of r){let a=t.split(`.`);for(let o=1;o<a.length;o++){let s=a.slice(0,o).join(`.`),c=r.get(s);if(c===void 0||!(n.checked(t)||n.checked(s)))continue;let[l,u,d]=n.authored(t)?[t,s,i]:[s,t,c],f=n.authored(t)===n.authored(s)?`Rename one so neither name starts with the other.`:`"${u}" is declared outside this file (the bundled default, a plugin, or a control the bar builds), so rename "${l}".`;e.issues.push({path:d.join(`.`),message:`variable "${t}" is declared under the variable "${s}" — a read of ".${t}" would name both, "${t}" and a field of "${s}". ${f}`,line:G(e.source,[...d])})}}}function KB(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?C.homedir()+e.slice(1):e}function qB(e,t){return s.resolve(e,KB(t))}function JB(e,t){return typeof t==`string`&&t!==``?qB(e,t):void 0}function YB(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const XB=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),ZB=`plugin.json5`,QB=/^[a-z][a-z0-9_]*$/;function $B(e){let t=s.basename(s.dirname(e));return QB.test(t)?t:void 0}const eV=`plugins.`;function tV(e){return`${eV}${e}.data`}function nV(e){return`${e}.json`}function rV(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:iV(e)}}}function iV(e){return e instanceof Z_?e.issues.map(e=>e.path===``||e.message.includes(e.path)?e.message:`${e.path}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}function aV(e,t){return e.map(e=>qB(s.dirname(t),e))}function oV(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=$B(n),o=(t,r)=>{let i=new Map(e.rendering);return a!==void 0&&r!==e.config&&i.delete(a),{...e,config:r,rendering:i,dropped:[...e.dropped,{path:n,plugin:a,reason:t}]}};if(s.basename(n)!==`plugin.json5`){let t=`a plugin is a folder holding its ${ZB}, and the folder's name is the plugin's: move this file to <dir>/<name>/${ZB} and list that`;return o(t,a===void 0?e.config:uV(lV(e.config,a),a,{path:n,plugin:a,reason:t}))}if(a===void 0)return o(`its folder "${s.basename(s.dirname(n))}" is not a plugin name (one matching ${QB}: it prefixes every name the plugin declares)`,e.config);let c=i.get(a);if(c!==void 0)return o(`plugin "${a}" is already listed, from ${c}`,e.config);i.set(a,n);let l=lV(e.config,a),u=rV(()=>{let i=p.readFileSync(n,`utf-8`),o=$I(gV(n,a,{source:i,json:Ii.default.parse(i)},t),l);return EV(n,a,o),r(o,a,l!==e.config),o});if(u.ok)return{...e,config:u.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[a,n]])};let d={path:n,plugin:a,reason:u.reason};return o(u.reason,uV(l,a,d))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function sV(e){let t=cV(e);return e=>e===t||e.startsWith(`${t}.`)}function cV(e){return`${eV}${e}`}function lV(e,t){let n=sV(t),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n(e)));return[e.variables,e.segments,e.helpers,e.actions].some(e=>Object.keys(e).some(n))?{...e,variables:r(e.variables),segments:r(e.segments),helpers:r(e.helpers),actions:r(e.actions)}:e}function uV(e,t,n){return{...e,variables:{...e.variables,[cV(t)]:{kind:`dropped`,reason:YB(n),definition:n.path}}}}function dV(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function fV(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments),...Object.keys(e.config.helpers),...Object.keys(e.config.actions)].map(dV)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:YB(e)}));return t=>{let i=dV(t);if(i===void 0)return[];let a=e.config.variables[cV(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function pV(e,t){let n=Qb(e.presets).flatMap(t=>[...E_(tx(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),r=[...new Set([...n.map(e=>e.name),...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),i=Object.fromEntries(r.map(({name:e,cause:t})=>[e,mV(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=dV(t),r=n===void 0?void 0:e.variables[cV(n)];return r?.kind===`dropped`?{definition:r.definition,notice:r.reason}:void 0},o=Object.values(e.variables).some(e=>e.kind===`dropped`),s=o?Object.values(e.segments).flatMap(e=>[`template`,`bg`,`fg`,`when`].flatMap(t=>e[t]===void 0?[]:[e[t]])):[],c=o?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],l=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:a(e);return n===void 0?[]:[[e,n]]}),u=l([...s.flatMap(t=>jx(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...Lx(t,e.helpers)]),e.helpers),f=Object.entries(e.actions).flatMap(([t,n])=>{if(!(`run`in n))return[];let r=new Map(l(n.refreshes,e.variables));return r.size===0?[]:[{name:t,action:{...n,refreshes:n.refreshes.filter(e=>!r.has(e))},causes:[...r.values()]}]}),p=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition),...f.flatMap(({causes:e})=>e.map(e=>e.definition))]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(f.map(({name:e,action:t})=>[e,t])),...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${cV(dV(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:p}}function mV(e,t,n){let r=`⚠ ${e}: ${t.join(`; `)}`,i=new Map;for(let e of n)for(let[t,n]of Object.entries(e.settings??{})){let e=i.get(t);i.set(t,e===void 0?[n]:[...e,n])}let a=Object.fromEntries([...i].map(([e,t])=>[e,hV(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function hV(e,t){let[n]=t,r=t.filter(e=>typeof e==`number`);return typeof n==`boolean`?{label:e,domain:`bool`,default:n}:typeof n==`number`?{label:e,domain:{min:Math.min(...r),max:Math.max(...r),step:1},default:n}:{label:e,domain:[...new Set(t.map(String))],default:n}}function gV(e,t,{source:n,json:r},{checkout:i}){let a=[],o=()=>{throw new Z_(e,a)};if(!sv(r))return a.push({path:``,message:`a plugin definition must be an object, got ${cv(r)}`}),o();for(let e of Object.keys(r))XB.has(e)||a.push({path:e,message:e===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${t}") — remove "plugin"`:`a plugin definition may not declare "${e}". Expected only: ${[...XB].join(`, `)}`});let c=r.data===void 0?void 0:kV(r.data,e,i,a),l=r.sources===void 0?{}:TV(r.sources,e,a);if(a.length>0)return o();let u={source:n,issues:a,allowedPalettes:new Set(Rg()),groups:[]},d=c===void 0?{}:vL(u,`data`,{[tV(t)]:{kind:`file`,path:c,parse:{json:!0},cache:{watch_file:c},default:{}}}),f=vL(u,`variables`,r.variables);for(let[e,n]of[[`variables`,Object.keys(f)],[`sources`,Object.keys(l)]])n.includes(`data`)&&a.push({path:`${e}.data`,message:`"data" names the plugin's data file (.${tV(t)}), declared by the definition's own "data" key: give this ${e===`sources`?`source`:`variable`} another name`});for(let e of Object.keys(l))Object.hasOwn(f,e)&&a.push({path:`sources.${e}`,message:`source "${e}" and variable "${e}" are one name (.${eV}${t}.${e}): give one of them another name`});let m={variables:{...d,...vV(t,l),...vV(t,Object.fromEntries(Object.entries(f).map(([e,n])=>[e,bV(t,n)])))},segments:vV(t,xV(t,uR(u,r.segments,new Set))),helpers:vV(t,$z(u,r.helpers)),actions:vV(t,SV(t,tz(u,r.actions,{dir:p.realpathSync(s.dirname(e))})))};for(let[e,t]of _V(m))try{xj.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),m}function*_V(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of P_(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of[`template`,`bg`,`fg`,`when`]){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[e,r]of Object.entries(n.vars??{}))for(let[n,i]of P_(r))yield[`segments.${t}.vars.${e}.${n}`,i]}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))for(let[e,r]of px(n))yield[`actions.${t}.${e}`,r]}function vV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${eV}${e}.${t}`,n]))}function yV(e,t){return`${eV}${e}.${t}`}function bV(e,t){return t.kind===`state`?{...t,key:yV(e,t.key)}:t}function xV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.vars===void 0?n:{...n,vars:Object.fromEntries(Object.entries(n.vars).map(([t,n])=>[t,bV(e,n)]))}]))}function SV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:yV(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>yV(e,t))}:n]))}const CV=QB,wV={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function TV(e,t,n){if(!sv(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${cv(e)}`}),{};let r=s.join(p.realpathSync(s.dirname(t)),`session`),i=JSON.stringify(wV),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!CV.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${CV}: it is the last segment of .${eV}<plugin>.${t})`});continue}let s=OV(o,wV,e);for(let{field:e,is:t}of s)n.push({path:e,message:`${e} ${t}: what is built is a source ${i} — a session's JSON file in the plugin's managed storage, re-read when it changes`});s.length===0&&(a[t]={kind:`source`,storage:r})}return a}function EV(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=DV(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=sV(t),a=[...r].filter(([,e])=>e.length>1&&e.some(i)).map(([e,n])=>({path:`sources.${n.find(i).slice(`${eV}${t}.`.length)}`,message:`sources ${n.map(e=>`.${e}`).join(` and `)} read the same file, ${e}: a session's file is one document, read by one source`}));if(a.length>0)throw new Z_(e,a)}function DV(e){return s.join(e.storage,nV(`<session id>`))}function OV(e,t,n){return!sv(t)||!sv(e)?JSON.stringify(e)===JSON.stringify(t)?[]:[{field:n,is:`is ${JSON.stringify(e)}`}]:[...new Set([...Object.keys(t),...Object.keys(e)])].flatMap(r=>{let i=`${n}.${r}`;return Object.hasOwn(t,r)?Object.hasOwn(e,r)?OV(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function kV(e,t,n,r){if(typeof e==`string`&&e!==``)return qB(s.dirname(t),e);if(sv(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(s.isAbsolute(t)||t.startsWith(`~`)||s.normalize(t).split(s.sep)[0]===`..`){r.push({path:`data.checkout`,message:`data.checkout "${t}" must be a path inside the checkout, relative to its root (like ".lit/statusline.json"): no absolute path, "~" or ".."`});return}if(n===null){r.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return s.resolve(n.root,t)}if(sv(e)&&`project`in e){r.push({path:`data.project`,message:`data: { project } is now data: { checkout }: the same path, relative to the root of the git checkout the session works in (a linked worktree is its own checkout)`});return}r.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { checkout: "<path>" } relative to the root of the session's checkout`})}function AV(e){let t=[...[...(process.env.XDG_DATA_DIRS||NV()).split(`:`).filter(e=>e!==``)].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),jV(),...e===null?[]:[s.join(e,MV)]];return t.filter((e,n)=>t.lastIndexOf(e)===n)}function jV(){let e=process.env.XDG_DATA_HOME||s.join(C.homedir(),`.local`,`share`);return s.join(e,`cc-candybar`,`plugins`)}const MV=s.join(`.cc-candybar`,`plugins`);function NV(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${s.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function PV(e){let t=AV(e),n=new Map,r=[],i=[];for(let e of t){let t=FV(e);if(`error`in t){r.push(t);continue}for(let r of t.folders)n.delete(r),n.set(r,s.join(e,r,ZB));for(let n of t.files)i.push({path:s.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${ZB}: move this file to ${s.join(e,`<name>`,ZB)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function FV(e){try{let t=p.readdirSync(e,{withFileTypes:!0}).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),n=t=>t.isDirectory()||IV(e,t);return{folders:t.filter(n).map(e=>e.name),files:t.filter(e=>!n(e)).map(e=>e.name)}}catch(t){return t.code===`ENOENT`?{folders:[],files:[]}:{path:e,error:t.message}}}function IV(e,t){if(!t.isSymbolicLink())return!1;try{return p.statSync(s.join(e,t.name)).isDirectory()}catch{return!0}}function LV(e){return p.existsSync(s.join(e,`.git`))}function RV(e){let t=s.resolve(e);for(;;){if(LV(t))return t;let e=s.dirname(t);if(e===t)return;t=e}}function zV(e){let t=RV(e);return t===void 0?{root:s.resolve(e),git:!1}:{root:t,git:!0}}function BV(e){try{return p.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const VV=[`json5`,`json`];function HV(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?VV.map(t=>s.join(e,`.cc-candybar.${t}`)):[],...VV.map(e=>s.join(r,`.cc-candybar.${e}`)),...VV.map(e=>`${UV()}.${e}`)])]}function UV(){let e=process.env.XDG_CONFIG_HOME??s.join(C.homedir(),`.config`);return s.join(e,`cc-candybar`,`config`)}function WV(e,t,n){let r=[],i=new Map;for(let a of HV(e,t,n)){let e=BV(a);if(e===`absent`)continue;if(e!==`present`){r.push(e);continue}let t=s.join(p.realpathSync(s.dirname(a)),s.basename(a).replace(/\.(json5|json)$/,``));i.has(t)||i.set(t,a)}let a=[...i.values()].reverse();if(n===void 0)return{kind:`chain`,layers:a,home:GV(a),unchecked:r};let[o]=r,c=n;return a.length>0?{kind:`chain`,layers:a,home:c,unchecked:r}:o===void 0?{kind:`missing`,path:n,home:c}:{kind:`unreadable`,...o,home:c}}function GV(e){let t=UV();return e.find(e=>VV.some(n=>e===`${t}.${n}`))??`${t}.${VV[0]}`}function KV(e,t,n){let r=WV(e,t,n),i=r.kind===`chain`?r.layers:[];return{path:r.home,above:i.filter(e=>e!==r.home),projectDir:e??null,cwd:t??null}}function qV(e){return JV(e).join(`
181
- `)||null}function JV(e){switch(e.kind){case`chain`:return e.unchecked.map(e=>`Config location could not be checked: ${e.path} — ${e.error}`);case`missing`:return[`Config file not found: ${e.path} — rendering the bundled default until it appears`];case`unreadable`:return[`Config file could not be read: ${e.path} — ${e.error} — rendering the bundled default until it can be`]}}function YV(e,t){let n=HV(e,t).filter(e=>BV(e)===`present`),r=new Map;for(let e of n){let t=s.dirname(e),n=s.basename(e).replace(/\.(json5|json)$/,``),i=s.join(t,n);r.has(i)||r.set(i,[]),r.get(i).push(e)}let i=[...r.values()].filter(e=>e.length>1);return i.length===0?null:`config-extension collision: ${i.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function XV(e,t,n,r){return e===null?{...oH,config:$I(oH.raw,t)}:QV(e,p.readFileSync(e,`utf-8`),t,n,r)}const ZV={projectDir:null,checkout:null,beneath:{dropped:[],rendering:new Map}};function QV(e,t,n,r,i){let a=lH(e,t,i,(t,a)=>{let o=oV(aV(t,e),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>iH(t,n,r,e,i)),s=fV(o,r.beneath.dropped);return{inherited:new Set([...lR(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=pV($I(a.raw,o.config),s);return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(YB)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const $V=new WeakMap;function eH(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e,nH(e)])]),a=$V.get(n)??new Map;$V.set(n,a);let o=JSON.stringify([t.projectDir,t.checkout?.root??null]),s=a.get(o);if(s?.key===i)return s.layer;let c=oV(e,t,{config:n,rendering:new Map},(e,t,n)=>iH(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function tH(e,t,n){return oV(e,{projectDir:null,checkout:n},{config:t,rendering:new Map},(e,t,n)=>iH(e,t,n,`<plugin install>`,void 0)).dropped}function nH(e){try{let t=p.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function rH(e,t,n,r,i=e=>p.readFileSync(e,`utf-8`),a){let o={projectDir:r.projectDir,checkout:r.cwd===null?null:zV(r.cwd)},s=PV(o.projectDir),c=eH(s.definitions,o,t,a),l={...c,dropped:[...c.dropped,...s.strays]};n.warned(s.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let u=l.config,d=[];for(let t of e){n.entered(t);let e=d.at(-1)?.plugins,r=QV(t,i(t),d.at(-1)?.config??u,{...o,beneath:{dropped:[...l.dropped,...d.flatMap(e=>e.plugins.dropped)],rendering:e?.rendering??l.rendering}},a);n.warned(r.warnings),d.push({...r,path:t})}let f=new Set(d.flatMap(e=>[...e.plugins.reached])),m=e=>f.has(e.path),h=l.dropped.filter(m),g=l.dropped.filter(e=>!m(e));n.warned(h.map(YB));let _={checkout:o.checkout,roots:s.roots,loaded:l.loaded,dropped:h,unreached:g,reached:f,rendering:d.at(-1)?.plugins.rendering??l.rendering},v=d.at(-1);if(v===void 0)return{layers:d,base:u,installed:_,config:sH(XV(null,u,ZV),`<default>`,a)};try{return{layers:d,base:u,installed:_,config:sH(v,v.path,a)}}catch(e){for(let e of d.slice(0,-1))n.entered(e.path),sH(e,e.path,a);throw n.entered(v.path),e}}function iH(e,t,n,r,i){if(n){sH(aH(e),r,i);return}let a=sV(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[]};if(HB(s,e,Hx(e),a),UB(s,e,a),GB(s,e,{checked:a,authored:a}),o.length>0)throw new Z_(r,o)}function aH(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const oH={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function sH({config:e,raw:t,source:n},r=`<config>`,i=new Set(Rg())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(gB(o,e,t),UB(o,e),a.length>0)throw new Z_(r,a);let s=ez(e,a);if(a.length>0)throw new Z_(r,a);let c=jI(ZF(s)),l=new Set([...Rx({variables:t.variables??{},segments:t.segments??{}})].map(([e])=>e));if(GB(o,c,{checked:()=>!0,authored:e=>l.has(e)}),a.length>0)throw new Z_(r,a);return c}function cH(e,t,n=new Set(Rg()),r=uH){return lH(e,t,n,()=>({inherited:r,layer:null})).raw}function lH(e,t,n,r){let i=dH(e,t),a=ev(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(Rg()),groups:[]};if(!sv(i))throw new Z_(e,[{path:``,message:`Config root must be an object, got ${cv(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:mH({...c,issues:[]},i.plugins)??[],sv(i.segments)?Object.keys(i.segments):[]),d=fH(c,i,l,rz(e));if(s.length>0)throw new Z_(e,s,o);return{raw:d,warnings:o,layer:u}}const uH=new Set;function dH(e,t){try{return Ii.default.parse(t)}catch(t){let n=t;throw new Z_(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function fH(e,t,n,r){for(let n of Object.keys(t))pH.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...pH].join(`, `)}`,line:G(e.source,[n])});let i={};return t.globals!==void 0&&(i.globals=QA(e,`globals`,t.globals)),t.variables!==void 0&&(i.variables=vL(e,`variables`,t.variables)),t.segments!==void 0&&(i.segments=uR(e,t.segments,n)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
180
+ New: { h: ["seg1", "seg2"] }`,line:G(e.source,[`root`])}),bR;if(n.kind===`group`){let r=lv(e,zR,t,n);return r===null?bR:(e.groups.push({name:r.name,label:r.label,...r.open!==void 0&&{open:r.open},...r.direction!==void 0&&{direction:r.direction},...r.key!==void 0&&{key:r.key},...r.bg!==void 0&&{bg:r.bg},...r.fg!==void 0&&{fg:r.fg},...r.when!==void 0&&{when:r.when},path:t}),VR(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:G(e.source,[`root`])}),bR}if(a){let r=lv(e,kR,t,n);return r===null?bR:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when},...r.id!==void 0&&{id:r.id},...r.settings!==void 0&&{settings:r.settings}}}if(r){let r=lv(e,AR,t,n);return r===null?bR:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}if(i){let r=lv(e,jR,t,n);return r===null?bR:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:G(e.source,[`root`])}),bR};function NR(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Bb.source},additionalProperties:{$ref:yR}},parse:(e,t,n,r)=>{let i=r[n];if(!sv(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${cv(i)}`,line:G(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!Bb.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:G(e.source,[...t.split(`.`),n,r])});continue}a[r]=MR(e,`${t}.${n}.${r}`,o)}return a}}}const PR={noun:`root key`,fields:{rows:NR(),when:bv(),distribution:ER()}};function FR(e,t,n){return sv(n)&&`rows`in n?lv(e,PR,t,n)??{rows:{}}:MR(e,t,n)}function IR(){return{required:!0,json:{type:`string`,pattern:Bb.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Bb.test(i)||i===`closed`){e.issues.push({path:`${t}.${n}`,message:`a group "name" must be an identifier (letters, digits, _; not starting with a digit) and not the reserved "${yi}", got ${K(i)}`,line:G(e.source,[`root`])});return}return i}}}function LR(){return{required:!1,json:{type:`string`,minLength:1},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`string`||i===``||i.includes(`/`)){e.issues.push({path:`${t}.${n}`,message:`a group "key" must be a non-empty, slash-free SessionState key, got ${K(i)}`,line:G(e.source,[`root`])});return}return i}}}}function RR(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=nv(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:G(e.source,[...t.split(`.`),n])});return}return i}}}}const zR={noun:`layout-node key`,fields:{kind:xR(`group`),name:IR(),label:RR(),open:xv(),direction:Ov(b_),key:LR(),bg:bv(),fg:bv(),when:bv(),distribution:ER(),children:wR(vv(()=>MR))}};function BR(e){return e.key??`groups.`+e.name}function VR(e){let t=mA+e.name;return wi(t,{variable:t,key:BR(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function HR(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function UR(e,t){xA(e,t,mA,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&HR(e,t.path,`duplicate group name "${t.name}" — group names must be unique (they name the synthesized state var, action, and toggle segment)`),r.add(t.name);for(let t of n)for(let r of n)t!==r&&t.path.startsWith(`${r.path}.`)&&BR(t)===BR(r)&&HR(e,t.path,`group "${t.name}" shares key "${BR(t)}" with its ancestor group "${r.name}" — a shared key holds ONE open group, so an ancestor and a descendant cannot share one. Sibling accordions share a key; nested groups use distinct keys.`);let i=new Map;for(let t of n){let n=BR(t);if(i.has(n)||i.set(n,yi),t.open===!0){let r=i.get(n);r!==`closed`&&HR(e,t.path,`groups "${r}" and "${t.name}" share key "${n}" and both declare open: true — a shared key holds one open group; pick one`),i.set(n,t.name)}}let a={},o={},s={};for(let e of n){let t=mA+e.name,r=BR(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=Ai(r,i.get(r)),o[t]=N(r,e.name),s[t]={template:Di(t,`${l}${e.label} ▸`,`${l}${e.label} ▾`),...e.bg!==void 0&&{bg:e.bg},...e.fg!==void 0&&{fg:e.fg}}}t.variables={...t.variables??{},...a},t.actions={...t.actions??{},...o},t.segments={...t.segments??{},...s}}const WR=`menu`,GR=`a menu binds its trigger text the way a cycle action binds a display — write {{ menu "applyTheme" "▸" "▾" }} (one per state) or {{ menu "insertHere" "+" }} (one static display for both), with the rare knobs in ONE trailing dict: {{ menu "applyTheme" "▸" "▾" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key). The renderer no longer appends ▸/▾ of its own (candybar-settings-ui-aok.4), and the older positional tail ("pageAction" closeOnPick paged "key") was removed — the page cursor is synthesized from the menu's identity`,KR=e=>e.kind===`call`&&e.name===`dict`,qR=e=>e.kind===`literal`&&typeof e.value!=`object`,JR=e=>xi(``,e,2)===void 0;function YR(e){let t=e=>({kind:`issue`,message:e}),[n,...r]=e.argExprs;if(n===void 0)return t(`with no arguments — it takes an apply-action name and its trigger text (e.g. {{ menu "applyTheme" "▸" "▾" }})`);if(n.kind!==`literal`||typeof n.value!=`string`)return t(`whose apply action is not a string literal — a menu's identity is its apply-action name, which must be a literal so it can be gated at load (e.g. {{ menu "applyTheme" "▸" "▾" }})`);let i=r[r.length-1],a=i!==void 0&&KR(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(KR))return t(`whose options (dict …) is not its last argument — ${GR}`);if(i!==void 0&&a===void 0&&!qR(i)&&JR(o.length-1))return t(`whose last argument is neither a literal nor a literal (dict …) — the renderer tells a display from the options dict by the value it evaluates to, so this call could be read as ${o.length} displays or as ${o.length-1} plus options, and both are legal. Make the options explicit as a trailing (dict …) — {{ menu "${n.value}" (printf "…") (printf "…") (dict) }} binds dynamic displays unambiguously — or bind the trigger text as literals`);let s=xi(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${GR}`);let c=a===void 0?{}:QT(a);if(c===null)return t(`whose options (dict …) is not fully literal — every option value must be a literal so the menu can be gated at load (a dynamic entry like (dict "key" .x) cannot)`);let l;try{l=AA(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=bA(u);if(e!==void 0)return t(`whose accordion key "${u}" lands in the reserved "${e}" namespace — a key is collapsed to an identifier (${JSON.stringify(u)} becomes "${wA(u)}"), so it would share one open-state key with the synthesized accordion that owns that namespace instead of grouping only your own menus. Name the group without the reserved prefix`)}return{kind:`ok`,apply:n.value,options:l}}function XR(e){let t=sw({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===WR).map(YR)}catch{return`parse-failed`}}function ZR(e,t){let n=XR(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:CA(t,e.apply,e.options.key),member:SA(e.apply)}]:[])}function QR(e){let t=sw({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(WR)}catch{return!1}}function $R(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function ez(e,t){xA(e,t,hA,`{{ menu }} helpers`),xA(e,t,gA,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))QR(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:G(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&QR(i)&&$R(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}if(t.root!==void 0)for(let n of E_(qb(t.root)))typeof n.when==`string`&&QR(n.when)&&$R(e,`root`,`a layout node's "when" predicate uses {{ menu }} — a menu is only valid in a segment's "template", not a node predicate. Move it into a segment.`);for(let[t,{template:r}]of Object.entries(n)){if(r===void 0||!QR(r))continue;let n=XR(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:tz(r.apply);n!==void 0&&$R(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function tz(e){if(e===``)return`with an empty apply-action name — an empty member aliases the absent-state sentinel ("") so the menu would render open before any click. Name the apply action`;if(SA(e)===`closed`)return`whose apply action is named "${yi}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function nz(e,t){let n={},r={},i=new Map,a=new Set,o=(e,n)=>{let r=`segments.${e}`;a.has(`${r}\0${n}`)||(a.add(`${r}\0${n}`),t.push({path:r,message:n}))};for(let t of $b(e.presets)){let a=new Map,s=new Map;for(let c of E_(nx(e,t).node)){if(c.kind!==`segment`)continue;let t=e.segments[c.name];if(t===void 0)continue;i.has(c.name)||i.set(c.name,XR(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=S_(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||tz(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=SA(i),f=CA(u,i,l.key),p=EA(f),m=l.key===void 0?`ind ${u} ${i}`:`key ${l.key}`,h=[f,p].find(e=>{let t=a.get(e);return t!==void 0&&t!==m});if(h!==void 0){o(c.name,`two {{ menu }} disclosures normalize to the same state key ("${h}") but were declared differently — distinct names that differ only by non-alphanumeric characters (e.g. "a-b" vs "a_b") collapse to one key and would silently share open-state. Rename so they don't collide.`);continue}a.set(f,m),a.set(p,m);let g=TA(f,d),_=`${c.name}\0${e}`,v=s.get(g);if(v!==void 0&&v!==_){o(c.name,`two {{ menu }} disclosures resolve to the same identity ("${g}") — ${l.key===void 0?`a segment cannot contain two menus over the same apply action "${i}"`:`menus sharing key "${l.key}" must have distinct apply actions`}.`);continue}s.set(g,_),r[g]=N(f,d),n[f]=Ai(f,yi),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}function rz(e,t,n){if(t===void 0)return{};if(!sv(t))return Z(e,`actions`,`actions must be an object, got ${cv(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=iz(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function Z(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function iz(e,t,n,r){if(!sv(n))return Z(e,t,`${t} must be an action object, got ${cv(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let i=fx.filter(e=>e in n);return i.length===1?oz(r)[i[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${fx.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function az(e){return s.isAbsolute(e)?{dir:s.dirname(e)}:{text:e}}const oz=e=>({set:(e,t,n)=>Hz(e,t,n,`set`,Rz),persist:(e,t,n)=>Hz(e,t,n,`persist`,zz),copy:sz(`copy`),open:sz(`open`),reset:cz,undo:uz(`undo`),redo:uz(`redo`),back:uz(`back`),rewind:uz(`rewind`),save:uz(`save`),preset:dz,themeDefault:fz,doctor:mz,slash:hz,run:vz(e),do:yz});function sz(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=nv(t,n,r,e);return i===null?null:{[e]:i}}}function cz(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=bz(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}const lz={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,back:`it steps the session's navigation history`,rewind:`it steps the session's settings history back to where edit mode opened`,save:`it saves the session's unsaved settings`};function uz(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Z(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${lz[e]}), got ${K(r[e])}`),null)}}function dz(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${K(r)}`),null;if(r===`save`)return{preset:`save`};let a=nv(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function fz(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Z(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${K(n.themeDefault)}`),null)}const pz={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function mz(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(pz,r),a=i?pz[r]:[...new Set(Object.values(pz).flat())];for(let r of Object.keys(n))a.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Z(e,`${t}.doctor`,`doctor must be ${Object.keys(pz).map(e=>`"${e}"`).join(`, `)}, got ${K(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?IN:FN;if(typeof o!=`string`||!s.some(e=>e.name===o))return Z(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${K(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return KM.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${KM.map(e=>`"${e}"`).join(` or `)}, got ${K(c)}`),null)}function hz(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=cP(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}const gz=[`run`,`env`,`refreshes`],_z=/^[A-Za-z_][A-Za-z0-9_]*$/;function vz(e){return(t,n,r)=>{for(let e of Object.keys(r))gz.includes(e)||Z(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${gz.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&Z(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${K(a)}`);let o=r.env??{};(!sv(o)||Object.entries(o).some(([e,t])=>!_z.test(e)||typeof t!=`string`))&&Z(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${K(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&Z(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${K(s)}`),`dir`in e||Z(t,`${n}.run`,`a run action runs in the directory of the file that declares it, and ${e.text} is no file`),t.issues.length>i||!(`dir`in e)?null:{run:a,env:o,refreshes:s,cwd:e.dir}}}_z.source;function yz(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${K(r)}`),null):{do:r}}function bz(e,t,n,r,i,a){let o=nv(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Z(e,s,i),null):o.includes(`/`)?(Z(e,s,a(o)),null):o}const xz={set:`the SessionState key to write`,persist:`the config globals field to write`};function Sz(e,t,n,r){let i=xz[r],a=bz(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);return a===null?null:{[r]:a}}function Cz(e){return e===`set`?`set-state`:`set-config`}const wz={to:Uz(`set`)},Tz={to:Uz(`persist`)},Ez={from:Wz(`set`)},Dz={from:Wz(`persist`)},Oz={min:Yz(),max:Yz(),by:Yz()},kz={int:Kz()},Az={cycle:Gz(`set`)},jz={cycle:Gz(`persist`)},Mz={removeSegment:qz(`removeSegment`)},Nz={insertSegment:qz(`insertSegment`),anchor:qz(`anchor`),relation:Jz()},Pz={insertSegmentFrom:Wz(`persist`),anchor:qz(`anchor`),relation:Jz()},Fz={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},Iz={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function Lz(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>dv(e,t,n,r),c=kv(t);return{detect:a,allowed:[...o,...i],label:i.join(`/`),json:{type:`object`,properties:{...Object.fromEntries(o.map(e=>[e,{type:`string`}])),...c.properties},required:[...o,...c.required??[]],additionalProperties:!1},parse:n.length?yv(s,...n):s}}const Rz=[Lz(`set`,wz),Lz(`set`,Ez),Lz(`set`,Oz,[Fz,Iz]),Lz(`set`,kz),Lz(`set`,Az)],zz=[Lz(`persist`,Tz),Lz(`persist`,Dz),Lz(`persist`,Oz,[Fz,Iz]),Lz(`persist`,jz),Lz(`persist`,Mz),Lz(`persist`,Nz,[],[`insertSegment`]),Lz(`persist`,Pz,[],[`insertSegmentFrom`])];function Bz(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"endcaps"/"styles", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function Vz(e){let t=Bz(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function Hz(e,t,n,r,i){let a=Sz(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${Vz(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Z(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function Uz(e){let t=Cz(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>bz(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function Wz(e){let t=Cz(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${K(o)}`)}}}function Gz(e){let t=Cz(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Z(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${cv(o)}`);return}let c=o;if(c.length<2){Z(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Z(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Z(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Z(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function Kz(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${K(r[n])}`);return}return!0}}}function qz(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=nv(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Z(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Z(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function Jz(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${K(i)}`);return}return i}}}function Yz(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${K(i)}`);return}return i}}}function Xz(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const Zz={noun:`style key`,fields:{hueShift:Cv(),chromaScale:Cv({min:0}),lightnessScale:Cv(),lightnessShift:Cv()}};function Qz(e,t){if(!sv(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${cv(t)}`,line:G(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:G(e.source,[`styles`,r])});continue}if(c_(r)){e.issues.push({path:`styles.${r}`,message:Xz(`styles.${r}`,r,`globals.endcaps`),line:G(e.source,[`styles`,r])});continue}let t=lv(e,Zz,`styles.${r}`,i);t!==null&&(n[r]={...ml,...t})}return n}const $z={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:FR(e,`${t}.${n}`,r[n])},globals:{required:!1,json:tj(),parse:(e,t,n,r)=>r[n]===void 0?void 0:ej(e,`${t}.${n}`,r[n])}}};function eB(e,t){if(!sv(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${cv(t)}`,line:G(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:G(e.source,[`presets`,r])});continue}let t=lv(e,$z,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function tB(e,t){if(t===void 0)return{};if(!sv(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${cv(t)}`,line:G(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${K(i)}`,line:G(e.source,[`helpers`,r])});continue}n[r]=i}return n}function nB({names:e,helpers:t,actions:n}){let r=(e,t)=>{let i=Object.hasOwn(n,e)?n[e]:void 0;return i===void 0||t.has(e)?[]:(t.add(e),[...[...mx(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=e=>{let i=Px(e,t)?Object.keys(n):Mx(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]},a=iB(n=>i(n).flatMap(n=>[...Ox(n,t).keys()].map(t=>({path:t,reaches:Vx(t,e)}))));return{ofTemplate:a,calls:iB(e=>new Set(i(e).flatMap(e=>[...Ix(e,t)]))),ofVariable:t=>[...P_(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...N_(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function rB(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}function iB(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const aB=new WeakMap;function oB(e){let t=aB.get(e);return t===void 0&&(t=nB({names:new Set([...Bx(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),aB.set(e,t)),t}function sB(e,t){for(let n of t.reads.calls(e))if(t.clock.has(n))return`calls "${n}"`;for(let{reaches:n}of t.reads.ofTemplate(e))for(let e of n){let n=t.projections.get(e);if(n!==void 0)return`reads "${e}", which ${n}`}return null}const cB=new WeakMap;function lB(e){let t=cB.get(e);return t===void 0&&(t=dB(e),cB.set(e,t)),t}function uB(e){return lB(e).projections}function dB(e){let t=new Map(Bx(e)),n=new Map,r={reads:oB(e),projections:n,clock:gk};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=rB(e,r),i=t===void 0?null:sA(t);i&&n.set(e,`reads the draw's "${i}" (${oA[i]})`)}let i=pB(e),a=new Map;for(let e=!0;e;){e=!1;for(let[i,a]of t){if(a.kind!==`template`||n.has(i))continue;let t=sB(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of Ug)if(!a.has(t))for(let n of i[t]){let i=sB(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=rB(r,i);if(t===void 0||n.has(r))continue;let o=lA(t),s=o===void 0?void 0:a.get(o);s!==void 0&&(n.set(r,`reads the ${o} rule, which ${s}`),e=!0)}}return r}function fB(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>Ug.flatMap(n=>{let r=t[n];return Wg(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function pB(e){let t=fB(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function mB(e,t){return sB(e,lB(t))}function hB(e){return t=>sB(t,e)!==null}const gB={cell:e=>`${e} sets "distribution" on a container inside a cell — everything inside a cell wears that cell's colour, so it would place nothing. Set it on the row whose children are the cells (the horizontal container), or, on the bar, on the root, which places the rows.`,bar:e=>`${e} sets "distribution" on a vertical container none of whose children is a segment or a horizontal container — a bar row's hue is placed by the innermost vertical container it stacks through, so it would place nothing. Set it on that container, or on the row whose children are the cells (the horizontal container).`,band:e=>`${e} sets "distribution" on a vertical container in a disclosure body — a body's items are placed along their rows, never by which row they sit on, so it would place nothing. Set it on the row whose children are the items (the horizontal container), or give a group \`direction: 'horizontal'\`.`};function _B(e,t){let n=new Map;for(let e of Object.keys(t)){let t=pA(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:G(e.source,[`presets`])})}function vB(e,t,n){let r=[[[`globals`],t.globals.style,`globals.endcaps`],[[`editGlobals`],t.editGlobals.style,`editGlobals.endcaps`],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style,`presets.${e}.globals.endcaps`]),...Object.entries(t.themeDefaults).map(([e,t])=>[[`themeDefaults`,e],t.style,`globals.endcaps`])];for(let[n,i,a]of r){if(i===void 0||Wg(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:c_(i)?Xz(r,i,a):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:G(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:G(e.source,[`globals`,`preset`])}),_B(e,t.presets);let i=Ux(t);for(let t of i.names)t!==`settings`&&!t.startsWith(xB)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:G(e.source,[`variables`,t])});let a=(t,n,r)=>{VF(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Cj}" ${VF(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:r}),HF(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Cj}" under a \`when\` or inside a disclosure body — the menu is visible under every condition, so its placement may not be gated. Move it to an ungated position, or remove it to put the menu at its default position.`,line:r});let i=o(t,`bar`);i!==void 0&&e.issues.push({path:n,message:gB[i](n),line:r});let a=new Map;for(let e of E_(t)){if(e.kind!==`segment`)continue;let t=S_(e);a.set(t,[...a.get(t)??[],e])}for(let[t,i]of a){if(i.length<2)continue;let o=i[1].name,s=w_(o,new Set(a.keys()));e.issues.push({path:n,message:`${n} has ${i.length} placements with the id "${t}" — an id names one placement (its settings, its menus' open state, and edit mode all address it), so give each its own: { seg: "${o}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:r})}};function o(e,t){if(e.kind===`segment`||e.distribution===void 0)return;if(t===`cell`)return`cell`;let n=t===`bar`&&e.children.some(e=>e.kind===`segment`||x_[e.direction]===`cell`);return x_[e.direction]===`row`&&!n?t:void 0}let s=(e,t)=>e.kind===`segment`?`band`:x_[e.direction]===`cell`?`cell`:t,c=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,D_(t,n)]):e.opens===void 0?[]:[[e.opens.body,O_(t)]];function*l(e,t){for(let[n,r]of e){let e=o(n,t);e!==void 0&&(yield[e,r]),yield*l(c(n,r),s(n,t))}}let u=(n,r)=>{let a=qb(n),o=Ub(n)?Object.entries(n.rows).map(([e,t])=>[t,`${r}.rows.${e}`]):c(a,r);for(let[t,n]of l(o,s(a,`bar`)))e.issues.push({path:n,message:gB[t](n),line:G(e.source,n.split(`.`))});for(let[a,o]of Jb(n,r)){let n=G(e.source,o.split(`.`));if(a.when!==void 0&&(LB(e,`${o}.when`,a.when,i,{line:n}),FB(e,`${o}.when`,a.when,n),IB(e,t,`${o}.when`,a.when,n)),a.kind===`segment`){if(RF(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${Cj}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${Cj}"`,line:n});continue}Object.prototype.hasOwnProperty.call(t.segments,a.name)||e.issues.push({path:o,message:`${r} entry "${a.name}" does not match any declared segment${JL(a.name)}`,line:n}),kB(e,t,a,o,n)}}};n.root!==void 0&&u(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&u(t.root,`presets.${e}.root`);let d=new Map([[`root`,Kb(t.root)]]);for(let e of $b(t.presets)){let{node:n,path:r}=nx(t,e);d.set(r,n)}for(let[t,n]of d)a(n,t,G(e.source,t.split(`.`)));WB(e,t,i,()=>!0)}const yB=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function bB(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=G(e.source,[`actions`,n,r]);if(!$b(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${$b(t.presets).join(`, `)})`,line:c});return}if(r===`reset`)return;let l=`removeSegment`in o,u=`insertSegment`in o,d=`insertSegmentFrom`in o;if(!l&&!u&&!d){e.issues.push({path:s,message:`actions.${n}: "${i}" is a "presets.<name>.root" target and can only be paired with "removeSegment", "insertSegment", or "insertSegmentFrom" (not "to"/"from"/"cycle"/bounded — those have no meaning as a tree op)`,line:c});return}let f=(r,i)=>{Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})${JL(i)}`,line:c})},p=new Set(C_(nx(t,a).node)),m=(r,i)=>{!qL.has(i)||p.has(i)||Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" names no placement${JL(i)}`,line:c})};`removeSegment`in o&&m(`removeSegment`,o.removeSegment),`insertSegment`in o&&f(`insertSegment`,o.insertSegment),(`insertSegment`in o||`insertSegmentFrom`in o)&&m(`anchor`,o.anchor)}const xB=`settings.`;function SB(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>xB+e)])}}function CB(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:G(e.source,[`segments`,t,`settings`,n])})},a=EB(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of U_(n,TB(n)))i(e,`the defaults do not stand together: ${t}`)}function wB(e){return EB(e).length>0||U_(e,TB(e)).length>0}function TB(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function EB(e){let t=t=>H_(DB(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||H_(DB(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${OB(e,n).join(`, `)||`none`})`}];let i=[n];for(let e=r;e!==void 0;e=t(e)){if(e===n)return i.every(e=>n<=e)?[{setting:n,message:`atLeast closes a cycle (${[...i,n].join(` ≥ `)}) — every setting on it could only ever equal the rest`}]:[];if(i.includes(e))return[];i.push(e)}return[]})}function DB(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function OB(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&H_(n)!==void 0).map(([e])=>e)}function kB(e,t,n,r,i){let a=Object.prototype.hasOwnProperty.call(t.segments,n.name)?t.segments[n.name]:void 0;if(a===void 0)return;let o=V_(a),s=`${r}: placement "${S_(n)}" of segment "${n.name}"`;for(let[t,a]of Object.entries(n.settings??{})){let c=Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0,l=c===void 0?`sets "${t}", which segment "${n.name}" does not declare (it has: ${Object.keys(o).join(`, `)})`:W_(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Fg(a):``}, but it must be ${J_(c)}`;l!==void 0&&e.issues.push({path:r,message:`${s} ${l}`,line:i})}let c=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,n.settings?.[e]??t.default]));if(!(!Object.entries(c).every(([e,t])=>W_(o[e],t))||wB(o)))for(let{message:t}of U_(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function AB(e,t,n,r,i){for(let[a,o]of P_(n))LB(e,`${t}.${a}`,o,r,{segCtx:i})}function jB(e,t,n,r,i){if(!(!N_(n)||!(`depends_on`in n.cache)))for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:G(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const MB=`it reads the instant a frame is drawn at, which changes every frame, and a cache policy re-runs its source when a stored value changes — re-run it on a period instead: cache: { ttl: "<duration>" }`;function NB(e,t,n,r){if(!N_(n))return;let i=n=>G(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=mB(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${MB}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=uB(r);n.cache.depends_on.forEach((n,r)=>{let o=a.get(n);o!==void 0&&e.issues.push({path:`${t}.cache.depends_on[${r}]`,message:`cache.depends_on names "${n}", which ${o}: ${MB}`,line:i(`depends_on`)})})}}function PB(e,t){let n=new Map(Bx(t)),r=oB(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=Ug.find(e=>cA[e]===n||cA[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${cA[e]}", the ${e}'s own name`;for(let e of r){let n=a(e,t);if(n!==null)return n}}return null},a=(e,t)=>{if(t.has(e))return null;t.add(e);let a=n.get(e),o=rB(e,a),s=o===void 0?void 0:lA(o);if(s!==void 0)return`reads "${e}", the ${s}'s own name`;for(let n of r.ofVariable(a)){let r=i([n],t);if(r!==null)return n.field===`template`?`reads "${e}", which ${r}`:`reads "${e}", whose ${n.field} ${r}`}return null};for(let{at:n,rule:a}of fB(t)){let t=i(r.ofTemplate(a),new Set);if(t===null)continue;let o=n.join(`.`);e.issues.push({path:o,message:`${o} ${t}: a rule decides that name, so it cannot read it — read the data the rule is about instead`,line:G(e.source,[...n])})}}function FB(e,t,n,r){try{Sj.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function IB(e,t,n,r,i){let a=n.slice(n.lastIndexOf(`.`)+1);for(let{name:o,site:s,via:c}of Mx(r,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,o))continue;let r=s===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(c!==null){RB(e,c,`Template references unknown action "${o}"${r}`);continue}e.issues.push({path:n,message:`${a} references unknown action "${o}"${r}`,line:i})}}function LB(e,t,n,r,i){for(let[a,o]of Ox(n,r.helpers)){if(Hx(a,r))continue;if(a.startsWith(xB)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??G(e.source,t.split(`.`))});continue}if(o!==null){RB(e,o,`Template references unknown variable ".${a}"${hL(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&Hx(n,r)?` (segment-local vars are namespaced — write ".${n}")`:hL(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??G(e.source,t.split(`.`))})}}function RB(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:G(e.source,[`helpers`,t])})}function zB(e,t,n,r,i){let a=n.set,o=zA(Sy[r].configKey),s=`${a} takes ${NA(o,i)}`;if(`min`in n&&(o===`bool`||!(`min`in o))){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:G(e.source,[`actions`,t,`min`])});return}let c=HB(n,i);if(c===VB){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:G(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!MA(o,e.value,i));if(l.length!==0){if(a===Sy.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>c_(e.value)))){let r=Sy.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:Xz(`actions.${t}.to`,n.to,`set: "${r}", to`),line:G(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:G(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=BB?r.join(`, `):`${r.slice(0,BB).join(`, `)} and ${r.length-BB} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:G(e.source,[`actions`,t,n])})}}}const BB=3,VB=Symbol(`any integer`);function HB(e,t){return`to`in e?[{field:`to`,value:e.to}]:`cycle`in e?e.cycle.map(e=>({field:`cycle`,value:e})):`from`in e?lx(e.from,t).members.map(e=>({field:`from`,value:e})):`min`in e?[{field:`min`,value:String(e.min)},{field:`max`,value:String(e.max)}]:VB}function UB(e,t){return Object.entries(e).filter(([e])=>t(e))}function WB(e,t,n,r){let i=hI(t),a=cx(i);for(let[n,o]of UB(t.actions,r)){let[t,r]=`from`in o?[`from`,o.from]:`insertSegmentFrom`in o?[`insertSegmentFrom`,o.insertSegmentFrom]:[null,null];if(t!==null&&typeof r==`string`&&!a.includes(r)){e.issues.push({path:`actions.${n}.${t}`,message:`actions.${n} ${t}: references ${dx(r,i)}`,line:G(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;Ey.has(o.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${o.set}", which has no session pick — globals.${o.set} is set in the config file only, so a click would change nothing; write it with { persist: "${o.set}", … } instead`,line:G(e.source,[`actions`,n,`set`])});let s=Ay.get(o.set);s!==void 0&&zB(e,n,o,s,i)}for(let[n,i]of UB(t.actions,r))`do`in i&&i.do.forEach((r,a)=>{let o=Object.prototype.hasOwnProperty.call(t.actions,r)?t.actions[r]:void 0,s=o===void 0?`references unknown action "${r}"`:`do`in o?`"${r}" is itself a do action — list its members here instead`:i.do.indexOf(r)===a?a>0&&hx(o)?`"${r}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${r}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:G(e.source,[`actions`,n,`do`])})});for(let[n,i]of UB(t.actions,r))if(`run`in i)for(let r of i.refreshes){let i=Object.hasOwn(t.variables,r)?t.variables[r]:void 0;i?.kind!==`source`&&e.issues.push({path:`actions.${n}.refreshes`,message:`actions.${n} refreshes "${r}", which ${i===void 0?`is not declared`:`is a ${i.kind} variable`}: a run refreshes only a declared source (by its full name, plugins.<plugin>.<source>; a plugin names its own sources bare)`,line:G(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of UB(t.actions,r)){let r=`persist`in i?i.persist:`reset`in i?i.reset:null;if(r===null)continue;let a=`persist`in i?`persist`:`reset`,o=_j(r);if(o===null){let t=aj(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${oj().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, a "themeDefaults.<theme>.<shade|variation|style>" target, or a "presets.<name>.root" target`:`actions.${n}: the globals field "${r}" was removed: ${t}`,line:G(e.source,[`actions`,n,a])});continue}let s=yB.filter(e=>e in i);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){bB(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!$b(t.presets).includes(o.preset)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names preset "${o.preset}" which is not declared (have: ${$b(t.presets).join(`, `)})`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`theme-default`&&!e.allowedPalettes.has(o.theme)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names theme "${o.theme}" which is not installed${Fg(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${JL(o.segment)}`,line:G(e.source,[`actions`,n,a])});continue}`min`in i&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:G(e.source,[`actions`,n,a])})}}for(let[i,a]of UB(t.variables,r)){AB(e,`variables.${i}`,a,n);let t=mL(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:G(e.source,[`variables`,i])})}for(let[i,a]of UB(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))AB(e,`segments.${i}.vars.${t}`,r,n,i);let r=V_(a);CB(e,i,r);let o=SB(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];typeof s==`string`&&(LB(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r}),IB(e,t,`segments.${i}.${n}`,s,G(e.source,[`segments`,i,n])))}}for(let[i,a]of UB(t.variables,r))jB(e,`variables.${i}`,a,n),NB(e,`variables.${i}`,a,t);PB(e,t);for(let[i,a]of UB(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))jB(e,`segments.${i}.vars.${r}`,o,n,i),NB(e,`segments.${i}.vars.${r}`,o,t)}function GB(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=KB(t),a=new Map,o=[];for(let e of r.keys())a.set(e,0);for(let e of r.keys())if(!(!n(e)||a.get(e)!==0)&&s(e))return;function s(t){a.set(t,1),o.push(t);for(let c of r.get(t)??[]){if(!n(c))continue;let t=a.get(c);if(t===1){let t=o.indexOf(c),n=[...o.slice(t),c],r=n[0],a=i.get(r);return e.issues.push({path:a?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:G(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function KB(e){let t=new Map,n=new Map,r=oB(e),i=(e,i,a)=>{t.set(e,{declarationPath:a.join(`.`),linePathParts:a}),n.set(e,new Set(r.ofVariable(i).flatMap(({reaches:e})=>e)))};for(let[t,n]of Object.entries(e.variables))i(t,n,[`variables`,t]);for(let[t,n]of Object.entries(e.segments))for(let[e,r]of Object.entries(n.vars??{}))i(`${t}.${e}`,r,[`segments`,t,`vars`,e]);return{graph:n,nodeInfo:t}}function qB(e,t,n){let r=new Map([...zx(t)].map(([e,,t])=>[e,t]));for(let[t,i]of r){let a=t.split(`.`);for(let o=1;o<a.length;o++){let s=a.slice(0,o).join(`.`),c=r.get(s);if(c===void 0||!(n.checked(t)||n.checked(s)))continue;let[l,u,d]=n.authored(t)?[t,s,i]:[s,t,c],f=n.authored(t)===n.authored(s)?`Rename one so neither name starts with the other.`:`"${u}" is declared outside this file (the bundled default, a plugin, or a control the bar builds), so rename "${l}".`;e.issues.push({path:d.join(`.`),message:`variable "${t}" is declared under the variable "${s}" — a read of ".${t}" would name both, "${t}" and a field of "${s}". ${f}`,line:G(e.source,[...d])})}}}function JB(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?C.homedir()+e.slice(1):e}function YB(e,t){return s.resolve(e,JB(t))}function XB(e,t){return typeof t==`string`&&t!==``?YB(e,t):void 0}function ZB(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const QB=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),$B=`plugin.json5`,eV=/^[a-z][a-z0-9_]*$/;function tV(e){let t=s.basename(s.dirname(e));return eV.test(t)?t:void 0}const nV=`plugins.`;function rV(e){return`${nV}${e}.data`}function iV(e){return`${e}.json`}function aV(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:oV(e)}}}function oV(e){return e instanceof Z_?e.issues.map(e=>e.path===``||e.message.includes(e.path)?e.message:`${e.path}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}function sV(e,t){return e.map(e=>YB(s.dirname(t),e))}function cV(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=tV(n),o=(t,r)=>{let i=new Map(e.rendering);return a!==void 0&&r!==e.config&&i.delete(a),{...e,config:r,rendering:i,dropped:[...e.dropped,{path:n,plugin:a,reason:t}]}};if(s.basename(n)!==`plugin.json5`){let t=`a plugin is a folder holding its ${$B}, and the folder's name is the plugin's: move this file to <dir>/<name>/${$B} and list that`;return o(t,a===void 0?e.config:fV(dV(e.config,a),a,{path:n,plugin:a,reason:t}))}if(a===void 0)return o(`its folder "${s.basename(s.dirname(n))}" is not a plugin name (one matching ${eV}: it prefixes every name the plugin declares)`,e.config);let c=i.get(a);if(c!==void 0)return o(`plugin "${a}" is already listed, from ${c}`,e.config);i.set(a,n);let l=dV(e.config,a),u=aV(()=>{let i=p.readFileSync(n,`utf-8`),o=tL(vV(n,a,{source:i,json:Ii.default.parse(i)},t),l);return OV(n,a,o),r(o,a,l!==e.config),o});if(u.ok)return{...e,config:u.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[a,n]])};let d={path:n,plugin:a,reason:u.reason};return o(u.reason,fV(l,a,d))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function lV(e){let t=uV(e);return e=>e===t||e.startsWith(`${t}.`)}function uV(e){return`${nV}${e}`}function dV(e,t){let n=lV(t),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n(e)));return[e.variables,e.segments,e.helpers,e.actions].some(e=>Object.keys(e).some(n))?{...e,variables:r(e.variables),segments:r(e.segments),helpers:r(e.helpers),actions:r(e.actions)}:e}function fV(e,t,n){return{...e,variables:{...e.variables,[uV(t)]:{kind:`dropped`,reason:ZB(n),definition:n.path}}}}function pV(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function mV(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments),...Object.keys(e.config.helpers),...Object.keys(e.config.actions)].map(pV)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:ZB(e)}));return t=>{let i=pV(t);if(i===void 0)return[];let a=e.config.variables[uV(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function hV(e,t){let n=$b(e.presets).flatMap(t=>[...E_(nx(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),r=[...new Set([...n.map(e=>e.name),...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),i=Object.fromEntries(r.map(({name:e,cause:t})=>[e,gV(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=pV(t),r=n===void 0?void 0:e.variables[uV(n)];return r?.kind===`dropped`?{definition:r.definition,notice:r.reason}:void 0},o=Object.values(e.variables).some(e=>e.kind===`dropped`),s=o?Object.values(e.segments).flatMap(e=>[`template`,`bg`,`fg`,`when`].flatMap(t=>e[t]===void 0?[]:[e[t]])):[],c=o?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],l=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:a(e);return n===void 0?[]:[[e,n]]}),u=l([...s.flatMap(t=>Mx(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...Rx(t,e.helpers)]),e.helpers),f=Object.entries(e.actions).flatMap(([t,n])=>{if(!(`run`in n))return[];let r=new Map(l(n.refreshes,e.variables));return r.size===0?[]:[{name:t,action:{...n,refreshes:n.refreshes.filter(e=>!r.has(e))},causes:[...r.values()]}]}),p=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition),...f.flatMap(({causes:e})=>e.map(e=>e.definition))]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(f.map(({name:e,action:t})=>[e,t])),...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${uV(pV(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:p}}function gV(e,t,n){let r=`⚠ ${e}: ${t.join(`; `)}`,i=new Map;for(let e of n)for(let[t,n]of Object.entries(e.settings??{})){let e=i.get(t);i.set(t,e===void 0?[n]:[...e,n])}let a=Object.fromEntries([...i].map(([e,t])=>[e,_V(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function _V(e,t){let[n]=t,r=t.filter(e=>typeof e==`number`);return typeof n==`boolean`?{label:e,domain:`bool`,default:n}:typeof n==`number`?{label:e,domain:{min:Math.min(...r),max:Math.max(...r),step:1},default:n}:{label:e,domain:[...new Set(t.map(String))],default:n}}function vV(e,t,{source:n,json:r},{checkout:i}){let a=[],o=()=>{throw new Z_(e,a)};if(!sv(r))return a.push({path:``,message:`a plugin definition must be an object, got ${cv(r)}`}),o();for(let e of Object.keys(r))QB.has(e)||a.push({path:e,message:e===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${t}") — remove "plugin"`:`a plugin definition may not declare "${e}". Expected only: ${[...QB].join(`, `)}`});let c=r.data===void 0?void 0:jV(r.data,e,i,a),l=r.sources===void 0?{}:DV(r.sources,e,a);if(a.length>0)return o();let u={source:n,issues:a,allowedPalettes:new Set(Rg()),groups:[]},d=c===void 0?{}:bL(u,`data`,{[rV(t)]:{kind:`file`,path:c,parse:{json:!0},cache:{watch_file:c},default:{}}}),f=bL(u,`variables`,r.variables);for(let[e,n]of[[`variables`,Object.keys(f)],[`sources`,Object.keys(l)]])n.includes(`data`)&&a.push({path:`${e}.data`,message:`"data" names the plugin's data file (.${rV(t)}), declared by the definition's own "data" key: give this ${e===`sources`?`source`:`variable`} another name`});for(let e of Object.keys(l))Object.hasOwn(f,e)&&a.push({path:`sources.${e}`,message:`source "${e}" and variable "${e}" are one name (.${nV}${t}.${e}): give one of them another name`});let m={variables:{...d,...bV(t,l),...bV(t,Object.fromEntries(Object.entries(f).map(([e,n])=>[e,SV(t,n)])))},segments:bV(t,CV(t,fR(u,r.segments,new Set))),helpers:bV(t,tB(u,r.helpers)),actions:bV(t,wV(t,rz(u,r.actions,{dir:p.realpathSync(s.dirname(e))})))};for(let[e,t]of yV(m))try{Sj.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),m}function*yV(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of P_(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of[`template`,`bg`,`fg`,`when`]){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[e,r]of Object.entries(n.vars??{}))for(let[n,i]of P_(r))yield[`segments.${t}.vars.${e}.${n}`,i]}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))for(let[e,r]of mx(n))yield[`actions.${t}.${e}`,r]}function bV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${nV}${e}.${t}`,n]))}function xV(e,t){return`${nV}${e}.${t}`}function SV(e,t){return t.kind===`state`?{...t,key:xV(e,t.key)}:t}function CV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.vars===void 0?n:{...n,vars:Object.fromEntries(Object.entries(n.vars).map(([t,n])=>[t,SV(e,n)]))}]))}function wV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:xV(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>xV(e,t))}:n]))}const TV=eV,EV={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function DV(e,t,n){if(!sv(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${cv(e)}`}),{};let r=s.join(p.realpathSync(s.dirname(t)),`session`),i=JSON.stringify(EV),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!TV.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${TV}: it is the last segment of .${nV}<plugin>.${t})`});continue}let s=AV(o,EV,e);for(let{field:e,is:t}of s)n.push({path:e,message:`${e} ${t}: what is built is a source ${i} — a session's JSON file in the plugin's managed storage, re-read when it changes`});s.length===0&&(a[t]={kind:`source`,storage:r})}return a}function OV(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=kV(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=lV(t),a=[...r].filter(([,e])=>e.length>1&&e.some(i)).map(([e,n])=>({path:`sources.${n.find(i).slice(`${nV}${t}.`.length)}`,message:`sources ${n.map(e=>`.${e}`).join(` and `)} read the same file, ${e}: a session's file is one document, read by one source`}));if(a.length>0)throw new Z_(e,a)}function kV(e){return s.join(e.storage,iV(`<session id>`))}function AV(e,t,n){return!sv(t)||!sv(e)?JSON.stringify(e)===JSON.stringify(t)?[]:[{field:n,is:`is ${JSON.stringify(e)}`}]:[...new Set([...Object.keys(t),...Object.keys(e)])].flatMap(r=>{let i=`${n}.${r}`;return Object.hasOwn(t,r)?Object.hasOwn(e,r)?AV(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function jV(e,t,n,r){if(typeof e==`string`&&e!==``)return YB(s.dirname(t),e);if(sv(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(s.isAbsolute(t)||t.startsWith(`~`)||s.normalize(t).split(s.sep)[0]===`..`){r.push({path:`data.checkout`,message:`data.checkout "${t}" must be a path inside the checkout, relative to its root (like ".lit/statusline.json"): no absolute path, "~" or ".."`});return}if(n===null){r.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return s.resolve(n.root,t)}if(sv(e)&&`project`in e){r.push({path:`data.project`,message:`data: { project } is now data: { checkout }: the same path, relative to the root of the git checkout the session works in (a linked worktree is its own checkout)`});return}r.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { checkout: "<path>" } relative to the root of the session's checkout`})}function MV(e){let t=[...[...(process.env.XDG_DATA_DIRS||FV()).split(`:`).filter(e=>e!==``)].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),NV(),...e===null?[]:[s.join(e,PV)]];return t.filter((e,n)=>t.lastIndexOf(e)===n)}function NV(){let e=process.env.XDG_DATA_HOME||s.join(C.homedir(),`.local`,`share`);return s.join(e,`cc-candybar`,`plugins`)}const PV=s.join(`.cc-candybar`,`plugins`);function FV(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${s.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function IV(e){let t=MV(e),n=new Map,r=[],i=[];for(let e of t){let t=LV(e);if(`error`in t){r.push(t);continue}for(let r of t.folders)n.delete(r),n.set(r,s.join(e,r,$B));for(let n of t.files)i.push({path:s.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${$B}: move this file to ${s.join(e,`<name>`,$B)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function LV(e){try{let t=p.readdirSync(e,{withFileTypes:!0}).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),n=t=>t.isDirectory()||RV(e,t);return{folders:t.filter(n).map(e=>e.name),files:t.filter(e=>!n(e)).map(e=>e.name)}}catch(t){return t.code===`ENOENT`?{folders:[],files:[]}:{path:e,error:t.message}}}function RV(e,t){if(!t.isSymbolicLink())return!1;try{return p.statSync(s.join(e,t.name)).isDirectory()}catch{return!0}}function zV(e){return p.existsSync(s.join(e,`.git`))}function BV(e){let t=s.resolve(e);for(;;){if(zV(t))return t;let e=s.dirname(t);if(e===t)return;t=e}}function VV(e){let t=BV(e);return t===void 0?{root:s.resolve(e),git:!1}:{root:t,git:!0}}function HV(e){try{return p.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const UV=[`json5`,`json`];function WV(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?UV.map(t=>s.join(e,`.cc-candybar.${t}`)):[],...UV.map(e=>s.join(r,`.cc-candybar.${e}`)),...UV.map(e=>`${GV()}.${e}`)])]}function GV(){let e=process.env.XDG_CONFIG_HOME??s.join(C.homedir(),`.config`);return s.join(e,`cc-candybar`,`config`)}function KV(e,t,n){let r=[],i=new Map;for(let a of WV(e,t,n)){let e=HV(a);if(e===`absent`)continue;if(e!==`present`){r.push(e);continue}let t=s.join(p.realpathSync(s.dirname(a)),s.basename(a).replace(/\.(json5|json)$/,``));i.has(t)||i.set(t,a)}let a=[...i.values()].reverse();if(n===void 0)return{kind:`chain`,layers:a,home:qV(a),unchecked:r};let[o]=r,c=n;return a.length>0?{kind:`chain`,layers:a,home:c,unchecked:r}:o===void 0?{kind:`missing`,path:n,home:c}:{kind:`unreadable`,...o,home:c}}function qV(e){let t=GV();return e.find(e=>UV.some(n=>e===`${t}.${n}`))??`${t}.${UV[0]}`}function JV(e,t,n){let r=KV(e,t,n),i=r.kind===`chain`?r.layers:[];return{path:r.home,above:i.filter(e=>e!==r.home),projectDir:e??null,cwd:t??null}}function YV(e){return XV(e).join(`
181
+ `)||null}function XV(e){switch(e.kind){case`chain`:return e.unchecked.map(e=>`Config location could not be checked: ${e.path} — ${e.error}`);case`missing`:return[`Config file not found: ${e.path} — rendering the bundled default until it appears`];case`unreadable`:return[`Config file could not be read: ${e.path} — ${e.error} — rendering the bundled default until it can be`]}}function ZV(e,t){let n=WV(e,t).filter(e=>HV(e)===`present`),r=new Map;for(let e of n){let t=s.dirname(e),n=s.basename(e).replace(/\.(json5|json)$/,``),i=s.join(t,n);r.has(i)||r.set(i,[]),r.get(i).push(e)}let i=[...r.values()].filter(e=>e.length>1);return i.length===0?null:`config-extension collision: ${i.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function QV(e,t,n,r){return e===null?{...cH,config:tL(cH.raw,t)}:eH(e,p.readFileSync(e,`utf-8`),t,n,r)}const $V={projectDir:null,checkout:null,beneath:{dropped:[],rendering:new Map}};function eH(e,t,n,r,i){let a=dH(e,t,i,(t,a)=>{let o=cV(sV(t,e),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>oH(t,n,r,e,i)),s=mV(o,r.beneath.dropped);return{inherited:new Set([...dR(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=hV(tL(a.raw,o.config),s);return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(ZB)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const tH=new WeakMap;function nH(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e,iH(e)])]),a=tH.get(n)??new Map;tH.set(n,a);let o=JSON.stringify([t.projectDir,t.checkout?.root??null]),s=a.get(o);if(s?.key===i)return s.layer;let c=cV(e,t,{config:n,rendering:new Map},(e,t,n)=>oH(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function rH(e,t,n){return cV(e,{projectDir:null,checkout:n},{config:t,rendering:new Map},(e,t,n)=>oH(e,t,n,`<plugin install>`,void 0)).dropped}function iH(e){try{let t=p.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function aH(e,t,n,r,i=e=>p.readFileSync(e,`utf-8`),a){let o={projectDir:r.projectDir,checkout:r.cwd===null?null:VV(r.cwd)},s=IV(o.projectDir),c=nH(s.definitions,o,t,a),l={...c,dropped:[...c.dropped,...s.strays]};n.warned(s.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let u=l.config,d=[];for(let t of e){n.entered(t);let e=d.at(-1)?.plugins,r=eH(t,i(t),d.at(-1)?.config??u,{...o,beneath:{dropped:[...l.dropped,...d.flatMap(e=>e.plugins.dropped)],rendering:e?.rendering??l.rendering}},a);n.warned(r.warnings),d.push({...r,path:t})}let f=new Set(d.flatMap(e=>[...e.plugins.reached])),m=e=>f.has(e.path),h=l.dropped.filter(m),g=l.dropped.filter(e=>!m(e));n.warned(h.map(ZB));let _={checkout:o.checkout,roots:s.roots,loaded:l.loaded,dropped:h,unreached:g,reached:f,rendering:d.at(-1)?.plugins.rendering??l.rendering},v=d.at(-1);if(v===void 0)return{layers:d,base:u,installed:_,config:lH(QV(null,u,$V),`<default>`,a)};try{return{layers:d,base:u,installed:_,config:lH(v,v.path,a)}}catch(e){for(let e of d.slice(0,-1))n.entered(e.path),lH(e,e.path,a);throw n.entered(v.path),e}}function oH(e,t,n,r,i){if(n){lH(sH(e),r,i);return}let a=lV(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[]};if(WB(s,e,Ux(e),a),GB(s,e,a),qB(s,e,{checked:a,authored:a}),o.length>0)throw new Z_(r,o)}function sH(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const cH={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function lH({config:e,raw:t,source:n},r=`<config>`,i=new Set(Rg())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(vB(o,e,t),GB(o,e),a.length>0)throw new Z_(r,a);let s=nz(e,a);if(a.length>0)throw new Z_(r,a);let c=NI($F(s)),l=new Set([...zx({variables:t.variables??{},segments:t.segments??{}})].map(([e])=>e));if(qB(o,c,{checked:()=>!0,authored:e=>l.has(e)}),a.length>0)throw new Z_(r,a);return c}function uH(e,t,n=new Set(Rg()),r=fH){return dH(e,t,n,()=>({inherited:r,layer:null})).raw}function dH(e,t,n,r){let i=pH(e,t),a=ev(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(Rg()),groups:[]};if(!sv(i))throw new Z_(e,[{path:``,message:`Config root must be an object, got ${cv(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:gH({...c,issues:[]},i.plugins)??[],sv(i.segments)?Object.keys(i.segments):[]),d=mH(c,i,l,az(e));if(s.length>0)throw new Z_(e,s,o);return{raw:d,warnings:o,layer:u}}const fH=new Set;function pH(e,t){try{return Ii.default.parse(t)}catch(t){let n=t;throw new Z_(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function mH(e,t,n,r){for(let n of Object.keys(t))hH.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...hH].join(`, `)}`,line:G(e.source,[n])});let i={};return t.globals!==void 0&&(i.globals=$A(e,`globals`,t.globals)),t.variables!==void 0&&(i.variables=bL(e,`variables`,t.variables)),t.segments!==void 0&&(i.segments=fR(e,t.segments,n)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
182
182
  Replace: layout: [["seg1", "seg2"], ["seg3"]]
183
183
  With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
184
- Single-row example: root: { h: ["seg1", "seg2"] }`,line:G(e.source,[`layout`])}),t.root!==void 0&&(i.root=NR(e,`root`,t.root)),t.actions!==void 0&&(i.actions=tz(e,t.actions,r)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:G(e.source,[`looks`])}),t.styles!==void 0&&(i.styles=Xz(e,t.styles)),t.themeDefaults!==void 0&&(i.themeDefaults=ZA(e,t.themeDefaults)),t.presets!==void 0&&(i.presets=Qz(e,t.presets)),t.editGlobals!==void 0&&(i.editGlobals=tj(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(i.helpers=$z(e,t.helpers)),t.plugins!==void 0&&(i.plugins=mH(e,t.plugins)),VR(e,i),QR(e,i),Fj(e,i),bA(e,i,X,`the global settings menu`),i}const pH=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function mH(e,t){if(Array.isArray(t)&&t.every(e=>typeof e==`string`&&e!==``))return t;e.issues.push({path:`plugins`,message:`"plugins" must be a list of plugin definition paths, got ${cv(t)}`,line:G(e.source,[`plugins`])})}const hH={},gH=dP(`commands.`),_H=_P(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),vH=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,yH=`{{ \$dir := .current_dir }}{{ if and (ne .home "") (or (eq .home .current_dir) (hasPrefix (printf "%s/" .home) .current_dir)) }}{{ \$dir = printf "~%s" (trimPrefix .home .current_dir) }}{{ else }}{{ if or (eq .project_dir .current_dir) (hasPrefix (printf "%s/" .project_dir) .current_dir) }}{{ $dir = ternary (${vH}) (basename .project_dir) (ne (${vH}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,bH=`{{ ${uM} }}`,xH={min:0,max:100,step:5},SH={warnAt:{label:`warning at %`,domain:xH,default:50},errorAt:{label:`error at %`,domain:{...xH,atLeast:`warnAt`},default:80}};function CH(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:xH,default:80}}}const wH={globals:{palette:`tokyo-night`},variables:{...gH.variables,...iA,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"effort.level":{kind:`input`,path:`effort.level`,default:``},"effort.glyphs":{kind:`literal`,value:`? 󰅃 󰅃 󰄿 󰶼`},version:{kind:`input`,path:`version`,default:``},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.tracking":{kind:`input`,path:`git.tracking`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.committedAt":{kind:`input`,path:`git.committedAt`,type:`number`,default:0},"git.timeSinceCommit":{kind:`template`,type:`number`,template:`{{ if gt .git.committedAt 0 }}{{ sub (int (unixEpoch now)) .git.committedAt }}{{ else }}0{{ end }}`},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`template`,type:`number`,template:`{{ etaMinutes .block.nativeUtilization .block.resetsAt 300 }}`},"weekly.etaMinutes":{kind:`template`,type:`number`,template:`{{ etaMinutes .weekly.percentage .weekly.resetsAt 10080 }}`},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``}},segments:{directory:{group:`location`,description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:yH},model:{group:`model-context`,description:`The active model's display name, followed by the effort gauge (a chevron ladder, climbing on a bubble at max) when an effort level is set.`,template:`✱ {{ formatModelName .model.display_name }}{{ if ne .effort.level "" }} {{ template "effortGauge" . }}{{ end }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{group:`session-tools`,description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{group:`model-context`,description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{group:`location`,description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{group:`location`,description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{group:`git`,description:`The git state: a summary (branch, ahead/behind, S/U/? flags) that the arrow at its right edge expands to every fact — repo, in-progress operation, sha, upstream ±, stash count, time since the last commit.`,template:`{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}`,fg:bH,when:`{{ ne .git.branch "" }}`,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if eq .git.prState "open" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (eq .git.prState "open") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:eP(``).template},commands:{group:`session-tools`,description:`Type /compact, /model or /clear into this session; /clear asks for a second click. Hidden when not inside tmux.`,template:gH.template,when:gH.when},themeSwitcher:{group:`session-tools`,description:"`◀ <theme> ▶`: the theme the bar is wearing; ◀ and ▶ switch this session to the previous or next theme, wrapping at the ends.",template:`{{ carousel "stepTheme" 0 }}`},session:{group:`cost-limits`,description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:CH(0)},today:{group:`cost-limits`,description:`Today's cost and tokens across every session, with a budget warning once a budget is configured.`,template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:CH(50)},block:{group:`cost-limits`,description:`The 5-hour rate-limit block: percent used and time to reset, heating to warning then error.`,template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:SH,when:`{{ gt .block.resetsAt 0 }}`},weekly:{group:`cost-limits`,description:`The weekly rate-limit quota: percent used and time to reset, heating to warning then error.`,template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:SH,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{group:`cost-limits`,description:`Spend per hour, with the projected time to the 5-hour and weekly limits.`,template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 (tint) 0 "error" .settings.errorWithin "warning" .settings.warnWithin (tint) }}`,settings:{errorWithin:{label:`error within (min)`,domain:{min:0,max:300,step:5},default:30},warnWithin:{label:`warning within (min)`,domain:{min:0,max:300,step:5,atLeast:`errorWithin`},default:60}},when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{group:`activity`,description:`Token throughput for the latest exchange: output, input, and total.`,template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{group:`activity`,description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,when:`{{ ne .speed.history "" }}`},cacheTimer:{group:`activity`,description:"Minutes until the prompt cache expires, or `cold` once it has.",template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ readableOn (color (cascade (minutesUntilReset .cache.expiresAt) "0:error" "9:warning" "21:foreground")) (bgOf) ${Yh} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:_H.template,bg:_H.bg,when:_H.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...eP(``).actions,...gH.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},..._H.actions},styles:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},themeDefaults:hH,presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{effortGauge:`{{ \$ord := default 0 (get (dict "low" 1 "medium" 2 "high" 3 "xhigh" 4 "max" 5) .effort.level) }}{{ \$glyphs := compact (splitList " " .effort.glyphs) }}{{ $bubble := readableOn (mix (bgOf) (color "accent") 40) (bgOf) 1.08 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${Yh} }}{{ \$climb := frames 1 (index \$glyphs 1) 1 (index \$glyphs 3) 1 (index \$glyphs 4) }}{{ if eq \$ord 5 }}{{ fg \$bubble "" }}{{ bg \$bubble (fg \$climbing \$climb) }}{{ fg \$bubble "" }}{{ else }}{{ fg (ramp $ord "step" 0 (${uM}) 2 (readableOn (color "accent") (bgOf) ${Yh})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Yh}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ $age := .git.timeSinceCommit }}{{ if and .settings.age (gt $age 0) }} ◷ {{ template "formatTimeSince" $age }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:vP(`.`),formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatToolTally:`{{ $names := splitList "," . }}{{ range $i, $pair := $names }}{{ if lt $i 2 }}{{ if $i }} {{ end }}{{ $kv := splitList ":" $pair }}{{ index $kv 0 }}{{ if ne (index $kv 1) "1" }}×{{ index $kv 1 }}{{ end }}{{ end }}{{ end }}{{ if gt (len $names) 2 }} +{{ sub (len $names) 2 }}{{ end }}`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},TH=new Set([wH.globals.palette,...Object.keys(wH.themeDefaults),...Object.values(wH.segments).map(e=>e.palette)].filter(e=>e!==void 0)),EH=$I(cH(`<default>`,JSON.stringify(wH),TH),wH),DH=Qb(EH.presets);function OH(e){return DH.includes(e)}const kH=Object.freeze({});function AH(e,t){return e.kind===`decided`?t[e.name]??kH:kH}function jH(e,t){return{...e,...Object.fromEntries(hy.map(n=>[n,e[n]??t[n]]))}}const MH=e=>Bv(t=>e[Pv[t].setting]);function NH(e,t,n,r){let i=_y(e);return Lg(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function PH(e,t){return $b(t(`preset`),e.globals.preset,e.presets)}function FH(e,t,n){let r=PH(e,t),i=nx(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Lb(a.palette,t(`theme`),i.palette),s=jH(i,AH(o,e.themeDefaults));return{...Object.fromEntries(py.map(e=>[e,NH(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:Yg(a.style,t(`style`),s.style,e.styles),effect:a_(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function IH(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?m_:h_;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const LH=Object.entries(Sy),RH=new Set(wy.map(e=>e.sessionKey)),zH=()=>!1;function BH(e,t){return FH(e,e=>RH.has(e)?t(e):null,zH)}const VH=[`preset`,`theme`];function HH(e,t,n){let r=new Set(VH.slice(0,n).map(e=>Sy[e].sessionKey));return FH(e,e=>r.has(e)?t(e):null,zH)}function UH(e,t){let n=Array.from({length:VH.length+1},(n,r)=>HH(e,t,r));return e=>{let t=VH.indexOf(e);return n[t===-1?VH.length:t]}}function WH(e,t,n,r){return e.flatMap(([e,i])=>{let a=IH(t,e);return a===null||a===IH(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function GH(e,t,n){return IH(BH(e,t),n)}function KH(e,t){let n=BH(e,t);return WH(LH,n,UH(e,t),t=>qH(e,n.preset,t.configKey))}function qH(e,t,n){return n in(ex(e.presets,t).globals??{})?hj(t,n):n}function JH(e,t,n){let r=$b(t(Sy.preset.sessionKey),e.globals.preset,e.presets),i=gj(n);return{key:i?.scope===`globals`?qH(e,r,i.field):n,globals:nx(e,r)}}function YH(e,t){let{preset:n}=BH(e,t);return QH(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:K_(a,s);return c===void 0||G_(c)===G_(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function XH(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Qb(e.presets).flatMap(n=>{let i=QH(e,n);return[...new Set(i.filter(e=>r.has(e.key)).map(e=>e.id))].flatMap(e=>{let n=i.filter(t=>t.id===e);return U_(Object.fromEntries(n.map(e=>[e.setting,e.decl])),Object.fromEntries(n.map(e=>{let n=r.get(e.key)??t(e.key),i=n===null?void 0:K_(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const ZH=new WeakMap;function QH(e,t){let n=ZH.get(e)??new Map;ZH.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...E_(tx(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=V_(e.segments[t.name])[n];return{id:r,setting:n,key:i,decl:a,saved:t.settings?.[n]??a.default}})),a=[...new Map(i.map(e=>[e.key,e])).values()];return n.set(t,a),a}function $H(e,t){let n=BH(e,t);return{from:n.preset,globals:ex(e.presets,n.preset).globals??{},picks:WH(LH.filter(([e])=>e!==`preset`),n,UH(e,t),e=>e.configKey),placements:YH(e,t)}}function eU(e,t){return FH({...e,globals:{palette:t},presets:{}},()=>null,zH)}function tU(e,t){let n=BH(e,t),r=IH(n,`theme`);if(r===null)return{kind:`rule`};let i=eU(e,r),a=nx(e,n.preset),o=Object.fromEntries(hy.map(e=>[e,IH(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:hy.some(e=>o[e]!==IH(i,e))}}function nU(e){return{sessionKeys:wy.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...qA(e)?DH.map(t=>hj(t,e)):[],...mj(e)?Rg().map(t=>pj(t,e)):[]]}}function rU(e){return new Set(wy.map(e=>e.configKey).filter(t=>nU(t).fileKeys.some(t=>oU(e,aU(t)))))}function iU(e,t,n){let r=KH(e,n),i=new Set(r.map(e=>e.configKey)),a=ky(e=>i.has(Sy[e].configKey)||t.has(Sy[e].configKey)),o=tU(e,n);return{unsaved:r.length+YH(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function aU(e){let t=gj(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return _j(t)}function oU(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&oU(e[n],r)}const sU=Rg(),cU=new Set(sU),lU=new Set(o_),uU=e=>e?cU.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${sU.join(`, `)})`}:{ok:!1,reason:`theme name is required`},dU=e=>e?lU.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${o_.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},fU=new Set([`1`,`true`]),pU=new Set([`0`,`false`]),mU={endcaps:dU,theme:uU,"toolbar-expanded":e=>fU.has(e)?{ok:!0,value:`1`}:pU.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},hU=WI(mU,`state`,SU);function gU(e,t){return hU.register(e,t)}function _U(e){return hU.gateFor(e)}function vU(e,t){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:cx(e.from,t).members}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function yU(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(mU,e.key))}function bU(e,t,n){let r=Ay.get(n);if(r!==void 0)return GH(e,t,r);for(let[,t]of L_(e))if(t.key===n)return t.default??null;return null}function xU(e){let t=pI(e);return yU(Object.values(e.actions).flatMap(e=>vU(e,t)))}function SU(e){return HI(xU(e))}const CU=`update.dismissed`,wU=`updateNotice`,TU=Sy.updateNotice.sessionKey;function EU(e){return e.kind===`source`?e.newer.digest:uo(e.newer)}const DU=e=>`${e.version} [${Xe(e.digest)}]`;function OU(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:DU(e.newer),running:DU(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:uo(e.newer),running:uo(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${po}@${uo(e.newer)}`,`install`]}}}}const kU={kind:`idle`},AU={kind:`running`};function jU(e,t,n){if(e===null)return[];let r=EU(e);if(!n.enabled||n.dismissed===r)return[];let i=OU(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
185
- `),c=pi([{verb:Wr,args:[s]}]),l=t.kind===`running`?yb(`[${i.busy}]`,c):yb(`[${i.act}]`,pi([{verb:ii,args:[n.sessionId]}]));return[{severity:_b,message:s,lines:[[yb(a,c),l,yb(`[dismiss]`,pi([{verb:Rr,args:[n.sessionId,CU,r]}])),yb(`[disable]`,pi([{verb:Kr,args:[n.sessionId,wU,`false`]},{verb:Rr,args:[n.sessionId,TU,`false`]}]))],...o.map(e=>[yb(e,c)])]}]}function MU(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function NU(e){switch(e.kind){case`current`:return[`info`,`build: current ${DU(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${DU(e.source)}, running ${DU(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function PU(e){switch(e.kind){case`current`:return[`info`,`release: current ${uo(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${uo(e.latest)}, running ${uo(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${uo(e.installed)}, latest ${uo(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function FU(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const IU=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function LU(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=IU(e.stderr)??e.error??IU(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function RU(){let e=[KI(wU,[`false`]),gU(TU,[`false`]),gU(CU,[])];return()=>e.forEach(e=>e())}function zU(e){let{entryUrl:t,intervalMs:n,releaseIntervalMs:r,registryUrl:i,fetchImpl:a,onApplied:o,log:s}=e,c={kind:`unchecked`,reason:`not sampled yet`},l=null,u=kU,d=null,f=FU(s),p=FU(s),m=()=>MU(c,l);function h(){let e=m(),t=e===null?null:EU(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:gU(CU,[t])})}function g(){c=nt(t,$e),f(NU(c)),h()}async function _(){l=ho(Ze,await mo(po,a,i)),p(PU(l)),h()}return{arm(){RU(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>jU(m(),u,e),act(){let e=m();if(e===null)throw new q(`apply-update: nothing newer is known to apply`);let t=OU(e);if(u.kind===`running`)throw new q(`apply-update: already ${t.busy}`);u=AU,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),pt({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=kU,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=LU(n);u={kind:`failed`,identity:EU(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}function BU(e,t){try{return P(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?F:I(e.message)}}function VU(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function HU(e){let{targets:t,intervalMs:n,stat:r,exit:i,log:a}=e,o=t.map(e=>({path:e,stamp:BU(e,r)})),s=o.filter(({stamp:e})=>e.kind!==`failed`),c=null,l=()=>{for(let{path:e,stamp:t}of s){let n=BU(e,r);if(n.kind===`failed`){a(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!VU(t,n)){a(`info`,`binary ${n.kind===`absent`?`gone`:`changed`} (${e}); shutting down`),c&&clearInterval(c),i();return}}};return{arm(){for(let{path:e,stamp:t}of o)t.kind===`failed`&&a(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);c=setInterval(l,n),c.unref()},checkNow:l}}const UU=`${Iy}${Fy}`;function WU(e){return`${UU}⚠ cc-candybar: ${GU(e)}${Ly}\n`}function GU(e){switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:return`daemon rejected request: ${Py(e.message,60)}`;case`render_failed`:return`render failed: ${Py(e.message,60)}`;case`switched_off`:return`switched off: ${Py(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${Py(e.message,60)}`}}function KU(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
186
- `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:WU(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}const qU=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function JU(e){if(e===void 0||e.isDefault)return;let t=e.fixedValue;if(t!==void 0)return t.hex;let n=e.type===R.STANDARD&&e.number!==void 0?qU[e.number]:void 0;if(n===void 0)throw Error(`frames: no band colour for ${e.name}`);return n}const YU={bold:`bold`,dim:`dimColor`,italic:`italic`,underline:`underline`,strike:`strikethrough`,reverse:`inverse`,blink:null,blink2:null,conceal:null,underline2:null,frame:null,encircle:null,overline:null},XU=Object.keys(YU);function ZU(e,t){let n=JU(t.color),r=JU(t.bgcolor),i={};for(let e of XU){if(t[e]!==!0)continue;let n=YU[e];if(n===null)throw Error(`frames: the band cannot draw ${e} text`);i[n]=!0}return{text:e,...n!==void 0&&{color:n},...r!==void 0&&{backgroundColor:r},...i,...t.link!==void 0&&{href:t.link}}}const QU=new V;function $U(e){return{ok:!0,band:new zp().decode(e).map(e=>{let t=e.plain,n=[],r=0;for(let i of e.spans){if(!(i.style instanceof V))throw Error(`frames: the decoder gave a span a ${typeof i.style} style`);i.start>r&&n.push(ZU(t.slice(r,i.start),QU)),n.push(ZU(t.slice(i.start,i.end),i.style)),r=i.end}return r<t.length&&n.push(ZU(t.slice(r),QU)),n})}}function eW(e){let t=KU(mn(e)).output;try{return $U(t)}catch(e){return $U(`${Iy}${Fy}⚠ cc-candybar ${Ny(e instanceof Error?e.message:String(e))}${Ly}\n`)}}function tW(e){return`ccb`+te(`sha256`).update(e).digest(`hex`).slice(0,12)}const nW=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function rW(e){if(e===void 0||e.isDefault)return`terminal`;switch(e.type){case R.STANDARD:{let t=e.number===void 0?void 0:nW[e.number];if(t!==void 0)return t;break}case R.EIGHT_BIT:if(e.number!==void 0)return`colour${e.number}`;break;case R.TRUECOLOR:{let t=e.fixedValue;if(t!==void 0)return t.hex;break}case R.DEFAULT:case R.WINDOWS:break}throw Error(`frames: no tmux colour for ${e.name}`)}const iW={bold:`bold`,dim:`dim`,italic:`italics`,underline:`underscore`,strike:`strikethrough`,reverse:`reverse`,blink:`blink`,conceal:`hidden`,underline2:`double-underscore`,overline:`overline`,blink2:null,frame:null,encircle:null},aW=Object.keys(iW);function oW(e){return e.replaceAll(`#`,`##`)}function sW(e){let t=aW.filter(t=>e[t]===!0).map(e=>{let t=iW[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${rW(e.color)}`,`bg=${rW(e.bgcolor)}`,...t].join(`,`)}]`}const cW=new V;function lW(e){let t={},n=(e,n)=>{let r=sW(n)+oW(e);if(n.link===void 0)return r;let i=tW(n.link);return t[i]=n.link,`#[range=user|${i}]${r}#[norange]`};return{rows:new zp().decode(e).map(e=>{let t=e.plain,r=[],i=0;for(let a of e.spans){if(!(a.style instanceof V))throw Error(`frames: the decoder gave a span a ${typeof a.style} style`);a.start>i&&r.push(n(t.slice(i,a.start),cW)),r.push(n(t.slice(a.start,a.end),a.style)),i=a.end}return i<t.length&&r.push(n(t.slice(i),cW)),r.join(``)}),links:t}}function uW(e){let t=KU(mn(e)).output;try{return lW(t)}catch(e){return lW(`${Iy}${Fy}⚠ cc-candybar ${Ny(e instanceof Error?e.message:String(e))}${Ly}\n`)}}const dW={band:e=>JSON.stringify(eW(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:uW(e)})};function fW(e){let t=typeof e==`string`?e===``?`is empty`:e===`.`||e===`..`?`is ${JSON.stringify(e)}, which names a folder, not a session`:/[/\\\0]/.test(e)?`contains a path separator or NUL: ${JSON.stringify(e)}`:Buffer.byteLength(e,`utf8`)>250?`is longer than 250 bytes`:null:`is not a string: ${JSON.stringify(e)??String(e)}`;return t===null?{ok:!0,id:e}:{ok:!1,problem:t}}function pW(e,t){return e.kind===`absent`?P(`none`):e.kind===`failed`?e:t.kind===`failed`?t:P(t.kind===`ok`?`tracked`:`gone`)}function mW(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?I(`HEAD: ${t.reason}`):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const hW={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},gW={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function _W(e,t,n){return Object.hasOwn(t,n)?P(t[n]):I(`${e}: unknown state ${JSON.stringify(n)}`)}const vW={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,tag:`tag`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function yW(e){return Object.keys(vW).flatMap(t=>{let n=e[t];return n?.kind===`failed`?[`git.${vW[t]}: ${n.reason}`]:[]})}function bW(e,t,n){return t.ok?P(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?F:I(xW(e,t))}function xW(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??SW(t.stderr)].filter(Boolean).join(`, `)}`}function SW(e){return e.trim().split(`
187
- `,1)[0]??``}function CW(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?F:P(n)}function wW(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?P(t):F}const TW={github:`gh`,gitlab:`glab`};function EW(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const DW=/^[A-Za-z]:[\\/]/;function OW(e){let t=e.trim();if(DW.test(t))return null;let n=t.match(/^(?:[^@/]+@)?(\[[^\]]+\]):(.*)$/)??t.match(/^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.*)$/),r=n?`ssh://${n[1]}/${n[2].replace(/^\/+/,``)}`:t,i;try{i=new URL(r)}catch{return null}return{scheme:i.protocol.replace(/:$/,``),host:i.hostname.toLowerCase(),port:i.port,path:i.pathname.replace(/^\/+/,``).replace(/\/+$/,``)}}function kW(e){return OW(e)?.host||null}function AW(e){let t=kW(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const jW=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function MW(e){let t=bW(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?NW(t.value):[]}}function NW(e){let t=new Map;for(let n of e.split(`
188
- `)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function PW(e){return e.urls.find(e=>zW(e)!==null)??e.urls[0]??null}function FW(e){return e.find(e=>e.name===`origin`)??e[0]??null}function IW(e){let t=FW(e);return t?PW(t):null}function LW(e){let t=FW(e);return t?t.urls.find(e=>AW(e)!==null)??PW(t):null}function RW(e){let t=(OW(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function zW(e){let t=OW(e);if(!t)return null;let n=t.scheme===`https`?{scheme:`https`,port:t.port}:t.scheme===`http`?{scheme:`http`,port:t.port}:t.scheme===`ssh`||t.scheme===`git`?{scheme:`https`,port:``}:null;if(!n||!t.host)return null;let r=t.path.replace(/\.git$/,``);if(!r)return null;let i=n.port?`${t.host}:${n.port}`:t.host;return`${n.scheme}://${i}/${r}`}function BW(e){let t=IW(e);return t===null?null:zW(t)}function VW(e,t,n,r){return t.ok?r(t.stdout):EW(t)||t.reason===`non-zero`&&n.test(t.stderr)?F:I(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??SW(t.stderr)].filter(Boolean).join(`, `)}`)}function HW(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function UW(e){let t=`detached`,n=F,r=F,i=F,a=0,o=0,s=0,c=0;for(let l of e.split(`
189
- `)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?F:P(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=P(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=P({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function WW(e){let t;try{t=JSON.parse(e)}catch(e){return I(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!HW(t))return I(`gh pr view: JSON is not an object`);let{number:n,state:r,url:i,headRefOid:a}=t;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return I(`gh pr view: missing number/state/url/headRefOid`);let o=_W(`gh pr view`,hW,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function GW(e){let t;try{t=JSON.parse(e)}catch(e){return I(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!HW(t))return I(`glab mr view: JSON is not an object`);let n=t.iid,r=t.state,i=t.web_url,a=t.sha;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return I(`glab mr view: missing iid/state/web_url/sha`);let o=_W(`glab mr view`,gW,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function KW(e){try{let t=p.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var qW=class{isGitRepo(e){return LV(e)}async execGitAsync(e,t){return pt({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}resolveEffectiveGitDir(e,t){return this.isWorktree(e)?P(e):t&&this.isGitRepo(t)?P(t):this.isGitRepo(e)?P(e):this.findGitRoot(e)}findGitRoot(e){let t=RV(e);return t===void 0?F:P(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return I(`git: ${e instanceof Error?e.message:String(e)}`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=this.findGitRoot(e);if(t.kind!==`ok`)return t;r=t.value}let a=await this.getCoreAsync(r);if(a.kind!==`ok`)return a;let o={branch:a.value.branch,status:a.value.status,aheadBehind:a.value.aheadBehind,head:a.value.oid};t.showWorkingTree&&(o.workingTree=a.value.workingTree),t.showSha&&(o.sha=CW(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showCommittedAt&&(o.committedAt=await this.committedAt(r,a.value.oid)),t.showStashCount&&(o.stashCount=this.getStashCount(r));let s=t.showRepoName||t.showRepoUrl?await this.getRemotesAsync(r):void 0;return s!==void 0&&t.showRepoName&&(o.repoName=CW(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=CW(s,BW)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),P(o)}resolveGitDir(e){let t=s.join(e,`.git`);try{if(p.existsSync(t)&&p.statSync(t).isFile()){let n=p.readFileSync(t,`utf-8`).match(/^gitdir:\s*(.+)$/m);if(n?.[1])return s.resolve(e,n[1].trim())}}catch{}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return p.existsSync(s.join(t,`MERGE_HEAD`))?P(`MERGE`):p.existsSync(s.join(t,`CHERRY_PICK_HEAD`))?P(`CHERRY-PICK`):p.existsSync(s.join(t,`REVERT_HEAD`))?P(`REVERT`):p.existsSync(s.join(t,`BISECT_LOG`))?P(`BISECT`):p.existsSync(s.join(t,`rebase-merge`))||p.existsSync(s.join(t,`rebase-apply`))?P(`REBASE`):F}catch(e){return I(`git operation probe: ${e instanceof Error?e.message:String(e)}`)}}async getNearestTagAsync(e){return wW(bW(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestamp(e,t.value):t}commitTimes=new Map;async commitTimestamp(e,t){let n=this.commitTimes.get(t);if(n!==void 0)return this.commitTimes.delete(t),this.commitTimes.set(t,n),n;let r=this.readCommitTimestamp(e,t);for(this.commitTimes.set(t,r),r.then(e=>{e.kind!==`ok`&&this.commitTimes.get(t)===r&&this.commitTimes.delete(t)},()=>{this.commitTimes.get(t)===r&&this.commitTimes.delete(t)});this.commitTimes.size>256;){let e=this.commitTimes.keys().next().value;if(e===void 0)break;this.commitTimes.delete(e)}return r}async readCommitTimestamp(e,t){let n=wW(bW(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10);return Number.isNaN(r)?I(`git log -1: unparseable timestamp "${n.value}"`):P(r)}resolveCommonGitDir(e){let t=this.resolveGitDir(e);try{let e=p.readFileSync(s.join(t,`commondir`),`utf-8`).trim();if(e)return s.resolve(t,e)}catch{}return t}getStashCount(e){let t=s.join(this.resolveCommonGitDir(e),`logs`,`refs`,`stash`),n;try{n=p.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?P(0):I(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`)}let r=n.trim();return P(r?r.split(`
190
- `).length:0)}async getRemotesAsync(e){let t=KW(s.join(this.resolveCommonGitDir(e),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){return MW(await this.execGitAsync(jW,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=IW(e);return(n===null?null:RW(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=LW(t.value);return n===null?F:P(n)}async execForgeAsync(e,t,n){return pt({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=AW(t);return n===`github`?VW(`gh pr view`,await this.execForgeAsync(TW.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,WW):n===`gitlab`?VW(`glab mr view`,await this.execForgeAsync(TW.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,GW):F}isWorktree(e){try{let t=s.join(e,`.git`);return!!(p.existsSync(t)&&p.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){E(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=bW(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?P(UW(t.value)):t}};const JW=(e,t)=>E(t);function YW(e,t){return t.kind===`failed`?t:e.kind===`changed`?t.kind===`unknown`?t:{kind:`changed`,names:new Set([...e.names,...t.names])}:e}const XW=e=>e===null?{kind:`unknown`}:{kind:`changed`,names:new Set([e])};var ZW=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??JW}acquire(e,t,n){if(this.closed)return{release:()=>{},refused:[...t.files,...t.dirs.map(e=>e.path)].map(e=>({path:e,reason:`the watcher registry is closed`}))};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,this.makeHandle(r);let i={key:e,watchers:[],refcount:1,debounce:null,onInvalidate:n,targets:t,refused:[]};return this.openWatchers(i),this.slots.set(e,i),this.counters&&(i.refused.length===0?this.counters.watchersOpened++:this.counters.watchRefusals++),this.makeHandle(i)}makeHandle(e){let t=!1;return{refused:e.refused,release:()=>{t||(t=!0,this.slots.get(e.key)===e&&(e.refcount=Math.max(0,e.refcount-1),e.refcount===0&&(this.closeSlot(e),this.slots.delete(e.key))))}}}openWatchers(e){let t=t=>{if(e.debounce!==null){e.debounce.window=YW(e.debounce.window,t);return}let n={window:t,timer:setTimeout(()=>{e.debounce=null;try{e.onInvalidate(n.window)}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50)};n.timer.unref(),e.debounce=n},n=e=>n=>{this.logger(`warn`,`watcher error ${e}: ${n.message}`),this.counters&&this.counters.watchErrors++,t({kind:`failed`,reason:`${e}: ${n.message}`})},r=[],i=(e,t)=>{let n=t.message;this.logger(`warn`,`watch failed ${e}: ${n}`),r.push({path:e,reason:n})};for(let r of e.targets.files)try{let i=p.watch(r,{persistent:!1},(e,n)=>t(XW(n)));i.on(`error`,n(r)),e.watchers.push(i)}catch(e){i(r,e)}for(let r of e.targets.dirs)try{let i=r.filenames?new Set(r.filenames):null,a=p.watch(r.path,{persistent:!1},(e,n)=>{i&&(!n||!i.has(n))||t(XW(n))});a.on(`error`,n(r.path)),e.watchers.push(a)}catch(e){i(r.path,e)}e.refused=r}closeSlot(e){e.debounce!==null&&(clearTimeout(e.debounce.timer),e.debounce=null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}};function QW(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var $W=class{timer=null;state=`released`;last=null;constructor(e,t=Date.now){this.tick=e,this.now=t}landed(e,t=this.now()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.now());this.timer=setTimeout(()=>{this.timer=null,this.tick()},e),this.timer.unref?.()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function eG(){return J.observable.box(tG(`unread`),{deep:!1})}function tG(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function nG(e,t){let n=e.reading.get();n.kind===`read`&&(0,J.compareStructural)(n.outcome,t)||((0,J.runInAction)(()=>e.reading.set({kind:`read`,outcome:t})),n.kind===`pending`&&n.land())}function rG(e,t){let n=e.reading.get();n.kind===`read`?(0,J.runInAction)(()=>e.reading.set(tG(t))):n.why!==t&&t===`unread`&&(0,J.runInAction)(()=>e.reading.set({...n,why:t}))}function iG(e,t){e.reading.get().kind===`pending`&&nG(e,t)}function aG(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function oG(e){let t=e.reading.get();return t.kind===`read`?t.outcome:t}async function sG(e){for(;;){let t=e();if(!aG(t))return t;await t.landed}}function cG(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),Math.max(0,t));return new Promise((t,i)=>{r.signal.addEventListener(`abort`,()=>t(`deadline`)),e(r.signal).then(()=>t(`answered`),e=>r.signal.aborted?n(e):i(e))}).finally(()=>{clearTimeout(i),r.abort()})}function lG(e){return{current:()=>e}}function uG(e){return sG(()=>e.current())}const dG=`pass`,fG={okMs:5*6e4,failedMs:45e3};function pG(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function mG(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function hG(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function gG(e){let t=[{path:e,filenames:[`HEAD`,`index`]}],n=s.join(e,`refs/heads`);try{p.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[],dirs:t}}function _G(e){return e.find(e=>e.kind===`ok`)?.value.branch}function vG(e){e.missed=!0,rG(e,`unread`)}function yG(e,t){return e.missed&&e.reading.get().kind===`pending`&&nG(e,t.size>0?I([...t].join(`; `)):F),`unkeyed`}function bG(e,t){let n=oG(e);return t===null||n.kind!==`ok`?n:P({...n.value,pullRequest:oG(t)})}function xG(e){return t=>I(`${e} threw: ${String(t)}`)}var SG=class{repos=new Map;resolutions=new Map;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;watchers;ownsWatchers;logger;constructor(e={}){this.inner=e.inner??new qW,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Me;let t=e.ledger??new jk(this.logger);this.gitRefreshes=t.declare({name:`git`,scope:`repo`,refresh:[`first`,`period`,`change`]}),this.prRefreshes=t.declare({name:`pr`,scope:`repo`,refresh:[`first`,`period`]}),e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new ZW({logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=I(`resolver threw: ${String(e)}`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`not-a-repo`)return lG(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>bG(a,o)}}asked(e,t,n,r){let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`not-a-repo`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n=this.inner.resolveGitDir(e),r={root:e,refresh:new kk,watcher:this.watchers.acquire(`git:${e}`,gG(n),()=>this.changed(e)),period:new $W(()=>{r.refresh.share(dG,()=>this.refreshPass(r))}),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,r),r}changedPass(e,t){e.asked.add(t),e.refresh.run(dG,()=>this.refreshPass(e))}async refreshPass(e){try{await this.pass(e)}catch(t){this.logger(`error`,`git refresh threw (${e.root}): ${String(t)}`)}finally{e.period.landed(this.periodMs)}}hold(e,t,n){return e.holders++,n!==null&&(n.holders++,t.missed&&vG(n),n.missed&&e.asked.add(`owed`)),t.readers++,t.missed&&e.asked.add(`resume`),this.held(e),this.evict(),()=>{e.holders--,t.readers--,n!==null&&n.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(dG,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr?.period.hold(e.pr.holders>0&&!e.pr.missed)}valueOf(e,t,n){let r=e.values.get(t);if(r!==void 0)return r;let i={options:n,reading:eG(),readers:0,missed:!1};return e.values.set(t,i),e.asked.add(`first`),i}ask(e,t,n,r){let i=e.asked.size,a=hG(n),o=this.valueOf(e,a,n);r&&e.pr===null&&(e.pr=this.prSource(e),e.asked.add(`pr`));let s=r?e.pr:null;return t.take(mG(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}async pass(e){if(this.repos.get(e.root)!==e)return;let t=Date.now(),n=[...e.asked];e.asked.clear();let r=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?r.push(t):t.missed=!0;let i=e.pr,[a,o]=await Promise.all([Promise.all(r.map(t=>this.inner.getGitInfo(e.root,t.options).catch(xG(`git fetch`)))),i!==null&&i.holders>0?this.remoteOf(e):null]);if(this.repos.get(e.root)!==e)return;let s=new Set;r.forEach((e,t)=>{let n=a[t];if(e.missed=!1,nG(e,n),n.kind===`failed`&&s.add(n.reason),n.kind===`ok`)for(let e of yW(n.value))s.add(e)});let c=_G(a),l=i===null||r.length===0?`-`:c===void 0?yG(i,s):this.movePr(e,i,c,o??i.remote);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} values=${r.length} pr=${l}`,pG(n),s.size===0?P(null):I([...s].join(`; `)),Date.now()-t)}prSource(e){let t={period:new $W(()=>{this.readPr(e,t,`period`)}),seen:new Map,holders:0,missed:!0,key:``,remote:F,reading:eG(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(xG(`git remote`))}movePr(e,t,n,r){let i=`${n}|${r.kind===`ok`?r.value:r.kind}`;if(i===t.key&&!t.missed)return`kept`;t.key=i,t.remote=r;let a=t.seen.get(i);return a===void 0?t.holders===0?(vG(t),`owed`):(rG(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,nG(t,a.outcome),t.period.landed(QW(fG,a.outcome),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=Date.now(),o=(i.kind===`ok`?this.inner.resolvePullRequest(e.root,i.value).catch(xG(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:F)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${as(r)}`,n,i,Date.now()-a);let o=Date.now();t.seen.delete(r),t.seen.set(r,{outcome:i,at:o});for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==r||t.missed||(nG(t,i),t.period.landed(QW(fG,i),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=I(`git state dropped: ${e.root}`);for(let n of e.values.values())iG(n,t);e.pr!==null&&iG(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watcher.release(),e.period.dispose(),e.pr?.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},CG=class{static CACHE_DIR=bt();static USAGE_CACHE_DIR=s.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=s.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=s.join(this.LOCKS_DIR,e);if(!p.existsSync(t))return!1;try{let n=p.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return E(`Invalid PID in lock file ${e}, removing stale lock`),p.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(E(`Removing stale lock file ${e} for dead process ${r}`),p.unlinkSync(t),!1):(E(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return E(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=s.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await p.promises.writeFile(n,i,{flag:`wx`}),E(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await be(50);else throw e}return E(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=s.join(this.LOCKS_DIR,e);try{await p.promises.unlink(t),E(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&E(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([p.promises.mkdir(this.CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){E(`Failed to create cache directories:`,e)}}static createProjectHash(e){return te(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=s.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){E(`Cache for ${e} is locked, waiting...`),await be(75);continue}try{let r=await p.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(E(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(E(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return E(`No shared ${e} usage cache found`),null;E(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await be(75)}}return E(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){E(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=s.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await p.promises.writeFile(r,i,`utf-8`),E(`[CACHE-SET] ${e} disk cache stored`)}catch(t){E(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const wG={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var TG=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await CG.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await CG.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=ye({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){E(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){E(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(E(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),E(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(E(`Invalid pricing data structure`),e(null))}catch(t){E(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{E(`Response error:`,t),e(null)})});r.on(`error`,t=>{E(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{E(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return E(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return E(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),E(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(E(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(wG).length} models`),this.executionCache=wG,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(wG).length} models`),wG)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return E(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),E(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const EG=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function DG(e){if(typeof e==`string`)return EG.exec(e)?.[1]}function OG(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function kG(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function AG(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=OG(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?DG(kG(n)):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&o===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...o!==void 0&&{command:o}}}function jG(e){if(e!==void 0)return[e];let t=w();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function MG(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await NG(Fa(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function NG(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function PG(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await Fa(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=d(a,o);if(n?.has(t)){r.push(t);continue}let s=await Va(t,void 0,void 0);if(s.kind!==`ok`){E(`Failed to check agent file ${t}`);continue}i=HG(i,t,s.value);let c=zG(Ha(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){E(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function FG(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(LG(t)===`tool_result`)return`tool-result`;let n=typeof e.origin==`object`&&e.origin!==null?e.origin.kind:void 0;if(n!==void 0&&n!==`human`)return`turn`;let r=kG(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||IG.test(r)?`claude-code`:`prompt`}const IG=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function LG(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function RG(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=FG(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:AG(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function zG(e){let t=e.trim();if(!t)return{kind:`blank`};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{kind:`object`,value:e}:{kind:`unparsed`,reason:`not a JSON object`}}catch(e){return{kind:`unparsed`,reason:String(e)}}}function BG(e){let t=zG(e);if(t.kind===`unparsed`)return E(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return RG(t.value)}catch(e){return E(`Failed to project JSONL line: ${e}`),null}}function VG(e){let t=[];for(let n of e.split(`
191
- `)){let e=BG(n);e&&t.push(e)}return t}function HG(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function UG(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function WG(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await Va(e,a===void 0?void 0:{offset:a.offset,ino:a.ino},s?.size);if(t.kind!==`ok`)return t;let c=t.value;c.reset&&(o=n),i=HG(c.reset?[]:i,e,c),(s===void 0||c.reset)&&(s={size:c.size,stamp:c.stamp});let l=c.start+c.lines.length;if(o=await r(o,Ha(c,e=>VG(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return P({folded:{cursor:a,value:o},longLines:i})}}var GG=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}},KG=class{entries=new Map;refreshes;constructor(e){this.spec=e,this.refreshes=e.ledger.declare({name:e.name,scope:e.scope,refresh:e.every===null?[`first`,`change`,`supersede`]:[`first`,`period`,`change`,`supersede`]})}declare(e,t){let n=this.spec.keyOf(t),r=this.touched(n)??this.firstRead(this.created(n,t));return e.take(`${this.spec.name}:${n}`,()=>this.hold(r)),{current:()=>oG(r)}}supersede(e){let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,rG(n,`superseded`),n.flight=null,n.changed=!1,this.evict();let r=!1;return()=>{r||(r=!0,n.superseding--,this.entries.get(n.key)===n&&this.refresh(n,`supersede`))}}changed(e){for(let t of this.entries.values())t.holders>0&&e(t.input)&&this.refresh(t,`change`)}isHeld(e){for(let t of this.entries.values())if(t.holders>0&&e(t.input))return!0;return!1}stats(){let e=0;for(let t of this.entries.values())t.holders>0&&e++;let{refreshes:t,failures:n,lastMs:r}=this.refreshes.record();return{entries:this.entries.size,held:e,refreshes:t,failures:n,lastMs:r}}close(){for(let e of[...this.entries.values()])this.drop(e)}touched(e){let t=this.entries.get(e);if(t!==void 0)return this.entries.delete(e),this.entries.set(e,t),t}created(e,t){let n={key:e,input:t,reading:eG(),holders:0,flight:null,changed:!1,superseding:0,revisit:qG(this.spec.every,{period:()=>this.refresh(n,`period`),holdReturned:()=>this.refresh(n,`change`)})};return this.entries.set(e,n),n}firstRead(e){return this.refresh(e,`first`),e}refresh(e,t){if(e.superseding>0)return;if(e.flight!==null){e.changed||=t===`change`;return}let n={};e.flight=n;let r=Date.now();YG(()=>this.spec.read(e.input)).then(i=>{let a=e.flight===n;try{this.refreshes.recorded(`${this.spec.fields(e.input)} stored=${a?`Y`:`N`}`,t,i,Date.now()-r)}finally{a&&this.store(e,i)}}).catch(t=>{this.spec.logger(`error`,`${this.spec.name} refresh threw (${this.spec.fields(e.input)}): ${String(t)}`)})}store(e,t){e.flight=null;try{nG(e,t)}finally{e.revisit.landed(t),e.changed&&(e.changed=!1,this.refresh(e,`change`))}}hold(e){return e.holders++,e.revisit.hold(!0),this.evict(),()=>{e.holders--,e.revisit.hold(e.holders>0)}}evict(){for(let e of[...this.entries.values()]){if(this.entries.size<=this.spec.maxEntries)return;e.holders===0&&e.superseding===0&&this.drop(e)}}drop(e){this.entries.delete(e.key),e.flight=null,e.revisit.dispose(),iG(e,I(`${this.spec.name} entry dropped`))}};function qG(e,t){if(e===null)return new JG(t.holdReturned);let n=new $W(t.period);return{landed:t=>n.landed(QW(e,t)),hold:e=>n.hold(e),dispose:()=>n.dispose()}}var JG=class{state=`released`;answered=!1;constructor(e){this.reread=e}landed(){this.answered=!0}hold(e){if(this.state===`disposed`)return;let t=e&&this.state===`released`&&this.answered;this.state=e?`held`:`released`,t&&this.reread()}dispose(){this.state=`disposed`}};function YG(e){let t=e=>I(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function XG(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const ZG={okMs:60*1e3,failedMs:10*1e3},QG={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},$G={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function eK(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function tK(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function nK(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const rK={entries:0,cost:0,breakdown:nK(),days:new Map};async function iK(e,t){let n=eK(new Date(tK())),r=e.entries,i=e.cost,a={...e.breakdown},o=new Map;for(let[t,r]of e.days)t>=n&&o.set(t,{...r});for(let e of t){let t=e.message?.usage;if(!t)continue;r++;let s=e.costUSD??await TG.calculateCostForEntry(e.raw);i+=s,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0;let c=eK(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...QG};l.cost+=s,l.input+=t.input_tokens||0,l.output+=t.output_tokens||0,l.cacheCreation+=t.cache_creation_input_tokens||0,l.cacheRead+=t.cache_read_input_tokens||0,o.set(c,l)}return{entries:r,cost:i,breakdown:a,days:o}}function aK(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function oK(e){let t=0,n=0,r=nK(),i=new Map;for(let{value:a}of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...QG};aK(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:$G,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}function sK(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function cK(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!sK(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...QG};aK(r,t),n.set(e,r)}return n}async function lK(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}function uK(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function dK(e,t){(0,J.runInAction)(()=>e.set(t))}var fK=class{sessions=J.observable.map(void 0,{deep:!1});flight=new GG;scans;daySets=new Map;speedFlight=new GG;requestFlight=new GG;staleAgeMs;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;sweepTimer=null;constructor(e={}){this.log=e.logger??Me,this.ledger=e.ledger??new jk(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new KG({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${as(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??ZG,maxEntries:8,logger:this.log,ledger:this.ledger});let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps}}scanStats(){return this.scans.stats()}getUsageInfo(e,t){return this.request(e,t?.transcript_path).usage(t)}request(e,t){let n=null,r=()=>{if(n!==null)return n;let r=ja(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async e=>{let t=await r().record;return t.kind===`failed`?t:P(uK(t.kind===`ok`?t.value.sessionInfo:$G,e))},speed:t=>this.observed(e,r,t),today:async e=>{await uG(e),await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return Oa;let r=n.failure.get();return r===null?P(uK(n.record?.sessionInfo??$G,t)):I(r)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=Date.now(),a=await this.ingest(e,t,r,n);return this.renderTally.hits+=r.hits,this.renderTally.misses+=r.misses,r.misses>0&&this.usage.recorded(`sid=${as(e)}`,`request`,a,Date.now()-i),dK(this.hold(e).failure,a.kind===`failed`?a.reason:null),a})}refreshToday(e,t){return this.request(t?.session_id??``,t?.transcript_path).today(e)}declareToday(e,t){let n=jG(t),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?P({roots:i.roots,sums:i.sums.read()}):e}}}todayAt(e,t,n){let r=this.sessions.get(t?.session_id??``),i=r?.failure.get()??null;if(i!==null)return I(i);let a=eK(ak(n)),o={...QG},s=e.sums.get(a);s!==void 0&&aK(o,s);let c=sK(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&aK(o,c),s===void 0&&c===void 0?F:P({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:a})}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return F;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return dK(this.hold(e).speed,t),t;let r=XG(t.kind===`ok`?t.value.sessionInfo.tokenBreakdown:null,n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=P({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return dK(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??Oa:F}async ingest(e,t,n,r){if(!e)return F;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,P(i);if(!t)return i?P(i):F;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return I(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,sessionInfo:s.value.sessionInfo,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),P(c)):l===void 0?P(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,J.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[],failure:J.observable.box(null),speed:J.observable.box(void 0,{deep:!1})};return(0,J.runInAction)(()=>this.sessions.set(e,n)),n}daySet(e){let t=e.join(`\0`),n=this.daySets.get(t);if(n!==void 0)return n;let r=e.map(e=>d(e,`projects`)+f),i={roots:r,sums:new rS(`today over ${e.join(`,`)}`,()=>cK(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await PG(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of UG(r.longLines))this.log(`info`,e);let i=new Map,a=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),o=await WG(e,r,rK,iK);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{folded:s,longLines:c}=o.value;for(let e of UG(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return P({files:i,...oK(i),mainStamp:a})}async scan(e){try{let t=tK(),n=await MG(e),r=[];for(let e of n){let n=await NG(Fa(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a=await NG(Ia(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:Ma(a)})}}let i=[],a={hits:0,misses:0};return await lK(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,a,e.stamp);t.kind===`failed`&&(i.push(t.reason),this.log(`warn`,`usageStore scan: ${t.reason}`))}),this.log(`info`,`usageStore scan dirs=${as(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?I(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`):P({sessions:r.length,read:a.misses})}catch(e){return I(`usage scan: ${e instanceof Error?e.message:String(e)}`)}}sweepStale(){let e=Date.now(),t=eK(new Date(e)),n=0,r=0,i=0;return(0,J.runInAction)(()=>{for(let[a,{lastSeenAt:o,record:s}]of[...this.sessions])if(!(e-o<=this.staleAgeMs)){if(s?.days.has(t)){r++;continue}this.sessions.delete(a),n++,s===void 0&&i++}}),n>0&&this.sweeps++,(n>0||r>0)&&this.log(`info`,`usageStore sweep dropped=${n} noRecord=${i} held=${r}`),n}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.scans.close(),(0,J.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},pK=class{values=J.observable.map(void 0,{deep:!1});order=new Set;constructor(e){this.max=e}get(e){return this.values.get(e)}get size(){return this.order.size}touch(e){this.order.delete(e)&&this.order.add(e)}set(e,t){this.order.delete(e),this.order.add(e),(0,J.runInAction)(()=>{this.values.set(e,t);for(let e of this.order){if(this.order.size<=this.max)break;this.order.delete(e),this.values.delete(e)}})}},mK=class{sessions;constructor(e,t,n,r=Me,i=256){this.empty=e,this.step=t,this.refreshes=n,this.log=r,this.sessions=new pK(i)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=ja(t);if(n?.folded&&i!==``&&n.folded.cursor.stamp===i){let{folded:t,answer:r}=n;return r.kind===`ok`&&r.value===t.value?(this.sessions.touch(e),r):this.store(e,t,{kind:`ok`,value:t.value})}let a=Date.now(),o=await WG(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${as(e)}`,`request`,o,Date.now()-a),o.kind===`failed`)return this.store(e,r,o);if(o.kind===`absent`)return this.store(e,r,{kind:`ok`,value:r?.value??this.empty});let{folded:s,longLines:c}=o.value;for(let e of UG(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??Oa}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function hK(e,t){let n=t.message?.usage;return!n?.input_tokens||t.isSidechain===!0?e:n.input_tokens+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0)}var gK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new mK(void 0,hK,(e.ledger??new jk(t)).declare({name:`context`,scope:`session`,refresh:[`request`]}),t)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return E(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);E(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){return this.contextFrom(await this.fold.read(e,t),n)}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t?P(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,_K(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return P(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,_K(e))}contextFrom(e,t){if(e.kind===`failed`)return I(`context transcript: ${e.reason}`);let n=e.value;return n===void 0?(E(`No main chain entries with usage data found`),F):(E(`Most recent main chain context: ${n} tokens (limit: ${t})`),P({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function _K(e){return e.context_window?.context_window_size??2e5}const vK={messageCount:0,nonPrompts:0,recent:[]},yK=new Set([`turn`,`interrupt`,`claude-code`]);function bK(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!yK.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function xK(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(r.userEntry===`prompt`||r.userEntry===`turn`)t=r.timestamp;else if(e===`assistant`&&t){let e=(r.timestamp.getTime()-t.getTime())/1e3;e>.1&&e<300&&(n=e)}}return n}var SK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new mK(vK,bK,(e.ledger??new jk(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),t)}async getMetricsInfo(e,t){E(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?CK(e,n,await this.fold.read(e,t.transcript_path)):F}metricsOf(e,t){let n=t.cost;if(!n)return F;let r=this.fold.answer(e);return r.kind===`pending`?r:CK(e,n,r)}};function CK(e,t,n){return n.kind===`failed`?I(`metrics (${e}): ${n.reason}`):P({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:xK(n.value.recent),sessionDuration:t.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.total_lines_added,linesRemoved:t.total_lines_removed})}const wK={command:null,todos:[],pending:[],done:[]};function TK(e,t){let n=e.findIndex(e=>e.name===t);return n<0?[...e,{name:t,count:1}]:e.map((e,t)=>t===n?{name:e.name,count:e.count+1}:e)}function EK(e,t){switch(t.userEntry){case`prompt`:return{...e,command:t.activity?.command??null,pending:[],done:[]};case`interrupt`:return{...e,pending:[]};case`turn`:case`tool-result`:case`claude-code`:case void 0:return e}}function DK(e,t){if(t.isSidechain)return e;let n=EK(e,t),r=t.activity;if(r===void 0)return n;let i=n.pending,a=n.done;r.started!==void 0&&(i=[...i,...r.started]);for(let e of r.finished??[]){let t=i.findIndex(t=>t.id===e);t<0||(a=TK(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function OK(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>TK(e,t.name),[]),done:e.done}}var kK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new mK(wK,DK,(e.ledger??new jk(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),t)}async getActivityInfo(e,t){return AK(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:AK(e,t)}};function AK(e,t){return t.kind===`failed`?I(`activity (${e}): ${t.reason}`):P(OK(t.value))}function jK(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function MK(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function NK(e,t,n,r){return MK(D(jK(e,t,n,r)),n)}async function PK(e,t,n,r){return MK(await pt(jK(e,t,n,r)),n)}const FK=3e4;var IK=class{names;constructor(e={}){let t=e.logger??Me;this.names=new KG({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${as(e.pane)} socket=${as(e.socket)}`,read:LK,every:{okMs:FK,failedMs:FK},maxEntries:64,logger:t,ledger:e.ledger??new jk(t)})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function LK(e){let t=await PK(e,`tmux`,[`display-message`,`-p`,`-t`,e.pane,`#S`]);if(t.kind!==`ok`)return I(t.reason);let n=t.stdout.trim();return n?P(n):F}const RK=6e4,zK={okMs:RK,failedMs:RK};function BK(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function VK(e,t){try{let e=t();return Promise.resolve(e===``?F:P(e))}catch(t){return Promise.resolve(I(`host.${e}: ${String(t)}`))}}var HK=class{name;user;constructor(e={}){let t=e.logger??Me,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:zK,maxEntries:1,logger:t,ledger:e.ledger??new jk(t)};this.name=new KG({...n,name:`host.name`,read:()=>VK(`name`,()=>BK(C.hostname()))}),this.user=new KG({...n,name:`host.user`,read:()=>VK(`user`,()=>C.userInfo().username)})}declareName(e){return this.name.declare(e,null)}declareUser(e){return this.user.declare(e,null)}held(){return this.name.stats().held+this.user.stats().held}close(){this.name.close(),this.user.close()}},UK=class{known=new pK(64);refreshes;constructor(e=Me,t=new jk(e)){this.refreshes=t.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=WK(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=Date.now(),i=hP(e);return this.refreshes.recorded(`path=${as(e)} stamp=${as(t)}`,`request`,i,Date.now()-r),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??Oa}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}};function WK(e){try{let t=p.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Ma(t)}catch(e){return`unread:${e.code??`error`}`}}const GK=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function KK(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}var qK=class{known=new pK(256);refreshes;constructor(e=Me,t=new jk(e)){this.refreshes=t.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=ja(t),r=this.known.get(e);if(r!==void 0&&n!==``&&r.stamp===n&&r.outcome.kind!==`failed`)return this.known.touch(e),r.outcome;let i=await this.read(e,t,n);return this.known.set(e,{stamp:n,outcome:i}),i}expiryOf(e){return this.known.get(e)?.outcome??Oa}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}async read(e,t,n){let r=Date.now(),i=await JK(t);return this.refreshes.recorded(`sid=${as(e)} stamp=${as(n)}`,`request`,i,Date.now()-r),i}};async function JK(e){let t=await YK(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function YK(e){for(let t of[65536,1048576]){let n=await Ga(e,t);if(n.kind!==`ok`)return n;let r=XK(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return F}return F}function XK(e,t){let n=e.toString(`utf8`).split(`
192
- `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!GK.test(t))continue;let r=KK(t);if(r!=null)return r}return null}var ZK=class{bySession=J.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:I(n)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,J.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const QK=e=>{try{let t=p.statSync(e,{bigint:!0});return{dev:t.dev,ino:t.ino,birthtimeNs:t.birthtimeNs}}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return`gone`;throw e}},$K=(e,t)=>e.dev===t.dev&&e.ino===t.ino&&e.birthtimeNs===t.birthtimeNs,eq=e=>nV(e),tq=e=>s.join(e.storage.folder,eq(e.sessionId)),nq=e=>JSON.stringify([e.folder,e.generation]),rq=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var iq=class{sessions;folders=new Map;watched=new Map;faults=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;identityOf;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??QK,this.sessions=new KG({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${as(tq(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new jk(e.logger)})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{p.mkdirSync(e,{recursive:!0}),n=this.identityOf(e)}catch(e){t.unusable=`could not be created or read: ${e.message}`}return(t.lost||t.identity!==null&&(n===`gone`||!$K(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${as(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(nq(e))??this.opened(e);t.holders++;let n=!1;return()=>{n||(n=!0,t.holders--,t.holders===0&&this.closed(t))}}declare(e,t,n){return this.sessions.declare(e,{storage:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({storage:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost}}close(){this.sessions.close();for(let e of[...this.watched.values()])this.closed(e)}recorded(e){let t={generation:0,identity:null,lost:!1,unusable:null};return this.folders.set(e,t),t}opened(e){let t=this.folders.get(e.folder);if(t===void 0)throw Error(`plugin storage: no key was asked for ${e.folder}`);let n=e.generation===t.generation?t.unusable:null,r=n===null?this.identityOf(e.folder):`gone`;e.generation===t.generation&&(t.identity=r===`gone`?null:r);let i={key:e,folder:t,identity:r,holders:0,handle:this.watchers.acquire(`plugin-storage:${nq(e)}`,{files:[],dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),sweep:setInterval(()=>void this.sweep(e),864e5)};i.sweep.unref(),this.watched.set(nq(e),i);for(let e of i.handle.refused)this.faulted(i,`refused`,e.reason);return n!==null&&this.faulted(i,`unusable`,n),this.sweep(e),i}closed(e){let t=nq(e.key);this.watched.delete(t),this.faults.delete(t),clearInterval(e.sweep),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>rq(e.storage,n);switch(t.kind){case`unknown`:this.sessions.changed(r);return;case`changed`:{let{names:i}=t;i.has(s.basename(n.folder))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(eq(e.sessionId)));return}case`failed`:this.judged(e,()=>this.faulted(e,`error`,t.reason));return}}judged(e,t){let{key:n,folder:r}=e,i;try{i=this.identityOf(n.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let a=e.identity;if(i!==`gone`&&a!==`gone`&&$K(i,a)){t();return}n.generation===r.generation&&(r.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${as(n.folder)} generation=${n.generation} now=${i===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>rq(e.storage,n)))}faulted(e,t,n){let{key:r,folder:i}=e;this.faults.set(nq(r),`cannot refresh: ${r.folder} ${n}; reload the config or restart the daemon`),this.faultCounts[t]++,r.generation===i.generation&&(i.lost=!0),this.logger(`warn`,`plugin storage fault folder=${as(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>rq(e.storage,r))}async read(e){let t=this.faults.get(nq(e.storage));if(t!==void 0)return I(t);let n=tq(e),r;try{r=await p.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?F:I(`${n}: ${t.message}`)}if(r.trim()===``)return F;let i=Ok(r);return i.kind===`failed`?I(`${n}: ${i.reason}`):i}async sweep(e){let t=Date.now(),n=t-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${as(e.folder)} scanned=${r} removed=${i} took=${Date.now()-t}ms`;try{let t=await p.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=s.join(e.folder,a.name);try{let{mtimeMs:r}=await p.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&eq(t.sessionId)===a.name);if(r>=n||o)continue;await p.promises.unlink(t),i++}catch(e){if(e.code!==`ENOENT`)throw e}}this.logger(`info`,a())}catch(e){this.logger(`warn`,`${a()} outcome=failed reason=${JSON.stringify(e.message)}`)}}};function aq(e){let{logger:t,ledger:n}=e;return{hostService:new HK({logger:t,ledger:n}),gitProvider:new SG({watchers:e.watchers,logger:t,ledger:n}),usageStore:new fK({logger:t,ledger:n}),contextProvider:new gK({logger:t,ledger:n}),metricsProvider:new SK({logger:t,ledger:n}),activityProvider:new kK({logger:t,ledger:n}),tmuxService:new IK({logger:t,ledger:n}),autoCompact:new UK(t,n),cacheExpiry:new qK(t,n),managedStorage:new iq({watchers:e.watchers,logger:t,ledger:n}),faults:new ZK,log:e.logger}}function oq(e){return Math.max(1,e-2)}function sq(e,t,n){return Ie({dir:e.project_dir,env:n===void 0?[]:[[qa,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function cq(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function lq(e){return{...Object.fromEntries(py.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:OH(e.preset)}}}const uq={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function dq(e,t){if(!t)return`-`;if(ka(e))return`pending`;let{prState:n,prError:r,prEarlier:i}=e??{};return ka(n)?`pending`:n===void 0?r===void 0?i===void 0?`-`:`earlier-${String(i)}`:`failed`:n}const fq=10*1e3;function pq(e,t){if(!(t<60))return e*3600/t}function mq(e,t,n,r){let i=r-t;if(i<50||i>fq)return;let a=n-e;if(!(a<=0))return a*1e3/i}function hq(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=mq(t.input,t.atMs,n.input,n.atMs),i=mq(t.output,t.atMs,n.output,n.atMs),a=mq(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function gq(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>fq)continue;let o=mq(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function _q(e,t){let n=nx(e,t),r=[...Ug.flatMap(e=>{let t=n[e];return Wg(t)?[t]:[]})];for(let n of E_(tx(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...vq(e,n.name));return bq(e,r)}function vq(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]):[]}function yq(e,t,n){return bq(e,[...vq(e,t),...n])}function bq(e,t){let n=iB(e),r=new Map(zx(e)),i=t.flatMap(e=>n.ofTemplate(e).flatMap(({reaches:e})=>e)),a=new Set,o=new Set;for(;i.length>0;){let e=i.pop();if(a.has(e))continue;a.add(e);let t=r.get(e),s=tB(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function xq(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=_q(e,n);return t.set(n,i),i}}function Sq(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Cq(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.committedAt`)&&{showCommittedAt:!0},...Object.keys(uq).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const wq=new WeakMap;function Tq(e){let t=wq.get(e);return t===void 0&&(t=Eq(e),wq.set(e,t)),t}function Eq(e){let t=t=>Sq(e,t);return{git:t(`git`),session:t(`session.cost`)||t(`session.tokens`)||t(`burn`),today:t(`today`),context:t(`context`)||t(`autocompact`),metrics:t(`metrics`)||t(`burn`),burn:t(`burn`),activity:t(`activity`),tmux:t(`tmux.session`),hostName:t(`host.name`),hostUser:t(`host.user`),cache:t(`cache`),speed:t(`speed`),autocompact:t(`autocompact`),block:t(`block`)}}function Dq(e){return oq(e.termCols??120)}function Oq(e){return Xa(Ya(e.claudeConfigDir))}function kq(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function Aq(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=Tq(e.neededInputPaths),s=r.session_id,c=i.usageStore.request(s,r.transcript_path),l=async(e,t,r)=>{if(!t)return;let a=performance.now();n.set(e,null);let o=null;try{await r()}catch(t){i.log(`error`,`${e} lane threw: ${T(t)}`),o=`${e}: ${String(t)}`}n.set(e,Math.round(performance.now()-a)),i.faults.refreshed(s,e,o)};await Promise.all([l(`session`,o.session,()=>c.usage(r)),l(`today`,o.today,()=>c.today(i.lanes().today)),l(`context`,o.context,()=>i.contextProvider.getContextInfo(r)),l(`metrics`,o.metrics,()=>i.metricsProvider.getMetricsInfo(s,r)),l(`activity`,o.activity,()=>i.activityProvider.getActivityInfo(s,r)),l(`cache`,o.cache,()=>i.cacheExpiry.refresh(s,r.transcript_path)),l(`speed`,o.speed,()=>c.speed(ak(t).getTime())),l(`autocompact`,o.autocompact,async()=>i.autoCompact.window(Oq(a)))])}function jq(e,t){return[...t.keys()].filter(t=>e.has(t))}function Mq(e,t){let n=lG(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function Nq({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,Cq(n),t.workspace?.project_dir]}function Pq(e,t,n,r,i){let a=Tq(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return lG(F);try{return n()}catch(t){return s.push(`${e}: ${T(t)}`),lG(I(`${e}: ${String(t)}`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...Nq(n,r))),tmux:c(`tmux`,a.tmux&&o!==null,()=>e.tmuxService.declare(t,o)),hostName:c(`host.name`,a.hostName,()=>e.hostService.declareName(t)),hostUser:c(`host.user`,a.hostUser,()=>e.hostService.declareUser(t)),today:c(`today`,a.today,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map(jq(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function Fq(e){let{hookData:t,deps:n}=e,r=Tq(e.neededInputPaths),i=t.session_id,a=n.lanes(),o=(e,t,r)=>{if(!t)return F;let a=n.faults.of(i,e);if(a!==void 0)return a;try{return r()}catch(t){return n.log(`error`,`${e} read threw: ${T(t)}`),I(`${e}: ${String(t)}`)}};return{git:a.git.current(),usage:o(`session`,r.session,()=>n.usageStore.usageOf(i,t)),context:o(`context`,r.context,()=>n.contextProvider.contextOf(t)),metrics:o(`metrics`,r.metrics,()=>n.metricsProvider.metricsOf(i,t)),activity:o(`activity`,r.activity,()=>n.activityProvider.activityOf(i)),tmuxSession:a.tmux.current(),hostName:a.hostName.current(),hostUser:a.hostUser.current(),cache:o(`cache`,r.cache,()=>n.cacheExpiry.expiryOf(i)),speed:o(`speed`,r.speed,()=>n.usageStore.speedOf(i)),autoCompact:o(`autocompact`,r.autocompact,()=>n.autoCompact.stored(Oq(e.hints))),sources:new Map([...a.sources].map(([e,t])=>[e,t.current()]))}}function Iq(e){let t=e.git.current(),n=t.kind===`ok`?t.value.pullRequest:void 0;return[t,e.tmux.current(),e.hostName.current(),e.hostUser.current(),e.today.current(),...[...e.sources.values()].map(e=>e.current()),...n===void 0?[]:[n]].flatMap(e=>e.kind===`pending`&&e.why===`unread`?[e.landed]:[])}function Lq(e,t,n){let{hookData:r,hints:i}=e,{effective:a,configFacts:o}=t,{configPath:s,...c}=o,l=Tq(e.neededInputPaths),u=(e,t)=>{switch(e.kind){case`pending`:return Oa;case`failed`:case`absent`:return;case`ok`:return t(e.value)}},d=e=>e.kind===`ok`?e.value:void 0,f=i.tmux??null,p=n.git.kind===`pending`?Oa:Xq(n.git,()=>Oa),m=n.tmuxSession.kind===`pending`?Oa:d(n.tmuxSession),h=n.hostName.kind===`pending`?Oa:d(n.hostName),g=n.hostUser.kind===`pending`?Oa:d(n.hostUser),_=n.autoCompact.kind===`pending`||l.autocompact&&n.context.kind===`pending`?Oa:Gq(n.autoCompact,d(n.context)?.maxTokens),v=r.rate_limits?.five_hour,y=r.rate_limits?.seven_day,b=l.burn?n.usage.kind===`pending`||n.metrics.kind===`pending`?Oa:Bq(d(n.usage)?.session.cost,d(n.metrics)?.sessionDuration):void 0,ee=u(n.speed,Vq),x=u(n.usage,e=>Jq({cost:e.session.cost,tokens:e.session.tokens})),S=u(n.metrics,e=>Jq({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),te=u(n.activity,Kq),ne=u(n.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),re=u(n.cache,e=>({expiresAt:e})),ie=Yq(process.env.HOME??process.env.USERPROFILE),ae=r.workspace?{...r.workspace,current_dir:Yq(r.workspace.current_dir)??``,project_dir:Yq(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>Yq(e)??e)}:r.workspace,C=r.session_id;return{...r,...ae!==void 0&&{workspace:ae},...ie!==void 0&&{home:ie},...p!==void 0&&{git:p},...f!==null&&{tmux:{pane:f.pane,...m!==void 0&&{session:m}}},host:{...h!==void 0&&{name:h},...g!==void 0&&{user:g},...i.ssh!==void 0&&{ssh:i.ssh}},...lq(a),history:t.history,navigation:{back:t.back},term:{cols:Dq(i)},...c,...s!==null&&{configPath:s},resumeCommand:sq(ae,C,i.claudeConfigDir),...x!==void 0&&{session:x},...b!==void 0&&{burn:b},...ee!==void 0&&{speed:ee},...l.block&&v!==void 0&&{block:{nativeUtilization:v.used_percentage,resetsAt:v.resets_at}},...y!==void 0&&{weekly:{percentage:y.used_percentage,resetsAt:y.resets_at}},...re!==void 0&&{cache:re},...ne!==void 0&&{context:ne},...S!==void 0&&{metrics:S},...te!==void 0&&{activity:te},..._!==void 0&&{autocompact:_},plugins:zq(n.sources.keys(),e=>{let t=n.sources.get(e);return t.kind===`pending`?Oa:t})}}function Rq(e){return{sources:String(e.size),sourcesPending:[...e].flatMap(([e,t])=>{let n=t.current();return n.kind===`pending`?[`${e}:${n.why}`]:[]}).join(`,`)||`-`}}function zq(e,t){let n={};for(let r of e){let[,e,i]=r.split(`.`);(n[e]??={})[i]=t(r)}return n}function Bq(e,t){let n=e!=null&&t!=null?pq(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function Vq(e){let t=hq(e),n=gq(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function Hq(e,t){return Lq(e,t,Fq(e))}function Uq({usageStore:e,faults:t,log:n},r,i,a){if(t.of(i.session_id,`today`)!==void 0)return;let o=r.current();if(o.kind===`pending`)return Oa;if(o.kind!==`ok`)return;let s=(()=>{try{return e.todayAt(o.value,i,a)}catch(e){return n(`error`,`today read threw: ${T(e)}`),F}})();return s.kind===`pending`?Oa:s.kind===`ok`?{cost:s.value.cost,tokens:s.value.tokens}:void 0}async function Wq(e,t,n){await Aq(e,t,n),await sG(()=>{let t=Iq(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function Gq(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return gP(e.value,t)}}function Kq(e){let t=e.todos.findIndex(e=>e.active),n=e.todos.length===0?void 0:{total:e.todos.length,completed:e.todos.filter(e=>e.done).length,...t>=0&&{position:t+1,active:e.todos[t].text}},r=qq(e.running),i=qq(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}};if(!(e.command===null&&n===void 0&&a===void 0))return{...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function qq(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function Jq(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function Yq(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function Xq(e,t){if(e.kind!==`ok`)return;let n=e.value,r=e=>e?.kind===`ok`?e.value:void 0,i=r(n.aheadBehind),a=r(n.sha),o=r(n.operation),s=r(n.committedAt),c=r(n.stashCount),l=r(n.upstream),u=n.upstream===void 0?void 0:r(pW(n.upstream,n.aheadBehind)),d=r(n.repoName),f=r(n.repoUrl),p=n.pullRequest===void 0?void 0:n.pullRequest.kind===`pending`?n.pullRequest:mW(n.pullRequest,n.head),m={};switch(p?.kind){case`pending`:{let e=t(`git.pr`);m={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:m={prNumber:p.value.number,prState:p.value.state,prUrl:p.value.url};break;case`failed`:m={prError:p.reason};break;case`earlier`:m={prEarlier:p.value.state};break;case`absent`:case void 0:break}return{branch:n.branch,status:n.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{committedAt:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{tracking:u},...d!==void 0&&{repoName:d},...f!==void 0&&{repoUrl:f},...m}}function Zq(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const Qq={kind:`hidden`},$q={kind:`shown`};function eJ(e,t){try{return Zq(e,t)?$q:Qq}catch(e){let t=eS(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function tJ(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function nJ(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function rJ({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function iJ({text:e,placement:t,lead:n,trail:r}){return{text:aJ(e),placement:t,...n!==void 0&&{lead:aJ(n)},...r!==void 0&&{trail:aJ(r)}}}function aJ(e){let t=e.blankCopy(e.plain);t.style=Hy(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(Hy(i).clearMetaAndLinks(),n,r);return t}function oJ(e){let t=rJ(e);if(t.length===1)return e.text;let n=tJ(t);return n.style=e.text.style,n}function sJ(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,placement:s,lead:c=[],trail:l=[]}=t;if(e.length===0)return[];let u=tJ(e,a).pad(o),d=new W(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:tJ([d,...c],a)},...l.length>0&&{trail:tJ([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(nJ(u,n,p),[{text:u,...f}])}const cJ=RegExp(`\\x1b\\[[0-9;]*m|${Zd.source}`,`g`);function lJ(e){return Math.max(0,...e.split(`
193
- `).map(e=>Us(e.replace(cJ,``))))}function uJ(e,t){let n=()=>e.map(e=>({owner:oJ(e),placement:e.placement})),r=[];if(e.forEach(({fill:e},t)=>{e!==void 0&&r.push({at:t,how:e})}),r.length===0||!Number.isFinite(t.width))return n();let i=pb(e.map(oJ),t).split(`
194
- `);if(i.length>1)return n();let a=Math.max(0,t.width-lJ(i[0]??``)),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];nJ(c,c.cellLength+a,n)}),n()}function dJ(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=fJ(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:Hy(a.style)};if(e.style.link){i();let r=fJ([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function fJ(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>pJ(e.frag,n?n.add(e.style):e.style)),i=W.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function pJ(e,t){let n=e.copy();return n.style=t,n}function mJ(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function hJ(e,t){let{look:n}=mJ(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function gJ(e,t){let{layout:n}=mJ(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function _J(e,t){if(e.bound!==void 0)throw Error(`a render bound a compile another render holds`);return e.bound=t,{[Symbol.dispose]:()=>{e.bound=void 0}}}function vJ(e,t,n,r){let i=new Map,a=Object.entries(t);for(let[t,o]of[...a.filter(([,e])=>!(`do`in e)),...a.filter(([,e])=>`do`in e)])i.set(t,yJ(e,t,o,n,r,i));return i}function yJ(e,t,n,r,i,a){if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=cx(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=Dy.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=cx(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=cx(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:SJ(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:SJ(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`slash`in n)return{kind:`slash`,line:n.slash};if(`run`in n)return{kind:`run`,name:t,declaration:fx(n),argv:n.run.map(n=>SJ(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,SJ(e,r,t)])};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:SJ(e,n.name,t)};if(`themeDefault`in n)return{kind:`theme-default-save`};let[o,...s]=n.do.map(e=>{let n=a.get(e);if(n===void 0)throw Error(`action "${t}" fires "${e}", which is not declared in this config`);return n});return{kind:`do`,head:o,rest:s}}function bJ(e){return e.kind===`do`?bJ(e.head):e}function xJ(e){switch(bJ(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`slash`:case`run`:case`do`:return!1}}function SJ(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function CJ(e,t){return e.has(t)?Xx(e.read(t)):``}function wJ(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function TJ(e,t,n,r){let i=new W(e,{style:V.combine([r,new V({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function EJ(e,t,n=!1){let r=new V({link:t,bold:n?!0:void 0}),i=new W(e.plain,{style:V.combine([Hy(e.style),r])});for(let t of e.spans)i.stylize(V.combine([Hy(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function DJ(e,t){return Math.max(e.members.indexOf(CJ(t,e.stateVar)),0)}function OJ(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=CJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=CJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=CJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(DJ(e,r)+1)%e.members.length];return{effects:[{verb:Rr,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:zr,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Br,args:[wJ(e.text,bk(r))]}],active:!1};case`open`:return{effects:[{verb:Vr,args:[wJ(e.target,bk(r))]}],active:!1};case`persist-literal`:{let t=CJ(r,e.stateVar);return{effects:[{verb:Kr,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=CJ(r,e.stateVar);return{effects:[{verb:Kr,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(DJ(e,r)+1)%e.members.length];return{effects:[{verb:Kr,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:qr,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Qr,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ei,args:[i]}],active:!1};case`redo`:return{effects:[{verb:ti,args:[i]}],active:!1};case`back`:return{effects:[{verb:ni,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:ri,args:[i]}],active:!1};case`save`:return{effects:[{verb:Jr,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:Yr,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Xr,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Zr,args:[i,wJ(e.name,bk(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:ai,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:oi,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:si,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:li,args:[i,e.line]}],active:!1};case`run`:{let t=bk(r),n=JSON.stringify({run:e.argv.map(e=>wJ(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,wJ(n,t)]))}),o=a.sign({sessionId:i,action:e.name,declaration:e.declaration,evaluated:n});return{effects:[{verb:`run`,args:[i,e.name,n,o]}],active:!1}}case`layout-op`:return{effects:[{verb:$r,args:[i,e.key,MI(e.op)]}],active:!1};case`do`:{let o=OJ(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>OJ(e,t,void 0,r,i,a).effects)],active:o.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:$r,args:[i,e.key,MI(r)]}],active:!1}}}}function kJ(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:Si(`action "${e}"`,n,t.members.length,DJ(t,r)),boundValue:void 0};if(n.length>2)throw Error(`action "${e}" takes a display and an optional bound value, got ${n.length} arguments (per-state displays are a cycle action's form)`);return{display:n[0],boundValue:n[1]?.plain}}function AJ(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=mJ(n,`action "${e}"`).store,{display:a,boundValue:o}=kJ(e,bJ(r),t,i),s=CJ(i,`session.id`),{effects:c,active:l}=OJ(r,a.plain,o,i,s,n.signer);return EJ(a,pi(c),l)}function jJ(e){return{action:{fn:(t,...n)=>AJ(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function MJ(e,t){return TJ(`✕`,pi([{verb:Rr,args:[CJ(e,`session.id`),t,yi]}]),!1)}function NJ(e,t,n){return new V({bgcolor:z.fromRgba(t),color:z.fromRgba(Xh(e,t,n))})}function PJ({tint:e,text:t}){return new V({bgcolor:z.fromRgba(e),color:z.fromRgba(t)})}function FJ(e,t,n){return new V({color:z.fromRgba(Fl(Bh(e,`warning`),t,Yh,n))})}function IJ(e,t,n){return V.combine([NJ(e,t,n),FJ(e,t,n)])}function LJ(e,t,n){return NJ(e.palette,Cg(e.palette,e.disclosure,t,n),n)}function RJ(e){let t=z.fromRgba(Bh(e,`background`)),n=W.fromFragments(mh.map(n=>new W(`▀`,{style:new V({color:z.fromRgba(Bh(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const zJ=(e,t)=>{let n=typeof e==`string`?new W(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},BJ=e=>new V({bold:e});function VJ(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>zJ(a,V.combine([LJ(e,{...n,distribution:t},i),BJ(o)]));let o=NJ(e.palette,a,i);return(e,t,i,a)=>HJ(i,V.combine([o,BJ(a)]),r(t,n))}const HJ=(e,t,n)=>zJ(W.fromFragments([zJ(e,t),zJ(` `,t),RJ(n)]));function UJ(e,t){return t===void 0?(e,t,n)=>zJ(n):(n,r,i)=>HJ(i,void 0,t(r,e))}function WJ(e,t,n,r,i){let a=NJ(e.palette,i,r);return(e,r,i,o)=>zJ(W.fromFragments([zJ(o?`[`:` `,a),RJ(n(r,t)),zJ(o?`]`:` `,a)]))}function GJ(e,t,n){let r=t.map(t=>({label:t.label,indices:e.flatMap((e,n)=>e.group===t.id?[n]:[])})).filter(e=>e.indices.length>0);if(r.reduce((e,t)=>e+t.indices.length,0)!==e.length){let n=new Set(t.map(e=>e.id)),r=e.flatMap((e,t)=>n.has(e.group)?[]:[`#${t} (group "${e.group}")`]);throw Error(`library: ${r.join(`, `)} name a group the domain does not list (${[...n].join(`, `)})`)}return n?r.flatMap(e=>KJ(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function KJ(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function qJ(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function JJ(e){return{current:null,drawnAt:e}}function YJ(e,t,n,r,i,a,o){let s={segName:t,placementId:n,palette:r,disclosure:i,tint:a,text:o,bg:void 0,drops:[]};return e.current=s,s}function XJ(e,t,n){return QJ(e,()=>n(YJ(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function ZJ(e,t){return QJ(e,()=>(e.current=null,t()))}function QJ(e,t){let n=e.current;try{return t()}finally{e.current=n}}function $J(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function eY(e){return new W(e).cellLength}function tY(e){let{width:t,chromeCols:n,padding:r}=mJ(e,`a row fit`);return Math.max(1,t-n-2*r)}function nY(e){let{padding:t,seamCols:n}=mJ(e,`a row fit`);return Math.max(1,tY(e)-(eY(`✕`)+2*t+n))}function rY(e,t,n){if(!Number.isFinite(t))return e.length>0?[e.map((e,t)=>t)]:[];let r=Math.max(1,t-n),i=[],a=[],o=0;for(let t=0;t<e.length;t++){let n=e[t];a.length===0?(a=[t],o=n):o+1+n<=r?(a.push(t),o+=1+n):(i.push(a),a=[t],o=n)}return a.length>0&&i.push(a),i}function iY(e,t,n){let r=eY(`←`)+1+eY(`→`)+1,i=rY(e,t,n);return(i.length>1?rY(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function aY(e,t){let n=[];for(let t of e)n.length>0&&n.push(new W(` `)),n.push(t);let r=W.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function oY(e,t,n,r,i){let a=e.compiled.get(t);if(!a||a.kind!==n)throw Error(`${i} references action "${t}" which must be ${r}, got ${a?`a ${a.kind} action`:`no such action`}`);return a}function sY(e,t,n){let r=e.compiled.get(t),i=r&&bJ(r);if(!i||i.kind!==`set-option`&&i.kind!==`persist-option`&&i.kind!==`layout-op-option`)throw Error(`${n} references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${i?`a ${i.kind} action`:`no such action`}`);return i}function cY(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=mJ(a,`picker`).store,d=CJ(u,`session.id`),f=`stateVar`in t?CJ(u,t.stateVar):void 0,p=(e,n)=>{let r=t.options[e];return o({index:e,count:t.options.length},r,n,r===f)},m=i?r.kind===`led`?nY(a):tY(a):1/0,h=(r.kind===`led`?0:eY(`✕`)+1)+c.reduce((e,t)=>e+eY(t.glyph)+1,0),g=t.library&&{groups:t.library.groups,entries:t.options.map(t.library.entry)},_=g===void 0?t.options.map((e,t)=>p(t,e)):[],v=g===void 0?iY(_.map(e=>e.cellLength),m,h):GJ(g.entries,g.groups,i),y=parseInt(CJ(u,n.stateVar),10),b=e=>Math.max(0,v.findIndex(t=>t.some(t=>t.indices.includes(e)))),ee=b(f===void 0?-1:t.options.indexOf(f)),x=Number.isInteger(y)?y<0?ee:Math.min(y,v.length-1):0,S=v[x]??[],te=e=>pi([{verb:Rr,args:[d,n.key,String(e)]}]),ne=r.kind===`led`?[]:[{verb:Rr,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],re=r.kind===`own`&&r.onPick?ne:[],ie=e=>pi([...OJ(l,e,e,u,d,a.signer).effects,...re]),ae=(e,n)=>EJ(e,ie(t.options[n])),C=r.kind===`led`?[]:[TJ(`✕`,pi(ne),!1,s)];C.push(...c.map(({glyph:e,option:r})=>TJ(e,pi([...OJ(l,r,r,u,d,a.signer).effects,{verb:Rr,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),x>0&&C.push(TJ(`←`,te(x-1),!1));let w=x<v.length-1?[TJ(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[aY([...C,...e.map(e=>ae(_[e],e)),...w],i)]}let oe=new V({bold:!0}),se=v.length>1?` ${x+1}/${v.length}`:``,T=S.length===1?[new W(`${S[0].label}${se}`,{style:oe})]:[],ce=[aY([...C,...T,...w],i)];for(let e of S){S.length>1&&ce.push(aY([new W(e.label,{style:oe})],i));let n=Math.max(...e.indices.map(e=>eY(t.options[e])));for(let r of e.indices){let e=t.options[r],a=g.entries[r].description,o=a===void 0?void 0:Ny(a),s=` `.repeat(n-eY(e)+2),c=o===void 0?e:`${e}${s}${o}`;ce.push(aY([ae(p(r,qJ(c,m)),r)],i))}}return ce}function lY(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{ZO(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=oY(e,r,`set-int`,`an int action ({ set, int: true })`,`picker`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=sY(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=$J(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let[d]=cY(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,VJ(u,kh(void 0),hJ(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),FJ(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function uY(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function dY(e,t,n,r,i){let a=Math.min(Math.floor((t-1)/2),i),o=n,s=0;for(;s<a;){let t=o+e(-(s+1))+1+e(s+1)+1;if(t>r)break;o=t,s+=1}return s}function fY(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=mJ(n,`carousel`).store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=CJ(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return aY([],!0);let d=CJ(o,t.stateVar),f=uY(l,d),p=e=>l[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let r=pi(OJ(s,p(e),p(e),o,c,n.signer).effects);return m.set(e,r),r},g=e=>r({index:f(e),count:u},p(e),p(e),p(e)===d),_=new Map,v=e=>{let t=_.get(e);if(t!==void 0)return t;let n=EJ(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):EJ(UJ(hJ(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),pi(OJ(n.compiled.get(a),p(0),void 0,o,c,n.signer).effects)),b=dY(e=>v(e).cellLength,u,eY(`◀`)+1+y.cellLength+1+eY(`▶`),nY(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return aY([...ee(-1).reverse(),TJ(`◀`,h(-1),!1),y,TJ(`▶`,h(1),!1),...ee(1)],!0)}function pY(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(ZO(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&xJ(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=sY(e,n,`carousel`),l=$J(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return fY(n,c,e,VJ(l,kh(void 0),hJ(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function mY(e,t,n){let r=sY(e,t,n);if(!(`stateVar`in r))throw Error(`${n} references action "${t}", which inserts a segment and holds no current value — a ${n} needs a { set, from } or { persist, from } action`);if(r.paletteOf===void 0)throw Error(`${n} references action "${t}", whose options are not colour-valued — a swatch draws the palette an option puts in force, as the "themes", "placementThemes" and "styles" domains do`);return r}function hY(e,t,n){let r=Math.imul(e^e>>>16,73244475);return r=Math.imul(r^r>>>16,73244475),r^=r>>>16,(n+1+(r>>>0)%Math.max(t-1,1))%t}function gY(e,t,n,r){let i=mY(e,t,n),a=r??CJ(mJ(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,hJ(e,`{{ ${n} }}`))}function _Y(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(ZO(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return RJ(gY(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function vY(e,t,n){return{swatches:{fn:(r,i)=>{let a=mY(e,r,`swatches`),o=oY(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=$J(t,`{{ swatches }}`);if(s.bg===void 0)throw Error(`{{ swatches }} is not available while segments.${s.segName}'s own "bg:" is being evaluated — a swatch row is drawn on that background`);let c=t.drawnAt(),{options:l}=a,u=l.length,[d]=cY(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,WJ(s,hJ(e,`{{ swatches }}`),a.paletteOf,c,s.bg),FJ(s.palette,s.bg,c),u===0?[]:(()=>{let t=uY(l,CJ(mJ(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[hY(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const yY=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function bY(e,t,n,r){let i=ug(e,n,r),a=(t,n)=>({text:t,colour:n,ink:Xh(e,n,r)});return[[wh(t).map((n,i)=>{let a=Vh(e,n);return{text:yY[i%yY.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Bh(e,`warning`)),a(`error`,Bh(e,`error`))]]]}function xY(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new W(` ${e} `,{style:PJ({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new W(e)),r.push(a)}return r}function SY(e,t,n,r,i){let a=bY(e,t,n,r).map(e=>xY(e,i)),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
195
- `),...e]));return o.overflow=`ignore`,o.end=``,o}function CY(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(ZO(`themePreview`,[`applyAction`],i),r!==void 0&&typeof r!=`string`)throw Error(`themePreview: applyAction must name a declared action, got ${JSON.stringify(r)}`);let{palette:a,decor:o}=hJ(e,`{{ themePreview }}`);return SY(r===void 0?a:gY(e,r,`themePreview`),o,{...$J(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),nY(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const wY=e=>e.slice(e.lastIndexOf(`.`)+1),TY=(e,t)=>{let n=new W(wY(e));return n.truncate(t,{marker:`…`}),n.plain};function EY(e,t){let n=e.map(e=>e.map(({name:e})=>eY(wY(e)))),r=e=>n.every(n=>n.reduce((t,n)=>t+Math.min(n,e)+2,0)<=t),i=Math.max(1,...n.flat());for(;i>1&&!r(i);)--i;return i}function DY(e,t,n,r){let i=EY(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new W(` ${TY(s,i)} `,{style:PJ(Ng(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
196
- `),...e]));return o.overflow=`ignore`,o.end=``,o}const OY=`layoutPreview`;function kY(e,t){return{[OY]:{fn:()=>DY(gJ(e,`{{ layoutPreview }}`),hJ(e,`{{ layoutPreview }}`).decor,t.drawnAt(),nY(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function AY(e,t,n,r){let i=$J(r.activeSegment,`{{ menu }}`),a=r.action,o=SA(i.placementId,e,n.key),s=TA(o),c=xA(e),l=mJ(a,`menu`).store,u=CJ(l,o)===c,d=CJ(l,`session.id`),f=u?yi:c,p=TJ(Si(`{{ menu "${e}" }}`,t,2,+!!u),pi([{verb:Rr,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=ug(i.palette,i.disclosure,t).plane,l=sY(a,e,`menu`);return cY(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,yi],[s,`0`]],onPick:n.closeOnPick},n.paged,a,VJ(i,n.distribution,hJ(a,`{{ menu }}`),l.paletteOf,t,c),FJ(i.palette,c,t))})():[]),p}const jY=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function MY(e,t){let n=t[t.length-1],r=jY(n)?n:void 0,i=r===void 0?t:t.slice(0,-1),a=i.findIndex(e=>typeof e!=`string`);if(a!==-1)throw Error(`{{ menu "${e}" }} display #${a+1} is not text (${JSON.stringify(i[a])}) — a menu binds its trigger text, then an optional trailing (dict …) of options`);return{displays:i,options:kA(r??{})}}function NY(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=MY(t,n);return AY(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function PY(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=FY(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new W(t?i:a,{style:l===void 0?void 0:new V({color:l})}))}let l=W.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function FY(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.min(n,Math.max(0,Math.round(e/t*n)))}function IY(e){let t={fn:(()=>{let t=$J(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],arity:{kind:`exact`},returnType:`string`},n={fn:(()=>$J(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=$J(e,`{{ keptOn }}`),i=El(r,t),a=El(r,n),o=_c(Ll(i,R.TRUECOLOR),Ll(a,R.TRUECOLOR)),s=Math.min(Yh,Math.max(o,3));return(Il(i,e.drawnAt(),(e,t)=>_c(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=FO(()=>$J(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...LY(s)];return PY({value:e,max:t,width:n,filled:r,empty:a,colourAt:c===void 0?void 0:e=>String(i.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...i,bgOf:t,tint:n,keptOn:r,gauge:a}}function LY(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function RY(e,t){if(e.kind!==`shell`&&e.kind!==`file`)return[];let n=`key`in e.cache&&[...t.calls(e.cache.key)].some(e=>vk.has(e));return[...t.ofVariable(e).flatMap(({reaches:e})=>e.length===0?[null]:e),...n?[null]:[]]}const zY={input:`view`,state:`view`,template:`view`,time:`view`,literal:`directory`,env:`directory`,dropped:`directory`,source:`view`},BY=new WeakMap;function VY(e){let t=BY.get(e);return t===void 0&&(t=HY(e),BY.set(e,t)),t}function HY(e){let t=new Map(zx(e)),n=iB(e),r=new Map([...t].map(([e,t])=>[e,t.kind===`shell`||t.kind===`file`?`directory`:zY[t.kind]])),i=new Map([...t].map(([e,t])=>[e,RY(t,n)]));for(let e=!0;e;){e=!1;for(let[t,n]of i)r.get(t)!==`view`&&n.some(e=>e===null||r.get(e)!==`directory`)&&(r.set(t,`view`),e=!0)}return r}function UY(e){let t=[],n=[];for(let r of e){if(!r.contains(`
184
+ Single-row example: root: { h: ["seg1", "seg2"] }`,line:G(e.source,[`layout`])}),t.root!==void 0&&(i.root=FR(e,`root`,t.root)),t.actions!==void 0&&(i.actions=rz(e,t.actions,r)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:G(e.source,[`looks`])}),t.styles!==void 0&&(i.styles=Qz(e,t.styles)),t.themeDefaults!==void 0&&(i.themeDefaults=QA(e,t.themeDefaults)),t.presets!==void 0&&(i.presets=eB(e,t.presets)),t.editGlobals!==void 0&&(i.editGlobals=nj(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(i.helpers=tB(e,t.helpers)),t.plugins!==void 0&&(i.plugins=gH(e,t.plugins)),UR(e,i),ez(e,i),Ij(e,i),xA(e,i,X,`the global settings menu`),i}const hH=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function gH(e,t){if(Array.isArray(t)&&t.every(e=>typeof e==`string`&&e!==``))return t;e.issues.push({path:`plugins`,message:`"plugins" must be a list of plugin definition paths, got ${cv(t)}`,line:G(e.source,[`plugins`])})}const _H={},vH=fP(`commands.`),yH=vP(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),bH=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,xH=`{{ \$dir := .current_dir }}{{ if and (ne .home "") (or (eq .home .current_dir) (hasPrefix (printf "%s/" .home) .current_dir)) }}{{ \$dir = printf "~%s" (trimPrefix .home .current_dir) }}{{ else }}{{ if or (eq .project_dir .current_dir) (hasPrefix (printf "%s/" .project_dir) .current_dir) }}{{ $dir = ternary (${bH}) (basename .project_dir) (ne (${bH}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,SH=`{{ ${dM} }}`,CH={min:0,max:100,step:5},wH={warnAt:{label:`warning at %`,domain:CH,default:50},errorAt:{label:`error at %`,domain:{...CH,atLeast:`warnAt`},default:80}};function TH(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:CH,default:80}}}const EH={globals:{palette:`tokyo-night`},variables:{...vH.variables,...aA,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"effort.level":{kind:`input`,path:`effort.level`,default:``},"effort.glyphs":{kind:`literal`,value:`? 󰅃 󰅃 󰄿 󰶼`},version:{kind:`input`,path:`version`,default:``},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.tracking":{kind:`input`,path:`git.tracking`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.committedAt":{kind:`input`,path:`git.committedAt`,type:`number`,default:0},"git.timeSinceCommit":{kind:`template`,type:`number`,template:`{{ if gt .git.committedAt 0 }}{{ sub (int (unixEpoch now)) .git.committedAt }}{{ else }}0{{ end }}`},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`template`,type:`number`,template:`{{ etaMinutes .block.nativeUtilization .block.resetsAt 300 }}`},"weekly.etaMinutes":{kind:`template`,type:`number`,template:`{{ etaMinutes .weekly.percentage .weekly.resetsAt 10080 }}`},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``}},segments:{directory:{group:`location`,description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:xH},model:{group:`model-context`,description:`The active model's display name, followed by the effort gauge (a chevron ladder, climbing on a bubble at max) when an effort level is set.`,template:`✱ {{ formatModelName .model.display_name }}{{ if ne .effort.level "" }} {{ template "effortGauge" . }}{{ end }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{group:`session-tools`,description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{group:`model-context`,description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{group:`location`,description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{group:`location`,description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{group:`git`,description:`The git state: a summary (branch, ahead/behind, S/U/? flags) that the arrow at its right edge expands to every fact — repo, in-progress operation, sha, upstream ±, stash count, time since the last commit.`,template:`{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}`,fg:SH,when:`{{ ne .git.branch "" }}`,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if eq .git.prState "open" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (eq .git.prState "open") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:tP(``).template},commands:{group:`session-tools`,description:`Type /compact, /model or /clear into this session; /clear asks for a second click. Hidden when not inside tmux.`,template:vH.template,when:vH.when},themeSwitcher:{group:`session-tools`,description:"`◀ <theme> ▶`: the theme the bar is wearing; ◀ and ▶ switch this session to the previous or next theme, wrapping at the ends.",template:`{{ carousel "stepTheme" 0 }}`},session:{group:`cost-limits`,description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:TH(0)},today:{group:`cost-limits`,description:`Today's cost and tokens across every session, with a budget warning once a budget is configured.`,template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:TH(50)},block:{group:`cost-limits`,description:`The 5-hour rate-limit block: percent used and time to reset, heating to warning then error.`,template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:wH,when:`{{ gt .block.resetsAt 0 }}`},weekly:{group:`cost-limits`,description:`The weekly rate-limit quota: percent used and time to reset, heating to warning then error.`,template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:wH,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{group:`cost-limits`,description:`Spend per hour, with the projected time to the 5-hour and weekly limits.`,template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 (tint) 0 "error" .settings.errorWithin "warning" .settings.warnWithin (tint) }}`,settings:{errorWithin:{label:`error within (min)`,domain:{min:0,max:300,step:5},default:30},warnWithin:{label:`warning within (min)`,domain:{min:0,max:300,step:5,atLeast:`errorWithin`},default:60}},when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{group:`activity`,description:`Token throughput for the latest exchange: output, input, and total.`,template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{group:`activity`,description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,when:`{{ ne .speed.history "" }}`},cacheTimer:{group:`activity`,description:"Minutes until the prompt cache expires, or `cold` once it has.",template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ readableOn (color (cascade (minutesUntilReset .cache.expiresAt) "0:error" "9:warning" "21:foreground")) (bgOf) ${Yh} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:yH.template,bg:yH.bg,when:yH.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...tP(``).actions,...vH.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...yH.actions},styles:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},themeDefaults:_H,presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{effortGauge:`{{ \$ord := default 0 (get (dict "low" 1 "medium" 2 "high" 3 "xhigh" 4 "max" 5) .effort.level) }}{{ \$glyphs := compact (splitList " " .effort.glyphs) }}{{ $bubble := readableOn (mix (bgOf) (color "accent") 40) (bgOf) 1.08 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${Yh} }}{{ \$climb := frames 1 (index \$glyphs 1) 1 (index \$glyphs 3) 1 (index \$glyphs 4) }}{{ if eq \$ord 5 }}{{ fg \$bubble "" }}{{ bg \$bubble (fg \$climbing \$climb) }}{{ fg \$bubble "" }}{{ else }}{{ fg (ramp $ord "step" 0 (${dM}) 2 (readableOn (color "accent") (bgOf) ${Yh})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Yh}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ $age := .git.timeSinceCommit }}{{ if and .settings.age (gt $age 0) }} ◷ {{ template "formatTimeSince" $age }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:yP(`.`),formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatToolTally:`{{ $names := splitList "," . }}{{ range $i, $pair := $names }}{{ if lt $i 2 }}{{ if $i }} {{ end }}{{ $kv := splitList ":" $pair }}{{ index $kv 0 }}{{ if ne (index $kv 1) "1" }}×{{ index $kv 1 }}{{ end }}{{ end }}{{ end }}{{ if gt (len $names) 2 }} +{{ sub (len $names) 2 }}{{ end }}`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},DH=new Set([EH.globals.palette,...Object.keys(EH.themeDefaults),...Object.values(EH.segments).map(e=>e.palette)].filter(e=>e!==void 0)),OH=tL(uH(`<default>`,JSON.stringify(EH),DH),EH),kH=$b(OH.presets);function AH(e){return kH.includes(e)}const jH=Object.freeze({});function MH(e,t){return e.kind===`decided`?t[e.name]??jH:jH}function NH(e,t){return{...e,...Object.fromEntries(hy.map(n=>[n,e[n]??t[n]]))}}const PH=e=>Bv(t=>e[Pv[t].setting]);function FH(e,t,n,r){let i=_y(e);return Lg(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function IH(e,t){return ex(t(`preset`),e.globals.preset,e.presets)}function LH(e,t,n){let r=IH(e,t),i=rx(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Rb(a.palette,t(`theme`),i.palette),s=NH(i,MH(o,e.themeDefaults));return{...Object.fromEntries(py.map(e=>[e,FH(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:Yg(a.style,t(`style`),s.style,e.styles),effect:a_(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function RH(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?m_:h_;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const zH=Object.entries(Sy),BH=new Set(wy.map(e=>e.sessionKey)),VH=()=>!1;function HH(e,t){return LH(e,e=>BH.has(e)?t(e):null,VH)}const UH=[`preset`,`theme`];function WH(e,t,n){let r=new Set(UH.slice(0,n).map(e=>Sy[e].sessionKey));return LH(e,e=>r.has(e)?t(e):null,VH)}function GH(e,t){let n=Array.from({length:UH.length+1},(n,r)=>WH(e,t,r));return e=>{let t=UH.indexOf(e);return n[t===-1?UH.length:t]}}function KH(e,t,n,r){return e.flatMap(([e,i])=>{let a=RH(t,e);return a===null||a===RH(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function qH(e,t,n){return RH(HH(e,t),n)}function JH(e,t){let n=HH(e,t);return KH(zH,n,GH(e,t),t=>YH(e,n.preset,t.configKey))}function YH(e,t,n){return n in(tx(e.presets,t).globals??{})?gj(t,n):n}function XH(e,t,n){let r=ex(t(Sy.preset.sessionKey),e.globals.preset,e.presets),i=_j(n);return{key:i?.scope===`globals`?YH(e,r,i.field):n,globals:rx(e,r)}}function ZH(e,t){let{preset:n}=HH(e,t);return eU(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:K_(a,s);return c===void 0||G_(c)===G_(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function QH(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return $b(e.presets).flatMap(n=>{let i=eU(e,n);return[...new Set(i.filter(e=>r.has(e.key)).map(e=>e.id))].flatMap(e=>{let n=i.filter(t=>t.id===e);return U_(Object.fromEntries(n.map(e=>[e.setting,e.decl])),Object.fromEntries(n.map(e=>{let n=r.get(e.key)??t(e.key),i=n===null?void 0:K_(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const $H=new WeakMap;function eU(e,t){let n=$H.get(e)??new Map;$H.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...E_(nx(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=V_(e.segments[t.name])[n];return{id:r,setting:n,key:i,decl:a,saved:t.settings?.[n]??a.default}})),a=[...new Map(i.map(e=>[e.key,e])).values()];return n.set(t,a),a}function tU(e,t){let n=HH(e,t);return{from:n.preset,globals:tx(e.presets,n.preset).globals??{},picks:KH(zH.filter(([e])=>e!==`preset`),n,GH(e,t),e=>e.configKey),placements:ZH(e,t)}}function nU(e,t){return LH({...e,globals:{palette:t},presets:{}},()=>null,VH)}function rU(e,t){let n=HH(e,t),r=RH(n,`theme`);if(r===null)return{kind:`rule`};let i=nU(e,r),a=rx(e,n.preset),o=Object.fromEntries(hy.map(e=>[e,RH(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:hy.some(e=>o[e]!==RH(i,e))}}function iU(e){return{sessionKeys:wy.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...JA(e)?kH.map(t=>gj(t,e)):[],...hj(e)?Rg().map(t=>mj(t,e)):[]]}}function aU(e){return new Set(wy.map(e=>e.configKey).filter(t=>iU(t).fileKeys.some(t=>cU(e,sU(t)))))}function oU(e,t,n){let r=JH(e,n),i=new Set(r.map(e=>e.configKey)),a=ky(e=>i.has(Sy[e].configKey)||t.has(Sy[e].configKey)),o=rU(e,n);return{unsaved:r.length+ZH(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function sU(e){let t=_j(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return vj(t)}function cU(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&cU(e[n],r)}const lU=Rg(),uU=new Set(lU),dU=new Set(o_),fU=e=>e?uU.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${lU.join(`, `)})`}:{ok:!1,reason:`theme name is required`},pU=e=>e?dU.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${o_.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},mU=new Set([`1`,`true`]),hU=new Set([`0`,`false`]),gU={endcaps:pU,theme:fU,"toolbar-expanded":e=>mU.has(e)?{ok:!0,value:`1`}:hU.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},_U=KI(gU,`state`,wU);function vU(e,t){return _U.register(e,t)}function yU(e){return _U.gateFor(e)}function bU(e,t){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:lx(e.from,t).members}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function xU(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(gU,e.key))}function SU(e,t,n){let r=Ay.get(n);if(r!==void 0)return qH(e,t,r);for(let[,t]of L_(e))if(t.key===n)return t.default??null;return null}function CU(e){let t=hI(e);return xU(Object.values(e.actions).flatMap(e=>bU(e,t)))}function wU(e){return WI(CU(e))}const TU=`update.dismissed`,EU=`updateNotice`,DU=Sy.updateNotice.sessionKey;function OU(e){return e.kind===`source`?e.newer.digest:uo(e.newer)}const kU=e=>`${e.version} [${Xe(e.digest)}]`;function AU(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:kU(e.newer),running:kU(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:uo(e.newer),running:uo(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${po}@${uo(e.newer)}`,`install`]}}}}const jU={kind:`idle`},MU={kind:`running`};function NU(e,t,n){if(e===null)return[];let r=OU(e);if(!n.enabled||n.dismissed===r)return[];let i=AU(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
185
+ `),c=pi([{verb:Wr,args:[s]}]),l=t.kind===`running`?yb(`[${i.busy}]`,c):yb(`[${i.act}]`,pi([{verb:ii,args:[n.sessionId]}]));return[{severity:_b,message:s,lines:[[yb(a,c),l,yb(`[dismiss]`,pi([{verb:Rr,args:[n.sessionId,TU,r]}])),yb(`[disable]`,pi([{verb:Kr,args:[n.sessionId,EU,`false`]},{verb:Rr,args:[n.sessionId,DU,`false`]}]))],...o.map(e=>[yb(e,c)])]}]}function PU(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function FU(e){switch(e.kind){case`current`:return[`info`,`build: current ${kU(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${kU(e.source)}, running ${kU(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function IU(e){switch(e.kind){case`current`:return[`info`,`release: current ${uo(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${uo(e.latest)}, running ${uo(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${uo(e.installed)}, latest ${uo(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function LU(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const RU=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function zU(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=RU(e.stderr)??e.error??RU(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function BU(){let e=[JI(EU,[`false`]),vU(DU,[`false`]),vU(TU,[])];return()=>e.forEach(e=>e())}function VU(e){let{entryUrl:t,intervalMs:n,releaseIntervalMs:r,registryUrl:i,fetchImpl:a,onApplied:o,log:s}=e,c={kind:`unchecked`,reason:`not sampled yet`},l=null,u=jU,d=null,f=LU(s),p=LU(s),m=()=>PU(c,l);function h(){let e=m(),t=e===null?null:OU(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:vU(TU,[t])})}function g(){c=nt(t,$e),f(FU(c)),h()}async function _(){l=ho(Ze,await mo(po,a,i)),p(IU(l)),h()}return{arm(){BU(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>NU(m(),u,e),act(){let e=m();if(e===null)throw new q(`apply-update: nothing newer is known to apply`);let t=AU(e);if(u.kind===`running`)throw new q(`apply-update: already ${t.busy}`);u=MU,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),pt({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=jU,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=zU(n);u={kind:`failed`,identity:OU(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}function HU(e,t){try{return P(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?F:I(e.message)}}function UU(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function WU(e){let{targets:t,intervalMs:n,stat:r,exit:i,log:a}=e,o=t.map(e=>({path:e,stamp:HU(e,r)})),s=o.filter(({stamp:e})=>e.kind!==`failed`),c=null,l=()=>{for(let{path:e,stamp:t}of s){let n=HU(e,r);if(n.kind===`failed`){a(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!UU(t,n)){a(`info`,`binary ${n.kind===`absent`?`gone`:`changed`} (${e}); shutting down`),c&&clearInterval(c),i();return}}};return{arm(){for(let{path:e,stamp:t}of o)t.kind===`failed`&&a(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);c=setInterval(l,n),c.unref()},checkNow:l}}const GU=`${Iy}${Fy}`;function KU(e){return`${GU}⚠ cc-candybar: ${qU(e)}${Ly}\n`}function qU(e){switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:return`daemon rejected request: ${Py(e.message,60)}`;case`render_failed`:return`render failed: ${Py(e.message,60)}`;case`switched_off`:return`switched off: ${Py(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${Py(e.message,60)}`}}function JU(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
186
+ `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:KU(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}const YU=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function XU(e){if(e===void 0||e.isDefault)return;let t=e.fixedValue;if(t!==void 0)return t.hex;let n=e.type===R.STANDARD&&e.number!==void 0?YU[e.number]:void 0;if(n===void 0)throw Error(`frames: no band colour for ${e.name}`);return n}const ZU={bold:`bold`,dim:`dimColor`,italic:`italic`,underline:`underline`,strike:`strikethrough`,reverse:`inverse`,blink:null,blink2:null,conceal:null,underline2:null,frame:null,encircle:null,overline:null},QU=Object.keys(ZU);function $U(e,t){let n=XU(t.color),r=XU(t.bgcolor),i={};for(let e of QU){if(t[e]!==!0)continue;let n=ZU[e];if(n===null)throw Error(`frames: the band cannot draw ${e} text`);i[n]=!0}return{text:e,...n!==void 0&&{color:n},...r!==void 0&&{backgroundColor:r},...i,...t.link!==void 0&&{href:t.link}}}const eW=new V;function tW(e){return{ok:!0,band:new zp().decode(e).map(e=>{let t=e.plain,n=[],r=0;for(let i of e.spans){if(!(i.style instanceof V))throw Error(`frames: the decoder gave a span a ${typeof i.style} style`);i.start>r&&n.push($U(t.slice(r,i.start),eW)),n.push($U(t.slice(i.start,i.end),i.style)),r=i.end}return r<t.length&&n.push($U(t.slice(r),eW)),n})}}function nW(e){let t=JU(mn(e)).output;try{return tW(t)}catch(e){return tW(`${Iy}${Fy}⚠ cc-candybar ${Ny(e instanceof Error?e.message:String(e))}${Ly}\n`)}}function rW(e){return`ccb`+te(`sha256`).update(e).digest(`hex`).slice(0,12)}const iW=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function aW(e){if(e===void 0||e.isDefault)return`terminal`;switch(e.type){case R.STANDARD:{let t=e.number===void 0?void 0:iW[e.number];if(t!==void 0)return t;break}case R.EIGHT_BIT:if(e.number!==void 0)return`colour${e.number}`;break;case R.TRUECOLOR:{let t=e.fixedValue;if(t!==void 0)return t.hex;break}case R.DEFAULT:case R.WINDOWS:break}throw Error(`frames: no tmux colour for ${e.name}`)}const oW={bold:`bold`,dim:`dim`,italic:`italics`,underline:`underscore`,strike:`strikethrough`,reverse:`reverse`,blink:`blink`,conceal:`hidden`,underline2:`double-underscore`,overline:`overline`,blink2:null,frame:null,encircle:null},sW=Object.keys(oW);function cW(e){return e.replaceAll(`#`,`##`)}function lW(e){let t=sW.filter(t=>e[t]===!0).map(e=>{let t=oW[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${aW(e.color)}`,`bg=${aW(e.bgcolor)}`,...t].join(`,`)}]`}const uW=new V;function dW(e){let t={},n=(e,n)=>{let r=lW(n)+cW(e);if(n.link===void 0)return r;let i=rW(n.link);return t[i]=n.link,`#[range=user|${i}]${r}#[norange]`};return{rows:new zp().decode(e).map(e=>{let t=e.plain,r=[],i=0;for(let a of e.spans){if(!(a.style instanceof V))throw Error(`frames: the decoder gave a span a ${typeof a.style} style`);a.start>i&&r.push(n(t.slice(i,a.start),uW)),r.push(n(t.slice(a.start,a.end),a.style)),i=a.end}return i<t.length&&r.push(n(t.slice(i),uW)),r.join(``)}),links:t}}function fW(e){let t=JU(mn(e)).output;try{return dW(t)}catch(e){return dW(`${Iy}${Fy}⚠ cc-candybar ${Ny(e instanceof Error?e.message:String(e))}${Ly}\n`)}}const pW={band:e=>JSON.stringify(nW(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:fW(e)})};function mW(e){let t=typeof e==`string`?e===``?`is empty`:e===`.`||e===`..`?`is ${JSON.stringify(e)}, which names a folder, not a session`:/[/\\\0]/.test(e)?`contains a path separator or NUL: ${JSON.stringify(e)}`:Buffer.byteLength(e,`utf8`)>250?`is longer than 250 bytes`:null:`is not a string: ${JSON.stringify(e)??String(e)}`;return t===null?{ok:!0,id:e}:{ok:!1,problem:t}}function hW(e,t){return e.kind===`absent`?P(`none`):e.kind===`failed`?e:t.kind===`failed`?t:P(t.kind===`ok`?`tracked`:`gone`)}function gW(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?I(`HEAD: ${t.reason}`):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const _W={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},vW={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function yW(e,t,n){return Object.hasOwn(t,n)?P(t[n]):I(`${e}: unknown state ${JSON.stringify(n)}`)}const bW={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,tag:`tag`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function xW(e){return Object.keys(bW).flatMap(t=>{let n=e[t];return n?.kind===`failed`?[`git.${bW[t]}: ${n.reason}`]:[]})}function SW(e,t,n){return t.ok?P(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?F:I(CW(e,t))}function CW(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??wW(t.stderr)].filter(Boolean).join(`, `)}`}function wW(e){return e.trim().split(`
187
+ `,1)[0]??``}function TW(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?F:P(n)}function EW(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?P(t):F}const DW={github:`gh`,gitlab:`glab`};function OW(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const kW=/^[A-Za-z]:[\\/]/;function AW(e){let t=e.trim();if(kW.test(t))return null;let n=t.match(/^(?:[^@/]+@)?(\[[^\]]+\]):(.*)$/)??t.match(/^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.*)$/),r=n?`ssh://${n[1]}/${n[2].replace(/^\/+/,``)}`:t,i;try{i=new URL(r)}catch{return null}return{scheme:i.protocol.replace(/:$/,``),host:i.hostname.toLowerCase(),port:i.port,path:i.pathname.replace(/^\/+/,``).replace(/\/+$/,``)}}function jW(e){return AW(e)?.host||null}function MW(e){let t=jW(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const NW=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function PW(e){let t=SW(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?FW(t.value):[]}}function FW(e){let t=new Map;for(let n of e.split(`
188
+ `)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function IW(e){return e.urls.find(e=>VW(e)!==null)??e.urls[0]??null}function LW(e){return e.find(e=>e.name===`origin`)??e[0]??null}function RW(e){let t=LW(e);return t?IW(t):null}function zW(e){let t=LW(e);return t?t.urls.find(e=>MW(e)!==null)??IW(t):null}function BW(e){let t=(AW(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function VW(e){let t=AW(e);if(!t)return null;let n=t.scheme===`https`?{scheme:`https`,port:t.port}:t.scheme===`http`?{scheme:`http`,port:t.port}:t.scheme===`ssh`||t.scheme===`git`?{scheme:`https`,port:``}:null;if(!n||!t.host)return null;let r=t.path.replace(/\.git$/,``);if(!r)return null;let i=n.port?`${t.host}:${n.port}`:t.host;return`${n.scheme}://${i}/${r}`}function HW(e){let t=RW(e);return t===null?null:VW(t)}function UW(e,t,n,r){return t.ok?r(t.stdout):OW(t)||t.reason===`non-zero`&&n.test(t.stderr)?F:I(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??wW(t.stderr)].filter(Boolean).join(`, `)}`)}function WW(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function GW(e){let t=`detached`,n=F,r=F,i=F,a=0,o=0,s=0,c=0;for(let l of e.split(`
189
+ `)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?F:P(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=P(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=P({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function KW(e){let t;try{t=JSON.parse(e)}catch(e){return I(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!WW(t))return I(`gh pr view: JSON is not an object`);let{number:n,state:r,url:i,headRefOid:a}=t;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return I(`gh pr view: missing number/state/url/headRefOid`);let o=yW(`gh pr view`,_W,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function qW(e){let t;try{t=JSON.parse(e)}catch(e){return I(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!WW(t))return I(`glab mr view: JSON is not an object`);let n=t.iid,r=t.state,i=t.web_url,a=t.sha;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return I(`glab mr view: missing iid/state/web_url/sha`);let o=yW(`glab mr view`,vW,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function JW(e){try{let t=p.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var YW=class{isGitRepo(e){return zV(e)}async execGitAsync(e,t){return pt({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}resolveEffectiveGitDir(e,t){return this.isWorktree(e)?P(e):t&&this.isGitRepo(t)?P(t):this.isGitRepo(e)?P(e):this.findGitRoot(e)}findGitRoot(e){let t=BV(e);return t===void 0?F:P(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return I(`git: ${e instanceof Error?e.message:String(e)}`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=this.findGitRoot(e);if(t.kind!==`ok`)return t;r=t.value}let a=await this.getCoreAsync(r);if(a.kind!==`ok`)return a;let o={branch:a.value.branch,status:a.value.status,aheadBehind:a.value.aheadBehind,head:a.value.oid};t.showWorkingTree&&(o.workingTree=a.value.workingTree),t.showSha&&(o.sha=TW(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showCommittedAt&&(o.committedAt=await this.committedAt(r,a.value.oid)),t.showStashCount&&(o.stashCount=this.getStashCount(r));let s=t.showRepoName||t.showRepoUrl?await this.getRemotesAsync(r):void 0;return s!==void 0&&t.showRepoName&&(o.repoName=TW(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=TW(s,HW)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),P(o)}resolveGitDir(e){let t=s.join(e,`.git`);try{if(p.existsSync(t)&&p.statSync(t).isFile()){let n=p.readFileSync(t,`utf-8`).match(/^gitdir:\s*(.+)$/m);if(n?.[1])return s.resolve(e,n[1].trim())}}catch{}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return p.existsSync(s.join(t,`MERGE_HEAD`))?P(`MERGE`):p.existsSync(s.join(t,`CHERRY_PICK_HEAD`))?P(`CHERRY-PICK`):p.existsSync(s.join(t,`REVERT_HEAD`))?P(`REVERT`):p.existsSync(s.join(t,`BISECT_LOG`))?P(`BISECT`):p.existsSync(s.join(t,`rebase-merge`))||p.existsSync(s.join(t,`rebase-apply`))?P(`REBASE`):F}catch(e){return I(`git operation probe: ${e instanceof Error?e.message:String(e)}`)}}async getNearestTagAsync(e){return EW(SW(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestamp(e,t.value):t}commitTimes=new Map;async commitTimestamp(e,t){let n=this.commitTimes.get(t);if(n!==void 0)return this.commitTimes.delete(t),this.commitTimes.set(t,n),n;let r=this.readCommitTimestamp(e,t);for(this.commitTimes.set(t,r),r.then(e=>{e.kind!==`ok`&&this.commitTimes.get(t)===r&&this.commitTimes.delete(t)},()=>{this.commitTimes.get(t)===r&&this.commitTimes.delete(t)});this.commitTimes.size>256;){let e=this.commitTimes.keys().next().value;if(e===void 0)break;this.commitTimes.delete(e)}return r}async readCommitTimestamp(e,t){let n=EW(SW(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10);return Number.isNaN(r)?I(`git log -1: unparseable timestamp "${n.value}"`):P(r)}resolveCommonGitDir(e){let t=this.resolveGitDir(e);try{let e=p.readFileSync(s.join(t,`commondir`),`utf-8`).trim();if(e)return s.resolve(t,e)}catch{}return t}getStashCount(e){let t=s.join(this.resolveCommonGitDir(e),`logs`,`refs`,`stash`),n;try{n=p.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?P(0):I(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`)}let r=n.trim();return P(r?r.split(`
190
+ `).length:0)}async getRemotesAsync(e){let t=JW(s.join(this.resolveCommonGitDir(e),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){return PW(await this.execGitAsync(NW,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=RW(e);return(n===null?null:BW(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=zW(t.value);return n===null?F:P(n)}async execForgeAsync(e,t,n){return pt({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=MW(t);return n===`github`?UW(`gh pr view`,await this.execForgeAsync(DW.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,KW):n===`gitlab`?UW(`glab mr view`,await this.execForgeAsync(DW.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,qW):F}isWorktree(e){try{let t=s.join(e,`.git`);return!!(p.existsSync(t)&&p.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){E(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=SW(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?P(GW(t.value)):t}};const XW=(e,t)=>E(t);function ZW(e,t){return t.kind===`failed`?t:e.kind===`changed`?t.kind===`unknown`?t:{kind:`changed`,names:new Set([...e.names,...t.names])}:e}const QW=e=>e===null?{kind:`unknown`}:{kind:`changed`,names:new Set([e])};var $W=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??XW}acquire(e,t,n){if(this.closed)return{release:()=>{},refused:[...t.files,...t.dirs.map(e=>e.path)].map(e=>({path:e,reason:`the watcher registry is closed`}))};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,this.makeHandle(r);let i={key:e,watchers:[],refcount:1,debounce:null,onInvalidate:n,targets:t,refused:[]};return this.openWatchers(i),this.slots.set(e,i),this.counters&&(i.refused.length===0?this.counters.watchersOpened++:this.counters.watchRefusals++),this.makeHandle(i)}makeHandle(e){let t=!1;return{refused:e.refused,release:()=>{t||(t=!0,this.slots.get(e.key)===e&&(e.refcount=Math.max(0,e.refcount-1),e.refcount===0&&(this.closeSlot(e),this.slots.delete(e.key))))}}}openWatchers(e){let t=t=>{if(e.debounce!==null){e.debounce.window=ZW(e.debounce.window,t);return}let n={window:t,timer:setTimeout(()=>{e.debounce=null;try{e.onInvalidate(n.window)}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50)};n.timer.unref(),e.debounce=n},n=e=>n=>{this.logger(`warn`,`watcher error ${e}: ${n.message}`),this.counters&&this.counters.watchErrors++,t({kind:`failed`,reason:`${e}: ${n.message}`})},r=[],i=(e,t)=>{let n=t.message;this.logger(`warn`,`watch failed ${e}: ${n}`),r.push({path:e,reason:n})};for(let r of e.targets.files)try{let i=p.watch(r,{persistent:!1},(e,n)=>t(QW(n)));i.on(`error`,n(r)),e.watchers.push(i)}catch(e){i(r,e)}for(let r of e.targets.dirs)try{let i=r.filenames?new Set(r.filenames):null,a=p.watch(r.path,{persistent:!1},(e,n)=>{i&&(!n||!i.has(n))||t(QW(n))});a.on(`error`,n(r.path)),e.watchers.push(a)}catch(e){i(r.path,e)}e.refused=r}closeSlot(e){e.debounce!==null&&(clearTimeout(e.debounce.timer),e.debounce=null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}};function eG(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var tG=class{timer=null;state=`released`;last=null;constructor(e,t=Date.now){this.tick=e,this.now=t}landed(e,t=this.now()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.now());this.timer=setTimeout(()=>{this.timer=null,this.tick()},e),this.timer.unref?.()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function nG(){return J.observable.box(rG(`unread`),{deep:!1})}function rG(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function iG(e,t){let n=e.reading.get();n.kind===`read`&&(0,J.compareStructural)(n.outcome,t)||((0,J.runInAction)(()=>e.reading.set({kind:`read`,outcome:t})),n.kind===`pending`&&n.land())}function aG(e,t){let n=e.reading.get();n.kind===`read`?(0,J.runInAction)(()=>e.reading.set(rG(t))):n.why!==t&&t===`unread`&&(0,J.runInAction)(()=>e.reading.set({...n,why:t}))}function oG(e,t){e.reading.get().kind===`pending`&&iG(e,t)}function sG(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function cG(e){let t=e.reading.get();return t.kind===`read`?t.outcome:t}async function lG(e){for(;;){let t=e();if(!sG(t))return t;await t.landed}}function uG(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),Math.max(0,t));return new Promise((t,i)=>{r.signal.addEventListener(`abort`,()=>t(`deadline`)),e(r.signal).then(()=>t(`answered`),e=>r.signal.aborted?n(e):i(e))}).finally(()=>{clearTimeout(i),r.abort()})}function dG(e){return{current:()=>e}}function fG(e){return lG(()=>e.current())}const pG=`pass`,mG={okMs:5*6e4,failedMs:45e3};function hG(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function gG(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function _G(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function vG(e){let t=[{path:e,filenames:[`HEAD`,`index`]}],n=s.join(e,`refs/heads`);try{p.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[],dirs:t}}function yG(e){return e.find(e=>e.kind===`ok`)?.value.branch}function bG(e){e.missed=!0,aG(e,`unread`)}function xG(e,t){return e.missed&&e.reading.get().kind===`pending`&&iG(e,t.size>0?I([...t].join(`; `)):F),`unkeyed`}function SG(e,t){let n=cG(e);return t===null||n.kind!==`ok`?n:P({...n.value,pullRequest:cG(t)})}function CG(e){return t=>I(`${e} threw: ${String(t)}`)}var wG=class{repos=new Map;resolutions=new Map;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;watchers;ownsWatchers;logger;constructor(e={}){this.inner=e.inner??new YW,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Me;let t=e.ledger??new Mk(this.logger);this.gitRefreshes=t.declare({name:`git`,scope:`repo`,refresh:[`first`,`period`,`change`]}),this.prRefreshes=t.declare({name:`pr`,scope:`repo`,refresh:[`first`,`period`]}),e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new $W({logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=I(`resolver threw: ${String(e)}`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`not-a-repo`)return dG(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>SG(a,o)}}asked(e,t,n,r){let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`not-a-repo`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n=this.inner.resolveGitDir(e),r={root:e,refresh:new Ak,watcher:this.watchers.acquire(`git:${e}`,vG(n),()=>this.changed(e)),period:new tG(()=>{r.refresh.share(pG,()=>this.refreshPass(r))}),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,r),r}changedPass(e,t){e.asked.add(t),e.refresh.run(pG,()=>this.refreshPass(e))}async refreshPass(e){try{await this.pass(e)}catch(t){this.logger(`error`,`git refresh threw (${e.root}): ${String(t)}`)}finally{e.period.landed(this.periodMs)}}hold(e,t,n){return e.holders++,n!==null&&(n.holders++,t.missed&&bG(n),n.missed&&e.asked.add(`owed`)),t.readers++,t.missed&&e.asked.add(`resume`),this.held(e),this.evict(),()=>{e.holders--,t.readers--,n!==null&&n.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(pG,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr?.period.hold(e.pr.holders>0&&!e.pr.missed)}valueOf(e,t,n){let r=e.values.get(t);if(r!==void 0)return r;let i={options:n,reading:nG(),readers:0,missed:!1};return e.values.set(t,i),e.asked.add(`first`),i}ask(e,t,n,r){let i=e.asked.size,a=_G(n),o=this.valueOf(e,a,n);r&&e.pr===null&&(e.pr=this.prSource(e),e.asked.add(`pr`));let s=r?e.pr:null;return t.take(gG(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}async pass(e){if(this.repos.get(e.root)!==e)return;let t=Date.now(),n=[...e.asked];e.asked.clear();let r=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?r.push(t):t.missed=!0;let i=e.pr,[a,o]=await Promise.all([Promise.all(r.map(t=>this.inner.getGitInfo(e.root,t.options).catch(CG(`git fetch`)))),i!==null&&i.holders>0?this.remoteOf(e):null]);if(this.repos.get(e.root)!==e)return;let s=new Set;r.forEach((e,t)=>{let n=a[t];if(e.missed=!1,iG(e,n),n.kind===`failed`&&s.add(n.reason),n.kind===`ok`)for(let e of xW(n.value))s.add(e)});let c=yG(a),l=i===null||r.length===0?`-`:c===void 0?xG(i,s):this.movePr(e,i,c,o??i.remote);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} values=${r.length} pr=${l}`,hG(n),s.size===0?P(null):I([...s].join(`; `)),Date.now()-t)}prSource(e){let t={period:new tG(()=>{this.readPr(e,t,`period`)}),seen:new Map,holders:0,missed:!0,key:``,remote:F,reading:nG(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(CG(`git remote`))}movePr(e,t,n,r){let i=`${n}|${r.kind===`ok`?r.value:r.kind}`;if(i===t.key&&!t.missed)return`kept`;t.key=i,t.remote=r;let a=t.seen.get(i);return a===void 0?t.holders===0?(bG(t),`owed`):(aG(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,iG(t,a.outcome),t.period.landed(eG(mG,a.outcome),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=Date.now(),o=(i.kind===`ok`?this.inner.resolvePullRequest(e.root,i.value).catch(CG(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:F)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${as(r)}`,n,i,Date.now()-a);let o=Date.now();t.seen.delete(r),t.seen.set(r,{outcome:i,at:o});for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==r||t.missed||(iG(t,i),t.period.landed(eG(mG,i),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=I(`git state dropped: ${e.root}`);for(let n of e.values.values())oG(n,t);e.pr!==null&&oG(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watcher.release(),e.period.dispose(),e.pr?.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},TG=class{static CACHE_DIR=bt();static USAGE_CACHE_DIR=s.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=s.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=s.join(this.LOCKS_DIR,e);if(!p.existsSync(t))return!1;try{let n=p.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return E(`Invalid PID in lock file ${e}, removing stale lock`),p.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(E(`Removing stale lock file ${e} for dead process ${r}`),p.unlinkSync(t),!1):(E(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return E(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=s.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await p.promises.writeFile(n,i,{flag:`wx`}),E(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await be(50);else throw e}return E(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=s.join(this.LOCKS_DIR,e);try{await p.promises.unlink(t),E(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&E(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([p.promises.mkdir(this.CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){E(`Failed to create cache directories:`,e)}}static createProjectHash(e){return te(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=s.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){E(`Cache for ${e} is locked, waiting...`),await be(75);continue}try{let r=await p.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(E(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(E(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return E(`No shared ${e} usage cache found`),null;E(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await be(75)}}return E(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){E(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=s.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await p.promises.writeFile(r,i,`utf-8`),E(`[CACHE-SET] ${e} disk cache stored`)}catch(t){E(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const EG={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var DG=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await TG.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await TG.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=ye({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){E(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){E(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(E(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),E(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(E(`Invalid pricing data structure`),e(null))}catch(t){E(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{E(`Response error:`,t),e(null)})});r.on(`error`,t=>{E(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{E(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return E(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return E(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),E(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(E(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(EG).length} models`),this.executionCache=EG,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(EG).length} models`),EG)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return E(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),E(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const OG=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function kG(e){if(typeof e==`string`)return OG.exec(e)?.[1]}function AG(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function jG(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function MG(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=AG(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?kG(jG(n)):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&o===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...o!==void 0&&{command:o}}}function NG(e){if(e!==void 0)return[e];let t=w();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function PG(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await FG(Fa(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function FG(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function IG(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await Fa(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=d(a,o);if(n?.has(t)){r.push(t);continue}let s=await Va(t,void 0,void 0);if(s.kind!==`ok`){E(`Failed to check agent file ${t}`);continue}i=WG(i,t,s.value);let c=VG(Ha(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){E(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function LG(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(zG(t)===`tool_result`)return`tool-result`;let n=typeof e.origin==`object`&&e.origin!==null?e.origin.kind:void 0;if(n!==void 0&&n!==`human`)return`turn`;let r=jG(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||RG.test(r)?`claude-code`:`prompt`}const RG=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function zG(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function BG(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=LG(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:MG(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function VG(e){let t=e.trim();if(!t)return{kind:`blank`};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{kind:`object`,value:e}:{kind:`unparsed`,reason:`not a JSON object`}}catch(e){return{kind:`unparsed`,reason:String(e)}}}function HG(e){let t=VG(e);if(t.kind===`unparsed`)return E(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return BG(t.value)}catch(e){return E(`Failed to project JSONL line: ${e}`),null}}function UG(e){let t=[];for(let n of e.split(`
191
+ `)){let e=HG(n);e&&t.push(e)}return t}function WG(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function GG(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function KG(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await Va(e,a===void 0?void 0:{offset:a.offset,ino:a.ino},s?.size);if(t.kind!==`ok`)return t;let c=t.value;c.reset&&(o=n),i=WG(c.reset?[]:i,e,c),(s===void 0||c.reset)&&(s={size:c.size,stamp:c.stamp});let l=c.start+c.lines.length;if(o=await r(o,Ha(c,e=>UG(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return P({folded:{cursor:a,value:o},longLines:i})}}var qG=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}},JG=class{entries=new Map;refreshes;constructor(e){this.spec=e,this.refreshes=e.ledger.declare({name:e.name,scope:e.scope,refresh:e.every===null?[`first`,`change`,`supersede`]:[`first`,`period`,`change`,`supersede`]})}declare(e,t){let n=this.spec.keyOf(t),r=this.touched(n)??this.firstRead(this.created(n,t));return e.take(`${this.spec.name}:${n}`,()=>this.hold(r)),{current:()=>cG(r)}}supersede(e){let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,aG(n,`superseded`),n.flight=null,n.changed=!1,this.evict();let r=!1;return()=>{r||(r=!0,n.superseding--,this.entries.get(n.key)===n&&this.refresh(n,`supersede`))}}changed(e){for(let t of this.entries.values())t.holders>0&&e(t.input)&&this.refresh(t,`change`)}isHeld(e){for(let t of this.entries.values())if(t.holders>0&&e(t.input))return!0;return!1}stats(){let e=0;for(let t of this.entries.values())t.holders>0&&e++;let{refreshes:t,failures:n,lastMs:r}=this.refreshes.record();return{entries:this.entries.size,held:e,refreshes:t,failures:n,lastMs:r}}close(){for(let e of[...this.entries.values()])this.drop(e)}touched(e){let t=this.entries.get(e);if(t!==void 0)return this.entries.delete(e),this.entries.set(e,t),t}created(e,t){let n={key:e,input:t,reading:nG(),holders:0,flight:null,changed:!1,superseding:0,revisit:YG(this.spec.every,{period:()=>this.refresh(n,`period`),holdReturned:()=>this.refresh(n,`change`)})};return this.entries.set(e,n),n}firstRead(e){return this.refresh(e,`first`),e}refresh(e,t){if(e.superseding>0)return;if(e.flight!==null){e.changed||=t===`change`;return}let n={};e.flight=n;let r=Date.now();ZG(()=>this.spec.read(e.input)).then(i=>{let a=e.flight===n;try{this.refreshes.recorded(`${this.spec.fields(e.input)} stored=${a?`Y`:`N`}`,t,i,Date.now()-r)}finally{a&&this.store(e,i)}}).catch(t=>{this.spec.logger(`error`,`${this.spec.name} refresh threw (${this.spec.fields(e.input)}): ${String(t)}`)})}store(e,t){e.flight=null;try{iG(e,t)}finally{e.revisit.landed(t),e.changed&&(e.changed=!1,this.refresh(e,`change`))}}hold(e){return e.holders++,e.revisit.hold(!0),this.evict(),()=>{e.holders--,e.revisit.hold(e.holders>0)}}evict(){for(let e of[...this.entries.values()]){if(this.entries.size<=this.spec.maxEntries)return;e.holders===0&&e.superseding===0&&this.drop(e)}}drop(e){this.entries.delete(e.key),e.flight=null,e.revisit.dispose(),oG(e,I(`${this.spec.name} entry dropped`))}};function YG(e,t){if(e===null)return new XG(t.holdReturned);let n=new tG(t.period);return{landed:t=>n.landed(eG(e,t)),hold:e=>n.hold(e),dispose:()=>n.dispose()}}var XG=class{state=`released`;answered=!1;constructor(e){this.reread=e}landed(){this.answered=!0}hold(e){if(this.state===`disposed`)return;let t=e&&this.state===`released`&&this.answered;this.state=e?`held`:`released`,t&&this.reread()}dispose(){this.state=`disposed`}};function ZG(e){let t=e=>I(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function QG(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const $G={okMs:60*1e3,failedMs:10*1e3},eK={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},tK={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function nK(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function rK(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function iK(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const aK={entries:0,cost:0,breakdown:iK(),days:new Map};async function oK(e,t){let n=nK(new Date(rK())),r=e.entries,i=e.cost,a={...e.breakdown},o=new Map;for(let[t,r]of e.days)t>=n&&o.set(t,{...r});for(let e of t){let t=e.message?.usage;if(!t)continue;r++;let s=e.costUSD??await DG.calculateCostForEntry(e.raw);i+=s,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0;let c=nK(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...eK};l.cost+=s,l.input+=t.input_tokens||0,l.output+=t.output_tokens||0,l.cacheCreation+=t.cache_creation_input_tokens||0,l.cacheRead+=t.cache_read_input_tokens||0,o.set(c,l)}return{entries:r,cost:i,breakdown:a,days:o}}function sK(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function cK(e){let t=0,n=0,r=iK(),i=new Map;for(let{value:a}of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...eK};sK(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:tK,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}function lK(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function uK(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!lK(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...eK};sK(r,t),n.set(e,r)}return n}async function dK(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}function fK(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function pK(e,t){(0,J.runInAction)(()=>e.set(t))}var mK=class{sessions=J.observable.map(void 0,{deep:!1});flight=new qG;scans;daySets=new Map;speedFlight=new qG;requestFlight=new qG;staleAgeMs;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;sweepTimer=null;constructor(e={}){this.log=e.logger??Me,this.ledger=e.ledger??new Mk(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new JG({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${as(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??$G,maxEntries:8,logger:this.log,ledger:this.ledger});let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps}}scanStats(){return this.scans.stats()}getUsageInfo(e,t){return this.request(e,t?.transcript_path).usage(t)}request(e,t){let n=null,r=()=>{if(n!==null)return n;let r=ja(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async e=>{let t=await r().record;return t.kind===`failed`?t:P(fK(t.kind===`ok`?t.value.sessionInfo:tK,e))},speed:t=>this.observed(e,r,t),today:async e=>{await fG(e),await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return Oa;let r=n.failure.get();return r===null?P(fK(n.record?.sessionInfo??tK,t)):I(r)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=Date.now(),a=await this.ingest(e,t,r,n);return this.renderTally.hits+=r.hits,this.renderTally.misses+=r.misses,r.misses>0&&this.usage.recorded(`sid=${as(e)}`,`request`,a,Date.now()-i),pK(this.hold(e).failure,a.kind===`failed`?a.reason:null),a})}refreshToday(e,t){return this.request(t?.session_id??``,t?.transcript_path).today(e)}declareToday(e,t){let n=NG(t),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?P({roots:i.roots,sums:i.sums.read()}):e}}}todayAt(e,t,n){let r=this.sessions.get(t?.session_id??``),i=r?.failure.get()??null;if(i!==null)return I(i);let a=nK(ok(n)),o={...eK},s=e.sums.get(a);s!==void 0&&sK(o,s);let c=lK(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&sK(o,c),s===void 0&&c===void 0?F:P({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:a})}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return F;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return pK(this.hold(e).speed,t),t;let r=QG(t.kind===`ok`?t.value.sessionInfo.tokenBreakdown:null,n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=P({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return pK(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??Oa:F}async ingest(e,t,n,r){if(!e)return F;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,P(i);if(!t)return i?P(i):F;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return I(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,sessionInfo:s.value.sessionInfo,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),P(c)):l===void 0?P(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,J.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[],failure:J.observable.box(null),speed:J.observable.box(void 0,{deep:!1})};return(0,J.runInAction)(()=>this.sessions.set(e,n)),n}daySet(e){let t=e.join(`\0`),n=this.daySets.get(t);if(n!==void 0)return n;let r=e.map(e=>d(e,`projects`)+f),i={roots:r,sums:new iS(`today over ${e.join(`,`)}`,()=>uK(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await IG(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of GG(r.longLines))this.log(`info`,e);let i=new Map,a=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),o=await KG(e,r,aK,oK);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{folded:s,longLines:c}=o.value;for(let e of GG(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return P({files:i,...cK(i),mainStamp:a})}async scan(e){try{let t=rK(),n=await PG(e),r=[];for(let e of n){let n=await FG(Fa(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a=await FG(Ia(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:Ma(a)})}}let i=[],a={hits:0,misses:0};return await dK(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,a,e.stamp);t.kind===`failed`&&(i.push(t.reason),this.log(`warn`,`usageStore scan: ${t.reason}`))}),this.log(`info`,`usageStore scan dirs=${as(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?I(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`):P({sessions:r.length,read:a.misses})}catch(e){return I(`usage scan: ${e instanceof Error?e.message:String(e)}`)}}sweepStale(){let e=Date.now(),t=nK(new Date(e)),n=0,r=0,i=0;return(0,J.runInAction)(()=>{for(let[a,{lastSeenAt:o,record:s}]of[...this.sessions])if(!(e-o<=this.staleAgeMs)){if(s?.days.has(t)){r++;continue}this.sessions.delete(a),n++,s===void 0&&i++}}),n>0&&this.sweeps++,(n>0||r>0)&&this.log(`info`,`usageStore sweep dropped=${n} noRecord=${i} held=${r}`),n}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.scans.close(),(0,J.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},hK=class{values=J.observable.map(void 0,{deep:!1});order=new Set;constructor(e){this.max=e}get(e){return this.values.get(e)}get size(){return this.order.size}touch(e){this.order.delete(e)&&this.order.add(e)}set(e,t){this.order.delete(e),this.order.add(e),(0,J.runInAction)(()=>{this.values.set(e,t);for(let e of this.order){if(this.order.size<=this.max)break;this.order.delete(e),this.values.delete(e)}})}},gK=class{sessions;constructor(e,t,n,r=Me,i=256){this.empty=e,this.step=t,this.refreshes=n,this.log=r,this.sessions=new hK(i)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=ja(t);if(n?.folded&&i!==``&&n.folded.cursor.stamp===i){let{folded:t,answer:r}=n;return r.kind===`ok`&&r.value===t.value?(this.sessions.touch(e),r):this.store(e,t,{kind:`ok`,value:t.value})}let a=Date.now(),o=await KG(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${as(e)}`,`request`,o,Date.now()-a),o.kind===`failed`)return this.store(e,r,o);if(o.kind===`absent`)return this.store(e,r,{kind:`ok`,value:r?.value??this.empty});let{folded:s,longLines:c}=o.value;for(let e of GG(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??Oa}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function _K(e,t){let n=t.message?.usage;return!n?.input_tokens||t.isSidechain===!0?e:n.input_tokens+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0)}var vK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new gK(void 0,_K,(e.ledger??new Mk(t)).declare({name:`context`,scope:`session`,refresh:[`request`]}),t)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return E(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);E(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){return this.contextFrom(await this.fold.read(e,t),n)}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t?P(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,yK(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return P(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,yK(e))}contextFrom(e,t){if(e.kind===`failed`)return I(`context transcript: ${e.reason}`);let n=e.value;return n===void 0?(E(`No main chain entries with usage data found`),F):(E(`Most recent main chain context: ${n} tokens (limit: ${t})`),P({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function yK(e){return e.context_window?.context_window_size??2e5}const bK={messageCount:0,nonPrompts:0,recent:[]},xK=new Set([`turn`,`interrupt`,`claude-code`]);function SK(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!xK.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function CK(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(r.userEntry===`prompt`||r.userEntry===`turn`)t=r.timestamp;else if(e===`assistant`&&t){let e=(r.timestamp.getTime()-t.getTime())/1e3;e>.1&&e<300&&(n=e)}}return n}var wK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new gK(bK,SK,(e.ledger??new Mk(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),t)}async getMetricsInfo(e,t){E(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?TK(e,n,await this.fold.read(e,t.transcript_path)):F}metricsOf(e,t){let n=t.cost;if(!n)return F;let r=this.fold.answer(e);return r.kind===`pending`?r:TK(e,n,r)}};function TK(e,t,n){return n.kind===`failed`?I(`metrics (${e}): ${n.reason}`):P({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:CK(n.value.recent),sessionDuration:t.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.total_lines_added,linesRemoved:t.total_lines_removed})}const EK={command:null,todos:[],pending:[],done:[]};function DK(e,t){let n=e.findIndex(e=>e.name===t);return n<0?[...e,{name:t,count:1}]:e.map((e,t)=>t===n?{name:e.name,count:e.count+1}:e)}function OK(e,t){switch(t.userEntry){case`prompt`:return{...e,command:t.activity?.command??null,pending:[],done:[]};case`interrupt`:return{...e,pending:[]};case`turn`:case`tool-result`:case`claude-code`:case void 0:return e}}function kK(e,t){if(t.isSidechain)return e;let n=OK(e,t),r=t.activity;if(r===void 0)return n;let i=n.pending,a=n.done;r.started!==void 0&&(i=[...i,...r.started]);for(let e of r.finished??[]){let t=i.findIndex(t=>t.id===e);t<0||(a=DK(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function AK(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>DK(e,t.name),[]),done:e.done}}var jK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new gK(EK,kK,(e.ledger??new Mk(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),t)}async getActivityInfo(e,t){return MK(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:MK(e,t)}};function MK(e,t){return t.kind===`failed`?I(`activity (${e}): ${t.reason}`):P(AK(t.value))}function NK(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function PK(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function FK(e,t,n,r){return PK(D(NK(e,t,n,r)),n)}async function IK(e,t,n,r){return PK(await pt(NK(e,t,n,r)),n)}const LK=3e4;var RK=class{names;constructor(e={}){let t=e.logger??Me;this.names=new JG({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${as(e.pane)} socket=${as(e.socket)}`,read:zK,every:{okMs:LK,failedMs:LK},maxEntries:64,logger:t,ledger:e.ledger??new Mk(t)})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function zK(e){let t=await IK(e,`tmux`,[`display-message`,`-p`,`-t`,e.pane,`#S`]);if(t.kind!==`ok`)return I(t.reason);let n=t.stdout.trim();return n?P(n):F}const BK=6e4,VK={okMs:BK,failedMs:BK};function HK(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function UK(e,t){try{let e=t();return Promise.resolve(e===``?F:P(e))}catch(t){return Promise.resolve(I(`host.${e}: ${String(t)}`))}}var WK=class{name;user;constructor(e={}){let t=e.logger??Me,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:VK,maxEntries:1,logger:t,ledger:e.ledger??new Mk(t)};this.name=new JG({...n,name:`host.name`,read:()=>UK(`name`,()=>HK(C.hostname()))}),this.user=new JG({...n,name:`host.user`,read:()=>UK(`user`,()=>C.userInfo().username)})}declareName(e){return this.name.declare(e,null)}declareUser(e){return this.user.declare(e,null)}held(){return this.name.stats().held+this.user.stats().held}close(){this.name.close(),this.user.close()}},GK=class{known=new hK(64);refreshes;constructor(e=Me,t=new Mk(e)){this.refreshes=t.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=KK(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=Date.now(),i=gP(e);return this.refreshes.recorded(`path=${as(e)} stamp=${as(t)}`,`request`,i,Date.now()-r),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??Oa}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}};function KK(e){try{let t=p.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Ma(t)}catch(e){return`unread:${e.code??`error`}`}}const qK=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function JK(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}var YK=class{known=new hK(256);refreshes;constructor(e=Me,t=new Mk(e)){this.refreshes=t.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=ja(t),r=this.known.get(e);if(r!==void 0&&n!==``&&r.stamp===n&&r.outcome.kind!==`failed`)return this.known.touch(e),r.outcome;let i=await this.read(e,t,n);return this.known.set(e,{stamp:n,outcome:i}),i}expiryOf(e){return this.known.get(e)?.outcome??Oa}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}async read(e,t,n){let r=Date.now(),i=await XK(t);return this.refreshes.recorded(`sid=${as(e)} stamp=${as(n)}`,`request`,i,Date.now()-r),i}};async function XK(e){let t=await ZK(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function ZK(e){for(let t of[65536,1048576]){let n=await Ga(e,t);if(n.kind!==`ok`)return n;let r=QK(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return F}return F}function QK(e,t){let n=e.toString(`utf8`).split(`
192
+ `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!qK.test(t))continue;let r=JK(t);if(r!=null)return r}return null}var $K=class{bySession=J.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:I(n)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,J.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const eq=e=>{try{let t=p.statSync(e,{bigint:!0});return{dev:t.dev,ino:t.ino,birthtimeNs:t.birthtimeNs}}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return`gone`;throw e}},tq=(e,t)=>e.dev===t.dev&&e.ino===t.ino&&e.birthtimeNs===t.birthtimeNs,nq=e=>iV(e),rq=e=>s.join(e.storage.folder,nq(e.sessionId)),iq=e=>JSON.stringify([e.folder,e.generation]),aq=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var oq=class{sessions;folders=new Map;watched=new Map;faults=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;identityOf;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??eq,this.sessions=new JG({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${as(rq(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new Mk(e.logger)})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{p.mkdirSync(e,{recursive:!0}),n=this.identityOf(e)}catch(e){t.unusable=`could not be created or read: ${e.message}`}return(t.lost||t.identity!==null&&(n===`gone`||!tq(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${as(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(iq(e))??this.opened(e);t.holders++;let n=!1;return()=>{n||(n=!0,t.holders--,t.holders===0&&this.closed(t))}}declare(e,t,n){return this.sessions.declare(e,{storage:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({storage:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost}}close(){this.sessions.close();for(let e of[...this.watched.values()])this.closed(e)}recorded(e){let t={generation:0,identity:null,lost:!1,unusable:null};return this.folders.set(e,t),t}opened(e){let t=this.folders.get(e.folder);if(t===void 0)throw Error(`plugin storage: no key was asked for ${e.folder}`);let n=e.generation===t.generation?t.unusable:null,r=n===null?this.identityOf(e.folder):`gone`;e.generation===t.generation&&(t.identity=r===`gone`?null:r);let i={key:e,folder:t,identity:r,holders:0,handle:this.watchers.acquire(`plugin-storage:${iq(e)}`,{files:[],dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),sweep:setInterval(()=>void this.sweep(e),864e5)};i.sweep.unref(),this.watched.set(iq(e),i);for(let e of i.handle.refused)this.faulted(i,`refused`,e.reason);return n!==null&&this.faulted(i,`unusable`,n),this.sweep(e),i}closed(e){let t=iq(e.key);this.watched.delete(t),this.faults.delete(t),clearInterval(e.sweep),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>aq(e.storage,n);switch(t.kind){case`unknown`:this.sessions.changed(r);return;case`changed`:{let{names:i}=t;i.has(s.basename(n.folder))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(nq(e.sessionId)));return}case`failed`:this.judged(e,()=>this.faulted(e,`error`,t.reason));return}}judged(e,t){let{key:n,folder:r}=e,i;try{i=this.identityOf(n.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let a=e.identity;if(i!==`gone`&&a!==`gone`&&tq(i,a)){t();return}n.generation===r.generation&&(r.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${as(n.folder)} generation=${n.generation} now=${i===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>aq(e.storage,n)))}faulted(e,t,n){let{key:r,folder:i}=e;this.faults.set(iq(r),`cannot refresh: ${r.folder} ${n}; reload the config or restart the daemon`),this.faultCounts[t]++,r.generation===i.generation&&(i.lost=!0),this.logger(`warn`,`plugin storage fault folder=${as(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>aq(e.storage,r))}async read(e){let t=this.faults.get(iq(e.storage));if(t!==void 0)return I(t);let n=rq(e),r;try{r=await p.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?F:I(`${n}: ${t.message}`)}if(r.trim()===``)return F;let i=kk(r);return i.kind===`failed`?I(`${n}: ${i.reason}`):i}async sweep(e){let t=Date.now(),n=t-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${as(e.folder)} scanned=${r} removed=${i} took=${Date.now()-t}ms`;try{let t=await p.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=s.join(e.folder,a.name);try{let{mtimeMs:r}=await p.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&nq(t.sessionId)===a.name);if(r>=n||o)continue;await p.promises.unlink(t),i++}catch(e){if(e.code!==`ENOENT`)throw e}}this.logger(`info`,a())}catch(e){this.logger(`warn`,`${a()} outcome=failed reason=${JSON.stringify(e.message)}`)}}};function sq(e){let{logger:t,ledger:n}=e;return{hostService:new WK({logger:t,ledger:n}),gitProvider:new wG({watchers:e.watchers,logger:t,ledger:n}),usageStore:new mK({logger:t,ledger:n}),contextProvider:new vK({logger:t,ledger:n}),metricsProvider:new wK({logger:t,ledger:n}),activityProvider:new jK({logger:t,ledger:n}),tmuxService:new RK({logger:t,ledger:n}),autoCompact:new GK(t,n),cacheExpiry:new YK(t,n),managedStorage:new oq({watchers:e.watchers,logger:t,ledger:n}),faults:new $K,log:e.logger}}function cq(e){return Math.max(1,e-2)}function lq(e,t,n){return Ie({dir:e.project_dir,env:n===void 0?[]:[[qa,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function uq(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function dq(e){return{...Object.fromEntries(py.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:AH(e.preset)}}}const fq={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function pq(e,t){if(!t)return`-`;if(ka(e))return`pending`;let{prState:n,prError:r,prEarlier:i}=e??{};return ka(n)?`pending`:n===void 0?r===void 0?i===void 0?`-`:`earlier-${String(i)}`:`failed`:n}const mq=10*1e3;function hq(e,t){if(!(t<60))return e*3600/t}function gq(e,t,n,r){let i=r-t;if(i<50||i>mq)return;let a=n-e;if(!(a<=0))return a*1e3/i}function _q(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=gq(t.input,t.atMs,n.input,n.atMs),i=gq(t.output,t.atMs,n.output,n.atMs),a=gq(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function vq(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>mq)continue;let o=gq(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function yq(e,t){let n=rx(e,t),r=[...Ug.flatMap(e=>{let t=n[e];return Wg(t)?[t]:[]})];for(let n of E_(nx(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...bq(e,n.name));return Sq(e,r)}function bq(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]):[]}function xq(e,t,n){return Sq(e,[...bq(e,t),...n])}function Sq(e,t){let n=oB(e),r=new Map(Bx(e)),i=t.flatMap(e=>n.ofTemplate(e).flatMap(({reaches:e})=>e)),a=new Set,o=new Set;for(;i.length>0;){let e=i.pop();if(a.has(e))continue;a.add(e);let t=r.get(e),s=rB(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function Cq(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=yq(e,n);return t.set(n,i),i}}function wq(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Tq(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.committedAt`)&&{showCommittedAt:!0},...Object.keys(fq).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const Eq=new WeakMap;function Dq(e){let t=Eq.get(e);return t===void 0&&(t=Oq(e),Eq.set(e,t)),t}function Oq(e){let t=t=>wq(e,t);return{git:t(`git`),session:t(`session.cost`)||t(`session.tokens`)||t(`burn`),today:t(`today`),context:t(`context`)||t(`autocompact`),metrics:t(`metrics`)||t(`burn`),burn:t(`burn`),activity:t(`activity`),tmux:t(`tmux.session`),hostName:t(`host.name`),hostUser:t(`host.user`),cache:t(`cache`),speed:t(`speed`),autocompact:t(`autocompact`),block:t(`block`)}}function kq(e){return cq(e.termCols??120)}function Aq(e){return Xa(Ya(e.claudeConfigDir))}function jq(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function Mq(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=Dq(e.neededInputPaths),s=r.session_id,c=i.usageStore.request(s,r.transcript_path),l=async(e,t,r)=>{if(!t)return;let a=performance.now();n.set(e,null);let o=null;try{await r()}catch(t){i.log(`error`,`${e} lane threw: ${T(t)}`),o=`${e}: ${String(t)}`}n.set(e,Math.round(performance.now()-a)),i.faults.refreshed(s,e,o)};await Promise.all([l(`session`,o.session,()=>c.usage(r)),l(`today`,o.today,()=>c.today(i.lanes().today)),l(`context`,o.context,()=>i.contextProvider.getContextInfo(r)),l(`metrics`,o.metrics,()=>i.metricsProvider.getMetricsInfo(s,r)),l(`activity`,o.activity,()=>i.activityProvider.getActivityInfo(s,r)),l(`cache`,o.cache,()=>i.cacheExpiry.refresh(s,r.transcript_path)),l(`speed`,o.speed,()=>c.speed(ok(t).getTime())),l(`autocompact`,o.autocompact,async()=>i.autoCompact.window(Aq(a)))])}function Nq(e,t){return[...t.keys()].filter(t=>e.has(t))}function Pq(e,t){let n=dG(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function Fq({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,Tq(n),t.workspace?.project_dir]}function Iq(e,t,n,r,i){let a=Dq(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return dG(F);try{return n()}catch(t){return s.push(`${e}: ${T(t)}`),dG(I(`${e}: ${String(t)}`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...Fq(n,r))),tmux:c(`tmux`,a.tmux&&o!==null,()=>e.tmuxService.declare(t,o)),hostName:c(`host.name`,a.hostName,()=>e.hostService.declareName(t)),hostUser:c(`host.user`,a.hostUser,()=>e.hostService.declareUser(t)),today:c(`today`,a.today,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map(Nq(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function Lq(e){let{hookData:t,deps:n}=e,r=Dq(e.neededInputPaths),i=t.session_id,a=n.lanes(),o=(e,t,r)=>{if(!t)return F;let a=n.faults.of(i,e);if(a!==void 0)return a;try{return r()}catch(t){return n.log(`error`,`${e} read threw: ${T(t)}`),I(`${e}: ${String(t)}`)}};return{git:a.git.current(),usage:o(`session`,r.session,()=>n.usageStore.usageOf(i,t)),context:o(`context`,r.context,()=>n.contextProvider.contextOf(t)),metrics:o(`metrics`,r.metrics,()=>n.metricsProvider.metricsOf(i,t)),activity:o(`activity`,r.activity,()=>n.activityProvider.activityOf(i)),tmuxSession:a.tmux.current(),hostName:a.hostName.current(),hostUser:a.hostUser.current(),cache:o(`cache`,r.cache,()=>n.cacheExpiry.expiryOf(i)),speed:o(`speed`,r.speed,()=>n.usageStore.speedOf(i)),autoCompact:o(`autocompact`,r.autocompact,()=>n.autoCompact.stored(Aq(e.hints))),sources:new Map([...a.sources].map(([e,t])=>[e,t.current()]))}}function Rq(e){let t=e.git.current(),n=t.kind===`ok`?t.value.pullRequest:void 0;return[t,e.tmux.current(),e.hostName.current(),e.hostUser.current(),e.today.current(),...[...e.sources.values()].map(e=>e.current()),...n===void 0?[]:[n]].flatMap(e=>e.kind===`pending`&&e.why===`unread`?[e.landed]:[])}function zq(e,t,n){let{hookData:r,hints:i}=e,{effective:a,configFacts:o}=t,{configPath:s,...c}=o,l=Dq(e.neededInputPaths),u=(e,t)=>{switch(e.kind){case`pending`:return Oa;case`failed`:case`absent`:return;case`ok`:return t(e.value)}},d=e=>e.kind===`ok`?e.value:void 0,f=i.tmux??null,p=n.git.kind===`pending`?Oa:Qq(n.git,()=>Oa),m=n.tmuxSession.kind===`pending`?Oa:d(n.tmuxSession),h=n.hostName.kind===`pending`?Oa:d(n.hostName),g=n.hostUser.kind===`pending`?Oa:d(n.hostUser),_=n.autoCompact.kind===`pending`||l.autocompact&&n.context.kind===`pending`?Oa:qq(n.autoCompact,d(n.context)?.maxTokens),v=r.rate_limits?.five_hour,y=r.rate_limits?.seven_day,b=l.burn?n.usage.kind===`pending`||n.metrics.kind===`pending`?Oa:Hq(d(n.usage)?.session.cost,d(n.metrics)?.sessionDuration):void 0,ee=u(n.speed,Uq),x=u(n.usage,e=>Xq({cost:e.session.cost,tokens:e.session.tokens})),S=u(n.metrics,e=>Xq({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),te=u(n.activity,Jq),ne=u(n.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),re=u(n.cache,e=>({expiresAt:e})),ie=Zq(process.env.HOME??process.env.USERPROFILE),ae=r.workspace?{...r.workspace,current_dir:Zq(r.workspace.current_dir)??``,project_dir:Zq(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>Zq(e)??e)}:r.workspace,C=r.session_id;return{...r,...ae!==void 0&&{workspace:ae},...ie!==void 0&&{home:ie},...p!==void 0&&{git:p},...f!==null&&{tmux:{pane:f.pane,...m!==void 0&&{session:m}}},host:{...h!==void 0&&{name:h},...g!==void 0&&{user:g},...i.ssh!==void 0&&{ssh:i.ssh}},...dq(a),history:t.history,navigation:{back:t.back},term:{cols:kq(i)},...c,...s!==null&&{configPath:s},resumeCommand:lq(ae,C,i.claudeConfigDir),...x!==void 0&&{session:x},...b!==void 0&&{burn:b},...ee!==void 0&&{speed:ee},...l.block&&v!==void 0&&{block:{nativeUtilization:v.used_percentage,resetsAt:v.resets_at}},...y!==void 0&&{weekly:{percentage:y.used_percentage,resetsAt:y.resets_at}},...re!==void 0&&{cache:re},...ne!==void 0&&{context:ne},...S!==void 0&&{metrics:S},...te!==void 0&&{activity:te},..._!==void 0&&{autocompact:_},plugins:Vq(n.sources.keys(),e=>{let t=n.sources.get(e);return t.kind===`pending`?Oa:t})}}function Bq(e){return{sources:String(e.size),sourcesPending:[...e].flatMap(([e,t])=>{let n=t.current();return n.kind===`pending`?[`${e}:${n.why}`]:[]}).join(`,`)||`-`}}function Vq(e,t){let n={};for(let r of e){let[,e,i]=r.split(`.`);(n[e]??={})[i]=t(r)}return n}function Hq(e,t){let n=e!=null&&t!=null?hq(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function Uq(e){let t=_q(e),n=vq(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function Wq(e,t){return zq(e,t,Lq(e))}function Gq({usageStore:e,faults:t,log:n},r,i,a){if(t.of(i.session_id,`today`)!==void 0)return;let o=r.current();if(o.kind===`pending`)return Oa;if(o.kind!==`ok`)return;let s=(()=>{try{return e.todayAt(o.value,i,a)}catch(e){return n(`error`,`today read threw: ${T(e)}`),F}})();return s.kind===`pending`?Oa:s.kind===`ok`?{cost:s.value.cost,tokens:s.value.tokens}:void 0}async function Kq(e,t,n){await Mq(e,t,n),await lG(()=>{let t=Rq(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function qq(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return _P(e.value,t)}}function Jq(e){let t=e.todos.findIndex(e=>e.active),n=e.todos.length===0?void 0:{total:e.todos.length,completed:e.todos.filter(e=>e.done).length,...t>=0&&{position:t+1,active:e.todos[t].text}},r=Yq(e.running),i=Yq(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}};if(!(e.command===null&&n===void 0&&a===void 0))return{...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function Yq(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function Xq(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function Zq(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function Qq(e,t){if(e.kind!==`ok`)return;let n=e.value,r=e=>e?.kind===`ok`?e.value:void 0,i=r(n.aheadBehind),a=r(n.sha),o=r(n.operation),s=r(n.committedAt),c=r(n.stashCount),l=r(n.upstream),u=n.upstream===void 0?void 0:r(hW(n.upstream,n.aheadBehind)),d=r(n.repoName),f=r(n.repoUrl),p=n.pullRequest===void 0?void 0:n.pullRequest.kind===`pending`?n.pullRequest:gW(n.pullRequest,n.head),m={};switch(p?.kind){case`pending`:{let e=t(`git.pr`);m={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:m={prNumber:p.value.number,prState:p.value.state,prUrl:p.value.url};break;case`failed`:m={prError:p.reason};break;case`earlier`:m={prEarlier:p.value.state};break;case`absent`:case void 0:break}return{branch:n.branch,status:n.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{committedAt:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{tracking:u},...d!==void 0&&{repoName:d},...f!==void 0&&{repoUrl:f},...m}}function $q(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const eJ={kind:`hidden`},tJ={kind:`shown`};function nJ(e,t){try{return $q(e,t)?tJ:eJ}catch(e){let t=tS(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function rJ(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function iJ(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function aJ({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function oJ({text:e,placement:t,lead:n,trail:r}){return{text:sJ(e),placement:t,...n!==void 0&&{lead:sJ(n)},...r!==void 0&&{trail:sJ(r)}}}function sJ(e){let t=e.blankCopy(e.plain);t.style=Hy(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(Hy(i).clearMetaAndLinks(),n,r);return t}function cJ(e){let t=aJ(e);if(t.length===1)return e.text;let n=rJ(t);return n.style=e.text.style,n}function lJ(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,placement:s,lead:c=[],trail:l=[]}=t;if(e.length===0)return[];let u=rJ(e,a).pad(o),d=new W(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:rJ([d,...c],a)},...l.length>0&&{trail:rJ([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(iJ(u,n,p),[{text:u,...f}])}const uJ=RegExp(`\\x1b\\[[0-9;]*m|${Zd.source}`,`g`);function dJ(e){return Math.max(0,...e.split(`
193
+ `).map(e=>Us(e.replace(uJ,``))))}function fJ(e,t){let n=()=>e.map(e=>({owner:cJ(e),placement:e.placement})),r=[];if(e.forEach(({fill:e},t)=>{e!==void 0&&r.push({at:t,how:e})}),r.length===0||!Number.isFinite(t.width))return n();let i=pb(e.map(cJ),t).split(`
194
+ `);if(i.length>1)return n();let a=Math.max(0,t.width-dJ(i[0]??``)),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];iJ(c,c.cellLength+a,n)}),n()}function pJ(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=mJ(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:Hy(a.style)};if(e.style.link){i();let r=mJ([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function mJ(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>hJ(e.frag,n?n.add(e.style):e.style)),i=W.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function hJ(e,t){let n=e.copy();return n.style=t,n}function gJ(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function _J(e,t){let{look:n}=gJ(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function vJ(e,t){let{layout:n}=gJ(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function yJ(e,t){if(e.bound!==void 0)throw Error(`a render bound a compile another render holds`);return e.bound=t,{[Symbol.dispose]:()=>{e.bound=void 0}}}function bJ(e,t,n,r){let i=new Map,a=Object.entries(t);for(let[t,o]of[...a.filter(([,e])=>!(`do`in e)),...a.filter(([,e])=>`do`in e)])i.set(t,xJ(e,t,o,n,r,i));return i}function xJ(e,t,n,r,i,a){if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=lx(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=Dy.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=lx(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=lx(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:wJ(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:wJ(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`slash`in n)return{kind:`slash`,line:n.slash};if(`run`in n)return{kind:`run`,name:t,declaration:px(n),argv:n.run.map(n=>wJ(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,wJ(e,r,t)])};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:wJ(e,n.name,t)};if(`themeDefault`in n)return{kind:`theme-default-save`};let[o,...s]=n.do.map(e=>{let n=a.get(e);if(n===void 0)throw Error(`action "${t}" fires "${e}", which is not declared in this config`);return n});return{kind:`do`,head:o,rest:s}}function SJ(e){return e.kind===`do`?SJ(e.head):e}function CJ(e){switch(SJ(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`slash`:case`run`:case`do`:return!1}}function wJ(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function TJ(e,t){return e.has(t)?Zx(e.read(t)):``}function EJ(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function DJ(e,t,n,r){let i=new W(e,{style:V.combine([r,new V({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function OJ(e,t,n=!1){let r=new V({link:t,bold:n?!0:void 0}),i=new W(e.plain,{style:V.combine([Hy(e.style),r])});for(let t of e.spans)i.stylize(V.combine([Hy(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function kJ(e,t){return Math.max(e.members.indexOf(TJ(t,e.stateVar)),0)}function AJ(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=TJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=TJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=TJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(kJ(e,r)+1)%e.members.length];return{effects:[{verb:Rr,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:zr,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Br,args:[EJ(e.text,xk(r))]}],active:!1};case`open`:return{effects:[{verb:Vr,args:[EJ(e.target,xk(r))]}],active:!1};case`persist-literal`:{let t=TJ(r,e.stateVar);return{effects:[{verb:Kr,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=TJ(r,e.stateVar);return{effects:[{verb:Kr,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(kJ(e,r)+1)%e.members.length];return{effects:[{verb:Kr,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:qr,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Qr,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ei,args:[i]}],active:!1};case`redo`:return{effects:[{verb:ti,args:[i]}],active:!1};case`back`:return{effects:[{verb:ni,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:ri,args:[i]}],active:!1};case`save`:return{effects:[{verb:Jr,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:Yr,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Xr,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Zr,args:[i,EJ(e.name,xk(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:ai,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:oi,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:si,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:li,args:[i,e.line]}],active:!1};case`run`:{let t=xk(r),n=JSON.stringify({run:e.argv.map(e=>EJ(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,EJ(n,t)]))}),o=a.sign({sessionId:i,action:e.name,declaration:e.declaration,evaluated:n});return{effects:[{verb:`run`,args:[i,e.name,n,o]}],active:!1}}case`layout-op`:return{effects:[{verb:$r,args:[i,e.key,PI(e.op)]}],active:!1};case`do`:{let o=AJ(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>AJ(e,t,void 0,r,i,a).effects)],active:o.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:$r,args:[i,e.key,PI(r)]}],active:!1}}}}function jJ(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:Si(`action "${e}"`,n,t.members.length,kJ(t,r)),boundValue:void 0};if(n.length>2)throw Error(`action "${e}" takes a display and an optional bound value, got ${n.length} arguments (per-state displays are a cycle action's form)`);return{display:n[0],boundValue:n[1]?.plain}}function MJ(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=gJ(n,`action "${e}"`).store,{display:a,boundValue:o}=jJ(e,SJ(r),t,i),s=TJ(i,`session.id`),{effects:c,active:l}=AJ(r,a.plain,o,i,s,n.signer);return OJ(a,pi(c),l)}function NJ(e){return{action:{fn:(t,...n)=>MJ(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function PJ(e,t){return DJ(`✕`,pi([{verb:Rr,args:[TJ(e,`session.id`),t,yi]}]),!1)}function FJ(e,t,n){return new V({bgcolor:z.fromRgba(t),color:z.fromRgba(Xh(e,t,n))})}function IJ({tint:e,text:t}){return new V({bgcolor:z.fromRgba(e),color:z.fromRgba(t)})}function LJ(e,t,n){return new V({color:z.fromRgba(Fl(Bh(e,`warning`),t,Yh,n))})}function RJ(e,t,n){return V.combine([FJ(e,t,n),LJ(e,t,n)])}function zJ(e,t,n){return FJ(e.palette,Cg(e.palette,e.disclosure,t,n),n)}function BJ(e){let t=z.fromRgba(Bh(e,`background`)),n=W.fromFragments(mh.map(n=>new W(`▀`,{style:new V({color:z.fromRgba(Bh(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const VJ=(e,t)=>{let n=typeof e==`string`?new W(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},HJ=e=>new V({bold:e});function UJ(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>VJ(a,V.combine([zJ(e,{...n,distribution:t},i),HJ(o)]));let o=FJ(e.palette,a,i);return(e,t,i,a)=>WJ(i,V.combine([o,HJ(a)]),r(t,n))}const WJ=(e,t,n)=>VJ(W.fromFragments([VJ(e,t),VJ(` `,t),BJ(n)]));function GJ(e,t){return t===void 0?(e,t,n)=>VJ(n):(n,r,i)=>WJ(i,void 0,t(r,e))}function KJ(e,t,n,r,i){let a=FJ(e.palette,i,r);return(e,r,i,o)=>VJ(W.fromFragments([VJ(o?`[`:` `,a),BJ(n(r,t)),VJ(o?`]`:` `,a)]))}function qJ(e,t,n){let r=t.map(t=>({label:t.label,indices:e.flatMap((e,n)=>e.group===t.id?[n]:[])})).filter(e=>e.indices.length>0);if(r.reduce((e,t)=>e+t.indices.length,0)!==e.length){let n=new Set(t.map(e=>e.id)),r=e.flatMap((e,t)=>n.has(e.group)?[]:[`#${t} (group "${e.group}")`]);throw Error(`library: ${r.join(`, `)} name a group the domain does not list (${[...n].join(`, `)})`)}return n?r.flatMap(e=>JJ(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function JJ(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function YJ(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function XJ(e){return{current:null,drawnAt:e}}function ZJ(e,t,n,r,i,a,o){let s={segName:t,placementId:n,palette:r,disclosure:i,tint:a,text:o,bg:void 0,drops:[]};return e.current=s,s}function QJ(e,t,n){return eY(e,()=>n(ZJ(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function $J(e,t){return eY(e,()=>(e.current=null,t()))}function eY(e,t){let n=e.current;try{return t()}finally{e.current=n}}function tY(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function nY(e){return new W(e).cellLength}function rY(e){let{width:t,chromeCols:n,padding:r}=gJ(e,`a row fit`);return Math.max(1,t-n-2*r)}function iY(e){let{padding:t,seamCols:n}=gJ(e,`a row fit`);return Math.max(1,rY(e)-(nY(`✕`)+2*t+n))}function aY(e,t,n){if(!Number.isFinite(t))return e.length>0?[e.map((e,t)=>t)]:[];let r=Math.max(1,t-n),i=[],a=[],o=0;for(let t=0;t<e.length;t++){let n=e[t];a.length===0?(a=[t],o=n):o+1+n<=r?(a.push(t),o+=1+n):(i.push(a),a=[t],o=n)}return a.length>0&&i.push(a),i}function oY(e,t,n){let r=nY(`←`)+1+nY(`→`)+1,i=aY(e,t,n);return(i.length>1?aY(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function sY(e,t){let n=[];for(let t of e)n.length>0&&n.push(new W(` `)),n.push(t);let r=W.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function cY(e,t,n,r,i){let a=e.compiled.get(t);if(!a||a.kind!==n)throw Error(`${i} references action "${t}" which must be ${r}, got ${a?`a ${a.kind} action`:`no such action`}`);return a}function lY(e,t,n){let r=e.compiled.get(t),i=r&&SJ(r);if(!i||i.kind!==`set-option`&&i.kind!==`persist-option`&&i.kind!==`layout-op-option`)throw Error(`${n} references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${i?`a ${i.kind} action`:`no such action`}`);return i}function uY(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=gJ(a,`picker`).store,d=TJ(u,`session.id`),f=`stateVar`in t?TJ(u,t.stateVar):void 0,p=(e,n)=>{let r=t.options[e];return o({index:e,count:t.options.length},r,n,r===f)},m=i?r.kind===`led`?iY(a):rY(a):1/0,h=(r.kind===`led`?0:nY(`✕`)+1)+c.reduce((e,t)=>e+nY(t.glyph)+1,0),g=t.library&&{groups:t.library.groups,entries:t.options.map(t.library.entry)},_=g===void 0?t.options.map((e,t)=>p(t,e)):[],v=g===void 0?oY(_.map(e=>e.cellLength),m,h):qJ(g.entries,g.groups,i),y=parseInt(TJ(u,n.stateVar),10),b=e=>Math.max(0,v.findIndex(t=>t.some(t=>t.indices.includes(e)))),ee=b(f===void 0?-1:t.options.indexOf(f)),x=Number.isInteger(y)?y<0?ee:Math.min(y,v.length-1):0,S=v[x]??[],te=e=>pi([{verb:Rr,args:[d,n.key,String(e)]}]),ne=r.kind===`led`?[]:[{verb:Rr,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],re=r.kind===`own`&&r.onPick?ne:[],ie=e=>pi([...AJ(l,e,e,u,d,a.signer).effects,...re]),ae=(e,n)=>OJ(e,ie(t.options[n])),C=r.kind===`led`?[]:[DJ(`✕`,pi(ne),!1,s)];C.push(...c.map(({glyph:e,option:r})=>DJ(e,pi([...AJ(l,r,r,u,d,a.signer).effects,{verb:Rr,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),x>0&&C.push(DJ(`←`,te(x-1),!1));let w=x<v.length-1?[DJ(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[sY([...C,...e.map(e=>ae(_[e],e)),...w],i)]}let oe=new V({bold:!0}),se=v.length>1?` ${x+1}/${v.length}`:``,T=S.length===1?[new W(`${S[0].label}${se}`,{style:oe})]:[],ce=[sY([...C,...T,...w],i)];for(let e of S){S.length>1&&ce.push(sY([new W(e.label,{style:oe})],i));let n=Math.max(...e.indices.map(e=>nY(t.options[e])));for(let r of e.indices){let e=t.options[r],a=g.entries[r].description,o=a===void 0?void 0:Ny(a),s=` `.repeat(n-nY(e)+2),c=o===void 0?e:`${e}${s}${o}`;ce.push(sY([ae(p(r,YJ(c,m)),r)],i))}}return ce}function dY(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{QO(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=cY(e,r,`set-int`,`an int action ({ set, int: true })`,`picker`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=lY(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=tY(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let[d]=uY(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,UJ(u,kh(void 0),_J(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),LJ(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function fY(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function pY(e,t,n,r,i){let a=Math.min(Math.floor((t-1)/2),i),o=n,s=0;for(;s<a;){let t=o+e(-(s+1))+1+e(s+1)+1;if(t>r)break;o=t,s+=1}return s}function mY(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=gJ(n,`carousel`).store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=TJ(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return sY([],!0);let d=TJ(o,t.stateVar),f=fY(l,d),p=e=>l[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let r=pi(AJ(s,p(e),p(e),o,c,n.signer).effects);return m.set(e,r),r},g=e=>r({index:f(e),count:u},p(e),p(e),p(e)===d),_=new Map,v=e=>{let t=_.get(e);if(t!==void 0)return t;let n=OJ(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):OJ(GJ(_J(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),pi(AJ(n.compiled.get(a),p(0),void 0,o,c,n.signer).effects)),b=pY(e=>v(e).cellLength,u,nY(`◀`)+1+y.cellLength+1+nY(`▶`),iY(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return sY([...ee(-1).reverse(),DJ(`◀`,h(-1),!1),y,DJ(`▶`,h(1),!1),...ee(1)],!0)}function hY(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(QO(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&CJ(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=lY(e,n,`carousel`),l=tY(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return mY(n,c,e,UJ(l,kh(void 0),_J(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function gY(e,t,n){let r=lY(e,t,n);if(!(`stateVar`in r))throw Error(`${n} references action "${t}", which inserts a segment and holds no current value — a ${n} needs a { set, from } or { persist, from } action`);if(r.paletteOf===void 0)throw Error(`${n} references action "${t}", whose options are not colour-valued — a swatch draws the palette an option puts in force, as the "themes", "placementThemes" and "styles" domains do`);return r}function _Y(e,t,n){let r=Math.imul(e^e>>>16,73244475);return r=Math.imul(r^r>>>16,73244475),r^=r>>>16,(n+1+(r>>>0)%Math.max(t-1,1))%t}function vY(e,t,n,r){let i=gY(e,t,n),a=r??TJ(gJ(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,_J(e,`{{ ${n} }}`))}function yY(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(QO(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return BJ(vY(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function bY(e,t,n){return{swatches:{fn:(r,i)=>{let a=gY(e,r,`swatches`),o=cY(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=tY(t,`{{ swatches }}`);if(s.bg===void 0)throw Error(`{{ swatches }} is not available while segments.${s.segName}'s own "bg:" is being evaluated — a swatch row is drawn on that background`);let c=t.drawnAt(),{options:l}=a,u=l.length,[d]=uY(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,KJ(s,_J(e,`{{ swatches }}`),a.paletteOf,c,s.bg),LJ(s.palette,s.bg,c),u===0?[]:(()=>{let t=fY(l,TJ(gJ(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[_Y(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const xY=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function SY(e,t,n,r){let i=ug(e,n,r),a=(t,n)=>({text:t,colour:n,ink:Xh(e,n,r)});return[[wh(t).map((n,i)=>{let a=Vh(e,n);return{text:xY[i%xY.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Bh(e,`warning`)),a(`error`,Bh(e,`error`))]]]}function CY(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new W(` ${e} `,{style:IJ({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new W(e)),r.push(a)}return r}function wY(e,t,n,r,i){let a=SY(e,t,n,r).map(e=>CY(e,i)),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
195
+ `),...e]));return o.overflow=`ignore`,o.end=``,o}function TY(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(QO(`themePreview`,[`applyAction`],i),r!==void 0&&typeof r!=`string`)throw Error(`themePreview: applyAction must name a declared action, got ${JSON.stringify(r)}`);let{palette:a,decor:o}=_J(e,`{{ themePreview }}`);return wY(r===void 0?a:vY(e,r,`themePreview`),o,{...tY(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),iY(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const EY=e=>e.slice(e.lastIndexOf(`.`)+1),DY=(e,t)=>{let n=new W(EY(e));return n.truncate(t,{marker:`…`}),n.plain};function OY(e,t){let n=e.map(e=>e.map(({name:e})=>nY(EY(e)))),r=e=>n.every(n=>n.reduce((t,n)=>t+Math.min(n,e)+2,0)<=t),i=Math.max(1,...n.flat());for(;i>1&&!r(i);)--i;return i}function kY(e,t,n,r){let i=OY(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new W(` ${DY(s,i)} `,{style:IJ(Ng(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
196
+ `),...e]));return o.overflow=`ignore`,o.end=``,o}const AY=`layoutPreview`;function jY(e,t){return{[AY]:{fn:()=>kY(vJ(e,`{{ layoutPreview }}`),_J(e,`{{ layoutPreview }}`).decor,t.drawnAt(),iY(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function MY(e,t,n,r){let i=tY(r.activeSegment,`{{ menu }}`),a=r.action,o=CA(i.placementId,e,n.key),s=EA(o),c=SA(e),l=gJ(a,`menu`).store,u=TJ(l,o)===c,d=TJ(l,`session.id`),f=u?yi:c,p=DJ(Si(`{{ menu "${e}" }}`,t,2,+!!u),pi([{verb:Rr,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=ug(i.palette,i.disclosure,t).plane,l=lY(a,e,`menu`);return uY(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,yi],[s,`0`]],onPick:n.closeOnPick},n.paged,a,UJ(i,n.distribution,_J(a,`{{ menu }}`),l.paletteOf,t,c),LJ(i.palette,c,t))})():[]),p}const NY=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function PY(e,t){let n=t[t.length-1],r=NY(n)?n:void 0,i=r===void 0?t:t.slice(0,-1),a=i.findIndex(e=>typeof e!=`string`);if(a!==-1)throw Error(`{{ menu "${e}" }} display #${a+1} is not text (${JSON.stringify(i[a])}) — a menu binds its trigger text, then an optional trailing (dict …) of options`);return{displays:i,options:AA(r??{})}}function FY(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=PY(t,n);return MY(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function IY(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=LY(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new W(t?i:a,{style:l===void 0?void 0:new V({color:l})}))}let l=W.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function LY(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.min(n,Math.max(0,Math.round(e/t*n)))}function RY(e){let t={fn:(()=>{let t=tY(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],arity:{kind:`exact`},returnType:`string`},n={fn:(()=>tY(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=tY(e,`{{ keptOn }}`),i=El(r,t),a=El(r,n),o=_c(Ll(i,R.TRUECOLOR),Ll(a,R.TRUECOLOR)),s=Math.min(Yh,Math.max(o,3));return(Il(i,e.drawnAt(),(e,t)=>_c(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=IO(()=>tY(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...zY(s)];return IY({value:e,max:t,width:n,filled:r,empty:a,colourAt:c===void 0?void 0:e=>String(i.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...i,bgOf:t,tint:n,keptOn:r,gauge:a}}function zY(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function BY(e,t){if(e.kind!==`shell`&&e.kind!==`file`)return[];let n=`key`in e.cache&&[...t.calls(e.cache.key)].some(e=>yk.has(e));return[...t.ofVariable(e).flatMap(({reaches:e})=>e.length===0?[null]:e),...n?[null]:[]]}const VY={input:`view`,state:`view`,template:`view`,time:`view`,literal:`directory`,env:`directory`,dropped:`directory`,source:`view`},HY=new WeakMap;function UY(e){let t=HY.get(e);return t===void 0&&(t=WY(e),HY.set(e,t)),t}function WY(e){let t=new Map(Bx(e)),n=oB(e),r=new Map([...t].map(([e,t])=>[e,t.kind===`shell`||t.kind===`file`?`directory`:VY[t.kind]])),i=new Map([...t].map(([e,t])=>[e,BY(t,n)]));for(let e=!0;e;){e=!1;for(let[t,n]of i)r.get(t)!==`view`&&n.some(e=>e===null||r.get(e)!==`directory`)&&(r.set(t,`view`),e=!0)}return r}function GY(e){let t=[],n=[];for(let r of e){if(!r.contains(`
197
197
  `)){n.push(r);continue}let e=r.split(`
198
- `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function WY(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}const GY=e=>e.kind===`failed`?Qq:e;function KY(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function qY(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:n,opened:r.length>0,ground:i},deeper:r}}function JY(e){return{...e,cells:e.cells.map(iJ)}}function YY(e,t){let n=t.flatMap(e=>e.filter(e=>e.place===`above`)),r=t.map(e=>e.filter(e=>e.place===`flow`));return[...n,...XY(e,r)]}function XY(e,t){switch(e){case`vertical`:return t.flatMap(e=>e);case`horizontal`:return t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`,place:`flow`},...t.flatMap(e=>e.slice(1))]}}function ZY(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:YY(e.direction,e.children.map((t,i)=>n(t,[...r,QY(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function QY(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:x_[e.direction]}}const $Y={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:kh(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,D_(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),YY(e.direction,e.children.map((n,r)=>t.renderChild(n,GY(t.gate),QY(e,r))))}},eX={drop:e=>e.place,above:()=>`above`},tX={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},nX={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:S_(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Ti(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,O_(t.path)),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render:(e,t)=>t.placed(e.id,rX(e,t))};function rX(e,t){let n=t.lookupSegment(e.name);if(n===void 0)throw Error(`Layout segment "${e.name}" has no matching segment`);if(t.gate.kind===`hidden`)return[];let r=Sk(t.scope,e.settings);if(t.gate.kind===`failed`)return lX(e,r,t,t.gate.message);try{let i=t.placement(e),a=KY(t.gate,i.gate());if(a.kind===`failed`)return lX(e,r,t,a.message);if(a.kind===`hidden`)return[];let o=i.bodyGate(),s=o.kind===`failed`&&a.kind===`pending`?a:o;if(s.kind===`failed`)return lX(e,r,t,s.message);let c=jb(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:Vj(c)},u=e=>({width:n.width??`auto`,justify:n.justify??`left`,truncate:n.truncate??`right`,baseStyle:e,padding:t.padding,placement:l}),d=s.kind===`shown`,f=a.kind===`pending`?a:s,p=f.kind===`pending`?iX(f.variable):aX(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?oX(p.segment,u):sX(e,r,t,p.variable,c,d,u);if(m===null)return[];let{styles:h,inline:g,drops:_}=m,v=e.opens,y=v===void 0?[]:t.renderBody(v.body,d?a:Qq,h.disclosure).map(e=>({...e,place:eX[v.placement](e)})),b=(e,t,n)=>sJ(dJ([e],t),{...u(t),width:`auto`,padding:n}),ee=y.findIndex(e=>e.band===`own`),{lead:x,stays:S}=v!==void 0&&ee!==-1?tX[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},te=x.flatMap(e=>b(new W(` `.repeat(cX(rJ(e)))),h.trigger,0)),ne=(e,t)=>e.band===`own`?t===ee?x:te:[],re=y.map((e,t)=>({cells:[...ne(e,t),...e.cells],band:`deeper`,place:e.place})),ie=[...S,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ie.flatMap(e=>e.cells),...y.flatMap(ne)].flatMap(rJ)),[...ie,...re]}catch(n){return lX(e,r,t,n.message??String(n))}}const iX=e=>({kind:`waiting`,variable:e});function aX(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=eS(e);if(t===void 0)throw e;return iX(t.variable)}}function oX(e,t){let{styles:n,fragments:r,lead:i,trail:a,drops:o,open:s}=e,c=s?n.trigger:n.closed,l=t(c);return{styles:n,inline:UY(dJ(r,c)).map((e,t)=>({cells:sJ(e,{...l,lead:t===0?dJ(i,c):[],trail:t===0?dJ(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:sJ(dJ([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function sX(e,t,n,r,i,a,o){n.waited(r);let s=n.lastDrawn(e.id);if(s?.kind===`hidden`)return null;let c=n.decorations(e,i),l=a?c.trigger:c.closed,u=dJ(uX(e.lead,e,t,n),l),d=dJ(uX(e.trail,e,t,n),l);return{styles:c,inline:(s===void 0||s.drawing.own.length===0?[[`auto`]]:s.drawing.own.map(e=>e.cells.map(e=>e.text.cellLength))).map((e,t)=>({cells:e.flatMap((e,n)=>{let r=t===0&&n===0;return sJ(dJ([new W(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function cX(e){return e.reduce((e,t)=>e+t.cellLength,0)}function lX(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:sJ([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:Vj(n.palette)},lead:uX(e.lead,e,t,n),trail:uX(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function uX(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=eS(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const dX={container:$Y,segment:nX};function fX(e){return dX[e]}var pX=class{last=null;from(e){let{last:t}=this;return t!==null&&t.source.config===e.config&&t.source.preset===e.preset&&t.source.revision===e.revision&&t.source.width===e.width?t:null}begin(e,t){let n=new Map,r=new Map;return{placed:(e,r)=>{let{drawing:i}=t(e,r);return n.set(e,i===null?mX:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const mX={kind:`hidden`},hX={palette:`theme`,style:`style`,effect:`effect`},gX=Dy.get(`colorCompatibility`),_X={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function vX(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function yX(e){if(e.ok)return e.value;throw e.error}const bX=e=>({read:()=>e}),xX=fh({basePalette:dh,palette:dh,decor:Eg});var SX=class{evaluated=0;memory=new pX;scope;binding;facts;look=J.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&xX(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=J.observable.box(r,{deep:!1}),this.scope=bk(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(gX);return typeof e==`string`&&u_(e)?e:`truecolor`});let i=(0,J.observable)(_X,void 0,{deep:!1});this.facts=i;let a=this.look,o=this.phase,s=()=>this.layout.read();this.binding={store:e,registry:t,get width(){return i.width},get chromeCols(){return i.chromeCols},get padding(){return i.padding},get seamCols(){return i.seamCols},get look(){return o.ruling?void 0:a.get()},get layout(){return o.ruling?void 0:s}},this.layout=this.derive(`layout`,n.layoutReadsInstant,()=>{let e=n.roots.get(i.preset),t=a.get().palette;return ZY(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=wI(e);return i===void 0?[]:[{name:i,address:n,palette:jb(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>d_(this.colorCompatibility())})}bind(e){(0,J.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,J.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=cA(e);return t===void 0?oA(e)===void 0?Yk(this.view.get().payload(),e):Yk(this.projected,e):this.slotName(t)}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[hX[e]];if(t.kind===`decided`)return TX(t.name,null,null);let r=DX(this.source,e,t.source);if(this.source.instant.has(r.template))return{kind:`per-draw`,rule:r};let i=this.rule(r.template);switch(i.kind){case`named`:{let t=null;return n=OX(this.source,e,i.name,r.where,e=>{t=e}),TX(n,t,null)}case`pending`:return TX(n??Zg[e],null,i.variable);case`failed`:return n=Zg[e],TX(n,Qg(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!EX(i,e))&&(i=e),i}),this.slots.set(e,t)}return t.read()}slotName(e){let t=this.slot(e);return t.kind===`settled`?t.name:this.drawnSlots.get(e)??Zg[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,J.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return eJ(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>ZJ(this.source.activeSegment,()=>eJ(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new kX(this,e),this.placements.set(e,t)),t}rule(e){let t=this.rules.get(e);return t===void 0&&(t=this.derive(`rule`,this.readsInstant(e),()=>{this.phase.ruling=!0;let t=this.source.runtime.bound===this.binding?null:_J(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=eS(e);return t===void 0?{kind:`failed`,error:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}finally{t?.[Symbol.dispose](),this.phase.ruling=!1}}),this.rules.set(e,t)),t.read()}readsInstant(...e){return e.some(e=>e!==void 0&&this.source.instant.has(e))}derive(e,t,n){let r=()=>(this.evaluated++,n());return this.store.derive(`part ${e}`,t?`projection`:`computed`,t?this.oncePerDraw(r):r)}oncePerDraw(e){let t=null;return()=>(t?.draw!==this.draws&&(t={draw:this.draws,answer:vX(e)}),yX(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:wI(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function CX(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new SX(t,n,e,r);return e.views.set(t,a),a}function wX(e,t){let n=e.views.get(t);if(n===void 0)throw Error(`a store was drawn before its view was bound (bindView): its inputs have no source`);return n}const TX=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),EX=(e,t)=>e.kind===`settled`?t.kind===`settled`&&e.name===t.name&&e.warning===t.warning&&e.waited===t.waited:t.kind===`per-draw`&&e.rule===t.rule;function DX(e,t,n){let r=e.globalExpressions.get(t)?.get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the view but no compiled template exists — the compile and the resolution disagree about isExpression`);return r}function OX(e,t,n,r,i){switch(t){case`palette`:return Ib(n,r,i).name;case`style`:return Jg(n,e.styles).name;case`effect`:return i_(n).name}}var kX=class{where=AX(fh({palette:dh,region:wg}));ground=AX(fh({colours:MX,bodyOpen:dh}));opened=AX(fh({colours:MX,open:dh}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=Sk(e.scope,t.settings),{when:a,bg:o,fg:s,template:c}=n,{lead:l,trail:u}=t,d=t.opens?.open;this.ownGate=a===void 0?bX($q):e.derive(`${t.id} when`,e.readsInstant(a),()=>ZJ(r,()=>eJ(a,i))),this.open=d===void 0?bX(Qq):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>ZJ(r,()=>eJ(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return FX(r,t,n,a,e.registry.drawnAt(),o,s,i)}),this.body=e.derive(`${t.id} body`,e.readsInstant(c),()=>{let{colours:e,bodyOpen:n}=this.ground.get();return IX(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?bX(RX):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return LX(r,t,e,n,l,u,i)})}gate(){return this.ownGate.read()}bodyGate(){return this.open.read()}evaluate(e,t){this.where.set({palette:e,region:t});let n=this.colours.read();this.ground.set({colours:n,bodyOpen:this.open.read().kind===`shown`});let r=this.body.read();return this.opened.set({colours:n,open:r.open}),BX(n,r,this.affixes.read())}};function AX(e){let t=J.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,J.runInAction)(()=>t.set(e)),get:()=>t.get()}}const jX=(e,t)=>e.hex===t.hex,MX=fh({palette:dh,drawnAt:dh,tint:jX,text:jX,bg:jX,disclosure:Dg});function NX(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const PX=e=>ug(e.palette,e.disclosure,e.drawnAt);function FX(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Ng(n,r,i)};return XJ(e,NX(t,c),e=>{let t=Uj(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function IX(e,t,n,r,i,a){return XJ(e,NX(t,n),e=>(e.bg=i?PX(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function LX(e,t,n,r,i,a,o){return XJ(e,NX(t,n),e=>(e.bg=r?PX(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const RX={lead:[],trail:[],drops:[]};function zX(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return NJ(t,PX(e).state,n)},get band(){return NJ(t,PX(e).plane,n)},get close(){return IJ(t,PX(e).state,n)},disclosure:r}}function BX(e,t,n){return{styles:zX(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open,shortfalls:t.open?PX(e).shortfalls:[]}}function VX(e,t,n,r,i,a,o){let s=FX(e,t,n,r,i,void 0,void 0,o);return BX(s,IX(e,t,s,a,!1,o),RX)}function HX(e,t,n,r,i){return zX(FX(e,t,n,r,i,void 0,void 0,{}))}function UX(e,t){return{payload:()=>e,selections:()=>t}}function WX(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Fk(e.ttl)};if(`watch_file`in e)return{kind:`watch_file`,path:e.watch_file};if(`depends_on`in e)return{kind:`depends_on`,varNames:e.depends_on};if(`key`in e)return{kind:`key`,template:e.key};if(`never`in e)return{kind:`never`};throw Error(`Unknown CacheDecl discriminator — loader invariant violated: ${JSON.stringify(e)}`)}function GX(e,t){switch(j_(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,regex:new RegExp(e.regex),default:t};case`text`:return{kind:`text`,default:t}}}function KX(e,t,n,r,i){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`source`:e.declareSourceDocument(t);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default,i);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:WX(n.cache),parse:GX(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:WX(n.cache),parse:GX(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{type:n.type??`string`,varDefault:n.default,derivation:i});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function qX(e,t){let n=HS.EMPTY;for(let[r,i]of Object.entries(t))try{n=e.parse(`{{ define "${r}" }}${i}{{ end }}`,n).defines()}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}return n}function JX(e,t,n){let{compiled:r,loadWarnings:i}=XX(e,t,n.cwd,YX(n.signer),eZ);return{...r,loadWarnings:i}}const YX=e=>(t,n)=>tZ(n,e);function XX(e,t,n,r,i=eZ){let a=ZX(e),o=QX(a);return{compiled:r(o,a),compileKey:o,loadWarnings:$X(e,t,n,i)}}function ZX(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of Oy)n in t&&r.set(e,n);for(let[t,n]of L_(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...cB(e)].sort(([e],[t])=>e<t?-1:1)}}function QX(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function $X(e,t,n,r){let i=VY(e),a=cB(e),o=[];for(let[s,c]of zx(e))if(r.has(i.get(s)))try{KX(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const eZ=new Set([`directory`,`view`]);function tZ({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>mJ(i,`drawnAt`).registry.drawnAt(),o=JJ(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=Qb(e.presets),u=pI(e),d=[e=>vY(i,o,e.now)],f=yk({extraFuncs:{...jJ(i),..._Y(i),...lY(i,o),...pY(i,o),...CY(i,o),...kY(i,o),...NY(s),...IY(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=qX(f,e.helpers),m=new Map,h=e=>{let t=f.parse(e,p);return m.set(t,e),t},g=new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n=h(e);return g.set(e,n),n},v=new Map(t);i.compiled=vJ(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=h)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:e(n.when,`when`,_),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let b=(e,t,n)=>{try{return _(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},ee=t=>{let n=V_(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>q_(t,e,a,t=>String(mJ(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},x=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:x,placementSettings:ee};return fX(e.kind).compile(e,n)},S=new Map;for(let t of l){let{node:n,path:r}=tx(e,t);S.set(t,x(n,r))}let te=new Map(Ug.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of uB(e)){let e=t.join(`.`),i=te.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:iZ(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let ne={reads:eB({names:new Set(n.map(([e])=>e)),helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:gk(d)},re=pB(ne),ie=[...S.values()].flatMap(rZ(y)).some(e=>re(m.get(e))),ae=ie?pB({...ne,clock:new Set([...ne.clock,OY])}):re;return{segments:y,roots:S,activeSegment:o,menuRuntime:s,globalExpressions:te,instant:new Set([...m].flatMap(([e,t])=>ae(t)?[e]:[])),layoutReadsInstant:ie,styles:e.styles,runtime:i,views:new WeakMap}}function nZ(e){return Object.entries(e.segments).flatMap(([t,n])=>[n.when,n.bg,n.fg,n.template].some(t=>t!==void 0&&e.instant.has(t))?[t]:[])}const rZ=e=>t=>{let n=[];return ZY(t,e=>(n.push(e),!0)),n.flatMap(t=>[...t.when===void 0?[]:[t.when],...t.kind===`segment`&&e[t.name].when!==void 0?[e[t.name].when]:[]])};function iZ(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}const aZ=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function oZ(e,t,n,r,i){let a=sZ(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function sZ(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??Zg[e];case`failed`:return r({kind:`rule`,slot:e,message:Qg(t.where,e,`the rule failed — ${n.error}`)}),Zg[e]}}function cZ(e){return lZ(e).filter(e=>!e.name.startsWith(gA)).map(e=>e.id)}function lZ(e){return e.kind===`container`?e.children.flatMap(lZ):[e,...e.opens===void 0?[]:lZ(e.opens.body)]}function uZ(e,t,n,r,i,a,o,s,c=FH(e,()=>null,()=>!1)){let l={...i,term:{cols:o.width},colorCompatibility:{effective:o.colorCompatibility}};return CX(t,n,r,UX(l,c)),fZ(e,t,n,r,l,a,o,s,c)}function dZ(...e){return uZ(...e).text}function fZ(e,t,n,r,i,a,o,s,c){try{var l=Aa();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=new Set,h=c.effects??new $y(``),g=h.clockAt(a,e_[c.animationSpeed]);l.u(sk(a,g.anim));let _=wX(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:sb(v),padding:v.padding,seamCols:cb(v),preset:c.preset},i);let y=_.evaluated;l.u(_J(t.menuRuntime.action,_.binding));let{preset:b,transitions:ee}=c,x={variation:Ch[c.variation],shade:xh[c.shade]},S={config:e,preset:b,revision:r.stateRevision(),width:v.width},te=_.memory.begin(S,qY),ne=_.memory.from(S),re=new Set,ie={held:e=>ne?.rules.get(e),waited:e=>re.add(e),settled:te.rule},ae=new Map,C=e=>{let n=_.slot(e);if(ae.set(e,n.kind===`settled`?`kept`:`per-draw`),n.kind===`settled`)return n.warning!==null&&p({kind:`rule`,slot:e,message:n.warning}),n.waited!==null&&re.add(n.waited),n.name;let r=OX(t,e,oZ(e,n.rule,_,p,ie),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:w,style:oe,effect:se}=_.selections(),T=w.kind===`decided`?w:Ib(C(`palette`),``,aZ),ce=oe.kind===`decided`?oe:Jg(C(`style`),e.styles),le=se.kind===`decided`?se:i_(C(`effect`)),ue=T.value,de=Nb(ue,ce.value);_.publishLook({basePalette:ue,palette:de,decor:x});let fe=c.idleSince===void 0?null:Jv(c.idleSince,c.menuTimeout,a),pe=Bh(de,`warning`),me=fe===null?null:{t:fe,fill:pe,text:Xh(de,pe,r.drawnAt())},he=h.motion(le.value,g,{transitions:ee,source:S,last:ne,returned:qY,hold:JY},me);u?.clear();let ge=t=>e.segments[t],_e=e=>{for(let t of e.shortfalls)m.add(t);return e},ve=e=>{let t=_.placement(e);return{gate:()=>t.gate(),bodyGate:()=>t.bodyGate(),evaluate:(e,n)=>_e(t.evaluate(e,n))}},ye=(e,i,a)=>{let o=i.kind===`hidden`?i:KY(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${cZ(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:o.message,message:`${t}: ${o.message} — what it gates is hidden`})}}:o,c={scope:_.scope,palette:de,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:ve,evaluateOnce:(e,n,i,o)=>_e(VX(t.activeSegment,e,i,a,r.drawnAt(),o,n)),lookupSegment:ge,renderChild:(e,t,n)=>ye(e,t,jg(a,n)),renderBody:(e,t,n)=>ye(e,t,Mg(n)),closeDisclosure:e=>MJ(n,e),placed:(e,t)=>te.placed(e,he.placed(e,t)),lastDrawn:e=>ne?.placements.get(e),waited:e=>re.add(e),decorations:(e,n)=>HX(t.activeSegment,e,n,a,r.drawnAt())};return fX(e.kind).render(e,c)},be=t.roots.get(b);if(be===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${Xb}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let xe=WY(ye(be,$q,Ag(x))).map(({line:e,row:t})=>{let n=uJ(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,...fb(n.map(e=>e.owner),v,he.row(t,r,n))}});he.drawn(),te.commit();let Se=xe.filter(e=>e.kind===`menu`).length,Ce=xe.some(e=>e.moves)?`moves`:Se>0||_.selections().effect.kind===`expression`||ee||lZ(be).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`)?`can-move`:`still`;for(let e of m)p({kind:`band-floor`,message:e});for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{text:xe.map(e=>e.text).join(`
199
- `),motion:Ce,menuRows:Se,evaluated:_.evaluated-y,pending:[...re].sort(),rules:ae}}catch(e){l.e=e}finally{l.d()}}function*pZ(e){yield*Object.entries(e.variables??{});for(let[t,n]of Object.entries(e.segments??{}))for(let[e,r]of Object.entries(n.vars??{}))yield[`${t}.${e}`,r]}function*mZ(e){for(let t of Object.values(e.segments))for(let e of[t.template,t.bg,t.fg,t.when])e!==void 0&&(yield e);for(let t of Qb(e.presets)){for(let n of E_(tx(e,t).node))n.when!==void 0&&(yield n.when);let n=nx(e,t);for(let e of Ug){let t=n[e];Wg(t)&&(yield t)}}for(let[,t]of pZ(e))for(let[,e]of P_(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of px(t))yield e}function hZ(e,t){let n=iB(t),r=new Set,i=new Set,a=new Set;for(let e of mZ(t)){for(let{reaches:t}of n.ofTemplate(e))for(let e of t)r.add(e);for(let{name:n}of jx(e,t.helpers))i.add(n);for(let n of Ix(e,t.helpers))a.add(n)}for(let[,e]of pZ(t))for(let{reaches:t}of n.ofVariable(e))for(let e of t)r.add(e);let o=new Set(i);for(let e of i){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)o.add(e)}let s=new Set,c=new Set;for(let e of o){let n=t.actions[e];if(n!==void 0&&(`set`in n&&s.add(n.set),`insertSegment`in n&&c.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)c.add(e)}for(let e of Qb(t.presets))for(let n of E_(tx(t,e).node))n.kind===`segment`&&c.add(n.name);let l=(e,t)=>r.has(e)||t.kind===`state`&&s.has(t.key),u=e=>[...e].filter(e=>!vA(e)),d=(e,t,n)=>u(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),f=new Map(pZ(e));return[...d(`variable`,f.keys(),e=>l(e,f.get(e))),...d(`action`,Object.keys(e.actions??{}),e=>o.has(e)),...d(`helper`,Object.keys(e.helpers??{}),e=>a.has(e)),...d(`segment`,Object.keys(e.segments??{}),e=>c.has(e))]}var gZ=class{held=new Map;declaring=null;closed=!1;take(e,t){if(this.closed)throw Error(`hold taken after close: ${e}`);this.declaring?.taken.add(e),!this.held.has(e)&&(this.held.set(e,t()),this.declaring!==null&&this.declaring.acquired++)}declare(e){if(this.declaring!==null)throw Error(`declaration within one`);let t={taken:new Set,acquired:0};this.declaring=t;let n;try{n=e()}finally{this.declaring=null}let r=0;for(let[e,n]of this.held)t.taken.has(e)||(this.held.delete(e),n(),r++);return{result:n,acquired:t.acquired,released:r}}close(){this.closed=!0;let e=this.held.size;for(let e of this.held.values())e();return this.held.clear(),e}get size(){return this.held.size}};function _Z(e){return Math.floor(Math.max(e/4,e*or-67108864))}const vZ={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function yZ(e,{plugins:t,config:n,compiled:r}){let{checkout:i,loaded:a,dropped:o,unreached:s}=t,c=i===null?`-`:`${i.git?`git`:`dir`}:${i.root}`,l=e=>{let t=$B(e),r=t===void 0?void 0:n.variables[tV(t)];return r?.kind===`file`?r.path:`none`},u=a.flatMap(e=>{let t=$B(e);return t===void 0?[]:[t]}).flatMap(e=>Object.entries(n.variables).filter(([t])=>sV(e)(t)&&t!==tV(e))),d=u.filter(([,e])=>e.kind===`source`).length,f=u.length-d;return`config load ${e.join(` < `)||`<default>`}: projections=${[...cB(n).keys()].join(`,`)||`-`} instantSegments=${nZ(r).join(`,`)||`-`} instantTemplates=${r.instant.size} plugins loaded=${a.length} sources=${d} pluginVariables=${f} dropped=${o.length} unplaced=${s.length} checkout=${c}`+a.map(e=>` +${e} data=${l(e)}`).join(``)+o.map(e=>` -${e.path} (${e.reason})`).join(``)+s.map(e=>` ~${e.path} (${e.reason})`).join(``)}function bZ(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function xZ(e,t,n){return e+`\0`+t+`\0`+(n??``)}function SZ(e,t){return new Set(Qb(e.presets).filter(n=>tx(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function CZ(e,t){let n=new Map,{roots:r,loaded:i,dropped:a,unreached:o}=e.state.plugins;for(let t of[...HV(e.projectDir,e.cwd,e.configFile),...r,...i,...[...a,...o].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))]){let{dir:e,name:r}=Wx(t),i=n.has(e)?n.get(e):new Set;i?.add(r),n.set(e,i)}for(let e of r){let{dir:t,name:r,leaf:i}=Wx(s.join(e,`_`));i&&r===`_`&&n.set(t,null)}return{files:t,dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})}}function wZ(e){return e.filter(Boolean).join(`
200
- `)||null}function TZ(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=rH(t.layers,EH,{entered:i,warned:e=>n.push(...e)},{projectDir:t.projectDir,cwd:e});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??EH,l=a.find(e=>e.path===t.home)?.raw??{},u=new pS,d=new $k(u,o.globals.default_empty_value??``,r.sessionState,null,r.ledger),f,p;try{f=XX(o,d,e,r.compile??YX(r.signer),kZ),n.push(...f.loadWarnings);let t=d.view();n.push(...$X(o,t,e,AZ)),t.dispose(),_U(o),qI(o),p=EZ(o,r.storage,d)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:xq(o),authoredRoots:SZ(c,l),fileHeldSettings:rU(l),configPath:t.layers.includes(t.home)?t.home:null,unused:[...new Map(a.flatMap(e=>hZ(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{checkout:s.checkout,roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering},sources:p}}function EZ(e,t,n){let r=new Map,i=new Map;for(let[a,o]of Object.entries(e.variables)){if(o.kind!==`source`)continue;let e=r.get(o.storage);e===void 0&&(e=t.keyFor(o.storage),r.set(o.storage,e),n.own(t.watch(e))),i.set(a,e)}return i}function DZ(e,t,n,r){let i=WV(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[YV(e,t),qV(i)],s,c=null;try{s=TZ(t,a,o,r,e=>{c=e})}catch(e){return e instanceof Z_&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:wZ(o),state:null,error:e instanceof Z_||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:wZ(o),state:s,error:null}}function OZ(e,t,n){return TZ(e,{layers:[],home:``,projectDir:t},[],n)}const kZ=new Set([`directory`]),AZ=new Set([`view`]);function jZ(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new gZ;$X(e.config,l,t,AZ);let d=()=>PH(e.config,e=>r.get(c,e)),f=(t,n)=>{try{let r=e.neededInputPaths(n),{result:{lanes:a,faults:o},acquired:l,released:d}=u.declare(()=>i(u,t,r,e.sources));for(let e of o)s(`error`,`session view declaration threw sid=${JSON.stringify(c)} ${e}`);return l+d>0&&s(`info`,`session view declared sid=${JSON.stringify(c)} acquired=${l} released=${d} held=${u.size}`),a}catch(t){return s(`error`,`session view declaration threw sid=${JSON.stringify(c)}: ${String(t)}`),Mq(I(`view declaration threw: ${String(t)}`),[...e.sources.keys()])}},p=(e,t)=>({facts:e,preset:t,lanes:f(e,t)}),m=J.observable.box(p(n,d()),{deep:!1}),h=(e,t)=>{let n=m.get();if(e===n.facts&&t===n.preset)return;let r=p(e,t);(0,J.runInAction)(()=>m.set(r))},g=(0,J.reaction)(d,e=>h(m.get().facts,e),{fireImmediately:!0}),_=a({sessionId:c,state:e,store:l.variableStore,declared:()=>m.get()});CX(e.compiled,l.variableStore,l,_);let v=(0,J.reaction)(()=>{let{sources:t,...n}=m.get().lanes;return[_.payload(),_.selections(),l.published(),e.registry.published(),...[...Object.values(n),...t.values()].map(e=>e.current())]},()=>o(c),{equals:J.compareShallow,fireImmediately:!0,onError:e=>s(`error`,`session view change threw sid=${JSON.stringify(c)}: ${String(e)}`)});return{sessionId:c,state:e,store:l.variableStore,registry:l,holds:u,source:_,requested:e=>h(e,d()),facts:()=>m.get().facts,lanes:()=>m.get().lanes,lastRenderCellsBySegment:new Map,retire:v,dispose:()=>(g(),v(),u.close(),l.dispose())}}var MZ=class{entries=new Map;sweep=null;closed=!1;holds=new Map;views=new Map;viewHolds=new Map;pins=new Map;openFailures=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Me,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}compileOf(e,t){return this.compiles.get(e)??tZ(t,this.deps.signer)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760+this.views.size*2621440}getOrCreate(e,t,n){let r=xZ(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.load(e,t,n);a.state!==null&&this.log(`info`,yZ(a.layers,a.state));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??OZ(t,e,this.deps),watcher:null,watcherKey:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${tr(this.accountedBytes())}/${tr(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o,[]),o}hold(e,t,n){let r=this.getOrCreate(e,t,n);return this.holdState(r,r.state)}holdState(e,t){let n=this.holdOf(t);n.holders++,this.armSweep();let r=!1;return{entry:e,state:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache hold released twice`);r=!0,n.holders--,this.reclaim(t,n)}}}holdSession(e,t,n,r){let i=this.hold(e,t,n),a,o;try{a=this.viewOf(i.entry,i.state,r,`request`),o=this.leaseOf(a)}catch(e){throw i[Symbol.dispose](),e}return o.read=!0,this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}follow(e,t,n,r){try{var i=Aa();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(xZ(t,n,r));if(a!==void 0&&s?.state===a.state)return;let c=i.u(this.hold(t,n,r));this.viewOf(c.entry,c.state,o,`click`)}catch(e){i.e=e}finally{i.d()}}pin(e){this.pins.set(e,(this.pins.get(e)??0)+1);let t=!1;return()=>{if(t)throw Error(`render-cache pin released twice`);t=!0;let n=(this.pins.get(e)??0)-1;n>0?this.pins.set(e,n):this.pins.delete(e)}}viewOf(e,t,n,r){let{sessionId:i}=n,a=this.views.get(i);if(a?.state===t)return this.views.delete(i),this.views.set(i,a),a.requested(n),a;this.views.delete(i);let o=a!==void 0&&this.leaseOf(a).read,s;try{s=this.opened(e,t,n,o,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),s}opened(e,t,n,r,i){let{sessionId:a}=n,o;try{o=jZ(t,e.cwd,n,{sessionState:this.deps.sessionState,declare:this.deps.declare,source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(a,{error:e,facts:n}),e}return this.openFailures.delete(a),this.views.set(a,o),this.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}leaseOf(e){let t=this.viewHolds.get(e);if(t===void 0)throw Error(`render-cache view never served`);return t}retireView(e,t){this.views.get(e.sessionId)===e&&this.views.delete(e.sessionId),e.retire();let n=this.leaseOf(e);n.retired={reason:t,held:n.holders},this.reclaimView(e,n)}reclaimView(e,t){t.retired===null||t.holders>0||(this.viewHolds.delete(e),this.log(`info`,`session view closed sid=${JSON.stringify(e.sessionId)} reason=${t.retired.reason} released=${e.dispose()} held=${t.retired.held} views=${this.views.size}`))}armSweep(){this.sweep===null&&(this.sweep=setInterval(()=>this.releaseIdle(),15e4),this.sweep.unref?.())}releaseIdle(){for(let[e,t]of this.viewHolds)t.retired!==null||this.pins.has(e.sessionId)||(t.read?t.read=!1:this.retireView(e,`idle`));for(let e of this.openFailures.keys())this.pins.has(e)||this.openFailures.delete(e);this.entries.size===0&&this.sweep!==null&&(clearInterval(this.sweep),this.sweep=null)}close(){if(this.closed)return;this.closed=!0,this.sweep!==null&&clearInterval(this.sweep),this.sweep=null;let e=this.entries.size;for(let[e,t]of this.entries)this.drop(e,t,`close`);this.log(`info`,`render-cache closed entries=${e} deferred=${this.stats.retired}`)}load(e,t,n){if(this.closed)throw Error(`render cache used after close`);return DZ(e,t,n,this.deps)}drop(e,t,n){t.watcher?.release(),this.entries.delete(e),this.retire(t.state,n,null)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;let n=0;for(let e of this.viewHolds.values())e.retired!==null&&n++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,views:this.views.size,pinned:this.pins.size,retiredViews:n,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes(),n=new Set([...this.pins.keys()].flatMap(e=>{let t=this.views.get(e);return t===void 0?[]:[t.state]}));for(let[r,i]of this.entries){if(t())return;i===e||n.has(i.state)||this.drop(r,i,`evict`)}t()||this.log(`warn`,`render-cache over budget entries=${this.entries.size} views=${this.views.size} pinned=${n.size} accounted=${tr(this.accountedBytes())}/${tr(this.budgetBytes())}MB`)}serve(e){let t=this.compiles.get(e.compileKey);if(t!==void 0&&t!==e.compiled)throw Error(`render cache: a second compile for key ${e.compileKey.slice(0,12)}`);this.holds.set(e,{holders:0,retired:null}),this.compiles.set(e.compileKey,e.compiled),t===void 0&&this.log(`info`,`render-cache compile built key=${e.compileKey.slice(0,12)} compiles=${this.compiles.size}`)}holdOf(e){let t=this.holds.get(e);if(t===void 0)throw Error(`render-cache state never served`);return t}retire(e,t,n){for(let r of[...this.views.values()])if(r.state===e){if(n!==null)try{this.opened(n.entry,n.state,r.facts(),this.leaseOf(r).read,`reload`)}catch(e){this.log(`error`,`session view reopen failed sid=${JSON.stringify(r.sessionId)}: ${String(e)}`)}this.retireView(r,t)}let r=this.holdOf(e);r.retired={reason:t,held:r.holders},this.reclaim(e,r)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,bZ(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}sessionsOn(e){return[...this.views.values()].filter(t=>t.state===e.state).map(e=>e.sessionId)}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=this.sessionsOn(e),n=this.load(e.projectDir,e.cwd,e.configFile);if(e.lastWarning=n.warning,e.lastError=n.error,n.state!==null){this.log(`info`,yZ(n.layers,n.state));let t=e.state;e.state=n.state,this.serve(n.state),this.retire(t,`reload`,{entry:e,state:n.state})}this.fit(e),this.refreshWatcher(e,n),this.observers.onReload?.(e,t)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=CZ(e,t.layers),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){this.log(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}latestView(){return[...this.views.values()].at(-1)??null}};const NZ=16384;var PZ=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<NZ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%NZ}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e().snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,handlerProbes:[],clients:[],bundle:`/`,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:Ze,sourceDigest:et(),protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};function FZ(e,t,n){let r=(r,i,a)=>{let o=i.filter(t).map(t=>({key:t,before:e.get(r,t)}));a();for(let{key:t,before:i}of o)n(r,t,i,e.get(r,t))};return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(t,n,i)=>r(t,[n],()=>e.set(t,n,i)),setBatch:(t,n)=>r(t,n.map(e=>e.key),()=>e.setBatch(t,n)),clear:(t,n)=>r(t,[n],()=>e.clear(t,n))}}const IZ={load:()=>({}),save:()=>{},flush:()=>{}};var LZ=class{sessions;storage;head=0;atom=(0,J.createAtom)(`SessionState`);constructor(e=IZ,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}observers(){return this.atom.observers_?.size??0}latestRevision(){return this.head}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,J.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t.some(({key:e,value:t})=>n.values.get(e)!==t)&&(n.revision=++this.head);for(let{key:e,value:r}of t)n.values.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,J.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.values.delete(t)&&(n.revision=++this.head),n.values.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,J.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function RZ(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e)){if(typeof t!=`object`||!t||Array.isArray(t))return!1;for(let e of Object.values(t))if(typeof e!=`string`)return!1}return!0}var zZ=class{timer=null;pending=null;constructor(e,t=500,n=Me){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=p.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return RZ(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;p.writeFileSync(t,JSON.stringify(e),{mode:384}),p.chmodSync(t,384),p.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const BZ=new Set([`1`,`true`]),VZ=new Set([`0`,`false`,``]);function HZ(e,t){let n=pQ(e),r=n.scope===`segment-palette`?`string`:yy(n.field);if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if(BZ.has(t))return`true`;if(VZ.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function UZ(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function WZ(e,t,n){try{if(t===null){p.rmSync(_t(e),{force:!0});return}gt(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function GZ(e){return/^\s*$/.test(e)?null:Ui(e)}function KZ(e,t){return e!==null&&Gi(e,t)!==void 0}function qZ(e){if(e.kind===`segment`)return e.when===void 0?e.name:{seg:e.name,when:e.when};if(e.kind===`container`){let{kind:t,direction:n,children:r,...i}=e;return{[n===`horizontal`?`h`:`v`]:r.map(qZ),...i}}return e}function JZ(e){if(!Hb(e))return qZ(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,qZ(t)])),...n}}const YZ=wH,XZ=YZ.segments,ZZ=YZ.presets,QZ=YZ.root;function $Z(e,t,n,r){if(!KZ(e,t)&&n===void 0)throw new q(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function eQ(e,t){let n=_j(t);return t.scope===`segment-palette`&&$Z(e,[`segments`,t.segment],XZ[t.segment],n.join(`.`)),n}function tQ(e){return Ui($i(e))}function nQ(){return Object.entries(QZ.rows).map(([e,t])=>{let n=qZ(t);return{path:[`root`],fragment:tQ({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function rQ(e,t){let n=e===null?void 0:Gi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function iQ(e,t){if(t===void 0)return null;let n=JZ(t);return{path:e,fragment:tQ(n),unit:{path:e,value:n}}}function aQ(e,t){let n=[`presets`,t],r=[...n,`root`],i=ZZ[t];$Z(e,n,i,r.join(`.`));let a=rQ(e,r)??iQ(r,i?.root);return a!==null&&ba(a.fragment)?a:null}function oQ(e,t){let n=ya(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function sQ(e,t){return[...nQ(),rQ(e,[`root`]),aQ(e,t)].filter(e=>e!==null).reduce(oQ,new Map)}function cQ(e,t,n){for(let{node:r,...i}of sQ(e,t).values())if(Sa(r,n))return i;throw new q(`${lQ(e,t).join(`.`)} holds no placement "${n}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`)}function lQ(e,t){return aQ(e,t)?.path??[`root`]}function uQ(e,t){return t.scope===`preset-root`?lQ(e,t.preset):_j(t)}function dQ(e,{unit:t}){return t===null?e:pa(e,t.path,$i(t.value),Zi)}function fQ(e){let t=gj(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function pQ(e){let t=fQ(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function mQ(e,t,n,r,i){i(t,n,TQ(t,r)),WZ(t.path,r,e.logger),e.record(t.path,n,r)}function hQ(e,t,n){let r=vQ(e,t,n);if(r.length>0)throw new q(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const gQ=()=>{};function _Q(e,t){try{return t()}catch(t){throw!(t instanceof q)||e.above.length===0?t:new q(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function vQ(e,t,n){let r=yQ(e,t);if(r===null)return[];let i=new Set(CQ(SQ(r),SQ(n)));return CQ(xQ(e,r),xQ(e,n)).filter(e=>!i.has(e))}function yQ(e,t){try{return bQ(e,t)}catch(e){if(e instanceof Z_)return null;throw e}}function bQ(e,t){return rH(t===null?e.above:[e.path,...e.above],EH,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function xQ(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function SQ(e){return e.layers.at(-1)?.config??e.base}function CQ(e,t,n=``){return!wQ(e)||!wQ(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>CQ(e[r],t[r],n===``?r:`${n}.${r}`))}function wQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function TQ(e,t){try{return bQ(e,t)}catch(e){throw e instanceof Z_?new q(`refused: the config file would not load after this click — ${e.message}`):e}}function EQ(e,t){let n=pQ(t),r=GZ(UZ(e)??``),i=r===null?void 0:Gi(r,_j(n));return i!==void 0&&`value`in i?i.value:void 0}function DQ(e,t,n){OQ(e,t,n,[])}function OQ(e,t,n,r){let i=UZ(t.path),a=n.reduce((e,[t,n])=>pa(e,eQ(GZ(e),pQ(t)),HZ(t,n),Zi),i??``);mQ(e,t,i,_Q(t,()=>kQ(a,t.path,r,e=>e)),hQ)}function kQ(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=cQ(GZ(s),n,i),l=Ea(dQ(s,c),c.path,i,a,$i(o));if(l===null)throw new q(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function AQ(e,t,n){let r=GZ(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of sQ(r,t)){if(!Sa(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?qi(e,c):$i(s.value);if(a!==`#`)return pa(e,[...i,`rows`,a],l,Zi);if(aQ(r,t)!==null)throw new q(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return pa(e,i,l,Zi)}return e}function jQ(e,t){return ha(e,t,t[0]===`presets`&&t.length>2&&!OH(t[1])?2:0)}function MQ(e,t,n){let r=n.map(fQ),i=UZ(t.path);if(i===null)return;let a=r.reduce((e,t)=>jQ(e,uQ(GZ(e),t)),i);a!==i&&mQ(e,t,i,a,gQ)}function NQ(e){let t=e===null?void 0:Gi(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function PQ(e,t){let n=new Set([...DH,...NQ(e),...t.above.flatMap(e=>Object.keys(Ii.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(fA));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(fA(e)))}function FQ(e,t,n,r,i,a){let o=UZ(t.path),s=GZ(o??``),c=PQ(s,t),l=[`presets`,c],u=_Q(t,()=>aQ(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?qi(o??``,u.fragment):$i(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],$i(r)]]],f=i.map(([e,t])=>{let n=hj(c,e);return[eQ(s,pQ(n)),HZ(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>pa(e,t,n,Zi),pa(o??``,l,`{}`,Zi));return mQ(e,t,o,_Q(t,()=>kQ(p,t.path,a.map(e=>({...e,preset:c})),AQ)),hQ),c}function IQ(e,t,n,r){let i=UZ(t.path);mQ(e,t,i,pa(i??``,[`themeDefaults`,n],$i(r),Zi),hQ)}function LQ(e,t,n){if(OH(n))throw new q(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=UZ(t.path),a=GZ(i??``);if(i===null||a===null||Gi(a,r)===void 0)throw new q(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Gi(a,[`globals`,`preset`]);mQ(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>jQ(e,t),i),gQ)}function RQ(e,t,n,r){let i=fQ(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=UZ(t.path),o=r.op===`remove`?r.target:r.anchor,s=_Q(t,()=>cQ(GZ(a??``),i.preset,o)),c=dQ(a??``,s),{after:l,placed:u}=zQ(c,s.path,r,()=>{let e=TQ(t,c).config;return Qb(e.presets).map(t=>tx(e,t).node)});if(l===null)throw new q(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return mQ(e,t,a,l,hQ),u}function zQ(e,t,n,r){switch(n.op){case`remove`:return{after:wa(e,t,n.target),placed:null};case`insert`:{let i=PI(n.segment,n.anchor,r());return{after:Ta(e,t,i,n.anchor,n.relation),placed:i}}}}const BQ={load:()=>({}),save:()=>{}},VQ=new Set(wy.map(e=>e.sessionKey)),HQ=e=>VQ.has(e)||e.startsWith(kj),UQ=8*1024*1024,WQ={past:[],future:[]},GQ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var KQ=class{held=J.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,J.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=BQ){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}useStorage(e){this.storage=e,this.state=new Map(Object.entries(e.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??WQ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??WQ}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(GQ(n));r.set(GQ(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:FZ(this.sessionState,e=>HQ(e)||e===`edit.mode`,(e,r,i,a)=>{if(r===`edit.mode`){let t=n.get(e);n.set(e,{before:t===void 0?i:t.before,after:a});return}t(e,{kind:`session`,key:r,before:i,after:a})}),file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=new Map(e),r=new Map(n);e.clear(),n.clear();for(let e of new Set([...t.keys(),...r.keys()])){let n=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=n.length===0?i:e$(i,n),o=r.get(e),s=o===void 0?a:i$(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new q(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,n$(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new q(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(GQ)),a=n.net.filter(e=>!i.has(GQ(e))),o=YQ(a$(r$(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new q(`rewind: ${r.map(s$).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new q(`redo: nothing to redo`);let a=[...n,i],o=YQ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...ZQ(t.savepoint,a.length-o.length,i)}),i}apply(e,t,n,r,i){let a=n===`before`?`after`:`before`,o=t.filter(t=>this.read(e,t)!==t[a]);if(o.length>0){let t=new Set(o.map(GQ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:a$(n,t),future:a$(i,t),...a!==void 0&&{savepoint:{at:a$([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(GQ(e))),below:a$(a.below,t)}}}),new q(`${r}: ${o.map(s$).join(`, `)} changed since that edit — refusing to overwrite it; this session's undo history no longer steps it`)}let s=[];try{for(let r of t)this.write(e,r,r[n]),s.push(r);this.put(e,i)}catch(t){try{for(let t of s.reverse())this.write(e,t,t[a])}catch(e){throw Error(`${t.message}; and putting the step back failed, so it is half-applied: ${e.message}`)}throw t}}read(e,t){return t.kind===`session`?this.sessionState.get(e,t.key):UZ(t.file)}write(e,t,n){t.kind===`file`?WZ(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||qQ(n)>UQ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,JQ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${UQ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function qQ(e){let t=0;for(let{past:n,future:r,savepoint:i}of e.values())for(let e of[...n,...r,...i===void 0?[]:[i.net,...i.below]])for(let n of e)t+=(n.before?.length??0)+(n.after?.length??0);return t}function JQ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...ZQ(n,1,[])}:{past:e,future:t.slice(1),...ZQ(n,0,[])}}function YQ(e){return e.slice(-50)}const XQ=e=>e===jj.member;function ZQ(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:QQ(e.net,n),below:e.below}}}function QQ(e,t){let n=new Map(e.map(e=>[GQ(e),e]));for(let e of t){let t=n.get(GQ(e));n.set(GQ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const $Q=e=>e.map(e=>({...e,before:e.after,after:e.before}));function e$(e,t){let n=[...e.past,t],r=YQ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...ZQ(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...t$(e.future,a),...i.below]},n.length-r.length,t)}}function t$(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function n$(e,t){return{past:e.past.slice(0,-1),future:YQ([...e.future,t]),...ZQ(e.savepoint,0,$Q(t))}}function r$(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...t$(r,t.at-i.length),...t.below]}function i$(e,t){if(XQ(t.after)&&!XQ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!XQ(t.after)&&XQ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function a$(e,t){return e.map(e=>e.filter(e=>!t.has(GQ(e)))).filter(e=>e.length>0)}function o$(e){return e.map(s$).join(`, `)}function s$(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function c$(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function l$(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(c$))}function u$(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(c$)&&l$(t.below)}function d$(e){if(typeof e!=`object`||!e)return!1;let t=e;return l$(t.past)&&l$(t.future)&&(t.savepoint===void 0||u$(t.savepoint))}function f$(e,t){let n=e=>e.kind===`file`||HQ(e.key)?!0:(t.add(e.key),!1),r=e=>e.map(e=>e.filter(n)).filter(e=>e.length>0),{savepoint:i}=e,a=r(e.past),o=r(e.future);return i===void 0?{past:a,future:o}:{past:a,future:o,savepoint:{at:r(e.past.slice(0,i.at)).length,net:i.net.filter(n),below:r(i.below)}}}function p$(e,t){return{load:()=>{let n;try{n=p.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(d$)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,f$(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{p.mkdirSync(s.dirname(e),{recursive:!0}),gt(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const m$=e=>!HQ(e)&&!iP(e)&&e!==`update.dismissed`;var h$=class{past=J.observable.map(void 0,{deep:!1});depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:FZ(e,m$,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new q(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,J.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){(0,J.runInAction)(()=>{for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)})}};const g$={inside:()=>[],defaultOf:()=>yi,menus:[]},_$=e=>`${e.key}\0${e.member}`;function v$(e){let t=new Map,n=n=>{let r=`${n.name}\0${S_(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:YR(a,S_(n));return t.set(r,o),o},r=e=>[...e.opens===void 0?[]:[e.opens.ref],...n(e)],i=new Map,a=new Map;for(let t of Object.values(e.variables))t.kind===`state`&&(t.default!==void 0&&i.set(t.key,t.default),t.within!==void 0&&a.set(t.key,t.within));let o=new Map,s=new Map,c=new Map,l=e=>{s.set(e.key,(s.get(e.key)??new Set).add(e.member))},u=(e,t)=>{let n=o.get(_$(e))??new Map;n.set(_$(t),t),o.set(_$(e),n)},d=(e,t)=>{if(e.kind===`container`){for(let n of e.children)d(n,t);return}for(let n of r(e)){l(n),c.set(_$(n),n);for(let e of t)u(e,n)}e.opens!==void 0&&d(e.opens.body,[...t,e.opens.ref])};for(let t of Qb(e.presets))d(tx(e,t).node,[]);for(let t of Object.values(e.actions)){let e=ji(t);e!==void 0&&l(e)}for(let[e,t]of a)for(let n of s.get(e)??[])for(let r of t)u(r,{key:e,member:n});let f=new Map;return{inside:e=>{let t=f.get(_$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(_$(e))??[])n.has(t)||(n.set(t,i),r(i))};r(e);let i=new Map;for(let{key:e,member:t}of n.values())i.set(e,(i.get(e)??new Set).add(t));let a=[...i].map(([e,t])=>({key:e,outside:new Set([...s.get(e)].filter(e=>!t.has(e)))}));return f.set(_$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const y$=new WeakMap;function b$(e){let t=y$.get(e);if(t!==void 0)return t;let n=v$(e);return y$.set(e,n),n}function x$(e,t,n){let r=new Set(n.map(e=>e.key)),i=n=>t(n)??e.defaultOf(n),a=new Set;for(let{key:t,value:o}of n){let n=i(t);if(n!==o)for(let o of e.inside({key:t,member:n})){let t=i(o.key);t!==e.defaultOf(o.key)&&!o.outside.has(t)&&!r.has(o.key)&&a.add(o.key)}}return[...a]}function S$(e,t){let n=({key:n,member:r})=>(t(n)??e.defaultOf(n))===r,r=(t,n)=>e.inside(n).some(({key:e,outside:n})=>e===t.key&&!n.has(t.member));return e.menus.filter(n).filter(t=>{let i=e.menus.filter(e=>e!==t&&r(t,e)),a=i.length>0&&e.defaultOf(t.key)===t.member;return!i.some(n)&&!a})}function C$(e,t,n){let r=(r,i,a)=>{let o=x$(t(r),t=>e.get(r,t),i);(0,J.runInAction)(()=>{a();for(let t of o)e.clear(r,t)}),o.length>0&&n(`close-nested: folded=${o.join(`,`)} (session=${r})`)},i=(t,n)=>r(t,n,()=>e.setBatch(t,n));return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(e,t,n)=>i(e,[{key:t,value:n}]),setBatch:i,clear:(n,i)=>r(n,[{key:i,value:t(n).defaultOf(i)}],()=>e.clear(n,i))}}const w$=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function T$(e,t){let n={...e};for(let e of w$)delete n[e];return{...n,CLAUDE_CODE_SESSION_ID:t.sessionId,CLAUDE_PROJECT_DIR:t.projectDir,...t.claudeConfigDir!==void 0&&{CLAUDE_CONFIG_DIR:t.claudeConfigDir}}}function E$(e,t,n,r){let i=s.join(e,t),a=()=>{let e;try{e=p.readFileSync(i,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${i}: ${e.message}`}}let t;try{t=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${i} is not JSON: ${e.message}`}}let a=r(t);return a.kind===`ok`?a:{kind:`failed`,reason:`${i} ${a.reason}`}};return{read:a,update:e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return n!==t.value&&gt(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const D$=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function O$(e){let t=e=>({kind:`failed`,reason:e});if(!D$(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!D$(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!GM.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${GM.join(` or `)}`)}return{kind:`ok`,value:e}}function k$(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const A$=e=>E$(e,`doctor-marks.json`,{},O$),j$=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},M$=(e,t)=>e.includes(t)?e:[...e,t],N$=e=>E$(e,`doctor-clicked-terminals.json`,[],j$);var P$=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const F$=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},I$=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),L$=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=I$(e,t);return r===void 0?n:r.projectDir},R$=(e,t)=>I$(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function z$(e){let t=new Map;for(let n of e.split(`
201
- `)){let e=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(n);if(e===null)continue;let r=Number(e[1]);t.set(r,{pid:r,ppid:Number(e[2]),command:e[3].trim()})}return t}function*B$(e,t){let n=new Set;for(let r=e.get(t);r!==void 0&&!n.has(r.pid);)n.add(r.pid),yield r,r=e.get(r.ppid)}const V$={pullRequests:e=>Cq(e).showPullRequest===!0,rateLimits:e=>Sq(e,`block`)||Sq(e,`weekly`)};function H$(e,t){let n=new Map;for(let r of E_(tx(e,t).node)){if(r.kind!==`segment`)continue;let e=n.get(r.name)??[];r.when&&e.push(r.when),n.set(r.name,e)}let r=[...n.keys()].filter(t=>I_(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,yq(e,t,n.get(t))])),a=e=>r.filter(t=>V$[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}
198
+ `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function KY(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}const qY=e=>e.kind===`failed`?eJ:e;function JY(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function YY(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:n,opened:r.length>0,ground:i},deeper:r}}function XY(e){return{...e,cells:e.cells.map(oJ)}}function ZY(e,t){let n=t.flatMap(e=>e.filter(e=>e.place===`above`)),r=t.map(e=>e.filter(e=>e.place===`flow`));return[...n,...QY(e,r)]}function QY(e,t){switch(e){case`vertical`:return t.flatMap(e=>e);case`horizontal`:return t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`,place:`flow`},...t.flatMap(e=>e.slice(1))]}}function $Y(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:ZY(e.direction,e.children.map((t,i)=>n(t,[...r,eX(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function eX(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:x_[e.direction]}}const tX={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:kh(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,D_(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),ZY(e.direction,e.children.map((n,r)=>t.renderChild(n,qY(t.gate),eX(e,r))))}},nX={drop:e=>e.place,above:()=>`above`},rX={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},iX={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:S_(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Ti(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,O_(t.path)),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render:(e,t)=>t.placed(e.id,aX(e,t))};function aX(e,t){let n=t.lookupSegment(e.name);if(n===void 0)throw Error(`Layout segment "${e.name}" has no matching segment`);if(t.gate.kind===`hidden`)return[];let r=Ck(t.scope,e.settings);if(t.gate.kind===`failed`)return dX(e,r,t,t.gate.message);try{let i=t.placement(e),a=JY(t.gate,i.gate());if(a.kind===`failed`)return dX(e,r,t,a.message);if(a.kind===`hidden`)return[];let o=i.bodyGate(),s=o.kind===`failed`&&a.kind===`pending`?a:o;if(s.kind===`failed`)return dX(e,r,t,s.message);let c=Mb(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:Hj(c)},u=e=>({width:n.width??`auto`,justify:n.justify??`left`,truncate:n.truncate??`right`,baseStyle:e,padding:t.padding,placement:l}),d=s.kind===`shown`,f=a.kind===`pending`?a:s,p=f.kind===`pending`?oX(f.variable):sX(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?cX(p.segment,u):lX(e,r,t,p.variable,c,d,u);if(m===null)return[];let{styles:h,inline:g,drops:_}=m,v=e.opens,y=v===void 0?[]:t.renderBody(v.body,d?a:eJ,h.disclosure).map(e=>({...e,place:nX[v.placement](e)})),b=(e,t,n)=>lJ(pJ([e],t),{...u(t),width:`auto`,padding:n}),ee=y.findIndex(e=>e.band===`own`),{lead:x,stays:S}=v!==void 0&&ee!==-1?rX[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},te=x.flatMap(e=>b(new W(` `.repeat(uX(aJ(e)))),h.trigger,0)),ne=(e,t)=>e.band===`own`?t===ee?x:te:[],re=y.map((e,t)=>({cells:[...ne(e,t),...e.cells],band:`deeper`,place:e.place})),ie=[...S,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ie.flatMap(e=>e.cells),...y.flatMap(ne)].flatMap(aJ)),[...ie,...re]}catch(n){return dX(e,r,t,n.message??String(n))}}const oX=e=>({kind:`waiting`,variable:e});function sX(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=tS(e);if(t===void 0)throw e;return oX(t.variable)}}function cX(e,t){let{styles:n,fragments:r,lead:i,trail:a,drops:o,open:s}=e,c=s?n.trigger:n.closed,l=t(c);return{styles:n,inline:GY(pJ(r,c)).map((e,t)=>({cells:lJ(e,{...l,lead:t===0?pJ(i,c):[],trail:t===0?pJ(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:lJ(pJ([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function lX(e,t,n,r,i,a,o){n.waited(r);let s=n.lastDrawn(e.id);if(s?.kind===`hidden`)return null;let c=n.decorations(e,i),l=a?c.trigger:c.closed,u=pJ(fX(e.lead,e,t,n),l),d=pJ(fX(e.trail,e,t,n),l);return{styles:c,inline:(s===void 0||s.drawing.own.length===0?[[`auto`]]:s.drawing.own.map(e=>e.cells.map(e=>e.text.cellLength))).map((e,t)=>({cells:e.flatMap((e,n)=>{let r=t===0&&n===0;return lJ(pJ([new W(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function uX(e){return e.reduce((e,t)=>e+t.cellLength,0)}function dX(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:lJ([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:Hj(n.palette)},lead:fX(e.lead,e,t,n),trail:fX(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function fX(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=tS(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const pX={container:tX,segment:iX};function mX(e){return pX[e]}var hX=class{last=null;from(e){let{last:t}=this;return t!==null&&t.source.config===e.config&&t.source.preset===e.preset&&t.source.revision===e.revision&&t.source.width===e.width?t:null}begin(e,t){let n=new Map,r=new Map;return{placed:(e,r)=>{let{drawing:i}=t(e,r);return n.set(e,i===null?gX:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const gX={kind:`hidden`},_X={palette:`theme`,style:`style`,effect:`effect`},vX=Dy.get(`colorCompatibility`),yX={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function bX(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function xX(e){if(e.ok)return e.value;throw e.error}const SX=e=>({read:()=>e}),CX=fh({basePalette:dh,palette:dh,decor:Eg});var wX=class{evaluated=0;memory=new hX;scope;binding;facts;look=J.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&CX(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=J.observable.box(r,{deep:!1}),this.scope=xk(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(vX);return typeof e==`string`&&u_(e)?e:`truecolor`});let i=(0,J.observable)(yX,void 0,{deep:!1});this.facts=i;let a=this.look,o=this.phase,s=()=>this.layout.read();this.binding={store:e,registry:t,get width(){return i.width},get chromeCols(){return i.chromeCols},get padding(){return i.padding},get seamCols(){return i.seamCols},get look(){return o.ruling?void 0:a.get()},get layout(){return o.ruling?void 0:s}},this.layout=this.derive(`layout`,n.layoutReadsInstant,()=>{let e=n.roots.get(i.preset),t=a.get().palette;return $Y(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=EI(e);return i===void 0?[]:[{name:i,address:n,palette:Mb(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>d_(this.colorCompatibility())})}bind(e){(0,J.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,J.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=lA(e);return t===void 0?sA(e)===void 0?Xk(this.view.get().payload(),e):Xk(this.projected,e):this.slotName(t)}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[_X[e]];if(t.kind===`decided`)return DX(t.name,null,null);let r=kX(this.source,e,t.source);if(this.source.instant.has(r.template))return{kind:`per-draw`,rule:r};let i=this.rule(r.template);switch(i.kind){case`named`:{let t=null;return n=AX(this.source,e,i.name,r.where,e=>{t=e}),DX(n,t,null)}case`pending`:return DX(n??Zg[e],null,i.variable);case`failed`:return n=Zg[e],DX(n,Qg(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!OX(i,e))&&(i=e),i}),this.slots.set(e,t)}return t.read()}slotName(e){let t=this.slot(e);return t.kind===`settled`?t.name:this.drawnSlots.get(e)??Zg[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,J.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return nJ(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>$J(this.source.activeSegment,()=>nJ(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new jX(this,e),this.placements.set(e,t)),t}rule(e){let t=this.rules.get(e);return t===void 0&&(t=this.derive(`rule`,this.readsInstant(e),()=>{this.phase.ruling=!0;let t=this.source.runtime.bound===this.binding?null:yJ(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=tS(e);return t===void 0?{kind:`failed`,error:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}finally{t?.[Symbol.dispose](),this.phase.ruling=!1}}),this.rules.set(e,t)),t.read()}readsInstant(...e){return e.some(e=>e!==void 0&&this.source.instant.has(e))}derive(e,t,n){let r=()=>(this.evaluated++,n());return this.store.derive(`part ${e}`,t?`projection`:`computed`,t?this.oncePerDraw(r):r)}oncePerDraw(e){let t=null;return()=>(t?.draw!==this.draws&&(t={draw:this.draws,answer:bX(e)}),xX(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:EI(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function TX(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new wX(t,n,e,r);return e.views.set(t,a),a}function EX(e,t){let n=e.views.get(t);if(n===void 0)throw Error(`a store was drawn before its view was bound (bindView): its inputs have no source`);return n}const DX=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),OX=(e,t)=>e.kind===`settled`?t.kind===`settled`&&e.name===t.name&&e.warning===t.warning&&e.waited===t.waited:t.kind===`per-draw`&&e.rule===t.rule;function kX(e,t,n){let r=e.globalExpressions.get(t)?.get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the view but no compiled template exists — the compile and the resolution disagree about isExpression`);return r}function AX(e,t,n,r,i){switch(t){case`palette`:return Lb(n,r,i).name;case`style`:return Jg(n,e.styles).name;case`effect`:return i_(n).name}}var jX=class{where=MX(fh({palette:dh,region:wg}));ground=MX(fh({colours:PX,bodyOpen:dh}));opened=MX(fh({colours:PX,open:dh}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=Ck(e.scope,t.settings),{when:a,bg:o,fg:s,template:c}=n,{lead:l,trail:u}=t,d=t.opens?.open;this.ownGate=a===void 0?SX(tJ):e.derive(`${t.id} when`,e.readsInstant(a),()=>$J(r,()=>nJ(a,i))),this.open=d===void 0?SX(eJ):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>$J(r,()=>nJ(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return LX(r,t,n,a,e.registry.drawnAt(),o,s,i)}),this.body=e.derive(`${t.id} body`,e.readsInstant(c),()=>{let{colours:e,bodyOpen:n}=this.ground.get();return RX(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?SX(BX):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return zX(r,t,e,n,l,u,i)})}gate(){return this.ownGate.read()}bodyGate(){return this.open.read()}evaluate(e,t){this.where.set({palette:e,region:t});let n=this.colours.read();this.ground.set({colours:n,bodyOpen:this.open.read().kind===`shown`});let r=this.body.read();return this.opened.set({colours:n,open:r.open}),HX(n,r,this.affixes.read())}};function MX(e){let t=J.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,J.runInAction)(()=>t.set(e)),get:()=>t.get()}}const NX=(e,t)=>e.hex===t.hex,PX=fh({palette:dh,drawnAt:dh,tint:NX,text:NX,bg:NX,disclosure:Dg});function FX(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const IX=e=>ug(e.palette,e.disclosure,e.drawnAt);function LX(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Ng(n,r,i)};return QJ(e,FX(t,c),e=>{let t=Wj(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function RX(e,t,n,r,i,a){return QJ(e,FX(t,n),e=>(e.bg=i?IX(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function zX(e,t,n,r,i,a,o){return QJ(e,FX(t,n),e=>(e.bg=r?IX(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const BX={lead:[],trail:[],drops:[]};function VX(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return FJ(t,IX(e).state,n)},get band(){return FJ(t,IX(e).plane,n)},get close(){return RJ(t,IX(e).state,n)},disclosure:r}}function HX(e,t,n){return{styles:VX(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open,shortfalls:t.open?IX(e).shortfalls:[]}}function UX(e,t,n,r,i,a,o){let s=LX(e,t,n,r,i,void 0,void 0,o);return HX(s,RX(e,t,s,a,!1,o),BX)}function WX(e,t,n,r,i){return VX(LX(e,t,n,r,i,void 0,void 0,{}))}function GX(e,t){return{payload:()=>e,selections:()=>t}}function KX(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Ik(e.ttl)};if(`watch_file`in e)return{kind:`watch_file`,path:e.watch_file};if(`depends_on`in e)return{kind:`depends_on`,varNames:e.depends_on};if(`key`in e)return{kind:`key`,template:e.key};if(`never`in e)return{kind:`never`};throw Error(`Unknown CacheDecl discriminator — loader invariant violated: ${JSON.stringify(e)}`)}function qX(e,t){switch(j_(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,regex:new RegExp(e.regex),default:t};case`text`:return{kind:`text`,default:t}}}function JX(e,t,n,r,i){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`source`:e.declareSourceDocument(t);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default,i);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:KX(n.cache),parse:qX(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:KX(n.cache),parse:qX(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{type:n.type??`string`,varDefault:n.default,derivation:i});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function YX(e,t){let n=US.EMPTY;for(let[r,i]of Object.entries(t))try{n=e.parse(`{{ define "${r}" }}${i}{{ end }}`,n).defines()}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}return n}function XX(e,t,n){let{compiled:r,loadWarnings:i}=QX(e,t,n.cwd,ZX(n.signer),nZ);return{...r,loadWarnings:i}}const ZX=e=>(t,n)=>rZ(n,e);function QX(e,t,n,r,i=nZ){let a=$X(e),o=eZ(a);return{compiled:r(o,a),compileKey:o,loadWarnings:tZ(e,t,n,i)}}function $X(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of Oy)n in t&&r.set(e,n);for(let[t,n]of L_(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...uB(e)].sort(([e],[t])=>e<t?-1:1)}}function eZ(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function tZ(e,t,n,r){let i=UY(e),a=uB(e),o=[];for(let[s,c]of Bx(e))if(r.has(i.get(s)))try{JX(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const nZ=new Set([`directory`,`view`]);function rZ({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>gJ(i,`drawnAt`).registry.drawnAt(),o=XJ(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=$b(e.presets),u=hI(e),d=[e=>bY(i,o,e.now)],f=bk({extraFuncs:{...NJ(i),...yY(i),...dY(i,o),...hY(i,o),...TY(i,o),...jY(i,o),...FY(s),...RY(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=YX(f,e.helpers),m=new Map,h=e=>{let t=f.parse(e,p);return m.set(t,e),t},g=new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n=h(e);return g.set(e,n),n},v=new Map(t);i.compiled=bJ(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=h)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:e(n.when,`when`,_),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let b=(e,t,n)=>{try{return _(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},ee=t=>{let n=V_(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>q_(t,e,a,t=>String(gJ(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},x=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:x,placementSettings:ee};return mX(e.kind).compile(e,n)},S=new Map;for(let t of l){let{node:n,path:r}=nx(e,t);S.set(t,x(n,r))}let te=new Map(Ug.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of fB(e)){let e=t.join(`.`),i=te.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:oZ(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let ne={reads:nB({names:new Set(n.map(([e])=>e)),helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:_k(d)},re=hB(ne),ie=[...S.values()].flatMap(aZ(y)).some(e=>re(m.get(e))),ae=ie?hB({...ne,clock:new Set([...ne.clock,AY])}):re;return{segments:y,roots:S,activeSegment:o,menuRuntime:s,globalExpressions:te,instant:new Set([...m].flatMap(([e,t])=>ae(t)?[e]:[])),layoutReadsInstant:ie,styles:e.styles,runtime:i,views:new WeakMap}}function iZ(e){return Object.entries(e.segments).flatMap(([t,n])=>[n.when,n.bg,n.fg,n.template].some(t=>t!==void 0&&e.instant.has(t))?[t]:[])}const aZ=e=>t=>{let n=[];return $Y(t,e=>(n.push(e),!0)),n.flatMap(t=>[...t.when===void 0?[]:[t.when],...t.kind===`segment`&&e[t.name].when!==void 0?[e[t.name].when]:[]])};function oZ(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}const sZ=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function cZ(e,t,n,r,i){let a=lZ(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function lZ(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??Zg[e];case`failed`:return r({kind:`rule`,slot:e,message:Qg(t.where,e,`the rule failed — ${n.error}`)}),Zg[e]}}function uZ(e){return dZ(e).filter(e=>!e.name.startsWith(_A)).map(e=>e.id)}function dZ(e){return e.kind===`container`?e.children.flatMap(dZ):[e,...e.opens===void 0?[]:dZ(e.opens.body)]}function fZ(e,t,n,r,i,a,o,s,c=LH(e,()=>null,()=>!1)){let l={...i,term:{cols:o.width},colorCompatibility:{effective:o.colorCompatibility}};return TX(t,n,r,GX(l,c)),mZ(e,t,n,r,l,a,o,s,c)}function pZ(...e){return fZ(...e).text}function mZ(e,t,n,r,i,a,o,s,c){try{var l=Aa();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=new Set,h=c.effects??new $y(``),g=h.clockAt(a,e_[c.animationSpeed]);l.u(ck(a,g.anim));let _=EX(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:sb(v),padding:v.padding,seamCols:cb(v),preset:c.preset},i);let y=_.evaluated;l.u(yJ(t.menuRuntime.action,_.binding));let{preset:b,transitions:ee}=c,x={variation:Ch[c.variation],shade:xh[c.shade]},S={config:e,preset:b,revision:r.stateRevision(),width:v.width},te=_.memory.begin(S,YY),ne=_.memory.from(S),re=new Set,ie={held:e=>ne?.rules.get(e),waited:e=>re.add(e),settled:te.rule},ae=new Map,C=e=>{let n=_.slot(e);if(ae.set(e,n.kind===`settled`?`kept`:`per-draw`),n.kind===`settled`)return n.warning!==null&&p({kind:`rule`,slot:e,message:n.warning}),n.waited!==null&&re.add(n.waited),n.name;let r=AX(t,e,cZ(e,n.rule,_,p,ie),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:w,style:oe,effect:se}=_.selections(),T=w.kind===`decided`?w:Lb(C(`palette`),``,sZ),ce=oe.kind===`decided`?oe:Jg(C(`style`),e.styles),le=se.kind===`decided`?se:i_(C(`effect`)),ue=T.value,de=Pb(ue,ce.value);_.publishLook({basePalette:ue,palette:de,decor:x});let fe=c.idleSince===void 0?null:Jv(c.idleSince,c.menuTimeout,a),pe=Bh(de,`warning`),me=fe===null?null:{t:fe,fill:pe,text:Xh(de,pe,r.drawnAt())},he=h.motion(le.value,g,{transitions:ee,source:S,last:ne,returned:YY,hold:XY},me);u?.clear();let ge=t=>e.segments[t],_e=e=>{for(let t of e.shortfalls)m.add(t);return e},ve=e=>{let t=_.placement(e);return{gate:()=>t.gate(),bodyGate:()=>t.bodyGate(),evaluate:(e,n)=>_e(t.evaluate(e,n))}},ye=(e,i,a)=>{let o=i.kind===`hidden`?i:JY(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${uZ(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:o.message,message:`${t}: ${o.message} — what it gates is hidden`})}}:o,c={scope:_.scope,palette:de,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:ve,evaluateOnce:(e,n,i,o)=>_e(UX(t.activeSegment,e,i,a,r.drawnAt(),o,n)),lookupSegment:ge,renderChild:(e,t,n)=>ye(e,t,jg(a,n)),renderBody:(e,t,n)=>ye(e,t,Mg(n)),closeDisclosure:e=>PJ(n,e),placed:(e,t)=>te.placed(e,he.placed(e,t)),lastDrawn:e=>ne?.placements.get(e),waited:e=>re.add(e),decorations:(e,n)=>WX(t.activeSegment,e,n,a,r.drawnAt())};return mX(e.kind).render(e,c)},be=t.roots.get(b);if(be===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${Zb}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let xe=KY(ye(be,tJ,Ag(x))).map(({line:e,row:t})=>{let n=fJ(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,...fb(n.map(e=>e.owner),v,he.row(t,r,n))}});he.drawn(),te.commit();let Se=xe.filter(e=>e.kind===`menu`).length,Ce=xe.some(e=>e.moves)?`moves`:Se>0||_.selections().effect.kind===`expression`||ee||dZ(be).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`)?`can-move`:`still`;for(let e of m)p({kind:`band-floor`,message:e});for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{text:xe.map(e=>e.text).join(`
199
+ `),motion:Ce,menuRows:Se,evaluated:_.evaluated-y,pending:[...re].sort(),rules:ae}}catch(e){l.e=e}finally{l.d()}}function*hZ(e){yield*Object.entries(e.variables??{});for(let[t,n]of Object.entries(e.segments??{}))for(let[e,r]of Object.entries(n.vars??{}))yield[`${t}.${e}`,r]}function*gZ(e){for(let t of Object.values(e.segments))for(let e of[t.template,t.bg,t.fg,t.when])e!==void 0&&(yield e);for(let t of $b(e.presets)){for(let n of E_(nx(e,t).node))n.when!==void 0&&(yield n.when);let n=rx(e,t);for(let e of Ug){let t=n[e];Wg(t)&&(yield t)}}for(let[,t]of hZ(e))for(let[,e]of P_(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of mx(t))yield e}function _Z(e,t){let n=oB(t),r=new Set,i=new Set,a=new Set;for(let e of gZ(t)){for(let{reaches:t}of n.ofTemplate(e))for(let e of t)r.add(e);for(let{name:n}of Mx(e,t.helpers))i.add(n);for(let n of Lx(e,t.helpers))a.add(n)}for(let[,e]of hZ(t))for(let{reaches:t}of n.ofVariable(e))for(let e of t)r.add(e);let o=new Set(i);for(let e of i){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)o.add(e)}let s=new Set,c=new Set;for(let e of o){let n=t.actions[e];if(n!==void 0&&(`set`in n&&s.add(n.set),`insertSegment`in n&&c.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)c.add(e)}for(let e of $b(t.presets))for(let n of E_(nx(t,e).node))n.kind===`segment`&&c.add(n.name);let l=(e,t)=>r.has(e)||t.kind===`state`&&s.has(t.key),u=e=>[...e].filter(e=>!yA(e)),d=(e,t,n)=>u(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),f=new Map(hZ(e));return[...d(`variable`,f.keys(),e=>l(e,f.get(e))),...d(`action`,Object.keys(e.actions??{}),e=>o.has(e)),...d(`helper`,Object.keys(e.helpers??{}),e=>a.has(e)),...d(`segment`,Object.keys(e.segments??{}),e=>c.has(e))]}var vZ=class{held=new Map;declaring=null;closed=!1;take(e,t){if(this.closed)throw Error(`hold taken after close: ${e}`);this.declaring?.taken.add(e),!this.held.has(e)&&(this.held.set(e,t()),this.declaring!==null&&this.declaring.acquired++)}declare(e){if(this.declaring!==null)throw Error(`declaration within one`);let t={taken:new Set,acquired:0};this.declaring=t;let n;try{n=e()}finally{this.declaring=null}let r=0;for(let[e,n]of this.held)t.taken.has(e)||(this.held.delete(e),n(),r++);return{result:n,acquired:t.acquired,released:r}}close(){this.closed=!0;let e=this.held.size;for(let e of this.held.values())e();return this.held.clear(),e}get size(){return this.held.size}};function yZ(e){return Math.floor(Math.max(e/4,e*or-67108864))}const bZ={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function xZ(e,{plugins:t,config:n,compiled:r}){let{checkout:i,loaded:a,dropped:o,unreached:s}=t,c=i===null?`-`:`${i.git?`git`:`dir`}:${i.root}`,l=e=>{let t=tV(e),r=t===void 0?void 0:n.variables[rV(t)];return r?.kind===`file`?r.path:`none`},u=a.flatMap(e=>{let t=tV(e);return t===void 0?[]:[t]}).flatMap(e=>Object.entries(n.variables).filter(([t])=>lV(e)(t)&&t!==rV(e))),d=u.filter(([,e])=>e.kind===`source`).length,f=u.length-d;return`config load ${e.join(` < `)||`<default>`}: projections=${[...uB(n).keys()].join(`,`)||`-`} instantSegments=${iZ(r).join(`,`)||`-`} instantTemplates=${r.instant.size} plugins loaded=${a.length} sources=${d} pluginVariables=${f} dropped=${o.length} unplaced=${s.length} checkout=${c}`+a.map(e=>` +${e} data=${l(e)}`).join(``)+o.map(e=>` -${e.path} (${e.reason})`).join(``)+s.map(e=>` ~${e.path} (${e.reason})`).join(``)}function SZ(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function CZ(e,t,n){return e+`\0`+t+`\0`+(n??``)}function wZ(e,t){return new Set($b(e.presets).filter(n=>nx(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function TZ(e,t){let n=new Map,{roots:r,loaded:i,dropped:a,unreached:o}=e.state.plugins;for(let t of[...WV(e.projectDir,e.cwd,e.configFile),...r,...i,...[...a,...o].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))]){let{dir:e,name:r}=Gx(t),i=n.has(e)?n.get(e):new Set;i?.add(r),n.set(e,i)}for(let e of r){let{dir:t,name:r,leaf:i}=Gx(s.join(e,`_`));i&&r===`_`&&n.set(t,null)}return{files:t,dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})}}function EZ(e){return e.filter(Boolean).join(`
200
+ `)||null}function DZ(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=aH(t.layers,OH,{entered:i,warned:e=>n.push(...e)},{projectDir:t.projectDir,cwd:e});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??OH,l=a.find(e=>e.path===t.home)?.raw??{},u=new mS,d=new eA(u,o.globals.default_empty_value??``,r.sessionState,null,r.ledger),f,p;try{f=QX(o,d,e,r.compile??ZX(r.signer),jZ),n.push(...f.loadWarnings);let t=d.view();n.push(...tZ(o,t,e,MZ)),t.dispose(),yU(o),YI(o),p=OZ(o,r.storage,d)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:Cq(o),authoredRoots:wZ(c,l),fileHeldSettings:aU(l),configPath:t.layers.includes(t.home)?t.home:null,unused:[...new Map(a.flatMap(e=>_Z(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{checkout:s.checkout,roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering},sources:p}}function OZ(e,t,n){let r=new Map,i=new Map;for(let[a,o]of Object.entries(e.variables)){if(o.kind!==`source`)continue;let e=r.get(o.storage);e===void 0&&(e=t.keyFor(o.storage),r.set(o.storage,e),n.own(t.watch(e))),i.set(a,e)}return i}function kZ(e,t,n,r){let i=KV(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[ZV(e,t),YV(i)],s,c=null;try{s=DZ(t,a,o,r,e=>{c=e})}catch(e){return e instanceof Z_&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:EZ(o),state:null,error:e instanceof Z_||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:EZ(o),state:s,error:null}}function AZ(e,t,n){return DZ(e,{layers:[],home:``,projectDir:t},[],n)}const jZ=new Set([`directory`]),MZ=new Set([`view`]);function NZ(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new vZ;tZ(e.config,l,t,MZ);let d=()=>IH(e.config,e=>r.get(c,e)),f=(t,n)=>{try{let r=e.neededInputPaths(n),{result:{lanes:a,faults:o},acquired:l,released:d}=u.declare(()=>i(u,t,r,e.sources));for(let e of o)s(`error`,`session view declaration threw sid=${JSON.stringify(c)} ${e}`);return l+d>0&&s(`info`,`session view declared sid=${JSON.stringify(c)} acquired=${l} released=${d} held=${u.size}`),a}catch(t){return s(`error`,`session view declaration threw sid=${JSON.stringify(c)}: ${String(t)}`),Pq(I(`view declaration threw: ${String(t)}`),[...e.sources.keys()])}},p=(e,t)=>({facts:e,preset:t,lanes:f(e,t)}),m=J.observable.box(p(n,d()),{deep:!1}),h=(e,t)=>{let n=m.get();if(e===n.facts&&t===n.preset)return;let r=p(e,t);(0,J.runInAction)(()=>m.set(r))},g=(0,J.reaction)(d,e=>h(m.get().facts,e),{fireImmediately:!0}),_=a({sessionId:c,state:e,store:l.variableStore,declared:()=>m.get()});TX(e.compiled,l.variableStore,l,_);let v=(0,J.reaction)(()=>{let{sources:t,...n}=m.get().lanes;return[_.payload(),_.selections(),l.published(),e.registry.published(),...[...Object.values(n),...t.values()].map(e=>e.current())]},()=>o(c),{equals:J.compareShallow,fireImmediately:!0,onError:e=>s(`error`,`session view change threw sid=${JSON.stringify(c)}: ${String(e)}`)});return{sessionId:c,state:e,store:l.variableStore,registry:l,holds:u,source:_,requested:e=>h(e,d()),facts:()=>m.get().facts,lanes:()=>m.get().lanes,lastRenderCellsBySegment:new Map,retire:v,dispose:()=>(g(),v(),u.close(),l.dispose())}}var PZ=class{entries=new Map;sweep=null;closed=!1;holds=new Map;views=new Map;viewHolds=new Map;pins=new Map;openFailures=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Me,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}compileOf(e,t){return this.compiles.get(e)??rZ(t,this.deps.signer)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760+this.views.size*2621440}getOrCreate(e,t,n){let r=CZ(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.load(e,t,n);a.state!==null&&this.log(`info`,xZ(a.layers,a.state));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??AZ(t,e,this.deps),watcher:null,watcherKey:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${tr(this.accountedBytes())}/${tr(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o,[]),o}hold(e,t,n){let r=this.getOrCreate(e,t,n);return this.holdState(r,r.state)}holdState(e,t){let n=this.holdOf(t);n.holders++,this.armSweep();let r=!1;return{entry:e,state:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache hold released twice`);r=!0,n.holders--,this.reclaim(t,n)}}}holdSession(e,t,n,r){let i=this.hold(e,t,n),a,o;try{a=this.viewOf(i.entry,i.state,r,`request`),o=this.leaseOf(a)}catch(e){throw i[Symbol.dispose](),e}return o.read=!0,this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}follow(e,t,n,r){try{var i=Aa();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(CZ(t,n,r));if(a!==void 0&&s?.state===a.state)return;let c=i.u(this.hold(t,n,r));this.viewOf(c.entry,c.state,o,`click`)}catch(e){i.e=e}finally{i.d()}}pin(e){this.pins.set(e,(this.pins.get(e)??0)+1);let t=!1;return()=>{if(t)throw Error(`render-cache pin released twice`);t=!0;let n=(this.pins.get(e)??0)-1;n>0?this.pins.set(e,n):this.pins.delete(e)}}viewOf(e,t,n,r){let{sessionId:i}=n,a=this.views.get(i);if(a?.state===t)return this.views.delete(i),this.views.set(i,a),a.requested(n),a;this.views.delete(i);let o=a!==void 0&&this.leaseOf(a).read,s;try{s=this.opened(e,t,n,o,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),s}opened(e,t,n,r,i){let{sessionId:a}=n,o;try{o=NZ(t,e.cwd,n,{sessionState:this.deps.sessionState,declare:this.deps.declare,source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(a,{error:e,facts:n}),e}return this.openFailures.delete(a),this.views.set(a,o),this.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}leaseOf(e){let t=this.viewHolds.get(e);if(t===void 0)throw Error(`render-cache view never served`);return t}retireView(e,t){this.views.get(e.sessionId)===e&&this.views.delete(e.sessionId),e.retire();let n=this.leaseOf(e);n.retired={reason:t,held:n.holders},this.reclaimView(e,n)}reclaimView(e,t){t.retired===null||t.holders>0||(this.viewHolds.delete(e),this.log(`info`,`session view closed sid=${JSON.stringify(e.sessionId)} reason=${t.retired.reason} released=${e.dispose()} held=${t.retired.held} views=${this.views.size}`))}armSweep(){this.sweep===null&&(this.sweep=setInterval(()=>this.releaseIdle(),15e4),this.sweep.unref?.())}releaseIdle(){for(let[e,t]of this.viewHolds)t.retired!==null||this.pins.has(e.sessionId)||(t.read?t.read=!1:this.retireView(e,`idle`));for(let e of this.openFailures.keys())this.pins.has(e)||this.openFailures.delete(e);this.entries.size===0&&this.sweep!==null&&(clearInterval(this.sweep),this.sweep=null)}close(){if(this.closed)return;this.closed=!0,this.sweep!==null&&clearInterval(this.sweep),this.sweep=null;let e=this.entries.size;for(let[e,t]of this.entries)this.drop(e,t,`close`);this.log(`info`,`render-cache closed entries=${e} deferred=${this.stats.retired}`)}load(e,t,n){if(this.closed)throw Error(`render cache used after close`);return kZ(e,t,n,this.deps)}drop(e,t,n){t.watcher?.release(),this.entries.delete(e),this.retire(t.state,n,null)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;let n=0;for(let e of this.viewHolds.values())e.retired!==null&&n++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,views:this.views.size,pinned:this.pins.size,retiredViews:n,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes(),n=new Set([...this.pins.keys()].flatMap(e=>{let t=this.views.get(e);return t===void 0?[]:[t.state]}));for(let[r,i]of this.entries){if(t())return;i===e||n.has(i.state)||this.drop(r,i,`evict`)}t()||this.log(`warn`,`render-cache over budget entries=${this.entries.size} views=${this.views.size} pinned=${n.size} accounted=${tr(this.accountedBytes())}/${tr(this.budgetBytes())}MB`)}serve(e){let t=this.compiles.get(e.compileKey);if(t!==void 0&&t!==e.compiled)throw Error(`render cache: a second compile for key ${e.compileKey.slice(0,12)}`);this.holds.set(e,{holders:0,retired:null}),this.compiles.set(e.compileKey,e.compiled),t===void 0&&this.log(`info`,`render-cache compile built key=${e.compileKey.slice(0,12)} compiles=${this.compiles.size}`)}holdOf(e){let t=this.holds.get(e);if(t===void 0)throw Error(`render-cache state never served`);return t}retire(e,t,n){for(let r of[...this.views.values()])if(r.state===e){if(n!==null)try{this.opened(n.entry,n.state,r.facts(),this.leaseOf(r).read,`reload`)}catch(e){this.log(`error`,`session view reopen failed sid=${JSON.stringify(r.sessionId)}: ${String(e)}`)}this.retireView(r,t)}let r=this.holdOf(e);r.retired={reason:t,held:r.holders},this.reclaim(e,r)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,SZ(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}sessionsOn(e){return[...this.views.values()].filter(t=>t.state===e.state).map(e=>e.sessionId)}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=this.sessionsOn(e),n=this.load(e.projectDir,e.cwd,e.configFile);if(e.lastWarning=n.warning,e.lastError=n.error,n.state!==null){this.log(`info`,xZ(n.layers,n.state));let t=e.state;e.state=n.state,this.serve(n.state),this.retire(t,`reload`,{entry:e,state:n.state})}this.fit(e),this.refreshWatcher(e,n),this.observers.onReload?.(e,t)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=TZ(e,t.layers),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){this.log(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}latestView(){return[...this.views.values()].at(-1)??null}};const FZ=16384;var IZ=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<FZ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%FZ}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e().snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,handlerProbes:[],clients:[],bundle:`/`,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:Ze,sourceDigest:et(),protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};function LZ(e,t,n){let r=(r,i,a)=>{let o=i.filter(t).map(t=>({key:t,before:e.get(r,t)}));a();for(let{key:t,before:i}of o)n(r,t,i,e.get(r,t))};return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(t,n,i)=>r(t,[n],()=>e.set(t,n,i)),setBatch:(t,n)=>r(t,n.map(e=>e.key),()=>e.setBatch(t,n)),clear:(t,n)=>r(t,[n],()=>e.clear(t,n))}}const RZ={load:()=>({}),save:()=>{},flush:()=>{}};var zZ=class{sessions;storage;head=0;atom=(0,J.createAtom)(`SessionState`);constructor(e=RZ,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}observers(){return this.atom.observers_?.size??0}latestRevision(){return this.head}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,J.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t.some(({key:e,value:t})=>n.values.get(e)!==t)&&(n.revision=++this.head);for(let{key:e,value:r}of t)n.values.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,J.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.values.delete(t)&&(n.revision=++this.head),n.values.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,J.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function BZ(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e)){if(typeof t!=`object`||!t||Array.isArray(t))return!1;for(let e of Object.values(t))if(typeof e!=`string`)return!1}return!0}var VZ=class{timer=null;pending=null;writing=!1;generation=0;constructor(e,t=500,n=Me){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=p.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return BZ(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,this.schedule()}schedule(){this.timer!==null||this.writing||(this.timer=setTimeout(()=>{this.timer=null,this.write()},this.debounceMs),this.timer.unref())}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=performance.now(),r=JSON.stringify(e),i=`${this.filePath}.writing`;this.writing=!0;let a=performance.now()-n;try{await p.promises.mkdir(s.dirname(this.filePath),{recursive:!0});let o=await p.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}if(t!==this.generation){await p.promises.rm(i,{force:!0});return}let c=performance.now();p.renameSync(i,this.filePath),this.saved(r,e,n,a+performance.now()-c),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.generation++,this.pending===null)return;let e=this.pending,t=performance.now();try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);p.writeFileSync(n,r,{mode:384}),p.chmodSync(n,384),p.renameSync(n,this.filePath),this.saved(r,e,t,performance.now()-t),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${Math.round(performance.now()-n)}ms held=${Math.round(r)}ms`)}};const HZ=new Set([`1`,`true`]),UZ=new Set([`0`,`false`,``]);function WZ(e,t){let n=hQ(e),r=n.scope===`segment-palette`?`string`:yy(n.field);if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if(HZ.has(t))return`true`;if(UZ.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function GZ(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function KZ(e,t,n){try{if(t===null){p.rmSync(_t(e),{force:!0});return}gt(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function qZ(e){return/^\s*$/.test(e)?null:Ui(e)}function JZ(e,t){return e!==null&&Gi(e,t)!==void 0}function YZ(e){if(e.kind===`segment`)return e.when===void 0?e.name:{seg:e.name,when:e.when};if(e.kind===`container`){let{kind:t,direction:n,children:r,...i}=e;return{[n===`horizontal`?`h`:`v`]:r.map(YZ),...i}}return e}function XZ(e){if(!Ub(e))return YZ(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,YZ(t)])),...n}}const ZZ=EH,QZ=ZZ.segments,$Z=ZZ.presets,eQ=ZZ.root;function tQ(e,t,n,r){if(!JZ(e,t)&&n===void 0)throw new q(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function nQ(e,t){let n=vj(t);return t.scope===`segment-palette`&&tQ(e,[`segments`,t.segment],QZ[t.segment],n.join(`.`)),n}function rQ(e){return Ui($i(e))}function iQ(){return Object.entries(eQ.rows).map(([e,t])=>{let n=YZ(t);return{path:[`root`],fragment:rQ({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function aQ(e,t){let n=e===null?void 0:Gi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function oQ(e,t){if(t===void 0)return null;let n=XZ(t);return{path:e,fragment:rQ(n),unit:{path:e,value:n}}}function sQ(e,t){let n=[`presets`,t],r=[...n,`root`],i=$Z[t];tQ(e,n,i,r.join(`.`));let a=aQ(e,r)??oQ(r,i?.root);return a!==null&&ba(a.fragment)?a:null}function cQ(e,t){let n=ya(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function lQ(e,t){return[...iQ(),aQ(e,[`root`]),sQ(e,t)].filter(e=>e!==null).reduce(cQ,new Map)}function uQ(e,t,n){for(let{node:r,...i}of lQ(e,t).values())if(Sa(r,n))return i;throw new q(`${dQ(e,t).join(`.`)} holds no placement "${n}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`)}function dQ(e,t){return sQ(e,t)?.path??[`root`]}function fQ(e,t){return t.scope===`preset-root`?dQ(e,t.preset):vj(t)}function pQ(e,{unit:t}){return t===null?e:pa(e,t.path,$i(t.value),Zi)}function mQ(e){let t=_j(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function hQ(e){let t=mQ(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function gQ(e,t,n,r,i){i(t,n,DQ(t,r)),KZ(t.path,r,e.logger),e.record(t.path,n,r)}function _Q(e,t,n){let r=bQ(e,t,n);if(r.length>0)throw new q(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const vQ=()=>{};function yQ(e,t){try{return t()}catch(t){throw!(t instanceof q)||e.above.length===0?t:new q(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function bQ(e,t,n){let r=xQ(e,t);if(r===null)return[];let i=new Set(TQ(wQ(r),wQ(n)));return TQ(CQ(e,r),CQ(e,n)).filter(e=>!i.has(e))}function xQ(e,t){try{return SQ(e,t)}catch(e){if(e instanceof Z_)return null;throw e}}function SQ(e,t){return aH(t===null?e.above:[e.path,...e.above],OH,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function CQ(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function wQ(e){return e.layers.at(-1)?.config??e.base}function TQ(e,t,n=``){return!EQ(e)||!EQ(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>TQ(e[r],t[r],n===``?r:`${n}.${r}`))}function EQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function DQ(e,t){try{return SQ(e,t)}catch(e){throw e instanceof Z_?new q(`refused: the config file would not load after this click — ${e.message}`):e}}function OQ(e,t){let n=hQ(t),r=qZ(GZ(e)??``),i=r===null?void 0:Gi(r,vj(n));return i!==void 0&&`value`in i?i.value:void 0}function kQ(e,t,n){AQ(e,t,n,[])}function AQ(e,t,n,r){let i=GZ(t.path),a=n.reduce((e,[t,n])=>pa(e,nQ(qZ(e),hQ(t)),WZ(t,n),Zi),i??``);gQ(e,t,i,yQ(t,()=>jQ(a,t.path,r,e=>e)),_Q)}function jQ(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=uQ(qZ(s),n,i),l=Ea(pQ(s,c),c.path,i,a,$i(o));if(l===null)throw new q(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function MQ(e,t,n){let r=qZ(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of lQ(r,t)){if(!Sa(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?qi(e,c):$i(s.value);if(a!==`#`)return pa(e,[...i,`rows`,a],l,Zi);if(sQ(r,t)!==null)throw new q(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return pa(e,i,l,Zi)}return e}function NQ(e,t){return ha(e,t,t[0]===`presets`&&t.length>2&&!AH(t[1])?2:0)}function PQ(e,t,n){let r=n.map(mQ),i=GZ(t.path);if(i===null)return;let a=r.reduce((e,t)=>NQ(e,fQ(qZ(e),t)),i);a!==i&&gQ(e,t,i,a,vQ)}function FQ(e){let t=e===null?void 0:Gi(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function IQ(e,t){let n=new Set([...kH,...FQ(e),...t.above.flatMap(e=>Object.keys(Ii.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(pA));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(pA(e)))}function LQ(e,t,n,r,i,a){let o=GZ(t.path),s=qZ(o??``),c=IQ(s,t),l=[`presets`,c],u=yQ(t,()=>sQ(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?qi(o??``,u.fragment):$i(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],$i(r)]]],f=i.map(([e,t])=>{let n=gj(c,e);return[nQ(s,hQ(n)),WZ(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>pa(e,t,n,Zi),pa(o??``,l,`{}`,Zi));return gQ(e,t,o,yQ(t,()=>jQ(p,t.path,a.map(e=>({...e,preset:c})),MQ)),_Q),c}function RQ(e,t,n,r){let i=GZ(t.path);gQ(e,t,i,pa(i??``,[`themeDefaults`,n],$i(r),Zi),_Q)}function zQ(e,t,n){if(AH(n))throw new q(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=GZ(t.path),a=qZ(i??``);if(i===null||a===null||Gi(a,r)===void 0)throw new q(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Gi(a,[`globals`,`preset`]);gQ(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>NQ(e,t),i),vQ)}function BQ(e,t,n,r){let i=mQ(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=GZ(t.path),o=r.op===`remove`?r.target:r.anchor,s=yQ(t,()=>uQ(qZ(a??``),i.preset,o)),c=pQ(a??``,s),{after:l,placed:u}=VQ(c,s.path,r,()=>{let e=DQ(t,c).config;return $b(e.presets).map(t=>nx(e,t).node)});if(l===null)throw new q(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return gQ(e,t,a,l,_Q),u}function VQ(e,t,n,r){switch(n.op){case`remove`:return{after:wa(e,t,n.target),placed:null};case`insert`:{let i=II(n.segment,n.anchor,r());return{after:Ta(e,t,i,n.anchor,n.relation),placed:i}}}}const HQ={load:()=>({}),save:()=>{}},UQ=new Set(wy.map(e=>e.sessionKey)),WQ=e=>UQ.has(e)||e.startsWith(Aj),GQ=8*1024*1024,KQ={past:[],future:[]},qQ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var JQ=class{held=J.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,J.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=HQ){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}useStorage(e){this.storage=e,this.state=new Map(Object.entries(e.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??KQ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??KQ}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(qQ(n));r.set(qQ(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:LZ(this.sessionState,e=>WQ(e)||e===`edit.mode`,(e,r,i,a)=>{if(r===`edit.mode`){let t=n.get(e);n.set(e,{before:t===void 0?i:t.before,after:a});return}t(e,{kind:`session`,key:r,before:i,after:a})}),file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=new Map(e),r=new Map(n);e.clear(),n.clear();for(let e of new Set([...t.keys(),...r.keys()])){let n=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=n.length===0?i:n$(i,n),o=r.get(e),s=o===void 0?a:o$(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new q(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,i$(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new q(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(qQ)),a=n.net.filter(e=>!i.has(qQ(e))),o=ZQ(s$(a$(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new q(`rewind: ${r.map(l$).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new q(`redo: nothing to redo`);let a=[...n,i],o=ZQ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...$Q(t.savepoint,a.length-o.length,i)}),i}apply(e,t,n,r,i){let a=n===`before`?`after`:`before`,o=t.filter(t=>this.read(e,t)!==t[a]);if(o.length>0){let t=new Set(o.map(qQ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:s$(n,t),future:s$(i,t),...a!==void 0&&{savepoint:{at:s$([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(qQ(e))),below:s$(a.below,t)}}}),new q(`${r}: ${o.map(l$).join(`, `)} changed since that edit — refusing to overwrite it; this session's undo history no longer steps it`)}let s=[];try{for(let r of t)this.write(e,r,r[n]),s.push(r);this.put(e,i)}catch(t){try{for(let t of s.reverse())this.write(e,t,t[a])}catch(e){throw Error(`${t.message}; and putting the step back failed, so it is half-applied: ${e.message}`)}throw t}}read(e,t){return t.kind===`session`?this.sessionState.get(e,t.key):GZ(t.file)}write(e,t,n){t.kind===`file`?KZ(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||YQ(n)>GQ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,XQ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${GQ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function YQ(e){let t=0;for(let{past:n,future:r,savepoint:i}of e.values())for(let e of[...n,...r,...i===void 0?[]:[i.net,...i.below]])for(let n of e)t+=(n.before?.length??0)+(n.after?.length??0);return t}function XQ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...$Q(n,1,[])}:{past:e,future:t.slice(1),...$Q(n,0,[])}}function ZQ(e){return e.slice(-50)}const QQ=e=>e===Mj.member;function $Q(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:e$(e.net,n),below:e.below}}}function e$(e,t){let n=new Map(e.map(e=>[qQ(e),e]));for(let e of t){let t=n.get(qQ(e));n.set(qQ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const t$=e=>e.map(e=>({...e,before:e.after,after:e.before}));function n$(e,t){let n=[...e.past,t],r=ZQ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...$Q(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...r$(e.future,a),...i.below]},n.length-r.length,t)}}function r$(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function i$(e,t){return{past:e.past.slice(0,-1),future:ZQ([...e.future,t]),...$Q(e.savepoint,0,t$(t))}}function a$(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...r$(r,t.at-i.length),...t.below]}function o$(e,t){if(QQ(t.after)&&!QQ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!QQ(t.after)&&QQ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function s$(e,t){return e.map(e=>e.filter(e=>!t.has(qQ(e)))).filter(e=>e.length>0)}function c$(e){return e.map(l$).join(`, `)}function l$(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function u$(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function d$(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(u$))}function f$(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(u$)&&d$(t.below)}function p$(e){if(typeof e!=`object`||!e)return!1;let t=e;return d$(t.past)&&d$(t.future)&&(t.savepoint===void 0||f$(t.savepoint))}function m$(e,t){let n=e=>e.kind===`file`||WQ(e.key)?!0:(t.add(e.key),!1),r=e=>e.map(e=>e.filter(n)).filter(e=>e.length>0),{savepoint:i}=e,a=r(e.past),o=r(e.future);return i===void 0?{past:a,future:o}:{past:a,future:o,savepoint:{at:r(e.past.slice(0,i.at)).length,net:i.net.filter(n),below:r(i.below)}}}function h$(e,t){return{load:()=>{let n;try{n=p.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(p$)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,m$(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{p.mkdirSync(s.dirname(e),{recursive:!0}),gt(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const g$=e=>!WQ(e)&&!aP(e)&&e!==`update.dismissed`;var _$=class{past=J.observable.map(void 0,{deep:!1});depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:LZ(e,g$,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new q(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,J.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){(0,J.runInAction)(()=>{for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)})}};const v$={inside:()=>[],defaultOf:()=>yi,menus:[]},y$=e=>`${e.key}\0${e.member}`;function b$(e){let t=new Map,n=n=>{let r=`${n.name}\0${S_(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:ZR(a,S_(n));return t.set(r,o),o},r=e=>[...e.opens===void 0?[]:[e.opens.ref],...n(e)],i=new Map,a=new Map;for(let t of Object.values(e.variables))t.kind===`state`&&(t.default!==void 0&&i.set(t.key,t.default),t.within!==void 0&&a.set(t.key,t.within));let o=new Map,s=new Map,c=new Map,l=e=>{s.set(e.key,(s.get(e.key)??new Set).add(e.member))},u=(e,t)=>{let n=o.get(y$(e))??new Map;n.set(y$(t),t),o.set(y$(e),n)},d=(e,t)=>{if(e.kind===`container`){for(let n of e.children)d(n,t);return}for(let n of r(e)){l(n),c.set(y$(n),n);for(let e of t)u(e,n)}e.opens!==void 0&&d(e.opens.body,[...t,e.opens.ref])};for(let t of $b(e.presets))d(nx(e,t).node,[]);for(let t of Object.values(e.actions)){let e=ji(t);e!==void 0&&l(e)}for(let[e,t]of a)for(let n of s.get(e)??[])for(let r of t)u(r,{key:e,member:n});let f=new Map;return{inside:e=>{let t=f.get(y$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(y$(e))??[])n.has(t)||(n.set(t,i),r(i))};r(e);let i=new Map;for(let{key:e,member:t}of n.values())i.set(e,(i.get(e)??new Set).add(t));let a=[...i].map(([e,t])=>({key:e,outside:new Set([...s.get(e)].filter(e=>!t.has(e)))}));return f.set(y$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const x$=new WeakMap;function S$(e){let t=x$.get(e);if(t!==void 0)return t;let n=b$(e);return x$.set(e,n),n}function C$(e,t,n){let r=new Set(n.map(e=>e.key)),i=n=>t(n)??e.defaultOf(n),a=new Set;for(let{key:t,value:o}of n){let n=i(t);if(n!==o)for(let o of e.inside({key:t,member:n})){let t=i(o.key);t!==e.defaultOf(o.key)&&!o.outside.has(t)&&!r.has(o.key)&&a.add(o.key)}}return[...a]}function w$(e,t){let n=({key:n,member:r})=>(t(n)??e.defaultOf(n))===r,r=(t,n)=>e.inside(n).some(({key:e,outside:n})=>e===t.key&&!n.has(t.member));return e.menus.filter(n).filter(t=>{let i=e.menus.filter(e=>e!==t&&r(t,e)),a=i.length>0&&e.defaultOf(t.key)===t.member;return!i.some(n)&&!a})}function T$(e,t,n){let r=(r,i,a)=>{let o=C$(t(r),t=>e.get(r,t),i);(0,J.runInAction)(()=>{a();for(let t of o)e.clear(r,t)}),o.length>0&&n(`close-nested: folded=${o.join(`,`)} (session=${r})`)},i=(t,n)=>r(t,n,()=>e.setBatch(t,n));return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(e,t,n)=>i(e,[{key:t,value:n}]),setBatch:i,clear:(n,i)=>r(n,[{key:i,value:t(n).defaultOf(i)}],()=>e.clear(n,i))}}const E$=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function D$(e,t){let n={...e};for(let e of E$)delete n[e];return{...n,CLAUDE_CODE_SESSION_ID:t.sessionId,CLAUDE_PROJECT_DIR:t.projectDir,...t.claudeConfigDir!==void 0&&{CLAUDE_CONFIG_DIR:t.claudeConfigDir}}}function O$(e,t,n,r){let i=s.join(e,t),a=()=>{let e;try{e=p.readFileSync(i,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${i}: ${e.message}`}}let t;try{t=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${i} is not JSON: ${e.message}`}}let a=r(t);return a.kind===`ok`?a:{kind:`failed`,reason:`${i} ${a.reason}`}};return{read:a,update:e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return n!==t.value&&gt(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const k$=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function A$(e){let t=e=>({kind:`failed`,reason:e});if(!k$(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!k$(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!KM.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${KM.join(` or `)}`)}return{kind:`ok`,value:e}}function j$(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const M$=e=>O$(e,`doctor-marks.json`,{},A$),N$=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},P$=(e,t)=>e.includes(t)?e:[...e,t],F$=e=>O$(e,`doctor-clicked-terminals.json`,[],N$);var I$=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const L$=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},R$=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),z$=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=R$(e,t);return r===void 0?n:r.projectDir},B$=(e,t)=>R$(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function V$(e){let t=new Map;for(let n of e.split(`
201
+ `)){let e=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(n);if(e===null)continue;let r=Number(e[1]);t.set(r,{pid:r,ppid:Number(e[2]),command:e[3].trim()})}return t}function*H$(e,t){let n=new Set;for(let r=e.get(t);r!==void 0&&!n.has(r.pid);)n.add(r.pid),yield r,r=e.get(r.ppid)}const U$={pullRequests:e=>Tq(e).showPullRequest===!0,rateLimits:e=>wq(e,`block`)||wq(e,`weekly`)};function W$(e,t){let n=new Map;for(let r of E_(nx(e,t).node)){if(r.kind!==`segment`)continue;let e=n.get(r.name)??[];r.when&&e.push(r.when),n.set(r.name,e)}let r=[...n.keys()].filter(t=>I_(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,xq(e,t,n.get(t))])),a=e=>r.filter(t=>U$[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}
202
202
  /*!
203
203
  * Copyright (c) Squirrel Chat et al., All rights reserved.
204
204
  * SPDX-License-Identifier: BSD-3-Clause
@@ -226,9 +226,9 @@ Config tooling:
226
226
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
227
227
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
228
228
  */
229
- function U$(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function W$(e,t,n){let r=e.split(/\r?\n/),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
229
+ function G$(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function K$(e,t,n){let r=e.split(/\r?\n/),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
230
230
  `,e===t&&(i+=` `.repeat(a+n+2),i+=`^
231
- `))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=U$(t.toml,t.ptr),i=W$(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}static x(t,n,r){throw new e(t,{toml:n.s,ptr:r??n.p})}};
231
+ `))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=G$(t.toml,t.ptr),i=K$(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}static x(t,n,r){throw new e(t,{toml:n.s,ptr:r??n.p})}};
232
232
  /*!
233
233
  * Copyright (c) Squirrel Chat et al., All rights reserved.
234
234
  * SPDX-License-Identifier: BSD-3-Clause
@@ -256,7 +256,7 @@ function U$(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().lengt
256
256
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
257
257
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
258
258
  */
259
- function G$(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);a&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o=``,s=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),a&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c&&=3;else if(n<32&&n!==9||n===127)Q.x(`control characters are not allowed in strings`,e);else if((!c||c===3)&&n===r&&(!a||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(a&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),!c){let t=e.s.slice(s,e.p);o=o?o+t:t}return e.p+=a?3:1,o}else if(!c)!i&&n===92&&(o+=e.s.slice(s,s=e.p),c=1);else if(c===1)if(n===120||n===117||n===85){let t=e.p++-1,r=0,i=n===120?2:n===117?4:8;for(let t=0;t<i;t++,e.p++){let t=e.s.charCodeAt(e.p),n=t>=48&&t<=57?t-48:t>=65&&t<=70?t-65+10:t>=97&&t<=102?t-97+10:-1;n<0&&Q.x(`invalid non-hex character in unicode escape`,e),r=r<<4|n}(r<0||r>1114111||r>=55296&&r<=57343)&&Q.x(`invalid unicode escape`,e,t),o+=String.fromCodePoint(r),s=e.p--,c=0}else a&&(n===32||n===9)?c=2:(n===98?o+=`\b`:n===116?o+=` `:n===110?o+=`
259
+ function q$(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);a&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o=``,s=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),a&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c&&=3;else if(n<32&&n!==9||n===127)Q.x(`control characters are not allowed in strings`,e);else if((!c||c===3)&&n===r&&(!a||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(a&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),!c){let t=e.s.slice(s,e.p);o=o?o+t:t}return e.p+=a?3:1,o}else if(!c)!i&&n===92&&(o+=e.s.slice(s,s=e.p),c=1);else if(c===1)if(n===120||n===117||n===85){let t=e.p++-1,r=0,i=n===120?2:n===117?4:8;for(let t=0;t<i;t++,e.p++){let t=e.s.charCodeAt(e.p),n=t>=48&&t<=57?t-48:t>=65&&t<=70?t-65+10:t>=97&&t<=102?t-97+10:-1;n<0&&Q.x(`invalid non-hex character in unicode escape`,e),r=r<<4|n}(r<0||r>1114111||r>=55296&&r<=57343)&&Q.x(`invalid unicode escape`,e,t),o+=String.fromCodePoint(r),s=e.p--,c=0}else a&&(n===32||n===9)?c=2:(n===98?o+=`\b`:n===116?o+=` `:n===110?o+=`
260
260
  `:n===102?o+=`\f`:n===114?o+=`\r`:n===101?o+=`\x1B`:n===34?o+=`"`:n===92?o+=`\\`:Q.x(`unrecognised escape sequence`,e),s=e.p+1,c=0);else n!==32&&n!==9&&(c===2&&Q.x(`invalid escape: only line-ending whitespace may be escaped`,e,s),c=+(!i&&n===92),s=e.p);Q.x(`unfinished string`,e,t)}
261
261
  /*!
262
262
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -285,7 +285,7 @@ function G$(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCode
285
285
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
286
286
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
287
287
  */
288
- let K$=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var q$=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e,t,n){let r=!0,i=!0,a=`Z`,o;if(typeof e==`string`)if(t)prep:{if(t<3){if(+e.slice(11,13)>23){e=``;break prep}t===2?(a=null,e+=`Z`):(o=e.charCodeAt(e.length-1))!==90&&o!==122&&(a=e.slice(e.length-6)),n&&(e=e.slice(0,10)+`T`+e.slice(11))}else t===4&&(e=+e.slice(0,2)>23?``:`0000-01-01T${e}Z`);r=t!==4,i=t!==3}else{let t=e.match(K$);t?(t[1]||(r=!1,e=`0000-01-01T${e}`),i=!!t[2],i&&e[10]===` `&&(e=e.replace(` `,`T`)),t[2]&&+t[2]>23?e=``:(a=t[3]||null,!a&&i&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=r,this.#t=i,this.#n=a)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`||this.#n===`z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
288
+ let J$=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var Y$=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e,t,n){let r=!0,i=!0,a=`Z`,o;if(typeof e==`string`)if(t)prep:{if(t<3){if(+e.slice(11,13)>23){e=``;break prep}t===2?(a=null,e+=`Z`):(o=e.charCodeAt(e.length-1))!==90&&o!==122&&(a=e.slice(e.length-6)),n&&(e=e.slice(0,10)+`T`+e.slice(11))}else t===4&&(e=+e.slice(0,2)>23?``:`0000-01-01T${e}Z`);r=t!==4,i=t!==3}else{let t=e.match(J$);t?(t[1]||(r=!1,e=`0000-01-01T${e}`),i=!!t[2],i&&e[10]===` `&&(e=e.replace(` `,`T`)),t[2]&&+t[2]>23?e=``:(a=t[3]||null,!a&&i&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=r,this.#t=i,this.#n=a)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`||this.#n===`z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
289
289
  /*!
290
290
  * Copyright (c) Squirrel Chat et al., All rights reserved.
291
291
  * SPDX-License-Identifier: BSD-3-Clause
@@ -313,7 +313,7 @@ let K$=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[
313
313
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
314
314
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
315
315
  */
316
- function J$(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function Y$(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function X$(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||Q.x(`document contains excessively nested structures. aborting.`,e);let t=r===91?s1(e):o1(e);return e.d++,t}return r===34||r===39?G$(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&Q.x(`invalid value`,e,n),e.p++,!0):r===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&Q.x(`invalid value`,e,n),e.p++,!1):r===43||r===45?Z$(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?e1(e,r,t):e.s.charCodeAt(e.p+2)===58?t1(e,r,t):Z$(e,e.p,r,0,t)}function Z$(e,t,n,r,i){let a=n,o=0,s=!1;if(a===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&Q.x(`invalid value`,e,t),e.p++,(r||1)/0;if(a===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&Q.x(`invalid value`,e,t),e.p++,NaN;if(a===48){if(++e.p>=e.s.length||Y$(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return Q$(e,t,16,i);if(a===98)return Q$(e,t,2,i);if(a===111)return Q$(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:Q.x(`illegal leading zero`,e,t)}else J$(a)||Q.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!Y$(a,i));)o||=1,a===95?(o&1||Q.x(`illegal underscore`,e),o+=11,s=!0):o===1&&a===46?o=2:(o===1||o===3)&&(a===101||a===69)?o=4:o===4&&(a===43||a===45)?o=6:J$(a)?o>9?o-=11:o&1||o++:Q.x(`illegal character in numeric literal`,e);if(!o){let t=(n-48)*(r||1);return e.bi===!0?BigInt(t):t}o&1||Q.x(`unfinished numeric value`,e,t);let c=e.s.slice(t,e.p);return s&&(c=c.replaceAll(`_`,``)),o>1?parseFloat(c):$$(e,c,10,t)}function Q$(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!Y$(i,r));)i===95?(a&1&&Q.x(`illegal underscore`,e),a=3):J$(i,n)?a&1&&a--:Q.x(`illegal character in numeric literal`,e);a&1&&Q.x(`unfinished numeric value`,e);let o=e.s.slice(t+2,e.p);return a&&(o=o.replaceAll(`_`,``)),$$(e,o,n,t)}function $$(e,t,n,r){if(e.bi!==!0)int:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break int;Q.x(`integer value cannot be represented losslessly`,e,r)}return i}return BigInt(n===10?t:(n===2?`0b`:n===8?`0o`:`0x`)+t)}function e1(e,t,n){let r=e.p++,i;if(!J$(t)||!J$(e.s.charCodeAt(e.p++))||!J$(e.s.charCodeAt(e.p++))||!J$(e.s.charCodeAt(e.p++)))return Z$(e,e.p=r,t,0,n);if(e.p+=5,J$(e.s.charCodeAt(e.p++))||Q.x(`invalid date-time: date part is malformed`,e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!J$(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return n1(e,e.s.slice(r,e.p),3,!1,r);if(e.s.charCodeAt(e.p+=3)!==58&&Q.x(`invalid date-time: time part is malformed`,e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;J$(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return n1(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return n1(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return n1(e,e.s.slice(r,e.p),2,i,r)}function t1(e,t,n){let r=e.p;if(!J$(t)||!J$(e.s.charCodeAt(++e.p)))return Z$(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;J$(e.s.charCodeAt(++e.p)););return n1(e,e.s.slice(r,e.p),4,!1,r)}function n1(e,t,n,r,i,a){if(e.ld){let a=new q$(t,n,r);return a.isValid()||Q.x(`invalid date`,e,i),a}try{switch(a&&(t+=a),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(t){Q.x(t instanceof Error?t.message:``+t,e,i)}}
316
+ function X$(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function Z$(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function Q$(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||Q.x(`document contains excessively nested structures. aborting.`,e);let t=r===91?l1(e):c1(e);return e.d++,t}return r===34||r===39?q$(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&Q.x(`invalid value`,e,n),e.p++,!0):r===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&Q.x(`invalid value`,e,n),e.p++,!1):r===43||r===45?$$(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?n1(e,r,t):e.s.charCodeAt(e.p+2)===58?r1(e,r,t):$$(e,e.p,r,0,t)}function $$(e,t,n,r,i){let a=n,o=0,s=!1;if(a===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&Q.x(`invalid value`,e,t),e.p++,(r||1)/0;if(a===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&Q.x(`invalid value`,e,t),e.p++,NaN;if(a===48){if(++e.p>=e.s.length||Z$(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return e1(e,t,16,i);if(a===98)return e1(e,t,2,i);if(a===111)return e1(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:Q.x(`illegal leading zero`,e,t)}else X$(a)||Q.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!Z$(a,i));)o||=1,a===95?(o&1||Q.x(`illegal underscore`,e),o+=11,s=!0):o===1&&a===46?o=2:(o===1||o===3)&&(a===101||a===69)?o=4:o===4&&(a===43||a===45)?o=6:X$(a)?o>9?o-=11:o&1||o++:Q.x(`illegal character in numeric literal`,e);if(!o){let t=(n-48)*(r||1);return e.bi===!0?BigInt(t):t}o&1||Q.x(`unfinished numeric value`,e,t);let c=e.s.slice(t,e.p);return s&&(c=c.replaceAll(`_`,``)),o>1?parseFloat(c):t1(e,c,10,t)}function e1(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!Z$(i,r));)i===95?(a&1&&Q.x(`illegal underscore`,e),a=3):X$(i,n)?a&1&&a--:Q.x(`illegal character in numeric literal`,e);a&1&&Q.x(`unfinished numeric value`,e);let o=e.s.slice(t+2,e.p);return a&&(o=o.replaceAll(`_`,``)),t1(e,o,n,t)}function t1(e,t,n,r){if(e.bi!==!0)int:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break int;Q.x(`integer value cannot be represented losslessly`,e,r)}return i}return BigInt(n===10?t:(n===2?`0b`:n===8?`0o`:`0x`)+t)}function n1(e,t,n){let r=e.p++,i;if(!X$(t)||!X$(e.s.charCodeAt(e.p++))||!X$(e.s.charCodeAt(e.p++))||!X$(e.s.charCodeAt(e.p++)))return $$(e,e.p=r,t,0,n);if(e.p+=5,X$(e.s.charCodeAt(e.p++))||Q.x(`invalid date-time: date part is malformed`,e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!X$(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return i1(e,e.s.slice(r,e.p),3,!1,r);if(e.s.charCodeAt(e.p+=3)!==58&&Q.x(`invalid date-time: time part is malformed`,e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;X$(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return i1(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return i1(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return i1(e,e.s.slice(r,e.p),2,i,r)}function r1(e,t,n){let r=e.p;if(!X$(t)||!X$(e.s.charCodeAt(++e.p)))return $$(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;X$(e.s.charCodeAt(++e.p)););return i1(e,e.s.slice(r,e.p),4,!1,r)}function i1(e,t,n,r,i,a){if(e.ld){let a=new Y$(t,n,r);return a.isValid()||Q.x(`invalid date`,e,i),a}try{switch(a&&(t+=a),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(t){Q.x(t instanceof Error?t.message:``+t,e,i)}}
317
317
  /*!
318
318
  * Copyright (c) Squirrel Chat et al., All rights reserved.
319
319
  * SPDX-License-Identifier: BSD-3-Clause
@@ -341,7 +341,7 @@ function J$(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48
341
341
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
342
342
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
343
343
  */
344
- function r1(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}(t<32&&t!==9||t===127)&&Q.x(`control characters are not allowed in comments`,e)}}function i1(e,t,n){let r;for(;e.p<e.s.length;){for(;e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10));)e.p++;if(n||r!==35)break;r1(e)}}
344
+ function a1(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}(t<32&&t!==9||t===127)&&Q.x(`control characters are not allowed in comments`,e)}}function o1(e,t,n){let r;for(;e.p<e.s.length;){for(;e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10));)e.p++;if(n||r!==35)break;a1(e)}}
345
345
  /*!
346
346
  * Copyright (c) Squirrel Chat et al., All rights reserved.
347
347
  * SPDX-License-Identifier: BSD-3-Clause
@@ -369,7 +369,7 @@ function r1(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)br
369
369
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
370
370
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
371
371
  */
372
- function a1(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return r||Q.x(`unexpected end of key`,e),r===1&&i.push(e.s.slice(a,e.p)),e.p++,i;else o===46?(r||Q.x(`illegal empty bare key`,e),r===1&&i.push(e.s.slice(a,e.p)),r=0):!r&&(o===34||o===39)?(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2)&&Q.x(`illegal quoted key: multiline strings are not allowed`,e),i.push(G$(e)),r=2,e.p--):o===32||o===9?r===1&&(i.push(e.s.slice(a,e.p)),r=2):r===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122?Q.x(`illegal character in key`,e):r||(r=1,a=e.p);while(o=e.s.charCodeAt(++e.p));Q.x(`incomplete key-value: cannot find end of key`,e,n)}function o1(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(i1(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=a1(e);for(let n=0;n<c.length;n++){n&&(a=o?a[t]:a[t]=Object.create(null)),t=c[n],(o=Object.hasOwn(a,t))&&(typeof a[t]!=`object`||r.has(a[t]))&&Q.x(`trying to redefine an already defined value`,e,s);let i=t===`__proto__`;if(e.uk&&(i||t===`constructor`)){a=e.uk!==1&&Q.x(`document contains an unsafe property`,e,s);break}!o&&i&&Object.defineProperty(a,t,{enumerable:!0,configurable:!0,writable:!0})}o&&Q.x(`trying to redefine an already defined value`,e,s),i1(e,!0,!0);let l=X$(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),i1(e),(i=e.s.charCodeAt(e.p++))===125)return n;i!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished table`,e,t)}function s1(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(i1(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(X$(e,93)),i1(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished array`,e,t)}
372
+ function s1(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return r||Q.x(`unexpected end of key`,e),r===1&&i.push(e.s.slice(a,e.p)),e.p++,i;else o===46?(r||Q.x(`illegal empty bare key`,e),r===1&&i.push(e.s.slice(a,e.p)),r=0):!r&&(o===34||o===39)?(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2)&&Q.x(`illegal quoted key: multiline strings are not allowed`,e),i.push(q$(e)),r=2,e.p--):o===32||o===9?r===1&&(i.push(e.s.slice(a,e.p)),r=2):r===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122?Q.x(`illegal character in key`,e):r||(r=1,a=e.p);while(o=e.s.charCodeAt(++e.p));Q.x(`incomplete key-value: cannot find end of key`,e,n)}function c1(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(o1(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=s1(e);for(let n=0;n<c.length;n++){n&&(a=o?a[t]:a[t]=Object.create(null)),t=c[n],(o=Object.hasOwn(a,t))&&(typeof a[t]!=`object`||r.has(a[t]))&&Q.x(`trying to redefine an already defined value`,e,s);let i=t===`__proto__`;if(e.uk&&(i||t===`constructor`)){a=e.uk!==1&&Q.x(`document contains an unsafe property`,e,s);break}!o&&i&&Object.defineProperty(a,t,{enumerable:!0,configurable:!0,writable:!0})}o&&Q.x(`trying to redefine an already defined value`,e,s),o1(e,!0,!0);let l=Q$(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),o1(e),(i=e.s.charCodeAt(e.p++))===125)return n;i!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished table`,e,t)}function l1(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(o1(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Q$(e,93)),o1(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished array`,e,t)}
373
373
  /*!
374
374
  * Copyright (c) Squirrel Chat et al., All rights reserved.
375
375
  * SPDX-License-Identifier: BSD-3-Clause
@@ -397,7 +397,7 @@ function a1(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return
397
397
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
398
398
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
399
399
  */
400
- function c1(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if(a=c?a[s]:a[s]=Object.create(null),o=(l=o[s]).c,i===0&&(l.t===1||l.t===2))return null;if(l.t===2){let e=a.length-1;a=a[e],o=o[e].c}}if(s=t[n],(c=Object.hasOwn(a,s))&&o[s]?.t===0&&o[s]?.d)return null;if(!c){let r=s===`__proto__`;if(e.uk&&(r||s===`constructor`))return!1;r&&(Object.defineProperty(a,s,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})),o[s]={t:n<t.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(l=o[s],l.t!==i&&!(i===1&&l.t===3)||(i===2&&(l.d||(l.d=!0,a[s]=[]),a[s].push(a=Object.create(null)),l.c[l.i++]=l={t:1,d:!1,i:0,c:Object.create(null)}),l.d))return null;if(l.d=!0,i===1)a=c?a[s]:a[s]=Object.create(null);else if(i===0&&c)return null;return[s,a,l.c]}function l1(e,t,n){(t===null||e.uk===2)&&Q.x(t===null?`trying to redefine an already defined table or value`:`document contains an unsafe property`,e,n)}function u1(e,t={}){let n={s:e,p:0,d:t.maxDepth??1e3,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour===`throw`?2:+(t.unsafeKeyBehaviour===`drop`)},r=Object.create(null),i=Object.create(null),a,o=!1,s=r,c=i;for(e.charCodeAt(0)===65279&&n.p++,i1(n);n.p<e.length;){if(e.charCodeAt(n.p)===91){let t=e.charCodeAt(++n.p)===91;a=n.p+=+t,o=!1;let l=a1(n,93);t&&(e.charCodeAt(n.p)!==93&&Q.x(`expected end of table array declaration`,n),n.p++);let u=c1(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(l1(n,u,a),o=!0)}else{a=n.p;let e=c1(n,a1(n),s,c,0);!e&&!o&&l1(n,e,a),i1(n,!0,!0);let t=X$(n,void 0);e&&!o&&(e[1][e[0]]=t)}i1(n,!0),n.p<e.length&&(a=e.charCodeAt(n.p))!==10&&(a!==13||e.charCodeAt(n.p+1)!==10)&&Q.x(`each key-value declaration must be followed by an end-of-line`,n),i1(n)}return r}``.isWellFormed;
400
+ function u1(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if(a=c?a[s]:a[s]=Object.create(null),o=(l=o[s]).c,i===0&&(l.t===1||l.t===2))return null;if(l.t===2){let e=a.length-1;a=a[e],o=o[e].c}}if(s=t[n],(c=Object.hasOwn(a,s))&&o[s]?.t===0&&o[s]?.d)return null;if(!c){let r=s===`__proto__`;if(e.uk&&(r||s===`constructor`))return!1;r&&(Object.defineProperty(a,s,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})),o[s]={t:n<t.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(l=o[s],l.t!==i&&!(i===1&&l.t===3)||(i===2&&(l.d||(l.d=!0,a[s]=[]),a[s].push(a=Object.create(null)),l.c[l.i++]=l={t:1,d:!1,i:0,c:Object.create(null)}),l.d))return null;if(l.d=!0,i===1)a=c?a[s]:a[s]=Object.create(null);else if(i===0&&c)return null;return[s,a,l.c]}function d1(e,t,n){(t===null||e.uk===2)&&Q.x(t===null?`trying to redefine an already defined table or value`:`document contains an unsafe property`,e,n)}function f1(e,t={}){let n={s:e,p:0,d:t.maxDepth??1e3,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour===`throw`?2:+(t.unsafeKeyBehaviour===`drop`)},r=Object.create(null),i=Object.create(null),a,o=!1,s=r,c=i;for(e.charCodeAt(0)===65279&&n.p++,o1(n);n.p<e.length;){if(e.charCodeAt(n.p)===91){let t=e.charCodeAt(++n.p)===91;a=n.p+=+t,o=!1;let l=s1(n,93);t&&(e.charCodeAt(n.p)!==93&&Q.x(`expected end of table array declaration`,n),n.p++);let u=u1(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(d1(n,u,a),o=!0)}else{a=n.p;let e=u1(n,s1(n),s,c,0);!e&&!o&&d1(n,e,a),o1(n,!0,!0);let t=Q$(n,void 0);e&&!o&&(e[1][e[0]]=t)}o1(n,!0),n.p<e.length&&(a=e.charCodeAt(n.p))!==10&&(a!==13||e.charCodeAt(n.p+1)!==10)&&Q.x(`each key-value declaration must be followed by an end-of-line`,n),o1(n)}return r}``.isWellFormed;
401
401
  /*!
402
402
  * Copyright (c) Squirrel Chat et al., All rights reserved.
403
403
  * SPDX-License-Identifier: BSD-3-Clause
@@ -425,7 +425,7 @@ function c1(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if
425
425
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
426
426
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
427
427
  */
428
- const d1=e=>e.codePointAt(0).toString(16).toUpperCase(),f1=String.raw`
428
+ const p1=e=>e.codePointAt(0).toString(16).toUpperCase(),m1=String.raw`
429
429
  ObjC.import("AppKit");
430
430
  ObjC.import("CoreText");
431
431
  function lacksOf(font, points) {
@@ -472,49 +472,49 @@ function run(argv) {
472
472
  : iterm(argv[1], points),
473
473
  );
474
474
  }
475
- `;function p1(e){let t=D({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,f1,...e],timeoutMs:3e3,category:`doctor.font`});if(!t.ok){if(t.reason===`rate-limited`)throw new P$(`the font`);return{kind:`failed`,reason:`osascript failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}let n;try{n=JSON.parse(t.stdout)}catch{return{kind:`failed`,reason:`osascript answered ${JSON.stringify(t.stdout.trim())}, not JSON`}}return typeof n==`object`&&n&&`error`in n?{kind:`failed`,reason:n.error}:{kind:`ok`,value:n}}const m1=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),h1=e=>[...e].map(d1).join(`,`);function g1(e,t){let n=p1([`font`,e.kind,e.name,h1(t)]);if(n.kind===`failed`)return n;let{lacks:r}=n.value;return{kind:`ok`,value:{font:e.name,lacks:r===null?null:m1(r)}}}function _1(e,t){if(e.font===null)return{kind:`failed`,reason:`iTerm2 profile ${JSON.stringify(e.name)} names no font`};let n=`iTerm2 profile ${JSON.stringify(e.name)}`+(e.nonAscii?`, its non-ASCII font`:``)+(e.powerline?`, built-in Powerline glyphs on`:``),r=e.lacks===null||!e.powerline?e.lacks:e.lacks.filter(e=>!OM(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const v1=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function y1(e,t,n){if(e.length===0)return{kind:`failed`,reason:t===null?`iTerm2 has no profiles in its preferences`:`iTerm2 has no profile named ${JSON.stringify(t)}`};let r=e.map(e=>_1(e,n));if(t!==null)return r[0];let i=r.find(e=>!v1(e));return i===void 0?{kind:`ok`,value:{font:[...new Set(r.flatMap(e=>e.kind===`ok`?[e.value.font]:[]))].join(`, `),from:`every iTerm2 profile, since the session does not say which draws the bar`,lacks:[]}}:i.kind===`failed`?i:{kind:`ok`,value:{...i.value,from:`${i.value.from}, one of its profiles, and the session does not say which draws the bar`}}}function b1(e,t,n){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let r=t.ITERM_PROFILE??null,i=p1([`iterm`,r??``,h1(n)]);return i.kind===`failed`?i:y1(i.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:m1(e.lacks)})),r,e)}function x1(e,t){let n=e.split(`
476
- `).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const S1=e=>e.replace(/[\\:,=-]/g,`\\$&`);function C1(e,t){let n=D({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
477
- `,`:family=${S1(e)}`],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new P$(`the font`);return{kind:`failed`,reason:`fc-match failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}return x1(n.stdout,t)}function w1(e,t){return process.platform===`darwin`?g1(e,t):C1(e.name,t)}function T1(e,t){let n=t||s.join(e,`.config`);return[s.join(n,`alacritty`,`alacritty.toml`),s.join(n,`alacritty.toml`),s.join(e,`.config`,`alacritty`,`alacritty.toml`),s.join(e,`.alacritty.toml`)]}function E1(e){return e===`darwin`?`Menlo`:`monospace`}const D1=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function O1(e){let t=D1(e.font)?e.font:{},n=D1(t.normal)?t.normal:{},r=(D1(e.general)?e.general:{}).import??e.import??[];return{family:typeof n.family==`string`?n.family:null,imports:Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}}function k1(e,t,n){let r;try{r=p.readFileSync(e,`utf8`)}catch(t){return{kind:`failed`,reason:`cannot read ${e}: ${t.message}`}}let i;try{i=u1(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=O1(i);if(a.family!==null)return{kind:`ok`,value:{family:a.family,from:e}};if(n===5)return{kind:`ok`,value:null};let o=null;for(let r of a.imports){let i=r.startsWith(`~/`)?s.join(t,r.slice(2)):s.resolve(s.dirname(e),r);if(!p.existsSync(i))continue;let a=k1(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}function A1(e,t){let n=C.homedir(),r=T1(n,e.XDG_CONFIG_HOME).find(e=>p.existsSync(e)),i=r===void 0?{kind:`ok`,value:null}:k1(r,n,0);if(i.kind===`failed`)return i;let a=i.value?.family??E1(process.platform),o=i.value?.from??(r===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${r} sets none`),s=w1({kind:`family`,name:a},t);if(s.kind===`failed`)return s;let{font:c,lacks:l}=s.value;return{kind:`ok`,value:{font:c,from:c===a?o:`${o}; ${a} as fontconfig matches it`,lacks:l}}}const j1={iterm2:b1,alacritty:(e,t,n)=>A1(t,n)};function M1(e,t,n){return j1[e.name](e.version,t,n)}function N1(e){let t=e?.through;return typeof t==`string`||t===null?{kind:`ok`,value:{through:t}}:{kind:`failed`,reason:`names no post-mortem read`}}const P1=e=>E$(e,`doctor-post-mortems-read.json`,{through:null},N1);function F1(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const I1={realpath:e=>F1(()=>p.realpathSync(e)),checkoutOf:Qe,digest:e=>F1(()=>Ye(e)),nativeShipped:vo(process.platform,process.arch)};function L1(e,t,n){let r=e.realpath(t);if(r.kind===`failed`)return{kind:`failed`,reason:`the daemon's bundle ${t} cannot be resolved: ${r.reason}`};let i=e.checkoutOf(r.value);return{kind:`ok`,value:{daemon:{bundle:r.value,checkout:i===null?null:{root:i,rustSource:e.digest(s.join(i,`rust-client`))}},nativeShipped:e.nativeShipped,clients:n.map(t=>t===null?{kind:`unreported`}:{kind:`reported`,client:t.kind,bundle:e.realpath(t.bundle),source:t.source})}}}const R1=e=>({marks:A$(e),clicked:N$(e),postMortemsRead:P1(e)}),z1=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function B1(e){let t=e.replace(/\n$/,``);if(t===` `)return{kind:`ok`,value:null};let n=t.split(` `),[r,i,a,o,s]=n;return n.length!==5||!/^[1-9]\d*$/.test(o)||!/^[01]$/.test(s)?{kind:`failed`,reason:`tmux answered ${JSON.stringify(e)}, not the five fields asked for`}:{kind:`ok`,value:{features:r.split(`,`).filter(e=>e!==``),termtype:i,termname:a,pid:Number(o),utf8:s===`1`}}}const V1=/^(sshd|mosh-server)\b/;function H1(e,t){let n=z$(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of B$(n,t))if(V1.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}function U1(e){let t=D({bin:`ps`,args:[`-A`,`-o`,`pid=,ppid=,comm=`],timeoutMs:2e3,category:`doctor.process`});if(!t.ok){if(t.reason===`rate-limited`)throw new P$(`the processes`);return{kind:`failed`,reason:`ps failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}return H1(t.stdout,e)}const W1=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function G1(e,t){let n=[];for(let r of e.split(`
478
- `)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function K1(e){let t;try{t=p.realpathSync(e)}catch{return!1}let n=W1.exec(t)?.[1];return n!==void 0&&p.existsSync(s.join(n,`bin`,`cc-candybar`))}function q1(){let e=D({bin:`ps`,args:[`-U`,String(C.userInfo().uid),`-ww`,`-o`,`pid=,ppid=,rss=,lstart=,args=`],timeoutMs:2e3,category:`doctor.daemons`,env:{...process.env,LC_ALL:`C`,TZ:`UTC`}});return e.ok?{kind:`ok`,value:G1(e.stdout,K1)}:{kind:`failed`,reason:`ps failed (${e.error??`${e.reason}: ${e.stderr.trim()}`})`}}function J1(e){let t=NK(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures} #{client_termtype} #{client_termname} #{client_pid} #{client_utf8}`]);if(t.kind===`rate-limited`)throw new P$(`tmux`);return t.kind===`failed`?{kind:`failed`,reason:t.reason}:B1(t.stdout)}function Y1(e){return{probeTmux:J1,remoteLogin:U1,fontInUse:M1,loadConfig:e,managedSettingsDir:process.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??no(process.platform),install:I1,daemons:q1,forge:e0,transcript:Z1}}function X1(e,t){let n=e.toString(`utf-8`),r=t?0:n.indexOf(`
475
+ `;function h1(e){let t=D({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,m1,...e],timeoutMs:3e3,category:`doctor.font`});if(!t.ok){if(t.reason===`rate-limited`)throw new I$(`the font`);return{kind:`failed`,reason:`osascript failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}let n;try{n=JSON.parse(t.stdout)}catch{return{kind:`failed`,reason:`osascript answered ${JSON.stringify(t.stdout.trim())}, not JSON`}}return typeof n==`object`&&n&&`error`in n?{kind:`failed`,reason:n.error}:{kind:`ok`,value:n}}const g1=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),_1=e=>[...e].map(p1).join(`,`);function v1(e,t){let n=h1([`font`,e.kind,e.name,_1(t)]);if(n.kind===`failed`)return n;let{lacks:r}=n.value;return{kind:`ok`,value:{font:e.name,lacks:r===null?null:g1(r)}}}function y1(e,t){if(e.font===null)return{kind:`failed`,reason:`iTerm2 profile ${JSON.stringify(e.name)} names no font`};let n=`iTerm2 profile ${JSON.stringify(e.name)}`+(e.nonAscii?`, its non-ASCII font`:``)+(e.powerline?`, built-in Powerline glyphs on`:``),r=e.lacks===null||!e.powerline?e.lacks:e.lacks.filter(e=>!kM(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const b1=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function x1(e,t,n){if(e.length===0)return{kind:`failed`,reason:t===null?`iTerm2 has no profiles in its preferences`:`iTerm2 has no profile named ${JSON.stringify(t)}`};let r=e.map(e=>y1(e,n));if(t!==null)return r[0];let i=r.find(e=>!b1(e));return i===void 0?{kind:`ok`,value:{font:[...new Set(r.flatMap(e=>e.kind===`ok`?[e.value.font]:[]))].join(`, `),from:`every iTerm2 profile, since the session does not say which draws the bar`,lacks:[]}}:i.kind===`failed`?i:{kind:`ok`,value:{...i.value,from:`${i.value.from}, one of its profiles, and the session does not say which draws the bar`}}}function S1(e,t,n){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let r=t.ITERM_PROFILE??null,i=h1([`iterm`,r??``,_1(n)]);return i.kind===`failed`?i:x1(i.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:g1(e.lacks)})),r,e)}function C1(e,t){let n=e.split(`
476
+ `).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const w1=e=>e.replace(/[\\:,=-]/g,`\\$&`);function T1(e,t){let n=D({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
477
+ `,`:family=${w1(e)}`],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new I$(`the font`);return{kind:`failed`,reason:`fc-match failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}return C1(n.stdout,t)}function E1(e,t){return process.platform===`darwin`?v1(e,t):T1(e.name,t)}function D1(e,t){let n=t||s.join(e,`.config`);return[s.join(n,`alacritty`,`alacritty.toml`),s.join(n,`alacritty.toml`),s.join(e,`.config`,`alacritty`,`alacritty.toml`),s.join(e,`.alacritty.toml`)]}function O1(e){return e===`darwin`?`Menlo`:`monospace`}const k1=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function A1(e){let t=k1(e.font)?e.font:{},n=k1(t.normal)?t.normal:{},r=(k1(e.general)?e.general:{}).import??e.import??[];return{family:typeof n.family==`string`?n.family:null,imports:Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}}function j1(e,t,n){let r;try{r=p.readFileSync(e,`utf8`)}catch(t){return{kind:`failed`,reason:`cannot read ${e}: ${t.message}`}}let i;try{i=f1(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=A1(i);if(a.family!==null)return{kind:`ok`,value:{family:a.family,from:e}};if(n===5)return{kind:`ok`,value:null};let o=null;for(let r of a.imports){let i=r.startsWith(`~/`)?s.join(t,r.slice(2)):s.resolve(s.dirname(e),r);if(!p.existsSync(i))continue;let a=j1(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}function M1(e,t){let n=C.homedir(),r=D1(n,e.XDG_CONFIG_HOME).find(e=>p.existsSync(e)),i=r===void 0?{kind:`ok`,value:null}:j1(r,n,0);if(i.kind===`failed`)return i;let a=i.value?.family??O1(process.platform),o=i.value?.from??(r===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${r} sets none`),s=E1({kind:`family`,name:a},t);if(s.kind===`failed`)return s;let{font:c,lacks:l}=s.value;return{kind:`ok`,value:{font:c,from:c===a?o:`${o}; ${a} as fontconfig matches it`,lacks:l}}}const N1={iterm2:S1,alacritty:(e,t,n)=>M1(t,n)};function P1(e,t,n){return N1[e.name](e.version,t,n)}function F1(e){let t=e?.through;return typeof t==`string`||t===null?{kind:`ok`,value:{through:t}}:{kind:`failed`,reason:`names no post-mortem read`}}const I1=e=>O$(e,`doctor-post-mortems-read.json`,{through:null},F1);function L1(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const R1={realpath:e=>L1(()=>p.realpathSync(e)),checkoutOf:Qe,digest:e=>L1(()=>Ye(e)),nativeShipped:vo(process.platform,process.arch)};function z1(e,t,n){let r=e.realpath(t);if(r.kind===`failed`)return{kind:`failed`,reason:`the daemon's bundle ${t} cannot be resolved: ${r.reason}`};let i=e.checkoutOf(r.value);return{kind:`ok`,value:{daemon:{bundle:r.value,checkout:i===null?null:{root:i,rustSource:e.digest(s.join(i,`rust-client`))}},nativeShipped:e.nativeShipped,clients:n.map(t=>t===null?{kind:`unreported`}:{kind:`reported`,client:t.kind,bundle:e.realpath(t.bundle),source:t.source})}}}const B1=e=>({marks:M$(e),clicked:F$(e),postMortemsRead:I1(e)}),V1=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function H1(e){let t=e.replace(/\n$/,``);if(t===` `)return{kind:`ok`,value:null};let n=t.split(` `),[r,i,a,o,s]=n;return n.length!==5||!/^[1-9]\d*$/.test(o)||!/^[01]$/.test(s)?{kind:`failed`,reason:`tmux answered ${JSON.stringify(e)}, not the five fields asked for`}:{kind:`ok`,value:{features:r.split(`,`).filter(e=>e!==``),termtype:i,termname:a,pid:Number(o),utf8:s===`1`}}}const U1=/^(sshd|mosh-server)\b/;function W1(e,t){let n=V$(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of H$(n,t))if(U1.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}function G1(e){let t=D({bin:`ps`,args:[`-A`,`-o`,`pid=,ppid=,comm=`],timeoutMs:2e3,category:`doctor.process`});if(!t.ok){if(t.reason===`rate-limited`)throw new I$(`the processes`);return{kind:`failed`,reason:`ps failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}return W1(t.stdout,e)}const K1=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function q1(e,t){let n=[];for(let r of e.split(`
478
+ `)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function J1(e){let t;try{t=p.realpathSync(e)}catch{return!1}let n=K1.exec(t)?.[1];return n!==void 0&&p.existsSync(s.join(n,`bin`,`cc-candybar`))}function Y1(){let e=D({bin:`ps`,args:[`-U`,String(C.userInfo().uid),`-ww`,`-o`,`pid=,ppid=,rss=,lstart=,args=`],timeoutMs:2e3,category:`doctor.daemons`,env:{...process.env,LC_ALL:`C`,TZ:`UTC`}});return e.ok?{kind:`ok`,value:q1(e.stdout,J1)}:{kind:`failed`,reason:`ps failed (${e.error??`${e.reason}: ${e.stderr.trim()}`})`}}function X1(e){let t=FK(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures} #{client_termtype} #{client_termname} #{client_pid} #{client_utf8}`]);if(t.kind===`rate-limited`)throw new I$(`tmux`);return t.kind===`failed`?{kind:`failed`,reason:t.reason}:H1(t.stdout)}function Z1(e){return{probeTmux:X1,remoteLogin:G1,fontInUse:P1,loadConfig:e,managedSettingsDir:process.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??no(process.platform),install:R1,daemons:Y1,forge:n0,transcript:$1}}function Q1(e,t){let n=e.toString(`utf-8`),r=t?0:n.indexOf(`
479
479
  `)+1,i=n.lastIndexOf(`
480
480
  `)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
481
- `)){let t=zG(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function Z1(e){let t=Ka(e,KM+1);return t.kind===`ok`?P(X1(t.value.buf,t.value.fromStart)):t}function Q1(e,t){if(t.kind===`failed`)return t;let n=new Map;for(let{path:e,answered:r}of t.value)n.set(e,r||(n.get(e)??!1));return{kind:`ok`,value:[...n].map(([t,n])=>({path:t,answered:n,read:e.transcript(t)}))}}const $1={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};function e0(e){if(RV(e)===void 0)return{kind:`ok`,value:null};let t=MW(D({bin:`git`,args:[...jW],cwd:e,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(t.kind===`failed`)return t;let n=LW(t.value);if(n===null)return{kind:`ok`,value:null};let r=AW(n);if(r===null)return{kind:`ok`,value:null};let i=TW[r],a=$1[r],o=a.loginHost(kW(n)),s=D({bin:i,args:[...a.args(o)],cwd:e,timeoutMs:2e3,category:`doctor.forge`});return t0(i,o,a.nonZero,s)}function t0(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):EW(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:SW(r.stderr)}):{kind:`failed`,reason:xW(e,r)}}function n0(e){let t={layers:e.layers,warnings:e.warning===null?[]:e.warning.split(`
482
- `)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}const r0=e=>F1(()=>io(e));function i0(e,t){let n=e=>JSON.stringify([e.managedDir,e.projectDir,e.userFile]),r=n(e),i=[],a=new Map;for(let o of t){let t={managedDir:e.managedDir,projectDir:o.projectDir,userFile:Xa(o.claudeConfigDir)},s=n(t);if(s===r)i.push(o);else{let e=a.get(s)??{at:t,bars:[]};e.bars.push(o),a.set(s,e)}}let o=(e,t)=>({at:e,sources:r0(e),bars:t.map(({role:e,frame:t})=>({role:e,frame:t}))});return{origin:o(e,i),elsewhere:[...a.values()].map(({at:e,bars:t})=>o(e,t))}}function a0(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:e.probeTmux(t)}}function o0(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:FM(t),tmuxClient:null};case`inside`:{if(e.client.kind===`failed`)return{kind:`unasked`,reason:e.client.reason};let t=e.client.value;return t===null?{kind:`unasked`,reason:`tmux has no client attached to the pane's session`}:{kind:`seen`,identified:PM(t),tmuxClient:t}}}}function s0(e,t,n,r){if(t.kind!==`seen`)return t;let{identified:i,tmuxClient:a}=t,o=n.terminalEnv;if(i.kind!==`known`)return i;let{name:s,version:c}=i.terminal;if(wM(s))return{kind:`bundling`,name:s,version:c};if(!TM(s))return{kind:`unread`,name:s,version:c};let{ITERM_PROFILE:l,...u}=o??{},d=a===null?{kind:`ok`,value:n.ssh===!0}:e.remoteLogin(a.pid);return{kind:`configured`,name:s,version:c,font:d.kind===`failed`?{kind:`failed`,reason:`whether the terminal is remote could not be asked: ${d.reason}`}:d.value?{kind:`failed`,reason:`the terminal is on the far side of a remote login, so its font is on the machine it runs on`}:e.fontInUse({name:s,version:c},a===null?o??{}:u,r)}}function c0(e){switch(e.via){case`link`:return{kind:`arrived`,handler:e.handler,bar:Ze};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}function l0(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:t()}}function u0(e,t,n,r){return{pullRequests:l0(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:l0(t.rateLimits,()=>r)}}function d0(e,t){let n=t.find(e=>e.role===`statusline`);return n===void 0?{kind:`failed`,reason:`the daemon holds no statusline render of session ${e} — none since it started, or dropped for newer sessions' renders, or only a frames display draws it, which reports no width — so no width a statusline client measured is known; run this again once the statusline has redrawn`}:{kind:`ok`,value:{columns:n.termCols,of:{kind:`session`,sessionId:e}}}}function f0(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=FH(d.config,r,()=>!1),p=a0(e,t.tmux),m=o0(p,t.terminalEnv),h=[...new Set([...db(f),...ub(JSON.stringify(d.config))])].join(``);return{tmux:p,width:l,terminal:m,nerdFont:h===``?{kind:`none`}:{kind:`glyphs`,glyphs:h,terminal:s0(e,m,t,h)},marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:e.daemons(),read:u.postMortemsRead},config:n0(d),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:u0(e,H$(d.config,f.preset),n,a),transcripts:Q1(e,o),claudeSettings:i0({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Xa(Ya(t.claudeConfigDir))},c.kind===`ok`?c.value:[])}}function p0(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;gt(e,pa($a(e),t.path,JSON.stringify(t.value),Qi));let r=e=>({...e,sources:r0(e.at)}),{origin:i,elsewhere:a}=n.claudeSettings;return{kind:`ok`,value:{...n,claudeSettings:{origin:r(i),elsewhere:a.map(r)}}}}case`post-mortems-read`:{let r=e.postMortemsRead.update(e=>e.through===null||ir(t.through,e.through)?{through:t.through}:e);return r.kind===`failed`?r:{kind:`ok`,value:{...n,daemon:{...n.daemon,read:r}}}}default:return t}}const m0={connectMs:200,budgetMs:500};async function h0(e){let n=e.includes(`--json`),r=await g0();r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${un(r)}\n`),t.exit(1)),n&&t.stdout.write(JSON.stringify(r.value,null,2)+`
483
- `);let i=_0(r.value);if(i!==null){t.stderr.write(`daemon-stats: ${i}\n`),t.exitCode=1;return}n||t.stdout.write(T0(r.value))}function g0(){return rn(()=>({kind:`stats`}),m0,e=>`stats`in e?e.stats:void 0)}function _0(e,t=v0){let n=PZ.referenceSnapshot(),r=y0(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=x0(e.version,e.sourceDigest??null),a=x0(Ze,et());return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}const v0=Object.keys(PZ.referenceSnapshot());function y0(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!b0(e))return[];if(!b0(t))return[n||`<snapshot>`];if(`kind`in e)return[];let r=[];for(let i of Object.keys(e)){let a=n===``?i:`${n}.${i}`;i in t?r.push(...y0(e[i],t[i],a)):r.push(a)}return r}function b0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function x0(e,t){return`${e} [${t===null?`no digest`:Xe(t)}]`}function S0(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function C0(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function w0(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${e%60}s`:`${Math.floor(e/3600)}h${Math.floor(e%3600/60)}m`}function T0(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${x0(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${w0(e.uptimeSec)}`),t.push(` rss ${S0(e.rssBytes)}`),t.push(` heapUsed ${S0(e.heapUsedBytes)}`),t.push(` heapTotal ${S0(e.heapTotalBytes)}`),t.push(` external ${S0(e.externalBytes)}`),t.push(` arrayBuffers ${S0(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${C0(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` changes ${e.gitCache.changes}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${C0(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`sources`);for(let n of e.sources.records){let e=Object.entries(n.refreshes).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` ${`${n.scope}/${n.name}`.padEnd(24)} failures=${n.failures} last=${n.lastMs===null?`-`:`${n.lastMs}ms`} refreshes ${e}`)}let n=Object.entries(e.sources.homes).map(([e,t])=>`${e}:${t}`).join(` `),r=Object.entries(e.sources.held).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` homes ${n}`),t.push(` held ${r}`);let i=e.sources.pluginStorage,a=Object.entries(i.faults).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` plugin storage folders=${i.folders} lost=${i.lost} faults ${a}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${S0(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${S0(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` views ${e.renderCache.views}`),t.push(` pinned ${e.renderCache.pinned}`),t.push(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${S0(e.renderCache.accountedBytes)} / ${S0(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`menuIdle`),t.push(` sessions ${e.menuIdle.sessions}`),t.push(` armed ${e.menuIdle.armed}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` refused ${e.watchers.refused}`),t.push(` errors ${e.watchers.errors}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let o=Object.entries(e.subprocesses.byCategory),s=o.reduce((e,[t])=>Math.max(e,t.length),13);for(let[n,r]of o){let i=e.subprocesses.p50DurationMs[n],a=e.subprocesses.p99DurationMs[n],o=i!==void 0&&a!==void 0?` (p50 ${i}ms · p99 ${a}ms)`:``;t.push(` ${n.padEnd(s)} ${r}${o}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
481
+ `)){let t=VG(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function $1(e){let t=Ka(e,qM+1);return t.kind===`ok`?P(Q1(t.value.buf,t.value.fromStart)):t}function e0(e,t){if(t.kind===`failed`)return t;let n=new Map;for(let{path:e,answered:r}of t.value)n.set(e,r||(n.get(e)??!1));return{kind:`ok`,value:[...n].map(([t,n])=>({path:t,answered:n,read:e.transcript(t)}))}}const t0={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};function n0(e){if(BV(e)===void 0)return{kind:`ok`,value:null};let t=PW(D({bin:`git`,args:[...NW],cwd:e,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(t.kind===`failed`)return t;let n=zW(t.value);if(n===null)return{kind:`ok`,value:null};let r=MW(n);if(r===null)return{kind:`ok`,value:null};let i=DW[r],a=t0[r],o=a.loginHost(jW(n)),s=D({bin:i,args:[...a.args(o)],cwd:e,timeoutMs:2e3,category:`doctor.forge`});return r0(i,o,a.nonZero,s)}function r0(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):OW(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:wW(r.stderr)}):{kind:`failed`,reason:CW(e,r)}}function i0(e){let t={layers:e.layers,warnings:e.warning===null?[]:e.warning.split(`
482
+ `)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}const a0=e=>L1(()=>io(e));function o0(e,t){let n=e=>JSON.stringify([e.managedDir,e.projectDir,e.userFile]),r=n(e),i=[],a=new Map;for(let o of t){let t={managedDir:e.managedDir,projectDir:o.projectDir,userFile:Xa(o.claudeConfigDir)},s=n(t);if(s===r)i.push(o);else{let e=a.get(s)??{at:t,bars:[]};e.bars.push(o),a.set(s,e)}}let o=(e,t)=>({at:e,sources:a0(e),bars:t.map(({role:e,frame:t})=>({role:e,frame:t}))});return{origin:o(e,i),elsewhere:[...a.values()].map(({at:e,bars:t})=>o(e,t))}}function s0(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:e.probeTmux(t)}}function c0(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:IM(t),tmuxClient:null};case`inside`:{if(e.client.kind===`failed`)return{kind:`unasked`,reason:e.client.reason};let t=e.client.value;return t===null?{kind:`unasked`,reason:`tmux has no client attached to the pane's session`}:{kind:`seen`,identified:FM(t),tmuxClient:t}}}}function l0(e,t,n,r){if(t.kind!==`seen`)return t;let{identified:i,tmuxClient:a}=t,o=n.terminalEnv;if(i.kind!==`known`)return i;let{name:s,version:c}=i.terminal;if(TM(s))return{kind:`bundling`,name:s,version:c};if(!EM(s))return{kind:`unread`,name:s,version:c};let{ITERM_PROFILE:l,...u}=o??{},d=a===null?{kind:`ok`,value:n.ssh===!0}:e.remoteLogin(a.pid);return{kind:`configured`,name:s,version:c,font:d.kind===`failed`?{kind:`failed`,reason:`whether the terminal is remote could not be asked: ${d.reason}`}:d.value?{kind:`failed`,reason:`the terminal is on the far side of a remote login, so its font is on the machine it runs on`}:e.fontInUse({name:s,version:c},a===null?o??{}:u,r)}}function u0(e){switch(e.via){case`link`:return{kind:`arrived`,handler:e.handler,bar:Ze};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}function d0(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:t()}}function f0(e,t,n,r){return{pullRequests:d0(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:d0(t.rateLimits,()=>r)}}function p0(e,t){let n=t.find(e=>e.role===`statusline`);return n===void 0?{kind:`failed`,reason:`the daemon holds no statusline render of session ${e} — none since it started, or dropped for newer sessions' renders, or only a frames display draws it, which reports no width — so no width a statusline client measured is known; run this again once the statusline has redrawn`}:{kind:`ok`,value:{columns:n.termCols,of:{kind:`session`,sessionId:e}}}}function m0(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=LH(d.config,r,()=>!1),p=s0(e,t.tmux),m=c0(p,t.terminalEnv),h=[...new Set([...db(f),...ub(JSON.stringify(d.config))])].join(``);return{tmux:p,width:l,terminal:m,nerdFont:h===``?{kind:`none`}:{kind:`glyphs`,glyphs:h,terminal:l0(e,m,t,h)},marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:e.daemons(),read:u.postMortemsRead},config:i0(d),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:f0(e,W$(d.config,f.preset),n,a),transcripts:e0(e,o),claudeSettings:o0({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Xa(Ya(t.claudeConfigDir))},c.kind===`ok`?c.value:[])}}function h0(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;gt(e,pa($a(e),t.path,JSON.stringify(t.value),Qi));let r=e=>({...e,sources:a0(e.at)}),{origin:i,elsewhere:a}=n.claudeSettings;return{kind:`ok`,value:{...n,claudeSettings:{origin:r(i),elsewhere:a.map(r)}}}}case`post-mortems-read`:{let r=e.postMortemsRead.update(e=>e.through===null||ir(t.through,e.through)?{through:t.through}:e);return r.kind===`failed`?r:{kind:`ok`,value:{...n,daemon:{...n.daemon,read:r}}}}default:return t}}const g0={connectMs:200,budgetMs:500};async function _0(e){let n=e.includes(`--json`),r=await v0();r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${un(r)}\n`),t.exit(1)),n&&t.stdout.write(JSON.stringify(r.value,null,2)+`
483
+ `);let i=y0(r.value);if(i!==null){t.stderr.write(`daemon-stats: ${i}\n`),t.exitCode=1;return}n||t.stdout.write(D0(r.value))}function v0(){return rn(()=>({kind:`stats`}),g0,e=>`stats`in e?e.stats:void 0)}function y0(e,t=b0){let n=IZ.referenceSnapshot(),r=x0(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=C0(e.version,e.sourceDigest??null),a=C0(Ze,et());return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}const b0=Object.keys(IZ.referenceSnapshot());function x0(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!S0(e))return[];if(!S0(t))return[n||`<snapshot>`];if(`kind`in e)return[];let r=[];for(let i of Object.keys(e)){let a=n===``?i:`${n}.${i}`;i in t?r.push(...x0(e[i],t[i],a)):r.push(a)}return r}function S0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function C0(e,t){return`${e} [${t===null?`no digest`:Xe(t)}]`}function w0(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function T0(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function E0(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${e%60}s`:`${Math.floor(e/3600)}h${Math.floor(e%3600/60)}m`}function D0(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${C0(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${E0(e.uptimeSec)}`),t.push(` rss ${w0(e.rssBytes)}`),t.push(` heapUsed ${w0(e.heapUsedBytes)}`),t.push(` heapTotal ${w0(e.heapTotalBytes)}`),t.push(` external ${w0(e.externalBytes)}`),t.push(` arrayBuffers ${w0(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(` unknownFields ${e.unknownHookFields.map(e=>JSON.stringify(e)).join(`, `)||`-`}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${T0(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` changes ${e.gitCache.changes}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${T0(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`sources`);for(let n of e.sources.records){let e=Object.entries(n.refreshes).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` ${`${n.scope}/${n.name}`.padEnd(24)} failures=${n.failures} last=${n.lastMs===null?`-`:`${n.lastMs}ms`} refreshes ${e}`)}let n=Object.entries(e.sources.homes).map(([e,t])=>`${e}:${t}`).join(` `),r=Object.entries(e.sources.held).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` homes ${n}`),t.push(` held ${r}`);let i=e.sources.pluginStorage,a=Object.entries(i.faults).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` plugin storage folders=${i.folders} lost=${i.lost} faults ${a}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${w0(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${w0(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` views ${e.renderCache.views}`),t.push(` pinned ${e.renderCache.pinned}`),t.push(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${w0(e.renderCache.accountedBytes)} / ${w0(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`menuIdle`),t.push(` sessions ${e.menuIdle.sessions}`),t.push(` armed ${e.menuIdle.armed}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` refused ${e.watchers.refused}`),t.push(` errors ${e.watchers.errors}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let o=Object.entries(e.subprocesses.byCategory),s=o.reduce((e,[t])=>Math.max(e,t.length),13);for(let[n,r]of o){let i=e.subprocesses.p50DurationMs[n],a=e.subprocesses.p99DurationMs[n],o=i!==void 0&&a!==void 0?` (p50 ${i}ms · p99 ${a}ms)`:``;t.push(` ${n.padEnd(s)} ${r}${o}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
484
484
  `)+`
485
- `}const E0=e=>({kind:`ok`,value:e}),D0=e=>({kind:`failed`,reason:e});var O0=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const k0=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function A0(e){return k0.test(e)?e:null}function j0(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return E0(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return E0({app:n,missing:D0(`its script could not be read (${r.reason})`)});let i=ko(r.value);return E0({app:n,missing:i===null?D0("its script is not one `cc-candybar install` wrote"):E0([i.node,i.script].filter(t=>!e.exists(t)))})}async function M0(e,t){let n=e.now()+5e3;for(;e.now()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,handler:r.handler,bar:n.value.version}}return null}async function N0(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${Ir}://${ci}/${n}`);return(r===null?await M0(e,n):null)??{kind:`lost`,unopened:r,opener:j0(e)}}function P0(e,t,n){let r=D({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?E0(r.stdout):D0(r.stderr.trim()||r.error||r.reason)}const F0=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${Ir}://probe"));u.isNil() ? "" : u.path.js`;async function I0(){let e=await g0();if(e.kind!==`ok`)return D0(un(e).split(`
486
- `).join(` — `));let t=_0(e.value,[`handlerProbes`]);if(t!==null)return D0(t);let{version:n,handlerProbes:r}=e.value;return E0({version:n,arrivals:r})}function L0(){return{platform:process.platform,sockets:{own:St(),handler:Ct()},now:Date.now,nonce:ie,daemon:I0,open:e=>{let t=P0(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=P0(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,F0]);if(e.kind===`failed`)return e;let t=e.value.trim();return E0(t===``?null:t)},script:e=>P0(`doctor.osadecompile`,`/usr/bin/osadecompile`,[Ao(e)]),exists:p.existsSync}}const R0=/^─{20,}/,z0=/^❯(\s|$)/,B0=/›\s*stashed$/;function V0(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>R0.test(e)?[t]:[]).at(-2);return n===void 0||!z0.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function H0(e){if(e.inMode)return{kind:`in-mode`};let t=V0(e);return t===null?{kind:`no-prompt`}:B0.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function U0(e){return/^❯\s*\S/u.test(V0(e)?.prompt??``)}const W0=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function G0(e){return e.screen.some(e=>W0.test(e))}const K0={"in-mode":`the Claude Code pane is in tmux copy mode — leave it (q) and click again`,stashed:`Claude Code is holding a stashed prompt (ctrl+s) — restore or send it, then click again`,"no-prompt":`Claude Code is not at its prompt (a dialog or picker is open) — close it and click again`};function q0(e){return e===void 0?{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`}:e===null?{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only act in a tmux pane`}:{kind:`pane`,hint:e}}function J0(e,t,n){let r=q0(t);if(r.kind===`refused`)return r;let i=r.hint,a=H0(e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:K0[a.kind]};let o=e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}function Y0(e,t,n,r){let i=NK(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function X0(e){let t=Y0(e,`claude-input.read`,[`display`,`-p`,`-t`,e.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,e.pane]);if(t.kind===`rate-limited`)throw Error(t.reason);let[n=``,...r]=t.stdout.split(`
487
- `);return{inMode:n!==`0`,screen:r}}function Z0(e,t,n){return[`load-buffer`,`-b`,t,`-`,`;`,...n.length===0?[]:[`send-keys`,`-t`,e,...n,`;`],`paste-buffer`,`-p`,`-d`,`-b`,t,`-t`,e,`;`,`send-keys`,`-t`,e,`Enter`]}function Q0(e,t){let n=Y0(e,`claude-input.type`,Z0(e.pane,`cc-candybar-slash`,[`C-s`]),t);return n.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${n.reason})`}}function $0(){return{read:X0,type:Q0}}function e2(e){let t=fW(e);if(!t.ok)throw new q(`session id ${t.problem}`);return t.id}function t2(e){return n2(()=>decodeURIComponent(e))}function n2(e){try{return e()}catch(e){throw e instanceof URIError?new q(`malformed wire encoding: ${e.message}`):e}}function r2(e,t){let n=D({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const i2=(e,t)=>r2(t2(e),t),a2=(e,t)=>{let n=D({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,t2(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},o2=(e,t)=>r2(t2(e),t),s2=(e,t)=>r2(t2(e),t),c2=(e,t)=>{let n=e2(t2(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},l2=(e,t)=>{let[n=``,...r]=n2(()=>di(e)),i=e2(n),a=_U(w2(t,i));if(r.length===0)throw new q(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new q(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new q(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new q(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}p2(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},u2=/^-?\d+$/;function d2(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const f2=(e,t)=>{let[n=``,r=``,i=``]=n2(()=>di(e)),a=e2(n);if(!r)throw new q(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!u2.test(i))throw new q(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=w2(t,a),c=_U(s),l=c.rangeParamsFor(r);if(!l)throw new q(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&u2.test(u)?m2(l,parseInt(u,10)):h2(`step-state`,r,l,bU(s,e=>t.sessionState.get(a,e),r)),f=d2(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new q(`step-state: ${p.reason}`);p2(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function p2(e,t,n,r){let i=r.filter(e=>e.key.startsWith(kj));if(i.length===0)return;let a=XH(w2(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new q(`${n}: refused — ${a.join(`; `)}`)}function m2(e,t){return Math.max(e.min,Math.min(e.max,t))}function h2(e,t,n,r){if(r===null)return n.min;if(!u2.test(r))throw new q(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return m2(n,parseInt(r,10))}const g2=`render-origin`;function _2(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function v2(e){return JSON.stringify(e)}function y2(e){let t;try{t=JSON.parse(e)}catch{throw new q(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new q(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new q(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function b2(e,t){let n=S2(e,t);if(n===null)throw new q(`session ${t} has not rendered yet — no config to act on`);return n}function x2(e,t){let n=e.sessionState.get(t,g2);return n===null?null:y2(n)}function S2(e,t){let n=x2(e,t);return n===null?null:_2(n,e.sessionState,t)}function C2(e,t,n){let r=S2(e,t);if(r===null)return;let{path:i}=D2(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function w2(e,t){return e.configFor(b2(e,t))}function T2(e,t){let n=x2(e,t);if(n===null)return null;let r=()=>e.lanes.of(_2(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function E2(e,t){let n=S2(e,t);return n===null?g$:b$(e.configFor(n))}function D2(e){return KV(e.projectDir,e.cwd,e.configFile??void 0)}function O2(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const k2=(e,t)=>{let[n=``,r=``,i=``]=n2(()=>di(e)),a=e2(n),o=b2(t,a),s=t.configFor(o),c=qI(s);if(!r)throw new q(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new q(`set-config: ${l.reason}`);let u=D2(o),d=JH(s,e=>t.sessionState.get(a,e),r);DQ(O2(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},A2=(e,t)=>{let[n=``,r=``,i=``]=n2(()=>di(e)),a=e2(n);if(!r)throw new q(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!u2.test(i))throw new q(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=b2(t,a),c=t.configFor(s),l=qI(c),u=l.rangeParamsFor(r);if(!u)throw new q(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=D2(s),f=JH(c,e=>t.sessionState.get(a,e),r),p=EQ(d.path,f.key),m=typeof p==`number`?m2(u,p):h2(`step-config`,r,u,YI(f.globals,r)),h=d2(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new q(`step-config: ${g.reason}`);DQ(O2(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.dlog(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},j2=(e,t)=>{let[n=``]=n2(()=>di(e)),r=e2(n),i=b2(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=KH(a,o),c=YH(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=_U(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new q(`save: ${t.reason}`);return[e.target,t.value]});N2(`save`,l,c);let d=D2(i);OQ(O2(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.dlog(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(M2)].join(` `)} → ${d.path} (session=${r})`)},M2=e=>`${e.preset}/${e.id}.settings.${e.setting}=${G_(e.value)}`;function N2(e,t,n){for(let r of n){let n=t.validate(r.key,G_(r.value));if(!n.ok)throw new q(`${e}: ${n.reason}`)}}const P2=(e,t)=>{let[n=``]=n2(()=>di(e)),r=e2(n),i=b2(t,r),a=t.configFor(i),o=$H(a,e=>t.sessionState.get(r,e)),s=_U(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new q(`save-preset: ${t.reason}`);return[e.configKey,t.value]});N2(`save-preset`,s,o.placements);let l=D2(i),u=FQ(O2(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...wy.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Sy.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(M2)].join(` `)} → ${l.path} (session=${r})`)},F2=(e,t)=>{let[n=``]=n2(()=>di(e)),r=e2(n),i=b2(t,r),a=tU(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new q(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=D2(i);IQ(O2(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(KH(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=hy.map(e=>Sy[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.dlog(`info`,`save-theme-default: ${a.theme} ${hy.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},I2=(e,t)=>{let[n=``,r=``]=n2(()=>di(e)),i=e2(n);if(!r)throw new q(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=b2(t,i),o=D2(a);LQ(O2(t,i),o,r),t.reloadConfig(a);let s=Sy.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},L2=(e,t)=>{let[n=``,...r]=n2(()=>di(e)),i=e2(n),a=b2(t,i),o=qI(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new q(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=D2(a),l=r.map(nU),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);MQ(O2(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.dlog(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function R2(e,t){let n=(e,t)=>[...E_(tx(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Qb(t.presets).flatMap(e=>n(t,e).map(t=>Aj(fA(e),S_(t)))));return Qb(e.presets).flatMap(t=>n(e,t).map(e=>({member:Aj(fA(t),S_(e)),node:e})).filter(({member:e})=>!r.has(e)))}function z2(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[Ej]:[]])}const B2=(e,t)=>{let[n=``,r=``,i=``]=n2(()=>di(e)),a=e2(n),o=b2(t,a),s=t.configFor(o),c=qI(s);if(!r)throw new q(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new q(`apply-layout-op: ${l.reason}`);let u=NI(l.value);if(u===null)throw new q(`apply-layout-op: "${l.value}" is not a layout op token`);let d=D2(o),f=RQ(O2(t,a),d,r,u);t.reloadConfig(o);let p=z2(R2(s,t.configFor(o)),t.sessionState.get(a,Ej)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.dlog(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},V2=(e,t)=>{let[n=``]=n2(()=>di(e)),r=e2(n);t.journal.commit();let i=t.history.undo(r);C2(t,r,i),t.dlog(`info`,`undo: restored ${o$(i)} (session=${r})`)},H2=(e,t)=>{let n=e2(t2(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,_U(w2(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},U2=(e,t)=>{let n=e2(t2(e));t.journal.commit();let r=t.history.rewind(n);C2(t,n,r),t.dlog(`info`,`rewind: put back ${o$(r)||`nothing`} as edit mode found it (session=${n})`)},W2=(e,t)=>{let[n=``]=n2(()=>di(e)),r=e2(n);t.journal.commit();let i=t.history.redo(r);C2(t,r,i),t.dlog(`info`,`redo: re-applied ${o$(i)} (session=${r})`)},G2=(e,t)=>{e2(t2(e)),t.applyUpdate()},K2=`client-hints`;function q2(e,t){let n=e.sessionState.get(t,K2);if(n===null)throw new q(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new q(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new q(`client hints record is not an object: ${n}`);return Vt(r)}function J2(e,t,n){let r=IN(n);e.sessionState.setBatch(t,QN(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${XN(n.nerdFont,n.marks)} ${BN(n.terminal,n.clicked)} ${VN(n.terminal,n.width)} ${HN(n.install)} ${WN(n.daemon)} ${GN(n.data)} ${YN(n.transcripts)} ${KN(n.frames,n.claudeSettings)} ${JN(n.claudeSettings.origin.sources)} (session=${t})`)}function Y2(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,ik(new Date)),i;try{i=f0(e.doctor,q2(e,t),b2(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:r.map(e=>e.rateLimits)},{kind:`ok`,value:r.map(e=>e.transcript)},n,{kind:`ok`,value:R$(n,r)},d0(t,r),z1(e.doctorStores))}catch(e){throw e instanceof P$?new q(e.message):e}return{...i,urlHandler:c0(e.arrival),install:L1(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:X2(e,i)}}function X2(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?IM(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>M$(e,r))}catch(t){return e.dlog(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const Z2=(e,t)=>{let n=e2(t2(e));J2(t,n,Y2(t,n))},Q2=(e,t)=>{let n=A0(t2(e));if(n===null)throw new q(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new q(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},$2=(e,t)=>{let[n=``,r=``]=n2(()=>di(e)),i=e2(n),a=LN(r);if(a===void 0)throw new q(`doctor-fix: unknown check "${r}"`);let o=Y2(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new q(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=p0(t.doctorStores,s.fix,o);if(c.kind===`failed`)throw new q(`doctor-fix: ${a.label} — ${c.reason}`);t.dlog(`info`,`doctor-fix: ${a.name} → ${JM(s.fix)} (session=${i})`),J2(t,i,c.value)},e4=(e,t)=>{let[n=``,r=``,i=``]=n2(()=>di(e)),a=e2(n),o=LN(r);if(o===void 0)throw new q(`doctor-mark: unknown check "${r}"`);if(!GM.includes(i))throw new q(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${GM.join(` or `)}`);let s=Y2(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new q(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);let l=[o.name,c.sighting.id,i],u=t.doctorStores.marks.update(e=>k$(e,...l));if(u.kind===`failed`)throw new q(`doctor-mark: ${u.reason}`);t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),J2(t,a,{...s,marks:u})},t4=(e,t)=>{let[n=``,r=``]=n2(()=>di(e)),i=e2(n),a=Object.values(t.configFor(b2(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new q(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=J0(t.claudeInput,q2(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new q(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)};function n4([e=``,t=``,n=``,r=``],i){let a=e2(e),o=b2(i,a),s=i.configFor(o).actions,c=Object.hasOwn(s,t)?s[t]:void 0;if(c===void 0||!(`run`in c))throw new q(`"${t}" is not a run action this session's config declares`);let l=fx(c);if(!i.links.verify({sessionId:a,action:t,declaration:l,evaluated:n},r))throw new q(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let u;try{u=JSON.parse(n)}catch{throw new q(`run ${t}: what the link carries is not JSON`)}let[d,...f]=u.run;if(d===void 0||d===``)throw new q(`run ${t}: the program evaluated to nothing`);let p=i.sourcesFor(o);return{sessionId:a,action:t,argv:[d,...f],env:{...T$(process.env,{sessionId:a,projectDir:o.projectDir,claudeConfigDir:q2(i,a).claudeConfigDir}),...u.env},cwd:c.cwd,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const r4=(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=n2(()=>di(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=n4(i,t)}catch(e){throw e instanceof q&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)},i4=`config-override`,a4=new Map([[Br,i2],[Gr,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new q(`load-config: expected <sessionId>/<path> (missing separator)`);let r=e2(n2(()=>decodeURIComponent(e.slice(0,n)))),i=n2(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new q(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new q(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,i4),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,i4,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Vr,a2],[Rr,l2],[zr,f2],[Kr,k2],[qr,A2],[Qr,L2],[Jr,j2],[Yr,P2],[Xr,F2],[Zr,I2],[$r,B2],[ei,V2],[ti,W2],[ni,H2],[ri,U2],[Ur,o2],[Wr,s2],[Hr,c2],[ii,G2],[ai,Z2],[oi,$2],[si,e4],[ci,Q2],[li,t4],[`run`,r4]]),o4=new Set([Rr,zr,Kr,qr,Qr,Jr,Yr,Xr,Zr,$r,ei,ti,ni,ri,Hr,ii,ai,oi,si,li,`run`,Gr]);function s4(e,t){return c4(e===`dispatch`?mi(t):[{verb:e,value:t}])}function c4(e){let t=e.find(e=>o4.has(e.verb)),n=t===void 0?``:n2(()=>fi(t.value));return n===``?null:n}const l4=(e,t)=>{let n=[],r=!1,i=mi(e),a=c4(i);for(let{verb:e,value:a}of gi(i)){let i=a4.get(e);if(!i){n.push(`unknown effect verb "${e}"`);continue}try{i(a,t)}catch(t){t instanceof q||(r=!0),n.push(`${e}: ${t instanceof Error?t.message:String(t)}`)}}if(n.length>0){a&&$o(t.sessionState,a,n.join(`
488
- `),ik(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new q(e)}};function u4(e,t){return(n,r)=>{let i=t(n),a=i===null?null:T2(r,i),o=r.history.begin(),s=r.navigation.begin(o.sessionState),c=[],l=e=>C$(e,e=>E2(r,e),e=>r.dlog(`info`,e));try{e(n,{...r,sessionState:l(o.sessionState),journal:o,navigating:l(s.sessionState)})}catch(e){c.push(e)}s.commit();try{o.commit()}catch(e){c.push(e)}if(a!==null)try{r.lanes.clicked(a.sessionId,a.before,a.read())}catch(e){c.push(e)}if(i!==null)try{let e=S2(r,i);e!==null&&r.views.follow(i,e)}catch(e){c.push(e)}if(c.length===1)throw c[0];if(c.length>1)throw Error(c.map(e=>String(e.message??e)).join(`; `))}}const d4=new Map([...a4,[Lr,l4]].map(([e,t])=>[e,u4(t,t=>s4(e,t))]));Object.freeze([...d4.keys()]);function f4(e,t,n){u4((n,r)=>{let i=S$(E2(r,e),t=>r.navigating.get(e,t));r.navigating.setBatch(e,i.map(({key:e})=>({key:e,value:yi}))),r.dlog(`info`,`menu-idle: closed=${i.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)},()=>e)(``,n)}const p4=new Set([`hook_event_name`,`session_id`,`session_name`,`transcript_path`,`cwd`,`model`,`workspace`,`version`,`output_style`,`cost`,`context_window`,`exceeds_200k_tokens`,`effort`,`thinking`,`rate_limits`,`vim`,`agent`,`worktree`]),m4=[[`session_id`,`string`],[`transcript_path`,`string`],[`cwd`,`string`],[`model`,`object`],[`model.id`,`string`],[`model.display_name`,`string`],[`workspace`,`object`],[`workspace.current_dir`,`string`],[`workspace.project_dir`,`string`]],h4=[[`workspace.added_dirs`,`string-list`]];function g4(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of m4){let i=y4(n,e);if(i==null)t.missingRequired.push(e);else{let n=_4(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of h4){let i=y4(n,e),a=i===void 0?r:v4(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))p4.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function _4(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function v4(e){return Array.isArray(e)&&e.every(e=>_4(e)===`string`)?`string-list`:_4(e)}function y4(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function b4(e,t){switch(e){case`vars`:return{what:e,vars:x4(t)};case`segments`:return{what:e,segments:E4(t)};case`config`:return{what:e,config:A4(t)}}}function x4(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=w4(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=S4(r),s=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...a,lastError:s===void 0?null:{timestampMs:s.timestamp,message:s.message},ageMs:C4(r.lastUpdatedMs())})}return o}function S4(e){if(e.kind===`projection`)return{type:e.type,value:`(read at each frame's instant)`};if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`pending`:return{type:`document`,value:`(not yet scanned)`};case`absent`:return{type:`document`,value:`(nothing to read, and no default)`};case`failed`:return{type:`document`,value:t.reason}}}function C4(e){return e===null?null:Math.max(0,Date.now()-e)}function w4(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,T4(r));for(let[n,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))t.set(`${n}.${e}`,T4(i));return t}function T4(e){return e.kind}function E4(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=O4(n),o=D4(n),s=[];for(let e of a){let t=n.segments[e];t&&s.push({name:e,description:t.description??null,template:t.template,referencedVars:k4(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function D4(e){let t=new Map;for(let n of Qb(e.presets))for(let r of E_(tx(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=S_(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function O4(e){let t=[],n=new Set;for(let r of E_(Gb(e.root)))r.kind===`segment`&&e.segments[r.name]&&!n.has(r.name)&&(t.push(r.name),n.add(r.name));for(let r of Object.keys(e.segments))n.has(r)||(t.push(r),n.add(r));return t}function k4(e,t,n){let r=new Set([...Dx(e,t).keys()].flatMap(e=>Bx(e,n)));return Array.from(r).sort()}function A4(e){return e===null?null:e.config}const j4=[`vars`,`segments`,`config`];function M4(e){return typeof e==`string`&&j4.includes(e)}function N4(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>FH(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return Hq({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...iU(n.config,n.fileHeldSettings,a),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})});return{payload:()=>s.read(),effective:()=>o.read(),selections:()=>o.read()}}}const P4={moving:1e3/30,still:1e3},F4=[`data`,`state`,`reload`,`visibility`];function I4(e){return Fv.filter(t=>e[t].subscribers>0).map(t=>{let{subscribers:n,fps:r,shown:i}=e[t];return`${t}:${n}sub/${r}fps/${i?`shown`:`offscreen`}`}).join(`,`)||`-`}function L4(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const R4=e=>({resp:e,bytes:JSON.stringify(e)}),z4=(e,t)=>Pv[t].elsewhere===null?e.statusline:e.bar,B4=e=>Math.round(1e3/e);var V4=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&i.noted++}subscribe(e,t){let n=this.deps.lanes(e);if(n!==null&&!n[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e),i=r??this.open(e);return i.followers.set(t,null),i.rates.has(t.lane)||i.rates.set(t.lane,[]),r!==void 0&&this.send(i,t),this.hasten(i),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${i.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(i,t)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e,t){let n=this.feeds.get(e);n!==void 0&&(n.woke[t]++,this.hasten(n)||n.coalesced++)}wakeWhere(e,t){for(let{sessionId:n,req:r}of this.watched())t(r)&&this.wake(n,e)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}latest(e){return this.requests.get(e)?.req??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e,t){let n=this.feeds.get(e);if(n===void 0)return Vv;let r=t-1,i=this.shown(n);return Bv(e=>{let a=n.rates.get(e);if(a===void 0)return Rv;let o=0;for(let t of n.followers.keys())t.lane===e&&o++;let s=0;for(let e of a)e>r&&e<=t&&s++;return{subscribers:o,fps:s,shown:i}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.now(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e,`state`)),unpin:this.deps.pin(e),phase:{kind:`waiting`},lastStart:-1/0,last:null,since:t,drawn:0,noted:0,noView:0,moving:0,unseen:0,failed:0,pushed:0,pace:B4(this.deps.periods.still),drawMs:0,evaluated:0,woke:{data:0,state:0,reload:0,visibility:0},coalesced:0,summarizedAt:t,refreshesAtOpen:this.deps.refreshes()};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),n}unsubscribe(e,t){if(e.followers.delete(t)){if([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),e.followers.size>0){this.hasten(e);return}e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),e.unpin(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)}}draw(e){e.phase={kind:`drawing`};let t=this.deps.now();try{this.step(e,t)}catch(n){if(e.lastStart=t,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${T(n)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,t)}}step(e,t){let n=this.deps.render(e.sessionId,e.pace);if(n===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=t;let r=this.deps.now();this.drawn++,e.drawn++,e.drawMs+=r-t,e.evaluated+=n.evaluated,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,n),this.push(e,n),this.feeds.get(e.sessionId)===e&&(r-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,n,t)))}schedule(e,t,n){let r=t?.moves===!0,i=r&&this.shown(e);i&&e.moving++,r&&!i&&e.unseen++;let a=i?this.deps.periods.moving:this.deps.periods.still;e.pace=B4(a),this.arm(e,n+a)}spacingOf(e){return this.shown(e)?this.deps.periods.moving:this.deps.periods.still}hasten(e){let{phase:t}=e;if(t.kind===`drawing`)return!1;let n=Math.max(this.deps.now(),e.lastStart+this.spacingOf(e));return t.kind===`due`&&t.at<=n?!1:(this.arm(e,n),!0)}arm(e,t){e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.phase={kind:`due`,at:t,timer:setTimeout(()=>this.draw(e),Math.max(0,t-this.deps.now()))}}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t){let n=this.deps.lanes(e.sessionId);if(n!==null)for(let t of[...e.followers.keys()])n[t.lane]||(this.unsubscribe(e,t),this.refuse(e.sessionId,t));if(e.followers.size===0)return;let r={bar:R4(t.resp),statusline:R4(t.statusline)};if(e.last?.answers.bar.bytes===r.bar.bytes&&e.last.answers.statusline.bytes===r.statusline.bytes)return;let i=e.last?.answers??null;e.last={answers:r},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);for(let[n,a]of e.rates)(i===null||z4(i,n).bytes!==z4(r,n).bytes)&&L4(a,t.at);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let{resp:n,bytes:r}=z4(e.last.answers,t.lane);e.followers.get(t)!==r&&(t.frame(n,r),e.followers.set(t,r))}refuse(e,t){this.refused++,this.deps.log(`info`,`feed sid=${JSON.stringify(e)} refused lane=${t.lane} switched-off`),t.refused({ok:!1,error:iM(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now(),r=this.deps.refreshes(),i=Ak.map(t=>`${t}:${r[t]-e.refreshesAtOpen[t]}`).join(`,`);this.deps.log(`info`,`feed sid=${JSON.stringify(e.sessionId)} ${t} subscribers=${e.followers.size} lanes=${[...e.followers.keys()].map(e=>e.lane).join(`,`)||`-`} for=${Math.round((n-e.since)/1e3)}s drawn=${e.drawn} noted=${e.noted} noView=${e.noView} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} pace=${e.pace}fps evaluated=${e.evaluated} woke=${F4.map(t=>`${t}:${e.woke[t]}`).join(`,`)} coalesced=${e.coalesced} daemonRefreshed=${i} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function H4(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}const U4=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,W4=`#{session_id} #{client_control_mode} #{pane_id}`;function G4(e){let t=new Set;for(let n of e.split(`
489
- `)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function K4(e,t){let n=new Set;for(let r of e.split(`
490
- `)){let[e,i,a,o,s,c]=r.trim().split(` `);e===void 0||e===``||i===void 0||Number(a)>0&&(o===`1`||t.has(i))&&(s!==`1`||c===`1`)&&n.add(e)}return n}function q4(e,t){let n=new Map;for(let t of e.split(`
485
+ `}const O0=e=>({kind:`ok`,value:e}),k0=e=>({kind:`failed`,reason:e});var A0=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const j0=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function M0(e){return j0.test(e)?e:null}function N0(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return O0(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return O0({app:n,missing:k0(`its script could not be read (${r.reason})`)});let i=ko(r.value);return O0({app:n,missing:i===null?k0("its script is not one `cc-candybar install` wrote"):O0([i.node,i.script].filter(t=>!e.exists(t)))})}async function P0(e,t){let n=e.now()+5e3;for(;e.now()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,handler:r.handler,bar:n.value.version}}return null}async function F0(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${Ir}://${ci}/${n}`);return(r===null?await P0(e,n):null)??{kind:`lost`,unopened:r,opener:N0(e)}}function I0(e,t,n){let r=D({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?O0(r.stdout):k0(r.stderr.trim()||r.error||r.reason)}const L0=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${Ir}://probe"));u.isNil() ? "" : u.path.js`;async function R0(){let e=await v0();if(e.kind!==`ok`)return k0(un(e).split(`
486
+ `).join(` — `));let t=y0(e.value,[`handlerProbes`]);if(t!==null)return k0(t);let{version:n,handlerProbes:r}=e.value;return O0({version:n,arrivals:r})}function z0(){return{platform:process.platform,sockets:{own:St(),handler:Ct()},now:Date.now,nonce:ie,daemon:R0,open:e=>{let t=I0(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=I0(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,L0]);if(e.kind===`failed`)return e;let t=e.value.trim();return O0(t===``?null:t)},script:e=>I0(`doctor.osadecompile`,`/usr/bin/osadecompile`,[Ao(e)]),exists:p.existsSync}}const B0=/^─{20,}/,V0=/^❯(\s|$)/,H0=/›\s*stashed$/;function U0(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>B0.test(e)?[t]:[]).at(-2);return n===void 0||!V0.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function W0(e){if(e.inMode)return{kind:`in-mode`};let t=U0(e);return t===null?{kind:`no-prompt`}:H0.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function G0(e){return/^❯\s*\S/u.test(U0(e)?.prompt??``)}const K0=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function q0(e){return e.screen.some(e=>K0.test(e))}const J0={"in-mode":`the Claude Code pane is in tmux copy mode — leave it (q) and click again`,stashed:`Claude Code is holding a stashed prompt (ctrl+s) — restore or send it, then click again`,"no-prompt":`Claude Code is not at its prompt (a dialog or picker is open) — close it and click again`};function Y0(e){return e===void 0?{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`}:e===null?{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only act in a tmux pane`}:{kind:`pane`,hint:e}}function X0(e,t,n){let r=Y0(t);if(r.kind===`refused`)return r;let i=r.hint,a=W0(e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:J0[a.kind]};let o=e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}function Z0(e,t,n,r){let i=FK(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function Q0(e){let t=Z0(e,`claude-input.read`,[`display`,`-p`,`-t`,e.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,e.pane]);if(t.kind===`rate-limited`)throw Error(t.reason);let[n=``,...r]=t.stdout.split(`
487
+ `);return{inMode:n!==`0`,screen:r}}function $0(e,t,n){return[`load-buffer`,`-b`,t,`-`,`;`,...n.length===0?[]:[`send-keys`,`-t`,e,...n,`;`],`paste-buffer`,`-p`,`-d`,`-b`,t,`-t`,e,`;`,`send-keys`,`-t`,e,`Enter`]}function e2(e,t){let n=Z0(e,`claude-input.type`,$0(e.pane,`cc-candybar-slash`,[`C-s`]),t);return n.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${n.reason})`}}function t2(){return{read:Q0,type:e2}}function n2(e){let t=mW(e);if(!t.ok)throw new q(`session id ${t.problem}`);return t.id}function r2(e){return kb(()=>decodeURIComponent(e))}function i2(e,t,n){let r=D(e);if(r.ok)return;if(r.reason===`rate-limited`){n(`warn`,`${e.category} rate-limited: ${r.error??``}`);return}let i=r.error??r.stderr.trim();throw Error(`${t} failed (${r.reason}, exit ${r.exitCode??`null`})${i===``?``:`: ${i}`}`)}function a2(e,t){i2({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`,t.dlog)}const o2=(e,t)=>a2(r2(e),t),s2=(e,t)=>i2({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,r2(e)],category:`click.open`},`open -a "Visual Studio Code"`,t.dlog),c2=(e,t)=>a2(r2(e),t),l2=(e,t)=>a2(r2(e),t),u2=(e,t)=>{let n=n2(r2(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},d2=(e,t)=>{let[n=``,...r]=kb(()=>di(e)),i=n2(n),a=yU(E2(t,i));if(r.length===0)throw new q(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new q(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new q(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new q(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}h2(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},f2=/^-?\d+$/;function p2(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const m2=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=n2(n);if(!r)throw new q(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!f2.test(i))throw new q(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=E2(t,a),c=yU(s),l=c.rangeParamsFor(r);if(!l)throw new q(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&f2.test(u)?g2(l,parseInt(u,10)):_2(`step-state`,r,l,SU(s,e=>t.sessionState.get(a,e),r)),f=p2(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new q(`step-state: ${p.reason}`);h2(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function h2(e,t,n,r){let i=r.filter(e=>e.key.startsWith(Aj));if(i.length===0)return;let a=QH(E2(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new q(`${n}: refused — ${a.join(`; `)}`)}function g2(e,t){return Math.max(e.min,Math.min(e.max,t))}function _2(e,t,n,r){if(r===null)return n.min;if(!f2.test(r))throw new q(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return g2(n,parseInt(r,10))}const v2=`render-origin`;function y2(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function b2(e){return JSON.stringify(e)}function x2(e){let t;try{t=JSON.parse(e)}catch{throw new q(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new q(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new q(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function S2(e,t){let n=w2(e,t);if(n===null)throw new q(`session ${t} has not rendered yet — no config to act on`);return n}function C2(e,t){let n=e.sessionState.get(t,v2);return n===null?null:x2(n)}function w2(e,t){let n=C2(e,t);return n===null?null:y2(n,e.sessionState,t)}function T2(e,t,n){let r=w2(e,t);if(r===null)return;let{path:i}=k2(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function E2(e,t){return e.configFor(S2(e,t))}function D2(e,t){let n=C2(e,t);if(n===null)return null;let r=()=>e.lanes.of(y2(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function O2(e,t){let n=w2(e,t);return n===null?v$:S$(e.configFor(n))}function k2(e){return JV(e.projectDir,e.cwd,e.configFile??void 0)}function A2(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const j2=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=n2(n),o=S2(t,a),s=t.configFor(o),c=YI(s);if(!r)throw new q(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new q(`set-config: ${l.reason}`);let u=k2(o),d=XH(s,e=>t.sessionState.get(a,e),r);kQ(A2(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},M2=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=n2(n);if(!r)throw new q(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!f2.test(i))throw new q(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=S2(t,a),c=t.configFor(s),l=YI(c),u=l.rangeParamsFor(r);if(!u)throw new q(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=k2(s),f=XH(c,e=>t.sessionState.get(a,e),r),p=OQ(d.path,f.key),m=typeof p==`number`?g2(u,p):_2(`step-config`,r,u,ZI(f.globals,r)),h=p2(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new q(`step-config: ${g.reason}`);kQ(A2(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.dlog(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},N2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=n2(n),i=S2(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=JH(a,o),c=ZH(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=yU(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new q(`save: ${t.reason}`);return[e.target,t.value]});F2(`save`,l,c);let d=k2(i);AQ(A2(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.dlog(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(P2)].join(` `)} → ${d.path} (session=${r})`)},P2=e=>`${e.preset}/${e.id}.settings.${e.setting}=${G_(e.value)}`;function F2(e,t,n){for(let r of n){let n=t.validate(r.key,G_(r.value));if(!n.ok)throw new q(`${e}: ${n.reason}`)}}const I2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=n2(n),i=S2(t,r),a=t.configFor(i),o=tU(a,e=>t.sessionState.get(r,e)),s=yU(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new q(`save-preset: ${t.reason}`);return[e.configKey,t.value]});F2(`save-preset`,s,o.placements);let l=k2(i),u=LQ(A2(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...wy.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Sy.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(P2)].join(` `)} → ${l.path} (session=${r})`)},L2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=n2(n),i=S2(t,r),a=rU(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new q(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=k2(i);RQ(A2(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(JH(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=hy.map(e=>Sy[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.dlog(`info`,`save-theme-default: ${a.theme} ${hy.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},R2=(e,t)=>{let[n=``,r=``]=kb(()=>di(e)),i=n2(n);if(!r)throw new q(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=S2(t,i),o=k2(a);zQ(A2(t,i),o,r),t.reloadConfig(a);let s=Sy.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},z2=(e,t)=>{let[n=``,...r]=kb(()=>di(e)),i=n2(n),a=S2(t,i),o=YI(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new q(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=k2(a),l=r.map(iU),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);PQ(A2(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.dlog(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function B2(e,t){let n=(e,t)=>[...E_(nx(e,t).node)].filter(e=>e.kind===`segment`),r=new Set($b(t.presets).flatMap(e=>n(t,e).map(t=>jj(pA(e),S_(t)))));return $b(e.presets).flatMap(t=>n(e,t).map(e=>({member:jj(pA(t),S_(e)),node:e})).filter(({member:e})=>!r.has(e)))}function V2(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[Dj]:[]])}const H2=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=n2(n),o=S2(t,a),s=t.configFor(o),c=YI(s);if(!r)throw new q(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new q(`apply-layout-op: ${l.reason}`);let u=FI(l.value);if(u===null)throw new q(`apply-layout-op: "${l.value}" is not a layout op token`);let d=k2(o),f=BQ(A2(t,a),d,r,u);t.reloadConfig(o);let p=V2(B2(s,t.configFor(o)),t.sessionState.get(a,Dj)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.dlog(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},U2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=n2(n);t.journal.commit();let i=t.history.undo(r);T2(t,r,i),t.dlog(`info`,`undo: restored ${c$(i)} (session=${r})`)},W2=(e,t)=>{let n=n2(r2(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,yU(E2(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},G2=(e,t)=>{let n=n2(r2(e));t.journal.commit();let r=t.history.rewind(n);T2(t,n,r),t.dlog(`info`,`rewind: put back ${c$(r)||`nothing`} as edit mode found it (session=${n})`)},K2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=n2(n);t.journal.commit();let i=t.history.redo(r);T2(t,r,i),t.dlog(`info`,`redo: re-applied ${c$(i)} (session=${r})`)},q2=(e,t)=>{n2(r2(e)),t.applyUpdate()},J2=`client-hints`;function Y2(e,t){let n=e.sessionState.get(t,J2);if(n===null)throw new q(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new q(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new q(`client hints record is not an object: ${n}`);return Vt(r)}function X2(e,t,n){let r=LN(n);e.sessionState.setBatch(t,$N(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${ZN(n.nerdFont,n.marks)} ${VN(n.terminal,n.clicked)} ${HN(n.terminal,n.width)} ${UN(n.install)} ${GN(n.daemon)} ${KN(n.data)} ${XN(n.transcripts)} ${qN(n.frames,n.claudeSettings)} ${YN(n.claudeSettings.origin.sources)} (session=${t})`)}function Z2(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,ak(new Date)),i;try{i=m0(e.doctor,Y2(e,t),S2(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:r.map(e=>e.rateLimits)},{kind:`ok`,value:r.map(e=>e.transcript)},n,{kind:`ok`,value:B$(n,r)},p0(t,r),V1(e.doctorStores))}catch(e){throw e instanceof I$?new q(e.message):e}return{...i,urlHandler:u0(e.arrival),install:z1(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:Q2(e,i)}}function Q2(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?LM(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>P$(e,r))}catch(t){return e.dlog(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const $2=(e,t)=>{let n=n2(r2(e));X2(t,n,Z2(t,n))},e4=(e,t)=>{let n=M0(r2(e));if(n===null)throw new q(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new q(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},t4=(e,t)=>{let[n=``,r=``]=kb(()=>di(e)),i=n2(n),a=RN(r);if(a===void 0)throw new q(`doctor-fix: unknown check "${r}"`);let o=Z2(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new q(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=h0(t.doctorStores,s.fix,o);if(c.kind===`failed`)throw new q(`doctor-fix: ${a.label} — ${c.reason}`);t.dlog(`info`,`doctor-fix: ${a.name} → ${YM(s.fix)} (session=${i})`),X2(t,i,c.value)},n4=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=n2(n),o=RN(r);if(o===void 0)throw new q(`doctor-mark: unknown check "${r}"`);if(!KM.includes(i))throw new q(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${KM.join(` or `)}`);let s=Z2(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new q(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);let l=[o.name,c.sighting.id,i],u=t.doctorStores.marks.update(e=>j$(e,...l));if(u.kind===`failed`)throw new q(`doctor-mark: ${u.reason}`);t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),X2(t,a,{...s,marks:u})},r4=(e,t)=>{let[n=``,r=``]=kb(()=>di(e)),i=n2(n),a=Object.values(t.configFor(S2(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new q(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=X0(t.claudeInput,Y2(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new q(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)};function i4([e=``,t=``,n=``,r=``],i){let a=n2(e),o=S2(i,a),s=i.configFor(o).actions,c=Object.hasOwn(s,t)?s[t]:void 0;if(c===void 0||!(`run`in c))throw new q(`"${t}" is not a run action this session's config declares`);let l=px(c);if(!i.links.verify({sessionId:a,action:t,declaration:l,evaluated:n},r))throw new q(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let u;try{u=JSON.parse(n)}catch{throw new q(`run ${t}: what the link carries is not JSON`)}let[d,...f]=u.run;if(d===void 0||d===``)throw new q(`run ${t}: the program evaluated to nothing`);let p=i.sourcesFor(o);return{sessionId:a,action:t,argv:[d,...f],env:{...D$(process.env,{sessionId:a,projectDir:o.projectDir,claudeConfigDir:Y2(i,a).claudeConfigDir}),...u.env},cwd:c.cwd,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const a4=(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=kb(()=>di(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=i4(i,t)}catch(e){throw e instanceof q&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)},o4=`config-override`,s4=new Map([[Br,o2],[Gr,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new q(`load-config: expected <sessionId>/<path> (missing separator)`);let r=n2(kb(()=>decodeURIComponent(e.slice(0,n)))),i=kb(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new q(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new q(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,o4),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,o4,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Vr,s2],[Rr,d2],[zr,m2],[Kr,j2],[qr,M2],[Qr,z2],[Jr,N2],[Yr,I2],[Xr,L2],[Zr,R2],[$r,H2],[ei,U2],[ti,K2],[ni,W2],[ri,G2],[Ur,c2],[Wr,l2],[Hr,u2],[ii,q2],[ai,$2],[oi,t4],[si,n4],[ci,e4],[li,r4],[`run`,a4]]),c4=new Set([Rr,zr,Kr,qr,Qr,Jr,Yr,Xr,Zr,$r,ei,ti,ni,ri,Hr,ii,ai,oi,si,li,`run`,Gr]);function l4(e,t){return u4(e===`dispatch`?mi(t):[{verb:e,value:t}])}function u4(e){let t=e.find(e=>c4.has(e.verb)),n=t===void 0?``:kb(()=>fi(t.value));return n===``?null:mW(n)}const d4=(e,t)=>{let n=[],r=!1,i=mi(e),a=u4(i);for(let{verb:e,value:a}of gi(i)){let i=s4.get(e);if(!i){n.push(`unknown effect verb "${e}"`);continue}try{i(a,t)}catch(t){t instanceof q||(r=!0),n.push(`${e}: ${t instanceof Error?t.message:String(t)}`)}}if(n.length>0){a?.ok&&$o(t.sessionState,a.id,n.join(`
488
+ `),ak(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new q(e)}};function f4(e,t){return(n,r)=>{let i=t(n),a=i===null?null:D2(r,i),o=r.history.begin(),s=r.navigation.begin(o.sessionState),c=[],l=e=>T$(e,e=>O2(r,e),e=>r.dlog(`info`,e));try{e(n,{...r,sessionState:l(o.sessionState),journal:o,navigating:l(s.sessionState)})}catch(e){c.push(e)}s.commit();try{o.commit()}catch(e){c.push(e)}if(a!==null)try{r.lanes.clicked(a.sessionId,a.before,a.read())}catch(e){c.push(e)}if(i!==null)try{let e=w2(r,i);e!==null&&r.views.follow(i,e)}catch(e){c.push(e)}if(c.length===1)throw c[0];if(c.length>1)throw Error(c.map(e=>String(e.message??e)).join(`; `))}}const p4=new Map([...s4,[Lr,d4]].map(([e,t])=>[e,f4(t,t=>{let n=l4(e,t);return n?.ok?n.id:null})]));Object.freeze([...p4.keys()]);function m4(e,t,n){f4((n,r)=>{let i=w$(O2(r,e),t=>r.navigating.get(e,t));r.navigating.setBatch(e,i.map(({key:e})=>({key:e,value:yi}))),r.dlog(`info`,`menu-idle: closed=${i.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)},()=>e)(``,n)}const h4=new Set([`hook_event_name`,`session_id`,`session_name`,`transcript_path`,`cwd`,`model`,`workspace`,`version`,`output_style`,`cost`,`context_window`,`exceeds_200k_tokens`,`effort`,`thinking`,`rate_limits`,`vim`,`agent`,`worktree`]),g4=[[`session_id`,`string`],[`transcript_path`,`string`],[`cwd`,`string`],[`model`,`object`],[`model.id`,`string`],[`model.display_name`,`string`],[`workspace`,`object`],[`workspace.current_dir`,`string`],[`workspace.project_dir`,`string`]],_4=[[`workspace.added_dirs`,`string-list`]];function v4(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of g4){let i=x4(n,e);if(i==null)t.missingRequired.push(e);else{let n=y4(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of _4){let i=x4(n,e),a=i===void 0?r:b4(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))h4.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function y4(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function b4(e){return Array.isArray(e)&&e.every(e=>y4(e)===`string`)?`string-list`:y4(e)}function x4(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function S4(e,t){switch(e){case`vars`:return{what:e,vars:C4(t)};case`segments`:return{what:e,segments:O4(t)};case`config`:return{what:e,config:M4(t)}}}function C4(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=E4(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=w4(r),s=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...a,lastError:s===void 0?null:{timestampMs:s.timestamp,message:s.message},ageMs:T4(r.lastUpdatedMs())})}return o}function w4(e){if(e.kind===`projection`)return{type:e.type,value:`(read at each frame's instant)`};if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`pending`:return{type:`document`,value:`(not yet scanned)`};case`absent`:return{type:`document`,value:`(nothing to read, and no default)`};case`failed`:return{type:`document`,value:t.reason}}}function T4(e){return e===null?null:Math.max(0,Date.now()-e)}function E4(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,D4(r));for(let[n,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))t.set(`${n}.${e}`,D4(i));return t}function D4(e){return e.kind}function O4(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=A4(n),o=k4(n),s=[];for(let e of a){let t=n.segments[e];t&&s.push({name:e,description:t.description??null,template:t.template,referencedVars:j4(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function k4(e){let t=new Map;for(let n of $b(e.presets))for(let r of E_(nx(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=S_(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function A4(e){let t=[],n=new Set;for(let r of E_(Kb(e.root)))r.kind===`segment`&&e.segments[r.name]&&!n.has(r.name)&&(t.push(r.name),n.add(r.name));for(let r of Object.keys(e.segments))n.has(r)||(t.push(r),n.add(r));return t}function j4(e,t,n){let r=new Set([...Ox(e,t).keys()].flatMap(e=>Vx(e,n)));return Array.from(r).sort()}function M4(e){return e===null?null:e.config}const N4=[`vars`,`segments`,`config`];function P4(e){return typeof e==`string`&&N4.includes(e)}function F4(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>LH(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return Wq({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...oU(n.config,n.fileHeldSettings,a),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})});return{payload:()=>s.read(),effective:()=>o.read(),selections:()=>o.read()}}}const I4={moving:1e3/30,still:1e3},L4=[`data`,`state`,`reload`,`visibility`];function R4(e){return Fv.filter(t=>e[t].subscribers>0).map(t=>{let{subscribers:n,fps:r,shown:i}=e[t];return`${t}:${n}sub/${r}fps/${i?`shown`:`offscreen`}`}).join(`,`)||`-`}function z4(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const B4=e=>({resp:e,bytes:JSON.stringify(e)}),V4=(e,t)=>Pv[t].elsewhere===null?e.statusline:e.bar,H4=e=>Math.round(1e3/e);var U4=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&i.noted++}subscribe(e,t){let n=this.deps.lanes(e);if(n!==null&&!n[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e),i=r??this.open(e);return i.followers.set(t,null),i.rates.has(t.lane)||i.rates.set(t.lane,[]),r!==void 0&&this.send(i,t),this.hasten(i),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${i.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(i,t)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e,t){let n=this.feeds.get(e);n!==void 0&&(n.woke[t]++,this.hasten(n)||n.coalesced++)}wakeWhere(e,t){for(let{sessionId:n,req:r}of this.watched())t(r)&&this.wake(n,e)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}latest(e){return this.requests.get(e)?.req??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e,t){let n=this.feeds.get(e);if(n===void 0)return Vv;let r=t-1,i=this.shown(n);return Bv(e=>{let a=n.rates.get(e);if(a===void 0)return Rv;let o=0;for(let t of n.followers.keys())t.lane===e&&o++;let s=0;for(let e of a)e>r&&e<=t&&s++;return{subscribers:o,fps:s,shown:i}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.now(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e,`state`)),unpin:this.deps.pin(e),phase:{kind:`waiting`},lastStart:-1/0,last:null,since:t,drawn:0,noted:0,noView:0,moving:0,unseen:0,failed:0,pushed:0,pace:H4(this.deps.periods.still),drawMs:0,evaluated:0,woke:{data:0,state:0,reload:0,visibility:0},coalesced:0,summarizedAt:t,refreshesAtOpen:this.deps.refreshes()};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),n}unsubscribe(e,t){if(e.followers.delete(t)){if([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),e.followers.size>0){this.hasten(e);return}e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),e.unpin(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)}}draw(e){e.phase={kind:`drawing`};let t=this.deps.now();try{this.step(e,t)}catch(n){if(e.lastStart=t,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${T(n)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,t)}}step(e,t){let n=this.deps.render(e.sessionId,e.pace);if(n===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=t;let r=this.deps.now();this.drawn++,e.drawn++,e.drawMs+=r-t,e.evaluated+=n.evaluated,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,n),this.push(e,n),this.feeds.get(e.sessionId)===e&&(r-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,n,t)))}schedule(e,t,n){let r=t?.moves===!0,i=r&&this.shown(e);i&&e.moving++,r&&!i&&e.unseen++;let a=i?this.deps.periods.moving:this.deps.periods.still;e.pace=H4(a),this.arm(e,n+a)}spacingOf(e){return this.shown(e)?this.deps.periods.moving:this.deps.periods.still}hasten(e){let{phase:t}=e;if(t.kind===`drawing`)return!1;let n=Math.max(this.deps.now(),e.lastStart+this.spacingOf(e));return t.kind===`due`&&t.at<=n?!1:(this.arm(e,n),!0)}arm(e,t){e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.phase={kind:`due`,at:t,timer:setTimeout(()=>this.draw(e),Math.max(0,t-this.deps.now()))}}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t){let n=this.deps.lanes(e.sessionId);if(n!==null)for(let t of[...e.followers.keys()])n[t.lane]||(this.unsubscribe(e,t),this.refuse(e.sessionId,t));if(e.followers.size===0)return;let r={bar:B4(t.resp),statusline:B4(t.statusline)};if(e.last?.answers.bar.bytes===r.bar.bytes&&e.last.answers.statusline.bytes===r.statusline.bytes)return;let i=e.last?.answers??null;e.last={answers:r},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);for(let[n,a]of e.rates)(i===null||V4(i,n).bytes!==V4(r,n).bytes)&&z4(a,t.at);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let{resp:n,bytes:r}=V4(e.last.answers,t.lane);e.followers.get(t)!==r&&(t.frame(n,r),e.followers.set(t,r))}refuse(e,t){this.refused++,this.deps.log(`info`,`feed sid=${JSON.stringify(e)} refused lane=${t.lane} switched-off`),t.refused({ok:!1,error:aM(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now(),r=this.deps.refreshes(),i=(n-e.since)/1e3,a=i===0?`-`:`${(e.drawn/i).toFixed(1)}fps`,o=jk.map(t=>`${t}:${r[t]-e.refreshesAtOpen[t]}`).join(`,`);this.deps.log(`info`,`feed sid=${JSON.stringify(e.sessionId)} ${t} subscribers=${e.followers.size} lanes=${[...e.followers.keys()].map(e=>e.lane).join(`,`)||`-`} for=${Math.round(i)}s drawn=${e.drawn} noted=${e.noted} noView=${e.noView} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} pace=${e.pace}fps achieved=${a} evaluated=${e.evaluated} woke=${L4.map(t=>`${t}:${e.woke[t]}`).join(`,`)} coalesced=${e.coalesced} daemonRefreshed=${o} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function W4(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}const G4=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,K4=`#{session_id} #{client_control_mode} #{pane_id}`;function q4(e){let t=new Set;for(let n of e.split(`
489
+ `)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function J4(e,t){let n=new Set;for(let r of e.split(`
490
+ `)){let[e,i,a,o,s,c]=r.trim().split(` `);e===void 0||e===``||i===void 0||Number(a)>0&&(o===`1`||t.has(i))&&(s!==`1`||c===`1`)&&n.add(e)}return n}function Y4(e,t){let n=new Map;for(let t of e.split(`
491
491
  `)){let[e,r]=t.trim().split(` `);e!==void 0&&e!==``&&r!==void 0&&n.set(e,r)}let r=new Map;for(let e of t.split(`
492
- `)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var J4=class{servers=new Map;loop={kind:`idle`};constructor(e){this.deps=e}follow(){switch(this.loop.kind){case`idle`:this.deps.log(`info`,`visibility following`),this.ask();break;case`asking`:this.loop.following=!0;break;case`due`:break}return()=>this.stop()}stop(){switch(this.loop.kind){case`due`:clearTimeout(this.loop.timer),this.end();return;case`asking`:this.loop.following=!1;return;case`idle`:return}}ask(){let e={kind:`asking`,following:!0};this.loop=e,Promise.resolve().then(()=>this.refresh(this.deps.sockets())).catch(e=>this.deps.log(`error`,`visibility refresh threw: ${T(e)}`)).then(()=>{if(e.following){this.loop={kind:`due`,timer:setTimeout(()=>this.ask(),this.deps.intervalMs).unref()};return}this.end()})}end(){this.deps.log(`info`,`visibility stopped forgot=${this.servers.size}`),this.loop={kind:`idle`},this.servers.clear()}shown(e){if(e==null)return!0;let t=this.servers.get(e.socket);return t?.kind!==`asked`||t.shown.has(e.pane)}async refresh(e){for(let t of this.servers.keys())e.has(t)||this.servers.delete(t);let t=await Promise.all([...e].map(async e=>{let[t,n]=await Promise.all([this.deps.listPanes(e),this.deps.listClients(e)]);return[e,t.kind===`ok`?n.kind===`ok`?{kind:`asked`,shown:K4(t.stdout,G4(n.stdout)),status:q4(t.stdout,n.stdout)}:{kind:`unasked`,reason:n.reason}:{kind:`unasked`,reason:t.reason}]})),n=new Set;for(let[e,r]of t){let t=this.servers.get(e);this.servers.set(e,r),!Y4(t,r)&&(n.add(e),this.deps.log(r.kind===`asked`?`info`:`warn`,r.kind===`asked`?`visibility socket=${JSON.stringify(e)} shown=${[...r.shown].join(`,`)||`-`}`:`visibility socket=${JSON.stringify(e)} unasked: ${r.reason} — its panes count as shown`))}for(let[e,n]of t)n.kind===`asked`&&this.deps.onAnswer(e,n.status);n.size>0&&this.deps.onChange(n)}};function Y4(e,t){return e===void 0||e.kind!==t.kind?!1:e.kind===`unasked`||t.kind===`unasked`?!0:e.shown.size===t.shown.size&&[...e.shown].every(e=>t.shown.has(e))}const X4=`@cc-candybar-status-prior`,Z4=`@cc-candybar-status-wrote`,Q4=`@cc-candybar-binding-prior`,$4=[`-T`,`root`,`MouseDown1Status`],e3=Array.from({length:5},(e,t)=>t),t3=e=>`@cc-candybar-row-${e}`,n3=e=>`#[fill=terminal]#{${t3(e)}}`,r3=e=>`status-format[${e}]`;function i3(e){return e===0?`off`:e===1?`on`:String(e)}function a3(e){let t=e===`off`?0:e===`on`?1:/^[2-5]$/.test(e)?+e:NaN;if(Number.isNaN(t))throw Error(`tmux status is ${JSON.stringify(e)}`);return t}function o3(e,t){if(e===null)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>e[Number(n)]===t[Number(n)])}function s3(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function c3(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function l3(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function u3(e){return e.map(e=>e.map(l3).join(` `)).join(` ; `)}const d3=`ccb:separator`;function f3(e){return c3(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,d3],e]))}function p3(e,t){let n=e.split(`${d3}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const m3=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],h3=e=>[`show-options`,`-g`,`-q`,`-v`,e],g3=e=>[[`show-options`,`-t`,e],m3(e,`status`),...e3.map(t=>m3(e,r3(t)))];function _3(e){let[t=``,n=``,...r]=e,i=t.split(`
493
- `).map(e=>e.split(` `)[0]??``),a={};for(let e of e3)i.includes(r3(e))&&(a[e]=r[e]??``);let o=i.includes(`status-format`)||Object.keys(a).length>0;return{status:i.includes(`status`)?n:null,formats:o?a:null}}function v3(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,r3(Number(t)),s3(n)])]}const y3=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...g3(e),...e3.map(e=>h3(r3(e))),m3(e,X4),m3(e,Z4)];function b3(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:a3(t)}catch(e){return{kind:`theirs`,why:`${X4} does not read (${String(e)})`}}return r.owner===n?{kind:`ours`,prior:r,status:i}:{kind:`theirs`,why:`the daemon at ${JSON.stringify(r.owner)} draws it`}}function x3(e,t,n){let[r=``,...i]=t,a=_3(i.slice(0,7)),o=i.slice(7,12),[s=``,c=``]=i.slice(12);if(s!==``)return b3(s,c,n);let l=a3(r),u={};for(let e=0;e<l;e++){let t=a.formats===null?o[e]:a.formats[e];t!==void 0&&t!==``&&(u[e]=t)}let d={...u,...Object.fromEntries(Array.from({length:5-l},(e,t)=>[l+t,n3(t)]))},f={owner:n,base:l,status:a.status,formats:a.formats,wrote:d};return{kind:`lay-out`,prior:f,commands:[[`set-option`,`-t`,e,X4,JSON.stringify(f)],...v3(e,d)]}}const S3=e=>[...g3(e),m3(e,Z4)];function C3(e,t,n){let r=_3(n.slice(0,7)),i=n[7]??``,a=[],o=[];if(o3(r.formats,t.wrote))a.push(...v3(e,t.formats));else{o.push(`status-format`);for(let[n,i]of Object.entries(r.formats??{}))Number(n)>=t.base&&i===t.wrote[Number(n)]&&a.push([`set-option`,`-u`,`-t`,e,r3(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,s3(t.status)]):o.push(`status`)),a.push(...e3.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,t3(t)]),[`set-option`,`-q`,`-u`,`-t`,e,X4],[`set-option`,`-q`,`-u`,`-t`,e,Z4]),{commands:a,kept:o}}const w3=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,T3=[[`list-keys`,`-T`,`root`]];function E3(e){let t=w3.exec(e);return t===null?null:{line:t[0],command:t[1]}}const D3=`cc-candybar://tmux-status-click/`,O3=e=>`${D3}${ui([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,k3=e=>e?.command.includes(D3)??!1;function A3(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,Q4]};return k3(E3(t))?{steps:[e===null?{command:[`unbind-key`,...$4]}:{command:[`source-file`,`-`],stdin:`${e.line}\n`},n],said:`restored MouseDown1Status to ${e===null?`unbound`:JSON.stringify(e.line)}`}:{steps:[n],said:`left MouseDown1Status as it is: bound again since`}}var j3=class{held=new Map;servers=new Map;closed=!1;writes=0;failedWrites=0;constructor(e){this.deps=e}observe(e,t,n){if(this.closed)return;let r=this.held.get(e),i=n&&t!=null?t:null;if(r!==void 0&&(i===null||r.socket!==i.socket||r.pane!==i.pane)&&this.release(r,`switched off or moved`),i===null||this.held.has(e))return;let a={sessionId:e,socket:i.socket,pane:i.pane,unsubscribe:null,frame:null};this.held.set(e,a),this.serverOf(i.socket),this.deps.log(`info`,`tmux-status: holding sid=${JSON.stringify(e)} pane=${i.pane} socket=${JSON.stringify(i.socket)}`),a.unsubscribe=this.deps.subscribe(e,{lane:`tmuxStatus`,frame:e=>{a.frame=uW(e),this.reconcile(a.socket)},refused:t=>{this.held.get(e)===a&&this.release(a,`refused: ${t.error}`)},drawing:()=>this.draws(a)})}answered(e,t){if(this.closed)return;let n=this.serverOf(e);n.view=t;for(let n of[...this.held.values()])if(n.socket===e)if(!t.sessionOf.has(n.pane))this.release(n,`pane gone`);else{let t=this.deps.sessionInPane(e,n.pane);t!==null&&t!==n.sessionId&&this.release(n,`pane taken by sid=${JSON.stringify(t)}`)}this.reconcile(e)}draws(e){let t=this.servers.get(e.socket),n=t?.view?.sessionOf.get(e.pane);return n!==void 0&&t.layouts.has(n)&&t.view.shownBy.get(n)===e.pane}restoreAll(){this.closed=!0;for(let e of this.held.values())e.unsubscribe?.();this.held.clear();for(let[e,t]of this.servers){for(let[n,r]of[...t.layouts]){t.layouts.delete(n);let i=this.askSync(e,S3(n));if(i===null)continue;let a=C3(n,r.prior,i);this.writeSync(e,a.commands),this.saidRestored(e,n,a.kept)}let n=t.binding;if(t.binding={kind:`none`},n.kind===`ours`||n.kind===`adopted`){let t=this.askSync(e,T3);if(t===null)continue;this.writeBindingRestoreSync(e,n.prior,t[0]??``)}}}linkAt(e){let[t,n,r,...i]=di(e);if(t===void 0||n===void 0||r===void 0||i.length>0)return{kind:`refused`,reason:`tmux-status-click needs <socket>/<pane>/<range>, got ${JSON.stringify(e)}`};let a=[...this.held.values()].find(e=>e.socket===t&&e.pane===`%${n}`)?.frame?.links[r];return a===void 0?{kind:`refused`,reason:`pane %${n}'s status line draws no link ${r} now`}:{kind:`link`,url:a}}stats(){return{sessions:this.held.size,layouts:[...this.servers.values()].reduce((e,t)=>e+t.layouts.size,0),writes:this.writes,failedWrites:this.failedWrites}}async settled(){for(let e of this.servers.values())await e.running}serverOf(e){let t=this.servers.get(e);if(t!==void 0)return t;let n={view:null,adopted:!1,layouts:new Map,left:new Map,binding:{kind:`none`},running:null,again:!1,lastFailure:null};return this.servers.set(e,n),n}release(e,t){e.unsubscribe?.(),this.held.delete(e.sessionId),this.deps.log(`info`,`tmux-status: released sid=${JSON.stringify(e.sessionId)} pane=${e.pane} — ${t}`),this.reconcile(e.socket)}reconcile(e){let t=this.servers.get(e);if(!(t===void 0||this.closed)){if(t.running!==null){t.again=!0;return}t.running=(async()=>{try{do t.again=!1,await this.step(e,t);while(t.again&&!this.closed)}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} reconcile threw: ${String(t)}`)}finally{t.running=null}})()}}async step(e,t){let n=t.view;if(n===null)return;t.adopted||(t.adopted=!0,await this.adopt(e,t));let r=new Map;for(let t of this.held.values()){if(t.socket!==e)continue;let i=n.sessionOf.get(t.pane);i!==void 0&&r.set(i,[...r.get(i)??[],t])}for(let i of new Set([...t.layouts.keys(),...t.left.keys(),...r.keys()])){if(this.closed)return;let a=r.get(i)??[],o=t.layouts.get(i);if(a.length===0){t.left.delete(i),o!==void 0&&await this.restore(e,t,i);continue}if(t.left.has(i))continue;let s=o??await this.install(e,t,i);if(s===null)continue;let c=a.find(e=>e.pane===n.shownBy.get(i))?.frame?.rows.slice(0,5-s.prior.base)??[];await this.draw(e,i,s,c)}this.closed||(t.layouts.size>0?await this.installBinding(e,t):await this.restoreBinding(e,t))}async adopt(e,t){let n=await this.run(e,[`list-sessions`,`-F`,`#{session_id}\t#{${X4}}\t#{${Z4}}`]);if(n.kind===`ok`)for(let r of n.stdout.split(`
494
- `)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=b3(i,a,this.deps.owner);o.kind===`ours`?t.layouts.set(n,{prior:o.prior,rows:[],status:o.status}):this.leave(e,t,n,o.why)}let r=(await this.ask(e,[h3(`@cc-candybar-binding-prior`)]))?.[0]??``;if(r!==``)try{let e=JSON.parse(r);e.owner===this.deps.owner&&(t.binding={kind:`adopted`,prior:e.prior})}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${Q4} does not read (${String(t)}), left as it is`)}(t.layouts.size>0||t.binding.kind===`adopted`)&&this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)||`-`} binding=${t.binding.kind}`)}leave(e,t,n,r){t.left.set(n,r),this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} session ${n} left as it is: ${r}`)}async install(e,t,n){let r=await this.ask(e,y3(n));if(r===null||this.closed)return null;let i=x3(n,r,this.deps.owner);if(i.kind===`theirs`)return this.leave(e,t,n,i.why),null;let a={prior:i.prior,rows:[],status:i.kind===`ours`?i.status:i.prior.base};return t.layouts.set(n,a),i.kind===`lay-out`&&await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} session ${n} base=${i.prior.base} own=${[i.prior.status===null?[]:[`status`],i.prior.formats===null?[]:[`status-format`]].flat().join(`,`)||`-`}`),a}async draw(e,t,n,r){let i=n.prior.base+r.length,a=[];if(r.forEach((e,r)=>{n.rows[r]!==e&&a.push([`set-option`,`-t`,t,t3(r),e])}),i!==n.status){let e=i3(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,Z4,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,u3(a)]]))&&(n.rows=r,n.status=i)}async restore(e,t,n){let r=t.layouts.get(n);if(r===void 0)return;t.layouts.delete(n);let i=await this.ask(e,S3(n));if(i===null)return;let a=C3(n,r.prior,i);await this.write(e,a.commands),this.saidRestored(e,n,a.kept)}saidRestored(e,t,n){this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} restored session ${t} kept=${n.join(`,`)||`-`}`)}async installBinding(e,t){let n=t.binding;if(n.kind===`ours`||n.kind===`left`)return;let r=await this.ask(e,T3);if(r===null||this.closed)return;let i=E3(r[0]??``);if(n.kind===`none`&&k3(i)){t.binding={kind:`left`,why:`another cc-candybar daemon's status-line clicks are bound to MouseDown1Status; left as it is, so this daemon's are off`},this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.binding.why}`);return}let a=n.kind===`adopted`&&k3(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...$4,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${l3(`${this.deps.handler} ${O3(e)}`)}`,...a===null?[]:[a.command]],[`set-option`,`-g`,`@cc-candybar-binding-prior`,JSON.stringify(o)]])){t.binding=n;return}this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} bound MouseDown1Status (was ${a===null?`unbound`:JSON.stringify(a.line)})`)}async restoreBinding(e,t){let n=t.binding;if(t.binding={kind:`none`},n.kind!==`ours`&&n.kind!==`adopted`)return;let r=await this.ask(e,T3);if(r===null)return;let i=A3(n.prior,r[0]??``);for(let t of i.steps)await this.write(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.said}`)}writeBindingRestoreSync(e,t,n){let r=A3(t,n);for(let t of r.steps)this.writeSync(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r.said}`)}counted(e,t){let n=this.serverOf(e);return t.kind===`ok`?(n.lastFailure=null,t):(this.failedWrites++,n.lastFailure!==t.reason&&this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.reason}`),n.lastFailure=t.reason,t)}async run(e,t,n){return this.counted(e,await this.deps.edge.run(e,t,n))}async ask(e,t){let n=await this.run(e,f3(t));return n.kind===`ok`?p3(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,f3(t)));return n.kind===`ok`?p3(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,c3(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,c3(t),n)))}};const M3=`CC_CANDYBAR_CONFIG`;function N3(e,t){return JB(t,e[M3])}const $=e=>({arity:e,keep:!0}),P3=e=>({arity:e,keep:!1}),F3={"--add-dir":$(`variadic`),"--agent":$(`one`),"--agents":$(`one`),"--allow-dangerously-skip-permissions":$(`none`),"--allowedTools":$(`variadic`),"--allowed-tools":$(`variadic`),"--append-system-prompt":$(`one`),"--autocompact":$(`one`),"--ax-screen-reader":$(`none`),"--bg":P3(`none`),"--background":P3(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":P3(`optional`),"-c":P3(`none`),"--continue":P3(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":P3(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":P3(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":P3(`none`),"--forward-subagent-text":$(`none`),"--from-pr":P3(`optional`),"-h":P3(`none`),"--help":P3(`none`),"--ide":$(`none`),"--include-hook-events":$(`none`),"--include-partial-messages":$(`none`),"--input-format":$(`one`),"--json-schema":$(`one`),"--max-budget-usd":$(`one`),"--mcp-config":$(`variadic`),"--model":$(`one`),"-n":$(`one`),"--name":$(`one`),"--no-chrome":$(`none`),"--no-session-persistence":$(`none`),"--output-format":$(`one`),"--permission-mode":$(`one`),"--permission-prompts":$(`one`),"--plugin-dir":$(`one`),"--plugin-url":$(`one`),"-p":P3(`none`),"--print":P3(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":P3(`optional`),"--resume":P3(`optional`),"--safe-mode":$(`none`),"--session-id":P3(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":P3(`optional`),"--tmux":P3(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":P3(`none`),"--version":P3(`none`),"-w":P3(`optional`),"--worktree":P3(`optional`)},I3={resume:`--resume`,fresh:`--session-id`};function L3(e){return[I3[e.kind],e.sessionId]}const R3=e=>e.startsWith(`-`)&&e!==`-`;function z3(e,t){let n=H3(t);return n===null?{dir:e??t,args:[]}:e!==null&&B3(e,n.top)?{dir:e,args:[]}:{dir:e===null||H3(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const B3=(e,t)=>e===t||e.startsWith(t+s.sep);function V3(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!R3(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=F3[a];if(o===void 0)return{kind:`refused`,reason:`Claude Code was started with ${a}, which cc-candybar does not know how to carry to a restart`};let s=i===-1?o.arity===`one`?n.slice(r,r+1):o.arity===`optional`?n.slice(r,r+1).filter(e=>!R3(e)):o.arity===`variadic`?U3(n.slice(r),e=>!R3(e)):[]:[];if(o.arity===`one`&&i===-1&&s.length===0)return{kind:`refused`,reason:`Claude Code was started with ${a} and no value after it`};r+=s.length,o.keep&&t.push(e,...s)}return{kind:`args`,args:t}}function H3(e){let t=e.split(s.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(s.sep),repo:t.slice(0,n-1).join(s.sep)||s.sep}}function U3(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const W3=`candybar-band@cc-candybar`,G3=s.join(`bin`,`cc-candybar-native`),K3=`@cc-candybar-bar-pane`,q3=cP(`/reload-plugins`),J3=e=>({kind:`done`,said:e});function Y3(e){let t=q0(e.hints.tmux);if(t.kind===`refused`)throw new q(t.reason);return t.hint}const X3={band:{on:(e,t,n)=>{let r=Qe(t.bundle);if(r===null)throw new q(`${Pv.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=s.join(r,G3);if(!n.fileExists(i))throw new q(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${W3} from ${r}`,finished:Z3(e,r,n)}},off:()=>J3(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=Y3(e),i=Re(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new q(`${Pv.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return{kind:`underway`,said:`restarting Claude Code in ${r.pane} under the attach launcher`,finished:e6(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>J3(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=Y3(e),i=n.barPanes(r);return i.length>0?J3(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):J3(`opened bar pane ${n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:(e,t,n)=>{let r=q0(e.hints.tmux);if(r.kind===`refused`)return J3(`no bar pane to close: ${r.reason}`);let i=r.hint,a=n.barPanes(i);for(let e of a)n.closePane(i,e);return J3(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>J3(`the daemon draws ${Y3(e).pane}'s bar in its status line`),off:()=>J3(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function Z3(e,t,n){let r={sessionId:e.sessionId,projectDir:e.origin.projectDir,claudeConfigDir:e.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,W3],r);let i=J0(n.claudeInput,e.hints.tmux,q3);if(i.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${i.reason} — or type /reload-plugins yourself`);return`installed ${W3} from ${t} and typed /reload-plugins into ${i.pane}`}const Q3=new Set([qa,M3]);function $3(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function e6(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,ze(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${Pv.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);if((await r.paneClaude(t)).pid!==i.pid)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}), so it was not restarted under the attach launcher`);let o=a6(r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${Pv.statusline.label} off and on again`);let s=t6(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=V3(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=$3(i.env),u=l.get(`PATH`),d=r.launcherNode(u);if(d.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${d.why}`);let f=r.onPath(`claude`,u)===i.executable?`claude`:i.executable,p=[...l].filter(([e])=>Q3.has(e)),m=(e,t)=>He(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...L3(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${15e3/1e3} s of SIGTERM, so it was not restarted under the attach launcher`);let h=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),g=n6(e,r.presence(e.transcript)),_=g.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:g,v;try{v=await r.paneDir(t,i.parent)}catch(e){throw h(`the directory it was started in could not be read (${e.message})`,m(z3(null,i.cwd),_))}let y=m(z3(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{r.typeShellLine(t,y)}catch(e){throw h(`the line could not be typed into its pane (${e.message})`,y)}if(!await r.followed(e.sessionId,`statusline`,3e4))throw Error(`Claude Code in ${t.pane} did not come back attached within ${3e4/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${r6[g.kind](e.sessionId)}, and its statusline follows lane B`}function t6(e,t){return typeof t==`object`?`whether session ${e.sessionId} has a conversation could not be seen (${t.error})`:t===`present`||e.answered===`no`?null:e.answered===`yes`?`session ${e.sessionId} has a conversation but no transcript to resume it from (is session persistence off?), so a restart would lose it`:`this Claude Code does not say whether session ${e.sessionId} has a conversation, and it has no transcript to resume one from`}function n6(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const r6={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},i6={"in-mode":`its pane is in tmux copy mode — leave it (q)`,stashed:`it holds a stashed prompt (ctrl+s), which ending it would lose — restore or send it`,"no-prompt":`it is not at its prompt (a dialog or picker is open) — close it`};function a6(e){let t=H0(e);return t.kind===`ready`?G0(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:U0(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:i6[t.kind]}var o6=class{owed=new Map;queued=new Map;constructor(e){this.deps=e}clicked(e,t,n,r){let i=Fv.filter(e=>n[e]!==r[e]),a=this.take(e);for(let e of i)a.has(e)||a.set(e,n[e]);let o=e=>i.includes(e)?`click`:`owed`;if(t!==null){this.settle(t,a,r,o);return}for(let[e,t]of a)t===r[e]&&a.delete(e);if(i.length>0){let t=[...a.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}a.size>0&&this.owed.set(e,a);for(let[e,t]of this.owed){if(this.owed.size<=1024)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t){this.settle(e,this.take(e.sessionId),t,()=>`owed`)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r){for(let[i,a]of t)n[i]===a?this.deps.log(`info`,`lane: ${i} ${a?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(i)} (session=${e.sessionId})`):this.start(e,i,n[i],r(i))}start(e,t,n,r){this.deps.defer(()=>this.enqueue(e.sessionId,()=>this.sync(e,t,n,r)))}enqueue(e,t){let n=this.queued.get(e);if(n!==void 0){n.push(t);return}let r=[];this.queued.set(e,r);let i=t=>void t().then(()=>{let t=r.shift();t===void 0?this.queued.delete(e):i(t)});i(t)}sync(e,t,n,r){let i=`by=${r} (session=${e.sessionId})`,a=r=>{let a=`lane: ${t} ${n?`on`:`off`}: ${r instanceof Error?r.message:String(r)}`;this.deps.log(`warn`,`${a} ${i}`),$o(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=X3[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){return a(e),Promise.resolve()}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`underway`?o.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${i}`),a):Promise.resolve()}};function s6(e,t,n){for(let r of(t??``).split(s.delimiter)){if(!s.isAbsolute(r))continue;let t=s.join(r,e);if(n(t))return t}return null}function c6(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function l6(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function u6(e,t,n){let r=s6(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const d6=2e3;function f6(e,t,n){let r=NK(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function p6(e,t){if(t.ok)return t.stdout;let n=t.error??[t.reason,t.stderr.trim(),t.stdout.trim()].filter(e=>e!==``).join(`: `);throw Error(`${e} failed (${n})`)}function m6(e){try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`ok`in t&&t.ok===!1&&`reason`in t&&typeof t.reason==`string`)return`detail`in t&&typeof t.detail==`string`?`${t.reason}: ${t.detail}`:t.reason}catch{}return null}const h6=`#{pane_id} #{${K3}}`;function g6(e,t){return e.split(`
495
- `).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const _6=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function v6(e,t,n){for(let r of B$(z$(e),t)){if(r.command.split(` `).some(e=>_6.test(e)))return!0;if(r.pid===n)return!1}return!1}const y6=[`import ctypes, json, struct, sys`,`libc = ctypes.CDLL(None)`,`mib = (ctypes.c_int * 3)(1, 49, int(sys.argv[1]))`,`size = ctypes.c_size_t(0)`,`if libc.sysctl(mib, 3, None, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`buf = ctypes.create_string_buffer(size.value)`,`if libc.sysctl(mib, 3, buf, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`raw = buf.raw[:size.value]`,`argc = struct.unpack_from('i', raw)[0]`,`rest = raw[4:]`,`end = rest.index(b'\\0')`,`exe = rest[:end].decode('utf-8', 'surrogateescape')`,`rest = rest[end:].lstrip(b'\\0')`,`words = [w.decode('utf-8', 'surrogateescape') for w in rest.split(b'\\0')]`,`end = words.index('', argc) if '' in words[argc:] else len(words)`,`print(json.dumps({'executable': exe, 'argv': words[:argc], 'env': words[argc:end]}))`].join(`
496
- `);async function b6(e){if(process.platform===`linux`)return{executable:await p.promises.readlink(`/proc/${e}/exe`),argv:(await p.promises.readFile(`/proc/${e}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await p.promises.readFile(`/proc/${e}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let t=p6(`reading process ${e}'s arguments`,await pt({bin:`python3`,args:[`-c`,y6,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function x6(e,t){return p6(e,await pt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function S6(e){let t=await PK(e,`lane.tmux`,[`display`,`-p`,`-t`,e.pane,`#{pane_pid} #{pane_current_path}`]);if(t.kind!==`ok`)throw Error(t.reason);let[n=``,r=``]=t.stdout.trimEnd().split(` `),i=(await x6(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function C6(e){let{panePid:t,cwd:n,foreground:r}=await S6(e),i=await x6(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await b6(r),o=z$(i).get(r)?.ppid;if(o===void 0)throw Error(`pane ${e.pane}'s foreground job ${r} is gone`);return{pid:r,executable:await p.promises.realpath(a.executable),argv:a.argv,env:a.env,cwd:n,parent:o,fromShell:r!==t,attached:v6(i,r,t)}}function w6(e){return{claudeInput:$0(),barPanes:e=>g6(f6(e,[`list-panes`,`-a`,`-F`,h6]),e.pane),openBarPane:(e,t,n)=>{let r=f6(e,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,e.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(n).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...t]).trim();return f6(e,[`set-option`,`-p`,`-t`,r,K3,e.pane]),r},closePane:(e,t)=>void f6(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void p6(`claude ${e.join(` `)}`,await pt({bin:`claude`,args:[...e],env:T$(process.env,t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:BV,paneClaude:C6,paneDir:async(e,t)=>{let n=Date.now()+d6;for(;;){let r=await S6(e);if(r.foreground===t){if(r.cwd===``)throw Error(`tmux read no directory for pane ${e.pane}`);return r.cwd}if(Date.now()>n)throw Error(`the shell in pane ${e.pane} (pid ${t}) did not take its terminal back within ${d6/1e3} s`);await be(100)}},launcherNode:e=>u6(e,e=>c6(e,p.constants.X_OK),l6),onPath:(e,t)=>{let n=s6(e,t,e=>c6(e,p.constants.X_OK));return n===null?null:p.realpathSync(n)},followed:async(t,n,r)=>{let i=Date.now()+r;for(;!e(t).has(n);){if(Date.now()>i)return!1;await be(200)}return!0},moduleGraph:async(e,t,n)=>{let r=await pt({bin:e,args:[t,n],timeoutMs:2e4,category:`lane.process`}),i=!r.ok&&r.reason===`non-zero`?m6(r.stdout):null;return i===null?(p6(`reading ${n}'s module graph`,r),{ok:!0}):{ok:!1,reason:i}},terminate:e=>{try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=Date.now()+t;for(;ws(e);){if(Date.now()>n)return!1;await be(100)}return!0},typeShellLine:(e,t)=>void f6(e,Z0(e.pane,`cc-candybar-lane`,[]),t)}}function T6(e,t){return Fv.filter(n=>e[n]&&Pv[n].elsewhere!==null&&t.has(n))}function E6(e,t){let n=`the bar is drawn in ${t.map(e=>Pv[e].elsewhere).join(` and `)}`,r=pi([{verb:Qr,args:[e,...t.map(e=>Pv[e].setting)]}]);return{channels:[{severity:vb,message:n,lines:[[yb(n,pi([{verb:Br,args:[n]}])),yb(`[⟲ draw it here]`,r)]]}]}}const D6={order:-1/0,text:null,failure:null};var O6=class{synced=new Map;constructor(e,t){this.dir=e,this.changed=t}pathFor(e){return s.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t,n){let r=this.synced.get(e)??D6;if(t<r.order)return{link:this.linkFor(e,n),failure:null};let i=n===r.text&&r.failure===null?null:this.write(e,n);return this.synced.delete(e),this.synced.set(e,{order:t,text:n,failure:i}),this.forgetOldestClean(),(n!==r.text||i!==r.failure)&&this.changed(e),{link:this.linkFor(e,n),failure:i}}linkFor(e,t){let n=this.synced.get(e)??D6;return n.text===t?n.failure===null?{kind:`file`,path:this.pathFor(e)}:{kind:`unavailable`,reason:n.failure}:{kind:`unavailable`,reason:`the file holds another render's text until the session's next statusline request`}}forgetOldestClean(){let e=0;for(let t of this.synced.values())t.text===null&&t.failure===null&&e++;for(let[t,n]of this.synced){if(e<=256)return;n.text!==null||n.failure!==null||(this.synced.delete(t),e--)}}write(e,t){let n=this.pathFor(e);try{return t===null?p.rmSync(n,{force:!0}):(p.mkdirSync(this.dir,{recursive:!0,mode:448}),p.writeFileSync(n,t,{mode:384})),null}catch(e){return`${n}: ${e.message}`}}reset(){this.synced.clear();try{return p.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}},k6=class{sessions=new Map;constructor(e){this.deps=e}clicked(e,t){this.record(e,t).since=t,this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;return{sessions:this.sessions.size,armed:e}}dispose(){for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=256)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown?qv(t.since,t.timeoutS):null;if(t.timer?.at===n||(this.disarm(t),n===null))return;let r=setTimeout(()=>this.fire(e),Math.max(0,(n-this.deps.now())*1e3));r.unref(),t.timer={at:n,handle:r}}disarm(e){e.timer!==null&&clearTimeout(e.timer.handle),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now(),r={idleS:n-t.since,timeoutS:t.timeoutS};t.since=n,t.shown=!1;try{this.deps.close(e,r)}catch(t){this.deps.failed(e,t)}}};function A6(e){return e===void 0?{kind:`unstated`}:typeof e==`number`&&Number.isSafeInteger(e)&&e>0?{kind:`stated`,at:e}:{kind:`refused`,problem:`request 'deadline' is not epoch milliseconds: ${JSON.stringify(e)}`}}function j6(e,t,n){let r=e.kind===`stated`?n.monoMs+(e.at-n.epochMs):t+150-50,i=Math.min(r,t+200);return Math.round(i-40-n.monoMs)}function M6(e,t){for(let n of Object.entries(t))e.push(n)}const N6={ok:`info`,"bad-request":`warn`,threw:`error`};function P6(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,T(e.error)]]}}function F6(e,t,n){let r=[...e,[`took`,`${n}ms`],[`outcome`,t.kind],...P6(t)];return{level:N6[t.kind],line:`render${r.map(([e,t])=>` ${e}=${as(t)}`).join(``)}`}}const I6=new PZ,L6=new O0,R6=new xM,z6=i(import.meta.url),B6=R1(yt());dt(I6.launchStats);const V6=new ZW({counters:I6,logger:M}),H6=new jk(M),U6=aq({watchers:V6,logger:M,ledger:H6}),{gitProvider:W6,usageStore:G6,tmuxService:K6,hostService:q6,managedStorage:J6}=U6,Y6=new LZ,X6=new KQ(Y6,M),Z6=new h$,Q6=new eb,$6=new k6({now:()=>ik(new Date),close:(e,t)=>f4(e,t,B8),failed:(e,t)=>M(`error`,`menu-idle: close failed (session=${e}): ${T(t)}`)}),e8=Yo(),t8=new ls({supersede:(e,t)=>J6.supersede(e,t),launch:pt,state:Y6,log:M,now:()=>ik(new Date)}),n8=[t.execPath,...t.execArgv],r8=new o6({edge:w6(e=>a8.following(e)),host:{bundle:z6,node:n8,socket:St(),preload:Do(z6)},state:Y6,log:M,now:()=>ik(new Date),defer:e=>void _e(e)}),i8=new j3({edge:{run:(e,t,n)=>PK({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>NK({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>a8.subscribe(e,t),sessionInPane:(e,t)=>a8.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${Fe(St())}`,...[...n8,z6].map(Fe),`url-handle`].join(` `),owner:St(),log:M}),a8=new V4({render:(e,t)=>K8(e,t),watch:(e,t)=>(0,J.reaction)(()=>Y6.revision(e),t),lanes:e=>J8(e),pin:e=>l8.pin(e),shown:e=>o8.shown(e.hints.tmux),watching:()=>o8.follow(),refreshes:()=>H6.totals(),periods:P4,now:()=>performance.now(),log:M}),o8=new J4({listPanes:e=>PK({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,U4]),listClients:e=>PK({socket:e},`frames.visibility`,[`list-clients`,`-F`,W4]),sockets:()=>new Set(a8.watched().flatMap(({req:e})=>s8(e))),onAnswer:(e,t)=>i8.answered(e,t),onChange:e=>a8.wakeWhere(`visibility`,t=>s8(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function s8({hints:{tmux:e}}){return e==null?[]:[e.socket]}const c8=new O6(Pt(),e=>a8.wake(e,`data`)),l8=new MZ({sessionState:Y6,watchers:V6,log:M,storage:J6,signer:e8,ledger:H6,declare:(e,t,n,r)=>Pq(U6,e,t,n,r),source:N4({providers:U6,sessionState:Y6,history:e=>X6.depth(e),navigation:(e,t)=>Z6.depth(e,Y6,_U(t))})},{budgetBytes:()=>(C8(),_Z(h8)),observers:{onReload:(e,t)=>{M(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`);for(let e of t)a8.wake(e,`reload`)},onViewChanged:e=>a8.wake(e,`data`)}}),u8=60*1e3,d8=HU({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:u8,stat:p.statSync,exit:()=>O8(0),log:M}),f8=zU({entryUrl:import.meta.url,intervalMs:u8,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>d8.checkNow(),log:M});let p8=null,m8=null,h8=0;function g8(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),O8(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),O8(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),O8(0)});try{w8(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),O8(1);return}p8=bs(t.pid);let e=As(Ms(p8));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),O8(1);return}m8=e.registryPath,p.mkdirSync(xt(),{recursive:!0}),Tt(St()),Y6.useStorage(new zZ(Ot(),500,M)),X6.useStorage(p$(kt(),M)),Cs({anchor:Ss(t.env),isAlive:ws,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),O8(0)}}),v8(ue.createServer({allowHalfOpen:!1},e=>{k8(e)}),St(),!1)}function _8(){let e=W6.getStats(),t=K6.getStats(),n=G6.scanStats(),r=J6.stats(),i=l8.stats;return{records:H6.snapshot(),homes:{daemon:1,configDir:n.entries,repo:e.size,directory:i.size,session:G6.getStats().size,view:i.views,pane:t.entries},held:{git:e.held,tmux:t.held,host:q6.held(),today:n.held,pluginStorage:r.held},pluginStorage:{folders:r.folders,faults:r.faults,lost:r.lost}}}function v8(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),O8(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}y8(e,n)}),e.listen(n,()=>b8(n))}function y8(e,n){let r=us(ds(Et(n)),(e,t)=>ys(e,t,{readStartTime:vs,pidAlive:ws}));if(r.kind===`attach-and-exit`){M(`info`,`EADDRINUSE: ${r.reason} — exiting`),t.exit(0);return}M(`warn`,`EADDRINUSE: ${r.reason} — unlinking stale socket and rebinding`);try{p.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){M(`error`,`cannot unlink stale socket ${n}: ${e.message}`),O8(1);return}}v8(e,n,!0)}function b8(e){let n=ms(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),O8(0);return}T8(e);try{p.chmodSync(e,384)}catch(e){M(`warn`,`chmod socket failed: ${e.message}`)}M(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${tr(de.getHeapStatistics().heap_size_limit)}MB memoryLimit=${tr(h8)}MB`),Tr();let r=c8.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),d8.arm(),f8.arm(),C8().arm(),x8(e,n.identity)}function x8(e,n){_s({bound:n,myPid:t.pid,readIdentity:()=>ms(e),readLease:()=>ds(Et(e)),shutdown:e=>O8(e),log:M}).arm()}let S8=null;function C8(){if(S8===null)throw Error(`daemon: limits not yet established`);return S8}function w8(e){h8=nr(e),S8=ur(gr(I6.startedAt.getTime(),e=>O8(e),{limitBytes:h8}))}function T8(e){let n=fs(Et(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:p8});n!==null&&M(`warn`,`lease write failed: ${n}`)}let E8=0,D8=!1;function O8(e){if(D8)return;D8=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);let n=[[`tmuxStatusLines restore`,()=>i8.restoreAll()],[`gitService close`,()=>W6.close()],[`usageStore close`,()=>G6.close()],[`tmuxService close`,()=>K6.close()],[`hostService close`,()=>q6.close()],[`runs close`,()=>t8.close()],[`managedStorage close`,()=>J6.close()],[`watcherRegistry close`,()=>V6.closeAll()],[`sessionState flush`,()=>Y6.flush()]];for(let[e,t]of n)try{t()}catch(t){M(`warn`,`${e} failed: ${t.message}`)}ps(Dt(),t.pid),m8!==null&&js(m8,t.pid,Os,e=>p.unlinkSync(e)),t.exit(e)}function k8(e){let t=performance.now();E8++,I6.inFlight=E8;let n=!1,r=!0,i=()=>{r&&(r=!1,E8=Math.max(0,E8-1),I6.inFlight=E8)},a=(t,r,i)=>{if(n){r!==null&&M(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}n=!0;let a=r===null?void 0:()=>O8(r);try{e.end(Qt(t),e=>{e??i(),a?.()})}catch(e){M(`warn`,`response write failed: ${e.message}`),a?.()}},o=!1,s=setTimeout(()=>{o=!0,I6.requestsTimedOut++,a({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,A8)},200),c=en(e=>{L8(e,()=>o,t).then(e=>e.kind===`reply`?a(e.resp,e.exitAfterFlush,e.delivered):l(e.sessionId,e.lane)).catch(e=>{M(`error`,`handler threw: ${T(e)}`),a(P8(e),null,A8)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),a({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,A8)}),l=(t,r)=>{if(n||e.destroyed)return;clearTimeout(s),i(),e.off(`data`,c);let a=H4(e),o=a8.subscribe(t,{lane:r,frame:(e,t)=>a($t(dW[r](e,t))),refused:t=>e.end(Qt(t)),drawing:()=>!0});n=!0,e.on(`close`,o)};e.on(`data`,c),e.on(`error`,e=>{M(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(s),i()})}const A8=()=>{},j8=e=>({resp:e,exitAfterFlush:null,delivered:A8}),M8=e=>({kind:`reply`,...e}),N8={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},P8=e=>({ok:!1,error:e instanceof Error?e.message:T(e),code:`RENDER_FAILED`,daemonV:3}),F8=(e,t)=>M8(j8({ok:!1,error:t,code:e,daemonV:3}));function I8(e){let t=fW(e.sessionId);if(!t.ok)return F8(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return F8(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Fv.join(`, `)}): it predates the lane toggles — update it`);let n=Hv(e.lane);return n===null?F8(`BAD_REQUEST`,`subscribe needs a lane, one of ${Fv.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function L8(e,t,n){return!e||typeof e!=`object`||typeof e.v!=`number`?F8(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?I8(e):typeof e.kind!=`string`||!Object.hasOwn(N8,e.kind)?F8(`BAD_REQUEST`,`unknown kind`):M8(await R8(e,t,n)):(e.v>3?M(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):M(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null,delivered:A8})}async function R8(e,t,n){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:A8};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return j8(typeof t!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:a8.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return j8({ok:!0,stats:I6.snapshot({gitCache:W6.getStats(),usageCache:G6.getStats(),sources:_8(),runs:t8.stats(),transcriptReads:Ra(),renderCache:l8.stats,effectCache:Q6.getStats(),menuIdle:$6.getStats(),sessionState:{sessions:Y6.size(),observers:Y6.observers(),revision:Y6.latestRevision()},frameFeeds:a8.getStats(),tmuxStatus:i8.stats(),watchersActive:V6.size(),nextRestartReason:C8().describeNextRestart(),handlerProbes:L6.list(),clients:R6.list(ik(new Date)),bundle:z6,daemon:C8().serving(),doctorStores:z1(B6)})});if(e.kind===`render`){let r=new Date,i=ik(r),a=performance.now(),o=Math.round(a-n),s=[],c=++I6.requestsTotal,l=X8(e),u=(e,t)=>R6.see(e.sessionId,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:Ya(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:_M(e.hookData),frame:t},i,c);l.ok&&(u(l.req,`drawing`),a8.note(l.req.sessionId,l.req,c));let d=l.ok?await o5(l.req,c,i,(e=>{let t=j6(e.deadline,n,{epochMs:r.getTime(),monoMs:a});return{stated:e.deadline.kind,ms:t,endsAt:a+t}})(l.req),s).then(({answer:e,motion:t,clickShown:n})=>(u(l.req,t),{outcome:{kind:`ok`},resp:{ok:!0,output:e},delivered:n===null?A8:()=>es(Y6,l.req.sessionId,n)}),e=>(u(l.req,`failed`),{outcome:{kind:`threw`,error:e},resp:P8(e),delivered:A8})):Z8(l.problems);d.outcome.kind!==`ok`&&I6.requestsErrored++,M6(s,{timedOut:t()?`Y`:`N`,queued:`${o}ms`});let{level:f,line:p}=F6(s,d.outcome,Math.round(performance.now()-a));return M(f,p),{resp:d.resp,exitAfterFlush:null,delivered:d.delivered}}if(e.kind===`click`)return j8(W8(e.verb,e.value,{via:`link`,handler:Zt(e.clientVersion)}));if(e.kind===`debug`){if(!M4(e.what))return j8({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${j4.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=l8.latestView(),n=t===null?null:{store:t.store,registry:t.registry,config:t.state.config,compiled:t.state.compiled,lastRenderBySegment:e.what===`segments`?U8(t.lastRenderCellsBySegment,t.state.config.globals.colorCompatibility??vy(`colorCompatibility`)):H8};return j8({ok:!0,debug:b4(e.what,n)})}throw Error(`no reply for request ${T(e)}`)}function z8(e,t){let{tokens:n}=ce({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=(n??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),i=(n??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===r&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:JB(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const B8={sessionState:Y6,dlog:M,applyUpdate:()=>f8.act(),doctor:Y1(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];l8.reload(...t);let n=l8.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:B6,probes:L6,clients:R6,bundle:z6,serving:()=>C8().serving(),claudeInput:$0(),history:X6,navigation:Z6,configFor:e=>l8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>l8.reload(e.projectDir,e.cwd,e.configFile??void 0),sourcesFor:e=>l8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.sources,links:e8,runs:t8,lanes:{of:Y8,clicked:l5},views:{follow:(e,t)=>l8.follow(e,t.projectDir,t.cwd,t.configFile??void 0)}};B8.reloadConfig;const V8={endcaps:vy(`endcaps`),colorCompatibility:vy(`colorCompatibility`),wrap:vy(`autoWrap`),padding:vy(`padding`),width:1/0},H8=new Map;function U8(e,t){let n=new Map;for(let[r,i]of e)n.set(r,pb(i,{...V8,colorCompatibility:t}));return n}function W8(e,t,n){if(e===`tmux-status-click`)return G8(t);let r=d4.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{let i=s4(e,t);return i!==null&&$6.clicked(i,ik(new Date)),r(t,{...B8,arrival:n}),{ok:!0,output:``}}catch(e){let t=e instanceof q?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}function G8(e){let n=e=>({ok:!1,error:e,code:`BAD_REQUEST`,daemonV:3}),r=i8.linkAt(e);if(r.kind===`refused`)return n(r.reason);if(M(`info`,`tmux-status: click ${JSON.stringify(r.url)}`),r.url.startsWith(`cc-candybar://`)){let e=zo(r.url);return e.verb===`tmux-status-click`?n(`a status-line link names another status-line click`):W8(e.verb,e.value,{via:`tmux-status`})}let i=D({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[r.url],category:`click.open`});return i.ok?{ok:!0,output:``}:{ok:!1,error:`opening ${r.url} failed (${i.error??i.reason})`,code:`RENDER_FAILED`,daemonV:3}}function K8(e,t){let n=new Date,r=ik(n),i=[];try{try{var a=Aa();let n=a.u(e5(e,r,i));if(n===null)return null;let{drawn:o,motion:s,evaluated:c,lanes:l}=n5(n,{by:`feed`,fps:t}),u=c8.linkFor(e,i5(o)),d=r5(o,u);return{at:r,resp:{ok:!0,output:d},statusline:{ok:!0,output:d5(e,o,u,d,T6(l,a8.following(e)))},moves:s===`moves`,evaluated:c,failure:null}}catch(e){a.e=e}finally{a.d()}}catch(e){let{level:t,line:a}=F6(i,{kind:`threw`,error:e},Date.now()-n.getTime()),o=P8(e);return{at:r,resp:o,statusline:o,moves:!1,evaluated:0,failure:{level:t,line:`frame ${a}`}}}}function q8(e,t){return FH(t.config,t=>Y6.get(e,t),e=>t.authoredRoots.has(e))}function J8(e){try{var t=Aa();let n=t.u(l8.holdView(e));return n===null?null:MH(n.view.source.effective())}catch(e){t.e=e}finally{t.d()}}function Y8(e,t){try{var n=Aa();return MH(q8(t,n.u(l8.hold(e.projectDir,e.cwd,e.configFile??void 0)).state))}catch(e){n.e=e}finally{n.d()}}function X8(e){let{report:t}=g4(e.hookData);for(let e of t.unknownTopLevelFields)M(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let n=[];for(let e of t.missingRequired)n.push(`missing required field '${e}'`);for(let{path:e,expected:r,got:i}of t.typeMismatches)n.push(`field '${e}' expected ${r}, got ${i}`);let r=fW(e.hookData?.session_id);r.ok||n.push(`field 'session_id' ${r.problem}`),(typeof e.cwd!=`string`||!u(e.cwd))&&n.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&n.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let i=A6(e.deadline);if(i.kind===`refused`)return{ok:!1,problems:[...n,i.problem]};if(n.length>0||!r.ok)return{ok:!1,problems:n};let a=Vt(e),{configFile:o,refusedArgs:s}=z8(e.args,e.cwd);return{ok:!0,req:{...e,deadline:i,sessionId:r.id,hints:a,rateLimits:gM(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:o??a.configEnv??null},refusedArgs:s}}}const Z8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:A8});function Q8(e,t,n){M6(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=Ht(e,r),a=Ut(i);return M6(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:i.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits}),a}function $8(e,t,n){let r=e.sessionId,i=Q8(e,t,n),a=_2(e.requested,Y6,r);return t5(l8.holdSession(a.projectDir,a.cwd,a.configFile??void 0,e),e,i,t,n)}function e5(e,t,n){let r=l8.holdView(e);if(r===null){let t=l8.openFailure(e);if(t!==null)throw t.error;return null}let i=r.view.facts(),a;try{a=Q8(i,t,n)}catch(e){throw r[Symbol.dispose](),e}return t5(r,i,a,t,n)}function t5(e,t,n,r,i){try{let{entry:a,state:o,view:s}=e,{sessionId:c,hints:l}=t,u=s.source.effective();return{req:t,at:r,facts:i,sessionId:c,entry:a,state:o,view:s,hintsError:n,payloadInputs:{hookData:t.hookData,deps:{...U6,lanes:s.lanes},cwd:t.cwd,neededInputPaths:o.neededInputPaths(u.preset),hints:l},[Symbol.dispose]:()=>e[Symbol.dispose]()}}catch(t){throw e[Symbol.dispose](),t}}function n5(e,t){let{req:n,at:r,facts:i,sessionId:a,entry:o,state:s,view:c,hintsError:l}=e,u=c.source.effective(),d=MH(u);M6(i,{lanes:Fv.filter(e=>d[e]).join(`,`)||`-`});let{hints:f}=c.facts(),p=Dq(f),m=mb(f.termRows);M6(i,{width:String(p)});let h=c.source.payload(),g={drawing:t,feeds:a8.feedsOf(a,r),today:Uq(U6,c.lanes().today,c.facts().hookData,r)},_=ka(h.metrics)?void 0:h.metrics;M6(i,Rq(c.lanes().sources)),M6(i,{prompts:String(_?.messageCount??`-`),nonPrompts:String(_?.nonPrompts??`-`),pr:dq(h.git,Cq(e.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:I4(g.feeds)});let v=[],y=cq(u,p),b=Q6.of(a),ee=$6.since(a,r),x=fZ(s.config,s.compiled,c.store,c.registry,g,r,y,{perSegmentSink:c.lastRenderCellsBySegment,onRenderWarning:e=>v.push(e)},{...u,effects:b,idleSince:ee});$6.observe(a,r,x.menuRows>0,u.menuTimeout);let S=$6.since(a,r);M6(i,{menuIdle:S===void 0?`-`:`${(r-S).toFixed(1)}s/${u.menuTimeout}s`});let te=ns(Y6,a,r,t.by),ne=te.kind===`held`||te.kind===`owed`?te.error:null,re=ne?.text??null,ie=[Gt(n.refusedArgs),l,o.lastError,re].filter(Boolean).join(`
497
- `),ae=f8.notice({sessionId:a,dismissed:Y6.get(a,CU),enabled:u.updateNotice}),C=o.lastError===null?null:o.failedFile,w=[...o.lastWarning===null?[]:[{kind:`load`,message:o.lastWarning}],...v],oe=bb(ie,ae,w.map(e=>e.message).join(`
498
- `)),se=W6.getStats(),T=G6.getStats(),ce=b.lastFrame(),le=ce.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,ue=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,de=w.map(e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`load`:case`band-floor`:case`when`:return e.kind}}).join(`,`)||`-`;return M6(i,{git:`${se.size}/${se.hits}h/${se.misses}m`,usage:`${T.size}/${T.hits}h/${T.misses}m`,effect:ce.effect,effectT:ce.t.toFixed(3),speed:`${ce.speed}x`,effectRows:`${ce.made}made/${ce.reused}reused`,effectOwn:le,fadeBasis:ce.basis,stateRev:String(ce.revision),fades:ue(ce.fades),leaves:ue(ce.leaves),motion:x.motion,evaluated:String(x.evaluated),pending:x.pending.join(`,`)||`-`,rules:[...x.rules].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:ie?`Y`:`N`,clickError:te.kind===`none`?`-`:te.kind,upd:String(ae.length),warn:de}),{drawn:{body:x.text,diagnostics:oe,failedConfigFile:C,geometry:{width:p,rowCap:m,colorCompatibility:u.colorCompatibility}},motion:x.motion,evaluated:x.evaluated,clickShown:ne,lanes:d}}function r5(e,t){return Cb(e.body,e.diagnostics,{fullText:t,failedConfigFile:e.failedConfigFile},e.geometry)+`
499
- `}function i5(e){return e.diagnostics===null?null:Sb(e.diagnostics)}function a5(e){let t=e.sessionId,{client:n,...r}=e.hints,i=JSON.stringify(r);Y6.get(t,`client-hints`)!==i&&Y6.set(t,K2,i);let a=v2(e.requested);Y6.get(t,`render-origin`)!==a&&Y6.set(t,g2,a)}async function o5(e,t,n,r,i){return a5(e),u5(e,t,n,r,i)}function s5(e,t){r8.noted(c5(e),t),i8.observe(e.hookData.session_id,e.hints.tmux,t.tmuxStatus)}function c5(e){let t=e.hookData.session_id;return{sessionId:t,hints:e.hints,origin:_2(e.requested,Y6,t),transcript:e.hookData.transcript_path,answered:mM(e.hookData)}}function l5(e,t,n){let r=a8.latest(e);r8.clicked(e,r===null?null:c5(r),t,n),r!==null&&t.tmuxStatus!==n.tmuxStatus&&i8.observe(e,r.hints.tmux,n.tmuxStatus)}async function u5(e,t,n,r,i){try{var a=Aa();let o=a.u($8(e,n,i));s5(e,MH(o.view.source.effective())),M6(i,{deadline:`${r.stated}:${r.ms}ms`});let s=performance.now(),c=new Map,l=await cG(e=>Promise.all([Wq(o.payloadInputs,n,c),o.view.registry.inFlight(e)]),r.endsAt-s,e=>M(`error`,`render wait failed after its deadline sid=${JSON.stringify(o.sessionId)}: ${T(e)}`)),u=performance.now();M6(i,{waited:`${Math.round(u-s)}ms`,ended:l,refreshed:kq(c)});let{drawn:d,motion:f,clickShown:p,lanes:m}=n5(o,Iv),{link:h,failure:g}=c8.sync(e.sessionId,t,i5(d));M6(i,{dumpFailed:g===null?`-`:JSON.stringify(g)});let _=r5(d,h),v=e.sessionId,y=T6(m,a8.following(v)),b=d5(v,d,h,_,y),ee=bM(e.hints.client??null)===`statusline`;return M6(i,{handoff:(ee?y:[]).join(`,`)||`-`,drew:`${Math.round(performance.now()-u)}ms`}),{answer:ee?b:_,motion:f,clickShown:p}}catch(e){a.e=e}finally{a.d()}}function d5(e,t,n,r,i){let[a,...o]=i;return a===void 0?r:r5({...t,body:wb(E6(e,[a,...o]),t.geometry)},n)}const f5={connectMs:200,budgetMs:500};async function p5(e,n){let r=n.includes(`--json`),i=await m5(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${un(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
500
- `);return}t.stdout.write(h5(i.value))}function m5(e){return rn(()=>({kind:`debug`,what:e}),f5,e=>`debug`in e?e.debug:void 0)}function h5(e){switch(e.what){case`vars`:return g5(e.vars);case`segments`:return _5(e.segments);case`config`:return v5(e.config);default:return e}}function g5(e){if(e.length===0)return`no variables (DSL not active)
501
- `;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${b5(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${y5(a.value)}${e}${o}`)}return t.join(`
492
+ `)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var X4=class{servers=new Map;loop={kind:`idle`};constructor(e){this.deps=e}follow(){switch(this.loop.kind){case`idle`:this.deps.log(`info`,`visibility following`),this.ask();break;case`asking`:this.loop.following=!0;break;case`due`:break}return()=>this.stop()}stop(){switch(this.loop.kind){case`due`:clearTimeout(this.loop.timer),this.end();return;case`asking`:this.loop.following=!1;return;case`idle`:return}}ask(){let e={kind:`asking`,following:!0};this.loop=e,Promise.resolve().then(()=>this.refresh(this.deps.sockets())).catch(e=>this.deps.log(`error`,`visibility refresh threw: ${T(e)}`)).then(()=>{if(e.following){this.loop={kind:`due`,timer:setTimeout(()=>this.ask(),this.deps.intervalMs).unref()};return}this.end()})}end(){this.deps.log(`info`,`visibility stopped forgot=${this.servers.size}`),this.loop={kind:`idle`},this.servers.clear()}shown(e){if(e==null)return!0;let t=this.servers.get(e.socket);return t?.kind!==`asked`||t.shown.has(e.pane)}async refresh(e){for(let t of this.servers.keys())e.has(t)||this.servers.delete(t);let t=await Promise.all([...e].map(async e=>{let[t,n]=await Promise.all([this.deps.listPanes(e),this.deps.listClients(e)]);return[e,t.kind===`ok`?n.kind===`ok`?{kind:`asked`,shown:J4(t.stdout,q4(n.stdout)),status:Y4(t.stdout,n.stdout)}:{kind:`unasked`,reason:n.reason}:{kind:`unasked`,reason:t.reason}]})),n=new Set;for(let[e,r]of t){let t=this.servers.get(e);this.servers.set(e,r),!Z4(t,r)&&(n.add(e),this.deps.log(r.kind===`asked`?`info`:`warn`,r.kind===`asked`?`visibility socket=${JSON.stringify(e)} shown=${[...r.shown].join(`,`)||`-`}`:`visibility socket=${JSON.stringify(e)} unasked: ${r.reason} — its panes count as shown`))}for(let[e,n]of t)n.kind===`asked`&&this.deps.onAnswer(e,n.status);n.size>0&&this.deps.onChange(n)}};function Z4(e,t){return e===void 0||e.kind!==t.kind?!1:e.kind===`unasked`||t.kind===`unasked`?!0:e.shown.size===t.shown.size&&[...e.shown].every(e=>t.shown.has(e))}const Q4=`@cc-candybar-status-prior`,$4=`@cc-candybar-status-wrote`,e3=`@cc-candybar-binding-prior`,t3=[`-T`,`root`,`MouseDown1Status`],n3=Array.from({length:5},(e,t)=>t),r3=e=>`@cc-candybar-row-${e}`,i3=e=>`#[fill=terminal]#{${r3(e)}}`,a3=e=>`status-format[${e}]`;function o3(e){return e===0?`off`:e===1?`on`:String(e)}function s3(e){let t=e===`off`?0:e===`on`?1:/^[2-5]$/.test(e)?+e:NaN;if(Number.isNaN(t))throw Error(`tmux status is ${JSON.stringify(e)}`);return t}function c3(e,t){if(e===null)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>e[Number(n)]===t[Number(n)])}function l3(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function u3(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function d3(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function f3(e){return e.map(e=>e.map(d3).join(` `)).join(` ; `)}const p3=`ccb:separator`;function m3(e){return u3(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,p3],e]))}function h3(e,t){let n=e.split(`${p3}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const g3=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],_3=e=>[`show-options`,`-g`,`-q`,`-v`,e],v3=e=>[[`show-options`,`-t`,e],g3(e,`status`),...n3.map(t=>g3(e,a3(t)))];function y3(e){let[t=``,n=``,...r]=e,i=t.split(`
493
+ `).map(e=>e.split(` `)[0]??``),a={};for(let e of n3)i.includes(a3(e))&&(a[e]=r[e]??``);let o=i.includes(`status-format`)||Object.keys(a).length>0;return{status:i.includes(`status`)?n:null,formats:o?a:null}}function b3(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,a3(Number(t)),l3(n)])]}const x3=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...v3(e),...n3.map(e=>_3(a3(e))),g3(e,Q4),g3(e,$4)];function S3(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:s3(t)}catch(e){return{kind:`theirs`,why:`${Q4} does not read (${String(e)})`}}return r.owner===n?{kind:`ours`,prior:r,status:i}:{kind:`theirs`,why:`the daemon at ${JSON.stringify(r.owner)} draws it`}}function C3(e,t,n){let[r=``,...i]=t,a=y3(i.slice(0,7)),o=i.slice(7,12),[s=``,c=``]=i.slice(12);if(s!==``)return S3(s,c,n);let l=s3(r),u={};for(let e=0;e<l;e++){let t=a.formats===null?o[e]:a.formats[e];t!==void 0&&t!==``&&(u[e]=t)}let d={...u,...Object.fromEntries(Array.from({length:5-l},(e,t)=>[l+t,i3(t)]))},f={owner:n,base:l,status:a.status,formats:a.formats,wrote:d};return{kind:`lay-out`,prior:f,commands:[[`set-option`,`-t`,e,Q4,JSON.stringify(f)],...b3(e,d)]}}const w3=e=>[...v3(e),g3(e,$4)];function T3(e,t,n){let r=y3(n.slice(0,7)),i=n[7]??``,a=[],o=[];if(c3(r.formats,t.wrote))a.push(...b3(e,t.formats));else{o.push(`status-format`);for(let[n,i]of Object.entries(r.formats??{}))Number(n)>=t.base&&i===t.wrote[Number(n)]&&a.push([`set-option`,`-u`,`-t`,e,a3(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,l3(t.status)]):o.push(`status`)),a.push(...n3.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,r3(t)]),[`set-option`,`-q`,`-u`,`-t`,e,Q4],[`set-option`,`-q`,`-u`,`-t`,e,$4]),{commands:a,kept:o}}const E3=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,D3=[[`list-keys`,`-T`,`root`]];function O3(e){let t=E3.exec(e);return t===null?null:{line:t[0],command:t[1]}}const k3=`cc-candybar://tmux-status-click/`,A3=e=>`${k3}${ui([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,j3=e=>e?.command.includes(k3)??!1;function M3(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,e3]};return j3(O3(t))?{steps:[e===null?{command:[`unbind-key`,...t3]}:{command:[`source-file`,`-`],stdin:`${e.line}\n`},n],said:`restored MouseDown1Status to ${e===null?`unbound`:JSON.stringify(e.line)}`}:{steps:[n],said:`left MouseDown1Status as it is: bound again since`}}var N3=class{held=new Map;servers=new Map;closed=!1;writes=0;failedWrites=0;constructor(e){this.deps=e}observe(e,t,n){if(this.closed)return;let r=this.held.get(e),i=n&&t!=null?t:null;if(r!==void 0&&(i===null||r.socket!==i.socket||r.pane!==i.pane)&&this.release(r,`switched off or moved`),i===null||this.held.has(e))return;let a={sessionId:e,socket:i.socket,pane:i.pane,unsubscribe:null,frame:null};this.held.set(e,a),this.serverOf(i.socket),this.deps.log(`info`,`tmux-status: holding sid=${JSON.stringify(e)} pane=${i.pane} socket=${JSON.stringify(i.socket)}`),a.unsubscribe=this.deps.subscribe(e,{lane:`tmuxStatus`,frame:e=>{a.frame=fW(e),this.reconcile(a.socket)},refused:t=>{this.held.get(e)===a&&this.release(a,`refused: ${t.error}`)},drawing:()=>this.draws(a)})}answered(e,t){if(this.closed)return;let n=this.serverOf(e);n.view=t;for(let n of[...this.held.values()])if(n.socket===e)if(!t.sessionOf.has(n.pane))this.release(n,`pane gone`);else{let t=this.deps.sessionInPane(e,n.pane);t!==null&&t!==n.sessionId&&this.release(n,`pane taken by sid=${JSON.stringify(t)}`)}this.reconcile(e)}draws(e){let t=this.servers.get(e.socket),n=t?.view?.sessionOf.get(e.pane);return n!==void 0&&t.layouts.has(n)&&t.view.shownBy.get(n)===e.pane}restoreAll(){this.closed=!0;for(let e of this.held.values())e.unsubscribe?.();this.held.clear();for(let[e,t]of this.servers){for(let[n,r]of[...t.layouts]){t.layouts.delete(n);let i=this.askSync(e,w3(n));if(i===null)continue;let a=T3(n,r.prior,i);this.writeSync(e,a.commands),this.saidRestored(e,n,a.kept)}let n=t.binding;if(t.binding={kind:`none`},n.kind===`ours`||n.kind===`adopted`){let t=this.askSync(e,D3);if(t===null)continue;this.writeBindingRestoreSync(e,n.prior,t[0]??``)}}}linkAt(e){let t=P3(e),[n,r,i,...a]=t??[];if(t===null||n===void 0||r===void 0||i===void 0||a.length>0)return{kind:`refused`,reason:`tmux-status-click needs <socket>/<pane>/<range>, got ${JSON.stringify(e)}`};let o=[...this.held.values()].find(e=>e.socket===n&&e.pane===`%${r}`)?.frame?.links[i];return o===void 0?{kind:`refused`,reason:`pane %${r}'s status line draws no link ${i} now`}:{kind:`link`,url:o}}stats(){return{sessions:this.held.size,layouts:[...this.servers.values()].reduce((e,t)=>e+t.layouts.size,0),writes:this.writes,failedWrites:this.failedWrites}}async settled(){for(let e of this.servers.values())await e.running}serverOf(e){let t=this.servers.get(e);if(t!==void 0)return t;let n={view:null,adopted:!1,layouts:new Map,left:new Map,binding:{kind:`none`},running:null,again:!1,lastFailure:null};return this.servers.set(e,n),n}release(e,t){e.unsubscribe?.(),this.held.delete(e.sessionId),this.deps.log(`info`,`tmux-status: released sid=${JSON.stringify(e.sessionId)} pane=${e.pane} — ${t}`),this.reconcile(e.socket)}reconcile(e){let t=this.servers.get(e);if(!(t===void 0||this.closed)){if(t.running!==null){t.again=!0;return}t.running=(async()=>{try{do t.again=!1,await this.step(e,t);while(t.again&&!this.closed)}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} reconcile threw: ${String(t)}`)}finally{t.running=null}})()}}async step(e,t){let n=t.view;if(n===null)return;t.adopted||(t.adopted=!0,await this.adopt(e,t));let r=new Map;for(let t of this.held.values()){if(t.socket!==e)continue;let i=n.sessionOf.get(t.pane);i!==void 0&&r.set(i,[...r.get(i)??[],t])}for(let i of new Set([...t.layouts.keys(),...t.left.keys(),...r.keys()])){if(this.closed)return;let a=r.get(i)??[],o=t.layouts.get(i);if(a.length===0){t.left.delete(i),o!==void 0&&await this.restore(e,t,i);continue}if(t.left.has(i))continue;let s=o??await this.install(e,t,i);if(s===null)continue;let c=a.find(e=>e.pane===n.shownBy.get(i))?.frame?.rows.slice(0,5-s.prior.base)??[];await this.draw(e,i,s,c)}this.closed||(t.layouts.size>0?await this.installBinding(e,t):await this.restoreBinding(e,t))}async adopt(e,t){let n=await this.run(e,[`list-sessions`,`-F`,`#{session_id}\t#{${Q4}}\t#{${$4}}`]);if(n.kind===`ok`)for(let r of n.stdout.split(`
494
+ `)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=S3(i,a,this.deps.owner);o.kind===`ours`?t.layouts.set(n,{prior:o.prior,rows:[],status:o.status}):this.leave(e,t,n,o.why)}let r=(await this.ask(e,[_3(`@cc-candybar-binding-prior`)]))?.[0]??``;if(r!==``)try{let e=JSON.parse(r);e.owner===this.deps.owner&&(t.binding={kind:`adopted`,prior:e.prior})}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${e3} does not read (${String(t)}), left as it is`)}(t.layouts.size>0||t.binding.kind===`adopted`)&&this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)||`-`} binding=${t.binding.kind}`)}leave(e,t,n,r){t.left.set(n,r),this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} session ${n} left as it is: ${r}`)}async install(e,t,n){let r=await this.ask(e,x3(n));if(r===null||this.closed)return null;let i=C3(n,r,this.deps.owner);if(i.kind===`theirs`)return this.leave(e,t,n,i.why),null;let a={prior:i.prior,rows:[],status:i.kind===`ours`?i.status:i.prior.base};return t.layouts.set(n,a),i.kind===`lay-out`&&await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} session ${n} base=${i.prior.base} own=${[i.prior.status===null?[]:[`status`],i.prior.formats===null?[]:[`status-format`]].flat().join(`,`)||`-`}`),a}async draw(e,t,n,r){let i=n.prior.base+r.length,a=[];if(r.forEach((e,r)=>{n.rows[r]!==e&&a.push([`set-option`,`-t`,t,r3(r),e])}),i!==n.status){let e=o3(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,$4,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,f3(a)]]))&&(n.rows=r,n.status=i)}async restore(e,t,n){let r=t.layouts.get(n);if(r===void 0)return;t.layouts.delete(n);let i=await this.ask(e,w3(n));if(i===null)return;let a=T3(n,r.prior,i);await this.write(e,a.commands),this.saidRestored(e,n,a.kept)}saidRestored(e,t,n){this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} restored session ${t} kept=${n.join(`,`)||`-`}`)}async installBinding(e,t){let n=t.binding;if(n.kind===`ours`||n.kind===`left`)return;let r=await this.ask(e,D3);if(r===null||this.closed)return;let i=O3(r[0]??``);if(n.kind===`none`&&j3(i)){t.binding={kind:`left`,why:`another cc-candybar daemon's status-line clicks are bound to MouseDown1Status; left as it is, so this daemon's are off`},this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.binding.why}`);return}let a=n.kind===`adopted`&&j3(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...t3,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${d3(`${this.deps.handler} ${A3(e)}`)}`,...a===null?[]:[a.command]],[`set-option`,`-g`,`@cc-candybar-binding-prior`,JSON.stringify(o)]])){t.binding=n;return}this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} bound MouseDown1Status (was ${a===null?`unbound`:JSON.stringify(a.line)})`)}async restoreBinding(e,t){let n=t.binding;if(t.binding={kind:`none`},n.kind!==`ours`&&n.kind!==`adopted`)return;let r=await this.ask(e,D3);if(r===null)return;let i=M3(n.prior,r[0]??``);for(let t of i.steps)await this.write(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.said}`)}writeBindingRestoreSync(e,t,n){let r=M3(t,n);for(let t of r.steps)this.writeSync(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r.said}`)}counted(e,t){let n=this.serverOf(e);return t.kind===`ok`?(n.lastFailure=null,t):(this.failedWrites++,n.lastFailure!==t.reason&&this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.reason}`),n.lastFailure=t.reason,t)}async run(e,t,n){return this.counted(e,await this.deps.edge.run(e,t,n))}async ask(e,t){let n=await this.run(e,m3(t));return n.kind===`ok`?h3(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,m3(t)));return n.kind===`ok`?h3(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,u3(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,u3(t),n)))}};function P3(e){try{return di(e)}catch(e){if(e instanceof URIError)return null;throw e}}const F3=`CC_CANDYBAR_CONFIG`;function I3(e,t){return XB(t,e[F3])}const $=e=>({arity:e,keep:!0}),L3=e=>({arity:e,keep:!1}),R3={"--add-dir":$(`variadic`),"--agent":$(`one`),"--agents":$(`one`),"--allow-dangerously-skip-permissions":$(`none`),"--allowedTools":$(`variadic`),"--allowed-tools":$(`variadic`),"--append-system-prompt":$(`one`),"--autocompact":$(`one`),"--ax-screen-reader":$(`none`),"--bg":L3(`none`),"--background":L3(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":L3(`optional`),"-c":L3(`none`),"--continue":L3(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":L3(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":L3(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":L3(`none`),"--forward-subagent-text":$(`none`),"--from-pr":L3(`optional`),"-h":L3(`none`),"--help":L3(`none`),"--ide":$(`none`),"--include-hook-events":$(`none`),"--include-partial-messages":$(`none`),"--input-format":$(`one`),"--json-schema":$(`one`),"--max-budget-usd":$(`one`),"--mcp-config":$(`variadic`),"--model":$(`one`),"-n":$(`one`),"--name":$(`one`),"--no-chrome":$(`none`),"--no-session-persistence":$(`none`),"--output-format":$(`one`),"--permission-mode":$(`one`),"--permission-prompts":$(`one`),"--plugin-dir":$(`one`),"--plugin-url":$(`one`),"-p":L3(`none`),"--print":L3(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":L3(`optional`),"--resume":L3(`optional`),"--safe-mode":$(`none`),"--session-id":L3(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":L3(`optional`),"--tmux":L3(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":L3(`none`),"--version":L3(`none`),"-w":L3(`optional`),"--worktree":L3(`optional`)},z3={resume:`--resume`,fresh:`--session-id`};function B3(e){return[z3[e.kind],e.sessionId]}const V3=e=>e.startsWith(`-`)&&e!==`-`;function H3(e,t){let n=G3(t);return n===null?{dir:e??t,args:[]}:e!==null&&U3(e,n.top)?{dir:e,args:[]}:{dir:e===null||G3(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const U3=(e,t)=>e===t||e.startsWith(t+s.sep);function W3(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!V3(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=R3[a];if(o===void 0)return{kind:`refused`,reason:`Claude Code was started with ${a}, which cc-candybar does not know how to carry to a restart`};let s=i===-1?o.arity===`one`?n.slice(r,r+1):o.arity===`optional`?n.slice(r,r+1).filter(e=>!V3(e)):o.arity===`variadic`?K3(n.slice(r),e=>!V3(e)):[]:[];if(o.arity===`one`&&i===-1&&s.length===0)return{kind:`refused`,reason:`Claude Code was started with ${a} and no value after it`};r+=s.length,o.keep&&t.push(e,...s)}return{kind:`args`,args:t}}function G3(e){let t=e.split(s.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(s.sep),repo:t.slice(0,n-1).join(s.sep)||s.sep}}function K3(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const q3=`candybar-band@cc-candybar`,J3=s.join(`bin`,`cc-candybar-native`),Y3=`@cc-candybar-bar-pane`,X3=lP(`/reload-plugins`),Z3=e=>({kind:`done`,said:e});function Q3(e){let t=Y0(e.hints.tmux);if(t.kind===`refused`)throw new q(t.reason);return t.hint}const $3={band:{on:(e,t,n)=>{let r=Qe(t.bundle);if(r===null)throw new q(`${Pv.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=s.join(r,J3);if(!n.fileExists(i))throw new q(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${q3} from ${r}`,finished:e6(e,r,n)}},off:()=>Z3(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=Q3(e),i=Re(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new q(`${Pv.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return{kind:`underway`,said:`restarting Claude Code in ${r.pane} under the attach launcher`,finished:r6(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>Z3(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=Q3(e),i=n.barPanes(r);return i.length>0?Z3(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):Z3(`opened bar pane ${n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:(e,t,n)=>{let r=Y0(e.hints.tmux);if(r.kind===`refused`)return Z3(`no bar pane to close: ${r.reason}`);let i=r.hint,a=n.barPanes(i);for(let e of a)n.closePane(i,e);return Z3(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>Z3(`the daemon draws ${Q3(e).pane}'s bar in its status line`),off:()=>Z3(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function e6(e,t,n){let r={sessionId:e.sessionId,projectDir:e.origin.projectDir,claudeConfigDir:e.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,q3],r);let i=X0(n.claudeInput,e.hints.tmux,X3);if(i.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${i.reason} — or type /reload-plugins yourself`);return`installed ${q3} from ${t} and typed /reload-plugins into ${i.pane}`}const t6=new Set([qa,F3]);function n6(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function r6(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,ze(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${Pv.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);if((await r.paneClaude(t)).pid!==i.pid)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}), so it was not restarted under the attach launcher`);let o=c6(r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${Pv.statusline.label} off and on again`);let s=i6(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=W3(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=n6(i.env),u=l.get(`PATH`),d=r.launcherNode(u);if(d.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${d.why}`);let f=r.onPath(`claude`,u)===i.executable?`claude`:i.executable,p=[...l].filter(([e])=>t6.has(e)),m=(e,t)=>He(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...B3(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${15e3/1e3} s of SIGTERM, so it was not restarted under the attach launcher`);let h=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),g=a6(e,r.presence(e.transcript)),_=g.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:g,v;try{v=await r.paneDir(t,i.parent)}catch(e){throw h(`the directory it was started in could not be read (${e.message})`,m(H3(null,i.cwd),_))}let y=m(H3(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{r.typeShellLine(t,y)}catch(e){throw h(`the line could not be typed into its pane (${e.message})`,y)}if(!await r.followed(e.sessionId,`statusline`,3e4))throw Error(`Claude Code in ${t.pane} did not come back attached within ${3e4/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${o6[g.kind](e.sessionId)}, and its statusline follows lane B`}function i6(e,t){return typeof t==`object`?`whether session ${e.sessionId} has a conversation could not be seen (${t.error})`:t===`present`||e.answered===`no`?null:e.answered===`yes`?`session ${e.sessionId} has a conversation but no transcript to resume it from (is session persistence off?), so a restart would lose it`:`this Claude Code does not say whether session ${e.sessionId} has a conversation, and it has no transcript to resume one from`}function a6(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const o6={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},s6={"in-mode":`its pane is in tmux copy mode — leave it (q)`,stashed:`it holds a stashed prompt (ctrl+s), which ending it would lose — restore or send it`,"no-prompt":`it is not at its prompt (a dialog or picker is open) — close it`};function c6(e){let t=W0(e);return t.kind===`ready`?q0(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:G0(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:s6[t.kind]}var l6=class{owed=new Map;queued=new Map;constructor(e){this.deps=e}clicked(e,t,n,r){let i=Fv.filter(e=>n[e]!==r[e]),a=this.take(e);for(let e of i)a.has(e)||a.set(e,n[e]);let o=e=>i.includes(e)?`click`:`owed`;if(t!==null){this.settle(t,a,r,o);return}for(let[e,t]of a)t===r[e]&&a.delete(e);if(i.length>0){let t=[...a.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}a.size>0&&this.owed.set(e,a);for(let[e,t]of this.owed){if(this.owed.size<=1024)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t){this.settle(e,this.take(e.sessionId),t,()=>`owed`)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r){for(let[i,a]of t)n[i]===a?this.deps.log(`info`,`lane: ${i} ${a?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(i)} (session=${e.sessionId})`):this.start(e,i,n[i],r(i))}start(e,t,n,r){this.deps.defer(()=>this.enqueue(e.sessionId,()=>this.sync(e,t,n,r)))}enqueue(e,t){let n=this.queued.get(e);if(n!==void 0){n.push(t);return}let r=[];this.queued.set(e,r);let i=t=>void t().then(()=>{let t=r.shift();t===void 0?this.queued.delete(e):i(t)});i(t)}sync(e,t,n,r){let i=`by=${r} (session=${e.sessionId})`,a=r=>{let a=`lane: ${t} ${n?`on`:`off`}: ${r instanceof Error?r.message:String(r)}`;this.deps.log(`warn`,`${a} ${i}`),$o(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=$3[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){return a(e),Promise.resolve()}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`underway`?o.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${i}`),a):Promise.resolve()}};function u6(e,t,n){for(let r of(t??``).split(s.delimiter)){if(!s.isAbsolute(r))continue;let t=s.join(r,e);if(n(t))return t}return null}function d6(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function f6(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function p6(e,t,n){let r=u6(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const m6=2e3;function h6(e,t,n){let r=FK(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function g6(e,t){if(t.ok)return t.stdout;let n=t.error??[t.reason,t.stderr.trim(),t.stdout.trim()].filter(e=>e!==``).join(`: `);throw Error(`${e} failed (${n})`)}function _6(e){try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`ok`in t&&t.ok===!1&&`reason`in t&&typeof t.reason==`string`)return`detail`in t&&typeof t.detail==`string`?`${t.reason}: ${t.detail}`:t.reason}catch{}return null}const v6=`#{pane_id} #{${Y3}}`;function y6(e,t){return e.split(`
495
+ `).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const b6=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function x6(e,t,n){for(let r of H$(V$(e),t)){if(r.command.split(` `).some(e=>b6.test(e)))return!0;if(r.pid===n)return!1}return!1}const S6=[`import ctypes, json, struct, sys`,`libc = ctypes.CDLL(None)`,`mib = (ctypes.c_int * 3)(1, 49, int(sys.argv[1]))`,`size = ctypes.c_size_t(0)`,`if libc.sysctl(mib, 3, None, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`buf = ctypes.create_string_buffer(size.value)`,`if libc.sysctl(mib, 3, buf, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`raw = buf.raw[:size.value]`,`argc = struct.unpack_from('i', raw)[0]`,`rest = raw[4:]`,`end = rest.index(b'\\0')`,`exe = rest[:end].decode('utf-8', 'surrogateescape')`,`rest = rest[end:].lstrip(b'\\0')`,`words = [w.decode('utf-8', 'surrogateescape') for w in rest.split(b'\\0')]`,`end = words.index('', argc) if '' in words[argc:] else len(words)`,`print(json.dumps({'executable': exe, 'argv': words[:argc], 'env': words[argc:end]}))`].join(`
496
+ `);async function C6(e){if(process.platform===`linux`)return{executable:await p.promises.readlink(`/proc/${e}/exe`),argv:(await p.promises.readFile(`/proc/${e}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await p.promises.readFile(`/proc/${e}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let t=g6(`reading process ${e}'s arguments`,await pt({bin:`python3`,args:[`-c`,S6,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function w6(e,t){return g6(e,await pt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function T6(e){let t=await IK(e,`lane.tmux`,[`display`,`-p`,`-t`,e.pane,`#{pane_pid} #{pane_current_path}`]);if(t.kind!==`ok`)throw Error(t.reason);let[n=``,r=``]=t.stdout.trimEnd().split(` `),i=(await w6(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function E6(e){let{panePid:t,cwd:n,foreground:r}=await T6(e),i=await w6(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await C6(r),o=V$(i).get(r)?.ppid;if(o===void 0)throw Error(`pane ${e.pane}'s foreground job ${r} is gone`);return{pid:r,executable:await p.promises.realpath(a.executable),argv:a.argv,env:a.env,cwd:n,parent:o,fromShell:r!==t,attached:x6(i,r,t)}}function D6(e){return{claudeInput:t2(),barPanes:e=>y6(h6(e,[`list-panes`,`-a`,`-F`,v6]),e.pane),openBarPane:(e,t,n)=>{let r=h6(e,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,e.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(n).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...t]).trim();return h6(e,[`set-option`,`-p`,`-t`,r,Y3,e.pane]),r},closePane:(e,t)=>void h6(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void g6(`claude ${e.join(` `)}`,await pt({bin:`claude`,args:[...e],env:D$(process.env,t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:HV,paneClaude:E6,paneDir:async(e,t)=>{let n=Date.now()+m6;for(;;){let r=await T6(e);if(r.foreground===t){if(r.cwd===``)throw Error(`tmux read no directory for pane ${e.pane}`);return r.cwd}if(Date.now()>n)throw Error(`the shell in pane ${e.pane} (pid ${t}) did not take its terminal back within ${m6/1e3} s`);await be(100)}},launcherNode:e=>p6(e,e=>d6(e,p.constants.X_OK),f6),onPath:(e,t)=>{let n=u6(e,t,e=>d6(e,p.constants.X_OK));return n===null?null:p.realpathSync(n)},followed:async(t,n,r)=>{let i=Date.now()+r;for(;!e(t).has(n);){if(Date.now()>i)return!1;await be(200)}return!0},moduleGraph:async(e,t,n)=>{let r=await pt({bin:e,args:[t,n],timeoutMs:2e4,category:`lane.process`}),i=!r.ok&&r.reason===`non-zero`?_6(r.stdout):null;return i===null?(g6(`reading ${n}'s module graph`,r),{ok:!0}):{ok:!1,reason:i}},terminate:e=>{try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=Date.now()+t;for(;ws(e);){if(Date.now()>n)return!1;await be(100)}return!0},typeShellLine:(e,t)=>void h6(e,$0(e.pane,`cc-candybar-lane`,[]),t)}}function O6(e,t){return Fv.filter(n=>e[n]&&Pv[n].elsewhere!==null&&t.has(n))}function k6(e,t){let n=`the bar is drawn in ${t.map(e=>Pv[e].elsewhere).join(` and `)}`,r=pi([{verb:Qr,args:[e,...t.map(e=>Pv[e].setting)]}]);return{channels:[{severity:vb,message:n,lines:[[yb(n,pi([{verb:Br,args:[n]}])),yb(`[⟲ draw it here]`,r)]]}]}}const A6={order:-1/0,text:null,failure:null};var j6=class{synced=new Map;constructor(e,t){this.dir=e,this.changed=t}pathFor(e){return s.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t,n){let r=this.synced.get(e)??A6;if(t<r.order)return{link:this.linkFor(e,n),failure:null};let i=n===r.text&&r.failure===null?null:this.write(e,n);return this.synced.delete(e),this.synced.set(e,{order:t,text:n,failure:i}),this.forgetOldestClean(),(n!==r.text||i!==r.failure)&&this.changed(e),{link:this.linkFor(e,n),failure:i}}linkFor(e,t){let n=this.synced.get(e)??A6;return n.text===t?n.failure===null?{kind:`file`,path:this.pathFor(e)}:{kind:`unavailable`,reason:n.failure}:{kind:`unavailable`,reason:`the file holds another render's text until the session's next statusline request`}}forgetOldestClean(){let e=0;for(let t of this.synced.values())t.text===null&&t.failure===null&&e++;for(let[t,n]of this.synced){if(e<=256)return;n.text!==null||n.failure!==null||(this.synced.delete(t),e--)}}write(e,t){let n=this.pathFor(e);try{return t===null?p.rmSync(n,{force:!0}):(p.mkdirSync(this.dir,{recursive:!0,mode:448}),p.writeFileSync(n,t,{mode:384})),null}catch(e){return`${n}: ${e.message}`}}reset(){this.synced.clear();try{return p.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}},M6=class{sessions=new Map;constructor(e){this.deps=e}clicked(e,t){this.record(e,t).since=t,this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;return{sessions:this.sessions.size,armed:e}}dispose(){for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=256)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown?qv(t.since,t.timeoutS):null;if(t.timer?.at===n||(this.disarm(t),n===null))return;let r=setTimeout(()=>this.fire(e),Math.max(0,(n-this.deps.now())*1e3));r.unref(),t.timer={at:n,handle:r}}disarm(e){e.timer!==null&&clearTimeout(e.timer.handle),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now(),r={idleS:n-t.since,timeoutS:t.timeoutS};t.since=n,t.shown=!1;try{this.deps.close(e,r)}catch(t){this.deps.failed(e,t)}}};function N6(e){return e===void 0?{kind:`unstated`}:typeof e==`number`&&Number.isSafeInteger(e)&&e>0?{kind:`stated`,at:e}:{kind:`refused`,problem:`request 'deadline' is not epoch milliseconds: ${JSON.stringify(e)}`}}function P6(e,t,n){let r=e.kind===`stated`?n.monoMs+(e.at-n.epochMs):t+150-50,i=Math.min(r,t+200);return Math.round(i-40-n.monoMs)}function F6(e,t){for(let n of Object.entries(t))e.push(n)}const I6={ok:`info`,"bad-request":`warn`,threw:`error`};function L6(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,T(e.error)]]}}function R6(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...L6(n)];return{level:I6[n.kind],line:`${e}${i.map(([e,t])=>` ${e}=${as(t)}`).join(``)}`}}const z6=new IZ,B6=new A0,V6=new SM,H6=i(import.meta.url),U6=B1(yt());dt(z6.launchStats);const W6=new $W({counters:z6,logger:M}),G6=new Mk(M),K6=sq({watchers:W6,logger:M,ledger:G6}),{gitProvider:q6,usageStore:J6,tmuxService:Y6,hostService:X6,managedStorage:Z6}=K6,Q6=new zZ,$6=new JQ(Q6,M),e8=new _$,t8=new eb,n8=new M6({now:()=>ak(new Date),close:(e,t)=>m4(e,t,U8),failed:(e,t)=>M(`error`,`menu-idle: close failed (session=${e}): ${T(t)}`)}),r8=Yo(),i8=new ls({supersede:(e,t)=>Z6.supersede(e,t),launch:pt,state:Q6,log:M,now:()=>ak(new Date)}),a8=[t.execPath,...t.execArgv],o8=new l6({edge:D6(e=>c8.following(e)),host:{bundle:H6,node:a8,socket:St(),preload:Do(H6)},state:Q6,log:M,now:()=>ak(new Date),defer:e=>void _e(e)}),s8=new N3({edge:{run:(e,t,n)=>IK({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>FK({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>c8.subscribe(e,t),sessionInPane:(e,t)=>c8.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${Fe(St())}`,...[...a8,H6].map(Fe),`url-handle`].join(` `),owner:St(),log:M}),c8=new U4({render:(e,t)=>Q8(e,t),watch:(e,t)=>(0,J.reaction)(()=>Q6.revision(e),t),lanes:e=>e5(e),pin:e=>f8.pin(e),shown:e=>l8.shown(e.hints.tmux),watching:()=>l8.follow(),refreshes:()=>G6.totals(),periods:I4,now:()=>performance.now(),log:M}),l8=new X4({listPanes:e=>IK({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,G4]),listClients:e=>IK({socket:e},`frames.visibility`,[`list-clients`,`-F`,K4]),sockets:()=>new Set(c8.watched().flatMap(({req:e})=>u8(e))),onAnswer:(e,t)=>s8.answered(e,t),onChange:e=>c8.wakeWhere(`visibility`,t=>u8(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function u8({hints:{tmux:e}}){return e==null?[]:[e.socket]}const d8=new j6(Pt(),e=>c8.wake(e,`data`)),f8=new PZ({sessionState:Q6,watchers:W6,log:M,storage:Z6,signer:r8,ledger:G6,declare:(e,t,n,r)=>Iq(K6,e,t,n,r),source:F4({providers:K6,sessionState:Q6,history:e=>$6.depth(e),navigation:(e,t)=>e8.depth(e,Q6,yU(t))})},{budgetBytes:()=>(E8(),yZ(v8)),observers:{onReload:(e,t)=>{M(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`);for(let e of t)c8.wake(e,`reload`)},onViewChanged:e=>c8.wake(e,`data`)}}),p8=60*1e3,m8=WU({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:p8,stat:p.statSync,exit:()=>j8(0),log:M}),h8=VU({entryUrl:import.meta.url,intervalMs:p8,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>m8.checkNow(),log:M});let g8=null,_8=null,v8=0;function y8(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),j8(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),j8(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),j8(0)});try{D8(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),j8(1);return}g8=bs(t.pid);let e=As(Ms(g8));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),j8(1);return}_8=e.registryPath,p.mkdirSync(xt(),{recursive:!0}),Tt(St()),Q6.useStorage(new VZ(Ot(),500,M)),$6.useStorage(h$(kt(),M)),Cs({anchor:Ss(t.env),isAlive:ws,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),j8(0)}}),x8(ue.createServer({allowHalfOpen:!1},e=>{M8(e)}),St(),!1)}function b8(){let e=q6.getStats(),t=Y6.getStats(),n=J6.scanStats(),r=Z6.stats(),i=f8.stats;return{records:G6.snapshot(),homes:{daemon:1,configDir:n.entries,repo:e.size,directory:i.size,session:J6.getStats().size,view:i.views,pane:t.entries},held:{git:e.held,tmux:t.held,host:X6.held(),today:n.held,pluginStorage:r.held},pluginStorage:{folders:r.folders,faults:r.faults,lost:r.lost}}}function x8(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),j8(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}S8(e,n)}),e.listen(n,()=>C8(n))}function S8(e,n){let r=us(ds(Et(n)),(e,t)=>ys(e,t,{readStartTime:vs,pidAlive:ws}));if(r.kind===`attach-and-exit`){M(`info`,`EADDRINUSE: ${r.reason} — exiting`),t.exit(0);return}M(`warn`,`EADDRINUSE: ${r.reason} — unlinking stale socket and rebinding`);try{p.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){M(`error`,`cannot unlink stale socket ${n}: ${e.message}`),j8(1);return}}x8(e,n,!0)}function C8(e){let n=ms(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),j8(0);return}O8(e);try{p.chmodSync(e,384)}catch(e){M(`warn`,`chmod socket failed: ${e.message}`)}M(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${tr(de.getHeapStatistics().heap_size_limit)}MB memoryLimit=${tr(v8)}MB`),Tr();let r=d8.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),m8.arm(),h8.arm(),E8().arm(),w8(e,n.identity)}function w8(e,n){_s({bound:n,myPid:t.pid,readIdentity:()=>ms(e),readLease:()=>ds(Et(e)),shutdown:e=>j8(e),log:M}).arm()}let T8=null;function E8(){if(T8===null)throw Error(`daemon: limits not yet established`);return T8}function D8(e){v8=nr(e),T8=ur(gr(z6.startedAt.getTime(),e=>j8(e),{limitBytes:v8}))}function O8(e){let n=fs(Et(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:g8});n!==null&&M(`warn`,`lease write failed: ${n}`)}let k8=0,A8=!1;function j8(e){if(A8)return;A8=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);let n=[[`tmuxStatusLines restore`,()=>s8.restoreAll()],[`gitService close`,()=>q6.close()],[`usageStore close`,()=>J6.close()],[`tmuxService close`,()=>Y6.close()],[`hostService close`,()=>X6.close()],[`runs close`,()=>i8.close()],[`managedStorage close`,()=>Z6.close()],[`watcherRegistry close`,()=>W6.closeAll()],[`sessionState flush`,()=>Q6.flush()]];for(let[e,t]of n)try{t()}catch(t){M(`warn`,`${e} failed: ${t.message}`)}ps(Dt(),t.pid),_8!==null&&js(_8,t.pid,Os,e=>p.unlinkSync(e)),t.exit(e)}function M8(e){let t=performance.now();k8++,z6.inFlight=k8;let n=!1,r=!0,i=()=>{r&&(r=!1,k8=Math.max(0,k8-1),z6.inFlight=k8)},a=(t,r,i)=>{if(n){r!==null&&M(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}n=!0;let a=r===null?void 0:()=>j8(r);try{e.end(Qt(t),e=>{e??i(),a?.()})}catch(e){M(`warn`,`response write failed: ${e.message}`),a?.()}},o=!1,s=setTimeout(()=>{o=!0,z6.requestsTimedOut++,a({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,N8)},200),c=en(e=>{B8(e,()=>o,t).then(e=>e.kind===`reply`?a(e.resp,e.exitAfterFlush,e.delivered):l(e.sessionId,e.lane)).catch(e=>{M(`error`,`handler threw: ${T(e)}`),a(L8(e),null,N8)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),a({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,N8)}),l=(t,r)=>{if(n||e.destroyed)return;clearTimeout(s),i(),e.off(`data`,c);let a=W4(e),o=c8.subscribe(t,{lane:r,frame:(e,t)=>a($t(pW[r](e,t))),refused:t=>e.end(Qt(t)),drawing:()=>!0});n=!0,e.on(`close`,o)};e.on(`data`,c),e.on(`error`,e=>{M(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(s),i()})}const N8=()=>{},P8=e=>({resp:e,exitAfterFlush:null,delivered:N8}),F8=e=>({kind:`reply`,...e}),I8={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},L8=e=>({ok:!1,error:e instanceof Error?e.message:T(e),code:`RENDER_FAILED`,daemonV:3}),R8=(e,t)=>F8(P8({ok:!1,error:t,code:e,daemonV:3}));function z8(e){let t=mW(e.sessionId);if(!t.ok)return R8(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return R8(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Fv.join(`, `)}): it predates the lane toggles — update it`);let n=Hv(e.lane);return n===null?R8(`BAD_REQUEST`,`subscribe needs a lane, one of ${Fv.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function B8(e,t,n){return!e||typeof e!=`object`||typeof e.v!=`number`?R8(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?z8(e):typeof e.kind!=`string`||!Object.hasOwn(I8,e.kind)?R8(`BAD_REQUEST`,`unknown kind`):F8(await V8(e,t,n)):(e.v>3?M(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):M(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null,delivered:N8})}async function V8(e,t,n){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:N8};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return P8(typeof t!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:c8.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return P8({ok:!0,stats:z6.snapshot({gitCache:q6.getStats(),usageCache:J6.getStats(),sources:b8(),runs:i8.stats(),transcriptReads:Ra(),renderCache:f8.stats,effectCache:t8.getStats(),menuIdle:n8.getStats(),sessionState:{sessions:Q6.size(),observers:Q6.observers(),revision:Q6.latestRevision()},frameFeeds:c8.getStats(),tmuxStatus:s8.stats(),watchersActive:W6.size(),nextRestartReason:E8().describeNextRestart(),handlerProbes:B6.list(),clients:V6.list(ak(new Date)),bundle:H6,daemon:E8().serving(),doctorStores:V1(U6)})});if(e.kind===`render`){let r=new Date,i=ak(r),a=performance.now(),o=Math.round(a-n),s=[],c=++z6.requestsTotal,l=n5(e),u=(e,t)=>V6.see(e.sessionId,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:Ya(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:vM(e.hookData),frame:t},i,c);l.ok&&(u(l.req,`drawing`),c8.note(l.req.sessionId,l.req,c));let d=l.ok?await f5(l.req,c,i,(e=>{let t=P6(e.deadline,n,{epochMs:r.getTime(),monoMs:a});return{stated:e.deadline.kind,ms:t,endsAt:a+t}})(l.req),s).then(({answer:e,motion:t,clickShown:n})=>(u(l.req,t),{outcome:{kind:`ok`},resp:{ok:!0,output:e},delivered:n===null?N8:()=>es(Q6,l.req.sessionId,n)}),e=>(u(l.req,`failed`),{outcome:{kind:`threw`,error:e},resp:L8(e),delivered:N8})):r5(l.problems);d.outcome.kind!==`ok`&&z6.requestsErrored++,F6(s,{timedOut:t()?`Y`:`N`,queued:`${o}ms`});let{level:f,line:p}=R6(`render`,s,d.outcome,Math.round(performance.now()-a));return M(f,p),{resp:d.resp,exitAfterFlush:null,delivered:d.delivered}}if(e.kind===`click`){let r=performance.now(),i=[[`queued`,`${Math.round(r-n)}ms`]],a=q8(e,i);F6(i,{timedOut:t()?`Y`:`N`});let{level:o,line:s}=R6(`click`,i,a,Math.round(performance.now()-r));return M(o,s),P8(X8(a))}if(e.kind===`debug`){if(!P4(e.what))return P8({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${N4.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=f8.latestView(),n=t===null?null:{store:t.store,registry:t.registry,config:t.state.config,compiled:t.state.compiled,lastRenderBySegment:e.what===`segments`?K8(t.lastRenderCellsBySegment,t.state.config.globals.colorCompatibility??vy(`colorCompatibility`)):G8};return P8({ok:!0,debug:S4(e.what,n)})}throw Error(`no reply for request ${T(e)}`)}function H8(e,t){let{tokens:n}=ce({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=(n??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),i=(n??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===r&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:XB(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const U8={sessionState:Q6,dlog:M,applyUpdate:()=>h8.act(),doctor:Z1(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];f8.reload(...t);let n=f8.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:U6,probes:B6,clients:V6,bundle:H6,serving:()=>E8().serving(),claudeInput:t2(),history:$6,navigation:e8,configFor:e=>f8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>f8.reload(e.projectDir,e.cwd,e.configFile??void 0),sourcesFor:e=>f8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.sources,links:r8,runs:i8,lanes:{of:t5,clicked:h5},views:{follow:(e,t)=>f8.follow(e,t.projectDir,t.cwd,t.configFile??void 0)}};U8.reloadConfig;const W8={endcaps:vy(`endcaps`),colorCompatibility:vy(`colorCompatibility`),wrap:vy(`autoWrap`),padding:vy(`padding`),width:1/0},G8=new Map;function K8(e,t){let n=new Map;for(let[r,i]of e)n.set(r,pb(i,{...W8,colorCompatibility:t}));return n}function q8(e,t){let{verb:n,value:r}=e;if(typeof n!=`string`||typeof r!=`string`)return{kind:`bad-request`,problems:[`a click's verb and value are strings, got ${typeof n} and ${typeof r}`]};try{return Y8(n,r,{via:`link`,handler:Zt(e.clientVersion)},t)}catch(e){return e instanceof q?{kind:`bad-request`,problems:[e.message]}:{kind:`threw`,error:e}}}const J8={link:`verb`,"tmux-status":`linkVerb`};function Y8(e,t,n,r){if(e===`tmux-status-click`)return F6(r,{verb:e}),Z8(t,r);let i=p4.get(e);if(!i)return{kind:`bad-request`,problems:[`unknown click verb: ${e}`]};F6(r,{[J8[n.via]]:e});let a=l4(e,t);return a===null?F6(r,{sid:`-`}):a.ok&&(F6(r,{sid:a.id}),n8.clicked(a.id,ak(new Date))),i(t,{...U8,arrival:n}),{kind:`ok`}}function X8(e){switch(e.kind){case`ok`:return{ok:!0,output:``};case`bad-request`:return{ok:!1,error:e.problems.join(`; `),code:`BAD_REQUEST`,daemonV:3};case`threw`:return L8(e.error)}}function Z8(e,n){let r=e=>({kind:`bad-request`,problems:[e]}),i=s8.linkAt(e);if(i.kind===`refused`)return r(i.reason);if(F6(n,{link:i.url}),i.url.startsWith(`cc-candybar://`)){let e=kb(()=>zo(i.url));return e.verb===`tmux-status-click`?r(`a status-line link names another status-line click`):Y8(e.verb,e.value,{via:`tmux-status`},n)}return i2({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[i.url],category:`click.open`},`opening ${i.url}`,M),{kind:`ok`}}function Q8(e,t){let n=new Date,r=ak(n),i=[];try{try{var a=Aa();let n=a.u(o5(e,r,i));if(n===null)return null;let{drawn:o,motion:s,evaluated:c,lanes:l}=c5(n,{by:`feed`,fps:t}),u=d8.linkFor(e,u5(o)),d=l5(o,u);return{at:r,resp:{ok:!0,output:d},statusline:{ok:!0,output:_5(e,o,u,d,O6(l,c8.following(e)))},moves:s===`moves`,evaluated:c,failure:null}}catch(e){a.e=e}finally{a.d()}}catch(e){let{level:t,line:a}=R6(`render`,i,{kind:`threw`,error:e},Date.now()-n.getTime()),o=L8(e);return{at:r,resp:o,statusline:o,moves:!1,evaluated:0,failure:{level:t,line:`frame ${a}`}}}}function $8(e,t){return LH(t.config,t=>Q6.get(e,t),e=>t.authoredRoots.has(e))}function e5(e){try{var t=Aa();let n=t.u(f8.holdView(e));return n===null?null:PH(n.view.source.effective())}catch(e){t.e=e}finally{t.d()}}function t5(e,t){try{var n=Aa();return PH($8(t,n.u(f8.hold(e.projectDir,e.cwd,e.configFile??void 0)).state))}catch(e){n.e=e}finally{n.d()}}function n5(e){let{report:t}=v4(e.hookData),n=[];for(let e of t.missingRequired)n.push(`missing required field '${e}'`);for(let{path:e,expected:r,got:i}of t.typeMismatches)n.push(`field '${e}' expected ${r}, got ${i}`);let r=mW(e.hookData?.session_id);r.ok||n.push(`field 'session_id' ${r.problem}`),(typeof e.cwd!=`string`||!u(e.cwd))&&n.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&n.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let i=N6(e.deadline);if(i.kind===`refused`)return{ok:!1,problems:[...n,i.problem]};if(n.length>0||!r.ok)return{ok:!1,problems:n};for(let e of t.unknownTopLevelFields)z6.firstSightOfUnknownHookField(e)&&M(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let a=Vt(e),{configFile:o,refusedArgs:s}=H8(e.args,e.cwd);return{ok:!0,req:{...e,deadline:i,sessionId:r.id,hints:a,rateLimits:_M(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:o??a.configEnv??null},refusedArgs:s}}}const r5=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:N8});function i5(e,t,n){F6(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=Ht(e,r),a=Ut(i);return F6(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:i.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits}),a}function a5(e,t,n){let r=e.sessionId,i=i5(e,t,n),a=y2(e.requested,Q6,r);return s5(f8.holdSession(a.projectDir,a.cwd,a.configFile??void 0,e),e,i,t,n)}function o5(e,t,n){let r=f8.holdView(e);if(r===null){let t=f8.openFailure(e);if(t!==null)throw t.error;return null}let i=r.view.facts(),a;try{a=i5(i,t,n)}catch(e){throw r[Symbol.dispose](),e}return s5(r,i,a,t,n)}function s5(e,t,n,r,i){try{let{entry:a,state:o,view:s}=e,{sessionId:c,hints:l}=t,u=s.source.effective();return{req:t,at:r,facts:i,sessionId:c,entry:a,state:o,view:s,hintsError:n,payloadInputs:{hookData:t.hookData,deps:{...K6,lanes:s.lanes},cwd:t.cwd,neededInputPaths:o.neededInputPaths(u.preset),hints:l},[Symbol.dispose]:()=>e[Symbol.dispose]()}}catch(t){throw e[Symbol.dispose](),t}}function c5(e,t){let{req:n,at:r,facts:i,sessionId:a,entry:o,state:s,view:c,hintsError:l}=e,u=c.source.effective(),d=PH(u);F6(i,{lanes:Fv.filter(e=>d[e]).join(`,`)||`-`});let{hints:f}=c.facts(),p=kq(f),m=mb(f.termRows);F6(i,{width:String(p)});let h=c.source.payload(),g={drawing:t,feeds:c8.feedsOf(a,r),today:Gq(K6,c.lanes().today,c.facts().hookData,r)},_=ka(h.metrics)?void 0:h.metrics;F6(i,Bq(c.lanes().sources)),F6(i,{prompts:String(_?.messageCount??`-`),nonPrompts:String(_?.nonPrompts??`-`),pr:pq(h.git,Tq(e.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:R4(g.feeds)});let v=[],y=uq(u,p),b=t8.of(a),ee=n8.since(a,r),x=mZ(s.config,s.compiled,c.store,c.registry,g,r,y,{perSegmentSink:c.lastRenderCellsBySegment,onRenderWarning:e=>v.push(e)},{...u,effects:b,idleSince:ee});n8.observe(a,r,x.menuRows>0,u.menuTimeout);let S=n8.since(a,r);F6(i,{menuIdle:S===void 0?`-`:`${(r-S).toFixed(1)}s/${u.menuTimeout}s`});let te=ns(Q6,a,r,t.by),ne=te.kind===`held`||te.kind===`owed`?te.error:null,re=ne?.text??null,ie=[Gt(n.refusedArgs),l,o.lastError,re].filter(Boolean).join(`
497
+ `),ae=h8.notice({sessionId:a,dismissed:Q6.get(a,TU),enabled:u.updateNotice}),C=o.lastError===null?null:o.failedFile,w=[...o.lastWarning===null?[]:[{kind:`load`,message:o.lastWarning}],...v],oe=bb(ie,ae,w.map(e=>e.message).join(`
498
+ `)),se=q6.getStats(),T=J6.getStats(),ce=b.lastFrame(),le=ce.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,ue=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,de=w.map(e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`load`:case`band-floor`:case`when`:return e.kind}}).join(`,`)||`-`;return F6(i,{git:`${se.size}/${se.hits}h/${se.misses}m`,usage:`${T.size}/${T.hits}h/${T.misses}m`,effect:ce.effect,effectT:ce.t.toFixed(3),speed:`${ce.speed}x`,effectRows:`${ce.made}made/${ce.reused}reused`,effectOwn:le,fadeBasis:ce.basis,stateRev:String(ce.revision),fades:ue(ce.fades),leaves:ue(ce.leaves),motion:x.motion,evaluated:String(x.evaluated),pending:x.pending.join(`,`)||`-`,rules:[...x.rules].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:ie?`Y`:`N`,clickError:te.kind===`none`?`-`:te.kind,upd:String(ae.length),warn:de}),{drawn:{body:x.text,diagnostics:oe,failedConfigFile:C,geometry:{width:p,rowCap:m,colorCompatibility:u.colorCompatibility}},motion:x.motion,evaluated:x.evaluated,clickShown:ne,lanes:d}}function l5(e,t){return Cb(e.body,e.diagnostics,{fullText:t,failedConfigFile:e.failedConfigFile},e.geometry)+`
499
+ `}function u5(e){return e.diagnostics===null?null:Sb(e.diagnostics)}function d5(e){let t=e.sessionId,{client:n,...r}=e.hints,i=JSON.stringify(r);Q6.get(t,`client-hints`)!==i&&Q6.set(t,J2,i);let a=b2(e.requested);Q6.get(t,`render-origin`)!==a&&Q6.set(t,v2,a)}async function f5(e,t,n,r,i){return d5(e),g5(e,t,n,r,i)}function p5(e,t){o8.noted(m5(e),t),s8.observe(e.hookData.session_id,e.hints.tmux,t.tmuxStatus)}function m5(e){let t=e.hookData.session_id;return{sessionId:t,hints:e.hints,origin:y2(e.requested,Q6,t),transcript:e.hookData.transcript_path,answered:hM(e.hookData)}}function h5(e,t,n){let r=c8.latest(e);o8.clicked(e,r===null?null:m5(r),t,n),r!==null&&t.tmuxStatus!==n.tmuxStatus&&s8.observe(e,r.hints.tmux,n.tmuxStatus)}async function g5(e,t,n,r,i){try{var a=Aa();let o=a.u(a5(e,n,i));p5(e,PH(o.view.source.effective())),F6(i,{deadline:`${r.stated}:${r.ms}ms`});let s=performance.now(),c=new Map,l=await uG(e=>Promise.all([Kq(o.payloadInputs,n,c),o.view.registry.inFlight(e)]),r.endsAt-s,e=>M(`error`,`render wait failed after its deadline sid=${JSON.stringify(o.sessionId)}: ${T(e)}`)),u=performance.now();F6(i,{waited:`${Math.round(u-s)}ms`,ended:l,refreshed:jq(c)});let{drawn:d,motion:f,clickShown:p,lanes:m}=c5(o,Iv),{link:h,failure:g}=d8.sync(e.sessionId,t,u5(d));F6(i,{dumpFailed:g===null?`-`:JSON.stringify(g)});let _=l5(d,h),v=e.sessionId,y=O6(m,c8.following(v)),b=_5(v,d,h,_,y),ee=xM(e.hints.client??null)===`statusline`;return F6(i,{handoff:(ee?y:[]).join(`,`)||`-`,drew:`${Math.round(performance.now()-u)}ms`}),{answer:ee?b:_,motion:f,clickShown:p}}catch(e){a.e=e}finally{a.d()}}function _5(e,t,n,r,i){let[a,...o]=i;return a===void 0?r:l5({...t,body:wb(k6(e,[a,...o]),t.geometry)},n)}const v5={connectMs:200,budgetMs:500};async function y5(e,n){let r=n.includes(`--json`),i=await b5(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${un(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
500
+ `);return}t.stdout.write(x5(i.value))}function b5(e){return rn(()=>({kind:`debug`,what:e}),v5,e=>`debug`in e?e.debug:void 0)}function x5(e){switch(e.what){case`vars`:return S5(e.vars);case`segments`:return C5(e.segments);case`config`:return w5(e.config);default:return e}}function S5(e){if(e.length===0)return`no variables (DSL not active)
501
+ `;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${E5(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${T5(a.value)}${e}${o}`)}return t.join(`
502
502
  `)+`
503
- `}function _5(e){if(e.length===0)return`no segments (DSL not active)
503
+ `}function C5(e){if(e.length===0)return`no segments (DSL not active)
504
504
  `;let t=[`segments (${e.length})`,``];for(let n of e){t.push(` ${n.name}`),n.description!==null&&t.push(` shows ${n.description}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`);for(let{id:e,lastRender:r}of n.placements)r!==null&&t.push(` last ${e}: ${r}`)}return t.join(`
505
505
  `)+`
506
- `}function v5(e){return e===null?`config: DSL not active
506
+ `}function w5(e){return e===null?`config: DSL not active
507
507
  `:JSON.stringify(e,null,2)+`
508
- `}function y5(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function b5(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function x5(){let e=C5();return e===null?null:p.readFileSync(e,`utf-8`)}function S5(){let e;try{e=x5()}catch(e){t.stderr.write(`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`),t.exit(2)}e===null&&(t.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),t.exit(2)),t.stdout.write(e),t.exit(0)}function C5(){let e=s.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let r=s.dirname(s.resolve(n));for(;;){let t=s.join(r,e);if(p.existsSync(t))return t;let n=s.dirname(r);if(n===r)return null;r=n}}const w5=5e3;function T5(e,t,n,r){let i=`/home/tester`,a=Math.floor(r),o=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,s={current_dir:`${i}/code/cc-candybar/src`,project_dir:`${i}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:o,version:`1.15.0`,home:i,cwd:`${i}/code/cc-candybar/src`,transcript_path:`${i}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:s,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,tracking:`tracked`,stash:1,status:`dirty`,operation:`rebase`,committedAt:a-780},session:{cost:.39,tokens:241400},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:a+2*3600},weekly:{percentage:21,resetsAt:a+5*86400},cache:{expiresAt:a+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:gP(4e5,1e6),...lq(t),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:ky(()=>!0),themeDefault:t.theme.kind===`decided`?{differs:!0,theme:t.theme.name}:{differs:!1},resumeCommand:sq(s,o,void 0),configPath:n??`${i}/.config/cc-candybar/config.json5`,plugins:zq(Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]),()=>F)}}const E5={cost:12.5,tokens:34e5};function D5(e,t){let n=WV(e,e),r=qV(n);return r!==null&&t.push(r),n.kind===`chain`?n.layers:[]}async function O5(e,n=t.cwd()){let r=[],i=JB(n,e)??null,a=i===null?D5(n,r):[i];if(i!==null){let e;try{e=p.statSync(i,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:i,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:i,message:`not a file`}}let o=YV(n,n);o!==null&&r.push(o);try{return{kind:`clean`,layers:a,warnings:r,rendered:await j5(a,n,r)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&a.includes(t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof Z_&&r.push(...e.warnings),{kind:`fatal`,layers:a,message:e instanceof Z_||e instanceof Error?e.message:String(e),warnings:r})}}async function k5(e,t,n,r){let i=rH(e,EH,{entered:()=>{},warned:e=>n.push(...e)},{projectDir:t,cwd:t}),{config:a}=i,o=new pS,s=new $k(o,a.globals.default_empty_value??``,new LZ);try{let c=JX(a,s,{cwd:t,signer:Yo()});n.push(...c.loadWarnings);let l=FH(a,()=>null,()=>!1);CX(c,o,s,UX({...T5(a,l,e.at(-1)??null,r),today:E5},l));let u=await s.settled(w5);return u.length>0&&n.push(`source${u.length===1?``:`s`} still running after ${w5} ms, rendered with fallback values: ${u.join(`, `)}`),{layers:e,droppedPlugins:[...i.installed.dropped,...i.layers.flatMap(e=>e.plugins.dropped)],config:a,compiled:c,store:o,registry:s}}catch(e){throw s.dispose(),e}}function A5({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=new Map,l=new Set,u=e=>{switch(e.kind){case`rule`:c.set(`${e.slot} rule`,e.message);return;case`when`:c.set(e.where,e.error);return;case`refresh`:c.set(`variable "${e.variable}"`,`cannot refresh: ${e.error}`);return;case`band-floor`:l.add(e.message);return;default:}};return{rendered:dZ(t,n,r,i,{...T5(t,a,e.at(-1)??null,s),today:E5},s,cq(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning:u},a),failures:c,advisories:l}}async function j5(e,t,n){let r=ik(new Date),i=await k5(e,t,n,r),{config:a}=i;try{let e=RU();try{_U(a),qI(a)}finally{e()}let t=$b(null,a.globals.preset,a.presets),o=(e,t)=>{let n=FH(a,t=>t===`preset`?e:null,()=>t),o;try{o=A5(i,n,200,r)}catch(e){o={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...o}},s=o(t,!1),c=[s,o(t,!0),...Qb(a.presets).filter(e=>e!==t).flatMap(e=>[o(e,!1),o(e,!0)])],l=e=>{let n=new Map;for(let t of c)for(let r of e(t)){let e=n.get(r)??new Map;e.set(t.preset,(e.get(t.preset)??new Set).add(t.customized)),n.set(r,e)}return[...n].map(([e,n])=>n.get(t)?.has(!1)?e:`${e} (under ${[...n].map(([e,n])=>[...e===t?[]:[`preset "${e}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};n.push(...l(e=>e.advisories));let u=l(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=s.rendered,f=i.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
508
+ `}function T5(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function E5(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function D5(){let e=k5();return e===null?null:p.readFileSync(e,`utf-8`)}function O5(){let e;try{e=D5()}catch(e){t.stderr.write(`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`),t.exit(2)}e===null&&(t.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),t.exit(2)),t.stdout.write(e),t.exit(0)}function k5(){let e=s.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let r=s.dirname(s.resolve(n));for(;;){let t=s.join(r,e);if(p.existsSync(t))return t;let n=s.dirname(r);if(n===r)return null;r=n}}const A5=5e3;function j5(e,t,n,r){let i=`/home/tester`,a=Math.floor(r),o=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,s={current_dir:`${i}/code/cc-candybar/src`,project_dir:`${i}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:o,version:`1.15.0`,home:i,cwd:`${i}/code/cc-candybar/src`,transcript_path:`${i}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:s,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,tracking:`tracked`,stash:1,status:`dirty`,operation:`rebase`,committedAt:a-780},session:{cost:.39,tokens:241400},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:a+2*3600},weekly:{percentage:21,resetsAt:a+5*86400},cache:{expiresAt:a+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:_P(4e5,1e6),...dq(t),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:ky(()=>!0),themeDefault:t.theme.kind===`decided`?{differs:!0,theme:t.theme.name}:{differs:!1},resumeCommand:lq(s,o,void 0),configPath:n??`${i}/.config/cc-candybar/config.json5`,plugins:Vq(Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]),()=>F)}}const M5={cost:12.5,tokens:34e5};function N5(e,t){let n=KV(e,e),r=YV(n);return r!==null&&t.push(r),n.kind===`chain`?n.layers:[]}async function P5(e,n=t.cwd()){let r=[],i=XB(n,e)??null,a=i===null?N5(n,r):[i];if(i!==null){let e;try{e=p.statSync(i,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:i,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:i,message:`not a file`}}let o=ZV(n,n);o!==null&&r.push(o);try{return{kind:`clean`,layers:a,warnings:r,rendered:await L5(a,n,r)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&a.includes(t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof Z_&&r.push(...e.warnings),{kind:`fatal`,layers:a,message:e instanceof Z_||e instanceof Error?e.message:String(e),warnings:r})}}async function F5(e,t,n,r){let i=aH(e,OH,{entered:()=>{},warned:e=>n.push(...e)},{projectDir:t,cwd:t}),{config:a}=i,o=new mS,s=new eA(o,a.globals.default_empty_value??``,new zZ);try{let c=XX(a,s,{cwd:t,signer:Yo()});n.push(...c.loadWarnings);let l=LH(a,()=>null,()=>!1);TX(c,o,s,GX({...j5(a,l,e.at(-1)??null,r),today:M5},l));let u=await s.settled(A5);return u.length>0&&n.push(`source${u.length===1?``:`s`} still running after ${A5} ms, rendered with fallback values: ${u.join(`, `)}`),{layers:e,droppedPlugins:[...i.installed.dropped,...i.layers.flatMap(e=>e.plugins.dropped)],config:a,compiled:c,store:o,registry:s}}catch(e){throw s.dispose(),e}}function I5({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=new Map,l=new Set,u=e=>{switch(e.kind){case`rule`:c.set(`${e.slot} rule`,e.message);return;case`when`:c.set(e.where,e.error);return;case`refresh`:c.set(`variable "${e.variable}"`,`cannot refresh: ${e.error}`);return;case`band-floor`:l.add(e.message);return;default:}};return{rendered:pZ(t,n,r,i,{...j5(t,a,e.at(-1)??null,s),today:M5},s,uq(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning:u},a),failures:c,advisories:l}}async function L5(e,t,n){let r=ak(new Date),i=await F5(e,t,n,r),{config:a}=i;try{let e=BU();try{yU(a),YI(a)}finally{e()}let t=ex(null,a.globals.preset,a.presets),o=(e,t)=>{let n=LH(a,t=>t===`preset`?e:null,()=>t),o;try{o=I5(i,n,200,r)}catch(e){o={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...o}},s=o(t,!1),c=[s,o(t,!0),...$b(a.presets).filter(e=>e!==t).flatMap(e=>[o(e,!1),o(e,!0)])],l=e=>{let n=new Map;for(let t of c)for(let r of e(t)){let e=n.get(r)??new Map;e.set(t.preset,(e.get(t.preset)??new Set).add(t.customized)),n.set(r,e)}return[...n].map(([e,n])=>n.get(t)?.has(!1)?e:`${e} (under ${[...n].map(([e,n])=>[...e===t?[]:[`preset "${e}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};n.push(...l(e=>e.advisories));let u=l(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=s.rendered,f=i.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
509
509
  `)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
510
- `));return d}finally{i.registry.dispose()}}function M5(e){return e.map(e=>`warning: ${e}\n`).join(``)}function N5(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.layers.join(` < `)||`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${e.rendered}\n`:``),stderr:M5(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:M5(e.warnings)+`✗ ${e.layers.join(` < `)||`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const P5=`--render`,F5=`Usage: cc-candybar check [${P5}] [config-file]\n`;function I5(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==P5);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${F5}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${F5}`}:{kind:`run`,target:n[0],render:t.includes(P5)}}async function L5(e){let n=I5(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:N5(await O5(n.target??N3(t.env,t.cwd())),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const R5=/^[a-z][a-z0-9+.-]*:\/\//i,z5=/^[^@\s/]+@[^:\s/]+:/,B5=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function V5(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function H5(e,t,n){let r=qB(t,e);if(n(r))return{kind:`path`,dir:r};if(R5.test(e)||z5.test(e))return{kind:`git`,url:e,shown:V5(e)};let i=B5.exec(e);if(i){let e=`https://github.com/${i[1]}.git`;return{kind:`git`,url:e,shown:e}}return{error:`"${e}" is not a directory, a GitHub repo slug (owner/repo) or a git URL`}}function U5(e,t){let n=s.join(e,MV),r=FV(n);if(`error`in r)throw Error(`${t}: could not list ${MV}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${MV}/<name>/${ZB}`);return r.folders.map(e=>s.join(n,e,ZB))}function W5(e,t,n){let r=(n,...r)=>{let i=D({bin:`git`,args:r,env:n,category:`plugin.git`});if(!i.ok)throw Error(`git ${r.map(n=>n===e?t:n).join(` `)} failed (${i.reason}): ${i.stderr.trim()||i.error||``}`);return i.stdout},i={...process.env,GIT_TERMINAL_PROMPT:`0`};for(let e of r(i,`rev-parse`,`--local-env-vars`).split(`
511
- `))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${MV}/`)}function G5(e,t){switch(e.kind){case`path`:return t(e.dir);case`git`:{let n=p.mkdtempSync(s.join(C.tmpdir(),`cc-candybar-plugin-`));try{return W5(e.url,e.shown,s.join(n,`repo`)),t(s.join(n,`repo`))}finally{p.rmSync(n,{recursive:!0,force:!0})}}}}function K5(e){let t;try{t=p.lstatSync(e)}catch(e){if(e.code===`ENOENT`)return`installed`;throw e}if(t.isDirectory())return`updated`;if(t.isSymbolicLink())return`replaced`;throw Error(`${e} is a file, not a plugin folder: move it, then install again`)}function q5(e,t,n,r){switch(r){case`updated`:p.renameSync(s.join(e,ZB),s.join(t,ZB));return;case`replaced`:p.renameSync(t,n),p.renameSync(e,t);return;case`installed`:p.renameSync(e,t);return}}function J5(e,t,n){let r=U5(e,n);p.mkdirSync(t,{recursive:!0});let i=p.mkdtempSync(s.join(t,`.install-`));try{let a=r.map(e=>{let t=s.join(i,s.basename(s.dirname(e)));p.mkdirSync(t);try{p.copyFileSync(e,s.join(t,ZB))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),o=tH(a.map(e=>s.join(e,ZB)),EH,{root:e,git:!1});if(o.length>0)throw Error(o.map(e=>`${n}: ${s.join(MV,s.relative(i,e.path))} would not load: ${e.reason.split(i).join(s.join(n,MV))}`).join(`
512
- `));let c=a.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:K5(r)}}),l=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)q5(e,n,s.join(i,`.replaced-${t}`),r),l.push(t)}catch(e){throw Error(`${e.message} (placed before it: ${l.join(`, `)||`none`})`)}return c.map(({target:e,placed:t})=>({path:s.join(e,ZB),placed:t}))}finally{p.rmSync(i,{recursive:!0,force:!0})}}function Y5(e){let[t,n,...r]=e;if(t!==`install`||n===void 0||r.length>0)return console.error(`Usage: cc-candybar plugin install <path | owner/repo | git URL>`),2;let i=H5(n,process.cwd(),Uk);if(`error`in i)return console.error(`plugin install: ${i.error}`),2;try{let e=i.kind===`path`?i.dir:i.shown,t=G5(i,t=>J5(t,jV(),e));for(let{path:n,placed:r}of t)console.log(`${r} plugin ${s.basename(s.dirname(n))} → ${n} (from ${e})`);return 0}catch(e){return console.error(`plugin install: ${e.message}`),1}}function X5(e,t){if(e!==void 0&&/^\+?\d+$/.test(e)){let t=Number(e);if(t>0&&t<=4294967295)return t}if(t&&t>0)return t}const Z5=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function Q5(e,t,n){return{termCols:X5(e.COLUMNS,n.columns),termRows:X5(e.LINES,n.rows),ssh:Z5.some(t=>(e[t]??``)!==``),tmux:fM(e),configEnv:N3(e,t),claudeConfigDir:Ja(e,t),terminalEnv:Lt(e)}}function $5(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function e7(e){let t=_0(e,[`bundle`,`clients`]);if(t!==null)return{kind:`failed`,reason:t};if(typeof e.bundle!=`string`)return{kind:`failed`,reason:`the running daemon (${e.version}) reported its bundle as ${JSON.stringify(e.bundle)}`};let n=$5(e);return n.every(e=>typeof e.ago==`number`&&typeof e.sessionId==`string`)?{kind:`ok`,value:{bundle:e.bundle,clients:n.map(e=>({client:nn(e.client)??null,sessionId:e.sessionId,ago:e.ago}))}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported clients without their age or session: ${JSON.stringify(e.clients)}`}}const t7=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},n7=e=>{let t=e??{};if(t.kind===`unmeasured`)return!0;let n=t.charge;return t.kind===`measured`&&typeof t.rss==`number`&&typeof t.heapTotal==`number`&&typeof n?.bytes==`number`&&(n.kind===`charged`&&(n.measure===`phys_footprint`||n.measure===`rss`)||n.kind===`stand-in`&&typeof n.unread==`string`&&Number.isFinite(n.gap))};function r7(e,t){let n=e;if(n?.kind===`failed`&&typeof n.reason==`string`)return{kind:`failed`,reason:n.reason};if(n?.kind!==`ok`)return{kind:`misshapen`,reason:`is not an answer`};let r=t(n.value);return r.kind===`ok`?r:{kind:`misshapen`,reason:r.reason}}function i7(e){let t=_0(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=r7(n?.postMortems,e=>Array.isArray(e)&&e.every(t7)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&n7(n.memory)&&typeof n.limit==`number`&&r.kind!==`misshapen`?{kind:`ok`,value:{...n,postMortems:r}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported itself as ${JSON.stringify(e.daemon)}`}}function a7(e,t,n){let r=_0(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=$5(e);return i.every(t)?{kind:`ok`,value:i}:{kind:`failed`,reason:`the running daemon (${e.version}) reported its renders without ${n} — restart it on this build: ${JSON.stringify(e.clients)}`}}const o7=e=>yM.includes(e.role),s7=e=>a7(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&hM.includes(e.rateLimits),`the rate-limit windows they carried`),c7=e=>a7(e,e=>{let t=e.transcript;return typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof t?.path==`string`&&typeof t.answered==`boolean`},`their transcripts`),l7=e=>a7(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&o7(e)&&vM.includes(e.frame),`what they drew and from which project`),u7=e=>a7(e,e=>typeof e.sessionId==`string`&&typeof e.ago==`number`&&o7(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function d7(e,t,n){let r=e.doctorStores?.[t],i=r7(r,n);return i.kind===`misshapen`?{kind:`failed`,reason:`the running daemon (${e.version}) reported its ${t} as ${JSON.stringify(r)}, which ${i.reason}`}:i}function f7(e){let t=_0(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:d7(e,`marks`,O$),clicked:d7(e,`clicked`,j$),postMortemsRead:d7(e,`postMortemsRead`,N1)}}async function p7(){let e=await g0();if(e.kind!==`ok`){let t={kind:`failed`,reason:un(e).split(`
513
- `).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:e7(e.value),rateLimits:s7(e.value),transcripts:c7(e.value),frames:l7(e.value),widths:u7(e.value),serving:i7(e.value),stores:f7(e.value)}}const m7=` (fix: click the settings menu (${bi} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,h7=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${bi} by default) › 🧰 tools › 🩺 doctor`;function g7({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:m7}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${h7}\n`)}function _7(e){let t={sessionState:new LZ,storage:vZ,signer:Yo()},n=DZ(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??OZ(e.cwd,e.projectDir,t);return r.registry.dispose(),{layers:n.layers,error:n.error,warning:n.warning,unused:r.unused,config:r.config}}function v7(e,t,n){return n.kind===`failed`?n:L1(e,n.value.bundle,I$(t,n.value.clients).map(({client:e})=>e))}function y7(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:I$(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function b7(e,t){return t.kind===`failed`?t:{kind:`ok`,value:I$(e,t.value).map(e=>e.transcript)}}function x7(e,t){return t.kind===`failed`?t:{kind:`ok`,value:R$(e,t.value)}}function S7(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:d0(e.sessionId,I$(e,t.value))}async function C7(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=Q5(r,i,a()),u=F$(r.CLAUDE_CODE_SESSION_ID);s={...f0(e,l,{projectDir:L$(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,configFile:JB(i,o)??N3(r,i)??null},()=>null,c.serving,y7(u,c.rateLimits,Ya(l.claudeConfigDir)),b7(u,c.transcripts),u,x7(u,c.frames),S7(u,c.widths,l.termCols??null),c.stores),urlHandler:await N0(t),install:v7(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=IN(s);return{stdout:c.map(g7).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function w7(){if(t.stderr.isTTY)return t.stderr;let e;try{e=v(`/dev/tty`,`r+`)}catch{return{}}let n=new xe(e),{columns:r}=n;return n.destroy(),{columns:r}}async function T7(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
510
+ `));return d}finally{i.registry.dispose()}}function R5(e){return e.map(e=>`warning: ${e}\n`).join(``)}function z5(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.layers.join(` < `)||`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${e.rendered}\n`:``),stderr:R5(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:R5(e.warnings)+`✗ ${e.layers.join(` < `)||`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const B5=`--render`,V5=`Usage: cc-candybar check [${B5}] [config-file]\n`;function H5(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==B5);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${V5}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${V5}`}:{kind:`run`,target:n[0],render:t.includes(B5)}}async function U5(e){let n=H5(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:z5(await P5(n.target??I3(t.env,t.cwd())),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const W5=/^[a-z][a-z0-9+.-]*:\/\//i,G5=/^[^@\s/]+@[^:\s/]+:/,K5=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function q5(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function J5(e,t,n){let r=YB(t,e);if(n(r))return{kind:`path`,dir:r};if(W5.test(e)||G5.test(e))return{kind:`git`,url:e,shown:q5(e)};let i=K5.exec(e);if(i){let e=`https://github.com/${i[1]}.git`;return{kind:`git`,url:e,shown:e}}return{error:`"${e}" is not a directory, a GitHub repo slug (owner/repo) or a git URL`}}function Y5(e,t){let n=s.join(e,PV),r=LV(n);if(`error`in r)throw Error(`${t}: could not list ${PV}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${PV}/<name>/${$B}`);return r.folders.map(e=>s.join(n,e,$B))}function X5(e,t,n){let r=(n,...r)=>{let i=D({bin:`git`,args:r,env:n,category:`plugin.git`});if(!i.ok)throw Error(`git ${r.map(n=>n===e?t:n).join(` `)} failed (${i.reason}): ${i.stderr.trim()||i.error||``}`);return i.stdout},i={...process.env,GIT_TERMINAL_PROMPT:`0`};for(let e of r(i,`rev-parse`,`--local-env-vars`).split(`
511
+ `))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${PV}/`)}function Z5(e,t){switch(e.kind){case`path`:return t(e.dir);case`git`:{let n=p.mkdtempSync(s.join(C.tmpdir(),`cc-candybar-plugin-`));try{return X5(e.url,e.shown,s.join(n,`repo`)),t(s.join(n,`repo`))}finally{p.rmSync(n,{recursive:!0,force:!0})}}}}function Q5(e){let t;try{t=p.lstatSync(e)}catch(e){if(e.code===`ENOENT`)return`installed`;throw e}if(t.isDirectory())return`updated`;if(t.isSymbolicLink())return`replaced`;throw Error(`${e} is a file, not a plugin folder: move it, then install again`)}function $5(e,t,n,r){switch(r){case`updated`:p.renameSync(s.join(e,$B),s.join(t,$B));return;case`replaced`:p.renameSync(t,n),p.renameSync(e,t);return;case`installed`:p.renameSync(e,t);return}}function e7(e,t,n){let r=Y5(e,n);p.mkdirSync(t,{recursive:!0});let i=p.mkdtempSync(s.join(t,`.install-`));try{let a=r.map(e=>{let t=s.join(i,s.basename(s.dirname(e)));p.mkdirSync(t);try{p.copyFileSync(e,s.join(t,$B))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),o=rH(a.map(e=>s.join(e,$B)),OH,{root:e,git:!1});if(o.length>0)throw Error(o.map(e=>`${n}: ${s.join(PV,s.relative(i,e.path))} would not load: ${e.reason.split(i).join(s.join(n,PV))}`).join(`
512
+ `));let c=a.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:Q5(r)}}),l=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)$5(e,n,s.join(i,`.replaced-${t}`),r),l.push(t)}catch(e){throw Error(`${e.message} (placed before it: ${l.join(`, `)||`none`})`)}return c.map(({target:e,placed:t})=>({path:s.join(e,$B),placed:t}))}finally{p.rmSync(i,{recursive:!0,force:!0})}}function t7(e){let[t,n,...r]=e;if(t!==`install`||n===void 0||r.length>0)return console.error(`Usage: cc-candybar plugin install <path | owner/repo | git URL>`),2;let i=J5(n,process.cwd(),Wk);if(`error`in i)return console.error(`plugin install: ${i.error}`),2;try{let e=i.kind===`path`?i.dir:i.shown,t=Z5(i,t=>e7(t,NV(),e));for(let{path:n,placed:r}of t)console.log(`${r} plugin ${s.basename(s.dirname(n))} → ${n} (from ${e})`);return 0}catch(e){return console.error(`plugin install: ${e.message}`),1}}function n7(e,t){if(e!==void 0&&/^\+?\d+$/.test(e)){let t=Number(e);if(t>0&&t<=4294967295)return t}if(t&&t>0)return t}const r7=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function i7(e,t,n){return{termCols:n7(e.COLUMNS,n.columns),termRows:n7(e.LINES,n.rows),ssh:r7.some(t=>(e[t]??``)!==``),tmux:pM(e),configEnv:I3(e,t),claudeConfigDir:Ja(e,t),terminalEnv:Lt(e)}}function a7(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function o7(e){let t=y0(e,[`bundle`,`clients`]);if(t!==null)return{kind:`failed`,reason:t};if(typeof e.bundle!=`string`)return{kind:`failed`,reason:`the running daemon (${e.version}) reported its bundle as ${JSON.stringify(e.bundle)}`};let n=a7(e);return n.every(e=>typeof e.ago==`number`&&typeof e.sessionId==`string`)?{kind:`ok`,value:{bundle:e.bundle,clients:n.map(e=>({client:nn(e.client)??null,sessionId:e.sessionId,ago:e.ago}))}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported clients without their age or session: ${JSON.stringify(e.clients)}`}}const s7=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},c7=e=>{let t=e??{};if(t.kind===`unmeasured`)return!0;let n=t.charge;return t.kind===`measured`&&typeof t.rss==`number`&&typeof t.heapTotal==`number`&&typeof n?.bytes==`number`&&(n.kind===`charged`&&(n.measure===`phys_footprint`||n.measure===`rss`)||n.kind===`stand-in`&&typeof n.unread==`string`&&Number.isFinite(n.gap))};function l7(e,t){let n=e;if(n?.kind===`failed`&&typeof n.reason==`string`)return{kind:`failed`,reason:n.reason};if(n?.kind!==`ok`)return{kind:`misshapen`,reason:`is not an answer`};let r=t(n.value);return r.kind===`ok`?r:{kind:`misshapen`,reason:r.reason}}function u7(e){let t=y0(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=l7(n?.postMortems,e=>Array.isArray(e)&&e.every(s7)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&c7(n.memory)&&typeof n.limit==`number`&&r.kind!==`misshapen`?{kind:`ok`,value:{...n,postMortems:r}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported itself as ${JSON.stringify(e.daemon)}`}}function d7(e,t,n){let r=y0(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=a7(e);return i.every(t)?{kind:`ok`,value:i}:{kind:`failed`,reason:`the running daemon (${e.version}) reported its renders without ${n} — restart it on this build: ${JSON.stringify(e.clients)}`}}const f7=e=>bM.includes(e.role),p7=e=>d7(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&gM.includes(e.rateLimits),`the rate-limit windows they carried`),m7=e=>d7(e,e=>{let t=e.transcript;return typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof t?.path==`string`&&typeof t.answered==`boolean`},`their transcripts`),h7=e=>d7(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&f7(e)&&yM.includes(e.frame),`what they drew and from which project`),g7=e=>d7(e,e=>typeof e.sessionId==`string`&&typeof e.ago==`number`&&f7(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function _7(e,t,n){let r=e.doctorStores?.[t],i=l7(r,n);return i.kind===`misshapen`?{kind:`failed`,reason:`the running daemon (${e.version}) reported its ${t} as ${JSON.stringify(r)}, which ${i.reason}`}:i}function v7(e){let t=y0(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:_7(e,`marks`,A$),clicked:_7(e,`clicked`,N$),postMortemsRead:_7(e,`postMortemsRead`,F1)}}async function y7(){let e=await v0();if(e.kind!==`ok`){let t={kind:`failed`,reason:un(e).split(`
513
+ `).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:o7(e.value),rateLimits:p7(e.value),transcripts:m7(e.value),frames:h7(e.value),widths:g7(e.value),serving:u7(e.value),stores:v7(e.value)}}const b7=` (fix: click the settings menu (${bi} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,x7=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${bi} by default) › 🧰 tools › 🩺 doctor`;function S7({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:b7}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${x7}\n`)}function C7(e){let t={sessionState:new zZ,storage:bZ,signer:Yo()},n=kZ(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??AZ(e.cwd,e.projectDir,t);return r.registry.dispose(),{layers:n.layers,error:n.error,warning:n.warning,unused:r.unused,config:r.config}}function w7(e,t,n){return n.kind===`failed`?n:z1(e,n.value.bundle,R$(t,n.value.clients).map(({client:e})=>e))}function T7(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:R$(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function E7(e,t){return t.kind===`failed`?t:{kind:`ok`,value:R$(e,t.value).map(e=>e.transcript)}}function D7(e,t){return t.kind===`failed`?t:{kind:`ok`,value:B$(e,t.value)}}function O7(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:p0(e.sessionId,R$(e,t.value))}async function k7(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=i7(r,i,a()),u=L$(r.CLAUDE_CODE_SESSION_ID);s={...m0(e,l,{projectDir:z$(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,configFile:XB(i,o)??I3(r,i)??null},()=>null,c.serving,T7(u,c.rateLimits,Ya(l.claudeConfigDir)),E7(u,c.transcripts),u,D7(u,c.frames),O7(u,c.widths,l.termCols??null),c.stores),urlHandler:await F0(t),install:w7(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=LN(s);return{stdout:c.map(S7).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function A7(){if(t.stderr.isTTY)return t.stderr;let e;try{e=v(`/dev/tty`,`r+`)}catch{return{}}let n=new xe(e),{columns:r}=n;return n.destroy(),{columns:r}}async function j7(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
514
514
  Usage: cc-candybar doctor [config-file]
515
- `),t.exit(2));let n=t.cwd(),r=await C7(Y1(_7),L0(),p7,t.env,n,w7,e[0]);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}function E7(e){return!e.ok&&e.code!==`RENDER_FAILED`}function D7(e,t,n,r,i){let a=null,o=e=>{a===null&&(a=e,s.destroy(),i(e))},s=ue.createConnection({path:e}),c={v:3,kind:`subscribe`,sessionId:t,lane:n};return s.once(`connect`,()=>s.write(Qt(c))),s.on(`data`,en(e=>{let t=e;E7(t)?o({kind:`refused`,resp:t}):r(t)},e=>o({kind:`failed`,error:e}))),s.on(`error`,e=>o({kind:`failed`,error:e})),s.on(`close`,()=>o({kind:`closed-there`})),{close:()=>o({kind:`closed-here`})}}function O7(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(2e3,e*2)}}function k7(e){switch(e.kind){case`failed`:return{kind:`reconnect`,reason:`stream failed (${e.error.message})`,kick:!0};case`closed-there`:return{kind:`reconnect`,reason:`daemon closed the stream`,kick:!1};case`refused`:return e.resp.code===`SWITCHED_OFF`?{kind:`off`,resp:e.resp}:e.resp.code===`TIMEOUT`?{kind:`reconnect`,reason:`the daemon was too busy to open the stream (${e.resp.error})`,kick:!1}:e.resp.code===`BAD_REQUEST`?{kind:`reconnect`,reason:`the daemon does not take subscribe (${e.resp.error}); it restarts on the new build`,kick:!1}:e.resp.code===`VERSION_MISMATCH`&&e.resp.daemonV!==void 0&&e.resp.daemonV<3?{kind:`reconnect`,reason:`the daemon is older than this client (${e.resp.error})`,kick:!0}:{kind:`exit`,reason:`the daemon refused the stream: ${e.resp.code}: ${e.resp.error}`}}}function A7(e,t,n,r){let i=null,a=null,o=!1,s=250,c=(e,t)=>{a=setTimeout(()=>{a=null,((t?r.beforeReconnect?.():void 0)??Promise.resolve()).then(()=>{o||l()})},e)},l=()=>{i=D7(e,t,n,e=>{s=O7(s,e.ok?`frame-ok`:`frame-failed`),r.frame(e)},e=>{if(e.kind===`closed-here`||o)return;let t=k7(e);switch(t.kind){case`exit`:r.exit(t.reason);return;case`off`:r.off(t.resp),c(5e3,!1);return;case`reconnect`:{r.fault(t.reason,s),t.kick&&_r();let e=s;s=O7(s,`fault`),c(e,!0);return}}})};return l(),{close:()=>{o=!0,a!==null&&clearTimeout(a),i?.close()}}}function j7(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function M7(e,n){let{values:r,tokens:i}=ce({args:e.slice(3),options:{config:{type:`string`},lane:{type:`string`}},strict:!0,tokens:!0}),a=[e[1],...i.flatMap(e=>e.kind===`option`&&e.name===`config`?[e.rawName,e.value]:[])],o=t.cwd(),s=e=>{t.stderr.write(`cc-candybar frames: ${e}\n`)},c=Hv(r.lane);c===null&&(s(`--lane needs one of ${Fv.join(`, `)}`),t.exit(2)),t.stdout.on(`error`,()=>t.exit(0));let l=H4(t.stdout),u=null,d=null,f=null,p={kind:`none`},m=(e,t)=>{j7(p,e)&&t(),p=e},h=async e=>{let r=await hn(e,a,o,{...Q5(t.env,o,t.stderr),client:zt(`frames`,n)});r.kind!==`ok`&&(s(un(r)),r.kind===`transient`&&_r())},g=e=>{f?.close(),f=A7(St(),e,c,{frame:e=>m({kind:`frame`},()=>l(`${JSON.stringify(e)}\n`)),off:e=>m({kind:`off`},()=>l(`${JSON.stringify(e)}\n`)),fault:(e,t)=>m({kind:`fault`,reason:e},()=>s(`${e}; reconnecting in ${t}ms`)),exit:e=>{s(e),t.exit(1)},beforeReconnect:()=>d===null?Promise.resolve():h(d)})};for await(let e of Se({input:t.stdin})){if(e.trim()===``)continue;let t;try{t=JSON.parse(e)}catch(e){s(`stdin line is not JSON: ${e.message}`);continue}if(typeof t.session_id!=`string`||t.session_id===``){s(`stdin line carries no session_id`);continue}d=t,await h(t),t.session_id!==u&&(u=t.session_id,g(u))}t.exit(0)}function N7(e){let t=e.replace(/\n+$/,``).split(`
516
- `);return{bytes:t.map((e,t)=>`\x1b[${t+1}H${e}`).join(``)+`\x1B[J`,rows:t.length}}const P7=5e3,F7=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function I7(e,t,n,r){let i=e.split(`
517
- `).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?K4(e,G4(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function L7(e,t){let[n,r]=await Promise.all([PK(e,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${t}},#{==:#{pane_id},${e.pane}}}`,`-F`,U4]),PK(e,`bar-pane.tmux`,[`list-clients`,`-F`,W4])]);return n.kind===`ok`?r.kind===`ok`?{kind:`ok`,placement:I7(n.stdout,r.stdout,t,e.pane)}:r:n}function R7(){let e=Date.now();return t=>{if(t.kind===`ok`)e=Date.now();else if(Date.now()-e>P7)throw Error(`tmux has not answered for ${P7/1e3} s: ${t.reason}`)}}function z7(e){let{positionals:t}=(()=>{try{return ce({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${F7}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(F7);return{pane:n}}async function B7(e){try{return await V7(e),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function V7(e){let{pane:n}=z7(e),r=fM(t.env);if(r===null)throw Error(`cc-candybar bar-pane runs in a tmux pane`);if(!t.stdout.isTTY)throw Error(`cc-candybar bar-pane draws on its pane's terminal`);let i=await L7(r,n);if(i.kind!==`ok`)throw Error(i.reason);let a=i.placement;if(a.kind===`gone`)throw Error(`no pane ${n} on this tmux server (${r.socket})`);t.stdout.write(`\x1B[?25l\x1B[?7l`),t.on(`exit`,()=>t.stdout.write(`\x1B[?25h\x1B[?7h`));for(let[e,n]of[[`SIGINT`,130],[`SIGTERM`,143],[`SIGHUP`,129]])t.once(e,()=>t.exit(n));let o=e=>{t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),t.exit(1)},s=null,c=`waiting for pane ${n}'s bar`,l=()=>s?.said.latest??c,u=``,d=R7(),f=async()=>{if(a.kind!==`shown`)return;let e=N7(l());e.rows!==t.stdout.rows&&!a.zoomed&&d(await PK(r,`bar-pane.tmux`,[`resize-pane`,`-t`,r.pane,`-y`,String(e.rows)])),e.bytes!==u&&t.stdout.write(e.bytes),u=e.bytes},p=null,m=!1,h=()=>{m=!0,p??=(async()=>{try{for(;m;)m=!1,await f()}finally{p=null}})(),p.catch(o)};t.stdout.on(`resize`,()=>{u=``,h()});let g=e=>{if(s?.sessionId===e)return;if(s?.follower.close(),e===null){s=null;return}let t={latest:null},n=e=>{t.latest=e,h()};s={sessionId:e,said:t,follower:A7(St(),e,`pane`,{frame:e=>n(KU(mn(e)).output),off:e=>n(e.error),fault:n,exit:e=>o(Error(e))})}},_=R7();for(;a.kind!==`gone`;){if(a.kind===`hidden`)g(null);else{let e=await gn(r.socket,n);e.kind===`ok`?(g(e.value),c=e.value===null?`waiting for pane ${n}'s statusline to render on ${St()}`:`waiting for pane ${n}'s bar`):(e.kind===`transient`&&(_r(),u=``),c=un(e))}h(),await be(500);let e=await L7(r,n);_(e),e.kind===`ok`&&(a=e.placement)}g(null),t.stderr.write(`cc-candybar bar-pane: pane ${n} closed\n`)}const H7=i(import.meta.url),U7=e=>e.some(e=>t.argv.includes(e));function W7(){console.log(lM);let e=Do(H7),t=p.existsSync(e)?``:" (nothing is there yet: run `cc-candybar install` first — in a checkout, `pnpm build`)\n";console.log(`Starting Claude Code on ${Pv.statusline.label} yourself (a Bun-compiled Claude Code):\n ${He(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const G7={install:async e=>{await Uo(e,H7),t.exit(0)},"install-url-handler":async()=>{Ro(H7),t.exit(0)},"url-handle":async e=>{await Bo(e[0])},daemon:async()=>{g8()},"daemon-stats":async e=>{await h0(e),t.exit(0)},frames:async()=>{await M7(t.argv,H7)},check:async e=>{await L5(e)},lint:async e=>{await L5(e)},plugin:async e=>{t.exit(Y5(e))},schema:async()=>{S5()},doctor:async e=>{await T7(e)},"bar-pane":async e=>{t.exit(await B7(e))},...Object.fromEntries(j4.map(e=>[e,async n=>{await p5(e,n),t.exit(0)}]))};async function K7(){try{let e=t.argv[2],n=e!==void 0&&!e.startsWith(`-`)?e:null;if(n!==null&&!Object.hasOwn(G7,n)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(n)} — see --help`),t.exit(2)),U7(qj.help)&&(W7(),t.exit(0)),U7(qj.version)&&(console.log(`cc-candybar ${Ze}`),t.exit(0)),n!==null){await G7[n](t.argv.slice(3));return}t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
515
+ `),t.exit(2));let n=t.cwd(),r=await k7(Z1(C7),z0(),y7,t.env,n,A7,e[0]);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}function M7(e){return!e.ok&&e.code!==`RENDER_FAILED`}function N7(e,t,n,r,i){let a=null,o=e=>{a===null&&(a=e,s.destroy(),i(e))},s=ue.createConnection({path:e}),c={v:3,kind:`subscribe`,sessionId:t,lane:n};return s.once(`connect`,()=>s.write(Qt(c))),s.on(`data`,en(e=>{let t=e;M7(t)?o({kind:`refused`,resp:t}):r(t)},e=>o({kind:`failed`,error:e}))),s.on(`error`,e=>o({kind:`failed`,error:e})),s.on(`close`,()=>o({kind:`closed-there`})),{close:()=>o({kind:`closed-here`})}}function P7(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(2e3,e*2)}}function F7(e){switch(e.kind){case`failed`:return{kind:`reconnect`,reason:`stream failed (${e.error.message})`,kick:!0};case`closed-there`:return{kind:`reconnect`,reason:`daemon closed the stream`,kick:!1};case`refused`:return e.resp.code===`SWITCHED_OFF`?{kind:`off`,resp:e.resp}:e.resp.code===`TIMEOUT`?{kind:`reconnect`,reason:`the daemon was too busy to open the stream (${e.resp.error})`,kick:!1}:e.resp.code===`BAD_REQUEST`?{kind:`reconnect`,reason:`the daemon does not take subscribe (${e.resp.error}); it restarts on the new build`,kick:!1}:e.resp.code===`VERSION_MISMATCH`&&e.resp.daemonV!==void 0&&e.resp.daemonV<3?{kind:`reconnect`,reason:`the daemon is older than this client (${e.resp.error})`,kick:!0}:{kind:`exit`,reason:`the daemon refused the stream: ${e.resp.code}: ${e.resp.error}`}}}function I7(e,t,n,r){let i=null,a=null,o=!1,s=250,c=(e,t)=>{a=setTimeout(()=>{a=null,((t?r.beforeReconnect?.():void 0)??Promise.resolve()).then(()=>{o||l()})},e)},l=()=>{i=N7(e,t,n,e=>{s=P7(s,e.ok?`frame-ok`:`frame-failed`),r.frame(e)},e=>{if(e.kind===`closed-here`||o)return;let t=F7(e);switch(t.kind){case`exit`:r.exit(t.reason);return;case`off`:r.off(t.resp),c(5e3,!1);return;case`reconnect`:{r.fault(t.reason,s),t.kick&&_r();let e=s;s=P7(s,`fault`),c(e,!0);return}}})};return l(),{close:()=>{o=!0,a!==null&&clearTimeout(a),i?.close()}}}function L7(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function R7(e,n){let{values:r,tokens:i}=ce({args:e.slice(3),options:{config:{type:`string`},lane:{type:`string`}},strict:!0,tokens:!0}),a=[e[1],...i.flatMap(e=>e.kind===`option`&&e.name===`config`?[e.rawName,e.value]:[])],o=t.cwd(),s=e=>{t.stderr.write(`cc-candybar frames: ${e}\n`)},c=Hv(r.lane);c===null&&(s(`--lane needs one of ${Fv.join(`, `)}`),t.exit(2)),t.stdout.on(`error`,()=>t.exit(0));let l=W4(t.stdout),u=null,d=null,f=null,p={kind:`none`},m=(e,t)=>{L7(p,e)&&t(),p=e},h=async e=>{let r=await hn(e,a,o,{...i7(t.env,o,t.stderr),client:zt(`frames`,n)});r.kind!==`ok`&&(s(un(r)),r.kind===`transient`&&_r())},g=e=>{f?.close(),f=I7(St(),e,c,{frame:e=>m({kind:`frame`},()=>l(`${JSON.stringify(e)}\n`)),off:e=>m({kind:`off`},()=>l(`${JSON.stringify(e)}\n`)),fault:(e,t)=>m({kind:`fault`,reason:e},()=>s(`${e}; reconnecting in ${t}ms`)),exit:e=>{s(e),t.exit(1)},beforeReconnect:()=>d===null?Promise.resolve():h(d)})};for await(let e of Se({input:t.stdin})){if(e.trim()===``)continue;let t;try{t=JSON.parse(e)}catch(e){s(`stdin line is not JSON: ${e.message}`);continue}if(typeof t.session_id!=`string`||t.session_id===``){s(`stdin line carries no session_id`);continue}d=t,await h(t),t.session_id!==u&&(u=t.session_id,g(u))}t.exit(0)}function z7(e){let t=e.replace(/\n+$/,``).split(`
516
+ `);return{bytes:t.map((e,t)=>`\x1b[${t+1}H${e}`).join(``)+`\x1B[J`,rows:t.length}}const B7=5e3,V7=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function H7(e,t,n,r){let i=e.split(`
517
+ `).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?J4(e,q4(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function U7(e,t){let[n,r]=await Promise.all([IK(e,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${t}},#{==:#{pane_id},${e.pane}}}`,`-F`,G4]),IK(e,`bar-pane.tmux`,[`list-clients`,`-F`,K4])]);return n.kind===`ok`?r.kind===`ok`?{kind:`ok`,placement:H7(n.stdout,r.stdout,t,e.pane)}:r:n}function W7(){let e=Date.now();return t=>{if(t.kind===`ok`)e=Date.now();else if(Date.now()-e>B7)throw Error(`tmux has not answered for ${B7/1e3} s: ${t.reason}`)}}function G7(e){let{positionals:t}=(()=>{try{return ce({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${V7}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(V7);return{pane:n}}async function K7(e){try{return await q7(e),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function q7(e){let{pane:n}=G7(e),r=pM(t.env);if(r===null)throw Error(`cc-candybar bar-pane runs in a tmux pane`);if(!t.stdout.isTTY)throw Error(`cc-candybar bar-pane draws on its pane's terminal`);let i=await U7(r,n);if(i.kind!==`ok`)throw Error(i.reason);let a=i.placement;if(a.kind===`gone`)throw Error(`no pane ${n} on this tmux server (${r.socket})`);t.stdout.write(`\x1B[?25l\x1B[?7l`),t.on(`exit`,()=>t.stdout.write(`\x1B[?25h\x1B[?7h`));for(let[e,n]of[[`SIGINT`,130],[`SIGTERM`,143],[`SIGHUP`,129]])t.once(e,()=>t.exit(n));let o=e=>{t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),t.exit(1)},s=null,c=`waiting for pane ${n}'s bar`,l=()=>s?.said.latest??c,u=``,d=W7(),f=async()=>{if(a.kind!==`shown`)return;let e=z7(l());e.rows!==t.stdout.rows&&!a.zoomed&&d(await IK(r,`bar-pane.tmux`,[`resize-pane`,`-t`,r.pane,`-y`,String(e.rows)])),e.bytes!==u&&t.stdout.write(e.bytes),u=e.bytes},p=null,m=!1,h=()=>{m=!0,p??=(async()=>{try{for(;m;)m=!1,await f()}finally{p=null}})(),p.catch(o)};t.stdout.on(`resize`,()=>{u=``,h()});let g=e=>{if(s?.sessionId===e)return;if(s?.follower.close(),e===null){s=null;return}let t={latest:null},n=e=>{t.latest=e,h()};s={sessionId:e,said:t,follower:I7(St(),e,`pane`,{frame:e=>n(JU(mn(e)).output),off:e=>n(e.error),fault:n,exit:e=>o(Error(e))})}},_=W7();for(;a.kind!==`gone`;){if(a.kind===`hidden`)g(null);else{let e=await gn(r.socket,n);e.kind===`ok`?(g(e.value),c=e.value===null?`waiting for pane ${n}'s statusline to render on ${St()}`:`waiting for pane ${n}'s bar`):(e.kind===`transient`&&(_r(),u=``),c=un(e))}h(),await be(500);let e=await U7(r,n);_(e),e.kind===`ok`&&(a=e.placement)}g(null),t.stderr.write(`cc-candybar bar-pane: pane ${n} closed\n`)}const J7=i(import.meta.url),Y7=e=>e.some(e=>t.argv.includes(e));function X7(){console.log(uM);let e=Do(J7),t=p.existsSync(e)?``:" (nothing is there yet: run `cc-candybar install` first — in a checkout, `pnpm build`)\n";console.log(`Starting Claude Code on ${Pv.statusline.label} yourself (a Bun-compiled Claude Code):\n ${He(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const Z7={install:async e=>{await Uo(e,J7),t.exit(0)},"install-url-handler":async()=>{Ro(J7),t.exit(0)},"url-handle":async e=>{await Bo(e[0])},daemon:async()=>{y8()},"daemon-stats":async e=>{await _0(e),t.exit(0)},frames:async()=>{await R7(t.argv,J7)},check:async e=>{await U5(e)},lint:async e=>{await U5(e)},plugin:async e=>{t.exit(t7(e))},schema:async()=>{O5()},doctor:async e=>{await j7(e)},"bar-pane":async e=>{t.exit(await K7(e))},...Object.fromEntries(N4.map(e=>[e,async n=>{await y5(e,n),t.exit(0)}]))};async function Q7(){try{let e=t.argv[2],n=e!==void 0&&!e.startsWith(`-`)?e:null;if(n!==null&&!Object.hasOwn(Z7,n)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(n)} — see --help`),t.exit(2)),Y7(Jj.help)&&(X7(),t.exit(0)),Y7(Jj.version)&&(console.log(`cc-candybar ${Ze}`),t.exit(0)),n!==null){await Z7[n](t.argv.slice(3));return}t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
518
518
 
519
519
  cc-candybar is designed to be used as a Claude Code statusLine command.
520
520
  It reads hook data from stdin and outputs formatted statusline.
@@ -530,4 +530,4 @@ Add to ~/.claude/settings.json:
530
530
  Run with --help for more options.
531
531
 
532
532
  To test output manually:
533
- echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),E(`Working directory: ${t.cwd()}`),E(`Process args:`,t.argv);let r=await o(t.stdin);E(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),W7(),t.exit(1));let i=KU(await hn(r,t.argv.slice(1),t.cwd(),{...Q5(t.env,t.cwd(),t.stderr),client:zt(`node`,H7)}));i.debug!==null&&E(i.debug),i.kick&&_r(),t.stdout.write(i.output),t.exit(0)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error generating statusline:`,n),t.exit(1)}}K7();export{};
533
+ echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),E(`Working directory: ${t.cwd()}`),E(`Process args:`,t.argv);let r=await o(t.stdin);E(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),X7(),t.exit(1));let i=JU(await hn(r,t.argv.slice(1),t.cwd(),{...i7(t.env,t.cwd(),t.stderr),client:zt(`node`,J7)}));i.debug!==null&&E(i.debug),i.kick&&_r(),t.stdout.write(i.output),t.exit(0)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error generating statusline:`,n),t.exit(1)}}Q7();export{};