@promptctl/cc-candybar 1.136.0 → 1.136.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +69 -69
  2. package/package.json +5 -5
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{json as n}from"node:stream/consumers";import r,{createReadStream as i,existsSync as a,realpathSync as o,statSync as s,watch as c}from"node:fs";import l,{basename as u,dirname as d,isAbsolute as f,join as p,sep as m}from"node:path";import h,{homedir as g}from"node:os";import{spawn as _,spawnSync as v}from"node:child_process";import{inspect as y,parseArgs as b,types as x}from"node:util";import S from"node:net";import C from"node:v8";import{URL as ee,URLSearchParams as te,fileURLToPath as ne,pathToFileURL as re}from"node:url";import ie,{createHash as ae,randomUUID as w}from"node:crypto";import{open as T,readFile as oe,readdir as E,stat as se}from"node:fs/promises";import{clearInterval as ce,setInterval as le}from"node:timers";import{get as ue}from"node:https";import{setTimeout as de}from"node:timers/promises";import{createInterface as fe}from"node:readline";var pe=Object.create,me=Object.defineProperty,he=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyNames,_e=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty,ye=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),be=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=ge(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ve.call(e,s)&&s!==n&&me(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=he(t,s))||r.enumerable});return e},xe=(e,t,n)=>(n=e==null?{}:pe(_e(e)),be(t||!e||!e.__esModule?me(n,`default`,{value:e,enumerable:!0}):n,e));function D(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}function Se(e,t){return x.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!a(t)?`working directory does not exist: ${t}`:e.message:String(e)}const Ce={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},we=new Map;function Te(e){let t=Ce[e];if(t===void 0)return{allowed:!0};let n=we.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 Ee(e){we.set(e,Date.now())}function De(e){return e.env??process.env}function Oe(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 ke=null;function Ae(e){ke=e}function je(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function Me(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=Te(e.category);if(!t.allowed)return Oe(e.category,t.minIntervalMs,t.sinceLastMs);Ee(e.category);let n=Date.now();return ke?.onStart(e.category),new Promise(t=>{let r;try{r=_(e.bin,e.args??[],{cwd:e.cwd,env:De(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ke?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Se(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),ke?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{je(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:Se(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 Ne(e){let t=Te(e.category);if(!t.allowed)return Oe(e.category,t.minIntervalMs,t.sinceLastMs);Ee(e.category);let n=Date.now();ke?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=v(e.bin,e.args??[],{cwd:e.cwd,env:De(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ke?.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:Se(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 ke?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Se(t,e.cwd)}}}function Pe(e){let t=Te(e.category);if(!t.allowed)return Oe(e.category,t.minIntervalMs,t.sinceLastMs);Ee(e.category);let n=Date.now();ke?.onStart(e.category);let r=Fe(e);return ke?.onEnd(e.category,Date.now()-n),r}function Fe(e){let t;try{t=_(e.bin,e.args??[],{cwd:e.cwd,env:De(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Se(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 Ie(e,t,n){let i=`${e}.tmp`,a=n??r.statSync(e,{throwIfNoEntry:!1})?.mode;try{r.writeFileSync(i,t,a===void 0?{}:{mode:a}),r.renameSync(i,e)}catch(e){throw r.rmSync(i,{force:!0}),e}}function Le(e,t){let n=e[t];return n&&n.length>0?n:void 0}function Re(e=process.env){let t=Le(e,`XDG_STATE_HOME`)??l.join(h.homedir(),`.local`,`state`);return l.join(t,`cc-candybar`)}function ze(){let e=Le(process.env,`XDG_CACHE_HOME`)??l.join(h.homedir(),`.cache`);return l.join(e,`cc-candybar`)}function Be(){return Re()}function Ve(){return process.env.CC_CANDYBAR_SOCKET||He()}function He(){let e=h.userInfo().uid;return l.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function Ue(e){r.mkdirSync(e,{recursive:!0,mode:448});let t=r.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=h.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 We(e){Ue(l.dirname(e));for(let t of[e,Ge(e)])try{if(r.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Ge(e){return`${e}.lease`}function Ke(){return Ge(Ve())}function qe(){return l.join(Re(),`session-state.json`)}function Je(){return l.join(Re(),`settings-history.json`)}function Ye(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=h.userInfo().uid;return l.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function Xe(){return l.join(Re(),`spawn.lock`)}function Ze(){return l.join(Re(),`spawn.cooldown`)}function Qe(){return l.join(Re(),`spawn.backoff`)}function $e(){return l.join(Re(),`diagnostics`)}function et(e=process.env){return l.join(Re(e),`daemon.log`)}const tt=[`MEMENTO_CONFIG_HOME`,`XDG_CONFIG_HOME`];function nt(e,t){return Object.fromEntries(tt.flatMap(n=>{let r=e[n]??``;return r===``?[]:[[n,l.resolve(t,r)]]}))}const rt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function it(e){return Object.fromEntries(rt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const at=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,mementoEnv:!0,terminalEnv:!0});function ot(e){let t=pt(e.termCols),n=pt(e.termRows),r=mt(e.ssh),i=ft(e.tmux),a=dt(e.configEnv),o=dt(e.claudeConfigDir),s=lt(e.mementoEnv),c=ut(e.terminalEnv);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&&{mementoEnv:s},...c!==void 0&&{terminalEnv:c}}}function st(e,t){return at.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function ct(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).`}function lt(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=tt.filter(e=>t[e]!==void 0);return n.every(e=>dt(t[e])!==void 0)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function ut(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=rt.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 dt(e){return typeof e==`string`&&l.isAbsolute(e)?e:void 0}function ft(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 O=1e4;function pt(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>O?O:t}function mt(e){return typeof e==`boolean`?e:void 0}function ht(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var gt=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function k(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function _t(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 gt(`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 gt(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function vt(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),c=_t(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(k(t))})}async function yt(e,t,n){let r=null;try{r=await wt(Ve(),t.connectMs);let i=await vt(r,{v:3,...e},t.budgetMs);return St(e.kind,i,n)}catch(e){return Ct(e)}finally{r&&r.destroy()}}function bt(e,t){return typeof e==`string`?e:t}function xt(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function St(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=bt(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:xt(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};default:return{kind:`permanent`,cause:`malformed_response`,message:`unknown error code: ${String(r.code)}`}}}function Ct(e){if(e instanceof gt||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 wt(e,t){return new Promise((n,r)=>{let i=S.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 Tt(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`malformed_response`:return`daemon error (${e.cause}): ${e.message}`}}const Et=`1.136.0`,Dt={connectMs:50,budgetMs:150},Ot={connectMs:50,budgetMs:200};function kt(e){let t=e.output;return typeof t==`string`?t:void 0}function At(e,t,n,r){return yt({kind:`render`,hookData:e,args:t,cwd:n,...r},Dt,kt)}function jt(e,t){return yt({kind:`click`,verb:e,value:t,clientVersion:Et},Ot,kt)}let Mt=null;function Nt(e){if(Mt!==null)return Mt;r.mkdirSync(l.dirname(e),{recursive:!0});try{Mt=r.statSync(e).size}catch{Mt=0}return Mt}function Pt(e){for(let t=2;t>=1;t--){let n=`${e}.${t}`,i=`${e}.${t+1}`;try{r.renameSync(n,i)}catch{}}try{r.renameSync(e,`${e}.1`)}catch{}Mt=0}const Ft=(e,t)=>D(t);function A(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=et(),t=Nt(e);r.appendFileSync(e,n),Mt=t+Buffer.byteLength(n,`utf8`),Mt>=5242880&&Pt(e)}catch(e){Mt=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}function It(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(`
2
+ import{createRequire as e}from"node:module";import t from"node:process";import{json as n}from"node:stream/consumers";import r,{createReadStream as i,existsSync as a,realpathSync as o,statSync as s,watch as c}from"node:fs";import l,{basename as u,dirname as d,isAbsolute as f,join as p,sep as m}from"node:path";import h,{homedir as g}from"node:os";import{spawn as _,spawnSync as v}from"node:child_process";import{inspect as y,parseArgs as b,types as x}from"node:util";import S from"node:net";import C from"node:v8";import{URL as ee,URLSearchParams as te,fileURLToPath as ne,pathToFileURL as re}from"node:url";import ie,{createHash as ae,randomUUID as w}from"node:crypto";import{open as T,readFile as oe,readdir as E,stat as se}from"node:fs/promises";import{clearInterval as ce,setInterval as le}from"node:timers";import{get as ue}from"node:https";import{setTimeout as de}from"node:timers/promises";import{createInterface as fe}from"node:readline";var pe=Object.create,me=Object.defineProperty,he=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyNames,_e=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty,ye=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),be=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=ge(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ve.call(e,s)&&s!==n&&me(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=he(t,s))||r.enumerable});return e},xe=(e,t,n)=>(n=e==null?{}:pe(_e(e)),be(t||!e||!e.__esModule?me(n,`default`,{value:e,enumerable:!0}):n,e));function D(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}function Se(e,t){return x.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!a(t)?`working directory does not exist: ${t}`:e.message:String(e)}const Ce={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},we=new Map;function Te(e){let t=Ce[e];if(t===void 0)return{allowed:!0};let n=we.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 Ee(e){we.set(e,Date.now())}function De(e){return e.env??process.env}function Oe(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 ke=null;function Ae(e){ke=e}function je(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function Me(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=Te(e.category);if(!t.allowed)return Oe(e.category,t.minIntervalMs,t.sinceLastMs);Ee(e.category);let n=Date.now();return ke?.onStart(e.category),new Promise(t=>{let r;try{r=_(e.bin,e.args??[],{cwd:e.cwd,env:De(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ke?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Se(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),ke?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{je(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:Se(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 Ne(e){let t=Te(e.category);if(!t.allowed)return Oe(e.category,t.minIntervalMs,t.sinceLastMs);Ee(e.category);let n=Date.now();ke?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=v(e.bin,e.args??[],{cwd:e.cwd,env:De(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ke?.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:Se(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 ke?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Se(t,e.cwd)}}}function Pe(e){let t=Te(e.category);if(!t.allowed)return Oe(e.category,t.minIntervalMs,t.sinceLastMs);Ee(e.category);let n=Date.now();ke?.onStart(e.category);let r=Fe(e);return ke?.onEnd(e.category,Date.now()-n),r}function Fe(e){let t;try{t=_(e.bin,e.args??[],{cwd:e.cwd,env:De(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Se(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 Ie(e,t,n){let i=`${e}.tmp`,a=n??r.statSync(e,{throwIfNoEntry:!1})?.mode;try{r.writeFileSync(i,t,a===void 0?{}:{mode:a}),r.renameSync(i,e)}catch(e){throw r.rmSync(i,{force:!0}),e}}function Le(e,t){let n=e[t];return n&&n.length>0?n:void 0}function Re(e=process.env){let t=Le(e,`XDG_STATE_HOME`)??l.join(h.homedir(),`.local`,`state`);return l.join(t,`cc-candybar`)}function ze(){let e=Le(process.env,`XDG_CACHE_HOME`)??l.join(h.homedir(),`.cache`);return l.join(e,`cc-candybar`)}function Be(){return Re()}function Ve(){return process.env.CC_CANDYBAR_SOCKET||He()}function He(){let e=h.userInfo().uid;return l.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function Ue(e){r.mkdirSync(e,{recursive:!0,mode:448});let t=r.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=h.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 We(e){Ue(l.dirname(e));for(let t of[e,Ge(e)])try{if(r.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Ge(e){return`${e}.lease`}function Ke(){return Ge(Ve())}function qe(){return l.join(Re(),`session-state.json`)}function Je(){return l.join(Re(),`settings-history.json`)}function Ye(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=h.userInfo().uid;return l.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function Xe(){return l.join(Re(),`spawn.lock`)}function Ze(){return l.join(Re(),`spawn.cooldown`)}function Qe(){return l.join(Re(),`spawn.backoff`)}function $e(){return l.join(Re(),`diagnostics`)}function et(e=process.env){return l.join(Re(e),`daemon.log`)}const tt=[`MEMENTO_CONFIG_HOME`,`XDG_CONFIG_HOME`];function nt(e,t){return Object.fromEntries(tt.flatMap(n=>{let r=e[n]??``;return r===``?[]:[[n,l.resolve(t,r)]]}))}const rt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function it(e){return Object.fromEntries(rt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const at=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,mementoEnv:!0,terminalEnv:!0});function ot(e){let t=pt(e.termCols),n=pt(e.termRows),r=mt(e.ssh),i=ft(e.tmux),a=dt(e.configEnv),o=dt(e.claudeConfigDir),s=lt(e.mementoEnv),c=ut(e.terminalEnv);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&&{mementoEnv:s},...c!==void 0&&{terminalEnv:c}}}function st(e,t){return at.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function ct(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).`}function lt(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=tt.filter(e=>t[e]!==void 0);return n.every(e=>dt(t[e])!==void 0)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function ut(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=rt.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 dt(e){return typeof e==`string`&&l.isAbsolute(e)?e:void 0}function ft(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 O=1e4;function pt(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>O?O:t}function mt(e){return typeof e==`boolean`?e:void 0}function ht(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var gt=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function k(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function _t(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 gt(`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 gt(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function vt(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),c=_t(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(k(t))})}async function yt(e,t,n){let r=null;try{r=await wt(Ve(),t.connectMs);let i=await vt(r,{v:3,...e},t.budgetMs);return St(e.kind,i,n)}catch(e){return Ct(e)}finally{r&&r.destroy()}}function bt(e,t){return typeof e==`string`?e:t}function xt(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function St(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=bt(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:xt(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};default:return{kind:`permanent`,cause:`malformed_response`,message:`unknown error code: ${String(r.code)}`}}}function Ct(e){if(e instanceof gt||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 wt(e,t){return new Promise((n,r)=>{let i=S.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 Tt(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`malformed_response`:return`daemon error (${e.cause}): ${e.message}`}}const Et=`1.136.1`,Dt={connectMs:50,budgetMs:150},Ot={connectMs:50,budgetMs:200};function kt(e){let t=e.output;return typeof t==`string`?t:void 0}function At(e,t,n,r){return yt({kind:`render`,hookData:e,args:t,cwd:n,...r},Dt,kt)}function jt(e,t){return yt({kind:`click`,verb:e,value:t,clientVersion:Et},Ot,kt)}let Mt=null;function Nt(e){if(Mt!==null)return Mt;r.mkdirSync(l.dirname(e),{recursive:!0});try{Mt=r.statSync(e).size}catch{Mt=0}return Mt}function Pt(e){for(let t=2;t>=1;t--){let n=`${e}.${t}`,i=`${e}.${t+1}`;try{r.renameSync(n,i)}catch{}}try{r.renameSync(e,`${e}.1`)}catch{}Mt=0}const Ft=(e,t)=>D(t);function A(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=et(),t=Nt(e);r.appendFileSync(e,n),Mt=t+Buffer.byteLength(n,`utf8`),Mt>=5242880&&Pt(e)}catch(e){Mt=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}function It(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(`
3
3
  `)}function Lt(e,t){return e===`darwin`?[Rt(`footprint`,[`-p`,String(t)]),Rt(`vmmap`,[`--summary`,String(t)])]:e===`linux`?[zt(`/proc/self/smaps_rollup`),zt(`/proc/self/status`)]:[]}function Rt(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=Ne({bin:e,args:[...t],timeoutMs:5e3,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}`}${Bt(n.stderr)}`}}}}function zt(e){return{name:e,read:()=>{try{let t=r.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 Bt(e){let t=e.split(`
4
4
  `).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const Vt=`CC_CANDYBAR_RSS_LIMIT_MB`;function Ht(e){let t=e[Vt];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${Vt} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function Ut(e){return Ht(e)*2}const j=1024*1024;function Wt(e){return Ht(e)*j}const Gt={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function Kt(e,t,n){let{prefix:r,suffix:i}=Gt[t];return l.join(e,`${r}${n}${i}`)}function qt(e){for(let t of Object.keys(Gt)){let{prefix:n,suffix:r}=Gt[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function Jt(e){let t=e.rssLimitBytes??512*j,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let{rss:i,heapTotal:a}=e.memoryBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t} (v8 heap ${a}); recording memory then shutting down`);let o=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return Yt(e.log,`memory report`,()=>{let t=Kt(e.snapshotDir,`memoryReport`,o);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),Yt(e.log,`heap snapshot`,()=>{let t=Kt(e.snapshotDir,`heapSnapshot`,o);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),Yt(e.log,`artifact rotation`,()=>{Xt(e.listArtifacts(),n,e.removeFile)}),e.shutdown(0),!0}function a(){let{rss:n,heapTotal:r}=e.memoryBytes();return n>t*.75?`rss ${n} approaching limit ${t} (v8 heap ${r})`:null}function o(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:o}}function Yt(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function M(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=qt(t);if(n===null)return t;let{prefix:r,suffix:i}=Gt[n];return t.slice(r.length,t.length-i.length)}function Xt(e,t,n){let r=new Map;for(let t of e){let e=M(t),n=r.get(e);n===void 0?r.set(e,[t]):n.push(t)}let i=[...r.keys()].sort((e,t)=>t.localeCompare(e));for(let e of i.slice(t))for(let t of r.get(e)??[])try{n(t)}catch{}}function Zt(e,t,n={}){let i=Be();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:A,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},captureMemoryReport:()=>It(Lt(process.platform,process.pid)),writeMemoryReport:(e,t)=>r.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>C.writeHeapSnapshot(e),listArtifacts:()=>{try{return r.readdirSync(i).filter(e=>qt(e)!==null).map(e=>l.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function Qt(e={}){if(hn()!==null)return;let n=e.spawn??gn,r=fn();if(r.kind===`contended`){let e=en();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),$t(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),$t(n);return}try{$t(n)}finally{mn()}}function $t(e){cn()&&tn(e)}function en(){try{let e=r.statSync(Xe());return Date.now()-e.mtimeMs}catch{return null}}function tn(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
5
5
  `)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function nn(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function rn(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function an(e){try{let t=r.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function on(e,n){try{r.mkdirSync(l.dirname(e),{recursive:!0}),r.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function sn(){try{r.unlinkSync(Qe())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function cn(){let e=Ze(),n=Qe(),r=an(n),i=nn(ln(e),rn(r));return i.kind===`deny`?!1:(i.kind===`allow-future-garbage`&&t.stderr.write(`cc-candybar: spawn.cooldown mtime is ${i.futureMs}ms in the future — ignoring and spawning\n`),un(e),on(n,Math.min(r+1,5)),!0)}function ln(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function un(e){try{r.mkdirSync(l.dirname(e),{recursive:!0}),r.writeFileSync(e,`${t.pid} ${Date.now()}\n`,{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}let dn=null;function fn(){let e=Xe();for(let n=0;n<2;n++){try{let n=r.openSync(e,`wx`,384);try{r.writeSync(n,JSON.stringify({pid:t.pid,ts:Date.now()}))}catch{}return dn={fd:n,path:e},{kind:`held`}}catch(t){let n=t.code;if(n!==`EEXIST`)return{kind:`error`,reason:`openSync(${e}): ${n??t.message}`}}if(!pn(e))return{kind:`contended`};try{r.unlinkSync(e)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function pn(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function mn(){if(!dn)return;let{fd:e,path:t}=dn;dn=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function hn(){try{return r.mkdirSync(Be(),{recursive:!0}),null}catch(e){return`mkdir ${Be()}: ${e.message}`}}function gn(){let e=t.execPath,n=t.argv[1];return n?Pe({bin:e,args:[`--max-old-space-size=${Ut(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const _n=`cc-candybar`,vn=`dispatch`,yn=`set-state`,bn=`step-state`,xn=`copy`,Sn=`open-vscode`,Cn=`toolbar-toggle`,wn=`show-config-error`,Tn=`show-config-warning`,N=`set-config`,En=`step-config`,Dn=`save`,On=`save-preset`,kn=`save-theme-default`,An=`delete-preset`,jn=`reset-config`,Mn=`apply-layout-op`,Nn=`undo`,Pn=`redo`,Fn=`back`,In=`rewind`,Ln=`apply-update`,Rn=`doctor-run`,zn=`doctor-fix`,Bn=`doctor-mark`,Vn=`doctor-probe`,Hn=`ceiling`,Un=`slash`;function Wn(e){return e.map(encodeURIComponent).join(`/`)}function Gn(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function Kn(e){return`${_n}://${vn}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${Wn(e.args)}`)}`).join(`&`)}`}function qn(e){return new te(e).getAll(`e`).map(Zn)}const Jn=new Set([yn,jn]);function Yn(e){return e.reduce((e,t)=>{let n=e.at(-1),r=n&&Xn(n,t);return r?[...e.slice(0,-1),r]:[...e,t]},[])}function Xn(e,t){if(e.verb!==t.verb||!Jn.has(e.verb))return;let[n,r]=[Zn(e.value),Zn(t.value)];return n.verb===r.verb?{verb:e.verb,value:`${n.verb}/${n.value}/${r.value}`}:void 0}function Zn(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const Qn=`closed`,$n=`🍫`;function er(e,t,n){if(t===0)return`${e} needs a display (the clickable text)`;if(t!==1&&t!==n)return`${e} cycles ${n} members; bind one display per member (${n}) or one static display, got ${t}`}function tr(e,t,n,r){let i=er(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function nr(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function rr(e,t,n,r,i){return{kind:`segment`,name:e,opens:{ref:t,body:n,placement:r},...i!==void 0&&{when:i}}}function ir(e,...t){return`{{ and ${[e,...t].map(ar).join(` `)} }}`}function ar(e){return`(eq .${e.variable} "${nr(e.member)}")`}function or(e,t,n){return`{{ ${sr(e,cr(t),cr(n))} }}`}function sr(e,t,n){return`action "${e}" ${t} ${n}`}function cr(e){return`"${nr(e)}"`}function lr(e,t){return{kind:`state`,key:e,default:t}}function ur(e,t){return{set:e,cycle:[Qn,t]}}const dr=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function fr(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function pr(e){return dr.test(e)?e:fr(e)}var mr=ye(((e,t)=>{t.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/,t.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/,t.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/})),hr=ye(((e,t)=>{let n=mr();t.exports={isSpaceSeparator(e){return typeof e==`string`&&n.Space_Separator.test(e)},isIdStartChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e===`$`||e===`_`||n.ID_Start.test(e))},isIdContinueChar(e){return typeof e==`string`&&(e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`||e>=`0`&&e<=`9`||e===`$`||e===`_`||e===`‌`||e===`‍`||n.ID_Continue.test(e))},isDigit(e){return typeof e==`string`&&/[0-9]/.test(e)},isHexDigit(e){return typeof e==`string`&&/[0-9A-Fa-f]/.test(e)}}})),gr=ye(((e,t)=>{let n=hr(),r,i,a,o,s,c,l,u,d;t.exports=function(e,t){r=String(e),i=`start`,a=[],o=0,s=1,c=0,l=void 0,u=void 0,d=void 0;do l=v(),re[i]();while(l.type!==`eof`);return typeof t==`function`?f({"":d},``,t):d};function f(e,t,n){let r=e[t];if(typeof r==`object`&&r)if(Array.isArray(r))for(let e=0;e<r.length;e++){let t=String(e),i=f(r,t,n);i===void 0?delete r[t]:Object.defineProperty(r,t,{value:i,writable:!0,enumerable:!0,configurable:!0})}else for(let e in r){let t=f(r,e,n);t===void 0?delete r[e]:Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}return n.call(e,t,r)}let p,m,h,g,_;function v(){for(p=`default`,m=``,h=!1,g=1;;){_=y();let e=x[p]();if(e)return e}}function y(){if(r[o])return String.fromCodePoint(r.codePointAt(o))}function b(){let e=y();return e===`
@@ -53,31 +53,31 @@ import{createRequire as e}from"node:module";import t from"node:process";import{j
53
53
  `))throw Error(`renderStripCells: rich-js strip output did not end its last line`);return s.slice(0,-1)}function kh(e){return Math.min(20,e??20)}const Ah={heading:`ERROR`,glyph:`⚠`,colors:qf},jh={heading:`WARNING`,glyph:`⚠`,colors:Jf},Mh={heading:`UPDATE`,glyph:`⬆`,colors:Jf};function Nh(e,t){return{text:Hf(e),link:t}}function Ph(e,t,n){let[r,...i]=[Fh(e,Ah,wn),t,Fh(n,jh,Tn)].flat();return r===void 0?null:{channels:[r,...i]}}function Fh(e,t,n){let r=Kn([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>Nh(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function Ih(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
54
54
  `)}function Lh(e,t,n,r){if(t===null)return e;let i=Rh(r),a=t.channels.flatMap(e=>zh(e,i)),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[Bh(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
55
55
  `);return e?`${l}\n${e}`:l}function Rh(e){return{endcaps:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function zh(e,t){let n=new H({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=_o(Math.max(2,t.width-1)),i=(e,t)=>new G(`${e} `,{style:t,end:``,overflow:`ignore`});return e.lines.flatMap((a,o)=>Oh([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=>So(e,r)).map(e=>i(e,t))})],t).split(`
56
- `))}function Bh(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new H({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new G(e,{style:t,end:``,overflow:`ignore`}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(re(a.path).href)):c(`full text unavailable: ${Hf(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(Hf(o),s.withLink(re(o).href))],d=[c(`↳ `,s),...l,...u.slice(0,-1)],f=d.reduce((e,t)=>e+t.cellLength,0),p=u.slice(-1).map(e=>e.truncate(Math.max(1,r.width-f),{mode:`middle`})),m=G.fromFragments([...d,...p]).truncate(r.width);return m.overflow=`ignore`,Oh([m],r)}const Vh=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Hh(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function Uh(e,t){return r.readdirSync(t).filter(Vh).sort().flatMap(n=>{let i=l.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?Uh(e,i):[[l.relative(e,i).split(l.sep).join(`/`),Hh(i,a)]]})}function Wh(e){let t=ie.createHash(`sha256`);for(let[n,r]of Uh(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const Gh=e=>e.slice(0,7);function Kh(e){return l.dirname(l.dirname(e))}function qh(){return{version:Et,digest:`e02e14389d1f5356af0bf8cf81cac05bb3f5d0e75eac7e04d8dac183b6d16a88`}}function Jh(e){let t=JSON.parse(r.readFileSync(l.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${l.join(e,`package.json`)} has no version string`);return n}function Yh(e,t){try{let n=Kh(ne(e)),i=l.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=Wh(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:Jh(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var K=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};const Xh=new Map;function Zh(e){let t=$h(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 Qh(e,t){return e===`bar`?t:Zh(e)}function $h(e){let t=Xh.get(e);if(t!==void 0)return t;let n=jc(e);return n===null?null:(Xh.set(e,n),n)}function eg(e,t){return tg(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>Uc(e,t))}const tg=Yf();function ng(e){let t=$h(e);return t===null?null:{kind:`decided`,name:e,value:t}}function rg(e,t,n){let r=ng(e);return r===null?(n(wm(t,`palette`,`"${e}" names no installed theme${om(e)}`)),ag()):r}function ig(e,t,n){return gm(e,t,n,ag(),ng)}function ag(){return{kind:`decided`,name:sm,value:Zh(sm)}}const og=[`vertical`,`horizontal`],sg={vertical:`row`,horizontal:`cell`};function cg(e){return e.id??e.name}function lg(e){return[...fg(e)].flatMap(e=>e.kind===`segment`?[cg(e)]:[])}function ug(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function dg(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*fg(e){yield e;for(let t of gg(e))yield*fg(t)}const pg=(e,t)=>`${e}.children[${t}]`,mg=e=>`${e}.opens.body`;function*hg(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*hg(r,pg(t,n));else e.opens!==void 0&&(yield*hg(e.opens.body,mg(t)))}function gg(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}const _g=[`shade`,`variation`,`style`];function vg(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const yg=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function bg(e){return e.kind===`file`||e.kind===`shell`}const xg=[`branch`,`sha`,`dirty`,`ahead`,`behind`,`stash`];function*Sg(e){for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&(yield[t,n]);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&(yield[`${t}.${e}`,r])}const Cg=`theme`,wg=`effect`,Tg=[Cg,wg];function Eg(e){return{...e.settings,[Cg]:{label:Cg,domain:`theme`,default:e.palette??`bar`},[wg]:{label:wg,domain:Em,default:`bar`}}}function Dg(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function Og(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=Dg(r)?.atLeast;if(i===void 0)return[];let a=t[n],o=t[i];return a>=o?[]:[{setting:n,message:`"${n}" (${a}) is below "${i}" (${o}) — ${r.label} must be at least ${e[i].label}`}]})}function kg(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&fm(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function Ag(e){return String(e)}function jg(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return Zm(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return kg(e,r)?r:void 0}function Mg(e,t,n,r){let i=e.settings?.[t]??n.default,a=e.drafts?.[t],o=a===void 0?null:r(a);return(o===null?void 0:jg(n,o))??i}function Ng(e){let{domain:t}=e;return t===`bool`?`true or false`:t===`theme`?`"bar" (the bar's own theme) or an installed theme name`:`min`in t?`an integer from ${t.min} to ${t.max}`:`one of ${t.map(e=>JSON.stringify(e)).join(`, `)}`}const Pg=[`left`,`center`,`right`],Fg=[`right`,`left`,`middle`],Ig=/^[A-Za-z_][A-Za-z0-9_]*$/;function Lg(e){return`#${e+1}`}const Rg={rows:{}};function zg(e){return`rows`in e}function Bg(e){return Object.fromEntries(e.map((e,t)=>[Lg(t),e]))}function Vg(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:Bg(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:Bg([n])}}function Hg(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function Ug(e){return zg(e)?Hg(e):e}function*Wg(e,t){if(!zg(e)){yield*hg(e,t);return}yield[Hg(e),t];for(let[n,r]of Object.entries(e.rows))yield*hg(r,`${t}.rows.${n}`)}function Gg(e,t){return zg(e)?{...t,...e,rows:{...t.rows,...e.rows}}:Vg(e)}function Kg(e){if(!zg(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const qg=`default`,Jg={};function Yg(e){return[...new Set([qg,...Object.keys(e)])]}function Xg(e,t,n){return pm(void 0,e,t,qg,n)}function Zg(e,t){let n={[qg]:Jg,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${qg}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function Qg(e,t){let n=Zg(e.presets,t).root??Rg;return{node:Hg(Gg(n,e.root)),path:Kg(n)?`presets.${t}.root`:`root`}}function $g(e,t){return{...e.globals,...Zg(e.presets,t).globals}}const e_=new Map;function t_(e,t,n){e_.set(e,{permanent:!0,resolve:t,paletteOf:n})}t_(`themes`,()=>lm(),e=>Zh(e));const n_=`placementThemes`;t_(n_,um,(e,t)=>Qh(e,t.palette)),t_(`endcaps`,()=>Am),t_(`variations`,()=>Bm),t_(`shades`,()=>Um),t_(`charsets`,()=>Fm),t_(`colorCompatibilities`,()=>Rm);function r_(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>eg(n.basePalette,e.styles[t])}],[`presets`,{members:Yg(e.presets)}]])}function i_(e){return[...new Set([...e_.keys(),...e.keys()])]}function a_(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=e_.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf};throw Error(s_(e,t))}const o_=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function s_(e,t){let n=o_.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${i_(t).join(`, `)})`}const c_=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*l_(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 u_=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,d_=RegExp(`^(?:(\\$)(?:\\.(${u_}))?|\\.(${u_})?)(?=[\\s)]|$)`);function f_(e,t,n){let r=d_.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 p_=/^(\w+)\b\s*([\s\S]*)$/;function*m_(e,t){let n=[t];for(let r of l_(e)){let e=r.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=p_.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:f_(r[1],s,t);continue}yield{code:e,dot:o},i===`if`&&n.push(o),i===`with`&&n.push(f_(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const h_=/(?<![.$])\btemplate\s+$/;function*g_(e,t,n){let r=0;for(let i of[...e.matchAll(c_)]){let a=i.index+i[0].length;h_.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:f_(e.slice(a),t,n)}),r=a}}function*__(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...m_(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...g_(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 v_=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${u_})`,`g`);function*y_({code:e,dot:t,root:n}){let r=e.replace(c_,``);for(let e of[...r.matchAll(v_)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function b_(e,t){let n=new Map;for(let r of __(e,t))for(let e of y_(r))n.has(e)||n.set(e,r.via);return n}const x_=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,S_={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*C_(e){let t=0,n=0,r=0,i=`action`;for(let a of[...e.matchAll(c_)]){let o=e.slice(t,a.index),s=x_.exec(o);if(s!==null)n=S_[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 w_(e,t){let n=new Map;for(let{code:r,via:i}of __(e,t))for(let{name:e,site:t}of C_(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}function T_(e,t){return new Set([...E_(e,t)].filter(e=>Object.hasOwn(t,e)))}function E_(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of __(e,t))for(let{name:e}of g_(r,i,a))n.add(e);return n}function D_(e,t){if(t.names.has(e))return!0;let n=`${e}.`;for(let e of t.names)if(e.startsWith(n))return!0;for(let n of t.documents)if(e.startsWith(`${n}.`))return!0;return!1}function O_(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),k_(r)&&n.add(e)};for(let[t,n]of Object.entries(e.variables))r(t,n);for(let[t,n]of Object.entries(e.segments))for(let[e,i]of Object.entries(n.vars??{}))r(`${t}.${e}`,i);return{names:t,documents:n,helpers:e.helpers}}function k_(e){return e.kind===`dropped`||(e.kind===`shell`||e.kind===`file`)&&vg(e.parse)===`json`}function A_(e){let t=l.basename(e),n=l.dirname(e);for(;;){let r=j_(n);if(r!==null)return{dir:r,name:t,leaf:n===l.dirname(e)};t=l.basename(n),n=l.dirname(n)}}function j_(e){try{return r.statSync(e).isDirectory()?r.realpathSync(e):null}catch{return null}}var M_=ye((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()===Bt}function s(e){let t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function c(e,t,n){It(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 Lt.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=Vt,n=Vt){let r=new Wt(e);return t!==Vt&&(r.onBOL=new Set([t])),n!==Vt&&(r.onBUOL=new Set([n])),r}function _(e,t){return At(e,t)}function v(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||tt(e)?e:Array.isArray(e)?sn.array(e,{name:n}):o(e)?sn.object(e,void 0,{name:n}):u(e)?sn.map(e,{name:n}):d(e)?sn.set(e,{name:n}):typeof e!=`function`||We(e)||Qe(e)?e:s(e)?Gn(e):Ln(n,e)}function y(e){return e}function b(e,t){return{t:e,i:t,o:x,u:S}}function x(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:We(n.value)?1:(It(r,t,ee(e,this,t,n,!1)),2)}function S(e,t,n,r){let i=ee(e,this,t,n);return e.l(t,i,r)}function C(e,n,r){let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>{var t;return ye(s.i?.name??a.toString(),e,(t=s.i?.autoAction)!=null&&t)};return i==`field`?function(e){var t;let n=e;return We(n)||(n=c(n)),(t=s.i)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n}:i==`method`?(We(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 ee(e,t,n,r,i=N.safeDescriptors){var a,o,s;let{value:c}=r;return(a=t.i)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:ye(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 te(e,t){return{t:e,i:t,o:ne,u:re}}function ne(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)||!Qe(e.h[t]))&&this.u(e,t,n,!1)===null?0:Qe(n.value)?1:(It(r,t,ae(e,0,0,n,!1,!1)),2)}function re(e,t,n,r){let i=ae(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function ie(e,t,n){var r;let{name:i,addInitializer:a}=n;return Qe(t)||(t=Gn(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 ae(e,t,n,r,i,a=N.safeDescriptors){let{value:o}=r;return Qe(o)||(o=Gn(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:T,u:oe}}function T(e,t,n){return this.u(e,t,n,!1)===null?0:1}function oe(e,t,n,r){return e.m(t,Ft({},this.i,{get:n.get,set:n.set}),r)}function E(e,t,n){function r(e){let n=Ft({},i.i,{get:t,context:e});return n.name||=`ObservableObject.${a.toString()}`,new yn(n)}let i=e,{name:a,addInitializer:o}=n,s;return o(function(){let e=Ct(this)[j],n=this,i=e.j.get(a);i instanceof yn&&i.derivation!==t&&e.j.delete(a),(e.O??=new Map).set(a,()=>r(n))}),function(){let e=this[j],n=e.j.get(a);if(n instanceof yn&&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 se(e,t){return{t:e,i:t,o:ce,u:le}}function ce(e,t,n){return this.u(e,t,n,!1)===null?0:1}function le(e,t,n,r){return e.S(t,n.value,this.i?.A??v,r)}function ue(e,t,n){function r(e,t){let n=Ct(e)[j];return(n.V??=new Map).set(o,()=>new _n(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[j]??r(this,t.get.call(this)))._(o)},set(e){return(this[j]??r(this,e)).M(o,e)},init(e){return r(this,e),e}}}function de(e){return{t:Jt,i:e,o:fe,u:pe}}function fe(e,t,n,r){var i,a,o;if(n.get)return dn.o(e,t,n,r);if(n.set){let i=We(n.set)?n.set:ye(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!N.safeDescriptors||e.p,set:i})===null?0:2:(It(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?Kn:Gn).o(e,t,n,r):((a=this.i)!=null&&a.autoBind?zn:Ln).o(e,t,n,r);let c=!1===this.i?.deep?nn:sn;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 pe(e,t,n,r){var i;return n.get?dn.u(e,t,n,r):n.set?e.l(t,{configurable:!N.safeDescriptors||e.p,set:ye(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?nn:sn).u(e,t,n,r))}function me(e,t){return Ft(function(n,r){if(r&&typeof r.kind==`string`)return t(e,n,r)},e)}function he(e){return e||Xt}function ge(e){return me(e,ue)}function _e(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 ve(e){return me(e,E)}function ye(e,t,n=!1,r){function i(){return be(0,n,t,r||this,arguments)}return i.isMobxAction=!0,i.toString=()=>t.toString(),hn&&(gn.value=e,It(i,`name`,gn)),i}function be(e,t,n,r,i){let a=xe(0,t);try{return n.apply(r,i)}catch(e){throw a.N=e,e}finally{D(a)}}function xe(e,t){let n=N.trackingDerivation,r=!t||!n;Pe();let i=N.allowStateChanges;r&&Oe();let a={R:r,k:n,C:i,I:N.allowStateReads,P:!1,T:0,B:mn++,D:pn};return pn=a.B,a}function D(e){pn!==e.B&&t(30),pn=e.D,e.N!==void 0&&(N.suppressReactionErrors=!0),Fe(),e.R&&ke(e.k),N.suppressReactionErrors=!1}function Se(e,t){let n=function(e){let t=N.allowStateChanges;return N.allowStateChanges=e,t}(e);try{return t()}finally{(function(e){N.allowStateChanges=e})(n)}}function Ce(e){return e instanceof xn}function we(e){switch(e.K){case 0:return!1;case-1:case 2:return!0;case 1:{let t=Oe(),n=e.L,r=n.length;for(let i=0;i<r;i++){let r=n[i];if(bn(r)){if(N.disableErrorBoundaries)r.get();else try{r.get()}catch{return ke(t),!0}if(e.K===2)return ke(t),!0}}return Ae(e),ke(t),!1}}}function Te(e,t,n){Ae(e),e.$=Array(e.U===0?100:e.L.length),e.W=0,e.U=++N.runId;let r=N.trackingDerivation,i;if(N.trackingDerivation=e,N.inBatch++,!0===N.disableErrorBoundaries)i=t.call(n);else try{i=t.call(n)}catch(e){i=new xn(e)}return N.inBatch--,N.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&&Me(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,je(t,e))}r!==0&&(e.K=r,e.q())}(e),i}function Ee(e){let t=e.L;e.L=[];let n=t.length;for(;n--;)Me(t[n],e);e.K=-1}function De(e){let t=Oe();try{return e()}finally{ke(t)}}function Oe(){let e=N.trackingDerivation;return N.trackingDerivation=null,e}function ke(e){N.trackingDerivation=e}function Ae(e){if(e.K===0)return;e.K=0;let t=e.L,n=t.length;for(;n--;)t[n].F=0}function je(e,t){(e.H??=new Set).add(t),e.F>t.K&&(e.F=t.K)}function Me(e,t){let n=e.H;n&&(n.delete(t),n.size===0&&Ne(e))}function Ne(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,N.pendingUnobservations.push(e))}function Pe(){N.inBatch++}function Fe(){--N.inBatch===0&&(ze(),!N.isRunningUnobservations&&N.pendingUnobservations.length>0&&function(){N.isRunningUnobservations=!0;try{let e=N.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 yn&&n.G())}N.pendingUnobservations=[]}finally{N.isRunningUnobservations=!1}}())}function Ie(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.L)==null||t.forEach(Ie))}function Le(e){let t=N.trackingDerivation;return t===null?((!e.H||e.H.size===0)&&N.inBatch>0&&Ne(e),!1):(t.U!==e.J&&(e.J=t.U,t.$[t.W++]=e,!e.isBeingObserved&&N.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function Re(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 ze(){N.inBatch>0||N.isRunningReactions||On(Be)}function Be(){N.isRunningReactions=!0;let e=N.pendingReactions,t=0;for(;e.length>0;){++t===Dn&&(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()}N.isRunningReactions=!1}function Ve(e){return me(e,C)}function He(e){return function(t,n){return n&&typeof n.kind==`string`?C(e?Pn:Mn,t,n):r(t)?ye(t.name||`<unnamed action>`,t,e):r(n)?ye(t,n,e):i(t)?Ve(b(e?jn:An,{name:t,autoAction:e})):void 0}}function Ue(e){return be(0,!1,e,this,void 0)}function We(e){return r(e)&&!0===e.isMobxAction}function Ge(e,t=zt){function n(){e(a)}var r;let i=t?.name??`Autorun`,a;if(t.scheduler||t.delay){let e=Ke(t),r=!1;a=new En(i,()=>{r||(r=!0,e(()=>{r=!1,a.isDisposed||a.track(n)}))},t.onError,t.requiresObservable)}else a=new En(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 Ke(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Bn}function qe(e,t,n,i){let a=typeof i==`function`?Et(t,n):Et(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 Je(e,t,n,r){let i=Ut(t);return kt(()=>{let t=Ct(e,r)[j];Ht(i).forEach(e=>{t.u(e,i[e],!n||!(e in n)||n[e])})}),e}function Ye(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(Ye)),t}function Xe(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),Xe)),t}function Ze(e){r(e.cancel)&&e.cancel()}function Qe(e){return!0===e?.isMobXFlow}function $e(e,t){var n;if(t===void 0)return bn(e);if(!1===Tt(e))return!1;let r=e[j];return(n=r.O)!=null&&n.has(t)?!0:r.j.has(t)?bn(Et(e,t)):!1}function et(e,t){if(!e)return!1;if(t!==void 0){if(Tt(e)){var n,r;let i=e[j];return i.j.has(t)||!((n=i.O)==null||!n.has(t))||!((r=i.V)==null||!r.has(t))}return!1}return Tt(e)||!!e[j]||Gt(e)||kn(e)||bn(e)}function tt(e){return et(e)}function nt(e){return Tt(e)?e[j].nt():ir(e)||sr(e)?Array.from(e.keys()):bt(e)?e.map((e,t)=>t):void t(5)}function rt(e,n){return Tt(e)?e[j].et(n):ir(e)||sr(e)?e.has(n):bt(e)?n>=0&&n<e.length:void t(10)}function it(e){if(Tt(e))return e[j].it();t(38)}function at(e,t,n){if(bn(e)){let r,i=!0;return Ge(()=>{let a=e.get();if(!i||n){let n=Oe();t({observableKind:`computed`,debugObjectName:e.tt,type:Xn,object:e,newValue:a,oldValue:r}),ke(n)}i=!1,r=a})}return n&&t({observableKind:`value`,debugObjectName:e.tt,object:e,type:Xn,newValue:e.rt,oldValue:void 0}),mt(e,t)}function ot(e,t,n){return e.set(t,n),n}function st(e,t){if(typeof e!=`object`||!e||e instanceof Date||!tt(e))return e;if(vn(e)||bn(e))return st(e.get(),t);if(t.has(e))return t.get(e);if(bt(e)){let n=ot(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=st(e,t)}),n}if(sr(e)){let n=ot(t,e,new Set);return e.forEach(e=>{n.add(st(e,t))}),n}if(ir(e)){let n=ot(t,e,new Map);return e.forEach((e,r)=>{n.set(r,st(e,t))}),n}{let n=ot(t,e,{});return it(e).forEach(r=>{Lt.propertyIsEnumerable.call(e,r)&&(n[r]=st(e[r],t))}),n}}function ct(e,t){Pe();try{return e.apply(t)}finally{Fe()}}function lt(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[j].isDisposed){if(a(),!n.onError)throw e;n.onError(e)}},n.timeout)}n.name=`When`;let i=ye(`When-effect`,t);var a=Ge(t=>{Se(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function ut(e){return e[j]}function dt(e){return e.st!==void 0&&e.st.length>0}function ft(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 O(e,n){let r=Oe();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{ke(r)}}function pt(e){return e.ot!==void 0&&e.ot.length>0}function mt(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 ht(e,t){let n=Oe(),r=e.ot;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);ke(n)}}function gt(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!==Lt;){let t=A(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 k(e,t){typeof Array.prototype[e]==`function`&&($n[e]=t(e))}function _t(e){return function(){let t=this[j];t.ct.reportObserved();let n=t.ht(t.j);return n[e].apply(n,arguments)}}function vt(e){return function(t,n){let r=this[j];return r.ct.reportObserved(),r.ht(r.j)[e]((e,r)=>t.call(n,e,r,this))}}function yt(e){return function(){let t=this[j];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 bt(e){return a(e)&&er(e[j])}function xt(e){return e[Symbol.toStringTag]=`MapIterator`,Nt(e)}function St(e){return e[Symbol.toStringTag]=`SetIterator`,Nt(e)}function Ct(e,t){if(p(e,j))return e;let n=t?.name??`ObservableObject`;return c(e,j,new ur(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 M[r]??(M[r]=de({deep:t,autoBind:n}))}(e):void 0}(t))),e}function wt(e){return cr[e]||(cr[e]={get(){return this[j]._(e)},set(t){return this[j].M(e,t)}})}function Tt(e){return!!a(e)&&dr(e[j])}function Et(e,n){if(typeof e==`object`&&e){if(bt(e))return n!==void 0&&t(23),e[j].ct;if(sr(e))return e.ct;if(ir(e)){if(n===void 0)return e.lt;let r=e.ft.get(n)||e.dt.get(n);return r||t(25,n,Ot(e)),r}if(Tt(e)){if(!n)return t(26);let r=e[j],i=r.j.get(n)??r.vt(n)??r.bt(n);return i||t(27,n,Ot(e)),i}if(Gt(e)||bn(e)||kn(e))return e}else if(r(e)&&kn(e[j]))return e[j];t(28)}function Dt(e,n){return e||t(29),n===void 0?Gt(e)||bn(e)||kn(e)||ir(e)||sr(e)?e:e[j]?e[j]:void t(24,e):Dt(Et(e,n))}function Ot(e,t){let n;if(t!==void 0)n=Et(e,t);else{if(We(e))return e.name;n=Tt(e)||ir(e)||sr(e)?Dt(e):Et(e)}return n.tt}function kt(e){let t=Oe();Pe();try{return e()}finally{Fe(),ke(t)}}function At(e,t,n=-1){return jt(e,t,n)}function jt(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=fr.call(e);if(s!==fr.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=Mt(e),t=Mt(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(!jt(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)||!jt(e[o],t[o],n-1,i,a))return!1}}return i.pop(),a.pop(),!0}function Mt(e){return bt(e)?e.slice():u(e)||ir(e)||d(e)||sr(e)?Array.from(e.entries()):e}function Nt(e){return e[Symbol.iterator]=Pt,Ft(Object.create(pr),e)}function Pt(){return this}Object.defineProperty(e,`__esModule`,{value:!0});let Ft=Object.assign,A=Object.getOwnPropertyDescriptor,It=Object.defineProperty,Lt=Object.prototype,Rt=[];Object.freeze(Rt);let zt={};Object.freeze(zt);let Bt=Object.toString(),Vt=()=>{},Ht=Reflect.ownKeys,Ut=Object.getOwnPropertyDescriptors,j=Symbol(`mobx administration`);var Wt=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 Le(this)}reportChanged(){Pe(),Re(this),Fe()}toString(){return this.tt}};let Gt=l(`Atom`,Wt),Kt=Object.is,qt={t:`override`,o:function(){return 0},u:function(){t(44,this.t)}},Jt=`true`,Yt=de(),M=[Yt],Xt={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Xt);let Zt=se(`observable`),Qt=se(`observable.ref`,{A:y}),$t=se(`observable.shallow`,{A:function(e,t,n){return e==null||Tt(e)||bt(e)||ir(e)||sr(e)?e:Array.isArray(e)?sn.array(e,{name:n,deep:!1}):o(e)?sn.object(e,void 0,{name:n,deep:!1}):u(e)?sn.map(e,{name:n,deep:!1}):d(e)?sn.set(e,{name:n,deep:!1}):void 0}}),en=se(`observable.struct`,{A:function(e,t){return At(e,t)?t:e}}),tn={box(e,t){let n=he(t);return new _n(e,_e(n),n.name,!0,n.equals)},array(e,t){let n=he(t);return function(e,t,n=`ObservableArray`,r=!1){return kt(()=>{let i=new Qn(n,t,r);It(i.j,j,{enumerable:!1,writable:!1,configurable:!0,value:i});let a=new Proxy(i.j,Zn);return i.v=a,e&&e.length&&i.wt(0,0,e),a})}(e,_e(n),n.name)},map(e,t){let n=he(t);return new rr(e,_e(n),n.name)},set(e,t){let n=he(t);return new or(e,_e(n),n.name)},object:(e,t,n)=>kt(()=>Je(function(e,t){var n;return(n=(e=Ct(e,t))[j]).v??(n.v=new Proxy(e,qn))}({},n),e,t))},nn=ge(Qt),rn=ge($t),an=ge(Zt),on=ge(en);var sn=Ft(function(e,t,n){return t&&typeof t.kind==`string`?ue(Zt,e,t):tt(e)?e:o(e)?sn.object(e,t,n):Array.isArray(e)?sn.array(e,t):u(e)?sn.map(e,t):d(e)?sn.set(e,t):typeof e==`object`&&e?e:sn.box(e,t)},Zt,tn);let cn=`computed`,ln=w(cn),un=ve(w(`computed.struct`,{equals:_})),dn=function(e,t){if(t&&typeof t.kind==`string`)return E(ln,e,t);if(o(e))return ve(w(cn,e));let n=o(t)?t:{};return n.get=e,n.name||=e.name||``,new yn(n)};var fn;Ft(dn,ln);let pn=0,mn=1,hn=(fn=A(()=>{},`name`)?.configurable)!=null&&fn,gn={value:`action`,configurable:!0,writable:!1,enumerable:!1};var _n=class extends Wt{constructor(e,t,n=`ObservableValue`,r=!0,i=Kt){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))!==N.UNCHANGED&&this.Ot(e)}jt(e){if(dt(this)){let t=O(this,{object:this,type:Xn,newValue:e});if(!t)return N.UNCHANGED;e=t.newValue}return e=this.A(e,this.rt,this.tt),this.xt(this.rt,e)?N.UNCHANGED:e}Ot(e){let t=this.rt;this.rt=e,this.reportChanged(),pt(this)&&ht(this,{type:Xn,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 vn=l(`ObservableValue`,_n);var yn=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 xn(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=ye(`ComputedValue-setter`,e.set)),this.xt=e.equals||Kt,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),N.inBatch!==0||this.H&&this.H.size!==0||this.Mt){let e=this.isBeingObserved;if(Le(this),we(this)){let e=N.trackingContext;e||!this.Mt&&!this.isBeingObserved||(N.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),N.trackingContext=e}else !e&&this.isBeingObserved&&this.L.forEach(Ie)}else we(this)&&(this.Nt(),Pe(),this.rt=this.Rt(!1),Fe());let e=this.rt;if(Ce(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||Ce(e)||Ce(n)||!this.xt(e,n);return r&&(this.rt=n),r}Rt(e){let t;if(this.isComputing=!0,e)t=Te(this,this.derivation,this.At);else if(!0===N.disableErrorBoundaries)t=this.derivation.call(this.At);else try{t=this.derivation.call(this.At)}catch(e){t=new xn(e)}return this.isComputing=!1,t}G(){this.Mt||(Ee(this),this.rt=void 0)}Nt(){}toString(){return`${this.tt}[${this.derivation.toString()}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let bn=l(`ComputedValue`,yn);var xn=class{constructor(e){this.cause=void 0,this.cause=e}};let Sn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Cn=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 wn=!0,Tn=!1,N=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(wn=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(wn=!1),wn?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Cn):(setTimeout(()=>{Tn||t(35)},1),new Cn)}();var En=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,N.pendingReactions.push(this),ze())}X(){if(!this.isDisposed){Pe(),this.isScheduled=!1;let e=N.trackingContext;if(N.trackingContext=this,we(this)){this.isTrackPending=!0;try{this.Et()}catch(e){this.Pt(e)}}N.trackingContext=e,Fe()}}track(e){if(this.isDisposed)return;Pe(),this.isRunning=!0;let t=N.trackingContext;N.trackingContext=this;let n=Te(this,e,void 0);N.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Ee(this),Ce(n)&&this.Pt(n.cause),Fe()}Pt(e){if(this.kt)this.kt(e,this);else{if(N.disableErrorBoundaries)throw e;N.suppressReactionErrors||console.error(`[mobx] uncaught error in '${this}'`,e),N.globalReactionErrorHandlers.forEach(t=>t(e,this))}}dispose(){var e;this.isDisposed||(this.isDisposed=!0,(e=this.It)==null||e.call(this),this.isRunning||(Pe(),Ee(this),Fe()))}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[j]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.tt}]`}};let Dn=100,On=e=>e(),kn=l(`Reaction`,En),An=`action`,jn=`autoAction`,Mn=b(An),Nn=b(`action.bound`,{bound:!0}),Pn=b(jn,{autoAction:!0}),Fn=b(`autoAction.bound`,{autoAction:!0,bound:!0}),In=He(!1);Ft(In,Mn);let Ln=He(!0);Ft(Ln,Pn);let Rn=Ve(Nn),zn=Ve(Fn),Bn=e=>e(),Vn=`always`;var Hn=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};let Un=te(`flow`),Wn=te(`flow.bound`,{bound:!0}),Gn=Ft(function(e,t){if(t&&typeof t.kind==`string`)return ie(Un,e,t);let n=e,i=n.name||`flow`,a=function(){let e=arguments,t=In(i,n).apply(this,e),a,o,s=new Promise(function(e,n){function s(e){let r;o=void 0;try{r=In(i,t.next).call(t,e)}catch(e){return n(e)}l(r)}function c(e){let r;o=void 0;try{r=In(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=In(i,function(){try{o&&Ze(o);let e=t.return(void 0),n=Promise.resolve(e.value);n.then(Vt,Vt),Ze(n),a(new Hn)}catch(e){a(e)}}),s};return a.isMobXFlow=!0,a},Un),Kn=me(Wn,ie),qn={has:(e,t)=>ut(e).et(t),get:(e,t)=>ut(e).Tt(t),set(e,t,n){var r;return!!i(t)&&((r=ut(e).Bt(t,n,!0))==null||r)},deleteProperty(e,t){var n;return!!i(t)&&((n=ut(e).Dt(t,!0))==null||n)},defineProperty(e,t,n){var r;return(r=ut(e).l(t,n))==null||r},ownKeys:e=>ut(e).it(),preventExtensions(e){t(13)}},Jn=Symbol(`mobx-keys`),Yn=`splice`,Xn=`update`,Zn={get(e,t){let n=e[j];return t===j?n:t===`length`?n.Kt():typeof t!=`string`||isNaN(t)?p($n,t)?$n[t]:e[t]:n.Tt(parseInt(t))},set(e,t,n){let r=e[j];return t===`length`?r.Lt(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.Bt(parseInt(t),n),!0},preventExtensions(){t(15)}};var Qn=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 Wt(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=Rt),dt(this)){let r=O(this,{object:this.v,type:Yn,index:e,removedCount:t,added:n});if(!r)return Rt;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=pt(this),i=r?{observableKind:`array`,object:this.v,type:Xn,debugObjectName:this.ct.tt,index:e,newValue:t,oldValue:n}:null;this.ct.reportChanged(),r&&ht(this,i)}Ft(e,t,n){let r=pt(this),i=r?{observableKind:`array`,object:this.v,debugObjectName:this.ct.tt,type:Yn,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;this.ct.reportChanged(),r&&ht(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(dt(this)){let n=O(this,{type:Xn,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)}}},$n={clear(){return this.splice(0)},replace(e){let t=this[j];return t.wt(0,t.j.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[j];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[j].wt(e,t,n)},push(...e){let t=this[j];return t.wt(t.j.length,0,e),t.j.length},pop(){return this.splice(Math.max(this[j].j.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[j];return t.wt(0,0,e),t.j.length},reverse(){return N.trackingDerivation&&t(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){N.trackingDerivation&&t(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[j],n=t.ht(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};k(`at`,_t),k(`concat`,_t),k(`flat`,_t),k(`includes`,_t),k(`indexOf`,_t),k(`join`,_t),k(`lastIndexOf`,_t),k(`slice`,_t),k(`toString`,_t),k(`toLocaleString`,_t),k(`toSorted`,_t),k(`toSpliced`,_t),k(`with`,_t),k(`every`,vt),k(`filter`,vt),k(`find`,vt),k(`findIndex`,vt),k(`findLast`,vt),k(`findLastIndex`,vt),k(`flatMap`,vt),k(`forEach`,vt),k(`map`,vt),k(`some`,vt),k(`toReversed`,vt),k(`reduce`,yt),k(`reduceRight`,yt);let er=l(`ObservableArrayAdministration`,Qn),tr={},nr=`delete`;var rr=class{constructor(e,t=v,n=`ObservableMap`){this.A=void 0,this.tt=void 0,this[j]=tr,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,kt(()=>{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(!N.trackingDerivation)return this.et(e);let t=this.dt.get(e);if(!t){let n=t=new _n(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(dt(this)){let r=O(this,{type:n?Xn:`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(dt(this)&&!O(this,{type:nr,object:this,name:e}))return!1;if(this.et(e)){let t=pt(this),n=t?{observableKind:`map`,debugObjectName:this.tt,type:nr,object:this,oldValue:this.ft.get(e).rt,name:e}:null;return ct(()=>{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&&ht(this,n),!0}return!1}Gt(e,t){let n=this.ft.get(e);if((t=n.jt(t))!==N.UNCHANGED){let r=pt(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:Xn,object:this,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&ht(this,i)}}Jt(e,t){ct(()=>{var n;let r=new _n(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=pt(this);n&&ht(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 xt({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 xt({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 ir(e)&&(e=new Map(e)),ct(()=>{o(e)?function(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>Lt.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(){ct(()=>{De(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return ct(()=>{let n=function(e){if(u(e)||ir(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`}},ir=l(`ObservableMap`,rr);let ar={};var or=class{constructor(e,t=v,n=`ObservableSet`){this.tt=void 0,this[j]=ar,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),kt(()=>{this.ct=g(this.tt),e&&this.replace(e)})}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){ct(()=>{De(()=>{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(dt(this)){let t=O(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){ct(()=>{e=this.A(e,void 0),this.ft.add(e),this.ct.reportChanged()});let t=pt(this);t&&ht(this,t?{observableKind:`set`,debugObjectName:this.tt,type:`add`,object:this,newValue:e}:null)}return this}delete(e){if(dt(this)&&!O(this,{type:nr,object:this,oldValue:e}))return!1;if(this.has(e)){let t=pt(this),n=t?{observableKind:`set`,debugObjectName:this.tt,type:nr,object:this,oldValue:e}:null;return ct(()=>{this.ct.reportChanged(),this.ft.delete(e)}),t&&ht(this,n),!0}return!1}has(e){return this.ct.reportObserved(),this.ft.has(this.Wt(e))}entries(){let e=this.values();return St({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 St({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 sr(e)&&(e=new Set(e)),Array.isArray(e)||d(e)?ct(()=>{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`}},sr=l(`ObservableSet`,or);let cr=Object.create(null),lr=`remove`;var ur=class{constructor(e,t=new Map,n,r=Yt){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 Wt(`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 yn)return n.set(t),!0;if(dt(this)){let n=O(this,{type:Xn,object:this.v||this.h,name:e,newValue:t});if(!n)return null;t=n.newValue}if((t=n.jt(t))!==N.UNCHANGED){let r=pt(this),i=r?{type:Xn,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&ht(this,i)}return!0}Tt(e){return N.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(!N.trackingDerivation)return e in this.h;this.Qt||=new Map;let t=this.Qt.get(e);return t||(t=new _n(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{Pe();let r=this.Dt(e);if(!r)return r;if(dt(this)){let n=O(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=Ft({},t,{value:r}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else It(this.h,e,t);this.Yt(e,t.value)}finally{Fe()}return!0}S(e,t,n,r=!1){try{Pe();let i=this.Dt(e);if(!i)return i;if(dt(this)){let n=O(this,{object:this.v||this.h,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let a=wt(e),o={configurable:!N.safeDescriptors||this.p,enumerable:!0,get:a.get,set:a.set};if(r){if(!Reflect.defineProperty(this.h,e,o))return!1}else It(this.h,e,o);let s=new _n(t,n,`ObservableObject.key`,!1);this.j.set(e,s),this.Yt(e,s.rt)}finally{Fe()}return!0}m(e,t,n=!1){try{Pe();let r=this.Dt(e);if(!r)return r;if(dt(this)&&!O(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=wt(e),a={configurable:!N.safeDescriptors||this.p,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.h,e,a))return!1}else It(this.h,e,a);this.j.set(e,new yn(t)),this.Yt(e,void 0)}finally{Fe()}return!0}Dt(e,t=!1){if(!p(this.h,e))return!0;if(dt(this)&&!O(this,{object:this.v||this.h,name:e,type:lr}))return null;try{var n;Pe();let r=pt(this),i=this.j.get(e),a;if(i||!r||(a=A(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 _n&&(a=i.rt),Re(i)),this.lt.reportChanged(),(n=this.Qt)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&ht(this,{type:lr,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{Fe()}return!0}Yt(e,t){var n;let r=pt(this);r&&r&&ht(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(),Ht(this.h)}nt(){return this.lt.reportObserved(),Object.keys(this.h)}};let dr=l(`ObservableObjectAdministration`,ur),fr=Lt.toString,pr=globalThis.Iterator?.prototype||{};e.$mobx=j,e.FlowCancellationError=Hn,e.ObservableMap=rr,e.ObservableSet=or,e.Reaction=En,e._allowStateChanges=Se,e._allowStateChangesInsideComputed=Ue,e._allowStateReadsEnd=function(e){N.allowStateReads=e},e._allowStateReadsStart=function(e){let t=N.allowStateReads;return N.allowStateReads=e,t},e._autoAction=Ln,e._autoActionBound=zn,e._endAction=D,e._getAdministration=Dt,e._getGlobalState=function(){return N},e._interceptReads=function(e,t,n){let r;return ir(e)||bt(e)||vn(e)?r=Dt(e):Tt(e)&&(r=Dt(e,t)),r.dehancer=typeof t==`function`?t:n,()=>{r.dehancer=void 0}},e._isComputingDerivation=function(){return N.trackingDerivation!==null},e._resetGlobalState=function(){let e=new Cn;for(let t in e)Sn.indexOf(t)===-1&&(N[t]=e[t]);N.allowStateChanges=!N.enforceActions},e._startAction=xe,e.action=In,e.actionBound=Rn,e.autorun=Ge,e.compareDefault=Kt,e.compareIdentity=function(e,t){return e===t},e.compareShallow=function(e,t){return At(e,t,1)},e.compareStructural=_,e.computed=dn,e.computedStruct=un,e.configure=function(e){!0===e.isolateGlobalState&&function(){if((N.pendingReactions.length||N.inBatch||N.isRunningReactions)&&t(36),Tn=!0,wn){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),N=new Cn}}();let{enforceActions:n}=e;if(n!==void 0){let e=n===Vn?Vn:n===`observed`;N.enforceActions=e,N.allowStateChanges=!0!==e&&e!==Vn}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(N[t]=!!e[t])}),N.allowStateReads=!N.observableRequiresReaction,e.reactionScheduler&&function(e){let t=On;On=n=>e(()=>t(n))}(e.reactionScheduler)},e.createAtom=g,e.defineProperty=function(e,n,r){if(Tt(e))return e[j].l(n,r);t(39)},e.entries=function(e){return Tt(e)?nt(e).map(t=>[t,e[t]]):ir(e)?nt(e).map(t=>[t,e.get(t)]):sr(e)?Array.from(e.entries()):bt(e)?e.map((e,t)=>[t,e]):void t(7)},e.extendObservable=Je,e.flow=Gn,e.flowBound=Kn,e.flowResult=function(e){return e},e.get=function(e,n){if(rt(e,n))return Tt(e)?e[j].Tt(n):ir(e)?e.get(n):bt(e)?e[n]:void t(11)},e.getAtom=Et,e.getDebugName=Ot,e.getDependencyTree=function(e,t){return Ye(Et(e,t))},e.getObserverTree=function(e,t){return Xe(Et(e,t))},e.has=rt,e.intercept=function(e,t,n){return r(n)?function(e,t,n){return ft(Dt(e,t),n)}(e,t,n):function(e,t){return ft(Dt(e),t)}(e,t)},e.isAction=We,e.isBoxedObservable=vn,e.isComputed=function(e){return $e(e)},e.isComputedProp=function(e,t){return $e(e,t)},e.isFlow=Qe,e.isFlowCancellationError=function(e){return e instanceof Hn},e.isObservable=tt,e.isObservableArray=bt,e.isObservableMap=ir,e.isObservableObject=Tt,e.isObservableProp=function(e,t){return et(e,t)},e.isObservableSet=sr,e.keys=nt,e.makeAutoObservable=function(e,t,n){return o(e)?Je(e,e,t,n):(kt(()=>{let r=Ct(e,n)[j];if(!e[Jn]){let t=Object.getPrototypeOf(e),n=new Set([...Ht(e),...Ht(t)]);n.delete(`constructor`),n.delete(j),c(t,Jn,n)}e[Jn].forEach(e=>gt(r,e,!t||!(e in t)||t[e]))}),e)},e.makeObservable=function(e,t,n){return kt(()=>{let r=Ct(e,n)[j];Ht(t).forEach(e=>gt(r,e,t[e]))}),e},e.observable=sn,e.observableDeep=an,e.observableRef=nn,e.observableShallow=rn,e.observableStruct=on,e.observe=function(e,t,n,i){return r(n)?function(e,t,n,r){return at(Dt(e,t),n,r)}(e,t,n,i):function(e,t,n){let r=Dt(e);if(bt(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(!ir(e)&&!sr(e)&&!Tt(e))return at(r,t,n);return mt(r,t)}(e,t,n)},e.onBecomeObserved=function(e,t,n){return qe(`onBO`,e,t,n)},e.onBecomeUnobserved=function(e,t,n){return qe(`onBUO`,e,t,n)},e.onReactionError=function(e){return N.globalReactionErrorHandlers.push(e),()=>{let t=N.globalReactionErrorHandlers.indexOf(e);t>=0&&N.globalReactionErrorHandlers.splice(t,1)}},e.override=qt,e.ownKeys=it,e.reaction=function(e,t,n=zt){function r(){if(p=!1,h.isDisposed)return;let t=!1,r=d;h.track(()=>{let n=Se(!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=In(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=Ke(n),d,f=!0,p=!1,m=n.equals||Kt,h=new En(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){Tt(e)?e[j].Dt(n):ir(e)||sr(e)?e.delete(n):bt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=Ue,e.set=function e(n,r,i){if(arguments.length===2&&!sr(n)){Pe();let t=r;try{for(let r in t)e(n,r,t[r])}finally{Fe()}return}Tt(n)?n[j].Bt(r,i):ir(n)?n.set(r,i):sr(n)?n.add(r):bt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(42,r),Pe(),r>=n.length&&(n.length=r+1),n[r]=i,Fe()):t(8)},e.spy=function(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}},e.toJS=function(e){return st(e,new Map)},e.transaction=ct,e.untracked=De,e.values=function(e){return Tt(e)?nt(e).map(t=>e[t]):ir(e)?nt(e).map(t=>e.get(t)):sr(e)?Array.from(e.values()):bt(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 Ft(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let r,i,a=new Promise((n,a)=>{var o;let s=lt(e,n,Ft({},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):lt(e,t,n||{})}})),N_=ye((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++M.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=ie(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 x(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function S(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function C(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function ee(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let te=Reflect.ownKeys;function ne(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function re(e){return e===null?null:typeof e==`object`?``+e:e}function ie(e,t){return o.hasOwnProperty.call(e,t)}let ae=Object.getOwnPropertyDescriptors;function w(e,t){return!!(e&t)}function T(e,t,n){return n?e|=t:e&=~t,e}function oe(e,t){t.includes(e.kind)||n(`The decorator applied to '${String(e.name)}' cannot be used on a ${e.kind} element`)}let E=Symbol(`mobx administration`);var se=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_=T(this.flags_,1,e)}get isPendingUnobservation(){return w(this.flags_,2)}set isPendingUnobservation(e){this.flags_=T(this.flags_,2,e)}get diffValue(){return+!!w(this.flags_,4)}set diffValue(e){this.flags_=T(this.flags_,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return ln(this)}reportChanged(){an(),un(this),on()}toString(){return this.name_}};let ce=b(`Atom`,se);function le(e,t=f,n=f){let r=new se(e);return t!==f&&(r.onBOL=new Set([t])),n!==f&&(r.onBUOL=new Set([n])),r}function ue(e,t){return e===t}function de(e,t){return Fi(e,t)}function fe(e,t){return Fi(e,t,1)}let pe=Object.is;function me(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||xr(e)?e:Array.isArray(e)?O.array(e,{name:n}):g(e)?O.object(e,void 0,{name:n}):x(e)?O.map(e,{name:n}):C(e)?O.set(e,{name:n}):typeof e==`function`&&!zn(e)&&!fr(e)?_(e)?cr(e):Fn(n,e):e}function he(e,t,r){if(e==null||Di(e)||pi(e)||P(e)||yi(e))return e;if(Array.isArray(e))return O.array(e,{name:r,deep:!1});if(g(e))return O.object(e,void 0,{name:r,deep:!1});if(x(e))return O.map(e,{name:r,deep:!1});if(C(e))return O.set(e,{name:r,deep:!1});n(`The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets`)}function ge(e){return e}function _e(e,t){return xr(e)&&n(`observable.struct should not be used with observable values`),Fi(e,t)?t:e}let ve=`override`,ye={annotationType_:ve,make_:xe,extend_:D};function be(e){return e.annotationType_===ve}function xe(e,t){return e.isPlainObject_&&n(`Cannot apply '${this.annotationType_}' to '${e.name_}.${t.toString()}':\n'${this.annotationType_}' cannot be used on plain objects.`),ie(e.appliedAnnotations_,t)||n(`'${e.name_}.${t.toString()}' is annotated with '${this.annotationType_}', but no such annotated member was found on prototype.`),0}function D(e,t,r,i){n(44,this.annotationType_)}function Se(e,t){return{annotationType_:e,options_:t,make_:Ce,extend_:we}}function Ce(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:zn(n.value)?1:(a(r,t,De(e,this,t,n,!1)),2)}function we(e,t,n,r){let i=De(e,this,t,n);return e.defineProperty_(t,i,r)}function Te(e,t,r){oe(r,[`method`,`field`]);let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>xt(s.options_?.name??a.toString(),e,s.options_?.autoAction??!1);if(i==`field`)return function(e){var t;let n=e;return zn(n)||(n=c(n)),(t=s.options_)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n};if(i==`method`){var l;return zn(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 Ee(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 De(e,t,n,r,i=M.safeDescriptors){var a,o;Ee(e,t,n,r);let{value:s}=r;return(a=t.options_)!=null&&a.bound&&(s=s.bind(e.proxy_??e.target_)),{value:xt(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 Oe(e,t){return{annotationType_:e,options_:t,make_:ke,extend_:Ae}}function ke(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&&(!ie(e.target_,t)||!fr(e.target_[t]))&&this.extend_(e,t,n,!1)===null?0:fr(n.value)?1:(a(r,t,Ne(e,this,t,n,!1,!1)),2)}function Ae(e,t,n,r){let i=Ne(e,this,t,n,this.options_?.bound);return e.defineProperty_(t,i,r)}function je(e,t,n){var r;oe(n,[`method`]);let{name:i,addInitializer:a}=n;return fr(t)||(t=cr(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 Me(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 Ne(e,t,n,r,i,a=M.safeDescriptors){Me(e,t,n,r);let{value:o}=r;return fr(o)||(o=cr(o)),i&&(o=o.bind(e.proxy_??e.target_),o.isMobXFlow=!0),{value:o,configurable:a?e.isPlainObject_:!0,enumerable:!1,writable:!a}}function Pe(e,t){return{annotationType_:e,options_:t,make_:Fe,extend_:Ie}}function Fe(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Ie(e,t,n,i){return Re(e,this,t,n),e.defineComputedProperty_(t,r({},this.options_,{get:n.get,set:n.set}),i)}function Le(e,t,n){oe(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 At(o)}return o(function(){let e=wi(this)[E],n=this,r=e.values_.get(a);r instanceof At&&r.derivation!==t&&e.values_.delete(a),(e.lazyComputedKeys_??=new Map).set(a,()=>c(n,e))}),function(){let e=this[E],n=e.values_.get(a);if(n instanceof At&&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 Re(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 ze(e,t){return{annotationType_:e,options_:t,make_:Be,extend_:Ve}}function Be(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Ve(e,t,n,r){return Ue(e,this,t,n),e.defineObservableProperty_(t,n.value,this.options_?.enhancer_??me,r)}function He(e,t,r){if(r.kind===`field`)throw n(`Please use \`@observable accessor ${String(r.name)}\` instead of \`@observable ${String(r.name)}\``);oe(r,[`accessor`]);let i=e,{kind:a,name:o}=r;if(a!==`accessor`)return;function s(e,t){let n=wi(e)[E];return(n.lazyObservableKeys_??=new Map).set(o,()=>new Ot(t,i.options_?.enhancer_??me,`${n.name_}.${o.toString()}`,!1)),n}return{get(){return(this[E]??s(this,t.get.call(this))).getObservablePropValue_(o)},set(e){return(this[E]??s(this,e)).setObservablePropValue_(o,e)},init(e){return s(this,e),e}}}function Ue(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 We=Ge();function Ge(e){return{annotationType_:`true`,options_:e,make_:Je,extend_:Ye}}let Ke=[We];function qe(e){let t=e.deep!==!1,n=!!e.autoBind,r=!t|(n?2:0);return Ke[r]??(Ke[r]=Ge({deep:t,autoBind:n}))}function Je(e,t,n,r){var i;if(n.get)return k.make_(e,t,n,r);if(n.set){let i=zn(n.set)?n.set:xt(t.toString(),n.set);return r===e.target_?e.defineProperty_(t,{configurable:M.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?lr:cr).make_(e,t,n,r)}return((o=this.options_)!=null&&o.autoBind?Ln:Fn).make_(e,t,n,r)}let c=this.options_?.deep===!1?lt:O;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 Ye(e,t,n,r){var i;return n.get?k.extend_(e,t,n,r):n.set?e.defineProperty_(t,{configurable:M.safeDescriptors?e.isPlainObject_:!0,set:xt(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?lt:O).extend_(e,t,n,r))}function Xe(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 Ze={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Ze);function Qe(e){return e||Ze}let $e=ze(`observable`),et=ze(`observable.ref`,{enhancer_:ge}),tt=ze(`observable.shallow`,{enhancer_:he}),nt=ze(`observable.struct`,{enhancer_:_e});function rt(e){return Xe(e,He)}function it(e){return e.deep===!0?me:e.deep===!1?ge:ot(e.defaultDecorator)}function at(e){return e?e.defaultDecorator??qe(e):void 0}function ot(e){return e?e.options_?.enhancer_??me:me}function st(e,t,n){return t&&typeof t.kind==`string`?He($e,e,t):xr(e)?e:g(e)?O.object(e,t,n):Array.isArray(e)?O.array(e,t):x(e)?O.map(e,t):C(e)?O.set(e,t):typeof e==`object`&&e?e:O.box(e,t)}let ct={box(e,t){let n=Qe(t);return new Ot(e,it(n),n.name,!0,n.equals)},array(e,t){let n=Qe(t);return oi(e,it(n),n.name)},map(e,t){let n=Qe(t);return new gi(e,it(n),n.name)},set(e,t){let n=Qe(t);return new vi(e,it(n),n.name)},object(e,t,n){return Ni(()=>Xn(Gr({},n),e,t))}},lt=rt(et),ut=rt(tt),dt=rt($e),ft=rt(nt);var O=r(st,$e,ct);let pt=`computed`;function mt(e){return Xe(e,Le)}let ht=Pe(pt),gt=mt(Pe(`computed.struct`,{equals:de})),k=function(e,t){if(t&&typeof t.kind==`string`)return Le(ht,e,t);if(g(e))return mt(Pe(pt,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 At(r)};r(k,ht);let _t=0,vt=1,yt=i(()=>{},`name`)?.configurable??!1,bt={value:`action`,configurable:!0,writable:!1,enumerable:!1};function xt(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 St(e,r,t,i||this,arguments)}return o.isMobxAction=!0,o.toString=()=>t.toString(),yt&&(bt.value=e,a(o,`name`,bt)),o}function St(e,t,n,r,i){let a=Ct(e,t,r,i);try{return n.apply(r,i)}catch(e){throw a.error_=e,e}finally{wt(a)}}function Ct(e,t,n,r){let i=bn()&&!!e,a=0;i&&(a=Date.now(),Sn({type:N,name:e,object:n,arguments:r?Array.from(r):s}));let o=M.trackingDerivation,c=!t||!o;an();let l=M.allowStateChanges;c&&(Ht(),l=Et(!0));let u=M.allowStateReads;j(!0);let d={runAsAction_:c,prevDerivation_:o,prevAllowStateChanges_:l,prevAllowStateReads_:u,notifySpy_:i,startTime_:a,actionId_:vt++,parentActionId_:_t};return _t=d.actionId_,d}function wt(e){_t!==e.actionId_&&n(30),_t=e.parentActionId_,e.error_!==void 0&&(M.suppressReactionErrors=!0),Dt(e.prevAllowStateChanges_),Wt(e.prevAllowStateReads_),on(),e.runAsAction_&&Ut(e.prevDerivation_),e.notifySpy_&&wn({time:Date.now()-e.startTime_}),M.suppressReactionErrors=!1}function Tt(e,t){let n=Et(e);try{return t()}finally{Dt(n)}}function Et(e){let t=M.allowStateChanges;return M.allowStateChanges=e,t}function Dt(e){M.allowStateChanges=e}var Ot=class extends se{constructor(e,t,n=`ObservableValue@`+u(),r=!0,i=pe){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&&bn()&&xn({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!==M.UNCHANGED){let n=bn();n&&Sn({type:ri,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:e,oldValue:t}),this.setNewValue_(e),n&&wn()}}prepareNewValue_(e){if(A(this),Kr(this)){let t=Jr(this,{object:this,type:ri,newValue:e});if(!t)return M.UNCHANGED;e=t.newValue}return e=this.enhancer_(e,this.value_,this.name_),this.equals_(this.value_,e)?M.UNCHANGED:e}setNewValue_(e){let t=this.value_;this.value_=e,this.reportChanged(),Yr(this)&&Zr(this,{type:ri,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 re(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let kt=b(`ObservableValue`,Ot);var At=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 Mt(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_=xt(this.name_+`-setter`,e.set)),this.equals_=e.equals||pe,this.scope_=e.context,this.requiresReaction_=e.requiresReaction,this.keepAlive_=!!e.keepAlive}onBecomeStale_(){fn(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_=T(this.flags_,1,e)}get isRunningSetter(){return w(this.flags_,2)}set isRunningSetter(e){this.flags_=T(this.flags_,2,e)}get isBeingObserved(){return w(this.flags_,4)}set isBeingObserved(e){this.flags_=T(this.flags_,4,e)}get isPendingUnobservation(){return w(this.flags_,8)}set isPendingUnobservation(e){this.flags_=T(this.flags_,8,e)}get diffValue(){return+!!w(this.flags_,16)}set diffValue(e){this.flags_=T(this.flags_,16,e===1)}get(){if(this.isComputing&&n(32,this.name_,this.derivation),M.inBatch===0&&(!this.observers_||this.observers_.size===0)&&!this.keepAlive_)Pt(this)&&(this.warnAboutUntrackedRead_(),an(),this.value_=this.computeValue_(!1),on());else{let e=this.isBeingObserved;if(ln(this),Pt(this)){let e=M.trackingContext;!e&&(this.keepAlive_||this.isBeingObserved)&&(M.trackingContext=this),this.trackAndCompute()&&dn(this),M.trackingContext=e}else !e&&this.isBeingObserved&&this.observing_.forEach(cn)}let e=this.value_;if(Nt(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||Nt(e)||Nt(n)||!this.equals_(e,n);return r&&(this.value_=n,bn()&&xn({observableKind:`computed`,debugObjectName:this.name_,object:this.scope_,type:`update`,oldValue:e,newValue:n})),r}computeValue_(e){this.isComputing=!0;let t=Et(!1),n;if(e)n=Lt(this,this.derivation,this.scope_);else if(M.disableErrorBoundaries===!0)n=this.derivation.call(this.scope_);else try{n=this.derivation.call(this.scope_)}catch(e){n=new Mt(e)}return Dt(t),this.isComputing=!1,n}suspend_(){this.keepAlive_||(Bt(this),this.value_=void 0)}warnAboutUntrackedRead_(){(typeof this.requiresReaction_==`boolean`?this.requiresReaction_:M.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 re(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let jt=b(`ComputedValue`,At);var Mt=class{constructor(e){this.cause=void 0,this.cause=e}};function Nt(e){return e instanceof Mt}function Pt(e){switch(e.dependenciesState_){case 0:return!1;case-1:case 2:return!0;case 1:{let t=j(!0),n=Ht(),r=e.observing_,i=r.length;for(let a=0;a<i;a++){let i=r[a];if(jt(i)){if(M.disableErrorBoundaries)i.get();else try{i.get()}catch{return Ut(n),Wt(t),!0}if(e.dependenciesState_===2)return Ut(n),Wt(t),!0}}return Gt(e),Ut(n),Wt(t),!1}}}function Ft(){return M.trackingDerivation!==null}function A(e){let t=!!e.observers_&&e.observers_.size>0;!M.allowStateChanges&&(t||M.enforceActions===`always`)&&console.warn(`[MobX] `+(M.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 It(e){!M.allowStateReads&&M.observableRequiresReaction&&console.warn(`[mobx] Observable '${e.name_}' being read outside a reactive context.`)}function Lt(e,t,n){let r=j(!0);Gt(e),e.newObserving_=Array(e.runId_===0?100:e.observing_.length),e.unboundDepsCount_=0,e.runId_=++M.runId;let i=M.trackingDerivation;M.trackingDerivation=e,M.inBatch++;let a;if(M.disableErrorBoundaries===!0)a=t.call(n);else try{a=t.call(n)}catch(e){a=new Mt(e)}return M.inBatch--,M.trackingDerivation=i,zt(e),Rt(e),Wt(r),a}function Rt(e){e.observing_.length===0&&(typeof e.requiresObservable_==`boolean`?e.requiresObservable_:M.reactionRequiresObservable)&&console.warn(`[mobx] Derivation '${e.name_}' is created/updated without reading any observable value.`)}function zt(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&&nn(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,tn(t,e))}r!==0&&(e.dependenciesState_=r,e.onBecomeStale_())}function Bt(e){let t=e.observing_;e.observing_=[];let n=t.length;for(;n--;)nn(t[n],e);e.dependenciesState_=-1}function Vt(e){let t=Ht();try{return e()}finally{Ut(t)}}function Ht(){let e=M.trackingDerivation;return M.trackingDerivation=null,e}function Ut(e){M.trackingDerivation=e}function j(e){let t=M.allowStateReads;return M.allowStateReads=e,t}function Wt(e){M.allowStateReads=e}function Gt(e){if(e.dependenciesState_===0)return;e.dependenciesState_=0;let t=e.observing_,n=t.length;for(;n--;)t[n].lowestObserverState_=0}let Kt=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var qt=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 Jt=!0,Yt=!1,M=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Jt=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(Jt=!1),Jt?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new qt):(setTimeout(()=>{Yt||n(35)},1),new qt)}();function Xt(){if((M.pendingReactions.length||M.inBatch||M.isRunningReactions)&&n(36),Yt=!0,Jt){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),M=new qt}}function Zt(){return M}function Qt(){let e=new qt;for(let t in e)Kt.indexOf(t)===-1&&(M[t]=e[t]);M.allowStateChanges=!M.enforceActions}function $t(e){return!!e.observers_&&e.observers_.size>0}function en(e){return e.observers_??new Set}function tn(e,t){(e.observers_??=new Set).add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function nn(e,t){let n=e.observers_;n&&(n.delete(t),n.size===0&&rn(e))}function rn(e){e.isPendingUnobservation===!1&&(e.isPendingUnobservation=!0,M.pendingUnobservations.push(e))}function an(){M.inBatch++}function on(){--M.inBatch===0&&(gn(),!M.isRunningUnobservations&&M.pendingUnobservations.length>0&&sn())}function sn(){M.isRunningUnobservations=!0;try{let e=M.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 At&&n.suspend_())}M.pendingUnobservations=[]}finally{M.isRunningUnobservations=!1}}function cn(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.observing_)==null||t.forEach(cn))}function ln(e){It(e);let t=M.trackingDerivation;return t===null?((!e.observers_||e.observers_.size===0)&&M.inBatch>0&&rn(e),!1):(t.runId_!==e.lastAccessedBy_&&(e.lastAccessedBy_=t.runId_,t.newObserving_[t.unboundDepsCount_++]=e,!e.isBeingObserved&&M.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function un(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 dn(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 fn(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 pn=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_=T(this.flags_,1,e)}get isScheduled(){return w(this.flags_,2)}set isScheduled(e){this.flags_=T(this.flags_,2,e)}get isTrackPending(){return w(this.flags_,4)}set isTrackPending(e){this.flags_=T(this.flags_,4,e)}get isRunning(){return w(this.flags_,8)}set isRunning(e){this.flags_=T(this.flags_,8,e)}get diffValue(){return+!!w(this.flags_,16)}set diffValue(e){this.flags_=T(this.flags_,16,e===1)}onBecomeStale_(){this.schedule_()}schedule_(){this.isScheduled||(this.isScheduled=!0,M.pendingReactions.push(this),gn())}runReaction_(){if(!this.isDisposed){an(),this.isScheduled=!1;let e=M.trackingContext;if(M.trackingContext=this,Pt(this)){this.isTrackPending=!0;try{this.onInvalidate_(),this.isTrackPending&&bn()&&xn({name:this.name_,type:`scheduled-reaction`})}catch(e){this.reportExceptionInDerivation_(e)}}M.trackingContext=e,on()}}track(e){if(this.isDisposed)return;an();let t=bn(),n;t&&(n=Date.now(),Sn({name:this.name_,type:`reaction`})),this.isRunning=!0;let r=M.trackingContext;M.trackingContext=this;let i=Lt(this,e,void 0);M.trackingContext=r,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Bt(this),Nt(i)&&this.reportExceptionInDerivation_(i.cause),t&&wn({time:Date.now()-n}),on()}reportExceptionInDerivation_(e){if(this.errorHandler_){this.errorHandler_(e,this);return}if(M.disableErrorBoundaries)throw e;let t=`[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '${this}'`;M.suppressReactionErrors?console.warn(`[mobx] (error in reaction '${this.name_}' suppressed, fix error of causing action below)`):console.error(t,e),bn()&&xn({type:`error`,name:this.name_,message:t,error:``+e}),M.globalReactionErrorHandlers.forEach(t=>t(e,this))}dispose(){if(!this.isDisposed){var e;this.isDisposed=!0,(e=this.removeAbortListener_)==null||e.call(this),this.isRunning||(an(),Bt(this),on())}}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[E]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.name_}]`}};function mn(e){return M.globalReactionErrorHandlers.push(e),()=>{let t=M.globalReactionErrorHandlers.indexOf(e);t>=0&&M.globalReactionErrorHandlers.splice(t,1)}}let hn=e=>e();function gn(){M.inBatch>0||M.isRunningReactions||hn(_n)}function _n(){M.isRunningReactions=!0;let e=M.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_()}M.isRunningReactions=!1}let vn=b(`Reaction`,pn);function yn(e){let t=hn;hn=n=>e(()=>t(n))}function bn(){return!!M.spyListeners.length}function xn(e){if(!M.spyListeners.length)return;let t=M.spyListeners;for(let n=0,r=t.length;n<r;n++)t[n](e)}function Sn(e){xn(r({},e,{spyReportStart:!0}))}let Cn={type:`report-end`,spyReportEnd:!0};function wn(e){xn(e?r({},e,{type:`report-end`,spyReportEnd:!0}):Cn)}function Tn(e){return M.spyListeners.push(e),d(()=>{M.spyListeners=M.spyListeners.filter(t=>t!==e)})}let N=`action`,En=`autoAction`,Dn=`<unnamed action>`,On=Se(N),kn=Se(`action.bound`,{bound:!0}),An=Se(En,{autoAction:!0}),jn=Se(`autoAction.bound`,{autoAction:!0,bound:!0});function Mn(e){return Xe(e,Te)}function Nn(e){return function(t,r){if(r&&typeof r.kind==`string`)return Te(e?An:On,t,r);if(p(t))return xt(t.name||Dn,t,e);if(p(r))return xt(t,r,e);if(m(t))return Mn(Se(e?En:N,{name:t,autoAction:e}));n("Invalid arguments for `action`")}}let Pn=Nn(!1);r(Pn,On);let Fn=Nn(!0);r(Fn,An);let In=Mn(kn),Ln=Mn(jn);function Rn(e){return St(e.name||Dn,!1,e,this,void 0)}function zn(e){return p(e)&&e.isMobxAction===!0}function Bn(e,t=c){var r;p(e)||n(`Autorun expects a function as first argument`),zn(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 pn(i,function(){this.track(s)},t.onError,t.requiresObservable);else{let e=Hn(t),n=!1;o=new pn(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 Vn=e=>e();function Hn(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Vn}function Un(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=Pn(a,r.onError?Wn(r.onError,t):t),s=!r.scheduler&&!r.delay,l=Hn(r),d=!0,f=!1,m,h=r.equals||pe,_=new pn(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=Tt(!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 Wn(e,t){return function(){try{return t.apply(this,arguments)}catch(t){e.call(this,t)}}}function Gn(e,t,n){return qn(`onBO`,e,t,n)}function Kn(e,t,n){return qn(`onBUO`,e,t,n)}function qn(e,t,n,r){let i=typeof r==`function`?Ai(t,n):Ai(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 Jn=`always`;function Yn(e){e.isolateGlobalState===!0&&Xt();let{enforceActions:t}=e;if(t!==void 0){let e=t===Jn?Jn:t===`observed`;M.enforceActions=e,M.allowStateChanges=!(e===!0||e===Jn)}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(M[t]=!!e[t])}),M.allowStateReads=!M.observableRequiresReaction,M.disableErrorBoundaries===!0&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),e.reactionScheduler&&yn(e.reactionScheduler)}function Xn(e,t,r,i){arguments.length>4&&n(`'extendObservable' expected 2-4 arguments`),typeof e!=`object`&&n(`'extendObservable' expects an object as first argument`),P(e)&&n(`'extendObservable' should not be used on maps, use map.merge instead`),g(t)||n(`'extendObservable' only accepts plain objects as second argument`),(xr(t)||xr(r))&&n(`Extending an object with another observable (object) is not supported`);let a=ae(t);return Ni(()=>{let t=wi(e,i)[E];te(a).forEach(e=>{t.extend_(e,a[e],r&&e in r?r[e]:!0)})}),e}function Zn(e,t){return Qn(Ai(e,t))}function Qn(e){let t={name:e.name_};return e.observing_&&e.observing_.length>0&&(t.dependencies=tr(e.observing_).map(Qn)),t}function $n(e,t){return er(Ai(e,t))}function er(e){let t={name:e.name_};return $t(e)&&(t.observers=Array.from(en(e),er)),t}function tr(e){return Array.from(new Set(e))}let nr=0;var rr=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};function ir(e){return e instanceof rr}function ar(e){return Xe(e,je)}let or=Oe(`flow`),sr=Oe(`flow.bound`,{bound:!0}),cr=r(function(e,t){if(t&&typeof t.kind==`string`)return je(or,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=++nr,a=Pn(`${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=Pn(`${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=Pn(`${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=Pn(`${i} - runid: ${n} - cancel`,function(){try{s&&ur(s);let e=a.return(void 0),t=Promise.resolve(e.value);t.then(f,f),ur(t),o(new rr)}catch(e){o(e)}}),c};return a.isMobXFlow=!0,a},or),lr=ar(sr);function ur(e){p(e.cancel)&&e.cancel()}function dr(e){return e}function fr(e){return e?.isMobXFlow===!0}function pr(e,t,r){let i;if(P(e)||pi(e)||kt(e))i=ji(e);else if(Di(e)){if(!m(t))return n(`InterceptReads can only be used with a specific property, not with an object in general`);i=ji(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 mr(e,t,n){return p(n)?gr(e,t,n):hr(e,t)}function hr(e,t){return qr(ji(e),t)}function gr(e,t,n){return qr(ji(e,t),n)}function _r(e,t){var n;if(t===void 0)return jt(e);if(Di(e)===!1)return!1;let r=e[E];return(n=r.lazyComputedKeys_)!=null&&n.has(t)?!0:r.values_.has(t)?jt(Ai(e,t)):!1}function vr(e){return arguments.length>1?n(`isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property`):_r(e)}function yr(e,t){return m(t)?_r(e,t):n(`isComputed expected a property name as second argument`)}function br(e,t){if(!e)return!1;if(t!==void 0){if(P(e)||pi(e))return n(`isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.`);if(Di(e)){var r,i;let n=e[E];return n.values_.has(t)||!!((r=n.lazyComputedKeys_)!=null&&r.has(t))||!!((i=n.lazyObservableKeys_)!=null&&i.has(t))}return!1}return Di(e)||!!e[E]||ce(e)||vn(e)||jt(e)}function xr(e){return arguments.length!==1&&n(`isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property`),br(e)}function Sr(e,t){return m(t)?br(e,t):n(`expected a property name as second argument`)}function Cr(e){if(Di(e))return e[E].keys_();if(P(e)||yi(e))return Array.from(e.keys());if(pi(e))return e.map((e,t)=>t);n(5)}function wr(e){if(Di(e))return Cr(e).map(t=>e[t]);if(P(e))return Cr(e).map(t=>e.get(t));if(yi(e))return Array.from(e.values());if(pi(e))return e.slice();n(6)}function Tr(e){if(Di(e))return Cr(e).map(t=>[t,e[t]]);if(P(e))return Cr(e).map(t=>[t,e.get(t)]);if(yi(e))return Array.from(e.entries());if(pi(e))return e.map((e,t)=>[t,e]);n(7)}function Er(e,t,r){if(arguments.length===2&&!yi(e)){an();let n=t;try{for(let t in n)Er(e,t,n[t])}finally{on()}return}Di(e)?e[E].set_(t,r):P(e)?e.set(t,r):yi(e)?e.add(t):pi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),t<0&&n(42,t),an(),t>=e.length&&(e.length=t+1),e[t]=r,on()):n(8)}function Dr(e,t){Di(e)?e[E].delete_(t):P(e)||yi(e)?e.delete(t):pi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),e.splice(t,1)):n(9)}function Or(e,t){if(Di(e))return e[E].has_(t);if(P(e)||yi(e))return e.has(t);if(pi(e))return t>=0&&t<e.length;n(10)}function kr(e,t){if(Or(e,t)){if(Di(e))return e[E].get_(t);if(P(e))return e.get(t);if(pi(e))return e[t];n(11)}}function Ar(e,t,r){if(Di(e))return e[E].defineProperty_(t,r);n(39)}function jr(e){if(Di(e))return e[E].ownKeys_();n(38)}function Mr(e,t,n,r){return p(n)?Pr(e,t,n,r):Nr(e,t,n)}function Nr(e,t,r){let i=ji(e);if(pi(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(P(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with maps.");else if(yi(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with sets.");else if(Di(e))r===!0&&n("`observe` doesn't support the fire immediately property for observable objects.");else return Fr(i,t,r);return Xr(i,t)}function Pr(e,t,n,r){return Fr(ji(e,t),n,r)}function Fr(e,t,n){if(jt(e)){let r=!0,i;return Bn(()=>{let a=e.get();if(!r||n){let n=Ht();t({observableKind:`computed`,debugObjectName:e.name_,type:ri,object:e,newValue:a,oldValue:i}),Ut(n)}r=!1,i=a})}return n&&t({observableKind:`value`,debugObjectName:e.name_,object:e,type:ri,newValue:e.value_,oldValue:void 0}),Xr(e,t)}function Ir(e,t,n){return e.set(t,n),n}function Lr(e,t){if(typeof e!=`object`||!e||e instanceof Date||!xr(e))return e;if(kt(e)||jt(e))return Lr(e.get(),t);if(t.has(e))return t.get(e);if(pi(e)){let n=Ir(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=Lr(e,t)}),n}if(yi(e)){let n=Ir(t,e,new Set);return e.forEach(e=>{n.add(Lr(e,t))}),n}if(P(e)){let n=Ir(t,e,new Map);return e.forEach((e,r)=>{n.set(r,Lr(e,t))}),n}else{let n=Ir(t,e,{});return jr(e).forEach(r=>{o.propertyIsEnumerable.call(e,r)&&(n[r]=Lr(e[r],t))}),n}}function Rr(e,t){return t&&n(`toJS no longer supports options`),Lr(e,new Map)}function zr(e,t=void 0){an();try{return e.apply(t)}finally{on()}}function Br(e,t,n){return arguments.length===1||t&&typeof t==`object`?Hr(e,t):Vr(e,t,n||{})}function Vr(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[E].isDisposed)if(a(),n.onError)n.onError(e);else throw e},n.timeout)}n.name=n.name||`When@`+u();let i=xt(n.name+`-effect`,t);var a=Bn(t=>{Tt(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function Hr(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=Vr(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 Ur(e){return e[E]}let Wr={has(e,t){return Ur(e).has_(t)},get(e,t){return Ur(e).get_(t)},set(e,t,n){return m(t)?Ur(e).set_(t,n,!0)??!0:!1},deleteProperty(e,t){return m(t)?Ur(e).delete_(t,!0)??!0:!1},defineProperty(e,t,n){return Ur(e).defineProperty_(t,n)??!0},ownKeys(e){return Ur(e).ownKeys_()},preventExtensions(e){n(13)}};function Gr(e,t){var n;return e=wi(e,t),(n=e[E]).proxy_??(n.proxy_=new Proxy(e,Wr))}function Kr(e){return e.interceptors_!==void 0&&e.interceptors_.length>0}function qr(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 Jr(e,t){let r=Ht();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{Ut(r)}}function Yr(e){return e.changeListeners_!==void 0&&e.changeListeners_.length>0}function Xr(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 Zr(e,t){let n=Ht(),r=e.changeListeners_;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Ut(n)}}function Qr(e,t,n){return Ni(()=>{let r=wi(e,n)[E];te(t).forEach(e=>ti(r,e,t[e]))}),e}let $r=Symbol(`mobx-keys`);function ei(e,t,r){return!g(e)&&!g(Object.getPrototypeOf(e))&&n(`'makeAutoObservable' can only be used for classes that don't have a superclass`),Di(e)&&n(`makeAutoObservable can only be used on objects not already made observable`),g(e)?Xn(e,e,t,r):(Ni(()=>{let n=wi(e,r)[E];if(!e[$r]){let t=Object.getPrototypeOf(e),n=new Set([...te(e),...te(t)]);n.delete(`constructor`),n.delete(E),v(t,$r,n)}e[$r].forEach(e=>ti(n,e,t&&e in t?t[e]:!0))}),e)}function ti(e,t,r){if(r===!0&&(r=e.defaultAnnotation_),r===!1)return;ki(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)}Oi(e,r,t)}let ni=`splice`,ri=`update`,ii={get(e,t){let n=e[E];return t===E?n:t===`length`?n.getArrayLength_():typeof t==`string`&&!isNaN(t)?n.get_(parseInt(t)):ie(si,t)?si[t]:e[t]},set(e,t,n){let r=e[E];return t===`length`?r.setArrayLength_(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.set_(parseInt(t),n),!0},preventExtensions(){n(15)}};var ai=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 se(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){A(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),Kr(this)){let r=Jr(this,{object:this.proxy_,type:ni,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_&&bn(),i=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,type:ri,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(this,a),r&&wn()}notifyArraySplice_(e,t,n){let r=!this.owned_&&bn(),i=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,debugObjectName:this.atom_.name_,type:ni,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(this,a),r&&wn()}get_(e){return this.atom_.reportObserved(),this.dehanceValue_(this.values_[e])}set_(e,t){let n=this.values_;if(e<n.length){A(this.atom_);let r=n[e];if(Kr(this)){let n=Jr(this,{type:ri,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 oi(e,t,n=`ObservableArray@`+u(),r=!1){return Ni(()=>{let i=new ai(n,t,r);y(i.values_,E,i);let a=new Proxy(i.values_,ii);return i.proxy_=a,e&&e.length&&i.spliceWithArray_(0,0,e),a})}var si={clear(){return this.splice(0)},replace(e){let t=this[E];return t.spliceWithArray_(0,t.values_.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[E];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[E].spliceWithArray_(e,t,n)},push(...e){let t=this[E];return t.spliceWithArray_(t.values_.length,0,e),t.values_.length},pop(){return this.splice(Math.max(this[E].values_.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[E];return t.spliceWithArray_(0,0,e),t.values_.length},reverse(){return M.trackingDerivation&&n(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){M.trackingDerivation&&n(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[E],n=t.dehanceValues_(t.values_).indexOf(e);return n>-1?(this.splice(n,1),!0):!1}};ci(`at`,li),ci(`concat`,li),ci(`flat`,li),ci(`includes`,li),ci(`indexOf`,li),ci(`join`,li),ci(`lastIndexOf`,li),ci(`slice`,li),ci(`toString`,li),ci(`toLocaleString`,li),ci(`toSorted`,li),ci(`toSpliced`,li),ci(`with`,li),ci(`every`,ui),ci(`filter`,ui),ci(`find`,ui),ci(`findIndex`,ui),ci(`findLast`,ui),ci(`findLastIndex`,ui),ci(`flatMap`,ui),ci(`forEach`,ui),ci(`map`,ui),ci(`some`,ui),ci(`toReversed`,ui),ci(`reduce`,di),ci(`reduceRight`,di);function ci(e,t){typeof Array.prototype[e]==`function`&&(si[e]=t(e))}function li(e){return function(){let t=this[E];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_);return n[e].apply(n,arguments)}}function ui(e){return function(t,n){let r=this[E];return r.atom_.reportObserved(),r.dehanceValues_(r.values_)[e]((e,r)=>t.call(n,e,r,this))}}function di(e){return function(){let t=this[E];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 fi=b(`ObservableArrayAdministration`,ai);function pi(e){return h(e)&&fi(e[E])}let mi={},hi=`delete`;var gi=class{constructor(e,t=me,n=`ObservableMap@`+u()){this.enhancer_=void 0,this.name_=void 0,this[E]=mi,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,Ni(()=>{this.keysAtom_=le(`${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(!M.trackingDerivation)return this.has_(e);let t=this.hasMap_.get(e);if(!t){let n=t=new Ot(this.has_(e),ge,`${this.name_}.${ne(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(Kr(this)){let r=Jr(this,{type:n?ri:`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(A(this.keysAtom_),Kr(this)&&!Jr(this,{type:hi,object:this,name:e}))return!1;if(this.has_(e)){let t=bn(),n=Yr(this),r=n||t?{observableKind:`map`,debugObjectName:this.name_,type:hi,object:this,oldValue:this.data_.get(e).value_,name:e}:null;return t&&Sn(r),zr(()=>{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&&Zr(this,r),t&&wn(),!0}return!1}updateValue_(e,t){let n=this.data_.get(e);if(t=n.prepareNewValue_(t),t!==M.UNCHANGED){let r=bn(),i=Yr(this),a=i||r?{observableKind:`map`,debugObjectName:this.name_,type:ri,object:this,oldValue:n.value_,name:e,newValue:t}:null;r&&Sn(a),n.setNewValue_(t),i&&Zr(this,a),r&&wn()}}addValue_(e,t){A(this.keysAtom_),zr(()=>{var n;let r=new Ot(t,this.enhancer_,`${this.name_}.${ne(e)}`,!1);this.data_.set(e,r),t=r.value_,(n=this.hasMap_.get(e))==null||n.setNewValue_(!0),this.keysAtom_.reportChanged()});let n=bn(),r=Yr(this),i=r||n?{observableKind:`map`,debugObjectName:this.name_,type:`add`,object:this,name:e,newValue:t}:null;n&&Sn(i),r&&Zr(this,i),n&&wn()}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 F({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 F({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 P(e)&&(e=new Map(e)),zr(()=>{g(e)?ee(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):x(e)?(S(e)||n(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&n(20,e)}),this}clear(){zr(()=>{Vt(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return zr(()=>{let t=I(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`}},P=b(`ObservableMap`,gi);function F(e){return e[Symbol.toStringTag]=`MapIterator`,zi(e)}function I(e){if(x(e)||P(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 _i={};var vi=class{constructor(e,t=me,n=`ObservableSet@`+u()){this.name_=void 0,this[E]=_i,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),Ni(()=>{this.atom_=le(this.name_),e&&this.replace(e)})}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){zr(()=>{Vt(()=>{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(A(this.atom_),Kr(this)){let t=Jr(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){zr(()=>{e=this.enhancer_(e,void 0),this.data_.add(e),this.atom_.reportChanged()});let t=bn(),n=Yr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:`add`,object:this,newValue:e}:null;t&&Sn(r),n&&Zr(this,r),t&&wn()}return this}delete(e){if(Kr(this)&&!Jr(this,{type:hi,object:this,oldValue:e}))return!1;if(this.has(e)){let t=bn(),n=Yr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:hi,object:this,oldValue:e}:null;return t&&Sn(r),zr(()=>{this.atom_.reportChanged(),this.data_.delete(e)}),n&&Zr(this,r),t&&wn(),!0}return!1}has(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))}entries(){let e=this.values();return bi({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 bi({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 yi(e)&&(e=new Set(e)),Array.isArray(e)||C(e)?zr(()=>{let t=C(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`}},yi=b(`ObservableSet`,vi);function bi(e){return e[Symbol.toStringTag]=`SetIterator`,zi(e)}let xi=Object.create(null),Si=`remove`;var Ci=class{constructor(e,t=new Map,r,i=We){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 se(`${this.name_}.keys`),this.isPlainObject_=g(this.target_),Vi(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 At)return n.set(t),!0;if(Kr(this)){let n=Jr(this,{type:ri,object:this.proxy_||this.target_,name:e,newValue:t});if(!n)return null;t=n.newValue}if(t=n.prepareNewValue_(t),t!==M.UNCHANGED){let r=Yr(this),i=bn(),a=r||i?{type:ri,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,oldValue:n.value_,name:e,newValue:t}:null;i&&Sn(a),n.setNewValue_(t),r&&Zr(this,a),i&&wn()}return!0}get_(e){return M.trackingDerivation&&!ie(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return ie(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(!M.trackingDerivation)return e in this.target_;this.pendingKeys_||=new Map;let t=this.pendingKeys_.get(e);return t||(t=new Ot(e in this.target_,ge,`${this.name_}.${ne(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);ki(this,n,e);let i=n.extend_(this,e,t,r);return i&&Oi(this,n,e),i}defineProperty_(e,t,n=!1){A(this.keysAtom_);try{an();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=Jr(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{on()}return!0}defineObservableProperty_(e,t,n,r=!1){A(this.keysAtom_);try{an();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=Jr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let o=Ei(e),s={configurable:M.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 Ot(t,n,`${this.name_}.${e.toString()}`,!1);this.values_.set(e,c),this.notifyPropertyAddition_(e,c.value_)}finally{on()}return!0}defineComputedProperty_(e,t,n=!1){A(this.keysAtom_);try{an();let r=this.delete_(e);if(!r)return r;if(Kr(this)&&!Jr(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=Ei(e),o={configurable:M.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 At(t)),this.notifyPropertyAddition_(e,void 0)}finally{on()}return!0}delete_(e,t=!1){if(A(this.keysAtom_),!ie(this.target_,e))return!0;if(Kr(this)&&!Jr(this,{object:this.proxy_||this.target_,name:e,type:Si}))return null;try{var n;an();let r=Yr(this),a=bn(),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 Ot&&(s=o.value_),un(o)),this.keysAtom_.reportChanged(),(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(e in this.target_),r||a){let t={type:Si,observableKind:`object`,object:this.proxy_||this.target_,debugObjectName:this.name_,oldValue:s,name:e};a&&Sn(t),r&&Zr(this,t),a&&wn()}}finally{on()}return!0}notifyPropertyAddition_(e,t){var n;let r=Yr(this),i=bn();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&&Sn(n),r&&Zr(this,n),i&&wn()}(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(!0),this.keysAtom_.reportChanged()}ownKeys_(){return this.keysAtom_.reportObserved(),te(this.target_)}keys_(){return this.keysAtom_.reportObserved(),Object.keys(this.target_)}};function wi(e,t){if(t&&Di(e)&&n(`Options can't be provided for already observable objects.`),ie(e,E))return ji(e)instanceof Ci||n(`Cannot convert '${Mi(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,E,new Ci(e,new Map,String(r),at(t))),e}let Ti=b(`ObservableObjectAdministration`,Ci);function Ei(e){return xi[e]||(xi[e]={get(){return this[E].getObservablePropValue_(e)},set(t){return this[E].setObservablePropValue_(e,t)}})}function Di(e){return h(e)?Ti(e[E]):!1}function Oi(e,t,n){e.appliedAnnotations_[n]=t}function ki(e,t,r){if(Vi(t)||n(`Cannot annotate '${e.name_}.${r.toString()}': Invalid annotation.`),!be(t)&&ie(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 Ai(e,t){if(typeof e==`object`&&e){if(pi(e))return t!==void 0&&n(23),e[E].atom_;if(yi(e))return e.atom_;if(P(e)){if(t===void 0)return e.keysAtom_;let r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,Mi(e)),r}if(Di(e)){if(!t)return n(26);let r=e[E],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,Mi(e)),i}if(ce(e)||jt(e)||vn(e))return e}else if(p(e)&&vn(e[E]))return e[E];n(28)}function ji(e,t){if(e||n(29),t!==void 0)return ji(Ai(e,t));if(ce(e)||jt(e)||vn(e)||P(e)||yi(e))return e;if(e[E])return e[E];n(24,e)}function Mi(e,t){let n;if(t!==void 0)n=Ai(e,t);else if(zn(e))return e.name;else n=Di(e)||P(e)||yi(e)?ji(e):Ai(e);return n.name_}function Ni(e){let t=Ht(),n=Et(!0);an();try{return e()}finally{on(),Dt(n),Ut(t)}}let Pi=o.toString;function Fi(e,t,n=-1){return Ii(e,t,n)}function Ii(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=Pi.call(e);if(o!==Pi.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=Li(e),t=Li(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(!Ii(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(!(ie(t,o)&&Ii(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function Li(e){return pi(e)?e.slice():x(e)||P(e)||C(e)||yi(e)?Array.from(e.entries()):e}let Ri=globalThis.Iterator?.prototype||{};function zi(e){return e[Symbol.iterator]=Bi,r(Object.create(Ri),e)}function Bi(){return this}function Vi(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:Tn,extras:{getDebugName:Mi},$mobx:E}),e.$mobx=E,e.FlowCancellationError=rr,e.ObservableMap=gi,e.ObservableSet=vi,e.Reaction=pn,e._allowStateChanges=Tt,e._allowStateChangesInsideComputed=Rn,e._allowStateReadsEnd=Wt,e._allowStateReadsStart=j,e._autoAction=Fn,e._autoActionBound=Ln,e._endAction=wt,e._getAdministration=ji,e._getGlobalState=Zt,e._interceptReads=pr,e._isComputingDerivation=Ft,e._resetGlobalState=Qt,e._startAction=Ct,e.action=Pn,e.actionBound=In,e.autorun=Bn,e.compareDefault=pe,e.compareIdentity=ue,e.compareShallow=fe,e.compareStructural=de,e.computed=k,e.computedStruct=gt,e.configure=Yn,e.createAtom=le,e.defineProperty=Ar,e.entries=Tr,e.extendObservable=Xn,e.flow=cr,e.flowBound=lr,e.flowResult=dr,e.get=kr,e.getAtom=Ai,e.getDebugName=Mi,e.getDependencyTree=Zn,e.getObserverTree=$n,e.has=Or,e.intercept=mr,e.isAction=zn,e.isBoxedObservable=kt,e.isComputed=vr,e.isComputedProp=yr,e.isFlow=fr,e.isFlowCancellationError=ir,e.isObservable=xr,e.isObservableArray=pi,e.isObservableMap=P,e.isObservableObject=Di,e.isObservableProp=Sr,e.isObservableSet=yi,e.keys=Cr,e.makeAutoObservable=ei,e.makeObservable=Qr,e.observable=O,e.observableDeep=dt,e.observableRef=lt,e.observableShallow=ut,e.observableStruct=ft,e.observe=Mr,e.onBecomeObserved=Gn,e.onBecomeUnobserved=Kn,e.onReactionError=mn,e.override=ye,e.ownKeys=jr,e.reaction=Un,e.remove=Dr,e.runInAction=Rn,e.set=Er,e.spy=Tn,e.toJS=Rr,e.transaction=zr,e.untracked=Vt,e.values=wr,e.when=Br})),P_=ye(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=M_():t.exports=N_()}))();function F_(e){if(Array.isArray(e))return Object.freeze(e.map(F_));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]=F_(r);return Object.freeze(t)}return e}function I_(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 L_(e){return typeof e==`string`?e:String(e)}function R_(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 z_(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 B_=class extends Error{constructor(e,t){super(t),this.variable=e}};function V_(e){return e instanceof B_||e instanceof Error&&e.cause!==void 0&&V_(e.cause)}var H_=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?Z_(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}},U_=class extends H_{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},W_=class extends H_{name=`EvalError`;kind=`EvalError`},G_=class extends W_{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=Q_(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}},K_=class extends W_{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}},q_=class extends W_{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}},J_=class extends q_{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)}`}},Y_=class extends W_{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},X_=class extends W_{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function Z_(e,t){let n=e.split(`
56
+ `))}function Bh(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new H({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new G(e,{style:t,end:``,overflow:`ignore`}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(re(a.path).href)):c(`full text unavailable: ${Hf(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(Hf(o),s.withLink(re(o).href))],d=[c(`↳ `,s),...l,...u.slice(0,-1)],f=d.reduce((e,t)=>e+t.cellLength,0),p=u.slice(-1).map(e=>e.truncate(Math.max(1,r.width-f),{mode:`middle`})),m=G.fromFragments([...d,...p]).truncate(r.width);return m.overflow=`ignore`,Oh([m],r)}const Vh=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Hh(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function Uh(e,t){return r.readdirSync(t).filter(Vh).sort().flatMap(n=>{let i=l.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?Uh(e,i):[[l.relative(e,i).split(l.sep).join(`/`),Hh(i,a)]]})}function Wh(e){let t=ie.createHash(`sha256`);for(let[n,r]of Uh(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const Gh=e=>e.slice(0,7);function Kh(e){return l.dirname(l.dirname(e))}function qh(){let e=Jh();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Et,digest:e}}function Jh(){return`8fb64dc033fdd2058fd9e969729e9dbadb649ac1d2e9f12be839ba4d123a081d`}function Yh(e){let t=JSON.parse(r.readFileSync(l.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${l.join(e,`package.json`)} has no version string`);return n}function Xh(e,t){try{let n=Kh(ne(e)),i=l.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=Wh(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:Yh(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var K=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};const Zh=new Map;function Qh(e){let t=eg(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 $h(e,t){return e===`bar`?t:Qh(e)}function eg(e){let t=Zh.get(e);if(t!==void 0)return t;let n=jc(e);return n===null?null:(Zh.set(e,n),n)}function tg(e,t){return ng(e,`${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,()=>Uc(e,t))}const ng=Yf();function rg(e){let t=eg(e);return t===null?null:{kind:`decided`,name:e,value:t}}function ig(e,t,n){let r=rg(e);return r===null?(n(wm(t,`palette`,`"${e}" names no installed theme${om(e)}`)),og()):r}function ag(e,t,n){return gm(e,t,n,og(),rg)}function og(){return{kind:`decided`,name:sm,value:Qh(sm)}}const sg=[`vertical`,`horizontal`],cg={vertical:`row`,horizontal:`cell`};function lg(e){return e.id??e.name}function ug(e){return[...pg(e)].flatMap(e=>e.kind===`segment`?[lg(e)]:[])}function dg(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function fg(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*pg(e){yield e;for(let t of _g(e))yield*pg(t)}const mg=(e,t)=>`${e}.children[${t}]`,hg=e=>`${e}.opens.body`;function*gg(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*gg(r,mg(t,n));else e.opens!==void 0&&(yield*gg(e.opens.body,hg(t)))}function _g(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}const vg=[`shade`,`variation`,`style`];function yg(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const bg=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function xg(e){return e.kind===`file`||e.kind===`shell`}const Sg=[`branch`,`sha`,`dirty`,`ahead`,`behind`,`stash`];function*Cg(e){for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&(yield[t,n]);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&(yield[`${t}.${e}`,r])}const wg=`theme`,Tg=`effect`,Eg=[wg,Tg];function Dg(e){return{...e.settings,[wg]:{label:wg,domain:`theme`,default:e.palette??`bar`},[Tg]:{label:Tg,domain:Em,default:`bar`}}}function Og(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function kg(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=Og(r)?.atLeast;if(i===void 0)return[];let a=t[n],o=t[i];return a>=o?[]:[{setting:n,message:`"${n}" (${a}) is below "${i}" (${o}) — ${r.label} must be at least ${e[i].label}`}]})}function Ag(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&fm(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function jg(e){return String(e)}function Mg(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return Zm(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return Ag(e,r)?r:void 0}function Ng(e,t,n,r){let i=e.settings?.[t]??n.default,a=e.drafts?.[t],o=a===void 0?null:r(a);return(o===null?void 0:Mg(n,o))??i}function Pg(e){let{domain:t}=e;return t===`bool`?`true or false`:t===`theme`?`"bar" (the bar's own theme) or an installed theme name`:`min`in t?`an integer from ${t.min} to ${t.max}`:`one of ${t.map(e=>JSON.stringify(e)).join(`, `)}`}const Fg=[`left`,`center`,`right`],Ig=[`right`,`left`,`middle`],Lg=/^[A-Za-z_][A-Za-z0-9_]*$/;function Rg(e){return`#${e+1}`}const zg={rows:{}};function Bg(e){return`rows`in e}function Vg(e){return Object.fromEntries(e.map((e,t)=>[Rg(t),e]))}function Hg(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:Vg(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:Vg([n])}}function Ug(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function Wg(e){return Bg(e)?Ug(e):e}function*Gg(e,t){if(!Bg(e)){yield*gg(e,t);return}yield[Ug(e),t];for(let[n,r]of Object.entries(e.rows))yield*gg(r,`${t}.rows.${n}`)}function Kg(e,t){return Bg(e)?{...t,...e,rows:{...t.rows,...e.rows}}:Hg(e)}function qg(e){if(!Bg(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}const Jg=`default`,Yg={};function Xg(e){return[...new Set([Jg,...Object.keys(e)])]}function Zg(e,t,n){return pm(void 0,e,t,Jg,n)}function Qg(e,t){let n={[Jg]:Yg,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${Jg}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function $g(e,t){let n=Qg(e.presets,t).root??zg;return{node:Ug(Kg(n,e.root)),path:qg(n)?`presets.${t}.root`:`root`}}function e_(e,t){return{...e.globals,...Qg(e.presets,t).globals}}const t_=new Map;function n_(e,t,n){t_.set(e,{permanent:!0,resolve:t,paletteOf:n})}n_(`themes`,()=>lm(),e=>Qh(e));const r_=`placementThemes`;n_(r_,um,(e,t)=>$h(e,t.palette)),n_(`endcaps`,()=>Am),n_(`variations`,()=>Bm),n_(`shades`,()=>Um),n_(`charsets`,()=>Fm),n_(`colorCompatibilities`,()=>Rm);function i_(e){return new Map([[`styles`,{members:Object.keys(e.styles),paletteOf:(t,n)=>tg(n.basePalette,e.styles[t])}],[`presets`,{members:Xg(e.presets)}]])}function a_(e){return[...new Set([...t_.keys(),...e.keys()])]}function o_(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=t_.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf};throw Error(c_(e,t))}const s_=new Map([[`looks`,`styles`],[`progressions`,`variations`]]);function c_(e,t){let n=s_.get(e);return`unknown option domain "${e}"${n===void 0?``:` — it was renamed "${n}"; write from: "${n}"`} (have: ${a_(t).join(`, `)})`}const l_=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g;function*u_(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 d_=`[A-Za-z_]\\w*(?:\\.[A-Za-z_]\\w*)*`,f_=RegExp(`^(?:(\\$)(?:\\.(${d_}))?|\\.(${d_})?)(?=[\\s)]|$)`);function p_(e,t,n){let r=f_.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 m_=/^(\w+)\b\s*([\s\S]*)$/;function*h_(e,t){let n=[t];for(let r of u_(e)){let e=r.replace(/^-(?=\s)/,``).trim(),[,i=``,a=``]=m_.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:p_(r[1],s,t);continue}yield{code:e,dot:o},i===`if`&&n.push(o),i===`with`&&n.push(p_(a,o,t)),(i===`range`||i===`define`||i===`block`)&&n.push(null)}}const g_=/(?<![.$])\btemplate\s+$/;function*__(e,t,n){let r=0;for(let i of[...e.matchAll(l_)]){let a=i.index+i[0].length;g_.test(e.slice(r,i.index))&&(yield{name:i[0].slice(1,-1),at:p_(e.slice(a),t,n)}),r=a}}function*v_(e,t){let n=new Set;function*r(e,i,a,o){for(let{code:s,dot:c}of[...h_(e,i)]){yield{code:s,dot:c,root:i,via:a};for(let e of[...__(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 y_=RegExp(`(?<![A-Za-z0-9_)$])(\\$?)\\.(${d_})`,`g`);function*b_({code:e,dot:t,root:n}){let r=e.replace(l_,``);for(let e of[...r.matchAll(y_)]){let r=e[1]===`$`?n:t;r!==null&&(yield`${r}${e[2]}`)}}function x_(e,t){let n=new Map;for(let r of v_(e,t))for(let e of b_(r))n.has(e)||n.set(e,r.via);return n}const S_=/(?<![.$])\b(action|picker|menu|carousel|swatches|swatch|themePreview)\s+$/,C_={action:1,picker:2,menu:1,carousel:2,swatch:1,swatches:2,themePreview:1};function*w_(e){let t=0,n=0,r=0,i=`action`;for(let a of[...e.matchAll(l_)]){let o=e.slice(t,a.index),s=S_.exec(o);if(s!==null)n=C_[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 T_(e,t){let n=new Map;for(let{code:r,via:i}of v_(e,t))for(let{name:e,site:t}of w_(r)){let r=`${e}\0${i??`\0`}`;n.has(r)||n.set(r,{name:e,site:t,via:i})}return[...n.values()]}function E_(e,t){return new Set([...D_(e,t)].filter(e=>Object.hasOwn(t,e)))}function D_(e,t){let n=new Set;for(let{code:r,dot:i,root:a}of v_(e,t))for(let{name:e}of __(r,i,a))n.add(e);return n}function O_(e,t){if(t.names.has(e))return!0;let n=`${e}.`;for(let e of t.names)if(e.startsWith(n))return!0;for(let n of t.documents)if(e.startsWith(`${n}.`))return!0;return!1}function k_(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),A_(r)&&n.add(e)};for(let[t,n]of Object.entries(e.variables))r(t,n);for(let[t,n]of Object.entries(e.segments))for(let[e,i]of Object.entries(n.vars??{}))r(`${t}.${e}`,i);return{names:t,documents:n,helpers:e.helpers}}function A_(e){return e.kind===`dropped`||(e.kind===`shell`||e.kind===`file`)&&yg(e.parse)===`json`}function j_(e){let t=l.basename(e),n=l.dirname(e);for(;;){let r=M_(n);if(r!==null)return{dir:r,name:t,leaf:n===l.dirname(e)};t=l.basename(n),n=l.dirname(n)}}function M_(e){try{return r.statSync(e).isDirectory()?r.realpathSync(e):null}catch{return null}}var N_=ye((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()===Bt}function s(e){let t=e?.constructor;return!!t&&(t.name===`GeneratorFunction`||t.displayName===`GeneratorFunction`)}function c(e,t,n){It(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 Lt.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=Vt,n=Vt){let r=new Wt(e);return t!==Vt&&(r.onBOL=new Set([t])),n!==Vt&&(r.onBUOL=new Set([n])),r}function _(e,t){return At(e,t)}function v(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||tt(e)?e:Array.isArray(e)?sn.array(e,{name:n}):o(e)?sn.object(e,void 0,{name:n}):u(e)?sn.map(e,{name:n}):d(e)?sn.set(e,{name:n}):typeof e!=`function`||We(e)||Qe(e)?e:s(e)?Gn(e):Ln(n,e)}function y(e){return e}function b(e,t){return{t:e,i:t,o:x,u:S}}function x(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:We(n.value)?1:(It(r,t,ee(e,this,t,n,!1)),2)}function S(e,t,n,r){let i=ee(e,this,t,n);return e.l(t,i,r)}function C(e,n,r){let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>{var t;return ye(s.i?.name??a.toString(),e,(t=s.i?.autoAction)!=null&&t)};return i==`field`?function(e){var t;let n=e;return We(n)||(n=c(n)),(t=s.i)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n}:i==`method`?(We(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 ee(e,t,n,r,i=N.safeDescriptors){var a,o,s;let{value:c}=r;return(a=t.i)!=null&&a.bound&&(c=c.bind(e.v??e.h)),{value:ye(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 te(e,t){return{t:e,i:t,o:ne,u:re}}function ne(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)||!Qe(e.h[t]))&&this.u(e,t,n,!1)===null?0:Qe(n.value)?1:(It(r,t,ae(e,0,0,n,!1,!1)),2)}function re(e,t,n,r){let i=ae(e,0,0,n,this.i?.bound);return e.l(t,i,r)}function ie(e,t,n){var r;let{name:i,addInitializer:a}=n;return Qe(t)||(t=Gn(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 ae(e,t,n,r,i,a=N.safeDescriptors){let{value:o}=r;return Qe(o)||(o=Gn(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:T,u:oe}}function T(e,t,n){return this.u(e,t,n,!1)===null?0:1}function oe(e,t,n,r){return e.m(t,Ft({},this.i,{get:n.get,set:n.set}),r)}function E(e,t,n){function r(e){let n=Ft({},i.i,{get:t,context:e});return n.name||=`ObservableObject.${a.toString()}`,new yn(n)}let i=e,{name:a,addInitializer:o}=n,s;return o(function(){let e=Ct(this)[j],n=this,i=e.j.get(a);i instanceof yn&&i.derivation!==t&&e.j.delete(a),(e.O??=new Map).set(a,()=>r(n))}),function(){let e=this[j],n=e.j.get(a);if(n instanceof yn&&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 se(e,t){return{t:e,i:t,o:ce,u:le}}function ce(e,t,n){return this.u(e,t,n,!1)===null?0:1}function le(e,t,n,r){return e.S(t,n.value,this.i?.A??v,r)}function ue(e,t,n){function r(e,t){let n=Ct(e)[j];return(n.V??=new Map).set(o,()=>new _n(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[j]??r(this,t.get.call(this)))._(o)},set(e){return(this[j]??r(this,e)).M(o,e)},init(e){return r(this,e),e}}}function de(e){return{t:Jt,i:e,o:fe,u:pe}}function fe(e,t,n,r){var i,a,o;if(n.get)return dn.o(e,t,n,r);if(n.set){let i=We(n.set)?n.set:ye(t.toString(),n.set);return r===e.h?e.l(t,{configurable:!N.safeDescriptors||e.p,set:i})===null?0:2:(It(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?Kn:Gn).o(e,t,n,r):((a=this.i)!=null&&a.autoBind?zn:Ln).o(e,t,n,r);let c=!1===this.i?.deep?nn:sn;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 pe(e,t,n,r){var i;return n.get?dn.u(e,t,n,r):n.set?e.l(t,{configurable:!N.safeDescriptors||e.p,set:ye(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?nn:sn).u(e,t,n,r))}function me(e,t){return Ft(function(n,r){if(r&&typeof r.kind==`string`)return t(e,n,r)},e)}function he(e){return e||Xt}function ge(e){return me(e,ue)}function _e(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 ve(e){return me(e,E)}function ye(e,t,n=!1,r){function i(){return be(0,n,t,r||this,arguments)}return i.isMobxAction=!0,i.toString=()=>t.toString(),hn&&(gn.value=e,It(i,`name`,gn)),i}function be(e,t,n,r,i){let a=xe(0,t);try{return n.apply(r,i)}catch(e){throw a.N=e,e}finally{D(a)}}function xe(e,t){let n=N.trackingDerivation,r=!t||!n;Pe();let i=N.allowStateChanges;r&&Oe();let a={R:r,k:n,C:i,I:N.allowStateReads,P:!1,T:0,B:mn++,D:pn};return pn=a.B,a}function D(e){pn!==e.B&&t(30),pn=e.D,e.N!==void 0&&(N.suppressReactionErrors=!0),Fe(),e.R&&ke(e.k),N.suppressReactionErrors=!1}function Se(e,t){let n=function(e){let t=N.allowStateChanges;return N.allowStateChanges=e,t}(e);try{return t()}finally{(function(e){N.allowStateChanges=e})(n)}}function Ce(e){return e instanceof xn}function we(e){switch(e.K){case 0:return!1;case-1:case 2:return!0;case 1:{let t=Oe(),n=e.L,r=n.length;for(let i=0;i<r;i++){let r=n[i];if(bn(r)){if(N.disableErrorBoundaries)r.get();else try{r.get()}catch{return ke(t),!0}if(e.K===2)return ke(t),!0}}return Ae(e),ke(t),!1}}}function Te(e,t,n){Ae(e),e.$=Array(e.U===0?100:e.L.length),e.W=0,e.U=++N.runId;let r=N.trackingDerivation,i;if(N.trackingDerivation=e,N.inBatch++,!0===N.disableErrorBoundaries)i=t.call(n);else try{i=t.call(n)}catch(e){i=new xn(e)}return N.inBatch--,N.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&&Me(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,je(t,e))}r!==0&&(e.K=r,e.q())}(e),i}function Ee(e){let t=e.L;e.L=[];let n=t.length;for(;n--;)Me(t[n],e);e.K=-1}function De(e){let t=Oe();try{return e()}finally{ke(t)}}function Oe(){let e=N.trackingDerivation;return N.trackingDerivation=null,e}function ke(e){N.trackingDerivation=e}function Ae(e){if(e.K===0)return;e.K=0;let t=e.L,n=t.length;for(;n--;)t[n].F=0}function je(e,t){(e.H??=new Set).add(t),e.F>t.K&&(e.F=t.K)}function Me(e,t){let n=e.H;n&&(n.delete(t),n.size===0&&Ne(e))}function Ne(e){!1===e.isPendingUnobservation&&(e.isPendingUnobservation=!0,N.pendingUnobservations.push(e))}function Pe(){N.inBatch++}function Fe(){--N.inBatch===0&&(ze(),!N.isRunningUnobservations&&N.pendingUnobservations.length>0&&function(){N.isRunningUnobservations=!0;try{let e=N.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 yn&&n.G())}N.pendingUnobservations=[]}finally{N.isRunningUnobservations=!1}}())}function Ie(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.L)==null||t.forEach(Ie))}function Le(e){let t=N.trackingDerivation;return t===null?((!e.H||e.H.size===0)&&N.inBatch>0&&Ne(e),!1):(t.U!==e.J&&(e.J=t.U,t.$[t.W++]=e,!e.isBeingObserved&&N.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function Re(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 ze(){N.inBatch>0||N.isRunningReactions||On(Be)}function Be(){N.isRunningReactions=!0;let e=N.pendingReactions,t=0;for(;e.length>0;){++t===Dn&&(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()}N.isRunningReactions=!1}function Ve(e){return me(e,C)}function He(e){return function(t,n){return n&&typeof n.kind==`string`?C(e?Pn:Mn,t,n):r(t)?ye(t.name||`<unnamed action>`,t,e):r(n)?ye(t,n,e):i(t)?Ve(b(e?jn:An,{name:t,autoAction:e})):void 0}}function Ue(e){return be(0,!1,e,this,void 0)}function We(e){return r(e)&&!0===e.isMobxAction}function Ge(e,t=zt){function n(){e(a)}var r;let i=t?.name??`Autorun`,a;if(t.scheduler||t.delay){let e=Ke(t),r=!1;a=new En(i,()=>{r||(r=!0,e(()=>{r=!1,a.isDisposed||a.track(n)}))},t.onError,t.requiresObservable)}else a=new En(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 Ke(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Bn}function qe(e,t,n,i){let a=typeof i==`function`?Et(t,n):Et(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 Je(e,t,n,r){let i=Ut(t);return kt(()=>{let t=Ct(e,r)[j];Ht(i).forEach(e=>{t.u(e,i[e],!n||!(e in n)||n[e])})}),e}function Ye(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(Ye)),t}function Xe(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),Xe)),t}function Ze(e){r(e.cancel)&&e.cancel()}function Qe(e){return!0===e?.isMobXFlow}function $e(e,t){var n;if(t===void 0)return bn(e);if(!1===Tt(e))return!1;let r=e[j];return(n=r.O)!=null&&n.has(t)?!0:r.j.has(t)?bn(Et(e,t)):!1}function et(e,t){if(!e)return!1;if(t!==void 0){if(Tt(e)){var n,r;let i=e[j];return i.j.has(t)||!((n=i.O)==null||!n.has(t))||!((r=i.V)==null||!r.has(t))}return!1}return Tt(e)||!!e[j]||Gt(e)||kn(e)||bn(e)}function tt(e){return et(e)}function nt(e){return Tt(e)?e[j].nt():ir(e)||sr(e)?Array.from(e.keys()):bt(e)?e.map((e,t)=>t):void t(5)}function rt(e,n){return Tt(e)?e[j].et(n):ir(e)||sr(e)?e.has(n):bt(e)?n>=0&&n<e.length:void t(10)}function it(e){if(Tt(e))return e[j].it();t(38)}function at(e,t,n){if(bn(e)){let r,i=!0;return Ge(()=>{let a=e.get();if(!i||n){let n=Oe();t({observableKind:`computed`,debugObjectName:e.tt,type:Xn,object:e,newValue:a,oldValue:r}),ke(n)}i=!1,r=a})}return n&&t({observableKind:`value`,debugObjectName:e.tt,object:e,type:Xn,newValue:e.rt,oldValue:void 0}),mt(e,t)}function ot(e,t,n){return e.set(t,n),n}function st(e,t){if(typeof e!=`object`||!e||e instanceof Date||!tt(e))return e;if(vn(e)||bn(e))return st(e.get(),t);if(t.has(e))return t.get(e);if(bt(e)){let n=ot(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=st(e,t)}),n}if(sr(e)){let n=ot(t,e,new Set);return e.forEach(e=>{n.add(st(e,t))}),n}if(ir(e)){let n=ot(t,e,new Map);return e.forEach((e,r)=>{n.set(r,st(e,t))}),n}{let n=ot(t,e,{});return it(e).forEach(r=>{Lt.propertyIsEnumerable.call(e,r)&&(n[r]=st(e[r],t))}),n}}function ct(e,t){Pe();try{return e.apply(t)}finally{Fe()}}function lt(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[j].isDisposed){if(a(),!n.onError)throw e;n.onError(e)}},n.timeout)}n.name=`When`;let i=ye(`When-effect`,t);var a=Ge(t=>{Se(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function ut(e){return e[j]}function dt(e){return e.st!==void 0&&e.st.length>0}function ft(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 O(e,n){let r=Oe();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{ke(r)}}function pt(e){return e.ot!==void 0&&e.ot.length>0}function mt(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 ht(e,t){let n=Oe(),r=e.ot;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);ke(n)}}function gt(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!==Lt;){let t=A(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 k(e,t){typeof Array.prototype[e]==`function`&&($n[e]=t(e))}function _t(e){return function(){let t=this[j];t.ct.reportObserved();let n=t.ht(t.j);return n[e].apply(n,arguments)}}function vt(e){return function(t,n){let r=this[j];return r.ct.reportObserved(),r.ht(r.j)[e]((e,r)=>t.call(n,e,r,this))}}function yt(e){return function(){let t=this[j];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 bt(e){return a(e)&&er(e[j])}function xt(e){return e[Symbol.toStringTag]=`MapIterator`,Nt(e)}function St(e){return e[Symbol.toStringTag]=`SetIterator`,Nt(e)}function Ct(e,t){if(p(e,j))return e;let n=t?.name??`ObservableObject`;return c(e,j,new ur(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 M[r]??(M[r]=de({deep:t,autoBind:n}))}(e):void 0}(t))),e}function wt(e){return cr[e]||(cr[e]={get(){return this[j]._(e)},set(t){return this[j].M(e,t)}})}function Tt(e){return!!a(e)&&dr(e[j])}function Et(e,n){if(typeof e==`object`&&e){if(bt(e))return n!==void 0&&t(23),e[j].ct;if(sr(e))return e.ct;if(ir(e)){if(n===void 0)return e.lt;let r=e.ft.get(n)||e.dt.get(n);return r||t(25,n,Ot(e)),r}if(Tt(e)){if(!n)return t(26);let r=e[j],i=r.j.get(n)??r.vt(n)??r.bt(n);return i||t(27,n,Ot(e)),i}if(Gt(e)||bn(e)||kn(e))return e}else if(r(e)&&kn(e[j]))return e[j];t(28)}function Dt(e,n){return e||t(29),n===void 0?Gt(e)||bn(e)||kn(e)||ir(e)||sr(e)?e:e[j]?e[j]:void t(24,e):Dt(Et(e,n))}function Ot(e,t){let n;if(t!==void 0)n=Et(e,t);else{if(We(e))return e.name;n=Tt(e)||ir(e)||sr(e)?Dt(e):Et(e)}return n.tt}function kt(e){let t=Oe();Pe();try{return e()}finally{Fe(),ke(t)}}function At(e,t,n=-1){return jt(e,t,n)}function jt(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=fr.call(e);if(s!==fr.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=Mt(e),t=Mt(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(!jt(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)||!jt(e[o],t[o],n-1,i,a))return!1}}return i.pop(),a.pop(),!0}function Mt(e){return bt(e)?e.slice():u(e)||ir(e)||d(e)||sr(e)?Array.from(e.entries()):e}function Nt(e){return e[Symbol.iterator]=Pt,Ft(Object.create(pr),e)}function Pt(){return this}Object.defineProperty(e,`__esModule`,{value:!0});let Ft=Object.assign,A=Object.getOwnPropertyDescriptor,It=Object.defineProperty,Lt=Object.prototype,Rt=[];Object.freeze(Rt);let zt={};Object.freeze(zt);let Bt=Object.toString(),Vt=()=>{},Ht=Reflect.ownKeys,Ut=Object.getOwnPropertyDescriptors,j=Symbol(`mobx administration`);var Wt=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 Le(this)}reportChanged(){Pe(),Re(this),Fe()}toString(){return this.tt}};let Gt=l(`Atom`,Wt),Kt=Object.is,qt={t:`override`,o:function(){return 0},u:function(){t(44,this.t)}},Jt=`true`,Yt=de(),M=[Yt],Xt={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Xt);let Zt=se(`observable`),Qt=se(`observable.ref`,{A:y}),$t=se(`observable.shallow`,{A:function(e,t,n){return e==null||Tt(e)||bt(e)||ir(e)||sr(e)?e:Array.isArray(e)?sn.array(e,{name:n,deep:!1}):o(e)?sn.object(e,void 0,{name:n,deep:!1}):u(e)?sn.map(e,{name:n,deep:!1}):d(e)?sn.set(e,{name:n,deep:!1}):void 0}}),en=se(`observable.struct`,{A:function(e,t){return At(e,t)?t:e}}),tn={box(e,t){let n=he(t);return new _n(e,_e(n),n.name,!0,n.equals)},array(e,t){let n=he(t);return function(e,t,n=`ObservableArray`,r=!1){return kt(()=>{let i=new Qn(n,t,r);It(i.j,j,{enumerable:!1,writable:!1,configurable:!0,value:i});let a=new Proxy(i.j,Zn);return i.v=a,e&&e.length&&i.wt(0,0,e),a})}(e,_e(n),n.name)},map(e,t){let n=he(t);return new rr(e,_e(n),n.name)},set(e,t){let n=he(t);return new or(e,_e(n),n.name)},object:(e,t,n)=>kt(()=>Je(function(e,t){var n;return(n=(e=Ct(e,t))[j]).v??(n.v=new Proxy(e,qn))}({},n),e,t))},nn=ge(Qt),rn=ge($t),an=ge(Zt),on=ge(en);var sn=Ft(function(e,t,n){return t&&typeof t.kind==`string`?ue(Zt,e,t):tt(e)?e:o(e)?sn.object(e,t,n):Array.isArray(e)?sn.array(e,t):u(e)?sn.map(e,t):d(e)?sn.set(e,t):typeof e==`object`&&e?e:sn.box(e,t)},Zt,tn);let cn=`computed`,ln=w(cn),un=ve(w(`computed.struct`,{equals:_})),dn=function(e,t){if(t&&typeof t.kind==`string`)return E(ln,e,t);if(o(e))return ve(w(cn,e));let n=o(t)?t:{};return n.get=e,n.name||=e.name||``,new yn(n)};var fn;Ft(dn,ln);let pn=0,mn=1,hn=(fn=A(()=>{},`name`)?.configurable)!=null&&fn,gn={value:`action`,configurable:!0,writable:!1,enumerable:!1};var _n=class extends Wt{constructor(e,t,n=`ObservableValue`,r=!0,i=Kt){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))!==N.UNCHANGED&&this.Ot(e)}jt(e){if(dt(this)){let t=O(this,{object:this,type:Xn,newValue:e});if(!t)return N.UNCHANGED;e=t.newValue}return e=this.A(e,this.rt,this.tt),this.xt(this.rt,e)?N.UNCHANGED:e}Ot(e){let t=this.rt;this.rt=e,this.reportChanged(),pt(this)&&ht(this,{type:Xn,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 vn=l(`ObservableValue`,_n);var yn=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 xn(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=ye(`ComputedValue-setter`,e.set)),this.xt=e.equals||Kt,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),N.inBatch!==0||this.H&&this.H.size!==0||this.Mt){let e=this.isBeingObserved;if(Le(this),we(this)){let e=N.trackingContext;e||!this.Mt&&!this.isBeingObserved||(N.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),N.trackingContext=e}else !e&&this.isBeingObserved&&this.L.forEach(Ie)}else we(this)&&(this.Nt(),Pe(),this.rt=this.Rt(!1),Fe());let e=this.rt;if(Ce(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||Ce(e)||Ce(n)||!this.xt(e,n);return r&&(this.rt=n),r}Rt(e){let t;if(this.isComputing=!0,e)t=Te(this,this.derivation,this.At);else if(!0===N.disableErrorBoundaries)t=this.derivation.call(this.At);else try{t=this.derivation.call(this.At)}catch(e){t=new xn(e)}return this.isComputing=!1,t}G(){this.Mt||(Ee(this),this.rt=void 0)}Nt(){}toString(){return`${this.tt}[${this.derivation.toString()}]`}valueOf(){return f(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let bn=l(`ComputedValue`,yn);var xn=class{constructor(e){this.cause=void 0,this.cause=e}};let Sn=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var Cn=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 wn=!0,Tn=!1,N=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(wn=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(wn=!1),wn?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new Cn):(setTimeout(()=>{Tn||t(35)},1),new Cn)}();var En=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,N.pendingReactions.push(this),ze())}X(){if(!this.isDisposed){Pe(),this.isScheduled=!1;let e=N.trackingContext;if(N.trackingContext=this,we(this)){this.isTrackPending=!0;try{this.Et()}catch(e){this.Pt(e)}}N.trackingContext=e,Fe()}}track(e){if(this.isDisposed)return;Pe(),this.isRunning=!0;let t=N.trackingContext;N.trackingContext=this;let n=Te(this,e,void 0);N.trackingContext=t,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Ee(this),Ce(n)&&this.Pt(n.cause),Fe()}Pt(e){if(this.kt)this.kt(e,this);else{if(N.disableErrorBoundaries)throw e;N.suppressReactionErrors||console.error(`[mobx] uncaught error in '${this}'`,e),N.globalReactionErrorHandlers.forEach(t=>t(e,this))}}dispose(){var e;this.isDisposed||(this.isDisposed=!0,(e=this.It)==null||e.call(this),this.isRunning||(Pe(),Ee(this),Fe()))}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[j]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.tt}]`}};let Dn=100,On=e=>e(),kn=l(`Reaction`,En),An=`action`,jn=`autoAction`,Mn=b(An),Nn=b(`action.bound`,{bound:!0}),Pn=b(jn,{autoAction:!0}),Fn=b(`autoAction.bound`,{autoAction:!0,bound:!0}),In=He(!1);Ft(In,Mn);let Ln=He(!0);Ft(Ln,Pn);let Rn=Ve(Nn),zn=Ve(Fn),Bn=e=>e(),Vn=`always`;var Hn=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};let Un=te(`flow`),Wn=te(`flow.bound`,{bound:!0}),Gn=Ft(function(e,t){if(t&&typeof t.kind==`string`)return ie(Un,e,t);let n=e,i=n.name||`flow`,a=function(){let e=arguments,t=In(i,n).apply(this,e),a,o,s=new Promise(function(e,n){function s(e){let r;o=void 0;try{r=In(i,t.next).call(t,e)}catch(e){return n(e)}l(r)}function c(e){let r;o=void 0;try{r=In(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=In(i,function(){try{o&&Ze(o);let e=t.return(void 0),n=Promise.resolve(e.value);n.then(Vt,Vt),Ze(n),a(new Hn)}catch(e){a(e)}}),s};return a.isMobXFlow=!0,a},Un),Kn=me(Wn,ie),qn={has:(e,t)=>ut(e).et(t),get:(e,t)=>ut(e).Tt(t),set(e,t,n){var r;return!!i(t)&&((r=ut(e).Bt(t,n,!0))==null||r)},deleteProperty(e,t){var n;return!!i(t)&&((n=ut(e).Dt(t,!0))==null||n)},defineProperty(e,t,n){var r;return(r=ut(e).l(t,n))==null||r},ownKeys:e=>ut(e).it(),preventExtensions(e){t(13)}},Jn=Symbol(`mobx-keys`),Yn=`splice`,Xn=`update`,Zn={get(e,t){let n=e[j];return t===j?n:t===`length`?n.Kt():typeof t!=`string`||isNaN(t)?p($n,t)?$n[t]:e[t]:n.Tt(parseInt(t))},set(e,t,n){let r=e[j];return t===`length`?r.Lt(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.Bt(parseInt(t),n),!0},preventExtensions(){t(15)}};var Qn=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 Wt(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=Rt),dt(this)){let r=O(this,{object:this.v,type:Yn,index:e,removedCount:t,added:n});if(!r)return Rt;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=pt(this),i=r?{observableKind:`array`,object:this.v,type:Xn,debugObjectName:this.ct.tt,index:e,newValue:t,oldValue:n}:null;this.ct.reportChanged(),r&&ht(this,i)}Ft(e,t,n){let r=pt(this),i=r?{observableKind:`array`,object:this.v,debugObjectName:this.ct.tt,type:Yn,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;this.ct.reportChanged(),r&&ht(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(dt(this)){let n=O(this,{type:Xn,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)}}},$n={clear(){return this.splice(0)},replace(e){let t=this[j];return t.wt(0,t.j.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[j];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[j].wt(e,t,n)},push(...e){let t=this[j];return t.wt(t.j.length,0,e),t.j.length},pop(){return this.splice(Math.max(this[j].j.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[j];return t.wt(0,0,e),t.j.length},reverse(){return N.trackingDerivation&&t(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){N.trackingDerivation&&t(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[j],n=t.ht(t.j).indexOf(e);return n>-1&&(this.splice(n,1),!0)}};k(`at`,_t),k(`concat`,_t),k(`flat`,_t),k(`includes`,_t),k(`indexOf`,_t),k(`join`,_t),k(`lastIndexOf`,_t),k(`slice`,_t),k(`toString`,_t),k(`toLocaleString`,_t),k(`toSorted`,_t),k(`toSpliced`,_t),k(`with`,_t),k(`every`,vt),k(`filter`,vt),k(`find`,vt),k(`findIndex`,vt),k(`findLast`,vt),k(`findLastIndex`,vt),k(`flatMap`,vt),k(`forEach`,vt),k(`map`,vt),k(`some`,vt),k(`toReversed`,vt),k(`reduce`,yt),k(`reduceRight`,yt);let er=l(`ObservableArrayAdministration`,Qn),tr={},nr=`delete`;var rr=class{constructor(e,t=v,n=`ObservableMap`){this.A=void 0,this.tt=void 0,this[j]=tr,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,kt(()=>{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(!N.trackingDerivation)return this.et(e);let t=this.dt.get(e);if(!t){let n=t=new _n(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(dt(this)){let r=O(this,{type:n?Xn:`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(dt(this)&&!O(this,{type:nr,object:this,name:e}))return!1;if(this.et(e)){let t=pt(this),n=t?{observableKind:`map`,debugObjectName:this.tt,type:nr,object:this,oldValue:this.ft.get(e).rt,name:e}:null;return ct(()=>{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&&ht(this,n),!0}return!1}Gt(e,t){let n=this.ft.get(e);if((t=n.jt(t))!==N.UNCHANGED){let r=pt(this),i=r?{observableKind:`map`,debugObjectName:this.tt,type:Xn,object:this,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&ht(this,i)}}Jt(e,t){ct(()=>{var n;let r=new _n(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=pt(this);n&&ht(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 xt({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 xt({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 ir(e)&&(e=new Map(e)),ct(()=>{o(e)?function(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>Lt.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(){ct(()=>{De(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return ct(()=>{let n=function(e){if(u(e)||ir(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`}},ir=l(`ObservableMap`,rr);let ar={};var or=class{constructor(e,t=v,n=`ObservableSet`){this.tt=void 0,this[j]=ar,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),kt(()=>{this.ct=g(this.tt),e&&this.replace(e)})}Wt(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){ct(()=>{De(()=>{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(dt(this)){let t=O(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){ct(()=>{e=this.A(e,void 0),this.ft.add(e),this.ct.reportChanged()});let t=pt(this);t&&ht(this,t?{observableKind:`set`,debugObjectName:this.tt,type:`add`,object:this,newValue:e}:null)}return this}delete(e){if(dt(this)&&!O(this,{type:nr,object:this,oldValue:e}))return!1;if(this.has(e)){let t=pt(this),n=t?{observableKind:`set`,debugObjectName:this.tt,type:nr,object:this,oldValue:e}:null;return ct(()=>{this.ct.reportChanged(),this.ft.delete(e)}),t&&ht(this,n),!0}return!1}has(e){return this.ct.reportObserved(),this.ft.has(this.Wt(e))}entries(){let e=this.values();return St({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 St({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 sr(e)&&(e=new Set(e)),Array.isArray(e)||d(e)?ct(()=>{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`}},sr=l(`ObservableSet`,or);let cr=Object.create(null),lr=`remove`;var ur=class{constructor(e,t=new Map,n,r=Yt){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 Wt(`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 yn)return n.set(t),!0;if(dt(this)){let n=O(this,{type:Xn,object:this.v||this.h,name:e,newValue:t});if(!n)return null;t=n.newValue}if((t=n.jt(t))!==N.UNCHANGED){let r=pt(this),i=r?{type:Xn,observableKind:`object`,debugObjectName:this.tt,object:this.v||this.h,oldValue:n.rt,name:e,newValue:t}:null;n.Ot(t),r&&ht(this,i)}return!0}Tt(e){return N.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(!N.trackingDerivation)return e in this.h;this.Qt||=new Map;let t=this.Qt.get(e);return t||(t=new _n(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{Pe();let r=this.Dt(e);if(!r)return r;if(dt(this)){let n=O(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=Ft({},t,{value:r}))}if(n){if(!Reflect.defineProperty(this.h,e,t))return!1}else It(this.h,e,t);this.Yt(e,t.value)}finally{Fe()}return!0}S(e,t,n,r=!1){try{Pe();let i=this.Dt(e);if(!i)return i;if(dt(this)){let n=O(this,{object:this.v||this.h,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let a=wt(e),o={configurable:!N.safeDescriptors||this.p,enumerable:!0,get:a.get,set:a.set};if(r){if(!Reflect.defineProperty(this.h,e,o))return!1}else It(this.h,e,o);let s=new _n(t,n,`ObservableObject.key`,!1);this.j.set(e,s),this.Yt(e,s.rt)}finally{Fe()}return!0}m(e,t,n=!1){try{Pe();let r=this.Dt(e);if(!r)return r;if(dt(this)&&!O(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=wt(e),a={configurable:!N.safeDescriptors||this.p,enumerable:!1,get:i.get,set:i.set};if(n){if(!Reflect.defineProperty(this.h,e,a))return!1}else It(this.h,e,a);this.j.set(e,new yn(t)),this.Yt(e,void 0)}finally{Fe()}return!0}Dt(e,t=!1){if(!p(this.h,e))return!0;if(dt(this)&&!O(this,{object:this.v||this.h,name:e,type:lr}))return null;try{var n;Pe();let r=pt(this),i=this.j.get(e),a;if(i||!r||(a=A(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 _n&&(a=i.rt),Re(i)),this.lt.reportChanged(),(n=this.Qt)==null||(n=n.get(e))==null||n.set(e in this.h),r&&r&&ht(this,{type:lr,observableKind:`object`,object:this.v||this.h,debugObjectName:this.tt,oldValue:a,name:e})}finally{Fe()}return!0}Yt(e,t){var n;let r=pt(this);r&&r&&ht(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(),Ht(this.h)}nt(){return this.lt.reportObserved(),Object.keys(this.h)}};let dr=l(`ObservableObjectAdministration`,ur),fr=Lt.toString,pr=globalThis.Iterator?.prototype||{};e.$mobx=j,e.FlowCancellationError=Hn,e.ObservableMap=rr,e.ObservableSet=or,e.Reaction=En,e._allowStateChanges=Se,e._allowStateChangesInsideComputed=Ue,e._allowStateReadsEnd=function(e){N.allowStateReads=e},e._allowStateReadsStart=function(e){let t=N.allowStateReads;return N.allowStateReads=e,t},e._autoAction=Ln,e._autoActionBound=zn,e._endAction=D,e._getAdministration=Dt,e._getGlobalState=function(){return N},e._interceptReads=function(e,t,n){let r;return ir(e)||bt(e)||vn(e)?r=Dt(e):Tt(e)&&(r=Dt(e,t)),r.dehancer=typeof t==`function`?t:n,()=>{r.dehancer=void 0}},e._isComputingDerivation=function(){return N.trackingDerivation!==null},e._resetGlobalState=function(){let e=new Cn;for(let t in e)Sn.indexOf(t)===-1&&(N[t]=e[t]);N.allowStateChanges=!N.enforceActions},e._startAction=xe,e.action=In,e.actionBound=Rn,e.autorun=Ge,e.compareDefault=Kt,e.compareIdentity=function(e,t){return e===t},e.compareShallow=function(e,t){return At(e,t,1)},e.compareStructural=_,e.computed=dn,e.computedStruct=un,e.configure=function(e){!0===e.isolateGlobalState&&function(){if((N.pendingReactions.length||N.inBatch||N.isRunningReactions)&&t(36),Tn=!0,wn){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),N=new Cn}}();let{enforceActions:n}=e;if(n!==void 0){let e=n===Vn?Vn:n===`observed`;N.enforceActions=e,N.allowStateChanges=!0!==e&&e!==Vn}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(N[t]=!!e[t])}),N.allowStateReads=!N.observableRequiresReaction,e.reactionScheduler&&function(e){let t=On;On=n=>e(()=>t(n))}(e.reactionScheduler)},e.createAtom=g,e.defineProperty=function(e,n,r){if(Tt(e))return e[j].l(n,r);t(39)},e.entries=function(e){return Tt(e)?nt(e).map(t=>[t,e[t]]):ir(e)?nt(e).map(t=>[t,e.get(t)]):sr(e)?Array.from(e.entries()):bt(e)?e.map((e,t)=>[t,e]):void t(7)},e.extendObservable=Je,e.flow=Gn,e.flowBound=Kn,e.flowResult=function(e){return e},e.get=function(e,n){if(rt(e,n))return Tt(e)?e[j].Tt(n):ir(e)?e.get(n):bt(e)?e[n]:void t(11)},e.getAtom=Et,e.getDebugName=Ot,e.getDependencyTree=function(e,t){return Ye(Et(e,t))},e.getObserverTree=function(e,t){return Xe(Et(e,t))},e.has=rt,e.intercept=function(e,t,n){return r(n)?function(e,t,n){return ft(Dt(e,t),n)}(e,t,n):function(e,t){return ft(Dt(e),t)}(e,t)},e.isAction=We,e.isBoxedObservable=vn,e.isComputed=function(e){return $e(e)},e.isComputedProp=function(e,t){return $e(e,t)},e.isFlow=Qe,e.isFlowCancellationError=function(e){return e instanceof Hn},e.isObservable=tt,e.isObservableArray=bt,e.isObservableMap=ir,e.isObservableObject=Tt,e.isObservableProp=function(e,t){return et(e,t)},e.isObservableSet=sr,e.keys=nt,e.makeAutoObservable=function(e,t,n){return o(e)?Je(e,e,t,n):(kt(()=>{let r=Ct(e,n)[j];if(!e[Jn]){let t=Object.getPrototypeOf(e),n=new Set([...Ht(e),...Ht(t)]);n.delete(`constructor`),n.delete(j),c(t,Jn,n)}e[Jn].forEach(e=>gt(r,e,!t||!(e in t)||t[e]))}),e)},e.makeObservable=function(e,t,n){return kt(()=>{let r=Ct(e,n)[j];Ht(t).forEach(e=>gt(r,e,t[e]))}),e},e.observable=sn,e.observableDeep=an,e.observableRef=nn,e.observableShallow=rn,e.observableStruct=on,e.observe=function(e,t,n,i){return r(n)?function(e,t,n,r){return at(Dt(e,t),n,r)}(e,t,n,i):function(e,t,n){let r=Dt(e);if(bt(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(!ir(e)&&!sr(e)&&!Tt(e))return at(r,t,n);return mt(r,t)}(e,t,n)},e.onBecomeObserved=function(e,t,n){return qe(`onBO`,e,t,n)},e.onBecomeUnobserved=function(e,t,n){return qe(`onBUO`,e,t,n)},e.onReactionError=function(e){return N.globalReactionErrorHandlers.push(e),()=>{let t=N.globalReactionErrorHandlers.indexOf(e);t>=0&&N.globalReactionErrorHandlers.splice(t,1)}},e.override=qt,e.ownKeys=it,e.reaction=function(e,t,n=zt){function r(){if(p=!1,h.isDisposed)return;let t=!1,r=d;h.track(()=>{let n=Se(!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=In(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=Ke(n),d,f=!0,p=!1,m=n.equals||Kt,h=new En(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){Tt(e)?e[j].Dt(n):ir(e)||sr(e)?e.delete(n):bt(e)?(typeof n!=`number`&&(n=parseInt(n,10)),e.splice(n,1)):t(9)},e.runInAction=Ue,e.set=function e(n,r,i){if(arguments.length===2&&!sr(n)){Pe();let t=r;try{for(let r in t)e(n,r,t[r])}finally{Fe()}return}Tt(n)?n[j].Bt(r,i):ir(n)?n.set(r,i):sr(n)?n.add(r):bt(n)?(typeof r!=`number`&&(r=parseInt(r,10)),r<0&&t(42,r),Pe(),r>=n.length&&(n.length=r+1),n[r]=i,Fe()):t(8)},e.spy=function(){return console.warn(`[mobx.spy] Is a no-op in production builds`),function(){}},e.toJS=function(e){return st(e,new Map)},e.transaction=ct,e.untracked=De,e.values=function(e){return Tt(e)?nt(e).map(t=>e[t]):ir(e)?nt(e).map(t=>e.get(t)):sr(e)?Array.from(e.values()):bt(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 Ft(Promise.reject(Error(`WHEN_ABORTED`)),{cancel:()=>null});let r,i,a=new Promise((n,a)=>{var o;let s=lt(e,n,Ft({},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):lt(e,t,n||{})}})),P_=ye((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++M.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=ie(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 x(e){return e!=null&&Object.prototype.toString.call(e)===`[object Map]`}function S(e){return Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(e)))===null}function C(e){return e!=null&&Object.prototype.toString.call(e)===`[object Set]`}function ee(e){let t=Object.keys(e),n=Object.getOwnPropertySymbols(e);return n.length?[...t,...n.filter(t=>o.propertyIsEnumerable.call(e,t))]:t}let te=Reflect.ownKeys;function ne(e){return typeof e==`string`?e:typeof e==`symbol`?e.toString():new String(e).toString()}function re(e){return e===null?null:typeof e==`object`?``+e:e}function ie(e,t){return o.hasOwnProperty.call(e,t)}let ae=Object.getOwnPropertyDescriptors;function w(e,t){return!!(e&t)}function T(e,t,n){return n?e|=t:e&=~t,e}function oe(e,t){t.includes(e.kind)||n(`The decorator applied to '${String(e.name)}' cannot be used on a ${e.kind} element`)}let E=Symbol(`mobx administration`);var se=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_=T(this.flags_,1,e)}get isPendingUnobservation(){return w(this.flags_,2)}set isPendingUnobservation(e){this.flags_=T(this.flags_,2,e)}get diffValue(){return+!!w(this.flags_,4)}set diffValue(e){this.flags_=T(this.flags_,4,e===1)}onBO(){this.onBOL&&this.onBOL.forEach(e=>e())}onBUO(){this.onBUOL&&this.onBUOL.forEach(e=>e())}reportObserved(){return ln(this)}reportChanged(){an(),un(this),on()}toString(){return this.name_}};let ce=b(`Atom`,se);function le(e,t=f,n=f){let r=new se(e);return t!==f&&(r.onBOL=new Set([t])),n!==f&&(r.onBUOL=new Set([n])),r}function ue(e,t){return e===t}function de(e,t){return Fi(e,t)}function fe(e,t){return Fi(e,t,1)}let pe=Object.is;function me(e,t,n){return e===null||typeof e!=`object`&&typeof e!=`function`||xr(e)?e:Array.isArray(e)?O.array(e,{name:n}):g(e)?O.object(e,void 0,{name:n}):x(e)?O.map(e,{name:n}):C(e)?O.set(e,{name:n}):typeof e==`function`&&!zn(e)&&!fr(e)?_(e)?cr(e):Fn(n,e):e}function he(e,t,r){if(e==null||Di(e)||pi(e)||P(e)||yi(e))return e;if(Array.isArray(e))return O.array(e,{name:r,deep:!1});if(g(e))return O.object(e,void 0,{name:r,deep:!1});if(x(e))return O.map(e,{name:r,deep:!1});if(C(e))return O.set(e,{name:r,deep:!1});n(`The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets`)}function ge(e){return e}function _e(e,t){return xr(e)&&n(`observable.struct should not be used with observable values`),Fi(e,t)?t:e}let ve=`override`,ye={annotationType_:ve,make_:xe,extend_:D};function be(e){return e.annotationType_===ve}function xe(e,t){return e.isPlainObject_&&n(`Cannot apply '${this.annotationType_}' to '${e.name_}.${t.toString()}':\n'${this.annotationType_}' cannot be used on plain objects.`),ie(e.appliedAnnotations_,t)||n(`'${e.name_}.${t.toString()}' is annotated with '${this.annotationType_}', but no such annotated member was found on prototype.`),0}function D(e,t,r,i){n(44,this.annotationType_)}function Se(e,t){return{annotationType_:e,options_:t,make_:Ce,extend_:we}}function Ce(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:zn(n.value)?1:(a(r,t,De(e,this,t,n,!1)),2)}function we(e,t,n,r){let i=De(e,this,t,n);return e.defineProperty_(t,i,r)}function Te(e,t,r){oe(r,[`method`,`field`]);let{kind:i,name:a,addInitializer:o}=r,s=e,c=e=>xt(s.options_?.name??a.toString(),e,s.options_?.autoAction??!1);if(i==`field`)return function(e){var t;let n=e;return zn(n)||(n=c(n)),(t=s.options_)!=null&&t.bound&&(n=n.bind(this),n.isMobxAction=!0),n};if(i==`method`){var l;return zn(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 Ee(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 De(e,t,n,r,i=M.safeDescriptors){var a,o;Ee(e,t,n,r);let{value:s}=r;return(a=t.options_)!=null&&a.bound&&(s=s.bind(e.proxy_??e.target_)),{value:xt(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 Oe(e,t){return{annotationType_:e,options_:t,make_:ke,extend_:Ae}}function ke(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&&(!ie(e.target_,t)||!fr(e.target_[t]))&&this.extend_(e,t,n,!1)===null?0:fr(n.value)?1:(a(r,t,Ne(e,this,t,n,!1,!1)),2)}function Ae(e,t,n,r){let i=Ne(e,this,t,n,this.options_?.bound);return e.defineProperty_(t,i,r)}function je(e,t,n){var r;oe(n,[`method`]);let{name:i,addInitializer:a}=n;return fr(t)||(t=cr(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 Me(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 Ne(e,t,n,r,i,a=M.safeDescriptors){Me(e,t,n,r);let{value:o}=r;return fr(o)||(o=cr(o)),i&&(o=o.bind(e.proxy_??e.target_),o.isMobXFlow=!0),{value:o,configurable:a?e.isPlainObject_:!0,enumerable:!1,writable:!a}}function Pe(e,t){return{annotationType_:e,options_:t,make_:Fe,extend_:Ie}}function Fe(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Ie(e,t,n,i){return Re(e,this,t,n),e.defineComputedProperty_(t,r({},this.options_,{get:n.get,set:n.set}),i)}function Le(e,t,n){oe(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 At(o)}return o(function(){let e=wi(this)[E],n=this,r=e.values_.get(a);r instanceof At&&r.derivation!==t&&e.values_.delete(a),(e.lazyComputedKeys_??=new Map).set(a,()=>c(n,e))}),function(){let e=this[E],n=e.values_.get(a);if(n instanceof At&&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 Re(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 ze(e,t){return{annotationType_:e,options_:t,make_:Be,extend_:Ve}}function Be(e,t,n){return this.extend_(e,t,n,!1)===null?0:1}function Ve(e,t,n,r){return Ue(e,this,t,n),e.defineObservableProperty_(t,n.value,this.options_?.enhancer_??me,r)}function He(e,t,r){if(r.kind===`field`)throw n(`Please use \`@observable accessor ${String(r.name)}\` instead of \`@observable ${String(r.name)}\``);oe(r,[`accessor`]);let i=e,{kind:a,name:o}=r;if(a!==`accessor`)return;function s(e,t){let n=wi(e)[E];return(n.lazyObservableKeys_??=new Map).set(o,()=>new Ot(t,i.options_?.enhancer_??me,`${n.name_}.${o.toString()}`,!1)),n}return{get(){return(this[E]??s(this,t.get.call(this))).getObservablePropValue_(o)},set(e){return(this[E]??s(this,e)).setObservablePropValue_(o,e)},init(e){return s(this,e),e}}}function Ue(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 We=Ge();function Ge(e){return{annotationType_:`true`,options_:e,make_:Je,extend_:Ye}}let Ke=[We];function qe(e){let t=e.deep!==!1,n=!!e.autoBind,r=!t|(n?2:0);return Ke[r]??(Ke[r]=Ge({deep:t,autoBind:n}))}function Je(e,t,n,r){var i;if(n.get)return k.make_(e,t,n,r);if(n.set){let i=zn(n.set)?n.set:xt(t.toString(),n.set);return r===e.target_?e.defineProperty_(t,{configurable:M.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?lr:cr).make_(e,t,n,r)}return((o=this.options_)!=null&&o.autoBind?Ln:Fn).make_(e,t,n,r)}let c=this.options_?.deep===!1?lt:O;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 Ye(e,t,n,r){var i;return n.get?k.extend_(e,t,n,r):n.set?e.defineProperty_(t,{configurable:M.safeDescriptors?e.isPlainObject_:!0,set:xt(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?lt:O).extend_(e,t,n,r))}function Xe(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 Ze={deep:!0,name:void 0,defaultDecorator:void 0};Object.freeze(Ze);function Qe(e){return e||Ze}let $e=ze(`observable`),et=ze(`observable.ref`,{enhancer_:ge}),tt=ze(`observable.shallow`,{enhancer_:he}),nt=ze(`observable.struct`,{enhancer_:_e});function rt(e){return Xe(e,He)}function it(e){return e.deep===!0?me:e.deep===!1?ge:ot(e.defaultDecorator)}function at(e){return e?e.defaultDecorator??qe(e):void 0}function ot(e){return e?e.options_?.enhancer_??me:me}function st(e,t,n){return t&&typeof t.kind==`string`?He($e,e,t):xr(e)?e:g(e)?O.object(e,t,n):Array.isArray(e)?O.array(e,t):x(e)?O.map(e,t):C(e)?O.set(e,t):typeof e==`object`&&e?e:O.box(e,t)}let ct={box(e,t){let n=Qe(t);return new Ot(e,it(n),n.name,!0,n.equals)},array(e,t){let n=Qe(t);return oi(e,it(n),n.name)},map(e,t){let n=Qe(t);return new gi(e,it(n),n.name)},set(e,t){let n=Qe(t);return new vi(e,it(n),n.name)},object(e,t,n){return Ni(()=>Xn(Gr({},n),e,t))}},lt=rt(et),ut=rt(tt),dt=rt($e),ft=rt(nt);var O=r(st,$e,ct);let pt=`computed`;function mt(e){return Xe(e,Le)}let ht=Pe(pt),gt=mt(Pe(`computed.struct`,{equals:de})),k=function(e,t){if(t&&typeof t.kind==`string`)return Le(ht,e,t);if(g(e))return mt(Pe(pt,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 At(r)};r(k,ht);let _t=0,vt=1,yt=i(()=>{},`name`)?.configurable??!1,bt={value:`action`,configurable:!0,writable:!1,enumerable:!1};function xt(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 St(e,r,t,i||this,arguments)}return o.isMobxAction=!0,o.toString=()=>t.toString(),yt&&(bt.value=e,a(o,`name`,bt)),o}function St(e,t,n,r,i){let a=Ct(e,t,r,i);try{return n.apply(r,i)}catch(e){throw a.error_=e,e}finally{wt(a)}}function Ct(e,t,n,r){let i=bn()&&!!e,a=0;i&&(a=Date.now(),Sn({type:N,name:e,object:n,arguments:r?Array.from(r):s}));let o=M.trackingDerivation,c=!t||!o;an();let l=M.allowStateChanges;c&&(Ht(),l=Et(!0));let u=M.allowStateReads;j(!0);let d={runAsAction_:c,prevDerivation_:o,prevAllowStateChanges_:l,prevAllowStateReads_:u,notifySpy_:i,startTime_:a,actionId_:vt++,parentActionId_:_t};return _t=d.actionId_,d}function wt(e){_t!==e.actionId_&&n(30),_t=e.parentActionId_,e.error_!==void 0&&(M.suppressReactionErrors=!0),Dt(e.prevAllowStateChanges_),Wt(e.prevAllowStateReads_),on(),e.runAsAction_&&Ut(e.prevDerivation_),e.notifySpy_&&wn({time:Date.now()-e.startTime_}),M.suppressReactionErrors=!1}function Tt(e,t){let n=Et(e);try{return t()}finally{Dt(n)}}function Et(e){let t=M.allowStateChanges;return M.allowStateChanges=e,t}function Dt(e){M.allowStateChanges=e}var Ot=class extends se{constructor(e,t,n=`ObservableValue@`+u(),r=!0,i=pe){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&&bn()&&xn({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!==M.UNCHANGED){let n=bn();n&&Sn({type:ri,object:this,observableKind:`value`,debugObjectName:this.name_,newValue:e,oldValue:t}),this.setNewValue_(e),n&&wn()}}prepareNewValue_(e){if(A(this),Kr(this)){let t=Jr(this,{object:this,type:ri,newValue:e});if(!t)return M.UNCHANGED;e=t.newValue}return e=this.enhancer_(e,this.value_,this.name_),this.equals_(this.value_,e)?M.UNCHANGED:e}setNewValue_(e){let t=this.value_;this.value_=e,this.reportChanged(),Yr(this)&&Zr(this,{type:ri,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 re(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let kt=b(`ObservableValue`,Ot);var At=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 Mt(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_=xt(this.name_+`-setter`,e.set)),this.equals_=e.equals||pe,this.scope_=e.context,this.requiresReaction_=e.requiresReaction,this.keepAlive_=!!e.keepAlive}onBecomeStale_(){fn(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_=T(this.flags_,1,e)}get isRunningSetter(){return w(this.flags_,2)}set isRunningSetter(e){this.flags_=T(this.flags_,2,e)}get isBeingObserved(){return w(this.flags_,4)}set isBeingObserved(e){this.flags_=T(this.flags_,4,e)}get isPendingUnobservation(){return w(this.flags_,8)}set isPendingUnobservation(e){this.flags_=T(this.flags_,8,e)}get diffValue(){return+!!w(this.flags_,16)}set diffValue(e){this.flags_=T(this.flags_,16,e===1)}get(){if(this.isComputing&&n(32,this.name_,this.derivation),M.inBatch===0&&(!this.observers_||this.observers_.size===0)&&!this.keepAlive_)Pt(this)&&(this.warnAboutUntrackedRead_(),an(),this.value_=this.computeValue_(!1),on());else{let e=this.isBeingObserved;if(ln(this),Pt(this)){let e=M.trackingContext;!e&&(this.keepAlive_||this.isBeingObserved)&&(M.trackingContext=this),this.trackAndCompute()&&dn(this),M.trackingContext=e}else !e&&this.isBeingObserved&&this.observing_.forEach(cn)}let e=this.value_;if(Nt(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||Nt(e)||Nt(n)||!this.equals_(e,n);return r&&(this.value_=n,bn()&&xn({observableKind:`computed`,debugObjectName:this.name_,object:this.scope_,type:`update`,oldValue:e,newValue:n})),r}computeValue_(e){this.isComputing=!0;let t=Et(!1),n;if(e)n=Lt(this,this.derivation,this.scope_);else if(M.disableErrorBoundaries===!0)n=this.derivation.call(this.scope_);else try{n=this.derivation.call(this.scope_)}catch(e){n=new Mt(e)}return Dt(t),this.isComputing=!1,n}suspend_(){this.keepAlive_||(Bt(this),this.value_=void 0)}warnAboutUntrackedRead_(){(typeof this.requiresReaction_==`boolean`?this.requiresReaction_:M.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 re(this.get())}[Symbol.toPrimitive](){return this.valueOf()}};let jt=b(`ComputedValue`,At);var Mt=class{constructor(e){this.cause=void 0,this.cause=e}};function Nt(e){return e instanceof Mt}function Pt(e){switch(e.dependenciesState_){case 0:return!1;case-1:case 2:return!0;case 1:{let t=j(!0),n=Ht(),r=e.observing_,i=r.length;for(let a=0;a<i;a++){let i=r[a];if(jt(i)){if(M.disableErrorBoundaries)i.get();else try{i.get()}catch{return Ut(n),Wt(t),!0}if(e.dependenciesState_===2)return Ut(n),Wt(t),!0}}return Gt(e),Ut(n),Wt(t),!1}}}function Ft(){return M.trackingDerivation!==null}function A(e){let t=!!e.observers_&&e.observers_.size>0;!M.allowStateChanges&&(t||M.enforceActions===`always`)&&console.warn(`[MobX] `+(M.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 It(e){!M.allowStateReads&&M.observableRequiresReaction&&console.warn(`[mobx] Observable '${e.name_}' being read outside a reactive context.`)}function Lt(e,t,n){let r=j(!0);Gt(e),e.newObserving_=Array(e.runId_===0?100:e.observing_.length),e.unboundDepsCount_=0,e.runId_=++M.runId;let i=M.trackingDerivation;M.trackingDerivation=e,M.inBatch++;let a;if(M.disableErrorBoundaries===!0)a=t.call(n);else try{a=t.call(n)}catch(e){a=new Mt(e)}return M.inBatch--,M.trackingDerivation=i,zt(e),Rt(e),Wt(r),a}function Rt(e){e.observing_.length===0&&(typeof e.requiresObservable_==`boolean`?e.requiresObservable_:M.reactionRequiresObservable)&&console.warn(`[mobx] Derivation '${e.name_}' is created/updated without reading any observable value.`)}function zt(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&&nn(n,e),n.diffValue=0}for(;i--;){let t=n[i];t.diffValue===1&&(t.diffValue=0,tn(t,e))}r!==0&&(e.dependenciesState_=r,e.onBecomeStale_())}function Bt(e){let t=e.observing_;e.observing_=[];let n=t.length;for(;n--;)nn(t[n],e);e.dependenciesState_=-1}function Vt(e){let t=Ht();try{return e()}finally{Ut(t)}}function Ht(){let e=M.trackingDerivation;return M.trackingDerivation=null,e}function Ut(e){M.trackingDerivation=e}function j(e){let t=M.allowStateReads;return M.allowStateReads=e,t}function Wt(e){M.allowStateReads=e}function Gt(e){if(e.dependenciesState_===0)return;e.dependenciesState_=0;let t=e.observing_,n=t.length;for(;n--;)t[n].lowestObserverState_=0}let Kt=[`mobxGuid`,`spyListeners`,`enforceActions`,`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`allowStateReads`,`disableErrorBoundaries`,`runId`,`UNCHANGED`];var qt=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 Jt=!0,Yt=!1,M=function(){let e=globalThis;return e.__mobxInstanceCount>0&&!e.__mobxGlobals&&(Jt=!1),e.__mobxGlobals&&e.__mobxGlobals.version!==7&&(Jt=!1),Jt?e.__mobxGlobals?(e.__mobxInstanceCount+=1,e.__mobxGlobals.UNCHANGED||(e.__mobxGlobals.UNCHANGED={}),e.__mobxGlobals):(e.__mobxInstanceCount=1,e.__mobxGlobals=new qt):(setTimeout(()=>{Yt||n(35)},1),new qt)}();function Xt(){if((M.pendingReactions.length||M.inBatch||M.isRunningReactions)&&n(36),Yt=!0,Jt){let e=globalThis;--e.__mobxInstanceCount===0&&(e.__mobxGlobals=void 0),M=new qt}}function Zt(){return M}function Qt(){let e=new qt;for(let t in e)Kt.indexOf(t)===-1&&(M[t]=e[t]);M.allowStateChanges=!M.enforceActions}function $t(e){return!!e.observers_&&e.observers_.size>0}function en(e){return e.observers_??new Set}function tn(e,t){(e.observers_??=new Set).add(t),e.lowestObserverState_>t.dependenciesState_&&(e.lowestObserverState_=t.dependenciesState_)}function nn(e,t){let n=e.observers_;n&&(n.delete(t),n.size===0&&rn(e))}function rn(e){e.isPendingUnobservation===!1&&(e.isPendingUnobservation=!0,M.pendingUnobservations.push(e))}function an(){M.inBatch++}function on(){--M.inBatch===0&&(gn(),!M.isRunningUnobservations&&M.pendingUnobservations.length>0&&sn())}function sn(){M.isRunningUnobservations=!0;try{let e=M.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 At&&n.suspend_())}M.pendingUnobservations=[]}finally{M.isRunningUnobservations=!1}}function cn(e){var t;e.isBeingObserved||(e.isBeingObserved=!0,e.onBO(),(t=e.observing_)==null||t.forEach(cn))}function ln(e){It(e);let t=M.trackingDerivation;return t===null?((!e.observers_||e.observers_.size===0)&&M.inBatch>0&&rn(e),!1):(t.runId_!==e.lastAccessedBy_&&(e.lastAccessedBy_=t.runId_,t.newObserving_[t.unboundDepsCount_++]=e,!e.isBeingObserved&&M.trackingContext&&(e.isBeingObserved=!0,e.onBO())),e.isBeingObserved)}function un(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 dn(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 fn(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 pn=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_=T(this.flags_,1,e)}get isScheduled(){return w(this.flags_,2)}set isScheduled(e){this.flags_=T(this.flags_,2,e)}get isTrackPending(){return w(this.flags_,4)}set isTrackPending(e){this.flags_=T(this.flags_,4,e)}get isRunning(){return w(this.flags_,8)}set isRunning(e){this.flags_=T(this.flags_,8,e)}get diffValue(){return+!!w(this.flags_,16)}set diffValue(e){this.flags_=T(this.flags_,16,e===1)}onBecomeStale_(){this.schedule_()}schedule_(){this.isScheduled||(this.isScheduled=!0,M.pendingReactions.push(this),gn())}runReaction_(){if(!this.isDisposed){an(),this.isScheduled=!1;let e=M.trackingContext;if(M.trackingContext=this,Pt(this)){this.isTrackPending=!0;try{this.onInvalidate_(),this.isTrackPending&&bn()&&xn({name:this.name_,type:`scheduled-reaction`})}catch(e){this.reportExceptionInDerivation_(e)}}M.trackingContext=e,on()}}track(e){if(this.isDisposed)return;an();let t=bn(),n;t&&(n=Date.now(),Sn({name:this.name_,type:`reaction`})),this.isRunning=!0;let r=M.trackingContext;M.trackingContext=this;let i=Lt(this,e,void 0);M.trackingContext=r,this.isRunning=!1,this.isTrackPending=!1,this.isDisposed&&Bt(this),Nt(i)&&this.reportExceptionInDerivation_(i.cause),t&&wn({time:Date.now()-n}),on()}reportExceptionInDerivation_(e){if(this.errorHandler_){this.errorHandler_(e,this);return}if(M.disableErrorBoundaries)throw e;let t=`[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '${this}'`;M.suppressReactionErrors?console.warn(`[mobx] (error in reaction '${this.name_}' suppressed, fix error of causing action below)`):console.error(t,e),bn()&&xn({type:`error`,name:this.name_,message:t,error:``+e}),M.globalReactionErrorHandlers.forEach(t=>t(e,this))}dispose(){if(!this.isDisposed){var e;this.isDisposed=!0,(e=this.removeAbortListener_)==null||e.call(this),this.isRunning||(an(),Bt(this),on())}}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[E]=this,`dispose`in Symbol&&typeof Symbol.dispose==`symbol`&&(t[Symbol.dispose]=t),t}toString(){return`Reaction[${this.name_}]`}};function mn(e){return M.globalReactionErrorHandlers.push(e),()=>{let t=M.globalReactionErrorHandlers.indexOf(e);t>=0&&M.globalReactionErrorHandlers.splice(t,1)}}let hn=e=>e();function gn(){M.inBatch>0||M.isRunningReactions||hn(_n)}function _n(){M.isRunningReactions=!0;let e=M.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_()}M.isRunningReactions=!1}let vn=b(`Reaction`,pn);function yn(e){let t=hn;hn=n=>e(()=>t(n))}function bn(){return!!M.spyListeners.length}function xn(e){if(!M.spyListeners.length)return;let t=M.spyListeners;for(let n=0,r=t.length;n<r;n++)t[n](e)}function Sn(e){xn(r({},e,{spyReportStart:!0}))}let Cn={type:`report-end`,spyReportEnd:!0};function wn(e){xn(e?r({},e,{type:`report-end`,spyReportEnd:!0}):Cn)}function Tn(e){return M.spyListeners.push(e),d(()=>{M.spyListeners=M.spyListeners.filter(t=>t!==e)})}let N=`action`,En=`autoAction`,Dn=`<unnamed action>`,On=Se(N),kn=Se(`action.bound`,{bound:!0}),An=Se(En,{autoAction:!0}),jn=Se(`autoAction.bound`,{autoAction:!0,bound:!0});function Mn(e){return Xe(e,Te)}function Nn(e){return function(t,r){if(r&&typeof r.kind==`string`)return Te(e?An:On,t,r);if(p(t))return xt(t.name||Dn,t,e);if(p(r))return xt(t,r,e);if(m(t))return Mn(Se(e?En:N,{name:t,autoAction:e}));n("Invalid arguments for `action`")}}let Pn=Nn(!1);r(Pn,On);let Fn=Nn(!0);r(Fn,An);let In=Mn(kn),Ln=Mn(jn);function Rn(e){return St(e.name||Dn,!1,e,this,void 0)}function zn(e){return p(e)&&e.isMobxAction===!0}function Bn(e,t=c){var r;p(e)||n(`Autorun expects a function as first argument`),zn(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 pn(i,function(){this.track(s)},t.onError,t.requiresObservable);else{let e=Hn(t),n=!1;o=new pn(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 Vn=e=>e();function Hn(e){return e.scheduler?e.scheduler:e.delay?t=>setTimeout(t,e.delay):Vn}function Un(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=Pn(a,r.onError?Wn(r.onError,t):t),s=!r.scheduler&&!r.delay,l=Hn(r),d=!0,f=!1,m,h=r.equals||pe,_=new pn(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=Tt(!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 Wn(e,t){return function(){try{return t.apply(this,arguments)}catch(t){e.call(this,t)}}}function Gn(e,t,n){return qn(`onBO`,e,t,n)}function Kn(e,t,n){return qn(`onBUO`,e,t,n)}function qn(e,t,n,r){let i=typeof r==`function`?Ai(t,n):Ai(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 Jn=`always`;function Yn(e){e.isolateGlobalState===!0&&Xt();let{enforceActions:t}=e;if(t!==void 0){let e=t===Jn?Jn:t===`observed`;M.enforceActions=e,M.allowStateChanges=!(e===!0||e===Jn)}[`computedRequiresReaction`,`reactionRequiresObservable`,`observableRequiresReaction`,`disableErrorBoundaries`,`safeDescriptors`].forEach(t=>{t in e&&(M[t]=!!e[t])}),M.allowStateReads=!M.observableRequiresReaction,M.disableErrorBoundaries===!0&&console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."),e.reactionScheduler&&yn(e.reactionScheduler)}function Xn(e,t,r,i){arguments.length>4&&n(`'extendObservable' expected 2-4 arguments`),typeof e!=`object`&&n(`'extendObservable' expects an object as first argument`),P(e)&&n(`'extendObservable' should not be used on maps, use map.merge instead`),g(t)||n(`'extendObservable' only accepts plain objects as second argument`),(xr(t)||xr(r))&&n(`Extending an object with another observable (object) is not supported`);let a=ae(t);return Ni(()=>{let t=wi(e,i)[E];te(a).forEach(e=>{t.extend_(e,a[e],r&&e in r?r[e]:!0)})}),e}function Zn(e,t){return Qn(Ai(e,t))}function Qn(e){let t={name:e.name_};return e.observing_&&e.observing_.length>0&&(t.dependencies=tr(e.observing_).map(Qn)),t}function $n(e,t){return er(Ai(e,t))}function er(e){let t={name:e.name_};return $t(e)&&(t.observers=Array.from(en(e),er)),t}function tr(e){return Array.from(new Set(e))}let nr=0;var rr=class extends Error{constructor(){super(`FLOW_CANCELLED`),Object.setPrototypeOf(this,new.target.prototype),this.name=`FlowCancellationError`}toString(){return`Error: ${this.message}`}};function ir(e){return e instanceof rr}function ar(e){return Xe(e,je)}let or=Oe(`flow`),sr=Oe(`flow.bound`,{bound:!0}),cr=r(function(e,t){if(t&&typeof t.kind==`string`)return je(or,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=++nr,a=Pn(`${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=Pn(`${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=Pn(`${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=Pn(`${i} - runid: ${n} - cancel`,function(){try{s&&ur(s);let e=a.return(void 0),t=Promise.resolve(e.value);t.then(f,f),ur(t),o(new rr)}catch(e){o(e)}}),c};return a.isMobXFlow=!0,a},or),lr=ar(sr);function ur(e){p(e.cancel)&&e.cancel()}function dr(e){return e}function fr(e){return e?.isMobXFlow===!0}function pr(e,t,r){let i;if(P(e)||pi(e)||kt(e))i=ji(e);else if(Di(e)){if(!m(t))return n(`InterceptReads can only be used with a specific property, not with an object in general`);i=ji(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 mr(e,t,n){return p(n)?gr(e,t,n):hr(e,t)}function hr(e,t){return qr(ji(e),t)}function gr(e,t,n){return qr(ji(e,t),n)}function _r(e,t){var n;if(t===void 0)return jt(e);if(Di(e)===!1)return!1;let r=e[E];return(n=r.lazyComputedKeys_)!=null&&n.has(t)?!0:r.values_.has(t)?jt(Ai(e,t)):!1}function vr(e){return arguments.length>1?n(`isComputed expects only 1 argument. Use isComputedProp to inspect the observability of a property`):_r(e)}function yr(e,t){return m(t)?_r(e,t):n(`isComputed expected a property name as second argument`)}function br(e,t){if(!e)return!1;if(t!==void 0){if(P(e)||pi(e))return n(`isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.`);if(Di(e)){var r,i;let n=e[E];return n.values_.has(t)||!!((r=n.lazyComputedKeys_)!=null&&r.has(t))||!!((i=n.lazyObservableKeys_)!=null&&i.has(t))}return!1}return Di(e)||!!e[E]||ce(e)||vn(e)||jt(e)}function xr(e){return arguments.length!==1&&n(`isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property`),br(e)}function Sr(e,t){return m(t)?br(e,t):n(`expected a property name as second argument`)}function Cr(e){if(Di(e))return e[E].keys_();if(P(e)||yi(e))return Array.from(e.keys());if(pi(e))return e.map((e,t)=>t);n(5)}function wr(e){if(Di(e))return Cr(e).map(t=>e[t]);if(P(e))return Cr(e).map(t=>e.get(t));if(yi(e))return Array.from(e.values());if(pi(e))return e.slice();n(6)}function Tr(e){if(Di(e))return Cr(e).map(t=>[t,e[t]]);if(P(e))return Cr(e).map(t=>[t,e.get(t)]);if(yi(e))return Array.from(e.entries());if(pi(e))return e.map((e,t)=>[t,e]);n(7)}function Er(e,t,r){if(arguments.length===2&&!yi(e)){an();let n=t;try{for(let t in n)Er(e,t,n[t])}finally{on()}return}Di(e)?e[E].set_(t,r):P(e)?e.set(t,r):yi(e)?e.add(t):pi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),t<0&&n(42,t),an(),t>=e.length&&(e.length=t+1),e[t]=r,on()):n(8)}function Dr(e,t){Di(e)?e[E].delete_(t):P(e)||yi(e)?e.delete(t):pi(e)?(typeof t!=`number`&&(t=parseInt(t,10)),e.splice(t,1)):n(9)}function Or(e,t){if(Di(e))return e[E].has_(t);if(P(e)||yi(e))return e.has(t);if(pi(e))return t>=0&&t<e.length;n(10)}function kr(e,t){if(Or(e,t)){if(Di(e))return e[E].get_(t);if(P(e))return e.get(t);if(pi(e))return e[t];n(11)}}function Ar(e,t,r){if(Di(e))return e[E].defineProperty_(t,r);n(39)}function jr(e){if(Di(e))return e[E].ownKeys_();n(38)}function Mr(e,t,n,r){return p(n)?Pr(e,t,n,r):Nr(e,t,n)}function Nr(e,t,r){let i=ji(e);if(pi(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(P(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with maps.");else if(yi(e))r===!0&&n("`observe` doesn't support fireImmediately=true in combination with sets.");else if(Di(e))r===!0&&n("`observe` doesn't support the fire immediately property for observable objects.");else return Fr(i,t,r);return Xr(i,t)}function Pr(e,t,n,r){return Fr(ji(e,t),n,r)}function Fr(e,t,n){if(jt(e)){let r=!0,i;return Bn(()=>{let a=e.get();if(!r||n){let n=Ht();t({observableKind:`computed`,debugObjectName:e.name_,type:ri,object:e,newValue:a,oldValue:i}),Ut(n)}r=!1,i=a})}return n&&t({observableKind:`value`,debugObjectName:e.name_,object:e,type:ri,newValue:e.value_,oldValue:void 0}),Xr(e,t)}function Ir(e,t,n){return e.set(t,n),n}function Lr(e,t){if(typeof e!=`object`||!e||e instanceof Date||!xr(e))return e;if(kt(e)||jt(e))return Lr(e.get(),t);if(t.has(e))return t.get(e);if(pi(e)){let n=Ir(t,e,Array(e.length));return e.forEach((e,r)=>{n[r]=Lr(e,t)}),n}if(yi(e)){let n=Ir(t,e,new Set);return e.forEach(e=>{n.add(Lr(e,t))}),n}if(P(e)){let n=Ir(t,e,new Map);return e.forEach((e,r)=>{n.set(r,Lr(e,t))}),n}else{let n=Ir(t,e,{});return jr(e).forEach(r=>{o.propertyIsEnumerable.call(e,r)&&(n[r]=Lr(e[r],t))}),n}}function Rr(e,t){return t&&n(`toJS no longer supports options`),Lr(e,new Map)}function zr(e,t=void 0){an();try{return e.apply(t)}finally{on()}}function Br(e,t,n){return arguments.length===1||t&&typeof t==`object`?Hr(e,t):Vr(e,t,n||{})}function Vr(e,t,n){let r;if(typeof n.timeout==`number`){let e=Error(`WHEN_TIMEOUT`);r=setTimeout(()=>{if(!a[E].isDisposed)if(a(),n.onError)n.onError(e);else throw e},n.timeout)}n.name=n.name||`When@`+u();let i=xt(n.name+`-effect`,t);var a=Bn(t=>{Tt(!1,e)&&(t.dispose(),r&&clearTimeout(r),i())},n);return a}function Hr(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=Vr(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 Ur(e){return e[E]}let Wr={has(e,t){return Ur(e).has_(t)},get(e,t){return Ur(e).get_(t)},set(e,t,n){return m(t)?Ur(e).set_(t,n,!0)??!0:!1},deleteProperty(e,t){return m(t)?Ur(e).delete_(t,!0)??!0:!1},defineProperty(e,t,n){return Ur(e).defineProperty_(t,n)??!0},ownKeys(e){return Ur(e).ownKeys_()},preventExtensions(e){n(13)}};function Gr(e,t){var n;return e=wi(e,t),(n=e[E]).proxy_??(n.proxy_=new Proxy(e,Wr))}function Kr(e){return e.interceptors_!==void 0&&e.interceptors_.length>0}function qr(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 Jr(e,t){let r=Ht();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{Ut(r)}}function Yr(e){return e.changeListeners_!==void 0&&e.changeListeners_.length>0}function Xr(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 Zr(e,t){let n=Ht(),r=e.changeListeners_;if(r){r=r.slice();for(let e=0,n=r.length;e<n;e++)r[e](t);Ut(n)}}function Qr(e,t,n){return Ni(()=>{let r=wi(e,n)[E];te(t).forEach(e=>ti(r,e,t[e]))}),e}let $r=Symbol(`mobx-keys`);function ei(e,t,r){return!g(e)&&!g(Object.getPrototypeOf(e))&&n(`'makeAutoObservable' can only be used for classes that don't have a superclass`),Di(e)&&n(`makeAutoObservable can only be used on objects not already made observable`),g(e)?Xn(e,e,t,r):(Ni(()=>{let n=wi(e,r)[E];if(!e[$r]){let t=Object.getPrototypeOf(e),n=new Set([...te(e),...te(t)]);n.delete(`constructor`),n.delete(E),v(t,$r,n)}e[$r].forEach(e=>ti(n,e,t&&e in t?t[e]:!0))}),e)}function ti(e,t,r){if(r===!0&&(r=e.defaultAnnotation_),r===!1)return;ki(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)}Oi(e,r,t)}let ni=`splice`,ri=`update`,ii={get(e,t){let n=e[E];return t===E?n:t===`length`?n.getArrayLength_():typeof t==`string`&&!isNaN(t)?n.get_(parseInt(t)):ie(si,t)?si[t]:e[t]},set(e,t,n){let r=e[E];return t===`length`?r.setArrayLength_(n):typeof t==`symbol`||isNaN(t)?e[t]=n:r.set_(parseInt(t),n),!0},preventExtensions(){n(15)}};var ai=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 se(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){A(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),Kr(this)){let r=Jr(this,{object:this.proxy_,type:ni,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_&&bn(),i=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,type:ri,debugObjectName:this.atom_.name_,index:e,newValue:t,oldValue:n}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(this,a),r&&wn()}notifyArraySplice_(e,t,n){let r=!this.owned_&&bn(),i=Yr(this),a=i||r?{observableKind:`array`,object:this.proxy_,debugObjectName:this.atom_.name_,type:ni,index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&Sn(a),this.atom_.reportChanged(),i&&Zr(this,a),r&&wn()}get_(e){return this.atom_.reportObserved(),this.dehanceValue_(this.values_[e])}set_(e,t){let n=this.values_;if(e<n.length){A(this.atom_);let r=n[e];if(Kr(this)){let n=Jr(this,{type:ri,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 oi(e,t,n=`ObservableArray@`+u(),r=!1){return Ni(()=>{let i=new ai(n,t,r);y(i.values_,E,i);let a=new Proxy(i.values_,ii);return i.proxy_=a,e&&e.length&&i.spliceWithArray_(0,0,e),a})}var si={clear(){return this.splice(0)},replace(e){let t=this[E];return t.spliceWithArray_(0,t.values_.length,e)},toJSON(){return this.slice()},splice(e,t,...n){let r=this[E];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[E].spliceWithArray_(e,t,n)},push(...e){let t=this[E];return t.spliceWithArray_(t.values_.length,0,e),t.values_.length},pop(){return this.splice(Math.max(this[E].values_.length-1,0),1)[0]},shift(){return this.splice(0,1)[0]},unshift(...e){let t=this[E];return t.spliceWithArray_(0,0,e),t.values_.length},reverse(){return M.trackingDerivation&&n(37,`reverse`),this.replace(this.slice().reverse()),this},sort(){M.trackingDerivation&&n(37,`sort`);let e=this.slice();return e.sort.apply(e,arguments),this.replace(e),this},remove(e){let t=this[E],n=t.dehanceValues_(t.values_).indexOf(e);return n>-1?(this.splice(n,1),!0):!1}};ci(`at`,li),ci(`concat`,li),ci(`flat`,li),ci(`includes`,li),ci(`indexOf`,li),ci(`join`,li),ci(`lastIndexOf`,li),ci(`slice`,li),ci(`toString`,li),ci(`toLocaleString`,li),ci(`toSorted`,li),ci(`toSpliced`,li),ci(`with`,li),ci(`every`,ui),ci(`filter`,ui),ci(`find`,ui),ci(`findIndex`,ui),ci(`findLast`,ui),ci(`findLastIndex`,ui),ci(`flatMap`,ui),ci(`forEach`,ui),ci(`map`,ui),ci(`some`,ui),ci(`toReversed`,ui),ci(`reduce`,di),ci(`reduceRight`,di);function ci(e,t){typeof Array.prototype[e]==`function`&&(si[e]=t(e))}function li(e){return function(){let t=this[E];t.atom_.reportObserved();let n=t.dehanceValues_(t.values_);return n[e].apply(n,arguments)}}function ui(e){return function(t,n){let r=this[E];return r.atom_.reportObserved(),r.dehanceValues_(r.values_)[e]((e,r)=>t.call(n,e,r,this))}}function di(e){return function(){let t=this[E];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 fi=b(`ObservableArrayAdministration`,ai);function pi(e){return h(e)&&fi(e[E])}let mi={},hi=`delete`;var gi=class{constructor(e,t=me,n=`ObservableMap@`+u()){this.enhancer_=void 0,this.name_=void 0,this[E]=mi,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,Ni(()=>{this.keysAtom_=le(`${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(!M.trackingDerivation)return this.has_(e);let t=this.hasMap_.get(e);if(!t){let n=t=new Ot(this.has_(e),ge,`${this.name_}.${ne(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(Kr(this)){let r=Jr(this,{type:n?ri:`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(A(this.keysAtom_),Kr(this)&&!Jr(this,{type:hi,object:this,name:e}))return!1;if(this.has_(e)){let t=bn(),n=Yr(this),r=n||t?{observableKind:`map`,debugObjectName:this.name_,type:hi,object:this,oldValue:this.data_.get(e).value_,name:e}:null;return t&&Sn(r),zr(()=>{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&&Zr(this,r),t&&wn(),!0}return!1}updateValue_(e,t){let n=this.data_.get(e);if(t=n.prepareNewValue_(t),t!==M.UNCHANGED){let r=bn(),i=Yr(this),a=i||r?{observableKind:`map`,debugObjectName:this.name_,type:ri,object:this,oldValue:n.value_,name:e,newValue:t}:null;r&&Sn(a),n.setNewValue_(t),i&&Zr(this,a),r&&wn()}}addValue_(e,t){A(this.keysAtom_),zr(()=>{var n;let r=new Ot(t,this.enhancer_,`${this.name_}.${ne(e)}`,!1);this.data_.set(e,r),t=r.value_,(n=this.hasMap_.get(e))==null||n.setNewValue_(!0),this.keysAtom_.reportChanged()});let n=bn(),r=Yr(this),i=r||n?{observableKind:`map`,debugObjectName:this.name_,type:`add`,object:this,name:e,newValue:t}:null;n&&Sn(i),r&&Zr(this,i),n&&wn()}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 F({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 F({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 P(e)&&(e=new Map(e)),zr(()=>{g(e)?ee(e).forEach(t=>this.set(t,e[t])):Array.isArray(e)?e.forEach(([e,t])=>this.set(e,t)):x(e)?(S(e)||n(19,e),e.forEach((e,t)=>this.set(t,e))):e!=null&&n(20,e)}),this}clear(){zr(()=>{Vt(()=>{for(let e of this.keys())this.delete(e)})})}replace(e){return zr(()=>{let t=I(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`}},P=b(`ObservableMap`,gi);function F(e){return e[Symbol.toStringTag]=`MapIterator`,zi(e)}function I(e){if(x(e)||P(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 _i={};var vi=class{constructor(e,t=me,n=`ObservableSet@`+u()){this.name_=void 0,this[E]=_i,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),Ni(()=>{this.atom_=le(this.name_),e&&this.replace(e)})}dehanceValue_(e){return this.dehancer===void 0?e:this.dehancer(e)}clear(){zr(()=>{Vt(()=>{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(A(this.atom_),Kr(this)){let t=Jr(this,{type:`add`,object:this,newValue:e});if(!t)return this;e=t.newValue}if(!this.has(e)){zr(()=>{e=this.enhancer_(e,void 0),this.data_.add(e),this.atom_.reportChanged()});let t=bn(),n=Yr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:`add`,object:this,newValue:e}:null;t&&Sn(r),n&&Zr(this,r),t&&wn()}return this}delete(e){if(Kr(this)&&!Jr(this,{type:hi,object:this,oldValue:e}))return!1;if(this.has(e)){let t=bn(),n=Yr(this),r=n||t?{observableKind:`set`,debugObjectName:this.name_,type:hi,object:this,oldValue:e}:null;return t&&Sn(r),zr(()=>{this.atom_.reportChanged(),this.data_.delete(e)}),n&&Zr(this,r),t&&wn(),!0}return!1}has(e){return this.atom_.reportObserved(),this.data_.has(this.dehanceValue_(e))}entries(){let e=this.values();return bi({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 bi({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 yi(e)&&(e=new Set(e)),Array.isArray(e)||C(e)?zr(()=>{let t=C(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`}},yi=b(`ObservableSet`,vi);function bi(e){return e[Symbol.toStringTag]=`SetIterator`,zi(e)}let xi=Object.create(null),Si=`remove`;var Ci=class{constructor(e,t=new Map,r,i=We){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 se(`${this.name_}.keys`),this.isPlainObject_=g(this.target_),Vi(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 At)return n.set(t),!0;if(Kr(this)){let n=Jr(this,{type:ri,object:this.proxy_||this.target_,name:e,newValue:t});if(!n)return null;t=n.newValue}if(t=n.prepareNewValue_(t),t!==M.UNCHANGED){let r=Yr(this),i=bn(),a=r||i?{type:ri,observableKind:`object`,debugObjectName:this.name_,object:this.proxy_||this.target_,oldValue:n.value_,name:e,newValue:t}:null;i&&Sn(a),n.setNewValue_(t),r&&Zr(this,a),i&&wn()}return!0}get_(e){return M.trackingDerivation&&!ie(this.target_,e)&&this.has_(e),this.target_[e]}set_(e,t,n=!1){return ie(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(!M.trackingDerivation)return e in this.target_;this.pendingKeys_||=new Map;let t=this.pendingKeys_.get(e);return t||(t=new Ot(e in this.target_,ge,`${this.name_}.${ne(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);ki(this,n,e);let i=n.extend_(this,e,t,r);return i&&Oi(this,n,e),i}defineProperty_(e,t,n=!1){A(this.keysAtom_);try{an();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=Jr(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{on()}return!0}defineObservableProperty_(e,t,n,r=!1){A(this.keysAtom_);try{an();let i=this.delete_(e);if(!i)return i;if(Kr(this)){let n=Jr(this,{object:this.proxy_||this.target_,name:e,type:`add`,newValue:t});if(!n)return null;t=n.newValue}let o=Ei(e),s={configurable:M.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 Ot(t,n,`${this.name_}.${e.toString()}`,!1);this.values_.set(e,c),this.notifyPropertyAddition_(e,c.value_)}finally{on()}return!0}defineComputedProperty_(e,t,n=!1){A(this.keysAtom_);try{an();let r=this.delete_(e);if(!r)return r;if(Kr(this)&&!Jr(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=Ei(e),o={configurable:M.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 At(t)),this.notifyPropertyAddition_(e,void 0)}finally{on()}return!0}delete_(e,t=!1){if(A(this.keysAtom_),!ie(this.target_,e))return!0;if(Kr(this)&&!Jr(this,{object:this.proxy_||this.target_,name:e,type:Si}))return null;try{var n;an();let r=Yr(this),a=bn(),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 Ot&&(s=o.value_),un(o)),this.keysAtom_.reportChanged(),(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(e in this.target_),r||a){let t={type:Si,observableKind:`object`,object:this.proxy_||this.target_,debugObjectName:this.name_,oldValue:s,name:e};a&&Sn(t),r&&Zr(this,t),a&&wn()}}finally{on()}return!0}notifyPropertyAddition_(e,t){var n;let r=Yr(this),i=bn();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&&Sn(n),r&&Zr(this,n),i&&wn()}(n=this.pendingKeys_)==null||(n=n.get(e))==null||n.set(!0),this.keysAtom_.reportChanged()}ownKeys_(){return this.keysAtom_.reportObserved(),te(this.target_)}keys_(){return this.keysAtom_.reportObserved(),Object.keys(this.target_)}};function wi(e,t){if(t&&Di(e)&&n(`Options can't be provided for already observable objects.`),ie(e,E))return ji(e)instanceof Ci||n(`Cannot convert '${Mi(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,E,new Ci(e,new Map,String(r),at(t))),e}let Ti=b(`ObservableObjectAdministration`,Ci);function Ei(e){return xi[e]||(xi[e]={get(){return this[E].getObservablePropValue_(e)},set(t){return this[E].setObservablePropValue_(e,t)}})}function Di(e){return h(e)?Ti(e[E]):!1}function Oi(e,t,n){e.appliedAnnotations_[n]=t}function ki(e,t,r){if(Vi(t)||n(`Cannot annotate '${e.name_}.${r.toString()}': Invalid annotation.`),!be(t)&&ie(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 Ai(e,t){if(typeof e==`object`&&e){if(pi(e))return t!==void 0&&n(23),e[E].atom_;if(yi(e))return e.atom_;if(P(e)){if(t===void 0)return e.keysAtom_;let r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,Mi(e)),r}if(Di(e)){if(!t)return n(26);let r=e[E],i=r.values_.get(t)??r.materializeLazyComputed_(t)??r.materializeLazyObservable_(t);return i||n(27,t,Mi(e)),i}if(ce(e)||jt(e)||vn(e))return e}else if(p(e)&&vn(e[E]))return e[E];n(28)}function ji(e,t){if(e||n(29),t!==void 0)return ji(Ai(e,t));if(ce(e)||jt(e)||vn(e)||P(e)||yi(e))return e;if(e[E])return e[E];n(24,e)}function Mi(e,t){let n;if(t!==void 0)n=Ai(e,t);else if(zn(e))return e.name;else n=Di(e)||P(e)||yi(e)?ji(e):Ai(e);return n.name_}function Ni(e){let t=Ht(),n=Et(!0);an();try{return e()}finally{on(),Dt(n),Ut(t)}}let Pi=o.toString;function Fi(e,t,n=-1){return Ii(e,t,n)}function Ii(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=Pi.call(e);if(o!==Pi.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=Li(e),t=Li(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(!Ii(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(!(ie(t,o)&&Ii(e[o],t[o],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function Li(e){return pi(e)?e.slice():x(e)||P(e)||C(e)||yi(e)?Array.from(e.entries()):e}let Ri=globalThis.Iterator?.prototype||{};function zi(e){return e[Symbol.iterator]=Bi,r(Object.create(Ri),e)}function Bi(){return this}function Vi(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:Tn,extras:{getDebugName:Mi},$mobx:E}),e.$mobx=E,e.FlowCancellationError=rr,e.ObservableMap=gi,e.ObservableSet=vi,e.Reaction=pn,e._allowStateChanges=Tt,e._allowStateChangesInsideComputed=Rn,e._allowStateReadsEnd=Wt,e._allowStateReadsStart=j,e._autoAction=Fn,e._autoActionBound=Ln,e._endAction=wt,e._getAdministration=ji,e._getGlobalState=Zt,e._interceptReads=pr,e._isComputingDerivation=Ft,e._resetGlobalState=Qt,e._startAction=Ct,e.action=Pn,e.actionBound=In,e.autorun=Bn,e.compareDefault=pe,e.compareIdentity=ue,e.compareShallow=fe,e.compareStructural=de,e.computed=k,e.computedStruct=gt,e.configure=Yn,e.createAtom=le,e.defineProperty=Ar,e.entries=Tr,e.extendObservable=Xn,e.flow=cr,e.flowBound=lr,e.flowResult=dr,e.get=kr,e.getAtom=Ai,e.getDebugName=Mi,e.getDependencyTree=Zn,e.getObserverTree=$n,e.has=Or,e.intercept=mr,e.isAction=zn,e.isBoxedObservable=kt,e.isComputed=vr,e.isComputedProp=yr,e.isFlow=fr,e.isFlowCancellationError=ir,e.isObservable=xr,e.isObservableArray=pi,e.isObservableMap=P,e.isObservableObject=Di,e.isObservableProp=Sr,e.isObservableSet=yi,e.keys=Cr,e.makeAutoObservable=ei,e.makeObservable=Qr,e.observable=O,e.observableDeep=dt,e.observableRef=lt,e.observableShallow=ut,e.observableStruct=ft,e.observe=Mr,e.onBecomeObserved=Gn,e.onBecomeUnobserved=Kn,e.onReactionError=mn,e.override=ye,e.ownKeys=jr,e.reaction=Un,e.remove=Dr,e.runInAction=Rn,e.set=Er,e.spy=Tn,e.toJS=Rr,e.transaction=zr,e.untracked=Vt,e.values=wr,e.when=Br})),F_=ye(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=N_():t.exports=P_()}))();function I_(e){if(Array.isArray(e))return Object.freeze(e.map(I_));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]=I_(r);return Object.freeze(t)}return e}function L_(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 R_(e){return typeof e==`string`?e:String(e)}function z_(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 B_(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 V_=class extends Error{constructor(e,t){super(t),this.variable=e}};function H_(e){return e instanceof V_||e instanceof Error&&e.cause!==void 0&&H_(e.cause)}var U_=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?Q_(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}},W_=class extends U_{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},G_=class extends U_{name=`EvalError`;kind=`EvalError`},K_=class extends G_{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=$_(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}},q_=class extends G_{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}},J_=class extends G_{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}},Y_=class extends J_{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)}`}},X_=class extends G_{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},Z_=class extends G_{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function Q_(e,t){let n=e.split(`
57
57
  `),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(`
58
- `)}function Q_(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:$_(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 $_(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 ev(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const tv=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`]]),nv={left:`{{`,right:`}}`};var rv=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=nv){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 U_(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&&iv(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);iv(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);iv(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(;iv(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`;iv(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&&(ov(e)||av(e)&&ov(this.src[this.offset+1]??``)||e===`.`&&ov(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&dv(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===`
58
+ `)}function $_(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:ev(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 ev(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 tv(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const nv=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`]]),rv={left:`{{`,right:`}}`};var iv=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=rv){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 W_(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&&av(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);av(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);av(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(;av(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`;av(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&&(sv(e)||ov(e)&&sv(this.src[this.offset+1]??``)||e===`.`&&sv(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&fv(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===`
59
59
  `)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===`
60
- `)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(av(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);sv(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);cv(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);lv(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;ov(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);ov(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),av(this.src[this.offset]??``)&&this.advanceBy(1);ov(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return sv(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);fv(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&dv(this.src[this.offset+1]??``);)for(this.advanceBy(1);fv(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),!dv(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;fv(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&dv(this.src[this.offset+1]??``);)for(this.advanceBy(1);fv(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(;fv(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=tv.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===`
60
+ `)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(ov(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);cv(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);lv(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);uv(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;sv(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);sv(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),ov(this.src[this.offset]??``)&&this.advanceBy(1);sv(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return cv(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);pv(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&fv(this.src[this.offset+1]??``);)for(this.advanceBy(1);pv(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),!fv(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;pv(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&fv(this.src[this.offset+1]??``);)for(this.advanceBy(1);pv(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(;pv(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=nv.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===`
61
61
  `)this.advanceBy(1);else return}}advanceBy(e){for(let t=0;t<e;t++){let e=this.src[this.offset];this.offset+=1,e===`
62
- `?(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 iv(e){return e===` `||e===` `||e===`\r`||e===`
63
- `}function av(e){return e===`+`||e===`-`}function ov(e){return e>=`0`&&e<=`9`}function sv(e){return ov(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function cv(e){return e>=`0`&&e<=`7`}function lv(e){return e===`0`||e===`1`}function uv(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function dv(e){return uv(e)||e===`_`}function fv(e){return dv(e)||ov(e)}let pv,mv;function hv(e,t){return mv(e,t)}var gv=class e{static EMPTY=new e(new Map,void 0);#e;#t;constructor(e,t){this.#e=e,this.#t=t}static{pv=(t,n)=>new e(t,n),mv=(e,t)=>e.#e.get(t)??(e.#t&&mv(e.#t,t))}has(e){return mv(this,e)!==void 0}};function _v(e,t,n=gv.EMPTY){return new vv(e,t,n).parseTemplate()}var vv=class{lex;buf=[];defines=new Map;inherit;source;rangeDepth=0;constructor(e,t,n){this.source=e,this.inherit=n,this.lex=t?new rv(e,t):new rv(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:xv(n)});return n}errAt(e,t,n={}){return new U_(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 ${xv(e)}`,{found:xv(e)})}return{root:e,defines:pv(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=bv(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 yv(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${xv(n)} at top level`,{found:xv(n)})}return yv(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 U_(`{{${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 U_(`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:xv(e)});return kv(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(!Sv(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:xv(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=[Cv(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(Cv(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;Sv(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 Cv(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:kv(e.value,e.pos,this.source)};case`Number`:return Tv(e);case`Char`:return Ev(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 ${xv(e)}`,{expected:`command argument`,found:xv(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 yv(e,t){return{type:`List`,pos:e,nodes:t}}function bv(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function xv(e){return e.type===`EOF`?`end of input`:e.value||e.type}function Sv(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 Cv(e){return{type:`Variable`,pos:e.pos,idents:wv(e.value)}}function wv(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function Tv(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=Dv(i);return{...s,intValue:e}}if(a){let e=Ov(i);return{...s,floatValue:e}}let c=Ov(i);return{...s,complexValue:[0,c]}}function Ev(e,t){let n=Av(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 Dv(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 Ov(e){return Number(e)}function kv(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+=`
64
- `;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 U_(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function Av(e,t,n){let r=kv(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new U_(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function jv(e,t){if(t(e)!==!1)for(let n of Mv(e))jv(n,t)}function Mv(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 ev(e)}}const Nv=Symbol(`go-template-js.MISSING`);function Pv(e,t){if(e==null)return Nv;if(e instanceof Map)return e.has(t)?e.get(t):Nv;if(Array.isArray(e))return Nv;if(typeof e==`object`){let n=e;return t in n?n[t]:Nv}return Nv}function Fv(e,t){let n=e;for(let e of t){if(n===Nv)return Nv;n=Pv(n,e)}return n}function Iv(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)=>Iv(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)||!Iv(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=>Iv(e[n],t[n])):!1}return!1}const Lv=new WeakSet;function Rv(e){return Lv.add(e),e}function zv(e){return Lv.has(e)}function Bv(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 Vv(e,t){return{eq:{fn:(e,...t)=>t.some(t=>Wv(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!Wv(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>Gv(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>Gv(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>Gv(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>Gv(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>Kv(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=qv(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>Yv(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>Qv(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${Qv(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>sy(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>uy(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>uy(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>ty(Qv(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>iy(Qv(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>oy(Qv(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!Bv(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function Hv(){return{and:Rv({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!Bv(t))return t;return t}}),or:Rv({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),Bv(t))return t;return t}})}}function Uv(e,t){return{...Vv(e,t),...Hv()}}function Wv(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):Iv(e,t)}function Gv(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 Kv(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function qv(e,t){if(Array.isArray(e)||typeof e==`string`){let n=Jv(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 ${Xv(t)}`);return e[t]}throw Error(`index: cannot index ${Xv(e)}`)}function Jv(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 ${Zv(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function Yv(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]=Jv(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 Xv(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Zv(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 Qv(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+=$v(a,t),r=o}return n}function $v(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const ey={"\0":`�`,'"':`&#34;`,"'":`&#39;`,"&":`&amp;`,"<":`&lt;`,">":`&gt;`};function ty(e){return e.replace(/[\0"'&<>]/g,e=>ey[e]??e)}const ny={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},ry=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function iy(e){let t=``;for(let n of e){let e=ny[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!ry.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const ay=new TextEncoder;function oy(e){let t=``,n=ay.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 sy(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+=cy(l??``,u,d,n,r),o=c+1}return i}function cy(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?ly(t,n):ly(t,$v(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Zv(n)}=${$v(n,r)})`:ly(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return ly(t,uy(n,r,i));case`q`:return ly(t,JSON.stringify($v(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${Zv(n)}=${$v(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return ly(t,Number(n).toFixed(i))}case`t`:return ly(t,Bv(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 ly(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Zv(n)}=${$v(n,r)})`:typeof n==`bigint`?ly(t,n.toString(16)):ly(t,Math.trunc(n).toString(16));default:return`%!${e}(${Zv(n)}=${$v(n,r)})`}}function ly(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 uy(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>uy(e,t,n)).join(` `)}]`:e instanceof Map?dy([...e.entries()],t,n):fy(e)?dy(Object.entries(e),t,n):String(e)}function dy(e,t,n){let r=e=>uy(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 fy(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 py(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function my(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function hy(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 gy(e,t,n){e.vars.set(t,n)}const _y=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],vy=new Set([`default`,`zero`,`error`]);function yy(e){if(e===void 0)return`default`;if(vy.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${by(e)}`)}function by(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 xy(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${by(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${by(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${by(e.right)}`);return{left:e.left,right:e.right}}}function Sy(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function Cy(e){let t=new Set(_y);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 ${_y.join(`, `)}`)}),Sy(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 wy=Object.freeze({kind:`break`}),Ty=Object.freeze({kind:`continue`}),Ey={kind:`none`};let Dy;(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{Dy=(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 Oy(e){let t=new Set,n=e=>{jv(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 ky={kind:`dynamic`};function Ay(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=Zy(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:ky}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return ky;let t=e.cmds[0];if(t===void 0)return ky;let n=t.args[0];return n===void 0||n.type!==`Identifier`?ky:{kind:`call`,name:n.ident,args:t.args.slice(1).map(Ay)}}default:return ky}}function jy(e){let t=[],n=e=>{jv(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(Ay);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 My=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??By,this.isT=e.isT??Ny,this.missingKey=yy(e.missingKey),this.delims=xy(e.delims),this.funcs=Cy({...Uv(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=_v(e,this.delims,t);return Dy(n.source,e=>this.evalParsed(n,e),n.defines,Oy(n),jy(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=py(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 wy;case`Continue`:throw Ty;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 W_(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:ev(e)}}evalIf(e,t,n){Bv(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(Bv(r)){let i=my(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=Jy(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=my(t,o);if(i.length===1)gy(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;gy(a,e,r),gy(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===Ty)continue;throw e}}}catch(e){if(e===wy)return;throw e}}evalTemplateInvoke(e,t,n){let r=hv(n.defines,e.name);if(!r)throw new W_(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=my(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=my(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=hv(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 W_(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,Ey);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)gy(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 W_(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new W_(`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 G_(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=zv(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){Fy(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof q_?new q_(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof X_?new X_(t.message,r,{source:i.source}):t instanceof H_?t:new W_(`error calling ${e}: ${Ky(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 Zy(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 G_(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 W_(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=Fv(e,t);if(i!==Nv)return i;if(this.missingKey===`error`)throw new Y_(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=hy(t,i);if(!a.found)throw new W_(`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(uy(e,this.toString,this.isT)))}};const Ny=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function Py(e){return new My(e)}function Fy(e,t,n,r,i,a=By,o=zy,s=Ny){let{argTypes:c,arity:l}=t,u=Iy(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new K_(e,u,n.length,r,{source:i});let d=Ly(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!Ry(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new J_(e,t+1,l,r,{source:i}):new q_(e,t+1,Gy(c),qy(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(!Hy(n[f],l))throw new q_(e,t+1,`${Gy(`ordered`)} of the same kind as ${qy(n[f])}`,qy(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!Uy(n[p],l))throw new q_(e,t+1,`${Gy(`comparable`)} of the same kind as ${qy(n[p])}`,qy(l),r,{source:i})}}}function Iy(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 Ly(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 Ry(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 fy(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||fy(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||fy(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||fy(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 Vy(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function zy(e){return e}function By(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 q_(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,qy(e),{line:0,column:0,offset:0})}function Vy(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function Hy(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function Uy(e,t){let n=Wy(e),r=Wy(t);return n===`nil`||r===`nil`?!0:n===r}function Wy(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 Gy(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 Ky(e){return e instanceof Error?e.message:String(e)}function qy(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Jy(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?Yy([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?Yy(Object.entries(e)):[]}function Yy(e){return[...e].sort((e,t)=>Xy(e[0],t[0]))}function Xy(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 Zy(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 Qy(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function $y(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 eb(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 tb(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=eb(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 nb(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=eb(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 rb(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 ib(e){return JSON.stringify(e)??`null`}function ab(){return{atoi:{fn:e=>Qy(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>tb(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>nb(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>$y(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>rb(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>ib(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const ob={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function sb(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*ob[a],n=n.slice(e[0].length)}return t?-r:r}function cb(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<ob.us?`${Math.floor(n)}ns`:n<ob.ms?lb(n,ob.us,3,`µs`):n<ob.s?lb(n,ob.ms,6,`ms`):ub(n),t?`-${r}`:r}function lb(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 ub(e){let t=Math.floor(e/ob.h);e-=t*ob.h;let n=Math.floor(e/ob.m);e-=n*ob.m;let r=Math.floor(e/ob.s),i=e-r*ob.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 db(e){return e*ob.s}function fb(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 pb(e,t){let n=t().getTime()-fb(e).getTime();return cb(Math.round(n/1e3)*1e9)}const mb=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],hb=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],gb=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],_b=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function vb(e){return e<10?`0${e}`:String(e)}function yb(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function bb(e){return e<10?` ${e}`:String(e)}function xb(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${vb(Math.floor(n/60))}${vb(n%60)}`}function Sb(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${vb(Math.floor(n/60))}:${vb(n%60)}`}function Cb(e){return`${e>=0?`+`:`-`}${vb(Math.floor(Math.abs(e)/60))}`}function wb(e){return e===0?`Z`:xb(e)}function Tb(e){return e===0?`Z`:Sb(e)}function Eb(e){return e===0?`Z`:Cb(e)}function Db(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const Ob=[[`.000000000`,e=>`.${Db(e.ms,9,!1)}`],[`.999999999`,e=>{let t=Db(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${Db(e.ms,6,!1)}`],[`.999999`,e=>{let t=Db(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${yb(e.ms)}`],[`.999`,e=>{let t=yb(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>mb[e.month-1]??`January`],[`Monday`,e=>gb[e.weekday]??`Monday`],[`Z07:00`,e=>Tb(e.offsetMinutes)],[`-07:00`,e=>Sb(e.offsetMinutes)],[`Z0700`,e=>wb(e.offsetMinutes)],[`-0700`,e=>xb(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>hb[e.month-1]??`Jan`],[`Mon`,e=>_b[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>Cb(e.offsetMinutes)],[`Z07`,e=>Eb(e.offsetMinutes)],[`15`,e=>vb(e.hour)],[`01`,e=>vb(e.month)],[`02`,e=>vb(e.day)],[`_2`,e=>bb(e.day)],[`03`,e=>vb(e.hour12)],[`04`,e=>vb(e.minute)],[`05`,e=>vb(e.second)],[`06`,e=>vb(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 kb(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of Ob)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const Ab={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function jb(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const Mb=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function Nb(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=jb(new Intl.DateTimeFormat(`en-US`,{...Ab,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=jb(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=Pb(jb(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=Mb.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 Pb(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 Fb(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function Ib(e,t){return kb(e,Nb(fb(t),Fb()))}function Lb(e,t,n){return kb(e,Nb(fb(t),n))}function Rb(e,t){let n=fb(t),r=sb(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function zb(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:cb(db(t))}return typeof e==`bigint`?cb(db(Number(e))):typeof e==`number`?cb(db(e)):`0s`}const Bb=36e11*24*365,Vb=36e11*24*30,Hb=36e11*24,Ub=36e11,Wb=6e10,Gb=1e9;function Kb(e){let t=sb(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>Bb?`${Math.floor(n/Bb)}y`:n>Vb?`${Math.floor(n/Vb)}mo`:n>Hb?`${Math.floor(n/Hb)}d`:n>Ub?`${Math.floor(n/Ub)}h`:n>Wb?`${Math.floor(n/Wb)}m`:n>Gb?`${Math.floor(n/Gb)}s`:`0s`}function qb(e){let t=Nb(fb(e),Fb());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function Jb(e,t){let n=Nb(fb(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function Yb(e){return e()}const Xb=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Zb=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function Qb(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function $b(e,t,n){return[e.slice(t,t+n),t+n]}function ex(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 tx(e,t){for(let[n,r]of Xb.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function nx(e,t){for(let[n,r]of Zb.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function rx(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 ix(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 ax(e,t){if(e[t]===` `){let[n,r]=ex(e,t+1,1,1);return[n,r]}return ex(e,t,1,2)}function ox(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]=ex(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=ex(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=ex(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function sx(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]=ex(e,t+1,2,2);return[n*r*60,i]}return ox(e,t,n)}function cx(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 lx(e,t,n){let[r,i]=$b(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function ux(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=tx(t,n);return i.month=e,[r,i]}case`Monday`:return[rx(t,n),i];case`Jan`:{let[e,r]=nx(t,n);return i.month=e,[r,i]}case`Mon`:return[ix(t,n),i];case`2006`:{let[e,r]=ex(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=ex(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=ex(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=ex(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=ax(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=ex(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=ex(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=ex(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=ex(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=ex(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=ex(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=ex(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=ex(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=ex(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[cx(t,n),i];case`-0700`:{let[e,r]=ox(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=ox(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]=ex(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=sx(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=sx(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=sx(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]=lx(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]=lx(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]=lx(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 dx=`.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 fx(e,t){let n=0,r=0,i=Qb();for(;n<e.length;){let a=!1;for(let o of dx)if(e.startsWith(o,n)){let[e,s]=ux(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 px(e,t){return fx(e,t)}function mx(e){return String(Math.floor(fb(e).getTime()/1e3))}function hx(e=()=>new Date){return{now:{fn:()=>Yb(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>Ib(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>Lb(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>Rb(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>qb(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>Jb(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>zb(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>Kb(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>px(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>pb(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>mx(e),argTypes:[`value`],arity:{kind:`exact`}}}}function gx(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 _x(...e){for(let t of e)if(!gx(t))return t}function vx(e,t){return gx(t)?e:t}function yx(e){return JSON.parse(e)}function bx(e,t,n){return Bv(n)?e:t}function xx(e){return JSON.stringify(e)??`null`}function Sx(e){return JSON.stringify(e,null,2)??`null`}function Cx(){return{default:{fn:(e,t)=>vx(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>gx(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>_x(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>bx(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>yx(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>xx(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>Sx(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function wx(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function Tx(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 wx(...t)}function Ex(e,t){return e[t]}function Dx(e,t){return t in e}function Ox(e){return Object.keys(e)}function kx(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 Ax(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function jx(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 Mx(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function Nx(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function Px(e,t,n){return e[t]=n,e}function Fx(e,t){return delete e[t],e}function Ix(e){return Object.values(e)}function Lx(){return{dict:{fn:(...e)=>wx(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>Ex(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>Px(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>Fx(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>Ox(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>Ix(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>Nx(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>Mx(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>jx(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>Dx(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>kx(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>Ax(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function Rx(e){throw new X_(e)}function zx(){return{fail:{fn:e=>Rx(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 Bx(...e){for(let t of e)if(gx(t))return!1;return!0}function Vx(...e){for(let t of e)if(!gx(t))return!0;return!1}function Hx(e,t){return[...e,t]}function Ux(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 Wx(e){return e.filter(e=>!gx(e))}function Gx(...e){let t=[];for(let n of e)t.push(...n);return t}const Kx={line:0,column:0,offset:0};function qx(e,t,n,r){return new q_(e,t,n,r,Kx)}function Jx(...e){if(e.length<3)throw qx(`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(!Xx(t))throw qx(`dig`,e.length-1,`dict`,Zx(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw qx(`dig`,e,`string`,Zx(r[e]));return Yx(t,n,r,e.length)}function Yx(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(!Xx(a))throw qx(`dig`,r-1,`dict at intermediate key`,Zx(a));return Yx(a,t,n.slice(1),r)}function Xx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function Zx(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function Qx(e){return e[0]}function $x(e,t){return t.some(t=>Iv(t,e))}function eS(e){return e.slice(0,-1)}function tS(e){return e[e.length-1]}function nS(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function rS(...e){return e}function iS(e,t){return[t,...e]}function aS(e){return e.slice(1)}function oS(e){return[...e].reverse()}function sS(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function cS(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function lS(e){let t=[];for(let n of e)t.some(e=>Iv(e,n))||t.push(n);return t}function uS(e,...t){return e.filter(e=>!t.some(t=>Iv(t,e)))}function dS(){return{list:{fn:(...e)=>rS(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>Qx(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>tS(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>aS(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>eS(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>nS(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>oS(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>lS(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>uS(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>$x(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>Wx(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>sS(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>Gx(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>Ux(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>iS(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>Hx(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>cS(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>Hx(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>rS(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>Jx(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>Bx(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>Vx(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function fS(...e){return e.reduce((e,t)=>e+t,0)}function pS(e){return e+1}function mS(e){return e+1}function hS(...e){return e.reduce((e,t)=>e+t,0)}function gS(e){return Math.ceil(e)}function _S(e,t){return Math.trunc(e/t)}function vS(e,...t){return t.reduce((e,t)=>e/t,e)}function yS(e){return Math.floor(e)}function bS(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function xS(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function SS(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function CS(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function wS(e,t){return e%t}function TS(...e){return e.reduce((e,t)=>e*t,1)}function ES(...e){return e.reduce((e,t)=>e*t,1)}function DS(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function OS(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 kS(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),OS(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return OS(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:OS(n,i+t,r).join(` `)}default:return``}}function AS(e,t){return e-t}function jS(e,...t){return t.reduce((e,t)=>e-t,e)}function MS(e){return OS(0,e,e<0?-1:1)}function NS(){return{add:{fn:(...e)=>fS(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>AS(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>TS(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>_S(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>wS(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>SS(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>bS(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>yS(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>gS(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>DS(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>hS(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>jS(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>ES(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>vS(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>pS(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>mS(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>xS(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>CS(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>bS(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>kS(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>MS(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>OS(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function PS(e){return Array.from(e)}function FS(e,t){return e===``?PS(t):t.split(e)}function IS(e,t){let n=PS(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function LS(e,t,n){let r=PS(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const q={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},RS=/^[-_\s]$/,zS=/^\p{P}$/u,BS=/^\p{L}$/u,VS=/^\p{Lu}$/u,HS=/^\p{N}$/u;function US(e){return e!==void 0&&RS.test(e)}function WS(e){return e!==void 0&&BS.test(e)}function GS(e){return e!==void 0&&VS.test(e)}function KS(e){return e!==void 0&&HS.test(e)}function qS(e){return e!==void 0&&zS.test(e)}function JS(e,t){if(t>=e.length)return{word:{wt:q.Invalid,text:``},next:t};let n=e[t],r=t+1;if(US(n)){for(;r<e.length&&US(e[r]);)r++;return{word:{wt:q.Connector,text:e.slice(t,r).join(``)},next:r}}if(qS(n)){for(;r<e.length&&qS(e[r]);)r++;return{word:{wt:q.Punct,text:e.slice(t,r).join(``)},next:r}}if(GS(n)){if(r>=e.length)return{word:{wt:q.UpperCase,text:n},next:r};if(GS(e[r])){let n=r;for(;n<e.length&&GS(e[n]);)n++;return n<e.length&&WS(e[n])?{word:{wt:q.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:q.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(WS(e[r])){let n=r+1;for(;n<e.length&&WS(e[n])&&!GS(e[n]);)n++;return{word:{wt:q.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:q.UpperCase,text:n},next:r}}if(WS(n)){for(;r<e.length&&WS(e[r])&&!GS(e[r]);)r++;return{word:{wt:q.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(KS(n)){for(;r<e.length&&KS(e[r]);)r++;return{word:{wt:q.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!US(e[r])&&!WS(e[r])&&!KS(e[r])&&!qS(e[r]);)r++;return{word:{wt:q.Other,text:e.slice(t,r).join(``)},next:r}}function YS(e,t,n){if(t.wt!==q.UpperCase&&t.wt!==q.Connector){e.push(t.text);return}for(let r of t.text)US(r)?e.push(n):GS(r)?e.push(r.toLowerCase()):e.push(r)}function XS(e,t){if(e.length===0)return``;let n=PS(e),r=[],{word:i,next:a}=JS(n,0);for(;a<n.length;){i.wt!==q.Connector&&YS(r,i,t);let e=i,o=i;if({word:i,next:a}=JS(n,a),e.wt===q.Number){for(;i.wt===q.Alphabet||i.wt===q.Number;)YS(r,i,t),{word:i,next:a}=JS(n,a);i.wt!==q.Invalid&&i.wt!==q.Punct&&i.wt!==q.Connector&&r.push(t);continue}if(e.wt===q.Connector){YS(r,o,t);continue}if(e.wt===q.Punct)continue;if(i.wt!==q.Number){i.wt!==q.Connector&&i.wt!==q.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=JS(n,a),i.wt!==q.Alphabet){YS(r,s,t),i.wt!==q.Connector&&i.wt!==q.Punct&&r.push(t);continue}for(r.push(t),YS(r,s,t);i.wt===q.Alphabet||i.wt===q.Number;)YS(r,i,t),{word:i,next:a}=JS(n,a);i.wt!==q.Invalid&&i.wt!==q.Connector&&i.wt!==q.Punct&&r.push(t)}return YS(r,i,t),r.join(``).toLowerCase()}function ZS(e){if(e.length===0)return``;let t=PS(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!US(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++,US(i)&&US(e)){n.push(e);continue}US(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function QS(e){return ZS(e)}function $S(...e){return e.join(` `)}function eC(e,t){return t.includes(e)}function tC(e,t){return t.startsWith(e)}function nC(e,t){return t.endsWith(e)}function rC(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
62
+ `?(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 av(e){return e===` `||e===` `||e===`\r`||e===`
63
+ `}function ov(e){return e===`+`||e===`-`}function sv(e){return e>=`0`&&e<=`9`}function cv(e){return sv(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function lv(e){return e>=`0`&&e<=`7`}function uv(e){return e===`0`||e===`1`}function dv(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function fv(e){return dv(e)||e===`_`}function pv(e){return fv(e)||sv(e)}let mv,hv;function gv(e,t){return hv(e,t)}var _v=class e{static EMPTY=new e(new Map,void 0);#e;#t;constructor(e,t){this.#e=e,this.#t=t}static{mv=(t,n)=>new e(t,n),hv=(e,t)=>e.#e.get(t)??(e.#t&&hv(e.#t,t))}has(e){return hv(this,e)!==void 0}};function vv(e,t,n=_v.EMPTY){return new yv(e,t,n).parseTemplate()}var yv=class{lex;buf=[];defines=new Map;inherit;source;rangeDepth=0;constructor(e,t,n){this.source=e,this.inherit=n,this.lex=t?new iv(e,t):new iv(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:Sv(n)});return n}errAt(e,t,n={}){return new W_(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 ${Sv(e)}`,{found:Sv(e)})}return{root:e,defines:mv(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=xv(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 bv(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${Sv(n)} at top level`,{found:Sv(n)})}return bv(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 W_(`{{${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 W_(`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:Sv(e)});return Av(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(!Cv(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:Sv(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=[wv(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(wv(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;Cv(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 wv(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:Av(e.value,e.pos,this.source)};case`Number`:return Ev(e);case`Char`:return Dv(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 ${Sv(e)}`,{expected:`command argument`,found:Sv(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 bv(e,t){return{type:`List`,pos:e,nodes:t}}function xv(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function Sv(e){return e.type===`EOF`?`end of input`:e.value||e.type}function Cv(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 wv(e){return{type:`Variable`,pos:e.pos,idents:Tv(e.value)}}function Tv(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function Ev(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=Ov(i);return{...s,intValue:e}}if(a){let e=kv(i);return{...s,floatValue:e}}let c=kv(i);return{...s,complexValue:[0,c]}}function Dv(e,t){let n=jv(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 Ov(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 kv(e){return Number(e)}function Av(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+=`
64
+ `;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 W_(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function jv(e,t,n){let r=Av(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new W_(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function Mv(e,t){if(t(e)!==!1)for(let n of Nv(e))Mv(n,t)}function Nv(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 tv(e)}}const Pv=Symbol(`go-template-js.MISSING`);function Fv(e,t){if(e==null)return Pv;if(e instanceof Map)return e.has(t)?e.get(t):Pv;if(Array.isArray(e))return Pv;if(typeof e==`object`){let n=e;return t in n?n[t]:Pv}return Pv}function Iv(e,t){let n=e;for(let e of t){if(n===Pv)return Pv;n=Fv(n,e)}return n}function Lv(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)=>Lv(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)||!Lv(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=>Lv(e[n],t[n])):!1}return!1}const Rv=new WeakSet;function zv(e){return Rv.add(e),e}function Bv(e){return Rv.has(e)}function Vv(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 Hv(e,t){return{eq:{fn:(e,...t)=>t.some(t=>Gv(e,t)),argTypes:[`comparable`,`comparable`],arity:{kind:`variadic`}},ne:{fn:(e,t)=>!Gv(e,t),argTypes:[`comparable`,`comparable`],arity:{kind:`exact`}},lt:{fn:(e,t)=>Kv(e,t)<0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},le:{fn:(e,t)=>Kv(e,t)<=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},gt:{fn:(e,t)=>Kv(e,t)>0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},ge:{fn:(e,t)=>Kv(e,t)>=0,argTypes:[`ordered`,`ordered`],arity:{kind:`exact`}},len:{fn:e=>qv(e),argTypes:[`sized`],arity:{kind:`exact`}},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=Jv(n,e);return n},argTypes:[`collection`,`index-key`],arity:{kind:`variadic`}},slice:{fn:(e,...t)=>Xv(e,t),argTypes:[`sliceable`,`int`],arity:{kind:`variadic`}},print:{fn:(...t)=>$v(t,e),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},println:{fn:(...t)=>`${$v(t,e)}\n`,argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},printf:{fn:(n,...r)=>cy(n,r,e,t),argTypes:[`string`,`stringifiable`],arity:{kind:`variadic`},returnType:`string`},toString:{fn:n=>dy(n,e,t),argTypes:[`value`],arity:{kind:`exact`},returnType:`string`},toStrings:{fn:n=>n.map(n=>dy(n,e,t)),argTypes:[`list`],arity:{kind:`exact`}},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`],arity:{kind:`variadic`}},html:{fn:(...t)=>ny($v(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},js:{fn:(...t)=>ay($v(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},urlquery:{fn:(...t)=>sy($v(t,e)),argTypes:[`stringifiable`],arity:{kind:`variadic`},returnType:`string`},not:{fn:e=>!Vv(e),argTypes:[`truthy`],arity:{kind:`exact`}}}}function Uv(){return{and:zv({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!Vv(t))return t;return t}}),or:zv({argTypes:[`truthy`,`truthy`],arity:{kind:`variadic`},fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),Vv(t))return t;return t}})}}function Wv(e,t){return{...Hv(e,t),...Uv()}}function Gv(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):Lv(e,t)}function Kv(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 qv(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Jv(e,t){if(Array.isArray(e)||typeof e==`string`){let n=Yv(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 ${Zv(t)}`);return e[t]}throw Error(`index: cannot index ${Zv(e)}`)}function Yv(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 ${Qv(e)}`);if(n<0||n>t)throw Error(`index out of range: ${String(e)}`);return n}function Xv(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]=Yv(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 Zv(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Qv(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 $v(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+=ey(a,t),r=o}return n}function ey(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const ty={"\0":`�`,'"':`&#34;`,"'":`&#39;`,"&":`&amp;`,"<":`&lt;`,">":`&gt;`};function ny(e){return e.replace(/[\0"'&<>]/g,e=>ty[e]??e)}const ry={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},iy=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function ay(e){let t=``;for(let n of e){let e=ry[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!iy.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const oy=new TextEncoder;function sy(e){let t=``,n=oy.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 cy(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+=ly(l??``,u,d,n,r),o=c+1}return i}function ly(e,t,n,r,i){switch(e){case`s`:return typeof n==`string`?uy(t,n):uy(t,ey(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Qv(n)}=${ey(n,r)})`:uy(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return uy(t,dy(n,r,i));case`q`:return uy(t,JSON.stringify(ey(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${Qv(n)}=${ey(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return uy(t,Number(n).toFixed(i))}case`t`:return uy(t,Vv(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 uy(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Qv(n)}=${ey(n,r)})`:typeof n==`bigint`?uy(t,n.toString(16)):uy(t,Math.trunc(n).toString(16));default:return`%!${e}(${Qv(n)}=${ey(n,r)})`}}function uy(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 dy(e,t,n){return e==null?`<nil>`:typeof e==`string`?e:n(e)?t(e):Array.isArray(e)?`[${e.map(e=>dy(e,t,n)).join(` `)}]`:e instanceof Map?fy([...e.entries()],t,n):py(e)?fy(Object.entries(e),t,n):String(e)}function fy(e,t,n){let r=e=>dy(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 py(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 my(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function hy(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function gy(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 _y(e,t,n){e.vars.set(t,n)}const vy=[`string`,`int`,`truncating-int`,`float`,`bool`,`T`,`ordered`,`list`,`dict`,`sized`,`comparable`,`stringifiable`,`liftable`,`callable`,`collection`,`index-key`,`sliceable`,`truthy`,`reflective`,`value`,`serializable`],yy=new Set([`default`,`zero`,`error`]);function by(e){if(e===void 0)return`default`;if(yy.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${xy(e)}`)}function xy(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 Sy(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${xy(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${xy(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${xy(e.right)}`);return{left:e.left,right:e.right}}}function Cy(e){switch(e.kind){case`exact`:return!1;case`variadic`:return!0;case`alternating`:return!0}}function wy(e){let t=new Set(vy);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 ${vy.join(`, `)}`)}),Cy(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 Ty=Object.freeze({kind:`break`}),Ey=Object.freeze({kind:`continue`}),Dy={kind:`none`};let Oy;(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{Oy=(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 ky(e){let t=new Set,n=e=>{Mv(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 Ay={kind:`dynamic`};function jy(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=Qy(e);return typeof t==`number`||typeof t==`bigint`?{kind:`literal`,value:t}:Ay}case`Pipe`:{if(e.decls.length!==0||e.cmds.length!==1)return Ay;let t=e.cmds[0];if(t===void 0)return Ay;let n=t.args[0];return n===void 0||n.type!==`Identifier`?Ay:{kind:`call`,name:n.ident,args:t.args.slice(1).map(jy)}}default:return Ay}}function My(e){let t=[],n=e=>{Mv(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(jy);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 Ny=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??Vy,this.isT=e.isT??Py,this.missingKey=by(e.missingKey),this.delims=Sy(e.delims),this.funcs=wy({...Wv(this.toString,this.isT),...e.funcs??{}})}parse(e,t){let n=vv(e,this.delims,t);return Oy(n.source,e=>this.evalParsed(n,e),n.defines,ky(n),My(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=my(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 Ty;case`Continue`:throw Ey;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 G_(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:tv(e)}}evalIf(e,t,n){Vv(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(Vv(r)){let i=hy(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=Yy(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=hy(t,o);if(i.length===1)_y(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;_y(a,e,r),_y(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===Ey)continue;throw e}}}catch(e){if(e===Ty)return;throw e}}evalTemplateInvoke(e,t,n){let r=gv(n.defines,e.name);if(!r)throw new G_(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=hy(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=hy(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=gv(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 G_(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,Dy);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)_y(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 G_(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new G_(`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 K_(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=Bv(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){Iy(e,t,n,r,i.source,this.toString,this.fromString,this.isT);try{return t.fn(...n)}catch(t){throw t instanceof J_?new J_(t.funcName,t.argIndex,t.expected,t.receivedSummary,r,{source:i.source}):t instanceof Z_?new Z_(t.message,r,{source:i.source}):t instanceof U_?t:new G_(`error calling ${e}: ${qy(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 Qy(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 K_(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 G_(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=Iv(e,t);if(i!==Pv)return i;if(this.missingKey===`error`)throw new X_(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=gy(t,i);if(!a.found)throw new G_(`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(dy(e,this.toString,this.isT)))}};const Py=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map);function Fy(e){return new Ny(e)}function Iy(e,t,n,r,i,a=Vy,o=By,s=Py){let{argTypes:c,arity:l}=t,u=Ly(c,l);if(n.length<u.minimum||n.length>u.maximum)throw new q_(e,u,n.length,r,{source:i});let d=Ry(c,l),f=-1,p=-1;for(let t=0;t<n.length;t++){let c=d(t),l=n[t];if(!zy(c,l,a,s))throw(c===`int`||c===`truncating-int`)&&(typeof l==`number`||typeof l==`bigint`)?new Y_(e,t+1,l,r,{source:i}):new J_(e,t+1,Ky(c),Jy(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(!Uy(n[f],l))throw new J_(e,t+1,`${Ky(`ordered`)} of the same kind as ${Jy(n[f])}`,Jy(l),r,{source:i})}if(c===`comparable`){if(p===-1)p=t;else if(!Wy(n[p],l))throw new J_(e,t+1,`${Ky(`comparable`)} of the same kind as ${Jy(n[p])}`,Jy(l),r,{source:i})}}}function Ly(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 Ry(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 zy(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 py(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||py(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||py(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||py(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 Hy(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function By(e){return e}function Vy(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 J_(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,Jy(e),{line:0,column:0,offset:0})}function Hy(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function Uy(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function Wy(e,t){let n=Gy(e),r=Gy(t);return n===`nil`||r===`nil`?!0:n===r}function Gy(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 Ky(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 qy(e){return e instanceof Error?e.message:String(e)}function Jy(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Yy(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?Xy([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?Xy(Object.entries(e)):[]}function Xy(e){return[...e].sort((e,t)=>Zy(e[0],t[0]))}function Zy(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 Qy(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 $y(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function eb(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 tb(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 nb(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=tb(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 rb(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=tb(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 ib(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 ab(e){return JSON.stringify(e)??`null`}function ob(){return{atoi:{fn:e=>$y(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},int:{fn:e=>nb(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`int`},int64:{fn:e=>rb(e),argTypes:[`value`],arity:{kind:`exact`}},float64:{fn:e=>eb(e),argTypes:[`value`],arity:{kind:`exact`},returnType:`float`},toDecimal:{fn:e=>ib(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`int`},toRawJson:{fn:e=>ab(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}const sb={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function cb(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*sb[a],n=n.slice(e[0].length)}return t?-r:r}function lb(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<sb.us?`${Math.floor(n)}ns`:n<sb.ms?ub(n,sb.us,3,`µs`):n<sb.s?ub(n,sb.ms,6,`ms`):db(n),t?`-${r}`:r}function ub(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 db(e){let t=Math.floor(e/sb.h);e-=t*sb.h;let n=Math.floor(e/sb.m);e-=n*sb.m;let r=Math.floor(e/sb.s),i=e-r*sb.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 fb(e){return e*sb.s}function pb(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 mb(e,t){let n=t().getTime()-pb(e).getTime();return lb(Math.round(n/1e3)*1e9)}const hb=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],gb=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],_b=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],vb=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function yb(e){return e<10?`0${e}`:String(e)}function bb(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function xb(e){return e<10?` ${e}`:String(e)}function Sb(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${yb(Math.floor(n/60))}${yb(n%60)}`}function Cb(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${yb(Math.floor(n/60))}:${yb(n%60)}`}function wb(e){return`${e>=0?`+`:`-`}${yb(Math.floor(Math.abs(e)/60))}`}function Tb(e){return e===0?`Z`:Sb(e)}function Eb(e){return e===0?`Z`:Cb(e)}function Db(e){return e===0?`Z`:wb(e)}function Ob(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const kb=[[`.000000000`,e=>`.${Ob(e.ms,9,!1)}`],[`.999999999`,e=>{let t=Ob(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${Ob(e.ms,6,!1)}`],[`.999999`,e=>{let t=Ob(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${bb(e.ms)}`],[`.999`,e=>{let t=bb(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>hb[e.month-1]??`January`],[`Monday`,e=>_b[e.weekday]??`Monday`],[`Z07:00`,e=>Eb(e.offsetMinutes)],[`-07:00`,e=>Cb(e.offsetMinutes)],[`Z0700`,e=>Tb(e.offsetMinutes)],[`-0700`,e=>Sb(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>gb[e.month-1]??`Jan`],[`Mon`,e=>vb[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>wb(e.offsetMinutes)],[`Z07`,e=>Db(e.offsetMinutes)],[`15`,e=>yb(e.hour)],[`01`,e=>yb(e.month)],[`02`,e=>yb(e.day)],[`_2`,e=>xb(e.day)],[`03`,e=>yb(e.hour12)],[`04`,e=>yb(e.minute)],[`05`,e=>yb(e.second)],[`06`,e=>yb(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 Ab(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of kb)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const jb={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function Mb(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const Nb=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function Pb(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=Mb(new Intl.DateTimeFormat(`en-US`,{...jb,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=Mb(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=Fb(Mb(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=Nb.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 Fb(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 Ib(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function Lb(e,t){return Ab(e,Pb(pb(t),Ib()))}function Rb(e,t,n){return Ab(e,Pb(pb(t),n))}function zb(e,t){let n=pb(t),r=cb(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function Bb(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:lb(fb(t))}return typeof e==`bigint`?lb(fb(Number(e))):typeof e==`number`?lb(fb(e)):`0s`}const Vb=36e11*24*365,Hb=36e11*24*30,Ub=36e11*24,Wb=36e11,Gb=6e10,Kb=1e9;function qb(e){let t=cb(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>Vb?`${Math.floor(n/Vb)}y`:n>Hb?`${Math.floor(n/Hb)}mo`:n>Ub?`${Math.floor(n/Ub)}d`:n>Wb?`${Math.floor(n/Wb)}h`:n>Gb?`${Math.floor(n/Gb)}m`:n>Kb?`${Math.floor(n/Kb)}s`:`0s`}function Jb(e){let t=Pb(pb(e),Ib());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function Yb(e,t){let n=Pb(pb(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function Xb(e){return e()}const Zb=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Qb=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function $b(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function ex(e,t,n){return[e.slice(t,t+n),t+n]}function tx(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 nx(e,t){for(let[n,r]of Zb.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function rx(e,t){for(let[n,r]of Qb.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function ix(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 ax(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 ox(e,t){if(e[t]===` `){let[n,r]=tx(e,t+1,1,1);return[n,r]}return tx(e,t,1,2)}function sx(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]=tx(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=tx(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=tx(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function cx(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]=tx(e,t+1,2,2);return[n*r*60,i]}return sx(e,t,n)}function lx(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 ux(e,t,n){let[r,i]=ex(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function dx(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=nx(t,n);return i.month=e,[r,i]}case`Monday`:return[ix(t,n),i];case`Jan`:{let[e,r]=rx(t,n);return i.month=e,[r,i]}case`Mon`:return[ax(t,n),i];case`2006`:{let[e,r]=tx(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=tx(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=tx(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=tx(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=ox(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=tx(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=tx(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=tx(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=tx(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=tx(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=tx(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=tx(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=tx(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=tx(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[lx(t,n),i];case`-0700`:{let[e,r]=sx(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=sx(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]=tx(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=cx(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=cx(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=cx(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]=ux(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]=ux(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]=ux(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 fx=`.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 px(e,t){let n=0,r=0,i=$b();for(;n<e.length;){let a=!1;for(let o of fx)if(e.startsWith(o,n)){let[e,s]=dx(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 mx(e,t){return px(e,t)}function hx(e){return String(Math.floor(pb(e).getTime()/1e3))}function gx(e=()=>new Date){return{now:{fn:()=>Xb(e),argTypes:[],arity:{kind:`exact`}},date:{fn:(e,t)=>Lb(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},dateInZone:{fn:(e,t,n)=>Rb(e,t,n),argTypes:[`string`,`value`,`string`],arity:{kind:`exact`}},dateModify:{fn:(e,t)=>zb(e,t),argTypes:[`string`,`value`],arity:{kind:`exact`}},htmlDate:{fn:e=>Jb(e),argTypes:[`value`],arity:{kind:`exact`}},htmlDateInZone:{fn:(e,t)=>Yb(e,t),argTypes:[`value`,`string`],arity:{kind:`exact`}},duration:{fn:e=>Bb(e),argTypes:[`value`],arity:{kind:`exact`}},durationRound:{fn:e=>qb(e),argTypes:[`value`],arity:{kind:`exact`}},toDate:{fn:(e,t)=>mx(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},ago:{fn:t=>mb(t,e),argTypes:[`value`],arity:{kind:`exact`}},unixEpoch:{fn:e=>hx(e),argTypes:[`value`],arity:{kind:`exact`}}}}function _x(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 vx(...e){for(let t of e)if(!_x(t))return t}function yx(e,t){return _x(t)?e:t}function bx(e){return JSON.parse(e)}function xx(e,t,n){return Vv(n)?e:t}function Sx(e){return JSON.stringify(e)??`null`}function Cx(e){return JSON.stringify(e,null,2)??`null`}function wx(){return{default:{fn:(e,t)=>yx(e,t),argTypes:[`value`,`truthy`],arity:{kind:`variadic`}},empty:{fn:e=>_x(e),argTypes:[`truthy`],arity:{kind:`exact`}},coalesce:{fn:(...e)=>vx(...e),argTypes:[`truthy`],arity:{kind:`variadic`}},ternary:{fn:(e,t,n)=>xx(e,t,n),argTypes:[`value`,`value`,`truthy`],arity:{kind:`exact`}},fromJson:{fn:e=>bx(e),argTypes:[`string`],arity:{kind:`exact`}},toJson:{fn:e=>Sx(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`},toPrettyJson:{fn:e=>Cx(e),argTypes:[`serializable`],arity:{kind:`exact`},returnType:`string`}}}function Tx(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function Ex(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 Tx(...t)}function Dx(e,t){return e[t]}function Ox(e,t){return t in e}function kx(e){return Object.keys(e)}function Ax(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 jx(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function Mx(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 Nx(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function Px(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function Fx(e,t,n){return e[t]=n,e}function Ix(e,t){return delete e[t],e}function Lx(e){return Object.values(e)}function Rx(){return{dict:{fn:(...e)=>Tx(...e),argTypes:[`string`,`value`],arity:{kind:`alternating`,minimum:0}},get:{fn:(e,t)=>Dx(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},set:{fn:(e,t,n)=>Fx(e,t,n),argTypes:[`dict`,`string`,`value`],arity:{kind:`exact`}},unset:{fn:(e,t)=>Ix(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},keys:{fn:e=>kx(e),argTypes:[`dict`],arity:{kind:`variadic`}},values:{fn:e=>Lx(e),argTypes:[`dict`],arity:{kind:`exact`}},pluck:{fn:(e,...t)=>Px(e,...t),argTypes:[`string`,`dict`],arity:{kind:`variadic`}},pick:{fn:(e,...t)=>Nx(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},omit:{fn:(e,...t)=>Mx(e,...t),argTypes:[`dict`,`string`],arity:{kind:`variadic`}},hasKey:{fn:(e,t)=>Ox(e,t),argTypes:[`dict`,`string`],arity:{kind:`exact`}},merge:{fn:(e,...t)=>Ax(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}},mergeOverwrite:{fn:(e,...t)=>jx(e,...t),argTypes:[`dict`,`dict`],arity:{kind:`variadic`}}}}function zx(e){throw new Z_(e)}function Bx(){return{fail:{fn:e=>zx(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 Vx(...e){for(let t of e)if(_x(t))return!1;return!0}function Hx(...e){for(let t of e)if(!_x(t))return!0;return!1}function Ux(e,t){return[...e,t]}function Wx(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 Gx(e){return e.filter(e=>!_x(e))}function Kx(...e){let t=[];for(let n of e)t.push(...n);return t}const qx={line:0,column:0,offset:0};function Jx(e,t,n,r){return new J_(e,t,n,r,qx)}function Yx(...e){if(e.length<3)throw Jx(`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(!Zx(t))throw Jx(`dig`,e.length-1,`dict`,Qx(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw Jx(`dig`,e,`string`,Qx(r[e]));return Xx(t,n,r,e.length)}function Xx(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(!Zx(a))throw Jx(`dig`,r-1,`dict at intermediate key`,Qx(a));return Xx(a,t,n.slice(1),r)}function Zx(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function Qx(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function $x(e){return e[0]}function eS(e,t){return t.some(t=>Lv(t,e))}function tS(e){return e.slice(0,-1)}function nS(e){return e[e.length-1]}function rS(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function iS(...e){return e}function aS(e,t){return[t,...e]}function oS(e){return e.slice(1)}function sS(e){return[...e].reverse()}function cS(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function lS(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function uS(e){let t=[];for(let n of e)t.some(e=>Lv(e,n))||t.push(n);return t}function dS(e,...t){return e.filter(e=>!t.some(t=>Lv(t,e)))}function fS(){return{list:{fn:(...e)=>iS(...e),argTypes:[`value`],arity:{kind:`variadic`}},first:{fn:e=>$x(e),argTypes:[`list`],arity:{kind:`exact`}},last:{fn:e=>nS(e),argTypes:[`list`],arity:{kind:`exact`}},rest:{fn:e=>oS(e),argTypes:[`list`],arity:{kind:`exact`}},initial:{fn:e=>tS(e),argTypes:[`list`],arity:{kind:`exact`}},len:{fn:e=>rS(e),argTypes:[`sized`],arity:{kind:`exact`}},reverse:{fn:e=>sS(e),argTypes:[`list`],arity:{kind:`exact`}},uniq:{fn:e=>uS(e),argTypes:[`list`],arity:{kind:`exact`}},without:{fn:(e,...t)=>dS(e,...t),argTypes:[`list`,`value`],arity:{kind:`variadic`}},has:{fn:(e,t)=>eS(e,t),argTypes:[`value`,`list`],arity:{kind:`exact`}},compact:{fn:e=>Gx(e),argTypes:[`list`],arity:{kind:`exact`}},slice:{fn:(e,t,n)=>cS(e,t,n),argTypes:[`list`,`truncating-int`],arity:{kind:`variadic`}},concat:{fn:(...e)=>Kx(...e),argTypes:[`list`],arity:{kind:`variadic`}},chunk:{fn:(e,t)=>Wx(e,t),argTypes:[`int`,`list`],arity:{kind:`exact`}},prepend:{fn:(e,t)=>aS(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},append:{fn:(e,t)=>Ux(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},sortAlpha:{fn:e=>lS(e),argTypes:[`list`],arity:{kind:`exact`},returnType:`list`},push:{fn:(e,t)=>Ux(e,t),argTypes:[`list`,`value`],arity:{kind:`exact`}},tuple:{fn:(...e)=>iS(...e),argTypes:[`value`],arity:{kind:`variadic`}},dig:{fn:(...e)=>Yx(...e),argTypes:[`value`],arity:{kind:`variadic`}},all:{fn:(...e)=>Vx(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`},any:{fn:(...e)=>Hx(...e),argTypes:[`truthy`],arity:{kind:`variadic`},returnType:`bool`}}}function pS(...e){return e.reduce((e,t)=>e+t,0)}function mS(e){return e+1}function hS(e){return e+1}function gS(...e){return e.reduce((e,t)=>e+t,0)}function _S(e){return Math.ceil(e)}function vS(e,t){return Math.trunc(e/t)}function yS(e,...t){return t.reduce((e,t)=>e/t,e)}function bS(e){return Math.floor(e)}function xS(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function SS(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function CS(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function wS(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function TS(e,t){return e%t}function ES(...e){return e.reduce((e,t)=>e*t,1)}function DS(...e){return e.reduce((e,t)=>e*t,1)}function OS(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function kS(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 AS(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),kS(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return kS(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:kS(n,i+t,r).join(` `)}default:return``}}function jS(e,t){return e-t}function MS(e,...t){return t.reduce((e,t)=>e-t,e)}function NS(e){return kS(0,e,e<0?-1:1)}function PS(){return{add:{fn:(...e)=>pS(...e),argTypes:[`truncating-int`],arity:{kind:`variadic`}},sub:{fn:(e,t)=>jS(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mul:{fn:(...e)=>ES(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},div:{fn:(e,t)=>vS(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},mod:{fn:(e,t)=>TS(e,t),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`exact`}},min:{fn:(...e)=>CS(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},max:{fn:(...e)=>xS(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},floor:{fn:e=>bS(e),argTypes:[`float`],arity:{kind:`exact`}},ceil:{fn:e=>_S(e),argTypes:[`float`],arity:{kind:`exact`}},round:{fn:(e,t)=>OS(e,t),argTypes:[`float`,`int`,`float`],arity:{kind:`variadic`}},addf:{fn:(...e)=>gS(...e),argTypes:[`float`],arity:{kind:`variadic`}},subf:{fn:(e,...t)=>MS(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},mulf:{fn:(...e)=>DS(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},divf:{fn:(e,...t)=>yS(e,...t),argTypes:[`float`,`float`],arity:{kind:`variadic`}},add1:{fn:e=>mS(e),argTypes:[`truncating-int`],arity:{kind:`exact`}},add1f:{fn:e=>hS(e),argTypes:[`float`],arity:{kind:`exact`}},maxf:{fn:(...e)=>SS(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},minf:{fn:(...e)=>wS(...e),argTypes:[`float`,`float`],arity:{kind:`variadic`}},biggest:{fn:(...e)=>xS(...e),argTypes:[`truncating-int`,`truncating-int`],arity:{kind:`variadic`}},seq:{fn:(...e)=>AS(...e),argTypes:[`int`],arity:{kind:`variadic`},returnType:`string`},until:{fn:e=>NS(e),argTypes:[`int`],arity:{kind:`exact`},returnType:`list`},untilStep:{fn:(e,t,n)=>kS(e,t,n),argTypes:[`int`,`int`,`int`],arity:{kind:`exact`},returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function FS(e){return Array.from(e)}function IS(e,t){return e===``?FS(t):t.split(e)}function LS(e,t){let n=FS(t);return n.length<=e||e<4?t:`${n.slice(0,e-3).join(``)}...`}function RS(e,t,n){let r=FS(n);return t<7||r.length<t||e<0||e>r.length-t+1?n:`...${r.slice(e,e+t-6).join(``)}...`}const q={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},zS=/^[-_\s]$/,BS=/^\p{P}$/u,VS=/^\p{L}$/u,HS=/^\p{Lu}$/u,US=/^\p{N}$/u;function WS(e){return e!==void 0&&zS.test(e)}function GS(e){return e!==void 0&&VS.test(e)}function KS(e){return e!==void 0&&HS.test(e)}function qS(e){return e!==void 0&&US.test(e)}function JS(e){return e!==void 0&&BS.test(e)}function YS(e,t){if(t>=e.length)return{word:{wt:q.Invalid,text:``},next:t};let n=e[t],r=t+1;if(WS(n)){for(;r<e.length&&WS(e[r]);)r++;return{word:{wt:q.Connector,text:e.slice(t,r).join(``)},next:r}}if(JS(n)){for(;r<e.length&&JS(e[r]);)r++;return{word:{wt:q.Punct,text:e.slice(t,r).join(``)},next:r}}if(KS(n)){if(r>=e.length)return{word:{wt:q.UpperCase,text:n},next:r};if(KS(e[r])){let n=r;for(;n<e.length&&KS(e[n]);)n++;return n<e.length&&GS(e[n])?{word:{wt:q.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:q.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(GS(e[r])){let n=r+1;for(;n<e.length&&GS(e[n])&&!KS(e[n]);)n++;return{word:{wt:q.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:q.UpperCase,text:n},next:r}}if(GS(n)){for(;r<e.length&&GS(e[r])&&!KS(e[r]);)r++;return{word:{wt:q.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(qS(n)){for(;r<e.length&&qS(e[r]);)r++;return{word:{wt:q.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!WS(e[r])&&!GS(e[r])&&!qS(e[r])&&!JS(e[r]);)r++;return{word:{wt:q.Other,text:e.slice(t,r).join(``)},next:r}}function XS(e,t,n){if(t.wt!==q.UpperCase&&t.wt!==q.Connector){e.push(t.text);return}for(let r of t.text)WS(r)?e.push(n):KS(r)?e.push(r.toLowerCase()):e.push(r)}function ZS(e,t){if(e.length===0)return``;let n=FS(e),r=[],{word:i,next:a}=YS(n,0);for(;a<n.length;){i.wt!==q.Connector&&XS(r,i,t);let e=i,o=i;if({word:i,next:a}=YS(n,a),e.wt===q.Number){for(;i.wt===q.Alphabet||i.wt===q.Number;)XS(r,i,t),{word:i,next:a}=YS(n,a);i.wt!==q.Invalid&&i.wt!==q.Punct&&i.wt!==q.Connector&&r.push(t);continue}if(e.wt===q.Connector){XS(r,o,t);continue}if(e.wt===q.Punct)continue;if(i.wt!==q.Number){i.wt!==q.Connector&&i.wt!==q.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=YS(n,a),i.wt!==q.Alphabet){XS(r,s,t),i.wt!==q.Connector&&i.wt!==q.Punct&&r.push(t);continue}for(r.push(t),XS(r,s,t);i.wt===q.Alphabet||i.wt===q.Number;)XS(r,i,t),{word:i,next:a}=YS(n,a);i.wt!==q.Invalid&&i.wt!==q.Connector&&i.wt!==q.Punct&&r.push(t)}return XS(r,i,t),r.join(``).toLowerCase()}function QS(e){if(e.length===0)return``;let t=FS(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!WS(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++,WS(i)&&WS(e)){n.push(e);continue}WS(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function $S(e){return QS(e)}function eC(...e){return e.join(` `)}function tC(e,t){return t.includes(e)}function nC(e,t){return t.startsWith(e)}function rC(e,t){return t.endsWith(e)}function iC(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
65
65
  `).map(e=>n+e).join(`
66
- `)}function iC(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 aC(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw qx(`join`,2,`list of strings/primitives`,`list element of type ${oC(e)}`);n.push(String(e))}return n.join(e)}function oC(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function sC(e){return XS(e,`-`)}function cC(e){return e.toLowerCase()}function lC(e,t){return`\n${rC(e,t)}`}function uC(e){return e.replace(/\s+/g,``)}function dC(e,t,n){return n===1?e:t}function fC(...e){return e.map(e=>`"${e}"`).join(` `)}function pC(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function mC(e,t){return t.repeat(Math.max(0,e))}function hC(e,t,n){return FS(e,n).join(t)}function gC(e){return XS(e,`_`)}function _C(e,t){let n=FS(e,t),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function vC(e,t){return FS(e,t)}function yC(e,t,n){let r=bC(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function bC(e,t,n){if(n===0)return[];let r=FS(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 xC(...e){return e.map(e=>`'${e}'`).join(` `)}function SC(e,t,n){let r=PS(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 CC(e){let t=``;for(let n of e)wC(n)?t+=n.toLowerCase():TC(n)?t+=n.toUpperCase():t+=n;return t}function wC(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function TC(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function EC(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function DC(e){return e.trim()}function OC(e,t){if(e.length===0)return t;let n=new Set(PS(e)),r=PS(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 kC(e,t){return t.startsWith(e)?t.slice(e.length):t}function AC(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function jC(e,t){let n=PS(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 MC(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function NC(e){return e.toUpperCase()}function PC(e,t){return FC(e,`
67
- `,t)}function FC(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
68
- `)){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 IC(e,t,n){return FC(e,t,n)}function LC(){return{abbrev:{fn:(e,t)=>IS(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>LS(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>QS(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>$S(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>eC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>tC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>nC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>rC(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>iC(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>aC(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>sC(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>cC(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>lC(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>uC(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>dC(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>fC(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>pC(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>mC(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>hC(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>gC(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>_C(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>vC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>yC(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>xC(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>SC(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>CC(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>EC(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>DC(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>OC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>kC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>AC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>jC(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>MC(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>NC(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>PC(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>IC(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function RC(e,t){let n=zC(e),r=n.copy();return r.style=ll(n.style,t),r}function zC(e){if(!(e instanceof G))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function BC(e){return{fn:(t=>RC(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function VC(e){return{fn:((t,n)=>RC(n,new H({[e]:B.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function HC(e,t){return new H({[e]:t})}function UC(){let e={};for(let t of rl)e[t]=BC(HC(t,!0)),e[`not_${t}`]=BC(HC(t,!1));for(let[t,n]of Object.entries(al))e[t]=BC(HC(n,!0));return e}const WC={fn:((e,t)=>RC(t,H.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},GC={fn:((e,t)=>RC(t,new H({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function KC(){return{fg:VC(`color`),bg:VC(`bgcolor`),...UC(),link:GC,style:WC}}function qC(e,t){let n;try{n=xs(e.trim())}catch(n){throw n instanceof rs?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 JC(n,t,JSON.stringify(e))}function JC(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 YC(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function XC(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 ZC=YC([`string`,`int`],((e,t)=>ic(qC(e,`darken`),t).hex)),QC=YC([`string`,`int`],((e,t)=>ic(qC(e,`lighten`),-t).hex)),$C={min:0,max:100,note:`0 = from, 100 = toward`},ew=YC([`string`,`string`,`float`],((e,t,n)=>Ss(qC(e,`mix`),qC(t,`mix`),XC(n,`mix`,`percentage`,$C)/100).hex)),tw={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},nw=YC([`string`],(e=>oc(qC(e,`contrastOn`)).hex)),rw={depth:z.TRUECOLOR},iw=e=>YC([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return sc(qC(t,`readableOn`),qC(n,`readableOn`),XC(r,`readableOn`,`ratio`,tw),i,void 0,a).hex})),aw={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function ow(){let e={};for(let[t,n]of Object.entries(aw)){let r=t;e[n]=YC([`string`,`float`],((e,t)=>{let i={...Bs,[r]:XC(t,n,`amount`)};return V.fromRgba(qC(e,n)).applyKey(i).toRgba().hex}))}return e}function sw(e=()=>rw){return{darken:ZC,lighten:QC,mix:ew,contrastOn:nw,readableOn:iw(e),...ow()}}function cw(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:JC(Qs(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function lw(e){return{color:{fn:(t=>Qs(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new Wc(Xc(n),cw(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}function uw(e){return{...KC(),...sw(e)}}new H({color:`red`,dim:!0});const dw=/^(?:(?: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,fw=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function pw(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(dw);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(fw);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 mw(e){let t=e.match(fw);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 hw(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 gw(e){return e.toLocaleString()}function _w(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 vw(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 yw=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],bw=yw.length;function xw(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*(bw-1));o+=yw[t]}return o}function Sw(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 Cw(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 ww=lm(),Tw=[...Am];function Ew(){return{basename:{fn:e=>u(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>d(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>hw(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(R_(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>L_(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>z_(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>ww,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>Tw,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(Cw(`sparkline`,[`width`],n),xw(Sw(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>vw(e,_w(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function Dw(e){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},formatInteger:{fn:e=>gw(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>pw(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>mw(e),argTypes:[`string`],arity:{kind:`exact`}}}}function Ow(e){let{clock:t,drawnAt:n,extraFuncs:r}=e;return Py({fromString:e=>new G(e),toString:e=>e.plain,isT:e=>e instanceof G,clock:t,missingKey:`error`,funcs:{...Cx(),...LC(),...dS(),...NS(),...hx(t),...ab(),...zx(),...Lx(),...uw(n&&(()=>({depth:n()}))),...Ew(),...Dw(t),...r??{}}})}function kw(e){return Aw(e,new Set(e.names()),``)}function Aw(e,t,n){return new Proxy(Object.create(null),{has(e,r){if(typeof r!=`string`)return!1;let i=n?`${n}.${r}`:r;if(t.has(i))return!0;let a=`${i}.`;for(let e of t)if(e.startsWith(a))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a))return e.getKind(a)===`document`?Mw(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return Aw(e,t,a)}})}function jw(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 Mw(e,t){switch(t.kind){case`ok`:return t.value;case`absent`:throw new B_(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}function Nw(e){return r.existsSync(l.join(e,`.git`))}function Pw(e){let t=l.resolve(e);for(;;){if(Nw(t))return t;let e=l.dirname(t);if(e===t)return;t=e}}function Fw(e){let t=Pw(e);return t===void 0?{root:l.resolve(e),git:!1}:{root:t,git:!0}}function Iw(e,t){return e.kind===`absent`?P(`none`):e.kind===`failed`?e:t.kind===`failed`?t:P(t.kind===`ok`?`tracked`:`gone`)}function Lw(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 Rw={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},zw={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function Bw(e,t,n){return Object.hasOwn(t,n)?P(t[n]):I(`${e}: unknown state ${JSON.stringify(n)}`)}function Vw(e,t,n){return t.ok?P(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?F:I(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??Hw(t.stderr)].filter(Boolean).join(`, `)}`)}function Hw(e){return e.trim().split(`
69
- `,1)[0]??``}function Uw(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 Gw=/^[A-Za-z]:[\\/]/;function Kw(e){let t=e.trim();if(Gw.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 qw(e){return Kw(e)?.host||null}function Jw(e){let t=qw(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}function Yw(e){let t=new Map;for(let n of e.split(`
70
- `)){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 Xw(e){return e.urls.find(e=>tT(e)!==null)??e.urls[0]??null}function Zw(e){return e.find(e=>e.name===`origin`)??e[0]??null}function Qw(e){let t=Zw(e);return t?Xw(t):null}function $w(e){let t=Zw(e);return t?t.urls.find(e=>Jw(e)!==null)??Xw(t):null}function eT(e){let t=(Kw(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function tT(e){let t=Kw(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 nT(e){let t=Qw(e);return t===null?null:tT(t)}function rT(e,t,n,r){return t.ok?r(t.stdout):t.reason===`spawn-error`&&/ENOENT/i.test(t.error??``)||t.reason===`non-zero`&&n.test(t.stderr)?F:I(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??Hw(t.stderr)].filter(Boolean).join(`, `)}`)}function iT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function aT(e){let t=`detached`,n=F,r=F,i=F,a=0,o=0,s=0,c=0;for(let l of e.split(`
71
- `)){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 oT(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(!iT(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=Bw(`gh pr view`,Rw,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function sT(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(!iT(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=Bw(`glab mr view`,zw,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function cT(e){try{let t=r.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var lT=class{isGitRepo(e){return Nw(e)}async execGitAsync(e,t){return Me({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}async resolveEffectiveGitDir(e,t){return this.isWorktree(e)?P(e):t&&this.isGitRepo(t)?P(t):this.isGitRepo(e)?P(e):this.findGitRoot(e)}async findGitRoot(e){let t=Pw(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=await 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=Uw(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showTimeSinceCommit&&(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=Uw(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=Uw(s,nT)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),P(o)}resolveGitDir(e){let t=l.join(e,`.git`);try{if(r.existsSync(t)&&r.statSync(t).isFile()){let n=r.readFileSync(t,`utf-8`).match(/^gitdir:\s*(.+)$/m);if(n?.[1])return l.resolve(e,n[1].trim())}}catch{}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return r.existsSync(l.join(t,`MERGE_HEAD`))?P(`MERGE`):r.existsSync(l.join(t,`CHERRY_PICK_HEAD`))?P(`CHERRY-PICK`):r.existsSync(l.join(t,`REVERT_HEAD`))?P(`REVERT`):r.existsSync(l.join(t,`BISECT_LOG`))?P(`BISECT`):r.existsSync(l.join(t,`rebase-merge`))||r.existsSync(l.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(Vw(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestampMs(e,t.value):t}commitTimes=new Map;async commitTimestampMs(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.readCommitTimestampMs(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 readCommitTimestampMs(e,t){let n=Ww(Vw(`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)*1e3;return Number.isNaN(r)?I(`git log -1: unparseable timestamp "${n.value}"`):P(r)}resolveCommonGitDir(e){let t=this.resolveGitDir(e);try{let e=r.readFileSync(l.join(t,`commondir`),`utf-8`).trim();if(e)return l.resolve(t,e)}catch{}return t}getStashCount(e){let t=l.join(this.resolveCommonGitDir(e),`logs`,`refs`,`stash`),n;try{n=r.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 i=n.trim();return P(i?i.split(`
72
- `).length:0)}async getRemotesAsync(e){let t=cT(l.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){let t=Vw(`git config --get-regexp remote url`,await this.execGitAsync([`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`],{cwd:e,timeout:2e3}),1);return t.kind===`failed`?t:P(t.kind===`ok`?Yw(t.value):[])}repoNameFrom(e,t){let n=Qw(e);return(n===null?null:eT(n))??l.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=$w(t.value);return n===null?F:P(n)}async execForgeAsync(e,t,n){return Me({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=Jw(t);return n===`github`?rT(`gh pr view`,await this.execForgeAsync(`gh`,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,oT):n===`gitlab`?rT(`glab mr view`,await this.execForgeAsync(`glab`,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,sT):F}isWorktree(e){try{let t=l.join(e,`.git`);return!!(r.existsSync(t)&&r.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){D(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=Vw(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?P(aT(t.value)):t}};const uT=(e,t)=>D(t);var dT=class{slots=new Map;maxWatchers;counters;logger;closed=!1;constructor(e={}){this.maxWatchers=e.maxWatchers??128,this.counters=e.counters,this.logger=e.logger??uT}acquire(e,t,n){if(this.closed)return{release:()=>{}};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,r.lastTouched=Date.now(),this.slots.delete(e),this.slots.set(e,r),this.makeHandle(e);let i={key:e,watchers:[],refcount:1,debounceTimer:null,onInvalidate:n,targets:t,lastTouched:Date.now()};return this.openWatchers(i),this.slots.set(e,i),this.counters&&this.counters.watchersOpened++,this.evictIfNeeded(),this.makeHandle(e)}makeHandle(e){let t=!1;return{release:()=>{if(t)return;t=!0;let n=this.slots.get(e);n&&(n.refcount=Math.max(0,n.refcount-1),n.refcount===0&&(this.closeSlot(n),this.slots.delete(e)))}}}openWatchers(e){let t=()=>{e.debounceTimer||(e.debounceTimer=setTimeout(()=>{e.debounceTimer=null;try{e.onInvalidate()}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50),e.debounceTimer.unref())};for(let n of e.targets.files)try{let i=r.watch(n,{persistent:!1},t);i.on(`error`,e=>{this.logger(`warn`,`watcher error ${n}: ${e.message}`)}),e.watchers.push(i)}catch(e){this.logger(`warn`,`watch failed ${n}: ${e.message}`)}for(let n of e.targets.dirs)try{let i=n.filenames?new Set(n.filenames):null,a=r.watch(n.path,{persistent:!1},(e,n)=>{i&&(!n||!i.has(n))||t()});a.on(`error`,e=>{this.logger(`warn`,`watcher error ${n.path}: ${e.message}`)}),e.watchers.push(a)}catch(e){this.logger(`warn`,`watch failed ${n.path}: ${e.message}`)}}closeSlot(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}evictIfNeeded(){for(;this.slots.size>this.maxWatchers;){let e=this.slots.keys().next().value;if(e===void 0)break;let t=this.slots.get(e);this.closeSlot(t),this.slots.delete(e),this.counters&&this.counters.watchersEvicted++;try{t.onInvalidate()}catch{}this.logger(`info`,`watcher LRU evict ${e}`)}}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}},fT=class{running=new Set;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:(this.running.add(e),{kind:`started`,done:this.loop(e,t)})}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 pT={showSha:!0,showStashCount:!0};function mT(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function hT(e){let t=t=>{try{return r.statSync(l.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function gT(e,t){return e.head!==t.head||e.index!==t.index}function _T(e){let t=[],n=l.join(e,`refs/heads`);try{r.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[l.join(e,`HEAD`),l.join(e,`index`)],dirs:t}}var vT=class extends lT{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new fT;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new lT,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??Ft,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new dT({logger:this.logger}),this.ownsWatchers=!0);let t=e.sanityIntervalMs??3e5;t>0&&(this.sanityTimer=setInterval(()=>this.runSanityCheck(),t),this.sanityTimer.unref())}getWatcherRegistry(){return this.watchers}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,invalidations:this.invalidations,watchers:this.watchers.size()}}resolveEffectiveGitDir(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.resolutions.delete(n),this.resolutions.set(n,i),i.dir;let a=this.inner.resolveEffectiveGitDir(e,t);return this.resolutions.set(n,{dir:a,computedAt:r}),a.catch(()=>{this.resolutions.get(n)?.dir===a&&this.resolutions.delete(n)}),this.evictResolutionsIfNeeded(),a}evictResolutionsIfNeeded(){for(;this.resolutions.size>this.maxEntries;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}}async getGitInfo(e,t={},n){let r=await this.resolveEffectiveGitDir(e,n);return r.kind===`ok`?this.getGitInfoForRoot(r.value,t):r}getGitInfoForRoot(e,t){let n=`${e}|${mT(t)}`,r=Date.now(),i=this.entries.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.entries.delete(n),this.entries.set(n,i),this.hits++,Promise.resolve(P(i.info));let a=this.fetchInFlight.get(n);if(a)return a;let o=this.doFetch(e,n,t,r).finally(()=>{this.fetchInFlight.delete(n)});return this.fetchInFlight.set(n,o),o}async doFetch(e,t,n,r){this.misses++;let i=this.inner.resolveGitDir(e),a=hT(i),o=await this.inner.getGitInfo(e,n);if(o.kind!==`ok`)return o;let s=o.value;n.showPullRequest&&(s.pullRequest=await this.getPullRequestCached(e,s.branch)),this.dropEntry(t);let c=this.watchers.acquire(`git:${e}`,_T(i),()=>this.invalidateRepo(e));return this.entries.set(t,{info:s,computedAt:r,mtime:a,watcher:c,repoRoot:e}),this.evictIfNeeded(),o}async getPullRequestCached(e,t){let n=await this.inner.getRepoRemoteUrl(e);if(n.kind===`failed`)return n;if(n.kind===`absent`)return F;let r=n.value,i=`${e}|${t}|${r}`,a=Date.now(),o=this.prCache.get(i);if(o){let e=o.pr.kind===`failed`?45e3:3e5;if(a-o.computedAt<e)return this.prCache.delete(i),this.prCache.set(i,o),o.pr}let s=this.prFetchInFlight.get(i);if(s)return s;let c=this.inner.resolvePullRequest(e,r).then(e=>(this.prCache.set(i,{pr:e,computedAt:Date.now()}),this.evictPrIfNeeded(),e)).finally(()=>{this.prFetchInFlight.delete(i)});return this.prFetchInFlight.set(i,c),c}evictPrIfNeeded(){for(;this.prCache.size>this.maxEntries;){let e=this.prCache.keys().next().value;if(e===void 0)break;this.prCache.delete(e)}}deliverable(e,t){return e.kind===`failed`?(this.logger(`warn`,`git fetch failed (${t}): ${e.reason}`),null):e.kind===`ok`?e.value:null}subscribe(e,t){let n=!1,r=null;return{firstDelivery:(async()=>{let i=await this.resolveEffectiveGitDir(e);if(n)return;if(i.kind!==`ok`){i.kind===`failed`&&this.logger(`warn`,`git resolve failed (subscribe ${e}): ${i.reason}`),this.safeInvoke(t,null);return}let a=i.value,o=this.subscribersByRepo.get(a);if(!o){let t=this.inner.resolveGitDir(a),n=this.watchers.acquire(`git:${a}`,_T(t),()=>this.invalidateRepo(a));o={workingDir:e,repoRoot:a,callbacks:new Set,watcher:n},this.subscribersByRepo.set(a,o)}o.callbacks.add(t),r={repoRoot:a,entry:o};let s=await this.getGitInfoForRoot(a,{...pT});n||this.safeInvoke(t,this.deliverable(s,a))})(),unsubscribe:()=>{if(n=!0,!r)return;let{repoRoot:e,entry:i}=r;i.callbacks.delete(t),i.callbacks.size===0&&(i.watcher.release(),this.subscribersByRepo.delete(e))}}}invalidateRepo(e){let t=0;for(let[n,r]of this.entries)r.repoRoot===e&&(r.watcher.release(),this.entries.delete(n),t++);t>0&&(this.invalidations+=t,this.logger(`info`,`gitCache invalidate ${e} dropped=${t}`)),this.refreshSubscribers(e)}refreshSubscribers(e){let t=this.subscribersByRepo.get(e);!t||t.callbacks.size===0||this.refreshes.run(e,()=>this.refreshOnce(e))}async refreshOnce(e){let t=this.subscribersByRepo.get(e);if(!t||t.callbacks.size===0)return;let n=await this.getGitInfoForRoot(e,{...pT}),r=this.deliverable(n,e),i=this.subscribersByRepo.get(e);if(!(!i||i.callbacks.size===0))for(let e of[...i.callbacks])i.callbacks.has(e)&&this.safeInvoke(e,r)}safeInvoke(e,t){try{e(t)}catch(e){this.logger(`warn`,`git subscriber threw: ${e.message??String(e)}`)}}dropEntry(e){let t=this.entries.get(e);t&&(t.watcher.release(),this.entries.delete(e))}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.dropEntry(e),this.logger(`info`,`gitCache evict ${e}`)}}runSanityCheck(){let e=new Map;for(let t of this.entries.values()){let n=e.get(t.repoRoot);n||(n=hT(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),gT(t.mtime,n)&&this.invalidateRepo(t.repoRoot)}}runSanityCheckNow(){this.runSanityCheck()}close(){this.sanityTimer&&=(clearInterval(this.sanityTimer),null);for(let e of this.entries.values())e.watcher.release();this.entries.clear();for(let e of this.subscribersByRepo.values())e.callbacks.clear(),e.watcher.release();this.subscribersByRepo.clear(),this.refreshes.clear(),this.fetchInFlight.clear(),this.prCache.clear(),this.prFetchInFlight.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}};const yT=/\r\n|\r|\n/g,bT=e=>P(e.replace(yT,` `).trim());function xT(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?I(`regex no-match`):P(n.replace(yT,` `))}}const ST=e=>{try{return P(JSON.parse(e))}catch(e){return I(`JSON parse failed: ${e.message}`)}},CT=e=>e.getTime()/1e3,wT=e=>new Date(e*1e3);function TT(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function ET(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 DT=`session.id`;function OT(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await Me({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 kT(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await oe(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 AT(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?I(`${r.reason} in ${n}`):r}const jT=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],MT=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],NT=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],PT=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function FT(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>jT[e.getMonth()]],[`Monday`,e=>NT[e.getDay()]],[`Jan`,e=>MT[e.getMonth()]],[`Mon`,e=>PT[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const IT={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function LT(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=IT[t];try{return GT(r,e)}catch{return KT(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return _i(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return _i(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return _i(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return _i(e.stashCount,0)}}function RT(e){try{return o(e)}catch{return e}}function zT(e){try{return s(e).isDirectory()}catch{return!1}}function BT(e){let t=RT(e);return zT(t)?{dir:t,name:null,leaf:!0}:A_(t)}const VT=e=>`${e.dir}\0${e.name??``}`;var HT=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:BT(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=BT(e);if(t.watcher!==null&&VT(n)===VT(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=l.basename(r);try{return c(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}},UT=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:le(()=>{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&&(ce(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())ce(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function WT(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function GT(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`?L_(e):t===`number`?R_(e):z_(e)}function KT(e){return e===`number`?0:e===`boolean`?!1:``}var qT=class{inputMetas=new Map;lastErrors=new Map;policyFaults=new Map;watchMgr=new HT;ttlMgr=new UT;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new fT;abort=new AbortController;drawn=P_.observable.box(z.TRUECOLOR);drawnAt=()=>this.drawn.get();instant=P_.observable.box(null);now=()=>{let e=this.instant.get();if(e===null)throw Error(`the time was read before any render published its instant`);return wT(e)};engine=Ow({clock:this.now,drawnAt:this.drawnAt});gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new vT({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,I_(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,I(t))}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}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,OT(t,n.cwd,this.abort.signal),TT(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,kT(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,bT,t.default,n);case`regex`:return this.scalarPublisher(e,xT(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=AT(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,_i(a,i))}}documentPublisher(e,t,n){let r=t===void 0?F: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=AT(s,ST,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)};u?i=setTimeout(d,250):d()}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.declareDerived(e,()=>r.evaluate(kw(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){this.declareDerived(e,()=>FT(t.format,this.now()),t.varDefault)}declareDerived(e,t,n){this.store.defineComputed(e,`string`,()=>{try{let n=t();return this.lastErrors.delete(e),n}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n===void 0)throw V_(t)?new B_(e,`variable "${e}": ${r}`):Error(`variable "${e}": ${r}`);return n}})}declareGit(e,t){let n=IT[t.field],r=t.varDefault===void 0?KT(n):GT(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,LT(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}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(DT);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(DT):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=WT(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,GT(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}drawAt(e){this.store.runInAction(()=>this.drawn.set(e))}renderAt(e){this.store.runInAction(()=>this.instant.set(e))}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 this.policyFaults}dispose(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let r=this.watchMgr.subscribe(t.path,n,t=>this.notePolicy(e,I(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template),i=()=>{try{return P(r.evaluate(kw(this.store)).map(e=>e.plain).join(``))}catch(e){return V_(e)?F:I(`cache key: ${e instanceof Error?e.message:String(e)}`)}},a=i();this.notePolicy(e,a);let o=a.kind===`ok`?a.value:void 0,s=(0,P_.reaction)(i,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===o)&&(o=t.value,n())});this.cleanups.push(s);break}case`depends_on`:{let e=(0,P_.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,GT(this.defaultEmptyValue,t))}catch{this.store.setBox(e,KT(t))}}defaultFor(e){try{return GT(this.defaultEmptyValue,e)}catch{return KT(e)}}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){t.kind===`failed`?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`)}};const JT={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[DT]:{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:``},"theme.effective":{kind:`input`,path:`theme.effective`,default:``},"style.effective":{kind:`input`,path:`style.effective`,default:``},"effect.effective":{kind:`input`,path:`effect.effective`,default:``},"preset.effective":{kind:`input`,path:`preset.effective`,default:``},"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},"endcaps.effective":{kind:`input`,path:`endcaps.effective`,default:``},"variation.effective":{kind:`input`,path:`variation.effective`,default:``},"shade.effective":{kind:`input`,path:`shade.effective`,default:``},"charset.effective":{kind:`input`,path:`charset.effective`,default:``},"colorCompatibility.effective":{kind:`input`,path:`colorCompatibility.effective`,default:``},"transitions.effective":{kind:`input`,path:`transitions.effective`,type:`boolean`,default:!1},"autoWrap.effective":{kind:`input`,path:`autoWrap.effective`,type:`boolean`,default:!0},"padding.effective":{kind:`input`,path:`padding.effective`,type:`number`,default:1},"updateNotice.effective":{kind:`input`,path:`updateNotice.effective`,type:`boolean`,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:``}},YT=`ne .tmux.pane ""`;function XT(e,t,n){let r=new Set,i=e=>{for(let t of b_(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 fg(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(DT);for(let t of Object.values(e.actions)){r.add(DT),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?Ea.get(t.set):void 0,n=`persist`in t?Ta.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function ZT(e,t,n){let r=O_({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of XT(e,t,n.helpers)){if(D_(a,r))continue;let e=JT[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 QT(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}var $T=class extends Error{file;issues;warnings;constructor(e,t,n=[]){super(rE(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t,this.warnings=n}};function J(e,t){let n=0,r;for(let i of t){if(i===``||/^\d+$/.test(i))continue;let t=eE(e,n,i);if(t===-1)return r===void 0?void 0:tE(e,r);n=t,r=t}return r===void 0?void 0:tE(e,r)}function eE(e,t,n){let r=n.replace(/[\\^$.*+?()[\]{}|]/g,`\\$&`),i=RegExp(`(?:["']${r}["']|\\b${r}\\b)\\s*:`,`g`);i.lastIndex=t;let a=i.exec(e);return a?a.index:-1}function tE(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function nE(e,t){try{return Tr(t),null}catch(n){if(!(n instanceof yr))throw n;return`${e}:${tE(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function rE(e,t){if(t.length===0)return`${e}: invalid config (no details)`;let n=[`Invalid config in ${e} (${t.length} issue${t.length===1?``:`s`}):`];for(let e of t){let t=[];e.line!==void 0&&t.push(`line ${e.line}${e.col===void 0?``:`:${e.col}`}`),e.path&&t.push(e.path);let r=t.length>0?`[${t.join(` • `)}] `:``;n.push(` ${r}${e.message}`)}return n.join(`
73
- `)}const iE=`groups.`,aE=`menus.`,oE=`edit.`,Y=`candybar.`,sE=[iE,aE,oE,Y];function cE(e){return sE.some(t=>e.startsWith(t))}function lE(e){let t=QT(e);return sE.find(e=>t.startsWith(QT(e)))}function uE(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:J(e.source,[`root`])})}function dE(e){return e}function fE(e,t,n){return n===void 0?aE+QT(e)+`.`+QT(t):pE(n)}function pE(e){return aE+QT(e)}function mE(e,t){return e+`.`+t}function hE(e){return e+`.page`}const gE=[`closeOnPick`,`paged`,`key`,`distribution`],_E=e=>gE.includes(e),vE=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${cp.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function yE(e){for(let t of Object.keys(e))if(!_E(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${vE}`);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&&!lp(r))throw Error(`{{ menu }} option "distribution" must be one of: ${cp.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:dp(r)}}const bE=e=>`from`in e?e.from:e.themes;function xE(e,t,n){return e===`bool`?Xm(t)!==null:`min`in e?Zm(t,e)!==null:a_(bE(e),n).members.includes(t)}function SE(e,t){if(e===`bool`)return Jm.join(` or `);if(!(`min`in e)){let n=bE(e),{members:r}=a_(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 CE(e){return{label:e.label,domain:wE(e.domain)}}function wE(e){return e===`theme`?{themes:n_}:e===`bool`||`min`in e?e:{from:e}}function TE(e,t,n,r,i){let a=nr(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...Jm]}},variables:{}};if(`from`in o)return EE(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 EE(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 EE(e,t,n,r,i){let a={variable:n,key:n,member:t},o=mE(n,t),s=`${t}.open`,c=hE(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]:ur(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:lr(n,Qn),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}function DE(e,t,n,r){let i=n[r];return typeof i==`string`?i:(e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${ME(i)}`,line:J(e.source,[...t.split(`.`),r])}),null)}function OE(e,t,n,r){let i=n.default;if(i!==void 0){if(!(r===`string`&&typeof i==`string`||r===`number`&&typeof i==`number`||r===`boolean`&&typeof i==`boolean`)){e.issues.push({path:`${t}.default`,message:`default must be a ${r}, got ${ME(i)}`,line:J(e.source,[...t.split(`.`),`default`])});return}return i}}function kE(e,t,n,r){let i=n[r];if(i!==void 0){if(typeof i!=`string`){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${ME(i)}`,line:J(e.source,[...t.split(`.`),r])});return}return i}}function AE(e,t,n){let r=kE(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${om(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[...t.split(`.`),`palette`])});return}return r}}function jE(e,t,n,r,i){let a=n[r];if(a!==void 0){if(typeof a!=`string`||!i.includes(a)){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be one of: ${i.join(`, `)}; got ${Z(a)}`,line:J(e.source,[...t.split(`.`),r])});return}return a}}function X(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ME(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Z(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function NE(e,t,n,r){return X(r)?(LE(e,n,r,t.noun,new Set(Object.keys(t.fields)),PE(e,t.removed??{},n,r)),FE(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${ME(r)}`,line:J(e.source,n.split(`.`))}),null)}function PE(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)RE(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function FE(e,t,n,r){let i=t,a={},o=!0;for(let[t,s]of Object.entries(i)){let i=s.parse(e,n,t,r);i===void 0?s.required&&(o=!1):a[t]=i}return o?a:null}const IE=new Set;function LE(e,t,n,r,i,a=IE){for(let o of Object.keys(n))!i.has(o)&&!a.has(`${t}.${o}`)&&e.issues.push({path:`${t}.${o}`,message:`Unknown ${r} "${o}". Expected one of: ${[...i].join(`, `)}`,line:J(e.source,[...t.split(`.`),o])})}function RE(e,t,n){return e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))}),null}function zE(e,t,n,r){if(!X(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${ME(r)}`,line:J(e.source,n.split(`.`))}),null;let i=t.arms,a=Object.keys(i),o=Object.keys(r).filter(e=>e in i),s=Object.keys(r).filter(e=>!(e in i));for(let r of s)e.issues.push({path:`${n}.${r}`,message:`Unknown ${t.noun} key "${r}". Expected exactly one of: ${a.join(`, `)}`,line:J(e.source,[...n.split(`.`),r])});if(o.length===0)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)}`,line:J(e.source,n.split(`.`))}),null;if(o.length>1)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)} (found: ${o.join(`, `)})`,line:J(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function BE(e,t,n,r){if(!X(r))return e.issues.push({path:n,message:`${n} must be an object, got ${ME(r)}`,line:J(e.source,n.split(`.`))}),null;let i=r[t.tag];if(typeof i!=`string`)return e.issues.push({path:`${n}.${t.tag}`,message:`${n}.${t.tag} must be a string, got ${ME(i)}`,line:J(e.source,n.split(`.`))}),null;let a=t.arms;if(!(i in a))return e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:J(e.source,[...n.split(`.`),t.tag])}),null;let o=a[i],s=e.issues.length,c=o.parse(e,n,r),l=new Set(e.issues.slice(s).map(e=>e.path));return LE(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function VE(e,t,n){return{json:tD($E(n),e,t),keys:new Set([e,...Object.keys(n)])}}function HE(e){return(...t)=>e()(...t)}function UE(e,...t){return(n,r,i)=>{let a=e(n,r,i);if(a===null)return null;for(let e of t){if(e.ok(a))continue;let{field:t,message:i}=e.issue(a),o=t===``?r:`${r}.${t}`;return n.issues.push({path:o,message:i,line:J(n.source,o.split(`.`))}),null}return a}}function WE(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>kE(e,t,r,n)}}function GE(){return{required:!1,json:{type:`boolean`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`boolean`){e.issues.push({path:`${t}.${n}`,message:`${n} must be a boolean, got ${ME(i)}`,line:J(e.source,[n])});return}return i}}}}function KE(e){let{min:t,max:n}=e;return{required:!1,json:{type:`integer`,minimum:t,maximum:n},parse:(e,r,i,a)=>{let o=a[i];if(o!==void 0){if(typeof o!=`number`||!Number.isInteger(o)||o<t||o>n){e.issues.push({path:`${r}.${i}`,message:`${i} must be an integer between ${t} and ${n}, got ${Z(o)}`,line:J(e.source,[i])});return}return o}}}}function qE(e={}){let{min:t}=e;return{required:!1,json:{type:`number`,...t!==void 0&&{minimum:t}},parse:(e,n,r,i)=>{let a=i[r];if(a!==void 0){if(typeof a!=`number`||!Number.isFinite(a)||t!==void 0&&a<t){let i=t===void 0?`a finite number`:`a finite number >= ${t}`;e.issues.push({path:`${n}.${r}`,message:`${r} must be ${i}, got ${Z(a)}`,line:J(e.source,[r])});return}return a}}}}function JE(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>AE(e,t,r)}}function YE(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>DE(e,t,r,n)??void 0}}function XE(e,t){return f(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function ZE(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=DE(e,t,r,n);if(i===null)return;let a=XE(`${t}.${n}`,i);return a===null?i:RE(e,`${t}.${n}`,a)??void 0}}}function QE(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>jE(t,n,i,r,e)}}function $E(e,t={closed:!0}){let n=e,r={},i=[];for(let[e,t]of Object.entries(n))r[e]=t.json,t.required&&i.push(e);return{type:`object`,properties:r,...i.length>0&&{required:i},...t.closed&&{additionalProperties:!1}}}function eD(e){return $E(e.fields)}function tD(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function nD(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function rD(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const iD={required:!1,json:{enum:[...Rm]},parse:(e,t,n,r)=>{if(r[n]===`auto`){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: "auto" is not supported — the render daemon runs detached, so terminal detection would read the daemon's environment, not your terminal's. Pick an explicit depth: ${Rm.join(`, `)}`,line:J(e.source,[...t.split(`.`),n])});return}return jE(e,t,r,n,Rm)}},aD={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=kE(e,t,r,n);return hm(i)?i:AE(e,t,r)}},oD={required:!1,json:{anyOf:[{enum:[...Tm]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&hm(i)?i:jE(e,t,r,n,Tm)}},sD=/^[^\r\n]*\S[^\r\n]*$/u,cD=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),lD={required:!1,json:{type:`string`,pattern:sD.source,not:{pattern:cD.source}},parse:(e,t,n,r)=>{let i=kE(e,t,r,n);if(i===void 0||sD.test(i)&&!cD.test(i))return i;e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: must be one line of visible text other than a close glyph ("✖", "✕") — the settings menu needs a glyph to click`,line:J(e.source,[...t.split(`.`),n])})}};function uD(e){return{spec:QE(e),domain:{from:e}}}function dD(){return{spec:GE(),domain:`bool`}}function fD(e){return{spec:e,domain:`text`}}const pD={default_empty_value:fD(WE()),default_separator:fD(WE()),palette:{spec:aD,domain:{themes:`themes`}},style:{spec:WE(),domain:{from:`styles`}},effect:{spec:oD,domain:{from:Tm}},preset:{spec:WE(),domain:{from:`presets`}},endcaps:uD(Am),variation:uD(Bm),shade:uD(Um),autoWrap:dD(),padding:{spec:KE(Ym),domain:{...Ym,step:1}},charset:uD(Fm),updateNotice:dD(),transitions:dD(),colorCompatibility:{spec:iD,domain:{from:Rm}},menuGlyph:fD(lD)},mD=Object.fromEntries(Object.entries(pD).map(([e,t])=>[e,t.spec]));function hD(e){return pD[e].domain}function gD(e){let t=hD(e);if(t===`text`)throw Error(`globals.${e} is free text, which no control can change — list it in UNCONTROLLED_GLOBALS instead of SETTINGS`);return t}function _D(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:J(e.source,[...n.split(`.`),r])})}}}function vD(e){return _D(`${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 yD(e){return _D(`${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 bD(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&hm(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:J(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const xD={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)`},SD={noun:`globals key`,fields:mD,removed:xD},CD={preset:vD(`a preset`),menuGlyph:yD(`a preset`)},wD={noun:`preset globals key`,fields:{...mD,...CD},removed:xD};function TD(e){return FD(e)&&!(e in CD)}const ED=`is decided later than any rule could be settled`,DD={noun:`editGlobals key`,removed:xD,fields:{...mD,preset:vD(`the editGlobals fragment`),menuGlyph:yD(`the editGlobals fragment`),palette:bD(mD.palette,`the editGlobals fragment`,ED),style:bD(mD.style,`the editGlobals fragment`,ED),effect:bD(mD.effect,`the editGlobals fragment`,ED)}},OD={noun:`theme default key`,fields:{...Object.fromEntries(_g.map(e=>[e,mD[e]])),style:bD(mD.style,`a theme's default`,`is the look that theme wears by name`)}};function kD(e,t){if(!X(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${ME(t)}`,line:J(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${om(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[`themeDefaults`,r])});continue}let a=NE(e,OD,t,i);a!==null&&(n[r]=a)}return n}function AD(e,t,n){return n===void 0?{}:NE(e,SD,t,n)??{}}function jD(e,t,n){return NE(e,wD,t,n)??{}}function MD(){return eD(wD)}function ND(e,t,n){return NE(e,DD,t,n)??{}}const PD=new Set(Object.keys(mD));function FD(e){return PD.has(e)}function ID(){return[...PD]}const LD={padding:1};function RD(e){let t=new Map;for(let[n,r]of Object.entries(LD)){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const zD=/^segments\.([^.]+)\.palette$/,BD=/^presets\.(.+)\.root$/,VD=/^presets\.(.+)\.globals\.([^.]+)$/,HD=/^themeDefaults\.(.+)\.([^.]+)$/;function UD(e){return`presets.${e}.root`}function WD(e,t){return`themeDefaults.${e}.${t}`}const GD=e=>_g.includes(e);function KD(e,t){return`presets.${e}.globals.${t}`}function qD(e){if(FD(e))return{scope:`globals`,field:e};let t=zD.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=VD.exec(e);if(n&&TD(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=HD.exec(e);if(r&&GD(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=BD.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function JD(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 YD=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],XD=[...YD,`other`],ZD={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},QD=Py({fromString:e=>e}),$D=`edit.mode`,eO=`edit.configure`,tO=`edit.toggle`,nO=`edit.unconfigure`,rO=[tO,nO],iO=`arrange`,aO=`${oE}draft.`;function oO(e,t){return`${e}:${t}`}const sO={variable:$D,key:$D,member:iO},cO=ir(sO);function lO(e){try{return QD.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function uO(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`&&lO(e))return!0;return!1}function dO(e,t){if(uE(e,t,oE,`edit mode`),!uO(t))return;let{variables:n,actions:r}=fO();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function fO(){return{variables:{[$D]:lr($D,Qn),[eO]:lr(eO,Qn)},actions:{[tO]:ur($D,iO),[nO]:{set:eO,to:Qn}}}}const pO=`open`;function mO(e,t,n,r){let i={variable:e,key:e,member:pO};return r.variables[e]=lr(e,Qn),r.actions[e]=ur(e,pO),r.segments[e]={template:or(e,`(?)`,`✕`),...hO(n)},rr(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 hO(e){let[t,...n]=e;return t===void 0?{}:{when:ir(t,...n)}}const gO=`none`;function _O(e){return Qs(e,`background`)}var vO=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function yO(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=bO(n,i),l=c!==gO,u=l?c===void 0?o:xO(a,c,`bg`):_O(a);e.bg=u;let d=bO(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:Np(a,e,t))(u):void 0:xO(a,d,`fg`);return new H({...l&&{bgcolor:B.fromRgba(u)},...f!==void 0&&{color:B.fromRgba(f)}})}function bO(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function xO(e,t,n){try{return Qs(e,t)}catch(e){throw e instanceof Zs?new vO(t,n,e.message):e}}const SO=`🔧`,CO={help:[`-h`,`--help`],version:[`-V`,`--version`]},wO=[`✚ inserts`,`✖ removes`,`${SO} configures`,`↺ resets layout`],TO=`
66
+ `)}function aC(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 oC(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw Jx(`join`,2,`list of strings/primitives`,`list element of type ${sC(e)}`);n.push(String(e))}return n.join(e)}function sC(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function cC(e){return ZS(e,`-`)}function lC(e){return e.toLowerCase()}function uC(e,t){return`\n${iC(e,t)}`}function dC(e){return e.replace(/\s+/g,``)}function fC(e,t,n){return n===1?e:t}function pC(...e){return e.map(e=>`"${e}"`).join(` `)}function mC(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function hC(e,t){return t.repeat(Math.max(0,e))}function gC(e,t,n){return IS(e,n).join(t)}function _C(e){return ZS(e,`_`)}function vC(e,t){let n=IS(e,t),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function yC(e,t){return IS(e,t)}function bC(e,t,n){let r=xC(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function xC(e,t,n){if(n===0)return[];let r=IS(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 SC(...e){return e.map(e=>`'${e}'`).join(` `)}function CC(e,t,n){let r=FS(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 wC(e){let t=``;for(let n of e)TC(n)?t+=n.toLowerCase():EC(n)?t+=n.toUpperCase():t+=n;return t}function TC(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function EC(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function DC(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function OC(e){return e.trim()}function kC(e,t){if(e.length===0)return t;let n=new Set(FS(e)),r=FS(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 AC(e,t){return t.startsWith(e)?t.slice(e.length):t}function jC(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function MC(e,t){let n=FS(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 NC(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function PC(e){return e.toUpperCase()}function FC(e,t){return IC(e,`
67
+ `,t)}function IC(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
68
+ `)){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 LC(e,t,n){return IC(e,t,n)}function RC(){return{abbrev:{fn:(e,t)=>LS(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>RS(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>$S(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>eC(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>tC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>nC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>rC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>iC(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>aC(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>oC(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>cC(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>lC(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>uC(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>dC(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>fC(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>pC(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>mC(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>hC(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>gC(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>_C(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>vC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>yC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>bC(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>SC(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>CC(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>wC(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>DC(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>OC(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>kC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>AC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>jC(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>MC(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>NC(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>PC(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>FC(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>LC(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function zC(e,t){let n=BC(e),r=n.copy();return r.style=ll(n.style,t),r}function BC(e){if(!(e instanceof G))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function VC(e){return{fn:(t=>zC(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function HC(e){return{fn:((t,n)=>zC(n,new H({[e]:B.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function UC(e,t){return new H({[e]:t})}function WC(){let e={};for(let t of rl)e[t]=VC(UC(t,!0)),e[`not_${t}`]=VC(UC(t,!1));for(let[t,n]of Object.entries(al))e[t]=VC(UC(n,!0));return e}const GC={fn:((e,t)=>zC(t,H.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},KC={fn:((e,t)=>zC(t,new H({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function qC(){return{fg:HC(`color`),bg:HC(`bgcolor`),...WC(),link:KC,style:GC}}function JC(e,t){let n;try{n=xs(e.trim())}catch(n){throw n instanceof rs?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 YC(n,t,JSON.stringify(e))}function YC(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 XC(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function ZC(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 QC=XC([`string`,`int`],((e,t)=>ic(JC(e,`darken`),t).hex)),$C=XC([`string`,`int`],((e,t)=>ic(JC(e,`lighten`),-t).hex)),ew={min:0,max:100,note:`0 = from, 100 = toward`},tw=XC([`string`,`string`,`float`],((e,t,n)=>Ss(JC(e,`mix`),JC(t,`mix`),ZC(n,`mix`,`percentage`,ew)/100).hex)),nw={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},rw=XC([`string`],(e=>oc(JC(e,`contrastOn`)).hex)),iw={depth:z.TRUECOLOR},aw=e=>XC([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return sc(JC(t,`readableOn`),JC(n,`readableOn`),ZC(r,`readableOn`,`ratio`,nw),i,void 0,a).hex})),ow={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function sw(){let e={};for(let[t,n]of Object.entries(ow)){let r=t;e[n]=XC([`string`,`float`],((e,t)=>{let i={...Bs,[r]:ZC(t,n,`amount`)};return V.fromRgba(JC(e,n)).applyKey(i).toRgba().hex}))}return e}function cw(e=()=>iw){return{darken:QC,lighten:$C,mix:tw,contrastOn:rw,readableOn:aw(e),...sw()}}function lw(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:YC(Qs(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function uw(e){return{color:{fn:(t=>Qs(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new Wc(Xc(n),lw(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}function dw(e){return{...qC(),...cw(e)}}new H({color:`red`,dim:!0});const fw=/^(?:(?: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,pw=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function mw(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(fw);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(pw);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 hw(e){let t=e.match(pw);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 gw(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 _w(e){return e.toLocaleString()}function vw(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 yw(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 bw=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],xw=bw.length;function Sw(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*(xw-1));o+=bw[t]}return o}function Cw(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 ww(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 Tw=lm(),Ew=[...Am];function Dw(){return{basename:{fn:e=>u(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>d(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>gw(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(z_(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>R_(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>B_(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>Tw,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>Ew,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(ww(`sparkline`,[`width`],n),Sw(Cw(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>yw(e,vw(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function Ow(e){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},formatInteger:{fn:e=>_w(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>mw(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>hw(e),argTypes:[`string`],arity:{kind:`exact`}}}}function kw(e){let{clock:t,drawnAt:n,extraFuncs:r}=e;return Fy({fromString:e=>new G(e),toString:e=>e.plain,isT:e=>e instanceof G,clock:t,missingKey:`error`,funcs:{...wx(),...RC(),...fS(),...PS(),...gx(t),...ob(),...Bx(),...Rx(),...dw(n&&(()=>({depth:n()}))),...Dw(),...Ow(t),...r??{}}})}function Aw(e){return jw(e,new Set(e.names()),``)}function jw(e,t,n){return new Proxy(Object.create(null),{has(e,r){if(typeof r!=`string`)return!1;let i=n?`${n}.${r}`:r;if(t.has(i))return!0;let a=`${i}.`;for(let e of t)if(e.startsWith(a))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a))return e.getKind(a)===`document`?Nw(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return jw(e,t,a)}})}function Mw(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 Nw(e,t){switch(t.kind){case`ok`:return t.value;case`absent`:throw new V_(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}function Pw(e){return r.existsSync(l.join(e,`.git`))}function Fw(e){let t=l.resolve(e);for(;;){if(Pw(t))return t;let e=l.dirname(t);if(e===t)return;t=e}}function Iw(e){let t=Fw(e);return t===void 0?{root:l.resolve(e),git:!1}:{root:t,git:!0}}function Lw(e,t){return e.kind===`absent`?P(`none`):e.kind===`failed`?e:t.kind===`failed`?t:P(t.kind===`ok`?`tracked`:`gone`)}function Rw(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 zw={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},Bw={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function Vw(e,t,n){return Object.hasOwn(t,n)?P(t[n]):I(`${e}: unknown state ${JSON.stringify(n)}`)}function Hw(e,t,n){return t.ok?P(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?F:I(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??Uw(t.stderr)].filter(Boolean).join(`, `)}`)}function Uw(e){return e.trim().split(`
69
+ `,1)[0]??``}function Ww(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?F:P(n)}function Gw(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?P(t):F}const Kw=/^[A-Za-z]:[\\/]/;function qw(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 qw(e)?.host||null}function Yw(e){let t=Jw(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}function Xw(e){let t=new Map;for(let n of e.split(`
70
+ `)){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 Zw(e){return e.urls.find(e=>nT(e)!==null)??e.urls[0]??null}function Qw(e){return e.find(e=>e.name===`origin`)??e[0]??null}function $w(e){let t=Qw(e);return t?Zw(t):null}function eT(e){let t=Qw(e);return t?t.urls.find(e=>Yw(e)!==null)??Zw(t):null}function tT(e){let t=(qw(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function nT(e){let t=qw(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 rT(e){let t=$w(e);return t===null?null:nT(t)}function iT(e,t,n,r){return t.ok?r(t.stdout):t.reason===`spawn-error`&&/ENOENT/i.test(t.error??``)||t.reason===`non-zero`&&n.test(t.stderr)?F:I(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??Uw(t.stderr)].filter(Boolean).join(`, `)}`)}function aT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function oT(e){let t=`detached`,n=F,r=F,i=F,a=0,o=0,s=0,c=0;for(let l of e.split(`
71
+ `)){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 sT(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(!aT(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=Vw(`gh pr view`,zw,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function cT(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(!aT(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=Vw(`glab mr view`,Bw,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function lT(e){try{let t=r.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var uT=class{isGitRepo(e){return Pw(e)}async execGitAsync(e,t){return Me({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}async resolveEffectiveGitDir(e,t){return this.isWorktree(e)?P(e):t&&this.isGitRepo(t)?P(t):this.isGitRepo(e)?P(e):this.findGitRoot(e)}async findGitRoot(e){let t=Fw(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=await 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=Ww(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showTimeSinceCommit&&(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=Ww(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=Ww(s,rT)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),P(o)}resolveGitDir(e){let t=l.join(e,`.git`);try{if(r.existsSync(t)&&r.statSync(t).isFile()){let n=r.readFileSync(t,`utf-8`).match(/^gitdir:\s*(.+)$/m);if(n?.[1])return l.resolve(e,n[1].trim())}}catch{}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return r.existsSync(l.join(t,`MERGE_HEAD`))?P(`MERGE`):r.existsSync(l.join(t,`CHERRY_PICK_HEAD`))?P(`CHERRY-PICK`):r.existsSync(l.join(t,`REVERT_HEAD`))?P(`REVERT`):r.existsSync(l.join(t,`BISECT_LOG`))?P(`BISECT`):r.existsSync(l.join(t,`rebase-merge`))||r.existsSync(l.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 Gw(Hw(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestampMs(e,t.value):t}commitTimes=new Map;async commitTimestampMs(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.readCommitTimestampMs(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 readCommitTimestampMs(e,t){let n=Gw(Hw(`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)*1e3;return Number.isNaN(r)?I(`git log -1: unparseable timestamp "${n.value}"`):P(r)}resolveCommonGitDir(e){let t=this.resolveGitDir(e);try{let e=r.readFileSync(l.join(t,`commondir`),`utf-8`).trim();if(e)return l.resolve(t,e)}catch{}return t}getStashCount(e){let t=l.join(this.resolveCommonGitDir(e),`logs`,`refs`,`stash`),n;try{n=r.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 i=n.trim();return P(i?i.split(`
72
+ `).length:0)}async getRemotesAsync(e){let t=lT(l.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){let t=Hw(`git config --get-regexp remote url`,await this.execGitAsync([`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`],{cwd:e,timeout:2e3}),1);return t.kind===`failed`?t:P(t.kind===`ok`?Xw(t.value):[])}repoNameFrom(e,t){let n=$w(e);return(n===null?null:tT(n))??l.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=eT(t.value);return n===null?F:P(n)}async execForgeAsync(e,t,n){return Me({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=Yw(t);return n===`github`?iT(`gh pr view`,await this.execForgeAsync(`gh`,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,sT):n===`gitlab`?iT(`glab mr view`,await this.execForgeAsync(`glab`,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,cT):F}isWorktree(e){try{let t=l.join(e,`.git`);return!!(r.existsSync(t)&&r.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){D(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=Hw(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?P(oT(t.value)):t}};const dT=(e,t)=>D(t);var fT=class{slots=new Map;maxWatchers;counters;logger;closed=!1;constructor(e={}){this.maxWatchers=e.maxWatchers??128,this.counters=e.counters,this.logger=e.logger??dT}acquire(e,t,n){if(this.closed)return{release:()=>{}};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,r.lastTouched=Date.now(),this.slots.delete(e),this.slots.set(e,r),this.makeHandle(e);let i={key:e,watchers:[],refcount:1,debounceTimer:null,onInvalidate:n,targets:t,lastTouched:Date.now()};return this.openWatchers(i),this.slots.set(e,i),this.counters&&this.counters.watchersOpened++,this.evictIfNeeded(),this.makeHandle(e)}makeHandle(e){let t=!1;return{release:()=>{if(t)return;t=!0;let n=this.slots.get(e);n&&(n.refcount=Math.max(0,n.refcount-1),n.refcount===0&&(this.closeSlot(n),this.slots.delete(e)))}}}openWatchers(e){let t=()=>{e.debounceTimer||(e.debounceTimer=setTimeout(()=>{e.debounceTimer=null;try{e.onInvalidate()}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50),e.debounceTimer.unref())};for(let n of e.targets.files)try{let i=r.watch(n,{persistent:!1},t);i.on(`error`,e=>{this.logger(`warn`,`watcher error ${n}: ${e.message}`)}),e.watchers.push(i)}catch(e){this.logger(`warn`,`watch failed ${n}: ${e.message}`)}for(let n of e.targets.dirs)try{let i=n.filenames?new Set(n.filenames):null,a=r.watch(n.path,{persistent:!1},(e,n)=>{i&&(!n||!i.has(n))||t()});a.on(`error`,e=>{this.logger(`warn`,`watcher error ${n.path}: ${e.message}`)}),e.watchers.push(a)}catch(e){this.logger(`warn`,`watch failed ${n.path}: ${e.message}`)}}closeSlot(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}evictIfNeeded(){for(;this.slots.size>this.maxWatchers;){let e=this.slots.keys().next().value;if(e===void 0)break;let t=this.slots.get(e);this.closeSlot(t),this.slots.delete(e),this.counters&&this.counters.watchersEvicted++;try{t.onInvalidate()}catch{}this.logger(`info`,`watcher LRU evict ${e}`)}}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}},pT=class{running=new Set;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:(this.running.add(e),{kind:`started`,done:this.loop(e,t)})}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 mT={showSha:!0,showStashCount:!0};function hT(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function gT(e){let t=t=>{try{return r.statSync(l.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function _T(e,t){return e.head!==t.head||e.index!==t.index}function vT(e){let t=[],n=l.join(e,`refs/heads`);try{r.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[l.join(e,`HEAD`),l.join(e,`index`)],dirs:t}}var yT=class extends uT{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new pT;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new uT,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??Ft,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new fT({logger:this.logger}),this.ownsWatchers=!0);let t=e.sanityIntervalMs??3e5;t>0&&(this.sanityTimer=setInterval(()=>this.runSanityCheck(),t),this.sanityTimer.unref())}getWatcherRegistry(){return this.watchers}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,invalidations:this.invalidations,watchers:this.watchers.size()}}resolveEffectiveGitDir(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.resolutions.delete(n),this.resolutions.set(n,i),i.dir;let a=this.inner.resolveEffectiveGitDir(e,t);return this.resolutions.set(n,{dir:a,computedAt:r}),a.catch(()=>{this.resolutions.get(n)?.dir===a&&this.resolutions.delete(n)}),this.evictResolutionsIfNeeded(),a}evictResolutionsIfNeeded(){for(;this.resolutions.size>this.maxEntries;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}}async getGitInfo(e,t={},n){let r=await this.resolveEffectiveGitDir(e,n);return r.kind===`ok`?this.getGitInfoForRoot(r.value,t):r}getGitInfoForRoot(e,t){let n=`${e}|${hT(t)}`,r=Date.now(),i=this.entries.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.entries.delete(n),this.entries.set(n,i),this.hits++,Promise.resolve(P(i.info));let a=this.fetchInFlight.get(n);if(a)return a;let o=this.doFetch(e,n,t,r).finally(()=>{this.fetchInFlight.delete(n)});return this.fetchInFlight.set(n,o),o}async doFetch(e,t,n,r){this.misses++;let i=this.inner.resolveGitDir(e),a=gT(i),o=await this.inner.getGitInfo(e,n);if(o.kind!==`ok`)return o;let s=o.value;n.showPullRequest&&(s.pullRequest=await this.getPullRequestCached(e,s.branch)),this.dropEntry(t);let c=this.watchers.acquire(`git:${e}`,vT(i),()=>this.invalidateRepo(e));return this.entries.set(t,{info:s,computedAt:r,mtime:a,watcher:c,repoRoot:e}),this.evictIfNeeded(),o}async getPullRequestCached(e,t){let n=await this.inner.getRepoRemoteUrl(e);if(n.kind===`failed`)return n;if(n.kind===`absent`)return F;let r=n.value,i=`${e}|${t}|${r}`,a=Date.now(),o=this.prCache.get(i);if(o){let e=o.pr.kind===`failed`?45e3:3e5;if(a-o.computedAt<e)return this.prCache.delete(i),this.prCache.set(i,o),o.pr}let s=this.prFetchInFlight.get(i);if(s)return s;let c=this.inner.resolvePullRequest(e,r).then(e=>(this.prCache.set(i,{pr:e,computedAt:Date.now()}),this.evictPrIfNeeded(),e)).finally(()=>{this.prFetchInFlight.delete(i)});return this.prFetchInFlight.set(i,c),c}evictPrIfNeeded(){for(;this.prCache.size>this.maxEntries;){let e=this.prCache.keys().next().value;if(e===void 0)break;this.prCache.delete(e)}}deliverable(e,t){return e.kind===`failed`?(this.logger(`warn`,`git fetch failed (${t}): ${e.reason}`),null):e.kind===`ok`?e.value:null}subscribe(e,t){let n=!1,r=null;return{firstDelivery:(async()=>{let i=await this.resolveEffectiveGitDir(e);if(n)return;if(i.kind!==`ok`){i.kind===`failed`&&this.logger(`warn`,`git resolve failed (subscribe ${e}): ${i.reason}`),this.safeInvoke(t,null);return}let a=i.value,o=this.subscribersByRepo.get(a);if(!o){let t=this.inner.resolveGitDir(a),n=this.watchers.acquire(`git:${a}`,vT(t),()=>this.invalidateRepo(a));o={workingDir:e,repoRoot:a,callbacks:new Set,watcher:n},this.subscribersByRepo.set(a,o)}o.callbacks.add(t),r={repoRoot:a,entry:o};let s=await this.getGitInfoForRoot(a,{...mT});n||this.safeInvoke(t,this.deliverable(s,a))})(),unsubscribe:()=>{if(n=!0,!r)return;let{repoRoot:e,entry:i}=r;i.callbacks.delete(t),i.callbacks.size===0&&(i.watcher.release(),this.subscribersByRepo.delete(e))}}}invalidateRepo(e){let t=0;for(let[n,r]of this.entries)r.repoRoot===e&&(r.watcher.release(),this.entries.delete(n),t++);t>0&&(this.invalidations+=t,this.logger(`info`,`gitCache invalidate ${e} dropped=${t}`)),this.refreshSubscribers(e)}refreshSubscribers(e){let t=this.subscribersByRepo.get(e);!t||t.callbacks.size===0||this.refreshes.run(e,()=>this.refreshOnce(e))}async refreshOnce(e){let t=this.subscribersByRepo.get(e);if(!t||t.callbacks.size===0)return;let n=await this.getGitInfoForRoot(e,{...mT}),r=this.deliverable(n,e),i=this.subscribersByRepo.get(e);if(!(!i||i.callbacks.size===0))for(let e of[...i.callbacks])i.callbacks.has(e)&&this.safeInvoke(e,r)}safeInvoke(e,t){try{e(t)}catch(e){this.logger(`warn`,`git subscriber threw: ${e.message??String(e)}`)}}dropEntry(e){let t=this.entries.get(e);t&&(t.watcher.release(),this.entries.delete(e))}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.dropEntry(e),this.logger(`info`,`gitCache evict ${e}`)}}runSanityCheck(){let e=new Map;for(let t of this.entries.values()){let n=e.get(t.repoRoot);n||(n=gT(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),_T(t.mtime,n)&&this.invalidateRepo(t.repoRoot)}}runSanityCheckNow(){this.runSanityCheck()}close(){this.sanityTimer&&=(clearInterval(this.sanityTimer),null);for(let e of this.entries.values())e.watcher.release();this.entries.clear();for(let e of this.subscribersByRepo.values())e.callbacks.clear(),e.watcher.release();this.subscribersByRepo.clear(),this.refreshes.clear(),this.fetchInFlight.clear(),this.prCache.clear(),this.prFetchInFlight.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}};const bT=/\r\n|\r|\n/g,xT=e=>P(e.replace(bT,` `).trim());function ST(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?I(`regex no-match`):P(n.replace(bT,` `))}}const CT=e=>{try{return P(JSON.parse(e))}catch(e){return I(`JSON parse failed: ${e.message}`)}},wT=e=>e.getTime()/1e3,TT=e=>new Date(e*1e3);function ET(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function DT(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 OT=`session.id`;function kT(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await Me({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 AT(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await oe(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 jT(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?I(`${r.reason} in ${n}`):r}const MT=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],NT=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],PT=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],FT=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function IT(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>MT[e.getMonth()]],[`Monday`,e=>PT[e.getDay()]],[`Jan`,e=>NT[e.getMonth()]],[`Mon`,e=>FT[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const LT={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function RT(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=LT[t];try{return KT(r,e)}catch{return qT(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return _i(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return _i(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return _i(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return _i(e.stashCount,0)}}function zT(e){try{return o(e)}catch{return e}}function BT(e){try{return s(e).isDirectory()}catch{return!1}}function VT(e){let t=zT(e);return BT(t)?{dir:t,name:null,leaf:!0}:j_(t)}const HT=e=>`${e.dir}\0${e.name??``}`;var UT=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:VT(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=VT(e);if(t.watcher!==null&&HT(n)===HT(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=l.basename(r);try{return c(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}},WT=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:le(()=>{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&&(ce(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())ce(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function GT(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function KT(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`?R_(e):t===`number`?z_(e):B_(e)}function qT(e){return e===`number`?0:e===`boolean`?!1:``}var JT=class{inputMetas=new Map;lastErrors=new Map;policyFaults=new Map;watchMgr=new UT;ttlMgr=new WT;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new pT;abort=new AbortController;drawn=F_.observable.box(z.TRUECOLOR);drawnAt=()=>this.drawn.get();instant=F_.observable.box(null);now=()=>{let e=this.instant.get();if(e===null)throw Error(`the time was read before any render published its instant`);return TT(e)};engine=kw({clock:this.now,drawnAt:this.drawnAt});gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new yT({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,L_(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,I(t))}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}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,kT(t,n.cwd,this.abort.signal),ET(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,AT(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,xT,t.default,n);case`regex`:return this.scalarPublisher(e,ST(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=jT(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,_i(a,i))}}documentPublisher(e,t,n){let r=t===void 0?F: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=jT(s,CT,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)};u?i=setTimeout(d,250):d()}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.declareDerived(e,()=>r.evaluate(Aw(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){this.declareDerived(e,()=>IT(t.format,this.now()),t.varDefault)}declareDerived(e,t,n){this.store.defineComputed(e,`string`,()=>{try{let n=t();return this.lastErrors.delete(e),n}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n===void 0)throw H_(t)?new V_(e,`variable "${e}": ${r}`):Error(`variable "${e}": ${r}`);return n}})}declareGit(e,t){let n=LT[t.field],r=t.varDefault===void 0?qT(n):KT(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,RT(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}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(OT);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(OT):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=GT(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,KT(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}drawAt(e){this.store.runInAction(()=>this.drawn.set(e))}renderAt(e){this.store.runInAction(()=>this.instant.set(e))}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 this.policyFaults}dispose(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();return this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let r=this.watchMgr.subscribe(t.path,n,t=>this.notePolicy(e,I(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template),i=()=>{try{return P(r.evaluate(Aw(this.store)).map(e=>e.plain).join(``))}catch(e){return H_(e)?F:I(`cache key: ${e instanceof Error?e.message:String(e)}`)}},a=i();this.notePolicy(e,a);let o=a.kind===`ok`?a.value:void 0,s=(0,F_.reaction)(i,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===o)&&(o=t.value,n())});this.cleanups.push(s);break}case`depends_on`:{let e=(0,F_.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,KT(this.defaultEmptyValue,t))}catch{this.store.setBox(e,qT(t))}}defaultFor(e){try{return KT(this.defaultEmptyValue,e)}catch{return qT(e)}}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){t.kind===`failed`?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`)}};const YT={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[OT]:{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:``},"theme.effective":{kind:`input`,path:`theme.effective`,default:``},"style.effective":{kind:`input`,path:`style.effective`,default:``},"effect.effective":{kind:`input`,path:`effect.effective`,default:``},"preset.effective":{kind:`input`,path:`preset.effective`,default:``},"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},"endcaps.effective":{kind:`input`,path:`endcaps.effective`,default:``},"variation.effective":{kind:`input`,path:`variation.effective`,default:``},"shade.effective":{kind:`input`,path:`shade.effective`,default:``},"charset.effective":{kind:`input`,path:`charset.effective`,default:``},"colorCompatibility.effective":{kind:`input`,path:`colorCompatibility.effective`,default:``},"transitions.effective":{kind:`input`,path:`transitions.effective`,type:`boolean`,default:!1},"autoWrap.effective":{kind:`input`,path:`autoWrap.effective`,type:`boolean`,default:!0},"padding.effective":{kind:`input`,path:`padding.effective`,type:`number`,default:1},"updateNotice.effective":{kind:`input`,path:`updateNotice.effective`,type:`boolean`,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:``}},XT=`ne .tmux.pane ""`;function ZT(e,t,n){let r=new Set,i=e=>{for(let t of x_(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 pg(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(OT);for(let t of Object.values(e.actions)){r.add(OT),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?Ea.get(t.set):void 0,n=`persist`in t?Ta.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function QT(e,t,n){let r=k_({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of ZT(e,t,n.helpers)){if(O_(a,r))continue;let e=YT[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 $T(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}var eE=class extends Error{file;issues;warnings;constructor(e,t,n=[]){super(iE(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t,this.warnings=n}};function J(e,t){let n=0,r;for(let i of t){if(i===``||/^\d+$/.test(i))continue;let t=tE(e,n,i);if(t===-1)return r===void 0?void 0:nE(e,r);n=t,r=t}return r===void 0?void 0:nE(e,r)}function tE(e,t,n){let r=n.replace(/[\\^$.*+?()[\]{}|]/g,`\\$&`),i=RegExp(`(?:["']${r}["']|\\b${r}\\b)\\s*:`,`g`);i.lastIndex=t;let a=i.exec(e);return a?a.index:-1}function nE(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function rE(e,t){try{return Tr(t),null}catch(n){if(!(n instanceof yr))throw n;return`${e}:${nE(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function iE(e,t){if(t.length===0)return`${e}: invalid config (no details)`;let n=[`Invalid config in ${e} (${t.length} issue${t.length===1?``:`s`}):`];for(let e of t){let t=[];e.line!==void 0&&t.push(`line ${e.line}${e.col===void 0?``:`:${e.col}`}`),e.path&&t.push(e.path);let r=t.length>0?`[${t.join(` • `)}] `:``;n.push(` ${r}${e.message}`)}return n.join(`
73
+ `)}const aE=`groups.`,oE=`menus.`,sE=`edit.`,Y=`candybar.`,cE=[aE,oE,sE,Y];function lE(e){return cE.some(t=>e.startsWith(t))}function uE(e){let t=$T(e);return cE.find(e=>t.startsWith($T(e)))}function dE(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:J(e.source,[`root`])})}function fE(e){return e}function pE(e,t,n){return n===void 0?oE+$T(e)+`.`+$T(t):mE(n)}function mE(e){return oE+$T(e)}function hE(e,t){return e+`.`+t}function gE(e){return e+`.page`}const _E=[`closeOnPick`,`paged`,`key`,`distribution`],vE=e=>_E.includes(e),yE=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${cp.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function bE(e){for(let t of Object.keys(e))if(!vE(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${yE}`);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&&!lp(r))throw Error(`{{ menu }} option "distribution" must be one of: ${cp.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:dp(r)}}const xE=e=>`from`in e?e.from:e.themes;function SE(e,t,n){return e===`bool`?Xm(t)!==null:`min`in e?Zm(t,e)!==null:o_(xE(e),n).members.includes(t)}function CE(e,t){if(e===`bool`)return Jm.join(` or `);if(!(`min`in e)){let n=xE(e),{members:r}=o_(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 wE(e){return{label:e.label,domain:TE(e.domain)}}function TE(e){return e===`theme`?{themes:r_}:e===`bool`||`min`in e?e:{from:e}}function EE(e,t,n,r,i){let a=nr(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...Jm]}},variables:{}};if(`from`in o)return DE(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 DE(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 DE(e,t,n,r,i){let a={variable:n,key:n,member:t},o=hE(n,t),s=`${t}.open`,c=gE(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]:ur(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:lr(n,Qn),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}function OE(e,t,n,r){let i=n[r];return typeof i==`string`?i:(e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${NE(i)}`,line:J(e.source,[...t.split(`.`),r])}),null)}function kE(e,t,n,r){let i=n.default;if(i!==void 0){if(!(r===`string`&&typeof i==`string`||r===`number`&&typeof i==`number`||r===`boolean`&&typeof i==`boolean`)){e.issues.push({path:`${t}.default`,message:`default must be a ${r}, got ${NE(i)}`,line:J(e.source,[...t.split(`.`),`default`])});return}return i}}function AE(e,t,n,r){let i=n[r];if(i!==void 0){if(typeof i!=`string`){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${NE(i)}`,line:J(e.source,[...t.split(`.`),r])});return}return i}}function jE(e,t,n){let r=AE(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${om(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[...t.split(`.`),`palette`])});return}return r}}function ME(e,t,n,r,i){let a=n[r];if(a!==void 0){if(typeof a!=`string`||!i.includes(a)){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be one of: ${i.join(`, `)}; got ${Z(a)}`,line:J(e.source,[...t.split(`.`),r])});return}return a}}function X(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function NE(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Z(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function PE(e,t,n,r){return X(r)?(RE(e,n,r,t.noun,new Set(Object.keys(t.fields)),FE(e,t.removed??{},n,r)),IE(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${NE(r)}`,line:J(e.source,n.split(`.`))}),null)}function FE(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)zE(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function IE(e,t,n,r){let i=t,a={},o=!0;for(let[t,s]of Object.entries(i)){let i=s.parse(e,n,t,r);i===void 0?s.required&&(o=!1):a[t]=i}return o?a:null}const LE=new Set;function RE(e,t,n,r,i,a=LE){for(let o of Object.keys(n))!i.has(o)&&!a.has(`${t}.${o}`)&&e.issues.push({path:`${t}.${o}`,message:`Unknown ${r} "${o}". Expected one of: ${[...i].join(`, `)}`,line:J(e.source,[...t.split(`.`),o])})}function zE(e,t,n){return e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))}),null}function BE(e,t,n,r){if(!X(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${NE(r)}`,line:J(e.source,n.split(`.`))}),null;let i=t.arms,a=Object.keys(i),o=Object.keys(r).filter(e=>e in i),s=Object.keys(r).filter(e=>!(e in i));for(let r of s)e.issues.push({path:`${n}.${r}`,message:`Unknown ${t.noun} key "${r}". Expected exactly one of: ${a.join(`, `)}`,line:J(e.source,[...n.split(`.`),r])});if(o.length===0)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)}`,line:J(e.source,n.split(`.`))}),null;if(o.length>1)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)} (found: ${o.join(`, `)})`,line:J(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function VE(e,t,n,r){if(!X(r))return e.issues.push({path:n,message:`${n} must be an object, got ${NE(r)}`,line:J(e.source,n.split(`.`))}),null;let i=r[t.tag];if(typeof i!=`string`)return e.issues.push({path:`${n}.${t.tag}`,message:`${n}.${t.tag} must be a string, got ${NE(i)}`,line:J(e.source,n.split(`.`))}),null;let a=t.arms;if(!(i in a))return e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:J(e.source,[...n.split(`.`),t.tag])}),null;let o=a[i],s=e.issues.length,c=o.parse(e,n,r),l=new Set(e.issues.slice(s).map(e=>e.path));return RE(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function HE(e,t,n){return{json:nD(eD(n),e,t),keys:new Set([e,...Object.keys(n)])}}function UE(e){return(...t)=>e()(...t)}function WE(e,...t){return(n,r,i)=>{let a=e(n,r,i);if(a===null)return null;for(let e of t){if(e.ok(a))continue;let{field:t,message:i}=e.issue(a),o=t===``?r:`${r}.${t}`;return n.issues.push({path:o,message:i,line:J(n.source,o.split(`.`))}),null}return a}}function GE(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>AE(e,t,r,n)}}function KE(){return{required:!1,json:{type:`boolean`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`boolean`){e.issues.push({path:`${t}.${n}`,message:`${n} must be a boolean, got ${NE(i)}`,line:J(e.source,[n])});return}return i}}}}function qE(e){let{min:t,max:n}=e;return{required:!1,json:{type:`integer`,minimum:t,maximum:n},parse:(e,r,i,a)=>{let o=a[i];if(o!==void 0){if(typeof o!=`number`||!Number.isInteger(o)||o<t||o>n){e.issues.push({path:`${r}.${i}`,message:`${i} must be an integer between ${t} and ${n}, got ${Z(o)}`,line:J(e.source,[i])});return}return o}}}}function JE(e={}){let{min:t}=e;return{required:!1,json:{type:`number`,...t!==void 0&&{minimum:t}},parse:(e,n,r,i)=>{let a=i[r];if(a!==void 0){if(typeof a!=`number`||!Number.isFinite(a)||t!==void 0&&a<t){let i=t===void 0?`a finite number`:`a finite number >= ${t}`;e.issues.push({path:`${n}.${r}`,message:`${r} must be ${i}, got ${Z(a)}`,line:J(e.source,[r])});return}return a}}}}function YE(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>jE(e,t,r)}}function XE(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>OE(e,t,r,n)??void 0}}function ZE(e,t){return f(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function QE(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=OE(e,t,r,n);if(i===null)return;let a=ZE(`${t}.${n}`,i);return a===null?i:zE(e,`${t}.${n}`,a)??void 0}}}function $E(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>ME(t,n,i,r,e)}}function eD(e,t={closed:!0}){let n=e,r={},i=[];for(let[e,t]of Object.entries(n))r[e]=t.json,t.required&&i.push(e);return{type:`object`,properties:r,...i.length>0&&{required:i},...t.closed&&{additionalProperties:!1}}}function tD(e){return eD(e.fields)}function nD(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function rD(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function iD(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const aD={required:!1,json:{enum:[...Rm]},parse:(e,t,n,r)=>{if(r[n]===`auto`){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: "auto" is not supported — the render daemon runs detached, so terminal detection would read the daemon's environment, not your terminal's. Pick an explicit depth: ${Rm.join(`, `)}`,line:J(e.source,[...t.split(`.`),n])});return}return ME(e,t,r,n,Rm)}},oD={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=AE(e,t,r,n);return hm(i)?i:jE(e,t,r)}},sD={required:!1,json:{anyOf:[{enum:[...Tm]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&hm(i)?i:ME(e,t,r,n,Tm)}},cD=/^[^\r\n]*\S[^\r\n]*$/u,lD=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),uD={required:!1,json:{type:`string`,pattern:cD.source,not:{pattern:lD.source}},parse:(e,t,n,r)=>{let i=AE(e,t,r,n);if(i===void 0||cD.test(i)&&!lD.test(i))return i;e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: must be one line of visible text other than a close glyph ("✖", "✕") — the settings menu needs a glyph to click`,line:J(e.source,[...t.split(`.`),n])})}};function dD(e){return{spec:$E(e),domain:{from:e}}}function fD(){return{spec:KE(),domain:`bool`}}function pD(e){return{spec:e,domain:`text`}}const mD={default_empty_value:pD(GE()),default_separator:pD(GE()),palette:{spec:oD,domain:{themes:`themes`}},style:{spec:GE(),domain:{from:`styles`}},effect:{spec:sD,domain:{from:Tm}},preset:{spec:GE(),domain:{from:`presets`}},endcaps:dD(Am),variation:dD(Bm),shade:dD(Um),autoWrap:fD(),padding:{spec:qE(Ym),domain:{...Ym,step:1}},charset:dD(Fm),updateNotice:fD(),transitions:fD(),colorCompatibility:{spec:aD,domain:{from:Rm}},menuGlyph:pD(uD)},hD=Object.fromEntries(Object.entries(mD).map(([e,t])=>[e,t.spec]));function gD(e){return mD[e].domain}function _D(e){let t=gD(e);if(t===`text`)throw Error(`globals.${e} is free text, which no control can change — list it in UNCONTROLLED_GLOBALS instead of SETTINGS`);return t}function vD(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:J(e.source,[...n.split(`.`),r])})}}}function yD(e){return vD(`${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 bD(e){return vD(`${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 xD(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&hm(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:J(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const SD={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)`},CD={noun:`globals key`,fields:hD,removed:SD},wD={preset:yD(`a preset`),menuGlyph:bD(`a preset`)},TD={noun:`preset globals key`,fields:{...hD,...wD},removed:SD};function ED(e){return ID(e)&&!(e in wD)}const DD=`is decided later than any rule could be settled`,OD={noun:`editGlobals key`,removed:SD,fields:{...hD,preset:yD(`the editGlobals fragment`),menuGlyph:bD(`the editGlobals fragment`),palette:xD(hD.palette,`the editGlobals fragment`,DD),style:xD(hD.style,`the editGlobals fragment`,DD),effect:xD(hD.effect,`the editGlobals fragment`,DD)}},kD={noun:`theme default key`,fields:{...Object.fromEntries(vg.map(e=>[e,hD[e]])),style:xD(hD.style,`a theme's default`,`is the look that theme wears by name`)}};function AD(e,t){if(!X(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${NE(t)}`,line:J(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${om(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:J(e.source,[`themeDefaults`,r])});continue}let a=PE(e,kD,t,i);a!==null&&(n[r]=a)}return n}function jD(e,t,n){return n===void 0?{}:PE(e,CD,t,n)??{}}function MD(e,t,n){return PE(e,TD,t,n)??{}}function ND(){return tD(TD)}function PD(e,t,n){return PE(e,OD,t,n)??{}}const FD=new Set(Object.keys(hD));function ID(e){return FD.has(e)}function LD(){return[...FD]}const RD={padding:1};function zD(e){let t=new Map;for(let[n,r]of Object.entries(RD)){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const BD=/^segments\.([^.]+)\.palette$/,VD=/^presets\.(.+)\.root$/,HD=/^presets\.(.+)\.globals\.([^.]+)$/,UD=/^themeDefaults\.(.+)\.([^.]+)$/;function WD(e){return`presets.${e}.root`}function GD(e,t){return`themeDefaults.${e}.${t}`}const KD=e=>vg.includes(e);function qD(e,t){return`presets.${e}.globals.${t}`}function JD(e){if(ID(e))return{scope:`globals`,field:e};let t=BD.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=HD.exec(e);if(n&&ED(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=UD.exec(e);if(r&&KD(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=VD.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function YD(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 XD=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],ZD=[...XD,`other`],QD={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},$D=Fy({fromString:e=>e}),eO=`edit.mode`,tO=`edit.configure`,nO=`edit.toggle`,rO=`edit.unconfigure`,iO=[nO,rO],aO=`arrange`,oO=`${sE}draft.`;function sO(e,t){return`${e}:${t}`}const cO={variable:eO,key:eO,member:aO},lO=ir(cO);function uO(e){try{return $D.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function dO(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`&&uO(e))return!0;return!1}function fO(e,t){if(dE(e,t,sE,`edit mode`),!dO(t))return;let{variables:n,actions:r}=pO();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function pO(){return{variables:{[eO]:lr(eO,Qn),[tO]:lr(tO,Qn)},actions:{[nO]:ur(eO,aO),[rO]:{set:tO,to:Qn}}}}const mO=`open`;function hO(e,t,n,r){let i={variable:e,key:e,member:mO};return r.variables[e]=lr(e,Qn),r.actions[e]=ur(e,mO),r.segments[e]={template:or(e,`(?)`,`✕`),...gO(n)},rr(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 gO(e){let[t,...n]=e;return t===void 0?{}:{when:ir(t,...n)}}const _O=`none`;function vO(e){return Qs(e,`background`)}var yO=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function bO(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=xO(n,i),l=c!==_O,u=l?c===void 0?o:SO(a,c,`bg`):vO(a);e.bg=u;let d=xO(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:Np(a,e,t))(u):void 0:SO(a,d,`fg`);return new H({...l&&{bgcolor:B.fromRgba(u)},...f!==void 0&&{color:B.fromRgba(f)}})}function xO(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function SO(e,t,n){try{return Qs(e,t)}catch(e){throw e instanceof Zs?new yO(t,n,e.message):e}}const CO=`🔧`,wO={help:[`-h`,`--help`],version:[`-V`,`--version`]},TO=[`✚ inserts`,`✖ removes`,`${CO} configures`,`↺ resets layout`],EO=`
74
74
  cc-candybar - Beautiful powerline statusline for Claude Code
75
75
 
76
76
  Usage: cc-candybar [options]
77
77
 
78
78
  Standalone Commands:
79
- ${CO.help.join(`, `).padEnd(25)}Show this help
80
- ${CO.version.join(`, `).padEnd(25)}Print the version of this runtime (cc-candybar <version>)
79
+ ${wO.help.join(`, `).padEnd(25)}Show this help
80
+ ${wO.version.join(`, `).padEnd(25)}Print the version of this runtime (cc-candybar <version>)
81
81
 
82
82
  Debugging:
83
83
  CC_CANDYBAR_DEBUG=1 Enable debug logging for troubleshooting
@@ -100,7 +100,7 @@ Configuration:
100
100
  failed row's [fix] to repair it (the same checks \`cc-candybar doctor\` runs).
101
101
 
102
102
  Anywhere the bar shows (?), clicking it reveals these same instructions
103
- in place. In edit mode: ${wO.join(`, `)}.
103
+ in place. In edit mode: ${TO.join(`, `)}.
104
104
 
105
105
  Subcommands:
106
106
  install One-shot setup: stages the runtime (native render
@@ -147,15 +147,15 @@ Config tooling:
147
147
  config [--json] The effective merged config. (All three query the
148
148
  running daemon; none spawn one.)
149
149
 
150
- `,EO=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`,DO={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function OO(e){let t=e[DO.socket]??``,n=e[DO.pane]??``;if(t===``||n===``)return null;let r=e[DO.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const kO={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:`20220319`}},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`}}},AO=e=>kO[e];function jO(e){return AO(e).glyphs.kind===`bundled`}function MO(e){return AO(e).glyphs.kind===`configured`}const NO=e=>AO(e).label,PO=[{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 FO(e,t){let n=t.codePointAt(0);return PO.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&RO(e,t)===!0)}const IO=Object.keys(kO);function LO(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function RO(e,t){let n=LO(e),r=LO(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 zO(e){for(let t of IO){let n=AO(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 BO(e){let t=IO.find(t=>AO(t).term===e);return t===void 0?null:{name:t,version:null}}function VO(e){let t=zO(e.termtype)??BO(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 HO(e){let t=e.TERM_PROGRAM,n=IO.find(e=>AO(e).program===t),r=n===void 0?BO(e.TERM):{name:n,version:AO(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 UO(e){switch(e.kind){case`known`:return NO(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function WO(e){switch(e.kind){case`known`:return NO(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function GO({name:e,version:t}){let n=AO(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=RO(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const KO=IO.filter(e=>AO(e).links!==null).map(NO).join(`, `),qO=[`drawn`,`boxes`];function JO(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const YO=DO.truecolor,XO={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings: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`:{if(e.client.kind===`failed`)return{ok:!1,reason:`tmux could not be asked: ${e.client.reason}`};if(e.client.value===null||!e.client.value.features.includes(`RGB`)||e.hint.truecolor!==null)return{ok:!0};let n=t.env[YO];return typeof n==`string`&&n!==``?{ok:!1,reason:`${YO} is set in ${t.path} — restart Claude Code to apply`}:{ok:!1,reason:`Claude Code renders the bar in 256 colours inside tmux`,fix:{kind:`claude-settings`,path:[`env`,YO],value:`1`}}}}}},ZO={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},QO={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(`
151
- `).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return JO([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${ZO[e]}`)])}}},$O="re-run `cc-candybar install`";function ek(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:// — ${$O}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${$O}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${$O}`)}const tk={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}) — ${$O}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${$O}`};case`lost`:return JO([...ek(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}`])}}},nk=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function rk(e,t){let n=UO(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?GO(e.terminal):{kind:`unknown`}}function ik({identified:e,tmuxClient:t},n){let r=WO(e),i=rk(e,n),a=UO(e)===null?nk:`${nk}, 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: ${KO}`];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 ak={name:`links`,label:`links`,takesMark:!1,probe:({askedBy:e,terminal:t,clicked:n})=>{if(e===`click`)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 JO(ik(t,n))}}},ok={name:`effectRefresh`,label:`effect refresh`,takesMark:!1,probe:({effect:e,placementEffects:t,transitions:n,claudeSettings:r})=>{let i=[...e.kind===`decided`?e.value===`none`?[]:[`the bar wears the ${e.name} effect`]:[`a globals.effect rule can give the bar an effect`],...t.map(({placement:e,effect:t})=>`${e} wears the ${t} effect`),...n?[`placements fade in and dissolve out as they come and go`]:[]];if(i.length===0)return{ok:!0};let a=i.join(` and `),{path:o,statusLine:s}=r;switch(s.kind){case`absent`:return{ok:!1,reason:`${a}, and ${o} sets no statusLine — set "refreshInterval": 1 beside the statusLine command that runs the bar`};case`not-an-object`:return{ok:!1,reason:`${a}, and ${o} sets statusLine to ${JSON.stringify(s.value)}, not a statusLine object — re-run \`cc-candybar install\` to write one`};case`present`:break}let c=s.refreshInterval;return c===1?{ok:!0}:{ok:!1,reason:c===void 0?`${a}, but Claude Code redraws it only on events`:typeof c==`number`&&c>1?`${a}, but Claude Code redraws it only every ${c} s`:`${a}, but statusLine.refreshInterval is ${JSON.stringify(c)}, not a number of seconds Claude Code accepts (its minimum is 1)`,fix:{kind:`claude-settings`,path:[`statusLine`,`refreshInterval`],value:1}}}},sk=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function ck(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return WO(e);case`bundling`:case`unread`:case`configured`:return[NO(e.name),e.version].filter(e=>e!==null).join(` `)}}function lk(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return UO(e);case`bundling`:case`unread`:return NO(e.name);case`configured`:{let t=NO(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 uk(e){let t=lk(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${sk(e.glyphs)}`}}const dk=`or set globals.charset to "ascii" to draw the bar without them`,fk=[QO,tk,ak,XO,ok,{name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};if(t.kind===`failed`)return{ok:!1,reason:`the mark book could not be read: ${t.reason}`};let n=uk(e),r=e=>({ok:!1,reason:e,...n!==void 0&&{sighting:n}}),i=e.terminal,a=ck(i);switch(n===void 0?null:t.value.nerdFont?.[n.id]??null){case`drawn`:return{ok:!0};case`boxes`:return r(`${a} draws ${sk(e.glyphs)} as boxes — set a Nerd Font as its font, ${dk}`);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=kO[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:RO(i.version,e);if(t===!0)return{ok:!0};let n=NO(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, ${dk}`)}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, ${dk}`):n.length===0?{ok:!0}:r(`${a} draws with ${e} (${t}), which has no ${sk(n)} — set a Nerd Font as its font, ${dk}`)}}}}],pk=fk.filter(e=>e.takesMark);function mk(e){return fk.map(t=>({check:t,verdict:t.probe(e)}))}function hk(e){return fk.find(t=>t.name===e)}const gk=`${Y}doctor.`;function _k(e){let t=`${gk}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function vk(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?UO(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 yk(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=uk(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 bk(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function xk(e){return e.flatMap(({check:e,verdict:t})=>{let n=_k(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:``},{key:n.fixable,value:qm},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:bk(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?qm:Km},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const Sk={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function Ck(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(Sk).map(([t,n])=>[`${e}${t}`,n]))}}const wk=`armed`,Tk=`disarmed`,Ek=`.armed`,Dk=e=>e.endsWith(Ek);function Ok(e,t,n){let r=`${e}${Ek}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${wk}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:wk},[a]:{set:r,to:Tk},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:Tk}},disarm:a}}const kk=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function Ak(e){return typeof e==`string`&&kk.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 jk(e){let t=Ak(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const Mk=[`/compact`,`/model`],Nk=`/clear`;function Pk(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=Ok(`${e}clear`,{arm:Nk,confirm:`${Nk} ✓ confirm`},[n]);return{template:Mk.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${YT} }}`,actions:{...Object.fromEntries(Mk.map(e=>[t(e),{slash:jk(e)}])),...r.actions,[n]:{slash:jk(Nk)}},variables:r.variables,disarm:r.disarm}}const Fk=Array.from({length:10},(e,t)=>(t+1)*1e5),Ik=Fk[0],Lk=Fk[Fk.length-1];function Rk(e){let t;try{t=mi(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>=Ik&&n<=Lk?P(n):I(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${Ik}–${Lk} tokens)`)}function zk(e,t){let n=Math.min(t??Lk,Lk),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:Fk.filter(e=>e<r).at(-1)??0,higher:Fk.find(e=>e>r&&e<=n)??0}}function Bk(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${YT} }}{{ 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:jk(`/autocompact auto`)},...Object.fromEntries(Fk.map(t=>[`${e}${t}`,{slash:jk(`/autocompact ${t}`)}]))}}}const Vk=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 }}`,Hk=`${Y}menu`,Uk=`open`,Wk=`${Y}edit`,Gk=`${Y}toolbar`,Kk=Ck(Y),qk=`${Y}commands`,Jk=Pk(`${qk}.`),Yk=`${Y}autocompact`,Xk=Bk(`${Yk}.`,Vk),Zk=e=>({kind:`segment`,name:e}),Qk=`${Y}tab`,$k=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],eA=e=>`${Qk}.${e}`,tA=e=>`${eA(e)}.toggle`,nA=e=>({variable:Qk,key:Qk,member:e}),rA=`${Y}save`,iA=`${Y}preset.save`,aA=`${Y}preset.delete`,oA=e=>`${Y}${e}`,sA=e=>`${Y}apply.${e}`,cA=e=>`${Y}reset.${e}`,lA=`${Y}themeDefault.save`,uA=`${Y}themeDefault.differs`,dA=`${Y}themeDefault.theme`,fA={when:`{{ .${uA} }}`,template:`{{ action "${lA}" (printf "⤓ default for %s" .${dA}) }} {{ swatch "${sA(`theme`)}" .${dA} }}`},pA=`${Y}resetAll`,mA=`${Hk}.toggle`,hA={variable:Hk,key:Hk,member:Uk},gA=`${Y}undo`,_A=`${Y}back`,vA=`${_A}.step`,yA=`${Y}navigation.back`,bA=_A,xA={template:`{{ if gt .${yA} 0 }}{{ action "${_A}" "◁" }}{{ else }}{{ fg (${EO}) "◁" }}{{ end }}`},SA=`${Y}redo`,CA=`${Y}doctor`,wA=`${CA}.run`,TA=e=>`${CA}.fix.${e}`,EA=(e,t)=>`${CA}.mark.${e}.${t}`,DA=e=>`${CA}.${e}`,OA={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},kA=pE(`${Y}pickers`),AA=`${Y}gear`,jA=`gear`,MA=`${AA}.toggle`,NA={variable:kA,key:kA,member:jA},PA=pE(`${Y}gearPickers`),FA=[{template:`{{ themePreview }}`}],IA={template:`{{ layoutPreview }}`},LA={preset:[IA,{when:`{{ not .preset.bundled }}`,template:`{{ action "${aA}" (printf "🚮 delete %s" .${xa.preset.effectiveVar}) }}`}],style:FA,variation:[IA],shade:[IA]},RA=(e,t)=>`${Y}list.${e}.${t}`,zA=e=>`${Y}resettable.${e}`,BA=e=>e.length===0?`false`:`(or ${e.map(e=>`.${zA(e)}`).join(` `)})`,VA={preset:`door`,theme:`look`,style:`gear`,effect:`look`,variation:`gear`,shade:`gear`,endcaps:`look`,transitions:`look`,autoWrap:`layout`,padding:`layout`,updateNotice:`config`},HA=e=>e===`gear`?VA.theme:e,UA=Object.keys(xa).map(e=>{let t=xa[e],n=gD(t.configKey),r=TE({label:t.label,domain:n},t.sessionKey,t.effectiveVar,sA(e),VA[e]===`gear`?PA:kA);return{...t,name:e,control:r,beneath:LA[e]??[]}}),WA=e=>UA.filter(t=>VA[t.name]===e),GA=e=>UA.filter(t=>HA(VA[t.name])===e),KA={theme:[rr(AA,NA,{kind:`container`,direction:`horizontal`,children:WA(`gear`).map(aj)},`drop`)]},qA=e=>WA(e).flatMap(e=>[aj(e),...KA[e.name]??[]]);new Set(UA.flatMap(e=>[e.sessionKey,e.configKey]));const JA=Ok(pA,{arm:`⟲`,confirm:`⟲ reset all?`},UA.map(e=>cA(e.name))),YA=[`unsaved`,`history.undo`,`history.redo`],XA=e=>`${Y}${e}`,ZA=XA(`unsaved`),QA=(e,t)=>({body:t,shown:`(gt .${XA(e)} 0)`}),$A=[QA(`unsaved`,`{{ action "${rA}" (printf "💾 save %d" .${ZA}) }}`),QA(`history.undo`,`{{ action "${gA}" "↶" }}`),QA(`history.redo`,`{{ action "${SA}" "↷" }}`),{body:JA.template,shown:`(or ${BA(UA.map(e=>e.name))} ${JA.armed})`}],ej={when:`{{ or ${$A.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+$A.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},tj=[{step:JA,place:`door`},{step:Jk,place:`session`}],nj=e=>e.map(e=>e.step.disarm),rj=nj(tj),ij=nj(tj.filter(e=>e.place!==`door`));function aj(e){let t=oA(e.name);return e.control.kind===`inline`?Zk(t):rr(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>Zk(RA(e.name,n)))},`drop`)}function oj(e){return e===Hk}function sj(e){let t=Zk(Hk);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[sj(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 cj(e){return lj(e)>0?e:sj(e)}function lj(e){let t=0;for(let n of fg(e))n.kind===`segment`&&oj(n.name)&&(t+=1);return t}function uj(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&oj(e.name)||e.opens!==void 0&&uj(e.opens.body,!0):e.children.some(e=>uj(e,n))}const dj={session:{direction:`vertical`,content:[Zk(Gk),{kind:`container`,direction:`horizontal`,children:[Zk(qk),Zk(Yk)]}],after:[]},look:{direction:`horizontal`,content:[],after:[Zk(lA)]},layout:{direction:`horizontal`,content:[Zk(iA),Zk(Wk)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[Zk(CA),...fk.map(e=>Zk(DA(e.name)))],after:[]}},fj=e=>({kind:`container`,direction:dj[e].direction,children:[...dj[e].content,...qA(e),...dj[e].after]});function pj(e){return e.kind===`segment`?oj(e.name)?rr(e.name,hA,hj,`above`):e:_j(e)}function mj(){return{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[Zk(bA),...qA(`door`),Zk(rA)]},{kind:`container`,direction:`horizontal`,children:$k.map(({member:e})=>rr(eA(e),nA(e),fj(e),`drop`))}]}}const hj=mj();function gj(e){let t=new Map;for(let e of fg(hj))e.kind===`segment`&&e.opens!==void 0&&t.set(e.opens.ref.key,e.opens.ref.variable);return[...t].map(([t,n])=>{let r=e.variables[n];if(r?.kind!==`state`||r.default===void 0)throw Error(`settings menu: the door folds "${t}", but "${n}" is not a state variable the menu declares with a default`);let i=`${Hk}.fold.${QT(t)}`;return e.actions[i]={set:t,to:r.default},i})}function _j(e){return{...e,children:e.children.map(e=>pj(e))}}function vj(e){let t={variables:{[Hk]:lr(Hk,Qn)},actions:{[mA]:ur(Hk,Uk),[wA]:{doctor:`run`},[Wk]:{do:[...rO]},...Kk.actions,...Jk.actions,...Xk.actions,[rA]:{save:!0},[gA]:{undo:!0},[vA]:{back:!0},[_A]:{do:[vA,...rj]},[SA]:{redo:!0},[iA]:{preset:`save`},[lA]:{themeDefault:`save`},[aA]:{preset:`delete`,name:`{{ .${xa.preset.effectiveVar} }}`}},segments:{[Hk]:{template:`{{ $door := ${sr(Hk,cr(e),cr(`✖`))} }}{{ if ${ar(hA)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`},[Gk]:{template:Kk.template},[qk]:{template:Jk.template,when:Jk.when},[Yk]:{template:Xk.template,bg:Xk.bg,when:Xk.when},[bA]:xA,[rA]:ej,[lA]:fA,[iA]:{template:`{{ action "${iA}" "+ preset" }}`},[CA]:{template:`{{ action "${wA}" "🩺 doctor" }}`},[Wk]:{template:`{{ action "${Wk}" "✎ arrange" "✎ done" }}`}}};t.variables[uA]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[dA]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[yA]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of YA)t.variables[XA(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[Qk]=lr(Qk,`session`);for(let{member:e,label:n}of $k){t.actions[tA(e)]=ur(Qk,e),t.actions[eA(e)]={do:[tA(e),...ij]};let r=BA(GA(e).map(e=>e.name)),i=`(ternary ${cr(` •`)} "" ${r})`,a=e=>`(print ${cr(e)} ${i})`;t.segments[eA(e)]={template:`{{ ${sr(eA(e),a(n),a(`▾ ${n}`))} }}`}}return Object.assign(t.variables,Jk.variables,JA.variables),bj(t),yj(t),t.actions[Hk]={do:[mA,...rj,...gj(t)]},t}function yj(e){for(let t of fk){let n=_k(t.name),r=TA(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?qO:[];for(let n of i)e.actions[EA(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${EA(t.name,e)}" "${OA[e]}" }}`).join(``);e.segments[DA(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${Km}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function bj(e){for(let t of UA){Object.assign(e.actions,t.control.actions);let n=cA(t.name);e.actions[n]={reset:t.configKey},e.variables[zA(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${zA(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[oA(t.name)]={template:`${t.control.template}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[RA(t.name,r)]=n})}Object.assign(e.actions,JA.actions),e.actions[MA]=ur(kA,jA),e.segments[AA]={template:`{{ action "${MA}" "⚙" }}`}}function xj(e){let{variables:t,actions:n}=fO();Object.assign(e.variables,t),Object.assign(e.actions,n)}function Sj(e){let t=vj(e.globals.menuGlyph??`🍫`);xj(t);let n={...e.presets},r=[];for(let t of Yg(e.presets)){let{node:i}=Qg(e,t),a=pj(cj(i));r.push(a),n[t]={...Zg(e.presets,t),root:a}}let i=ZT(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const Cj=`${oE}live`,wj=[`☐ live`,`☑ live`],Tj=`${oE}done`,Ej=`${oE}cancel`,Dj=`${oE}rewind`,Oj=`${oE}changes`,kj=`(gt .${Oj} 0)`,Aj=`(or ${kj} (gt .${ZA} 0))`,jj={variable:Cj,key:Cj,member:`open`};function Mj(e){return`${oE}configuring.p${e}`}function Nj(e){return`and ${ar(sO)} (not ${ar(jj)}) (ne .${Mj(e)} "true")`}function Pj(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${eO} "${nr(e)}")`).join(` `)} false }}`}}function Fj(e,t,n){return`{{ if ${Nj(e)} }}${t}{{ else }}${n}{{ end }}`}const Ij=`{{ and ${ar(sO)} .preset.customized }}`,Lj=cE;function Rj(e){return new Map([...r_(e),...Bj(e)])}const zj=`${oE}addable`;function Bj(e){return new Map([[zj,{members:Object.keys(e.segments).filter(e=>!Lj(e)),library:{groups:XD.map(e=>({id:e,label:ZD[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function Vj(e,t,n){return n.segments[e]={template:t,when:cO,bg:gO},{kind:`segment`,name:e}}function Hj(e,t,n){let r=`${oE}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Mp}`}) (action "${r}" "✖") }}`}function Uj(e){return`{{ if ${ar(sO)} }}${e}{{ end }}`}function Wj(e,t){return e.reduce((e,t)=>`{{ if and ${ar(sO)} ${ar(t)} }}true{{ else }}${e}{{ end }}`,t)}function Gj(e){return e.flatMap(e=>[...fg(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function Kj(e,t,n){return`${aO}${e}.${t}.${n}`}function qj(e,t,n,r){let i=cg(n),a=`${oE}${e.presetIdent}`,o=oO(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=pE(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:Qn},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:eO,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=Kj(e.presetIdent,i,r),l=`${aO}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Ag(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=TE(CE(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 rr(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${SO}" }}`,ref:{variable:eO,key:eO,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const Jj=`${oE}label:`;function Yj(e){if(e.startsWith(Jj)){let t=e.slice(Jj.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function Xj(e,t,n,r){let{artifacts:i}=n,a=cg(e),o=`${Jj}${a}:${e.name}`;i.segments[o]={template:`{{ "${nr(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=Object.fromEntries(Tg.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...rr(o,r.ref,r.body,`drop`,Wj([r.ref],`{{ ${Nj(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(Tg.map(e=>[e,r.drafts[e]]))}}function Zj(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${oE}${i}.insert.${t}`,s=`${oE}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:zj,anchor:n,relation:r};let c=dE(o),l=fE(s,o,void 0),u=hE(l),d=mE(l,c);return a.variables[l]=lr(l,Qn),a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=ur(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${ar({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Mp}`}) $m }}{{ end }}`}}function Qj(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!Lj(e.name)),i=e=>Qj(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=dg(o,i);if(Lj(o.name)){n.push(s);continue}let c=cg(o),l=a===r?[Zj(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=Zj(t,u,c,`after`),f=Hj(t,u,c),p=t.segments[o.name],m=qj(t,u,o,Eg(p)),h=Uj(f),g=Uj(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>Vj(e.host,e.template,t.artifacts)),{...Xj(o,p,t,m),lead:h,trail:g},{...s,when:Fj(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},Vj(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:Wj(Gj(n),Fj(t.presetIdent,`true`,e.when))}}}function $j(e,t,n,r,i,a,o){let s=`${oE}${t}.resetLayout`,c=`${oE}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:Ij},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},eM(e,o)]}}function eM(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),eM(n,t)]}:{...e,children:[...e.children,t]}}function tM(e,t,n,r,i,a){let{node:o}=Qg(e,t),s={presetIdent:QT(t),rootKey:UD(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=Qj(o,s);return n.variables[Mj(s.presetIdent)]=Pj(s.configured),$j(c,s.presetIdent,s.rootKey,n,r,i,a)}function nM(e){let t={variables:{},actions:{},segments:{}},n=mO(`${oE}help`,wO,[sO],t);t.variables[Cj]=lr(Cj,Qn),t.actions[Cj]=ur(Cj,jj.member),t.segments[Cj]={template:or(Cj,...wj),when:cO};let r={kind:`segment`,name:Cj},i=n;t.variables[Oj]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[Tj]={do:[rA,...rO]},t.segments[Tj]={template:`{{ if ${Aj} }}{{ action "${Tj}" "✓ save" }}{{ else }}{{ action "${Tj}" "✓ done" }}{{ end }}`,when:cO},t.actions[Dj]={rewind:!0},t.actions[Ej]={do:[Dj,...rO]},t.segments[Ej]={template:`{{ action "${Ej}" "↩ cancel" }}`,when:`{{ and ${ar(sO)} ${kj} }}`};let a=[{kind:`segment`,name:Tj},{kind:`segment`,name:Ej}],o={...e.presets},s=[];for(let n of Yg(e.presets)){let c=tM(e,n,t,a,r,i);s.push(c),o[n]={...Zg(e.presets,n),root:c}}let c=ZT(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function rM(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function iM(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 aM(e,t,n){let r=ug(e,new Set(n.map(lg).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const oM=/^-?\d+$/;function sM(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 cM(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!oM.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 lM(e,t,n){return r=>r?oM.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 uM(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=>!oM.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 dM(e){return e===`config`?`set-config`:`set-state`}function fM(e,t,n){return t.kind===`int`?cM(`menu page "${e}"`):t.kind===`range`?lM(t.min,t.max,`${n} stepper "${e}"`):sM(t.allowed,`${n} "${e}"`,dM(n))}function pM(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:uM(e,n,t)}))}function mM(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 pM(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,fM(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 hM(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};mM(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=mM(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const gM=hM({},`config`,CM);function _M(e,t){return gM.register(e,t)}function vM(e){return gM.gateFor(e)}function yM(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:a_(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:[rM({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[rM({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:a_(e.insertSegmentFrom,t).members.map(t=>rM({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function bM(e,t){let n=RD(e).get(t);return n===void 0?null:String(n)}function xM(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?qD(n.persist):null;e?.scope===`preset-root`&&t.add(UD(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function SM(e){let t=Rj(e);return[...xM(e),...Object.values(e.actions).flatMap(e=>yM(e,t))]}function CM(e){return pM(SM(e),`config`)}function wM(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:DM(t.segments,TM(t.segments,e.segments??{})),root:Gg(e.root??Rg,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:DM(t.presets,EM(t.presets,e.presets??{})),themeDefaults:DM(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function TM(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 EM(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 DM(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function OM(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: ${yg.join(`, `)})`,line:J(e.source,t.split(`.`))}),null):jM(e,`${t}.cache`,n.cache)}function kM(e){return{required:!0,json:MM(),parse:(t,n,r,i)=>OM(t,n,i,e)??void 0}}const AM={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&PM(n)?{ttl:n}:RE(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${Z(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return RE(e,t,`cache.watch_file must be a path string, got ${Z(n)}`);let r=XE(`cache.watch_file`,n);return r===null?{watch_file:n}:RE(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}:RE(e,t,`cache.depends_on must be an array of variable-name strings, got ${Z(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:RE(e,t,`cache.key must be a non-empty template string, got ${Z(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:RE(e,t,`cache.never must be the literal boolean true, got ${Z(n)}`)}}};function jM(e,t,n){return zE(e,AM,t,n)}function MM(){return rD(AM)}const NM=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function PM(e){return NM.test(e)}function FM(e,t,n){if(n===void 0)return{};if(!X(n))return e.issues.push({path:t,message:`${t} must be an object, got ${ME(n)}`,line:J(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=BE(e,sN,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function IM(){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 ${ME(i)}`,line:J(e.source,t.split(`.`))});return}return i}}}function LM(){return{required:!0,json:{enum:[...xg]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!xg.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${xg.join(`, `)}, got ${JSON.stringify(i)}`,line:J(e.source,[...t.split(`.`),`field`])});return}return i}}}function RM(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return OE(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const zM={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:RE(e,t,`parse.text must be the literal boolean true, got ${Z(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?BM(e,t,n):RE(e,t,`parse.regex must be a pattern string, got ${Z(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:RE(e,t,`parse.json must be the literal boolean true, got ${Z(n)}`)}}};function BM(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return RE(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:RE(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function VM(){return{required:!1,json:rD(zM),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:J(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:zE(e,zM,`${t}.parse`,r.parse)??void 0)}}function HM(){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)=>X(r.parse)&&`json`in r.parse?UM(e,t,r.default):kE(e,t,r,`default`)}}function UM(e,t,n){if(n!==void 0)return WM(n)?n:RE(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${Z(n)}`)??void 0}function WM(e){return e!==null&&GM(e)}function GM(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(GM);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(GM)}default:return!1}}const KM={value:IM(),default:WE()},qM={path:YE(),type:QE([`string`,`number`,`boolean`]),default:RM()},JM={name:YE(),default:WE()},YM={path:ZE(),readMode:QE([`whole`,`first-line`]),parse:VM(),cache:kM(`file`),default:HM()},XM={command:YE(),parse:VM(),cache:kM(`shell`),default:HM()};function ZM(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const QM={template:YE(),default:WE()},$M=ZM(`a template variable recomputes whenever a variable it reads changes`),eN={layout:YE(),default:WE()},tN=ZM(`a time variable reads the instant its render is drawn at`),nN={field:LM(),default:WE()},rN=ZM(`a git variable is refreshed by the daemon's own watch on the repository`),iN={key:YE(),default:WE()},aN=`kind`;function oN(e,t,n={}){return{...VE(aN,e,t),parse:(r,i,a)=>{PE(r,n,i,a);let o=FE(r,t,i,a);return o===null?null:{kind:e,...o}}}}const sN={tag:aN,noun:`source kind`,memberNoun:`variable`,arms:{literal:oN(`literal`,KM),input:oN(`input`,qM),env:oN(`env`,JM),file:oN(`file`,YM),shell:oN(`shell`,XM),template:oN(`template`,QM,$M),time:oN(`time`,eN,tN),git:oN(`git`,nN,rN),state:oN(`state`,iN)}};function cN(){return nD(sN)}function lN(){return{type:`object`,additionalProperties:cN()}}const uN=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`}]]);function dN(e){let t=uN.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)`}}const fN=/^[A-Za-z_][A-Za-z0-9_]*$/,pN={pattern:fN.source},mN={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},hN={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`,...pN}}}]},default:mN}},gN=[`label`,`domain`,`default`],_N=[`min`,`max`,`step`,`atLeast`];function vN(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function yN(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 vN(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 vN(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?vN(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(X(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!_N.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}}:vN(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 vN(e,t,`domain must be "bool", a list of words, or { min, max }, got ${Z(n)}`)}function bN(e,t,n){if(!X(n))return vN(e,t,`${t} must be { label, domain, default }, got ${ME(n)}`);for(let r of Object.keys(n))gN.includes(r)||vN(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${gN.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||vN(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${Z(r)}`);let a=yN(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!xN(n.default)||!kg(o,n.default)?vN(e,`${t}.default`,`default must be ${Ng(o)}, got ${Z(n.default)}`):o}function xN(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const SN={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${Cg}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function CN(e){return Tg.includes(e)}function wN(){return{required:!1,json:{type:`object`,propertyNames:{...pN,not:{enum:[...Tg]}},additionalProperties:hN},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!X(i))return vN(e,a,`${a} must be an object of name → { label, domain, default }, got ${ME(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!fN.test(t)){vN(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(CN(t)){vN(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${SN[t]}`);continue}let r=bN(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const TN=sE.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function EN(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${TN})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!cE(i)?i:vN(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${sE.map(e=>`"${e}"`).join(`, `)} namespaces, got ${Z(i)}`)}}}function DN(){return{required:!1,json:{type:`object`,propertyNames:pN,additionalProperties:mN},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!X(i))return vN(e,a,`a placement's "settings" must be an object of setting name → value, got ${ME(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))xN(n)?o[t]=n:vN(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${ME(n)}`);return o}}}function ON(e){return new Set(Object.keys(e.segments).filter(e=>!cE(e)))}function kN(e,t,n){if(t===void 0)return{};if(!X(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${ME(t)}`,line:J(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=NE(e,n.has(i)?FN:PN,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function AN(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?RE(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${dN(t.slice(9))}`)??void 0:DE(e,t,r,n)??void 0}}function jN(){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 ${Z(i)}`,line:J(e.source,[...t.split(`.`),n])})}}}}function MN(){return{required:!1,json:lN(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return FM(e,`${t}.${n}`,i)}}}const NN={template:AN(),description:WE(),group:QE(YD),width:jN(),justify:QE(Pg),truncate:QE(Fg),bg:WE(),fg:WE(),when:WE(),palette:JE(),vars:MN(),settings:wN()},PN={noun:`segment key`,fields:NN},FN={noun:`segment key`,fields:{...NN,template:WE()}},IN=`#/definitions/LayoutNode`,LN={kind:`container`,direction:`vertical`,children:[]};function RN(e){return{required:!0,json:{const:e},parse:()=>e}}function zN(){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 ${Z(i)}`,line:J(e.source,[`root`])}),``)}}}function BN(){return{required:!0,json:{enum:[...og]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&og.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${og.join(`, `)} (got ${JSON.stringify(i)})`,line:J(e.source,[`root`])}),`vertical`)}}}function VN(e){return{required:!0,json:{type:`array`,items:{$ref:IN}},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 ${ME(a)}`,line:J(t.source,[`root`])}),[])}}}const HN={noun:`layout-node key`,fields:{kind:RN(`segment`),name:zN(),when:WE(),id:EN(),settings:DN()}},UN=()=>QE(cp),WN={noun:`layout-node key`,fields:{kind:RN(`container`),direction:BN(),children:VN(HE(()=>YN)),when:WE(),distribution:UN()}};function GN(){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 ${Z(i)}`,line:J(e.source,[`root`])}),``)}}}const KN={noun:`layout-node key`,fields:{seg:GN(),when:WE(),id:EN(),settings:DN()}},qN={noun:`layout-node key`,fields:{h:VN(HE(()=>YN)),when:WE(),distribution:UN()}},JN={noun:`layout-node key`,fields:{v:VN(HE(()=>YN)),when:WE(),distribution:UN()}},YN=(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:J(e.source,[`root`])}),LN):{kind:`segment`,name:n};if(!X(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 ${ME(n)}`,line:J(e.source,[`root`])}),LN;if(n.kind===`container`)return NE(e,WN,t,n)??LN;if(n.kind===`segment`)return NE(e,HN,t,n)??LN;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
150
+ `,DO=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`,OO={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function kO(e){let t=e[OO.socket]??``,n=e[OO.pane]??``;if(t===``||n===``)return null;let r=e[OO.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const AO={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:`20220319`}},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`}}},jO=e=>AO[e];function MO(e){return jO(e).glyphs.kind===`bundled`}function NO(e){return jO(e).glyphs.kind===`configured`}const PO=e=>jO(e).label,FO=[{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 IO(e,t){let n=t.codePointAt(0);return FO.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&zO(e,t)===!0)}const LO=Object.keys(AO);function RO(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function zO(e,t){let n=RO(e),r=RO(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 BO(e){for(let t of LO){let n=jO(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 VO(e){let t=LO.find(t=>jO(t).term===e);return t===void 0?null:{name:t,version:null}}function HO(e){let t=BO(e.termtype)??VO(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 UO(e){let t=e.TERM_PROGRAM,n=LO.find(e=>jO(e).program===t),r=n===void 0?VO(e.TERM):{name:n,version:jO(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 WO(e){switch(e.kind){case`known`:return PO(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function GO(e){switch(e.kind){case`known`:return PO(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function KO({name:e,version:t}){let n=jO(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=zO(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const qO=LO.filter(e=>jO(e).links!==null).map(PO).join(`, `),JO=[`drawn`,`boxes`];function YO(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const XO=OO.truecolor,ZO={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings: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`:{if(e.client.kind===`failed`)return{ok:!1,reason:`tmux could not be asked: ${e.client.reason}`};if(e.client.value===null||!e.client.value.features.includes(`RGB`)||e.hint.truecolor!==null)return{ok:!0};let n=t.env[XO];return typeof n==`string`&&n!==``?{ok:!1,reason:`${XO} is set in ${t.path} — restart Claude Code to apply`}:{ok:!1,reason:`Claude Code renders the bar in 256 colours inside tmux`,fix:{kind:`claude-settings`,path:[`env`,XO],value:`1`}}}}}},QO={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},$O={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(`
151
+ `).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return YO([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${QO[e]}`)])}}},ek="re-run `cc-candybar install`";function tk(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:// — ${ek}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${ek}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${ek}`)}const nk={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}) — ${ek}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${ek}`};case`lost`:return YO([...tk(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}`])}}},rk=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function ik(e,t){let n=WO(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?KO(e.terminal):{kind:`unknown`}}function ak({identified:e,tmuxClient:t},n){let r=GO(e),i=ik(e,n),a=WO(e)===null?rk:`${rk}, 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: ${qO}`];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 ok={name:`links`,label:`links`,takesMark:!1,probe:({askedBy:e,terminal:t,clicked:n})=>{if(e===`click`)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 YO(ak(t,n))}}},sk={name:`effectRefresh`,label:`effect refresh`,takesMark:!1,probe:({effect:e,placementEffects:t,transitions:n,claudeSettings:r})=>{let i=[...e.kind===`decided`?e.value===`none`?[]:[`the bar wears the ${e.name} effect`]:[`a globals.effect rule can give the bar an effect`],...t.map(({placement:e,effect:t})=>`${e} wears the ${t} effect`),...n?[`placements fade in and dissolve out as they come and go`]:[]];if(i.length===0)return{ok:!0};let a=i.join(` and `),{path:o,statusLine:s}=r;switch(s.kind){case`absent`:return{ok:!1,reason:`${a}, and ${o} sets no statusLine — set "refreshInterval": 1 beside the statusLine command that runs the bar`};case`not-an-object`:return{ok:!1,reason:`${a}, and ${o} sets statusLine to ${JSON.stringify(s.value)}, not a statusLine object — re-run \`cc-candybar install\` to write one`};case`present`:break}let c=s.refreshInterval;return c===1?{ok:!0}:{ok:!1,reason:c===void 0?`${a}, but Claude Code redraws it only on events`:typeof c==`number`&&c>1?`${a}, but Claude Code redraws it only every ${c} s`:`${a}, but statusLine.refreshInterval is ${JSON.stringify(c)}, not a number of seconds Claude Code accepts (its minimum is 1)`,fix:{kind:`claude-settings`,path:[`statusLine`,`refreshInterval`],value:1}}}},ck=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function lk(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return GO(e);case`bundling`:case`unread`:case`configured`:return[PO(e.name),e.version].filter(e=>e!==null).join(` `)}}function uk(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return WO(e);case`bundling`:case`unread`:return PO(e.name);case`configured`:{let t=PO(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 dk(e){let t=uk(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${ck(e.glyphs)}`}}const fk=`or set globals.charset to "ascii" to draw the bar without them`,pk=[$O,nk,ok,ZO,sk,{name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};if(t.kind===`failed`)return{ok:!1,reason:`the mark book could not be read: ${t.reason}`};let n=dk(e),r=e=>({ok:!1,reason:e,...n!==void 0&&{sighting:n}}),i=e.terminal,a=lk(i);switch(n===void 0?null:t.value.nerdFont?.[n.id]??null){case`drawn`:return{ok:!0};case`boxes`:return r(`${a} draws ${ck(e.glyphs)} as boxes — set a Nerd Font as its font, ${fk}`);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=AO[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:zO(i.version,e);if(t===!0)return{ok:!0};let n=PO(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, ${fk}`)}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, ${fk}`):n.length===0?{ok:!0}:r(`${a} draws with ${e} (${t}), which has no ${ck(n)} — set a Nerd Font as its font, ${fk}`)}}}}],mk=pk.filter(e=>e.takesMark);function hk(e){return pk.map(t=>({check:t,verdict:t.probe(e)}))}function gk(e){return pk.find(t=>t.name===e)}const _k=`${Y}doctor.`;function vk(e){let t=`${_k}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function yk(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?WO(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 bk(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=dk(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 xk(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function Sk(e){return e.flatMap(({check:e,verdict:t})=>{let n=vk(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:``},{key:n.fixable,value:qm},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:xk(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?qm:Km},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const Ck={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function wk(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(Ck).map(([t,n])=>[`${e}${t}`,n]))}}const Tk=`armed`,Ek=`disarmed`,Dk=`.armed`,Ok=e=>e.endsWith(Dk);function kk(e,t,n){let r=`${e}${Dk}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${Tk}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:Tk},[a]:{set:r,to:Ek},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:Ek}},disarm:a}}const Ak=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function jk(e){return typeof e==`string`&&Ak.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 Mk(e){let t=jk(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const Nk=[`/compact`,`/model`],Pk=`/clear`;function Fk(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=kk(`${e}clear`,{arm:Pk,confirm:`${Pk} ✓ confirm`},[n]);return{template:Nk.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${XT} }}`,actions:{...Object.fromEntries(Nk.map(e=>[t(e),{slash:Mk(e)}])),...r.actions,[n]:{slash:Mk(Pk)}},variables:r.variables,disarm:r.disarm}}const Ik=Array.from({length:10},(e,t)=>(t+1)*1e5),Lk=Ik[0],Rk=Ik[Ik.length-1];function zk(e){let t;try{t=mi(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>=Lk&&n<=Rk?P(n):I(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${Lk}–${Rk} tokens)`)}function Bk(e,t){let n=Math.min(t??Rk,Rk),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:Ik.filter(e=>e<r).at(-1)??0,higher:Ik.find(e=>e>r&&e<=n)??0}}function Vk(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${XT} }}{{ 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:Mk(`/autocompact auto`)},...Object.fromEntries(Ik.map(t=>[`${e}${t}`,{slash:Mk(`/autocompact ${t}`)}]))}}}const Hk=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 }}`,Uk=`${Y}menu`,Wk=`open`,Gk=`${Y}edit`,Kk=`${Y}toolbar`,qk=wk(Y),Jk=`${Y}commands`,Yk=Fk(`${Jk}.`),Xk=`${Y}autocompact`,Zk=Vk(`${Xk}.`,Hk),Qk=e=>({kind:`segment`,name:e}),$k=`${Y}tab`,eA=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],tA=e=>`${$k}.${e}`,nA=e=>`${tA(e)}.toggle`,rA=e=>({variable:$k,key:$k,member:e}),iA=`${Y}save`,aA=`${Y}preset.save`,oA=`${Y}preset.delete`,sA=e=>`${Y}${e}`,cA=e=>`${Y}apply.${e}`,lA=e=>`${Y}reset.${e}`,uA=`${Y}themeDefault.save`,dA=`${Y}themeDefault.differs`,fA=`${Y}themeDefault.theme`,pA={when:`{{ .${dA} }}`,template:`{{ action "${uA}" (printf "⤓ default for %s" .${fA}) }} {{ swatch "${cA(`theme`)}" .${fA} }}`},mA=`${Y}resetAll`,hA=`${Uk}.toggle`,gA={variable:Uk,key:Uk,member:Wk},_A=`${Y}undo`,vA=`${Y}back`,yA=`${vA}.step`,bA=`${Y}navigation.back`,xA=vA,SA={template:`{{ if gt .${bA} 0 }}{{ action "${vA}" "◁" }}{{ else }}{{ fg (${DO}) "◁" }}{{ end }}`},CA=`${Y}redo`,wA=`${Y}doctor`,TA=`${wA}.run`,EA=e=>`${wA}.fix.${e}`,DA=(e,t)=>`${wA}.mark.${e}.${t}`,OA=e=>`${wA}.${e}`,kA={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},AA=mE(`${Y}pickers`),jA=`${Y}gear`,MA=`gear`,NA=`${jA}.toggle`,PA={variable:AA,key:AA,member:MA},FA=mE(`${Y}gearPickers`),IA=[{template:`{{ themePreview }}`}],LA={template:`{{ layoutPreview }}`},RA={preset:[LA,{when:`{{ not .preset.bundled }}`,template:`{{ action "${oA}" (printf "🚮 delete %s" .${xa.preset.effectiveVar}) }}`}],style:IA,variation:[LA],shade:[LA]},zA=(e,t)=>`${Y}list.${e}.${t}`,BA=e=>`${Y}resettable.${e}`,VA=e=>e.length===0?`false`:`(or ${e.map(e=>`.${BA(e)}`).join(` `)})`,HA={preset:`door`,theme:`look`,style:`gear`,effect:`look`,variation:`gear`,shade:`gear`,endcaps:`look`,transitions:`look`,autoWrap:`layout`,padding:`layout`,updateNotice:`config`},UA=e=>e===`gear`?HA.theme:e,WA=Object.keys(xa).map(e=>{let t=xa[e],n=_D(t.configKey),r=EE({label:t.label,domain:n},t.sessionKey,t.effectiveVar,cA(e),HA[e]===`gear`?FA:AA);return{...t,name:e,control:r,beneath:RA[e]??[]}}),GA=e=>WA.filter(t=>HA[t.name]===e),KA=e=>WA.filter(t=>UA(HA[t.name])===e),qA={theme:[rr(jA,PA,{kind:`container`,direction:`horizontal`,children:GA(`gear`).map(oj)},`drop`)]},JA=e=>GA(e).flatMap(e=>[oj(e),...qA[e.name]??[]]);new Set(WA.flatMap(e=>[e.sessionKey,e.configKey]));const YA=kk(mA,{arm:`⟲`,confirm:`⟲ reset all?`},WA.map(e=>lA(e.name))),XA=[`unsaved`,`history.undo`,`history.redo`],ZA=e=>`${Y}${e}`,QA=ZA(`unsaved`),$A=(e,t)=>({body:t,shown:`(gt .${ZA(e)} 0)`}),ej=[$A(`unsaved`,`{{ action "${iA}" (printf "💾 save %d" .${QA}) }}`),$A(`history.undo`,`{{ action "${_A}" "↶" }}`),$A(`history.redo`,`{{ action "${CA}" "↷" }}`),{body:YA.template,shown:`(or ${VA(WA.map(e=>e.name))} ${YA.armed})`}],tj={when:`{{ or ${ej.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+ej.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},nj=[{step:YA,place:`door`},{step:Yk,place:`session`}],rj=e=>e.map(e=>e.step.disarm),ij=rj(nj),aj=rj(nj.filter(e=>e.place!==`door`));function oj(e){let t=sA(e.name);return e.control.kind===`inline`?Qk(t):rr(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>Qk(zA(e.name,n)))},`drop`)}function sj(e){return e===Uk}function cj(e){let t=Qk(Uk);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[cj(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 lj(e){return uj(e)>0?e:cj(e)}function uj(e){let t=0;for(let n of pg(e))n.kind===`segment`&&sj(n.name)&&(t+=1);return t}function dj(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&sj(e.name)||e.opens!==void 0&&dj(e.opens.body,!0):e.children.some(e=>dj(e,n))}const fj={session:{direction:`vertical`,content:[Qk(Kk),{kind:`container`,direction:`horizontal`,children:[Qk(Jk),Qk(Xk)]}],after:[]},look:{direction:`horizontal`,content:[],after:[Qk(uA)]},layout:{direction:`horizontal`,content:[Qk(aA),Qk(Gk)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[Qk(wA),...pk.map(e=>Qk(OA(e.name)))],after:[]}},pj=e=>({kind:`container`,direction:fj[e].direction,children:[...fj[e].content,...JA(e),...fj[e].after]});function mj(e){return e.kind===`segment`?sj(e.name)?rr(e.name,gA,gj,`above`):e:vj(e)}function hj(){return{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[Qk(xA),...JA(`door`),Qk(iA)]},{kind:`container`,direction:`horizontal`,children:eA.map(({member:e})=>rr(tA(e),rA(e),pj(e),`drop`))}]}}const gj=hj();function _j(e){let t=new Map;for(let e of pg(gj))e.kind===`segment`&&e.opens!==void 0&&t.set(e.opens.ref.key,e.opens.ref.variable);return[...t].map(([t,n])=>{let r=e.variables[n];if(r?.kind!==`state`||r.default===void 0)throw Error(`settings menu: the door folds "${t}", but "${n}" is not a state variable the menu declares with a default`);let i=`${Uk}.fold.${$T(t)}`;return e.actions[i]={set:t,to:r.default},i})}function vj(e){return{...e,children:e.children.map(e=>mj(e))}}function yj(e){let t={variables:{[Uk]:lr(Uk,Qn)},actions:{[hA]:ur(Uk,Wk),[TA]:{doctor:`run`},[Gk]:{do:[...iO]},...qk.actions,...Yk.actions,...Zk.actions,[iA]:{save:!0},[_A]:{undo:!0},[yA]:{back:!0},[vA]:{do:[yA,...ij]},[CA]:{redo:!0},[aA]:{preset:`save`},[uA]:{themeDefault:`save`},[oA]:{preset:`delete`,name:`{{ .${xa.preset.effectiveVar} }}`}},segments:{[Uk]:{template:`{{ $door := ${sr(Uk,cr(e),cr(`✖`))} }}{{ if ${ar(gA)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`},[Kk]:{template:qk.template},[Jk]:{template:Yk.template,when:Yk.when},[Xk]:{template:Zk.template,bg:Zk.bg,when:Zk.when},[xA]:SA,[iA]:tj,[uA]:pA,[aA]:{template:`{{ action "${aA}" "+ preset" }}`},[wA]:{template:`{{ action "${TA}" "🩺 doctor" }}`},[Gk]:{template:`{{ action "${Gk}" "✎ arrange" "✎ done" }}`}}};t.variables[dA]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[fA]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[bA]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of XA)t.variables[ZA(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[$k]=lr($k,`session`);for(let{member:e,label:n}of eA){t.actions[nA(e)]=ur($k,e),t.actions[tA(e)]={do:[nA(e),...aj]};let r=VA(KA(e).map(e=>e.name)),i=`(ternary ${cr(` •`)} "" ${r})`,a=e=>`(print ${cr(e)} ${i})`;t.segments[tA(e)]={template:`{{ ${sr(tA(e),a(n),a(`▾ ${n}`))} }}`}}return Object.assign(t.variables,Yk.variables,YA.variables),xj(t),bj(t),t.actions[Uk]={do:[hA,...ij,..._j(t)]},t}function bj(e){for(let t of pk){let n=vk(t.name),r=EA(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?JO:[];for(let n of i)e.actions[DA(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${DA(t.name,e)}" "${kA[e]}" }}`).join(``);e.segments[OA(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${Km}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function xj(e){for(let t of WA){Object.assign(e.actions,t.control.actions);let n=lA(t.name);e.actions[n]={reset:t.configKey},e.variables[BA(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${BA(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[sA(t.name)]={template:`${t.control.template}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[zA(t.name,r)]=n})}Object.assign(e.actions,YA.actions),e.actions[NA]=ur(AA,MA),e.segments[jA]={template:`{{ action "${NA}" "⚙" }}`}}function Sj(e){let{variables:t,actions:n}=pO();Object.assign(e.variables,t),Object.assign(e.actions,n)}function Cj(e){let t=yj(e.globals.menuGlyph??`🍫`);Sj(t);let n={...e.presets},r=[];for(let t of Xg(e.presets)){let{node:i}=$g(e,t),a=mj(lj(i));r.push(a),n[t]={...Qg(e.presets,t),root:a}}let i=QT(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const wj=`${sE}live`,Tj=[`☐ live`,`☑ live`],Ej=`${sE}done`,Dj=`${sE}cancel`,Oj=`${sE}rewind`,kj=`${sE}changes`,Aj=`(gt .${kj} 0)`,jj=`(or ${Aj} (gt .${QA} 0))`,Mj={variable:wj,key:wj,member:`open`};function Nj(e){return`${sE}configuring.p${e}`}function Pj(e){return`and ${ar(cO)} (not ${ar(Mj)}) (ne .${Nj(e)} "true")`}function Fj(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${tO} "${nr(e)}")`).join(` `)} false }}`}}function Ij(e,t,n){return`{{ if ${Pj(e)} }}${t}{{ else }}${n}{{ end }}`}const Lj=`{{ and ${ar(cO)} .preset.customized }}`,Rj=lE;function zj(e){return new Map([...i_(e),...Vj(e)])}const Bj=`${sE}addable`;function Vj(e){return new Map([[Bj,{members:Object.keys(e.segments).filter(e=>!Rj(e)),library:{groups:ZD.map(e=>({id:e,label:QD[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function Hj(e,t,n){return n.segments[e]={template:t,when:lO,bg:_O},{kind:`segment`,name:e}}function Uj(e,t,n){let r=`${sE}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Mp}`}) (action "${r}" "✖") }}`}function Wj(e){return`{{ if ${ar(cO)} }}${e}{{ end }}`}function Gj(e,t){return e.reduce((e,t)=>`{{ if and ${ar(cO)} ${ar(t)} }}true{{ else }}${e}{{ end }}`,t)}function Kj(e){return e.flatMap(e=>[...pg(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function qj(e,t,n){return`${oO}${e}.${t}.${n}`}function Jj(e,t,n,r){let i=lg(n),a=`${sE}${e.presetIdent}`,o=sO(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=mE(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:Qn},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:tO,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=qj(e.presetIdent,i,r),l=`${oO}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:jg(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=EE(wE(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 rr(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${CO}" }}`,ref:{variable:tO,key:tO,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const Yj=`${sE}label:`;function Xj(e){if(e.startsWith(Yj)){let t=e.slice(Yj.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function Zj(e,t,n,r){let{artifacts:i}=n,a=lg(e),o=`${Yj}${a}:${e.name}`;i.segments[o]={template:`{{ "${nr(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=Object.fromEntries(Eg.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...rr(o,r.ref,r.body,`drop`,Gj([r.ref],`{{ ${Pj(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(Eg.map(e=>[e,r.drafts[e]]))}}function Qj(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${sE}${i}.insert.${t}`,s=`${sE}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:Bj,anchor:n,relation:r};let c=fE(o),l=pE(s,o,void 0),u=gE(l),d=hE(l,c);return a.variables[l]=lr(l,Qn),a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=ur(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${ar({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Mp}`}) $m }}{{ end }}`}}function $j(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!Rj(e.name)),i=e=>$j(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=fg(o,i);if(Rj(o.name)){n.push(s);continue}let c=lg(o),l=a===r?[Qj(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=Qj(t,u,c,`after`),f=Uj(t,u,c),p=t.segments[o.name],m=Jj(t,u,o,Dg(p)),h=Wj(f),g=Wj(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>Hj(e.host,e.template,t.artifacts)),{...Zj(o,p,t,m),lead:h,trail:g},{...s,when:Ij(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},Hj(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:Gj(Kj(n),Ij(t.presetIdent,`true`,e.when))}}}function eM(e,t,n,r,i,a,o){let s=`${sE}${t}.resetLayout`,c=`${sE}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:Lj},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},tM(e,o)]}}function tM(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),tM(n,t)]}:{...e,children:[...e.children,t]}}function nM(e,t,n,r,i,a){let{node:o}=$g(e,t),s={presetIdent:$T(t),rootKey:WD(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=$j(o,s);return n.variables[Nj(s.presetIdent)]=Fj(s.configured),eM(c,s.presetIdent,s.rootKey,n,r,i,a)}function rM(e){let t={variables:{},actions:{},segments:{}},n=hO(`${sE}help`,TO,[cO],t);t.variables[wj]=lr(wj,Qn),t.actions[wj]=ur(wj,Mj.member),t.segments[wj]={template:or(wj,...Tj),when:lO};let r={kind:`segment`,name:wj},i=n;t.variables[kj]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[Ej]={do:[iA,...iO]},t.segments[Ej]={template:`{{ if ${jj} }}{{ action "${Ej}" "✓ save" }}{{ else }}{{ action "${Ej}" "✓ done" }}{{ end }}`,when:lO},t.actions[Oj]={rewind:!0},t.actions[Dj]={do:[Oj,...iO]},t.segments[Dj]={template:`{{ action "${Dj}" "↩ cancel" }}`,when:`{{ and ${ar(cO)} ${Aj} }}`};let a=[{kind:`segment`,name:Ej},{kind:`segment`,name:Dj}],o={...e.presets},s=[];for(let n of Xg(e.presets)){let c=nM(e,n,t,a,r,i);s.push(c),o[n]={...Qg(e.presets,n),root:c}}let c=QT(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function iM(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function aM(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 oM(e,t,n){let r=dg(e,new Set(n.map(ug).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const sM=/^-?\d+$/;function cM(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 lM(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!sM.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 uM(e,t,n){return r=>r?sM.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 dM(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=>!sM.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 fM(e){return e===`config`?`set-config`:`set-state`}function pM(e,t,n){return t.kind===`int`?lM(`menu page "${e}"`):t.kind===`range`?uM(t.min,t.max,`${n} stepper "${e}"`):cM(t.allowed,`${n} "${e}"`,fM(n))}function mM(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:dM(e,n,t)}))}function hM(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 mM(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,pM(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 gM(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};hM(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=hM(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const _M=gM({},`config`,wM);function vM(e,t){return _M.register(e,t)}function yM(e){return _M.gateFor(e)}function bM(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:o_(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:[iM({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[iM({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:o_(e.insertSegmentFrom,t).members.map(t=>iM({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function xM(e,t){let n=zD(e).get(t);return n===void 0?null:String(n)}function SM(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?JD(n.persist):null;e?.scope===`preset-root`&&t.add(WD(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function CM(e){let t=zj(e);return[...SM(e),...Object.values(e.actions).flatMap(e=>bM(e,t))]}function wM(e){return mM(CM(e),`config`)}function TM(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:OM(t.segments,EM(t.segments,e.segments??{})),root:Kg(e.root??zg,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:OM(t.presets,DM(t.presets,e.presets??{})),themeDefaults:OM(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function EM(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 DM(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 OM(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function kM(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: ${bg.join(`, `)})`,line:J(e.source,t.split(`.`))}),null):MM(e,`${t}.cache`,n.cache)}function AM(e){return{required:!0,json:NM(),parse:(t,n,r,i)=>kM(t,n,i,e)??void 0}}const jM={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&FM(n)?{ttl:n}:zE(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${Z(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return zE(e,t,`cache.watch_file must be a path string, got ${Z(n)}`);let r=ZE(`cache.watch_file`,n);return r===null?{watch_file:n}:zE(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}:zE(e,t,`cache.depends_on must be an array of variable-name strings, got ${Z(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:zE(e,t,`cache.key must be a non-empty template string, got ${Z(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:zE(e,t,`cache.never must be the literal boolean true, got ${Z(n)}`)}}};function MM(e,t,n){return BE(e,jM,t,n)}function NM(){return iD(jM)}const PM=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function FM(e){return PM.test(e)}function IM(e,t,n){if(n===void 0)return{};if(!X(n))return e.issues.push({path:t,message:`${t} must be an object, got ${NE(n)}`,line:J(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=VE(e,cN,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function LM(){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 ${NE(i)}`,line:J(e.source,t.split(`.`))});return}return i}}}function RM(){return{required:!0,json:{enum:[...Sg]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!Sg.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${Sg.join(`, `)}, got ${JSON.stringify(i)}`,line:J(e.source,[...t.split(`.`),`field`])});return}return i}}}function zM(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return kE(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const BM={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:zE(e,t,`parse.text must be the literal boolean true, got ${Z(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?VM(e,t,n):zE(e,t,`parse.regex must be a pattern string, got ${Z(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:zE(e,t,`parse.json must be the literal boolean true, got ${Z(n)}`)}}};function VM(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return zE(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:zE(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function HM(){return{required:!1,json:iD(BM),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:J(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:BE(e,BM,`${t}.parse`,r.parse)??void 0)}}function UM(){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)=>X(r.parse)&&`json`in r.parse?WM(e,t,r.default):AE(e,t,r,`default`)}}function WM(e,t,n){if(n!==void 0)return GM(n)?n:zE(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${Z(n)}`)??void 0}function GM(e){return e!==null&&KM(e)}function KM(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(KM);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(KM)}default:return!1}}const qM={value:LM(),default:GE()},JM={path:XE(),type:$E([`string`,`number`,`boolean`]),default:zM()},YM={name:XE(),default:GE()},XM={path:QE(),readMode:$E([`whole`,`first-line`]),parse:HM(),cache:AM(`file`),default:UM()},ZM={command:XE(),parse:HM(),cache:AM(`shell`),default:UM()};function QM(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const $M={template:XE(),default:GE()},eN=QM(`a template variable recomputes whenever a variable it reads changes`),tN={layout:XE(),default:GE()},nN=QM(`a time variable reads the instant its render is drawn at`),rN={field:RM(),default:GE()},iN=QM(`a git variable is refreshed by the daemon's own watch on the repository`),aN={key:XE(),default:GE()},oN=`kind`;function sN(e,t,n={}){return{...HE(oN,e,t),parse:(r,i,a)=>{FE(r,n,i,a);let o=IE(r,t,i,a);return o===null?null:{kind:e,...o}}}}const cN={tag:oN,noun:`source kind`,memberNoun:`variable`,arms:{literal:sN(`literal`,qM),input:sN(`input`,JM),env:sN(`env`,YM),file:sN(`file`,XM),shell:sN(`shell`,ZM),template:sN(`template`,$M,eN),time:sN(`time`,tN,nN),git:sN(`git`,rN,iN),state:sN(`state`,aN)}};function lN(){return rD(cN)}function uN(){return{type:`object`,additionalProperties:lN()}}const dN=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`}]]);function fN(e){let t=dN.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)`}}const pN=/^[A-Za-z_][A-Za-z0-9_]*$/,mN={pattern:pN.source},hN={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},gN={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`,...mN}}}]},default:hN}},_N=[`label`,`domain`,`default`],vN=[`min`,`max`,`step`,`atLeast`];function yN(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function bN(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 yN(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 yN(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?yN(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(X(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!vN.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}}:yN(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 yN(e,t,`domain must be "bool", a list of words, or { min, max }, got ${Z(n)}`)}function xN(e,t,n){if(!X(n))return yN(e,t,`${t} must be { label, domain, default }, got ${NE(n)}`);for(let r of Object.keys(n))_N.includes(r)||yN(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${_N.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||yN(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${Z(r)}`);let a=bN(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!SN(n.default)||!Ag(o,n.default)?yN(e,`${t}.default`,`default must be ${Pg(o)}, got ${Z(n.default)}`):o}function SN(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const CN={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${wg}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function wN(e){return Eg.includes(e)}function TN(){return{required:!1,json:{type:`object`,propertyNames:{...mN,not:{enum:[...Eg]}},additionalProperties:gN},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!X(i))return yN(e,a,`${a} must be an object of name → { label, domain, default }, got ${NE(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!pN.test(t)){yN(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(wN(t)){yN(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${CN[t]}`);continue}let r=xN(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const EN=cE.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function DN(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${EN})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!lE(i)?i:yN(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${cE.map(e=>`"${e}"`).join(`, `)} namespaces, got ${Z(i)}`)}}}function ON(){return{required:!1,json:{type:`object`,propertyNames:mN,additionalProperties:hN},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!X(i))return yN(e,a,`a placement's "settings" must be an object of setting name → value, got ${NE(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))SN(n)?o[t]=n:yN(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${NE(n)}`);return o}}}function kN(e){return new Set(Object.keys(e.segments).filter(e=>!lE(e)))}function AN(e,t,n){if(t===void 0)return{};if(!X(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${NE(t)}`,line:J(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=PE(e,n.has(i)?IN:FN,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function jN(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?zE(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${fN(t.slice(9))}`)??void 0:OE(e,t,r,n)??void 0}}function MN(){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 ${Z(i)}`,line:J(e.source,[...t.split(`.`),n])})}}}}function NN(){return{required:!1,json:uN(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return IM(e,`${t}.${n}`,i)}}}const PN={template:jN(),description:GE(),group:$E(XD),width:MN(),justify:$E(Fg),truncate:$E(Ig),bg:GE(),fg:GE(),when:GE(),palette:YE(),vars:NN(),settings:TN()},FN={noun:`segment key`,fields:PN},IN={noun:`segment key`,fields:{...PN,template:GE()}},LN=`#/definitions/LayoutNode`,RN={kind:`container`,direction:`vertical`,children:[]};function zN(e){return{required:!0,json:{const:e},parse:()=>e}}function BN(){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 ${Z(i)}`,line:J(e.source,[`root`])}),``)}}}function VN(){return{required:!0,json:{enum:[...sg]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&sg.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${sg.join(`, `)} (got ${JSON.stringify(i)})`,line:J(e.source,[`root`])}),`vertical`)}}}function HN(e){return{required:!0,json:{type:`array`,items:{$ref:LN}},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 ${NE(a)}`,line:J(t.source,[`root`])}),[])}}}const UN={noun:`layout-node key`,fields:{kind:zN(`segment`),name:BN(),when:GE(),id:DN(),settings:ON()}},WN=()=>$E(cp),GN={noun:`layout-node key`,fields:{kind:zN(`container`),direction:VN(),children:HN(UE(()=>XN)),when:GE(),distribution:WN()}};function KN(){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 ${Z(i)}`,line:J(e.source,[`root`])}),``)}}}const qN={noun:`layout-node key`,fields:{seg:KN(),when:GE(),id:DN(),settings:ON()}},JN={noun:`layout-node key`,fields:{h:HN(UE(()=>XN)),when:GE(),distribution:WN()}},YN={noun:`layout-node key`,fields:{v:HN(UE(()=>XN)),when:GE(),distribution:WN()}},XN=(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:J(e.source,[`root`])}),RN):{kind:`segment`,name:n};if(!X(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 ${NE(n)}`,line:J(e.source,[`root`])}),RN;if(n.kind===`container`)return PE(e,GN,t,n)??RN;if(n.kind===`segment`)return PE(e,UN,t,n)??RN;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
152
152
  Old: { kind: "cells", segments: ["seg1", "seg2"] }
153
- New: { h: ["seg1", "seg2"] }`,line:J(e.source,[`root`])}),LN;if(n.kind===`group`){let r=NE(e,nP,t,n);return r===null?LN:(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}),iP(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:J(e.source,[`root`])}),LN}if(a){let r=NE(e,KN,t,n);return r===null?LN:{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=NE(e,qN,t,n);return r===null?LN:{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=NE(e,JN,t,n);return r===null?LN:{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:J(e.source,[`root`])}),LN};function XN(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Ig.source},additionalProperties:{$ref:IN}},parse:(e,t,n,r)=>{let i=r[n];if(!X(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${ME(i)}`,line:J(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!Ig.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:J(e.source,[...t.split(`.`),n,r])});continue}a[r]=YN(e,`${t}.${n}.${r}`,o)}return a}}}const ZN={noun:`root key`,fields:{rows:XN(),when:WE(),distribution:UN()}};function QN(e,t,n){return X(n)&&`rows`in n?NE(e,ZN,t,n)??{rows:{}}:YN(e,t,n)}function $N(){return{required:!0,json:{type:`string`,pattern:Ig.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Ig.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 "${Qn}", got ${Z(i)}`,line:J(e.source,[`root`])});return}return i}}}function eP(){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 ${Z(i)}`,line:J(e.source,[`root`])});return}return i}}}}function tP(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=DE(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:J(e.source,[...t.split(`.`),n])});return}return i}}}}const nP={noun:`layout-node key`,fields:{kind:RN(`group`),name:$N(),label:tP(),open:GE(),direction:QE(og),key:eP(),bg:WE(),fg:WE(),when:WE(),distribution:UN(),children:VN(HE(()=>YN))}};function rP(e){return e.key??`groups.`+e.name}function iP(e){let t=iE+e.name;return rr(t,{variable:t,key:rP(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function aP(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function oP(e,t){uE(e,t,iE,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&aP(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}.`)&&rP(t)===rP(r)&&aP(e,t.path,`group "${t.name}" shares key "${rP(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=rP(t);if(i.has(n)||i.set(n,Qn),t.open===!0){let r=i.get(n);r!==`closed`&&aP(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=iE+e.name,r=rP(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=lr(r,i.get(r)),o[t]=ur(r,e.name),s[t]={template:or(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 sP=`menu`,cP=`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`,lP=e=>e.kind===`call`&&e.name===`dict`,uP=e=>e.kind===`literal`&&typeof e.value!=`object`,dP=e=>er(``,e,2)===void 0;function fP(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&&lP(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(lP))return t(`whose options (dict …) is not its last argument — ${cP}`);if(i!==void 0&&a===void 0&&!uP(i)&&dP(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=er(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${cP}`);let c=a===void 0?{}:Tx(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=yE(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=lE(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 "${pE(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 pP(e){let t=Py({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===sP).map(fP)}catch{return`parse-failed`}}function mP(e){let t=Py({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(sP)}catch{return!1}}function hP(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function gP(e,t){uE(e,t,aE,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))mP(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:J(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`&&mP(i)&&hP(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 fg(Ug(t.root)))typeof n.when==`string`&&mP(n.when)&&hP(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||!mP(r))continue;let n=pP(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:_P(r.apply);n!==void 0&&hP(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function _P(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(dE(e)===`closed`)return`whose apply action is named "${Qn}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function vP(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 Yg(e.presets)){let a=new Map,s=new Map;for(let c of fg(Qg(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,pP(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=cg(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||_P(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=dE(i),f=fE(u,i,l.key),p=hE(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=mE(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]=ur(f,d),n[f]=lr(f,Qn),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}const yP=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`ceiling`,`slash`,`do`];function bP(e){return e.ceiling===`set`?[`set`,e.to]:[`clear`]}function xP(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function SP(e,t){if(t===void 0)return{};if(!X(t))return Q(e,`actions`,`actions must be an object, got ${ME(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=CP(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Q(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function CP(e,t,n){if(!X(n))return Q(e,t,`${t} must be an action object, got ${ME(n)}`),null;if(`persistWhen`in n)return Q(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 r=yP.filter(e=>e in n);return r.length===1?wP[r[0]](e,t,n):(Q(e,t,`action must declare exactly one of: ${yP.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const wP={set:(e,t,n)=>iF(e,t,n,`set`,eF),persist:(e,t,n)=>iF(e,t,n,`persist`,tF),copy:TP(`copy`),open:TP(`open`),reset:EP,undo:OP(`undo`),redo:OP(`redo`),back:OP(`back`),rewind:OP(`rewind`),save:OP(`save`),preset:kP,themeDefault:AP,doctor:MP,ceiling:NP,slash:PP,do:FP};function TP(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=DE(t,n,r,e);return i===null?null:{[e]:i}}}function EP(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=IP(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 DP={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 OP(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Q(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${DP[e]}), got ${Z(r[e])}`),null)}}function kP(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Q(e,`${t}.preset`,`preset must be "save" or "delete", got ${Z(r)}`),null;if(r===`save`)return{preset:`save`};let a=DE(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function AP(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Q(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${Z(n.themeDefault)}`),null)}const jP={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function MP(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(jP,r),a=i?jP[r]:[...new Set(Object.values(jP).flat())];for(let r of Object.keys(n))a.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Q(e,`${t}.doctor`,`doctor must be ${Object.keys(jP).map(e=>`"${e}"`).join(`, `)}, got ${Z(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?pk:fk;if(typeof o!=`string`||!s.some(e=>e.name===o))return Q(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${Z(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return qO.includes(c)?{doctor:`mark`,check:o,mark:c}:(Q(e,`${t}.mark`,`doctor mark must be ${qO.map(e=>`"${e}"`).join(` or `)}, got ${Z(c)}`),null)}function NP(e,t,n){let r=n.ceiling,i=r===`clear`?[`ceiling`]:[`ceiling`,`to`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a ceiling action. Expected only: ${i.join(`, `)}`);if(r===`clear`)return{ceiling:`clear`};if(r!==`set`)return Q(e,`${t}.ceiling`,`ceiling must be "set" or "clear", got ${Z(r)}`),null;let a=n.to;return typeof a!=`string`||a.trim()===``?(Q(e,`${t}.to`,`ceiling set needs \`to\`: a memento ceiling value such as "+100_000", "400000" or "off", got ${Z(a)}`),null):{ceiling:`set`,to:a}}function PP(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=Ak(n.slash);return r.kind===`refused`?(Q(e,`${t}.slash`,r.reason),null):{slash:r.line}}function FP(e,t,n){for(let r of Object.keys(n))r!==`do`&&Q(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===``)?(Q(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 ${Z(r)}`),null):{do:r}}function IP(e,t,n,r,i,a){let o=DE(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Q(e,s,i),null):o.includes(`/`)?(Q(e,s,a(o)),null):o}const LP={set:`the SessionState key to write`,persist:`the config globals field to write`};function RP(e,t,n,r){let i=LP[r],a=IP(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 zP(e){return e===`set`?`set-state`:`set-config`}const BP={to:aF(`set`)},VP={to:aF(`persist`)},HP={from:oF(`set`)},UP={from:oF(`persist`)},WP={min:dF(),max:dF(),by:dF()},GP={int:cF()},KP={cycle:sF(`set`)},qP={cycle:sF(`persist`)},JP={removeSegment:lF(`removeSegment`)},YP={insertSegment:lF(`insertSegment`),anchor:lF(`anchor`),relation:uF()},XP={insertSegmentFrom:oF(`persist`),anchor:lF(`anchor`),relation:uF()},ZP={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},QP={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function $P(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>FE(e,t,n,r),c=$E(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?UE(s,...n):s}}const eF=[$P(`set`,BP),$P(`set`,HP),$P(`set`,WP,[ZP,QP]),$P(`set`,GP),$P(`set`,KP)],tF=[$P(`persist`,VP),$P(`persist`,UP),$P(`persist`,WP,[ZP,QP]),$P(`persist`,qP),$P(`persist`,JP),$P(`persist`,YP,[],[`insertSegment`]),$P(`persist`,XP,[],[`insertSegmentFrom`])];function nF(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 rF(e){let t=nF(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 iF(e,t,n,r,i){let a=RP(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Q(e,t,`${rF(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)||Q(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 aF(e){let t=zP(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>IP(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 oF(e){let t=zP(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===``){Q(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){Q(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===``)){Q(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){Q(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){Q(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Q(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${Z(o)}`)}}}function sF(e){let t=zP(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`)){Q(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${ME(o)}`);return}let c=o;if(c.length<2){Q(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){Q(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Q(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){Q(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function cF(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Q(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${Z(r[n])}`);return}return!0}}}function lF(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=DE(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Q(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Q(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 uF(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Q(e,`${t}.${n}`,`relation must be "before" or "after", got ${Z(i)}`);return}return i}}}function dF(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Q(e,`${t}.${n}`,`${n} must be an integer, got ${Z(i)}`);return}return i}}}function fF(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const pF={noun:`style key`,fields:{hueShift:qE(),chromaScale:qE({min:0}),lightnessScale:qE(),lightnessShift:qE()}};function mF(e,t){if(!X(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${ME(t)}`,line:J(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:J(e.source,[`styles`,r])});continue}if(Nm(r)){e.issues.push({path:`styles.${r}`,message:fF(`styles.${r}`,r,`globals.endcaps`),line:J(e.source,[`styles`,r])});continue}let t=NE(e,pF,`styles.${r}`,i);t!==null&&(n[r]={...Bs,...t})}return n}const hF={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:QN(e,`${t}.${n}`,r[n])},globals:{required:!1,json:MD(),parse:(e,t,n,r)=>r[n]===void 0?void 0:jD(e,`${t}.${n}`,r[n])}}};function gF(e,t){if(!X(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${ME(t)}`,line:J(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:J(e.source,[`presets`,r])});continue}let t=NE(e,hF,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function _F(e,t){if(t===void 0)return{};if(!X(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${ME(t)}`,line:J(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 ${Z(i)}`,line:J(e.source,[`helpers`,r])});continue}n[r]=i}return n}const vF=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 yF(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 bF(e){let t=vF.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${yF(t)}`}function xF(e){let t=vF.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${yF(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}function SF(e,t){let n=new Map;for(let e of Object.keys(t)){let t=QT(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:J(e.source,[`presets`])})}function CF(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||hm(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:Nm(i)?fF(r,i,a):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:J(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:J(e.source,[`globals`,`preset`])}),SF(e,t.presets),KF(e,t);let i=O_(t);for(let t of i.names)t!==`settings`&&!t.startsWith(EF)||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:J(e.source,[`variables`,t])});let a=(t,n,r)=>{lj(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Hk}" ${lj(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}),uj(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Hk}" 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}),o(t)&&e.issues.push({path:n,message:`${n} sets "distribution" on a container inside a bar cell — everything inside a cell wears that cell's hue and shade, so it would place nothing. Set it on the row whose children are the cells (the horizontal container) or on the root, which places the rows.`,line:r});let i=new Map;for(let e of fg(t)){if(e.kind!==`segment`)continue;let t=cg(e);i.set(t,[...i.get(t)??[],e])}for(let[t,a]of i){if(a.length<2)continue;let o=a[1].name,s=ug(o,new Set(i.keys()));e.issues.push({path:n,message:`${n} has ${a.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=!1){return e.kind===`segment`?!1:t&&e.distribution!==void 0||e.children.some(n=>o(n,t||sg[e.direction]===`cell`))}let s=(n,r)=>{for(let[a,o]of Wg(n,r)){let n=J(e.source,o.split(`.`));if(a.when!==void 0&&(RF(e,`${o}.when`,a.when,i,{line:n}),LF(e,`${o}.when`,a.when,n)),a.kind===`segment`){if(oj(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${Hk}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${Hk}"`,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${dN(a.name)}`,line:n}),PF(e,t,a,o,n)}}};n.root!==void 0&&s(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&s(t.root,`presets.${e}.root`);let c=new Map([[`root`,Hg(t.root)]]);for(let e of Yg(t.presets)){let{node:n,path:r}=Qg(t,e);c.set(r,n)}for(let[t,n]of c)a(n,t,J(e.source,t.split(`.`)));GF(e,t,i,()=>!0)}const wF=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function TF(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=J(e.source,[`actions`,n,r]);if(!Yg(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Yg(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(`, `)})${dN(i)}`,line:c})},p=new Set(lg(Qg(t,a).node)),m=(r,i)=>{!uN.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${dN(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 EF=`settings.`;function DF(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>EF+e)])}}function OF(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:J(e.source,[`segments`,t,`settings`,n])})},a=jF(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of Og(n,AF(n)))i(e,`the defaults do not stand together: ${t}`)}function kF(e){return jF(e).length>0||Og(e,AF(e)).length>0}function AF(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function jF(e){let t=t=>Dg(MF(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||Dg(MF(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${NF(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 MF(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function NF(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&Dg(n)!==void 0).map(([e])=>e)}function PF(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=Eg(a),s=`${r}: placement "${cg(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(`, `)})`:kg(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?om(a):``}, but it must be ${Ng(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])=>kg(o[e],t))||kF(o)))for(let{message:t}of Og(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function FF(e,t,n,r,i){n.kind===`template`&&RF(e,`${t}.template`,n.template,r,{segCtx:i}),bg(n)&&`key`in n.cache&&RF(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function IF(e,t,n,r,i){if(!(!bg(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:J(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function LF(e,t,n,r){try{QD.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function RF(e,t,n,r,i){for(let[a,o]of b_(n,r.helpers)){if(D_(a,r))continue;if(a.startsWith(EF)){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??J(e.source,t.split(`.`))});continue}if(o!==null){zF(e,o,`Template references unknown variable ".${a}"${xF(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&D_(n,r)?` (segment-local vars are namespaced — write ".${n}")`:xF(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??J(e.source,t.split(`.`))})}}function zF(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:J(e.source,[`helpers`,t])})}function BF(e,t,n,r,i){let a=n.set,o=gD(xa[r].configKey),s=`${a} takes ${SE(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:J(e.source,[`actions`,t,`min`])});return}let c=UF(n,i);if(c===HF){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:J(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!xE(o,e.value,i));if(l.length!==0){if(a===xa.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>Nm(e.value)))){let r=xa.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:fF(`actions.${t}.to`,n.to,`set: "${r}", to`),line:J(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:J(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<=VF?r.join(`, `):`${r.slice(0,VF).join(`, `)} and ${r.length-VF} 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:J(e.source,[`actions`,t,n])})}}}const VF=3,HF=Symbol(`any integer`);function UF(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?a_(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)}]:HF}function WF(e,t){return Object.entries(e).filter(([e])=>t(e))}function GF(e,t,n,r){let i=Rj(t),a=i_(i);for(let[n,o]of WF(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 ${s_(r,i)}`,line:J(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;wa.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:J(e.source,[`actions`,n,`set`])});let s=Oa.get(o.set);s!==void 0&&BF(e,n,o,s,i)}for(let[n,i]of WF(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&&xP(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:J(e.source,[`actions`,n,`do`])})});for(let[n,i]of WF(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=qD(r);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a config globals field (have: ${ID().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`,line:J(e.source,[`actions`,n,a])});continue}let s=wF.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:J(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){TF(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Yg(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: ${Yg(t.presets).join(`, `)})`,line:J(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${om(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:J(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(`, `)})${dN(o.segment)}`,line:J(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:J(e.source,[`actions`,n,a])})}}for(let[i,a]of WF(t.variables,r)){FF(e,`variables.${i}`,a,n);let t=bF(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:J(e.source,[`variables`,i])})}for(let[i,a]of WF(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))FF(e,`segments.${i}.vars.${t}`,r,n,i);let r=Eg(a);OF(e,i,r);let o=DF(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];if(typeof s==`string`){RF(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r});for(let{name:r,site:a,via:o}of w_(s,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,r))continue;let s=a===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(o!==null){zF(e,o,`Template references unknown action "${r}"${s}`);continue}e.issues.push({path:`segments.${i}.${n}`,message:`${n} references unknown action "${r}"${s}`,line:J(e.source,[`segments`,i,n])})}}}}for(let[i,a]of WF(t.variables,r))IF(e,`variables.${i}`,a,n);for(let[i,a]of WF(t.segments,r))if(a.vars)for(let[t,r]of Object.entries(a.vars))IF(e,`segments.${i}.vars.${t}`,r,n,i)}function KF(e,t){let n=new Set;for(let r of Yg(t.presets)){let i=$g(t,r),a=[{},t.editGlobals];for(let o of a){let a=o.charset??i.charset??`unicode`,s=o.default_separator??i.default_separator;if(a!==`ascii`||Im(s??``))continue;let c=o.default_separator===void 0?Zg(t.presets,r).globals?.default_separator===void 0?[`globals`]:[`presets`,r,`globals`]:[`editGlobals`],l=[...c,`default_separator`].join(`.`);n.has(l)||(n.add(l),e.issues.push({path:l,message:`${l} ${JSON.stringify(s)} is not ASCII, but charset is "ascii" — under ascii a joiner draws only ASCII; write an ASCII separator or set charset: "unicode"`,line:J(e.source,[...c,`default_separator`])}))}}}function qF(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=JF(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:J(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function JF(e){let t=new Set(Object.keys(e.variables)),n=new Map;for(let t of Object.keys(e.variables))n.set(t,{declarationPath:`variables.${t}`,linePathParts:[`variables`,t]});for(let[r,i]of Object.entries(e.segments))if(i.vars)for(let e of Object.keys(i.vars)){let i=`${r}.${e}`;t.add(i),n.set(i,{declarationPath:`segments.${r}.vars.${e}`,linePathParts:[`segments`,r,`vars`,e]})}let r=new Map;for(let e of t)r.set(e,new Set);let i=(n,i)=>{for(let a of b_(i,e.helpers).keys()){if(t.has(a)){r.get(n).add(a);continue}let e=a.split(`.`)[0];e!==a&&t.has(e)&&r.get(n).add(e)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),bg(n)&&(`key`in n.cache&&i(e,n.cache.key),`depends_on`in n.cache))for(let i of n.cache.depends_on)t.has(i)&&r.get(e).add(i)};for(let[t,n]of Object.entries(e.variables))a(t,n);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))a(`${t}.${e}`,r);return{graph:r,nodeInfo:n}}function YF(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?h.homedir()+e.slice(1):e}function XF(e,t){return l.resolve(e,YF(t))}function ZF(e,t){return typeof t==`string`&&t!==``?XF(e,t):void 0}function QF(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const $F=new Set([`data`,`segments`,`helpers`,`actions`]),eI=`plugin.json5`,tI=/^[a-z][a-z0-9_]*$/;function nI(e){let t=l.basename(l.dirname(e));return tI.test(t)?t:void 0}const rI=`plugins.`;function iI(e){return`${rI}${e}.data`}function aI(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:oI(e)}}}function oI(e){return e instanceof $T?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 sI(e,t){return e.map(e=>XF(l.dirname(t),e))}function cI(e,t,n,i){let a=new Map;return e.reduce((e,n)=>{let o=nI(n),s=(t,r)=>{let i=new Map(e.rendering);return o!==void 0&&r!==e.config&&i.delete(o),{...e,config:r,rendering:i,dropped:[...e.dropped,{path:n,plugin:o,reason:t}]}};if(l.basename(n)!==`plugin.json5`){let t=`a plugin is a folder holding its ${eI}, and the folder's name is the plugin's: move this file to <dir>/<name>/${eI} and list that`;return s(t,o===void 0?e.config:dI(uI(e.config,o),o,{path:n,plugin:o,reason:t}))}if(o===void 0)return s(`its folder "${l.basename(l.dirname(n))}" is not a plugin name (one matching ${tI}: it prefixes every name the plugin declares)`,e.config);let c=a.get(o);if(c!==void 0)return s(`plugin "${o}" is already listed, from ${c}`,e.config);a.set(o,n);let u=uI(e.config,o),d=aI(()=>{let a=r.readFileSync(n,`utf-8`),s=wM(_I(n,o,{source:a,json:vr.default.parse(a)},t),u);return i(s,o,u!==e.config),s});if(d.ok)return{...e,config:d.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[o,n]])};let f={path:n,plugin:o,reason:d.reason};return s(d.reason,dI(u,o,f))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function lI(e){let t=`${rI}${e}.`;return e=>e.startsWith(t)}function uI(e,t){let n=lI(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 dI(e,t,n){return{...e,variables:{...e.variables,[iI(t)]:{kind:`dropped`,reason:QF(n),definition:n.path}}}}function fI(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function pI(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments)].map(fI)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:QF(e)}));return t=>{let i=fI(t);if(i===void 0)return[];let a=e.config.variables[iI(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function mI(e,t){let n=Yg(e.presets).flatMap(t=>[...fg(Qg(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,hI(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=fI(t),r=n===void 0?void 0:e.variables[iI(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=>w_(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...E_(t,e.helpers)]),e.helpers),f=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition)]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${iI(fI(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:f}}function hI(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,gI(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function gI(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 _I(e,t,{source:n,json:r},{checkout:i}){let a=[],o=()=>{throw new $T(e,a)};if(!X(r))return a.push({path:``,message:`a plugin definition must be an object, got ${ME(r)}`}),o();for(let e of Object.keys(r))$F.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: ${[...$F].join(`, `)}`});let s=CI(r.data,e,i,a);if(X(r.segments)||a.push({path:`segments`,message:`"segments" must be an object naming the plugin's segments`}),a.length>0||s===void 0)return o();let c={source:n,issues:a,allowedPalettes:new Set(lm()),groups:[]},l=FM(c,`data`,{[iI(t)]:{kind:`file`,path:s,parse:{json:!0},cache:{watch_file:s},default:{}}});for(let[e,t]of Object.entries(r.segments))if(!(!X(t)||!X(t.vars)))for(let[n,r]of Object.entries(t.vars)){let t=X(r)?r.kind:void 0;typeof t!=`string`||t===`state`||a.push({path:`segments.${e}.vars.${n}`,message:`a plugin segment's vars may declare only state variables (kind: "state"), never a source such as ${JSON.stringify(t)}: a plugin's only source is its data file`})}let u={variables:l,segments:yI(t,xI(t,kN(c,r.segments,new Set))),helpers:yI(t,_F(c,r.helpers)),actions:yI(t,SI(t,SP(c,r.actions)))};for(let[e,t]of vI(u))try{QD.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),u}function*vI(e){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[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))`copy`in n&&(yield[`actions.${t}.copy`,n.copy]),`open`in n&&(yield[`actions.${t}.open`,n.open]),`preset`in n&&n.preset===`delete`&&(yield[`actions.${t}.name`,n.name])}function yI(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${rI}${e}.${t}`,n]))}function bI(e,t){return`${rI}${e}.${t}`}function xI(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,n.kind===`state`?{...n,key:bI(e,n.key)}:n]))}]))}function SI(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:bI(e,n.set)}:n]))}function CI(e,t,n,r){if(typeof e==`string`&&e!==``)return XF(l.dirname(t),e);if(X(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(l.isAbsolute(t)||t.startsWith(`~`)||l.normalize(t).split(l.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 l.resolve(n.root,t)}if(X(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 wI(e){let t=[...[...(process.env.XDG_DATA_DIRS||DI()).split(`:`).filter(e=>e!==``)].reverse().map(e=>l.join(e,`cc-candybar`,`plugins`)),TI(),...e===null?[]:[l.join(e,EI)]];return t.filter((e,n)=>t.lastIndexOf(e)===n)}function TI(){let e=process.env.XDG_DATA_HOME||l.join(h.homedir(),`.local`,`share`);return l.join(e,`cc-candybar`,`plugins`)}const EI=l.join(`.cc-candybar`,`plugins`);function DI(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${l.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function OI(e){let t=wI(e),n=new Map,r=[],i=[];for(let e of t){let t=kI(e);if(`error`in t){r.push(t);continue}for(let r of t.folders)n.delete(r),n.set(r,l.join(e,r,eI));for(let n of t.files)i.push({path:l.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${eI}: move this file to ${l.join(e,`<name>`,eI)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function kI(e){try{let t=r.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()||AI(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 AI(e,t){if(!t.isSymbolicLink())return!1;try{return r.statSync(l.join(e,t.name)).isDirectory()}catch{return!0}}const jI=[`json5`,`json`];function MI(e){try{return r.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function NI(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?jI.map(t=>l.join(e,`.cc-candybar.${t}`)):[],...jI.map(e=>l.join(r,`.cc-candybar.${e}`)),...jI.map(e=>`${PI()}.${e}`)])]}function PI(){let e=process.env.XDG_CONFIG_HOME??l.join(h.homedir(),`.config`);return l.join(e,`cc-candybar`,`config`)}function FI(e,t,n){let i=[],a=new Map;for(let o of NI(e,t,n)){let e=MI(o);if(e===`absent`)continue;if(e!==`present`){i.push(e);continue}let t=l.join(r.realpathSync(l.dirname(o)),l.basename(o).replace(/\.(json5|json)$/,``));a.has(t)||a.set(t,o)}let o=[...a.values()].reverse();if(n===void 0)return{kind:`chain`,layers:o,home:II(o),unchecked:i};let[s]=i,c=n;return o.length>0?{kind:`chain`,layers:o,home:c,unchecked:i}:s===void 0?{kind:`missing`,path:n,home:c}:{kind:`unreadable`,...s,home:c}}function II(e){let t=PI();return e.find(e=>jI.some(n=>e===`${t}.${n}`))??`${t}.${jI[0]}`}function LI(e,t,n){let r=FI(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 RI(e){return zI(e).join(`
154
- `)||null}function zI(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 BI(e,t){let n=NI(e,t).filter(e=>MI(e)===`present`),r=new Map;for(let e of n){let t=l.dirname(e),n=l.basename(e).replace(/\.(json5|json)$/,``),i=l.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 VI(e,t,n,i){return e===null?{...ZI,config:wM(ZI.raw,t)}:UI(e,r.readFileSync(e,`utf-8`),t,n,i)}const HI={projectDir:null,checkout:null,beneath:{dropped:[],rendering:new Map}};function UI(e,t,n,r,i){let a=eL(e,t,i,(t,a)=>{let o=cI(sI(t,e),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>YI(t,n,r,e,i)),s=pI(o,r.beneath.dropped);return{inherited:new Set([...ON(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=mI(wM(a.raw,o.config),s);return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(QF)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const WI=new WeakMap;function GI(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e,qI(e)])]),a=WI.get(n)??new Map;WI.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=cI(e,t,{config:n,rendering:new Map},(e,t,n)=>YI(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function KI(e,t,n){return cI(e,{projectDir:null,checkout:n},{config:t,rendering:new Map},(e,t,n)=>YI(e,t,n,`<plugin install>`,void 0)).dropped}function qI(e){try{let t=r.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function JI(e,t,n,i,a=e=>r.readFileSync(e,`utf-8`),o){let s={projectDir:i.projectDir,checkout:i.cwd===null?null:Fw(i.cwd)},c=OI(s.projectDir),l=GI(c.definitions,s,t,o),u={...l,dropped:[...l.dropped,...c.strays]};n.warned(c.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let d=u.config,f=[];for(let t of e){n.entered(t);let e=f.at(-1)?.plugins,r=UI(t,a(t),f.at(-1)?.config??d,{...s,beneath:{dropped:[...u.dropped,...f.flatMap(e=>e.plugins.dropped)],rendering:e?.rendering??u.rendering}},o);n.warned(r.warnings),f.push({...r,path:t})}let p=new Set(f.flatMap(e=>[...e.plugins.reached])),m=e=>p.has(e.path),h=u.dropped.filter(m),g=u.dropped.filter(e=>!m(e));n.warned(h.map(QF));let _={checkout:s.checkout,roots:c.roots,loaded:u.loaded,dropped:h,unreached:g,reached:p,rendering:f.at(-1)?.plugins.rendering??u.rendering},v=f.at(-1);if(v===void 0)return{layers:f,base:d,installed:_,config:QI(VI(null,d,HI),`<default>`,o)};try{return{layers:f,base:d,installed:_,config:QI(v,v.path,o)}}catch(e){for(let e of f.slice(0,-1))n.entered(e.path),QI(e,e.path,o);throw n.entered(v.path),e}}function YI(e,t,n,r,i){if(n){QI(XI(e),r,i);return}let a=lI(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[]};if(GF(s,e,O_(e),a),qF(s,e,a),o.length>0)throw new $T(r,o)}function XI(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const ZI={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function QI({config:e,raw:t,source:n},r=`<config>`,i=new Set(lm())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(CF(o,e,t),qF(o,e),a.length>0)throw new $T(r,a);let s=vP(e,a);if(a.length>0)throw new $T(r,a);return nM(Sj(s))}function $I(e,t,n=new Set(lm()),r=tL){return eL(e,t,n,()=>({inherited:r,layer:null})).raw}function eL(e,t,n,r){let i=nL(e,t),a=nE(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(lm()),groups:[]};if(!X(i))throw new $T(e,[{path:``,message:`Config root must be an object, got ${ME(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:aL({...c,issues:[]},i.plugins)??[],X(i.segments)?Object.keys(i.segments):[]),d=rL(c,i,l);if(s.length>0)throw new $T(e,s,o);return{raw:d,warnings:o,layer:u}}const tL=new Set;function nL(e,t){try{return vr.default.parse(t)}catch(t){let n=t;throw new $T(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function rL(e,t,n){for(let n of Object.keys(t))iL.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...iL].join(`, `)}`,line:J(e.source,[n])});let r={};return t.globals!==void 0&&(r.globals=AD(e,`globals`,t.globals)),t.variables!==void 0&&(r.variables=FM(e,`variables`,t.variables)),t.segments!==void 0&&(r.segments=kN(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.
153
+ New: { h: ["seg1", "seg2"] }`,line:J(e.source,[`root`])}),RN;if(n.kind===`group`){let r=PE(e,rP,t,n);return r===null?RN:(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}),aP(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:J(e.source,[`root`])}),RN}if(a){let r=PE(e,qN,t,n);return r===null?RN:{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=PE(e,JN,t,n);return r===null?RN:{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=PE(e,YN,t,n);return r===null?RN:{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:J(e.source,[`root`])}),RN};function ZN(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Lg.source},additionalProperties:{$ref:LN}},parse:(e,t,n,r)=>{let i=r[n];if(!X(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${NE(i)}`,line:J(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!Lg.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:J(e.source,[...t.split(`.`),n,r])});continue}a[r]=XN(e,`${t}.${n}.${r}`,o)}return a}}}const QN={noun:`root key`,fields:{rows:ZN(),when:GE(),distribution:WN()}};function $N(e,t,n){return X(n)&&`rows`in n?PE(e,QN,t,n)??{rows:{}}:XN(e,t,n)}function eP(){return{required:!0,json:{type:`string`,pattern:Lg.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Lg.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 "${Qn}", got ${Z(i)}`,line:J(e.source,[`root`])});return}return i}}}function tP(){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 ${Z(i)}`,line:J(e.source,[`root`])});return}return i}}}}function nP(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=OE(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:J(e.source,[...t.split(`.`),n])});return}return i}}}}const rP={noun:`layout-node key`,fields:{kind:zN(`group`),name:eP(),label:nP(),open:KE(),direction:$E(sg),key:tP(),bg:GE(),fg:GE(),when:GE(),distribution:WN(),children:HN(UE(()=>XN))}};function iP(e){return e.key??`groups.`+e.name}function aP(e){let t=aE+e.name;return rr(t,{variable:t,key:iP(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function oP(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function sP(e,t){dE(e,t,aE,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&oP(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}.`)&&iP(t)===iP(r)&&oP(e,t.path,`group "${t.name}" shares key "${iP(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=iP(t);if(i.has(n)||i.set(n,Qn),t.open===!0){let r=i.get(n);r!==`closed`&&oP(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=aE+e.name,r=iP(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=lr(r,i.get(r)),o[t]=ur(r,e.name),s[t]={template:or(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 cP=`menu`,lP=`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`,uP=e=>e.kind===`call`&&e.name===`dict`,dP=e=>e.kind===`literal`&&typeof e.value!=`object`,fP=e=>er(``,e,2)===void 0;function pP(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&&uP(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(uP))return t(`whose options (dict …) is not its last argument — ${lP}`);if(i!==void 0&&a===void 0&&!dP(i)&&fP(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=er(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${lP}`);let c=a===void 0?{}:Ex(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=bE(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=uE(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 "${mE(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 mP(e){let t=Fy({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===cP).map(pP)}catch{return`parse-failed`}}function hP(e){let t=Fy({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(cP)}catch{return!1}}function gP(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,[`root`])})}function _P(e,t){dE(e,t,oE,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))hP(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:J(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`&&hP(i)&&gP(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 pg(Wg(t.root)))typeof n.when==`string`&&hP(n.when)&&gP(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||!hP(r))continue;let n=mP(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:vP(r.apply);n!==void 0&&gP(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function vP(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(fE(e)===`closed`)return`whose apply action is named "${Qn}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function yP(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 Xg(e.presets)){let a=new Map,s=new Map;for(let c of pg($g(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,mP(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=lg(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||vP(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=fE(i),f=pE(u,i,l.key),p=gE(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=hE(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]=ur(f,d),n[f]=lr(f,Qn),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}const bP=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`ceiling`,`slash`,`do`];function xP(e){return e.ceiling===`set`?[`set`,e.to]:[`clear`]}function SP(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function CP(e,t){if(t===void 0)return{};if(!X(t))return Q(e,`actions`,`actions must be an object, got ${NE(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=wP(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Q(e,t,n){e.issues.push({path:t,message:n,line:J(e.source,t.split(`.`))})}function wP(e,t,n){if(!X(n))return Q(e,t,`${t} must be an action object, got ${NE(n)}`),null;if(`persistWhen`in n)return Q(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 r=bP.filter(e=>e in n);return r.length===1?TP[r[0]](e,t,n):(Q(e,t,`action must declare exactly one of: ${bP.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const TP={set:(e,t,n)=>aF(e,t,n,`set`,tF),persist:(e,t,n)=>aF(e,t,n,`persist`,nF),copy:EP(`copy`),open:EP(`open`),reset:DP,undo:kP(`undo`),redo:kP(`redo`),back:kP(`back`),rewind:kP(`rewind`),save:kP(`save`),preset:AP,themeDefault:jP,doctor:NP,ceiling:PP,slash:FP,do:IP};function EP(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=OE(t,n,r,e);return i===null?null:{[e]:i}}}function DP(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=LP(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 OP={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 kP(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Q(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Q(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${OP[e]}), got ${Z(r[e])}`),null)}}function AP(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Q(e,`${t}.preset`,`preset must be "save" or "delete", got ${Z(r)}`),null;if(r===`save`)return{preset:`save`};let a=OE(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function jP(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Q(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${Z(n.themeDefault)}`),null)}const MP={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function NP(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(MP,r),a=i?MP[r]:[...new Set(Object.values(MP).flat())];for(let r of Object.keys(n))a.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Q(e,`${t}.doctor`,`doctor must be ${Object.keys(MP).map(e=>`"${e}"`).join(`, `)}, got ${Z(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?mk:pk;if(typeof o!=`string`||!s.some(e=>e.name===o))return Q(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${Z(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return JO.includes(c)?{doctor:`mark`,check:o,mark:c}:(Q(e,`${t}.mark`,`doctor mark must be ${JO.map(e=>`"${e}"`).join(` or `)}, got ${Z(c)}`),null)}function PP(e,t,n){let r=n.ceiling,i=r===`clear`?[`ceiling`]:[`ceiling`,`to`];for(let r of Object.keys(n))i.includes(r)||Q(e,`${t}.${r}`,`Unknown key "${r}" on a ceiling action. Expected only: ${i.join(`, `)}`);if(r===`clear`)return{ceiling:`clear`};if(r!==`set`)return Q(e,`${t}.ceiling`,`ceiling must be "set" or "clear", got ${Z(r)}`),null;let a=n.to;return typeof a!=`string`||a.trim()===``?(Q(e,`${t}.to`,`ceiling set needs \`to\`: a memento ceiling value such as "+100_000", "400000" or "off", got ${Z(a)}`),null):{ceiling:`set`,to:a}}function FP(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Q(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=jk(n.slash);return r.kind===`refused`?(Q(e,`${t}.slash`,r.reason),null):{slash:r.line}}function IP(e,t,n){for(let r of Object.keys(n))r!==`do`&&Q(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===``)?(Q(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 ${Z(r)}`),null):{do:r}}function LP(e,t,n,r,i,a){let o=OE(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Q(e,s,i),null):o.includes(`/`)?(Q(e,s,a(o)),null):o}const RP={set:`the SessionState key to write`,persist:`the config globals field to write`};function zP(e,t,n,r){let i=RP[r],a=LP(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 BP(e){return e===`set`?`set-state`:`set-config`}const VP={to:oF(`set`)},HP={to:oF(`persist`)},UP={from:sF(`set`)},WP={from:sF(`persist`)},GP={min:fF(),max:fF(),by:fF()},KP={int:lF()},qP={cycle:cF(`set`)},JP={cycle:cF(`persist`)},YP={removeSegment:uF(`removeSegment`)},XP={insertSegment:uF(`insertSegment`),anchor:uF(`anchor`),relation:dF()},ZP={insertSegmentFrom:sF(`persist`),anchor:uF(`anchor`),relation:dF()},QP={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},$P={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function eF(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>IE(e,t,n,r),c=eD(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?WE(s,...n):s}}const tF=[eF(`set`,VP),eF(`set`,UP),eF(`set`,GP,[QP,$P]),eF(`set`,KP),eF(`set`,qP)],nF=[eF(`persist`,HP),eF(`persist`,WP),eF(`persist`,GP,[QP,$P]),eF(`persist`,JP),eF(`persist`,YP),eF(`persist`,XP,[],[`insertSegment`]),eF(`persist`,ZP,[],[`insertSegmentFrom`])];function rF(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 iF(e){let t=rF(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 aF(e,t,n,r,i){let a=zP(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Q(e,t,`${iF(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)||Q(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 oF(e){let t=BP(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>LP(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 sF(e){let t=BP(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===``){Q(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){Q(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===``)){Q(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){Q(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){Q(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Q(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${Z(o)}`)}}}function cF(e){let t=BP(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`)){Q(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${NE(o)}`);return}let c=o;if(c.length<2){Q(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){Q(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Q(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){Q(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function lF(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Q(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${Z(r[n])}`);return}return!0}}}function uF(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=OE(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Q(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Q(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 dF(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Q(e,`${t}.${n}`,`relation must be "before" or "after", got ${Z(i)}`);return}return i}}}function fF(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Q(e,`${t}.${n}`,`${n} must be an integer, got ${Z(i)}`);return}return i}}}function pF(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const mF={noun:`style key`,fields:{hueShift:JE(),chromaScale:JE({min:0}),lightnessScale:JE(),lightnessShift:JE()}};function hF(e,t){if(!X(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${NE(t)}`,line:J(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:J(e.source,[`styles`,r])});continue}if(Nm(r)){e.issues.push({path:`styles.${r}`,message:pF(`styles.${r}`,r,`globals.endcaps`),line:J(e.source,[`styles`,r])});continue}let t=PE(e,mF,`styles.${r}`,i);t!==null&&(n[r]={...Bs,...t})}return n}const gF={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:$N(e,`${t}.${n}`,r[n])},globals:{required:!1,json:ND(),parse:(e,t,n,r)=>r[n]===void 0?void 0:MD(e,`${t}.${n}`,r[n])}}};function _F(e,t){if(!X(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${NE(t)}`,line:J(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:J(e.source,[`presets`,r])});continue}let t=PE(e,gF,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function vF(e,t){if(t===void 0)return{};if(!X(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${NE(t)}`,line:J(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 ${Z(i)}`,line:J(e.source,[`helpers`,r])});continue}n[r]=i}return n}const yF=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 bF(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 xF(e){let t=yF.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${bF(t)}`}function SF(e){let t=yF.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${bF(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}function CF(e,t){let n=new Map;for(let e of Object.keys(t)){let t=$T(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:J(e.source,[`presets`])})}function wF(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||hm(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:Nm(i)?pF(r,i,a):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:J(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:J(e.source,[`globals`,`preset`])}),CF(e,t.presets),qF(e,t);let i=k_(t);for(let t of i.names)t!==`settings`&&!t.startsWith(DF)||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:J(e.source,[`variables`,t])});let a=(t,n,r)=>{uj(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Uk}" ${uj(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}),dj(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Uk}" 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}),o(t)&&e.issues.push({path:n,message:`${n} sets "distribution" on a container inside a bar cell — everything inside a cell wears that cell's hue and shade, so it would place nothing. Set it on the row whose children are the cells (the horizontal container) or on the root, which places the rows.`,line:r});let i=new Map;for(let e of pg(t)){if(e.kind!==`segment`)continue;let t=lg(e);i.set(t,[...i.get(t)??[],e])}for(let[t,a]of i){if(a.length<2)continue;let o=a[1].name,s=dg(o,new Set(i.keys()));e.issues.push({path:n,message:`${n} has ${a.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=!1){return e.kind===`segment`?!1:t&&e.distribution!==void 0||e.children.some(n=>o(n,t||cg[e.direction]===`cell`))}let s=(n,r)=>{for(let[a,o]of Gg(n,r)){let n=J(e.source,o.split(`.`));if(a.when!==void 0&&(zF(e,`${o}.when`,a.when,i,{line:n}),RF(e,`${o}.when`,a.when,n)),a.kind===`segment`){if(sj(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${Uk}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${Uk}"`,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${fN(a.name)}`,line:n}),FF(e,t,a,o,n)}}};n.root!==void 0&&s(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&s(t.root,`presets.${e}.root`);let c=new Map([[`root`,Ug(t.root)]]);for(let e of Xg(t.presets)){let{node:n,path:r}=$g(t,e);c.set(r,n)}for(let[t,n]of c)a(n,t,J(e.source,t.split(`.`)));KF(e,t,i,()=>!0)}const TF=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function EF(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=J(e.source,[`actions`,n,r]);if(!Xg(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Xg(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(`, `)})${fN(i)}`,line:c})},p=new Set(ug($g(t,a).node)),m=(r,i)=>{!dN.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${fN(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 DF=`settings.`;function OF(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>DF+e)])}}function kF(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:J(e.source,[`segments`,t,`settings`,n])})},a=MF(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of kg(n,jF(n)))i(e,`the defaults do not stand together: ${t}`)}function AF(e){return MF(e).length>0||kg(e,jF(e)).length>0}function jF(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function MF(e){let t=t=>Og(NF(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||Og(NF(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${PF(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 NF(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function PF(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&Og(n)!==void 0).map(([e])=>e)}function FF(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=Dg(a),s=`${r}: placement "${lg(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(`, `)})`:Ag(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?om(a):``}, but it must be ${Pg(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])=>Ag(o[e],t))||AF(o)))for(let{message:t}of kg(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function IF(e,t,n,r,i){n.kind===`template`&&zF(e,`${t}.template`,n.template,r,{segCtx:i}),xg(n)&&`key`in n.cache&&zF(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function LF(e,t,n,r,i){if(!(!xg(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:J(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function RF(e,t,n,r){try{$D.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function zF(e,t,n,r,i){for(let[a,o]of x_(n,r.helpers)){if(O_(a,r))continue;if(a.startsWith(DF)){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??J(e.source,t.split(`.`))});continue}if(o!==null){BF(e,o,`Template references unknown variable ".${a}"${SF(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&O_(n,r)?` (segment-local vars are namespaced — write ".${n}")`:SF(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??J(e.source,t.split(`.`))})}}function BF(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:J(e.source,[`helpers`,t])})}function VF(e,t,n,r,i){let a=n.set,o=_D(xa[r].configKey),s=`${a} takes ${CE(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:J(e.source,[`actions`,t,`min`])});return}let c=WF(n,i);if(c===UF){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:J(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!SE(o,e.value,i));if(l.length!==0){if(a===xa.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>Nm(e.value)))){let r=xa.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:pF(`actions.${t}.to`,n.to,`set: "${r}", to`),line:J(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:J(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<=HF?r.join(`, `):`${r.slice(0,HF).join(`, `)} and ${r.length-HF} 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:J(e.source,[`actions`,t,n])})}}}const HF=3,UF=Symbol(`any integer`);function WF(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?o_(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)}]:UF}function GF(e,t){return Object.entries(e).filter(([e])=>t(e))}function KF(e,t,n,r){let i=zj(t),a=a_(i);for(let[n,o]of GF(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 ${c_(r,i)}`,line:J(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;wa.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:J(e.source,[`actions`,n,`set`])});let s=Oa.get(o.set);s!==void 0&&VF(e,n,o,s,i)}for(let[n,i]of GF(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&&SP(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:J(e.source,[`actions`,n,`do`])})});for(let[n,i]of GF(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=JD(r);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a config globals field (have: ${LD().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`,line:J(e.source,[`actions`,n,a])});continue}let s=TF.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:J(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){EF(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Xg(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: ${Xg(t.presets).join(`, `)})`,line:J(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${om(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:J(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(`, `)})${fN(o.segment)}`,line:J(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:J(e.source,[`actions`,n,a])})}}for(let[i,a]of GF(t.variables,r)){IF(e,`variables.${i}`,a,n);let t=xF(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:J(e.source,[`variables`,i])})}for(let[i,a]of GF(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))IF(e,`segments.${i}.vars.${t}`,r,n,i);let r=Dg(a);kF(e,i,r);let o=OF(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];if(typeof s==`string`){zF(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r});for(let{name:r,site:a,via:o}of T_(s,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,r))continue;let s=a===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(o!==null){BF(e,o,`Template references unknown action "${r}"${s}`);continue}e.issues.push({path:`segments.${i}.${n}`,message:`${n} references unknown action "${r}"${s}`,line:J(e.source,[`segments`,i,n])})}}}}for(let[i,a]of GF(t.variables,r))LF(e,`variables.${i}`,a,n);for(let[i,a]of GF(t.segments,r))if(a.vars)for(let[t,r]of Object.entries(a.vars))LF(e,`segments.${i}.vars.${t}`,r,n,i)}function qF(e,t){let n=new Set;for(let r of Xg(t.presets)){let i=e_(t,r),a=[{},t.editGlobals];for(let o of a){let a=o.charset??i.charset??`unicode`,s=o.default_separator??i.default_separator;if(a!==`ascii`||Im(s??``))continue;let c=o.default_separator===void 0?Qg(t.presets,r).globals?.default_separator===void 0?[`globals`]:[`presets`,r,`globals`]:[`editGlobals`],l=[...c,`default_separator`].join(`.`);n.has(l)||(n.add(l),e.issues.push({path:l,message:`${l} ${JSON.stringify(s)} is not ASCII, but charset is "ascii" — under ascii a joiner draws only ASCII; write an ASCII separator or set charset: "unicode"`,line:J(e.source,[...c,`default_separator`])}))}}}function JF(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=YF(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:J(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function YF(e){let t=new Set(Object.keys(e.variables)),n=new Map;for(let t of Object.keys(e.variables))n.set(t,{declarationPath:`variables.${t}`,linePathParts:[`variables`,t]});for(let[r,i]of Object.entries(e.segments))if(i.vars)for(let e of Object.keys(i.vars)){let i=`${r}.${e}`;t.add(i),n.set(i,{declarationPath:`segments.${r}.vars.${e}`,linePathParts:[`segments`,r,`vars`,e]})}let r=new Map;for(let e of t)r.set(e,new Set);let i=(n,i)=>{for(let a of x_(i,e.helpers).keys()){if(t.has(a)){r.get(n).add(a);continue}let e=a.split(`.`)[0];e!==a&&t.has(e)&&r.get(n).add(e)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),xg(n)&&(`key`in n.cache&&i(e,n.cache.key),`depends_on`in n.cache))for(let i of n.cache.depends_on)t.has(i)&&r.get(e).add(i)};for(let[t,n]of Object.entries(e.variables))a(t,n);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))a(`${t}.${e}`,r);return{graph:r,nodeInfo:n}}function XF(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?h.homedir()+e.slice(1):e}function ZF(e,t){return l.resolve(e,XF(t))}function QF(e,t){return typeof t==`string`&&t!==``?ZF(e,t):void 0}function $F(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const eI=new Set([`data`,`segments`,`helpers`,`actions`]),tI=`plugin.json5`,nI=/^[a-z][a-z0-9_]*$/;function rI(e){let t=l.basename(l.dirname(e));return nI.test(t)?t:void 0}const iI=`plugins.`;function aI(e){return`${iI}${e}.data`}function oI(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:sI(e)}}}function sI(e){return e instanceof eE?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 cI(e,t){return e.map(e=>ZF(l.dirname(t),e))}function lI(e,t,n,i){let a=new Map;return e.reduce((e,n)=>{let o=rI(n),s=(t,r)=>{let i=new Map(e.rendering);return o!==void 0&&r!==e.config&&i.delete(o),{...e,config:r,rendering:i,dropped:[...e.dropped,{path:n,plugin:o,reason:t}]}};if(l.basename(n)!==`plugin.json5`){let t=`a plugin is a folder holding its ${tI}, and the folder's name is the plugin's: move this file to <dir>/<name>/${tI} and list that`;return s(t,o===void 0?e.config:fI(dI(e.config,o),o,{path:n,plugin:o,reason:t}))}if(o===void 0)return s(`its folder "${l.basename(l.dirname(n))}" is not a plugin name (one matching ${nI}: it prefixes every name the plugin declares)`,e.config);let c=a.get(o);if(c!==void 0)return s(`plugin "${o}" is already listed, from ${c}`,e.config);a.set(o,n);let u=dI(e.config,o),d=oI(()=>{let a=r.readFileSync(n,`utf-8`),s=TM(vI(n,o,{source:a,json:vr.default.parse(a)},t),u);return i(s,o,u!==e.config),s});if(d.ok)return{...e,config:d.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[o,n]])};let f={path:n,plugin:o,reason:d.reason};return s(d.reason,fI(u,o,f))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function uI(e){let t=`${iI}${e}.`;return e=>e.startsWith(t)}function dI(e,t){let n=uI(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 fI(e,t,n){return{...e,variables:{...e.variables,[aI(t)]:{kind:`dropped`,reason:$F(n),definition:n.path}}}}function pI(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function mI(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments)].map(pI)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:$F(e)}));return t=>{let i=pI(t);if(i===void 0)return[];let a=e.config.variables[aI(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function hI(e,t){let n=Xg(e.presets).flatMap(t=>[...pg($g(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,gI(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=pI(t),r=n===void 0?void 0:e.variables[aI(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=>T_(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...D_(t,e.helpers)]),e.helpers),f=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition)]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${aI(pI(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:f}}function gI(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,_I(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function _I(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 vI(e,t,{source:n,json:r},{checkout:i}){let a=[],o=()=>{throw new eE(e,a)};if(!X(r))return a.push({path:``,message:`a plugin definition must be an object, got ${NE(r)}`}),o();for(let e of Object.keys(r))eI.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: ${[...eI].join(`, `)}`});let s=wI(r.data,e,i,a);if(X(r.segments)||a.push({path:`segments`,message:`"segments" must be an object naming the plugin's segments`}),a.length>0||s===void 0)return o();let c={source:n,issues:a,allowedPalettes:new Set(lm()),groups:[]},l=IM(c,`data`,{[aI(t)]:{kind:`file`,path:s,parse:{json:!0},cache:{watch_file:s},default:{}}});for(let[e,t]of Object.entries(r.segments))if(!(!X(t)||!X(t.vars)))for(let[n,r]of Object.entries(t.vars)){let t=X(r)?r.kind:void 0;typeof t!=`string`||t===`state`||a.push({path:`segments.${e}.vars.${n}`,message:`a plugin segment's vars may declare only state variables (kind: "state"), never a source such as ${JSON.stringify(t)}: a plugin's only source is its data file`})}let u={variables:l,segments:bI(t,SI(t,AN(c,r.segments,new Set))),helpers:bI(t,vF(c,r.helpers)),actions:bI(t,CI(t,CP(c,r.actions)))};for(let[e,t]of yI(u))try{$D.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),u}function*yI(e){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[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))`copy`in n&&(yield[`actions.${t}.copy`,n.copy]),`open`in n&&(yield[`actions.${t}.open`,n.open]),`preset`in n&&n.preset===`delete`&&(yield[`actions.${t}.name`,n.name])}function bI(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${iI}${e}.${t}`,n]))}function xI(e,t){return`${iI}${e}.${t}`}function SI(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,n.kind===`state`?{...n,key:xI(e,n.key)}:n]))}]))}function CI(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:xI(e,n.set)}:n]))}function wI(e,t,n,r){if(typeof e==`string`&&e!==``)return ZF(l.dirname(t),e);if(X(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(l.isAbsolute(t)||t.startsWith(`~`)||l.normalize(t).split(l.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 l.resolve(n.root,t)}if(X(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 TI(e){let t=[...[...(process.env.XDG_DATA_DIRS||OI()).split(`:`).filter(e=>e!==``)].reverse().map(e=>l.join(e,`cc-candybar`,`plugins`)),EI(),...e===null?[]:[l.join(e,DI)]];return t.filter((e,n)=>t.lastIndexOf(e)===n)}function EI(){let e=process.env.XDG_DATA_HOME||l.join(h.homedir(),`.local`,`share`);return l.join(e,`cc-candybar`,`plugins`)}const DI=l.join(`.cc-candybar`,`plugins`);function OI(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${l.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function kI(e){let t=TI(e),n=new Map,r=[],i=[];for(let e of t){let t=AI(e);if(`error`in t){r.push(t);continue}for(let r of t.folders)n.delete(r),n.set(r,l.join(e,r,tI));for(let n of t.files)i.push({path:l.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${tI}: move this file to ${l.join(e,`<name>`,tI)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function AI(e){try{let t=r.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()||jI(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 jI(e,t){if(!t.isSymbolicLink())return!1;try{return r.statSync(l.join(e,t.name)).isDirectory()}catch{return!0}}const MI=[`json5`,`json`];function NI(e){try{return r.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function PI(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?MI.map(t=>l.join(e,`.cc-candybar.${t}`)):[],...MI.map(e=>l.join(r,`.cc-candybar.${e}`)),...MI.map(e=>`${FI()}.${e}`)])]}function FI(){let e=process.env.XDG_CONFIG_HOME??l.join(h.homedir(),`.config`);return l.join(e,`cc-candybar`,`config`)}function II(e,t,n){let i=[],a=new Map;for(let o of PI(e,t,n)){let e=NI(o);if(e===`absent`)continue;if(e!==`present`){i.push(e);continue}let t=l.join(r.realpathSync(l.dirname(o)),l.basename(o).replace(/\.(json5|json)$/,``));a.has(t)||a.set(t,o)}let o=[...a.values()].reverse();if(n===void 0)return{kind:`chain`,layers:o,home:LI(o),unchecked:i};let[s]=i,c=n;return o.length>0?{kind:`chain`,layers:o,home:c,unchecked:i}:s===void 0?{kind:`missing`,path:n,home:c}:{kind:`unreadable`,...s,home:c}}function LI(e){let t=FI();return e.find(e=>MI.some(n=>e===`${t}.${n}`))??`${t}.${MI[0]}`}function RI(e,t,n){let r=II(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 zI(e){return BI(e).join(`
154
+ `)||null}function BI(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 VI(e,t){let n=PI(e,t).filter(e=>NI(e)===`present`),r=new Map;for(let e of n){let t=l.dirname(e),n=l.basename(e).replace(/\.(json5|json)$/,``),i=l.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 HI(e,t,n,i){return e===null?{...QI,config:TM(QI.raw,t)}:WI(e,r.readFileSync(e,`utf-8`),t,n,i)}const UI={projectDir:null,checkout:null,beneath:{dropped:[],rendering:new Map}};function WI(e,t,n,r,i){let a=tL(e,t,i,(t,a)=>{let o=lI(cI(t,e),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>XI(t,n,r,e,i)),s=mI(o,r.beneath.dropped);return{inherited:new Set([...kN(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=hI(TM(a.raw,o.config),s);return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map($F)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const GI=new WeakMap;function KI(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e,JI(e)])]),a=GI.get(n)??new Map;GI.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=lI(e,t,{config:n,rendering:new Map},(e,t,n)=>XI(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function qI(e,t,n){return lI(e,{projectDir:null,checkout:n},{config:t,rendering:new Map},(e,t,n)=>XI(e,t,n,`<plugin install>`,void 0)).dropped}function JI(e){try{let t=r.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function YI(e,t,n,i,a=e=>r.readFileSync(e,`utf-8`),o){let s={projectDir:i.projectDir,checkout:i.cwd===null?null:Iw(i.cwd)},c=kI(s.projectDir),l=KI(c.definitions,s,t,o),u={...l,dropped:[...l.dropped,...c.strays]};n.warned(c.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let d=u.config,f=[];for(let t of e){n.entered(t);let e=f.at(-1)?.plugins,r=WI(t,a(t),f.at(-1)?.config??d,{...s,beneath:{dropped:[...u.dropped,...f.flatMap(e=>e.plugins.dropped)],rendering:e?.rendering??u.rendering}},o);n.warned(r.warnings),f.push({...r,path:t})}let p=new Set(f.flatMap(e=>[...e.plugins.reached])),m=e=>p.has(e.path),h=u.dropped.filter(m),g=u.dropped.filter(e=>!m(e));n.warned(h.map($F));let _={checkout:s.checkout,roots:c.roots,loaded:u.loaded,dropped:h,unreached:g,reached:p,rendering:f.at(-1)?.plugins.rendering??u.rendering},v=f.at(-1);if(v===void 0)return{layers:f,base:d,installed:_,config:$I(HI(null,d,UI),`<default>`,o)};try{return{layers:f,base:d,installed:_,config:$I(v,v.path,o)}}catch(e){for(let e of f.slice(0,-1))n.entered(e.path),$I(e,e.path,o);throw n.entered(v.path),e}}function XI(e,t,n,r,i){if(n){$I(ZI(e),r,i);return}let a=uI(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[]};if(KF(s,e,k_(e),a),JF(s,e,a),o.length>0)throw new eE(r,o)}function ZI(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const QI={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function $I({config:e,raw:t,source:n},r=`<config>`,i=new Set(lm())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(wF(o,e,t),JF(o,e),a.length>0)throw new eE(r,a);let s=yP(e,a);if(a.length>0)throw new eE(r,a);return rM(Cj(s))}function eL(e,t,n=new Set(lm()),r=nL){return tL(e,t,n,()=>({inherited:r,layer:null})).raw}function tL(e,t,n,r){let i=rL(e,t),a=rE(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(lm()),groups:[]};if(!X(i))throw new eE(e,[{path:``,message:`Config root must be an object, got ${NE(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:oL({...c,issues:[]},i.plugins)??[],X(i.segments)?Object.keys(i.segments):[]),d=iL(c,i,l);if(s.length>0)throw new eE(e,s,o);return{raw:d,warnings:o,layer:u}}const nL=new Set;function rL(e,t){try{return vr.default.parse(t)}catch(t){let n=t;throw new eE(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function iL(e,t,n){for(let n of Object.keys(t))aL.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...aL].join(`, `)}`,line:J(e.source,[n])});let r={};return t.globals!==void 0&&(r.globals=jD(e,`globals`,t.globals)),t.variables!==void 0&&(r.variables=IM(e,`variables`,t.variables)),t.segments!==void 0&&(r.segments=AN(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.
155
155
  Replace: layout: [["seg1", "seg2"], ["seg3"]]
156
156
  With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
157
- Single-row example: root: { h: ["seg1", "seg2"] }`,line:J(e.source,[`layout`])}),t.root!==void 0&&(r.root=QN(e,`root`,t.root)),t.actions!==void 0&&(r.actions=SP(e,t.actions)),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:J(e.source,[`looks`])}),t.styles!==void 0&&(r.styles=mF(e,t.styles)),t.themeDefaults!==void 0&&(r.themeDefaults=kD(e,t.themeDefaults)),t.presets!==void 0&&(r.presets=gF(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=ND(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=_F(e,t.helpers)),t.plugins!==void 0&&(r.plugins=aL(e,t.plugins)),oP(e,r),gP(e,r),dO(e,r),uE(e,r,Y,`the global settings menu`),r}const iL=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function aL(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 ${ME(t)}`,line:J(e.source,[`plugins`])})}const oL={},sL=Pk(`commands.`),cL=Bk(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),lL=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,uL=`{{ \$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 (${lL}) (basename .project_dir) (ne (${lL}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,dL=`{{ ${EO} }}`,fL={min:0,max:100,step:5},pL={warnAt:{label:`warning at %`,domain:fL,default:50},errorAt:{label:`error at %`,domain:{...fL,atLeast:`warnAt`},default:80}};function mL(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:fL,default:80}}}const hL={globals:{palette:`tokyo-night`},variables:{...sL.variables,...JT,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},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.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"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:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"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},"memento.ceiling":{kind:`input`,path:`memento.ceiling`,type:`number`,default:-1},"memento.off":{kind:`input`,path:`memento.off`,type:`boolean`,default:!1},"memento.session":{kind:`input`,path:`memento.session`,default:``},"memento.error":{kind:`input`,path:`memento.error`,default:``},"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:uL},model:{group:`model-context`,description:`The active model's display name.`,template:`✱ {{ formatModelName .model.display_name }}`,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:dL,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:Ck(``).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:sL.template,when:sL.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:mL(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:mL(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:pL,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:pL,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) ${Mp} }}`,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 }}`},ceiling:{group:`model-context`,description:`The memento plugin's context ceiling for this session: − and + move it by 100K, ∞ lifts it, ↺ drops this session's own setting.`,template:`{{ if ne .memento.error "" }}⌈ ⚠ {{ .memento.error }} {{ action "ceiling.clear" "↺" }}{{ else }}⌈ {{ if .memento.off }}off{{ else }}{{ template "formatTokenCount" .memento.ceiling }} {{ action "ceiling.lower" "−" }} {{ action "ceiling.raise" "+" }} {{ action "ceiling.off" "∞" }}{{ end }}{{ if ne .memento.session "" }} {{ action "ceiling.clear" "↺" }}{{ end }}{{ end }}`,bg:`{{ if ne .memento.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .memento.ceiling 0) (ne .memento.error "") }}`},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:cL.template,bg:cL.bg,when:cL.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:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...Ck(``).actions,...sL.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},"ceiling.raise":{ceiling:`set`,to:`+100_000`},"ceiling.lower":{ceiling:`set`,to:`-100_000`},"ceiling.off":{ceiling:`set`,to:`off`},"ceiling.clear":{ceiling:`clear`},...cL.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:oL,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:`ceiling`},{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:`ceiling`},{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:`ceiling`},{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:{gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Mp}) .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:`{{ if and .settings.age (gt .git.timeSinceCommit 0) }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:Vk(`.`),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 .)) }}`}},gL=new Set([hL.globals.palette,...Object.keys(hL.themeDefaults),...Object.values(hL.segments).map(e=>e.palette)].filter(e=>e!==void 0)),_L=wM($I(`<default>`,JSON.stringify(hL),gL),hL),vL=Yg(_L.presets);function yL(e){return vL.includes(e)}const bL=Object.freeze({});function xL(e,t){return e.kind===`decided`?t[e.name]??bL:bL}function SL(e,t){return{...e,...Object.fromEntries(_g.map(n=>[n,e[n]??t[n]]))}}function CL(e){if(!e)return``;try{return wL(s(e))}catch{return``}}function wL(e){return`${e.mtimeMs}:${e.size}`}const TL=new class{slots;head=null;tail=null;constructor(e){this.slots=e}async run(e){await this.acquire();try{return await e()}finally{this.release()}}async acquire(){if(this.slots>0){this.slots--;return}await new Promise(e=>{let t={wake:e,next:null};this.tail?this.tail.next=t:this.head=t,this.tail=t})}release(){let e=this.head;if(!e){this.slots++;return}this.head=e.next,this.head||(this.tail=null),e.wake()}}(8);function EL(e){return((...t)=>TL.run(()=>e(...t)))}const DL=EL(E),OL=EL(oe),kL=EL(se);async function AL(e,t){return TL.run(async()=>{let n=null;try{n=await T(e,`r`);let r=await n.stat(),{size:i,ino:a}=r,o=wL(r),s=t!==void 0&&(a!==t.ino||i<t.offset),c=s||t===void 0?0:t.offset;if(c>=i)return P({buf:Buffer.alloc(0),start:c,size:i,stamp:o,ino:a,reset:s});let l=Buffer.alloc(i-c),u=0;for(;u<l.length;){let{bytesRead:e}=await n.read(l,u,l.length-u,c+u);if(e===0)break;u+=e}return P({buf:u===l.length?l:l.subarray(0,u),start:c,size:i,stamp:o,ino:a,reset:s})}catch(t){return t.code===`ENOENT`?F:I(`readAppended ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{D(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}async function jL(e,t){return TL.run(async()=>{let n=null;try{n=await T(e,`r`);let{size:r}=await n.stat(),i=Math.max(0,r-t),a=Buffer.alloc(r-i),o=0;for(;o<a.length;){let{bytesRead:e}=await n.read(a,o,a.length-o,i+o);if(e===0)break;o+=e}return P({buf:o===a.length?a:a.subarray(0,o),fromStart:i===0})}catch(t){return t.code===`ENOENT`?F:I(`readTail ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{D(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}const ML=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function NL(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}async function PL(e){let t=await FL(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function FL(e){for(let t of[65536,1048576]){let n=await jL(e,t);if(n.kind!==`ok`)return n;let r=IL(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return F}return F}function IL(e,t){let n=e.toString(`utf8`).split(`
158
- `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!ML.test(t))continue;let r=NL(t);if(r!=null)return r}return null}function LL(e,t){return{...e,claudeConfigDir:ui(t.claudeConfigDir),env:t.mementoEnv}}const RL=l.join(`lib`,`ceiling_config.py`),zL=l.join(`skills`,`ceiling`,`bin`,`ceiling`);function BL(e,t){let n=typeof e==`object`&&e?e.plugins:void 0;if(typeof n!=`object`||!n)throw Error(`${t} has no "plugins" object`);return Object.entries(n).filter(([e])=>e.split(`@`)[0]===`memento`).flatMap(([e,n])=>{if(!Array.isArray(n))throw Error(`${t}: "${e}" is not a list of installs`);return n.map(n=>{let{scope:r,installPath:i,projectPath:a}=n??{};if(typeof r!=`string`||typeof i!=`string`)throw Error(`${t}: an install of "${e}" has no scope/path`);return typeof a==`string`?{key:e,scope:r,installPath:i,projectPath:a}:{key:e,scope:r,installPath:i}})})}function VL(e,t){let n=!0;for(let i of e){if(!r.existsSync(i))continue;let e;try{e=JSON.parse(r.readFileSync(i,`utf8`))?.enabledPlugins?.[t]}catch(e){return I(`memento lookup: ${i}: ${e.message}`)}typeof e==`boolean`&&(n=e)}return P(n)}function HL(e,t){if(!r.existsSync(e))return F;let n;try{n=BL(JSON.parse(r.readFileSync(e,`utf8`)),e)}catch(e){return I(`memento lookup: ${e.message}`)}let i=n.find(e=>e.projectPath===t)??n.find(e=>e.scope===`user`);if(i===void 0)return F;let a=VL([l.join(l.dirname(l.dirname(e)),`settings.json`),l.join(t,`.claude`,`settings.json`),l.join(t,`.claude`,`settings.local.json`)],i.key);if(a.kind!==`ok`)return a;if(!a.value)return F;let o=[RL,zL].filter(e=>!r.existsSync(l.join(i.installPath,e)));return o.length===0?P(i.installPath):I(`memento at ${i.installPath} has no ${o.join(` or `)} — upgrade the plugin`)}function UL(e,t=process.env){let n=new Set([`CLAUDE_PROJECT_DIR`,`CLAUDE_CODE_SESSION_ID`,...e.env===void 0?[]:tt]);return{...Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e))),...e.env,CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir||e.cwd}}function WL(e){return e.stderr.trim()||e.error||`${e.reason}${e.exitCode===null?``:` (exit ${e.exitCode})`}`}function GL(e){let t;try{t=JSON.parse(e)}catch{return I(`memento read: not JSON: ${e.trim()}`)}let{ceiling:n,session:r}=t??{},i=n===`off`||typeof n==`number`&&n>=0?n:void 0;return i!==void 0&&(r===null||typeof r==`string`)?P({ceiling:i,session:r}):I(`memento read: unexpected answer: ${e.trim()}`)}async function KL(e,t){let n=await Me({bin:`python3`,args:[`-c`,`
157
+ Single-row example: root: { h: ["seg1", "seg2"] }`,line:J(e.source,[`layout`])}),t.root!==void 0&&(r.root=$N(e,`root`,t.root)),t.actions!==void 0&&(r.actions=CP(e,t.actions)),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:J(e.source,[`looks`])}),t.styles!==void 0&&(r.styles=hF(e,t.styles)),t.themeDefaults!==void 0&&(r.themeDefaults=AD(e,t.themeDefaults)),t.presets!==void 0&&(r.presets=_F(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=PD(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=vF(e,t.helpers)),t.plugins!==void 0&&(r.plugins=oL(e,t.plugins)),sP(e,r),_P(e,r),fO(e,r),dE(e,r,Y,`the global settings menu`),r}const aL=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function oL(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 ${NE(t)}`,line:J(e.source,[`plugins`])})}const sL={},cL=Fk(`commands.`),lL=Vk(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),uL=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,dL=`{{ \$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 (${uL}) (basename .project_dir) (ne (${uL}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,fL=`{{ ${DO} }}`,pL={min:0,max:100,step:5},mL={warnAt:{label:`warning at %`,domain:pL,default:50},errorAt:{label:`error at %`,domain:{...pL,atLeast:`warnAt`},default:80}};function hL(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:pL,default:80}}}const gL={globals:{palette:`tokyo-night`},variables:{...cL.variables,...YT,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},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.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"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:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"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},"memento.ceiling":{kind:`input`,path:`memento.ceiling`,type:`number`,default:-1},"memento.off":{kind:`input`,path:`memento.off`,type:`boolean`,default:!1},"memento.session":{kind:`input`,path:`memento.session`,default:``},"memento.error":{kind:`input`,path:`memento.error`,default:``},"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:dL},model:{group:`model-context`,description:`The active model's display name.`,template:`✱ {{ formatModelName .model.display_name }}`,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:fL,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:wk(``).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:cL.template,when:cL.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:hL(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:hL(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:mL,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:mL,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) ${Mp} }}`,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 }}`},ceiling:{group:`model-context`,description:`The memento plugin's context ceiling for this session: − and + move it by 100K, ∞ lifts it, ↺ drops this session's own setting.`,template:`{{ if ne .memento.error "" }}⌈ ⚠ {{ .memento.error }} {{ action "ceiling.clear" "↺" }}{{ else }}⌈ {{ if .memento.off }}off{{ else }}{{ template "formatTokenCount" .memento.ceiling }} {{ action "ceiling.lower" "−" }} {{ action "ceiling.raise" "+" }} {{ action "ceiling.off" "∞" }}{{ end }}{{ if ne .memento.session "" }} {{ action "ceiling.clear" "↺" }}{{ end }}{{ end }}`,bg:`{{ if ne .memento.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .memento.ceiling 0) (ne .memento.error "") }}`},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:lL.template,bg:lL.bg,when:lL.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:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...wk(``).actions,...cL.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},"ceiling.raise":{ceiling:`set`,to:`+100_000`},"ceiling.lower":{ceiling:`set`,to:`-100_000`},"ceiling.off":{ceiling:`set`,to:`off`},"ceiling.clear":{ceiling:`clear`},...lL.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:sL,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:`ceiling`},{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:`ceiling`},{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:`ceiling`},{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:{gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Mp}) .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:`{{ if and .settings.age (gt .git.timeSinceCommit 0) }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:Hk(`.`),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 .)) }}`}},_L=new Set([gL.globals.palette,...Object.keys(gL.themeDefaults),...Object.values(gL.segments).map(e=>e.palette)].filter(e=>e!==void 0)),vL=TM(eL(`<default>`,JSON.stringify(gL),_L),gL),yL=Xg(vL.presets);function bL(e){return yL.includes(e)}const xL=Object.freeze({});function SL(e,t){return e.kind===`decided`?t[e.name]??xL:xL}function CL(e,t){return{...e,...Object.fromEntries(vg.map(n=>[n,e[n]??t[n]]))}}function wL(e){if(!e)return``;try{return TL(s(e))}catch{return``}}function TL(e){return`${e.mtimeMs}:${e.size}`}const EL=new class{slots;head=null;tail=null;constructor(e){this.slots=e}async run(e){await this.acquire();try{return await e()}finally{this.release()}}async acquire(){if(this.slots>0){this.slots--;return}await new Promise(e=>{let t={wake:e,next:null};this.tail?this.tail.next=t:this.head=t,this.tail=t})}release(){let e=this.head;if(!e){this.slots++;return}this.head=e.next,this.head||(this.tail=null),e.wake()}}(8);function DL(e){return((...t)=>EL.run(()=>e(...t)))}const OL=DL(E),kL=DL(oe),AL=DL(se);async function jL(e,t){return EL.run(async()=>{let n=null;try{n=await T(e,`r`);let r=await n.stat(),{size:i,ino:a}=r,o=TL(r),s=t!==void 0&&(a!==t.ino||i<t.offset),c=s||t===void 0?0:t.offset;if(c>=i)return P({buf:Buffer.alloc(0),start:c,size:i,stamp:o,ino:a,reset:s});let l=Buffer.alloc(i-c),u=0;for(;u<l.length;){let{bytesRead:e}=await n.read(l,u,l.length-u,c+u);if(e===0)break;u+=e}return P({buf:u===l.length?l:l.subarray(0,u),start:c,size:i,stamp:o,ino:a,reset:s})}catch(t){return t.code===`ENOENT`?F:I(`readAppended ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{D(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}async function ML(e,t){return EL.run(async()=>{let n=null;try{n=await T(e,`r`);let{size:r}=await n.stat(),i=Math.max(0,r-t),a=Buffer.alloc(r-i),o=0;for(;o<a.length;){let{bytesRead:e}=await n.read(a,o,a.length-o,i+o);if(e===0)break;o+=e}return P({buf:o===a.length?a:a.subarray(0,o),fromStart:i===0})}catch(t){return t.code===`ENOENT`?F:I(`readTail ${e}: ${t instanceof Error?t.message:String(t)}`)}finally{await n?.close().catch(e=>{D(`transcript-fs: close failed: ${e instanceof Error?e.message:String(e)}`)})}})}const NL=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function PL(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}async function FL(e){let t=await IL(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function IL(e){for(let t of[65536,1048576]){let n=await ML(e,t);if(n.kind!==`ok`)return n;let r=LL(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return F}return F}function LL(e,t){let n=e.toString(`utf8`).split(`
158
+ `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!NL.test(t))continue;let r=PL(t);if(r!=null)return r}return null}function RL(e,t){return{...e,claudeConfigDir:ui(t.claudeConfigDir),env:t.mementoEnv}}const zL=l.join(`lib`,`ceiling_config.py`),BL=l.join(`skills`,`ceiling`,`bin`,`ceiling`);function VL(e,t){let n=typeof e==`object`&&e?e.plugins:void 0;if(typeof n!=`object`||!n)throw Error(`${t} has no "plugins" object`);return Object.entries(n).filter(([e])=>e.split(`@`)[0]===`memento`).flatMap(([e,n])=>{if(!Array.isArray(n))throw Error(`${t}: "${e}" is not a list of installs`);return n.map(n=>{let{scope:r,installPath:i,projectPath:a}=n??{};if(typeof r!=`string`||typeof i!=`string`)throw Error(`${t}: an install of "${e}" has no scope/path`);return typeof a==`string`?{key:e,scope:r,installPath:i,projectPath:a}:{key:e,scope:r,installPath:i}})})}function HL(e,t){let n=!0;for(let i of e){if(!r.existsSync(i))continue;let e;try{e=JSON.parse(r.readFileSync(i,`utf8`))?.enabledPlugins?.[t]}catch(e){return I(`memento lookup: ${i}: ${e.message}`)}typeof e==`boolean`&&(n=e)}return P(n)}function UL(e,t){if(!r.existsSync(e))return F;let n;try{n=VL(JSON.parse(r.readFileSync(e,`utf8`)),e)}catch(e){return I(`memento lookup: ${e.message}`)}let i=n.find(e=>e.projectPath===t)??n.find(e=>e.scope===`user`);if(i===void 0)return F;let a=HL([l.join(l.dirname(l.dirname(e)),`settings.json`),l.join(t,`.claude`,`settings.json`),l.join(t,`.claude`,`settings.local.json`)],i.key);if(a.kind!==`ok`)return a;if(!a.value)return F;let o=[zL,BL].filter(e=>!r.existsSync(l.join(i.installPath,e)));return o.length===0?P(i.installPath):I(`memento at ${i.installPath} has no ${o.join(` or `)} — upgrade the plugin`)}function WL(e,t=process.env){let n=new Set([`CLAUDE_PROJECT_DIR`,`CLAUDE_CODE_SESSION_ID`,...e.env===void 0?[]:tt]);return{...Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e))),...e.env,CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir||e.cwd}}function GL(e){return e.stderr.trim()||e.error||`${e.reason}${e.exitCode===null?``:` (exit ${e.exitCode})`}`}function KL(e){let t;try{t=JSON.parse(e)}catch{return I(`memento read: not JSON: ${e.trim()}`)}let{ceiling:n,session:r}=t??{},i=n===`off`||typeof n==`number`&&n>=0?n:void 0;return i!==void 0&&(r===null||typeof r==`string`)?P({ceiling:i,session:r}):I(`memento read: unexpected answer: ${e.trim()}`)}async function qL(e,t){let n=await Me({bin:`python3`,args:[`-c`,`
159
159
  import json, math, sys
160
160
  sys.path.insert(0, sys.argv[1])
161
161
  from ceiling_config import CONFIG_NAME, anchored, ceiling_in, in_force, session_directory
@@ -164,19 +164,19 @@ ceiling = in_force(directory, anchored(sys.argv[3]))
164
164
  layer = ceiling_in(directory / CONFIG_NAME)
165
165
  print(json.dumps({"ceiling": "off" if ceiling == math.inf else ceiling,
166
166
  "session": layer.text if layer else None}))
167
- `,l.join(e,`lib`),t.sessionId,t.cwd],env:UL(t),timeoutMs:3e3,category:`memento.read`});return n.ok?GL(n.stdout):I(WL(n))}function qL(e,t,n){let r=Ne({bin:l.join(e,zL),args:n.kind===`set`?[`set`,`session`,n.to]:[`clear`,`session`],env:UL(t),timeoutMs:5e3,category:`memento.move`});if(!r.ok)throw Error(WL(r))}function JL(){return{locate:e=>HL(fi(e.claudeConfigDir),e.projectDir),read:KL,move:qL}}function YL(e,t,n){let r=n===void 0?``:`CLAUDE_CONFIG_DIR=${pr(n)} `,i=e.added_dirs.map(e=>` --add-dir ${pr(e)}`).join(``);return`cd ${pr(e.project_dir)} && ${r}claude --resume ${pr(t)}${i}`}function XL(e,t,n){let r=Xg(t(`preset`),e.globals.preset,e.presets),i=$g(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=ig(a.palette,t(`theme`),i.palette),s=SL(i,xL(o,e.themeDefaults));return{preset:r,presetCustomized:n(r),theme:o,style:xm(a.style,t(`style`),s.style,e.styles),effect:km(a.effect,t(`effect`),s.effect),endcaps:Pm(a.endcaps,t(`endcaps`),s.endcaps),variation:Hm(a.variation,t(`variation`),s.variation),shade:Gm(a.shade,t(`shade`),s.shade),separator:a.default_separator??s.default_separator,autoWrap:$m(a.autoWrap,t(`autoWrap`),s.autoWrap),padding:nh(a.padding,t(`padding`),s.padding),charset:a.charset??s.charset??`unicode`,updateNotice:eh(a.updateNotice,t(`updateNotice`),s.updateNotice),transitions:th(a.transitions,t(`transitions`),s.transitions),colorCompatibility:a.colorCompatibility??s.colorCompatibility??`truecolor`}}function ZL(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,charset:e.charset,width:t}}function QL(e){return{theme:e.theme,style:e.style,effect:e.effect,preset:e.preset,variation:e.variation,shade:e.shade,transitions:e.transitions}}function $L(e){return{preset:{effective:e.preset,customized:e.presetCustomized,bundled:yL(e.preset)},endcaps:{effective:e.endcaps},variation:{effective:e.variation},shade:{effective:e.shade},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding},updateNotice:{effective:e.updateNotice},transitions:{effective:e.transitions}}}const eR={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function tR(e){return e?.prState===void 0?e?.prError===void 0?e?.prEarlier===void 0?`-`:`earlier-${e.prEarlier}`:`failed`:e.prState}const nR=10*1e3;function rR(e,t,n,r){let i=n-(t*1e3-r);if(i<3e5||e<=0)return;let a=e/i,o=(100-e)/a;return Math.max(0,Math.round(o/6e4))}function iR(e,t){if(!(t<60))return e*3600/t}function aR(e,t,n,r){let i=r-t;if(i<50||i>nR)return;let a=n-e;if(!(a<=0))return a*1e3/i}function oR(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=aR(t.input,t.atMs,n.input,n.atMs),i=aR(t.output,t.atMs,n.output,n.atMs),a=aR(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 sR(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>nR)continue;let o=aR(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function cR(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function lR(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>cR(h.hostname())),i=n(`user`,()=>h.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function uR(e,t){let n=new Map;for(let[t,r]of Object.entries(e.variables))n.set(t,r);for(let[t,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))n.set(`${t}.${e}`,i);let r=[],i=new Set,a=t=>b_(t,e.helpers).keys(),o=$g(e,t);for(let e of mm){let t=o[e];if(hm(t))for(let e of a(t))r.push(e)}for(let n of fg(Qg(e,t).node)){if(n.when)for(let e of a(n.when))r.push(e);if(n.kind!==`segment`)continue;let t=e.segments[n.name];if(t){for(let e of[t.template,t.when,t.bg,t.fg])if(e)for(let t of a(e))r.push(t)}}let s=new Set;for(;r.length>0;){let e=r.pop();for(let t of fR(n,e)){if(i.has(t))continue;i.add(t);let e=n.get(t);if(e){if(e.kind===`input`)s.add(e.path);else if(e.kind===`template`)for(let t of a(e.template))r.push(t)}}}return s}function dR(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=uR(e,n);return t.set(n,i),i}}function fR(e,t){let n=t;for(;n.length>0;){if(e.has(n))return[n];let t=n.lastIndexOf(`.`);if(t<0)break;n=n.slice(0,t)}let r=`${t}.`,i=[];for(let t of e.keys())t.startsWith(r)&&i.push(t);return i}function pR(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function mR(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.timeSinceCommit`)&&{showTimeSinceCommit:!0},...Object.keys(eR).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}async function hR(e,t,n,r,i,a,o,{configPath:s,...c}){let l=e=>pR(i,e),u=wT(t).getTime(),d=o.tmux??null,f=(e,t,n)=>t?n().catch(t=>I(`${e}: ${String(t)}`)):Promise.resolve(F),[p,m,h,g,_,v,y,b,x,S,C]=await Promise.all([f(`git`,l(`git`),()=>n.gitProvider.getGitInfo(r??e.workspace?.current_dir,mR(i),e.workspace?.project_dir)),f(`session`,l(`session.cost`)||l(`session.tokens`)||l(`burn`),()=>n.usageStore.getUsageInfo(e.session_id,e)),f(`today`,l(`today`),()=>n.usageStore.getTodayInfo(e,o.claudeConfigDir,t)),f(`context`,l(`context`)||l(`autocompact`),()=>n.contextProvider.getContextInfo(e)),f(`metrics`,l(`metrics`)||l(`burn`),()=>n.metricsProvider.getMetricsInfo(e.session_id,e)),f(`activity`,l(`activity`),()=>n.activityProvider.getActivityInfo(e.session_id,e)),f(`tmux`,l(`tmux.session`),()=>d===null?Promise.resolve(F):n.tmuxService.getSessionName(d)),f(`cache`,l(`cache`),()=>PL(e.transcript_path)),f(`speed`,l(`speed`),()=>n.usageStore.observeSpeed(e.session_id,e.transcript_path,u)),f(`memento`,l(`memento`),()=>n.mementoProvider.getCeiling(LL({sessionId:e.session_id,projectDir:e.workspace?.project_dir??``,cwd:r??e.workspace?.current_dir??``},o))),f(`autocompact`,l(`autocompact`),()=>Promise.resolve(n.autoCompact(di(ui(o.claudeConfigDir)))))]),ee=[],te=e=>{if(e.kind===`failed`){ee.push(e.reason);return}return e.kind===`ok`?e.value:void 0},ne=CR(p,u);ee.push(...ne.failures);let re=lR(o);ee.push(...re.failures);let ie=te(m),ae=te(h),w=te(g),T=te(_),oe=te(v),E=te(y),se=te(b),ce=vR(S);S.kind===`failed`&&ee.push(`memento: ${S.reason}`);let le=gR(C,w?.maxTokens);C.kind===`failed`&&ee.push(`autocompact: ${C.reason}`);for(let e of ee)n.log(`warn`,`provider fetch failed: ${e}`);let ue=e.rate_limits?.five_hour,de=e.rate_limits?.seven_day,fe=ue?rR(ue.used_percentage,ue.resets_at,18e6,u):void 0,pe=de?rR(de.used_percentage,de.resets_at,6048e5,u):void 0,me=ie?.session.cost,he=T?.sessionDuration,ge=l(`burn`)&&me!=null&&he!=null?iR(me,he):void 0,_e=te(x),ve=_e===void 0?void 0:oR(_e),ye=_e===void 0?void 0:sR(_e),be=ve!==void 0||ye!==void 0?{...ve,...ye!==void 0&&{history:ye}}:void 0,xe=SR(process.env.HOME??process.env.USERPROFILE),D=e.workspace?{...e.workspace,current_dir:SR(e.workspace.current_dir)??``,project_dir:SR(e.workspace.project_dir)??``,added_dirs:(e.workspace.added_dirs??[]).map(e=>SR(e)??e)}:e.workspace,Se=ie===void 0?void 0:xR({cost:ie.session.cost,tokens:ie.session.tokens}),Ce=ae===void 0?void 0:{cost:ae.cost,tokens:ae.tokens},we=T===void 0?void 0:xR({lastResponseTime:T.lastResponseTime,responseTime:T.responseTime,sessionDuration:T.sessionDuration,messageCount:T.messageCount,nonPrompts:T.nonPrompts,linesAdded:T.linesAdded,linesRemoved:T.linesRemoved}),Te=oe===void 0?void 0:yR(oe);return{...e,...D!==void 0&&{workspace:D},...xe!==void 0&&{home:xe},...ne.git!==void 0&&{git:ne.git},...d!==null&&{tmux:{pane:d.pane,...E!==void 0&&{session:E}}},host:re.host,...$L(a),history:n.history(e.session_id),navigation:{back:n.navigation(e.session_id)},...c,...s!==null&&{configPath:s},resumeCommand:YL(D,e.session_id,o.claudeConfigDir),...Se!==void 0&&{session:Se},...Ce!==void 0&&{today:Ce},...ge!==void 0&&{burn:{costPerHour:ge}},...be!==void 0&&{speed:be},...l(`block`)&&ue!==void 0&&{block:{nativeUtilization:ue.used_percentage,resetsAt:ue.resets_at,...fe!==void 0&&{etaMinutes:fe}}},...de!==void 0&&{weekly:{percentage:de.used_percentage,resetsAt:de.resets_at,...pe!==void 0&&{etaMinutes:pe}}},...se!==void 0&&{cache:{expiresAt:se}},...w!==void 0&&{context:{totalTokens:w.totalTokens,contextLeft:w.contextLeftPercentage}},...we!==void 0&&{metrics:we},...Te!==void 0&&{activity:Te},...ce!==void 0&&{memento:ce},...le!==void 0&&{autocompact:le}}}function gR(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return zk(e.value,t)}}const _R=e=>e.trim().split(`
168
- `).at(-1).trim();function vR(e){switch(e.kind){case`absent`:return;case`failed`:return{error:_R(e.reason)};case`ok`:{let{ceiling:t,session:n}=e.value;return{ceiling:t===`off`?0:t,off:t===`off`,session:n??``}}}}function yR(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=bR(e.running),i=bR(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 bR(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function xR(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 SR(e){return e===void 0||e.length===0||l.sep!==`\\`?e:e.replace(/\\/g,`/`)}function CR(e,t){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let n=e.value,r=[],i=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){r.push(`git.${e}: ${t.reason}`);return}return t.value}},a=i(`aheadBehind`,n.aheadBehind),o=i(`sha`,n.sha),s=i(`operation`,n.operation),c=i(`timeSinceCommit`,n.committedAt),l=c===void 0?void 0:Math.floor((t-c)/1e3),u=i(`stash`,n.stashCount),d=i(`upstream`,n.upstream),f=n.upstream===void 0?void 0:i(`tracking`,Iw(n.upstream,n.aheadBehind)),p=i(`repoName`,n.repoName),m=i(`repoUrl`,n.repoUrl),h=n.pullRequest===void 0?void 0:Lw(n.pullRequest,n.head),g={};switch(h?.kind){case`ok`:g={prNumber:h.value.number,prState:h.value.state,prUrl:h.value.url};break;case`failed`:r.push(`git.pr: ${h.reason}`),g={prError:h.reason};break;case`earlier`:g={prEarlier:h.value.state};break;case`absent`:case void 0:break}return{git:{branch:n.branch,status:n.status,...a!==void 0&&{ahead:a.ahead,behind:a.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...o!==void 0&&{sha:o},...s!==void 0&&{operation:s},...l!==void 0&&{timeSinceCommit:l},...u!==void 0&&{stash:u},...d!==void 0&&{upstream:d},...f!==void 0&&{tracking:f},...p!==void 0&&{repoName:p},...m!==void 0&&{repoUrl:m},...g},failures:r}}const wR={theme:e=>e.theme.kind===`decided`?e.theme.name:null,preset:e=>e.preset,style:e=>e.style.kind===`decided`?e.style.name:null,effect:e=>e.effect.kind===`decided`?e.effect.name:null,endcaps:e=>e.endcaps,variation:e=>e.variation,shade:e=>e.shade,transitions:e=>e.transitions?Km:qm,autoWrap:e=>e.autoWrap?Km:qm,padding:e=>String(e.padding),updateNotice:e=>e.updateNotice?Km:qm},TR=Object.entries(xa),ER=new Set(Sa.map(e=>e.sessionKey)),DR=()=>!1;function OR(e,t){return XL(e,e=>ER.has(e)?t(e):null,DR)}const kR=[`preset`,`theme`];function AR(e,t,n){let r=new Set(kR.slice(0,n).map(e=>xa[e].sessionKey));return XL(e,e=>r.has(e)?t(e):null,DR)}function jR(e,t){let n=Array.from({length:kR.length+1},(n,r)=>AR(e,t,r));return e=>{let t=kR.indexOf(e);return n[t===-1?kR.length:t]}}function MR(e,t,n,r){return e.flatMap(([e,i])=>{let a=wR[e](t);return a===null||a===wR[e](n(e))?[]:[{...i,value:a,target:r(i)}]})}function NR(e,t,n){return wR[n](OR(e,t))}function PR(e,t){let n=OR(e,t);return MR(TR,n,jR(e,t),t=>FR(e,n.preset,t.configKey))}function FR(e,t,n){return n in(Zg(e.presets,t).globals??{})?KD(t,n):n}function IR(e,t,n){let r=Xg(t(xa.preset.sessionKey),e.globals.preset,e.presets),i=qD(n);return{key:i?.scope===`globals`?FR(e,r,i.field):n,globals:$g(e,r)}}function LR(e,t){let{preset:n}=OR(e,t);return BR(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:jg(a,s);return c===void 0||Ag(c)===Ag(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function RR(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Yg(e.presets).flatMap(n=>{let i=BR(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 Og(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:jg(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const zR=new WeakMap;function BR(e,t){let n=zR.get(e)??new Map;zR.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...fg(Qg(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Eg(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 VR(e,t){let n=OR(e,t);return{from:n.preset,globals:Zg(e.presets,n.preset).globals??{},picks:MR(TR.filter(([e])=>e!==`preset`),n,jR(e,t),e=>e.configKey),placements:LR(e,t)}}function HR(e,t){return XL({...e,globals:{palette:t},presets:{}},()=>null,DR)}function UR(e,t){let n=OR(e,t),r=wR.theme(n);if(r===null)return{kind:`rule`};let i=HR(e,r),a=$g(e,n.preset),o=Object.fromEntries(_g.map(e=>[e,wR[e](a[e]===void 0?n:i)]));return{kind:`look`,theme:r,look:o,differs:_g.some(e=>o[e]!==wR[e](i))}}function WR(e){return{sessionKeys:Sa.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...TD(e)?vL.map(t=>KD(t,e)):[],...GD(e)?lm().map(t=>WD(t,e)):[]]}}function GR(e){return new Set(Sa.map(e=>e.configKey).filter(t=>WR(t).fileKeys.some(t=>JR(e,qR(t)))))}function KR(e,t,n){let r=PR(e,n),i=new Set(r.map(e=>e.configKey)),a=Da(e=>i.has(xa[e].configKey)||t.has(xa[e].configKey)),o=UR(e,n);return{unsaved:r.length+LR(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function qR(e){let t=qD(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return JD(t)}function JR(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&JR(e[n],r)}const YR=lm(),XR=new Set(YR),ZR=new Set(Am),QR=e=>e?XR.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${YR.join(`, `)})`}:{ok:!1,reason:`theme name is required`},$R=e=>e?ZR.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Am.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},ez=new Set([`1`,`true`]),tz=new Set([`0`,`false`]),nz={endcaps:$R,theme:QR,"toolbar-expanded":e=>ez.has(e)?{ok:!0,value:`1`}:tz.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},rz=hM(nz,`state`,uz);function iz(e,t){return rz.register(e,t)}function az(e){return rz.gateFor(e)}function oz(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:a_(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 sz(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(nz,e.key))}function cz(e,t,n){let r=Oa.get(n);if(r!==void 0)return NR(e,t,r);for(let[,t]of Sg(e))if(t.key===n)return t.default??null;return null}function lz(e){let t=Rj(e);return sz(Object.values(e.actions).flatMap(e=>oz(e,t)))}function uz(e){return pM(lz(e))}const dz=`update.dismissed`,fz=`updateNotice`,pz=xa.updateNotice.sessionKey;function mz(e){return e.kind===`source`?e.newer.digest:bi(e.newer)}const hz=e=>`${e.version} [${Gh(e.digest)}]`;function gz(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:hz(e.newer),running:hz(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:bi(e.newer),running:bi(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${Si}@${bi(e.newer)}`,`install`]}}}}const _z={kind:`idle`},vz={kind:`running`};function yz(e,t,n){if(e===null)return[];let r=mz(e);if(!n.enabled||n.dismissed===r)return[];let i=gz(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(`
169
- `),c=Kn([{verb:Tn,args:[s]}]),l=t.kind===`running`?Nh(`[${i.busy}]`,c):Nh(`[${i.act}]`,Kn([{verb:Ln,args:[n.sessionId]}]));return[{severity:Mh,message:s,lines:[[Nh(a,c),l,Nh(`[dismiss]`,Kn([{verb:yn,args:[n.sessionId,dz,r]}])),Nh(`[disable]`,Kn([{verb:N,args:[n.sessionId,fz,`false`]},{verb:yn,args:[n.sessionId,pz,`false`]}]))],...o.map(e=>[Nh(e,c)])]}]}function bz(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 xz(e){switch(e.kind){case`current`:return[`info`,`build: current ${hz(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${hz(e.source)}, running ${hz(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function Sz(e){switch(e.kind){case`current`:return[`info`,`release: current ${bi(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${bi(e.latest)}, running ${bi(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${bi(e.installed)}, latest ${bi(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function Cz(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const wz=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function Tz(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=wz(e.stderr)??e.error??wz(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function Ez(){let e=[_M(fz,[`false`]),iz(pz,[`false`]),iz(dz,[])];return()=>e.forEach(e=>e())}function Dz(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=_z,d=null,f=Cz(s),p=Cz(s),m=()=>bz(c,l);function h(){let e=m(),t=e===null?null:mz(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:iz(dz,[t])})}function g(){c=Yh(t,qh),f(xz(c)),h()}async function _(){l=wi(Et,await Ci(Si,a,i)),p(Sz(l)),h()}return{arm(){Ez(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>yz(m(),u,e),act(){let e=m();if(e===null)throw new K(`apply-update: nothing newer is known to apply`);let t=gz(e);if(u.kind===`running`)throw new K(`apply-update: already ${t.busy}`);u=vz,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),Me({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=_z,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=Tz(n);u={kind:`failed`,identity:mz(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}var Oz=class{static CACHE_DIR=ze();static USAGE_CACHE_DIR=l.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=l.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=l.join(this.LOCKS_DIR,e);if(!r.existsSync(t))return!1;try{let n=r.readFileSync(t,`utf-8`),i=parseInt(n.trim(),10);if(isNaN(i))return D(`Invalid PID in lock file ${e}, removing stale lock`),r.unlinkSync(t),!1;try{return process.kill(i,0),!0}catch(n){return n.code===`ESRCH`?(D(`Removing stale lock file ${e} for dead process ${i}`),r.unlinkSync(t),!1):(D(`Error checking process ${i} for lock ${e}:`,n),!0)}}catch(t){return D(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=l.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await r.promises.writeFile(n,a,{flag:`wx`}),D(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await de(50);else throw e}return D(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=l.join(this.LOCKS_DIR,e);try{await r.promises.unlink(t),D(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&D(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([r.promises.mkdir(this.CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){D(`Failed to create cache directories:`,e)}}static createProjectHash(e){return ae(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=l.join(this.USAGE_CACHE_DIR,`${e}.json`),i=`${e}.usage.lock`;for(let a=0;a<3;a++){if(this.isLocked(i)){D(`Cache for ${e} is locked, waiting...`),await de(75);continue}try{let i=await r.promises.readFile(n,`utf-8`),a=JSON.parse(i);return!t||a.timestamp>=t?(D(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(a.data)):(D(`${e} cache outdated: cache=${a.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return D(`No shared ${e} usage cache found`),null;D(`Attempt ${a+1} failed to read ${e} cache: ${t.message}. Retrying...`),await de(75)}}return D(`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 i=`${e}.usage.lock`;if(!await this.acquireLock(i)){D(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=l.join(this.USAGE_CACHE_DIR,`${e}.json`),a=JSON.stringify({data:t,timestamp:n||Date.now()});await r.promises.writeFile(i,a,`utf-8`),D(`[CACHE-SET] ${e} disk cache stored`)}catch(t){D(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(i)}}};const kz={"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 Az=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 Oz.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await Oz.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new ee(this.GITHUB_PRICING_URL),n=ue({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){D(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let r=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){D(`Response too large`),n.destroy(),e(null);return}r+=t}),t.on(`end`,()=>{try{let t=JSON.parse(r),n=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(D(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),D(`Pricing last updated: ${n?.updated||`unknown`}`),e(i)):(D(`Invalid pricing data structure`),e(null))}catch(t){D(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{D(`Response error:`,t),e(null)})});n.on(`error`,t=>{D(`Request error:`,t),e(null)}),n.on(`timeout`,()=>{D(`Request timeout`),n.destroy(),e(null)}),n.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return D(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return D(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),D(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(D(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(kz).length} models`),this.executionCache=kz,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(kz).length} models`),kz)}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 D(`[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),D(`[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 jz=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function Mz(e){if(typeof e==`string`)return jz.exec(e)?.[1]}function Nz(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 Pz(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 Fz(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=Nz(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`?Mz(Pz(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 Iz(e){if(e!==void 0)return[e];let t=g();return[p(t,`.config`,`claude`),p(t,`.claude`)].filter(e=>a(e))}async function Lz(e){let t=[];for(let n of e){let e=p(n,`projects`);if(a(e))try{let n=await DL(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=p(e,r.name);t.push(n)}}catch(t){D(`Failed to read projects directory ${e}:`,t)}}return t}async function Rz(e,t,n){let r=[],i=p(t,e,`subagents`);try{let t=(await DL(i)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let a of t){let t=p(i,a);if(n?.has(t)){r.push(t);continue}try{let n=(await OL(t,`utf-8`)).split(`
170
- `)[0];n&&JSON.parse(n).sessionId===e&&r.push(t)}catch{D(`Failed to check agent file ${t}`)}}}catch(e){D(`Failed to read subagents directory ${i}:`,e)}return r}function zz(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(Vz(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=Pz(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||Bz.test(r)?`claude-code`:`prompt`}const Bz=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function Vz(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}const Hz=new Map;async function Uz(e){try{let t=await kL(e),n=t.size,r=Hz.get(e);if(r&&r.mtime===t.mtimeMs&&r.size===n)return D(`[parse-cache] hit ${e}`),Hz.delete(e),Hz.set(e,r),r.entries;let i;return n>1048576?(D(`Using streaming parser for large file ${e} (${Math.round(n/1024)}KB)`),i=await Jz(e)):i=await Kz(e),D(`Parsed ${i.length} entries from ${e}`),n>5242880?i:(Hz.delete(e),Hz.size>=16&&Hz.delete(Hz.keys().next().value),Hz.set(e,{mtime:t.mtimeMs,size:n,entries:i}),i)}catch(t){if(t.code===`ENOENT`)return D(`Transcript not present yet: ${e}`),[];throw t}}function Wz(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=zz(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:Fz(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 Gz(e){let t=[];for(let n of e.split(`
171
- `))if(n.trim())try{let e=Wz(JSON.parse(n));e&&t.push(e)}catch(e){D(`Failed to parse JSONL line: ${e}`);continue}return t}async function Kz(e){return Gz(await OL(e,`utf-8`))}async function qz(e,t){let n=await AL(e,t===void 0?void 0:{offset:t.offset,ino:t.ino});if(n.kind!==`ok`)return n;let{buf:r,start:i,stamp:a,ino:o,reset:s}=n.value,c=r.lastIndexOf(10);return P(c<0?{entries:[],cursor:{offset:i,stamp:a,ino:o},reset:s}:{entries:Gz(r.subarray(0,c+1).toString(`utf-8`)),cursor:{offset:i+c+1,stamp:a,ino:o},reset:s})}async function Jz(e){return new Promise((t,n)=>{let r=[],a=i(e,{encoding:`utf8`}),o=fe({input:a,crlfDelay:1/0});o.on(`line`,e=>{let t=e.trim();if(t)try{let e=Wz(JSON.parse(t));e&&r.push(e)}catch(e){D(`Failed to parse JSONL line: ${e}`)}}),o.on(`close`,()=>{t(r)}),o.on(`error`,t=>{D(`Streaming parser error for ${e}:`,t),n(t)}),a.on(`error`,t=>{D(`File stream error for ${e}:`,t),n(t)})})}var Yz=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}};function Xz(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 Zz=new Map,Qz={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},$z={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function eB(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function tB(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function nB(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}async function rB(e,t,n,r){let i=eB(new Date(tB())),a=e&&!t?e:void 0,o=a?.entries??0,s=a?.cost??0,c=a?{...a.breakdown}:nB(),l=new Map;if(a)for(let[e,t]of a.days)e>=i&&l.set(e,{...t});for(let e of n){let t=e.message?.usage;if(!t)continue;o++;let n=e.costUSD??await Az.calculateCostForEntry(e.raw);s+=n,c.input+=t.input_tokens||0,c.output+=t.output_tokens||0,c.cacheCreation+=t.cache_creation_input_tokens||0,c.cacheRead+=t.cache_read_input_tokens||0;let r=eB(new Date(e.timestamp));if(r<i)continue;let a=l.get(r)??{...Qz};a.cost+=n,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,l.set(r,a)}return{cursor:r,entries:o,cost:s,breakdown:c,days:l}}function iB(e){let t=0,n=0,r=nB(),i=new Map;for(let 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)??{...Qz};n.cost+=t.cost,n.input+=t.input,n.output+=t.output,n.cacheCreation+=t.cacheCreation,n.cacheRead+=t.cacheRead,i.set(e,n)}}if(t===0)return{sessionInfo:$z,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}}async function aB(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))}var oB=class{sessions=new Map;flight=new Yz;seeded=new Map;seededDay=``;rescanIntervalMs;speedFlight=new Yz;staleAgeMs;log;renderTally={hits:0,misses:0};sweeps=0;scans={seed:0,rescan:0};sweepTimer=null;constructor(e={}){this.log=e.logger??Ft,this.staleAgeMs=e.staleAgeMs??864e5,this.rescanIntervalMs=e.rescanIntervalMs??6e4;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,seeds:this.scans.seed,rescans:this.scans.rescan}}async getUsageInfo(e,t){let n=await this.ingest(e,t?.transcript_path,this.renderTally);if(n.kind===`failed`)return n;let r=n.kind===`ok`?n.value.sessionInfo:$z,i=t?.cost?.total_cost_usd??null;return P({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e,t,n){let r=eB(wT(n)),i=Iz(t);try{await this.ensureSeeded(r,i,n*1e3)}catch(e){return I(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let a=await this.ingest(e?.session_id??``,e?.transcript_path,this.renderTally);if(a.kind===`failed`)return a;let o=i.map(e=>p(e,`projects`)+m),s={...Qz},c=!1;for(let[t,{record:n}]of this.sessions){let i=n?.transcriptPath??``,a=t===e?.session_id||o.some(e=>i.startsWith(e))?n?.days??Zz:Zz;c||=a.has(r);let l=a.get(r)??Qz;s.cost+=l.cost,s.input+=l.input,s.output+=l.output,s.cacheCreation+=l.cacheCreation,s.cacheRead+=l.cacheRead}return c?P({cost:s.cost,tokens:s.input+s.output+s.cacheCreation+s.cacheRead,tokenBreakdown:{input:s.input,output:s.output,cacheCreation:s.cacheCreation,cacheRead:s.cacheRead},date:r}):F}async observeSpeed(e,t,n){if(!e)return F;let r=CL(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,this.renderTally,r);if(i.kind===`failed`)return i;let a=Xz(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),{ring:o}=this.hold(e),s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);return o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift(),P({...s!==void 0&&{prev:s},cur:a,samples:[...o]})})}async ingest(e,t,n,r){if(!e)return F;let i=r??CL(t),a=this.see(e)?.record;if(a&&i!==``&&a.transcriptStamp===i)return n.hits++,P(a);if(!t)return a?P(a):F;n.misses++;let o;try{o=await this.flight.run(`${e}:${i}`,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:s,outcome:c}=o;if(c.kind!==`ok`)return c;let l={files:c.value.files,sessionInfo:c.value.sessionInfo,days:c.value.days,transcriptStamp:c.value.mainStamp,transcriptPath:t};return this.sessions.get(e)?.record===s&&(this.hold(e).record=l),P(l)}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:[]};return this.sessions.set(e,n),n}async refold(e,t,n){let r=await Rz(e,d(t),n===void 0?void 0:new Set(n.files.keys())),i=new Map,a=``;for(let e of[t,...r]){let r=n?.files.get(e),o=await qz(e,r?.cursor);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{entries:s,cursor:c,reset:l}=o.value;i.set(e,await rB(r,l,s,c)),e===t&&(a=c.stamp)}return P({files:i,...iB(i),mainStamp:a})}ensureSeeded(e,t,n){this.seededDay!==e&&(this.seeded.clear(),this.seededDay=e);let r=t.join(`\0`),i=this.seeded.get(r);if(!i){let e=this.seed(t,`seed`),i={done:e,scanning:e,startedAtMs:n};return this.seeded.set(r,i),this.settle(r,i,e),e}return i.scanning===void 0&&n-i.startedAtMs>=this.rescanIntervalMs&&(i.startedAtMs=n,i.scanning=this.seed(t,`rescan`),this.settle(r,i,i.scanning)),i.done}settle(e,t,n){n.then(()=>{t.scanning=void 0},n=>{this.log(`warn`,`usageStore scan: ${n instanceof Error?n.message:String(n)}`),this.seeded.get(e)===t&&this.seeded.delete(e)})}async scanned(){await Promise.allSettled([...this.seeded.values()].map(e=>e.scanning))}async seed(e,t){let n=Date.now(),r=tB(),i=await Lz(e),a=[];for(let e of i){let t;try{t=await DL(e)}catch{continue}for(let n of t){if(!n.endsWith(`.jsonl`))continue;let t=p(e,n),i;try{i=await kL(t)}catch{continue}i.mtimeMs<r||a.push({sessionId:n.slice(0,-6),path:t,stamp:wL(i)})}}let o={hits:0,misses:0};await aB(a,8,async e=>{let n=await this.ingest(e.sessionId,e.path,o,e.stamp);n.kind===`failed`&&this.log(`warn`,`usageStore ${t}: ${n.reason}`)}),this.log(`info`,`usageStore ${t} sessions=${a.length} read=${o.misses} dirs=${e.join(`,`)} ms=${Date.now()-n}`),this.scans[t]++}sweepStale(){let e=Date.now(),t=0,n=0,r=0;for(let[i,{lastSeenAt:a,record:o}]of this.sessions)if(!(e-a<=this.staleAgeMs)){if(o?.days.has(this.seededDay)){n++;continue}this.sessions.delete(i),t++,o===void 0&&r++}return t>0&&this.sweeps++,(t>0||n>0)&&this.log(`info`,`usageStore sweep dropped=${t} noRecord=${r} held=${n}`),t}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.sessions.clear(),this.seeded.clear()}},sB=class{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 D(`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);D(`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){try{D(`Calculating context tokens from transcript: ${e}`);let n=await Uz(e);if(n.length===0)return D(`No entries in transcript`),F;let r=null;for(let e=n.length-1;e>=0;e--){let t=n[e];if(t&&t.message?.usage?.input_tokens&&t.isSidechain!==!0){r=t,D(`Context segment: Found most recent entry at ${t.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let e=r.message.usage,n=(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0);return D(`Most recent main chain context: ${n} tokens (limit: ${t})`),P({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return D(`No main chain entries with usage data found`),F}catch(e){return I(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return P(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}},cB=class{states=new Map;constructor(e,t,n=256){this.empty=e,this.step=t,this.maxSessions=n}async read(e,t){let n=this.states.get(e),r=CL(t);if(n&&r!==``&&n.cursor.stamp===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await qz(t,n?.cursor);if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:n?.value??this.empty};let{entries:a,cursor:o,reset:s}=i.value,c=s||n===void 0?this.empty:n.value;for(let e of a)c=this.step(c,e);for(this.touch(e,{cursor:o,value:c});this.states.size>this.maxSessions;){let e=this.states.keys().next().value;if(e===void 0)break;this.states.delete(e)}return{kind:`ok`,value:c}}touch(e,t){this.states.delete(e),this.states.set(e,t)}};const lB={messageCount:0,nonPrompts:0,recent:[]},uB=new Set([`turn`,`interrupt`,`claude-code`]);function dB(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!uB.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function fB(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 pB=class{fold=new cB(lB,dB);async getMetricsInfo(e,t){if(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return F;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?I(`metrics (${e}): ${n.reason}`):P({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:fB(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const mB={command:null,todos:[],pending:[],done:[]};function hB(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 gB(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 _B(e,t){if(t.isSidechain)return e;let n=gB(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=hB(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 vB(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>hB(e,t.name),[]),done:e.done}}var yB=class{fold=new cB(mB,_B);async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?I(`activity (${e}): ${n.reason}`):P(vB(n.value))}};function bB(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function xB(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 SB(e,t,n,r){return xB(Ne(bB(e,t,n,r)),n)}async function CB(e,t,n){return xB(await Me(bB(e,t,n)),n)}const wB=e=>`${e.socket}\n${e.pane}`;var TB=class{names=new Map;asking=new Yz;constructor(e=Date.now){this.now=e}getSessionName(e){let t=wB(e),n=this.names.get(t);if(n&&this.now()-n.at<3e4)return Promise.resolve(n.outcome);let r=this.asking.run(t,()=>this.ask(t,e));return n?Promise.resolve(n.outcome):r}async ask(e,t){D(`Getting tmux session name for pane ${t.pane} on ${t.socket}`);let n=await CB(t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]),r=n.kind===`ok`?n.stdout.trim():``,i=n.kind===`ok`?r?P(r):F:I(n.reason);for(this.names.delete(e),this.names.set(e,{outcome:i,at:this.now()});this.names.size>64;)this.names.delete(this.names.keys().next().value);return i}};const EB=e=>JSON.stringify([e.sessionId,e.projectDir,e.cwd,e.claudeConfigDir,e.env===void 0?null:tt.map(t=>e.env?.[t]??null)]);var DB=class{readings=new Map;inFlight=new Map;constructor(e,t=Date.now){this.edge=e,this.now=t}getCeiling(e){let t=EB(e),n=this.readings.get(t);if(n&&this.now()-n.at<1e4)return Promise.resolve(n.outcome);let r=this.inFlight.get(t)??this.fetch(t,e);return n?Promise.resolve(n.outcome):r}fetch(e,t){let n=this.edge.locate(t),r=(n.kind===`ok`?this.edge.read(n.value,t):Promise.resolve(n)).then(t=>{if(this.inFlight.get(e)!==r)return t;for(this.readings.delete(e),this.readings.set(e,{outcome:t,at:this.now()});this.readings.size>64;)this.readings.delete(this.readings.keys().next().value);return t}).finally(()=>{this.inFlight.get(e)===r&&this.inFlight.delete(e)});return this.inFlight.set(e,r),r}move(e,t){let n=this.edge.locate(e);if(n.kind!==`ok`)throw Error(n.kind===`failed`?n.reason:`memento is not installed or not enabled for this project`);let r=EB(e);try{this.edge.move(n.value,e,t)}finally{this.readings.delete(r),this.inFlight.delete(r),this.fetch(r,e)}}};function OB(e){return{gitProvider:new vT({watchers:e.watchers,logger:e.logger}),usageStore:new oB({logger:e.logger}),contextProvider:new sB,metricsProvider:new pB,activityProvider:new yB,tmuxService:new TB,mementoProvider:new DB(JL()),autoCompact:Rk,log:e.logger}}function kB(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const AB={kind:`hidden`},jB={kind:`shown`};function MB(e,t){try{return kB(e,t)?jB:AB}catch(e){return{kind:`failed`,message:e instanceof Error?e.message:String(e)}}}function NB(e,t){let n=G.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function PB(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function FB({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function IB({text:e,placement:t,lead:n,trail:r}){return{text:LB(e),placement:t,...n!==void 0&&{lead:LB(n)},...r!==void 0&&{trail:LB(r)}}}function LB(e){let t=e.blankCopy(e.plain);t.style=ih(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(ih(i).clearMetaAndLinks(),n,r);return t}function RB(e){let t=FB(e);if(t.length===1)return e.text;let n=NB(t);return n.style=e.text.style,n}function zB(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=NB(e,a).pad(o),d=new G(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:NB([d,...c],a)},...l.length>0&&{trail:NB([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(PB(u,n,p),[{text:u,...f}])}const BB=RegExp(`\\x1b\\[[0-9;]*m|${Ul.source}`,`g`);function VB(e){return Math.max(0,...e.split(`
172
- `).map(e=>L(e.replace(BB,``))))}function HB(e,t){let n=()=>e.map(e=>({owner:RB(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=Oh(e.map(RB),t).split(`
173
- `);if(i.length>1)return n();let a=Math.max(0,t.width-VB(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];PB(c,c.cellLength+a,n)}),n()}function UB(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=WB(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:ih(a.style)};if(e.style.link){i();let r=WB([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function WB(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>GB(e.frag,n?n.add(e.style):e.style)),i=G.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function GB(e,t){let n=e.copy();return n.style=t,n}function KB(e,t){if(e.look===void 0)throw Error(`${t} read the render's look before any render resolved one`);return e.look}function qB(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,JB(e,t,o,n,r,i));return i}function JB(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=a_(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=Ta.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=a_(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=a_(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:ZB(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:ZB(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(`ceiling`in n)return{kind:`ceiling`,args:bP(n)};if(`slash`in n)return{kind:`slash`,line:n.slash};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:ZB(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 YB(e){return e.kind===`do`?YB(e.head):e}function XB(e){switch(YB(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`ceiling`:case`slash`:case`do`:return!1}}function ZB(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function QB(e,t){return e.has(t)?L_(e.read(t)):``}function $B(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function eV(e,t,n,r){let i=new G(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function tV(e,t,n=!1){let r=new H({link:t,bold:n?!0:void 0}),i=new G(e.plain,{style:H.combine([ih(e.style),r])});for(let t of e.spans)i.stylize(H.combine([ih(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function nV(e,t){return Math.max(e.members.indexOf(QB(t,e.stateVar)),0)}function rV(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=QB(r,e.stateVar);return{effects:[{verb:yn,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=QB(r,e.stateVar);return{effects:[{verb:yn,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=QB(r,e.stateVar);return{effects:[{verb:yn,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(nV(e,r)+1)%e.members.length];return{effects:[{verb:yn,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:bn,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:xn,args:[$B(e.text,kw(r))]}],active:!1};case`open`:return{effects:[{verb:Sn,args:[$B(e.target,kw(r))]}],active:!1};case`persist-literal`:{let t=QB(r,e.stateVar);return{effects:[{verb:N,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=QB(r,e.stateVar);return{effects:[{verb:N,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(nV(e,r)+1)%e.members.length];return{effects:[{verb:N,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:En,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:jn,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:Nn,args:[i]}],active:!1};case`redo`:return{effects:[{verb:Pn,args:[i]}],active:!1};case`back`:return{effects:[{verb:Fn,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:In,args:[i]}],active:!1};case`save`:return{effects:[{verb:Dn,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:On,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:kn,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:An,args:[i,$B(e.name,kw(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:Rn,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:zn,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:Bn,args:[i,e.check,e.mark]}],active:!1};case`ceiling`:return{effects:[{verb:Hn,args:[i,...e.args]}],active:!1};case`slash`:return{effects:[{verb:Un,args:[i,e.line]}],active:!1};case`layout-op`:return{effects:[{verb:Mn,args:[i,e.key,rM(e.op)]}],active:!1};case`do`:{let a=rV(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>rV(e,t,void 0,r,i).effects)],active:a.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Mn,args:[i,e.key,rM(r)]}],active:!1}}}}function iV(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:tr(`action "${e}"`,n,t.members.length,nV(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 aV(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=n.store,{display:a,boundValue:o}=iV(e,YB(r),t,i),s=QB(i,`session.id`),{effects:c,active:l}=rV(r,a.plain,o,i,s);return tV(a,Kn(c),l)}function oV(e){return{action:{fn:(t,...n)=>aV(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function sV(e,t){return eV(`✕`,Kn([{verb:yn,args:[QB(e,`session.id`),t,Qn]}]),!1)}function cV(e,t,n){return new H({bgcolor:B.fromRgba(t),color:B.fromRgba(Np(e,t,n))})}function lV({tint:e,text:t}){return new H({bgcolor:B.fromRgba(e),color:B.fromRgba(t)})}function uV(e,t,n){return new H({color:B.fromRgba(sc(Cp(e,`warning`),t,Mp,n))})}function dV(e,t,n){return H.combine([cV(e,t,n),uV(e,t,n)])}function fV(e,t,n){return cV(e.palette,em(e.palette,e.disclosure,[t],n),n)}function pV(e){let t=B.fromRgba(Cp(e,`background`)),n=G.fromFragments(Xf.map(n=>new G(`▀`,{style:new H({color:B.fromRgba(Cp(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const mV=(e,t)=>{let n=typeof e==`string`?new G(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},hV=e=>new H({bold:e});function gV(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>mV(a,H.combine([fV(e,{...n,distribution:t},i),hV(o)]));let o=cV(e.palette,a,i);return(e,t,i,a)=>_V(i,H.combine([o,hV(a)]),r(t,n))}const _V=(e,t,n)=>mV(G.fromFragments([mV(e,t),mV(` `,t),pV(n)]));function vV(e,t){return t===void 0?(e,t,n)=>mV(n):(n,r,i)=>_V(i,void 0,t(r,e))}function yV(e,t,n,r,i){let a=cV(e.palette,i,r);return(e,r,i,o)=>mV(G.fromFragments([mV(o?`[`:` `,a),pV(n(r,t)),mV(o?`]`:` `,a)]))}function bV(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=>xV(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function xV(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function SV(e,t){return new G(e).truncate(t,{marker:`…`}).plain}function CV(e){return{current:null,drawnAt:e}}function wV(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 TV(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 EV(e){return new G(e).cellLength}function DV(e){return Math.max(1,e.width-e.chromeCols-2*e.padding)}function OV(e){return Math.max(1,DV(e)-(EV(`✕`)+2*e.padding+e.seamCols))}function kV(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 AV(e,t,n){let r=EV(`←`)+1+EV(`→`)+1,i=kV(e,t,n);return(i.length>1?kV(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function jV(e,t){let n=[];for(let t of e)n.length>0&&n.push(new G(` `)),n.push(t);let r=G.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function MV(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 NV(e,t,n){let r=e.compiled.get(t),i=r&&YB(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 PV(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=a.store,d=QB(u,`session.id`),f=`stateVar`in t?QB(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`?OV(a):DV(a):1/0,h=(r.kind===`led`?0:EV(`✕`)+1)+c.reduce((e,t)=>e+EV(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?AV(_.map(e=>e.cellLength),m,h):bV(g.entries,g.groups,i),y=parseInt(QB(u,n.stateVar),10),b=e=>Math.max(0,v.findIndex(t=>t.some(t=>t.indices.includes(e)))),x=b(f===void 0?-1:t.options.indexOf(f)),S=Number.isInteger(y)?y<0?x:Math.min(y,v.length-1):0,C=v[S]??[],ee=e=>Kn([{verb:yn,args:[d,n.key,String(e)]}]),te=r.kind===`led`?[]:[{verb:yn,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],ne=r.kind===`own`&&r.onPick?te:[],re=e=>Kn([...rV(l,e,e,u,d).effects,...ne]),ie=(e,n)=>tV(e,re(t.options[n])),ae=r.kind===`led`?[]:[eV(`✕`,Kn(te),!1,s)];ae.push(...c.map(({glyph:e,option:r})=>eV(e,Kn([...rV(l,r,r,u,d).effects,{verb:yn,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),S>0&&ae.push(eV(`←`,ee(S-1),!1));let w=S<v.length-1?[eV(`→`,ee(S+1),!1)]:[];if(g===void 0){let e=C.flatMap(e=>e.indices);return[jV([...ae,...e.map(e=>ie(_[e],e)),...w],i)]}let T=new H({bold:!0}),oe=v.length>1?` ${S+1}/${v.length}`:``,E=C.length===1?[new G(`${C[0].label}${oe}`,{style:T})]:[],se=[jV([...ae,...E,...w],i)];for(let e of C){C.length>1&&se.push(jV([new G(e.label,{style:T})],i));let n=Math.max(...e.indices.map(e=>EV(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:Hf(a),s=` `.repeat(n-EV(e)+2),c=o===void 0?e:`${e}${s}${o}`;se.push(jV([ie(p(r,SV(c,m)),r)],i))}}return se}function FV(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{Cw(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=MV(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=NV(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=TV(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]=PV(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,gV(u,dp(void 0),KB(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),uV(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function IV(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function LV(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 RV(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=n.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=QB(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return jV([],!0);let d=QB(o,t.stateVar),f=IV(l,d),p=e=>l[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let n=Kn(rV(s,p(e),p(e),o,c).effects);return m.set(e,n),n},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=tV(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):tV(vV(KB(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),Kn(rV(n.compiled.get(a),p(0),void 0,o,c).effects)),b=LV(e=>v(e).cellLength,u,EV(`◀`)+1+y.cellLength+1+EV(`▶`),OV(n),i),x=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return jV([...x(-1).reverse(),eV(`◀`,h(-1),!1),y,eV(`▶`,h(1),!1),...x(1)],!0)}function zV(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(Cw(`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&&XB(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=NV(e,n,`carousel`),l=TV(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 RV(n,c,e,gV(l,dp(void 0),KB(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function BV(e,t,n){let r=NV(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 VV(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 HV(e,t,n,r){let i=BV(e,t,n),a=r??QB(e.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,KB(e,`{{ ${n} }}`))}function UV(e,t,n){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(Cw(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return pV(HV(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`},swatches:{fn:(r,i)=>{let a=BV(e,r,`swatches`),o=MV(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=TV(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]=PV(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,yV(s,KB(e,`{{ swatches }}`),a.paletteOf,c,s.bg),uV(s.palette,s.bg,c),u===0?[]:(()=>{let t=IV(l,QB(e.store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[VV(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const WV=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function GV(e,t,n,r){let i=Gp(e,n,r),a=(t,n)=>({text:t,colour:n,ink:Np(e,n,r)});return[[op(t).map((n,i)=>{let a=wp(e,n);return{text:WV[i%WV.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Cp(e,`warning`)),a(`error`,Cp(e,`error`))]]]}function KV(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new G(` ${e} `,{style:lV({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 G(e)),r.push(a)}return r}function qV(e,t,n,r,i){let a=GV(e,t,n,r).map(e=>KV(e,i)),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
174
- `),...e]));return o.overflow=`ignore`,o.end=``,o}function JV(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(Cw(`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}=KB(e,`{{ themePreview }}`);return qV(r===void 0?a:HV(e,r,`themePreview`),o,{...TV(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),OV(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const YV=e=>e.slice(e.lastIndexOf(`.`)+1),XV=(e,t)=>{let n=new G(YV(e));return n.truncate(t,{marker:`…`}),n.plain};function ZV(e,t){let n=e.map(e=>e.map(({name:e})=>EV(YV(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 QV(e,t,n,r){let i=ZV(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new G(` ${XV(s,i)} `,{style:lV(im(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
175
- `),...e]));return o.overflow=`ignore`,o.end=``,o}function $V(e,t){return{layoutPreview:{fn:()=>QV(e.layout(),KB(e,`{{ layoutPreview }}`).decor,t.drawnAt(),OV(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function eH(e,t,n,r){let i=TV(r.activeSegment,`{{ menu }}`),a=r.action,o=fE(i.placementId,e,n.key),s=hE(o),c=dE(e),l=QB(a.store,o)===c,u=QB(a.store,`session.id`),d=l?Qn:c,f=eV(tr(`{{ menu "${e}" }}`,t,2,+!!l),Kn([{verb:yn,args:[u,o,d,s,`0`]}]),!1);return i.drops.push(...l?(()=>{let t=r.activeSegment.drawnAt(),c=Gp(i.palette,i.disclosure,t).plane,l=NV(a,e,`menu`);return PV(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,Qn],[s,`0`]],onPick:n.closeOnPick},n.paged,a,gV(i,n.distribution,KB(a,`{{ menu }}`),l.paletteOf,t,c),uV(i.palette,c,t))})():[]),f}const tH=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function nH(e,t){let n=t[t.length-1],r=tH(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:yE(r??{})}}function rH(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=nH(t,n);return eH(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function iH(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=aH(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 G(t?i:a,{style:l===void 0?void 0:new H({color:l})}))}let l=G.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function aH(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 oH(e){let t={fn:(()=>{let t=TV(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:(()=>TV(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=TV(e,`{{ keptOn }}`),i=Qs(r,t),a=Qs(r,n),o=Uo(lc(i,z.TRUECOLOR),lc(a,z.TRUECOLOR)),s=Math.min(Mp,Math.max(o,3));return(cc(i,e.drawnAt(),(e,t)=>Uo(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=lw(()=>TV(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...sH(s)];return iH({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 sH(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 cH(e){let t=[],n=[];for(let r of e){if(!r.contains(`
167
+ `,l.join(e,`lib`),t.sessionId,t.cwd],env:WL(t),timeoutMs:3e3,category:`memento.read`});return n.ok?KL(n.stdout):I(GL(n))}function JL(e,t,n){let r=Ne({bin:l.join(e,BL),args:n.kind===`set`?[`set`,`session`,n.to]:[`clear`,`session`],env:WL(t),timeoutMs:5e3,category:`memento.move`});if(!r.ok)throw Error(GL(r))}function YL(){return{locate:e=>UL(fi(e.claudeConfigDir),e.projectDir),read:qL,move:JL}}function XL(e,t,n){let r=n===void 0?``:`CLAUDE_CONFIG_DIR=${pr(n)} `,i=e.added_dirs.map(e=>` --add-dir ${pr(e)}`).join(``);return`cd ${pr(e.project_dir)} && ${r}claude --resume ${pr(t)}${i}`}function ZL(e,t,n){let r=Zg(t(`preset`),e.globals.preset,e.presets),i=e_(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=ag(a.palette,t(`theme`),i.palette),s=CL(i,SL(o,e.themeDefaults));return{preset:r,presetCustomized:n(r),theme:o,style:xm(a.style,t(`style`),s.style,e.styles),effect:km(a.effect,t(`effect`),s.effect),endcaps:Pm(a.endcaps,t(`endcaps`),s.endcaps),variation:Hm(a.variation,t(`variation`),s.variation),shade:Gm(a.shade,t(`shade`),s.shade),separator:a.default_separator??s.default_separator,autoWrap:$m(a.autoWrap,t(`autoWrap`),s.autoWrap),padding:nh(a.padding,t(`padding`),s.padding),charset:a.charset??s.charset??`unicode`,updateNotice:eh(a.updateNotice,t(`updateNotice`),s.updateNotice),transitions:th(a.transitions,t(`transitions`),s.transitions),colorCompatibility:a.colorCompatibility??s.colorCompatibility??`truecolor`}}function QL(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,charset:e.charset,width:t}}function $L(e){return{theme:e.theme,style:e.style,effect:e.effect,preset:e.preset,variation:e.variation,shade:e.shade,transitions:e.transitions}}function eR(e){return{preset:{effective:e.preset,customized:e.presetCustomized,bundled:bL(e.preset)},endcaps:{effective:e.endcaps},variation:{effective:e.variation},shade:{effective:e.shade},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding},updateNotice:{effective:e.updateNotice},transitions:{effective:e.transitions}}}const tR={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function nR(e){return e?.prState===void 0?e?.prError===void 0?e?.prEarlier===void 0?`-`:`earlier-${e.prEarlier}`:`failed`:e.prState}const rR=10*1e3;function iR(e,t,n,r){let i=n-(t*1e3-r);if(i<3e5||e<=0)return;let a=e/i,o=(100-e)/a;return Math.max(0,Math.round(o/6e4))}function aR(e,t){if(!(t<60))return e*3600/t}function oR(e,t,n,r){let i=r-t;if(i<50||i>rR)return;let a=n-e;if(!(a<=0))return a*1e3/i}function sR(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=oR(t.input,t.atMs,n.input,n.atMs),i=oR(t.output,t.atMs,n.output,n.atMs),a=oR(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 cR(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>rR)continue;let o=oR(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function lR(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function uR(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>lR(h.hostname())),i=n(`user`,()=>h.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function dR(e,t){let n=new Map;for(let[t,r]of Object.entries(e.variables))n.set(t,r);for(let[t,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))n.set(`${t}.${e}`,i);let r=[],i=new Set,a=t=>x_(t,e.helpers).keys(),o=e_(e,t);for(let e of mm){let t=o[e];if(hm(t))for(let e of a(t))r.push(e)}for(let n of pg($g(e,t).node)){if(n.when)for(let e of a(n.when))r.push(e);if(n.kind!==`segment`)continue;let t=e.segments[n.name];if(t){for(let e of[t.template,t.when,t.bg,t.fg])if(e)for(let t of a(e))r.push(t)}}let s=new Set;for(;r.length>0;){let e=r.pop();for(let t of pR(n,e)){if(i.has(t))continue;i.add(t);let e=n.get(t);if(e){if(e.kind===`input`)s.add(e.path);else if(e.kind===`template`)for(let t of a(e.template))r.push(t)}}}return s}function fR(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=dR(e,n);return t.set(n,i),i}}function pR(e,t){let n=t;for(;n.length>0;){if(e.has(n))return[n];let t=n.lastIndexOf(`.`);if(t<0)break;n=n.slice(0,t)}let r=`${t}.`,i=[];for(let t of e.keys())t.startsWith(r)&&i.push(t);return i}function mR(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function hR(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.timeSinceCommit`)&&{showTimeSinceCommit:!0},...Object.keys(tR).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}async function gR(e,t,n,r,i,a,o,{configPath:s,...c}){let l=e=>mR(i,e),u=TT(t).getTime(),d=o.tmux??null,f=(e,t,n)=>t?n().catch(t=>I(`${e}: ${String(t)}`)):Promise.resolve(F),[p,m,h,g,_,v,y,b,x,S,C]=await Promise.all([f(`git`,l(`git`),()=>n.gitProvider.getGitInfo(r??e.workspace?.current_dir,hR(i),e.workspace?.project_dir)),f(`session`,l(`session.cost`)||l(`session.tokens`)||l(`burn`),()=>n.usageStore.getUsageInfo(e.session_id,e)),f(`today`,l(`today`),()=>n.usageStore.getTodayInfo(e,o.claudeConfigDir,t)),f(`context`,l(`context`)||l(`autocompact`),()=>n.contextProvider.getContextInfo(e)),f(`metrics`,l(`metrics`)||l(`burn`),()=>n.metricsProvider.getMetricsInfo(e.session_id,e)),f(`activity`,l(`activity`),()=>n.activityProvider.getActivityInfo(e.session_id,e)),f(`tmux`,l(`tmux.session`),()=>d===null?Promise.resolve(F):n.tmuxService.getSessionName(d)),f(`cache`,l(`cache`),()=>FL(e.transcript_path)),f(`speed`,l(`speed`),()=>n.usageStore.observeSpeed(e.session_id,e.transcript_path,u)),f(`memento`,l(`memento`),()=>n.mementoProvider.getCeiling(RL({sessionId:e.session_id,projectDir:e.workspace?.project_dir??``,cwd:r??e.workspace?.current_dir??``},o))),f(`autocompact`,l(`autocompact`),()=>Promise.resolve(n.autoCompact(di(ui(o.claudeConfigDir)))))]),ee=[],te=e=>{if(e.kind===`failed`){ee.push(e.reason);return}return e.kind===`ok`?e.value:void 0},ne=wR(p,u);ee.push(...ne.failures);let re=uR(o);ee.push(...re.failures);let ie=te(m),ae=te(h),w=te(g),T=te(_),oe=te(v),E=te(y),se=te(b),ce=yR(S);S.kind===`failed`&&ee.push(`memento: ${S.reason}`);let le=_R(C,w?.maxTokens);C.kind===`failed`&&ee.push(`autocompact: ${C.reason}`);for(let e of ee)n.log(`warn`,`provider fetch failed: ${e}`);let ue=e.rate_limits?.five_hour,de=e.rate_limits?.seven_day,fe=ue?iR(ue.used_percentage,ue.resets_at,18e6,u):void 0,pe=de?iR(de.used_percentage,de.resets_at,6048e5,u):void 0,me=ie?.session.cost,he=T?.sessionDuration,ge=l(`burn`)&&me!=null&&he!=null?aR(me,he):void 0,_e=te(x),ve=_e===void 0?void 0:sR(_e),ye=_e===void 0?void 0:cR(_e),be=ve!==void 0||ye!==void 0?{...ve,...ye!==void 0&&{history:ye}}:void 0,xe=CR(process.env.HOME??process.env.USERPROFILE),D=e.workspace?{...e.workspace,current_dir:CR(e.workspace.current_dir)??``,project_dir:CR(e.workspace.project_dir)??``,added_dirs:(e.workspace.added_dirs??[]).map(e=>CR(e)??e)}:e.workspace,Se=ie===void 0?void 0:SR({cost:ie.session.cost,tokens:ie.session.tokens}),Ce=ae===void 0?void 0:{cost:ae.cost,tokens:ae.tokens},we=T===void 0?void 0:SR({lastResponseTime:T.lastResponseTime,responseTime:T.responseTime,sessionDuration:T.sessionDuration,messageCount:T.messageCount,nonPrompts:T.nonPrompts,linesAdded:T.linesAdded,linesRemoved:T.linesRemoved}),Te=oe===void 0?void 0:bR(oe);return{...e,...D!==void 0&&{workspace:D},...xe!==void 0&&{home:xe},...ne.git!==void 0&&{git:ne.git},...d!==null&&{tmux:{pane:d.pane,...E!==void 0&&{session:E}}},host:re.host,...eR(a),history:n.history(e.session_id),navigation:{back:n.navigation(e.session_id)},...c,...s!==null&&{configPath:s},resumeCommand:XL(D,e.session_id,o.claudeConfigDir),...Se!==void 0&&{session:Se},...Ce!==void 0&&{today:Ce},...ge!==void 0&&{burn:{costPerHour:ge}},...be!==void 0&&{speed:be},...l(`block`)&&ue!==void 0&&{block:{nativeUtilization:ue.used_percentage,resetsAt:ue.resets_at,...fe!==void 0&&{etaMinutes:fe}}},...de!==void 0&&{weekly:{percentage:de.used_percentage,resetsAt:de.resets_at,...pe!==void 0&&{etaMinutes:pe}}},...se!==void 0&&{cache:{expiresAt:se}},...w!==void 0&&{context:{totalTokens:w.totalTokens,contextLeft:w.contextLeftPercentage}},...we!==void 0&&{metrics:we},...Te!==void 0&&{activity:Te},...ce!==void 0&&{memento:ce},...le!==void 0&&{autocompact:le}}}function _R(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return Bk(e.value,t)}}const vR=e=>e.trim().split(`
168
+ `).at(-1).trim();function yR(e){switch(e.kind){case`absent`:return;case`failed`:return{error:vR(e.reason)};case`ok`:{let{ceiling:t,session:n}=e.value;return{ceiling:t===`off`?0:t,off:t===`off`,session:n??``}}}}function bR(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=xR(e.running),i=xR(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 xR(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function SR(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 CR(e){return e===void 0||e.length===0||l.sep!==`\\`?e:e.replace(/\\/g,`/`)}function wR(e,t){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let n=e.value,r=[],i=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){r.push(`git.${e}: ${t.reason}`);return}return t.value}},a=i(`aheadBehind`,n.aheadBehind),o=i(`sha`,n.sha),s=i(`operation`,n.operation),c=i(`timeSinceCommit`,n.committedAt),l=c===void 0?void 0:Math.floor((t-c)/1e3),u=i(`stash`,n.stashCount),d=i(`upstream`,n.upstream),f=n.upstream===void 0?void 0:i(`tracking`,Lw(n.upstream,n.aheadBehind)),p=i(`repoName`,n.repoName),m=i(`repoUrl`,n.repoUrl),h=n.pullRequest===void 0?void 0:Rw(n.pullRequest,n.head),g={};switch(h?.kind){case`ok`:g={prNumber:h.value.number,prState:h.value.state,prUrl:h.value.url};break;case`failed`:r.push(`git.pr: ${h.reason}`),g={prError:h.reason};break;case`earlier`:g={prEarlier:h.value.state};break;case`absent`:case void 0:break}return{git:{branch:n.branch,status:n.status,...a!==void 0&&{ahead:a.ahead,behind:a.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...o!==void 0&&{sha:o},...s!==void 0&&{operation:s},...l!==void 0&&{timeSinceCommit:l},...u!==void 0&&{stash:u},...d!==void 0&&{upstream:d},...f!==void 0&&{tracking:f},...p!==void 0&&{repoName:p},...m!==void 0&&{repoUrl:m},...g},failures:r}}const TR={theme:e=>e.theme.kind===`decided`?e.theme.name:null,preset:e=>e.preset,style:e=>e.style.kind===`decided`?e.style.name:null,effect:e=>e.effect.kind===`decided`?e.effect.name:null,endcaps:e=>e.endcaps,variation:e=>e.variation,shade:e=>e.shade,transitions:e=>e.transitions?Km:qm,autoWrap:e=>e.autoWrap?Km:qm,padding:e=>String(e.padding),updateNotice:e=>e.updateNotice?Km:qm},ER=Object.entries(xa),DR=new Set(Sa.map(e=>e.sessionKey)),OR=()=>!1;function kR(e,t){return ZL(e,e=>DR.has(e)?t(e):null,OR)}const AR=[`preset`,`theme`];function jR(e,t,n){let r=new Set(AR.slice(0,n).map(e=>xa[e].sessionKey));return ZL(e,e=>r.has(e)?t(e):null,OR)}function MR(e,t){let n=Array.from({length:AR.length+1},(n,r)=>jR(e,t,r));return e=>{let t=AR.indexOf(e);return n[t===-1?AR.length:t]}}function NR(e,t,n,r){return e.flatMap(([e,i])=>{let a=TR[e](t);return a===null||a===TR[e](n(e))?[]:[{...i,value:a,target:r(i)}]})}function PR(e,t,n){return TR[n](kR(e,t))}function FR(e,t){let n=kR(e,t);return NR(ER,n,MR(e,t),t=>IR(e,n.preset,t.configKey))}function IR(e,t,n){return n in(Qg(e.presets,t).globals??{})?qD(t,n):n}function LR(e,t,n){let r=Zg(t(xa.preset.sessionKey),e.globals.preset,e.presets),i=JD(n);return{key:i?.scope===`globals`?IR(e,r,i.field):n,globals:e_(e,r)}}function RR(e,t){let{preset:n}=kR(e,t);return VR(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:Mg(a,s);return c===void 0||jg(c)===jg(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function zR(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Xg(e.presets).flatMap(n=>{let i=VR(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 kg(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:Mg(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const BR=new WeakMap;function VR(e,t){let n=BR.get(e)??new Map;BR.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...pg($g(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Dg(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 HR(e,t){let n=kR(e,t);return{from:n.preset,globals:Qg(e.presets,n.preset).globals??{},picks:NR(ER.filter(([e])=>e!==`preset`),n,MR(e,t),e=>e.configKey),placements:RR(e,t)}}function UR(e,t){return ZL({...e,globals:{palette:t},presets:{}},()=>null,OR)}function WR(e,t){let n=kR(e,t),r=TR.theme(n);if(r===null)return{kind:`rule`};let i=UR(e,r),a=e_(e,n.preset),o=Object.fromEntries(vg.map(e=>[e,TR[e](a[e]===void 0?n:i)]));return{kind:`look`,theme:r,look:o,differs:vg.some(e=>o[e]!==TR[e](i))}}function GR(e){return{sessionKeys:Sa.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...ED(e)?yL.map(t=>qD(t,e)):[],...KD(e)?lm().map(t=>GD(t,e)):[]]}}function KR(e){return new Set(Sa.map(e=>e.configKey).filter(t=>GR(t).fileKeys.some(t=>YR(e,JR(t)))))}function qR(e,t,n){let r=FR(e,n),i=new Set(r.map(e=>e.configKey)),a=Da(e=>i.has(xa[e].configKey)||t.has(xa[e].configKey)),o=WR(e,n);return{unsaved:r.length+RR(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function JR(e){let t=JD(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return YD(t)}function YR(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&YR(e[n],r)}const XR=lm(),ZR=new Set(XR),QR=new Set(Am),$R=e=>e?ZR.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${XR.join(`, `)})`}:{ok:!1,reason:`theme name is required`},ez=e=>e?QR.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Am.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},tz=new Set([`1`,`true`]),nz=new Set([`0`,`false`]),rz={endcaps:ez,theme:$R,"toolbar-expanded":e=>tz.has(e)?{ok:!0,value:`1`}:nz.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},iz=gM(rz,`state`,dz);function az(e,t){return iz.register(e,t)}function oz(e){return iz.gateFor(e)}function sz(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:o_(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 cz(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(rz,e.key))}function lz(e,t,n){let r=Oa.get(n);if(r!==void 0)return PR(e,t,r);for(let[,t]of Cg(e))if(t.key===n)return t.default??null;return null}function uz(e){let t=zj(e);return cz(Object.values(e.actions).flatMap(e=>sz(e,t)))}function dz(e){return mM(uz(e))}const fz=`update.dismissed`,pz=`updateNotice`,mz=xa.updateNotice.sessionKey;function hz(e){return e.kind===`source`?e.newer.digest:bi(e.newer)}const gz=e=>`${e.version} [${Gh(e.digest)}]`;function _z(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:gz(e.newer),running:gz(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:bi(e.newer),running:bi(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${Si}@${bi(e.newer)}`,`install`]}}}}const vz={kind:`idle`},yz={kind:`running`};function bz(e,t,n){if(e===null)return[];let r=hz(e);if(!n.enabled||n.dismissed===r)return[];let i=_z(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(`
169
+ `),c=Kn([{verb:Tn,args:[s]}]),l=t.kind===`running`?Nh(`[${i.busy}]`,c):Nh(`[${i.act}]`,Kn([{verb:Ln,args:[n.sessionId]}]));return[{severity:Mh,message:s,lines:[[Nh(a,c),l,Nh(`[dismiss]`,Kn([{verb:yn,args:[n.sessionId,fz,r]}])),Nh(`[disable]`,Kn([{verb:N,args:[n.sessionId,pz,`false`]},{verb:yn,args:[n.sessionId,mz,`false`]}]))],...o.map(e=>[Nh(e,c)])]}]}function xz(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 Sz(e){switch(e.kind){case`current`:return[`info`,`build: current ${gz(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${gz(e.source)}, running ${gz(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function Cz(e){switch(e.kind){case`current`:return[`info`,`release: current ${bi(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${bi(e.latest)}, running ${bi(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${bi(e.installed)}, latest ${bi(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function wz(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const Tz=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function Ez(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=Tz(e.stderr)??e.error??Tz(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function Dz(){let e=[vM(pz,[`false`]),az(mz,[`false`]),az(fz,[])];return()=>e.forEach(e=>e())}function Oz(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=vz,d=null,f=wz(s),p=wz(s),m=()=>xz(c,l);function h(){let e=m(),t=e===null?null:hz(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:az(fz,[t])})}function g(){c=Xh(t,qh),f(Sz(c)),h()}async function _(){l=wi(Et,await Ci(Si,a,i)),p(Cz(l)),h()}return{arm(){Dz(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>bz(m(),u,e),act(){let e=m();if(e===null)throw new K(`apply-update: nothing newer is known to apply`);let t=_z(e);if(u.kind===`running`)throw new K(`apply-update: already ${t.busy}`);u=yz,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),Me({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=vz,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=Ez(n);u={kind:`failed`,identity:hz(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}var kz=class{static CACHE_DIR=ze();static USAGE_CACHE_DIR=l.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=l.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=l.join(this.LOCKS_DIR,e);if(!r.existsSync(t))return!1;try{let n=r.readFileSync(t,`utf-8`),i=parseInt(n.trim(),10);if(isNaN(i))return D(`Invalid PID in lock file ${e}, removing stale lock`),r.unlinkSync(t),!1;try{return process.kill(i,0),!0}catch(n){return n.code===`ESRCH`?(D(`Removing stale lock file ${e} for dead process ${i}`),r.unlinkSync(t),!1):(D(`Error checking process ${i} for lock ${e}:`,n),!0)}}catch(t){return D(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=l.join(this.LOCKS_DIR,e),i=Date.now(),a=String(process.pid);for(;Date.now()-i<t;)try{return await r.promises.writeFile(n,a,{flag:`wx`}),D(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await de(50);else throw e}return D(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=l.join(this.LOCKS_DIR,e);try{await r.promises.unlink(t),D(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&D(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([r.promises.mkdir(this.CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),r.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){D(`Failed to create cache directories:`,e)}}static createProjectHash(e){return ae(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=l.join(this.USAGE_CACHE_DIR,`${e}.json`),i=`${e}.usage.lock`;for(let a=0;a<3;a++){if(this.isLocked(i)){D(`Cache for ${e} is locked, waiting...`),await de(75);continue}try{let i=await r.promises.readFile(n,`utf-8`),a=JSON.parse(i);return!t||a.timestamp>=t?(D(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(a.data)):(D(`${e} cache outdated: cache=${a.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return D(`No shared ${e} usage cache found`),null;D(`Attempt ${a+1} failed to read ${e} cache: ${t.message}. Retrying...`),await de(75)}}return D(`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 i=`${e}.usage.lock`;if(!await this.acquireLock(i)){D(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let i=l.join(this.USAGE_CACHE_DIR,`${e}.json`),a=JSON.stringify({data:t,timestamp:n||Date.now()});await r.promises.writeFile(i,a,`utf-8`),D(`[CACHE-SET] ${e} disk cache stored`)}catch(t){D(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(i)}}};const Az={"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 jz=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 kz.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await kz.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new ee(this.GITHUB_PRICING_URL),n=ue({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){D(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let r=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){D(`Response too large`),n.destroy(),e(null);return}r+=t}),t.on(`end`,()=>{try{let t=JSON.parse(r),n=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(D(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),D(`Pricing last updated: ${n?.updated||`unknown`}`),e(i)):(D(`Invalid pricing data structure`),e(null))}catch(t){D(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{D(`Response error:`,t),e(null)})});n.on(`error`,t=>{D(`Request error:`,t),e(null)}),n.on(`timeout`,()=>{D(`Request timeout`),n.destroy(),e(null)}),n.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return D(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return D(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),D(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(D(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(Az).length} models`),this.executionCache=Az,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(Az).length} models`),Az)}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 D(`[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),D(`[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 Mz=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function Nz(e){if(typeof e==`string`)return Mz.exec(e)?.[1]}function Pz(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 Fz(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 Iz(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=Pz(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`?Nz(Fz(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 Lz(e){if(e!==void 0)return[e];let t=g();return[p(t,`.config`,`claude`),p(t,`.claude`)].filter(e=>a(e))}async function Rz(e){let t=[];for(let n of e){let e=p(n,`projects`);if(a(e))try{let n=await OL(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=p(e,r.name);t.push(n)}}catch(t){D(`Failed to read projects directory ${e}:`,t)}}return t}async function zz(e,t,n){let r=[],i=p(t,e,`subagents`);try{let t=(await OL(i)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let a of t){let t=p(i,a);if(n?.has(t)){r.push(t);continue}try{let n=(await kL(t,`utf-8`)).split(`
170
+ `)[0];n&&JSON.parse(n).sessionId===e&&r.push(t)}catch{D(`Failed to check agent file ${t}`)}}}catch(e){D(`Failed to read subagents directory ${i}:`,e)}return r}function Bz(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(Hz(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=Fz(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||Vz.test(r)?`claude-code`:`prompt`}const Vz=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function Hz(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}const Uz=new Map;async function Wz(e){try{let t=await AL(e),n=t.size,r=Uz.get(e);if(r&&r.mtime===t.mtimeMs&&r.size===n)return D(`[parse-cache] hit ${e}`),Uz.delete(e),Uz.set(e,r),r.entries;let i;return n>1048576?(D(`Using streaming parser for large file ${e} (${Math.round(n/1024)}KB)`),i=await Yz(e)):i=await qz(e),D(`Parsed ${i.length} entries from ${e}`),n>5242880?i:(Uz.delete(e),Uz.size>=16&&Uz.delete(Uz.keys().next().value),Uz.set(e,{mtime:t.mtimeMs,size:n,entries:i}),i)}catch(t){if(t.code===`ENOENT`)return D(`Transcript not present yet: ${e}`),[];throw t}}function Gz(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=Bz(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:Iz(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 Kz(e){let t=[];for(let n of e.split(`
171
+ `))if(n.trim())try{let e=Gz(JSON.parse(n));e&&t.push(e)}catch(e){D(`Failed to parse JSONL line: ${e}`);continue}return t}async function qz(e){return Kz(await kL(e,`utf-8`))}async function Jz(e,t){let n=await jL(e,t===void 0?void 0:{offset:t.offset,ino:t.ino});if(n.kind!==`ok`)return n;let{buf:r,start:i,stamp:a,ino:o,reset:s}=n.value,c=r.lastIndexOf(10);return P(c<0?{entries:[],cursor:{offset:i,stamp:a,ino:o},reset:s}:{entries:Kz(r.subarray(0,c+1).toString(`utf-8`)),cursor:{offset:i+c+1,stamp:a,ino:o},reset:s})}async function Yz(e){return new Promise((t,n)=>{let r=[],a=i(e,{encoding:`utf8`}),o=fe({input:a,crlfDelay:1/0});o.on(`line`,e=>{let t=e.trim();if(t)try{let e=Gz(JSON.parse(t));e&&r.push(e)}catch(e){D(`Failed to parse JSONL line: ${e}`)}}),o.on(`close`,()=>{t(r)}),o.on(`error`,t=>{D(`Streaming parser error for ${e}:`,t),n(t)}),a.on(`error`,t=>{D(`File stream error for ${e}:`,t),n(t)})})}var Xz=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}};function Zz(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 Qz=new Map,$z={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},eB={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function tB(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function nB(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function rB(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}async function iB(e,t,n,r){let i=tB(new Date(nB())),a=e&&!t?e:void 0,o=a?.entries??0,s=a?.cost??0,c=a?{...a.breakdown}:rB(),l=new Map;if(a)for(let[e,t]of a.days)e>=i&&l.set(e,{...t});for(let e of n){let t=e.message?.usage;if(!t)continue;o++;let n=e.costUSD??await jz.calculateCostForEntry(e.raw);s+=n,c.input+=t.input_tokens||0,c.output+=t.output_tokens||0,c.cacheCreation+=t.cache_creation_input_tokens||0,c.cacheRead+=t.cache_read_input_tokens||0;let r=tB(new Date(e.timestamp));if(r<i)continue;let a=l.get(r)??{...$z};a.cost+=n,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,l.set(r,a)}return{cursor:r,entries:o,cost:s,breakdown:c,days:l}}function aB(e){let t=0,n=0,r=rB(),i=new Map;for(let 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)??{...$z};n.cost+=t.cost,n.input+=t.input,n.output+=t.output,n.cacheCreation+=t.cacheCreation,n.cacheRead+=t.cacheRead,i.set(e,n)}}if(t===0)return{sessionInfo:eB,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}}async function oB(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))}var sB=class{sessions=new Map;flight=new Xz;seeded=new Map;seededDay=``;rescanIntervalMs;speedFlight=new Xz;staleAgeMs;log;renderTally={hits:0,misses:0};sweeps=0;scans={seed:0,rescan:0};sweepTimer=null;constructor(e={}){this.log=e.logger??Ft,this.staleAgeMs=e.staleAgeMs??864e5,this.rescanIntervalMs=e.rescanIntervalMs??6e4;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,seeds:this.scans.seed,rescans:this.scans.rescan}}async getUsageInfo(e,t){let n=await this.ingest(e,t?.transcript_path,this.renderTally);if(n.kind===`failed`)return n;let r=n.kind===`ok`?n.value.sessionInfo:eB,i=t?.cost?.total_cost_usd??null;return P({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e,t,n){let r=tB(TT(n)),i=Lz(t);try{await this.ensureSeeded(r,i,n*1e3)}catch(e){return I(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let a=await this.ingest(e?.session_id??``,e?.transcript_path,this.renderTally);if(a.kind===`failed`)return a;let o=i.map(e=>p(e,`projects`)+m),s={...$z},c=!1;for(let[t,{record:n}]of this.sessions){let i=n?.transcriptPath??``,a=t===e?.session_id||o.some(e=>i.startsWith(e))?n?.days??Qz:Qz;c||=a.has(r);let l=a.get(r)??$z;s.cost+=l.cost,s.input+=l.input,s.output+=l.output,s.cacheCreation+=l.cacheCreation,s.cacheRead+=l.cacheRead}return c?P({cost:s.cost,tokens:s.input+s.output+s.cacheCreation+s.cacheRead,tokenBreakdown:{input:s.input,output:s.output,cacheCreation:s.cacheCreation,cacheRead:s.cacheRead},date:r}):F}async observeSpeed(e,t,n){if(!e)return F;let r=wL(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,this.renderTally,r);if(i.kind===`failed`)return i;let a=Zz(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),{ring:o}=this.hold(e),s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);return o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift(),P({...s!==void 0&&{prev:s},cur:a,samples:[...o]})})}async ingest(e,t,n,r){if(!e)return F;let i=r??wL(t),a=this.see(e)?.record;if(a&&i!==``&&a.transcriptStamp===i)return n.hits++,P(a);if(!t)return a?P(a):F;n.misses++;let o;try{o=await this.flight.run(`${e}:${i}`,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:s,outcome:c}=o;if(c.kind!==`ok`)return c;let l={files:c.value.files,sessionInfo:c.value.sessionInfo,days:c.value.days,transcriptStamp:c.value.mainStamp,transcriptPath:t};return this.sessions.get(e)?.record===s&&(this.hold(e).record=l),P(l)}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:[]};return this.sessions.set(e,n),n}async refold(e,t,n){let r=await zz(e,d(t),n===void 0?void 0:new Set(n.files.keys())),i=new Map,a=``;for(let e of[t,...r]){let r=n?.files.get(e),o=await Jz(e,r?.cursor);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{entries:s,cursor:c,reset:l}=o.value;i.set(e,await iB(r,l,s,c)),e===t&&(a=c.stamp)}return P({files:i,...aB(i),mainStamp:a})}ensureSeeded(e,t,n){this.seededDay!==e&&(this.seeded.clear(),this.seededDay=e);let r=t.join(`\0`),i=this.seeded.get(r);if(!i){let e=this.seed(t,`seed`),i={done:e,scanning:e,startedAtMs:n};return this.seeded.set(r,i),this.settle(r,i,e),e}return i.scanning===void 0&&n-i.startedAtMs>=this.rescanIntervalMs&&(i.startedAtMs=n,i.scanning=this.seed(t,`rescan`),this.settle(r,i,i.scanning)),i.done}settle(e,t,n){n.then(()=>{t.scanning=void 0},n=>{this.log(`warn`,`usageStore scan: ${n instanceof Error?n.message:String(n)}`),this.seeded.get(e)===t&&this.seeded.delete(e)})}async scanned(){await Promise.allSettled([...this.seeded.values()].map(e=>e.scanning))}async seed(e,t){let n=Date.now(),r=nB(),i=await Rz(e),a=[];for(let e of i){let t;try{t=await OL(e)}catch{continue}for(let n of t){if(!n.endsWith(`.jsonl`))continue;let t=p(e,n),i;try{i=await AL(t)}catch{continue}i.mtimeMs<r||a.push({sessionId:n.slice(0,-6),path:t,stamp:TL(i)})}}let o={hits:0,misses:0};await oB(a,8,async e=>{let n=await this.ingest(e.sessionId,e.path,o,e.stamp);n.kind===`failed`&&this.log(`warn`,`usageStore ${t}: ${n.reason}`)}),this.log(`info`,`usageStore ${t} sessions=${a.length} read=${o.misses} dirs=${e.join(`,`)} ms=${Date.now()-n}`),this.scans[t]++}sweepStale(){let e=Date.now(),t=0,n=0,r=0;for(let[i,{lastSeenAt:a,record:o}]of this.sessions)if(!(e-a<=this.staleAgeMs)){if(o?.days.has(this.seededDay)){n++;continue}this.sessions.delete(i),t++,o===void 0&&r++}return t>0&&this.sweeps++,(t>0||n>0)&&this.log(`info`,`usageStore sweep dropped=${t} noRecord=${r} held=${n}`),t}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.sessions.clear(),this.seeded.clear()}},cB=class{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 D(`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);D(`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){try{D(`Calculating context tokens from transcript: ${e}`);let n=await Wz(e);if(n.length===0)return D(`No entries in transcript`),F;let r=null;for(let e=n.length-1;e>=0;e--){let t=n[e];if(t&&t.message?.usage?.input_tokens&&t.isSidechain!==!0){r=t,D(`Context segment: Found most recent entry at ${t.timestamp.toISOString()}, stopping search`);break}}if(r?.message?.usage){let e=r.message.usage,n=(e.input_tokens||0)+(e.cache_read_input_tokens||0)+(e.cache_creation_input_tokens||0);return D(`Most recent main chain context: ${n} tokens (limit: ${t})`),P({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return D(`No main chain entries with usage data found`),F}catch(e){return I(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return P(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}},lB=class{states=new Map;constructor(e,t,n=256){this.empty=e,this.step=t,this.maxSessions=n}async read(e,t){let n=this.states.get(e),r=wL(t);if(n&&r!==``&&n.cursor.stamp===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await Jz(t,n?.cursor);if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:n?.value??this.empty};let{entries:a,cursor:o,reset:s}=i.value,c=s||n===void 0?this.empty:n.value;for(let e of a)c=this.step(c,e);for(this.touch(e,{cursor:o,value:c});this.states.size>this.maxSessions;){let e=this.states.keys().next().value;if(e===void 0)break;this.states.delete(e)}return{kind:`ok`,value:c}}touch(e,t){this.states.delete(e),this.states.set(e,t)}};const uB={messageCount:0,nonPrompts:0,recent:[]},dB=new Set([`turn`,`interrupt`,`claude-code`]);function fB(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!dB.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function pB(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 mB=class{fold=new lB(uB,fB);async getMetricsInfo(e,t){if(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return F;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?I(`metrics (${e}): ${n.reason}`):P({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:pB(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const hB={command:null,todos:[],pending:[],done:[]};function gB(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 _B(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 vB(e,t){if(t.isSidechain)return e;let n=_B(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=gB(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 yB(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>gB(e,t.name),[]),done:e.done}}var bB=class{fold=new lB(hB,vB);async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?I(`activity (${e}): ${n.reason}`):P(yB(n.value))}};function xB(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function SB(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 CB(e,t,n,r){return SB(Ne(xB(e,t,n,r)),n)}async function wB(e,t,n){return SB(await Me(xB(e,t,n)),n)}const TB=e=>`${e.socket}\n${e.pane}`;var EB=class{names=new Map;asking=new Xz;constructor(e=Date.now){this.now=e}getSessionName(e){let t=TB(e),n=this.names.get(t);if(n&&this.now()-n.at<3e4)return Promise.resolve(n.outcome);let r=this.asking.run(t,()=>this.ask(t,e));return n?Promise.resolve(n.outcome):r}async ask(e,t){D(`Getting tmux session name for pane ${t.pane} on ${t.socket}`);let n=await wB(t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]),r=n.kind===`ok`?n.stdout.trim():``,i=n.kind===`ok`?r?P(r):F:I(n.reason);for(this.names.delete(e),this.names.set(e,{outcome:i,at:this.now()});this.names.size>64;)this.names.delete(this.names.keys().next().value);return i}};const DB=e=>JSON.stringify([e.sessionId,e.projectDir,e.cwd,e.claudeConfigDir,e.env===void 0?null:tt.map(t=>e.env?.[t]??null)]);var OB=class{readings=new Map;inFlight=new Map;constructor(e,t=Date.now){this.edge=e,this.now=t}getCeiling(e){let t=DB(e),n=this.readings.get(t);if(n&&this.now()-n.at<1e4)return Promise.resolve(n.outcome);let r=this.inFlight.get(t)??this.fetch(t,e);return n?Promise.resolve(n.outcome):r}fetch(e,t){let n=this.edge.locate(t),r=(n.kind===`ok`?this.edge.read(n.value,t):Promise.resolve(n)).then(t=>{if(this.inFlight.get(e)!==r)return t;for(this.readings.delete(e),this.readings.set(e,{outcome:t,at:this.now()});this.readings.size>64;)this.readings.delete(this.readings.keys().next().value);return t}).finally(()=>{this.inFlight.get(e)===r&&this.inFlight.delete(e)});return this.inFlight.set(e,r),r}move(e,t){let n=this.edge.locate(e);if(n.kind!==`ok`)throw Error(n.kind===`failed`?n.reason:`memento is not installed or not enabled for this project`);let r=DB(e);try{this.edge.move(n.value,e,t)}finally{this.readings.delete(r),this.inFlight.delete(r),this.fetch(r,e)}}};function kB(e){return{gitProvider:new yT({watchers:e.watchers,logger:e.logger}),usageStore:new sB({logger:e.logger}),contextProvider:new cB,metricsProvider:new mB,activityProvider:new bB,tmuxService:new EB,mementoProvider:new OB(YL()),autoCompact:zk,log:e.logger}}function AB(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const jB={kind:`hidden`},MB={kind:`shown`};function NB(e,t){try{return AB(e,t)?MB:jB}catch(e){return{kind:`failed`,message:e instanceof Error?e.message:String(e)}}}function PB(e,t){let n=G.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function FB(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function IB({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function LB({text:e,placement:t,lead:n,trail:r}){return{text:RB(e),placement:t,...n!==void 0&&{lead:RB(n)},...r!==void 0&&{trail:RB(r)}}}function RB(e){let t=e.blankCopy(e.plain);t.style=ih(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(ih(i).clearMetaAndLinks(),n,r);return t}function zB(e){let t=IB(e);if(t.length===1)return e.text;let n=PB(t);return n.style=e.text.style,n}function BB(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=PB(e,a).pad(o),d=new G(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:PB([d,...c],a)},...l.length>0&&{trail:PB([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(FB(u,n,p),[{text:u,...f}])}const VB=RegExp(`\\x1b\\[[0-9;]*m|${Ul.source}`,`g`);function HB(e){return Math.max(0,...e.split(`
172
+ `).map(e=>L(e.replace(VB,``))))}function UB(e,t){let n=()=>e.map(e=>({owner:zB(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=Oh(e.map(zB),t).split(`
173
+ `);if(i.length>1)return n();let a=Math.max(0,t.width-HB(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];FB(c,c.cellLength+a,n)}),n()}function WB(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=GB(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:ih(a.style)};if(e.style.link){i();let r=GB([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function GB(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>KB(e.frag,n?n.add(e.style):e.style)),i=G.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function KB(e,t){let n=e.copy();return n.style=t,n}function qB(e,t){if(e.look===void 0)throw Error(`${t} read the render's look before any render resolved one`);return e.look}function JB(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,YB(e,t,o,n,r,i));return i}function YB(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=o_(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=Ta.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=o_(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=o_(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:QB(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:QB(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(`ceiling`in n)return{kind:`ceiling`,args:xP(n)};if(`slash`in n)return{kind:`slash`,line:n.slash};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:QB(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 XB(e){return e.kind===`do`?XB(e.head):e}function ZB(e){switch(XB(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`ceiling`:case`slash`:case`do`:return!1}}function QB(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function $B(e,t){return e.has(t)?R_(e.read(t)):``}function eV(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function tV(e,t,n,r){let i=new G(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function nV(e,t,n=!1){let r=new H({link:t,bold:n?!0:void 0}),i=new G(e.plain,{style:H.combine([ih(e.style),r])});for(let t of e.spans)i.stylize(H.combine([ih(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function rV(e,t){return Math.max(e.members.indexOf($B(t,e.stateVar)),0)}function iV(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=$B(r,e.stateVar);return{effects:[{verb:yn,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=$B(r,e.stateVar);return{effects:[{verb:yn,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=$B(r,e.stateVar);return{effects:[{verb:yn,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(rV(e,r)+1)%e.members.length];return{effects:[{verb:yn,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:bn,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:xn,args:[eV(e.text,Aw(r))]}],active:!1};case`open`:return{effects:[{verb:Sn,args:[eV(e.target,Aw(r))]}],active:!1};case`persist-literal`:{let t=$B(r,e.stateVar);return{effects:[{verb:N,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=$B(r,e.stateVar);return{effects:[{verb:N,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(rV(e,r)+1)%e.members.length];return{effects:[{verb:N,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:En,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:jn,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:Nn,args:[i]}],active:!1};case`redo`:return{effects:[{verb:Pn,args:[i]}],active:!1};case`back`:return{effects:[{verb:Fn,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:In,args:[i]}],active:!1};case`save`:return{effects:[{verb:Dn,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:On,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:kn,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:An,args:[i,eV(e.name,Aw(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:Rn,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:zn,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:Bn,args:[i,e.check,e.mark]}],active:!1};case`ceiling`:return{effects:[{verb:Hn,args:[i,...e.args]}],active:!1};case`slash`:return{effects:[{verb:Un,args:[i,e.line]}],active:!1};case`layout-op`:return{effects:[{verb:Mn,args:[i,e.key,iM(e.op)]}],active:!1};case`do`:{let a=iV(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>iV(e,t,void 0,r,i).effects)],active:a.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Mn,args:[i,e.key,iM(r)]}],active:!1}}}}function aV(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:tr(`action "${e}"`,n,t.members.length,rV(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 oV(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=n.store,{display:a,boundValue:o}=aV(e,XB(r),t,i),s=$B(i,`session.id`),{effects:c,active:l}=iV(r,a.plain,o,i,s);return nV(a,Kn(c),l)}function sV(e){return{action:{fn:(t,...n)=>oV(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function cV(e,t){return tV(`✕`,Kn([{verb:yn,args:[$B(e,`session.id`),t,Qn]}]),!1)}function lV(e,t,n){return new H({bgcolor:B.fromRgba(t),color:B.fromRgba(Np(e,t,n))})}function uV({tint:e,text:t}){return new H({bgcolor:B.fromRgba(e),color:B.fromRgba(t)})}function dV(e,t,n){return new H({color:B.fromRgba(sc(Cp(e,`warning`),t,Mp,n))})}function fV(e,t,n){return H.combine([lV(e,t,n),dV(e,t,n)])}function pV(e,t,n){return lV(e.palette,em(e.palette,e.disclosure,[t],n),n)}function mV(e){let t=B.fromRgba(Cp(e,`background`)),n=G.fromFragments(Xf.map(n=>new G(`▀`,{style:new H({color:B.fromRgba(Cp(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const hV=(e,t)=>{let n=typeof e==`string`?new G(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},gV=e=>new H({bold:e});function _V(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>hV(a,H.combine([pV(e,{...n,distribution:t},i),gV(o)]));let o=lV(e.palette,a,i);return(e,t,i,a)=>vV(i,H.combine([o,gV(a)]),r(t,n))}const vV=(e,t,n)=>hV(G.fromFragments([hV(e,t),hV(` `,t),mV(n)]));function yV(e,t){return t===void 0?(e,t,n)=>hV(n):(n,r,i)=>vV(i,void 0,t(r,e))}function bV(e,t,n,r,i){let a=lV(e.palette,i,r);return(e,r,i,o)=>hV(G.fromFragments([hV(o?`[`:` `,a),mV(n(r,t)),hV(o?`]`:` `,a)]))}function xV(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=>SV(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function SV(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function CV(e,t){return new G(e).truncate(t,{marker:`…`}).plain}function wV(e){return{current:null,drawnAt:e}}function TV(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 EV(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 DV(e){return new G(e).cellLength}function OV(e){return Math.max(1,e.width-e.chromeCols-2*e.padding)}function kV(e){return Math.max(1,OV(e)-(DV(`✕`)+2*e.padding+e.seamCols))}function AV(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 jV(e,t,n){let r=DV(`←`)+1+DV(`→`)+1,i=AV(e,t,n);return(i.length>1?AV(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function MV(e,t){let n=[];for(let t of e)n.length>0&&n.push(new G(` `)),n.push(t);let r=G.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function NV(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 PV(e,t,n){let r=e.compiled.get(t),i=r&&XB(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 FV(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=a.store,d=$B(u,`session.id`),f=`stateVar`in t?$B(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`?kV(a):OV(a):1/0,h=(r.kind===`led`?0:DV(`✕`)+1)+c.reduce((e,t)=>e+DV(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?jV(_.map(e=>e.cellLength),m,h):xV(g.entries,g.groups,i),y=parseInt($B(u,n.stateVar),10),b=e=>Math.max(0,v.findIndex(t=>t.some(t=>t.indices.includes(e)))),x=b(f===void 0?-1:t.options.indexOf(f)),S=Number.isInteger(y)?y<0?x:Math.min(y,v.length-1):0,C=v[S]??[],ee=e=>Kn([{verb:yn,args:[d,n.key,String(e)]}]),te=r.kind===`led`?[]:[{verb:yn,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],ne=r.kind===`own`&&r.onPick?te:[],re=e=>Kn([...iV(l,e,e,u,d).effects,...ne]),ie=(e,n)=>nV(e,re(t.options[n])),ae=r.kind===`led`?[]:[tV(`✕`,Kn(te),!1,s)];ae.push(...c.map(({glyph:e,option:r})=>tV(e,Kn([...iV(l,r,r,u,d).effects,{verb:yn,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),S>0&&ae.push(tV(`←`,ee(S-1),!1));let w=S<v.length-1?[tV(`→`,ee(S+1),!1)]:[];if(g===void 0){let e=C.flatMap(e=>e.indices);return[MV([...ae,...e.map(e=>ie(_[e],e)),...w],i)]}let T=new H({bold:!0}),oe=v.length>1?` ${S+1}/${v.length}`:``,E=C.length===1?[new G(`${C[0].label}${oe}`,{style:T})]:[],se=[MV([...ae,...E,...w],i)];for(let e of C){C.length>1&&se.push(MV([new G(e.label,{style:T})],i));let n=Math.max(...e.indices.map(e=>DV(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:Hf(a),s=` `.repeat(n-DV(e)+2),c=o===void 0?e:`${e}${s}${o}`;se.push(MV([ie(p(r,CV(c,m)),r)],i))}}return se}function IV(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{ww(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=NV(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=PV(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=EV(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]=FV(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,_V(u,dp(void 0),qB(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),dV(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function LV(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function RV(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 zV(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=n.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=$B(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return MV([],!0);let d=$B(o,t.stateVar),f=LV(l,d),p=e=>l[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let n=Kn(iV(s,p(e),p(e),o,c).effects);return m.set(e,n),n},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=nV(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):nV(yV(qB(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),Kn(iV(n.compiled.get(a),p(0),void 0,o,c).effects)),b=RV(e=>v(e).cellLength,u,DV(`◀`)+1+y.cellLength+1+DV(`▶`),kV(n),i),x=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return MV([...x(-1).reverse(),tV(`◀`,h(-1),!1),y,tV(`▶`,h(1),!1),...x(1)],!0)}function BV(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(ww(`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&&ZB(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=PV(e,n,`carousel`),l=EV(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 zV(n,c,e,_V(l,dp(void 0),qB(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function VV(e,t,n){let r=PV(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 HV(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 UV(e,t,n,r){let i=VV(e,t,n),a=r??$B(e.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,qB(e,`{{ ${n} }}`))}function WV(e,t,n){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(ww(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return mV(UV(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`},swatches:{fn:(r,i)=>{let a=VV(e,r,`swatches`),o=NV(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=EV(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]=FV(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,bV(s,qB(e,`{{ swatches }}`),a.paletteOf,c,s.bg),dV(s.palette,s.bg,c),u===0?[]:(()=>{let t=LV(l,$B(e.store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[HV(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const GV=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function KV(e,t,n,r){let i=Gp(e,n,r),a=(t,n)=>({text:t,colour:n,ink:Np(e,n,r)});return[[op(t).map((n,i)=>{let a=wp(e,n);return{text:GV[i%GV.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Cp(e,`warning`)),a(`error`,Cp(e,`error`))]]]}function qV(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new G(` ${e} `,{style:uV({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 G(e)),r.push(a)}return r}function JV(e,t,n,r,i){let a=KV(e,t,n,r).map(e=>qV(e,i)),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
174
+ `),...e]));return o.overflow=`ignore`,o.end=``,o}function YV(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(ww(`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}=qB(e,`{{ themePreview }}`);return JV(r===void 0?a:UV(e,r,`themePreview`),o,{...EV(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),kV(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const XV=e=>e.slice(e.lastIndexOf(`.`)+1),ZV=(e,t)=>{let n=new G(XV(e));return n.truncate(t,{marker:`…`}),n.plain};function QV(e,t){let n=e.map(e=>e.map(({name:e})=>DV(XV(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 $V(e,t,n,r){let i=QV(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new G(` ${ZV(s,i)} `,{style:uV(im(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
175
+ `),...e]));return o.overflow=`ignore`,o.end=``,o}function eH(e,t){return{layoutPreview:{fn:()=>$V(e.layout(),qB(e,`{{ layoutPreview }}`).decor,t.drawnAt(),kV(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function tH(e,t,n,r){let i=EV(r.activeSegment,`{{ menu }}`),a=r.action,o=pE(i.placementId,e,n.key),s=gE(o),c=fE(e),l=$B(a.store,o)===c,u=$B(a.store,`session.id`),d=l?Qn:c,f=tV(tr(`{{ menu "${e}" }}`,t,2,+!!l),Kn([{verb:yn,args:[u,o,d,s,`0`]}]),!1);return i.drops.push(...l?(()=>{let t=r.activeSegment.drawnAt(),c=Gp(i.palette,i.disclosure,t).plane,l=PV(a,e,`menu`);return FV(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,Qn],[s,`0`]],onPick:n.closeOnPick},n.paged,a,_V(i,n.distribution,qB(a,`{{ menu }}`),l.paletteOf,t,c),dV(i.palette,c,t))})():[]),f}const nH=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function rH(e,t){let n=t[t.length-1],r=nH(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:bE(r??{})}}function iH(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=rH(t,n);return tH(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function aH(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=oH(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 G(t?i:a,{style:l===void 0?void 0:new H({color:l})}))}let l=G.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function oH(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 sH(e){let t={fn:(()=>{let t=EV(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:(()=>EV(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=EV(e,`{{ keptOn }}`),i=Qs(r,t),a=Qs(r,n),o=Uo(lc(i,z.TRUECOLOR),lc(a,z.TRUECOLOR)),s=Math.min(Mp,Math.max(o,3));return(cc(i,e.drawnAt(),(e,t)=>Uo(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=uw(()=>EV(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...cH(s)];return aH({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 cH(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 lH(e){let t=[],n=[];for(let r of e){if(!r.contains(`
176
176
  `)){n.push(r);continue}let e=r.split(`
177
- `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function lH(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}`}})}function uH(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:r.length===0?n:[],ground:i},deeper:r}}function dH(e){return{...e,cells:e.cells.map(IB)}}function fH(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,...pH(e,r)]}function pH(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 mH(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:fH(e.direction,e.children.map((t,i)=>n(t,[...r,hH(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function hH(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:sg[e.direction]}}const gH={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:dp(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,pg(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),fH(e.direction,e.children.map((n,r)=>t.renderChild(n,t.gate.kind===`shown`,hH(e,r))))}},_H={drop:e=>e.place,above:()=>`above`},vH={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},yH={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:cg(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(ir(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,mg(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,bH(e,t))};function bH(e,t){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(t.gate.kind===`hidden`)return[];let a=jw(t.scope,e.settings);if(t.gate.kind===`failed`)return xH(e,a,t,t.gate.message);try{if(!kB(i.when,a))return[];let n=Qh(e.settings.theme,t.palette),o={id:e.id,effect:e.settings.effect,ground:_O(n)},s=e.opens!==void 0&&kB(e.opens.open,t.scope),{styles:c,fragments:l,lead:u,trail:d,drops:f,open:p}=t.evaluateSegment(e,a,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,lead:e.lead,trail:e.trail},s),m=p?c.trigger:c.closed,h={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:m,padding:t.padding,placement:o},g=e.opens,_=g===void 0?[]:t.renderBody(g.body,s,c.disclosure).map(e=>({...e,place:_H[g.placement](e)})),v=cH(UB(l,m)).map((e,t)=>({cells:zB(e,{...h,lead:t===0?UB(u,m):[],trail:t===0?UB(d,m):[]}),band:`own`,place:`flow`})),y=f.map(e=>({cells:zB(UB([e],c.band),{...h,baseStyle:c.band}),band:`deeper`,place:`flow`})),b=(e,t,n)=>zB(UB([e],t),{...h,width:`auto`,baseStyle:t,padding:n}),x=_.findIndex(e=>e.band===`own`),{lead:S,stays:C}=g!==void 0&&x!==-1?vH[g.placement](v,()=>b(t.closeDisclosure(g.key),c.close,t.padding)):{lead:[],stays:v},ee=S.flatMap(e=>b(new G(` `.repeat(FB(e).reduce((e,t)=>e+t.cellLength,0))),c.trigger,0)),te=(e,t)=>e.band===`own`?t===x?S:ee:[],ne=_.map((e,t)=>({cells:[...te(e,t),...e.cells],band:`deeper`,place:e.place})),re=[...C,...y];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...re.flatMap(e=>e.cells),..._.flatMap(te)].flatMap(FB)),[...re,...ne]}catch(n){return xH(e,a,t,n.message??String(n))}}function xH(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:zB([new G(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:_O(n.palette)},lead:SH(e.lead,e,t,n),trail:SH(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function SH(e,t,n,r){if(e===void 0)return[];try{return r.evaluateSegment(t,n,r.palette,r.region,{bg:void 0,fg:void 0,body:e,lead:void 0,trail:void 0},!1).fragments}catch(e){return r.onSegmentError?.(t.id,e.message??String(e)),[]}}const CH={container:gH,segment:yH};function wH(e){return CH[e]}function TH(e){if(`ttl`in e)return{kind:`ttl`,durationMs:ET(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 EH(e,t){switch(vg(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 DH(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:TH(n.cache),parse:EH(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:TH(n.cache),parse:EH(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`git`:e.declareGit(t,{field:n.field,cwd:r,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function OH(e,t){let n=gv.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}const kH=(e,t,n,r,i)=>{let a=SL(t,xL(n,e.themeDefaults));return{variation:ap[r??Hm(void 0,null,a.variation)],shade:rp[i??Gm(void 0,null,a.shade)]}};function AH(e,t,n){let r=n.cwd,i={store:t.variableStore,compiled:new Map,chromeCols:Ch({endcaps:`powerline`,charset:Lm}),width:80,padding:1,seamCols:wh({endcaps:`powerline`,charset:Lm}),layout:()=>[],look:void 0},a=CV(t.drawnAt),o={action:i,activeSegment:a},s=Object.keys(e.styles),c=Yg(e.presets),l=Rj(e),u=Ow({extraFuncs:{...oV(i),...FV(i,a),...zV(i,a),...JV(i,a),...UV(i,a,t.now),...$V(i,a),...rH(o),...oH(a),styles:{fn:()=>s,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>c,argTypes:[],arity:{kind:`exact`}}},clock:t.now,drawnAt:t.drawnAt}),d=OH(u,e.helpers),f=e=>u.parse(e,d),p=new Map,m=e=>{let t=p.get(e);if(t!==void 0)return t;let n=f(e);return p.set(e,n),n},h=new Map;for(let[t,n]of Ea)n in e.variables&&h.set(t,n);for(let[t,n]of Sg(e))h.has(n.key)||h.set(n.key,t);i.compiled=qB(f,e.actions,h,l);let g=[];for(let[n,i]of Object.entries(e.variables))try{DH(t,n,i,r)}catch(e){g.push(`Variable "${n}": ${e.message??String(e)}`)}for(let[n,i]of Object.entries(e.segments))if(i.vars)for(let[e,a]of Object.entries(i.vars))try{DH(t,`${n}.${e}`,a,r)}catch(t){g.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let _=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=f)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};_[t]={when:n.when===void 0?void 0:e(n.when,`when`,m),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 v=(e,t,n)=>{try{return m(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},y=t.variableStore,b=t=>{let n=Eg(e.segments[t.name]),r=Object.create(null);for(let[e,i]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Mg(t,e,i,e=>String(y.read(e.variable)))});return Object.freeze(r)},x=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:v(e.when,t,`when`),parse:(e,n)=>v(e,t,n),compileChild:x,placementSettings:b};return wH(e.kind).compile(e,n)},S=new Map;for(let t of c){let{node:n,path:r}=Qg(e,t);S.set(t,x(n,r))}let C=new Map(mm.map(e=>[e,new Map])),ee=[[`globals`,e.globals],...Object.entries(e.presets).map(([e,t])=>[`presets.${e}.globals`,t.globals??{}])];for(let[e,t]of ee)for(let n of mm){let r=t[n];if(!hm(r))continue;let i=`${e}.${n}`,a=C.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:jH(f,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:_,roots:S,activeSegment:a,menuRuntime:o,globalExpressions:C,loadWarnings:g}}function jH(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function MH(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 render but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r}function NH(e,t,n,r){try{return t.template.evaluate(n).map(e=>e.plain).join(``)}catch(n){return r({kind:`rule`,slot:e,message:wm(t.where,e,`the rule failed — ${n instanceof Error?n.message:String(n)}`)}),Cm[e]}}function PH(e,t){return e.kind===`decided`?e.name:Cm[t]}function FH(e){return e.kind===`container`?e.children.flatMap(FH):[...e.name.startsWith(`edit.`)?[]:[e.id],...e.opens===void 0?[]:FH(e.opens.body)]}function IH(e,t,n,r,i,a,o,s,c){let{perSegmentSink:l,onSegmentError:u,onRenderWarning:d}=s??{},f=e=>d?.(e),p=new Set;r.renderAt(a),r.drawAt(zm(o.colorCompatibility));let{preset:m=qg}=c??{},h=$g(e,m),g=c?.style??bm(`none`,e.styles),_=c?.theme??ig(void 0,null,h.palette),v=kH(e,h,_,c?.variation,c?.shade),y=c?.effect??km(void 0,null,h.effect),b=(e,t,n)=>({...i,term:{cols:o.width},theme:{effective:e},style:{effective:t},effect:{effective:n}});r.applyInput(b(PH(_,`palette`),PH(g,`style`),PH(y,`effect`))),t.menuRuntime.action.chromeCols=Ch(o),t.menuRuntime.action.padding=o.padding,t.menuRuntime.action.width=o.width,t.menuRuntime.action.seamCols=wh(o);let x=kw(n),S=_m(_,e=>{let n=MH(t,`palette`,e);return rg(NH(`palette`,n,x,f),n.where,e=>f({kind:`rule`,slot:`palette`,message:e}))}),C=_m(g,n=>bm(NH(`style`,MH(t,`style`,n),x,f),e.styles)),ee=_m(y,e=>Om(NH(`effect`,MH(t,`effect`,e),x,f)));(S!==_||C!==g||ee!==y)&&r.applyInput(b(S.name,C.name,ee.name));let te=S.value,ne=eg(te,C.value);t.menuRuntime.action.look={basePalette:te,palette:ne,decor:v};let re=(c?.effects??new mh(``)).motion(ee.value,a,{transitions:c?.transitions??th(void 0,null,h.transitions),source:{config:t,preset:m,revision:r.stateRevision(),width:o.width},returned:uH,hold:dH});l?.clear();let ie=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},ae=(e,n,i,a,o,s)=>{try{let c=r.drawnAt(),{tint:l,text:u,disclosure:d}=im(i,a,c),f=wV(t.activeSegment,e.name,e.id,i,d,l,u),m=yO(f,c,o.bg,o.fg,n),h=()=>Gp(i,d,c);s&&(f.bg=h().state);let g=o.body.evaluate(n),_=f.drops.length>0||s;if(_){let e=h();f.bg=e.state;for(let t of e.shortfalls)p.add(t)}let v=o.lead?.evaluate(n)??[],y=o.trail?.evaluate(n)??[];return{styles:{closed:m,get trigger(){return cV(i,h().state,c)},get band(){return cV(i,h().plane,c)},get close(){return dV(i,h().state,c)},disclosure:d},fragments:g,lead:v,trail:y,drops:f.drops,open:_}}finally{t.activeSegment.current=null}},w=(e,t,r)=>{let i=t?MB(e.when,x):AB,a=i.kind===`failed`?{...i,report:()=>{let t=`when over ${FH(e).join(`, `)||`no placement`}`;f({kind:`when`,where:t,error:i.message,message:`${t}: ${i.message} — what it gates is hidden`})}}:i,s={scope:x,palette:ne,gate:a,padding:o.padding,region:r,perSegmentSink:l,onSegmentError:u,evaluateSegment:ae,lookupSegment:ie,renderChild:(e,t,n)=>w(e,t,nm(r,n)),renderBody:(e,t,n)=>w(e,a.kind===`shown`&&t,rm(n)),closeDisclosure:e=>sV(n,e),placed:re.placed};return wH(e.kind).render(e,s)},T=t.roots.get(m);if(T===void 0)throw Error(`Preset "${m}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${qg}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let oe=e=>{let n=MB(e.when,x);if(e.kind===`container`)return n.kind===`shown`;if(Yj(e.name)===void 0)return!1;if(n.kind!==`shown`)return n.kind===`failed`;try{return kB(t.segments[e.name].when,jw(x,e.settings))}catch{return!0}};t.menuRuntime.action.layout=()=>mH(T,oe).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=Yj(e);return r===void 0?[]:[{name:r,address:t,palette:Qh(n.theme,ne)}]}));let E=lH(w(T,!0,tm(v))).map(({line:e,row:t})=>{let n=HB(e.cells,o);return Oh(n.map(e=>e.owner),o,re.row(t,n))}).join(`
178
- `);re.drawn();for(let e of p)f({kind:`band-floor`,message:e});for(let[e,t]of r.cachePolicyFaults())f({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return E}function*LH(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*RH(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 Yg(e.presets)){for(let n of fg(Qg(e,t).node))n.when!==void 0&&(yield n.when);let n=$g(e,t);for(let e of mm){let t=n[e];hm(t)&&(yield t)}}for(let[,t]of LH(e))t.kind===`template`&&(yield t.template),bg(t)&&`key`in t.cache&&(yield t.cache.key);for(let t of Object.values(e.actions))`copy`in t&&(yield t.copy),`open`in t&&(yield t.open),`preset`in t&&t.preset===`delete`&&(yield t.name)}function zH(e,t){return e===t||t.startsWith(`${e}.`)||e.startsWith(`${t}.`)}function BH(e,t){let n=new Set,r=new Set,i=new Set;for(let e of RH(t)){for(let r of b_(e,t.helpers).keys())n.add(r);for(let{name:n}of w_(e,t.helpers))r.add(n);for(let n of T_(e,t.helpers))i.add(n)}for(let[,e]of LH(t))if(bg(e)&&`depends_on`in e.cache)for(let t of e.cache.depends_on)n.add(t);let a=new Set(r);for(let e of r){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)a.add(e)}let o=new Set,s=new Set;for(let e of a){let n=t.actions[e];if(n!==void 0&&(`set`in n&&o.add(n.set),`insertSegment`in n&&s.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)s.add(e)}for(let e of Yg(t.presets))for(let n of fg(Qg(t,e).node))n.kind===`segment`&&s.add(n.name);let c=(e,t)=>[...n].some(t=>zH(t,e))||t.kind===`state`&&o.has(t.key),l=e=>[...e].filter(e=>!cE(e)),u=(e,t,n)=>l(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),d=new Map(LH(e));return[...u(`variable`,d.keys(),e=>c(e,d.get(e))),...u(`action`,Object.keys(e.actions??{}),e=>a.has(e)),...u(`helper`,Object.keys(e.helpers??{}),e=>i.has(e)),...u(`segment`,Object.keys(e.segments??{}),e=>s.has(e))]}var VH=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,qH(e,t,n,`initial value`),this.cell=P_.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){qH(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}},HH=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,P_.computed)(()=>{let e=n();return qH(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},UH=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=P_.observable.box(KH(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=KH(e);GH(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function WH(e){return JSON.stringify(e)}function GH(e,t){return WH(e)===WH(t)}function KH(e){return e.kind===`ok`?{kind:`ok`,value:F_(e.value)}:e}function qH(e,t,n,r){let i=I_(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var JH=class{nodes=P_.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new VH(e,t,n))}defineDocument(e,t){this.declare(e,new UH(e,t))}defineComputed(e,t,n){let r=e=>this.read(e);this.declare(e,new HH(e,t,()=>n(r)))}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()}setDocument(e,t){let n=this.requireNode(e);if(n.kind!==`document`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,P_.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireNode(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,P_.runInAction)(()=>n.set(t))}runInAction(e){(0,P_.runInAction)(e)}has(e){return this.nodes.has(e)}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`)return WH(t.read());try{return String(t.read())}catch(e){return`failed:${e instanceof Error?e.message:String(e)}`}}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.nodes.keys()]}requireNode(e){let t=this.nodes.get(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}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}declare(e,t){if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`);(0,P_.runInAction)(()=>this.nodes.set(e,t))}};function YH(e,{plugins:t,config:n}){let{checkout:r,loaded:i,dropped:a,unreached:o}=t,s=r===null?`-`:`${r.git?`git`:`dir`}:${r.root}`,c=e=>{let t=nI(e),r=t===void 0?void 0:n.variables[iI(t)];return r?.kind===`file`?r.path:`none`};return`config load ${e.join(` < `)||`<default>`}: plugins loaded=${i.length} dropped=${a.length} unplaced=${o.length} checkout=${s}`+i.map(e=>` +${e} data=${c(e)}`).join(``)+a.map(e=>` -${e.path} (${e.reason})`).join(``)+o.map(e=>` ~${e.path} (${e.reason})`).join(``)}function XH(e,t,n){return e+`\0`+t+`\0`+(n??``)}function ZH(e,t){return new Set(Yg(e.presets).filter(n=>Qg(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function QH(e,t){let n=new Map,{roots:r,loaded:i,dropped:a,unreached:o}=e.state.plugins;for(let t of[...NI(e.projectDir,e.cwd,e.configFile),...r,...i,...[...a,...o].map(e=>e.path)]){let{dir:e,name:r}=A_(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}=A_(l.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 $H(e){return e.filter(Boolean).join(`
179
- `)||null}function eU(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=JI(t.layers,_L,{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??_L,l=a.find(e=>e.path===t.home)?.raw??{},u=new JH,d=new qT(u,o.globals.default_empty_value??``,r.gitService,r.sessionState),f;try{f=AH(o,d,{cwd:e}),n.push(...f.loadWarnings),az(o),vM(o)}catch(e){throw d.dispose(),e}return{config:o,store:u,registry:d,compiled:f,neededInputPaths:dR(o),lastRenderCellsBySegment:new Map,authoredRoots:ZH(c,l),fileHeldSettings:GR(l),unused:[...new Map(a.flatMap(e=>BH(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}}}function tU(e,t,n,r){let i=FI(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[BI(e,t),RI(i)],s,c=null;try{s=eU(t,a,o,r,e=>{c=e})}catch(e){return e instanceof $T&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:$H(o),state:null,error:e instanceof $T||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:$H(o),state:s,error:null}}function nU(e,t,n){return eU(e,{layers:[],home:``,projectDir:t},[],n)}var rU=class{entries=new Map;deps;maxEntries;observers;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}getOrCreate(e,t,n){let r=XH(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=tU(e,t,n,this.deps);a.state!==null&&A(`info`,YH(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??nU(t,e,this.deps),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;n.state.registry.dispose(),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a),this.observers.onReload?.(o),o}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=tU(e.projectDir,e.cwd,e.configFile,this.deps);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(A(`info`,YH(t.layers,t.state)),e.state.registry.dispose(),e.state=t.state),this.refreshWatcher(e,t),this.observers.onReload?.(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=QH(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){A(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const iU=16384;var aU=class{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;watchersOpened=0;watchersClosed=0;watchersEvicted=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<iU){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%iU}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}}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version: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,renderCache:{size:e.renderCacheSize},effectCache:e.effectCache,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes}}};function oU(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 sU={load:()=>({}),save:()=>{},flush:()=>{}};var cU=class{sessions;storage;head=0;atom=(0,P_.createAtom)(`SessionState`);constructor(e=sU,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}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,P_.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,P_.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,P_.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 lU(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 uU=class{timer=null;pending=null;constructor(e,t=500,n=Ft){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=r.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 lU(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{r.mkdirSync(l.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;r.writeFileSync(t,JSON.stringify(e),{mode:384}),r.chmodSync(t,384),r.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const dU={default_empty_value:`string`,default_separator:`string`,palette:`string`,style:`string`,effect:`string`,preset:`string`,endcaps:`string`,variation:`string`,shade:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,updateNotice:`boolean`,transitions:`boolean`,colorCompatibility:`string`,menuGlyph:`string`},fU=new Set([`1`,`true`]),pU=new Set([`0`,`false`,``]);function mU(e,t){let n=zU(e),r=n.scope===`segment-palette`?`string`:dU[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(fU.has(t))return`true`;if(pU.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function hU(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function gU(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(l.dirname(e),{recursive:!0}),Ie(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function _U(e){return/^\s*$/.test(e)?null:Tr(e)}function vU(e,t){return e!==null&&Dr(e,t)!==void 0}function yU(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(yU),...i}}return e}function bU(e){if(!zg(e))return yU(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,yU(t)])),...n}}const xU=hL,SU=xU.segments,CU=xU.presets,wU=xU.root;function TU(e,t,n,r){if(!vU(e,t)&&n===void 0)throw new K(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function EU(e,t){let n=JD(t);return t.scope===`segment-palette`&&TU(e,[`segments`,t.segment],SU[t.segment],n.join(`.`)),n}function DU(e){return Tr(Fr(e))}function OU(){return Object.entries(wU.rows).map(([e,t])=>{let n=yU(t);return{path:[`root`],fragment:DU({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function kU(e,t){let n=e===null?void 0:Dr(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function AU(e,t){if(t===void 0)return null;let n=bU(t);return{path:e,fragment:DU(n),unit:{path:e,value:n}}}function jU(e,t){let n=[`presets`,t],r=[...n,`root`],i=CU[t];TU(e,n,i,r.join(`.`));let a=kU(e,r)??AU(r,i?.root);return a!==null&&ni(a.fragment)?a:null}function MU(e,t){let n=ti(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 NU(e,t){return[...OU(),kU(e,[`root`]),jU(e,t)].filter(e=>e!==null).reduce(MU,new Map)}function PU(e,t,n){for(let{node:r,...i}of NU(e,t).values())if(ii(r,n))return i;throw new K(`${FU(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 FU(e,t){return jU(e,t)?.path??[`root`]}function IU(e,t){return t.scope===`preset-root`?FU(e,t.preset):JD(t)}function LU(e,{unit:t}){return t===null?e:Yr(e,t.path,Fr(t.value),Nr)}function RU(e){let t=qD(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function zU(e){let t=RU(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function BU(e,t,n,r,i){i(t,n,ZU(t,r)),gU(t.path,r,e.logger),e.record(t.path,n,r)}function VU(e,t,n){let r=WU(e,t,n);if(r.length>0)throw new K(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const HU=()=>{};function UU(e,t){try{return t()}catch(t){throw!(t instanceof K)||e.above.length===0?t:new K(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function WU(e,t,n){let r=GU(e,t);if(r===null)return[];let i=new Set(YU(JU(r),JU(n)));return YU(qU(e,r),qU(e,n)).filter(e=>!i.has(e))}function GU(e,t){try{return KU(e,t)}catch(e){if(e instanceof $T)return null;throw e}}function KU(e,t){return JI(t===null?e.above:[e.path,...e.above],_L,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:r.readFileSync(n,`utf8`))}function qU(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function JU(e){return e.layers.at(-1)?.config??e.base}function YU(e,t,n=``){return!XU(e)||!XU(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>YU(e[r],t[r],n===``?r:`${n}.${r}`))}function XU(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ZU(e,t){try{return KU(e,t)}catch(e){throw e instanceof $T?new K(`refused: the config file would not load after this click — ${e.message}`):e}}function QU(e,t){let n=zU(t),r=_U(hU(e)??``),i=r===null?void 0:Dr(r,JD(n));return i!==void 0&&`value`in i?i.value:void 0}function $U(e,t,n){eW(e,t,n,[])}function eW(e,t,n,r){let i=hU(t.path),a=n.reduce((e,[t,n])=>Yr(e,EU(_U(e),zU(t)),mU(t,n),Nr),i??``);BU(e,t,i,UU(t,()=>tW(a,t.path,r,e=>e)),VU)}function tW(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=PU(_U(s),n,i),l=ci(LU(s,c),c.path,i,a,Fr(o));if(l===null)throw new K(`${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 nW(e,t,n){let r=_U(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of NU(r,t)){if(!ii(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?kr(e,c):Fr(s.value);if(a!==`#`)return Yr(e,[...i,`rows`,a],l,Nr);if(jU(r,t)!==null)throw new K(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return Yr(e,i,l,Nr)}return e}function rW(e,t){return Zr(e,t,t[0]===`presets`&&t.length>2&&!yL(t[1])?2:0)}function iW(e,t,n){let r=n.map(RU),i=hU(t.path);if(i===null)return;let a=r.reduce((e,t)=>rW(e,IU(_U(e),t)),i);a!==i&&BU(e,t,i,a,HU)}function aW(e){let t=e===null?void 0:Dr(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function oW(e,t){let n=new Set([...vL,...aW(e),...t.above.flatMap(e=>Object.keys(vr.default.parse(r.readFileSync(e,`utf8`)).presets??{}))].map(QT));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(QT(e)))}function sW(e,t,n,r,i,a){let o=hU(t.path),s=_U(o??``),c=oW(s,t),l=[`presets`,c],u=UU(t,()=>jU(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?kr(o??``,u.fragment):Fr(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Fr(r)]]],f=i.map(([e,t])=>{let n=KD(c,e);return[EU(s,zU(n)),mU(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Yr(e,t,n,Nr),Yr(o??``,l,`{}`,Nr));return BU(e,t,o,UU(t,()=>tW(p,t.path,a.map(e=>({...e,preset:c})),nW)),VU),c}function cW(e,t,n,r){let i=hU(t.path);BU(e,t,i,Yr(i??``,[`themeDefaults`,n],Fr(r),Nr),VU)}function lW(e,t,n){if(yL(n))throw new K(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=hU(t.path),a=_U(i??``);if(i===null||a===null||Dr(a,r)===void 0)throw new K(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Dr(a,[`globals`,`preset`]);BU(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>rW(e,t),i),HU)}function uW(e,t,n,r){let i=RU(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=hU(t.path),o=r.op===`remove`?r.target:r.anchor,s=UU(t,()=>PU(_U(a??``),i.preset,o)),c=LU(a??``,s),{after:l,placed:u}=dW(c,s.path,r,()=>{let e=ZU(t,c).config;return Yg(e.presets).map(t=>Qg(e,t).node)});if(l===null)throw new K(`${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 BU(e,t,a,l,VU),u}function dW(e,t,n,r){switch(n.op){case`remove`:return{after:oi(e,t,n.target),placed:null};case`insert`:{let i=aM(n.segment,n.anchor,r());return{after:si(e,t,i,n.anchor,n.relation),placed:i}}}}const fW={load:()=>({}),save:()=>{}},pW=new Set(Sa.map(e=>e.sessionKey)),mW=e=>pW.has(e)||e.startsWith(aO),hW=8*1024*1024,gW={past:[],future:[]},_W=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var vW=class{state=new Map;constructor(e,t,n=fW){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)??gW;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??gW}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(_W(n));r.set(_W(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:oU(this.sessionState,e=>mW(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:EW(i,n),o=r.get(e),s=o===void 0?a:AW(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 K(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,OW(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new K(`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(_W)),a=n.net.filter(e=>!i.has(_W(e))),o=xW(jW(kW(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new K(`rewind: ${r.map(NW).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 K(`redo: nothing to redo`);let a=[...n,i],o=xW(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...CW(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(_W)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:jW(n,t),future:jW(i,t),...a!==void 0&&{savepoint:{at:jW([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(_W(e))),below:jW(a.below,t)}}}),new K(`${r}: ${o.map(NW).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):hU(t.file)}write(e,t,n){t.kind===`file`?gU(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||yW(n)>hW;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,bW(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${hW} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function yW(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 bW({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...CW(n,1,[])}:{past:e,future:t.slice(1),...CW(n,0,[])}}function xW(e){return e.slice(-50)}const SW=e=>e===sO.member;function CW(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:wW(e.net,n),below:e.below}}}function wW(e,t){let n=new Map(e.map(e=>[_W(e),e]));for(let e of t){let t=n.get(_W(e));n.set(_W(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const TW=e=>e.map(e=>({...e,before:e.after,after:e.before}));function EW(e,t){let n=[...e.past,t],r=xW(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...CW(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...DW(e.future,a),...i.below]},n.length-r.length,t)}}function DW(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function OW(e,t){return{past:e.past.slice(0,-1),future:xW([...e.future,t]),...CW(e.savepoint,0,TW(t))}}function kW(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...DW(r,t.at-i.length),...t.below]}function AW(e,t){if(SW(t.after)&&!SW(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!SW(t.after)&&SW(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function jW(e,t){return e.map(e=>e.filter(e=>!t.has(_W(e)))).filter(e=>e.length>0)}function MW(e){return e.map(NW).join(`, `)}function NW(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function PW(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 FW(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(PW))}function IW(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(PW)&&FW(t.below)}function LW(e){if(typeof e!=`object`||!e)return!1;let t=e;return FW(t.past)&&FW(t.future)&&(t.savepoint===void 0||IW(t.savepoint))}function RW(e,t){let n=e=>e.kind===`file`||mW(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 zW(e,t){return{load:()=>{let n;try{n=r.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(LW)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,RW(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{r.mkdirSync(l.dirname(e),{recursive:!0}),Ie(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 BW=e=>!mW(e)&&!Dk(e)&&e!==`update.dismissed`;var VW=class{past=new Map;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:oU(e,BW,(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 K(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,P_.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){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 HW=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function UW(e,t){let n=e=>({kind:`failed`,reason:`${t} ${e}`}),r;try{r=JSON.parse(e)}catch(e){return n(`is not JSON: ${e.message}`)}if(!HW(r))return n(`is not an object`);for(let[e,t]of Object.entries(r)){if(!HW(t))return n(`holds ${JSON.stringify(e)} as something other than its sightings`);for(let[e,r]of Object.entries(t))if(!qO.includes(r))return n(`marks ${JSON.stringify(e)} ${JSON.stringify(r)}, not ${qO.join(` or `)}`)}return{kind:`ok`,value:r}}function WW(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}function GW(e=l.join(Re(),`doctor-marks.json`)){let t=()=>{let t;try{t=r.readFileSync(e,`utf8`)}catch(t){return t.code===`ENOENT`?{kind:`ok`,value:{}}:{kind:`failed`,reason:`${e}: ${t.message}`}}return UW(t,e)};return{read:t,record:(n,i,a)=>{let o=t();if(o.kind===`failed`)throw Error(`doctor: the mark book could not be read: ${o.reason}`);r.mkdirSync(l.dirname(e),{recursive:!0}),Ie(e,`${JSON.stringify(WW(o.value,n,i,a),null,2)}\n`)}}}var KW=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};
177
+ `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function uH(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}`}})}function dH(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:r.length===0?n:[],ground:i},deeper:r}}function fH(e){return{...e,cells:e.cells.map(LB)}}function pH(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,...mH(e,r)]}function mH(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 hH(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:pH(e.direction,e.children.map((t,i)=>n(t,[...r,gH(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function gH(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:cg[e.direction]}}const _H={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:dp(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,mg(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),pH(e.direction,e.children.map((n,r)=>t.renderChild(n,t.gate.kind===`shown`,gH(e,r))))}},vH={drop:e=>e.place,above:()=>`above`},yH={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},bH={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:lg(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(ir(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,hg(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,xH(e,t))};function xH(e,t){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(t.gate.kind===`hidden`)return[];let a=Mw(t.scope,e.settings);if(t.gate.kind===`failed`)return SH(e,a,t,t.gate.message);try{if(!AB(i.when,a))return[];let n=$h(e.settings.theme,t.palette),o={id:e.id,effect:e.settings.effect,ground:vO(n)},s=e.opens!==void 0&&AB(e.opens.open,t.scope),{styles:c,fragments:l,lead:u,trail:d,drops:f,open:p}=t.evaluateSegment(e,a,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,lead:e.lead,trail:e.trail},s),m=p?c.trigger:c.closed,h={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:m,padding:t.padding,placement:o},g=e.opens,_=g===void 0?[]:t.renderBody(g.body,s,c.disclosure).map(e=>({...e,place:vH[g.placement](e)})),v=lH(WB(l,m)).map((e,t)=>({cells:BB(e,{...h,lead:t===0?WB(u,m):[],trail:t===0?WB(d,m):[]}),band:`own`,place:`flow`})),y=f.map(e=>({cells:BB(WB([e],c.band),{...h,baseStyle:c.band}),band:`deeper`,place:`flow`})),b=(e,t,n)=>BB(WB([e],t),{...h,width:`auto`,baseStyle:t,padding:n}),x=_.findIndex(e=>e.band===`own`),{lead:S,stays:C}=g!==void 0&&x!==-1?yH[g.placement](v,()=>b(t.closeDisclosure(g.key),c.close,t.padding)):{lead:[],stays:v},ee=S.flatMap(e=>b(new G(` `.repeat(IB(e).reduce((e,t)=>e+t.cellLength,0))),c.trigger,0)),te=(e,t)=>e.band===`own`?t===x?S:ee:[],ne=_.map((e,t)=>({cells:[...te(e,t),...e.cells],band:`deeper`,place:e.place})),re=[...C,...y];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...re.flatMap(e=>e.cells),..._.flatMap(te)].flatMap(IB)),[...re,...ne]}catch(n){return SH(e,a,t,n.message??String(n))}}function SH(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:BB([new G(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:vO(n.palette)},lead:CH(e.lead,e,t,n),trail:CH(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function CH(e,t,n,r){if(e===void 0)return[];try{return r.evaluateSegment(t,n,r.palette,r.region,{bg:void 0,fg:void 0,body:e,lead:void 0,trail:void 0},!1).fragments}catch(e){return r.onSegmentError?.(t.id,e.message??String(e)),[]}}const wH={container:_H,segment:bH};function TH(e){return wH[e]}function EH(e){if(`ttl`in e)return{kind:`ttl`,durationMs:DT(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 DH(e,t){switch(yg(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 OH(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:EH(n.cache),parse:DH(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:EH(n.cache),parse:DH(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`git`:e.declareGit(t,{field:n.field,cwd:r,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function kH(e,t){let n=_v.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}const AH=(e,t,n,r,i)=>{let a=CL(t,SL(n,e.themeDefaults));return{variation:ap[r??Hm(void 0,null,a.variation)],shade:rp[i??Gm(void 0,null,a.shade)]}};function jH(e,t,n){let r=n.cwd,i={store:t.variableStore,compiled:new Map,chromeCols:Ch({endcaps:`powerline`,charset:Lm}),width:80,padding:1,seamCols:wh({endcaps:`powerline`,charset:Lm}),layout:()=>[],look:void 0},a=wV(t.drawnAt),o={action:i,activeSegment:a},s=Object.keys(e.styles),c=Xg(e.presets),l=zj(e),u=kw({extraFuncs:{...sV(i),...IV(i,a),...BV(i,a),...YV(i,a),...WV(i,a,t.now),...eH(i,a),...iH(o),...sH(a),styles:{fn:()=>s,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>c,argTypes:[],arity:{kind:`exact`}}},clock:t.now,drawnAt:t.drawnAt}),d=kH(u,e.helpers),f=e=>u.parse(e,d),p=new Map,m=e=>{let t=p.get(e);if(t!==void 0)return t;let n=f(e);return p.set(e,n),n},h=new Map;for(let[t,n]of Ea)n in e.variables&&h.set(t,n);for(let[t,n]of Cg(e))h.has(n.key)||h.set(n.key,t);i.compiled=JB(f,e.actions,h,l);let g=[];for(let[n,i]of Object.entries(e.variables))try{OH(t,n,i,r)}catch(e){g.push(`Variable "${n}": ${e.message??String(e)}`)}for(let[n,i]of Object.entries(e.segments))if(i.vars)for(let[e,a]of Object.entries(i.vars))try{OH(t,`${n}.${e}`,a,r)}catch(t){g.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let _=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=f)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};_[t]={when:n.when===void 0?void 0:e(n.when,`when`,m),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 v=(e,t,n)=>{try{return m(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},y=t.variableStore,b=t=>{let n=Dg(e.segments[t.name]),r=Object.create(null);for(let[e,i]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Ng(t,e,i,e=>String(y.read(e.variable)))});return Object.freeze(r)},x=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:v(e.when,t,`when`),parse:(e,n)=>v(e,t,n),compileChild:x,placementSettings:b};return TH(e.kind).compile(e,n)},S=new Map;for(let t of c){let{node:n,path:r}=$g(e,t);S.set(t,x(n,r))}let C=new Map(mm.map(e=>[e,new Map])),ee=[[`globals`,e.globals],...Object.entries(e.presets).map(([e,t])=>[`presets.${e}.globals`,t.globals??{}])];for(let[e,t]of ee)for(let n of mm){let r=t[n];if(!hm(r))continue;let i=`${e}.${n}`,a=C.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:MH(f,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:_,roots:S,activeSegment:a,menuRuntime:o,globalExpressions:C,loadWarnings:g}}function MH(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function NH(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 render but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r}function PH(e,t,n,r){try{return t.template.evaluate(n).map(e=>e.plain).join(``)}catch(n){return r({kind:`rule`,slot:e,message:wm(t.where,e,`the rule failed — ${n instanceof Error?n.message:String(n)}`)}),Cm[e]}}function FH(e,t){return e.kind===`decided`?e.name:Cm[t]}function IH(e){return e.kind===`container`?e.children.flatMap(IH):[...e.name.startsWith(`edit.`)?[]:[e.id],...e.opens===void 0?[]:IH(e.opens.body)]}function LH(e,t,n,r,i,a,o,s,c){let{perSegmentSink:l,onSegmentError:u,onRenderWarning:d}=s??{},f=e=>d?.(e),p=new Set;r.renderAt(a),r.drawAt(zm(o.colorCompatibility));let{preset:m=Jg}=c??{},h=e_(e,m),g=c?.style??bm(`none`,e.styles),_=c?.theme??ag(void 0,null,h.palette),v=AH(e,h,_,c?.variation,c?.shade),y=c?.effect??km(void 0,null,h.effect),b=(e,t,n)=>({...i,term:{cols:o.width},theme:{effective:e},style:{effective:t},effect:{effective:n}});r.applyInput(b(FH(_,`palette`),FH(g,`style`),FH(y,`effect`))),t.menuRuntime.action.chromeCols=Ch(o),t.menuRuntime.action.padding=o.padding,t.menuRuntime.action.width=o.width,t.menuRuntime.action.seamCols=wh(o);let x=Aw(n),S=_m(_,e=>{let n=NH(t,`palette`,e);return ig(PH(`palette`,n,x,f),n.where,e=>f({kind:`rule`,slot:`palette`,message:e}))}),C=_m(g,n=>bm(PH(`style`,NH(t,`style`,n),x,f),e.styles)),ee=_m(y,e=>Om(PH(`effect`,NH(t,`effect`,e),x,f)));(S!==_||C!==g||ee!==y)&&r.applyInput(b(S.name,C.name,ee.name));let te=S.value,ne=tg(te,C.value);t.menuRuntime.action.look={basePalette:te,palette:ne,decor:v};let re=(c?.effects??new mh(``)).motion(ee.value,a,{transitions:c?.transitions??th(void 0,null,h.transitions),source:{config:t,preset:m,revision:r.stateRevision(),width:o.width},returned:dH,hold:fH});l?.clear();let ie=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},ae=(e,n,i,a,o,s)=>{try{let c=r.drawnAt(),{tint:l,text:u,disclosure:d}=im(i,a,c),f=TV(t.activeSegment,e.name,e.id,i,d,l,u),m=bO(f,c,o.bg,o.fg,n),h=()=>Gp(i,d,c);s&&(f.bg=h().state);let g=o.body.evaluate(n),_=f.drops.length>0||s;if(_){let e=h();f.bg=e.state;for(let t of e.shortfalls)p.add(t)}let v=o.lead?.evaluate(n)??[],y=o.trail?.evaluate(n)??[];return{styles:{closed:m,get trigger(){return lV(i,h().state,c)},get band(){return lV(i,h().plane,c)},get close(){return fV(i,h().state,c)},disclosure:d},fragments:g,lead:v,trail:y,drops:f.drops,open:_}}finally{t.activeSegment.current=null}},w=(e,t,r)=>{let i=t?NB(e.when,x):jB,a=i.kind===`failed`?{...i,report:()=>{let t=`when over ${IH(e).join(`, `)||`no placement`}`;f({kind:`when`,where:t,error:i.message,message:`${t}: ${i.message} — what it gates is hidden`})}}:i,s={scope:x,palette:ne,gate:a,padding:o.padding,region:r,perSegmentSink:l,onSegmentError:u,evaluateSegment:ae,lookupSegment:ie,renderChild:(e,t,n)=>w(e,t,nm(r,n)),renderBody:(e,t,n)=>w(e,a.kind===`shown`&&t,rm(n)),closeDisclosure:e=>cV(n,e),placed:re.placed};return TH(e.kind).render(e,s)},T=t.roots.get(m);if(T===void 0)throw Error(`Preset "${m}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${Jg}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let oe=e=>{let n=NB(e.when,x);if(e.kind===`container`)return n.kind===`shown`;if(Xj(e.name)===void 0)return!1;if(n.kind!==`shown`)return n.kind===`failed`;try{return AB(t.segments[e.name].when,Mw(x,e.settings))}catch{return!0}};t.menuRuntime.action.layout=()=>hH(T,oe).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=Xj(e);return r===void 0?[]:[{name:r,address:t,palette:$h(n.theme,ne)}]}));let E=uH(w(T,!0,tm(v))).map(({line:e,row:t})=>{let n=UB(e.cells,o);return Oh(n.map(e=>e.owner),o,re.row(t,n))}).join(`
178
+ `);re.drawn();for(let e of p)f({kind:`band-floor`,message:e});for(let[e,t]of r.cachePolicyFaults())f({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return E}function*RH(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*zH(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 Xg(e.presets)){for(let n of pg($g(e,t).node))n.when!==void 0&&(yield n.when);let n=e_(e,t);for(let e of mm){let t=n[e];hm(t)&&(yield t)}}for(let[,t]of RH(e))t.kind===`template`&&(yield t.template),xg(t)&&`key`in t.cache&&(yield t.cache.key);for(let t of Object.values(e.actions))`copy`in t&&(yield t.copy),`open`in t&&(yield t.open),`preset`in t&&t.preset===`delete`&&(yield t.name)}function BH(e,t){return e===t||t.startsWith(`${e}.`)||e.startsWith(`${t}.`)}function VH(e,t){let n=new Set,r=new Set,i=new Set;for(let e of zH(t)){for(let r of x_(e,t.helpers).keys())n.add(r);for(let{name:n}of T_(e,t.helpers))r.add(n);for(let n of E_(e,t.helpers))i.add(n)}for(let[,e]of RH(t))if(xg(e)&&`depends_on`in e.cache)for(let t of e.cache.depends_on)n.add(t);let a=new Set(r);for(let e of r){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)a.add(e)}let o=new Set,s=new Set;for(let e of a){let n=t.actions[e];if(n!==void 0&&(`set`in n&&o.add(n.set),`insertSegment`in n&&s.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)s.add(e)}for(let e of Xg(t.presets))for(let n of pg($g(t,e).node))n.kind===`segment`&&s.add(n.name);let c=(e,t)=>[...n].some(t=>BH(t,e))||t.kind===`state`&&o.has(t.key),l=e=>[...e].filter(e=>!lE(e)),u=(e,t,n)=>l(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),d=new Map(RH(e));return[...u(`variable`,d.keys(),e=>c(e,d.get(e))),...u(`action`,Object.keys(e.actions??{}),e=>a.has(e)),...u(`helper`,Object.keys(e.helpers??{}),e=>i.has(e)),...u(`segment`,Object.keys(e.segments??{}),e=>s.has(e))]}var HH=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,JH(e,t,n,`initial value`),this.cell=F_.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){JH(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}},UH=class{kind=`computed`;cell;constructor(e,t,n){if(this.name=e,this.type=t,this.cell=(0,F_.computed)(()=>{let e=n();return JH(this.name,this.type,e,`computed result`),e},{keepAlive:!0}),typeof this.cell.suspend_!=`function`)throw TypeError(`Variable "${e}": this MobX's computed has no suspend_; release() cannot unsubscribe it`);if(typeof this.cell.keepAlive_!=`boolean`)throw TypeError(`Variable "${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_()}lastUpdatedMs(){return null}},WH=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=F_.observable.box(qH(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=qH(e);KH(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function GH(e){return JSON.stringify(e)}function KH(e,t){return GH(e)===GH(t)}function qH(e){return e.kind===`ok`?{kind:`ok`,value:I_(e.value)}:e}function JH(e,t,n,r){let i=L_(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var YH=class{nodes=F_.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new HH(e,t,n))}defineDocument(e,t){this.declare(e,new WH(e,t))}defineComputed(e,t,n){let r=e=>this.read(e);this.declare(e,new UH(e,t,()=>n(r)))}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()}setDocument(e,t){let n=this.requireNode(e);if(n.kind!==`document`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,F_.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireNode(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,F_.runInAction)(()=>n.set(t))}runInAction(e){(0,F_.runInAction)(e)}has(e){return this.nodes.has(e)}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`)return GH(t.read());try{return String(t.read())}catch(e){return`failed:${e instanceof Error?e.message:String(e)}`}}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.nodes.keys()]}dispose(){if(this.disposed)return 0;this.disposed=!0;let e=0;return(0,F_.runInAction)(()=>{for(let t of this.nodes.values())t instanceof UH&&(t.release(),e++)}),e}disposed=!1;requireNode(e){let t=this.nodes.get(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}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}declare(e,t){if(this.disposed)throw Error(`Variable "${e}": cannot declare on a disposed store`);if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`);(0,F_.runInAction)(()=>this.nodes.set(e,t))}};function XH(e,{plugins:t,config:n}){let{checkout:r,loaded:i,dropped:a,unreached:o}=t,s=r===null?`-`:`${r.git?`git`:`dir`}:${r.root}`,c=e=>{let t=rI(e),r=t===void 0?void 0:n.variables[aI(t)];return r?.kind===`file`?r.path:`none`};return`config load ${e.join(` < `)||`<default>`}: plugins loaded=${i.length} dropped=${a.length} unplaced=${o.length} checkout=${s}`+i.map(e=>` +${e} data=${c(e)}`).join(``)+a.map(e=>` -${e.path} (${e.reason})`).join(``)+o.map(e=>` ~${e.path} (${e.reason})`).join(``)}function ZH(e,t){return`config disposed reason=${e} released=${t}`}function QH(e,t,n){return e+`\0`+t+`\0`+(n??``)}function $H(e,t){return new Set(Xg(e.presets).filter(n=>$g(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function eU(e,t){let n=new Map,{roots:r,loaded:i,dropped:a,unreached:o}=e.state.plugins;for(let t of[...PI(e.projectDir,e.cwd,e.configFile),...r,...i,...[...a,...o].map(e=>e.path)]){let{dir:e,name:r}=j_(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}=j_(l.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 tU(e){return e.filter(Boolean).join(`
179
+ `)||null}function nU(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=YI(t.layers,vL,{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??vL,l=a.find(e=>e.path===t.home)?.raw??{},u=new YH,d=new JT(u,o.globals.default_empty_value??``,r.gitService,r.sessionState),f;try{f=jH(o,d,{cwd:e}),n.push(...f.loadWarnings),oz(o),yM(o)}catch(e){throw d.dispose(),e}return{config:o,store:u,registry:d,compiled:f,neededInputPaths:fR(o),lastRenderCellsBySegment:new Map,authoredRoots:$H(c,l),fileHeldSettings:KR(l),unused:[...new Map(a.flatMap(e=>VH(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}}}function rU(e,t,n,r){let i=II(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[VI(e,t),zI(i)],s,c=null;try{s=nU(t,a,o,r,e=>{c=e})}catch(e){return e instanceof eE&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:tU(o),state:null,error:e instanceof eE||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:tU(o),state:s,error:null}}function iU(e,t,n){return nU(e,{layers:[],home:``,projectDir:t},[],n)}var aU=class{entries=new Map;deps;log;maxEntries;observers;constructor(e,t={}){this.deps=e,this.log=e.log??Ft,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}getOrCreate(e,t,n){let r=QH(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=rU(e,t,n,this.deps);a.state!==null&&this.log(`info`,XH(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??iU(t,e,this.deps),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;this.log(`info`,ZH(`evict`,n.state.registry.dispose())),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a),this.observers.onReload?.(o),o}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=rU(e.projectDir,e.cwd,e.configFile,this.deps);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(this.log(`info`,XH(t.layers,t.state)),this.log(`info`,ZH(`reload`,e.state.registry.dispose())),e.state=t.state),this.refreshWatcher(e,t),this.observers.onReload?.(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=eU(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}firstState(){return this.entries.values().next().value?.state??null}};const oU=16384;var sU=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;watchersOpened=0;watchersClosed=0;watchersEvicted=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<oU){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%oU}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,hits:0,misses:0,invalidations:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},renderCacheSize:0,effectCache:{sessions:0,effects:0},sessionState:{sessions:0,observers:0},watchersActive:0,handlerProbes:[]})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:Et,sourceDigest:Jh(),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,renderCache:{size:e.renderCacheSize},effectCache:e.effectCache,sessionState:e.sessionState,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes}}};function cU(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 lU={load:()=>({}),save:()=>{},flush:()=>{}};var uU=class{sessions;storage;head=0;atom=(0,F_.createAtom)(`SessionState`);constructor(e=lU,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}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,F_.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,F_.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,F_.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 dU(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 fU=class{timer=null;pending=null;constructor(e,t=500,n=Ft){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=r.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 dU(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{r.mkdirSync(l.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;r.writeFileSync(t,JSON.stringify(e),{mode:384}),r.chmodSync(t,384),r.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const pU={default_empty_value:`string`,default_separator:`string`,palette:`string`,style:`string`,effect:`string`,preset:`string`,endcaps:`string`,variation:`string`,shade:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,updateNotice:`boolean`,transitions:`boolean`,colorCompatibility:`string`,menuGlyph:`string`},mU=new Set([`1`,`true`]),hU=new Set([`0`,`false`,``]);function gU(e,t){let n=VU(e),r=n.scope===`segment-palette`?`string`:pU[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(mU.has(t))return`true`;if(hU.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function _U(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function vU(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(l.dirname(e),{recursive:!0}),Ie(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function yU(e){return/^\s*$/.test(e)?null:Tr(e)}function bU(e,t){return e!==null&&Dr(e,t)!==void 0}function xU(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(xU),...i}}return e}function SU(e){if(!Bg(e))return xU(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,xU(t)])),...n}}const CU=gL,wU=CU.segments,TU=CU.presets,EU=CU.root;function DU(e,t,n,r){if(!bU(e,t)&&n===void 0)throw new K(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function OU(e,t){let n=YD(t);return t.scope===`segment-palette`&&DU(e,[`segments`,t.segment],wU[t.segment],n.join(`.`)),n}function kU(e){return Tr(Fr(e))}function AU(){return Object.entries(EU.rows).map(([e,t])=>{let n=xU(t);return{path:[`root`],fragment:kU({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function jU(e,t){let n=e===null?void 0:Dr(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function MU(e,t){if(t===void 0)return null;let n=SU(t);return{path:e,fragment:kU(n),unit:{path:e,value:n}}}function NU(e,t){let n=[`presets`,t],r=[...n,`root`],i=TU[t];DU(e,n,i,r.join(`.`));let a=jU(e,r)??MU(r,i?.root);return a!==null&&ni(a.fragment)?a:null}function PU(e,t){let n=ti(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 FU(e,t){return[...AU(),jU(e,[`root`]),NU(e,t)].filter(e=>e!==null).reduce(PU,new Map)}function IU(e,t,n){for(let{node:r,...i}of FU(e,t).values())if(ii(r,n))return i;throw new K(`${LU(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 LU(e,t){return NU(e,t)?.path??[`root`]}function RU(e,t){return t.scope===`preset-root`?LU(e,t.preset):YD(t)}function zU(e,{unit:t}){return t===null?e:Yr(e,t.path,Fr(t.value),Nr)}function BU(e){let t=JD(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function VU(e){let t=BU(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function HU(e,t,n,r,i){i(t,n,$U(t,r)),vU(t.path,r,e.logger),e.record(t.path,n,r)}function UU(e,t,n){let r=KU(e,t,n);if(r.length>0)throw new K(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const WU=()=>{};function GU(e,t){try{return t()}catch(t){throw!(t instanceof K)||e.above.length===0?t:new K(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function KU(e,t,n){let r=qU(e,t);if(r===null)return[];let i=new Set(ZU(XU(r),XU(n)));return ZU(YU(e,r),YU(e,n)).filter(e=>!i.has(e))}function qU(e,t){try{return JU(e,t)}catch(e){if(e instanceof eE)return null;throw e}}function JU(e,t){return YI(t===null?e.above:[e.path,...e.above],vL,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:r.readFileSync(n,`utf8`))}function YU(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function XU(e){return e.layers.at(-1)?.config??e.base}function ZU(e,t,n=``){return!QU(e)||!QU(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>ZU(e[r],t[r],n===``?r:`${n}.${r}`))}function QU(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $U(e,t){try{return JU(e,t)}catch(e){throw e instanceof eE?new K(`refused: the config file would not load after this click — ${e.message}`):e}}function eW(e,t){let n=VU(t),r=yU(_U(e)??``),i=r===null?void 0:Dr(r,YD(n));return i!==void 0&&`value`in i?i.value:void 0}function tW(e,t,n){nW(e,t,n,[])}function nW(e,t,n,r){let i=_U(t.path),a=n.reduce((e,[t,n])=>Yr(e,OU(yU(e),VU(t)),gU(t,n),Nr),i??``);HU(e,t,i,GU(t,()=>rW(a,t.path,r,e=>e)),UU)}function rW(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=IU(yU(s),n,i),l=ci(zU(s,c),c.path,i,a,Fr(o));if(l===null)throw new K(`${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 iW(e,t,n){let r=yU(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of FU(r,t)){if(!ii(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?kr(e,c):Fr(s.value);if(a!==`#`)return Yr(e,[...i,`rows`,a],l,Nr);if(NU(r,t)!==null)throw new K(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return Yr(e,i,l,Nr)}return e}function aW(e,t){return Zr(e,t,t[0]===`presets`&&t.length>2&&!bL(t[1])?2:0)}function oW(e,t,n){let r=n.map(BU),i=_U(t.path);if(i===null)return;let a=r.reduce((e,t)=>aW(e,RU(yU(e),t)),i);a!==i&&HU(e,t,i,a,WU)}function sW(e){let t=e===null?void 0:Dr(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function cW(e,t){let n=new Set([...yL,...sW(e),...t.above.flatMap(e=>Object.keys(vr.default.parse(r.readFileSync(e,`utf8`)).presets??{}))].map($T));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has($T(e)))}function lW(e,t,n,r,i,a){let o=_U(t.path),s=yU(o??``),c=cW(s,t),l=[`presets`,c],u=GU(t,()=>NU(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?kr(o??``,u.fragment):Fr(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Fr(r)]]],f=i.map(([e,t])=>{let n=qD(c,e);return[OU(s,VU(n)),gU(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Yr(e,t,n,Nr),Yr(o??``,l,`{}`,Nr));return HU(e,t,o,GU(t,()=>rW(p,t.path,a.map(e=>({...e,preset:c})),iW)),UU),c}function uW(e,t,n,r){let i=_U(t.path);HU(e,t,i,Yr(i??``,[`themeDefaults`,n],Fr(r),Nr),UU)}function dW(e,t,n){if(bL(n))throw new K(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=_U(t.path),a=yU(i??``);if(i===null||a===null||Dr(a,r)===void 0)throw new K(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Dr(a,[`globals`,`preset`]);HU(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>aW(e,t),i),WU)}function fW(e,t,n,r){let i=BU(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=_U(t.path),o=r.op===`remove`?r.target:r.anchor,s=GU(t,()=>IU(yU(a??``),i.preset,o)),c=zU(a??``,s),{after:l,placed:u}=pW(c,s.path,r,()=>{let e=$U(t,c).config;return Xg(e.presets).map(t=>$g(e,t).node)});if(l===null)throw new K(`${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 HU(e,t,a,l,UU),u}function pW(e,t,n,r){switch(n.op){case`remove`:return{after:oi(e,t,n.target),placed:null};case`insert`:{let i=oM(n.segment,n.anchor,r());return{after:si(e,t,i,n.anchor,n.relation),placed:i}}}}const mW={load:()=>({}),save:()=>{}},hW=new Set(Sa.map(e=>e.sessionKey)),gW=e=>hW.has(e)||e.startsWith(oO),_W=8*1024*1024,vW={past:[],future:[]},yW=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var bW=class{state=new Map;constructor(e,t,n=mW){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)??vW;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??vW}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(yW(n));r.set(yW(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:cU(this.sessionState,e=>gW(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:OW(i,n),o=r.get(e),s=o===void 0?a:MW(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 K(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,AW(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new K(`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(yW)),a=n.net.filter(e=>!i.has(yW(e))),o=CW(NW(jW(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new K(`rewind: ${r.map(FW).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 K(`redo: nothing to redo`);let a=[...n,i],o=CW(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...TW(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(yW)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:NW(n,t),future:NW(i,t),...a!==void 0&&{savepoint:{at:NW([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(yW(e))),below:NW(a.below,t)}}}),new K(`${r}: ${o.map(FW).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):_U(t.file)}write(e,t,n){t.kind===`file`?vU(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||xW(n)>_W;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,SW(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${_W} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function xW(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 SW({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...TW(n,1,[])}:{past:e,future:t.slice(1),...TW(n,0,[])}}function CW(e){return e.slice(-50)}const wW=e=>e===cO.member;function TW(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:EW(e.net,n),below:e.below}}}function EW(e,t){let n=new Map(e.map(e=>[yW(e),e]));for(let e of t){let t=n.get(yW(e));n.set(yW(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const DW=e=>e.map(e=>({...e,before:e.after,after:e.before}));function OW(e,t){let n=[...e.past,t],r=CW(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...TW(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...kW(e.future,a),...i.below]},n.length-r.length,t)}}function kW(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function AW(e,t){return{past:e.past.slice(0,-1),future:CW([...e.future,t]),...TW(e.savepoint,0,DW(t))}}function jW(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...kW(r,t.at-i.length),...t.below]}function MW(e,t){if(wW(t.after)&&!wW(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!wW(t.after)&&wW(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function NW(e,t){return e.map(e=>e.filter(e=>!t.has(yW(e)))).filter(e=>e.length>0)}function PW(e){return e.map(FW).join(`, `)}function FW(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function IW(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 LW(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(IW))}function RW(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(IW)&&LW(t.below)}function zW(e){if(typeof e!=`object`||!e)return!1;let t=e;return LW(t.past)&&LW(t.future)&&(t.savepoint===void 0||RW(t.savepoint))}function BW(e,t){let n=e=>e.kind===`file`||gW(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 VW(e,t){return{load:()=>{let n;try{n=r.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(zW)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,BW(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{r.mkdirSync(l.dirname(e),{recursive:!0}),Ie(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 HW=e=>!gW(e)&&!Ok(e)&&e!==`update.dismissed`;var UW=class{past=new Map;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:cU(e,HW,(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 K(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,F_.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){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 WW=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function GW(e,t){let n=e=>({kind:`failed`,reason:`${t} ${e}`}),r;try{r=JSON.parse(e)}catch(e){return n(`is not JSON: ${e.message}`)}if(!WW(r))return n(`is not an object`);for(let[e,t]of Object.entries(r)){if(!WW(t))return n(`holds ${JSON.stringify(e)} as something other than its sightings`);for(let[e,r]of Object.entries(t))if(!JO.includes(r))return n(`marks ${JSON.stringify(e)} ${JSON.stringify(r)}, not ${JO.join(` or `)}`)}return{kind:`ok`,value:r}}function KW(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}function qW(e=l.join(Re(),`doctor-marks.json`)){let t=()=>{let t;try{t=r.readFileSync(e,`utf8`)}catch(t){return t.code===`ENOENT`?{kind:`ok`,value:{}}:{kind:`failed`,reason:`${e}: ${t.message}`}}return GW(t,e)};return{read:t,record:(n,i,a)=>{let o=t();if(o.kind===`failed`)throw Error(`doctor: the mark book could not be read: ${o.reason}`);r.mkdirSync(l.dirname(e),{recursive:!0}),Ie(e,`${JSON.stringify(KW(o.value,n,i,a),null,2)}\n`)}}}var JW=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};
180
180
  /*!
181
181
  * Copyright (c) Squirrel Chat et al., All rights reserved.
182
182
  * SPDX-License-Identifier: BSD-3-Clause
@@ -204,9 +204,9 @@ print(json.dumps({"ceiling": "off" if ceiling == math.inf else ceiling,
204
204
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
205
205
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
206
206
  */
207
- function qW(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function JW(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+=`
207
+ function YW(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function XW(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+=`
208
208
  `,e===t&&(i+=` `.repeat(a+n+2),i+=`^
209
- `))}return i}var $=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=qW(t.toml,t.ptr),i=JW(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})}};
209
+ `))}return i}var $=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=YW(t.toml,t.ptr),i=XW(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})}};
210
210
  /*!
211
211
  * Copyright (c) Squirrel Chat et al., All rights reserved.
212
212
  * SPDX-License-Identifier: BSD-3-Clause
@@ -234,7 +234,7 @@ function qW(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().lengt
234
234
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
235
235
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
236
236
  */
237
- function YW(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)$.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&&$.x(`invalid non-hex character in unicode escape`,e),r=r<<4|n}(r<0||r>1114111||r>=55296&&r<=57343)&&$.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+=`
237
+ function ZW(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)$.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&&$.x(`invalid non-hex character in unicode escape`,e),r=r<<4|n}(r<0||r>1114111||r>=55296&&r<=57343)&&$.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+=`
238
238
  `:n===102?o+=`\f`:n===114?o+=`\r`:n===101?o+=`\x1B`:n===34?o+=`"`:n===92?o+=`\\`:$.x(`unrecognised escape sequence`,e),s=e.p+1,c=0);else n!==32&&n!==9&&(c===2&&$.x(`invalid escape: only line-ending whitespace may be escaped`,e,s),c=+(!i&&n===92),s=e.p);$.x(`unfinished string`,e,t)}
239
239
  /*!
240
240
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -263,7 +263,7 @@ function YW(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCode
263
263
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
264
264
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
265
265
  */
266
- let XW=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var ZW=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(XW);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}};
266
+ let QW=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var $W=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(QW);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}};
267
267
  /*!
268
268
  * Copyright (c) Squirrel Chat et al., All rights reserved.
269
269
  * SPDX-License-Identifier: BSD-3-Clause
@@ -291,7 +291,7 @@ let XW=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[
291
291
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
292
292
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
293
293
  */
294
- function QW(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function $W(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function eG(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||$.x(`document contains excessively nested structures. aborting.`,e);let t=r===91?dG(e):uG(e);return e.d++,t}return r===34||r===39?YW(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&$.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)&&$.x(`invalid value`,e,n),e.p++,!1):r===43||r===45?tG(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?iG(e,r,t):e.s.charCodeAt(e.p+2)===58?aG(e,r,t):tG(e,e.p,r,0,t)}function tG(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)&&$.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)&&$.x(`invalid value`,e,t),e.p++,NaN;if(a===48){if(++e.p>=e.s.length||$W(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return nG(e,t,16,i);if(a===98)return nG(e,t,2,i);if(a===111)return nG(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:$.x(`illegal leading zero`,e,t)}else QW(a)||$.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!$W(a,i));)o||=1,a===95?(o&1||$.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:QW(a)?o>9?o-=11:o&1||o++:$.x(`illegal character in numeric literal`,e);if(!o){let t=(n-48)*(r||1);return e.bi===!0?BigInt(t):t}o&1||$.x(`unfinished numeric value`,e,t);let c=e.s.slice(t,e.p);return s&&(c=c.replaceAll(`_`,``)),o>1?parseFloat(c):rG(e,c,10,t)}function nG(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!$W(i,r));)i===95?(a&1&&$.x(`illegal underscore`,e),a=3):QW(i,n)?a&1&&a--:$.x(`illegal character in numeric literal`,e);a&1&&$.x(`unfinished numeric value`,e);let o=e.s.slice(t+2,e.p);return a&&(o=o.replaceAll(`_`,``)),rG(e,o,n,t)}function rG(e,t,n,r){if(e.bi!==!0)int:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break int;$.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 iG(e,t,n){let r=e.p++,i;if(!QW(t)||!QW(e.s.charCodeAt(e.p++))||!QW(e.s.charCodeAt(e.p++))||!QW(e.s.charCodeAt(e.p++)))return tG(e,e.p=r,t,0,n);if(e.p+=5,QW(e.s.charCodeAt(e.p++))||$.x(`invalid date-time: date part is malformed`,e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!QW(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return oG(e,e.s.slice(r,e.p),3,!1,r);if(e.s.charCodeAt(e.p+=3)!==58&&$.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(;QW(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return oG(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return oG(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return oG(e,e.s.slice(r,e.p),2,i,r)}function aG(e,t,n){let r=e.p;if(!QW(t)||!QW(e.s.charCodeAt(++e.p)))return tG(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;QW(e.s.charCodeAt(++e.p)););return oG(e,e.s.slice(r,e.p),4,!1,r)}function oG(e,t,n,r,i,a){if(e.ld){let a=new ZW(t,n,r);return a.isValid()||$.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){$.x(t instanceof Error?t.message:``+t,e,i)}}
294
+ function eG(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function tG(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function nG(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||$.x(`document contains excessively nested structures. aborting.`,e);let t=r===91?pG(e):fG(e);return e.d++,t}return r===34||r===39?ZW(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&$.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)&&$.x(`invalid value`,e,n),e.p++,!1):r===43||r===45?rG(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?oG(e,r,t):e.s.charCodeAt(e.p+2)===58?sG(e,r,t):rG(e,e.p,r,0,t)}function rG(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)&&$.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)&&$.x(`invalid value`,e,t),e.p++,NaN;if(a===48){if(++e.p>=e.s.length||tG(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return iG(e,t,16,i);if(a===98)return iG(e,t,2,i);if(a===111)return iG(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:$.x(`illegal leading zero`,e,t)}else eG(a)||$.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!tG(a,i));)o||=1,a===95?(o&1||$.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:eG(a)?o>9?o-=11:o&1||o++:$.x(`illegal character in numeric literal`,e);if(!o){let t=(n-48)*(r||1);return e.bi===!0?BigInt(t):t}o&1||$.x(`unfinished numeric value`,e,t);let c=e.s.slice(t,e.p);return s&&(c=c.replaceAll(`_`,``)),o>1?parseFloat(c):aG(e,c,10,t)}function iG(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!tG(i,r));)i===95?(a&1&&$.x(`illegal underscore`,e),a=3):eG(i,n)?a&1&&a--:$.x(`illegal character in numeric literal`,e);a&1&&$.x(`unfinished numeric value`,e);let o=e.s.slice(t+2,e.p);return a&&(o=o.replaceAll(`_`,``)),aG(e,o,n,t)}function aG(e,t,n,r){if(e.bi!==!0)int:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break int;$.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 oG(e,t,n){let r=e.p++,i;if(!eG(t)||!eG(e.s.charCodeAt(e.p++))||!eG(e.s.charCodeAt(e.p++))||!eG(e.s.charCodeAt(e.p++)))return rG(e,e.p=r,t,0,n);if(e.p+=5,eG(e.s.charCodeAt(e.p++))||$.x(`invalid date-time: date part is malformed`,e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!eG(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return cG(e,e.s.slice(r,e.p),3,!1,r);if(e.s.charCodeAt(e.p+=3)!==58&&$.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(;eG(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return cG(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return cG(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return cG(e,e.s.slice(r,e.p),2,i,r)}function sG(e,t,n){let r=e.p;if(!eG(t)||!eG(e.s.charCodeAt(++e.p)))return rG(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;eG(e.s.charCodeAt(++e.p)););return cG(e,e.s.slice(r,e.p),4,!1,r)}function cG(e,t,n,r,i,a){if(e.ld){let a=new $W(t,n,r);return a.isValid()||$.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){$.x(t instanceof Error?t.message:``+t,e,i)}}
295
295
  /*!
296
296
  * Copyright (c) Squirrel Chat et al., All rights reserved.
297
297
  * SPDX-License-Identifier: BSD-3-Clause
@@ -319,7 +319,7 @@ function QW(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48
319
319
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
320
320
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
321
321
  */
322
- function sG(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)&&$.x(`control characters are not allowed in comments`,e)}}function cG(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;sG(e)}}
322
+ function lG(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)&&$.x(`control characters are not allowed in comments`,e)}}function uG(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;lG(e)}}
323
323
  /*!
324
324
  * Copyright (c) Squirrel Chat et al., All rights reserved.
325
325
  * SPDX-License-Identifier: BSD-3-Clause
@@ -347,7 +347,7 @@ function sG(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)br
347
347
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
348
348
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
349
349
  */
350
- function lG(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return r||$.x(`unexpected end of key`,e),r===1&&i.push(e.s.slice(a,e.p)),e.p++,i;else o===46?(r||$.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)&&$.x(`illegal quoted key: multiline strings are not allowed`,e),i.push(YW(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?$.x(`illegal character in key`,e):r||(r=1,a=e.p);while(o=e.s.charCodeAt(++e.p));$.x(`incomplete key-value: cannot find end of key`,e,n)}function uG(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(cG(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=lG(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]))&&$.x(`trying to redefine an already defined value`,e,s);let i=t===`__proto__`;if(e.uk&&(i||t===`constructor`)){a=e.uk!==1&&$.x(`document contains an unsafe property`,e,s);break}!o&&i&&Object.defineProperty(a,t,{enumerable:!0,configurable:!0,writable:!0})}o&&$.x(`trying to redefine an already defined value`,e,s),cG(e,!0,!0);let l=eG(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),cG(e),(i=e.s.charCodeAt(e.p++))===125)return n;i!==44&&$.x(`expected comma or end of structure`,e,e.p-1)}$.x(`unfinished table`,e,t)}function dG(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(cG(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(eG(e,93)),cG(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&$.x(`expected comma or end of structure`,e,e.p-1)}$.x(`unfinished array`,e,t)}
350
+ function dG(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return r||$.x(`unexpected end of key`,e),r===1&&i.push(e.s.slice(a,e.p)),e.p++,i;else o===46?(r||$.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)&&$.x(`illegal quoted key: multiline strings are not allowed`,e),i.push(ZW(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?$.x(`illegal character in key`,e):r||(r=1,a=e.p);while(o=e.s.charCodeAt(++e.p));$.x(`incomplete key-value: cannot find end of key`,e,n)}function fG(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(uG(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=dG(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]))&&$.x(`trying to redefine an already defined value`,e,s);let i=t===`__proto__`;if(e.uk&&(i||t===`constructor`)){a=e.uk!==1&&$.x(`document contains an unsafe property`,e,s);break}!o&&i&&Object.defineProperty(a,t,{enumerable:!0,configurable:!0,writable:!0})}o&&$.x(`trying to redefine an already defined value`,e,s),uG(e,!0,!0);let l=nG(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),uG(e),(i=e.s.charCodeAt(e.p++))===125)return n;i!==44&&$.x(`expected comma or end of structure`,e,e.p-1)}$.x(`unfinished table`,e,t)}function pG(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(uG(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(nG(e,93)),uG(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&$.x(`expected comma or end of structure`,e,e.p-1)}$.x(`unfinished array`,e,t)}
351
351
  /*!
352
352
  * Copyright (c) Squirrel Chat et al., All rights reserved.
353
353
  * SPDX-License-Identifier: BSD-3-Clause
@@ -375,7 +375,7 @@ function lG(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return
375
375
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
376
376
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
377
377
  */
378
- function fG(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 pG(e,t,n){(t===null||e.uk===2)&&$.x(t===null?`trying to redefine an already defined table or value`:`document contains an unsafe property`,e,n)}function mG(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++,cG(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=lG(n,93);t&&(e.charCodeAt(n.p)!==93&&$.x(`expected end of table array declaration`,n),n.p++);let u=fG(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(pG(n,u,a),o=!0)}else{a=n.p;let e=fG(n,lG(n),s,c,0);!e&&!o&&pG(n,e,a),cG(n,!0,!0);let t=eG(n,void 0);e&&!o&&(e[1][e[0]]=t)}cG(n,!0),n.p<e.length&&(a=e.charCodeAt(n.p))!==10&&(a!==13||e.charCodeAt(n.p+1)!==10)&&$.x(`each key-value declaration must be followed by an end-of-line`,n),cG(n)}return r}``.isWellFormed;
378
+ function mG(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 hG(e,t,n){(t===null||e.uk===2)&&$.x(t===null?`trying to redefine an already defined table or value`:`document contains an unsafe property`,e,n)}function gG(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++,uG(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=dG(n,93);t&&(e.charCodeAt(n.p)!==93&&$.x(`expected end of table array declaration`,n),n.p++);let u=mG(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(hG(n,u,a),o=!0)}else{a=n.p;let e=mG(n,dG(n),s,c,0);!e&&!o&&hG(n,e,a),uG(n,!0,!0);let t=nG(n,void 0);e&&!o&&(e[1][e[0]]=t)}uG(n,!0),n.p<e.length&&(a=e.charCodeAt(n.p))!==10&&(a!==13||e.charCodeAt(n.p+1)!==10)&&$.x(`each key-value declaration must be followed by an end-of-line`,n),uG(n)}return r}``.isWellFormed;
379
379
  /*!
380
380
  * Copyright (c) Squirrel Chat et al., All rights reserved.
381
381
  * SPDX-License-Identifier: BSD-3-Clause
@@ -403,7 +403,7 @@ function fG(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
403
403
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
404
404
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
405
405
  */
406
- const hG=e=>e.codePointAt(0).toString(16).toUpperCase(),gG=String.raw`
406
+ const _G=e=>e.codePointAt(0).toString(16).toUpperCase(),vG=String.raw`
407
407
  ObjC.import("AppKit");
408
408
  ObjC.import("CoreText");
409
409
  function lacksOf(font, points) {
@@ -450,36 +450,36 @@ function run(argv) {
450
450
  : iterm(argv[1], points),
451
451
  );
452
452
  }
453
- `;function _G(e){let t=Ne({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,gG,...e],timeoutMs:3e3,category:`doctor.font`});if(!t.ok){if(t.reason===`rate-limited`)throw new KW(`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 vG=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),yG=e=>[...e].map(hG).join(`,`);function bG(e,t){let n=_G([`font`,e.kind,e.name,yG(t)]);if(n.kind===`failed`)return n;let{lacks:r}=n.value;return{kind:`ok`,value:{font:e.name,lacks:r===null?null:vG(r)}}}function xG(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=>!FO(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const SG=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function CG(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=>xG(e,n));if(t!==null)return r[0];let i=r.find(e=>!SG(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 wG(e,t,n){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let r=t.ITERM_PROFILE??null,i=_G([`iterm`,r??``,yG(n)]);return i.kind===`failed`?i:CG(i.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:vG(e.lacks)})),r,e)}function TG(e,t){let n=e.split(`
454
- `).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 EG=e=>e.replace(/[\\:,=-]/g,`\\$&`);function DG(e,t){let n=Ne({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
455
- `,`:family=${EG(e)}`],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new KW(`the font`);return{kind:`failed`,reason:`fc-match failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}return TG(n.stdout,t)}function OG(e,t){return process.platform===`darwin`?bG(e,t):DG(e.name,t)}function kG(e,t){let n=t||l.join(e,`.config`);return[l.join(n,`alacritty`,`alacritty.toml`),l.join(n,`alacritty.toml`),l.join(e,`.config`,`alacritty`,`alacritty.toml`),l.join(e,`.alacritty.toml`)]}function AG(e){return e===`darwin`?`Menlo`:`monospace`}const jG=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function MG(e){let t=jG(e.font)?e.font:{},n=jG(t.normal)?t.normal:{},r=(jG(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 NG(e,t,n){let i;try{i=r.readFileSync(e,`utf8`)}catch(t){return{kind:`failed`,reason:`cannot read ${e}: ${t.message}`}}let a;try{a=mG(i)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let o=MG(a);if(o.family!==null)return{kind:`ok`,value:{family:o.family,from:e}};if(n===5)return{kind:`ok`,value:null};let s=null;for(let i of o.imports){let a=i.startsWith(`~/`)?l.join(t,i.slice(2)):l.resolve(l.dirname(e),i);if(!r.existsSync(a))continue;let o=NG(a,t,n+1);if(o.kind===`failed`)return o;s=o.value??s}return{kind:`ok`,value:s}}function PG(e,t){let n=h.homedir(),i=kG(n,e.XDG_CONFIG_HOME).find(e=>r.existsSync(e)),a=i===void 0?{kind:`ok`,value:null}:NG(i,n,0);if(a.kind===`failed`)return a;let o=a.value?.family??AG(process.platform),s=a.value?.from??(i===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${i} sets none`),c=OG({kind:`family`,name:o},t);if(c.kind===`failed`)return c;let{font:l,lacks:u}=c.value;return{kind:`ok`,value:{font:l,from:l===o?s:`${s}; ${o} as fontconfig matches it`,lacks:u}}}const FG={iterm2:wG,alacritty:(e,t,n)=>PG(t,n)};function IG(e,t,n){return FG[e.name](e.version,t,n)}function LG(e,t){let n;try{n=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${t} is not JSON: ${e.message}`}}return Array.isArray(n)&&n.every(e=>typeof e==`string`)?{kind:`ok`,value:n}:{kind:`failed`,reason:`${t} is not a list of terminals`}}function RG(e=l.join(Re(),`doctor-clicked-terminals.json`)){let t=()=>{let t;try{t=r.readFileSync(e,`utf8`)}catch(t){return t.code===`ENOENT`?{kind:`ok`,value:[]}:{kind:`failed`,reason:`${e}: ${t.message}`}}return LG(t,e)};return{read:t,record:n=>{let i=t();if(i.kind===`failed`)throw Error(`doctor: the clicked terminals could not be read: ${i.reason}`);i.value.includes(n)||(r.mkdirSync(l.dirname(e),{recursive:!0}),Ie(e,`${JSON.stringify([...i.value,n],null,2)}\n`))}}}function zG(e){let t=e.replace(/\n$/,``);if(t===` `)return{kind:`ok`,value:null};let n=t.split(` `),[r,i,a,o]=n;return n.length!==4||!/^[1-9]\d*$/.test(o)?{kind:`failed`,reason:`tmux answered ${JSON.stringify(e)}, not the four fields asked for`}:{kind:`ok`,value:{features:r.split(`,`).filter(e=>e!==``),termtype:i,termname:a,pid:Number(o)}}}const BG=/^(sshd|mosh-server)\b/;function VG(e,t){let n=new Map;for(let t of e.split(`
456
- `)){let e=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(t);if(e===null)continue;let r=e[3].trim();n.set(Number(e[1]),{ppid:Number(e[2]),name:r.slice(r.lastIndexOf(`/`)+1)})}if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};let r=new Set;for(let e=n.get(t);e!==void 0;e=n.get(e.ppid)){if(BG.test(e.name))return{kind:`ok`,value:!0};if(r.has(e.ppid))break;r.add(e.ppid)}return{kind:`ok`,value:!1}}function HG(e){let t=Ne({bin:`ps`,args:[`-A`,`-o`,`pid=,ppid=,comm=`],timeoutMs:2e3,category:`doctor.process`});if(!t.ok){if(t.reason===`rate-limited`)throw new KW(`the processes`);return{kind:`failed`,reason:`ps failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}return VG(t.stdout,e)}function UG(e){let t=SB(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures} #{client_termtype} #{client_termname} #{client_pid}`]);if(t.kind===`rate-limited`)throw new KW(`tmux`);return t.kind===`failed`?{kind:`failed`,reason:t.reason}:zG(t.stdout)}function WG(e){return{probeTmux:UG,remoteLogin:HG,fontInUse:IG,loadConfig:e,marks:GW(),clicked:RG()}}function GG(e){let t={layers:e.layers,warnings:e.warning===null?[]:e.warning.split(`
457
- `)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}function KG(e){let{env:t,statusLine:n}=mi(e);if(t!==void 0&&!hi(t))throw Error(`cannot read ${e}: \`env\` is not an object`);return{path:e,env:t??{},statusLine:n===void 0?{kind:`absent`}:hi(n)?{kind:`present`,refreshInterval:n.refreshInterval}:{kind:`not-an-object`,value:n}}}function qG(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:e.probeTmux(t)}}function JG(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:HO(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:VO(t),tmuxClient:t}}}}function YG(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(jO(s))return{kind:`bundling`,name:s,version:c};if(!MO(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 XG(e){return{kind:`arrived`,handler:e,bar:Et}}function ZG(e,t,n){let r=new Map;for(let i of fg(Qg(e,t).node)){if(i.kind!==`segment`)continue;let t=Eg(e.segments[i.name])[wg],a=Mg(i,wg,t,e=>n(e.key));a===`bar`||a===`none`||r.set(i.drafts?.effect?.id??cg(i),a)}return[...r].map(([e,t])=>({placement:e,effect:t}))}function QG(e,t,n,r){let i=e.loadConfig(n),a=XL(i.config,r,()=>!1),o=qG(e,t.tmux),s=JG(o,t.terminalEnv),c=[...new Set([...Dh(a),...Eh(JSON.stringify(i.config))])].join(``);return{tmux:o,terminal:s,nerdFont:c===``?{kind:`none`}:{kind:`glyphs`,glyphs:c,terminal:YG(e,s,t,c)},marks:e.marks.read(),clicked:e.clicked.read(),config:GG(i),effect:a.effect,placementEffects:ZG(i.config,a.preset,r),transitions:a.transitions,claudeSettings:KG(di(ui(t.claudeConfigDir)))}}function $G(e,t){let n=t.claudeSettings.path;switch(e.kind){case`claude-settings`:{let i=Yr(pi(n),e.path,JSON.stringify(e.value),Pr);return r.mkdirSync(l.dirname(n),{recursive:!0}),Ie(n,i),{...t,claudeSettings:KG(n)}}default:return e.kind}}const eK={connectMs:200,budgetMs:500};async function tK(e){let n=e.includes(`--json`),r=await nK();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${Tt(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
458
- `);return}t.stdout.write(oK(r.value))}function nK(){return yt({kind:`stats`},eK,e=>`stats`in e?e.stats:void 0)}function rK(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function iK(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function aK(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 oK(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` version ${e.version}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${aK(e.uptimeSec)}`),t.push(` rss ${rK(e.rssBytes)}`),t.push(` heapUsed ${rK(e.heapUsedBytes)}`),t.push(` heapTotal ${rK(e.heapTotalBytes)}`),t.push(` external ${rK(e.externalBytes)}`),t.push(` arrayBuffers ${rK(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(` hit rate ${iK(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` invalidations ${e.gitCache.invalidations}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${iK(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(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),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(` evicted ${e.watchers.evicted}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let n=Object.entries(e.subprocesses.byCategory),r=n.reduce((e,[t])=>Math.max(e,t.length),13);for(let[i,a]of n){let n=e.subprocesses.p50DurationMs[i],o=e.subprocesses.p99DurationMs[i],s=n!==void 0&&o!==void 0?` (p50 ${n}ms · p99 ${o}ms)`:``;t.push(` ${i.padEnd(r)} ${a}${s}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
453
+ `;function yG(e){let t=Ne({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,vG,...e],timeoutMs:3e3,category:`doctor.font`});if(!t.ok){if(t.reason===`rate-limited`)throw new JW(`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 bG=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),xG=e=>[...e].map(_G).join(`,`);function SG(e,t){let n=yG([`font`,e.kind,e.name,xG(t)]);if(n.kind===`failed`)return n;let{lacks:r}=n.value;return{kind:`ok`,value:{font:e.name,lacks:r===null?null:bG(r)}}}function CG(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=>!IO(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const wG=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function TG(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=>CG(e,n));if(t!==null)return r[0];let i=r.find(e=>!wG(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 EG(e,t,n){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let r=t.ITERM_PROFILE??null,i=yG([`iterm`,r??``,xG(n)]);return i.kind===`failed`?i:TG(i.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:bG(e.lacks)})),r,e)}function DG(e,t){let n=e.split(`
454
+ `).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 OG=e=>e.replace(/[\\:,=-]/g,`\\$&`);function kG(e,t){let n=Ne({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
455
+ `,`:family=${OG(e)}`],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new JW(`the font`);return{kind:`failed`,reason:`fc-match failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}return DG(n.stdout,t)}function AG(e,t){return process.platform===`darwin`?SG(e,t):kG(e.name,t)}function jG(e,t){let n=t||l.join(e,`.config`);return[l.join(n,`alacritty`,`alacritty.toml`),l.join(n,`alacritty.toml`),l.join(e,`.config`,`alacritty`,`alacritty.toml`),l.join(e,`.alacritty.toml`)]}function MG(e){return e===`darwin`?`Menlo`:`monospace`}const NG=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function PG(e){let t=NG(e.font)?e.font:{},n=NG(t.normal)?t.normal:{},r=(NG(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 FG(e,t,n){let i;try{i=r.readFileSync(e,`utf8`)}catch(t){return{kind:`failed`,reason:`cannot read ${e}: ${t.message}`}}let a;try{a=gG(i)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let o=PG(a);if(o.family!==null)return{kind:`ok`,value:{family:o.family,from:e}};if(n===5)return{kind:`ok`,value:null};let s=null;for(let i of o.imports){let a=i.startsWith(`~/`)?l.join(t,i.slice(2)):l.resolve(l.dirname(e),i);if(!r.existsSync(a))continue;let o=FG(a,t,n+1);if(o.kind===`failed`)return o;s=o.value??s}return{kind:`ok`,value:s}}function IG(e,t){let n=h.homedir(),i=jG(n,e.XDG_CONFIG_HOME).find(e=>r.existsSync(e)),a=i===void 0?{kind:`ok`,value:null}:FG(i,n,0);if(a.kind===`failed`)return a;let o=a.value?.family??MG(process.platform),s=a.value?.from??(i===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${i} sets none`),c=AG({kind:`family`,name:o},t);if(c.kind===`failed`)return c;let{font:l,lacks:u}=c.value;return{kind:`ok`,value:{font:l,from:l===o?s:`${s}; ${o} as fontconfig matches it`,lacks:u}}}const LG={iterm2:EG,alacritty:(e,t,n)=>IG(t,n)};function RG(e,t,n){return LG[e.name](e.version,t,n)}function zG(e,t){let n;try{n=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${t} is not JSON: ${e.message}`}}return Array.isArray(n)&&n.every(e=>typeof e==`string`)?{kind:`ok`,value:n}:{kind:`failed`,reason:`${t} is not a list of terminals`}}function BG(e=l.join(Re(),`doctor-clicked-terminals.json`)){let t=()=>{let t;try{t=r.readFileSync(e,`utf8`)}catch(t){return t.code===`ENOENT`?{kind:`ok`,value:[]}:{kind:`failed`,reason:`${e}: ${t.message}`}}return zG(t,e)};return{read:t,record:n=>{let i=t();if(i.kind===`failed`)throw Error(`doctor: the clicked terminals could not be read: ${i.reason}`);i.value.includes(n)||(r.mkdirSync(l.dirname(e),{recursive:!0}),Ie(e,`${JSON.stringify([...i.value,n],null,2)}\n`))}}}function VG(e){let t=e.replace(/\n$/,``);if(t===` `)return{kind:`ok`,value:null};let n=t.split(` `),[r,i,a,o]=n;return n.length!==4||!/^[1-9]\d*$/.test(o)?{kind:`failed`,reason:`tmux answered ${JSON.stringify(e)}, not the four fields asked for`}:{kind:`ok`,value:{features:r.split(`,`).filter(e=>e!==``),termtype:i,termname:a,pid:Number(o)}}}const HG=/^(sshd|mosh-server)\b/;function UG(e,t){let n=new Map;for(let t of e.split(`
456
+ `)){let e=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(t);if(e===null)continue;let r=e[3].trim();n.set(Number(e[1]),{ppid:Number(e[2]),name:r.slice(r.lastIndexOf(`/`)+1)})}if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};let r=new Set;for(let e=n.get(t);e!==void 0;e=n.get(e.ppid)){if(HG.test(e.name))return{kind:`ok`,value:!0};if(r.has(e.ppid))break;r.add(e.ppid)}return{kind:`ok`,value:!1}}function WG(e){let t=Ne({bin:`ps`,args:[`-A`,`-o`,`pid=,ppid=,comm=`],timeoutMs:2e3,category:`doctor.process`});if(!t.ok){if(t.reason===`rate-limited`)throw new JW(`the processes`);return{kind:`failed`,reason:`ps failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}return UG(t.stdout,e)}function GG(e){let t=CB(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures} #{client_termtype} #{client_termname} #{client_pid}`]);if(t.kind===`rate-limited`)throw new JW(`tmux`);return t.kind===`failed`?{kind:`failed`,reason:t.reason}:VG(t.stdout)}function KG(e){return{probeTmux:GG,remoteLogin:WG,fontInUse:RG,loadConfig:e,marks:qW(),clicked:BG()}}function qG(e){let t={layers:e.layers,warnings:e.warning===null?[]:e.warning.split(`
457
+ `)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}function JG(e){let{env:t,statusLine:n}=mi(e);if(t!==void 0&&!hi(t))throw Error(`cannot read ${e}: \`env\` is not an object`);return{path:e,env:t??{},statusLine:n===void 0?{kind:`absent`}:hi(n)?{kind:`present`,refreshInterval:n.refreshInterval}:{kind:`not-an-object`,value:n}}}function YG(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:e.probeTmux(t)}}function XG(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:UO(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:HO(t),tmuxClient:t}}}}function ZG(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(MO(s))return{kind:`bundling`,name:s,version:c};if(!NO(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 QG(e){return{kind:`arrived`,handler:e,bar:Et}}function $G(e,t,n){let r=new Map;for(let i of pg($g(e,t).node)){if(i.kind!==`segment`)continue;let t=Dg(e.segments[i.name])[Tg],a=Ng(i,Tg,t,e=>n(e.key));a===`bar`||a===`none`||r.set(i.drafts?.effect?.id??lg(i),a)}return[...r].map(([e,t])=>({placement:e,effect:t}))}function eK(e,t,n,r){let i=e.loadConfig(n),a=ZL(i.config,r,()=>!1),o=YG(e,t.tmux),s=XG(o,t.terminalEnv),c=[...new Set([...Dh(a),...Eh(JSON.stringify(i.config))])].join(``);return{tmux:o,terminal:s,nerdFont:c===``?{kind:`none`}:{kind:`glyphs`,glyphs:c,terminal:ZG(e,s,t,c)},marks:e.marks.read(),clicked:e.clicked.read(),config:qG(i),effect:a.effect,placementEffects:$G(i.config,a.preset,r),transitions:a.transitions,claudeSettings:JG(di(ui(t.claudeConfigDir)))}}function tK(e,t){let n=t.claudeSettings.path;switch(e.kind){case`claude-settings`:{let i=Yr(pi(n),e.path,JSON.stringify(e.value),Pr);return r.mkdirSync(l.dirname(n),{recursive:!0}),Ie(n,i),{...t,claudeSettings:JG(n)}}default:return e.kind}}const nK={connectMs:200,budgetMs:500};async function rK(e){let n=e.includes(`--json`),r=await iK();r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${Tt(r)}\n`),t.exit(1)),n&&t.stdout.write(JSON.stringify(r.value,null,2)+`
458
+ `);let i=aK(r.value);if(i!==null){t.stderr.write(`daemon-stats: ${i}\n`),t.exitCode=1;return}n||t.stdout.write(fK(r.value))}function iK(){return yt({kind:`stats`},nK,e=>`stats`in e?e.stats:void 0)}function aK(e){let t=oK(sU.referenceSnapshot(),e);if(t.length===0)return null;let n=cK(e.version,e.sourceDigest??null),r=cK(Et,Jh());return`the daemon (${n}) reports no ${t.join(`, `)}; it is another build than this client (${r}), and restarts only when its own bundle changes`}function oK(e,t,n=``){if(!sK(e))return[];if(!sK(t))return[n||`<snapshot>`];let r=[];for(let i of Object.keys(e)){let a=n===``?i:`${n}.${i}`;i in t?r.push(...oK(e[i],t[i],a)):r.push(a)}return r}function sK(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cK(e,t){return`${e} [${t===null?`no digest`:Gh(t)}]`}function lK(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function uK(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function dK(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 fK(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${cK(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${dK(e.uptimeSec)}`),t.push(` rss ${lK(e.rssBytes)}`),t.push(` heapUsed ${lK(e.heapUsedBytes)}`),t.push(` heapTotal ${lK(e.heapTotalBytes)}`),t.push(` external ${lK(e.externalBytes)}`),t.push(` arrayBuffers ${lK(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(` hit rate ${uK(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` invalidations ${e.gitCache.invalidations}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${uK(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(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),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(` evicted ${e.watchers.evicted}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let n=Object.entries(e.subprocesses.byCategory),r=n.reduce((e,[t])=>Math.max(e,t.length),13);for(let[i,a]of n){let n=e.subprocesses.p50DurationMs[i],o=e.subprocesses.p99DurationMs[i],s=n!==void 0&&o!==void 0?` (p50 ${n}ms · p99 ${o}ms)`:``;t.push(` ${i.padEnd(r)} ${a}${s}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
459
459
  `)+`
460
- `}const sK=e=>({kind:`ok`,value:e}),cK=e=>({kind:`failed`,reason:e});var lK=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const uK=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function dK(e){return uK.test(e)?e:null}function fK(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return sK(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return sK({app:n,missing:cK(`its script could not be read (${r.reason})`)});let i=Ii(r.value);return sK({app:n,missing:i===null?cK("its script is not one `cc-candybar install` wrote"):sK([i.node,i.script].filter(t=>!e.exists(t)))})}async function pK(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 mK(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(`${_n}://${Vn}/${n}`);return(r===null?await pK(e,n):null)??{kind:`lost`,unopened:r,opener:fK(e)}}function hK(e,t,n){let r=Ne({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?sK(r.stdout):cK(r.stderr.trim()||r.error||r.reason)}const gK=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${_n}://probe"));u.isNil() ? "" : u.path.js`;async function _K(){let e=await nK();if(e.kind!==`ok`)return cK(Tt(e).split(`
461
- `).join(` — `));let{version:t,handlerProbes:n}=e.value;return Array.isArray(n)?sK({version:t,arrivals:n}):cK(`the running daemon (${t}) predates this check`)}function vK(){return{platform:process.platform,sockets:{own:Ve(),handler:He()},now:Date.now,nonce:w,daemon:_K,open:e=>{let t=hK(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=hK(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,gK]);if(e.kind===`failed`)return e;let t=e.value.trim();return sK(t===``?null:t)},script:e=>hK(`doctor.osadecompile`,`/usr/bin/osadecompile`,[Li(e)]),exists:r.existsSync}}const yK=/^─{20,}/,bK=/^❯(\s|$)/,xK=/›\s*stashed$/;function SK(e){if(e.inMode)return{kind:`in-mode`};let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>yK.test(e)?[t]:[]).at(-2);return n===void 0||!bK.test(t[n+1]??``)?{kind:`no-prompt`}:xK.test(t[n-1]??``)?{kind:`stashed`}:{kind:`ready`}}const CK={"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 wK(e,t,n){if(t===void 0)return{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`};if(t===null)return{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only type into a tmux pane`};let r=SK(e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:CK[r.kind]};let i=e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}const TK=`cc-candybar-slash`;function EK(e,t,n,r){let i=SB(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function DK(e){let t=EK(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(`
462
- `);return{inMode:n!==`0`,screen:r}}function OK(e,t){let n=EK(e,`claude-input.type`,[`load-buffer`,`-b`,TK,`-`,`;`,`send-keys`,`-t`,e.pane,`C-s`,`;`,`paste-buffer`,`-p`,`-d`,`-b`,TK,`-t`,e.pane,`;`,`send-keys`,`-t`,e.pane,`Enter`],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 kK(){return{read:DK,type:OK}}function AK(e){if(!e)throw new K(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new K(`invalid session id "${e}"`);return e}function jK(e){return MK(()=>decodeURIComponent(e))}function MK(e){try{return e()}catch(e){throw e instanceof URIError?new K(`malformed wire encoding: ${e.message}`):e}}function NK(e,t){let n=Ne({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 PK=(e,t)=>NK(jK(e),t),FK=(e,t)=>{let n=Ne({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,jK(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`})`)}},IK=(e,t)=>NK(jK(e),t),LK=(e,t)=>NK(jK(e),t),RK=(e,t)=>{let n=AK(jK(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},zK=(e,t)=>{let[n=``,...r]=MK(()=>Gn(e)),i=AK(n),a=az(ZK(t,i));if(r.length===0)throw new K(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new K(`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 K(`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 K(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}UK(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})`)},BK=/^-?\d+$/;function VK(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const HK=(e,t)=>{let[n=``,r=``,i=``]=MK(()=>Gn(e)),a=AK(n);if(!r)throw new K(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!BK.test(i))throw new K(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=ZK(t,a),c=az(s),l=c.rangeParamsFor(r);if(!l)throw new K(`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&&BK.test(u)?WK(l,parseInt(u,10)):GK(`step-state`,r,l,cz(s,e=>t.sessionState.get(a,e),r)),f=VK(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new K(`step-state: ${p.reason}`);UK(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 UK(e,t,n,r){let i=r.filter(e=>e.key.startsWith(aO));if(i.length===0)return;let a=RR(ZK(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new K(`${n}: refused — ${a.join(`; `)}`)}function WK(e,t){return Math.max(e.min,Math.min(e.max,t))}function GK(e,t,n,r){if(r===null)return n.min;if(!BK.test(r))throw new K(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return WK(n,parseInt(r,10))}const KK=`render-origin`;function qK(e){return JSON.stringify(e)}function JK(e){let t;try{t=JSON.parse(e)}catch{throw new K(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new K(`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 K(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function YK(e,t){let n=e.sessionState.get(t,KK);if(n===null)throw new K(`session ${t} has not rendered yet — no config to act on`);return JK(n)}function XK(e,t,n){let r=e.sessionState.get(t,KK);if(r===null)return;let i=JK(r),{path:a}=QK(i);n.some(e=>e.kind===`file`&&e.file===a)&&e.reloadConfig(i)}function ZK(e,t){return e.configFor(YK(e,t))}function QK(e){return LI(e.projectDir,e.cwd,e.configFile??void 0)}function $K(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const eq=(e,t)=>{let[n=``,r=``,i=``]=MK(()=>Gn(e)),a=AK(n),o=YK(t,a),s=t.configFor(o),c=vM(s);if(!r)throw new K(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new K(`set-config: ${l.reason}`);let u=QK(o),d=IR(s,e=>t.sessionState.get(a,e),r);$U($K(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},tq=(e,t)=>{let[n=``,r=``,i=``]=MK(()=>Gn(e)),a=AK(n);if(!r)throw new K(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!BK.test(i))throw new K(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=YK(t,a),c=t.configFor(s),l=vM(c),u=l.rangeParamsFor(r);if(!u)throw new K(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=QK(s),f=IR(c,e=>t.sessionState.get(a,e),r),p=QU(d.path,f.key),m=typeof p==`number`?WK(u,p):GK(`step-config`,r,u,bM(f.globals,r)),h=VK(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new K(`step-config: ${g.reason}`);$U($K(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})`)},nq=(e,t)=>{let[n=``]=MK(()=>Gn(e)),r=AK(n),i=YK(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=PR(a,o),c=LR(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=az(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new K(`save: ${t.reason}`);return[e.target,t.value]});iq(`save`,l,c);let d=QK(i);eW($K(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(rq)].join(` `)} → ${d.path} (session=${r})`)},rq=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Ag(e.value)}`;function iq(e,t,n){for(let r of n){let n=t.validate(r.key,Ag(r.value));if(!n.ok)throw new K(`${e}: ${n.reason}`)}}const aq=(e,t)=>{let[n=``]=MK(()=>Gn(e)),r=AK(n),i=YK(t,r),a=t.configFor(i),o=VR(a,e=>t.sessionState.get(r,e)),s=az(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new K(`save-preset: ${t.reason}`);return[e.configKey,t.value]});iq(`save-preset`,s,o.placements);let l=QK(i),u=sW($K(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Sa.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,xa.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(rq)].join(` `)} → ${l.path} (session=${r})`)},oq=(e,t)=>{let[n=``]=MK(()=>Gn(e)),r=AK(n),i=YK(t,r),a=UR(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new K(`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=QK(i);cW($K(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(PR(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=_g.map(e=>xa[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} ${_g.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},sq=(e,t)=>{let[n=``,r=``]=MK(()=>Gn(e)),i=AK(n);if(!r)throw new K(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=YK(t,i),o=QK(a);lW($K(t,i),o,r),t.reloadConfig(a);let s=xa.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},cq=(e,t)=>{let[n=``,...r]=MK(()=>Gn(e)),i=AK(n),a=YK(t,i),o=vM(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new K(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=QK(a),l=r.map(WR),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);iW($K(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 lq(e,t){let n=(e,t)=>[...fg(Qg(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Yg(t.presets).flatMap(e=>n(t,e).map(t=>oO(QT(e),cg(t)))));return Yg(e.presets).flatMap(t=>n(e,t).map(e=>({member:oO(QT(t),cg(e)),node:e})).filter(({member:e})=>!r.has(e)))}function uq(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[eO]:[]])}const dq=(e,t)=>{let[n=``,r=``,i=``]=MK(()=>Gn(e)),a=AK(n),o=YK(t,a),s=t.configFor(o),c=vM(s);if(!r)throw new K(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new K(`apply-layout-op: ${l.reason}`);let u=iM(l.value);if(u===null)throw new K(`apply-layout-op: "${l.value}" is not a layout op token`);let d=QK(o),f=uW($K(t,a),d,r,u);t.reloadConfig(o);let p=uq(lq(s,t.configFor(o)),t.sessionState.get(a,eO)).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})`)},fq=(e,t)=>{let[n=``]=MK(()=>Gn(e)),r=AK(n);t.journal.commit();let i=t.history.undo(r);XK(t,r,i),t.dlog(`info`,`undo: restored ${MW(i)} (session=${r})`)},pq=(e,t)=>{let n=AK(jK(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,az(ZK(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},mq=(e,t)=>{let n=AK(jK(e));t.journal.commit();let r=t.history.rewind(n);XK(t,n,r),t.dlog(`info`,`rewind: put back ${MW(r)||`nothing`} as edit mode found it (session=${n})`)},hq=(e,t)=>{let[n=``]=MK(()=>Gn(e)),r=AK(n);t.journal.commit();let i=t.history.redo(r);XK(t,r,i),t.dlog(`info`,`redo: re-applied ${MW(i)} (session=${r})`)},gq=(e,t)=>{AK(jK(e)),t.applyUpdate()},_q=`client-hints`;function vq(e,t){let n=e.sessionState.get(t,_q);if(n===null)throw new K(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new K(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new K(`client hints record is not an object: ${n}`);return ot(r)}function yq(e,t,n){let r=mk(n);e.sessionState.setBatch(t,xk(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${yk(n.nerdFont,n.marks)} ${vk(n.terminal,n.clicked)} (session=${t})`)}function bq(e,t){let n;try{n=QG(e.doctor,vq(e,t),YK(e,t),n=>e.sessionState.get(t,n))}catch(e){throw e instanceof KW?new K(e.message):e}return{...n,urlHandler:XG(e.clientVersion),askedBy:`click`,clicked:xq(e,n)}}function xq(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?UO(t.identified):null;if(r===null||n.kind===`failed`)return n;try{e.doctor.clicked.record(r)}catch(t){return e.dlog(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}return{kind:`ok`,value:n.value.includes(r)?n.value:[...n.value,r]}}const Sq=(e,t)=>{let n=AK(jK(e));yq(t,n,bq(t,n))},Cq=(e,t)=>{let n=dK(jK(e));if(n===null)throw new K(`doctor-probe: the value is not a probe nonce`);t.probes.arrive({nonce:n,handler:t.clientVersion}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${t.clientVersion??`unreported`}`)},wq=(e,t)=>{let[n=``,r=``]=MK(()=>Gn(e)),i=AK(n),a=hk(r);if(a===void 0)throw new K(`doctor-fix: unknown check "${r}"`);let o=bq(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new K(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=$G(s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.path.join(`.`)}=${JSON.stringify(s.fix.value)} (session=${i})`),yq(t,i,c)},Tq=(e,t)=>{let[n=``,r=``,i=``]=MK(()=>Gn(e)),a=AK(n),o=hk(r);if(o===void 0)throw new K(`doctor-mark: unknown check "${r}"`);if(!qO.includes(i))throw new K(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${qO.join(` or `)}`);let s=bq(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new K(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);if(s.marks.kind===`failed`)throw new K(`doctor-mark: ${s.marks.reason}`);let l=[o.name,c.sighting.id,i];t.doctor.marks.record(...l),t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),yq(t,a,{...s,marks:{kind:`ok`,value:WW(s.marks.value,...l)}})},Eq=(e,t)=>{let[n=``,...r]=MK(()=>Gn(e)),i=AK(n),a=YK(t,i),o=Object.values(t.configFor(a).actions).filter(e=>`ceiling`in e).find(e=>{let t=bP(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(o===void 0)throw new K(`ceiling: "${r.join(` `)}" is not a move this config declares`);let s=o.ceiling===`set`?{kind:`set`,to:o.to}:{kind:`clear`},c=LL({sessionId:i,projectDir:a.projectDir,cwd:a.cwd},vq(t,i));t.memento.move(c,s),t.dlog(`info`,`ceiling: ${r.join(` `)} (session=${i} claudeConfigDir=${c.claudeConfigDir})`)},Dq=(e,t)=>{let[n=``,r=``]=MK(()=>Gn(e)),i=AK(n),a=Object.values(t.configFor(YK(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new K(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=wK(t.claudeInput,vq(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new K(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)},Oq=`config-override`,kq=new Map([[xn,PK],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new K(`load-config: expected <sessionId>/<path> (missing separator)`);let r=AK(MK(()=>decodeURIComponent(e.slice(0,n)))),i=MK(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new K(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new K(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,Oq),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,Oq,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Sn,FK],[yn,zK],[bn,HK],[N,eq],[En,tq],[jn,cq],[Dn,nq],[On,aq],[kn,oq],[An,sq],[Mn,dq],[Nn,fq],[Pn,hq],[Fn,pq],[In,mq],[wn,IK],[Tn,LK],[Cn,RK],[Ln,gq],[Rn,Sq],[zn,wq],[Bn,Tq],[Vn,Cq],[Hn,Eq],[Un,Dq]]),Aq=new Set([yn,bn,N,En,jn,Dn,On,kn,An,Mn,Nn,Pn,Fn,In,Cn,Ln,Rn,zn,Bn,Hn,Un]),jq=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Yn(qn(e))){if(!i&&Aq.has(a)){let e=Gn(o);e.length>0&&e[0]&&(i=e[0])}let e=kq.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof K||(r=!0),n.push(`${a}: ${e instanceof Error?e.message:String(e)}`)}}if(n.length>0){i&&t.sessionState.set(i,`click.error`,n.join(`
463
- `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new K(e)}};function Mq(e){return(t,n)=>{let r=n.history.begin(),i=n.navigation.begin(r.sessionState),a=[];try{e(t,{...n,sessionState:r.sessionState,journal:r,navigating:i.sessionState})}catch(e){a.push(e)}i.commit();try{r.commit()}catch(e){a.push(e)}if(a.length===1)throw a[0];if(a.length>1)throw Error(a.map(e=>String(e.message??e)).join(`; `))}}const Nq=new Map([...kq,[vn,jq]].map(([e,t])=>[e,Mq(t)]));Object.freeze([...Nq.keys()]);const Pq=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`]),Fq=[[`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`]],Iq=[[`workspace.added_dirs`,`string-list`]];function Lq(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of Fq){let i=Bq(n,e);if(i==null)t.missingRequired.push(e);else{let n=Rq(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of Iq){let i=Bq(n,e),a=i===void 0?r:zq(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))Pq.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function Rq(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function zq(e){return Array.isArray(e)&&e.every(e=>Rq(e)===`string`)?`string-list`:Rq(e)}function Bq(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 Vq(e,t){switch(e){case`vars`:return{what:e,vars:Hq(t)};case`segments`:return{what:e,segments:qq(t)};case`config`:return{what:e,config:Zq(t)}}}function Hq(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=Gq(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=Uq(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:Wq(r.lastUpdatedMs())})}return o}function Uq(e){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`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function Wq(e){return e===null?null:Math.max(0,Date.now()-e)}function Gq(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,Kq(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}`,Kq(i));return t}function Kq(e){return e.kind}function qq(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=Yq(n),o=Jq(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:Xq(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function Jq(e){let t=new Map;for(let n of Yg(e.presets))for(let r of fg(Qg(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=cg(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function Yq(e){let t=[],n=new Set;for(let r of fg(Hg(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 Xq(e,t,n){let r=new Set;for(let i of b_(e,t).keys()){if(n.has(i)){r.add(i);continue}let e=i.split(`.`);for(;e.length>1;){e.pop();let t=e.join(`.`);if(n.has(t)){r.add(t);break}}}return Array.from(r).sort()}function Zq(e){return e===null?null:e.config}const Qq=[`vars`,`segments`,`config`];function $q(e){return typeof e==`string`&&Qq.includes(e)}function eJ(e){return Math.max(1,e-2)}var tJ=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return l.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t){let n=this.pathFor(e);if(t===(this.written.get(e)??null))return null;try{return t===null?(r.rmSync(n,{force:!0}),this.written.delete(e)):(r.mkdirSync(this.dir,{recursive:!0,mode:448}),r.writeFileSync(n,t,{mode:384}),this.written.set(e,t)),null}catch(e){return`${n}: ${e.message}`}}reset(){this.written.clear();try{return r.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};function nJ(e,t){for(let n of Object.entries(t))e.push(n)}const rJ={ok:`info`,"bad-request":`warn`,threw:`error`};function iJ(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,y(e.error)]]}}const aJ=/^[^\s"=\\]+$/,oJ=e=>aJ.test(e)?e:JSON.stringify(e);function sJ(e,t,n){let r=[...e,[`took`,`${n}ms`],[`outcome`,t.kind],...iJ(t)];return{level:rJ[t.kind],line:`render${r.map(([e,t])=>` ${e}=${oJ(t)}`).join(``)}`}}const cJ=new aU,lJ=new lK;Ae(cJ.launchStats);const uJ=new dT({counters:cJ,logger:A}),dJ=OB({watchers:uJ,logger:A}),{gitProvider:fJ,usageStore:pJ,mementoProvider:mJ}=dJ,hJ=new cU,gJ=new vW(hJ,A),_J=new VW,vJ=new hh,yJ=new tJ($e()),bJ=new rU({gitService:fJ,sessionState:hJ,watchers:uJ},{observers:{onReload:e=>A(`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)}`)}}),xJ=60*1e3;function SJ(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(ne(e)),t.argv[1]&&n.push(t.argv[1]);let i=new Map;for(let e of n)try{i.set(e,r.statSync(e).mtimeMs)}catch{}let a=null,o=()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){A(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),RJ(0);return}}catch(e){A(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,xJ),a.unref())},checkNow:o}}const CJ=SJ(),wJ=Dz({entryUrl:import.meta.url,intervalMs:xJ,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>CJ.checkNow(),log:A});let TJ=null,EJ=null,DJ=0;function OJ(){t.on(`uncaughtException`,e=>{A(`error`,`uncaughtException: ${e.stack||e.message}`),RJ(1)}),t.on(`unhandledRejection`,e=>{A(`error`,`unhandledRejection: ${String(e)}`),RJ(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{A(`info`,`received ${e}, shutting down`),RJ(0)});try{DJ=Wt(t.env)}catch(e){A(`error`,`refusing to boot: ${e.message}`),RJ(1);return}TJ=ca(t.pid);let e=va(ba(TJ));if(!e.decision.allow){A(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),RJ(1);return}EJ=e.registryPath,r.mkdirSync(Be(),{recursive:!0}),We(Ve()),hJ.useStorage(new uU(qe(),500,A)),gJ.useStorage(zW(Je(),A)),da({anchor:ua(t.env),isAlive:fa,onOrphaned:e=>{A(`info`,`parent watchdog: ${e}; shutting down`),RJ(0)}}),kJ(S.createServer({allowHalfOpen:!1},e=>{zJ(e)}),Ve(),!1)}function kJ(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){A(`error`,`server error: ${i.message}`),RJ(1);return}if(r){A(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}AJ(e,n)}),e.listen(n,()=>jJ(n))}function AJ(e,n){let i=Qi($i(Ge(n)),(e,t)=>sa(e,t,{readStartTime:oa,pidAlive:fa}));if(i.kind===`attach-and-exit`){A(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}A(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){A(`error`,`cannot unlink stale socket ${n}: ${e.message}`),RJ(1);return}}kJ(e,n,!0)}function jJ(e){let n=na(e);if(n.kind!==`present`){A(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),RJ(0);return}FJ(e);try{r.chmodSync(e,384)}catch(e){A(`warn`,`chmod socket failed: ${e.message}`)}A(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(C.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(DJ/1048576)}MB`),sn();let i=yJ.reset();i!==null&&A(`warn`,`diagnostic dump wipe failed: ${i}`),CJ.arm(),wJ.arm(),PJ(),MJ(e,n.identity)}function MJ(e,n){aa({bound:n,myPid:t.pid,readIdentity:()=>na(e),readLease:()=>$i(Ge(e)),shutdown:e=>RJ(e),log:A}).arm()}let NJ=null;function PJ(){NJ=Jt(Zt(cJ.startedAt.getTime(),e=>RJ(e),{rssLimitBytes:DJ})),NJ.arm()}function FJ(e){let n=ea(Ge(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:TJ});n!==null&&A(`warn`,`lease write failed: ${n}`)}let IJ=0,LJ=!1;function RJ(e){if(!LJ){LJ=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{fJ.close()}catch(e){A(`warn`,`gitService close failed: ${e.message}`)}try{pJ.close()}catch(e){A(`warn`,`usageStore close failed: ${e.message}`)}try{uJ.closeAll()}catch(e){A(`warn`,`watcherRegistry close failed: ${e.message}`)}try{hJ.flush()}catch(e){A(`warn`,`sessionState flush failed: ${e.message}`)}ta(Ke(),t.pid),EJ!==null&&ya(EJ,t.pid,ga,e=>r.unlinkSync(e)),t.exit(e)}}function zJ(e){IJ++,cJ.inFlight=IJ;let t=!1,n=(n,r)=>{if(t){r!==null&&A(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>RJ(r);try{e.end(k(n),i)}catch(e){A(`warn`,`response write failed: ${e.message}`),i?.()}},r=!1,i=setTimeout(()=>{r=!0,cJ.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),a=_t(e=>{HJ(e,()=>r).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{A(`error`,`handler threw: ${y(e)}`),n(VJ(e),null)})},e=>{A(`warn`,`frame parse failed: ${e.message}`),n({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null)});e.on(`data`,a),e.on(`error`,e=>{A(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(i),IJ=Math.max(0,IJ-1),cJ.inFlight=IJ})}const BJ=e=>({resp:e,exitAfterFlush:null}),VJ=e=>({ok:!1,error:e instanceof Error?e.message:y(e),code:`RENDER_FAILED`,daemonV:3});async function HJ(e,t){if(!e||typeof e!=`object`||typeof e.v!=`number`)return BJ({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?A(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):A(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null};if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0};if(e.kind===`stats`)return BJ({ok:!0,stats:cJ.snapshot({gitCache:fJ.getStats(),usageCache:pJ.getStats(),renderCacheSize:bJ.size,effectCache:vJ.getStats(),watchersActive:uJ.size(),nextRestartReason:NJ?.describeNextRestart()??null,handlerProbes:lJ.list()})});if(e.kind===`render`){cJ.requestsTotal++;let n=new Date,r=CT(n),i=n.getTime(),a=[],o=await XJ(e,r,a).catch(e=>({outcome:{kind:`threw`,error:e},resp:VJ(e)}));o.outcome.kind!==`ok`&&cJ.requestsErrored++,nJ(a,{timedOut:t()?`Y`:`N`});let{level:s,line:c}=sJ(a,o.outcome,Date.now()-i);return A(s,c),BJ(o.resp)}if(e.kind===`click`)return BJ(YJ(e.verb,e.value,ht(e.clientVersion)));if(e.kind===`debug`){if(!$q(e.what))return BJ({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${Qq.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=bJ.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?qJ(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):KJ};return BJ({ok:!0,debug:Vq(e.what,n)})}return BJ({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function UJ(e,t){let{values:n,tokens:r}=b({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),i=[...new Set((r??[]).filter(e=>e.kind===`option`&&e.name!==`config`).map(e=>`--${e.name}`))];return{configFile:ZF(t,n.config),unknownFlagsError:i.length>0?`Unknown flags: ${i.join(`, `)}`:null}}const WJ={sessionState:hJ,dlog:A,applyUpdate:()=>wJ.act(),doctor:WG(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];bJ.reload(...t);let n=bJ.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),probes:lJ,memento:mJ,claudeInput:kK(),history:gJ,navigation:_J,configFor:e=>bJ.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>bJ.reload(e.projectDir,e.cwd,e.configFile??void 0)};WJ.reloadConfig;const GJ={endcaps:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:Lm,width:1/0},KJ=new Map;function qJ(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,Oh(a,{...GJ,charset:t,colorCompatibility:n}));return r}const JJ={...dJ,history:e=>gJ.depth(e)};function YJ(e,t,n){let r=Nq.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return r(t,{...WJ,clientVersion:n}),{ok:!0,output:``}}catch(e){let t=e instanceof K?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}async function XJ(e,t,n){let{report:r}=Lq(e.hookData);for(let e of r.unknownTopLevelFields)A(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let i=[];for(let e of r.missingRequired)i.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of r.typeMismatches)i.push(`field '${e}' expected ${t}, got ${n}`);if(f(e.cwd)||i.push(`request 'cwd' is not an absolute path: "${e.cwd}"`),i.length>0)return{outcome:{kind:`bad-request`,problems:i},resp:{ok:!1,error:`malformed hookData: ${i.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3}};nJ(n,{sid:e.hookData.session_id,at:t.toFixed(3)});let a=e.hookData.workspace.project_dir,{configFile:o,unknownFlagsError:s}=UJ(e.args,e.cwd),c=e.hookData.session_id,l=ot(e),u=st(e,l),d=ct(u);nJ(n,{termCols:String(l.termCols??`?`),termRows:String(l.termRows??`?`),refused:u.map(e=>e.hint).join(`,`)||`-`});let p=JSON.stringify(l);hJ.get(c,`client-hints`)!==p&&hJ.set(c,_q,p);let m=hJ.get(c,`config-override`)??o??l.configEnv,h=bJ.getOrCreate(a,e.cwd,m),g=qK({projectDir:a,cwd:e.cwd,configFile:m??null});hJ.get(c,`render-origin`)!==g&&hJ.set(c,KK,g);let _=l.termCols,v=eJ(_??120),y=kh(l.termRows);nJ(n,{width:String(v)});let{authoredRoots:b}=h.state,x=t=>hJ.get(e.hookData.session_id,t),S=XL(h.state.config,x,e=>b.has(e)),C=await hR(e.hookData,t,{...JJ,navigation:e=>_J.depth(e,hJ,az(h.state.config))},e.cwd,h.state.neededInputPaths(S.preset),S,l,{...KR(h.state.config,h.state.fileHeldSettings,x),configPath:h.configLayers.includes(h.configHome)?h.configHome:null});nJ(n,{prompts:String(C.metrics?.messageCount??`-`),nonPrompts:String(C.metrics?.nonPrompts??`-`),pr:tR(C.git)});let ee=[],te=ZL(S,v),ne=vJ.of(c),re=IH(h.state.config,h.state.compiled,h.state.store,h.state.registry,C,t,te,{perSegmentSink:h.state.lastRenderCellsBySegment,onRenderWarning:e=>ee.push(e)},{...QL(S),effects:ne}),ie=hJ.get(e.hookData.session_id,`click.error`);ie&&hJ.clear(e.hookData.session_id,`click.error`);let ae=[s,d,h.lastError,ie].filter(Boolean).join(`
464
- `),w=wJ.notice({sessionId:c,dismissed:hJ.get(c,dz),enabled:S.updateNotice}),T=h.lastError===null?null:h.failedFile,oe=[...h.lastWarning===null?[]:[{kind:`load`,message:h.lastWarning}],...ee],E=Ph(ae,w,oe.map(e=>e.message).join(`
465
- `)),se=yJ.sync(c,E===null?null:Ih(E));se!==null&&A(`warn`,`diagnostic dump failed: ${se}`);let ce=Lh(re,E,{fullText:se===null?{kind:`file`,path:yJ.pathFor(c)}:{kind:`unavailable`,reason:se},failedConfigFile:T},{width:v,rowCap:y,colorCompatibility:S.colorCompatibility}),le=fJ.getStats(),ue=pJ.getStats(),de=ne.lastFrame(),fe=de.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,pe=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,me=oe.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 nJ(n,{git:`${le.size}/${le.hits}h/${le.misses}m`,usage:`${ue.size}/${ue.hits}h/${ue.misses}m`,effect:de.effect,effectT:de.t.toFixed(3),effectRows:`${de.made}made/${de.reused}reused`,effectOwn:fe,fadeBasis:de.basis,stateRev:String(de.revision),fades:pe(de.fades),leaves:pe(de.leaves),err:ae?`Y`:`N`,upd:String(w.length),warn:me}),{outcome:{kind:`ok`},resp:{ok:!0,output:ce+`
466
- `}}}const ZJ={connectMs:200,budgetMs:500};async function QJ(e,n){let r=n.includes(`--json`),i=await $J(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${Tt(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
467
- `);return}t.stdout.write(eY(i.value))}function $J(e){return yt({kind:`debug`,what:e},ZJ,e=>`debug`in e?e.debug:void 0)}function eY(e){switch(e.what){case`vars`:return tY(e.vars);case`segments`:return nY(e.segments);case`config`:return rY(e.config);default:return e}}function tY(e){if(e.length===0)return`no variables (DSL not active)
468
- `;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?``:` ${aY(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${iY(a.value)}${e}${o}`)}return t.join(`
460
+ `}const pK=e=>({kind:`ok`,value:e}),mK=e=>({kind:`failed`,reason:e});var hK=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const gK=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function _K(e){return gK.test(e)?e:null}function vK(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return pK(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return pK({app:n,missing:mK(`its script could not be read (${r.reason})`)});let i=Ii(r.value);return pK({app:n,missing:i===null?mK("its script is not one `cc-candybar install` wrote"):pK([i.node,i.script].filter(t=>!e.exists(t)))})}async function yK(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 bK(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(`${_n}://${Vn}/${n}`);return(r===null?await yK(e,n):null)??{kind:`lost`,unopened:r,opener:vK(e)}}function xK(e,t,n){let r=Ne({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?pK(r.stdout):mK(r.stderr.trim()||r.error||r.reason)}const SK=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${_n}://probe"));u.isNil() ? "" : u.path.js`;async function CK(){let e=await iK();if(e.kind!==`ok`)return mK(Tt(e).split(`
461
+ `).join(` — `));let{version:t,handlerProbes:n}=e.value;return Array.isArray(n)?pK({version:t,arrivals:n}):mK(`the running daemon (${t}) predates this check`)}function wK(){return{platform:process.platform,sockets:{own:Ve(),handler:He()},now:Date.now,nonce:w,daemon:CK,open:e=>{let t=xK(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=xK(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,SK]);if(e.kind===`failed`)return e;let t=e.value.trim();return pK(t===``?null:t)},script:e=>xK(`doctor.osadecompile`,`/usr/bin/osadecompile`,[Li(e)]),exists:r.existsSync}}const TK=/^─{20,}/,EK=/^❯(\s|$)/,DK=/›\s*stashed$/;function OK(e){if(e.inMode)return{kind:`in-mode`};let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>TK.test(e)?[t]:[]).at(-2);return n===void 0||!EK.test(t[n+1]??``)?{kind:`no-prompt`}:DK.test(t[n-1]??``)?{kind:`stashed`}:{kind:`ready`}}const kK={"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 AK(e,t,n){if(t===void 0)return{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`};if(t===null)return{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only type into a tmux pane`};let r=OK(e.read(t));if(r.kind!==`ready`)return{kind:`refused`,reason:kK[r.kind]};let i=e.type(t,n);return i.kind===`typed`?{kind:`typed`,pane:t.pane}:i}const jK=`cc-candybar-slash`;function MK(e,t,n,r){let i=CB(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function NK(e){let t=MK(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(`
462
+ `);return{inMode:n!==`0`,screen:r}}function PK(e,t){let n=MK(e,`claude-input.type`,[`load-buffer`,`-b`,jK,`-`,`;`,`send-keys`,`-t`,e.pane,`C-s`,`;`,`paste-buffer`,`-p`,`-d`,`-b`,jK,`-t`,e.pane,`;`,`send-keys`,`-t`,e.pane,`Enter`],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 FK(){return{read:NK,type:PK}}function IK(e){if(!e)throw new K(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new K(`invalid session id "${e}"`);return e}function LK(e){return RK(()=>decodeURIComponent(e))}function RK(e){try{return e()}catch(e){throw e instanceof URIError?new K(`malformed wire encoding: ${e.message}`):e}}function zK(e,t){let n=Ne({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 BK=(e,t)=>zK(LK(e),t),VK=(e,t)=>{let n=Ne({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,LK(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`})`)}},HK=(e,t)=>zK(LK(e),t),UK=(e,t)=>zK(LK(e),t),WK=(e,t)=>{let n=IK(LK(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},GK=(e,t)=>{let[n=``,...r]=RK(()=>Gn(e)),i=IK(n),a=oz(rq(t,i));if(r.length===0)throw new K(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new K(`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 K(`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 K(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}YK(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})`)},KK=/^-?\d+$/;function qK(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const JK=(e,t)=>{let[n=``,r=``,i=``]=RK(()=>Gn(e)),a=IK(n);if(!r)throw new K(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!KK.test(i))throw new K(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=rq(t,a),c=oz(s),l=c.rangeParamsFor(r);if(!l)throw new K(`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&&KK.test(u)?XK(l,parseInt(u,10)):ZK(`step-state`,r,l,lz(s,e=>t.sessionState.get(a,e),r)),f=qK(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new K(`step-state: ${p.reason}`);YK(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 YK(e,t,n,r){let i=r.filter(e=>e.key.startsWith(oO));if(i.length===0)return;let a=zR(rq(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new K(`${n}: refused — ${a.join(`; `)}`)}function XK(e,t){return Math.max(e.min,Math.min(e.max,t))}function ZK(e,t,n,r){if(r===null)return n.min;if(!KK.test(r))throw new K(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return XK(n,parseInt(r,10))}const QK=`render-origin`;function $K(e){return JSON.stringify(e)}function eq(e){let t;try{t=JSON.parse(e)}catch{throw new K(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new K(`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 K(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function tq(e,t){let n=e.sessionState.get(t,QK);if(n===null)throw new K(`session ${t} has not rendered yet — no config to act on`);return eq(n)}function nq(e,t,n){let r=e.sessionState.get(t,QK);if(r===null)return;let i=eq(r),{path:a}=iq(i);n.some(e=>e.kind===`file`&&e.file===a)&&e.reloadConfig(i)}function rq(e,t){return e.configFor(tq(e,t))}function iq(e){return RI(e.projectDir,e.cwd,e.configFile??void 0)}function aq(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const oq=(e,t)=>{let[n=``,r=``,i=``]=RK(()=>Gn(e)),a=IK(n),o=tq(t,a),s=t.configFor(o),c=yM(s);if(!r)throw new K(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new K(`set-config: ${l.reason}`);let u=iq(o),d=LR(s,e=>t.sessionState.get(a,e),r);tW(aq(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},sq=(e,t)=>{let[n=``,r=``,i=``]=RK(()=>Gn(e)),a=IK(n);if(!r)throw new K(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!KK.test(i))throw new K(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=tq(t,a),c=t.configFor(s),l=yM(c),u=l.rangeParamsFor(r);if(!u)throw new K(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=iq(s),f=LR(c,e=>t.sessionState.get(a,e),r),p=eW(d.path,f.key),m=typeof p==`number`?XK(u,p):ZK(`step-config`,r,u,xM(f.globals,r)),h=qK(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new K(`step-config: ${g.reason}`);tW(aq(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})`)},cq=(e,t)=>{let[n=``]=RK(()=>Gn(e)),r=IK(n),i=tq(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=FR(a,o),c=RR(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=oz(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new K(`save: ${t.reason}`);return[e.target,t.value]});uq(`save`,l,c);let d=iq(i);nW(aq(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(lq)].join(` `)} → ${d.path} (session=${r})`)},lq=e=>`${e.preset}/${e.id}.settings.${e.setting}=${jg(e.value)}`;function uq(e,t,n){for(let r of n){let n=t.validate(r.key,jg(r.value));if(!n.ok)throw new K(`${e}: ${n.reason}`)}}const dq=(e,t)=>{let[n=``]=RK(()=>Gn(e)),r=IK(n),i=tq(t,r),a=t.configFor(i),o=HR(a,e=>t.sessionState.get(r,e)),s=oz(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new K(`save-preset: ${t.reason}`);return[e.configKey,t.value]});uq(`save-preset`,s,o.placements);let l=iq(i),u=lW(aq(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Sa.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,xa.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(lq)].join(` `)} → ${l.path} (session=${r})`)},fq=(e,t)=>{let[n=``]=RK(()=>Gn(e)),r=IK(n),i=tq(t,r),a=WR(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new K(`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=iq(i);uW(aq(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(FR(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=vg.map(e=>xa[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} ${vg.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},pq=(e,t)=>{let[n=``,r=``]=RK(()=>Gn(e)),i=IK(n);if(!r)throw new K(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=tq(t,i),o=iq(a);dW(aq(t,i),o,r),t.reloadConfig(a);let s=xa.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},mq=(e,t)=>{let[n=``,...r]=RK(()=>Gn(e)),i=IK(n),a=tq(t,i),o=yM(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new K(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=iq(a),l=r.map(GR),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);oW(aq(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 hq(e,t){let n=(e,t)=>[...pg($g(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Xg(t.presets).flatMap(e=>n(t,e).map(t=>sO($T(e),lg(t)))));return Xg(e.presets).flatMap(t=>n(e,t).map(e=>({member:sO($T(t),lg(e)),node:e})).filter(({member:e})=>!r.has(e)))}function gq(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[tO]:[]])}const _q=(e,t)=>{let[n=``,r=``,i=``]=RK(()=>Gn(e)),a=IK(n),o=tq(t,a),s=t.configFor(o),c=yM(s);if(!r)throw new K(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new K(`apply-layout-op: ${l.reason}`);let u=aM(l.value);if(u===null)throw new K(`apply-layout-op: "${l.value}" is not a layout op token`);let d=iq(o),f=fW(aq(t,a),d,r,u);t.reloadConfig(o);let p=gq(hq(s,t.configFor(o)),t.sessionState.get(a,tO)).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})`)},vq=(e,t)=>{let[n=``]=RK(()=>Gn(e)),r=IK(n);t.journal.commit();let i=t.history.undo(r);nq(t,r,i),t.dlog(`info`,`undo: restored ${PW(i)} (session=${r})`)},yq=(e,t)=>{let n=IK(LK(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,oz(rq(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},bq=(e,t)=>{let n=IK(LK(e));t.journal.commit();let r=t.history.rewind(n);nq(t,n,r),t.dlog(`info`,`rewind: put back ${PW(r)||`nothing`} as edit mode found it (session=${n})`)},xq=(e,t)=>{let[n=``]=RK(()=>Gn(e)),r=IK(n);t.journal.commit();let i=t.history.redo(r);nq(t,r,i),t.dlog(`info`,`redo: re-applied ${PW(i)} (session=${r})`)},Sq=(e,t)=>{IK(LK(e)),t.applyUpdate()},Cq=`client-hints`;function wq(e,t){let n=e.sessionState.get(t,Cq);if(n===null)throw new K(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new K(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new K(`client hints record is not an object: ${n}`);return ot(r)}function Tq(e,t,n){let r=hk(n);e.sessionState.setBatch(t,Sk(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${bk(n.nerdFont,n.marks)} ${yk(n.terminal,n.clicked)} (session=${t})`)}function Eq(e,t){let n;try{n=eK(e.doctor,wq(e,t),tq(e,t),n=>e.sessionState.get(t,n))}catch(e){throw e instanceof JW?new K(e.message):e}return{...n,urlHandler:QG(e.clientVersion),askedBy:`click`,clicked:Dq(e,n)}}function Dq(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?WO(t.identified):null;if(r===null||n.kind===`failed`)return n;try{e.doctor.clicked.record(r)}catch(t){return e.dlog(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}return{kind:`ok`,value:n.value.includes(r)?n.value:[...n.value,r]}}const Oq=(e,t)=>{let n=IK(LK(e));Tq(t,n,Eq(t,n))},kq=(e,t)=>{let n=_K(LK(e));if(n===null)throw new K(`doctor-probe: the value is not a probe nonce`);t.probes.arrive({nonce:n,handler:t.clientVersion}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${t.clientVersion??`unreported`}`)},Aq=(e,t)=>{let[n=``,r=``]=RK(()=>Gn(e)),i=IK(n),a=gk(r);if(a===void 0)throw new K(`doctor-fix: unknown check "${r}"`);let o=Eq(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new K(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=tK(s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.path.join(`.`)}=${JSON.stringify(s.fix.value)} (session=${i})`),Tq(t,i,c)},jq=(e,t)=>{let[n=``,r=``,i=``]=RK(()=>Gn(e)),a=IK(n),o=gk(r);if(o===void 0)throw new K(`doctor-mark: unknown check "${r}"`);if(!JO.includes(i))throw new K(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${JO.join(` or `)}`);let s=Eq(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new K(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);if(s.marks.kind===`failed`)throw new K(`doctor-mark: ${s.marks.reason}`);let l=[o.name,c.sighting.id,i];t.doctor.marks.record(...l),t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),Tq(t,a,{...s,marks:{kind:`ok`,value:KW(s.marks.value,...l)}})},Mq=(e,t)=>{let[n=``,...r]=RK(()=>Gn(e)),i=IK(n),a=tq(t,i),o=Object.values(t.configFor(a).actions).filter(e=>`ceiling`in e).find(e=>{let t=xP(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(o===void 0)throw new K(`ceiling: "${r.join(` `)}" is not a move this config declares`);let s=o.ceiling===`set`?{kind:`set`,to:o.to}:{kind:`clear`},c=RL({sessionId:i,projectDir:a.projectDir,cwd:a.cwd},wq(t,i));t.memento.move(c,s),t.dlog(`info`,`ceiling: ${r.join(` `)} (session=${i} claudeConfigDir=${c.claudeConfigDir})`)},Nq=(e,t)=>{let[n=``,r=``]=RK(()=>Gn(e)),i=IK(n),a=Object.values(t.configFor(tq(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new K(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=AK(t.claudeInput,wq(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new K(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)},Pq=`config-override`,Fq=new Map([[xn,BK],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new K(`load-config: expected <sessionId>/<path> (missing separator)`);let r=IK(RK(()=>decodeURIComponent(e.slice(0,n)))),i=RK(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new K(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new K(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,Pq),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,Pq,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Sn,VK],[yn,GK],[bn,JK],[N,oq],[En,sq],[jn,mq],[Dn,cq],[On,dq],[kn,fq],[An,pq],[Mn,_q],[Nn,vq],[Pn,xq],[Fn,yq],[In,bq],[wn,HK],[Tn,UK],[Cn,WK],[Ln,Sq],[Rn,Oq],[zn,Aq],[Bn,jq],[Vn,kq],[Hn,Mq],[Un,Nq]]),Iq=new Set([yn,bn,N,En,jn,Dn,On,kn,An,Mn,Nn,Pn,Fn,In,Cn,Ln,Rn,zn,Bn,Hn,Un]),Lq=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Yn(qn(e))){if(!i&&Iq.has(a)){let e=Gn(o);e.length>0&&e[0]&&(i=e[0])}let e=Fq.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof K||(r=!0),n.push(`${a}: ${e instanceof Error?e.message:String(e)}`)}}if(n.length>0){i&&t.sessionState.set(i,`click.error`,n.join(`
463
+ `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new K(e)}};function Rq(e){return(t,n)=>{let r=n.history.begin(),i=n.navigation.begin(r.sessionState),a=[];try{e(t,{...n,sessionState:r.sessionState,journal:r,navigating:i.sessionState})}catch(e){a.push(e)}i.commit();try{r.commit()}catch(e){a.push(e)}if(a.length===1)throw a[0];if(a.length>1)throw Error(a.map(e=>String(e.message??e)).join(`; `))}}const zq=new Map([...Fq,[vn,Lq]].map(([e,t])=>[e,Rq(t)]));Object.freeze([...zq.keys()]);const Bq=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`]),Vq=[[`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`]],Hq=[[`workspace.added_dirs`,`string-list`]];function Uq(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of Vq){let i=Kq(n,e);if(i==null)t.missingRequired.push(e);else{let n=Wq(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of Hq){let i=Kq(n,e),a=i===void 0?r:Gq(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))Bq.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function Wq(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function Gq(e){return Array.isArray(e)&&e.every(e=>Wq(e)===`string`)?`string-list`:Wq(e)}function Kq(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 qq(e,t){switch(e){case`vars`:return{what:e,vars:Jq(t)};case`segments`:return{what:e,segments:$q(t)};case`config`:return{what:e,config:rJ(t)}}}function Jq(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=Zq(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=Yq(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:Xq(r.lastUpdatedMs())})}return o}function Yq(e){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`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function Xq(e){return e===null?null:Math.max(0,Date.now()-e)}function Zq(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,Qq(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}`,Qq(i));return t}function Qq(e){return e.kind}function $q(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=tJ(n),o=eJ(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:nJ(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function eJ(e){let t=new Map;for(let n of Xg(e.presets))for(let r of pg($g(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=lg(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function tJ(e){let t=[],n=new Set;for(let r of pg(Ug(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 nJ(e,t,n){let r=new Set;for(let i of x_(e,t).keys()){if(n.has(i)){r.add(i);continue}let e=i.split(`.`);for(;e.length>1;){e.pop();let t=e.join(`.`);if(n.has(t)){r.add(t);break}}}return Array.from(r).sort()}function rJ(e){return e===null?null:e.config}const iJ=[`vars`,`segments`,`config`];function aJ(e){return typeof e==`string`&&iJ.includes(e)}function oJ(e){return Math.max(1,e-2)}var sJ=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return l.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t){let n=this.pathFor(e);if(t===(this.written.get(e)??null))return null;try{return t===null?(r.rmSync(n,{force:!0}),this.written.delete(e)):(r.mkdirSync(this.dir,{recursive:!0,mode:448}),r.writeFileSync(n,t,{mode:384}),this.written.set(e,t)),null}catch(e){return`${n}: ${e.message}`}}reset(){this.written.clear();try{return r.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};function cJ(e,t){for(let n of Object.entries(t))e.push(n)}const lJ={ok:`info`,"bad-request":`warn`,threw:`error`};function uJ(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,y(e.error)]]}}const dJ=/^[^\s"=\\]+$/,fJ=e=>dJ.test(e)?e:JSON.stringify(e);function pJ(e,t,n){let r=[...e,[`took`,`${n}ms`],[`outcome`,t.kind],...uJ(t)];return{level:lJ[t.kind],line:`render${r.map(([e,t])=>` ${e}=${fJ(t)}`).join(``)}`}}const mJ=new sU,hJ=new hK;Ae(mJ.launchStats);const gJ=new fT({counters:mJ,logger:A}),_J=kB({watchers:gJ,logger:A}),{gitProvider:vJ,usageStore:yJ,mementoProvider:bJ}=_J,xJ=new uU,SJ=new bW(xJ,A),CJ=new UW,wJ=new hh,TJ=new sJ($e()),EJ=new aU({gitService:vJ,sessionState:xJ,watchers:gJ,log:A},{observers:{onReload:e=>A(`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)}`)}}),DJ=60*1e3;function OJ(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(ne(e)),t.argv[1]&&n.push(t.argv[1]);let i=new Map;for(let e of n)try{i.set(e,r.statSync(e).mtimeMs)}catch{}let a=null,o=()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){A(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),WJ(0);return}}catch(e){A(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,DJ),a.unref())},checkNow:o}}const kJ=OJ(),AJ=Oz({entryUrl:import.meta.url,intervalMs:DJ,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>kJ.checkNow(),log:A});let jJ=null,MJ=null,NJ=0;function PJ(){t.on(`uncaughtException`,e=>{A(`error`,`uncaughtException: ${e.stack||e.message}`),WJ(1)}),t.on(`unhandledRejection`,e=>{A(`error`,`unhandledRejection: ${String(e)}`),WJ(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{A(`info`,`received ${e}, shutting down`),WJ(0)});try{NJ=Wt(t.env)}catch(e){A(`error`,`refusing to boot: ${e.message}`),WJ(1);return}jJ=ca(t.pid);let e=va(ba(jJ));if(!e.decision.allow){A(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),WJ(1);return}MJ=e.registryPath,r.mkdirSync(Be(),{recursive:!0}),We(Ve()),xJ.useStorage(new fU(qe(),500,A)),SJ.useStorage(VW(Je(),A)),da({anchor:ua(t.env),isAlive:fa,onOrphaned:e=>{A(`info`,`parent watchdog: ${e}; shutting down`),WJ(0)}}),FJ(S.createServer({allowHalfOpen:!1},e=>{GJ(e)}),Ve(),!1)}function FJ(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){A(`error`,`server error: ${i.message}`),WJ(1);return}if(r){A(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}IJ(e,n)}),e.listen(n,()=>LJ(n))}function IJ(e,n){let i=Qi($i(Ge(n)),(e,t)=>sa(e,t,{readStartTime:oa,pidAlive:fa}));if(i.kind===`attach-and-exit`){A(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}A(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){A(`error`,`cannot unlink stale socket ${n}: ${e.message}`),WJ(1);return}}FJ(e,n,!0)}function LJ(e){let n=na(e);if(n.kind!==`present`){A(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),WJ(0);return}VJ(e);try{r.chmodSync(e,384)}catch(e){A(`warn`,`chmod socket failed: ${e.message}`)}A(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(C.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(NJ/1048576)}MB`),sn();let i=TJ.reset();i!==null&&A(`warn`,`diagnostic dump wipe failed: ${i}`),kJ.arm(),AJ.arm(),BJ(),RJ(e,n.identity)}function RJ(e,n){aa({bound:n,myPid:t.pid,readIdentity:()=>na(e),readLease:()=>$i(Ge(e)),shutdown:e=>WJ(e),log:A}).arm()}let zJ=null;function BJ(){zJ=Jt(Zt(mJ.startedAt.getTime(),e=>WJ(e),{rssLimitBytes:NJ})),zJ.arm()}function VJ(e){let n=ea(Ge(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:jJ});n!==null&&A(`warn`,`lease write failed: ${n}`)}let HJ=0,UJ=!1;function WJ(e){if(!UJ){UJ=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{vJ.close()}catch(e){A(`warn`,`gitService close failed: ${e.message}`)}try{yJ.close()}catch(e){A(`warn`,`usageStore close failed: ${e.message}`)}try{gJ.closeAll()}catch(e){A(`warn`,`watcherRegistry close failed: ${e.message}`)}try{xJ.flush()}catch(e){A(`warn`,`sessionState flush failed: ${e.message}`)}ta(Ke(),t.pid),MJ!==null&&ya(MJ,t.pid,ga,e=>r.unlinkSync(e)),t.exit(e)}}function GJ(e){HJ++,mJ.inFlight=HJ;let t=!1,n=(n,r)=>{if(t){r!==null&&A(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>WJ(r);try{e.end(k(n),i)}catch(e){A(`warn`,`response write failed: ${e.message}`),i?.()}},r=!1,i=setTimeout(()=>{r=!0,mJ.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),a=_t(e=>{JJ(e,()=>r).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{A(`error`,`handler threw: ${y(e)}`),n(qJ(e),null)})},e=>{A(`warn`,`frame parse failed: ${e.message}`),n({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null)});e.on(`data`,a),e.on(`error`,e=>{A(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(i),HJ=Math.max(0,HJ-1),mJ.inFlight=HJ})}const KJ=e=>({resp:e,exitAfterFlush:null}),qJ=e=>({ok:!1,error:e instanceof Error?e.message:y(e),code:`RENDER_FAILED`,daemonV:3});async function JJ(e,t){if(!e||typeof e!=`object`||typeof e.v!=`number`)return KJ({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?A(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):A(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null};if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0};if(e.kind===`stats`)return KJ({ok:!0,stats:mJ.snapshot({gitCache:vJ.getStats(),usageCache:yJ.getStats(),renderCacheSize:EJ.size,effectCache:wJ.getStats(),sessionState:{sessions:xJ.size(),observers:xJ.observers()},watchersActive:gJ.size(),nextRestartReason:zJ?.describeNextRestart()??null,handlerProbes:hJ.list()})});if(e.kind===`render`){mJ.requestsTotal++;let n=new Date,r=wT(n),i=n.getTime(),a=[],o=await nY(e,r,a).catch(e=>({outcome:{kind:`threw`,error:e},resp:qJ(e)}));o.outcome.kind!==`ok`&&mJ.requestsErrored++,cJ(a,{timedOut:t()?`Y`:`N`});let{level:s,line:c}=pJ(a,o.outcome,Date.now()-i);return A(s,c),KJ(o.resp)}if(e.kind===`click`)return KJ(tY(e.verb,e.value,ht(e.clientVersion)));if(e.kind===`debug`){if(!aJ(e.what))return KJ({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${iJ.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=EJ.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?$J(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):QJ};return KJ({ok:!0,debug:qq(e.what,n)})}return KJ({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function YJ(e,t){let{values:n,tokens:r}=b({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),i=[...new Set((r??[]).filter(e=>e.kind===`option`&&e.name!==`config`).map(e=>`--${e.name}`))];return{configFile:QF(t,n.config),unknownFlagsError:i.length>0?`Unknown flags: ${i.join(`, `)}`:null}}const XJ={sessionState:xJ,dlog:A,applyUpdate:()=>AJ.act(),doctor:KG(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];EJ.reload(...t);let n=EJ.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),probes:hJ,memento:bJ,claudeInput:FK(),history:SJ,navigation:CJ,configFor:e=>EJ.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>EJ.reload(e.projectDir,e.cwd,e.configFile??void 0)};XJ.reloadConfig;const ZJ={endcaps:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:Lm,width:1/0},QJ=new Map;function $J(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,Oh(a,{...ZJ,charset:t,colorCompatibility:n}));return r}const eY={..._J,history:e=>SJ.depth(e)};function tY(e,t,n){let r=zq.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return r(t,{...XJ,clientVersion:n}),{ok:!0,output:``}}catch(e){let t=e instanceof K?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}async function nY(e,t,n){let{report:r}=Uq(e.hookData);for(let e of r.unknownTopLevelFields)A(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let i=[];for(let e of r.missingRequired)i.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of r.typeMismatches)i.push(`field '${e}' expected ${t}, got ${n}`);if(f(e.cwd)||i.push(`request 'cwd' is not an absolute path: "${e.cwd}"`),i.length>0)return{outcome:{kind:`bad-request`,problems:i},resp:{ok:!1,error:`malformed hookData: ${i.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3}};cJ(n,{sid:e.hookData.session_id,at:t.toFixed(3)});let a=e.hookData.workspace.project_dir,{configFile:o,unknownFlagsError:s}=YJ(e.args,e.cwd),c=e.hookData.session_id,l=ot(e),u=st(e,l),d=ct(u);cJ(n,{termCols:String(l.termCols??`?`),termRows:String(l.termRows??`?`),refused:u.map(e=>e.hint).join(`,`)||`-`});let p=JSON.stringify(l);xJ.get(c,`client-hints`)!==p&&xJ.set(c,Cq,p);let m=xJ.get(c,`config-override`)??o??l.configEnv,h=EJ.getOrCreate(a,e.cwd,m),g=$K({projectDir:a,cwd:e.cwd,configFile:m??null});xJ.get(c,`render-origin`)!==g&&xJ.set(c,QK,g);let _=l.termCols,v=oJ(_??120),y=kh(l.termRows);cJ(n,{width:String(v)});let{authoredRoots:b}=h.state,x=t=>xJ.get(e.hookData.session_id,t),S=ZL(h.state.config,x,e=>b.has(e)),C=await gR(e.hookData,t,{...eY,navigation:e=>CJ.depth(e,xJ,oz(h.state.config))},e.cwd,h.state.neededInputPaths(S.preset),S,l,{...qR(h.state.config,h.state.fileHeldSettings,x),configPath:h.configLayers.includes(h.configHome)?h.configHome:null});cJ(n,{prompts:String(C.metrics?.messageCount??`-`),nonPrompts:String(C.metrics?.nonPrompts??`-`),pr:nR(C.git)});let ee=[],te=QL(S,v),ne=wJ.of(c),re=LH(h.state.config,h.state.compiled,h.state.store,h.state.registry,C,t,te,{perSegmentSink:h.state.lastRenderCellsBySegment,onRenderWarning:e=>ee.push(e)},{...$L(S),effects:ne}),ie=xJ.get(e.hookData.session_id,`click.error`);ie&&xJ.clear(e.hookData.session_id,`click.error`);let ae=[s,d,h.lastError,ie].filter(Boolean).join(`
464
+ `),w=AJ.notice({sessionId:c,dismissed:xJ.get(c,fz),enabled:S.updateNotice}),T=h.lastError===null?null:h.failedFile,oe=[...h.lastWarning===null?[]:[{kind:`load`,message:h.lastWarning}],...ee],E=Ph(ae,w,oe.map(e=>e.message).join(`
465
+ `)),se=TJ.sync(c,E===null?null:Ih(E));se!==null&&A(`warn`,`diagnostic dump failed: ${se}`);let ce=Lh(re,E,{fullText:se===null?{kind:`file`,path:TJ.pathFor(c)}:{kind:`unavailable`,reason:se},failedConfigFile:T},{width:v,rowCap:y,colorCompatibility:S.colorCompatibility}),le=vJ.getStats(),ue=yJ.getStats(),de=ne.lastFrame(),fe=de.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,pe=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,me=oe.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 cJ(n,{git:`${le.size}/${le.hits}h/${le.misses}m`,usage:`${ue.size}/${ue.hits}h/${ue.misses}m`,effect:de.effect,effectT:de.t.toFixed(3),effectRows:`${de.made}made/${de.reused}reused`,effectOwn:fe,fadeBasis:de.basis,stateRev:String(de.revision),fades:pe(de.fades),leaves:pe(de.leaves),err:ae?`Y`:`N`,upd:String(w.length),warn:me}),{outcome:{kind:`ok`},resp:{ok:!0,output:ce+`
466
+ `}}}const rY={connectMs:200,budgetMs:500};async function iY(e,n){let r=n.includes(`--json`),i=await aY(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${Tt(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
467
+ `);return}t.stdout.write(oY(i.value))}function aY(e){return yt({kind:`debug`,what:e},rY,e=>`debug`in e?e.debug:void 0)}function oY(e){switch(e.what){case`vars`:return sY(e.vars);case`segments`:return cY(e.segments);case`config`:return lY(e.config);default:return e}}function sY(e){if(e.length===0)return`no variables (DSL not active)
468
+ `;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?``:` ${dY(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${uY(a.value)}${e}${o}`)}return t.join(`
469
469
  `)+`
470
- `}function nY(e){if(e.length===0)return`no segments (DSL not active)
470
+ `}function cY(e){if(e.length===0)return`no segments (DSL not active)
471
471
  `;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(`
472
472
  `)+`
473
- `}function rY(e){return e===null?`config: DSL not active
473
+ `}function lY(e){return e===null?`config: DSL not active
474
474
  `:JSON.stringify(e,null,2)+`
475
- `}function iY(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function aY(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function oY(){let e=cY();return e===null?null:r.readFileSync(e,`utf-8`)}function sY(){let e;try{e=oY()}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 cY(){let e=l.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let i=l.dirname(l.resolve(n));for(;;){let t=l.join(i,e);if(r.existsSync(t))return t;let n=l.dirname(i);if(n===i)return null;i=n}}function lY(e,t){return ZF(t,e.CC_CANDYBAR_CONFIG)}const uY=5e3;function dY(e,t,n){let r=`/home/tester`,i=Math.floor(n),a=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,o={current_dir:`${r}/code/cc-candybar/src`,project_dir:`${r}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:a,version:`1.15.0`,home:r,cwd:`${r}/code/cc-candybar/src`,transcript_path:`${r}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:o,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`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:i+2*3600},weekly:{percentage:21,resetsAt:i+5*86400},cache:{expiresAt:i+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:zk(4e5,1e6),...$L(e),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:Da(()=>!0),themeDefault:{differs:!0,theme:`<theme>`},resumeCommand:YL(o,a,void 0),configPath:t??`${r}/.config/cc-candybar/config.json5`}}function fY(e,t){let n=FI(e,e),r=RI(n);return r!==null&&t.push(r),n.kind===`chain`?n.layers:[]}async function pY(e,n=t.cwd()){let i=[],a=ZF(n,e)??null,o=a===null?fY(n,i):[a];if(a!==null){let e;try{e=r.statSync(a,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:a,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:a,message:`not a file`}}let s=BI(n,n);s!==null&&i.push(s);try{return{kind:`clean`,layers:o,warnings:i,rendered:await gY(o,n,i)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&o.includes(t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof $T&&i.push(...e.warnings),{kind:`fatal`,layers:o,message:e instanceof $T||e instanceof Error?e.message:String(e),warnings:i})}}async function mY(e,t,n){let r=JI(e,_L,{entered:()=>{},warned:e=>n.push(...e)},{projectDir:t,cwd:t}),{config:i}=r,a=new JH,o=new qT(a,i.globals.default_empty_value??``,void 0,new cU);try{let s=AH(i,o,{cwd:t});n.push(...s.loadWarnings);let c=await o.settled(uY);return c.length>0&&n.push(`source${c.length===1?``:`s`} still running after ${uY} ms, rendered with fallback values: ${c.join(`, `)}`),{layers:e,droppedPlugins:[...r.installed.dropped,...r.layers.flatMap(e=>e.plugins.dropped)],config:i,compiled:s,store:a,registry:o}}catch(e){throw o.dispose(),e}}function hY({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=new Map,l=new Set;return{rendered:IH(t,n,r,i,dY(a,e.at(-1)??null,s),s,ZL(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning: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:}}},QL(a)),failures:c,advisories:l}}async function gY(e,t,n){let r=await mY(e,t,n),{config:i}=r,a=CT(new Date);try{let e=Ez();try{az(i),vM(i)}finally{e()}let t=Xg(null,i.globals.preset,i.presets),o=(e,t)=>{let n=XL(i,t=>t===`preset`?e:null,()=>t),o;try{o=hY(r,n,200,a)}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),...Yg(i.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=r.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(`
475
+ `}function uY(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function dY(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function fY(){let e=mY();return e===null?null:r.readFileSync(e,`utf-8`)}function pY(){let e;try{e=fY()}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 mY(){let e=l.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let i=l.dirname(l.resolve(n));for(;;){let t=l.join(i,e);if(r.existsSync(t))return t;let n=l.dirname(i);if(n===i)return null;i=n}}function hY(e,t){return QF(t,e.CC_CANDYBAR_CONFIG)}const gY=5e3;function _Y(e,t,n){let r=`/home/tester`,i=Math.floor(n),a=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,o={current_dir:`${r}/code/cc-candybar/src`,project_dir:`${r}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:a,version:`1.15.0`,home:r,cwd:`${r}/code/cc-candybar/src`,transcript_path:`${r}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:o,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`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:i+2*3600},weekly:{percentage:21,resetsAt:i+5*86400},cache:{expiresAt:i+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:Bk(4e5,1e6),...eR(e),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:Da(()=>!0),themeDefault:{differs:!0,theme:`<theme>`},resumeCommand:XL(o,a,void 0),configPath:t??`${r}/.config/cc-candybar/config.json5`}}function vY(e,t){let n=II(e,e),r=zI(n);return r!==null&&t.push(r),n.kind===`chain`?n.layers:[]}async function yY(e,n=t.cwd()){let i=[],a=QF(n,e)??null,o=a===null?vY(n,i):[a];if(a!==null){let e;try{e=r.statSync(a,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:a,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:a,message:`not a file`}}let s=VI(n,n);s!==null&&i.push(s);try{return{kind:`clean`,layers:o,warnings:i,rendered:await SY(o,n,i)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&o.includes(t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof eE&&i.push(...e.warnings),{kind:`fatal`,layers:o,message:e instanceof eE||e instanceof Error?e.message:String(e),warnings:i})}}async function bY(e,t,n){let r=YI(e,vL,{entered:()=>{},warned:e=>n.push(...e)},{projectDir:t,cwd:t}),{config:i}=r,a=new YH,o=new JT(a,i.globals.default_empty_value??``,void 0,new uU);try{let s=jH(i,o,{cwd:t});n.push(...s.loadWarnings);let c=await o.settled(gY);return c.length>0&&n.push(`source${c.length===1?``:`s`} still running after ${gY} ms, rendered with fallback values: ${c.join(`, `)}`),{layers:e,droppedPlugins:[...r.installed.dropped,...r.layers.flatMap(e=>e.plugins.dropped)],config:i,compiled:s,store:a,registry:o}}catch(e){throw o.dispose(),e}}function xY({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=new Map,l=new Set;return{rendered:LH(t,n,r,i,_Y(a,e.at(-1)??null,s),s,QL(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning: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:}}},$L(a)),failures:c,advisories:l}}async function SY(e,t,n){let r=await bY(e,t,n),{config:i}=r,a=wT(new Date);try{let e=Dz();try{oz(i),yM(i)}finally{e()}let t=Zg(null,i.globals.preset,i.presets),o=(e,t)=>{let n=ZL(i,t=>t===`preset`?e:null,()=>t),o;try{o=xY(r,n,200,a)}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),...Xg(i.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=r.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(`
476
476
  `)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
477
- `));return d}finally{r.registry.dispose()}}function _Y(e){return e.map(e=>`warning: ${e}\n`).join(``)}function vY(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:_Y(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:_Y(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 yY=`--render`,bY=`Usage: cc-candybar check [${yY}] [config-file]\n`;function xY(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==yY);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${bY}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${bY}`}:{kind:`run`,target:n[0],render:t.includes(yY)}}async function SY(e){let n=xY(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:vY(await pY(n.target??lY(t.env,t.cwd())),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const CY=/^[a-z][a-z0-9+.-]*:\/\//i,wY=/^[^@\s/]+@[^:\s/]+:/,TY=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function EY(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function DY(e,t,n){let r=XF(t,e);if(n(r))return{kind:`path`,dir:r};if(CY.test(e)||wY.test(e))return{kind:`git`,url:e,shown:EY(e)};let i=TY.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 OY(e,t){let n=l.join(e,EI),r=kI(n);if(`error`in r)throw Error(`${t}: could not list ${EI}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${EI}/<name>/${eI}`);return r.folders.map(e=>l.join(n,e,eI))}function kY(e,t,n){let r=(n,...r)=>{let i=Ne({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(`
478
- `))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${EI}/`)}function AY(e,t){switch(e.kind){case`path`:return t(e.dir);case`git`:{let n=r.mkdtempSync(l.join(h.tmpdir(),`cc-candybar-plugin-`));try{return kY(e.url,e.shown,l.join(n,`repo`)),t(l.join(n,`repo`))}finally{r.rmSync(n,{recursive:!0,force:!0})}}}}function jY(e){let t;try{t=r.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 MY(e,t,n,i){switch(i){case`updated`:r.renameSync(l.join(e,eI),l.join(t,eI));return;case`replaced`:r.renameSync(t,n),r.renameSync(e,t);return;case`installed`:r.renameSync(e,t);return}}function NY(e,t,n){let i=OY(e,n);r.mkdirSync(t,{recursive:!0});let a=r.mkdtempSync(l.join(t,`.install-`));try{let o=i.map(e=>{let t=l.join(a,l.basename(l.dirname(e)));r.mkdirSync(t);try{r.copyFileSync(e,l.join(t,eI))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),s=KI(o.map(e=>l.join(e,eI)),_L,{root:e,git:!1});if(s.length>0)throw Error(s.map(e=>`${n}: ${l.join(EI,l.relative(a,e.path))} would not load: ${e.reason.split(a).join(l.join(n,EI))}`).join(`
479
- `));let c=o.map(e=>{let n=l.basename(e),r=l.join(t,n);return{folder:e,name:n,target:r,placed:jY(r)}}),u=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)MY(e,n,l.join(a,`.replaced-${t}`),r),u.push(t)}catch(e){throw Error(`${e.message} (placed before it: ${u.join(`, `)||`none`})`)}return c.map(({target:e,placed:t})=>({path:l.join(e,eI),placed:t}))}finally{r.rmSync(a,{recursive:!0,force:!0})}}function PY(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=DY(n,process.cwd(),zT);if(`error`in i)return console.error(`plugin install: ${i.error}`),2;try{let e=i.kind===`path`?i.dir:i.shown,t=AY(i,t=>NY(t,TI(),e));for(let{path:n,placed:r}of t)console.log(`${r} plugin ${l.basename(l.dirname(n))} → ${n} (from ${e})`);return 0}catch(e){return console.error(`plugin install: ${e.message}`),1}}const FY=`${Gf}${Wf}`;function IY(e){return`${FY}⚠ cc-candybar: ${LY(e)}\n`}function LY(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: ${Uf(e.message,60)}`;case`render_failed`:return`render failed: ${Uf(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${Uf(e.message,60)}`}}function RY(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
480
- `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:IY(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function zY(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 BY=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function VY(e,t,n){return{termCols:zY(e.COLUMNS,n.columns),termRows:zY(e.LINES,n.rows),ssh:BY.some(t=>(e[t]??``)!==``),tmux:OO(e),configEnv:lY(e,t),claudeConfigDir:li(e,t),mementoEnv:nt(e,t),terminalEnv:it(e)}}const HY=` (fix: click the settings menu (${$n} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,UY=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${$n} by default) › 🧰 tools › 🩺 doctor`;function WY({check:e,verdict:t}){return t.ok?`✓ ${e.label}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:HY}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${UY}\n`)}function GY(e){let t={sessionState:new cU},n=tU(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??nU(e.cwd,e.projectDir,t);return r.registry.dispose(),{layers:n.layers,error:n.error,warning:n.warning,unused:r.unused,config:r.config}}async function KY(e,t,n,r,i=void 0){let a;try{a={...QG(e,VY(n,r,{}),{projectDir:r,cwd:r,configFile:ZF(r,i)??lY(n,r)??null},()=>null),urlHandler:await mK(t),askedBy:`command`}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let o=mk(a);return{stdout:o.map(WY).join(``),stderr:``,code:+!o.every(e=>e.verdict.ok)}}async function qY(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
477
+ `));return d}finally{r.registry.dispose()}}function CY(e){return e.map(e=>`warning: ${e}\n`).join(``)}function wY(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:CY(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:CY(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 TY=`--render`,EY=`Usage: cc-candybar check [${TY}] [config-file]\n`;function DY(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==TY);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${EY}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${EY}`}:{kind:`run`,target:n[0],render:t.includes(TY)}}async function OY(e){let n=DY(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:wY(await yY(n.target??hY(t.env,t.cwd())),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const kY=/^[a-z][a-z0-9+.-]*:\/\//i,AY=/^[^@\s/]+@[^:\s/]+:/,jY=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function MY(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function NY(e,t,n){let r=ZF(t,e);if(n(r))return{kind:`path`,dir:r};if(kY.test(e)||AY.test(e))return{kind:`git`,url:e,shown:MY(e)};let i=jY.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 PY(e,t){let n=l.join(e,DI),r=AI(n);if(`error`in r)throw Error(`${t}: could not list ${DI}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${DI}/<name>/${tI}`);return r.folders.map(e=>l.join(n,e,tI))}function FY(e,t,n){let r=(n,...r)=>{let i=Ne({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(`
478
+ `))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${DI}/`)}function IY(e,t){switch(e.kind){case`path`:return t(e.dir);case`git`:{let n=r.mkdtempSync(l.join(h.tmpdir(),`cc-candybar-plugin-`));try{return FY(e.url,e.shown,l.join(n,`repo`)),t(l.join(n,`repo`))}finally{r.rmSync(n,{recursive:!0,force:!0})}}}}function LY(e){let t;try{t=r.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 RY(e,t,n,i){switch(i){case`updated`:r.renameSync(l.join(e,tI),l.join(t,tI));return;case`replaced`:r.renameSync(t,n),r.renameSync(e,t);return;case`installed`:r.renameSync(e,t);return}}function zY(e,t,n){let i=PY(e,n);r.mkdirSync(t,{recursive:!0});let a=r.mkdtempSync(l.join(t,`.install-`));try{let o=i.map(e=>{let t=l.join(a,l.basename(l.dirname(e)));r.mkdirSync(t);try{r.copyFileSync(e,l.join(t,tI))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),s=qI(o.map(e=>l.join(e,tI)),vL,{root:e,git:!1});if(s.length>0)throw Error(s.map(e=>`${n}: ${l.join(DI,l.relative(a,e.path))} would not load: ${e.reason.split(a).join(l.join(n,DI))}`).join(`
479
+ `));let c=o.map(e=>{let n=l.basename(e),r=l.join(t,n);return{folder:e,name:n,target:r,placed:LY(r)}}),u=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)RY(e,n,l.join(a,`.replaced-${t}`),r),u.push(t)}catch(e){throw Error(`${e.message} (placed before it: ${u.join(`, `)||`none`})`)}return c.map(({target:e,placed:t})=>({path:l.join(e,tI),placed:t}))}finally{r.rmSync(a,{recursive:!0,force:!0})}}function BY(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=NY(n,process.cwd(),BT);if(`error`in i)return console.error(`plugin install: ${i.error}`),2;try{let e=i.kind===`path`?i.dir:i.shown,t=IY(i,t=>zY(t,EI(),e));for(let{path:n,placed:r}of t)console.log(`${r} plugin ${l.basename(l.dirname(n))} → ${n} (from ${e})`);return 0}catch(e){return console.error(`plugin install: ${e.message}`),1}}const VY=`${Gf}${Wf}`;function HY(e){return`${VY}⚠ cc-candybar: ${UY(e)}\n`}function UY(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: ${Uf(e.message,60)}`;case`render_failed`:return`render failed: ${Uf(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${Uf(e.message,60)}`}}function WY(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
480
+ `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:HY(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function GY(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 KY=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function qY(e,t,n){return{termCols:GY(e.COLUMNS,n.columns),termRows:GY(e.LINES,n.rows),ssh:KY.some(t=>(e[t]??``)!==``),tmux:kO(e),configEnv:hY(e,t),claudeConfigDir:li(e,t),mementoEnv:nt(e,t),terminalEnv:it(e)}}const JY=` (fix: click the settings menu (${$n} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,YY=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${$n} by default) › 🧰 tools › 🩺 doctor`;function XY({check:e,verdict:t}){return t.ok?`✓ ${e.label}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:JY}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${YY}\n`)}function ZY(e){let t={sessionState:new uU},n=rU(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??iU(e.cwd,e.projectDir,t);return r.registry.dispose(),{layers:n.layers,error:n.error,warning:n.warning,unused:r.unused,config:r.config}}async function QY(e,t,n,r,i=void 0){let a;try{a={...eK(e,qY(n,r,{}),{projectDir:r,cwd:r,configFile:QF(r,i)??hY(n,r)??null},()=>null),urlHandler:await bK(t),askedBy:`command`}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let o=hk(a);return{stdout:o.map(XY).join(``),stderr:``,code:+!o.every(e=>e.verdict.ok)}}async function $Y(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
481
481
  Usage: cc-candybar doctor [config-file]
482
- `),t.exit(2));let n=t.cwd(),r=await KY(WG(GY),vK(),t.env,n,e[0]);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const JY=e=>e.some(e=>t.argv.includes(e));function YY(){console.log(TO)}async function XY(){try{JY(CO.help)&&(YY(),t.exit(0)),JY(CO.version)&&(console.log(`cc-candybar ${Et}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await Xi(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(Gi(),t.exit(0)),e===`url-handle`){await qi(t.argv[3]);return}if(e===`daemon`){OJ();return}if(e===`daemon-stats`&&(await tK(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){await SY(t.argv.slice(3));return}if(e===`plugin`&&t.exit(PY(t.argv.slice(3))),e===`schema`){sY();return}if(e===`doctor`){await qY(t.argv.slice(3));return}$q(e)&&(await QJ(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
482
+ `),t.exit(2));let n=t.cwd(),r=await QY(KG(ZY),wK(),t.env,n,e[0]);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const eX=e=>e.some(e=>t.argv.includes(e));function tX(){console.log(EO)}async function nX(){try{eX(wO.help)&&(tX(),t.exit(0)),eX(wO.version)&&(console.log(`cc-candybar ${Et}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await Xi(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(Gi(),t.exit(0)),e===`url-handle`){await qi(t.argv[3]);return}if(e===`daemon`){PJ();return}if(e===`daemon-stats`&&(await rK(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){await OY(t.argv.slice(3));return}if(e===`plugin`&&t.exit(BY(t.argv.slice(3))),e===`schema`){pY();return}if(e===`doctor`){await $Y(t.argv.slice(3));return}aJ(e)&&(await iY(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
483
483
 
484
484
  cc-candybar is designed to be used as a Claude Code statusLine command.
485
485
  It reads hook data from stdin and outputs formatted statusline.
@@ -495,4 +495,4 @@ Add to ~/.claude/settings.json:
495
495
  Run with --help for more options.
496
496
 
497
497
  To test output manually:
498
- 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)),D(`Working directory: ${t.cwd()}`),D(`Process args:`,t.argv);let r=await n(t.stdin);D(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),YY(),t.exit(1));let i=RY(await At(r,t.argv,t.cwd(),VY(t.env,t.cwd(),t.stderr)));i.debug!==null&&D(i.debug),i.kick&&Qt(),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)}}XY();export{};
498
+ 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)),D(`Working directory: ${t.cwd()}`),D(`Process args:`,t.argv);let r=await n(t.stdin);D(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),tX(),t.exit(1));let i=WY(await At(r,t.argv,t.cwd(),qY(t.env,t.cwd(),t.stderr)));i.debug!==null&&D(i.debug),i.kick&&Qt(),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)}}nX();export{};