typebulb 0.23.0 → 0.23.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -9,8 +9,8 @@ ${s}
9
9
  ${o}`});return["---",`format: ${vl}`,`name: ${Qi(r.name)}`,"---","",...e].join(`
10
10
  `)}var Ol=R(()=>{On();Rn()});function Rl(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}var _l=R(()=>{});var Cl=R(()=>{});function Zi(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index:-1}var Nl=R(()=>{});function br(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index+s[0].length-1:-1}var Il=R(()=>{});function _n(r,e){let t=new RegExp(e,"g"),n=r.match(t);return n?n.length:0}var Ll=R(()=>{});function wr(r,e,t){let n=t&&t.debug||!1,s=!(t&&typeof t.nested===!1),i=t&&t.startIndex||0;n&&console.log("[xml-utils] starting findTagByName with",e," and ",t);let o=Zi(r,`<${e}[
11
11
  >/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=br(a,"^[^<]*[ /]>",0),l=c!==-1&&a[c-1]==="/";if(n&&console.log("[xml-utils] selfClosing:",l),l===!1)if(s){let p=0,b=1,m=0;for(;(c=br(a,"[ /]"+e+">",p))!==-1;){let y=a.substring(p,c+1);if(b+=_n(y,"<"+e+`[
12
- >]`),m+=_n(y,"</"+e+">"),m>=b)break;p=c}}else c=br(a,"[ /]"+e+">",0);let f=o+e.length+c+1;if(n&&console.log("[xml-utils] end:",f),f===-1)return;let u=r.slice(o,f),d;return l?d=null:d=u.slice(u.indexOf(">")+1,u.lastIndexOf("<")),{inner:d,outer:u,start:o,end:f}}var eo=R(()=>{Nl();Il();Ll()});var to=R(()=>{eo()});var ro=R(()=>{to()});var $l=R(()=>{ro()});var Ml=R(()=>{});var Dl=R(()=>{Cl();eo();to();$l();ro();Ml()});var I=P(z=>{"use strict";var no=Symbol.for("yaml.alias"),Bl=Symbol.for("yaml.document"),Cn=Symbol.for("yaml.map"),jl=Symbol.for("yaml.pair"),so=Symbol.for("yaml.scalar"),Nn=Symbol.for("yaml.seq"),Te=Symbol.for("yaml.node.type"),kg=r=>!!r&&typeof r=="object"&&r[Te]===no,xg=r=>!!r&&typeof r=="object"&&r[Te]===Bl,Eg=r=>!!r&&typeof r=="object"&&r[Te]===Cn,Ag=r=>!!r&&typeof r=="object"&&r[Te]===jl,Fl=r=>!!r&&typeof r=="object"&&r[Te]===so,Tg=r=>!!r&&typeof r=="object"&&r[Te]===Nn;function ql(r){if(r&&typeof r=="object")switch(r[Te]){case Cn:case Nn:return!0}return!1}function Pg(r){if(r&&typeof r=="object")switch(r[Te]){case no:case Cn:case so:case Nn:return!0}return!1}var Og=r=>(Fl(r)||ql(r))&&!!r.anchor;z.ALIAS=no;z.DOC=Bl;z.MAP=Cn;z.NODE_TYPE=Te;z.PAIR=jl;z.SCALAR=so;z.SEQ=Nn;z.hasAnchor=Og;z.isAlias=kg;z.isCollection=ql;z.isDocument=xg;z.isMap=Eg;z.isNode=Pg;z.isPair=Ag;z.isScalar=Fl;z.isSeq=Tg});var vr=P(io=>{"use strict";var H=I(),re=Symbol("break visit"),Ul=Symbol("skip children"),be=Symbol("remove node");function In(r,e){let t=Jl(e);H.isDocument(r)?$t(null,r.contents,t,Object.freeze([r]))===be&&(r.contents=null):$t(null,r,t,Object.freeze([]))}In.BREAK=re;In.SKIP=Ul;In.REMOVE=be;function $t(r,e,t,n){let s=Kl(r,e,t,n);if(H.isNode(s)||H.isPair(s))return Wl(r,n,s),$t(r,s,t,n);if(typeof s!="symbol"){if(H.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=$t(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===re)return re;o===be&&(e.items.splice(i,1),i-=1)}}}else if(H.isPair(e)){n=Object.freeze(n.concat(e));let i=$t("key",e.key,t,n);if(i===re)return re;i===be&&(e.key=null);let o=$t("value",e.value,t,n);if(o===re)return re;o===be&&(e.value=null)}}return s}async function Ln(r,e){let t=Jl(e);H.isDocument(r)?await Mt(null,r.contents,t,Object.freeze([r]))===be&&(r.contents=null):await Mt(null,r,t,Object.freeze([]))}Ln.BREAK=re;Ln.SKIP=Ul;Ln.REMOVE=be;async function Mt(r,e,t,n){let s=await Kl(r,e,t,n);if(H.isNode(s)||H.isPair(s))return Wl(r,n,s),Mt(r,s,t,n);if(typeof s!="symbol"){if(H.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=await Mt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===re)return re;o===be&&(e.items.splice(i,1),i-=1)}}}else if(H.isPair(e)){n=Object.freeze(n.concat(e));let i=await Mt("key",e.key,t,n);if(i===re)return re;i===be&&(e.key=null);let o=await Mt("value",e.value,t,n);if(o===re)return re;o===be&&(e.value=null)}}return s}function Jl(r){return typeof r=="object"&&(r.Collection||r.Node||r.Value)?Object.assign({Alias:r.Node,Map:r.Node,Scalar:r.Node,Seq:r.Node},r.Value&&{Map:r.Value,Scalar:r.Value,Seq:r.Value},r.Collection&&{Map:r.Collection,Seq:r.Collection},r):r}function Kl(r,e,t,n){if(typeof t=="function")return t(r,e,n);if(H.isMap(e))return t.Map?.(r,e,n);if(H.isSeq(e))return t.Seq?.(r,e,n);if(H.isPair(e))return t.Pair?.(r,e,n);if(H.isScalar(e))return t.Scalar?.(r,e,n);if(H.isAlias(e))return t.Alias?.(r,e,n)}function Wl(r,e,t){let n=e[e.length-1];if(H.isCollection(n))n.items[r]=t;else if(H.isPair(n))r==="key"?n.key=t:n.value=t;else if(H.isDocument(n))n.contents=t;else{let s=H.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}io.visit=In;io.visitAsync=Ln});var oo=P(Vl=>{"use strict";var Hl=I(),Rg=vr(),_g={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Cg=r=>r.replace(/[!,[\]{}]/g,e=>_g[e]),Sr=class r{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),s=n.shift();switch(s){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${s}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,n,s]=e.match(/^(.*!)([^!]*)$/s);s||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(s)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Cg(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),s;if(e&&n.length>0&&Hl.isNode(e.contents)){let i={};Rg.visit(e.contents,(o,a)=>{Hl.isNode(a)&&a.tag&&(i[a.tag]=!0)}),s=Object.keys(i)}else s=[];for(let[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||s.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
13
- `)}};Sr.defaultYaml={explicit:!1,version:"1.2"};Sr.defaultTags={"!!":"tag:yaml.org,2002:"};Vl.Directives=Sr});var $n=P(kr=>{"use strict";var Yl=I(),Ng=vr();function Ig(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function Gl(r){let e=new Set;return Ng.visit(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function zl(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function Lg(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s??(s=Gl(r));let o=zl(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(Yl.isScalar(o.node)||Yl.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:n}}kr.anchorIsValid=Ig;kr.anchorNames=Gl;kr.createNodeAnchors=Lg;kr.findNewAnchor=zl});var ao=P(Ql=>{"use strict";function xr(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let s=0,i=n.length;s<i;++s){let o=n[s],a=xr(r,n,String(s),o);a===void 0?delete n[s]:a!==o&&(n[s]=a)}else if(n instanceof Map)for(let s of Array.from(n.keys())){let i=n.get(s),o=xr(r,n,s,i);o===void 0?n.delete(s):o!==i&&n.set(s,o)}else if(n instanceof Set)for(let s of Array.from(n)){let i=xr(r,n,s,s);i===void 0?n.delete(s):i!==s&&(n.delete(s),n.add(i))}else for(let[s,i]of Object.entries(n)){let o=xr(r,n,s,i);o===void 0?delete n[s]:o!==i&&(n[s]=o)}return r.call(e,t,n)}Ql.applyReviver=xr});var je=P(Zl=>{"use strict";var $g=I();function Xl(r,e,t){if(Array.isArray(r))return r.map((n,s)=>Xl(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!$g.hasAnchor(r))return r.toJSON(e,t);let n={aliasCount:0,count:1,res:void 0};t.anchors.set(r,n),t.onCreate=i=>{n.res=i,delete t.onCreate};let s=r.toJSON(e,t);return t.onCreate&&t.onCreate(s),s}return typeof r=="bigint"&&!t?.keep?Number(r):r}Zl.toJS=Xl});var Mn=P(tu=>{"use strict";var Mg=ao(),eu=I(),Dg=je(),co=class{constructor(e){Object.defineProperty(this,eu.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:s,reviver:i}={}){if(!eu.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=Dg.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?Mg.applyReviver(i,{"":a},"",a):a}};tu.NodeBase=co});var Er=P(ru=>{"use strict";var Bg=$n(),jg=vr(),Dt=I(),Fg=Mn(),qg=je(),lo=class extends Fg.NodeBase{constructor(e){super(Dt.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],jg.visit(e,{Node:(i,o)=>{(Dt.isAlias(o)||Dt.hasAnchor(o))&&n.push(o)}}),t&&(t.aliasResolveCache=n));let s;for(let i of n){if(i===this)break;i.anchor===this.source&&(s=i)}return s}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:s,maxAliasCount:i}=t,o=this.resolve(s,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(qg.toJS(o,null,t),a=n.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Dn(s,o,n)),a.count*a.aliasCount>i)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){let s=`*${this.source}`;if(e){if(Bg.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${s} `}return s}};function Dn(r,e,t){if(Dt.isAlias(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(Dt.isCollection(e)){let n=0;for(let s of e.items){let i=Dn(r,s,t);i>n&&(n=i)}return n}else if(Dt.isPair(e)){let n=Dn(r,e.key,t),s=Dn(r,e.value,t);return Math.max(n,s)}return 1}ru.Alias=lo});var J=P(uo=>{"use strict";var Ug=I(),Jg=Mn(),Kg=je(),Wg=r=>!r||typeof r!="function"&&typeof r!="object",Fe=class extends Jg.NodeBase{constructor(e){super(Ug.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:Kg.toJS(this.value,e,t)}toString(){return String(this.value)}};Fe.BLOCK_FOLDED="BLOCK_FOLDED";Fe.BLOCK_LITERAL="BLOCK_LITERAL";Fe.PLAIN="PLAIN";Fe.QUOTE_DOUBLE="QUOTE_DOUBLE";Fe.QUOTE_SINGLE="QUOTE_SINGLE";uo.Scalar=Fe;uo.isScalarValue=Wg});var Ar=P(su=>{"use strict";var Hg=Er(),ot=I(),nu=J(),Vg="tag:yaml.org,2002:";function Yg(r,e,t){if(e){let n=t.filter(i=>i.tag===e),s=n.find(i=>!i.format)??n[0];if(!s)throw new Error(`Tag ${e} not found`);return s}return t.find(n=>n.identify?.(r)&&!n.format)}function Gg(r,e,t){if(ot.isDocument(r)&&(r=r.contents),ot.isNode(r))return r;if(ot.isPair(r)){let u=t.schema[ot.MAP].createNode?.(t.schema,null,t);return u.items.push(r),u}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt<"u"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:s,onTagObj:i,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return c.anchor??(c.anchor=s(r)),new Hg.Alias(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=Vg+e.slice(2));let l=Yg(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new nu.Scalar(r);return c&&(c.node=u),u}l=r instanceof Map?o[ot.MAP]:Symbol.iterator in Object(r)?o[ot.SEQ]:o[ot.MAP]}i&&(i(l),delete t.onTagObj);let f=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new nu.Scalar(r);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}su.createNode=Gg});var jn=P(Bn=>{"use strict";var zg=Ar(),we=I(),Qg=Mn();function fo(r,e,t){let n=t;for(let s=e.length-1;s>=0;--s){let i=e[s];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=n,n=o}else n=new Map([[i,n]])}return zg.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:r,sourceObjects:new Map})}var iu=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,po=class extends Qg.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>we.isNode(n)||we.isPair(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(iu(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(we.isCollection(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,fo(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let s=this.get(t,!0);if(we.isCollection(s))return s.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...s]=e,i=this.get(n,!0);return s.length===0?!t&&we.isScalar(i)?i.value:i:we.isCollection(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!we.isPair(t))return!1;let n=t.value;return n==null||e&&we.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let s=this.get(t,!0);return we.isCollection(s)?s.hasIn(n):!1}setIn(e,t){let[n,...s]=e;if(s.length===0)this.set(n,t);else{let i=this.get(n,!0);if(we.isCollection(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,fo(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};Bn.Collection=po;Bn.collectionFromPath=fo;Bn.isEmptyPath=iu});var Tr=P(Fn=>{"use strict";var Xg=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function mo(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var Zg=(r,e,t)=>r.endsWith(`
12
+ >]`),m+=_n(y,"</"+e+">"),m>=b)break;p=c}}else c=br(a,"[ /]"+e+">",0);let f=o+e.length+c+1;if(n&&console.log("[xml-utils] end:",f),f===-1)return;let u=r.slice(o,f),d;return l?d=null:d=u.slice(u.indexOf(">")+1,u.lastIndexOf("<")),{inner:d,outer:u,start:o,end:f}}var eo=R(()=>{Nl();Il();Ll()});var to=R(()=>{eo()});var ro=R(()=>{to()});var Ml=R(()=>{ro()});var $l=R(()=>{});var Dl=R(()=>{Cl();eo();to();Ml();ro();$l()});var I=P(z=>{"use strict";var no=Symbol.for("yaml.alias"),Bl=Symbol.for("yaml.document"),Cn=Symbol.for("yaml.map"),jl=Symbol.for("yaml.pair"),so=Symbol.for("yaml.scalar"),Nn=Symbol.for("yaml.seq"),Te=Symbol.for("yaml.node.type"),kg=r=>!!r&&typeof r=="object"&&r[Te]===no,xg=r=>!!r&&typeof r=="object"&&r[Te]===Bl,Eg=r=>!!r&&typeof r=="object"&&r[Te]===Cn,Ag=r=>!!r&&typeof r=="object"&&r[Te]===jl,Fl=r=>!!r&&typeof r=="object"&&r[Te]===so,Tg=r=>!!r&&typeof r=="object"&&r[Te]===Nn;function ql(r){if(r&&typeof r=="object")switch(r[Te]){case Cn:case Nn:return!0}return!1}function Pg(r){if(r&&typeof r=="object")switch(r[Te]){case no:case Cn:case so:case Nn:return!0}return!1}var Og=r=>(Fl(r)||ql(r))&&!!r.anchor;z.ALIAS=no;z.DOC=Bl;z.MAP=Cn;z.NODE_TYPE=Te;z.PAIR=jl;z.SCALAR=so;z.SEQ=Nn;z.hasAnchor=Og;z.isAlias=kg;z.isCollection=ql;z.isDocument=xg;z.isMap=Eg;z.isNode=Pg;z.isPair=Ag;z.isScalar=Fl;z.isSeq=Tg});var vr=P(io=>{"use strict";var H=I(),re=Symbol("break visit"),Ul=Symbol("skip children"),be=Symbol("remove node");function In(r,e){let t=Jl(e);H.isDocument(r)?Mt(null,r.contents,t,Object.freeze([r]))===be&&(r.contents=null):Mt(null,r,t,Object.freeze([]))}In.BREAK=re;In.SKIP=Ul;In.REMOVE=be;function Mt(r,e,t,n){let s=Kl(r,e,t,n);if(H.isNode(s)||H.isPair(s))return Wl(r,n,s),Mt(r,s,t,n);if(typeof s!="symbol"){if(H.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=Mt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===re)return re;o===be&&(e.items.splice(i,1),i-=1)}}}else if(H.isPair(e)){n=Object.freeze(n.concat(e));let i=Mt("key",e.key,t,n);if(i===re)return re;i===be&&(e.key=null);let o=Mt("value",e.value,t,n);if(o===re)return re;o===be&&(e.value=null)}}return s}async function Ln(r,e){let t=Jl(e);H.isDocument(r)?await $t(null,r.contents,t,Object.freeze([r]))===be&&(r.contents=null):await $t(null,r,t,Object.freeze([]))}Ln.BREAK=re;Ln.SKIP=Ul;Ln.REMOVE=be;async function $t(r,e,t,n){let s=await Kl(r,e,t,n);if(H.isNode(s)||H.isPair(s))return Wl(r,n,s),$t(r,s,t,n);if(typeof s!="symbol"){if(H.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=await $t(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===re)return re;o===be&&(e.items.splice(i,1),i-=1)}}}else if(H.isPair(e)){n=Object.freeze(n.concat(e));let i=await $t("key",e.key,t,n);if(i===re)return re;i===be&&(e.key=null);let o=await $t("value",e.value,t,n);if(o===re)return re;o===be&&(e.value=null)}}return s}function Jl(r){return typeof r=="object"&&(r.Collection||r.Node||r.Value)?Object.assign({Alias:r.Node,Map:r.Node,Scalar:r.Node,Seq:r.Node},r.Value&&{Map:r.Value,Scalar:r.Value,Seq:r.Value},r.Collection&&{Map:r.Collection,Seq:r.Collection},r):r}function Kl(r,e,t,n){if(typeof t=="function")return t(r,e,n);if(H.isMap(e))return t.Map?.(r,e,n);if(H.isSeq(e))return t.Seq?.(r,e,n);if(H.isPair(e))return t.Pair?.(r,e,n);if(H.isScalar(e))return t.Scalar?.(r,e,n);if(H.isAlias(e))return t.Alias?.(r,e,n)}function Wl(r,e,t){let n=e[e.length-1];if(H.isCollection(n))n.items[r]=t;else if(H.isPair(n))r==="key"?n.key=t:n.value=t;else if(H.isDocument(n))n.contents=t;else{let s=H.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}io.visit=In;io.visitAsync=Ln});var oo=P(Vl=>{"use strict";var Hl=I(),Rg=vr(),_g={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Cg=r=>r.replace(/[!,[\]{}]/g,e=>_g[e]),Sr=class r{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),s=n.shift();switch(s){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${s}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,n,s]=e.match(/^(.*!)([^!]*)$/s);s||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(s)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Cg(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),s;if(e&&n.length>0&&Hl.isNode(e.contents)){let i={};Rg.visit(e.contents,(o,a)=>{Hl.isNode(a)&&a.tag&&(i[a.tag]=!0)}),s=Object.keys(i)}else s=[];for(let[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||s.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
13
+ `)}};Sr.defaultYaml={explicit:!1,version:"1.2"};Sr.defaultTags={"!!":"tag:yaml.org,2002:"};Vl.Directives=Sr});var Mn=P(kr=>{"use strict";var Yl=I(),Ng=vr();function Ig(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function Gl(r){let e=new Set;return Ng.visit(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function zl(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function Lg(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s??(s=Gl(r));let o=zl(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(Yl.isScalar(o.node)||Yl.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:n}}kr.anchorIsValid=Ig;kr.anchorNames=Gl;kr.createNodeAnchors=Lg;kr.findNewAnchor=zl});var ao=P(Ql=>{"use strict";function xr(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let s=0,i=n.length;s<i;++s){let o=n[s],a=xr(r,n,String(s),o);a===void 0?delete n[s]:a!==o&&(n[s]=a)}else if(n instanceof Map)for(let s of Array.from(n.keys())){let i=n.get(s),o=xr(r,n,s,i);o===void 0?n.delete(s):o!==i&&n.set(s,o)}else if(n instanceof Set)for(let s of Array.from(n)){let i=xr(r,n,s,s);i===void 0?n.delete(s):i!==s&&(n.delete(s),n.add(i))}else for(let[s,i]of Object.entries(n)){let o=xr(r,n,s,i);o===void 0?delete n[s]:o!==i&&(n[s]=o)}return r.call(e,t,n)}Ql.applyReviver=xr});var je=P(Zl=>{"use strict";var Mg=I();function Xl(r,e,t){if(Array.isArray(r))return r.map((n,s)=>Xl(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!Mg.hasAnchor(r))return r.toJSON(e,t);let n={aliasCount:0,count:1,res:void 0};t.anchors.set(r,n),t.onCreate=i=>{n.res=i,delete t.onCreate};let s=r.toJSON(e,t);return t.onCreate&&t.onCreate(s),s}return typeof r=="bigint"&&!t?.keep?Number(r):r}Zl.toJS=Xl});var $n=P(tu=>{"use strict";var $g=ao(),eu=I(),Dg=je(),co=class{constructor(e){Object.defineProperty(this,eu.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:s,reviver:i}={}){if(!eu.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=Dg.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?$g.applyReviver(i,{"":a},"",a):a}};tu.NodeBase=co});var Er=P(ru=>{"use strict";var Bg=Mn(),jg=vr(),Dt=I(),Fg=$n(),qg=je(),lo=class extends Fg.NodeBase{constructor(e){super(Dt.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],jg.visit(e,{Node:(i,o)=>{(Dt.isAlias(o)||Dt.hasAnchor(o))&&n.push(o)}}),t&&(t.aliasResolveCache=n));let s;for(let i of n){if(i===this)break;i.anchor===this.source&&(s=i)}return s}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:s,maxAliasCount:i}=t,o=this.resolve(s,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(qg.toJS(o,null,t),a=n.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Dn(s,o,n)),a.count*a.aliasCount>i)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){let s=`*${this.source}`;if(e){if(Bg.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${s} `}return s}};function Dn(r,e,t){if(Dt.isAlias(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(Dt.isCollection(e)){let n=0;for(let s of e.items){let i=Dn(r,s,t);i>n&&(n=i)}return n}else if(Dt.isPair(e)){let n=Dn(r,e.key,t),s=Dn(r,e.value,t);return Math.max(n,s)}return 1}ru.Alias=lo});var J=P(uo=>{"use strict";var Ug=I(),Jg=$n(),Kg=je(),Wg=r=>!r||typeof r!="function"&&typeof r!="object",Fe=class extends Jg.NodeBase{constructor(e){super(Ug.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:Kg.toJS(this.value,e,t)}toString(){return String(this.value)}};Fe.BLOCK_FOLDED="BLOCK_FOLDED";Fe.BLOCK_LITERAL="BLOCK_LITERAL";Fe.PLAIN="PLAIN";Fe.QUOTE_DOUBLE="QUOTE_DOUBLE";Fe.QUOTE_SINGLE="QUOTE_SINGLE";uo.Scalar=Fe;uo.isScalarValue=Wg});var Ar=P(su=>{"use strict";var Hg=Er(),ot=I(),nu=J(),Vg="tag:yaml.org,2002:";function Yg(r,e,t){if(e){let n=t.filter(i=>i.tag===e),s=n.find(i=>!i.format)??n[0];if(!s)throw new Error(`Tag ${e} not found`);return s}return t.find(n=>n.identify?.(r)&&!n.format)}function Gg(r,e,t){if(ot.isDocument(r)&&(r=r.contents),ot.isNode(r))return r;if(ot.isPair(r)){let u=t.schema[ot.MAP].createNode?.(t.schema,null,t);return u.items.push(r),u}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt<"u"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:s,onTagObj:i,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return c.anchor??(c.anchor=s(r)),new Hg.Alias(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=Vg+e.slice(2));let l=Yg(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new nu.Scalar(r);return c&&(c.node=u),u}l=r instanceof Map?o[ot.MAP]:Symbol.iterator in Object(r)?o[ot.SEQ]:o[ot.MAP]}i&&(i(l),delete t.onTagObj);let f=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new nu.Scalar(r);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}su.createNode=Gg});var jn=P(Bn=>{"use strict";var zg=Ar(),we=I(),Qg=$n();function fo(r,e,t){let n=t;for(let s=e.length-1;s>=0;--s){let i=e[s];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=n,n=o}else n=new Map([[i,n]])}return zg.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:r,sourceObjects:new Map})}var iu=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,po=class extends Qg.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>we.isNode(n)||we.isPair(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(iu(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(we.isCollection(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,fo(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let s=this.get(t,!0);if(we.isCollection(s))return s.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...s]=e,i=this.get(n,!0);return s.length===0?!t&&we.isScalar(i)?i.value:i:we.isCollection(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!we.isPair(t))return!1;let n=t.value;return n==null||e&&we.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let s=this.get(t,!0);return we.isCollection(s)?s.hasIn(n):!1}setIn(e,t){let[n,...s]=e;if(s.length===0)this.set(n,t);else{let i=this.get(n,!0);if(we.isCollection(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,fo(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};Bn.Collection=po;Bn.collectionFromPath=fo;Bn.isEmptyPath=iu});var Tr=P(Fn=>{"use strict";var Xg=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function mo(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var Zg=(r,e,t)=>r.endsWith(`
14
14
  `)?mo(t,e):t.includes(`
15
15
  `)?`
16
16
  `+mo(t,e):(r.endsWith(" ")?"":" ")+t;Fn.indentComment=mo;Fn.lineComment=Zg;Fn.stringifyComment=Xg});var au=P(Pr=>{"use strict";var ey="flow",ho="block",qn="quoted";function ty(r,e,t="flow",{indentAtStart:n,lineWidth:s=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!s||s<0)return r;s<i&&(i=0);let c=Math.max(1+i,1+s-e.length);if(r.length<=c)return r;let l=[],f={},u=s-e.length;typeof n=="number"&&(n>s-Math.max(2,i)?l.push(0):u=s-n);let d,p,b=!1,m=-1,y=-1,E=-1;t===ho&&(m=ou(r,m,e.length),m!==-1&&(u=m+c));for(let g;g=r[m+=1];){if(t===qn&&g==="\\"){switch(y=m,r[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}E=m}if(g===`
@@ -41,7 +41,7 @@ ${l}${T}${t}${p}`}function ny(r,e,t,n){let{type:s,value:i}=r,{actualString:o,imp
41
41
  `)||f&&/[[\]{},]/.test(i))return Bt(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||f||!i.includes(`
42
42
  `)?Bt(i,e):Un(r,e,t,n);if(!a&&!f&&s!==le.Scalar.PLAIN&&i.includes(`
43
43
  `))return Un(r,e,t,n);if(Kn(i)){if(c==="")return e.forceBlockIndent=!0,Un(r,e,t,n);if(a&&c===l)return Bt(i,e)}let u=i.replace(/\n+/g,`$&
44
- ${c}`);if(o){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(u),{compat:p,tags:b}=e.doc.schema;if(b.some(d)||p?.some(d))return Bt(i,e)}return a?u:qe.foldFlowLines(u,c,qe.FOLD_FLOW,Jn(e,!1))}function sy(r,e,t,n){let{implicitKey:s,inFlow:i}=e,o=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==le.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=le.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case le.Scalar.BLOCK_FOLDED:case le.Scalar.BLOCK_LITERAL:return s||i?Bt(o.value,e):Un(o,e,t,n);case le.Scalar.QUOTE_DOUBLE:return Or(o.value,e);case le.Scalar.QUOTE_SINGLE:return go(o.value,e);case le.Scalar.PLAIN:return ny(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=s&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}cu.stringifyString=sy});var _r=P(bo=>{"use strict";var iy=$n(),Ue=I(),oy=Tr(),ay=Rr();function cy(r,e){let t=Object.assign({blockQuote:!0,commentString:oy.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},r.schema.toStringOptions,e),n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}function ly(r,e){if(e.tag){let s=r.filter(i=>i.tag===e.tag);if(s.length>0)return s.find(i=>i.format===e.format)??s[0]}let t,n;if(Ue.isScalar(e)){n=e.value;let s=r.filter(i=>i.identify?.(n));if(s.length>1){let i=s.filter(o=>o.test);i.length>0&&(s=i)}t=s.find(i=>i.format===e.format)??s.find(i=>!i.format)}else n=e,t=r.find(s=>s.nodeClass&&n instanceof s.nodeClass);if(!t){let s=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${s} value`)}return t}function uy(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],i=(Ue.isScalar(r)||Ue.isCollection(r))&&r.anchor;i&&iy.anchorIsValid(i)&&(t.add(i),s.push(`&${i}`));let o=r.tag??(e.default?null:e.tag);return o&&s.push(n.directives.tagString(o)),s.join(" ")}function fy(r,e,t,n){if(Ue.isPair(r))return r.toString(e,t,n);if(Ue.isAlias(r)){if(e.doc.directives)return r.toString(e);if(e.resolvedAliases?.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let s,i=Ue.isNode(r)?r:e.doc.createNode(r,{onTagObj:c=>s=c});s??(s=ly(e.doc.schema.tags,i));let o=uy(i,s,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof s.stringify=="function"?s.stringify(i,e,t,n):Ue.isScalar(i)?ay.stringifyString(i,e,t,n):i.toString(e,t,n);return o?Ue.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
44
+ ${c}`);if(o){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(u),{compat:p,tags:b}=e.doc.schema;if(b.some(d)||p?.some(d))return Bt(i,e)}return a?u:qe.foldFlowLines(u,c,qe.FOLD_FLOW,Jn(e,!1))}function sy(r,e,t,n){let{implicitKey:s,inFlow:i}=e,o=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==le.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=le.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case le.Scalar.BLOCK_FOLDED:case le.Scalar.BLOCK_LITERAL:return s||i?Bt(o.value,e):Un(o,e,t,n);case le.Scalar.QUOTE_DOUBLE:return Or(o.value,e);case le.Scalar.QUOTE_SINGLE:return go(o.value,e);case le.Scalar.PLAIN:return ny(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=s&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}cu.stringifyString=sy});var _r=P(bo=>{"use strict";var iy=Mn(),Ue=I(),oy=Tr(),ay=Rr();function cy(r,e){let t=Object.assign({blockQuote:!0,commentString:oy.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},r.schema.toStringOptions,e),n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}function ly(r,e){if(e.tag){let s=r.filter(i=>i.tag===e.tag);if(s.length>0)return s.find(i=>i.format===e.format)??s[0]}let t,n;if(Ue.isScalar(e)){n=e.value;let s=r.filter(i=>i.identify?.(n));if(s.length>1){let i=s.filter(o=>o.test);i.length>0&&(s=i)}t=s.find(i=>i.format===e.format)??s.find(i=>!i.format)}else n=e,t=r.find(s=>s.nodeClass&&n instanceof s.nodeClass);if(!t){let s=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${s} value`)}return t}function uy(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],i=(Ue.isScalar(r)||Ue.isCollection(r))&&r.anchor;i&&iy.anchorIsValid(i)&&(t.add(i),s.push(`&${i}`));let o=r.tag??(e.default?null:e.tag);return o&&s.push(n.directives.tagString(o)),s.join(" ")}function fy(r,e,t,n){if(Ue.isPair(r))return r.toString(e,t,n);if(Ue.isAlias(r)){if(e.doc.directives)return r.toString(e);if(e.resolvedAliases?.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let s,i=Ue.isNode(r)?r:e.doc.createNode(r,{onTagObj:c=>s=c});s??(s=ly(e.doc.schema.tags,i));let o=uy(i,s,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof s.stringify=="function"?s.stringify(i,e,t,n):Ue.isScalar(i)?ay.stringifyString(i,e,t,n):i.toString(e,t,n);return o?Ue.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
45
45
  ${e.indent}${a}`:a}bo.createStringifyContext=cy;bo.stringify=fy});var du=P(fu=>{"use strict";var Pe=I(),lu=J(),uu=_r(),Cr=Tr();function dy({key:r,value:e},t,n,s){let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=t,d=Pe.isNode(r)&&r.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Pe.isCollection(r)||!Pe.isNode(r)&&typeof r=="object"){let O="With simple keys, collection cannot be used as a key value";throw new Error(O)}}let p=!u&&(!r||d&&e==null&&!t.inFlow||Pe.isCollection(r)||(Pe.isScalar(r)?r.type===lu.Scalar.BLOCK_FOLDED||r.type===lu.Scalar.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!i),indent:a+c});let b=!1,m=!1,y=uu.stringify(r,t,()=>b=!0,()=>m=!0);if(!p&&!t.inFlow&&y.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(i||e==null)return b&&n&&n(),y===""?"?":p?`? ${y}`:y}else if(i&&!u||e==null&&p)return y=`? ${y}`,d&&!b?y+=Cr.lineComment(y,t.indent,l(d)):m&&s&&s(),y;b&&(d=null),p?(d&&(y+=Cr.lineComment(y,t.indent,l(d))),y=`? ${y}
46
46
  ${a}:`):(y=`${y}:`,d&&(y+=Cr.lineComment(y,t.indent,l(d))));let E,T,g;Pe.isNode(e)?(E=!!e.spaceBefore,T=e.commentBefore,g=e.comment):(E=!1,T=null,g=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!d&&Pe.isScalar(e)&&(t.indentAtStart=y.length+1),m=!1,!f&&c.length>=2&&!t.inFlow&&!p&&Pe.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let w=!1,S=uu.stringify(e,t,()=>w=!0,()=>m=!0),x=" ";if(d||E||T){if(x=E?`
47
47
  `:"",T){let O=l(T);x+=`
@@ -59,13 +59,13 @@ ${c}${m}`:`
59
59
  `))&&(l=!0),u.push(E),f=u.length}let{start:d,end:p}=t;if(u.length===0)return d+p;if(!l){let b=u.reduce((m,y)=>m+y.length+2,2);l=e.options.lineWidth>0&&b>e.options.lineWidth}if(l){let b=d;for(let m of u)b+=m?`
60
60
  ${i}${s}${m}`:`
61
61
  `;return`${b}
62
- ${s}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function Xn({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=Qn.indentComment(e(n),r);t.push(i.trimStart())}}Su.stringifyCollection=xy});var We=P(Po=>{"use strict";var Ty=Ao(),Py=xo(),Oy=jn(),Ke=I(),Zn=Je(),Ry=J();function Ir(r,e){let t=Ke.isScalar(e)?e.value:e;for(let n of r)if(Ke.isPair(n)&&(n.key===e||n.key===t||Ke.isScalar(n.key)&&n.key.value===t))return n}var To=class extends Oy.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ke.MAP,e),this.items=[]}static from(e,t,n){let{keepUndefined:s,replacer:i}=n,o=new this(e),a=(c,l)=>{if(typeof i=="function")l=i.call(t,c,l);else if(Array.isArray(i)&&!i.includes(c))return;(l!==void 0||s)&&o.items.push(Zn.createPair(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;Ke.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Zn.Pair(e,e?.value):n=new Zn.Pair(e.key,e.value);let s=Ir(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);Ke.isScalar(s.value)&&Ry.isScalarValue(n.value)?s.value.value=n.value:s.value=n.value}else if(i){let o=this.items.findIndex(a=>i(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let t=Ir(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=Ir(this.items,e)?.value;return(!t&&Ke.isScalar(s)?s.value:s)??void 0}has(e){return!!Ir(this.items,e)}set(e,t){this.add(new Zn.Pair(e,t),!0)}toJSON(e,t,n){let s=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(s);for(let i of this.items)Py.addPairToJSMap(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!Ke.isPair(s))throw new Error(`Map items must all be pairs; found ${JSON.stringify(s)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ty.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};Po.YAMLMap=To;Po.findPair=Ir});var jt=P(xu=>{"use strict";var _y=I(),ku=We(),Cy={collection:"map",default:!0,nodeClass:ku.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return _y.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>ku.YAMLMap.from(r,e,t)};xu.map=Cy});var He=P(Eu=>{"use strict";var Ny=Ar(),Iy=Ao(),Ly=jn(),ts=I(),$y=J(),My=je(),Oo=class extends Ly.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(ts.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=es(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=es(e);if(typeof n!="number")return;let s=this.items[n];return!t&&ts.isScalar(s)?s.value:s}has(e){let t=es(e);return typeof t=="number"&&t<this.items.length}set(e,t){let n=es(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[n];ts.isScalar(s)&&$y.isScalarValue(t)?s.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let s=0;for(let i of this.items)n.push(My.toJS(i,String(s++),t));return n}toString(e,t,n){return e?Iy.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:s}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof s=="function"){let c=t instanceof Set?a:String(o++);a=s.call(t,c,a)}i.items.push(Ny.createNode(a,void 0,n))}}return i}};function es(r){let e=ts.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Eu.YAMLSeq=Oo});var Ft=P(Tu=>{"use strict";var Dy=I(),Au=He(),By={collection:"seq",default:!0,nodeClass:Au.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Dy.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Au.YAMLSeq.from(r,e,t)};Tu.seq=By});var Lr=P(Pu=>{"use strict";var jy=Rr(),Fy={identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify(r,e,t,n){return e=Object.assign({actualString:!0},e),jy.stringifyString(r,e,t,n)}};Pu.string=Fy});var rs=P(_u=>{"use strict";var Ou=J(),Ru={identify:r=>r==null,createNode:()=>new Ou.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ou.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&Ru.test.test(r)?r:e.options.nullStr};_u.nullTag=Ru});var Ro=P(Nu=>{"use strict";var qy=J(),Cu={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new qy.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Cu.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};Nu.boolTag=Cu});var qt=P(Iu=>{"use strict";function Uy({format:r,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);let s=typeof n=="number"?n:Number(n);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let i=Object.is(n,-0)?"-0":JSON.stringify(n);if(!r&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(i)){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}Iu.stringifyNumber=Uy});var Co=P(ns=>{"use strict";var Jy=J(),_o=qt(),Ky={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:_o.stringifyNumber},Wy={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():_o.stringifyNumber(r)}},Hy={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(r){let e=new Jy.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:_o.stringifyNumber};ns.float=Hy;ns.floatExp=Wy;ns.floatNaN=Ky});var Io=P(is=>{"use strict";var Lu=qt(),ss=r=>typeof r=="bigint"||Number.isInteger(r),No=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function $u(r,e,t){let{value:n}=r;return ss(n)&&n>=0?t+n.toString(e):Lu.stringifyNumber(r)}var Vy={identify:r=>ss(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>No(r,2,8,t),stringify:r=>$u(r,8,"0o")},Yy={identify:ss,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>No(r,0,10,t),stringify:Lu.stringifyNumber},Gy={identify:r=>ss(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>No(r,2,16,t),stringify:r=>$u(r,16,"0x")};is.int=Yy;is.intHex=Gy;is.intOct=Vy});var Du=P(Mu=>{"use strict";var zy=jt(),Qy=rs(),Xy=Ft(),Zy=Lr(),eb=Ro(),Lo=Co(),$o=Io(),tb=[zy.map,Xy.seq,Zy.string,Qy.nullTag,eb.boolTag,$o.intOct,$o.int,$o.intHex,Lo.floatNaN,Lo.floatExp,Lo.float];Mu.schema=tb});var Fu=P(ju=>{"use strict";var rb=J(),nb=jt(),sb=Ft();function Bu(r){return typeof r=="bigint"||Number.isInteger(r)}var os=({value:r})=>JSON.stringify(r),ib=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:os},{identify:r=>r==null,createNode:()=>new rb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:os},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:os},{identify:Bu,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(r,e,{intAsBigInt:t})=>t?BigInt(r):parseInt(r,10),stringify:({value:r})=>Bu(r)?r.toString():JSON.stringify(r)},{identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:r=>parseFloat(r),stringify:os}],ob={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},ab=[nb.map,sb.seq].concat(ib,ob);ju.schema=ab});var Do=P(qu=>{"use strict";var $r=Pn("buffer"),Mo=J(),cb=Rr(),lb={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof $r.Buffer=="function")return $r.Buffer.from(r,"base64");if(typeof atob=="function"){let t=atob(r.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let s=0;s<t.length;++s)n[s]=t.charCodeAt(s);return n}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),r},stringify({comment:r,type:e,value:t},n,s,i){if(!t)return"";let o=t,a;if(typeof $r.Buffer=="function")a=o instanceof $r.Buffer?o.toString("base64"):$r.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=Mo.Scalar.BLOCK_LITERAL),e!==Mo.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(a.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=a.substr(d,c);a=f.join(e===Mo.Scalar.BLOCK_LITERAL?`
62
+ ${s}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function Xn({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=Qn.indentComment(e(n),r);t.push(i.trimStart())}}Su.stringifyCollection=xy});var We=P(Po=>{"use strict";var Ty=Ao(),Py=xo(),Oy=jn(),Ke=I(),Zn=Je(),Ry=J();function Ir(r,e){let t=Ke.isScalar(e)?e.value:e;for(let n of r)if(Ke.isPair(n)&&(n.key===e||n.key===t||Ke.isScalar(n.key)&&n.key.value===t))return n}var To=class extends Oy.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ke.MAP,e),this.items=[]}static from(e,t,n){let{keepUndefined:s,replacer:i}=n,o=new this(e),a=(c,l)=>{if(typeof i=="function")l=i.call(t,c,l);else if(Array.isArray(i)&&!i.includes(c))return;(l!==void 0||s)&&o.items.push(Zn.createPair(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;Ke.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Zn.Pair(e,e?.value):n=new Zn.Pair(e.key,e.value);let s=Ir(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);Ke.isScalar(s.value)&&Ry.isScalarValue(n.value)?s.value.value=n.value:s.value=n.value}else if(i){let o=this.items.findIndex(a=>i(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let t=Ir(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=Ir(this.items,e)?.value;return(!t&&Ke.isScalar(s)?s.value:s)??void 0}has(e){return!!Ir(this.items,e)}set(e,t){this.add(new Zn.Pair(e,t),!0)}toJSON(e,t,n){let s=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(s);for(let i of this.items)Py.addPairToJSMap(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!Ke.isPair(s))throw new Error(`Map items must all be pairs; found ${JSON.stringify(s)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ty.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};Po.YAMLMap=To;Po.findPair=Ir});var jt=P(xu=>{"use strict";var _y=I(),ku=We(),Cy={collection:"map",default:!0,nodeClass:ku.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return _y.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>ku.YAMLMap.from(r,e,t)};xu.map=Cy});var He=P(Eu=>{"use strict";var Ny=Ar(),Iy=Ao(),Ly=jn(),ts=I(),My=J(),$y=je(),Oo=class extends Ly.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(ts.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=es(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=es(e);if(typeof n!="number")return;let s=this.items[n];return!t&&ts.isScalar(s)?s.value:s}has(e){let t=es(e);return typeof t=="number"&&t<this.items.length}set(e,t){let n=es(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[n];ts.isScalar(s)&&My.isScalarValue(t)?s.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let s=0;for(let i of this.items)n.push($y.toJS(i,String(s++),t));return n}toString(e,t,n){return e?Iy.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:s}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof s=="function"){let c=t instanceof Set?a:String(o++);a=s.call(t,c,a)}i.items.push(Ny.createNode(a,void 0,n))}}return i}};function es(r){let e=ts.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Eu.YAMLSeq=Oo});var Ft=P(Tu=>{"use strict";var Dy=I(),Au=He(),By={collection:"seq",default:!0,nodeClass:Au.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Dy.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Au.YAMLSeq.from(r,e,t)};Tu.seq=By});var Lr=P(Pu=>{"use strict";var jy=Rr(),Fy={identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify(r,e,t,n){return e=Object.assign({actualString:!0},e),jy.stringifyString(r,e,t,n)}};Pu.string=Fy});var rs=P(_u=>{"use strict";var Ou=J(),Ru={identify:r=>r==null,createNode:()=>new Ou.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ou.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&Ru.test.test(r)?r:e.options.nullStr};_u.nullTag=Ru});var Ro=P(Nu=>{"use strict";var qy=J(),Cu={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new qy.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Cu.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};Nu.boolTag=Cu});var qt=P(Iu=>{"use strict";function Uy({format:r,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);let s=typeof n=="number"?n:Number(n);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let i=Object.is(n,-0)?"-0":JSON.stringify(n);if(!r&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(i)){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}Iu.stringifyNumber=Uy});var Co=P(ns=>{"use strict";var Jy=J(),_o=qt(),Ky={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:_o.stringifyNumber},Wy={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():_o.stringifyNumber(r)}},Hy={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(r){let e=new Jy.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:_o.stringifyNumber};ns.float=Hy;ns.floatExp=Wy;ns.floatNaN=Ky});var Io=P(is=>{"use strict";var Lu=qt(),ss=r=>typeof r=="bigint"||Number.isInteger(r),No=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function Mu(r,e,t){let{value:n}=r;return ss(n)&&n>=0?t+n.toString(e):Lu.stringifyNumber(r)}var Vy={identify:r=>ss(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>No(r,2,8,t),stringify:r=>Mu(r,8,"0o")},Yy={identify:ss,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>No(r,0,10,t),stringify:Lu.stringifyNumber},Gy={identify:r=>ss(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>No(r,2,16,t),stringify:r=>Mu(r,16,"0x")};is.int=Yy;is.intHex=Gy;is.intOct=Vy});var Du=P($u=>{"use strict";var zy=jt(),Qy=rs(),Xy=Ft(),Zy=Lr(),eb=Ro(),Lo=Co(),Mo=Io(),tb=[zy.map,Xy.seq,Zy.string,Qy.nullTag,eb.boolTag,Mo.intOct,Mo.int,Mo.intHex,Lo.floatNaN,Lo.floatExp,Lo.float];$u.schema=tb});var Fu=P(ju=>{"use strict";var rb=J(),nb=jt(),sb=Ft();function Bu(r){return typeof r=="bigint"||Number.isInteger(r)}var os=({value:r})=>JSON.stringify(r),ib=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:os},{identify:r=>r==null,createNode:()=>new rb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:os},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:os},{identify:Bu,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(r,e,{intAsBigInt:t})=>t?BigInt(r):parseInt(r,10),stringify:({value:r})=>Bu(r)?r.toString():JSON.stringify(r)},{identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:r=>parseFloat(r),stringify:os}],ob={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},ab=[nb.map,sb.seq].concat(ib,ob);ju.schema=ab});var Do=P(qu=>{"use strict";var Mr=Pn("buffer"),$o=J(),cb=Rr(),lb={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof Mr.Buffer=="function")return Mr.Buffer.from(r,"base64");if(typeof atob=="function"){let t=atob(r.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let s=0;s<t.length;++s)n[s]=t.charCodeAt(s);return n}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),r},stringify({comment:r,type:e,value:t},n,s,i){if(!t)return"";let o=t,a;if(typeof Mr.Buffer=="function")a=o instanceof Mr.Buffer?o.toString("base64"):Mr.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=$o.Scalar.BLOCK_LITERAL),e!==$o.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(a.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=a.substr(d,c);a=f.join(e===$o.Scalar.BLOCK_LITERAL?`
63
63
  `:" ")}return cb.stringifyString({comment:r,type:e,value:a},n,s,i)}};qu.binary=lb});var ls=P(cs=>{"use strict";var as=I(),Bo=Je(),ub=J(),fb=He();function Uu(r,e){if(as.isSeq(r))for(let t=0;t<r.items.length;++t){let n=r.items[t];if(!as.isPair(n)){if(as.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let s=n.items[0]||new Bo.Pair(new ub.Scalar(null));if(n.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${n.commentBefore}
64
64
  ${s.key.commentBefore}`:n.commentBefore),n.comment){let i=s.value??s.key;i.comment=i.comment?`${n.comment}
65
- ${i.comment}`:n.comment}n=s}r.items[t]=as.isPair(n)?n:new Bo.Pair(n)}}else e("Expected a sequence for this tag");return r}function Ju(r,e,t){let{replacer:n}=t,s=new fb.YAMLSeq(r);s.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(i++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;s.items.push(Bo.createPair(a,c,t))}return s}var db={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Uu,createNode:Ju};cs.createPairs=Ju;cs.pairs=db;cs.resolvePairs=Uu});var qo=P(Fo=>{"use strict";var Ku=I(),jo=je(),Mr=We(),pb=He(),Wu=ls(),ct=class r extends pb.YAMLSeq{constructor(){super(),this.add=Mr.YAMLMap.prototype.add.bind(this),this.delete=Mr.YAMLMap.prototype.delete.bind(this),this.get=Mr.YAMLMap.prototype.get.bind(this),this.has=Mr.YAMLMap.prototype.has.bind(this),this.set=Mr.YAMLMap.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let s of this.items){let i,o;if(Ku.isPair(s)?(i=jo.toJS(s.key,"",t),o=jo.toJS(s.value,i,t)):i=jo.toJS(s,"",t),n.has(i))throw new Error("Ordered maps must not include duplicate keys");n.set(i,o)}return n}static from(e,t,n){let s=Wu.createPairs(e,t,n),i=new this;return i.items=s.items,i}};ct.tag="tag:yaml.org,2002:omap";var mb={collection:"seq",identify:r=>r instanceof Map,nodeClass:ct,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Wu.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Ku.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new ct,t)},createNode:(r,e,t)=>ct.from(r,e,t)};Fo.YAMLOMap=ct;Fo.omap=mb});var zu=P(Uo=>{"use strict";var Hu=J();function Vu({value:r,source:e},t){return e&&(r?Yu:Gu).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Yu={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Hu.Scalar(!0),stringify:Vu},Gu={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Hu.Scalar(!1),stringify:Vu};Uo.falseTag=Gu;Uo.trueTag=Yu});var Qu=P(us=>{"use strict";var hb=J(),Jo=qt(),gb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Jo.stringifyNumber},yb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Jo.stringifyNumber(r)}},bb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new hb.Scalar(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let n=r.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:Jo.stringifyNumber};us.float=bb;us.floatExp=yb;us.floatNaN=gb});var Zu=P(Br=>{"use strict";var Xu=qt(),Dr=r=>typeof r=="bigint"||Number.isInteger(r);function fs(r,e,t,{intAsBigInt:n}){let s=r[0];if((s==="-"||s==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),n){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let o=BigInt(r);return s==="-"?BigInt(-1)*o:o}let i=parseInt(r,t);return s==="-"?-1*i:i}function Ko(r,e,t){let{value:n}=r;if(Dr(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return Xu.stringifyNumber(r)}var wb={identify:Dr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>fs(r,2,2,t),stringify:r=>Ko(r,2,"0b")},vb={identify:Dr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>fs(r,1,8,t),stringify:r=>Ko(r,8,"0")},Sb={identify:Dr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>fs(r,0,10,t),stringify:Xu.stringifyNumber},kb={identify:Dr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>fs(r,2,16,t),stringify:r=>Ko(r,16,"0x")};Br.int=Sb;Br.intBin=wb;Br.intHex=kb;Br.intOct=vb});var Ho=P(Wo=>{"use strict";var ms=I(),ds=Je(),ps=We(),lt=class r extends ps.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;ms.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new ds.Pair(e.key,null):t=new ds.Pair(e,null),ps.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=ps.findPair(this.items,e);return!t&&ms.isPair(n)?ms.isScalar(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=ps.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new ds.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){let{replacer:s}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof s=="function"&&(o=s.call(t,o,o)),i.items.push(ds.createPair(o,null,n));return i}};lt.tag="tag:yaml.org,2002:set";var xb={collection:"map",identify:r=>r instanceof Set,nodeClass:lt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>lt.from(r,e,t),resolve(r,e){if(ms.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new lt,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Wo.YAMLSet=lt;Wo.set=xb});var Yo=P(hs=>{"use strict";var Eb=qt();function Vo(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,s=o=>e?BigInt(o):Number(o),i=n.replace(/_/g,"").split(":").reduce((o,a)=>o*s(60)+s(a),s(0));return t==="-"?s(-1)*i:i}function ef(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Eb.stringifyNumber(r);let n="";e<0&&(n="-",e*=t(-1));let s=t(60),i=[e%s];return e<60?i.unshift(0):(e=(e-i[0])/s,i.unshift(e%s),e>=60&&(e=(e-i[0])/s,i.unshift(e))),n+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Ab={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>Vo(r,t),stringify:ef},Tb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>Vo(r,!1),stringify:ef},tf={identify:r=>r instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(r){let e=r.match(tf.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,s,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,s,i||0,o||0,a||0,c),f=e[8];if(f&&f!=="Z"){let u=Vo(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};hs.floatTime=Tb;hs.intTime=Ab;hs.timestamp=tf});var sf=P(nf=>{"use strict";var Pb=jt(),Ob=rs(),Rb=Ft(),_b=Lr(),Cb=Do(),rf=zu(),Go=Qu(),gs=Zu(),Nb=Yn(),Ib=qo(),Lb=ls(),$b=Ho(),zo=Yo(),Mb=[Pb.map,Rb.seq,_b.string,Ob.nullTag,rf.trueTag,rf.falseTag,gs.intBin,gs.intOct,gs.int,gs.intHex,Go.floatNaN,Go.floatExp,Go.float,Cb.binary,Nb.merge,Ib.omap,Lb.pairs,$b.set,zo.intTime,zo.floatTime,zo.timestamp];nf.schema=Mb});var hf=P(Zo=>{"use strict";var lf=jt(),Db=rs(),uf=Ft(),Bb=Lr(),jb=Ro(),Qo=Co(),Xo=Io(),Fb=Du(),qb=Fu(),ff=Do(),jr=Yn(),df=qo(),pf=ls(),of=sf(),mf=Ho(),ys=Yo(),af=new Map([["core",Fb.schema],["failsafe",[lf.map,uf.seq,Bb.string]],["json",qb.schema],["yaml11",of.schema],["yaml-1.1",of.schema]]),cf={binary:ff.binary,bool:jb.boolTag,float:Qo.float,floatExp:Qo.floatExp,floatNaN:Qo.floatNaN,floatTime:ys.floatTime,int:Xo.int,intHex:Xo.intHex,intOct:Xo.intOct,intTime:ys.intTime,map:lf.map,merge:jr.merge,null:Db.nullTag,omap:df.omap,pairs:pf.pairs,seq:uf.seq,set:mf.set,timestamp:ys.timestamp},Ub={"tag:yaml.org,2002:binary":ff.binary,"tag:yaml.org,2002:merge":jr.merge,"tag:yaml.org,2002:omap":df.omap,"tag:yaml.org,2002:pairs":pf.pairs,"tag:yaml.org,2002:set":mf.set,"tag:yaml.org,2002:timestamp":ys.timestamp};function Jb(r,e,t){let n=af.get(e);if(n&&!r)return t&&!n.includes(jr.merge)?n.concat(jr.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(af.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(r))for(let i of r)s=s.concat(i);else typeof r=="function"&&(s=r(s.slice()));return t&&(s=s.concat(jr.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?cf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(cf).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}Zo.coreKnownTags=Ub;Zo.getTags=Jb});var ra=P(gf=>{"use strict";var ea=I(),Kb=jt(),Wb=Ft(),Hb=Lr(),bs=hf(),Vb=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,ta=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?bs.getTags(e,"compat"):e?bs.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?bs.coreKnownTags:{},this.tags=bs.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,ea.MAP,{value:Kb.map}),Object.defineProperty(this,ea.SCALAR,{value:Hb.string}),Object.defineProperty(this,ea.SEQ,{value:Wb.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Vb:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};gf.Schema=ta});var bf=P(yf=>{"use strict";var Yb=I(),na=_r(),Fr=Tr();function Gb(r,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let c=r.directives.toString(r);c?(t.push(c),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let s=na.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(Fr.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(Yb.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let f=i(r.contents.commentBefore);t.push(Fr.indentComment(f,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=na.stringify(r.contents,s,()=>a=null,c);a&&(l+=Fr.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(na.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
65
+ ${i.comment}`:n.comment}n=s}r.items[t]=as.isPair(n)?n:new Bo.Pair(n)}}else e("Expected a sequence for this tag");return r}function Ju(r,e,t){let{replacer:n}=t,s=new fb.YAMLSeq(r);s.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(i++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;s.items.push(Bo.createPair(a,c,t))}return s}var db={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Uu,createNode:Ju};cs.createPairs=Ju;cs.pairs=db;cs.resolvePairs=Uu});var qo=P(Fo=>{"use strict";var Ku=I(),jo=je(),$r=We(),pb=He(),Wu=ls(),ct=class r extends pb.YAMLSeq{constructor(){super(),this.add=$r.YAMLMap.prototype.add.bind(this),this.delete=$r.YAMLMap.prototype.delete.bind(this),this.get=$r.YAMLMap.prototype.get.bind(this),this.has=$r.YAMLMap.prototype.has.bind(this),this.set=$r.YAMLMap.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let s of this.items){let i,o;if(Ku.isPair(s)?(i=jo.toJS(s.key,"",t),o=jo.toJS(s.value,i,t)):i=jo.toJS(s,"",t),n.has(i))throw new Error("Ordered maps must not include duplicate keys");n.set(i,o)}return n}static from(e,t,n){let s=Wu.createPairs(e,t,n),i=new this;return i.items=s.items,i}};ct.tag="tag:yaml.org,2002:omap";var mb={collection:"seq",identify:r=>r instanceof Map,nodeClass:ct,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Wu.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Ku.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new ct,t)},createNode:(r,e,t)=>ct.from(r,e,t)};Fo.YAMLOMap=ct;Fo.omap=mb});var zu=P(Uo=>{"use strict";var Hu=J();function Vu({value:r,source:e},t){return e&&(r?Yu:Gu).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Yu={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Hu.Scalar(!0),stringify:Vu},Gu={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Hu.Scalar(!1),stringify:Vu};Uo.falseTag=Gu;Uo.trueTag=Yu});var Qu=P(us=>{"use strict";var hb=J(),Jo=qt(),gb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Jo.stringifyNumber},yb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Jo.stringifyNumber(r)}},bb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new hb.Scalar(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let n=r.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:Jo.stringifyNumber};us.float=bb;us.floatExp=yb;us.floatNaN=gb});var Zu=P(Br=>{"use strict";var Xu=qt(),Dr=r=>typeof r=="bigint"||Number.isInteger(r);function fs(r,e,t,{intAsBigInt:n}){let s=r[0];if((s==="-"||s==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),n){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let o=BigInt(r);return s==="-"?BigInt(-1)*o:o}let i=parseInt(r,t);return s==="-"?-1*i:i}function Ko(r,e,t){let{value:n}=r;if(Dr(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return Xu.stringifyNumber(r)}var wb={identify:Dr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>fs(r,2,2,t),stringify:r=>Ko(r,2,"0b")},vb={identify:Dr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>fs(r,1,8,t),stringify:r=>Ko(r,8,"0")},Sb={identify:Dr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>fs(r,0,10,t),stringify:Xu.stringifyNumber},kb={identify:Dr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>fs(r,2,16,t),stringify:r=>Ko(r,16,"0x")};Br.int=Sb;Br.intBin=wb;Br.intHex=kb;Br.intOct=vb});var Ho=P(Wo=>{"use strict";var ms=I(),ds=Je(),ps=We(),lt=class r extends ps.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;ms.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new ds.Pair(e.key,null):t=new ds.Pair(e,null),ps.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=ps.findPair(this.items,e);return!t&&ms.isPair(n)?ms.isScalar(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=ps.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new ds.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){let{replacer:s}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof s=="function"&&(o=s.call(t,o,o)),i.items.push(ds.createPair(o,null,n));return i}};lt.tag="tag:yaml.org,2002:set";var xb={collection:"map",identify:r=>r instanceof Set,nodeClass:lt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>lt.from(r,e,t),resolve(r,e){if(ms.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new lt,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Wo.YAMLSet=lt;Wo.set=xb});var Yo=P(hs=>{"use strict";var Eb=qt();function Vo(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,s=o=>e?BigInt(o):Number(o),i=n.replace(/_/g,"").split(":").reduce((o,a)=>o*s(60)+s(a),s(0));return t==="-"?s(-1)*i:i}function ef(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Eb.stringifyNumber(r);let n="";e<0&&(n="-",e*=t(-1));let s=t(60),i=[e%s];return e<60?i.unshift(0):(e=(e-i[0])/s,i.unshift(e%s),e>=60&&(e=(e-i[0])/s,i.unshift(e))),n+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Ab={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>Vo(r,t),stringify:ef},Tb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>Vo(r,!1),stringify:ef},tf={identify:r=>r instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(r){let e=r.match(tf.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,s,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,s,i||0,o||0,a||0,c),f=e[8];if(f&&f!=="Z"){let u=Vo(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};hs.floatTime=Tb;hs.intTime=Ab;hs.timestamp=tf});var sf=P(nf=>{"use strict";var Pb=jt(),Ob=rs(),Rb=Ft(),_b=Lr(),Cb=Do(),rf=zu(),Go=Qu(),gs=Zu(),Nb=Yn(),Ib=qo(),Lb=ls(),Mb=Ho(),zo=Yo(),$b=[Pb.map,Rb.seq,_b.string,Ob.nullTag,rf.trueTag,rf.falseTag,gs.intBin,gs.intOct,gs.int,gs.intHex,Go.floatNaN,Go.floatExp,Go.float,Cb.binary,Nb.merge,Ib.omap,Lb.pairs,Mb.set,zo.intTime,zo.floatTime,zo.timestamp];nf.schema=$b});var hf=P(Zo=>{"use strict";var lf=jt(),Db=rs(),uf=Ft(),Bb=Lr(),jb=Ro(),Qo=Co(),Xo=Io(),Fb=Du(),qb=Fu(),ff=Do(),jr=Yn(),df=qo(),pf=ls(),of=sf(),mf=Ho(),ys=Yo(),af=new Map([["core",Fb.schema],["failsafe",[lf.map,uf.seq,Bb.string]],["json",qb.schema],["yaml11",of.schema],["yaml-1.1",of.schema]]),cf={binary:ff.binary,bool:jb.boolTag,float:Qo.float,floatExp:Qo.floatExp,floatNaN:Qo.floatNaN,floatTime:ys.floatTime,int:Xo.int,intHex:Xo.intHex,intOct:Xo.intOct,intTime:ys.intTime,map:lf.map,merge:jr.merge,null:Db.nullTag,omap:df.omap,pairs:pf.pairs,seq:uf.seq,set:mf.set,timestamp:ys.timestamp},Ub={"tag:yaml.org,2002:binary":ff.binary,"tag:yaml.org,2002:merge":jr.merge,"tag:yaml.org,2002:omap":df.omap,"tag:yaml.org,2002:pairs":pf.pairs,"tag:yaml.org,2002:set":mf.set,"tag:yaml.org,2002:timestamp":ys.timestamp};function Jb(r,e,t){let n=af.get(e);if(n&&!r)return t&&!n.includes(jr.merge)?n.concat(jr.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(af.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(r))for(let i of r)s=s.concat(i);else typeof r=="function"&&(s=r(s.slice()));return t&&(s=s.concat(jr.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?cf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(cf).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}Zo.coreKnownTags=Ub;Zo.getTags=Jb});var ra=P(gf=>{"use strict";var ea=I(),Kb=jt(),Wb=Ft(),Hb=Lr(),bs=hf(),Vb=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,ta=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?bs.getTags(e,"compat"):e?bs.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?bs.coreKnownTags:{},this.tags=bs.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,ea.MAP,{value:Kb.map}),Object.defineProperty(this,ea.SCALAR,{value:Hb.string}),Object.defineProperty(this,ea.SEQ,{value:Wb.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Vb:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};gf.Schema=ta});var bf=P(yf=>{"use strict";var Yb=I(),na=_r(),Fr=Tr();function Gb(r,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let c=r.directives.toString(r);c?(t.push(c),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let s=na.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(Fr.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(Yb.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let f=i(r.contents.commentBefore);t.push(Fr.indentComment(f,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=na.stringify(r.contents,s,()=>a=null,c);a&&(l+=Fr.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(na.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
66
66
  `)?(t.push("..."),t.push(Fr.indentComment(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=r.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(Fr.indentComment(i(c),"")))}return t.join(`
67
67
  `)+`
68
- `}yf.stringifyDocument=Gb});var qr=P(wf=>{"use strict";var zb=Er(),Ut=jn(),ie=I(),Qb=Je(),Xb=je(),Zb=ra(),ew=bf(),sa=$n(),tw=ao(),rw=Ar(),ia=oo(),oa=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ie.NODE_TYPE,{value:ie.DOC});let s=null;typeof t=="function"||Array.isArray(t)?s=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:o}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new ia.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,s,n)}clone(){let e=Object.create(r.prototype,{[ie.NODE_TYPE]:{value:ie.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=ie.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Jt(this.contents)&&this.contents.add(e)}addIn(e,t){Jt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=sa.anchorNames(this);e.anchor=!t||n.has(t)?sa.findNewAnchor(t||"a",n):t}return new zb.Alias(e.anchor)}createNode(e,t,n){let s;if(typeof t=="function")e=t.call({"":e},"",e),s=t;else if(Array.isArray(t)){let y=T=>typeof T=="number"||T instanceof String||T instanceof Number,E=t.filter(y).map(String);E.length>0&&(t=t.concat(E)),s=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=sa.createNodeAnchors(this,o||"a"),b={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},m=rw.createNode(e,f,b);return a&&ie.isCollection(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){let s=this.createNode(e,null,n),i=this.createNode(t,null,n);return new Qb.Pair(s,i)}delete(e){return Jt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ut.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Jt(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return ie.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Ut.isEmptyPath(e)?!t&&ie.isScalar(this.contents)?this.contents.value:this.contents:ie.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return ie.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Ut.isEmptyPath(e)?this.contents!==void 0:ie.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ut.collectionFromPath(this.schema,[e],t):Jt(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ut.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=Ut.collectionFromPath(this.schema,Array.from(e),t):Jt(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new ia.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new ia.Directives({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let s=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${s}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new Zb.Schema(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:s,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},c=Xb.toJS(this.contents,t??"",a);if(typeof i=="function")for(let{count:l,res:f}of a.anchors.values())i(f,l);return typeof o=="function"?tw.applyReviver(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return ew.stringifyDocument(this,e)}};function Jt(r){if(ie.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}wf.Document=oa});var Kr=P(Jr=>{"use strict";var Ur=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},aa=class extends Ur{constructor(e,t,n){super("YAMLParseError",e,t,n)}},ca=class extends Ur{constructor(e,t,n){super("YAMLWarning",e,t,n)}},nw=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:s}=t.linePos[0];t.message+=` at line ${n}, column ${s}`;let i=s-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,i))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
68
+ `}yf.stringifyDocument=Gb});var qr=P(wf=>{"use strict";var zb=Er(),Ut=jn(),ie=I(),Qb=Je(),Xb=je(),Zb=ra(),ew=bf(),sa=Mn(),tw=ao(),rw=Ar(),ia=oo(),oa=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ie.NODE_TYPE,{value:ie.DOC});let s=null;typeof t=="function"||Array.isArray(t)?s=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:o}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new ia.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,s,n)}clone(){let e=Object.create(r.prototype,{[ie.NODE_TYPE]:{value:ie.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=ie.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Jt(this.contents)&&this.contents.add(e)}addIn(e,t){Jt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=sa.anchorNames(this);e.anchor=!t||n.has(t)?sa.findNewAnchor(t||"a",n):t}return new zb.Alias(e.anchor)}createNode(e,t,n){let s;if(typeof t=="function")e=t.call({"":e},"",e),s=t;else if(Array.isArray(t)){let y=T=>typeof T=="number"||T instanceof String||T instanceof Number,E=t.filter(y).map(String);E.length>0&&(t=t.concat(E)),s=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=sa.createNodeAnchors(this,o||"a"),b={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},m=rw.createNode(e,f,b);return a&&ie.isCollection(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){let s=this.createNode(e,null,n),i=this.createNode(t,null,n);return new Qb.Pair(s,i)}delete(e){return Jt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ut.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Jt(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return ie.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Ut.isEmptyPath(e)?!t&&ie.isScalar(this.contents)?this.contents.value:this.contents:ie.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return ie.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Ut.isEmptyPath(e)?this.contents!==void 0:ie.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ut.collectionFromPath(this.schema,[e],t):Jt(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ut.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=Ut.collectionFromPath(this.schema,Array.from(e),t):Jt(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new ia.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new ia.Directives({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let s=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${s}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new Zb.Schema(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:s,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},c=Xb.toJS(this.contents,t??"",a);if(typeof i=="function")for(let{count:l,res:f}of a.anchors.values())i(f,l);return typeof o=="function"?tw.applyReviver(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return ew.stringifyDocument(this,e)}};function Jt(r){if(ie.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}wf.Document=oa});var Kr=P(Jr=>{"use strict";var Ur=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},aa=class extends Ur{constructor(e,t,n){super("YAMLParseError",e,t,n)}},ca=class extends Ur{constructor(e,t,n){super("YAMLWarning",e,t,n)}},nw=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:s}=t.linePos[0];t.message+=` at line ${n}, column ${s}`;let i=s-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,i))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
69
69
  `),o=a+o}if(/[^ ]/.test(o)){let a=1,c=t.linePos[1];c?.line===n&&c.col>s&&(a=Math.max(1,Math.min(c.col-s,80-i)));let l=" ".repeat(i)+"^".repeat(a);t.message+=`:
70
70
 
71
71
  ${o}
@@ -73,11 +73,11 @@ ${l}
73
73
  `}};Jr.YAMLError=Ur;Jr.YAMLParseError=aa;Jr.YAMLWarning=ca;Jr.prettifyError=nw});var Wr=P(vf=>{"use strict";function sw(r,{flow:e,indicator:t,next:n,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,f=a,u="",d="",p=!1,b=!1,m=null,y=null,E=null,T=null,g=null,w=null,S=null;for(let A of r)switch(b&&(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&i(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),b=!1),m&&(l&&A.type!=="comment"&&A.type!=="newline"&&i(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),A.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&A.source.includes(" ")&&(m=A),f=!0;break;case"comment":{f||i(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let L=A.source.substring(1)||" ";u?u+=d+L:u=L,d="",l=!1;break}case"newline":l?u?u+=A.source:(!w||t!=="seq-item-ind")&&(c=!0):d+=A.source,l=!0,p=!0,(y||E)&&(T=A),f=!0;break;case"anchor":y&&i(A,"MULTIPLE_ANCHORS","A node can have at most one anchor"),A.source.endsWith(":")&&i(A.offset+A.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=A,S??(S=A.offset),l=!1,f=!1,b=!0;break;case"tag":{E&&i(A,"MULTIPLE_TAGS","A node can have at most one tag"),E=A,S??(S=A.offset),l=!1,f=!1,b=!0;break}case t:(y||E)&&i(A,"BAD_PROP_ORDER",`Anchors and tags must be after the ${A.source} indicator`),w&&i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${e??"collection"}`),w=A,l=t==="seq-item-ind"||t==="explicit-key-ind",f=!1;break;case"comma":if(e){g&&i(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),g=A,l=!1,f=!1;break}default:i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),l=!1,f=!1}let x=r[r.length-1],O=x?x.offset+x.source.length:s;return b&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&i(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&i(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:g,found:w,spaceBefore:c,comment:u,hasNewline:p,anchor:y,tag:E,newlineAfterProp:T,end:O,start:S??O}}vf.resolveProps=sw});var ws=P(Sf=>{"use strict";function la(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(`
74
74
  `))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(la(e.key)||la(e.value))return!0}return!1;default:return!0}}Sf.containsNewline=la});var ua=P(kf=>{"use strict";var iw=ws();function ow(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&iw.containsNewline(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}kf.flowIndentCheck=ow});var fa=P(Ef=>{"use strict";var xf=I();function aw(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(i,o)=>i===o||xf.isScalar(i)&&xf.isScalar(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}Ef.mapIncludes=aw});var _f=P(Rf=>{"use strict";var Af=Je(),cw=We(),Tf=Wr(),lw=ws(),Pf=ua(),uw=fa(),Of="All mapping items must start at the same column";function fw({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??cw.YAMLMap,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let f of n.items){let{start:u,key:d,sep:p,value:b}=f,m=Tf.resolveProps(u,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0}),y=!m.found;if(y){if(d&&(d.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==n.indent&&s(c,"BAD_INDENT",Of)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=`
75
75
  `+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||lw.containsNewline(d))&&s(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==n.indent&&s(c,"BAD_INDENT",Of);t.atKey=!0;let E=m.end,T=d?r(t,d,m,s):e(t,E,u,null,m,s);t.schema.compat&&Pf.flowIndentCheck(n.indent,d,s),t.atKey=!1,uw.mapIncludes(t,a.items,T)&&s(E,"DUPLICATE_KEY","Map keys must be unique");let g=Tf.resolveProps(p??[],{indicator:"map-value-ind",next:b,offset:T.range[2],onError:s,parentIndent:n.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=g.end,g.found){y&&(b?.type==="block-map"&&!g.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&m.start<g.found.offset-1024&&s(T.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let w=b?r(t,b,g,s):e(t,c,p,null,g,s);t.schema.compat&&Pf.flowIndentCheck(n.indent,b,s),c=w.range[2];let S=new Af.Pair(T,w);t.options.keepSourceTokens&&(S.srcToken=f),a.items.push(S)}else{y&&s(T.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),g.comment&&(T.comment?T.comment+=`
76
- `+g.comment:T.comment=g.comment);let w=new Af.Pair(T);t.options.keepSourceTokens&&(w.srcToken=f),a.items.push(w)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}Rf.resolveBlockMap=fw});var Nf=P(Cf=>{"use strict";var dw=He(),pw=Wr(),mw=ua();function hw({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??dw.YAMLSeq,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=n.offset,l=null;for(let{start:f,value:u}of n.items){let d=pw.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?s(d.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let p=u?r(t,u,d,s):e(t,d.end,f,null,d,s);t.schema.compat&&mw.flowIndentCheck(n.indent,u,s),c=p.range[2],a.items.push(p)}return a.range=[n.offset,c,l??c],a}Cf.resolveBlockSeq=hw});var Kt=P(If=>{"use strict";function gw(r,e,t,n){let s="";if(r){let i=!1,o="";for(let a of r){let{source:c,type:l}=a;switch(l){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";s?s+=o+f:s=f,o="";break}case"newline":s&&(o+=c),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:s,offset:e}}If.resolveEnd=gw});var Df=P(Mf=>{"use strict";var yw=I(),bw=Je(),Lf=We(),ww=He(),vw=Kt(),$f=Wr(),Sw=ws(),kw=fa(),da="Block collections are not allowed within flow collections",pa=r=>r&&(r.type==="block-map"||r.type==="block-seq");function xw({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?Lf.YAMLMap:ww.YAMLSeq),l=new c(t.schema);l.flow=!0;let f=t.atRoot;f&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=n.offset+n.start.source.length;for(let y=0;y<n.items.length;++y){let E=n.items[y],{start:T,key:g,sep:w,value:S}=E,x=$f.resolveProps(T,{flow:a,indicator:"explicit-key-ind",next:g??w?.[0],offset:u,onError:s,parentIndent:n.indent,startOnNewline:!1});if(!x.found){if(!x.anchor&&!x.tag&&!w&&!S){y===0&&x.comma?s(x.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<n.items.length-1&&s(x.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),x.comment&&(l.comment?l.comment+=`
76
+ `+g.comment:T.comment=g.comment);let w=new Af.Pair(T);t.options.keepSourceTokens&&(w.srcToken=f),a.items.push(w)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}Rf.resolveBlockMap=fw});var Nf=P(Cf=>{"use strict";var dw=He(),pw=Wr(),mw=ua();function hw({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??dw.YAMLSeq,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=n.offset,l=null;for(let{start:f,value:u}of n.items){let d=pw.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?s(d.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let p=u?r(t,u,d,s):e(t,d.end,f,null,d,s);t.schema.compat&&mw.flowIndentCheck(n.indent,u,s),c=p.range[2],a.items.push(p)}return a.range=[n.offset,c,l??c],a}Cf.resolveBlockSeq=hw});var Kt=P(If=>{"use strict";function gw(r,e,t,n){let s="";if(r){let i=!1,o="";for(let a of r){let{source:c,type:l}=a;switch(l){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";s?s+=o+f:s=f,o="";break}case"newline":s&&(o+=c),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:s,offset:e}}If.resolveEnd=gw});var Df=P($f=>{"use strict";var yw=I(),bw=Je(),Lf=We(),ww=He(),vw=Kt(),Mf=Wr(),Sw=ws(),kw=fa(),da="Block collections are not allowed within flow collections",pa=r=>r&&(r.type==="block-map"||r.type==="block-seq");function xw({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?Lf.YAMLMap:ww.YAMLSeq),l=new c(t.schema);l.flow=!0;let f=t.atRoot;f&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=n.offset+n.start.source.length;for(let y=0;y<n.items.length;++y){let E=n.items[y],{start:T,key:g,sep:w,value:S}=E,x=Mf.resolveProps(T,{flow:a,indicator:"explicit-key-ind",next:g??w?.[0],offset:u,onError:s,parentIndent:n.indent,startOnNewline:!1});if(!x.found){if(!x.anchor&&!x.tag&&!w&&!S){y===0&&x.comma?s(x.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<n.items.length-1&&s(x.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),x.comment&&(l.comment?l.comment+=`
77
77
  `+x.comment:l.comment=x.comment),u=x.end;continue}!o&&t.options.strict&&Sw.containsNewline(g)&&s(g,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)x.comma&&s(x.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(x.comma||s(x.start,"MISSING_CHAR",`Missing , between ${a} items`),x.comment){let O="";e:for(let A of T)switch(A.type){case"comma":case"space":break;case"comment":O=A.source.substring(1);break e;default:break e}if(O){let A=l.items[l.items.length-1];yw.isPair(A)&&(A=A.value??A.key),A.comment?A.comment+=`
78
- `+O:A.comment=O,x.comment=x.comment.substring(O.length+1)}}if(!o&&!w&&!x.found){let O=S?r(t,S,x,s):e(t,x.end,w,null,x,s);l.items.push(O),u=O.range[2],pa(S)&&s(O.range,"BLOCK_IN_FLOW",da)}else{t.atKey=!0;let O=x.end,A=g?r(t,g,x,s):e(t,O,T,null,x,s);pa(g)&&s(A.range,"BLOCK_IN_FLOW",da),t.atKey=!1;let L=$f.resolveProps(w??[],{flow:a,indicator:"map-value-ind",next:S,offset:A.range[2],onError:s,parentIndent:n.indent,startOnNewline:!1});if(L.found){if(!o&&!x.found&&t.options.strict){if(w)for(let B of w){if(B===L.found)break;if(B.type==="newline"){s(B,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}x.start<L.found.offset-1024&&s(L.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?s(S,"MISSING_CHAR",`Missing space after : in ${a}`):s(L.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let te=S?r(t,S,L,s):L.found?e(t,L.end,w,null,L,s):null;te?pa(S)&&s(te.range,"BLOCK_IN_FLOW",da):L.comment&&(A.comment?A.comment+=`
78
+ `+O:A.comment=O,x.comment=x.comment.substring(O.length+1)}}if(!o&&!w&&!x.found){let O=S?r(t,S,x,s):e(t,x.end,w,null,x,s);l.items.push(O),u=O.range[2],pa(S)&&s(O.range,"BLOCK_IN_FLOW",da)}else{t.atKey=!0;let O=x.end,A=g?r(t,g,x,s):e(t,O,T,null,x,s);pa(g)&&s(A.range,"BLOCK_IN_FLOW",da),t.atKey=!1;let L=Mf.resolveProps(w??[],{flow:a,indicator:"map-value-ind",next:S,offset:A.range[2],onError:s,parentIndent:n.indent,startOnNewline:!1});if(L.found){if(!o&&!x.found&&t.options.strict){if(w)for(let B of w){if(B===L.found)break;if(B.type==="newline"){s(B,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}x.start<L.found.offset-1024&&s(L.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?s(S,"MISSING_CHAR",`Missing space after : in ${a}`):s(L.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let te=S?r(t,S,L,s):L.found?e(t,L.end,w,null,L,s):null;te?pa(S)&&s(te.range,"BLOCK_IN_FLOW",da):L.comment&&(A.comment?A.comment+=`
79
79
  `+L.comment:A.comment=L.comment);let V=new bw.Pair(A,te);if(t.options.keepSourceTokens&&(V.srcToken=E),o){let B=l;kw.mapIncludes(t,B.items,A)&&s(O,"DUPLICATE_KEY","Map keys must be unique"),B.items.push(V)}else{let B=new Lf.YAMLMap(t.schema);B.flow=!0,B.items.push(V);let it=(te??A).range;B.range=[A.range[0],it[1],it[2]],l.items.push(B)}u=te?te.range[2]:L.end}}let d=o?"}":"]",[p,...b]=n.end,m=u;if(p?.source===d)m=p.offset+p.source.length;else{let y=a[0].toUpperCase()+a.substring(1),E=f?`${y} must end with a ${d}`:`${y} in block collection must be sufficiently indented and end with a ${d}`;s(u,f?"MISSING_CHAR":"BAD_INDENT",E),p&&p.source.length!==1&&b.unshift(p)}if(b.length>0){let y=vw.resolveEnd(b,m,t.options.strict,s);y.comment&&(l.comment?l.comment+=`
80
- `+y.comment:l.comment=y.comment),l.range=[n.offset,m,y.offset]}else l.range=[n.offset,m,m];return l}Mf.resolveFlowCollection=xw});var jf=P(Bf=>{"use strict";var Ew=I(),Aw=J(),Tw=We(),Pw=He(),Ow=_f(),Rw=Nf(),_w=Df();function ma(r,e,t,n,s,i){let o=t.type==="block-map"?Ow.resolveBlockMap(r,e,t,n,i):t.type==="block-seq"?Rw.resolveBlockSeq(r,e,t,n,i):_w.resolveFlowCollection(r,e,t,n,i),a=o.constructor;return s==="!"||s===a.tagName?(o.tag=a.tagName,o):(s&&(o.tag=s),o)}function Cw(r,e,t,n,s){let i=n.tag,o=i?e.directives.tagName(i.source,d=>s(i,"TAG_RESOLVE_FAILED",d)):null;if(t.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=n,b=d&&i?d.offset>i.offset?d:i:d??i;b&&(!p||p.offset<b.offset)&&s(b,"MISSING_CHAR","Missing newline after block sequence props")}let a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===Tw.YAMLMap.tagName&&a==="map"||o===Pw.YAMLSeq.tagName&&a==="seq")return ma(r,e,t,s,o);let c=e.schema.tags.find(d=>d.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?s(i,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),ma(r,e,t,s,o)}let l=ma(r,e,t,s,o,c),f=c.resolve?.(l,d=>s(i,"TAG_RESOLVE_FAILED",d),e.options)??l,u=Ew.isNode(f)?f:new Aw.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Bf.composeCollection=Cw});var ga=P(Ff=>{"use strict";var ha=J();function Nw(r,e,t){let n=e.offset,s=Iw(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?ha.Scalar.BLOCK_FOLDED:ha.Scalar.BLOCK_LITERAL,o=e.source?Lw(e.source):[],a=o.length;for(let m=o.length-1;m>=0;--m){let y=o[m][1];if(y===""||y==="\r")a=m;else break}if(a===0){let m=s.chomp==="+"&&o.length>0?`
80
+ `+y.comment:l.comment=y.comment),l.range=[n.offset,m,y.offset]}else l.range=[n.offset,m,m];return l}$f.resolveFlowCollection=xw});var jf=P(Bf=>{"use strict";var Ew=I(),Aw=J(),Tw=We(),Pw=He(),Ow=_f(),Rw=Nf(),_w=Df();function ma(r,e,t,n,s,i){let o=t.type==="block-map"?Ow.resolveBlockMap(r,e,t,n,i):t.type==="block-seq"?Rw.resolveBlockSeq(r,e,t,n,i):_w.resolveFlowCollection(r,e,t,n,i),a=o.constructor;return s==="!"||s===a.tagName?(o.tag=a.tagName,o):(s&&(o.tag=s),o)}function Cw(r,e,t,n,s){let i=n.tag,o=i?e.directives.tagName(i.source,d=>s(i,"TAG_RESOLVE_FAILED",d)):null;if(t.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=n,b=d&&i?d.offset>i.offset?d:i:d??i;b&&(!p||p.offset<b.offset)&&s(b,"MISSING_CHAR","Missing newline after block sequence props")}let a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===Tw.YAMLMap.tagName&&a==="map"||o===Pw.YAMLSeq.tagName&&a==="seq")return ma(r,e,t,s,o);let c=e.schema.tags.find(d=>d.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?s(i,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),ma(r,e,t,s,o)}let l=ma(r,e,t,s,o,c),f=c.resolve?.(l,d=>s(i,"TAG_RESOLVE_FAILED",d),e.options)??l,u=Ew.isNode(f)?f:new Aw.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Bf.composeCollection=Cw});var ga=P(Ff=>{"use strict";var ha=J();function Nw(r,e,t){let n=e.offset,s=Iw(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?ha.Scalar.BLOCK_FOLDED:ha.Scalar.BLOCK_LITERAL,o=e.source?Lw(e.source):[],a=o.length;for(let m=o.length-1;m>=0;--m){let y=o[m][1];if(y===""||y==="\r")a=m;else break}if(a===0){let m=s.chomp==="+"&&o.length>0?`
81
81
  `.repeat(Math.max(1,o.length-1)):"",y=n+s.length;return e.source&&(y+=e.source.length),{value:m,type:i,comment:s.comment,range:[n,y,y]}}let c=e.indent+s.indent,l=e.offset+s.length,f=0;for(let m=0;m<a;++m){let[y,E]=o[m];if(E===""||E==="\r")s.indent===0&&y.length>c&&(c=y.length);else{y.length<c&&t(l+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(c=y.length),f=m,c===0&&!r.atRoot&&t(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=y.length+E.length+1}for(let m=o.length-1;m>=a;--m)o[m][0].length>c&&(a=m+1);let u="",d="",p=!1;for(let m=0;m<f;++m)u+=o[m][0].slice(c)+`
82
82
  `;for(let m=f;m<a;++m){let[y,E]=o[m];l+=y.length+E.length+1;let T=E[E.length-1]==="\r";if(T&&(E=E.slice(0,-1)),E&&y.length<c){let w=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;t(l-E.length-(T?2:1),"BAD_INDENT",w),y=""}i===ha.Scalar.BLOCK_LITERAL?(u+=d+y.slice(c)+E,d=`
83
83
  `):y.length>c||E[0]===" "?(d===" "?d=`
@@ -92,7 +92,7 @@ ${l}
92
92
  `+o[m][0].slice(c);u[u.length-1]!==`
93
93
  `&&(u+=`
94
94
  `);break;default:u+=`
95
- `}let b=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,b,b]}}function Iw({offset:r,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=e[0],i=s[0],o=0,a="",c=-1;for(let d=1;d<s.length;++d){let p=s[d];if(!a&&(p==="-"||p==="+"))a=p;else{let b=Number(p);!o&&b?o=b:c===-1&&(c=r+d)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,f="",u=s.length;for(let d=1;d<e.length;++d){let p=e[d];switch(p.type){case"space":l=!0;case"newline":u+=p.source.length;break;case"comment":t&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,f=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let b=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",b);let m=p.source;m&&typeof m=="string"&&(u+=m.length)}}}return{mode:i,indent:o,chomp:a,comment:f,length:u}}function Lw(r){let e=r.split(/\n( *)/),t=e[0],n=t.match(/^( *)/),i=[n?.[1]?[n[1],t.slice(n[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)i.push([e[o],e[o+1]]);return i}Ff.resolveBlockScalar=Nw});var ba=P(Uf=>{"use strict";var ya=J(),$w=Kt();function Mw(r,e,t){let{offset:n,type:s,source:i,end:o}=r,a,c,l=(d,p,b)=>t(n+d,p,b);switch(s){case"scalar":a=ya.Scalar.PLAIN,c=Dw(i,l);break;case"single-quoted-scalar":a=ya.Scalar.QUOTE_SINGLE,c=Bw(i,l);break;case"double-quoted-scalar":a=ya.Scalar.QUOTE_DOUBLE,c=jw(i,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}let f=n+i.length,u=$w.resolveEnd(o,f,e,t);return{value:c,type:a,comment:u.comment,range:[n,f,u.offset]}}function Dw(r,e){let t="";switch(r[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),qf(r)}function Bw(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),qf(r.slice(1,-1)).replace(/''/g,"'")}function qf(r){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
95
+ `}let b=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,b,b]}}function Iw({offset:r,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=e[0],i=s[0],o=0,a="",c=-1;for(let d=1;d<s.length;++d){let p=s[d];if(!a&&(p==="-"||p==="+"))a=p;else{let b=Number(p);!o&&b?o=b:c===-1&&(c=r+d)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,f="",u=s.length;for(let d=1;d<e.length;++d){let p=e[d];switch(p.type){case"space":l=!0;case"newline":u+=p.source.length;break;case"comment":t&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,f=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let b=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",b);let m=p.source;m&&typeof m=="string"&&(u+=m.length)}}}return{mode:i,indent:o,chomp:a,comment:f,length:u}}function Lw(r){let e=r.split(/\n( *)/),t=e[0],n=t.match(/^( *)/),i=[n?.[1]?[n[1],t.slice(n[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)i.push([e[o],e[o+1]]);return i}Ff.resolveBlockScalar=Nw});var ba=P(Uf=>{"use strict";var ya=J(),Mw=Kt();function $w(r,e,t){let{offset:n,type:s,source:i,end:o}=r,a,c,l=(d,p,b)=>t(n+d,p,b);switch(s){case"scalar":a=ya.Scalar.PLAIN,c=Dw(i,l);break;case"single-quoted-scalar":a=ya.Scalar.QUOTE_SINGLE,c=Bw(i,l);break;case"double-quoted-scalar":a=ya.Scalar.QUOTE_DOUBLE,c=jw(i,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}let f=n+i.length,u=Mw.resolveEnd(o,f,e,t);return{value:c,type:a,comment:u.comment,range:[n,f,u.offset]}}function Dw(r,e){let t="";switch(r[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),qf(r)}function Bw(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),qf(r.slice(1,-1)).replace(/''/g,"'")}function qf(r){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
96
96
  `,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
97
97
  `,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(r);if(!n)return r;let s=n[1],i=" ",o=e.lastIndex;for(t.lastIndex=o;n=t.exec(r);)n[1]===""?i===`
98
98
  `?s+=i:i=`
@@ -107,7 +107,7 @@ ${l}
107
107
  `);)n===`
108
108
  `&&(t+=`
109
109
  `),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var qw={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
110
- `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Uw(r,e,t,n){let s=r.substr(e,t),o=s.length===t&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;if(isNaN(o)){let a=r.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}Uf.resolveFlowScalar=Mw});var Wf=P(Kf=>{"use strict";var ut=I(),Jf=J(),Jw=ga(),Kw=ba();function Ww(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?Jw.resolveBlockScalar(r,e,n):Kw.resolveFlowScalar(e,r.options.strict,n),c=t?r.directives.tagName(t.source,u=>n(t,"TAG_RESOLVE_FAILED",u)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[ut.SCALAR]:c?l=Hw(r.schema,s,c,t,n):e.type==="scalar"?l=Vw(r,s,e,n):l=r.schema[ut.SCALAR];let f;try{let u=l.resolve(s,d=>n(t??e,"TAG_RESOLVE_FAILED",d),r.options);f=ut.isScalar(u)?u:new Jf.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);n(t??e,"TAG_RESOLVE_FAILED",d),f=new Jf.Scalar(s)}return f.range=a,f.source=s,i&&(f.type=i),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Hw(r,e,t,n,s){if(t==="!")return r[ut.SCALAR];let i=[];for(let a of r.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)i.push(a);else return a;for(let a of i)if(a.test?.test(e))return a;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(s(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[ut.SCALAR])}function Vw({atKey:r,directives:e,schema:t},n,s,i){let o=t.tags.find(a=>(a.default===!0||r&&a.default==="key")&&a.test?.test(n))||t[ut.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[ut.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;i(s,"TAG_RESOLVE_FAILED",f,!0)}}return o}Kf.composeScalar=Ww});var Vf=P(Hf=>{"use strict";function Yw(r,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let s=e[n];switch(s.type){case"space":case"comment":case"newline":r-=s.source.length;continue}for(s=e[++n];s?.type==="space";)r+=s.source.length,s=e[++n];break}}return r}Hf.emptyScalarPosition=Yw});var zf=P(va=>{"use strict";var Gw=Er(),zw=I(),Qw=jf(),Yf=Wf(),Xw=Kt(),Zw=Vf(),ev={composeNode:Gf,composeEmptyNode:wa};function Gf(r,e,t,n){let s=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=t,l,f=!0;switch(e.type){case"alias":l=tv(r,e,n),(a||c)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Yf.composeScalar(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=Qw.composeCollection(ev,r,e,t,n),a&&(l.anchor=a.source.substring(1));break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",u),l=wa(r,e.offset,void 0,null,t,n),f=!1}}return a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&r.options.stringKeys&&(!zw.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&f&&(l.srcToken=e),l}function wa(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:Zw.emptyScalarPosition(e,t,n),indent:-1,source:""},u=Yf.composeScalar(r,f,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=c),u}function tv({options:r},{offset:e,source:t,end:n},s){let i=new Gw.Alias(t.substring(1));i.source===""&&s(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&s(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=Xw.resolveEnd(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}va.composeEmptyNode=wa;va.composeNode=Gf});var Zf=P(Xf=>{"use strict";var rv=qr(),Qf=zf(),nv=Kt(),sv=Wr();function iv(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new rv.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=sv.resolveProps(n,{indicator:"doc-start",next:s??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Qf.composeNode(l,s,f,o):Qf.composeEmptyNode(l,f.end,n,null,f,o);let u=c.contents.range[2],d=nv.resolveEnd(i,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[t,u,d.offset],c}Xf.composeDoc=iv});var ka=P(rd=>{"use strict";var ov=Pn("process"),av=oo(),cv=qr(),Hr=Kr(),ed=I(),lv=Zf(),uv=Kt();function Vr(r){if(typeof r=="number")return[r,r+1];if(Array.isArray(r))return r.length===2?r:[r[0],r[1]];let{offset:e,source:t}=r;return[e,e+(typeof t=="string"?t.length:1)]}function td(r){let e="",t=!1,n=!1;for(let s=0;s<r.length;++s){let i=r[s];switch(i[0]){case"#":e+=(e===""?"":n?`
110
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Uw(r,e,t,n){let s=r.substr(e,t),o=s.length===t&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;if(isNaN(o)){let a=r.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}Uf.resolveFlowScalar=$w});var Wf=P(Kf=>{"use strict";var ut=I(),Jf=J(),Jw=ga(),Kw=ba();function Ww(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?Jw.resolveBlockScalar(r,e,n):Kw.resolveFlowScalar(e,r.options.strict,n),c=t?r.directives.tagName(t.source,u=>n(t,"TAG_RESOLVE_FAILED",u)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[ut.SCALAR]:c?l=Hw(r.schema,s,c,t,n):e.type==="scalar"?l=Vw(r,s,e,n):l=r.schema[ut.SCALAR];let f;try{let u=l.resolve(s,d=>n(t??e,"TAG_RESOLVE_FAILED",d),r.options);f=ut.isScalar(u)?u:new Jf.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);n(t??e,"TAG_RESOLVE_FAILED",d),f=new Jf.Scalar(s)}return f.range=a,f.source=s,i&&(f.type=i),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Hw(r,e,t,n,s){if(t==="!")return r[ut.SCALAR];let i=[];for(let a of r.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)i.push(a);else return a;for(let a of i)if(a.test?.test(e))return a;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(s(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[ut.SCALAR])}function Vw({atKey:r,directives:e,schema:t},n,s,i){let o=t.tags.find(a=>(a.default===!0||r&&a.default==="key")&&a.test?.test(n))||t[ut.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[ut.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;i(s,"TAG_RESOLVE_FAILED",f,!0)}}return o}Kf.composeScalar=Ww});var Vf=P(Hf=>{"use strict";function Yw(r,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let s=e[n];switch(s.type){case"space":case"comment":case"newline":r-=s.source.length;continue}for(s=e[++n];s?.type==="space";)r+=s.source.length,s=e[++n];break}}return r}Hf.emptyScalarPosition=Yw});var zf=P(va=>{"use strict";var Gw=Er(),zw=I(),Qw=jf(),Yf=Wf(),Xw=Kt(),Zw=Vf(),ev={composeNode:Gf,composeEmptyNode:wa};function Gf(r,e,t,n){let s=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=t,l,f=!0;switch(e.type){case"alias":l=tv(r,e,n),(a||c)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Yf.composeScalar(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=Qw.composeCollection(ev,r,e,t,n),a&&(l.anchor=a.source.substring(1));break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",u),l=wa(r,e.offset,void 0,null,t,n),f=!1}}return a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&r.options.stringKeys&&(!zw.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&f&&(l.srcToken=e),l}function wa(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:Zw.emptyScalarPosition(e,t,n),indent:-1,source:""},u=Yf.composeScalar(r,f,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=c),u}function tv({options:r},{offset:e,source:t,end:n},s){let i=new Gw.Alias(t.substring(1));i.source===""&&s(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&s(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=Xw.resolveEnd(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}va.composeEmptyNode=wa;va.composeNode=Gf});var Zf=P(Xf=>{"use strict";var rv=qr(),Qf=zf(),nv=Kt(),sv=Wr();function iv(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new rv.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=sv.resolveProps(n,{indicator:"doc-start",next:s??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Qf.composeNode(l,s,f,o):Qf.composeEmptyNode(l,f.end,n,null,f,o);let u=c.contents.range[2],d=nv.resolveEnd(i,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[t,u,d.offset],c}Xf.composeDoc=iv});var ka=P(rd=>{"use strict";var ov=Pn("process"),av=oo(),cv=qr(),Hr=Kr(),ed=I(),lv=Zf(),uv=Kt();function Vr(r){if(typeof r=="number")return[r,r+1];if(Array.isArray(r))return r.length===2?r:[r[0],r[1]];let{offset:e,source:t}=r;return[e,e+(typeof t=="string"?t.length:1)]}function td(r){let e="",t=!1,n=!1;for(let s=0;s<r.length;++s){let i=r[s];switch(i[0]){case"#":e+=(e===""?"":n?`
111
111
 
112
112
  `:`
113
113
  `)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":r[s+1]?.[0]!=="#"&&(s+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var Sa=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=Vr(t);i?this.warnings.push(new Hr.YAMLWarning(o,n,s)):this.errors.push(new Hr.YAMLParseError(o,n,s))},this.directives=new av.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=td(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}
@@ -143,11 +143,11 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
143
143
  `,i=this.buffer[n+1]):t=n),i==="#"||e&&Es.has(i))break;if(s===`
144
144
  `){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Es.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield Yr.SCALAR,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(_a))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(ue(t)||e&&Es.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!ue(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(Tv.has(t))t=this.buffer[++e];else if(t==="%"&&dd.has(this.buffer[e+1])&&dd.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
145
145
  `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
146
- `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let s=t-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};pd.Lexer=Ca});var La=P(md=>{"use strict";var Ia=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let i=t+n>>1;this.lineStarts[i]<e?t=i+1:n=i}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let s=this.lineStarts[t-1];return{line:t,col:e-s+1}}}};md.LineCounter=Ia});var Ma=P(wd=>{"use strict";var Ov=Pn("process"),hd=xs(),Rv=Na();function Ve(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function gd(r){for(let e=0;e<r.length;++e)switch(r[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function bd(r){switch(r?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function As(r){switch(r.type){case"document":return r.start;case"block-map":{let e=r.items[r.items.length-1];return e.sep??e.start}case"block-seq":return r.items[r.items.length-1].start;default:return[]}}function Wt(r){if(r.length===0)return[];let e=r.length;e:for(;--e>=0;)switch(r[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;r[++e]?.type==="space";);return r.splice(e,r.length)}function yd(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!Ve(e.start,"explicit-key-ind")&&!Ve(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,bd(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}var $a=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Rv.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,Ov.env.LOG_TOKENS&&console.log("|",hd.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=hd.tokenType(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let n=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&yd(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{let s=n.items[n.items.length-1];if(s.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(s.sep)s.value=t;else{Object.assign(s,{key:t,sep:[]}),this.onKeyLine=!s.explicitKey;return}break}case"block-seq":{let s=n.items[n.items.length-1];s.value?n.items.push({start:[],value:t}):s.value=t;break}case"flow-collection":{let s=n.items[n.items.length-1];!s||s.value?n.items.push({start:[],key:t,sep:[]}):s.sep?s.value=t:Object.assign(s,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let s=t.items[t.items.length-1];s&&!s.sep&&!s.value&&s.start.length>0&&gd(s.start)===-1&&(t.indent===0||s.start.every(i=>i.type!=="comment"||i.indent<t.indent))&&(n.type==="document"?n.end=s.start:n.items.push({start:s.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{gd(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let t=As(this.peek(2)),n=Wt(t),s;e.end?(s=e.end,s.push(this.sourceToken),delete e.end):s=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
146
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let s=t-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};pd.Lexer=Ca});var La=P(md=>{"use strict";var Ia=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let i=t+n>>1;this.lineStarts[i]<e?t=i+1:n=i}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let s=this.lineStarts[t-1];return{line:t,col:e-s+1}}}};md.LineCounter=Ia});var $a=P(wd=>{"use strict";var Ov=Pn("process"),hd=xs(),Rv=Na();function Ve(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function gd(r){for(let e=0;e<r.length;++e)switch(r[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function bd(r){switch(r?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function As(r){switch(r.type){case"document":return r.start;case"block-map":{let e=r.items[r.items.length-1];return e.sep??e.start}case"block-seq":return r.items[r.items.length-1].start;default:return[]}}function Wt(r){if(r.length===0)return[];let e=r.length;e:for(;--e>=0;)switch(r[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;r[++e]?.type==="space";);return r.splice(e,r.length)}function yd(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!Ve(e.start,"explicit-key-ind")&&!Ve(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,bd(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}var Ma=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Rv.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,Ov.env.LOG_TOKENS&&console.log("|",hd.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=hd.tokenType(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let n=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&yd(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{let s=n.items[n.items.length-1];if(s.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(s.sep)s.value=t;else{Object.assign(s,{key:t,sep:[]}),this.onKeyLine=!s.explicitKey;return}break}case"block-seq":{let s=n.items[n.items.length-1];s.value?n.items.push({start:[],value:t}):s.value=t;break}case"flow-collection":{let s=n.items[n.items.length-1];!s||s.value?n.items.push({start:[],key:t,sep:[]}):s.sep?s.value=t:Object.assign(s,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let s=t.items[t.items.length-1];s&&!s.sep&&!s.value&&s.start.length>0&&gd(s.start)===-1&&(t.indent===0||s.start.every(i=>i.type!=="comment"||i.indent<t.indent))&&(n.type==="document"?n.end=s.start:n.items.push({start:s.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{gd(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let t=As(this.peek(2)),n=Wt(t),s;e.end?(s=e.end,s.push(this.sourceToken),delete e.end):s=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
147
147
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
148
148
  `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,s=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ve(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(bd(t.key)&&!Ve(t.sep,"newline")){let o=Wt(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(Ve(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=Wt(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||s?e.items.push({start:i,key:null,sep:[this.sourceToken]}):Ve(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);s||t.value?(e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Ve(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Ve(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:s,sep:[]}):t.sep?this.stack.push(s):Object.assign(t,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let s=As(n),i=Wt(s);yd(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
149
149
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
150
- `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=As(e),n=Wt(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=As(e),n=Wt(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};wd.Parser=$a});var Ed=P(zr=>{"use strict";var vd=ka(),_v=qr(),Gr=Kr(),Cv=vo(),Nv=I(),Iv=La(),Sd=Ma();function kd(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new Iv.LineCounter||null,prettyErrors:e}}function Lv(r,e={}){let{lineCounter:t,prettyErrors:n}=kd(e),s=new Sd.Parser(t?.addNewLine),i=new vd.Composer(e),o=Array.from(i.compose(s.parse(r)));if(n&&t)for(let a of o)a.errors.forEach(Gr.prettifyError(r,t)),a.warnings.forEach(Gr.prettifyError(r,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function xd(r,e={}){let{lineCounter:t,prettyErrors:n}=kd(e),s=new Sd.Parser(t?.addNewLine),i=new vd.Composer(e),o=null;for(let a of i.compose(s.parse(r),!0,r.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Gr.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Gr.prettifyError(r,t)),o.warnings.forEach(Gr.prettifyError(r,t))),o}function $v(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=xd(r,t);if(!s)return null;if(s.warnings.forEach(i=>Cv.warn(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:n},t))}function Mv(r,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let s=Math.round(t);t=s<1?void 0:s>8?{indent:8}:{indent:s}}if(r===void 0){let{keepUndefined:s}=t??e??{};if(!s)return}return Nv.isDocument(r)&&!n?r.toString(t):new _v.Document(r,n,t).toString(t)}zr.parse=$v;zr.parseAllDocuments=Lv;zr.parseDocument=xd;zr.stringify=Mv});var Td=P(D=>{"use strict";var Dv=ka(),Bv=qr(),jv=ra(),Da=Kr(),Fv=Er(),Ye=I(),qv=Je(),Uv=J(),Jv=We(),Kv=He(),Wv=xs(),Hv=Na(),Vv=La(),Yv=Ma(),Ts=Ed(),Ad=vr();D.Composer=Dv.Composer;D.Document=Bv.Document;D.Schema=jv.Schema;D.YAMLError=Da.YAMLError;D.YAMLParseError=Da.YAMLParseError;D.YAMLWarning=Da.YAMLWarning;D.Alias=Fv.Alias;D.isAlias=Ye.isAlias;D.isCollection=Ye.isCollection;D.isDocument=Ye.isDocument;D.isMap=Ye.isMap;D.isNode=Ye.isNode;D.isPair=Ye.isPair;D.isScalar=Ye.isScalar;D.isSeq=Ye.isSeq;D.Pair=qv.Pair;D.Scalar=Uv.Scalar;D.YAMLMap=Jv.YAMLMap;D.YAMLSeq=Kv.YAMLSeq;D.CST=Wv;D.Lexer=Hv.Lexer;D.LineCounter=Vv.LineCounter;D.Parser=Yv.Parser;D.parse=Ts.parse;D.parseAllDocuments=Ts.parseAllDocuments;D.parseDocument=Ts.parseDocument;D.stringify=Ts.stringify;D.visit=Ad.visit;D.visitAsync=Ad.visitAsync});function zv(r){try{return JSON.parse(r.trim()),!0}catch{return!1}}function Qv(r){let e=r.trim();if(!e.startsWith("<"))return!1;let t=e.match(Gv);return t?wr(e,t[1])!==null:!1}function Xv(r){let e=r.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=Pd.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function Od(r){return zv(r)||Qv(r)||Xv(r)}var Pd,Gv,Ba=R(()=>{Dl();Pd=og(Td(),1),Gv=/<([a-zA-Z_][\w.-]*)/});function Zv(r){if(!r?.trim())return[];let e=r.replace(/\r\n/g,`
150
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=As(e),n=Wt(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=As(e),n=Wt(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};wd.Parser=Ma});var Ed=P(zr=>{"use strict";var vd=ka(),_v=qr(),Gr=Kr(),Cv=vo(),Nv=I(),Iv=La(),Sd=$a();function kd(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new Iv.LineCounter||null,prettyErrors:e}}function Lv(r,e={}){let{lineCounter:t,prettyErrors:n}=kd(e),s=new Sd.Parser(t?.addNewLine),i=new vd.Composer(e),o=Array.from(i.compose(s.parse(r)));if(n&&t)for(let a of o)a.errors.forEach(Gr.prettifyError(r,t)),a.warnings.forEach(Gr.prettifyError(r,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function xd(r,e={}){let{lineCounter:t,prettyErrors:n}=kd(e),s=new Sd.Parser(t?.addNewLine),i=new vd.Composer(e),o=null;for(let a of i.compose(s.parse(r),!0,r.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Gr.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Gr.prettifyError(r,t)),o.warnings.forEach(Gr.prettifyError(r,t))),o}function Mv(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=xd(r,t);if(!s)return null;if(s.warnings.forEach(i=>Cv.warn(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:n},t))}function $v(r,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let s=Math.round(t);t=s<1?void 0:s>8?{indent:8}:{indent:s}}if(r===void 0){let{keepUndefined:s}=t??e??{};if(!s)return}return Nv.isDocument(r)&&!n?r.toString(t):new _v.Document(r,n,t).toString(t)}zr.parse=Mv;zr.parseAllDocuments=Lv;zr.parseDocument=xd;zr.stringify=$v});var Td=P(D=>{"use strict";var Dv=ka(),Bv=qr(),jv=ra(),Da=Kr(),Fv=Er(),Ye=I(),qv=Je(),Uv=J(),Jv=We(),Kv=He(),Wv=xs(),Hv=Na(),Vv=La(),Yv=$a(),Ts=Ed(),Ad=vr();D.Composer=Dv.Composer;D.Document=Bv.Document;D.Schema=jv.Schema;D.YAMLError=Da.YAMLError;D.YAMLParseError=Da.YAMLParseError;D.YAMLWarning=Da.YAMLWarning;D.Alias=Fv.Alias;D.isAlias=Ye.isAlias;D.isCollection=Ye.isCollection;D.isDocument=Ye.isDocument;D.isMap=Ye.isMap;D.isNode=Ye.isNode;D.isPair=Ye.isPair;D.isScalar=Ye.isScalar;D.isSeq=Ye.isSeq;D.Pair=qv.Pair;D.Scalar=Uv.Scalar;D.YAMLMap=Jv.YAMLMap;D.YAMLSeq=Kv.YAMLSeq;D.CST=Wv;D.Lexer=Hv.Lexer;D.LineCounter=Vv.LineCounter;D.Parser=Yv.Parser;D.parse=Ts.parse;D.parseAllDocuments=Ts.parseAllDocuments;D.parseDocument=Ts.parseDocument;D.stringify=Ts.stringify;D.visit=Ad.visit;D.visitAsync=Ad.visitAsync});function zv(r){try{return JSON.parse(r.trim()),!0}catch{return!1}}function Qv(r){let e=r.trim();if(!e.startsWith("<"))return!1;let t=e.match(Gv);return t?wr(e,t[1])!==null:!1}function Xv(r){let e=r.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=Pd.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function Od(r){return zv(r)||Qv(r)||Xv(r)}var Pd,Gv,Ba=R(()=>{Dl();Pd=og(Td(),1),Gv=/<([a-zA-Z_][\w.-]*)/});function Zv(r){if(!r?.trim())return[];let e=r.replace(/\r\n/g,`
151
151
  `),t=e.trim();if(Od(t))return[{text:t,startLine:1,endLine:e.split(`
152
152
  `).length}];let n=e.split(`
153
153
  `),s=[],i=0,o=-1,a=0,c=()=>{if(o>=i){let l=n.slice(i,o+1).join(`
@@ -336,13 +336,13 @@ const something = require('module-name') // NOT SUPPORTED!
336
336
 
337
337
  `);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function ic(r){let t=r.split(/\r?\n/).filter(s=>s.startsWith("data:"));if(!t.length)return null;let n=t.map(s=>s.replace(/^data:\s?/,"")).join(`
338
338
  `).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*fp(r,e,t){let n=new TextDecoder,s="",i=e?new Promise((o,a)=>{e.aborted&&a(new Error("Aborted")),e.addEventListener("abort",()=>a(new Error("Aborted")),{once:!0})}):null;try{for(;;){let{done:o,value:a}=i?await Promise.race([r.read(),i]):await r.read();if(o){if(s.trim()){let f=ic(s);f!==null&&f!=="done"&&(yield f)}return}t?.(),s+=n.decode(a,{stream:!0});let{pos:c,len:l}=up(s);for(;c!==-1;){let f=s.slice(0,c);s=s.slice(c+l);let u=ic(f);if(u==="done")return;u!==null&&(yield u),{pos:c,len:l}=up(s)}}}finally{try{await r.cancel()}catch{}}}async function bt(r,e){if(!r.body)throw new Error("Response body is missing");let t="";for await(let n of Zt(r,e))n.kind==="text"&&(t+=n.text);return t}async function*Zt(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=yt(t);if(!r.body)return;let s=r.body.getReader();for await(let i of fp(s)){let o=n.parseStreamChunk(i);o?.reasoning&&(yield{kind:"reasoning",text:o.reasoning}),o?.text&&(yield{kind:"text",text:o.text})}}var dp=R(()=>{sc()});var er=R(()=>{cp();Qt();sc();dp();Zs();ec();tc();Xa();Za();rc()});function oc(r){return(r.includes("://")?r:`http://${r}`).replace(/\/+$/,"")}async function Ne(){let[r,e]=await Promise.all([pp(),WS()]);return[...HS(e),...r]}async function WS(){if(tr&&Date.now()-tr.fetchedAt<=JS)return tr.models;let r=await fetch(US).catch(()=>null);return!r||!r.ok?tr?.models??[]:(tr={models:await r.json(),fetchedAt:Date.now()},tr.models)}async function pp(){if(si&&Date.now()-si.fetchedAt<=KS)return si.models;let r=oc(process.env.OLLAMA_HOST??"http://localhost:11434"),e=[];try{let t=await fetch(new URL("/api/tags",r).toString());t.ok&&(e=((await t.json()).models??[]).map(s=>s.name).filter(s=>!!s).map(s=>({provider:"ollama",name:s,friendlyName:s,providerName:"Ollama"})))}catch{}return si={models:e,fetchedAt:Date.now()},e}function HS(r){let e=new Set(Object.entries(rr).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function ac(){return Object.values(rr).some(r=>!!process.env[r])}async function ii(){return ac()||process.env.TB_AI_BASE_URL?!0:(await pp()).length>0}function mp(r,e,t){let n=Math.max(...r.map(o=>o.name.length)),s=Math.max(...r.map(o=>o.friendlyName.length)),i=["Models available to tb.ai (filtered by your .env keys):",""];for(let o of r)i.push(` ${o.name.padEnd(n)} ${o.friendlyName.padEnd(s)} (${o.provider})`);return i.push("","Pass an id as the `model` in tb.ai({ provider, model })."),e&&t&&i.push(`Default (from .env): ${e} / ${t}`),i.join(`
339
- `)}var rr,US,JS,KS,tr,si,nr=R(()=>{rr={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};US="https://api.typebulb.com/api/models",JS=1440*60*1e3,KS=60*1e3,tr=null,si=null});function wt(r,e){let t=r??process.env.TB_AI_PROVIDER,n=e??process.env.TB_AI_MODEL;if(!t)return"No provider specified. Set TB_AI_PROVIDER in your .env file or pass provider in the tb.ai() call.";if(!n)return"No model specified. Set TB_AI_MODEL in your .env file or pass model in the tb.ai() call.";let s;try{s=yt(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${oc(process.env.OLLAMA_HOST??s.defaultBaseUrl)}/v1`,protocol:t,model:n,isFreeModel:!1};if(t==="openai-compat"){let a=process.env.TB_AI_BASE_URL;return a?{apiKey:process.env.TB_AI_API_KEY??"",baseUrl:a,protocol:t,model:n,isFreeModel:!1}:"No base URL for openai-compat. Set TB_AI_BASE_URL (the OpenAI-style base ending in /v1, e.g. http://localhost:1234/v1) in your .env file."}let i=rr[t];if(!i)return`Unknown provider '${t}'.`;let o=process.env[i];return o?{apiKey:o,baseUrl:s.defaultBaseUrl,protocol:t,model:n,isFreeModel:!1}:`No API key for '${t}'. Set ${i} in your .env file.`}function vt(r,e){let t=[...e.system?[{role:"system",content:e.system}]:[],...e.messages.map(s=>({role:s.role,content:s.content}))],n=e.effort;return nc(r,{messages:t,stream:!0,effort:n!=null&&n>=0&&n<=3?n:void 0,webSearch:e.webSearch??!0,signal:e.signal})}var oi=R(()=>{er();nr()});import{realpathSync as zS}from"fs";import{join as lc,resolve as QS}from"path";import{homedir as XS}from"os";function ci(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?lc(r,".."):lc(XS(),".typebulb")}function Ie(){return process.env.TYPEBULB_SERVERS_DIR||lc(ci(),"servers")}function Q(r){let e=QS(r),t=e;try{t=zS.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function bp(r,e){let t=Q(r),n=Q(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var li=R(()=>{});import{readFileSync as ZS,writeFileSync as ek,mkdirSync as tk}from"fs";import{join as rk}from"path";function wp(){return rk(ci(),"trust.json")}function uc(){try{let r=JSON.parse(ZS(wp(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function nk(r){tk(ci(),{recursive:!0}),ek(wp(),JSON.stringify([...r]))}function St(r){return uc().has(Q(r))}function sr(r,e){let t=uc(),n=Q(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),nk(t))}function fc(){return[...uc()]}var fn=R(()=>{li()});function ar(r){if(r.server.trim())return"server-side code (server.ts)";let e=r.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai"))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*(?!log\b)\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}var pi=R(()=>{});import{spawn as Cp}from"child_process";import{readdir as Ak,readFile as Ip,writeFile as Lp,unlink as mc,mkdir as Tk}from"fs/promises";import{mkdirSync as $p,writeFileSync as mi,appendFileSync as Pk,readFileSync as hc}from"fs";import*as ce from"path";import{fileURLToPath as Ok}from"url";function gc(r){return ce.join(Ie(),`${r}.json`)}function pn(r){return ce.join(Ie(),`${r}.log`)}function yc(r){return ce.join(Ie(),`${r}.wait.json`)}function Mp(r){try{let e=JSON.parse(hc(yc(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function bc(r,e=""){let t=Mp(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function hi(r,e,t=""){try{$p(Ie(),{recursive:!0});let n=Mp(r);n[t]=e,mi(yc(r),JSON.stringify({cursors:n}))}catch{}}function gi(r){let e=pn(r);try{$p(Ie(),{recursive:!0}),mi(e,"")}catch{return()=>{}}let t=process.stdout.write.bind(process.stdout),n=process.stderr.write.bind(process.stderr),s=0,i=!1,o=a=>{if(!i)try{let c=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(Pk(e,c),s+=c.length,s>2*Np){let l=hc(e),f=l.subarray(Math.max(0,l.length-Np));mi(e,f),s=f.length}}catch{i=!0}};return process.stdout.write=((a,...c)=>(o(a),t(a,...c))),process.stderr.write=((a,...c)=>(o(a),n(a,...c))),()=>{process.stdout.write=t,process.stderr.write=n}}function Dp(r){try{mi(pn(r),"")}catch{}}function ve(r,e=0){try{let t=hc(pn(r)),n=e>=0&&e<=t.length?e:0;return{text:t.subarray(n).toString("utf8"),offset:t.length}}catch{return{text:"",offset:0}}}function wc(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function _k(r){let e=Rk.exec(r);return e?Number(e[1]):void 0}function Bp(r,e){let t=r.split(`
339
+ `)}var rr,US,JS,KS,tr,si,nr=R(()=>{rr={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};US="https://api.typebulb.com/api/models",JS=1440*60*1e3,KS=60*1e3,tr=null,si=null});function wt(r,e){let t=r??process.env.TB_AI_PROVIDER,n=e??process.env.TB_AI_MODEL;if(!t)return"No provider specified. Set TB_AI_PROVIDER in your .env file or pass provider in the tb.ai() call.";if(!n)return"No model specified. Set TB_AI_MODEL in your .env file or pass model in the tb.ai() call.";let s;try{s=yt(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${oc(process.env.OLLAMA_HOST??s.defaultBaseUrl)}/v1`,protocol:t,model:n,isFreeModel:!1};if(t==="openai-compat"){let a=process.env.TB_AI_BASE_URL;return a?{apiKey:process.env.TB_AI_API_KEY??"",baseUrl:a,protocol:t,model:n,isFreeModel:!1}:"No base URL for openai-compat. Set TB_AI_BASE_URL (the OpenAI-style base ending in /v1, e.g. http://localhost:1234/v1) in your .env file."}let i=rr[t];if(!i)return`Unknown provider '${t}'.`;let o=process.env[i];return o?{apiKey:o,baseUrl:s.defaultBaseUrl,protocol:t,model:n,isFreeModel:!1}:`No API key for '${t}'. Set ${i} in your .env file.`}function vt(r,e){let t=[...e.system?[{role:"system",content:e.system}]:[],...e.messages.map(s=>({role:s.role,content:s.content}))],n=e.effort;return nc(r,{messages:t,stream:!0,effort:n!=null&&n>=0&&n<=3?n:void 0,webSearch:e.webSearch??!0,signal:e.signal})}var oi=R(()=>{er();nr()});import{realpathSync as zS}from"fs";import{join as lc,resolve as QS}from"path";import{homedir as XS}from"os";function ci(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?lc(r,".."):lc(XS(),".typebulb")}function Ie(){return process.env.TYPEBULB_SERVERS_DIR||lc(ci(),"servers")}function Q(r){let e=QS(r),t=e;try{t=zS.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function bp(r,e){let t=Q(r),n=Q(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var li=R(()=>{});import{readFileSync as ZS,writeFileSync as ek,mkdirSync as tk}from"fs";import{join as rk}from"path";function wp(){return rk(ci(),"trust.json")}function uc(){try{let r=JSON.parse(ZS(wp(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function nk(r){tk(ci(),{recursive:!0}),ek(wp(),JSON.stringify([...r]))}function St(r){return uc().has(Q(r))}function sr(r,e){let t=uc(),n=Q(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),nk(t))}function fc(){return[...uc()]}var fn=R(()=>{li()});function ar(r){if(r.server.trim())return"server-side code (server.ts)";let e=r.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai"))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*(?!log\b)\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}var pi=R(()=>{});import{spawn as Cp}from"child_process";import{readdir as Ak,readFile as Ip,writeFile as Lp,unlink as mc,mkdir as Tk}from"fs/promises";import{mkdirSync as Mp,writeFileSync as mi,appendFileSync as Pk,readFileSync as hc}from"fs";import*as ce from"path";import{fileURLToPath as Ok}from"url";function gc(r){return ce.join(Ie(),`${r}.json`)}function pn(r){return ce.join(Ie(),`${r}.log`)}function yc(r){return ce.join(Ie(),`${r}.wait.json`)}function $p(r){try{let e=JSON.parse(hc(yc(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function bc(r,e=""){let t=$p(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function hi(r,e,t=""){try{Mp(Ie(),{recursive:!0});let n=$p(r);n[t]=e,mi(yc(r),JSON.stringify({cursors:n}))}catch{}}function gi(r){let e=pn(r);try{Mp(Ie(),{recursive:!0}),mi(e,"")}catch{return()=>{}}let t=process.stdout.write.bind(process.stdout),n=process.stderr.write.bind(process.stderr),s=0,i=!1,o=a=>{if(!i)try{let c=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(Pk(e,c),s+=c.length,s>2*Np){let l=hc(e),f=l.subarray(Math.max(0,l.length-Np));mi(e,f),s=f.length}}catch{i=!0}};return process.stdout.write=((a,...c)=>(o(a),t(a,...c))),process.stderr.write=((a,...c)=>(o(a),n(a,...c))),()=>{process.stdout.write=t,process.stderr.write=n}}function Dp(r){try{mi(pn(r),"")}catch{}}function ve(r,e=0){try{let t=hc(pn(r)),n=e>=0&&e<=t.length?e:0;return{text:t.subarray(n).toString("utf8"),offset:t.length}}catch{return{text:"",offset:0}}}function wc(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function _k(r){let e=Rk.exec(r);return e?Number(e[1]):void 0}function Bp(r,e){let t=r.split(`
340
340
  `),n=[];if(t.forEach((o,a)=>{let c=_k(o);c!==void 0&&n.push({id:c,idx:a})}),!n.length)return e==="latest"?r:"";let s=e==="latest"?n[n.length-1]:n.find(o=>o.id===e);if(!s)return"";let i=n.find(o=>o.idx>s.idx);return t.slice(s.idx,i?i.idx:t.length).join(`
341
- `)}function vc(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function yi(r){await Tk(Ie(),{recursive:!0}),await Lp(gc(r.pid),JSON.stringify(r))}async function jp(r,e){let t=gc(r);try{let n=JSON.parse(await Ip(t,"utf8"));if(n.denied===e)return;n.denied=e,await Lp(t,JSON.stringify(n))}catch{}}async function kt(r){await mc(gc(r)).catch(()=>{}),await mc(pn(r)).catch(()=>{}),await mc(yc(r)).catch(()=>{})}async function K(r){let e;try{e=await Ak(Ie())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!/^\d+\.json$/.test(s))return;let i=parseInt(s,10),o;try{o=JSON.parse(await Ip(ce.join(Ie(),s),"utf8"))}catch{await kt(i);return}o&&typeof o.pid=="number"&&vc(o.pid)?t.push(o):await kt(i)})),(r?t.filter(s=>s.agent==null&&bp(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function Sc(r,e){let t=Q(r);return(await K()).find(n=>n.cwd!=null&&Q(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function xt(r){try{process.kill(r,"SIGTERM")}catch{}await kt(r)}function cr(r,e){let t=Q(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&Q(n.file)===t)}async function kc(r){let e=cr(await K(),r);for(let t of e)await xt(t.pid);return e}function Nk(r,e,t){(process.platform==="win32"?Cp("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):Cp(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function Fp(){return ce.join(ce.dirname(Ok(import.meta.url)),"index.js")}function Ik(r,e={}){return{command:process.execPath,args:[Fp(),...e.trust?["--trust"]:[],r,...e.open===!1?["--no-open"]:[]]}}function Lk(r){return{command:process.execPath,args:[Fp(),`agent:${r}`,"--no-open"]}}async function qp(r,e,t,n){let s=await r();if(s)return s;Nk(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await Ck(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function bi(r,e={}){let t=e.cwd??process.cwd(),n=ce.resolve(t,r);return await kc(n),qp(async()=>cr(await K(),n)[0],Ik(r,e),t,ce.basename(r))}async function Up(r,e=process.cwd()){return qp(()=>Sc(e,r),Lk(r),e,`the ${r} mirror`)}var Np,Rk,Ck,$e=R(()=>{li();Np=1e6;Rk=/^── run (\d+) ── /;Ck=r=>new Promise(e=>setTimeout(e,r))});function Se(r){return r.length>5e4?r.slice(0,5e4)+`
342
- \u2026[${r.length-5e4} more characters truncated]`:r}function Me(r){let e=r.replace($k,"").split(`
343
- `).map(i=>i.trim()).filter(Boolean),t=e[0];if(!t)return"";let n=t.length>300?t.slice(0,300).trimEnd()+"\u2026":t,s=e.length-1;return s>0?`${n} (+${s} line${s===1?"":"s"})`:n}var $k,wi,vi=R(()=>{$k=/\u001b\[[0-9;]*m/g;wi=(r,e)=>`![pasted image](data:${e||"image/png"};base64,${r})`});import{existsSync as Mk,readdirSync as Dk,statSync as Bk}from"fs";import{join as jk}from"path";function Si(r){if(!Mk(r))return[];let e;try{e=Dk(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=jk(r,n);try{let i=Bk(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var xc=R(()=>{});var lr,Ec=R(()=>{lr=class{ensureHarnessSupport(){}}});import{openSync as Fk,readSync as qk,closeSync as Uk,statSync as Jk,readdirSync as Kk,readFileSync as Wk,existsSync as Hk}from"fs";import{join as hn}from"path";import{homedir as Pc}from"os";function Vk(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function ki(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?wi(e.data,e.media_type):""}function Ac(r){return typeof r=="string"?Se(r):Array.isArray(r)?r.map(e=>{if(typeof e=="string")return Se(e);let t=e;return typeof t?.text=="string"?Se(t.text):t?.content!=null?Ac(t.content):ki(t)}).join(`
344
- `):r==null?"":Se(JSON.stringify(r))}function Gk(r){let e=r.trim();return!!e&&Hp.some(t=>t.test(e))}function zk(r){let e=r.trim();return e?Hp.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function Xk(r){return r.replace(Qk,"")}function Zk(r){let e=/^<command-name>([\s\S]*?)<\/command-name>/.exec(r)?.[1]?.trim();if(!e)return;let t=/<command-args>([\s\S]*?)<\/command-args>/.exec(r)?.[1]?.trim();return t?`${e} ${t}`:e}function rt(r){let e=Xk(r).trim();return e?Zk(e)??(Gk(e)?"":e):""}function Tc(r){return r?.type==="text"&&typeof r.text=="string"?rt(r.text):""}function Oc(r,e){if(typeof r=="string")return Me(r);if(!r||typeof r!="object")return Me(e);let t=r;if(t.type==="text"&&typeof t.file?.numLines=="number")return ge(t.file.numLines,"line");if(t.type==="image"){let n=Kp(t.file?.originalSize);return n?`image (${n})`:"image"}if(t.type==="pdf"){let n=Kp(t.file?.originalSize);return n?`PDF (${n})`:"PDF"}if(t.type==="parts"&&typeof t.file?.count=="number")return ge(t.file.count,"page");if(t.type==="file_unchanged")return"unchanged since last read";if(t.type==="create"&&typeof t.content=="string")return`created, ${ge(t.content.split(`
345
- `).length,"line")}`;if(t.mode==="content")return ge(t.numLines??0,"line");if(t.mode==="count")return`${ge(t.numMatches??0,"match","matches")} (${ge(t.numFiles??0,"file")})`;if(t.mode==="files_with_matches")return ge(t.numFiles??0,"file");if(Array.isArray(t.structuredPatch)){let n=0,s=0;for(let i of t.structuredPatch)for(let o of i?.lines??[])typeof o=="string"&&(o.startsWith("+")?n++:o.startsWith("-")&&s++);return`+${n} \u2212${s}`}return typeof t.stdout=="string"||typeof t.stderr=="string"?t.backgroundTaskId?"running in background":t.interrupted?"interrupted":Me(t.stdout||t.stderr||"")||"no output":typeof t.code=="number"&&typeof t.codeText=="string"?`${t.code} ${t.codeText}`:typeof t.searchCount=="number"?ge(t.searchCount,"search","searches"):Array.isArray(t.matches)&&typeof t.total_deferred_tools=="number"?ge(t.matches.length,"tool"):Array.isArray(t.newTodos)?ge(t.newTodos.length,"todo"):typeof t.numFiles=="number"?ge(t.numFiles,"file"):Me(e)}function mn(r){return!!r.isSidechain||!!r.isMeta}function ex(r){let e;try{e=Fk(r,"r")}catch{return""}try{let n=65536;try{n=Jk(r).size}catch{}let s=(l,f)=>{if(f<=0)return"";let u=Buffer.alloc(f),d=qk(e,u,0,f,l);return u.subarray(0,d).toString("utf8")},i=(l,f,u)=>{let d="";for(let p of l.split(`
341
+ `)}function vc(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function yi(r){await Tk(Ie(),{recursive:!0}),await Lp(gc(r.pid),JSON.stringify(r))}async function jp(r,e){let t=gc(r);try{let n=JSON.parse(await Ip(t,"utf8"));if(n.denied===e)return;n.denied=e,await Lp(t,JSON.stringify(n))}catch{}}async function kt(r){await mc(gc(r)).catch(()=>{}),await mc(pn(r)).catch(()=>{}),await mc(yc(r)).catch(()=>{})}async function K(r){let e;try{e=await Ak(Ie())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!/^\d+\.json$/.test(s))return;let i=parseInt(s,10),o;try{o=JSON.parse(await Ip(ce.join(Ie(),s),"utf8"))}catch{await kt(i);return}o&&typeof o.pid=="number"&&vc(o.pid)?t.push(o):await kt(i)})),(r?t.filter(s=>s.agent==null&&bp(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function Sc(r,e){let t=Q(r);return(await K()).find(n=>n.cwd!=null&&Q(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function xt(r){try{process.kill(r,"SIGTERM")}catch{}await kt(r)}function cr(r,e){let t=Q(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&Q(n.file)===t)}async function kc(r){let e=cr(await K(),r);for(let t of e)await xt(t.pid);return e}function Nk(r,e,t){(process.platform==="win32"?Cp("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):Cp(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function Fp(){return ce.join(ce.dirname(Ok(import.meta.url)),"index.js")}function Ik(r,e={}){return{command:process.execPath,args:[Fp(),...e.trust?["--trust"]:[],r,...e.open===!1?["--no-open"]:[]]}}function Lk(r){return{command:process.execPath,args:[Fp(),`agent:${r}`,"--no-open"]}}async function qp(r,e,t,n){let s=await r();if(s)return s;Nk(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await Ck(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function bi(r,e={}){let t=e.cwd??process.cwd(),n=ce.resolve(t,r);return await kc(n),qp(async()=>cr(await K(),n)[0],Ik(r,e),t,ce.basename(r))}async function Up(r,e=process.cwd()){return qp(()=>Sc(e,r),Lk(r),e,`the ${r} mirror`)}var Np,Rk,Ck,Me=R(()=>{li();Np=1e6;Rk=/^── run (\d+) ── /;Ck=r=>new Promise(e=>setTimeout(e,r))});function Se(r){return r.length>5e4?r.slice(0,5e4)+`
342
+ \u2026[${r.length-5e4} more characters truncated]`:r}function $e(r){let e=r.replace(Mk,"").split(`
343
+ `).map(i=>i.trim()).filter(Boolean),t=e[0];if(!t)return"";let n=t.length>300?t.slice(0,300).trimEnd()+"\u2026":t,s=e.length-1;return s>0?`${n} (+${s} line${s===1?"":"s"})`:n}var Mk,wi,vi=R(()=>{Mk=/\u001b\[[0-9;]*m/g;wi=(r,e)=>`![pasted image](data:${e||"image/png"};base64,${r})`});import{existsSync as $k,readdirSync as Dk,statSync as Bk}from"fs";import{join as jk}from"path";function Si(r){if(!$k(r))return[];let e;try{e=Dk(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=jk(r,n);try{let i=Bk(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var xc=R(()=>{});var lr,Ec=R(()=>{lr=class{ensureHarnessSupport(){}}});import{openSync as Fk,readSync as qk,closeSync as Uk,statSync as Jk,readdirSync as Kk,readFileSync as Wk,existsSync as Hk}from"fs";import{join as hn}from"path";import{homedir as Pc}from"os";function Vk(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function ki(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?wi(e.data,e.media_type):""}function Ac(r){return typeof r=="string"?Se(r):Array.isArray(r)?r.map(e=>{if(typeof e=="string")return Se(e);let t=e;return typeof t?.text=="string"?Se(t.text):t?.content!=null?Ac(t.content):ki(t)}).join(`
344
+ `):r==null?"":Se(JSON.stringify(r))}function Gk(r){let e=r.trim();return!!e&&Hp.some(t=>t.test(e))}function zk(r){let e=r.trim();return e?Hp.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function Xk(r){return r.replace(Qk,"")}function Zk(r){let e=/^<command-name>([\s\S]*?)<\/command-name>/.exec(r)?.[1]?.trim();if(!e)return;let t=/<command-args>([\s\S]*?)<\/command-args>/.exec(r)?.[1]?.trim();return t?`${e} ${t}`:e}function rt(r){let e=Xk(r).trim();return e?Zk(e)??(Gk(e)?"":e):""}function Tc(r){return r?.type==="text"&&typeof r.text=="string"?rt(r.text):""}function Oc(r,e){if(typeof r=="string")return $e(r);if(!r||typeof r!="object")return $e(e);let t=r;if(t.type==="text"&&typeof t.file?.numLines=="number")return ge(t.file.numLines,"line");if(t.type==="image"){let n=Kp(t.file?.originalSize);return n?`image (${n})`:"image"}if(t.type==="pdf"){let n=Kp(t.file?.originalSize);return n?`PDF (${n})`:"PDF"}if(t.type==="parts"&&typeof t.file?.count=="number")return ge(t.file.count,"page");if(t.type==="file_unchanged")return"unchanged since last read";if(t.type==="create"&&typeof t.content=="string")return`created, ${ge(t.content.split(`
345
+ `).length,"line")}`;if(t.mode==="content")return ge(t.numLines??0,"line");if(t.mode==="count")return`${ge(t.numMatches??0,"match","matches")} (${ge(t.numFiles??0,"file")})`;if(t.mode==="files_with_matches")return ge(t.numFiles??0,"file");if(Array.isArray(t.structuredPatch)){let n=0,s=0;for(let i of t.structuredPatch)for(let o of i?.lines??[])typeof o=="string"&&(o.startsWith("+")?n++:o.startsWith("-")&&s++);return`+${n} \u2212${s}`}return typeof t.stdout=="string"||typeof t.stderr=="string"?t.backgroundTaskId?"running in background":t.interrupted?"interrupted":$e(t.stdout||t.stderr||"")||"no output":typeof t.code=="number"&&typeof t.codeText=="string"?`${t.code} ${t.codeText}`:typeof t.searchCount=="number"?ge(t.searchCount,"search","searches"):Array.isArray(t.matches)&&typeof t.total_deferred_tools=="number"?ge(t.matches.length,"tool"):Array.isArray(t.newTodos)?ge(t.newTodos.length,"todo"):typeof t.numFiles=="number"?ge(t.numFiles,"file"):$e(e)}function mn(r){return!!r.isSidechain||!!r.isMeta}function ex(r){let e;try{e=Fk(r,"r")}catch{return""}try{let n=65536;try{n=Jk(r).size}catch{}let s=(l,f)=>{if(f<=0)return"";let u=Buffer.alloc(f),d=qk(e,u,0,f,l);return u.subarray(0,d).toString("utf8")},i=(l,f,u)=>{let d="";for(let p of l.split(`
346
346
  `)){if(!p.includes(`"${f}"`))continue;let b;try{b=JSON.parse(p)}catch{continue}let m=b?.[u];b?.type===f&&typeof m=="string"&&m&&(d=m)}return d},o=s(0,Math.min(65536,n)),a=n>65536?s(n-65536,65536):"",c=i(a,"custom-title","customTitle")||i(o,"custom-title","customTitle")||i(a,"ai-title","aiTitle")||i(o,"ai-title","aiTitle");if(c)return c.replace(/\s+/g," ").trim().slice(0,200);for(let l of o.split(`
347
347
  `)){if(!l.trim())continue;let f;try{f=JSON.parse(l)}catch{continue}if(!f||mn(f)||f.type!=="user")continue;let u=f.message?.content,d="";typeof u=="string"?d=rt(u):Array.isArray(u)&&(d=u.map(Tc).filter(Boolean).join(" "));let p=d.replace(/\s+/g," ").trim();if(p)return(p.replace(/^Continuing from a prior session\. Here is the summary of our work so far:\s*/i,"").trim()||p).slice(0,200)}return""}finally{Uk(e)}}function tx(r){let e;try{e=Kk(Wp)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let n=JSON.parse(Wk(hn(Wp,t),"utf8"));if(n?.sessionId!==r)continue;return process.kill(n.pid,0),!0}catch{}return!1}var Yk,Jp,Hp,Qk,ge,Kp,Wp,ur,xi=R(()=>{vi();xc();Ec();Yk=hn(Pc(),".claude","projects"),Jp=r=>hn(Yk,Vk(r));Hp=[/\[Request interrupted by user\b/i,/\[Tool use was interrupted\]/i,/Claude Code returned an error/i,/\[ede_diagnostic\]/i,/^No response requested\.?$/i,/^<task-notification\b/i,/^<system-reminder\b/i,/^<local-command-stdout\b/i,/^<local-command-stderr\b/i];Qk=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;ge=(r,e,t=e+"s")=>`${r} ${r===1?e:t}`,Kp=r=>typeof r!="number"?"":r<1024?`${r}B`:r<1048576?`${Math.round(r/1024)}KB`:`${(r/1048576).toFixed(1)}MB`;Wp=hn(Pc(),".claude","sessions");ur=class extends lr{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}detectsInstalled(){return Hk(hn(Pc(),".claude"))}sessionsDir(e){return Jp(e)}listSessionFiles(e){return Si(Jp(e))}parseEntry(e){try{return JSON.parse(e)}catch{return null}}idOf(e){return e.uuid}parentOf(e){return e.parentUuid}timestampOf(e){return e.timestamp}isSidechain(e){return!!e.isSidechain}isLeafType(e){return e.type==="user"||e.type==="assistant"}isRecoveryNoise(e){return!!e.isApiErrorMessage}apply(e,t){if(mn(e))return{events:[]};let n=[];if(e.type==="user"){let s=e.message?.content;if(typeof s=="string"){let i=rt(s);i&&n.push({type:"user",text:i})}else if(Array.isArray(s))for(let i of s)if(i?.type==="tool_result"){let o=Ac(i.content);n.push({type:"tool_result",id:i.tool_use_id??"",content:o,isError:!!i.is_error,digest:Oc(e.toolUseResult,o)})}else{let o=Tc(i)||ki(i);o&&n.push({type:"user",text:o})}return{events:n}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=rt(Ac(e.attachment.prompt));return s&&n.push({type:"user",text:s}),{events:n}}if(e.type==="assistant"){let s=e.message?.content,i=Array.isArray(s)?s:[],o=i.filter(u=>u.type==="text").map(u=>u.text??"").filter(u=>!zk(u)).join(""),a=i.filter(u=>u.type==="thinking").map(u=>u.thinking??"").join(`
348
348
  `),c=i.filter(u=>u.type==="tool_use").map(u=>({id:u.id??"",name:u.name??"",input:u.input??{}}));if(o||a||c.length){let u=Date.parse(e.timestamp??""),d=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:d})}let l=e.message?.usage??e.usage,f=l&&{in:l.input_tokens??0,out:l.output_tokens??0,cached:l.cache_read_input_tokens??0,cacheCreate:l.cache_creation_input_tokens??0};return{events:n,usage:f,model:e.message?.model}}return{events:n}}chainWorking(e){let t;for(let o of e)(o.type==="user"||o.type==="assistant")&&(t=o);if(!t)return!1;if(t.type==="user"){try{let o=t.message?.content,a=typeof o=="string"?o:Array.isArray(o)?o.filter(l=>l&&l.type==="text").map(l=>l.text??"").join(""):"";if(!(Array.isArray(o)&&o.some(l=>l&&l.type==="tool_result"))&&a.trim()&&rt(a)==="")return!1}catch{}return!0}let s=(Array.isArray(t.message?.content)?t.message.content:[]).filter(o=>o.type==="tool_use").map(o=>o.id);if(s.length===0)return!1;let i=new Set;for(let o of e){let a=o.message?.content;if(Array.isArray(a))for(let c of a)c.type==="tool_result"&&c.tool_use_id&&i.add(c.tool_use_id)}return s.some(o=>o&&!i.has(o))}sessionAlive(e){return tx(e)}readPreview(e){return ex(e)}searchText(e){if(!e||mn(e)||e.type!=="user"&&e.type!=="assistant")return"";let t=e.message?.content,n="";if(typeof t=="string")n=rt(t);else if(Array.isArray(t)){let s=t;n=e.type==="user"?s.map(Tc).filter(Boolean).join(" "):s.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(" ")}return n.replace(/\s+/g," ").trim()}}});function Ei(r){let e=/^---[^\n]*\n([\s\S]*?)\n---/.exec(r),t=e?/^\s*name:\s*(.+?)\s*$/m.exec(e[1]):null;return t?t[1].replace(/^["']|["']$/g,""):void 0}function Rc(r){return(Ei(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var _c=R(()=>{});import{readdirSync as rx,readFileSync as nx,statSync as sx}from"fs";import{join as Vp,basename as ix}from"path";function Yp(r,e,t){if(e>8)return t;let n;try{n=rx(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;Yp(Vp(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(Vp(r,s.name));return t}function Ai(r){return Yp(r,0,[]).map(e=>{let t=0;try{t=sx(e).mtimeMs}catch{}let n,s=!1;try{let i=nx(e,"utf8");n=Ei(i.slice(0,1024));let o=Ae(i);s=!!o&&Ps(Ht(o))}catch{}return{path:e,name:n??ix(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var Gp=R(()=>{Qr();Xr();_c()});import{readFile as ox}from"fs/promises";async function Cc(r){try{let e=Ae(await ox(r,"utf-8"));return e?ar(Ht(e)):void 0}catch{return}}var zp=R(()=>{Xr();pi()});function Nc(r){let e=Ae(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=Nd(t);if(!n.length)return r;let s=e.files.get("config.json"),i={};if(s)try{let l=JSON.parse(s);l&&typeof l=="object"&&(i=l)}catch{}let o=i.dependencies&&typeof i.dependencies=="object"?{...i.dependencies}:{},a=n.filter(l=>!(l in o));if(!a.length)return r;for(let l of a)o[l]="latest";i.dependencies=o;let c={name:e.frontmatter.name};for(let[l,f]of e.files){let u=wl(l);u&&(c[u]=f)}return c.config=JSON.stringify(i,null,2),Pl(c)}var Qp=R(()=>{Qr();Os()});import{spawn as Xp}from"child_process";import{basename as ax}from"path";function cx(){return process.env.TYPEBULB_EDITOR||"code"}function ux(r,e,t){return t==null?[e]:lx.test(ax(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function fx(r,e){let t=cx();return{command:t,args:ux(t,r,e)}}function Ic(r,e){let{command:t,args:n}=fx(r,e),s=process.platform==="win32"?Xp("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):Xp(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var lx,Zp=R(()=>{lx=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as dx,existsSync as px}from"fs";import*as Et from"path";import{fileURLToPath as mx}from"url";function em(){let r=Et.dirname(mx(import.meta.url));for(;!px(Et.join(r,"package.json"));){let e=Et.dirname(r);if(e===r)break;r=e}return r}function At(){return Et.join(em(),"README.md")}function fr(){return Et.join(em(),"description.md")}function hx(r){let e=dx(fr(),"utf8").trim().replace(/\s+/g," ");return`---
@@ -354,14 +354,31 @@ version: ${r}
354
354
  ${gx(e)}
355
355
 
356
356
  ${r.trim()}
357
- `}var Ti=R(()=>{});var gn=R(()=>{$e();Gp();zp();_c();Qp();Zp();fn();nr();oi();Ti()});import{copyFileSync as yx,existsSync as rm,mkdirSync as nm,rmSync as bx,writeFileSync as wx}from"fs";import{homedir as vx}from"os";import*as ke from"path";import{fileURLToPath as Sx}from"url";function Px(){return Tx.replace('"__TB_DESCRIPTION_PATH__"',JSON.stringify(fr())).replace('"__TB_README_PATH__"',JSON.stringify(At()))}function sm(){try{if(!rm(Pi()))return}catch{return}try{let r=kx();nm(ke.dirname(r),{recursive:!0}),wx(r,Px()),bx(xx(),{force:!0})}catch{}try{let r=Ex();if(!rm(r))return;let e=Ax();nm(ke.dirname(e),{recursive:!0}),yx(r,e)}catch{}}var Pi,kx,xx,Ex,Ax,Tx,im=R(()=>{gn();Pi=()=>ke.join(vx(),".pi","agent"),kx=()=>ke.join(Pi(),"extensions","typebulb.ts"),xx=()=>ke.join(Pi(),"extensions","typebulb-wait.ts"),Ex=()=>ke.join(ke.dirname(Sx(import.meta.url)),"agents","pi","matchu-patchu.ts"),Ax=()=>ke.join(Pi(),"extensions","matchu-patchu.ts"),Tx=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
357
+ `}var Ti=R(()=>{});var gn=R(()=>{Me();Gp();zp();_c();Qp();Zp();fn();nr();oi();Ti()});import{copyFileSync as yx,existsSync as rm,mkdirSync as nm,rmSync as bx,writeFileSync as wx}from"fs";import{homedir as vx}from"os";import*as ke from"path";import{fileURLToPath as Sx}from"url";function Px(){return Tx.replace('"__TB_DESCRIPTION_PATH__"',JSON.stringify(fr())).replace('"__TB_README_PATH__"',JSON.stringify(At()))}function sm(){try{if(!rm(Pi()))return}catch{return}try{let r=kx();nm(ke.dirname(r),{recursive:!0}),wx(r,Px()),bx(xx(),{force:!0})}catch{}try{let r=Ex();if(!rm(r))return;let e=Ax();nm(ke.dirname(e),{recursive:!0}),yx(r,e)}catch{}}var Pi,kx,xx,Ex,Ax,Tx,im=R(()=>{gn();Pi=()=>ke.join(vx(),".pi","agent"),kx=()=>ke.join(Pi(),"extensions","typebulb.ts"),xx=()=>ke.join(Pi(),"extensions","typebulb-wait.ts"),Ex=()=>ke.join(ke.dirname(Sx(import.meta.url)),"agents","pi","matchu-patchu.ts"),Ax=()=>ke.join(Pi(),"extensions","matchu-patchu.ts"),Tx=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
358
358
  import { spawn } from "node:child_process";
359
+ import { existsSync } from "node:fs";
359
360
 
360
361
  function logErr(...a) { try { console.error("[typebulb]", ...a); } catch (e) {} }
361
362
 
362
363
  // Matches "typebulb wait", "npx typebulb wait", "/path/to/typebulb wait", "pnpm exec typebulb wait", etc.
363
364
  function isWaitCommand(command) { return /\btypebulb\s+wait\b/.test(String(command || "")); }
364
365
 
366
+ // pi's bash tool runs every command under Git Bash on Windows (its getShellConfig), so the
367
+ // intercepted string is POSIX. Re-running it under node's shell:true (cmd.exe on Windows) breaks
368
+ // that syntax — cmd doesn't split on ";", so a trailing "; echo ..." rides along as extra ARGS to
369
+ // typebulb wait, which resolves a garbage target and dies code 1 before the event (field: a wait
370
+ // that resolved the target 'exit: $?'). Resolve bash the way pi does; null → shell:true (POSIX sh).
371
+ function resolveBash() {
372
+ try {
373
+ if (process.platform !== "win32") return existsSync("/bin/bash") ? "/bin/bash" : null;
374
+ var dirs = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]];
375
+ for (var i = 0; i < dirs.length; i++) {
376
+ if (dirs[i] && existsSync(dirs[i] + "\\Git\\bin\\bash.exe")) return dirs[i] + "\\Git\\bin\\bash.exe";
377
+ }
378
+ return "bash.exe"; // PATH fallback (Cygwin/MSYS2); a spawn miss lands in the "error" handler
379
+ } catch (e) { return null; }
380
+ }
381
+
365
382
  // Resolved at shim-write time to this install's absolute skill-part paths (same files
366
383
  // commands/agent.ts prints — readable without a permission prompt, unlike the npx command).
367
384
  var TB_DESCRIPTION_PATH = "__TB_DESCRIPTION_PATH__";
@@ -410,15 +427,23 @@ export default function (pi) {
410
427
  // is a shim-backgrounded (non-blocking) wait, so it runs as a pure subscription: no give-up clock,
411
428
  // it waits for the event however long (bounded by the session-shutdown reap below) — an embed's
412
429
  // first paint OR a running bulb's next event line alike.
413
- const child = spawn(command, {
414
- shell: true,
415
- stdio: ["ignore", "pipe", "ignore"],
430
+ const bash = resolveBash();
431
+ const opts = {
432
+ stdio: ["ignore", "pipe", "pipe"],
416
433
  env: { ...process.env, TYPEBULB_WAIT_SHIM: "1" },
417
- });
434
+ };
435
+ const child = bash ? spawn(bash, ["-c", command], opts) : spawn(command, { ...opts, shell: true });
418
436
  pending.add(child);
419
437
  let out = "";
438
+ let errOut = "";
420
439
  if (child.stdout) child.stdout.on("data", (b) => { out += b.toString(); });
421
- child.on("error", (e) => { pending.delete(child); logErr("spawn", e && e.message); });
440
+ if (child.stderr) child.stderr.on("data", (b) => { errOut += b.toString(); });
441
+ child.on("error", (e) => {
442
+ pending.delete(child);
443
+ logErr("spawn", e && e.message);
444
+ // Same class as a failure exit: the subscription never armed, so silence is a deadlock.
445
+ try { pi.sendUserMessage("typebulb wait FAILED to spawn: " + (e && e.message) + "\nNothing is watching — fix and re-arm the wait.", { deliverAs: "followUp" }); } catch (e2) {}
446
+ });
422
447
  child.on("exit", (code) => {
423
448
  pending.delete(child);
424
449
  try {
@@ -427,6 +452,9 @@ export default function (pi) {
427
452
  // agent (followUp delivers immediately when idle and queues when streaming — the same call
428
453
  // git-merge-and-resolve.ts makes from agent_end). A late wake is fine; it just reports
429
454
  // something true. Exit 2/3 (no render yet / server gone) surface passively, no turn.
455
+ // Any OTHER non-zero exit means the subscription itself broke (bad args, no resolvable
456
+ // mirror): the agent parked on a wake that can never come, so that failure must wake too —
457
+ // missed wakes are fatal, spurious wakes cheap (TB-Wait.md). null (reap-killed) stays silent.
430
458
  // EXCEPT an embed's clean ok verdict ("[embed <name> vN] ok" — core/client/bulbEmbed.ts):
431
459
  // the user already sees the bulb and the skill orders silence on ok, so a wake would spend
432
460
  // a whole turn saying nothing and render a noise message. Silence IS the ok. Anything else
@@ -439,6 +467,9 @@ export default function (pi) {
439
467
  const embedOk = code === 0 && waitLines.length > 0 && waitLines.every(function (l) { return /^\[embed .*\] ok$/.test(l); });
440
468
  if (code === 0 && text && !embedOk) {
441
469
  pi.sendUserMessage("typebulb wait result:\n" + text, { deliverAs: "followUp" });
470
+ } else if (code !== null && code !== 0 && code !== 2 && code !== 3) {
471
+ var diag = (text + "\n" + errOut.trim()).trim();
472
+ pi.sendUserMessage("typebulb wait FAILED (exit " + code + ")" + (diag ? ":\n" + diag : " with no output.") + "\nThe wait never armed — nothing is watching. Fix the command and re-arm it.", { deliverAs: "followUp" });
442
473
  } else if (ctx.ui && typeof ctx.ui.notify === "function") {
443
474
  // INVARIANT: this notify must never quote the "[embed <name>" tag verbatim. In a
444
475
  // composer-driven session the mirror's driver echoes extension notifies into the
@@ -461,21 +492,21 @@ export default function (pi) {
461
492
  try { pi.on("session_shutdown", () => { for (const c of pending) { try { c.kill(); } catch (e) {} } pending.clear(); }); } catch (e) {}
462
493
  } catch (e) { logErr("load", e && e.message); }
463
494
  }
464
- `});function U(r){return r?.message??String(r)}var G,dr=R(()=>{G=process.cwd()});import{spawn as om}from"child_process";import{StringDecoder as Ox}from"string_decoder";function Mx(r,e){let t=new Ox("utf8"),n="";r.on("data",s=>{n+=typeof s=="string"?s:t.write(s);let i;for(;(i=n.indexOf(`
465
- `))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var Rx,_x,am,Cx,Nx,Ix,Lx,$x,Oi,Ri,cm,lm=R(()=>{dr();Rx=3e4,_x=5e3,am=2e3,Cx=2e3,Nx=12e4,Ix=8e3,Lx=15e3,$x=new Set(["get_state","get_commands","get_available_models","set_model","set_thinking_level","cycle_thinking_level","get_session_stats","compact","set_auto_compaction","get_fork_messages","fork","clone","set_session_name","export_html","bash","abort_bash"]),Oi=new Set;process.on("exit",()=>{for(let r of Oi)try{r.kill()}catch{}});Ri=class{#e;#o=!1;#a=0;#i=!1;#c=null;#t=null;#n=null;#l=new Map;#r=[];#p=null;#y=null;#m=null;#b;#u;#h="";#E=1;#s=new Map;#w;#g;constructor(e,t,n=(s,i)=>om(s,{cwd:i,shell:!0,stdio:["pipe","pipe","pipe"],env:{...process.env,TYPEBULB_MIRROR:"1"}})){if(this.#w=new Promise(o=>{this.#g=o}),t?.includes('"')){this.#u="session path contains a quote \u2014 cannot drive it",this.#g();return}let s=t?`pi --mode rpc --session "${t}"`:"pi --mode rpc",i;try{i=n(s,e)}catch(o){this.#u=`could not start pi: ${U(o)}`,this.#g();return}this.#e=i,this.#b=t,Oi.add(i),i.stdout&&Mx(i.stdout,o=>this.#A(o)),i.stderr&&i.stderr.on("data",o=>{this.#h=(this.#h+o.toString()).slice(-Cx)}),i.on("error",o=>this.#k(`could not start pi: ${o.message}`)),i.on("exit",o=>{this.#e===i&&this.#k(o?`pi exited (code ${o})${this.#h.trim()?`: ${this.#h.trim()}`:""}`:"pi exited"),Oi.delete(i),this.#g()}),this.#d({type:"get_state"}).then(o=>{let a=o.data?.sessionFile;typeof a=="string"&&a&&(this.#b=a);let c=o.data?.model;c&&typeof c.id=="string"&&c.id&&(this.#m=c.id)}).catch(()=>{}),this.#v()}get streaming(){return this.#o||Date.now()<this.#a}get draft(){return this.#c}get queue(){return this.#p}get stats(){return this.#y}get model(){return this.#m}get sessionFile(){return this.#b}get error(){return this.#u}get status(){if(this.#t)return this.#t;if(this.#n){if(Date.now()<this.#n.until)return{text:this.#n.text,kind:this.#n.kind};this.#n=null}return this.#l.size?{text:[...this.#l.values()].join(" \xB7 "),kind:"info"}:null}get dialog(){let e=Date.now();for(;this.#r.length;){let t=this.#r[0];if(e<t.until)return t.req;this.#r.shift(),t.ownTimeout||this.#S({type:"extension_ui_response",id:t.req.id,cancelled:!0})}return null}notice(e,t){this.#f(e,t)}respondUi(e,t){let n=this.#r.findIndex(o=>o.req.id===e);if(n<0)return{ok:!1,error:"dialog expired or already answered"};let[s]=this.#r.splice(n,1),i={type:"extension_ui_response",id:e};return t.cancelled?i.cancelled=!0:s.req.method==="confirm"?i.confirmed=!!t.confirmed:i.value=t.value??"",this.#S(i),{ok:!0}}async rpc(e){if(!$x.has(e.type))return{ok:!1,error:`command not allowed: ${e.type}`};try{let t=await this.#d(e);if(t.success&&e.type==="set_model"){let n=t.data?.id;typeof n=="string"&&n&&(this.#m=n)}return t.success?{ok:!0,data:t.data}:{ok:!1,error:t.error??`pi rejected ${e.type}`}}catch(t){return{ok:!1,error:U(t)}}}async send(e,t){let n=this.streaming,s=n?e.trimStart().startsWith("/")?{type:"prompt",message:e,streamingBehavior:t?.followUp?"followUp":"steer"}:{type:t?.followUp?"follow_up":"steer",message:e}:{type:"prompt",message:e},i;try{i=await this.#d(s)}catch(o){return{ok:!1,error:U(o)}}return i.success&&!n&&(this.#a=Date.now()+_x),i.success?{ok:!0}:{ok:!1,error:i.error??"pi rejected the message"}}async stop(){if(this.#e)try{await this.#d({type:"abort"})}catch{}}clearCompletedDraft(){this.#i||(this.#c=null)}async dispose(){let e=this.#e;if(e){if(this.#e=void 0,this.#o){try{e.stdin?.write(JSON.stringify({type:"abort"})+`
495
+ `});function U(r){return r?.message??String(r)}var G,dr=R(()=>{G=process.cwd()});import{spawn as om}from"child_process";import{StringDecoder as Ox}from"string_decoder";function $x(r,e){let t=new Ox("utf8"),n="";r.on("data",s=>{n+=typeof s=="string"?s:t.write(s);let i;for(;(i=n.indexOf(`
496
+ `))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var Rx,_x,am,Cx,Nx,Ix,Lx,Mx,Oi,Ri,cm,lm=R(()=>{dr();Rx=3e4,_x=5e3,am=2e3,Cx=2e3,Nx=12e4,Ix=8e3,Lx=15e3,Mx=new Set(["get_state","get_commands","get_available_models","set_model","set_thinking_level","cycle_thinking_level","get_session_stats","compact","set_auto_compaction","get_fork_messages","fork","clone","set_session_name","export_html","bash","abort_bash"]),Oi=new Set;process.on("exit",()=>{for(let r of Oi)try{r.kill()}catch{}});Ri=class{#e;#o=!1;#a=0;#i=!1;#c=null;#t=null;#n=null;#l=new Map;#r=[];#p=null;#y=null;#m=null;#b;#u;#h="";#E=1;#s=new Map;#w;#g;constructor(e,t,n=(s,i)=>om(s,{cwd:i,shell:!0,stdio:["pipe","pipe","pipe"],env:{...process.env,TYPEBULB_MIRROR:"1"}})){if(this.#w=new Promise(o=>{this.#g=o}),t?.includes('"')){this.#u="session path contains a quote \u2014 cannot drive it",this.#g();return}let s=t?`pi --mode rpc --session "${t}"`:"pi --mode rpc",i;try{i=n(s,e)}catch(o){this.#u=`could not start pi: ${U(o)}`,this.#g();return}this.#e=i,this.#b=t,Oi.add(i),i.stdout&&$x(i.stdout,o=>this.#A(o)),i.stderr&&i.stderr.on("data",o=>{this.#h=(this.#h+o.toString()).slice(-Cx)}),i.on("error",o=>this.#k(`could not start pi: ${o.message}`)),i.on("exit",o=>{this.#e===i&&this.#k(o?`pi exited (code ${o})${this.#h.trim()?`: ${this.#h.trim()}`:""}`:"pi exited"),Oi.delete(i),this.#g()}),this.#d({type:"get_state"}).then(o=>{let a=o.data?.sessionFile;typeof a=="string"&&a&&(this.#b=a);let c=o.data?.model;c&&typeof c.id=="string"&&c.id&&(this.#m=c.id)}).catch(()=>{}),this.#v()}get streaming(){return this.#o||Date.now()<this.#a}get draft(){return this.#c}get queue(){return this.#p}get stats(){return this.#y}get model(){return this.#m}get sessionFile(){return this.#b}get error(){return this.#u}get status(){if(this.#t)return this.#t;if(this.#n){if(Date.now()<this.#n.until)return{text:this.#n.text,kind:this.#n.kind};this.#n=null}return this.#l.size?{text:[...this.#l.values()].join(" \xB7 "),kind:"info"}:null}get dialog(){let e=Date.now();for(;this.#r.length;){let t=this.#r[0];if(e<t.until)return t.req;this.#r.shift(),t.ownTimeout||this.#S({type:"extension_ui_response",id:t.req.id,cancelled:!0})}return null}notice(e,t){this.#f(e,t)}respondUi(e,t){let n=this.#r.findIndex(o=>o.req.id===e);if(n<0)return{ok:!1,error:"dialog expired or already answered"};let[s]=this.#r.splice(n,1),i={type:"extension_ui_response",id:e};return t.cancelled?i.cancelled=!0:s.req.method==="confirm"?i.confirmed=!!t.confirmed:i.value=t.value??"",this.#S(i),{ok:!0}}async rpc(e){if(!Mx.has(e.type))return{ok:!1,error:`command not allowed: ${e.type}`};try{let t=await this.#d(e);if(t.success&&e.type==="set_model"){let n=t.data?.id;typeof n=="string"&&n&&(this.#m=n)}return t.success?{ok:!0,data:t.data}:{ok:!1,error:t.error??`pi rejected ${e.type}`}}catch(t){return{ok:!1,error:U(t)}}}async send(e,t){let n=this.streaming,s=n?e.trimStart().startsWith("/")?{type:"prompt",message:e,streamingBehavior:t?.followUp?"followUp":"steer"}:{type:t?.followUp?"follow_up":"steer",message:e}:{type:"prompt",message:e},i;try{i=await this.#d(s)}catch(o){return{ok:!1,error:U(o)}}return i.success&&!n&&(this.#a=Date.now()+_x),i.success?{ok:!0}:{ok:!1,error:i.error??"pi rejected the message"}}async stop(){if(this.#e)try{await this.#d({type:"abort"})}catch{}}clearCompletedDraft(){this.#i||(this.#c=null)}async dispose(){let e=this.#e;if(e){if(this.#e=void 0,this.#o){try{e.stdin?.write(JSON.stringify({type:"abort"})+`
466
497
  `)}catch{}await Promise.race([this.#w,cm(am)])}try{e.stdin?.end()}catch{}if(await Promise.race([this.#w,cm(am)]),e.exitCode===null&&!e.killed)if(process.platform==="win32"&&e.pid)try{om("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}else try{e.kill("SIGKILL")}catch{}Oi.delete(e),this.#r=[],this.#x("pi was shut down")}}#S(e){try{this.#e?.stdin?.write(JSON.stringify(e)+`
467
498
  `)}catch{}}#f(e,t){let n=e.length>200?e.slice(0,200)+"\u2026":e;n&&(this.#n={text:n,kind:t,until:Date.now()+(t==="info"?Ix:Lx)})}#v(){this.#d({type:"get_session_stats"}).then(e=>{if(!e.success||!e.data)return;let t=e.data;this.#y={cost:typeof t.cost=="number"?t.cost:0,contextTokens:typeof t.contextUsage?.tokens=="number"?t.contextUsage.tokens:null,contextPercent:typeof t.contextUsage?.percent=="number"?t.contextUsage.percent:null}}).catch(()=>{})}#d(e){let t=this.#e;if(!t?.stdin?.writable)return Promise.reject(new Error(this.#u??"pi is not running"));let n=`tb-${this.#E++}`;return new Promise((s,i)=>{let o=setTimeout(()=>{this.#s.delete(n),i(new Error("pi did not respond (30s)"))},Rx);o.unref?.(),this.#s.set(n,{resolve:s,timer:o});try{t.stdin.write(JSON.stringify({id:n,...e})+`
468
499
  `)}catch(a){clearTimeout(o),this.#s.delete(n),i(new Error(U(a)))}})}#A(e){let t;try{t=JSON.parse(e)}catch{return}switch(t.type){case"response":{let n=t,s=n.id?this.#s.get(n.id):void 0;s&&(this.#s.delete(n.id),clearTimeout(s.timer),s.resolve(n));return}case"agent_start":this.#o=!0,this.#a=0;return;case"agent_end":this.#o=!1,this.#a=0,this.#i=!1,this.#t=null,this.#p=null,this.#v();return;case"message_start":{t.message?.role==="assistant"&&(this.#i=!0,this.#c={text:"",thinking:""});return}case"message_update":{if(!this.#i)return;let n=t.message,s=Array.isArray(n?.content)?n.content:[];this.#c={text:s.filter(i=>i?.type==="text").map(i=>i.text??"").join(""),thinking:s.filter(i=>i?.type==="thinking").map(i=>i.thinking??"").join(`
469
- `)};return}case"message_end":this.#i=!1;return;case"auto_retry_start":this.#t={text:`retrying after a transient error (attempt ${Number(t.attempt)||1}/${Number(t.maxAttempts)||"?"})\u2026`,kind:"warning"};return;case"auto_retry_end":this.#t=null,t.success===!1&&this.#f(`retries exhausted: ${String(t.finalError??"unknown error")}`,"error");return;case"compaction_start":this.#t={text:"compacting context\u2026",kind:"info"};return;case"compaction_end":{this.#t=null;let n=t.result;typeof t.errorMessage=="string"&&t.errorMessage?this.#f(`compaction failed: ${t.errorMessage}`,"error"):n?.tokensBefore&&this.#f(`compacted: ~${Math.round(n.tokensBefore/1e3)}k \u2192 ~${Math.round((n.estimatedTokensAfter??0)/1e3)}k tokens`,"info"),this.#v();return}case"queue_update":{let n=Array.isArray(t.steering)?t.steering.map(String):[],s=Array.isArray(t.followUp)?t.followUp.map(String):[];this.#p=n.length||s.length?{steering:n,followUp:s}:null;return}case"extension_ui_request":{let n=String(t.method??"");if(n==="select"||n==="confirm"||n==="input"||n==="editor"){let s=typeof t.timeout=="number"&&t.timeout>0?t.timeout:void 0;this.#r.push({req:{id:String(t.id??""),method:n,title:typeof t.title=="string"?t.title:void 0,message:typeof t.message=="string"?t.message:void 0,options:Array.isArray(t.options)?t.options.map(String):void 0,placeholder:typeof t.placeholder=="string"?t.placeholder:void 0,prefill:typeof t.prefill=="string"?t.prefill:void 0},until:Date.now()+(s??Nx),ownTimeout:s!==void 0})}else if(n==="notify"){let s=t.notifyType==="warning"?"warning":t.notifyType==="error"?"error":"info";this.#f(String(t.message??""),s),console.log(`[composer] pi extension: ${String(t.message??"")}`)}else if(n==="setStatus"){let s=String(t.statusKey??"");typeof t.statusText=="string"&&t.statusText?this.#l.set(s,t.statusText):this.#l.delete(s)}return}default:return}}#k(e){this.#u=e,this.#o=!1,this.#a=0,this.#i=!1,this.#c=null,this.#t=null,this.#n=null,this.#l.clear(),this.#r=[],this.#p=null,this.#y=null,this.#m=null,this.#e=void 0,this.#x(e)}#x(e){for(let[,t]of this.#s)clearTimeout(t.timer),t.resolve({type:"response",success:!1,error:e});this.#s.clear()}},cm=r=>new Promise(e=>{setTimeout(e,r).unref?.()})});import{existsSync as um,readFileSync as Dx,realpathSync as Bx}from"fs";import{join as Tt,dirname as mm,resolve as jx}from"path";import{homedir as fm}from"os";function qx(r,e){let t=Tt(r,".pi");if(Fx.some(s=>um(Tt(t,s))))return!0;let n=Tt(e,".agents","skills");for(let s=r;;){let i=Tt(s,".agents","skills");if(i!==n&&um(i))return!0;let o=mm(s);if(o===s)return!1;s=o}}function Ux(r,e){for(let t=e;;){if(r[t]===!0||r[t]===!1)return!0;let n=mm(t);if(n===t)return!1;t=n}}function hm(r,e){try{let t=e?.agentDir??Tt(fm(),".pi","agent"),n=dm(e?.home??process.env.HOME??fm()),s=dm(jx(r));if(!qx(s,n))return null;let i=pm(Tt(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||Ux(pm(Tt(t,"trust.json")),s)?null:"pi has no trust decision for this project \u2014 running untrusted; run `pi` once in a terminal to grant it"}catch{return null}}var Fx,dm,pm,gm=R(()=>{Fx=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],dm=r=>{try{return Bx(r)}catch{return r}},pm=r=>{try{return JSON.parse(Dx(r,"utf8"))}catch{return{}}}});import{statSync as Jx,openSync as Kx,readSync as Wx,closeSync as Hx,existsSync as Vx}from"fs";import{join as Lc}from"path";import{homedir as bm}from"os";function Gx(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function ym(r){return r.type==="message"?zx(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var Yx,zx,pr,$c=R(()=>{vi();xc();Ec();im();lm();gm();Yx=Lc(bm(),".pi","agent","sessions");zx=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";pr=class extends lr{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return Vx(Lc(bm(),".pi","agent"))}ensureHarnessSupport(){sm()}createDriver(e,t){let n=new Ri(e,t),s=hm(e);return s&&n.notice(s,"warning"),n}sessionsDir(e){return Lc(Yx,Gx(e))}listSessionFiles(e){return Si(this.sessionsDir(e))}parseEntry(e){let t;try{t=JSON.parse(e)}catch{return null}return!t||t.type==="session"||!t.id?null:t}idOf(e){return e.id}parentOf(e){return e.parentId??void 0}timestampOf(e){return e.timestamp}isSidechain(e){return!1}isLeafType(e){return ym(e)}isRecoveryNoise(e){return!1}apply(e,t){let n=[];if(e.type==="custom_message"){if(e.display===!1)return{events:n};let i=this.contentText(e.content).trim();return i&&n.push({type:"user",text:i}),{events:n}}if(e.type!=="message"||!e.message)return{events:n};let s=e.message;if(s.role==="user"){let i=this.contentText(s.content).trim();return i&&n.push({type:"user",text:i}),{events:n}}if(s.role==="toolResult"){let i=this.contentText(s.content);return n.push({type:"tool_result",id:s.toolCallId??"",content:i,isError:!!s.isError,digest:Me(i)}),{events:n}}if(s.role==="bashExecution")return s.command&&!s.excludeFromContext&&n.push({type:"user",text:`$ ${s.command}`}),{events:n};if(s.role==="assistant"){let i=Array.isArray(s.content)?s.content:[],o=i.filter(d=>d.type==="text").map(d=>d.text??"").join(""),a=i.filter(d=>d.type==="thinking").map(d=>d.thinking??"").join(`
500
+ `)};return}case"message_end":this.#i=!1;return;case"auto_retry_start":this.#t={text:`retrying after a transient error (attempt ${Number(t.attempt)||1}/${Number(t.maxAttempts)||"?"})\u2026`,kind:"warning"};return;case"auto_retry_end":this.#t=null,t.success===!1&&this.#f(`retries exhausted: ${String(t.finalError??"unknown error")}`,"error");return;case"compaction_start":this.#t={text:"compacting context\u2026",kind:"info"};return;case"compaction_end":{this.#t=null;let n=t.result;typeof t.errorMessage=="string"&&t.errorMessage?this.#f(`compaction failed: ${t.errorMessage}`,"error"):n?.tokensBefore&&this.#f(`compacted: ~${Math.round(n.tokensBefore/1e3)}k \u2192 ~${Math.round((n.estimatedTokensAfter??0)/1e3)}k tokens`,"info"),this.#v();return}case"queue_update":{let n=Array.isArray(t.steering)?t.steering.map(String):[],s=Array.isArray(t.followUp)?t.followUp.map(String):[];this.#p=n.length||s.length?{steering:n,followUp:s}:null;return}case"extension_ui_request":{let n=String(t.method??"");if(n==="select"||n==="confirm"||n==="input"||n==="editor"){let s=typeof t.timeout=="number"&&t.timeout>0?t.timeout:void 0;this.#r.push({req:{id:String(t.id??""),method:n,title:typeof t.title=="string"?t.title:void 0,message:typeof t.message=="string"?t.message:void 0,options:Array.isArray(t.options)?t.options.map(String):void 0,placeholder:typeof t.placeholder=="string"?t.placeholder:void 0,prefill:typeof t.prefill=="string"?t.prefill:void 0},until:Date.now()+(s??Nx),ownTimeout:s!==void 0})}else if(n==="notify"){let s=t.notifyType==="warning"?"warning":t.notifyType==="error"?"error":"info";this.#f(String(t.message??""),s),console.log(`[composer] pi extension: ${String(t.message??"")}`)}else if(n==="setStatus"){let s=String(t.statusKey??"");typeof t.statusText=="string"&&t.statusText?this.#l.set(s,t.statusText):this.#l.delete(s)}return}default:return}}#k(e){this.#u=e,this.#o=!1,this.#a=0,this.#i=!1,this.#c=null,this.#t=null,this.#n=null,this.#l.clear(),this.#r=[],this.#p=null,this.#y=null,this.#m=null,this.#e=void 0,this.#x(e)}#x(e){for(let[,t]of this.#s)clearTimeout(t.timer),t.resolve({type:"response",success:!1,error:e});this.#s.clear()}},cm=r=>new Promise(e=>{setTimeout(e,r).unref?.()})});import{existsSync as um,readFileSync as Dx,realpathSync as Bx}from"fs";import{join as Tt,dirname as mm,resolve as jx}from"path";import{homedir as fm}from"os";function qx(r,e){let t=Tt(r,".pi");if(Fx.some(s=>um(Tt(t,s))))return!0;let n=Tt(e,".agents","skills");for(let s=r;;){let i=Tt(s,".agents","skills");if(i!==n&&um(i))return!0;let o=mm(s);if(o===s)return!1;s=o}}function Ux(r,e){for(let t=e;;){if(r[t]===!0||r[t]===!1)return!0;let n=mm(t);if(n===t)return!1;t=n}}function hm(r,e){try{let t=e?.agentDir??Tt(fm(),".pi","agent"),n=dm(e?.home??process.env.HOME??fm()),s=dm(jx(r));if(!qx(s,n))return null;let i=pm(Tt(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||Ux(pm(Tt(t,"trust.json")),s)?null:"pi has no trust decision for this project \u2014 running untrusted; run `pi` once in a terminal to grant it"}catch{return null}}var Fx,dm,pm,gm=R(()=>{Fx=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],dm=r=>{try{return Bx(r)}catch{return r}},pm=r=>{try{return JSON.parse(Dx(r,"utf8"))}catch{return{}}}});import{statSync as Jx,openSync as Kx,readSync as Wx,closeSync as Hx,existsSync as Vx}from"fs";import{join as Lc}from"path";import{homedir as bm}from"os";function Gx(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function ym(r){return r.type==="message"?zx(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var Yx,zx,pr,Mc=R(()=>{vi();xc();Ec();im();lm();gm();Yx=Lc(bm(),".pi","agent","sessions");zx=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";pr=class extends lr{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return Vx(Lc(bm(),".pi","agent"))}ensureHarnessSupport(){sm()}createDriver(e,t){let n=new Ri(e,t),s=hm(e);return s&&n.notice(s,"warning"),n}sessionsDir(e){return Lc(Yx,Gx(e))}listSessionFiles(e){return Si(this.sessionsDir(e))}parseEntry(e){let t;try{t=JSON.parse(e)}catch{return null}return!t||t.type==="session"||!t.id?null:t}idOf(e){return e.id}parentOf(e){return e.parentId??void 0}timestampOf(e){return e.timestamp}isSidechain(e){return!1}isLeafType(e){return ym(e)}isRecoveryNoise(e){return!1}apply(e,t){let n=[];if(e.type==="custom_message"){if(e.display===!1)return{events:n};let i=this.contentText(e.content).trim();return i&&n.push({type:"user",text:i}),{events:n}}if(e.type!=="message"||!e.message)return{events:n};let s=e.message;if(s.role==="user"){let i=this.contentText(s.content).trim();return i&&n.push({type:"user",text:i}),{events:n}}if(s.role==="toolResult"){let i=this.contentText(s.content);return n.push({type:"tool_result",id:s.toolCallId??"",content:i,isError:!!s.isError,digest:$e(i)}),{events:n}}if(s.role==="bashExecution")return s.command&&!s.excludeFromContext&&n.push({type:"user",text:`$ ${s.command}`}),{events:n};if(s.role==="assistant"){let i=Array.isArray(s.content)?s.content:[],o=i.filter(d=>d.type==="text").map(d=>d.text??"").join(""),a=i.filter(d=>d.type==="thinking").map(d=>d.thinking??"").join(`
470
501
  `),c=i.filter(d=>d.type==="toolCall").map(d=>({id:d.id??"",name:d.name??"",input:d.arguments??{}}));if(o||a||c.length){let d=Date.parse(e.timestamp??""),p=!isNaN(d)&&d>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:p})}let l=s.usage,f=l?(l.input??0)+(l.output??0)+(l.cacheRead??0)+(l.cacheWrite??0):0,u=l&&f>0&&s.stopReason!=="aborted"&&s.stopReason!=="error"?{in:l.input??0,out:l.output??0,cached:l.cacheRead??0,cacheCreate:l.cacheWrite??0}:void 0;return{events:n,usage:u,model:s.model,cost:l?.cost?.total}}return{events:n}}chainWorking(e){let t;for(let a of e)ym(a)&&(t=a);if(!t||t.type==="custom_message")return!1;let n=t.message.role;if(n==="user"||n==="toolResult"||n==="bashExecution")return!0;if(n!=="assistant")return!1;let i=(Array.isArray(t.message.content)?t.message.content:[]).filter(a=>a.type==="toolCall").map(a=>a.id);if(!i.length)return!1;let o=new Set;for(let a of e)a.type==="message"&&a.message?.role==="toolResult"&&a.message.toolCallId&&o.add(a.message.toolCallId);return i.some(a=>a&&!o.has(a))}sessionAlive(){}readPreview(e){let t;try{t=Kx(e,"r")}catch{return""}try{let s=65536;try{s=Jx(e).size}catch{}let i=Buffer.alloc(Math.min(65536,s)),o=Wx(t,i,0,i.length,0),a=i.subarray(0,o).toString("utf8"),c="",l="";for(let u of a.split(`
471
502
  `)){if(!u.includes('"type"'))continue;let d;try{d=JSON.parse(u)}catch{continue}d?.type==="session_info"&&typeof d.name=="string"&&d.name?c=d.name:!l&&d?.type==="message"&&d.message?.role==="user"&&(l=this.contentText(d.message.content).replace(/\s+/g," ").trim())}let f=c||l;return f?f.slice(0,200):""}finally{Hx(t)}}searchText(e){if(e?.type!=="message")return"";let t=e.message?.role;if(t!=="user"&&t!=="assistant")return"";let n=e.message?.content,s="";return typeof n=="string"?s=n:Array.isArray(n)&&(s=n.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(" ")),s.replace(/\s+/g," ").trim()}contentText(e){return typeof e=="string"?Se(e):Array.isArray(e)?e.map(t=>typeof t?.text=="string"?Se(t.text):t?.type==="image"&&t.data?wi(t.data,t.mimeType):"").filter(Boolean).join(`
472
- `):""}}});var Li,Um=R(()=>{Li=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});function $i(r,e){let t=0,n="";for(let s of r){let i=s.lower.indexOf(e);if(!(i<0)&&(t++,!n)){let o=Math.max(0,i-110),a=Math.min(s.text.length,i+e.length+110);n=(o>0?"\u2026":"")+s.text.slice(o,a)+(a<s.text.length?"\u2026":"")}}return{hitCount:t,snippet:n}}var Vc=R(()=>{});var Mi,Di,Jm=R(()=>{Mi=".typebulb/paste",Di={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp"}});import{existsSync as x0,mkdirSync as E0,writeFileSync as A0,readFileSync as T0}from"fs";import{join as Bi}from"path";function Km(){let r=new Date,e=t=>String(t).padStart(2,"0");return`${r.getFullYear()}${e(r.getMonth()+1)}${e(r.getDate())}-${e(r.getHours())}${e(r.getMinutes())}${e(r.getSeconds())}`}function _0(r){return r.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function C0(r){let e=AbortSignal.timeout(P0);for(let[t,n]of R0){let s=wt(t,n);if(typeof s!="string"){try{let i=await vt(s,{messages:[{role:"user",content:`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
503
+ `):""}}});var Li,Um=R(()=>{Li=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});function Mi(r,e){let t=0,n="";for(let s of r){let i=s.lower.indexOf(e);if(!(i<0)&&(t++,!n)){let o=Math.max(0,i-110),a=Math.min(s.text.length,i+e.length+110);n=(o>0?"\u2026":"")+s.text.slice(o,a)+(a<s.text.length?"\u2026":"")}}return{hitCount:t,snippet:n}}var Vc=R(()=>{});var $i,Di,Jm=R(()=>{$i=".typebulb/paste",Di={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp"}});import{existsSync as x0,mkdirSync as E0,writeFileSync as A0,readFileSync as T0}from"fs";import{join as Bi}from"path";function Km(){let r=new Date,e=t=>String(t).padStart(2,"0");return`${r.getFullYear()}${e(r.getMonth()+1)}${e(r.getDate())}-${e(r.getHours())}${e(r.getMinutes())}${e(r.getSeconds())}`}function _0(r){return r.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function C0(r){let e=AbortSignal.timeout(P0);for(let[t,n]of R0){let s=wt(t,n);if(typeof s!="string"){try{let i=await vt(s,{messages:[{role:"user",content:`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
473
504
 
474
- ${r.slice(0,O0)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=_0(await bt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function Wm(r,e){if(!e||e.kind!=="image"&&e.kind!=="text")return{ok:!1,error:"bad paste kind"};if(typeof e.data!="string"||!e.data)return{ok:!1,error:"empty paste"};let t=Bi(r,Mi);try{E0(t,{recursive:!0})}catch(a){return{ok:!1,error:U(a)}}let n,s,i;if(e.kind==="image"){if(n=`img-${Km()}`,s=Object.keys(Di).find(a=>Di[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else n=await C0(e.data)??`paste-${Km()}`,s="md",i=e.data;let o=`${n}.${s}`;for(let a=2;x0(Bi(t,o));a++)o=`${n}-${a}.${s}`;try{A0(Bi(t,o),i)}catch(a){return{ok:!1,error:U(a)}}return{ok:!0,path:`${Mi}/${o}`}}function Hm(r,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),n=Di[t];if(!n)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:n,base64:T0(Bi(r,Mi,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var P0,O0,R0,Vm=R(()=>{er();gn();dr();Jm();P0=4e3,O0=4e3,R0=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});import{existsSync as Ym,openSync as N0,readSync as I0,closeSync as L0,statSync as hr,readdirSync as Gm,watchFile as $0,unwatchFile as zm,mkdirSync as M0,writeFileSync as D0,readFileSync as Yc,unlinkSync as B0,rmSync as j0}from"fs";import{stat as F0}from"fs/promises";import{join as Rt}from"path";import{execFile as q0}from"child_process";function ji(r){let e={cwd:G,sessionId:"",sessionStartMs:Date.now(),buffer:[],partial:"",offset:0,latest:{in:0,out:0,cached:0,cacheCreate:0},latestModel:null,everAttached:!1,entries:new Map},t=new Set,n;function s(){if(e.file){for(let h of t)if(h.file===e.file)return h;return}return n}function i(h){let k={d:r.createDriver(e.cwd,h),file:h};return t.add(k),e.file||(n=k),k}async function o(h){t.delete(h),n===h&&(n=void 0);try{await h.d.dispose()}catch(k){console.error("[composer] dispose:",U(k))}}function a(){let h=s();for(let k of[...t])k!==h&&(k.d.streaming||k.d.queue||k.d.error||o(k))}function c(){for(let h of t)!h.file&&h.d.sessionFile&&(h.file=h.d.sessionFile);if(n&&!e.file&&n.file){let h=r.listSessionFiles(e.cwd).find(k=>k.file===n.file);h&&S(h)}}let l=h=>Rt(h,J0),f=(h,k)=>Rt(l(h),`${k}.lock`);function u(h,k){try{let v=f(h,k);if(Date.now()-hr(v).mtimeMs>=Qm)return!1;try{if(parseInt(Yc(v,"utf8").trim(),10)===process.pid)return!1}catch{}return!0}catch{return!1}}function d(h,k){if(k)try{M0(l(h),{recursive:!0}),D0(f(h,k),String(process.pid))}catch(v){console.error("[lock] claim failed:",U(v))}}function p(h){try{j0(Rt(h,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function b(h){let k=l(h);if(!Ym(k))return;let v;try{v=Gm(k)}catch{return}let _=Date.now();for(let $ of v){if(!$.endsWith(".lock"))continue;let M=Rt(k,$);try{let C=hr(M);_-C.mtimeMs>K0&&B0(M)}catch{}}}function m(h){try{return hr(h),!1}catch(k){return k.code==="ENOENT"}}function y(){let h=e;if(h.file&&!m(h.file)){d(h.cwd,h.sessionId);return}let k=E(h);k&&S(k)}function E(h){if(!h.everAttached)return T(h.cwd)??g(h.cwd,()=>!0)}function T(h){let k=l(h);if(!Ym(k))return;let v;try{v=Gm(k)}catch{return}let _;for(let M of v)if(M.endsWith(".lock"))try{let C=hr(Rt(k,M));if(Date.now()-C.mtimeMs>=Qm||parseInt(Yc(Rt(k,M),"utf8").trim(),10)!==process.pid)continue;(!_||C.mtimeMs>_.mtime)&&(_={sessionId:M.slice(0,-5),mtime:C.mtimeMs})}catch{}if(!_)return;let $=r.listSessionFiles(h).find(M=>M.sessionId===_.sessionId);if(!(!$||m($.file)))return $}function g(h,k){return r.listSessionFiles(h).sort((v,_)=>_.mtime-v.mtime).find(v=>!u(h,v.sessionId)&&k(v))}function w(h,k){let v=e;if(v.file)try{zm(v.file)}catch{}v.file=h,v.sessionId=k,v.partial="",v.offset=0,v.latest={in:0,out:0,cached:0,cacheCreate:0},v.latestModel=null,v.entries=new Map,v.chainLastId=void 0,v.buffer.push({type:"cleared"}),v.buffer.push({type:"session",sessionId:k})}function S(h){let k=e;n=void 0,w(h.file,h.sessionId),k.everAttached=!0,d(k.cwd,h.sessionId),O();try{zm(h.file)}catch{}$0(h.file,{interval:200},()=>O())}function x(){w(void 0,"")}function O(){let h=e;if(!h.file)return;let k;try{k=hr(h.file).size}catch{return}if(k<=h.offset)return;let v;try{v=N0(h.file,"r")}catch{return}try{let j=k-h.offset,se=Buffer.alloc(j),Y=0;for(;Y<j;){let al=I0(v,se,Y,j-Y,h.offset+Y);if(!al)break;Y+=al}h.offset+=Y,h.partial+=se.subarray(0,Y).toString("utf8")}finally{L0(v)}let _,$;for(;($=h.partial.indexOf(`
475
- `))>=0;){let j=h.partial.slice(0,$);if(h.partial=h.partial.slice($+1),!j.trim())continue;let se=r.parseEntry(j);if(!se)continue;let Y=r.idOf(se);Y&&(h.entries.set(Y,se),!r.isSidechain(se)&&r.isLeafType(se)&&(_=Y))}if(!_)return;let M=[],C=h.entries.get(_),F=!1;for(;C;){if(M.push(C),r.idOf(C)===h.chainLastId){F=!0;break}let j=r.parentOf(C);C=j?h.entries.get(j):void 0}if(F)for(let j=M.length-2;j>=0;j--)V(M[j]);else{h.chainLastId!==void 0&&(h.buffer.push({type:"cleared"}),h.buffer.push({type:"session",sessionId:h.sessionId}),h.latest={in:0,out:0,cached:0,cacheCreate:0});let j=new Set(M.map(Y=>r.idOf(Y))),se=A(h.entries);for(let Y=M.length-1;Y>=0;Y--)V(M[Y]),L(r.idOf(M[Y]),se,j)}h.chainLastId=_}function A(h){let k=new Map;for(let v of h.values()){let _=r.parentOf(v);if(!_)continue;let $=k.get(_);$?$.push(v):k.set(_,[v])}return k}function L(h,k,v){if(!h)return;let _=k.get(h);if(!_)return;let $=_.filter(j=>!r.isSidechain(j));if($.length<2)return;let M=$.filter(j=>!v.has(r.idOf(j)));if(!M.length)return;let C=[],F=0;for(let j of M){let se=te(j,k);C.push(...se.events),F+=se.count}F>0&&e.buffer.push({type:"fork",atId:h,count:F,events:C})}function te(h,k){let v=[],_=[h];for(;_.length;){let C=_.pop();if(r.isSidechain(C))continue;v.push(C);let F=k.get(r.idOf(C)??"");if(F)for(let j of F)_.push(j)}v.sort((C,F)=>(Date.parse(r.timestampOf(C)??"")||0)-(Date.parse(r.timestampOf(F)??"")||0));let $=[];for(let C of v)r.isRecoveryNoise(C)||$.push(...r.apply(C,e.sessionStartMs).events);return{count:$.reduce((C,F)=>C+(F.type==="user"||F.type==="assistant"?1:0),0),events:$}}function V(h){try{let{events:k,usage:v,model:_,cost:$}=r.apply(h,e.sessionStartMs);for(let M of k)e.buffer.push(M);k.some(M=>M.type==="assistant")&&s()?.d.clearCompletedDraft(),_&&(e.latestModel=_),v&&(e.latest=v),(v||$)&&e.buffer.push({type:"usage",...e.latest,cost:$})}catch(k){console.error("[mirror] skipped malformed entry:",U(k))}}async function B(){return{cwd:e.cwd,pid:process.pid,composer:!!r.createDriver}}let it=new Li;async function Wi(h,k){it.accept(h,k)&&console.log(k)}function Bh(){let h=r.sessionAlive(e.sessionId,e.cwd);if(h!==void 0)return h;if(!e.file)return!1;try{return Date.now()-hr(e.file).mtimeMs<1e4}catch{return!1}}function Hi(){return r.chainWorking([...e.entries.values()])&&Bh()}function jh(){!r.createDriver||s()||e.latestModel||Hi()||i(e.file)}async function Fh(h){let k=e;y(),c(),jh(),a();let v=s();for(let C of t)C!==v&&C.d.dialog;let _=new Set([...t].filter(C=>C.d.streaming&&C.file).map(C=>C.file)),$=_.size?r.listSessionFiles(k.cwd).filter(C=>_.has(C.file)).map(C=>C.sessionId):[],M=r.createDriver?{streaming:!!v?.d.streaming,draft:v?.d.draft??null,status:v?.d.status??null,dialog:v?.d.dialog??null,queue:v?.d.queue??null,stats:v?.d.stats??null,model:v?.d.model??null,error:v?.d.error}:void 0;return{events:k.buffer.slice(h),cursor:k.buffer.length,working:!!v?.d.streaming||Hi(),latestModel:k.latestModel,composer:M,busy:$}}async function il(){y(),c();let h=s();if(h?.d.error&&!h.d.streaming&&(await o(h),h=void 0),!h){if(Hi())return{ok:!1,error:"the agent is mid-turn in a terminal \u2014 watch only"};h=i(e.file)}return{ok:!0,d:h.d}}async function qh(h,k){if(!r.createDriver)return{ok:!1,error:"not supported"};let v=String(h??"").trim();if(!v)return{ok:!1,error:"empty message"};let _=await il();return _.ok?_.d.send(v,k):_}async function Uh(h,k){let v=s();return v?v.d.respondUi(String(h??""),k??{}):{ok:!1,error:"no dialog pending"}}async function Jh(h,k){if(!r.createDriver)return{ok:!1,error:"not supported"};if(!h||typeof h.type!="string")return{ok:!1,error:"bad command"};if(k?.spawn){let _=await il();return _.ok?_.d.rpc(h):_}let v=s();return!v||v.d.error?{ok:!1,error:"not running"}:v.d.rpc(h)}async function Kh(){let h=s();if(h)try{await h.d.stop()}catch(k){console.error("[composer] stop:",U(k))}return{ok:!0}}async function Wh(){return r.createDriver?(c(),!e.file&&n&&!n.d.streaming&&!n.d.error?{ok:!0}:(n?.d.error&&await o(n),n=void 0,e.file&&x(),i(void 0),a(),{ok:!0})):{ok:!1,error:"not supported"}}async function Hh(){if(!r.createDriver)return[];let h=await new Promise(v=>{q0("git",["ls-files"],{cwd:e.cwd,maxBuffer:64*1024*1024},(_,$)=>v(_?"":$))});return(await Promise.all(h.split(`
476
- `).filter(Boolean).map(async v=>{try{return{f:v,m:(await F0(Rt(e.cwd,v))).mtimeMs}}catch{return{f:v,m:0}}}))).sort((v,_)=>_.m-v.m).map(v=>v.f)}function Vh(){for(let h of[...t])o(h)}async function Yh(h){return r.createDriver?Wm(e.cwd,h):{ok:!1,error:"not supported"}}async function Gh(h){return Hm(e.cwd,String(h??""))}async function zh(){return r.listSessionFiles(e.cwd).sort((h,k)=>k.mtime-h.mtime).map(({sessionId:h,file:k,mtime:v})=>({sessionId:h,mtime:v,preview:r.readPreview(k)}))}let ol=new Map;function Qh(h,k){let v=ol.get(h);if(v&&v.mtime===k)return v.turns;let _=[],$="";try{$=Yc(h,"utf8")}catch{return[]}for(let M of $.split(`
477
- `)){if(!M.trim())continue;let C=r.parseEntry(M);if(!C)continue;let F=r.searchText(C);F&&_.push({text:F,lower:F.toLowerCase()})}return ol.set(h,{mtime:k,turns:_}),_}async function Xh(h){let k=h.toLowerCase(),v=[];for(let{sessionId:_,file:$,mtime:M}of r.listSessionFiles(e.cwd).sort((C,F)=>F.mtime-C.mtime)){let{hitCount:C,snippet:F}=$i(Qh($,M),k);if(C&&(v.push({sessionId:_,mtime:M,preview:r.readPreview($),hitCount:C,snippet:F}),v.length>=W0))break}return v}async function Zh(h){let k=e,v=r.listSessionFiles(k.cwd).find(_=>_.sessionId===h);return v?v.file===k.file?{ok:!0}:(S(v),a(),{ok:!0}):{ok:!1,error:"session not found"}}return p(e.cwd),b(e.cwd),y(),{info:B,poll:Fh,logEmbedStatus:Wi,listSessions:zh,searchSessions:Xh,attach:Zh,composerSend:qh,composerStop:Kh,composerNew:Wh,composerFiles:Hh,composerUiRespond:Uh,composerRpc:Jh,composerPaste:Yh,composerPasteRead:Gh,shutdownComposer:Vh}}var U0,J0,Qm,K0,W0,Gc=R(()=>{dr();Um();Vc();Vm();U0=".typebulb",J0=`${U0}/locks`,Qm=5e3,K0=6e4,W0=50});import{existsSync as zc,mkdirSync as H0,readFileSync as Xm,writeFileSync as V0}from"fs";import{join as gr,isAbsolute as Y0}from"path";async function Zm(r,e){let t=Y0(r)?r:gr(G,r);return zc(t)?(Ic(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function eh(r){let e=G,t=Nc(r),n=gr(e,"typebulbs");H0(n,{recursive:!0});let s=Rc(t),i=`${s}.bulb.md`;for(let l=2;zc(gr(n,i))&&Xm(gr(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=gr(n,i);zc(o)||V0(o,t);let a=gr("typebulbs",i),c=await bi(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function th(){return K(G)}async function rh(r){return await xt(r),{ok:!0}}async function nh(){return Ai(G).filter(r=>!r.serverOnly).map(r=>({...r,trusted:St(r.path)}))}async function sh(r){let e=r.toLowerCase(),t=[];for(let n of Ai(G).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=Xm(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
478
- `)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=$i(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function ih(r,e){let t=G;e!=null&&sr(r,e);let n=await bi(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function oh(r){return{cap:await Cc(r)}}async function ah(r,e){return sr(r,e),{ok:!0}}async function ch(r,e){return ve(r,e)}var Qc=R(()=>{gn();dr();Vc()});import{readFileSync as el,writeFileSync as uh,mkdirSync as G0,appendFileSync as fh,rmSync as lh}from"fs";import{join as Ui,dirname as z0}from"path";import{createServer as Q0}from"http";function st(r){try{return JSON.parse(el(r,"utf8"))}catch{return null}}function qi(r,e){G0(z0(r),{recursive:!0}),uh(r,JSON.stringify(e,null,2)+`
505
+ ${r.slice(0,O0)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=_0(await bt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function Wm(r,e){if(!e||e.kind!=="image"&&e.kind!=="text")return{ok:!1,error:"bad paste kind"};if(typeof e.data!="string"||!e.data)return{ok:!1,error:"empty paste"};let t=Bi(r,$i);try{E0(t,{recursive:!0})}catch(a){return{ok:!1,error:U(a)}}let n,s,i;if(e.kind==="image"){if(n=`img-${Km()}`,s=Object.keys(Di).find(a=>Di[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else n=await C0(e.data)??`paste-${Km()}`,s="md",i=e.data;let o=`${n}.${s}`;for(let a=2;x0(Bi(t,o));a++)o=`${n}-${a}.${s}`;try{A0(Bi(t,o),i)}catch(a){return{ok:!1,error:U(a)}}return{ok:!0,path:`${$i}/${o}`}}function Hm(r,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),n=Di[t];if(!n)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:n,base64:T0(Bi(r,$i,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var P0,O0,R0,Vm=R(()=>{er();gn();dr();Jm();P0=4e3,O0=4e3,R0=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});import{existsSync as Ym,openSync as N0,readSync as I0,closeSync as L0,statSync as hr,readdirSync as Gm,watchFile as M0,unwatchFile as zm,mkdirSync as $0,writeFileSync as D0,readFileSync as Yc,unlinkSync as B0,rmSync as j0}from"fs";import{stat as F0}from"fs/promises";import{join as Rt}from"path";import{execFile as q0}from"child_process";function ji(r){let e={cwd:G,sessionId:"",sessionStartMs:Date.now(),buffer:[],partial:"",offset:0,latest:{in:0,out:0,cached:0,cacheCreate:0},latestModel:null,everAttached:!1,entries:new Map},t=new Set,n;function s(){if(e.file){for(let h of t)if(h.file===e.file)return h;return}return n}function i(h){let k={d:r.createDriver(e.cwd,h),file:h};return t.add(k),e.file||(n=k),k}async function o(h){t.delete(h),n===h&&(n=void 0);try{await h.d.dispose()}catch(k){console.error("[composer] dispose:",U(k))}}function a(){let h=s();for(let k of[...t])k!==h&&(k.d.streaming||k.d.queue||k.d.error||o(k))}function c(){for(let h of t)!h.file&&h.d.sessionFile&&(h.file=h.d.sessionFile);if(n&&!e.file&&n.file){let h=r.listSessionFiles(e.cwd).find(k=>k.file===n.file);h&&S(h)}}let l=h=>Rt(h,J0),f=(h,k)=>Rt(l(h),`${k}.lock`);function u(h,k){try{let v=f(h,k);if(Date.now()-hr(v).mtimeMs>=Qm)return!1;try{if(parseInt(Yc(v,"utf8").trim(),10)===process.pid)return!1}catch{}return!0}catch{return!1}}function d(h,k){if(k)try{$0(l(h),{recursive:!0}),D0(f(h,k),String(process.pid))}catch(v){console.error("[lock] claim failed:",U(v))}}function p(h){try{j0(Rt(h,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function b(h){let k=l(h);if(!Ym(k))return;let v;try{v=Gm(k)}catch{return}let _=Date.now();for(let M of v){if(!M.endsWith(".lock"))continue;let $=Rt(k,M);try{let C=hr($);_-C.mtimeMs>K0&&B0($)}catch{}}}function m(h){try{return hr(h),!1}catch(k){return k.code==="ENOENT"}}function y(){let h=e;if(h.file&&!m(h.file)){d(h.cwd,h.sessionId);return}let k=E(h);k&&S(k)}function E(h){if(!h.everAttached)return T(h.cwd)??g(h.cwd,()=>!0)}function T(h){let k=l(h);if(!Ym(k))return;let v;try{v=Gm(k)}catch{return}let _;for(let $ of v)if($.endsWith(".lock"))try{let C=hr(Rt(k,$));if(Date.now()-C.mtimeMs>=Qm||parseInt(Yc(Rt(k,$),"utf8").trim(),10)!==process.pid)continue;(!_||C.mtimeMs>_.mtime)&&(_={sessionId:$.slice(0,-5),mtime:C.mtimeMs})}catch{}if(!_)return;let M=r.listSessionFiles(h).find($=>$.sessionId===_.sessionId);if(!(!M||m(M.file)))return M}function g(h,k){return r.listSessionFiles(h).sort((v,_)=>_.mtime-v.mtime).find(v=>!u(h,v.sessionId)&&k(v))}function w(h,k){let v=e;if(v.file)try{zm(v.file)}catch{}v.file=h,v.sessionId=k,v.partial="",v.offset=0,v.latest={in:0,out:0,cached:0,cacheCreate:0},v.latestModel=null,v.entries=new Map,v.chainLastId=void 0,v.buffer.push({type:"cleared"}),v.buffer.push({type:"session",sessionId:k})}function S(h){let k=e;n=void 0,w(h.file,h.sessionId),k.everAttached=!0,d(k.cwd,h.sessionId),O();try{zm(h.file)}catch{}M0(h.file,{interval:200},()=>O())}function x(){w(void 0,"")}function O(){let h=e;if(!h.file)return;let k;try{k=hr(h.file).size}catch{return}if(k<=h.offset)return;let v;try{v=N0(h.file,"r")}catch{return}try{let j=k-h.offset,se=Buffer.alloc(j),Y=0;for(;Y<j;){let al=I0(v,se,Y,j-Y,h.offset+Y);if(!al)break;Y+=al}h.offset+=Y,h.partial+=se.subarray(0,Y).toString("utf8")}finally{L0(v)}let _,M;for(;(M=h.partial.indexOf(`
506
+ `))>=0;){let j=h.partial.slice(0,M);if(h.partial=h.partial.slice(M+1),!j.trim())continue;let se=r.parseEntry(j);if(!se)continue;let Y=r.idOf(se);Y&&(h.entries.set(Y,se),!r.isSidechain(se)&&r.isLeafType(se)&&(_=Y))}if(!_)return;let $=[],C=h.entries.get(_),F=!1;for(;C;){if($.push(C),r.idOf(C)===h.chainLastId){F=!0;break}let j=r.parentOf(C);C=j?h.entries.get(j):void 0}if(F)for(let j=$.length-2;j>=0;j--)V($[j]);else{h.chainLastId!==void 0&&(h.buffer.push({type:"cleared"}),h.buffer.push({type:"session",sessionId:h.sessionId}),h.latest={in:0,out:0,cached:0,cacheCreate:0});let j=new Set($.map(Y=>r.idOf(Y))),se=A(h.entries);for(let Y=$.length-1;Y>=0;Y--)V($[Y]),L(r.idOf($[Y]),se,j)}h.chainLastId=_}function A(h){let k=new Map;for(let v of h.values()){let _=r.parentOf(v);if(!_)continue;let M=k.get(_);M?M.push(v):k.set(_,[v])}return k}function L(h,k,v){if(!h)return;let _=k.get(h);if(!_)return;let M=_.filter(j=>!r.isSidechain(j));if(M.length<2)return;let $=M.filter(j=>!v.has(r.idOf(j)));if(!$.length)return;let C=[],F=0;for(let j of $){let se=te(j,k);C.push(...se.events),F+=se.count}F>0&&e.buffer.push({type:"fork",atId:h,count:F,events:C})}function te(h,k){let v=[],_=[h];for(;_.length;){let C=_.pop();if(r.isSidechain(C))continue;v.push(C);let F=k.get(r.idOf(C)??"");if(F)for(let j of F)_.push(j)}v.sort((C,F)=>(Date.parse(r.timestampOf(C)??"")||0)-(Date.parse(r.timestampOf(F)??"")||0));let M=[];for(let C of v)r.isRecoveryNoise(C)||M.push(...r.apply(C,e.sessionStartMs).events);return{count:M.reduce((C,F)=>C+(F.type==="user"||F.type==="assistant"?1:0),0),events:M}}function V(h){try{let{events:k,usage:v,model:_,cost:M}=r.apply(h,e.sessionStartMs);for(let $ of k)e.buffer.push($);k.some($=>$.type==="assistant")&&s()?.d.clearCompletedDraft(),_&&(e.latestModel=_),v&&(e.latest=v),(v||M)&&e.buffer.push({type:"usage",...e.latest,cost:M})}catch(k){console.error("[mirror] skipped malformed entry:",U(k))}}async function B(){return{cwd:e.cwd,pid:process.pid,composer:!!r.createDriver}}let it=new Li;async function Wi(h,k){it.accept(h,k)&&console.log(k)}function Bh(){let h=r.sessionAlive(e.sessionId,e.cwd);if(h!==void 0)return h;if(!e.file)return!1;try{return Date.now()-hr(e.file).mtimeMs<1e4}catch{return!1}}function Hi(){return r.chainWorking([...e.entries.values()])&&Bh()}function jh(){!r.createDriver||s()||e.latestModel||Hi()||i(e.file)}async function Fh(h){let k=e;y(),c(),jh(),a();let v=s();for(let C of t)C!==v&&C.d.dialog;let _=new Set([...t].filter(C=>C.d.streaming&&C.file).map(C=>C.file)),M=_.size?r.listSessionFiles(k.cwd).filter(C=>_.has(C.file)).map(C=>C.sessionId):[],$=r.createDriver?{streaming:!!v?.d.streaming,draft:v?.d.draft??null,status:v?.d.status??null,dialog:v?.d.dialog??null,queue:v?.d.queue??null,stats:v?.d.stats??null,model:v?.d.model??null,error:v?.d.error}:void 0;return{events:k.buffer.slice(h),cursor:k.buffer.length,working:!!v?.d.streaming||Hi(),latestModel:k.latestModel,composer:$,busy:M}}async function il(){y(),c();let h=s();if(h?.d.error&&!h.d.streaming&&(await o(h),h=void 0),!h){if(Hi())return{ok:!1,error:"the agent is mid-turn in a terminal \u2014 watch only"};h=i(e.file)}return{ok:!0,d:h.d}}async function qh(h,k){if(!r.createDriver)return{ok:!1,error:"not supported"};let v=String(h??"").trim();if(!v)return{ok:!1,error:"empty message"};let _=await il();return _.ok?_.d.send(v,k):_}async function Uh(h,k){let v=s();return v?v.d.respondUi(String(h??""),k??{}):{ok:!1,error:"no dialog pending"}}async function Jh(h,k){if(!r.createDriver)return{ok:!1,error:"not supported"};if(!h||typeof h.type!="string")return{ok:!1,error:"bad command"};if(k?.spawn){let _=await il();return _.ok?_.d.rpc(h):_}let v=s();return!v||v.d.error?{ok:!1,error:"not running"}:v.d.rpc(h)}async function Kh(){let h=s();if(h)try{await h.d.stop()}catch(k){console.error("[composer] stop:",U(k))}return{ok:!0}}async function Wh(){return r.createDriver?(c(),!e.file&&n&&!n.d.streaming&&!n.d.error?{ok:!0}:(n?.d.error&&await o(n),n=void 0,e.file&&x(),i(void 0),a(),{ok:!0})):{ok:!1,error:"not supported"}}async function Hh(){if(!r.createDriver)return[];let h=await new Promise(v=>{q0("git",["ls-files"],{cwd:e.cwd,maxBuffer:64*1024*1024},(_,M)=>v(_?"":M))});return(await Promise.all(h.split(`
507
+ `).filter(Boolean).map(async v=>{try{return{f:v,m:(await F0(Rt(e.cwd,v))).mtimeMs}}catch{return{f:v,m:0}}}))).sort((v,_)=>_.m-v.m).map(v=>v.f)}function Vh(){for(let h of[...t])o(h)}async function Yh(h){return r.createDriver?Wm(e.cwd,h):{ok:!1,error:"not supported"}}async function Gh(h){return Hm(e.cwd,String(h??""))}async function zh(){return r.listSessionFiles(e.cwd).sort((h,k)=>k.mtime-h.mtime).map(({sessionId:h,file:k,mtime:v})=>({sessionId:h,mtime:v,preview:r.readPreview(k)}))}let ol=new Map;function Qh(h,k){let v=ol.get(h);if(v&&v.mtime===k)return v.turns;let _=[],M="";try{M=Yc(h,"utf8")}catch{return[]}for(let $ of M.split(`
508
+ `)){if(!$.trim())continue;let C=r.parseEntry($);if(!C)continue;let F=r.searchText(C);F&&_.push({text:F,lower:F.toLowerCase()})}return ol.set(h,{mtime:k,turns:_}),_}async function Xh(h){let k=h.toLowerCase(),v=[];for(let{sessionId:_,file:M,mtime:$}of r.listSessionFiles(e.cwd).sort((C,F)=>F.mtime-C.mtime)){let{hitCount:C,snippet:F}=Mi(Qh(M,$),k);if(C&&(v.push({sessionId:_,mtime:$,preview:r.readPreview(M),hitCount:C,snippet:F}),v.length>=W0))break}return v}async function Zh(h){let k=e,v=r.listSessionFiles(k.cwd).find(_=>_.sessionId===h);return v?v.file===k.file?{ok:!0}:(S(v),a(),{ok:!0}):{ok:!1,error:"session not found"}}return p(e.cwd),b(e.cwd),y(),{info:B,poll:Fh,logEmbedStatus:Wi,listSessions:zh,searchSessions:Xh,attach:Zh,composerSend:qh,composerStop:Kh,composerNew:Wh,composerFiles:Hh,composerUiRespond:Uh,composerRpc:Jh,composerPaste:Yh,composerPasteRead:Gh,shutdownComposer:Vh}}var U0,J0,Qm,K0,W0,Gc=R(()=>{dr();Um();Vc();Vm();U0=".typebulb",J0=`${U0}/locks`,Qm=5e3,K0=6e4,W0=50});import{existsSync as zc,mkdirSync as H0,readFileSync as Xm,writeFileSync as V0}from"fs";import{join as gr,isAbsolute as Y0}from"path";async function Zm(r,e){let t=Y0(r)?r:gr(G,r);return zc(t)?(Ic(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function eh(r){let e=G,t=Nc(r),n=gr(e,"typebulbs");H0(n,{recursive:!0});let s=Rc(t),i=`${s}.bulb.md`;for(let l=2;zc(gr(n,i))&&Xm(gr(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=gr(n,i);zc(o)||V0(o,t);let a=gr("typebulbs",i),c=await bi(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function th(){return K(G)}async function rh(r){return await xt(r),{ok:!0}}async function nh(){return Ai(G).filter(r=>!r.serverOnly).map(r=>({...r,trusted:St(r.path)}))}async function sh(r){let e=r.toLowerCase(),t=[];for(let n of Ai(G).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=Xm(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
509
+ `)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=Mi(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function ih(r,e){let t=G;e!=null&&sr(r,e);let n=await bi(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function oh(r){return{cap:await Cc(r)}}async function ah(r,e){return sr(r,e),{ok:!0}}async function ch(r,e){return ve(r,e)}var Qc=R(()=>{gn();dr();Vc()});import{readFileSync as el,writeFileSync as uh,mkdirSync as G0,appendFileSync as fh,rmSync as lh}from"fs";import{join as Ui,dirname as z0}from"path";import{createServer as Q0}from"http";function st(r){try{return JSON.parse(el(r,"utf8"))}catch{return null}}function qi(r,e){G0(z0(r),{recursive:!0}),uh(r,JSON.stringify(e,null,2)+`
479
510
  `)}function ph(r,e,t){let n=Ui(r,".gitignore"),s="";try{s=el(n,"utf8")}catch{}let i=new Set(s.split(/\r?\n/).map(c=>c.trim())),o=e.filter(c=>!i.has(c));if(!o.length)return;let a=s&&!s.endsWith(`
480
511
  `)?`
481
512
  `:"";try{fh(n,a+t+`
@@ -492,7 +523,7 @@ data: ${JSON.stringify(a)}
492
523
  `))!==-1;){let c=r.slice(0,a);if(r=r.slice(a+2),!c.trim())continue;let l=s(c);l!==null&&(o+=l)}return o}}function iE(r){return new Promise(e=>{let t=[];r.on("data",n=>t.push(n)),r.on("end",()=>e(Buffer.concat(t).toString("utf8"))),r.on("error",()=>e(Buffer.concat(t).toString("utf8")))})}function kn(r,e,t,n){r.writableEnded||(r.writeHead(e,{"content-type":"application/json"}),r.end(JSON.stringify({type:"error",error:{type:t,message:n}})))}async function oE(r,e,t){if(!Ee){kn(e,400,"invalid_request_error",eE);return}let n=process.env.OPENROUTER_API_KEY;if(!n){kn(e,401,"authentication_error","OPENROUTER_API_KEY not set in the typebulb proxy");return}let s=new AbortController;e.on("close",()=>{e.writableEnded||s.abort()});let i;try{i=await fetch(tl,{method:"POST",headers:hh(r,n),body:gh(t),signal:s.signal})}catch(u){kn(e,502,"api_error",`proxy upstream failed: ${U(u)}`);return}let o=i.headers.get("content-type")||"application/json";if(e.writeHead(i.status,{"content-type":o}),!i.body){e.end();return}let a=o.includes("event-stream"),c=i.body.getReader(),l=new TextDecoder,f=a?sE():null;try{for(;;){let{done:u,value:d}=await c.read();if(u)break;if(d)if(f){let p=l.decode(d,{stream:!0});rE(p);let b=f(p);b&&e.write(b)}else e.write(Buffer.from(d))}}catch{}finally{e.writableEnded||e.end()}}async function aE(r,e,t){let n=process.env.OPENROUTER_API_KEY,s=()=>{e.writeHead(200,{"content-type":"application/json"}),e.end(JSON.stringify({input_tokens:Math.max(1,Math.ceil(t.length/4))}))};if(!Ee||!n)return s();try{let i=await fetch(`${tl}/count_tokens`,{method:"POST",headers:hh(r,n),body:gh(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function cE(r,e){let t=r.url||"/";if(r.method==="HEAD"){e.writeHead(200),e.end();return}if(r.method!=="POST"){kn(e,404,"not_found_error",t);return}iE(r).then(n=>{if(t.includes("count_tokens"))return aE(r,e,n);if(t.includes("/v1/messages"))return oE(r,e,n);kn(e,404,"not_found_error",t)})}function lE(){return yr&&_t?Promise.resolve(_t):new Promise((r,e)=>{let t=Q0(cE);t.on("error",e),t.listen(0,"127.0.0.1",()=>{yr=t,_t=t.address().port,console.log(`[switcher] wire proxy listening on ${Fi(_t)}`),r(_t)})})}function uE(){try{yr?.close()}catch{}yr=null,_t=null}function fE(r,e){let t=Ji(r),n=st(t),s=n||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===Fi(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=Ki(r);if(!st(i)){let a={};for(let c of dh)a[c]=c in s.env?s.env[c]:null;qi(i,{managedBy:"agent-switcher",fileExisted:n!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=Fi(e),s.env.ANTHROPIC_AUTH_TOKEN=Z0,qi(t,s),ph(r,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function dE(r,e,t){let n=Ki(r),s=st(n)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},qi(n,s)}function yh(r){let e=Ji(r),t=Ki(r),n=st(t),s=st(e);if(s?.env){let i=n?.snapshot||{};for(let o of dh){let a=i[o];a==null?delete s.env[o]:s.env[o]=a}if(Object.keys(s.env).length===0&&delete s.env,n?.fileExisted===!1&&Object.keys(s).length===0)try{lh(e,{force:!0})}catch{}else qi(e,s)}try{lh(t,{force:!0})}catch{}}async function pE(){let r=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await Ne()).filter(t=>t.provider==="openrouter"&&!rl(t.name)).map(t=>({id:t.name,label:t.friendlyName||t.name}))}catch(t){console.error("[switcher] model list failed",U(t))}return{hasKey:r,models:e}}async function mE(){if(yr&&Ee)return{active:!0,managed:!0,model:Ee,port:_t,provider:Ct,routedModel:xn,caching:En,reasoning:An,externalBaseUrl:null};let r=st(Ji(G))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:An,externalBaseUrl:r.ANTHROPIC_BASE_URL||null}}async function bh(r,e){let t=await lE();return Ee=r,Ct=e,fE(G,t),t}async function hE({model:r}){if(!process.env.OPENROUTER_API_KEY)return{ok:!1,error:"OPENROUTER_API_KEY not set \u2014 add a key first"};if(!r)return{ok:!1,error:"no model given"};if(rl(r))return{ok:!1,error:"Refusing to route an Anthropic model through OpenRouter \u2014 that bills full API rate with no caching. Use it on your Anthropic subscription instead."};try{await bh(r,nl[r]??null),xn=null,En="unknown",dE(G,r,Ct)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${U(e)}`}}return{ok:!0}}async function gE({level:r}){return r!=null&&(!Number.isInteger(r)||r<0||r>=Xc.length)?{ok:!1,error:`reasoning level must be 0\u2013${Xc.length-1} or null`}:(An=r,{ok:!0,level:r})}async function yE(){return yh(G),Ee=null,Ct=null,xn=null,En="unknown",{ok:!0}}async function bE({key:r}){let e=(r||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=G,n=Ui(t,".env"),s="";try{s=el(n,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))uh(n,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
493
524
  `)?`
494
525
  `:"";fh(n,i+`OPENROUTER_API_KEY=${e}
495
- `)}}catch(i){return{ok:!1,error:U(i)}}return process.env.OPENROUTER_API_KEY=e,ph(t,[".env"],"# secrets"),{ok:!0}}function wE(){if(!(!yr&&!Ee)){try{yh(G)}catch{}uE()}}function vE(r,e){return wh.test(e)?"blocked by your OpenRouter data policy":r===401||r===403||/unauthor|invalid api key|no auth|forbidden/i.test(e)?"auth rejected \u2014 check your OpenRouter key":r===404||/not a valid model|no such model|unknown model|model not found/i.test(e)?"model not found on this route":r===429||/rate limit/i.test(e)?"rate limited":r===402||/insufficient|credit|quota|balance/i.test(e)?"out of credits / quota":e.slice(0,160)}function SE(r){if(wh.test(r))return"This model's only provider(s) require prompt logging/training, which your OpenRouter account disallows by default. Allow it (or that provider) at openrouter.ai/settings/privacy, then probe again."}function kE(r,e,t){if(!r)return{works:null,read:0,note:t?`couldn't re-test on ${t} \u2014 caching unconfirmed`:"caching unconfirmed"};let n=Zc(e?.cache_read_input_tokens)||Zc(e?.prompt_tokens_details?.cached_tokens),s=e?.cache_read_input_tokens!==void 0||e?.cache_creation_input_tokens!==void 0||e?.prompt_tokens_details!==void 0;return n>0?{works:!0,read:n,note:`${n} tokens read from cache on the 2nd call`}:s?{works:!1,read:n,note:"no cache reads after a warm call \u2014 every turn re-bills the full context"}:{works:null,read:n,note:"route doesn't report cache usage \u2014 caching almost certainly not honored"}}async function xE({model:r}){let e=process.env.OPENROUTER_API_KEY;if(!e)return{ok:!1,error:"OPENROUTER_API_KEY not set \u2014 add a key first"};if(!r)return{ok:!1,error:"no model given"};if(rl(r))return{ok:!1,error:"Anthropic model \u2014 not offered or probed via OpenRouter"};let t=Date.now(),n=Array(350).fill("Caching probe filler sentence; its only purpose is to exceed the prompt-cache minimum token threshold.").join(" "),s={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":"2023-06-01"},i={model:r,max_tokens:8,system:[{type:"text",text:n,cache_control:{type:"ephemeral"}}],messages:[{role:"user",content:"Reply with exactly: ok"}]},o=async a=>{let c=new AbortController,l=setTimeout(()=>c.abort(),2e4);try{let f=JSON.stringify(a?{...i,provider:mh(a)}:i),u=await fetch(tl,{method:"POST",signal:c.signal,headers:s,body:f}),d=await u.json().catch(()=>({}));return{r:u,j:d}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let E=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:vE(a.status,E),restriction:SE(E)}}let l=typeof c?.provider=="string"?c.provider:void 0,f=c?.content?.find?.(E=>E.type==="text")?.text??c?.content?.[0]?.text??"ok",u=Zc(c?.usage?.cache_creation_input_tokens),{r:d,j:p}=await o(l),{works:b,read:m,note:y}=kE(d.ok,p?.usage,l);return b===!0&&l&&(nl[r]=l,Ee===r&&(Ct=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:l,sample:String(f).trim().slice(0,60),cache:{works:b,created:u,read:m,note:y}}}catch(a){let c=U(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var X0,tl,Z0,eE,dh,tE,Xc,Ji,Ki,Fi,rl,yr,_t,Ee,Ct,xn,En,An,nl,Zc,mh,wh,vh=R(()=>{gn();dr();X0="https://openrouter.ai/api",tl=`${X0}/v1/messages`,Z0="typebulb-proxy-managed",eE="The typebulb model override was reverted to Anthropic, but this Claude Code session still points at the now-idle proxy. Reload the window (VS Code/Cursor: \u201CDeveloper: Reload Window\u201D) or relaunch `claude` in a terminal to return to your Anthropic subscription.",dh=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],tE=5e3,Xc=["low","medium","high"],Ji=r=>Ui(r,".claude","settings.local.json"),Ki=r=>Ui(r,".claude",".cc-switcher.json"),Fi=r=>`http://127.0.0.1:${r}`;rl=r=>/^anthropic\//i.test(r)||/claude/i.test(r),yr=null,_t=null,Ee=null,Ct=null,xn=null,En="unknown",An=1,nl={},Zc=r=>typeof r=="number"?r:0,mh=r=>({order:[r],allow_fallbacks:!1});wh=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=st(Ki(G)),t=e?.active?.model;if(!t)return;let s=(st(Ji(G))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await bh(t,e.active.provider??nl[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${Fi(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",U(e))}})()});var kh={};cl(kh,{attach:()=>_E,blockToMarkdown:()=>ki,breakout:()=>eh,capText:()=>Se,cleanUserText:()=>rt,clearSwitchModel:()=>yE,composerPasteRead:()=>CE,displayName:()=>EE,firstLineDigest:()=>Me,info:()=>AE,isHiddenTurn:()=>mn,launchBulb:()=>ih,listBreakouts:()=>th,listBulbFiles:()=>nh,listSessions:()=>OE,listSwitchModels:()=>pE,logEmbedStatus:()=>PE,openFile:()=>Zm,poll:()=>TE,predictTrustOf:()=>oh,probeModel:()=>xE,readBulbLog:()=>ch,saveOpenRouterKey:()=>bE,searchBulbs:()=>sh,searchSessions:()=>RE,setBulbTrust:()=>ah,setReasoning:()=>gE,setSwitchModel:()=>hE,shutdownSwitcher:()=>wE,stopBreakout:()=>rh,switchState:()=>mE,toolResultDigest:()=>Oc});var Sh,EE,AE,TE,PE,OE,RE,_E,CE,xh=R(()=>{Gc();xi();Qc();vh();xi();vi();Sh=new ur,EE=Sh.displayName,{info:AE,poll:TE,logEmbedStatus:PE,listSessions:OE,searchSessions:RE,attach:_E,composerPasteRead:CE}=ji(Sh)});var Ah={};cl(Ah,{attach:()=>BE,breakout:()=>eh,composerFiles:()=>UE,composerNew:()=>qE,composerPaste:()=>WE,composerPasteRead:()=>HE,composerRpc:()=>KE,composerSend:()=>jE,composerStop:()=>FE,composerUiRespond:()=>JE,displayName:()=>NE,info:()=>IE,launchBulb:()=>ih,listBreakouts:()=>th,listBulbFiles:()=>nh,listSessions:()=>ME,logEmbedStatus:()=>$E,openFile:()=>Zm,poll:()=>LE,predictTrustOf:()=>oh,readBulbLog:()=>ch,searchBulbs:()=>sh,searchSessions:()=>DE,setBulbTrust:()=>ah,shutdownComposer:()=>VE,stopBreakout:()=>rh});var Eh,NE,IE,LE,$E,ME,DE,BE,jE,FE,qE,UE,JE,KE,WE,HE,VE,Th=R(()=>{Gc();$c();Qc();Eh=new pr,NE=Eh.displayName,{info:IE,poll:LE,logEmbedStatus:$E,listSessions:ME,searchSessions:DE,attach:BE,composerSend:jE,composerStop:FE,composerNew:qE,composerFiles:UE,composerUiRespond:JE,composerRpc:KE,composerPaste:WE,composerPasteRead:HE,shutdownComposer:VE}=ji(Eh)});import*as Dh from"fs/promises";import*as Be from"path";import*as ul from"fs/promises";import{existsSync as Nt,readFileSync as ag}from"fs";import*as W from"path";import{pathToFileURL as cg}from"url";import{resolve as Gi}from"resolve.exports";import{init as fl,parse as dl}from"es-module-lexer";function pl(r,e){let t=W.join(r,"package.json");try{return JSON.parse(ag(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var Yi=["browser","import","default"],ll=["node","import","default"];function ml(r){let e=r.indexOf("=");if(e===-1)throw new Error(`--replace must be <name>=<path> (got '${r}')`);let t=r.slice(0,e).trim(),n=r.slice(e+1).trim();if(!t)throw new Error(`--replace missing package name (got '${r}')`);if(!n)throw new Error(`--replace missing path for '${t}'`);if(t.startsWith("@"))throw new Error(`--replace does not support scoped names yet; '${t}' is scoped`);return{name:t,dir:W.resolve(n)}}async function hl(r){let{name:e,dir:t}=r;if(!Nt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=pl(t,e),s=lg(n,e),i=W.resolve(t,s);if(!Nt(i))throw new Error(`--replace package '${e}' entry not found on disk: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);let o=W.dirname(i),a=`/local/${e}/${W.basename(i)}`,c=ug(n,t);return await fg(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function lg(r,e){if(r.exports!==void 0){let n;try{n=Gi(r,".",{browser:!0,conditions:Yi})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Yi.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=zi(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Yi.join(", ")}); too complex to override.`);return s}let t=r.module??r.main;if(!t)throw new Error(`--replace package '${e}' has no "exports", "module", or "main" entry to resolve.`);return t}function ug(r,e){if(r.exports!==void 0)try{let n=Gi(r,".",{conditions:["types"]}),s=zi(n);if(s){let i=W.resolve(e,s);if(Nt(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=W.resolve(e,t);if(Nt(n))return n}}function zi(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function fg(r,e,t){await fl;let n=W.normalize(t),s=new Set,i=[e];for(;i.length;){let o=i.shift();if(s.has(o))continue;s.add(o);let a;try{a=await ul.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=dl(a,o)}catch{continue}if(o===e&&!l)throw new Error(`override package '${r}' entry is not an ES module (no import/export syntax); CommonJS or non-module entries aren't supported (esm.sh would have to transform it).`);for(let f of c){if(f.d===-2)continue;let u=f.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let d=dg(o,u,n);d&&!s.has(d)&&i.push(d);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${u}'`)}}}}function dg(r,e,t){let n=e.replace(/[?#].*$/,""),s=W.resolve(W.dirname(r),n),i=[s,s+".js",s+".mjs",W.join(s,"index.js"),W.join(s,"index.mjs")];for(let o of i)if(W.normalize(o).startsWith(t)&&Nt(o))return o}function pg(r,e,t){let n=pl(r,e),s;if(n.exports!==void 0)try{s=zi(Gi(n,t,{conditions:ll}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${ll.join(", ")}): ${o instanceof Error?o.message:o}`)}else t==="."&&(s=n.main??n.module);if(!s)throw new Error(`--replace package '${e}' has no node export for '${t}'.`);let i=W.resolve(r,s);if(!Nt(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return cg(i).href}async function gl(r,e){await fl;let t;try{[t]=dl(r)}catch{return r}let n="",s=0;for(let i of t){if(i.d!==-1)continue;let o=i.n;if(!o||o!==e.name&&!o.startsWith(e.name+"/"))continue;let a=o===e.name?".":"."+o.slice(e.name.length),c=pg(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var mg=5e3;function yl(r){let t={subcommand:"run",file:"",port:3e3,watch:!0,open:!(process.env.TERM_PROGRAM==="vscode"),server:!1,trust:!1,noTrust:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},n=["call","check","predict","logs","wait","stop","trust","untrust","skill","models","send"],s=r[0];if(s==="agent"||s?.startsWith("agent:")){t.subcommand="agent";let o=s.indexOf(":");if(o!==-1){let a=s.slice(o+1);a&&(t.agentTarget=a)}r=r.slice(1)}else s&&n.includes(s)&&(t.subcommand=s,r=r.slice(1));let i=[];for(let o=0;o<r.length;o++){let a=r[o];if(a==="--help"||a==="-h")t.help=!0;else if(a==="--version"||a==="-V")t.version=!0;else if(a==="--no-watch")t.watch=!1;else if(a==="--open")t.open=!0;else if(a==="--no-open")t.open=!1;else if(a==="--server")t.server=!0;else if(a==="--trust")t.trust=!0;else if(a==="--no-trust")t.noTrust=!0;else if(a==="--mode"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),t.mode=c}else if(a==="--follow"||a==="-f")t.follow=!0;else if(a==="--clear")t.clear=!0;else if(a==="--run"){let c=r[++o];if(c==="latest")t.run="latest";else{let l=parseInt(c,10);(isNaN(l)||l<1)&&(console.error(`Invalid --run value: ${c} (a run number, or 'latest')`),process.exit(1)),t.run=l}}else if(a==="--bulbs")t.stopScope="bulbs";else if(a==="--agent")t.stopScope="agent";else if(a==="--global")t.stopScope="global";else if(a==="--match"){let c=r[++o];c===void 0&&(console.error("Missing value for --match (a literal substring new log lines must contain)"),process.exit(1)),t.match=c}else if(a==="--timeout"){let c=parseInt(r[++o],10);(isNaN(c)||c<=0)&&(console.error(`Invalid --timeout value: ${r[o]} (seconds)`),process.exit(1)),t.timeoutSec=c}else if(a==="--wait"||a.startsWith("--wait="))if(a.startsWith("--wait=")){let c=parseInt(a.slice(7),10);(isNaN(c)||c<=0)&&(console.error(`Invalid --wait value: ${a.slice(7)} (milliseconds)`),process.exit(1)),t.sendWaitMs=c}else t.sendWaitMs=mg;else if(a==="--lines"||a==="-n"){let c=parseInt(r[++o],10);(isNaN(c)||c<0)&&(console.error(`Invalid --lines value: ${r[o]}`),process.exit(1)),t.lines=c}else if(a==="--port"||a==="-p"){let c=r[++o],l=parseInt(c,10);isNaN(l)&&(console.error(`Invalid port: ${c}`),process.exit(1)),t.port=l}else if(a==="--replace"||a.startsWith("--replace=")){let c=a.startsWith("--replace=")?a.slice(10):r[++o]??"";try{let l=ml(c);if(t.local)throw new Error(`--replace can only be used once (got '${t.local.name}' and '${l.name}')`);t.local=l}catch(l){console.error(l instanceof Error?l.message:String(l)),process.exit(1)}}else if(a==="--args"||a.startsWith("--args=")){t.hasArgsFlag=!0;let c=a.startsWith("--args=")?a.slice(7):r[++o];c===void 0&&(console.error("Missing value for --args (a JSON array, or - to read it from stdin)"),process.exit(1)),t.argsJson=c}else a.startsWith("-")||(t.subcommand==="call"||t.subcommand==="send"?i.push(a):t.file=a)}return t.subcommand==="call"&&(i.length<2&&(console.error("Usage: typebulb call <file> <fn> [arg\u2026]"),process.exit(1)),t.file=i[0],t.fn=i[1],t.callArgs=i.slice(2)),t.subcommand==="send"&&(i.length<1&&(console.error("Usage: typebulb send <file> [message]"),process.exit(1)),t.file=i[0],t.sendMessage=i[1]),t}function bl(){console.log(`
526
+ `)}}catch(i){return{ok:!1,error:U(i)}}return process.env.OPENROUTER_API_KEY=e,ph(t,[".env"],"# secrets"),{ok:!0}}function wE(){if(!(!yr&&!Ee)){try{yh(G)}catch{}uE()}}function vE(r,e){return wh.test(e)?"blocked by your OpenRouter data policy":r===401||r===403||/unauthor|invalid api key|no auth|forbidden/i.test(e)?"auth rejected \u2014 check your OpenRouter key":r===404||/not a valid model|no such model|unknown model|model not found/i.test(e)?"model not found on this route":r===429||/rate limit/i.test(e)?"rate limited":r===402||/insufficient|credit|quota|balance/i.test(e)?"out of credits / quota":e.slice(0,160)}function SE(r){if(wh.test(r))return"This model's only provider(s) require prompt logging/training, which your OpenRouter account disallows by default. Allow it (or that provider) at openrouter.ai/settings/privacy, then probe again."}function kE(r,e,t){if(!r)return{works:null,read:0,note:t?`couldn't re-test on ${t} \u2014 caching unconfirmed`:"caching unconfirmed"};let n=Zc(e?.cache_read_input_tokens)||Zc(e?.prompt_tokens_details?.cached_tokens),s=e?.cache_read_input_tokens!==void 0||e?.cache_creation_input_tokens!==void 0||e?.prompt_tokens_details!==void 0;return n>0?{works:!0,read:n,note:`${n} tokens read from cache on the 2nd call`}:s?{works:!1,read:n,note:"no cache reads after a warm call \u2014 every turn re-bills the full context"}:{works:null,read:n,note:"route doesn't report cache usage \u2014 caching almost certainly not honored"}}async function xE({model:r}){let e=process.env.OPENROUTER_API_KEY;if(!e)return{ok:!1,error:"OPENROUTER_API_KEY not set \u2014 add a key first"};if(!r)return{ok:!1,error:"no model given"};if(rl(r))return{ok:!1,error:"Anthropic model \u2014 not offered or probed via OpenRouter"};let t=Date.now(),n=Array(350).fill("Caching probe filler sentence; its only purpose is to exceed the prompt-cache minimum token threshold.").join(" "),s={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":"2023-06-01"},i={model:r,max_tokens:8,system:[{type:"text",text:n,cache_control:{type:"ephemeral"}}],messages:[{role:"user",content:"Reply with exactly: ok"}]},o=async a=>{let c=new AbortController,l=setTimeout(()=>c.abort(),2e4);try{let f=JSON.stringify(a?{...i,provider:mh(a)}:i),u=await fetch(tl,{method:"POST",signal:c.signal,headers:s,body:f}),d=await u.json().catch(()=>({}));return{r:u,j:d}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let E=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:vE(a.status,E),restriction:SE(E)}}let l=typeof c?.provider=="string"?c.provider:void 0,f=c?.content?.find?.(E=>E.type==="text")?.text??c?.content?.[0]?.text??"ok",u=Zc(c?.usage?.cache_creation_input_tokens),{r:d,j:p}=await o(l),{works:b,read:m,note:y}=kE(d.ok,p?.usage,l);return b===!0&&l&&(nl[r]=l,Ee===r&&(Ct=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:l,sample:String(f).trim().slice(0,60),cache:{works:b,created:u,read:m,note:y}}}catch(a){let c=U(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var X0,tl,Z0,eE,dh,tE,Xc,Ji,Ki,Fi,rl,yr,_t,Ee,Ct,xn,En,An,nl,Zc,mh,wh,vh=R(()=>{gn();dr();X0="https://openrouter.ai/api",tl=`${X0}/v1/messages`,Z0="typebulb-proxy-managed",eE="The typebulb model override was reverted to Anthropic, but this Claude Code session still points at the now-idle proxy. Reload the window (VS Code/Cursor: \u201CDeveloper: Reload Window\u201D) or relaunch `claude` in a terminal to return to your Anthropic subscription.",dh=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],tE=5e3,Xc=["low","medium","high"],Ji=r=>Ui(r,".claude","settings.local.json"),Ki=r=>Ui(r,".claude",".cc-switcher.json"),Fi=r=>`http://127.0.0.1:${r}`;rl=r=>/^anthropic\//i.test(r)||/claude/i.test(r),yr=null,_t=null,Ee=null,Ct=null,xn=null,En="unknown",An=1,nl={},Zc=r=>typeof r=="number"?r:0,mh=r=>({order:[r],allow_fallbacks:!1});wh=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=st(Ki(G)),t=e?.active?.model;if(!t)return;let s=(st(Ji(G))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await bh(t,e.active.provider??nl[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${Fi(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",U(e))}})()});var kh={};cl(kh,{attach:()=>_E,blockToMarkdown:()=>ki,breakout:()=>eh,capText:()=>Se,cleanUserText:()=>rt,clearSwitchModel:()=>yE,composerPasteRead:()=>CE,displayName:()=>EE,firstLineDigest:()=>$e,info:()=>AE,isHiddenTurn:()=>mn,launchBulb:()=>ih,listBreakouts:()=>th,listBulbFiles:()=>nh,listSessions:()=>OE,listSwitchModels:()=>pE,logEmbedStatus:()=>PE,openFile:()=>Zm,poll:()=>TE,predictTrustOf:()=>oh,probeModel:()=>xE,readBulbLog:()=>ch,saveOpenRouterKey:()=>bE,searchBulbs:()=>sh,searchSessions:()=>RE,setBulbTrust:()=>ah,setReasoning:()=>gE,setSwitchModel:()=>hE,shutdownSwitcher:()=>wE,stopBreakout:()=>rh,switchState:()=>mE,toolResultDigest:()=>Oc});var Sh,EE,AE,TE,PE,OE,RE,_E,CE,xh=R(()=>{Gc();xi();Qc();vh();xi();vi();Sh=new ur,EE=Sh.displayName,{info:AE,poll:TE,logEmbedStatus:PE,listSessions:OE,searchSessions:RE,attach:_E,composerPasteRead:CE}=ji(Sh)});var Ah={};cl(Ah,{attach:()=>BE,breakout:()=>eh,composerFiles:()=>UE,composerNew:()=>qE,composerPaste:()=>WE,composerPasteRead:()=>HE,composerRpc:()=>KE,composerSend:()=>jE,composerStop:()=>FE,composerUiRespond:()=>JE,displayName:()=>NE,info:()=>IE,launchBulb:()=>ih,listBreakouts:()=>th,listBulbFiles:()=>nh,listSessions:()=>$E,logEmbedStatus:()=>ME,openFile:()=>Zm,poll:()=>LE,predictTrustOf:()=>oh,readBulbLog:()=>ch,searchBulbs:()=>sh,searchSessions:()=>DE,setBulbTrust:()=>ah,shutdownComposer:()=>VE,stopBreakout:()=>rh});var Eh,NE,IE,LE,ME,$E,DE,BE,jE,FE,qE,UE,JE,KE,WE,HE,VE,Th=R(()=>{Gc();Mc();Qc();Eh=new pr,NE=Eh.displayName,{info:IE,poll:LE,logEmbedStatus:ME,listSessions:$E,searchSessions:DE,attach:BE,composerSend:jE,composerStop:FE,composerNew:qE,composerFiles:UE,composerUiRespond:JE,composerRpc:KE,composerPaste:WE,composerPasteRead:HE,shutdownComposer:VE}=ji(Eh)});import*as Dh from"fs/promises";import*as Be from"path";import*as ul from"fs/promises";import{existsSync as Nt,readFileSync as ag}from"fs";import*as W from"path";import{pathToFileURL as cg}from"url";import{resolve as Gi}from"resolve.exports";import{init as fl,parse as dl}from"es-module-lexer";function pl(r,e){let t=W.join(r,"package.json");try{return JSON.parse(ag(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var Yi=["browser","import","default"],ll=["node","import","default"];function ml(r){let e=r.indexOf("=");if(e===-1)throw new Error(`--replace must be <name>=<path> (got '${r}')`);let t=r.slice(0,e).trim(),n=r.slice(e+1).trim();if(!t)throw new Error(`--replace missing package name (got '${r}')`);if(!n)throw new Error(`--replace missing path for '${t}'`);if(t.startsWith("@"))throw new Error(`--replace does not support scoped names yet; '${t}' is scoped`);return{name:t,dir:W.resolve(n)}}async function hl(r){let{name:e,dir:t}=r;if(!Nt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=pl(t,e),s=lg(n,e),i=W.resolve(t,s);if(!Nt(i))throw new Error(`--replace package '${e}' entry not found on disk: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);let o=W.dirname(i),a=`/local/${e}/${W.basename(i)}`,c=ug(n,t);return await fg(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function lg(r,e){if(r.exports!==void 0){let n;try{n=Gi(r,".",{browser:!0,conditions:Yi})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Yi.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=zi(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Yi.join(", ")}); too complex to override.`);return s}let t=r.module??r.main;if(!t)throw new Error(`--replace package '${e}' has no "exports", "module", or "main" entry to resolve.`);return t}function ug(r,e){if(r.exports!==void 0)try{let n=Gi(r,".",{conditions:["types"]}),s=zi(n);if(s){let i=W.resolve(e,s);if(Nt(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=W.resolve(e,t);if(Nt(n))return n}}function zi(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function fg(r,e,t){await fl;let n=W.normalize(t),s=new Set,i=[e];for(;i.length;){let o=i.shift();if(s.has(o))continue;s.add(o);let a;try{a=await ul.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=dl(a,o)}catch{continue}if(o===e&&!l)throw new Error(`override package '${r}' entry is not an ES module (no import/export syntax); CommonJS or non-module entries aren't supported (esm.sh would have to transform it).`);for(let f of c){if(f.d===-2)continue;let u=f.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let d=dg(o,u,n);d&&!s.has(d)&&i.push(d);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${u}'`)}}}}function dg(r,e,t){let n=e.replace(/[?#].*$/,""),s=W.resolve(W.dirname(r),n),i=[s,s+".js",s+".mjs",W.join(s,"index.js"),W.join(s,"index.mjs")];for(let o of i)if(W.normalize(o).startsWith(t)&&Nt(o))return o}function pg(r,e,t){let n=pl(r,e),s;if(n.exports!==void 0)try{s=zi(Gi(n,t,{conditions:ll}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${ll.join(", ")}): ${o instanceof Error?o.message:o}`)}else t==="."&&(s=n.main??n.module);if(!s)throw new Error(`--replace package '${e}' has no node export for '${t}'.`);let i=W.resolve(r,s);if(!Nt(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return cg(i).href}async function gl(r,e){await fl;let t;try{[t]=dl(r)}catch{return r}let n="",s=0;for(let i of t){if(i.d!==-1)continue;let o=i.n;if(!o||o!==e.name&&!o.startsWith(e.name+"/"))continue;let a=o===e.name?".":"."+o.slice(e.name.length),c=pg(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var mg=5e3;function yl(r){let t={subcommand:"run",file:"",port:3e3,watch:!0,open:!(process.env.TERM_PROGRAM==="vscode"),server:!1,trust:!1,noTrust:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},n=["call","check","predict","logs","wait","stop","trust","untrust","skill","models","send"],s=r[0];if(s==="agent"||s?.startsWith("agent:")){t.subcommand="agent";let o=s.indexOf(":");if(o!==-1){let a=s.slice(o+1);a&&(t.agentTarget=a)}r=r.slice(1)}else s&&n.includes(s)&&(t.subcommand=s,r=r.slice(1));let i=[];for(let o=0;o<r.length;o++){let a=r[o];if(a==="--help"||a==="-h")t.help=!0;else if(a==="--version"||a==="-V")t.version=!0;else if(a==="--no-watch")t.watch=!1;else if(a==="--open")t.open=!0;else if(a==="--no-open")t.open=!1;else if(a==="--server")t.server=!0;else if(a==="--trust")t.trust=!0;else if(a==="--no-trust")t.noTrust=!0;else if(a==="--mode"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),t.mode=c}else if(a==="--follow"||a==="-f")t.follow=!0;else if(a==="--clear")t.clear=!0;else if(a==="--run"){let c=r[++o];if(c==="latest")t.run="latest";else{let l=parseInt(c,10);(isNaN(l)||l<1)&&(console.error(`Invalid --run value: ${c} (a run number, or 'latest')`),process.exit(1)),t.run=l}}else if(a==="--bulbs")t.stopScope="bulbs";else if(a==="--agent")t.stopScope="agent";else if(a==="--global")t.stopScope="global";else if(a==="--match"){let c=r[++o];c===void 0&&(console.error("Missing value for --match (a literal substring new log lines must contain)"),process.exit(1)),t.match=c}else if(a==="--timeout"){let c=parseInt(r[++o],10);(isNaN(c)||c<=0)&&(console.error(`Invalid --timeout value: ${r[o]} (seconds)`),process.exit(1)),t.timeoutSec=c}else if(a==="--wait"||a.startsWith("--wait="))if(a.startsWith("--wait=")){let c=parseInt(a.slice(7),10);(isNaN(c)||c<=0)&&(console.error(`Invalid --wait value: ${a.slice(7)} (milliseconds)`),process.exit(1)),t.sendWaitMs=c}else t.sendWaitMs=mg;else if(a==="--lines"||a==="-n"){let c=parseInt(r[++o],10);(isNaN(c)||c<0)&&(console.error(`Invalid --lines value: ${r[o]}`),process.exit(1)),t.lines=c}else if(a==="--port"||a==="-p"){let c=r[++o],l=parseInt(c,10);isNaN(l)&&(console.error(`Invalid port: ${c}`),process.exit(1)),t.port=l}else if(a==="--replace"||a.startsWith("--replace=")){let c=a.startsWith("--replace=")?a.slice(10):r[++o]??"";try{let l=ml(c);if(t.local)throw new Error(`--replace can only be used once (got '${t.local.name}' and '${l.name}')`);t.local=l}catch(l){console.error(l instanceof Error?l.message:String(l)),process.exit(1)}}else if(a==="--args"||a.startsWith("--args=")){t.hasArgsFlag=!0;let c=a.startsWith("--args=")?a.slice(7):r[++o];c===void 0&&(console.error("Missing value for --args (a JSON array, or - to read it from stdin)"),process.exit(1)),t.argsJson=c}else a.startsWith("-")||(t.subcommand==="call"||t.subcommand==="send"?i.push(a):t.file=a)}return t.subcommand==="call"&&(i.length<2&&(console.error("Usage: typebulb call <file> <fn> [arg\u2026]"),process.exit(1)),t.file=i[0],t.fn=i[1],t.callArgs=i.slice(2)),t.subcommand==="send"&&(i.length<1&&(console.error("Usage: typebulb send <file> [message]"),process.exit(1)),t.file=i[0],t.sendMessage=i[1]),t}function bl(){console.log(`
496
527
  typebulb - Local bulb runner for Typebulb
497
528
 
498
529
  Usage:
@@ -624,7 +655,7 @@ Examples:
624
655
  `)}Xr();import*as et from"fs/promises";import*as ai from"path";import{pathToFileURL as GS}from"url";import{transform as eS}from"sucrase";function ja(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=eS(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}Os();function aS(r){return r.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
625
656
  `)[0]}`).join(`
626
657
  `)}function Id(r,e){let t=Zr(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
627
- ${aS(t)}`)}var Ge="https://esm.sh",en="https://cdn.jsdelivr.net/npm/",Fa="https://data.jsdelivr.com/v1/package/npm/";function Ld(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var N=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=Vt(t??s.version),this.subpath=Vt(n??s.subpath)}static parse(e){let t=Ld(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=$d(t[1]??""),a=Vt(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=$d(t[0]),o=Vt(t.slice(1).join("/"));return new r({name:s,version:i,subpath:o})}}static fromUrl(e){try{let t=new URL(e),n=new URL(Ge).host,s=new URL(en).host;if(t.host===n){let i=Ld(t.pathname.replace(/^\/v\d+\//,"/"));if(!i.length)return;let o=i[0].startsWith("@")?`${i[0]}/${i[1]??""}`:i[0];return r.parse(o)}if(t.host===s){let i=t.pathname.split("/npm/")[1];if(!i)return;let o=i.split("/")[0]||"";return r.parse(o)}return}catch{return}}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return r.parse(e).name}withVersion(e){return new r({name:this.name,version:Vt(e),subpath:this.subpath})}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},Vt=r=>r&&r.length?r:void 0,$d=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),Vt(r.slice(e+1))]};async function Oe(r){try{return await r()}catch{return}}function mt(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function qa(r){return r.startsWith("./")?r:`./${r}`}var tn=class{constructor(e,t){this.cache=e,this.http=t,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}baseDir(e){let t=typeof e=="string"?new N(e):e;return`${en}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(mt(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:n="es2022",bundle:s=!1,external:i}=t,o=new URLSearchParams({target:n});return s&&o.append("bundle",""),i?.length&&o.append("external",i.join(",")),`${Ge}/${e}?${o.toString()}`}async resolveExactVersion(e){let t=Date.now(),n=this.pinCache.get(e);if(n&&t-n.ts<this.pinMs)return n.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${Ge}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await Oe(()=>this.http.head(t)),s=this.parseVersionFromUrl(n?.url||t);if(s)return s}}async fetchVersionsIndex(e){if(await this.cache.isNegative(e))return;let t=await this.cache.getIndex(e);if(t&&Date.now()-t.updatedAt<this.versionsIndexMs)return{versions:t.versions,distTags:t.distTags};let n=await Oe(()=>this.http.getJson(`${Fa}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.distTags&&Object.keys(n.distTags).length?n.distTags:void 0;return await this.cache.setIndex(e,n.versions,s),n}parseVersionFromUrl(e){let t=N.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:f,peerDependencies:u,peerDependenciesMeta:d}=n;return{name:e,version:t,dependencies:f,peerDependencies:u,peerDependenciesMeta:d}}let s=this.packageJson(new N(`${e}@${t}`)),i=await Oe(()=>this.http.getJson(s));if(!i)return;let o=f=>f&&Object.keys(f).length?f:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}};var Md=r=>r.startsWith("@types/"),rn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!Md(e)),Ua=r=>Object.keys(r?.dependencies||{}).filter(e=>!Md(e)),cS=r=>rn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),nn=class{constructor(e){this.cdn=e}async resolve(e,t){let n=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:i}=await this.expandWithPeers(n,t),o=this.computeFlags(s);return{allRoots:s,flags:o,autoAddedPeers:i}}async fetchMeta(e){return Promise.all(e.map(async({name:t,version:n})=>({name:t,version:n,meta:await this.cdn.fetchPackageMeta(t,n)})))}async expandWithPeers(e,t){let n=new Map(e.map(i=>[i.name,i])),s=[];for(let i of e)for(let o of cS(i.meta))!n.has(o)&&!s.some(a=>a.name===o)&&s.push({name:o,requiredBy:i.name});for(let{name:i,requiredBy:o}of s)try{let a=await t(i),c=await this.cdn.fetchPackageMeta(i,a);n.set(i,{name:i,version:a,meta:c})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${i}" for "${o}":`,a)}return{allRoots:[...n.values()],autoAddedPeers:s.filter(i=>n.has(i.name))}}computeFlags(e){let t=new Set(e.flatMap(i=>rn(i.meta))),n=new Map;for(let i of e)for(let o of Ua(i.meta))n.set(o,(n.get(o)||0)+1);let s=new Set([...n.entries()].filter(([,i])=>i>=2).map(([i])=>i));return new Map(e.map(i=>[i.name,{isPeerRoot:t.has(i.name),hasPeers:rn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var sn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await Oe(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let n=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(n)return n}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let n=await this.cache.getPinnedExact(e,t);if(n){if(this.semver.isExactVersion(n))return n;console.debug("[typebulb] cached version for",e,"is not exact (",n,"); re-resolving from registry")}let s=async o=>{if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o},i=await Oe(()=>this.cdn.fetchVersionsIndex(e));if(i?.versions?.length){let o=this.semver.selectBestVersion(i.versions,{range:t,distTags:i.distTags});if(o){let a=await s(o);if(a)return a}else{console.debug("[typebulb] refreshing version cache for",e,"(",t,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(e);let a=await Oe(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=await s(this.semver.selectBestVersion(a.versions,{range:t,distTags:a.distTags}));if(c)return c}}}return s(await this.cdn.resolveExactVersion(`${e}@${t}`))}async effectivePackage(e,t){let n=new N(e),s=n.root(),i=t[s],o=i?await Oe(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as lS,parse as uS}from"es-module-lexer";var Yt=class r{constructor(e,t,n){this.version=e,this.cdn=t,this.peer=n}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))N.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{N.isBare(s)&&t.add(s)};try{await lS;let[s]=uS(e);s.forEach(i=>n(e.slice(i.s,i.e).trim()))}catch{return this.extractImportsSync(e)}return Array.from(t)}async buildImportMap(e,t,n){let s=(await this.extractImports(e)).filter(u=>!n?.has(N.rootOf(u))),i=[...new Set(s.map(N.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),f=this.buildEntries([...s,...l.map(u=>u.name)],a,c);return{importMap:{imports:Object.fromEntries(f)},prefetchUrls:f.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=await this.version.resolveExactForRoot(e,n);if(!s)throw new Error(`Cannot resolve ${n?`${e}@${n}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,n){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let b=s.get(N.rootOf(p));return new N(p).withVersion(b.version).format()},o=new Set([...n.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==N.rootOf(p)).map(N.rootOf)),c=[],l=new Set,f=new Set(e.filter(p=>p===N.rootOf(p))),u=new Set;for(let p of e){let b=N.rootOf(p),m=s.get(b),{isPeerRoot:y,hasPeers:E,isSharedDep:T}=n.get(b),g=a.has(b),w=p!==b,x=!(y||T)&&(g||!E),O=this.singletonDepsOf(m,o),A=w&&f.has(b);A&&u.add(b);let L=A?[...O,b]:O.length?O:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:x,external:L})]),l.add(p)}let d=new Set([...o,...u]);for(let p of d)s.has(p)&&(l.has(p)||c.push([p,this.cdn.buildEsmUrl(i(p),{})]),c.push([`${p}/`,`${Ge}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...rn(e.meta),...Ua(e.meta)])].filter(n=>t.has(n))}};Yt.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as Dd,satisfies as fS,maxSatisfying as Bd,major as dS,valid as pS}from"semver";var Rs=class{cmp(e,t){return e===t?0:Dd(e,t)?1:Dd(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!fS(t,e,{includePrerelease:!0})}selectBestVersion(e,t){if(!e?.length)return;let n=t?.range?.trim()||"*",s=t?.preferStable??!0,i=t?.distTags?.latest;if(i&&e.includes(i)&&this.satisfies(n,i))return i;if(s){let a=Bd(e,n,{includePrerelease:!1});if(a)return a}return Bd(e,n,{includePrerelease:!0})??void 0}majorOf(e){return dS(e)}isExactVersion(e){return pS(e)!==null}},ht=new Rs;function jd(r,e){let t=new tn(r,e),n=new nn(t),s=new sn(r,t,ht);return{packageService:new Yt(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as tp from"fs/promises";import*as de from"path";var Ja=[{name:"es5"},{name:"es2015.core"},{name:"es2015.collection"},{name:"es2015.promise"},{name:"es2015.iterable"},{name:"es2015.symbol"},{name:"es2015.symbol.wellknown"},{name:"es2015.generator"},{name:"es2015.proxy"},{name:"es2015.reflect"},{name:"es2016.array.include"},{name:"es2016.intl"},{name:"es2017.object"},{name:"es2017.string"},{name:"es2017.sharedmemory"},{name:"es2017.typedarrays"},{name:"es2017.date"},{name:"es2017.intl"},{name:"es2018.asynciterable"},{name:"es2018.asyncgenerator"},{name:"es2018.promise"},{name:"es2018.regexp"},{name:"es2018.intl"},{name:"es2019.array"},{name:"es2019.object"},{name:"es2019.string"},{name:"es2019.symbol"},{name:"es2019.intl"},{name:"es2020.bigint"},{name:"es2020.promise"},{name:"es2020.string"},{name:"es2020.sharedmemory"},{name:"es2020.date"},{name:"es2020.number"},{name:"es2020.symbol.wellknown"},{name:"es2020.intl"},{name:"es2021.promise"},{name:"es2021.string"},{name:"es2021.weakref"},{name:"es2021.intl"},{name:"es2022.array"},{name:"es2022.object"},{name:"es2022.error"},{name:"es2022.string"},{name:"es2022.regexp"},{name:"es2022.intl"},{name:"es2023.array"},{name:"es2023.collection"},{name:"es2023.intl",since:"5.5"},{name:"es2024.arraybuffer",since:"5.5"},{name:"es2024.collection",since:"5.5"},{name:"es2024.object",since:"5.5"},{name:"es2024.promise",since:"5.5"},{name:"es2024.regexp",since:"5.5"},{name:"es2024.sharedmemory",since:"5.5"},{name:"es2024.string",since:"5.5"},{name:"esnext.array",since:"5.5"},{name:"esnext.collection"},{name:"esnext.decorators"},{name:"esnext.disposable"},{name:"esnext.error",since:"5.5"},{name:"esnext.float16",since:"5.5"},{name:"esnext.iterator",since:"5.5"},{name:"esnext.object"},{name:"esnext.promise"},{name:"esnext.sharedmemory",since:"5.5"},{name:"esnext.intl"}],Ka=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function Wa(r,e){if(!e)return r.filter(s=>!s.since);let t={"5.0":0,"5.5":1},n=t[e];return r.filter(s=>!s.since||t[s.since]<=n)}var mS=`
658
+ ${aS(t)}`)}var Ge="https://esm.sh",en="https://cdn.jsdelivr.net/npm/",Fa="https://data.jsdelivr.com/v1/package/npm/";function Ld(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var N=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=Vt(t??s.version),this.subpath=Vt(n??s.subpath)}static parse(e){let t=Ld(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=Md(t[1]??""),a=Vt(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Md(t[0]),o=Vt(t.slice(1).join("/"));return new r({name:s,version:i,subpath:o})}}static fromUrl(e){try{let t=new URL(e),n=new URL(Ge).host,s=new URL(en).host;if(t.host===n){let i=Ld(t.pathname.replace(/^\/v\d+\//,"/"));if(!i.length)return;let o=i[0].startsWith("@")?`${i[0]}/${i[1]??""}`:i[0];return r.parse(o)}if(t.host===s){let i=t.pathname.split("/npm/")[1];if(!i)return;let o=i.split("/")[0]||"";return r.parse(o)}return}catch{return}}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return r.parse(e).name}withVersion(e){return new r({name:this.name,version:Vt(e),subpath:this.subpath})}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},Vt=r=>r&&r.length?r:void 0,Md=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),Vt(r.slice(e+1))]};async function Oe(r){try{return await r()}catch{return}}function mt(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function qa(r){return r.startsWith("./")?r:`./${r}`}var tn=class{constructor(e,t){this.cache=e,this.http=t,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}baseDir(e){let t=typeof e=="string"?new N(e):e;return`${en}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(mt(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:n="es2022",bundle:s=!1,external:i}=t,o=new URLSearchParams({target:n});return s&&o.append("bundle",""),i?.length&&o.append("external",i.join(",")),`${Ge}/${e}?${o.toString()}`}async resolveExactVersion(e){let t=Date.now(),n=this.pinCache.get(e);if(n&&t-n.ts<this.pinMs)return n.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${Ge}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await Oe(()=>this.http.head(t)),s=this.parseVersionFromUrl(n?.url||t);if(s)return s}}async fetchVersionsIndex(e){if(await this.cache.isNegative(e))return;let t=await this.cache.getIndex(e);if(t&&Date.now()-t.updatedAt<this.versionsIndexMs)return{versions:t.versions,distTags:t.distTags};let n=await Oe(()=>this.http.getJson(`${Fa}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.distTags&&Object.keys(n.distTags).length?n.distTags:void 0;return await this.cache.setIndex(e,n.versions,s),n}parseVersionFromUrl(e){let t=N.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:f,peerDependencies:u,peerDependenciesMeta:d}=n;return{name:e,version:t,dependencies:f,peerDependencies:u,peerDependenciesMeta:d}}let s=this.packageJson(new N(`${e}@${t}`)),i=await Oe(()=>this.http.getJson(s));if(!i)return;let o=f=>f&&Object.keys(f).length?f:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}};var $d=r=>r.startsWith("@types/"),rn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!$d(e)),Ua=r=>Object.keys(r?.dependencies||{}).filter(e=>!$d(e)),cS=r=>rn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),nn=class{constructor(e){this.cdn=e}async resolve(e,t){let n=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:i}=await this.expandWithPeers(n,t),o=this.computeFlags(s);return{allRoots:s,flags:o,autoAddedPeers:i}}async fetchMeta(e){return Promise.all(e.map(async({name:t,version:n})=>({name:t,version:n,meta:await this.cdn.fetchPackageMeta(t,n)})))}async expandWithPeers(e,t){let n=new Map(e.map(i=>[i.name,i])),s=[];for(let i of e)for(let o of cS(i.meta))!n.has(o)&&!s.some(a=>a.name===o)&&s.push({name:o,requiredBy:i.name});for(let{name:i,requiredBy:o}of s)try{let a=await t(i),c=await this.cdn.fetchPackageMeta(i,a);n.set(i,{name:i,version:a,meta:c})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${i}" for "${o}":`,a)}return{allRoots:[...n.values()],autoAddedPeers:s.filter(i=>n.has(i.name))}}computeFlags(e){let t=new Set(e.flatMap(i=>rn(i.meta))),n=new Map;for(let i of e)for(let o of Ua(i.meta))n.set(o,(n.get(o)||0)+1);let s=new Set([...n.entries()].filter(([,i])=>i>=2).map(([i])=>i));return new Map(e.map(i=>[i.name,{isPeerRoot:t.has(i.name),hasPeers:rn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var sn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await Oe(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let n=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(n)return n}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let n=await this.cache.getPinnedExact(e,t);if(n){if(this.semver.isExactVersion(n))return n;console.debug("[typebulb] cached version for",e,"is not exact (",n,"); re-resolving from registry")}let s=async o=>{if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o},i=await Oe(()=>this.cdn.fetchVersionsIndex(e));if(i?.versions?.length){let o=this.semver.selectBestVersion(i.versions,{range:t,distTags:i.distTags});if(o){let a=await s(o);if(a)return a}else{console.debug("[typebulb] refreshing version cache for",e,"(",t,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(e);let a=await Oe(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=await s(this.semver.selectBestVersion(a.versions,{range:t,distTags:a.distTags}));if(c)return c}}}return s(await this.cdn.resolveExactVersion(`${e}@${t}`))}async effectivePackage(e,t){let n=new N(e),s=n.root(),i=t[s],o=i?await Oe(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as lS,parse as uS}from"es-module-lexer";var Yt=class r{constructor(e,t,n){this.version=e,this.cdn=t,this.peer=n}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))N.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{N.isBare(s)&&t.add(s)};try{await lS;let[s]=uS(e);s.forEach(i=>n(e.slice(i.s,i.e).trim()))}catch{return this.extractImportsSync(e)}return Array.from(t)}async buildImportMap(e,t,n){let s=(await this.extractImports(e)).filter(u=>!n?.has(N.rootOf(u))),i=[...new Set(s.map(N.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),f=this.buildEntries([...s,...l.map(u=>u.name)],a,c);return{importMap:{imports:Object.fromEntries(f)},prefetchUrls:f.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=await this.version.resolveExactForRoot(e,n);if(!s)throw new Error(`Cannot resolve ${n?`${e}@${n}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,n){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let b=s.get(N.rootOf(p));return new N(p).withVersion(b.version).format()},o=new Set([...n.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==N.rootOf(p)).map(N.rootOf)),c=[],l=new Set,f=new Set(e.filter(p=>p===N.rootOf(p))),u=new Set;for(let p of e){let b=N.rootOf(p),m=s.get(b),{isPeerRoot:y,hasPeers:E,isSharedDep:T}=n.get(b),g=a.has(b),w=p!==b,x=!(y||T)&&(g||!E),O=this.singletonDepsOf(m,o),A=w&&f.has(b);A&&u.add(b);let L=A?[...O,b]:O.length?O:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:x,external:L})]),l.add(p)}let d=new Set([...o,...u]);for(let p of d)s.has(p)&&(l.has(p)||c.push([p,this.cdn.buildEsmUrl(i(p),{})]),c.push([`${p}/`,`${Ge}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...rn(e.meta),...Ua(e.meta)])].filter(n=>t.has(n))}};Yt.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as Dd,satisfies as fS,maxSatisfying as Bd,major as dS,valid as pS}from"semver";var Rs=class{cmp(e,t){return e===t?0:Dd(e,t)?1:Dd(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!fS(t,e,{includePrerelease:!0})}selectBestVersion(e,t){if(!e?.length)return;let n=t?.range?.trim()||"*",s=t?.preferStable??!0,i=t?.distTags?.latest;if(i&&e.includes(i)&&this.satisfies(n,i))return i;if(s){let a=Bd(e,n,{includePrerelease:!1});if(a)return a}return Bd(e,n,{includePrerelease:!0})??void 0}majorOf(e){return dS(e)}isExactVersion(e){return pS(e)!==null}},ht=new Rs;function jd(r,e){let t=new tn(r,e),n=new nn(t),s=new sn(r,t,ht);return{packageService:new Yt(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as tp from"fs/promises";import*as de from"path";var Ja=[{name:"es5"},{name:"es2015.core"},{name:"es2015.collection"},{name:"es2015.promise"},{name:"es2015.iterable"},{name:"es2015.symbol"},{name:"es2015.symbol.wellknown"},{name:"es2015.generator"},{name:"es2015.proxy"},{name:"es2015.reflect"},{name:"es2016.array.include"},{name:"es2016.intl"},{name:"es2017.object"},{name:"es2017.string"},{name:"es2017.sharedmemory"},{name:"es2017.typedarrays"},{name:"es2017.date"},{name:"es2017.intl"},{name:"es2018.asynciterable"},{name:"es2018.asyncgenerator"},{name:"es2018.promise"},{name:"es2018.regexp"},{name:"es2018.intl"},{name:"es2019.array"},{name:"es2019.object"},{name:"es2019.string"},{name:"es2019.symbol"},{name:"es2019.intl"},{name:"es2020.bigint"},{name:"es2020.promise"},{name:"es2020.string"},{name:"es2020.sharedmemory"},{name:"es2020.date"},{name:"es2020.number"},{name:"es2020.symbol.wellknown"},{name:"es2020.intl"},{name:"es2021.promise"},{name:"es2021.string"},{name:"es2021.weakref"},{name:"es2021.intl"},{name:"es2022.array"},{name:"es2022.object"},{name:"es2022.error"},{name:"es2022.string"},{name:"es2022.regexp"},{name:"es2022.intl"},{name:"es2023.array"},{name:"es2023.collection"},{name:"es2023.intl",since:"5.5"},{name:"es2024.arraybuffer",since:"5.5"},{name:"es2024.collection",since:"5.5"},{name:"es2024.object",since:"5.5"},{name:"es2024.promise",since:"5.5"},{name:"es2024.regexp",since:"5.5"},{name:"es2024.sharedmemory",since:"5.5"},{name:"es2024.string",since:"5.5"},{name:"esnext.array",since:"5.5"},{name:"esnext.collection"},{name:"esnext.decorators"},{name:"esnext.disposable"},{name:"esnext.error",since:"5.5"},{name:"esnext.float16",since:"5.5"},{name:"esnext.iterator",since:"5.5"},{name:"esnext.object"},{name:"esnext.promise"},{name:"esnext.sharedmemory",since:"5.5"},{name:"esnext.intl"}],Ka=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function Wa(r,e){if(!e)return r.filter(s=>!s.since);let t={"5.0":0,"5.5":1},n=t[e];return r.filter(s=>!s.since||t[s.since]<=n)}var mS=`
628
659
  /**
629
660
  * Get raw data chunk from the Data tab.
630
661
  * @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
@@ -827,9 +858,9 @@ declare const tb: {${mS}${bS}${hS}${vS}${wS}${Ud}${yS}${Jd}${gS}${Kd}
827
858
  */
828
859
  declare const tb: {${Ud}${Jd}${Kd}
829
860
  };
830
- `;var gt=class{constructor(e){this.store=e}async isNegative(e){let t=await _s(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await _s(()=>this.store.get(e)))?.attempts||0)+1;await _s(()=>this.store.set(e,{until:Date.now()+SS(n),attempts:n}))}async clearNegative(e){await _s(()=>this.store.delete(e))}};function SS(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}async function _s(r){try{return await r()}catch{return}}import AS from"p-limit";import{resolve as Hd}from"resolve.exports";var Re={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},Cs=["index.d.ts","index.d.mts"],Ya=/\.d\.(ts|mts|cts)$/i;function Ns(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function Wd(r){return[`${r}.d.ts`,`${r}.d.mts`]}function ze(r){if(!r||r==="./"||r==="/")return[...Cs];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=Wd(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...Wd(`${n}index`)),t}async function Is(r,{retries:e=2,timeoutMs:t=15e3,init:n}={}){for(let s=0;s<=e;s++){let i=new AbortController,o=setTimeout(()=>i.abort(),t);try{let a=await fetch(r,{...n,signal:i.signal});if(kS(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function kS(r){return r===408||r===429||r>=500&&r<600}var Ls=class{constructor(e,t){this.fetchDts=e,this.cdnClient=t}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||Ns(n.url)))return n}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new N({name:e,version:t})),s=await Is(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new N({name:e,version:t??i.version})),version:t}}extractPathFromResult(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.find(t=>typeof t=="string")}async tryUntilSuccess(e,t){for(let n of e){let s=await t(n);if(s)return s}}async resolveFromSelected(e,t){if(e.kind==="types"){let s=mt(e.path);if(!s||s==="/"||s===".")return this.tryUntilSuccess([...Cs],t);if(!Ya.test(s)){let i=await this.tryUntilSuccess(ze(s),t);if(i)return i}return t(s)}let n=ze(e.path);return this.tryUntilSuccess([...Cs,...n],t)}toResolutionResult(e){return{kind:Ya.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(Hd(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(Hd(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=N.parse(e),{pkg:n,baseDir:s}=await this.loadPackageAtVersionedRoot(t.name,t.version)||{};if(!n||!s)return;let i={name:t.name,version:t.version},o=new N(i).format(),a=new N({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=qa(t.subpath),d=this.resolveExportsPath(n,u);if(d){let b=await this.resolveFromSelected(this.toResolutionResult(d),c);if(b)return{...b,resolvedPkg:a}}let p=await this.tryUntilSuccess(ze(u),c);if(p)return{...p,resolvedPkg:a}}let l=n.types??n.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:o}}let f=this.resolveExportsPath(n,".");if(f){let u=await this.resolveFromSelected(this.toResolutionResult(f),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=mt(n),i=new URL(s,e).toString(),o=await this.tryUrls([i]);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}};import{gunzipSync as xS}from"fflate";var $s=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Is(n,{timeoutMs:3e4});if(!s?.ok)return new Map;let i=new Uint8Array(await s.arrayBuffer());return this.extractDtsFiles(i)}getTarballUrl(e,t){return`https://registry.npmjs.org/${e.replace("/","%2F")}/-/${e.split("/").pop()}-${t}.tgz`}normalizeTarPath(e){let t=e.replace(/^package\//,""),n=t.indexOf("/");return n>0?t.substring(n+1):t}extractDtsFiles(e){let t=new Map;try{let n=xS(e),s=new TextDecoder("utf-8"),i=0;for(;i<n.length-512;){let o=n.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),f=o.slice(124,136),u=s.decode(f).trim().replace(/\0/g,""),d=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let b=n.slice(i,i+d);t.set(this.normalizeTarPath(l),s.decode(b))}i+=Math.ceil(d/512)*512}}catch{}return t}};var Ms=class{constructor(e,t,n=new $s){this.cdnClient=e,this.cache=t,this.tarballFetcher=n}typesNameCandidates(e){let t=e.startsWith("@")?e.slice(1).replace("/","__"):e;return t.includes(".")?[t,t.split(".").join("-"),t.split(".").join("")]:[t]}selectTypesVersion(e,t,n){try{if(n){let i=ht.majorOf(n),o=e.filter(a=>ht.majorOf(a)===i);if(o.length)return o.sort((a,c)=>ht.cmp(c,a))[0]}let s=t?.latest;return s&&e.includes(s)?s:e[0]}catch{return e[0]}}subpathCandidates(e){let t=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=ze(e);return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new N(e),s=n.version;if(!s)return;let i;try{i=await this.tarballFetcher.fetchAndExtract(n.name,s)}catch{return}if(!i||i.size===0)return;for(let[a,c]of i.entries()){let l=this.cdnClient.file(e,a);try{await this.cache.setCachedFile(l,c)}catch{}}let o=t.subpath?this.subpathCandidates(t.subpath):["index.d.ts"];for(let a of o){let c=i.get(a);if(c)return{dts:c,url:this.cdnClient.file(e,a),resolvedPkg:t.subpath?new N(t).format():t.name}}}async resolve(e){let t=N.parse(e);if(t.name)for(let n of this.typesNameCandidates(t.name)){let s=`@types/${n}`,i;try{i=await this.cdnClient.fetchVersionsIndex(s)}catch{continue}if(!i?.versions?.length)continue;let o=this.selectTypesVersion(i.versions,i.distTags,t.version),a=await this.fetchFromVersionedRoot(`${s}@${o}`,t);if(a)return a}}};var Ds=class{collectRelativeTypeRefs(e){return this.collectRefs(e).filter(t=>t.startsWith("./")||t.startsWith("../"))}collectBareModuleRefs(e){return this.collectRefs(e).filter(t=>this.isBare(t))}collectRefs(e){let t=e.split(`
861
+ `;var gt=class{constructor(e){this.store=e}async isNegative(e){let t=await _s(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await _s(()=>this.store.get(e)))?.attempts||0)+1;await _s(()=>this.store.set(e,{until:Date.now()+SS(n),attempts:n}))}async clearNegative(e){await _s(()=>this.store.delete(e))}};function SS(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}async function _s(r){try{return await r()}catch{return}}import AS from"p-limit";import{resolve as Hd}from"resolve.exports";var Re={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},Cs=["index.d.ts","index.d.mts"],Ya=/\.d\.(ts|mts|cts)$/i;function Ns(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function Wd(r){return[`${r}.d.ts`,`${r}.d.mts`]}function ze(r){if(!r||r==="./"||r==="/")return[...Cs];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=Wd(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...Wd(`${n}index`)),t}async function Is(r,{retries:e=2,timeoutMs:t=15e3,init:n}={}){for(let s=0;s<=e;s++){let i=new AbortController,o=setTimeout(()=>i.abort(),t);try{let a=await fetch(r,{...n,signal:i.signal});if(kS(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function kS(r){return r===408||r===429||r>=500&&r<600}var Ls=class{constructor(e,t){this.fetchDts=e,this.cdnClient=t}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||Ns(n.url)))return n}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new N({name:e,version:t})),s=await Is(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new N({name:e,version:t??i.version})),version:t}}extractPathFromResult(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.find(t=>typeof t=="string")}async tryUntilSuccess(e,t){for(let n of e){let s=await t(n);if(s)return s}}async resolveFromSelected(e,t){if(e.kind==="types"){let s=mt(e.path);if(!s||s==="/"||s===".")return this.tryUntilSuccess([...Cs],t);if(!Ya.test(s)){let i=await this.tryUntilSuccess(ze(s),t);if(i)return i}return t(s)}let n=ze(e.path);return this.tryUntilSuccess([...Cs,...n],t)}toResolutionResult(e){return{kind:Ya.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(Hd(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(Hd(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=N.parse(e),{pkg:n,baseDir:s}=await this.loadPackageAtVersionedRoot(t.name,t.version)||{};if(!n||!s)return;let i={name:t.name,version:t.version},o=new N(i).format(),a=new N({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=qa(t.subpath),d=this.resolveExportsPath(n,u);if(d){let b=await this.resolveFromSelected(this.toResolutionResult(d),c);if(b)return{...b,resolvedPkg:a}}let p=await this.tryUntilSuccess(ze(u),c);if(p)return{...p,resolvedPkg:a}}let l=n.types??n.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:o}}let f=this.resolveExportsPath(n,".");if(f){let u=await this.resolveFromSelected(this.toResolutionResult(f),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=mt(n),i=new URL(s,e).toString(),o=await this.tryUrls([i]);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}};import{gunzipSync as xS}from"fflate";var Ms=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Is(n,{timeoutMs:3e4});if(!s?.ok)return new Map;let i=new Uint8Array(await s.arrayBuffer());return this.extractDtsFiles(i)}getTarballUrl(e,t){return`https://registry.npmjs.org/${e.replace("/","%2F")}/-/${e.split("/").pop()}-${t}.tgz`}normalizeTarPath(e){let t=e.replace(/^package\//,""),n=t.indexOf("/");return n>0?t.substring(n+1):t}extractDtsFiles(e){let t=new Map;try{let n=xS(e),s=new TextDecoder("utf-8"),i=0;for(;i<n.length-512;){let o=n.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),f=o.slice(124,136),u=s.decode(f).trim().replace(/\0/g,""),d=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let b=n.slice(i,i+d);t.set(this.normalizeTarPath(l),s.decode(b))}i+=Math.ceil(d/512)*512}}catch{}return t}};var $s=class{constructor(e,t,n=new Ms){this.cdnClient=e,this.cache=t,this.tarballFetcher=n}typesNameCandidates(e){let t=e.startsWith("@")?e.slice(1).replace("/","__"):e;return t.includes(".")?[t,t.split(".").join("-"),t.split(".").join("")]:[t]}selectTypesVersion(e,t,n){try{if(n){let i=ht.majorOf(n),o=e.filter(a=>ht.majorOf(a)===i);if(o.length)return o.sort((a,c)=>ht.cmp(c,a))[0]}let s=t?.latest;return s&&e.includes(s)?s:e[0]}catch{return e[0]}}subpathCandidates(e){let t=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=ze(e);return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new N(e),s=n.version;if(!s)return;let i;try{i=await this.tarballFetcher.fetchAndExtract(n.name,s)}catch{return}if(!i||i.size===0)return;for(let[a,c]of i.entries()){let l=this.cdnClient.file(e,a);try{await this.cache.setCachedFile(l,c)}catch{}}let o=t.subpath?this.subpathCandidates(t.subpath):["index.d.ts"];for(let a of o){let c=i.get(a);if(c)return{dts:c,url:this.cdnClient.file(e,a),resolvedPkg:t.subpath?new N(t).format():t.name}}}async resolve(e){let t=N.parse(e);if(t.name)for(let n of this.typesNameCandidates(t.name)){let s=`@types/${n}`,i;try{i=await this.cdnClient.fetchVersionsIndex(s)}catch{continue}if(!i?.versions?.length)continue;let o=this.selectTypesVersion(i.versions,i.distTags,t.version),a=await this.fetchFromVersionedRoot(`${s}@${o}`,t);if(a)return a}}};var Ds=class{collectRelativeTypeRefs(e){return this.collectRefs(e).filter(t=>t.startsWith("./")||t.startsWith("../"))}collectBareModuleRefs(e){return this.collectRefs(e).filter(t=>this.isBare(t))}collectRefs(e){let t=e.split(`
831
862
  `).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
832
- `),n=new Set;for(let s of t.matchAll(/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/g))n.add(s[2]);for(let s of t.matchAll(/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/g))n.add(s[1]);return Array.from(n)}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};var Vd="file:///node_modules",Bs=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${Vd}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=mt(t);return`${Vd}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as ES}from"lru-cache";function Yd(r){let e=new ES({ttl:Re.negativeTtlMs,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s)||e.has(s))return;let i=await r.getCachedFile(s);if(i)return{dts:i,url:s};let o=t.get(s);if(o)return o;let a=(async()=>{let c=await fetch(s,{cache:"no-store"});if(!c.ok){c.status===404&&(e.set(s,!0),await r.recordNegative(s));return}let l=await c.text(),f=c.url||s;return await r.clearNegative(s),await r.setCachedFile(f,l),{dts:l,url:f}})();return t.set(s,a),await a.finally(()=>t.delete(s))}catch{return}}}var on=class{constructor(e){this.inFlight=new Map,this.scanner=new Ds,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=Yd(e.cache),this.typescriptProvider=new Ls(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Ms(e.cdnClient,e.cache),this.virtualFs=new Bs}withInFlight(e,t){let n=this.inFlight.get(e);if(n)return n;let s=t().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}pushFileIfNew(e,t,n){e.some(s=>s.path===t)||e.push({path:t,content:n})}createStubDef(e){let t=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:t,files:[{path:t,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:t}]}}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}async fetchRootDts(e,t){let{effectivePackage:n,root:s,pinned:i}=await this.versionResolver.effectivePackage(e,t),o=await this.cache.getCachedDts(n);if(o?.content){let c=o.url??this.cdnClient.file(i?`${s}@${i}`:s,"index.d.ts");return{dts:o.content,url:c,resolvedPkg:n}}let a;try{a=await this.fetchViaProviders(n)}catch{return}if(!(!a?.dts||!a.url)&&new N(n).subpath===new N(a.resolvedPkg||n).subpath){try{await this.cache.setCachedDts(n,a.dts,a.url)}catch{}return a}}extractPackageRootUrl(e){let t=e.pathname.match(/^(.+@[^/]+\/)/);return t?new URL(t[1],e.origin):new URL("./",e)}toVirtualPath(e,t,n){let s=t.pathname.startsWith(e.pathname)?t.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(t.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(n,s)}computeEntryPath(e,t){if(!e)return{mainPath:this.virtualFs.pathForMain(t),packageRootUrl:void 0};let n=new URL(e),s=this.extractPackageRootUrl(n);return{mainPath:this.toVirtualPath(s,n,t),packageRootUrl:s}}async expandRelativeRefs(e,t,n,s,i=new Set,o){if(!i.has(t)&&(i.add(t),!(i.size>Re.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,Re.maxRelativeTypeRefs);for(let f of l)await this.tryRelativeRef(f,c,o,n,s,i)}catch{}}async tryRelativeRef(e,t,n,s,i,o){try{let a=new URL(e,t),c=a.pathname+a.search,l=Ns(c)?[c]:ze(c);for(let f of l){let d=new URL(f,a).toString();if(o.has(d))return;let p=await this.fetchDts(d);if(p?.dts){let b=this.toVirtualPath(n,new URL(p.url),s);this.pushFileIfNew(i,b,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new N(e).name!==new N(t).name}ambientlyDeclares(e,t){if(/^(?:import|export)\b/m.test(e))return!1;for(let n of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=n[1];if(s===t||s.endsWith("/*")&&t.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,t){let n=e.find(s=>s.path===t);n&&(n.ambient=!0)}async prefetchBareDeps(e,t,n,s,i){try{let o=this.scanner.collectBareModuleRefs(e).slice(0,Re.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=AS(Re.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Re.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let f=this.scanner.collectBareModuleRefs(a.dts).slice(0,Re.maxBareDeps).filter(u=>!i.has(u));for(let u of f)await this.prefetchBareDepsRecursive(u,t,n,s-1,i,o)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),i=n?[...s,...n]:s;return(await Promise.all(i.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=new N(e),i=await this.fetchRootDts(e,t)??(s.subpath?await this.fetchRootDts(s.name,t):void 0);return i?this.buildDefFromContent(e,i,i.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,n,s){let{dts:i,url:o,resolvedPkg:a}=t,c=new N(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:f,packageRootUrl:u}=this.computeEntryPath(o,l),d=[{path:f,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,d,void 0,u);let b=d.map(T=>T.content).join(`
863
+ `),n=new Set;for(let s of t.matchAll(/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/g))n.add(s[2]);for(let s of t.matchAll(/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/g))n.add(s[1]);return Array.from(n)}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};var Vd="file:///node_modules",Bs=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${Vd}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=mt(t);return`${Vd}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as ES}from"lru-cache";function Yd(r){let e=new ES({ttl:Re.negativeTtlMs,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s)||e.has(s))return;let i=await r.getCachedFile(s);if(i)return{dts:i,url:s};let o=t.get(s);if(o)return o;let a=(async()=>{let c=await fetch(s,{cache:"no-store"});if(!c.ok){c.status===404&&(e.set(s,!0),await r.recordNegative(s));return}let l=await c.text(),f=c.url||s;return await r.clearNegative(s),await r.setCachedFile(f,l),{dts:l,url:f}})();return t.set(s,a),await a.finally(()=>t.delete(s))}catch{return}}}var on=class{constructor(e){this.inFlight=new Map,this.scanner=new Ds,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=Yd(e.cache),this.typescriptProvider=new Ls(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new $s(e.cdnClient,e.cache),this.virtualFs=new Bs}withInFlight(e,t){let n=this.inFlight.get(e);if(n)return n;let s=t().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}pushFileIfNew(e,t,n){e.some(s=>s.path===t)||e.push({path:t,content:n})}createStubDef(e){let t=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:t,files:[{path:t,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:t}]}}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}async fetchRootDts(e,t){let{effectivePackage:n,root:s,pinned:i}=await this.versionResolver.effectivePackage(e,t),o=await this.cache.getCachedDts(n);if(o?.content){let c=o.url??this.cdnClient.file(i?`${s}@${i}`:s,"index.d.ts");return{dts:o.content,url:c,resolvedPkg:n}}let a;try{a=await this.fetchViaProviders(n)}catch{return}if(!(!a?.dts||!a.url)&&new N(n).subpath===new N(a.resolvedPkg||n).subpath){try{await this.cache.setCachedDts(n,a.dts,a.url)}catch{}return a}}extractPackageRootUrl(e){let t=e.pathname.match(/^(.+@[^/]+\/)/);return t?new URL(t[1],e.origin):new URL("./",e)}toVirtualPath(e,t,n){let s=t.pathname.startsWith(e.pathname)?t.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(t.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(n,s)}computeEntryPath(e,t){if(!e)return{mainPath:this.virtualFs.pathForMain(t),packageRootUrl:void 0};let n=new URL(e),s=this.extractPackageRootUrl(n);return{mainPath:this.toVirtualPath(s,n,t),packageRootUrl:s}}async expandRelativeRefs(e,t,n,s,i=new Set,o){if(!i.has(t)&&(i.add(t),!(i.size>Re.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,Re.maxRelativeTypeRefs);for(let f of l)await this.tryRelativeRef(f,c,o,n,s,i)}catch{}}async tryRelativeRef(e,t,n,s,i,o){try{let a=new URL(e,t),c=a.pathname+a.search,l=Ns(c)?[c]:ze(c);for(let f of l){let d=new URL(f,a).toString();if(o.has(d))return;let p=await this.fetchDts(d);if(p?.dts){let b=this.toVirtualPath(n,new URL(p.url),s);this.pushFileIfNew(i,b,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new N(e).name!==new N(t).name}ambientlyDeclares(e,t){if(/^(?:import|export)\b/m.test(e))return!1;for(let n of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=n[1];if(s===t||s.endsWith("/*")&&t.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,t){let n=e.find(s=>s.path===t);n&&(n.ambient=!0)}async prefetchBareDeps(e,t,n,s,i){try{let o=this.scanner.collectBareModuleRefs(e).slice(0,Re.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=AS(Re.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Re.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let f=this.scanner.collectBareModuleRefs(a.dts).slice(0,Re.maxBareDeps).filter(u=>!i.has(u));for(let u of f)await this.prefetchBareDepsRecursive(u,t,n,s-1,i,o)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),i=n?[...s,...n]:s;return(await Promise.all(i.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=new N(e),i=await this.fetchRootDts(e,t)??(s.subpath?await this.fetchRootDts(s.name,t):void 0);return i?this.buildDefFromContent(e,i,i.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,n,s){let{dts:i,url:o,resolvedPkg:a}=t,c=new N(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:f,packageRootUrl:u}=this.computeEntryPath(o,l),d=[{path:f,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,d,void 0,u);let b=d.map(T=>T.content).join(`
833
864
  `);await this.prefetchBareDeps(b,l,d,p,s);let m=c.format(),y=e===m?[e]:[e,m],E=y.some(T=>this.ambientlyDeclares(i,T));return E?this.markFileAmbient(d,f):p.push(...y.map(T=>({module:T,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:E}}};import*as Xe from"fs/promises";import*as Ce from"path";import*as Qd from"os";import*as Ga from"fs/promises";import*as Gd from"crypto";function fe(r){return Gd.createHash("sha1").update(r).digest("hex")}async function _e(r){try{return JSON.parse(await Ga.readFile(r,"utf8"))}catch{return}}async function js(r){try{return await Ga.readFile(r,"utf8")}catch{return}}var zd=1,Qe=Ce.join(Qd.homedir(),".typebulb","cache"),an=Ce.join(Qe,"packages"),cn=Ce.join(Qe,"proxy"),Fs=Ce.join(Qe,"dts"),TS=Ce.join(Qe,"emit"),za;function q(){return za||(za=PS()),za}function qs(r,e){return Ce.join(TS,fe(r),e)}async function PS(){await Xe.mkdir(Qe,{recursive:!0});let r=Ce.join(Qe,"version.json");if((await _e(r))?.version===zd)return;let t=await Xe.readdir(Qe).catch(()=>[]);await Promise.all(t.map(n=>Xe.rm(Ce.join(Qe,n),{recursive:!0,force:!0}))),await Xe.writeFile(r,JSON.stringify({version:zd})+`
834
865
  `,"utf8")}import*as Ze from"fs/promises";import*as Xd from"path";async function oe(r,e){await Ze.mkdir(Xd.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await Ze.writeFile(t,e,"utf8"),await Ze.rename(t,r).catch(async n=>{throw await Ze.rm(t,{force:!0}).catch(()=>{}),n})}var Gt=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=_e(this.filePath).then(e=>(this.mem=new Map(Object.entries(e??{})),this.mem))),this.loadPromise)}async get(e){return(await this.load()).get(e)}async set(e,t){let n=await this.load();n.set(e,t),await this.persist(n)}async delete(e){let t=await this.load();t.delete(e)&&await this.persist(t)}async persist(e){await oe(this.filePath,JSON.stringify(Object.fromEntries(e)))}};var Qa=de.join(an,"indexes"),Zd=de.join(an,"pinned"),OS=de.join(an,"meta"),RS=de.join(an,"negative.json"),Js=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new gt(new Gt(RS));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await q();let s=await js(de.join(Zd,fe(n)+".txt"));return this.pinnedMem.set(n,s),s}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await q(),await oe(de.join(Zd,fe(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await q();let t=await _e(de.join(Qa,Us(e)+".json"));return this.indexMem.set(e,t),t}async setIndex(e,t,n){let s={versions:t,distTags:n,updatedAt:Date.now()};this.indexMem.set(e,s),await q(),await oe(de.join(Qa,Us(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await tp.rm(de.join(Qa,Us(e)+".json"),{force:!0})}async isNegative(e){return await q(),this.negativeCache.isNegative(e)}async recordNegative(e){await q(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,t){let n=`${e}@${t}`;if(this.metaMem.has(n))return this.metaMem.get(n);await q();let s=await _e(ep(e,t));return this.metaMem.set(n,s),s}async setMeta(e,t,n,s,i){let o={dependencies:n,peerDependencies:s,peerDependenciesMeta:i,updatedAt:Date.now()};this.metaMem.set(`${e}@${t}`,o),await q(),await oe(ep(e,t),JSON.stringify(o))}};function ep(r,e){return de.join(OS,Us(r),encodeURIComponent(e)+".json")}function Us(r){return r.replace(/\//g,"__")}var rp={async getJson(r){try{let e=await fetch(r,{redirect:"follow"});return e.ok?await e.json():void 0}catch{return}},async head(r){try{let e=await fetch(r,{method:"HEAD",redirect:"follow"});return{ok:e.ok,url:e.url}}catch{return}}};var _S=new Js,{packageService:Ks,versionResolver:np,cdnClient:sp,peerResolver:fR}=jd(_S,rp);var ip=`
835
866
  (() => {
@@ -1338,24 +1369,24 @@ globalThis.__tbEntryRan = true; /* load-failure backstop \u2014 see embedProtoco
1338
1369
  }
1339
1370
  });
1340
1371
  })();
1341
- </script>`;function NS(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}import*as Gs from"fs/promises";import*as Ys from"path";import{existsSync as ap,readFileSync as IS}from"fs";import{execFile as LS}from"child_process";import{promisify as $S}from"util";import{satisfies as MS}from"semver";var DS=$S(LS);async function zs(r,e,t){let s=r.map(o=>BS(o,t)).filter(o=>!jS(o,e));if(s.length===0)return;await Gs.mkdir(e,{recursive:!0});let i=Ys.join(e,"package.json");ap(i)||await Gs.writeFile(i,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${s.join(", ")}`),await DS("npm",["install","--no-audit","--no-fund",...s],{cwd:e,shell:!0})}function BS(r,e){if(!e||N.parse(r).version)return r;let t=e[r];return t?`${r}@${t}`:r}function jS(r,e){let{name:t,version:n}=N.parse(r),s=Ys.join(e,"node_modules",t);if(!ap(s))return!1;if(!n)return!0;try{let i=JSON.parse(IS(Ys.join(s,"package.json"),"utf-8")).version;return MS(i,n)}catch{return!1}}function Qs(r){let e=new Set,t=/\bimport\s+(?:[\s\S]*?\s+from\s+)?['"]([^./][^'"]*)['"]/g,n;for(;n=t.exec(r);){let s=n[1];s.includes(":")||e.add(N.rootOf(s))}return[...e]}er();oi();nr();async function hp(r){let e=wt(r.provider,r.model);if(typeof e=="string")throw new Error(e);let t=await vt(e,r);if(!t.ok){let n=await ln(t,e.protocol);throw new Error(n.message)}return{response:t,protocol:e.protocol}}async function VS(r){let{response:e,protocol:t}=await hp(r);return{text:await bt(e,t)}}async function*YS(r){let{response:e,protocol:t}=await hp(r);yield*Zt(e,t)}function gp(){let r=Object.assign(VS,{stream:YS});globalThis.tb=Object.freeze({ai:r,models:()=>Ne(),hasOwnKeys:ii,mode:"local"})}async function yp(r){let t=(await et.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?ai.join(r,t):null}async function he(r){let e=await et.readFile(r,"utf-8"),t=Ae(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=Ht(t);return{bulb:n,config:Rl(n.config),warnings:El(e)}}async function un(r,e,t,n){let s=ja(r,{serverOnly:!0});if(s.error)throw new Error(`Server compilation error: ${s.error}`);let i=s.code;t&&(i=await gl(i,t));let o=ai.join(e,".typebulb");await et.mkdir(o,{recursive:!0});let a=Qs(i);a.length>0&&await zs(a,o,n);let c=ai.join(o,"server.mjs");return await et.writeFile(c,i,"utf-8"),gp(),await import(`${GS(c).href}?t=${Date.now()}`)}async function cc(r,e,t,n,s){let{bulb:i,config:o}=await he(r),a=Rd(i.data);Id(i.code,o.dependencies??{});let c=ja(i.code,{jsxImportSource:o.ts?.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await Ks.buildImportMap(c.code,o.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let f=op({name:i.name,code:c.code,css:i.css,html:i.html,data:a,insight:i.insight,importMap:l,watch:e}),u=null;return i.server&&t&&(u=await un(i.server,s,n,o.dependencies)),{html:f,bulb:i,serverExports:u}}Xr();fn();var vp=new Set(["claude","pi"]);function Sp(r){return vp.has(r)}function ir(){return[...vp]}import*as tt from"path";import{spawn as bk,execSync as wk}from"child_process";import{createRequire as vk}from"module";import{existsSync as Sk}from"fs";import*as ee from"fs/promises";import*as X from"path";import*as or from"path";var sk=or.join(Fs,"pkg"),ik=or.join(Fs,"files"),ok=or.join(Fs,"negative.json"),fi=class{pkgMem=new Map;fileMem=new Map;negativeCache=new gt(new Gt(ok));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await q();let t=await _e(kp(e));return this.pkgMem.set(e,t),t}async setCachedDts(e,t,n){let s={content:t,url:n};this.pkgMem.set(e,s),await ui(async()=>{await q(),await oe(kp(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await q();let t=await js(xp(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await ui(async()=>{await q(),await oe(xp(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await ui(async()=>{await q(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return ui(()=>this.negativeCache.clearNegative(e))}};async function ui(r){try{await r()}catch{}}function kp(r){return or.join(sk,fe(r)+".json")}function xp(r){return or.join(ik,fe(r)+".txt")}var dc;function ak(){return dc||(dc=new on({cache:new fi,cdnClient:sp,packageService:Ks,versionResolver:np})),dc}var Ep="file:///node_modules/";async function Ap(r){let e=qs(r.emitKey,"typecheck");await q(),await ee.rm(e,{recursive:!0,force:!0}),await ee.mkdir(e,{recursive:!0});let t=fk(r.jsxImportSource,r.dependencies),n=await ak().resolve(r.code,r.dependencies,t),s=r.local?.name,i=s?n.filter(f=>f.pkg!==s):n,o=new Set;for(let f of i)for(let u of f.files){let d=di(u.path);if(!d||o.has(d))continue;o.add(d);let p=X.join(e,"node_modules",d);await ee.mkdir(X.dirname(p),{recursive:!0}),await ee.writeFile(p,u.content,"utf8")}let a={};for(let f of i)for(let u of f.shims){let d=di(u.path);d&&(a[u.module]=[`./node_modules/${d}`])}for(let f of i){if(f.ambient)continue;let u=di(f.mainPath);u&&(a[f.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let f of i)for(let u of f.files){if(!u.ambient)continue;let d=di(u.path);d&&c.add(`node_modules/${d}`)}if(r.local){delete a[r.local.name];let f=await dk(r.local,e);f?a[r.local.name]=[`./node_modules/${r.local.name}/${f}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=ck(r.jsxImportSource,a,[...c]);return await ee.writeFile(X.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
1372
+ </script>`;function NS(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}import*as Gs from"fs/promises";import*as Ys from"path";import{existsSync as ap,readFileSync as IS}from"fs";import{execFile as LS}from"child_process";import{promisify as MS}from"util";import{satisfies as $S}from"semver";var DS=MS(LS);async function zs(r,e,t){let s=r.map(o=>BS(o,t)).filter(o=>!jS(o,e));if(s.length===0)return;await Gs.mkdir(e,{recursive:!0});let i=Ys.join(e,"package.json");ap(i)||await Gs.writeFile(i,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${s.join(", ")}`),await DS("npm",["install","--no-audit","--no-fund",...s],{cwd:e,shell:!0})}function BS(r,e){if(!e||N.parse(r).version)return r;let t=e[r];return t?`${r}@${t}`:r}function jS(r,e){let{name:t,version:n}=N.parse(r),s=Ys.join(e,"node_modules",t);if(!ap(s))return!1;if(!n)return!0;try{let i=JSON.parse(IS(Ys.join(s,"package.json"),"utf-8")).version;return $S(i,n)}catch{return!1}}function Qs(r){let e=new Set,t=/\bimport\s+(?:[\s\S]*?\s+from\s+)?['"]([^./][^'"]*)['"]/g,n;for(;n=t.exec(r);){let s=n[1];s.includes(":")||e.add(N.rootOf(s))}return[...e]}er();oi();nr();async function hp(r){let e=wt(r.provider,r.model);if(typeof e=="string")throw new Error(e);let t=await vt(e,r);if(!t.ok){let n=await ln(t,e.protocol);throw new Error(n.message)}return{response:t,protocol:e.protocol}}async function VS(r){let{response:e,protocol:t}=await hp(r);return{text:await bt(e,t)}}async function*YS(r){let{response:e,protocol:t}=await hp(r);yield*Zt(e,t)}function gp(){let r=Object.assign(VS,{stream:YS});globalThis.tb=Object.freeze({ai:r,models:()=>Ne(),hasOwnKeys:ii,mode:"local"})}async function yp(r){let t=(await et.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?ai.join(r,t):null}async function he(r){let e=await et.readFile(r,"utf-8"),t=Ae(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=Ht(t);return{bulb:n,config:Rl(n.config),warnings:El(e)}}async function un(r,e,t,n){let s=ja(r,{serverOnly:!0});if(s.error)throw new Error(`Server compilation error: ${s.error}`);let i=s.code;t&&(i=await gl(i,t));let o=ai.join(e,".typebulb");await et.mkdir(o,{recursive:!0});let a=Qs(i);a.length>0&&await zs(a,o,n);let c=ai.join(o,"server.mjs");return await et.writeFile(c,i,"utf-8"),gp(),await import(`${GS(c).href}?t=${Date.now()}`)}async function cc(r,e,t,n,s){let{bulb:i,config:o}=await he(r),a=Rd(i.data);Id(i.code,o.dependencies??{});let c=ja(i.code,{jsxImportSource:o.ts?.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await Ks.buildImportMap(c.code,o.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let f=op({name:i.name,code:c.code,css:i.css,html:i.html,data:a,insight:i.insight,importMap:l,watch:e}),u=null;return i.server&&t&&(u=await un(i.server,s,n,o.dependencies)),{html:f,bulb:i,serverExports:u}}Xr();fn();var vp=new Set(["claude","pi"]);function Sp(r){return vp.has(r)}function ir(){return[...vp]}import*as tt from"path";import{spawn as bk,execSync as wk}from"child_process";import{createRequire as vk}from"module";import{existsSync as Sk}from"fs";import*as ee from"fs/promises";import*as X from"path";import*as or from"path";var sk=or.join(Fs,"pkg"),ik=or.join(Fs,"files"),ok=or.join(Fs,"negative.json"),fi=class{pkgMem=new Map;fileMem=new Map;negativeCache=new gt(new Gt(ok));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await q();let t=await _e(kp(e));return this.pkgMem.set(e,t),t}async setCachedDts(e,t,n){let s={content:t,url:n};this.pkgMem.set(e,s),await ui(async()=>{await q(),await oe(kp(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await q();let t=await js(xp(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await ui(async()=>{await q(),await oe(xp(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await ui(async()=>{await q(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return ui(()=>this.negativeCache.clearNegative(e))}};async function ui(r){try{await r()}catch{}}function kp(r){return or.join(sk,fe(r)+".json")}function xp(r){return or.join(ik,fe(r)+".txt")}var dc;function ak(){return dc||(dc=new on({cache:new fi,cdnClient:sp,packageService:Ks,versionResolver:np})),dc}var Ep="file:///node_modules/";async function Ap(r){let e=qs(r.emitKey,"typecheck");await q(),await ee.rm(e,{recursive:!0,force:!0}),await ee.mkdir(e,{recursive:!0});let t=fk(r.jsxImportSource,r.dependencies),n=await ak().resolve(r.code,r.dependencies,t),s=r.local?.name,i=s?n.filter(f=>f.pkg!==s):n,o=new Set;for(let f of i)for(let u of f.files){let d=di(u.path);if(!d||o.has(d))continue;o.add(d);let p=X.join(e,"node_modules",d);await ee.mkdir(X.dirname(p),{recursive:!0}),await ee.writeFile(p,u.content,"utf8")}let a={};for(let f of i)for(let u of f.shims){let d=di(u.path);d&&(a[u.module]=[`./node_modules/${d}`])}for(let f of i){if(f.ambient)continue;let u=di(f.mainPath);u&&(a[f.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let f of i)for(let u of f.files){if(!u.ambient)continue;let d=di(u.path);d&&c.add(`node_modules/${d}`)}if(r.local){delete a[r.local.name];let f=await dk(r.local,e);f?a[r.local.name]=[`./node_modules/${r.local.name}/${f}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=ck(r.jsxImportSource,a,[...c]);return await ee.writeFile(X.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
1342
1373
  `,"utf8"),await ee.writeFile(X.join(e,"code.tsx"),r.code,"utf8"),await ee.writeFile(X.join(e,"tb.d.ts"),Ha,"utf8"),{dir:e}}var pc={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function ck(r,e,t=[]){return{compilerOptions:{...pc,lib:lk([...Ja,...Ka]),jsx:"react-jsx",jsxImportSource:r??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function lk(r){return Wa(r).map(e=>uk(e.name))}function uk(r){return r.split(".").map(e=>/^es\d+$/i.test(e)?e.toUpperCase():e==="dom"?"DOM":e==="esnext"?"ESNext":e.charAt(0).toUpperCase()+e.slice(1)).join(".")}function fk(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function di(r){if(!r.startsWith(Ep))return;let e=r.slice(Ep.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function dk(r,e){if(!r.typesAbs)return;let t=X.dirname(r.typesAbs),n=X.join(e,"node_modules",r.name);for(let s of await pk(t)){let i=X.join(n,X.relative(t,s));await ee.mkdir(X.dirname(i),{recursive:!0}),await ee.copyFile(s,i)}return X.basename(r.typesAbs)}async function pk(r){let e=[];async function t(n){let s=await ee.readdir(n,{withFileTypes:!0});for(let i of s){let o=X.join(n,i.name);i.isDirectory()?await t(o):/\.d\.ts(\.map)?$/.test(i.name)&&e.push(o)}}return await t(r),e}import*as ae from"fs/promises";import*as Le from"path";import{existsSync as mk}from"fs";var hk="^22";async function Tp(r){let e=qs(r.emitKey,"typecheck-server");await q(),await ae.rm(e,{recursive:!0,force:!0}),await ae.mkdir(e,{recursive:!0});let t=Le.join(r.bulbDir,".typebulb"),n=Qs(r.server).filter(o=>o!==r.local?.name);await zs([`@types/node@${hk}`,...n],t,r.dependencies);let s=Le.join(t,"node_modules"),i=Le.join(e,"node_modules");return await yk(s,i),await ae.writeFile(Le.join(e,"server.ts"),r.server,"utf8"),await ae.writeFile(Le.join(e,"tb.d.ts"),Va,"utf8"),await ae.writeFile(Le.join(e,"tsconfig.json"),JSON.stringify(gk(r.local),null,2)+`
1343
1374
  `,"utf8"),{dir:e}}function gk(r){let e={...pc,lib:["ES2023"],types:["node"]};if(r?.typesAbs){let t=i=>i.replace(/\\/g,"/"),n=t(Le.dirname(r.typesAbs)),s=t(r.typesAbs).replace(/\.d\.ts$/,"");e.paths={[r.name]:[s],[`${r.name}/*`]:[`${n}/*`]}}return{compilerOptions:e,include:["server.ts","tb.d.ts"]}}async function yk(r,e){if(!mk(r)){await ae.mkdir(e,{recursive:!0});return}await ae.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await ae.symlink(r,e,t)}Os();async function Op(r,e){let{bulb:t,config:n,warnings:s}=await he(r);!t.code&&!t.server&&(console.error("Bulb has neither **code.tsx** nor **server.ts**; nothing to check."),process.exit(1));let i=!1;for(let l of s)console.log(`structure ${l}`);s.length&&(i=!0),t.code&&(i=Pp(Zr(t.code,{target:"client",dependencies:n.dependencies??{}}),"client")||i),t.server&&(i=Pp(Zr(t.server,{target:"server"}),"server")||i);let o=Ek([process.cwd(),tt.dirname(r)]);if(!o){let l=tt.relative(process.cwd(),r)||r;console.error("check: TypeScript not found \u2014 install it once, then re-run:"),console.error(" npm i -g typescript"),console.error(` typebulb check ${l}`),process.exit(2)}let a=[];if(t.code){let{dir:l}=await Ap({code:t.code,dependencies:n.dependencies??{},jsxImportSource:n.ts?.jsxImportSource,emitKey:r,local:e});a.push({role:"client",dir:l})}if(t.server){let{dir:l}=await Tp({server:t.server,bulbDir:tt.dirname(r),emitKey:r,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:n.dependencies});a.push({role:"server",dir:l})}for(let{role:l,dir:f}of a){let{stdout:u,exitCode:d}=await kk(o,f);for(let p of u.split(/\r?\n/))p.trim()&&console.log(`${l} ${p}`);d!==0&&(i=!0)}i&&process.exit(1);let c=[t.code&&"code.tsx",t.server&&"server.ts"].filter(Boolean).join(", ");console.error(`\u2713 no issues (${c})`)}function Pp(r,e){for(let t of r)for(let n of t.message.split(`
1344
- `))console.log(`${e} ${n}`);return r.length>0}function kk(r,e){return new Promise(t=>{let n=bk(process.execPath,[r,"--noEmit"],{cwd:e}),s="";n.stdout?.on("data",i=>{s+=i.toString()}),n.stderr?.on("data",i=>{s+=i.toString()}),n.on("close",i=>t({stdout:s,exitCode:i??1}))})}var xk=vk(import.meta.url);function Ek(r){let e=n=>{try{let s=xk.resolve("typescript/package.json",{paths:n}),i=tt.join(tt.dirname(s),"lib","tsc.js");return Sk(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=wk("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}pi();fn();async function Rp(r,e){let{bulb:t}=await he(r),n=ar(t);if(St(r)){console.log("remembered-trusted \u2014 runs with filesystem / AI / server.ts automatically (`typebulb untrust` to revoke)."),n&&console.log(` (it uses ${n})`);return}n?(console.log(`This bulb appears to use ${n}; it runs Restricted unless you grant trust:`),console.log(` ${e}`)):console.log("No privileged capability detected \u2014 runs Restricted by default. (A clean scan is a hint, not a guarantee.)")}fn();import*as dn from"path";async function _p(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=fc();if(!n.length){console.log("No bulbs are remembered as trusted.");return}console.log("Trusted bulbs (run with fs/AI/server.ts without --trust):");for(let s of n)console.log(` ${s}`);return}let t=dn.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),sr(t,e),console.log(e?`Trusted ${dn.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${dn.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}$e();import*as km from"readline";xi();$c();var yn={claude:()=>new ur,pi:()=>new pr};function wm(){for(let r of Object.values(yn))try{r().ensureHarnessSupport()}catch{}}function bn(){for(let r of Object.keys(yn))try{if(yn[r]().detectsSelf())return r}catch{}}function vm(r){let e=ir(),t=new Map(e.filter(i=>yn[i]).map(i=>[i,yn[i]()]));for(let[i,o]of t)if(o.detectsSelf())return{name:i};let n=[...t].filter(([,i])=>i.listSessionFiles(r).length>0).map(([i])=>i);if(n.length===1)return{name:n[0]};if(n.length>=2)return{ambiguous:n};let s=[...t].filter(([,i])=>i.detectsInstalled()).map(([i])=>i);return s.length===1?{name:s[0]}:s.length>=2?{ambiguous:s}:{name:e[0]}}Ti();function Mc(r){let e=t=>n=>r?`\x1B[${t}m${n}\x1B[0m`:n;return{lit:e("38;5;70"),litLink:e("4;38;5;70"),brand:e("38;5;135")}}async function xm(r){let e=vm(process.cwd());if("ambiguous"in e){let t=await Qx(r,e.ambiguous);return t?Sm(r,t):Xx(r,e.ambiguous)}return Sm(r,e.name)}async function Sm(r,e){let t,n;try{t=await Up(e)}catch(f){n=f instanceof Error?f.message:String(f)}let{lit:s,litLink:i,brand:o}=Mc(process.stdout.isTTY===!0),a=[" Read the authoring skill before writing a bulb:",` \u2022 ${s("npx typebulb skill")} \u2014 assembles one SKILL.md`," \u2022 or, open its parts:",` ${s(fr())}`,` ${s(At())}`],c=t?[" Agent mirror is live\u{1F4A1}",` ${s("\u25CF")} ${i(t.url)}`," Embedded bulbs render live here."," Agents:",` Reusable app/tool \u2192 write a ${s(".bulb.md")}`," Show something inline \u2192 embed a bulb"," background a wait for its render verdict:",` \u2022 ${s('typebulb wait agent --match "[embed <name>"')}`,...a," End your reply with the mirror link above"," \u2022 easy to miss the link mid-message"]:[` The mirror did not start (${n})`,` \u25CF Start it manually: ${s(`npx typebulb agent:${e}`)}`," Agents:",...a],l=[` ${o(`typebulb v${r}`)}`,...c,""];process.stdout.write(l.join(`
1375
+ `))console.log(`${e} ${n}`);return r.length>0}function kk(r,e){return new Promise(t=>{let n=bk(process.execPath,[r,"--noEmit"],{cwd:e}),s="";n.stdout?.on("data",i=>{s+=i.toString()}),n.stderr?.on("data",i=>{s+=i.toString()}),n.on("close",i=>t({stdout:s,exitCode:i??1}))})}var xk=vk(import.meta.url);function Ek(r){let e=n=>{try{let s=xk.resolve("typescript/package.json",{paths:n}),i=tt.join(tt.dirname(s),"lib","tsc.js");return Sk(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=wk("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}pi();fn();async function Rp(r,e){let{bulb:t}=await he(r),n=ar(t);if(St(r)){console.log("remembered-trusted \u2014 runs with filesystem / AI / server.ts automatically (`typebulb untrust` to revoke)."),n&&console.log(` (it uses ${n})`);return}n?(console.log(`This bulb appears to use ${n}; it runs Restricted unless you grant trust:`),console.log(` ${e}`)):console.log("No privileged capability detected \u2014 runs Restricted by default. (A clean scan is a hint, not a guarantee.)")}fn();import*as dn from"path";async function _p(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=fc();if(!n.length){console.log("No bulbs are remembered as trusted.");return}console.log("Trusted bulbs (run with fs/AI/server.ts without --trust):");for(let s of n)console.log(` ${s}`);return}let t=dn.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),sr(t,e),console.log(e?`Trusted ${dn.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${dn.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}Me();import*as km from"readline";xi();Mc();var yn={claude:()=>new ur,pi:()=>new pr};function wm(){for(let r of Object.values(yn))try{r().ensureHarnessSupport()}catch{}}function bn(){for(let r of Object.keys(yn))try{if(yn[r]().detectsSelf())return r}catch{}}function vm(r){let e=ir(),t=new Map(e.filter(i=>yn[i]).map(i=>[i,yn[i]()]));for(let[i,o]of t)if(o.detectsSelf())return{name:i};let n=[...t].filter(([,i])=>i.detectsInstalled()).map(([i])=>i);if(n.length===0)return{name:e[0]};if(n.length===1)return{name:n[0]};let s=i=>t.get(i).listSessionFiles(r).length>0;return{ambiguous:[...n].sort((i,o)=>Number(s(o))-Number(s(i)))}}Ti();function $c(r){let e=t=>n=>r?`\x1B[${t}m${n}\x1B[0m`:n;return{lit:e("38;5;70"),litLink:e("4;38;5;70"),brand:e("38;5;135")}}async function xm(r){let e=vm(process.cwd());if("ambiguous"in e){let t=await Qx(r,e.ambiguous);return t?Sm(r,t):Xx(r,e.ambiguous)}return Sm(r,e.name)}async function Sm(r,e){let t,n;try{t=await Up(e)}catch(f){n=f instanceof Error?f.message:String(f)}let{lit:s,litLink:i,brand:o}=$c(process.stdout.isTTY===!0),a=[" Read the authoring skill before writing a bulb:",` \u2022 ${s("npx typebulb skill")} \u2014 assembles one SKILL.md`," \u2022 or, open its parts:",` ${s(fr())}`,` ${s(At())}`],c=t?[" Agent mirror is live\u{1F4A1}",` ${s("\u25CF")} ${i(t.url)}`," Embedded bulbs render live here."," Agents:",` Reusable app/tool \u2192 write a ${s(".bulb.md")}`," Show something inline \u2192 embed a bulb"," background a wait for its render verdict:",` \u2022 ${s('typebulb wait agent --match "[embed <name>"')}`,...a," End your reply with the mirror link above"," \u2022 easy to miss the link mid-message"]:[` The mirror did not start (${n})`,` \u25CF Start it manually: ${s(`npx typebulb agent:${e}`)}`," Agents:",...a],l=[` ${o(`typebulb v${r}`)}`,...c,""];process.stdout.write(l.join(`
1345
1376
  `)+`
1346
- `)}async function Qx(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=Mc(!0),s=[` ${n(`typebulb v${r}`)}`," More than one agent harness is available here.",...e.map((o,a)=>` ${t(String(a+1))}) ${o}`),""];process.stdout.write(s.join(`
1377
+ `)}async function Qx(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=$c(!0),s=[` ${n(`typebulb v${r}`)}`," More than one agent harness is available here.",...e.map((o,a)=>` ${t(String(a+1))}) ${o}`),""];process.stdout.write(s.join(`
1347
1378
  `)+`
1348
- `);let i=km.createInterface({input:process.stdin,output:process.stdout});try{let o=(await new Promise(c=>i.question(" Open which? [1]: ",c))).trim();if(o==="")return e[0];let a=Number(o);return Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:e.find(c=>c===o.toLowerCase())}finally{i.close()}}function Xx(r,e){let{lit:t,brand:n}=Mc(process.stdout.isTTY===!0),s=[` ${n(`typebulb v${r}`)}`," More than one agent harness is available here."," Open the mirror for the one you want:",...e.map(i=>` \u2022 ${t(`npx typebulb agent:${i}`)}`),""];process.stdout.write(s.join(`
1379
+ `);let i=km.createInterface({input:process.stdin,output:process.stdout});try{let o=(await new Promise(c=>i.question(" Open which? [1]: ",c))).trim();if(o==="")return e[0];let a=Number(o);return Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:e.find(c=>c===o.toLowerCase())}finally{i.close()}}function Xx(r,e){let{lit:t,brand:n}=$c(process.stdout.isTTY===!0),s=[` ${n(`typebulb v${r}`)}`," More than one agent harness is available here."," Open the mirror for the one you want:",...e.map(i=>` \u2022 ${t(`npx typebulb agent:${i}`)}`),""];process.stdout.write(s.join(`
1349
1380
  `)+`
1350
1381
  `)}import{readFileSync as Zx,existsSync as e0}from"fs";import*as De from"path";function t0(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function xe(r,e=process.cwd()){let t={},n=[];for(let s of t0(r)){let i;try{i=Zx(De.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[o,a]of r0(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:r,sources:t,loaded:n}}function*r0(r){for(let e of r.split(`
1351
- `)){let t=e.trim();if(!t||t.startsWith("#"))continue;let n=t.indexOf("=");if(n===-1)continue;let s=t.slice(0,n).trim(),i=t.slice(n+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),yield[s,i]}}function n0(r){let e=new Set,t=/process\.env\.([A-Za-z_$][\w$]*)|process\.env\[\s*['"]([^'"]+)['"]\s*\]/g;for(let n;n=t.exec(r);)e.add(n[1]??n[2]);return[...e]}function nt(r,e,t){let{sources:n,mode:s,loaded:i}=r,o=process.cwd(),a=De.dirname(e),c=`(mode: ${s??"none"})`,l=t?n0(t):[],f=l.filter(p=>n[p]).map(p=>`${p} \u2190 ${n[p]}`);f.length?console.log(`env: ${f.join(", ")} ${c}`):i.length&&console.log(`env: loaded ${i.join(", ")} ${c}`),s&&!i.some(p=>p===`.env.${s}`||p===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=De.resolve(a)!==De.resolve(o);if(u)for(let p of[".env.local",".env"])e0(De.join(a,p))&&console.log(`env: ${De.join(a,p)} present but not loaded (cwd is ${o})`);let d=l.filter(p=>process.env[p]===void 0);if(d.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${d.join(", ")} but ${d.length>1?"they are":"it's"} unset${p}`)}}nr();async function Em(r){xe(r);let e=await Ne();if(e.length>0){console.log(mp(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!ac()){console.log("No AI provider keys found in this directory's .env, and no local Ollama server detected."),console.log("Set one of these to use a cloud model with tb.ai:");for(let[t,n]of Object.entries(rr))console.log(` ${n.padEnd(20)} (${t})`);console.log("\u2026or start Ollama (http://localhost:11434, or set OLLAMA_HOST) for local models. Then re-run `typebulb models`.");return}console.log("Couldn't fetch the model catalog (offline?). tb.ai still works with any valid provider/model id for your keys.")}Ti();import*as Am from"fs/promises";async function Tm(r){let e=At(),t;try{t=await Am.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(tm(t,r))}li();import*as Pm from"path";$e();function s0(r,e,t,n){if(/^\d+$/.test(e))return r.find(i=>i.pid===parseInt(e,10));let s=e==="agent"?r.filter(i=>i.agent!=null):r.filter(i=>i.agent===e);if(s.length){if(!t)return s[0];let i=s.filter(o=>o.cwd&&Q(o.cwd)===Q(t));return n&&i.find(o=>o.agent===n)||i[0]}return r.find(i=>Q(i.file)===Q(e))}var wn=r=>r.agent??Pm.basename(r.file);function Om(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"} ${t.file}`)}function Dc(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Om(r,t=>console.log(t)),console.log(`
1382
+ `)){let t=e.trim();if(!t||t.startsWith("#"))continue;let n=t.indexOf("=");if(n===-1)continue;let s=t.slice(0,n).trim(),i=t.slice(n+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),yield[s,i]}}function n0(r){let e=new Set,t=/process\.env\.([A-Za-z_$][\w$]*)|process\.env\[\s*['"]([^'"]+)['"]\s*\]/g;for(let n;n=t.exec(r);)e.add(n[1]??n[2]);return[...e]}function nt(r,e,t){let{sources:n,mode:s,loaded:i}=r,o=process.cwd(),a=De.dirname(e),c=`(mode: ${s??"none"})`,l=t?n0(t):[],f=l.filter(p=>n[p]).map(p=>`${p} \u2190 ${n[p]}`);f.length?console.log(`env: ${f.join(", ")} ${c}`):i.length&&console.log(`env: loaded ${i.join(", ")} ${c}`),s&&!i.some(p=>p===`.env.${s}`||p===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=De.resolve(a)!==De.resolve(o);if(u)for(let p of[".env.local",".env"])e0(De.join(a,p))&&console.log(`env: ${De.join(a,p)} present but not loaded (cwd is ${o})`);let d=l.filter(p=>process.env[p]===void 0);if(d.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${d.join(", ")} but ${d.length>1?"they are":"it's"} unset${p}`)}}nr();async function Em(r){xe(r);let e=await Ne();if(e.length>0){console.log(mp(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!ac()){console.log("No AI provider keys found in this directory's .env, and no local Ollama server detected."),console.log("Set one of these to use a cloud model with tb.ai:");for(let[t,n]of Object.entries(rr))console.log(` ${n.padEnd(20)} (${t})`);console.log("\u2026or start Ollama (http://localhost:11434, or set OLLAMA_HOST) for local models. Then re-run `typebulb models`.");return}console.log("Couldn't fetch the model catalog (offline?). tb.ai still works with any valid provider/model id for your keys.")}Ti();import*as Am from"fs/promises";async function Tm(r){let e=At(),t;try{t=await Am.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(tm(t,r))}li();import*as Pm from"path";Me();function s0(r,e,t,n){if(/^\d+$/.test(e))return r.find(i=>i.pid===parseInt(e,10));let s=e==="agent"?r.filter(i=>i.agent!=null):r.filter(i=>i.agent===e);if(s.length){if(!t)return s[0];let i=s.filter(o=>o.cwd&&Q(o.cwd)===Q(t));return n&&i.find(o=>o.agent===n)||i[0]}return r.find(i=>Q(i.file)===Q(e))}var wn=r=>r.agent??Pm.basename(r.file);function Om(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"} ${t.file}`)}function Dc(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Om(r,t=>console.log(t)),console.log(`
1352
1383
  `+e)}function Bc(r,e,t,n,s){let i=s0(r,e,n,s);if(i)return i;console.error(`No running server for '${e}'.`),r.length?(console.error(`Running servers (try \`typebulb ${t} <file|pid>\`):`),Om(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Rm(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),Dc(await K(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=Bc(await K(),r,"logs",process.cwd(),bn());if(e.clear){Dp(t.pid),console.log(`Cleared log for ${wn(t)} (pid ${t.pid}).`);return}let n=ve(t.pid),s=n.text;if(e.run!==void 0&&(s=Bp(s,e.run),!s&&e.run!=="latest"&&console.error(`No output for run ${e.run} (it hasn't started, or was trimmed from the log).`)),e.lines&&e.lines>0){let i=s.split(`
1353
1384
  `);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
1354
1385
  `)}if(process.stdout.write(s),s&&!s.endsWith(`
1355
1386
  `)&&process.stdout.write(`
1356
1387
  `),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=ve(t.pid,i);i=c.offset,c.text&&process.stdout.write(c.text)},500),a=()=>{clearInterval(o),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a),await new Promise(()=>{})}}var i0=r=>new Promise(e=>setTimeout(e,r));async function _m(r,e){if(!r){Dc(await K(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=Bc(await K(),r,"wait",process.cwd(),bn()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=e.timeoutSec??1800,a=e.match??"",c=ve(t.pid).offset,l=bc(t.pid,a)??(a?bc(t.pid):void 0),f=l!==void 0&&l<=c?l:a?0:c,u=Date.now()+o*1e3,d=n?1e4:1e3,p=2e3,b,m="",y=0;for(;;){let E=ve(t.pid,f);if(f=E.offset,E.text){m+=E.text;let T=m.split(`
1357
- `);m=T.pop()??"";for(let g of T)g.trim()&&(e.match&&!g.includes(e.match)||(console.log(g),b??=Date.now()+d,n&&(g.includes("] compile error")||g.includes("] runtime error"))&&(b=Math.min(b,Date.now()+p))))}if(b&&Date.now()>=b)break;if(!i&&!b&&Date.now()>=u){console.error(`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${wn(t)} within ${o}s`),y=2;break}if(!vc(t.pid)){b||(console.error(`server ${wn(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await i0(400)}hi(t.pid,f,a),process.exit(y)}async function Cm(r){if(!r){Dc(await K(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Bc(await K(),r,"stop",process.cwd(),bn());await xt(e.pid),console.log(`Stopped ${wn(e)} (pid ${e.pid}, ${e.url}).`)}async function Nm(r){let e=process.cwd(),t=r==="agent"?bn():void 0,n=r==="global"?await K():r==="bulbs"?await K(e):(await K()).filter(i=>i.agent!=null&&i.cwd!=null&&Q(i.cwd)===Q(e)&&(!t||i.agent===t)),s=r==="global"?"server":r==="agent"?"mirror":"bulb";if(!n.length){console.log(r==="global"?"No running bulb servers.":`No running ${s}s for this project.`);return}await Promise.all(n.map(i=>xt(i.pid))),console.log(`Stopped ${n.length} ${s}${n.length===1?"":"s"}:`);for(let i of n)console.log(` ${i.url} pid ${i.pid} ${wn(i)}`)}$e();import*as Im from"path";async function Lm(r,e,t=0){let n=Im.resolve(r),s=cr(await K(),n)[0];s||(console.error(`No running server for '${r}'. Start it first: npx typebulb ${r}`),process.exit(1));let i=async()=>{let a=await fetch(`${s.url}/__send`,{method:"POST",headers:{"Content-Type":"text/plain"},body:e??""});return a.ok||(console.error(`send failed: HTTP ${a.status} from ${s.url}/__send`),process.exit(1)),(await a.json().catch(()=>({}))).clients??0},o=0;try{let a=Date.now()+t;do{if(o=await i(),o>0||Date.now()>=a)break;await new Promise(c=>setTimeout(c,150))}while(!0)}catch(a){console.error(`send failed: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}o>0?console.log(`Sent to ${o} page${o===1?"":"s"}.`):t>0?console.log(`No page connected after ${t/1e3}s \u2014 is the bulb open?`):console.log("Sent, but no page is connected yet \u2014 open the bulb and retry.")}import*as jm from"fs/promises";import*as mr from"path";import{EventEmitter as Bm}from"events";pi();import S0 from"open";er();import{Hono as f0}from"hono";import{serve as d0}from"@hono/node-server";import{streamSSE as p0}from"hono/streaming";import*as Pt from"fs/promises";import*as ye from"path";import*as jc from"fs/promises";import*as vn from"path";var _i=class{async get(e){let t=fe(e),n=vn.join(cn,t+".bin"),s=vn.join(cn,t+".json");try{let[i,o]=await Promise.all([jc.readFile(n),jc.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await q();let n=fe(e),s=vn.join(cn,n+".bin"),i=vn.join(cn,n+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([oe(s,t.body),oe(i,JSON.stringify(o))])}};$e();nr();oi();er();import{stream as o0}from"hono/streaming";var a0="X-TB-Stream";function Fc(r){return r instanceof pe?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function qc(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(a0,"1"),o0(r,async t=>{let n=e[Symbol.asyncIterator]();t.onAbort(()=>{n.return?.()});try{for(;;){let{done:s,value:i}=await n.next();if(s)break;await t.writeln(JSON.stringify({type:"chunk",value:i}))}}catch(s){await t.writeln(JSON.stringify({type:"error",error:Fc(s)}))}finally{try{await n.return?.()}catch{}}})}var Uc={log:(...r)=>console.log(...r)};function Ci(r,e){let t=r?.[e]??Uc[e];return typeof t=="function"?t:void 0}function Ni(r){return r.constructor?.name==="AsyncGeneratorFunction"}var c0=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,l0=/[?&]target=/,u0=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function $m(r,e=""){return c0.test(r)?!0:u0.test(r)&&l0.test(e)}var Dm="127.0.0.1",m0=new Set(["localhost","127.0.0.1","::1"]);function h0(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function g0(r){let e=h0(r);return!!e&&m0.has(e)}function y0(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function Jc(r){return r instanceof Error?r.message:"Unknown error"}async function Ii(r){let{getHtml:e,basePath:t,port:n,reloadEmitter:s,messageEmitter:i,getServerExports:o,localOverride:a,trusted:c=!1,trustHint:l,staticAssets:f}=r,u=new f0;u.use("*",async(g,w)=>{if(!g0(g.req.header("host")))return g.text("Forbidden: untrusted Host",403);await w()}),u.use("*",async(g,w)=>{await w(),g.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),g.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let d=["/__fs/*","/__api/*","/__ai"],p=async(g,w)=>{if(!c){let S=new URL(g.req.url).pathname,x=S.startsWith("/__fs")?"the filesystem":S==="/__ai"?"AI (your API keys)":"server-side code (server.ts)";jp(process.pid,x);let O=l?`
1358
- ${l}`:"";return g.text(`Forbidden: this capability requires --trust.${O}`,403)}await w()},b=async(g,w)=>{let S=g.req.header("sec-fetch-site");if(S){if(S!=="same-origin")return g.text(`Forbidden: ${S} request`,403)}else{let x=g.req.header("origin");if(x&&!y0(x,g.req.header("host")))return g.text("Forbidden: cross-origin request",403)}await w()};for(let g of d)u.use(g,p),u.use(g,b);u.use("/__log",b),u.post("/__log",async g=>{try{let{args:w}=await g.req.json();console.log(...w||[])}catch{}return g.json({ok:!0})}),i&&(u.use("/__send",b),u.post("/__send",async g=>{let w="";try{w=await g.req.text()}catch{}let S=i.listenerCount("message");return i.emit("message",w),g.json({clients:S})})),u.get("/",g=>g.html(e())),u.post("/__fs/read",async g=>{try{let{path:w}=await g.req.json(),S=Wc(w,t),x=await Pt.readFile(S);return new Response(new Uint8Array(x),{headers:{"Content-Type":"application/octet-stream"}})}catch(w){let S=Jc(w);return g.json({error:S},400)}}),u.post("/__fs/write",async g=>{try{let w=g.req.query("path");if(!w)return g.json({error:"Missing path"},400);let S=Wc(w,t);return await Pt.mkdir(ye.dirname(S),{recursive:!0}),await Pt.writeFile(S,Buffer.from(await g.req.arrayBuffer())),g.json({success:!0})}catch(w){let S=Jc(w);return g.json({error:S},400)}}),u.post("/__api/:name",async g=>{try{let w=g.req.param("name"),S=Ci(o?.(),w);if(!S)return g.json({error:`API function '${w}' not found`},404);let{args:x}=await g.req.json();if(Ni(S))return qc(g,S(...x||[]));let O=await S(...x||[]);return g.json({result:O})}catch(w){let S=Jc(w);return g.json({error:S},500)}}),u.post("/__ai",async g=>{try{let{messages:w,system:S,effort:x,provider:O,model:A,webSearch:L,stream:te}=await g.req.json();if(!w||!Array.isArray(w)||w.length===0)return g.json({message:"messages array is required",code:"unknown",retryable:!1},400);let V=wt(O,A);if(typeof V=="string")return g.json({message:V,code:"unknown",retryable:!1},400);let B=await vt(V,{messages:w,system:S,effort:x,webSearch:L});if(!B.ok){let Wi=await ln(B,V.protocol);return g.json(Wi,B.status)}if(te)return qc(g,Zt(B,V.protocol));let it=await bt(B,V.protocol);return it||console.warn("[tb.ai] Empty response from provider"),g.json({text:it})}catch(w){return g.json(Fc(w),500)}}),u.get("/__models",async g=>{try{let w=await Ne();return g.json(w)}catch{return g.json([],200)}}),u.get("/__has-own-keys",async g=>{try{return g.json(await ii())}catch{return g.json(!1,200)}});let m=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],y=new _i;u.get("/proxy/*",async g=>{let w=new URL(g.req.url),x=(w.pathname+w.search).slice(7),O=x.lastIndexOf("https://");return O===-1?g.text("Invalid proxy URL",400):E(g,x.slice(O))}),a&&Mm(u,`/local/${a.name}/`,a.serveDir),f&&Mm(u,f.mount,f.dir);async function E(g,w){let S;try{S=new URL(w)}catch{return g.text("Invalid URL",400)}if(S.protocol!=="https:")return g.text("HTTPS only",400);if(!m.includes(S.hostname))return g.text("Host not allowed",403);let x=await y.get(w);if(x)return new Response(x.body,{status:200,headers:Kc(x.contentType,x.cacheControl)});try{let O=await fetch(w,{headers:{Accept:g.req.header("Accept")||"*/*"},redirect:"follow"});if(!O.ok)return g.text(`Upstream ${O.status}`,O.status);let A=O.headers.get("Content-Type")||void 0,L=O.headers.get("Cache-Control")||void 0;if(O.body){let[te,V]=O.body.tee();return(async()=>{try{let B=await new Response(V).arrayBuffer();await y.set(w,{body:Buffer.from(B),contentType:A,cacheControl:L})}catch{}})(),new Response(te,{status:O.status,headers:Kc(A,L)})}return new Response(null,{status:O.status,headers:Kc(A,L)})}catch(O){return g.text(`Proxy fetch failed: ${O instanceof Error?O.message:O}`,502)}}(s||i)&&u.get("/__reload",g=>p0(g,async w=>{let S=()=>{w.writeSSE({event:"reload",data:""})},x=O=>{w.writeSSE({event:"message",data:JSON.stringify(O)})};for(s?.on("reload",S),i?.on("message",x),w.onAbort(()=>{s?.removeListener("reload",S),i?.removeListener("message",x)});;)await w.sleep(3e4)})),u.notFound(async g=>{if(g.req.method!=="GET")return g.text("Not Found",404);let w=new URL(g.req.url);return $m(w.pathname,w.search)?E(g,"https://esm.sh"+w.pathname+w.search):g.text("Not Found",404)});let T=d0({fetch:u.fetch,port:n,hostname:Dm});return{port:n,close:()=>T.close()}}function Kc(r,e){let t=new Headers;return r&&t.set("Content-Type",r),e&&t.set("Cache-Control",e),t.set("Access-Control-Allow-Origin","*"),t.set("Cross-Origin-Resource-Policy","cross-origin"),t}function Mm(r,e,t){r.get(`${e}*`,async n=>{let{pathname:s}=new URL(n.req.url);if(!s.startsWith(e))return n.text("Not Found",404);let i=decodeURIComponent(s.slice(e.length));try{let o=Wc(i,t),a=await Pt.readFile(o);return new Response(a,{headers:{"Content-Type":b0(o)}})}catch{return n.text("Not Found",404)}})}function b0(r){switch(ye.extname(r).toLowerCase()){case".js":case".mjs":return"text/javascript";case".wasm":return"application/wasm";case".json":case".map":return"application/json";default:return"application/octet-stream"}}function Wc(r,e){let t=ye.resolve(e,r),n=ye.normalize(e),s=ye.normalize(t);if(s!==n&&!s.startsWith(n+ye.sep))throw new Error("Path traversal detected - access denied");return t}async function Sn(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,Dm,()=>{let s=n.address(),i=typeof s=="object"&&s?s.port:r;n.close(()=>t(i))}),n.on("error",()=>{t(Sn(r+1))})})}import w0 from"chokidar";var v0={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Ot(r){let{target:e,onChange:t,events:n="change",debounceMs:s=150}=r,i,o=w0.watch(e,v0),a=()=>{i&&clearTimeout(i),i=setTimeout(t,s)};return n==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}$e();async function Fm(r,e,t,n,s){let i=process.cwd(),o=gi(process.pid),a=e.watch?new Bm:void 0,c=new Bm;c.setMaxListeners(0);let l=xe(e.mode),f=await kc(r);f.length&&console.log(`Replacing the running server for this bulb (pid ${f.map(x=>x.pid).join(", ")})`);let u=1;console.log(wc(u)),console.log(`Loading ${mr.basename(r)}...`);let{html:d,bulb:p,serverExports:b}=await cc(r,e.watch,e.trust,n,s);nt(l,r,p.server);let m=await Sn(e.port),y=await Ii({getHtml:()=>d,basePath:i,port:m,reloadEmitter:a,messageEmitter:c,getServerExports:()=>b,localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,trusted:e.trust,trustHint:t}),E=`http://localhost:${m}`,T=e.trust?void 0:ar(p);await yi({pid:process.pid,port:m,url:E,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,predicted:T}),console.log(`
1388
+ `);m=T.pop()??"";for(let g of T)g.trim()&&(e.match&&!g.includes(e.match)||(console.log(g),b??=Date.now()+d,n&&(g.includes("] compile error")||g.includes("] runtime error"))&&(b=Math.min(b,Date.now()+p))))}if(b&&Date.now()>=b)break;if(!i&&!b&&Date.now()>=u){console.error(`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${wn(t)} within ${o}s`),y=2;break}if(!vc(t.pid)){b||(console.error(`server ${wn(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await i0(400)}hi(t.pid,f,a),process.exit(y)}async function Cm(r){if(!r){Dc(await K(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Bc(await K(),r,"stop",process.cwd(),bn());await xt(e.pid),console.log(`Stopped ${wn(e)} (pid ${e.pid}, ${e.url}).`)}async function Nm(r){let e=process.cwd(),t=r==="agent"?bn():void 0,n=r==="global"?await K():r==="bulbs"?await K(e):(await K()).filter(i=>i.agent!=null&&i.cwd!=null&&Q(i.cwd)===Q(e)&&(!t||i.agent===t)),s=r==="global"?"server":r==="agent"?"mirror":"bulb";if(!n.length){console.log(r==="global"?"No running bulb servers.":`No running ${s}s for this project.`);return}await Promise.all(n.map(i=>xt(i.pid))),console.log(`Stopped ${n.length} ${s}${n.length===1?"":"s"}:`);for(let i of n)console.log(` ${i.url} pid ${i.pid} ${wn(i)}`)}Me();import*as Im from"path";async function Lm(r,e,t=0){let n=Im.resolve(r),s=cr(await K(),n)[0];s||(console.error(`No running server for '${r}'. Start it first: npx typebulb ${r}`),process.exit(1));let i=async()=>{let a=await fetch(`${s.url}/__send`,{method:"POST",headers:{"Content-Type":"text/plain"},body:e??""});return a.ok||(console.error(`send failed: HTTP ${a.status} from ${s.url}/__send`),process.exit(1)),(await a.json().catch(()=>({}))).clients??0},o=0;try{let a=Date.now()+t;do{if(o=await i(),o>0||Date.now()>=a)break;await new Promise(c=>setTimeout(c,150))}while(!0)}catch(a){console.error(`send failed: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}o>0?console.log(`Sent to ${o} page${o===1?"":"s"}.`):t>0?console.log(`No page connected after ${t/1e3}s \u2014 is the bulb open?`):console.log("Sent, but no page is connected yet \u2014 open the bulb and retry.")}import*as jm from"fs/promises";import*as mr from"path";import{EventEmitter as Bm}from"events";pi();import S0 from"open";er();import{Hono as f0}from"hono";import{serve as d0}from"@hono/node-server";import{streamSSE as p0}from"hono/streaming";import*as Pt from"fs/promises";import*as ye from"path";import*as jc from"fs/promises";import*as vn from"path";var _i=class{async get(e){let t=fe(e),n=vn.join(cn,t+".bin"),s=vn.join(cn,t+".json");try{let[i,o]=await Promise.all([jc.readFile(n),jc.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await q();let n=fe(e),s=vn.join(cn,n+".bin"),i=vn.join(cn,n+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([oe(s,t.body),oe(i,JSON.stringify(o))])}};Me();nr();oi();er();import{stream as o0}from"hono/streaming";var a0="X-TB-Stream";function Fc(r){return r instanceof pe?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function qc(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(a0,"1"),o0(r,async t=>{let n=e[Symbol.asyncIterator]();t.onAbort(()=>{n.return?.()});try{for(;;){let{done:s,value:i}=await n.next();if(s)break;await t.writeln(JSON.stringify({type:"chunk",value:i}))}}catch(s){await t.writeln(JSON.stringify({type:"error",error:Fc(s)}))}finally{try{await n.return?.()}catch{}}})}var Uc={log:(...r)=>console.log(...r)};function Ci(r,e){let t=r?.[e]??Uc[e];return typeof t=="function"?t:void 0}function Ni(r){return r.constructor?.name==="AsyncGeneratorFunction"}var c0=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,l0=/[?&]target=/,u0=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function Mm(r,e=""){return c0.test(r)?!0:u0.test(r)&&l0.test(e)}var Dm="127.0.0.1",m0=new Set(["localhost","127.0.0.1","::1"]);function h0(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function g0(r){let e=h0(r);return!!e&&m0.has(e)}function y0(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function Jc(r){return r instanceof Error?r.message:"Unknown error"}async function Ii(r){let{getHtml:e,basePath:t,port:n,reloadEmitter:s,messageEmitter:i,getServerExports:o,localOverride:a,trusted:c=!1,trustHint:l,staticAssets:f}=r,u=new f0;u.use("*",async(g,w)=>{if(!g0(g.req.header("host")))return g.text("Forbidden: untrusted Host",403);await w()}),u.use("*",async(g,w)=>{await w(),g.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),g.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let d=["/__fs/*","/__api/*","/__ai"],p=async(g,w)=>{if(!c){let S=new URL(g.req.url).pathname,x=S.startsWith("/__fs")?"the filesystem":S==="/__ai"?"AI (your API keys)":"server-side code (server.ts)";jp(process.pid,x);let O=l?`
1389
+ ${l}`:"";return g.text(`Forbidden: this capability requires --trust.${O}`,403)}await w()},b=async(g,w)=>{let S=g.req.header("sec-fetch-site");if(S){if(S!=="same-origin")return g.text(`Forbidden: ${S} request`,403)}else{let x=g.req.header("origin");if(x&&!y0(x,g.req.header("host")))return g.text("Forbidden: cross-origin request",403)}await w()};for(let g of d)u.use(g,p),u.use(g,b);u.use("/__log",b),u.post("/__log",async g=>{try{let{args:w}=await g.req.json();console.log(...w||[])}catch{}return g.json({ok:!0})}),i&&(u.use("/__send",b),u.post("/__send",async g=>{let w="";try{w=await g.req.text()}catch{}let S=i.listenerCount("message");return i.emit("message",w),g.json({clients:S})})),u.get("/",g=>g.html(e())),u.post("/__fs/read",async g=>{try{let{path:w}=await g.req.json(),S=Wc(w,t),x=await Pt.readFile(S);return new Response(new Uint8Array(x),{headers:{"Content-Type":"application/octet-stream"}})}catch(w){let S=Jc(w);return g.json({error:S},400)}}),u.post("/__fs/write",async g=>{try{let w=g.req.query("path");if(!w)return g.json({error:"Missing path"},400);let S=Wc(w,t);return await Pt.mkdir(ye.dirname(S),{recursive:!0}),await Pt.writeFile(S,Buffer.from(await g.req.arrayBuffer())),g.json({success:!0})}catch(w){let S=Jc(w);return g.json({error:S},400)}}),u.post("/__api/:name",async g=>{try{let w=g.req.param("name"),S=Ci(o?.(),w);if(!S)return g.json({error:`API function '${w}' not found`},404);let{args:x}=await g.req.json();if(Ni(S))return qc(g,S(...x||[]));let O=await S(...x||[]);return g.json({result:O})}catch(w){let S=Jc(w);return g.json({error:S},500)}}),u.post("/__ai",async g=>{try{let{messages:w,system:S,effort:x,provider:O,model:A,webSearch:L,stream:te}=await g.req.json();if(!w||!Array.isArray(w)||w.length===0)return g.json({message:"messages array is required",code:"unknown",retryable:!1},400);let V=wt(O,A);if(typeof V=="string")return g.json({message:V,code:"unknown",retryable:!1},400);let B=await vt(V,{messages:w,system:S,effort:x,webSearch:L});if(!B.ok){let Wi=await ln(B,V.protocol);return g.json(Wi,B.status)}if(te)return qc(g,Zt(B,V.protocol));let it=await bt(B,V.protocol);return it||console.warn("[tb.ai] Empty response from provider"),g.json({text:it})}catch(w){return g.json(Fc(w),500)}}),u.get("/__models",async g=>{try{let w=await Ne();return g.json(w)}catch{return g.json([],200)}}),u.get("/__has-own-keys",async g=>{try{return g.json(await ii())}catch{return g.json(!1,200)}});let m=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],y=new _i;u.get("/proxy/*",async g=>{let w=new URL(g.req.url),x=(w.pathname+w.search).slice(7),O=x.lastIndexOf("https://");return O===-1?g.text("Invalid proxy URL",400):E(g,x.slice(O))}),a&&$m(u,`/local/${a.name}/`,a.serveDir),f&&$m(u,f.mount,f.dir);async function E(g,w){let S;try{S=new URL(w)}catch{return g.text("Invalid URL",400)}if(S.protocol!=="https:")return g.text("HTTPS only",400);if(!m.includes(S.hostname))return g.text("Host not allowed",403);let x=await y.get(w);if(x)return new Response(x.body,{status:200,headers:Kc(x.contentType,x.cacheControl)});try{let O=await fetch(w,{headers:{Accept:g.req.header("Accept")||"*/*"},redirect:"follow"});if(!O.ok)return g.text(`Upstream ${O.status}`,O.status);let A=O.headers.get("Content-Type")||void 0,L=O.headers.get("Cache-Control")||void 0;if(O.body){let[te,V]=O.body.tee();return(async()=>{try{let B=await new Response(V).arrayBuffer();await y.set(w,{body:Buffer.from(B),contentType:A,cacheControl:L})}catch{}})(),new Response(te,{status:O.status,headers:Kc(A,L)})}return new Response(null,{status:O.status,headers:Kc(A,L)})}catch(O){return g.text(`Proxy fetch failed: ${O instanceof Error?O.message:O}`,502)}}(s||i)&&u.get("/__reload",g=>p0(g,async w=>{let S=()=>{w.writeSSE({event:"reload",data:""})},x=O=>{w.writeSSE({event:"message",data:JSON.stringify(O)})};for(s?.on("reload",S),i?.on("message",x),w.onAbort(()=>{s?.removeListener("reload",S),i?.removeListener("message",x)});;)await w.sleep(3e4)})),u.notFound(async g=>{if(g.req.method!=="GET")return g.text("Not Found",404);let w=new URL(g.req.url);return Mm(w.pathname,w.search)?E(g,"https://esm.sh"+w.pathname+w.search):g.text("Not Found",404)});let T=d0({fetch:u.fetch,port:n,hostname:Dm});return{port:n,close:()=>T.close()}}function Kc(r,e){let t=new Headers;return r&&t.set("Content-Type",r),e&&t.set("Cache-Control",e),t.set("Access-Control-Allow-Origin","*"),t.set("Cross-Origin-Resource-Policy","cross-origin"),t}function $m(r,e,t){r.get(`${e}*`,async n=>{let{pathname:s}=new URL(n.req.url);if(!s.startsWith(e))return n.text("Not Found",404);let i=decodeURIComponent(s.slice(e.length));try{let o=Wc(i,t),a=await Pt.readFile(o);return new Response(a,{headers:{"Content-Type":b0(o)}})}catch{return n.text("Not Found",404)}})}function b0(r){switch(ye.extname(r).toLowerCase()){case".js":case".mjs":return"text/javascript";case".wasm":return"application/wasm";case".json":case".map":return"application/json";default:return"application/octet-stream"}}function Wc(r,e){let t=ye.resolve(e,r),n=ye.normalize(e),s=ye.normalize(t);if(s!==n&&!s.startsWith(n+ye.sep))throw new Error("Path traversal detected - access denied");return t}async function Sn(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,Dm,()=>{let s=n.address(),i=typeof s=="object"&&s?s.port:r;n.close(()=>t(i))}),n.on("error",()=>{t(Sn(r+1))})})}import w0 from"chokidar";var v0={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Ot(r){let{target:e,onChange:t,events:n="change",debounceMs:s=150}=r,i,o=w0.watch(e,v0),a=()=>{i&&clearTimeout(i),i=setTimeout(t,s)};return n==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}Me();async function Fm(r,e,t,n,s){let i=process.cwd(),o=gi(process.pid),a=e.watch?new Bm:void 0,c=new Bm;c.setMaxListeners(0);let l=xe(e.mode),f=await kc(r);f.length&&console.log(`Replacing the running server for this bulb (pid ${f.map(x=>x.pid).join(", ")})`);let u=1;console.log(wc(u)),console.log(`Loading ${mr.basename(r)}...`);let{html:d,bulb:p,serverExports:b}=await cc(r,e.watch,e.trust,n,s);nt(l,r,p.server);let m=await Sn(e.port),y=await Ii({getHtml:()=>d,basePath:i,port:m,reloadEmitter:a,messageEmitter:c,getServerExports:()=>b,localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,trusted:e.trust,trustHint:t}),E=`http://localhost:${m}`,T=e.trust?void 0:ar(p);await yi({pid:process.pid,port:m,url:E,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,predicted:T}),console.log(`
1359
1390
  ${p.name}`),console.log(` ${E}`),m!==e.port&&console.log(` (port ${e.port} was busy)`),e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(T?` trust: restricted \u2014 this bulb appears to use ${T}; re-run with --trust to enable it:
1360
1391
  ${t}
1361
1392
  `:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
@@ -1363,7 +1394,7 @@ globalThis.__tbEntryRan = true; /* load-failure backstop \u2014 see embedProtoco
1363
1394
  `);let g,w;if(e.watch&&a&&(g=Ot({target:r,onChange:async()=>{try{console.log("Recompiling...");let x=await cc(r,!0,e.trust,n,s);d=x.html,b=x.serverExports,u++,console.log(wc(u)),a.emit("reload")}catch(x){console.error("Compile error:",x)}}}),n)){let{name:x,serveDir:O}=n;w=Ot({target:O,events:"all",onChange:()=>{console.log(`Local package '${x}' changed. Browser reloading...
1364
1395
  `),a.emit("reload")}})}e.open&&(f.some(x=>x.port===m)?console.log(` Reusing the open browser tab.
1365
1396
  `):await S0(E));let S=async()=>{console.log(`
1366
- Shutting down...`),y.close(),g?.(),w?.(),o(),await kt(process.pid);let x=mr.join(mr.dirname(r),".typebulb","server.mjs");await jm.rm(x,{force:!0}).catch(()=>{}),process.exit(0)};process.on("SIGINT",S),process.on("SIGTERM",S)}import{readFileSync as Ph,copyFileSync as YE,existsSync as GE}from"fs";import*as Z from"path";import{fileURLToPath as zE}from"url";import{EventEmitter as QE}from"events";import Oh from"open";$e();var Hc=r=>`/agents/${r}/client.js`,k0=`
1397
+ Shutting down...`),y.close(),g?.(),w?.(),o(),await kt(process.pid);let x=mr.join(mr.dirname(r),".typebulb","server.mjs");await jm.rm(x,{force:!0}).catch(()=>{}),process.exit(0)};process.on("SIGINT",S),process.on("SIGTERM",S)}import{readFileSync as Ph,copyFileSync as YE,existsSync as GE}from"fs";import*as Z from"path";import{fileURLToPath as zE}from"url";import{EventEmitter as QE}from"events";import Oh from"open";Me();var Hc=r=>`/agents/${r}/client.js`,k0=`
1367
1398
  (() => {
1368
1399
  const api = async (name, ...args) => {
1369
1400
  const resp = await fetch('/__api/' + name, {
@@ -1429,8 +1460,8 @@ ${k0}
1429
1460
  `);let T=Z.join(u,t,"client"),g=Z.join(u,"core","client");async function w(){await(await import("esbuild")).build({entryPoints:[Z.join(T,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:Z.join(f,"client.js")});for(let A of["styles.css","index.html","typebulb.png","typebulb-inv.png"])YE(Z.join(g,A),Z.join(f,A))}let S;if(r.watch&&i){let O=GE(T),A=!1;S=Ot({target:O?u:f,events:"all",onChange:async()=>{if(!A){A=!0;try{O&&await w(),console.log(`Mirror rebuilt. Browser reloading...
1430
1461
  `),i.emit("reload")}catch(L){console.error("Mirror rebuild failed:",L instanceof Error?L.message:L)}finally{A=!1}}}})}r.open&&await Oh(E);let x=async()=>{console.log(`
1431
1462
  Shutting down...`);try{a.shutdownSwitcher?.()}catch{}try{a.shutdownComposer?.()}catch{}y.close(),S?.(),s(),await kt(process.pid),process.exit(0)};process.on("SIGINT",x),process.on("SIGTERM",x)}import*as _h from"path";async function Ch(r,e,t,n,s){let i=xe(t),o=!1,a=async()=>{let{bulb:c,config:l}=await he(r);o||(nt(i,r,c.server),o=!0),await un(c.server,s,n,l.dependencies)};console.log(`Running ${_h.basename(r)}...`),await a(),e&&(console.log(`Watching for changes...
1432
- `),Ot({target:r,onChange:async()=>{try{console.log("Re-running..."),await a()}catch(c){console.error("Error:",c)}}}))}import{Console as ZE}from"node:console";$e();async function Lh(r,e,t,n,s){sA();try{let p=cr(await K(),r)[0];p&&(hi(p.pid,ve(p.pid).offset),console.error(`note: 'call' boots a fresh server.ts instance; the running server (${p.url}) is not contacted \u2014 state shared with it must live on disk.`))}catch{}let i=xe(t),{bulb:o,config:a}=await he(r);o.server||Tn("This bulb has no **server.ts** block; nothing to call."),nt(i,r,o.server);let c;try{c=await un(o.server,s,n,a.dependencies)}catch(p){Tn(p instanceof Error?p.message:String(p))}let l=Ci(c,e.fn);if(!l){let p=[...Object.keys(c).filter(b=>typeof c[b]=="function"),...Object.keys(Uc)];Tn(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let f=await eA(e);if(Ni(l)){try{for await(let p of l(...f))await Ih(JSON.stringify(p,$h)+`
1463
+ `),Ot({target:r,onChange:async()=>{try{console.log("Re-running..."),await a()}catch(c){console.error("Error:",c)}}}))}import{Console as ZE}from"node:console";Me();async function Lh(r,e,t,n,s){sA();try{let p=cr(await K(),r)[0];p&&(hi(p.pid,ve(p.pid).offset),console.error(`note: 'call' boots a fresh server.ts instance; the running server (${p.url}) is not contacted \u2014 state shared with it must live on disk.`))}catch{}let i=xe(t),{bulb:o,config:a}=await he(r);o.server||Tn("This bulb has no **server.ts** block; nothing to call."),nt(i,r,o.server);let c;try{c=await un(o.server,s,n,a.dependencies)}catch(p){Tn(p instanceof Error?p.message:String(p))}let l=Ci(c,e.fn);if(!l){let p=[...Object.keys(c).filter(b=>typeof c[b]=="function"),...Object.keys(Uc)];Tn(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let f=await eA(e);if(Ni(l)){try{for await(let p of l(...f))await Ih(JSON.stringify(p,Mh)+`
1433
1464
  `)}catch(p){Tn(p instanceof Error?p.stack??p.message:String(p))}return Nh(0)}let u;try{u=await l(...f)}catch(p){Tn(p instanceof Error?p.stack??p.message:String(p))}let d=nA(u);d!==void 0&&await Ih(d+`
1434
- `),Nh(0)}function Nh(r){process.exitCode=r,setTimeout(()=>process.exit(r),2e3).unref?.()}async function eA(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await iA()),rA(e)}return tA(r.positional)}function tA(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function rA(r){let e;try{e=JSON.parse(r)}catch(t){throw new Error(`--args must be a JSON array: ${t instanceof Error?t.message:String(t)}`)}if(!Array.isArray(e))throw new Error(`--args must be a JSON array, got ${e===null?"null":typeof e}`);return e}function nA(r){if(r!==void 0)return JSON.stringify(r,$h,2)}function $h(r,e){return typeof e=="bigint"?e.toString():e}function Tn(r){process.stderr.write(r+`
1435
- `),process.exit(1)}function sA(){let r=new ZE(process.stderr,process.stderr);console.log=r.log.bind(r),console.info=r.info.bind(r),console.debug=r.debug.bind(r),console.dir=r.dir.bind(r)}function Ih(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function iA(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var sl="0.23.0";function Mh(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
1436
- ${e}`),process.exit(1))}async function oA(){let r=yl(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${sl}`),process.exit(0)),r.help&&(bl(),process.exit(0)),wm(),r.subcommand==="logs"){await Rm(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await _m(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await Nm(r.stopScope):await Cm(r.file||void 0);return}if(r.subcommand==="send"){await Lm(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await Tm(sl);return}if(r.subcommand==="models"){await Em(r.mode);return}if(r.subcommand==="agent"){await(r.agentTarget?Rh(r):xm(sl));return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await _p(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let l=await yp(process.cwd());l||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=l}else e=Be.resolve(r.file);await Dh.access(e).then(()=>!0,()=>!1)||(ir().includes(r.file)&&(console.error(`To open the ${r.file} agent mirror, run: npx typebulb agent:${r.file}`),process.exit(1)),console.error(`File not found: ${e}`),process.exit(1)),e.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1));let n=r.file&&r.file!=="."?r.file:Be.relative(process.cwd(),e)||Be.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await Rp(e,s);return}let i=!r.noTrust&&St(e);i&&!r.trust&&console.log("trust: granted from memory (run `typebulb untrust` to revoke)"),r.trust=r.noTrust?!1:r.trust||i;let o;try{o=await he(e)}catch{}let a;if(r.local){o&&!(r.local.name in(o.config.dependencies??{}))&&(console.error(`--replace: '${r.local.name}' is not a dependency in this bulb's config.json; nothing to replace.`),process.exit(1)),o&&r.subcommand!=="call"&&(!o.bulb.code||r.server)&&console.warn("warning: --replace has no effect in server mode (the override is client-only).");try{a=await hl(r.local)}catch(l){console.error(l instanceof Error?l.message:String(l)),process.exit(1)}console.log(`replace: ${a.name} \u2192 ${Be.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await Op(e,a);return}let c=Be.dirname(e);if(r.subcommand==="call"){Mh(r.trust,s),await Lh(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a,c);return}if(o&&o.bulb.server&&(Ps(o.bulb)||r.server)){Mh(r.trust,s),await Ch(e,r.watch,r.mode,a,c);return}await Fm(e,r,s,a,c)}oA().catch(r=>{console.error("Error:",r.message),process.exit(1)});
1465
+ `),Nh(0)}function Nh(r){process.exitCode=r,setTimeout(()=>process.exit(r),2e3).unref?.()}async function eA(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await iA()),rA(e)}return tA(r.positional)}function tA(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function rA(r){let e;try{e=JSON.parse(r)}catch(t){throw new Error(`--args must be a JSON array: ${t instanceof Error?t.message:String(t)}`)}if(!Array.isArray(e))throw new Error(`--args must be a JSON array, got ${e===null?"null":typeof e}`);return e}function nA(r){if(r!==void 0)return JSON.stringify(r,Mh,2)}function Mh(r,e){return typeof e=="bigint"?e.toString():e}function Tn(r){process.stderr.write(r+`
1466
+ `),process.exit(1)}function sA(){let r=new ZE(process.stderr,process.stderr);console.log=r.log.bind(r),console.info=r.info.bind(r),console.debug=r.debug.bind(r),console.dir=r.dir.bind(r)}function Ih(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function iA(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var sl="0.23.2";function $h(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
1467
+ ${e}`),process.exit(1))}async function oA(){let r=yl(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${sl}`),process.exit(0)),r.help&&(bl(),process.exit(0)),wm(),r.subcommand==="logs"){await Rm(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await _m(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await Nm(r.stopScope):await Cm(r.file||void 0);return}if(r.subcommand==="send"){await Lm(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await Tm(sl);return}if(r.subcommand==="models"){await Em(r.mode);return}if(r.subcommand==="agent"){await(r.agentTarget?Rh(r):xm(sl));return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await _p(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let l=await yp(process.cwd());l||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=l}else e=Be.resolve(r.file);await Dh.access(e).then(()=>!0,()=>!1)||(ir().includes(r.file)&&(console.error(`To open the ${r.file} agent mirror, run: npx typebulb agent:${r.file}`),process.exit(1)),console.error(`File not found: ${e}`),process.exit(1)),e.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1));let n=r.file&&r.file!=="."?r.file:Be.relative(process.cwd(),e)||Be.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await Rp(e,s);return}let i=!r.noTrust&&St(e);i&&!r.trust&&console.log("trust: granted from memory (run `typebulb untrust` to revoke)"),r.trust=r.noTrust?!1:r.trust||i;let o;try{o=await he(e)}catch{}let a;if(r.local){o&&!(r.local.name in(o.config.dependencies??{}))&&(console.error(`--replace: '${r.local.name}' is not a dependency in this bulb's config.json; nothing to replace.`),process.exit(1)),o&&r.subcommand!=="call"&&(!o.bulb.code||r.server)&&console.warn("warning: --replace has no effect in server mode (the override is client-only).");try{a=await hl(r.local)}catch(l){console.error(l instanceof Error?l.message:String(l)),process.exit(1)}console.log(`replace: ${a.name} \u2192 ${Be.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await Op(e,a);return}let c=Be.dirname(e);if(r.subcommand==="call"){$h(r.trust,s),await Lh(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a,c);return}if(o&&o.bulb.server&&(Ps(o.bulb)||r.server)){$h(r.trust,s),await Ch(e,r.watch,r.mode,a,c);return}await Fm(e,r,s,a,c)}oA().catch(r=>{console.error("Error:",r.message),process.exit(1)});