@promptctl/cc-candybar 1.71.0 → 1.72.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +24 -24
- package/package.json +5 -5
package/dist/index.mjs
CHANGED
|
@@ -38,7 +38,7 @@ import{createRequire as e}from"node:module";import t from"node:process";import{j
|
|
|
38
38
|
`,t-1)+1}function Zi(e){return/^[ \t]*$/.test(e)}function Qi(e,t){let n=Xi(e,t);return/^[ \t]*/.exec(e.slice(n))[0]}function $i(e,t){return Zi(e.slice(Xi(e,t),t))}const ea=/(?:\/\/[^\n]*?)?(\r\n|\n|$)/y;function ta(e,t){let n=t;for(;n<e.length&&(e[n]===` `||e[n]===` `);)n++;let r=e[n]===`,`?n+1:-1;for(r!==-1&&(n=r);n<e.length&&(e[n]===` `||e[n]===` `);)n++;ea.lastIndex=n;let i=ea.exec(e);if(i===null)return{commaEnd:r,line:null};let a=n+i[0].length;return{commaEnd:r,line:{at:a-i[1].length,next:a}}}function na(e,t){let{commaEnd:n,line:r}=ta(e,t.end);if($i(e,t.start)&&r!==null)return Yi(e,Xi(e,t.start),r.next,``);if(n!==-1){let r=n;for(;r<e.length&&e[r]===` `;)r++;return Yi(e,t.start,r,``)}let i=t.start;for(;i>0&&(e[i-1]===` `||e[i-1]===` `);)i--;return e[i-1]===`,`?Yi(e,i-1,t.end,``):Yi(e,t.start,t.end,``)}function ra(e,t,n,r,i){let a=n.commaEnd!==-1,o=a?e:Yi(e,t.end,t.end,`,`),s=n.line.at+ +!a,c=Ki(e);return Yi(o,s,s,`${c}${i}${qi(r,i,c)}${a?`,`:``}`)}function ia(e,t,n,r){let i=t.kind===`object`?t.entries:t.elements,a=i[i.length-1],o=Qi(e,t.span.start);if(a===void 0){let i=o+` `,a=Ki(e);return Yi(e,t.span.start+1,t.span.end-1,`${a}${i}${qi(n,i,a)}${r.trailingComma}${a}${o}`)}let{commaEnd:s,line:c}=ta(e,a.span.end);if($i(e,a.span.start)&&c!==null){let t=e.slice(Xi(e,a.span.start),a.span.start);return ra(e,a.span,{commaEnd:s,line:c},n,t)}let l=s===-1?a.span.end:s;return Yi(e,l,l,`${s===-1?`, `:` `}${n}${s===-1?``:`,`}`)}function aa(e,t,n,r){if(t.length===0)throw new ji(`setValue needs a non-empty path`,0);if(/^\s*$/.test(e)){let i=Ki(e);return`{${i} ${qi(Ji(t,n,r),` `,i)}${r.trailingComma}${i}}${i}`}let i=Li(e);for(let a=0;a<t.length;a++){if(i.kind!==`object`)throw new ji(`cannot set ${t.join(`.`)}: ${t.slice(0,a).join(`.`)||`the document`} is not an object`,i.span.start);let o=Ri(i,t[a]);if(o===void 0)return ia(e,i,Ji(t.slice(a),n,r),r);if(a===t.length-1){let t=Qi(e,o.keySpan.start);return Yi(e,o.value.span.start,o.value.span.end,qi(n,t,Ki(e)))}i=o.value}throw new ji(`unreachable: path exhausted`,0)}function oa(e,t){if(t.length===0)throw new ji(`deleteValue needs a non-empty path`,0);if(/^\s*$/.test(e))return e;let n=t.slice(0,-1),r=zi(Li(e),n),i=r===void 0?void 0:Ri(r,t[t.length-1]);if(i===void 0||r?.kind!==`object`)return e;let a=na(e,i.span);return n.length>0&&r.entries.length===1?oa(a,n):a}const sa=[`h`,`v`,`children`];function ca(e){if(e.kind===`string`)return e.value;if(e.kind!==`object`)return;let t=Ri(e,`seg`)?.value;if(t?.kind===`string`)return t.value;let n=Ri(e,`kind`)?.value,r=Ri(e,`name`)?.value;return n?.kind===`string`&&n.value===`segment`&&r?.kind===`string`?r.value:void 0}function la(e){return e.kind===`object`?sa.map(t=>Ri(e,t)?.value).filter(e=>e?.kind===`array`):[]}function ua(e){let t=Ri(e,`rows`)?.value;return t?.kind===`object`?t.entries:null}function da(e){if(e.kind!==`object`)return!0;let t=ua(e);return t===null||t.length>0||e.entries.some(e=>e.key!==`rows`)}function*fa(e,t){yield{node:e,bareAt:t};for(let t of la(e))for(let e of t.elements)yield*fa(e,null);for(let n of ua(e)??[])yield*fa(n.value,t===null?null:[...t,`rows`,n.key])}function pa(e,t){for(let{node:n}of fa(e,null))if(ca(n)===t)return!0;return!1}function ma(e,t,n){let r=zi(Li(e),t);if(r===void 0)return null;for(let{node:i,bareAt:a}of fa(r,t))if(ca(i)===n)return a===null?{text:e,ref:i}:ma(aa(e,a,`{ h: [${Bi(e,i)}] }`,Ui),t,n);return null}function ha(e,t,n){let r=ma(e,t,n);return r===null?null:na(r.text,r.ref.span)}function ga(e,t,n,r,i){let a=ma(e,t,r);if(a===null)return null;let{text:o,ref:s}=a,c=JSON.stringify(n),{commaEnd:l,line:u}=ta(o,s.span.end);if($i(o,s.span.start)&&u!==null){let e=o.slice(Xi(o,s.span.start),s.span.start);return i===`after`?ra(o,s.span,{commaEnd:l,line:u},c,e):Yi(o,s.span.start,s.span.start,`${c},${Ki(o)}${e}`)}let d=Bi(o,s),f=i===`before`?`${c}, ${d}`:`${d}, ${c}`;return Yi(o,s.span.start,s.span.end,f)}var _a=class extends Error{file;issues;warnings;constructor(e,t,n=[]){super(xa(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t,this.warnings=n}};function G(e,t){let n=0,r;for(let i of t){if(i===``||/^\d+$/.test(i))continue;let t=va(e,n,i);if(t===-1)return r===void 0?void 0:ya(e,r);n=t,r=t}return r===void 0?void 0:ya(e,r)}function va(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 ya(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function ba(e,t){try{return Li(t),null}catch(n){if(!(n instanceof ji))throw n;return`${e}:${ya(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function xa(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(`
|
|
39
39
|
`)}const Sa=[`vertical`,`horizontal`];function Ca(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*wa(e){yield e;for(let t of Ta(e))yield*wa(t)}function Ta(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}function Ea(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const Da=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function Oa(e){return e.kind!==`literal`&&e.kind!==`input`&&e.kind!==`env`&&e.kind!==`state`}const ka=[`branch`,`sha`,`dirty`,`ahead`,`behind`,`stash`],Aa=[`file`,`shell`,`git`],ja=[`left`,`center`,`right`],Ma=[`right`,`left`,`middle`];function Na(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 ${za(i)}`,line:G(e.source,[...t.split(`.`),r])}),null)}function Pa(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 ${za(i)}`,line:G(e.source,[...t.split(`.`),`default`])});return}return i}}function Fa(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 ${za(i)}`,line:G(e.source,[...t.split(`.`),r])});return}return i}}function Ia(e,t,n){let r=Fa(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:G(e.source,[...t.split(`.`),`palette`])});return}return r}}function La(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 ${Ba(a)}`,line:G(e.source,[...t.split(`.`),r])});return}return a}}function Ra(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function za(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function Ba(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function Va(e,t,n,r){return Ra(r)?(Wa(e,n,r,t.noun,new Set(Object.keys(t.fields))),Ha(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${za(r)}`,line:G(e.source,n.split(`.`))}),null)}function Ha(e,t,n,r){let i=t,a={},o=!0;for(let[t,s]of Object.entries(i)){let i=s.parse(e,n,t,r);i===void 0?s.required&&(o=!1):a[t]=i}return o?a:null}const Ua=new Set;function Wa(e,t,n,r,i,a=Ua){for(let o of Object.keys(n))!i.has(o)&&!a.has(`${t}.${o}`)&&e.issues.push({path:`${t}.${o}`,message:`Unknown ${r} "${o}". Expected one of: ${[...i].join(`, `)}`,line:G(e.source,[...t.split(`.`),o])})}function Ga(e,t,n){return e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))}),null}function Ka(e,t,n,r){if(!Ra(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${za(r)}`,line:G(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:G(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:G(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:G(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function qa(e,t,n,r){if(!Ra(r))return e.issues.push({path:n,message:`${n} must be an object, got ${za(r)}`,line:G(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 ${za(i)}`,line:G(e.source,n.split(`.`))}),null;let a=t.arms;if(!(i in a))return e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:G(e.source,[...n.split(`.`),t.tag])}),null;let o=a[i],s=e.issues.length,c=o.parse(e,n,r),l=new Set(e.issues.slice(s).map(e=>e.path));return Wa(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function Ja(e,t,n){return{json:ao(ro(n),e,t),keys:new Set([e,...Object.keys(n)])}}function Ya(e){return(...t)=>e()(...t)}function Xa(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:G(n.source,o.split(`.`))}),null}return a}}function K(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Fa(e,t,r,n)}}function Za(){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 ${za(i)}`,line:G(e.source,[n])});return}return i}}}}function Qa(e){let{min:t,max:n}=e;return{required:!1,json:{type:`integer`,minimum:t,maximum:n},parse:(e,r,i,a)=>{let o=a[i];if(o!==void 0){if(typeof o!=`number`||!Number.isInteger(o)||o<t||o>n){e.issues.push({path:`${r}.${i}`,message:`${i} must be an integer between ${t} and ${n}, got ${Ba(o)}`,line:G(e.source,[i])});return}return o}}}}function $a(e={}){let{min:t}=e;return{required:!1,json:{type:`number`,...t!==void 0&&{minimum:t}},parse:(e,n,r,i)=>{let a=i[r];if(a!==void 0){if(typeof a!=`number`||!Number.isFinite(a)||t!==void 0&&a<t){let i=t===void 0?`a finite number`:`a finite number >= ${t}`;e.issues.push({path:`${n}.${r}`,message:`${r} must be ${i}, got ${Ba(a)}`,line:G(e.source,[r])});return}return a}}}}function eo(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Ia(e,t,r)}}function to(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Na(e,t,r,n)??void 0}}function no(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>La(t,n,i,r,e)}}function ro(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 io(e){return ro(e.fields)}function ao(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function oo(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function so(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const co=/^[A-Za-z_][A-Za-z0-9_]*$/;function lo(e){return`#${e+1}`}const uo={rows:{}};function fo(e){return`rows`in e}function po(e){return Object.fromEntries(e.map((e,t)=>[lo(t),e]))}function mo(e){if(e.kind===`container`&&e.direction===`vertical`){let{kind:t,direction:n,children:r,...i}=e;return{...i,rows:po(r)}}let{when:t,...n}=e;return{...t!==void 0&&{when:t},rows:po([n])}}function ho(e){let{rows:t,...n}=e;return{kind:`container`,direction:`vertical`,children:Object.values(t),...n}}function go(e){return fo(e)?ho(e):e}function _o(e,t){return fo(e)?{...t,...e,rows:{...t.rows,...e.rows}}:mo(e)}function vo(e){if(!fo(e))return!0;let{rows:t,...n}=e;return Object.values(n).some(e=>e!==void 0)||Object.keys(t).length>0}function yo(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:bo(t.segments,e.segments??{}),root:_o(e.root??uo,t.root),actions:{...t.actions,...e.actions??{}},looks:{...t.looks,...e.looks??{}},presets:bo(t.presets,e.presets??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function bo(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}const xo={required:!1,json:{enum:[...Ci]},parse:(e,t,n,r)=>{if(r[n]===`auto`){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: "auto" is not supported — the render daemon runs detached, so terminal detection would read the daemon's environment, not your terminal's. Pick an explicit depth: ${Ci.join(`, `)}`,line:G(e.source,[...t.split(`.`),n])});return}return La(e,t,r,n,Ci)}},So={default_bg:K(),default_fg:K(),default_empty_value:K(),default_separator:K(),default_truncate_marker:K(),palette:{required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=Fa(e,t,r,n);return fi(i)?i:Ia(e,t,r)}},look:K(),preset:K(),style:no(yi),autoWrap:Za(),padding:Qa(Di),charset:no(Si),updateNotice:Za(),colorCompatibility:xo},Co={noun:`globals key`,fields:So};function wo(e){return{required:!1,json:{not:{},description:`not allowed here — ${e} cannot select a preset`},parse:(t,n,r,i)=>{i[r]!==void 0&&t.issues.push({path:`${n}.${r}`,message:`${n}.${r}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`,line:G(t.source,[...n.split(`.`),r])})}}}const To={noun:`preset globals key`,fields:{...So,preset:wo(`a preset`)}},Eo={noun:`editGlobals key`,fields:{...So,preset:wo(`the editGlobals fragment`)}};function Do(e,t,n){return n===void 0?{}:Va(e,Co,t,n)??{}}function Oo(e,t,n){return Va(e,To,t,n)??{}}function ko(){return io(To)}function Ao(e,t,n){return Va(e,Eo,t,n)??{}}const jo=new Set(Object.keys(Co.fields));function Mo(e){return jo.has(e)}function No(){return[...jo]}const Po={padding:1};function Fo(e){let t=new Map;for(let[n,r]of Object.entries(Po)){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}function Io(e,t,n,r){return n.cache===void 0?(Aa.includes(r)&&e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${Da.join(`, `)})`,line:G(e.source,t.split(`.`))}),null):Vo(e,`${t}.cache`,n.cache)}function Lo(e,t,n){if(n.cache!==void 0)return Vo(e,`${t}.cache`,n.cache)??void 0}function Ro(e){return{required:!0,json:Wo(),parse:(t,n,r,i)=>Io(t,n,i,e)??void 0}}function zo(){return{required:!1,json:Wo(),parse:(e,t,n,r)=>Lo(e,t,r)}}const Bo={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&Ko(n)?{ttl:n}:Ga(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${Ba(n)}`)},watch_file:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{watch_file:n}:Ga(e,t,`cache.watch_file must be a non-empty path string, got ${Ba(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}:Ga(e,t,`cache.depends_on must be an array of variable-name strings, got ${Ba(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:Ga(e,t,`cache.key must be a non-empty template string, got ${Ba(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:Ga(e,t,`cache.never must be the literal boolean true, got ${Ba(n)}`)}}};function Vo(e,t,n){return Ka(e,Bo,t,n)}const Ho={noun:`time-variable cache`,arms:{ttl:Bo.arms.ttl}};function Uo(){return{required:!1,json:so(Ho),parse:(e,t,n,r)=>r.cache===void 0?void 0:Ka(e,Ho,`${t}.cache`,r.cache)??void 0}}function Wo(){return so(Bo)}const Go=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function Ko(e){return Go.test(e)}function qo(e,t,n){if(n===void 0)return{};if(!Ra(n))return e.issues.push({path:t,message:`${t} must be an object, got ${za(n)}`,line:G(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=qa(e,hs,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function Jo(){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 ${za(i)}`,line:G(e.source,t.split(`.`))});return}return i}}}function Yo(){return{required:!0,json:{enum:[...ka]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!ka.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${ka.join(`, `)}, got ${JSON.stringify(i)}`,line:G(e.source,[...t.split(`.`),`field`])});return}return i}}}function Xo(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return Pa(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const Zo={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:Ga(e,t,`parse.text must be the literal boolean true, got ${Ba(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?Qo(e,t,n):Ga(e,t,`parse.regex must be a pattern string, got ${Ba(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:Ga(e,t,`parse.json must be the literal boolean true, got ${Ba(n)}`)}}};function Qo(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return Ga(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:Ga(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function $o(){return{required:!1,json:so(Zo),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:G(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:Ka(e,Zo,`${t}.parse`,r.parse)??void 0)}}function es(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>Ra(r.parse)&&`json`in r.parse?ts(e,t,r.default):Fa(e,t,r,`default`)}}function ts(e,t,n){if(n!==void 0)return ns(n)?n:Ga(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${Ba(n)}`)??void 0}function ns(e){return e!==null&&rs(e)}function rs(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(rs);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(rs)}default:return!1}}const is={value:Jo(),default:K()},as={path:to(),type:no([`string`,`number`,`boolean`]),default:Xo()},os={name:to(),default:K()},ss={path:to(),readMode:no([`whole`,`first-line`]),parse:$o(),cache:Ro(`file`),default:es()},cs={command:to(),parse:$o(),cache:Ro(`shell`),default:es()},ls={template:to(),cache:zo(),default:K()},us={layout:to(),cache:Uo(),default:K()},ds={field:Yo(),cache:Ro(`git`),default:K()},fs={key:to(),default:K()},ps=`kind`;function ms(e,t){return{...Ja(ps,e,t),parse:(n,r,i)=>{let a=Ha(n,t,r,i);return a===null?null:{kind:e,...a}}}}const hs={tag:ps,noun:`source kind`,memberNoun:`variable`,arms:{literal:ms(`literal`,is),input:ms(`input`,as),env:ms(`env`,os),file:ms(`file`,ss),shell:ms(`shell`,cs),template:ms(`template`,ls),time:ms(`time`,us),git:ms(`git`,ds),state:ms(`state`,fs)}};function gs(){return oo(hs)}function _s(){return{type:`object`,additionalProperties:gs()}}function vs(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const ys=`groups.`,bs=`menus.`,xs=`edit.`,Ss=`settings.`,Cs=[ys,bs,xs,Ss];function ws(e){return Cs.some(t=>e.startsWith(t))}function Ts(e){let t=vs(e);return Cs.find(e=>t.startsWith(vs(e)))}function Es(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:G(e.source,[`root`])})}function Ds(e){return new Set(Object.keys(e.segments).filter(e=>!ws(e)))}function Os(e,t,n){if(t===void 0)return{};if(!Ra(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${za(t)}`,line:G(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=Va(e,n.has(i)?Ps:Ns,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function ks(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?Ga(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own`)??void 0:Na(e,t,r,n)??void 0}}function As(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${Ba(i)}`,line:G(e.source,[...t.split(`.`),n])})}}}}function js(){return{required:!1,json:_s(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return qo(e,`${t}.${n}`,i)}}}const Ms={template:ks(),description:K(),width:As(),justify:no(ja),truncate:no(Ma),bg:K(),fg:K(),when:K(),palette:eo(),vars:js()},Ns={noun:`segment key`,fields:Ms},Ps={noun:`segment key`,fields:{...Ms,template:K()}},Fs=[`primary`,`secondary`,`accent`],Is=[`surface`,`panel`,`surface-lighten-1`],Ls=[.16,.3],Rs=Ls.reduce((e,t)=>t>e?t:e),zs=Ls.flatMap(e=>Fs.flatMap(t=>Is.map(n=>({base:n,hue:t,amount:e})))),Bs=e=>{let t=0,n=.5;for(let r=e;r>0;r>>=1,n/=2)t+=n*(r&1);return t},Vs=[`van-der-corput`,`golden-angle`,`ends-interleaved`,`monotonic`,`uniform`],Hs=e=>typeof e==`string`&&Vs.includes(e),Us={"van-der-corput":Bs,"golden-angle":e=>e*.6180339887498949%1,"ends-interleaved":(e,t)=>((e%2==0?e/2:t-1-(e-1)/2)+.5)/t,monotonic:(e,t)=>(e+.5)/t,uniform:()=>.5},Ws=e=>Us[e??`van-der-corput`],Gs=.37;function Ks(e,t){let n=0,r=1;for(let{index:i,count:a,distribution:o}of e)n+=o(i,a)*r*t,r*=Gs;let i=Math.round(n)%t;return i<0?i+t:i}function qs(e){let t=0,n=1;for(let{index:r,count:i,distribution:a}of e)t+=a(r,i)*n,n*=Gs;return t%1}function Js(e,t){let n=e[Ks(t,e.length)];if(n===void 0)throw Error(`vocabularySelect: empty vocabulary`);return n}const Ys=e=>Js(zs,e);function Xs(e,t){let n=e.get(t);if(n===void 0)throw Error(`palette "${e.name}" has no "${t}" role; decoration needs it`);return n}function Zs(e,{base:t,hue:n,amount:r}){return cn(Xs(e,t),Xs(e,n),r)}const Qs=2.2;function $s(e,t){let n=zs.filter(e=>e.hue===t&&e.amount===Rs).map(t=>Zs(e,t)),r=cn(Xs(e,`surface`),Xs(e,t),.92),i=Xs(e,`foreground`),a=Array.from({length:13},(e,t)=>cn(r,i,t/12)).find(e=>n.every(t=>Rn(e,t)>=Qs));if(a===void 0)throw Error(`palette "${e.name}": "${t}" cannot clear the ${Qs} state floor even at foreground`);return a}function ec(e,t){return[`background`,`foreground`].map(t=>Xs(e,t)).reduce((e,n)=>Rn(t,n)>Rn(t,e)?n:e)}const tc={base:.42,perDepth:.14,cap:.75},nc={floor:.12,span:.8};function rc(e,t){return Fs[(Fs.indexOf(e)+t)%Fs.length]}function ic(e,t){let n=`${t.hue}|${t.depth}`,r=ac.get(e);r===void 0&&(r=new Map,ac.set(e,r));let i=r.get(n);if(i!==void 0)return i;let a=$s(e,rc(t.hue,t.depth)),o=Math.min(tc.cap,tc.base+tc.perDepth*t.depth),s={state:a,plane:cn(a,Xs(e,`background`),o)};return r.set(n,s),s}const ac=new WeakMap;function oc(e,t,n){let{state:r,plane:i}=ic(e,t);return cn(i,r,nc.floor+nc.span*qs(n))}const sc={kind:`bar`,address:[]},cc=(e,t)=>({...e,address:[...e.address,t]}),lc=e=>({kind:`band`,band:e,address:[]}),uc=()=>void 0;function dc(e,t){switch(t.kind){case`bar`:{let n=Ys(t.address);return{tint:Zs(e,n),text:uc,disclosure:{hue:n.hue,depth:0}}}case`band`:return{tint:oc(e,t.band,t.address),text:t=>ec(e,t),disclosure:{hue:t.band.hue,depth:t.band.depth+1}}}}const fc=`closed`;function pc(e,t,n){if(t===0)return`${e} needs a display (the clickable text)`;if(t!==1&&t!==n)return`${e} cycles ${n} members; bind one display per member (${n}) or one static display, got ${t}`}function mc(e,t,n,r){let i=pc(e,t.length,n);if(i!==void 0)throw Error(i);return t.length===1?t[0]:t[r]}function hc(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function gc(e,t,n,r){return{kind:`segment`,name:e,opens:{ref:t,body:n},...r!==void 0&&{when:r}}}function _c(e,...t){return`{{ and ${[e,...t].map(vc).join(` `)} }}`}function vc(e){return`(eq .${e.variable} "${hc(e.member)}")`}function yc(e,t,n){return`{{ action "${e}" "${hc(t)}" "${hc(n)}" }}`}function bc(e,t){return{kind:`state`,key:e,default:t}}function xc(e,t){return{set:e,cycle:[fc,t]}}const Sc=`#/definitions/LayoutNode`,Cc={kind:`container`,direction:`vertical`,children:[]};function wc(e){return{required:!0,json:{const:e},parse:()=>e}}function Tc(){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 ${Ba(i)}`,line:G(e.source,[`root`])}),``)}}}function Ec(){return{required:!0,json:{enum:[...Sa]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Sa.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${Sa.join(`, `)} (got ${JSON.stringify(i)})`,line:G(e.source,[`root`])}),`vertical`)}}}function Dc(e){return{required:!0,json:{type:`array`,items:{$ref:Sc}},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 ${za(a)}`,line:G(t.source,[`root`])}),[])}}}const Oc={noun:`layout-node key`,fields:{kind:wc(`segment`),name:Tc(),when:K()}},kc=()=>no(Vs),Ac={noun:`layout-node key`,fields:{kind:wc(`container`),direction:Ec(),children:Dc(Ya(()=>Fc)),when:K(),distribution:kc()}};function jc(){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 ${Ba(i)}`,line:G(e.source,[`root`])}),``)}}}const Mc={noun:`layout-node key`,fields:{seg:jc(),when:K()}},Nc={noun:`layout-node key`,fields:{h:Dc(Ya(()=>Fc)),when:K(),distribution:kc()}},Pc={noun:`layout-node key`,fields:{v:Dc(Ya(()=>Fc)),when:K(),distribution:kc()}},Fc=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:G(e.source,[`root`])}),Cc):{kind:`segment`,name:n};if(!Ra(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 ${za(n)}`,line:G(e.source,[`root`])}),Cc;if(n.kind===`container`)return Va(e,Ac,t,n)??Cc;if(n.kind===`segment`)return Va(e,Oc,t,n)??Cc;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
40
40
|
Old: { kind: "cells", segments: ["seg1", "seg2"] }
|
|
41
|
-
New: { h: ["seg1", "seg2"] }`,line:G(e.source,[`root`])}),Cc;if(n.kind===`group`){let r=Va(e,Hc,t,n);return r===null?Cc:(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}),Wc(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:G(e.source,[`root`])}),Cc}if(a){let r=Va(e,Mc,t,n);return r===null?Cc:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when}}}if(r){let r=Va(e,Nc,t,n);return r===null?Cc:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}if(i){let r=Va(e,Pc,t,n);return r===null?Cc:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:G(e.source,[`root`])}),Cc};function Ic(){return{required:!0,json:{type:`object`,propertyNames:{pattern:co.source},additionalProperties:{$ref:Sc}},parse:(e,t,n,r)=>{let i=r[n];if(!Ra(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${za(i)}`,line:G(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!co.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:G(e.source,[...t.split(`.`),n,r])});continue}a[r]=Fc(e,`${t}.${n}.${r}`,o)}return a}}}const Lc={noun:`root key`,fields:{rows:Ic(),when:K(),distribution:kc()}};function Rc(e,t,n){return Ra(n)&&`rows`in n?Va(e,Lc,t,n)??{rows:{}}:Fc(e,t,n)}function zc(){return{required:!0,json:{type:`string`,pattern:co.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!co.test(i)||i===`closed`){e.issues.push({path:`${t}.${n}`,message:`a group "name" must be an identifier (letters, digits, _; not starting with a digit) and not the reserved "${fc}", got ${Ba(i)}`,line:G(e.source,[`root`])});return}return i}}}function Bc(){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 ${Ba(i)}`,line:G(e.source,[`root`])});return}return i}}}}function Vc(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Na(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:G(e.source,[...t.split(`.`),n])});return}return i}}}}const Hc={noun:`layout-node key`,fields:{kind:wc(`group`),name:zc(),label:Vc(),open:Za(),direction:no(Sa),key:Bc(),bg:K(),fg:K(),when:K(),distribution:kc(),children:Dc(Ya(()=>Fc))}};function Uc(e){return e.key??`groups.`+e.name}function Wc(e){let t=ys+e.name;return gc(t,{variable:t,member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},e.when)}function Gc(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function Kc(e,t){Es(e,t,ys,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&Gc(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}.`)&&Uc(t)===Uc(r)&&Gc(e,t.path,`group "${t.name}" shares key "${Uc(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=Uc(t);if(i.has(n)||i.set(n,fc),t.open===!0){let r=i.get(n);r!==`closed`&&Gc(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=ys+e.name,r=Uc(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=bc(r,i.get(r)),o[t]=xc(r,e.name),s[t]={template:yc(t,`${l}${e.label} ▸`,`${l}${e.label} ▾`),...e.bg!==void 0&&{bg:e.bg},...e.fg!==void 0&&{fg:e.fg}}}t.variables={...t.variables??{},...a},t.actions={...t.actions??{},...o},t.segments={...t.segments??{},...s}}var qc=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?el(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}},Jc=class extends qc{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},Yc=class extends qc{name=`EvalError`;kind=`EvalError`},Xc=class extends Yc{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=tl(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}},Zc=class extends Yc{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}},Qc=class extends Yc{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},$c=class extends Yc{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function el(e,t){let n=e.split(`
|
|
41
|
+
New: { h: ["seg1", "seg2"] }`,line:G(e.source,[`root`])}),Cc;if(n.kind===`group`){let r=Va(e,Hc,t,n);return r===null?Cc:(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}),Wc(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:G(e.source,[`root`])}),Cc}if(a){let r=Va(e,Mc,t,n);return r===null?Cc:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when}}}if(r){let r=Va(e,Nc,t,n);return r===null?Cc:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}if(i){let r=Va(e,Pc,t,n);return r===null?Cc:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:G(e.source,[`root`])}),Cc};function Ic(){return{required:!0,json:{type:`object`,propertyNames:{pattern:co.source},additionalProperties:{$ref:Sc}},parse:(e,t,n,r)=>{let i=r[n];if(!Ra(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${za(i)}`,line:G(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!co.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:G(e.source,[...t.split(`.`),n,r])});continue}a[r]=Fc(e,`${t}.${n}.${r}`,o)}return a}}}const Lc={noun:`root key`,fields:{rows:Ic(),when:K(),distribution:kc()}};function Rc(e,t,n){return Ra(n)&&`rows`in n?Va(e,Lc,t,n)??{rows:{}}:Fc(e,t,n)}function zc(){return{required:!0,json:{type:`string`,pattern:co.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!co.test(i)||i===`closed`){e.issues.push({path:`${t}.${n}`,message:`a group "name" must be an identifier (letters, digits, _; not starting with a digit) and not the reserved "${fc}", got ${Ba(i)}`,line:G(e.source,[`root`])});return}return i}}}function Bc(){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 ${Ba(i)}`,line:G(e.source,[`root`])});return}return i}}}}function Vc(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Na(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:G(e.source,[...t.split(`.`),n])});return}return i}}}}const Hc={noun:`layout-node key`,fields:{kind:wc(`group`),name:zc(),label:Vc(),open:Za(),direction:no(Sa),key:Bc(),bg:K(),fg:K(),when:K(),distribution:kc(),children:Dc(Ya(()=>Fc))}};function Uc(e){return e.key??`groups.`+e.name}function Wc(e){let t=ys+e.name;return gc(t,{variable:t,key:Uc(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},e.when)}function Gc(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function Kc(e,t){Es(e,t,ys,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&Gc(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}.`)&&Uc(t)===Uc(r)&&Gc(e,t.path,`group "${t.name}" shares key "${Uc(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=Uc(t);if(i.has(n)||i.set(n,fc),t.open===!0){let r=i.get(n);r!==`closed`&&Gc(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=ys+e.name,r=Uc(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=bc(r,i.get(r)),o[t]=xc(r,e.name),s[t]={template:yc(t,`${l}${e.label} ▸`,`${l}${e.label} ▾`),...e.bg!==void 0&&{bg:e.bg},...e.fg!==void 0&&{fg:e.fg}}}t.variables={...t.variables??{},...a},t.actions={...t.actions??{},...o},t.segments={...t.segments??{},...s}}var qc=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?el(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}},Jc=class extends qc{name=`ParseError`;kind=`ParseError`;expected;found;constructor(e,t,n={}){super(e,t,n),this.expected=n.expected,this.found=n.found}},Yc=class extends qc{name=`EvalError`;kind=`EvalError`},Xc=class extends Yc{name=`FuncNotFoundError`;kind=`FuncNotFoundError`;funcName;suggestions;constructor(e,t,n={}){let r=tl(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}},Zc=class extends Yc{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}},Qc=class extends Yc{name=`MissingFieldError`;kind=`MissingFieldError`;path;constructor(e,t,n={}){super(`field "${e.join(`.`)}" not found on receiver`,t,n),this.path=e}},$c=class extends Yc{name=`FailError`;kind=`FailError`;constructor(e,t={line:0,column:0,offset:0},n={}){super(e,t,n)}};function el(e,t){let n=e.split(`
|
|
42
42
|
`),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(`
|
|
43
43
|
`)}function tl(e,t){if(t.length===0)return[];let n=t.map(t=>({name:t,dist:nl(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 nl(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 rl(e){throw Error(`unhandled node kind: ${JSON.stringify(e)}`)}const il=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`]]),al={left:`{{`,right:`}}`};var ol=class{src;leftDelim;rightDelim;offset=0;line=1;column=1;mode=`text`;pending;constructor(e,t=al){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 Jc(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&&sl(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);sl(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);sl(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(;sl(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`;sl(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&&(ll(e)||cl(e)&&ll(this.src[this.offset+1]??``)||e===`.`&&ll(this.src[this.offset+1]??``)))return this.readNumber(t);if(e===`.`)return this.readDotOrField(t);if(e!==void 0&&ml(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===`
|
|
44
44
|
`)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===`
|
|
@@ -50,7 +50,7 @@ import{createRequire as e}from"node:module";import t from"node:process";import{j
|
|
|
50
50
|
`).map(e=>n+e).join(`
|
|
51
51
|
`)}function Zp(e){let t=new TextEncoder;return e.split(/\s+/).filter(e=>e.length>0).map(e=>String.fromCharCode(...t.encode(e).slice(0,1))).join(``)}function Qp(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw Hf(`join`,2,`list of strings/primitives`,`list element of type ${$p(e)}`);n.push(String(e))}return n.join(e)}function $p(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function em(e){return Up(e,`-`)}function tm(e){return e.toLowerCase()}function nm(e,t){return`\n${Xp(e,t)}`}function rm(e){return e.replace(/\s+/g,``)}function im(e,t,n){return n===1?e:t}function am(...e){return e.map(e=>`"${e}"`).join(` `)}function om(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function sm(e,t){return t.repeat(Math.max(0,e))}function cm(e,t,n){return n.split(e).join(t)}function lm(e){return Up(e,`_`)}function um(e,t){let n=t.split(e),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function dm(e,t){return t.split(e)}function fm(e,t,n){let r=pm(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function pm(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 mm(...e){return e.map(e=>`'${e}'`).join(` `)}function hm(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 gm(e){let t=``;for(let n of e)_m(n)?t+=n.toLowerCase():vm(n)?t+=n.toUpperCase():t+=n;return t}function _m(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function vm(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function ym(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function bm(e){return e.trim()}function xm(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 Sm(e,t){return t.startsWith(e)?t.slice(e.length):t}function Cm(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function wm(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 Tm(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function Em(e){return e.toUpperCase()}function Dm(e,t){return Om(e,`
|
|
52
52
|
`,t)}function Om(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
|
|
53
|
-
`)){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 km(e,t,n){return Om(e,t,n)}function Am(){return{abbrev:{fn:(e,t)=>kp(e,t),argTypes:[`int`,`string`]},abbrevboth:{fn:(e,t,n)=>Ap(e,t,n),argTypes:[`int`,`int`,`string`]},camelcase:{fn:e=>Gp(e),argTypes:[`string`],returnType:`string`},cat:{fn:(...e)=>Kp(...e),argTypes:[`string`]},contains:{fn:(e,t)=>qp(e,t),argTypes:[`string`,`string`]},hasPrefix:{fn:(e,t)=>Jp(e,t),argTypes:[`string`,`string`]},hasSuffix:{fn:(e,t)=>Yp(e,t),argTypes:[`string`,`string`]},indent:{fn:(e,t)=>Xp(e,t),argTypes:[`int`,`string`]},initials:{fn:e=>Zp(e),argTypes:[`string`]},join:{fn:(e,t)=>Qp(e,t),argTypes:[`string`,`list`]},kebabcase:{fn:e=>em(e),argTypes:[`string`],returnType:`string`},lower:{fn:e=>tm(e),argTypes:[`string`]},nindent:{fn:(e,t)=>nm(e,t),argTypes:[`int`,`string`]},nospace:{fn:e=>rm(e),argTypes:[`string`],returnType:`string`},plural:{fn:(e,t,n)=>im(e,t,n),argTypes:[`string`,`string`,`int`],returnType:`string`},quote:{fn:(...e)=>am(...e),argTypes:[`string`]},regexQuoteMeta:{fn:e=>om(e),argTypes:[`string`],returnType:`string`},repeat:{fn:(e,t)=>sm(e,t),argTypes:[`int`,`string`]},replace:{fn:(e,t,n)=>cm(e,t,n),argTypes:[`string`,`string`,`string`]},snakecase:{fn:e=>lm(e),argTypes:[`string`],returnType:`string`},split:{fn:(e,t)=>um(e,t),argTypes:[`string`,`string`]},splitList:{fn:(e,t)=>dm(e,t),argTypes:[`string`,`string`]},splitn:{fn:(e,t,n)=>fm(e,t,n),argTypes:[`string`,`int`,`string`],returnType:`dict`},squote:{fn:(...e)=>mm(...e),argTypes:[`string`]},substr:{fn:(e,t,n)=>hm(e,t,n),argTypes:[`int`,`int`,`string`]},swapcase:{fn:e=>gm(e),argTypes:[`string`],returnType:`string`},title:{fn:e=>ym(e),argTypes:[`string`]},trim:{fn:e=>bm(e),argTypes:[`string`]},trimAll:{fn:(e,t)=>xm(e,t),argTypes:[`string`,`string`]},trimPrefix:{fn:(e,t)=>Sm(e,t),argTypes:[`string`,`string`]},trimSuffix:{fn:(e,t)=>Cm(e,t),argTypes:[`string`,`string`]},trunc:{fn:(e,t)=>wm(e,t),argTypes:[`int`,`string`]},untitle:{fn:e=>Tm(e),argTypes:[`string`]},upper:{fn:e=>Em(e),argTypes:[`string`]},wrap:{fn:(e,t)=>Dm(e,t),argTypes:[`int`,`string`]},wrapWith:{fn:(e,t,n)=>km(e,t,n),argTypes:[`int`,`string`,`string`]}}}function jm(e){return e}function Mm(e,t,n){return n===void 0?bs+vs(e)+`.`+vs(t):Nm(n)}function Nm(e){return bs+vs(e)}function Pm(e,t){return e+`.`+t}function Fm(e){return e+`.page`}const Im=[`closeOnPick`,`paged`,`key`,`distribution`],Lm=e=>Im.includes(e),Rm=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${Vs.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function zm(e){for(let t of Object.keys(e))if(!Lm(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${Rm}`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);let r=e.distribution;if(r!==void 0&&!Hs(r))throw Error(`{{ menu }} option "distribution" must be one of: ${Vs.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Ws(r)}}const Bm=`menu`,Vm=`a menu binds its trigger text the way a cycle action binds a display — write {{ menu "applyTheme" "▸" "▾" }} (one per state) or {{ menu "insertHere" "+" }} (one static display for both), with the rare knobs in ONE trailing dict: {{ menu "applyTheme" "▸" "▾" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key). The renderer no longer appends ▸/▾ of its own (candybar-settings-ui-aok.4), and the older positional tail ("pageAction" closeOnPick paged "key") was removed — the page cursor is synthesized from the menu's identity`,Hm=e=>e.kind===`call`&&e.name===`dict`,Um=e=>e.kind===`literal`&&typeof e.value!=`object`,Wm=e=>pc(``,e,2)===void 0;function Gm(e){let t=e=>({kind:`issue`,message:e}),[n,...r]=e.argExprs;if(n===void 0)return t(`with no arguments — it takes an apply-action name and its trigger text (e.g. {{ menu "applyTheme" "▸" "▾" }})`);if(n.kind!==`literal`||typeof n.value!=`string`)return t(`whose apply action is not a string literal — a menu's identity is its apply-action name, which must be a literal so it can be gated at load (e.g. {{ menu "applyTheme" "▸" "▾" }})`);let i=r[r.length-1],a=i!==void 0&&Hm(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(Hm))return t(`whose options (dict …) is not its last argument — ${Vm}`);if(i!==void 0&&a===void 0&&!Um(i)&&Wm(o.length-1))return t(`whose last argument is neither a literal nor a literal (dict …) — the renderer tells a display from the options dict by the value it evaluates to, so this call could be read as ${o.length} displays or as ${o.length-1} plus options, and both are legal. Make the options explicit as a trailing (dict …) — {{ menu "${n.value}" (printf "…") (printf "…") (dict) }} binds dynamic displays unambiguously — or bind the trigger text as literals`);let s=pc(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${Vm}`);let c=a===void 0?{}:Sf(a);if(c===null)return t(`whose options (dict …) is not fully literal — every option value must be a literal so the menu can be gated at load (a dynamic entry like (dict "key" .x) cannot)`);let l;try{l=zm(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=Ts(u);if(e!==void 0)return t(`whose accordion key "${u}" lands in the reserved "${e}" namespace — a key is collapsed to an identifier (${JSON.stringify(u)} becomes "${Nm(u)}"), so it would share one open-state key with the synthesized accordion that owns that namespace instead of grouping only your own menus. Name the group without the reserved prefix`)}return{kind:`ok`,apply:n.value,options:l}}function Km(e){let t=Mu({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===Bm).map(Gm)}catch{return`parse-failed`}}function qm(e){let t=Mu({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(Bm)}catch{return!1}}function Jm(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function Ym(e,t){Es(e,t,bs,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))qm(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:G(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&qm(i)&&Jm(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}if(t.root!==void 0)for(let n of wa(go(t.root)))typeof n.when==`string`&&qm(n.when)&&Jm(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.`);let r=new Set,i={},a=new Set,o=new Map;for(let[t,{template:s}]of Object.entries(n)){if(s===void 0||!qm(s))continue;let n=Km(s);if(n!==`parse-failed`)for(let s of n){if(s.kind===`issue`){Jm(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${s.message}.`);continue}let{apply:n,options:c}=s;if(n===``){Jm(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 l=jm(n);if(l===`closed`){Jm(e,`segments.${t}`,`segment "${t}" has a {{ menu }} whose apply action is named "${fc}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action.`);continue}let u=Mm(t,n,c.key),d=Fm(u),f=c.key===void 0?`ind${t}${n}`:`key${c.key}`,p=[u,d].find(e=>{let t=o.get(e);return t!==void 0&&t!==f});if(p!==void 0){Jm(e,`segments.${t}`,`two {{ menu }} disclosures normalize to the same state key ("${p}") 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}o.set(u,f),o.set(d,f);let m=Pm(u,l);if(a.has(m)){Jm(e,`segments.${t}`,`two {{ menu }} disclosures resolve to the same identity ("${m}") — ${c.key===void 0?`a segment cannot contain two menus over the same apply action "${n}"`:`menus sharing key "${c.key}" must have distinct apply actions`}.`);continue}a.add(m),r.add(u),i[m]=xc(u,l)}}if(r.size===0)return;let s={};for(let e of r){s[e]=bc(e,fc);let t=Fm(e);s[t]={kind:`state`,key:t,default:`0`},i[t]={set:t,int:!0}}t.variables={...t.variables??{},...s},t.actions={...t.actions??{},...i}}const Xm=`edit.mode`,Zm=`edit.toggle`,Qm=`open`,$m={variable:Xm,member:Qm},eh=_c($m);function th(e){let t=Mu({fromString:e=>e});try{return t.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function nh(e){for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&th(e))return!0;return!1}function rh(e,t){if(Es(e,t,xs,`edit mode`),!nh(t))return;let n={[Xm]:bc(Xm,fc)},r={[Zm]:xc(Xm,Qm)};t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function ih(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function ah(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function oh(e){let t=new Set;for(let n of wa(e))n.kind===`segment`&&t.add(n.name);return t}const sh=`default`,ch={};function lh(e){return[...new Set([sh,...Object.keys(e)])]}function uh(e,t,n){return ui(void 0,e,t,sh,n)}function dh(e,t){let n={[sh]:ch,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${sh}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function fh(e,t){let n=dh(e.presets,t).root??uo;return{node:ho(_o(n,e.root)),path:vo(n)?`presets.${t}.root`:`root`}}function ph(e,t){return{...e.globals,...dh(e.presets,t).globals}}const mh=/^segments\.([^.]+)\.palette$/,hh=/^presets\.(.+)\.root$/;function gh(e){return`presets.${e}.root`}function _h(e){if(Mo(e))return{scope:`globals`,field:e};let t=mh.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=hh.exec(e);return n?{scope:`preset-root`,preset:n[1]}:null}function vh(e){return e.scope===`globals`?[`globals`,e.field]:[`segments`,e.segment,`palette`]}const yh=`open`;function bh(e,t,n,r){let i={variable:e,member:yh};return r.variables[e]=bc(e,fc),r.actions[e]=xc(e,yh),r.segments[e]={template:yc(e,`(?)`,`✕`),...xh(n)},gc(e,i,{kind:`container`,direction:`horizontal`,children:t.map((t,n)=>{let i=`${e}.${n}`;return r.segments[i]={template:t},{kind:`segment`,name:i}})})}function xh(e){let[t,...n]=e;return t===void 0?{}:{when:_c(t,...n)}}const Sh={help:[`-h`,`--help`],version:[`-V`,`--version`]},Ch=[`+ inserts here`,`- removes the one left of it`,`↺ undoes edits`],wh=[`☐ this session only`,`☑ default for every session`],Th=`
|
|
53
|
+
`)){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 km(e,t,n){return Om(e,t,n)}function Am(){return{abbrev:{fn:(e,t)=>kp(e,t),argTypes:[`int`,`string`]},abbrevboth:{fn:(e,t,n)=>Ap(e,t,n),argTypes:[`int`,`int`,`string`]},camelcase:{fn:e=>Gp(e),argTypes:[`string`],returnType:`string`},cat:{fn:(...e)=>Kp(...e),argTypes:[`string`]},contains:{fn:(e,t)=>qp(e,t),argTypes:[`string`,`string`]},hasPrefix:{fn:(e,t)=>Jp(e,t),argTypes:[`string`,`string`]},hasSuffix:{fn:(e,t)=>Yp(e,t),argTypes:[`string`,`string`]},indent:{fn:(e,t)=>Xp(e,t),argTypes:[`int`,`string`]},initials:{fn:e=>Zp(e),argTypes:[`string`]},join:{fn:(e,t)=>Qp(e,t),argTypes:[`string`,`list`]},kebabcase:{fn:e=>em(e),argTypes:[`string`],returnType:`string`},lower:{fn:e=>tm(e),argTypes:[`string`]},nindent:{fn:(e,t)=>nm(e,t),argTypes:[`int`,`string`]},nospace:{fn:e=>rm(e),argTypes:[`string`],returnType:`string`},plural:{fn:(e,t,n)=>im(e,t,n),argTypes:[`string`,`string`,`int`],returnType:`string`},quote:{fn:(...e)=>am(...e),argTypes:[`string`]},regexQuoteMeta:{fn:e=>om(e),argTypes:[`string`],returnType:`string`},repeat:{fn:(e,t)=>sm(e,t),argTypes:[`int`,`string`]},replace:{fn:(e,t,n)=>cm(e,t,n),argTypes:[`string`,`string`,`string`]},snakecase:{fn:e=>lm(e),argTypes:[`string`],returnType:`string`},split:{fn:(e,t)=>um(e,t),argTypes:[`string`,`string`]},splitList:{fn:(e,t)=>dm(e,t),argTypes:[`string`,`string`]},splitn:{fn:(e,t,n)=>fm(e,t,n),argTypes:[`string`,`int`,`string`],returnType:`dict`},squote:{fn:(...e)=>mm(...e),argTypes:[`string`]},substr:{fn:(e,t,n)=>hm(e,t,n),argTypes:[`int`,`int`,`string`]},swapcase:{fn:e=>gm(e),argTypes:[`string`],returnType:`string`},title:{fn:e=>ym(e),argTypes:[`string`]},trim:{fn:e=>bm(e),argTypes:[`string`]},trimAll:{fn:(e,t)=>xm(e,t),argTypes:[`string`,`string`]},trimPrefix:{fn:(e,t)=>Sm(e,t),argTypes:[`string`,`string`]},trimSuffix:{fn:(e,t)=>Cm(e,t),argTypes:[`string`,`string`]},trunc:{fn:(e,t)=>wm(e,t),argTypes:[`int`,`string`]},untitle:{fn:e=>Tm(e),argTypes:[`string`]},upper:{fn:e=>Em(e),argTypes:[`string`]},wrap:{fn:(e,t)=>Dm(e,t),argTypes:[`int`,`string`]},wrapWith:{fn:(e,t,n)=>km(e,t,n),argTypes:[`int`,`string`,`string`]}}}function jm(e){return e}function Mm(e,t,n){return n===void 0?bs+vs(e)+`.`+vs(t):Nm(n)}function Nm(e){return bs+vs(e)}function Pm(e,t){return e+`.`+t}function Fm(e){return e+`.page`}const Im=[`closeOnPick`,`paged`,`key`,`distribution`],Lm=e=>Im.includes(e),Rm=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${Vs.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function zm(e){for(let t of Object.keys(e))if(!Lm(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${Rm}`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);let r=e.distribution;if(r!==void 0&&!Hs(r))throw Error(`{{ menu }} option "distribution" must be one of: ${Vs.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Ws(r)}}const Bm=`menu`,Vm=`a menu binds its trigger text the way a cycle action binds a display — write {{ menu "applyTheme" "▸" "▾" }} (one per state) or {{ menu "insertHere" "+" }} (one static display for both), with the rare knobs in ONE trailing dict: {{ menu "applyTheme" "▸" "▾" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key). The renderer no longer appends ▸/▾ of its own (candybar-settings-ui-aok.4), and the older positional tail ("pageAction" closeOnPick paged "key") was removed — the page cursor is synthesized from the menu's identity`,Hm=e=>e.kind===`call`&&e.name===`dict`,Um=e=>e.kind===`literal`&&typeof e.value!=`object`,Wm=e=>pc(``,e,2)===void 0;function Gm(e){let t=e=>({kind:`issue`,message:e}),[n,...r]=e.argExprs;if(n===void 0)return t(`with no arguments — it takes an apply-action name and its trigger text (e.g. {{ menu "applyTheme" "▸" "▾" }})`);if(n.kind!==`literal`||typeof n.value!=`string`)return t(`whose apply action is not a string literal — a menu's identity is its apply-action name, which must be a literal so it can be gated at load (e.g. {{ menu "applyTheme" "▸" "▾" }})`);let i=r[r.length-1],a=i!==void 0&&Hm(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(Hm))return t(`whose options (dict …) is not its last argument — ${Vm}`);if(i!==void 0&&a===void 0&&!Um(i)&&Wm(o.length-1))return t(`whose last argument is neither a literal nor a literal (dict …) — the renderer tells a display from the options dict by the value it evaluates to, so this call could be read as ${o.length} displays or as ${o.length-1} plus options, and both are legal. Make the options explicit as a trailing (dict …) — {{ menu "${n.value}" (printf "…") (printf "…") (dict) }} binds dynamic displays unambiguously — or bind the trigger text as literals`);let s=pc(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${Vm}`);let c=a===void 0?{}:Sf(a);if(c===null)return t(`whose options (dict …) is not fully literal — every option value must be a literal so the menu can be gated at load (a dynamic entry like (dict "key" .x) cannot)`);let l;try{l=zm(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=Ts(u);if(e!==void 0)return t(`whose accordion key "${u}" lands in the reserved "${e}" namespace — a key is collapsed to an identifier (${JSON.stringify(u)} becomes "${Nm(u)}"), so it would share one open-state key with the synthesized accordion that owns that namespace instead of grouping only your own menus. Name the group without the reserved prefix`)}return{kind:`ok`,apply:n.value,options:l}}function Km(e){let t=Mu({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===Bm).map(Gm)}catch{return`parse-failed`}}function qm(e){let t=Mu({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(Bm)}catch{return!1}}function Jm(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function Ym(e,t){Es(e,t,bs,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))qm(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:G(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&qm(i)&&Jm(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}if(t.root!==void 0)for(let n of wa(go(t.root)))typeof n.when==`string`&&qm(n.when)&&Jm(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.`);let r=new Set,i={},a=new Set,o=new Map;for(let[t,{template:s}]of Object.entries(n)){if(s===void 0||!qm(s))continue;let n=Km(s);if(n!==`parse-failed`)for(let s of n){if(s.kind===`issue`){Jm(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${s.message}.`);continue}let{apply:n,options:c}=s;if(n===``){Jm(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 l=jm(n);if(l===`closed`){Jm(e,`segments.${t}`,`segment "${t}" has a {{ menu }} whose apply action is named "${fc}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action.`);continue}let u=Mm(t,n,c.key),d=Fm(u),f=c.key===void 0?`ind${t}${n}`:`key${c.key}`,p=[u,d].find(e=>{let t=o.get(e);return t!==void 0&&t!==f});if(p!==void 0){Jm(e,`segments.${t}`,`two {{ menu }} disclosures normalize to the same state key ("${p}") 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}o.set(u,f),o.set(d,f);let m=Pm(u,l);if(a.has(m)){Jm(e,`segments.${t}`,`two {{ menu }} disclosures resolve to the same identity ("${m}") — ${c.key===void 0?`a segment cannot contain two menus over the same apply action "${n}"`:`menus sharing key "${c.key}" must have distinct apply actions`}.`);continue}a.add(m),r.add(u),i[m]=xc(u,l)}}if(r.size===0)return;let s={};for(let e of r){s[e]=bc(e,fc);let t=Fm(e);s[t]={kind:`state`,key:t,default:`0`},i[t]={set:t,int:!0}}t.variables={...t.variables??{},...s},t.actions={...t.actions??{},...i}}const Xm=`edit.mode`,Zm=`edit.toggle`,Qm=`open`,$m={variable:Xm,key:Xm,member:Qm},eh=_c($m);function th(e){let t=Mu({fromString:e=>e});try{return t.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function nh(e){for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&th(e))return!0;return!1}function rh(e,t){if(Es(e,t,xs,`edit mode`),!nh(t))return;let n={[Xm]:bc(Xm,fc)},r={[Zm]:xc(Xm,Qm)};t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function ih(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function ah(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function oh(e){let t=new Set;for(let n of wa(e))n.kind===`segment`&&t.add(n.name);return t}const sh=`default`,ch={};function lh(e){return[...new Set([sh,...Object.keys(e)])]}function uh(e,t,n){return ui(void 0,e,t,sh,n)}function dh(e,t){let n={[sh]:ch,...e}[t];if(n===void 0)throw Error(`Preset "${t}" is not declared in this config — effectivePresetName collapses unknown names to "${sh}", which always resolves; a miss here means a raw name reached this function without going through that resolution`);return n}function fh(e,t){let n=dh(e.presets,t).root??uo;return{node:ho(_o(n,e.root)),path:vo(n)?`presets.${t}.root`:`root`}}function ph(e,t){return{...e.globals,...dh(e.presets,t).globals}}const mh=/^segments\.([^.]+)\.palette$/,hh=/^presets\.(.+)\.root$/;function gh(e){return`presets.${e}.root`}function _h(e){if(Mo(e))return{scope:`globals`,field:e};let t=mh.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=hh.exec(e);return n?{scope:`preset-root`,preset:n[1]}:null}function vh(e){return e.scope===`globals`?[`globals`,e.field]:[`segments`,e.segment,`palette`]}const yh=`open`;function bh(e,t,n,r){let i={variable:e,key:e,member:yh};return r.variables[e]=bc(e,fc),r.actions[e]=xc(e,yh),r.segments[e]={template:yc(e,`(?)`,`✕`),...xh(n)},gc(e,i,{kind:`container`,direction:`horizontal`,children:t.map((t,n)=>{let i=`${e}.${n}`;return r.segments[i]={template:t},{kind:`segment`,name:i}})})}function xh(e){let[t,...n]=e;return t===void 0?{}:{when:_c(t,...n)}}const Sh={help:[`-h`,`--help`],version:[`-V`,`--version`]},Ch=[`+ inserts here`,`- removes the one left of it`,`↺ undoes edits`],wh=[`☐ this session only`,`☑ default for every session`],Th=`
|
|
54
54
|
cc-candybar - Beautiful powerline statusline for Claude Code
|
|
55
55
|
|
|
56
56
|
Usage: cc-candybar [options]
|
|
@@ -115,14 +115,14 @@ Config tooling:
|
|
|
115
115
|
config [--json] The effective merged config. (All three query the
|
|
116
116
|
running daemon; none spawn one.)
|
|
117
117
|
|
|
118
|
-
`,Eh=`preset.customized`,Dh=`{{ and ${vc($m)} .${Eh} }}`,Oh=ws;function kh(e){return`${xs}addable.${e}`}function Ah(e){let t=Object.keys(e.segments).filter(e=>!Oh(e)),n=new Map;for(let r of lh(e.presets)){let{node:i}=fh(e,r),a=oh(i);n.set(kh(r),{members:t.filter(e=>!a.has(e))})}return n}function jh(e,t,n,r){let i=`${xs}${e}.remove.${vs(n)}`,a=`${xs}${e}.removeSeg.${vs(n)}`;return r.actions[i]={persist:t,removeSegment:n},r.segments[a]={template:`{{ action "${i}" "-" }}`,when:eh},{kind:`segment`,name:a}}function Mh(e,t,n,r,i,a,o){let s=`${xs}${e}.insert.${n}`,c=`${xs}${e}.insertSeg.${n}`;o.actions[s]={persist:t,insertSegmentFrom:r,anchor:i,relation:a};let l=jm(s),u=Mm(c,s,void 0),d=Fm(u),f=Pm(u,l);return o.variables[u]=bc(u,fc),o.variables[d]={kind:`state`,key:d,default:`0`},o.actions[f]=xc(u,l),o.actions[d]={set:d,int:!0},o.segments[c]={template:`{{ menu "${s}" "+" "✕" }}`,when:eh},{kind:`segment`,name:c}}function Nh(e,t,n,r,i,a){let o=[],s=e.children.reduce((e,t,n)=>t.kind===`segment`&&!Oh(t.name)?n:e,-1),c=e=>Nh(e,t,n,r,i,a);for(let[l,u]of e.children.entries()){if(u.kind===`container`){o.push(c(u));continue}let d=Ca(u,c);if(Oh(u.name)){o.push(d);continue}let f=[Mh(t,n,String(a.n++),r,u.name,`before`,i),d,jh(t,n,u.name,i),...l===s?[Mh(t,n,String(a.n++),r,u.name,`after`,i)]:[]];o.push(...e.direction===`vertical`?[{kind:`container`,direction:`horizontal`,children:f,...u.when!==void 0&&{when:u.when}}]:f)}return{...e,children:o}}function Ph(e,t,n,r,i,a){let o=`${xs}${n}.resetLayout`,s=`${xs}${n}.customized`;i.actions[o]={reset:r},i.ensured[Eh]={kind:`input`,path:Eh,type:`boolean`,default:!1};let c=hc(t);return i.segments[s]={template:`{{ action "${o}" "↺ ${c} customized" }}`,when:Dh},{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:s},Fh(e,a)],...e.when!==void 0&&{when:e.when}}}function Fh(e,t){if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t]};let n=e.children.at(-1);return e.direction===`vertical`&&n!==void 0&&(n.kind===`segment`||n.when===void 0)?{...e,children:[...e.children.slice(0,-1),Fh(n,t)]}:{...e,children:[...e.children,t]}}function Ih(e,t,n,r){let{node:i}=fh(e,t),a=gh(t),o=kh(t),s=vs(t);return Ph(Nh(i,s,a,o,n,{n:0}),t,s,a,n,r)}function Lh(e){if(!(`edit.toggle`in e.actions))return e;let t={variables:{},ensured:{},actions:{},segments:{}},n=bh(`${xs}help`,Ch,[$m],t),r={...e.presets};for(let i of lh(e.presets)){let a=Ih(e,i,t,n);r[i]={...dh(e.presets,i),root:a}}return{...e,variables:{...t.ensured,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:r}}const Rh={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function zh(e){let t=e[Rh.socket]??``,n=e[Rh.pane]??``;if(t===``||n===``)return null;let r=e[Rh.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const Bh=Rh.truecolor,Vh=[{name:`tmuxTruecolor`,label:`tmux truecolor`,probe:({tmux:e,claudeSettingsEnv:t})=>{switch(e.kind){case`unreported`:return{ok:!1,reason:"the client reported no tmux facts — re-run `cc-candybar install` to stage a current client"};case`outside`:return{ok:!0};case`inside`:{if(e.termfeatures.kind===`failed`)return{ok:!1,reason:`tmux could not be asked: ${e.termfeatures.reason}`};if(!e.termfeatures.value.includes(`RGB`)||e.hint.truecolor!==null)return{ok:!0};let n=t[Bh];return typeof n==`string`&&n!==``?{ok:!1,reason:`${Bh} is set in ~/.claude/settings.json — restart Claude Code to apply`}:{ok:!1,reason:`Claude Code renders the bar in 256 colours inside tmux`,fix:{kind:`claude-settings-env`,name:Bh,value:`1`}}}}}}];function Hh(e){return Vh.map(t=>({check:t,verdict:t.probe(e)}))}function Uh(e){return Vh.find(t=>t.name===e)}function Wh(e){let t=`settings.doctor.${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`}}function Gh(e){return e.flatMap(({check:e,verdict:t})=>{let n=Wh(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:``},{key:n.fixable,value:Ti}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:t.reason},{key:n.fixable,value:t.fix===void 0?Ti:wi}]})}const Kh=`${Ss}menu`,qh=Qm,Jh=`${Ss}edit`,Yh=`${Ss}persist`,Xh=`${Ss}config`,Zh=Yh,Qh={variable:Kh,member:qh},$h={variable:Xh,member:qh},eg=`${Ss}tools`,tg={variable:eg,member:qh},ng=`${Ss}doctor`,rg=`${ng}.run`,ig=e=>`${ng}.fix.${e}`,ag=e=>`${ng}.${e}`,og=`${Ss}help.persist`,sg={bg:`{{ color "accent" }}`,fg:`{{ contrastOn (bgOf) }}`},cg=`${Ss}pickers`,lg=[{name:`preset`,sessionKey:`preset`,configKey:`preset`,effectiveVar:`preset.effective`,glyph:`▦`,domain:`presets`}],ug=[{name:`theme`,sessionKey:`theme`,configKey:`palette`,effectiveVar:`theme.effective`,glyph:`🎨`,domain:`themes`},{name:`look`,sessionKey:`look`,configKey:`look`,effectiveVar:`look.effective`,glyph:`◐`,domain:`looks`},{name:`style`,sessionKey:`style`,configKey:`style`,effectiveVar:`style.effective`,glyph:`✦`,domain:`styles`}],dg={name:`wrap`,sessionKey:`autoWrap`,configKey:`autoWrap`},fg={name:`padding`,sessionKey:`padding`,configKey:`padding`},pg=`${Ss}${dg.name}`,mg=`${Ss}${fg.name}`,hg=[...lg,...ug];new Set([...hg,dg,fg].flatMap(e=>[e.sessionKey,e.configKey]));const gg=e=>`${Ss}${e}`,_g=e=>`${Ss}apply.${e}`,vg=e=>`${Ss}reset.${e}`;function yg(e){return e===Kh}function bg(e){let t={kind:`segment`,name:Kh};if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[t,e],...e.when!==void 0&&{when:e.when}};let[n,...r]=e.children;return e.direction===`vertical`&&n!==void 0&&n.when===void 0?{...e,children:[bg(n),...r]}:{...e,children:[t,...e.children]}}function xg(e){return Sg(e)>0?e:bg(e)}function Sg(e){let t=0;for(let n of wa(e))n.kind===`segment`&&yg(n.name)&&(t+=1);return t}function Cg(e,t){return e.kind===`segment`?yg(e.name)?gc(e.name,Qh,{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:Yh},t,...lg.map(e=>({kind:`segment`,name:gg(e.name)})),gc(Xh,$h,{kind:`container`,direction:`horizontal`,children:[...ug.map(e=>({kind:`segment`,name:gg(e.name)})),{kind:`segment`,name:pg},{kind:`segment`,name:mg}]}),gc(eg,tg,{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:ng},...Vh.map(e=>({kind:`segment`,name:ag(e.name)}))]}),{kind:`segment`,name:Jh}]},e.when):Ca(e,e=>wg(e,t)):wg(e,t)}function wg(e,t){return{...e,children:e.children.map(e=>Cg(e,t))}}function Tg(e,t,n,r){let i=jm(t),a=Mm(e,t,r),o=Fm(a);n.variables[a]=bc(a,fc),n.variables[o]={kind:`state`,key:o,default:`0`},n.actions[Pm(a,i)]=xc(a,i),n.actions[o]={set:o,int:!0}}function Eg(){let e={variables:{[Kh]:bc(Kh,fc)},actions:{[Kh]:xc(Kh,qh),[Xh]:xc(Xh,qh),[eg]:xc(eg,qh),[rg]:{doctor:`run`},[Yh]:{set:Zh,cycle:[Ti,wi]}},segments:{[Kh]:{template:yc(Kh,`☰`,`✕`),...sg},[Yh]:{template:`{{ action "${Yh}" "☐ persist?" "☑ persist?" }}`},[Xh]:{template:yc(Xh,`⚙ config ▸`,`⚙ config ▾`)},[eg]:{template:yc(eg,`🧰 tools ▸`,`🧰 tools ▾`)},[ng]:{template:`{{ action "${rg}" "🩺 doctor" }}`},[pg]:{template:`{{ action "${_g(`wrap`)}" "wrap: on" "wrap: off" }} {{ action "${vg(`wrap`)}" "↺" }}`},[mg]:{template:`{{ action "${_g(`padding`)}.down" "◀" }} padding {{ .padding.effective }} {{ action "${_g(`padding`)}.up" "▶" }} {{ action "${vg(`padding`)}" "↺" }}`},[Jh]:{template:`{{ action "${Zm}" "✎ edit" "✎ done" }}`}}};return e.variables[Zh]={kind:`state`,key:Zh,default:Ti},e.variables[Xh]=bc(Xh,fc),e.variables[eg]=bc(eg,fc),Og(e),Dg(e),{artifacts:e,help:bh(og,wh,[Qh],e)}}function Dg(e){for(let t of Vh){let n=Wh(t.name),r=ig(t.name);for(let t of Object.values(n))e.variables[t]={kind:`state`,key:t,default:``};e.actions[r]={doctor:`fix`,check:t.name},e.segments[ag(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${wi}" }} {{ action "${r}" "[fix]" }}{{ end }}{{ end }}`}}}function Og(e){for(let t of hg){let n=gg(t.name),r=_g(t.name);e.segments[n]={template:`${t.glyph} {{ .${t.effectiveVar} }} {{ menu "${r}" "▸" "▾" (dict "key" "${cg}" "closeOnPick" true) }} {{ action "${vg(t.name)}" "↺" }}`},e.actions[r]={set:t.sessionKey,persist:t.configKey,persistWhen:Zh,from:t.domain},e.actions[vg(t.name)]={reset:t.configKey},Tg(n,r,e,cg)}e.actions[_g(dg.name)]={set:dg.sessionKey,persist:dg.configKey,persistWhen:Zh,cycle:[...Ei]},e.actions[vg(dg.name)]={reset:dg.configKey};for(let t of[-1,1])e.actions[`${_g(fg.name)}.${t<0?`down`:`up`}`]={set:fg.sessionKey,persist:fg.configKey,persistWhen:Zh,...Di,by:t};e.actions[vg(fg.name)]={reset:fg.configKey}}function kg(e){e.variables[Xm]=bc(Xm,fc),e.actions[Zm]=xc(Xm,Qm)}const Ag=`session.id`;function jg(e){return Object.prototype.hasOwnProperty.call(e.variables,Ag)}function Mg(e){if(!jg(e))return e;let{artifacts:t,help:n}=Eg();kg(t);let r={...e.presets};for(let t of lh(e.presets)){let{node:i}=fh(e,t);r[t]={...dh(e.presets,t),root:Cg(xg(i),n)}}return{...e,variables:{...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:r}}const Ng=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`doctor`],Pg=`persistWhen`;function Fg(e){return Pg in e}function Ig(e){return Fg(e)?`to`in e?[{set:e.set,to:e.to},{persist:e.persist,to:e.to}]:`from`in e?[{set:e.set,from:e.from},{persist:e.persist,from:e.from}]:`cycle`in e?[{set:e.set,cycle:e.cycle},{persist:e.persist,cycle:e.cycle}]:[{set:e.set,min:e.min,max:e.max,by:e.by},{persist:e.persist,min:e.min,max:e.max,by:e.by}]:[e]}function Lg(e){return`set`in e}function Rg(e){return`persist`in e}function zg(e){return`reset`in e}function Bg(e){return`undo`in e}function Vg(e){return`redo`in e}function Hg(e){return`doctor`in e}function Ug(e,t){if(t===void 0)return{};if(!Ra(t))return J(e,`actions`,`actions must be an object, got ${za(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=Wg(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function J(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function Wg(e,t,n){if(!Ra(n))return J(e,t,`${t} must be an action object, got ${za(n)}`),null;if(`persistWhen`in n)return S_(e,t,n,`dual`,y_);let r=Ng.filter(e=>e in n);return r.length===1?Gg[r[0]](e,t,n):(J(e,t,`action must declare exactly one of: ${Ng.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const Gg={set:(e,t,n)=>S_(e,t,n,`set`,__),persist:(e,t,n)=>S_(e,t,n,`persist`,v_),copy:Kg(`copy`),open:Kg(`open`),reset:qg,undo:Jg(`undo`),redo:Jg(`redo`),doctor:Yg};function Kg(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&J(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Na(t,n,r,e);return i===null?null:{[e]:i}}}function qg(e,t,n){for(let r of Object.keys(n))r!==`reset`&&J(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=Xg(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}function Jg(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&J(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(J(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — it steps the history of the session's config file), got ${Ba(r[e])}`),null)}}function Yg(e,t,n){let r=n.doctor,i=r===`run`?[`doctor`]:[`doctor`,`check`];for(let r of Object.keys(n))i.includes(r)||J(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${i.join(`, `)}`);if(r!==`run`&&r!==`fix`)return J(e,`${t}.doctor`,`doctor must be "run" or "fix", got ${Ba(r)}`),null;if(r===`run`)return{doctor:`run`};let a=n.check;return typeof a!=`string`||Uh(a)===void 0?(J(e,`${t}.check`,`doctor fix must name a check (have: ${Vh.map(e=>e.name).join(`, `)}), got ${Ba(a)}`),null):{doctor:`fix`,check:a}}function Xg(e,t,n,r,i,a){let o=Na(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(J(e,s,i),null):o.includes(`/`)?(J(e,s,a(o)),null):o}const Zg={set:[[`set`,`the SessionState key to write`]],persist:[[`persist`,`the config globals field to write`]],dual:[[`set`,`the SessionState key written while persistWhen is off`],[`persist`,`the config globals field written while persistWhen is on`],[Pg,`the SessionState key whose boolean value chooses the destination`]]};function Qg(e,t,n,r){let i={},a=Zg[r],o=!0;for(let[r,s]of a){if(!(r in n)){J(e,t,`${r} is required here (${s}) — a dual-destination action declares ${a.map(([e])=>e).join(`, `)} together, plus one value source`),o=!1;continue}let c=Xg(e,t,r,n,`${r} key must be non-empty (${s})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);if(c===null){o=!1;continue}i[r]=c}return o?i:null}function $g(e){return e===`set`?`set-state`:e===`persist`?`set-config`:`set-state/set-config`}const e_={to:C_(`set`)},t_={to:C_(`persist`)},n_={from:w_(`set`)},r_={from:w_(`persist`)},i_={min:k_(),max:k_(),by:k_()},a_={int:E_()},o_={cycle:T_(`set`)},s_={to:C_(`dual`)},c_={from:w_(`dual`)},l_={cycle:T_(`dual`)},u_={cycle:T_(`persist`)},d_={removeSegment:D_(`removeSegment`)},f_={insertSegment:D_(`insertSegment`),anchor:D_(`anchor`),relation:O_()},p_={insertSegmentFrom:w_(`persist`),anchor:D_(`anchor`),relation:O_()},m_={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},h_={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function g_(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=Zg[e].map(([e])=>e),s=(e,n,r)=>Ha(e,t,n,r),c=ro(t);return{detect:a,allowed:[...o,...i],label:i.join(`/`),json:{type:`object`,properties:{...Object.fromEntries(o.map(e=>[e,{type:`string`}])),...c.properties},required:[...o,...c.required??[]],additionalProperties:!1},parse:n.length?Xa(s,...n):s}}const __=[g_(`set`,e_),g_(`set`,n_),g_(`set`,i_,[m_,h_]),g_(`set`,a_),g_(`set`,o_)],v_=[g_(`persist`,t_),g_(`persist`,r_),g_(`persist`,i_,[m_,h_]),g_(`persist`,u_),g_(`persist`,d_),g_(`persist`,f_,[],[`insertSegment`]),g_(`persist`,p_,[],[`insertSegmentFrom`])],y_=[g_(`dual`,s_),g_(`dual`,c_),g_(`dual`,i_,[m_,h_]),g_(`dual`,l_)];function b_(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"styles"/"looks", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function x_(e){let t=b_(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function S_(e,t,n,r,i){let a=Qg(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return J(e,t,`${x_(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||J(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function C_(e){let t=$g(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>Xg(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function w_(e){let t=$g(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){J(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){J(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){J(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){J(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){J(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}J(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${Ba(o)}`)}}}function T_(e){let t=$g(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){J(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${za(o)}`);return}let c=o;if(c.length<2){J(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){J(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){J(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){J(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function E_(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){J(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${Ba(r[n])}`);return}return!0}}}function D_(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Na(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){J(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){J(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function O_(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){J(e,`${t}.${n}`,`relation must be "before" or "after", got ${Ba(i)}`);return}return i}}}function k_(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){J(e,`${t}.${n}`,`${n} must be an integer, got ${Ba(i)}`);return}return i}}}const A_={noun:`look key`,fields:{hueShift:$a(),chromaScale:$a({min:0}),lightnessScale:$a(),lightnessShift:$a()}};function j_(e,t){if(!Ra(t))return e.issues.push({path:`looks`,message:`looks must be an object mapping look names to adaptation objects, got ${za(t)}`,line:G(e.source,[`looks`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`looks.${r}`,message:`look name ${JSON.stringify(r)} must be non-empty and slash-free — a look picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:G(e.source,[`looks`,r])});continue}let t=Va(e,A_,`looks.${r}`,i);t!==null&&(n[r]={...gn,...t})}return n}const M_={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:Rc(e,`${t}.${n}`,r[n])},globals:{required:!1,json:ko(),parse:(e,t,n,r)=>r[n]===void 0?void 0:Oo(e,`${t}.${n}`,r[n])}}};function N_(e,t){if(!Ra(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${za(t)}`,line:G(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:G(e.source,[`presets`,r])});continue}let t=Va(e,M_,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function P_(e,t){if(t===void 0)return{};if(!Ra(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${za(t)}`,line:G(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${Ba(i)}`,line:G(e.source,[`helpers`,r])});continue}n[r]=i}return n}const F_=new Map,I_=new Map;function L_(e){let t=R_(e);if(t===null)throw Error(`Palette "${e}" (resolved "${ai(e)}") did not resolve in the theme registry — allowed names and the registry are inconsistent`);return t}function R_(e){let t=ai(e),n=F_.get(t);if(n!==void 0)return n;let r=Kn(t);return r===null?null:(F_.set(t,r),r)}function z_(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=I_.get(n);if(r!==void 0)return r;let i=tr(e,t);return I_.set(n,i),i}function B_(e){let t=R_(e);return t===null?null:{kind:`decided`,name:e,value:t}}function V_(e,t){let n=B_(e);return n===null?(t(`globals.palette rendered "${oi}": "${e}" names no installed theme`),B_(oi)):n}function H_(e,t,n){return pi(e,t,n,B_(oi),B_)}function U_(){return B_(oi)}function W_(e){return mi(H_(void 0,null,e),()=>oi,U_).value}const G_=new Map;function K_(e,t,n){G_.set(e,{permanent:!0,resolve:t,paletteOf:n})}K_(`themes`,()=>li(),e=>L_(e)),K_(`styles`,()=>yi),K_(`charsets`,()=>Si),K_(`colorCompatibilities`,()=>Ci);function q_(e){return new Map([[`looks`,{members:Object.keys(e.looks),paletteOf:(t,n)=>z_(n,e.looks[t])}],[`presets`,{members:lh(e.presets)}]])}function J_(e){return[...new Set([...G_.keys(),...e.keys()])]}function Y_(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=G_.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf};throw Error(`unknown option domain "${e}" (have: ${J_(t).join(`, `)})`)}const X_=/{{([\s\S]*?)}}/g,Z_=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g,Q_=/(?<![A-Za-z0-9_)])\.([A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*)/g;function $_(e){let t=new Set,n;for(X_.lastIndex=0;(n=X_.exec(e))!==null;){let e=n[1].replace(Z_,``),r;for(Q_.lastIndex=0;(r=Q_.exec(e))!==null;)t.add(r[1])}return t}const ev=/\baction\s+$/;function tv(e){let t=new Set;X_.lastIndex=0;let n;for(;(n=X_.exec(e))!==null;){let e=n[1],r=0,i;for(Z_.lastIndex=0;(i=Z_.exec(e))!==null;)ev.test(e.slice(r,i.index))&&t.add(i[0].slice(1,-1)),r=i.index+i[0].length}return t}const nv=/\b(picker|menu)\s+$/;function rv(e){let t=new Set;X_.lastIndex=0;let n;for(;(n=X_.exec(e))!==null;){let e=n[1],r=0,i=0,a;for(Z_.lastIndex=0;(a=Z_.exec(e))!==null;){let n=nv.exec(e.slice(r,a.index));n!==null&&(i=n[1]===`picker`?2:1),i>0&&(t.add(a[0].slice(1,-1)),i--),r=a.index+a[0].length}}return t}function iv(e,t){if(t.names.has(e))return!0;let n=`${e}.`;for(let e of t.names)if(e.startsWith(n))return!0;for(let n of t.documents)if(e.startsWith(`${n}.`))return!0;return!1}const av={gitTaculous:`gitaculous`};function ov(e,t){let n=new Map;for(let e of Object.keys(t)){let t=vs(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:G(e.source,[`presets`])})}function sv(e,t){t.globals.look!==void 0&&!fi(t.globals.look)&&!Object.prototype.hasOwnProperty.call(t.looks,t.globals.look)&&e.issues.push({path:`globals.look`,message:`globals.look "${t.globals.look}" does not match any declared look (have: ${Object.keys(t.looks).join(`, `)})`,line:G(e.source,[`globals`,`look`])}),t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:G(e.source,[`globals`,`preset`])}),ov(e,t.presets);let n=q_(t);for(let[r,i]of Object.entries(t.actions))!(`set`in i)||!(`from`in i)||typeof i.from!=`string`||J_(n).includes(i.from)||e.issues.push({path:`actions.${r}.from`,message:`actions.${r} from: references unknown option domain "${i.from}" (have: ${J_(n).join(`, `)})`,line:G(e.source,[`actions`,r,`from`])});for(let[n,r]of Object.entries(t.actions)){if(!Fg(r))continue;let i=r[Pg];fv(t,i)||e.issues.push({path:`actions.${n}.${Pg}`,message:`actions.${n} ${Pg}: "${i}" is not a declared state key — a dual action's selector must name a { kind: "state", key: "${i}" } variable, or the destination can never change`,line:G(e.source,[`actions`,n,Pg])})}for(let[n,r]of Object.entries(t.actions)){let i=`persist`in r?r.persist:`reset`in r?r.reset:null;if(i===null)continue;let a=`persist`in r?`persist`:`reset`,o=_h(i);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a config globals field (have: ${No().join(`, `)}), a "segments.<name>.palette" target, or a "presets.<name>.root" target`,line:G(e.source,[`actions`,n,a])});continue}let s=cv.filter(e=>e in r);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){lv(e,t,n,a,i,o.preset,r);continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})`,line:G(e.source,[`actions`,n,a])});continue}`min`in r&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:G(e.source,[`actions`,n,a])})}}let r=mv(t),i=jg(t),a=Object.entries(t.segments).filter(([,e])=>qm(e.template)).map(([e])=>e),o=(t,n,r)=>{Sg(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Kh}" ${Sg(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:r});let i=new Map;for(let e of wa(t))e.kind===`segment`&&i.set(e.name,(i.get(e.name)??0)+1);for(let t of a)(i.get(t)??0)>1&&e.issues.push({path:n,message:`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.`,line:r})},s=(n,a,o)=>{for(let s of wa(n))if(s.when!==void 0&&vv(e,`${a}.when`,s.when,r,{line:o}),s.kind===`segment`){if(yg(s.name)){i||e.issues.push({path:a,message:`${a} places the global settings menu anchor "${Kh}", but this config declares no "${Ag}" variable — the menu is a click surface and every click composes a URL from "${Ag}", so it is not synthesized for a config without it. Declare a "${Ag}" variable (any config merged onto the bundled default inherits one) or remove the anchor placement.`,line:o});continue}if(!Object.prototype.hasOwnProperty.call(t.segments,s.name)){let t=av[s.name],n=t===void 0?``:` (the built-in segment "${s.name}" was renamed to "${t}" — update this reference)`;e.issues.push({path:a,message:`${a} entry "${s.name}" does not match any declared segment${n}`,line:o})}}},c=yv(e.source);s(ho(t.root),c,G(e.source,[c]));for(let[n,r]of Object.entries(t.presets)){if(r.root===void 0)continue;let t=`presets.${n}.root`,i=G(e.source,[`presets`,n,`root`]);s(go(r.root),t,i)}let l=new Map([[`root`,ho(t.root)]]);for(let e of lh(t.presets)){let{node:n,path:r}=fh(t,e);l.set(r,n)}for(let[t,n]of l)o(n,t,G(e.source,t.split(`.`)));for(let[n,i]of Object.entries(t.variables))gv(e,`variables.${n}`,i,r);for(let[n,i]of Object.entries(t.segments)){if(i.vars)for(let[t,a]of Object.entries(i.vars))gv(e,`segments.${n}.vars.${t}`,a,r,n);for(let a of[`template`,`bg`,`fg`,`when`]){let o=i[a];if(typeof o==`string`){vv(e,`segments.${n}.${a}`,o,r,{segCtx:n});for(let r of tv(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}"`,line:G(e.source,[`segments`,n,a])});for(let r of rv(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}" (in a picker or menu)`,line:G(e.source,[`segments`,n,a])})}}}for(let[n,i]of Object.entries(t.variables))_v(e,`variables.${n}`,i,r);for(let[n,i]of Object.entries(t.segments))if(i.vars)for(let[t,a]of Object.entries(i.vars))_v(e,`segments.${n}.vars.${t}`,a,r,n);(dv(t)||pv(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:G(e.source,[`variables`])})}const cv=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function lv(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=G(e.source,[`actions`,n,r]);if(!lh(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${lh(t.presets).join(`, `)})`,line:c});return}if(r===`reset`)return;let l=`removeSegment`in o,u=`insertSegment`in o,d=`insertSegmentFrom`in o;if(!l&&!u&&!d){e.issues.push({path:s,message:`actions.${n}: "${i}" is a "presets.<name>.root" target and can only be paired with "removeSegment", "insertSegment", or "insertSegmentFrom" (not "to"/"from"/"cycle"/bounded — those have no meaning as a tree op)`,line:c});return}let f=e=>!Object.prototype.hasOwnProperty.call(t.segments,e);l&&`removeSegment`in o&&f(o.removeSegment)&&e.issues.push({path:s,message:`actions.${n}: removeSegment "${o.removeSegment}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c}),u&&`insertSegment`in o&&(f(o.insertSegment)&&e.issues.push({path:s,message:`actions.${n}: insertSegment "${o.insertSegment}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c}),f(o.anchor)&&e.issues.push({path:s,message:`actions.${n}: anchor "${o.anchor}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c})),d&&`insertSegmentFrom`in o&&f(o.anchor)&&e.issues.push({path:s,message:`actions.${n}: anchor "${o.anchor}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c})}function uv(e){return[...Object.values(e.variables),...Object.values(e.segments).flatMap(e=>Object.values(e.vars??{}))].filter(e=>e.kind===`state`)}function dv(e){return uv(e).length>0}function fv(e,t){return uv(e).some(e=>e.kind===`state`&&e.key===t)}function pv(e){return Object.values(e.actions).some(e=>Lg(e)||Rg(e)||zg(e)||Bg(e)||Vg(e)||Hg(e))}function mv(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),hv(r)&&n.add(e)};for(let[t,n]of Object.entries(e.variables))r(t,n);for(let[t,n]of Object.entries(e.segments))for(let[e,i]of Object.entries(n.vars??{}))r(`${t}.${e}`,i);return{names:t,documents:n}}function hv(e){return(e.kind===`shell`||e.kind===`file`)&&Ea(e.parse)===`json`}function gv(e,t,n,r,i){n.kind===`template`&&vv(e,`${t}.template`,n.template,r,{segCtx:i}),Oa(n)&&n.cache&&`key`in n.cache&&vv(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function _v(e,t,n,r,i){if(Oa(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.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:G(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function vv(e,t,n,r,i){for(let a of $_(n)){if(iv(a,r))continue;let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,o=n!==void 0&&iv(n,r)?` (segment-local vars are namespaced — write ".${n}")`:``;e.issues.push({path:t,message:`Template references unknown variable ".${a}"${o}`,line:i?.line??G(e.source,t.split(`.`))})}}function yv(e){try{let t=Ze.default.parse(e);if(Ra(t)&&`root`in t)return`root`}catch{}return`layout`}function bv(e,t){let{graph:n,nodeInfo:r}=xv(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:G(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function xv(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 $_(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),Oa(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 Sv=[`json5`,`json`];function Cv(e){try{return r.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function wv(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?f.homedir()+e.slice(1):e}function Tv(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?Sv.map(t=>c.join(e,`.cc-candybar.${t}`)):[],...Sv.map(e=>c.join(r,`.cc-candybar.${e}`)),...Sv.map(e=>`${Ev()}.${e}`)])]}function Ev(){let e=process.env.XDG_CONFIG_HOME??c.join(f.homedir(),`.config`);return c.join(e,`cc-candybar`,`config`)}function Dv(e,t,n){let r=[];for(let i of Tv(e,t,n)){let e=Cv(i);if(e===`present`)return{kind:`file`,path:i,unchecked:r};e!==`absent`&&r.push(e)}if(n===void 0)return{kind:`default`,unchecked:r};let[i]=r;return i===void 0?{kind:`missing`,path:n}:{kind:`unreadable`,...i}}function Ov(e,t,n){let r=Dv(e,t,n);return r.kind===`default`?`${Ev()}.${Sv[0]}`:r.path}function kv(e){return Av(e).join(`
|
|
118
|
+
`,Eh=`preset.customized`,Dh=`{{ and ${vc($m)} .${Eh} }}`,Oh=ws;function kh(e){return`${xs}addable.${e}`}function Ah(e){let t=Object.keys(e.segments).filter(e=>!Oh(e)),n=new Map;for(let r of lh(e.presets)){let{node:i}=fh(e,r),a=oh(i);n.set(kh(r),{members:t.filter(e=>!a.has(e))})}return n}function jh(e,t,n,r){let i=`${xs}${e}.remove.${vs(n)}`,a=`${xs}${e}.removeSeg.${vs(n)}`;return r.actions[i]={persist:t,removeSegment:n},r.segments[a]={template:`{{ action "${i}" "-" }}`,when:eh},{kind:`segment`,name:a}}function Mh(e,t,n,r,i,a,o){let s=`${xs}${e}.insert.${n}`,c=`${xs}${e}.insertSeg.${n}`;o.actions[s]={persist:t,insertSegmentFrom:r,anchor:i,relation:a};let l=jm(s),u=Mm(c,s,void 0),d=Fm(u),f=Pm(u,l);return o.variables[u]=bc(u,fc),o.variables[d]={kind:`state`,key:d,default:`0`},o.actions[f]=xc(u,l),o.actions[d]={set:d,int:!0},o.segments[c]={template:`{{ menu "${s}" "+" "✕" }}`,when:eh},{kind:`segment`,name:c}}function Nh(e,t,n,r,i,a){let o=[],s=e.children.reduce((e,t,n)=>t.kind===`segment`&&!Oh(t.name)?n:e,-1),c=e=>Nh(e,t,n,r,i,a);for(let[l,u]of e.children.entries()){if(u.kind===`container`){o.push(c(u));continue}let d=Ca(u,c);if(Oh(u.name)){o.push(d);continue}let f=[Mh(t,n,String(a.n++),r,u.name,`before`,i),d,jh(t,n,u.name,i),...l===s?[Mh(t,n,String(a.n++),r,u.name,`after`,i)]:[]];o.push(...e.direction===`vertical`?[{kind:`container`,direction:`horizontal`,children:f,...u.when!==void 0&&{when:u.when}}]:f)}return{...e,children:o}}function Ph(e,t,n,r,i,a){let o=`${xs}${n}.resetLayout`,s=`${xs}${n}.customized`;i.actions[o]={reset:r},i.ensured[Eh]={kind:`input`,path:Eh,type:`boolean`,default:!1};let c=hc(t);return i.segments[s]={template:`{{ action "${o}" "↺ ${c} customized" }}`,when:Dh},{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:s},Fh(e,a)],...e.when!==void 0&&{when:e.when}}}function Fh(e,t){if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t]};let n=e.children.at(-1);return e.direction===`vertical`&&n!==void 0&&(n.kind===`segment`||n.when===void 0)?{...e,children:[...e.children.slice(0,-1),Fh(n,t)]}:{...e,children:[...e.children,t]}}function Ih(e,t,n,r){let{node:i}=fh(e,t),a=gh(t),o=kh(t),s=vs(t);return Ph(Nh(i,s,a,o,n,{n:0}),t,s,a,n,r)}function Lh(e){if(!(`edit.toggle`in e.actions))return e;let t={variables:{},ensured:{},actions:{},segments:{}},n=bh(`${xs}help`,Ch,[$m],t),r={...e.presets};for(let i of lh(e.presets)){let a=Ih(e,i,t,n);r[i]={...dh(e.presets,i),root:a}}return{...e,variables:{...t.ensured,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:r}}const Rh={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function zh(e){let t=e[Rh.socket]??``,n=e[Rh.pane]??``;if(t===``||n===``)return null;let r=e[Rh.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const Bh=Rh.truecolor,Vh=[{name:`tmuxTruecolor`,label:`tmux truecolor`,probe:({tmux:e,claudeSettingsEnv:t})=>{switch(e.kind){case`unreported`:return{ok:!1,reason:"the client reported no tmux facts — re-run `cc-candybar install` to stage a current client"};case`outside`:return{ok:!0};case`inside`:{if(e.termfeatures.kind===`failed`)return{ok:!1,reason:`tmux could not be asked: ${e.termfeatures.reason}`};if(!e.termfeatures.value.includes(`RGB`)||e.hint.truecolor!==null)return{ok:!0};let n=t[Bh];return typeof n==`string`&&n!==``?{ok:!1,reason:`${Bh} is set in ~/.claude/settings.json — restart Claude Code to apply`}:{ok:!1,reason:`Claude Code renders the bar in 256 colours inside tmux`,fix:{kind:`claude-settings-env`,name:Bh,value:`1`}}}}}}];function Hh(e){return Vh.map(t=>({check:t,verdict:t.probe(e)}))}function Uh(e){return Vh.find(t=>t.name===e)}function Wh(e){let t=`settings.doctor.${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`}}function Gh(e){return e.flatMap(({check:e,verdict:t})=>{let n=Wh(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:``},{key:n.fixable,value:Ti}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:t.reason},{key:n.fixable,value:t.fix===void 0?Ti:wi}]})}const Kh=`${Ss}menu`,qh=Qm,Jh=`${Ss}edit`,Yh=`${Ss}persist`,Xh=`${Ss}config`,Zh=Yh,Qh={variable:Kh,key:Kh,member:qh},$h={variable:Xh,key:Xh,member:qh},eg=`${Ss}tools`,tg={variable:eg,key:eg,member:qh},ng=`${Ss}doctor`,rg=`${ng}.run`,ig=e=>`${ng}.fix.${e}`,ag=e=>`${ng}.${e}`,og=`${Ss}help.persist`,sg={bg:`{{ color "accent" }}`,fg:`{{ contrastOn (bgOf) }}`},cg=`${Ss}pickers`,lg=[{name:`preset`,sessionKey:`preset`,configKey:`preset`,effectiveVar:`preset.effective`,glyph:`▦`,domain:`presets`}],ug=[{name:`theme`,sessionKey:`theme`,configKey:`palette`,effectiveVar:`theme.effective`,glyph:`🎨`,domain:`themes`},{name:`look`,sessionKey:`look`,configKey:`look`,effectiveVar:`look.effective`,glyph:`◐`,domain:`looks`},{name:`style`,sessionKey:`style`,configKey:`style`,effectiveVar:`style.effective`,glyph:`✦`,domain:`styles`}],dg={name:`wrap`,sessionKey:`autoWrap`,configKey:`autoWrap`},fg={name:`padding`,sessionKey:`padding`,configKey:`padding`},pg=`${Ss}${dg.name}`,mg=`${Ss}${fg.name}`,hg=[...lg,...ug];new Set([...hg,dg,fg].flatMap(e=>[e.sessionKey,e.configKey]));const gg=e=>`${Ss}${e}`,_g=e=>`${Ss}apply.${e}`,vg=e=>`${Ss}reset.${e}`;function yg(e){return e===Kh}function bg(e){let t={kind:`segment`,name:Kh};if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[t,e],...e.when!==void 0&&{when:e.when}};let[n,...r]=e.children;return e.direction===`vertical`&&n!==void 0&&n.when===void 0?{...e,children:[bg(n),...r]}:{...e,children:[t,...e.children]}}function xg(e){return Sg(e)>0?e:bg(e)}function Sg(e){let t=0;for(let n of wa(e))n.kind===`segment`&&yg(n.name)&&(t+=1);return t}function Cg(e,t){return e.kind===`segment`?yg(e.name)?gc(e.name,Qh,{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:Yh},t,...lg.map(e=>({kind:`segment`,name:gg(e.name)})),gc(Xh,$h,{kind:`container`,direction:`horizontal`,children:[...ug.map(e=>({kind:`segment`,name:gg(e.name)})),{kind:`segment`,name:pg},{kind:`segment`,name:mg}]}),gc(eg,tg,{kind:`container`,direction:`vertical`,children:[{kind:`segment`,name:ng},...Vh.map(e=>({kind:`segment`,name:ag(e.name)}))]}),{kind:`segment`,name:Jh}]},e.when):Ca(e,e=>wg(e,t)):wg(e,t)}function wg(e,t){return{...e,children:e.children.map(e=>Cg(e,t))}}function Tg(e,t,n,r){let i=jm(t),a=Mm(e,t,r),o=Fm(a);n.variables[a]=bc(a,fc),n.variables[o]={kind:`state`,key:o,default:`0`},n.actions[Pm(a,i)]=xc(a,i),n.actions[o]={set:o,int:!0}}function Eg(){let e={variables:{[Kh]:bc(Kh,fc)},actions:{[Kh]:xc(Kh,qh),[Xh]:xc(Xh,qh),[eg]:xc(eg,qh),[rg]:{doctor:`run`},[Yh]:{set:Zh,cycle:[Ti,wi]}},segments:{[Kh]:{template:yc(Kh,`☰`,`✕`),...sg},[Yh]:{template:`{{ action "${Yh}" "☐ persist?" "☑ persist?" }}`},[Xh]:{template:yc(Xh,`⚙ config ▸`,`⚙ config ▾`)},[eg]:{template:yc(eg,`🧰 tools ▸`,`🧰 tools ▾`)},[ng]:{template:`{{ action "${rg}" "🩺 doctor" }}`},[pg]:{template:`{{ action "${_g(`wrap`)}" "wrap: on" "wrap: off" }} {{ action "${vg(`wrap`)}" "↺" }}`},[mg]:{template:`{{ action "${_g(`padding`)}.down" "◀" }} padding {{ .padding.effective }} {{ action "${_g(`padding`)}.up" "▶" }} {{ action "${vg(`padding`)}" "↺" }}`},[Jh]:{template:`{{ action "${Zm}" "✎ edit" "✎ done" }}`}}};return e.variables[Zh]={kind:`state`,key:Zh,default:Ti},e.variables[Xh]=bc(Xh,fc),e.variables[eg]=bc(eg,fc),Og(e),Dg(e),{artifacts:e,help:bh(og,wh,[Qh],e)}}function Dg(e){for(let t of Vh){let n=Wh(t.name),r=ig(t.name);for(let t of Object.values(n))e.variables[t]={kind:`state`,key:t,default:``};e.actions[r]={doctor:`fix`,check:t.name},e.segments[ag(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${wi}" }} {{ action "${r}" "[fix]" }}{{ end }}{{ end }}`}}}function Og(e){for(let t of hg){let n=gg(t.name),r=_g(t.name);e.segments[n]={template:`${t.glyph} {{ .${t.effectiveVar} }} {{ menu "${r}" "▸" "▾" (dict "key" "${cg}" "closeOnPick" true) }} {{ action "${vg(t.name)}" "↺" }}`},e.actions[r]={set:t.sessionKey,persist:t.configKey,persistWhen:Zh,from:t.domain},e.actions[vg(t.name)]={reset:t.configKey},Tg(n,r,e,cg)}e.actions[_g(dg.name)]={set:dg.sessionKey,persist:dg.configKey,persistWhen:Zh,cycle:[...Ei]},e.actions[vg(dg.name)]={reset:dg.configKey};for(let t of[-1,1])e.actions[`${_g(fg.name)}.${t<0?`down`:`up`}`]={set:fg.sessionKey,persist:fg.configKey,persistWhen:Zh,...Di,by:t};e.actions[vg(fg.name)]={reset:fg.configKey}}function kg(e){e.variables[Xm]=bc(Xm,fc),e.actions[Zm]=xc(Xm,Qm)}const Ag=`session.id`;function jg(e){return Object.prototype.hasOwnProperty.call(e.variables,Ag)}function Mg(e){if(!jg(e))return e;let{artifacts:t,help:n}=Eg();kg(t);let r={...e.presets};for(let t of lh(e.presets)){let{node:i}=fh(e,t);r[t]={...dh(e.presets,t),root:Cg(xg(i),n)}}return{...e,variables:{...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:r}}const Ng=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`doctor`],Pg=`persistWhen`;function Fg(e){return Pg in e}function Ig(e){return Fg(e)?`to`in e?[{set:e.set,to:e.to},{persist:e.persist,to:e.to}]:`from`in e?[{set:e.set,from:e.from},{persist:e.persist,from:e.from}]:`cycle`in e?[{set:e.set,cycle:e.cycle},{persist:e.persist,cycle:e.cycle}]:[{set:e.set,min:e.min,max:e.max,by:e.by},{persist:e.persist,min:e.min,max:e.max,by:e.by}]:[e]}function Lg(e){return`set`in e}function Rg(e){return`persist`in e}function zg(e){return`reset`in e}function Bg(e){return`undo`in e}function Vg(e){return`redo`in e}function Hg(e){return`doctor`in e}function Ug(e,t){if(t===void 0)return{};if(!Ra(t))return J(e,`actions`,`actions must be an object, got ${za(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=Wg(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function J(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function Wg(e,t,n){if(!Ra(n))return J(e,t,`${t} must be an action object, got ${za(n)}`),null;if(`persistWhen`in n)return S_(e,t,n,`dual`,y_);let r=Ng.filter(e=>e in n);return r.length===1?Gg[r[0]](e,t,n):(J(e,t,`action must declare exactly one of: ${Ng.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const Gg={set:(e,t,n)=>S_(e,t,n,`set`,__),persist:(e,t,n)=>S_(e,t,n,`persist`,v_),copy:Kg(`copy`),open:Kg(`open`),reset:qg,undo:Jg(`undo`),redo:Jg(`redo`),doctor:Yg};function Kg(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&J(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Na(t,n,r,e);return i===null?null:{[e]:i}}}function qg(e,t,n){for(let r of Object.keys(n))r!==`reset`&&J(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=Xg(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}function Jg(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&J(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(J(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — it steps the history of the session's config file), got ${Ba(r[e])}`),null)}}function Yg(e,t,n){let r=n.doctor,i=r===`run`?[`doctor`]:[`doctor`,`check`];for(let r of Object.keys(n))i.includes(r)||J(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${i.join(`, `)}`);if(r!==`run`&&r!==`fix`)return J(e,`${t}.doctor`,`doctor must be "run" or "fix", got ${Ba(r)}`),null;if(r===`run`)return{doctor:`run`};let a=n.check;return typeof a!=`string`||Uh(a)===void 0?(J(e,`${t}.check`,`doctor fix must name a check (have: ${Vh.map(e=>e.name).join(`, `)}), got ${Ba(a)}`),null):{doctor:`fix`,check:a}}function Xg(e,t,n,r,i,a){let o=Na(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(J(e,s,i),null):o.includes(`/`)?(J(e,s,a(o)),null):o}const Zg={set:[[`set`,`the SessionState key to write`]],persist:[[`persist`,`the config globals field to write`]],dual:[[`set`,`the SessionState key written while persistWhen is off`],[`persist`,`the config globals field written while persistWhen is on`],[Pg,`the SessionState key whose boolean value chooses the destination`]]};function Qg(e,t,n,r){let i={},a=Zg[r],o=!0;for(let[r,s]of a){if(!(r in n)){J(e,t,`${r} is required here (${s}) — a dual-destination action declares ${a.map(([e])=>e).join(`, `)} together, plus one value source`),o=!1;continue}let c=Xg(e,t,r,n,`${r} key must be non-empty (${s})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);if(c===null){o=!1;continue}i[r]=c}return o?i:null}function $g(e){return e===`set`?`set-state`:e===`persist`?`set-config`:`set-state/set-config`}const e_={to:C_(`set`)},t_={to:C_(`persist`)},n_={from:w_(`set`)},r_={from:w_(`persist`)},i_={min:k_(),max:k_(),by:k_()},a_={int:E_()},o_={cycle:T_(`set`)},s_={to:C_(`dual`)},c_={from:w_(`dual`)},l_={cycle:T_(`dual`)},u_={cycle:T_(`persist`)},d_={removeSegment:D_(`removeSegment`)},f_={insertSegment:D_(`insertSegment`),anchor:D_(`anchor`),relation:O_()},p_={insertSegmentFrom:w_(`persist`),anchor:D_(`anchor`),relation:O_()},m_={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},h_={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function g_(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=Zg[e].map(([e])=>e),s=(e,n,r)=>Ha(e,t,n,r),c=ro(t);return{detect:a,allowed:[...o,...i],label:i.join(`/`),json:{type:`object`,properties:{...Object.fromEntries(o.map(e=>[e,{type:`string`}])),...c.properties},required:[...o,...c.required??[]],additionalProperties:!1},parse:n.length?Xa(s,...n):s}}const __=[g_(`set`,e_),g_(`set`,n_),g_(`set`,i_,[m_,h_]),g_(`set`,a_),g_(`set`,o_)],v_=[g_(`persist`,t_),g_(`persist`,r_),g_(`persist`,i_,[m_,h_]),g_(`persist`,u_),g_(`persist`,d_),g_(`persist`,f_,[],[`insertSegment`]),g_(`persist`,p_,[],[`insertSegmentFrom`])],y_=[g_(`dual`,s_),g_(`dual`,c_),g_(`dual`,i_,[m_,h_]),g_(`dual`,l_)];function b_(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"styles"/"looks", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function x_(e){let t=b_(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function S_(e,t,n,r,i){let a=Qg(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return J(e,t,`${x_(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||J(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function C_(e){let t=$g(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>Xg(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function w_(e){let t=$g(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){J(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){J(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){J(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){J(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){J(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}J(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${Ba(o)}`)}}}function T_(e){let t=$g(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){J(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${za(o)}`);return}let c=o;if(c.length<2){J(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){J(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){J(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){J(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function E_(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){J(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${Ba(r[n])}`);return}return!0}}}function D_(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Na(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){J(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){J(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function O_(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){J(e,`${t}.${n}`,`relation must be "before" or "after", got ${Ba(i)}`);return}return i}}}function k_(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){J(e,`${t}.${n}`,`${n} must be an integer, got ${Ba(i)}`);return}return i}}}const A_={noun:`look key`,fields:{hueShift:$a(),chromaScale:$a({min:0}),lightnessScale:$a(),lightnessShift:$a()}};function j_(e,t){if(!Ra(t))return e.issues.push({path:`looks`,message:`looks must be an object mapping look names to adaptation objects, got ${za(t)}`,line:G(e.source,[`looks`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`looks.${r}`,message:`look name ${JSON.stringify(r)} must be non-empty and slash-free — a look picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:G(e.source,[`looks`,r])});continue}let t=Va(e,A_,`looks.${r}`,i);t!==null&&(n[r]={...gn,...t})}return n}const M_={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:Rc(e,`${t}.${n}`,r[n])},globals:{required:!1,json:ko(),parse:(e,t,n,r)=>r[n]===void 0?void 0:Oo(e,`${t}.${n}`,r[n])}}};function N_(e,t){if(!Ra(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${za(t)}`,line:G(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:G(e.source,[`presets`,r])});continue}let t=Va(e,M_,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function P_(e,t){if(t===void 0)return{};if(!Ra(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${za(t)}`,line:G(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${Ba(i)}`,line:G(e.source,[`helpers`,r])});continue}n[r]=i}return n}const F_=new Map,I_=new Map;function L_(e){let t=R_(e);if(t===null)throw Error(`Palette "${e}" (resolved "${ai(e)}") did not resolve in the theme registry — allowed names and the registry are inconsistent`);return t}function R_(e){let t=ai(e),n=F_.get(t);if(n!==void 0)return n;let r=Kn(t);return r===null?null:(F_.set(t,r),r)}function z_(e,t){let n=`${e.name} ${t.hueShift} ${t.chromaScale} ${t.lightnessScale} ${t.lightnessShift}`,r=I_.get(n);if(r!==void 0)return r;let i=tr(e,t);return I_.set(n,i),i}function B_(e){let t=R_(e);return t===null?null:{kind:`decided`,name:e,value:t}}function V_(e,t){let n=B_(e);return n===null?(t(`globals.palette rendered "${oi}": "${e}" names no installed theme`),U_()):n}function H_(e,t,n){return pi(e,t,n,U_(),B_)}function U_(){return B_(oi)}function W_(e){return mi(H_(void 0,null,e),()=>oi,U_).value}const G_=new Map;function K_(e,t,n){G_.set(e,{permanent:!0,resolve:t,paletteOf:n})}K_(`themes`,()=>li(),e=>L_(e)),K_(`styles`,()=>yi),K_(`charsets`,()=>Si),K_(`colorCompatibilities`,()=>Ci);function q_(e){return new Map([[`looks`,{members:Object.keys(e.looks),paletteOf:(t,n)=>z_(n,e.looks[t])}],[`presets`,{members:lh(e.presets)}]])}function J_(e){return[...new Set([...G_.keys(),...e.keys()])]}function Y_(e,t){if(typeof e!=`string`)return{members:e};let n=t.get(e);if(n)return n;let r=G_.get(e);if(r)return{members:r.resolve(),paletteOf:r.paletteOf};throw Error(`unknown option domain "${e}" (have: ${J_(t).join(`, `)})`)}const X_=/{{([\s\S]*?)}}/g,Z_=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`[^`]*`/g,Q_=/(?<![A-Za-z0-9_)])\.([A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*)/g;function $_(e){let t=new Set,n;for(X_.lastIndex=0;(n=X_.exec(e))!==null;){let e=n[1].replace(Z_,``),r;for(Q_.lastIndex=0;(r=Q_.exec(e))!==null;)t.add(r[1])}return t}const ev=/\baction\s+$/;function tv(e){let t=new Set;X_.lastIndex=0;let n;for(;(n=X_.exec(e))!==null;){let e=n[1],r=0,i;for(Z_.lastIndex=0;(i=Z_.exec(e))!==null;)ev.test(e.slice(r,i.index))&&t.add(i[0].slice(1,-1)),r=i.index+i[0].length}return t}const nv=/\b(picker|menu)\s+$/;function rv(e){let t=new Set;X_.lastIndex=0;let n;for(;(n=X_.exec(e))!==null;){let e=n[1],r=0,i=0,a;for(Z_.lastIndex=0;(a=Z_.exec(e))!==null;){let n=nv.exec(e.slice(r,a.index));n!==null&&(i=n[1]===`picker`?2:1),i>0&&(t.add(a[0].slice(1,-1)),i--),r=a.index+a[0].length}}return t}function iv(e,t){if(t.names.has(e))return!0;let n=`${e}.`;for(let e of t.names)if(e.startsWith(n))return!0;for(let n of t.documents)if(e.startsWith(`${n}.`))return!0;return!1}const av={gitTaculous:`gitaculous`};function ov(e,t){let n=new Map;for(let e of Object.keys(t)){let t=vs(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:G(e.source,[`presets`])})}function sv(e,t){t.globals.look!==void 0&&!fi(t.globals.look)&&!Object.prototype.hasOwnProperty.call(t.looks,t.globals.look)&&e.issues.push({path:`globals.look`,message:`globals.look "${t.globals.look}" does not match any declared look (have: ${Object.keys(t.looks).join(`, `)})`,line:G(e.source,[`globals`,`look`])}),t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:G(e.source,[`globals`,`preset`])}),ov(e,t.presets);let n=q_(t);for(let[r,i]of Object.entries(t.actions))!(`set`in i)||!(`from`in i)||typeof i.from!=`string`||J_(n).includes(i.from)||e.issues.push({path:`actions.${r}.from`,message:`actions.${r} from: references unknown option domain "${i.from}" (have: ${J_(n).join(`, `)})`,line:G(e.source,[`actions`,r,`from`])});for(let[n,r]of Object.entries(t.actions)){if(!Fg(r))continue;let i=r[Pg];fv(t,i)||e.issues.push({path:`actions.${n}.${Pg}`,message:`actions.${n} ${Pg}: "${i}" is not a declared state key — a dual action's selector must name a { kind: "state", key: "${i}" } variable, or the destination can never change`,line:G(e.source,[`actions`,n,Pg])})}for(let[n,r]of Object.entries(t.actions)){let i=`persist`in r?r.persist:`reset`in r?r.reset:null;if(i===null)continue;let a=`persist`in r?`persist`:`reset`,o=_h(i);if(o===null){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a config globals field (have: ${No().join(`, `)}), a "segments.<name>.palette" target, or a "presets.<name>.root" target`,line:G(e.source,[`actions`,n,a])});continue}let s=cv.filter(e=>e in r);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){lv(e,t,n,a,i,o.preset,r);continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})`,line:G(e.source,[`actions`,n,a])});continue}`min`in r&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${i}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:G(e.source,[`actions`,n,a])})}}let r=mv(t),i=jg(t),a=Object.entries(t.segments).filter(([,e])=>qm(e.template)).map(([e])=>e),o=(t,n,r)=>{Sg(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Kh}" ${Sg(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:r});let i=new Map;for(let e of wa(t))e.kind===`segment`&&i.set(e.name,(i.get(e.name)??0)+1);for(let t of a)(i.get(t)??0)>1&&e.issues.push({path:n,message:`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.`,line:r})},s=(n,a,o)=>{for(let s of wa(n))if(s.when!==void 0&&vv(e,`${a}.when`,s.when,r,{line:o}),s.kind===`segment`){if(yg(s.name)){i||e.issues.push({path:a,message:`${a} places the global settings menu anchor "${Kh}", but this config declares no "${Ag}" variable — the menu is a click surface and every click composes a URL from "${Ag}", so it is not synthesized for a config without it. Declare a "${Ag}" variable (any config merged onto the bundled default inherits one) or remove the anchor placement.`,line:o});continue}if(!Object.prototype.hasOwnProperty.call(t.segments,s.name)){let t=av[s.name],n=t===void 0?``:` (the built-in segment "${s.name}" was renamed to "${t}" — update this reference)`;e.issues.push({path:a,message:`${a} entry "${s.name}" does not match any declared segment${n}`,line:o})}}},c=yv(e.source);s(ho(t.root),c,G(e.source,[c]));for(let[n,r]of Object.entries(t.presets)){if(r.root===void 0)continue;let t=`presets.${n}.root`,i=G(e.source,[`presets`,n,`root`]);s(go(r.root),t,i)}let l=new Map([[`root`,ho(t.root)]]);for(let e of lh(t.presets)){let{node:n,path:r}=fh(t,e);l.set(r,n)}for(let[t,n]of l)o(n,t,G(e.source,t.split(`.`)));for(let[n,i]of Object.entries(t.variables))gv(e,`variables.${n}`,i,r);for(let[n,i]of Object.entries(t.segments)){if(i.vars)for(let[t,a]of Object.entries(i.vars))gv(e,`segments.${n}.vars.${t}`,a,r,n);for(let a of[`template`,`bg`,`fg`,`when`]){let o=i[a];if(typeof o==`string`){vv(e,`segments.${n}.${a}`,o,r,{segCtx:n});for(let r of tv(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}"`,line:G(e.source,[`segments`,n,a])});for(let r of rv(o))Object.prototype.hasOwnProperty.call(t.actions,r)||e.issues.push({path:`segments.${n}.${a}`,message:`${a} references unknown action "${r}" (in a picker or menu)`,line:G(e.source,[`segments`,n,a])})}}}for(let[n,i]of Object.entries(t.variables))_v(e,`variables.${n}`,i,r);for(let[n,i]of Object.entries(t.segments))if(i.vars)for(let[t,a]of Object.entries(i.vars))_v(e,`segments.${n}.vars.${t}`,a,r,n);(dv(t)||pv(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:G(e.source,[`variables`])})}const cv=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function lv(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=G(e.source,[`actions`,n,r]);if(!lh(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${lh(t.presets).join(`, `)})`,line:c});return}if(r===`reset`)return;let l=`removeSegment`in o,u=`insertSegment`in o,d=`insertSegmentFrom`in o;if(!l&&!u&&!d){e.issues.push({path:s,message:`actions.${n}: "${i}" is a "presets.<name>.root" target and can only be paired with "removeSegment", "insertSegment", or "insertSegmentFrom" (not "to"/"from"/"cycle"/bounded — those have no meaning as a tree op)`,line:c});return}let f=e=>!Object.prototype.hasOwnProperty.call(t.segments,e);l&&`removeSegment`in o&&f(o.removeSegment)&&e.issues.push({path:s,message:`actions.${n}: removeSegment "${o.removeSegment}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c}),u&&`insertSegment`in o&&(f(o.insertSegment)&&e.issues.push({path:s,message:`actions.${n}: insertSegment "${o.insertSegment}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c}),f(o.anchor)&&e.issues.push({path:s,message:`actions.${n}: anchor "${o.anchor}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c})),d&&`insertSegmentFrom`in o&&f(o.anchor)&&e.issues.push({path:s,message:`actions.${n}: anchor "${o.anchor}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})`,line:c})}function uv(e){return[...Object.values(e.variables),...Object.values(e.segments).flatMap(e=>Object.values(e.vars??{}))].filter(e=>e.kind===`state`)}function dv(e){return uv(e).length>0}function fv(e,t){return uv(e).some(e=>e.kind===`state`&&e.key===t)}function pv(e){return Object.values(e.actions).some(e=>Lg(e)||Rg(e)||zg(e)||Bg(e)||Vg(e)||Hg(e))}function mv(e){let t=new Set,n=new Set,r=(e,r)=>{t.add(e),hv(r)&&n.add(e)};for(let[t,n]of Object.entries(e.variables))r(t,n);for(let[t,n]of Object.entries(e.segments))for(let[e,i]of Object.entries(n.vars??{}))r(`${t}.${e}`,i);return{names:t,documents:n}}function hv(e){return(e.kind===`shell`||e.kind===`file`)&&Ea(e.parse)===`json`}function gv(e,t,n,r,i){n.kind===`template`&&vv(e,`${t}.template`,n.template,r,{segCtx:i}),Oa(n)&&n.cache&&`key`in n.cache&&vv(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function _v(e,t,n,r,i){if(Oa(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.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:G(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function vv(e,t,n,r,i){for(let a of $_(n)){if(iv(a,r))continue;let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,o=n!==void 0&&iv(n,r)?` (segment-local vars are namespaced — write ".${n}")`:``;e.issues.push({path:t,message:`Template references unknown variable ".${a}"${o}`,line:i?.line??G(e.source,t.split(`.`))})}}function yv(e){try{let t=Ze.default.parse(e);if(Ra(t)&&`root`in t)return`root`}catch{}return`layout`}function bv(e,t){let{graph:n,nodeInfo:r}=xv(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:G(e.source,o?.linePathParts??[`variables`,i])}),!0}if(t===0&&o(s))return!0}return i.set(t,2),a.pop(),!1}}function xv(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 $_(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),Oa(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 Sv=[`json5`,`json`];function Cv(e){try{return r.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}function wv(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?f.homedir()+e.slice(1):e}function Tv(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?Sv.map(t=>c.join(e,`.cc-candybar.${t}`)):[],...Sv.map(e=>c.join(r,`.cc-candybar.${e}`)),...Sv.map(e=>`${Ev()}.${e}`)])]}function Ev(){let e=process.env.XDG_CONFIG_HOME??c.join(f.homedir(),`.config`);return c.join(e,`cc-candybar`,`config`)}function Dv(e,t,n){let r=[];for(let i of Tv(e,t,n)){let e=Cv(i);if(e===`present`)return{kind:`file`,path:i,unchecked:r};e!==`absent`&&r.push(e)}if(n===void 0)return{kind:`default`,unchecked:r};let[i]=r;return i===void 0?{kind:`missing`,path:n}:{kind:`unreadable`,...i}}function Ov(e,t,n){let r=Dv(e,t,n);return r.kind===`default`?`${Ev()}.${Sv[0]}`:r.path}function kv(e){return Av(e).join(`
|
|
119
119
|
`)||null}function Av(e){switch(e.kind){case`file`:case`default`:return e.unchecked.map(e=>`Config location could not be checked: ${e.path} — ${e.error}`);case`missing`:return[`Config file not found: ${e.path} — rendering the bundled default until it appears`];case`unreadable`:return[`Config file could not be read: ${e.path} — ${e.error} — rendering the bundled default until it can be`]}}function jv(e,t){let n=Tv(e,t).filter(e=>Cv(e)===`present`),r=new Map;for(let e of n){let t=c.dirname(e),n=c.basename(e).replace(/\.(json5|json)$/,``),i=c.join(t,n);r.has(i)||r.set(i,[]),r.get(i).push(e)}let i=[...r.values()].filter(e=>e.length>1);return i.length===0?null:`config-extension collision: ${i.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function Mv(e,t,n){let r=e===null?Nv:Pv(e,t,n);return{...r,config:yo(r.raw,t)}}const Nv={raw:{},source:``,warnings:[]};function Pv(e,t,n){let i=r.readFileSync(e,`utf-8`);return{source:i,...Lv(e,i,n,Ds(t))}}function Fv(e,t=`<config>`,n=``,r=new Set(li())){let i=[],a={source:n,issues:i,allowedPalettes:r,groups:[]};if(sv(a,e),bv(a,e),i.length>0)throw new _a(t,i);return Lh(Mg(e))}function Iv(e,t,n=new Set(li()),r=Rv){return Lv(e,t,n,r).raw}function Lv(e,t,n,r){let i=zv(e,t),a=ba(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(li()),groups:[]};if(!Ra(i))throw new _a(e,[{path:``,message:`Config root must be an object, got ${za(i)}`}],o);let l=Bv(c,i,r);if(s.length>0)throw new _a(e,s,o);return{raw:l,warnings:o}}const Rv=new Set;function zv(e,t){try{return Ze.default.parse(t)}catch(t){let n=t;throw new _a(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function Bv(e,t,n){for(let n of Object.keys(t))Vv.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...Vv].join(`, `)}`,line:G(e.source,[n])});let r={};return t.globals!==void 0&&(r.globals=Do(e,`globals`,t.globals)),t.variables!==void 0&&(r.variables=qo(e,`variables`,t.variables)),t.segments!==void 0&&(r.segments=Os(e,t.segments,n)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
|
|
120
120
|
Replace: layout: [["seg1", "seg2"], ["seg3"]]
|
|
121
121
|
With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
|
|
122
122
|
Single-row example: root: { h: ["seg1", "seg2"] }`,line:G(e.source,[`layout`])}),t.root!==void 0&&(r.root=Rc(e,`root`,t.root)),t.actions!==void 0&&(r.actions=Ug(e,t.actions)),t.looks!==void 0&&(r.looks=j_(e,t.looks)),t.presets!==void 0&&(r.presets=N_(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=Ao(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=P_(e,t.helpers)),Kc(e,r),Ym(e,r),rh(e,r),Es(e,r,Ss,`the global settings menu`),r}const Vv=new Set([`globals`,`variables`,`segments`,`layout`,`root`,`actions`,`looks`,`presets`,`editGlobals`,`helpers`]);function Hv(e){let t=Kv(e.termCols),n=Kv(e.termRows),r=qv(e.ssh),i=Wv(e.tmux),a=Uv(e.configEnv);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a}}}function Uv(e){return typeof e==`string`&&e!==``?wv(e):void 0}function Wv(e){if(e===null)return null;if(typeof e!=`object`)return;let{socket:t,pane:n,truecolor:r}=e;if(!(typeof t!=`string`||t===``)&&!(typeof n!=`string`||n===``)&&!(r!==null&&(typeof r!=`string`||r===``)))return{socket:t,pane:n,truecolor:r}}const Gv=1e4;function Kv(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>Gv?Gv:t}function qv(e){return typeof e==`boolean`?e:void 0}var Jv=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Yv(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function Xv(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 Jv(`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 Jv(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function Zv(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=Xv(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(Yv(t))})}async function Qv(e,t,n){let r=null;try{r=await ry(Pe(),t.connectMs);let i=await Zv(r,{v:3,...e},t.budgetMs);return ty(e.kind,i,n)}catch(e){return ny(e)}finally{r&&r.destroy()}}function $v(e,t){return typeof e==`string`?e:t}function ey(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function ty(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=$v(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:ey(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 ny(e){if(e instanceof Jv||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 ry(e,t){return new Promise((n,r)=>{let i=g.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 iy(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 ay={connectMs:50,budgetMs:150},oy={connectMs:50,budgetMs:200};function sy(e){let t=e.output;return typeof t==`string`?t:void 0}function cy(e,t,n,r){return Qv({kind:`render`,hookData:e,args:t,cwd:n,...r},ay,sy)}function ly(e,t){return Qv({kind:`click`,verb:e,value:t},oy,sy)}let uy=null;function dy(e){if(uy!==null)return uy;r.mkdirSync(c.dirname(e),{recursive:!0});try{uy=r.statSync(e).size}catch{uy=0}return uy}function fy(e){for(let t=2;t>=1;t--){let n=`${e}.${t}`,i=`${e}.${t+1}`;try{r.renameSync(n,i)}catch{}}try{r.renameSync(e,`${e}.1`)}catch{}uy=0}function Y(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=Ke(),t=dy(e);r.appendFileSync(e,n),uy=t+Buffer.byteLength(n,`utf8`),uy>=5242880&&fy(e)}catch(e){uy=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}function py(e){let t=[];for(let n of e){let e=n.read();if(e.kind===`text`)return`# memory report from: ${n.name}\n${e.text}`;t.push(`# ${n.name}: unavailable — ${e.reason}`)}return[`# memory report: no probe answered`,...t.length>0?t:[`# no probe is known for this platform`]].join(`
|
|
123
123
|
`)}function my(e,t){return e===`darwin`?[hy(`footprint`,[`-p`,String(t)]),hy(`vmmap`,[`--summary`,String(t)])]:e===`linux`?[gy(`/proc/self/smaps_rollup`),gy(`/proc/self/status`)]:[]}function hy(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=De({bin:e,args:[...t],timeoutMs:5e3,category:`limits.memory-report`});return n.ok?n.stdout.trim().length>0?{kind:`text`,text:n.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${n.reason}${n.error===void 0?``:`: ${n.error}`}${_y(n.stderr)}`}}}}function gy(e){return{name:e,read:()=>{try{let t=r.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}function _y(e){let t=e.split(`
|
|
124
124
|
`).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const vy=`CC_CANDYBAR_RSS_LIMIT_MB`;function yy(e){let t=e[vy];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${vy} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function by(e){return yy(e)*2}const xy=1024*1024;function Sy(e){return yy(e)*xy}const Cy={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function wy(e,t,n){let{prefix:r,suffix:i}=Cy[t];return c.join(e,`${r}${n}${i}`)}function Ty(e){for(let t of Object.keys(Cy)){let{prefix:n,suffix:r}=Cy[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function Ey(e){let t=e.rssLimitBytes??512*xy,n=e.snapshotsKeep??3,r=!1;function i(){if(r)return!0;let{rss:i,heapTotal:a}=e.memoryBytes();if(i<=t)return!1;r=!0,e.log(`warn`,`RSS ${i} > limit ${t} (v8 heap ${a}); recording memory then shutting down`);let o=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return Dy(e.log,`memory report`,()=>{let t=wy(e.snapshotDir,`memoryReport`,o);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),Dy(e.log,`heap snapshot`,()=>{let t=wy(e.snapshotDir,`heapSnapshot`,o);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),Dy(e.log,`artifact rotation`,()=>{ky(e.listArtifacts(),n,e.removeFile)}),e.shutdown(0),!0}function a(){let{rss:n,heapTotal:r}=e.memoryBytes();return n>t*.75?`rss ${n} approaching limit ${t} (v8 heap ${r})`:null}function o(e=6e4){let t=setInterval(()=>{i()},e);return t.unref(),{disarm:()=>clearInterval(t)}}return{checkRss:i,describeNextRestart:a,arm:o}}function Dy(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function Oy(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=Ty(t);if(n===null)return t;let{prefix:r,suffix:i}=Cy[n];return t.slice(r.length,t.length-i.length)}function ky(e,t,n){let r=new Map;for(let t of e){let e=Oy(t),n=r.get(e);n===void 0?r.set(e,[t]):n.push(t)}let i=[...r.keys()].sort((e,t)=>t.localeCompare(e));for(let e of i.slice(t))for(let t of r.get(e)??[])try{n(t)}catch{}}function Ay(e,t,n={}){let i=Ne();return{now:()=>Date.now(),pid:process.pid,snapshotDir:i,log:Y,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},captureMemoryReport:()=>py(my(process.platform,process.pid)),writeMemoryReport:(e,t)=>r.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>_.writeHeapSnapshot(e),listArtifacts:()=>{try{return r.readdirSync(i).filter(e=>Ty(e)!==null).map(e=>c.join(i,e))}catch{return[]}},removeFile:e=>r.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function jy(e={}){if(qy()!==null)return;let n=e.spawn??Jy,r=Wy();if(r.kind===`contended`){let e=Ny();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),My(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),My(n);return}try{My(n)}finally{Ky()}}function My(e){By()&&Py(e)}function Ny(){try{let e=r.statSync(He());return Date.now()-e.mtimeMs}catch{return null}}function Py(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
|
|
125
|
-
`)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function Fy(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function Iy(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function Ly(e){try{let t=r.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function Ry(e,n){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function zy(){try{r.unlinkSync(We())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function By(){let e=Ue(),n=We(),r=Ly(n),i=Fy(Vy(e),Iy(r));return i.kind===`deny`?!1:(i.kind===`allow-future-garbage`&&t.stderr.write(`cc-candybar: spawn.cooldown mtime is ${i.futureMs}ms in the future — ignoring and spawning\n`),Hy(e),Ry(n,Math.min(r+1,5)),!0)}function Vy(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function Hy(e){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,`${t.pid} ${Date.now()}\n`,{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}let Uy=null;function Wy(){let e=He();for(let n=0;n<2;n++){try{let n=r.openSync(e,`wx`,384);try{r.writeSync(n,JSON.stringify({pid:t.pid,ts:Date.now()}))}catch{}return Uy={fd:n,path:e},{kind:`held`}}catch(t){let n=t.code;if(n!==`EEXIST`)return{kind:`error`,reason:`openSync(${e}): ${n??t.message}`}}if(!Gy(e))return{kind:`contended`};try{r.unlinkSync(e)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function Gy(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function Ky(){if(!Uy)return;let{fd:e,path:t}=Uy;Uy=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function qy(){try{return r.mkdirSync(Ne(),{recursive:!0}),null}catch(e){return`mkdir ${Ne()}: ${e.message}`}}function Jy(){let e=t.execPath,n=t.argv[1];return n?Oe({bin:e,args:[`--max-old-space-size=${by(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const Yy=`cc-candybar`,Xy=`dispatch`,Zy=`set-state`,Qy=`step-state`,$y=`copy`,eb=`open-vscode`,tb=`toolbar-toggle`,nb=`show-config-error`,rb=`show-config-warning`,ib=`set-config`,ab=`step-config`,ob=`reset-config`,sb=`apply-layout-op`,cb=`undo`,lb=`redo`,ub=`apply-update`,db=`doctor-run`,fb=`doctor-fix`;function pb(e){return e.map(encodeURIComponent).join(`/`)}function mb(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function hb(e){return`${Yy}://${Xy}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${pb(e.args)}`)}`).join(`&`)}`}function gb(e){return new y(e).getAll(`e`).map(_b)}function _b(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const vb=`1.
|
|
125
|
+
`)}catch(e){t.stderr.write(`cc-candybar: daemon spawn failed: ${e.message}\n`)}}function Fy(e,t){return e===null?{kind:`allow`}:e<-1e4?{kind:`allow-future-garbage`,futureMs:-e}:e<t?{kind:`deny`}:{kind:`allow`}}function Iy(e){return Math.min(3e3*2**Math.min(Math.max(e,0),5),6e4)}function Ly(e){try{let t=r.readFileSync(e,`utf8`).trim(),n=Number(t);return!Number.isInteger(n)||n<0?0:Math.min(n,5)}catch{return 0}}function Ry(e,n){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,String(n),{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.backoff: ${e.message}\n`)}}function zy(){try{r.unlinkSync(We())}catch(e){e.code!==`ENOENT`&&t.stderr.write(`cc-candybar: could not reset spawn.backoff: ${e.message}\n`)}}function By(){let e=Ue(),n=We(),r=Ly(n),i=Fy(Vy(e),Iy(r));return i.kind===`deny`?!1:(i.kind===`allow-future-garbage`&&t.stderr.write(`cc-candybar: spawn.cooldown mtime is ${i.futureMs}ms in the future — ignoring and spawning\n`),Hy(e),Ry(n,Math.min(r+1,5)),!0)}function Vy(e){try{return Date.now()-r.statSync(e).mtimeMs}catch{return null}}function Hy(e){try{r.mkdirSync(c.dirname(e),{recursive:!0}),r.writeFileSync(e,`${t.pid} ${Date.now()}\n`,{mode:384})}catch(e){t.stderr.write(`cc-candybar: could not record spawn.cooldown: ${e.message}\n`)}}let Uy=null;function Wy(){let e=He();for(let n=0;n<2;n++){try{let n=r.openSync(e,`wx`,384);try{r.writeSync(n,JSON.stringify({pid:t.pid,ts:Date.now()}))}catch{}return Uy={fd:n,path:e},{kind:`held`}}catch(t){let n=t.code;if(n!==`EEXIST`)return{kind:`error`,reason:`openSync(${e}): ${n??t.message}`}}if(!Gy(e))return{kind:`contended`};try{r.unlinkSync(e)}catch(e){if(e.code!==`ENOENT`)return{kind:`error`,reason:`unlink stale spawn.lock: ${e.message}`}}}return{kind:`contended`}}function Gy(e){try{let t=r.statSync(e);return Date.now()-t.mtimeMs>1e4}catch{return!0}}function Ky(){if(!Uy)return;let{fd:e,path:t}=Uy;Uy=null;try{r.closeSync(e)}catch{}try{r.unlinkSync(t)}catch{}}function qy(){try{return r.mkdirSync(Ne(),{recursive:!0}),null}catch(e){return`mkdir ${Ne()}: ${e.message}`}}function Jy(){let e=t.execPath,n=t.argv[1];return n?Oe({bin:e,args:[`--max-old-space-size=${by(t.env)}`,n,`daemon`],category:`daemon-spawn`}).ok:!1}const Yy=`cc-candybar`,Xy=`dispatch`,Zy=`set-state`,Qy=`step-state`,$y=`copy`,eb=`open-vscode`,tb=`toolbar-toggle`,nb=`show-config-error`,rb=`show-config-warning`,ib=`set-config`,ab=`step-config`,ob=`reset-config`,sb=`apply-layout-op`,cb=`undo`,lb=`redo`,ub=`apply-update`,db=`doctor-run`,fb=`doctor-fix`;function pb(e){return e.map(encodeURIComponent).join(`/`)}function mb(e){return e.length===0?[]:e.split(`/`).map(decodeURIComponent)}function hb(e){return`${Yy}://${Xy}/${e.map(e=>`e=${encodeURIComponent(`${e.verb}/${pb(e.args)}`)}`).join(`&`)}`}function gb(e){return new y(e).getAll(`e`).map(_b)}function _b(e){let t=e.indexOf(`/`);return t===-1?{verb:e,value:``}:{verb:e.slice(0,t),value:e.slice(t+1)}}const vb=`1.72.0`;function yb(){return c.join(f.homedir(),`.claude`,`settings.json`)}function X(e){return{kind:`ok`,value:e}}const Z={kind:`absent`};function Q(e){return{kind:`failed`,reason:e}}function bb(e,t){return e?.kind===`ok`?e.value:t}const xb=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function Sb(e){let t=xb.exec(e);return t?{kind:`ok`,value:[Number(t[1]),Number(t[2]),Number(t[3])]}:{kind:`failed`,reason:`"${e}" is not a release version (expected MAJOR.MINOR.PATCH)`}}function Cb(e){return e.join(`.`)}function wb([e,t,n],[r,i,a]){return e-r||t-i||n-a}const Tb=`@promptctl/cc-candybar`;async function Eb(e,t,n){let r=`${n}/-/package/${encodeURIComponent(e)}/dist-tags`;try{let e=await t(r,{signal:AbortSignal.timeout(5e3)});if(!e.ok)return Q(`registry responded ${e.status} for ${r}`);let n=await e.json();return typeof n.latest==`string`?Sb(n.latest):Z}catch(e){return Q(e instanceof Error?e.message:String(e))}}function Db(e,t){let n=Sb(e);if(n.kind===`failed`)return{kind:`unchecked`,installed:e,reason:n.reason};switch(t.kind){case`failed`:return{kind:`unchecked`,installed:e,reason:t.reason};case`absent`:return{kind:`unchecked`,installed:e,reason:"the registry lists no `latest` dist-tag"};case`ok`:{let e=wb(n.value,t.value);return e<0?{kind:`stale`,installed:n.value,latest:t.value}:e>0?{kind:`ahead`,installed:n.value,latest:t.value}:{kind:`current`,installed:n.value}}}}function Ob(e,t){switch(t.kind){case`current`:return{stream:`stdout`,text:`✓ cc-candybar ${Cb(t.installed)} is the latest release.\n`};case`ahead`:return{stream:`stdout`,text:`cc-candybar ${Cb(t.installed)} is newer than the registry's latest release (${Cb(t.latest)}): an unpublished build.\n`};case`stale`:{let n=Cb(t.latest);return{stream:`stderr`,text:`⚠ cc-candybar ${Cb(t.installed)} was staged, but the latest release is ${n}.\n pnpm's release-age gate (minimumReleaseAge) and its dlx cache can both\n resolve \`@latest\` to an older release without saying so.\n To install ${n} now, name it explicitly:\n pnpm dlx ${e}@${n} install\n`}}case`unchecked`:return{stream:`stderr`,text:`⚠ Could not check for a cc-candybar release newer than ${t.installed} (${t.reason}); the registry check was skipped.\n`}}}const kb=`CCCandybarURLHandler`,Ab=[],jb={"darwin-arm64":`@promptctl/cc-candybar-darwin-arm64`,"darwin-x64":`@promptctl/cc-candybar-darwin-x64`,"linux-x64":`@promptctl/cc-candybar-linux-x64`,"linux-arm64":`@promptctl/cc-candybar-linux-arm64`};function Mb(e){return/^[A-Za-z0-9_./=,:-]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function Nb(e,t){return[e,...t].map(Mb).join(` `)}function Pb(){return c.join(f.homedir(),`Applications`,`${kb}.app`)}function Fb(){if(process.platform!==`darwin`)throw Error(`URL handler installation requires macOS (found platform: ${process.platform}).`)}function Ib(){if(process.platform===`darwin`)return c.join(f.homedir(),`Library`,`Application Support`,`CCCandybar`);let e=process.env.XDG_DATA_HOME??c.join(f.homedir(),`.local`,`share`);return c.join(e,`cc-candybar`)}function Lb(){return c.join(Ib(),`bin`,`cc-candybar`)}function Rb(){return c.join(Ib(),`dist`,`index.mjs`)}function zb(e,t){return[`on open location L`,`\tdo shell script "'${e.replace(/"/g,`\\"`)}' '${t.replace(/"/g,`\\"`)}' url-handle " & quoted form of L`,`end open location`].join(`
|
|
126
126
|
`)}function Bb(e){if(!e)throw Error(`install: process.argv[1] not set`);return e.endsWith(`.mjs`)||e.endsWith(`.js`)?e:c.resolve(c.dirname(e),`..`,`dist`,`index.mjs`)}function Vb(t){let n=jb[`${process.platform}-${process.arch}`];if(n){let r=e(t);try{return{kind:`native`,sourcePath:r.resolve(`${n}/bin/cc-candybar`)}}catch{}}return{kind:`node-shim`,sourcePath:c.resolve(c.dirname(t),`..`,`bin`,`cc-candybar`)}}function Hb(e,t){c.resolve(e)!==c.resolve(t)&&r.copyFileSync(e,t)}function Ub(e){let t=r.openSync(e,`r`);try{let n=Buffer.alloc(2),i=r.readSync(t,n,0,2,0);if(i<2)throw Error(`install: staged render entry at ${e} is truncated (${i} byte(s)). Re-run: pnpm dlx ${Tb}@latest install`);return n.toString(`latin1`)===`#!`?`node-shim`:`native`}finally{r.closeSync(t)}}function Wb(){let e=Bb(process.argv[1]);if(!r.existsSync(e))throw Error(`install: bundled dist not found at ${e}. Reinstall the package.`);let t=Vb(e);if(!r.existsSync(t.sourcePath))throw Error(`install: render entry not found at ${t.sourcePath}. Reinstall the package.`);r.mkdirSync(c.dirname(Rb()),{recursive:!0}),r.mkdirSync(c.dirname(Lb()),{recursive:!0}),Hb(e,Rb()),Hb(t.sourcePath,Lb()),r.chmodSync(Lb(),493),r.rmSync(c.join(Ib(),`url-handler.mjs`),{force:!0});let n=Ub(Lb());return process.stdout.write(`Staged cc-candybar v${vb} runtime at ${Ib()}\n`+(n===`native`?` render entry: native binary (${process.platform}-${process.arch})\n`:` render entry: node shim (no native binary for ${process.platform}-${process.arch}; renders are correct but pay node startup)\n`)),{binPath:Lb(),distPath:Rb(),entryKind:n}}function Gb(){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>${Yy}</string>`,` </array>`,` </dict>`,`</array>`].join(`
|
|
127
127
|
`)}]}function Kb(e){let t=Pb();r.mkdirSync(c.dirname(t),{recursive:!0}),r.existsSync(t)&&r.rmSync(t,{recursive:!0,force:!0}),process.stdout.write(`Building ${t}\n`);let n=De({bin:`/usr/bin/osacompile`,args:[`-o`,t,`-e`,zb(process.execPath,e)],category:`install.osacompile`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`osacompile failed (${n.reason})`);let i=c.join(t,`Contents`,`Info.plist`);for(let{key:e}of Gb())De({bin:`/usr/bin/plutil`,args:[`-remove`,e,i],category:`install.plutil`});for(let{key:e,xml:t}of Gb()){let n=De({bin:`/usr/bin/plutil`,args:[`-insert`,e,`-xml`,t,i],category:`install.plutil`});if(!n.ok)throw process.stderr.write(n.stderr),Error(`plutil -insert ${e} failed (${n.reason})`)}process.stdout.write(`Registering ${Yy}:// with Launch Services\n`);let a=De({bin:`/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister`,args:[`-f`,t],category:`install.lsregister`});if(!a.ok)throw process.stderr.write(a.stderr),Error(`lsregister failed (${a.reason})`);process.stdout.write(`✓ ${kb}.app installed and registered.\n`),process.stdout.write(` Test: open '${Yy}://hello-world' && pbpaste\n`)}function qb(){Fb(),Kb(Wb().distPath)}function Jb(e,t=Yy){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:$y,value:r}:{verb:decodeURIComponent(r.slice(0,i)),value:r.slice(i+1)}}async function Yb(e){e||(process.stderr.write(`url-handle: missing URL argument.
|
|
128
128
|
`),process.exit(1));let t;try{t=Jb(e)}catch(e){process.stderr.write(`url-handle: ${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let n=await ly(t.verb,t.value);n.kind===`ok`&&process.exit(0),n.kind===`transient`&&(jy(),process.stderr.write(`url-handle: daemon unavailable (${n.cause}: ${n.message})\n`),process.exit(1)),process.stderr.write(Xb(n)+`
|
|
@@ -135,7 +135,7 @@ Config tooling:
|
|
|
135
135
|
`)?r.slice(0,-1):r}return Vr(new jr([...e],n),{colorSystem:t.colorCompatibility})}function Ix(e){return Math.min(20,e??20)}const Lx={heading:`ERROR`,glyph:`⚠`,colors:kx},Rx={heading:`WARNING`,glyph:`⚠`,colors:Ax},zx={heading:`UPDATE`,glyph:`⬆`,colors:Ax};function Bx(e,t){return{text:wx(e),link:t}}function Vx(e,t,n){let[r,...i]=[Hx(e,Lx,nb),t,Hx(n,Rx,rb)].flat();return r===void 0?null:{channels:[r,...i]}}function Hx(e,t,n){let r=hb([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>Bx(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function Ux(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
|
|
136
136
|
`)}function Wx(e,t,n,r){if(t===null)return e;let i=Gx(r),a=t.channels.flatMap(e=>Kx(e,i)),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[qx(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
|
|
137
137
|
`);return e?`${l}\n${e}`:l}function Gx(e){return{style:`plain`,separator:``,width:e.width,wrap:!0,padding:0,charset:`unicode`,colorCompatibility:e.colorCompatibility}}function Kx(e,t){let n=new H({bgcolor:e.severity.colors.bg,color:e.severity.colors.fg}),r=A(Math.max(2,t.width-1)),i=(e,t)=>new Ar(`${e} `,{style:t,end:``,noWrap:!0});return e.lines.flatMap((a,o)=>Fx([i(o===0?e.severity.glyph:` `,n.withLink(a[0].link)),...a.flatMap(e=>{let t=n.withLink(e.link);return e.text.split(` `).flatMap(e=>Vt(e,r)).map(e=>i(e,t))})],t).split(`
|
|
138
|
-
`))}function qx(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new H({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new Ar(e,{style:t,end:``,noWrap:!0}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(x(a.path).href)):c(`full text unavailable: ${wx(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(wx(o),s.withLink(x(o).href))],d=[c(`↳ `,s),...l,...u.slice(0,-1)],f=d.reduce((e,t)=>e+t.cellLength,0),p=u.slice(-1).map(e=>e.truncate(Math.max(1,r.width-f),{mode:`middle`})),m=Ar.fromFragments([...d,...p]).truncate(r.width,{overflow:`ellipsis`});return m.noWrap=!0,Fx([m],r)}const Jx=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Yx(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function Xx(e,t){return r.readdirSync(t).filter(Jx).sort().flatMap(n=>{let i=c.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?Xx(e,i):[[c.relative(e,i).split(c.sep).join(`/`),Yx(i,a)]]})}function Zx(e){let t=C.createHash(`sha256`);for(let[n,r]of Xx(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const Qx=e=>e.slice(0,7);function $x(e){return c.dirname(c.dirname(e))}function eS(){return{version:vb,digest:`9e93d3272d4865300e11b6828d14bfc52e227c8dc410a4bf74eec910cd5c1085`}}function tS(e){let t=JSON.parse(r.readFileSync(c.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${c.join(e,`package.json`)} has no version string`);return n}function nS(e,t){try{let n=$x(b(e)),i=c.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=Zx(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:tS(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var $=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};const rS=/^-?\d+$/;function iS(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function aS(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function oS(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!rS.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 sS(e,t,n){return r=>r?rS.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 cS(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!rS.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i,seed:iS(r[0].seed,t,i)}}return{kind:`int`}}function lS(e){return e===`config`?`set-config`:`set-state`}function uS(e,t,n){return t.kind===`int`?oS(`menu page "${e}"`):t.kind===`range`?sS(t.min,t.max,`${n} stepper "${e}"`):aS(t.allowed,`${n} "${e}"`,lS(n))}function dS(e,t,n){return uS(e,cS(e,t,n),n)}function fS(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:cS(e,n,t)}))}function pS(e,t=`state`){let n=new Map(Object.entries(e).map(([e,t])=>[e,{validator:t,permanent:!0}]));function r(){let e=[];for(let[t,r]of n)r.permanent&&e.push(t);return e}return{register(e,i){if(!e)throw Error(`register: key is required`);if(e.includes(`/`))throw Error(`register: key "${e}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);let a=n.get(e);if(a){if(a.permanent)throw Error(`register: key "${e}" is a built-in ${t} key and cannot be re-claimed (built-in keys: ${[...r()].join(`, `)})`);if(a.kind!==i.kind)throw Error(`register: key "${e}" is already a ${a.kind} ${t} key; cannot also register it as ${i.kind}. A ${t} key has one key shape — a menu page index (int) and a button allow-list cannot share a key.`);a.specs.push(i),a.validator=dS(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:dS(e,r,t),specs:r})}let o=!0;return()=>{if(!o)return;o=!1;let r=n.get(e);if(!r||r.permanent)return;let a=r.specs.indexOf(i);a>=0&&r.specs.splice(a,1),r.specs.length===0?n.delete(e):r.validator=dS(e,r.specs,t)}},validate(e,r){let i=n.get(e);return i?i.validator(r):{ok:!1,reason:`unknown ${t} key "${e}" (have: ${[...n.keys()].join(`, `)})`}},listKeys(){return[...n.keys()]},listBaselineKeys(){return r()},rangeParamsFor(e){let r=n.get(e);if(!r||r.permanent||r.kind!==`range`)return null;let i=cS(e,r.specs,t);if(i.kind!==`range`)throw Error(`rangeParamsFor: key "${e}" holds range specs but the merge produced a ${i.kind} spec — the entry-kind invariant is broken.`);return{min:i.min,max:i.max,seed:i.seed}}}}const mS=pS({},`config`);function hS(){return mS.listKeys()}function gS(e,t){return mS.validate(e,t)}function _S(e){return mS.rangeParamsFor(e)}function vS(e,t,n){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Y_(e.from,n).members}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[ih({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[ih({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Y_(e.insertSegmentFrom,n).members.map(t=>ih({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max,seed:iS(t.get(e.persist),e.min,e.max)}}]:[]}function yS(e){return Fo(e.globals)}function bS(e){let t=new Set;for(let n of SS(e)){let e=`persist`in n?n.persist:`reset`in n?n.reset:null;if(e===null)continue;let r=_h(e);r?.scope===`preset-root`&&t.add(r.preset)}return[...t].map(e=>({key:gh(e),spec:{kind:`allow-list`,allowed:[]}}))}function xS(e){let t=yS(e),n=new Map([...q_(e),...Ah(e)]);return[...bS(e),...SS(e).flatMap(e=>vS(e,t,n))]}function SS(e){return Object.values(e.actions).flatMap(Ig)}function CS(e){return fS(xS(e),`config`)}function wS(e,t){return mS.register(e,t)}const TS=li(),ES=new Set(TS),DS=new Set(yi),OS=e=>e?ES.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${TS.join(`, `)})`}:{ok:!1,reason:`theme name is required`},kS=e=>e?DS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${yi.join(`, `)})`}:{ok:!1,reason:`style name is required`},AS=new Set([`1`,`true`]),jS=new Set([`0`,`false`]),MS=pS({style:kS,theme:OS,"toolbar-expanded":e=>AS.has(e)?{ok:!0,value:`1`}:jS.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function NS(){return MS.listKeys()}function PS(e,t){return MS.register(e,t)}function FS(e,t){return MS.validate(e,t)}function IS(e){return MS.rangeParamsFor(e)}function LS(e,t,n){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:Y_(e.from,n).members}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max,seed:iS(t.get(e.set),e.min,e.max)}}]:[]}function RS(e){let t=new Set(MS.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function zS(e){let t=new Map,n=/^-?\d+$/;for(let r of Object.values(e.variables)){if(r.kind!==`state`)continue;let e=r.default;e!==void 0&&n.test(e)&&t.set(r.key,parseInt(e,10))}for(let[n,r]of Fo(e.globals))t.set(n,r);return t}function BS(e){let t=zS(e),n=q_(e);return RS(Object.values(e.actions).flatMap(Ig).flatMap(e=>LS(e,t,n)))}function VS(e){return fS(BS(e))}const HS=`update.dismissed`,US=`updateNotice`;function WS(e){return e.kind===`source`?e.newer.digest:Cb(e.newer)}const GS=e=>`${e.version} [${Qx(e.digest)}]`;function KS(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:GS(e.newer),running:GS(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:Cb(e.newer),running:Cb(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${Tb}@${Cb(e.newer)}`,`install`]}}}}const qS={kind:`idle`},JS={kind:`running`};function YS(e,t,n){if(e===null)return[];let r=WS(e);if(!n.enabled||n.dismissed===r)return[];let i=KS(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
|
|
138
|
+
`))}function qx(e,t,n,r){let{colors:i}=e.channels[0].severity,{fullText:a,failedConfigFile:o}=t,s=new H({bgcolor:i.bg,color:i.fg}),c=(e,t)=>new Ar(e,{style:t,end:``,noWrap:!0}),l=n>0?[c(`${n} more rows · `,s),a.kind===`file`?c(`open full text`,s.withLink(x(a.path).href)):c(`full text unavailable: ${wx(a.reason)}`,s)]:[],u=o===null?[]:[c(`${l.length>0?` · `:``}open `,s),c(wx(o),s.withLink(x(o).href))],d=[c(`↳ `,s),...l,...u.slice(0,-1)],f=d.reduce((e,t)=>e+t.cellLength,0),p=u.slice(-1).map(e=>e.truncate(Math.max(1,r.width-f),{mode:`middle`})),m=Ar.fromFragments([...d,...p]).truncate(r.width,{overflow:`ellipsis`});return m.noWrap=!0,Fx([m],r)}const Jx=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Yx(e,t){return t.isSymbolicLink()?Buffer.from(r.readlinkSync(e)):r.readFileSync(e)}function Xx(e,t){return r.readdirSync(t).filter(Jx).sort().flatMap(n=>{let i=c.join(t,n),a=r.lstatSync(i,{throwIfNoEntry:!1});return a===void 0?[]:a.isDirectory()?Xx(e,i):[[c.relative(e,i).split(c.sep).join(`/`),Yx(i,a)]]})}function Zx(e){let t=C.createHash(`sha256`);for(let[n,r]of Xx(e,e))t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}const Qx=e=>e.slice(0,7);function $x(e){return c.dirname(c.dirname(e))}function eS(){return{version:vb,digest:`c6d4fb2f93fb3c9c21b046688a3dc309a80923fce841d9b956867ce8e9844acb`}}function tS(e){let t=JSON.parse(r.readFileSync(c.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${c.join(e,`package.json`)} has no version string`);return n}function nS(e,t){try{let n=$x(b(e)),i=c.join(n,`src`);if(!r.existsSync(i))return{kind:`not-source-checkout`};let a=t(),o=Zx(i);return o===a.digest?{kind:`current`,root:n,stamp:a}:{kind:`stale`,root:n,source:{version:tS(n),digest:o},running:a}}catch(e){return{kind:`unchecked`,reason:e.message}}}var $=class extends Error{constructor(e){super(e),this.name=`BadVerbArgs`}};const rS=/^-?\d+$/;function iS(e,t,n){return e===void 0?t:Math.max(t,Math.min(n,e))}function aS(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function oS(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!rS.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 sS(e,t,n){return r=>r?rS.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 cS(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!rS.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i,seed:iS(r[0].seed,t,i)}}return{kind:`int`}}function lS(e){return e===`config`?`set-config`:`set-state`}function uS(e,t,n){return t.kind===`int`?oS(`menu page "${e}"`):t.kind===`range`?sS(t.min,t.max,`${n} stepper "${e}"`):aS(t.allowed,`${n} "${e}"`,lS(n))}function dS(e,t,n){return uS(e,cS(e,t,n),n)}function fS(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:cS(e,n,t)}))}function pS(e,t=`state`){let n=new Map(Object.entries(e).map(([e,t])=>[e,{validator:t,permanent:!0}]));function r(){let e=[];for(let[t,r]of n)r.permanent&&e.push(t);return e}return{register(e,i){if(!e)throw Error(`register: key is required`);if(e.includes(`/`))throw Error(`register: key "${e}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);let a=n.get(e);if(a){if(a.permanent)throw Error(`register: key "${e}" is a built-in ${t} key and cannot be re-claimed (built-in keys: ${[...r()].join(`, `)})`);if(a.kind!==i.kind)throw Error(`register: key "${e}" is already a ${a.kind} ${t} key; cannot also register it as ${i.kind}. A ${t} key has one key shape — a menu page index (int) and a button allow-list cannot share a key.`);a.specs.push(i),a.validator=dS(e,a.specs,t)}else{let r=[i];n.set(e,{permanent:!1,kind:i.kind,validator:dS(e,r,t),specs:r})}let o=!0;return()=>{if(!o)return;o=!1;let r=n.get(e);if(!r||r.permanent)return;let a=r.specs.indexOf(i);a>=0&&r.specs.splice(a,1),r.specs.length===0?n.delete(e):r.validator=dS(e,r.specs,t)}},validate(e,r){let i=n.get(e);return i?i.validator(r):{ok:!1,reason:`unknown ${t} key "${e}" (have: ${[...n.keys()].join(`, `)})`}},listKeys(){return[...n.keys()]},listBaselineKeys(){return r()},rangeParamsFor(e){let r=n.get(e);if(!r||r.permanent||r.kind!==`range`)return null;let i=cS(e,r.specs,t);if(i.kind!==`range`)throw Error(`rangeParamsFor: key "${e}" holds range specs but the merge produced a ${i.kind} spec — the entry-kind invariant is broken.`);return{min:i.min,max:i.max,seed:i.seed}}}}const mS=pS({},`config`);function hS(){return mS.listKeys()}function gS(e,t){return mS.validate(e,t)}function _S(e){return mS.rangeParamsFor(e)}function vS(e,t,n){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Y_(e.from,n).members}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[ih({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[ih({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Y_(e.insertSegmentFrom,n).members.map(t=>ih({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max,seed:iS(t.get(e.persist),e.min,e.max)}}]:[]}function yS(e){return Fo(e.globals)}function bS(e){let t=new Set;for(let n of SS(e)){let e=`persist`in n?n.persist:`reset`in n?n.reset:null;if(e===null)continue;let r=_h(e);r?.scope===`preset-root`&&t.add(r.preset)}return[...t].map(e=>({key:gh(e),spec:{kind:`allow-list`,allowed:[]}}))}function xS(e){let t=yS(e),n=new Map([...q_(e),...Ah(e)]);return[...bS(e),...SS(e).flatMap(e=>vS(e,t,n))]}function SS(e){return Object.values(e.actions).flatMap(Ig)}function CS(e){return fS(xS(e),`config`)}function wS(e,t){return mS.register(e,t)}const TS=li(),ES=new Set(TS),DS=new Set(yi),OS=e=>e?ES.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${TS.join(`, `)})`}:{ok:!1,reason:`theme name is required`},kS=e=>e?DS.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown style "${e}" (have: ${yi.join(`, `)})`}:{ok:!1,reason:`style name is required`},AS=new Set([`1`,`true`]),jS=new Set([`0`,`false`]),MS=pS({style:kS,theme:OS,"toolbar-expanded":e=>AS.has(e)?{ok:!0,value:`1`}:jS.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}});function NS(){return MS.listKeys()}function PS(e,t){return MS.register(e,t)}function FS(e,t){return MS.validate(e,t)}function IS(e){return MS.rangeParamsFor(e)}function LS(e,t,n){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:Y_(e.from,n).members}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max,seed:iS(t.get(e.set),e.min,e.max)}}]:[]}function RS(e){let t=new Set(MS.listBaselineKeys());return e.filter(e=>e.spec.kind!==`allow-list`||!t.has(e.key))}function zS(e){let t=new Map,n=/^-?\d+$/;for(let r of Object.values(e.variables)){if(r.kind!==`state`)continue;let e=r.default;e!==void 0&&n.test(e)&&t.set(r.key,parseInt(e,10))}for(let[n,r]of Fo(e.globals))t.set(n,r);return t}function BS(e){let t=zS(e),n=q_(e);return RS(Object.values(e.actions).flatMap(Ig).flatMap(e=>LS(e,t,n)))}function VS(e){return fS(BS(e))}const HS=`update.dismissed`,US=`updateNotice`;function WS(e){return e.kind===`source`?e.newer.digest:Cb(e.newer)}const GS=e=>`${e.version} [${Qx(e.digest)}]`;function KS(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:GS(e.newer),running:GS(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:Cb(e.newer),running:Cb(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${Tb}@${Cb(e.newer)}`,`install`]}}}}const qS={kind:`idle`},JS={kind:`running`};function YS(e,t,n){if(e===null)return[];let r=WS(e);if(!n.enabled||n.dismissed===r)return[];let i=KS(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
|
|
139
139
|
`),c=hb([{verb:rb,args:[s]}]),l=t.kind===`running`?Bx(`[${i.busy}]`,c):Bx(`[${i.act}]`,hb([{verb:ub,args:[n.sessionId]}]));return[{severity:zx,message:s,lines:[[Bx(a,c),l,Bx(`[dismiss]`,hb([{verb:Zy,args:[n.sessionId,HS,r]}])),Bx(`[disable]`,hb([{verb:ib,args:[n.sessionId,US,`false`]}]))],...o.map(e=>[Bx(e,c)])]}]}function XS(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function ZS(e){switch(e.kind){case`current`:return[`info`,`build: current ${GS(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${GS(e.source)}, running ${GS(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function QS(e){switch(e.kind){case`current`:return[`info`,`release: current ${Cb(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${Cb(e.latest)}, running ${Cb(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${Cb(e.installed)}, latest ${Cb(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function $S(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const eC=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function tC(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=eC(e.stderr)??e.error??eC(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function nC(e){let{entryUrl:t,intervalMs:n,releaseIntervalMs:r,registryUrl:i,fetchImpl:a,onApplied:o,log:s}=e,c={kind:`unchecked`,reason:`not sampled yet`},l=null,u=qS,d=null,f=$S(s),p=$S(s),m=()=>XS(c,l);function h(){let e=m(),t=e===null?null:WS(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:PS(HS,{kind:`allow-list`,allowed:[t]})})}function g(){c=nS(t,eS),f(ZS(c)),h()}async function _(){l=Db(vb,await Eb(Tb,a,i)),p(QS(l)),h()}return{arm(){wS(US,{kind:`allow-list`,allowed:[`false`]}),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>YS(m(),u,e),act(){let e=m();if(e===null)throw new $(`apply-update: nothing newer is known to apply`);let t=KS(e);if(u.kind===`running`)throw new $(`apply-update: already ${t.busy}`);u=JS,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),Ee({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=qS,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=tC(n);u={kind:`failed`,identity:WS(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}function rC(e,t,n){return t.ok?X(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?Z:Q(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??iC(t.stderr)].filter(Boolean).join(`, `)}`)}function iC(e){return e.trim().split(`
|
|
140
140
|
`,1)[0]??``}function aC(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?Z:X(n)}function oC(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?X(t):Z}const sC=/^[A-Za-z]:[\\/]/;function cC(e){let t=e.trim();if(sC.test(t))return null;let n=t.match(/^(?:[^@/]+@)?(\[[^\]]+\]):(.*)$/)??t.match(/^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.*)$/),r=n?`ssh://${n[1]}/${n[2].replace(/^\/+/,``)}`:t,i;try{i=new URL(r)}catch{return null}return{scheme:i.protocol.replace(/:$/,``),host:i.hostname.toLowerCase(),port:i.port,path:i.pathname.replace(/^\/+/,``).replace(/\/+$/,``)}}function lC(e){return cC(e)?.host||null}function uC(e){let t=lC(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}function dC(e){let t=new Map;for(let n of e.split(`
|
|
141
141
|
`)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function fC(e){return e.urls.find(e=>_C(e)!==null)??e.urls[0]??null}function pC(e){return e.find(e=>e.name===`origin`)??e[0]??null}function mC(e){let t=pC(e);return t?fC(t):null}function hC(e){let t=pC(e);return t?t.urls.find(e=>uC(e)!==null)??fC(t):null}function gC(e){let t=(cC(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function _C(e){let t=cC(e);if(!t)return null;let n=t.scheme===`https`?{scheme:`https`,port:t.port}:t.scheme===`http`?{scheme:`http`,port:t.port}:t.scheme===`ssh`||t.scheme===`git`?{scheme:`https`,port:``}:null;if(!n||!t.host)return null;let r=t.path.replace(/\.git$/,``);if(!r)return null;let i=n.port?`${t.host}:${n.port}`:t.host;return`${n.scheme}://${i}/${r}`}function vC(e){let t=mC(e);return t===null?null:_C(t)}function yC(e,t,n,r){return t.ok?r(t.stdout):t.reason===`spawn-error`&&/ENOENT/i.test(t.error??``)||t.reason===`non-zero`&&n.test(t.stderr)?Z:Q(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??iC(t.stderr)].filter(Boolean).join(`, `)}`)}function bC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function xC(e){let t=`detached`,n=Z,r=Z,i=Z,a=0,o=0,s=0,c=0;for(let l of e.split(`
|
|
@@ -176,31 +176,31 @@ Extending builtins is not supported.`),e;Object.isExtensible(e)||n(`Cannot make
|
|
|
176
176
|
The field is already annotated with '`+a+`'.`)+`
|
|
177
177
|
Re-annotating fields is not allowed.
|
|
178
178
|
Use 'override' annotation for methods overridden by subclass.`)}}var na=ca(0),ra=function(){var e=!1,t={};return Object.defineProperty(t,`0`,{set:function(){e=!0}}),Object.create(t)[0]=1,e===!1}(),ia=0,aa=function(){};function oa(e,t){Object.setPrototypeOf?Object.setPrototypeOf(e.prototype,t):e.prototype.__proto__===void 0?e.prototype=t:e.prototype.__proto__=t}oa(aa,Array.prototype);var sa=function(e){function t(t,n,r,i){var a;return r===void 0&&(r=`ObservableArray@`+h()),i===void 0&&(i=!1),a=e.call(this)||this,ha(function(){var e=new Oi(r,n,i,!0);e.proxy_=a,ee(a,D,e),t&&t.length&&a.spliceWithArray(0,0,t),ra&&Object.defineProperty(a,`0`,na)}),a}ve(t,e);var n=t.prototype;return n.concat=function(){this[D].atom_.reportObserved();var e=[...arguments];return Array.prototype.concat.apply(this.slice(),e.map(function(e){return Fi(e)?e.slice():e}))},n[Symbol.iterator]=function(){var e=this,t=0;return ba({next:function(){return t<e.length?{value:e[t++],done:!1}:{done:!0,value:void 0}}})},he(t,[{key:`length`,get:function(){return this[D].getArrayLength_()},set:function(e){this[D].setArrayLength_(e)}},{key:Symbol.toStringTag,get:function(){return`Array`}}])}(aa);Object.entries(Ai).forEach(function(e){var t=e[0],n=e[1];t!==`concat`&&C(sa.prototype,t,n)});function ca(e){return{enumerable:!1,configurable:!0,get:function(){return this[D].get_(e)},set:function(t){this[D].set_(e,t)}}}function la(e){s(sa.prototype,``+e,ca(e))}function ua(e){if(e>ia){for(var t=ia;t<e+100;t++)la(t);ia=e}}ua(1e3);function da(e,t,n){return new sa(e,t,n)}function fa(e,t){if(typeof e==`object`&&e){if(Fi(e))return t!==void 0&&n(23),e[D].atom_;if(Gi(e))return e.atom_;if(Bi(e)){if(t===void 0)return e.keysAtom_;var r=e.data_.get(t)||e.hasMap_.get(t);return r||n(25,t,ma(e)),r}if($i(e)){if(!t)return n(26);var i=e[D].values_.get(t);return i||n(27,t,ma(e)),i}if(Pe(e)||tn(e)||z(e))return e}else if(v(e)&&z(e[D]))return e[D];n(28)}function pa(e,t){if(e||n(29),t!==void 0)return pa(fa(e,t));if(Pe(e)||tn(e)||z(e)||Bi(e)||Gi(e))return e;if(e[D])return e[D];n(24,e)}function ma(e,t){var n;if(t!==void 0)n=fa(e,t);else if(sr(e))return e.name;else n=$i(e)||Bi(e)||Gi(e)?pa(e):fa(e);return n.name_}function ha(e){var t=F(),n=Xt(!0);An();try{return e()}finally{jn(),Zt(n),hn(t)}}var ga=c.toString;function _a(e,t,n){return n===void 0&&(n=-1),G(e,t,n)}function G(e,t,n,r,i){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return!1;if(e!==e)return t!==t;var a=typeof e;if(a!==`function`&&a!==`object`&&typeof t!=`object`)return!1;var o=ga.call(e);if(o!==ga.call(t))return!1;switch(o){case`[object RegExp]`:case`[object String]`:return``+e==``+t;case`[object Number]`:return+e==+e?+e==0?1/e==1/t:+e==+t:+t!=+t;case`[object Date]`:case`[object Boolean]`:return+e==+t;case`[object Symbol]`:return typeof Symbol<`u`&&Symbol.valueOf.call(e)===Symbol.valueOf.call(t);case`[object Map]`:case`[object Set]`:n>=0&&n++;break}e=va(e),t=va(t);var s=o===`[object Array]`;if(!s){if(typeof e!=`object`||typeof t!=`object`)return!1;var c=e.constructor,l=t.constructor;if(c!==l&&!(v(c)&&c instanceof c&&v(l)&&l instanceof l)&&`constructor`in e&&`constructor`in t)return!1}if(n===0)return!1;n<0&&(n=-1),r||=[],i||=[];for(var u=r.length;u--;)if(r[u]===e)return i[u]===t;if(r.push(e),i.push(t),s){if(u=e.length,u!==t.length)return!1;for(;u--;)if(!G(e[u],t[u],n-1,r,i))return!1}else{var d=Object.keys(e),f=d.length;if(Object.keys(t).length!==f)return!1;for(var p=0;p<f;p++){var m=d[p];if(!(ce(t,m)&&G(e[m],t[m],n-1,r,i)))return!1}}return r.pop(),i.pop(),!0}function va(e){return Fi(e)?e.slice():ne(e)||Bi(e)||ie(e)||Gi(e)?Array.from(e.entries()):e}var ya=i().Iterator?.prototype||{};function ba(e){return e[Symbol.iterator]=xa,Object.assign(Object.create(ya),e)}function xa(){return this}function Sa(e){return e instanceof Object&&typeof e.annotationType_==`string`&&v(e.make_)&&v(e.extend_)}[`Symbol`,`Map`,`Set`].forEach(function(e){i()[e]===void 0&&n(`MobX requires global '`+e+`' to be available or polyfilled`)}),typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__==`object`&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({spy:Jn,extras:{getDebugName:ma},$mobx:D}),e.$mobx=D,e.FlowCancellationError=Dr,e.ObservableMap=zi,e.ObservableSet=Wi,e.Reaction=Ln,e._allowStateChanges=M,e._allowStateChangesInsideComputed=or,e._allowStateReadsEnd=_n,e._allowStateReadsStart=gn,e._autoAction=ar,e._endAction=Yt,e._getAdministration=pa,e._getGlobalState=wn,e._interceptReads=Fr,e._isComputingDerivation=sn,e._resetGlobalState=Tn,e._startAction=j,e.action=ir,e.autorun=cr,e.comparer=Be,e.computed=Ht,e.configure=br,e.createAtom=Fe,e.defineProperty=Qr,e.entries=qr,e.extendObservable=U,e.flow=jr,e.flowResult=Nr,e.get=Zr,e.getAtom=fa,e.getDebugName=ma,e.getDependencyTree=xr,e.getObserverTree=Cr,e.has=Xr,e.intercept=Ir,e.isAction=sr,e.isBoxedObservable=en,e.isComputed=Br,e.isComputedProp=Vr,e.isFlow=Pr,e.isFlowCancellationError=Or,e.isObservable=Ur,e.isObservableArray=Fi,e.isObservableMap=Bi,e.isObservableObject=$i,e.isObservableProp=Wr,e.isObservableSet=Gi,e.keys=Gr,e.makeAutoObservable=Ci,e.makeObservable=xi,e.observable=A,e.observe=ei,e.onBecomeObserved=mr,e.onBecomeUnobserved=hr,e.onReactionError=Rn,e.override=Ke,e.ownKeys=$r,e.reaction=dr,e.remove=Yr,e.runInAction=or,e.set=Jr,e.spy=Jn,e.toJS=ai,e.trace=oi,e.transaction=ci,e.untracked=mn,e.values=Kr,e.when=li})),tT=me(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=$w():t.exports=eT()}))();function nT(e){if(Array.isArray(e))return Object.freeze(e.map(nT));if(typeof e==`object`&&e){let t=Object.create(null),n=Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t));for(let[e,r]of n)t[e]=nT(r);return Object.freeze(t)}return e}function rT(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 iT(e){return typeof e==`string`?e:String(e)}function aT(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 oT(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")`)}function sT(e,t){if(!(e instanceof Ar))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 cT(e){return{fn:(t=>sT(t,e)),argTypes:[`liftable`],returnType:`T`}}function lT(e){return{fn:((t,n)=>sT(n,new H({[e]:N.parse(t)}))),argTypes:[`string`,`liftable`],returnType:`T`}}function uT(e,t){return new H({[e]:t})}function dT(){let e={};for(let t of lr)e[t]=cT(uT(t,!0)),e[`not_${t}`]=cT(uT(t,!1));for(let[t,n]of Object.entries(dr))e[t]=cT(uT(n,!0));return e}const fT={fn:((e,t)=>sT(t,H.parse(e))),argTypes:[`string`,`liftable`],returnType:`T`},pT={fn:((e,t)=>sT(t,new H({link:e}))),argTypes:[`string`,`liftable`],returnType:`T`};function mT(){return{fg:lT(`color`),bg:lT(`bgcolor`),...dT(),link:pT,style:fT}}function hT(e,t){if(!Dn.test(e.trim()))throw TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`);return On(e)}function gT(e,t){return{fn:t,argTypes:e,returnType:`string`}}function _T(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`+(e===void 0?` — ${t} takes it as its last argument`:``))}return e}const vT=gT([`string`,`int`],((e,t)=>Fn(hT(e,`darken`),_T(t,`darken`,`levels`)).hex)),yT=gT([`string`,`int`],((e,t)=>Fn(hT(e,`lighten`),-_T(t,`lighten`,`levels`)).hex)),bT={min:0,max:100,note:`0 = from, 100 = toward`},xT=gT([`string`,`string`,`float`],((e,t,n)=>cn(hT(e,`mix`),hT(t,`mix`),_T(n,`mix`,`percentage`,bT)/100).hex)),ST={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},CT=gT([`string`],(e=>In(hT(e,`contrastOn`)).hex)),wT=gT([`string`,`string`,`float`],((e,t,n)=>zn(hT(e,`readableOn`),hT(t,`readableOn`),_T(n,`readableOn`,`ratio`,ST)).hex)),TT={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function ET(){let e={};for(let[t,n]of Object.entries(TT)){let r=t;e[n]=gT([`string`,`float`],((e,t)=>{let i={...gn,[r]:_T(t,n,`amount`)};return L.fromRgba(hT(e,n)).applyKey(i).toRgba().hex}))}return e}function DT(){return{darken:vT,lighten:yT,mix:xT,contrastOn:CT,readableOn:wT,...ET()}}function OT(e,t){if(e.length===0)throw RangeError(`ramp needs at least one stop after the easing: ramp <value> <easing> <position> <color> …`);if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:kn(t,e[r+1])});return n}function kT(e){return{color:{fn:(t=>kn(e(),t).hex),argTypes:[`string`],returnType:`string`},ramp:{fn:((...t)=>{if(t.length<2)throw RangeError(`ramp needs a value and an easing before its stops (got ${t.length}): ramp <value> "linear"|"step" <position> <color> …`);let[n,r,...i]=t;return new ar(ir(r),OT(i,e())).at(n).hex}),argTypes:[`float`,`string`],argTypePattern:`alternating`,returnType:`string`}}}function AT(){return{...mT(),...DT()}}new H({color:`red`,dim:!0});const jT=/^(?:(?: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,MT=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function NT(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(jT);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(MT);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 PT(e){let t=e.match(MT);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 FT(e){let t=e.split(`/`),n=t.length-1;return t.map((e,t)=>{if(t===n)return e;let r=e.match(/^\.*./);return r?r[0]:e}).join(`/`)}function IT(e){return e.toLocaleString()}function LT(e){if(e.length===0)throw Error(`a cascade needs at least one stop, e.g. "0:calm"`);let t=[];for(let[n,r]of e.entries()){let e=r.indexOf(`:`),i=e<0?NaN:Number(r.slice(0,e));if(!Number.isFinite(i))throw Error(`cascade stop ${n} ("${r}") must be "<position>:<result>", e.g. "80:hot" — the position must be a number`);let a=t[n-1];if(a!==void 0&&i<a.at)throw Error(`cascade stops must be in ascending position order; stop ${n} at ${i} follows stop ${n-1} at ${a.at}`);t.push({at:i,text:r.slice(e+1)})}return t}function RT(e,t){if(!Number.isFinite(e))throw Error(`a cascade needs a finite value, got ${e}`);let n=-1;for(;n+1<t.length&&t[n+1].at<=e;)n++;return(n<0?t[0]:t[n]).text}const zT=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],BT=zT.length;function VT(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*(BT-1));o+=zT[t]}return o}function HT(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 UT=li(),WT=[...yi];function GT(){return{basename:{fn:e=>l(e),argTypes:[`string`]},dirname:{fn:e=>u(e),argTypes:[`string`]},abbreviatePath:{fn:e=>FT(e),argTypes:[`string`]},int:{fn:e=>aT(e),argTypes:[`value`]},string:{fn:e=>iT(e),argTypes:[`value`]},bool:{fn:e=>oT(e),argTypes:[`value`]},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`]},themes:{fn:()=>UT,argTypes:[]},styles:{fn:()=>WT,argTypes:[]},sparkline:{fn:(e,t)=>VT(HT(e),t),argTypes:[`string`,`int`]},cascade:{fn:(e,...t)=>RT(e,LT(t)),argTypes:[`float`,`string`]}}}function KT(e=()=>new Date){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`]},formatInteger:{fn:e=>IT(e),argTypes:[`int`]},round:{fn:e=>Math.round(e),argTypes:[`float`]},formatModelName:{fn:e=>NT(e),argTypes:[`string`]},shortenModelName:{fn:e=>PT(e),argTypes:[`string`]}}}function qT(e,t=()=>new Date){return Mu({fromString:e=>new Ar(e),toString:e=>e.plain,isT:e=>e instanceof Ar,clock:t,missingKey:`error`,funcs:{...bf(),...Am(),...op(),...Op(),...ff(t),...td(),...Pf(),...AT(),...GT(),...KT(t),...e??{}}})}function JT(e){return YT(e,new Set(e.names()),``)}function YT(e,t,n){return new Proxy(Object.create(null),{has(e,r){if(typeof r!=`string`)return!1;let i=n?`${n}.${r}`:r;if(t.has(i))return!0;let a=`${i}.`;for(let e of t)if(e.startsWith(a))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a))return e.getKind(a)===`document`?XT(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return YT(e,t,a)}})}function XT(e,t){switch(t.kind){case`ok`:return t.value;case`absent`:throw Error(`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}const ZT=/\r\n|\r|\n/g,QT=e=>X(e.replace(ZT,` `).trim());function $T(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?Q(`regex no-match`):X(n.replace(ZT,` `))}}const eE=e=>{try{return X(JSON.parse(e))}catch(e){return Q(`JSON parse failed: ${e.message}`)}};function tE(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(E(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function nE(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]}"`)}}function rE(e,t){return{where:`output of "${e}"`,read:async()=>{let n=await Ee({bin:`/bin/sh`,args:[`-c`,e],category:`user-shell`,signal:t});if(!n.ok&&n.reason===`aborted`)throw t.reason;return n.ok?X(n.stdout):Q(`shell "${e}" ${n.exitCode===null?[n.reason,n.error].filter(e=>e!==void 0).join(`: `):`exited with code ${n.exitCode}`}`)}}}function iE(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await ie(e,{encoding:`utf8`,signal:n});return X(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return Q(`file unreadable: ${e}`)}}}}function aE(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?Q(`${r.reason} in ${n}`):r}const oE=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],sE=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],cE=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],lE=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function uE(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>oE[e.getMonth()]],[`Monday`,e=>cE[e.getDay()]],[`Jan`,e=>sE[e.getMonth()]],[`Mon`,e=>lE[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 dE={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function fE(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=dE[t];try{return gE(r,e)}catch{return _E(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return bb(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return bb(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return bb(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return bb(e.stashCount,0)}}var pE=class{watchers=new Map;subscribe(e,t){let n=this.watchers.get(e);if(!n){let t=new Set,r;try{r=s(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}},mE=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:se(()=>{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&&(oe(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())oe(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function hE(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function gE(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`?iT(e):t===`number`?aT(e):oT(e)}function _E(e){return e===`number`?0:e===`boolean`?!1:``}var vE=class{inputMetas=new Map;lastErrors=new Map;watchMgr=new pE;ttlMgr=new mE;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new OC;abort=new AbortController;engine=qT();gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new FC({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,rT(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){this.declareSource(e,rE(t,this.abort.signal),tE(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,iE(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,QT,t.default,n);case`regex`:return this.scalarPublisher(e,$T(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=aE(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,bb(a,i))}}documentPublisher(e,t,n){let r=t===void 0?Z:X(t);return this.store.defineDocument(e,r),i=>{let a=aE(i,eE,n);this.noteOutcome(e,a),this.store.setDocument(e,a.kind===`ok`||t===void 0?a:r)}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.store.defineComputed(e,`string`,t=>{let i=JT(this.store);try{let t=r.evaluate(i).map(e=>e.plain).join(``);return this.lastErrors.delete(e),t}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n.varDefault===void 0)throw Error(`variable "${e}": ${r}`);return n.varDefault}});try{this.store.read(e)}catch{}}declareTime(e,t){let n=t.ttlMs??1e3;this.store.defineBox(e,`string`,(e=>{try{return uE(t.format,e)}catch{return this.stringInitial(t.varDefault)}})(new Date));let r=this.ttlMgr.subscribe(n,()=>{try{this.store.setBox(e,uE(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=dE[t.field],r=t.varDefault===void 0?_E(n):gE(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,fE(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(`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=hE(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,gE(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(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let e=this.watchMgr.subscribe(t.path,n);this.cleanups.push(e);break}case`key`:{let e=this.engine.parse(t.template),r=(0,tT.reaction)(()=>{let t=JT(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,tT.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,gE(this.defaultEmptyValue,t))}catch{this.store.setBox(e,_E(t))}}defaultFor(e){try{return gE(this.defaultEmptyValue,e)}catch{return _E(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})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function yE(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}function bE(e,t){let n=Ar.fromFragments(e);return n.end=``,n.noWrap=!0,t!==void 0&&!t.isNull&&(n.style=t),n}function xE(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:n.truncateMarker}):e.cellLength<t&&e.align(n.justify,t)}const SE=Symbol(`cc-candybar.fillDemand`);function CE(e,t){return e[SE]=t,e}function wE(e){return e[SE]}function TE(e,t){let{width:n,justify:r,truncate:i,truncateMarker:a=`…`,baseStyle:o,padding:s}=t;if(e.length===0)return[];let c=bE(e,o).pad(s);if(n===`auto`)return[c];let l={justify:r,truncate:i,truncateMarker:a};return n===`fill`?[CE(c,l)]:(xE(c,n,l),[c])}const EE=/\x1b\[[0-9;]*m|\x1b\]8;;[^\x07\x1b]*(?:\x1b\\|\x07)/g;function DE(e){return k(e.replace(EE,``))}function OE(e,t){let n=[];for(let t of e){let e=wE(t);e!==void 0&&n.push({cell:t,how:e})}if(n.length===0||!Number.isFinite(t.width))return e;let r=Fx(e,t).split(`
|
|
179
|
-
`);if(r.length>1)return e;let i=Math.max(0,t.width-DE(r[0]??``)),a=Math.floor(i/n.length),o=i-a*n.length;return n.forEach(({cell:e,how:t},r)=>{let i=a+(r===n.length-1?o:0);xE(e,e.cellLength+i,t)}),e}function kE(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=AE(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=AE([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function AE(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>jE(e,t)):e,r=Ar.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 jE(e,t){let n=e.copy();return n.style=t.add(e.style),n}var ME=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function NE(e,t,n,r,i,a,o,s,c){let l={segName:t,palette:n,disclosure:r,bg:void 0};e.current=l;let u=PE(o,c),d=u===void 0?i:FE(n,u,`bg`);l.bg=d;let f=PE(s,c),p=f===void 0?a(d):FE(n,f,`fg`);return new H({bgcolor:N.fromRgba(d),color:p===void 0?void 0:N.fromRgba(p)})}function PE(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function FE(e,t,n){try{return kn(e,t)}catch(e){throw e instanceof En?new ME(t,n,e.message):e}}const IE=new Map([[`palette`,`theme.effective`],[`preset`,`preset.effective`],[`look`,`look.effective`],[`style`,`style.effective`],[`charset`,`charset.effective`],[`colorCompatibility`,`colorCompatibility.effective`],[`autoWrap`,`autoWrap.effective`],[`padding`,`padding.effective`]]);function LE(e,t,n,r){let i=new Map;for(let[a,o]of Object.entries(t))i.set(a,RE(e,a,o,n,r));return i}function RE(e,t,n,r,i){if(Fg(n)){let[a,o]=Ig(n);return zE(r.get(n.persistWhen)??n.persistWhen,n.set,RE(e,t,a,r,i),RE(e,t,o,r,i))}if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=Y_(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=IE.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=Y_(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=Y_(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}return`copy`in n?{kind:`copy`,text:VE(e,n.copy,t)}:`open`in n?{kind:`open`,target:VE(e,n.open,t)}:`reset`in n?{kind:`reset`,key:n.reset}:`doctor`in n?n.doctor===`run`?{kind:`doctor-run`}:{kind:`doctor-fix`,check:n.check}:`undo`in n?{kind:`undo`}:{kind:`redo`}}function zE(e,t,n,r){return{kind:`dual`,selector:e,session:`stateVar`in n&&`stateVar`in r?{...n,stateVar:r.stateVar}:n,durable:r,sessionKey:t}}function BE(e,t){return e.kind===`dual`?Oi(HE(t,e.selector))===!0?e.durable:e.session:e}function VE(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function HE(e,t){return e.has(t)?iT(e.read(t)):``}function UE(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function WE(e,t,n,r){let i=new Ar(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.noWrap=!0,i.end=``,i}function GE(e,t){return Math.max(e.members.indexOf(HE(t,e.stateVar)),0)}function KE(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=HE(r,e.stateVar);return{effects:[{verb:Zy,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=HE(r,e.stateVar);return{effects:[{verb:Zy,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=HE(r,e.stateVar);return{effects:[{verb:Zy,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(GE(e,r)+1)%e.members.length];return{effects:[{verb:Zy,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Qy,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:$y,args:[UE(e.text,JT(r))]}],active:!1};case`open`:return{effects:[{verb:eb,args:[UE(e.target,JT(r))]}],active:!1};case`persist-literal`:{let t=HE(r,e.stateVar);return{effects:[{verb:ib,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=HE(r,e.stateVar);return{effects:[{verb:ib,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(GE(e,r)+1)%e.members.length];return{effects:[{verb:ib,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:ab,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:ob,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:cb,args:[i]}],active:!1};case`redo`:return{effects:[{verb:lb,args:[i]}],active:!1};case`doctor-run`:return{effects:[{verb:db,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:fb,args:[i,e.check]}],active:!1};case`layout-op`:return{effects:[{verb:sb,args:[i,e.key,ih(e.op)]}],active:!1};case`dual`:{let a=BE(e,r),{effects:o,active:s}=KE(a,t,n,r,i);return a===e.durable?{effects:o.map(t=>({...t,args:[...t.args,e.sessionKey]})),active:s}:{effects:o,active:s}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:sb,args:[i,e.key,ih(r)]}],active:!1}}}}function qE(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:mc(`action "${e}"`,n,t.members.length,GE(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 JE(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}=qE(e,BE(r,i),t,i),{effects:s,active:c}=KE(r,a,o,i,HE(i,`session.id`));return WE(a,hb(s),c)}function YE(e){return{action:{fn:(t,...n)=>JE(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function XE(e,t){return new H({bgcolor:N.fromRgba(t),color:N.fromRgba(ec(e,t))})}function ZE(e,t){return XE(e.palette,oc(e.palette,e.disclosure,[t]))}function QE(e,t,n,r){return r===void 0?n=>ZE(e,{...n,distribution:t}):(e,t)=>$E(r(t,n))}function $E(e){let t=Xs(e,`background`);return new H({bgcolor:N.fromRgba(t),color:N.fromRgba(zn(Xs(e,`primary`),t,4.5))})}function eD(){return{current:null}}function tD(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function nD(e){return new Ar(e).cellLength}function rD(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 iD(e,t){let n=[];for(let t of e)n.length>0&&n.push(new Ar(` `)),n.push(t);let r=Ar.fromFragments(n);return r.noWrap=t,r.end=``,r}function aD(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 oD(e,t){let n=e.compiled.get(t),r=n&&BE(n,e.store);if(!r||r.kind!==`set-option`&&r.kind!==`persist-option`&&r.kind!==`layout-op-option`)throw Error(`picker references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${r?`a ${r.kind} action`:`no such action`}`);return r}function sD(e,t,n,r,i,a,o){let s=oD(a,e),c=a.compiled.get(e),l=a.store,u=HE(l,`session.id`),d=`stateVar`in s?HE(l,s.stateVar):void 0,f=s.options.map(nD),p=i?Math.max(1,aT(l.read(`term.cols`))-Px(a.stripStyle)-2*a.padding):1/0,m=nD(`✕`)+1,h=nD(`←`)+1+nD(`→`)+1,g=rD(f,p,m),_=g.length>1?rD(f,p,m+h):g,v=parseInt(HE(l,t.stateVar),10),y=Number.isInteger(v)?Math.max(0,Math.min(v,_.length-1)):0,b=_[y]??[],x=e=>hb([{verb:Zy,args:[u,t.key,String(e)]}]),S=n.flatMap(([e,t])=>[e,t]),C=hb([{verb:Zy,args:[u,...S]}]),ee=r?[{verb:Zy,args:[u,...S]}]:[],te=e=>{let{effects:t}=KE(c,e,e,l,u),n=t.length===1?t[0]:void 0;return n?.verb===`set-state`?hb([{verb:Zy,args:[...n.args,...r?S:[]]}]):hb([...t,...ee])},ne=[WE(`✕`,C,!1)];y>0&&ne.push(WE(`←`,x(y-1),!1));for(let e of b){let t=s.options[e];ne.push(WE(t,te(t),t===d,o({index:e,count:s.options.length},t)))}return y<_.length-1&&ne.push(WE(`→`,x(y+1),!1)),iD(ne,i)}function cD(e,t){return{picker:{fn:(n,r,i,a)=>{let o=aD(e,r,`set-int`,`an int action ({ set, int: true })`);return sD(n,{key:o.key,stateVar:o.stateVar},[[o.key,`-1`]],i===!0,a===!0,e,QE(tD(t,`{{ picker }}`),Ws(void 0),e.basePalette,oD(e,n).paletteOf))},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const lD=Symbol(`cc-candybar.menuDrop`);function uD(e){return e.flatMap(e=>e[lD]??[])}function dD(e,t,n,r){let i=r.activeSegment.current;if(i===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let a=r.action,o=Mm(i.segName,e,n.key),s=Fm(o),c=jm(e),l=HE(a.store,o)===c,u=HE(a.store,`session.id`),d=l?fc:c,f=WE(mc(`{{ menu "${e}" }}`,t,2,+!!l),hb([{verb:Zy,args:[u,o,d,s,`0`]}]),!1);return f[lD]=l?[sD(e,{key:s,stateVar:s},[[o,fc],[s,`0`]],n.closeOnPick,n.paged,a,QE(i,n.distribution,a.basePalette,oD(a,e).paletteOf))]:[],f}const fD=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function pD(e,t){let n=t[t.length-1],r=fD(n)?n:void 0,i=r===void 0?t:t.slice(0,-1),a=i.findIndex(e=>typeof e!=`string`);if(a!==-1)throw Error(`{{ menu "${e}" }} display #${a+1} is not text (${JSON.stringify(i[a])}) — a menu binds its trigger text, then an optional trailing (dict …) of options`);return{displays:i,options:zm(r??{})}}function mD(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=pD(t,n);return dD(t,r,i,e)},argTypes:[`string`,`value`],returnType:`T`}}}function hD(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=gD(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new Ar(t?i:a,{style:l===void 0?void 0:new H({color:l})}))}let l=Ar.fromFragments(c);return l.end=``,l.noWrap=!0,l}function gD(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.min(n,Math.max(0,Math.round(e/t*n)))}function _D(e){let t={fn:(()=>{let t=tD(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],returnType:`string`},n=kT(()=>tD(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),r={fn:((e,t,r,i,a,o,...s)=>hD({value:e,max:t,width:r,filled:i,empty:a,colourAt:o===void 0||s.length===0?void 0:e=>String(n.ramp.fn(e,o,...vD(s)))})),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`,`string`],returnType:`T`};return{...n,bgOf:t,gauge:r}}function vD(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function yD(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
179
|
+
`);if(r.length>1)return e;let i=Math.max(0,t.width-DE(r[0]??``)),a=Math.floor(i/n.length),o=i-a*n.length;return n.forEach(({cell:e,how:t},r)=>{let i=a+(r===n.length-1?o:0);xE(e,e.cellLength+i,t)}),e}function kE(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=AE(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e)if(a.style.link){i();let e=AE([a],t);e.plain.length>0&&n.push(e)}else r.push(a);return i(),n}function AE(e,t){let n=t!==void 0&&!t.isNull?e.map(e=>jE(e,t)):e,r=Ar.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 jE(e,t){let n=e.copy();return n.style=t.add(e.style),n}var ME=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function NE(e,t,n,r,i,a,o,s,c){let l={segName:t,palette:n,disclosure:r,bg:void 0};e.current=l;let u=PE(o,c),d=u===void 0?i:FE(n,u,`bg`);l.bg=d;let f=PE(s,c),p=f===void 0?a(d):FE(n,f,`fg`);return new H({bgcolor:N.fromRgba(d),color:p===void 0?void 0:N.fromRgba(p)})}function PE(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function FE(e,t,n){try{return kn(e,t)}catch(e){throw e instanceof En?new ME(t,n,e.message):e}}const IE=new Map([[`palette`,`theme.effective`],[`preset`,`preset.effective`],[`look`,`look.effective`],[`style`,`style.effective`],[`charset`,`charset.effective`],[`colorCompatibility`,`colorCompatibility.effective`],[`autoWrap`,`autoWrap.effective`],[`padding`,`padding.effective`]]);function LE(e,t,n,r){let i=new Map;for(let[a,o]of Object.entries(t))i.set(a,RE(e,a,o,n,r));return i}function RE(e,t,n,r,i){if(Fg(n)){let[a,o]=Ig(n);return zE(r.get(n.persistWhen)??n.persistWhen,n.set,RE(e,t,a,r,i),RE(e,t,o,r,i))}if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=Y_(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=IE.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=Y_(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=Y_(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}return`copy`in n?{kind:`copy`,text:VE(e,n.copy,t)}:`open`in n?{kind:`open`,target:VE(e,n.open,t)}:`reset`in n?{kind:`reset`,key:n.reset}:`doctor`in n?n.doctor===`run`?{kind:`doctor-run`}:{kind:`doctor-fix`,check:n.check}:`undo`in n?{kind:`undo`}:{kind:`redo`}}function zE(e,t,n,r){return{kind:`dual`,selector:e,session:`stateVar`in n&&`stateVar`in r?{...n,stateVar:r.stateVar}:n,durable:r,sessionKey:t}}function BE(e,t){return e.kind===`dual`?Oi(HE(t,e.selector))===!0?e.durable:e.session:e}function VE(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function HE(e,t){return e.has(t)?iT(e.read(t)):``}function UE(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function WE(e,t,n,r){let i=new Ar(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.noWrap=!0,i.end=``,i}function GE(e,t){return Math.max(e.members.indexOf(HE(t,e.stateVar)),0)}function KE(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=HE(r,e.stateVar);return{effects:[{verb:Zy,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=HE(r,e.stateVar);return{effects:[{verb:Zy,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=HE(r,e.stateVar);return{effects:[{verb:Zy,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(GE(e,r)+1)%e.members.length];return{effects:[{verb:Zy,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Qy,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:$y,args:[UE(e.text,JT(r))]}],active:!1};case`open`:return{effects:[{verb:eb,args:[UE(e.target,JT(r))]}],active:!1};case`persist-literal`:{let t=HE(r,e.stateVar);return{effects:[{verb:ib,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=HE(r,e.stateVar);return{effects:[{verb:ib,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(GE(e,r)+1)%e.members.length];return{effects:[{verb:ib,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:ab,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:ob,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:cb,args:[i]}],active:!1};case`redo`:return{effects:[{verb:lb,args:[i]}],active:!1};case`doctor-run`:return{effects:[{verb:db,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:fb,args:[i,e.check]}],active:!1};case`layout-op`:return{effects:[{verb:sb,args:[i,e.key,ih(e.op)]}],active:!1};case`dual`:{let a=BE(e,r),{effects:o,active:s}=KE(a,t,n,r,i);return a===e.durable?{effects:o.map(t=>({...t,args:[...t.args,e.sessionKey]})),active:s}:{effects:o,active:s}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:sb,args:[i,e.key,ih(r)]}],active:!1}}}}function qE(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:mc(`action "${e}"`,n,t.members.length,GE(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 JE(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}=qE(e,BE(r,i),t,i),{effects:s,active:c}=KE(r,a,o,i,HE(i,`session.id`));return WE(a,hb(s),c)}function YE(e){return{action:{fn:(t,...n)=>JE(t,n,e),argTypes:[`string`,`string`],returnType:`T`}}}function XE(e,t){return WE(`✕`,hb([{verb:Zy,args:[HE(e,`session.id`),t,fc]}]),!1)}function ZE(e,t){return new H({bgcolor:N.fromRgba(t),color:N.fromRgba(ec(e,t))})}function QE(e,t){return ZE(e.palette,oc(e.palette,e.disclosure,[t]))}function $E(e,t,n,r){return r===void 0?n=>QE(e,{...n,distribution:t}):(e,t)=>eD(r(t,n))}function eD(e){let t=Xs(e,`background`);return new H({bgcolor:N.fromRgba(t),color:N.fromRgba(zn(Xs(e,`primary`),t,4.5))})}function tD(){return{current:null}}function nD(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function rD(e){return new Ar(e).cellLength}function iD(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 aD(e,t){let n=[];for(let t of e)n.length>0&&n.push(new Ar(` `)),n.push(t);let r=Ar.fromFragments(n);return r.noWrap=t,r.end=``,r}function oD(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 sD(e,t){let n=e.compiled.get(t),r=n&&BE(n,e.store);if(!r||r.kind!==`set-option`&&r.kind!==`persist-option`&&r.kind!==`layout-op-option`)throw Error(`picker references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${r?`a ${r.kind} action`:`no such action`}`);return r}function cD(e,t,n,r,i,a,o){let s=sD(a,e),c=a.compiled.get(e),l=a.store,u=HE(l,`session.id`),d=`stateVar`in s?HE(l,s.stateVar):void 0,f=s.options.map(rD),p=i?Math.max(1,aT(l.read(`term.cols`))-Px(a.stripStyle)-2*a.padding):1/0,m=rD(`✕`)+1,h=rD(`←`)+1+rD(`→`)+1,g=iD(f,p,m),_=g.length>1?iD(f,p,m+h):g,v=parseInt(HE(l,t.stateVar),10),y=Number.isInteger(v)?Math.max(0,Math.min(v,_.length-1)):0,b=_[y]??[],x=e=>hb([{verb:Zy,args:[u,t.key,String(e)]}]),S=n.flatMap(([e,t])=>[e,t]),C=hb([{verb:Zy,args:[u,...S]}]),ee=r?[{verb:Zy,args:[u,...S]}]:[],te=e=>{let{effects:t}=KE(c,e,e,l,u),n=t.length===1?t[0]:void 0;return n?.verb===`set-state`?hb([{verb:Zy,args:[...n.args,...r?S:[]]}]):hb([...t,...ee])},ne=[WE(`✕`,C,!1)];y>0&&ne.push(WE(`←`,x(y-1),!1));for(let e of b){let t=s.options[e];ne.push(WE(t,te(t),t===d,o({index:e,count:s.options.length},t)))}return y<_.length-1&&ne.push(WE(`→`,x(y+1),!1)),aD(ne,i)}function lD(e,t){return{picker:{fn:(n,r,i,a)=>{let o=oD(e,r,`set-int`,`an int action ({ set, int: true })`);return cD(n,{key:o.key,stateVar:o.stateVar},[[o.key,`-1`]],i===!0,a===!0,e,$E(nD(t,`{{ picker }}`),Ws(void 0),e.basePalette,sD(e,n).paletteOf))},argTypes:[`string`,`string`,`bool`,`bool`],returnType:`T`}}}const uD=Symbol(`cc-candybar.menuDrop`);function dD(e){return e.flatMap(e=>e[uD]??[])}function fD(e,t,n,r){let i=r.activeSegment.current;if(i===null)throw Error(`{{ menu }} rendered with no active segment placement — the render walk must publish one before evaluating a segment template`);let a=r.action,o=Mm(i.segName,e,n.key),s=Fm(o),c=jm(e),l=HE(a.store,o)===c,u=HE(a.store,`session.id`),d=l?fc:c,f=WE(mc(`{{ menu "${e}" }}`,t,2,+!!l),hb([{verb:Zy,args:[u,o,d,s,`0`]}]),!1);return f[uD]=l?[cD(e,{key:s,stateVar:s},[[o,fc],[s,`0`]],n.closeOnPick,n.paged,a,$E(i,n.distribution,a.basePalette,sD(a,e).paletteOf))]:[],f}const pD=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function mD(e,t){let n=t[t.length-1],r=pD(n)?n:void 0,i=r===void 0?t:t.slice(0,-1),a=i.findIndex(e=>typeof e!=`string`);if(a!==-1)throw Error(`{{ menu "${e}" }} display #${a+1} is not text (${JSON.stringify(i[a])}) — a menu binds its trigger text, then an optional trailing (dict …) of options`);return{displays:i,options:zm(r??{})}}function hD(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=mD(t,n);return fD(t,r,i,e)},argTypes:[`string`,`value`],returnType:`T`}}}function gD(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=_D(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new Ar(t?i:a,{style:l===void 0?void 0:new H({color:l})}))}let l=Ar.fromFragments(c);return l.end=``,l.noWrap=!0,l}function _D(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.min(n,Math.max(0,Math.round(e/t*n)))}function vD(e){let t={fn:(()=>{let t=nD(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],returnType:`string`},n=kT(()=>nD(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),r={fn:((e,t,r,i,a,o,...s)=>gD({value:e,max:t,width:r,filled:i,empty:a,colourAt:o===void 0||s.length===0?void 0:e=>String(n.ramp.fn(e,o,...yD(s)))})),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`,`string`],returnType:`T`};return{...n,bgOf:t,gauge:r}}function yD(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function bD(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
180
180
|
`)){n.push(r);continue}let e=r.split(`
|
|
181
|
-
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function
|
|
182
|
-
`)}var
|
|
183
|
-
`)||null}var GD=class{entries=new Map;deps;maxEntries;observers;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}getOrCreate(e,t,n){let r=BD(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.loadFromDisk(e,t,n),o={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:a.error,lastWarning:a.warning,state:a.state??this.buildState(t,null,[]),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;n.state.registry.dispose(),n.state.validatorDisposers.forEach(e=>e()),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a.resolvedPath),this.observers.onReload?.(o),o}reloadInto(e){let t=this.loadFromDisk(e.projectDir,e.cwd,e.configFile);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(e.state.registry.dispose(),e.state.validatorDisposers.forEach(e=>e()),e.state=t.state),this.refreshWatcher(e,t.resolvedPath),this.observers.onReload?.(e)}loadFromDisk(e,t,n){let r=Dv(e,t,n),i=r.kind===`file`?r.path:null,a=[jv(e,t),kv(r)],o;try{o=this.buildState(t,i,a)}catch(e){return e instanceof _a&&a.push(...e.warnings),{resolvedPath:i,warning:WD(a),state:null,error:e instanceof _a||e instanceof Error?e.message:String(e)}}return{resolvedPath:i,warning:WD(a),state:o,error:null}}buildState(e,t,n){let{config:r,raw:i,source:a,warnings:o}=Mv(t,Qw);n.push(...o);let s=Fv(r,t??`<default>`,a),c=new zD,l=new vE(c,s.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),u,d=[];try{u=DD(s,l,{cwd:e}),n.push(...u.loadWarnings);for(let{key:e,spec:t}of VS(s))d.push(PS(e,t));for(let{key:e,spec:t}of CS(s))d.push(wS(e,t))}catch(e){for(let e of d)e();throw l.dispose(),e}return{config:s,store:c,registry:l,compiled:u,neededInputPaths:Nw(s),lastRenderCellsBySegment:new Map,validatorDisposers:d,authoredRoots:VD(r,i)}}refreshWatcher(e,t){e.configFilePath=t;let n=UD(e,t),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){Y(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const KD=16384;var qD=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<KD){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%KD}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:vb,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,renderCache:{size:e.renderCacheSize},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null}}};const JD={load:()=>({}),save:()=>{},flush:()=>{}};function YD(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var XD=class{sessions;storage;atom=(0,tT.createAtom)(`SessionState`);constructor(e=JD,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=YD(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,tT.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,tT.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,tT.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 ZD=(e,t)=>E(t);function QD(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 $D=class{timer=null;pending=null;constructor(e,t=500,n=ZD){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=r.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return QD(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{r.mkdirSync(c.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;r.writeFileSync(t,JSON.stringify(e),{mode:384}),r.chmodSync(t,384),r.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const eO={default_bg:`string`,default_fg:`string`,default_empty_value:`string`,default_separator:`string`,default_truncate_marker:`string`,palette:`string`,look:`string`,preset:`string`,style:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,updateNotice:`boolean`,colorCompatibility:`string`},tO=new Set([`1`,`true`]),nO=new Set([`0`,`false`,``]);function rO(e,t){let n=OO(e),r=n.scope===`globals`?eO[n.field]:`string`;if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if(tO.has(t))return`true`;if(nO.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function iO(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function aO(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(c.dirname(e),{recursive:!0}),Ae(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function oO(e){return/^\s*$/.test(e)?null:Li(e)}function sO(e,t){return e!==null&&zi(e,t)!==void 0}function cO(e){if(e.kind===`segment`)return e.when===void 0?e.name:{seg:e.name,when:e.when};if(e.kind===`container`){let{kind:t,direction:n,children:r,...i}=e;return{[n===`horizontal`?`h`:`v`]:r.map(cO),...i}}return e}function lO(e){if(!fo(e))return cO(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,cO(t)])),...n}}const uO=Xw,dO=uO.segments,fO=uO.presets,pO=uO.root;function mO(e,t,n,r){if(!sO(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function hO(e,t){let n=vh(t);return t.scope===`segment-palette`&&mO(e,[`segments`,t.segment],dO[t.segment],n.join(`.`)),n}function gO(e){return Li(Gi(e))}function _O(){return Object.entries(pO.rows).map(([e,t])=>{let n=cO(t);return{path:[`root`],fragment:gO({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function vO(e,t){let n=e===null?void 0:zi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function yO(e,t){if(t===void 0)return null;let n=lO(t);return{path:e,fragment:gO(n),unit:{path:e,value:n}}}function bO(e,t){let n=[`presets`,t],r=[...n,`root`],i=fO[t];mO(e,n,i,r.join(`.`));let a=vO(e,r)??yO(r,i?.root);return a!==null&&da(a.fragment)?a:null}function xO(e,t){let n=ua(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function SO(e,t){return[..._O(),vO(e,[`root`]),bO(e,t)].filter(e=>e!==null).reduce(xO,new Map)}function CO(e,t,n){for(let{node:r,...i}of SO(e,t).values())if(pa(r,n))return i;throw new $(`${wO(e,t).join(`.`)} holds no segment "${n}" — the bar you clicked is stale; it reloads on the next render`)}function wO(e,t){return bO(e,t)?.path??[`root`]}function TO(e,t){return t.scope===`preset-root`?wO(e,t.preset):vh(t)}function EO(e,{unit:t}){return t===null?e:aa(e,t.path,Gi(t.value),Ui)}function DO(e){let t=_h(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function OO(e){let t=DO(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function kO(e,t){let n=OO(t),r=oO(iO(e)??``),i=r===null?void 0:zi(r,vh(n));return i!==void 0&&`value`in i?i.value:void 0}function AO(e,t,n,r){let i=OO(n),a=iO(t);BO(e,t,{before:a,after:aa(a??``,hO(oO(a??``),i),rO(n,r),Ui)})}function jO(e,t,n){let r=DO(n),i=iO(t);if(i===null)return;let a=oa(i,TO(oO(i),r));a!==i&&BO(e,t,{before:i,after:a})}function MO(e,t,n,r){let i=DO(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=iO(t),o=r.op===`remove`?r.target:r.anchor,s=CO(oO(a??``),i.preset,o),c=EO(a??``,s),l=r.op===`remove`?ha(c,s.path,r.target):ga(c,s.path,r.segment,r.anchor,r.relation);if(l===null)throw new $(`${s.path.join(`.`)} in ${t} has no segment "${o}" — the bar you clicked is stale; it reloads on the next render`);BO(e,t,{before:a,after:l})}const NO={past:[],future:[]};function PO(e){if(typeof e!=`object`||!e)return!1;let t=e;return(t.before===null||typeof t.before==`string`)&&typeof t.after==`string`}function FO(e){if(typeof e!=`object`||!e)return!1;let t=e;return Array.isArray(t.past)&&t.past.every(PO)&&Array.isArray(t.future)&&t.future.every(PO)}function IO(e){let t;try{t=r.readFileSync(e.historyPath,`utf8`)}catch(t){let n=t.code;return n!==`ENOENT`&&e.logger(`warn`,`config-edit-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(t);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(FO))return e}catch{}return e.logger(`warn`,`config-edit-history load: unexpected shape, starting empty`),{}}function LO(e,t){try{r.mkdirSync(c.dirname(e.historyPath),{recursive:!0}),Ae(e.historyPath,JSON.stringify(t),384)}catch(t){let n=`config-edit-history write failed: ${t.message}`;throw e.logger(`error`,n),Error(n)}}function RO(e,t){let n=[...e,t];return n.length>50?n.slice(-50):n}function zO(e,t,n,r,i){aO(t,n,e.logger);try{LO(e,r)}catch(e){throw Error(`${i} landed in ${t} but recording it failed — it is not undoable: ${e.message}`)}}function BO(e,t,n){let r=IO(e),{past:i}=r[t]??NO;zO(e,t,n.after,{...r,[t]:{past:RO(i,n),future:[]}},`edit`)}function VO(e,t){let n=IO(e),{past:r,future:i}=n[t]??NO,a=r[r.length-1];return a===void 0?null:(UO(t,a.after,`undo`),zO(e,t,a.before,{...n,[t]:{past:r.slice(0,-1),future:RO(i,a)}},`undo`),a)}function HO(e,t){let n=IO(e),{past:r,future:i}=n[t]??NO,a=i[i.length-1];return a===void 0?null:(UO(t,a.before,`redo`),zO(e,t,a.after,{...n,[t]:{past:RO(r,a),future:i.slice(0,-1)}},`redo`),a)}function UO(e,t,n){if(iO(e)!==t)throw new $(`${n}: ${e} has changed since that edit — refusing to overwrite it`)}function WO(e){let t=De({bin:`tmux`,args:[`-S`,e.socket,`display`,`-p`,`-t`,e.pane,`#{client_termfeatures}`],timeoutMs:2e3,category:`doctor.tmux`});return t.ok?{kind:`ok`,value:t.stdout.trim().split(`,`).filter(e=>e!==``)}:{kind:`failed`,reason:`tmux display -p failed (${t.error??[t.reason,t.stderr.trim()].filter(e=>e!==``).join(`: `)})`}}function GO(){return{probeTmux:WO,claudeSettingsPath:yb()}}function KO(e){return r.existsSync(e.claudeSettingsPath)?r.readFileSync(e.claudeSettingsPath,`utf8`):``}function qO(e){if(/^\s*$/.test(e))return{};let t=Wi.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`not a JSON object`);let n=t.env;if(n===void 0)return{};if(typeof n!=`object`||!n||Array.isArray(n))throw Error("`env` is not an object");return n}function JO(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function YO(e){try{return qO(KO(e))}catch(t){throw Error(`cannot read ${e.claudeSettingsPath}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}function XO(e,t){return{tmux:JO(e,t),claudeSettingsEnv:YO(e)}}function ZO(e,t,n){switch(t.kind){case`claude-settings-env`:{let i=aa(KO(e),[`env`,t.name],JSON.stringify(t.value),Wi);return r.mkdirSync(c.dirname(e.claudeSettingsPath),{recursive:!0}),Ae(e.claudeSettingsPath,i),{...n,claudeSettingsEnv:YO(e)}}default:return t.kind}}function QO(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function $O(e){return ek(()=>decodeURIComponent(e))}function ek(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function tk(e,t){let n=De({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 nk=(e,t)=>tk($O(e),t),rk=(e,t)=>{let n=De({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,$O(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},ik=(e,t)=>tk($O(e),t),ak=(e,t)=>tk($O(e),t),ok=(e,t)=>{let n=QO($O(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},sk=(e,t)=>{let[n=``,...r]=ek(()=>mb(e)),i=QO(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${NS().join(`, `)})`);if(r.length%2!=0)throw new $(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${NS().join(`, `)})`);let a=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new $(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=FS(t,n);if(!i.ok)throw new $(`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})`)},ck=/^-?\d+$/;function lk(e,t,n){return e>n?t:e<t?n:e}function uk(e,t){if(!e)return null;if(!NS().includes(e))throw new $(`${t}: unknown session key "${e}" to release (have: ${NS().join(`, `)})`);return e}function dk(e,t,n,r){e!==null&&(n.sessionState.clear(t,e),n.dlog(`info`,`${r}: released session key ${e} (session=${t})`))}const fk=(e,t)=>{let[n=``,r=``,i=``]=ek(()=>mb(e)),a=QO(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!ck.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=IS(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${NS().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&ck.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=lk(l+o,s.min,s.max),d=FS(r,String(u));if(!d.ok)throw new $(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)},pk=`render-origin`;function mk(e){return JSON.stringify(e)}function hk(e){let t;try{t=JSON.parse(e)}catch{throw new $(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new $(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new $(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function gk(e,t){let n=e.sessionState.get(t,pk);if(n===null)throw new $(`session ${t} has not rendered yet — no config file to write`);let r=hk(n);return Ov(r.projectDir,r.cwd,r.configFile??void 0)}function _k(e){return{historyPath:Be(),logger:e.dlog}}const vk=(e,t)=>{let[n=``,r=``,i=``,a=``]=ek(()=>mb(e)),o=QO(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${hS().join(`, `)})`);let s=gS(r,i);if(!s.ok)throw new $(`set-config: ${s.reason}`);let c=uk(a,`set-config`),l=gk(t,o);AO(_k(t),l,r,s.value),t.dlog(`info`,`set-config: ${r}=${s.value} → ${l} (session=${o})`),dk(c,o,t,`set-config`)},yk=(e,t)=>{let[n=``,r=``,i=``,a=``]=ek(()=>mb(e)),o=QO(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!ck.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let s=parseInt(i,10),c=uk(a,`step-config`),l=_S(r);if(!l)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${hS().join(`, `)})`);let u=gk(t,o),d=kO(u,r),f=typeof d==`number`?Math.max(l.min,Math.min(l.max,d)):l.seed,p=lk(f+s,l.min,l.max),m=gS(r,String(p));if(!m.ok)throw new $(`step-config: ${m.reason}`);AO(_k(t),u,r,m.value),t.dlog(`info`,`step-config: ${r} ${f}→${m.value} (by ${s}) → ${u} (session=${o})`),dk(c,o,t,`step-config`)},bk=(e,t)=>{let[n=``,r=``]=ek(()=>mb(e)),i=QO(n);if(!r||!hS().includes(r))throw new $(`reset-config: unknown config key "${r}" (have: ${hS().join(`, `)})`);let a=gk(t,i);jO(_k(t),a,r),t.dlog(`info`,`reset-config: ${r} ← ${a} (session=${i})`)},xk=(e,t)=>{let[n=``,r=``,i=``]=ek(()=>mb(e)),a=QO(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${hS().join(`, `)})`);let o=gS(r,i);if(!o.ok)throw new $(`apply-layout-op: ${o.reason}`);let s=ah(o.value);if(s===null)throw new $(`apply-layout-op: "${o.value}" is not a layout op token`);let c=gk(t,a);MO(_k(t),c,r,s),t.dlog(`info`,`apply-layout-op: ${r} ${o.value} → ${c} (session=${a})`)},Sk=(e,t)=>{let[n=``]=ek(()=>mb(e)),r=QO(n),i=gk(t,r);if(VO(_k(t),i)===null)throw new $(`undo: history is empty, nothing to undo`);t.dlog(`info`,`undo: ${i} (session=${r})`)},Ck=(e,t)=>{let[n=``]=ek(()=>mb(e)),r=QO(n),i=gk(t,r);if(HO(_k(t),i)===null)throw new $(`redo: nothing to redo`);t.dlog(`info`,`redo: ${i} (session=${r})`)},wk=(e,t)=>{QO($O(e)),t.applyUpdate()},Tk=`client-hints`;function Ek(e,t){let n=e.sessionState.get(t,Tk);if(n===null)throw new $(`session ${t} has not rendered yet — no client facts to diagnose`);let r;try{r=JSON.parse(n)}catch{throw new $(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new $(`client hints record is not an object: ${n}`);return Hv(r)}function Dk(e,t,n){let r=Hh(n);e.sessionState.setBatch(t,Gh(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed`}`).join(` `)} (session=${t})`)}const Ok=(e,t)=>{let n=QO($O(e));Dk(t,n,XO(t.doctor,Ek(t,n).tmux))},kk=(e,t)=>{let[n=``,r=``]=ek(()=>mb(e)),i=QO(n),a=Uh(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=XO(t.doctor,Ek(t,i).tmux),s=a.probe(o);if(s.ok||s.fix===void 0)throw new $(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=ZO(t.doctor,s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.name}=${s.fix.value} (session=${i})`),Dk(t,i,c)},Ak=`config-override`,jk=new Map([[$y,nk],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=QO(ek(()=>decodeURIComponent(e.slice(0,n)))),i=ek(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new $(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new $(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,Ak),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,Ak,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[eb,rk],[Zy,sk],[Qy,fk],[ib,vk],[ab,yk],[ob,bk],[sb,xk],[cb,Sk],[lb,Ck],[nb,ik],[rb,ak],[tb,ok],[ub,wk],[db,Ok],[fb,kk]]),Mk=new Set([Zy,Qy,ib,ab,ob,sb,cb,lb,tb,ub,db,fb]),Nk=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of gb(e)){if(!i&&Mk.has(a)){let e=mb(o);e.length>0&&e[0]&&(i=e[0])}let e=jk.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof $||(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(`
|
|
184
|
-
`));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},Pk=new Map([...jk,[Xy,Nk]]);Object.freeze([...Pk.keys()]);const Fk=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`]),Ik=[[`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 Lk(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of Ik){let i=zk(n,e);if(i==null)t.missingRequired.push(e);else{let n=Rk(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))Fk.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function Rk(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function zk(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 Bk(e,t){switch(e){case`vars`:return{what:e,vars:Vk(t)};case`segments`:return{what:e,segments:Kk(t)};case`config`:return{what:e,config:Yk(t)}}}function Vk(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=Wk(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,...Hk(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:Uk(r.lastUpdatedMs())})}return o}function Hk(e){if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function Uk(e){return e===null?null:Math.max(0,Date.now()-e)}function Wk(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,Gk(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}`,Gk(i));return t}function Gk(e){return e.kind}function Kk(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=qk(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,description:t.description??null,template:t.template,referencedVars:Jk(t.template,i),lastRender:r.get(e)??null})}return o}function qk(e){let t=[],n=new Set;for(let r of wa(ho(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 Jk(e,t){let n=new Set;for(let r of $_(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 Yk(e){return e===null?null:e.config}const Xk=[`vars`,`segments`,`config`];function Zk(e){return typeof e==`string`&&Xk.includes(e)}function Qk(e){return Math.max(1,e-2)}var $k=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 E(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);E(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t){try{E(`Calculating context tokens from transcript: ${e}`);let n=await nw(e);if(n.length===0)return E(`No entries in transcript`),Z;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,E(`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 E(`Most recent main chain context: ${n} tokens (limit: ${t})`),X({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return E(`No main chain entries with usage data found`),Z}catch(e){return Q(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return X(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}},eA=class{states=new Map;constructor(e,t,n=256){this.empty=e,this.step=t,this.maxSessions=n}async read(e,t){let n=this.states.get(e),r=zC(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await ow(t,n?.cursor);if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:n?.value??this.empty};let{entries:a,cursor:o,reset:s}=i.value,c=s||n===void 0?this.empty:n.value;for(let e of a)c=this.step(c,e);for(this.touch(e,{cursor:o,value:c});this.states.size>this.maxSessions;){let e=this.states.keys().next().value;if(e===void 0)break;this.states.delete(e)}return{kind:`ok`,value:c}}touch(e,t){this.states.delete(e),this.states.set(e,t)}};const tA={messageCount:0,recent:[]};function nA(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +!!ew(t),recent:n.length>20?n.slice(-20):n}}function rA(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(ew(r))t=r.timestamp;else if(e===`assistant`&&t){let e=(r.timestamp.getTime()-t.getTime())/1e3;e>.1&&e<300&&(n=e)}}return n}var iA=class{fold=new eA(tA,nA);async getMetricsInfo(e,t){if(E(`Getting metrics from hook data for session: ${e}`),!t.cost)return Z;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?Q(`metrics (${e}): ${n.reason}`):X({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:rA(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const aA={command:null,todos:[],pending:[],done:[]};function oA(e,t){let n=e.findIndex(e=>e.name===t);return n<0?[...e,{name:t,count:1}]:e.map((e,t)=>t===n?{name:e.name,count:e.count+1}:e)}function sA(e,t){if(t.isSidechain)return e;let n=ew(t)?{...e,command:t.activity?.command??null,pending:[],done:[]}:e,r=t.activity;if(r===void 0)return n;let i=n.pending,a=n.done;r.started!==void 0&&(i=[...i,...r.started]);for(let e of r.finished??[]){let t=i.findIndex(t=>t.id===e);t<0||(a=oA(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function cA(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>oA(e,t.name),[]),done:e.done}}var lA=class{fold=new eA(aA,sA);async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?Q(`activity (${e}): ${n.reason}`):X(cA(n.value))}};const uA=new Map;function dA(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var fA=class{async getSessionId(){if(!process.env.TMUX_PANE)return Z;let e=dA(process.env.TMUX),t=uA.get(e);if(t!==void 0)return t;E(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await Ee({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?X(n.stdout.trim()):Z:Q(`tmux display-message: ${n.reason}`);return uA.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}},pA=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return c.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t){let n=this.pathFor(e);if(t===(this.written.get(e)??null))return null;try{return t===null?(r.rmSync(n,{force:!0}),this.written.delete(e)):(r.mkdirSync(this.dir,{recursive:!0,mode:448}),r.writeFileSync(n,t,{mode:384}),this.written.set(e,t)),null}catch(e){return`${n}: ${e.message}`}}reset(){this.written.clear();try{return r.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};const mA=new qD;we(mA.launchStats);const hA=new DC({counters:mA,logger:Y}),gA=new FC({watchers:hA,logger:Y}),_A=new vw,vA=new XD,yA=new pA(Ge()),bA=new $k,xA=new iA,SA=new lA,CA=new fA,wA=new GD({gitService:gA,sessionState:vA,watchers:hA},{observers:{onReload:e=>Y(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} file=${e.configFilePath??`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),TA=60*1e3;function EA(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(b(e)),t.argv[1]&&n.push(t.argv[1]);let i=new Map;for(let e of n)try{i.set(e,r.statSync(e).mtimeMs)}catch{}let a=null,o=()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){Y(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),HA(0);return}}catch(e){Y(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,TA),a.unref())},checkNow:o}}const DA=EA(),OA=nC({entryUrl:import.meta.url,intervalMs:TA,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>DA.checkNow(),log:Y});let kA=null,AA=null,jA=0;function MA(){t.on(`uncaughtException`,e=>{Y(`error`,`uncaughtException: ${e.stack||e.message}`),HA(1)}),t.on(`unhandledRejection`,e=>{Y(`error`,`unhandledRejection: ${String(e)}`),HA(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Y(`info`,`received ${e}, shutting down`),HA(0)});try{jA=Sy(t.env)}catch(e){Y(`error`,`refusing to boot: ${e.message}`),HA(1);return}kA=ux(t.pid);let e=bx(Sx(kA));if(!e.decision.allow){Y(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),HA(1);return}AA=e.registryPath,r.mkdirSync(Ne(),{recursive:!0}),Ie(Pe()),vA.useStorage(new $D(ze(),500,Y)),px({anchor:fx(t.env),isAlive:mx,onOrphaned:e=>{Y(`info`,`parent watchdog: ${e}; shutting down`),HA(0)}}),NA(g.createServer({allowHalfOpen:!1},e=>{UA(e)}),Pe(),!1)}function NA(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Y(`error`,`server error: ${i.message}`),HA(1);return}if(r){Y(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}PA(e,n)}),e.listen(n,()=>FA(n))}function PA(e,n){let i=ex(tx(Le(n)),(e,t)=>lx(e,t,{readStartTime:cx,pidAlive:mx}));if(i.kind===`attach-and-exit`){Y(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}Y(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){Y(`error`,`cannot unlink stale socket ${n}: ${e.message}`),HA(1);return}}NA(e,n,!0)}function FA(e){let n=ix(e);if(n.kind!==`present`){Y(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),HA(0);return}zA(e);try{r.chmodSync(e,384)}catch(e){Y(`warn`,`chmod socket failed: ${e.message}`)}Y(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(_.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(jA/1048576)}MB`),zy();let i=yA.reset();i!==null&&Y(`warn`,`diagnostic dump wipe failed: ${i}`),DA.arm(),OA.arm(),RA(),IA(e,n.identity)}function IA(e,n){sx({bound:n,myPid:t.pid,readIdentity:()=>ix(e),readLease:()=>tx(Le(e)),shutdown:e=>HA(e),log:Y}).arm()}let LA=null;function RA(){LA=Ey(Ay(mA.startedAt.getTime(),e=>HA(e),{rssLimitBytes:jA})),LA.arm()}function zA(e){let n=nx(Le(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:kA});n!==null&&Y(`warn`,`lease write failed: ${n}`)}let BA=0,VA=!1;function HA(e){if(!VA){VA=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{gA.close()}catch(e){Y(`warn`,`gitService close failed: ${e.message}`)}try{_A.close()}catch(e){Y(`warn`,`usageStore close failed: ${e.message}`)}try{hA.closeAll()}catch(e){Y(`warn`,`watcherRegistry close failed: ${e.message}`)}try{vA.flush()}catch(e){Y(`warn`,`sessionState flush failed: ${e.message}`)}rx(Re(),t.pid),AA!==null&&xx(AA,t.pid,vx,e=>r.unlinkSync(e)),t.exit(e)}}function UA(e){BA++,mA.inFlight=BA;let t=!1,n=(n,r)=>{if(t){r!==null&&Y(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>HA(r);try{e.end(Yv(n),i)}catch(e){Y(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{mA.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Xv(e=>{GA(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{Y(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{Y(`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=>{Y(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),BA=Math.max(0,BA-1),mA.inFlight=BA})}const WA=e=>({resp:e,exitAfterFlush:null});async function GA(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return WA({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?Y(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):Y(`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 WA({ok:!0,stats:mA.snapshot({gitCache:gA.getStats(),usageCache:_A.getStats(),renderCacheSize:wA.size,watchersActive:hA.size(),nextRestartReason:LA?.describeNextRestart()??null})});if(e.kind===`render`){mA.requestsTotal++;let t=Date.now();try{let{report:n}=Lk(e.hookData);for(let e of n.unknownTopLevelFields)Y(`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 mA.requestsErrored++,Y(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),WA({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=KA(e.args),s=e.hookData.session_id,c=Hv(e),l=JSON.stringify(c);vA.get(s,`client-hints`)!==l&&vA.set(s,Tk,l);let u=vA.get(s,`config-override`)??a??c.configEnv,d=wA.getOrCreate(i,e.cwd,u),f=mk({projectDir:i,cwd:e.cwd,configFile:u??null});vA.get(s,`render-origin`)!==f&&vA.set(s,pk,f);let p=c.termCols,m=Qk(p??120),h=Ix(c.termRows),g={...JA,width:m},{authoredRoots:_}=d.state,v=ww(d.state.config,t=>vA.get(e.hookData.session_id,t),e=>_.has(e)),y=await Lw(e.hookData,QA,e.cwd,d.state.neededInputPaths,v,c),b=[];g.style=v.style,g.separator=v.separator,g.wrap=v.autoWrap,g.padding=v.padding,g.charset=v.charset,g.colorCompatibility=v.colorCompatibility;let x=jD(d.state.config,d.state.compiled,d.state.store,d.state.registry,y,g,{perSegmentSink:d.state.lastRenderCellsBySegment,onRenderWarning:e=>b.push(e)},{theme:v.theme,look:v.look,preset:v.preset}),S=vA.get(e.hookData.session_id,`click.error`);S&&vA.clear(e.hookData.session_id,`click.error`);let C=[o,d.lastError,S].filter(Boolean).join(`
|
|
185
|
-
`),ee=
|
|
186
|
-
`)),re=
|
|
187
|
-
`})}catch(e){throw
|
|
188
|
-
`);return}t.stdout.write(
|
|
181
|
+
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function xD(e,t){switch(e){case`vertical`:return t.flatMap(e=>e);case`horizontal`:return t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`},...t.flatMap(e=>e.slice(1))]}}const SD={container:{compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Ws(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,`${t.path}.children[${n}]`))}},render(e,t){return xD(e.direction,e.children.map((n,r)=>t.renderChild(n,t.visible,{index:r,count:e.children.length,distribution:e.distribution})))}},segment:{compile(e,t){return{kind:`segment`,when:t.when,name:e.name,...e.opens!==void 0&&{opens:{open:t.parse(_c(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,`${t.path}.opens.body`),key:e.opens.ref.key}}}},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;if(!t.visible)return[];try{if(!yE(i.when,t.scope))return[];let n=i.palette??t.palette,a=t.enterSegment(e.name,n,t.region,i.bg,i.fg),o=i.template.evaluate(t.scope),s=t.exitSegment(o),c=e.opens!==void 0&&yE(e.opens.open,t.scope),l=s.length>0||c?a.trigger:a.closed,u={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:l,padding:t.padding},d=e.opens!==void 0&&c?TE(kE([t.closeDisclosure(e.opens.key)],a.trigger),{...u,width:`auto`,baseStyle:a.trigger}):[],f=e.opens===void 0?[]:t.renderBody(e.opens.body,c,a.disclosure),p=e=>e.band===`own`?d:[],m=f.map(e=>({cells:[...p(e),...e.cells],band:`deeper`})),h=bD(kE(o,l)).map(e=>({cells:TE(e,u),band:`own`})),g=s.map(e=>({cells:TE(kE([e],a.band),{...u,baseStyle:a.band}),band:`deeper`})),_=[...h,...g];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.name,[..._.flatMap(e=>e.cells),...f.flatMap(p)]),[..._,...m]}catch(n){let r=n.message??String(n);return t.onSegmentError?.(e.name,r),[{cells:[new Ar(`⚠ ${e.name}: ${r}`)],band:`own`}]}}}};function CD(e){return SD[e]}function wD(e){if(`ttl`in e)return{kind:`ttl`,durationMs:nE(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 TD(e,t){switch(Ea(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,regex:new RegExp(e.regex),default:t};case`text`:return{kind:`text`,default:t}}}function ED(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,cache:wD(n.cache),parse:TD(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cache:wD(n.cache),parse:TD(n.parse,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?nE(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 DD(e,t){let n=yl.EMPTY;for(let[r,i]of Object.entries(t))try{n=e.parse(`{{ define "${r}" }}${i}{{ end }}`,n).defines()}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}return n}function OD(e,t,n){let r=n?.cwd??process.cwd(),i={store:t.variableStore,compiled:new Map,stripStyle:`powerline`,basePalette:W_(e.globals.palette),padding:1},a=tD(),o={action:i,activeSegment:a},s=Object.keys(e.looks),c=lh(e.presets),l=new Map([...q_(e),...Ah(e)]),u=qT({...YE(i),...lD(i,a),...hD(o),...vD(a),looks:{fn:()=>s,argTypes:[]},presets:{fn:()=>c,argTypes:[]}},n?.clock),d=DD(u,e.helpers),f=e=>u.parse(e,d),p=new Map;for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&!p.has(n.key)&&p.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`&&!p.has(r.key)&&p.set(r.key,`${t}.${e}`);i.compiled=LE(f,e.actions,p,l);let m=[];for(let[n,i]of Object.entries(e.variables))try{ED(t,n,i,r)}catch(e){m.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{ED(t,`${n}.${e}`,a,r)}catch(t){m.push(`Variable "${n}.${e}": ${t.message??String(t)}`)}let h=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n)=>{try{return f(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};h[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`),palette:n.palette===void 0?void 0:L_(n.palette)}}let g=(e,t,n)=>{try{return f(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},_=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:g(e.when,t,`when`),parse:(e,n)=>g(e,t,n),compileChild:_};return CD(e.kind).compile(e,n)},v=new Map;for(let t of c){let{node:n,path:r}=fh(e,t);v.set(t,_(n,r))}let y=new Map;for(let t of di){let n=e.globals[t];fi(n)&&y.set(t,kD(f,t,n))}return{segments:h,roots:v,activeSegment:a,menuRuntime:o,globalExpressions:y,loadWarnings:m}}function kD(e,t,n){try{return e(n)}catch(e){throw Error(`globals.${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function AD(e,t,n){let r=e.globalExpressions.get(t);if(r===void 0)throw Error(`globals.${t} is an expression but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r.evaluate(n).map(e=>e.plain).join(``)}function jD(e,t){return e.kind===`decided`?e.name:t}function MD(e,t,n,r,i,a,o,s){let{perSegmentSink:c,onSegmentError:l,onRenderWarning:u}=o??{},{preset:d=sh}=s??{},f=s?.look??_i(`none`,e.looks),p=s?.theme??H_(void 0,null,e.globals.palette),m=(e,t)=>({...i,term:{cols:a.width},theme:{effective:e},look:{effective:t}});r.applyInput(m(jD(p,oi),jD(f,hi))),t.menuRuntime.action.stripStyle=a.style,t.menuRuntime.action.padding=a.padding;let h=JT(n),g=mi(p,()=>AD(t,`palette`,h),e=>V_(e,e=>u?.(e))),_=mi(f,()=>AD(t,`look`,h),t=>_i(t,e.looks));(g!==p||_!==f)&&r.applyInput(m(g.name,_.name));let v=g.value;t.menuRuntime.action.basePalette=v;let y=z_(v,_.value);c?.clear();let b=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},x=(e,n,r,i,a)=>{let{tint:o,text:s,disclosure:c}=dc(n,r),l=NE(t.activeSegment,e,n,c,o,s,i,a,h),u=ic(n,c);return{closed:l,trigger:ZE(n,u.state),band:ZE(n,u.plane),disclosure:c}},S=e=>(t.activeSegment.current=null,dD(e)),C=(e,t,r)=>{let i=t&&yE(e.when,h),o={scope:h,palette:y,visible:i,padding:a.padding,region:r,perSegmentSink:c,onSegmentError:l,enterSegment:x,exitSegment:S,lookupSegment:b,renderChild:(e,t,n)=>C(e,t,cc(r,n)),renderBody:(e,t,n)=>C(e,i&&t,lc(n)),closeDisclosure:e=>XE(n,e)};return CD(e.kind).render(e,o)},ee=t.roots.get(d);if(ee===void 0)throw Error(`Preset "${d}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${sh}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);return C(ee,!0,sc).map(e=>Fx(OE(e.cells,a),a)).join(`
|
|
182
|
+
`)}var ND=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,zD(e,t,n,`initial value`),this.cell=tT.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){zD(this.name,this.type,e,`set value`),!Object.is(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}},PD=class{kind=`computed`;cell;constructor(e,t,n){this.name=e,this.type=t,this.cell=(0,tT.computed)(()=>{let e=n();return zD(this.name,this.type,e,`computed result`),e},{keepAlive:!0})}read(){return this.cell.get()}lastUpdatedMs(){return null}},FD=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=tT.observable.box(RD(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=RD(e);LD(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function ID(e){return JSON.stringify(e)}function LD(e,t){return ID(e)===ID(t)}function RD(e){return e.kind===`ok`?{kind:`ok`,value:nT(e.value)}:e}function zD(e,t,n,r){let i=rT(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var BD=class{nodes=new Map;defineBox(e,t,n){this.assertNotDefined(e),this.nodes.set(e,new ND(e,t,n))}defineDocument(e,t){this.assertNotDefined(e),this.nodes.set(e,new FD(e,t))}defineComputed(e,t,n){this.assertNotDefined(e);let r=e=>this.read(e);this.nodes.set(e,new PD(e,t,()=>n(r)))}read(e){return this.requireVar(e).read()}readDocument(e){let t=this.requireNode(e);if(t.kind!==`document`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a document`);return t.read()}setDocument(e,t){let n=this.requireNode(e);if(n.kind!==`document`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,tT.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireNode(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,tT.runInAction)(()=>n.set(t))}runInAction(e){(0,tT.runInAction)(e)}has(e){return this.nodes.has(e)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`)return ID(t.read());try{return String(t.read())}catch(e){return`failed:${e instanceof Error?e.message:String(e)}`}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.nodes.keys()]}requireNode(e){let t=this.nodes.get(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireVar(e){let t=this.requireNode(e);if(t.kind===`document`)throw TypeError(`Variable "${e}" is a document; read its fields by path (.${e}.<field>)`);return t}assertNotDefined(e){if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`)}};function VD(e,t,n){return e+`\0`+t+`\0`+(n??``)}function HD(e,t){return new Set(lh(e.presets).filter(n=>fh(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function UD(e){let t=c.basename(e),n=c.dirname(e);for(;!r.existsSync(n);)t=c.basename(n),n=c.dirname(n);return{dir:n,name:t}}function WD(e,t){let n=new Map;for(let t of Tv(e.projectDir,e.cwd,e.configFile)){let{dir:e,name:r}=UD(t);n.has(e)||n.set(e,new Set),n.get(e).add(r)}return{files:t===null?[]:[t],dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({path:e,filenames:[...t].sort()}))}}function GD(e){return e.filter(Boolean).join(`
|
|
183
|
+
`)||null}var KD=class{entries=new Map;deps;maxEntries;observers;constructor(e,t={}){this.deps=e,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}getOrCreate(e,t,n){let r=VD(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.loadFromDisk(e,t,n),o={projectDir:e,cwd:t,configFile:n,configFilePath:null,lastError:a.error,lastWarning:a.warning,state:a.state??this.buildState(t,null,[]),watcher:null,watcherKey:null};if(this.entries.set(r,o),this.entries.size>this.maxEntries){let e=this.entries.entries().next().value;if(e!==void 0){let[t,n]=e;n.state.registry.dispose(),n.state.validatorDisposers.forEach(e=>e()),n.watcher?.release(),this.entries.delete(t)}}return this.refreshWatcher(o,a.resolvedPath),this.observers.onReload?.(o),o}reloadInto(e){let t=this.loadFromDisk(e.projectDir,e.cwd,e.configFile);e.lastWarning=t.warning,e.lastError=t.error,t.state!==null&&(e.state.registry.dispose(),e.state.validatorDisposers.forEach(e=>e()),e.state=t.state),this.refreshWatcher(e,t.resolvedPath),this.observers.onReload?.(e)}loadFromDisk(e,t,n){let r=Dv(e,t,n),i=r.kind===`file`?r.path:null,a=[jv(e,t),kv(r)],o;try{o=this.buildState(t,i,a)}catch(e){return e instanceof _a&&a.push(...e.warnings),{resolvedPath:i,warning:GD(a),state:null,error:e instanceof _a||e instanceof Error?e.message:String(e)}}return{resolvedPath:i,warning:GD(a),state:o,error:null}}buildState(e,t,n){let{config:r,raw:i,source:a,warnings:o}=Mv(t,Qw);n.push(...o);let s=Fv(r,t??`<default>`,a),c=new BD,l=new vE(c,s.globals.default_empty_value??``,this.deps.gitService,this.deps.sessionState),u,d=[];try{u=OD(s,l,{cwd:e}),n.push(...u.loadWarnings);for(let{key:e,spec:t}of VS(s))d.push(PS(e,t));for(let{key:e,spec:t}of CS(s))d.push(wS(e,t))}catch(e){for(let e of d)e();throw l.dispose(),e}return{config:s,store:c,registry:l,compiled:u,neededInputPaths:Nw(s),lastRenderCellsBySegment:new Map,validatorDisposers:d,authoredRoots:HD(r,i)}}refreshWatcher(e,t){e.configFilePath=t;let n=WD(e,t),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){Y(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const qD=16384;var JD=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<qD){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%qD}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:vb,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,renderCache:{size:e.renderCacheSize},watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null}}};const YD={load:()=>({}),save:()=>{},flush:()=>{}};function XD(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,new Map(Object.entries(r)));return t}var ZD=class{sessions;storage;atom=(0,tT.createAtom)(`SessionState`);constructor(e=YD,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=XD(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,tT.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,tT.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,tT.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 QD=(e,t)=>E(t);function $D(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 eO=class{timer=null;pending=null;constructor(e,t=500,n=QD){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=r.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return $D(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{r.mkdirSync(c.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;r.writeFileSync(t,JSON.stringify(e),{mode:384}),r.chmodSync(t,384),r.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const tO={default_bg:`string`,default_fg:`string`,default_empty_value:`string`,default_separator:`string`,default_truncate_marker:`string`,palette:`string`,look:`string`,preset:`string`,style:`string`,autoWrap:`boolean`,padding:`number`,charset:`string`,updateNotice:`boolean`,colorCompatibility:`string`},nO=new Set([`1`,`true`]),rO=new Set([`0`,`false`,``]);function iO(e,t){let n=kO(e),r=n.scope===`globals`?tO[n.field]:`string`;if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if(nO.has(t))return`true`;if(rO.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function aO(e){try{return r.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function oO(e,t,n){try{if(t===null){r.rmSync(e,{force:!0});return}r.mkdirSync(c.dirname(e),{recursive:!0}),Ae(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function sO(e){return/^\s*$/.test(e)?null:Li(e)}function cO(e,t){return e!==null&&zi(e,t)!==void 0}function lO(e){if(e.kind===`segment`)return e.when===void 0?e.name:{seg:e.name,when:e.when};if(e.kind===`container`){let{kind:t,direction:n,children:r,...i}=e;return{[n===`horizontal`?`h`:`v`]:r.map(lO),...i}}return e}function uO(e){if(!fo(e))return lO(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,lO(t)])),...n}}const dO=Xw,fO=dO.segments,pO=dO.presets,mO=dO.root;function hO(e,t,n,r){if(!cO(e,t)&&n===void 0)throw new $(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function gO(e,t){let n=vh(t);return t.scope===`segment-palette`&&hO(e,[`segments`,t.segment],fO[t.segment],n.join(`.`)),n}function _O(e){return Li(Gi(e))}function vO(){return Object.entries(mO.rows).map(([e,t])=>{let n=lO(t);return{path:[`root`],fragment:_O({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function yO(e,t){let n=e===null?void 0:zi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function bO(e,t){if(t===void 0)return null;let n=uO(t);return{path:e,fragment:_O(n),unit:{path:e,value:n}}}function xO(e,t){let n=[`presets`,t],r=[...n,`root`],i=pO[t];hO(e,n,i,r.join(`.`));let a=yO(e,r)??bO(r,i?.root);return a!==null&&da(a.fragment)?a:null}function SO(e,t){let n=ua(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function CO(e,t){return[...vO(),yO(e,[`root`]),xO(e,t)].filter(e=>e!==null).reduce(SO,new Map)}function wO(e,t,n){for(let{node:r,...i}of CO(e,t).values())if(pa(r,n))return i;throw new $(`${TO(e,t).join(`.`)} holds no segment "${n}" — the bar you clicked is stale; it reloads on the next render`)}function TO(e,t){return xO(e,t)?.path??[`root`]}function EO(e,t){return t.scope===`preset-root`?TO(e,t.preset):vh(t)}function DO(e,{unit:t}){return t===null?e:aa(e,t.path,Gi(t.value),Ui)}function OO(e){let t=_h(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function kO(e){let t=OO(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function AO(e,t){let n=kO(t),r=sO(aO(e)??``),i=r===null?void 0:zi(r,vh(n));return i!==void 0&&`value`in i?i.value:void 0}function jO(e,t,n,r){let i=kO(n),a=aO(t);VO(e,t,{before:a,after:aa(a??``,gO(sO(a??``),i),iO(n,r),Ui)})}function MO(e,t,n){let r=OO(n),i=aO(t);if(i===null)return;let a=oa(i,EO(sO(i),r));a!==i&&VO(e,t,{before:i,after:a})}function NO(e,t,n,r){let i=OO(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=aO(t),o=r.op===`remove`?r.target:r.anchor,s=wO(sO(a??``),i.preset,o),c=DO(a??``,s),l=r.op===`remove`?ha(c,s.path,r.target):ga(c,s.path,r.segment,r.anchor,r.relation);if(l===null)throw new $(`${s.path.join(`.`)} in ${t} has no segment "${o}" — the bar you clicked is stale; it reloads on the next render`);VO(e,t,{before:a,after:l})}const PO={past:[],future:[]};function FO(e){if(typeof e!=`object`||!e)return!1;let t=e;return(t.before===null||typeof t.before==`string`)&&typeof t.after==`string`}function IO(e){if(typeof e!=`object`||!e)return!1;let t=e;return Array.isArray(t.past)&&t.past.every(FO)&&Array.isArray(t.future)&&t.future.every(FO)}function LO(e){let t;try{t=r.readFileSync(e.historyPath,`utf8`)}catch(t){let n=t.code;return n!==`ENOENT`&&e.logger(`warn`,`config-edit-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(t);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(IO))return e}catch{}return e.logger(`warn`,`config-edit-history load: unexpected shape, starting empty`),{}}function RO(e,t){try{r.mkdirSync(c.dirname(e.historyPath),{recursive:!0}),Ae(e.historyPath,JSON.stringify(t),384)}catch(t){let n=`config-edit-history write failed: ${t.message}`;throw e.logger(`error`,n),Error(n)}}function zO(e,t){let n=[...e,t];return n.length>50?n.slice(-50):n}function BO(e,t,n,r,i){oO(t,n,e.logger);try{RO(e,r)}catch(e){throw Error(`${i} landed in ${t} but recording it failed — it is not undoable: ${e.message}`)}}function VO(e,t,n){let r=LO(e),{past:i}=r[t]??PO;BO(e,t,n.after,{...r,[t]:{past:zO(i,n),future:[]}},`edit`)}function HO(e,t){let n=LO(e),{past:r,future:i}=n[t]??PO,a=r[r.length-1];return a===void 0?null:(WO(t,a.after,`undo`),BO(e,t,a.before,{...n,[t]:{past:r.slice(0,-1),future:zO(i,a)}},`undo`),a)}function UO(e,t){let n=LO(e),{past:r,future:i}=n[t]??PO,a=i[i.length-1];return a===void 0?null:(WO(t,a.before,`redo`),BO(e,t,a.after,{...n,[t]:{past:zO(r,a),future:i.slice(0,-1)}},`redo`),a)}function WO(e,t,n){if(aO(e)!==t)throw new $(`${n}: ${e} has changed since that edit — refusing to overwrite it`)}function GO(e){let t=De({bin:`tmux`,args:[`-S`,e.socket,`display`,`-p`,`-t`,e.pane,`#{client_termfeatures}`],timeoutMs:2e3,category:`doctor.tmux`});return t.ok?{kind:`ok`,value:t.stdout.trim().split(`,`).filter(e=>e!==``)}:{kind:`failed`,reason:`tmux display -p failed (${t.error??[t.reason,t.stderr.trim()].filter(e=>e!==``).join(`: `)})`}}function KO(){return{probeTmux:GO,claudeSettingsPath:yb()}}function qO(e){return r.existsSync(e.claudeSettingsPath)?r.readFileSync(e.claudeSettingsPath,`utf8`):``}function JO(e){if(/^\s*$/.test(e))return{};let t=Wi.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`not a JSON object`);let n=t.env;if(n===void 0)return{};if(typeof n!=`object`||!n||Array.isArray(n))throw Error("`env` is not an object");return n}function YO(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,termfeatures:e.probeTmux(t)}}function XO(e){try{return JO(qO(e))}catch(t){throw Error(`cannot read ${e.claudeSettingsPath}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}function ZO(e,t){return{tmux:YO(e,t),claudeSettingsEnv:XO(e)}}function QO(e,t,n){switch(t.kind){case`claude-settings-env`:{let i=aa(qO(e),[`env`,t.name],JSON.stringify(t.value),Wi);return r.mkdirSync(c.dirname(e.claudeSettingsPath),{recursive:!0}),Ae(e.claudeSettingsPath,i),{...n,claudeSettingsEnv:XO(e)}}default:return t.kind}}function $O(e){if(!e)throw new $(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new $(`invalid session id "${e}"`);return e}function ek(e){return tk(()=>decodeURIComponent(e))}function tk(e){try{return e()}catch(e){throw e instanceof URIError?new $(`malformed wire encoding: ${e.message}`):e}}function nk(e,t){let n=De({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 rk=(e,t)=>nk(ek(e),t),ik=(e,t)=>{let n=De({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,ek(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`})`)}},ak=(e,t)=>nk(ek(e),t),ok=(e,t)=>nk(ek(e),t),sk=(e,t)=>{let n=$O(ek(e));t.sessionState.get(n,`toolbar-expanded`)?t.sessionState.clear(n,`toolbar-expanded`):t.sessionState.set(n,`toolbar-expanded`,`1`)},ck=(e,t)=>{let[n=``,...r]=tk(()=>mb(e)),i=$O(n);if(r.length===0)throw new $(`set-state: <key>/<value> is required (have keys: ${NS().join(`, `)})`);if(r.length%2!=0)throw new $(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${NS().join(`, `)})`);let a=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new $(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=FS(t,n);if(!i.ok)throw new $(`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})`)},lk=/^-?\d+$/;function uk(e,t,n){return e>n?t:e<t?n:e}function dk(e,t){if(!e)return null;if(!NS().includes(e))throw new $(`${t}: unknown session key "${e}" to release (have: ${NS().join(`, `)})`);return e}function fk(e,t,n,r){e!==null&&(n.sessionState.clear(t,e),n.dlog(`info`,`${r}: released session key ${e} (session=${t})`))}const pk=(e,t)=>{let[n=``,r=``,i=``]=tk(()=>mb(e)),a=$O(n);if(!r)throw new $(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!lk.test(i))throw new $(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=IS(r);if(!s)throw new $(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${NS().join(`, `)})`);let c=t.sessionState.get(a,r),l=c&&lk.test(c)?Math.max(s.min,Math.min(s.max,parseInt(c,10))):s.seed,u=uk(l+o,s.min,s.max),d=FS(r,String(u));if(!d.ok)throw new $(`step-state: ${d.reason}`);t.sessionState.set(a,r,d.value),t.dlog(`info`,`step-state: ${r} ${l}→${d.value} (by ${o}, session=${a})`)},mk=`render-origin`;function hk(e){return JSON.stringify(e)}function gk(e){let t;try{t=JSON.parse(e)}catch{throw new $(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new $(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new $(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function _k(e,t){let n=e.sessionState.get(t,mk);if(n===null)throw new $(`session ${t} has not rendered yet — no config file to write`);let r=gk(n);return Ov(r.projectDir,r.cwd,r.configFile??void 0)}function vk(e){return{historyPath:Be(),logger:e.dlog}}const yk=(e,t)=>{let[n=``,r=``,i=``,a=``]=tk(()=>mb(e)),o=$O(n);if(!r)throw new $(`set-config: <key>/<value> is required (have keys: ${hS().join(`, `)})`);let s=gS(r,i);if(!s.ok)throw new $(`set-config: ${s.reason}`);let c=dk(a,`set-config`),l=_k(t,o);jO(vk(t),l,r,s.value),t.dlog(`info`,`set-config: ${r}=${s.value} → ${l} (session=${o})`),fk(c,o,t,`set-config`)},bk=(e,t)=>{let[n=``,r=``,i=``,a=``]=tk(()=>mb(e)),o=$O(n);if(!r)throw new $(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!lk.test(i))throw new $(`step-config: delta must be an integer, got "${i}"`);let s=parseInt(i,10),c=dk(a,`step-config`),l=_S(r);if(!l)throw new $(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${hS().join(`, `)})`);let u=_k(t,o),d=AO(u,r),f=typeof d==`number`?Math.max(l.min,Math.min(l.max,d)):l.seed,p=uk(f+s,l.min,l.max),m=gS(r,String(p));if(!m.ok)throw new $(`step-config: ${m.reason}`);jO(vk(t),u,r,m.value),t.dlog(`info`,`step-config: ${r} ${f}→${m.value} (by ${s}) → ${u} (session=${o})`),fk(c,o,t,`step-config`)},xk=(e,t)=>{let[n=``,r=``]=tk(()=>mb(e)),i=$O(n);if(!r||!hS().includes(r))throw new $(`reset-config: unknown config key "${r}" (have: ${hS().join(`, `)})`);let a=_k(t,i);MO(vk(t),a,r),t.dlog(`info`,`reset-config: ${r} ← ${a} (session=${i})`)},Sk=(e,t)=>{let[n=``,r=``,i=``]=tk(()=>mb(e)),a=$O(n);if(!r)throw new $(`apply-layout-op: <key>/<op> is required (have: ${hS().join(`, `)})`);let o=gS(r,i);if(!o.ok)throw new $(`apply-layout-op: ${o.reason}`);let s=ah(o.value);if(s===null)throw new $(`apply-layout-op: "${o.value}" is not a layout op token`);let c=_k(t,a);NO(vk(t),c,r,s),t.dlog(`info`,`apply-layout-op: ${r} ${o.value} → ${c} (session=${a})`)},Ck=(e,t)=>{let[n=``]=tk(()=>mb(e)),r=$O(n),i=_k(t,r);if(HO(vk(t),i)===null)throw new $(`undo: history is empty, nothing to undo`);t.dlog(`info`,`undo: ${i} (session=${r})`)},wk=(e,t)=>{let[n=``]=tk(()=>mb(e)),r=$O(n),i=_k(t,r);if(UO(vk(t),i)===null)throw new $(`redo: nothing to redo`);t.dlog(`info`,`redo: ${i} (session=${r})`)},Tk=(e,t)=>{$O(ek(e)),t.applyUpdate()},Ek=`client-hints`;function Dk(e,t){let n=e.sessionState.get(t,Ek);if(n===null)throw new $(`session ${t} has not rendered yet — no client facts to diagnose`);let r;try{r=JSON.parse(n)}catch{throw new $(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new $(`client hints record is not an object: ${n}`);return Hv(r)}function Ok(e,t,n){let r=Hh(n);e.sessionState.setBatch(t,Gh(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed`}`).join(` `)} (session=${t})`)}const kk=(e,t)=>{let n=$O(ek(e));Ok(t,n,ZO(t.doctor,Dk(t,n).tmux))},Ak=(e,t)=>{let[n=``,r=``]=tk(()=>mb(e)),i=$O(n),a=Uh(r);if(a===void 0)throw new $(`doctor-fix: unknown check "${r}"`);let o=ZO(t.doctor,Dk(t,i).tmux),s=a.probe(o);if(s.ok||s.fix===void 0)throw new $(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=QO(t.doctor,s.fix,o);t.dlog(`info`,`doctor-fix: ${a.name} → ${s.fix.kind} ${s.fix.name}=${s.fix.value} (session=${i})`),Ok(t,i,c)},jk=`config-override`,Mk=new Map([[$y,rk],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new $(`load-config: expected <sessionId>/<path> (missing separator)`);let r=$O(tk(()=>decodeURIComponent(e.slice(0,n)))),i=tk(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new $(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new $(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,jk),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,jk,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[eb,ik],[Zy,ck],[Qy,pk],[ib,yk],[ab,bk],[ob,xk],[sb,Sk],[cb,Ck],[lb,wk],[nb,ak],[rb,ok],[tb,sk],[ub,Tk],[db,kk],[fb,Ak]]),Nk=new Set([Zy,Qy,ib,ab,ob,sb,cb,lb,tb,ub,db,fb]),Pk=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of gb(e)){if(!i&&Nk.has(a)){let e=mb(o);e.length>0&&e[0]&&(i=e[0])}let e=Mk.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof $||(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(`
|
|
184
|
+
`));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new $(e)}},Fk=new Map([...Mk,[Xy,Pk]]);Object.freeze([...Fk.keys()]);const Ik=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`]),Lk=[[`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 Rk(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of Lk){let i=Bk(n,e);if(i==null)t.missingRequired.push(e);else{let n=zk(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let e of Object.keys(n))Ik.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function zk(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function Bk(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 Vk(e,t){switch(e){case`vars`:return{what:e,vars:Hk(t)};case`segments`:return{what:e,segments:qk(t)};case`config`:return{what:e,config:Xk(t)}}}function Hk(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=Gk(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,...Uk(r),lastError:a===void 0?null:{timestampMs:a.timestamp,message:a.message},ageMs:Wk(r.lastUpdatedMs())})}return o}function Uk(e){if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function Wk(e){return e===null?null:Math.max(0,Date.now()-e)}function Gk(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,Kk(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}`,Kk(i));return t}function Kk(e){return e.kind}function qk(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=Jk(n),o=[];for(let e of a){let t=n.segments[e];t&&o.push({name:e,description:t.description??null,template:t.template,referencedVars:Yk(t.template,i),lastRender:r.get(e)??null})}return o}function Jk(e){let t=[],n=new Set;for(let r of wa(ho(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 Yk(e,t){let n=new Set;for(let r of $_(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 Xk(e){return e===null?null:e.config}const Zk=[`vars`,`segments`,`config`];function Qk(e){return typeof e==`string`&&Zk.includes(e)}function $k(e){return Math.max(1,e-2)}var eA=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 E(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);E(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t){try{E(`Calculating context tokens from transcript: ${e}`);let n=await nw(e);if(n.length===0)return E(`No entries in transcript`),Z;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,E(`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 E(`Most recent main chain context: ${n} tokens (limit: ${t})`),X({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)})}return E(`No main chain entries with usage data found`),Z}catch(e){return Q(`context transcript: ${e instanceof Error?e.message:String(e)}`)}}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return X(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.transcript_path,n)}},tA=class{states=new Map;constructor(e,t,n=256){this.empty=e,this.step=t,this.maxSessions=n}async read(e,t){let n=this.states.get(e),r=zC(t);if(n&&r!==0&&n.cursor.mtimeMs===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await ow(t,n?.cursor);if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:n?.value??this.empty};let{entries:a,cursor:o,reset:s}=i.value,c=s||n===void 0?this.empty:n.value;for(let e of a)c=this.step(c,e);for(this.touch(e,{cursor:o,value:c});this.states.size>this.maxSessions;){let e=this.states.keys().next().value;if(e===void 0)break;this.states.delete(e)}return{kind:`ok`,value:c}}touch(e,t){this.states.delete(e),this.states.set(e,t)}};const nA={messageCount:0,recent:[]};function rA(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +!!ew(t),recent:n.length>20?n.slice(-20):n}}function iA(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(ew(r))t=r.timestamp;else if(e===`assistant`&&t){let e=(r.timestamp.getTime()-t.getTime())/1e3;e>.1&&e<300&&(n=e)}}return n}var aA=class{fold=new tA(nA,rA);async getMetricsInfo(e,t){if(E(`Getting metrics from hook data for session: ${e}`),!t.cost)return Z;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?Q(`metrics (${e}): ${n.reason}`):X({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:iA(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const oA={command:null,todos:[],pending:[],done:[]};function sA(e,t){let n=e.findIndex(e=>e.name===t);return n<0?[...e,{name:t,count:1}]:e.map((e,t)=>t===n?{name:e.name,count:e.count+1}:e)}function cA(e,t){if(t.isSidechain)return e;let n=ew(t)?{...e,command:t.activity?.command??null,pending:[],done:[]}:e,r=t.activity;if(r===void 0)return n;let i=n.pending,a=n.done;r.started!==void 0&&(i=[...i,...r.started]);for(let e of r.finished??[]){let t=i.findIndex(t=>t.id===e);t<0||(a=sA(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function lA(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>sA(e,t.name),[]),done:e.done}}var uA=class{fold=new tA(oA,cA);async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?Q(`activity (${e}): ${n.reason}`):X(lA(n.value))}};const dA=new Map;function fA(e){if(!e)return``;let t=e.indexOf(`,`);return t<0?e:e.slice(0,t)}var pA=class{async getSessionId(){if(!process.env.TMUX_PANE)return Z;let e=fA(process.env.TMUX),t=dA.get(e);if(t!==void 0)return t;E(`Getting tmux session ID, TMUX_PANE: ${process.env.TMUX_PANE}`);let n=await Ee({bin:`tmux`,args:[`display-message`,`-p`,`#S`],timeoutMs:1e3,category:`tmux`}),r=n.ok?n.stdout.trim()?X(n.stdout.trim()):Z:Q(`tmux display-message: ${n.reason}`);return dA.set(e,r),r}isInTmux(){return!!process.env.TMUX_PANE}},mA=class{written=new Map;constructor(e){this.dir=e}pathFor(e){return c.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t){let n=this.pathFor(e);if(t===(this.written.get(e)??null))return null;try{return t===null?(r.rmSync(n,{force:!0}),this.written.delete(e)):(r.mkdirSync(this.dir,{recursive:!0,mode:448}),r.writeFileSync(n,t,{mode:384}),this.written.set(e,t)),null}catch(e){return`${n}: ${e.message}`}}reset(){this.written.clear();try{return r.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};const hA=new JD;we(hA.launchStats);const gA=new DC({counters:hA,logger:Y}),_A=new FC({watchers:gA,logger:Y}),vA=new vw,yA=new ZD,bA=new mA(Ge()),xA=new eA,SA=new aA,CA=new uA,wA=new pA,TA=new KD({gitService:_A,sessionState:yA,watchers:gA},{observers:{onReload:e=>Y(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} file=${e.configFilePath??`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),EA=60*1e3;function DA(){let e=import.meta.url,n=[];e.startsWith(`file://`)&&n.push(b(e)),t.argv[1]&&n.push(t.argv[1]);let i=new Map;for(let e of n)try{i.set(e,r.statSync(e).mtimeMs)}catch{}let a=null,o=()=>{for(let[e,t]of i)try{if(r.statSync(e).mtimeMs!==t){Y(`info`,`binary mtime changed (${e}); shutting down`),a&&clearInterval(a),UA(0);return}}catch(e){Y(`warn`,`bin stat failed: ${e.message}`)}};return{arm(){i.size!==0&&(a=setInterval(o,EA),a.unref())},checkNow:o}}const OA=DA(),kA=nC({entryUrl:import.meta.url,intervalMs:EA,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>OA.checkNow(),log:Y});let AA=null,jA=null,MA=0;function NA(){t.on(`uncaughtException`,e=>{Y(`error`,`uncaughtException: ${e.stack||e.message}`),UA(1)}),t.on(`unhandledRejection`,e=>{Y(`error`,`unhandledRejection: ${String(e)}`),UA(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{Y(`info`,`received ${e}, shutting down`),UA(0)});try{MA=Sy(t.env)}catch(e){Y(`error`,`refusing to boot: ${e.message}`),UA(1);return}AA=ux(t.pid);let e=bx(Sx(AA));if(!e.decision.allow){Y(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),UA(1);return}jA=e.registryPath,r.mkdirSync(Ne(),{recursive:!0}),Ie(Pe()),yA.useStorage(new eO(ze(),500,Y)),px({anchor:fx(t.env),isAlive:mx,onOrphaned:e=>{Y(`info`,`parent watchdog: ${e}; shutting down`),UA(0)}}),PA(g.createServer({allowHalfOpen:!1},e=>{WA(e)}),Pe(),!1)}function PA(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){Y(`error`,`server error: ${i.message}`),UA(1);return}if(r){Y(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}FA(e,n)}),e.listen(n,()=>IA(n))}function FA(e,n){let i=ex(tx(Le(n)),(e,t)=>lx(e,t,{readStartTime:cx,pidAlive:mx}));if(i.kind===`attach-and-exit`){Y(`info`,`EADDRINUSE: ${i.reason} — exiting`),t.exit(0);return}Y(`warn`,`EADDRINUSE: ${i.reason} — unlinking stale socket and rebinding`);try{r.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){Y(`error`,`cannot unlink stale socket ${n}: ${e.message}`),UA(1);return}}PA(e,n,!0)}function IA(e){let n=ix(e);if(n.kind!==`present`){Y(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),UA(0);return}BA(e);try{r.chmodSync(e,384)}catch(e){Y(`warn`,`chmod socket failed: ${e.message}`)}Y(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Math.round(_.getHeapStatistics().heap_size_limit/1048576)}MB rssLimit=${Math.round(MA/1048576)}MB`),zy();let i=bA.reset();i!==null&&Y(`warn`,`diagnostic dump wipe failed: ${i}`),OA.arm(),kA.arm(),zA(),LA(e,n.identity)}function LA(e,n){sx({bound:n,myPid:t.pid,readIdentity:()=>ix(e),readLease:()=>tx(Le(e)),shutdown:e=>UA(e),log:Y}).arm()}let RA=null;function zA(){RA=Ey(Ay(hA.startedAt.getTime(),e=>UA(e),{rssLimitBytes:MA})),RA.arm()}function BA(e){let n=nx(Le(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:AA});n!==null&&Y(`warn`,`lease write failed: ${n}`)}let VA=0,HA=!1;function UA(e){if(!HA){HA=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{_A.close()}catch(e){Y(`warn`,`gitService close failed: ${e.message}`)}try{vA.close()}catch(e){Y(`warn`,`usageStore close failed: ${e.message}`)}try{gA.closeAll()}catch(e){Y(`warn`,`watcherRegistry close failed: ${e.message}`)}try{yA.flush()}catch(e){Y(`warn`,`sessionState flush failed: ${e.message}`)}rx(Re(),t.pid),jA!==null&&xx(jA,t.pid,vx,e=>r.unlinkSync(e)),t.exit(e)}}function WA(e){VA++,hA.inFlight=VA;let t=!1,n=(n,r)=>{if(t){r!==null&&Y(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let i=r===null?void 0:()=>UA(r);try{e.end(Yv(n),i)}catch(e){Y(`warn`,`response write failed: ${e.message}`),i?.()}},r=setTimeout(()=>{hA.requestsTimedOut++,n({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null)},200),i=Xv(e=>{KA(e).then(e=>n(e.resp,e.exitAfterFlush)).catch(e=>{Y(`error`,`handler threw: ${e?.stack||e}`),n({ok:!1,error:String(e?.message||e),code:`RENDER_FAILED`,daemonV:3},null)})},e=>{Y(`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=>{Y(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(r),VA=Math.max(0,VA-1),hA.inFlight=VA})}const GA=e=>({resp:e,exitAfterFlush:null});async function KA(e){if(!e||typeof e!=`object`||typeof e.v!=`number`)return GA({ok:!1,error:`malformed request`,code:`BAD_REQUEST`,daemonV:3});if(e.v!==3)return e.v>3?Y(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):Y(`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 GA({ok:!0,stats:hA.snapshot({gitCache:_A.getStats(),usageCache:vA.getStats(),renderCacheSize:TA.size,watchersActive:gA.size(),nextRestartReason:RA?.describeNextRestart()??null})});if(e.kind===`render`){hA.requestsTotal++;let t=Date.now();try{let{report:n}=Rk(e.hookData);for(let e of n.unknownTopLevelFields)Y(`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 hA.requestsErrored++,Y(`warn`,`BAD_REQUEST: ${r.join(`; `)}`),GA({ok:!1,error:`malformed hookData: ${r.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3});let i=e.hookData.workspace.project_dir,{configFile:a,unknownFlagsError:o}=qA(e.args),s=e.hookData.session_id,c=Hv(e),l=JSON.stringify(c);yA.get(s,`client-hints`)!==l&&yA.set(s,Ek,l);let u=yA.get(s,`config-override`)??a??c.configEnv,d=TA.getOrCreate(i,e.cwd,u),f=hk({projectDir:i,cwd:e.cwd,configFile:u??null});yA.get(s,`render-origin`)!==f&&yA.set(s,mk,f);let p=c.termCols,m=$k(p??120),h=Ix(c.termRows),g={...YA,width:m},{authoredRoots:_}=d.state,v=ww(d.state.config,t=>yA.get(e.hookData.session_id,t),e=>_.has(e)),y=await Lw(e.hookData,$A,e.cwd,d.state.neededInputPaths,v,c),b=[];g.style=v.style,g.separator=v.separator,g.wrap=v.autoWrap,g.padding=v.padding,g.charset=v.charset,g.colorCompatibility=v.colorCompatibility;let x=MD(d.state.config,d.state.compiled,d.state.store,d.state.registry,y,g,{perSegmentSink:d.state.lastRenderCellsBySegment,onRenderWarning:e=>b.push(e)},{theme:v.theme,look:v.look,preset:v.preset}),S=yA.get(e.hookData.session_id,`click.error`);S&&yA.clear(e.hookData.session_id,`click.error`);let C=[o,d.lastError,S].filter(Boolean).join(`
|
|
185
|
+
`),ee=kA.notice({sessionId:s,dismissed:yA.get(s,HS),enabled:v.updateNotice}),te=d.lastError===null?null:d.configFilePath,ne=Vx(C,ee,[d.lastWarning??``,...b].filter(Boolean).join(`
|
|
186
|
+
`)),re=bA.sync(s,ne===null?null:Ux(ne));re!==null&&Y(`warn`,`diagnostic dump failed: ${re}`);let ie=Wx(x,ne,{fullText:re===null?{kind:`file`,path:bA.pathFor(s)}:{kind:`unavailable`,reason:re},failedConfigFile:te},{width:m,rowCap:h,colorCompatibility:v.colorCompatibility}),ae=Date.now()-t,w=_A.getStats(),T=vA.getStats();return Y(`info`,`render sid=${e.hookData.session_id??`?`} took=${ae}ms termCols=${p??`?`} termRows=${c.termRows??`?`} width=${m} git=${w.size}/${w.hits}h/${w.misses}m usage=${T.size}/${T.hits}h/${T.misses}m err=${C?`Y`:`N`} upd=${ee.length} warn=${d.lastWarning?`Y`:`N`}`),GA({ok:!0,output:ie+`
|
|
187
|
+
`})}catch(e){throw hA.requestsErrored++,e}}if(e.kind===`click`)return GA(await ej(e.verb,e.value));if(e.kind===`debug`){if(!Qk(e.what))return GA({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${Zk.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=TA.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?QA(t.lastRenderCellsBySegment,t.config.globals.charset??`unicode`,t.config.globals.colorCompatibility??`truecolor`):ZA};return GA({ok:!0,debug:Vk(e.what,n)})}return GA({ok:!1,error:`unknown kind`,code:`BAD_REQUEST`,daemonV:3})}function qA(e){let{values:t,tokens:n}=S({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}`))];return{configFile:Uv(t.config),unknownFlagsError:r.length>0?`Unknown flags: ${r.join(`, `)}`:null}}const JA={sessionState:yA,dlog:Y,applyUpdate:()=>kA.act(),doctor:KO()},YA={style:`powerline`,colorCompatibility:`truecolor`,wrap:!0,padding:1,charset:`unicode`},XA={...YA,width:1/0},ZA=new Map;function QA(e,t,n){let r=new Map;for(let[i,a]of e)r.set(i,Fx(a,{...XA,charset:t,colorCompatibility:n}));return r}const $A={gitProvider:_A,usageStore:vA,contextProvider:xA,metricsProvider:SA,activityProvider:CA,tmuxService:wA,log:Y,clock:()=>new Date};function ej(e,t){let n=Fk.get(e);if(!n)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return n(t,JA),{ok:!0,output:``}}catch(e){let t=e instanceof $?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}const tj={connectMs:200,budgetMs:500};async function nj(e){let n=e.includes(`--json`),r=await rj();if(r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${iy(r)}\n`),t.exit(1)),n){t.stdout.write(JSON.stringify(r.value,null,2)+`
|
|
188
|
+
`);return}t.stdout.write(sj(r.value))}function rj(){return Qv({kind:`stats`},tj,e=>`stats`in e?e.stats:void 0)}function ij(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function aj(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function oj(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 sj(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` version ${e.version}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${oj(e.uptimeSec)}`),t.push(` rss ${ij(e.rssBytes)}`),t.push(` heapUsed ${ij(e.heapUsedBytes)}`),t.push(` heapTotal ${ij(e.heapTotalBytes)}`),t.push(` external ${ij(e.externalBytes)}`),t.push(` arrayBuffers ${ij(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 ${aj(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 ${aj(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(`
|
|
189
189
|
`)+`
|
|
190
|
-
`}const
|
|
191
|
-
`);return}t.stdout.write(
|
|
192
|
-
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${
|
|
190
|
+
`}const cj={connectMs:200,budgetMs:500};async function lj(e,n){let r=n.includes(`--json`),i=await uj(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${iy(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
|
|
191
|
+
`);return}t.stdout.write(dj(i.value))}function uj(e){return Qv({kind:`debug`,what:e},cj,e=>`debug`in e?e.debug:void 0)}function dj(e){switch(e.what){case`vars`:return fj(e.vars);case`segments`:return pj(e.segments);case`config`:return mj(e.config);default:return e}}function fj(e){if(e.length===0)return`no variables (DSL not active)
|
|
192
|
+
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${gj(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${hj(a.value)}${e}${o}`)}return t.join(`
|
|
193
193
|
`)+`
|
|
194
|
-
`}function
|
|
194
|
+
`}function pj(e){if(e.length===0)return`no segments (DSL not active)
|
|
195
195
|
`;let t=[`segments (${e.length})`,``];for(let n of e)t.push(` ${n.name}`),n.description!==null&&t.push(` shows ${n.description}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`),n.lastRender!==null&&t.push(` last ${n.lastRender}`);return t.join(`
|
|
196
196
|
`)+`
|
|
197
|
-
`}function
|
|
197
|
+
`}function mj(e){return e===null?`config: DSL not active
|
|
198
198
|
`:JSON.stringify(e,null,2)+`
|
|
199
|
-
`}function
|
|
200
|
-
`));return l.rendered}finally{c.dispose()}}function
|
|
201
|
-
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:
|
|
199
|
+
`}function hj(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function gj(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function _j(){let e=yj();return e===null?null:r.readFileSync(e,`utf-8`)}function vj(){let e;try{e=_j()}catch(e){t.stderr.write(`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`),t.exit(2)}e===null&&(t.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),t.exit(2)),t.stdout.write(e),t.exit(0)}function yj(){let e=c.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let i=c.dirname(c.resolve(n));for(;;){let t=c.join(i,e);if(r.existsSync(t))return t;let n=c.dirname(i);if(n===i)return null;i=n}}function bj(e){let t=e.CC_CANDYBAR_CONFIG??``;return t===``?void 0:t}const xj=5e3;function Sj(e){let t=`/home/tester`,n=Math.floor(Date.now()/1e3);return{hook_event_name:`Status`,session_id:`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,version:`1.15.0`,home:t,cwd:`${t}/code/cc-candybar/src`,transcript_path:`${t}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},workspace:{current_dir:`${t}/code/cc-candybar/src`,project_dir:`${t}/code/cc-candybar`},git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:n+2*3600},weekly:{percentage:21,resetsAt:n+5*86400},cache:{expiresAt:n+900},tmux:{session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},preset:{effective:e.preset,customized:e.presetCustomized},style:{effective:e.style},charset:{effective:e.charset},colorCompatibility:{effective:e.colorCompatibility},autoWrap:{effective:e.autoWrap},padding:{effective:e.padding}}}function Cj(e,t){let n=Dv(e,e),r=kv(n);return r!==null&&t.push(r),n.kind===`file`?n.path:null}async function wj(e,n=t.cwd()){let i=[],a=e===void 0?Cj(n,i):c.resolve(wv(e));if(e!==void 0&&a!==null){let e;try{e=r.statSync(a,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:a,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:a,message:`not a file`}}let o=jv(n,n);o!==null&&i.push(o);try{return{kind:`clean`,configPath:a,warnings:i,rendered:await Tj(a,n,i)}}catch(e){let t=e;return a!==null&&typeof t==`object`&&t&&typeof t.code==`string`&&t.path===a&&typeof t.message==`string`?{kind:`unreadable`,path:a,message:t.message}:(e instanceof _a&&i.push(...e.warnings),{kind:`fatal`,configPath:a,message:e instanceof _a||e instanceof Error?e.message:String(e),warnings:i})}}async function Tj(e,t,n){let{config:r,source:i,warnings:a}=Mv(e,Qw);n.push(...a);let o=Fv(r,e??`<default>`,i),s=new BD,c=new vE(s,o.globals.default_empty_value??``,void 0,new ZD);try{let e=OD(o,c,{cwd:t});n.push(...e.loadWarnings);let r=await c.settled(xj);r.length>0&&n.push(`source${r.length===1?``:`s`} still running after ${xj} ms, rendered with fallback values: ${r.join(`, `)}`),VS(o);let i=ww(o,()=>null,()=>!1),a=t=>{let n=new Map;return{rendered:MD(o,e,s,c,Sj(t),{style:t.style,separator:t.separator,width:200,colorCompatibility:t.colorCompatibility,wrap:t.autoWrap,padding:t.padding,charset:t.charset},{onSegmentError:(e,t)=>n.set(`segment "${e}"`,t),onRenderWarning:e=>n.set(`globals.palette`,e)},{theme:t.theme,look:t.look,preset:t.preset}),failures:n}},l=a(i),u=a({...i,presetCustomized:!0}),d=[...[...l.failures].map(([e,t])=>`${e}: ${t}`),...[...u.failures].filter(([e])=>!l.failures.has(e)).map(([e,t])=>`${e}: ${t} (under .preset.customized = true)`)];if(d.length>0)throw Error(`config renders with ${d.length} render error${d.length===1?``:`s`} (the daemon would show them on the bar):\n`+d.map(e=>` ${e}`).join(`
|
|
200
|
+
`));return l.rendered}finally{c.dispose()}}function Ej(e){return e.map(e=>`warning: ${e}\n`).join(``)}function Dj(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.configPath??`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${e.rendered}\n`:``),stderr:Ej(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:Ej(e.warnings)+`✗ ${e.configPath??`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const Oj=`--render`,kj=`Usage: cc-candybar check [${Oj}] [config-file]\n`;function Aj(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==Oj);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${kj}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${kj}`}:{kind:`run`,target:n[0],render:t.includes(Oj)}}async function jj(e){let n=Aj(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:Dj(await wj(n.target??bj(t.env)),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const Mj=`${Dx}${Ex}`;function Nj(e){return`${Mj}⚠ cc-candybar: ${Pj(e)}[0m\n`}function Pj(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: ${Tx(e.message,60)}`;case`render_failed`:return`render failed: ${Tx(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${Tx(e.message,60)}`}}function Fj(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
|
|
201
|
+
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:Nj(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}function Ij(e,t){if(e!==void 0&&/^\+?\d+$/.test(e)){let t=Number(e);if(t>0&&t<=4294967295)return t}if(t&&t>0)return t}function Lj({check:e,verdict:t}){return t.ok?`✓ ${e.label}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:` (fix: click ☰ 🧰 tools ▸ 🩺 doctor, then [fix] on the bar)`}\n`}function Rj(e,t){let n;try{n=ZO(e,zh(t))}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let r=Hh(n);return{stdout:r.map(Lj).join(``),stderr:``,code:+!r.every(e=>e.verdict.ok)}}function zj(e){e.length>0&&(t.stderr.write(`doctor: takes no arguments
|
|
202
202
|
Usage: cc-candybar doctor
|
|
203
|
-
`),t.exit(2));let n=
|
|
203
|
+
`),t.exit(2));let n=Rj(KO(),t.env);t.stdout.write(n.stdout),t.stderr.write(n.stderr),t.exit(n.code)}function Bj(){return Ij(t.env.COLUMNS,t.stderr.columns)}function Vj(){return Ij(t.env.LINES,t.stderr.rows)}const Hj=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`],Uj=e=>e.some(e=>t.argv.includes(e));function Wj(){return Hj.some(e=>(t.env[e]??``)!==``)}function Gj(){console.log(Th)}async function Kj(){try{Uj(Sh.help)&&(Gj(),t.exit(0)),Uj(Sh.version)&&(console.log(`cc-candybar ${vb}`),t.exit(0));let e=t.argv[2];if(e===`install`&&(await Qb(t.argv.slice(3)),t.exit(0)),e===`install-url-handler`&&(qb(),t.exit(0)),e===`url-handle`){await Yb(t.argv[3]);return}if(e===`daemon`){NA();return}if(e===`daemon-stats`&&(await nj(t.argv.slice(3)),t.exit(0)),e===`check`||e===`lint`){await jj(t.argv.slice(3));return}if(e===`schema`){vj();return}if(e===`doctor`){zj(t.argv.slice(3));return}Qk(e)&&(await lj(e,t.argv.slice(3)),t.exit(0)),t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
204
204
|
|
|
205
205
|
cc-candybar is designed to be used as a Claude Code statusLine command.
|
|
206
206
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -216,4 +216,4 @@ Add to ~/.claude/settings.json:
|
|
|
216
216
|
Run with --help for more options.
|
|
217
217
|
|
|
218
218
|
To test output manually:
|
|
219
|
-
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),t.exit(1)),E(`Working directory: ${t.cwd()}`),E(`Process args:`,t.argv);let r=await n(t.stdin);E(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),
|
|
219
|
+
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar --style=powerline`),t.exit(1)),E(`Working directory: ${t.cwd()}`),E(`Process args:`,t.argv);let r=await n(t.stdin);E(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),Gj(),t.exit(1));let i=Fj(await cy(r,t.argv,t.cwd(),{termCols:Bj(),termRows:Vj(),ssh:Wj(),tmux:zh(t.env),configEnv:bj(t.env)}));i.debug!==null&&E(i.debug),i.kick&&jy(),t.stdout.write(i.output),t.exit(0)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error generating statusline:`,n),t.exit(1)}}Kj();export{};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@promptctl/cc-candybar",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.72.0",
|
|
4
4
|
"description": "Statusline renderer for Claude Code — a JSON5-configurable DSL with daemon-cached data sources, byte-clean palette-aware composition, and OSC8 click verbs.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.mjs",
|
|
@@ -90,9 +90,9 @@
|
|
|
90
90
|
"mobx": "^6.15.0"
|
|
91
91
|
},
|
|
92
92
|
"optionalDependencies": {
|
|
93
|
-
"@promptctl/cc-candybar-darwin-arm64": "1.
|
|
94
|
-
"@promptctl/cc-candybar-darwin-x64": "1.
|
|
95
|
-
"@promptctl/cc-candybar-linux-x64": "1.
|
|
96
|
-
"@promptctl/cc-candybar-linux-arm64": "1.
|
|
93
|
+
"@promptctl/cc-candybar-darwin-arm64": "1.72.0",
|
|
94
|
+
"@promptctl/cc-candybar-darwin-x64": "1.72.0",
|
|
95
|
+
"@promptctl/cc-candybar-linux-x64": "1.72.0",
|
|
96
|
+
"@promptctl/cc-candybar-linux-arm64": "1.72.0"
|
|
97
97
|
}
|
|
98
98
|
}
|