typebulb 0.18.1 → 0.18.3
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/README.md +4 -4
- package/dist/index.js +231 -172
- 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 Dh=Object.create;var Ei=Object.defineProperty;var Bh=Object.getOwnPropertyDescriptor;var jh=Object.getOwnPropertyNames;var Fh=Object.getPrototypeOf,qh=Object.prototype.hasOwnProperty;var hn=(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 C=(r,e)=>()=>(r&&(e=r(r=0)),e);var T=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Cc=(r,e)=>{for(var t in e)Ei(r,t,{get:e[t],enumerable:!0})},Uh=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jh(e))!qh.call(r,s)&&s!==t&&Ei(r,s,{get:()=>e[s],enumerable:!(n=Bh(e,s))||n.enumerable});return r};var Jh=(r,e,t)=>(t=r!=null?Dh(Fh(r)):{},Uh(e||!r||!r.__esModule?Ei(t,"default",{value:r,enumerable:!0}):t,r));function Fc(r){return vt.find(e=>wt[e].path===r)}function Uc(r){return!!r?.startsWith("typebulb")}var wt,vt,qc,mn=C(()=>{wt={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"}},vt=["code","css","html","data","infer","insight","config","notes"];qc="typebulb/v1"});function Oi(r){return/[:\n"']/.test(r)||r.startsWith(" ")||r.endsWith(" ")?`"${r.replace(/"/g,'\\"')}"`:r}function Ci(r){return r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1).replace(/\\"/g,'"'):r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}var gn=C(()=>{});function Qe(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=tm(n);if(!s)return null;let i=new Map,o=[],a=t;for(;t<e.length;){let l=e[t]?.trim()?.match(Jc);if(l){let d=l[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let u=e[t]?.match(Kc);if(!u){t++;continue}let f=u[1];t++;let p=[];for(;t<e.length&&!e[t]?.match(new RegExp(`^${f}\\s*$`));)p.push(e[t]),t++;let m=t<e.length;t++,o.push(...Zh(d,p,m)),i.set(d,p.join(`
|
|
5
|
+
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function Zh(r,e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s]?.trim().match(Jc);i&&Xh.has(i[1].trim())&&em(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 em(r,e){let t=e+1;for(;t<r.length&&r[t]?.trim()==="";)t++;return!!r[t]?.match(Kc)}function tm(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=Ci(i);break}}return!Uc(e.format)||!e.name?null:e}function Wc(r){return Qe(r)?.warnings??[]}function Hc(r){let e=Object.fromEntries(vt.map(t=>[t,r.files.get(wt[t].path)||""]));return{name:r.frontmatter.name,...e}}var Jc,Kc,Xh,Vc=C(()=>{mn();gn();Jc=/^\*\*(.+)\*\*$/,Kc=/^(`{3,})(\w*)\s*$/,Xh=new Set(vt.map(r=>wt[r].path))});function rm(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 Yc(r){let e=vt.filter(t=>r[t]).map(t=>{let{path:n}=wt[t],s=r[t],i=n.split(".").pop(),o=rm(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=er(a,"^[^<]*[ /]>",0),l=c!==-1&&a[c-1]==="/";if(n&&console.log("[xml-utils] selfClosing:",l),l===!1)if(s){let p=0,m=1,h=0;for(;(c=er(a,"[ /]"+e+">",p))!==-1;){let y=a.substring(p,c+1);if(m+=
|
|
12
|
-
>]`),h+=
|
|
13
|
-
`)}};nr.defaultYaml={explicit:!1,version:"1.2"};nr.defaultTags={"!!":"tag:yaml.org,2002:"};
|
|
14
|
-
`)?
|
|
9
|
+
${o}`});return["---",`format: ${qc}`,`name: ${Oi(r.name)}`,"---","",...e].join(`
|
|
10
|
+
`)}var Gc=C(()=>{mn();gn()});function zc(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}var Qc=C(()=>{});var Xc=C(()=>{});function Ri(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index:-1}var Zc=C(()=>{});function er(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index+s[0].length-1:-1}var el=C(()=>{});function yn(r,e){let t=new RegExp(e,"g"),n=r.match(t);return n?n.length:0}var tl=C(()=>{});function tr(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=Ri(r,`<${e}[
|
|
11
|
+
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=er(a,"^[^<]*[ /]>",0),l=c!==-1&&a[c-1]==="/";if(n&&console.log("[xml-utils] selfClosing:",l),l===!1)if(s){let p=0,m=1,h=0;for(;(c=er(a,"[ /]"+e+">",p))!==-1;){let y=a.substring(p,c+1);if(m+=yn(y,"<"+e+`[
|
|
12
|
+
>]`),h+=yn(y,"</"+e+">"),h>=m)break;p=c}}else c=er(a,"[ /]"+e+">",0);let d=o+e.length+c+1;if(n&&console.log("[xml-utils] end:",d),d===-1)return;let u=r.slice(o,d),f;return l?f=null:f=u.slice(u.indexOf(">")+1,u.lastIndexOf("<")),{inner:f,outer:u,start:o,end:d}}var Ni=C(()=>{Zc();el();tl()});var _i=C(()=>{Ni()});var Ii=C(()=>{_i()});var rl=C(()=>{Ii()});var nl=C(()=>{});var sl=C(()=>{Xc();Ni();_i();rl();Ii();nl()});var _=T(z=>{"use strict";var Li=Symbol.for("yaml.alias"),il=Symbol.for("yaml.document"),bn=Symbol.for("yaml.map"),ol=Symbol.for("yaml.pair"),$i=Symbol.for("yaml.scalar"),wn=Symbol.for("yaml.seq"),Te=Symbol.for("yaml.node.type"),im=r=>!!r&&typeof r=="object"&&r[Te]===Li,om=r=>!!r&&typeof r=="object"&&r[Te]===il,am=r=>!!r&&typeof r=="object"&&r[Te]===bn,cm=r=>!!r&&typeof r=="object"&&r[Te]===ol,al=r=>!!r&&typeof r=="object"&&r[Te]===$i,lm=r=>!!r&&typeof r=="object"&&r[Te]===wn;function cl(r){if(r&&typeof r=="object")switch(r[Te]){case bn:case wn:return!0}return!1}function um(r){if(r&&typeof r=="object")switch(r[Te]){case Li:case bn:case $i:case wn:return!0}return!1}var fm=r=>(al(r)||cl(r))&&!!r.anchor;z.ALIAS=Li;z.DOC=il;z.MAP=bn;z.NODE_TYPE=Te;z.PAIR=ol;z.SCALAR=$i;z.SEQ=wn;z.hasAnchor=fm;z.isAlias=im;z.isCollection=cl;z.isDocument=om;z.isMap=am;z.isNode=um;z.isPair=cm;z.isScalar=al;z.isSeq=lm});var rr=T(Mi=>{"use strict";var H=_(),te=Symbol("break visit"),ll=Symbol("skip children"),we=Symbol("remove node");function vn(r,e){let t=ul(e);H.isDocument(r)?St(null,r.contents,t,Object.freeze([r]))===we&&(r.contents=null):St(null,r,t,Object.freeze([]))}vn.BREAK=te;vn.SKIP=ll;vn.REMOVE=we;function St(r,e,t,n){let s=fl(r,e,t,n);if(H.isNode(s)||H.isPair(s))return dl(r,n,s),St(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=St(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===te)return te;o===we&&(e.items.splice(i,1),i-=1)}}}else if(H.isPair(e)){n=Object.freeze(n.concat(e));let i=St("key",e.key,t,n);if(i===te)return te;i===we&&(e.key=null);let o=St("value",e.value,t,n);if(o===te)return te;o===we&&(e.value=null)}}return s}async function Sn(r,e){let t=ul(e);H.isDocument(r)?await xt(null,r.contents,t,Object.freeze([r]))===we&&(r.contents=null):await xt(null,r,t,Object.freeze([]))}Sn.BREAK=te;Sn.SKIP=ll;Sn.REMOVE=we;async function xt(r,e,t,n){let s=await fl(r,e,t,n);if(H.isNode(s)||H.isPair(s))return dl(r,n,s),xt(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 xt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===te)return te;o===we&&(e.items.splice(i,1),i-=1)}}}else if(H.isPair(e)){n=Object.freeze(n.concat(e));let i=await xt("key",e.key,t,n);if(i===te)return te;i===we&&(e.key=null);let o=await xt("value",e.value,t,n);if(o===te)return te;o===we&&(e.value=null)}}return s}function ul(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 fl(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 dl(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`)}}Mi.visit=vn;Mi.visitAsync=Sn});var Di=T(hl=>{"use strict";var pl=_(),dm=rr(),pm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},hm=r=>r.replace(/[!,[\]{}]/g,e=>pm[e]),nr=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+hm(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&&pl.isNode(e.contents)){let i={};dm.visit(e.contents,(o,a)=>{pl.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
|
+
`)}};nr.defaultYaml={explicit:!1,version:"1.2"};nr.defaultTags={"!!":"tag:yaml.org,2002:"};hl.Directives=nr});var xn=T(sr=>{"use strict";var ml=_(),mm=rr();function gm(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function gl(r){let e=new Set;return mm.visit(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function yl(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function ym(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s??(s=gl(r));let o=yl(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(ml.isScalar(o.node)||ml.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}}sr.anchorIsValid=gm;sr.anchorNames=gl;sr.createNodeAnchors=ym;sr.findNewAnchor=yl});var Bi=T(bl=>{"use strict";function ir(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=ir(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=ir(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=ir(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=ir(r,n,s,i);o===void 0?delete n[s]:o!==i&&(n[s]=o)}return r.call(e,t,n)}bl.applyReviver=ir});var Ie=T(vl=>{"use strict";var bm=_();function wl(r,e,t){if(Array.isArray(r))return r.map((n,s)=>wl(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!bm.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}vl.toJS=wl});var kn=T(xl=>{"use strict";var wm=Bi(),Sl=_(),vm=Ie(),ji=class{constructor(e){Object.defineProperty(this,Sl.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(!Sl.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=vm.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?wm.applyReviver(i,{"":a},"",a):a}};xl.NodeBase=ji});var or=T(kl=>{"use strict";var Sm=xn(),xm=rr(),kt=_(),km=kn(),Em=Ie(),Fi=class extends km.NodeBase{constructor(e){super(kt.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=[],xm.visit(e,{Node:(i,o)=>{(kt.isAlias(o)||kt.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||(Em.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=En(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(Sm.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 En(r,e,t){if(kt.isAlias(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(kt.isCollection(e)){let n=0;for(let s of e.items){let i=En(r,s,t);i>n&&(n=i)}return n}else if(kt.isPair(e)){let n=En(r,e.key,t),s=En(r,e.value,t);return Math.max(n,s)}return 1}kl.Alias=Fi});var U=T(qi=>{"use strict";var Am=_(),Tm=kn(),Pm=Ie(),Om=r=>!r||typeof r!="function"&&typeof r!="object",Le=class extends Tm.NodeBase{constructor(e){super(Am.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:Pm.toJS(this.value,e,t)}toString(){return String(this.value)}};Le.BLOCK_FOLDED="BLOCK_FOLDED";Le.BLOCK_LITERAL="BLOCK_LITERAL";Le.PLAIN="PLAIN";Le.QUOTE_DOUBLE="QUOTE_DOUBLE";Le.QUOTE_SINGLE="QUOTE_SINGLE";qi.Scalar=Le;qi.isScalarValue=Om});var ar=T(Al=>{"use strict";var Cm=or(),Xe=_(),El=U(),Rm="tag:yaml.org,2002:";function Nm(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 _m(r,e,t){if(Xe.isDocument(r)&&(r=r.contents),Xe.isNode(r))return r;if(Xe.isPair(r)){let u=t.schema[Xe.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 Cm.Alias(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=Rm+e.slice(2));let l=Nm(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new El.Scalar(r);return c&&(c.node=u),u}l=r instanceof Map?o[Xe.MAP]:Symbol.iterator in Object(r)?o[Xe.SEQ]:o[Xe.MAP]}i&&(i(l),delete t.onTagObj);let d=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new El.Scalar(r);return e?d.tag=e:l.default||(d.tag=l.tag),c&&(c.node=d),d}Al.createNode=_m});var Tn=T(An=>{"use strict";var Im=ar(),ve=_(),Lm=kn();function Ui(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 Im.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 Tl=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,Ji=class extends Lm.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=>ve.isNode(n)||ve.isPair(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Tl(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(ve.isCollection(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,Ui(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(ve.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&&ve.isScalar(i)?i.value:i:ve.isCollection(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ve.isPair(t))return!1;let n=t.value;return n==null||e&&ve.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 ve.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(ve.isCollection(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,Ui(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};An.Collection=Ji;An.collectionFromPath=Ui;An.isEmptyPath=Tl});var cr=T(Pn=>{"use strict";var $m=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Ki(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var Mm=(r,e,t)=>r.endsWith(`
|
|
14
|
+
`)?Ki(t,e):t.includes(`
|
|
15
15
|
`)?`
|
|
16
|
-
`+
|
|
17
|
-
`)t===
|
|
16
|
+
`+Ki(t,e):(r.endsWith(" ")?"":" ")+t;Pn.indentComment=Ki;Pn.lineComment=Mm;Pn.stringifyComment=$m});var Ol=T(lr=>{"use strict";var Dm="flow",Wi="block",On="quoted";function Bm(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=[],d={},u=s-e.length;typeof n=="number"&&(n>s-Math.max(2,i)?l.push(0):u=s-n);let f,p,m=!1,h=-1,y=-1,x=-1;t===Wi&&(h=Pl(r,h,e.length),h!==-1&&(u=h+c));for(let g;g=r[h+=1];){if(t===On&&g==="\\"){switch(y=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}x=h}if(g===`
|
|
17
|
+
`)t===Wi&&(h=Pl(r,h,e.length)),u=h+e.length+c,f=void 0;else{if(g===" "&&p&&p!==" "&&p!==`
|
|
18
18
|
`&&p!==" "){let b=r[h+1];b&&b!==" "&&b!==`
|
|
19
|
-
`&&b!==" "&&(f=h)}if(h>=u)if(f)l.push(f),u=f+c,f=void 0;else if(t===
|
|
20
|
-
${e}${r.slice(0,v)}`:(t===
|
|
21
|
-
${e}${r.slice(b+1,v)}`)}return
|
|
22
|
-
`);n=e,s=e+1,i=r[s]}return n}lr.FOLD_BLOCK=
|
|
23
|
-
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function ur(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(
|
|
19
|
+
`&&b!==" "&&(f=h)}if(h>=u)if(f)l.push(f),u=f+c,f=void 0;else if(t===On){for(;p===" "||p===" ";)p=g,g=r[h+=1],m=!0;let b=h>x+1?h-2:y-1;if(d[b])return r;l.push(b),d[b]=!0,u=b+c,f=void 0}else m=!0}p=g}if(m&&a&&a(),l.length===0)return r;o&&o();let k=r.slice(0,l[0]);for(let g=0;g<l.length;++g){let b=l[g],v=l[g+1]||r.length;b===0?k=`
|
|
20
|
+
${e}${r.slice(0,v)}`:(t===On&&d[b]&&(k+=`${r[b]}\\`),k+=`
|
|
21
|
+
${e}${r.slice(b+1,v)}`)}return k}function Pl(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}lr.FOLD_BLOCK=Wi;lr.FOLD_FLOW=Dm;lr.FOLD_QUOTED=On;lr.foldFlowLines=Bm});var fr=T(Cl=>{"use strict";var fe=U(),$e=Ol(),Rn=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),Nn=r=>/^(%|---|\.\.\.)/m.test(r);function jm(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 ur(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Nn(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 d=t.substr(c+2,4);switch(d){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:d.substr(0,2)==="00"?o+="\\x"+d.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:$e.foldFlowLines(o,i,$e.FOLD_QUOTED,
|
|
27
|
-
`)||/[ \t]\n|\n[ \t]/.test(r))return ur(r,e);let t=e.indent||(
|
|
28
|
-
${t}`)+"'";return e.implicitKey?n:$e.foldFlowLines(n,t,$e.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:$e.foldFlowLines(o,i,$e.FOLD_QUOTED,Rn(e,!1))}function Hi(r,e){if(e.options.singleQuote===!1||e.implicitKey&&r.includes(`
|
|
27
|
+
`)||/[ \t]\n|\n[ \t]/.test(r))return ur(r,e);let t=e.indent||(Nn(r)?" ":""),n="'"+r.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
28
|
+
${t}`)+"'";return e.implicitKey?n:$e.foldFlowLines(n,t,$e.FOLD_FLOW,Rn(e,!1))}function Et(r,e){let{singleQuote:t}=e.options,n;if(t===!1)n=ur;else{let s=r.includes('"'),i=r.includes("'");s&&!i?n=Hi:i&&!s?n=ur:n=t?Hi:ur}return n(r,e)}var Vi;try{Vi=new RegExp(`(^|(?<!
|
|
29
29
|
))
|
|
30
30
|
+(?!
|
|
31
|
-
|$)`,"g")}catch{Vi=/\n+(?!\n|$)/g}function
|
|
31
|
+
|$)`,"g")}catch{Vi=/\n+(?!\n|$)/g}function Cn({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 Et(t,n);let l=n.indent||(n.forceBlockIndent||Nn(t)?" ":""),d=o==="literal"?!0:o==="folded"||e===fe.Scalar.BLOCK_FOLDED?!1:e===fe.Scalar.BLOCK_LITERAL?!0:!jm(t,c,l.length);if(!t)return d?`|
|
|
32
32
|
`:`>
|
|
33
33
|
`;let u,f;for(f=t.length;f>0;--f){let v=t[f-1];if(v!==`
|
|
34
34
|
`&&v!==" "&&v!==" ")break}let p=t.substring(f),m=p.indexOf(`
|
|
35
35
|
`);m===-1?u="-":t===p||m!==p.length-1?(u="+",i&&i()):u="",p&&(t=t.slice(0,-p.length),p[p.length-1]===`
|
|
36
36
|
`&&(p=p.slice(0,-1)),p=p.replace(Vi,`$&${l}`));let h=!1,y,x=-1;for(y=0;y<t.length;++y){let v=t[y];if(v===" ")h=!0;else if(v===`
|
|
37
|
-
`)x=y;else break}let
|
|
38
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),S=!1,P=
|
|
39
|
-
${l}${
|
|
40
|
-
${l}${
|
|
37
|
+
`)x=y;else break}let k=t.substring(0,x<y?x+1:y);k&&(t=t.substring(k.length),k=k.replace(/\n+/g,`$&${l}`));let b=(h?l?"2":"1":"")+u;if(r&&(b+=" "+a(r.replace(/ ?[\r\n]+/g," ")),s&&s()),!d){let v=t.replace(/\n+/g,`
|
|
38
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),S=!1,P=Rn(n,!0);o!=="folded"&&e!==fe.Scalar.BLOCK_FOLDED&&(P.onOverflow=()=>{S=!0});let E=$e.foldFlowLines(`${k}${v}${p}`,l,$e.FOLD_BLOCK,P);if(!S)return`>${b}
|
|
39
|
+
${l}${E}`}return t=t.replace(/\n+/g,`$&${l}`),`|${b}
|
|
40
|
+
${l}${k}${t}${p}`}function Fm(r,e,t,n){let{type:s,value:i}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:d}=e;if(a&&i.includes(`
|
|
41
41
|
`)||d&&/[[\]{},]/.test(i))return Et(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||d||!i.includes(`
|
|
42
|
-
`)?Et(i,e):
|
|
43
|
-
`))return
|
|
44
|
-
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:p,tags:m}=e.doc.schema;if(m.some(f)||p?.some(f))return Et(i,e)}return a?u:$e.foldFlowLines(u,c,$e.FOLD_FLOW,
|
|
45
|
-
${e.indent}${a}`:a}
|
|
46
|
-
${a}:`):(y=`${y}:`,f&&(y+=pr.lineComment(y,t.indent,l(f))));let x,
|
|
47
|
-
`:"",
|
|
42
|
+
`)?Et(i,e):Cn(r,e,t,n);if(!a&&!d&&s!==fe.Scalar.PLAIN&&i.includes(`
|
|
43
|
+
`))return Cn(r,e,t,n);if(Nn(i)){if(c==="")return e.forceBlockIndent=!0,Cn(r,e,t,n);if(a&&c===l)return Et(i,e)}let u=i.replace(/\n+/g,`$&
|
|
44
|
+
${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:p,tags:m}=e.doc.schema;if(m.some(f)||p?.some(f))return Et(i,e)}return a?u:$e.foldFlowLines(u,c,$e.FOLD_FLOW,Rn(e,!1))}function qm(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!==fe.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=fe.Scalar.QUOTE_DOUBLE);let c=d=>{switch(d){case fe.Scalar.BLOCK_FOLDED:case fe.Scalar.BLOCK_LITERAL:return s||i?Et(o.value,e):Cn(o,e,t,n);case fe.Scalar.QUOTE_DOUBLE:return ur(o.value,e);case fe.Scalar.QUOTE_SINGLE:return Hi(o.value,e);case fe.Scalar.PLAIN:return Fm(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:d,defaultStringType:u}=e.options,f=s&&d||u;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Cl.stringifyString=qm});var dr=T(Yi=>{"use strict";var Um=xn(),Me=_(),Jm=cr(),Km=fr();function Wm(r,e){let t=Object.assign({blockQuote:!0,commentString:Jm.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 Hm(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(Me.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 Vm(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],i=(Me.isScalar(r)||Me.isCollection(r))&&r.anchor;i&&Um.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 Ym(r,e,t,n){if(Me.isPair(r))return r.toString(e,t,n);if(Me.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=Me.isNode(r)?r:e.doc.createNode(r,{onTagObj:c=>s=c});s??(s=Hm(e.doc.schema.tags,i));let o=Vm(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):Me.isScalar(i)?Km.stringifyString(i,e,t,n):i.toString(e,t,n);return o?Me.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
45
|
+
${e.indent}${a}`:a}Yi.createStringifyContext=Wm;Yi.stringify=Ym});var Il=T(_l=>{"use strict";var Pe=_(),Rl=U(),Nl=dr(),pr=cr();function Gm({key:r,value:e},t,n,s){let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:d,simpleKeys:u}}=t,f=Pe.isNode(r)&&r.comment||null;if(u){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Pe.isCollection(r)||!Pe.isNode(r)&&typeof r=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let p=!u&&(!r||f&&e==null&&!t.inFlow||Pe.isCollection(r)||(Pe.isScalar(r)?r.type===Rl.Scalar.BLOCK_FOLDED||r.type===Rl.Scalar.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!i),indent:a+c});let m=!1,h=!1,y=Nl.stringify(r,t,()=>m=!0,()=>h=!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 m&&n&&n(),y===""?"?":p?`? ${y}`:y}else if(i&&!u||e==null&&p)return y=`? ${y}`,f&&!m?y+=pr.lineComment(y,t.indent,l(f)):h&&s&&s(),y;m&&(f=null),p?(f&&(y+=pr.lineComment(y,t.indent,l(f))),y=`? ${y}
|
|
46
|
+
${a}:`):(y=`${y}:`,f&&(y+=pr.lineComment(y,t.indent,l(f))));let x,k,g;Pe.isNode(e)?(x=!!e.spaceBefore,k=e.commentBefore,g=e.comment):(x=!1,k=null,g=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&Pe.isScalar(e)&&(t.indentAtStart=y.length+1),h=!1,!d&&c.length>=2&&!t.inFlow&&!p&&Pe.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let b=!1,v=Nl.stringify(e,t,()=>b=!0,()=>h=!0),S=" ";if(f||x||k){if(S=x?`
|
|
47
|
+
`:"",k){let P=l(k);S+=`
|
|
48
48
|
${pr.indentComment(P,t.indent)}`}v===""&&!t.inFlow?S===`
|
|
49
49
|
`&&g&&(S=`
|
|
50
50
|
|
|
51
51
|
`):S+=`
|
|
52
|
-
${t.indent}`}else if(!p&&Pe.isCollection(e)){let P=v[0],
|
|
53
|
-
`),L=
|
|
52
|
+
${t.indent}`}else if(!p&&Pe.isCollection(e)){let P=v[0],E=v.indexOf(`
|
|
53
|
+
`),L=E!==-1,Q=t.inFlow??e.flow??e.items.length===0;if(L||!Q){let V=!1;if(L&&(P==="&"||P==="!")){let B=v.indexOf(" ");P==="&"&&B!==-1&&B<E&&v[B+1]==="!"&&(B=v.indexOf(" ",B+1)),(B===-1||E<B)&&(V=!0)}V||(S=`
|
|
54
54
|
${t.indent}`)}}else(v===""||v[0]===`
|
|
55
|
-
`)&&(S="");return y+=S+v,t.inFlow?b&&n&&n():g&&!b?y+=pr.lineComment(y,t.indent,l(g)):h&&s&&s(),y}
|
|
55
|
+
`)&&(S="");return y+=S+v,t.inFlow?b&&n&&n():g&&!b?y+=pr.lineComment(y,t.indent,l(g)):h&&s&&s(),y}_l.stringifyPair=Gm});var zi=T(Gi=>{"use strict";var Ll=hn("process");function zm(r,...e){r==="debug"&&console.log(...e)}function Qm(r,e){(r==="debug"||r==="warn")&&(typeof Ll.emitWarning=="function"?Ll.emitWarning(e):console.warn(e))}Gi.debug=zm;Gi.warn=Qm});var $n=T(Ln=>{"use strict";var hr=_(),$l=U(),_n="<<",In={identify:r=>r===_n||typeof r=="symbol"&&r.description===_n,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new $l.Scalar(Symbol(_n)),{addToJSMap:Ml}),stringify:()=>_n},Xm=(r,e)=>(In.identify(e)||hr.isScalar(e)&&(!e.type||e.type===$l.Scalar.PLAIN)&&In.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===In.tag&&t.default);function Ml(r,e,t){if(t=r&&hr.isAlias(t)?t.resolve(r.doc):t,hr.isSeq(t))for(let n of t.items)Qi(r,e,n);else if(Array.isArray(t))for(let n of t)Qi(r,e,n);else Qi(r,e,t)}function Qi(r,e,t){let n=r&&hr.isAlias(t)?t.resolve(r.doc):t;if(!hr.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}Ln.addMergeToJSMap=Ml;Ln.isMergeKey=Xm;Ln.merge=In});var Zi=T(jl=>{"use strict";var Zm=zi(),Dl=$n(),eg=dr(),Bl=_(),Xi=Ie();function tg(r,e,{key:t,value:n}){if(Bl.isNode(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(Dl.isMergeKey(r,t))Dl.addMergeToJSMap(r,e,n);else{let s=Xi.toJS(t,"",r);if(e instanceof Map)e.set(s,Xi.toJS(n,s,r));else if(e instanceof Set)e.add(s);else{let i=rg(t,s,r),o=Xi.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 rg(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(Bl.isNode(r)&&t?.doc){let n=eg.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)+'..."'),Zm.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)}jl.addPairToJSMap=tg});var De=T(eo=>{"use strict";var Fl=ar(),ng=Il(),sg=Zi(),Mn=_();function ig(r,e,t){let n=Fl.createNode(r,void 0,t),s=Fl.createNode(e,void 0,t);return new Dn(n,s)}var Dn=class r{constructor(e,t=null){Object.defineProperty(this,Mn.NODE_TYPE,{value:Mn.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Mn.isNode(t)&&(t=t.clone(e)),Mn.isNode(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return sg.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?ng.stringifyPair(this,e,t,n):JSON.stringify(this)}};eo.Pair=Dn;eo.createPair=ig});var to=T(Ul=>{"use strict";var Ze=_(),ql=dr(),Bn=cr();function og(r,e,t){return(e.inFlow??r.flow?cg:ag)(r,e,t)}function ag({comment:r,items:e},t,{blockItemPrefix:n,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,d=Object.assign({},t,{indent:i,type:null}),u=!1,f=[];for(let m=0;m<e.length;++m){let h=e[m],y=null;if(Ze.isNode(h))!u&&h.spaceBefore&&f.push(""),jn(t,f,h.commentBefore,u),h.comment&&(y=h.comment);else if(Ze.isPair(h)){let k=Ze.isNode(h.key)?h.key:null;k&&(!u&&k.spaceBefore&&f.push(""),jn(t,f,k.commentBefore,u))}u=!1;let x=ql.stringify(h,d,()=>y=null,()=>u=!0);y&&(x+=Bn.lineComment(x,i,l(y))),u&&y&&(u=!1),f.push(n+x)}let p;if(f.length===0)p=s.start+s.end;else{p=f[0];for(let m=1;m<f.length;++m){let h=f[m];p+=h?`
|
|
56
56
|
${c}${h}`:`
|
|
57
57
|
`}}return r?(p+=`
|
|
58
|
-
`+
|
|
58
|
+
`+Bn.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function cg({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,d=0,u=[];for(let m=0;m<r.length;++m){let h=r[m],y=null;if(Ze.isNode(h))h.spaceBefore&&u.push(""),jn(e,u,h.commentBefore,!1),h.comment&&(y=h.comment);else if(Ze.isPair(h)){let k=Ze.isNode(h.key)?h.key:null;k&&(k.spaceBefore&&u.push(""),jn(e,u,k.commentBefore,!1),k.comment&&(l=!0));let g=Ze.isNode(h.value)?h.value:null;g?(g.comment&&(y=g.comment),g.commentBefore&&(l=!0)):h.value==null&&k?.comment&&(y=k.comment)}y&&(l=!0);let x=ql.stringify(h,c,()=>y=null);m<r.length-1&&(x+=","),y&&(x+=Bn.lineComment(x,n,a(y))),!l&&(u.length>d||x.includes(`
|
|
59
59
|
`))&&(l=!0),u.push(x),d=u.length}let{start:f,end:p}=t;if(u.length===0)return f+p;if(!l){let m=u.reduce((h,y)=>h+y.length+2,2);l=e.options.lineWidth>0&&m>e.options.lineWidth}if(l){let m=f;for(let h of u)m+=h?`
|
|
60
60
|
${i}${s}${h}`:`
|
|
61
61
|
`;return`${m}
|
|
62
|
-
${s}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function
|
|
63
|
-
`:" ")}return
|
|
62
|
+
${s}${p}`}else return`${f}${o}${u.join(" ")}${o}${p}`}function jn({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=Bn.indentComment(e(n),r);t.push(i.trimStart())}}Ul.stringifyCollection=og});var je=T(no=>{"use strict";var lg=to(),ug=Zi(),fg=Tn(),Be=_(),Fn=De(),dg=U();function mr(r,e){let t=Be.isScalar(e)?e.value:e;for(let n of r)if(Be.isPair(n)&&(n.key===e||n.key===t||Be.isScalar(n.key)&&n.key.value===t))return n}var ro=class extends fg.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Be.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(Fn.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;Be.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Fn.Pair(e,e?.value):n=new Fn.Pair(e.key,e.value);let s=mr(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);Be.isScalar(s.value)&&dg.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=mr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=mr(this.items,e)?.value;return(!t&&Be.isScalar(s)?s.value:s)??void 0}has(e){return!!mr(this.items,e)}set(e,t){this.add(new Fn.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)ug.addPairToJSMap(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!Be.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})),lg.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};no.YAMLMap=ro;no.findPair=mr});var At=T(Kl=>{"use strict";var pg=_(),Jl=je(),hg={collection:"map",default:!0,nodeClass:Jl.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return pg.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Jl.YAMLMap.from(r,e,t)};Kl.map=hg});var Fe=T(Wl=>{"use strict";var mg=ar(),gg=to(),yg=Tn(),Un=_(),bg=U(),wg=Ie(),so=class extends yg.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Un.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=qn(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=qn(e);if(typeof n!="number")return;let s=this.items[n];return!t&&Un.isScalar(s)?s.value:s}has(e){let t=qn(e);return typeof t=="number"&&t<this.items.length}set(e,t){let n=qn(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[n];Un.isScalar(s)&&bg.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(wg.toJS(i,String(s++),t));return n}toString(e,t,n){return e?gg.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(mg.createNode(a,void 0,n))}}return i}};function qn(r){let e=Un.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Wl.YAMLSeq=so});var Tt=T(Vl=>{"use strict";var vg=_(),Hl=Fe(),Sg={collection:"seq",default:!0,nodeClass:Hl.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return vg.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Hl.YAMLSeq.from(r,e,t)};Vl.seq=Sg});var gr=T(Yl=>{"use strict";var xg=fr(),kg={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),xg.stringifyString(r,e,t,n)}};Yl.string=kg});var Jn=T(Ql=>{"use strict";var Gl=U(),zl={identify:r=>r==null,createNode:()=>new Gl.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Gl.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&zl.test.test(r)?r:e.options.nullStr};Ql.nullTag=zl});var io=T(Zl=>{"use strict";var Eg=U(),Xl={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new Eg.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Xl.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};Zl.boolTag=Xl});var Pt=T(eu=>{"use strict";function Ag({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}eu.stringifyNumber=Ag});var ao=T(Kn=>{"use strict";var Tg=U(),oo=Pt(),Pg={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:oo.stringifyNumber},Og={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():oo.stringifyNumber(r)}},Cg={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 Tg.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:oo.stringifyNumber};Kn.float=Cg;Kn.floatExp=Og;Kn.floatNaN=Pg});var lo=T(Hn=>{"use strict";var tu=Pt(),Wn=r=>typeof r=="bigint"||Number.isInteger(r),co=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function ru(r,e,t){let{value:n}=r;return Wn(n)&&n>=0?t+n.toString(e):tu.stringifyNumber(r)}var Rg={identify:r=>Wn(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>co(r,2,8,t),stringify:r=>ru(r,8,"0o")},Ng={identify:Wn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>co(r,0,10,t),stringify:tu.stringifyNumber},_g={identify:r=>Wn(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>co(r,2,16,t),stringify:r=>ru(r,16,"0x")};Hn.int=Ng;Hn.intHex=_g;Hn.intOct=Rg});var su=T(nu=>{"use strict";var Ig=At(),Lg=Jn(),$g=Tt(),Mg=gr(),Dg=io(),uo=ao(),fo=lo(),Bg=[Ig.map,$g.seq,Mg.string,Lg.nullTag,Dg.boolTag,fo.intOct,fo.int,fo.intHex,uo.floatNaN,uo.floatExp,uo.float];nu.schema=Bg});var au=T(ou=>{"use strict";var jg=U(),Fg=At(),qg=Tt();function iu(r){return typeof r=="bigint"||Number.isInteger(r)}var Vn=({value:r})=>JSON.stringify(r),Ug=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Vn},{identify:r=>r==null,createNode:()=>new jg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Vn},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Vn},{identify:iu,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})=>iu(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:Vn}],Jg={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Kg=[Fg.map,qg.seq].concat(Ug,Jg);ou.schema=Kg});var ho=T(cu=>{"use strict";var yr=hn("buffer"),po=U(),Wg=fr(),Hg={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof yr.Buffer=="function")return yr.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 yr.Buffer=="function")a=o instanceof yr.Buffer?o.toString("base64"):yr.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=po.Scalar.BLOCK_LITERAL),e!==po.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(a.length/c),d=new Array(l);for(let u=0,f=0;u<l;++u,f+=c)d[u]=a.substr(f,c);a=d.join(e===po.Scalar.BLOCK_LITERAL?`
|
|
63
|
+
`:" ")}return Wg.stringifyString({comment:r,type:e,value:a},n,s,i)}};cu.binary=Hg});var zn=T(Gn=>{"use strict";var Yn=_(),mo=De(),Vg=U(),Yg=Fe();function lu(r,e){if(Yn.isSeq(r))for(let t=0;t<r.items.length;++t){let n=r.items[t];if(!Yn.isPair(n)){if(Yn.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let s=n.items[0]||new mo.Pair(new Vg.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]=Hn.isPair(n)?n:new ho.Pair(n)}}else e("Expected a sequence for this tag");return r}function cu(r,e,t){let{replacer:n}=t,s=new Jg.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(ho.createPair(a,c,t))}return s}var Kg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:au,createNode:cu};Yn.createPairs=cu;Yn.pairs=Kg;Yn.resolvePairs=au});var yo=T(go=>{"use strict";var lu=_(),mo=Ie(),br=je(),Wg=Fe(),uu=Gn(),et=class r extends Wg.YAMLSeq{constructor(){super(),this.add=br.YAMLMap.prototype.add.bind(this),this.delete=br.YAMLMap.prototype.delete.bind(this),this.get=br.YAMLMap.prototype.get.bind(this),this.has=br.YAMLMap.prototype.has.bind(this),this.set=br.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(lu.isPair(s)?(i=mo.toJS(s.key,"",t),o=mo.toJS(s.value,i,t)):i=mo.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=uu.createPairs(e,t,n),i=new this;return i.items=s.items,i}};et.tag="tag:yaml.org,2002:omap";var Vg={collection:"seq",identify:r=>r instanceof Map,nodeClass:et,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=uu.resolvePairs(r,e),n=[];for(let{key:s}of t.items)lu.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new et,t)},createNode:(r,e,t)=>et.from(r,e,t)};go.YAMLOMap=et;go.omap=Vg});var mu=T(bo=>{"use strict";var fu=U();function du({value:r,source:e},t){return e&&(r?pu:hu).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var pu={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 fu.Scalar(!0),stringify:du},hu={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 fu.Scalar(!1),stringify:du};bo.falseTag=hu;bo.trueTag=pu});var gu=T(zn=>{"use strict";var Hg=U(),wo=Pt(),Yg={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:wo.stringifyNumber},Gg={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():wo.stringifyNumber(r)}},zg={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 Hg.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:wo.stringifyNumber};zn.float=zg;zn.floatExp=Gg;zn.floatNaN=Yg});var bu=T(vr=>{"use strict";var yu=Pt(),wr=r=>typeof r=="bigint"||Number.isInteger(r);function Qn(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(wr(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return yu.stringifyNumber(r)}var Qg={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Qn(r,2,2,t),stringify:r=>vo(r,2,"0b")},Xg={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Qn(r,1,8,t),stringify:r=>vo(r,8,"0")},Zg={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Qn(r,0,10,t),stringify:yu.stringifyNumber},ey={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Qn(r,2,16,t),stringify:r=>vo(r,16,"0x")};vr.int=Zg;vr.intBin=Qg;vr.intHex=ey;vr.intOct=Xg});var xo=T(So=>{"use strict";var es=_(),Xn=De(),Zn=je(),tt=class r extends Zn.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;es.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Xn.Pair(e.key,null):t=new Xn.Pair(e,null),Zn.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=Zn.findPair(this.items,e);return!t&&es.isPair(n)?es.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=Zn.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Xn.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(Xn.createPair(o,null,n));return i}};tt.tag="tag:yaml.org,2002:set";var ty={collection:"map",identify:r=>r instanceof Set,nodeClass:tt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>tt.from(r,e,t),resolve(r,e){if(es.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new tt,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};So.YAMLSet=tt;So.set=ty});var Eo=T(ts=>{"use strict";var ry=Pt();function ko(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 wu(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return ry.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 ny={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})=>ko(r,t),stringify:wu},sy={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=>ko(r,!1),stringify:wu},vu={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(vu.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),d=e[8];if(d&&d!=="Z"){let u=ko(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ts.floatTime=sy;ts.intTime=ny;ts.timestamp=vu});var ku=T(xu=>{"use strict";var iy=At(),oy=Un(),ay=Tt(),cy=gr(),ly=po(),Su=mu(),Ao=gu(),rs=bu(),uy=Ln(),fy=yo(),dy=Gn(),py=xo(),To=Eo(),hy=[iy.map,ay.seq,cy.string,oy.nullTag,Su.trueTag,Su.falseTag,rs.intBin,rs.intOct,rs.int,rs.intHex,Ao.floatNaN,Ao.floatExp,Ao.float,ly.binary,uy.merge,fy.omap,dy.pairs,py.set,To.intTime,To.floatTime,To.timestamp];xu.schema=hy});var Iu=T(Co=>{"use strict";var Pu=At(),my=Un(),Ou=Tt(),gy=gr(),yy=so(),Po=oo(),Oo=co(),by=ru(),wy=iu(),Cu=po(),Sr=Ln(),Ru=yo(),Nu=Gn(),Eu=ku(),_u=xo(),ns=Eo(),Au=new Map([["core",by.schema],["failsafe",[Pu.map,Ou.seq,gy.string]],["json",wy.schema],["yaml11",Eu.schema],["yaml-1.1",Eu.schema]]),Tu={binary:Cu.binary,bool:yy.boolTag,float:Po.float,floatExp:Po.floatExp,floatNaN:Po.floatNaN,floatTime:ns.floatTime,int:Oo.int,intHex:Oo.intHex,intOct:Oo.intOct,intTime:ns.intTime,map:Pu.map,merge:Sr.merge,null:my.nullTag,omap:Ru.omap,pairs:Nu.pairs,seq:Ou.seq,set:_u.set,timestamp:ns.timestamp},vy={"tag:yaml.org,2002:binary":Cu.binary,"tag:yaml.org,2002:merge":Sr.merge,"tag:yaml.org,2002:omap":Ru.omap,"tag:yaml.org,2002:pairs":Nu.pairs,"tag:yaml.org,2002:set":_u.set,"tag:yaml.org,2002:timestamp":ns.timestamp};function Sy(r,e,t){let n=Au.get(e);if(n&&!r)return t&&!n.includes(Sr.merge)?n.concat(Sr.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(Au.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(Sr.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?Tu[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Tu).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}Co.coreKnownTags=vy;Co.getTags=Sy});var _o=T(Lu=>{"use strict";var Ro=_(),xy=At(),ky=Tt(),Ey=gr(),ss=Iu(),Ay=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,No=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ss.getTags(e,"compat"):e?ss.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?ss.coreKnownTags:{},this.tags=ss.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Ro.MAP,{value:xy.map}),Object.defineProperty(this,Ro.SCALAR,{value:Ey.string}),Object.defineProperty(this,Ro.SEQ,{value:ky.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Ay:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Lu.Schema=No});var Mu=T($u=>{"use strict";var Ty=_(),Io=dr(),xr=cr();function Py(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=Io.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(xr.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(Ty.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(xr.indentComment(d,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Io.stringify(r.contents,s,()=>a=null,c);a&&(l+=xr.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Io.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
65
|
+
${i.comment}`:n.comment}n=s}r.items[t]=Yn.isPair(n)?n:new mo.Pair(n)}}else e("Expected a sequence for this tag");return r}function uu(r,e,t){let{replacer:n}=t,s=new Yg.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(mo.createPair(a,c,t))}return s}var Gg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:lu,createNode:uu};Gn.createPairs=uu;Gn.pairs=Gg;Gn.resolvePairs=lu});var bo=T(yo=>{"use strict";var fu=_(),go=Ie(),br=je(),zg=Fe(),du=zn(),et=class r extends zg.YAMLSeq{constructor(){super(),this.add=br.YAMLMap.prototype.add.bind(this),this.delete=br.YAMLMap.prototype.delete.bind(this),this.get=br.YAMLMap.prototype.get.bind(this),this.has=br.YAMLMap.prototype.has.bind(this),this.set=br.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(fu.isPair(s)?(i=go.toJS(s.key,"",t),o=go.toJS(s.value,i,t)):i=go.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=du.createPairs(e,t,n),i=new this;return i.items=s.items,i}};et.tag="tag:yaml.org,2002:omap";var Qg={collection:"seq",identify:r=>r instanceof Map,nodeClass:et,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=du.resolvePairs(r,e),n=[];for(let{key:s}of t.items)fu.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new et,t)},createNode:(r,e,t)=>et.from(r,e,t)};yo.YAMLOMap=et;yo.omap=Qg});var yu=T(wo=>{"use strict";var pu=U();function hu({value:r,source:e},t){return e&&(r?mu:gu).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var mu={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 pu.Scalar(!0),stringify:hu},gu={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new pu.Scalar(!1),stringify:hu};wo.falseTag=gu;wo.trueTag=mu});var bu=T(Qn=>{"use strict";var Xg=U(),vo=Pt(),Zg={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:vo.stringifyNumber},ey={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():vo.stringifyNumber(r)}},ty={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 Xg.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:vo.stringifyNumber};Qn.float=ty;Qn.floatExp=ey;Qn.floatNaN=Zg});var vu=T(vr=>{"use strict";var wu=Pt(),wr=r=>typeof r=="bigint"||Number.isInteger(r);function Xn(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 So(r,e,t){let{value:n}=r;if(wr(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return wu.stringifyNumber(r)}var ry={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Xn(r,2,2,t),stringify:r=>So(r,2,"0b")},ny={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Xn(r,1,8,t),stringify:r=>So(r,8,"0")},sy={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Xn(r,0,10,t),stringify:wu.stringifyNumber},iy={identify:wr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Xn(r,2,16,t),stringify:r=>So(r,16,"0x")};vr.int=sy;vr.intBin=ry;vr.intHex=iy;vr.intOct=ny});var ko=T(xo=>{"use strict";var ts=_(),Zn=De(),es=je(),tt=class r extends es.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;ts.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Zn.Pair(e.key,null):t=new Zn.Pair(e,null),es.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=es.findPair(this.items,e);return!t&&ts.isPair(n)?ts.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=es.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Zn.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(Zn.createPair(o,null,n));return i}};tt.tag="tag:yaml.org,2002:set";var oy={collection:"map",identify:r=>r instanceof Set,nodeClass:tt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>tt.from(r,e,t),resolve(r,e){if(ts.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new tt,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};xo.YAMLSet=tt;xo.set=oy});var Ao=T(rs=>{"use strict";var ay=Pt();function Eo(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 Su(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return ay.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 cy={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})=>Eo(r,t),stringify:Su},ly={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=>Eo(r,!1),stringify:Su},xu={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(xu.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),d=e[8];if(d&&d!=="Z"){let u=Eo(d,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};rs.floatTime=ly;rs.intTime=cy;rs.timestamp=xu});var Au=T(Eu=>{"use strict";var uy=At(),fy=Jn(),dy=Tt(),py=gr(),hy=ho(),ku=yu(),To=bu(),ns=vu(),my=$n(),gy=bo(),yy=zn(),by=ko(),Po=Ao(),wy=[uy.map,dy.seq,py.string,fy.nullTag,ku.trueTag,ku.falseTag,ns.intBin,ns.intOct,ns.int,ns.intHex,To.floatNaN,To.floatExp,To.float,hy.binary,my.merge,gy.omap,yy.pairs,by.set,Po.intTime,Po.floatTime,Po.timestamp];Eu.schema=wy});var $u=T(Ro=>{"use strict";var Cu=At(),vy=Jn(),Ru=Tt(),Sy=gr(),xy=io(),Oo=ao(),Co=lo(),ky=su(),Ey=au(),Nu=ho(),Sr=$n(),_u=bo(),Iu=zn(),Tu=Au(),Lu=ko(),ss=Ao(),Pu=new Map([["core",ky.schema],["failsafe",[Cu.map,Ru.seq,Sy.string]],["json",Ey.schema],["yaml11",Tu.schema],["yaml-1.1",Tu.schema]]),Ou={binary:Nu.binary,bool:xy.boolTag,float:Oo.float,floatExp:Oo.floatExp,floatNaN:Oo.floatNaN,floatTime:ss.floatTime,int:Co.int,intHex:Co.intHex,intOct:Co.intOct,intTime:ss.intTime,map:Cu.map,merge:Sr.merge,null:vy.nullTag,omap:_u.omap,pairs:Iu.pairs,seq:Ru.seq,set:Lu.set,timestamp:ss.timestamp},Ay={"tag:yaml.org,2002:binary":Nu.binary,"tag:yaml.org,2002:merge":Sr.merge,"tag:yaml.org,2002:omap":_u.omap,"tag:yaml.org,2002:pairs":Iu.pairs,"tag:yaml.org,2002:set":Lu.set,"tag:yaml.org,2002:timestamp":ss.timestamp};function Ty(r,e,t){let n=Pu.get(e);if(n&&!r)return t&&!n.includes(Sr.merge)?n.concat(Sr.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(Pu.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(Sr.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?Ou[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Ou).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}Ro.coreKnownTags=Ay;Ro.getTags=Ty});var Io=T(Mu=>{"use strict";var No=_(),Py=At(),Oy=Tt(),Cy=gr(),is=$u(),Ry=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,_o=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?is.getTags(e,"compat"):e?is.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?is.coreKnownTags:{},this.tags=is.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,No.MAP,{value:Py.map}),Object.defineProperty(this,No.SCALAR,{value:Cy.string}),Object.defineProperty(this,No.SEQ,{value:Oy.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Ry:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Mu.Schema=_o});var Bu=T(Du=>{"use strict";var Ny=_(),Lo=dr(),xr=cr();function _y(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=Lo.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(xr.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(Ny.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(xr.indentComment(d,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Lo.stringify(r.contents,s,()=>a=null,c);a&&(l+=xr.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Lo.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
66
66
|
`)?(t.push("..."),t.push(xr.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(xr.indentComment(i(c),"")))}return t.join(`
|
|
67
67
|
`)+`
|
|
68
|
-
`}
|
|
68
|
+
`}Du.stringifyDocument=_y});var kr=T(ju=>{"use strict";var Iy=or(),Ot=Tn(),ae=_(),Ly=De(),$y=Ie(),My=Io(),Dy=Bu(),$o=xn(),By=Bi(),jy=ar(),Mo=Di(),Do=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ae.NODE_TYPE,{value:ae.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 Mo.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,{[ae.NODE_TYPE]:{value:ae.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=ae.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ct(this.contents)&&this.contents.add(e)}addIn(e,t){Ct(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=$o.anchorNames(this);e.anchor=!t||n.has(t)?$o.findNewAnchor(t||"a",n):t}return new Iy.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=k=>typeof k=="number"||k instanceof String||k instanceof Number,x=t.filter(y).map(String);x.length>0&&(t=t.concat(x)),s=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:d}=n??{},{onAnchor:u,setAnchors:f,sourceObjects:p}=$o.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},h=jy.createNode(e,d,m);return a&&ae.isCollection(h)&&(h.flow=!0),f(),h}createPair(e,t,n={}){let s=this.createNode(e,null,n),i=this.createNode(t,null,n);return new Ly.Pair(s,i)}delete(e){return Ct(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ot.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Ct(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return ae.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Ot.isEmptyPath(e)?!t&&ae.isScalar(this.contents)?this.contents.value:this.contents:ae.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return ae.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Ot.isEmptyPath(e)?this.contents!==void 0:ae.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ot.collectionFromPath(this.schema,[e],t):Ct(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ot.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=Ot.collectionFromPath(this.schema,Array.from(e),t):Ct(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 Mo.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 Mo.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 My.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=$y.toJS(this.contents,t??"",a);if(typeof i=="function")for(let{count:l,res:d}of a.anchors.values())i(d,l);return typeof o=="function"?By.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 Dy.stringifyDocument(this,e)}};function Ct(r){if(ae.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}ju.Document=Do});var Tr=T(Ar=>{"use strict";var Er=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},Bo=class extends Er{constructor(e,t,n){super("YAMLParseError",e,t,n)}},jo=class extends Er{constructor(e,t,n){super("YAMLWarning",e,t,n)}},Fy=(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
|
-
`}};Ar.YAMLError=Er;Ar.YAMLParseError=
|
|
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
|
-
`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||
|
|
76
|
-
`+g.comment:
|
|
77
|
-
`+S.comment:l.comment=S.comment),u=S.end;continue}!o&&t.options.strict&&
|
|
78
|
-
`+P:
|
|
79
|
-
`+L.comment:
|
|
80
|
-
`+y.comment:l.comment=y.comment),l.range=[n.offset,h,y.offset]}else l.range=[n.offset,h,h];return l}
|
|
73
|
+
`}};Ar.YAMLError=Er;Ar.YAMLParseError=Bo;Ar.YAMLWarning=jo;Ar.prettifyError=Fy});var Pr=T(Fu=>{"use strict";function qy(r,{flow:e,indicator:t,next:n,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,d=a,u="",f="",p=!1,m=!1,h=null,y=null,x=null,k=null,g=null,b=null,v=null;for(let E of r)switch(m&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&i(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&E.type!=="comment"&&E.type!=="newline"&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),E.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&E.source.includes(" ")&&(h=E),d=!0;break;case"comment":{d||i(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let L=E.source.substring(1)||" ";u?u+=f+L:u=L,f="",l=!1;break}case"newline":l?u?u+=E.source:(!b||t!=="seq-item-ind")&&(c=!0):f+=E.source,l=!0,p=!0,(y||x)&&(k=E),d=!0;break;case"anchor":y&&i(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&i(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=E,v??(v=E.offset),l=!1,d=!1,m=!0;break;case"tag":{x&&i(E,"MULTIPLE_TAGS","A node can have at most one tag"),x=E,v??(v=E.offset),l=!1,d=!1,m=!0;break}case t:(y||x)&&i(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),b&&i(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${e??"collection"}`),b=E,l=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){g&&i(E,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),g=E,l=!1,d=!1;break}default:i(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),l=!1,d=!1}let S=r[r.length-1],P=S?S.offset+S.source.length:s;return m&&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"),h&&(l&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:g,found:b,spaceBefore:c,comment:u,hasNewline:p,anchor:y,tag:x,newlineAfterProp:k,end:P,start:v??P}}Fu.resolveProps=qy});var os=T(qu=>{"use strict";function Fo(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(Fo(e.key)||Fo(e.value))return!0}return!1;default:return!0}}qu.containsNewline=Fo});var qo=T(Uu=>{"use strict";var Uy=os();function Jy(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&Uy.containsNewline(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Uu.flowIndentCheck=Jy});var Uo=T(Ku=>{"use strict";var Ju=_();function Ky(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(i,o)=>i===o||Ju.isScalar(i)&&Ju.isScalar(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}Ku.mapIncludes=Ky});var zu=T(Gu=>{"use strict";var Wu=De(),Wy=je(),Hu=Pr(),Hy=os(),Vu=qo(),Vy=Uo(),Yu="All mapping items must start at the same column";function Yy({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Wy.YAMLMap,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let d of n.items){let{start:u,key:f,sep:p,value:m}=d,h=Hu.resolveProps(u,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0}),y=!h.found;if(y){if(f&&(f.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&s(c,"BAD_INDENT",Yu)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(a.comment?a.comment+=`
|
|
75
|
+
`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||Hy.containsNewline(f))&&s(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&s(c,"BAD_INDENT",Yu);t.atKey=!0;let x=h.end,k=f?r(t,f,h,s):e(t,x,u,null,h,s);t.schema.compat&&Vu.flowIndentCheck(n.indent,f,s),t.atKey=!1,Vy.mapIncludes(t,a.items,k)&&s(x,"DUPLICATE_KEY","Map keys must be unique");let g=Hu.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:k.range[2],onError:s,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=g.end,g.found){y&&(m?.type==="block-map"&&!g.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&h.start<g.found.offset-1024&&s(k.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let b=m?r(t,m,g,s):e(t,c,p,null,g,s);t.schema.compat&&Vu.flowIndentCheck(n.indent,m,s),c=b.range[2];let v=new Wu.Pair(k,b);t.options.keepSourceTokens&&(v.srcToken=d),a.items.push(v)}else{y&&s(k.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),g.comment&&(k.comment?k.comment+=`
|
|
76
|
+
`+g.comment:k.comment=g.comment);let b=new Wu.Pair(k);t.options.keepSourceTokens&&(b.srcToken=d),a.items.push(b)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}Gu.resolveBlockMap=Yy});var Xu=T(Qu=>{"use strict";var Gy=Fe(),zy=Pr(),Qy=qo();function Xy({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Gy.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:d,value:u}of n.items){let f=zy.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.type==="block-seq"?s(f.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let p=u?r(t,u,f,s):e(t,f.end,d,null,f,s);t.schema.compat&&Qy.flowIndentCheck(n.indent,u,s),c=p.range[2],a.items.push(p)}return a.range=[n.offset,c,l??c],a}Qu.resolveBlockSeq=Xy});var Rt=T(Zu=>{"use strict";function Zy(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 d=c.substring(1)||" ";s?s+=o+d:s=d,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}}Zu.resolveEnd=Zy});var nf=T(rf=>{"use strict";var eb=_(),tb=De(),ef=je(),rb=Fe(),nb=Rt(),tf=Pr(),sb=os(),ib=Uo(),Jo="Block collections are not allowed within flow collections",Ko=r=>r&&(r.type==="block-map"||r.type==="block-seq");function ob({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?ef.YAMLMap:rb.YAMLSeq),l=new c(t.schema);l.flow=!0;let d=t.atRoot;d&&(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 x=n.items[y],{start:k,key:g,sep:b,value:v}=x,S=tf.resolveProps(k,{flow:a,indicator:"explicit-key-ind",next:g??b?.[0],offset:u,onError:s,parentIndent:n.indent,startOnNewline:!1});if(!S.found){if(!S.anchor&&!S.tag&&!b&&!v){y===0&&S.comma?s(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<n.items.length-1&&s(S.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),S.comment&&(l.comment?l.comment+=`
|
|
77
|
+
`+S.comment:l.comment=S.comment),u=S.end;continue}!o&&t.options.strict&&sb.containsNewline(g)&&s(g,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)S.comma&&s(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(S.comma||s(S.start,"MISSING_CHAR",`Missing , between ${a} items`),S.comment){let P="";e:for(let E of k)switch(E.type){case"comma":case"space":break;case"comment":P=E.source.substring(1);break e;default:break e}if(P){let E=l.items[l.items.length-1];eb.isPair(E)&&(E=E.value??E.key),E.comment?E.comment+=`
|
|
78
|
+
`+P:E.comment=P,S.comment=S.comment.substring(P.length+1)}}if(!o&&!b&&!S.found){let P=v?r(t,v,S,s):e(t,S.end,b,null,S,s);l.items.push(P),u=P.range[2],Ko(v)&&s(P.range,"BLOCK_IN_FLOW",Jo)}else{t.atKey=!0;let P=S.end,E=g?r(t,g,S,s):e(t,P,k,null,S,s);Ko(g)&&s(E.range,"BLOCK_IN_FLOW",Jo),t.atKey=!1;let L=tf.resolveProps(b??[],{flow:a,indicator:"map-value-ind",next:v,offset:E.range[2],onError:s,parentIndent:n.indent,startOnNewline:!1});if(L.found){if(!o&&!S.found&&t.options.strict){if(b)for(let B of b){if(B===L.found)break;if(B.type==="newline"){s(B,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}S.start<L.found.offset-1024&&s(L.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else v&&("source"in v&&v.source?.[0]===":"?s(v,"MISSING_CHAR",`Missing space after : in ${a}`):s(L.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let Q=v?r(t,v,L,s):L.found?e(t,L.end,b,null,L,s):null;Q?Ko(v)&&s(Q.range,"BLOCK_IN_FLOW",Jo):L.comment&&(E.comment?E.comment+=`
|
|
79
|
+
`+L.comment:E.comment=L.comment);let V=new tb.Pair(E,Q);if(t.options.keepSourceTokens&&(V.srcToken=x),o){let B=l;ib.mapIncludes(t,B.items,E)&&s(P,"DUPLICATE_KEY","Map keys must be unique"),B.items.push(V)}else{let B=new ef.YAMLMap(t.schema);B.flow=!0,B.items.push(V);let w=(Q??E).range;B.range=[E.range[0],w[1],w[2]],l.items.push(B)}u=Q?Q.range[2]:L.end}}let f=o?"}":"]",[p,...m]=n.end,h=u;if(p?.source===f)h=p.offset+p.source.length;else{let y=a[0].toUpperCase()+a.substring(1),x=d?`${y} must end with a ${f}`:`${y} in block collection must be sufficiently indented and end with a ${f}`;s(u,d?"MISSING_CHAR":"BAD_INDENT",x),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let y=nb.resolveEnd(m,h,t.options.strict,s);y.comment&&(l.comment?l.comment+=`
|
|
80
|
+
`+y.comment:l.comment=y.comment),l.range=[n.offset,h,y.offset]}else l.range=[n.offset,h,h];return l}rf.resolveFlowCollection=ob});var of=T(sf=>{"use strict";var ab=_(),cb=U(),lb=je(),ub=Fe(),fb=zu(),db=Xu(),pb=nf();function Wo(r,e,t,n,s,i){let o=t.type==="block-map"?fb.resolveBlockMap(r,e,t,n,i):t.type==="block-seq"?db.resolveBlockSeq(r,e,t,n,i):pb.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 hb(r,e,t,n,s){let i=n.tag,o=i?e.directives.tagName(i.source,f=>s(i,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=n,m=f&&i?f.offset>i.offset?f:i:f??i;m&&(!p||p.offset<m.offset)&&s(m,"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===lb.YAMLMap.tagName&&a==="map"||o===ub.YAMLSeq.tagName&&a==="seq")return Wo(r,e,t,s,o);let c=e.schema.tags.find(f=>f.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?s(i,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Wo(r,e,t,s,o)}let l=Wo(r,e,t,s,o,c),d=c.resolve?.(l,f=>s(i,"TAG_RESOLVE_FAILED",f),e.options)??l,u=ab.isNode(d)?d:new cb.Scalar(d);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}sf.composeCollection=hb});var Vo=T(af=>{"use strict";var Ho=U();function mb(r,e,t){let n=e.offset,s=gb(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?Ho.Scalar.BLOCK_FOLDED:Ho.Scalar.BLOCK_LITERAL,o=e.source?yb(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let y=o[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){let h=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:h,type:i,comment:s.comment,range:[n,y,y]}}let c=e.indent+s.indent,l=e.offset+s.length,d=0;for(let h=0;h<a;++h){let[y,x]=o[h];if(x===""||x==="\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),d=h,c===0&&!r.atRoot&&t(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=y.length+x.length+1}for(let h=o.length-1;h>=a;--h)o[h][0].length>c&&(a=h+1);let u="",f="",p=!1;for(let h=0;h<d;++h)u+=o[h][0].slice(c)+`
|
|
82
|
-
`;for(let h=d;h<a;++h){let[y,x]=o[h];l+=y.length+x.length+1;let
|
|
82
|
+
`;for(let h=d;h<a;++h){let[y,x]=o[h];l+=y.length+x.length+1;let k=x[x.length-1]==="\r";if(k&&(x=x.slice(0,-1)),x&&y.length<c){let b=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;t(l-x.length-(k?2:1),"BAD_INDENT",b),y=""}i===Ho.Scalar.BLOCK_LITERAL?(u+=f+y.slice(c)+x,f=`
|
|
83
83
|
`):y.length>c||x[0]===" "?(f===" "?f=`
|
|
84
84
|
`:!p&&f===`
|
|
85
85
|
`&&(f=`
|
|
@@ -92,68 +92,68 @@ ${l}
|
|
|
92
92
|
`+o[h][0].slice(c);u[u.length-1]!==`
|
|
93
93
|
`&&(u+=`
|
|
94
94
|
`);break;default:u+=`
|
|
95
|
-
`}let m=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,m,m]}}function
|
|
95
|
+
`}let m=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,m,m]}}function gb({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 f=1;f<s.length;++f){let p=s[f];if(!a&&(p==="-"||p==="+"))a=p;else{let m=Number(p);!o&&m?o=m:c===-1&&(c=r+f)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,d="",u=s.length;for(let f=1;f<e.length;++f){let p=e[f];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,d=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let m=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",m);let h=p.source;h&&typeof h=="string"&&(u+=h.length)}}}return{mode:i,indent:o,chomp:a,comment:d,length:u}}function yb(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}af.resolveBlockScalar=mb});var Go=T(lf=>{"use strict";var Yo=U(),bb=Rt();function wb(r,e,t){let{offset:n,type:s,source:i,end:o}=r,a,c,l=(f,p,m)=>t(n+f,p,m);switch(s){case"scalar":a=Yo.Scalar.PLAIN,c=vb(i,l);break;case"single-quoted-scalar":a=Yo.Scalar.QUOTE_SINGLE,c=Sb(i,l);break;case"double-quoted-scalar":a=Yo.Scalar.QUOTE_DOUBLE,c=xb(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 d=n+i.length,u=bb.resolveEnd(o,d,e,t);return{value:c,type:a,comment:u.comment,range:[n,d,u.offset]}}function vb(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}`),cf(r)}function Sb(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),cf(r.slice(1,-1)).replace(/''/g,"'")}function cf(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 xb(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}=kb(r,n);t+=i,n=o}else if(s==="\\"){let i=r[++n],o=Eb[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+=Ab(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 kb(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 Eb={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 Ab(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)}lf.resolveFlowScalar=wb});var df=T(ff=>{"use strict";var rt=_(),uf=U(),Tb=Vo(),Pb=Go();function Ob(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?Tb.resolveBlockScalar(r,e,n):Pb.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[rt.SCALAR]:c?l=Cb(r.schema,s,c,t,n):e.type==="scalar"?l=Rb(r,s,e,n):l=r.schema[rt.SCALAR];let d;try{let u=l.resolve(s,f=>n(t??e,"TAG_RESOLVE_FAILED",f),r.options);d=rt.isScalar(u)?u:new uf.Scalar(u)}catch(u){let f=u instanceof Error?u.message:String(u);n(t??e,"TAG_RESOLVE_FAILED",f),d=new uf.Scalar(s)}return d.range=a,d.source=s,i&&(d.type=i),c&&(d.tag=c),l.format&&(d.format=l.format),o&&(d.comment=o),d}function Cb(r,e,t,n,s){if(t==="!")return r[rt.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[rt.SCALAR])}function Rb({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[rt.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[rt.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),d=`Value may be parsed as either ${c} or ${l}`;i(s,"TAG_RESOLVE_FAILED",d,!0)}}return o}ff.composeScalar=Ob});var hf=T(pf=>{"use strict";function Nb(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}pf.emptyScalarPosition=Nb});var yf=T(Qo=>{"use strict";var _b=or(),Ib=_(),Lb=of(),mf=df(),$b=Rt(),Mb=hf(),Db={composeNode:gf,composeEmptyNode:zo};function gf(r,e,t,n){let s=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=t,l,d=!0;switch(e.type){case"alias":l=Bb(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=mf.composeScalar(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=Lb.composeCollection(Db,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=zo(r,e.offset,void 0,null,t,n),d=!1}}return a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&r.options.stringKeys&&(!Ib.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&&d&&(l.srcToken=e),l}function zo(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let d={type:"scalar",offset:Mb.emptyScalarPosition(e,t,n),indent:-1,source:""},u=mf.composeScalar(r,d,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 Bb({options:r},{offset:e,source:t,end:n},s){let i=new _b.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=$b.resolveEnd(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}Qo.composeEmptyNode=zo;Qo.composeNode=gf});var vf=T(wf=>{"use strict";var jb=kr(),bf=yf(),Fb=Rt(),qb=Pr();function Ub(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new jb.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=qb.resolveProps(n,{indicator:"doc-start",next:s??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?bf.composeNode(l,s,d,o):bf.composeEmptyNode(l,d.end,n,null,d,o);let u=c.contents.range[2],f=Fb.resolveEnd(i,u,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,u,f.offset],c}wf.composeDoc=Ub});var Zo=T(kf=>{"use strict";var Jb=hn("process"),Kb=Di(),Wb=kr(),Or=Tr(),Sf=_(),Hb=vf(),Vb=Rt();function Cr(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 xf(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 Xo=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=Cr(t);i?this.warnings.push(new Or.YAMLWarning(o,n,s)):this.errors.push(new Or.YAMLParseError(o,n,s))},this.directives=new Kb.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=xf(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(Sf.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];Sf.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 Or.YAMLParseError(Cr(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
|
|
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:xf(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(Jb.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,n,s)=>{let i=Cr(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=Hb.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 Or.YAMLParseError(Cr(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 Or.YAMLParseError(Cr(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=Vb.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 Or.YAMLParseError(Cr(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 Wb.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}}};kf.Composer=Xo});var Tf=T(as=>{"use strict";var Yb=Vo(),Gb=Go(),zb=Tr(),Ef=fr();function Qb(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 zb.YAMLParseError([a,a+1],i,o)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Gb.resolveFlowScalar(r,e,n);case"block-scalar":return Yb.resolveBlockScalar({options:{strict:e}},r,n)}}return null}function Xb(r,e){let{implicitKey:t=!1,indent:n,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=e,a=Ef.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
|
`),d=a.substring(0,l),u=a.substring(l+1)+`
|
|
120
|
-
`,f=[{type:"block-scalar-header",offset:i,indent:n,source:d}];return
|
|
121
|
-
`}),{type:"block-scalar",offset:i,indent:n,props:f,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
|
+
`,f=[{type:"block-scalar-header",offset:i,indent:n,source:d}];return Af(f,c)||f.push({type:"newline",offset:-1,indent:n,source:`
|
|
121
|
+
`}),{type:"block-scalar",offset:i,indent:n,props:f,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 Zb(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=Ef.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">":ew(r,c);break;case'"':ea(r,c,"double-quoted-scalar");break;case"'":ea(r,c,"single-quoted-scalar");break;default:ea(r,c,"scalar")}}function ew(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}];Af(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 Af(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 ea(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})}}}as.createScalarToken=Xb;as.resolveAsScalar=Qb;as.setScalarValue=Zb});var Of=T(Pf=>{"use strict";var tw=r=>"type"in r?ls(r):cs(r);function ls(r){switch(r.type){case"block-scalar":{let e="";for(let t of r.props)e+=ls(t);return e+r.source}case"block-map":case"block-seq":{let e="";for(let t of r.items)e+=cs(t);return e}case"flow-collection":{let e=r.start.source;for(let t of r.items)e+=cs(t);for(let t of r.end)e+=t.source;return e}case"document":{let e=cs(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 cs({start:r,key:e,sep:t,value:n}){let s="";for(let i of r)s+=i.source;if(e&&(s+=ls(e)),t)for(let i of t)s+=i.source;return n&&(s+=ls(n)),s}Pf.stringify=tw});var _f=T(Nf=>{"use strict";var ta=Symbol("break visit"),rw=Symbol("skip children"),Cf=Symbol("remove item");function nt(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),Rf(Object.freeze([]),r,e)}nt.BREAK=ta;nt.SKIP=rw;nt.REMOVE=Cf;nt.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};nt.parentCollection=(r,e)=>{let t=nt.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 Rf(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=Rf(Object.freeze(r.concat([[s,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===ta)return ta;a===Cf&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&s==="key"&&(n=n(e,r))}}return typeof n=="function"?n(e,r):n}Nf.visit=nt});var us=T(re=>{"use strict";var ra=Tf(),nw=Of(),sw=_f(),na="\uFEFF",sa="",ia="",oa="",iw=r=>!!r&&"items"in r,ow=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar");function aw(r){switch(r){case na:return"<BOM>";case sa:return"<DOC>";case ia:return"<FLOW_END>";case oa:return"<SCALAR>";default:return JSON.stringify(r)}}function cw(r){switch(r){case na:return"byte-order-mark";case sa:return"doc-mode";case ia:return"flow-error-end";case oa: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}re.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}re.createScalarToken=ra.createScalarToken;re.resolveAsScalar=ra.resolveAsScalar;re.setScalarValue=ra.setScalarValue;re.stringify=nw.stringify;re.visit=sw.visit;re.BOM=na;re.DOCUMENT=sa;re.FLOW_END=ia;re.SCALAR=oa;re.isCollection=iw;re.isScalar=ow;re.prettyToken=aw;re.tokenType=cw});var la=T(Lf=>{"use strict";var Rr=us();function de(r){switch(r){case void 0:case" ":case`
|
|
128
|
+
`:case"\r":case" ":return!0;default:return!1}}var If=new Set("0123456789ABCDEFabcdef"),lw=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),fs=new Set(",[]{}"),uw=new Set(` ,[]{}
|
|
129
|
+
\r `),aa=r=>!r||uw.has(r),ca=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==="...")&&de(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]===Rr.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 Rr.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==="...")&&de(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&&!de(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===":")&&de(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(
|
|
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]===Rr.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 Rr.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==="...")&&de(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&&!de(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===":")&&de(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(aa),"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("..."))&&de(s[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield Rr.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(aa),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||de(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=>de(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 Rr.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(de(i)||e&&
|
|
141
|
+
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield Rr.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(de(i)||e&&fs.has(i))break;t=n}else if(de(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&&fs.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&&fs.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield Rr.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(aa))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(de(t)||e&&fs.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(;!de(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(lw.has(t))t=this.buffer[++e];else if(t==="%"&&If.has(this.buffer[e+1])&&If.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)}};Lf.Lexer=ca});var fa=T($f=>{"use strict";var ua=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}}}};$f.LineCounter=ua});var pa=T(Ff=>{"use strict";var fw=hn("process"),Mf=us(),dw=la();function qe(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function Df(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 jf(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 ds(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 Nt(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 Bf(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!qe(e.start,"explicit-key-ind")&&!qe(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,jf(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 da=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 dw.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,fw.env.LOG_TOKENS&&console.log("|",Mf.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Mf.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"&&Bf(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&&Df(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":{Df(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=ds(this.peek(2)),n=Nt(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(qe(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(qe(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(jf(t.key)&&!qe(t.sep,"newline")){let o=Nt(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(qe(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=Nt(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]}):qe(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&&!qe(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||qe(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=ds(n),i=Nt(s);Bf(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=ds(e),n=Nt(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=ds(e),n=Nt(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())}}};Ff.Parser=da});var Wf=T(_r=>{"use strict";var qf=Zo(),pw=kr(),Nr=Tr(),hw=zi(),mw=_(),gw=fa(),Uf=pa();function Jf(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new gw.LineCounter||null,prettyErrors:e}}function yw(r,e={}){let{lineCounter:t,prettyErrors:n}=Jf(e),s=new Uf.Parser(t?.addNewLine),i=new qf.Composer(e),o=Array.from(i.compose(s.parse(r)));if(n&&t)for(let a of o)a.errors.forEach(Nr.prettifyError(r,t)),a.warnings.forEach(Nr.prettifyError(r,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Kf(r,e={}){let{lineCounter:t,prettyErrors:n}=Jf(e),s=new Uf.Parser(t?.addNewLine),i=new qf.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 Nr.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Nr.prettifyError(r,t)),o.warnings.forEach(Nr.prettifyError(r,t))),o}function bw(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=Kf(r,t);if(!s)return null;if(s.warnings.forEach(i=>hw.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 ww(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 mw.isDocument(r)&&!n?r.toString(t):new pw.Document(r,n,t).toString(t)}_r.parse=bw;_r.parseAllDocuments=yw;_r.parseDocument=Kf;_r.stringify=ww});var Vf=T($=>{"use strict";var vw=Zo(),Sw=kr(),xw=Io(),ha=Tr(),kw=or(),Ue=_(),Ew=De(),Aw=U(),Tw=je(),Pw=Fe(),Ow=us(),Cw=la(),Rw=fa(),Nw=pa(),ps=Wf(),Hf=rr();$.Composer=vw.Composer;$.Document=Sw.Document;$.Schema=xw.Schema;$.YAMLError=ha.YAMLError;$.YAMLParseError=ha.YAMLParseError;$.YAMLWarning=ha.YAMLWarning;$.Alias=kw.Alias;$.isAlias=Ue.isAlias;$.isCollection=Ue.isCollection;$.isDocument=Ue.isDocument;$.isMap=Ue.isMap;$.isNode=Ue.isNode;$.isPair=Ue.isPair;$.isScalar=Ue.isScalar;$.isSeq=Ue.isSeq;$.Pair=Ew.Pair;$.Scalar=Aw.Scalar;$.YAMLMap=Tw.YAMLMap;$.YAMLSeq=Pw.YAMLSeq;$.CST=Ow;$.Lexer=Cw.Lexer;$.LineCounter=Rw.LineCounter;$.Parser=Nw.Parser;$.parse=ps.parse;$.parseAllDocuments=ps.parseAllDocuments;$.parseDocument=ps.parseDocument;$.stringify=ps.stringify;$.visit=Hf.visit;$.visitAsync=Hf.visitAsync});function Iw(r){try{return JSON.parse(r.trim()),!0}catch{return!1}}function Lw(r){let e=r.trim();if(!e.startsWith("<"))return!1;let t=e.match(_w);return t?tr(e,t[1])!==null:!1}function $w(r){let e=r.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=Yf.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function Gf(r){return Iw(r)||Lw(r)||$w(r)}var Yf,_w,ma=C(()=>{sl();Yf=Jh(Vf(),1),_w=/<([a-zA-Z_][\w.-]*)/});function Mw(r){if(!r?.trim())return[];let e=r.replace(/\r\n/g,`
|
|
151
|
+
`),t=e.trim();if(Gf(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
|
-
`))for(let s of
|
|
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 ga(r){return Mw(r).map(e=>e.text)}var zf=C(()=>{ma()});var Ir=C(()=>{mn();Vc();Gc();Qc();ma();zf();gn()});function hs(r){return{...Hc(r),server:r.files.get("server.ts")??""}}var ya=C(()=>{Ir();Ir();Ir()});function Xf(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 Zf(r){let e=[],t=new Set;for(let n of r.split(`
|
|
155
|
+
`))for(let s of Qf)for(let i of n.matchAll(s)){let o=Xf(i[1]);o&&!t.has(o)&&(t.add(o),e.push(o))}return e}function Lr(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 Bw)l.targets.includes(t)&&l.pattern.test(a)&&s.push({type:l.type,severity:"error",message:qw(l.type,c),lineNumber:c,lineContent:a})}return t==="client"&&n&&s.push(...jw(i,n)),s}function jw(r,e){let t=new Set(Object.keys(e)),n=new Set,s=[];for(let i=0;i<r.length;i++)for(let o of Qf)for(let a of r[i].matchAll(o)){let c=Xf(a[1]);!c||t.has(c)||n.has(c)||(n.add(c),s.push({type:"UNDECLARED_IMPORT",severity:"error",message:Fw(c,i+1),lineNumber:i+1,lineContent:r[i]}))}return s}function Fw(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 qw(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,27 +321,85 @@ 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 st,it,
|
|
325
|
-
`),n=[];if(t.forEach((o,a)=>{let c=
|
|
326
|
-
`)}function
|
|
327
|
-
\u2026[${r.length-5e4} more characters truncated]`:r}var
|
|
328
|
-
`):r==null?"":ke(JSON.stringify(r))}function
|
|
324
|
+
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var st,it,Bw,Qf,ms=C(()=>{st=["client"],it=["client","server"],Bw=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:st},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:it},{type:"JS_EXTENSION_IMPORT",pattern:/from\s+['"][^'"]*\/[^'"]*\.js['"]/,targets:st},{type:"URL_IMPORT",pattern:/from\s+['"]https?:\/\//,targets:st},{type:"VERSION_SPECIFIER_IMPORT",pattern:/from\s+['"][^'"]*@[\d^~]/,targets:st},{type:"REDUNDANT_TB_DECLARATION",pattern:/declare\s+(const|var|let)\s+tb\b/,targets:it},{type:"CONST_ENUM",pattern:/\bconst\s+enum\b/,targets:it},{type:"NAMESPACE_DECLARATION",pattern:/\bnamespace\s+\w+/,targets:it},{type:"COMMONJS_EXPORT_EQUALS",pattern:/\bexport\s*=/,targets:it},{type:"COMMONJS_IMPORT_EQUALS",pattern:/\bimport\s+\w+\s*=/,targets:it},{type:"MODULE_DECLARATION",pattern:/\bmodule\s+\w+\s*\{/,targets:it},{type:"CSS_FILE_IMPORT",pattern:/(?:from|import)\s+['"][^'"]*\.css['"]/,targets:st},{type:"NAVIGATION",pattern:/window\.(location\.(reload|assign|replace)\s*\(|open\s*\()/,targets:st},{type:"NAVIGATION",pattern:/window\.location(\.href)?\s*=[^=]/,targets:st}],Qf=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{realpathSync as Av}from"fs";import{join as Ia,resolve as Tv}from"path";import{homedir as Pv}from"os";function Is(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?Ia(r,".."):Ia(Pv(),".typebulb")}function Ce(){return process.env.TYPEBULB_SERVERS_DIR||Ia(Is(),"servers")}function J(r){let e=Tv(r),t=e;try{t=Av.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function _d(r,e){let t=J(r),n=J(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var Qr=C(()=>{});import{readFileSync as Ov,writeFileSync as Cv,mkdirSync as Rv}from"fs";import{join as Nv}from"path";function Id(){return Nv(Is(),"trust.json")}function La(){try{let r=JSON.parse(Ov(Id(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function _v(r){Rv(Is(),{recursive:!0}),Cv(Id(),JSON.stringify([...r]))}function lt(r){return La().has(J(r))}function jt(r,e){let t=La(),n=J(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),_v(t))}function $a(){return[...La()]}var Xr=C(()=>{Qr()});function Ut(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 Ds=C(()=>{});import{spawn as Wd}from"child_process";import{readdir as tS,readFile as Vd,writeFile as Yd,unlink as ut,mkdir as rS}from"fs/promises";import{mkdirSync as Gd,writeFileSync as Bs,appendFileSync as nS,readFileSync as Da}from"fs";import*as ue from"path";import{fileURLToPath as sS}from"url";function Ba(r){return ue.join(Ce(),`${r}.json`)}function Jt(r){return ue.join(Ce(),`${r}.log`)}function js(r){return ue.join(Ce(),`${r}.wait.json`)}function zd(r){try{let e=JSON.parse(Da(js(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:typeof e.offset=="number"?{"":e.offset}:{}}catch{return{}}}function ja(r,e=""){let t=zd(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Fs(r,e,t=""){try{Gd(Ce(),{recursive:!0});let n=zd(r);n[t]=e,Bs(js(r),JSON.stringify({cursors:n}))}catch{}}function qs(r){let e=Jt(r);try{Gd(Ce(),{recursive:!0}),Bs(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(nS(e,c),s+=c.length,s>2*Hd){let l=Da(e),d=l.subarray(Math.max(0,l.length-Hd));Bs(e,d),s=d.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 Qd(r){try{Bs(Jt(r),"")}catch{}}function xe(r,e=0){try{let t=Da(Jt(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 Fa(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function oS(r){let e=iS.exec(r);return e?Number(e[1]):void 0}function Xd(r,e){let t=r.split(`
|
|
325
|
+
`),n=[];if(t.forEach((o,a)=>{let c=oS(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(`
|
|
326
|
+
`)}function qa(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function Us(r){await rS(Ce(),{recursive:!0}),await Yd(Ba(r.pid),JSON.stringify(r))}async function Zd(r,e){let t=Ba(r);try{let n=JSON.parse(await Vd(t,"utf8"));if(n.denied===e)return;n.denied=e,await Yd(t,JSON.stringify(n))}catch{}}async function tn(r){await ut(Ba(r)).catch(()=>{}),await ut(Jt(r)).catch(()=>{}),await ut(js(r)).catch(()=>{})}async function K(r){let e;try{e=await tS(Ce())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!/^\d+\.json$/.test(s))return;let i=ue.join(Ce(),s),o;try{o=JSON.parse(await Vd(i,"utf8"))}catch{await ut(i).catch(()=>{});return}o&&typeof o.pid=="number"&&qa(o.pid)?t.push(o):(await ut(i).catch(()=>{}),o?.pid&&(await ut(Jt(o.pid)).catch(()=>{}),await ut(js(o.pid)).catch(()=>{})))})),(r?t.filter(s=>s.agent==null&&_d(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function rn(r,e){let t=J(r);return(await K()).find(n=>n.cwd!=null&&J(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function ft(r){try{process.kill(r,"SIGTERM")}catch{}await tn(r)}function Js(r,e){let t=J(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&J(n.file)===t)}async function Ua(r){let e=Js(await K(),r);for(let t of e)await ft(t.pid);return e}function cS(r,e,t){(process.platform==="win32"?Wd("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):Wd(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function ep(){return ue.join(ue.dirname(sS(import.meta.url)),"index.js")}function lS(r,e={}){return{command:process.execPath,args:[ep(),...e.trust?["--trust"]:[],r,...e.open===!1?["--no-open"]:[]]}}function uS(r){return{command:process.execPath,args:[ep(),`agent:${r}`,"--no-open"]}}async function tp(r,e,t,n){let s=await r();if(s)return s;cS(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await aS(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function Ks(r,e={}){let t=e.cwd??process.cwd(),n=ue.resolve(t,r);return await Ua(n),tp(async()=>Js(await K(),n)[0],lS(r,e),t,ue.basename(r))}async function rp(r,e=process.cwd()){return tp(()=>rn(e,r),uS(r),e,`the ${r} mirror`)}var Hd,iS,aS,ge=C(()=>{Qr();Hd=1e6;iS=/^── run (\d+) ── /;aS=r=>new Promise(e=>setTimeout(e,r))});function ke(r){return r.length>5e4?r.slice(0,5e4)+`
|
|
327
|
+
\u2026[${r.length-5e4} more characters truncated]`:r}var Ws,Hs=C(()=>{Ws=(r,e)=>``});import{existsSync as fS,readdirSync as dS,statSync as pS}from"fs";import{join as hS}from"path";function Vs(r){if(!fS(r))return[];let e;try{e=dS(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=hS(r,n);try{let i=pS(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var Ja=C(()=>{});var Kt,Ka=C(()=>{Kt=class{ensureWaitSupport(){}}});import{openSync as mS,readSync as gS,closeSync as yS,statSync as bS,readdirSync as wS,readFileSync as vS}from"fs";import{join as Ys}from"path";import{homedir as ip}from"os";function SS(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function Gs(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?Ws(e.data,e.media_type):""}function Wa(r){return typeof r=="string"?ke(r):Array.isArray(r)?r.map(e=>{if(typeof e=="string")return ke(e);let t=e;return typeof t?.text=="string"?ke(t.text):t?.content!=null?Wa(t.content):Gs(t)}).join(`
|
|
328
|
+
`):r==null?"":ke(JSON.stringify(r))}function kS(r){let e=r.trim();return!!e&&op.some(t=>t.test(e))}function ES(r){let e=r.trim();return e?op.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function TS(r){return r.replace(AS,"")}function PS(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 Ye(r){let e=TS(r).trim();return e?PS(e)??(kS(e)?"":e):""}function Ha(r){return r?.type==="text"&&typeof r.text=="string"?Ye(r.text):""}function nn(r){return!!r.isSidechain||!!r.isMeta}function OS(r){let e;try{e=mS(r,"r")}catch{return""}try{let n=65536;try{n=bS(r).size}catch{}let s=(l,d)=>{if(d<=0)return"";let u=Buffer.alloc(d),f=gS(e,u,0,d,l);return u.subarray(0,f).toString("utf8")},i=(l,d,u)=>{let f="";for(let p of l.split(`
|
|
329
329
|
`)){if(!p.includes(`"${d}"`))continue;let m;try{m=JSON.parse(p)}catch{continue}let h=m?.[u];m?.type===d&&typeof h=="string"&&h&&(f=h)}return f},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(`
|
|
330
|
-
`)){if(!l.trim())continue;let d;try{d=JSON.parse(l)}catch{continue}if(!d||nn(d)||d.type!=="user")continue;let u=d.message?.content,f="";typeof u=="string"?f=Ye(u):Array.isArray(u)&&(f=u.map(
|
|
331
|
-
`),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??""),f=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:f})}let l=e.message?.usage??e.usage,d=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:d,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()&&Ye(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
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
330
|
+
`)){if(!l.trim())continue;let d;try{d=JSON.parse(l)}catch{continue}if(!d||nn(d)||d.type!=="user")continue;let u=d.message?.content,f="";typeof u=="string"?f=Ye(u):Array.isArray(u)&&(f=u.map(Ha).filter(Boolean).join(" "));let p=f.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{yS(e)}}function CS(r){let e;try{e=wS(sp)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let n=JSON.parse(vS(Ys(sp,t),"utf8"));if(n?.sessionId!==r)continue;return process.kill(n.pid,0),!0}catch{}return!1}var xS,np,op,AS,sp,Wt,zs=C(()=>{Hs();Ja();Ka();xS=Ys(ip(),".claude","projects"),np=r=>Ys(xS,SS(r));op=[/\[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];AS=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;sp=Ys(ip(),".claude","sessions");Wt=class extends Kt{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}sessionsDir(e){return np(e)}listSessionFiles(e){return Vs(np(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(nn(e))return{events:[]};let n=[];if(e.type==="user"){let s=e.message?.content;if(typeof s=="string"){let i=Ye(s);i&&n.push({type:"user",text:i})}else if(Array.isArray(s))for(let i of s)if(i?.type==="tool_result")n.push({type:"tool_result",id:i.tool_use_id??"",content:Wa(i.content),isError:!!i.is_error});else{let o=Ha(i)||Gs(i);o&&n.push({type:"user",text:o})}return{events:n}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=Ye(Wa(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=>!ES(u)).join(""),a=i.filter(u=>u.type==="thinking").map(u=>u.thinking??"").join(`
|
|
331
|
+
`),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??""),f=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:f})}let l=e.message?.usage??e.usage,d=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:d,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()&&Ye(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 CS(e)}readPreview(e){return OS(e)}searchText(e){if(!e||nn(e)||e.type!=="user"&&e.type!=="assistant")return"";let t=e.message?.content,n="";if(typeof t=="string")n=Ye(t);else if(Array.isArray(t)){let s=t;n=e.type==="user"?s.map(Ha).filter(Boolean).join(" "):s.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(" ")}return n.replace(/\s+/g," ").trim()}}});import{existsSync as RS,mkdirSync as NS,writeFileSync as _S}from"fs";import{homedir as IS}from"os";import*as sn from"path";function cp(){try{if(!RS(ap()))return;let r=LS();NS(sn.dirname(r),{recursive:!0}),_S(r,$S)}catch{}}var ap,LS,$S,lp=C(()=>{ap=()=>sn.join(IS(),".pi","agent"),LS=()=>sn.join(ap(),"extensions","typebulb-wait.ts"),$S=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
|
|
332
|
+
import { spawn } from "node:child_process";
|
|
333
|
+
|
|
334
|
+
function logErr(...a) { try { console.error("[typebulb-wait]", ...a); } catch (e) {} }
|
|
335
|
+
|
|
336
|
+
// Matches "typebulb wait", "npx typebulb wait", "/path/to/typebulb wait", "pnpm exec typebulb wait", etc.
|
|
337
|
+
function isWaitCommand(command) { return /\btypebulb\s+wait\b/.test(String(command || "")); }
|
|
338
|
+
|
|
339
|
+
export default function (pi) {
|
|
340
|
+
try {
|
|
341
|
+
const pending = new Set();
|
|
342
|
+
|
|
343
|
+
pi.on("tool_call", (event, ctx) => {
|
|
344
|
+
try {
|
|
345
|
+
if (!event || event.toolName !== "bash") return undefined;
|
|
346
|
+
const command = event.input && event.input.command;
|
|
347
|
+
if (!isWaitCommand(command)) return undefined;
|
|
348
|
+
|
|
349
|
+
// Run the REAL typebulb wait in the background instead of foreground (which would deadlock the
|
|
350
|
+
// turn). It does the mirror/registry lookup, --match and offsets itself. The marker tells it this
|
|
351
|
+
// is a shim-backgrounded (non-blocking) wait, so it runs as a pure subscription: no give-up clock,
|
|
352
|
+
// it waits for the event however long (bounded by the session-shutdown reap below) — an embed's
|
|
353
|
+
// first paint OR a running bulb's next event line alike.
|
|
354
|
+
const child = spawn(command, {
|
|
355
|
+
shell: true,
|
|
356
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
357
|
+
env: { ...process.env, TYPEBULB_WAIT_SHIM: "1" },
|
|
358
|
+
});
|
|
359
|
+
pending.add(child);
|
|
360
|
+
let out = "";
|
|
361
|
+
if (child.stdout) child.stdout.on("data", (b) => { out += b.toString(); });
|
|
362
|
+
child.on("error", (e) => { pending.delete(child); logErr("spawn", e && e.message); });
|
|
363
|
+
child.on("exit", (code) => {
|
|
364
|
+
pending.delete(child);
|
|
365
|
+
try {
|
|
366
|
+
const text = out.trim();
|
|
367
|
+
// Exit 0 with output is a real outcome (embed ok/error, a turn-based move) -> wake the
|
|
368
|
+
// agent (followUp delivers immediately when idle and queues when streaming — the same call
|
|
369
|
+
// git-merge-and-resolve.ts makes from agent_end). A late wake is fine; it just reports
|
|
370
|
+
// something true. Exit 2/3 (no render yet / server gone) surface passively, no turn.
|
|
371
|
+
if (code === 0 && text) {
|
|
372
|
+
pi.sendUserMessage("typebulb wait result:\n" + text, { deliverAs: "followUp" });
|
|
373
|
+
} else if (ctx.ui && typeof ctx.ui.notify === "function") {
|
|
374
|
+
ctx.ui.notify("typebulb wait: " + (code === 2 ? "timed out, nothing to report" : "ended (code " + code + ")"), "info");
|
|
375
|
+
}
|
|
376
|
+
} catch (e) { logErr("exit", e && e.message); }
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
return {
|
|
380
|
+
block: true,
|
|
381
|
+
reason: "Armed in the background. You will be re-invoked automatically with the result when it is ready - do not run this command again; end your turn now and wait for the result.",
|
|
382
|
+
};
|
|
383
|
+
} catch (e) { logErr("tool_call", e && e.message); return undefined; }
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
try { pi.on("session_shutdown", () => { for (const c of pending) { try { c.kill(); } catch (e) {} } pending.clear(); }); } catch (e) {}
|
|
387
|
+
} catch (e) { logErr("load", e && e.message); }
|
|
388
|
+
}
|
|
389
|
+
`});import{statSync as MS,openSync as DS,readSync as BS,closeSync as jS}from"fs";import{join as fp}from"path";import{homedir as FS}from"os";function US(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function up(r){return r.type==="message"?JS(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var qS,JS,Ht,Va=C(()=>{Hs();Ja();Ka();lp();qS=fp(FS(),".pi","agent","sessions");JS=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";Ht=class extends Kt{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}ensureWaitSupport(){cp()}sessionsDir(e){return fp(qS,US(e))}listSessionFiles(e){return Vs(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 up(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")return n.push({type:"tool_result",id:s.toolCallId??"",content:this.contentText(s.content),isError:!!s.isError}),{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(u=>u.type==="text").map(u=>u.text??"").join(""),a=i.filter(u=>u.type==="thinking").map(u=>u.thinking??"").join(`
|
|
390
|
+
`),c=i.filter(u=>u.type==="toolCall").map(u=>({id:u.id??"",name:u.name??"",input:u.arguments??{}}));if(o||a||c.length){let u=Date.parse(e.timestamp??""),f=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:f})}let l=s.usage,d=l&&{in:l.input??0,out:l.output??0,cached:l.cacheRead??0,cacheCreate:l.cacheWrite??0};return{events:n,usage:d,model:s.model}}return{events:n}}chainWorking(e){let t;for(let a of e)up(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=DS(e,"r")}catch{return""}try{let s=65536;try{s=MS(e).size}catch{}let i=Buffer.alloc(Math.min(65536,s)),o=BS(t,i,0,i.length,0),a=i.subarray(0,o).toString("utf8"),c="",l="";for(let u of a.split(`
|
|
391
|
+
`)){if(!u.includes('"type"'))continue;let f;try{f=JSON.parse(u)}catch{continue}f?.type==="session_info"&&typeof f.name=="string"&&f.name?c=f.name:!l&&f?.type==="message"&&f.message?.role==="user"&&(l=this.contentText(f.message.content).replace(/\s+/g," ").trim())}let d=c||l;return d?d.slice(0,200):""}finally{jS(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"?ke(e):Array.isArray(e)?e.map(t=>typeof t?.text=="string"?ke(t.text):t?.type==="image"&&t.data?Ws(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
392
|
+
`):""}}});function za(r){return(r.includes("://")?r:`http://${r}`).replace(/\/+$/,"")}async function pt(){let[r,e]=await Promise.all([ix(),sx()]);return[...ox(e),...r]}async function sx(){if(Vt&&Date.now()-Vt.fetchedAt<=rx)return Vt.models;let r=await fetch(tx).catch(()=>null);return!r||!r.ok?Vt?.models??[]:(Vt={models:await r.json(),fetchedAt:Date.now()},Vt.models)}async function ix(){if(Xs&&Date.now()-Xs.fetchedAt<=nx)return Xs.models;let r=za(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 Xs={models:e,fetchedAt:Date.now()},e}function ox(r){let e=new Set(Object.entries(Yt).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function yp(){return Object.values(Yt).some(r=>!!process.env[r])}function bp(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(`
|
|
393
|
+
`)}var Yt,tx,rx,nx,Vt,Xs,Zs=C(()=>{Yt={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};tx="https://api.typebulb.com/api/models",rx=1440*60*1e3,nx=60*1e3,Vt=null,Xs=null});function be(r){return r?.message??String(r)}var G,pi=C(()=>{G=process.cwd()});var hi,qp=C(()=>{hi=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});function mi(r,e){let t=0,n="";for(let s of r){let i=s.lower.indexOf(e);if(!(i<0)&&(t++,!n)){let o=Math.max(0,i-110),a=Math.min(s.text.length,i+e.length+110);n=(o>0?"\u2026":"")+s.text.slice(o,a)+(a<s.text.length?"\u2026":"")}}return{hitCount:t,snippet:n}}var uc=C(()=>{});import{existsSync as Up,openSync as Px,readSync as Ox,closeSync as Cx,statSync as zt,readdirSync as Jp,watchFile as Rx,unwatchFile as Kp,mkdirSync as Nx,writeFileSync as _x,readFileSync as fc,unlinkSync as Ix,rmSync as Lx}from"fs";import{join as Qt}from"path";function gi(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=w=>Qt(w,Mx),n=(w,A)=>Qt(t(w),`${A}.lock`);function s(w,A){try{let O=n(w,A);if(Date.now()-zt(O).mtimeMs>=Wp)return!1;try{if(parseInt(fc(O,"utf8").trim(),10)===process.pid)return!1}catch{}return!0}catch{return!1}}function i(w,A){if(A)try{Nx(t(w),{recursive:!0}),_x(n(w,A),String(process.pid))}catch(O){console.error("[lock] claim failed:",be(O))}}function o(w){try{Lx(Qt(w,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function a(w){let A=t(w);if(!Up(A))return;let O;try{O=Jp(A)}catch{return}let N=Date.now();for(let M of O){if(!M.endsWith(".lock"))continue;let D=Qt(A,M);try{let I=zt(D);N-I.mtimeMs>Dx&&Ix(D)}catch{}}}function c(w){try{return zt(w),!1}catch(A){return A.code==="ENOENT"}}function l(){let w=e;if(w.file&&!c(w.file)){i(w.cwd,w.sessionId);return}let A=d(w);A&&p(A)}function d(w){if(!w.everAttached)return u(w.cwd)??f(w.cwd,()=>!0)}function u(w){let A=t(w);if(!Up(A))return;let O;try{O=Jp(A)}catch{return}let N;for(let D of O)if(D.endsWith(".lock"))try{let I=zt(Qt(A,D));if(Date.now()-I.mtimeMs>=Wp||parseInt(fc(Qt(A,D),"utf8").trim(),10)!==process.pid)continue;(!N||I.mtimeMs>N.mtime)&&(N={sessionId:D.slice(0,-5),mtime:I.mtimeMs})}catch{}if(!N)return;let M=r.listSessionFiles(w).find(D=>D.sessionId===N.sessionId);if(!(!M||c(M.file)))return M}function f(w,A){return r.listSessionFiles(w).sort((O,N)=>N.mtime-O.mtime).find(O=>!s(w,O.sessionId)&&A(O))}function p(w){let A=e;if(A.file)try{Kp(A.file)}catch{}A.file=w.file,A.sessionId=w.sessionId,A.everAttached=!0,A.partial="",A.offset=0,A.latest={in:0,out:0,cached:0,cacheCreate:0},A.latestModel=null,A.entries=new Map,A.chainLastId=void 0,A.buffer.push({type:"cleared"}),A.buffer.push({type:"session",sessionId:w.sessionId}),i(A.cwd,w.sessionId),m();try{Kp(w.file)}catch{}Rx(w.file,{interval:200},()=>m())}function m(){let w=e;if(!w.file)return;let A;try{A=zt(w.file).size}catch{return}if(A<=w.offset)return;let O;try{O=Px(w.file,"r")}catch{return}try{let j=A-w.offset,ie=Buffer.alloc(j),Y=0;for(;Y<j;){let Oc=Ox(O,ie,Y,j-Y,w.offset+Y);if(!Oc)break;Y+=Oc}w.offset+=Y,w.partial+=ie.subarray(0,Y).toString("utf8")}finally{Cx(O)}let N,M;for(;(M=w.partial.indexOf(`
|
|
394
|
+
`))>=0;){let j=w.partial.slice(0,M);if(w.partial=w.partial.slice(M+1),!j.trim())continue;let ie=r.parseEntry(j);if(!ie)continue;let Y=r.idOf(ie);Y&&(w.entries.set(Y,ie),!r.isSidechain(ie)&&r.isLeafType(ie)&&(N=Y))}if(!N)return;let D=[],I=w.entries.get(N),F=!1;for(;I;){if(D.push(I),r.idOf(I)===w.chainLastId){F=!0;break}let j=r.parentOf(I);I=j?w.entries.get(j):void 0}if(F)for(let j=D.length-2;j>=0;j--)k(D[j]);else{w.chainLastId!==void 0&&(w.buffer.push({type:"cleared"}),w.buffer.push({type:"session",sessionId:w.sessionId}),w.latest={in:0,out:0,cached:0,cacheCreate:0});let j=new Set(D.map(Y=>r.idOf(Y))),ie=h(w.entries);for(let Y=D.length-1;Y>=0;Y--)k(D[Y]),y(r.idOf(D[Y]),ie,j)}w.chainLastId=N}function h(w){let A=new Map;for(let O of w.values()){let N=r.parentOf(O);if(!N)continue;let M=A.get(N);M?M.push(O):A.set(N,[O])}return A}function y(w,A,O){if(!w)return;let N=A.get(w);if(!N)return;let M=N.filter(j=>!r.isSidechain(j));if(M.length<2)return;let D=M.filter(j=>!O.has(r.idOf(j)));if(!D.length)return;let I=[],F=0;for(let j of D){let ie=x(j,A);I.push(...ie.events),F+=ie.count}F>0&&e.buffer.push({type:"fork",atId:w,count:F,events:I})}function x(w,A){let O=[],N=[w];for(;N.length;){let I=N.pop();if(r.isSidechain(I))continue;O.push(I);let F=A.get(r.idOf(I)??"");if(F)for(let j of F)N.push(j)}O.sort((I,F)=>(Date.parse(r.timestampOf(I)??"")||0)-(Date.parse(r.timestampOf(F)??"")||0));let M=[];for(let I of O)r.isRecoveryNoise(I)||M.push(...r.apply(I,e.sessionStartMs).events);return{count:M.reduce((I,F)=>I+(F.type==="user"||F.type==="assistant"?1:0),0),events:M}}function k(w){try{let{events:A,usage:O,model:N}=r.apply(w,e.sessionStartMs);for(let M of A)e.buffer.push(M);N&&(e.latestModel=N),O&&(e.latest=O,e.buffer.push({type:"usage",...e.latest}))}catch(A){console.error("[mirror] skipped malformed entry:",be(A))}}async function g(){return{cwd:e.cwd,pid:process.pid}}let b=new hi;async function v(w,A){b.accept(w,A)&&console.log(A)}function S(){let w=r.sessionAlive(e.sessionId,e.cwd);if(w!==void 0)return w;if(!e.file)return!1;try{return Date.now()-zt(e.file).mtimeMs<1e4}catch{return!1}}async function P(w){let A=e;return l(),{events:A.buffer.slice(w),cursor:A.buffer.length,working:r.chainWorking([...A.entries.values()])&&S(),latestModel:A.latestModel}}async function E(){return r.listSessionFiles(e.cwd).sort((w,A)=>A.mtime-w.mtime).map(({sessionId:w,file:A,mtime:O})=>({sessionId:w,mtime:O,preview:r.readPreview(A)}))}let L=new Map;function Q(w,A){let O=L.get(w);if(O&&O.mtime===A)return O.turns;let N=[],M="";try{M=fc(w,"utf8")}catch{return[]}for(let D of M.split(`
|
|
395
|
+
`)){if(!D.trim())continue;let I=r.parseEntry(D);if(!I)continue;let F=r.searchText(I);F&&N.push({text:F,lower:F.toLowerCase()})}return L.set(w,{mtime:A,turns:N}),N}async function V(w){let A=w.toLowerCase(),O=[];for(let{sessionId:N,file:M,mtime:D}of r.listSessionFiles(e.cwd).sort((I,F)=>F.mtime-I.mtime)){let{hitCount:I,snippet:F}=mi(Q(M,D),A);if(I&&(O.push({sessionId:N,mtime:D,preview:r.readPreview(M),hitCount:I,snippet:F}),O.length>=Bx))break}return O}async function B(w){let A=e,O=r.listSessionFiles(A.cwd).find(N=>N.sessionId===w);return O?O.file===A.file?{ok:!0}:(p(O),{ok:!0}):{ok:!1,error:"session not found"}}return o(e.cwd),a(e.cwd),l(),{info:g,poll:P,logEmbedStatus:v,listSessions:E,searchSessions:V,attach:B}}var $x,Mx,Wp,Dx,Bx,dc=C(()=>{pi();qp();uc();$x=".typebulb",Mx=`${$x}/locks`,Wp=5e3,Dx=6e4,Bx=50});function yi(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 pc(r){return(yi(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var hc=C(()=>{});import{readdirSync as jx,readFileSync as Fx,statSync as qx}from"fs";import{join as Hp,basename as Ux}from"path";function Vp(r,e,t){if(e>8)return t;let n;try{n=jx(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;Vp(Hp(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(Hp(r,s.name));return t}function bi(r){return Vp(r,0,[]).map(e=>{let t=0;try{t=qx(e).mtimeMs}catch{}let n;try{n=yi(Fx(e,"utf8").slice(0,1024))}catch{}return{path:e,name:n??Ux(e).replace(/\.bulb\.md$/,""),mtime:t}})}var Yp=C(()=>{hc()});import{readFile as Jx}from"fs/promises";async function mc(r){try{let e=Qe(await Jx(r,"utf-8"));return e?Ut(hs(e)):void 0}catch{return}}var Gp=C(()=>{ya();Ds()});function gc(r){let e=Qe(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=Zf(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,d]of e.files){let u=Fc(l);u&&(c[u]=d)}return c.config=JSON.stringify(i,null,2),Yc(c)}var zp=C(()=>{Ir();ms()});import{spawn as Qp}from"child_process";import{basename as Kx}from"path";function Wx(){return process.env.TYPEBULB_EDITOR||"code"}function Vx(r,e,t){return t==null?[e]:Hx.test(Kx(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function Yx(r,e){let t=Wx();return{command:t,args:Vx(t,r,e)}}function yc(r,e){let{command:t,args:n}=Yx(r,e),s=process.platform==="win32"?Qp("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):Qp(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var Hx,Xp=C(()=>{Hx=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});var bc=C(()=>{ge();Yp();Gp();hc();zp();Xp();Xr();Zs()});import{existsSync as wc,mkdirSync as Gx,readFileSync as Zp,writeFileSync as zx}from"fs";import{join as Xt,isAbsolute as Qx}from"path";async function eh(r,e){let t=Qx(r)?r:Xt(G,r);return wc(t)?(yc(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function th(r){let e=G,t=gc(r),n=Xt(e,"typebulbs");Gx(n,{recursive:!0});let s=pc(t),i=`${s}.bulb.md`;for(let l=2;wc(Xt(n,i))&&Zp(Xt(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=Xt(n,i);wc(o)||zx(o,t);let a=Xt("typebulbs",i),c=await Ks(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function rh(){return K(G)}async function nh(r){return await ft(r),{ok:!0}}async function sh(){return bi(G).map(r=>({...r,trusted:lt(r.path)}))}async function ih(r){let e=r.toLowerCase(),t=[];for(let n of bi(G).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=Zp(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
|
|
396
|
+
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=mi(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function oh(r,e){let t=G;e!=null&&jt(r,e);let n=await Ks(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function ah(r){return{cap:await mc(r)}}async function ch(r,e){return jt(r,e),{ok:!0}}async function lh(r,e){return xe(r,e)}var vc=C(()=>{bc();pi();uc()});import{readFileSync as kc,writeFileSync as fh,mkdirSync as Xx,appendFileSync as dh,rmSync as uh}from"fs";import{join as Si,dirname as Zx}from"path";import{createServer as ek}from"http";function ze(r){try{return JSON.parse(kc(r,"utf8"))}catch{return null}}function vi(r,e){Xx(Zx(r),{recursive:!0}),fh(r,JSON.stringify(e,null,2)+`
|
|
397
|
+
`)}function hh(r,e,t){let n=Si(r,".gitignore"),s="";try{s=kc(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(`
|
|
340
398
|
`)?`
|
|
341
|
-
`:"";try{
|
|
399
|
+
`:"";try{dh(n,a+t+`
|
|
342
400
|
`+o.join(`
|
|
343
401
|
`)+`
|
|
344
|
-
`)}catch(c){console.error("[switcher] .gitignore update failed",be(c))}}function
|
|
402
|
+
`)}catch(c){console.error("[switcher] .gitignore update failed",be(c))}}function ik(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?fn="live":s>sk&&(fn="uncached")}function gh(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 ok(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 yh(r){let e;try{e=JSON.parse(r)}catch{return r}un=typeof e?.model=="string"?e.model:null,Ae&&(e.model=Ae),yt&&(e.provider=mh(yt));let t=/haiku/i.test(un||"");return dn!=null&&!t&&(e.reasoning={effort:Sc[dn]}),delete e.thinking,e.output_config&&delete e.output_config.effort,ok(e),JSON.stringify(e)}function ak(){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}
|
|
345
403
|
data: ${JSON.stringify(a)}
|
|
346
404
|
|
|
347
405
|
`}case"content_block_delta":case"content_block_stop":{let c=t.get(a.index);return c==null?null:(a.index=c,`event: ${a.type}
|
|
@@ -349,10 +407,10 @@ data: ${JSON.stringify(a)}
|
|
|
349
407
|
|
|
350
408
|
`)}default:return i}};return i=>{r+=i;let o="",a;for(;(a=r.indexOf(`
|
|
351
409
|
|
|
352
|
-
`))!==-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
|
|
410
|
+
`))!==-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 ck(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 ln(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 lk(r,e,t){if(!Ae){ln(e,400,"invalid_request_error",nk);return}let n=process.env.OPENROUTER_API_KEY;if(!n){ln(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(Ec,{method:"POST",headers:gh(r,n),body:yh(t),signal:s.signal})}catch(u){ln(e,502,"api_error",`proxy upstream failed: ${be(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,d=a?ak():null;try{for(;;){let{done:u,value:f}=await c.read();if(u)break;if(f)if(d){let p=l.decode(f,{stream:!0});ik(p);let m=d(p);m&&e.write(m)}else e.write(Buffer.from(f))}}catch{}finally{e.writableEnded||e.end()}}async function uk(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(!Ae||!n)return s();try{let i=await fetch(`${Ec}/count_tokens`,{method:"POST",headers:gh(r,n),body:yh(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function fk(r,e){let t=r.url||"/";if(r.method==="HEAD"){e.writeHead(200),e.end();return}if(r.method!=="POST"){ln(e,404,"not_found_error",t);return}ck(r).then(n=>{if(t.includes("count_tokens"))return uk(r,e,n);if(t.includes("/v1/messages"))return lk(r,e,n);ln(e,404,"not_found_error",t)})}function dk(){return Zt&>?Promise.resolve(gt):new Promise((r,e)=>{let t=ek(fk);t.on("error",e),t.listen(0,"127.0.0.1",()=>{Zt=t,gt=t.address().port,console.log(`[switcher] wire proxy listening on ${wi(gt)}`),r(gt)})})}function pk(){try{Zt?.close()}catch{}Zt=null,gt=null}function hk(r,e){let t=xi(r),n=ze(t),s=n||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===wi(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=ki(r);if(!ze(i)){let a={};for(let c of ph)a[c]=c in s.env?s.env[c]:null;vi(i,{managedBy:"agent-switcher",fileExisted:n!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=wi(e),s.env.ANTHROPIC_AUTH_TOKEN=rk,vi(t,s),hh(r,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function mk(r,e,t){let n=ki(r),s=ze(n)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},vi(n,s)}function bh(r){let e=xi(r),t=ki(r),n=ze(t),s=ze(e);if(s?.env){let i=n?.snapshot||{};for(let o of ph){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{uh(e,{force:!0})}catch{}else vi(e,s)}try{uh(t,{force:!0})}catch{}}async function gk(){let r=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await pt()).filter(t=>t.provider==="openrouter"&&!Ac(t.name)).map(t=>({id:t.name,label:t.friendlyName||t.name}))}catch(t){console.error("[switcher] model list failed",be(t))}return{hasKey:r,models:e}}async function yk(){if(Zt&&Ae)return{active:!0,managed:!0,model:Ae,port:gt,provider:yt,routedModel:un,caching:fn,reasoning:dn,externalBaseUrl:null};let r=ze(xi(G))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:dn,externalBaseUrl:r.ANTHROPIC_BASE_URL||null}}async function wh(r,e){let t=await dk();return Ae=r,yt=e,hk(G,t),t}async function bk({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(Ac(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 wh(r,Tc[r]??null),un=null,fn="unknown",mk(G,r,yt)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${be(e)}`}}return{ok:!0}}async function wk({level:r}){return r!=null&&(!Number.isInteger(r)||r<0||r>=Sc.length)?{ok:!1,error:`reasoning level must be 0\u2013${Sc.length-1} or null`}:(dn=r,{ok:!0,level:r})}async function vk(){return bh(G),Ae=null,yt=null,un=null,fn="unknown",{ok:!0}}async function Sk({key:r}){let e=(r||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=G,n=Si(t,".env"),s="";try{s=kc(n,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))fh(n,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
|
|
353
411
|
`)?`
|
|
354
|
-
`:"";
|
|
355
|
-
`)}}catch(i){return{ok:!1,error:be(i)}}return process.env.OPENROUTER_API_KEY=e,lh(t,[".env"],"# secrets"),{ok:!0}}function fk(){if(!(!Zt&&!Ae)){try{ph(G)}catch{}rk()}}function dk(r,e){return mh.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 pk(r){if(mh.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 hk(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=vc(e?.cache_read_input_tokens)||vc(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 mk({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(kc(r))return{ok:!1,error:"Anthropic model \u2014 not offered or probed via OpenRouter"};let t=Date.now(),n=Array(350).fill("Caching probe filler sentence; its only purpose is to exceed the prompt-cache minimum token threshold.").join(" "),s={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":"2023-06-01"},i={model:r,max_tokens:8,system:[{type:"text",text:n,cache_control:{type:"ephemeral"}}],messages:[{role:"user",content:"Reply with exactly: ok"}]},o=async a=>{let c=new AbortController,l=setTimeout(()=>c.abort(),2e4);try{let d=JSON.stringify(a?{...i,provider:uh(a)}:i),u=await fetch(xc,{method:"POST",signal:c.signal,headers:s,body:d}),f=await u.json().catch(()=>({}));return{r:u,j:f}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let x=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:dk(a.status,x),restriction:pk(x)}}let l=typeof c?.provider=="string"?c.provider:void 0,d=c?.content?.find?.(x=>x.type==="text")?.text??c?.content?.[0]?.text??"ok",u=vc(c?.usage?.cache_creation_input_tokens),{r:f,j:p}=await o(l),{works:m,read:h,note:y}=hk(f.ok,p?.usage,l);return m===!0&&l&&(Ec[r]=l,Ae===r&&(yt=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:l,sample:String(d).trim().slice(0,60),cache:{works:m,created:u,read:h,note:y}}}catch(a){let c=be(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var Kx,xc,Wx,Vx,ch,Hx,wc,Si,xi,bi,kc,Zt,gt,Ae,yt,ln,un,fn,Ec,vc,uh,mh,gh=C(()=>{gc();di();Kx="https://openrouter.ai/api",xc=`${Kx}/v1/messages`,Wx="typebulb-proxy-managed",Vx="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.",ch=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],Hx=5e3,wc=["low","medium","high"],Si=r=>vi(r,".claude","settings.local.json"),xi=r=>vi(r,".claude",".cc-switcher.json"),bi=r=>`http://127.0.0.1:${r}`;kc=r=>/^anthropic\//i.test(r)||/claude/i.test(r),Zt=null,gt=null,Ae=null,yt=null,ln=null,un="unknown",fn=1,Ec={},vc=r=>typeof r=="number"?r:0,uh=r=>({order:[r],allow_fallbacks:!1});mh=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=ze(xi(G)),t=e?.active?.model;if(!t)return;let s=(ze(Si(G))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await hh(t,e.active.provider??Ec[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${bi(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",be(e))}})()});var bh={};Pc(bh,{attach:()=>xk,blockToMarkdown:()=>Ys,breakout:()=>zp,capText:()=>ke,cleanUserText:()=>Ye,clearSwitchModel:()=>lk,displayName:()=>gk,info:()=>yk,isHiddenTurn:()=>nn,launchBulb:()=>th,listBreakouts:()=>Qp,listBulbFiles:()=>Zp,listSessions:()=>vk,listSwitchModels:()=>ik,logEmbedStatus:()=>wk,openFile:()=>Gp,poll:()=>bk,predictTrustOf:()=>rh,probeModel:()=>mk,readBulbLog:()=>sh,saveOpenRouterKey:()=>uk,searchBulbs:()=>eh,searchSessions:()=>Sk,setBulbTrust:()=>nh,setReasoning:()=>ck,setSwitchModel:()=>ak,shutdownSwitcher:()=>fk,stopBreakout:()=>Xp,switchState:()=>ok});var yh,gk,yk,bk,wk,vk,Sk,xk,wh=C(()=>{uc();Gs();bc();gh();Gs();Ws();yh=new Wt,gk=yh.displayName,{info:yk,poll:bk,logEmbedStatus:wk,listSessions:vk,searchSessions:Sk,attach:xk}=mi(yh)});var Sh={};Pc(Sh,{attach:()=>Ck,breakout:()=>zp,displayName:()=>kk,info:()=>Ek,launchBulb:()=>th,listBreakouts:()=>Qp,listBulbFiles:()=>Zp,listSessions:()=>Pk,logEmbedStatus:()=>Tk,openFile:()=>Gp,poll:()=>Ak,predictTrustOf:()=>rh,readBulbLog:()=>sh,searchBulbs:()=>eh,searchSessions:()=>Ok,setBulbTrust:()=>nh,stopBreakout:()=>Xp});var vh,kk,Ek,Ak,Tk,Pk,Ok,Ck,xh=C(()=>{uc();Va();bc();vh=new Vt,kk=vh.displayName,{info:Ek,poll:Ak,logEmbedStatus:Tk,listSessions:Pk,searchSessions:Ok,attach:Ck}=mi(vh)});import*as Nh from"fs/promises";import*as _e from"path";import*as Cc from"fs/promises";import{existsSync as bt,readFileSync as jh}from"fs";import*as W from"path";import{pathToFileURL as Fh}from"url";import{resolve as Ai}from"resolve.exports";import{init as Rc,parse as Nc}from"es-module-lexer";function _c(r,e){let t=W.join(r,"package.json");try{return JSON.parse(jh(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var Ei=["browser","import","default"],Oc=["node","import","default"];function Ic(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 Lc(r){let{name:e,dir:t}=r;if(!bt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=_c(t,e),s=qh(n,e),i=W.resolve(t,s);if(!bt(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=Uh(n,t);return await Jh(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function qh(r,e){if(r.exports!==void 0){let n;try{n=Ai(r,".",{browser:!0,conditions:Ei})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Ei.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=Ti(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Ei.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 Uh(r,e){if(r.exports!==void 0)try{let n=Ai(r,".",{conditions:["types"]}),s=Ti(n);if(s){let i=W.resolve(e,s);if(bt(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=W.resolve(e,t);if(bt(n))return n}}function Ti(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function Jh(r,e,t){await Rc;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 Cc.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=Nc(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 d of c){if(d.d===-2)continue;let u=d.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let f=Kh(o,u,n);f&&!s.has(f)&&i.push(f);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${u}'`)}}}}function Kh(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)&&bt(o))return o}function Wh(r,e,t){let n=_c(r,e),s;if(n.exports!==void 0)try{s=Ti(Ai(n,t,{conditions:Oc}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${Oc.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(!bt(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return Fh(i).href}async function $c(r,e){await Rc;let t;try{[t]=Nc(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=Wh(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var Vh=5e3;function Mc(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 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=Vh;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=Ic(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 Dc(){console.log(`
|
|
412
|
+
`:"";dh(n,i+`OPENROUTER_API_KEY=${e}
|
|
413
|
+
`)}}catch(i){return{ok:!1,error:be(i)}}return process.env.OPENROUTER_API_KEY=e,hh(t,[".env"],"# secrets"),{ok:!0}}function xk(){if(!(!Zt&&!Ae)){try{bh(G)}catch{}pk()}}function kk(r,e){return vh.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 Ek(r){if(vh.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 Ak(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=xc(e?.cache_read_input_tokens)||xc(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 Tk({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(Ac(r))return{ok:!1,error:"Anthropic model \u2014 not offered or probed via OpenRouter"};let t=Date.now(),n=Array(350).fill("Caching probe filler sentence; its only purpose is to exceed the prompt-cache minimum token threshold.").join(" "),s={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":"2023-06-01"},i={model:r,max_tokens:8,system:[{type:"text",text:n,cache_control:{type:"ephemeral"}}],messages:[{role:"user",content:"Reply with exactly: ok"}]},o=async a=>{let c=new AbortController,l=setTimeout(()=>c.abort(),2e4);try{let d=JSON.stringify(a?{...i,provider:mh(a)}:i),u=await fetch(Ec,{method:"POST",signal:c.signal,headers:s,body:d}),f=await u.json().catch(()=>({}));return{r:u,j:f}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let x=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:kk(a.status,x),restriction:Ek(x)}}let l=typeof c?.provider=="string"?c.provider:void 0,d=c?.content?.find?.(x=>x.type==="text")?.text??c?.content?.[0]?.text??"ok",u=xc(c?.usage?.cache_creation_input_tokens),{r:f,j:p}=await o(l),{works:m,read:h,note:y}=Ak(f.ok,p?.usage,l);return m===!0&&l&&(Tc[r]=l,Ae===r&&(yt=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:l,sample:String(d).trim().slice(0,60),cache:{works:m,created:u,read:h,note:y}}}catch(a){let c=be(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var tk,Ec,rk,nk,ph,sk,Sc,xi,ki,wi,Ac,Zt,gt,Ae,yt,un,fn,dn,Tc,xc,mh,vh,Sh=C(()=>{bc();pi();tk="https://openrouter.ai/api",Ec=`${tk}/v1/messages`,rk="typebulb-proxy-managed",nk="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.",ph=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],sk=5e3,Sc=["low","medium","high"],xi=r=>Si(r,".claude","settings.local.json"),ki=r=>Si(r,".claude",".cc-switcher.json"),wi=r=>`http://127.0.0.1:${r}`;Ac=r=>/^anthropic\//i.test(r)||/claude/i.test(r),Zt=null,gt=null,Ae=null,yt=null,un=null,fn="unknown",dn=1,Tc={},xc=r=>typeof r=="number"?r:0,mh=r=>({order:[r],allow_fallbacks:!1});vh=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=ze(ki(G)),t=e?.active?.model;if(!t)return;let s=(ze(xi(G))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await wh(t,e.active.provider??Tc[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${wi(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",be(e))}})()});var kh={};Cc(kh,{attach:()=>Ik,blockToMarkdown:()=>Gs,breakout:()=>th,capText:()=>ke,cleanUserText:()=>Ye,clearSwitchModel:()=>vk,displayName:()=>Pk,info:()=>Ok,isHiddenTurn:()=>nn,launchBulb:()=>oh,listBreakouts:()=>rh,listBulbFiles:()=>sh,listSessions:()=>Nk,listSwitchModels:()=>gk,logEmbedStatus:()=>Rk,openFile:()=>eh,poll:()=>Ck,predictTrustOf:()=>ah,probeModel:()=>Tk,readBulbLog:()=>lh,saveOpenRouterKey:()=>Sk,searchBulbs:()=>ih,searchSessions:()=>_k,setBulbTrust:()=>ch,setReasoning:()=>wk,setSwitchModel:()=>bk,shutdownSwitcher:()=>xk,stopBreakout:()=>nh,switchState:()=>yk});var xh,Pk,Ok,Ck,Rk,Nk,_k,Ik,Eh=C(()=>{dc();zs();vc();Sh();zs();Hs();xh=new Wt,Pk=xh.displayName,{info:Ok,poll:Ck,logEmbedStatus:Rk,listSessions:Nk,searchSessions:_k,attach:Ik}=gi(xh)});var Th={};Cc(Th,{attach:()=>Fk,breakout:()=>th,displayName:()=>Lk,info:()=>$k,launchBulb:()=>oh,listBreakouts:()=>rh,listBulbFiles:()=>sh,listSessions:()=>Bk,logEmbedStatus:()=>Dk,openFile:()=>eh,poll:()=>Mk,predictTrustOf:()=>ah,readBulbLog:()=>lh,searchBulbs:()=>ih,searchSessions:()=>jk,setBulbTrust:()=>ch,stopBreakout:()=>nh});var Ah,Lk,$k,Mk,Dk,Bk,jk,Fk,Ph=C(()=>{dc();Va();vc();Ah=new Ht,Lk=Ah.displayName,{info:$k,poll:Mk,logEmbedStatus:Dk,listSessions:Bk,searchSessions:jk,attach:Fk}=gi(Ah)});import*as Mh from"fs/promises";import*as _e from"path";import*as Nc from"fs/promises";import{existsSync as bt,readFileSync as Kh}from"fs";import*as W from"path";import{pathToFileURL as Wh}from"url";import{resolve as Ti}from"resolve.exports";import{init as _c,parse as Ic}from"es-module-lexer";function Lc(r,e){let t=W.join(r,"package.json");try{return JSON.parse(Kh(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var Ai=["browser","import","default"],Rc=["node","import","default"];function $c(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 Mc(r){let{name:e,dir:t}=r;if(!bt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=Lc(t,e),s=Hh(n,e),i=W.resolve(t,s);if(!bt(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=Vh(n,t);return await Yh(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function Hh(r,e){if(r.exports!==void 0){let n;try{n=Ti(r,".",{browser:!0,conditions:Ai})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Ai.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=Pi(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Ai.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 Vh(r,e){if(r.exports!==void 0)try{let n=Ti(r,".",{conditions:["types"]}),s=Pi(n);if(s){let i=W.resolve(e,s);if(bt(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=W.resolve(e,t);if(bt(n))return n}}function Pi(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function Yh(r,e,t){await _c;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 Nc.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=Ic(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 d of c){if(d.d===-2)continue;let u=d.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let f=Gh(o,u,n);f&&!s.has(f)&&i.push(f);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${u}'`)}}}}function Gh(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)&&bt(o))return o}function zh(r,e,t){let n=Lc(r,e),s;if(n.exports!==void 0)try{s=Pi(Ti(n,t,{conditions:Rc}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${Rc.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(!bt(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return Wh(i).href}async function Dc(r,e){await _c;let t;try{[t]=Ic(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=zh(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var Qh=5e3;function Bc(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=Qh;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=$c(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 jc(){console.log(`
|
|
356
414
|
typebulb - Local bulb runner for Typebulb
|
|
357
415
|
|
|
358
416
|
Usage:
|
|
@@ -411,9 +469,10 @@ Options:
|
|
|
411
469
|
--clear Empty the target server's log instead of
|
|
412
470
|
printing it, for a clean run (logs)
|
|
413
471
|
-n, --lines <n> Print only the last n lines (logs)
|
|
414
|
-
--match <substring> Only lines containing this
|
|
415
|
-
|
|
416
|
-
|
|
472
|
+
--match <substring> Only lines containing this literal substring end
|
|
473
|
+
the wait \u2014 not a regex (wait)
|
|
474
|
+
--timeout <sec> Give up waiting after this long; exit 2 (wait;
|
|
475
|
+
bulb default 1800, mirror/embed capped at 30)
|
|
417
476
|
--wait[=ms] For 'send': if no page is connected yet (e.g. the
|
|
418
477
|
page is mid hot-reload), retry the push for up to
|
|
419
478
|
ms (default 5000) before reporting. Use it right
|
|
@@ -480,10 +539,10 @@ Examples:
|
|
|
480
539
|
typebulb my-editor.bulb.md
|
|
481
540
|
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
482
541
|
typebulb .
|
|
483
|
-
`)}
|
|
542
|
+
`)}ya();import*as He from"fs/promises";import*as _s from"path";import{pathToFileURL as Ev}from"url";import{transform as Dw}from"sucrase";function ba(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=Dw(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}ms();function Uw(r){return r.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
484
543
|
`)[0]}`).join(`
|
|
485
|
-
`)}function
|
|
486
|
-
${Dw(t)}`)}var $r="https://esm.sh",Mr="https://cdn.jsdelivr.net/npm/",ba="https://data.jsdelivr.com/v1/package/npm/";function Zf(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var R=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=_t(t??s.version),this.subpath=_t(n??s.subpath)}static parse(e){let t=Zf(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=ed(t[1]??""),a=_t(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=ed(t[0]),o=_t(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($r).host,s=new URL(Mr).host;if(t.host===n){let i=Zf(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}}static versionFromUrl(e){return r.fromUrl(e)?.version}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:_t(e),subpath:this.subpath})}withPreferredVersion(e,t){let n=e||t;return n?this.withVersion(n):this}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},_t=r=>r&&r.length?r:void 0,ed=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),_t(r.slice(e+1))]};async function ne(r){try{return await r()}catch{return}}var Dr=class{constructor(e,t){this.cache=e,this.http=t,this.esmHost=$r,this.jsDelivrBase=Mr,this.jsDelivrMeta=ba,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}normalizeRelative(e){let t=e||"";return t.startsWith("./")?t.slice(2):t.replace(/^\/+/,"")}ensureLeadingDotSlash(e){return e.startsWith("./")?e:`./${e}`}baseDir(e){let t=typeof e=="string"?new R(e):e;return`${this.jsDelivrBase}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(this.normalizeRelative(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(",")),`${this.esmHost}/${e}?${o.toString()}`}async pinEsmUrl(e,t="es2022"){let n=this.buildEsmUrl(e,{target:t}),s=await ne(()=>this.http.head(n));return s?.ok?s.url||n:void 0}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),`${this.esmHost}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await ne(()=>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 ne(()=>this.http.getJson(`${this.jsDelivrMeta}${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=R.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:d,peerDependencies:u,peerDependenciesMeta:f}=n;return{name:e,version:t,dependencies:d,peerDependencies:u,peerDependenciesMeta:f}}let s=this.packageJson(new R(`${e}@${t}`)),i=await ne(()=>this.http.getJson(s));if(!i)return;let o=d=>d&&Object.keys(d).length?d: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 td=r=>r.startsWith("@types/"),Br=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!td(e)),wa=r=>Object.keys(r?.dependencies||{}).filter(e=>!td(e)),Bw=r=>Br(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),jr=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 Bw(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=>Br(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:Br(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var Fr=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}selectVersionFromIndex(e,t,n){return this.semver.selectBestVersion(e,{range:t,distTags:n})}async learnExactVersion(e){let t=await ne(()=>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=await ne(()=>this.cdn.fetchVersionsIndex(e));if(s?.versions?.length){let o=this.selectVersionFromIndex(s.versions,t,s.distTags);if(o){if(this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o}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 ne(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=this.selectVersionFromIndex(a.versions,t,a.distTags);if(c&&this.semver.isExactVersion(c))return await this.cache.setPinnedExact(e,t,c),c}}}let i=await this.cdn.resolveExactVersion(`${e}@${t}`);if(i&&this.semver.isExactVersion(i))return await this.cache.setPinnedExact(e,t,i),i}async effectivePackage(e,t){let n=new R(e),s=n.root(),i=t[s],o=i?await ne(()=>this.cache.getPinnedExact(s,i))??await ne(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as jw,parse as Fw}from"es-module-lexer";var It=class r{constructor(e,t,n,s){this.version=e,this.cdn=t,this.peer=n,this.cache=s}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))R.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{R.isBare(s)&&t.add(s)};try{await jw;let[s]=Fw(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(R.rootOf(u))),i=[...new Set(s.map(R.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)),d=this.buildEntries([...s,...l.map(u=>u.name)],a,c,t);return{importMap:{imports:Object.fromEntries(d)},prefetchUrls:d.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=n?`${e}@${n}`:e,i=await this.version.resolveExactForRoot(e,n);if(!i){let o=await ne(()=>this.cdn.pinEsmUrl(s));if(!o)throw new Error(`Cannot resolve ${s}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);i=R.versionFromUrl(o),i&&n&&await ne(()=>this.cache.setPinnedExact(e,n,i))}if(!i)throw new Error(`Cannot resolve ${s}: no concrete version found.`);return i}buildEntries(e,t,n,s){let i=new Map(t.map(m=>[m.name,m])),o=m=>{let h=i.get(R.rootOf(m));return new R(m).withPreferredVersion(h.version,s[h.name]).format()},a=new Set([...n.entries()].filter(([,m])=>m.isPeerRoot||m.isSharedDep).map(([m])=>m)),c=new Set(e.filter(m=>m!==R.rootOf(m)).map(R.rootOf)),l=[],d=new Set,u=new Set(e.filter(m=>m===R.rootOf(m))),f=new Set;for(let m of e){let h=R.rootOf(m),y=i.get(h),{isPeerRoot:x,hasPeers:A,isSharedDep:g}=n.get(h),b=c.has(h),v=m!==h,P=!(x||g)&&(b||!A),k=this.singletonDepsOf(y,a),L=v&&u.has(h);L&&f.add(h);let Q=L?[...k,h]:k.length?k:void 0;l.push([m,this.cdn.buildEsmUrl(o(m),{bundle:P,external:Q})]),d.add(m)}let p=new Set([...a,...f]);for(let m of p)i.has(m)&&(d.has(m)||l.push([m,this.cdn.buildEsmUrl(o(m),{})]),l.push([`${m}/`,`${this.cdn.esmHost}/${o(m)}/`]));return l}singletonDepsOf(e,t){return[...new Set([...Br(e.meta),...wa(e.meta)])].filter(n=>t.has(n))}};It.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as rd,satisfies as qw,maxSatisfying as va,major as Uw,prerelease as Jw,rsort as Kw,valid as Ww}from"semver";var ms=class{cmp(e,t){return e===t?0:rd(e,t)?1:rd(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!qw(t,e,{includePrerelease:!0})}pickMaxSatisfying(e,t){if(!e?.length)return;let n=va(e,t,{includePrerelease:!0});return n===null?void 0:n}pickLatest(e){return e?.length?Kw(e)[0]:void 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=va(e,n,{includePrerelease:!1});if(a)return a}return va(e,n,{includePrerelease:!0})??void 0}majorOf(e){return Uw(e)}isPrerelease(e){return Jw(e)!==null}isExactVersion(e){return Ww(e)!==null}},ot=new ms;function nd(r,e){let t=new Dr(r,e),n=new jr(t),s=new Fr(r,t,ot);return{packageService:new It(s,t,n,r),versionResolver:s,cdnClient:t,peerResolver:n}}import*as vd from"fs/promises";import*as he from"path";var Sa=[{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"}],xa=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];var id=`
|
|
544
|
+
`)}function ed(r,e){let t=Lr(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
545
|
+
${Uw(t)}`)}var $r="https://esm.sh",Mr="https://cdn.jsdelivr.net/npm/",wa="https://data.jsdelivr.com/v1/package/npm/";function td(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var R=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=_t(t??s.version),this.subpath=_t(n??s.subpath)}static parse(e){let t=td(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=rd(t[1]??""),a=_t(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=rd(t[0]),o=_t(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($r).host,s=new URL(Mr).host;if(t.host===n){let i=td(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}}static versionFromUrl(e){return r.fromUrl(e)?.version}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:_t(e),subpath:this.subpath})}withPreferredVersion(e,t){let n=e||t;return n?this.withVersion(n):this}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},_t=r=>r&&r.length?r:void 0,rd=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),_t(r.slice(e+1))]};async function ne(r){try{return await r()}catch{return}}var Dr=class{constructor(e,t){this.cache=e,this.http=t,this.esmHost=$r,this.jsDelivrBase=Mr,this.jsDelivrMeta=wa,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}normalizeRelative(e){let t=e||"";return t.startsWith("./")?t.slice(2):t.replace(/^\/+/,"")}ensureLeadingDotSlash(e){return e.startsWith("./")?e:`./${e}`}baseDir(e){let t=typeof e=="string"?new R(e):e;return`${this.jsDelivrBase}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(this.normalizeRelative(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(",")),`${this.esmHost}/${e}?${o.toString()}`}async pinEsmUrl(e,t="es2022"){let n=this.buildEsmUrl(e,{target:t}),s=await ne(()=>this.http.head(n));return s?.ok?s.url||n:void 0}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),`${this.esmHost}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await ne(()=>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 ne(()=>this.http.getJson(`${this.jsDelivrMeta}${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=R.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:d,peerDependencies:u,peerDependenciesMeta:f}=n;return{name:e,version:t,dependencies:d,peerDependencies:u,peerDependenciesMeta:f}}let s=this.packageJson(new R(`${e}@${t}`)),i=await ne(()=>this.http.getJson(s));if(!i)return;let o=d=>d&&Object.keys(d).length?d: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 nd=r=>r.startsWith("@types/"),Br=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!nd(e)),va=r=>Object.keys(r?.dependencies||{}).filter(e=>!nd(e)),Jw=r=>Br(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),jr=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 Jw(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=>Br(i.meta))),n=new Map;for(let i of e)for(let o of va(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:Br(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var Fr=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}selectVersionFromIndex(e,t,n){return this.semver.selectBestVersion(e,{range:t,distTags:n})}async learnExactVersion(e){let t=await ne(()=>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=await ne(()=>this.cdn.fetchVersionsIndex(e));if(s?.versions?.length){let o=this.selectVersionFromIndex(s.versions,t,s.distTags);if(o){if(this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o}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 ne(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=this.selectVersionFromIndex(a.versions,t,a.distTags);if(c&&this.semver.isExactVersion(c))return await this.cache.setPinnedExact(e,t,c),c}}}let i=await this.cdn.resolveExactVersion(`${e}@${t}`);if(i&&this.semver.isExactVersion(i))return await this.cache.setPinnedExact(e,t,i),i}async effectivePackage(e,t){let n=new R(e),s=n.root(),i=t[s],o=i?await ne(()=>this.cache.getPinnedExact(s,i))??await ne(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as Kw,parse as Ww}from"es-module-lexer";var It=class r{constructor(e,t,n,s){this.version=e,this.cdn=t,this.peer=n,this.cache=s}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))R.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{R.isBare(s)&&t.add(s)};try{await Kw;let[s]=Ww(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(R.rootOf(u))),i=[...new Set(s.map(R.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)),d=this.buildEntries([...s,...l.map(u=>u.name)],a,c,t);return{importMap:{imports:Object.fromEntries(d)},prefetchUrls:d.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=n?`${e}@${n}`:e,i=await this.version.resolveExactForRoot(e,n);if(!i){let o=await ne(()=>this.cdn.pinEsmUrl(s));if(!o)throw new Error(`Cannot resolve ${s}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);i=R.versionFromUrl(o),i&&n&&await ne(()=>this.cache.setPinnedExact(e,n,i))}if(!i)throw new Error(`Cannot resolve ${s}: no concrete version found.`);return i}buildEntries(e,t,n,s){let i=new Map(t.map(m=>[m.name,m])),o=m=>{let h=i.get(R.rootOf(m));return new R(m).withPreferredVersion(h.version,s[h.name]).format()},a=new Set([...n.entries()].filter(([,m])=>m.isPeerRoot||m.isSharedDep).map(([m])=>m)),c=new Set(e.filter(m=>m!==R.rootOf(m)).map(R.rootOf)),l=[],d=new Set,u=new Set(e.filter(m=>m===R.rootOf(m))),f=new Set;for(let m of e){let h=R.rootOf(m),y=i.get(h),{isPeerRoot:x,hasPeers:k,isSharedDep:g}=n.get(h),b=c.has(h),v=m!==h,P=!(x||g)&&(b||!k),E=this.singletonDepsOf(y,a),L=v&&u.has(h);L&&f.add(h);let Q=L?[...E,h]:E.length?E:void 0;l.push([m,this.cdn.buildEsmUrl(o(m),{bundle:P,external:Q})]),d.add(m)}let p=new Set([...a,...f]);for(let m of p)i.has(m)&&(d.has(m)||l.push([m,this.cdn.buildEsmUrl(o(m),{})]),l.push([`${m}/`,`${this.cdn.esmHost}/${o(m)}/`]));return l}singletonDepsOf(e,t){return[...new Set([...Br(e.meta),...va(e.meta)])].filter(n=>t.has(n))}};It.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as sd,satisfies as Hw,maxSatisfying as Sa,major as Vw,prerelease as Yw,rsort as Gw,valid as zw}from"semver";var gs=class{cmp(e,t){return e===t?0:sd(e,t)?1:sd(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Hw(t,e,{includePrerelease:!0})}pickMaxSatisfying(e,t){if(!e?.length)return;let n=Sa(e,t,{includePrerelease:!0});return n===null?void 0:n}pickLatest(e){return e?.length?Gw(e)[0]:void 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=Sa(e,n,{includePrerelease:!1});if(a)return a}return Sa(e,n,{includePrerelease:!0})??void 0}majorOf(e){return Vw(e)}isPrerelease(e){return Yw(e)!==null}isExactVersion(e){return zw(e)!==null}},ot=new gs;function id(r,e){let t=new Dr(r,e),n=new jr(t),s=new Fr(r,t,ot);return{packageService:new It(s,t,n,r),versionResolver:s,cdnClient:t,peerResolver:n}}import*as xd from"fs/promises";import*as he from"path";var xa=[{name:"es5"},{name:"es2015.core"},{name:"es2015.collection"},{name:"es2015.promise"},{name:"es2015.iterable"},{name:"es2015.symbol"},{name:"es2015.symbol.wellknown"},{name:"es2015.generator"},{name:"es2015.proxy"},{name:"es2015.reflect"},{name:"es2016.array.include"},{name:"es2016.intl"},{name:"es2017.object"},{name:"es2017.string"},{name:"es2017.sharedmemory"},{name:"es2017.typedarrays"},{name:"es2017.date"},{name:"es2017.intl"},{name:"es2018.asynciterable"},{name:"es2018.asyncgenerator"},{name:"es2018.promise"},{name:"es2018.regexp"},{name:"es2018.intl"},{name:"es2019.array"},{name:"es2019.object"},{name:"es2019.string"},{name:"es2019.symbol"},{name:"es2019.intl"},{name:"es2020.bigint"},{name:"es2020.promise"},{name:"es2020.string"},{name:"es2020.sharedmemory"},{name:"es2020.date"},{name:"es2020.number"},{name:"es2020.symbol.wellknown"},{name:"es2020.intl"},{name:"es2021.promise"},{name:"es2021.string"},{name:"es2021.weakref"},{name:"es2021.intl"},{name:"es2022.array"},{name:"es2022.object"},{name:"es2022.error"},{name:"es2022.string"},{name:"es2022.regexp"},{name:"es2022.intl"},{name:"es2023.array"},{name:"es2023.collection"},{name:"es2023.intl",since:"5.5"},{name:"es2024.arraybuffer",since:"5.5"},{name:"es2024.collection",since:"5.5"},{name:"es2024.object",since:"5.5"},{name:"es2024.promise",since:"5.5"},{name:"es2024.regexp",since:"5.5"},{name:"es2024.sharedmemory",since:"5.5"},{name:"es2024.string",since:"5.5"},{name:"esnext.array",since:"5.5"},{name:"esnext.collection"},{name:"esnext.decorators"},{name:"esnext.disposable"},{name:"esnext.error",since:"5.5"},{name:"esnext.float16",since:"5.5"},{name:"esnext.iterator",since:"5.5"},{name:"esnext.object"},{name:"esnext.promise"},{name:"esnext.sharedmemory",since:"5.5"},{name:"esnext.intl"}],ka=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];var ad=`
|
|
487
546
|
/**
|
|
488
547
|
* Get raw data chunk from the Data tab.
|
|
489
548
|
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
@@ -494,7 +553,7 @@ ${Dw(t)}`)}var $r="https://esm.sh",Mr="https://cdn.jsdelivr.net/npm/",ba="https:
|
|
|
494
553
|
* @param index - Chunk index (0-based)
|
|
495
554
|
* @throws If chunk is not valid JSON/JSON-ish
|
|
496
555
|
*/
|
|
497
|
-
json<T = unknown>(index: number): T;`,
|
|
556
|
+
json<T = unknown>(index: number): T;`,cd=`
|
|
498
557
|
/**
|
|
499
558
|
* Get the insight data produced by the inference layer.
|
|
500
559
|
*
|
|
@@ -503,7 +562,7 @@ ${Dw(t)}`)}var $r="https://esm.sh",Mr="https://cdn.jsdelivr.net/npm/",ba="https:
|
|
|
503
562
|
*
|
|
504
563
|
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
505
564
|
*/
|
|
506
|
-
insight<T = unknown>(): T | undefined;`,
|
|
565
|
+
insight<T = unknown>(): T | undefined;`,od=`options: {
|
|
507
566
|
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
508
567
|
system?: string;
|
|
509
568
|
/** Reasoning depth hint (0=min, 1=low, 2=med, 3=high). Mapped to provider-specific parameters (e.g. Anthropic adaptive thinking, OpenAI reasoning effort). Default: 0. */
|
|
@@ -514,12 +573,12 @@ ${Dw(t)}`)}var $r="https://esm.sh",Mr="https://cdn.jsdelivr.net/npm/",ba="https:
|
|
|
514
573
|
webSearch?: boolean;
|
|
515
574
|
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
516
575
|
signal?: AbortSignal;
|
|
517
|
-
}`,
|
|
576
|
+
}`,ld=`
|
|
518
577
|
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
519
578
|
type AiChunk =
|
|
520
579
|
| { kind: "text"; text: string }
|
|
521
580
|
| { kind: "reasoning"; text: string };
|
|
522
|
-
`,
|
|
581
|
+
`,ud=`
|
|
523
582
|
/**
|
|
524
583
|
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
525
584
|
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
@@ -528,7 +587,7 @@ type AiChunk =
|
|
|
528
587
|
* @throws On rate limit, network error, or provider error
|
|
529
588
|
*/
|
|
530
589
|
ai: {
|
|
531
|
-
(${
|
|
590
|
+
(${od}): Promise<{ text: string }>;
|
|
532
591
|
/**
|
|
533
592
|
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
534
593
|
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
@@ -542,8 +601,8 @@ type AiChunk =
|
|
|
542
601
|
* if (c.kind === "text") answer += c.text;
|
|
543
602
|
* }
|
|
544
603
|
*/
|
|
545
|
-
stream(${
|
|
546
|
-
};`,
|
|
604
|
+
stream(${od}): AsyncIterable<AiChunk>;
|
|
605
|
+
};`,fd=`
|
|
547
606
|
/**
|
|
548
607
|
* Returns AI models available to the current user.
|
|
549
608
|
* Models are filtered by the user's configured API keys.
|
|
@@ -558,7 +617,7 @@ type AiChunk =
|
|
|
558
617
|
friendlyName: string;
|
|
559
618
|
/** Provider display name, e.g. "Anthropic" */
|
|
560
619
|
providerName: string;
|
|
561
|
-
}>>;`,
|
|
620
|
+
}>>;`,Qw="\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;",dd=`
|
|
562
621
|
/**
|
|
563
622
|
* The mode this bulb is running in.
|
|
564
623
|
*
|
|
@@ -568,7 +627,7 @@ type AiChunk =
|
|
|
568
627
|
* - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
|
|
569
628
|
* client-only: AI, filesystem, and server RPC are unavailable)
|
|
570
629
|
*/
|
|
571
|
-
mode: 'local' | 'editor' | 'published' | 'embedded';`,
|
|
630
|
+
mode: 'local' | 'editor' | 'published' | 'embedded';`,pd=`
|
|
572
631
|
/**
|
|
573
632
|
* Local filesystem access (CLI only).
|
|
574
633
|
*
|
|
@@ -583,7 +642,7 @@ type AiChunk =
|
|
|
583
642
|
readBytes(path: string): Promise<Uint8Array>;
|
|
584
643
|
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
585
644
|
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
586
|
-
};`,
|
|
645
|
+
};`,Xw=`
|
|
587
646
|
/**
|
|
588
647
|
* Server-side function proxy. The built-in \`log\` prints to CLI stdout
|
|
589
648
|
* (falls back to console.log on web). On the server side, this object only
|
|
@@ -591,7 +650,7 @@ type AiChunk =
|
|
|
591
650
|
*/
|
|
592
651
|
server: {
|
|
593
652
|
log(...args: any[]): Promise<void>;
|
|
594
|
-
};`,
|
|
653
|
+
};`,Zw=`
|
|
595
654
|
/**
|
|
596
655
|
* Async value inspector for tensor-like objects.
|
|
597
656
|
*
|
|
@@ -658,7 +717,7 @@ type AiChunk =
|
|
|
658
717
|
*
|
|
659
718
|
* @returns The full canonical URL
|
|
660
719
|
*/
|
|
661
|
-
url(): Promise<string>;`,
|
|
720
|
+
url(): Promise<string>;`,ev=`
|
|
662
721
|
/**
|
|
663
722
|
* Subscribe to a value pushed from the terminal via \`typebulb send <file> [message]\`.
|
|
664
723
|
*
|
|
@@ -673,23 +732,23 @@ type AiChunk =
|
|
|
673
732
|
* @param handler - Called with each pushed message.
|
|
674
733
|
* @returns An unsubscribe function.
|
|
675
734
|
*/
|
|
676
|
-
onMessage(handler: (message: any) => void): () => void;`,
|
|
735
|
+
onMessage(handler: (message: any) => void): () => void;`,tv="\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>>;",Ea=`${ld}
|
|
677
736
|
/**
|
|
678
737
|
* Typebulb utilities namespace.
|
|
679
738
|
* Type \`tb.\` to discover available helpers.
|
|
680
739
|
*/
|
|
681
|
-
declare const tb: {${
|
|
740
|
+
declare const tb: {${ad}${Zw}${cd}${tv}${ev}${ud}${pd}${fd}${Qw}${dd}
|
|
682
741
|
};
|
|
683
|
-
`,
|
|
742
|
+
`,Aa=`${ld}
|
|
684
743
|
/**
|
|
685
744
|
* Typebulb utilities namespace (server-side).
|
|
686
745
|
* Type \`tb.\` to discover available helpers.
|
|
687
746
|
*/
|
|
688
|
-
declare const tb: {${
|
|
747
|
+
declare const tb: {${ad}${cd}${ud}${pd}${Xw}${fd}${dd}
|
|
689
748
|
};
|
|
690
|
-
`;var at=class{constructor(e){this.store=e}async isNegative(e){let t=await gs(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await gs(()=>this.store.get(e)))?.attempts||0)+1;await gs(()=>this.store.set(e,{until:Date.now()+Qw(n),attempts:n}))}async clearNegative(e){await gs(()=>this.store.delete(e))}};function Qw(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}async function gs(r){try{return await r()}catch{return}}import nv from"p-limit";import{resolve as dd}from"resolve.exports";var Lt=class{constructor(e){this.fetchDts=e}fetchDtsText(e){return this.tryUrls([e])}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||/\.(d\.ts|d\.mts)(?:[?#].*)?$/i.test(n.url)||/[?&]dts(?:[&#]|$)/i.test(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)}};var Je={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},qr=["index.d.ts","index.d.mts"],Ur=/\.d\.(ts|mts)$/i;function Aa(r){if(Ur.test(r))return!0;try{return new URL(r,"file://").search.includes("dts")}catch{return r.includes("?")&&r.includes("dts")}}function $t(r){return[`${r}.d.ts`,`${r}.d.mts`]}async function Jr(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(Xw(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function Xw(r){return r===408||r===429||r>=500&&r<600}var Kr=class extends Lt{constructor(e,t){super(e),this.cdnClient=t}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new R({name:e,version:t})),s=await Jr(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new R({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=this.cdnClient.normalizeRelative(e.path);if(!s||s==="/"||s===".")return this.tryUntilSuccess([...qr],t);if(!Ur.test(s)){let i=await this.tryUntilSuccess(this.declarationCandidatesFor(s),t);if(i)return i}return t(s)}let n=this.declarationCandidatesFor(e.path);return this.tryUntilSuccess([...qr,...n],t)}toResolutionResult(e){return{kind:Ur.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(dd(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(dd(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=R.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 R(i).format(),a=new R({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=this.cdnClient.ensureLeadingDotSlash(t.subpath),f=this.resolveExportsPath(n,u);if(f){let m=await this.resolveFromSelected(this.toResolutionResult(f),c);if(m)return{...m,resolvedPkg:a}}let p=await this.tryUntilSuccess(this.declarationCandidatesFor(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 d=this.resolveExportsPath(n,".");if(d){let u=await this.resolveFromSelected(this.toResolutionResult(d),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=this.cdnClient.normalizeRelative(n),i=new URL(s,e).toString(),o=await this.fetchDtsText(i);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}declarationCandidatesFor(e){if(!e||e==="./"||e==="/")return[...qr];let t=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=$t(t),s=t.endsWith("/")?t:`${t}/`;return n.push(...$t(`${s}index`)),n}};import{gunzipSync as Zw}from"fflate";var Mt=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Jr(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=Zw(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(),d=o.slice(124,136),u=s.decode(d).trim().replace(/\0/g,""),f=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 m=n.slice(i,i+f);t.set(this.normalizeTarPath(l),s.decode(m))}i+=Math.ceil(f/512)*512}}catch{}return t}},ev=new Mt;var Wr=class extends Lt{constructor(e,t,n,s=new Mt){super(e),this.cdnClient=t,this.cache=n,this.tarballFetcher=s}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=ot.majorOf(n),o=e.filter(a=>ot.majorOf(a)===i);if(o.length)return o.sort((a,c)=>ot.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=[...$t(t),`${t}/index.d.ts`,`${t}/index.d.mts`];return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new R(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 R(t).format():t.name}}}async resolve(e){let t=R.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 Vr=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=new Set,n=(s,i)=>(t.add(s[i]),null);return this.matchAll(e,/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/,s=>n(s,2)),this.matchAll(e,/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/,s=>n(s,1)),Array.from(t)}matchAll(e,t,n){let s=[];try{let i=new RegExp(t.source,"g"),o;for(;o=i.exec(e);){let a=n(o);a!==null&&s.push(a)}}catch{}return s}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};var pd="file:///node_modules",Hr=class{constructor(){this.epoch=0,this.listeners=new Set}getEpoch(){return this.epoch}bumpEpoch(){this.epoch+=1;for(let e of this.listeners)try{e(this.epoch)}catch{}return this.epoch}onEpochChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${pd}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=tv(t);return`${pd}/${this.epochDir()}/${e}/${n}`}};function tv(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}import{LRUCache as rv}from"lru-cache";function Ta(r){let e=new rv({ttl:1e4,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s))return;let i=e.get(s);if(i&&Date.now()-i<1e4)return;let o=await r.getCachedFile(s);if(o)return{dts:o,url:s};let a=t.get(s);if(a)return a;let c=(async()=>{let l=await fetch(s,{cache:"no-store"});if(!l.ok){l.status===404&&(e.set(s,Date.now()),await r.recordNegative(s));return}let d=await l.text(),u=l.url||s;return await r.clearNegative(s),await r.setCachedFile(u,d),{dts:d,url:u}})();return t.set(s,c),await c.finally(()=>t.delete(s))}catch{return}}}var ys=class{constructor(e){this.inFlight=new Map,this.scanner=new Vr,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=Ta(e.cache),this.typescriptProvider=new Kr(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Wr(this.fetchDts,e.cdnClient,e.cache),this.virtualFs=new Hr}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()}capArray(e,t){return e.length<=t?e:e.slice(0,t)}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 trySubpathWithRootFallback(e,t){let n=new R(e);return n.subpath?this.fetchRootDts(n.name,t):void 0}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}subpathsMatch(e,t){return new R(e).subpath===new R(t).subpath}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)){try{await this.cache.setCachedFile(a.url,a.dts)}catch{}if(this.subpathsMatch(n,a.resolvedPkg||n)){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>Je.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.capArray(this.scanner.collectRelativeTypeRefs(e),Je.maxRelativeTypeRefs);for(let d of l)await this.tryRelativeRef(d,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=Aa(c)?[c]:this.typescriptProvider.declarationCandidatesFor(c);for(let d of l){let f=new URL(d,a).toString();if(o.has(f))return;let p=await this.fetchDts(f);if(p?.dts){let m=this.toVirtualPath(n,new URL(p.url),s);this.pushFileIfNew(i,m,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new R(e).name!==new R(t).name}ambientlyDeclares(e,t){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.capArray(this.scanner.collectBareModuleRefs(e),Je.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=nv(Je.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Je.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 d=this.capArray(this.scanner.collectBareModuleRefs(a.dts),Je.maxBareDeps).filter(u=>!i.has(u));for(let u of d)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=await this.fetchRootDts(e,t)??await this.trySubpathWithRootFallback(e,t);return s?this.buildDefFromContent(e,s,s.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,n,s){let{dts:i,url:o,resolvedPkg:a}=t,c=new R(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:d,packageRootUrl:u}=this.computeEntryPath(o,l),f=[{path:d,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,f,void 0,u);let m=f.map(A=>A.content).join(`
|
|
691
|
-
`);await this.prefetchBareDeps(m,l,f,p,s);let h=c.format(),y=e===h?[e]:[e,h],x=y.some(
|
|
692
|
-
`,"utf8")}async function
|
|
749
|
+
`;var at=class{constructor(e){this.store=e}async isNegative(e){let t=await ys(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await ys(()=>this.store.get(e)))?.attempts||0)+1;await ys(()=>this.store.set(e,{until:Date.now()+rv(n),attempts:n}))}async clearNegative(e){await ys(()=>this.store.delete(e))}};function rv(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}async function ys(r){try{return await r()}catch{return}}import cv from"p-limit";import{resolve as hd}from"resolve.exports";var Lt=class{constructor(e){this.fetchDts=e}fetchDtsText(e){return this.tryUrls([e])}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||/\.(d\.ts|d\.mts)(?:[?#].*)?$/i.test(n.url)||/[?&]dts(?:[&#]|$)/i.test(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)}};var Je={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},qr=["index.d.ts","index.d.mts"],Ur=/\.d\.(ts|mts)$/i;function Ta(r){if(Ur.test(r))return!0;try{return new URL(r,"file://").search.includes("dts")}catch{return r.includes("?")&&r.includes("dts")}}function $t(r){return[`${r}.d.ts`,`${r}.d.mts`]}async function Jr(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(nv(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function nv(r){return r===408||r===429||r>=500&&r<600}var Kr=class extends Lt{constructor(e,t){super(e),this.cdnClient=t}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new R({name:e,version:t})),s=await Jr(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new R({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=this.cdnClient.normalizeRelative(e.path);if(!s||s==="/"||s===".")return this.tryUntilSuccess([...qr],t);if(!Ur.test(s)){let i=await this.tryUntilSuccess(this.declarationCandidatesFor(s),t);if(i)return i}return t(s)}let n=this.declarationCandidatesFor(e.path);return this.tryUntilSuccess([...qr,...n],t)}toResolutionResult(e){return{kind:Ur.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(hd(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(hd(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=R.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 R(i).format(),a=new R({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=this.cdnClient.ensureLeadingDotSlash(t.subpath),f=this.resolveExportsPath(n,u);if(f){let m=await this.resolveFromSelected(this.toResolutionResult(f),c);if(m)return{...m,resolvedPkg:a}}let p=await this.tryUntilSuccess(this.declarationCandidatesFor(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 d=this.resolveExportsPath(n,".");if(d){let u=await this.resolveFromSelected(this.toResolutionResult(d),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=this.cdnClient.normalizeRelative(n),i=new URL(s,e).toString(),o=await this.fetchDtsText(i);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}declarationCandidatesFor(e){if(!e||e==="./"||e==="/")return[...qr];let t=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=$t(t),s=t.endsWith("/")?t:`${t}/`;return n.push(...$t(`${s}index`)),n}};import{gunzipSync as sv}from"fflate";var Mt=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Jr(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=sv(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(),d=o.slice(124,136),u=s.decode(d).trim().replace(/\0/g,""),f=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 m=n.slice(i,i+f);t.set(this.normalizeTarPath(l),s.decode(m))}i+=Math.ceil(f/512)*512}}catch{}return t}},iv=new Mt;var Wr=class extends Lt{constructor(e,t,n,s=new Mt){super(e),this.cdnClient=t,this.cache=n,this.tarballFetcher=s}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=ot.majorOf(n),o=e.filter(a=>ot.majorOf(a)===i);if(o.length)return o.sort((a,c)=>ot.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=[...$t(t),`${t}/index.d.ts`,`${t}/index.d.mts`];return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new R(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 R(t).format():t.name}}}async resolve(e){let t=R.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 Hr=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=new Set,n=(s,i)=>(t.add(s[i]),null);return this.matchAll(e,/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/,s=>n(s,2)),this.matchAll(e,/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/,s=>n(s,1)),Array.from(t)}matchAll(e,t,n){let s=[];try{let i=new RegExp(t.source,"g"),o;for(;o=i.exec(e);){let a=n(o);a!==null&&s.push(a)}}catch{}return s}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};var md="file:///node_modules",Vr=class{constructor(){this.epoch=0,this.listeners=new Set}getEpoch(){return this.epoch}bumpEpoch(){this.epoch+=1;for(let e of this.listeners)try{e(this.epoch)}catch{}return this.epoch}onEpochChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${md}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=ov(t);return`${md}/${this.epochDir()}/${e}/${n}`}};function ov(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}import{LRUCache as av}from"lru-cache";function Pa(r){let e=new av({ttl:1e4,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s))return;let i=e.get(s);if(i&&Date.now()-i<1e4)return;let o=await r.getCachedFile(s);if(o)return{dts:o,url:s};let a=t.get(s);if(a)return a;let c=(async()=>{let l=await fetch(s,{cache:"no-store"});if(!l.ok){l.status===404&&(e.set(s,Date.now()),await r.recordNegative(s));return}let d=await l.text(),u=l.url||s;return await r.clearNegative(s),await r.setCachedFile(u,d),{dts:d,url:u}})();return t.set(s,c),await c.finally(()=>t.delete(s))}catch{return}}}var bs=class{constructor(e){this.inFlight=new Map,this.scanner=new Hr,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=Pa(e.cache),this.typescriptProvider=new Kr(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Wr(this.fetchDts,e.cdnClient,e.cache),this.virtualFs=new Vr}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()}capArray(e,t){return e.length<=t?e:e.slice(0,t)}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 trySubpathWithRootFallback(e,t){let n=new R(e);return n.subpath?this.fetchRootDts(n.name,t):void 0}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}subpathsMatch(e,t){return new R(e).subpath===new R(t).subpath}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)){try{await this.cache.setCachedFile(a.url,a.dts)}catch{}if(this.subpathsMatch(n,a.resolvedPkg||n)){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>Je.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.capArray(this.scanner.collectRelativeTypeRefs(e),Je.maxRelativeTypeRefs);for(let d of l)await this.tryRelativeRef(d,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=Ta(c)?[c]:this.typescriptProvider.declarationCandidatesFor(c);for(let d of l){let f=new URL(d,a).toString();if(o.has(f))return;let p=await this.fetchDts(f);if(p?.dts){let m=this.toVirtualPath(n,new URL(p.url),s);this.pushFileIfNew(i,m,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new R(e).name!==new R(t).name}ambientlyDeclares(e,t){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.capArray(this.scanner.collectBareModuleRefs(e),Je.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=cv(Je.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,Je.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 d=this.capArray(this.scanner.collectBareModuleRefs(a.dts),Je.maxBareDeps).filter(u=>!i.has(u));for(let u of d)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=await this.fetchRootDts(e,t)??await this.trySubpathWithRootFallback(e,t);return s?this.buildDefFromContent(e,s,s.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,n,s){let{dts:i,url:o,resolvedPkg:a}=t,c=new R(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:d,packageRootUrl:u}=this.computeEntryPath(o,l),f=[{path:d,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,f,void 0,u);let m=f.map(k=>k.content).join(`
|
|
750
|
+
`);await this.prefetchBareDeps(m,l,f,p,s);let h=c.format(),y=e===h?[e]:[e,h],x=y.some(k=>this.ambientlyDeclares(i,k));return x?this.markFileAmbient(f,d):p.push(...y.map(k=>({module:k,path:d}))),{pkg:e,mainPath:d,files:f,shims:p,ambient:x}}};function Oa(r){return new bs(r)}import*as Se from"fs/promises";import*as Oe from"path";import*as bd from"os";import*as Ca from"fs/promises";import*as gd from"crypto";function pe(r){return gd.createHash("sha1").update(r).digest("hex")}async function ct(r){try{return JSON.parse(await Ca.readFile(r,"utf8"))}catch{return}}async function ws(r){try{return await Ca.readFile(r,"utf8")}catch{return}}var yd=1,Ke=Oe.join(bd.homedir(),".typebulb","cache"),Yr=Oe.join(Ke,"packages"),Gr=Oe.join(Ke,"proxy"),vs=Oe.join(Ke,"dts"),lv=Oe.join(Ke,"emit"),Ra;function q(){return Ra||(Ra=uv()),Ra}function Ss(r,e){return Oe.join(lv,pe(r),e)}async function uv(){await Se.mkdir(Ke,{recursive:!0});let r=Oe.join(Ke,"version.json");if((await fv(r))?.version===yd)return;let t=await Se.readdir(Ke).catch(()=>[]);await Promise.all(t.map(n=>Se.rm(Oe.join(Ke,n),{recursive:!0,force:!0}))),await Se.writeFile(r,JSON.stringify({version:yd})+`
|
|
751
|
+
`,"utf8")}async function fv(r){try{let e=await Se.readFile(r,"utf8");return JSON.parse(e)}catch{return}}import*as We from"fs/promises";import*as wd from"path";async function ce(r,e){await We.mkdir(wd.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await We.writeFile(t,e,"utf8"),await We.rename(t,r).catch(async n=>{throw await We.rm(t,{force:!0}).catch(()=>{}),n})}var Dt=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=ct(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 ce(this.filePath,JSON.stringify(Object.fromEntries(e)))}};var Na=he.join(Yr,"indexes"),vd=he.join(Yr,"pinned"),dv=he.join(Yr,"meta"),pv=he.join(Yr,"negative.json"),Bt=Symbol("missing"),ks=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new at(new Dt(pv));async getPinnedExact(e,t){let n=`${e}@${t}`,s=this.pinnedMem.get(n);if(s!==void 0)return s===Bt?void 0:s;await q();let i=await ws(he.join(vd,pe(n)+".txt"));return this.pinnedMem.set(n,i??Bt),i}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await q(),await ce(he.join(vd,pe(s)+".txt"),n)}async getIndex(e){let t=this.indexMem.get(e);if(t!==void 0)return t===Bt?void 0:t;await q();let n=await ct(he.join(Na,xs(e)+".json"));return this.indexMem.set(e,n??Bt),n}async setIndex(e,t,n){let s={versions:t,distTags:n,updatedAt:Date.now()};this.indexMem.set(e,s),await q(),await ce(he.join(Na,xs(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await xd.rm(he.join(Na,xs(e)+".json"),{force:!0})}async isNegative(e){return await q(),this.negativeCache.isNegative(e)}async recordNegative(e){await q(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,t){let n=`${e}@${t}`,s=this.metaMem.get(n);if(s!==void 0)return s===Bt?void 0:s;await q();let i=await ct(Sd(e,t));return this.metaMem.set(n,i??Bt),i}async setMeta(e,t,n,s,i){let o={dependencies:n,peerDependencies:s,peerDependenciesMeta:i,updatedAt:Date.now()};this.metaMem.set(`${e}@${t}`,o),await q(),await ce(Sd(e,t),JSON.stringify(o))}};function Sd(r,e){return he.join(dv,xs(r),encodeURIComponent(e)+".json")}function xs(r){return r.replace(/\//g,"__")}var kd={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 hv=new ks,{packageService:Es,versionResolver:Ed,cdnClient:Ad,peerResolver:yP}=id(hv,kd);var Td=`
|
|
693
752
|
(() => {
|
|
694
753
|
// Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
|
|
695
754
|
// bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
|
|
@@ -1023,11 +1082,11 @@ declare const tb: {${id}${od}${cd}${fd}${Hw}${ld}${ud}
|
|
|
1023
1082
|
};
|
|
1024
1083
|
}
|
|
1025
1084
|
})();
|
|
1026
|
-
`;function
|
|
1085
|
+
`;function As(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var Ts=` *, *::before, *::after { box-sizing: border-box; }
|
|
1027
1086
|
canvas { max-width: 100%; }
|
|
1028
1087
|
body { margin: 0; display: flow-root; font-family: system-ui, -apple-system, sans-serif; }
|
|
1029
1088
|
html[data-theme="dark"] { color-scheme: dark; }
|
|
1030
|
-
html[data-theme="light"] { color-scheme: light; }`;function
|
|
1089
|
+
html[data-theme="light"] { color-scheme: light; }`;function Ps(r,e){let t=n=>n.replace(/<\/script/gi,"<\\/script");return` <script>
|
|
1031
1090
|
(function() {
|
|
1032
1091
|
try {
|
|
1033
1092
|
var KEY = ${t(JSON.stringify("tb-theme:"+r))};
|
|
@@ -1062,19 +1121,19 @@ declare const tb: {${id}${od}${cd}${fd}${Hw}${ld}${ud}
|
|
|
1062
1121
|
});
|
|
1063
1122
|
} catch (e) {}
|
|
1064
1123
|
})();
|
|
1065
|
-
</script>`}function
|
|
1066
|
-
html, body { height: 100%; }`,f=m=>m.replace(/<\/script/gi,"<\\/script"),p={imports:
|
|
1124
|
+
</script>`}function Pd(r){let{name:e,code:t,css:n,html:s,data:i,insight:o,importMap:a,theme:c,embedded:l}=r,d=s.trim()||'<div id="app"></div>',u=l?"":`
|
|
1125
|
+
html, body { height: 100%; }`,f=m=>m.replace(/<\/script/gi,"<\\/script"),p={imports:gv(a.imports)};return`<!DOCTYPE html>
|
|
1067
1126
|
<html>
|
|
1068
1127
|
<head>
|
|
1069
1128
|
<meta charset="utf-8">
|
|
1070
1129
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1071
|
-
<title>${
|
|
1072
|
-
${
|
|
1130
|
+
<title>${As(e)} - typebulb</title>
|
|
1131
|
+
${Ps(e,c)}
|
|
1073
1132
|
<script type="importmap">
|
|
1074
1133
|
${JSON.stringify(p,null,2)}
|
|
1075
1134
|
</script>
|
|
1076
1135
|
<style>
|
|
1077
|
-
${
|
|
1136
|
+
${Ts}${u}
|
|
1078
1137
|
</style>
|
|
1079
1138
|
<style>
|
|
1080
1139
|
${n}
|
|
@@ -1087,17 +1146,17 @@ ${i.length>0?`<script>window.__TB_DATA__ = ${f(JSON.stringify(i))};</script>`:""
|
|
|
1087
1146
|
${o?`<script>window.__TB_INSIGHT__ = ${f(JSON.stringify(o))};</script>`:""}
|
|
1088
1147
|
|
|
1089
1148
|
<script>
|
|
1090
|
-
${
|
|
1149
|
+
${Td}
|
|
1091
1150
|
</script>
|
|
1092
1151
|
|
|
1093
|
-
${
|
|
1152
|
+
${mv}
|
|
1094
1153
|
|
|
1095
1154
|
<script type="module">
|
|
1096
1155
|
${f(t)}
|
|
1097
1156
|
globalThis.__tbEntryRan = true; /* load-failure backstop \u2014 see embedProtocol */
|
|
1098
1157
|
</script>
|
|
1099
1158
|
</body>
|
|
1100
|
-
</html>`}var
|
|
1159
|
+
</html>`}var mv=`<script>
|
|
1101
1160
|
(function () {
|
|
1102
1161
|
var framed = window.parent !== window;
|
|
1103
1162
|
var post = function (m) { try { parent.postMessage(m, '*'); } catch (e) {} }; /* framed only */
|
|
@@ -1193,53 +1252,53 @@ globalThis.__tbEntryRan = true; /* load-failure backstop \u2014 see embedProtoco
|
|
|
1193
1252
|
}
|
|
1194
1253
|
});
|
|
1195
1254
|
})();
|
|
1196
|
-
</script>`;function
|
|
1197
|
-
`,"utf8"),await ee.writeFile(X.join(e,"code.tsx"),r.code,"utf8"),await ee.writeFile(X.join(e,"tb.d.ts"),
|
|
1198
|
-
`,"utf8"),{dir:e}}function
|
|
1199
|
-
`))console.log(`${e} ${n}`);return r.length>0}function
|
|
1255
|
+
</script>`;function gv(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}import*as Cs from"fs/promises";import*as Os from"path";import{existsSync as Od,readFileSync as yv}from"fs";import{execFile as bv}from"child_process";import{promisify as wv}from"util";import{satisfies as vv}from"semver";var Sv=wv(bv);async function Rs(r,e,t){let s=r.map(o=>xv(o,t)).filter(o=>!kv(o,e));if(s.length===0)return;await Cs.mkdir(e,{recursive:!0});let i=Os.join(e,"package.json");Od(i)||await Cs.writeFile(i,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${s.join(", ")}`),await Sv("npm",["install","--no-audit","--no-fund",...s],{cwd:e,shell:!0})}function xv(r,e){if(!e||Rd(r))return r;let t=e[r];return t?`${r}@${t}`:r}function kv(r,e){let t=Os.join(e,"node_modules",Cd(r));if(!Od(t))return!1;let n=Rd(r);if(!n)return!0;try{let s=JSON.parse(yv(Os.join(t,"package.json"),"utf-8")).version;return vv(s,n)}catch{return!1}}function Ns(r){let e=new Set,t=/\bimport\s+(?:[\s\S]*?\s+from\s+)?['"]([^./][^'"]*)['"]/g,n;for(;n=t.exec(r);){let s=n[1];if(s.includes(":"))continue;let i=s.startsWith("@")?s.split("/").slice(0,2).join("/"):s.split("/")[0];e.add(i)}return[...e]}function Cd(r){if(r.startsWith("@")){let t=r.indexOf("/");if(t<0)return r;let n=r.indexOf("@",t+1);return n<0?r:r.slice(0,n)}let e=r.indexOf("@");return e<0?r:r.slice(0,e)}function Rd(r){let e=Cd(r);return r.length>e.length?r.slice(e.length+1):""}async function Nd(r){let t=(await He.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?_s.join(r,t):null}async function me(r){let e=await He.readFile(r,"utf-8"),t=Qe(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=hs(t);return{bulb:n,config:zc(n.config),warnings:Wc(e)}}async function zr(r,e,t,n){let s=ba(r,{serverOnly:!0});if(s.error)throw new Error(`Server compilation error: ${s.error}`);let i=s.code;t&&(i=await Dc(i,t));let o=_s.join(e,".typebulb");await He.mkdir(o,{recursive:!0});let a=Ns(i);a.length>0&&await Rs(a,o,n);let c=_s.join(o,"server.mjs");return await He.writeFile(c,i,"utf-8"),await import(`${Ev(c).href}?t=${Date.now()}`)}async function _a(r,e,t,n,s){let{bulb:i,config:o}=await me(r),a=ga(i.data);ed(i.code,o.dependencies??{});let c=ba(i.code,{jsxImportSource:o.ts?.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await Es.buildImportMap(c.code,o.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let d=Pd({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 zr(i.server,s,n,o.dependencies)),{html:d,bulb:i,serverExports:u}}Xr();import Iv from"open";async function Ft(r){await Iv(r)}var Ld=new Set(["claude","pi"]);function $d(r){return Ld.has(r)}function Zr(){return[...Ld]}import*as Ve from"path";import{spawn as Yv,execSync as Gv}from"child_process";import{createRequire as zv}from"module";import{existsSync as Qv}from"fs";import*as ee from"fs/promises";import*as X from"path";import*as qt from"path";var Lv=qt.join(vs,"pkg"),$v=qt.join(vs,"files"),Mv=qt.join(vs,"negative.json"),$s=class{pkgMem=new Map;fileMem=new Map;negativeCache=new at(new Dt(Mv));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await q();let t=await ct(Md(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 Ls(async()=>{await q(),await ce(Md(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await q();let t=await ws(Dd(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await Ls(async()=>{await q(),await ce(Dd(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await Ls(async()=>{await q(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return Ls(()=>this.negativeCache.clearNegative(e))}};async function Ls(r){try{await r()}catch{}}function Md(r){return qt.join(Lv,pe(r)+".json")}function Dd(r){return qt.join($v,pe(r)+".txt")}var Ma;function Dv(){return Ma||(Ma=Oa({cache:new $s,cdnClient:Ad,packageService:Es,versionResolver:Ed})),Ma}var Bd="file:///node_modules/";async function jd(r){let e=Ss(r.emitKey,"typecheck");await q(),await ee.rm(e,{recursive:!0,force:!0}),await ee.mkdir(e,{recursive:!0});let t=qv(r.jsxImportSource,r.dependencies),n=await Dv().resolve(r.code,r.dependencies,t),s=r.local?.name,i=s?n.filter(d=>d.pkg!==s):n,o=new Set;for(let d of i)for(let u of d.files){let f=Ms(u.path);if(!f||o.has(f))continue;o.add(f);let p=X.join(e,"node_modules",f);await ee.mkdir(X.dirname(p),{recursive:!0}),await ee.writeFile(p,u.content,"utf8")}let a={};for(let d of i)for(let u of d.shims){let f=Ms(u.path);f&&(a[u.module]=[`./node_modules/${f}`])}for(let d of i){if(d.ambient)continue;let u=Ms(d.mainPath);u&&(a[d.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let d of i)for(let u of d.files){if(!u.ambient)continue;let f=Ms(u.path);f&&c.add(`node_modules/${f}`)}if(r.local){delete a[r.local.name];let d=await Uv(r.local,e);d?a[r.local.name]=[`./node_modules/${r.local.name}/${d}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=Bv(r.jsxImportSource,a,[...c]);return await ee.writeFile(X.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1256
|
+
`,"utf8"),await ee.writeFile(X.join(e,"code.tsx"),r.code,"utf8"),await ee.writeFile(X.join(e,"tb.d.ts"),Ea,"utf8"),{dir:e}}function Bv(r,e,t=[]){return{compilerOptions:{target:"es2023",module:"esnext",moduleResolution:"bundler",lib:jv([...xa,...ka]),jsx:"react-jsx",jsxImportSource:r??"react",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0,paths:e},include:["code.tsx","tb.d.ts",...t]}}function jv(r){return r.filter(e=>!e.since).map(e=>Fv(e.name))}function Fv(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 qv(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function Ms(r){if(!r.startsWith(Bd))return;let e=r.slice(Bd.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function Uv(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 Jv(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 Jv(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 le from"fs/promises";import*as Re from"path";import{existsSync as Kv}from"fs";var Wv="^22";async function Fd(r){let e=Ss(r.emitKey,"typecheck-server");await q(),await le.rm(e,{recursive:!0,force:!0}),await le.mkdir(e,{recursive:!0});let t=Re.join(r.bulbDir,".typebulb"),n=Ns(r.server).filter(o=>o!==r.local?.name);await Rs([`@types/node@${Wv}`,...n],t,r.dependencies);let s=Re.join(t,"node_modules"),i=Re.join(e,"node_modules");return await Vv(s,i),await le.writeFile(Re.join(e,"server.ts"),r.server,"utf8"),await le.writeFile(Re.join(e,"tb.d.ts"),Aa,"utf8"),await le.writeFile(Re.join(e,"tsconfig.json"),JSON.stringify(Hv(r.local),null,2)+`
|
|
1257
|
+
`,"utf8"),{dir:e}}function Hv(r){let e={target:"es2023",module:"esnext",moduleResolution:"bundler",lib:["ES2023"],types:["node"],strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};if(r?.typesAbs){let t=i=>i.replace(/\\/g,"/"),n=t(Re.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 Vv(r,e){if(!Kv(r)){await le.mkdir(e,{recursive:!0});return}await le.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await le.symlink(r,e,t)}ms();async function Ud(r,e){let{bulb:t,config:n,warnings:s}=await me(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=qd(Lr(t.code,{target:"client",dependencies:n.dependencies??{}}),"client")||i),t.server&&(i=qd(Lr(t.server,{target:"server"}),"server")||i);let o=eS([process.cwd(),Ve.dirname(r)]);if(!o){let l=Ve.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 jd({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 Fd({server:t.server,bulbDir:Ve.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:d}of a){let{stdout:u,exitCode:f}=await Xv(o,d);for(let p of u.split(/\r?\n/))p.trim()&&console.log(`${l} ${p}`);f!==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 qd(r,e){for(let t of r)for(let n of t.message.split(`
|
|
1258
|
+
`))console.log(`${e} ${n}`);return r.length>0}function Xv(r,e){return new Promise(t=>{let n=Yv(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 Zv=zv(import.meta.url);function eS(r){let e=n=>{try{let s=Zv.resolve("typescript/package.json",{paths:n}),i=Ve.join(Ve.dirname(s),"lib","tsc.js");return Qv(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=Gv("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}Ds();Xr();async function Jd(r,e){let{bulb:t}=await me(r),n=Ut(t);if(lt(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.)")}Xr();import*as en from"path";async function Kd(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=$a();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=en.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),jt(t,e),console.log(e?`Trusted ${en.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${en.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}ge();ge();zs();Va();var Ya={claude:()=>new Wt,pi:()=>new Ht};function dp(){for(let r of Object.values(Ya))try{r().ensureWaitSupport()}catch{}}async function pp(r){let e=Zr(),t=new Map(e.filter(i=>Ya[i]).map(i=>[i,Ya[i]()]));for(let[i,o]of t)if(o.detectsSelf())return{name:i};let n=await rn(r);if(n?.agent&&t.has(n.agent))return{name:n.agent};let s=[...t].filter(([,i])=>i.listSessionFiles(r).length>0).map(([i])=>i);return s.length===1?{name:s[0]}:s.length===0?{name:e[0]}:{ambiguous:s}}import{readFileSync as KS,existsSync as WS}from"fs";import*as dt from"path";import{fileURLToPath as HS}from"url";function hp(){let r=dt.dirname(HS(import.meta.url));for(;!WS(dt.join(r,"package.json"));){let e=dt.dirname(r);if(e===r)break;r=e}return r}function Qs(){return dt.join(hp(),"README.md")}function Ga(){return dt.join(hp(),"description.md")}function VS(r){return`---
|
|
1200
1259
|
name: typebulb
|
|
1201
|
-
description: ${
|
|
1260
|
+
description: ${KS(Ga(),"utf8").trim().replace(/\s+/g," ")}
|
|
1202
1261
|
version: ${r}
|
|
1203
|
-
---`}function
|
|
1262
|
+
---`}function YS(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 mp(r,e){return`${VS(e)}
|
|
1204
1263
|
|
|
1205
|
-
${
|
|
1264
|
+
${YS(e)}
|
|
1206
1265
|
|
|
1207
1266
|
${r.trim()}
|
|
1208
|
-
`}async function
|
|
1267
|
+
`}async function gp(r){let e=await pp(process.cwd());if("ambiguous"in e)return GS(r,e.ambiguous);let t=e.name,n,s;try{n=await rp(t)}catch(p){s=p instanceof Error?p.message:String(p)}let i=process.stdout.isTTY===!0,o=p=>m=>i?`\x1B[${p}m${m}\x1B[0m`:m,a=o("1;92"),c=o("1;4;92"),l=o("38;5;135"),d=[" Read the authoring skill before writing a bulb:",` \u2022 ${a("npx typebulb skill")} \u2014 assembles one SKILL.md`," \u2022 or, open its parts:",` ${a(Ga())}`,` ${a(Qs())}`],u=n?[" Agent mirror is live",` ${a("\u25CF")} ${c(n.url)}`," Embedded bulbs render live here."," Agents:",` Reusable app/tool \u2192 write a ${a(".bulb.md")}`," Show something inline \u2192 embed a bulb"," after emitting the bulb, background a wait:",` \u2022 ${a('typebulb wait agent --match "[embed <name>"')}`,...d," End your reply with the mirror link above"," \u2022 easy to miss the link mid-message"]:[` The mirror did not start (${s})`,` \u25CF Start it manually: ${a(`npx typebulb agent:${t}`)}`," Agents:",...d],f=[` ${l(`typebulb v${r}`)}`,...u,""];process.stdout.write(f.join(`
|
|
1209
1268
|
`)+`
|
|
1210
|
-
`)}function
|
|
1269
|
+
`)}function GS(r,e){let t=process.stdout.isTTY===!0,n=a=>c=>t?`\x1B[${a}m${c}\x1B[0m`:c,s=n("1;92"),o=[` ${n("38;5;135")(`typebulb v${r}`)}`," This project has sessions for more than one agent harness."," Open the mirror for the one you want:",...e.map(a=>` \u2022 ${s(`npx typebulb agent:${a}`)}`),""];process.stdout.write(o.join(`
|
|
1211
1270
|
`)+`
|
|
1212
|
-
`)}import{readFileSync as
|
|
1213
|
-
`)){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
|
|
1214
|
-
`+e)}function
|
|
1271
|
+
`)}import{readFileSync as zS,existsSync as QS}from"fs";import*as Ne from"path";function XS(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function Ee(r,e=process.cwd()){let t={},n=[];for(let s of XS(r)){let i;try{i=zS(Ne.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[o,a]of ZS(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:r,sources:t,loaded:n}}function*ZS(r){for(let e of r.split(`
|
|
1272
|
+
`)){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 ex(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 Ge(r,e,t){let{sources:n,mode:s,loaded:i}=r,o=process.cwd(),a=Ne.dirname(e),c=`(mode: ${s??"none"})`,l=t?ex(t):[],d=l.filter(p=>n[p]).map(p=>`${p} \u2190 ${n[p]}`);d.length?console.log(`env: ${d.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=Ne.resolve(a)!==Ne.resolve(o);if(u)for(let p of[".env.local",".env"])QS(Ne.join(a,p))&&console.log(`env: ${Ne.join(a,p)} present but not loaded (cwd is ${o})`);let f=l.filter(p=>process.env[p]===void 0);if(f.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${f.join(", ")} but ${f.length>1?"they are":"it's"} unset${p}`)}}Zs();async function wp(r){Ee(r);let e=await pt();if(e.length>0){console.log(bp(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!yp()){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(Yt))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.")}import*as vp from"fs/promises";async function Sp(r){let e=Qs(),t;try{t=await vp.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(mp(t,r))}Qr();ge();import*as xp from"path";function ax(r,e,t){if(/^\d+$/.test(e))return r.find(s=>s.pid===parseInt(e,10));let n=e==="agent"?r.filter(s=>s.agent!=null):r.filter(s=>s.agent===e);return n.length?t?n.find(s=>s.cwd&&J(s.cwd)===J(t)):n[0]:r.find(s=>J(s.file)===J(e))}var on=r=>r.agent??xp.basename(r.file);function kp(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"} ${t.file}`)}function Qa(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),kp(r,t=>console.log(t)),console.log(`
|
|
1273
|
+
`+e)}function Xa(r,e,t,n){let s=ax(r,e,n);if(s)return s;console.error(`No running server for '${e}'.`),r.length?(console.error(`Running servers (try \`typebulb ${t} <file|pid>\`):`),kp(r,i=>console.error(i))):console.error("No bulb servers are running."),process.exit(1)}async function Ep(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),Qa(await K(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=Xa(await K(),r,"logs",process.cwd());if(e.clear){Qd(t.pid),console.log(`Cleared log for ${on(t)} (pid ${t.pid}).`);return}let n=xe(t.pid),s=n.text;if(e.run!==void 0&&(s=Xd(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(`
|
|
1215
1274
|
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1216
1275
|
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1217
1276
|
`)&&process.stdout.write(`
|
|
1218
|
-
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=xe(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
|
|
1219
|
-
`);
|
|
1277
|
+
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=xe(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 cx=r=>new Promise(e=>setTimeout(e,r));async function Ap(r,e){if(!r){Qa(await K(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=Xa(await K(),r,"wait",process.cwd()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=n?30:e.timeoutSec??1800,a=e.match??"",c=xe(t.pid).offset,l=ja(t.pid,a)??(a?ja(t.pid):void 0),d=l!==void 0&&l<=c?l:a?0:c,u=Date.now()+o*1e3,f=n?1e4:1e3,p,m="",h=0;for(;;){let y=xe(t.pid,d);if(d=y.offset,y.text){m+=y.text;let x=m.split(`
|
|
1278
|
+
`);m=x.pop()??"";for(let k of x)k.trim()&&(e.match&&!k.includes(e.match)||(console.log(k),p??=Date.now()+f))}if(p&&Date.now()>=p)break;if(!i&&!p&&Date.now()>=u){console.error(`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${on(t)} within ${o}s`),h=2;break}if(!qa(t.pid)){p||(console.error(`server ${on(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await cx(400)}Fs(t.pid,d,a),process.exit(h)}async function Tp(r){if(!r){Qa(await K(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Xa(await K(),r,"stop",process.cwd());await ft(e.pid),console.log(`Stopped ${on(e)} (pid ${e.pid}, ${e.url}).`)}async function Pp(r){let e=process.cwd(),t=r==="global"?await K():r==="bulbs"?await K(e):(await K()).filter(s=>s.agent!=null&&s.cwd!=null&&J(s.cwd)===J(e)),n=r==="global"?"server":r==="agent"?"mirror":"bulb";if(!t.length){console.log(r==="global"?"No running bulb servers.":`No running ${n}s for this project.`);return}await Promise.all(t.map(s=>ft(s.pid))),console.log(`Stopped ${t.length} ${n}${t.length===1?"":"s"}:`);for(let s of t)console.log(` ${s.url} pid ${s.pid} ${on(s)}`)}ge();import*as Op from"path";async function Cp(r,e,t=0){let n=Op.resolve(r),s=Js(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.")}ge();import*as Bp from"fs/promises";import*as Gt from"path";import{EventEmitter as cc}from"events";Ds();import{Hono as yx}from"hono";import{serve as bx}from"@hono/node-server";import{streamSSE as wx}from"hono/streaming";import*as mt from"fs/promises";import*as ye from"path";var se=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},oe=class{getPath(e,t){return this.path}parseStreamChunk(e){return this.checkAndThrowError(e),this.parseProviderStreamChunk(e)}isReasoningEnabled(e){return e?.reasoning!==void 0&&e.reasoning>0}extractSystemMessages(e,t=`
|
|
1220
1279
|
|
|
1221
|
-
`){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,n=!1){if(!e)return{message:`HTTP ${t}`};try{let s=JSON.parse(e);if(s.error&&typeof s.error=="object"){let i={message:s.error.message||`HTTP ${t}`,type:s.error.type};return n&&(i.code=s.error.code),i}return s.message?{message:s.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 se(t.message,n,!!t.retryable)}if(t.error)throw new se(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
|
|
1280
|
+
`){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,n=!1){if(!e)return{message:`HTTP ${t}`};try{let s=JSON.parse(e);if(s.error&&typeof s.error=="object"){let i={message:s.error.message||`HTTP ${t}`,type:s.error.type};return n&&(i.code=s.error.code),i}return s.message?{message:s.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 se(t.message,n,!!t.retryable)}if(t.error)throw new se(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=class extends oe{constructor(){super(...arguments),this.providerName="OpenAI",this.defaultBaseUrl="https://api.openai.com",this.path="/v1/responses",this.effortMap={0:"minimal",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};return n?.webSearch!==!1&&(o.tools=[{type:"web_search"}]),this.isReasoningEnabled(n)&&(o.reasoning={effort:this.effortMap[n.reasoning],summary:"auto"}),o}parseError(e,t){return this.parseJsonError(e,t,!0)}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(`
|
|
1222
1281
|
`)),!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"error":return null;case"response.failed":{let s=e.response?.error,i=s?.message||"Response failed",o=s?.code==="insufficient_quota"||s?.code==="rate_limit_exceeded";throw new se(i,o?"rate_limit":"unknown",o)}case"response.output_text.delta":return{text:e.delta};case"response.reasoning_summary_text.delta":return{reasoning:e.delta};case"response.created":case"response.in_progress":case"response.output_item.added":case"response.output_item.done":case"response.content_part.added":case"response.content_part.done":case"response.output_text.done":case"response.output_text.annotation.added":case"response.reasoning_summary_text.done":case"response.completed":case"response.web_search_call.in_progress":case"response.web_search_call.searching":case"response.web_search_call.completed":return null;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(`
|
|
1223
1282
|
|
|
1224
|
-
`)}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
|
|
1283
|
+
`)}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 ti=class extends oe{constructor(){super(...arguments),this.providerName="OpenRouter",this.defaultBaseUrl="https://openrouter.ai",this.path="/api/v1/chat/completions",this.effortMap={0:"low",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};return n?.webSearch===!0&&(i.plugins=[{id:"web"}]),this.isReasoningEnabled(n)&&(i.reasoning={effort:this.effortMap[n.reasoning]}),i}parseError(e,t){return this.parseJsonError(e,t,!0)}parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let t=e,n=t.choices[0],s=n?.message?.content??n?.text??"",i=n?.message?.reasoning??t.reasoning;return{text:s,reasoning:i}}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||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=class extends oe{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};if(n?.webSearch!==!1&&(a.tools=[{type:"web_search_20250305",name:"web_search"}]),i&&(a.system=[{type:"text",text:i,cache_control:{type:"ephemeral"}}]),this.isReasoningEnabled(n)){let c=n.reasoning;if(this.isModernModel(t)){let l={0:"low",1:"low",2:"medium",3:"high"};a.thinking={type:"adaptive"},a.output_config={effort:l[c]}}else{let l={0:0,1:2048,2:4096,3:8192};a.thinking={type:"enabled",budget_tokens:l[c]}}}return a}parseError(e,t){return this.parseJsonError(e,t)}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(`
|
|
1225
1284
|
|
|
1226
|
-
`);return{text:t,reasoning:n||void 0}}parseProviderStreamChunk(e){if(!this.isAnthropicEvent(e))return null;switch(e.type){case"content_block_delta":return e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null;case"message_start":case"content_block_start":case"content_block_stop":case"message_delta":case"message_stop":case"ping":return null;default:return 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-\w+-(\d+)-(\d+)/);return!!t&&(+t[1]>4||+t[1]==4&&+t[2]>=6)}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}};var
|
|
1285
|
+
`);return{text:t,reasoning:n||void 0}}parseProviderStreamChunk(e){if(!this.isAnthropicEvent(e))return null;switch(e.type){case"content_block_delta":return e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null;case"message_start":case"content_block_start":case"content_block_stop":case"message_delta":case"message_stop":case"ping":return null;default:return 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-\w+-(\d+)-(\d+)/);return!!t&&(+t[1]>4||+t[1]==4&&+t[2]>=6)}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}};var ni=class extends oe{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,`
|
|
1227
1286
|
`),c={contents:o.map(l=>({role:l.role==="assistant"?"model":"user",parts:[{text:l.content}]}))};return n?.webSearch!==!1&&(c.tools=[{google_search:{}}]),i&&(c.systemInstruction={role:"system",parts:[{text:i}]}),this.isReasoningEnabled(n)&&(c.generationConfig={thinkingConfig:{includeThoughts:!0,thinkingBudget:-1}}),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(`
|
|
1228
|
-
`)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(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(typeof e=="object"&&e!==null&&"error"in e){let t=e.error,n;if(typeof t=="string")n=t;else if(typeof t=="object"&&t!==null){let s=t;n=s.message||s.status||"Gemini returned an error"}else n="Gemini returned an error";throw new se(n)}if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new se(`Prompt blocked: ${t}`)}}};var
|
|
1287
|
+
`)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(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(typeof e=="object"&&e!==null&&"error"in e){let t=e.error,n;if(typeof t=="string")n=t;else if(typeof t=="object"&&t!==null){let s=t;n=s.message||s.status||"Gemini returned an error"}else n="Gemini returned an error";throw new se(n)}if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new se(`Prompt blocked: ${t}`)}}};var si=class extends oe{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}}parseError(e,t){return this.parseJsonError(e,t,!0)}parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let n=e.choices[0]?.message,s=n?.content??"",i=n?.reasoning??n?.reasoning_content;return{text:s,reasoning:i}}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 Rp=new si,lx=new Map([["openai",new ei],["openrouter",new ti],["anthropic",new ri],["gemini",new ni],["ollama",Rp],["openai-compat",Rp]]);function ht(r){let e=lx.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}function ux(r,e){return r.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function Za(r,e){let t=ht(r.protocol),n=t.getPath(e.model,e.stream),s=ux(r.baseUrl,n),i=t.buildHeaders(r.apiKey,e.origin),o=t.buildPayload(e.messages,e.model,{reasoning:e.reasoning,webSearch:e.webSearch},e.stream);return e.modifyPayload?.(o),fetch(s,{method:"POST",headers:i,body:JSON.stringify(o),signal:e.signal})}async function ec(r,e){let t=ht(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}}function Np(r){let e=r.indexOf(`\r
|
|
1229
1288
|
\r
|
|
1230
1289
|
`),t=r.indexOf(`
|
|
1231
1290
|
|
|
1232
|
-
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function
|
|
1233
|
-
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*
|
|
1234
|
-
${l}`:"";return g.text(`Forbidden: this capability requires --trust.${P}`,403)}await b()},m=async(g,b)=>{let v=g.req.header("sec-fetch-site");if(v){if(v!=="same-origin")return g.text(`Forbidden: ${v} request`,403)}else{let S=g.req.header("origin");if(S&&!
|
|
1235
|
-
${p.name}`),console.log(` ${x}`),h!==e.port&&console.log(` (port ${e.port} was busy)`),e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(
|
|
1291
|
+
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function tc(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(`
|
|
1292
|
+
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*_p(r,e){let t=new TextDecoder,n="";try{for(;;){if(e?.aborted)return;let{done:s,value:i}=await r.read();if(s){if(n.trim()){let c=tc(n);c!==null&&c!=="done"&&(yield c)}return}n+=t.decode(i,{stream:!0});let{pos:o,len:a}=Np(n);for(;o!==-1;){let c=n.slice(0,o);n=n.slice(o+a);let l=tc(c);if(l==="done")return;l!==null&&(yield l),{pos:o,len:a}=Np(n)}}}finally{try{await r.cancel()}catch{}}}async function rc(r,e){if(!r.body)throw new Error("Response body is missing");let t="";for await(let n of ii(r,e))n.kind==="text"&&(t+=n.text);return t}async function*ii(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=ht(t);if(!r.body)return;let s=r.body.getReader();for await(let i of _p(s)){let o=n.parseStreamChunk(i);o?.reasoning&&(yield{kind:"reasoning",text:o.reasoning}),o?.text&&(yield{kind:"text",text:o.text})}}import*as nc from"fs/promises";import*as an from"path";var oi=class{async get(e){let t=pe(e),n=an.join(Gr,t+".bin"),s=an.join(Gr,t+".json");try{let[i,o]=await Promise.all([nc.readFile(n),nc.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await q();let n=pe(e),s=an.join(Gr,n+".bin"),i=an.join(Gr,n+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([ce(s,t.body),ce(i,JSON.stringify(o))])}};ge();Zs();import{stream as fx}from"hono/streaming";var dx="X-TB-Stream";function px(r){return r instanceof se?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function sc(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(dx,"1"),fx(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:px(s)}))}finally{try{await n.return?.()}catch{}}})}var ic={log:(...r)=>console.log(...r)};function ai(r,e){let t=r?.[e]??ic[e];return typeof t=="function"?t:void 0}function ci(r){return r.constructor?.name==="AsyncGeneratorFunction"}var hx=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,mx=/[?&]target=/,gx=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function Ip(r,e=""){return hx.test(r)?!0:gx.test(r)&&mx.test(e)}var $p="127.0.0.1",vx=new Set(["localhost","127.0.0.1","::1"]);function Sx(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function xx(r){let e=Sx(r);return!!e&&vx.has(e)}function kx(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function li(r){return r instanceof Error?r.message:"Unknown error"}async function ui(r){let{getHtml:e,basePath:t,port:n,reloadEmitter:s,messageEmitter:i,getServerExports:o,localOverride:a,trusted:c=!1,trustHint:l,staticAssets:d}=r,u=new yx;u.use("*",async(g,b)=>{if(!xx(g.req.header("host")))return g.text("Forbidden: untrusted Host",403);await b()}),u.use("*",async(g,b)=>{await b(),g.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),g.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let f=["/__fs/*","/__api/*","/__ai"],p=async(g,b)=>{if(!c){let v=new URL(g.req.url).pathname,S=v.startsWith("/__fs")?"the filesystem":v==="/__ai"?"AI (your API keys)":"server-side code (server.ts)";Zd(process.pid,S);let P=l?`
|
|
1293
|
+
${l}`:"";return g.text(`Forbidden: this capability requires --trust.${P}`,403)}await b()},m=async(g,b)=>{let v=g.req.header("sec-fetch-site");if(v){if(v!=="same-origin")return g.text(`Forbidden: ${v} request`,403)}else{let S=g.req.header("origin");if(S&&!kx(S,g.req.header("host")))return g.text("Forbidden: cross-origin request",403)}await b()};for(let g of f)u.use(g,p),u.use(g,m);u.use("/__log",m),u.post("/__log",async g=>{try{let{args:b}=await g.req.json();console.log(...b||[])}catch{}return g.json({ok:!0})}),i&&(u.use("/__send",m),u.post("/__send",async g=>{let b="";try{b=await g.req.text()}catch{}let v=i.listenerCount("message");return i.emit("message",b),g.json({clients:v})})),u.get("/",g=>g.html(e())),u.post("/__fs/read",async g=>{try{let{path:b}=await g.req.json(),v=ac(b,t),S=await mt.readFile(v);return new Response(new Uint8Array(S),{headers:{"Content-Type":"application/octet-stream"}})}catch(b){let v=li(b);return g.json({error:v},400)}}),u.post("/__fs/write",async g=>{try{let b=g.req.query("path");if(!b)return g.json({error:"Missing path"},400);let v=ac(b,t);return await mt.mkdir(ye.dirname(v),{recursive:!0}),await mt.writeFile(v,Buffer.from(await g.req.arrayBuffer())),g.json({success:!0})}catch(b){let v=li(b);return g.json({error:v},400)}}),u.post("/__api/:name",async g=>{try{let b=g.req.param("name"),v=ai(o?.(),b);if(!v)return g.json({error:`API function '${b}' not found`},404);let{args:S}=await g.req.json();if(ci(v))return sc(g,v(...S||[]));let P=await v(...S||[]);return g.json({result:P})}catch(b){let v=li(b);return g.json({error:v},500)}}),u.post("/__ai",async g=>{try{let{messages:b,system:v,reasoning:S,provider:P,model:E,webSearch:L,stream:Q}=await g.req.json();if(!b||!Array.isArray(b)||b.length===0)return g.json({message:"messages array is required",code:"unknown",retryable:!1},400);let V=Ex(P,E);if(typeof V=="string")return g.json({message:V,code:"unknown",retryable:!1},400);let B=[...v?[{role:"system",content:v}]:[],...b.map(O=>({role:O.role,content:O.content}))],w=await Za(V,{model:V.model,messages:B,stream:!0,reasoning:S??0,webSearch:L??!0});if(!w.ok){let O=await ec(w,V.protocol);return g.json(O,w.status)}if(Q)return sc(g,ii(w,V.protocol));let A=await rc(w,V.protocol);return A||console.warn("[tb.ai] Empty response from provider"),g.json({text:A})}catch(b){if(b instanceof se)return g.json({message:b.message,code:b.code,retryable:b.retryable},500);let v=li(b);return g.json({message:v,code:"unknown",retryable:!1},500)}}),u.get("/__models",async g=>{try{let b=await pt();return g.json(b)}catch{return g.json([],200)}});let h=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],y=new oi;u.get("/proxy/*",async g=>{let b=new URL(g.req.url),S=(b.pathname+b.search).slice(7),P=S.lastIndexOf("https://");return P===-1?g.text("Invalid proxy URL",400):x(g,S.slice(P))}),a&&Lp(u,`/local/${a.name}/`,a.serveDir),d&&Lp(u,d.mount,d.dir);async function x(g,b){let v;try{v=new URL(b)}catch{return g.text("Invalid URL",400)}if(v.protocol!=="https:")return g.text("HTTPS only",400);if(!h.includes(v.hostname))return g.text("Host not allowed",403);let S=await y.get(b);if(S)return new Response(S.body,{status:200,headers:oc(S.contentType,S.cacheControl)});try{let P=await fetch(b,{headers:{Accept:g.req.header("Accept")||"*/*"},redirect:"follow"});if(!P.ok)return g.text(`Upstream ${P.status}`,P.status);let E=P.headers.get("Content-Type")||void 0,L=P.headers.get("Cache-Control")||void 0;if(P.body){let[Q,V]=P.body.tee();return(async()=>{try{let B=await new Response(V).arrayBuffer();await y.set(b,{body:Buffer.from(B),contentType:E,cacheControl:L})}catch{}})(),new Response(Q,{status:P.status,headers:oc(E,L)})}return new Response(null,{status:P.status,headers:oc(E,L)})}catch(P){return g.text(`Proxy fetch failed: ${P instanceof Error?P.message:P}`,502)}}(s||i)&&u.get("/__reload",g=>wx(g,async b=>{let v=()=>{b.writeSSE({event:"reload",data:""})},S=P=>{b.writeSSE({event:"message",data:JSON.stringify(P)})};for(s?.on("reload",v),i?.on("message",S),b.onAbort(()=>{s?.removeListener("reload",v),i?.removeListener("message",S)});;)await b.sleep(3e4)})),u.notFound(async g=>{if(g.req.method!=="GET")return g.text("Not Found",404);let b=new URL(g.req.url);return Ip(b.pathname,b.search)?x(g,"https://esm.sh"+b.pathname+b.search):g.text("Not Found",404)});let k=bx({fetch:u.fetch,port:n,hostname:$p});return{port:n,close:()=>k.close()}}function Ex(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=ht(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${za(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=Yt[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 oc(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 Lp(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=ac(i,t),a=await mt.readFile(o);return new Response(a,{headers:{"Content-Type":Ax(o)}})}catch{return n.text("Not Found",404)}})}function Ax(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 ac(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 cn(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,$p,()=>{let s=n.address(),i=typeof s=="object"&&s?s.port:r;n.close(()=>t(i))}),n.on("error",()=>{t(cn(r+1))})})}import Mp from"chokidar";var Dp={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function fi(r){let{bulbPath:e,emitter:t,debounceMs:n=150}=r,s,i=Mp.watch(e,Dp);return i.on("change",()=>{s&&clearTimeout(s),s=setTimeout(()=>t.emit("reload"),n)}),()=>{s&&clearTimeout(s),i.close()}}function di(r){let{dir:e,onChange:t,debounceMs:n=150}=r,s,i=Mp.watch(e,Dp);return i.on("all",()=>{s&&clearTimeout(s),s=setTimeout(t,n)}),()=>{s&&clearTimeout(s),i.close()}}ge();async function jp(r,e,t,n,s){let i=process.cwd(),o=qs(process.pid),a=e.watch?new cc:void 0,c=new cc;c.setMaxListeners(0);let l=Ee(e.mode),d=await Ua(r);d.length&&console.log(`Replacing the running server for this bulb (pid ${d.map(S=>S.pid).join(", ")})`);let u=1;console.log(Fa(u)),console.log(`Loading ${Gt.basename(r)}...`);let{html:f,bulb:p,serverExports:m}=await _a(r,e.watch,e.trust,n,s);Ge(l,r,p.server);let h=await cn(e.port),y=await ui({getHtml:()=>f,basePath:i,port:h,reloadEmitter:a,messageEmitter:c,getServerExports:()=>m,localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,trusted:e.trust,trustHint:t}),x=`http://localhost:${h}`,k=e.trust?void 0:Ut(p);await Us({pid:process.pid,port:h,url:x,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,predicted:k}),console.log(`
|
|
1294
|
+
${p.name}`),console.log(` ${x}`),h!==e.port&&console.log(` (port ${e.port} was busy)`),e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(k?` trust: restricted \u2014 this bulb appears to use ${k}; re-run with --trust to enable it:
|
|
1236
1295
|
${t}
|
|
1237
1296
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
1238
1297
|
`),e.watch&&console.log(` Watching for changes...
|
|
1239
|
-
`);let g,b;if(e.watch&&a){let S=new
|
|
1298
|
+
`);let g,b;if(e.watch&&a){let S=new cc;if(S.on("reload",async()=>{try{console.log("Recompiling...");let P=await _a(r,!0,e.trust,n,s);f=P.html,m=P.serverExports,u++,console.log(Fa(u)),a.emit("reload")}catch(P){console.error("Compile error:",P)}}),g=fi({bulbPath:r,emitter:S}),n){let{name:P,serveDir:E}=n;b=di({dir:E,onChange:()=>{console.log(`Local package '${P}' changed. Browser reloading...
|
|
1240
1299
|
`),a.emit("reload")}})}}e.open&&(d.some(S=>S.port===h)?console.log(` Reusing the open browser tab.
|
|
1241
1300
|
`):await Ft(x));let v=async()=>{console.log(`
|
|
1242
|
-
Shutting down...`),y.close(),g?.(),b?.(),o(),await tn(process.pid);let S=Gt.join(Gt.dirname(r),".typebulb","server.mjs");await
|
|
1301
|
+
Shutting down...`),y.close(),g?.(),b?.(),o(),await tn(process.pid);let S=Gt.join(Gt.dirname(r),".typebulb","server.mjs");await Bp.rm(S,{force:!0}).catch(()=>{}),process.exit(0)};process.on("SIGINT",v),process.on("SIGTERM",v)}import{readFileSync as Oh,copyFileSync as qk,existsSync as Uk}from"fs";import*as Z from"path";import{fileURLToPath as Jk}from"url";import{EventEmitter as Kk}from"events";ge();var lc=r=>`/agents/${r}/client.js`,Tx=`
|
|
1243
1302
|
(() => {
|
|
1244
1303
|
const api = async (name, ...args) => {
|
|
1245
1304
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -1274,15 +1333,15 @@ Shutting down...`),y.close(),g?.(),b?.(),o(),await tn(process.pid);let S=Gt.join
|
|
|
1274
1333
|
es.onerror = () => { es.close(); };
|
|
1275
1334
|
}
|
|
1276
1335
|
})();
|
|
1277
|
-
`;function
|
|
1336
|
+
`;function Fp(r){let{name:e,agent:t,styles:n,mountHtml:s,watch:i,theme:o}=r,a=lc(t);return`<!DOCTYPE html>
|
|
1278
1337
|
<html>
|
|
1279
1338
|
<head>
|
|
1280
1339
|
<meta charset="utf-8">
|
|
1281
1340
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1282
|
-
<title>${
|
|
1283
|
-
${
|
|
1341
|
+
<title>${As(e)} - typebulb</title>
|
|
1342
|
+
${Ps(e,o)}
|
|
1284
1343
|
<style>
|
|
1285
|
-
${
|
|
1344
|
+
${Ts}
|
|
1286
1345
|
</style>
|
|
1287
1346
|
<style>
|
|
1288
1347
|
${n}
|
|
@@ -1294,19 +1353,19 @@ ${s}
|
|
|
1294
1353
|
${i?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
|
|
1295
1354
|
|
|
1296
1355
|
<script>
|
|
1297
|
-
${
|
|
1356
|
+
${Tx}
|
|
1298
1357
|
</script>
|
|
1299
1358
|
|
|
1300
1359
|
<script type="module" src="${a}"></script>
|
|
1301
1360
|
</body>
|
|
1302
|
-
</html>`}var
|
|
1361
|
+
</html>`}var Wk={claude:()=>Promise.resolve().then(()=>(Eh(),kh)),pi:()=>Promise.resolve().then(()=>(Ph(),Th))};async function Ch(r){let e=process.cwd(),t=r.agentTarget,n=qs(process.pid),s=r.watch?new Kk:void 0,i=Ee(r.mode),o=await Wk[t](),a=o.displayName||`${t} mirror`;Ge(i,Z.join(e,"mirror"));let c=Z.dirname(Jk(import.meta.url)),l=Z.join(c,"agents",t),d=Z.join(c,"..","cli","agents"),u=Z.join(l,"styles.css"),f=Z.join(l,"index.html"),p=()=>Fp({name:a,agent:t,styles:Oh(u,"utf8"),mountHtml:Oh(f,"utf8"),watch:r.watch}),m=await cn(r.port),h=await ui({getHtml:p,basePath:e,port:m,reloadEmitter:s,getServerExports:()=>o,trusted:!0,staticAssets:{mount:`${Z.posix.dirname(lc(t))}/`,dir:l}}),y=`http://localhost:${m}`;await Us({pid:process.pid,port:m,url:y,file:`agent:${t}`,cwd:e,startedAt:Date.now(),trust:!0,agent:t}),console.log(`
|
|
1303
1362
|
${a}`),console.log(` ${y}`),m!==r.port&&console.log(` (port ${r.port} was busy)`),r.watch&&console.log(` Watching for changes...
|
|
1304
|
-
`);let x=Z.join(d,t,"client"),
|
|
1305
|
-
`),s.emit("reload")}catch(
|
|
1306
|
-
Shutting down...`);try{o.shutdownSwitcher?.()}catch{}h.close(),b?.(),n(),await tn(process.pid),process.exit(0)};process.on("SIGINT",v),process.on("SIGTERM",v)}import*as
|
|
1307
|
-
`);let c=new
|
|
1308
|
-
`)}catch(p){
|
|
1309
|
-
`),process.exit(0)}async function
|
|
1310
|
-
`),process.exit(1)}function
|
|
1311
|
-
${e}`),process.exit(1))}async function
|
|
1312
|
-
${l.url}`),r.open&&await Ft(l.url);return}await
|
|
1363
|
+
`);let x=Z.join(d,t,"client"),k=Z.join(d,"core","client");async function g(){await(await import("esbuild")).build({entryPoints:[Z.join(x,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:Z.join(l,"client.js")});for(let P of["styles.css","index.html"])qk(Z.join(k,P),Z.join(l,P))}let b;if(r.watch&&s){let S=Uk(x),P=!1;b=di({dir:S?d:l,onChange:async()=>{if(!P){P=!0;try{S&&await g(),console.log(`Mirror rebuilt. Browser reloading...
|
|
1364
|
+
`),s.emit("reload")}catch(E){console.error("Mirror rebuild failed:",E instanceof Error?E.message:E)}finally{P=!1}}}})}r.open&&await Ft(y);let v=async()=>{console.log(`
|
|
1365
|
+
Shutting down...`);try{o.shutdownSwitcher?.()}catch{}h.close(),b?.(),n(),await tn(process.pid),process.exit(0)};process.on("SIGINT",v),process.on("SIGTERM",v)}import*as Rh from"path";import{EventEmitter as Hk}from"events";async function Nh(r,e,t,n,s){let i=Ee(t),o=!1,a=async()=>{let{bulb:c,config:l}=await me(r);o||(Ge(i,r,c.server),o=!0),await zr(c.server,s,n,l.dependencies)};if(console.log(`Running ${Rh.basename(r)}...`),await a(),e){console.log(`Watching for changes...
|
|
1366
|
+
`);let c=new Hk;c.on("reload",async()=>{try{console.log("Re-running..."),await a()}catch(l){console.error("Error:",l)}}),fi({bulbPath:r,emitter:c})}}import{Console as Vk}from"node:console";ge();Qr();async function Ih(r,e,t,n,s){Xk();try{let p=J(r),m=(await K()).find(h=>J(h.file)===p);m&&Fs(m.pid,xe(m.pid).offset)}catch{}let i=Ee(t),{bulb:o,config:a}=await me(r);o.server||pn("This bulb has no **server.ts** block; nothing to call."),Ge(i,r,o.server);let c;try{c=await zr(o.server,s,n,a.dependencies)}catch(p){pn(p instanceof Error?p.message:String(p))}let l=ai(c,e.fn);if(!l){let p=[...Object.keys(c).filter(m=>typeof c[m]=="function"),...Object.keys(ic)];pn(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let d=await Yk(e);if(ci(l)){try{for await(let p of l(...d))await _h(JSON.stringify(p,Lh)+`
|
|
1367
|
+
`)}catch(p){pn(p instanceof Error?p.stack??p.message:String(p))}process.exit(0)}let u;try{u=await l(...d)}catch(p){pn(p instanceof Error?p.stack??p.message:String(p))}let f=Qk(u);f!==void 0&&await _h(f+`
|
|
1368
|
+
`),process.exit(0)}async function Yk(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await Zk()),zk(e)}return Gk(r.positional)}function Gk(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function zk(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 Qk(r){if(r!==void 0)return JSON.stringify(r,Lh,2)}function Lh(r,e){return typeof e=="bigint"?e.toString():e}function pn(r){process.stderr.write(r+`
|
|
1369
|
+
`),process.exit(1)}function Xk(){let r=new Vk(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 _h(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function Zk(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var Pc="0.18.3";function $h(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
1370
|
+
${e}`),process.exit(1))}async function e0(){let r=Bc(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${Pc}`),process.exit(0)),r.help&&(jc(),process.exit(0)),dp(),r.subcommand==="logs"){await Ep(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await Ap(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await Pp(r.stopScope):await Tp(r.file||void 0);return}if(r.subcommand==="send"){await Cp(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await Sp(Pc);return}if(r.subcommand==="models"){await wp(r.mode);return}if(r.subcommand==="agent"){if(!r.agentTarget){await gp(Pc);return}$d(r.agentTarget)||(console.error(`Unknown agent '${r.agentTarget}'. Known: ${Zr().join(", ")}.`),process.exit(1));let l=await rn(process.cwd(),r.agentTarget);if(l){console.log(`Mirror '${r.agentTarget}' is already running for this project:
|
|
1371
|
+
${l.url}`),r.open&&await Ft(l.url);return}await Ch(r);return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await Kd(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let l=await Nd(process.cwd());l||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=l}else e=_e.resolve(r.file);await Mh.access(e).then(()=>!0,()=>!1)||(Zr().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:_e.relative(process.cwd(),e)||_e.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await Jd(e,s);return}let i=!r.noTrust&<(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 me(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 Mc(r.local)}catch(l){console.error(l instanceof Error?l.message:String(l)),process.exit(1)}console.log(`replace: ${a.name} \u2192 ${_e.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await Ud(e,a);return}let c=_e.dirname(e);if(r.subcommand==="call"){$h(r.trust,s),await Ih(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a,c);return}if(o&&o.bulb.server&&(!o.bulb.code||r.server)){$h(r.trust,s),await Nh(e,r.watch,r.mode,a,c);return}await jp(e,r,s,a,c)}e0().catch(r=>{console.error("Error:",r.message),process.exit(1)});
|