@promptctl/cc-candybar 1.8.1 → 1.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import e from"node:process";import{json as t}from"node:stream/consumers";import n,{createReadStream as r,existsSync as i,watch as a}from"node:fs";import o,{basename as s,dirname as c,join as l}from"node:path";import u,{homedir as d}from"node:os";import{spawn as f,spawnSync as p}from"node:child_process";import m from"node:net";import{URL as h,URLSearchParams as g,fileURLToPath as _}from"node:url";import{parseArgs as v}from"node:util";import{get as y}from"node:https";import{createHash as b}from"node:crypto";import{setTimeout as x}from"node:timers/promises";import{open as S,readFile as C,readdir as ee,stat as te}from"node:fs/promises";import{createInterface as w}from"node:readline";import{clearInterval as ne,setInterval as re}from"node:timers";import ie from"node:v8";var T=Object.create,E=Object.defineProperty,ae=Object.getOwnPropertyDescriptor,oe=Object.getOwnPropertyNames,se=Object.getPrototypeOf,ce=Object.prototype.hasOwnProperty,D=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),le=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=oe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ce.call(e,s)&&s!==n&&E(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ae(t,s))||r.enumerable});return e},ue=(e,t,n)=>(n=e==null?{}:T(se(e)),le(t||!e||!e.__esModule?E(n,`default`,{value:e,enumerable:!0}):n,e));function O(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const de={"click.pbcopy":1e3,"click.open":1e3},fe=new Map;function pe(e){let t=de[e];if(t===void 0)return{allowed:!0};let n=fe.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 me(e){fe.set(e,Date.now())}function he(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 ge=null;function k(e){ge=e}async function _e(e){let t=pe(e.category);if(!t.allowed)return he(e.category,t.minIntervalMs,t.sinceLastMs);me(e.category);let n=Date.now();return ge?.onStart(e.category),new Promise(t=>{let r;try{r=f(e.bin,e.args??[],{cwd:e.cwd,env:e.env,stdio:[`pipe`,`pipe`,`pipe`]})}catch(r){ge?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:r instanceof Error?r.message:String(r)});return}let i=``,a=``,o=!1,s=null,c=null,l=!1,u=r=>{o||(o=!0,s&&clearTimeout(s),c&&clearTimeout(c),ge?.onEnd(e.category,Date.now()-n),t(r))};r.stdout?.on(`data`,e=>{i+=e.toString(`utf8`)}),r.stderr?.on(`data`,e=>{a+=e.toString(`utf8`)}),r.on(`error`,e=>{u({ok:!1,reason:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:null,error:e.message})}),r.on(`close`,(e,t)=>{if(l){u({ok:!1,reason:`timeout`,stdout:i,stderr:a,exitCode:e,signal:t});return}if(e===0){u({ok:!0,stdout:i,stderr:a,exitCode:e});return}u({ok:!1,reason:t?`signal`:`non-zero`,stdout:i,stderr:a,exitCode:e,signal:t})}),e.timeoutMs&&e.timeoutMs>0&&(s=setTimeout(()=>{l=!0,r.pid!==void 0&&(r.kill(`SIGTERM`),c=setTimeout(()=>{r.kill(`SIGKILL`)},250))},e.timeoutMs)),e.stdinInput!==void 0&&r.stdin?r.stdin.end(e.stdinInput):r.stdin&&r.stdin.end()})}function ve(e){let t=pe(e.category);if(!t.allowed)return he(e.category,t.minIntervalMs,t.sinceLastMs);me(e.category);let n=Date.now();ge?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=p(e.bin,e.args??[],{cwd:e.cwd,env:e.env,input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ge?.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:t.error.message};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 ge?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:t instanceof Error?t.message:String(t)}}}function ye(e){let t=pe(e.category);if(!t.allowed)return he(e.category,t.minIntervalMs,t.sinceLastMs);me(e.category);let n=Date.now();ge?.onStart(e.category);let r=be(e);return ge?.onEnd(e.category,Date.now()-n),r}function be(e){let t;try{t=f(e.bin,e.args??[],{cwd:e.cwd,env:e.env,detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)}}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 xe(e){let t=process.env[e];return t&&t.length>0?t:void 0}function Se(){let e=xe(`XDG_STATE_HOME`)??o.join(u.homedir(),`.local`,`state`);return o.join(e,`cc-candybar`)}function Ce(){let e=xe(`XDG_CACHE_HOME`)??o.join(u.homedir(),`.cache`);return o.join(e,`cc-candybar`)}function we(){return Se()}function Te(){let e=process.env.CC_CANDYBAR_SOCKET;if(e)return e;let t=u.userInfo().uid;return o.join(`/tmp`,`cc-candybar-${t}`,`socket`)}function Ee(e){let t=o.dirname(e);n.mkdirSync(t,{recursive:!0,mode:448});let r=n.lstatSync(t);if(r.isSymbolicLink())throw Error(`socket parent is a symlink: ${t}`);if(!r.isDirectory())throw Error(`socket parent is not a directory: ${t}`);let i=u.userInfo().uid;if(typeof i==`number`&&r.uid!==i)throw Error(`socket parent is not owned by uid ${i}: ${t} (owner uid=${r.uid})`);if(r.mode&63)throw Error(`socket parent has unsafe permissions: ${t} (mode=${(r.mode&511).toString(8)}, expected 0700)`);try{if(n.lstatSync(e).isSymbolicLink())throw Error(`socket path is a symlink: ${e}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function De(){return o.join(Se(),`pid`)}function Oe(){return o.join(Se(),`session-state.json`)}function ke(){return o.join(Se(),`spawn.lock`)}function A(){return o.join(Se(),`daemon.log`)}const Ae=1e4;function je(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>Ae?Ae:t}var Me=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Ne(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function Pe(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 Me(`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 Me(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function Fe(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=Pe(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(Ne(t))})}async function Ie(e,t,n){let r=null;try{r=await Ve(Te(),t.connectMs);let i=await Fe(r,{v:3,...e},t.budgetMs);return ze(e.kind,i,n)}catch(e){return Be(e)}finally{r&&r.destroy()}}function Le(e,t){return typeof e==`string`?e:t}function Re(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function ze(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=Le(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:Re(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 Be(e){if(e instanceof Me||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 Ve(e,t){return new Promise((n,r)=>{let i=m.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 He(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 Ue={connectMs:50,budgetMs:150},We={connectMs:50,budgetMs:200};function Ge(e){let t=e.output;return typeof t==`string`?t:void 0}function Ke(e,t,n,r){return Ie({kind:`render`,hookData:e,args:t,cwd:n,termCols:r},Ue,Ge)}function qe(e,t){return Ie({kind:`click`,verb:e,value:t},We,Ge)}function Je(t={}){if(tt()!==null)return;let n=t.spawn??nt,r=Qe();if(r.kind===`contended`){let t=Ye();t!==null&&t>2e3&&(e.stderr.write(`cc-candybar: spawn-lock held ${t}ms (likely crashed holder) — spawning unlocked\n`),Xe(n));return}if(r.kind===`error`){e.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),Xe(n);return}try{Xe(n)}finally{et()}}function Ye(){try{let e=n.statSync(ke());return Date.now()-e.mtimeMs}catch{return null}}function Xe(t){try{t()||e.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
3
- `)}catch(t){e.stderr.write(`cc-candybar: daemon spawn failed: ${t.message}\n`)}}let Ze=null;function Qe(){let t=ke();for(let r=0;r<2;r++){try{let r=n.openSync(t,`wx`,384);try{n.writeSync(r,JSON.stringify({pid:e.pid,ts:Date.now()}))}catch{}return Ze={fd:r,path:t},{kind:`held`}}catch(e){let n=e.code;if(n!==`EEXIST`)return{kind:`error`,reason:`openSync(${t}): ${n??e.message}`}}if(!$e(t))return{kind:`contended`};try{n.unlinkSync(t)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function $e(e){try{let t=n.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function et(){if(!Ze)return;let{fd:e,path:t}=Ze;Ze=null;try{n.closeSync(e)}catch{}try{n.unlinkSync(t)}catch{}}function tt(){try{return n.mkdirSync(we(),{recursive:!0}),null}catch(e){return`mkdir ${we()}: ${e.message}`}}function nt(){let t=e.execPath,n=e.argv[1];return n?ye({bin:t,args:[`--max-old-space-size=400`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const rt=`cc-candybar`,it=`dispatch`,at=`set-state`,ot=`step-state`,st=`copy`,ct=`open-vscode`,lt=`show-config-error`,ut=`show-config-warning`;function dt(e){return e.map(encodeURIComponent).join(`/`)}function ft(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function pt(e){return`${rt}://${it}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${dt(e.args)}`)}`).join(`&`)}`}function mt(e){return new g(e).getAll(`e`).map(ht)}function ht(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const gt=`@promptctl/cc-candybar`,_t=`CCCandybarURLHandler`,vt=[];function yt(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function bt(e){return[`pnpm`,`dlx`,`${gt}@1.8.1`,...e.map(yt)].join(` `)}function xt(){return o.join(u.homedir(),`Applications`,`${_t}.app`)}function St(){return o.join(u.homedir(),`.claude`,`settings.json`)}function Ct(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function wt(){return o.join(u.homedir(),`Library`,`Application Support`,`CCCandybar`)}function Tt(){return o.join(wt(),`url-handler.mjs`)}function Et(e,t,n){let r=e.replace(/"/g,`\\"`),i=t.replace(/"/g,`\\"`);return[`on open location L`,`\tdo shell script "NODE_PATH='${n.replace(/"/g,`\\"`)}' '${r}' '${i}' url-handle " & quoted form of L`,`end open location`].join(`
3
+ `)}catch(t){e.stderr.write(`cc-candybar: daemon spawn failed: ${t.message}\n`)}}let Ze=null;function Qe(){let t=ke();for(let r=0;r<2;r++){try{let r=n.openSync(t,`wx`,384);try{n.writeSync(r,JSON.stringify({pid:e.pid,ts:Date.now()}))}catch{}return Ze={fd:r,path:t},{kind:`held`}}catch(e){let n=e.code;if(n!==`EEXIST`)return{kind:`error`,reason:`openSync(${t}): ${n??e.message}`}}if(!$e(t))return{kind:`contended`};try{n.unlinkSync(t)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function $e(e){try{let t=n.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function et(){if(!Ze)return;let{fd:e,path:t}=Ze;Ze=null;try{n.closeSync(e)}catch{}try{n.unlinkSync(t)}catch{}}function tt(){try{return n.mkdirSync(we(),{recursive:!0}),null}catch(e){return`mkdir ${we()}: ${e.message}`}}function nt(){let t=e.execPath,n=e.argv[1];return n?ye({bin:t,args:[`--max-old-space-size=400`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const rt=`cc-candybar`,it=`dispatch`,at=`set-state`,ot=`step-state`,st=`copy`,ct=`open-vscode`,lt=`show-config-error`,ut=`show-config-warning`;function dt(e){return e.map(encodeURIComponent).join(`/`)}function ft(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function pt(e){return`${rt}://${it}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${dt(e.args)}`)}`).join(`&`)}`}function mt(e){return new g(e).getAll(`e`).map(ht)}function ht(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const gt=`@promptctl/cc-candybar`,_t=`CCCandybarURLHandler`,vt=[];function yt(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function bt(e){return[`pnpm`,`dlx`,`${gt}@1.8.2`,...e.map(yt)].join(` `)}function xt(){return o.join(u.homedir(),`Applications`,`${_t}.app`)}function St(){return o.join(u.homedir(),`.claude`,`settings.json`)}function Ct(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function wt(){return o.join(u.homedir(),`Library`,`Application Support`,`CCCandybar`)}function Tt(){return o.join(wt(),`url-handler.mjs`)}function Et(e,t,n){let r=e.replace(/"/g,`\\"`),i=t.replace(/"/g,`\\"`);return[`on open location L`,`\tdo shell script "NODE_PATH='${n.replace(/"/g,`\\"`)}' '${r}' '${i}' url-handle " & quoted form of L`,`end open location`].join(`
4
4
  `)}function Dt(e){if(!e)throw Error(`install-url-handler: process.argv[1] not set`);return e.endsWith(`.mjs`)||e.endsWith(`.js`)?e:o.resolve(o.dirname(e),`..`,`dist`,`index.mjs`)}function Ot(){let e=Dt(process.argv[1]);if(!n.existsSync(e))throw Error(`install-url-handler: bundled dist not found at ${e}. Reinstall the package.`);n.mkdirSync(wt(),{recursive:!0});let t=Tt();return n.copyFileSync(e,t),t}function kt(){return[{key:`CFBundleIdentifier`,xml:`<string>com.cccandybar.url-handler</string>`},{key:`CFBundleURLTypes`,xml:[`<array>`,` <dict>`,` <key>CFBundleURLName</key>`,` <string>Claude Powerline Click Action</string>`,` <key>CFBundleURLSchemes</key>`,` <array>`,` <string>${rt}</string>`,` </array>`,` </dict>`,`</array>`].join(`
5
5
  `)}]}function At(){Ct();let e=Ot();process.stdout.write(`Copied dist to ${e}\n`);let t=Dt(process.argv[1]),r=o.join(o.dirname(t),`..`,`node_modules`);if(!n.existsSync(r))throw Error(`install-url-handler: node_modules not found at ${r}. Install deps first.`);let i=xt();n.mkdirSync(o.dirname(i),{recursive:!0}),n.existsSync(i)&&n.rmSync(i,{recursive:!0,force:!0}),process.stdout.write(`Building ${i}\n`);let a=ve({bin:`/usr/bin/osacompile`,args:[`-o`,i,`-e`,Et(process.execPath,e,r)],category:`install.osacompile`});if(!a.ok)throw process.stderr.write(a.stderr),Error(`osacompile failed (${a.reason})`);let s=o.join(i,`Contents`,`Info.plist`);for(let{key:e}of kt())ve({bin:`/usr/bin/plutil`,args:[`-remove`,e,s],category:`install.plutil`});for(let{key:e,xml:t}of kt()){let n=ve({bin:`/usr/bin/plutil`,args:[`-insert`,e,`-xml`,t,s],category:`install.plutil`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`plutil -insert ${e} failed (${n.reason})`)}process.stdout.write(`Registering ${rt}:// with Launch Services\n`);let c=ve({bin:`/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister`,args:[`-f`,i],category:`install.lsregister`});if(!c.ok)throw process.stderr.write(c.stderr),Error(`lsregister failed (${c.reason})`);process.stdout.write(`✓ ${_t}.app installed and registered.\n`),process.stdout.write(` Test: open '${rt}://hello-world' && pbpaste\n`)}function jt(e,t=rt){let n=`${t}://`;if(!e.startsWith(n))throw Error(`expected ${n} scheme, got: ${e}`);let r=e.slice(n.length),i=r.indexOf(`/`);return i===-1?{verb:st,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function Mt(e){e||(process.stderr.write(`url-handle: missing URL argument.
6
6
  `),process.exit(1));let t;try{t=jt(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await qe(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(Je(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(Nt(n)+`
@@ -78,55 +78,54 @@ Use 'override' annotation for methods overridden by subclass.`)}}var ea=oa(0),ta
78
78
  `)),u.isContinuation&&h.push(new Y(this._continuationMarker,c));let d;n===0&&f?d={ch:`▲`,style:m}:n===a-1&&p&&(d={ch:`▼`,style:m});let _=u.isContinuation?H(Math.max(0,e.maxWidth-this._markerWidth)):H(e.maxWidth);this._emitRowContent(h,u,o===r&&g,s,l,d,_)}for(let t=0;t<o;t++)h.push(new Y(`
79
79
  `)),h.push(new Y(zr(``,H(e.maxWidth)),s));return h}_emitRowContent(e,t,n,r,i,a,o){let s=t.content,c=n?this.cursorPosition-t.valueStart:-1;if(a===void 0){if(!n){s.length>0&&e.push(new Y(s,r));return}let t=s.slice(0,c),a=Hr(s,Rr(c)),o=s.slice(c,a)||` `,l=s.slice(a);t.length>0&&e.push(new Y(t,r)),e.push(new Y(o,i)),l.length>0&&e.push(new Y(l,r));return}let l=H(V(a.ch)),u=H(Math.max(0,o-l)),[d]=Br(s,u),f=zr(d,u),p=n&&c>=0?V(s.slice(0,c)):-1;if(p>=0&&p<u){let[t,n]=Br(f,H(p)),a=``;for(let e of n){a=e;break}let o=a||` `,s=n.slice(a.length);t.length>0&&e.push(new Y(t,r)),e.push(new Y(o,i)),s.length>0&&e.push(new Y(s,r))}else f.length>0&&e.push(new Y(f,r));e.push(new Y(a.ch,a.style))}_computeVisualRows(e){let t=H(Math.max(1,e)),n=H(Math.max(1,t-this._markerWidth)),r=[],i=this.value.split(`
80
80
  `),a=0;for(let e=0;e<i.length;e++){let o=i[e];if(this._wrap!==void 0){let e=this._wrap(o,{firstWidth:t,continuationWidth:n});if(e.length===0)r.push({content:``,valueStart:Rr(a),isContinuation:!1});else for(let t=0;t<e.length;t++){let n=e[t];r.push({content:n.content,valueStart:Rr(a+n.start),isContinuation:t>0})}}else r.push({content:o,valueStart:Rr(a),isContinuation:!1});a+=o.length+1}return r}measure(e){return{minimum:10,maximum:Math.max(10,Math.max(V(this.value),V(this.placeholder))+2)}}get scrollIndicatorText(){if(this._scrollIndicator!==`indices`||this._maxRows===void 0)return;let e=this._visualRows;if(!(e===null||e.length<=this._maxRows))return`[${this._cursorVisualRow()+1}/${e.length}]`}resolvePalette(e){let t=this._theme.palette.get(e);return G.fromRgba(t)}}})();var To=function(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0},Eo=function(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else (d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0};(()=>{var e,t;let n=$a,r=[],i,a=[],o=[],s,c=[],l=[],u,d=[],f=[],p,m=[],h=[],g,_=[],v=[],y,b=[],x=[],S,C,ee,te;return class extends n{static{let w=typeof Symbol==`function`&&Symbol.metadata?Object.create(n[Symbol.metadata]??null):void 0;i=[(e=X.observable).shallow.bind(e)],s=[X.observable],u=[X.observable],p=[X.observable],g=[X.observable],y=[(t=X.observable).ref.bind(t)],S=[X.action],C=[X.action],ee=[X.action],te=[X.action],Eo(this,null,i,{kind:`accessor`,name:`options`,static:!1,private:!1,access:{has:e=>`options`in e,get:e=>e.options,set:(e,t)=>{e.options=t}},metadata:w},a,o),Eo(this,null,s,{kind:`accessor`,name:`selectedIndex`,static:!1,private:!1,access:{has:e=>`selectedIndex`in e,get:e=>e.selectedIndex,set:(e,t)=>{e.selectedIndex=t}},metadata:w},c,l),Eo(this,null,u,{kind:`accessor`,name:`expanded`,static:!1,private:!1,access:{has:e=>`expanded`in e,get:e=>e.expanded,set:(e,t)=>{e.expanded=t}},metadata:w},d,f),Eo(this,null,p,{kind:`accessor`,name:`highlightedIndex`,static:!1,private:!1,access:{has:e=>`highlightedIndex`in e,get:e=>e.highlightedIndex,set:(e,t)=>{e.highlightedIndex=t}},metadata:w},m,h),Eo(this,null,g,{kind:`accessor`,name:`filter`,static:!1,private:!1,access:{has:e=>`filter`in e,get:e=>e.filter,set:(e,t)=>{e.filter=t}},metadata:w},_,v),Eo(this,null,y,{kind:`accessor`,name:`_theme`,static:!1,private:!1,access:{has:e=>`_theme`in e,get:e=>e._theme,set:(e,t)=>{e._theme=t}},metadata:w},b,x),Eo(this,null,S,{kind:`method`,name:`setTheme`,static:!1,private:!1,access:{has:e=>`setTheme`in e,get:e=>e.setTheme},metadata:w},null,r),Eo(this,null,C,{kind:`method`,name:`handleKey`,static:!1,private:!1,access:{has:e=>`handleKey`in e,get:e=>e.handleKey},metadata:w},null,r),Eo(this,null,ee,{kind:`method`,name:`handleMouse`,static:!1,private:!1,access:{has:e=>`handleMouse`in e,get:e=>e.handleMouse},metadata:w},null,r),Eo(this,null,te,{kind:`method`,name:`handleFocus`,static:!1,private:!1,access:{has:e=>`handleFocus`in e,get:e=>e.handleFocus},metadata:w},null,r),w&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:w})}id=To(this,r);focusable=!0;#e=To(this,a,void 0);get options(){return this.#e}set options(e){this.#e=e}#t=(To(this,o),To(this,c,void 0));get selectedIndex(){return this.#t}set selectedIndex(e){this.#t=e}#n=(To(this,l),To(this,d,!1));get expanded(){return this.#n}set expanded(e){this.#n=e}#r=(To(this,f),To(this,m,void 0));get highlightedIndex(){return this.#r}set highlightedIndex(e){this.#r=e}#i=(To(this,h),To(this,_,``));get filter(){return this.#i}set filter(e){this.#i=e}get filteredOptions(){let e=this.filter.toLowerCase(),t=[];for(let n=0;n<this.options.length;n++){let r=this.options[n];r.toLowerCase().includes(e)&&t.push({label:r,idx:n})}return t}#a=(To(this,v),To(this,b,void 0));get _theme(){return this.#a}set _theme(e){this.#a=e}constructor(e){super(),To(this,x),this.id=e.id??`dropdown-${Math.random().toString(36).slice(2,8)}`,this.options=[...e.options],this.selectedIndex=this.clampIndex(e.selectedIndex??0),this.highlightedIndex=this.selectedIndex,this.disabled=e.disabled??!1,this._theme=e.theme??Xi}clampIndex(e){return this.options.length===0?0:Math.max(0,Math.min(e,this.options.length-1))}setTheme(e){this._theme=e}handleKey(e){if(this.disabled)return;let t=e.character.length===1&&!e.ctrl&&!e.meta&&e.character>=` `&&e.character!==``;if(!this.expanded){if(e.key===`enter`||e.key===`space`){this.expanded=!0,this.highlightedIndex=this.clampIndex(this.selectedIndex),e.stop();return}t&&(this.expanded=!0,this.filter+=e.character,this.highlightedIndex=0,e.stop());return}switch(e.key){case`up`:this.highlightedIndex=Math.max(0,this.highlightedIndex-1),e.stop();return;case`down`:{let t=Math.max(0,this.filteredOptions.length-1);this.highlightedIndex=Math.min(t,this.highlightedIndex+1),e.stop();return}case`enter`:{let t=this.filteredOptions[this.highlightedIndex];if(e.stop(),t===void 0)return;this.selectedIndex=t.idx,this.filter=``,this.expanded=!1,this.emitChange(),this.emitSubmit();return}case`escape`:this.filter=``,this.expanded=!1,e.stop();return;case`backspace`:this.filter=this.filter.slice(0,-1),this.highlightedIndex=0,e.stop();return;case`tab`:this.filter=``,this.expanded=!1,e.stop();return}t&&(this.filter+=e.character,this.highlightedIndex=0,e.stop())}handleMouse(e){if(this.disabled||e.type!==`mouse_up`)return;let t=this.bounds;if(!t)return;let n=e.x>=t.x&&e.x<t.x+t.width&&e.y>=t.y&&e.y<t.y+t.height;if(!this.expanded){n&&(this.expanded=!0,this.highlightedIndex=this.clampIndex(this.selectedIndex));return}if(!n){this.filter=``,this.expanded=!1;return}let r=e.y-t.y;if(r===0){this.filter=``,this.expanded=!1;return}let i=this.filteredOptions[r-1];i!==void 0&&(this.selectedIndex=i.idx,this.filter=``,this.expanded=!1,this.emitChange(),this.emitSubmit())}handleFocus(e){super.handleFocus(e),e.type===`blur`&&(this.filter=``,this.expanded=!1)}render(e){let t=e.asciiOnly?`v`:`▾`,n=this.focused?e.asciiOnly?`|`:`│`:``,r=this.maxLabelLen(),i=this.disabled?new q({color:`#666666`,bgcolor:`#333333`,dim:!0}):new q({color:this.resolvePalette(`foreground`),bgcolor:this.resolvePalette(`surface`),underline:this.focused}),a=this.headerText(r,n);return[new Y(`[`,i),new Y(`${a} ${t}`,i),new Y(`]`,i)]}headerText(e,t){if(this.filter===``){let t=this.options[this.selectedIndex]??``,n=V(t);if(n>=e)return zr(t,H(e));let r=e-n,i=Math.floor(r/2),a=r-i;return` `.repeat(i)+t+` `.repeat(a)}let n=Math.max(0,e-V(t)-1),[r]=Br(this.filter,H(n));return zr(` `+r+t,H(e))}renderOverlay(e){if(!this.expanded)return null;let t=this.maxLabelLen(),n=this.filteredOptions;if(n.length===0)return this.renderNoMatchRow(t);let r=[];for(let e=0;e<n.length;e++)e>0&&r.push(new Y(`
81
- `)),r.push(...this.renderOptionRow(n[e],e,t));return r}renderNoMatchRow(e){let t=` ${zr(`(no matches)`,H(e))} `,n=this.disabled?new q({color:`#666666`,bgcolor:`#333333`,dim:!0}):new q({color:this.resolvePalette(`foreground`),bgcolor:this.resolvePalette(`surface`),dim:!0});return[new Y(` `,n),new Y(t,n),new Y(` `,n)]}renderOptionRow(e,t,n){let r=` ${zr(e.label,H(n))} `,i=e.idx===this.selectedIndex,a=t===this.highlightedIndex,o=this.disabled?new q({color:`#666666`,bgcolor:`#333333`,dim:!0}):a?new q({color:this.resolvePalette(`text-primary`),bgcolor:this.resolvePalette(`primary-muted`)}):i?new q({color:this.resolvePalette(`on-primary`),bgcolor:this.resolvePalette(`primary`)}):new q({color:this.resolvePalette(`foreground`),bgcolor:this.resolvePalette(`surface`)});return[new Y(` `,o),new Y(r,o),new Y(` `,o)]}maxLabelLen(){let e=0;for(let t of this.options){let n=V(t);n>e&&(e=n)}return e}measure(e){let t=this.maxLabelLen()+4;return{minimum:t,maximum:t}}resolvePalette(e){let t=this._theme.palette.get(e);return G.fromRgba(t)}}})();var Do=function(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0},Oo=function(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else (d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0};(()=>{var e,t,n,r,i;let a=$a,o=[],s,c=[],l=[],u,d=[],f=[],p,m=[],h=[],g,_=[],v=[],y,b=[],x=[],S,C=[],ee=[],te,w,ne,re;return class extends a{static{let ie=typeof Symbol==`function`&&Symbol.metadata?Object.create(a[Symbol.metadata]??null):void 0;s=[X.observable],u=[(e=X.observable).ref.bind(e)],p=[(t=X.observable).ref.bind(t)],g=[(n=X.observable).ref.bind(n)],y=[(r=X.observable).ref.bind(r)],S=[(i=X.observable).ref.bind(i)],te=[X.action],w=[X.action],ne=[X.action],re=[X.action],Oo(this,null,s,{kind:`accessor`,name:`value`,static:!1,private:!1,access:{has:e=>`value`in e,get:e=>e.value,set:(e,t)=>{e.value=t}},metadata:ie},c,l),Oo(this,null,u,{kind:`accessor`,name:`min`,static:!1,private:!1,access:{has:e=>`min`in e,get:e=>e.min,set:(e,t)=>{e.min=t}},metadata:ie},d,f),Oo(this,null,p,{kind:`accessor`,name:`max`,static:!1,private:!1,access:{has:e=>`max`in e,get:e=>e.max,set:(e,t)=>{e.max=t}},metadata:ie},m,h),Oo(this,null,g,{kind:`accessor`,name:`step`,static:!1,private:!1,access:{has:e=>`step`in e,get:e=>e.step,set:(e,t)=>{e.step=t}},metadata:ie},_,v),Oo(this,null,y,{kind:`accessor`,name:`width`,static:!1,private:!1,access:{has:e=>`width`in e,get:e=>e.width,set:(e,t)=>{e.width=t}},metadata:ie},b,x),Oo(this,null,S,{kind:`accessor`,name:`_theme`,static:!1,private:!1,access:{has:e=>`_theme`in e,get:e=>e._theme,set:(e,t)=>{e._theme=t}},metadata:ie},C,ee),Oo(this,null,te,{kind:`method`,name:`setTheme`,static:!1,private:!1,access:{has:e=>`setTheme`in e,get:e=>e.setTheme},metadata:ie},null,o),Oo(this,null,w,{kind:`method`,name:`handleKey`,static:!1,private:!1,access:{has:e=>`handleKey`in e,get:e=>e.handleKey},metadata:ie},null,o),Oo(this,null,ne,{kind:`method`,name:`handleMouse`,static:!1,private:!1,access:{has:e=>`handleMouse`in e,get:e=>e.handleMouse},metadata:ie},null,o),Oo(this,null,re,{kind:`method`,name:`setValue`,static:!1,private:!1,access:{has:e=>`setValue`in e,get:e=>e.setValue},metadata:ie},null,o),ie&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:ie})}id=Do(this,o);focusable=!0;#e=Do(this,c,void 0);get value(){return this.#e}set value(e){this.#e=e}#t=(Do(this,l),Do(this,d,void 0));get min(){return this.#t}set min(e){this.#t=e}#n=(Do(this,f),Do(this,m,void 0));get max(){return this.#n}set max(e){this.#n=e}#r=(Do(this,h),Do(this,_,void 0));get step(){return this.#r}set step(e){this.#r=e}#i=(Do(this,v),Do(this,b,void 0));get width(){return this.#i}set width(e){this.#i=e}#a=(Do(this,x),Do(this,C,void 0));get _theme(){return this.#a}set _theme(e){this.#a=e}_dragging=(Do(this,ee),!1);constructor(e={}){super(),this.id=e.id??`slider-${Math.random().toString(36).slice(2,8)}`,this.min=e.min??0,this.max=e.max??100,this.step=e.step??1;let t=e.width??20;if(!Number.isInteger(t)||t<1)throw RangeError(`Slider width must be a positive integer; got ${t}`);this.width=t,this.value=ko(e.value??this.min,this.min,this.max,this.step),this.disabled=e.disabled??!1,this._theme=e.theme??Xi}setTheme(e){this._theme=e}handleKey(e){if(!this.disabled)switch(e.key){case`left`:this.setValue(this.value-this.step),e.stop();return;case`right`:this.setValue(this.value+this.step),e.stop();return;case`home`:this.setValue(this.min),e.stop();return;case`end`:this.setValue(this.max),e.stop();return}}handleMouse(e){if(!this.disabled){if(e.type===`mouse_down`){this._dragging=!0,this.setValueFromMouseX(e.x);return}if(e.type===`mouse_move`){this._dragging&&this.setValueFromMouseX(e.x);return}if(e.type===`mouse_up`){let t=this._dragging;this._dragging=!1,t&&(this.setValueFromMouseX(e.x),this.emitSubmit());return}}}setValue(e){let t=ko(e,this.min,this.max,this.step);t!==this.value&&(this.value=t,this.emitChange())}setValueFromMouseX(e){let t=this.bounds;if(!t)return;let n=Math.max(1,this.width-1),r=Math.max(0,Math.min(this.width-1,e-t.x))/n,i=this.min+r*(this.max-this.min);this.setValue(i)}render(e){let t=e.asciiOnly?`-`:`─`,n=e.asciiOnly?`*`:`●`,r=this.max-this.min,i=r===0?0:(this.value-this.min)/r,a=Math.round(i*(this.width-1)),o={underline:this.focused},s=this.disabled?new q({color:`#666666`,bgcolor:`#333333`,dim:!0,...o}):new q({color:this.resolvePalette(`primary`),...o}),c=this.disabled?new q({color:`#666666`,bgcolor:`#333333`,dim:!0,...o}):new q({color:this.resolvePalette(`surface`),...o}),l=this.disabled?new q({color:`#666666`,bgcolor:`#333333`,dim:!0,bold:!0,...o}):new q({color:this.resolvePalette(`primary`),bold:!0,...o}),u=[];a>0&&u.push(new Y(t.repeat(a),s)),u.push(new Y(n,l));let d=this.width-a-1;return d>0&&u.push(new Y(t.repeat(d),c)),u}measure(e){return{minimum:this.width,maximum:this.width}}resolvePalette(e){let t=this._theme.palette.get(e);return G.fromRgba(t)}}})();function ko(e,t,n,r){let i=Math.max(t,Math.min(n,e));if(r<=0)return i;let a=t+Math.round((i-t)/r)*r;return Math.max(t,Math.min(n,a))}new TextEncoder,new TextDecoder(`utf-8`),new TextDecoder(`ascii`);var Ao=class extends Error{name=`TemplateError`;kind=`EvalError`;pos;source;constructor(e,t,n={}){super(e),this.pos=t,this.source=n.source}get sourceSnippet(){return this.source?Lo(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}},jo=class extends Ao{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},Mo=class extends Ao{name=`EvalError`;kind=`EvalError`},No=class extends Mo{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=Ro(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}},Po=class extends Mo{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}},Fo=class extends Mo{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},Io=class extends Mo{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function Lo(e,t){let n=e.split(`
81
+ `)),r.push(...this.renderOptionRow(n[e],e,t));return r}renderNoMatchRow(e){let t=` ${zr(`(no matches)`,H(e))} `,n=this.disabled?new q({color:`#666666`,bgcolor:`#333333`,dim:!0}):new q({color:this.resolvePalette(`foreground`),bgcolor:this.resolvePalette(`surface`),dim:!0});return[new Y(` `,n),new Y(t,n),new Y(` `,n)]}renderOptionRow(e,t,n){let r=` ${zr(e.label,H(n))} `,i=e.idx===this.selectedIndex,a=t===this.highlightedIndex,o=this.disabled?new q({color:`#666666`,bgcolor:`#333333`,dim:!0}):a?new q({color:this.resolvePalette(`text-primary`),bgcolor:this.resolvePalette(`primary-muted`)}):i?new q({color:this.resolvePalette(`on-primary`),bgcolor:this.resolvePalette(`primary`)}):new q({color:this.resolvePalette(`foreground`),bgcolor:this.resolvePalette(`surface`)});return[new Y(` `,o),new Y(r,o),new Y(` `,o)]}maxLabelLen(){let e=0;for(let t of this.options){let n=V(t);n>e&&(e=n)}return e}measure(e){let t=this.maxLabelLen()+4;return{minimum:t,maximum:t}}resolvePalette(e){let t=this._theme.palette.get(e);return G.fromRgba(t)}}})();var Do=function(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0},Oo=function(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else (d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0};(()=>{var e,t,n,r,i;let a=$a,o=[],s,c=[],l=[],u,d=[],f=[],p,m=[],h=[],g,_=[],v=[],y,b=[],x=[],S,C=[],ee=[],te,w,ne,re;return class extends a{static{let ie=typeof Symbol==`function`&&Symbol.metadata?Object.create(a[Symbol.metadata]??null):void 0;s=[X.observable],u=[(e=X.observable).ref.bind(e)],p=[(t=X.observable).ref.bind(t)],g=[(n=X.observable).ref.bind(n)],y=[(r=X.observable).ref.bind(r)],S=[(i=X.observable).ref.bind(i)],te=[X.action],w=[X.action],ne=[X.action],re=[X.action],Oo(this,null,s,{kind:`accessor`,name:`value`,static:!1,private:!1,access:{has:e=>`value`in e,get:e=>e.value,set:(e,t)=>{e.value=t}},metadata:ie},c,l),Oo(this,null,u,{kind:`accessor`,name:`min`,static:!1,private:!1,access:{has:e=>`min`in e,get:e=>e.min,set:(e,t)=>{e.min=t}},metadata:ie},d,f),Oo(this,null,p,{kind:`accessor`,name:`max`,static:!1,private:!1,access:{has:e=>`max`in e,get:e=>e.max,set:(e,t)=>{e.max=t}},metadata:ie},m,h),Oo(this,null,g,{kind:`accessor`,name:`step`,static:!1,private:!1,access:{has:e=>`step`in e,get:e=>e.step,set:(e,t)=>{e.step=t}},metadata:ie},_,v),Oo(this,null,y,{kind:`accessor`,name:`width`,static:!1,private:!1,access:{has:e=>`width`in e,get:e=>e.width,set:(e,t)=>{e.width=t}},metadata:ie},b,x),Oo(this,null,S,{kind:`accessor`,name:`_theme`,static:!1,private:!1,access:{has:e=>`_theme`in e,get:e=>e._theme,set:(e,t)=>{e._theme=t}},metadata:ie},C,ee),Oo(this,null,te,{kind:`method`,name:`setTheme`,static:!1,private:!1,access:{has:e=>`setTheme`in e,get:e=>e.setTheme},metadata:ie},null,o),Oo(this,null,w,{kind:`method`,name:`handleKey`,static:!1,private:!1,access:{has:e=>`handleKey`in e,get:e=>e.handleKey},metadata:ie},null,o),Oo(this,null,ne,{kind:`method`,name:`handleMouse`,static:!1,private:!1,access:{has:e=>`handleMouse`in e,get:e=>e.handleMouse},metadata:ie},null,o),Oo(this,null,re,{kind:`method`,name:`setValue`,static:!1,private:!1,access:{has:e=>`setValue`in e,get:e=>e.setValue},metadata:ie},null,o),ie&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:ie})}id=Do(this,o);focusable=!0;#e=Do(this,c,void 0);get value(){return this.#e}set value(e){this.#e=e}#t=(Do(this,l),Do(this,d,void 0));get min(){return this.#t}set min(e){this.#t=e}#n=(Do(this,f),Do(this,m,void 0));get max(){return this.#n}set max(e){this.#n=e}#r=(Do(this,h),Do(this,_,void 0));get step(){return this.#r}set step(e){this.#r=e}#i=(Do(this,v),Do(this,b,void 0));get width(){return this.#i}set width(e){this.#i=e}#a=(Do(this,x),Do(this,C,void 0));get _theme(){return this.#a}set _theme(e){this.#a=e}_dragging=(Do(this,ee),!1);constructor(e={}){super(),this.id=e.id??`slider-${Math.random().toString(36).slice(2,8)}`,this.min=e.min??0,this.max=e.max??100,this.step=e.step??1;let t=e.width??20;if(!Number.isInteger(t)||t<1)throw RangeError(`Slider width must be a positive integer; got ${t}`);this.width=t,this.value=ko(e.value??this.min,this.min,this.max,this.step),this.disabled=e.disabled??!1,this._theme=e.theme??Xi}setTheme(e){this._theme=e}handleKey(e){if(!this.disabled)switch(e.key){case`left`:this.setValue(this.value-this.step),e.stop();return;case`right`:this.setValue(this.value+this.step),e.stop();return;case`home`:this.setValue(this.min),e.stop();return;case`end`:this.setValue(this.max),e.stop();return}}handleMouse(e){if(!this.disabled){if(e.type===`mouse_down`){this._dragging=!0,this.setValueFromMouseX(e.x);return}if(e.type===`mouse_move`){this._dragging&&this.setValueFromMouseX(e.x);return}if(e.type===`mouse_up`){let t=this._dragging;this._dragging=!1,t&&(this.setValueFromMouseX(e.x),this.emitSubmit());return}}}setValue(e){let t=ko(e,this.min,this.max,this.step);t!==this.value&&(this.value=t,this.emitChange())}setValueFromMouseX(e){let t=this.bounds;if(!t)return;let n=Math.max(1,this.width-1),r=Math.max(0,Math.min(this.width-1,e-t.x))/n,i=this.min+r*(this.max-this.min);this.setValue(i)}render(e){let t=e.asciiOnly?`-`:`─`,n=e.asciiOnly?`*`:`●`,r=this.max-this.min,i=r===0?0:(this.value-this.min)/r,a=Math.round(i*(this.width-1)),o={underline:this.focused},s=this.disabled?new q({color:`#666666`,bgcolor:`#333333`,dim:!0,...o}):new q({color:this.resolvePalette(`primary`),...o}),c=this.disabled?new q({color:`#666666`,bgcolor:`#333333`,dim:!0,...o}):new q({color:this.resolvePalette(`surface`),...o}),l=this.disabled?new q({color:`#666666`,bgcolor:`#333333`,dim:!0,bold:!0,...o}):new q({color:this.resolvePalette(`primary`),bold:!0,...o}),u=[];a>0&&u.push(new Y(t.repeat(a),s)),u.push(new Y(n,l));let d=this.width-a-1;return d>0&&u.push(new Y(t.repeat(d),c)),u}measure(e){return{minimum:this.width,maximum:this.width}}resolvePalette(e){let t=this._theme.palette.get(e);return G.fromRgba(t)}}})();function ko(e,t,n,r){let i=Math.max(t,Math.min(n,e));if(r<=0)return i;let a=t+Math.round((i-t)/r)*r;return Math.max(t,Math.min(n,a))}new TextEncoder,new TextDecoder(`utf-8`),new TextDecoder(`ascii`);function Ao(e,t){if(!(e instanceof Ca))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);let n=e.copy();return n.style=e.style.add(t),n}function jo(e){return{fn:(t=>Ao(t,e)),argTypes:[`liftable`],returnType:`T`}}function Mo(){let e={};for(let t of Object.keys(hi))e[t]=jo(new q({color:G.parse(t)}));return e}const No={fn:((e,t)=>{if(!Number.isInteger(e)||e<0||e>255)throw RangeError(`color index ${e} is out of range (0-255)`);return Ao(t,new q({color:G.fromAnsi(e)}))}),argTypes:[`int`,`liftable`],returnType:`T`},Po=/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/,Fo={fn:((e,t)=>{if(!Po.test(e))throw RangeError(`hex expected #RRGGBB or #RRGGBBAA, got ${JSON.stringify(e)}`);return Ao(t,new q({color:G.parse(e)}))}),argTypes:[`string`,`liftable`],returnType:`T`},Io={fn:((e,t,n,r)=>Ao(r,new q({color:G.fromRgb(e,t,n)}))),argTypes:[`int`,`int`,`int`,`liftable`],returnType:`T`},Lo={fn:((e,t)=>Ao(t,new q({bgcolor:G.parse(e)}))),argTypes:[`string`,`liftable`],returnType:`T`};function Ro(e,t){return new q({[e]:t})}function zo(){let e={};for(let t of ia)e[t]=jo(Ro(t,!0)),e[`not_${t}`]=jo(Ro(t,!1));for(let[t,n]of Object.entries(oa))e[t]=jo(Ro(n,!0));return e}const Bo={fn:((e,t)=>Ao(t,q.parse(e))),argTypes:[`string`,`liftable`],returnType:`T`},Vo={fn:((e,t)=>Ao(t,new q({link:e}))),argTypes:[`string`,`liftable`],returnType:`T`};function Ho(){return{...Mo(),color:No,hex:Fo,rgb:Io,on:Lo,...zo(),link:Vo,style:Bo}}const Uo=/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/;function Wo(e){if(!Uo.test(e))throw RangeError(`palette background expected #RRGGBB or #RRGGBBAA, got ${JSON.stringify(e)}`);return G.parse(e).getTruecolor()}function Go(e,t,n,r){let i=e.resolve(t,n===void 0?void 0:{against:n});if(i===null){let e=n===void 0?`; for specs with alpha or auto-contrast, use paletteOver`:``;throw Error(`palette spec ${JSON.stringify(t)} did not resolve — check the spec string is valid and the variable exists${e}`)}return Ao(r,new q({color:G.fromRgba(i)}))}const Ko=/^[A-Za-z_][A-Za-z0-9_]*$/;function qo(e){let t={};for(let n of e.palette.vars.keys()){if(!Ko.test(n))continue;let r=n;t[r]={fn:(t=>Go(e,r,void 0,t)),argTypes:[`liftable`],returnType:`T`}}return t}function Jo(e){return{fn:((t,n)=>Go(e,t,void 0,n)),argTypes:[`string`,`liftable`],returnType:`T`}}function Yo(e){return{fn:((t,n,r)=>Go(e,t,Wo(n),r)),argTypes:[`string`,`string`,`liftable`],returnType:`T`}}function Xo(e){return{fn:((t,n)=>Go(e,`auto`,Wo(t),n)),argTypes:[`string`,`liftable`],returnType:`T`}}function Zo(e){return{...qo(e),palette:Jo(e),paletteOver:Yo(e),auto:Xo(e)}}function Qo(){return Ho()}new q({color:`red`,dim:!0});const $o={dark:`textual-dark`,light:`textual-light`};function es(e){return $o[e]??e}function ts(e,t){return e??t??`textual-dark`}function ns(){return Object.keys($o)}function rs(){return[...Vi(),...ns()]}const is=[`powerline`,`capsule`,`plain`];function as(e){return is.includes(e)}function os(e,t){let n=e??t??`powerline`;return as(n)?n:`powerline`}var ss=class extends Error{file;issues;constructor(e,t){super(us(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t}};function Q(e,t){let n=0,r;for(let i of t){if(i===``||/^\d+$/.test(i))continue;let t=cs(e,n,i);if(t===-1)return r===void 0?void 0:ls(e,r);n=t,r=t}return r===void 0?void 0:ls(e,r)}function cs(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 ls(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function us(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(`
82
+ `)}function ds(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 ${_s(i)}`,line:Q(e.source,[...t.split(`.`),r])}),null)}function fs(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 ${_s(i)}`,line:Q(e.source,[...t.split(`.`),`default`])});return}return i}}function ps(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 ${_s(i)}`,line:Q(e.source,[...t.split(`.`),r])});return}return i}}function ms(e,t,n){let r=ps(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}". Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:Q(e.source,[...t.split(`.`),`palette`])});return}return r}}function hs(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 ${vs(a)}`,line:Q(e.source,[...t.split(`.`),r])});return}return a}}function gs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _s(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function vs(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function ys(e,t,n,r){return gs(r)?(xs(e,n,r,t.noun,new Set(Object.keys(t.fields))),bs(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${_s(r)}`,line:Q(e.source,n.split(`.`))}),null)}function bs(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}function xs(e,t,n,r,i){for(let a of Object.keys(n))i.has(a)||e.issues.push({path:`${t}.${a}`,message:`Unknown ${r} "${a}". Expected one of: ${[...i].join(`, `)}`,line:Q(e.source,[...t.split(`.`),a])})}function Ss(e,t,n,r){if(!gs(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${_s(r)}`,line:Q(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:Q(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:Q(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:Q(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function Cs(e,t,n,r){if(!gs(r))return e.issues.push({path:n,message:`${n} must be an object, got ${_s(r)}`,line:Q(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 ${_s(i)}`,line:Q(e.source,n.split(`.`))}),null;let a=t.arms;return i in a?a[i].parse(e,n,r):(e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:Q(e.source,[...n.split(`.`),t.tag])}),null)}function ws(e){return(...t)=>e()(...t)}function Ts(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:Q(n.source,o.split(`.`))}),null}return a}}function Es(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>ps(e,t,r,n)}}function Ds(){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 ${_s(i)}`,line:Q(e.source,[n])});return}return i}}}}function Os(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>ms(e,t,r)}}function ks(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>ds(e,t,r,n)??void 0}}function As(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>hs(t,n,i,r,e)}}function js(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 Ms(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function Ns(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function Ps(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}function Fs(e,t=Xn){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:{...t.segments,...e.segments??{}},root:e.root===void 0?t.root:e.root,actions:{...t.actions,...e.actions??{}},helpers:{...t.helpers,...e.helpers??{}}}}const Is={noun:`globals key`,fields:{default_bg:Es(),default_fg:Es(),default_empty_value:Es(),default_separator:Es(),default_truncate_marker:Es(),palette:Os(),style:As(is)}};function Ls(e,t){return t===void 0?{}:ys(e,Is,`globals`,t)??{}}function Rs(e,t,n,r){return n.cache===void 0?(Ln.includes(r)&&e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${z.join(`, `)})`,line:Q(e.source,t.split(`.`))}),null):Ws(e,`${t}.cache`,n.cache)}function zs(e,t,n){if(n.cache!==void 0)return Ws(e,`${t}.cache`,n.cache)??void 0}function Bs(e){return{required:!0,json:qs(),parse:(t,n,r,i)=>Rs(t,n,i,e)??void 0}}function Vs(){return{required:!1,json:qs(),parse:(e,t,n,r)=>zs(e,t,r)}}function Hs(e,t,n){return e.issues.push({path:t,message:n,line:Q(e.source,t.split(`.`))}),null}const Us={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Ys(n)?{ttl:n}:Hs(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${vs(n)}`)},watch_file:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{watch_file:n}:Hs(e,t,`cache.watch_file must be a non-empty path string, got ${vs(n)}`)},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:Hs(e,t,`cache.depends_on must be an array of variable-name strings, got ${vs(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:Hs(e,t,`cache.key must be a non-empty template string, got ${vs(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:Hs(e,t,`cache.never must be the literal boolean true, got ${vs(n)}`)}}};function Ws(e,t,n){return Ss(e,Us,t,n)}const Gs={noun:`time-variable cache`,arms:{ttl:Us.arms.ttl}};function Ks(){return{required:!1,json:Ps(Gs),parse:(e,t,n,r)=>r.cache===void 0?void 0:Ss(e,Gs,`${t}.cache`,r.cache)??void 0}}function qs(){return Ps(Us)}const Js=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Ys(e){return Js.test(e)}function Xs(e,t,n){if(n===void 0)return{};if(!gs(n))return e.issues.push({path:t,message:`${t} must be an object, got ${_s(n)}`,line:Q(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=Cs(e,uc,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function Zs(){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 ${_s(i)}`,line:Q(e.source,t.split(`.`))});return}return i}}}function Qs(){return{required:!0,json:{enum:[...In]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!In.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${In.join(`, `)}, got ${JSON.stringify(i)}`,line:Q(e.source,[...t.split(`.`),`field`])});return}return i}}}function $s(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return fs(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const ec={value:Zs(),default:Es()},tc={path:ks(),type:As([`string`,`number`,`boolean`]),default:$s()},nc={name:ks(),default:Es()},rc={path:ks(),readMode:As([`whole`,`first-line`]),regex:Es(),cache:Bs(`file`),default:Es()},ic={command:ks(),regex:Es(),cache:Bs(`shell`),default:Es()},ac={template:ks(),cache:Vs(),default:Es()},oc={layout:ks(),cache:Ks(),default:Es()},sc={field:Qs(),cache:Bs(`git`),default:Es()},cc={key:ks(),default:Es()};function lc(e,t){return{json:Ms(js(t),`kind`,e),parse:(n,r,i)=>{let a=bs(n,t,r,i);return a===null?null:{kind:e,...a}}}}const uc={tag:`kind`,noun:`source kind`,arms:{literal:lc(`literal`,ec),input:lc(`input`,tc),env:lc(`env`,nc),file:lc(`file`,rc),shell:lc(`shell`,ic),template:lc(`template`,ac),time:lc(`time`,oc),git:lc(`git`,sc),state:lc(`state`,cc)}};function dc(){return Ns(uc)}function fc(){return{type:`object`,additionalProperties:dc()}}function pc(e,t){if(t===void 0)return{};if(!gs(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${_s(t)}`,line:Q(e.source,[`segments`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=ys(e,gc,`segments.${r}`,i);t!==null&&(n[r]=t)}return n}function mc(){return{required:!1,json:{anyOf:[{const:`auto`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto" or a positive integer, got ${vs(i)}`,line:Q(e.source,[...t.split(`.`),n])})}}}}function hc(){return{required:!1,json:fc(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return Xs(e,`${t}.${n}`,i)}}}const gc={noun:`segment key`,fields:{template:ks(),width:mc(),justify:As(Rn),truncate:As(zn),bg:Es(),fg:Es(),when:Es(),palette:Os(),vars:hc()}},_c={kind:`container`,direction:`vertical`,children:[]};function vc(e){return{required:!0,json:{const:e},parse:()=>e}}function yc(){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 ${vs(i)}`,line:Q(e.source,[`root`])}),``)}}}function bc(){return{required:!0,json:{enum:[...Nn]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Nn.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${Nn.join(`, `)} (got ${JSON.stringify(i)})`,line:Q(e.source,[`root`])}),`vertical`)}}}function xc(e){return{required:!0,json:{type:`array`,items:{$ref:`#/definitions/LayoutNode`}},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 ${_s(a)}`,line:Q(t.source,[`root`])}),[])}}}const Sc={noun:`layout-node key`,fields:{kind:vc(`segment`),name:yc(),when:Es()}},Cc={noun:`layout-node key`,fields:{kind:vc(`container`),direction:bc(),children:xc(ws(()=>Oc)),when:Es()}};function wc(){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 ${vs(i)}`,line:Q(e.source,[`root`])}),``)}}}const Tc={noun:`layout-node key`,fields:{seg:wc(),when:Es()}},Ec={noun:`layout-node key`,fields:{h:xc(ws(()=>Oc)),when:Es()}},Dc={noun:`layout-node key`,fields:{v:xc(ws(()=>Oc)),when:Es()}},Oc=(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:Q(e.source,[`root`])}),_c):{kind:`segment`,name:n};if(!gs(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 ${_s(n)}`,line:Q(e.source,[`root`])}),_c;if(n.kind===`container`)return ys(e,Cc,t,n)??_c;if(n.kind===`segment`)return ys(e,Sc,t,n)??_c;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
83
+ Old: { kind: "cells", segments: ["seg1", "seg2"] }
84
+ New: { h: ["seg1", "seg2"] }`,line:Q(e.source,[`root`])}),_c;if(n.kind===`group`){let r=ys(e,Fc,t,n);return r===null?_c:(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}),Lc(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:Q(e.source,[`root`])}),_c}if(a){let r=ys(e,Tc,t,n);return r===null?_c:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when}}}if(r){let r=ys(e,Ec,t,n);return r===null?_c:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when}}}if(i){let r=ys(e,Dc,t,n);return r===null?_c:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when}}}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:Q(e.source,[`root`])}),_c},kc=`groups.`,Ac=`closed`,jc=/^[A-Za-z_][A-Za-z0-9_]*$/;function Mc(){return{required:!0,json:{type:`string`,pattern:jc.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!jc.test(i)||i===Ac){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 "${Ac}", got ${vs(i)}`,line:Q(e.source,[`root`])});return}return i}}}function Nc(){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 ${vs(i)}`,line:Q(e.source,[`root`])});return}return i}}}}function Pc(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=ds(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:Q(e.source,[...t.split(`.`),n])});return}return i}}}}const Fc={noun:`layout-node key`,fields:{kind:vc(`group`),name:Mc(),label:Pc(),open:Ds(),direction:As(Nn),key:Nc(),bg:Es(),fg:Es(),when:Es(),children:xc(ws(()=>Oc))}};function Ic(e){return e.key??`groups.`+e.name}function Lc(e){let t=kc+e.name;return{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:t},{kind:`container`,direction:e.direction??`vertical`,children:e.children,when:`{{ eq .${t} "${e.name}" }}`}],...e.when!==void 0&&{when:e.when}}}function Rc(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function zc(e,t,n){e.issues.push({path:t,message:n,line:Q(e.source,[`root`])})}function Bc(e,t){let n=e.groups;if(n.length===0)return;for(let n of[`variables`,`actions`,`segments`])for(let r of Object.keys(t[n]??{}))r.startsWith(`groups.`)&&zc(e,`${n}.${r}`,`"${r}" is in the reserved "${kc}" namespace (synthesized by group nodes) — rename it`);let r=new Set;for(let t of n)r.has(t.name)&&zc(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}.`)&&Ic(t)===Ic(r)&&zc(e,t.path,`group "${t.name}" shares key "${Ic(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=Ic(t);if(i.has(n)||i.set(n,Ac),t.open===!0){let r=i.get(n);r!==Ac&&zc(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=kc+e.name,r=Ic(e),c=Rc(e.label),l=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,u=` `.repeat(l);a[t]={kind:`state`,key:r,default:i.get(r)},o[t]={set:r,cycle:[Ac,e.name]},s[t]={template:`{{ action "${t}" "${u}${c} ▸" "${u}${c} ▾" }}`,...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}}var Vc=class extends Error{name=`TemplateError`;kind=`EvalError`;pos;source;constructor(e,t,n={}){super(e),this.pos=t,this.source=n.source}get sourceSnippet(){return this.source?Jc(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}},Hc=class extends Vc{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},Uc=class extends Vc{name=`EvalError`;kind=`EvalError`},Wc=class extends Uc{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=Yc(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}},Gc=class extends Uc{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}},Kc=class extends Uc{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},qc=class extends Uc{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function Jc(e,t){let n=e.split(`
82
85
  `),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(`
83
- `)}function Ro(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:zo(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 zo(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 Bo(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const Vo=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`]]),Ho={left:`{{`,right:`}}`};var Uo=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=Ho){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 jo(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&&Wo(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);Wo(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);Wo(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(;Wo(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`;Wo(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&&(Ko(e)||Go(e)&&Ko(this.src[this.offset+1]??``)||e===`.`&&Ko(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&Zo(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===`
86
+ `)}function Yc(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:Xc(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 Xc(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 Zc(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const Qc=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`]]),$c={left:`{{`,right:`}}`};var el=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=$c){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 Hc(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&&tl(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);tl(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);tl(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(;tl(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`;tl(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&&(rl(e)||nl(e)&&rl(this.src[this.offset+1]??``)||e===`.`&&rl(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&cl(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===`
84
87
  `)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===`
85
- `)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(Go(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);qo(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);Jo(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);Yo(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;Ko(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);Ko(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),Go(this.src[this.offset]??``)&&this.advanceBy(1);Ko(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return qo(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);Qo(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&Zo(this.src[this.offset+1]??``);)for(this.advanceBy(1);Qo(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),!Zo(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;Qo(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&Zo(this.src[this.offset+1]??``);)for(this.advanceBy(1);Qo(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(;Qo(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=Vo.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===`
88
+ `)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(nl(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);il(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);al(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);ol(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);return this.finishNumber(t,e)}}for(;rl(this.src[this.offset]??``)||this.src[this.offset]===`_`;)this.advanceBy(1);if(this.src[this.offset]===`.`)for(this.advanceBy(1);rl(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),nl(this.src[this.offset]??``)&&this.advanceBy(1);rl(this.src[this.offset]??``);)this.advanceBy(1);return this.src[this.offset]===`i`&&this.advanceBy(1),this.finishNumber(t,e)}isHexFloatTail(e){return il(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);ll(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&cl(this.src[this.offset+1]??``);)for(this.advanceBy(1);ll(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),!cl(this.src[this.offset]??``))return this.makeToken(`Dot`,`.`,e);for(;ll(this.src[this.offset]??``);)this.advanceBy(1);for(;this.src[this.offset]===`.`&&cl(this.src[this.offset+1]??``);)for(this.advanceBy(1);ll(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(;ll(this.src[this.offset]??``);)this.advanceBy(1);let n=this.src.slice(t,this.offset),r=Qc.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===`
86
89
  `)this.advanceBy(1);else return}}advanceBy(e){for(let t=0;t<e;t++){let e=this.src[this.offset];this.offset+=1,e===`
87
- `?(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 Wo(e){return e===` `||e===` `||e===`\r`||e===`
88
- `}function Go(e){return e===`+`||e===`-`}function Ko(e){return e>=`0`&&e<=`9`}function qo(e){return Ko(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function Jo(e){return e>=`0`&&e<=`7`}function Yo(e){return e===`0`||e===`1`}function Xo(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function Zo(e){return Xo(e)||e===`_`}function Qo(e){return Zo(e)||Ko(e)}function $o(e,t){return new es(e,t).parseTemplate()}var es=class{lex;buf=[];defines=new Map;source;rangeDepth=0;constructor(e,t){this.source=e,this.lex=t?new Uo(e,t):new Uo(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:rs(n)});return n}errAt(e,t,n={}){return new jo(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 ${rs(e)}`,{found:rs(e)})}return{root:e,defines: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=ns(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 ts(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${rs(n)} at top level`,{found:rs(n)})}return ts(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 jo(`{{${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.defines.set(n,a),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))throw new jo(`redefinition of template ${JSON.stringify(n)}`,i.pos,{source:this.source});this.defines.set(n,i)}parseQuotedName(){let e=this.next();if(e.type!==`String`)throw this.errAt(e,`expected template name (quoted string)`,{expected:`string`,found:rs(e)});return ds(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(!is(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:rs(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=[as(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(as(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;is(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 as(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:ds(e.value,e.pos,this.source)};case`Number`:return ss(e);case`Char`:return cs(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 ${rs(e)}`,{expected:`command argument`,found:rs(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 ts(e,t){return{type:`List`,pos:e,nodes:t}}function ns(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function rs(e){return e.type===`EOF`?`end of input`:e.value||e.type}function is(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 as(e){return{type:`Variable`,pos:e.pos,idents:os(e.value)}}function os(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function ss(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=ls(i);return{...s,intValue:e}}if(a){let e=us(i);return{...s,floatValue:e}}let c=us(i);return{...s,complexValue:[0,c]}}function cs(e,t){let n=fs(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 ls(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 us(e){return Number(e)}function ds(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+=`
89
- `;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 jo(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function fs(e,t,n){let r=ds(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new jo(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function ps(e,t){if(t(e)!==!1)for(let n of ms(e))ps(n,t)}function ms(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 Bo(e)}}const hs=Symbol(`go-template-js.MISSING`);function gs(e,t){if(e==null)return hs;if(e instanceof Map)return e.has(t)?e.get(t):hs;if(Array.isArray(e))return hs;if(typeof e==`object`){let n=e;return t in n?n[t]:hs}return hs}function _s(e,t){let n=e;for(let e of t){if(n===hs)return hs;n=gs(n,e)}return n}function vs(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)=>vs(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)||!vs(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=>vs(e[n],t[n])):!1}return!1}const ys=new WeakSet;function bs(e){return ys.add(e),e}function xs(e){return ys.has(e)}function Ss(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 Cs(e){return{eq:{fn:(e,...t)=>t.some(t=>Es(e,t)),argTypes:[`comparable`]},ne:{fn:(e,t)=>!Es(e,t),argTypes:[`comparable`,`comparable`]},lt:{fn:(e,t)=>Ds(e,t)<0,argTypes:[`ordered`,`ordered`]},le:{fn:(e,t)=>Ds(e,t)<=0,argTypes:[`ordered`,`ordered`]},gt:{fn:(e,t)=>Ds(e,t)>0,argTypes:[`ordered`,`ordered`]},ge:{fn:(e,t)=>Ds(e,t)>=0,argTypes:[`ordered`,`ordered`]},len:{fn:e=>Os(e),argTypes:[`sized`]},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=ks(n,e);return n},argTypes:[`collection`,`index-key`]},slice:{fn:(e,...t)=>{let n=t.length>=1?t[0]:0,r=t.length>=2?t[1]:void 0;return e.slice(n,r)},argTypes:[`sliceable`,`int`]},print:{fn:(...t)=>Ms(t,e),argTypes:[`stringifiable`],returnType:`string`},println:{fn:(...t)=>`${Ms(t,e)}\n`,argTypes:[`stringifiable`],returnType:`string`},printf:{fn:(t,...n)=>Vs(t,n,e),argTypes:[`string`,`stringifiable`],returnType:`string`},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`]},html:{fn:(...t)=>Fs(Ms(t,e)),argTypes:[`stringifiable`],returnType:`string`},js:{fn:(...t)=>Rs(Ms(t,e)),argTypes:[`stringifiable`],returnType:`string`},urlquery:{fn:(...t)=>Bs(Ms(t,e)),argTypes:[`stringifiable`],returnType:`string`},not:{fn:e=>!Ss(e),argTypes:[`truthy`]}}}function ws(){return{and:bs({argTypes:[`truthy`],fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!Ss(t))return t;return t}}),or:bs({argTypes:[`truthy`],fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),Ss(t))return t;return t}})}}function Ts(e){return{...Cs(e),...ws()}}function Es(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):vs(e,t)}function Ds(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 Os(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function ks(e,t){if(Array.isArray(e)){let n=Number(t);if(!Number.isInteger(n))throw Error(`index: array index must be integer, got ${As(t)}`);if(n<0||n>=e.length)throw Error(`index: out of range [${n}] with length ${e.length}`);return e[n]}if(e instanceof Map)return e.get(t);if(typeof e==`string`)return e[Number(t)];if(typeof e==`object`&&e){if(typeof t!=`string`)throw Error(`index: object index must be string, got ${As(t)}`);return e[t]}throw Error(`index: cannot index ${As(e)}`)}function As(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function js(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 Ms(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+=Ns(a,t),r=o}return n}function Ns(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const Ps={"\0":`�`,'"':`&#34;`,"'":`&#39;`,"&":`&amp;`,"<":`&lt;`,">":`&gt;`};function Fs(e){return e.replace(/[\0"'&<>]/g,e=>Ps[e]??e)}const Is={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},Ls=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function Rs(e){let t=``;for(let n of e){let e=Is[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!Ls.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const zs=new TextEncoder;function Bs(e){let t=``,n=zs.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 Vs(e,t,n){let r=``,i=0,a=0;for(;a<e.length;){let o=e[a];if(o!==`%`){r+=o,a+=1;continue}if(e[a+1]===`%`){r+=`%`,a+=2;continue}let s=a+1;for(;s<e.length&&`+-# 0`.includes(e[s]??``);)s+=1;for(;s<e.length&&e[s]!==void 0&&/[0-9]/.test(e[s]);)s+=1;if(e[s]===`.`)for(s+=1;s<e.length&&e[s]!==void 0&&/[0-9]/.test(e[s]);)s+=1;let c=e[s],l=e.slice(a+1,s),u=t[i++];r+=Hs(c??``,l,u,n),a=s+1}return r}function Hs(e,t,n,r){switch(e){case`s`:return typeof n==`string`?Us(t,n):Us(t,Ns(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${js(n)}=${Ns(n,r)})`:Us(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return Us(t,Ws(n));case`q`:return Us(t,JSON.stringify(Ns(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${js(n)}=${Ns(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return Us(t,Number(n).toFixed(i))}case`t`:return Us(t,Ss(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 Us(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${js(n)}=${Ns(n,r)})`:typeof n==`bigint`?Us(t,n.toString(16)):Us(t,Math.trunc(n).toString(16));default:return`%!${e}(${js(n)}=${Ns(n,r)})`}}function Us(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 Ws(e){return e==null?`<nil>`:typeof e==`string`?e:typeof e==`bigint`?e.toString():Array.isArray(e)?`[${e.map(Ws).join(` `)}]`:e instanceof Map?`map[${[...e.entries()].map(([e,t])=>`${Ws(e)}:${Ws(t)}`).join(` `)}]`:typeof e==`object`?`{${Object.values(e).map(Ws).join(` `)}}`:String(e)}function Gs(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function Ks(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function qs(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 Js(e,t,n){e.vars.set(t,n)}const Ys=new Set([`default`,`zero`,`error`]);function Xs(e){if(e===void 0)return`default`;if(Ys.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${Zs(e)}`)}function Zs(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 Qs(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${Zs(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${Zs(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${Zs(e.right)}`);return{left:e.left,right:e.right}}}const $s=Object.freeze({kind:`break`}),ec=Object.freeze({kind:`continue`}),tc={kind:`none`};let nc;(class e{source;_evaluate;_referencedFunctions;constructor(e,t,n){this.source=e,this._evaluate=t,this._referencedFunctions=n}static{nc=(t,n,r)=>new e(t,n,r)}evaluate(e){return this._evaluate(e)}referencedFunctions(){return this._referencedFunctions}});function rc(e){let t=new Set,n=e=>{ps(e,e=>{e.type===`Identifier`&&t.add(e.ident)})};n(e.root);for(let t of e.defines.values())n(t);return t}var ic=class{fromString;toString;funcs;missingKey;delims;constructor(e){this.fromString=e.fromString;let t=Object.hasOwn(e,`toString`)?e.toString:void 0;this.toString=t??pc,this.missingKey=Xs(e.missingKey),this.delims=Qs(e.delims),this.funcs={...Ts(this.toString),...e.funcs??{}}}parse(e){let t=$o(e,this.delims);return nc(t.source,e=>this.evalParsed(t,e),rc(t))}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=Gs(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 $s;case`Continue`:throw ec;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 Mo(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:Bo(e)}}evalIf(e,t,n){Ss(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(Ss(r)){let i=Ks(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=xc(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=Ks(t,o);if(i.length===1)Js(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;Js(a,e,r),Js(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===ec)continue;throw e}}}catch(e){if(e===$s)return;throw e}}evalTemplateInvoke(e,t,n){let r=n.defines.get(e.name);if(!r)throw new Mo(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=Ks(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot);this.evalList(r,i,n)}evalBlock(e,t,n){let r=Ks(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=n.defines.get(e.name)??e.list;this.evalList(i,r,n)}evalAction(e,t,n){return this.evalPipe(e.pipe,t,n)}evalPipe(e,t,n){if(e.cmds.length===0)throw new Mo(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,tc);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)Js(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 Mo(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new Mo(`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 No(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=xs(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)}lc(i.ident,a.argTypes,c,e.pos,n.source,this.toString,a.argTypePattern,this.fromString);try{return a.fn(...c)}catch(t){throw t instanceof Po?new Po(t.funcName,t.argIndex,t.expected,t.receivedSummary,e.pos,{source:n.source}):t instanceof Io?new Io(t.message,e.pos,{source:n.source}):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 wc(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 No(e.ident,e.pos,{source:n.source,available:Object.keys(this.funcs)});return lc(e.ident,t.argTypes,[],e.pos,n.source,this.toString,t.argTypePattern,this.fromString),t.fn()}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 Mo(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=_s(e,t);if(i!==hs)return i;if(this.missingKey===`error`)throw new Fo(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=qs(t,i);if(!a.found)throw new Mo(`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(Array.isArray(e)){t.out.push(this.fromString(ac(e)));return}if(e instanceof Map){t.out.push(this.fromString(oc(e)));return}t.out.push(e)}};function ac(e){return`[${e.map(sc).join(` `)}]`}function oc(e){let t=[];for(let[n,r]of e)t.push(`${sc(n)}:${sc(r)}`);return`map[${t.join(` `)}]`}function sc(e){return e==null?`<nil>`:Array.isArray(e)?ac(e):e instanceof Map?oc(e):String(e)}function cc(e){return new ic(e)}function lc(e,t,n,r,i,a=pc,o,s=fc){let c=uc(t,o),l=-1,u=-1;for(let t=0;t<n.length;t++){let o=c(t),d=n[t];if(!dc(o,d,a))throw new Po(e,t+1,yc(o),bc(d),r,{source:i});if(o===`liftable`&&typeof d==`string`&&(n[t]=s(d)),o===`int`?n[t]=Math.trunc(Number(d)):o===`float`&&(n[t]=Number(d)),o===`ordered`){if(l===-1)l=t;else if(!gc(n[l],d))throw new Po(e,t+1,`${yc(`ordered`)} of the same kind as ${bc(n[l])}`,bc(d),r,{source:i})}if(o===`comparable`){if(u===-1)u=t;else if(!_c(n[u],d))throw new Po(e,t+1,`${yc(`comparable`)} of the same kind as ${bc(n[u])}`,bc(d),r,{source:i})}}}function uc(e,t){if(e.length===0)return()=>`value`;if(t===`alternating`){let t=e.length;return n=>e[n%t]}let n=e[e.length-1];return t=>t<e.length?e[t]:n}function dc(e,t,n){switch(e){case`truthy`:case`reflective`:case`value`:return!0;case`string`:return typeof t==`string`;case`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 t!=null&&typeof t!=`string`&&typeof t!=`number`&&typeof t!=`boolean`&&typeof t!=`bigint`&&typeof t!=`symbol`;case`list`:return Array.isArray(t);case`dict`:return mc(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||mc(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||mc(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||mc(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`||t!=null&&typeof t!=`number`&&typeof t!=`boolean`&&typeof t!=`bigint`&&typeof t!=`symbol`;case`serializable`:return hc(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function fc(e){return e}function pc(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 Po(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,bc(e),{line:0,column:0,offset:0})}function mc(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 hc(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function gc(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function _c(e,t){let n=vc(e),r=vc(t);return n===`nil`||r===`nil`?!0:n===r}function vc(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 yc(e){switch(e){case`int`:return`integer (finite number 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 bc(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function xc(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?Sc([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?Sc(Object.entries(e)):[]}function Sc(e){return[...e].sort((e,t)=>Cc(e[0],t[0]))}function Cc(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 wc(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 Tc(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function Ec(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 Dc(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 Oc(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=Dc(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 kc(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=Dc(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 Ac(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 jc(e){return JSON.stringify(e)??`null`}function Mc(e){return typeof e==`string`?e:Ws(e)}function Nc(e){return e.map(Mc)}function Pc(){return{atoi:{fn:e=>Tc(e),argTypes:[`string`],returnType:`int`},int:{fn:e=>Oc(e),argTypes:[`value`],returnType:`int`},int64:{fn:e=>kc(e),argTypes:[`value`]},float64:{fn:e=>Ec(e),argTypes:[`value`],returnType:`float`},toString:{fn:e=>Mc(e),argTypes:[`value`],returnType:`string`},toStrings:{fn:e=>Nc(e),argTypes:[`list`]},toDecimal:{fn:e=>Ac(e),argTypes:[`string`],returnType:`int`},toRawJson:{fn:e=>jc(e),argTypes:[`serializable`],returnType:`string`}}}const Fc={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function Ic(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*Fc[a],n=n.slice(e[0].length)}return t?-r:r}function Lc(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<Fc.us?`${Math.floor(n)}ns`:n<Fc.ms?Rc(n,Fc.us,3,`µs`):n<Fc.s?Rc(n,Fc.ms,6,`ms`):zc(n),t?`-${r}`:r}function Rc(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 zc(e){let t=Math.floor(e/Fc.h);e-=t*Fc.h;let n=Math.floor(e/Fc.m);e-=n*Fc.m;let r=Math.floor(e/Fc.s),i=e-r*Fc.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 Bc(e){return e*Fc.s}function Vc(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 Hc(e,t){let n=t().getTime()-Vc(e).getTime();return Lc(Math.round(n/1e3)*1e9)}const Uc=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Wc=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Gc=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],Kc=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function qc(e){return e<10?`0${e}`:String(e)}function Jc(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function Yc(e){return e<10?` ${e}`:String(e)}function Xc(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${qc(Math.floor(n/60))}${qc(n%60)}`}function Zc(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${qc(Math.floor(n/60))}:${qc(n%60)}`}function Qc(e){return`${e>=0?`+`:`-`}${qc(Math.floor(Math.abs(e)/60))}`}function $c(e){return e===0?`Z`:Xc(e)}function el(e){return e===0?`Z`:Zc(e)}function tl(e){return e===0?`Z`:Qc(e)}function nl(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const rl=[[`.000000000`,e=>`.${nl(e.ms,9,!1)}`],[`.999999999`,e=>{let t=nl(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${nl(e.ms,6,!1)}`],[`.999999`,e=>{let t=nl(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${Jc(e.ms)}`],[`.999`,e=>{let t=Jc(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>Uc[e.month-1]??`January`],[`Monday`,e=>Gc[e.weekday]??`Monday`],[`Z07:00`,e=>el(e.offsetMinutes)],[`-07:00`,e=>Zc(e.offsetMinutes)],[`Z0700`,e=>$c(e.offsetMinutes)],[`-0700`,e=>Xc(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>Wc[e.month-1]??`Jan`],[`Mon`,e=>Kc[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>Qc(e.offsetMinutes)],[`Z07`,e=>tl(e.offsetMinutes)],[`15`,e=>qc(e.hour)],[`01`,e=>qc(e.month)],[`02`,e=>qc(e.day)],[`_2`,e=>Yc(e.day)],[`03`,e=>qc(e.hour12)],[`04`,e=>qc(e.minute)],[`05`,e=>qc(e.second)],[`06`,e=>qc(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 il(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of rl)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const al={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function ol(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const sl=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function cl(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=ol(new Intl.DateTimeFormat(`en-US`,{...al,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=ol(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=ll(ol(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=sl.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 ll(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 ul(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function dl(e,t){return il(e,cl(Vc(t),ul()))}function fl(e,t,n){return il(e,cl(Vc(t),n))}function pl(e,t){let n=Vc(t),r=Ic(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function ml(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:Lc(Bc(t))}return typeof e==`bigint`?Lc(Bc(Number(e))):typeof e==`number`?Lc(Bc(e)):`0s`}const hl=36e11*24*365,gl=36e11*24*30,_l=36e11*24,vl=36e11,yl=6e10,bl=1e9;function xl(e){let t=Ic(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>hl?`${Math.floor(n/hl)}y`:n>gl?`${Math.floor(n/gl)}mo`:n>_l?`${Math.floor(n/_l)}d`:n>vl?`${Math.floor(n/vl)}h`:n>yl?`${Math.floor(n/yl)}m`:n>bl?`${Math.floor(n/bl)}s`:`0s`}function Sl(e){let t=cl(Vc(e),ul());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function Cl(e,t){let n=cl(Vc(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function wl(e){return e()}const Tl=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],El=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function Dl(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function Ol(e,t,n){return[e.slice(t,t+n),t+n]}function kl(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 Al(e,t){for(let[n,r]of Tl.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function jl(e,t){for(let[n,r]of El.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function Ml(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 Nl(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 Pl(e,t){if(e[t]===` `){let[n,r]=kl(e,t+1,1,1);return[n,r]}return kl(e,t,1,2)}function Fl(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]=kl(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=kl(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=kl(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function Il(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]=kl(e,t+1,2,2);return[n*r*60,i]}return Fl(e,t,n)}function Ll(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 Rl(e,t,n){let[r,i]=Ol(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function zl(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=Al(t,n);return i.month=e,[r,i]}case`Monday`:return[Ml(t,n),i];case`Jan`:{let[e,r]=jl(t,n);return i.month=e,[r,i]}case`Mon`:return[Nl(t,n),i];case`2006`:{let[e,r]=kl(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=kl(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=kl(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=kl(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=Pl(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=kl(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=kl(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=kl(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=kl(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=kl(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=kl(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=kl(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=kl(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=kl(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[Ll(t,n),i];case`-0700`:{let[e,r]=Fl(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=Fl(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]=kl(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=Il(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=Il(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=Il(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]=Rl(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]=Rl(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]=Rl(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 Bl=`.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 Vl(e,t){let n=0,r=0,i=Dl();for(;n<e.length;){let a=!1;for(let o of Bl)if(e.startsWith(o,n)){let[e,s]=zl(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 Hl(e,t){return Vl(e,t)}function Ul(e){return String(Math.floor(Vc(e).getTime()/1e3))}function Wl(e=()=>new Date){return{now:{fn:()=>wl(e),argTypes:[]},date:{fn:(e,t)=>dl(e,t),argTypes:[`string`,`value`]},dateInZone:{fn:(e,t,n)=>fl(e,t,n),argTypes:[`string`,`value`,`string`]},dateModify:{fn:(e,t)=>pl(e,t),argTypes:[`string`,`value`]},htmlDate:{fn:e=>Sl(e),argTypes:[`value`]},htmlDateInZone:{fn:(e,t)=>Cl(e,t),argTypes:[`value`,`string`]},duration:{fn:e=>ml(e),argTypes:[`value`]},durationRound:{fn:e=>xl(e),argTypes:[`value`]},toDate:{fn:(e,t)=>Hl(e,t),argTypes:[`string`,`string`]},ago:{fn:t=>Hc(t,e),argTypes:[`value`]},unixEpoch:{fn:e=>Ul(e),argTypes:[`value`]}}}function Gl(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 Kl(...e){for(let t of e)if(!Gl(t))return t}function ql(e,t){return Gl(t)?e:t}function Jl(e){return JSON.parse(e)}function Yl(e,t,n){return Ss(n)?e:t}function Xl(e){return JSON.stringify(e)??`null`}function Zl(e){return JSON.stringify(e,null,2)??`null`}function Ql(){return{default:{fn:(e,t)=>ql(e,t),argTypes:[`value`,`truthy`]},empty:{fn:e=>Gl(e),argTypes:[`truthy`]},coalesce:{fn:(...e)=>Kl(...e),argTypes:[`truthy`]},ternary:{fn:(e,t,n)=>Yl(e,t,n),argTypes:[`value`,`value`,`truthy`]},fromJson:{fn:e=>Jl(e),argTypes:[`string`]},toJson:{fn:e=>Xl(e),argTypes:[`serializable`],returnType:`string`},toPrettyJson:{fn:e=>Zl(e),argTypes:[`serializable`],returnType:`string`}}}function $l(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function eu(e,t){return e[t]}function tu(e,t){return t in e}function nu(e){return Object.keys(e)}function ru(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 iu(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function au(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 ou(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function su(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function cu(e,t,n){return e[t]=n,e}function lu(e,t){return delete e[t],e}function uu(e){return Object.values(e)}function du(){return{dict:{fn:(...e)=>$l(...e),argTypes:[`string`,`value`],argTypePattern:`alternating`},get:{fn:(e,t)=>eu(e,t),argTypes:[`dict`,`string`]},set:{fn:(e,t,n)=>cu(e,t,n),argTypes:[`dict`,`string`,`value`]},unset:{fn:(e,t)=>lu(e,t),argTypes:[`dict`,`string`]},keys:{fn:e=>nu(e),argTypes:[`dict`]},values:{fn:e=>uu(e),argTypes:[`dict`]},pluck:{fn:(e,...t)=>su(e,...t),argTypes:[`string`,`dict`]},pick:{fn:(e,...t)=>ou(e,...t),argTypes:[`dict`,`string`]},omit:{fn:(e,...t)=>au(e,...t),argTypes:[`dict`,`string`]},hasKey:{fn:(e,t)=>tu(e,t),argTypes:[`dict`,`string`]},merge:{fn:(e,...t)=>ru(e,...t),argTypes:[`dict`]},mergeOverwrite:{fn:(e,...t)=>iu(e,...t),argTypes:[`dict`]}}}new TextEncoder,new Map(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`).map((e,t)=>[e,t])),new TextDecoder,new TextEncoder,new TextDecoder,new TextEncoder;function fu(...e){for(let t of e)if(Gl(t))return!1;return!0}function pu(...e){for(let t of e)if(!Gl(t))return!0;return!1}function mu(e,t){return[...e,t]}function hu(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 gu(e){return e.filter(e=>!Gl(e))}function _u(...e){let t=[];for(let n of e)t.push(...n);return t}const vu={line:0,column:0,offset:0};function yu(e,t,n,r){return new Po(e,t,n,r,vu)}function bu(...e){if(e.length<3)throw yu(`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(!Su(t))throw yu(`dig`,e.length-1,`dict`,Cu(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw yu(`dig`,e,`string`,Cu(r[e]));return xu(t,n,r,e.length)}function xu(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(!Su(a))throw yu(`dig`,r-1,`dict at intermediate key`,Cu(a));return xu(a,t,n.slice(1),r)}function Su(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function Cu(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function wu(e){return e[0]}function Tu(e,t){return t.some(t=>vs(t,e))}function Eu(e){return e.slice(0,-1)}function Du(e){return e[e.length-1]}function Ou(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function ku(...e){return e}function Au(e,t){return[t,...e]}function ju(e){return e.slice(1)}function Mu(e){return[...e].reverse()}function Nu(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function Pu(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function Fu(e){let t=[];for(let n of e)t.some(e=>vs(e,n))||t.push(n);return t}function Iu(e,...t){return e.filter(e=>!t.some(t=>vs(t,e)))}function Lu(){return{list:{fn:(...e)=>ku(...e),argTypes:[`value`]},first:{fn:e=>wu(e),argTypes:[`list`]},last:{fn:e=>Du(e),argTypes:[`list`]},rest:{fn:e=>ju(e),argTypes:[`list`]},initial:{fn:e=>Eu(e),argTypes:[`list`]},len:{fn:e=>Ou(e),argTypes:[`sized`]},reverse:{fn:e=>Mu(e),argTypes:[`list`]},uniq:{fn:e=>Fu(e),argTypes:[`list`]},without:{fn:(e,...t)=>Iu(e,...t),argTypes:[`list`,`value`]},has:{fn:(e,t)=>Tu(e,t),argTypes:[`value`,`list`]},compact:{fn:e=>gu(e),argTypes:[`list`]},slice:{fn:(e,t,n)=>Nu(e,t,n),argTypes:[`list`,`int`,`int`]},concat:{fn:(...e)=>_u(...e),argTypes:[`list`]},chunk:{fn:(e,t)=>hu(e,t),argTypes:[`int`,`list`]},prepend:{fn:(e,t)=>Au(e,t),argTypes:[`list`,`value`]},append:{fn:(e,t)=>mu(e,t),argTypes:[`list`,`value`]},sortAlpha:{fn:e=>Pu(e),argTypes:[`list`],returnType:`list`},push:{fn:(e,t)=>mu(e,t),argTypes:[`list`,`value`]},tuple:{fn:(...e)=>ku(...e),argTypes:[`value`]},dig:{fn:(...e)=>bu(...e),argTypes:[`value`]},all:{fn:(...e)=>fu(...e),argTypes:[`truthy`],returnType:`bool`},any:{fn:(...e)=>pu(...e),argTypes:[`truthy`],returnType:`bool`}}}function Ru(...e){return e.reduce((e,t)=>e+t,0)}function zu(e){return e+1}function Bu(e){return e+1}function Vu(...e){return e.reduce((e,t)=>e+t,0)}function Hu(e){return Math.ceil(e)}function Uu(e,t){return Math.trunc(e/t)}function Wu(e,t){return e/t}function Gu(e){return Math.floor(e)}function Ku(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function qu(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function Ju(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function Yu(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function Xu(e,t){return e%t}function Zu(...e){return e.reduce((e,t)=>e*t,1)}function Qu(...e){return e.reduce((e,t)=>e*t,1)}function $u(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function ed(e,t,n){let r=[];if(t<e){if(n>=0)return r;for(let i=e;i>t;i+=n)r.push(i);return r}if(n<=0)return r;for(let i=e;i<t;i+=n)r.push(i);return r}function td(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),ed(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return ed(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:ed(n,i+t,r).join(` `)}default:return``}}function nd(e,t){return e-t}function rd(e,t){return e-t}function id(e){return ed(0,e,e<0?-1:1)}function ad(){return{add:{fn:(...e)=>Ru(...e),argTypes:[`int`]},sub:{fn:(e,t)=>nd(e,t),argTypes:[`int`,`int`]},mul:{fn:(...e)=>Zu(...e),argTypes:[`int`]},div:{fn:(e,t)=>Uu(e,t),argTypes:[`int`,`int`]},mod:{fn:(e,t)=>Xu(e,t),argTypes:[`int`,`int`]},min:{fn:(...e)=>Ju(...e),argTypes:[`int`]},max:{fn:(...e)=>Ku(...e),argTypes:[`int`]},floor:{fn:e=>Gu(e),argTypes:[`float`]},ceil:{fn:e=>Hu(e),argTypes:[`float`]},round:{fn:(e,t)=>$u(e,t),argTypes:[`float`,`int`]},addf:{fn:(...e)=>Vu(...e),argTypes:[`float`]},subf:{fn:(e,t)=>rd(e,t),argTypes:[`float`,`float`]},mulf:{fn:(...e)=>Qu(...e),argTypes:[`float`]},divf:{fn:(e,t)=>Wu(e,t),argTypes:[`float`,`float`]},add1:{fn:e=>zu(e),argTypes:[`int`]},add1f:{fn:e=>Bu(e),argTypes:[`float`]},maxf:{fn:(...e)=>qu(...e),argTypes:[`float`]},minf:{fn:(...e)=>Yu(...e),argTypes:[`float`]},biggest:{fn:(...e)=>Ku(...e),argTypes:[`int`]},seq:{fn:(...e)=>td(...e),argTypes:[`int`],returnType:`string`},until:{fn:e=>id(e),argTypes:[`int`],returnType:`list`},untilStep:{fn:(e,t,n)=>ed(e,t,n),argTypes:[`int`,`int`,`int`],returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function od(e,t){return t.length<=e||e<4?t:`${t.slice(0,e-3)}...`}function sd(e,t,n){return t<7||n.length<t||e<0||e>n.length-t+1?n:`...${n.slice(e,e+t-6)}...`}const Q={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},cd=/^[-_\s]$/,ld=/^\p{P}$/u,ud=/^\p{L}$/u,dd=/^\p{Lu}$/u,fd=/^\p{N}$/u;function pd(e){return e!==void 0&&cd.test(e)}function md(e){return e!==void 0&&ud.test(e)}function hd(e){return e!==void 0&&dd.test(e)}function gd(e){return e!==void 0&&fd.test(e)}function _d(e){return e!==void 0&&ld.test(e)}function vd(e,t){if(t>=e.length)return{word:{wt:Q.Invalid,text:``},next:t};let n=e[t],r=t+1;if(pd(n)){for(;r<e.length&&pd(e[r]);)r++;return{word:{wt:Q.Connector,text:e.slice(t,r).join(``)},next:r}}if(_d(n)){for(;r<e.length&&_d(e[r]);)r++;return{word:{wt:Q.Punct,text:e.slice(t,r).join(``)},next:r}}if(hd(n)){if(r>=e.length)return{word:{wt:Q.UpperCase,text:n},next:r};if(hd(e[r])){let n=r;for(;n<e.length&&hd(e[n]);)n++;return n<e.length&&md(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(md(e[r])){let n=r+1;for(;n<e.length&&md(e[n])&&!hd(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(md(n)){for(;r<e.length&&md(e[r])&&!hd(e[r]);)r++;return{word:{wt:Q.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(gd(n)){for(;r<e.length&&gd(e[r]);)r++;return{word:{wt:Q.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!pd(e[r])&&!md(e[r])&&!gd(e[r])&&!_d(e[r]);)r++;return{word:{wt:Q.Other,text:e.slice(t,r).join(``)},next:r}}function yd(e,t,n){if(t.wt!==Q.UpperCase&&t.wt!==Q.Connector){e.push(t.text);return}for(let r of t.text)pd(r)?e.push(n):hd(r)?e.push(r.toLowerCase()):e.push(r)}function bd(e,t){if(e.length===0)return``;let n=Array.from(e),r=[],{word:i,next:a}=vd(n,0);for(;a<n.length;){i.wt!==Q.Connector&&yd(r,i,t);let e=i,o=i;if({word:i,next:a}=vd(n,a),e.wt===Q.Number){for(;i.wt===Q.Alphabet||i.wt===Q.Number;)yd(r,i,t),{word:i,next:a}=vd(n,a);i.wt!==Q.Invalid&&i.wt!==Q.Punct&&i.wt!==Q.Connector&&r.push(t);continue}if(e.wt===Q.Connector){yd(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}=vd(n,a),i.wt!==Q.Alphabet){yd(r,s,t),i.wt!==Q.Connector&&i.wt!==Q.Punct&&r.push(t);continue}for(r.push(t),yd(r,s,t);i.wt===Q.Alphabet||i.wt===Q.Number;)yd(r,i,t),{word:i,next:a}=vd(n,a);i.wt!==Q.Invalid&&i.wt!==Q.Connector&&i.wt!==Q.Punct&&r.push(t)}return yd(r,i,t),r.join(``).toLowerCase()}function xd(e){if(e.length===0)return``;let t=Array.from(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!pd(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++,pd(i)&&pd(e)){n.push(e);continue}pd(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function Sd(e){return xd(e)}function Cd(...e){return e.join(` `)}function wd(e,t){return t.includes(e)}function Td(e,t){return t.startsWith(e)}function Ed(e,t){return t.endsWith(e)}function Dd(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
90
+ `?(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 tl(e){return e===` `||e===` `||e===`\r`||e===`
91
+ `}function nl(e){return e===`+`||e===`-`}function rl(e){return e>=`0`&&e<=`9`}function il(e){return rl(e)||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}function al(e){return e>=`0`&&e<=`7`}function ol(e){return e===`0`||e===`1`}function sl(e){return e>=`a`&&e<=`z`||e>=`A`&&e<=`Z`}function cl(e){return sl(e)||e===`_`}function ll(e){return cl(e)||rl(e)}function ul(e,t){return new dl(e,t).parseTemplate()}var dl=class{lex;buf=[];defines=new Map;source;rangeDepth=0;constructor(e,t){this.source=e,this.lex=t?new el(e,t):new el(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:ml(n)});return n}errAt(e,t,n={}){return new Hc(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 ${ml(e)}`,{found:ml(e)})}return{root:e,defines: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=pl(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 fl(e,t);let r=this.parseAction();r!==null&&t.push(r);continue}throw this.errAt(n,`unexpected ${ml(n)} at top level`,{found:ml(n)})}return fl(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 Hc(`{{${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.defines.set(n,a),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))throw new Hc(`redefinition of template ${JSON.stringify(n)}`,i.pos,{source:this.source});this.defines.set(n,i)}parseQuotedName(){let e=this.next();if(e.type!==`String`)throw this.errAt(e,`expected template name (quoted string)`,{expected:`string`,found:ml(e)});return Sl(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(!hl(e.type))throw this.errAt(e,"missing command after `|`",{expected:`command`,found:ml(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=[gl(this.next())];for(;this.peek().type===`Comma`;)this.next(),n.push(gl(this.expect(`Variable`,`$variable`)));return{vars:n,isAssign:this.next().type===`Assign`}}parseCommand(){let e=this.peek().pos,t=[this.parsePrimary()];for(;hl(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 gl(e);case`Identifier`:return{type:`Identifier`,pos:e.pos,ident:e.value};case`String`:return{type:`String`,pos:e.pos,raw:e.value,value:Sl(e.value,e.pos,this.source)};case`Number`:return vl(e);case`Char`:return yl(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 ${ml(e)}`,{expected:`command argument`,found:ml(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 fl(e,t){return{type:`List`,pos:e,nodes:t}}function pl(e){return{trimLeft:e.trimLeft===!0,trimRight:e.trimRight===!0}}function ml(e){return e.type===`EOF`?`end of input`:e.value||e.type}function hl(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 gl(e){return{type:`Variable`,pos:e.pos,idents:_l(e.value)}}function _l(e){let t=e.indexOf(`.`);return t===-1?[e]:[e.slice(0,t),...e.slice(t+1).split(`.`)]}function vl(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=bl(i);return{...s,intValue:e}}if(a){let e=xl(i);return{...s,floatValue:e}}let c=xl(i);return{...s,complexValue:[0,c]}}function yl(e,t){let n=Cl(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 bl(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 xl(e){return Number(e)}function Sl(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+=`
92
+ `;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 Hc(`bad escape sequence \\${o}`,t,{expected:`valid escape sequence`,found:`\\${o}`,source:n})}}return r}function Cl(e,t,n){let r=Sl(`"${e.slice(1,-1).replace(/"/g,`\\"`)}"`,t,n);if(r.length===0)throw new Hc(`empty rune literal`,t,{source:n});return r.codePointAt(0)??0}function wl(e,t){if(t(e)!==!1)for(let n of Tl(e))wl(n,t)}function Tl(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 Zc(e)}}const El=Symbol(`go-template-js.MISSING`);function Dl(e,t){if(e==null)return El;if(e instanceof Map)return e.has(t)?e.get(t):El;if(Array.isArray(e))return El;if(typeof e==`object`){let n=e;return t in n?n[t]:El}return El}function Ol(e,t){let n=e;for(let e of t){if(n===El)return El;n=Dl(n,e)}return n}function kl(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)=>kl(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)||!kl(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=>kl(e[n],t[n])):!1}return!1}const Al=new WeakSet;function jl(e){return Al.add(e),e}function Ml(e){return Al.has(e)}function Nl(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 Pl(e){return{eq:{fn:(e,...t)=>t.some(t=>Ll(e,t)),argTypes:[`comparable`]},ne:{fn:(e,t)=>!Ll(e,t),argTypes:[`comparable`,`comparable`]},lt:{fn:(e,t)=>Rl(e,t)<0,argTypes:[`ordered`,`ordered`]},le:{fn:(e,t)=>Rl(e,t)<=0,argTypes:[`ordered`,`ordered`]},gt:{fn:(e,t)=>Rl(e,t)>0,argTypes:[`ordered`,`ordered`]},ge:{fn:(e,t)=>Rl(e,t)>=0,argTypes:[`ordered`,`ordered`]},len:{fn:e=>zl(e),argTypes:[`sized`]},index:{fn:(e,...t)=>{let n=e;for(let e of t)n=Bl(n,e);return n},argTypes:[`collection`,`index-key`]},slice:{fn:(e,...t)=>{let n=t.length>=1?t[0]:0,r=t.length>=2?t[1]:void 0;return e.slice(n,r)},argTypes:[`sliceable`,`int`]},print:{fn:(...t)=>Ul(t,e),argTypes:[`stringifiable`],returnType:`string`},println:{fn:(...t)=>`${Ul(t,e)}\n`,argTypes:[`stringifiable`],returnType:`string`},printf:{fn:(t,...n)=>Ql(t,n,e),argTypes:[`string`,`stringifiable`],returnType:`string`},call:{fn:(e,...t)=>e(...t),argTypes:[`callable`,`value`]},html:{fn:(...t)=>Kl(Ul(t,e)),argTypes:[`stringifiable`],returnType:`string`},js:{fn:(...t)=>Yl(Ul(t,e)),argTypes:[`stringifiable`],returnType:`string`},urlquery:{fn:(...t)=>Zl(Ul(t,e)),argTypes:[`stringifiable`],returnType:`string`},not:{fn:e=>!Nl(e),argTypes:[`truthy`]}}}function Fl(){return{and:jl({argTypes:[`truthy`],fn:(...e)=>{let t=!0;for(let n of e)if(t=n(),!Nl(t))return t;return t}}),or:jl({argTypes:[`truthy`],fn:(...e)=>{let t=!1;for(let n of e)if(t=n(),Nl(t))return t;return t}})}}function Il(e){return{...Pl(e),...Fl()}}function Ll(e,t){return typeof e==`number`&&typeof t==`bigint`?BigInt(e)===t:typeof e==`bigint`&&typeof t==`number`?e===BigInt(t):kl(e,t)}function Rl(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 zl(e){return typeof e==`string`||Array.isArray(e)?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Bl(e,t){if(Array.isArray(e)){let n=Number(t);if(!Number.isInteger(n))throw Error(`index: array index must be integer, got ${Vl(t)}`);if(n<0||n>=e.length)throw Error(`index: out of range [${n}] with length ${e.length}`);return e[n]}if(e instanceof Map)return e.get(t);if(typeof e==`string`)return e[Number(t)];if(typeof e==`object`&&e){if(typeof t!=`string`)throw Error(`index: object index must be string, got ${Vl(t)}`);return e[t]}throw Error(`index: cannot index ${Vl(e)}`)}function Vl(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Hl(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 Ul(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+=Wl(a,t),r=o}return n}function Wl(e,t){return e==null?`<nil>`:typeof e==`string`?e:t(e)}const Gl={"\0":`�`,'"':`&#34;`,"'":`&#39;`,"&":`&amp;`,"<":`&lt;`,">":`&gt;`};function Kl(e){return e.replace(/[\0"'&<>]/g,e=>Gl[e]??e)}const ql={"\\":`\\\\`,"'":`\\'`,'"':`\\"`,"<":`\\u003C`,">":`\\u003E`,"&":`\\u0026`,"=":`\\u003D`},Jl=/^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;function Yl(e){let t=``;for(let n of e){let e=ql[n];if(e!==void 0){t+=e;continue}let r=n.codePointAt(0);if(r<32||r>=128&&!Jl.test(n)){t+=`\\u${r.toString(16).toUpperCase().padStart(4,`0`)}`;continue}t+=n}return t}const Xl=new TextEncoder;function Zl(e){let t=``,n=Xl.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 Ql(e,t,n){let r=``,i=0,a=0;for(;a<e.length;){let o=e[a];if(o!==`%`){r+=o,a+=1;continue}if(e[a+1]===`%`){r+=`%`,a+=2;continue}let s=a+1;for(;s<e.length&&`+-# 0`.includes(e[s]??``);)s+=1;for(;s<e.length&&e[s]!==void 0&&/[0-9]/.test(e[s]);)s+=1;if(e[s]===`.`)for(s+=1;s<e.length&&e[s]!==void 0&&/[0-9]/.test(e[s]);)s+=1;let c=e[s],l=e.slice(a+1,s),u=t[i++];r+=$l(c??``,l,u,n),a=s+1}return r}function $l(e,t,n,r){switch(e){case`s`:return typeof n==`string`?eu(t,n):eu(t,Wl(n,r));case`d`:return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Hl(n)}=${Wl(n,r)})`:eu(t,String(typeof n==`bigint`?n:Math.trunc(n)));case`v`:return eu(t,tu(n));case`q`:return eu(t,JSON.stringify(Wl(n,r)));case`f`:{if(typeof n!=`number`&&typeof n!=`bigint`)return`%!${e}(${Hl(n)}=${Wl(n,r)})`;let i=t.includes(`.`)?Number(t.split(`.`)[1]):6;return eu(t,Number(n).toFixed(i))}case`t`:return eu(t,Nl(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 eu(t,r)}return typeof n!=`number`&&typeof n!=`bigint`?`%!${e}(${Hl(n)}=${Wl(n,r)})`:typeof n==`bigint`?eu(t,n.toString(16)):eu(t,Math.trunc(n).toString(16));default:return`%!${e}(${Hl(n)}=${Wl(n,r)})`}}function eu(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 tu(e){return e==null?`<nil>`:typeof e==`string`?e:typeof e==`bigint`?e.toString():Array.isArray(e)?`[${e.map(tu).join(` `)}]`:e instanceof Map?`map[${[...e.entries()].map(([e,t])=>`${tu(e)}:${tu(t)}`).join(` `)}]`:typeof e==`object`?`{${Object.values(e).map(tu).join(` `)}}`:String(e)}function nu(e){return{dot:e,root:e,parent:void 0,vars:new Map}}function ru(e,t){return{dot:t,root:e.root,parent:e,vars:new Map}}function iu(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 au(e,t,n){e.vars.set(t,n)}const ou=new Set([`default`,`zero`,`error`]);function su(e){if(e===void 0)return`default`;if(ou.has(e))return e;throw Error(`EngineConfig.missingKey: expected "default" | "zero" | "error", got ${cu(e)}`)}function cu(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 lu(e){if(e!==void 0){if(typeof e!=`object`||!e)throw Error(`EngineConfig.delims: expected { left, right } object, got ${cu(e)}`);if(typeof e.left!=`string`||e.left.length===0)throw Error(`EngineConfig.delims.left: expected non-empty string, got ${cu(e.left)}`);if(typeof e.right!=`string`||e.right.length===0)throw Error(`EngineConfig.delims.right: expected non-empty string, got ${cu(e.right)}`);return{left:e.left,right:e.right}}}const uu=Object.freeze({kind:`break`}),du=Object.freeze({kind:`continue`}),fu={kind:`none`};let pu;(class e{source;_evaluate;_referencedFunctions;_referencedCalls;constructor(e,t,n,r){this.source=e,this._evaluate=t,this._referencedFunctions=n,this._referencedCalls=r}static{pu=(t,n,r,i)=>new e(t,n,r,i)}evaluate(e){return this._evaluate(e)}referencedFunctions(){return this._referencedFunctions}referencedCalls(){return this._referencedCalls}});function mu(e){let t=new Set,n=e=>{wl(e,e=>{e.type===`Identifier`&&t.add(e.ident)})};n(e.root);for(let t of e.defines.values())n(t);return t}function hu(e){let t=[],n=e=>{wl(e,e=>{if(e.type!==`Command`)return;let n=e.args[0];n===void 0||n.type!==`Identifier`||t.push({name:n.ident,args:e.args.slice(1).map(e=>e.type===`String`?e.value:null)})})};n(e.root);for(let t of e.defines.values())n(t);return t}var gu=class{fromString;toString;funcs;missingKey;delims;constructor(e){this.fromString=e.fromString;let t=Object.hasOwn(e,`toString`)?e.toString:void 0;this.toString=t??Tu,this.missingKey=su(e.missingKey),this.delims=lu(e.delims),this.funcs={...Il(this.toString),...e.funcs??{}}}parse(e){let t=ul(e,this.delims);return pu(t.source,e=>this.evalParsed(t,e),mu(t),hu(t))}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=nu(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 uu;case`Continue`:throw du;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 Uc(`unexpected ${e.type} at statement position`,e.pos,{source:n.source});default:Zc(e)}}evalIf(e,t,n){Nl(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(Nl(r)){let i=ru(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=Nu(r);try{if(a.length===0){e.elseList&&this.evalList(e.elseList,t,n);return}for(let[r,o]of a){let a=ru(t,o);if(i.length===1)au(a,i[0]?.idents[0]??`$`,o);else if(i.length>=2){let e=i[0]?.idents[0]??`$`,t=i[1]?.idents[0]??`$`;au(a,e,r),au(a,t,o)}try{this.evalList(e.list,a,n)}catch(e){if(e===du)continue;throw e}}}catch(e){if(e===uu)return;throw e}}evalTemplateInvoke(e,t,n){let r=n.defines.get(e.name);if(!r)throw new Uc(`template ${JSON.stringify(e.name)} is not defined`,e.pos,{source:n.source});let i=ru(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot);this.evalList(r,i,n)}evalBlock(e,t,n){let r=ru(t,e.pipe?this.evalPipe(e.pipe,t,n):t.dot),i=n.defines.get(e.name)??e.list;this.evalList(i,r,n)}evalAction(e,t,n){return this.evalPipe(e.pipe,t,n)}evalPipe(e,t,n){if(e.cmds.length===0)throw new Uc(`empty pipeline`,e.pos,{source:n.source});let r=this.evalCommand(e.cmds[0],t,n,fu);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)au(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 Uc(`empty command`,e.pos,{source:n.source});let i=e.args[0];if(i.type!==`Identifier`){if(e.args.length>1)throw new Uc(`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 Wc(i.ident,i.pos,{source:n.source,available:Object.keys(this.funcs)});let o=e.args.slice(1),s=Ml(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)}xu(i.ident,a.argTypes,c,e.pos,n.source,this.toString,a.argTypePattern,this.fromString);try{return a.fn(...c)}catch(t){throw t instanceof Gc?new Gc(t.funcName,t.argIndex,t.expected,t.receivedSummary,e.pos,{source:n.source}):t instanceof qc?new qc(t.message,e.pos,{source:n.source}):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 Iu(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 Wc(e.ident,e.pos,{source:n.source,available:Object.keys(this.funcs)});return xu(e.ident,t.argTypes,[],e.pos,n.source,this.toString,t.argTypePattern,this.fromString),t.fn()}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 Uc(`cannot evaluate ${e.type} as a value`,e.pos,{source:n.source})}}resolveFieldChain(e,t,n,r){let i=Ol(e,t);if(i!==El)return i;if(this.missingKey===`error`)throw new Kc(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=iu(t,i);if(!a.found)throw new Uc(`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(Array.isArray(e)){t.out.push(this.fromString(_u(e)));return}if(e instanceof Map){t.out.push(this.fromString(vu(e)));return}t.out.push(e)}};function _u(e){return`[${e.map(yu).join(` `)}]`}function vu(e){let t=[];for(let[n,r]of e)t.push(`${yu(n)}:${yu(r)}`);return`map[${t.join(` `)}]`}function yu(e){return e==null?`<nil>`:Array.isArray(e)?_u(e):e instanceof Map?vu(e):String(e)}function bu(e){return new gu(e)}function xu(e,t,n,r,i,a=Tu,o,s=wu){let c=Su(t,o),l=-1,u=-1;for(let t=0;t<n.length;t++){let o=c(t),d=n[t];if(!Cu(o,d,a))throw new Gc(e,t+1,ju(o),Mu(d),r,{source:i});if(o===`liftable`&&typeof d==`string`&&(n[t]=s(d)),o===`int`?n[t]=Math.trunc(Number(d)):o===`float`&&(n[t]=Number(d)),o===`ordered`){if(l===-1)l=t;else if(!Ou(n[l],d))throw new Gc(e,t+1,`${ju(`ordered`)} of the same kind as ${Mu(n[l])}`,Mu(d),r,{source:i})}if(o===`comparable`){if(u===-1)u=t;else if(!ku(n[u],d))throw new Gc(e,t+1,`${ju(`comparable`)} of the same kind as ${Mu(n[u])}`,Mu(d),r,{source:i})}}}function Su(e,t){if(e.length===0)return()=>`value`;if(t===`alternating`){let t=e.length;return n=>e[n%t]}let n=e[e.length-1];return t=>t<e.length?e[t]:n}function Cu(e,t,n){switch(e){case`truthy`:case`reflective`:case`value`:return!0;case`string`:return typeof t==`string`;case`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 t!=null&&typeof t!=`string`&&typeof t!=`number`&&typeof t!=`boolean`&&typeof t!=`bigint`&&typeof t!=`symbol`;case`list`:return Array.isArray(t);case`dict`:return Eu(t);case`sized`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||t instanceof Set||Eu(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||Eu(t);case`callable`:return typeof t==`function`;case`collection`:return typeof t==`string`||Array.isArray(t)||t instanceof Map||Eu(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`||t!=null&&typeof t!=`number`&&typeof t!=`boolean`&&typeof t!=`bigint`&&typeof t!=`symbol`;case`serializable`:return Du(t);default:throw Error(`invalid ArgType: ${String(e)}`)}}function wu(e){return e}function Tu(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 Gc(`<engine.toString>`,1,`string (or a consumer-supplied toString that flattens T)`,Mu(e),{line:0,column:0,offset:0})}function Eu(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 Du(e){try{return JSON.stringify(e)!==void 0}catch{return!1}}function Ou(e,t){return typeof e==typeof t||typeof e==`number`&&typeof t==`bigint`||typeof e==`bigint`&&typeof t==`number`}function ku(e,t){let n=Au(e),r=Au(t);return n===`nil`||r===`nil`?!0:n===r}function Au(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 ju(e){switch(e){case`int`:return`integer (finite number 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 Mu(e){return e===null?`null`:e===void 0?`undefined`:Array.isArray(e)?`array`:e instanceof Map?`Map`:typeof e}function Nu(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?Pu([...e.entries()]):e instanceof Set?[...e.values()].map((e,t)=>[t,e]):typeof e==`object`?Pu(Object.entries(e)):[]}function Pu(e){return[...e].sort((e,t)=>Fu(e[0],t[0]))}function Fu(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 Iu(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 Lu(e){if(!/^[+-]?\d+$/.test(e))return 0;let t=Number.parseInt(e,10);return Number.isSafeInteger(t)?t:0}function Ru(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 zu(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 Bu(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=zu(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 Vu(e){if(typeof e==`bigint`)return e;if(typeof e==`number`)return BigInt(Math.trunc(e));if(typeof e==`string`){let t=zu(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 Hu(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 Uu(e){return JSON.stringify(e)??`null`}function Wu(e){return typeof e==`string`?e:tu(e)}function Gu(e){return e.map(Wu)}function Ku(){return{atoi:{fn:e=>Lu(e),argTypes:[`string`],returnType:`int`},int:{fn:e=>Bu(e),argTypes:[`value`],returnType:`int`},int64:{fn:e=>Vu(e),argTypes:[`value`]},float64:{fn:e=>Ru(e),argTypes:[`value`],returnType:`float`},toString:{fn:e=>Wu(e),argTypes:[`value`],returnType:`string`},toStrings:{fn:e=>Gu(e),argTypes:[`list`]},toDecimal:{fn:e=>Hu(e),argTypes:[`string`],returnType:`int`},toRawJson:{fn:e=>Uu(e),argTypes:[`serializable`],returnType:`string`}}}const qu={h:36e11,m:6e10,s:1e9,ms:1e6,us:1e3,µs:1e3,ns:1};function Ju(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*qu[a],n=n.slice(e[0].length)}return t?-r:r}function Yu(e){if(e===0)return`0s`;let t=!1,n=e;n<0&&(t=!0,n=-n);let r;return r=n<qu.us?`${Math.floor(n)}ns`:n<qu.ms?Xu(n,qu.us,3,`µs`):n<qu.s?Xu(n,qu.ms,6,`ms`):Zu(n),t?`-${r}`:r}function Xu(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 Zu(e){let t=Math.floor(e/qu.h);e-=t*qu.h;let n=Math.floor(e/qu.m);e-=n*qu.m;let r=Math.floor(e/qu.s),i=e-r*qu.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 Qu(e){return e*qu.s}function $u(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 ed(e,t){let n=t().getTime()-$u(e).getTime();return Yu(Math.round(n/1e3)*1e9)}const td=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],nd=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],rd=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],id=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function ad(e){return e<10?`0${e}`:String(e)}function od(e){return e<10?`00${e}`:e<100?`0${e}`:String(e)}function sd(e){return e<10?` ${e}`:String(e)}function cd(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${ad(Math.floor(n/60))}${ad(n%60)}`}function ld(e){let t=e>=0?`+`:`-`,n=Math.abs(e);return`${t}${ad(Math.floor(n/60))}:${ad(n%60)}`}function ud(e){return`${e>=0?`+`:`-`}${ad(Math.floor(Math.abs(e)/60))}`}function dd(e){return e===0?`Z`:cd(e)}function fd(e){return e===0?`Z`:ld(e)}function pd(e){return e===0?`Z`:ud(e)}function md(e,t,n){let r=e*1e6,i=String(r).padStart(9,`0`).slice(0,t);return n?i.replace(/0+$/,``):i}const hd=[[`.000000000`,e=>`.${md(e.ms,9,!1)}`],[`.999999999`,e=>{let t=md(e.ms,9,!0);return t?`.${t}`:``}],[`.000000`,e=>`.${md(e.ms,6,!1)}`],[`.999999`,e=>{let t=md(e.ms,6,!0);return t?`.${t}`:``}],[`.000`,e=>`.${od(e.ms)}`],[`.999`,e=>{let t=od(e.ms).replace(/0+$/,``);return t?`.${t}`:``}],[`January`,e=>td[e.month-1]??`January`],[`Monday`,e=>rd[e.weekday]??`Monday`],[`Z07:00`,e=>fd(e.offsetMinutes)],[`-07:00`,e=>ld(e.offsetMinutes)],[`Z0700`,e=>dd(e.offsetMinutes)],[`-0700`,e=>cd(e.offsetMinutes)],[`2006`,e=>String(e.year)],[`Jan`,e=>nd[e.month-1]??`Jan`],[`Mon`,e=>id[e.weekday]??`Mon`],[`MST`,e=>e.tzAbbr],[`-07`,e=>ud(e.offsetMinutes)],[`Z07`,e=>pd(e.offsetMinutes)],[`15`,e=>ad(e.hour)],[`01`,e=>ad(e.month)],[`02`,e=>ad(e.day)],[`_2`,e=>sd(e.day)],[`03`,e=>ad(e.hour12)],[`04`,e=>ad(e.minute)],[`05`,e=>ad(e.second)],[`06`,e=>ad(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 gd(e,t){let n=``,r=0;for(;r<e.length;){let i=!1;for(let[a,o]of hd)if(e.startsWith(a,r)){n+=o(t),r+=a.length,i=!0;break}i||(n+=e[r++])}return n}const _d={year:`numeric`,month:`2-digit`,day:`2-digit`,weekday:`long`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1};function vd(e){let t=new Map;for(let n of e)t.set(n.type,n.value);return t}const yd=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`];function bd(e,t){let n;try{new Intl.DateTimeFormat(`en-US`,{timeZone:t}),n=t}catch{n=`UTC`}let r=vd(new Intl.DateTimeFormat(`en-US`,{..._d,timeZone:n}).formatToParts(e)),i=parseInt(r.get(`hour`)??`0`,10)%24,a=vd(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`short`}).formatToParts(e)).get(`timeZoneName`)??n,o=xd(vd(new Intl.DateTimeFormat(`en-US`,{timeZone:n,timeZoneName:`shortOffset`}).formatToParts(e)).get(`timeZoneName`)??`GMT`),s=yd.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 xd(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 Sd(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function Cd(e,t){return gd(e,bd($u(t),Sd()))}function wd(e,t,n){return gd(e,bd($u(t),n))}function Td(e,t){let n=$u(t),r=Ju(e);return Number.isNaN(r)?n:new Date(n.getTime()+r/1e6)}function Ed(e){if(typeof e==`string`){let t=parseInt(e,10);return Number.isNaN(t)?`0s`:Yu(Qu(t))}return typeof e==`bigint`?Yu(Qu(Number(e))):typeof e==`number`?Yu(Qu(e)):`0s`}const Dd=36e11*24*365,Od=36e11*24*30,kd=36e11*24,Ad=36e11,jd=6e10,Md=1e9;function Nd(e){let t=Ju(String(e));if(Number.isNaN(t))return`0s`;let n=Math.abs(t);return n>Dd?`${Math.floor(n/Dd)}y`:n>Od?`${Math.floor(n/Od)}mo`:n>kd?`${Math.floor(n/kd)}d`:n>Ad?`${Math.floor(n/Ad)}h`:n>jd?`${Math.floor(n/jd)}m`:n>Md?`${Math.floor(n/Md)}s`:`0s`}function Pd(e){let t=bd($u(e),Sd());return`${t.year}-${String(t.month).padStart(2,`0`)}-${String(t.day).padStart(2,`0`)}`}function Fd(e,t){let n=bd($u(e),t);return`${n.year}-${String(n.month).padStart(2,`0`)}-${String(n.day).padStart(2,`0`)}`}function Id(e){return e()}const Ld=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Rd=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function zd(){return{year:2e3,month:1,day:1,hour:0,minute:0,second:0,ms:0,offsetMinutes:0,isPM:!1,hour12:!1}}function Bd(e,t,n){return[e.slice(t,t+n),t+n]}function Vd(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 Hd(e,t){for(let[n,r]of Ld.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected month name at pos ${t}`)}function Ud(e,t){for(let[n,r]of Rd.entries())if(e.startsWith(r,t))return[n+1,t+r.length];throw Error(`sprig toDate: expected short month name at pos ${t}`)}function Wd(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 Gd(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 Kd(e,t){if(e[t]===` `){let[n,r]=Vd(e,t+1,1,1);return[n,r]}return Vd(e,t,1,2)}function qd(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]=Vd(e,i,2,2);i=o;let s=0;if(n&&e[i]===`:`){let[t,n]=Vd(e,i+1,2,2);s=t,i=n}else if(!n){let[t,n]=Vd(e,i,2,2);s=t,i=n}return[r*(a*60+s),i]}function Jd(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]=Vd(e,t+1,2,2);return[n*r*60,i]}return qd(e,t,n)}function Yd(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 Xd(e,t,n){let[r,i]=Bd(e,t,n),a=parseInt(r.padEnd(9,`0`),10);return[Math.round(a/1e6),i]}function Zd(e,t,n,r){let i={...r};switch(e){case`January`:{let[e,r]=Hd(t,n);return i.month=e,[r,i]}case`Monday`:return[Wd(t,n),i];case`Jan`:{let[e,r]=Ud(t,n);return i.month=e,[r,i]}case`Mon`:return[Gd(t,n),i];case`2006`:{let[e,r]=Vd(t,n,4,4);return i.year=e,[r,i]}case`06`:{let[e,r]=Vd(t,n,2,2);return i.year=e<70?2e3+e:1900+e,[r,i]}case`01`:{let[e,r]=Vd(t,n,2,2);return i.month=e,[r,i]}case`1`:{let[e,r]=Vd(t,n,1,2);return i.month=e,[r,i]}case`_2`:{let[e,r]=Kd(t,n);return i.day=e,[r,i]}case`02`:{let[e,r]=Vd(t,n,2,2);return i.day=e,[r,i]}case`2`:{let[e,r]=Vd(t,n,1,2);return i.day=e,[r,i]}case`15`:{let[e,r]=Vd(t,n,2,2);return i.hour=e,[r,i]}case`03`:{let[e,r]=Vd(t,n,2,2);return i.hour=e,i.hour12=!0,[r,i]}case`3`:{let[e,r]=Vd(t,n,1,2);return i.hour=e,i.hour12=!0,[r,i]}case`04`:{let[e,r]=Vd(t,n,2,2);return i.minute=e,[r,i]}case`4`:{let[e,r]=Vd(t,n,1,2);return i.minute=e,[r,i]}case`05`:{let[e,r]=Vd(t,n,2,2);return i.second=e,[r,i]}case`5`:{let[e,r]=Vd(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[Yd(t,n),i];case`-0700`:{let[e,r]=qd(t,n,!1);return i.offsetMinutes=e,[r,i]}case`-07:00`:{let[e,r]=qd(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]=Vd(t,n+1,2,2);return i.offsetMinutes=e*r*60,[a,i]}case`Z0700`:{let[e,r]=Jd(t,n,!1,!1);return i.offsetMinutes=e,[r,i]}case`Z07:00`:{let[e,r]=Jd(t,n,!0,!1);return i.offsetMinutes=e,[r,i]}case`Z07`:{let[e,r]=Jd(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]=Xd(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]=Xd(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]=Xd(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 Qd=`.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 $d(e,t){let n=0,r=0,i=zd();for(;n<e.length;){let a=!1;for(let o of Qd)if(e.startsWith(o,n)){let[e,s]=Zd(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 ef(e,t){return $d(e,t)}function tf(e){return String(Math.floor($u(e).getTime()/1e3))}function nf(e=()=>new Date){return{now:{fn:()=>Id(e),argTypes:[]},date:{fn:(e,t)=>Cd(e,t),argTypes:[`string`,`value`]},dateInZone:{fn:(e,t,n)=>wd(e,t,n),argTypes:[`string`,`value`,`string`]},dateModify:{fn:(e,t)=>Td(e,t),argTypes:[`string`,`value`]},htmlDate:{fn:e=>Pd(e),argTypes:[`value`]},htmlDateInZone:{fn:(e,t)=>Fd(e,t),argTypes:[`value`,`string`]},duration:{fn:e=>Ed(e),argTypes:[`value`]},durationRound:{fn:e=>Nd(e),argTypes:[`value`]},toDate:{fn:(e,t)=>ef(e,t),argTypes:[`string`,`string`]},ago:{fn:t=>ed(t,e),argTypes:[`value`]},unixEpoch:{fn:e=>tf(e),argTypes:[`value`]}}}function rf(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 af(...e){for(let t of e)if(!rf(t))return t}function of(e,t){return rf(t)?e:t}function sf(e){return JSON.parse(e)}function cf(e,t,n){return Nl(n)?e:t}function lf(e){return JSON.stringify(e)??`null`}function uf(e){return JSON.stringify(e,null,2)??`null`}function df(){return{default:{fn:(e,t)=>of(e,t),argTypes:[`value`,`truthy`]},empty:{fn:e=>rf(e),argTypes:[`truthy`]},coalesce:{fn:(...e)=>af(...e),argTypes:[`truthy`]},ternary:{fn:(e,t,n)=>cf(e,t,n),argTypes:[`value`,`value`,`truthy`]},fromJson:{fn:e=>sf(e),argTypes:[`string`]},toJson:{fn:e=>lf(e),argTypes:[`serializable`],returnType:`string`},toPrettyJson:{fn:e=>uf(e),argTypes:[`serializable`],returnType:`string`}}}function ff(...e){let t={};for(let n=0;n<e.length;n+=2)t[e[n]]=e[n+1];return t}function pf(e,t){return e[t]}function mf(e,t){return t in e}function hf(e){return Object.keys(e)}function gf(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 _f(e,...t){let n={...e};for(let e of t)Object.assign(n,e);return n}function vf(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 yf(e,...t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function bf(e,...t){let n=[];for(let r of t)e in r&&n.push(r[e]);return n}function xf(e,t,n){return e[t]=n,e}function Sf(e,t){return delete e[t],e}function Cf(e){return Object.values(e)}function wf(){return{dict:{fn:(...e)=>ff(...e),argTypes:[`string`,`value`],argTypePattern:`alternating`},get:{fn:(e,t)=>pf(e,t),argTypes:[`dict`,`string`]},set:{fn:(e,t,n)=>xf(e,t,n),argTypes:[`dict`,`string`,`value`]},unset:{fn:(e,t)=>Sf(e,t),argTypes:[`dict`,`string`]},keys:{fn:e=>hf(e),argTypes:[`dict`]},values:{fn:e=>Cf(e),argTypes:[`dict`]},pluck:{fn:(e,...t)=>bf(e,...t),argTypes:[`string`,`dict`]},pick:{fn:(e,...t)=>yf(e,...t),argTypes:[`dict`,`string`]},omit:{fn:(e,...t)=>vf(e,...t),argTypes:[`dict`,`string`]},hasKey:{fn:(e,t)=>mf(e,t),argTypes:[`dict`,`string`]},merge:{fn:(e,...t)=>gf(e,...t),argTypes:[`dict`]},mergeOverwrite:{fn:(e,...t)=>_f(e,...t),argTypes:[`dict`]}}}new TextEncoder,new Map(Array.from(`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`).map((e,t)=>[e,t])),new TextDecoder,new TextEncoder,new TextDecoder,new TextEncoder;function Tf(...e){for(let t of e)if(rf(t))return!1;return!0}function Ef(...e){for(let t of e)if(!rf(t))return!0;return!1}function Df(e,t){return[...e,t]}function Of(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 kf(e){return e.filter(e=>!rf(e))}function Af(...e){let t=[];for(let n of e)t.push(...n);return t}const jf={line:0,column:0,offset:0};function Mf(e,t,n,r){return new Gc(e,t,n,r,jf)}function Nf(...e){if(e.length<3)throw Mf(`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(!Ff(t))throw Mf(`dig`,e.length-1,`dict`,If(t));for(let e=0;e<r.length;e++)if(typeof r[e]!=`string`)throw Mf(`dig`,e,`string`,If(r[e]));return Pf(t,n,r,e.length)}function Pf(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(!Ff(a))throw Mf(`dig`,r-1,`dict at intermediate key`,If(a));return Pf(a,t,n.slice(1),r)}function Ff(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)&&!(e instanceof Set)}function If(e){return e===null?`null`:Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:typeof e}function Lf(e){return e[0]}function Rf(e,t){return t.some(t=>kl(t,e))}function zf(e){return e.slice(0,-1)}function Bf(e){return e[e.length-1]}function Vf(e){return Array.isArray(e)||typeof e==`string`?e.length:e instanceof Map||e instanceof Set?e.size:Object.keys(e).length}function Hf(...e){return e}function Uf(e,t){return[t,...e]}function Wf(e){return e.slice(1)}function Gf(e){return[...e].reverse()}function Kf(e,t,n){let r=t===void 0?0:t,i=n===void 0?e.length:n;return e.slice(r,i)}function qf(e){let t=[];for(let n of e)n!=null&&t.push(String(n));return t.sort()}function Jf(e){let t=[];for(let n of e)t.some(e=>kl(e,n))||t.push(n);return t}function Yf(e,...t){return e.filter(e=>!t.some(t=>kl(t,e)))}function Xf(){return{list:{fn:(...e)=>Hf(...e),argTypes:[`value`]},first:{fn:e=>Lf(e),argTypes:[`list`]},last:{fn:e=>Bf(e),argTypes:[`list`]},rest:{fn:e=>Wf(e),argTypes:[`list`]},initial:{fn:e=>zf(e),argTypes:[`list`]},len:{fn:e=>Vf(e),argTypes:[`sized`]},reverse:{fn:e=>Gf(e),argTypes:[`list`]},uniq:{fn:e=>Jf(e),argTypes:[`list`]},without:{fn:(e,...t)=>Yf(e,...t),argTypes:[`list`,`value`]},has:{fn:(e,t)=>Rf(e,t),argTypes:[`value`,`list`]},compact:{fn:e=>kf(e),argTypes:[`list`]},slice:{fn:(e,t,n)=>Kf(e,t,n),argTypes:[`list`,`int`,`int`]},concat:{fn:(...e)=>Af(...e),argTypes:[`list`]},chunk:{fn:(e,t)=>Of(e,t),argTypes:[`int`,`list`]},prepend:{fn:(e,t)=>Uf(e,t),argTypes:[`list`,`value`]},append:{fn:(e,t)=>Df(e,t),argTypes:[`list`,`value`]},sortAlpha:{fn:e=>qf(e),argTypes:[`list`],returnType:`list`},push:{fn:(e,t)=>Df(e,t),argTypes:[`list`,`value`]},tuple:{fn:(...e)=>Hf(...e),argTypes:[`value`]},dig:{fn:(...e)=>Nf(...e),argTypes:[`value`]},all:{fn:(...e)=>Tf(...e),argTypes:[`truthy`],returnType:`bool`},any:{fn:(...e)=>Ef(...e),argTypes:[`truthy`],returnType:`bool`}}}function Zf(...e){return e.reduce((e,t)=>e+t,0)}function Qf(e){return e+1}function $f(e){return e+1}function ep(...e){return e.reduce((e,t)=>e+t,0)}function tp(e){return Math.ceil(e)}function np(e,t){return Math.trunc(e/t)}function rp(e,t){return e/t}function ip(e){return Math.floor(e)}function ap(...e){return e.reduce((e,t)=>t>e?t:e,-1/0)}function op(...e){return e.reduce((e,t)=>Math.max(e,t),-1/0)}function sp(...e){return e.reduce((e,t)=>t<e?t:e,1/0)}function cp(...e){return e.reduce((e,t)=>Math.min(e,t),1/0)}function lp(e,t){return e%t}function up(...e){return e.reduce((e,t)=>e*t,1)}function dp(...e){return e.reduce((e,t)=>e*t,1)}function fp(e,t=0){let n=10**t;return Math.sign(e)*Math.round(Math.abs(e)*n)/n}function pp(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 mp(...e){let t=1;switch(e.length){case 0:return``;case 1:{let n=e[0];return n<1&&(t=-1),pp(1,n+t,t).join(` `)}case 2:{let t=e[0],n=e[1],r=n<t?-1:1;return pp(t,n+r,r).join(` `)}case 3:{let n=e[0],r=e[1],i=e[2];return i<n&&(t=-1,r>0)?``:pp(n,i+t,r).join(` `)}default:return``}}function hp(e,t){return e-t}function gp(e,t){return e-t}function _p(e){return pp(0,e,e<0?-1:1)}function vp(){return{add:{fn:(...e)=>Zf(...e),argTypes:[`int`]},sub:{fn:(e,t)=>hp(e,t),argTypes:[`int`,`int`]},mul:{fn:(...e)=>up(...e),argTypes:[`int`]},div:{fn:(e,t)=>np(e,t),argTypes:[`int`,`int`]},mod:{fn:(e,t)=>lp(e,t),argTypes:[`int`,`int`]},min:{fn:(...e)=>sp(...e),argTypes:[`int`]},max:{fn:(...e)=>ap(...e),argTypes:[`int`]},floor:{fn:e=>ip(e),argTypes:[`float`]},ceil:{fn:e=>tp(e),argTypes:[`float`]},round:{fn:(e,t)=>fp(e,t),argTypes:[`float`,`int`]},addf:{fn:(...e)=>ep(...e),argTypes:[`float`]},subf:{fn:(e,t)=>gp(e,t),argTypes:[`float`,`float`]},mulf:{fn:(...e)=>dp(...e),argTypes:[`float`]},divf:{fn:(e,t)=>rp(e,t),argTypes:[`float`,`float`]},add1:{fn:e=>Qf(e),argTypes:[`int`]},add1f:{fn:e=>$f(e),argTypes:[`float`]},maxf:{fn:(...e)=>op(...e),argTypes:[`float`]},minf:{fn:(...e)=>cp(...e),argTypes:[`float`]},biggest:{fn:(...e)=>ap(...e),argTypes:[`int`]},seq:{fn:(...e)=>mp(...e),argTypes:[`int`],returnType:`string`},until:{fn:e=>_p(e),argTypes:[`int`],returnType:`list`},untilStep:{fn:(e,t,n)=>pp(e,t,n),argTypes:[`int`,`int`,`int`],returnType:`list`}}}Array.from({length:95},(e,t)=>String.fromCharCode(t+32)).join(``);function yp(e,t){return t.length<=e||e<4?t:`${t.slice(0,e-3)}...`}function bp(e,t,n){return t<7||n.length<t||e<0||e>n.length-t+1?n:`...${n.slice(e,e+t-6)}...`}const $={Invalid:0,Number:1,UpperCase:2,Alphabet:3,Connector:4,Punct:5,Other:6},xp=/^[-_\s]$/,Sp=/^\p{P}$/u,Cp=/^\p{L}$/u,wp=/^\p{Lu}$/u,Tp=/^\p{N}$/u;function Ep(e){return e!==void 0&&xp.test(e)}function Dp(e){return e!==void 0&&Cp.test(e)}function Op(e){return e!==void 0&&wp.test(e)}function kp(e){return e!==void 0&&Tp.test(e)}function Ap(e){return e!==void 0&&Sp.test(e)}function jp(e,t){if(t>=e.length)return{word:{wt:$.Invalid,text:``},next:t};let n=e[t],r=t+1;if(Ep(n)){for(;r<e.length&&Ep(e[r]);)r++;return{word:{wt:$.Connector,text:e.slice(t,r).join(``)},next:r}}if(Ap(n)){for(;r<e.length&&Ap(e[r]);)r++;return{word:{wt:$.Punct,text:e.slice(t,r).join(``)},next:r}}if(Op(n)){if(r>=e.length)return{word:{wt:$.UpperCase,text:n},next:r};if(Op(e[r])){let n=r;for(;n<e.length&&Op(e[n]);)n++;return n<e.length&&Dp(e[n])?{word:{wt:$.UpperCase,text:e.slice(t,n-1).join(``)},next:n-1}:{word:{wt:$.UpperCase,text:e.slice(t,n).join(``)},next:n}}if(Dp(e[r])){let n=r+1;for(;n<e.length&&Dp(e[n])&&!Op(e[n]);)n++;return{word:{wt:$.UpperCase,text:e.slice(t,n).join(``)},next:n}}return{word:{wt:$.UpperCase,text:n},next:r}}if(Dp(n)){for(;r<e.length&&Dp(e[r])&&!Op(e[r]);)r++;return{word:{wt:$.Alphabet,text:e.slice(t,r).join(``)},next:r}}if(kp(n)){for(;r<e.length&&kp(e[r]);)r++;return{word:{wt:$.Number,text:e.slice(t,r).join(``)},next:r}}for(;r<e.length&&!Ep(e[r])&&!Dp(e[r])&&!kp(e[r])&&!Ap(e[r]);)r++;return{word:{wt:$.Other,text:e.slice(t,r).join(``)},next:r}}function Mp(e,t,n){if(t.wt!==$.UpperCase&&t.wt!==$.Connector){e.push(t.text);return}for(let r of t.text)Ep(r)?e.push(n):Op(r)?e.push(r.toLowerCase()):e.push(r)}function Np(e,t){if(e.length===0)return``;let n=Array.from(e),r=[],{word:i,next:a}=jp(n,0);for(;a<n.length;){i.wt!==$.Connector&&Mp(r,i,t);let e=i,o=i;if({word:i,next:a}=jp(n,a),e.wt===$.Number){for(;i.wt===$.Alphabet||i.wt===$.Number;)Mp(r,i,t),{word:i,next:a}=jp(n,a);i.wt!==$.Invalid&&i.wt!==$.Punct&&i.wt!==$.Connector&&r.push(t);continue}if(e.wt===$.Connector){Mp(r,o,t);continue}if(e.wt===$.Punct)continue;if(i.wt!==$.Number){i.wt!==$.Connector&&i.wt!==$.Punct&&r.push(t);continue}if(a>=n.length)continue;let s=i;if({word:i,next:a}=jp(n,a),i.wt!==$.Alphabet){Mp(r,s,t),i.wt!==$.Connector&&i.wt!==$.Punct&&r.push(t);continue}for(r.push(t),Mp(r,s,t);i.wt===$.Alphabet||i.wt===$.Number;)Mp(r,i,t),{word:i,next:a}=jp(n,a);i.wt!==$.Invalid&&i.wt!==$.Connector&&i.wt!==$.Punct&&r.push(t)}return Mp(r,i,t),r.join(``).toLowerCase()}function Pp(e){if(e.length===0)return``;let t=Array.from(e),n=[],r=0,i=``;for(;r<t.length;){if(i=t[r],r++,!Ep(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++,Ep(i)&&Ep(e)){n.push(e);continue}Ep(e)?i=i.toUpperCase():(i=i.toLowerCase(),n.push(e))}return n.push(i),n.join(``)}function Fp(e){return Pp(e)}function Ip(...e){return e.join(` `)}function Lp(e,t){return t.includes(e)}function Rp(e,t){return t.startsWith(e)}function zp(e,t){return t.endsWith(e)}function Bp(e,t){let n=` `.repeat(Math.max(0,e));return t.split(`
90
93
  `).map(e=>n+e).join(`
91
- `)}function Od(e){return e.split(/\s+/).filter(e=>e.length>0).map(e=>(e[0]??``).toUpperCase()).join(``)}function kd(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw yu(`join`,2,`list of strings/primitives`,`list element of type ${Ad(e)}`);n.push(String(e))}return n.join(e)}function Ad(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function jd(e){return bd(e,`-`)}function Md(e){return e.toLowerCase()}function Nd(e,t){return`\n${Dd(e,t)}`}function Pd(e){return e.replace(/\s+/g,``)}function Fd(e,t,n){return n===1?e:t}function Id(...e){return e.map(e=>`"${e}"`).join(` `)}function Ld(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function Rd(e,t){return t.repeat(Math.max(0,e))}function zd(e,t,n){return n.split(e).join(t)}function Bd(e){return bd(e,`_`)}function Vd(e,t){let n=t.split(e),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function Hd(e,t){return t.split(e)}function Ud(e,t,n){let r=Wd(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function Wd(e,t,n){if(n===0)return[];let r=t===``?Array.from(e):e.split(t);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 Gd(...e){return e.map(e=>`'${e}'`).join(` `)}function Kd(e,t,n){let r=t<0||t>n.length?n.length:t,i=Math.min(Math.max(0,e),r);return n.slice(i,r)}function qd(e){let t=``;for(let n of e)Jd(n)?t+=n.toLowerCase():Yd(n)?t+=n.toUpperCase():t+=n;return t}function Jd(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function Yd(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function Xd(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function Zd(e){return e.trim()}function Qd(e,t){if(e.length===0)return t;let n=new Set([...e]),r=0;for(;r<t.length&&n.has(t[r]);)r+=1;let i=t.length;for(;i>r&&n.has(t[i-1]);)--i;return t.slice(r,i)}function $d(e,t){return t.startsWith(e)?t.slice(e.length):t}function ef(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function tf(e,t){if(e<0){let n=-e;return n>=t.length?t:t.slice(t.length-n)}return e>=t.length?t:t.slice(0,e)}function nf(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function rf(e){return e.toUpperCase()}function af(e,t){return of(e,`
92
- `,t)}function of(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
93
- `)){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 sf(e,t,n){return of(e,t,n)}function cf(){return{abbrev:{fn:(e,t)=>od(e,t),argTypes:[`int`,`string`]},abbrevboth:{fn:(e,t,n)=>sd(e,t,n),argTypes:[`int`,`int`,`string`]},camelcase:{fn:e=>Sd(e),argTypes:[`string`],returnType:`string`},cat:{fn:(...e)=>Cd(...e),argTypes:[`string`]},contains:{fn:(e,t)=>wd(e,t),argTypes:[`string`,`string`]},hasPrefix:{fn:(e,t)=>Td(e,t),argTypes:[`string`,`string`]},hasSuffix:{fn:(e,t)=>Ed(e,t),argTypes:[`string`,`string`]},indent:{fn:(e,t)=>Dd(e,t),argTypes:[`int`,`string`]},initials:{fn:e=>Od(e),argTypes:[`string`]},join:{fn:(e,t)=>kd(e,t),argTypes:[`string`,`list`]},kebabcase:{fn:e=>jd(e),argTypes:[`string`],returnType:`string`},lower:{fn:e=>Md(e),argTypes:[`string`]},nindent:{fn:(e,t)=>Nd(e,t),argTypes:[`int`,`string`]},nospace:{fn:e=>Pd(e),argTypes:[`string`],returnType:`string`},plural:{fn:(e,t,n)=>Fd(e,t,n),argTypes:[`string`,`string`,`int`],returnType:`string`},quote:{fn:(...e)=>Id(...e),argTypes:[`string`]},regexQuoteMeta:{fn:e=>Ld(e),argTypes:[`string`],returnType:`string`},repeat:{fn:(e,t)=>Rd(e,t),argTypes:[`int`,`string`]},replace:{fn:(e,t,n)=>zd(e,t,n),argTypes:[`string`,`string`,`string`]},snakecase:{fn:e=>Bd(e),argTypes:[`string`],returnType:`string`},split:{fn:(e,t)=>Vd(e,t),argTypes:[`string`,`string`]},splitList:{fn:(e,t)=>Hd(e,t),argTypes:[`string`,`string`]},splitn:{fn:(e,t,n)=>Ud(e,t,n),argTypes:[`string`,`int`,`string`],returnType:`dict`},squote:{fn:(...e)=>Gd(...e),argTypes:[`string`]},substr:{fn:(e,t,n)=>Kd(e,t,n),argTypes:[`int`,`int`,`string`]},swapcase:{fn:e=>qd(e),argTypes:[`string`],returnType:`string`},title:{fn:e=>Xd(e),argTypes:[`string`]},trim:{fn:e=>Zd(e),argTypes:[`string`]},trimAll:{fn:(e,t)=>Qd(e,t),argTypes:[`string`,`string`]},trimPrefix:{fn:(e,t)=>$d(e,t),argTypes:[`string`,`string`]},trimSuffix:{fn:(e,t)=>ef(e,t),argTypes:[`string`,`string`]},trunc:{fn:(e,t)=>tf(e,t),argTypes:[`int`,`string`]},untitle:{fn:e=>nf(e),argTypes:[`string`]},upper:{fn:e=>rf(e),argTypes:[`string`]},wrap:{fn:(e,t)=>af(e,t),argTypes:[`int`,`string`]},wrapWith:{fn:(e,t,n)=>sf(e,t,n),argTypes:[`int`,`string`,`string`]}}}function lf(e,t){if(!(e instanceof Ca))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);let n=e.copy();return n.style=e.style.add(t),n}function uf(e){return{fn:(t=>lf(t,e)),argTypes:[`liftable`],returnType:`T`}}function df(){let e={};for(let t of Object.keys(hi))e[t]=uf(new q({color:G.parse(t)}));return e}const ff={fn:((e,t)=>{if(!Number.isInteger(e)||e<0||e>255)throw RangeError(`color index ${e} is out of range (0-255)`);return lf(t,new q({color:G.fromAnsi(e)}))}),argTypes:[`int`,`liftable`],returnType:`T`},pf=/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/,mf={fn:((e,t)=>{if(!pf.test(e))throw RangeError(`hex expected #RRGGBB or #RRGGBBAA, got ${JSON.stringify(e)}`);return lf(t,new q({color:G.parse(e)}))}),argTypes:[`string`,`liftable`],returnType:`T`},hf={fn:((e,t,n,r)=>lf(r,new q({color:G.fromRgb(e,t,n)}))),argTypes:[`int`,`int`,`int`,`liftable`],returnType:`T`},gf={fn:((e,t)=>lf(t,new q({bgcolor:G.parse(e)}))),argTypes:[`string`,`liftable`],returnType:`T`};function _f(e,t){return new q({[e]:t})}function vf(){let e={};for(let t of ia)e[t]=uf(_f(t,!0)),e[`not_${t}`]=uf(_f(t,!1));for(let[t,n]of Object.entries(oa))e[t]=uf(_f(n,!0));return e}const yf={fn:((e,t)=>lf(t,q.parse(e))),argTypes:[`string`,`liftable`],returnType:`T`},bf={fn:((e,t)=>lf(t,new q({link:e}))),argTypes:[`string`,`liftable`],returnType:`T`};function xf(){return{...df(),color:ff,hex:mf,rgb:hf,on:gf,...vf(),link:bf,style:yf}}const Sf=/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/;function Cf(e){if(!Sf.test(e))throw RangeError(`palette background expected #RRGGBB or #RRGGBBAA, got ${JSON.stringify(e)}`);return G.parse(e).getTruecolor()}function wf(e,t,n,r){let i=e.resolve(t,n===void 0?void 0:{against:n});if(i===null){let e=n===void 0?`; for specs with alpha or auto-contrast, use paletteOver`:``;throw Error(`palette spec ${JSON.stringify(t)} did not resolve — check the spec string is valid and the variable exists${e}`)}return lf(r,new q({color:G.fromRgba(i)}))}const Tf=/^[A-Za-z_][A-Za-z0-9_]*$/;function Ef(e){let t={};for(let n of e.palette.vars.keys()){if(!Tf.test(n))continue;let r=n;t[r]={fn:(t=>wf(e,r,void 0,t)),argTypes:[`liftable`],returnType:`T`}}return t}function Df(e){return{fn:((t,n)=>wf(e,t,void 0,n)),argTypes:[`string`,`liftable`],returnType:`T`}}function Of(e){return{fn:((t,n,r)=>wf(e,t,Cf(n),r)),argTypes:[`string`,`string`,`liftable`],returnType:`T`}}function kf(e){return{fn:((t,n)=>wf(e,`auto`,Cf(t),n)),argTypes:[`string`,`liftable`],returnType:`T`}}function Af(e){return{...Ef(e),palette:Df(e),paletteOver:Of(e),auto:kf(e)}}function jf(){return xf()}new q({color:`red`,dim:!0});const Mf={dark:`textual-dark`,light:`textual-light`};function Nf(e){return Mf[e]??e}function Pf(e,t){return e??t??`textual-dark`}function Ff(){return Object.keys(Mf)}function If(){return[...Vi(),...Ff()]}const Lf=[`powerline`,`capsule`,`plain`];function Rf(e){return Lf.includes(e)}function zf(e,t){let n=e??t??`powerline`;return Rf(n)?n:`powerline`}var Bf=class extends Error{file;issues;constructor(e,t){super(Uf(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t}};function $(e,t){let n=0,r;for(let i of t){if(i===``||/^\d+$/.test(i))continue;let t=Vf(e,n,i);if(t===-1)return r===void 0?void 0:Hf(e,r);n=t,r=t}return r===void 0?void 0:Hf(e,r)}function Vf(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 Hf(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Uf(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(`
94
- `)}function Wf(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 ${Xf(i)}`,line:$(e.source,[...t.split(`.`),r])}),null)}function Gf(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 ${Xf(i)}`,line:$(e.source,[...t.split(`.`),`default`])});return}return i}}function Kf(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 ${Xf(i)}`,line:$(e.source,[...t.split(`.`),r])});return}return i}}function qf(e,t,n){let r=Kf(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}". Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:$(e.source,[...t.split(`.`),`palette`])});return}return r}}function Jf(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 ${Zf(a)}`,line:$(e.source,[...t.split(`.`),r])});return}return a}}function Yf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xf(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Zf(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function Qf(e,t,n,r){return Yf(r)?(ep(e,n,r,t.noun,new Set(Object.keys(t.fields))),$f(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${Xf(r)}`,line:$(e.source,n.split(`.`))}),null)}function $f(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}function ep(e,t,n,r,i){for(let a of Object.keys(n))i.has(a)||e.issues.push({path:`${t}.${a}`,message:`Unknown ${r} "${a}". Expected one of: ${[...i].join(`, `)}`,line:$(e.source,[...t.split(`.`),a])})}function tp(e,t,n,r){if(!Yf(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${Xf(r)}`,line:$(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:$(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:$(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:$(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function np(e,t,n,r){if(!Yf(r))return e.issues.push({path:n,message:`${n} must be an object, got ${Xf(r)}`,line:$(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 ${Xf(i)}`,line:$(e.source,n.split(`.`))}),null;let a=t.arms;return i in a?a[i].parse(e,n,r):(e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:$(e.source,[...n.split(`.`),t.tag])}),null)}function rp(e){return(...t)=>e()(...t)}function ip(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:$(n.source,o.split(`.`))}),null}return a}}function ap(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Kf(e,t,r,n)}}function op(){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 ${Xf(i)}`,line:$(e.source,[n])});return}return i}}}}function sp(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>qf(e,t,r)}}function cp(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Wf(e,t,r,n)??void 0}}function lp(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>Jf(t,n,i,r,e)}}function up(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 dp(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function fp(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function pp(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}function mp(e,t=Xn){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:{...t.segments,...e.segments??{}},root:e.root===void 0?t.root:e.root,actions:{...t.actions,...e.actions??{}},helpers:{...t.helpers,...e.helpers??{}}}}const hp={noun:`globals key`,fields:{default_bg:ap(),default_fg:ap(),default_empty_value:ap(),default_separator:ap(),default_truncate_marker:ap(),palette:sp(),style:lp(Lf)}};function gp(e,t){return t===void 0?{}:Qf(e,hp,`globals`,t)??{}}function _p(e,t,n,r){return n.cache===void 0?(Ln.includes(r)&&e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${z.join(`, `)})`,line:$(e.source,t.split(`.`))}),null):Cp(e,`${t}.cache`,n.cache)}function vp(e,t,n){if(n.cache!==void 0)return Cp(e,`${t}.cache`,n.cache)??void 0}function yp(e){return{required:!0,json:Ep(),parse:(t,n,r,i)=>_p(t,n,i,e)??void 0}}function bp(){return{required:!1,json:Ep(),parse:(e,t,n,r)=>vp(e,t,r)}}function xp(e,t,n){return e.issues.push({path:t,message:n,line:$(e.source,t.split(`.`))}),null}const Sp={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Op(n)?{ttl:n}:xp(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${Zf(n)}`)},watch_file:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{watch_file:n}:xp(e,t,`cache.watch_file must be a non-empty path string, got ${Zf(n)}`)},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:xp(e,t,`cache.depends_on must be an array of variable-name strings, got ${Zf(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:xp(e,t,`cache.key must be a non-empty template string, got ${Zf(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:xp(e,t,`cache.never must be the literal boolean true, got ${Zf(n)}`)}}};function Cp(e,t,n){return tp(e,Sp,t,n)}const wp={noun:`time-variable cache`,arms:{ttl:Sp.arms.ttl}};function Tp(){return{required:!1,json:pp(wp),parse:(e,t,n,r)=>r.cache===void 0?void 0:tp(e,wp,`${t}.cache`,r.cache)??void 0}}function Ep(){return pp(Sp)}const Dp=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Op(e){return Dp.test(e)}function kp(e,t,n){if(n===void 0)return{};if(!Yf(n))return e.issues.push({path:t,message:`${t} must be an object, got ${Xf(n)}`,line:$(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=np(e,Up,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function Ap(){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 ${Xf(i)}`,line:$(e.source,t.split(`.`))});return}return i}}}function jp(){return{required:!0,json:{enum:[...In]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!In.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${In.join(`, `)}, got ${JSON.stringify(i)}`,line:$(e.source,[...t.split(`.`),`field`])});return}return i}}}function Mp(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Gf(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const Np={value:Ap(),default:ap()},Pp={path:cp(),type:lp([`string`,`number`,`boolean`]),default:Mp()},Fp={name:cp(),default:ap()},Ip={path:cp(),readMode:lp([`whole`,`first-line`]),regex:ap(),cache:yp(`file`),default:ap()},Lp={command:cp(),regex:ap(),cache:yp(`shell`),default:ap()},Rp={template:cp(),cache:bp(),default:ap()},zp={layout:cp(),cache:Tp(),default:ap()},Bp={field:jp(),cache:yp(`git`),default:ap()},Vp={key:cp(),default:ap()};function Hp(e,t){return{json:dp(up(t),`kind`,e),parse:(n,r,i)=>{let a=$f(n,t,r,i);return a===null?null:{kind:e,...a}}}}const Up={tag:`kind`,noun:`source kind`,arms:{literal:Hp(`literal`,Np),input:Hp(`input`,Pp),env:Hp(`env`,Fp),file:Hp(`file`,Ip),shell:Hp(`shell`,Lp),template:Hp(`template`,Rp),time:Hp(`time`,zp),git:Hp(`git`,Bp),state:Hp(`state`,Vp)}};function Wp(){return fp(Up)}function Gp(){return{type:`object`,additionalProperties:Wp()}}function Kp(e,t){if(t===void 0)return{};if(!Yf(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${Xf(t)}`,line:$(e.source,[`segments`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=Qf(e,Yp,`segments.${r}`,i);t!==null&&(n[r]=t)}return n}function qp(){return{required:!1,json:{anyOf:[{const:`auto`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto" or a positive integer, got ${Zf(i)}`,line:$(e.source,[...t.split(`.`),n])})}}}}function Jp(){return{required:!1,json:Gp(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return kp(e,`${t}.${n}`,i)}}}const Yp={noun:`segment key`,fields:{template:cp(),width:qp(),justify:lp(Rn),truncate:lp(zn),bg:ap(),fg:ap(),when:ap(),palette:sp(),vars:Jp()}},Xp={kind:`container`,direction:`vertical`,children:[]};function Zp(e){return{required:!0,json:{const:e},parse:()=>e}}function Qp(){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 ${Zf(i)}`,line:$(e.source,[`root`])}),``)}}}function $p(){return{required:!0,json:{enum:[...Nn]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Nn.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${Nn.join(`, `)} (got ${JSON.stringify(i)})`,line:$(e.source,[`root`])}),`vertical`)}}}function em(e){return{required:!0,json:{type:`array`,items:{$ref:`#/definitions/LayoutNode`}},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 ${Xf(a)}`,line:$(t.source,[`root`])}),[])}}}const tm={noun:`layout-node key`,fields:{kind:Zp(`segment`),name:Qp(),when:ap()}},nm={noun:`layout-node key`,fields:{kind:Zp(`container`),direction:$p(),children:em(rp(()=>sm)),when:ap()}};function rm(){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 ${Zf(i)}`,line:$(e.source,[`root`])}),``)}}}const im={noun:`layout-node key`,fields:{seg:rm(),when:ap()}},am={noun:`layout-node key`,fields:{h:em(rp(()=>sm)),when:ap()}},om={noun:`layout-node key`,fields:{v:em(rp(()=>sm)),when:ap()}},sm=(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:$(e.source,[`root`])}),Xp):{kind:`segment`,name:n};if(!Yf(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 ${Xf(n)}`,line:$(e.source,[`root`])}),Xp;if(n.kind===`container`)return Qf(e,nm,t,n)??Xp;if(n.kind===`segment`)return Qf(e,tm,t,n)??Xp;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
95
- Old: { kind: "cells", segments: ["seg1", "seg2"] }
96
- New: { h: ["seg1", "seg2"] }`,line:$(e.source,[`root`])}),Xp;if(n.kind===`group`){let r=Qf(e,mm,t,n);return r===null?Xp:(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}),gm(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:$(e.source,[`root`])}),Xp}if(a){let r=Qf(e,im,t,n);return r===null?Xp:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when}}}if(r){let r=Qf(e,am,t,n);return r===null?Xp:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when}}}if(i){let r=Qf(e,om,t,n);return r===null?Xp:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when}}}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:$(e.source,[`root`])}),Xp},cm=`groups.`,lm=`closed`,um=/^[A-Za-z_][A-Za-z0-9_]*$/;function dm(){return{required:!0,json:{type:`string`,pattern:um.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!um.test(i)||i===lm){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 "${lm}", got ${Zf(i)}`,line:$(e.source,[`root`])});return}return i}}}function fm(){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 ${Zf(i)}`,line:$(e.source,[`root`])});return}return i}}}}function pm(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Wf(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:$(e.source,[...t.split(`.`),n])});return}return i}}}}const mm={noun:`layout-node key`,fields:{kind:Zp(`group`),name:dm(),label:pm(),open:op(),direction:lp(Nn),key:fm(),bg:ap(),fg:ap(),when:ap(),children:em(rp(()=>sm))}};function hm(e){return e.key??`groups.`+e.name}function gm(e){let t=cm+e.name;return{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:t},{kind:`container`,direction:e.direction??`vertical`,children:e.children,when:`{{ eq .${t} "${e.name}" }}`}],...e.when!==void 0&&{when:e.when}}}function _m(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function vm(e,t,n){e.issues.push({path:t,message:n,line:$(e.source,[`root`])})}function ym(e,t){let n=e.groups;if(n.length===0)return;for(let n of[`variables`,`actions`,`segments`])for(let r of Object.keys(t[n]??{}))r.startsWith(`groups.`)&&vm(e,`${n}.${r}`,`"${r}" is in the reserved "${cm}" namespace (synthesized by group nodes) — rename it`);let r=new Set;for(let t of n)r.has(t.name)&&vm(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}.`)&&hm(t)===hm(r)&&vm(e,t.path,`group "${t.name}" shares key "${hm(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=hm(t);if(i.has(n)||i.set(n,lm),t.open===!0){let r=i.get(n);r!==lm&&vm(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=cm+e.name,r=hm(e),c=_m(e.label),l=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,u=` `.repeat(l);a[t]={kind:`state`,key:r,default:i.get(r)},o[t]={set:r,cycle:[lm,e.name]},s[t]={template:`{{ action "${t}" "${u}${c} ▸" "${u}${c} ▾" }}`,...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 bm=`menus.`,xm=`closed`;function Sm(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function Cm(e){return bm+Sm(e)}function wm(e,t){return bm+Sm(e)+`.`+t}function Tm(e,t){return e??t}function Em(e,t){let n=(e,r,i)=>{if(e.kind===`segment`){t(e.name,Tm(i,r),r);return}let a=e.direction===`horizontal`?r:i;e.children.forEach((e,t)=>n(e,`${r}.children[${t}]`,a))};n(e,`root`,void 0)}function Dm(e){let t=cc({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(`menu`)}catch{return!1}}function Om(e,t,n){e.issues.push({path:t,message:n,line:$(e.source,[`root`])})}function km(e,t){for(let n of[`variables`,`actions`,`segments`])for(let r of Object.keys(t[n]??{}))r.startsWith(`menus.`)&&Om(e,`${n}.${r}`,`"${r}" is in the reserved "${bm}" namespace (synthesized by {{ menu }} helpers) — rename it`);for(let[n,r]of Object.entries(t.helpers??{}))Dm(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its accordion identity is derived from the segment's position in the layout, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:$(e.source,[`helpers`,n])});if(t.root===void 0)return;let n=t.segments??{},r=new Map,i=e=>{let t=r.get(e);if(t!==void 0)return t;let i=n[e],a=i===void 0?!1:Dm(i.template);return r.set(e,a),a},a=new Map,o={};if(Em(t.root,(t,n)=>{if(!i(t))return;if(t===`closed`){Om(e,`segments.${t}`,`segment "${t}" hosts a {{ menu }}, but a menu cannot live in a segment named "${xm}" — that name collides with the menu's closed-state sentinel, leaving the menu unopenable. Rename the segment.`);return}let r=Cm(n);a.set(r,n),o[wm(n,t)]={set:r,cycle:[xm,t]}}),a.size===0)return;let s={};for(let e of a.keys())s[e]={kind:`state`,key:e,default:xm};t.variables={...t.variables??{},...s},t.actions={...t.actions??{},...o}}const Am=[`themes`,`styles`],jm=[`set`,`copy`,`open`];function Mm(e){return`set`in e}function Nm(e,t){if(t===void 0)return{};if(!Yf(t))return Pm(e,`actions`,`actions must be an object, got ${Xf(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=Fm(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Pm(e,t,n){e.issues.push({path:t,message:n,line:$(e.source,t.split(`.`))})}function Fm(e,t,n){if(!Yf(n))return Pm(e,t,`${t} must be an action object, got ${Xf(n)}`),null;let r=jm.filter(e=>e in n);return r.length===1?Im[r[0]](e,t,n):(Pm(e,t,`action must declare exactly one of: ${jm.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const Im={set:Xm,copy:Lm(`copy`),open:Lm(`open`)};function Lm(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Pm(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Wf(t,n,r,e);return i===null?null:{[e]:i}}}function Rm(e,t,n,r,i,a){let o=Wf(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Pm(e,s,i),null):o.includes(`/`)?(Pm(e,s,a(o)),null):o}function zm(e,t,n){return Rm(e,t,`set`,n,`set key must be non-empty (the SessionState key to write)`,e=>`set key "${e}" contains "/" — state keys must be slash-free`)}const Bm={to:Zm()},Vm={from:Qm()},Hm={min:th(),max:th(),by:th()},Um={int:eh()},Wm={cycle:$m()},Gm={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},Km={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function qm(e,...t){let n=Object.keys(e),r=(t,n,r)=>$f(t,e,n,r),i=up(e);return{detect:n,allowed:[`set`,...n],label:n.join(`/`),json:{type:`object`,properties:{set:{type:`string`},...i.properties},required:[`set`,...i.required??[]],additionalProperties:!1},parse:t.length?ip(r,...t):r}}const Jm=[qm(Bm),qm(Vm),qm(Hm,Gm,Km),qm(Um),qm(Wm)],Ym=`a set action declares exactly one value source: "to" (a literal value), "from" (an option domain: ${Am.join(`/`)}), "min"/"max"/"by" (a bounded step), "int" (an unbounded integer cursor), or "cycle" (an enumerated domain stepped in order)`;function Xm(e,t,n){let r=zm(e,t,n),i=Jm.filter(e=>e.detect.some(e=>e in n));if(i.length!==1)return Pm(e,t,`${Ym}${i.length>1?` — found: ${i.map(e=>e.label).join(`, `)}`:``}`),null;let a=i[0];for(let r of Object.keys(n))a.allowed.includes(r)||Pm(e,`${t}.${r}`,`Unknown key "${r}" on this set action. Expected one of: ${a.allowed.join(`, `)}`);let o=a.parse(e,t,n);return r===null||o===null?null:{set:r,...o}}function Zm(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Rm(e,t,n,r,`set value must be non-empty — an empty value cannot be delivered on the set-state wire`,e=>`set value "${e}" contains "/" — set values must be slash-free`)??void 0}}function Qm(){return{required:!0,json:{enum:[...Am]},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Am.includes(i)){Pm(e,`${t}.${n}`,`from must be one of: ${Am.join(`, `)}, got ${Zf(i)}`);return}return i}}}function $m(){return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(e,t,n,r)=>{let i=r[n],a=`${t}.${n}`;if(!Array.isArray(i)||i.some(e=>typeof e!=`string`)){Pm(e,a,`cycle must be an array of strings (the enumerated values a click steps through), got ${Xf(i)}`);return}let o=i;if(o.length<2){Pm(e,a,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let s=o.some(e=>e===``),c=o.filter(e=>e.includes(`/`));if(s){Pm(e,a,`cycle members must be non-empty — an empty value cannot be delivered on the set-state wire`);return}if(c.length>0){Pm(e,a,`cycle member(s) ${c.map(e=>`"${e}"`).join(`, `)} contain "/" — set values must be slash-free`);return}if(new Set(o).size!==o.length){Pm(e,a,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return o}}}function eh(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Pm(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${Zf(r[n])}`);return}return!0}}}function th(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Pm(e,`${t}.${n}`,`${n} must be an integer, got ${Zf(i)}`);return}return i}}}function nh(e,t){if(t===void 0)return{};if(!Yf(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${Xf(t)}`,line:$(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 ${Zf(i)}`,line:$(e.source,[`helpers`,r])});continue}n[r]=i}return n}const rh=/{{([\s\S]*?)}}/g,ih=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g,ah=/(?<![A-Za-z0-9_)])\.([A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*)/g;function oh(e){let t=new Set,n;for(rh.lastIndex=0;(n=rh.exec(e))!==null;){let e=n[1].replace(ih,``),r;for(ah.lastIndex=0;(r=ah.exec(e))!==null;)t.add(r[1])}return t}const sh=/\baction\s+$/;function ch(e){let t=new Set;rh.lastIndex=0;let n;for(;(n=rh.exec(e))!==null;){let e=n[1],r=0,i;for(ih.lastIndex=0;(i=ih.exec(e))!==null;)sh.test(e.slice(r,i.index))&&t.add(i[0].slice(1,-1)),r=i.index+i[0].length}return t}const lh=/\bpicker\s+$/;function uh(e){let t=new Set;rh.lastIndex=0;let n;for(;(n=rh.exec(e))!==null;){let e=n[1],r=0,i=0,a;for(ih.lastIndex=0;(a=ih.exec(e))!==null;)lh.test(e.slice(r,a.index))&&(i=2),i>0&&(t.add(a[0].slice(1,-1)),i--),r=a.index+a[0].length}return t}function dh(e,t){if(t.has(e))return!0;let n=`${e}.`;for(let e of t)if(e.startsWith(n))return!0;return!1}const fh={gitTaculous:`gitaculous`};function ph(e,t){let n=new Set(Object.keys(t.variables));for(let[e,r]of Object.entries(t.segments))if(r.vars)for(let t of Object.keys(r.vars))n.add(`${e}.${t}`);let r=yh(e.source),i=$(e.source,[r]);for(let a of Pn(t.root))if(a.when!==void 0&&vh(e,`${r}.when`,a.when,n,{line:i}),a.kind===`segment`&&!Object.prototype.hasOwnProperty.call(t.segments,a.name)){let t=fh[a.name],n=t===void 0?``:` (the built-in segment "${a.name}" was renamed to "${t}" — update this reference)`;e.issues.push({path:r,message:`${r} entry "${a.name}" does not match any declared segment${n}`,line:i})}for(let[r,i]of Object.entries(t.variables))gh(e,`variables.${r}`,i,n);for(let[r,i]of Object.entries(t.segments)){if(i.vars)for(let[t,a]of Object.entries(i.vars))gh(e,`segments.${r}.vars.${t}`,a,n,r);for(let a of[`template`,`bg`,`fg`,`when`]){let o=i[a];if(typeof o==`string`){vh(e,`segments.${r}.${a}`,o,n,{segCtx:r});for(let n of ch(o))Object.prototype.hasOwnProperty.call(t.actions,n)||e.issues.push({path:`segments.${r}.${a}`,message:`${a} references unknown action "${n}"`,line:$(e.source,[`segments`,r,a])});for(let n of uh(o))Object.prototype.hasOwnProperty.call(t.actions,n)||e.issues.push({path:`segments.${r}.${a}`,message:`${a} references unknown action "${n}" (in a picker)`,line:$(e.source,[`segments`,r,a])})}}}for(let[r,i]of Object.entries(t.variables))_h(e,`variables.${r}`,i,n);for(let[r,i]of Object.entries(t.segments))if(i.vars)for(let[t,a]of Object.entries(i.vars))_h(e,`segments.${r}.vars.${t}`,a,n,r);(mh(t)||hh(t))&&!Object.prototype.hasOwnProperty.call(t.variables,`session.id`)&&e.issues.push({path:`variables.session.id`,message:`state reads and action set-writes require a global "session.id" variable (segment-local declarations do not satisfy this — declareState/set-state both read the global box; conventionally { kind: "input", path: "session_id" })`,line:$(e.source,[`variables`])})}function mh(e){for(let t of Object.values(e.variables))if(t.kind===`state`)return!0;for(let t of Object.values(e.segments))if(t.vars){for(let e of Object.values(t.vars))if(e.kind===`state`)return!0}return!1}function hh(e){return Object.values(e.actions).some(Mm)}function gh(e,t,n,r,i){n.kind===`template`&&vh(e,`${t}.template`,n.template,r,{segCtx:i}),Fn(n)&&n.cache&&`key`in n.cache&&vh(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function _h(e,t,n,r,i){if(Fn(n)&&n.cache&&`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.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.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:$(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function vh(e,t,n,r,i){for(let a of oh(n)){if(dh(a,r))continue;let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,o=n!==void 0&&dh(n,r)?` (segment-local vars are namespaced — write ".${n}")`:``;e.issues.push({path:t,message:`Template references unknown variable ".${a}"${o}`,line:i?.line??$(e.source,t.split(`.`))})}}function yh(e){try{let t=Un.default.parse(e);if(Yf(t)&&`root`in t)return`root`}catch{}return`layout`}function bh(e,t){let{graph:n,nodeInfo:r}=xh(t),i=new Map,a=[];for(let e of n.keys())i.set(e,0);for(let e of n.keys())if(i.get(e)===0&&o(e))return;function o(t){i.set(t,1),a.push(t);for(let s of n.get(t)??[]){let t=i.get(s);if(t===1){let t=a.indexOf(s),n=[...a.slice(t),s],i=n[0],o=r.get(i);return e.issues.push({path:o?.declarationPath??`variables.${i}`,message:`Dependency cycle: ${n.join(` → `)}`,line:$(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function xh(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=(e,n)=>{for(let i of oh(n)){if(t.has(i)){r.get(e).add(i);continue}let n=i.split(`.`)[0];n!==i&&t.has(n)&&r.get(e).add(n)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),Fn(n)&&(n.cache&&`key`in n.cache&&i(e,n.cache.key),n.cache&&`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}}const Sh=[`json5`,`json`];function Ch(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?u.homedir()+e.slice(1):e}function wh(e,t,n){if(n)return[n];let r=process.env.CC_CANDYBAR_CONFIG;if(r)return[Ch(r)];let i=t??process.cwd(),a=process.env.XDG_CONFIG_HOME??o.join(u.homedir(),`.config`);return[...e?Sh.map(t=>o.join(e,`.cc-candybar.${t}`)):[],...Sh.map(e=>o.join(i,`.cc-candybar.${e}`)),...Sh.map(e=>o.join(a,`cc-candybar`,`config.${e}`))]}function Th(e,t,r){return wh(e,t,r).find(n.existsSync)??null}function Eh(e,t){let r=wh(e,t),i=new Set,a=[];for(let e of r)i.has(e)||(i.add(e),n.existsSync(e)&&a.push(e));let s=new Map;for(let e of a){let t=o.dirname(e),n=o.basename(e).replace(/\.(json5|json)$/,``),r=o.join(t,n);s.has(r)||s.set(r,[]),s.get(r).push(e)}let c=[...s.values()].filter(e=>e.length>1);return c.length===0?null:`config-extension collision: ${c.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function Dh(e,t=Xn,r){let i=e===null?``:n.readFileSync(e,`utf-8`);return{config:mp(e===null?{}:kh(e,i,r),t),source:i}}function Oh(e,t=`<config>`,n=``,r=new Set(If())){let i=[],a={source:n,issues:i,allowedPalettes:r,groups:[]};if(ph(a,e),bh(a,e),i.length>0)throw new Bf(t,i);return e}function kh(e,t,n=new Set(If())){let r=Ah(e,t),i=[],a={source:t,issues:i,allowedPalettes:n,groups:[]};if(!Yf(r))throw new Bf(e,[{path:``,message:`Config root must be an object, got ${Xf(r)}`}]);let o=jh(a,r);if(i.length>0)throw new Bf(e,i);return o}function Ah(e,t){try{return Un.default.parse(t)}catch(t){let n=t;throw new Bf(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function jh(e,t){for(let n of Object.keys(t))Mh.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...Mh].join(`, `)}`,line:$(e.source,[n])});let n={};return t.globals!==void 0&&(n.globals=gp(e,t.globals)),t.variables!==void 0&&(n.variables=kp(e,`variables`,t.variables)),t.segments!==void 0&&(n.segments=Kp(e,t.segments)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
94
+ `)}function Vp(e){return e.split(/\s+/).filter(e=>e.length>0).map(e=>(e[0]??``).toUpperCase()).join(``)}function Hp(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw Mf(`join`,2,`list of strings/primitives`,`list element of type ${Up(e)}`);n.push(String(e))}return n.join(e)}function Up(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function Wp(e){return Np(e,`-`)}function Gp(e){return e.toLowerCase()}function Kp(e,t){return`\n${Bp(e,t)}`}function qp(e){return e.replace(/\s+/g,``)}function Jp(e,t,n){return n===1?e:t}function Yp(...e){return e.map(e=>`"${e}"`).join(` `)}function Xp(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function Zp(e,t){return t.repeat(Math.max(0,e))}function Qp(e,t,n){return n.split(e).join(t)}function $p(e){return Np(e,`_`)}function em(e,t){let n=t.split(e),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function tm(e,t){return t.split(e)}function nm(e,t,n){let r=rm(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function rm(e,t,n){if(n===0)return[];let r=t===``?Array.from(e):e.split(t);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 im(...e){return e.map(e=>`'${e}'`).join(` `)}function am(e,t,n){let r=t<0||t>n.length?n.length:t,i=Math.min(Math.max(0,e),r);return n.slice(i,r)}function om(e){let t=``;for(let n of e)sm(n)?t+=n.toLowerCase():cm(n)?t+=n.toUpperCase():t+=n;return t}function sm(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function cm(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function lm(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function um(e){return e.trim()}function dm(e,t){if(e.length===0)return t;let n=new Set([...e]),r=0;for(;r<t.length&&n.has(t[r]);)r+=1;let i=t.length;for(;i>r&&n.has(t[i-1]);)--i;return t.slice(r,i)}function fm(e,t){return t.startsWith(e)?t.slice(e.length):t}function pm(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function mm(e,t){if(e<0){let n=-e;return n>=t.length?t:t.slice(t.length-n)}return e>=t.length?t:t.slice(0,e)}function hm(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function gm(e){return e.toUpperCase()}function _m(e,t){return vm(e,`
95
+ `,t)}function vm(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
96
+ `)){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 ym(e,t,n){return vm(e,t,n)}function bm(){return{abbrev:{fn:(e,t)=>yp(e,t),argTypes:[`int`,`string`]},abbrevboth:{fn:(e,t,n)=>bp(e,t,n),argTypes:[`int`,`int`,`string`]},camelcase:{fn:e=>Fp(e),argTypes:[`string`],returnType:`string`},cat:{fn:(...e)=>Ip(...e),argTypes:[`string`]},contains:{fn:(e,t)=>Lp(e,t),argTypes:[`string`,`string`]},hasPrefix:{fn:(e,t)=>Rp(e,t),argTypes:[`string`,`string`]},hasSuffix:{fn:(e,t)=>zp(e,t),argTypes:[`string`,`string`]},indent:{fn:(e,t)=>Bp(e,t),argTypes:[`int`,`string`]},initials:{fn:e=>Vp(e),argTypes:[`string`]},join:{fn:(e,t)=>Hp(e,t),argTypes:[`string`,`list`]},kebabcase:{fn:e=>Wp(e),argTypes:[`string`],returnType:`string`},lower:{fn:e=>Gp(e),argTypes:[`string`]},nindent:{fn:(e,t)=>Kp(e,t),argTypes:[`int`,`string`]},nospace:{fn:e=>qp(e),argTypes:[`string`],returnType:`string`},plural:{fn:(e,t,n)=>Jp(e,t,n),argTypes:[`string`,`string`,`int`],returnType:`string`},quote:{fn:(...e)=>Yp(...e),argTypes:[`string`]},regexQuoteMeta:{fn:e=>Xp(e),argTypes:[`string`],returnType:`string`},repeat:{fn:(e,t)=>Zp(e,t),argTypes:[`int`,`string`]},replace:{fn:(e,t,n)=>Qp(e,t,n),argTypes:[`string`,`string`,`string`]},snakecase:{fn:e=>$p(e),argTypes:[`string`],returnType:`string`},split:{fn:(e,t)=>em(e,t),argTypes:[`string`,`string`]},splitList:{fn:(e,t)=>tm(e,t),argTypes:[`string`,`string`]},splitn:{fn:(e,t,n)=>nm(e,t,n),argTypes:[`string`,`int`,`string`],returnType:`dict`},squote:{fn:(...e)=>im(...e),argTypes:[`string`]},substr:{fn:(e,t,n)=>am(e,t,n),argTypes:[`int`,`int`,`string`]},swapcase:{fn:e=>om(e),argTypes:[`string`],returnType:`string`},title:{fn:e=>lm(e),argTypes:[`string`]},trim:{fn:e=>um(e),argTypes:[`string`]},trimAll:{fn:(e,t)=>dm(e,t),argTypes:[`string`,`string`]},trimPrefix:{fn:(e,t)=>fm(e,t),argTypes:[`string`,`string`]},trimSuffix:{fn:(e,t)=>pm(e,t),argTypes:[`string`,`string`]},trunc:{fn:(e,t)=>mm(e,t),argTypes:[`int`,`string`]},untitle:{fn:e=>hm(e),argTypes:[`string`]},upper:{fn:e=>gm(e),argTypes:[`string`]},wrap:{fn:(e,t)=>_m(e,t),argTypes:[`int`,`string`]},wrapWith:{fn:(e,t,n)=>ym(e,t,n),argTypes:[`int`,`string`,`string`]}}}const xm=`menus.`,Sm=`closed`;function Cm(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}function wm(e){return e}function Tm(e,t,n){return n===void 0?xm+Cm(e)+`.`+Cm(t):xm+Cm(n)}function Em(e,t){return e+`.`+t}const Dm=`menu`;function Om(e){let t=bu({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===Dm).map(e=>({apply:e.args[0]??null,key:e.args.length>4?e.args[4]:void 0}))}catch{return`parse-failed`}}function km(e){let t=bu({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(Dm)}catch{return!1}}function Am(e,t,n){e.issues.push({path:t,message:n,line:Q(e.source,[`root`])})}function jm(e,t){for(let n of[`variables`,`actions`,`segments`])for(let r of Object.keys(t[n]??{}))r.startsWith(`menus.`)&&Am(e,`${n}.${r}`,`"${r}" is in the reserved "${xm}" namespace (synthesized by {{ menu }} helpers) — rename it`);for(let[n,r]of Object.entries(t.helpers??{}))km(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:Q(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`&&km(i)&&Am(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.`)}let r=new Map;if(t.root!==void 0)for(let n of Pn(t.root))typeof n.when==`string`&&km(n.when)&&Am(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.`),n.kind===`segment`&&r.set(n.name,(r.get(n.name)??0)+1);for(let[t,i]of Object.entries(n))km(i.template)&&(r.get(t)??0)>1&&Am(e,`segments.${t}`,`segment "${t}" hosts a {{ menu }} and is placed in the layout more than once — a menu's open-state is keyed by segment name, so the copies would share one state (clicking one would toggle both). Give each placement its own named segment.`);let i=new Set,a={},o=new Set,s=new Map;for(let[t,r]of Object.entries(n)){if(!km(r.template))continue;let n=Om(r.template);if(n!==`parse-failed`)for(let r of n){if(r.apply===null){Am(e,`segments.${t}`,`segment "${t}" has a {{ menu }} 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" "themePage" }}).`);continue}if(r.key===null){Am(e,`segments.${t}`,`segment "${t}" has a {{ menu }} whose accordion key is not a string literal — a shared key must be a literal so the mutually-exclusive group can be gated at load (e.g. {{ menu "applyTheme" "themePage" false false "pickers" }}).`);continue}if(r.key===``){Am(e,`segments.${t}`,`segment "${t}" has a {{ menu }} with an empty accordion key — a shared key must be a non-empty name (or omit it for an independent menu).`);continue}if(r.apply===``){Am(e,`segments.${t}`,`segment "${t}" has a {{ menu }} 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.`);continue}let n=wm(r.apply);if(n===`closed`){Am(e,`segments.${t}`,`segment "${t}" has a {{ menu }} whose apply action is named "${Sm}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action.`);continue}let c=Tm(t,r.apply,r.key),l=r.key===void 0?`ind${t}${r.apply}`:`key${r.key}`,u=s.get(c);if(u!==void 0&&u!==l){Am(e,`segments.${t}`,`two {{ menu }} disclosures normalize to the same state key ("${c}") 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}s.set(c,l);let d=Em(c,n);if(o.has(d)){Am(e,`segments.${t}`,`two {{ menu }} disclosures resolve to the same identity ("${d}") — ${r.key===void 0?`a segment cannot contain two menus over the same apply action "${r.apply}"`:`menus sharing key "${r.key}" must have distinct apply actions`}.`);continue}o.add(d),i.add(c),a[d]={set:c,cycle:[Sm,n]}}}if(i.size===0)return;let c={};for(let e of i)c[e]={kind:`state`,key:e,default:Sm};t.variables={...t.variables??{},...c},t.actions={...t.actions??{},...a}}const Mm=[`themes`,`styles`],Nm=[`set`,`copy`,`open`];function Pm(e){return`set`in e}function Fm(e,t){if(t===void 0)return{};if(!gs(t))return Im(e,`actions`,`actions must be an object, got ${_s(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=Lm(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Im(e,t,n){e.issues.push({path:t,message:n,line:Q(e.source,t.split(`.`))})}function Lm(e,t,n){if(!gs(n))return Im(e,t,`${t} must be an action object, got ${_s(n)}`),null;let r=Nm.filter(e=>e in n);return r.length===1?Rm[r[0]](e,t,n):(Im(e,t,`action must declare exactly one of: ${Nm.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const Rm={set:Qm,copy:zm(`copy`),open:zm(`open`)};function zm(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Im(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=ds(t,n,r,e);return i===null?null:{[e]:i}}}function Bm(e,t,n,r,i,a){let o=ds(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Im(e,s,i),null):o.includes(`/`)?(Im(e,s,a(o)),null):o}function Vm(e,t,n){return Bm(e,t,`set`,n,`set key must be non-empty (the SessionState key to write)`,e=>`set key "${e}" contains "/" — state keys must be slash-free`)}const Hm={to:$m()},Um={from:eh()},Wm={min:rh(),max:rh(),by:rh()},Gm={int:nh()},Km={cycle:th()},qm={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},Jm={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function Ym(e,...t){let n=Object.keys(e),r=(t,n,r)=>bs(t,e,n,r),i=js(e);return{detect:n,allowed:[`set`,...n],label:n.join(`/`),json:{type:`object`,properties:{set:{type:`string`},...i.properties},required:[`set`,...i.required??[]],additionalProperties:!1},parse:t.length?Ts(r,...t):r}}const Xm=[Ym(Hm),Ym(Um),Ym(Wm,qm,Jm),Ym(Gm),Ym(Km)],Zm=`a set action declares exactly one value source: "to" (a literal value), "from" (an option domain: ${Mm.join(`/`)}), "min"/"max"/"by" (a bounded step), "int" (an unbounded integer cursor), or "cycle" (an enumerated domain stepped in order)`;function Qm(e,t,n){let r=Vm(e,t,n),i=Xm.filter(e=>e.detect.some(e=>e in n));if(i.length!==1)return Im(e,t,`${Zm}${i.length>1?` — found: ${i.map(e=>e.label).join(`, `)}`:``}`),null;let a=i[0];for(let r of Object.keys(n))a.allowed.includes(r)||Im(e,`${t}.${r}`,`Unknown key "${r}" on this set action. Expected one of: ${a.allowed.join(`, `)}`);let o=a.parse(e,t,n);return r===null||o===null?null:{set:r,...o}}function $m(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Bm(e,t,n,r,`set value must be non-empty — an empty value cannot be delivered on the set-state wire`,e=>`set value "${e}" contains "/" — set values must be slash-free`)??void 0}}function eh(){return{required:!0,json:{enum:[...Mm]},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Mm.includes(i)){Im(e,`${t}.${n}`,`from must be one of: ${Mm.join(`, `)}, got ${vs(i)}`);return}return i}}}function th(){return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(e,t,n,r)=>{let i=r[n],a=`${t}.${n}`;if(!Array.isArray(i)||i.some(e=>typeof e!=`string`)){Im(e,a,`cycle must be an array of strings (the enumerated values a click steps through), got ${_s(i)}`);return}let o=i;if(o.length<2){Im(e,a,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let s=o.some(e=>e===``),c=o.filter(e=>e.includes(`/`));if(s){Im(e,a,`cycle members must be non-empty — an empty value cannot be delivered on the set-state wire`);return}if(c.length>0){Im(e,a,`cycle member(s) ${c.map(e=>`"${e}"`).join(`, `)} contain "/" — set values must be slash-free`);return}if(new Set(o).size!==o.length){Im(e,a,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return o}}}function nh(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Im(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${vs(r[n])}`);return}return!0}}}function rh(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Im(e,`${t}.${n}`,`${n} must be an integer, got ${vs(i)}`);return}return i}}}function ih(e,t){if(t===void 0)return{};if(!gs(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${_s(t)}`,line:Q(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 ${vs(i)}`,line:Q(e.source,[`helpers`,r])});continue}n[r]=i}return n}const ah=/{{([\s\S]*?)}}/g,oh=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g,sh=/(?<![A-Za-z0-9_)])\.([A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*)/g;function ch(e){let t=new Set,n;for(ah.lastIndex=0;(n=ah.exec(e))!==null;){let e=n[1].replace(oh,``),r;for(sh.lastIndex=0;(r=sh.exec(e))!==null;)t.add(r[1])}return t}const lh=/\baction\s+$/;function uh(e){let t=new Set;ah.lastIndex=0;let n;for(;(n=ah.exec(e))!==null;){let e=n[1],r=0,i;for(oh.lastIndex=0;(i=oh.exec(e))!==null;)lh.test(e.slice(r,i.index))&&t.add(i[0].slice(1,-1)),r=i.index+i[0].length}return t}const dh=/\b(?:picker|menu)\s+$/;function fh(e){let t=new Set;ah.lastIndex=0;let n;for(;(n=ah.exec(e))!==null;){let e=n[1],r=0,i=0,a;for(oh.lastIndex=0;(a=oh.exec(e))!==null;)dh.test(e.slice(r,a.index))&&(i=2),i>0&&(t.add(a[0].slice(1,-1)),i--),r=a.index+a[0].length}return t}function ph(e,t){if(t.has(e))return!0;let n=`${e}.`;for(let e of t)if(e.startsWith(n))return!0;return!1}const mh={gitTaculous:`gitaculous`};function hh(e,t){let n=new Set(Object.keys(t.variables));for(let[e,r]of Object.entries(t.segments))if(r.vars)for(let t of Object.keys(r.vars))n.add(`${e}.${t}`);let r=xh(e.source),i=Q(e.source,[r]);for(let a of Pn(t.root))if(a.when!==void 0&&bh(e,`${r}.when`,a.when,n,{line:i}),a.kind===`segment`&&!Object.prototype.hasOwnProperty.call(t.segments,a.name)){let t=mh[a.name],n=t===void 0?``:` (the built-in segment "${a.name}" was renamed to "${t}" — update this reference)`;e.issues.push({path:r,message:`${r} entry "${a.name}" does not match any declared segment${n}`,line:i})}for(let[r,i]of Object.entries(t.variables))vh(e,`variables.${r}`,i,n);for(let[r,i]of Object.entries(t.segments)){if(i.vars)for(let[t,a]of Object.entries(i.vars))vh(e,`segments.${r}.vars.${t}`,a,n,r);for(let a of[`template`,`bg`,`fg`,`when`]){let o=i[a];if(typeof o==`string`){bh(e,`segments.${r}.${a}`,o,n,{segCtx:r});for(let n of uh(o))Object.prototype.hasOwnProperty.call(t.actions,n)||e.issues.push({path:`segments.${r}.${a}`,message:`${a} references unknown action "${n}"`,line:Q(e.source,[`segments`,r,a])});for(let n of fh(o))Object.prototype.hasOwnProperty.call(t.actions,n)||e.issues.push({path:`segments.${r}.${a}`,message:`${a} references unknown action "${n}" (in a picker or menu)`,line:Q(e.source,[`segments`,r,a])})}}}for(let[r,i]of Object.entries(t.variables))yh(e,`variables.${r}`,i,n);for(let[r,i]of Object.entries(t.segments))if(i.vars)for(let[t,a]of Object.entries(i.vars))yh(e,`segments.${r}.vars.${t}`,a,n,r);(gh(t)||_h(t))&&!Object.prototype.hasOwnProperty.call(t.variables,`session.id`)&&e.issues.push({path:`variables.session.id`,message:`state reads and action set-writes require a global "session.id" variable (segment-local declarations do not satisfy this — declareState/set-state both read the global box; conventionally { kind: "input", path: "session_id" })`,line:Q(e.source,[`variables`])})}function gh(e){for(let t of Object.values(e.variables))if(t.kind===`state`)return!0;for(let t of Object.values(e.segments))if(t.vars){for(let e of Object.values(t.vars))if(e.kind===`state`)return!0}return!1}function _h(e){return Object.values(e.actions).some(Pm)}function vh(e,t,n,r,i){n.kind===`template`&&bh(e,`${t}.template`,n.template,r,{segCtx:i}),Fn(n)&&n.cache&&`key`in n.cache&&bh(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function yh(e,t,n,r,i){if(Fn(n)&&n.cache&&`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.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.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:Q(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function bh(e,t,n,r,i){for(let a of ch(n)){if(ph(a,r))continue;let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,o=n!==void 0&&ph(n,r)?` (segment-local vars are namespaced — write ".${n}")`:``;e.issues.push({path:t,message:`Template references unknown variable ".${a}"${o}`,line:i?.line??Q(e.source,t.split(`.`))})}}function xh(e){try{let t=Un.default.parse(e);if(gs(t)&&`root`in t)return`root`}catch{}return`layout`}function Sh(e,t){let{graph:n,nodeInfo:r}=Ch(t),i=new Map,a=[];for(let e of n.keys())i.set(e,0);for(let e of n.keys())if(i.get(e)===0&&o(e))return;function o(t){i.set(t,1),a.push(t);for(let s of n.get(t)??[]){let t=i.get(s);if(t===1){let t=a.indexOf(s),n=[...a.slice(t),s],i=n[0],o=r.get(i);return e.issues.push({path:o?.declarationPath??`variables.${i}`,message:`Dependency cycle: ${n.join(` → `)}`,line:Q(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function Ch(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=(e,n)=>{for(let i of ch(n)){if(t.has(i)){r.get(e).add(i);continue}let n=i.split(`.`)[0];n!==i&&t.has(n)&&r.get(e).add(n)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),Fn(n)&&(n.cache&&`key`in n.cache&&i(e,n.cache.key),n.cache&&`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}}const wh=[`json5`,`json`];function Th(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?u.homedir()+e.slice(1):e}function Eh(e,t,n){if(n)return[n];let r=process.env.CC_CANDYBAR_CONFIG;if(r)return[Th(r)];let i=t??process.cwd(),a=process.env.XDG_CONFIG_HOME??o.join(u.homedir(),`.config`);return[...e?wh.map(t=>o.join(e,`.cc-candybar.${t}`)):[],...wh.map(e=>o.join(i,`.cc-candybar.${e}`)),...wh.map(e=>o.join(a,`cc-candybar`,`config.${e}`))]}function Dh(e,t,r){return Eh(e,t,r).find(n.existsSync)??null}function Oh(e,t){let r=Eh(e,t),i=new Set,a=[];for(let e of r)i.has(e)||(i.add(e),n.existsSync(e)&&a.push(e));let s=new Map;for(let e of a){let t=o.dirname(e),n=o.basename(e).replace(/\.(json5|json)$/,``),r=o.join(t,n);s.has(r)||s.set(r,[]),s.get(r).push(e)}let c=[...s.values()].filter(e=>e.length>1);return c.length===0?null:`config-extension collision: ${c.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function kh(e,t=Xn,r){let i=e===null?``:n.readFileSync(e,`utf-8`);return{config:Fs(e===null?{}:jh(e,i,r),t),source:i}}function Ah(e,t=`<config>`,n=``,r=new Set(rs())){let i=[],a={source:n,issues:i,allowedPalettes:r,groups:[]};if(hh(a,e),Sh(a,e),i.length>0)throw new ss(t,i);return e}function jh(e,t,n=new Set(rs())){let r=Mh(e,t),i=[],a={source:t,issues:i,allowedPalettes:n,groups:[]};if(!gs(r))throw new ss(e,[{path:``,message:`Config root must be an object, got ${_s(r)}`}]);let o=Nh(a,r);if(i.length>0)throw new ss(e,i);return o}function Mh(e,t){try{return Un.default.parse(t)}catch(t){let n=t;throw new ss(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function Nh(e,t){for(let n of Object.keys(t))Ph.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...Ph].join(`, `)}`,line:Q(e.source,[n])});let n={};return t.globals!==void 0&&(n.globals=Ls(e,t.globals)),t.variables!==void 0&&(n.variables=Xs(e,`variables`,t.variables)),t.segments!==void 0&&(n.segments=pc(e,t.segments)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
97
97
  Replace: layout: [["seg1", "seg2"], ["seg3"]]
98
98
  With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
99
- Single-row example: root: { h: ["seg1", "seg2"] }`,line:$(e.source,[`layout`])}),t.root!==void 0&&(n.root=sm(e,`root`,t.root)),t.actions!==void 0&&(n.actions=Nm(e,t.actions)),t.helpers!==void 0&&(n.helpers=nh(e,t.helpers)),ym(e,n),km(e,n),n}const Mh=new Set([`globals`,`variables`,`segments`,`layout`,`root`,`actions`,`helpers`]),Nh=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function Ph(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 Fh(e){let t=await Ih(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function Ih(e){for(let t of[65536,1048576]){let n=await pn(e,t);if(n.kind!==`ok`)return n;let r=Lh(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return zt}return zt}function Lh(e,t){let n=e.toString(`utf8`).split(`
100
- `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!Nh.test(t))continue;let r=Ph(t);if(r!=null)return r}return null}const Rh=10*1e3;function zh(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 Bh(e,t){if(!(t<60))return e*3600/t}function Vh(e,t,n,r){let i=r-t;if(i<50||i>Rh)return;let a=n-e;if(!(a<=0))return a*1e3/i}function Hh(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=Vh(t.input,t.atMs,n.input,n.atMs),i=Vh(t.output,t.atMs,n.output,n.atMs),a=Vh(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 Uh(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>Rh)continue;let o=Vh(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function Wh(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,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}`,i);let n=[],r=new Set;for(let t of Pn(e.root)){if(t.when)for(let e of oh(t.when))n.push(e);if(t.kind!==`segment`)continue;let r=e.segments[t.name];if(r){for(let e of[r.template,r.when,r.bg,r.fg])if(e)for(let t of oh(e))n.push(t)}}let i=new Set;for(;n.length>0;){let e=n.pop();for(let a of Gh(t,e)){if(r.has(a))continue;r.add(a);let e=t.get(a);if(e){if(e.kind===`input`)i.add(e.path);else if(e.kind===`template`)for(let t of oh(e.template))n.push(t)}}}return i}function Gh(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 Kh(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function qh(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`)&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.timeSinceCommit`)&&{showTimeSinceCommit:!0},...(t(`git.prNumber`)||t(`git.prState`)||t(`git.prUrl`)||t(`git.prError`))&&{showPullRequest:!0}}}async function Jh(e,t,n,r){let i=e=>Kh(r,e),a=(t.clock??(()=>new Date))().getTime(),o=(e,t,n)=>t?n().catch(t=>F(`${e}: ${String(t)}`)):Promise.resolve(zt),[s,c,l,u,d,f,p,m]=await Promise.all([o(`git`,i(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,qh(r),e.workspace?.project_dir)),o(`session`,i(`session.cost`)||i(`session.tokens`)||i(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),o(`today`,i(`today`),()=>t.usageStore.getTodayInfo(e)),o(`context`,i(`context`),()=>t.contextProvider.getContextInfo(e)),o(`metrics`,i(`metrics`)||i(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),o(`tmux`,i(`tmux`),()=>t.tmuxService.getSessionId()),o(`cache`,i(`cache`),()=>Fh(e.transcript_path)),o(`speed`,i(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,a))]),h=[],g=e=>{if(e.kind===`failed`){h.push(e.reason);return}return e.kind===`ok`?e.value:void 0},_=Zh(s);h.push(..._.failures);let v=g(c),y=g(l),b=g(u),x=g(d),S=g(f),C=g(p);for(let e of h)t.log(`warn`,`provider fetch failed: ${e}`);let ee=e.rate_limits?.five_hour,te=e.rate_limits?.seven_day,w=ee?zh(ee.used_percentage,ee.resets_at,18e6,a):void 0,ne=te?zh(te.used_percentage,te.resets_at,6048e5,a):void 0,re=v?.session.cost,ie=x?.sessionDuration,T=i(`burn`)&&re!=null&&ie!=null?Bh(re,ie):void 0,E=g(m),ae=E===void 0?void 0:Hh(E),oe=E===void 0?void 0:Uh(E),se=ae!==void 0||oe!==void 0?{...ae,...oe!==void 0&&{history:oe}}:void 0,ce=i(`theme`)?t.sessionState.get(e.session_id,`theme`):void 0,D=typeof ce==`string`?ce:void 0,le=Xh(process.env.HOME??process.env.USERPROFILE),ue=e.workspace?{...e.workspace,current_dir:Xh(e.workspace.current_dir)??``,project_dir:Xh(e.workspace.project_dir)??``}:e.workspace,O=v===void 0?void 0:Yh({cost:v.session.cost,tokens:v.session.tokens}),de=y===void 0?void 0:{cost:y.cost,tokens:y.tokens},fe=x===void 0?void 0:Yh({lastResponseTime:x.lastResponseTime,responseTime:x.responseTime,sessionDuration:x.sessionDuration,messageCount:x.messageCount,linesAdded:x.linesAdded,linesRemoved:x.linesRemoved});return{...e,...ue!==void 0&&{workspace:ue},...le!==void 0&&{home:le},..._.git!==void 0&&{git:_.git},...S!==void 0&&{tmux:{session:S}},...D!==void 0&&{theme:D},...O!==void 0&&{session:O},...de!==void 0&&{today:de},...T!==void 0&&{burn:{costPerHour:T}},...se!==void 0&&{speed:se},...i(`block`)&&ee!==void 0&&{block:{nativeUtilization:ee.used_percentage,resetsAt:ee.resets_at,...w!==void 0&&{etaMinutes:w}}},...te!==void 0&&{weekly:{percentage:te.used_percentage,resetsAt:te.resets_at,...ne!==void 0&&{etaMinutes:ne}}},...C!==void 0&&{cache:{expiresAt:C}},...b!==void 0&&{context:{totalTokens:b.totalTokens,contextLeft:b.contextLeftPercentage}},...fe!==void 0&&{metrics:fe}}}function Yh(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 Xh(e){return e===void 0||e.length===0||o.sep!==`\\`?e:e.replace(/\\/g,`/`)}function Zh(e){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let t=e.value,n=[],r=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){n.push(`git.${e}: ${t.reason}`);return}return t.value}},i=r(`aheadBehind`,t.aheadBehind),a=r(`sha`,t.sha),o=r(`operation`,t.operation),s=r(`timeSinceCommit`,t.timeSinceCommit),c=r(`stash`,t.stashCount),l=r(`upstream`,t.upstream),u=r(`repoName`,t.repoName),d=t.pullRequest,f={};return d?.kind===`ok`?(f.prNumber=d.value.number,f.prState=d.value.state,f.prUrl=d.value.url):d?.kind===`failed`&&(n.push(`git.pr: ${d.reason}`),f.prError=d.reason),{git:{branch:t.branch,status:t.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...t.workingTree!==void 0&&{staged:t.workingTree.staged,unstaged:t.workingTree.unstaged,untracked:t.workingTree.untracked,conflicts:t.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{timeSinceCommit:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{repoName:u},...f},failures:n}}function Qh(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 $h(e){return typeof e==`string`?e:String(e)}function eg(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 tg(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")`)}const ng=/^(?:(?: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,rg=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function ig(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(ng);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(rg);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 ag(e){let t=e.match(rg);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 og(e){return e.toLocaleString()}const sg=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],cg=sg.length;function lg(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*(cg-1));o+=sg[t]}return o}function ug(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}const dg=If(),fg=[...Lf];function pg(){return{basename:{fn:e=>s(e),argTypes:[`string`]},dirname:{fn:e=>c(e),argTypes:[`string`]},int:{fn:e=>eg(e),argTypes:[`value`]},string:{fn:e=>$h(e),argTypes:[`value`]},bool:{fn:e=>tg(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>dg,argTypes:[]},styles:{fn:()=>fg,argTypes:[]},sparkline:{fn:(e,t)=>lg(ug(e),t),argTypes:[`string`,`int`]}}}function mg(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>og(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>ig(e),argTypes:[`string`]},shortenModelName:{fn:e=>ag(e),argTypes:[`string`]}}}function hg(e,t,n=()=>new Date){return cc({fromString:e=>new Ca(e),toString:e=>e.plain,clock:n,missingKey:`error`,funcs:{...Ql(),...cf(),...Lu(),...ad(),...Wl(n),...Pc(),...du(),...jf(),...e===void 0?{}:Af(e),...pg(),...mg(n),...t??{}}})}function gg(e){return _g(e,new Set(e.names()),``)}function _g(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.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return _g(e,t,a)}})}function vg(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(O(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function yg(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]}"`)}}async function bg(e){let t=await _e({bin:`/bin/sh`,args:[`-c`,e],category:`user-shell`});return t.ok?{stdout:t.stdout,exitCode:t.exitCode??0}:{stdout:t.stdout,exitCode:t.exitCode??1}}async function xg(e,t,n){let r;try{r=await C(e,`utf8`)}catch{return{error:`file unreadable: ${e}`}}if(n!==void 0){let t=new RegExp(n).exec(r);return t?.[1]?{content:t[1].replace(/\n/g,` `)}:{error:`regex no-match in "${e}"`}}return t===`first-line`?{content:(r.split(`
101
- `)[0]??``).trim()}:{content:r.replace(/\n/g,` `).trim()}}const Sg=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Cg=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],wg=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],Tg=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function Eg(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>Sg[e.getMonth()]],[`Monday`,e=>wg[e.getDay()]],[`Jan`,e=>Cg[e.getMonth()]],[`Mon`,e=>Tg[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 Dg={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function Og(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=Dg[t];try{return Mg(r,e)}catch{return Ng(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return Bt(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return Bt(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return Bt(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return Bt(e.stashCount,0)}}var kg=class{watchers=new Map;subscribe(e,t){let n=this.watchers.get(e);if(!n){let t=new Set,r;try{r=a(e,()=>{for(let e of t)e()})}catch{return()=>{}}n={watcher:r,callbacks:t},this.watchers.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.callbacks.delete(t),n.callbacks.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}},Ag=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:re(()=>{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&&(ne(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())ne(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function jg(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function Mg(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`?$h(e):t===`number`?eg(e):tg(e)}function Ng(e){return e===`number`?0:e===`boolean`?!1:``}var Pg=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new kg;ttlMgr=new Ag;gitSubscriptions=new Map;cleanups=[];inFlight=new Set;engine=hg();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new an({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Qh(t),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){let r=vg(e,n.cache);this.store.defineBox(e,`string`,this.stringInitial(n.varDefault));let i=()=>void this.updateFromShell(e,t,n.regex,n.varDefault);i(),this.registerCachePolicy(e,r,i)}declareFile(e,t,n){this.store.defineBox(e,`string`,this.stringInitial(n.varDefault));let r=()=>void this.updateFromFile(e,t,n.readMode,n.regex,n.varDefault);r(),this.registerCachePolicy(e,n.cache,r)}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.store.defineComputed(e,`string`,t=>{let i=gg(this.store);try{let t=r.evaluate(i).map(e=>e.plain).join(``);return this.lastErrors.delete(e),t}catch(t){return this.recordError(e,t instanceof Error?t.message:String(t)),this.stringInitial(n.varDefault)}}),this.store.read(e)}declareTime(e,t){let n=t.ttlMs??1e3;this.store.defineBox(e,`string`,(e=>{try{return Eg(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,Eg(t.format,new Date)),this.lastErrors.delete(e)}catch(n){this.applyFallback(e,`string`,t.varDefault,n instanceof Error?n.message:String(n))}});this.cleanups.push(r)}declareGit(e,t){let n=Dg[t.field],r=t.varDefault===void 0?Ng(n):Mg(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map;i={fieldSubs:e,unsubscribe: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,Og(t,n,i,this.defaultEmptyValue))})})},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})}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(`session.id`);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=jg(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,Mg(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`)}})}getLastError(e){return this.lastErrors.get(e)}dispose(){for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.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 e=this.watchMgr.subscribe(t.path,n);this.cleanups.push(e);break}case`key`:{let e=this.engine.parse(t.template),r=(0,X.reaction)(()=>{let t=gg(this.store);try{return e.evaluate(t).map(e=>e.plain).join(``)}catch{return``}},n);this.cleanups.push(r);break}case`depends_on`:{let e=(0,X.reaction)(()=>t.varNames.map(e=>String(this.store.read(e))).join(`,`),n);this.cleanups.push(e);break}}}async updateFromShell(e,t,n,r){if(!this.inFlight.has(e)){this.inFlight.add(e);try{let{stdout:i,exitCode:a}=await bg(t);if(a!==0){this.applyFallback(e,`string`,r,`shell "${t}" exited with code ${a}`);return}if(n!==void 0){let a=new RegExp(n).exec(i);if(!a?.[1]){this.applyFallback(e,`string`,r,`regex no-match in output of "${t}"`);return}this.store.setBox(e,a[1].replace(/\n/g,` `))}else this.store.setBox(e,i.replace(/\n/g,` `).trim());this.lastErrors.delete(e)}finally{this.inFlight.delete(e)}}}async updateFromFile(e,t,n,r,i){if(!this.inFlight.has(e)){this.inFlight.add(e);try{let a=await xg(t,n,r);if(a.error!==void 0){this.applyFallback(e,`string`,i,a.error);return}this.store.setBox(e,a.content??``),this.lastErrors.delete(e)}finally{this.inFlight.delete(e)}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,Mg(this.defaultEmptyValue,t))}catch{this.store.setBox(e,Ng(t))}}defaultFor(e){try{return Mg(this.defaultEmptyValue,e)}catch{return Ng(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})}};function Fg(e,t){switch(e){case`capsule`:return new Aa;case`plain`:return new ja(t===void 0?{}:{separator:t});case`powerline`:return new ka;default:return e}}function Ig(e,t){if(e.length===0)return``;let n=Fg(t.style,t.separator);if(Number.isFinite(t.width)){let r=Pa(new Ka([...e],{joiner:n}),{width:t.width,colorSystem:t.colorCompatibility});return r.endsWith(`
102
- `)?r.slice(0,-1):r}return Pa(new wa([...e],n),{colorSystem:t.colorCompatibility})}const Lg=new Map,Rg=new Map;function zg(e){let t=Nf(e),n=Lg.get(t);if(n!==void 0)return n;let r=Hi(t);if(r===null)throw Error(`Palette "${e}" (resolved "${t}") did not resolve in the theme registry — allowed names and the registry are inconsistent`);let i=new Fi(r);return Lg.set(t,i),i}function Bg(e,t){let n=`${e.palette.name} ${t}`,r=Rg.get(n);if(r!==void 0)return r;let i={hueShift:t,chromaScale:1,lightnessScale:1,lightnessShift:0},a=new Fi(ea(e.palette,i));return Rg.set(n,a),a}function Vg(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=Hg(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=Hg([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function Hg(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>Ug(e,t)):e,r=Ca.fromFragments(n);return r.end=``,r.noWrap=!0,n.length===1?r.style=n[0].style:t!==void 0&&!t.isNull&&(r.style=t),r}function Ug(e,t){let n=e.copy();return n.style=t.add(e.style),n}function Wg(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function Gg(e,t){let n=Ca.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function Kg(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o}=t;if(e.length===0)return[];let s=Gg(e,o);return n===`auto`||(s.cellLength>n?s.truncate(n,{mode:i,marker:a}):s.cellLength<n&&s.align(r,n)),[s]}var qg=class extends Error{constructor(e,t){super(`Invalid ${t} color spec: ${JSON.stringify(e)}`),this.name=`ColorSpecError`}};function Jg(e,t,n,r){let i=Yg(t,r),a=i===void 0?void 0:Xg(e,i,void 0,`bg`),o=Yg(n,r),s=o===void 0?void 0:Xg(e,o,a,`fg`);return new q({bgcolor:a===void 0?void 0:G.fromRgba(a),color:s===void 0?void 0:G.fromRgba(s)})}function Yg(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function Xg(e,t,n,r){let i=e.resolve(t.trim(),n===void 0?void 0:{against:n});if(i===null)throw new qg(t,r);return i}function Zg(e){return e===`themes`?If():Lf}function Qg(e,t,n){let r=new Map;for(let[i,a]of Object.entries(t))r.set(i,$g(e,i,a,n));return r}function $g(e,t,n,r){if(`set`in n){let e=r.get(n.set)??n.set;return`to`in n?{kind:`set-literal`,key:n.set,value:n.to,stateVar:e}:`from`in n?{kind:`set-option`,key:n.set,stateVar:e,options:[...Zg(n.from)]}:`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}}return`copy`in n?{kind:`copy`,text:e_(e,n.copy,t)}:{kind:`open`,target:e_(e,n.open,t)}}function e_(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function t_(e,t){return e.has(t)?$h(e.read(t)):``}function n_(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function r_(e,t,n){let r=new Ca(e,{style:new q({link:t,bold:n})});return r.noWrap=!0,r.end=``,r}function i_(e,t){return Math.max(e.members.indexOf(t_(t,e.stateVar)),0)}function a_(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=t_(r,e.stateVar);return{effect:{verb:at,args:[i,e.key,e.value]},active:t===e.value}}case`set-option`:{let a=n??t,o=t_(r,e.stateVar);return{effect:{verb:at,args:[i,e.key,a]},active:o===a}}case`set-int`:{let a=n??t,o=t_(r,e.stateVar);return{effect:{verb:at,args:[i,e.key,a]},active:o===a}}case`set-cycle`:{let t=e.members[(i_(e,r)+1)%e.members.length];return{effect:{verb:at,args:[i,e.key,t]},active:!1}}case`set-bounded`:return{effect:{verb:ot,args:[i,e.key,String(e.by)]},active:!1};case`copy`:return{effect:{verb:st,args:[n_(e.text,gg(r))]},active:!1};case`open`:return{effect:{verb:ct,args:[n_(e.target,gg(r))]},active:!1}}}function o_(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`){if(n.length!==1&&n.length!==t.members.length)throw Error(`action "${e}" cycles ${t.members.length} members; bind one display per member (${t.members.length}) or one static display, got ${n.length}`);return{display:n.length===1?n[0]:n[i_(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]}}function s_(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}=o_(e,r,t,i),{effect:s,active:c}=a_(r,a,o,i,t_(i,`session.id`));return r_(a,pt([s]),c)}function c_(e){return{action:{fn:(t,...n)=>s_(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function l_(e){return new Ca(e).cellLength}function u_(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 d_(e,t){let n=[];for(let t of e)n.length>0&&n.push(new Ca(` `)),n.push(t);let r=Ca.fromFragments(n);return r.noWrap=t,r.end=``,r}function f_(e,t,n,r){let i=e.compiled.get(t);if(!i||i.kind!==n)throw Error(`picker references action "${t}" which must be ${r}, got ${i?`a ${i.kind} action`:`no such action`}`);return i}function p_(e,t,n,r,i){let a=f_(i,e,`set-option`,`a set-option action ({ set, from })`),o=f_(i,t,`set-int`,`an int action ({ set, int: true })`),s=i.store,c=t_(s,`session.id`),l=t_(s,a.stateVar),u=a.options.map(l_),d=r?eg(s.read(`term.cols`)):1/0,f=l_(`✕`)+1,p=l_(`←`)+1+l_(`→`)+1,m=u_(u,d,f),h=m.length>1?u_(u,d,f+p):m,g=parseInt(t_(s,o.stateVar),10),_=Number.isInteger(g)?Math.max(0,Math.min(g,h.length-1)):0,v=h[_]??[],y=e=>pt([{verb:at,args:[c,o.key,String(e)]}]),b=e=>pt([{verb:at,args:[c,a.key,e,...n?[o.key,`-1`]:[]]}]),x=[r_(`✕`,y(-1),!1)];_>0&&x.push(r_(`←`,y(_-1),!1));for(let e of v){let t=a.options[e];x.push(r_(t,b(t),t===l))}return _<h.length-1&&x.push(r_(`→`,y(_+1),!1)),d_(x,r)}function m_(e){return{picker:{fn:(t,n,r,i)=>p_(t,n,r===!0,i===!0,e),argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}function h_(e,t,n,r,i){let a=i.current;if(a===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let{rowKey:o,segName:s}=a,c=i.action,l=s_(wm(o,s),[`▸`,`▾`],c);if(t_(c.store,Cm(o))!==s)return l;let u=p_(e,t,n,r,c),d=Ca.fromFragments([l,new Ca(`
103
- `),u]);return d.end=``,d}function g_(e){return{menu:{fn:(t,n,r,i)=>h_(t,n,r===!0,i===!0,e),argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}function __(e){let t=[],n=[];for(let r of e){if(!r.contains(`
99
+ Single-row example: root: { h: ["seg1", "seg2"] }`,line:Q(e.source,[`layout`])}),t.root!==void 0&&(n.root=Oc(e,`root`,t.root)),t.actions!==void 0&&(n.actions=Fm(e,t.actions)),t.helpers!==void 0&&(n.helpers=ih(e,t.helpers)),Bc(e,n),jm(e,n),n}const Ph=new Set([`globals`,`variables`,`segments`,`layout`,`root`,`actions`,`helpers`]),Fh=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function Ih(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 Lh(e){let t=await Rh(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function Rh(e){for(let t of[65536,1048576]){let n=await pn(e,t);if(n.kind!==`ok`)return n;let r=zh(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return zt}return zt}function zh(e,t){let n=e.toString(`utf8`).split(`
100
+ `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!Fh.test(t))continue;let r=Ih(t);if(r!=null)return r}return null}const Bh=10*1e3;function Vh(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 Hh(e,t){if(!(t<60))return e*3600/t}function Uh(e,t,n,r){let i=r-t;if(i<50||i>Bh)return;let a=n-e;if(!(a<=0))return a*1e3/i}function Wh(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=Uh(t.input,t.atMs,n.input,n.atMs),i=Uh(t.output,t.atMs,n.output,n.atMs),a=Uh(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 Gh(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>Bh)continue;let o=Uh(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function Kh(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,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}`,i);let n=[],r=new Set;for(let t of Pn(e.root)){if(t.when)for(let e of ch(t.when))n.push(e);if(t.kind!==`segment`)continue;let r=e.segments[t.name];if(r){for(let e of[r.template,r.when,r.bg,r.fg])if(e)for(let t of ch(e))n.push(t)}}let i=new Set;for(;n.length>0;){let e=n.pop();for(let a of qh(t,e)){if(r.has(a))continue;r.add(a);let e=t.get(a);if(e){if(e.kind===`input`)i.add(e.path);else if(e.kind===`template`)for(let t of ch(e.template))n.push(t)}}}return i}function qh(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 Jh(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Yh(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`)&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.timeSinceCommit`)&&{showTimeSinceCommit:!0},...(t(`git.prNumber`)||t(`git.prState`)||t(`git.prUrl`)||t(`git.prError`))&&{showPullRequest:!0}}}async function Xh(e,t,n,r){let i=e=>Jh(r,e),a=(t.clock??(()=>new Date))().getTime(),o=(e,t,n)=>t?n().catch(t=>F(`${e}: ${String(t)}`)):Promise.resolve(zt),[s,c,l,u,d,f,p,m]=await Promise.all([o(`git`,i(`git`),()=>t.gitProvider.getGitInfo(n??e.workspace?.current_dir,Yh(r),e.workspace?.project_dir)),o(`session`,i(`session.cost`)||i(`session.tokens`)||i(`burn`),()=>t.usageStore.getUsageInfo(e.session_id,e)),o(`today`,i(`today`),()=>t.usageStore.getTodayInfo(e)),o(`context`,i(`context`),()=>t.contextProvider.getContextInfo(e)),o(`metrics`,i(`metrics`)||i(`burn`),()=>t.metricsProvider.getMetricsInfo(e.session_id,e)),o(`tmux`,i(`tmux`),()=>t.tmuxService.getSessionId()),o(`cache`,i(`cache`),()=>Lh(e.transcript_path)),o(`speed`,i(`speed`),()=>t.usageStore.observeSpeed(e.session_id,e.transcript_path,a))]),h=[],g=e=>{if(e.kind===`failed`){h.push(e.reason);return}return e.kind===`ok`?e.value:void 0},_=$h(s);h.push(..._.failures);let v=g(c),y=g(l),b=g(u),x=g(d),S=g(f),C=g(p);for(let e of h)t.log(`warn`,`provider fetch failed: ${e}`);let ee=e.rate_limits?.five_hour,te=e.rate_limits?.seven_day,w=ee?Vh(ee.used_percentage,ee.resets_at,18e6,a):void 0,ne=te?Vh(te.used_percentage,te.resets_at,6048e5,a):void 0,re=v?.session.cost,ie=x?.sessionDuration,T=i(`burn`)&&re!=null&&ie!=null?Hh(re,ie):void 0,E=g(m),ae=E===void 0?void 0:Wh(E),oe=E===void 0?void 0:Gh(E),se=ae!==void 0||oe!==void 0?{...ae,...oe!==void 0&&{history:oe}}:void 0,ce=i(`theme`)?t.sessionState.get(e.session_id,`theme`):void 0,D=typeof ce==`string`?ce:void 0,le=Qh(process.env.HOME??process.env.USERPROFILE),ue=e.workspace?{...e.workspace,current_dir:Qh(e.workspace.current_dir)??``,project_dir:Qh(e.workspace.project_dir)??``}:e.workspace,O=v===void 0?void 0:Zh({cost:v.session.cost,tokens:v.session.tokens}),de=y===void 0?void 0:{cost:y.cost,tokens:y.tokens},fe=x===void 0?void 0:Zh({lastResponseTime:x.lastResponseTime,responseTime:x.responseTime,sessionDuration:x.sessionDuration,messageCount:x.messageCount,linesAdded:x.linesAdded,linesRemoved:x.linesRemoved});return{...e,...ue!==void 0&&{workspace:ue},...le!==void 0&&{home:le},..._.git!==void 0&&{git:_.git},...S!==void 0&&{tmux:{session:S}},...D!==void 0&&{theme:D},...O!==void 0&&{session:O},...de!==void 0&&{today:de},...T!==void 0&&{burn:{costPerHour:T}},...se!==void 0&&{speed:se},...i(`block`)&&ee!==void 0&&{block:{nativeUtilization:ee.used_percentage,resetsAt:ee.resets_at,...w!==void 0&&{etaMinutes:w}}},...te!==void 0&&{weekly:{percentage:te.used_percentage,resetsAt:te.resets_at,...ne!==void 0&&{etaMinutes:ne}}},...C!==void 0&&{cache:{expiresAt:C}},...b!==void 0&&{context:{totalTokens:b.totalTokens,contextLeft:b.contextLeftPercentage}},...fe!==void 0&&{metrics:fe}}}function Zh(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 Qh(e){return e===void 0||e.length===0||o.sep!==`\\`?e:e.replace(/\\/g,`/`)}function $h(e){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let t=e.value,n=[],r=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){n.push(`git.${e}: ${t.reason}`);return}return t.value}},i=r(`aheadBehind`,t.aheadBehind),a=r(`sha`,t.sha),o=r(`operation`,t.operation),s=r(`timeSinceCommit`,t.timeSinceCommit),c=r(`stash`,t.stashCount),l=r(`upstream`,t.upstream),u=r(`repoName`,t.repoName),d=t.pullRequest,f={};return d?.kind===`ok`?(f.prNumber=d.value.number,f.prState=d.value.state,f.prUrl=d.value.url):d?.kind===`failed`&&(n.push(`git.pr: ${d.reason}`),f.prError=d.reason),{git:{branch:t.branch,status:t.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...t.workingTree!==void 0&&{staged:t.workingTree.staged,unstaged:t.workingTree.unstaged,untracked:t.workingTree.untracked,conflicts:t.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{timeSinceCommit:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{repoName:u},...f},failures:n}}function eg(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 tg(e){return typeof e==`string`?e:String(e)}function ng(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 rg(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")`)}const ig=/^(?:(?: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,ag=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function og(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(ig);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(ag);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 sg(e){let t=e.match(ag);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 cg(e){return e.toLocaleString()}const lg=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],ug=lg.length;function dg(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*(ug-1));o+=lg[t]}return o}function fg(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}const pg=rs(),mg=[...is];function hg(){return{basename:{fn:e=>s(e),argTypes:[`string`]},dirname:{fn:e=>c(e),argTypes:[`string`]},int:{fn:e=>ng(e),argTypes:[`value`]},string:{fn:e=>tg(e),argTypes:[`value`]},bool:{fn:e=>rg(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>pg,argTypes:[]},styles:{fn:()=>mg,argTypes:[]},sparkline:{fn:(e,t)=>dg(fg(e),t),argTypes:[`string`,`int`]}}}function gg(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>cg(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>og(e),argTypes:[`string`]},shortenModelName:{fn:e=>sg(e),argTypes:[`string`]}}}function _g(e,t,n=()=>new Date){return bu({fromString:e=>new Ca(e),toString:e=>e.plain,clock:n,missingKey:`error`,funcs:{...df(),...bm(),...Xf(),...vp(),...nf(n),...Ku(),...wf(),...Qo(),...e===void 0?{}:Zo(e),...hg(),...gg(n),...t??{}}})}function vg(e){return yg(e,new Set(e.names()),``)}function yg(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.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return yg(e,t,a)}})}function bg(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(O(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function xg(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]}"`)}}async function Sg(e){let t=await _e({bin:`/bin/sh`,args:[`-c`,e],category:`user-shell`});return t.ok?{stdout:t.stdout,exitCode:t.exitCode??0}:{stdout:t.stdout,exitCode:t.exitCode??1}}async function Cg(e,t,n){let r;try{r=await C(e,`utf8`)}catch{return{error:`file unreadable: ${e}`}}if(n!==void 0){let t=new RegExp(n).exec(r);return t?.[1]?{content:t[1].replace(/\n/g,` `)}:{error:`regex no-match in "${e}"`}}return t===`first-line`?{content:(r.split(`
101
+ `)[0]??``).trim()}:{content:r.replace(/\n/g,` `).trim()}}const wg=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],Tg=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],Eg=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],Dg=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function Og(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>wg[e.getMonth()]],[`Monday`,e=>Eg[e.getDay()]],[`Jan`,e=>Tg[e.getMonth()]],[`Mon`,e=>Dg[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 kg={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function Ag(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=kg[t];try{return Pg(r,e)}catch{return Fg(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return Bt(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return Bt(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return Bt(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return Bt(e.stashCount,0)}}var jg=class{watchers=new Map;subscribe(e,t){let n=this.watchers.get(e);if(!n){let t=new Set,r;try{r=a(e,()=>{for(let e of t)e()})}catch{return()=>{}}n={watcher:r,callbacks:t},this.watchers.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.callbacks.delete(t),n.callbacks.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}},Mg=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:re(()=>{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&&(ne(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())ne(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function Ng(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function Pg(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`?tg(e):t===`number`?ng(e):rg(e)}function Fg(e){return e===`number`?0:e===`boolean`?!1:``}var Ig=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new jg;ttlMgr=new Mg;gitSubscriptions=new Map;cleanups=[];inFlight=new Set;engine=_g();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new an({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,eg(t),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){let r=bg(e,n.cache);this.store.defineBox(e,`string`,this.stringInitial(n.varDefault));let i=()=>void this.updateFromShell(e,t,n.regex,n.varDefault);i(),this.registerCachePolicy(e,r,i)}declareFile(e,t,n){this.store.defineBox(e,`string`,this.stringInitial(n.varDefault));let r=()=>void this.updateFromFile(e,t,n.readMode,n.regex,n.varDefault);r(),this.registerCachePolicy(e,n.cache,r)}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.store.defineComputed(e,`string`,t=>{let i=vg(this.store);try{let t=r.evaluate(i).map(e=>e.plain).join(``);return this.lastErrors.delete(e),t}catch(t){return this.recordError(e,t instanceof Error?t.message:String(t)),this.stringInitial(n.varDefault)}}),this.store.read(e)}declareTime(e,t){let n=t.ttlMs??1e3;this.store.defineBox(e,`string`,(e=>{try{return Og(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,Og(t.format,new Date)),this.lastErrors.delete(e)}catch(n){this.applyFallback(e,`string`,t.varDefault,n instanceof Error?n.message:String(n))}});this.cleanups.push(r)}declareGit(e,t){let n=kg[t.field],r=t.varDefault===void 0?Fg(n):Pg(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map;i={fieldSubs:e,unsubscribe: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,Ag(t,n,i,this.defaultEmptyValue))})})},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})}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(`session.id`);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=Ng(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,Pg(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`)}})}getLastError(e){return this.lastErrors.get(e)}dispose(){for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.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 e=this.watchMgr.subscribe(t.path,n);this.cleanups.push(e);break}case`key`:{let e=this.engine.parse(t.template),r=(0,X.reaction)(()=>{let t=vg(this.store);try{return e.evaluate(t).map(e=>e.plain).join(``)}catch{return``}},n);this.cleanups.push(r);break}case`depends_on`:{let e=(0,X.reaction)(()=>t.varNames.map(e=>String(this.store.read(e))).join(`,`),n);this.cleanups.push(e);break}}}async updateFromShell(e,t,n,r){if(!this.inFlight.has(e)){this.inFlight.add(e);try{let{stdout:i,exitCode:a}=await Sg(t);if(a!==0){this.applyFallback(e,`string`,r,`shell "${t}" exited with code ${a}`);return}if(n!==void 0){let a=new RegExp(n).exec(i);if(!a?.[1]){this.applyFallback(e,`string`,r,`regex no-match in output of "${t}"`);return}this.store.setBox(e,a[1].replace(/\n/g,` `))}else this.store.setBox(e,i.replace(/\n/g,` `).trim());this.lastErrors.delete(e)}finally{this.inFlight.delete(e)}}}async updateFromFile(e,t,n,r,i){if(!this.inFlight.has(e)){this.inFlight.add(e);try{let a=await Cg(t,n,r);if(a.error!==void 0){this.applyFallback(e,`string`,i,a.error);return}this.store.setBox(e,a.content??``),this.lastErrors.delete(e)}finally{this.inFlight.delete(e)}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,Pg(this.defaultEmptyValue,t))}catch{this.store.setBox(e,Fg(t))}}defaultFor(e){try{return Pg(this.defaultEmptyValue,e)}catch{return Fg(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})}};function Lg(e,t){switch(e){case`capsule`:return new Aa;case`plain`:return new ja(t===void 0?{}:{separator:t});case`powerline`:return new ka;default:return e}}function Rg(e,t){if(e.length===0)return``;let n=Lg(t.style,t.separator);if(Number.isFinite(t.width)){let r=Pa(new Ka([...e],{joiner:n}),{width:t.width,colorSystem:t.colorCompatibility});return r.endsWith(`
102
+ `)?r.slice(0,-1):r}return Pa(new wa([...e],n),{colorSystem:t.colorCompatibility})}const zg=new Map,Bg=new Map;function Vg(e){let t=es(e),n=zg.get(t);if(n!==void 0)return n;let r=Hi(t);if(r===null)throw Error(`Palette "${e}" (resolved "${t}") did not resolve in the theme registry — allowed names and the registry are inconsistent`);let i=new Fi(r);return zg.set(t,i),i}function Hg(e,t){let n=`${e.palette.name} ${t}`,r=Bg.get(n);if(r!==void 0)return r;let i={hueShift:t,chromaScale:1,lightnessScale:1,lightnessShift:0},a=new Fi(ea(e.palette,i));return Bg.set(n,a),a}function Ug(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=Wg(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=Wg([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function Wg(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>Gg(e,t)):e,r=Ca.fromFragments(n);return r.end=``,r.noWrap=!0,n.length===1?r.style=n[0].style:t!==void 0&&!t.isNull&&(r.style=t),r}function Gg(e,t){let n=e.copy();return n.style=t.add(e.style),n}function Kg(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function qg(e,t){let n=Ca.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function Jg(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o}=t;if(e.length===0)return[];let s=qg(e,o);return n===`auto`||(s.cellLength>n?s.truncate(n,{mode:i,marker:a}):s.cellLength<n&&s.align(r,n)),[s]}var Yg=class extends Error{constructor(e,t){super(`Invalid ${t} color spec: ${JSON.stringify(e)}`),this.name=`ColorSpecError`}};function Xg(e,t,n,r){let i=Zg(t,r),a=i===void 0?void 0:Qg(e,i,void 0,`bg`),o=Zg(n,r),s=o===void 0?void 0:Qg(e,o,a,`fg`);return new q({bgcolor:a===void 0?void 0:G.fromRgba(a),color:s===void 0?void 0:G.fromRgba(s)})}function Zg(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function Qg(e,t,n,r){let i=e.resolve(t.trim(),n===void 0?void 0:{against:n});if(i===null)throw new Yg(t,r);return i}function $g(e){return e===`themes`?rs():is}function e_(e,t,n){let r=new Map;for(let[i,a]of Object.entries(t))r.set(i,t_(e,i,a,n));return r}function t_(e,t,n,r){if(`set`in n){let e=r.get(n.set)??n.set;return`to`in n?{kind:`set-literal`,key:n.set,value:n.to,stateVar:e}:`from`in n?{kind:`set-option`,key:n.set,stateVar:e,options:[...$g(n.from)]}:`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}}return`copy`in n?{kind:`copy`,text:n_(e,n.copy,t)}:{kind:`open`,target:n_(e,n.open,t)}}function n_(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function r_(e,t){return e.has(t)?tg(e.read(t)):``}function i_(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function a_(e,t,n){let r=new Ca(e,{style:new q({link:t,bold:n})});return r.noWrap=!0,r.end=``,r}function o_(e,t){return Math.max(e.members.indexOf(r_(t,e.stateVar)),0)}function s_(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=r_(r,e.stateVar);return{effect:{verb:at,args:[i,e.key,e.value]},active:t===e.value}}case`set-option`:{let a=n??t,o=r_(r,e.stateVar);return{effect:{verb:at,args:[i,e.key,a]},active:o===a}}case`set-int`:{let a=n??t,o=r_(r,e.stateVar);return{effect:{verb:at,args:[i,e.key,a]},active:o===a}}case`set-cycle`:{let t=e.members[(o_(e,r)+1)%e.members.length];return{effect:{verb:at,args:[i,e.key,t]},active:!1}}case`set-bounded`:return{effect:{verb:ot,args:[i,e.key,String(e.by)]},active:!1};case`copy`:return{effect:{verb:st,args:[i_(e.text,vg(r))]},active:!1};case`open`:return{effect:{verb:ct,args:[i_(e.target,vg(r))]},active:!1}}}function c_(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`){if(n.length!==1&&n.length!==t.members.length)throw Error(`action "${e}" cycles ${t.members.length} members; bind one display per member (${t.members.length}) or one static display, got ${n.length}`);return{display:n.length===1?n[0]:n[o_(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]}}function l_(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}=c_(e,r,t,i),{effect:s,active:c}=s_(r,a,o,i,r_(i,`session.id`));return a_(a,pt([s]),c)}function u_(e){return{action:{fn:(t,...n)=>l_(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function d_(e){return new Ca(e).cellLength}function f_(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 p_(e,t){let n=[];for(let t of e)n.length>0&&n.push(new Ca(` `)),n.push(t);let r=Ca.fromFragments(n);return r.noWrap=t,r.end=``,r}function m_(e,t,n,r){let i=e.compiled.get(t);if(!i||i.kind!==n)throw Error(`picker references action "${t}" which must be ${r}, got ${i?`a ${i.kind} action`:`no such action`}`);return i}function h_(e,t,n,r,i){let a=m_(i,e,`set-option`,`a set-option action ({ set, from })`),o=m_(i,t,`set-int`,`an int action ({ set, int: true })`),s=i.store,c=r_(s,`session.id`),l=r_(s,a.stateVar),u=a.options.map(d_),d=r?ng(s.read(`term.cols`)):1/0,f=d_(`✕`)+1,p=d_(`←`)+1+d_(`→`)+1,m=f_(u,d,f),h=m.length>1?f_(u,d,f+p):m,g=parseInt(r_(s,o.stateVar),10),_=Number.isInteger(g)?Math.max(0,Math.min(g,h.length-1)):0,v=h[_]??[],y=e=>pt([{verb:at,args:[c,o.key,String(e)]}]),b=e=>pt([{verb:at,args:[c,a.key,e,...n?[o.key,`-1`]:[]]}]),x=[a_(`✕`,y(-1),!1)];_>0&&x.push(a_(`←`,y(_-1),!1));for(let e of v){let t=a.options[e];x.push(a_(t,b(t),t===l))}return _<h.length-1&&x.push(a_(`→`,y(_+1),!1)),p_(x,r)}function g_(e){return{picker:{fn:(t,n,r,i)=>h_(t,n,r===!0,i===!0,e),argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const __=Symbol(`cc-candybar.menuDrop`);function v_(e){return e.flatMap(e=>e[__]??[])}function y_(e,t,n,r,i,a){let o=a.current;if(o===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let s=a.action,c=Tm(o.segName,e,i),l=wm(e),u=l_(Em(c,l),[`▸`,`▾`],s);return u[__]=r_(s.store,c)===l?[h_(e,t,n,r,s)]:[],u}function b_(e){return{menu:{fn:(t,n,r,i,a)=>y_(t,n,r===!0,i===!0,a,e),argTypes:[`string`,`string`,`bool`,`bool`,`string`],returnType:`T`}}}function x_(e){let t=[],n=[];for(let r of e){if(!r.contains(`
104
103
  `)){n.push(r);continue}let e=r.split(`
105
- `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function v_(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?[]:[t.flatMap(e=>e[0]??[]),...t.flatMap(e=>e.slice(1))]}}const y_={container:{compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,children:e.children.map((e,n)=>t.compileChild(e,`${t.path}.children[${n}]`))}},render(e,t){return v_(e.direction,e.children.map(e=>t.renderChild(e,t.visible)))}},segment:{compile(e,t){return{kind:`segment`,when:t.when,name:e.name,rowKey:t.rowKeyByPath.get(t.path)??t.path}},render(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,a=t.nextHueShift();if(!t.visible)return[];try{if(!Wg(i.when,t.scope))return[];let n=Jg(Bg(i.paletteResolver??t.basePalette,a),i.bg,i.fg,t.scope),o=t.prepareSegment(e.name,e.rowKey,n),s=__(Vg(i.template.evaluate(t.scope),o)).map(e=>Kg(e,{width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:o}));return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.name,s.flat()),s}catch(t){return[[new Ca(`⚠ ${e.name}: ${t.message??String(t)}`)]]}}}};function b_(e){return y_[e]}function x_(e){if(`ttl`in e)return{kind:`ttl`,durationMs:yg(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 S_(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);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,regex:n.regex,cache:x_(n.cache),varDefault:n.default});break;case`shell`:e.declareShell(t,n.command,{regex:n.regex,cache:x_(n.cache),varDefault:n.default});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,ttlMs:n.cache?yg(n.cache.ttl):void 0,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 C_(e,t){let n=``;for(let[r,i]of Object.entries(t)){let t=`{{ define "${r}" }}${i}{{ end }}`;try{e.parse(t)}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}n+=t}return n}function w_(e,t,n){let r=n?.cwd??process.cwd(),i={store:t.variableStore,compiled:new Map},a={action:i,current:null},o=hg(void 0,{...c_(i),...m_(i),...g_(a)},n?.clock),s=C_(o,e.helpers),c=e=>o.parse(s+e),l=new Map;for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&!l.has(n.key)&&l.set(n.key,t);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&!l.has(r.key)&&l.set(r.key,`${t}.${e}`);i.compiled=Qg(c,e.actions,l);let u=[];for(let[n,i]of Object.entries(e.variables))try{S_(t,n,i,r)}catch(e){u.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{S_(t,`${n}.${e}`,a,r)}catch(t){u.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let d=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n)=>{try{return c(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};d[t]={when:n.when===void 0?void 0:e(n.when,`when`),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`),paletteResolver:n.palette===void 0?void 0:zg(n.palette)}}let f=(e,t,n)=>{try{return c(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},p=new Map;Em(e.root,(e,t,n)=>{p.set(n,t)});let m=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:f(e.when,t,`when`),rowKeyByPath:p,compileChild:m};return b_(e.kind).compile(e,n)};return{segments:d,root:m(e.root,`root`),menuRuntime:a,loadWarnings:u}}function T_(e){let t=e.bgcolor;return t===void 0?e:new q({bgcolor:G.fromRgba(K(t.getTruecolor(),1)),color:e.color})}function E_(e,t,n,r,i,a,o,s){r.applyInput({...i,term:{cols:o.width}});let c=gg(n),l=n.has(`hue.step`)?Number(n.read(`hue.step`)):0,u=Number.isFinite(l)?l:0;s?.clear();let d={value:0},f=()=>{let e=d.value*u;return d.value+=1,e},p=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},m=(e,r,i)=>{t.menuRuntime.current={rowKey:r,segName:e};let a=Cm(r);return n.has(a)&&t_(n,a)===e?T_(i):i},h=(e,t)=>{let n={scope:c,basePalette:a,visible:t&&Wg(e.when,c),nextHueShift:f,perSegmentSink:s,prepareSegment:m,lookupSegment:p,renderChild:h};return b_(e.kind).render(e,n)};return h(t.root,!0).map(e=>Ig(e,o)).join(`
106
- `)}const D_=If(),O_=new Set(D_),k_=new Set(Lf),A_=e=>e?O_.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${D_.join(`, `)})`}:{ok:!1,reason:`theme name is required`},j_=e=>e?k_.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${Lf.join(`, `)})`}:{ok:!1,reason:`style name is required`},M_=new Set([`1`,`true`]),N_=new Set([`0`,`false`]),P_=new Map([[`style`,{validator:j_,permanent:!0}],[`theme`,{validator:A_,permanent:!0}],[`toolbar-expanded`,{validator:e=>M_.has(e)?{ok:!0,value:`1`}:N_.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`},permanent:!0}]]);function F_(){return[...P_.keys()]}function I_(e,t,n){if(t===`int`)return V_(`menu page "${e}"`);if(t===`range`){let t=n.flatMap(e=>e.kind===`range`?[e.min]:[]),r=n.flatMap(e=>e.kind===`range`?[e.max]:[]);return H_(Math.min(...t),Math.max(...r),`stepper "${e}"`)}return z_([...new Set(n.flatMap(e=>e.kind===`allow-list`?e.allowed:[]))],`state "${e}"`)}function L_(e,t){if(!e)throw Error(`registerStateValidator: key is required`);if(e.includes(`/`))throw Error(`registerStateValidator: key "${e}" contains "/" — the set-state wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);let n=P_.get(e);if(n){if(n.permanent)throw Error(`registerStateValidator: key "${e}" is a built-in state key and cannot be re-claimed (built-in keys: ${[...R_()].join(`, `)})`);if(n.kind!==t.kind)throw Error(`registerStateValidator: key "${e}" is already a ${n.kind} state key; cannot also register it as ${t.kind}. A state key has one key shape — a menu page index (int) and a button allow-list cannot share a key.`);n.specs.push(t),n.validator=I_(e,n.kind,n.specs)}else{let n=[t];P_.set(e,{permanent:!1,kind:t.kind,validator:I_(e,t.kind,n),specs:n})}let r=!0;return()=>{if(!r)return;r=!1;let n=P_.get(e);if(!n||n.permanent)return;let i=n.specs.indexOf(t);i>=0&&n.specs.splice(i,1),n.specs.length===0?P_.delete(e):n.validator=I_(e,n.kind,n.specs)}}function R_(){let e=[];for(let[t,n]of P_)n.permanent&&e.push(t);return e}function z_(e,t){let n=e.filter(e=>e.includes(`/`));if(n.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the set-state wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${n.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 r=new Set(e),i=[...e];return e=>e?r.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${i.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}const B_=/^-?\d+$/;function V_(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!B_.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 H_(e,t,n){return r=>r?B_.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 U_(e){return e===`themes`?D_:Lf}function W_(e,t){let n=t.filter(e=>e.kind===`range`),r=t.some(e=>e.kind===`int`),i=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(n.length===0&&!r)return{kind:`allow-list`,allowed:[...new Set(i)]};let a=i.filter(e=>!B_.test(e));if(a.length>0)throw Error(`deriveActionValidators: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${a.join(`, `)}). A state key has one key shape — point that click at a distinct key, or write an integer.`);if(r&&n.length>0)throw Error(`deriveActionValidators: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a state key has one key shape. Use distinct keys.`);if(n.length>0){let t=Math.min(...n.map(e=>e.min)),r=Math.max(...n.map(e=>e.max)),a=i.filter(e=>{let n=parseInt(e,10);return n<t||n>r});if(a.length>0)throw Error(`deriveActionValidators: key "${e}" is a bounded range [${t},${r}] but a click writes out-of-range value(s) to it (${a.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:r,seed:J_(n[0].seed,t,r)}}return{kind:`int`}}function G_(e){let t=new Set(R_());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function K_(e){let t=new Map;for(let{key:n,spec:r}of e){let e=t.get(n);e?e.push(r):t.set(n,[r])}return[...t].map(([e,t])=>({key:e,spec:W_(e,t)}))}function q_(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:U_(e.from)}}]:`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,seed:J_(t.get(e.set),e.min,e.max)}}]:[]}function J_(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function Y_(e){let t=new Map;for(let n of Object.values(e.variables)){if(n.kind!==`state`)continue;let e=n.default;e!==void 0&&B_.test(e)&&t.set(n.key,parseInt(e,10))}return t}function X_(e){let t=Y_(e);return G_(Object.values(e.actions).flatMap(e=>q_(e,t)))}function Z_(e){return K_(X_(e))}function Q_(e,t){let n=P_.get(e);return n?n.validator(t):{ok:!1,reason:`unknown state key "${e}" (have: ${F_().join(`, `)})`}}function $_(e){let t=P_.get(e);if(!t||t.permanent||t.kind!==`range`)return null;let n=t.specs.flatMap(e=>e.kind===`range`?[e]:[]);if(n.length===0)return null;let r=Math.min(...n.map(e=>e.min)),i=Math.max(...n.map(e=>e.max));return{min:r,max:i,seed:J_(n[0].seed,r,i)}}var ev=class{kind=`box`;cell;lastSetAt;constructor(e,t,n){this.name=e,this.type=t,nv(e,t,n,`initial value`),this.cell=X.observable.box(n,{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){nv(this.name,this.type,e,`set value`),this.cell.set(e),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}},tv=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,X.computed)(()=>{let e=n();return nv(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}};function nv(e,t,n,r){let i=Qh(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var rv=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new ev(e,t,n))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new tv(e,t,()=>n(r)))}read(e){return this.requireNode(e).read()}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,X.runInAction)(()=>n.set(t))}runInAction(e){(0,X.runInAction)(e)}has(e){return this.nodes.has(e)}getType(e){return this.requireNode(e).type}getKind(e){return this.requireNode(e).kind}getNode(e){let t=this.requireNode(e);return{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}assertNotDefined(e){if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`)}};function iv(e,t,n){return e+`\0`+t+`\0`+(n??``)}var av=class{entries=new Map;deps;maxEntries;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256}getOrCreate(e,t,n){let r=iv(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:null,lastWarning:null,state:null,watcher:null};if(this.reloadInto(a),this.entries.set(r,a),this.entries.size>this.maxEntries){let e=this.entries.keys().next().value;if(e!==void 0){let t=this.entries.get(e);t?.state?.registry.dispose(),t?.state?.validatorDisposers.forEach(e=>e()),t?.watcher?.release(),this.entries.delete(e)}}return a}reloadInto(e){let t=Th(e.projectDir,e.cwd,e.configFile);e.lastWarning=Eh(e.projectDir,e.cwd);let n;try{n=this.buildState(e,t)}catch(n){e.lastError=n instanceof Bf||n instanceof Error?n.message:String(n),this.refreshWatcher(e,t);return}if(e.state?.registry.dispose(),e.state?.validatorDisposers.forEach(e=>e()),e.lastError=null,e.state=n,n.compiled.loadWarnings.length>0){let t=n.compiled.loadWarnings.join(`
104
+ `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function S_(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?[]:[t.flatMap(e=>e[0]??[]),...t.flatMap(e=>e.slice(1))]}}const C_={container:{compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,children:e.children.map((e,n)=>t.compileChild(e,`${t.path}.children[${n}]`))}},render(e,t){return S_(e.direction,e.children.map(e=>t.renderChild(e,t.visible)))}},segment:{compile(e,t){return{kind:`segment`,when:t.when,name:e.name}},render(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,a=t.nextHueShift();if(!t.visible)return[];try{if(!Kg(i.when,t.scope))return[];t.beginSegment(e.name);let n=i.template.evaluate(t.scope),o=t.collectDrops(n),s=Xg(Hg(i.paletteResolver??t.basePalette,a),i.bg,i.fg,t.scope),c=o.length>0?t.focusTint(s):s,l={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:c},u=x_(Ug(n,c)).map(e=>Jg(e,l)),d=o.map(e=>Jg(Ug([e],c),l)),f=[...u,...d];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.name,f.flat()),f}catch(t){return[[new Ca(`⚠ ${e.name}: ${t.message??String(t)}`)]]}}}};function w_(e){return C_[e]}function T_(e){if(`ttl`in e)return{kind:`ttl`,durationMs:xg(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 E_(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);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,regex:n.regex,cache:T_(n.cache),varDefault:n.default});break;case`shell`:e.declareShell(t,n.command,{regex:n.regex,cache:T_(n.cache),varDefault:n.default});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,ttlMs:n.cache?xg(n.cache.ttl):void 0,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 D_(e,t){let n=``;for(let[r,i]of Object.entries(t)){let t=`{{ define "${r}" }}${i}{{ end }}`;try{e.parse(t)}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}n+=t}return n}function O_(e,t,n){let r=n?.cwd??process.cwd(),i={store:t.variableStore,compiled:new Map},a={action:i,current:null},o=_g(void 0,{...u_(i),...g_(i),...b_(a)},n?.clock),s=D_(o,e.helpers),c=e=>o.parse(s+e),l=new Map;for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&!l.has(n.key)&&l.set(n.key,t);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&!l.has(r.key)&&l.set(r.key,`${t}.${e}`);i.compiled=e_(c,e.actions,l);let u=[];for(let[n,i]of Object.entries(e.variables))try{E_(t,n,i,r)}catch(e){u.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{E_(t,`${n}.${e}`,a,r)}catch(t){u.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let d=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n)=>{try{return c(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};d[t]={when:n.when===void 0?void 0:e(n.when,`when`),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`),paletteResolver:n.palette===void 0?void 0:Vg(n.palette)}}let f=(e,t,n)=>{try{return c(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},p=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:f(e.when,t,`when`),compileChild:p};return w_(e.kind).compile(e,n)};return{segments:d,root:p(e.root,`root`),menuRuntime:a,loadWarnings:u}}function k_(e){let t=e.bgcolor;return t===void 0?e:new q({bgcolor:G.fromRgba(K(t.getTruecolor(),1)),color:e.color})}function A_(e,t,n,r,i,a,o,s){r.applyInput({...i,term:{cols:o.width}});let c=vg(n),l=n.has(`hue.step`)?Number(n.read(`hue.step`)):0,u=Number.isFinite(l)?l:0;s?.clear();let d={value:0},f=()=>{let e=d.value*u;return d.value+=1,e},p=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},m=e=>{t.menuRuntime.current={segName:e}},h=e=>(t.menuRuntime.current=null,v_(e)),g=(e,t)=>{let n={scope:c,basePalette:a,visible:t&&Kg(e.when,c),nextHueShift:f,perSegmentSink:s,beginSegment:m,collectDrops:h,focusTint:k_,lookupSegment:p,renderChild:g};return w_(e.kind).render(e,n)};return g(t.root,!0).map(e=>Rg(e,o)).join(`
105
+ `)}const j_=rs(),M_=new Set(j_),N_=new Set(is),P_=e=>e?M_.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${j_.join(`, `)})`}:{ok:!1,reason:`theme name is required`},F_=e=>e?N_.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${is.join(`, `)})`}:{ok:!1,reason:`style name is required`},I_=new Set([`1`,`true`]),L_=new Set([`0`,`false`]),R_=new Map([[`style`,{validator:F_,permanent:!0}],[`theme`,{validator:P_,permanent:!0}],[`toolbar-expanded`,{validator:e=>I_.has(e)?{ok:!0,value:`1`}:L_.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`},permanent:!0}]]);function z_(){return[...R_.keys()]}function B_(e,t,n){if(t===`int`)return G_(`menu page "${e}"`);if(t===`range`){let t=n.flatMap(e=>e.kind===`range`?[e.min]:[]),r=n.flatMap(e=>e.kind===`range`?[e.max]:[]);return K_(Math.min(...t),Math.max(...r),`stepper "${e}"`)}return U_([...new Set(n.flatMap(e=>e.kind===`allow-list`?e.allowed:[]))],`state "${e}"`)}function V_(e,t){if(!e)throw Error(`registerStateValidator: key is required`);if(e.includes(`/`))throw Error(`registerStateValidator: key "${e}" contains "/" — the set-state wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);let n=R_.get(e);if(n){if(n.permanent)throw Error(`registerStateValidator: key "${e}" is a built-in state key and cannot be re-claimed (built-in keys: ${[...H_()].join(`, `)})`);if(n.kind!==t.kind)throw Error(`registerStateValidator: key "${e}" is already a ${n.kind} state key; cannot also register it as ${t.kind}. A state key has one key shape — a menu page index (int) and a button allow-list cannot share a key.`);n.specs.push(t),n.validator=B_(e,n.kind,n.specs)}else{let n=[t];R_.set(e,{permanent:!1,kind:t.kind,validator:B_(e,t.kind,n),specs:n})}let r=!0;return()=>{if(!r)return;r=!1;let n=R_.get(e);if(!n||n.permanent)return;let i=n.specs.indexOf(t);i>=0&&n.specs.splice(i,1),n.specs.length===0?R_.delete(e):n.validator=B_(e,n.kind,n.specs)}}function H_(){let e=[];for(let[t,n]of R_)n.permanent&&e.push(t);return e}function U_(e,t){let n=e.filter(e=>e.includes(`/`));if(n.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the set-state wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${n.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 r=new Set(e),i=[...e];return e=>e?r.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${i.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}const W_=/^-?\d+$/;function G_(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!W_.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 K_(e,t,n){return r=>r?W_.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 q_(e){return e===`themes`?j_:is}function J_(e,t){let n=t.filter(e=>e.kind===`range`),r=t.some(e=>e.kind===`int`),i=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(n.length===0&&!r)return{kind:`allow-list`,allowed:[...new Set(i)]};let a=i.filter(e=>!W_.test(e));if(a.length>0)throw Error(`deriveActionValidators: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${a.join(`, `)}). A state key has one key shape — point that click at a distinct key, or write an integer.`);if(r&&n.length>0)throw Error(`deriveActionValidators: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a state key has one key shape. Use distinct keys.`);if(n.length>0){let t=Math.min(...n.map(e=>e.min)),r=Math.max(...n.map(e=>e.max)),a=i.filter(e=>{let n=parseInt(e,10);return n<t||n>r});if(a.length>0)throw Error(`deriveActionValidators: key "${e}" is a bounded range [${t},${r}] but a click writes out-of-range value(s) to it (${a.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:r,seed:Q_(n[0].seed,t,r)}}return{kind:`int`}}function Y_(e){let t=new Set(H_());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function X_(e){let t=new Map;for(let{key:n,spec:r}of e){let e=t.get(n);e?e.push(r):t.set(n,[r])}return[...t].map(([e,t])=>({key:e,spec:J_(e,t)}))}function Z_(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:q_(e.from)}}]:`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,seed:Q_(t.get(e.set),e.min,e.max)}}]:[]}function Q_(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function $_(e){let t=new Map;for(let n of Object.values(e.variables)){if(n.kind!==`state`)continue;let e=n.default;e!==void 0&&W_.test(e)&&t.set(n.key,parseInt(e,10))}return t}function ev(e){let t=$_(e);return Y_(Object.values(e.actions).flatMap(e=>Z_(e,t)))}function tv(e){return X_(ev(e))}function nv(e,t){let n=R_.get(e);return n?n.validator(t):{ok:!1,reason:`unknown state key "${e}" (have: ${z_().join(`, `)})`}}function rv(e){let t=R_.get(e);if(!t||t.permanent||t.kind!==`range`)return null;let n=t.specs.flatMap(e=>e.kind===`range`?[e]:[]);if(n.length===0)return null;let r=Math.min(...n.map(e=>e.min)),i=Math.max(...n.map(e=>e.max));return{min:r,max:i,seed:Q_(n[0].seed,r,i)}}var iv=class{kind=`box`;cell;lastSetAt;constructor(e,t,n){this.name=e,this.type=t,ov(e,t,n,`initial value`),this.cell=X.observable.box(n,{deep:!1}),this.lastSetAt=Date.now()}read(){return this.cell.get()}set(e){ov(this.name,this.type,e,`set value`),this.cell.set(e),this.lastSetAt=Date.now()}lastUpdatedMs(){return this.lastSetAt}},av=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,X.computed)(()=>{let e=n();return ov(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}};function ov(e,t,n,r){let i=eg(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var sv=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new iv(e,t,n))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new av(e,t,()=>n(r)))}read(e){return this.requireNode(e).read()}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,X.runInAction)(()=>n.set(t))}runInAction(e){(0,X.runInAction)(e)}has(e){return this.nodes.has(e)}getType(e){return this.requireNode(e).type}getKind(e){return this.requireNode(e).kind}getNode(e){let t=this.requireNode(e);return{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}assertNotDefined(e){if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`)}};function cv(e,t,n){return e+`\0`+t+`\0`+(n??``)}var lv=class{entries=new Map;deps;maxEntries;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256}getOrCreate(e,t,n){let r=cv(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:null,lastWarning:null,state:null,watcher:null};if(this.reloadInto(a),this.entries.set(r,a),this.entries.size>this.maxEntries){let e=this.entries.keys().next().value;if(e!==void 0){let t=this.entries.get(e);t?.state?.registry.dispose(),t?.state?.validatorDisposers.forEach(e=>e()),t?.watcher?.release(),this.entries.delete(e)}}return a}reloadInto(e){let t=Dh(e.projectDir,e.cwd,e.configFile);e.lastWarning=Oh(e.projectDir,e.cwd);let n;try{n=this.buildState(e,t)}catch(n){e.lastError=n instanceof ss||n instanceof Error?n.message:String(n),this.refreshWatcher(e,t);return}if(e.state?.registry.dispose(),e.state?.validatorDisposers.forEach(e=>e()),e.lastError=null,e.state=n,n.compiled.loadWarnings.length>0){let t=n.compiled.loadWarnings.join(`
107
106
  `);e.lastWarning=e.lastWarning?e.lastWarning+`
108
- `+t:t}this.refreshWatcher(e,t)}buildState(e,t){let{config:n,source:r}=Dh(t),i=Oh(n,t??`<default>`,r),a=new rv,o=new Pg(a,i.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),s,c=[];try{s=w_(i,o,{cwd:e.cwd});for(let{key:e,spec:t}of Z_(i))c.push(L_(e,t))}catch(e){for(let e of c)e();throw o.dispose(),e}return{config:i,store:a,registry:o,compiled:s,neededInputPaths:Wh(i),lastRenderCellsBySegment:new Map,validatorDisposers:c}}refreshWatcher(e,t){(t!==e.configFilePath||e.watcher===null)&&(e.configFilePath=t,this.rebindWatcher(e,t))}rebindWatcher(e,t){e.watcher&&=(e.watcher.release(),null);let r=wh(e.projectDir,e.cwd,e.configFile),i=new Map;for(let e of r){let t=o.dirname(e);if(!n.existsSync(t))continue;let r=o.basename(e);i.has(t)||i.set(t,new Set),i.get(t).add(r)}let a=[...i.entries()].map(([e,t])=>({path:e,filenames:[...t]})),s=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${t??`<none>`}`;e.watcher=this.deps.watchers.acquire(s,{files:t===null?[]:[t],dirs:a},()=>this.onConfigChanged(e))}onConfigChanged(e){N(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstPopulatedState(){for(let e of this.entries.values())if(e.state!==null)return e.state;return null}};const ov=16384;var sv=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<ov){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%ov}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: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},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null}}};const cv=(parseInt(process.env.CC_CANDYBAR_RSS_LIMIT_MB??``,10)||512)*1024*1024;function lv(e){let t=e.rssLimitBytes??cv,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let i=e.rssBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t}; writing heap snapshot then shutting down`);try{let t=new Date(e.now()).toISOString().replace(/[:.]/g,`-`),r=o.join(e.snapshotDir,`heap-${t}-${e.pid}.heapsnapshot`),i=e.writeHeapSnapshot(r);e.log(`info`,`heap snapshot written: ${i}`),uv(e.listSnapshots(),n,e.removeFile)}catch(t){e.log(`warn`,`heap snapshot failed: ${t.message}`)}return e.shutdown(0),!0}function a(){let n=e.rssBytes();return n>t*.75?`rss ${n} approaching limit ${t}`:null}function s(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:s}}function uv(e,t,n){let r=[...e].sort((e,t)=>{let n=e.slice(e.lastIndexOf(`/`)+1);return t.slice(t.lastIndexOf(`/`)+1).localeCompare(n)});for(let e of r.slice(t))try{n(e)}catch{}}function dv(e,t,r={}){let i=we();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:N,rssBytes:()=>process.memoryUsage().rss,writeHeapSnapshot:e=>ie.writeHeapSnapshot(e),listSnapshots:()=>{try{return n.readdirSync(i).filter(e=>e.startsWith(`heap-`)&&e.endsWith(`.heapsnapshot`)).map(e=>o.join(i,e))}catch{return[]}},removeFile:e=>n.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}const fv=`CC_CANDYBAR_PARENT_PID`;function pv(e){let t=e[fv];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${fv} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function mv(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor,n=setInterval(()=>{e.isAlive(t)||e.onOrphaned(`spawner pid ${t} gone`)},e.intervalMs??1e3);return n.unref(),{disarm:()=>clearInterval(n)}}function hv(t){try{return e.kill(t,0),!0}catch(e){return e.code===`EPERM`}}const gv={load:()=>({}),save:()=>{},flush:()=>{}};function _v(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var vv=class{sessions;storage;atom=(0,X.createAtom)(`SessionState`);constructor(e=gv,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=_v(this.storage.load()),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.get(t)??null):null}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,X.runInAction)(()=>{let n=this.sessions.get(e)??new Map;for(let{key:e,value:r}of t)n.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,X.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.delete(t),n.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,X.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,n]of this.sessions)e[t]=Object.fromEntries(n);return e}};const yv=(e,t)=>O(t);function bv(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 xv=class{timer=null;pending=null;constructor(e,t=500,n=yv){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=n.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 bv(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{n.mkdirSync(o.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;n.writeFileSync(t,JSON.stringify(e),{mode:384}),n.chmodSync(t,384),n.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}},Sv=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};function Cv(e){if(!e)throw new Sv(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new Sv(`invalid session id "${e}"`);return e}function wv(e){return Tv(()=>decodeURIComponent(e))}function Tv(e){try{return e()}catch(e){throw e instanceof URIError?new Sv(`malformed wire encoding: ${e.message}`):e}}function Ev(e,t){let n=ve({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 Dv=(e,t)=>Ev(wv(e),t),Ov=(e,t)=>{let n=ve({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,wv(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`})`)}},kv=(e,t)=>Ev(wv(e),t),Av=(e,t)=>Ev(wv(e),t),jv=(e,t)=>{let n=Cv(wv(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},Mv=(e,t)=>{let[n=``,...r]=Tv(()=>ft(e)),i=Cv(n);if(r.length===0)throw new Sv(`set-state: <key>/<value> is required (have keys: ${F_().join(`, `)})`);if(r.length%2!=0)throw new Sv(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${F_().join(`, `)})`);let a=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new Sv(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=Q_(t,n);if(!i.ok)throw new Sv(`set-state: pair ${e/2+1}: ${i.reason}`);a.push({key:t,value:i.value})}t.sessionState.setBatch(i,a);let o=a.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${o} (session=${i})`)},Nv=/^-?\d+$/;function Pv(e,t,n){return e>n?t:e<t?n:e}const Fv=(e,t)=>{let[n=``,r=``,i=``]=Tv(()=>ft(e)),a=Cv(n);if(!r)throw new Sv(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!Nv.test(i))throw new Sv(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=$_(r);if(!s)throw new Sv(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${F_().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&Nv.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=Pv(l+o,s.min,s.max),d=Q_(r,String(u));if(!d.ok)throw new Sv(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)},Iv=`config-override`,Lv=new Map([[st,Dv],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new Sv(`load-config: expected <sessionId>/<path> (missing separator)`);let r=Cv(Tv(()=>decodeURIComponent(e.slice(0,n)))),i=Tv(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new Sv(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new Sv(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,Iv),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,Iv,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[ct,Ov],[at,Mv],[ot,Fv],[lt,kv],[ut,Av],[`toolbar-toggle`,jv]]),Rv=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of mt(e)){if(!i&&(a===`set-state`||a===`step-state`||a===`toolbar-toggle`)){let e=ft(o);e.length>0&&e[0]&&(i=e[0])}let e=Lv.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof Sv||(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(`
109
- `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new Sv(e)}},zv=new Map([...Lv,[it,Rv]]);Object.freeze([...zv.keys()]);const Bv=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`]),Vv=[[`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`]];function Hv(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of Vv){let i=Uv(n,e);if(i==null)t.missingRequired.push(e);else{let n=Array.isArray(i)?`array`:typeof i;(r===`object`?n!==`object`:n!==r)&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))Bv.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function Uv(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 Wv(e,t){switch(e){case`vars`:return{what:e,vars:Gv(t)};case`segments`:return{what:e,segments:Yv(t)};case`config`:return{what:e,config:Qv(t)}}}function Gv(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=qv(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=n.getLastError(e);o.push({name:e,source:i.get(e)??null,type:r.type,value:r.read(),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:Kv(r.lastUpdatedMs())})}return o}function Kv(e){return e===null?null:Math.max(0,Date.now()-e)}function qv(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,Jv(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}`,Jv(i));return t}function Jv(e){return e.kind}function Yv(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=Xv(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,template:t.template,referencedVars:Zv(t.template,i),lastRender:r.get(e)??null})}return o}function Xv(e){let t=[],n=new Set;for(let r of Pn(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 Zv(e,t){let n=new Set;for(let r of oh(e)){if(t.has(r)){n.add(r);continue}let e=r.split(`.`);for(;e.length>1;){e.pop();let r=e.join(`.`);if(t.has(r)){n.add(r);break}}}return Array.from(n).sort()}function Qv(e){return e===null?null:e.config}const $v=[`vars`,`segments`,`config`];function ey(e){return typeof e==`string`&&$v.includes(e)}function ty(e){return Math.max(1,e-2)}var ny=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 O(`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);O(`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{O(`Calculating context tokens from transcript: ${e}`);let n=await vn(e);if(n.length===0)return O(`No entries in transcript`),zt;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,O(`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 O(`Most recent main chain context: ${n} tokens (limit: ${t})`),P({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return O(`No main chain entries with usage data found`),zt}catch(e){return F(`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)}};function ry(e){let t=e.type||e.message?.role||e.message?.type,n=e.type===`user`&&e.message?.firstContentType===`tool_result`;return t===`user`&&!n}var iy=class{calculateMessageCount(e){return e.filter(ry).length}calculateLastResponseTime(e){if(e.length===0)return null;let t=e.slice(-20),n=null,r=null;for(let e of t){let t=e.type||e.message?.role||e.message?.type;if(ry(e))n=e.timestamp;else if(t===`assistant`&&n){let t=(e.timestamp.getTime()-n.getTime())/1e3;t>.1&&t<300&&(r=t)}}return r}async getMetricsInfo(e,t){try{if(O(`Getting metrics from hook data for session: ${e}`),!t.cost)return zt;let n=(await vn(t.transcript_path)).filter(e=>!e.isSidechain),r=this.calculateMessageCount(n),i=this.calculateLastResponseTime(n);return P({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:i,sessionDuration:t.cost.total_duration_ms/1e3,messageCount:r,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}catch(t){return F(`metrics (${e}): ${t instanceof Error?t.message:String(t)}`)}}};const ay=new Map;function oy(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var sy=class{async getSessionId(){if(!process.env.TMUX_PANE)return zt;let e=oy(process.env.TMUX),t=ay.get(e);if(t!==void 0)return t;O(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await _e({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?P(n.stdout.trim()):zt:F(`tmux display-message: ${n.reason}`);return ay.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}};function cy(e){return e<32||e===127||e>=128&&e<=159}function ly(e,t){let n=``;for(let t of e)n+=cy(t.codePointAt(0)??0)?` `:t;n=n.replace(/\s+/g,` `).trim();let r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const uy=`\x1B[38;2;255;255;255m`,dy=`\x1B[48;2;200;40;40m`,fy=`\x1B[0m`,py=new sv;k(py.launchStats);const my=new Qt({counters:py,logger:N}),hy=new an({watchers:my,logger:N}),gy=new Mn,_y=new vv,vy=new ny,yy=new iy,by=new sy,xy=new av({gitService:hy,sessionState:_y,watchers:my});function Sy(){n.mkdirSync(we(),{recursive:!0}),Ee(Te()),_y.useStorage(new xv(Oe(),500,N)),e.on(`uncaughtException`,e=>{N(`error`,`uncaughtException: ${e.stack||e.message}`),Fy(1)}),e.on(`unhandledRejection`,e=>{N(`error`,`unhandledRejection: ${String(e)}`),Fy(1)});for(let t of[`SIGINT`,`SIGTERM`,`SIGHUP`])e.on(t,()=>{N(`info`,`received ${t}, shutting down`),Fy(0)});mv({anchor:pv(e.env),isAlive:hv,onOrphaned:e=>{N(`info`,`parent watchdog: ${e}; shutting down`),Fy(0)}}),Cy(m.createServer({allowHalfOpen:!1},e=>{Iy(e)}),Te(),!1)}function Cy(t,n,r){t.removeAllListeners(`error`),t.once(`error`,i=>{if(i.code!==`EADDRINUSE`){N(`error`,`server error: ${i.message}`),Fy(1);return}if(r){N(`info`,`lost rebind race; another daemon is alive — exiting`),e.exit(0);return}wy(t,n)}),t.listen(n,()=>Dy(n))}async function wy(t,r){await Ey(r)&&(N(`info`,`another daemon is listening on socket — exiting`),e.exit(0)),await Ey(r)&&(N(`info`,`race: another daemon claimed the socket during recovery — exiting`),e.exit(0)),N(`warn`,`stale socket from crashed daemon — unlinking and rebinding`);try{n.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){N(`error`,`cannot unlink stale socket ${r}: ${e.message}`),Fy(1);return}}Cy(t,r,!0)}function Ty(e){return new Promise(t=>{let n=m.connect(e),r=!1,i=null,a=e=>{r||(r=!0,i&&clearTimeout(i),n.removeAllListeners(),n.destroy(),t(e))};n.once(`connect`,()=>a(`alive`)),n.once(`error`,e=>{let t=e.code;a(t===`ECONNREFUSED`||t===`ENOENT`||t===`ENOTSOCK`?`dead`:`unknown`)}),i=setTimeout(()=>a(`unknown`),50),i.unref()})}async function Ey(e){return await Ty(e)!==`dead`}function Dy(t){try{n.chmodSync(t,384)}catch(e){N(`warn`,`chmod socket failed: ${e.message}`)}jy(),N(`info`,`daemon up: pid=${e.pid} v=3 sock=${t}`),Oy(),Ay()}function Oy(){let t=import.meta.url,r=[];t.startsWith(`file://`)&&r.push(_(t)),e.argv[1]&&r.push(e.argv[1]);let i=new Map;for(let e of r)try{i.set(e,n.statSync(e).mtimeMs)}catch{}if(i.size===0)return;let a=setInterval(()=>{for(let[e,t]of i)try{if(n.statSync(e).mtimeMs!==t){N(`info`,`binary mtime changed (${e}); shutting down`),clearInterval(a),Fy(0);return}}catch(e){N(`warn`,`bin stat failed: ${e.message}`)}},6e4);a.unref()}let ky=null;function Ay(){ky=lv(dv(py.startedAt.getTime(),e=>Fy(e))),ky.arm()}function jy(){let t=JSON.stringify({pid:e.pid,version:3,binPath:e.argv[1],startedAt:new Date().toISOString()});try{n.writeFileSync(De(),t,{mode:384}),n.chmodSync(De(),384)}catch(e){N(`warn`,`pidfile write failed: ${e.message}`)}}function My(){try{n.unlinkSync(De())}catch{}}let Ny=0,Py=!1;function Fy(t){if(!Py){Py=!0,setTimeout(()=>e.kill(e.pid,`SIGKILL`),500);try{hy.close()}catch(e){N(`warn`,`gitService close failed: ${e.message}`)}try{gy.close()}catch(e){N(`warn`,`usageStore close failed: ${e.message}`)}try{my.closeAll()}catch(e){N(`warn`,`watcherRegistry close failed: ${e.message}`)}try{_y.flush()}catch(e){N(`warn`,`sessionState flush failed: ${e.message}`)}My(),Rt(),e.exit(t)}}function Iy(e){Ny++,py.inFlight=Ny;let t=!1,n=(n,r)=>{if(t){r!==null&&N(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>Fy(r);try{e.end(Ne(n),i)}catch(e){N(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{py.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Pe(e=>{Ry(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{N(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{N(`warn`,`frame parse failed: ${e.message}`),n({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null)});e.on(`data`,i),e.on(`error`,e=>{N(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),Ny=Math.max(0,Ny-1),py.inFlight=Ny})}const Ly=e=>({resp:e,exitAfterFlush:null});async function Ry(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return Ly({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?N(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):N(`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 Ly({ok:!0,stats:py.snapshot({gitCache:hy.getStats(),usageCache:gy.getStats(),renderCacheSize:xy.size,watchersActive:my.size(),nextRestartReason:ky?.describeNextRestart()??null})});if(e.kind===`render`){py.requestsTotal++;let t=Date.now();try{let{report:n}=Hv(e.hookData);for(let e of n.unknownTopLevelFields)N(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let r=[];for(let e of n.missingRequired)r.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:i}of n.typeMismatches)r.push(`field '${e}' expected ${t}, got ${i}`);if(e.cwd===``&&r.push(`request 'cwd' is empty`),r.length>0)return py.requestsErrored++,N(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),Ly({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=Vy(e.args),s=e.hookData.session_id,c=_y.get(s,`config-override`)??a,l=xy.getOrCreate(i,e.cwd,c),u=je(e.termCols),d=ty(u??120),f={...Gy,width:d},p=``;if(l.state!==null){let t=await Jh(e.hookData,Yy,e.cwd,l.state.neededInputPaths),n=zg(Pf(_y.get(e.hookData.session_id,`theme`),l.state.config.globals.palette));f.style=zf(_y.get(e.hookData.session_id,`style`),l.state.config.globals.style),p=E_(l.state.config,l.state.compiled,l.state.store,l.state.registry,t,n,f,l.state.lastRenderCellsBySegment)}let m=_y.get(e.hookData.session_id,`click.error`);m&&_y.clear(e.hookData.session_id,`click.error`);let h=[o,l.lastError,m].filter(Boolean).join(`
110
- `)||null,g=Uy(p,h,l.lastWarning),_=Date.now()-t,v=hy.getStats(),y=gy.getStats();return N(`info`,`render sid=${e.hookData.session_id??`?`} took=${_}ms termCols=${u??`?`} width=${d} git=${v.size}/${v.hits}h/${v.misses}m usage=${y.size}/${y.hits}h/${y.misses}m err=${l.lastError?`Y`:`N`} warn=${l.lastWarning?`Y`:`N`}`),Ly({ok:!0,output:g+`
111
- `})}catch(e){throw py.requestsErrored++,e}}if(e.kind===`click`)return Ly(await Xy(e.verb,e.value));if(e.kind===`debug`){if(!ey(e.what))return Ly({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${$v.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=xy.firstPopulatedState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?Jy(t.lastRenderCellsBySegment):qy};return Ly({ok:!0,debug:Wv(e.what,n)})}return Ly({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}const zy=`\x1B]8;;`,By=`\x1B]8;;\x1B\\`;function Vy(e){let{values:t,tokens:n}=v({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=[...new Set((n??[]).filter(e=>e.kind===`option`&&e.name!==`config`).map(e=>`--${e.name}`))],i=t.config;return{configFile:i===void 0?void 0:Ch(i),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}function Hy(e,t,n,r){let i=pt([{verb:e,args:[t]}]),a=t.split(/\r\n|\r|\n/).map(e=>ly(e,120)).filter(Boolean).slice(0,8);return a.length===0?``:[`${zy}${i}\\${n}${r} ⚠ ${a[0]} ${fy}${By}`,...a.slice(1).map(e=>`${zy}${i}\\${n}${r} ${e} ${fy}${By}`)].join(`
112
- `)}function Uy(e,t,n){let r=[];if(t&&r.push(Hy(lt,t,dy,uy)),n&&r.push(Hy(ut,n,`\x1B[48;2;220;160;40m`,`\x1B[38;2;0;0;0m`)),r.length===0)return e;let i=r.join(`
113
- `);return e?`${i}\n${e}`:i}const Wy={sessionState:_y,dlog:N},Gy={style:`powerline`,colorCompatibility:`truecolor`},Ky={...Gy,width:1/0},qy=new Map;function Jy(e){let t=new Map;for(let[n,r]of e)t.set(n,Ig(r,Ky));return t}const Yy={gitProvider:hy,usageStore:gy,contextProvider:vy,metricsProvider:yy,tmuxService:by,sessionState:_y,log:N,clock:()=>new Date};function Xy(e,t){let n=zv.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,Wy),{ok:!0,output:``}}catch(e){let t=e instanceof Sv?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}const Zy={connectMs:200,budgetMs:500};async function Qy(t){let n=t.includes(`--json`),r=await $y();if(r.kind!==`ok`&&(e.stderr.write(`daemon-stats: ${He(r)}\n`),e.exit(1)),n){e.stdout.write(JSON.stringify(r.value,null,2)+`
114
- `);return}e.stdout.write(rb(r.value))}function $y(){return Ie({kind:`stats`},Zy,e=>`stats`in e?e.stats:void 0)}function eb(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function tb(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function nb(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 rb(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(` startedAt ${e.startedAt}`),t.push(` uptime ${nb(e.uptimeSec)}`),t.push(` rss ${eb(e.rssBytes)}`),t.push(` heapUsed ${eb(e.heapUsedBytes)}`),t.push(` heapTotal ${eb(e.heapTotalBytes)}`),t.push(` external ${eb(e.externalBytes)}`),t.push(` arrayBuffers ${eb(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 ${tb(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 ${tb(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(`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(`
107
+ `+t:t}this.refreshWatcher(e,t)}buildState(e,t){let{config:n,source:r}=kh(t),i=Ah(n,t??`<default>`,r),a=new sv,o=new Ig(a,i.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),s,c=[];try{s=O_(i,o,{cwd:e.cwd});for(let{key:e,spec:t}of tv(i))c.push(V_(e,t))}catch(e){for(let e of c)e();throw o.dispose(),e}return{config:i,store:a,registry:o,compiled:s,neededInputPaths:Kh(i),lastRenderCellsBySegment:new Map,validatorDisposers:c}}refreshWatcher(e,t){(t!==e.configFilePath||e.watcher===null)&&(e.configFilePath=t,this.rebindWatcher(e,t))}rebindWatcher(e,t){e.watcher&&=(e.watcher.release(),null);let r=Eh(e.projectDir,e.cwd,e.configFile),i=new Map;for(let e of r){let t=o.dirname(e);if(!n.existsSync(t))continue;let r=o.basename(e);i.has(t)||i.set(t,new Set),i.get(t).add(r)}let a=[...i.entries()].map(([e,t])=>({path:e,filenames:[...t]})),s=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${t??`<none>`}`;e.watcher=this.deps.watchers.acquire(s,{files:t===null?[]:[t],dirs:a},()=>this.onConfigChanged(e))}onConfigChanged(e){N(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstPopulatedState(){for(let e of this.entries.values())if(e.state!==null)return e.state;return null}};const uv=16384;var dv=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<uv){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%uv}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: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},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null}}};const fv=(parseInt(process.env.CC_CANDYBAR_RSS_LIMIT_MB??``,10)||512)*1024*1024;function pv(e){let t=e.rssLimitBytes??fv,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let i=e.rssBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t}; writing heap snapshot then shutting down`);try{let t=new Date(e.now()).toISOString().replace(/[:.]/g,`-`),r=o.join(e.snapshotDir,`heap-${t}-${e.pid}.heapsnapshot`),i=e.writeHeapSnapshot(r);e.log(`info`,`heap snapshot written: ${i}`),mv(e.listSnapshots(),n,e.removeFile)}catch(t){e.log(`warn`,`heap snapshot failed: ${t.message}`)}return e.shutdown(0),!0}function a(){let n=e.rssBytes();return n>t*.75?`rss ${n} approaching limit ${t}`:null}function s(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:s}}function mv(e,t,n){let r=[...e].sort((e,t)=>{let n=e.slice(e.lastIndexOf(`/`)+1);return t.slice(t.lastIndexOf(`/`)+1).localeCompare(n)});for(let e of r.slice(t))try{n(e)}catch{}}function hv(e,t,r={}){let i=we();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:N,rssBytes:()=>process.memoryUsage().rss,writeHeapSnapshot:e=>ie.writeHeapSnapshot(e),listSnapshots:()=>{try{return n.readdirSync(i).filter(e=>e.startsWith(`heap-`)&&e.endsWith(`.heapsnapshot`)).map(e=>o.join(i,e))}catch{return[]}},removeFile:e=>n.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}const gv=`CC_CANDYBAR_PARENT_PID`;function _v(e){let t=e[gv];if(t===void 0)return{kind:`outlives-nobody`};let n=Number.parseInt(t,10);if(!Number.isInteger(n)||n<=0)throw Error(`${gv} must be a positive integer pid, got ${JSON.stringify(t)}`);return{kind:`anchored`,pid:n}}function vv(e){if(e.anchor.kind===`outlives-nobody`)return{disarm:()=>{}};let{pid:t}=e.anchor,n=setInterval(()=>{e.isAlive(t)||e.onOrphaned(`spawner pid ${t} gone`)},e.intervalMs??1e3);return n.unref(),{disarm:()=>clearInterval(n)}}function yv(t){try{return e.kill(t,0),!0}catch(e){return e.code===`EPERM`}}const bv={load:()=>({}),save:()=>{},flush:()=>{}};function xv(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var Sv=class{sessions;storage;atom=(0,X.createAtom)(`SessionState`);constructor(e=bv,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=xv(this.storage.load()),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.get(t)??null):null}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,X.runInAction)(()=>{let n=this.sessions.get(e)??new Map;for(let{key:e,value:r}of t)n.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,X.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.delete(t),n.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,X.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,n]of this.sessions)e[t]=Object.fromEntries(n);return e}};const Cv=(e,t)=>O(t);function wv(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 Tv=class{timer=null;pending=null;constructor(e,t=500,n=Cv){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=n.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 wv(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{n.mkdirSync(o.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;n.writeFileSync(t,JSON.stringify(e),{mode:384}),n.chmodSync(t,384),n.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}},Ev=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};function Dv(e){if(!e)throw new Ev(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new Ev(`invalid session id "${e}"`);return e}function Ov(e){return kv(()=>decodeURIComponent(e))}function kv(e){try{return e()}catch(e){throw e instanceof URIError?new Ev(`malformed wire encoding: ${e.message}`):e}}function Av(e,t){let n=ve({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 jv=(e,t)=>Av(Ov(e),t),Mv=(e,t)=>{let n=ve({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,Ov(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`})`)}},Nv=(e,t)=>Av(Ov(e),t),Pv=(e,t)=>Av(Ov(e),t),Fv=(e,t)=>{let n=Dv(Ov(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},Iv=(e,t)=>{let[n=``,...r]=kv(()=>ft(e)),i=Dv(n);if(r.length===0)throw new Ev(`set-state: <key>/<value> is required (have keys: ${z_().join(`, `)})`);if(r.length%2!=0)throw new Ev(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${z_().join(`, `)})`);let a=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new Ev(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=nv(t,n);if(!i.ok)throw new Ev(`set-state: pair ${e/2+1}: ${i.reason}`);a.push({key:t,value:i.value})}t.sessionState.setBatch(i,a);let o=a.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${o} (session=${i})`)},Lv=/^-?\d+$/;function Rv(e,t,n){return e>n?t:e<t?n:e}const zv=(e,t)=>{let[n=``,r=``,i=``]=kv(()=>ft(e)),a=Dv(n);if(!r)throw new Ev(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!Lv.test(i))throw new Ev(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=rv(r);if(!s)throw new Ev(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${z_().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&Lv.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=Rv(l+o,s.min,s.max),d=nv(r,String(u));if(!d.ok)throw new Ev(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)},Bv=`config-override`,Vv=new Map([[st,jv],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new Ev(`load-config: expected <sessionId>/<path> (missing separator)`);let r=Dv(kv(()=>decodeURIComponent(e.slice(0,n)))),i=kv(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new Ev(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new Ev(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,Bv),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,Bv,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[ct,Mv],[at,Iv],[ot,zv],[lt,Nv],[ut,Pv],[`toolbar-toggle`,Fv]]),Hv=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of mt(e)){if(!i&&(a===`set-state`||a===`step-state`||a===`toolbar-toggle`)){let e=ft(o);e.length>0&&e[0]&&(i=e[0])}let e=Vv.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof Ev||(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(`
108
+ `));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new Ev(e)}},Uv=new Map([...Vv,[it,Hv]]);Object.freeze([...Uv.keys()]);const Wv=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`]),Gv=[[`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`]];function Kv(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of Gv){let i=qv(n,e);if(i==null)t.missingRequired.push(e);else{let n=Array.isArray(i)?`array`:typeof i;(r===`object`?n!==`object`:n!==r)&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))Wv.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function qv(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 Jv(e,t){switch(e){case`vars`:return{what:e,vars:Yv(t)};case`segments`:return{what:e,segments:$v(t)};case`config`:return{what:e,config:ny(t)}}}function Yv(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=Zv(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=n.getLastError(e);o.push({name:e,source:i.get(e)??null,type:r.type,value:r.read(),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:Xv(r.lastUpdatedMs())})}return o}function Xv(e){return e===null?null:Math.max(0,Date.now()-e)}function Zv(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,Qv(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}`,Qv(i));return t}function Qv(e){return e.kind}function $v(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=ey(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,template:t.template,referencedVars:ty(t.template,i),lastRender:r.get(e)??null})}return o}function ey(e){let t=[],n=new Set;for(let r of Pn(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 ty(e,t){let n=new Set;for(let r of ch(e)){if(t.has(r)){n.add(r);continue}let e=r.split(`.`);for(;e.length>1;){e.pop();let r=e.join(`.`);if(t.has(r)){n.add(r);break}}}return Array.from(n).sort()}function ny(e){return e===null?null:e.config}const ry=[`vars`,`segments`,`config`];function iy(e){return typeof e==`string`&&ry.includes(e)}function ay(e){return Math.max(1,e-2)}var oy=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 O(`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);O(`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{O(`Calculating context tokens from transcript: ${e}`);let n=await vn(e);if(n.length===0)return O(`No entries in transcript`),zt;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,O(`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 O(`Most recent main chain context: ${n} tokens (limit: ${t})`),P({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return O(`No main chain entries with usage data found`),zt}catch(e){return F(`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)}};function sy(e){let t=e.type||e.message?.role||e.message?.type,n=e.type===`user`&&e.message?.firstContentType===`tool_result`;return t===`user`&&!n}var cy=class{calculateMessageCount(e){return e.filter(sy).length}calculateLastResponseTime(e){if(e.length===0)return null;let t=e.slice(-20),n=null,r=null;for(let e of t){let t=e.type||e.message?.role||e.message?.type;if(sy(e))n=e.timestamp;else if(t===`assistant`&&n){let t=(e.timestamp.getTime()-n.getTime())/1e3;t>.1&&t<300&&(r=t)}}return r}async getMetricsInfo(e,t){try{if(O(`Getting metrics from hook data for session: ${e}`),!t.cost)return zt;let n=(await vn(t.transcript_path)).filter(e=>!e.isSidechain),r=this.calculateMessageCount(n),i=this.calculateLastResponseTime(n);return P({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:i,sessionDuration:t.cost.total_duration_ms/1e3,messageCount:r,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}catch(t){return F(`metrics (${e}): ${t instanceof Error?t.message:String(t)}`)}}};const ly=new Map;function uy(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var dy=class{async getSessionId(){if(!process.env.TMUX_PANE)return zt;let e=uy(process.env.TMUX),t=ly.get(e);if(t!==void 0)return t;O(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await _e({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?P(n.stdout.trim()):zt:F(`tmux display-message: ${n.reason}`);return ly.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}};function fy(e){return e<32||e===127||e>=128&&e<=159}function py(e,t){let n=``;for(let t of e)n+=fy(t.codePointAt(0)??0)?` `:t;n=n.replace(/\s+/g,` `).trim();let r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const my=`\x1B[38;2;255;255;255m`,hy=`\x1B[48;2;200;40;40m`,gy=`\x1B[0m`,_y=new dv;k(_y.launchStats);const vy=new Qt({counters:_y,logger:N}),yy=new an({watchers:vy,logger:N}),by=new Mn,xy=new Sv,Sy=new oy,Cy=new cy,wy=new dy,Ty=new lv({gitService:yy,sessionState:xy,watchers:vy});function Ey(){n.mkdirSync(we(),{recursive:!0}),Ee(Te()),xy.useStorage(new Tv(Oe(),500,N)),e.on(`uncaughtException`,e=>{N(`error`,`uncaughtException: ${e.stack||e.message}`),zy(1)}),e.on(`unhandledRejection`,e=>{N(`error`,`unhandledRejection: ${String(e)}`),zy(1)});for(let t of[`SIGINT`,`SIGTERM`,`SIGHUP`])e.on(t,()=>{N(`info`,`received ${t}, shutting down`),zy(0)});vv({anchor:_v(e.env),isAlive:yv,onOrphaned:e=>{N(`info`,`parent watchdog: ${e}; shutting down`),zy(0)}}),Dy(m.createServer({allowHalfOpen:!1},e=>{By(e)}),Te(),!1)}function Dy(t,n,r){t.removeAllListeners(`error`),t.once(`error`,i=>{if(i.code!==`EADDRINUSE`){N(`error`,`server error: ${i.message}`),zy(1);return}if(r){N(`info`,`lost rebind race; another daemon is alive — exiting`),e.exit(0);return}Oy(t,n)}),t.listen(n,()=>jy(n))}async function Oy(t,r){await Ay(r)&&(N(`info`,`another daemon is listening on socket — exiting`),e.exit(0)),await Ay(r)&&(N(`info`,`race: another daemon claimed the socket during recovery — exiting`),e.exit(0)),N(`warn`,`stale socket from crashed daemon — unlinking and rebinding`);try{n.unlinkSync(r)}catch(e){if(e.code!==`ENOENT`){N(`error`,`cannot unlink stale socket ${r}: ${e.message}`),zy(1);return}}Dy(t,r,!0)}function ky(e){return new Promise(t=>{let n=m.connect(e),r=!1,i=null,a=e=>{r||(r=!0,i&&clearTimeout(i),n.removeAllListeners(),n.destroy(),t(e))};n.once(`connect`,()=>a(`alive`)),n.once(`error`,e=>{let t=e.code;a(t===`ECONNREFUSED`||t===`ENOENT`||t===`ENOTSOCK`?`dead`:`unknown`)}),i=setTimeout(()=>a(`unknown`),50),i.unref()})}async function Ay(e){return await ky(e)!==`dead`}function jy(t){try{n.chmodSync(t,384)}catch(e){N(`warn`,`chmod socket failed: ${e.message}`)}Fy(),N(`info`,`daemon up: pid=${e.pid} v=3 sock=${t}`),My(),Py()}function My(){let t=import.meta.url,r=[];t.startsWith(`file://`)&&r.push(_(t)),e.argv[1]&&r.push(e.argv[1]);let i=new Map;for(let e of r)try{i.set(e,n.statSync(e).mtimeMs)}catch{}if(i.size===0)return;let a=setInterval(()=>{for(let[e,t]of i)try{if(n.statSync(e).mtimeMs!==t){N(`info`,`binary mtime changed (${e}); shutting down`),clearInterval(a),zy(0);return}}catch(e){N(`warn`,`bin stat failed: ${e.message}`)}},6e4);a.unref()}let Ny=null;function Py(){Ny=pv(hv(_y.startedAt.getTime(),e=>zy(e))),Ny.arm()}function Fy(){let t=JSON.stringify({pid:e.pid,version:3,binPath:e.argv[1],startedAt:new Date().toISOString()});try{n.writeFileSync(De(),t,{mode:384}),n.chmodSync(De(),384)}catch(e){N(`warn`,`pidfile write failed: ${e.message}`)}}function Iy(){try{n.unlinkSync(De())}catch{}}let Ly=0,Ry=!1;function zy(t){if(!Ry){Ry=!0,setTimeout(()=>e.kill(e.pid,`SIGKILL`),500);try{yy.close()}catch(e){N(`warn`,`gitService close failed: ${e.message}`)}try{by.close()}catch(e){N(`warn`,`usageStore close failed: ${e.message}`)}try{vy.closeAll()}catch(e){N(`warn`,`watcherRegistry close failed: ${e.message}`)}try{xy.flush()}catch(e){N(`warn`,`sessionState flush failed: ${e.message}`)}Iy(),Rt(),e.exit(t)}}function By(e){Ly++,_y.inFlight=Ly;let t=!1,n=(n,r)=>{if(t){r!==null&&N(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>zy(r);try{e.end(Ne(n),i)}catch(e){N(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{_y.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Pe(e=>{Hy(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{N(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{N(`warn`,`frame parse failed: ${e.message}`),n({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null)});e.on(`data`,i),e.on(`error`,e=>{N(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),Ly=Math.max(0,Ly-1),_y.inFlight=Ly})}const Vy=e=>({resp:e,exitAfterFlush:null});async function Hy(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return Vy({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?N(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):N(`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 Vy({ok:!0,stats:_y.snapshot({gitCache:yy.getStats(),usageCache:by.getStats(),renderCacheSize:Ty.size,watchersActive:vy.size(),nextRestartReason:Ny?.describeNextRestart()??null})});if(e.kind===`render`){_y.requestsTotal++;let t=Date.now();try{let{report:n}=Kv(e.hookData);for(let e of n.unknownTopLevelFields)N(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let r=[];for(let e of n.missingRequired)r.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:i}of n.typeMismatches)r.push(`field '${e}' expected ${t}, got ${i}`);if(e.cwd===``&&r.push(`request 'cwd' is empty`),r.length>0)return _y.requestsErrored++,N(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),Vy({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=Gy(e.args),s=e.hookData.session_id,c=xy.get(s,`config-override`)??a,l=Ty.getOrCreate(i,e.cwd,c),u=je(e.termCols),d=ay(u??120),f={...Yy,width:d},p=``;if(l.state!==null){let t=await Xh(e.hookData,$y,e.cwd,l.state.neededInputPaths),n=Vg(ts(xy.get(e.hookData.session_id,`theme`),l.state.config.globals.palette));f.style=os(xy.get(e.hookData.session_id,`style`),l.state.config.globals.style),p=A_(l.state.config,l.state.compiled,l.state.store,l.state.registry,t,n,f,l.state.lastRenderCellsBySegment)}let m=xy.get(e.hookData.session_id,`click.error`);m&&xy.clear(e.hookData.session_id,`click.error`);let h=[o,l.lastError,m].filter(Boolean).join(`
109
+ `)||null,g=qy(p,h,l.lastWarning),_=Date.now()-t,v=yy.getStats(),y=by.getStats();return N(`info`,`render sid=${e.hookData.session_id??`?`} took=${_}ms termCols=${u??`?`} width=${d} git=${v.size}/${v.hits}h/${v.misses}m usage=${y.size}/${y.hits}h/${y.misses}m err=${l.lastError?`Y`:`N`} warn=${l.lastWarning?`Y`:`N`}`),Vy({ok:!0,output:g+`
110
+ `})}catch(e){throw _y.requestsErrored++,e}}if(e.kind===`click`)return Vy(await eb(e.verb,e.value));if(e.kind===`debug`){if(!iy(e.what))return Vy({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${ry.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=Ty.firstPopulatedState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?Qy(t.lastRenderCellsBySegment):Zy};return Vy({ok:!0,debug:Jv(e.what,n)})}return Vy({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}const Uy=`\x1B]8;;`,Wy=`\x1B]8;;\x1B\\`;function Gy(e){let{values:t,tokens:n}=v({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=[...new Set((n??[]).filter(e=>e.kind===`option`&&e.name!==`config`).map(e=>`--${e.name}`))],i=t.config;return{configFile:i===void 0?void 0:Th(i),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}function Ky(e,t,n,r){let i=pt([{verb:e,args:[t]}]),a=t.split(/\r\n|\r|\n/).map(e=>py(e,120)).filter(Boolean).slice(0,8);return a.length===0?``:[`${Uy}${i}\\${n}${r} ⚠ ${a[0]} ${gy}${Wy}`,...a.slice(1).map(e=>`${Uy}${i}\\${n}${r} ${e} ${gy}${Wy}`)].join(`
111
+ `)}function qy(e,t,n){let r=[];if(t&&r.push(Ky(lt,t,hy,my)),n&&r.push(Ky(ut,n,`\x1B[48;2;220;160;40m`,`\x1B[38;2;0;0;0m`)),r.length===0)return e;let i=r.join(`
112
+ `);return e?`${i}\n${e}`:i}const Jy={sessionState:xy,dlog:N},Yy={style:`powerline`,colorCompatibility:`truecolor`},Xy={...Yy,width:1/0},Zy=new Map;function Qy(e){let t=new Map;for(let[n,r]of e)t.set(n,Rg(r,Xy));return t}const $y={gitProvider:yy,usageStore:by,contextProvider:Sy,metricsProvider:Cy,tmuxService:wy,sessionState:xy,log:N,clock:()=>new Date};function eb(e,t){let n=Uv.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,Jy),{ok:!0,output:``}}catch(e){let t=e instanceof Ev?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}const tb={connectMs:200,budgetMs:500};async function nb(t){let n=t.includes(`--json`),r=await rb();if(r.kind!==`ok`&&(e.stderr.write(`daemon-stats: ${He(r)}\n`),e.exit(1)),n){e.stdout.write(JSON.stringify(r.value,null,2)+`
113
+ `);return}e.stdout.write(sb(r.value))}function rb(){return Ie({kind:`stats`},tb,e=>`stats`in e?e.stats:void 0)}function ib(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function ab(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function ob(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 sb(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(` startedAt ${e.startedAt}`),t.push(` uptime ${ob(e.uptimeSec)}`),t.push(` rss ${ib(e.rssBytes)}`),t.push(` heapUsed ${ib(e.heapUsedBytes)}`),t.push(` heapTotal ${ib(e.heapTotalBytes)}`),t.push(` external ${ib(e.externalBytes)}`),t.push(` arrayBuffers ${ib(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 ${ab(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 ${ab(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(`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(`
115
114
  `)+`
116
- `}const ib={connectMs:200,budgetMs:500};async function ab(t,n){let r=n.includes(`--json`),i=await ob(t);if(i.kind!==`ok`&&(e.stderr.write(`${t}: ${He(i)}\n`),e.exit(1)),r){e.stdout.write(JSON.stringify(i.value,null,2)+`
117
- `);return}e.stdout.write(sb(i.value))}function ob(e){return Ie({kind:`debug`,what:e},ib,e=>`debug`in e?e.debug:void 0)}function sb(e){switch(e.what){case`vars`:return cb(e.vars);case`segments`:return lb(e.segments);case`config`:return ub(e.config);default:return e}}function cb(e){if(e.length===0)return`no variables (DSL not active)
118
- `;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);for(let i of e){let e=i.ageMs===null?``:` ${fb(i.ageMs)}`,a=i.lastError?` ✗ ${i.lastError.message}`:``;t.push(` ${i.name.padEnd(n)} ${(i.source??`—`).padEnd(r)} ${i.type.padEnd(7)} ${db(i.value)}${e}${a}`)}return t.join(`
115
+ `}const cb={connectMs:200,budgetMs:500};async function lb(t,n){let r=n.includes(`--json`),i=await ub(t);if(i.kind!==`ok`&&(e.stderr.write(`${t}: ${He(i)}\n`),e.exit(1)),r){e.stdout.write(JSON.stringify(i.value,null,2)+`
116
+ `);return}e.stdout.write(db(i.value))}function ub(e){return Ie({kind:`debug`,what:e},cb,e=>`debug`in e?e.debug:void 0)}function db(e){switch(e.what){case`vars`:return fb(e.vars);case`segments`:return pb(e.segments);case`config`:return mb(e.config);default:return e}}function fb(e){if(e.length===0)return`no variables (DSL not active)
117
+ `;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);for(let i of e){let e=i.ageMs===null?``:` ${gb(i.ageMs)}`,a=i.lastError?` ✗ ${i.lastError.message}`:``;t.push(` ${i.name.padEnd(n)} ${(i.source??`—`).padEnd(r)} ${i.type.padEnd(7)} ${hb(i.value)}${e}${a}`)}return t.join(`
119
118
  `)+`
120
- `}function lb(e){if(e.length===0)return`no segments (DSL not active)
119
+ `}function pb(e){if(e.length===0)return`no segments (DSL not active)
121
120
  `;let t=[`segments (${e.length})`,``];for(let n of e)t.push(` ${n.name}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`),n.lastRender!==null&&t.push(` last ${n.lastRender}`);return t.join(`
122
121
  `)+`
123
- `}function ub(e){return e===null?`config: DSL not active
122
+ `}function mb(e){return e===null?`config: DSL not active
124
123
  `:JSON.stringify(e,null,2)+`
125
- `}function db(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function fb(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function pb(e){let t=o.resolve(e),r;try{r=n.readFileSync(t,`utf-8`)}catch(t){return{kind:`unreadable`,path:e,message:t instanceof Error?t.message:String(t)}}try{let{config:e}=Dh(t);Oh(e,t,r)}catch(e){if(e instanceof Bf)return{kind:`invalid`,message:e.message};throw e}return{kind:`valid`,path:e}}function mb(t){let n=t[0];(n===void 0||n===``)&&(e.stderr.write(`lint: missing <path>
124
+ `}function hb(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function gb(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function _b(e){let t=o.resolve(e),r;try{r=n.readFileSync(t,`utf-8`)}catch(t){return{kind:`unreadable`,path:e,message:t instanceof Error?t.message:String(t)}}try{let{config:e}=kh(t);Ah(e,t,r)}catch(e){if(e instanceof ss)return{kind:`invalid`,message:e.message};throw e}return{kind:`valid`,path:e}}function vb(t){let n=t[0];(n===void 0||n===``)&&(e.stderr.write(`lint: missing <path>
126
125
  Usage: cc-candybar lint <config-file>
127
- `),e.exit(2)),gb(pb(n))}function hb(t){switch(t.kind){case`valid`:return{stream:e.stdout,text:`✓ ${t.path}: config valid\n`,code:0};case`invalid`:return{stream:e.stderr,text:t.message+`
128
- `,code:1};case`unreadable`:return{stream:e.stderr,text:`lint: cannot read ${t.path}: ${t.message}\n`,code:2}}}function gb(t){let n=hb(t);n.stream.write(n.text),e.exit(n.code)}function _b(){let e=yb();return e===null?null:n.readFileSync(e,`utf-8`)}function vb(){let t=_b();t===null&&(e.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),e.exit(2)),e.stdout.write(t),e.exit(0)}function yb(){let t=o.join(`schema`,`cc-candybar.schema.json`),r=e.argv[1];if(r===void 0)return null;let i=o.dirname(o.resolve(r));for(;;){let e=o.join(i,t);if(n.existsSync(e))return e;let r=o.dirname(i);if(r===i)return null;i=r}}const bb=`${dy}${uy}`;function xb(e){return`${bb}⚠ cc-candybar: ${Sb(e)}${fy}\n`}function Sb(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: ${ly(e.message,60)}`;case`render_failed`:return`render failed: ${ly(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${ly(e.message,60)}`}}function Cb(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
129
- `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:xb(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function wb(){let t=e.env.COLUMNS;if(t){let e=parseInt(t,10);if(!isNaN(e)&&e>0)return e}let n=e.stderr.columns;if(n&&n>0)return n}function Tb(){console.log(`
126
+ `),e.exit(2)),bb(_b(n))}function yb(t){switch(t.kind){case`valid`:return{stream:e.stdout,text:`✓ ${t.path}: config valid\n`,code:0};case`invalid`:return{stream:e.stderr,text:t.message+`
127
+ `,code:1};case`unreadable`:return{stream:e.stderr,text:`lint: cannot read ${t.path}: ${t.message}\n`,code:2}}}function bb(t){let n=yb(t);n.stream.write(n.text),e.exit(n.code)}function xb(){let e=Cb();return e===null?null:n.readFileSync(e,`utf-8`)}function Sb(){let t=xb();t===null&&(e.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),e.exit(2)),e.stdout.write(t),e.exit(0)}function Cb(){let t=o.join(`schema`,`cc-candybar.schema.json`),r=e.argv[1];if(r===void 0)return null;let i=o.dirname(o.resolve(r));for(;;){let e=o.join(i,t);if(n.existsSync(e))return e;let r=o.dirname(i);if(r===i)return null;i=r}}const wb=`${hy}${my}`;function Tb(e){return`${wb}⚠ cc-candybar: ${Eb(e)}${gy}\n`}function Eb(e){switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:return`daemon rejected request: ${py(e.message,60)}`;case`render_failed`:return`render failed: ${py(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${py(e.message,60)}`}}function Db(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
128
+ `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:Tb(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function Ob(){let t=e.env.COLUMNS;if(t){let e=parseInt(t,10);if(!isNaN(e)&&e>0)return e}let n=e.stderr.columns;if(n&&n>0)return n}function kb(){console.log(`
130
129
  cc-candybar - Beautiful powerline statusline for Claude Code
131
130
 
132
131
  Usage: cc-candybar [options]
@@ -167,7 +166,7 @@ Config tooling:
167
166
  config [--json] The effective merged config. (All three query the
168
167
  running daemon; none spawn one.)
169
168
 
170
- `)}async function Eb(){try{(e.argv.includes(`--help`)||e.argv.includes(`-h`))&&(Tb(),e.exit(0));let n=e.argv[2];if(n===`install`&&(Pt(e.argv.slice(3)),e.exit(0)),n===`install-url-handler`&&(At(),e.exit(0)),n===`url-handle`){await Mt(e.argv[3]);return}if(n===`daemon`){Sy();return}if(n===`daemon-stats`&&(await Qy(e.argv.slice(3)),e.exit(0)),n===`lint`){mb(e.argv.slice(3));return}if(n===`schema`){vb();return}ey(n)&&(await ab(n,e.argv.slice(3)),e.exit(0)),e.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
169
+ `)}async function Ab(){try{(e.argv.includes(`--help`)||e.argv.includes(`-h`))&&(kb(),e.exit(0));let n=e.argv[2];if(n===`install`&&(Pt(e.argv.slice(3)),e.exit(0)),n===`install-url-handler`&&(At(),e.exit(0)),n===`url-handle`){await Mt(e.argv[3]);return}if(n===`daemon`){Ey();return}if(n===`daemon-stats`&&(await nb(e.argv.slice(3)),e.exit(0)),n===`lint`){vb(e.argv.slice(3));return}if(n===`schema`){Sb();return}iy(n)&&(await lb(n,e.argv.slice(3)),e.exit(0)),e.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
171
170
 
172
171
  cc-candybar is designed to be used as a Claude Code statusLine command.
173
172
  It reads hook data from stdin and outputs formatted statusline.
@@ -183,4 +182,4 @@ Add to ~/.claude/settings.json:
183
182
  Run with --help for more options.
184
183
 
185
184
  To test output manually:
186
- echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),e.exit(1)),O(`Working directory: ${e.cwd()}`),O(`Process args:`,e.argv);let r=await t(e.stdin);O(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),Tb(),e.exit(1));let i=Cb(await Ke(r,e.argv,e.cwd(),wb()));i.debug!==null&&O(i.debug),i.kick&&Je(),e.stdout.write(i.output),e.exit(0)}catch(t){let n=t instanceof Error?t.message:String(t);console.error(`Error generating statusline:`,n),e.exit(1)}}Eb();export{};
185
+ echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),e.exit(1)),O(`Working directory: ${e.cwd()}`),O(`Process args:`,e.argv);let r=await t(e.stdin);O(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),kb(),e.exit(1));let i=Db(await Ke(r,e.argv,e.cwd(),Ob()));i.debug!==null&&O(i.debug),i.kick&&Je(),e.stdout.write(i.output),e.exit(0)}catch(t){let n=t instanceof Error?t.message:String(t);console.error(`Error generating statusline:`,n),e.exit(1)}}Ab();export{};