typebulb 0.23.5 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/claude/styles.css +16 -7
- package/dist/agents/pi/client.js +218 -218
- package/dist/agents/pi/matchu-patchu.ts +1 -1
- package/dist/agents/pi/styles.css +16 -7
- package/dist/index.js +185 -184
- package/dist/servers.js +43 -43
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,85 +1,85 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);
|
|
3
|
-
var
|
|
4
|
-
`),t=0;if(e[t]?.trim()!=="---")return null;t++;let n=[];for(;t<e.length&&e[t]?.trim()!=="---";)n.push(e[t]),t++;if(e[t]?.trim()!=="---")return null;t++;let s=
|
|
5
|
-
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function
|
|
3
|
+
var dg=Object.create;var zi=Object.defineProperty;var pg=Object.getOwnPropertyDescriptor;var mg=Object.getOwnPropertyNames;var hg=Object.getPrototypeOf,gg=Object.prototype.hasOwnProperty;var Rn=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var R=(r,e)=>()=>(r&&(e=r(r=0)),e);var P=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),dl=(r,e)=>{for(var t in e)zi(r,t,{get:e[t],enumerable:!0})},yg=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of mg(e))!gg.call(r,s)&&s!==t&&zi(r,s,{get:()=>e[s],enumerable:!(n=pg(e,s))||n.enumerable});return r};var bg=(r,e,t)=>(t=r!=null?dg(hg(r)):{},yg(e||!r||!r.__esModule?zi(t,"default",{value:r,enumerable:!0}):t,r));function xl(r){return $t.find(e=>Mt[e].path===r)}function Al(r){return!!r?.startsWith("typebulb")}var Mt,$t,El,_n=R(()=>{Mt={code:{path:"code.tsx",language:"typescript"},css:{path:"styles.css",language:"css"},html:{path:"index.html",language:"html"},config:{path:"config.json",language:"json"},notes:{path:"notes.md",language:"markdown"},data:{path:"data.txt",language:"text"},infer:{path:"infer.md",language:"markdown"},insight:{path:"insight.json",language:"json"}},$t=["code","css","html","data","infer","insight","config","notes"];El="typebulb/v1"});function eo(r){return/[:\n"']/.test(r)||r.startsWith(" ")||r.endsWith(" ")?`"${r.replace(/"/g,'\\"')}"`:r}function to(r){return r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1).replace(/\\"/g,'"'):r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}var Cn=R(()=>{});function Ae(r){try{let e=r.split(`
|
|
4
|
+
`),t=0;if(e[t]?.trim()!=="---")return null;t++;let n=[];for(;t<e.length&&e[t]?.trim()!=="---";)n.push(e[t]),t++;if(e[t]?.trim()!=="---")return null;t++;let s=_g(n);if(!s)return null;let i=new Map,o=[],a=t;for(;t<e.length;){let l=e[t]?.trim()?.match(Tl);if(l){let f=l[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let u=e[t]?.match(Pl);if(!u){t++;continue}let d=u[1];t++;let p=[];for(;t<e.length&&!e[t]?.match(new RegExp(`^${d}\\s*$`));)p.push(e[t]),t++;let b=t<e.length;t++,o.push(...Og(f,p,b)),i.set(f,p.join(`
|
|
5
|
+
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function Og(r,e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s]?.trim().match(Tl);i&&Pg.has(i[1].trim())&&Rg(e,s)&&n.push(i[1].trim())}return n.length?n.map(s=>`**${r}** block has an unterminated code fence \u2014 it swallowed the **${s}** block.`):t?[]:[`**${r}** block has an unterminated code fence (it runs to the end of the file).`]}function Rg(r,e){let t=e+1;for(;t<r.length&&r[t]?.trim()==="";)t++;return!!r[t]?.match(Pl)}function _g(r){let e={};for(let t of r){let n=t.indexOf(":");if(n===-1)continue;let s=t.slice(0,n).trim(),i=t.slice(n+1).trim();switch(s){case"format":e.format=i;break;case"name":e.name=to(i);break}}return!Al(e.format)||!e.name?null:e}function Ol(r){return Ae(r)?.warnings??[]}function Rl(r){let e=Object.fromEntries($t.map(t=>[t,r.files.get(Mt[t].path)||""]));return{name:r.frontmatter.name,...e}}var Tl,Pl,Pg,_l=R(()=>{_n();Cn();Tl=/^\*\*(.+)\*\*$/,Pl=/^(`{3,})(\w*)\s*$/,Pg=new Set($t.map(r=>Mt[r].path))});function Cg(r){let e=r.match(/^`{3,}/gm),t=e?Math.max(...e.map(n=>n.length)):0;return"`".repeat(Math.max(3,t+1))}function Cl(r){let e=$t.filter(t=>r[t]).map(t=>{let{path:n}=Mt[t],s=r[t],i=n.split(".").pop(),o=Cg(s);return`**${n}**
|
|
6
6
|
|
|
7
7
|
${o}${i}
|
|
8
8
|
${s}
|
|
9
|
-
${o}`});return["---",`format: ${
|
|
10
|
-
`)}var
|
|
11
|
-
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=
|
|
12
|
-
>]`),m+=
|
|
13
|
-
`)}};
|
|
14
|
-
`)?
|
|
9
|
+
${o}`});return["---",`format: ${El}`,`name: ${eo(r.name)}`,"---","",...e].join(`
|
|
10
|
+
`)}var Nl=R(()=>{_n();Cn()});function Il(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}var Ll=R(()=>{});var Ml=R(()=>{});function ro(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index:-1}var $l=R(()=>{});function wr(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index+s[0].length-1:-1}var Dl=R(()=>{});function Nn(r,e){let t=new RegExp(e,"g"),n=r.match(t);return n?n.length:0}var Bl=R(()=>{});function vr(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=ro(r,`<${e}[
|
|
11
|
+
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=wr(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=wr(a,"[ /]"+e+">",p))!==-1;){let y=a.substring(p,c+1);if(b+=Nn(y,"<"+e+`[
|
|
12
|
+
>]`),m+=Nn(y,"</"+e+">"),m>=b)break;p=c}}else c=wr(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 no=R(()=>{$l();Dl();Bl()});var so=R(()=>{no()});var io=R(()=>{so()});var jl=R(()=>{io()});var Fl=R(()=>{});var ql=R(()=>{Ml();no();so();jl();io();Fl()});var L=P(z=>{"use strict";var oo=Symbol.for("yaml.alias"),Ul=Symbol.for("yaml.document"),In=Symbol.for("yaml.map"),Jl=Symbol.for("yaml.pair"),ao=Symbol.for("yaml.scalar"),Ln=Symbol.for("yaml.seq"),Te=Symbol.for("yaml.node.type"),Lg=r=>!!r&&typeof r=="object"&&r[Te]===oo,Mg=r=>!!r&&typeof r=="object"&&r[Te]===Ul,$g=r=>!!r&&typeof r=="object"&&r[Te]===In,Dg=r=>!!r&&typeof r=="object"&&r[Te]===Jl,Kl=r=>!!r&&typeof r=="object"&&r[Te]===ao,Bg=r=>!!r&&typeof r=="object"&&r[Te]===Ln;function Wl(r){if(r&&typeof r=="object")switch(r[Te]){case In:case Ln:return!0}return!1}function jg(r){if(r&&typeof r=="object")switch(r[Te]){case oo:case In:case ao:case Ln:return!0}return!1}var Fg=r=>(Kl(r)||Wl(r))&&!!r.anchor;z.ALIAS=oo;z.DOC=Ul;z.MAP=In;z.NODE_TYPE=Te;z.PAIR=Jl;z.SCALAR=ao;z.SEQ=Ln;z.hasAnchor=Fg;z.isAlias=Lg;z.isCollection=Wl;z.isDocument=Mg;z.isMap=$g;z.isNode=jg;z.isPair=Dg;z.isScalar=Kl;z.isSeq=Bg});var Sr=P(co=>{"use strict";var H=L(),re=Symbol("break visit"),Hl=Symbol("skip children"),be=Symbol("remove node");function Mn(r,e){let t=Vl(e);H.isDocument(r)?Dt(null,r.contents,t,Object.freeze([r]))===be&&(r.contents=null):Dt(null,r,t,Object.freeze([]))}Mn.BREAK=re;Mn.SKIP=Hl;Mn.REMOVE=be;function Dt(r,e,t,n){let s=Yl(r,e,t,n);if(H.isNode(s)||H.isPair(s))return Gl(r,n,s),Dt(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=Dt(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=Dt("key",e.key,t,n);if(i===re)return re;i===be&&(e.key=null);let o=Dt("value",e.value,t,n);if(o===re)return re;o===be&&(e.value=null)}}return s}async function $n(r,e){let t=Vl(e);H.isDocument(r)?await Bt(null,r.contents,t,Object.freeze([r]))===be&&(r.contents=null):await Bt(null,r,t,Object.freeze([]))}$n.BREAK=re;$n.SKIP=Hl;$n.REMOVE=be;async function Bt(r,e,t,n){let s=await Yl(r,e,t,n);if(H.isNode(s)||H.isPair(s))return Gl(r,n,s),Bt(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 Bt(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 Bt("key",e.key,t,n);if(i===re)return re;i===be&&(e.key=null);let o=await Bt("value",e.value,t,n);if(o===re)return re;o===be&&(e.value=null)}}return s}function Vl(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 Yl(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 Gl(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`)}}co.visit=Mn;co.visitAsync=$n});var lo=P(Ql=>{"use strict";var zl=L(),qg=Sr(),Ug={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Jg=r=>r.replace(/[!,[\]{}]/g,e=>Ug[e]),kr=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+Jg(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&&zl.isNode(e.contents)){let i={};qg.visit(e.contents,(o,a)=>{zl.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
|
+
`)}};kr.defaultYaml={explicit:!1,version:"1.2"};kr.defaultTags={"!!":"tag:yaml.org,2002:"};Ql.Directives=kr});var Dn=P(xr=>{"use strict";var Xl=L(),Kg=Sr();function Wg(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 Zl(r){let e=new Set;return Kg.visit(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function eu(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function Hg(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s??(s=Zl(r));let o=eu(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(Xl.isScalar(o.node)||Xl.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}}xr.anchorIsValid=Wg;xr.anchorNames=Zl;xr.createNodeAnchors=Hg;xr.findNewAnchor=eu});var uo=P(tu=>{"use strict";function Er(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=Er(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=Er(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=Er(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=Er(r,n,s,i);o===void 0?delete n[s]:o!==i&&(n[s]=o)}return r.call(e,t,n)}tu.applyReviver=Er});var je=P(nu=>{"use strict";var Vg=L();function ru(r,e,t){if(Array.isArray(r))return r.map((n,s)=>ru(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!Vg.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}nu.toJS=ru});var Bn=P(iu=>{"use strict";var Yg=uo(),su=L(),Gg=je(),fo=class{constructor(e){Object.defineProperty(this,su.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(!su.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=Gg.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?Yg.applyReviver(i,{"":a},"",a):a}};iu.NodeBase=fo});var Ar=P(ou=>{"use strict";var zg=Dn(),Qg=Sr(),jt=L(),Xg=Bn(),Zg=je(),po=class extends Xg.NodeBase{constructor(e){super(jt.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=[],Qg.visit(e,{Node:(i,o)=>{(jt.isAlias(o)||jt.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||(Zg.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=jn(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(zg.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 jn(r,e,t){if(jt.isAlias(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(jt.isCollection(e)){let n=0;for(let s of e.items){let i=jn(r,s,t);i>n&&(n=i)}return n}else if(jt.isPair(e)){let n=jn(r,e.key,t),s=jn(r,e.value,t);return Math.max(n,s)}return 1}ou.Alias=po});var J=P(mo=>{"use strict";var ey=L(),ty=Bn(),ry=je(),ny=r=>!r||typeof r!="function"&&typeof r!="object",Fe=class extends ty.NodeBase{constructor(e){super(ey.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:ry.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";mo.Scalar=Fe;mo.isScalarValue=ny});var Tr=P(cu=>{"use strict";var sy=Ar(),ot=L(),au=J(),iy="tag:yaml.org,2002:";function oy(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 ay(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 sy.Alias(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=iy+e.slice(2));let l=oy(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new au.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 au.Scalar(r);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}cu.createNode=ay});var qn=P(Fn=>{"use strict";var cy=Tr(),we=L(),ly=Bn();function ho(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 cy.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 lu=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,go=class extends ly.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(lu(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,ho(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,ho(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};Fn.Collection=go;Fn.collectionFromPath=ho;Fn.isEmptyPath=lu});var Pr=P(Un=>{"use strict";var uy=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function yo(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var fy=(r,e,t)=>r.endsWith(`
|
|
14
|
+
`)?yo(t,e):t.includes(`
|
|
15
15
|
`)?`
|
|
16
|
-
`+
|
|
17
|
-
`)t===
|
|
16
|
+
`+yo(t,e):(r.endsWith(" ")?"":" ")+t;Un.indentComment=yo;Un.lineComment=fy;Un.stringifyComment=uy});var fu=P(Or=>{"use strict";var dy="flow",bo="block",Jn="quoted";function py(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===bo&&(m=uu(r,m,e.length),m!==-1&&(u=m+c));for(let g;g=r[m+=1];){if(t===Jn&&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===`
|
|
17
|
+
`)t===bo&&(m=uu(r,m,e.length)),u=m+e.length+c,d=void 0;else{if(g===" "&&p&&p!==" "&&p!==`
|
|
18
18
|
`&&p!==" "){let w=r[m+1];w&&w!==" "&&w!==`
|
|
19
|
-
`&&w!==" "&&(d=m)}if(m>=u)if(d)l.push(d),u=d+c,d=void 0;else if(t===
|
|
20
|
-
${e}${r.slice(0,k)}`:(t===
|
|
21
|
-
${e}${r.slice(w+1,k)}`)}return T}function
|
|
22
|
-
`);n=e,s=e+1,i=r[s]}return n}
|
|
23
|
-
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function
|
|
19
|
+
`&&w!==" "&&(d=m)}if(m>=u)if(d)l.push(d),u=d+c,d=void 0;else if(t===Jn){for(;p===" "||p===" ";)p=g,g=r[m+=1],b=!0;let w=m>E+1?m-2:y-1;if(f[w])return r;l.push(w),f[w]=!0,u=w+c,d=void 0}else b=!0}p=g}if(b&&a&&a(),l.length===0)return r;o&&o();let T=r.slice(0,l[0]);for(let g=0;g<l.length;++g){let w=l[g],k=l[g+1]||r.length;w===0?T=`
|
|
20
|
+
${e}${r.slice(0,k)}`:(t===Jn&&f[w]&&(T+=`${r[w]}\\`),T+=`
|
|
21
|
+
${e}${r.slice(w+1,k)}`)}return T}function uu(r,e,t){let n=e,s=e+1,i=r[s];for(;i===" "||i===" ";)if(e<s+t)i=r[++e];else{do i=r[++e];while(i&&i!==`
|
|
22
|
+
`);n=e,s=e+1,i=r[s]}return n}Or.FOLD_BLOCK=bo;Or.FOLD_FLOW=dy;Or.FOLD_QUOTED=Jn;Or.foldFlowLines=py});var _r=P(du=>{"use strict";var le=J(),qe=fu(),Wn=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),Hn=r=>/^(%|---|\.\.\.)/m.test(r);function my(r,e,t){if(!e||e<0)return!1;let n=e-t,s=r.length;if(s<=n)return!1;for(let i=0,o=0;i<s;++i)if(r[i]===`
|
|
23
|
+
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function Rr(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Hn(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let f=t.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length<s)c+=1;else{for(o+=t.slice(a,c)+`
|
|
24
24
|
|
|
25
25
|
`;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)o+=`
|
|
26
|
-
`,c+=2;o+=i,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,n?o:qe.foldFlowLines(o,i,qe.FOLD_QUOTED,
|
|
27
|
-
`)||/[ \t]\n|\n[ \t]/.test(r))return
|
|
28
|
-
${t}`)+"'";return e.implicitKey?n:qe.foldFlowLines(n,t,qe.FOLD_FLOW,
|
|
26
|
+
`,c+=2;o+=i,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,n?o:qe.foldFlowLines(o,i,qe.FOLD_QUOTED,Wn(e,!1))}function wo(r,e){if(e.options.singleQuote===!1||e.implicitKey&&r.includes(`
|
|
27
|
+
`)||/[ \t]\n|\n[ \t]/.test(r))return Rr(r,e);let t=e.indent||(Hn(r)?" ":""),n="'"+r.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
28
|
+
${t}`)+"'";return e.implicitKey?n:qe.foldFlowLines(n,t,qe.FOLD_FLOW,Wn(e,!1))}function Ft(r,e){let{singleQuote:t}=e.options,n;if(t===!1)n=Rr;else{let s=r.includes('"'),i=r.includes("'");s&&!i?n=wo:i&&!s?n=Rr:n=t?wo:Rr}return n(r,e)}var vo;try{vo=new RegExp(`(^|(?<!
|
|
29
29
|
))
|
|
30
30
|
+(?!
|
|
31
|
-
|$)`,"g")}catch{
|
|
31
|
+
|$)`,"g")}catch{vo=/\n+(?!\n|$)/g}function Kn({comment:r,type:e,value:t},n,s,i){let{blockQuote:o,commentString:a,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(t))return Ft(t,n);let l=n.indent||(n.forceBlockIndent||Hn(t)?" ":""),f=o==="literal"?!0:o==="folded"||e===le.Scalar.BLOCK_FOLDED?!1:e===le.Scalar.BLOCK_LITERAL?!0:!my(t,c,l.length);if(!t)return f?`|
|
|
32
32
|
`:`>
|
|
33
33
|
`;let u,d;for(d=t.length;d>0;--d){let k=t[d-1];if(k!==`
|
|
34
34
|
`&&k!==" "&&k!==" ")break}let p=t.substring(d),b=p.indexOf(`
|
|
35
35
|
`);b===-1?u="-":t===p||b!==p.length-1?(u="+",i&&i()):u="",p&&(t=t.slice(0,-p.length),p[p.length-1]===`
|
|
36
|
-
`&&(p=p.slice(0,-1)),p=p.replace(
|
|
36
|
+
`&&(p=p.slice(0,-1)),p=p.replace(vo,`$&${l}`));let m=!1,y,E=-1;for(y=0;y<t.length;++y){let k=t[y];if(k===" ")m=!0;else if(k===`
|
|
37
37
|
`)E=y;else break}let T=t.substring(0,E<y?E+1:y);T&&(t=t.substring(T.length),T=T.replace(/\n+/g,`$&${l}`));let w=(m?l?"2":"1":"")+u;if(r&&(w+=" "+a(r.replace(/ ?[\r\n]+/g," ")),s&&s()),!f){let k=t.replace(/\n+/g,`
|
|
38
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),x=!1,O=
|
|
38
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),x=!1,O=Wn(n,!0);o!=="folded"&&e!==le.Scalar.BLOCK_FOLDED&&(O.onOverflow=()=>{x=!0});let A=qe.foldFlowLines(`${T}${k}${p}`,l,qe.FOLD_BLOCK,O);if(!x)return`>${w}
|
|
39
39
|
${l}${A}`}return t=t.replace(/\n+/g,`$&${l}`),`|${w}
|
|
40
|
-
${l}${T}${t}${p}`}function
|
|
41
|
-
`)||f&&/[[\]{},]/.test(i))return
|
|
42
|
-
`)?
|
|
43
|
-
`))return
|
|
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
|
|
45
|
-
${e.indent}${a}`:a}
|
|
46
|
-
${a}:`):(y=`${y}:`,d&&(y+=
|
|
40
|
+
${l}${T}${t}${p}`}function hy(r,e,t,n){let{type:s,value:i}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:f}=e;if(a&&i.includes(`
|
|
41
|
+
`)||f&&/[[\]{},]/.test(i))return Ft(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||f||!i.includes(`
|
|
42
|
+
`)?Ft(i,e):Kn(r,e,t,n);if(!a&&!f&&s!==le.Scalar.PLAIN&&i.includes(`
|
|
43
|
+
`))return Kn(r,e,t,n);if(Hn(i)){if(c==="")return e.forceBlockIndent=!0,Kn(r,e,t,n);if(a&&c===l)return Ft(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 Ft(i,e)}return a?u:qe.foldFlowLines(u,c,qe.FOLD_FLOW,Wn(e,!1))}function gy(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?Ft(o.value,e):Kn(o,e,t,n);case le.Scalar.QUOTE_DOUBLE:return Rr(o.value,e);case le.Scalar.QUOTE_SINGLE:return wo(o.value,e);case le.Scalar.PLAIN:return hy(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}du.stringifyString=gy});var Cr=P(So=>{"use strict";var yy=Dn(),Ue=L(),by=Pr(),wy=_r();function vy(r,e){let t=Object.assign({blockQuote:!0,commentString:by.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 Sy(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 ky(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],i=(Ue.isScalar(r)||Ue.isCollection(r))&&r.anchor;i&&yy.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 xy(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=Sy(e.doc.schema.tags,i));let o=ky(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)?wy.stringifyString(i,e,t,n):i.toString(e,t,n);return o?Ue.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
45
|
+
${e.indent}${a}`:a}So.createStringifyContext=vy;So.stringify=xy});var gu=P(hu=>{"use strict";var Pe=L(),pu=J(),mu=Cr(),Nr=Pr();function Ey({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===pu.Scalar.BLOCK_FOLDED||r.type===pu.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=mu.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+=Nr.lineComment(y,t.indent,l(d)):m&&s&&s(),y;b&&(d=null),p?(d&&(y+=Nr.lineComment(y,t.indent,l(d))),y=`? ${y}
|
|
46
|
+
${a}:`):(y=`${y}:`,d&&(y+=Nr.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,k=mu.stringify(e,t,()=>w=!0,()=>m=!0),x=" ";if(d||E||T){if(x=E?`
|
|
47
47
|
`:"",T){let O=l(T);x+=`
|
|
48
|
-
${
|
|
48
|
+
${Nr.indentComment(O,t.indent)}`}k===""&&!t.inFlow?x===`
|
|
49
49
|
`&&g&&(x=`
|
|
50
50
|
|
|
51
51
|
`):x+=`
|
|
52
52
|
${t.indent}`}else if(!p&&Pe.isCollection(e)){let O=k[0],A=k.indexOf(`
|
|
53
53
|
`),M=A!==-1,te=t.inFlow??e.flow??e.items.length===0;if(M||!te){let V=!1;if(M&&(O==="&"||O==="!")){let B=k.indexOf(" ");O==="&"&&B!==-1&&B<A&&k[B+1]==="!"&&(B=k.indexOf(" ",B+1)),(B===-1||A<B)&&(V=!0)}V||(x=`
|
|
54
54
|
${t.indent}`)}}else(k===""||k[0]===`
|
|
55
|
-
`)&&(x="");return y+=x+k,t.inFlow?w&&n&&n():g&&!w?y+=
|
|
55
|
+
`)&&(x="");return y+=x+k,t.inFlow?w&&n&&n():g&&!w?y+=Nr.lineComment(y,t.indent,l(g)):m&&s&&s(),y}hu.stringifyPair=Ey});var xo=P(ko=>{"use strict";var yu=Rn("process");function Ay(r,...e){r==="debug"&&console.log(...e)}function Ty(r,e){(r==="debug"||r==="warn")&&(typeof yu.emitWarning=="function"?yu.emitWarning(e):console.warn(e))}ko.debug=Ay;ko.warn=Ty});var zn=P(Gn=>{"use strict";var Ir=L(),bu=J(),Vn="<<",Yn={identify:r=>r===Vn||typeof r=="symbol"&&r.description===Vn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new bu.Scalar(Symbol(Vn)),{addToJSMap:wu}),stringify:()=>Vn},Py=(r,e)=>(Yn.identify(e)||Ir.isScalar(e)&&(!e.type||e.type===bu.Scalar.PLAIN)&&Yn.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===Yn.tag&&t.default);function wu(r,e,t){if(t=r&&Ir.isAlias(t)?t.resolve(r.doc):t,Ir.isSeq(t))for(let n of t.items)Eo(r,e,n);else if(Array.isArray(t))for(let n of t)Eo(r,e,n);else Eo(r,e,t)}function Eo(r,e,t){let n=r&&Ir.isAlias(t)?t.resolve(r.doc):t;if(!Ir.isMap(n))throw new Error("Merge sources must be maps or map aliases");let s=n.toJSON(null,r,Map);for(let[i,o]of s)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}Gn.addMergeToJSMap=wu;Gn.isMergeKey=Py;Gn.merge=Yn});var To=P(ku=>{"use strict";var Oy=xo(),vu=zn(),Ry=Cr(),Su=L(),Ao=je();function _y(r,e,{key:t,value:n}){if(Su.isNode(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(vu.isMergeKey(r,t))vu.addMergeToJSMap(r,e,n);else{let s=Ao.toJS(t,"",r);if(e instanceof Map)e.set(s,Ao.toJS(n,s,r));else if(e instanceof Set)e.add(s);else{let i=Cy(t,s,r),o=Ao.toJS(n,i,r);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function Cy(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(Su.isNode(r)&&t?.doc){let n=Ry.createStringifyContext(t.doc,{});n.anchors=new Set;for(let i of t.anchors.keys())n.anchors.add(i.anchor);n.inFlow=!0,n.inStringifyKey=!0;let s=r.toString(n);if(!t.mapKeyWarned){let i=JSON.stringify(s);i.length>40&&(i=i.substring(0,36)+'..."'),Oy.warn(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return s}return JSON.stringify(e)}ku.addPairToJSMap=_y});var Je=P(Po=>{"use strict";var xu=Tr(),Ny=gu(),Iy=To(),Qn=L();function Ly(r,e,t){let n=xu.createNode(r,void 0,t),s=xu.createNode(e,void 0,t);return new Xn(n,s)}var Xn=class r{constructor(e,t=null){Object.defineProperty(this,Qn.NODE_TYPE,{value:Qn.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Qn.isNode(t)&&(t=t.clone(e)),Qn.isNode(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return Iy.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?Ny.stringifyPair(this,e,t,n):JSON.stringify(this)}};Po.Pair=Xn;Po.createPair=Ly});var Oo=P(Au=>{"use strict";var at=L(),Eu=Cr(),Zn=Pr();function My(r,e,t){return(e.inFlow??r.flow?Dy:$y)(r,e,t)}function $y({comment:r,items:e},t,{blockItemPrefix:n,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,f=Object.assign({},t,{indent:i,type:null}),u=!1,d=[];for(let b=0;b<e.length;++b){let m=e[b],y=null;if(at.isNode(m))!u&&m.spaceBefore&&d.push(""),es(t,d,m.commentBefore,u),m.comment&&(y=m.comment);else if(at.isPair(m)){let T=at.isNode(m.key)?m.key:null;T&&(!u&&T.spaceBefore&&d.push(""),es(t,d,T.commentBefore,u))}u=!1;let E=Eu.stringify(m,f,()=>y=null,()=>u=!0);y&&(E+=Zn.lineComment(E,i,l(y))),u&&y&&(u=!1),d.push(n+E)}let p;if(d.length===0)p=s.start+s.end;else{p=d[0];for(let b=1;b<d.length;++b){let m=d[b];p+=m?`
|
|
56
56
|
${c}${m}`:`
|
|
57
57
|
`}}return r?(p+=`
|
|
58
|
-
`+
|
|
58
|
+
`+Zn.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function Dy({items:r},e,{flowChars:t,itemIndent:n}){let{indent:s,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let b=0;b<r.length;++b){let m=r[b],y=null;if(at.isNode(m))m.spaceBefore&&u.push(""),es(e,u,m.commentBefore,!1),m.comment&&(y=m.comment);else if(at.isPair(m)){let T=at.isNode(m.key)?m.key:null;T&&(T.spaceBefore&&u.push(""),es(e,u,T.commentBefore,!1),T.comment&&(l=!0));let g=at.isNode(m.value)?m.value:null;g?(g.comment&&(y=g.comment),g.commentBefore&&(l=!0)):m.value==null&&T?.comment&&(y=T.comment)}y&&(l=!0);let E=Eu.stringify(m,c,()=>y=null);b<r.length-1&&(E+=","),y&&(E+=Zn.lineComment(E,n,a(y))),!l&&(u.length>f||E.includes(`
|
|
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
|
|
63
|
-
`:" ")}return
|
|
62
|
+
${s}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function es({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=Zn.indentComment(e(n),r);t.push(i.trimStart())}}Au.stringifyCollection=My});var We=P(_o=>{"use strict";var By=Oo(),jy=To(),Fy=qn(),Ke=L(),ts=Je(),qy=J();function Lr(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 Ro=class extends Fy.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(ts.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 ts.Pair(e,e?.value):n=new ts.Pair(e.key,e.value);let s=Lr(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);Ke.isScalar(s.value)&&qy.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=Lr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=Lr(this.items,e)?.value;return(!t&&Ke.isScalar(s)?s.value:s)??void 0}has(e){return!!Lr(this.items,e)}set(e,t){this.add(new ts.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)jy.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})),By.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};_o.YAMLMap=Ro;_o.findPair=Lr});var qt=P(Pu=>{"use strict";var Uy=L(),Tu=We(),Jy={collection:"map",default:!0,nodeClass:Tu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return Uy.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Tu.YAMLMap.from(r,e,t)};Pu.map=Jy});var He=P(Ou=>{"use strict";var Ky=Tr(),Wy=Oo(),Hy=qn(),ns=L(),Vy=J(),Yy=je(),Co=class extends Hy.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(ns.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=rs(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=rs(e);if(typeof n!="number")return;let s=this.items[n];return!t&&ns.isScalar(s)?s.value:s}has(e){let t=rs(e);return typeof t=="number"&&t<this.items.length}set(e,t){let n=rs(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[n];ns.isScalar(s)&&Vy.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(Yy.toJS(i,String(s++),t));return n}toString(e,t,n){return e?Wy.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(Ky.createNode(a,void 0,n))}}return i}};function rs(r){let e=ns.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Ou.YAMLSeq=Co});var Ut=P(_u=>{"use strict";var Gy=L(),Ru=He(),zy={collection:"seq",default:!0,nodeClass:Ru.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Gy.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Ru.YAMLSeq.from(r,e,t)};_u.seq=zy});var Mr=P(Cu=>{"use strict";var Qy=_r(),Xy={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),Qy.stringifyString(r,e,t,n)}};Cu.string=Xy});var ss=P(Lu=>{"use strict";var Nu=J(),Iu={identify:r=>r==null,createNode:()=>new Nu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Nu.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&Iu.test.test(r)?r:e.options.nullStr};Lu.nullTag=Iu});var No=P($u=>{"use strict";var Zy=J(),Mu={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new Zy.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Mu.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};$u.boolTag=Mu});var Jt=P(Du=>{"use strict";function eb({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}Du.stringifyNumber=eb});var Lo=P(is=>{"use strict";var tb=J(),Io=Jt(),rb={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:Io.stringifyNumber},nb={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():Io.stringifyNumber(r)}},sb={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 tb.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Io.stringifyNumber};is.float=sb;is.floatExp=nb;is.floatNaN=rb});var $o=P(as=>{"use strict";var Bu=Jt(),os=r=>typeof r=="bigint"||Number.isInteger(r),Mo=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function ju(r,e,t){let{value:n}=r;return os(n)&&n>=0?t+n.toString(e):Bu.stringifyNumber(r)}var ib={identify:r=>os(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>Mo(r,2,8,t),stringify:r=>ju(r,8,"0o")},ob={identify:os,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>Mo(r,0,10,t),stringify:Bu.stringifyNumber},ab={identify:r=>os(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>Mo(r,2,16,t),stringify:r=>ju(r,16,"0x")};as.int=ob;as.intHex=ab;as.intOct=ib});var qu=P(Fu=>{"use strict";var cb=qt(),lb=ss(),ub=Ut(),fb=Mr(),db=No(),Do=Lo(),Bo=$o(),pb=[cb.map,ub.seq,fb.string,lb.nullTag,db.boolTag,Bo.intOct,Bo.int,Bo.intHex,Do.floatNaN,Do.floatExp,Do.float];Fu.schema=pb});var Ku=P(Ju=>{"use strict";var mb=J(),hb=qt(),gb=Ut();function Uu(r){return typeof r=="bigint"||Number.isInteger(r)}var cs=({value:r})=>JSON.stringify(r),yb=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:cs},{identify:r=>r==null,createNode:()=>new mb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:cs},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:cs},{identify:Uu,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})=>Uu(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:cs}],bb={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},wb=[hb.map,gb.seq].concat(yb,bb);Ju.schema=wb});var Fo=P(Wu=>{"use strict";var $r=Rn("buffer"),jo=J(),vb=_r(),Sb={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=jo.Scalar.BLOCK_LITERAL),e!==jo.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===jo.Scalar.BLOCK_LITERAL?`
|
|
63
|
+
`:" ")}return vb.stringifyString({comment:r,type:e,value:a},n,s,i)}};Wu.binary=Sb});var fs=P(us=>{"use strict";var ls=L(),qo=Je(),kb=J(),xb=He();function Hu(r,e){if(ls.isSeq(r))for(let t=0;t<r.items.length;++t){let n=r.items[t];if(!ls.isPair(n)){if(ls.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let s=n.items[0]||new qo.Pair(new kb.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]=cs.isPair(n)?n:new jo.Pair(n)}}else e("Expected a sequence for this tag");return r}function Wu(r,e,t){let{replacer:n}=t,s=new mb.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(jo.createPair(a,c,t))}return s}var hb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ku,createNode:Wu};ls.createPairs=Wu;ls.pairs=hb;ls.resolvePairs=Ku});var Uo=P(qo=>{"use strict";var Hu=L(),Fo=je(),Mr=We(),gb=He(),Vu=us(),ct=class r extends gb.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(Hu.isPair(s)?(i=Fo.toJS(s.key,"",t),o=Fo.toJS(s.value,i,t)):i=Fo.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=Vu.createPairs(e,t,n),i=new this;return i.items=s.items,i}};ct.tag="tag:yaml.org,2002:omap";var yb={collection:"seq",identify:r=>r instanceof Map,nodeClass:ct,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Vu.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Hu.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)};qo.YAMLOMap=ct;qo.omap=yb});var Xu=P(Jo=>{"use strict";var Yu=J();function Gu({value:r,source:e},t){return e&&(r?zu:Qu).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var zu={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 Yu.Scalar(!0),stringify:Gu},Qu={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 Yu.Scalar(!1),stringify:Gu};Jo.falseTag=Qu;Jo.trueTag=zu});var Zu=P(fs=>{"use strict";var bb=J(),Ko=qt(),wb={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:Ko.stringifyNumber},vb={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():Ko.stringifyNumber(r)}},Sb={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 bb.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:Ko.stringifyNumber};fs.float=Sb;fs.floatExp=vb;fs.floatNaN=wb});var tf=P(Dr=>{"use strict";var ef=qt(),$r=r=>typeof r=="bigint"||Number.isInteger(r);function ds(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 Wo(r,e,t){let{value:n}=r;if($r(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return ef.stringifyNumber(r)}var kb={identify:$r,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>ds(r,2,2,t),stringify:r=>Wo(r,2,"0b")},xb={identify:$r,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>ds(r,1,8,t),stringify:r=>Wo(r,8,"0")},Eb={identify:$r,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>ds(r,0,10,t),stringify:ef.stringifyNumber},Ab={identify:$r,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>ds(r,2,16,t),stringify:r=>Wo(r,16,"0x")};Dr.int=Eb;Dr.intBin=kb;Dr.intHex=Ab;Dr.intOct=xb});var Vo=P(Ho=>{"use strict";var hs=L(),ps=Je(),ms=We(),lt=class r extends ms.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;hs.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new ps.Pair(e.key,null):t=new ps.Pair(e,null),ms.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=ms.findPair(this.items,e);return!t&&hs.isPair(n)?hs.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=ms.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new ps.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(ps.createPair(o,null,n));return i}};lt.tag="tag:yaml.org,2002:set";var Tb={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(hs.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}};Ho.YAMLSet=lt;Ho.set=Tb});var Go=P(gs=>{"use strict";var Pb=qt();function Yo(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 rf(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Pb.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 Ob={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})=>Yo(r,t),stringify:rf},Rb={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=>Yo(r,!1),stringify:rf},nf={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(nf.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=Yo(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$/,"")??""};gs.floatTime=Rb;gs.intTime=Ob;gs.timestamp=nf});var af=P(of=>{"use strict";var _b=jt(),Cb=ns(),Nb=Ft(),Ib=Ir(),Lb=Bo(),sf=Xu(),zo=Zu(),ys=tf(),Mb=Gn(),$b=Uo(),Db=us(),Bb=Vo(),Qo=Go(),jb=[_b.map,Nb.seq,Ib.string,Cb.nullTag,sf.trueTag,sf.falseTag,ys.intBin,ys.intOct,ys.int,ys.intHex,zo.floatNaN,zo.floatExp,zo.float,Lb.binary,Mb.merge,$b.omap,Db.pairs,Bb.set,Qo.intTime,Qo.floatTime,Qo.timestamp];of.schema=jb});var yf=P(ea=>{"use strict";var ff=jt(),Fb=ns(),df=Ft(),qb=Ir(),Ub=_o(),Xo=No(),Zo=Lo(),Jb=ju(),Kb=Uu(),pf=Bo(),Br=Gn(),mf=Uo(),hf=us(),cf=af(),gf=Vo(),bs=Go(),lf=new Map([["core",Jb.schema],["failsafe",[ff.map,df.seq,qb.string]],["json",Kb.schema],["yaml11",cf.schema],["yaml-1.1",cf.schema]]),uf={binary:pf.binary,bool:Ub.boolTag,float:Xo.float,floatExp:Xo.floatExp,floatNaN:Xo.floatNaN,floatTime:bs.floatTime,int:Zo.int,intHex:Zo.intHex,intOct:Zo.intOct,intTime:bs.intTime,map:ff.map,merge:Br.merge,null:Fb.nullTag,omap:mf.omap,pairs:hf.pairs,seq:df.seq,set:gf.set,timestamp:bs.timestamp},Wb={"tag:yaml.org,2002:binary":pf.binary,"tag:yaml.org,2002:merge":Br.merge,"tag:yaml.org,2002:omap":mf.omap,"tag:yaml.org,2002:pairs":hf.pairs,"tag:yaml.org,2002:set":gf.set,"tag:yaml.org,2002:timestamp":bs.timestamp};function Hb(r,e,t){let n=lf.get(e);if(n&&!r)return t&&!n.includes(Br.merge)?n.concat(Br.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(lf.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(Br.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?uf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(uf).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},[])}ea.coreKnownTags=Wb;ea.getTags=Hb});var na=P(bf=>{"use strict";var ta=L(),Vb=jt(),Yb=Ft(),Gb=Ir(),ws=yf(),zb=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,ra=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ws.getTags(e,"compat"):e?ws.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?ws.coreKnownTags:{},this.tags=ws.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,ta.MAP,{value:Vb.map}),Object.defineProperty(this,ta.SCALAR,{value:Gb.string}),Object.defineProperty(this,ta.SEQ,{value:Yb.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?zb:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};bf.Schema=ra});var vf=P(wf=>{"use strict";var Qb=L(),sa=Rr(),jr=Ar();function Xb(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=sa.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(jr.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(Qb.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let f=i(r.contents.commentBefore);t.push(jr.indentComment(f,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=sa.stringify(r.contents,s,()=>a=null,c);a&&(l+=jr.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(sa.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
66
|
-
`)?(t.push("..."),t.push(
|
|
65
|
+
${i.comment}`:n.comment}n=s}r.items[t]=ls.isPair(n)?n:new qo.Pair(n)}}else e("Expected a sequence for this tag");return r}function Vu(r,e,t){let{replacer:n}=t,s=new xb.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(qo.createPair(a,c,t))}return s}var Eb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Hu,createNode:Vu};us.createPairs=Vu;us.pairs=Eb;us.resolvePairs=Hu});var Ko=P(Jo=>{"use strict";var Yu=L(),Uo=je(),Dr=We(),Ab=He(),Gu=fs(),ct=class r extends Ab.YAMLSeq{constructor(){super(),this.add=Dr.YAMLMap.prototype.add.bind(this),this.delete=Dr.YAMLMap.prototype.delete.bind(this),this.get=Dr.YAMLMap.prototype.get.bind(this),this.has=Dr.YAMLMap.prototype.has.bind(this),this.set=Dr.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(Yu.isPair(s)?(i=Uo.toJS(s.key,"",t),o=Uo.toJS(s.value,i,t)):i=Uo.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=Gu.createPairs(e,t,n),i=new this;return i.items=s.items,i}};ct.tag="tag:yaml.org,2002:omap";var Tb={collection:"seq",identify:r=>r instanceof Map,nodeClass:ct,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Gu.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Yu.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)};Jo.YAMLOMap=ct;Jo.omap=Tb});var ef=P(Wo=>{"use strict";var zu=J();function Qu({value:r,source:e},t){return e&&(r?Xu:Zu).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Xu={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 zu.Scalar(!0),stringify:Qu},Zu={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 zu.Scalar(!1),stringify:Qu};Wo.falseTag=Zu;Wo.trueTag=Xu});var tf=P(ds=>{"use strict";var Pb=J(),Ho=Jt(),Ob={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:Ho.stringifyNumber},Rb={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():Ho.stringifyNumber(r)}},_b={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 Pb.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:Ho.stringifyNumber};ds.float=_b;ds.floatExp=Rb;ds.floatNaN=Ob});var nf=P(jr=>{"use strict";var rf=Jt(),Br=r=>typeof r=="bigint"||Number.isInteger(r);function ps(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 Vo(r,e,t){let{value:n}=r;if(Br(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return rf.stringifyNumber(r)}var Cb={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>ps(r,2,2,t),stringify:r=>Vo(r,2,"0b")},Nb={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>ps(r,1,8,t),stringify:r=>Vo(r,8,"0")},Ib={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>ps(r,0,10,t),stringify:rf.stringifyNumber},Lb={identify:Br,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>ps(r,2,16,t),stringify:r=>Vo(r,16,"0x")};jr.int=Ib;jr.intBin=Cb;jr.intHex=Lb;jr.intOct=Nb});var Go=P(Yo=>{"use strict";var gs=L(),ms=Je(),hs=We(),lt=class r extends hs.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;gs.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new ms.Pair(e.key,null):t=new ms.Pair(e,null),hs.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=hs.findPair(this.items,e);return!t&&gs.isPair(n)?gs.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=hs.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new ms.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(ms.createPair(o,null,n));return i}};lt.tag="tag:yaml.org,2002:set";var Mb={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(gs.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}};Yo.YAMLSet=lt;Yo.set=Mb});var Qo=P(ys=>{"use strict";var $b=Jt();function zo(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 sf(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return $b.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 Db={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})=>zo(r,t),stringify:sf},Bb={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=>zo(r,!1),stringify:sf},of={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(of.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=zo(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$/,"")??""};ys.floatTime=Bb;ys.intTime=Db;ys.timestamp=of});var lf=P(cf=>{"use strict";var jb=qt(),Fb=ss(),qb=Ut(),Ub=Mr(),Jb=Fo(),af=ef(),Xo=tf(),bs=nf(),Kb=zn(),Wb=Ko(),Hb=fs(),Vb=Go(),Zo=Qo(),Yb=[jb.map,qb.seq,Ub.string,Fb.nullTag,af.trueTag,af.falseTag,bs.intBin,bs.intOct,bs.int,bs.intHex,Xo.floatNaN,Xo.floatExp,Xo.float,Jb.binary,Kb.merge,Wb.omap,Hb.pairs,Vb.set,Zo.intTime,Zo.floatTime,Zo.timestamp];cf.schema=Yb});var wf=P(ra=>{"use strict";var pf=qt(),Gb=ss(),mf=Ut(),zb=Mr(),Qb=No(),ea=Lo(),ta=$o(),Xb=qu(),Zb=Ku(),hf=Fo(),Fr=zn(),gf=Ko(),yf=fs(),uf=lf(),bf=Go(),ws=Qo(),ff=new Map([["core",Xb.schema],["failsafe",[pf.map,mf.seq,zb.string]],["json",Zb.schema],["yaml11",uf.schema],["yaml-1.1",uf.schema]]),df={binary:hf.binary,bool:Qb.boolTag,float:ea.float,floatExp:ea.floatExp,floatNaN:ea.floatNaN,floatTime:ws.floatTime,int:ta.int,intHex:ta.intHex,intOct:ta.intOct,intTime:ws.intTime,map:pf.map,merge:Fr.merge,null:Gb.nullTag,omap:gf.omap,pairs:yf.pairs,seq:mf.seq,set:bf.set,timestamp:ws.timestamp},ew={"tag:yaml.org,2002:binary":hf.binary,"tag:yaml.org,2002:merge":Fr.merge,"tag:yaml.org,2002:omap":gf.omap,"tag:yaml.org,2002:pairs":yf.pairs,"tag:yaml.org,2002:set":bf.set,"tag:yaml.org,2002:timestamp":ws.timestamp};function tw(r,e,t){let n=ff.get(e);if(n&&!r)return t&&!n.includes(Fr.merge)?n.concat(Fr.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(ff.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(Fr.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?df[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(df).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},[])}ra.coreKnownTags=ew;ra.getTags=tw});var ia=P(vf=>{"use strict";var na=L(),rw=qt(),nw=Ut(),sw=Mr(),vs=wf(),iw=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,sa=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?vs.getTags(e,"compat"):e?vs.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?vs.coreKnownTags:{},this.tags=vs.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,na.MAP,{value:rw.map}),Object.defineProperty(this,na.SCALAR,{value:sw.string}),Object.defineProperty(this,na.SEQ,{value:nw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?iw:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};vf.Schema=sa});var kf=P(Sf=>{"use strict";var ow=L(),oa=Cr(),qr=Pr();function aw(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=oa.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(qr.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(ow.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let f=i(r.contents.commentBefore);t.push(qr.indentComment(f,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=oa.stringify(r.contents,s,()=>a=null,c);a&&(l+=qr.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(oa.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
66
|
+
`)?(t.push("..."),t.push(qr.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(qr.indentComment(i(c),"")))}return t.join(`
|
|
67
67
|
`)+`
|
|
68
|
-
`}
|
|
68
|
+
`}Sf.stringifyDocument=aw});var Ur=P(xf=>{"use strict";var cw=Ar(),Kt=qn(),ie=L(),lw=Je(),uw=je(),fw=ia(),dw=kf(),aa=Dn(),pw=uo(),mw=Tr(),ca=lo(),la=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 ca.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){Wt(this.contents)&&this.contents.add(e)}addIn(e,t){Wt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=aa.anchorNames(this);e.anchor=!t||n.has(t)?aa.findNewAnchor(t||"a",n):t}return new cw.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}=aa.createNodeAnchors(this,o||"a"),b={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},m=mw.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 lw.Pair(s,i)}delete(e){return Wt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Kt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Wt(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 Kt.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 Kt.isEmptyPath(e)?this.contents!==void 0:ie.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Kt.collectionFromPath(this.schema,[e],t):Wt(this.contents)&&this.contents.set(e,t)}setIn(e,t){Kt.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=Kt.collectionFromPath(this.schema,Array.from(e),t):Wt(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 ca.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 ca.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 fw.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=uw.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"?pw.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 dw.stringifyDocument(this,e)}};function Wt(r){if(ie.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}xf.Document=la});var Wr=P(Kr=>{"use strict";var Jr=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},ua=class extends Jr{constructor(e,t,n){super("YAMLParseError",e,t,n)}},fa=class extends Jr{constructor(e,t,n){super("YAMLWarning",e,t,n)}},hw=(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}
|
|
72
72
|
${l}
|
|
73
|
-
`}};
|
|
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(
|
|
75
|
-
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||
|
|
76
|
-
`+g.comment:T.comment=g.comment);let w=new
|
|
77
|
-
`+x.comment:l.comment=x.comment),u=x.end;continue}!o&&t.options.strict&&
|
|
78
|
-
`+O:A.comment=O,x.comment=x.comment.substring(O.length+1)}}if(!o&&!w&&!x.found){let O=k?r(t,k,x,s):e(t,x.end,w,null,x,s);l.items.push(O),u=O.range[2],
|
|
79
|
-
`+M.comment:A.comment=M.comment);let V=new
|
|
80
|
-
`+y.comment:l.comment=y.comment),l.range=[n.offset,m,y.offset]}else l.range=[n.offset,m,m];return l}
|
|
73
|
+
`}};Kr.YAMLError=Jr;Kr.YAMLParseError=ua;Kr.YAMLWarning=fa;Kr.prettifyError=hw});var Hr=P(Ef=>{"use strict";function gw(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,k=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 M=A.source.substring(1)||" ";u?u+=d+M:u=M,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,k??(k=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,k??(k=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:k??O}}Ef.resolveProps=gw});var Ss=P(Af=>{"use strict";function da(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
|
+
`))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(da(e.key)||da(e.value))return!0}return!1;default:return!0}}Af.containsNewline=da});var pa=P(Tf=>{"use strict";var yw=Ss();function bw(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&yw.containsNewline(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Tf.flowIndentCheck=bw});var ma=P(Of=>{"use strict";var Pf=L();function ww(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(i,o)=>i===o||Pf.isScalar(i)&&Pf.isScalar(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}Of.mapIncludes=ww});var Lf=P(If=>{"use strict";var Rf=Je(),vw=We(),_f=Hr(),Sw=Ss(),Cf=pa(),kw=ma(),Nf="All mapping items must start at the same column";function xw({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??vw.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=_f.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",Nf)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=`
|
|
75
|
+
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||Sw.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",Nf);t.atKey=!0;let E=m.end,T=d?r(t,d,m,s):e(t,E,u,null,m,s);t.schema.compat&&Cf.flowIndentCheck(n.indent,d,s),t.atKey=!1,kw.mapIncludes(t,a.items,T)&&s(E,"DUPLICATE_KEY","Map keys must be unique");let g=_f.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&&Cf.flowIndentCheck(n.indent,b,s),c=w.range[2];let k=new Rf.Pair(T,w);t.options.keepSourceTokens&&(k.srcToken=f),a.items.push(k)}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 Rf.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}If.resolveBlockMap=xw});var $f=P(Mf=>{"use strict";var Ew=He(),Aw=Hr(),Tw=pa();function Pw({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Ew.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=Aw.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&&Tw.flowIndentCheck(n.indent,u,s),c=p.range[2],a.items.push(p)}return a.range=[n.offset,c,l??c],a}Mf.resolveBlockSeq=Pw});var Ht=P(Df=>{"use strict";function Ow(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}}Df.resolveEnd=Ow});var qf=P(Ff=>{"use strict";var Rw=L(),_w=Je(),Bf=We(),Cw=He(),Nw=Ht(),jf=Hr(),Iw=Ss(),Lw=ma(),ha="Block collections are not allowed within flow collections",ga=r=>r&&(r.type==="block-map"||r.type==="block-seq");function Mw({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?Bf.YAMLMap:Cw.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:k}=E,x=jf.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&&!k){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
|
+
`+x.comment:l.comment=x.comment),u=x.end;continue}!o&&t.options.strict&&Iw.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];Rw.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=k?r(t,k,x,s):e(t,x.end,w,null,x,s);l.items.push(O),u=O.range[2],ga(k)&&s(O.range,"BLOCK_IN_FLOW",ha)}else{t.atKey=!0;let O=x.end,A=g?r(t,g,x,s):e(t,O,T,null,x,s);ga(g)&&s(A.range,"BLOCK_IN_FLOW",ha),t.atKey=!1;let M=jf.resolveProps(w??[],{flow:a,indicator:"map-value-ind",next:k,offset:A.range[2],onError:s,parentIndent:n.indent,startOnNewline:!1});if(M.found){if(!o&&!x.found&&t.options.strict){if(w)for(let B of w){if(B===M.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<M.found.offset-1024&&s(M.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?s(k,"MISSING_CHAR",`Missing space after : in ${a}`):s(M.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let te=k?r(t,k,M,s):M.found?e(t,M.end,w,null,M,s):null;te?ga(k)&&s(te.range,"BLOCK_IN_FLOW",ha):M.comment&&(A.comment?A.comment+=`
|
|
79
|
+
`+M.comment:A.comment=M.comment);let V=new _w.Pair(A,te);if(t.options.keepSourceTokens&&(V.srcToken=E),o){let B=l;Lw.mapIncludes(t,B.items,A)&&s(O,"DUPLICATE_KEY","Map keys must be unique"),B.items.push(V)}else{let B=new Bf.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]:M.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=Nw.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}Ff.resolveFlowCollection=Mw});var Jf=P(Uf=>{"use strict";var $w=L(),Dw=J(),Bw=We(),jw=He(),Fw=Lf(),qw=$f(),Uw=qf();function ya(r,e,t,n,s,i){let o=t.type==="block-map"?Fw.resolveBlockMap(r,e,t,n,i):t.type==="block-seq"?qw.resolveBlockSeq(r,e,t,n,i):Uw.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 Jw(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===Bw.YAMLMap.tagName&&a==="map"||o===jw.YAMLSeq.tagName&&a==="seq")return ya(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),ya(r,e,t,s,o)}let l=ya(r,e,t,s,o,c),f=c.resolve?.(l,d=>s(i,"TAG_RESOLVE_FAILED",d),e.options)??l,u=$w.isNode(f)?f:new Dw.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Uf.composeCollection=Jw});var wa=P(Kf=>{"use strict";var ba=J();function Kw(r,e,t){let n=e.offset,s=Ww(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?ba.Scalar.BLOCK_FOLDED:ba.Scalar.BLOCK_LITERAL,o=e.source?Hw(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
|
-
`;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===
|
|
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===ba.Scalar.BLOCK_LITERAL?(u+=d+y.slice(c)+E,d=`
|
|
83
83
|
`):y.length>c||E[0]===" "?(d===" "?d=`
|
|
84
84
|
`:!p&&d===`
|
|
85
85
|
`&&(d=`
|
|
@@ -92,68 +92,68 @@ ${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
|
|
95
|
+
`}let b=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,b,b]}}function Ww({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 Hw(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}Kf.resolveBlockScalar=Kw});var Sa=P(Hf=>{"use strict";var va=J(),Vw=Ht();function Yw(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=va.Scalar.PLAIN,c=Gw(i,l);break;case"single-quoted-scalar":a=va.Scalar.QUOTE_SINGLE,c=zw(i,l);break;case"double-quoted-scalar":a=va.Scalar.QUOTE_DOUBLE,c=Qw(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=Vw.resolveEnd(o,f,e,t);return{value:c,type:a,comment:u.comment,range:[n,f,u.offset]}}function Gw(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}`),Wf(r)}function zw(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),Wf(r.slice(1,-1)).replace(/''/g,"'")}function Wf(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=`
|
|
99
|
-
`:(s+=i+n[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(r),s+i+(n?.[1]??"")}function
|
|
99
|
+
`:(s+=i+n[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(r),s+i+(n?.[1]??"")}function Qw(r,e){let t="";for(let n=1;n<r.length-1;++n){let s=r[n];if(!(s==="\r"&&r[n+1]===`
|
|
100
100
|
`))if(s===`
|
|
101
|
-
`){let{fold:i,offset:o}=
|
|
101
|
+
`){let{fold:i,offset:o}=Xw(r,n);t+=i,n=o}else if(s==="\\"){let i=r[++n],o=Zw[i];if(o)t+=o;else if(i===`
|
|
102
102
|
`)for(i=r[n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="\r"&&r[n+1]===`
|
|
103
|
-
`)for(i=r[++n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=
|
|
103
|
+
`)for(i=r[++n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=ev(r,n+1,a,e),n+=a}else{let a=r.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(s===" "||s===" "){let i=n,o=r[n+1];for(;o===" "||o===" ";)o=r[++n+1];o!==`
|
|
104
104
|
`&&!(o==="\r"&&r[n+2]===`
|
|
105
|
-
`)&&(t+=n>i?r.slice(i,n+1):s)}else t+=s}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function
|
|
105
|
+
`)&&(t+=n>i?r.slice(i,n+1):s)}else t+=s}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function Xw(r,e){let t="",n=r[e+1];for(;(n===" "||n===" "||n===`
|
|
106
106
|
`||n==="\r")&&!(n==="\r"&&r[e+2]!==`
|
|
107
107
|
`);)n===`
|
|
108
108
|
`&&(t+=`
|
|
109
|
-
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var
|
|
110
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
109
|
+
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var Zw={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 ev(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)}Hf.resolveFlowScalar=Yw});var Gf=P(Yf=>{"use strict";var ut=L(),Vf=J(),tv=wa(),rv=Sa();function nv(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?tv.resolveBlockScalar(r,e,n):rv.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=sv(r.schema,s,c,t,n):e.type==="scalar"?l=iv(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 Vf.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);n(t??e,"TAG_RESOLVE_FAILED",d),f=new Vf.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 sv(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 iv({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}Yf.composeScalar=nv});var Qf=P(zf=>{"use strict";function ov(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}zf.emptyScalarPosition=ov});var ed=P(xa=>{"use strict";var av=Ar(),cv=L(),lv=Jf(),Xf=Gf(),uv=Ht(),fv=Qf(),dv={composeNode:Zf,composeEmptyNode:ka};function Zf(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=pv(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=Xf.composeScalar(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=lv.composeCollection(dv,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=ka(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&&(!cv.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 ka(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:fv.emptyScalarPosition(e,t,n),indent:-1,source:""},u=Xf.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 pv({options:r},{offset:e,source:t,end:n},s){let i=new av.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=uv.resolveEnd(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}xa.composeEmptyNode=ka;xa.composeNode=Zf});var nd=P(rd=>{"use strict";var mv=Ur(),td=ed(),hv=Ht(),gv=Hr();function yv(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new mv.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=gv.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?td.composeNode(l,s,f,o):td.composeEmptyNode(l,f.end,n,null,f,o);let u=c.contents.range[2],d=hv.resolveEnd(i,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[t,u,d.offset],c}rd.composeDoc=yv});var Aa=P(od=>{"use strict";var bv=Rn("process"),wv=lo(),vv=Ur(),Vr=Wr(),sd=L(),Sv=nd(),kv=Ht();function Yr(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 id(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
|
-
`)+(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
|
|
114
|
-
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(
|
|
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 Ea=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=Yr(t);i?this.warnings.push(new Vr.YAMLWarning(o,n,s)):this.errors.push(new Vr.YAMLParseError(o,n,s))},this.directives=new wv.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=id(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}
|
|
114
|
+
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(sd.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];sd.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n}
|
|
115
115
|
${a}`:n}else{let o=i.commentBefore;i.commentBefore=o?`${n}
|
|
116
|
-
${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
117
|
-
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new
|
|
116
|
+
${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:id(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let s of e)yield*this.next(s);yield*this.end(t,n)}*next(e){switch(bv.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,n,s)=>{let i=Yr(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=Sv.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new Vr.YAMLParseError(Yr(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new Vr.YAMLParseError(Yr(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=kv.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
|
|
117
|
+
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Vr.YAMLParseError(Yr(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),s=new vv.Document(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),s.range=[0,t,t],this.decorate(s,!1),yield s}}};od.Composer=Ea});var ld=P(ks=>{"use strict";var xv=wa(),Ev=Sa(),Av=Wr(),ad=_r();function Tv(r,e=!0,t){if(r){let n=(s,i,o)=>{let a=typeof s=="number"?s:Array.isArray(s)?s[0]:s.offset;if(t)t(a,i,o);else throw new Av.YAMLParseError([a,a+1],i,o)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Ev.resolveFlowScalar(r,e,n);case"block-scalar":return xv.resolveBlockScalar({options:{strict:e}},r,n)}}return null}function Pv(r,e){let{implicitKey:t=!1,indent:n,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=e,a=ad.stringifyString({type:o,value:r},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
|
|
118
118
|
`}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
|
|
119
119
|
`),f=a.substring(0,l),u=a.substring(l+1)+`
|
|
120
|
-
`,d=[{type:"block-scalar-header",offset:i,indent:n,source:f}];return
|
|
121
|
-
`}),{type:"block-scalar",offset:i,indent:n,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:c};default:return{type:"scalar",offset:i,indent:n,source:a,end:c}}}function
|
|
120
|
+
`,d=[{type:"block-scalar-header",offset:i,indent:n,source:f}];return cd(d,c)||d.push({type:"newline",offset:-1,indent:n,source:`
|
|
121
|
+
`}),{type:"block-scalar",offset:i,indent:n,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:c};default:return{type:"scalar",offset:i,indent:n,source:a,end:c}}}function Ov(r,e,t={}){let{afterKey:n=!1,implicitKey:s=!1,inFlow:i=!1,type:o}=t,a="indent"in r?r.indent:null;if(n&&typeof a=="number"&&(a+=2),!o)switch(r.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=r.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=ad.stringifyString({type:o,value:e},{implicitKey:s||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Rv(r,c);break;case'"':Ta(r,c,"double-quoted-scalar");break;case"'":Ta(r,c,"single-quoted-scalar");break;default:Ta(r,c,"scalar")}}function Rv(r,e){let t=e.indexOf(`
|
|
122
122
|
`),n=e.substring(0,t),s=e.substring(t+1)+`
|
|
123
|
-
`;if(r.type==="block-scalar"){let i=r.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=n,r.source=s}else{let{offset:i}=r,o="indent"in r?r.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:n}];
|
|
124
|
-
`});for(let c of Object.keys(r))c!=="type"&&c!=="offset"&&delete r[c];Object.assign(r,{type:"block-scalar",indent:o,props:a,source:s})}}function
|
|
125
|
-
`};delete r.items,Object.assign(r,{type:t,source:e,end:[s]});break}default:{let n="indent"in r?r.indent:-1,s="end"in r&&Array.isArray(r.end)?r.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(r))i!=="type"&&i!=="offset"&&delete r[i];Object.assign(r,{type:t,indent:n,source:e,end:s})}}}
|
|
123
|
+
`;if(r.type==="block-scalar"){let i=r.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=n,r.source=s}else{let{offset:i}=r,o="indent"in r?r.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:n}];cd(a,"end"in r?r.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
|
|
124
|
+
`});for(let c of Object.keys(r))c!=="type"&&c!=="offset"&&delete r[c];Object.assign(r,{type:"block-scalar",indent:o,props:a,source:s})}}function cd(r,e){if(e)for(let t of e)switch(t.type){case"space":case"comment":r.push(t);break;case"newline":return r.push(t),!0}return!1}function Ta(r,e,t){switch(r.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":r.type=t,r.source=e;break;case"block-scalar":{let n=r.props.slice(1),s=e.length;r.props[0].type==="block-scalar-header"&&(s-=r.props[0].source.length);for(let i of n)i.offset+=s;delete r.props,Object.assign(r,{type:t,source:e,end:n});break}case"block-map":case"block-seq":{let s={type:"newline",offset:r.offset+e.length,indent:r.indent,source:`
|
|
125
|
+
`};delete r.items,Object.assign(r,{type:t,source:e,end:[s]});break}default:{let n="indent"in r?r.indent:-1,s="end"in r&&Array.isArray(r.end)?r.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(r))i!=="type"&&i!=="offset"&&delete r[i];Object.assign(r,{type:t,indent:n,source:e,end:s})}}}ks.createScalarToken=Pv;ks.resolveAsScalar=Tv;ks.setScalarValue=Ov});var fd=P(ud=>{"use strict";var _v=r=>"type"in r?Es(r):xs(r);function Es(r){switch(r.type){case"block-scalar":{let e="";for(let t of r.props)e+=Es(t);return e+r.source}case"block-map":case"block-seq":{let e="";for(let t of r.items)e+=xs(t);return e}case"flow-collection":{let e=r.start.source;for(let t of r.items)e+=xs(t);for(let t of r.end)e+=t.source;return e}case"document":{let e=xs(r);if(r.end)for(let t of r.end)e+=t.source;return e}default:{let e=r.source;if("end"in r&&r.end)for(let t of r.end)e+=t.source;return e}}}function xs({start:r,key:e,sep:t,value:n}){let s="";for(let i of r)s+=i.source;if(e&&(s+=Es(e)),t)for(let i of t)s+=i.source;return n&&(s+=Es(n)),s}ud.stringify=_v});var hd=P(md=>{"use strict";var Pa=Symbol("break visit"),Cv=Symbol("skip children"),dd=Symbol("remove item");function ft(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),pd(Object.freeze([]),r,e)}ft.BREAK=Pa;ft.SKIP=Cv;ft.REMOVE=dd;ft.itemAtPath=(r,e)=>{let t=r;for(let[n,s]of e){let i=t?.[n];if(i&&"items"in i)t=i.items[s];else return}return t};ft.parentCollection=(r,e)=>{let t=ft.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],s=t?.[n];if(s&&"items"in s)return s;throw new Error("Parent collection not found")};function pd(r,e,t){let n=t(e,r);if(typeof n=="symbol")return n;for(let s of["key","value"]){let i=e[s];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){let a=pd(Object.freeze(r.concat([[s,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Pa)return Pa;a===dd&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&s==="key"&&(n=n(e,r))}}return typeof n=="function"?n(e,r):n}md.visit=ft});var As=P(ne=>{"use strict";var Oa=ld(),Nv=fd(),Iv=hd(),Ra="\uFEFF",_a="",Ca="",Na="",Lv=r=>!!r&&"items"in r,Mv=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar");function $v(r){switch(r){case Ra:return"<BOM>";case _a:return"<DOC>";case Ca:return"<FLOW_END>";case Na:return"<SCALAR>";default:return JSON.stringify(r)}}function Dv(r){switch(r){case Ra:return"byte-order-mark";case _a:return"doc-mode";case Ca:return"flow-error-end";case Na:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
126
126
|
`:case`\r
|
|
127
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ne.createScalarToken=
|
|
128
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
129
|
-
\r `),
|
|
127
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ne.createScalarToken=Oa.createScalarToken;ne.resolveAsScalar=Oa.resolveAsScalar;ne.setScalarValue=Oa.setScalarValue;ne.stringify=Nv.stringify;ne.visit=Iv.visit;ne.BOM=Ra;ne.DOCUMENT=_a;ne.FLOW_END=Ca;ne.SCALAR=Na;ne.isCollection=Lv;ne.isScalar=Mv;ne.prettyToken=$v;ne.tokenType=Dv});var Ma=P(yd=>{"use strict";var Gr=As();function ue(r){switch(r){case void 0:case" ":case`
|
|
128
|
+
`:case"\r":case" ":return!0;default:return!1}}var gd=new Set("0123456789ABCDEFabcdef"),Bv=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ts=new Set(",[]{}"),jv=new Set(` ,[]{}
|
|
129
|
+
\r `),Ia=r=>!r||jv.has(r),La=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
|
|
130
130
|
`?!0:t==="\r"?this.buffer[e+1]===`
|
|
131
131
|
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){let s=this.buffer[n+e+1];if(s===`
|
|
132
132
|
`||!s&&!this.atEnd)return e+n+1}return t===`
|
|
133
133
|
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&ue(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
134
|
-
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===
|
|
134
|
+
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Gr.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,n=e.indexOf("#");for(;n!==-1;){let i=e[n-1];if(i===" "||i===" "){t=n-1;break}else n=e.indexOf("#",n+1)}for(;;){let i=e[t-1];if(i===" "||i===" ")t-=1;else break}let s=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-s),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield Gr.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&ue(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ue(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&ue(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Ia),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let s=this.getLine();if(s===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&s[0]!=="#"||n===0&&(s.startsWith("---")||s.startsWith("..."))&&ue(s[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield Gr.FLOW_END,yield*this.parseLineStart();let i=0;for(;s[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),s[i]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Ia),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||ue(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let i=0;for(;this.buffer[t-1-i]==="\\";)i+=1;if(i%2===0)break;t=this.buffer.indexOf('"',t+1)}let n=this.buffer.substring(0,t),s=n.indexOf(`
|
|
135
135
|
`,this.pos);if(s!==-1){for(;s!==-1;){let i=this.continueScalar(s+1);if(i===-1)break;s=n.indexOf(`
|
|
136
136
|
`,i)}s!==-1&&(t=s-(n[s-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>ue(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let i=this.pos;n=this.buffer[i];++i)switch(n){case" ":t+=1;break;case`
|
|
137
137
|
`:e=i,t=0;break;case"\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
138
138
|
`)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(`
|
|
139
139
|
`,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let s=e+1;for(n=this.buffer[s];n===" ";)n=this.buffer[++s];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
|
|
140
140
|
`;)n=this.buffer[++s];e=s-1}else if(!this.blockScalarKeep)do{let i=e-1,o=this.buffer[i];o==="\r"&&(o=this.buffer[--i]);let a=i;for(;o===" ";)o=this.buffer[--i];if(o===`
|
|
141
|
-
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield
|
|
141
|
+
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield Gr.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,s;for(;s=this.buffer[++n];)if(s===":"){let i=this.buffer[n+1];if(ue(i)||e&&Ts.has(i))break;t=n}else if(ue(s)){let i=this.buffer[n+1];if(s==="\r"&&(i===`
|
|
142
142
|
`?(n+=1,s=`
|
|
143
|
-
`,i=this.buffer[n+1]):t=n),i==="#"||e&&
|
|
144
|
-
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&
|
|
143
|
+
`,i=this.buffer[n+1]):t=n),i==="#"||e&&Ts.has(i))break;if(s===`
|
|
144
|
+
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Ts.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield Gr.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(Ia))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(ue(t)||e&&Ts.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(Bv.has(t))t=this.buffer[++e];else if(t==="%"&&gd.has(this.buffer[e+1])&&gd.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)}};
|
|
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)}};yd.Lexer=La});var Da=P(bd=>{"use strict";var $a=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}}}};bd.LineCounter=$a});var ja=P(xd=>{"use strict";var Fv=Rn("process"),wd=As(),qv=Ma();function Ve(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function vd(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 kd(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 Ps(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 Vt(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 Sd(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,kd(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 Ba=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 qv.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,Fv.env.LOG_TOKENS&&console.log("|",wd.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=wd.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"&&Sd(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&&vd(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":{vd(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=Ps(this.peek(2)),n=Vt(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
|
-
`,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(
|
|
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(kd(t.key)&&!Ve(t.sep,"newline")){let o=Vt(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=Vt(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=Ps(n),i=Vt(s);Sd(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=
|
|
151
|
-
`),t=e.trim();if(
|
|
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=Ps(e),n=Vt(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=Ps(e),n=Vt(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())}}};xd.Parser=Ba});var Od=P(Qr=>{"use strict";var Ed=Aa(),Uv=Ur(),zr=Wr(),Jv=xo(),Kv=L(),Wv=Da(),Ad=ja();function Td(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new Wv.LineCounter||null,prettyErrors:e}}function Hv(r,e={}){let{lineCounter:t,prettyErrors:n}=Td(e),s=new Ad.Parser(t?.addNewLine),i=new Ed.Composer(e),o=Array.from(i.compose(s.parse(r)));if(n&&t)for(let a of o)a.errors.forEach(zr.prettifyError(r,t)),a.warnings.forEach(zr.prettifyError(r,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Pd(r,e={}){let{lineCounter:t,prettyErrors:n}=Td(e),s=new Ad.Parser(t?.addNewLine),i=new Ed.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 zr.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(zr.prettifyError(r,t)),o.warnings.forEach(zr.prettifyError(r,t))),o}function Vv(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=Pd(r,t);if(!s)return null;if(s.warnings.forEach(i=>Jv.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 Yv(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 Kv.isDocument(r)&&!n?r.toString(t):new Uv.Document(r,n,t).toString(t)}Qr.parse=Vv;Qr.parseAllDocuments=Hv;Qr.parseDocument=Pd;Qr.stringify=Yv});var _d=P(D=>{"use strict";var Gv=Aa(),zv=Ur(),Qv=ia(),Fa=Wr(),Xv=Ar(),Ye=L(),Zv=Je(),eS=J(),tS=We(),rS=He(),nS=As(),sS=Ma(),iS=Da(),oS=ja(),Os=Od(),Rd=Sr();D.Composer=Gv.Composer;D.Document=zv.Document;D.Schema=Qv.Schema;D.YAMLError=Fa.YAMLError;D.YAMLParseError=Fa.YAMLParseError;D.YAMLWarning=Fa.YAMLWarning;D.Alias=Xv.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=Zv.Pair;D.Scalar=eS.Scalar;D.YAMLMap=tS.YAMLMap;D.YAMLSeq=rS.YAMLSeq;D.CST=nS;D.Lexer=sS.Lexer;D.LineCounter=iS.LineCounter;D.Parser=oS.Parser;D.parse=Os.parse;D.parseAllDocuments=Os.parseAllDocuments;D.parseDocument=Os.parseDocument;D.stringify=Os.stringify;D.visit=Rd.visit;D.visitAsync=Rd.visitAsync});function cS(r){try{return JSON.parse(r.trim()),!0}catch{return!1}}function lS(r){let e=r.trim();if(!e.startsWith("<"))return!1;let t=e.match(aS);return t?vr(e,t[1])!==null:!1}function uS(r){let e=r.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=Cd.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function Nd(r){return cS(r)||lS(r)||uS(r)}var Cd,aS,qa=R(()=>{ql();Cd=bg(_d(),1),aS=/<([a-zA-Z_][\w.-]*)/});function fS(r){if(!r?.trim())return[];let e=r.replace(/\r\n/g,`
|
|
151
|
+
`),t=e.trim();if(Nd(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(`
|
|
154
|
-
`).trim();l&&s.push({text:l,startLine:i+1,endLine:o+1})}};for(let l=0;l<n.length;l++)n[l].trim()?(a>=2&&o>=i&&(c(),i=l),a=0,o=l):a++;return c(),s}function
|
|
155
|
-
`)).map(e=>e.root)}function
|
|
156
|
-
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of
|
|
154
|
+
`).trim();l&&s.push({text:l,startLine:i+1,endLine:o+1})}};for(let l=0;l<n.length;l++)n[l].trim()?(a>=2&&o>=i&&(c(),i=l),a=0,o=l):a++;return c(),s}function Id(r){return fS(r).map(e=>e.text)}var Ld=R(()=>{qa()});var Xr=R(()=>{_n();_l();Nl();Ll();qa();Ld();Cn()});function Yt(r){return{...Rl(r),server:r.files.get("server.ts")??""}}function Rs(r){return!!r.server&&!r.code}var Zr=R(()=>{Xr();Xr()});function hS(r){if(/^[./]/.test(r)||/^[a-z][a-z0-9+.-]*:/i.test(r))return null;let e=r.split("/");return r.startsWith("@")?e.slice(0,2).join("/"):e[0]}function Md(r){let e=[],t=new Set;for(let n=0;n<r.length;n++)for(let s of mS)for(let i of r[n].matchAll(s)){let o=hS(i[1]);o&&!t.has(o)&&(t.add(o),e.push({root:o,lineIndex:n}))}return e}function $d(r){return Md(r.split(`
|
|
155
|
+
`)).map(e=>e.root)}function en(r,e){if(!r)return[];let{target:t,dependencies:n}=e,s=[],i=r.split(`
|
|
156
|
+
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of pS)l.targets.includes(t)&&l.pattern.test(a)&&s.push({type:l.type,severity:"error",message:bS(l.type,c),lineNumber:c,lineContent:a})}return t==="client"&&n&&s.push(...gS(i,n)),s}function gS(r,e){let t=new Set(Object.keys(e));return Md(r).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:yS(n,s+1),lineNumber:s+1,lineContent:r[s]}))}function yS(r,e){return`Import "${r}" is not declared in config.json dependencies! Found on line ${e}.
|
|
157
157
|
|
|
158
158
|
**CRITICAL**: Every bare import in code.tsx must be declared in the **config.json** "dependencies" block. A bulb that imports a package it doesn't declare is incomplete \u2014 it won't type-check, its versions aren't pinned, and it can't be reliably re-run or ported to typebulb.com.
|
|
159
159
|
|
|
@@ -167,7 +167,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
167
167
|
}
|
|
168
168
|
\`\`\`
|
|
169
169
|
|
|
170
|
-
**Fix:** Add a **config.json** block (or extend the existing one) with a "dependencies" entry for "${r}" \u2014 and for every other bare import in code.tsx. Pin a real version where you can (e.g. "react": "^19.2.7").`}function
|
|
170
|
+
**Fix:** Add a **config.json** block (or extend the existing one) with a "dependencies" entry for "${r}" \u2014 and for every other bare import in code.tsx. Pin a real version where you can (e.g. "react": "^19.2.7").`}function bS(r,e){return r==="URL_IMPORT"?`Direct URL imports are not supported! Found on line ${e}.
|
|
171
171
|
|
|
172
172
|
**CRITICAL**: Import packages by name only. Do NOT use CDN URLs:
|
|
173
173
|
|
|
@@ -321,40 +321,40 @@ import { something } from 'module-name'
|
|
|
321
321
|
const something = require('module-name') // NOT SUPPORTED!
|
|
322
322
|
\`\`\`
|
|
323
323
|
|
|
324
|
-
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var dt,pt,
|
|
324
|
+
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var dt,pt,pS,mS,_s=R(()=>{dt=["client"],pt=["client","server"],pS=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:dt},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:pt},{type:"JS_EXTENSION_IMPORT",pattern:/from\s+['"][^'"]*\/[^'"]*\.js['"]/,targets:dt},{type:"URL_IMPORT",pattern:/from\s+['"]https?:\/\//,targets:dt},{type:"VERSION_SPECIFIER_IMPORT",pattern:/from\s+['"][^'"]*@[\d^~]/,targets:dt},{type:"REDUNDANT_TB_DECLARATION",pattern:/declare\s+(const|var|let)\s+tb\b/,targets:pt},{type:"CONST_ENUM",pattern:/\bconst\s+enum\b/,targets:pt},{type:"NAMESPACE_DECLARATION",pattern:/\bnamespace\s+\w+/,targets:pt},{type:"COMMONJS_EXPORT_EQUALS",pattern:/\bexport\s*=/,targets:pt},{type:"COMMONJS_IMPORT_EQUALS",pattern:/\bimport\s+\w+\s*=/,targets:pt},{type:"MODULE_DECLARATION",pattern:/\bmodule\s+\w+\s*\{/,targets:pt},{type:"CSS_FILE_IMPORT",pattern:/(?:from|import)\s+['"][^'"]*\.css['"]/,targets:dt},{type:"NAVIGATION",pattern:/window\.(location\.(reload|assign|replace)\s*\(|open\s*\()/,targets:dt},{type:"NAVIGATION",pattern:/window\.location(\.href)?\s*=[^=]/,targets:dt}],mS=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});var dp=R(()=>{});var pe,me,Zt=R(()=>{pe=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},me=class{getPath(e,t){return this.path}parseError(e,t){return this.parseJsonError(e,t)}parseStreamChunk(e){return this.checkAndThrowError(e),this.parseProviderStreamChunk(e)}extractSystemMessages(e,t=`
|
|
325
325
|
|
|
326
|
-
`){let n=e.filter(s=>s.role==="system").map(s=>s.content);return{system:n.length?n.join(t):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,t){if(!e)return{message:`HTTP ${t}`};try{let n=JSON.parse(e);return n.error&&typeof n.error=="object"?{message:n.error.message||`HTTP ${t}`,type:n.error.type}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if(typeof e!="object"||e===null)return;let t=e;if(t.type==="error"&&"message"in t){let n=t.code||"unknown";throw new pe(t.message,n,!!t.retryable)}if(t.error)throw new pe(this.extractErrorMessage(t.error))}extractErrorMessage(e){if(typeof e=="string")try{let t=JSON.parse(e);return t.error?.message||t.message||e}catch{return e}return typeof e=="object"&&e!==null?e.message||JSON.stringify(e):`${this.providerName} returned an error`}}});var
|
|
326
|
+
`){let n=e.filter(s=>s.role==="system").map(s=>s.content);return{system:n.length?n.join(t):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,t){if(!e)return{message:`HTTP ${t}`};try{let n=JSON.parse(e);return n.error&&typeof n.error=="object"?{message:n.error.message||`HTTP ${t}`,type:n.error.type}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if(typeof e!="object"||e===null)return;let t=e;if(t.type==="error"&&"message"in t){let n=t.code||"unknown";throw new pe(t.message,n,!!t.retryable)}if(t.error)throw new pe(this.extractErrorMessage(t.error))}extractErrorMessage(e){if(typeof e=="string")try{let t=JSON.parse(e);return t.error?.message||t.message||e}catch{return e}return typeof e=="object"&&e!==null?e.message||JSON.stringify(e):`${this.providerName} returned an error`}}});var ei,tc=R(()=>{Zt();ei=class extends me{constructor(){super(...arguments),this.providerName="OpenAI",this.defaultBaseUrl="https://api.openai.com",this.path="/v1/responses",this.effortMap={0:"none",1:"low",2:"medium",3:"high"}}buildHeaders(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,n,s){let i=this.convertMessagesToInput(e),o={model:t,input:i,stream:s};if(n?.webSearch!==!1&&(o.tools=[{type:"web_search"}]),n?.effort!==void 0){let a=this.effortMap[n.effort];o.reasoning=a==="none"?{effort:a}:{effort:a,summary:"auto"}}return o}parseNonStreamingResponse(e){if(!this.isResponsesApiResponse(e))return{text:""};let t=e.output_text||"",n;if(e.output&&Array.isArray(e.output))for(let s of e.output)s.type==="reasoning"&&s.summary&&(n=s.summary.map(i=>i.text).join(`
|
|
327
327
|
`)),!t&&s.type==="message"&&s.content&&(t=s.content.filter(i=>i.type==="output_text").map(i=>i.text).join(""));return{text:t,reasoning:n}}parseProviderStreamChunk(e){if(!this.isResponsesApiEvent(e))return null;switch(e.type){case"response.failed":{let n=e.response?.error,s=n?.message||"Response failed",i=n?.code==="insufficient_quota"||n?.code==="rate_limit_exceeded";throw new pe(s,i?"rate_limit":"unknown",i)}case"response.output_text.delta":return{text:e.delta};case"response.reasoning_summary_text.delta":return{reasoning:e.delta};default:return null}}convertMessagesToInput(e){return e.map(t=>t.role==="system"?`System: ${t.content}`:t.role==="user"?`User: ${t.content}`:t.role==="assistant"?`Assistant: ${t.content}`:t.content).join(`
|
|
328
328
|
|
|
329
|
-
`)}isResponsesApiEvent(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"}isResponsesApiResponse(e){return typeof e=="object"&&e!==null&&e.object==="response"}}});var
|
|
329
|
+
`)}isResponsesApiEvent(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"}isResponsesApiResponse(e){return typeof e=="object"&&e!==null&&e.object==="response"}}});var er,ti=R(()=>{Zt();er=class extends me{parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let t=e,n=t.choices[0],s=n?.message,i=s?.content??n?.text??"",o=s?.reasoning??s?.reasoning_content??t.reasoning;return{text:i,reasoning:o}}parseProviderStreamChunk(e){if(!this.hasChoices(e))return null;let t=e.choices[0];if(!t)return null;let n=t.delta||t.message;if(!n)return null;let s=n.content||void 0,i=n.reasoning||n.reasoning_content||void 0;return!s&&!i?null:{text:s,reasoning:i}}hasChoices(e){return typeof e=="object"&&e!==null&&"choices"in e&&Array.isArray(e.choices)}}});var ri,rc=R(()=>{ti();ri=class extends er{constructor(){super(...arguments),this.providerName="OpenRouter",this.defaultBaseUrl="https://openrouter.ai",this.path="/api/v1/chat/completions",this.effortMap={0:"none",1:"low",2:"medium",3:"high"}}buildHeaders(e,t){let n={Authorization:`Bearer ${e}`,"x-api-key":e,"Content-Type":"application/json",Accept:"application/json","X-Title":"Typebulb"};return t&&(n["HTTP-Referer"]=t,n.Referer=t,n.Origin=t),n}buildPayload(e,t,n,s){let i={model:t,messages:e,stream:s};n?.webSearch===!0&&(i.plugins=[{id:"web"}]);let o=n?.effort;return o!==void 0&&(i.reasoning={effort:this.effortMap[o]}),i}}});var ni,nc=R(()=>{Zt();ni=class extends me{constructor(){super(...arguments),this.providerName="Anthropic",this.defaultBaseUrl="https://api.anthropic.com",this.path="/v1/messages"}buildHeaders(e){return{"x-api-key":e,"anthropic-version":"2023-06-01","Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,n,s){let{system:i,conversationMessages:o}=this.extractSystemMessages(e),a={model:t,max_tokens:this.getMaxTokens(t),messages:this.withLastMessageCached(o),stream:s};n?.webSearch!==!1&&(a.tools=[{type:"web_search_20250305",name:"web_search"}]),i&&(a.system=[{type:"text",text:i,cache_control:{type:"ephemeral"}}]);let c=n?.effort;if(c!==void 0){if(this.isModernModel(t))if(c===0)a.output_config={effort:"low"};else{let l={1:"low",2:"medium",3:"high"};a.thinking={type:"adaptive",display:"summarized"},a.output_config={effort:l[c]}}else if(c!==0){let l={1:2048,2:4096,3:8192};a.thinking={type:"enabled",budget_tokens:l[c]}}}return a}parseNonStreamingResponse(e){if(!this.isAnthropicResponse(e))return{text:""};let t=e.content.filter(s=>s.type==="text").map(s=>s.text).join(""),n=e.content.filter(s=>s.type==="thinking").map(s=>s.thinking).join(`
|
|
330
330
|
|
|
331
|
-
`);return{text:t,reasoning:n||void 0}}parseProviderStreamChunk(e){return this.isAnthropicEvent(e)&&e.type==="content_block_delta"?e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null:null}withLastMessageCached(e){let t=e.length-1;return e.map((n,s)=>s===t?{role:n.role,content:[{type:"text",text:n.content,cache_control:{type:"ephemeral"}}]}:n)}isAnthropicResponse(e){return typeof e=="object"&&e!==null&&e.type==="message"&&Array.isArray(e.content)}isAnthropicEvent(e){return typeof e=="object"&&e!==null&&"type"in e}isModernModel(e){let t=e.match(/^claude-[a-z]+-(\d+)(?:-(\d+))?/i);if(!t)return!1;let n=+t[1],s=t[2]?+t[2]:0;return n>4||n===4&&s>=6}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}}});var
|
|
331
|
+
`);return{text:t,reasoning:n||void 0}}parseProviderStreamChunk(e){return this.isAnthropicEvent(e)&&e.type==="content_block_delta"?e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null:null}withLastMessageCached(e){let t=e.length-1;return e.map((n,s)=>s===t?{role:n.role,content:[{type:"text",text:n.content,cache_control:{type:"ephemeral"}}]}:n)}isAnthropicResponse(e){return typeof e=="object"&&e!==null&&e.type==="message"&&Array.isArray(e.content)}isAnthropicEvent(e){return typeof e=="object"&&e!==null&&"type"in e}isModernModel(e){let t=e.match(/^claude-[a-z]+-(\d+)(?:-(\d+))?/i);if(!t)return!1;let n=+t[1],s=t[2]?+t[2]:0;return n>4||n===4&&s>=6}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}}});var si,sc=R(()=>{Zt();si=class extends me{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models"}getPath(e,t){return`/v1beta/models/${e}:${t?"streamGenerateContent":"generateContent"}${t?"?alt=sse":""}`}buildHeaders(e){return{"Content-Type":"application/json","x-goog-api-key":e}}buildPayload(e,t,n,s){let{system:i,conversationMessages:o}=this.extractSystemMessages(e,`
|
|
332
332
|
`),c={contents:o.map(f=>({role:f.role==="assistant"?"model":"user",parts:[{text:f.content}]}))};n?.webSearch!==!1&&(c.tools=[{google_search:{}}]),i&&(c.systemInstruction={role:"system",parts:[{text:i}]});let l=n?.effort;if(l!==void 0){let u={0:0,1:1024,2:8192,3:-1}[l];c.generationConfig={thinkingConfig:u===0?{thinkingBudget:0}:{includeThoughts:!0,thinkingBudget:u}}}return c}parseError(e,t){if(!e)return{message:`HTTP ${t}`};try{let n=JSON.parse(e),s=Array.isArray(n)?n[0]?.error:n?.error;return s&&typeof s=="object"?{message:(s.message||`HTTP ${t}`).split(`
|
|
333
|
-
`)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkAndThrowError(e),this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractParts(e).text||"",n=e.candidates?.[0]?.finishReason,s="complete";return n==="MAX_TOKENS"?s="interrupted":(n==="SAFETY"||n==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractParts(e);return t.text||t.reasoning?t:null}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let t=e.candidates?.[0]?.content?.parts;if(!t)return{};let n="",s="";for(let i of t)i.text&&(i.thought?s+=i.text:n+=i.text);return{text:n||void 0,reasoning:s||void 0}}checkGeminiError(e){if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new pe(`Prompt blocked: ${t}`)}}}});var
|
|
333
|
+
`)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkAndThrowError(e),this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractParts(e).text||"",n=e.candidates?.[0]?.finishReason,s="complete";return n==="MAX_TOKENS"?s="interrupted":(n==="SAFETY"||n==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractParts(e);return t.text||t.reasoning?t:null}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let t=e.candidates?.[0]?.content?.parts;if(!t)return{};let n="",s="";for(let i of t)i.text&&(i.thought?s+=i.text:n+=i.text);return{text:n||void 0,reasoning:s||void 0}}checkGeminiError(e){if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new pe(`Prompt blocked: ${t}`)}}}});var ii,ic=R(()=>{ti();ii=class extends er{constructor(){super(...arguments),this.providerName="Ollama",this.defaultBaseUrl="http://localhost:11434",this.path="/chat/completions"}buildHeaders(e){let t={"Content-Type":"application/json",Accept:"application/json"};return e&&(t.Authorization=`Bearer ${e}`),t}buildPayload(e,t,n,s){return{model:t,messages:e,stream:s}}}});function yt(r){let e=XS.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}function ZS(r,e){return r.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function oc(r,e){let t=yt(r.protocol),n=t.getPath(r.model,e.stream),s=ZS(r.baseUrl,n),i=t.buildHeaders(r.apiKey,e.origin),o=t.buildPayload(e.messages,r.model,{effort:e.effort,webSearch:e.webSearch},e.stream);return e.modifyPayload?.(o),fetch(s,{method:"POST",headers:i,body:JSON.stringify(o),signal:e.signal})}async function un(r,e){let t=yt(e),n=await r.text().catch(()=>""),{message:s}=t.parseError(n,r.status),i=r.status,o="unknown";return i===429?o="rate_limit":i===413&&(o="context_exceeded"),{code:o,message:s,retryable:i===429}}var pp,XS,ac=R(()=>{tc();rc();nc();sc();ic();pp=new ii,XS=new Map([["openai",new ei],["openrouter",new ri],["anthropic",new ni],["gemini",new si],["ollama",pp],["openai-compat",pp]])});function mp(r){let e=r.indexOf(`\r
|
|
334
334
|
\r
|
|
335
335
|
`),t=r.indexOf(`
|
|
336
336
|
|
|
337
|
-
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function
|
|
338
|
-
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*
|
|
339
|
-
`)}var
|
|
340
|
-
`),n=[];if(t.forEach((o,a)=>{let c=
|
|
341
|
-
`)}function
|
|
342
|
-
\u2026[${r.length-5e4} more characters truncated]`:r}function $e(r){let e=r.replace(
|
|
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
|
|
344
|
-
`):r==null?"":Se(JSON.stringify(r))}function
|
|
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
|
|
337
|
+
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function cc(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
|
+
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*hp(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=cc(s);f!==null&&f!=="done"&&(yield f)}return}t?.(),s+=n.decode(a,{stream:!0});let{pos:c,len:l}=mp(s);for(;c!==-1;){let f=s.slice(0,c);s=s.slice(c+l);let u=cc(f);if(u==="done")return;u!==null&&(yield u),{pos:c,len:l}=mp(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 tr(r,e))n.kind==="text"&&(t+=n.text);return t}async function*tr(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 hp(s)){let o=n.parseStreamChunk(i);o?.reasoning&&(yield{kind:"reasoning",text:o.reasoning}),o?.text&&(yield{kind:"text",text:o.text})}}var gp=R(()=>{ac()});var rr=R(()=>{dp();Zt();ac();gp();ti();nc();sc();tc();rc();ic()});function sr(r){return(r.includes("://")?r:`http://${r}`).replace(/\/+$/,"")}function lc(){return dn}async function Ne(){let[r,e]=await Promise.all([bp(),sk()]);return[...ik(e),...r]}async function yp(){let r;try{r=await fetch(ek,{signal:AbortSignal.timeout(rk)})}catch(e){return dn=`catalog fetch failed: ${e?.message??e}`,null}if(!r.ok)return dn=`catalog fetch failed: HTTP ${r.status}`,null;try{return await r.json()}catch(e){return dn=`catalog returned an unreadable body: ${e?.message??e}`,null}}async function sk(){if(fn&&Date.now()-fn.fetchedAt<=tk)return fn.models;let r=await yp()??await yp();return r?(fn={models:r,fetchedAt:Date.now()},dn=null,r):fn?.models??[]}async function bp(){if(oi&&Date.now()-oi.fetchedAt<=nk)return oi.models;let r=sr(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 oi={models:e,fetchedAt:Date.now()},e}function ik(r){let e=new Set(Object.entries(nr).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function uc(){return Object.values(nr).some(r=>!!process.env[r])}async function ai(){return uc()||process.env.TB_AI_BASE_URL?!0:(await bp()).length>0}function wp(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 nr,ek,tk,rk,nk,fn,oi,dn,wt=R(()=>{nr={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};ek="https://api.typebulb.com/api/models",tk=1440*60*1e3,rk=5e3,nk=60*1e3,fn=null,oi=null,dn=null});function vt(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:`${sr(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=nr[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 St(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 oc(r,{messages:t,stream:!0,effort:n!=null&&n>=0&&n<=3?n:void 0,webSearch:e.webSearch??!0,signal:e.signal})}var ci=R(()=>{rr();wt()});import{realpathSync as lk}from"fs";import{join as dc,resolve as uk}from"path";import{homedir as fk}from"os";function ui(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?dc(r,".."):dc(fk(),".typebulb")}function Ie(){return process.env.TYPEBULB_SERVERS_DIR||dc(ui(),"servers")}function Q(r){let e=uk(r),t=e;try{t=lk.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function xp(r,e){let t=Q(r),n=Q(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var fi=R(()=>{});import{readFileSync as dk,writeFileSync as pk,mkdirSync as mk}from"fs";import{join as hk}from"path";function Ep(){return hk(ui(),"trust.json")}function pc(){try{let r=JSON.parse(dk(Ep(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function gk(r){mk(ui(),{recursive:!0}),pk(Ep(),JSON.stringify([...r]))}function kt(r){return pc().has(Q(r))}function ir(r,e){let t=pc(),n=Q(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),gk(t))}function mc(){return[...pc()]}var mn=R(()=>{fi()});function cr(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 hi=R(()=>{});import{spawn as $p}from"child_process";import{readdir as Bk,readFile as Bp,writeFile as jp,unlink as yc,mkdir as jk}from"fs/promises";import{mkdirSync as Fp,writeFileSync as gi,appendFileSync as Fk,readFileSync as bc}from"fs";import*as ce from"path";import{fileURLToPath as qk}from"url";function wc(r){return ce.join(Ie(),`${r}.json`)}function gn(r){return ce.join(Ie(),`${r}.log`)}function vc(r){return ce.join(Ie(),`${r}.wait.json`)}function qp(r){try{let e=JSON.parse(bc(vc(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function Sc(r,e=""){let t=qp(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function yi(r,e,t=""){try{Fp(Ie(),{recursive:!0});let n=qp(r);n[t]=e,gi(vc(r),JSON.stringify({cursors:n}))}catch{}}function bi(r){let e=gn(r);try{Fp(Ie(),{recursive:!0}),gi(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(Fk(e,c),s+=c.length,s>2*Dp){let l=bc(e),f=l.subarray(Math.max(0,l.length-Dp));gi(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 Up(r){try{gi(gn(r),"")}catch{}}function ve(r,e=0){try{let t=bc(gn(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 kc(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function Jk(r){let e=Uk.exec(r);return e?Number(e[1]):void 0}function Jp(r,e){let t=r.split(`
|
|
340
|
+
`),n=[];if(t.forEach((o,a)=>{let c=Jk(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 xc(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function wi(r){await jk(Ie(),{recursive:!0}),await jp(wc(r.pid),JSON.stringify(r))}async function Kp(r,e){let t=wc(r);try{let n=JSON.parse(await Bp(t,"utf8"));if(n.denied===e)return;n.denied=e,await jp(t,JSON.stringify(n))}catch{}}async function xt(r){await yc(wc(r)).catch(()=>{}),await yc(gn(r)).catch(()=>{}),await yc(vc(r)).catch(()=>{})}async function K(r){let e;try{e=await Bk(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 Bp(ce.join(Ie(),s),"utf8"))}catch{await xt(i);return}o&&typeof o.pid=="number"&&xc(o.pid)?t.push(o):await xt(i)})),(r?t.filter(s=>s.agent==null&&xp(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function Ec(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 Et(r){try{process.kill(r,"SIGTERM")}catch{}await xt(r)}function lr(r,e){let t=Q(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&Q(n.file)===t)}async function Ac(r){let e=lr(await K(),r);for(let t of e)await Et(t.pid);return e}function Wk(r,e,t){(process.platform==="win32"?$p("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):$p(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function Wp(){return ce.join(ce.dirname(qk(import.meta.url)),"index.js")}function Hk(r,e={}){return{command:process.execPath,args:[Wp(),...e.trust?["--trust"]:[],r,...e.open===!1?["--no-open"]:[]]}}function Vk(r){return{command:process.execPath,args:[Wp(),`agent:${r}`,"--no-open"]}}async function Hp(r,e,t,n){let s=await r();if(s)return s;Wk(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await Kk(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function vi(r,e={}){let t=e.cwd??process.cwd(),n=ce.resolve(t,r);return await Ac(n),Hp(async()=>lr(await K(),n)[0],Hk(r,e),t,ce.basename(r))}async function Vp(r,e=process.cwd()){return Hp(()=>Ec(e,r),Vk(r),e,`the ${r} mirror`)}var Dp,Uk,Kk,Me=R(()=>{fi();Dp=1e6;Uk=/^── run (\d+) ── /;Kk=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(Yk,"").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 Yk,Si,ki=R(()=>{Yk=/\u001b\[[0-9;]*m/g;Si=(r,e)=>``});import{existsSync as Gk,readdirSync as zk,statSync as Qk}from"fs";import{join as Xk}from"path";function xi(r){if(!Gk(r))return[];let e;try{e=zk(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=Xk(r,n);try{let i=Qk(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var Tc=R(()=>{});var ur,Pc=R(()=>{ur=class{ensureHarnessSupport(){}}});import{openSync as Zk,readSync as ex,closeSync as tx,statSync as rx,readdirSync as nx,readFileSync as sx,existsSync as ix}from"fs";import{join as bn}from"path";import{homedir as _c}from"os";function ox(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function Ei(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?Si(e.data,e.media_type):""}function Oc(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?Oc(t.content):Ei(t)}).join(`
|
|
344
|
+
`):r==null?"":Se(JSON.stringify(r))}function cx(r){let e=r.trim();return!!e&&Qp.some(t=>t.test(e))}function lx(r){let e=r.trim();return e?Qp.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function fx(r){return r.replace(ux,"")}function dx(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=fx(r).trim();return e?dx(e)??(cx(e)?"":e):""}function Rc(r){return r?.type==="text"&&typeof r.text=="string"?rt(r.text):""}function Cc(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=Gp(t.file?.originalSize);return n?`image (${n})`:"image"}if(t.type==="pdf"){let n=Gp(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 yn(r){return!!r.isSidechain||!!r.isMeta}function px(r){let e;try{e=Zk(r,"r")}catch{return""}try{let n=65536;try{n=rx(r).size}catch{}let s=(l,f)=>{if(f<=0)return"";let u=Buffer.alloc(f),d=ex(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
|
-
`)){if(!l.trim())continue;let f;try{f=JSON.parse(l)}catch{continue}if(!f||
|
|
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
|
|
347
|
+
`)){if(!l.trim())continue;let f;try{f=JSON.parse(l)}catch{continue}if(!f||yn(f)||f.type!=="user")continue;let u=f.message?.content,d="";typeof u=="string"?d=rt(u):Array.isArray(u)&&(d=u.map(Rc).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{tx(e)}}function mx(r){let e;try{e=nx(zp)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let n=JSON.parse(sx(bn(zp,t),"utf8"));if(n?.sessionId!==r)continue;return process.kill(n.pid,0),!0}catch{}return!1}var ax,Yp,Qp,ux,ge,Gp,zp,fr,Ai=R(()=>{ki();Tc();Pc();ax=bn(_c(),".claude","projects"),Yp=r=>bn(ax,ox(r));Qp=[/\[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];ux=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;ge=(r,e,t=e+"s")=>`${r} ${r===1?e:t}`,Gp=r=>typeof r!="number"?"":r<1024?`${r}B`:r<1048576?`${Math.round(r/1024)}KB`:`${(r/1048576).toFixed(1)}MB`;zp=bn(_c(),".claude","sessions");fr=class extends ur{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}detectsInstalled(){return ix(bn(_c(),".claude"))}sessionsDir(e){return Yp(e)}listSessionFiles(e){return xi(Yp(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(yn(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=Oc(i.content);n.push({type:"tool_result",id:i.tool_use_id??"",content:o,isError:!!i.is_error,digest:Cc(e.toolUseResult,o)})}else{let o=Rc(i)||Ei(i);o&&n.push({type:"user",text:o})}return{events:n}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=rt(Oc(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=>!lx(u)).join(""),a=i.filter(u=>u.type==="thinking").map(u=>u.thinking??"").join(`
|
|
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 mx(e)}readPreview(e){return px(e)}searchText(e){if(!e||yn(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(Rc).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 Ti(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 Nc(r){return(Ti(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var Ic=R(()=>{});import{readdirSync as hx,readFileSync as gx,statSync as yx}from"fs";import{join as Xp,basename as bx}from"path";function Zp(r,e,t){if(e>8)return t;let n;try{n=hx(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;Zp(Xp(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(Xp(r,s.name));return t}function Pi(r){return Zp(r,0,[]).map(e=>{let t=0;try{t=yx(e).mtimeMs}catch{}let n,s=!1;try{let i=gx(e,"utf8");n=Ti(i.slice(0,1024));let o=Ae(i);s=!!o&&Rs(Yt(o))}catch{}return{path:e,name:n??bx(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var em=R(()=>{Xr();Zr();Ic()});import{readFile as wx}from"fs/promises";async function Lc(r){try{let e=Ae(await wx(r,"utf-8"));return e?cr(Yt(e)):void 0}catch{return}}var tm=R(()=>{Zr();hi()});function Mc(r){let e=Ae(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=$d(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=xl(l);u&&(c[u]=f)}return c.config=JSON.stringify(i,null,2),Cl(c)}var rm=R(()=>{Xr();_s()});import{spawn as nm}from"child_process";import{basename as vx}from"path";function Sx(){return process.env.TYPEBULB_EDITOR||"code"}function xx(r,e,t){return t==null?[e]:kx.test(vx(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function Ex(r,e){let t=Sx();return{command:t,args:xx(t,r,e)}}function $c(r,e){let{command:t,args:n}=Ex(r,e),s=process.platform==="win32"?nm("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):nm(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var kx,sm=R(()=>{kx=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as Ax,existsSync as Tx}from"fs";import*as At from"path";import{fileURLToPath as Px}from"url";function im(){let r=At.dirname(Px(import.meta.url));for(;!Tx(At.join(r,"package.json"));){let e=At.dirname(r);if(e===r)break;r=e}return r}function Tt(){return At.join(im(),"README.md")}function dr(){return At.join(im(),"description.md")}function Ox(r){let e=Ax(dr(),"utf8").trim().replace(/\s+/g," ");return`---
|
|
349
349
|
name: typebulb
|
|
350
350
|
description: ${JSON.stringify(e)}
|
|
351
351
|
version: ${r}
|
|
352
|
-
---`}function
|
|
352
|
+
---`}function Rx(r){return`> Generated from typebulb v${r}. If \`npx typebulb --version\` reports a newer version, re-run \`npx typebulb skill\` to refresh this file.`}function om(r,e){return`${Ox(e)}
|
|
353
353
|
|
|
354
|
-
${
|
|
354
|
+
${Rx(e)}
|
|
355
355
|
|
|
356
356
|
${r.trim()}
|
|
357
|
-
`}var
|
|
357
|
+
`}var Oi=R(()=>{});var pr=R(()=>{Me();em();tm();Ic();rm();sm();mn();wt();wt();ci();Oi()});import{copyFileSync as _x,existsSync as am,mkdirSync as cm,rmSync as Cx,writeFileSync as Nx}from"fs";import{homedir as Ix}from"os";import*as ke from"path";import{fileURLToPath as Lx}from"url";function Fx(){return jx.replace('"__TB_DESCRIPTION_PATH__"',JSON.stringify(dr())).replace('"__TB_README_PATH__"',JSON.stringify(Tt()))}function lm(){try{if(!am(Ri()))return}catch{return}try{let r=Mx();cm(ke.dirname(r),{recursive:!0}),Nx(r,Fx()),Cx($x(),{force:!0})}catch{}try{let r=Dx();if(!am(r))return;let e=Bx();cm(ke.dirname(e),{recursive:!0}),_x(r,e)}catch{}}var Ri,Mx,$x,Dx,Bx,jx,um=R(()=>{pr();Ri=()=>ke.join(Ix(),".pi","agent"),Mx=()=>ke.join(Ri(),"extensions","typebulb.ts"),$x=()=>ke.join(Ri(),"extensions","typebulb-wait.ts"),Dx=()=>ke.join(ke.dirname(Lx(import.meta.url)),"agents","pi","matchu-patchu.ts"),Bx=()=>ke.join(Ri(),"extensions","matchu-patchu.ts"),jx=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
|
|
358
358
|
import { spawn } from "node:child_process";
|
|
359
359
|
import { existsSync } from "node:fs";
|
|
360
360
|
|
|
@@ -503,27 +503,27 @@ export default function (pi) {
|
|
|
503
503
|
try { pi.on("session_shutdown", () => { for (const c of pending) { try { c.kill(); } catch (e) {} } pending.clear(); }); } catch (e) {}
|
|
504
504
|
} catch (e) { logErr("load", e && e.message); }
|
|
505
505
|
}
|
|
506
|
-
`});function
|
|
507
|
-
`))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var
|
|
508
|
-
`)}catch{}await Promise.race([this.#v,
|
|
509
|
-
`)}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"?
|
|
510
|
-
`)}catch(a){clearTimeout(o),this.#s.delete(n),i(new Error(
|
|
511
|
-
`)};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.#S();return}case"queue_update":{let n=Array.isArray(t.steering)?t.steering.map(String):[],s=Array.isArray(t.followUp)?t.followUp.map(String):[];this.#m=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
|
|
512
|
-
`),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)
|
|
513
|
-
`)){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{
|
|
514
|
-
`):""}}});var
|
|
515
|
-
|
|
516
|
-
${r.slice(0,
|
|
517
|
-
`))>=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 I=[],C=h.entries.get(_),
|
|
518
|
-
`).filter(Boolean).map(async v=>{try{return{f:v,m:(await
|
|
519
|
-
`)){if(!I.trim())continue;let C=r.parseEntry(I);if(!C)continue;let
|
|
520
|
-
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}
|
|
521
|
-
`)}function
|
|
506
|
+
`});function F(r){return r?.message??String(r)}var G,Pt=R(()=>{G=process.cwd()});import{spawn as fm}from"child_process";import{StringDecoder as qx}from"string_decoder";function Gx(r,e){let t=new qx("utf8"),n="";r.on("data",s=>{n+=typeof s=="string"?s:t.write(s);let i;for(;(i=n.indexOf(`
|
|
507
|
+
`))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var Ux,Jx,dm,Kx,Wx,Hx,Vx,Yx,_i,Ci,pm,mm=R(()=>{Pt();Ux=3e4,Jx=5e3,dm=2e3,Kx=2e3,Wx=12e4,Hx=8e3,Vx=15e3,Yx=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"]),_i=new Set;process.on("exit",()=>{for(let r of _i)try{r.kill()}catch{}});Ci=class{#e;#o=!1;#a=0;#i=!1;#c=null;#p=null;#t=null;#n=null;#l=new Map;#r=[];#m=null;#b=null;#h=null;#w;#u;#g="";#A=1;#s=new Map;#v;#y;constructor(e,t,n=(s,i)=>fm(s,{cwd:i,shell:!0,stdio:["pipe","pipe","pipe"],env:{...process.env,TYPEBULB_MIRROR:"1"}})){if(this.#v=new Promise(o=>{this.#y=o}),t?.includes('"')){this.#u="session path contains a quote \u2014 cannot drive it",this.#y();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: ${F(o)}`,this.#y();return}this.#e=i,this.#w=t,_i.add(i),i.stdout&&Gx(i.stdout,o=>this.#T(o)),i.stderr&&i.stderr.on("data",o=>{this.#g=(this.#g+o.toString()).slice(-Kx)}),i.on("error",o=>this.#x(`could not start pi: ${o.message}`)),i.on("exit",o=>{this.#e===i&&this.#x(o?`pi exited (code ${o})${this.#g.trim()?`: ${this.#g.trim()}`:""}`:"pi exited"),_i.delete(i),this.#y()}),this.#d({type:"get_state"}).then(o=>{let a=o.data?.sessionFile;typeof a=="string"&&a&&(this.#w=a);let c=o.data?.model;c&&typeof c.id=="string"&&c.id&&(this.#h=c.id)}).catch(()=>{}),this.#S()}get streaming(){return this.#o||Date.now()<this.#a}get draft(){return this.#c}get echo(){return this.#p}get queue(){return this.#m}get stats(){return this.#b}get model(){return this.#h}get sessionFile(){return this.#w}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.#k({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.#k(i),{ok:!0}}async rpc(e){if(!Yx.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.#h=n)}return t.success?{ok:!0,data:t.data}:{ok:!1,error:t.error??`pi rejected ${e.type}`}}catch(t){return{ok:!1,error:F(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:F(o)}}return i.success&&!n&&(this.#a=Date.now()+Jx),i.success&&!n&&!e.trimStart().startsWith("/")&&(this.#p=e),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)}clearEcho(){this.#p=null}async dispose(){let e=this.#e;if(e){if(this.#e=void 0,this.#o){try{e.stdin?.write(JSON.stringify({type:"abort"})+`
|
|
508
|
+
`)}catch{}await Promise.race([this.#v,pm(dm)])}try{e.stdin?.end()}catch{}if(await Promise.race([this.#v,pm(dm)]),e.exitCode===null&&!e.killed)if(process.platform==="win32"&&e.pid)try{fm("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}else try{e.kill("SIGKILL")}catch{}_i.delete(e),this.#r=[],this.#E("pi was shut down")}}#k(e){try{this.#e?.stdin?.write(JSON.stringify(e)+`
|
|
509
|
+
`)}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"?Hx:Vx)})}#S(){this.#d({type:"get_session_stats"}).then(e=>{if(!e.success||!e.data)return;let t=e.data;this.#b={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.#A++}`;return new Promise((s,i)=>{let o=setTimeout(()=>{this.#s.delete(n),i(new Error("pi did not respond (30s)"))},Ux);o.unref?.(),this.#s.set(n,{resolve:s,timer:o});try{t.stdin.write(JSON.stringify({id:n,...e})+`
|
|
510
|
+
`)}catch(a){clearTimeout(o),this.#s.delete(n),i(new Error(F(a)))}})}#T(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.#m=null,this.#S();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(`
|
|
511
|
+
`)};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.#S();return}case"queue_update":{let n=Array.isArray(t.steering)?t.steering.map(String):[],s=Array.isArray(t.followUp)?t.followUp.map(String):[];this.#m=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??Wx),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}}#x(e){this.#u=e,this.#o=!1,this.#a=0,this.#i=!1,this.#c=null,this.#p=null,this.#t=null,this.#n=null,this.#l.clear(),this.#r=[],this.#m=null,this.#b=null,this.#h=null,this.#e=void 0,this.#E(e)}#E(e){for(let[,t]of this.#s)clearTimeout(t.timer),t.resolve({type:"response",success:!1,error:e});this.#s.clear()}},pm=r=>new Promise(e=>{setTimeout(e,r).unref?.()})});import{existsSync as hm,readFileSync as zx,realpathSync as Qx}from"fs";import{join as Ot,dirname as wm,resolve as Xx}from"path";import{homedir as gm}from"os";function e0(r,e){let t=Ot(r,".pi");if(Zx.some(s=>hm(Ot(t,s))))return!0;let n=Ot(e,".agents","skills");for(let s=r;;){let i=Ot(s,".agents","skills");if(i!==n&&hm(i))return!0;let o=wm(s);if(o===s)return!1;s=o}}function t0(r,e){for(let t=e;;){if(r[t]===!0||r[t]===!1)return!0;let n=wm(t);if(n===t)return!1;t=n}}function vm(r,e){try{let t=e?.agentDir??Ot(gm(),".pi","agent"),n=ym(e?.home??process.env.HOME??gm()),s=ym(Xx(r));if(!e0(s,n))return null;let i=bm(Ot(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||t0(bm(Ot(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 Zx,ym,bm,Sm=R(()=>{Zx=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],ym=r=>{try{return Qx(r)}catch{return r}},bm=r=>{try{return JSON.parse(zx(r,"utf8"))}catch{return{}}}});import{statSync as r0,openSync as n0,readSync as s0,closeSync as i0,existsSync as o0}from"fs";import{join as Dc}from"path";import{homedir as xm}from"os";function c0(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function km(r){return r.type==="message"?l0(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var a0,l0,mr,Bc=R(()=>{ki();Tc();Pc();um();mm();Sm();a0=Dc(xm(),".pi","agent","sessions");l0=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";mr=class extends ur{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return o0(Dc(xm(),".pi","agent"))}ensureHarnessSupport(){lm()}createDriver(e,t){let n=new Ci(e,t),s=vm(e);return s&&n.notice(s,"warning"),n}sessionsDir(e){return Dc(a0,c0(e))}listSessionFiles(e){return xi(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 km(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(`
|
|
512
|
+
`),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)km(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=n0(e,"r")}catch{return""}try{let s=65536;try{s=r0(e).size}catch{}let i=Buffer.alloc(Math.min(65536,s)),o=s0(t,i,0,i.length,0),a=i.subarray(0,o).toString("utf8"),c="",l="";for(let u of a.split(`
|
|
513
|
+
`)){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{i0(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?Si(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
514
|
+
`):""}}});var $i,Vm=R(()=>{$i=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});function Di(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 zc=R(()=>{});var Bi,ji,Ym=R(()=>{Bi=".typebulb/paste",ji={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 $0,mkdirSync as D0,writeFileSync as B0,readFileSync as j0}from"fs";import{join as Fi}from"path";function Gm(){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 J0(r){return r.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function K0(r){let e=AbortSignal.timeout(F0);for(let[t,n]of U0){let s=vt(t,n);if(typeof s!="string"){try{let i=await St(s,{messages:[{role:"user",content:`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
|
|
515
|
+
|
|
516
|
+
${r.slice(0,q0)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=J0(await bt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function zm(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=Fi(r,Bi);try{D0(t,{recursive:!0})}catch(a){return{ok:!1,error:F(a)}}let n,s,i;if(e.kind==="image"){if(n=`img-${Gm()}`,s=Object.keys(ji).find(a=>ji[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else n=await K0(e.data)??`paste-${Gm()}`,s="md",i=e.data;let o=`${n}.${s}`;for(let a=2;$0(Fi(t,o));a++)o=`${n}-${a}.${s}`;try{B0(Fi(t,o),i)}catch(a){return{ok:!1,error:F(a)}}return{ok:!0,path:`${Bi}/${o}`}}function Qm(r,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),n=ji[t];if(!n)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:n,base64:j0(Fi(r,Bi,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var F0,q0,U0,Xm=R(()=>{rr();pr();Pt();Ym();F0=4e3,q0=4e3,U0=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});import{existsSync as Zm,openSync as W0,readSync as H0,closeSync as V0,statSync as gr,readdirSync as eh,watchFile as Y0,unwatchFile as th,mkdirSync as G0,writeFileSync as z0,readFileSync as Qc,unlinkSync as Q0,rmSync as X0}from"fs";import{stat as Z0}from"fs/promises";import{join as Ct}from"path";import{execFile as eE}from"child_process";function qi(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 S={d:r.createDriver(e.cwd,h),file:h};return t.add(S),e.file||(n=S),S}async function o(h){t.delete(h),n===h&&(n=void 0);try{await h.d.dispose()}catch(S){console.error("[composer] dispose:",F(S))}}function a(){let h=s();for(let S of[...t])S!==h&&(S.d.streaming||S.d.queue||S.d.error||o(S))}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(S=>S.file===n.file);h&&k(h)}}let l=h=>Ct(h,rE),f=(h,S)=>Ct(l(h),`${S}.lock`);function u(h,S){try{let v=f(h,S);if(Date.now()-gr(v).mtimeMs>=rh)return!1;try{if(parseInt(Qc(v,"utf8").trim(),10)===process.pid)return!1}catch{}return!0}catch{return!1}}function d(h,S){if(S)try{G0(l(h),{recursive:!0}),z0(f(h,S),String(process.pid))}catch(v){console.error("[lock] claim failed:",F(v))}}function p(h){try{X0(Ct(h,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function b(h){let S=l(h);if(!Zm(S))return;let v;try{v=eh(S)}catch{return}let _=Date.now();for(let $ of v){if(!$.endsWith(".lock"))continue;let I=Ct(S,$);try{let C=gr(I);_-C.mtimeMs>nE&&Q0(I)}catch{}}}function m(h){try{return gr(h),!1}catch(S){return S.code==="ENOENT"}}function y(){let h=e;if(h.file&&!m(h.file)){d(h.cwd,h.sessionId);return}let S=E(h);S&&k(S)}function E(h){if(!h.everAttached)return T(h.cwd)??g(h.cwd,()=>!0)}function T(h){let S=l(h);if(!Zm(S))return;let v;try{v=eh(S)}catch{return}let _;for(let I of v)if(I.endsWith(".lock"))try{let C=gr(Ct(S,I));if(Date.now()-C.mtimeMs>=rh||parseInt(Qc(Ct(S,I),"utf8").trim(),10)!==process.pid)continue;(!_||C.mtimeMs>_.mtime)&&(_={sessionId:I.slice(0,-5),mtime:C.mtimeMs})}catch{}if(!_)return;let $=r.listSessionFiles(h).find(I=>I.sessionId===_.sessionId);if(!(!$||m($.file)))return $}function g(h,S){return r.listSessionFiles(h).sort((v,_)=>_.mtime-v.mtime).find(v=>!u(h,v.sessionId)&&S(v))}function w(h,S){let v=e;if(v.file)try{th(v.file)}catch{}v.file=h,v.sessionId=S,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:S})}function k(h){let S=e;n=void 0,w(h.file,h.sessionId),S.everAttached=!0,d(S.cwd,h.sessionId),O();try{th(h.file)}catch{}Y0(h.file,{interval:200},()=>O())}function x(){w(void 0,"")}function O(){let h=e;if(!h.file)return;let S;try{S=gr(h.file).size}catch{return}if(S<=h.offset)return;let v;try{v=W0(h.file,"r")}catch{return}try{let j=S-h.offset,se=Buffer.alloc(j),Y=0;for(;Y<j;){let fl=H0(v,se,Y,j-Y,h.offset+Y);if(!fl)break;Y+=fl}h.offset+=Y,h.partial+=se.subarray(0,Y).toString("utf8")}finally{V0(v)}let _,$;for(;($=h.partial.indexOf(`
|
|
517
|
+
`))>=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 I=[],C=h.entries.get(_),q=!1;for(;C;){if(I.push(C),r.idOf(C)===h.chainLastId){q=!0;break}let j=r.parentOf(C);C=j?h.entries.get(j):void 0}if(q)for(let j=I.length-2;j>=0;j--)V(I[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(I.map(Y=>r.idOf(Y))),se=A(h.entries);for(let Y=I.length-1;Y>=0;Y--)V(I[Y]),M(r.idOf(I[Y]),se,j)}h.chainLastId=_}function A(h){let S=new Map;for(let v of h.values()){let _=r.parentOf(v);if(!_)continue;let $=S.get(_);$?$.push(v):S.set(_,[v])}return S}function M(h,S,v){if(!h)return;let _=S.get(h);if(!_)return;let $=_.filter(j=>!r.isSidechain(j));if($.length<2)return;let I=$.filter(j=>!v.has(r.idOf(j)));if(!I.length)return;let C=[],q=0;for(let j of I){let se=te(j,S);C.push(...se.events),q+=se.count}q>0&&e.buffer.push({type:"fork",atId:h,count:q,events:C})}function te(h,S){let v=[],_=[h];for(;_.length;){let C=_.pop();if(r.isSidechain(C))continue;v.push(C);let q=S.get(r.idOf(C)??"");if(q)for(let j of q)_.push(j)}v.sort((C,q)=>(Date.parse(r.timestampOf(C)??"")||0)-(Date.parse(r.timestampOf(q)??"")||0));let $=[];for(let C of v)r.isRecoveryNoise(C)||$.push(...r.apply(C,e.sessionStartMs).events);return{count:$.reduce((C,q)=>C+(q.type==="user"||q.type==="assistant"?1:0),0),events:$}}function V(h){try{let{events:S,usage:v,model:_,cost:$}=r.apply(h,e.sessionStartMs);for(let I of S)e.buffer.push(I);S.some(I=>I.type==="assistant")&&s()?.d.clearCompletedDraft(),S.some(I=>I.type==="user")&&s()?.d.clearEcho(),_&&(e.latestModel=_),v&&(e.latest=v),(v||$)&&e.buffer.push({type:"usage",...e.latest,cost:$})}catch(S){console.error("[mirror] skipped malformed entry:",F(S))}}async function B(){return{cwd:e.cwd,pid:process.pid,composer:!!r.createDriver}}let it=new $i;async function Yi(h,S){it.accept(h,S)&&console.log(S)}function zh(){let h=r.sessionAlive(e.sessionId,e.cwd);if(h!==void 0)return h;if(!e.file)return!1;try{return Date.now()-gr(e.file).mtimeMs<1e4}catch{return!1}}function Gi(){return r.chainWorking([...e.entries.values()])&&zh()}function Qh(){!r.createDriver||s()||e.latestModel||Gi()||i(e.file)}async function Xh(h){let S=e;y(),c(),Qh(),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(S.cwd).filter(C=>_.has(C.file)).map(C=>C.sessionId):[],I=r.createDriver?{streaming:!!v?.d.streaming,draft:v?.d.draft??null,echo:v?.d.echo??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:S.buffer.slice(h),cursor:S.buffer.length,working:!!v?.d.streaming||Gi(),latestModel:S.latestModel,composer:I,busy:$}}async function ll(){y(),c();let h=s();if(h?.d.error&&!h.d.streaming&&(await o(h),h=void 0),!h){if(Gi())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 Zh(h,S){if(!r.createDriver)return{ok:!1,error:"not supported"};let v=String(h??"").trim();if(!v)return{ok:!1,error:"empty message"};let _=await ll();return _.ok?_.d.send(v,S):_}async function eg(h,S){let v=s();return v?v.d.respondUi(String(h??""),S??{}):{ok:!1,error:"no dialog pending"}}async function tg(h,S){if(!r.createDriver)return{ok:!1,error:"not supported"};if(!h||typeof h.type!="string")return{ok:!1,error:"bad command"};if(S?.spawn){let _=await ll();return _.ok?_.d.rpc(h):_}let v=s();return!v||v.d.error?{ok:!1,error:"not running"}:v.d.rpc(h)}async function rg(){let h=s();if(h)try{await h.d.stop()}catch(S){console.error("[composer] stop:",F(S))}return{ok:!0}}async function ng(){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 sg(){if(!r.createDriver)return[];let h=await new Promise(v=>{eE("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e.cwd,maxBuffer:64*1024*1024},(_,$)=>v(_?"":$))});return(await Promise.all(h.split(`
|
|
518
|
+
`).filter(Boolean).map(async v=>{try{return{f:v,m:(await Z0(Ct(e.cwd,v))).mtimeMs}}catch{return{f:v,m:0}}}))).sort((v,_)=>_.m-v.m).map(v=>v.f)}function ig(){for(let h of[...t])o(h)}async function og(h){return r.createDriver?zm(e.cwd,h):{ok:!1,error:"not supported"}}async function ag(h){return Qm(e.cwd,String(h??""))}async function cg(){return r.listSessionFiles(e.cwd).sort((h,S)=>S.mtime-h.mtime).map(({sessionId:h,file:S,mtime:v})=>({sessionId:h,mtime:v,preview:r.readPreview(S)}))}let ul=new Map;function lg(h,S){let v=ul.get(h);if(v&&v.mtime===S)return v.turns;let _=[],$="";try{$=Qc(h,"utf8")}catch{return[]}for(let I of $.split(`
|
|
519
|
+
`)){if(!I.trim())continue;let C=r.parseEntry(I);if(!C)continue;let q=r.searchText(C);q&&_.push({text:q,lower:q.toLowerCase()})}return ul.set(h,{mtime:S,turns:_}),_}async function ug(h){let S=h.toLowerCase(),v=[];for(let{sessionId:_,file:$,mtime:I}of r.listSessionFiles(e.cwd).sort((C,q)=>q.mtime-C.mtime)){let{hitCount:C,snippet:q}=Di(lg($,I),S);if(C&&(v.push({sessionId:_,mtime:I,preview:r.readPreview($),hitCount:C,snippet:q}),v.length>=sE))break}return v}async function fg(h){let S=e,v=r.listSessionFiles(S.cwd).find(_=>_.sessionId===h);return v?v.file===S.file?{ok:!0}:(k(v),a(),{ok:!0}):{ok:!1,error:"session not found"}}return p(e.cwd),b(e.cwd),y(),{info:B,poll:Xh,logEmbedStatus:Yi,listSessions:cg,searchSessions:ug,attach:fg,composerSend:Zh,composerStop:rg,composerNew:ng,composerFiles:sg,composerUiRespond:eg,composerRpc:tg,composerPaste:og,composerPasteRead:ag,shutdownComposer:ig}}var tE,rE,rh,nE,sE,Xc=R(()=>{Pt();Vm();zc();Xm();tE=".typebulb",rE=`${tE}/locks`,rh=5e3,nE=6e4,sE=50});import{existsSync as Zc,mkdirSync as iE,readFileSync as nh,writeFileSync as oE}from"fs";import{join as yr,isAbsolute as aE}from"path";async function sh(r,e){let t=aE(r)?r:yr(G,r);return Zc(t)?($c(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function ih(r){let e=G,t=Mc(r),n=yr(e,"typebulbs");iE(n,{recursive:!0});let s=Nc(t),i=`${s}.bulb.md`;for(let l=2;Zc(yr(n,i))&&nh(yr(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=yr(n,i);Zc(o)||oE(o,t);let a=yr("typebulbs",i),c=await vi(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function oh(){return K(G)}async function ah(r){return await Et(r),{ok:!0}}async function ch(){return Pi(G).filter(r=>!r.serverOnly).map(r=>({...r,trusted:kt(r.path)}))}async function lh(r){let e=r.toLowerCase(),t=[];for(let n of Pi(G).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=nh(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
|
|
520
|
+
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=Di(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function uh(r,e){let t=G;e!=null&&ir(r,e);let n=await vi(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function fh(r){return{cap:await Lc(r)}}async function dh(r,e){return ir(r,e),{ok:!0}}async function ph(r,e){return ve(r,e)}var el=R(()=>{pr();Pt();zc()});import{readFileSync as nl,writeFileSync as hh,mkdirSync as cE,appendFileSync as gh,rmSync as mh}from"fs";import{join as Ki,dirname as lE}from"path";import{createServer as uE}from"http";function st(r){try{return JSON.parse(nl(r,"utf8"))}catch{return null}}function Ji(r,e){cE(lE(r),{recursive:!0}),hh(r,JSON.stringify(e,null,2)+`
|
|
521
|
+
`)}function bh(r,e,t){let n=Ki(r,".gitignore"),s="";try{s=nl(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(`
|
|
522
522
|
`)?`
|
|
523
|
-
`:"";try{
|
|
523
|
+
`:"";try{gh(n,a+t+`
|
|
524
524
|
`+o.join(`
|
|
525
525
|
`)+`
|
|
526
|
-
`)}catch(c){console.error("[switcher] .gitignore update failed",
|
|
526
|
+
`)}catch(c){console.error("[switcher] .gitignore update failed",F(c))}}function hE(r){let e=i=>{let o=i.exec(r);return o?Number(o[1]):0},t=e(/"cache_read_input_tokens":\s*(\d+)/),n=e(/"cache_creation_input_tokens":\s*(\d+)/),s=e(/"input_tokens":\s*(\d+)/);t>0||n>0?Tn="live":s>mE&&(Tn="uncached")}function vh(r,e){let t={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":r.headers["anthropic-version"]||"2023-06-01"},n=r.headers["anthropic-beta"];return typeof n=="string"&&(t["anthropic-beta"]=n),t}function gE(r){if(Array.isArray(r?.messages))for(let e of r.messages){if(!Array.isArray(e?.content))continue;let t=e.content.filter(n=>n?.type!=="thinking"&&n?.type!=="redacted_thinking");t.length&&t.length!==e.content.length&&(e.content=t)}}function Sh(r){let e;try{e=JSON.parse(r)}catch{return r}An=typeof e?.model=="string"?e.model:null,Ee&&(e.model=Ee),It&&(e.provider=wh(It));let t=/haiku/i.test(An||"");return Pn!=null&&!t&&(e.reasoning={effort:tl[Pn]}),delete e.thinking,e.output_config&&delete e.output_config.effort,gE(e),JSON.stringify(e)}function yE(){let r="",e=0,t=new Map,n=new Set(["thinking","redacted_thinking"]),s=i=>{let o=/^data: (.*)$/m.exec(i);if(!o)return i;let a;try{a=JSON.parse(o[1])}catch{return i}switch(a.type){case"message_start":return t.clear(),e=0,i;case"content_block_start":{if(n.has(a.content_block?.type))return t.set(a.index,null),null;let c=e++;return t.set(a.index,c),a.index=c,`event: ${a.type}
|
|
527
527
|
data: ${JSON.stringify(a)}
|
|
528
528
|
|
|
529
529
|
`}case"content_block_delta":case"content_block_stop":{let c=t.get(a.index);return c==null?null:(a.index=c,`event: ${a.type}
|
|
@@ -531,10 +531,11 @@ data: ${JSON.stringify(a)}
|
|
|
531
531
|
|
|
532
532
|
`)}default:return i}};return i=>{r+=i;let o="",a;for(;(a=r.indexOf(`
|
|
533
533
|
|
|
534
|
-
`))!==-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
|
|
534
|
+
`))!==-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 bE(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 En(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 wE(r,e,t){if(!Ee){En(e,400,"invalid_request_error",pE);return}let n=process.env.OPENROUTER_API_KEY;if(!n){En(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(sl,{method:"POST",headers:vh(r,n),body:Sh(t),signal:s.signal})}catch(u){En(e,502,"api_error",`proxy upstream failed: ${F(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?yE():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});hE(p);let b=f(p);b&&e.write(b)}else e.write(Buffer.from(d))}}catch{}finally{e.writableEnded||e.end()}}async function vE(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(`${sl}/count_tokens`,{method:"POST",headers:vh(r,n),body:Sh(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function SE(r,e){let t=r.url||"/";if(r.method==="HEAD"){e.writeHead(200),e.end();return}if(r.method!=="POST"){En(e,404,"not_found_error",t);return}bE(r).then(n=>{if(t.includes("count_tokens"))return vE(r,e,n);if(t.includes("/v1/messages"))return wE(r,e,n);En(e,404,"not_found_error",t)})}function kE(){return br&&Nt?Promise.resolve(Nt):new Promise((r,e)=>{let t=uE(SE);t.on("error",e),t.listen(0,"127.0.0.1",()=>{br=t,Nt=t.address().port,console.log(`[switcher] wire proxy listening on ${Ui(Nt)}`),r(Nt)})})}function xE(){try{br?.close()}catch{}br=null,Nt=null}function EE(r,e){let t=Wi(r),n=st(t),s=n||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===Ui(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=Hi(r);if(!st(i)){let a={};for(let c of yh)a[c]=c in s.env?s.env[c]:null;Ji(i,{managedBy:"agent-switcher",fileExisted:n!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=Ui(e),s.env.ANTHROPIC_AUTH_TOKEN=dE,Ji(t,s),bh(r,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function AE(r,e,t){let n=Hi(r),s=st(n)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},Ji(n,s)}function kh(r){let e=Wi(r),t=Hi(r),n=st(t),s=st(e);if(s?.env){let i=n?.snapshot||{};for(let o of yh){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{mh(e,{force:!0})}catch{}else Ji(e,s)}try{mh(t,{force:!0})}catch{}}async function TE(){let r=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await Ne()).filter(n=>n.provider==="openrouter"&&!il(n.name)).map(n=>({id:n.name,label:n.friendlyName||n.name}))}catch(n){console.error("[switcher] model list failed",F(n))}let t=e.length?void 0:lc()??void 0;return{hasKey:r,models:e,error:t}}async function PE(){if(br&&Ee)return{active:!0,managed:!0,model:Ee,port:Nt,provider:It,routedModel:An,caching:Tn,reasoning:Pn,externalBaseUrl:null};let r=st(Wi(G))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:Pn,externalBaseUrl:r.ANTHROPIC_BASE_URL||null}}async function xh(r,e){let t=await kE();return Ee=r,It=e,EE(G,t),t}async function OE({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(il(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 xh(r,ol[r]??null),An=null,Tn="unknown",AE(G,r,It)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${F(e)}`}}return{ok:!0}}async function RE({level:r}){return r!=null&&(!Number.isInteger(r)||r<0||r>=tl.length)?{ok:!1,error:`reasoning level must be 0\u2013${tl.length-1} or null`}:(Pn=r,{ok:!0,level:r})}async function _E(){return kh(G),Ee=null,It=null,An=null,Tn="unknown",{ok:!0}}async function CE({key:r}){let e=(r||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=G,n=Ki(t,".env"),s="";try{s=nl(n,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))hh(n,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
|
|
535
535
|
`)?`
|
|
536
|
-
`:"";
|
|
537
|
-
`)}}catch(i){return{ok:!1,error:U(i)}}return process.env.OPENROUTER_API_KEY=e,gh(t,[".env"],"# secrets"),{ok:!0}}function xE(){if(!(!gr&&!Ee)){try{vh(G)}catch{}mE()}}function EE(r,e){return kh.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 AE(r){if(kh.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 TE(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=tl(e?.cache_read_input_tokens)||tl(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 PE({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(sl(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:64,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:yh(a)}:i),u=await fetch(nl,{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:EE(a.status,E),restriction:AE(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=tl(c?.usage?.cache_creation_input_tokens),{r:d,j:p}=await o(l),{works:b,read:m,note:y}=TE(d.ok,p?.usage,l);return b===!0&&l&&(il[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 rE,nl,nE,sE,hh,iE,el,Ki,Wi,qi,sl,gr,_t,Ee,Ct,En,An,Tn,il,tl,yh,kh,xh=R(()=>{yn();fr();rE="https://openrouter.ai/api",nl=`${rE}/v1/messages`,nE="typebulb-proxy-managed",sE="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.",hh=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],iE=5e3,el=["low","medium","high"],Ki=r=>Ji(r,".claude","settings.local.json"),Wi=r=>Ji(r,".claude",".cc-switcher.json"),qi=r=>`http://127.0.0.1:${r}`;sl=r=>/^anthropic\//i.test(r)||/claude/i.test(r),gr=null,_t=null,Ee=null,Ct=null,En=null,An="unknown",Tn=1,il={},tl=r=>typeof r=="number"?r:0,yh=r=>({order:[r],allow_fallbacks:!1});kh=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=st(Wi(G)),t=e?.active?.model;if(!t)return;let s=(st(Ki(G))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await Sh(t,e.active.provider??il[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${qi(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",U(e))}})()});var Ah={};ul(Ah,{attach:()=>LE,blockToMarkdown:()=>xi,breakout:()=>nh,capText:()=>Se,cleanUserText:()=>rt,clearSwitchModel:()=>SE,composerPasteRead:()=>ME,displayName:()=>OE,firstLineDigest:()=>$e,info:()=>RE,isHiddenTurn:()=>hn,launchBulb:()=>ch,listBreakouts:()=>sh,listBulbFiles:()=>oh,listSessions:()=>NE,listSwitchModels:()=>yE,logEmbedStatus:()=>CE,openFile:()=>rh,poll:()=>_E,predictTrustOf:()=>lh,probeModel:()=>PE,readBulbLog:()=>fh,saveOpenRouterKey:()=>kE,searchBulbs:()=>ah,searchSessions:()=>IE,setBulbTrust:()=>uh,setReasoning:()=>vE,setSwitchModel:()=>wE,shutdownSwitcher:()=>xE,stopBreakout:()=>ih,switchState:()=>bE,toolResultDigest:()=>_c});var Eh,OE,RE,_E,CE,NE,IE,LE,ME,Th=R(()=>{Qc();Ei();Zc();xh();Ei();Si();Eh=new lr,OE=Eh.displayName,{info:RE,poll:_E,logEmbedStatus:CE,listSessions:NE,searchSessions:IE,attach:LE,composerPasteRead:ME}=Fi(Eh)});var Oh={};ul(Oh,{attach:()=>UE,breakout:()=>nh,composerFiles:()=>HE,composerNew:()=>WE,composerPaste:()=>GE,composerPasteRead:()=>zE,composerRpc:()=>YE,composerSend:()=>JE,composerStop:()=>KE,composerUiRespond:()=>VE,displayName:()=>$E,info:()=>DE,launchBulb:()=>ch,listBreakouts:()=>sh,listBulbFiles:()=>oh,listSessions:()=>FE,logEmbedStatus:()=>jE,openFile:()=>rh,poll:()=>BE,predictTrustOf:()=>lh,readBulbLog:()=>fh,searchBulbs:()=>ah,searchSessions:()=>qE,setBulbTrust:()=>uh,shutdownComposer:()=>QE,stopBreakout:()=>ih});var Ph,$E,DE,BE,jE,FE,qE,UE,JE,KE,WE,HE,VE,YE,GE,zE,QE,Rh=R(()=>{Qc();Dc();Zc();Ph=new dr,$E=Ph.displayName,{info:DE,poll:BE,logEmbedStatus:jE,listSessions:FE,searchSessions:qE,attach:UE,composerSend:JE,composerStop:KE,composerNew:WE,composerFiles:HE,composerUiRespond:VE,composerRpc:YE,composerPaste:GE,composerPasteRead:zE,shutdownComposer:QE}=Fi(Ph)});import*as Fh from"fs/promises";import*as Be from"path";import*as dl from"fs/promises";import{existsSync as Nt,readFileSync as ug}from"fs";import*as W from"path";import{pathToFileURL as fg}from"url";import{resolve as zi}from"resolve.exports";import{init as pl,parse as ml}from"es-module-lexer";function hl(r,e){let t=W.join(r,"package.json");try{return JSON.parse(ug(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var Gi=["browser","import","default"],fl=["node","import","default"];function gl(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 yl(r){let{name:e,dir:t}=r;if(!Nt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=hl(t,e),s=dg(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=pg(n,t);return await mg(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function dg(r,e){if(r.exports!==void 0){let n;try{n=zi(r,".",{browser:!0,conditions:Gi})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Gi.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=Qi(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Gi.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 pg(r,e){if(r.exports!==void 0)try{let n=zi(r,".",{conditions:["types"]}),s=Qi(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 Qi(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function mg(r,e,t){await pl;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 dl.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=ml(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=hg(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 hg(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 gg(r,e,t){let n=hl(r,e),s;if(n.exports!==void 0)try{s=Qi(zi(n,t,{conditions:fl}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${fl.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 fg(i).href}async function bl(r,e){await pl;let t;try{[t]=ml(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=gg(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var yg=5e3;function wl(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=yg;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=gl(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 vl(){console.log(`
|
|
536
|
+
`:"";gh(n,i+`OPENROUTER_API_KEY=${e}
|
|
537
|
+
`)}}catch(i){return{ok:!1,error:F(i)}}return process.env.OPENROUTER_API_KEY=e,bh(t,[".env"],"# secrets"),{ok:!0}}function NE(){if(!(!br&&!Ee)){try{kh(G)}catch{}xE()}}function IE(r,e){return Eh.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 LE(r){if(Eh.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 ME(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=rl(e?.cache_read_input_tokens)||rl(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 $E({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(il(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:64,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:wh(a)}:i),u=await fetch(sl,{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:IE(a.status,E),restriction:LE(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=rl(c?.usage?.cache_creation_input_tokens),{r:d,j:p}=await o(l),{works:b,read:m,note:y}=ME(d.ok,p?.usage,l);return b===!0&&l&&(ol[r]=l,Ee===r&&(It=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=F(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var fE,sl,dE,pE,yh,mE,tl,Wi,Hi,Ui,il,br,Nt,Ee,It,An,Tn,Pn,ol,rl,wh,Eh,Ah=R(()=>{pr();Pt();fE="https://openrouter.ai/api",sl=`${fE}/v1/messages`,dE="typebulb-proxy-managed",pE="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.",yh=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],mE=5e3,tl=["low","medium","high"],Wi=r=>Ki(r,".claude","settings.local.json"),Hi=r=>Ki(r,".claude",".cc-switcher.json"),Ui=r=>`http://127.0.0.1:${r}`;il=r=>/^anthropic\//i.test(r)||/claude/i.test(r),br=null,Nt=null,Ee=null,It=null,An=null,Tn="unknown",Pn=1,ol={},rl=r=>typeof r=="number"?r:0,wh=r=>({order:[r],allow_fallbacks:!1});Eh=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=st(Hi(G)),t=e?.active?.model;if(!t)return;let s=(st(Wi(G))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await xh(t,e.active.provider??ol[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${Ui(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",F(e))}})()});var Ph={};dl(Ph,{attach:()=>JE,blockToMarkdown:()=>Ei,breakout:()=>ih,capText:()=>Se,cleanUserText:()=>rt,clearSwitchModel:()=>_E,composerPasteRead:()=>KE,displayName:()=>DE,firstLineDigest:()=>$e,info:()=>BE,isHiddenTurn:()=>yn,launchBulb:()=>uh,listBreakouts:()=>oh,listBulbFiles:()=>ch,listSessions:()=>qE,listSwitchModels:()=>TE,logEmbedStatus:()=>FE,openFile:()=>sh,poll:()=>jE,predictTrustOf:()=>fh,probeModel:()=>$E,readBulbLog:()=>ph,saveOpenRouterKey:()=>CE,searchBulbs:()=>lh,searchSessions:()=>UE,setBulbTrust:()=>dh,setReasoning:()=>RE,setSwitchModel:()=>OE,shutdownSwitcher:()=>NE,stopBreakout:()=>ah,switchState:()=>PE,toolResultDigest:()=>Cc});var Th,DE,BE,jE,FE,qE,UE,JE,KE,Oh=R(()=>{Xc();Ai();el();Ah();Ai();ki();Th=new fr,DE=Th.displayName,{info:BE,poll:jE,logEmbedStatus:FE,listSessions:qE,searchSessions:UE,attach:JE,composerPasteRead:KE}=qi(Th)});import{readFileSync as WE,writeFileSync as HE,mkdirSync as VE}from"fs";import{homedir as YE}from"os";import*as Vi from"path";async function Ch(){try{let r=await fetch(new URL("/api/tags",_h()).toString(),{signal:AbortSignal.timeout(GE)});return r.ok?((await r.json()).models??[]).map(t=>t.name).filter(t=>!!t):[]}catch{return[]}}function Nh(r){let e;try{e=WE(r,"utf-8")}catch{return{json:void 0,unreadable:!1}}try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t;return{json:n,unreadable:"providers"in n&&!al(n)}}}catch{}return{json:void 0,unreadable:!0}}function al(r){let e=r?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function zE(r){let e=al(r);if(!e||!("ollama"in e))return null;let t=e.ollama?.models;return Array.isArray(t)?t.map(n=>n?.id).filter(n=>typeof n=="string"):[]}async function Ih(){let{json:r,unreadable:e}=Nh(Rh());return e?{installed:[],configured:null}:{installed:await Ch(),configured:zE(r)}}async function Lh(){let r=await Ch();return r.length?QE(Rh(),r,_h()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function QE(r,e,t){let{json:n,unreadable:s}=Nh(r);if(s)return{ok:!1,error:`could not parse ${r} \u2014 edit the ollama provider there yourself`};let i={...n??{},providers:{...al(n)??{},ollama:{baseUrl:`${t}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{VE(Vi.dirname(r),{recursive:!0}),HE(r,JSON.stringify(i,null,2)+`
|
|
538
|
+
`)}catch(o){return{ok:!1,error:`could not write ${r}: ${F(o)}`}}return{ok:!0,count:e.length}}var GE,Rh,_h,Mh=R(()=>{Pt();pr();GE=1500,Rh=()=>Vi.join(YE(),".pi","agent","models.json"),_h=()=>sr(process.env.OLLAMA_HOST??"http://localhost:11434")});var Dh={};dl(Dh,{attach:()=>sA,breakout:()=>ih,composerFiles:()=>cA,composerNew:()=>aA,composerPaste:()=>fA,composerPasteRead:()=>dA,composerRpc:()=>uA,composerSend:()=>iA,composerStop:()=>oA,composerUiRespond:()=>lA,displayName:()=>XE,info:()=>ZE,launchBulb:()=>uh,listBreakouts:()=>oh,listBulbFiles:()=>ch,listSessions:()=>rA,logEmbedStatus:()=>tA,ollamaOffer:()=>Ih,ollamaSync:()=>Lh,openFile:()=>sh,poll:()=>eA,predictTrustOf:()=>fh,readBulbLog:()=>ph,searchBulbs:()=>lh,searchSessions:()=>nA,setBulbTrust:()=>dh,shutdownComposer:()=>pA,stopBreakout:()=>ah});var $h,XE,ZE,eA,tA,rA,nA,sA,iA,oA,aA,cA,lA,uA,fA,dA,pA,Bh=R(()=>{Xc();Bc();el();Mh();$h=new mr,XE=$h.displayName,{info:ZE,poll:eA,logEmbedStatus:tA,listSessions:rA,searchSessions:nA,attach:sA,composerSend:iA,composerStop:oA,composerNew:aA,composerFiles:cA,composerUiRespond:lA,composerRpc:uA,composerPaste:fA,composerPasteRead:dA,shutdownComposer:pA}=qi($h)});import*as Gh from"fs/promises";import*as Be from"path";import*as ml from"fs/promises";import{existsSync as Lt,readFileSync as wg}from"fs";import*as W from"path";import{pathToFileURL as vg}from"url";import{resolve as Xi}from"resolve.exports";import{init as hl,parse as gl}from"es-module-lexer";function yl(r,e){let t=W.join(r,"package.json");try{return JSON.parse(wg(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var Qi=["browser","import","default"],pl=["node","import","default"];function bl(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 wl(r){let{name:e,dir:t}=r;if(!Lt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=yl(t,e),s=Sg(n,e),i=W.resolve(t,s);if(!Lt(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=kg(n,t);return await xg(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function Sg(r,e){if(r.exports!==void 0){let n;try{n=Xi(r,".",{browser:!0,conditions:Qi})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Qi.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: ${Qi.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 kg(r,e){if(r.exports!==void 0)try{let n=Xi(r,".",{conditions:["types"]}),s=Zi(n);if(s){let i=W.resolve(e,s);if(Lt(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=W.resolve(e,t);if(Lt(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 xg(r,e,t){await hl;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 ml.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=gl(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=Eg(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 Eg(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)&&Lt(o))return o}function Ag(r,e,t){let n=yl(r,e),s;if(n.exports!==void 0)try{s=Zi(Xi(n,t,{conditions:pl}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${pl.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(!Lt(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return vg(i).href}async function vl(r,e){await hl;let t;try{[t]=gl(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=Ag(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var Tg=5e3;function Sl(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=Tg;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=bl(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 kl(){console.log(`
|
|
538
539
|
typebulb - Local bulb runner for Typebulb
|
|
539
540
|
|
|
540
541
|
Usage:
|
|
@@ -663,10 +664,10 @@ Examples:
|
|
|
663
664
|
typebulb my-editor.bulb.md
|
|
664
665
|
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
665
666
|
typebulb .
|
|
666
|
-
`)}
|
|
667
|
+
`)}Zr();import*as et from"fs/promises";import*as li from"path";import{pathToFileURL as ck}from"url";import{transform as dS}from"sucrase";function Ua(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=dS(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}_s();function wS(r){return r.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
667
668
|
`)[0]}`).join(`
|
|
668
|
-
`)}function
|
|
669
|
-
${uS(t)}`)}var Ge="https://esm.sh",Zr="https://cdn.jsdelivr.net/npm/",qa="https://data.jsdelivr.com/v1/package/npm/";function $d(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=$d(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=Dd(t[1]??""),a=Vt(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Dd(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(Zr).host;if(t.host===n){let i=$d(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,Dd=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 Ua(r){return r.startsWith("./")?r:`./${r}`}var en=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`${Zr}${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(`${qa}${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 Bd=r=>r.startsWith("@types/"),tn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!Bd(e)),Ja=r=>Object.keys(r?.dependencies||{}).filter(e=>!Bd(e)),fS=r=>tn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),rn=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 fS(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=>tn(i.meta))),n=new Map;for(let i of e)for(let o of Ja(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:tn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var nn=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 dS,parse as pS}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 dS;let[s]=pS(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 M=A?[...O,b]:O.length?O:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:x,external:M})]),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([...tn(e.meta),...Ja(e.meta)])].filter(n=>t.has(n))}};Yt.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as jd,satisfies as mS,maxSatisfying as Fd,major as hS,valid as gS}from"semver";var _s=class{cmp(e,t){return e===t?0:jd(e,t)?1:jd(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!mS(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=Fd(e,n,{includePrerelease:!1});if(a)return a}return Fd(e,n,{includePrerelease:!0})??void 0}majorOf(e){return hS(e)}isExactVersion(e){return gS(e)!==null}},ht=new _s;function qd(r,e){let t=new en(r,e),n=new rn(t),s=new nn(r,t,ht);return{packageService:new Yt(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as np from"fs/promises";import*as de from"path";var Ka=[{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"}],Wa=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function Ha(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 yS=`
|
|
669
|
+
`)}function Dd(r,e){let t=en(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
670
|
+
${wS(t)}`)}var Ge="https://esm.sh",tn="https://cdn.jsdelivr.net/npm/",Ja="https://data.jsdelivr.com/v1/package/npm/";function Bd(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=Gt(t??s.version),this.subpath=Gt(n??s.subpath)}static parse(e){let t=Bd(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=jd(t[1]??""),a=Gt(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=jd(t[0]),o=Gt(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(tn).host;if(t.host===n){let i=Bd(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:Gt(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://")}},Gt=r=>r&&r.length?r:void 0,jd=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),Gt(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 Ka(r){return r.startsWith("./")?r:`./${r}`}var rn=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`${tn}${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(`${Ja}${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 Fd=r=>r.startsWith("@types/"),nn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!Fd(e)),Wa=r=>Object.keys(r?.dependencies||{}).filter(e=>!Fd(e)),vS=r=>nn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),sn=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 vS(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=>nn(i.meta))),n=new Map;for(let i of e)for(let o of Wa(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:nn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var on=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 SS,parse as kS}from"es-module-lexer";var zt=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 SS;let[s]=kS(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 M=A?[...O,b]:O.length?O:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:x,external:M})]),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([...nn(e.meta),...Wa(e.meta)])].filter(n=>t.has(n))}};zt.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as qd,satisfies as xS,maxSatisfying as Ud,major as ES,valid as AS}from"semver";var Cs=class{cmp(e,t){return e===t?0:qd(e,t)?1:qd(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!xS(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=Ud(e,n,{includePrerelease:!1});if(a)return a}return Ud(e,n,{includePrerelease:!0})??void 0}majorOf(e){return ES(e)}isExactVersion(e){return AS(e)!==null}},ht=new Cs;function Jd(r,e){let t=new rn(r,e),n=new sn(t),s=new on(r,t,ht);return{packageService:new zt(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as ip from"fs/promises";import*as de from"path";var Ha=[{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"}],Va=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function Ya(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 TS=`
|
|
670
671
|
/**
|
|
671
672
|
* Get raw data chunk from the Data tab.
|
|
672
673
|
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
@@ -677,7 +678,7 @@ ${uS(t)}`)}var Ge="https://esm.sh",Zr="https://cdn.jsdelivr.net/npm/",qa="https:
|
|
|
677
678
|
* @param index - Chunk index (0-based)
|
|
678
679
|
* @throws If chunk is not valid JSON/JSON-ish
|
|
679
680
|
*/
|
|
680
|
-
json<T = unknown>(index: number): T;`,
|
|
681
|
+
json<T = unknown>(index: number): T;`,PS=`
|
|
681
682
|
/**
|
|
682
683
|
* Get the insight data produced by the inference layer.
|
|
683
684
|
*
|
|
@@ -686,7 +687,7 @@ ${uS(t)}`)}var Ge="https://esm.sh",Zr="https://cdn.jsdelivr.net/npm/",qa="https:
|
|
|
686
687
|
*
|
|
687
688
|
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
688
689
|
*/
|
|
689
|
-
insight<T = unknown>(): T | undefined;`,
|
|
690
|
+
insight<T = unknown>(): T | undefined;`,Kd=`options: {
|
|
690
691
|
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
691
692
|
system?: string;
|
|
692
693
|
/** Reasoning effort hint: 0=minimal, 1=low, 2=med, 3=high. Mapped to each provider's native mechanism (OpenAI/OpenRouter reasoning effort, Gemini thinking budget, Anthropic adaptive thinking). 0 minimizes reasoning \u2014 a floor, not a guaranteed "off": some models still think a little at 0, and adaptive models already self-skip at 1 (low). Level 1 (low) is the sensible default for most work; reach for 0 only when you truly want minimal deliberation. Omit for the model's own default. */
|
|
@@ -697,12 +698,12 @@ ${uS(t)}`)}var Ge="https://esm.sh",Zr="https://cdn.jsdelivr.net/npm/",qa="https:
|
|
|
697
698
|
webSearch?: boolean;
|
|
698
699
|
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
699
700
|
signal?: AbortSignal;
|
|
700
|
-
}`,
|
|
701
|
+
}`,Wd=`
|
|
701
702
|
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
702
703
|
type AiChunk =
|
|
703
704
|
| { kind: "text"; text: string }
|
|
704
705
|
| { kind: "reasoning"; text: string };
|
|
705
|
-
`,
|
|
706
|
+
`,Hd=`
|
|
706
707
|
/**
|
|
707
708
|
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
708
709
|
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
@@ -711,7 +712,7 @@ type AiChunk =
|
|
|
711
712
|
* @throws On rate limit, network error, or provider error
|
|
712
713
|
*/
|
|
713
714
|
ai: {
|
|
714
|
-
(${
|
|
715
|
+
(${Kd}): Promise<{ text: string }>;
|
|
715
716
|
/**
|
|
716
717
|
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
717
718
|
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
@@ -725,8 +726,8 @@ type AiChunk =
|
|
|
725
726
|
* if (c.kind === "text") answer += c.text;
|
|
726
727
|
* }
|
|
727
728
|
*/
|
|
728
|
-
stream(${
|
|
729
|
-
};`,
|
|
729
|
+
stream(${Kd}): AsyncIterable<AiChunk>;
|
|
730
|
+
};`,Vd=`
|
|
730
731
|
/**
|
|
731
732
|
* Returns AI models available to the current user.
|
|
732
733
|
* Models are filtered by the user's configured API keys.
|
|
@@ -748,7 +749,7 @@ type AiChunk =
|
|
|
748
749
|
* making many AI calls should check this and show a "use your own keys"
|
|
749
750
|
* notice instead of running.
|
|
750
751
|
*/
|
|
751
|
-
hasOwnKeys(): Promise<boolean>;`,
|
|
752
|
+
hasOwnKeys(): Promise<boolean>;`,OS="\n /**\n * The bulb's theme override (`<html data-theme>`).\n *\n * - Get: the current override \u2014 `'dark'` | `'light'`, or `undefined` when\n * following the OS preference.\n * - Set `'dark'`/`'light'` to force and persist it (per-bulb); set\n * `undefined` to clear the override and follow the OS again.\n *\n * Drives `<html data-theme>`, so render off `html[data-theme=\"\u2026\"]` selectors\n * (or observe the attribute) rather than reading `tb.theme`.\n */\n theme: 'light' | 'dark' | undefined;",Yd=`
|
|
752
753
|
/**
|
|
753
754
|
* The mode this bulb is running in.
|
|
754
755
|
*
|
|
@@ -758,7 +759,7 @@ type AiChunk =
|
|
|
758
759
|
* - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
|
|
759
760
|
* client-only: AI, filesystem, and server RPC are unavailable)
|
|
760
761
|
*/
|
|
761
|
-
mode: 'local' | 'editor' | 'published' | 'embedded';`,
|
|
762
|
+
mode: 'local' | 'editor' | 'published' | 'embedded';`,RS=`
|
|
762
763
|
/**
|
|
763
764
|
* Local filesystem access (CLI only).
|
|
764
765
|
*
|
|
@@ -773,7 +774,7 @@ type AiChunk =
|
|
|
773
774
|
readBytes(path: string): Promise<Uint8Array>;
|
|
774
775
|
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
775
776
|
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
776
|
-
};`,
|
|
777
|
+
};`,_S=`
|
|
777
778
|
/**
|
|
778
779
|
* Async value inspector for tensor-like objects.
|
|
779
780
|
*
|
|
@@ -840,7 +841,7 @@ type AiChunk =
|
|
|
840
841
|
*
|
|
841
842
|
* @returns The full canonical URL
|
|
842
843
|
*/
|
|
843
|
-
url(): Promise<string>;`,
|
|
844
|
+
url(): Promise<string>;`,CS=`
|
|
844
845
|
/**
|
|
845
846
|
* Subscribe to a value pushed from the terminal via \`typebulb send <file> [message]\`.
|
|
846
847
|
*
|
|
@@ -855,25 +856,25 @@ type AiChunk =
|
|
|
855
856
|
* @param handler - Called with each pushed message.
|
|
856
857
|
* @returns An unsubscribe function.
|
|
857
858
|
*/
|
|
858
|
-
onMessage(handler: (message: any) => void): () => void;`,
|
|
859
|
+
onMessage(handler: (message: any) => void): () => void;`,NS="\n /**\n * Server-side function proxy.\n *\n * In the CLI, calls exported functions from the `**server.ts**` section.\n * `tb.server.log(...)` is a built-in that prints to CLI stdout (falls back to console.log on web).\n * User exports override built-ins of the same name.\n *\n * A normal export is awaited for its result (`await tb.server.fn()`). An `async function*`\n * export streams: `for await (const chunk of tb.server.gen())`. The call object supports both;\n * break the `for await` to cancel and tear down the server generator.\n */\n server: Record<string, (...args: any[]) => Promise<any> & AsyncIterable<any>>;",Ga=`${Wd}
|
|
859
860
|
/**
|
|
860
861
|
* Typebulb utilities namespace.
|
|
861
862
|
* Type \`tb.\` to discover available helpers.
|
|
862
863
|
*/
|
|
863
|
-
declare const tb: {${
|
|
864
|
+
declare const tb: {${TS}${_S}${PS}${NS}${CS}${Hd}${RS}${Vd}${OS}${Yd}
|
|
864
865
|
};
|
|
865
|
-
`,
|
|
866
|
+
`,za=`${Wd}
|
|
866
867
|
/**
|
|
867
868
|
* Typebulb utilities namespace (server-side).
|
|
868
869
|
* Type \`tb.\` to discover available helpers.
|
|
869
870
|
*/
|
|
870
|
-
declare const tb: {${
|
|
871
|
+
declare const tb: {${Hd}${Vd}${Yd}
|
|
871
872
|
};
|
|
872
|
-
`;var gt=class{constructor(e){this.store=e}async isNegative(e){let t=await
|
|
873
|
+
`;var gt=class{constructor(e){this.store=e}async isNegative(e){let t=await Ns(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await Ns(()=>this.store.get(e)))?.attempts||0)+1;await Ns(()=>this.store.set(e,{until:Date.now()+IS(n),attempts:n}))}async clearNegative(e){await Ns(()=>this.store.delete(e))}};function IS(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}async function Ns(r){try{return await r()}catch{return}}import DS from"p-limit";import{resolve as zd}from"resolve.exports";var Re={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},Is=["index.d.ts","index.d.mts"],Qa=/\.d\.(ts|mts|cts)$/i;function Ls(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function Gd(r){return[`${r}.d.ts`,`${r}.d.mts`]}function ze(r){if(!r||r==="./"||r==="/")return[...Is];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=Gd(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...Gd(`${n}index`)),t}async function Ms(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(LS(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function LS(r){return r===408||r===429||r>=500&&r<600}var $s=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)||Ls(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 Ms(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([...Is],t);if(!Qa.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([...Is,...n],t)}toResolutionResult(e){return{kind:Qa.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(zd(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(zd(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=Ka(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 MS}from"fflate";var Ds=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Ms(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=MS(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 Bs=class{constructor(e,t,n=new Ds){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 js=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(`
|
|
873
874
|
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
874
|
-
`),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
|
|
875
|
-
`);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
|
|
876
|
-
`,"utf8")}import*as Ze from"fs/promises";import*as
|
|
875
|
+
`),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 Qd="file:///node_modules",Fs=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${Qd}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=mt(t);return`${Qd}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as $S}from"lru-cache";function Xd(r){let e=new $S({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 an=class{constructor(e){this.inFlight=new Map,this.scanner=new js,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=Xd(e.cache),this.typescriptProvider=new $s(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Bs(e.cdnClient,e.cache),this.virtualFs=new Fs}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=Ls(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=DS(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(`
|
|
876
|
+
`);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 tp from"os";import*as Xa from"fs/promises";import*as Zd from"crypto";function fe(r){return Zd.createHash("sha1").update(r).digest("hex")}async function _e(r){try{return JSON.parse(await Xa.readFile(r,"utf8"))}catch{return}}async function qs(r){try{return await Xa.readFile(r,"utf8")}catch{return}}var ep=1,Qe=Ce.join(tp.homedir(),".typebulb","cache"),cn=Ce.join(Qe,"packages"),ln=Ce.join(Qe,"proxy"),Us=Ce.join(Qe,"dts"),BS=Ce.join(Qe,"emit"),Za;function U(){return Za||(Za=jS()),Za}function Js(r,e){return Ce.join(BS,fe(r),e)}async function jS(){await Xe.mkdir(Qe,{recursive:!0});let r=Ce.join(Qe,"version.json");if((await _e(r))?.version===ep)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:ep})+`
|
|
877
|
+
`,"utf8")}import*as Ze from"fs/promises";import*as rp from"path";async function oe(r,e){await Ze.mkdir(rp.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 Qt=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 ec=de.join(cn,"indexes"),np=de.join(cn,"pinned"),FS=de.join(cn,"meta"),qS=de.join(cn,"negative.json"),Ws=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new gt(new Qt(qS));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await U();let s=await qs(de.join(np,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 U(),await oe(de.join(np,fe(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await U();let t=await _e(de.join(ec,Ks(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 U(),await oe(de.join(ec,Ks(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await ip.rm(de.join(ec,Ks(e)+".json"),{force:!0})}async isNegative(e){return await U(),this.negativeCache.isNegative(e)}async recordNegative(e){await U(),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 U();let s=await _e(sp(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 U(),await oe(sp(e,t),JSON.stringify(o))}};function sp(r,e){return de.join(FS,Ks(r),encodeURIComponent(e)+".json")}function Ks(r){return r.replace(/\//g,"__")}var op={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 US=new Ws,{packageService:Hs,versionResolver:ap,cdnClient:cp,peerResolver:CR}=Jd(US,op);var lp=`
|
|
877
878
|
(() => {
|
|
878
879
|
// Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
|
|
879
880
|
// bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
|
|
@@ -1210,18 +1211,18 @@ declare const tb: {${Kd}${Wd}${Hd}
|
|
|
1210
1211
|
};
|
|
1211
1212
|
}
|
|
1212
1213
|
})();
|
|
1213
|
-
`;var
|
|
1214
|
+
`;var Xt=r=>r.replace(/<\/script/gi,"<\\/script");function Vs(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var Ys=` *, *::before, *::after { box-sizing: border-box; }
|
|
1214
1215
|
canvas { max-width: 100%; }
|
|
1215
1216
|
body { margin: 0; display: flow-root; font-family: system-ui, -apple-system, sans-serif; }
|
|
1216
1217
|
html[data-theme="dark"] { color-scheme: dark; }
|
|
1217
|
-
html[data-theme="light"] { color-scheme: light; }`;function
|
|
1218
|
+
html[data-theme="light"] { color-scheme: light; }`;function Gs(r,e){return` <script>
|
|
1218
1219
|
(function() {
|
|
1219
1220
|
try {
|
|
1220
|
-
var KEY = ${
|
|
1221
|
+
var KEY = ${Xt(JSON.stringify("tb-theme:"+r))};
|
|
1221
1222
|
var doc = document.documentElement;
|
|
1222
1223
|
var mq = window.matchMedia('(prefers-color-scheme: dark)');
|
|
1223
1224
|
var os = function() { return mq.matches ? 'dark' : 'light'; };
|
|
1224
|
-
var FORCED = ${
|
|
1225
|
+
var FORCED = ${Xt(JSON.stringify(e??null))};
|
|
1225
1226
|
var stored = function() {
|
|
1226
1227
|
try { var v = localStorage.getItem(KEY); return (v === 'dark' || v === 'light') ? v : undefined; }
|
|
1227
1228
|
catch (e) { return undefined; }
|
|
@@ -1249,19 +1250,19 @@ declare const tb: {${Kd}${Wd}${Hd}
|
|
|
1249
1250
|
});
|
|
1250
1251
|
} catch (e) {}
|
|
1251
1252
|
})();
|
|
1252
|
-
</script>`}function
|
|
1253
|
-
html, body { height: 100%; }`,d={imports:
|
|
1253
|
+
</script>`}function up(r){let{name:e,code:t,css:n,html:s,data:i,insight:o,importMap:a,theme:c,embedded:l}=r,f=s.trim()||'<div id="app"></div>',u=l?"":`
|
|
1254
|
+
html, body { height: 100%; }`,d={imports:KS(a.imports)};return`<!DOCTYPE html>
|
|
1254
1255
|
<html>
|
|
1255
1256
|
<head>
|
|
1256
1257
|
<meta charset="utf-8">
|
|
1257
1258
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1258
|
-
<title>${
|
|
1259
|
-
${
|
|
1259
|
+
<title>${Vs(e)} - typebulb</title>
|
|
1260
|
+
${Gs(e,c)}
|
|
1260
1261
|
<script type="importmap">
|
|
1261
1262
|
${JSON.stringify(d,null,2)}
|
|
1262
1263
|
</script>
|
|
1263
1264
|
<style>
|
|
1264
|
-
${
|
|
1265
|
+
${Ys}${u}
|
|
1265
1266
|
</style>
|
|
1266
1267
|
<style>
|
|
1267
1268
|
${n}
|
|
@@ -1270,21 +1271,21 @@ ${n}
|
|
|
1270
1271
|
<body>
|
|
1271
1272
|
${f}
|
|
1272
1273
|
|
|
1273
|
-
${i.length>0?`<script>window.__TB_DATA__ = ${
|
|
1274
|
-
${o?`<script>window.__TB_INSIGHT__ = ${
|
|
1274
|
+
${i.length>0?`<script>window.__TB_DATA__ = ${Xt(JSON.stringify(i))};</script>`:""}
|
|
1275
|
+
${o?`<script>window.__TB_INSIGHT__ = ${Xt(JSON.stringify(o))};</script>`:""}
|
|
1275
1276
|
|
|
1276
1277
|
<script>
|
|
1277
|
-
${
|
|
1278
|
+
${lp}
|
|
1278
1279
|
</script>
|
|
1279
1280
|
|
|
1280
|
-
${
|
|
1281
|
+
${JS}
|
|
1281
1282
|
|
|
1282
1283
|
<script type="module">
|
|
1283
|
-
${
|
|
1284
|
+
${Xt(t)}
|
|
1284
1285
|
globalThis.__tbEntryRan = true; /* load-failure backstop \u2014 see embedProtocol */
|
|
1285
1286
|
</script>
|
|
1286
1287
|
</body>
|
|
1287
|
-
</html>`}var
|
|
1288
|
+
</html>`}var JS=`<script>
|
|
1288
1289
|
(function () {
|
|
1289
1290
|
var framed = window.parent !== window;
|
|
1290
1291
|
var post = function (m) { try { parent.postMessage(m, '*'); } catch (e) {} }; /* framed only */
|
|
@@ -1380,32 +1381,32 @@ globalThis.__tbEntryRan = true; /* load-failure backstop \u2014 see embedProtoco
|
|
|
1380
1381
|
}
|
|
1381
1382
|
});
|
|
1382
1383
|
})();
|
|
1383
|
-
</script>`;function
|
|
1384
|
-
`,"utf8"),await ee.writeFile(X.join(e,"code.tsx"),r.code,"utf8"),await ee.writeFile(X.join(e,"tb.d.ts"),
|
|
1385
|
-
`,"utf8"),{dir:e}}function
|
|
1386
|
-
`))console.log(`${e} ${n}`);return r.length>0}function
|
|
1384
|
+
</script>`;function KS(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}import*as Qs from"fs/promises";import*as zs from"path";import{existsSync as fp,readFileSync as WS}from"fs";import{execFile as HS}from"child_process";import{promisify as VS}from"util";import{satisfies as YS}from"semver";var GS=VS(HS);async function Xs(r,e,t){let s=r.map(o=>zS(o,t)).filter(o=>!QS(o,e));if(s.length===0)return;await Qs.mkdir(e,{recursive:!0});let i=zs.join(e,"package.json");fp(i)||await Qs.writeFile(i,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${s.join(", ")}`),await GS("npm",["install","--no-audit","--no-fund",...s],{cwd:e,shell:!0})}function zS(r,e){if(!e||N.parse(r).version)return r;let t=e[r];return t?`${r}@${t}`:r}function QS(r,e){let{name:t,version:n}=N.parse(r),s=zs.join(e,"node_modules",t);if(!fp(s))return!1;if(!n)return!0;try{let i=JSON.parse(WS(zs.join(s,"package.json"),"utf-8")).version;return YS(i,n)}catch{return!1}}function Zs(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]}rr();ci();wt();async function vp(r){let e=vt(r.provider,r.model);if(typeof e=="string")throw new Error(e);let t=await St(e,r);if(!t.ok){let n=await un(t,e.protocol);throw new Error(n.message)}return{response:t,protocol:e.protocol}}async function ok(r){let{response:e,protocol:t}=await vp(r);return{text:await bt(e,t)}}async function*ak(r){let{response:e,protocol:t}=await vp(r);yield*tr(e,t)}function Sp(){let r=Object.assign(ok,{stream:ak});globalThis.tb=Object.freeze({ai:r,models:()=>Ne(),hasOwnKeys:ai,mode:"local"})}async function kp(r){let t=(await et.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?li.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=Yt(t);return{bulb:n,config:Il(n.config),warnings:Ol(e)}}async function pn(r,e,t,n){let s=Ua(r,{serverOnly:!0});if(s.error)throw new Error(`Server compilation error: ${s.error}`);let i=s.code;t&&(i=await vl(i,t));let o=li.join(e,".typebulb");await et.mkdir(o,{recursive:!0});let a=Zs(i);a.length>0&&await Xs(a,o,n);let c=li.join(o,"server.mjs");return await et.writeFile(c,i,"utf-8"),Sp(),await import(`${ck(c).href}?t=${Date.now()}`)}async function fc(r,e,t,n,s){let{bulb:i,config:o}=await he(r),a=Id(i.data);Dd(i.code,o.dependencies??{});let c=Ua(i.code,{jsxImportSource:o.ts?.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await Hs.buildImportMap(c.code,o.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let f=up({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 pn(i.server,s,n,o.dependencies)),{html:f,bulb:i,serverExports:u}}Zr();mn();var Ap=new Set(["claude","pi"]);function Tp(r){return Ap.has(r)}function or(){return[...Ap]}import*as tt from"path";import{spawn as Ck,execSync as Nk}from"child_process";import{createRequire as Ik}from"module";import{existsSync as Lk}from"fs";import*as ee from"fs/promises";import*as X from"path";import*as ar from"path";var yk=ar.join(Us,"pkg"),bk=ar.join(Us,"files"),wk=ar.join(Us,"negative.json"),pi=class{pkgMem=new Map;fileMem=new Map;negativeCache=new gt(new Qt(wk));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await U();let t=await _e(Pp(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 di(async()=>{await U(),await oe(Pp(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await U();let t=await qs(Op(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await di(async()=>{await U(),await oe(Op(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await di(async()=>{await U(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return di(()=>this.negativeCache.clearNegative(e))}};async function di(r){try{await r()}catch{}}function Pp(r){return ar.join(yk,fe(r)+".json")}function Op(r){return ar.join(bk,fe(r)+".txt")}var hc;function vk(){return hc||(hc=new an({cache:new pi,cdnClient:cp,packageService:Hs,versionResolver:ap})),hc}var Rp="file:///node_modules/";async function _p(r){let e=Js(r.emitKey,"typecheck");await U(),await ee.rm(e,{recursive:!0,force:!0}),await ee.mkdir(e,{recursive:!0});let t=Ek(r.jsxImportSource,r.dependencies),n=await vk().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=mi(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=mi(u.path);d&&(a[u.module]=[`./node_modules/${d}`])}for(let f of i){if(f.ambient)continue;let u=mi(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=mi(u.path);d&&c.add(`node_modules/${d}`)}if(r.local){delete a[r.local.name];let f=await Ak(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=Sk(r.jsxImportSource,a,[...c]);return await ee.writeFile(X.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1385
|
+
`,"utf8"),await ee.writeFile(X.join(e,"code.tsx"),r.code,"utf8"),await ee.writeFile(X.join(e,"tb.d.ts"),Ga,"utf8"),{dir:e}}var gc={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function Sk(r,e,t=[]){return{compilerOptions:{...gc,lib:kk([...Ha,...Va]),jsx:"react-jsx",jsxImportSource:r??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function kk(r){return Ya(r).map(e=>xk(e.name))}function xk(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 Ek(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function mi(r){if(!r.startsWith(Rp))return;let e=r.slice(Rp.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function Ak(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 Tk(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 Tk(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 Pk}from"fs";var Ok="^22";async function Cp(r){let e=Js(r.emitKey,"typecheck-server");await U(),await ae.rm(e,{recursive:!0,force:!0}),await ae.mkdir(e,{recursive:!0});let t=Le.join(r.bulbDir,".typebulb"),n=Zs(r.server).filter(o=>o!==r.local?.name);await Xs([`@types/node@${Ok}`,...n],t,r.dependencies);let s=Le.join(t,"node_modules"),i=Le.join(e,"node_modules");return await _k(s,i),await ae.writeFile(Le.join(e,"server.ts"),r.server,"utf8"),await ae.writeFile(Le.join(e,"tb.d.ts"),za,"utf8"),await ae.writeFile(Le.join(e,"tsconfig.json"),JSON.stringify(Rk(r.local),null,2)+`
|
|
1386
|
+
`,"utf8"),{dir:e}}function Rk(r){let e={...gc,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 _k(r,e){if(!Pk(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)}_s();async function Ip(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=Np(en(t.code,{target:"client",dependencies:n.dependencies??{}}),"client")||i),t.server&&(i=Np(en(t.server,{target:"server"}),"server")||i);let o=Dk([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 _p({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 Cp({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 Mk(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 Np(r,e){for(let t of r)for(let n of t.message.split(`
|
|
1387
|
+
`))console.log(`${e} ${n}`);return r.length>0}function Mk(r,e){return new Promise(t=>{let n=Ck(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 $k=Ik(import.meta.url);function Dk(r){let e=n=>{try{let s=$k.resolve("typescript/package.json",{paths:n}),i=tt.join(tt.dirname(s),"lib","tsc.js");return Lk(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=Nk("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}hi();mn();async function Lp(r,e){let{bulb:t}=await he(r),n=cr(t);if(kt(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.)")}mn();import*as hn from"path";async function Mp(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=mc();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=hn.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),ir(t,e),console.log(e?`Trusted ${hn.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${hn.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}Me();import*as Pm from"readline";Ai();Bc();var wn={claude:()=>new fr,pi:()=>new mr};function Em(){for(let r of Object.values(wn))try{r().ensureHarnessSupport()}catch{}}function vn(){for(let r of Object.keys(wn))try{if(wn[r]().detectsSelf())return r}catch{}}function Am(r){let e=or(),t=new Map(e.filter(i=>wn[i]).map(i=>[i,wn[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)))}}Oi();function jc(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 Om(r){let e=Am(process.cwd());if("ambiguous"in e){let t=await u0(r,e.ambiguous);return t?Tm(r,t):f0(r,e.ambiguous)}return Tm(r,e.name)}async function Tm(r,e){let t,n;try{t=await Vp(e)}catch(f){n=f instanceof Error?f.message:String(f)}let{lit:s,litLink:i,brand:o}=jc(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(dr())}`,` ${s(Tt())}`],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",e==="pi"?" arm a wait for its render verdict \u2014 run it plainly:":" 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(`
|
|
1387
1388
|
`)+`
|
|
1388
|
-
`)}async function
|
|
1389
|
+
`)}async function u0(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=jc(!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(`
|
|
1389
1390
|
`)+`
|
|
1390
|
-
`);let i=
|
|
1391
|
+
`);let i=Pm.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 f0(r,e){let{lit:t,brand:n}=jc(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(`
|
|
1391
1392
|
`)+`
|
|
1392
|
-
`)}import{readFileSync as
|
|
1393
|
-
`)){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
|
|
1394
|
-
`+e)}function
|
|
1393
|
+
`)}import{readFileSync as d0,existsSync as p0}from"fs";import*as De from"path";function m0(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function xe(r,e=process.cwd()){let t={},n=[];for(let s of m0(r)){let i;try{i=d0(De.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[o,a]of h0(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:r,sources:t,loaded:n}}function*h0(r){for(let e of r.split(`
|
|
1394
|
+
`)){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 g0(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?g0(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"])p0(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}`)}}wt();async function Rm(r){xe(r);let e=await Ne();if(e.length>0){console.log(wp(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!uc()){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(nr))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.")}Oi();import*as _m from"fs/promises";async function Cm(r){let e=Tt(),t;try{t=await _m.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(om(t,r))}fi();import*as Nm from"path";Me();function y0(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 Sn=r=>r.agent??Nm.basename(r.file);function Im(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"} ${t.file}`)}function Fc(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Im(r,t=>console.log(t)),console.log(`
|
|
1395
|
+
`+e)}function qc(r,e,t,n,s){let i=y0(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>\`):`),Im(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Lm(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),Fc(await K(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=qc(await K(),r,"logs",process.cwd(),vn());if(e.clear){Up(t.pid),console.log(`Cleared log for ${Sn(t)} (pid ${t.pid}).`);return}let n=ve(t.pid),s=n.text;if(e.run!==void 0&&(s=Jp(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(`
|
|
1395
1396
|
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1396
1397
|
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1397
1398
|
`)&&process.stdout.write(`
|
|
1398
|
-
`),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
|
|
1399
|
-
`);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 ${
|
|
1400
|
-
${l}`:"";return g.text(`Forbidden: this capability requires --trust.${O}`,403)}await w()},b=async(g,w)=>{let k=g.req.header("sec-fetch-site");if(k){if(k!=="same-origin")return g.text(`Forbidden: ${k} request`,403)}else{let x=g.req.header("origin");if(x&&!
|
|
1399
|
+
`),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 b0=r=>new Promise(e=>setTimeout(e,r));async function Mm(r,e){if(!r){Fc(await K(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=qc(await K(),r,"wait",process.cwd(),vn()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=e.timeoutSec??1800,a=e.match??"",c=ve(t.pid).offset,l=Sc(t.pid,a)??(a?Sc(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(`
|
|
1400
|
+
`);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 ${Sn(t)} within ${o}s`),y=2;break}if(!xc(t.pid)){b||(console.error(`server ${Sn(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await b0(400)}yi(t.pid,f,a),process.exit(y)}async function $m(r){if(!r){Fc(await K(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=qc(await K(),r,"stop",process.cwd(),vn());await Et(e.pid),console.log(`Stopped ${Sn(e)} (pid ${e.pid}, ${e.url}).`)}async function Dm(r){let e=process.cwd(),t=r==="agent"?vn():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=>Et(i.pid))),console.log(`Stopped ${n.length} ${s}${n.length===1?"":"s"}:`);for(let i of n)console.log(` ${i.url} pid ${i.pid} ${Sn(i)}`)}Me();import*as Bm from"path";async function jm(r,e,t=0){let n=Bm.resolve(r),s=lr(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 Km from"fs/promises";import*as hr from"path";import{EventEmitter as Jm}from"events";hi();import L0 from"open";rr();import{Hono as E0}from"hono";import{serve as A0}from"@hono/node-server";import{streamSSE as T0}from"hono/streaming";import*as Rt from"fs/promises";import*as ye from"path";import*as Uc from"fs/promises";import*as kn from"path";var Ni=class{async get(e){let t=fe(e),n=kn.join(ln,t+".bin"),s=kn.join(ln,t+".json");try{let[i,o]=await Promise.all([Uc.readFile(n),Uc.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await U();let n=fe(e),s=kn.join(ln,n+".bin"),i=kn.join(ln,n+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([oe(s,t.body),oe(i,JSON.stringify(o))])}};Me();wt();ci();rr();import{stream as w0}from"hono/streaming";var v0="X-TB-Stream";function Jc(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 Kc(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(v0,"1"),w0(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:Jc(s)}))}finally{try{await n.return?.()}catch{}}})}var Wc={log:(...r)=>console.log(...r)};function Ii(r,e){let t=r?.[e]??Wc[e];return typeof t=="function"?t:void 0}function Li(r){return r.constructor?.name==="AsyncGeneratorFunction"}var S0=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,k0=/[?&]target=/,x0=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function Fm(r,e=""){return S0.test(r)?!0:x0.test(r)&&k0.test(e)}var Um="127.0.0.1",P0=new Set(["localhost","127.0.0.1","::1"]);function O0(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function R0(r){let e=O0(r);return!!e&&P0.has(e)}function _0(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function Hc(r){return r instanceof Error?r.message:"Unknown error"}async function Mi(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 E0;u.use("*",async(g,w)=>{if(!R0(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 k=new URL(g.req.url).pathname,x=k.startsWith("/__fs")?"the filesystem":k==="/__ai"?"AI (your API keys)":"server-side code (server.ts)";Kp(process.pid,x);let O=l?`
|
|
1401
|
+
${l}`:"";return g.text(`Forbidden: this capability requires --trust.${O}`,403)}await w()},b=async(g,w)=>{let k=g.req.header("sec-fetch-site");if(k){if(k!=="same-origin")return g.text(`Forbidden: ${k} request`,403)}else{let x=g.req.header("origin");if(x&&!_0(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 k=i.listenerCount("message");return i.emit("message",w),g.json({clients:k})})),u.get("/",g=>g.html(e())),u.post("/__fs/read",async g=>{try{let{path:w}=await g.req.json(),k=Yc(w,t),x=await Rt.readFile(k);return new Response(new Uint8Array(x),{headers:{"Content-Type":"application/octet-stream"}})}catch(w){let k=Hc(w);return g.json({error:k},400)}}),u.post("/__fs/write",async g=>{try{let w=g.req.query("path");if(!w)return g.json({error:"Missing path"},400);let k=Yc(w,t);return await Rt.mkdir(ye.dirname(k),{recursive:!0}),await Rt.writeFile(k,Buffer.from(await g.req.arrayBuffer())),g.json({success:!0})}catch(w){let k=Hc(w);return g.json({error:k},400)}}),u.post("/__api/:name",async g=>{try{let w=g.req.param("name"),k=Ii(o?.(),w);if(!k)return g.json({error:`API function '${w}' not found`},404);let{args:x}=await g.req.json();if(Li(k))return Kc(g,k(...x||[]));let O=await k(...x||[]);return g.json({result:O})}catch(w){let k=Hc(w);return g.json({error:k},500)}}),u.post("/__ai",async g=>{try{let{messages:w,system:k,effort:x,provider:O,model:A,webSearch:M,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=vt(O,A);if(typeof V=="string")return g.json({message:V,code:"unknown",retryable:!1},400);let B=await St(V,{messages:w,system:k,effort:x,webSearch:M});if(!B.ok){let Yi=await un(B,V.protocol);return g.json(Yi,B.status)}if(te)return Kc(g,tr(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(Jc(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 ai())}catch{return g.json(!1,200)}});let m=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],y=new Ni;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&&qm(u,`/local/${a.name}/`,a.serveDir),f&&qm(u,f.mount,f.dir);async function E(g,w){let k;try{k=new URL(w)}catch{return g.text("Invalid URL",400)}if(k.protocol!=="https:")return g.text("HTTPS only",400);if(!m.includes(k.hostname))return g.text("Host not allowed",403);let x=await y.get(w);if(x)return new Response(x.body,{status:200,headers:Vc(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,M=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:M})}catch{}})(),new Response(te,{status:O.status,headers:Vc(A,M)})}return new Response(null,{status:O.status,headers:Vc(A,M)})}catch(O){return g.text(`Proxy fetch failed: ${O instanceof Error?O.message:O}`,502)}}(s||i)&&u.get("/__reload",g=>T0(g,async w=>{let k=()=>{w.writeSSE({event:"reload",data:""})},x=O=>{w.writeSSE({event:"message",data:JSON.stringify(O)})};for(s?.on("reload",k),i?.on("message",x),w.onAbort(()=>{s?.removeListener("reload",k),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 Fm(w.pathname,w.search)?E(g,"https://esm.sh"+w.pathname+w.search):g.text("Not Found",404)});let T=A0({fetch:u.fetch,port:n,hostname:Um});return{port:n,close:()=>T.close()}}function Vc(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 qm(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=Yc(i,t),a=await Rt.readFile(o);return new Response(a,{headers:{"Content-Type":C0(o)}})}catch{return n.text("Not Found",404)}})}function C0(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 Yc(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 xn(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,Um,()=>{let s=n.address(),i=typeof s=="object"&&s?s.port:r;n.close(()=>t(i))}),n.on("error",()=>{t(xn(r+1))})})}import N0 from"chokidar";var I0={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function _t(r){let{target:e,onChange:t,events:n="change",debounceMs:s=150}=r,i,o=N0.watch(e,I0),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 Wm(r,e,t,n,s){let i=process.cwd(),o=bi(process.pid),a=e.watch?new Jm:void 0,c=new Jm;c.setMaxListeners(0);let l=xe(e.mode),f=await Ac(r);f.length&&console.log(`Replacing the running server for this bulb (pid ${f.map(x=>x.pid).join(", ")})`);let u=1;console.log(kc(u)),console.log(`Loading ${hr.basename(r)}...`);let{html:d,bulb:p,serverExports:b}=await fc(r,e.watch,e.trust,n,s);nt(l,r,p.server);let m=await xn(e.port),y=await Mi({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:cr(p);await wi({pid:process.pid,port:m,url:E,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,predicted:T}),console.log(`
|
|
1401
1402
|
${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:
|
|
1402
1403
|
${t}
|
|
1403
1404
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
1404
1405
|
`),e.watch&&console.log(` Watching for changes...
|
|
1405
|
-
`);let g,w;if(e.watch&&a&&(g=
|
|
1406
|
+
`);let g,w;if(e.watch&&a&&(g=_t({target:r,onChange:async()=>{try{console.log("Recompiling...");let x=await fc(r,!0,e.trust,n,s);d=x.html,b=x.serverExports,u++,console.log(kc(u)),a.emit("reload")}catch(x){console.error("Compile error:",x)}}}),n)){let{name:x,serveDir:O}=n;w=_t({target:O,events:"all",onChange:()=>{console.log(`Local package '${x}' changed. Browser reloading...
|
|
1406
1407
|
`),a.emit("reload")}})}e.open&&(f.some(x=>x.port===m)?console.log(` Reusing the open browser tab.
|
|
1407
|
-
`):await
|
|
1408
|
-
Shutting down...`),y.close(),g?.(),w?.(),o(),await
|
|
1408
|
+
`):await L0(E));let k=async()=>{console.log(`
|
|
1409
|
+
Shutting down...`),y.close(),g?.(),w?.(),o(),await xt(process.pid);let x=hr.join(hr.dirname(r),".typebulb","server.mjs");await Km.rm(x,{force:!0}).catch(()=>{}),process.exit(0)};process.on("SIGINT",k),process.on("SIGTERM",k)}import{readFileSync as jh,copyFileSync as mA,existsSync as hA}from"fs";import*as Z from"path";import{fileURLToPath as gA}from"url";import{EventEmitter as yA}from"events";import Fh from"open";Me();var Gc=r=>`/agents/${r}/client.js`,M0=`
|
|
1409
1410
|
(() => {
|
|
1410
1411
|
const api = async (name, ...args) => {
|
|
1411
1412
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -1440,15 +1441,15 @@ Shutting down...`),y.close(),g?.(),w?.(),o(),await kt(process.pid);let x=pr.join
|
|
|
1440
1441
|
es.onerror = () => { es.close(); };
|
|
1441
1442
|
}
|
|
1442
1443
|
})();
|
|
1443
|
-
`;function
|
|
1444
|
+
`;function Hm(r){let{name:e,agent:t,styles:n,mountHtml:s,watch:i,theme:o}=r,a=Gc(t);return`<!DOCTYPE html>
|
|
1444
1445
|
<html>
|
|
1445
1446
|
<head>
|
|
1446
1447
|
<meta charset="utf-8">
|
|
1447
1448
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1448
|
-
<title>${
|
|
1449
|
-
${
|
|
1449
|
+
<title>${Vs(e)} - typebulb</title>
|
|
1450
|
+
${Gs(e,o)}
|
|
1450
1451
|
<style>
|
|
1451
|
-
${
|
|
1452
|
+
${Ys}
|
|
1452
1453
|
</style>
|
|
1453
1454
|
<style>
|
|
1454
1455
|
${n}
|
|
@@ -1460,19 +1461,19 @@ ${s}
|
|
|
1460
1461
|
${i?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
|
|
1461
1462
|
|
|
1462
1463
|
<script>
|
|
1463
|
-
${
|
|
1464
|
+
${M0}
|
|
1464
1465
|
</script>
|
|
1465
1466
|
|
|
1466
1467
|
<script type="module" src="${a}"></script>
|
|
1467
1468
|
</body>
|
|
1468
|
-
</html>`}var
|
|
1469
|
-
${n.url}`),r.open&&await
|
|
1469
|
+
</html>`}var bA={claude:()=>Promise.resolve().then(()=>(Oh(),Ph)),pi:()=>Promise.resolve().then(()=>(Bh(),Dh))};async function qh(r){let e=process.cwd(),t=r.agentTarget;Tp(t)||(console.error(`Unknown agent '${t}'. Known: ${or().join(", ")}.`),process.exit(1));let n=await Ec(e,t);if(n){console.log(`Mirror '${t}' is already running for this project:
|
|
1470
|
+
${n.url}`),r.open&&await Fh(n.url);return}let s=bi(process.pid),i=r.watch?new yA:void 0,o=xe(r.mode),a=await bA[t](),c=a.displayName||`${t} mirror`;nt(o,Z.join(e,"mirror"));let l=Z.dirname(gA(import.meta.url)),f=Z.join(l,"agents",t),u=Z.join(l,"..","cli","agents"),d=Z.join(f,"styles.css"),p=Z.join(f,"index.html"),b=()=>Hm({name:c,agent:t,styles:jh(d,"utf8"),mountHtml:jh(p,"utf8"),watch:r.watch}),m=await xn(r.port),y=await Mi({getHtml:b,basePath:e,port:m,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${Z.posix.dirname(Gc(t))}/`,dir:f}}),E=`http://localhost:${m}`;await wi({pid:process.pid,port:m,url:E,file:`agent:${t}`,cwd:e,startedAt:Date.now(),trust:!0,agent:t}),console.log(`
|
|
1470
1471
|
${c}`),console.log(` ${E}`),m!==r.port&&console.log(` (port ${r.port} was busy)`),r.watch&&console.log(` Watching for changes...
|
|
1471
|
-
`);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"])
|
|
1472
|
-
`),i.emit("reload")}catch(M){console.error("Mirror rebuild failed:",M instanceof Error?M.message:M)}finally{A=!1}}}})}r.open&&await
|
|
1473
|
-
Shutting down...`);try{a.shutdownSwitcher?.()}catch{}try{a.shutdownComposer?.()}catch{}y.close(),k?.(),s(),await
|
|
1474
|
-
`),
|
|
1475
|
-
`)}catch(p){
|
|
1476
|
-
`),
|
|
1477
|
-
`),process.exit(1)}function
|
|
1478
|
-
${e}`),process.exit(1))}async function
|
|
1472
|
+
`);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"])mA(Z.join(g,A),Z.join(f,A))}let k;if(r.watch&&i){let O=hA(T),A=!1;k=_t({target:O?u:f,events:"all",onChange:async()=>{if(!A){A=!0;try{O&&await w(),console.log(`Mirror rebuilt. Browser reloading...
|
|
1473
|
+
`),i.emit("reload")}catch(M){console.error("Mirror rebuild failed:",M instanceof Error?M.message:M)}finally{A=!1}}}})}r.open&&await Fh(E);let x=async()=>{console.log(`
|
|
1474
|
+
Shutting down...`);try{a.shutdownSwitcher?.()}catch{}try{a.shutdownComposer?.()}catch{}y.close(),k?.(),s(),await xt(process.pid),process.exit(0)};process.on("SIGINT",x),process.on("SIGTERM",x)}import*as Uh from"path";async function Jh(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 pn(c.server,s,n,l.dependencies)};console.log(`Running ${Uh.basename(r)}...`),await a(),e&&(console.log(`Watching for changes...
|
|
1475
|
+
`),_t({target:r,onChange:async()=>{try{console.log("Re-running..."),await a()}catch(c){console.error("Error:",c)}}}))}import{Console as wA}from"node:console";Me();async function Hh(r,e,t,n,s){EA();try{let p=lr(await K(),r)[0];p&&(yi(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||On("This bulb has no **server.ts** block; nothing to call."),nt(i,r,o.server);let c;try{c=await pn(o.server,s,n,a.dependencies)}catch(p){On(p instanceof Error?p.message:String(p))}let l=Ii(c,e.fn);if(!l){let p=[...Object.keys(c).filter(b=>typeof c[b]=="function"),...Object.keys(Wc)];On(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let f=await vA(e);if(Li(l)){try{for await(let p of l(...f))await Wh(JSON.stringify(p,Vh)+`
|
|
1476
|
+
`)}catch(p){On(p instanceof Error?p.stack??p.message:String(p))}return Kh(0)}let u;try{u=await l(...f)}catch(p){On(p instanceof Error?p.stack??p.message:String(p))}let d=xA(u);d!==void 0&&await Wh(d+`
|
|
1477
|
+
`),Kh(0)}function Kh(r){process.exitCode=r,setTimeout(()=>process.exit(r),2e3).unref?.()}async function vA(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await AA()),kA(e)}return SA(r.positional)}function SA(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function kA(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 xA(r){if(r!==void 0)return JSON.stringify(r,Vh,2)}function Vh(r,e){return typeof e=="bigint"?e.toString():e}function On(r){process.stderr.write(r+`
|
|
1478
|
+
`),process.exit(1)}function EA(){let r=new wA(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 Wh(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function AA(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var cl="0.24.0";function Yh(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
1479
|
+
${e}`),process.exit(1))}async function TA(){let r=Sl(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${cl}`),process.exit(0)),r.help&&(kl(),process.exit(0)),Em(),r.subcommand==="logs"){await Lm(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await Mm(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await Dm(r.stopScope):await $m(r.file||void 0);return}if(r.subcommand==="send"){await jm(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await Cm(cl);return}if(r.subcommand==="models"){await Rm(r.mode);return}if(r.subcommand==="agent"){await(r.agentTarget?qh(r):Om(cl));return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await Mp(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let l=await kp(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 Gh.access(e).then(()=>!0,()=>!1)||(or().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 Lp(e,s);return}let i=!r.noTrust&&kt(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 wl(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 Ip(e,a);return}let c=Be.dirname(e);if(r.subcommand==="call"){Yh(r.trust,s),await Hh(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a,c);return}if(o&&o.bulb.server&&(Rs(o.bulb)||r.server)){Yh(r.trust,s),await Jh(e,r.watch,r.mode,a,c);return}await Wm(e,r,s,a,c)}TA().catch(r=>{console.error("Error:",r.message),process.exit(1)});
|