typebulb 0.28.3 → 0.29.1
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 +7 -5
- package/dist/agents/claude/client.js +1 -1
- package/dist/agents/pi/client.js +1 -1
- package/dist/agents/pi/matchu-patchu.ts +1 -1
- package/dist/dts/tbTypings.d.ts +4 -4
- package/dist/dts/tbTypings.d.ts.map +1 -1
- package/dist/dts/tbTypings.js +6 -5
- package/dist/dts/tbTypings.js.map +1 -1
- package/dist/index.js +225 -219
- package/dist/render.js +1 -1
- package/package.json +15 -9
package/dist/index.js
CHANGED
|
@@ -1,169 +1,169 @@
|
|
|
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 My=Object.create;var Oo=Object.defineProperty;var Dy=Object.getOwnPropertyDescriptor;var By=Object.getOwnPropertyNames;var jy=Object.getPrototypeOf,Fy=Object.prototype.hasOwnProperty;var Gn=(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 A=(r,e)=>()=>(r&&(e=r(r=0)),e);var E=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ou=(r,e)=>{for(var t in e)Oo(r,t,{get:e[t],enumerable:!0})},qy=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of By(e))!Fy.call(r,s)&&s!==t&&Oo(r,s,{get:()=>e[s],enumerable:!(n=Dy(e,s))||n.enumerable});return r};var Uy=(r,e,t)=>(t=r!=null?My(jy(r)):{},qy(e||!r||!r.__esModule?Oo(t,"default",{value:r,enumerable:!0}):t,r));function bu(r){return Ge.find(e=>Te[e].path===r)}function vu(r){return!!r?.startsWith("typebulb")}var Te,Ge,wu,zn=A(()=>{Te={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"}},Ge=["code","css","html","data","infer","insight","config","notes"];wu="typebulb/v1"});function No(r){return/[:\n"']/.test(r)||r.startsWith(" ")||r.endsWith(" ")?`"${r.replace(/"/g,'\\"')}"`:r}function Io(r){return r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1).replace(/\\"/g,'"'):r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}var Qn=A(()=>{});function de(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=eb(n);if(!s)return null;let i=new Map,o=[],a=t;for(;t<e.length;){let l=e[t]?.trim()?.match(Su);if(l){let f=l[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let u=e[t]?.match(Xn);if(!u){o.push(`**${f}** has no code fence \u2014 block skipped`);continue}let d=u[1];t++;let p=[],y=$o(d);for(;t<e.length&&!e[t]?.match(y);)p.push(e[t]),t++;let m=t<e.length;t++,o.push(...Xy(f,p,m)),i.set(f,p.join(`
|
|
5
|
+
`)),a=t}else t++}return{frontmatter:s,files:i,warnings:o,bodyEndLine:a}}catch{return null}}function Xy(r,e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s]?.trim().match(Su);i&&Qy.has(i[1].trim())&&Zy(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 Zy(r,e){let t=e+1;for(;t<r.length&&r[t]?.trim()==="";)t++;return!!r[t]?.match(Xn)}function eb(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=Io(i);break}}return!vu(e.format)||!e.name?null:e}function ku(r){return de(r)?.warnings??[]}function xu(r){let e=Object.fromEntries(Ge.map(t=>[t,r.files.get(Te[t].path)||""]));return{name:r.frontmatter.name,...e}}var Su,Xn,Qy,$o,Lo=A(()=>{zn();Qn();Su=/^\*\*(.+)\*\*$/,Xn=/^(`{3,})(\w*)\s*$/,Qy=new Set(Ge.map(r=>Te[r].path)),$o=r=>new RegExp(`^${r}\\s*$`)});function Eu(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 Au(r,e){let{path:t}=Te[r],n=t.split(".").pop(),s=Eu(e);return`**${t}**
|
|
6
6
|
|
|
7
7
|
${s}${n}
|
|
8
8
|
${e}
|
|
9
|
-
${s}`}function
|
|
10
|
-
`)}function
|
|
11
|
-
`);for(let i=0;i<s.length;i++){if(s[i]?.trim()!==`**${n}**`)continue;let o=i+1;for(;o<s.length&&s[o]?.trim()==="";)o++;let a=s[o]?.match(
|
|
9
|
+
${s}`}function Tu(r){let e=Ge.filter(t=>r[t]).map(t=>Au(t,r[t]));return["---",`format: ${wu}`,`name: ${No(r.name)}`,"---","",...e].join(`
|
|
10
|
+
`)}function Mo(r,e,t){let{path:n}=Te[e],s=r.split(`
|
|
11
|
+
`);for(let i=0;i<s.length;i++){if(s[i]?.trim()!==`**${n}**`)continue;let o=i+1;for(;o<s.length&&s[o]?.trim()==="";)o++;let a=s[o]?.match(Xn);if(!a)continue;let c=$o(a[1]),l=o+1;for(;l<s.length&&!s[l]?.match(c);)l++;if(l>=s.length)return r;let f=Eu(t),u=f.length>a[1].length?f:a[1];return[...s.slice(0,o),u+a[2],...t.split(`
|
|
12
12
|
`),u,...s.slice(l+1)].join(`
|
|
13
13
|
`)}return`${r.replace(/\s*$/,"")}
|
|
14
14
|
|
|
15
|
-
${
|
|
16
|
-
`}var
|
|
17
|
-
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=Mr(a,"^[^<]*[ /]>",0),l=c!==-1&&a[c-1]==="/";if(n&&console.log("[xml-utils] selfClosing:",l),l===!1)if(s){let p=0,y=1,m=0;for(;(c=Mr(a,"[ /]"+e+">",p))!==-1;){let b=a.substring(p,c+1);if(y+=
|
|
18
|
-
>]`),m+=
|
|
19
|
-
`)}};jr.defaultYaml={explicit:!1,version:"1.2"};jr.defaultTags={"!!":"tag:yaml.org,2002:"};
|
|
20
|
-
`)?
|
|
15
|
+
${Au(e,t)}
|
|
16
|
+
`}var Pu=A(()=>{zn();Lo();Qn()});function Lr(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}function rb(r){return r.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"")}function Do(r){let e=Lr(r??"").description?.trim();if(!e)return tb;let t=rb(e);return(t.length>200?t.slice(0,197)+"...":t).replace(/\n/g," ")}var tb,Ou=A(()=>{tb="A Typebulb bulb."});var Cu=A(()=>{});function Bo(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index:-1}var _u=A(()=>{});function Mr(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index+s[0].length-1:-1}var Ru=A(()=>{});function Zn(r,e){let t=new RegExp(e,"g"),n=r.match(t);return n?n.length:0}var Nu=A(()=>{});function Dr(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=Bo(r,`<${e}[
|
|
17
|
+
>/]`,i);if(n&&console.log("[xml-utils] start:",o),o===-1)return;let a=r.slice(o+e.length),c=Mr(a,"^[^<]*[ /]>",0),l=c!==-1&&a[c-1]==="/";if(n&&console.log("[xml-utils] selfClosing:",l),l===!1)if(s){let p=0,y=1,m=0;for(;(c=Mr(a,"[ /]"+e+">",p))!==-1;){let b=a.substring(p,c+1);if(y+=Zn(b,"<"+e+`[
|
|
18
|
+
>]`),m+=Zn(b,"</"+e+">"),m>=y)break;p=c}}else c=Mr(a,"[ /]"+e+">",0);let f=o+e.length+c+1;if(n&&console.log("[xml-utils] end:",f),f===-1)return;let u=r.slice(o,f),d;return l?d=null:d=u.slice(u.indexOf(">")+1,u.lastIndexOf("<")),{inner:d,outer:u,start:o,end:f}}var jo=A(()=>{_u();Ru();Nu()});var Fo=A(()=>{jo()});var qo=A(()=>{Fo()});var Iu=A(()=>{qo()});var $u=A(()=>{});var Lu=A(()=>{Cu();jo();Fo();Iu();qo();$u()});var j=E(Z=>{"use strict";var Uo=Symbol.for("yaml.alias"),Mu=Symbol.for("yaml.document"),es=Symbol.for("yaml.map"),Du=Symbol.for("yaml.pair"),Jo=Symbol.for("yaml.scalar"),ts=Symbol.for("yaml.seq"),Me=Symbol.for("yaml.node.type"),ib=r=>!!r&&typeof r=="object"&&r[Me]===Uo,ob=r=>!!r&&typeof r=="object"&&r[Me]===Mu,ab=r=>!!r&&typeof r=="object"&&r[Me]===es,cb=r=>!!r&&typeof r=="object"&&r[Me]===Du,Bu=r=>!!r&&typeof r=="object"&&r[Me]===Jo,lb=r=>!!r&&typeof r=="object"&&r[Me]===ts;function ju(r){if(r&&typeof r=="object")switch(r[Me]){case es:case ts:return!0}return!1}function ub(r){if(r&&typeof r=="object")switch(r[Me]){case Uo:case es:case Jo:case ts:return!0}return!1}var fb=r=>(Bu(r)||ju(r))&&!!r.anchor;Z.ALIAS=Uo;Z.DOC=Mu;Z.MAP=es;Z.NODE_TYPE=Me;Z.PAIR=Du;Z.SCALAR=Jo;Z.SEQ=ts;Z.hasAnchor=fb;Z.isAlias=ib;Z.isCollection=ju;Z.isDocument=ob;Z.isMap=ab;Z.isNode=ub;Z.isPair=cb;Z.isScalar=Bu;Z.isSeq=lb});var Br=E(Ko=>{"use strict";var G=j(),oe=Symbol("break visit"),Fu=Symbol("skip children"),Pe=Symbol("remove node");function rs(r,e){let t=qu(e);G.isDocument(r)?zt(null,r.contents,t,Object.freeze([r]))===Pe&&(r.contents=null):zt(null,r,t,Object.freeze([]))}rs.BREAK=oe;rs.SKIP=Fu;rs.REMOVE=Pe;function zt(r,e,t,n){let s=Uu(r,e,t,n);if(G.isNode(s)||G.isPair(s))return Ju(r,n,s),zt(r,s,t,n);if(typeof s!="symbol"){if(G.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=zt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===oe)return oe;o===Pe&&(e.items.splice(i,1),i-=1)}}}else if(G.isPair(e)){n=Object.freeze(n.concat(e));let i=zt("key",e.key,t,n);if(i===oe)return oe;i===Pe&&(e.key=null);let o=zt("value",e.value,t,n);if(o===oe)return oe;o===Pe&&(e.value=null)}}return s}async function ns(r,e){let t=qu(e);G.isDocument(r)?await Qt(null,r.contents,t,Object.freeze([r]))===Pe&&(r.contents=null):await Qt(null,r,t,Object.freeze([]))}ns.BREAK=oe;ns.SKIP=Fu;ns.REMOVE=Pe;async function Qt(r,e,t,n){let s=await Uu(r,e,t,n);if(G.isNode(s)||G.isPair(s))return Ju(r,n,s),Qt(r,s,t,n);if(typeof s!="symbol"){if(G.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=await Qt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===oe)return oe;o===Pe&&(e.items.splice(i,1),i-=1)}}}else if(G.isPair(e)){n=Object.freeze(n.concat(e));let i=await Qt("key",e.key,t,n);if(i===oe)return oe;i===Pe&&(e.key=null);let o=await Qt("value",e.value,t,n);if(o===oe)return oe;o===Pe&&(e.value=null)}}return s}function qu(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 Uu(r,e,t,n){if(typeof t=="function")return t(r,e,n);if(G.isMap(e))return t.Map?.(r,e,n);if(G.isSeq(e))return t.Seq?.(r,e,n);if(G.isPair(e))return t.Pair?.(r,e,n);if(G.isScalar(e))return t.Scalar?.(r,e,n);if(G.isAlias(e))return t.Alias?.(r,e,n)}function Ju(r,e,t){let n=e[e.length-1];if(G.isCollection(n))n.items[r]=t;else if(G.isPair(n))r==="key"?n.key=t:n.value=t;else if(G.isDocument(n))n.contents=t;else{let s=G.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}Ko.visit=rs;Ko.visitAsync=ns});var Ho=E(Hu=>{"use strict";var Ku=j(),db=Br(),pb={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},mb=r=>r.replace(/[!,[\]{}]/g,e=>pb[e]),jr=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+mb(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&&Ku.isNode(e.contents)){let i={};db.visit(e.contents,(o,a)=>{Ku.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(`
|
|
19
|
+
`)}};jr.defaultYaml={explicit:!1,version:"1.2"};jr.defaultTags={"!!":"tag:yaml.org,2002:"};Hu.Directives=jr});var ss=E(Fr=>{"use strict";var Wu=j(),hb=Br();function gb(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 Yu(r){let e=new Set;return hb.visit(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function Vu(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function yb(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s??(s=Yu(r));let o=Vu(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(Wu.isScalar(o.node)||Wu.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}}Fr.anchorIsValid=gb;Fr.anchorNames=Yu;Fr.createNodeAnchors=yb;Fr.findNewAnchor=Vu});var Wo=E(Gu=>{"use strict";function qr(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=qr(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=qr(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=qr(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=qr(r,n,s,i);o===void 0?delete n[s]:o!==i&&(n[s]=o)}return r.call(e,t,n)}Gu.applyReviver=qr});var ze=E(Qu=>{"use strict";var bb=j();function zu(r,e,t){if(Array.isArray(r))return r.map((n,s)=>zu(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!bb.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}Qu.toJS=zu});var is=E(Zu=>{"use strict";var wb=Wo(),Xu=j(),vb=ze(),Yo=class{constructor(e){Object.defineProperty(this,Xu.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(!Xu.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=vb.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?wb.applyReviver(i,{"":a},"",a):a}};Zu.NodeBase=Yo});var Ur=E(ef=>{"use strict";var Sb=ss(),kb=Br(),Xt=j(),xb=is(),Eb=ze(),Vo=class extends xb.NodeBase{constructor(e){super(Xt.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=[],kb.visit(e,{Node:(i,o)=>{(Xt.isAlias(o)||Xt.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||(Eb.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=os(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(Sb.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 os(r,e,t){if(Xt.isAlias(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(Xt.isCollection(e)){let n=0;for(let s of e.items){let i=os(r,s,t);i>n&&(n=i)}return n}else if(Xt.isPair(e)){let n=os(r,e.key,t),s=os(r,e.value,t);return Math.max(n,s)}return 1}ef.Alias=Vo});var W=E(Go=>{"use strict";var Ab=j(),Tb=is(),Pb=ze(),Ob=r=>!r||typeof r!="function"&&typeof r!="object",Qe=class extends Tb.NodeBase{constructor(e){super(Ab.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:Pb.toJS(this.value,e,t)}toString(){return String(this.value)}};Qe.BLOCK_FOLDED="BLOCK_FOLDED";Qe.BLOCK_LITERAL="BLOCK_LITERAL";Qe.PLAIN="PLAIN";Qe.QUOTE_DOUBLE="QUOTE_DOUBLE";Qe.QUOTE_SINGLE="QUOTE_SINGLE";Go.Scalar=Qe;Go.isScalarValue=Ob});var Jr=E(rf=>{"use strict";var Cb=Ur(),kt=j(),tf=W(),_b="tag:yaml.org,2002:";function Rb(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 Nb(r,e,t){if(kt.isDocument(r)&&(r=r.contents),kt.isNode(r))return r;if(kt.isPair(r)){let u=t.schema[kt.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 Cb.Alias(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=_b+e.slice(2));let l=Rb(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new tf.Scalar(r);return c&&(c.node=u),u}l=r instanceof Map?o[kt.MAP]:Symbol.iterator in Object(r)?o[kt.SEQ]:o[kt.MAP]}i&&(i(l),delete t.onTagObj);let f=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new tf.Scalar(r);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}rf.createNode=Nb});var cs=E(as=>{"use strict";var Ib=Jr(),Oe=j(),$b=is();function zo(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 Ib.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 nf=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,Qo=class extends $b.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=>Oe.isNode(n)||Oe.isPair(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(nf(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(Oe.isCollection(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,zo(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(Oe.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&&Oe.isScalar(i)?i.value:i:Oe.isCollection(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!Oe.isPair(t))return!1;let n=t.value;return n==null||e&&Oe.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 Oe.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(Oe.isCollection(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,zo(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};as.Collection=Qo;as.collectionFromPath=zo;as.isEmptyPath=nf});var Kr=E(ls=>{"use strict";var Lb=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Xo(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var Mb=(r,e,t)=>r.endsWith(`
|
|
20
|
+
`)?Xo(t,e):t.includes(`
|
|
21
21
|
`)?`
|
|
22
|
-
`+
|
|
23
|
-
`)t===
|
|
22
|
+
`+Xo(t,e):(r.endsWith(" ")?"":" ")+t;ls.indentComment=Xo;ls.lineComment=Mb;ls.stringifyComment=Lb});var of=E(Hr=>{"use strict";var Db="flow",Zo="block",us="quoted";function Bb(r,e,t="flow",{indentAtStart:n,lineWidth:s=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!s||s<0)return r;s<i&&(i=0);let c=Math.max(1+i,1+s-e.length);if(r.length<=c)return r;let l=[],f={},u=s-e.length;typeof n=="number"&&(n>s-Math.max(2,i)?l.push(0):u=s-n);let d,p,y=!1,m=-1,b=-1,k=-1;t===Zo&&(m=sf(r,m,e.length),m!==-1&&(u=m+c));for(let T;T=r[m+=1];){if(t===us&&T==="\\"){switch(b=m,r[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}k=m}if(T===`
|
|
23
|
+
`)t===Zo&&(m=sf(r,m,e.length)),u=m+e.length+c,d=void 0;else{if(T===" "&&p&&p!==" "&&p!==`
|
|
24
24
|
`&&p!==" "){let P=r[m+1];P&&P!==" "&&P!==`
|
|
25
|
-
`&&P!==" "&&(
|
|
26
|
-
${e}${r.slice(0,C)}`:(t===
|
|
27
|
-
${e}${r.slice(P+1,C)}`)}return x}function
|
|
28
|
-
`);n=e,s=e+1,i=r[s]}return n}Hr.FOLD_BLOCK=
|
|
29
|
-
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function Wr(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(
|
|
25
|
+
`&&P!==" "&&(d=m)}if(m>=u)if(d)l.push(d),u=d+c,d=void 0;else if(t===us){for(;p===" "||p===" ";)p=T,T=r[m+=1],y=!0;let P=m>k+1?m-2:b-1;if(f[P])return r;l.push(P),f[P]=!0,u=P+c,d=void 0}else y=!0}p=T}if(y&&a&&a(),l.length===0)return r;o&&o();let x=r.slice(0,l[0]);for(let T=0;T<l.length;++T){let P=l[T],C=l[T+1]||r.length;P===0?x=`
|
|
26
|
+
${e}${r.slice(0,C)}`:(t===us&&f[P]&&(x+=`${r[P]}\\`),x+=`
|
|
27
|
+
${e}${r.slice(P+1,C)}`)}return x}function sf(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!==`
|
|
28
|
+
`);n=e,s=e+1,i=r[s]}return n}Hr.FOLD_BLOCK=Zo;Hr.FOLD_FLOW=Db;Hr.FOLD_QUOTED=us;Hr.foldFlowLines=Bb});var Yr=E(af=>{"use strict";var be=W(),Xe=of(),ds=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),ps=r=>/^(%|---|\.\.\.)/m.test(r);function jb(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]===`
|
|
29
|
+
`){if(i-o>n)return!0;if(o=i+1,s-o<=n)return!1}return!0}function Wr(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(ps(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let f=t.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length<s)c+=1;else{for(o+=t.slice(a,c)+`
|
|
30
30
|
|
|
31
31
|
`;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)o+=`
|
|
32
|
-
`,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:Xe.foldFlowLines(o,i,Xe.FOLD_QUOTED,
|
|
33
|
-
`)||/[ \t]\n|\n[ \t]/.test(r))return Wr(r,e);let t=e.indent||(
|
|
34
|
-
${t}`)+"'";return e.implicitKey?n:Xe.foldFlowLines(n,t,Xe.FOLD_FLOW,
|
|
32
|
+
`,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:Xe.foldFlowLines(o,i,Xe.FOLD_QUOTED,ds(e,!1))}function ea(r,e){if(e.options.singleQuote===!1||e.implicitKey&&r.includes(`
|
|
33
|
+
`)||/[ \t]\n|\n[ \t]/.test(r))return Wr(r,e);let t=e.indent||(ps(r)?" ":""),n="'"+r.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
34
|
+
${t}`)+"'";return e.implicitKey?n:Xe.foldFlowLines(n,t,Xe.FOLD_FLOW,ds(e,!1))}function Zt(r,e){let{singleQuote:t}=e.options,n;if(t===!1)n=Wr;else{let s=r.includes('"'),i=r.includes("'");s&&!i?n=ea:i&&!s?n=Wr:n=t?ea:Wr}return n(r,e)}var ta;try{ta=new RegExp(`(^|(?<!
|
|
35
35
|
))
|
|
36
36
|
+(?!
|
|
37
|
-
|$)`,"g")}catch{
|
|
37
|
+
|$)`,"g")}catch{ta=/\n+(?!\n|$)/g}function fs({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 Zt(t,n);let l=n.indent||(n.forceBlockIndent||ps(t)?" ":""),f=o==="literal"?!0:o==="folded"||e===be.Scalar.BLOCK_FOLDED?!1:e===be.Scalar.BLOCK_LITERAL?!0:!jb(t,c,l.length);if(!t)return f?`|
|
|
38
38
|
`:`>
|
|
39
|
-
`;let u,
|
|
40
|
-
`&&C!==" "&&C!==" ")break}let p=t.substring(
|
|
39
|
+
`;let u,d;for(d=t.length;d>0;--d){let C=t[d-1];if(C!==`
|
|
40
|
+
`&&C!==" "&&C!==" ")break}let p=t.substring(d),y=p.indexOf(`
|
|
41
41
|
`);y===-1?u="-":t===p||y!==p.length-1?(u="+",i&&i()):u="",p&&(t=t.slice(0,-p.length),p[p.length-1]===`
|
|
42
|
-
`&&(p=p.slice(0,-1)),p=p.replace(
|
|
43
|
-
`)k=b;else break}let x=t.substring(0,k<b?k+1:b);x&&(t=t.substring(x.length),x=x.replace(/\n+/g,`$&${l}`));let P=(m?l?"2":"1":"")+u;if(r&&(P+=" "+a(r.replace(/ ?[\r\n]+/g," ")),s&&s()),!
|
|
44
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),O=!1,R=
|
|
42
|
+
`&&(p=p.slice(0,-1)),p=p.replace(ta,`$&${l}`));let m=!1,b,k=-1;for(b=0;b<t.length;++b){let C=t[b];if(C===" ")m=!0;else if(C===`
|
|
43
|
+
`)k=b;else break}let x=t.substring(0,k<b?k+1:b);x&&(t=t.substring(x.length),x=x.replace(/\n+/g,`$&${l}`));let P=(m?l?"2":"1":"")+u;if(r&&(P+=" "+a(r.replace(/ ?[\r\n]+/g," ")),s&&s()),!f){let C=t.replace(/\n+/g,`
|
|
44
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),O=!1,R=ds(n,!0);o!=="folded"&&e!==be.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{O=!0});let h=Xe.foldFlowLines(`${x}${C}${p}`,l,Xe.FOLD_BLOCK,R);if(!O)return`>${P}
|
|
45
45
|
${l}${h}`}return t=t.replace(/\n+/g,`$&${l}`),`|${P}
|
|
46
|
-
${l}${x}${t}${p}`}function
|
|
47
|
-
`)||
|
|
48
|
-
`)?
|
|
49
|
-
`))return
|
|
50
|
-
${c}`);if(o){let
|
|
51
|
-
${e.indent}${a}`:a}
|
|
52
|
-
${a}:`):(b=`${b}:`,
|
|
46
|
+
${l}${x}${t}${p}`}function Fb(r,e,t,n){let{type:s,value:i}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:f}=e;if(a&&i.includes(`
|
|
47
|
+
`)||f&&/[[\]{},]/.test(i))return Zt(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||f||!i.includes(`
|
|
48
|
+
`)?Zt(i,e):fs(r,e,t,n);if(!a&&!f&&s!==be.Scalar.PLAIN&&i.includes(`
|
|
49
|
+
`))return fs(r,e,t,n);if(ps(i)){if(c==="")return e.forceBlockIndent=!0,fs(r,e,t,n);if(a&&c===l)return Zt(i,e)}let u=i.replace(/\n+/g,`$&
|
|
50
|
+
${c}`);if(o){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(u),{compat:p,tags:y}=e.doc.schema;if(y.some(d)||p?.some(d))return Zt(i,e)}return a?u:Xe.foldFlowLines(u,c,Xe.FOLD_FLOW,ds(e,!1))}function qb(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!==be.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=be.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case be.Scalar.BLOCK_FOLDED:case be.Scalar.BLOCK_LITERAL:return s||i?Zt(o.value,e):fs(o,e,t,n);case be.Scalar.QUOTE_DOUBLE:return Wr(o.value,e);case be.Scalar.QUOTE_SINGLE:return ea(o.value,e);case be.Scalar.PLAIN:return Fb(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=e.options,d=s&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}af.stringifyString=qb});var Vr=E(ra=>{"use strict";var Ub=ss(),Ze=j(),Jb=Kr(),Kb=Yr();function Hb(r,e){let t=Object.assign({blockQuote:!0,commentString:Jb.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 Wb(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(Ze.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 Yb(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],i=(Ze.isScalar(r)||Ze.isCollection(r))&&r.anchor;i&&Ub.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 Vb(r,e,t,n){if(Ze.isPair(r))return r.toString(e,t,n);if(Ze.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=Ze.isNode(r)?r:e.doc.createNode(r,{onTagObj:c=>s=c});s??(s=Wb(e.doc.schema.tags,i));let o=Yb(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):Ze.isScalar(i)?Kb.stringifyString(i,e,t,n):i.toString(e,t,n);return o?Ze.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
51
|
+
${e.indent}${a}`:a}ra.createStringifyContext=Hb;ra.stringify=Vb});var ff=E(uf=>{"use strict";var De=j(),cf=W(),lf=Vr(),Gr=Kr();function Gb({key:r,value:e},t,n,s){let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=t,d=De.isNode(r)&&r.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(De.isCollection(r)||!De.isNode(r)&&typeof r=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let p=!u&&(!r||d&&e==null&&!t.inFlow||De.isCollection(r)||(De.isScalar(r)?r.type===cf.Scalar.BLOCK_FOLDED||r.type===cf.Scalar.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!i),indent:a+c});let y=!1,m=!1,b=lf.stringify(r,t,()=>y=!0,()=>m=!0);if(!p&&!t.inFlow&&b.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 y&&n&&n(),b===""?"?":p?`? ${b}`:b}else if(i&&!u||e==null&&p)return b=`? ${b}`,d&&!y?b+=Gr.lineComment(b,t.indent,l(d)):m&&s&&s(),b;y&&(d=null),p?(d&&(b+=Gr.lineComment(b,t.indent,l(d))),b=`? ${b}
|
|
52
|
+
${a}:`):(b=`${b}:`,d&&(b+=Gr.lineComment(b,t.indent,l(d))));let k,x,T;De.isNode(e)?(k=!!e.spaceBefore,x=e.commentBefore,T=e.comment):(k=!1,x=null,T=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!d&&De.isScalar(e)&&(t.indentAtStart=b.length+1),m=!1,!f&&c.length>=2&&!t.inFlow&&!p&&De.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let P=!1,C=lf.stringify(e,t,()=>P=!0,()=>m=!0),O=" ";if(d||k||x){if(O=k?`
|
|
53
53
|
`:"",x){let R=l(x);O+=`
|
|
54
54
|
${Gr.indentComment(R,t.indent)}`}C===""&&!t.inFlow?O===`
|
|
55
55
|
`&&T&&(O=`
|
|
56
56
|
|
|
57
57
|
`):O+=`
|
|
58
|
-
${t.indent}`}else if(!p&&
|
|
59
|
-
`),S=h!==-1,I=t.inFlow??e.flow??e.items.length===0;if(S||!I){let
|
|
58
|
+
${t.indent}`}else if(!p&&De.isCollection(e)){let R=C[0],h=C.indexOf(`
|
|
59
|
+
`),S=h!==-1,I=t.inFlow??e.flow??e.items.length===0;if(S||!I){let D=!1;if(S&&(R==="&"||R==="!")){let N=C.indexOf(" ");R==="&"&&N!==-1&&N<h&&C[N+1]==="!"&&(N=C.indexOf(" ",N+1)),(N===-1||h<N)&&(D=!0)}D||(O=`
|
|
60
60
|
${t.indent}`)}}else(C===""||C[0]===`
|
|
61
|
-
`)&&(O="");return b+=O+C,t.inFlow?P&&n&&n():T&&!P?b+=Gr.lineComment(b,t.indent,l(T)):m&&s&&s(),b}
|
|
61
|
+
`)&&(O="");return b+=O+C,t.inFlow?P&&n&&n():T&&!P?b+=Gr.lineComment(b,t.indent,l(T)):m&&s&&s(),b}uf.stringifyPair=Gb});var sa=E(na=>{"use strict";var df=Gn("process");function zb(r,...e){r==="debug"&&console.log(...e)}function Qb(r,e){(r==="debug"||r==="warn")&&(typeof df.emitWarning=="function"?df.emitWarning(e):console.warn(e))}na.debug=zb;na.warn=Qb});var ys=E(gs=>{"use strict";var zr=j(),pf=W(),ms="<<",hs={identify:r=>r===ms||typeof r=="symbol"&&r.description===ms,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new pf.Scalar(Symbol(ms)),{addToJSMap:mf}),stringify:()=>ms},Xb=(r,e)=>(hs.identify(e)||zr.isScalar(e)&&(!e.type||e.type===pf.Scalar.PLAIN)&&hs.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===hs.tag&&t.default);function mf(r,e,t){if(t=r&&zr.isAlias(t)?t.resolve(r.doc):t,zr.isSeq(t))for(let n of t.items)ia(r,e,n);else if(Array.isArray(t))for(let n of t)ia(r,e,n);else ia(r,e,t)}function ia(r,e,t){let n=r&&zr.isAlias(t)?t.resolve(r.doc):t;if(!zr.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}gs.addMergeToJSMap=mf;gs.isMergeKey=Xb;gs.merge=hs});var aa=E(yf=>{"use strict";var Zb=sa(),hf=ys(),ew=Vr(),gf=j(),oa=ze();function tw(r,e,{key:t,value:n}){if(gf.isNode(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(hf.isMergeKey(r,t))hf.addMergeToJSMap(r,e,n);else{let s=oa.toJS(t,"",r);if(e instanceof Map)e.set(s,oa.toJS(n,s,r));else if(e instanceof Set)e.add(s);else{let i=rw(t,s,r),o=oa.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 rw(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(gf.isNode(r)&&t?.doc){let n=ew.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)+'..."'),Zb.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)}yf.addPairToJSMap=tw});var et=E(ca=>{"use strict";var bf=Jr(),nw=ff(),sw=aa(),bs=j();function iw(r,e,t){let n=bf.createNode(r,void 0,t),s=bf.createNode(e,void 0,t);return new ws(n,s)}var ws=class r{constructor(e,t=null){Object.defineProperty(this,bs.NODE_TYPE,{value:bs.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return bs.isNode(t)&&(t=t.clone(e)),bs.isNode(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return sw.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?nw.stringifyPair(this,e,t,n):JSON.stringify(this)}};ca.Pair=ws;ca.createPair=iw});var la=E(vf=>{"use strict";var xt=j(),wf=Vr(),vs=Kr();function ow(r,e,t){return(e.inFlow??r.flow?cw:aw)(r,e,t)}function aw({comment:r,items:e},t,{blockItemPrefix:n,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,f=Object.assign({},t,{indent:i,type:null}),u=!1,d=[];for(let y=0;y<e.length;++y){let m=e[y],b=null;if(xt.isNode(m))!u&&m.spaceBefore&&d.push(""),Ss(t,d,m.commentBefore,u),m.comment&&(b=m.comment);else if(xt.isPair(m)){let x=xt.isNode(m.key)?m.key:null;x&&(!u&&x.spaceBefore&&d.push(""),Ss(t,d,x.commentBefore,u))}u=!1;let k=wf.stringify(m,f,()=>b=null,()=>u=!0);b&&(k+=vs.lineComment(k,i,l(b))),u&&b&&(u=!1),d.push(n+k)}let p;if(d.length===0)p=s.start+s.end;else{p=d[0];for(let y=1;y<d.length;++y){let m=d[y];p+=m?`
|
|
62
62
|
${c}${m}`:`
|
|
63
63
|
`}}return r?(p+=`
|
|
64
|
-
`+
|
|
65
|
-
`))&&(l=!0),u.push(k),
|
|
64
|
+
`+vs.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function cw({items:r},e,{flowChars:t,itemIndent:n}){let{indent:s,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let y=0;y<r.length;++y){let m=r[y],b=null;if(xt.isNode(m))m.spaceBefore&&u.push(""),Ss(e,u,m.commentBefore,!1),m.comment&&(b=m.comment);else if(xt.isPair(m)){let x=xt.isNode(m.key)?m.key:null;x&&(x.spaceBefore&&u.push(""),Ss(e,u,x.commentBefore,!1),x.comment&&(l=!0));let T=xt.isNode(m.value)?m.value:null;T?(T.comment&&(b=T.comment),T.commentBefore&&(l=!0)):m.value==null&&x?.comment&&(b=x.comment)}b&&(l=!0);let k=wf.stringify(m,c,()=>b=null);y<r.length-1&&(k+=","),b&&(k+=vs.lineComment(k,n,a(b))),!l&&(u.length>f||k.includes(`
|
|
65
|
+
`))&&(l=!0),u.push(k),f=u.length}let{start:d,end:p}=t;if(u.length===0)return d+p;if(!l){let y=u.reduce((m,b)=>m+b.length+2,2);l=e.options.lineWidth>0&&y>e.options.lineWidth}if(l){let y=d;for(let m of u)y+=m?`
|
|
66
66
|
${i}${s}${m}`:`
|
|
67
67
|
`;return`${y}
|
|
68
|
-
${s}${p}`}else return`${
|
|
69
|
-
`:" ")}return
|
|
68
|
+
${s}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function Ss({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=vs.indentComment(e(n),r);t.push(i.trimStart())}}vf.stringifyCollection=ow});var rt=E(fa=>{"use strict";var lw=la(),uw=aa(),fw=cs(),tt=j(),ks=et(),dw=W();function Qr(r,e){let t=tt.isScalar(e)?e.value:e;for(let n of r)if(tt.isPair(n)&&(n.key===e||n.key===t||tt.isScalar(n.key)&&n.key.value===t))return n}var ua=class extends fw.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(tt.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(ks.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;tt.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new ks.Pair(e,e?.value):n=new ks.Pair(e.key,e.value);let s=Qr(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);tt.isScalar(s.value)&&dw.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=Qr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=Qr(this.items,e)?.value;return(!t&&tt.isScalar(s)?s.value:s)??void 0}has(e){return!!Qr(this.items,e)}set(e,t){this.add(new ks.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)uw.addPairToJSMap(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!tt.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})),lw.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};fa.YAMLMap=ua;fa.findPair=Qr});var er=E(kf=>{"use strict";var pw=j(),Sf=rt(),mw={collection:"map",default:!0,nodeClass:Sf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return pw.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Sf.YAMLMap.from(r,e,t)};kf.map=mw});var nt=E(xf=>{"use strict";var hw=Jr(),gw=la(),yw=cs(),Es=j(),bw=W(),ww=ze(),da=class extends yw.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Es.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=xs(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=xs(e);if(typeof n!="number")return;let s=this.items[n];return!t&&Es.isScalar(s)?s.value:s}has(e){let t=xs(e);return typeof t=="number"&&t<this.items.length}set(e,t){let n=xs(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[n];Es.isScalar(s)&&bw.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(ww.toJS(i,String(s++),t));return n}toString(e,t,n){return e?gw.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(hw.createNode(a,void 0,n))}}return i}};function xs(r){let e=Es.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}xf.YAMLSeq=da});var tr=E(Af=>{"use strict";var vw=j(),Ef=nt(),Sw={collection:"seq",default:!0,nodeClass:Ef.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return vw.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Ef.YAMLSeq.from(r,e,t)};Af.seq=Sw});var Xr=E(Tf=>{"use strict";var kw=Yr(),xw={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),kw.stringifyString(r,e,t,n)}};Tf.string=xw});var As=E(Cf=>{"use strict";var Pf=W(),Of={identify:r=>r==null,createNode:()=>new Pf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Pf.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&Of.test.test(r)?r:e.options.nullStr};Cf.nullTag=Of});var pa=E(Rf=>{"use strict";var Ew=W(),_f={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new Ew.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&_f.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};Rf.boolTag=_f});var rr=E(Nf=>{"use strict";function Aw({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}Nf.stringifyNumber=Aw});var ha=E(Ts=>{"use strict";var Tw=W(),ma=rr(),Pw={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:ma.stringifyNumber},Ow={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():ma.stringifyNumber(r)}},Cw={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 Tw.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:ma.stringifyNumber};Ts.float=Cw;Ts.floatExp=Ow;Ts.floatNaN=Pw});var ya=E(Os=>{"use strict";var If=rr(),Ps=r=>typeof r=="bigint"||Number.isInteger(r),ga=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function $f(r,e,t){let{value:n}=r;return Ps(n)&&n>=0?t+n.toString(e):If.stringifyNumber(r)}var _w={identify:r=>Ps(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>ga(r,2,8,t),stringify:r=>$f(r,8,"0o")},Rw={identify:Ps,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>ga(r,0,10,t),stringify:If.stringifyNumber},Nw={identify:r=>Ps(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>ga(r,2,16,t),stringify:r=>$f(r,16,"0x")};Os.int=Rw;Os.intHex=Nw;Os.intOct=_w});var Mf=E(Lf=>{"use strict";var Iw=er(),$w=As(),Lw=tr(),Mw=Xr(),Dw=pa(),ba=ha(),wa=ya(),Bw=[Iw.map,Lw.seq,Mw.string,$w.nullTag,Dw.boolTag,wa.intOct,wa.int,wa.intHex,ba.floatNaN,ba.floatExp,ba.float];Lf.schema=Bw});var jf=E(Bf=>{"use strict";var jw=W(),Fw=er(),qw=tr();function Df(r){return typeof r=="bigint"||Number.isInteger(r)}var Cs=({value:r})=>JSON.stringify(r),Uw=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Cs},{identify:r=>r==null,createNode:()=>new jw.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Cs},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Cs},{identify:Df,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})=>Df(r)?r.toString():JSON.stringify(r)},{identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:r=>parseFloat(r),stringify:Cs}],Jw={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Kw=[Fw.map,qw.seq].concat(Uw,Jw);Bf.schema=Kw});var Sa=E(Ff=>{"use strict";var Zr=Gn("buffer"),va=W(),Hw=Yr(),Ww={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof Zr.Buffer=="function")return Zr.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 Zr.Buffer=="function")a=o instanceof Zr.Buffer?o.toString("base64"):Zr.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=va.Scalar.BLOCK_LITERAL),e!==va.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(a.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=a.substr(d,c);a=f.join(e===va.Scalar.BLOCK_LITERAL?`
|
|
69
|
+
`:" ")}return Hw.stringifyString({comment:r,type:e,value:a},n,s,i)}};Ff.binary=Ww});var Ns=E(Rs=>{"use strict";var _s=j(),ka=et(),Yw=W(),Vw=nt();function qf(r,e){if(_s.isSeq(r))for(let t=0;t<r.items.length;++t){let n=r.items[t];if(!_s.isPair(n)){if(_s.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let s=n.items[0]||new ka.Pair(new Yw.Scalar(null));if(n.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${n.commentBefore}
|
|
70
70
|
${s.key.commentBefore}`:n.commentBefore),n.comment){let i=s.value??s.key;i.comment=i.comment?`${n.comment}
|
|
71
|
-
${i.comment}`:n.comment}n=s}r.items[t]=Cs.isPair(n)?n:new wa.Pair(n)}}else e("Expected a sequence for this tag");return r}function jf(r,e,t){let{replacer:n}=t,s=new Uw.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(wa.createPair(a,c,t))}return s}var Jw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Bf,createNode:jf};_s.createPairs=jf;_s.pairs=Jw;_s.resolvePairs=Bf});var ka=E(Sa=>{"use strict";var Ff=j(),va=ze(),en=rt(),Kw=nt(),qf=Rs(),Et=class r extends Kw.YAMLSeq{constructor(){super(),this.add=en.YAMLMap.prototype.add.bind(this),this.delete=en.YAMLMap.prototype.delete.bind(this),this.get=en.YAMLMap.prototype.get.bind(this),this.has=en.YAMLMap.prototype.has.bind(this),this.set=en.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(Ff.isPair(s)?(i=va.toJS(s.key,"",t),o=va.toJS(s.value,i,t)):i=va.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=qf.createPairs(e,t,n),i=new this;return i.items=s.items,i}};Et.tag="tag:yaml.org,2002:omap";var Hw={collection:"seq",identify:r=>r instanceof Map,nodeClass:Et,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=qf.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Ff.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)};Sa.YAMLOMap=Et;Sa.omap=Hw});var Wf=E(xa=>{"use strict";var Uf=W();function Jf({value:r,source:e},t){return e&&(r?Kf:Hf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Kf={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 Uf.Scalar(!0),stringify:Jf},Hf={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 Uf.Scalar(!1),stringify:Jf};xa.falseTag=Hf;xa.trueTag=Kf});var Yf=E(Ns=>{"use strict";var Ww=W(),Ea=nr(),Yw={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:Ea.stringifyNumber},Vw={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():Ea.stringifyNumber(r)}},Gw={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 Ww.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:Ea.stringifyNumber};Ns.float=Gw;Ns.floatExp=Vw;Ns.floatNaN=Yw});var Gf=E(rn=>{"use strict";var Vf=nr(),tn=r=>typeof r=="bigint"||Number.isInteger(r);function Is(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 Aa(r,e,t){let{value:n}=r;if(tn(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return Vf.stringifyNumber(r)}var zw={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Is(r,2,2,t),stringify:r=>Aa(r,2,"0b")},Qw={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Is(r,1,8,t),stringify:r=>Aa(r,8,"0")},Xw={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Is(r,0,10,t),stringify:Vf.stringifyNumber},Zw={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Is(r,2,16,t),stringify:r=>Aa(r,16,"0x")};rn.int=Xw;rn.intBin=zw;rn.intHex=Zw;rn.intOct=Qw});var Pa=E(Ta=>{"use strict";var Ms=j(),$s=et(),Ls=rt(),At=class r extends Ls.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;Ms.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new $s.Pair(e.key,null):t=new $s.Pair(e,null),Ls.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=Ls.findPair(this.items,e);return!t&&Ms.isPair(n)?Ms.isScalar(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Ls.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new $s.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($s.createPair(o,null,n));return i}};At.tag="tag:yaml.org,2002:set";var ev={collection:"map",identify:r=>r instanceof Set,nodeClass:At,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>At.from(r,e,t),resolve(r,e){if(Ms.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new At,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Ta.YAMLSet=At;Ta.set=ev});var Ca=E(Ds=>{"use strict";var tv=nr();function Oa(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 zf(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return tv.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 rv={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})=>Oa(r,t),stringify:zf},nv={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=>Oa(r,!1),stringify:zf},Qf={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(Qf.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=Oa(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$/,"")??""};Ds.floatTime=nv;Ds.intTime=rv;Ds.timestamp=Qf});var ed=E(Zf=>{"use strict";var sv=tr(),iv=Es(),ov=rr(),av=Xr(),cv=ba(),Xf=Wf(),_a=Yf(),Bs=Gf(),lv=gs(),uv=ka(),fv=Rs(),dv=Pa(),Ra=Ca(),pv=[sv.map,ov.seq,av.string,iv.nullTag,Xf.trueTag,Xf.falseTag,Bs.intBin,Bs.intOct,Bs.int,Bs.intHex,_a.floatNaN,_a.floatExp,_a.float,cv.binary,lv.merge,uv.omap,fv.pairs,dv.set,Ra.intTime,Ra.floatTime,Ra.timestamp];Zf.schema=pv});var ud=E($a=>{"use strict";var sd=tr(),mv=Es(),id=rr(),hv=Xr(),gv=ua(),Na=da(),Ia=ma(),yv=If(),bv=Mf(),od=ba(),nn=gs(),ad=ka(),cd=Rs(),td=ed(),ld=Pa(),js=Ca(),rd=new Map([["core",yv.schema],["failsafe",[sd.map,id.seq,hv.string]],["json",bv.schema],["yaml11",td.schema],["yaml-1.1",td.schema]]),nd={binary:od.binary,bool:gv.boolTag,float:Na.float,floatExp:Na.floatExp,floatNaN:Na.floatNaN,floatTime:js.floatTime,int:Ia.int,intHex:Ia.intHex,intOct:Ia.intOct,intTime:js.intTime,map:sd.map,merge:nn.merge,null:mv.nullTag,omap:ad.omap,pairs:cd.pairs,seq:id.seq,set:ld.set,timestamp:js.timestamp},wv={"tag:yaml.org,2002:binary":od.binary,"tag:yaml.org,2002:merge":nn.merge,"tag:yaml.org,2002:omap":ad.omap,"tag:yaml.org,2002:pairs":cd.pairs,"tag:yaml.org,2002:set":ld.set,"tag:yaml.org,2002:timestamp":js.timestamp};function vv(r,e,t){let n=rd.get(e);if(n&&!r)return t&&!n.includes(nn.merge)?n.concat(nn.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(rd.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(nn.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?nd[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(nd).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},[])}$a.coreKnownTags=wv;$a.getTags=vv});var Da=E(fd=>{"use strict";var La=j(),Sv=tr(),kv=rr(),xv=Xr(),Fs=ud(),Ev=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,Ma=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Fs.getTags(e,"compat"):e?Fs.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?Fs.coreKnownTags:{},this.tags=Fs.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,La.MAP,{value:Sv.map}),Object.defineProperty(this,La.SCALAR,{value:xv.string}),Object.defineProperty(this,La.SEQ,{value:kv.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Ev:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};fd.Schema=Ma});var pd=E(dd=>{"use strict";var Av=j(),Ba=Vr(),sn=Kr();function Tv(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=Ba.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(sn.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(Av.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(sn.indentComment(d,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Ba.stringify(r.contents,s,()=>a=null,c);a&&(l+=sn.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Ba.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
71
|
+
${i.comment}`:n.comment}n=s}r.items[t]=_s.isPair(n)?n:new ka.Pair(n)}}else e("Expected a sequence for this tag");return r}function Uf(r,e,t){let{replacer:n}=t,s=new Vw.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(ka.createPair(a,c,t))}return s}var Gw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:qf,createNode:Uf};Rs.createPairs=Uf;Rs.pairs=Gw;Rs.resolvePairs=qf});var Aa=E(Ea=>{"use strict";var Jf=j(),xa=ze(),en=rt(),zw=nt(),Kf=Ns(),Et=class r extends zw.YAMLSeq{constructor(){super(),this.add=en.YAMLMap.prototype.add.bind(this),this.delete=en.YAMLMap.prototype.delete.bind(this),this.get=en.YAMLMap.prototype.get.bind(this),this.has=en.YAMLMap.prototype.has.bind(this),this.set=en.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(Jf.isPair(s)?(i=xa.toJS(s.key,"",t),o=xa.toJS(s.value,i,t)):i=xa.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=Kf.createPairs(e,t,n),i=new this;return i.items=s.items,i}};Et.tag="tag:yaml.org,2002:omap";var Qw={collection:"seq",identify:r=>r instanceof Map,nodeClass:Et,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Kf.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Jf.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)};Ea.YAMLOMap=Et;Ea.omap=Qw});var Gf=E(Ta=>{"use strict";var Hf=W();function Wf({value:r,source:e},t){return e&&(r?Yf:Vf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Yf={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 Hf.Scalar(!0),stringify:Wf},Vf={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 Hf.Scalar(!1),stringify:Wf};Ta.falseTag=Vf;Ta.trueTag=Yf});var zf=E(Is=>{"use strict";var Xw=W(),Pa=rr(),Zw={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:Pa.stringifyNumber},ev={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():Pa.stringifyNumber(r)}},tv={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 Xw.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:Pa.stringifyNumber};Is.float=tv;Is.floatExp=ev;Is.floatNaN=Zw});var Xf=E(rn=>{"use strict";var Qf=rr(),tn=r=>typeof r=="bigint"||Number.isInteger(r);function $s(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 Oa(r,e,t){let{value:n}=r;if(tn(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return Qf.stringifyNumber(r)}var rv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>$s(r,2,2,t),stringify:r=>Oa(r,2,"0b")},nv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>$s(r,1,8,t),stringify:r=>Oa(r,8,"0")},sv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>$s(r,0,10,t),stringify:Qf.stringifyNumber},iv={identify:tn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>$s(r,2,16,t),stringify:r=>Oa(r,16,"0x")};rn.int=sv;rn.intBin=rv;rn.intHex=iv;rn.intOct=nv});var _a=E(Ca=>{"use strict";var Ds=j(),Ls=et(),Ms=rt(),At=class r extends Ms.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;Ds.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Ls.Pair(e.key,null):t=new Ls.Pair(e,null),Ms.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let n=Ms.findPair(this.items,e);return!t&&Ds.isPair(n)?Ds.isScalar(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Ms.findPair(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Ls.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(Ls.createPair(o,null,n));return i}};At.tag="tag:yaml.org,2002:set";var ov={collection:"map",identify:r=>r instanceof Set,nodeClass:At,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>At.from(r,e,t),resolve(r,e){if(Ds.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new At,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Ca.YAMLSet=At;Ca.set=ov});var Na=E(Bs=>{"use strict";var av=rr();function Ra(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 Zf(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return av.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 cv={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})=>Ra(r,t),stringify:Zf},lv={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=>Ra(r,!1),stringify:Zf},ed={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(ed.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,s,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,s,i||0,o||0,a||0,c),f=e[8];if(f&&f!=="Z"){let u=Ra(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Bs.floatTime=lv;Bs.intTime=cv;Bs.timestamp=ed});var nd=E(rd=>{"use strict";var uv=er(),fv=As(),dv=tr(),pv=Xr(),mv=Sa(),td=Gf(),Ia=zf(),js=Xf(),hv=ys(),gv=Aa(),yv=Ns(),bv=_a(),$a=Na(),wv=[uv.map,dv.seq,pv.string,fv.nullTag,td.trueTag,td.falseTag,js.intBin,js.intOct,js.int,js.intHex,Ia.floatNaN,Ia.floatExp,Ia.float,mv.binary,hv.merge,gv.omap,yv.pairs,bv.set,$a.intTime,$a.floatTime,$a.timestamp];rd.schema=wv});var pd=E(Da=>{"use strict";var ad=er(),vv=As(),cd=tr(),Sv=Xr(),kv=pa(),La=ha(),Ma=ya(),xv=Mf(),Ev=jf(),ld=Sa(),nn=ys(),ud=Aa(),fd=Ns(),sd=nd(),dd=_a(),Fs=Na(),id=new Map([["core",xv.schema],["failsafe",[ad.map,cd.seq,Sv.string]],["json",Ev.schema],["yaml11",sd.schema],["yaml-1.1",sd.schema]]),od={binary:ld.binary,bool:kv.boolTag,float:La.float,floatExp:La.floatExp,floatNaN:La.floatNaN,floatTime:Fs.floatTime,int:Ma.int,intHex:Ma.intHex,intOct:Ma.intOct,intTime:Fs.intTime,map:ad.map,merge:nn.merge,null:vv.nullTag,omap:ud.omap,pairs:fd.pairs,seq:cd.seq,set:dd.set,timestamp:Fs.timestamp},Av={"tag:yaml.org,2002:binary":ld.binary,"tag:yaml.org,2002:merge":nn.merge,"tag:yaml.org,2002:omap":ud.omap,"tag:yaml.org,2002:pairs":fd.pairs,"tag:yaml.org,2002:set":dd.set,"tag:yaml.org,2002:timestamp":Fs.timestamp};function Tv(r,e,t){let n=id.get(e);if(n&&!r)return t&&!n.includes(nn.merge)?n.concat(nn.merge):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(id.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(nn.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?od[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(od).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}Da.coreKnownTags=Av;Da.getTags=Tv});var Fa=E(md=>{"use strict";var Ba=j(),Pv=er(),Ov=tr(),Cv=Xr(),qs=pd(),_v=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,ja=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?qs.getTags(e,"compat"):e?qs.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?qs.coreKnownTags:{},this.tags=qs.getTags(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Ba.MAP,{value:Pv.map}),Object.defineProperty(this,Ba.SCALAR,{value:Cv.string}),Object.defineProperty(this,Ba.SEQ,{value:Ov.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?_v:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};md.Schema=ja});var gd=E(hd=>{"use strict";var Rv=j(),qa=Vr(),sn=Kr();function Nv(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=qa.createStringifyContext(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=i(r.commentBefore);t.unshift(sn.indentComment(c,""))}let o=!1,a=null;if(r.contents){if(Rv.isNode(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let f=i(r.contents.commentBefore);t.push(sn.indentComment(f,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=qa.stringify(r.contents,s,()=>a=null,c);a&&(l+=sn.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(qa.stringify(r.contents,s));if(r.directives?.docEnd)if(r.comment){let c=i(r.comment);c.includes(`
|
|
72
72
|
`)?(t.push("..."),t.push(sn.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(sn.indentComment(i(c),"")))}return t.join(`
|
|
73
73
|
`)+`
|
|
74
|
-
`}
|
|
74
|
+
`}hd.stringifyDocument=Nv});var on=E(yd=>{"use strict";var Iv=Ur(),nr=cs(),pe=j(),$v=et(),Lv=ze(),Mv=Fa(),Dv=gd(),Ua=ss(),Bv=Wo(),jv=Jr(),Ja=Ho(),Ka=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,pe.NODE_TYPE,{value:pe.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 Ja.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,{[pe.NODE_TYPE]:{value:pe.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=pe.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){sr(this.contents)&&this.contents.add(e)}addIn(e,t){sr(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=Ua.anchorNames(this);e.anchor=!t||n.has(t)?Ua.findNewAnchor(t||"a",n):t}return new Iv.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 b=x=>typeof x=="number"||x instanceof String||x instanceof Number,k=t.filter(b).map(String);k.length>0&&(t=t.concat(k)),s=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=Ua.createNodeAnchors(this,o||"a"),y={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},m=jv.createNode(e,f,y);return a&&pe.isCollection(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){let s=this.createNode(e,null,n),i=this.createNode(t,null,n);return new $v.Pair(s,i)}delete(e){return sr(this.contents)?this.contents.delete(e):!1}deleteIn(e){return nr.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):sr(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return pe.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return nr.isEmptyPath(e)?!t&&pe.isScalar(this.contents)?this.contents.value:this.contents:pe.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return pe.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return nr.isEmptyPath(e)?this.contents!==void 0:pe.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=nr.collectionFromPath(this.schema,[e],t):sr(this.contents)&&this.contents.set(e,t)}setIn(e,t){nr.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=nr.collectionFromPath(this.schema,Array.from(e),t):sr(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 Ja.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 Ja.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 Mv.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=Lv.toJS(this.contents,t??"",a);if(typeof i=="function")for(let{count:l,res:f}of a.anchors.values())i(f,l);return typeof o=="function"?Bv.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 Dv.stringifyDocument(this,e)}};function sr(r){if(pe.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}yd.Document=Ka});var ln=E(cn=>{"use strict";var an=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},Ha=class extends an{constructor(e,t,n){super("YAMLParseError",e,t,n)}},Wa=class extends an{constructor(e,t,n){super("YAMLWarning",e,t,n)}},Fv=(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
|
|
75
75
|
`),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+=`:
|
|
76
76
|
|
|
77
77
|
${o}
|
|
78
78
|
${l}
|
|
79
|
-
`}};cn.YAMLError=an;cn.YAMLParseError=
|
|
80
|
-
`))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(
|
|
81
|
-
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||
|
|
82
|
-
`+T.comment:x.comment=T.comment);let P=new
|
|
83
|
-
`+O.comment:l.comment=O.comment),u=O.end;continue}!o&&t.options.strict&&
|
|
84
|
-
`+R:h.comment=R,O.comment=O.comment.substring(R.length+1)}}if(!o&&!P&&!O.found){let R=C?r(t,C,O,s):e(t,O.end,P,null,O,s);l.items.push(R),u=R.range[2],
|
|
85
|
-
`+S.comment:h.comment=S.comment);let
|
|
86
|
-
`+b.comment:l.comment=b.comment),l.range=[n.offset,m,b.offset]}else l.range=[n.offset,m,m];return l}
|
|
87
|
-
`.repeat(Math.max(1,o.length-1)):"",b=n+s.length;return e.source&&(b+=e.source.length),{value:m,type:i,comment:s.comment,range:[n,b,b]}}let c=e.indent+s.indent,l=e.offset+s.length,
|
|
88
|
-
`;for(let m=
|
|
89
|
-
`):b.length>c||k[0]===" "?(
|
|
90
|
-
`:!p&&
|
|
91
|
-
`&&(
|
|
92
|
-
|
|
93
|
-
`),u+=
|
|
94
|
-
`,p=!0):k===""?
|
|
79
|
+
`}};cn.YAMLError=an;cn.YAMLParseError=Ha;cn.YAMLWarning=Wa;cn.prettifyError=Fv});var un=E(bd=>{"use strict";function qv(r,{flow:e,indicator:t,next:n,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,f=a,u="",d="",p=!1,y=!1,m=null,b=null,k=null,x=null,T=null,P=null,C=null;for(let h of r)switch(y&&(h.type!=="space"&&h.type!=="newline"&&h.type!=="comma"&&i(h.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),m&&(l&&h.type!=="comment"&&h.type!=="newline"&&i(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),h.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&h.source.includes(" ")&&(m=h),f=!0;break;case"comment":{f||i(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let S=h.source.substring(1)||" ";u?u+=d+S:u=S,d="",l=!1;break}case"newline":l?u?u+=h.source:(!P||t!=="seq-item-ind")&&(c=!0):d+=h.source,l=!0,p=!0,(b||k)&&(x=h),f=!0;break;case"anchor":b&&i(h,"MULTIPLE_ANCHORS","A node can have at most one anchor"),h.source.endsWith(":")&&i(h.offset+h.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),b=h,C??(C=h.offset),l=!1,f=!1,y=!0;break;case"tag":{k&&i(h,"MULTIPLE_TAGS","A node can have at most one tag"),k=h,C??(C=h.offset),l=!1,f=!1,y=!0;break}case t:(b||k)&&i(h,"BAD_PROP_ORDER",`Anchors and tags must be after the ${h.source} indicator`),P&&i(h,"UNEXPECTED_TOKEN",`Unexpected ${h.source} in ${e??"collection"}`),P=h,l=t==="seq-item-ind"||t==="explicit-key-ind",f=!1;break;case"comma":if(e){T&&i(h,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),T=h,l=!1,f=!1;break}default:i(h,"UNEXPECTED_TOKEN",`Unexpected ${h.type} token`),l=!1,f=!1}let O=r[r.length-1],R=O?O.offset+O.source.length:s;return y&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&i(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&i(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:T,found:P,spaceBefore:c,comment:u,hasNewline:p,anchor:b,tag:k,newlineAfterProp:x,end:R,start:C??R}}bd.resolveProps=qv});var Us=E(wd=>{"use strict";function Ya(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(`
|
|
80
|
+
`))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(Ya(e.key)||Ya(e.value))return!0}return!1;default:return!0}}wd.containsNewline=Ya});var Va=E(vd=>{"use strict";var Uv=Us();function Jv(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&Uv.containsNewline(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}vd.flowIndentCheck=Jv});var Ga=E(kd=>{"use strict";var Sd=j();function Kv(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(i,o)=>i===o||Sd.isScalar(i)&&Sd.isScalar(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}kd.mapIncludes=Kv});var Od=E(Pd=>{"use strict";var xd=et(),Hv=rt(),Ed=un(),Wv=Us(),Ad=Va(),Yv=Ga(),Td="All mapping items must start at the same column";function Vv({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Hv.YAMLMap,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let f of n.items){let{start:u,key:d,sep:p,value:y}=f,m=Ed.resolveProps(u,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0}),b=!m.found;if(b){if(d&&(d.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==n.indent&&s(c,"BAD_INDENT",Td)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=`
|
|
81
|
+
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||Wv.containsNewline(d))&&s(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==n.indent&&s(c,"BAD_INDENT",Td);t.atKey=!0;let k=m.end,x=d?r(t,d,m,s):e(t,k,u,null,m,s);t.schema.compat&&Ad.flowIndentCheck(n.indent,d,s),t.atKey=!1,Yv.mapIncludes(t,a.items,x)&&s(k,"DUPLICATE_KEY","Map keys must be unique");let T=Ed.resolveProps(p??[],{indicator:"map-value-ind",next:y,offset:x.range[2],onError:s,parentIndent:n.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=T.end,T.found){b&&(y?.type==="block-map"&&!T.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&m.start<T.found.offset-1024&&s(x.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let P=y?r(t,y,T,s):e(t,c,p,null,T,s);t.schema.compat&&Ad.flowIndentCheck(n.indent,y,s),c=P.range[2];let C=new xd.Pair(x,P);t.options.keepSourceTokens&&(C.srcToken=f),a.items.push(C)}else{b&&s(x.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),T.comment&&(x.comment?x.comment+=`
|
|
82
|
+
`+T.comment:x.comment=T.comment);let P=new xd.Pair(x);t.options.keepSourceTokens&&(P.srcToken=f),a.items.push(P)}}return l&&l<c&&s(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,l??c],a}Pd.resolveBlockMap=Vv});var _d=E(Cd=>{"use strict";var Gv=nt(),zv=un(),Qv=Va();function Xv({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Gv.YAMLSeq,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=n.offset,l=null;for(let{start:f,value:u}of n.items){let d=zv.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?s(d.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let p=u?r(t,u,d,s):e(t,d.end,f,null,d,s);t.schema.compat&&Qv.flowIndentCheck(n.indent,u,s),c=p.range[2],a.items.push(p)}return a.range=[n.offset,c,l??c],a}Cd.resolveBlockSeq=Xv});var ir=E(Rd=>{"use strict";function Zv(r,e,t,n){let s="";if(r){let i=!1,o="";for(let a of r){let{source:c,type:l}=a;switch(l){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";s?s+=o+f:s=f,o="";break}case"newline":s&&(o+=c),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:s,offset:e}}Rd.resolveEnd=Zv});var Ld=E($d=>{"use strict";var eS=j(),tS=et(),Nd=rt(),rS=nt(),nS=ir(),Id=un(),sS=Us(),iS=Ga(),za="Block collections are not allowed within flow collections",Qa=r=>r&&(r.type==="block-map"||r.type==="block-seq");function oS({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?Nd.YAMLMap:rS.YAMLSeq),l=new c(t.schema);l.flow=!0;let f=t.atRoot;f&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=n.offset+n.start.source.length;for(let b=0;b<n.items.length;++b){let k=n.items[b],{start:x,key:T,sep:P,value:C}=k,O=Id.resolveProps(x,{flow:a,indicator:"explicit-key-ind",next:T??P?.[0],offset:u,onError:s,parentIndent:n.indent,startOnNewline:!1});if(!O.found){if(!O.anchor&&!O.tag&&!P&&!C){b===0&&O.comma?s(O.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):b<n.items.length-1&&s(O.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),O.comment&&(l.comment?l.comment+=`
|
|
83
|
+
`+O.comment:l.comment=O.comment),u=O.end;continue}!o&&t.options.strict&&sS.containsNewline(T)&&s(T,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(b===0)O.comma&&s(O.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(O.comma||s(O.start,"MISSING_CHAR",`Missing , between ${a} items`),O.comment){let R="";e:for(let h of x)switch(h.type){case"comma":case"space":break;case"comment":R=h.source.substring(1);break e;default:break e}if(R){let h=l.items[l.items.length-1];eS.isPair(h)&&(h=h.value??h.key),h.comment?h.comment+=`
|
|
84
|
+
`+R:h.comment=R,O.comment=O.comment.substring(R.length+1)}}if(!o&&!P&&!O.found){let R=C?r(t,C,O,s):e(t,O.end,P,null,O,s);l.items.push(R),u=R.range[2],Qa(C)&&s(R.range,"BLOCK_IN_FLOW",za)}else{t.atKey=!0;let R=O.end,h=T?r(t,T,O,s):e(t,R,x,null,O,s);Qa(T)&&s(h.range,"BLOCK_IN_FLOW",za),t.atKey=!1;let S=Id.resolveProps(P??[],{flow:a,indicator:"map-value-ind",next:C,offset:h.range[2],onError:s,parentIndent:n.indent,startOnNewline:!1});if(S.found){if(!o&&!O.found&&t.options.strict){if(P)for(let N of P){if(N===S.found)break;if(N.type==="newline"){s(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}O.start<S.found.offset-1024&&s(S.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else C&&("source"in C&&C.source?.[0]===":"?s(C,"MISSING_CHAR",`Missing space after : in ${a}`):s(S.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let I=C?r(t,C,S,s):S.found?e(t,S.end,P,null,S,s):null;I?Qa(C)&&s(I.range,"BLOCK_IN_FLOW",za):S.comment&&(h.comment?h.comment+=`
|
|
85
|
+
`+S.comment:h.comment=S.comment);let D=new tS.Pair(h,I);if(t.options.keepSourceTokens&&(D.srcToken=k),o){let N=l;iS.mapIncludes(t,N.items,h)&&s(R,"DUPLICATE_KEY","Map keys must be unique"),N.items.push(D)}else{let N=new Nd.YAMLMap(t.schema);N.flow=!0,N.items.push(D);let X=(I??h).range;N.range=[h.range[0],X[1],X[2]],l.items.push(N)}u=I?I.range[2]:S.end}}let d=o?"}":"]",[p,...y]=n.end,m=u;if(p?.source===d)m=p.offset+p.source.length;else{let b=a[0].toUpperCase()+a.substring(1),k=f?`${b} must end with a ${d}`:`${b} in block collection must be sufficiently indented and end with a ${d}`;s(u,f?"MISSING_CHAR":"BAD_INDENT",k),p&&p.source.length!==1&&y.unshift(p)}if(y.length>0){let b=nS.resolveEnd(y,m,t.options.strict,s);b.comment&&(l.comment?l.comment+=`
|
|
86
|
+
`+b.comment:l.comment=b.comment),l.range=[n.offset,m,b.offset]}else l.range=[n.offset,m,m];return l}$d.resolveFlowCollection=oS});var Dd=E(Md=>{"use strict";var aS=j(),cS=W(),lS=rt(),uS=nt(),fS=Od(),dS=_d(),pS=Ld();function Xa(r,e,t,n,s,i){let o=t.type==="block-map"?fS.resolveBlockMap(r,e,t,n,i):t.type==="block-seq"?dS.resolveBlockSeq(r,e,t,n,i):pS.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 mS(r,e,t,n,s){let i=n.tag,o=i?e.directives.tagName(i.source,d=>s(i,"TAG_RESOLVE_FAILED",d)):null;if(t.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=n,y=d&&i?d.offset>i.offset?d:i:d??i;y&&(!p||p.offset<y.offset)&&s(y,"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===lS.YAMLMap.tagName&&a==="map"||o===uS.YAMLSeq.tagName&&a==="seq")return Xa(r,e,t,s,o);let c=e.schema.tags.find(d=>d.tag===o&&d.collection===a);if(!c){let d=e.schema.knownTags[o];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?s(i,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Xa(r,e,t,s,o)}let l=Xa(r,e,t,s,o,c),f=c.resolve?.(l,d=>s(i,"TAG_RESOLVE_FAILED",d),e.options)??l,u=aS.isNode(f)?f:new cS.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Md.composeCollection=mS});var ec=E(Bd=>{"use strict";var Za=W();function hS(r,e,t){let n=e.offset,s=gS(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?Za.Scalar.BLOCK_FOLDED:Za.Scalar.BLOCK_LITERAL,o=e.source?yS(e.source):[],a=o.length;for(let m=o.length-1;m>=0;--m){let b=o[m][1];if(b===""||b==="\r")a=m;else break}if(a===0){let m=s.chomp==="+"&&o.length>0?`
|
|
87
|
+
`.repeat(Math.max(1,o.length-1)):"",b=n+s.length;return e.source&&(b+=e.source.length),{value:m,type:i,comment:s.comment,range:[n,b,b]}}let c=e.indent+s.indent,l=e.offset+s.length,f=0;for(let m=0;m<a;++m){let[b,k]=o[m];if(k===""||k==="\r")s.indent===0&&b.length>c&&(c=b.length);else{b.length<c&&t(l+b.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(c=b.length),f=m,c===0&&!r.atRoot&&t(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=b.length+k.length+1}for(let m=o.length-1;m>=a;--m)o[m][0].length>c&&(a=m+1);let u="",d="",p=!1;for(let m=0;m<f;++m)u+=o[m][0].slice(c)+`
|
|
88
|
+
`;for(let m=f;m<a;++m){let[b,k]=o[m];l+=b.length+k.length+1;let x=k[k.length-1]==="\r";if(x&&(k=k.slice(0,-1)),k&&b.length<c){let P=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;t(l-k.length-(x?2:1),"BAD_INDENT",P),b=""}i===Za.Scalar.BLOCK_LITERAL?(u+=d+b.slice(c)+k,d=`
|
|
89
|
+
`):b.length>c||k[0]===" "?(d===" "?d=`
|
|
90
|
+
`:!p&&d===`
|
|
91
|
+
`&&(d=`
|
|
92
|
+
|
|
93
|
+
`),u+=d+b.slice(c)+k,d=`
|
|
94
|
+
`,p=!0):k===""?d===`
|
|
95
95
|
`?u+=`
|
|
96
|
-
`:
|
|
97
|
-
`:(u+=
|
|
96
|
+
`:d=`
|
|
97
|
+
`:(u+=d+k,d=" ",p=!1)}switch(s.chomp){case"-":break;case"+":for(let m=a;m<o.length;++m)u+=`
|
|
98
98
|
`+o[m][0].slice(c);u[u.length-1]!==`
|
|
99
99
|
`&&(u+=`
|
|
100
100
|
`);break;default:u+=`
|
|
101
|
-
`}let y=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,y,y]}}function
|
|
101
|
+
`}let y=n+s.length+e.source.length;return{value:u,type:i,comment:s.comment,range:[n,y,y]}}function gS({offset:r,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=e[0],i=s[0],o=0,a="",c=-1;for(let d=1;d<s.length;++d){let p=s[d];if(!a&&(p==="-"||p==="+"))a=p;else{let y=Number(p);!o&&y?o=y:c===-1&&(c=r+d)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let l=!1,f="",u=s.length;for(let d=1;d<e.length;++d){let p=e[d];switch(p.type){case"space":l=!0;case"newline":u+=p.source.length;break;case"comment":t&&!l&&n(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,f=p.source.substring(1);break;case"error":n(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let y=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",y);let m=p.source;m&&typeof m=="string"&&(u+=m.length)}}}return{mode:i,indent:o,chomp:a,comment:f,length:u}}function yS(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}Bd.resolveBlockScalar=hS});var rc=E(Fd=>{"use strict";var tc=W(),bS=ir();function wS(r,e,t){let{offset:n,type:s,source:i,end:o}=r,a,c,l=(d,p,y)=>t(n+d,p,y);switch(s){case"scalar":a=tc.Scalar.PLAIN,c=vS(i,l);break;case"single-quoted-scalar":a=tc.Scalar.QUOTE_SINGLE,c=SS(i,l);break;case"double-quoted-scalar":a=tc.Scalar.QUOTE_DOUBLE,c=kS(i,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}let f=n+i.length,u=bS.resolveEnd(o,f,e,t);return{value:c,type:a,comment:u.comment,range:[n,f,u.offset]}}function vS(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}`),jd(r)}function SS(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),jd(r.slice(1,-1)).replace(/''/g,"'")}function jd(r){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
102
102
|
`,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
103
103
|
`,"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===`
|
|
104
104
|
`?s+=i:i=`
|
|
105
|
-
`:(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
|
|
105
|
+
`:(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 kS(r,e){let t="";for(let n=1;n<r.length-1;++n){let s=r[n];if(!(s==="\r"&&r[n+1]===`
|
|
106
106
|
`))if(s===`
|
|
107
|
-
`){let{fold:i,offset:o}=
|
|
107
|
+
`){let{fold:i,offset:o}=xS(r,n);t+=i,n=o}else if(s==="\\"){let i=r[++n],o=ES[i];if(o)t+=o;else if(i===`
|
|
108
108
|
`)for(i=r[n+1];i===" "||i===" ";)i=r[++n+1];else if(i==="\r"&&r[n+1]===`
|
|
109
|
-
`)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+=
|
|
109
|
+
`)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+=AS(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!==`
|
|
110
110
|
`&&!(o==="\r"&&r[n+2]===`
|
|
111
|
-
`)&&(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
|
|
111
|
+
`)&&(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 xS(r,e){let t="",n=r[e+1];for(;(n===" "||n===" "||n===`
|
|
112
112
|
`||n==="\r")&&!(n==="\r"&&r[e+2]!==`
|
|
113
113
|
`);)n===`
|
|
114
114
|
`&&(t+=`
|
|
115
|
-
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var
|
|
116
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
115
|
+
`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var ES={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
116
|
+
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function AS(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)}Fd.resolveFlowScalar=wS});var Jd=E(Ud=>{"use strict";var Tt=j(),qd=W(),TS=ec(),PS=rc();function OS(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?TS.resolveBlockScalar(r,e,n):PS.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[Tt.SCALAR]:c?l=CS(r.schema,s,c,t,n):e.type==="scalar"?l=_S(r,s,e,n):l=r.schema[Tt.SCALAR];let f;try{let u=l.resolve(s,d=>n(t??e,"TAG_RESOLVE_FAILED",d),r.options);f=Tt.isScalar(u)?u:new qd.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);n(t??e,"TAG_RESOLVE_FAILED",d),f=new qd.Scalar(s)}return f.range=a,f.source=s,i&&(f.type=i),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function CS(r,e,t,n,s){if(t==="!")return r[Tt.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[Tt.SCALAR])}function _S({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[Tt.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[Tt.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;i(s,"TAG_RESOLVE_FAILED",f,!0)}}return o}Ud.composeScalar=OS});var Hd=E(Kd=>{"use strict";function RS(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}Kd.emptyScalarPosition=RS});var Vd=E(sc=>{"use strict";var NS=Ur(),IS=j(),$S=Dd(),Wd=Jd(),LS=ir(),MS=Hd(),DS={composeNode:Yd,composeEmptyNode:nc};function Yd(r,e,t,n){let s=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=t,l,f=!0;switch(e.type){case"alias":l=BS(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=Wd.composeScalar(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=$S.composeCollection(DS,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=nc(r,e.offset,void 0,null,t,n),f=!1}}return a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&r.options.stringKeys&&(!IS.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&f&&(l.srcToken=e),l}function nc(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:MS.emptyScalarPosition(e,t,n),indent:-1,source:""},u=Wd.composeScalar(r,f,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=c),u}function BS({options:r},{offset:e,source:t,end:n},s){let i=new NS.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=LS.resolveEnd(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}sc.composeEmptyNode=nc;sc.composeNode=Yd});var Qd=E(zd=>{"use strict";var jS=on(),Gd=Vd(),FS=ir(),qS=un();function US(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new jS.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=qS.resolveProps(n,{indicator:"doc-start",next:s??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Gd.composeNode(l,s,f,o):Gd.composeEmptyNode(l,f.end,n,null,f,o);let u=c.contents.range[2],d=FS.resolveEnd(i,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[t,u,d.offset],c}zd.composeDoc=US});var oc=E(ep=>{"use strict";var JS=Gn("process"),KS=Ho(),HS=on(),fn=ln(),Xd=j(),WS=Qd(),YS=ir();function dn(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 Zd(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?`
|
|
117
117
|
|
|
118
118
|
`:`
|
|
119
|
-
`)+(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
|
|
120
|
-
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(
|
|
119
|
+
`)+(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 ic=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=dn(t);i?this.warnings.push(new fn.YAMLWarning(o,n,s)):this.errors.push(new fn.YAMLParseError(o,n,s))},this.directives=new KS.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=Zd(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}
|
|
120
|
+
${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(Xd.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];Xd.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n}
|
|
121
121
|
${a}`:n}else{let o=i.commentBefore;i.commentBefore=o?`${n}
|
|
122
|
-
${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:
|
|
123
|
-
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new fn.YAMLParseError(dn(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
|
|
122
|
+
${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:Zd(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(JS.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,n,s)=>{let i=dn(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=WS.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 fn.YAMLParseError(dn(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 fn.YAMLParseError(dn(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=YS.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}
|
|
123
|
+
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new fn.YAMLParseError(dn(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 HS.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}}};ep.Composer=ic});var np=E(Js=>{"use strict";var VS=ec(),GS=rc(),zS=ln(),tp=Yr();function QS(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 zS.YAMLParseError([a,a+1],i,o)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return GS.resolveFlowScalar(r,e,n);case"block-scalar":return VS.resolveBlockScalar({options:{strict:e}},r,n)}}return null}function XS(r,e){let{implicitKey:t=!1,indent:n,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=e,a=tp.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:`
|
|
124
124
|
`}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
|
|
125
|
-
`),
|
|
126
|
-
`,
|
|
127
|
-
`}),{type:"block-scalar",offset:i,indent:n,props:
|
|
125
|
+
`),f=a.substring(0,l),u=a.substring(l+1)+`
|
|
126
|
+
`,d=[{type:"block-scalar-header",offset:i,indent:n,source:f}];return rp(d,c)||d.push({type:"newline",offset:-1,indent:n,source:`
|
|
127
|
+
`}),{type:"block-scalar",offset:i,indent:n,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:c};default:return{type:"scalar",offset:i,indent:n,source:a,end:c}}}function ZS(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=tp.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">":ek(r,c);break;case'"':ac(r,c,"double-quoted-scalar");break;case"'":ac(r,c,"single-quoted-scalar");break;default:ac(r,c,"scalar")}}function ek(r,e){let t=e.indexOf(`
|
|
128
128
|
`),n=e.substring(0,t),s=e.substring(t+1)+`
|
|
129
|
-
`;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}];
|
|
130
|
-
`});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
|
|
131
|
-
`};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})}}}
|
|
129
|
+
`;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}];rp(a,"end"in r?r.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
|
|
130
|
+
`});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 rp(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 ac(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:`
|
|
131
|
+
`};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})}}}Js.createScalarToken=XS;Js.resolveAsScalar=QS;Js.setScalarValue=ZS});var ip=E(sp=>{"use strict";var tk=r=>"type"in r?Hs(r):Ks(r);function Hs(r){switch(r.type){case"block-scalar":{let e="";for(let t of r.props)e+=Hs(t);return e+r.source}case"block-map":case"block-seq":{let e="";for(let t of r.items)e+=Ks(t);return e}case"flow-collection":{let e=r.start.source;for(let t of r.items)e+=Ks(t);for(let t of r.end)e+=t.source;return e}case"document":{let e=Ks(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 Ks({start:r,key:e,sep:t,value:n}){let s="";for(let i of r)s+=i.source;if(e&&(s+=Hs(e)),t)for(let i of t)s+=i.source;return n&&(s+=Hs(n)),s}sp.stringify=tk});var lp=E(cp=>{"use strict";var cc=Symbol("break visit"),rk=Symbol("skip children"),op=Symbol("remove item");function Pt(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),ap(Object.freeze([]),r,e)}Pt.BREAK=cc;Pt.SKIP=rk;Pt.REMOVE=op;Pt.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};Pt.parentCollection=(r,e)=>{let t=Pt.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 ap(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=ap(Object.freeze(r.concat([[s,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===cc)return cc;a===op&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&s==="key"&&(n=n(e,r))}}return typeof n=="function"?n(e,r):n}cp.visit=Pt});var Ws=E(ae=>{"use strict";var lc=np(),nk=ip(),sk=lp(),uc="\uFEFF",fc="",dc="",pc="",ik=r=>!!r&&"items"in r,ok=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar");function ak(r){switch(r){case uc:return"<BOM>";case fc:return"<DOC>";case dc:return"<FLOW_END>";case pc:return"<SCALAR>";default:return JSON.stringify(r)}}function ck(r){switch(r){case uc:return"byte-order-mark";case fc:return"doc-mode";case dc:return"flow-error-end";case pc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
132
132
|
`:case`\r
|
|
133
|
-
`: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}
|
|
134
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
135
|
-
\r `),
|
|
133
|
+
`: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}ae.createScalarToken=lc.createScalarToken;ae.resolveAsScalar=lc.resolveAsScalar;ae.setScalarValue=lc.setScalarValue;ae.stringify=nk.stringify;ae.visit=sk.visit;ae.BOM=uc;ae.DOCUMENT=fc;ae.FLOW_END=dc;ae.SCALAR=pc;ae.isCollection=ik;ae.isScalar=ok;ae.prettyToken=ak;ae.tokenType=ck});var gc=E(fp=>{"use strict";var pn=Ws();function we(r){switch(r){case void 0:case" ":case`
|
|
134
|
+
`:case"\r":case" ":return!0;default:return!1}}var up=new Set("0123456789ABCDEFabcdef"),lk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ys=new Set(",[]{}"),uk=new Set(` ,[]{}
|
|
135
|
+
\r `),mc=r=>!r||uk.has(r),hc=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===`
|
|
136
136
|
`?!0:t==="\r"?this.buffer[e+1]===`
|
|
137
137
|
`:!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===`
|
|
138
138
|
`||!s&&!this.atEnd)return e+n+1}return t===`
|
|
139
139
|
`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&we(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(`
|
|
140
|
-
`,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]===pn.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 pn.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==="...")&&we(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&&!we(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===":")&&we(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(
|
|
140
|
+
`,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]===pn.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 pn.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==="...")&&we(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&&!we(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===":")&&we(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(mc),"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("..."))&&we(s[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield pn.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(mc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||we(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(`
|
|
141
141
|
`,this.pos);if(s!==-1){for(;s!==-1;){let i=this.continueScalar(s+1);if(i===-1)break;s=n.indexOf(`
|
|
142
142
|
`,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=>we(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`
|
|
143
143
|
`:e=i,t=0;break;case"\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
144
144
|
`)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(`
|
|
145
145
|
`,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===`
|
|
146
146
|
`;)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===`
|
|
147
|
-
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield pn.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(we(i)||e&&
|
|
147
|
+
`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield pn.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(we(i)||e&&Ys.has(i))break;t=n}else if(we(s)){let i=this.buffer[n+1];if(s==="\r"&&(i===`
|
|
148
148
|
`?(n+=1,s=`
|
|
149
|
-
`,i=this.buffer[n+1]):t=n),i==="#"||e&&
|
|
150
|
-
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&
|
|
149
|
+
`,i=this.buffer[n+1]):t=n),i==="#"||e&&Ys.has(i))break;if(s===`
|
|
150
|
+
`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Ys.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield pn.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(mc))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(we(t)||e&&Ys.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(;!we(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(lk.has(t))t=this.buffer[++e];else if(t==="%"&&up.has(this.buffer[e+1])&&up.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===`
|
|
151
151
|
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
152
|
-
`?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)}};
|
|
152
|
+
`?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)}};fp.Lexer=hc});var bc=E(dp=>{"use strict";var yc=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}}}};dp.LineCounter=yc});var vc=E(yp=>{"use strict";var fk=Gn("process"),pp=Ws(),dk=gc();function st(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function mp(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 gp(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 Vs(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 or(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 hp(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!st(e.start,"explicit-key-ind")&&!st(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,gp(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 wc=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 dk.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,fk.env.LOG_TOKENS&&console.log("|",pp.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=pp.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"&&hp(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&&mp(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":{mp(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=Vs(this.peek(2)),n=or(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(`
|
|
153
153
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
154
|
-
`,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(st(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(
|
|
154
|
+
`,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(st(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(gp(t.key)&&!st(t.sep,"newline")){let o=or(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(st(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=or(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]}):st(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&&!st(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||st(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=Vs(n),i=or(s);hp(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(`
|
|
155
155
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
156
|
-
`,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=
|
|
157
|
-
`),t=e.trim();if(
|
|
156
|
+
`,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=Vs(e),n=or(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=Vs(e),n=or(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())}}};yp.Parser=wc});var kp=E(hn=>{"use strict";var bp=oc(),pk=on(),mn=ln(),mk=sa(),hk=j(),gk=bc(),wp=vc();function vp(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new gk.LineCounter||null,prettyErrors:e}}function yk(r,e={}){let{lineCounter:t,prettyErrors:n}=vp(e),s=new wp.Parser(t?.addNewLine),i=new bp.Composer(e),o=Array.from(i.compose(s.parse(r)));if(n&&t)for(let a of o)a.errors.forEach(mn.prettifyError(r,t)),a.warnings.forEach(mn.prettifyError(r,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Sp(r,e={}){let{lineCounter:t,prettyErrors:n}=vp(e),s=new wp.Parser(t?.addNewLine),i=new bp.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 mn.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(mn.prettifyError(r,t)),o.warnings.forEach(mn.prettifyError(r,t))),o}function bk(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=Sp(r,t);if(!s)return null;if(s.warnings.forEach(i=>mk.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 wk(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 hk.isDocument(r)&&!n?r.toString(t):new pk.Document(r,n,t).toString(t)}hn.parse=bk;hn.parseAllDocuments=yk;hn.parseDocument=Sp;hn.stringify=wk});var Ep=E(F=>{"use strict";var vk=oc(),Sk=on(),kk=Fa(),Sc=ln(),xk=Ur(),it=j(),Ek=et(),Ak=W(),Tk=rt(),Pk=nt(),Ok=Ws(),Ck=gc(),_k=bc(),Rk=vc(),Gs=kp(),xp=Br();F.Composer=vk.Composer;F.Document=Sk.Document;F.Schema=kk.Schema;F.YAMLError=Sc.YAMLError;F.YAMLParseError=Sc.YAMLParseError;F.YAMLWarning=Sc.YAMLWarning;F.Alias=xk.Alias;F.isAlias=it.isAlias;F.isCollection=it.isCollection;F.isDocument=it.isDocument;F.isMap=it.isMap;F.isNode=it.isNode;F.isPair=it.isPair;F.isScalar=it.isScalar;F.isSeq=it.isSeq;F.Pair=Ek.Pair;F.Scalar=Ak.Scalar;F.YAMLMap=Tk.YAMLMap;F.YAMLSeq=Pk.YAMLSeq;F.CST=Ok;F.Lexer=Ck.Lexer;F.LineCounter=_k.LineCounter;F.Parser=Rk.Parser;F.parse=Gs.parse;F.parseAllDocuments=Gs.parseAllDocuments;F.parseDocument=Gs.parseDocument;F.stringify=Gs.stringify;F.visit=xp.visit;F.visitAsync=xp.visitAsync});function Ik(r){try{return JSON.parse(r.trim()),!0}catch{return!1}}function $k(r){let e=r.trim();if(!e.startsWith("<"))return!1;let t=e.match(Nk);return t?Dr(e,t[1])!==null:!1}function Lk(r){let e=r.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=Ap.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function Tp(r){return Ik(r)||$k(r)||Lk(r)}var Ap,Nk,kc=A(()=>{Lu();Ap=Uy(Ep(),1),Nk=/<([a-zA-Z_][\w.-]*)/});function Mk(r){if(!r?.trim())return[];let e=r.replace(/\r\n/g,`
|
|
157
|
+
`),t=e.trim();if(Tp(t))return[{text:t,startLine:1,endLine:e.split(`
|
|
158
158
|
`).length}];let n=e.split(`
|
|
159
159
|
`),s=[],i=0,o=-1,a=0,c=()=>{if(o>=i){let l=n.slice(i,o+1).join(`
|
|
160
|
-
`).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
|
|
160
|
+
`).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 zs(r){return Mk(r).map(e=>e.text)}var Pp,Op=A(()=>{kc();Pp=`
|
|
161
161
|
|
|
162
162
|
|
|
163
|
-
`});var
|
|
164
|
-
`).length-1}));return n}function
|
|
165
|
-
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of
|
|
166
|
-
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:
|
|
163
|
+
`});var Be=A(()=>{zn();Lo();Pu();Ou();kc();Op();Qn()});function ar(r){return{...xu(r),server:r.files.get("server.ts")??""}}function Qs(r){return!!r.server&&!r.code}var gn=A(()=>{Be();Be()});function Fk(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 Cp(r){let e=[];for(let s of jk)for(let i of r.matchAll(s)){let o=Fk(i[1]);o&&e.push({root:o,index:i.index??0})}e.sort((s,i)=>s.index-i.index);let t=new Set,n=[];for(let{root:s,index:i}of e)t.has(s)||(t.add(s),n.push({root:s,lineIndex:r.slice(0,i).split(`
|
|
164
|
+
`).length-1}));return n}function _p(r){return Cp(r).map(e=>e.root)}function yn(r,e){if(!r)return[];let{target:t,dependencies:n}=e,s=[],i=r.split(`
|
|
165
|
+
`);for(let o=0;o<i.length;o++){let a=i[o],c=o+1;for(let l of Bk)l.targets.includes(t)&&l.pattern.test(a)&&s.push({type:l.type,severity:"error",message:Jk(l.type,c),lineNumber:c,lineContent:a})}return t==="client"&&n&&s.push(...qk(i,n)),s}function qk(r,e){let t=new Set(Object.keys(e));return Cp(r.join(`
|
|
166
|
+
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:Uk(n,s+1),lineNumber:s+1,lineContent:r[s]}))}function Uk(r,e){return`Import "${r}" is not declared in config.json dependencies! Found on line ${e}.
|
|
167
167
|
|
|
168
168
|
**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.
|
|
169
169
|
|
|
@@ -177,7 +177,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
177
177
|
}
|
|
178
178
|
\`\`\`
|
|
179
179
|
|
|
180
|
-
**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
|
|
180
|
+
**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 Jk(r,e){return r==="URL_IMPORT"?`Direct URL imports are not supported! Found on line ${e}.
|
|
181
181
|
|
|
182
182
|
**CRITICAL**: Import packages by name only. Do NOT use CDN URLs:
|
|
183
183
|
|
|
@@ -331,21 +331,21 @@ import { something } from 'module-name'
|
|
|
331
331
|
const something = require('module-name') // NOT SUPPORTED!
|
|
332
332
|
\`\`\`
|
|
333
333
|
|
|
334
|
-
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var Ot,Ct,
|
|
334
|
+
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var Ot,Ct,Bk,jk,Xs=A(()=>{Ot=["client"],Ct=["client","server"],Bk=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:Ot},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:Ct},{type:"JS_EXTENSION_IMPORT",pattern:/from\s+['"][^'"]*\/[^'"]*\.js['"]/,targets:Ot},{type:"URL_IMPORT",pattern:/from\s+['"]https?:\/\//,targets:Ot},{type:"VERSION_SPECIFIER_IMPORT",pattern:/from\s+['"][^'"]*@[\d^~]/,targets:Ot},{type:"REDUNDANT_TB_DECLARATION",pattern:/declare\s+(const|var|let)\s+tb\b/,targets:Ct},{type:"CONST_ENUM",pattern:/\bconst\s+enum\b/,targets:Ct},{type:"NAMESPACE_DECLARATION",pattern:/\bnamespace\s+\w+/,targets:Ct},{type:"COMMONJS_EXPORT_EQUALS",pattern:/\bexport\s*=/,targets:Ct},{type:"COMMONJS_IMPORT_EQUALS",pattern:/\bimport\s+\w+\s*=/,targets:Ct},{type:"MODULE_DECLARATION",pattern:/\bmodule\s+\w+\s*\{/,targets:Ct},{type:"CSS_FILE_IMPORT",pattern:/(?:from|import)\s+['"][^'"]*\.css['"]/,targets:Ot},{type:"NAVIGATION",pattern:/window\.(location\.(reload|assign|replace)\s*\(|open\s*\()/,targets:Ot},{type:"NAVIGATION",pattern:/window\.location(\.href)?\s*=[^=]/,targets:Ot}],jk=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});var Qp=A(()=>{});var ue,ke,fr=A(()=>{ue=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},ke=class{getPath(e,t){return this.path}parseError(e,t){return this.parseJsonError(e,t)}parseStreamChunk(e){return this.checkAndThrowError(e),this.parseProviderStreamChunk(e)}extractSystemMessages(e,t=`
|
|
335
335
|
|
|
336
|
-
`){let n=e.filter(s=>s.role==="system").map(s=>s.content);return{system:n.length?n.join(t):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,t){if(!e)return{message:`HTTP ${t}`};try{let n=JSON.parse(e);return n.error&&typeof n.error=="object"?{message:n.error.message||`HTTP ${t}`,type:n.error.type}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if(typeof e!="object"||e===null)return;let t=e;if(t.type==="error"&&"message"in t){let n=t.code||"unknown";throw new ue(t.message,n,!!t.retryable)}if(t.error){let n=t.error,s=typeof n=="object"&&n!==null?String(n.type??n.code??""):"",i=/rate_limit|too_many_requests/i.test(s),o=/overloaded|server_error|unavailable/i.test(s),a=/context_length/i.test(s);throw new ue(this.extractErrorMessage(t.error),i?"rate_limit":a?"context_exceeded":"unknown",i||o)}}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
|
|
336
|
+
`){let n=e.filter(s=>s.role==="system").map(s=>s.content);return{system:n.length?n.join(t):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,t){if(!e)return{message:`HTTP ${t}`};try{let n=JSON.parse(e);return n.error&&typeof n.error=="object"?{message:n.error.message||`HTTP ${t}`,type:n.error.type}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if(typeof e!="object"||e===null)return;let t=e;if(t.type==="error"&&"message"in t){let n=t.code||"unknown";throw new ue(t.message,n,!!t.retryable)}if(t.error){let n=t.error,s=typeof n=="object"&&n!==null?String(n.type??n.code??""):"",i=/rate_limit|too_many_requests/i.test(s),o=/overloaded|server_error|unavailable/i.test(s),a=/context_length/i.test(s);throw new ue(this.extractErrorMessage(t.error),i?"rate_limit":a?"context_exceeded":"unknown",i||o)}}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 pi,_c=A(()=>{fr();pi=class extends ke{constructor(){super(...arguments),this.providerName="OpenAI",this.defaultBaseUrl="https://api.openai.com",this.path="/v1/responses",this.effortMap={0:"none",1:"low",2:"medium",3:"high"}}buildHeaders(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,n,s){let i=this.convertMessagesToInput(e),o={model:t,input:i,stream:s};if(n?.webSearch!==!1&&(o.tools=[{type:"web_search"}]),n?.effort!==void 0){let a=this.effortMap[n.effort];o.reasoning=a==="none"?{effort:a}:{effort:a,summary:"auto"}}return o}parseNonStreamingResponse(e){if(!this.isResponsesApiResponse(e))return{text:""};let t=e.output_text||"",n;if(e.output&&Array.isArray(e.output))for(let s of e.output)s.type==="reasoning"&&s.summary&&(n=s.summary.map(i=>i.text).join(`
|
|
337
337
|
`)),!t&&s.type==="message"&&s.content&&(t=s.content.filter(i=>i.type==="output_text").map(i=>i.text).join(""));return{text:t,reasoning:n}}parseProviderStreamChunk(e){if(!this.isResponsesApiEvent(e))return null;switch(e.type){case"response.failed":{let n=e.response?.error,s=n?.message||"Response failed",i=n?.code==="insufficient_quota"||n?.code==="rate_limit_exceeded";throw new ue(s,i?"rate_limit":"unknown",i)}case"response.output_text.delta":return{text:e.delta};case"response.reasoning_summary_text.delta":return{reasoning:e.delta};default:return null}}convertMessagesToInput(e){return e.map(t=>t.role==="system"?`System: ${t.content}`:t.role==="user"?`User: ${t.content}`:t.role==="assistant"?`Assistant: ${t.content}`:t.content).join(`
|
|
338
338
|
|
|
339
|
-
`)}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
|
|
339
|
+
`)}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 dr,mi=A(()=>{fr();dr=class extends ke{parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let t=e,n=t.choices[0],s=n?.message,i=s?.content??n?.text??"",o=s?.reasoning??s?.reasoning_content??t.reasoning;return{text:i,reasoning:o}}parseProviderStreamChunk(e){if(!this.hasChoices(e))return null;let t=e.choices[0];if(!t)return null;let n=t.delta||t.message;if(!n)return null;let s=n.content||void 0,i=n.reasoning||n.reasoning_content||void 0;return!s&&!i?null:{text:s,reasoning:i}}hasChoices(e){return typeof e=="object"&&e!==null&&"choices"in e&&Array.isArray(e.choices)}}});var hi,Rc=A(()=>{mi();hi=class extends dr{constructor(){super(...arguments),this.providerName="OpenRouter",this.defaultBaseUrl="https://openrouter.ai",this.path="/api/v1/chat/completions",this.effortMap={0:"none",1:"low",2:"medium",3:"high"}}buildHeaders(e,t){let n={Authorization:`Bearer ${e}`,"x-api-key":e,"Content-Type":"application/json",Accept:"application/json","X-Title":"Typebulb"};return t&&(n["HTTP-Referer"]=t,n.Referer=t,n.Origin=t),n}buildPayload(e,t,n,s){let i={model:t,messages:e,stream:s};n?.webSearch===!0&&(i.plugins=[{id:"web"}]);let o=n?.effort;return o!==void 0&&(i.reasoning={effort:this.effortMap[o]}),i}}});var gi,Nc=A(()=>{fr();gi=class extends ke{constructor(){super(...arguments),this.providerName="Anthropic",this.defaultBaseUrl="https://api.anthropic.com",this.path="/v1/messages"}buildHeaders(e){return{"x-api-key":e,"anthropic-version":"2023-06-01","Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,n,s){let{system:i,conversationMessages:o}=this.extractSystemMessages(e),a={model:t,max_tokens:this.getMaxTokens(t),messages:this.withLastMessageCached(o),stream:s};n?.webSearch!==!1&&(a.tools=[{type:"web_search_20250305",name:"web_search"}]),i&&(a.system=[{type:"text",text:i,cache_control:{type:"ephemeral"}}]);let c=n?.effort;if(c!==void 0){if(this.isModernModel(t))if(c===0)a.output_config={effort:"low"};else{let l={1:"low",2:"medium",3:"high"};a.thinking={type:"adaptive",display:"summarized"},a.output_config={effort:l[c]}}else if(c!==0){let l={1:2048,2:4096,3:8192};a.thinking={type:"enabled",budget_tokens:l[c]}}}return a}parseNonStreamingResponse(e){if(!this.isAnthropicResponse(e))return{text:""};let t=e.content.filter(s=>s.type==="text").map(s=>s.text).join(""),n=e.content.filter(s=>s.type==="thinking").map(s=>s.thinking).join(`
|
|
340
340
|
|
|
341
|
-
`);return{text:t,reasoning:n||void 0}}parseProviderStreamChunk(e){return this.isAnthropicEvent(e)&&e.type==="content_block_delta"?e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null:null}withLastMessageCached(e){let t=e.length-1;return e.map((n,s)=>s===t?{role:n.role,content:[{type:"text",text:n.content,cache_control:{type:"ephemeral"}}]}:n)}isAnthropicResponse(e){return typeof e=="object"&&e!==null&&e.type==="message"&&Array.isArray(e.content)}isAnthropicEvent(e){return typeof e=="object"&&e!==null&&"type"in e}isModernModel(e){let t=e.match(/^claude-[a-z]+-(\d+)(?:-(\d+))?/i);if(!t)return!1;let n=+t[1],s=t[2]?+t[2]:0;return n>4||n===4&&s>=6}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}}});var
|
|
342
|
-
`),c={contents:o.map(
|
|
343
|
-
`)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkAndThrowError(e),this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractParts(e).text||"",n=e.candidates?.[0]?.finishReason,s="complete";return n==="MAX_TOKENS"?s="interrupted":(n==="SAFETY"||n==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractParts(e);return t.text||t.reasoning?t:null}geminiVersion(e){let t=e.match(/^gemini-(\d+(?:\.\d+)?)/);return t?Number(t[1]):null}thinkingLevelFor(e,t){let n=["minimal","low","medium","high"][t];return n==="minimal"&&e<3.5?"low":n}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let t=e.candidates?.[0]?.content?.parts;if(!t)return{};let n="",s="";for(let i of t)i.text&&(i.thought?s+=i.text:n+=i.text);return{text:n||void 0,reasoning:s||void 0}}checkGeminiError(e){if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new ue(`Prompt blocked: ${t}`)}}}});var
|
|
341
|
+
`);return{text:t,reasoning:n||void 0}}parseProviderStreamChunk(e){return this.isAnthropicEvent(e)&&e.type==="content_block_delta"?e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null:null}withLastMessageCached(e){let t=e.length-1;return e.map((n,s)=>s===t?{role:n.role,content:[{type:"text",text:n.content,cache_control:{type:"ephemeral"}}]}:n)}isAnthropicResponse(e){return typeof e=="object"&&e!==null&&e.type==="message"&&Array.isArray(e.content)}isAnthropicEvent(e){return typeof e=="object"&&e!==null&&"type"in e}isModernModel(e){let t=e.match(/^claude-[a-z]+-(\d+)(?:-(\d+))?/i);if(!t)return!1;let n=+t[1],s=t[2]?+t[2]:0;return n>4||n===4&&s>=6}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}}});var yi,Ic=A(()=>{fr();yi=class extends ke{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models",this.budgetMap={0:0,1:1024,2:8192,3:-1}}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,`
|
|
342
|
+
`),c={contents:o.map(f=>({role:f.role==="assistant"?"model":"user",parts:[{text:f.content}]}))};n?.webSearch!==!1&&(c.tools=[{google_search:{}}]),i&&(c.systemInstruction={role:"system",parts:[{text:i}]});let l=n?.effort;if(l!==void 0){let f=this.geminiVersion(t),u=f!==null&&f>=3?{thinkingLevel:this.thinkingLevelFor(f,l)}:{thinkingBudget:this.budgetMap[l]};c.generationConfig={thinkingConfig:l===0?u:{includeThoughts:!0,...u}}}return c}parseError(e,t){if(!e)return{message:`HTTP ${t}`};try{let n=JSON.parse(e),s=Array.isArray(n)?n[0]?.error:n?.error;return s&&typeof s=="object"?{message:(s.message||`HTTP ${t}`).split(`
|
|
343
|
+
`)[0],type:s.status,code:s.code?.toString()}:n.message?{message:n.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkAndThrowError(e),this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractParts(e).text||"",n=e.candidates?.[0]?.finishReason,s="complete";return n==="MAX_TOKENS"?s="interrupted":(n==="SAFETY"||n==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractParts(e);return t.text||t.reasoning?t:null}geminiVersion(e){let t=e.match(/^gemini-(\d+(?:\.\d+)?)/);return t?Number(t[1]):null}thinkingLevelFor(e,t){let n=["minimal","low","medium","high"][t];return n==="minimal"&&e<3.5?"low":n}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let t=e.candidates?.[0]?.content?.parts;if(!t)return{};let n="",s="";for(let i of t)i.text&&(i.thought?s+=i.text:n+=i.text);return{text:n||void 0,reasoning:s||void 0}}checkGeminiError(e){if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new ue(`Prompt blocked: ${t}`)}}}});var bi,$c=A(()=>{mi();bi=class extends dr{constructor(){super(...arguments),this.providerName="Ollama",this.defaultBaseUrl="http://localhost:11434",this.path="/chat/completions"}buildHeaders(e){let t={"Content-Type":"application/json",Accept:"application/json"};return e&&(t.Authorization=`Bearer ${e}`),t}buildPayload(e,t,n,s){return{model:t,messages:e,stream:s}}}});function $t(r){let e=px.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}function mx(r,e){return r.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function Lc(r,e){let t=$t(r.protocol),n=t.getPath(r.model,e.stream),s=mx(r.baseUrl,n),i=t.buildHeaders(r.apiKey,e.origin),o=t.buildPayload(e.messages,r.model,{effort:e.effort,webSearch:e.webSearch},e.stream);return e.modifyPayload?.(o),fetch(s,{method:"POST",headers:i,body:JSON.stringify(o),signal:e.signal})}function hx(r){return/prompt is too long|context[_ ](length|window)|maximum context|token count exceeds|too many tokens/i.test(r)}async function pr(r,e){let t=$t(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||hx(s))&&(o="context_exceeded"),{code:o,message:s,retryable:i===429||i>=500}}var Xp,px,Mc=A(()=>{_c();Rc();Nc();Ic();$c();Xp=new bi,px=new Map([["openai",new pi],["openrouter",new hi],["anthropic",new gi],["gemini",new yi],["ollama",Xp],["openai-compat",Xp]])});function Zp(r){let e=r.indexOf(`\r
|
|
344
344
|
\r
|
|
345
345
|
`),t=r.indexOf(`
|
|
346
346
|
|
|
347
|
-
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function
|
|
348
|
-
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*
|
|
347
|
+
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function Dc(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(`
|
|
348
|
+
`).trim();if(!n)return null;if(n==="[DONE]")return"done";try{return JSON.parse(n)}catch{return null}}async function*em(r,e,t){let n=new TextDecoder,s="",i,o=e?new Promise((a,c)=>{e.aborted&&c(new Error("Aborted")),i=()=>c(new Error("Aborted")),e.addEventListener("abort",i,{once:!0})}):null;o?.catch(()=>{});try{for(;;){let{done:a,value:c}=o?await Promise.race([r.read(),o]):await r.read();if(a){if(s.trim()){let u=Dc(s);u!==null&&u!=="done"&&(yield u)}return}t?.(),s+=n.decode(c,{stream:!0});let{pos:l,len:f}=Zp(s);for(;l!==-1;){let u=s.slice(0,l);s=s.slice(l+f);let d=Dc(u);if(d==="done")return;d!==null&&(yield d),{pos:l,len:f}=Zp(s)}}}finally{i&&e?.removeEventListener("abort",i);try{await r.cancel()}catch{}}}async function Lt(r,e){if(!r.body)throw new Error("Response body is missing");let t="";for await(let n of Mt(r,e))n.kind==="text"&&(t+=n.text);return t}async function*Mt(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=$t(t);if(!r.body)return;let s=r.body.getReader();for await(let i of em(s)){let o=n.parseStreamChunk(i);o?.reasoning&&(yield{kind:"reasoning",text:o.reasoning}),o?.text&&(yield{kind:"text",text:o.text})}}var tm=A(()=>{Mc()});import{strToU8 as gx,strFromU8 as yx,deflateSync as bx,inflateSync as wx}from"fflate";function jc(r,e){let t=[];if(t.push(`You are a data processor. Follow the instructions to analyze the provided data. Output valid JSON that the code can consume.
|
|
349
349
|
|
|
350
350
|
---
|
|
351
351
|
Instructions:
|
|
@@ -363,35 +363,35 @@ ${n}
|
|
|
363
363
|
</data>`)}return t.push(`
|
|
364
364
|
Output only valid JSON. No explanation, no markdown fences, just the JSON object. Every number must be a JSON literal \u2014 never an expression like 2 * pi; write the computed decimal instead.`),t.join(`
|
|
365
365
|
|
|
366
|
-
`)}function An(r){try{return JSON.parse(r)}catch{return null}}function
|
|
367
|
-
`)}var
|
|
368
|
-
\u2026[${r.length-5e4} more characters truncated]`:r}function He(r){let e=r.replace(
|
|
369
|
-
`).map(i=>i.trim()).filter(Boolean),t=e[0];if(!t)return"";let n=t.length>300?t.slice(0,300).trimEnd()+"\u2026":t,s=e.length-1;return s>0?`${n} (+${s} line${s===1?"":"s"})`:n}var
|
|
370
|
-
`):r==null?"":
|
|
371
|
-
`).length,"line")}`;if(t.mode==="content")return Ee(t.numLines??0,"line");if(t.mode==="count")return`${Ee(t.numMatches??0,"match","matches")} (${Ee(t.numFiles??0,"file")})`;if(t.mode==="files_with_matches")return Ee(t.numFiles??0,"file");if(Array.isArray(t.structuredPatch)){let n=0,s=0;for(let i of t.structuredPatch)for(let o of i?.lines??[])typeof o=="string"&&(o.startsWith("+")?n++:o.startsWith("-")&&s++);return`+${n} \u2212${s}`}return typeof t.stdout=="string"||typeof t.stderr=="string"?t.backgroundTaskId?"running in background":t.interrupted?"interrupted":He(t.stdout||t.stderr||"")||"no output":typeof t.code=="number"&&typeof t.codeText=="string"?`${t.code} ${t.codeText}`:typeof t.searchCount=="number"?Ee(t.searchCount,"search","searches"):Array.isArray(t.matches)&&typeof t.total_deferred_tools=="number"?Ee(t.matches.length,"tool"):Array.isArray(t.newTodos)?Ee(t.newTodos.length,"todo"):typeof t.numFiles=="number"?Ee(t.numFiles,"file"):He(e)}function
|
|
372
|
-
`)){if(!p.includes(`"${
|
|
373
|
-
`)){if(!l.trim())continue;let
|
|
374
|
-
`),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??""),
|
|
375
|
-
`),n=[];if(t.forEach((o,a)=>{let c=
|
|
376
|
-
`)}function
|
|
366
|
+
`)}function An(r){try{return JSON.parse(r)}catch{return null}}function Sx(r,e){let t="",n=0,s=!1,i=!1;for(let o=0;o<r.length;o++){let a=r[o];if(i){i=!1;continue}if(a==="\\"){i=!0;continue}a==='"'&&(s?(t+=r.slice(n,o+1),n=o+1):(t+=e(r.slice(n,o))+'"',n=o+1),s=!s)}return t+=s?r.slice(n):e(r.slice(n)),t}function kx(r){let e=Sx(r,t=>t.replace(/\bpi\b/g,"3.141592653589793").replace(/\be\b/g,"2.718281828459045").replace(/-?\d[\d.\s+\-*/()]*\d|\(-?\d[\d.\s+\-*/()]*\d\)/g,n=>{if(!/[+\-*/]/.test(n.replace(/^-/,""))||n.length>64||!/^[\d\s.+\-*/()]+$/.test(n))return n;try{let s=Function(`"use strict"; return (${n})`)();return typeof s=="number"&&Number.isFinite(s)?String(s):n}catch{return n}}));return e!==r?e:null}function xx(r,e){let t=0,n=!1,s=!1;for(let i=e;i<r.length;i++){let o=r[i];if(s){s=!1;continue}if(o==="\\"){s=!0;continue}if(o==='"'){n=!n;continue}if(!n){if(o==="{"||o==="[")t++;else if((o==="}"||o==="]")&&(t--,t===0))return i}}return-1}function Ex(r){let e=null,t=0;for(;t<r.length;){let n=r[t];if(n==="{"||n==="["){let s=xx(r,t);if(s!==-1){let i=r.slice(t,s+1),o=An(i);o!==null&&(e={parsed:o,json:i}),t=s+1;continue}}t++}return e}function Fc(r){let e=[],t=r.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""),e.push("markdown fences"));let n=An(t);if(n!==null)return{parsed:n,json:t,fixesApplied:e};let s=t.match(/```(?:json)?\s*\n([\s\S]*?)\n?```\s*$/);if(s&&(t=s[1].trim(),e.push("preamble before fenced JSON"),n=An(t),n!==null))return{parsed:n,json:t,fixesApplied:e};if(!t.startsWith("{")&&!t.startsWith("[")){let o=t.indexOf("{"),a=t.indexOf("["),c=o>=0&&a>=0?Math.min(o,a):o>=0?o:a;if(c>0&&(t=t.slice(c),e.push("preamble text"),n=An(t),n!==null))return{parsed:n,json:t,fixesApplied:e}}for(let[o,a]of vx){let c=a(t);if(c!==null){let l=An(c);if(l!==null)return{parsed:l,json:c,fixesApplied:[...e,o]}}}let i=Ex(r);return i!==null?{...i,fixesApplied:[...e,"extracted last JSON value"]}:{parsed:null,json:t,fixesApplied:e}}function qc(r){try{let e={i:r.insight,d:r.data},t=JSON.stringify(e),n=bx(gx(t),{level:9}),s=Tx(n),i=`${rm}:${s}`;return i.length>Ax?"":"#"+Bc+i}catch{return""}}function Uc(r){try{let e=r.startsWith("#")?r.slice(1):r;if(!e.startsWith(Bc))return null;let t=e.slice(Bc.length),n=t.indexOf(":");if(n===-1||t.slice(0,n)!==rm)return null;let s=Px(t.slice(n+1)),i=JSON.parse(yx(wx(s)));return!i||typeof i.i>"u"||!Array.isArray(i.d)?null:{insight:i.i,insightJson:JSON.stringify(i.i,null,2),data:i.d}}catch{return null}}function Tx(r){let e="";for(let t=0;t<r.length;t+=32768)e+=String.fromCharCode(...r.subarray(t,t+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Px(r){let e=r.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n}var vx,Bc,rm,Ax,nm=A(()=>{vx=[["orphan quote",r=>{let e=r.replace(/^[ \t]*"[ \t]*\r?\n/gm,"");return e!==r?e:null}],["trailing }",r=>r.endsWith("}}")?r.slice(0,-1):null],["trailing ]",r=>r.endsWith("]]")?r.slice(0,-1):null],["trailing },",r=>r.endsWith("},")?r.slice(0,-1):null],["trailing ],",r=>r.endsWith("],")?r.slice(0,-1):null],["trailing comma in object",r=>r.match(/,\s*\}$/)?r.replace(/,\s*\}$/,"}"):null],["trailing comma in array",r=>r.match(/,\s*\]$/)?r.replace(/,\s*\]$/,"]"):null],["arithmetic constants",kx]];Bc="tb=",rm="1",Ax=6e4});var mr=A(()=>{Qp();fr();Mc();tm();nm();mi();Nc();Ic();_c();Rc();$c()});function gr(r){return(r.includes("://")?r:`http://${r}`).replace(/\/+$/,"")}function Jc(){return Pn}async function qe(){let[r,e]=await Promise.all([im(),Nx()]);return[...Ix(e),...r]}async function sm(){let r;try{r=await fetch(Ox,{signal:AbortSignal.timeout(_x)})}catch(e){return Pn=`catalog fetch failed: ${e?.message??e}`,null}if(!r.ok)return Pn=`catalog fetch failed: HTTP ${r.status}`,null;try{return await r.json()}catch(e){return Pn=`catalog returned an unreadable body: ${e?.message??e}`,null}}async function Nx(){if(Tn&&Date.now()-Tn.fetchedAt<=Cx)return Tn.models;let r=await sm()??await sm();return r?(Tn={models:r,fetchedAt:Date.now()},Pn=null,r):Tn?.models??[]}async function im(){if(wi&&Date.now()-wi.fetchedAt<=Rx)return wi.models;let r=gr(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 wi={models:e,fetchedAt:Date.now()},e}function Ix(r){let e=new Set(Object.entries(hr).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function Kc(){return Object.values(hr).some(r=>!!process.env[r])}async function vi(){return Kc()||process.env.TB_AI_BASE_URL?!0:(await im()).length>0}function om(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(`
|
|
367
|
+
`)}var hr,Ox,Cx,_x,Rx,Tn,wi,Pn,Dt=A(()=>{hr={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};Ox="https://api.typebulb.com/api/models",Cx=1440*60*1e3,_x=5e3,Rx=60*1e3,Tn=null,wi=null,Pn=null});function Ue(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=$t(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${gr(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=hr[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 ut(r,e){let t=[...e.system?[{role:"system",content:e.system}]:[],...e.messages.map(s=>({role:s.role,content:s.content}))],n=e.effort;return Lc(r,{messages:t,stream:!0,effort:n!=null&&n>=0&&n<=3?n:void 0,webSearch:e.webSearch??!0,signal:e.signal})}var Si=A(()=>{mr();Dt()});import{realpathSync as Dx}from"fs";import{join as Yc,resolve as Bx}from"path";import{homedir as jx}from"os";function Ai(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?Yc(r,".."):Yc(jx(),".typebulb")}function Ke(){return process.env.TYPEBULB_SERVERS_DIR||Yc(Ai(),"servers")}function ee(r){let e=Bx(r),t=e;try{t=Dx.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function um(r,e){let t=ee(r),n=ee(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var Ti=A(()=>{});import{readFileSync as Fx,writeFileSync as qx,mkdirSync as Ux}from"fs";import{join as Jx}from"path";function fm(){return Jx(Ai(),"trust.json")}function Vc(){try{let r=JSON.parse(Fx(fm(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function Kx(r){Ux(Ai(),{recursive:!0}),qx(fm(),JSON.stringify([...r]))}function Bt(r){return Vc().has(ee(r))}function br(r,e){let t=Vc(),n=ee(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),Kx(t))}function Gc(){return[...Vc()]}var _n=A(()=>{Ti()});function Ce(r){return r.length>5e4?r.slice(0,5e4)+`
|
|
368
|
+
\u2026[${r.length-5e4} more characters truncated]`:r}function He(r){let e=r.replace(Hx,"").split(`
|
|
369
|
+
`).map(i=>i.trim()).filter(Boolean),t=e[0];if(!t)return"";let n=t.length>300?t.slice(0,300).trimEnd()+"\u2026":t,s=e.length-1;return s>0?`${n} (+${s} line${s===1?"":"s"})`:n}var Hx,Pi,Oi=A(()=>{Hx=/\u001b\[[0-9;]*m/g;Pi=(r,e)=>``});import{existsSync as Wx,readdirSync as Yx,statSync as Vx}from"fs";import{join as Gx}from"path";function Ci(r){if(!Wx(r))return[];let e;try{e=Yx(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=Gx(r,n);try{let i=Vx(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var zc=A(()=>{});var wr,Qc=A(()=>{wr=class{ensureHarnessSupport(){}}});import{openSync as zx,readSync as Qx,closeSync as Xx,statSync as Zx,readdirSync as e0,readFileSync as t0,existsSync as r0}from"fs";import{join as Nn}from"path";import{homedir as el}from"os";function n0(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function _i(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?Pi(e.data,e.media_type):""}function Xc(r){return typeof r=="string"?Ce(r):Array.isArray(r)?r.map(e=>{if(typeof e=="string")return Ce(e);let t=e;return typeof t?.text=="string"?Ce(t.text):t?.content!=null?Xc(t.content):_i(t)}).join(`
|
|
370
|
+
`):r==null?"":Ce(JSON.stringify(r))}function i0(r){let e=r.trim();return!!e&&hm.some(t=>t.test(e))}function o0(r){let e=r.trim();return e?hm.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function c0(r){return r.replace(a0,"")}function l0(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 dt(r){let e=c0(r).trim();return e?l0(e)??(i0(e)?"":e):""}function Zc(r){return r?.type==="text"&&typeof r.text=="string"?dt(r.text):""}function tl(r,e){if(typeof r=="string")return He(r);if(!r||typeof r!="object")return He(e);let t=r;if(t.type==="text"&&typeof t.file?.numLines=="number")return Ee(t.file.numLines,"line");if(t.type==="image"){let n=pm(t.file?.originalSize);return n?`image (${n})`:"image"}if(t.type==="pdf"){let n=pm(t.file?.originalSize);return n?`PDF (${n})`:"PDF"}if(t.type==="parts"&&typeof t.file?.count=="number")return Ee(t.file.count,"page");if(t.type==="file_unchanged")return"unchanged since last read";if(t.type==="create"&&typeof t.content=="string")return`created, ${Ee(t.content.split(`
|
|
371
|
+
`).length,"line")}`;if(t.mode==="content")return Ee(t.numLines??0,"line");if(t.mode==="count")return`${Ee(t.numMatches??0,"match","matches")} (${Ee(t.numFiles??0,"file")})`;if(t.mode==="files_with_matches")return Ee(t.numFiles??0,"file");if(Array.isArray(t.structuredPatch)){let n=0,s=0;for(let i of t.structuredPatch)for(let o of i?.lines??[])typeof o=="string"&&(o.startsWith("+")?n++:o.startsWith("-")&&s++);return`+${n} \u2212${s}`}return typeof t.stdout=="string"||typeof t.stderr=="string"?t.backgroundTaskId?"running in background":t.interrupted?"interrupted":He(t.stdout||t.stderr||"")||"no output":typeof t.code=="number"&&typeof t.codeText=="string"?`${t.code} ${t.codeText}`:typeof t.searchCount=="number"?Ee(t.searchCount,"search","searches"):Array.isArray(t.matches)&&typeof t.total_deferred_tools=="number"?Ee(t.matches.length,"tool"):Array.isArray(t.newTodos)?Ee(t.newTodos.length,"todo"):typeof t.numFiles=="number"?Ee(t.numFiles,"file"):He(e)}function Rn(r){return!!r.isSidechain||!!r.isMeta}function u0(r){let e;try{e=zx(r,"r")}catch{return""}try{let n=65536;try{n=Zx(r).size}catch{}let s=(l,f)=>{if(f<=0)return"";let u=Buffer.alloc(f),d=Qx(e,u,0,f,l);return u.subarray(0,d).toString("utf8")},i=(l,f,u)=>{let d="";for(let p of l.split(`
|
|
372
|
+
`)){if(!p.includes(`"${f}"`))continue;let y;try{y=JSON.parse(p)}catch{continue}let m=y?.[u];y?.type===f&&typeof m=="string"&&m&&(d=m)}return d},o=s(0,Math.min(65536,n)),a=n>65536?s(n-65536,65536):"",c=i(a,"custom-title","customTitle")||i(o,"custom-title","customTitle")||i(a,"ai-title","aiTitle")||i(o,"ai-title","aiTitle");if(c)return c.replace(/\s+/g," ").trim().slice(0,200);for(let l of o.split(`
|
|
373
|
+
`)){if(!l.trim())continue;let f;try{f=JSON.parse(l)}catch{continue}if(!f||Rn(f)||f.type!=="user")continue;let u=f.message?.content,d="";typeof u=="string"?d=dt(u):Array.isArray(u)&&(d=u.map(Zc).filter(Boolean).join(" "));let p=d.replace(/\s+/g," ").trim();if(p)return(p.replace(/^Continuing from a prior session\. Here is the summary of our work so far:\s*/i,"").trim()||p).slice(0,200)}return""}finally{Xx(e)}}function f0(r){let e;try{e=e0(mm)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let n=JSON.parse(t0(Nn(mm,t),"utf8"));if(n?.sessionId!==r)continue;return process.kill(n.pid,0),!0}catch{}return!1}var s0,dm,hm,a0,Ee,pm,mm,vr,Ri=A(()=>{Oi();zc();Qc();s0=Nn(el(),".claude","projects"),dm=r=>Nn(s0,n0(r));hm=[/\[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];a0=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;Ee=(r,e,t=e+"s")=>`${r} ${r===1?e:t}`,pm=r=>typeof r!="number"?"":r<1024?`${r}B`:r<1048576?`${Math.round(r/1024)}KB`:`${(r/1048576).toFixed(1)}MB`;mm=Nn(el(),".claude","sessions");vr=class extends wr{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}detectsInstalled(){return r0(Nn(el(),".claude"))}sessionsDir(e){return dm(e)}listSessionFiles(e){return Ci(dm(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(Rn(e))return{events:[]};let n=[];if(e.type==="user"){let s=e.message?.content;if(typeof s=="string"){let i=dt(s);i&&n.push({type:"user",text:i})}else if(Array.isArray(s))for(let i of s)if(i?.type==="tool_result"){let o=Xc(i.content);n.push({type:"tool_result",id:i.tool_use_id??"",content:o,isError:!!i.is_error,digest:tl(e.toolUseResult,o)})}else{let o=Zc(i)||_i(i);o&&n.push({type:"user",text:o})}return{events:n}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=dt(Xc(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=>!o0(u)).join(""),a=i.filter(u=>u.type==="thinking").map(u=>u.thinking??"").join(`
|
|
374
|
+
`),c=i.filter(u=>u.type==="tool_use").map(u=>({id:u.id??"",name:u.name??"",input:u.input??{}}));if(o||a||c.length){let u=Date.parse(e.timestamp??""),d=!isNaN(u)&&u>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:d})}let l=e.message?.usage??e.usage,f=l&&{in:l.input_tokens??0,out:l.output_tokens??0,cached:l.cache_read_input_tokens??0,cacheCreate:l.cache_creation_input_tokens??0};return{events:n,usage:f,model:e.message?.model}}return{events:n}}chainWorking(e){let t;for(let o of e)(o.type==="user"||o.type==="assistant")&&(t=o);if(!t)return!1;if(t.type==="user"){try{let o=t.message?.content,a=typeof o=="string"?o:Array.isArray(o)?o.filter(l=>l&&l.type==="text").map(l=>l.text??"").join(""):"";if(!(Array.isArray(o)&&o.some(l=>l&&l.type==="tool_result"))&&a.trim()&&dt(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 f0(e)}readPreview(e){return u0(e)}searchText(e){if(!e||Rn(e)||e.type!=="user"&&e.type!=="assistant")return"";let t=e.message?.content,n="";if(typeof t=="string")n=dt(t);else if(Array.isArray(t)){let s=t;n=e.type==="user"?s.map(Zc).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{spawn as gm}from"child_process";import{readdir as d0,readFile as bm,writeFile as wm,unlink as rl,mkdir as p0}from"fs/promises";import{mkdirSync as vm,writeFileSync as Ni,appendFileSync as m0,readFileSync as nl}from"fs";import*as he from"path";import{fileURLToPath as h0}from"url";function sl(r){return he.join(Ke(),`${r}.json`)}function $n(r){return he.join(Ke(),`${r}.log`)}function il(r){return he.join(Ke(),`${r}.wait.json`)}function Sm(r){try{let e=JSON.parse(nl(il(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function ol(r,e=""){let t=Sm(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Ii(r,e,t=""){try{vm(Ke(),{recursive:!0});let n=Sm(r);n[t]=e,Ni(il(r),JSON.stringify({cursors:n}))}catch{}}function $i(r){let e=$n(r);try{vm(Ke(),{recursive:!0}),Ni(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(m0(e,c),s+=c.length,s>2*ym){let l=nl(e),f=l.subarray(Math.max(0,l.length-ym));Ni(e,f),s=f.length}}catch{i=!0}};return process.stdout.write=((a,...c)=>(o(a),t(a,...c))),process.stderr.write=((a,...c)=>(o(a),n(a,...c))),()=>{process.stdout.write=t,process.stderr.write=n}}function km(r){try{Ni($n(r),"")}catch{}}function _e(r,e=0){try{let t=nl($n(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 al(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function y0(r){let e=g0.exec(r);return e?Number(e[1]):void 0}function xm(r,e){let t=r.split(`
|
|
375
|
+
`),n=[];if(t.forEach((o,a)=>{let c=y0(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(`
|
|
376
|
+
`)}function cl(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function Em(r){await p0(Ke(),{recursive:!0}),await wm(sl(r.pid),JSON.stringify(r))}async function Am(r,e){let t=sl(r);try{let n=JSON.parse(await bm(t,"utf8"));if(n.denied===e)return;n.denied=e,await wm(t,JSON.stringify(n))}catch{}}async function In(r){await rl(sl(r)).catch(()=>{}),await rl($n(r)).catch(()=>{}),await rl(il(r)).catch(()=>{})}async function Y(r){let e;try{e=await d0(Ke())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!/^\d+\.json$/.test(s))return;let i=parseInt(s,10),o;try{o=JSON.parse(await bm(he.join(Ke(),s),"utf8"))}catch{await In(i);return}o&&typeof o.pid=="number"&&cl(o.pid)?t.push(o):await In(i)})),(r?t.filter(s=>s.agent==null&&um(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function ll(r,e){let t=ee(r);return(await Y()).find(n=>n.cwd!=null&&ee(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function jt(r){try{process.kill(r,"SIGTERM")}catch{}await In(r)}function Sr(r,e){let t=ee(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&ee(n.file)===t)}async function ul(r){let e=Sr(await Y(),r);for(let t of e)await jt(t.pid);return e}function w0(r,e,t){(process.platform==="win32"?gm("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):gm(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function Tm(){return he.join(he.dirname(h0(import.meta.url)),"index.js")}function v0(r,e={}){return{command:process.execPath,args:[Tm(),...e.trust?["--trust"]:[],r,...e.open===!1?["--no-open"]:[]]}}function S0(r){return{command:process.execPath,args:[Tm(),`agent:${r}`,"--no-open"]}}async function Pm(r,e,t,n){let s=await r();if(s)return s;w0(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await b0(150);let o=await r();if(o)return o}throw new Error(`Launched ${n} but it did not register within 20s.`)}async function Li(r,e={}){let t=e.cwd??process.cwd(),n=he.resolve(t,r);return await ul(n),Pm(async()=>Sr(await Y(),n)[0],v0(r,e),t,he.basename(r))}async function Om(r,e=process.cwd()){return Pm(()=>ll(e,r),S0(r),e,`the ${r} mirror`)}var ym,g0,b0,Re=A(()=>{Ti();ym=1e6;g0=/^── run (\d+) ── /;b0=r=>new Promise(e=>setTimeout(e,r))});function Mi(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 fl(r){return(Mi(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var dl=A(()=>{});import{readdirSync as k0,readFileSync as x0,statSync as E0}from"fs";import{join as Cm,basename as A0}from"path";function _m(r,e,t){if(e>8)return t;let n;try{n=k0(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;_m(Cm(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(Cm(r,s.name));return t}function Di(r){return _m(r,0,[]).map(e=>{let t=0;try{t=E0(e).mtimeMs}catch{}let n,s=!1;try{let i=x0(e,"utf8");n=Mi(i.slice(0,1024));let o=de(i);s=!!o&&Qs(ar(o))}catch{}return{path:e,name:n??A0(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var Rm=A(()=>{Be();gn();dl()});function kr(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")||r.infer.trim()||/\btb\s*\.\s*infer\b/.test(e))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 Bi=A(()=>{});import{readFile as T0}from"fs/promises";async function pl(r){try{let e=de(await T0(r,"utf-8"));return e?kr(ar(e)):void 0}catch{return}}var Nm=A(()=>{gn();Bi()});function ml(r){let e=de(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=_p(t);if(!n.length)return r;let s=e.files.get("config.json"),i={};if(s)try{let l=JSON.parse(s);l&&typeof l=="object"&&(i=l)}catch{}let o=i.dependencies&&typeof i.dependencies=="object"?{...i.dependencies}:{},a=n.filter(l=>!(l in o));if(!a.length)return r;for(let l of a)o[l]="latest";i.dependencies=o;let c={name:e.frontmatter.name};for(let[l,f]of e.files){let u=bu(l);u&&(c[u]=f)}return c.config=JSON.stringify(i,null,2),Tu(c)}var Im=A(()=>{Be();Xs()});import{spawn as $m}from"child_process";import{basename as P0}from"path";function O0(){return process.env.TYPEBULB_EDITOR||"code"}function _0(r,e,t){return t==null?[e]:C0.test(P0(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function R0(r,e){let t=O0();return{command:t,args:_0(t,r,e)}}function hl(r,e){let{command:t,args:n}=R0(r,e),s=process.platform==="win32"?$m("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):$m(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var C0,Lm=A(()=>{C0=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as N0,existsSync as I0}from"fs";import*as Ft from"path";import{fileURLToPath as $0}from"url";function Mm(){let r=Ft.dirname($0(import.meta.url));for(;!I0(Ft.join(r,"package.json"));){let e=Ft.dirname(r);if(e===r)break;r=e}return r}function qt(){return Ft.join(Mm(),"README.md")}function xr(){return Ft.join(Mm(),"description.md")}function L0(r){let e=N0(xr(),"utf8").trim().replace(/\s+/g," ");return`---
|
|
377
377
|
name: typebulb
|
|
378
378
|
description: ${JSON.stringify(e)}
|
|
379
379
|
version: ${r}
|
|
380
|
-
---`}function
|
|
380
|
+
---`}function M0(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 Dm(r,e){return`${L0(e)}
|
|
381
381
|
|
|
382
|
-
${
|
|
382
|
+
${M0(e)}
|
|
383
383
|
|
|
384
384
|
${r.trim()}
|
|
385
|
-
`}var
|
|
386
|
-
`)){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
|
|
387
|
-
Expected <origin>/u/<user>/<slug>`);let u=
|
|
388
|
-
A pull target must be a bulb URL, or a local file at typebulbs/u/<user>/<slug>.bulb.md \u2014 the path is its remote identity.`);return{origin:t,userSlug:o,slug:a.slice(0,-8),dest:n}}async function
|
|
389
|
-
`),n=de(t(r)),s=de(t(e));return!n||!s?t(r)===t(e):n.frontmatter.name===s.frontmatter.name&&Ge.every(i=>(n.files.get(
|
|
385
|
+
`}var ji=A(()=>{});import{readFileSync as Bm,existsSync as D0}from"fs";import*as Ne from"path";function jm(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function ge(r,e=process.cwd()){let t={},n=[];for(let s of jm(r)){let i;try{i=Bm(Ne.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[o,a]of Fm(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:r,sources:t,loaded:n}}function*Fm(r){for(let e of r.split(`
|
|
386
|
+
`)){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 Fi(r,e=process.cwd()){for(let t of jm()){let n;try{n=Bm(Ne.resolve(e,t),"utf-8")}catch{continue}for(let[s,i]of Fm(n))if(s===r)return i}return process.env[r]}function B0(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 pt(r,e,t){let{sources:n,mode:s,loaded:i}=r,o=process.cwd(),a=Ne.dirname(e),c=`(mode: ${s??"none"})`,l=t?B0(t):[],f=l.filter(p=>n[p]).map(p=>`${p} \u2190 ${n[p]}`);f.length?console.log(`env: ${f.join(", ")} ${c}`):i.length&&console.log(`env: loaded ${i.join(", ")} ${c}`),s&&!i.some(p=>p===`.env.${s}`||p===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=Ne.resolve(a)!==Ne.resolve(o);if(u)for(let p of[".env.local",".env"])D0(Ne.join(a,p))&&console.log(`env: ${Ne.join(a,p)} present but not loaded (cwd is ${o})`);let d=l.filter(p=>process.env[p]===void 0);if(d.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${d.join(", ")} but ${d.length>1?"they are":"it's"} unset${p}`)}}var mt=A(()=>{});import*as Ie from"fs/promises";import*as Ae from"path";function yl(r,e){ge(e);let t=process.env.TYPEBULB_ORIGIN||j0;try{return Ui(r,process.cwd(),t)}catch(n){console.error(n instanceof Error?n.message:String(n)),process.exit(1)}}function Ui(r,e,t){if(/^https?:\/\//i.test(r)){let c=new URL(r),l=c.pathname.split("/").filter(Boolean).map(decodeURIComponent),f=l[0]==="api"&&l[1]==="scripts"?l.slice(2):l;if(f[0]!=="u"||!f[1]||!f[2])throw new Error(`Not a bulb URL: ${r}
|
|
387
|
+
Expected <origin>/u/<user>/<slug>`);let u=f[1],d=f[2].replace(/(\.bulb)?\.md$/,"");return{origin:c.origin,userSlug:u,slug:d,dest:Ae.join(e,qi(u,d))}}let n=Ae.resolve(e,r),[s,i,o,a]=n.split(Ae.sep).slice(-4);if(s!=="typebulbs"||i!=="u"||!o||!a?.endsWith(".bulb.md"))throw new Error(`Not a conventional bulb path: ${r}
|
|
388
|
+
A pull target must be a bulb URL, or a local file at typebulbs/u/<user>/<slug>.bulb.md \u2014 the path is its remote identity.`);return{origin:t,userSlug:o,slug:a.slice(0,-8),dest:n}}async function Ji(r,e={}){let t=await fetch(gl(r),{headers:e.token?{Authorization:`Bearer ${e.token}`}:{},signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0});if(!t.ok)return{kind:"http-error",status:t.status};let n=t.headers.get("content-type");if(!n?.includes("text/markdown"))return{kind:"not-markdown",contentType:n};let s=await t.text(),i;try{i=await Ie.readFile(r.dest,"utf-8")}catch{}if(i!==void 0){if(F0(i,s))return{kind:"up-to-date",dest:r.dest};if(!e.force){let{mtime:a}=await Ie.stat(r.dest);return{kind:"conflict",dest:r.dest,localMtime:a,remoteLastModified:t.headers.get("last-modified")}}}await Ie.mkdir(Ae.dirname(r.dest),{recursive:!0}),await Ie.writeFile(r.dest,s);let o=new Date(t.headers.get("last-modified")??"");return isNaN(o.getTime())||await Ie.utimes(r.dest,new Date,o),{kind:"written",dest:r.dest,created:i===void 0}}function F0(r,e){let t=i=>i.replace(/\r\n/g,`
|
|
389
|
+
`),n=de(t(r)),s=de(t(e));return!n||!s?t(r)===t(e):n.frontmatter.name===s.frontmatter.name&&Ge.every(i=>(n.files.get(Te[i].path)||"")===(s.files.get(Te[i].path)||""))}async function qm(r,e){r||(console.error("Usage: typebulb pull <bulb url | typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1));let t=yl(r,e.mode),n=`${t.origin}/u/${t.userSlug}/${t.slug}`,s;try{s=await Ji(t,{force:e.force,token:process.env.TYPEBULB_TOKEN})}catch(o){console.error(`Could not reach ${t.origin}: ${o instanceof Error?o.message:String(o)}`),process.exitCode=1;return}let i=Ae.relative(process.cwd(),t.dest)||t.dest;switch(s.kind){case"written":console.log(`pulled ${n} \u2192 ${i}${s.created?"":" (overwritten)"}`);return;case"up-to-date":console.log(`up to date: ${i}`);return;case"conflict":console.error(`Refusing to overwrite ${i} \u2014 it differs from ${n}
|
|
390
390
|
local file modified ${s.localMtime.toISOString()}
|
|
391
391
|
remote last saved ${s.remoteLastModified??"unknown"}
|
|
392
|
-
Re-run with --force to overwrite the local file.`),process.exitCode=1;return;case"http-error":s.status===404?console.error(`Bulb not found: ${n}`):s.status===401||s.status===403?console.error(`This bulb is private (${s.status}) \u2014 pulling it needs a TYPEBULB_TOKEN for its owner.`):console.error(`Pull failed: ${t.origin} responded ${s.status}`),process.exitCode=1;return;case"not-markdown":console.error(`${n}.md did not return bulb markdown (got ${s.contentType??"no content-type"}) \u2014 is ${t.origin} a typebulb host?`),process.exitCode=1}}var
|
|
392
|
+
Re-run with --force to overwrite the local file.`),process.exitCode=1;return;case"http-error":s.status===404?console.error(`Bulb not found: ${n}`):s.status===401||s.status===403?console.error(`This bulb is private (${s.status}) \u2014 pulling it needs a TYPEBULB_TOKEN for its owner.`):console.error(`Pull failed: ${t.origin} responded ${s.status}`),process.exitCode=1;return;case"not-markdown":console.error(`${n}.md did not return bulb markdown (got ${s.contentType??"no content-type"}) \u2014 is ${t.origin} a typebulb host?`),process.exitCode=1}}var j0,qi,gl,Ki=A(()=>{mt();Be();j0="https://typebulb.com",qi=(r,e)=>Ae.join("typebulbs","u",r,`${e}.bulb.md`),gl=r=>`${r.origin}/u/${encodeURIComponent(r.userSlug)}/${encodeURIComponent(r.slug)}.md`});import*as Er from"fs/promises";import*as Jm from"path";async function Hi(r,e){let t=await Er.readFile(r.dest,"utf-8"),{mtime:n}=await Er.stat(r.dest),s={Authorization:`Bearer ${e.token}`,"Content-Type":"text/markdown; charset=utf-8"};e.force||(s["If-Unmodified-Since"]=n.toUTCString());let i=await fetch(gl(r),{method:"PUT",body:t,headers:s,signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0}),o=await i.text();if(i.status===409)return{kind:"conflict",message:Um(o)};if(!i.ok)return{kind:"http-error",status:i.status,message:Um(o)};let a=JSON.parse(o);return await Er.utimes(r.dest,new Date,new Date(a.updatedAt)),{kind:"pushed",created:a.created,serverStripped:a.serverStripped,updatedAt:a.updatedAt}}function Um(r){try{return JSON.parse(r).error||r}catch{return r}}async function Km(r,e){r||(console.error("Usage: typebulb push <typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1)),/^https?:\/\//i.test(r)&&(console.error("push takes a local .bulb.md file, not a URL (the path is its remote identity)"),process.exit(1));let t=yl(r,e.mode),n=process.env.TYPEBULB_TOKEN;n||(console.error("push needs TYPEBULB_TOKEN in your .env \u2014 create one on your typebulb.com settings page."),process.exit(1));let s=`${t.origin}/u/${t.userSlug}/${t.slug}`,i=Jm.relative(process.cwd(),t.dest)||t.dest,o;try{o=await Hi(t,{token:n,force:e.force})}catch(a){let c=a instanceof Error?a.message:String(a);console.error(a?.code==="ENOENT"?`File not found: ${i}`:`Could not push to ${t.origin}: ${c}`),process.exitCode=1;return}switch(o.kind){case"pushed":console.log(`pushed ${i} \u2192 ${s}${o.created?" (created, unlisted)":""}`),o.serverStripped&&console.log("note: the server.ts block was stripped on the server copy (CLI-only); your local file is untouched.");return;case"conflict":console.error(`${o.message}
|
|
393
393
|
pull to see the remote: typebulb pull ${i}
|
|
394
|
-
or overwrite it: typebulb push ${i} --force`),process.exitCode=1;return;case"http-error":o.status===401?console.error("The server rejected TYPEBULB_TOKEN (401) \u2014 it may be revoked; mint a new one on the settings page."):console.error(`Push failed: ${t.origin} responded ${o.status}${o.message?` \u2014 ${o.message}`:""}`),process.exitCode=1}}var
|
|
394
|
+
or overwrite it: typebulb push ${i} --force`),process.exitCode=1;return;case"http-error":o.status===401?console.error("The server rejected TYPEBULB_TOKEN (401) \u2014 it may be revoked; mint a new one on the settings page."):console.error(`Push failed: ${t.origin} responded ${o.status}${o.message?` \u2014 ${o.message}`:""}`),process.exitCode=1}}var bl=A(()=>{Ki()});var Ar=A(()=>{Re();Rm();Nm();dl();Im();Lm();_n();Dt();Dt();Si();ji();Ki();bl();mt()});import{copyFileSync as q0,existsSync as Hm,mkdirSync as Wm,rmSync as U0,writeFileSync as J0}from"fs";import{homedir as K0}from"os";import*as $e from"path";import{fileURLToPath as H0}from"url";function Q0(){return z0.replace('"__TB_DESCRIPTION_PATH__"',JSON.stringify(xr())).replace('"__TB_README_PATH__"',JSON.stringify(qt()))}function Ym(){try{if(!Hm(Wi()))return}catch{return}try{let r=W0();Wm($e.dirname(r),{recursive:!0}),J0(r,Q0()),U0(Y0(),{force:!0})}catch{}try{let r=V0();if(!Hm(r))return;let e=G0();Wm($e.dirname(e),{recursive:!0}),q0(r,e)}catch{}}var Wi,W0,Y0,V0,G0,z0,Vm=A(()=>{Ar();Wi=()=>$e.join(K0(),".pi","agent"),W0=()=>$e.join(Wi(),"extensions","typebulb.ts"),Y0=()=>$e.join(Wi(),"extensions","typebulb-wait.ts"),V0=()=>$e.join($e.dirname(H0(import.meta.url)),"agents","pi","matchu-patchu.ts"),G0=()=>$e.join(Wi(),"extensions","matchu-patchu.ts"),z0=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
|
|
395
395
|
import { spawn } from "node:child_process";
|
|
396
396
|
import { existsSync } from "node:fs";
|
|
397
397
|
|
|
@@ -540,31 +540,31 @@ export default function (pi) {
|
|
|
540
540
|
try { pi.on("session_shutdown", () => { for (const c of pending) { try { c.kill(); } catch (e) {} } pending.clear(); }); } catch (e) {}
|
|
541
541
|
} catch (e) { logErr("load", e && e.message); }
|
|
542
542
|
}
|
|
543
|
-
`});function U(r){return r?.message??String(r)}var K,ht=A(()=>{K=process.cwd()});import{spawn as
|
|
544
|
-
`))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var
|
|
545
|
-
`)}catch{}await Promise.race([this.#v,
|
|
546
|
-
`)}catch{}}#p(e,t){let n=e.length>200?e.slice(0,200)+"\u2026":e;n&&(this.#n={text:n,kind:t,until:Date.now()+(t==="info"?
|
|
543
|
+
`});function U(r){return r?.message??String(r)}var K,ht=A(()=>{K=process.cwd()});import{spawn as Gm}from"child_process";import{StringDecoder as X0}from"string_decoder";function oE(r,e){let t=new X0("utf8"),n="";r.on("data",s=>{n+=typeof s=="string"?s:t.write(s);let i;for(;(i=n.indexOf(`
|
|
544
|
+
`))>=0;){let o=n.slice(0,i);n=n.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var Z0,eE,zm,tE,rE,nE,sE,iE,Yi,Vi,Qm,Xm=A(()=>{ht();Z0=3e4,eE=5e3,zm=2e3,tE=2e3,rE=12e4,nE=8e3,sE=15e3,iE=new Set(["get_state","get_commands","get_available_models","set_model","set_thinking_level","cycle_thinking_level","get_session_stats","compact","set_auto_compaction","get_fork_messages","fork","clone","set_session_name","export_html","bash","abort_bash"]),Yi=new Set;process.on("exit",()=>{for(let r of Yi)try{r.kill()}catch{}});Vi=class{#e;#a=!1;#c=0;#i=!1;#l=null;#m=null;#t=null;#n=null;#u=new Map;#r=[];#h=null;#w=null;#g=null;#f;#d;#y="";#A=1;#s=new Map;#v;#b;constructor(e,t,n=(s,i)=>Gm(s,{cwd:i,shell:!0,stdio:["pipe","pipe","pipe"],env:{...process.env,TYPEBULB_MIRROR:"1"}})){if(this.#v=new Promise(o=>{this.#b=o}),t?.includes('"')){this.#d="session path contains a quote \u2014 cannot drive it",this.#b();return}let s=t?`pi --mode rpc --session "${t}"`:"pi --mode rpc",i;try{i=n(s,e)}catch(o){this.#d=`could not start pi: ${U(o)}`,this.#b();return}this.#e=i,this.#f=t,Yi.add(i),i.stdout&&oE(i.stdout,o=>this.#T(o)),i.stderr&&i.stderr.on("data",o=>{this.#y=(this.#y+o.toString()).slice(-tE)}),i.on("error",o=>this.#x(`could not start pi: ${o.message}`)),i.on("exit",o=>{this.#e===i&&this.#x(o?`pi exited (code ${o})${this.#y.trim()?`: ${this.#y.trim()}`:""}`:"pi exited"),Yi.delete(i),this.#b()}),this.#o({type:"get_state"}).then(o=>{let a=o.data?.sessionFile;typeof a=="string"&&a&&(this.#f=a);let c=o.data?.model;c&&typeof c.id=="string"&&c.id&&(this.#g=c.id)}).catch(()=>{}),this.#S()}get streaming(){return this.#a||Date.now()<this.#c}get draft(){return this.#l}get echo(){return this.#m}get queue(){return this.#h}get stats(){return this.#w}get model(){return this.#g}get sessionFile(){return this.#f}get error(){return this.#d}get status(){if(this.#t)return this.#t;if(this.#n){if(Date.now()<this.#n.until)return{text:this.#n.text,kind:this.#n.kind};this.#n=null}return this.#u.size?{text:[...this.#u.values()].join(" \xB7 "),kind:"info"}:null}get dialog(){let e=Date.now();for(;this.#r.length;){let t=this.#r[0];if(e<t.until)return t.req;this.#r.shift(),t.ownTimeout||this.#k({type:"extension_ui_response",id:t.req.id,cancelled:!0})}return null}notice(e,t){this.#p(e,t)}respondUi(e,t){let n=this.#r.findIndex(o=>o.req.id===e);if(n<0)return{ok:!1,error:"dialog expired or already answered"};let[s]=this.#r.splice(n,1),i={type:"extension_ui_response",id:e};return t.cancelled?i.cancelled=!0:s.req.method==="confirm"?i.confirmed=!!t.confirmed:i.value=t.value??"",this.#k(i),{ok:!0}}async rpc(e){if(!iE.has(e.type))return{ok:!1,error:`command not allowed: ${e.type}`};try{let t=await this.#o(e);if(t.success&&e.type==="set_model"){let n=t.data?.id;typeof n=="string"&&n&&(this.#g=n)}if(t.success&&(e.type==="fork"||e.type==="clone")){try{let s=(await this.#o({type:"get_state"})).data?.sessionFile;typeof s=="string"&&s&&(this.#f=s)}catch{}return{ok:!0,data:{...t.data??{},sessionFile:this.#f}}}return t.success?{ok:!0,data:t.data}:{ok:!1,error:t.error??`pi rejected ${e.type}`}}catch(t){return{ok:!1,error:U(t)}}}async send(e,t){let n=this.streaming,s=n?e.trimStart().startsWith("/")?{type:"prompt",message:e,streamingBehavior:t?.followUp?"followUp":"steer"}:{type:t?.followUp?"follow_up":"steer",message:e}:{type:"prompt",message:e},i;try{i=await this.#o(s)}catch(o){return{ok:!1,error:U(o)}}return i.success&&!n&&(this.#c=Date.now()+eE),i.success&&!n&&!e.trimStart().startsWith("/")&&(this.#m=e),i.success?{ok:!0}:{ok:!1,error:i.error??"pi rejected the message"}}async stop(){if(this.#e)try{await this.#o({type:"abort"})}catch{}}clearCompletedDraft(){this.#i||(this.#l=null)}clearEcho(){this.#m=null}async dispose(){let e=this.#e;if(e){if(this.#e=void 0,this.#a){try{e.stdin?.write(JSON.stringify({type:"abort"})+`
|
|
545
|
+
`)}catch{}await Promise.race([this.#v,Qm(zm)])}try{e.stdin?.end()}catch{}if(await Promise.race([this.#v,Qm(zm)]),e.exitCode===null&&!e.killed)if(process.platform==="win32"&&e.pid)try{Gm("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}else try{e.kill("SIGKILL")}catch{}Yi.delete(e),this.#r=[],this.#E("pi was shut down")}}#k(e){try{this.#e?.stdin?.write(JSON.stringify(e)+`
|
|
546
|
+
`)}catch{}}#p(e,t){let n=e.length>200?e.slice(0,200)+"\u2026":e;n&&(this.#n={text:n,kind:t,until:Date.now()+(t==="info"?nE:sE)})}#S(){this.#o({type:"get_session_stats"}).then(e=>{if(!e.success||!e.data)return;let t=e.data;this.#w={cost:typeof t.cost=="number"?t.cost:0,contextTokens:typeof t.contextUsage?.tokens=="number"?t.contextUsage.tokens:null,contextPercent:typeof t.contextUsage?.percent=="number"?t.contextUsage.percent:null}}).catch(()=>{})}#o(e){let t=this.#e;if(!t?.stdin?.writable)return Promise.reject(new Error(this.#d??"pi is not running"));let n=`tb-${this.#A++}`;return new Promise((s,i)=>{let o=setTimeout(()=>{this.#s.delete(n),i(new Error("pi did not respond (30s)"))},Z0);o.unref?.(),this.#s.set(n,{resolve:s,timer:o});try{t.stdin.write(JSON.stringify({id:n,...e})+`
|
|
547
547
|
`)}catch(a){clearTimeout(o),this.#s.delete(n),i(new Error(U(a)))}})}#T(e){let t;try{t=JSON.parse(e)}catch{return}switch(t.type){case"response":{let n=t,s=n.id?this.#s.get(n.id):void 0;s&&(this.#s.delete(n.id),clearTimeout(s.timer),s.resolve(n));return}case"agent_start":this.#a=!0,this.#c=0;return;case"agent_end":this.#a=!1,this.#c=0,this.#i=!1,this.#t=null,this.#h=null,this.#S();return;case"message_start":{t.message?.role==="assistant"&&(this.#i=!0,this.#l={text:"",thinking:""});return}case"message_update":{if(!this.#i)return;let n=t.message,s=Array.isArray(n?.content)?n.content:[];this.#l={text:s.filter(i=>i?.type==="text").map(i=>i.text??"").join(""),thinking:s.filter(i=>i?.type==="thinking").map(i=>i.thinking??"").join(`
|
|
548
|
-
`)};return}case"message_end":this.#i=!1;return;case"auto_retry_start":this.#t={text:`retrying after a transient error (attempt ${Number(t.attempt)||1}/${Number(t.maxAttempts)||"?"})\u2026`,kind:"warning"};return;case"auto_retry_end":this.#t=null,t.success===!1&&this.#p(`retries exhausted: ${String(t.finalError??"unknown error")}`,"error");return;case"compaction_start":this.#t={text:"compacting context\u2026",kind:"info"};return;case"compaction_end":{this.#t=null;let n=t.result;typeof t.errorMessage=="string"&&t.errorMessage?this.#p(`compaction failed: ${t.errorMessage}`,"error"):n?.tokensBefore&&this.#p(`compacted: ~${Math.round(n.tokensBefore/1e3)}k \u2192 ~${Math.round((n.estimatedTokensAfter??0)/1e3)}k tokens`,"info"),this.#S();return}case"queue_update":{let n=Array.isArray(t.steering)?t.steering.map(String):[],s=Array.isArray(t.followUp)?t.followUp.map(String):[];this.#h=n.length||s.length?{steering:n,followUp:s}:null;return}case"extension_ui_request":{let n=String(t.method??"");if(n==="select"||n==="confirm"||n==="input"||n==="editor"){let s=typeof t.timeout=="number"&&t.timeout>0?t.timeout:void 0;this.#r.push({req:{id:String(t.id??""),method:n,title:typeof t.title=="string"?t.title:void 0,message:typeof t.message=="string"?t.message:void 0,options:Array.isArray(t.options)?t.options.map(String):void 0,placeholder:typeof t.placeholder=="string"?t.placeholder:void 0,prefill:typeof t.prefill=="string"?t.prefill:void 0},until:Date.now()+(s??
|
|
549
|
-
`),c=i.filter(
|
|
550
|
-
`))if(p.includes('"session_info"'))try{let y=JSON.parse(p);y?.type==="session_info"&&typeof y.name=="string"&&y.name&&(
|
|
551
|
-
`))if(!(l||!u.includes('"type"')))try{let
|
|
552
|
-
`):""}}});var
|
|
553
|
-
`)){let a=/^(\d+)\t(\d+)\t(.+)$/.exec(o);a&&i.set(a[3],{add:+a[1],del:+a[2]})}for(let o of t){let a=i.get(o.path);a&&(o.add=a.add,o.del=a.del)}}catch{}return t.sort((s,i)=>s.path.localeCompare(i.path)),{repo:!0,root:r,files:t}}catch(e){return{repo:!1,root:"",files:[],error:U(e)}}}async function
|
|
554
|
-
|
|
555
|
-
${r.slice(0,
|
|
556
|
-
`))>=0;){let q=g.partial.slice(0,
|
|
557
|
-
`).filter(Boolean).map(async w=>{try{return{f:w,m:(await
|
|
558
|
-
`)){if(!B.trim())continue;let $=r.parseEntry(B);if(!$)continue;let J=r.searchText($);J&&_.push({text:J,lower:J.toLowerCase()})}return
|
|
559
|
-
`)){if(!$.trim())continue;let J=r.parseEntry($);if(J)for(let q of r.apply(J,e.sessionStartMs).events)q.type==="assistant"&&q.text.trim()&&(
|
|
560
|
-
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=
|
|
561
|
-
${r}`;return gt?.key===e&&Date.now()-gt.fetchedAt<=
|
|
562
|
-
`)}function
|
|
548
|
+
`)};return}case"message_end":this.#i=!1;return;case"auto_retry_start":this.#t={text:`retrying after a transient error (attempt ${Number(t.attempt)||1}/${Number(t.maxAttempts)||"?"})\u2026`,kind:"warning"};return;case"auto_retry_end":this.#t=null,t.success===!1&&this.#p(`retries exhausted: ${String(t.finalError??"unknown error")}`,"error");return;case"compaction_start":this.#t={text:"compacting context\u2026",kind:"info"};return;case"compaction_end":{this.#t=null;let n=t.result;typeof t.errorMessage=="string"&&t.errorMessage?this.#p(`compaction failed: ${t.errorMessage}`,"error"):n?.tokensBefore&&this.#p(`compacted: ~${Math.round(n.tokensBefore/1e3)}k \u2192 ~${Math.round((n.estimatedTokensAfter??0)/1e3)}k tokens`,"info"),this.#S();return}case"queue_update":{let n=Array.isArray(t.steering)?t.steering.map(String):[],s=Array.isArray(t.followUp)?t.followUp.map(String):[];this.#h=n.length||s.length?{steering:n,followUp:s}:null;return}case"extension_ui_request":{let n=String(t.method??"");if(n==="select"||n==="confirm"||n==="input"||n==="editor"){let s=typeof t.timeout=="number"&&t.timeout>0?t.timeout:void 0;this.#r.push({req:{id:String(t.id??""),method:n,title:typeof t.title=="string"?t.title:void 0,message:typeof t.message=="string"?t.message:void 0,options:Array.isArray(t.options)?t.options.map(String):void 0,placeholder:typeof t.placeholder=="string"?t.placeholder:void 0,prefill:typeof t.prefill=="string"?t.prefill:void 0},until:Date.now()+(s??rE),ownTimeout:s!==void 0})}else if(n==="notify"){let s=t.notifyType==="warning"?"warning":t.notifyType==="error"?"error":"info";this.#p(String(t.message??""),s),console.log(`[composer] pi extension: ${String(t.message??"")}`)}else if(n==="setStatus"){let s=String(t.statusKey??"");typeof t.statusText=="string"&&t.statusText?this.#u.set(s,t.statusText):this.#u.delete(s)}return}default:return}}#x(e){this.#d=e,this.#a=!1,this.#c=0,this.#i=!1,this.#l=null,this.#m=null,this.#t=null,this.#n=null,this.#u.clear(),this.#r=[],this.#h=null,this.#w=null,this.#g=null,this.#e=void 0,this.#E(e)}#E(e){for(let[,t]of this.#s)clearTimeout(t.timer),t.resolve({type:"response",success:!1,error:e});this.#s.clear()}},Qm=r=>new Promise(e=>{setTimeout(e,r).unref?.()})});import{existsSync as Zm,readFileSync as aE,realpathSync as cE}from"fs";import{join as Ut,dirname as nh,resolve as lE}from"path";import{homedir as eh}from"os";function fE(r,e){let t=Ut(r,".pi");if(uE.some(s=>Zm(Ut(t,s))))return!0;let n=Ut(e,".agents","skills");for(let s=r;;){let i=Ut(s,".agents","skills");if(i!==n&&Zm(i))return!0;let o=nh(s);if(o===s)return!1;s=o}}function dE(r,e){for(let t=e;;){if(r[t]===!0||r[t]===!1)return!0;let n=nh(t);if(n===t)return!1;t=n}}function sh(r,e){try{let t=e?.agentDir??Ut(eh(),".pi","agent"),n=th(e?.home??process.env.HOME??eh()),s=th(lE(r));if(!fE(s,n))return null;let i=rh(Ut(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||dE(rh(Ut(t,"trust.json")),s)?null:"pi has no trust decision for this project \u2014 running untrusted; run `pi` once in a terminal to grant it"}catch{return null}}var uE,th,rh,ih=A(()=>{uE=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],th=r=>{try{return cE(r)}catch{return r}},rh=r=>{try{return JSON.parse(aE(r,"utf8"))}catch{return{}}}});import{statSync as pE,openSync as mE,readSync as hE,closeSync as gE,existsSync as yE}from"fs";import{join as wl}from"path";import{homedir as ah}from"os";function wE(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function oh(r){return r.type==="message"?vE(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var bE,vE,Tr,vl=A(()=>{Oi();zc();Qc();Vm();Xm();ih();bE=wl(ah(),".pi","agent","sessions");vE=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";Tr=class extends wr{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return yE(wl(ah(),".pi","agent"))}ensureHarnessSupport(){Ym()}createDriver(e,t){let n=new Vi(e,t),s=sh(e);return s&&n.notice(s,"warning"),n}sessionsDir(e){return wl(bE,wE(e))}listSessionFiles(e){return Ci(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 oh(e)}isRecoveryNoise(e){return!1}apply(e,t){let n=[];if(e.type==="custom_message"){if(e.display===!1)return{events:n};let i=this.contentText(e.content).trim();return i&&n.push({type:"user",text:i}),{events:n}}if(e.type!=="message"||!e.message)return{events:n};let s=e.message;if(s.role==="user"){let i=this.contentText(s.content).trim();return i&&n.push({type:"user",text:i}),{events:n}}if(s.role==="toolResult"){let i=this.contentText(s.content);return n.push({type:"tool_result",id:s.toolCallId??"",content:i,isError:!!s.isError,digest:He(i)}),{events:n}}if(s.role==="bashExecution")return s.command&&!s.excludeFromContext&&n.push({type:"user",text:`$ ${s.command}`}),{events:n};if(s.role==="assistant"){let i=Array.isArray(s.content)?s.content:[],o=i.filter(d=>d.type==="text").map(d=>d.text??"").join(""),a=i.filter(d=>d.type==="thinking").map(d=>d.thinking??"").join(`
|
|
549
|
+
`),c=i.filter(d=>d.type==="toolCall").map(d=>({id:d.id??"",name:d.name??"",input:d.arguments??{}}));if(o||a||c.length){let d=Date.parse(e.timestamp??""),p=!isNaN(d)&&d>=t;n.push({type:"assistant",text:o,thinking:a,tools:c,live:p})}let l=s.usage,f=l?(l.input??0)+(l.output??0)+(l.cacheRead??0)+(l.cacheWrite??0):0,u=l&&f>0&&s.stopReason!=="aborted"&&s.stopReason!=="error"?{in:l.input??0,out:l.output??0,cached:l.cacheRead??0,cacheCreate:l.cacheWrite??0}:void 0;return{events:n,usage:u,model:s.model,cost:l?.cost?.total}}return{events:n}}chainWorking(e){let t;for(let a of e)oh(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=mE(e,"r")}catch{return""}try{let s=65536;try{s=pE(e).size}catch{}let i=(u,d)=>{let p=Buffer.alloc(d),y=hE(t,p,0,d,u);return p.subarray(0,y).toString("utf8")},o=i(0,Math.min(65536,s)),a=s>65536?i(s-65536,65536):"",c=u=>{let d="";for(let p of u.split(`
|
|
550
|
+
`))if(p.includes('"session_info"'))try{let y=JSON.parse(p);y?.type==="session_info"&&typeof y.name=="string"&&y.name&&(d=y.name)}catch{}return d},l="";for(let u of o.split(`
|
|
551
|
+
`))if(!(l||!u.includes('"type"')))try{let d=JSON.parse(u);d?.type==="message"&&d.message?.role==="user"&&(l=this.contentText(d.message.content).replace(/\s+/g," ").trim())}catch{}let f=c(a)||c(o)||l;return f?f.slice(0,200):""}finally{gE(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"?Ce(e):Array.isArray(e)?e.map(t=>typeof t?.text=="string"?Ce(t.text):t?.type==="image"&&t.data?Pi(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
552
|
+
`):""}}});var Gi,ch=A(()=>{Gi=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});import{execFile as SE}from"child_process";import{promisify as kE}from"util";import{readFile as xE}from"fs/promises";import{resolve as lh,sep as EE}from"path";async function Pr(r,e){let{stdout:t}=await AE("git",r,{cwd:e,maxBuffer:67108864});return t}async function Or(){if(zi)return zi;try{zi=(await Pr(["rev-parse","--show-toplevel"],K)).trim()}catch{}return zi}function TE(r,e){let t=e===" "?r:e;return t==="?"?"U":t}async function fh(){let r=await Or();if(!r)return{repo:!1,root:"",files:[]};try{let e=await Pr(["status","--porcelain","-z"],r),t=[],n=e.split("\0");for(let s=0;s<n.length;s++){let i=n[s];i.length<4||((i[0]==="R"||i[0]==="C")&&s++,t.push({path:i.slice(3),status:TE(i[0],i[1])}))}try{let s=await Pr(["diff","--numstat","HEAD"],r),i=new Map;for(let o of s.split(`
|
|
553
|
+
`)){let a=/^(\d+)\t(\d+)\t(.+)$/.exec(o);a&&i.set(a[3],{add:+a[1],del:+a[2]})}for(let o of t){let a=i.get(o.path);a&&(o.add=a.add,o.del=a.del)}}catch{}return t.sort((s,i)=>s.path.localeCompare(i.path)),{repo:!0,root:r,files:t}}catch(e){return{repo:!1,root:"",files:[],error:U(e)}}}async function dh(r){let e=await Or();if(!e)return{ok:!1,error:"not a git repository"};try{if((await Pr(["status","--porcelain","-z","--",r],e)).startsWith("??")){let s=lh(e,r);if(!s.startsWith(lh(e)+EE))return{ok:!1,error:"outside repository"};let i=await xE(s);return i.includes(0)?Sl("Binary file (not shown)",!1):Sl(i.toString("utf8"),!0)}let n;try{n=await Pr(["diff","--no-color","--unified=999999","HEAD","--",r],e)}catch{n=await Pr(["diff","--no-color","--unified=999999","--",r],e)}return Sl(n,!1)}catch(t){return{ok:!1,error:U(t)}}}var AE,uh,zi,Sl,Qi=A(()=>{ht();AE=kE(SE),uh=2e6;Sl=(r,e)=>({ok:!0,text:r.slice(0,uh),untracked:e,truncated:r.length>uh})});function Xi(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 kl=A(()=>{});var Zi,eo,ph=A(()=>{Zi=".typebulb/paste",eo={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp"}});import{existsSync as PE,mkdirSync as OE,writeFileSync as CE,readFileSync as _E}from"fs";import{join as to}from"path";function mh(){let r=new Date,e=t=>String(t).padStart(2,"0");return`${r.getFullYear()}${e(r.getMonth()+1)}${e(r.getDate())}-${e(r.getHours())}${e(r.getMinutes())}${e(r.getSeconds())}`}function $E(r){return r.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function LE(r){let e=AbortSignal.timeout(RE);for(let[t,n]of IE){let s=Ue(t,n);if(typeof s!="string"){try{let i=await ut(s,{messages:[{role:"user",content:`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
|
|
554
|
+
|
|
555
|
+
${r.slice(0,NE)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=$E(await Lt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function hh(r,e){if(!e||e.kind!=="image"&&e.kind!=="text")return{ok:!1,error:"bad paste kind"};if(typeof e.data!="string"||!e.data)return{ok:!1,error:"empty paste"};let t=to(r,Zi);try{OE(t,{recursive:!0})}catch(a){return{ok:!1,error:U(a)}}let n,s,i;if(e.kind==="image"){if(n=`img-${mh()}`,s=Object.keys(eo).find(a=>eo[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else n=await LE(e.data)??`paste-${mh()}`,s="md",i=e.data;let o=`${n}.${s}`;for(let a=2;PE(to(t,o));a++)o=`${n}-${a}.${s}`;try{CE(to(t,o),i)}catch(a){return{ok:!1,error:U(a)}}return{ok:!0,path:`${Zi}/${o}`}}function gh(r,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),n=eo[t];if(!n)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:n,base64:_E(to(r,Zi,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var RE,NE,IE,yh=A(()=>{mr();Ar();ht();ph();RE=4e3,NE=4e3,IE=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});import{existsSync as bh,openSync as ME,readSync as DE,closeSync as BE,statSync as Cr,readdirSync as wh,watchFile as jE,unwatchFile as vh,mkdirSync as FE,writeFileSync as qE,readFileSync as ro,unlinkSync as UE,rmSync as JE}from"fs";import{stat as KE}from"fs/promises";import{dirname as HE,join as Jt,resolve as Sh}from"path";import{execFile as WE}from"child_process";function zE(r){if(!Number.isInteger(r))return!0;try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}function no(r){let e={cwd:K,sessionId:"",sessionStartMs:Date.now(),buffer:[],partial:"",offset:0,latest:{in:0,out:0,cached:0,cacheCreate:0},latestModel:null,everAttached:!1,entries:new Map},t=new Set,n;function s(){if(e.file){for(let g of t)if(g.file===e.file)return g;return}return n}function i(g){let v={d:r.createDriver(e.cwd,g),file:g};return t.add(v),e.file||(n=v),v}async function o(g){t.delete(g),n===g&&(n=void 0);try{await g.d.dispose()}catch(v){console.error("[composer] dispose:",U(v))}}function a(){let g=s();for(let v of[...t])v!==g&&(v.d.streaming||v.d.queue||v.d.error||o(v))}function c(){for(let g of t)g.d.sessionFile&&g.file!==g.d.sessionFile&&(g.file=g.d.sessionFile);if(n&&!e.file&&n.file){let g=r.listSessionFiles(e.cwd).find(v=>v.file===n.file);g&&C(g)}}let l=g=>Jt(g,VE),f=(g,v)=>Jt(l(g),`${v}.lock`);function u(g,v){try{let w=f(g,v);if(Date.now()-Cr(w).mtimeMs>=kh)return!1;try{let _=parseInt(ro(w,"utf8").trim(),10);if(_===process.pid||!zE(_))return!1}catch{}return!0}catch{return!1}}function d(g,v){if(v)try{FE(l(g),{recursive:!0}),qE(f(g,v),String(process.pid))}catch(w){console.error("[lock] claim failed:",U(w))}}function p(g){try{JE(Jt(g,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function y(g){let v=l(g);if(!bh(v))return;let w;try{w=wh(v)}catch{return}let _=Date.now();for(let L of w){if(!L.endsWith(".lock"))continue;let B=Jt(v,L);try{let $=Cr(B);_-$.mtimeMs>GE&&UE(B)}catch{}}}function m(g){try{return Cr(g),!1}catch(v){return v.code==="ENOENT"}}function b(){let g=e;if(g.file&&!m(g.file)){d(g.cwd,g.sessionId);return}let v=k(g);v&&C(v)}function k(g){if(!g.everAttached)return x(g.cwd)??T(g.cwd,()=>!0)}function x(g){let v=l(g);if(!bh(v))return;let w;try{w=wh(v)}catch{return}let _;for(let B of w)if(B.endsWith(".lock"))try{let $=Cr(Jt(v,B));if(Date.now()-$.mtimeMs>=kh||parseInt(ro(Jt(v,B),"utf8").trim(),10)!==process.pid)continue;(!_||$.mtimeMs>_.mtime)&&(_={sessionId:B.slice(0,-5),mtime:$.mtimeMs})}catch{}if(!_)return;let L=r.listSessionFiles(g).find(B=>B.sessionId===_.sessionId);if(!(!L||m(L.file)))return L}function T(g,v){return r.listSessionFiles(g).sort((w,_)=>_.mtime-w.mtime).find(w=>!u(g,w.sessionId)&&v(w))}function P(g,v){let w=e;if(w.file)try{vh(w.file)}catch{}w.file=g,w.sessionId=v,w.partial="",w.offset=0,w.latest={in:0,out:0,cached:0,cacheCreate:0},w.latestModel=null,w.entries=new Map,w.chainLastId=void 0,w.buffer.push({type:"cleared"}),w.buffer.push({type:"session",sessionId:v})}function C(g){let v=e;n=void 0,P(g.file,g.sessionId),v.everAttached=!0,d(v.cwd,g.sessionId),R();try{vh(g.file)}catch{}jE(g.file,{interval:200},()=>R())}function O(){P(void 0,"")}function R(){let g=e;if(!g.file)return;let v;try{v=Cr(g.file).size}catch{return}if(v<=g.offset)return;let w;try{w=ME(g.file,"r")}catch{return}try{let q=v-g.offset,le=Buffer.alloc(q),Q=0;for(;Q<q;){let iu=DE(w,le,Q,q-Q,g.offset+Q);if(!iu)break;Q+=iu}g.offset+=Q,g.partial+=le.subarray(0,Q).toString("utf8")}finally{BE(w)}let _,L;for(;(L=g.partial.indexOf(`
|
|
556
|
+
`))>=0;){let q=g.partial.slice(0,L);if(g.partial=g.partial.slice(L+1),!q.trim())continue;let le=r.parseEntry(q);if(!le)continue;let Q=r.idOf(le);Q&&(g.entries.set(Q,le),!r.isSidechain(le)&&r.isLeafType(le)&&(_=Q))}if(!_)return;let B=[],$=g.entries.get(_),J=!1;for(;$;){if(B.push($),r.idOf($)===g.chainLastId){J=!0;break}let q=r.parentOf($);$=q?g.entries.get(q):void 0}if(J)for(let q=B.length-2;q>=0;q--)D(B[q]);else{g.chainLastId!==void 0&&(g.buffer.push({type:"cleared"}),g.buffer.push({type:"session",sessionId:g.sessionId}),g.latest={in:0,out:0,cached:0,cacheCreate:0});let q=new Set(B.map(Q=>r.idOf(Q))),le=h(g.entries);for(let Q=B.length-1;Q>=0;Q--)D(B[Q]),S(r.idOf(B[Q]),le,q)}g.chainLastId=_}function h(g){let v=new Map;for(let w of g.values()){let _=r.parentOf(w);if(!_)continue;let L=v.get(_);L?L.push(w):v.set(_,[w])}return v}function S(g,v,w){if(!g)return;let _=v.get(g);if(!_)return;let L=_.filter(q=>!r.isSidechain(q));if(L.length<2)return;let B=L.filter(q=>!w.has(r.idOf(q)));if(!B.length)return;let $=[],J=0;for(let q of B){let le=I(q,v);$.push(...le.events),J+=le.count}J>0&&e.buffer.push({type:"fork",atId:g,count:J,events:$})}function I(g,v){let w=[],_=[g];for(;_.length;){let $=_.pop();if(r.isSidechain($))continue;w.push($);let J=v.get(r.idOf($)??"");if(J)for(let q of J)_.push(q)}w.sort(($,J)=>(Date.parse(r.timestampOf($)??"")||0)-(Date.parse(r.timestampOf(J)??"")||0));let L=[];for(let $ of w)r.isRecoveryNoise($)||L.push(...r.apply($,e.sessionStartMs).events);return{count:L.reduce(($,J)=>$+(J.type==="user"||J.type==="assistant"?1:0),0),events:L}}function D(g){try{let{events:v,usage:w,model:_,cost:L}=r.apply(g,e.sessionStartMs);for(let B of v)e.buffer.push(B);v.some(B=>B.type==="assistant")&&s()?.d.clearCompletedDraft(),v.some(B=>B.type==="user")&&s()?.d.clearEcho(),_&&(e.latestModel=_),w&&(e.latest=w),(w||L)&&e.buffer.push({type:"usage",...e.latest,cost:L})}catch(v){console.error("[mirror] skipped malformed entry:",U(v))}}async function N(){return{cwd:e.cwd,pid:process.pid,composer:!!r.createDriver,elsewhere:await X()}}async function X(){if(r.listSessionFiles(e.cwd).length)return;let g=await Or();if(!g)return;let v=Sh(g).toLowerCase();for(let w=Sh(e.cwd);w.toLowerCase()!==v;){let _=HE(w);if(_===w)return;w=_;let L=r.listSessionFiles(w).length;if(L)return{dir:w,count:L}}}X().then(g=>{g&&console.log(`No sessions for ${e.cwd} \u2014 ${g.count} exist for ${g.dir}. Launched from a subfolder? Relaunch from the project root.`)}).catch(()=>{});let fe=new Gi;async function vt(g,v){fe.accept(g,v)&&console.log(v)}function te(){let g=r.sessionAlive(e.sessionId,e.cwd);if(g!==void 0)return g;if(!e.file)return!1;try{return Date.now()-Cr(e.file).mtimeMs<1e4}catch{return!1}}function z(){return r.chainWorking([...e.entries.values()])&&te()}function St(){!r.createDriver||s()||e.latestModel||z()||i(e.file)}async function Ve(g){let v=e;b(),c(),St(),a();let w=s();for(let $ of t)$!==w&&$.d.dialog;let _=new Set([...t].filter($=>$.d.streaming&&$.file).map($=>$.file)),L=_.size?r.listSessionFiles(v.cwd).filter($=>_.has($.file)).map($=>$.sessionId):[],B=r.createDriver?{streaming:!!w?.d.streaming,draft:w?.d.draft??null,echo:w?.d.echo??null,status:w?.d.status??null,dialog:w?.d.dialog??null,queue:w?.d.queue??null,stats:w?.d.stats??null,model:w?.d.model??null,error:w?.d.error}:void 0;return{events:v.buffer.slice(g),cursor:v.buffer.length,working:!!w?.d.streaming||z(),latestModel:v.latestModel,composer:B,busy:L}}async function tu(){b(),c();let g=s();if(g?.d.error&&!g.d.streaming&&(await o(g),g=void 0),!g){if(z())return{ok:!1,error:"the agent is mid-turn in a terminal \u2014 watch only"};g=i(e.file)}return{ok:!0,d:g.d}}async function Sy(g,v){if(!r.createDriver)return{ok:!1,error:"not supported"};let w=String(g??"").trim();if(!w)return{ok:!1,error:"empty message"};let _=await tu();return _.ok?_.d.send(w,v):_}async function ky(g,v){let w=s();return w?w.d.respondUi(String(g??""),v??{}):{ok:!1,error:"no dialog pending"}}async function xy(g,v){if(!r.createDriver)return{ok:!1,error:"not supported"};if(!g||typeof g.type!="string")return{ok:!1,error:"bad command"};if(v?.spawn){let _=await tu();return _.ok?_.d.rpc(g):_}let w=s();return!w||w.d.error?{ok:!1,error:"not running"}:w.d.rpc(g)}async function Ey(){let g=s();if(g)try{await g.d.stop()}catch(v){console.error("[composer] stop:",U(v))}return{ok:!0}}async function Ay(){return r.createDriver?(c(),!e.file&&n&&!n.d.streaming&&!n.d.error?{ok:!0}:(n?.d.error&&await o(n),n=void 0,e.file&&O(),i(void 0),a(),{ok:!0})):{ok:!1,error:"not supported"}}async function Ty(){if(!r.createDriver)return[];let g=await new Promise(w=>{WE("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e.cwd,maxBuffer:64*1024*1024},(_,L)=>w(_?"":L))});return(await Promise.all(g.split(`
|
|
557
|
+
`).filter(Boolean).map(async w=>{try{return{f:w,m:(await KE(Jt(e.cwd,w))).mtimeMs}}catch{return{f:w,m:0}}}))).sort((w,_)=>_.m-w.m).map(w=>w.f)}function Py(){for(let g of[...t])o(g)}async function Oy(g){return r.createDriver?hh(e.cwd,g):{ok:!1,error:"not supported"}}async function Cy(g){return gh(e.cwd,String(g??""))}async function _y(){return r.listSessionFiles(e.cwd).sort((g,v)=>v.mtime-g.mtime).map(({sessionId:g,file:v,mtime:w})=>({sessionId:g,mtime:w,preview:r.readPreview(v)}))}let ru=new Map;function Ry(g,v){let w=ru.get(g);if(w&&w.mtime===v)return w.turns;let _=[],L="";try{L=ro(g,"utf8")}catch{return[]}for(let B of L.split(`
|
|
558
|
+
`)){if(!B.trim())continue;let $=r.parseEntry(B);if(!$)continue;let J=r.searchText($);J&&_.push({text:J,lower:J.toLowerCase()})}return ru.set(g,{mtime:v,turns:_}),_}async function Ny(g){let v=g.toLowerCase(),w=[];for(let{sessionId:_,file:L,mtime:B}of r.listSessionFiles(e.cwd).sort(($,J)=>J.mtime-$.mtime)){let{hitCount:$,snippet:J}=Xi(Ry(L,B),v);if($&&(w.push({sessionId:_,mtime:B,preview:r.readPreview(L),hitCount:$,snippet:J}),w.length>=QE))break}return w}let nu=800,su=new Map;function Iy(g,v){let w=su.get(g);if(w&&w.mtime===v)return w.text;let _="";try{_=ro(g,"utf8")}catch{return""}let L="";for(let $ of _.split(`
|
|
559
|
+
`)){if(!$.trim())continue;let J=r.parseEntry($);if(J)for(let q of r.apply(J,e.sessionStartMs).events)q.type==="assistant"&&q.text.trim()&&(L=q.text.trim())}let B=L.length>nu?L.slice(0,nu).trimEnd()+"\u2026":L;return su.set(g,{mtime:v,text:B}),B}async function $y(g){let v=r.listSessionFiles(e.cwd).find(w=>w.sessionId===g);return{text:v?Iy(v.file,v.mtime):""}}async function Ly(g){let v=e,w=r.listSessionFiles(v.cwd).find(_=>_.sessionId===g);return w?w.file===v.file?{ok:!0}:(C(w),c(),a(),{ok:!0}):{ok:!1,error:"session not found"}}return p(e.cwd),y(e.cwd),b(),{info:N,poll:Ve,logEmbedStatus:vt,listSessions:_y,searchSessions:Ny,sessionPeek:$y,attach:Ly,composerSend:Sy,composerStop:Ey,composerNew:Ay,composerFiles:Ty,composerUiRespond:ky,composerRpc:xy,composerPaste:Oy,composerPasteRead:Cy,shutdownComposer:Py}}var YE,VE,kh,GE,QE,xl=A(()=>{ht();ch();Qi();kl();yh();YE=".typebulb",VE=`${YE}/locks`,kh=5e3,GE=6e4;QE=50});import{existsSync as Pl,mkdirSync as XE,readFileSync as xh,writeFileSync as ZE}from"fs";import{join as Kt,isAbsolute as eA}from"path";async function Eh(r,e){let t=eA(r)?r:Kt(K,r);return Pl(t)?(hl(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function Ah(r){let e=K,t=ml(r),n=Kt(e,"typebulbs");XE(n,{recursive:!0});let s=fl(t),i=`${s}.bulb.md`;for(let l=2;Pl(Kt(n,i))&&xh(Kt(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=Kt(n,i);Pl(o)||ZE(o,t);let a=Kt("typebulbs",i),c=await Li(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function Th(){return Y(K)}async function Ph(r){return await jt(r),{ok:!0}}async function Oh(){return Di(K).filter(r=>!r.serverOnly).map(r=>({...r,trusted:Bt(r.path)}))}async function Ch(r){let e=r.toLowerCase(),t=[];for(let n of Di(K).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=xh(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
|
|
560
|
+
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=Xi(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function _h(r,e){let t=K;e!=null&&br(r,e);let n=await Li(r,{cwd:t,open:!1,trust:e});return{ok:!0,file:n.file,pid:n.pid,url:n.url,trust:!!n.trust}}async function Rh(r){return{cap:await pl(r)}}async function Nh(r,e){return br(r,e),{ok:!0}}async function Ih(r,e){return _e(r,e)}async function Dh(){return Ln&&Date.now()-Ln.fetchedAt<=rA?Ln.samples:(El??=nA().finally(()=>{El=null}),El)}async function nA(){try{let r=await fetch(`${tA}/api/scripts/u/samples?stubs`,{signal:AbortSignal.timeout(Lh)});if(!r.ok)throw new Error(`HTTP ${r.status}`);let e=await r.json(),t=i=>i.order??Number.MAX_SAFE_INTEGER,n=i=>Date.parse(i.createdAt??"")||0,s=e.filter(i=>i.slug!=="welcome").sort((i,o)=>t(i)-t(o)||n(o)-n(i)).map(i=>({slug:i.slug,name:i.name,description:Do(i.config)}));return Ln={samples:s,fetchedAt:Date.now()},s}catch{return Ln?.samples??[]}}async function Bh(r){return Ol.test(r)?qh($h,"samples",r,!0):{ok:!1,error:"bad slug"}}async function jh(){let r=Cl();if(!r)return{bulbs:[]};let e=`${so()}
|
|
561
|
+
${r}`;return gt?.key===e&&Date.now()-gt.fetchedAt<=sA?{user:gt.user,bulbs:gt.bulbs}:(Al??=iA(e,r).finally(()=>{Al=null}),Al)}async function Tl(r,e,t){let n=await fetch(`${r}${e}`,{headers:t,signal:AbortSignal.timeout(Lh)});if(!n.ok)throw new Error(`HTTP ${n.status}`);if(!n.headers.get("content-type")?.includes("json"))throw new Error("not json");return n.json()}async function iA(r,e){let t={Authorization:`Bearer ${e}`};try{let n=so(),s;try{s=await Tl(n,"/api/me",t)}catch{let a=new URL(n);n=`${a.protocol}//api.${a.host}`,s=await Tl(n,"/api/me",t)}let o=(await Tl(n,"/api/scripts/list",t)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:Do(a.config)}));return gt={key:r,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return gt?.key===r?{user:gt.user,bulbs:gt.bulbs}:{bulbs:[]}}}async function Fh(r,e,t=!1){return!Ol.test(e)||!Ol.test(r)?{ok:!1,error:"bad slug"}:qh(so(),r,e,t)}async function qh(r,e,t,n){let s=qi(e,t);try{let i=await Ji({origin:r,userSlug:e,slug:t,dest:Kt(K,s)},{force:n,token:Cl(),timeoutMs:Mh});return i.kind==="conflict"?{ok:!1,conflict:!0,error:"local file differs from the site copy"}:i.kind==="http-error"?{ok:!1,error:`HTTP ${i.status}`}:i.kind==="not-markdown"?{ok:!1,error:`not a bulb (${i.contentType??"no content-type"})`}:{ok:!0,file:s,upToDate:i.kind==="up-to-date"}}catch(i){return{ok:!1,error:i?.message??String(i)}}}async function Uh(r,e=!1){let t=Cl();if(!t)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let n=Ui(r,K,so()),s=await Hi(n,{token:t,force:e,timeoutMs:Mh});return s.kind==="conflict"?{ok:!1,conflict:!0,error:s.message}:s.kind==="http-error"?{ok:!1,error:`HTTP ${s.status}: ${s.message}`}:{ok:!0,created:s.created,serverStripped:s.serverStripped}}catch(n){return{ok:!1,error:n?.message??String(n)}}}var tA,$h,rA,Lh,Mh,Ln,El,Ol,sA,gt,Al,so,Cl,_l=A(()=>{Ar();ht();kl();Be();tA="https://api.typebulb.com",$h="https://typebulb.com",rA=3600*1e3,Lh=5e3,Mh=15e3,Ln=null,El=null;Ol=/^[a-z0-9][a-z0-9-]*$/,sA=300*1e3,gt=null,Al=null,so=()=>Fi("TYPEBULB_ORIGIN",K)||$h,Cl=()=>Fi("TYPEBULB_TOKEN",K)});import{readFileSync as Il,writeFileSync as Kh,mkdirSync as oA,appendFileSync as Hh,rmSync as Jh}from"fs";import{join as ao,dirname as aA}from"path";import{createServer as cA}from"http";function yt(r){try{return JSON.parse(Il(r,"utf8"))}catch{return null}}function oo(r,e){oA(aA(r),{recursive:!0}),Kh(r,JSON.stringify(e,null,2)+`
|
|
562
|
+
`)}function Yh(r,e,t){let n=ao(r,".gitignore"),s="";try{s=Il(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(`
|
|
563
563
|
`)?`
|
|
564
|
-
`:"";try{
|
|
564
|
+
`:"";try{Hh(n,a+t+`
|
|
565
565
|
`+o.join(`
|
|
566
566
|
`)+`
|
|
567
|
-
`)}catch(c){console.error("[switcher] .gitignore update failed",U(c))}}function
|
|
567
|
+
`)}catch(c){console.error("[switcher] .gitignore update failed",U(c))}}function pA(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?Bn="live":s>dA&&(Bn="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 mA(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 zh(r){let e;try{e=JSON.parse(r)}catch{return r}Dn=typeof e?.model=="string"?e.model:null,Le&&(e.model=Le),Wt&&(e.provider=Vh(Wt));let t=/haiku/i.test(Dn||"");return jn!=null&&!t&&(e.reasoning={effort:Rl[jn]}),delete e.thinking,e.output_config&&delete e.output_config.effort,mA(e),JSON.stringify(e)}function hA(){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}
|
|
568
568
|
data: ${JSON.stringify(a)}
|
|
569
569
|
|
|
570
570
|
`}case"content_block_delta":case"content_block_stop":{let c=t.get(a.index);return c==null?null:(a.index=c,`event: ${a.type}
|
|
@@ -572,11 +572,11 @@ data: ${JSON.stringify(a)}
|
|
|
572
572
|
|
|
573
573
|
`)}default:return i}};return i=>{r+=i;let o="",a;for(;(a=r.indexOf(`
|
|
574
574
|
|
|
575
|
-
`))!==-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
|
|
575
|
+
`))!==-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 gA(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 Mn(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 yA(r,e,t){if(!Le){Mn(e,400,"invalid_request_error",fA);return}let n=process.env.OPENROUTER_API_KEY;if(!n){Mn(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($l,{method:"POST",headers:Gh(r,n),body:zh(t),signal:s.signal})}catch(u){Mn(e,502,"api_error",`proxy upstream failed: ${U(u)}`);return}let o=i.headers.get("content-type")||"application/json";if(e.writeHead(i.status,{"content-type":o}),!i.body){e.end();return}let a=o.includes("event-stream"),c=i.body.getReader(),l=new TextDecoder,f=a?hA():null;try{for(;;){let{done:u,value:d}=await c.read();if(u)break;if(d)if(f){let p=l.decode(d,{stream:!0});pA(p);let y=f(p);y&&e.write(y)}else e.write(Buffer.from(d))}}catch{}finally{e.writableEnded||e.end()}}async function bA(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(!Le||!n)return s();try{let i=await fetch(`${$l}/count_tokens`,{method:"POST",headers:Gh(r,n),body:zh(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function wA(r,e){let t=r.url||"/";if(r.method==="HEAD"){e.writeHead(200),e.end();return}if(r.method!=="POST"){Mn(e,404,"not_found_error",t);return}gA(r).then(n=>{if(t.includes("count_tokens"))return bA(r,e,n);if(t.includes("/v1/messages"))return yA(r,e,n);Mn(e,404,"not_found_error",t)})}function vA(){return _r&&Ht?Promise.resolve(Ht):new Promise((r,e)=>{let t=cA(wA);t.on("error",e),t.listen(0,"127.0.0.1",()=>{_r=t,Ht=t.address().port,console.log(`[switcher] wire proxy listening on ${io(Ht)}`),r(Ht)})})}function SA(){try{_r?.close()}catch{}_r=null,Ht=null}function kA(r,e){let t=co(r),n=yt(t),s=n||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===io(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=lo(r);if(!yt(i)){let a={};for(let c of Wh)a[c]=c in s.env?s.env[c]:null;oo(i,{managedBy:"agent-switcher",fileExisted:n!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=io(e),s.env.ANTHROPIC_AUTH_TOKEN=uA,oo(t,s),Yh(r,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function xA(r,e,t){let n=lo(r),s=yt(n)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},oo(n,s)}function Qh(r){let e=co(r),t=lo(r),n=yt(t),s=yt(e);if(s?.env){let i=n?.snapshot||{};for(let o of Wh){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{Jh(e,{force:!0})}catch{}else oo(e,s)}try{Jh(t,{force:!0})}catch{}}async function EA(){let r=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await qe()).filter(n=>n.provider==="openrouter"&&!Ll(n.name)).map(n=>({id:n.name,label:n.friendlyName||n.name}))}catch(n){console.error("[switcher] model list failed",U(n))}let t=e.length?void 0:Jc()??void 0;return{hasKey:r,models:e,error:t}}async function AA(){if(_r&&Le)return{active:!0,managed:!0,model:Le,port:Ht,provider:Wt,routedModel:Dn,caching:Bn,reasoning:jn,externalBaseUrl:null};let r=yt(co(K))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:jn,externalBaseUrl:r.ANTHROPIC_BASE_URL||null}}async function Xh(r,e){let t=await vA();return Le=r,Wt=e,kA(K,t),t}async function TA({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(Ll(r))return{ok:!1,error:"Refusing to route an Anthropic model through OpenRouter \u2014 that bills full API rate with no caching. Use it on your Anthropic subscription instead."};try{await Xh(r,Ml[r]??null),Dn=null,Bn="unknown",xA(K,r,Wt)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${U(e)}`}}return{ok:!0}}async function PA({level:r}){return r!=null&&(!Number.isInteger(r)||r<0||r>=Rl.length)?{ok:!1,error:`reasoning level must be 0\u2013${Rl.length-1} or null`}:(jn=r,{ok:!0,level:r})}async function OA(){return Qh(K),Le=null,Wt=null,Dn=null,Bn="unknown",{ok:!0}}async function CA({key:r}){let e=(r||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=K,n=ao(t,".env"),s="";try{s=Il(n,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))Kh(n,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
|
|
576
576
|
`)?`
|
|
577
|
-
`:"";
|
|
578
|
-
`)}}catch(i){return{ok:!1,error:U(i)}}return process.env.OPENROUTER_API_KEY=e,
|
|
579
|
-
`)}catch(o){return{ok:!1,error:`could not write ${r}: ${U(o)}`}}return{ok:!0,count:e.length}}var
|
|
577
|
+
`:"";Hh(n,i+`OPENROUTER_API_KEY=${e}
|
|
578
|
+
`)}}catch(i){return{ok:!1,error:U(i)}}return process.env.OPENROUTER_API_KEY=e,Yh(t,[".env"],"# secrets"),{ok:!0}}function _A(){if(!(!_r&&!Le)){try{Qh(K)}catch{}SA()}}function RA(r,e){return Zh.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 NA(r){if(Zh.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 IA(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=Nl(e?.cache_read_input_tokens)||Nl(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 $A({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(Ll(r))return{ok:!1,error:"Anthropic model \u2014 not offered or probed via OpenRouter"};let t=Date.now(),n=Array(350).fill("Caching probe filler sentence; its only purpose is to exceed the prompt-cache minimum token threshold.").join(" "),s={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":"2023-06-01"},i={model:r,max_tokens:64,system:[{type:"text",text:n,cache_control:{type:"ephemeral"}}],messages:[{role:"user",content:"Reply with exactly: ok"}]},o=async a=>{let c=new AbortController,l=setTimeout(()=>c.abort(),2e4);try{let f=JSON.stringify(a?{...i,provider:Vh(a)}:i),u=await fetch($l,{method:"POST",signal:c.signal,headers:s,body:f}),d=await u.json().catch(()=>({}));return{r:u,j:d}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let k=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:RA(a.status,k),restriction:NA(k)}}let l=typeof c?.provider=="string"?c.provider:void 0,f=c?.content?.find?.(k=>k.type==="text")?.text??c?.content?.[0]?.text??"ok",u=Nl(c?.usage?.cache_creation_input_tokens),{r:d,j:p}=await o(l),{works:y,read:m,note:b}=IA(d.ok,p?.usage,l);return y===!0&&l&&(Ml[r]=l,Le===r&&(Wt=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:l,sample:String(f).trim().slice(0,60),cache:{works:y,created:u,read:m,note:b}}}catch(a){let c=U(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var lA,$l,uA,fA,Wh,dA,Rl,co,lo,io,Ll,_r,Ht,Le,Wt,Dn,Bn,jn,Ml,Nl,Vh,Zh,eg=A(()=>{Ar();ht();lA="https://openrouter.ai/api",$l=`${lA}/v1/messages`,uA="typebulb-proxy-managed",fA="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.",Wh=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],dA=5e3,Rl=["low","medium","high"],co=r=>ao(r,".claude","settings.local.json"),lo=r=>ao(r,".claude",".cc-switcher.json"),io=r=>`http://127.0.0.1:${r}`;Ll=r=>/^anthropic\//i.test(r)||/claude/i.test(r),_r=null,Ht=null,Le=null,Wt=null,Dn=null,Bn="unknown",jn=1,Ml={},Nl=r=>typeof r=="number"?r:0,Vh=r=>({order:[r],allow_fallbacks:!1});Zh=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=yt(lo(K)),t=e?.active?.model;if(!t)return;let s=(yt(co(K))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await Xh(t,e.active.provider??Ml[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${io(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",U(e))}})()});var rg={};ou(rg,{attach:()=>UA,blockToMarkdown:()=>_i,breakout:()=>Ah,capText:()=>Ce,cleanUserText:()=>dt,clearSwitchModel:()=>OA,composerPasteRead:()=>JA,displayName:()=>LA,downloadSample:()=>Bh,firstLineDigest:()=>He,gitChangedFiles:()=>fh,gitDiff:()=>dh,info:()=>MA,isHiddenTurn:()=>Rn,launchBulb:()=>_h,listBreakouts:()=>Th,listBulbFiles:()=>Oh,listMyBulbs:()=>jh,listSamples:()=>Dh,listSessions:()=>jA,listSwitchModels:()=>EA,logEmbedStatus:()=>BA,openFile:()=>Eh,poll:()=>DA,predictTrustOf:()=>Rh,probeModel:()=>$A,pullRemoteBulb:()=>Fh,pushLocalBulb:()=>Uh,readBulbLog:()=>Ih,repoRoot:()=>Or,saveOpenRouterKey:()=>CA,searchBulbs:()=>Ch,searchSessions:()=>FA,sessionPeek:()=>qA,setBulbTrust:()=>Nh,setReasoning:()=>PA,setSwitchModel:()=>TA,shutdownSwitcher:()=>_A,stopBreakout:()=>Ph,switchState:()=>AA,toolResultDigest:()=>tl});var tg,LA,MA,DA,BA,jA,FA,qA,UA,JA,ng=A(()=>{xl();Ri();_l();Qi();eg();Ri();Oi();tg=new vr,LA=tg.displayName,{info:MA,poll:DA,logEmbedStatus:BA,listSessions:jA,searchSessions:FA,sessionPeek:qA,attach:UA,composerPasteRead:JA}=no(tg)});import{readFileSync as KA,writeFileSync as HA,mkdirSync as WA}from"fs";import{homedir as YA}from"os";import*as uo from"path";async function og(){try{let r=await fetch(new URL("/api/tags",ig()).toString(),{signal:AbortSignal.timeout(VA)});return r.ok?((await r.json()).models??[]).map(t=>t.name).filter(t=>!!t):[]}catch{return[]}}function ag(r){let e;try{e=KA(r,"utf-8")}catch{return{json:void 0,unreadable:!1}}try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t)){let n=t;return{json:n,unreadable:"providers"in n&&!Dl(n)}}}catch{}return{json:void 0,unreadable:!0}}function Dl(r){let e=r?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function GA(r){let e=Dl(r);if(!e||!("ollama"in e))return null;let t=e.ollama?.models;return Array.isArray(t)?t.map(n=>n?.id).filter(n=>typeof n=="string"):[]}async function cg(){let{json:r,unreadable:e}=ag(sg());return e?{installed:[],configured:null}:{installed:await og(),configured:GA(r)}}async function lg(){let r=await og();return r.length?zA(sg(),r,ig()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function zA(r,e,t){let{json:n,unreadable:s}=ag(r);if(s)return{ok:!1,error:`could not parse ${r} \u2014 edit the ollama provider there yourself`};let i={...n??{},providers:{...Dl(n)??{},ollama:{baseUrl:`${t}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{WA(uo.dirname(r),{recursive:!0}),HA(r,JSON.stringify(i,null,2)+`
|
|
579
|
+
`)}catch(o){return{ok:!1,error:`could not write ${r}: ${U(o)}`}}return{ok:!0,count:e.length}}var VA,sg,ig,ug=A(()=>{ht();Ar();VA=1500,sg=()=>uo.join(YA(),".pi","agent","models.json"),ig=()=>gr(process.env.OLLAMA_HOST??"http://localhost:11434")});var dg={};ou(dg,{attach:()=>sT,breakout:()=>Ah,composerFiles:()=>cT,composerNew:()=>aT,composerPaste:()=>fT,composerPasteRead:()=>dT,composerRpc:()=>uT,composerSend:()=>iT,composerStop:()=>oT,composerUiRespond:()=>lT,displayName:()=>QA,downloadSample:()=>Bh,gitChangedFiles:()=>fh,gitDiff:()=>dh,info:()=>XA,launchBulb:()=>_h,listBreakouts:()=>Th,listBulbFiles:()=>Oh,listMyBulbs:()=>jh,listSamples:()=>Dh,listSessions:()=>tT,logEmbedStatus:()=>eT,ollamaOffer:()=>cg,ollamaSync:()=>lg,openFile:()=>Eh,poll:()=>ZA,predictTrustOf:()=>Rh,pullRemoteBulb:()=>Fh,pushLocalBulb:()=>Uh,readBulbLog:()=>Ih,repoRoot:()=>Or,searchBulbs:()=>Ch,searchSessions:()=>rT,sessionPeek:()=>nT,setBulbTrust:()=>Nh,shutdownComposer:()=>pT,stopBreakout:()=>Ph});var fg,QA,XA,ZA,eT,tT,rT,nT,sT,iT,oT,aT,cT,lT,uT,fT,dT,pT,pg=A(()=>{xl();vl();_l();Qi();ug();fg=new Tr,QA=fg.displayName,{info:XA,poll:ZA,logEmbedStatus:eT,listSessions:tT,searchSessions:rT,sessionPeek:nT,attach:sT,composerSend:iT,composerStop:oT,composerNew:aT,composerFiles:cT,composerUiRespond:lT,composerRpc:uT,composerPaste:fT,composerPasteRead:dT,shutdownComposer:pT}=no(fg)});import*as vy from"fs/promises";import*as Vt from"path";import*as hu from"path";import*as cu from"fs/promises";import{existsSync as Gt,readFileSync as Jy}from"fs";import*as V from"path";import{pathToFileURL as Ky}from"url";import{resolve as _o}from"resolve.exports";import{init as lu,parse as uu}from"es-module-lexer";function fu(r,e){let t=V.join(r,"package.json");try{return JSON.parse(Jy(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var Co=["browser","import","default"],au=["node","import","default"];function du(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:V.resolve(n)}}async function pu(r){let{name:e,dir:t}=r;if(!Gt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=fu(t,e),s=Hy(n,e),i=V.resolve(t,s);if(!Gt(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=V.dirname(i),a=`/local/${e}/${V.basename(i)}`,c=Wy(n,t);return await Yy(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function Hy(r,e){if(r.exports!==void 0){let n;try{n=_o(r,".",{browser:!0,conditions:Co})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Co.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=Ro(n);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Co.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 Wy(r,e){if(r.exports!==void 0)try{let n=_o(r,".",{conditions:["types"]}),s=Ro(n);if(s){let i=V.resolve(e,s);if(Gt(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=V.resolve(e,t);if(Gt(n))return n}}function Ro(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function Yy(r,e,t){await lu;let n=V.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 cu.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=uu(a,o)}catch{continue}if(o===e&&!l)throw new Error(`override package '${r}' entry is not an ES module (no import/export syntax); CommonJS or non-module entries aren't supported (esm.sh would have to transform it).`);for(let f of c){if(f.d===-2)continue;let u=f.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let d=Vy(o,u,n);d&&!s.has(d)&&i.push(d);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${r} externalizes '${u}'`)}}}}function Vy(r,e,t){let n=e.replace(/[?#].*$/,""),s=V.resolve(V.dirname(r),n),i=[s,s+".js",s+".mjs",V.join(s,"index.js"),V.join(s,"index.mjs")];for(let o of i)if(V.normalize(o).startsWith(t)&&Gt(o))return o}function Gy(r,e,t){let n=fu(r,e),s;if(n.exports!==void 0)try{s=Ro(_o(n,t,{conditions:au}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${au.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=V.resolve(r,s);if(!Gt(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return Ky(i).href}async function mu(r,e){await lu;let t;try{[t]=uu(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=Gy(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var zy=5e3;function gu(r){let t={subcommand:"run",file:"",port:3e3,watch:!0,open:!(process.env.TERM_PROGRAM==="vscode"),server:!1,trust:!1,noTrust:!1,force:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},n=["call","check","predict","logs","wait","stop","trust","untrust","skill","models","send","pull","push"],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==="--force")t.force=!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==="--dir"){let c=r[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --dir (a subfolder of the bulb's folder, e.g. --dir batch2)"),process.exit(1));let l=c.replace(/[\\/]+$/,"");(!l||hu.isAbsolute(l)||l.split(/[\\/]/).some(f=>f===""||f===".."))&&(console.error(`Invalid --dir value: ${c} (a relative subfolder of the bulb's folder \u2014 no absolute paths or '..')`),process.exit(1)),t.dir=l}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=zy;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=du(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 if(!a.startsWith("-"))t.subcommand==="call"||t.subcommand==="send"?i.push(a):t.file=a;else{let c=t.subcommand==="call"?" (for a negative or dash-leading argument, use --args '<json-array>')":"";console.error(`Unknown option: ${a}${c}`),process.exit(1)}}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 yu(){console.log(`
|
|
580
580
|
typebulb - Local bulb runner for Typebulb
|
|
581
581
|
|
|
582
582
|
Usage:
|
|
@@ -672,6 +672,11 @@ Options:
|
|
|
672
672
|
--mode <name> Also load .env.<name> (+ .env.<name>.local) on top
|
|
673
673
|
of .env / .env.local. Free-form name; loads no mode
|
|
674
674
|
file by default.
|
|
675
|
+
--dir <sub> Scope the bulb's dir to a subfolder for this run:
|
|
676
|
+
tb.dir and relative tb.fs paths land in
|
|
677
|
+
<bulb-folder>/<sub>. Batch runs without touching
|
|
678
|
+
the bulb's code (e.g. --dir batch2). Relative
|
|
679
|
+
subpaths only \u2014 no absolute paths or '..'.
|
|
675
680
|
--server Run server.ts only, no web server (needs --trust)
|
|
676
681
|
--args <json-array> For 'call': the whole argument list as one JSON
|
|
677
682
|
array (strict). '--args -' reads it from stdin,
|
|
@@ -718,11 +723,11 @@ Examples:
|
|
|
718
723
|
typebulb my-editor.bulb.md
|
|
719
724
|
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
720
725
|
typebulb .
|
|
721
|
-
`)}gn();import*as ft from"fs/promises";import*as
|
|
726
|
+
`)}gn();import*as ft from"fs/promises";import*as se from"path";import{pathToFileURL as Mx}from"url";import{transform as Dk}from"sucrase";function xc(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=Dk(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}Xs();function Kk(r){return r.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
722
727
|
`)[0]}`).join(`
|
|
723
|
-
`)}function
|
|
724
|
-
${Bk(t)}`)}var ot="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Sc="https://data.jsdelivr.com/v1/package/npm/";function Cp(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var D=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=lr(t??s.version),this.subpath=lr(n??s.subpath)}static parse(e){let t=Cp(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=_p(t[1]??""),a=lr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=_p(t[0]),o=lr(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(ot).host,s=new URL(bn).host;if(t.host===n){let i=Cp(t.pathname.replace(/^\/v\d+\//,"/"));if(!i.length)return;let o=i[0].startsWith("@")?`${i[0]}/${i[1]??""}`:i[0];return r.parse(o)}if(t.host===s){let i=t.pathname.split("/npm/")[1];if(!i)return;let o=i.split("/")[0]||"";return r.parse(o)}return}catch{return}}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return r.parse(e).name}withVersion(e){return new r({name:this.name,version:lr(e),subpath:this.subpath})}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},lr=r=>r&&r.length?r:void 0,_p=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),lr(r.slice(e+1))]};async function ae(r){try{return await r()}catch{return}}function _t(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function kc(r){return r.startsWith("./")?r:`./${r}`}var wn=class{constructor(e,t){this.cache=e,this.http=t,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}baseDir(e){let t=typeof e=="string"?new D(e):e;return`${bn}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(_t(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(",")),`${ot}/${e}?${o.toString()}`}async resolveExactVersion(e){let t=Date.now(),n=this.pinCache.get(e);if(n&&t-n.ts<this.pinMs)return n.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${ot}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await ae(()=>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 ae(()=>this.http.getJson(`${Sc}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.tags&&Object.keys(n.tags).length?n.tags:void 0;return await this.cache.setIndex(e,n.versions,s),{versions:n.versions,distTags:s}}parseVersionFromUrl(e){let t=D.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 D(`${e}@${t}`)),i=await ae(()=>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 Rp=r=>r.startsWith("@types/"),vn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!Rp(e)),xc=r=>Object.keys(r?.dependencies||{}).filter(e=>!Rp(e)),jk=r=>vn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),Sn=class{constructor(e){this.cdn=e}async resolve(e,t){let n=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:i}=await this.expandWithPeers(n,t),o=this.computeFlags(s);return{allRoots:s,flags:o,autoAddedPeers:i}}async fetchMeta(e){return Promise.all(e.map(async({name:t,version:n})=>({name:t,version:n,meta:await this.cdn.fetchPackageMeta(t,n)})))}async expandWithPeers(e,t){let n=new Map(e.map(i=>[i.name,i])),s=[];for(let i of e)for(let o of jk(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=>vn(i.meta))),n=new Map;for(let i of e)for(let o of xc(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:vn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var kn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await ae(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let n=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(n)return n}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let n=await this.cache.getPinnedExact(e,t);if(n){if(this.semver.isExactVersion(n))return n;console.debug("[typebulb] cached version for",e,"is not exact (",n,"); re-resolving from registry")}let s=async o=>{if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o},i=await ae(()=>this.cdn.fetchVersionsIndex(e));if(i?.versions?.length){let o=this.semver.selectBestVersion(i.versions,{range:t,distTags:i.distTags});if(o){let a=await s(o);if(a)return a}else{console.debug("[typebulb] refreshing version cache for",e,"(",t,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(e);let a=await ae(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=await s(this.semver.selectBestVersion(a.versions,{range:t,distTags:a.distTags}));if(c)return c}}}return s(await this.cdn.resolveExactVersion(`${e}@${t}`))}async effectivePackage(e,t){let n=new D(e),s=n.root(),i=t[s],o=i?await ae(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as Fk,parse as qk}from"es-module-lexer";var ur=class r{constructor(e,t,n){this.version=e,this.cdn=t,this.peer=n}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))D.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{D.isBare(s)&&t.add(s)};try{await Fk;let[s]=qk(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(D.rootOf(u))),i=[...new Set(s.map(D.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);return{importMap:{imports:Object.fromEntries(d)},prefetchUrls:d.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=await this.version.resolveExactForRoot(e,n);if(!s)throw new Error(`Cannot resolve ${n?`${e}@${n}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,n){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let y=s.get(D.rootOf(p));return new D(p).withVersion(y.version).format()},o=new Set([...n.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==D.rootOf(p)).map(D.rootOf)),c=[],l=new Set,d=new Set(e.filter(p=>p===D.rootOf(p))),u=new Set;for(let p of e){let y=D.rootOf(p),m=s.get(y),{isPeerRoot:b,hasPeers:k,isSharedDep:x}=n.get(y),T=a.has(y),P=p!==y,O=!(b||x)&&(T||!k),R=this.singletonDepsOf(m,o),h=P&&d.has(y);h&&u.add(y);let S=h?[...R,y]:R.length?R:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:O,external:S})]),l.add(p)}let f=new Set([...o,...u]);for(let p of f)s.has(p)&&(l.has(p)||c.push([p,this.cdn.buildEsmUrl(i(p),{})]),c.push([`${p}/`,`${ot}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...vn(e.meta),...xc(e.meta)])].filter(n=>t.has(n))}};ur.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as Np,satisfies as Uk,maxSatisfying as Ip,major as Jk,valid as Kk}from"semver";var Xs=class{cmp(e,t){return e===t?0:Np(e,t)?1:Np(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Uk(t,e,{includePrerelease:!0})}selectBestVersion(e,t){if(!e?.length)return;let n=t?.range?.trim()||"*",s=t?.preferStable??!0,i=t?.distTags?.latest;if(i&&e.includes(i)&&this.satisfies(n,i))return i;if(s){let a=Ip(e,n,{includePrerelease:!1});if(a)return a}return Ip(e,n,{includePrerelease:!0})??void 0}majorOf(e){return Jk(e)}isExactVersion(e){return Kk(e)!==null}},Rt=new Xs;var Nt=class{constructor(e){this.store=e}async isNegative(e){let t=await ae(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await ae(()=>this.store.get(e)))?.attempts||0)+1;await ae(()=>this.store.set(e,{until:Date.now()+Hk(n),attempts:n}))}async clearNegative(e){await ae(()=>this.store.delete(e))}};function Hk(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}function $p(r,e){let t=new wn(r,e),n=new Sn(t),s=new kn(r,t,Rt);return{packageService:new ur(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as qp from"fs/promises";import*as Se from"path";import*as ct from"fs/promises";import*as qe from"path";import*as Dp from"os";import*as Ec from"fs/promises";import*as Lp from"crypto";function ve(r){return Lp.createHash("sha1").update(r).digest("hex")}async function Fe(r){try{return JSON.parse(await Ec.readFile(r,"utf8"))}catch{return}}async function Zs(r){try{return await Ec.readFile(r,"utf8")}catch{return}}var Mp=1,at=qe.join(Dp.homedir(),".typebulb","cache"),xn=qe.join(at,"packages"),En=qe.join(at,"proxy"),ei=qe.join(at,"dts"),Wk=qe.join(at,"emit"),Ac;function H(){return Ac||(Ac=Yk()),Ac}function ti(r,e){return qe.join(Wk,ve(r),e)}async function Yk(){await ct.mkdir(at,{recursive:!0});let r=qe.join(at,"version.json");if((await Fe(r))?.version===Mp)return;let t=await ct.readdir(at).catch(()=>[]);await Promise.all(t.map(n=>ct.rm(qe.join(at,n),{recursive:!0,force:!0}))),await ct.writeFile(r,JSON.stringify({version:Mp})+`
|
|
725
|
-
`,"utf8")}import*as lt from"fs/promises";import*as
|
|
728
|
+
`)}function Rp(r,e){let t=yn(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
729
|
+
${Kk(t)}`)}var ot="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Ec="https://data.jsdelivr.com/v1/package/npm/";function Np(r){let e=(r||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var M=class r{constructor(e,t,n){let s=typeof e=="string"?r.parse(e):e;this.name=s.name,this.version=cr(t??s.version),this.subpath=cr(n??s.subpath)}static parse(e){let t=Np(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=Ip(t[1]??""),a=cr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Ip(t[0]),o=cr(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(ot).host,s=new URL(bn).host;if(t.host===n){let i=Np(t.pathname.replace(/^\/v\d+\//,"/"));if(!i.length)return;let o=i[0].startsWith("@")?`${i[0]}/${i[1]??""}`:i[0];return r.parse(o)}if(t.host===s){let i=t.pathname.split("/npm/")[1];if(!i)return;let o=i.split("/")[0]||"";return r.parse(o)}return}catch{return}}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return r.parse(e).name}withVersion(e){return new r({name:this.name,version:cr(e),subpath:this.subpath})}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},cr=r=>r&&r.length?r:void 0,Ip=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),cr(r.slice(e+1))]};async function ce(r){try{return await r()}catch{return}}function _t(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Ac(r){return r.startsWith("./")?r:`./${r}`}var wn=class{constructor(e,t){this.cache=e,this.http=t,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}baseDir(e){let t=typeof e=="string"?new M(e):e;return`${bn}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(_t(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(",")),`${ot}/${e}?${o.toString()}`}async resolveExactVersion(e){let t=Date.now(),n=this.pinCache.get(e);if(n&&t-n.ts<this.pinMs)return n.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${ot}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await ce(()=>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 ce(()=>this.http.getJson(`${Ec}${encodeURIComponent(e)}`));if(!n?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=n.tags&&Object.keys(n.tags).length?n.tags:void 0;return await this.cache.setIndex(e,n.versions,s),{versions:n.versions,distTags:s}}parseVersionFromUrl(e){let t=M.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let n=await this.cache.getMeta(e,t);if(n&&Date.now()-n.updatedAt<this.metaTtlMs){let{dependencies:f,peerDependencies:u,peerDependenciesMeta:d}=n;return{name:e,version:t,dependencies:f,peerDependencies:u,peerDependenciesMeta:d}}let s=this.packageJson(new M(`${e}@${t}`)),i=await ce(()=>this.http.getJson(s));if(!i)return;let o=f=>f&&Object.keys(f).length?f:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}};var $p=r=>r.startsWith("@types/"),vn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!$p(e)),Tc=r=>Object.keys(r?.dependencies||{}).filter(e=>!$p(e)),Hk=r=>vn(r).filter(e=>!r?.peerDependenciesMeta?.[e]?.optional),Sn=class{constructor(e){this.cdn=e}async resolve(e,t){let n=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:i}=await this.expandWithPeers(n,t),o=this.computeFlags(s);return{allRoots:s,flags:o,autoAddedPeers:i}}async fetchMeta(e){return Promise.all(e.map(async({name:t,version:n})=>({name:t,version:n,meta:await this.cdn.fetchPackageMeta(t,n)})))}async expandWithPeers(e,t){let n=new Map(e.map(i=>[i.name,i])),s=[];for(let i of e)for(let o of Hk(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=>vn(i.meta))),n=new Map;for(let i of e)for(let o of Tc(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:vn(i.meta).length>0,isSharedDep:s.has(i.name)}]))}};var kn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await ce(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let n=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(n)return n}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let n=await this.cache.getPinnedExact(e,t);if(n){if(this.semver.isExactVersion(n))return n;console.debug("[typebulb] cached version for",e,"is not exact (",n,"); re-resolving from registry")}let s=async o=>{if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o},i=await ce(()=>this.cdn.fetchVersionsIndex(e));if(i?.versions?.length){let o=this.semver.selectBestVersion(i.versions,{range:t,distTags:i.distTags});if(o){let a=await s(o);if(a)return a}else{console.debug("[typebulb] refreshing version cache for",e,"(",t,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(e);let a=await ce(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=await s(this.semver.selectBestVersion(a.versions,{range:t,distTags:a.distTags}));if(c)return c}}}return s(await this.cdn.resolveExactVersion(`${e}@${t}`))}async effectivePackage(e,t){let n=new M(e),s=n.root(),i=t[s],o=i?await ce(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as Wk,parse as Yk}from"es-module-lexer";var lr=class r{constructor(e,t,n){this.version=e,this.cdn=t,this.peer=n}extractImportsSync(e){let t=new Set;for(let n of r.importPatterns){n.lastIndex=0;for(let s of e.matchAll(n))M.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,n=s=>{M.isBare(s)&&t.add(s)};try{await Wk;let[s]=Yk(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(M.rootOf(u))),i=[...new Set(s.map(M.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),f=this.buildEntries([...s,...l.map(u=>u.name)],a,c);return{importMap:{imports:Object.fromEntries(f)},prefetchUrls:f.map(([,u])=>u)}}async resolveVersion(e,t){let n=t[e],s=await this.version.resolveExactForRoot(e,n);if(!s)throw new Error(`Cannot resolve ${n?`${e}@${n}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,n){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let y=s.get(M.rootOf(p));return new M(p).withVersion(y.version).format()},o=new Set([...n.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==M.rootOf(p)).map(M.rootOf)),c=[],l=new Set,f=new Set(e.filter(p=>p===M.rootOf(p))),u=new Set;for(let p of e){let y=M.rootOf(p),m=s.get(y),{isPeerRoot:b,hasPeers:k,isSharedDep:x}=n.get(y),T=a.has(y),P=p!==y,O=!(b||x)&&(T||!k),R=this.singletonDepsOf(m,o),h=P&&f.has(y);h&&u.add(y);let S=h?[...R,y]:R.length?R:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:O,external:S})]),l.add(p)}let d=new Set([...o,...u]);for(let p of d)s.has(p)&&(l.has(p)||c.push([p,this.cdn.buildEsmUrl(i(p),{})]),c.push([`${p}/`,`${ot}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...vn(e.meta),...Tc(e.meta)])].filter(n=>t.has(n))}};lr.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as Lp,satisfies as Vk,maxSatisfying as Mp,major as Gk,valid as zk}from"semver";var Zs=class{cmp(e,t){return e===t?0:Lp(e,t)?1:Lp(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Vk(t,e,{includePrerelease:!0})}selectBestVersion(e,t){if(!e?.length)return;let n=t?.range?.trim()||"*",s=t?.preferStable??!0,i=t?.distTags?.latest;if(i&&e.includes(i)&&this.satisfies(n,i))return i;if(s){let a=Mp(e,n,{includePrerelease:!1});if(a)return a}return Mp(e,n,{includePrerelease:!0})??void 0}majorOf(e){return Gk(e)}isExactVersion(e){return zk(e)!==null}},Rt=new Zs;var Nt=class{constructor(e){this.store=e}async isNegative(e){let t=await ce(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await ce(()=>this.store.get(e)))?.attempts||0)+1;await ce(()=>this.store.set(e,{until:Date.now()+Qk(n),attempts:n}))}async clearNegative(e){await ce(()=>this.store.delete(e))}};function Qk(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}function Dp(r,e){let t=new wn(r,e),n=new Sn(t),s=new kn(r,t,Rt);return{packageService:new lr(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as Kp from"fs/promises";import*as Se from"path";import*as ct from"fs/promises";import*as Fe from"path";import*as Fp from"os";import*as Pc from"fs/promises";import*as Bp from"crypto";function ve(r){return Bp.createHash("sha1").update(r).digest("hex")}async function je(r){try{return JSON.parse(await Pc.readFile(r,"utf8"))}catch{return}}async function ei(r){try{return await Pc.readFile(r,"utf8")}catch{return}}var jp=1,at=Fe.join(Fp.homedir(),".typebulb","cache"),xn=Fe.join(at,"packages"),En=Fe.join(at,"proxy"),ti=Fe.join(at,"dts"),Xk=Fe.join(at,"emit"),Oc;function H(){return Oc||(Oc=Zk()),Oc}function ri(r,e){return Fe.join(Xk,ve(r),e)}async function Zk(){await ct.mkdir(at,{recursive:!0});let r=Fe.join(at,"version.json");if((await je(r))?.version===jp)return;let t=await ct.readdir(at).catch(()=>[]);await Promise.all(t.map(n=>ct.rm(Fe.join(at,n),{recursive:!0,force:!0}))),await ct.writeFile(r,JSON.stringify({version:jp})+`
|
|
730
|
+
`,"utf8")}import*as lt from"fs/promises";import*as qp from"path";async function me(r,e){await lt.mkdir(qp.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await lt.writeFile(t,e,"utf8"),await lt.rename(t,r).catch(async n=>{throw await lt.rm(t,{force:!0}).catch(()=>{}),n})}var ur=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=je(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 me(this.filePath,JSON.stringify(Object.fromEntries(e)))}};var Cc=Se.join(xn,"indexes"),Up=Se.join(xn,"pinned"),ex=Se.join(xn,"meta"),tx=Se.join(xn,"negative.json"),si=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new Nt(new ur(tx));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await H();let s=await ei(Se.join(Up,ve(n)+".txt"));return this.pinnedMem.set(n,s),s}async setPinnedExact(e,t,n){let s=`${e}@${t}`;this.pinnedMem.set(s,n),await H(),await me(Se.join(Up,ve(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await H();let t=await je(Se.join(Cc,ni(e)+".json"));return this.indexMem.set(e,t),t}async setIndex(e,t,n){let s={versions:t,distTags:n,updatedAt:Date.now()};this.indexMem.set(e,s),await H(),await me(Se.join(Cc,ni(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await Kp.rm(Se.join(Cc,ni(e)+".json"),{force:!0})}async isNegative(e){return await H(),this.negativeCache.isNegative(e)}async recordNegative(e){await H(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,t){let n=`${e}@${t}`;if(this.metaMem.has(n))return this.metaMem.get(n);await H();let s=await je(Jp(e,t));return this.metaMem.set(n,s),s}async setMeta(e,t,n,s,i){let o={dependencies:n,peerDependencies:s,peerDependenciesMeta:i,updatedAt:Date.now()};this.metaMem.set(`${e}@${t}`,o),await H(),await me(Jp(e,t),JSON.stringify(o))}};function Jp(r,e){return Se.join(ex,ni(r),encodeURIComponent(e)+".json")}function ni(r){return r.replace(/\//g,"__")}var Hp={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 rx=new si,{packageService:ii,versionResolver:Wp,cdnClient:Yp,peerResolver:G_}=Dp(rx,Hp);var Vp=`
|
|
726
731
|
(() => {
|
|
727
732
|
// Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
|
|
728
733
|
// bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
|
|
@@ -1082,7 +1087,7 @@ ${Bk(t)}`)}var ot="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Sc="https:
|
|
|
1082
1087
|
// Filesystem - local CLI extension
|
|
1083
1088
|
fs,
|
|
1084
1089
|
|
|
1085
|
-
// The bulb's
|
|
1090
|
+
// The bulb's folder, absolute (TB-FS.md) \u2014 for interop (paths handed to server.ts or
|
|
1086
1091
|
// spawned tools); tb.fs itself already resolves relative paths against it. Absent in an
|
|
1087
1092
|
// embed (no filesystem to name), where access throws like tb.fs.
|
|
1088
1093
|
get dir() {
|
|
@@ -1130,11 +1135,11 @@ ${Bk(t)}`)}var ot="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Sc="https:
|
|
|
1130
1135
|
};
|
|
1131
1136
|
}
|
|
1132
1137
|
})();
|
|
1133
|
-
`;var It=r=>r.replace(/<\/script/gi,"<\\/script");function
|
|
1138
|
+
`;var It=r=>r.replace(/<\/script/gi,"<\\/script");function oi(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var ai=` *, *::before, *::after { box-sizing: border-box; }
|
|
1134
1139
|
canvas { max-width: 100%; }
|
|
1135
1140
|
body { margin: 0; display: flow-root; font-family: system-ui, -apple-system, sans-serif; }
|
|
1136
1141
|
html[data-theme="dark"] { color-scheme: dark; }
|
|
1137
|
-
html[data-theme="light"] { color-scheme: light; }`;function
|
|
1142
|
+
html[data-theme="light"] { color-scheme: light; }`;function ci(r,e){return` <script>
|
|
1138
1143
|
(function() {
|
|
1139
1144
|
try {
|
|
1140
1145
|
var KEY = ${It(JSON.stringify("tb-theme:"+r))};
|
|
@@ -1169,19 +1174,19 @@ ${Bk(t)}`)}var ot="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Sc="https:
|
|
|
1169
1174
|
});
|
|
1170
1175
|
} catch (e) {}
|
|
1171
1176
|
})();
|
|
1172
|
-
</script>`}function
|
|
1173
|
-
html, body { height: 100%; }`,p={imports:
|
|
1177
|
+
</script>`}function Gp(r){let{name:e,code:t,css:n,html:s,data:i,insight:o,importMap:a,theme:c,embedded:l,dir:f}=r,u=s.trim()||'<div id="app"></div>',d=l?"":`
|
|
1178
|
+
html, body { height: 100%; }`,p={imports:sx(a.imports)};return`<!DOCTYPE html>
|
|
1174
1179
|
<html>
|
|
1175
1180
|
<head>
|
|
1176
1181
|
<meta charset="utf-8">
|
|
1177
1182
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1178
|
-
<title>${
|
|
1179
|
-
${
|
|
1183
|
+
<title>${oi(e)} - typebulb</title>
|
|
1184
|
+
${ci(e,c)}
|
|
1180
1185
|
<script type="importmap">
|
|
1181
1186
|
${JSON.stringify(p,null,2)}
|
|
1182
1187
|
</script>
|
|
1183
1188
|
<style>
|
|
1184
|
-
${
|
|
1189
|
+
${ai}${d}
|
|
1185
1190
|
</style>
|
|
1186
1191
|
<style>
|
|
1187
1192
|
${n}
|
|
@@ -1192,13 +1197,13 @@ ${u}
|
|
|
1192
1197
|
|
|
1193
1198
|
${i.length>0?`<script>window.__TB_DATA__ = ${It(JSON.stringify(i))};</script>`:""}
|
|
1194
1199
|
${o?`<script>window.__TB_INSIGHT__ = ${It(JSON.stringify(o))};</script>`:""}
|
|
1195
|
-
${
|
|
1200
|
+
${f?`<script>window.__TB_DIR__ = ${It(JSON.stringify(f))};</script>`:""}
|
|
1196
1201
|
|
|
1197
1202
|
<script>
|
|
1198
|
-
${
|
|
1203
|
+
${Vp}
|
|
1199
1204
|
</script>
|
|
1200
1205
|
|
|
1201
|
-
${
|
|
1206
|
+
${nx}
|
|
1202
1207
|
|
|
1203
1208
|
<script type="module">
|
|
1204
1209
|
globalThis.__tbEntryRan = true; /* import graph resolved \u2014 the load-failure backstop's signal (imports hoist above this line) */
|
|
@@ -1206,7 +1211,7 @@ await globalThis.__tbBoot; /* #tb= fragment restore, set by the shim when presen
|
|
|
1206
1211
|
${It(t)}
|
|
1207
1212
|
</script>
|
|
1208
1213
|
</body>
|
|
1209
|
-
</html>`}var
|
|
1214
|
+
</html>`}var nx=`<script>
|
|
1210
1215
|
(function () {
|
|
1211
1216
|
var framed = window.parent !== window;
|
|
1212
1217
|
var post = function (m) { try { parent.postMessage(m, '*'); } catch (e) {} }; /* framed only */
|
|
@@ -1302,8 +1307,8 @@ ${It(t)}
|
|
|
1302
1307
|
}
|
|
1303
1308
|
});
|
|
1304
1309
|
})();
|
|
1305
|
-
</script>`;function
|
|
1306
|
-
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await
|
|
1310
|
+
</script>`;function sx(r){let e={};for(let[t,n]of Object.entries(r))e[t]=n.startsWith("https://")?"/proxy/"+n:n;return e}import*as ui from"fs/promises";import*as li from"path";import{existsSync as zp,readFileSync as ix}from"fs";import{execFile as ox}from"child_process";import{promisify as ax}from"util";import{satisfies as cx}from"semver";var lx=ax(ox),ux=/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+(@[a-zA-Z0-9.^~*x-]+)?$/i;async function fi(r,e,t,n){let i=r.map(l=>fx(l,t)).filter(l=>!dx(l,e));if(i.length===0)return;let o=i.filter(l=>!ux.test(l));if(o.length)throw new Error(`Refusing to install npm spec(s) with unsupported characters: ${o.join(", ")}
|
|
1311
|
+
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await ui.mkdir(e,{recursive:!0});let a=li.join(e,"package.json");zp(a)||await ui.writeFile(a,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${i.join(", ")}`);let c=["--no-audit","--no-fund",...n?.ignoreScripts?["--ignore-scripts"]:[]];await lx("npm",["install",...c,...i],{cwd:e,shell:!0})}function fx(r,e){if(!e||M.parse(r).version)return r;let t=e[r];return t?`${r}@${t}`:r}function dx(r,e){let{name:t,version:n}=M.parse(r),s=li.join(e,"node_modules",t);if(!zp(s))return!1;if(!n)return!0;try{let i=JSON.parse(ix(li.join(s,"package.json"),"utf-8")).version;return cx(i,n)}catch{return!1}}function di(r){let e=new Set,t=/\bimport\s+(?:[\s\S]*?\s+from\s+)?['"]([^./][^'"]*)['"]/g,n;for(;n=t.exec(r);){let s=n[1];s.includes(":")||e.add(M.rootOf(s))}return[...e]}mr();Si();Dt();import*as yr from"fs/promises";import*as Je from"path";function ki(r,e,t=e){let n=Je.resolve(e,r),s=Je.normalize(t),i=Je.normalize(n);if(i!==s&&!i.startsWith(s+Je.sep))throw new Error("Path traversal detected - access denied");return n}async function On(r,e,t){return yr.readFile(ki(r,e,t))}async function xi(r,e,t,n){let s=ki(r,t,n);await yr.mkdir(Je.dirname(s),{recursive:!0}),await yr.writeFile(s,typeof e=="string"?e:Buffer.from(e))}async function am(r){let e=Ue(r.provider,r.model);if(typeof e=="string")throw new Error(e);let t=await ut(e,r);if(!t.ok){let n=await pr(t,e.protocol);throw new Error(n.message)}return{response:t,protocol:e.protocol}}async function $x(r){let{response:e,protocol:t}=await am(r);return{text:await Lt(e,t)}}async function*Lx(r){let{response:e,protocol:t}=await am(r);yield*Mt(e,t)}function cm(r,e=process.cwd()){let t=Object.assign($x,{stream:Lx}),n={read:async s=>{let i=await On(s,r,e);try{return new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{throw new Error(`File is not valid UTF-8 text: ${s} \u2014 use tb.fs.readBytes() for binary files.`)}},readBytes:async s=>new Uint8Array(await On(s,r,e)),write:async(s,i)=>(await xi(s,i,r,e),!0)};globalThis.tb=Object.freeze({ai:t,fs:n,dir:r,models:()=>qe(),hasOwnKeys:vi,mode:"local"})}async function lm(r){let t=(await ft.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?se.join(r,t):null}function Ei(r,e){let t=se.resolve(r),n=se.join(se.dirname(t),se.basename(t).replace(/\.bulb\.md$/,""));return e?se.join(n,e):n}async function xe(r){let e=await ft.readFile(r,"utf-8"),t=de(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=ar(t);return{bulb:n,config:Lr(n.config),warnings:ku(e)}}function Hc(r){let e=se.basename(r).replace(/\.bulb\.md$/i,"");return se.join(se.dirname(r),".typebulb",`${e}.server.mjs`)}async function Cn(r,e,t,n,s){let i=xc(r,{serverOnly:!0});if(i.error)throw new Error(`Server compilation error: ${i.error}`);let o=i.code;t&&(o=await mu(o,t));let a=se.join(se.dirname(e),".typebulb");await ft.mkdir(a,{recursive:!0});let c=di(o);c.length>0&&await fi(c,a,n);let l=Hc(e);return await ft.writeFile(l,o,"utf-8"),cm(Ei(e,s)),await import(`${Mx(l).href}?t=${Date.now()}`)}async function Wc(r,e,t,n,s){let{bulb:i,config:o}=await xe(r),a=zs(i.data);Rp(i.code,o.dependencies??{});let c=xc(i.code,{jsxImportSource:o.ts?.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:l}=await ii.buildImportMap(c.code,o.dependencies??{},n?new Set([n.name]):void 0);n&&(l.imports[n.name]=n.entryUrl);let f=Gp({name:i.name,code:c.code,css:i.css,html:i.html,data:a,insight:i.insight,importMap:l,dir:Ei(r,s),watch:e}),u=null;return i.server&&t&&(u=await Cn(i.server,r,n,o.dependencies,s)),{html:f,bulb:i,serverExports:u}}gn();_n();Ri();vl();var fo={claude:{adapter:()=>new vr,server:()=>Promise.resolve().then(()=>(ng(),rg))},pi:{adapter:()=>new Tr,server:()=>Promise.resolve().then(()=>(pg(),dg))}};function mg(r){return r in fo}function Rr(){return Object.keys(fo)}function hg(){return Object.fromEntries(Object.entries(fo).map(([r,e])=>[r,e.adapter]))}function gg(r){return fo[r].server()}import*as wt from"path";import{spawn as BT,execSync as jT}from"child_process";import{createRequire as FT}from"module";import{existsSync as qT}from"fs";import*as ie from"fs/promises";import*as re from"path";var Bl=[{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"}],jl=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function Fl(r,e){if(!e)return r.filter(s=>!s.since);let t={"5.0":0,"5.5":1},n=t[e];return r.filter(s=>!s.since||t[s.since]<=n)}var mT=`
|
|
1307
1312
|
/**
|
|
1308
1313
|
* Get raw data chunk from the Data tab.
|
|
1309
1314
|
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
@@ -1314,7 +1319,7 @@ ${It(t)}
|
|
|
1314
1319
|
* @param index - Chunk index (0-based)
|
|
1315
1320
|
* @throws If chunk is not valid JSON/JSON-ish
|
|
1316
1321
|
*/
|
|
1317
|
-
json<T = unknown>(index: number): T;`,
|
|
1322
|
+
json<T = unknown>(index: number): T;`,hT=`
|
|
1318
1323
|
/**
|
|
1319
1324
|
* Get the insight data produced by the inference layer.
|
|
1320
1325
|
*
|
|
@@ -1323,7 +1328,7 @@ ${It(t)}
|
|
|
1323
1328
|
*
|
|
1324
1329
|
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
1325
1330
|
*/
|
|
1326
|
-
insight<T = unknown>(): T | undefined;`,
|
|
1331
|
+
insight<T = unknown>(): T | undefined;`,yg=`options: {
|
|
1327
1332
|
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
1328
1333
|
system?: string;
|
|
1329
1334
|
/** Reasoning effort hint: 0=minimal, 1=low, 2=med, 3=high. Mapped to each provider's native mechanism (OpenAI/OpenRouter reasoning effort, Gemini thinking budget, Anthropic adaptive thinking). 0 minimizes reasoning \u2014 a floor, not a guaranteed "off": some models still think a little at 0, and adaptive models already self-skip at 1 (low). Level 1 (low) is the sensible default for most work; reach for 0 only when you truly want minimal deliberation. Omit for the model's own default. */
|
|
@@ -1334,12 +1339,12 @@ ${It(t)}
|
|
|
1334
1339
|
webSearch?: boolean;
|
|
1335
1340
|
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
1336
1341
|
signal?: AbortSignal;
|
|
1337
|
-
}`,
|
|
1342
|
+
}`,bg=`
|
|
1338
1343
|
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
1339
1344
|
type AiChunk =
|
|
1340
1345
|
| { kind: "text"; text: string }
|
|
1341
1346
|
| { kind: "reasoning"; text: string };
|
|
1342
|
-
`,
|
|
1347
|
+
`,wg=`
|
|
1343
1348
|
/**
|
|
1344
1349
|
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
1345
1350
|
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
@@ -1348,7 +1353,7 @@ type AiChunk =
|
|
|
1348
1353
|
* @throws On rate limit, network error, or provider error
|
|
1349
1354
|
*/
|
|
1350
1355
|
ai: {
|
|
1351
|
-
(${
|
|
1356
|
+
(${yg}): Promise<{ text: string }>;
|
|
1352
1357
|
/**
|
|
1353
1358
|
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
1354
1359
|
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
@@ -1362,8 +1367,8 @@ type AiChunk =
|
|
|
1362
1367
|
* if (c.kind === "text") answer += c.text;
|
|
1363
1368
|
* }
|
|
1364
1369
|
*/
|
|
1365
|
-
stream(${
|
|
1366
|
-
};`,
|
|
1370
|
+
stream(${yg}): AsyncIterable<AiChunk>;
|
|
1371
|
+
};`,vg=`
|
|
1367
1372
|
/**
|
|
1368
1373
|
* Returns AI models available to the current user.
|
|
1369
1374
|
* Models are filtered by the user's configured API keys.
|
|
@@ -1385,7 +1390,7 @@ type AiChunk =
|
|
|
1385
1390
|
* making many AI calls should check this and show a "use your own keys"
|
|
1386
1391
|
* notice instead of running.
|
|
1387
1392
|
*/
|
|
1388
|
-
hasOwnKeys(): Promise<boolean>;`,
|
|
1393
|
+
hasOwnKeys(): Promise<boolean>;`,gT="\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;",Sg=`
|
|
1389
1394
|
/**
|
|
1390
1395
|
* The mode this bulb is running in.
|
|
1391
1396
|
*
|
|
@@ -1395,11 +1400,11 @@ type AiChunk =
|
|
|
1395
1400
|
* - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
|
|
1396
1401
|
* client-only: AI, filesystem, and server RPC are unavailable)
|
|
1397
1402
|
*/
|
|
1398
|
-
mode: 'local' | 'editor' | 'published' | 'embedded';`,
|
|
1403
|
+
mode: 'local' | 'editor' | 'published' | 'embedded';`,kg=`
|
|
1399
1404
|
/**
|
|
1400
1405
|
* Local filesystem access (CLI only).
|
|
1401
1406
|
*
|
|
1402
|
-
* Relative paths resolve against the bulb's
|
|
1407
|
+
* Relative paths resolve against the bulb's folder (\`tb.dir\` \u2014
|
|
1403
1408
|
* \`<bulb-dir>/<filename-stem>/\`, created on demand), so
|
|
1404
1409
|
* \`tb.fs.write('results.json')\` lands beside the bulb. \`../\` reaches sibling
|
|
1405
1410
|
* bulbs' folders; everything stays confined to the project (the launch cwd).
|
|
@@ -1412,15 +1417,16 @@ type AiChunk =
|
|
|
1412
1417
|
readBytes(path: string): Promise<Uint8Array>;
|
|
1413
1418
|
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
1414
1419
|
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
1415
|
-
};`,
|
|
1420
|
+
};`,xg=`
|
|
1416
1421
|
/**
|
|
1417
|
-
* The bulb's
|
|
1422
|
+
* The bulb's folder \u2014 absolute path to \`<bulb-dir>/<filename-stem>/\`
|
|
1423
|
+
* (or its subfolder when the run is scoped with \`--dir\`).
|
|
1418
1424
|
*
|
|
1419
1425
|
* For interop only (handing a path to \`server.ts\` or a spawned tool):
|
|
1420
1426
|
* \`tb.fs\` already resolves relative paths against it, so bulb code writing
|
|
1421
1427
|
* its own files never needs it. CLI only \u2014 throws in editor/published/embedded mode.
|
|
1422
1428
|
*/
|
|
1423
|
-
readonly dir: string;`,
|
|
1429
|
+
readonly dir: string;`,yT=`
|
|
1424
1430
|
/**
|
|
1425
1431
|
* Async value inspector for tensor-like objects.
|
|
1426
1432
|
*
|
|
@@ -1487,7 +1493,7 @@ type AiChunk =
|
|
|
1487
1493
|
*
|
|
1488
1494
|
* @returns The full canonical URL
|
|
1489
1495
|
*/
|
|
1490
|
-
url(): Promise<string>;`,
|
|
1496
|
+
url(): Promise<string>;`,bT=`
|
|
1491
1497
|
/**
|
|
1492
1498
|
* Subscribe to a value pushed from the terminal via \`typebulb send <file> [message]\`.
|
|
1493
1499
|
*
|
|
@@ -1502,39 +1508,39 @@ type AiChunk =
|
|
|
1502
1508
|
* @param handler - Called with each pushed message.
|
|
1503
1509
|
* @returns An unsubscribe function.
|
|
1504
1510
|
*/
|
|
1505
|
-
onMessage(handler: (message: any) => void): () => void;`,
|
|
1511
|
+
onMessage(handler: (message: any) => void): () => void;`,wT="\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>>;",ql=`${bg}
|
|
1506
1512
|
/**
|
|
1507
1513
|
* Typebulb utilities namespace.
|
|
1508
1514
|
* Type \`tb.\` to discover available helpers.
|
|
1509
1515
|
*/
|
|
1510
|
-
declare const tb: {${
|
|
1516
|
+
declare const tb: {${mT}${yT}${hT}${wT}${bT}${wg}${kg}${xg}${vg}${gT}${Sg}
|
|
1511
1517
|
};
|
|
1512
|
-
`,
|
|
1518
|
+
`,Ul=`${bg}
|
|
1513
1519
|
/**
|
|
1514
1520
|
* Typebulb utilities namespace (server-side).
|
|
1515
1521
|
* Type \`tb.\` to discover available helpers.
|
|
1516
1522
|
*/
|
|
1517
|
-
declare const tb: {${
|
|
1523
|
+
declare const tb: {${wg}${kg}${xg}${vg}${Sg}
|
|
1518
1524
|
};
|
|
1519
|
-
`;import
|
|
1525
|
+
`;import xT from"p-limit";import{resolve as Ag}from"resolve.exports";var We={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},Fn=["index.d.ts","index.d.mts"],Jl=/\.d\.(ts|mts|cts)$/i;function po(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function Eg(r){return[`${r}.d.ts`,`${r}.d.mts`]}function bt(r){if(!r||r==="./"||r==="/")return[...Fn];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=Eg(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...Eg(`${n}index`)),t}async function Nr(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(vT(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function vT(r){return r===408||r===429||r>=500&&r<600}var mo=class{constructor(e,t){this.fetchDts=e,this.cdnClient=t}async tryUrls(e){for(let t of e){let n=await this.fetchDts(t);if(n&&(this.looksLikeDts(n.dts)||po(n.url)))return n}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}async loadPackageAtVersionedRoot(e,t){let n=this.cdnClient.packageJson(new M({name:e,version:t})),s=await Nr(n);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new M({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,n){if(e.kind==="types"){let o=_t(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([...Fn],t);if(!Jl.test(o)){let a=await this.tryUntilSuccess(bt(o),t);if(a)return a}return t(o)}let s=bt(e.path),i=n?.subpath?[...s,...Fn]:[...Fn,...s];return this.tryUntilSuccess(i,t)}toResolutionResult(e){return{kind:Jl.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(Ag(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(Ag(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=M.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 M(i).format(),a=new M({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=Ac(t.subpath),d=this.resolveExportsPath(n,u);if(d){let y=await this.resolveFromSelected(this.toResolutionResult(d),c,{subpath:!0});if(y)return{...y,resolvedPkg:a}}let p=await this.tryUntilSuccess(bt(u),c);if(p)return{...p,resolvedPkg:a}}let l=n.types??n.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:o}}let f=this.resolveExportsPath(n,".");if(f){let u=await this.resolveFromSelected(this.toResolutionResult(f),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,n){let s=_t(n),i=new URL(s,e).toString(),o=await this.tryUrls([i]);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}};import{gunzipSync as ST}from"fflate";var ho=class{async fetchAndExtract(e,t){let n=this.getTarballUrl(e,t),s=await Nr(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=ST(e),s=new TextDecoder("utf-8"),i=0;for(;i<n.length-512;){let o=n.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),f=o.slice(124,136),u=s.decode(f).trim().replace(/\0/g,""),d=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let y=n.slice(i,i+d);t.set(this.normalizeTarPath(l),s.decode(y))}i+=Math.ceil(d/512)*512}}catch{}return t}};var go=class{constructor(e,t,n=new ho){this.cdnClient=e,this.cache=t,this.tarballFetcher=n}typesNameCandidates(e){let t=e.startsWith("@")?e.slice(1).replace("/","__"):e;return t.includes(".")?[t,t.split(".").join("-"),t.split(".").join("")]:[t]}selectTypesVersion(e,t,n){try{if(n){let i=Rt.majorOf(n),o=e.filter(a=>Rt.majorOf(a)===i);if(o.length)return o.sort((a,c)=>Rt.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=bt(e);return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new M(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 M(t).format():t.name}}}async resolve(e){let t=M.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 yo=class{collectRelativeTypeRefs(e){return this.collectRefs(e).filter(t=>t.startsWith("./")||t.startsWith("../"))}collectBareModuleRefs(e){return this.collectRefs(e).filter(t=>this.isBare(t))}collectRefs(e){let t=e.split(`
|
|
1520
1526
|
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
1521
|
-
`),n=new Set;for(let s of t.matchAll(/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/g))n.add(s[2]);for(let s of t.matchAll(/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/g))n.add(s[1]);return Array.from(n)}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};var
|
|
1522
|
-
`);await this.prefetchBareDeps(y,l,
|
|
1523
|
-
`,"utf8"),await
|
|
1524
|
-
`,"utf8"),{dir:e}}function
|
|
1525
|
-
`))console.log(`${e} ${n}`);return r.length>0}function
|
|
1527
|
+
`),n=new Set;for(let s of t.matchAll(/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/g))n.add(s[2]);for(let s of t.matchAll(/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/g))n.add(s[1]);return Array.from(n)}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};var Tg="file:///node_modules",bo=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${Tg}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=_t(t);return`${Tg}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as kT}from"lru-cache";function Pg(r){let e=new kT({ttl:We.negativeTtlMs,max:500}),t=new Map;return async function(s){try{if(await r.isNegative(s)||e.has(s))return;let i=await r.getCachedFile(s);if(i)return{dts:i,url:s};let o=t.get(s);if(o)return o;let a=(async()=>{let c=await Nr(s,{init:{cache:"no-store"}});if(!c?.ok){c?.status===404&&(e.set(s,!0),await r.recordNegative(s));return}let l=await c.text(),f=c.url||s;return await r.clearNegative(s),await r.setCachedFile(f,l),{dts:l,url:f}})();return t.set(s,a),await a.finally(()=>t.delete(s))}catch{return}}}var qn=class{constructor(e){this.inFlight=new Map,this.scanner=new yo,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=Pg(e.cache),this.typescriptProvider=new mo(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new go(e.cdnClient,e.cache),this.virtualFs=new bo}withInFlight(e,t){let n=this.inFlight.get(e);if(n)return n;let s=t().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}pushFileIfNew(e,t,n){e.some(s=>s.path===t)||e.push({path:t,content:n})}createStubDef(e){let t=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:t,files:[{path:t,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:t}]}}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let n=await t.resolve(e);if(n?.dts)return n}catch{}}async fetchRootDts(e,t){let{effectivePackage:n,root:s,pinned:i}=await this.versionResolver.effectivePackage(e,t),o=await this.cache.getCachedDts(n);if(o?.content){let c=o.url??this.cdnClient.file(i?`${s}@${i}`:s,"index.d.ts");return{dts:o.content,url:c,resolvedPkg:n}}let a;try{a=await this.fetchViaProviders(n)}catch{return}if(!(!a?.dts||!a.url)&&new M(n).subpath===new M(a.resolvedPkg||n).subpath){try{await this.cache.setCachedDts(n,a.dts,a.url)}catch{}return a}}extractPackageRootUrl(e){let t=e.pathname.match(/^(.+@[^/]+\/)/);return t?new URL(t[1],e.origin):new URL("./",e)}toVirtualPath(e,t,n){let s=t.pathname.startsWith(e.pathname)?t.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(t.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(n,s)}computeEntryPath(e,t){if(!e)return{mainPath:this.virtualFs.pathForMain(t),packageRootUrl:void 0};let n=new URL(e),s=this.extractPackageRootUrl(n);return{mainPath:this.toVirtualPath(s,n,t),packageRootUrl:s}}async expandRelativeRefs(e,t,n,s,i=new Set,o){if(!i.has(t)&&(i.add(t),!(i.size>We.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,We.maxRelativeTypeRefs);for(let f of l)await this.tryRelativeRef(f,c,o,n,s,i)}catch{}}async tryRelativeRef(e,t,n,s,i,o){try{let a=new URL(e,t),c=a.pathname+a.search,l=po(c)?[c]:bt(c);for(let f of l){let d=new URL(f,a).toString();if(o.has(d))return;let p=await this.fetchDts(d);if(p?.dts){let y=this.toVirtualPath(n,new URL(p.url),s);this.pushFileIfNew(i,y,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,n);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new M(e).name!==new M(t).name}ambientlyDeclares(e,t){if(/^(?:import|export)\b/m.test(e))return!1;for(let n of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=n[1];if(s===t||s.endsWith("/*")&&t.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,t){let n=e.find(s=>s.path===t);n&&(n.ambient=!0)}async prefetchBareDeps(e,t,n,s,i){try{let o=this.scanner.collectBareModuleRefs(e).slice(0,We.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=xT(We.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,We.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,n,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):n.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let f=this.scanner.collectBareModuleRefs(a.dts).slice(0,We.maxBareDeps).filter(u=>!i.has(u));for(let u of f)await this.prefetchBareDepsRecursive(u,t,n,s-1,i,o)}async resolve(e,t,n){let s=await this.packageService.extractImports(e),i=n?[...s,...n]:s;return(await Promise.all(i.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:n}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(n,async()=>{let s=new M(e),i=await this.fetchRootDts(e,t)??(s.subpath?await this.fetchRootDts(s.name,t):void 0);return i?this.buildDefFromContent(e,i,i.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,n,s){let{dts:i,url:o,resolvedPkg:a}=t,c=new M(a||n),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:f,packageRootUrl:u}=this.computeEntryPath(o,l),d=[{path:f,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,d,void 0,u);let y=d.map(x=>x.content).join(`
|
|
1528
|
+
`);await this.prefetchBareDeps(y,l,d,p,s);let m=c.format(),b=e===m?[e]:[e,m],k=b.some(x=>this.ambientlyDeclares(i,x));return k?this.markFileAmbient(d,f):p.push(...b.map(x=>({module:x,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:k}}};import*as Ir from"path";var ET=Ir.join(ti,"pkg"),AT=Ir.join(ti,"files"),TT=Ir.join(ti,"negative.json"),vo=class{pkgMem=new Map;fileMem=new Map;negativeCache=new Nt(new ur(TT));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await H();let t=await je(Og(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 wo(async()=>{await H(),await me(Og(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await H();let t=await ei(Cg(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await wo(async()=>{await H(),await me(Cg(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await wo(async()=>{await H(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return wo(()=>this.negativeCache.clearNegative(e))}};async function wo(r){try{await r()}catch{}}function Og(r){return Ir.join(ET,ve(r)+".json")}function Cg(r){return Ir.join(AT,ve(r)+".txt")}var Kl;function PT(){return Kl||(Kl=new qn({cache:new vo,cdnClient:Yp,packageService:ii,versionResolver:Wp})),Kl}var _g="file:///node_modules/";async function Rg(r){let e=ri(r.emitKey,"typecheck");await H(),await ie.rm(e,{recursive:!0,force:!0}),await ie.mkdir(e,{recursive:!0});let t=RT(r.jsxImportSource,r.dependencies),n=await PT().resolve(r.code,r.dependencies,t),s=r.local?.name,i=s?n.filter(f=>f.pkg!==s):n,o=new Set;for(let f of i)for(let u of f.files){let d=So(u.path);if(!d||o.has(d))continue;o.add(d);let p=re.join(e,"node_modules",d);await ie.mkdir(re.dirname(p),{recursive:!0}),await ie.writeFile(p,u.content,"utf8")}let a={};for(let f of i)for(let u of f.shims){let d=So(u.path);d&&(a[u.module]=[`./node_modules/${d}`])}for(let f of i){if(f.ambient)continue;let u=So(f.mainPath);u&&(a[f.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let f of i)for(let u of f.files){if(!u.ambient)continue;let d=So(u.path);d&&c.add(`node_modules/${d}`)}if(r.local){delete a[r.local.name];let f=await NT(r.local,e);f?a[r.local.name]=[`./node_modules/${r.local.name}/${f}`]:console.warn(` local: '${r.local.name}' ships no type defs; check cannot type against it.`)}let l=OT(r.jsxImportSource,a,[...c]);return await ie.writeFile(re.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1529
|
+
`,"utf8"),await ie.writeFile(re.join(e,"code.tsx"),r.code,"utf8"),await ie.writeFile(re.join(e,"tb.d.ts"),ql,"utf8"),{dir:e}}var Hl={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function OT(r,e,t=[]){return{compilerOptions:{...Hl,lib:CT([...Bl,...jl]),jsx:"react-jsx",jsxImportSource:r??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function CT(r){return Fl(r).map(e=>_T(e.name))}function _T(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 RT(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function So(r){if(!r.startsWith(_g))return;let e=r.slice(_g.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function NT(r,e){if(!r.typesAbs)return;let t=re.dirname(r.typesAbs),n=re.join(e,"node_modules",r.name);for(let s of await IT(t)){let i=re.join(n,re.relative(t,s));await ie.mkdir(re.dirname(i),{recursive:!0}),await ie.copyFile(s,i)}return re.basename(r.typesAbs)}async function IT(r){let e=[];async function t(n){let s=await ie.readdir(n,{withFileTypes:!0});for(let i of s){let o=re.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 ye from"fs/promises";import*as Ye from"path";import{existsSync as $T}from"fs";var LT="^22";async function Ng(r){let e=ri(r.emitKey,"typecheck-server");await H(),await ye.rm(e,{recursive:!0,force:!0}),await ye.mkdir(e,{recursive:!0});let t=Ye.join(r.bulbDir,".typebulb"),n=di(r.server).filter(o=>o!==r.local?.name);await fi([`@types/node@${LT}`,...n],t,r.dependencies,{ignoreScripts:!0});let s=Ye.join(t,"node_modules"),i=Ye.join(e,"node_modules");return await DT(s,i),await ye.writeFile(Ye.join(e,"server.ts"),r.server,"utf8"),await ye.writeFile(Ye.join(e,"tb.d.ts"),Ul,"utf8"),await ye.writeFile(Ye.join(e,"tsconfig.json"),JSON.stringify(MT(r.local),null,2)+`
|
|
1530
|
+
`,"utf8"),{dir:e}}function MT(r){let e={...Hl,lib:["ES2023"],types:["node"]};if(r?.typesAbs){let t=i=>i.replace(/\\/g,"/"),n=t(Ye.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 DT(r,e){if(!$T(r)){await ye.mkdir(e,{recursive:!0});return}await ye.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await ye.symlink(r,e,t)}Xs();async function $g(r,e){let{bulb:t,config:n,warnings:s}=await xe(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=Ig(yn(t.code,{target:"client",dependencies:n.dependencies??{}}),"client")||i),t.server&&(i=Ig(yn(t.server,{target:"server"}),"server")||i);let o=KT([process.cwd(),wt.dirname(r)]);if(!o){let l=wt.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 Rg({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 Ng({server:t.server,bulbDir:wt.dirname(r),emitKey:r,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:n.dependencies});a.push({role:"server",dir:l})}for(let{role:l,dir:f}of a){let{stdout:u,exitCode:d}=await UT(o,f);for(let p of u.split(/\r?\n/))p.trim()&&console.log(`${l} ${p}`);d!==0&&(i=!0)}i&&process.exit(1);let c=[t.code&&"code.tsx",t.server&&"server.ts"].filter(Boolean).join(", ");console.error(`\u2713 no issues (${c})`)}function Ig(r,e){for(let t of r)for(let n of t.message.split(`
|
|
1531
|
+
`))console.log(`${e} ${n}`);return r.length>0}function UT(r,e){return new Promise(t=>{let n=BT(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 JT=FT(import.meta.url);function KT(r){let e=n=>{try{let s=JT.resolve("typescript/package.json",{paths:n}),i=wt.join(wt.dirname(s),"lib","tsc.js");return qT(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=jT("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}Bi();_n();async function Lg(r,e){let{bulb:t}=await xe(r),n=kr(t);if(Bt(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.)")}_n();import*as Un from"path";async function Mg(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=Gc();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=Un.resolve(r);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),br(t,e),console.log(e?`Trusted ${Un.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${Un.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}Re();import*as Fg from"readline";var Jn=hg();function Dg(){for(let r of Object.values(Jn))try{r().ensureHarnessSupport()}catch{}}function Kn(){for(let r of Object.keys(Jn))try{if(Jn[r]().detectsSelf())return r}catch{}}function Bg(r){let e=Rr(),t=new Map(e.filter(i=>Jn[i]).map(i=>[i,Jn[i]()]));for(let[i,o]of t)if(o.detectsSelf())return{name:i};let n=[...t].filter(([,i])=>i.detectsInstalled()).map(([i])=>i);if(n.length===0)return{name:e[0]};if(n.length===1)return{name:n[0]};let s=i=>t.get(i).listSessionFiles(r).length>0;return{ambiguous:[...n].sort((i,o)=>Number(s(o))-Number(s(i)))}}ji();function Wl(r){let e=t=>n=>r?`\x1B[${t}m${n}\x1B[0m`:n;return{lit:e("38;5;70"),litLink:e("4;38;5;70"),brand:e("38;5;135")}}async function qg(r){let e=Bg(process.cwd());if("ambiguous"in e){let t=await HT(r,e.ambiguous);return t?jg(r,t):WT(r,e.ambiguous)}return jg(r,e.name)}async function jg(r,e){let t,n;try{t=await Om(e)}catch(f){n=f instanceof Error?f.message:String(f)}let{lit:s,litLink:i,brand:o}=Wl(process.stdout.isTTY===!0),a=[" Read the authoring skill before writing a bulb:",` \u2022 ${s("npx typebulb skill")} \u2014 assembles one SKILL.md`," \u2022 or, open its parts:",` ${s(xr())}`,` ${s(qt())}`],c=t?[" Agent mirror is live\u{1F4A1}",` ${s("\u25CF")} ${i(t.url)}`," Embedded bulbs render live here."," Agents:",` Reusable app/tool \u2192 write a ${s(".bulb.md")}`," Show something inline \u2192 embed a bulb",e==="pi"?" arm a wait for its render verdict \u2014 run it plainly:":" background a wait for its render verdict:",` \u2022 ${s('typebulb wait agent --match "[embed <name>"')}`,...a," End your reply with the mirror link above"," \u2022 easy to miss the link mid-message"]:[` The mirror did not start (${n})`,` \u25CF Start it manually: ${s(`npx typebulb agent:${e}`)}`," Agents:",...a],l=[` ${o(`typebulb v${r}`)}`,...c,""];process.stdout.write(l.join(`
|
|
1526
1532
|
`)+`
|
|
1527
|
-
`)}async function
|
|
1533
|
+
`)}async function HT(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=Wl(!0),s=[` ${n(`typebulb v${r}`)}`," More than one agent harness is available here.",...e.map((o,a)=>` ${t(String(a+1))}) ${o}`),""];process.stdout.write(s.join(`
|
|
1528
1534
|
`)+`
|
|
1529
|
-
`);let i=
|
|
1535
|
+
`);let i=Fg.createInterface({input:process.stdin,output:process.stdout});try{let o=(await new Promise(c=>i.question(" Open which? [1]: ",c))).trim();if(o==="")return e[0];let a=Number(o);return Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:e.find(c=>c===o.toLowerCase())}finally{i.close()}}function WT(r,e){let{lit:t,brand:n}=Wl(process.stdout.isTTY===!0),s=[` ${n(`typebulb v${r}`)}`," More than one agent harness is available here."," Open the mirror for the one you want:",...e.map(i=>` \u2022 ${t(`npx typebulb agent:${i}`)}`),""];process.stdout.write(s.join(`
|
|
1530
1536
|
`)+`
|
|
1531
|
-
`)}mt();Dt();async function
|
|
1532
|
-
`+e)}function
|
|
1537
|
+
`)}mt();Dt();async function Ug(r){ge(r);let e=await qe();if(e.length>0){console.log(om(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!Kc()){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(hr))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.")}ji();import*as Jg from"fs/promises";async function Kg(r){let e=qt(),t;try{t=await Jg.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(Dm(t,r))}Ti();import*as Hg from"path";Re();function YT(r,e,t,n){if(/^\d+$/.test(e))return r.find(i=>i.pid===parseInt(e,10));let s=e==="agent"?r.filter(i=>i.agent!=null):r.filter(i=>i.agent===e);if(s.length){if(!t)return s[0];let i=s.filter(o=>o.cwd&&ee(o.cwd)===ee(t));return n&&i.find(o=>o.agent===n)||i[0]}return r.find(i=>ee(i.file)===ee(e))}var Hn=r=>r.agent??Hg.basename(r.file);function Wg(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"} ${t.file}`)}function Yl(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Wg(r,t=>console.log(t)),console.log(`
|
|
1538
|
+
`+e)}function Vl(r,e,t,n,s){let i=YT(r,e,n,s);if(i)return i;console.error(`No running server for '${e}'.`),r.length?(console.error(`Running servers (try \`typebulb ${t} <file|pid>\`):`),Wg(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Yg(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),Yl(await Y(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=Vl(await Y(),r,"logs",process.cwd(),Kn());if(e.clear){km(t.pid),console.log(`Cleared log for ${Hn(t)} (pid ${t.pid}).`);return}let n=_e(t.pid),s=n.text;if(e.run!==void 0&&(s=xm(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(`
|
|
1533
1539
|
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1534
1540
|
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1535
1541
|
`)&&process.stdout.write(`
|
|
1536
|
-
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=
|
|
1537
|
-
`);m=x.pop()??"";for(let T of x)T.trim()&&(e.match&&!T.includes(e.match)||(console.log(T),y??=Date.now()+
|
|
1542
|
+
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=_e(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 VT=r=>new Promise(e=>setTimeout(e,r));async function Vg(r,e){if(!r){Yl(await Y(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=Vl(await Y(),r,"wait",process.cwd(),Kn()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=e.timeoutSec??1800,a=e.match??"",c=_e(t.pid).offset,l=ol(t.pid,a)??(a?ol(t.pid):void 0),f=l!==void 0&&l<=c?l:a?0:c,u=Date.now()+o*1e3,d=n?1e4:1e3,p=2e3,y,m="",b=0;for(;;){let k=_e(t.pid,f);if(f=k.offset,k.text){m+=k.text;let x=m.split(`
|
|
1543
|
+
`);m=x.pop()??"";for(let T of x)T.trim()&&(e.match&&!T.includes(e.match)||(console.log(T),y??=Date.now()+d,n&&(T.includes("] compile error")||T.includes("] runtime error"))&&(y=Math.min(y,Date.now()+p))))}if(y&&Date.now()>=y)break;if(!i&&!y&&Date.now()>=u){console.error(`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${Hn(t)} within ${o}s`),b=2;break}if(!cl(t.pid)){y||(console.error(`server ${Hn(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await VT(400)}Ii(t.pid,f,a),process.exit(b)}async function Gg(r){if(!r){Yl(await Y(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Vl(await Y(),r,"stop",process.cwd(),Kn());await jt(e.pid),console.log(`Stopped ${Hn(e)} (pid ${e.pid}, ${e.url}).`)}async function zg(r){let e=process.cwd(),t=r==="agent"?Kn():void 0,n=r==="global"?await Y():r==="bulbs"?await Y(e):(await Y()).filter(i=>i.agent!=null&&i.cwd!=null&&ee(i.cwd)===ee(e)&&(!t||i.agent===t)),s=r==="global"?"server":r==="agent"?"mirror":"bulb";if(!n.length){console.log(r==="global"?"No running bulb servers.":`No running ${s}s for this project.`);return}await Promise.all(n.map(i=>jt(i.pid))),console.log(`Stopped ${n.length} ${s}${n.length===1?"":"s"}:`);for(let i of n)console.log(` ${i.url} pid ${i.pid} ${Hn(i)}`)}Re();import*as Qg from"path";async function Xg(r,e,t=0){let n=Qg.resolve(r),s=Sr(await Y(),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.")}Ki();bl();mt();import*as $r from"fs/promises";import*as ay from"path";import{EventEmitter as oy}from"events";Be();Bi();import uP from"open";mr();Be();import{Hono as eP}from"hono";import{serve as tP}from"@hono/node-server";import{streamSSE as rP}from"hono/streaming";import*as ry from"fs/promises";import*as ny from"path";import*as Gl from"fs/promises";import*as Wn from"path";var ko=class{async get(e){let t=ve(e),n=Wn.join(En,t+".bin"),s=Wn.join(En,t+".json");try{let[i,o]=await Promise.all([Gl.readFile(n),Gl.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await H();let n=ve(e),s=Wn.join(En,n+".bin"),i=Wn.join(En,n+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([me(s,t.body),me(i,JSON.stringify(o))])}};var Zg=`
|
|
1538
1544
|
const CSS = '\\n' +
|
|
1539
1545
|
/* The agent mirror's token set, verbatim (agents/core/client/styles.css) \u2014 one system across CLI
|
|
1540
1546
|
chrome: app chrome sits on --panel, content wells paint --veil, grays ride one neutral tint.
|
|
@@ -1838,17 +1844,17 @@ export function runInference(ctx) {
|
|
|
1838
1844
|
showConfirm();
|
|
1839
1845
|
document.body.appendChild(host);
|
|
1840
1846
|
}
|
|
1841
|
-
`;
|
|
1842
|
-
${
|
|
1843
|
-
`+te.slice(-4e3)),new ue("LLM output is not valid JSON","parse_error",!0);z.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",z.fixesApplied.join(", "));let St={insight:z.parsed,insightJson:z.json,data:N};yield{kind:"complete",...St,fixesApplied:z.fixesApplied,hash:
|
|
1844
|
-
${s}`),console.log(` ${c}`),o!==e&&console.log(` (port ${e} was busy)`);let l=[],
|
|
1845
|
-
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await
|
|
1847
|
+
`;Re();Dt();Si();mr();import{stream as GT}from"hono/streaming";var zT="X-TB-Stream";function Yn(r){return r instanceof ue?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function xo(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(zT,"1"),GT(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:Yn(s)}))}finally{try{await n.return?.()}catch{}}})}var Eo={log:(...r)=>console.log(...r)};function Ao(r,e){let t=r?.[e]??(Object.hasOwn(Eo,e)?Eo[e]:void 0);return typeof t=="function"?t:void 0}function To(r){return r.constructor?.name==="AsyncGeneratorFunction"}var QT=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,XT=/[?&]target=/,ZT=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function ey(r,e=""){return QT.test(r)?!0:ZT.test(r)&&XT.test(e)}var sy="127.0.0.1",nP=new Set(["localhost","127.0.0.1","::1"]);function sP(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function iP(r){let e=sP(r);return!!e&&nP.has(e)}function oP(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function zl(r){return r instanceof Error?r.message:"Unknown error"}async function iy(r){let{getHtml:e,basePath:t,fsBase:n,port:s,reloadEmitter:i,messageEmitter:o,getServerExports:a,getBulbBlocks:c,saveInferenceResult:l,localOverride:f,trusted:u=!1,trustHint:d,staticAssets:p}=r,y=n??t,m=new eP;m.use("*",async(h,S)=>{if(!iP(h.req.header("host")))return h.text("Forbidden: untrusted Host",403);await S()}),m.use("*",async(h,S)=>{await S(),h.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),h.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let b=[["/__fs/*","the filesystem"],["/__api/*","server-side code (server.ts)"],["/__ai","AI (your API keys)"],["/__infer","AI (your API keys)"],["/__infer-save","the filesystem"]],k=async(h,S)=>{if(!u){let I=new URL(h.req.url).pathname,D=b.find(([X])=>X.endsWith("/*")?I.startsWith(X.slice(0,-2)):I===X)?.[1]??"server-side code (server.ts)";Am(process.pid,D);let N=d?`
|
|
1848
|
+
${d}`:"";return h.text(`Forbidden: this capability requires --trust.${N}`,403)}await S()},x=async(h,S)=>{let I=h.req.header("sec-fetch-site");if(I){if(I!=="same-origin")return h.text(`Forbidden: ${I} request`,403)}else{let D=h.req.header("origin");if(D&&!oP(D,h.req.header("host")))return h.text("Forbidden: cross-origin request",403)}await S()};for(let[h]of b)m.use(h,k),m.use(h,x);m.use("/__log",x),m.post("/__log",async h=>{try{let{args:S}=await h.req.json();console.log(...S||[])}catch{}return h.json({ok:!0})}),o&&(m.use("/__send",x),m.post("/__send",async h=>{let S="";try{S=await h.req.text()}catch{}let I=o.listenerCount("message");return o.emit("message",S),h.json({clients:I})})),m.get("/",h=>h.html(e())),m.post("/__fs/read",async h=>{try{let{path:S}=await h.req.json(),I=await On(S,y,t);return new Response(new Uint8Array(I),{headers:{"Content-Type":"application/octet-stream"}})}catch(S){let I=zl(S);return h.json({error:I},400)}}),m.post("/__fs/write",async h=>{try{let S=h.req.query("path");return S?(await xi(S,new Uint8Array(await h.req.arrayBuffer()),y,t),h.json({success:!0})):h.json({error:"Missing path"},400)}catch(S){let I=zl(S);return h.json({error:I},400)}}),m.post("/__api/:name",async h=>{try{let S=h.req.param("name"),I=Ao(a?.(),S);if(!I)return h.json({error:`API function '${S}' not found`},404);let{args:D}=await h.req.json();if(To(I))return xo(h,I(...D||[]));let N=await I(...D||[]);return h.json({result:N})}catch(S){let I=zl(S);return h.json({error:I},500)}}),m.post("/__ai",async h=>{try{let{messages:S,system:I,effort:D,provider:N,model:X,webSearch:fe,stream:vt}=await h.req.json();if(!S||!Array.isArray(S)||S.length===0)return h.json({message:"messages array is required",code:"unknown",retryable:!1},400);let te=Ue(N,X);if(typeof te=="string")return h.json({message:te,code:"unknown",retryable:!1},400);let z=await ut(te,{messages:S,system:I,effort:D,webSearch:fe,signal:h.req.raw.signal});if(!z.ok){let Ve=await pr(z,te.protocol);return h.json(Ve,z.status)}if(vt)return xo(h,Mt(z,te.protocol));let St=await Lt(z,te.protocol);return St||console.warn("[tb.ai] Empty response from provider"),h.json({text:St})}catch(S){return h.json(Yn(S),500)}}),m.post("/__infer",async h=>{try{let{data:S}=await h.req.json().catch(()=>({})),I=c?.();if(!I?.infer.trim())return h.json({message:"This bulb has no infer.md block.",code:"unknown",retryable:!1},400);let D=Ue();if(typeof D=="string")return h.json({message:D,code:"unknown",retryable:!1},400);let N=Array.isArray(S)?S.map(String):[],X=jc(I,N),fe=await ut(D,{messages:[{role:"user",content:X}],signal:h.req.raw.signal});if(!fe.ok){let te=await pr(fe,D.protocol);return h.json(te,fe.status)}let vt=(async function*(){let te="";for await(let Ve of Mt(fe,D.protocol))Ve.kind!=="text"||!Ve.text||(te+=Ve.text,yield{kind:"delta",text:Ve.text});let z=Fc(te);if(z.parsed===null)throw console.warn(`[tb.infer] output not valid JSON after sanitize; raw output (last 4000 chars):
|
|
1849
|
+
`+te.slice(-4e3)),new ue("LLM output is not valid JSON","parse_error",!0);z.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",z.fixesApplied.join(", "));let St={insight:z.parsed,insightJson:z.json,data:N};yield{kind:"complete",...St,fixesApplied:z.fixesApplied,hash:qc(St)}})();return xo(h,vt)}catch(S){return h.json(Yn(S),500)}});let T=async h=>{let{hash:S}=await h.req.json().catch(()=>({}));return typeof S=="string"?Uc(S):null};m.post("/__infer-save",async h=>{try{if(!l)return h.json({message:"Save is not available for this server.",code:"unknown",retryable:!1},400);let S=await T(h);return S?(await l(S.data,S.insightJson),h.json({ok:!0})):h.json({message:"No decodable #tb= fragment to save.",code:"unknown",retryable:!1},400)}catch(S){return h.json(Yn(S),500)}}),m.get("/__infer-info",h=>{let S=c?.(),I=Lr(S?.config??"").inference,D=zs(S?.data??""),N=Ue();return typeof N=="string"?h.json({error:N,inference:I,data:D}):h.json({provider:N.protocol,model:N.model,inference:I,data:D})}),m.use("/__infer-decode",x),m.post("/__infer-decode",async h=>h.json(await T(h)??{error:"invalid fragment"})),m.get("/__infer-ui.js",h=>h.body(Zg,200,{"Content-Type":"text/javascript; charset=utf-8"})),m.get("/__models",async h=>{try{let S=await qe();return h.json(S)}catch{return h.json([],200)}}),m.get("/__has-own-keys",async h=>{try{return h.json(await vi())}catch{return h.json(!1,200)}});let P=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],C=new ko;m.get("/proxy/*",async h=>{let S=new URL(h.req.url),D=(S.pathname+S.search).slice(7),N=D.lastIndexOf("https://");return N===-1?h.text("Invalid proxy URL",400):O(h,D.slice(N))}),f&&ty(m,`/local/${f.name}/`,f.serveDir),p&&ty(m,p.mount,p.dir);async function O(h,S){let I;try{I=new URL(S)}catch{return h.text("Invalid URL",400)}if(I.protocol!=="https:")return h.text("HTTPS only",400);if(!P.includes(I.hostname))return h.text("Host not allowed",403);let D=await C.get(S);if(D)return new Response(D.body,{status:200,headers:Ql(D.contentType,D.cacheControl)});try{let N=await fetch(S,{headers:{Accept:h.req.header("Accept")||"*/*"},redirect:"follow"});if(!N.ok)return h.text(`Upstream ${N.status}`,N.status);let X=N.headers.get("Content-Type")||void 0,fe=N.headers.get("Cache-Control")||void 0;if(N.body){let[vt,te]=N.body.tee();return(async()=>{try{let z=await new Response(te).arrayBuffer();await C.set(S,{body:Buffer.from(z),contentType:X,cacheControl:fe})}catch{}})(),new Response(vt,{status:N.status,headers:Ql(X,fe)})}return new Response(null,{status:N.status,headers:Ql(X,fe)})}catch(N){return h.text(`Proxy fetch failed: ${N instanceof Error?N.message:N}`,502)}}(i||o)&&m.get("/__reload",h=>rP(h,async S=>{let I=()=>{S.writeSSE({event:"reload",data:""})},D=N=>{S.writeSSE({event:"message",data:JSON.stringify(N)})};for(i?.on("reload",I),o?.on("message",D),S.onAbort(()=>{i?.removeListener("reload",I),o?.removeListener("message",D)});!S.aborted;)await S.sleep(3e4)})),m.notFound(async h=>{if(h.req.method!=="GET")return h.text("Not Found",404);let S=new URL(h.req.url);return ey(S.pathname,S.search)?O(h,"https://esm.sh"+S.pathname+S.search):h.text("Not Found",404)});let R=tP({fetch:m.fetch,port:s,hostname:sy});return{port:s,close:()=>R.close()}}function Ql(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 ty(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=ki(i,t),a=await ry.readFile(o);return new Response(a,{headers:{"Content-Type":aP(o)}})}catch{return n.text("Not Found",404)}})}function aP(r){switch(ny.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"}}async function Xl(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,sy,()=>{let s=n.address(),i=typeof s=="object"&&s?s.port:r;n.close(()=>t(i))}),n.on("error",()=>{t(Xl(r+1))})})}Re();async function Po(r){let{portPreference:e,makeServerOptions:t,makeEntry:n,displayName:s,stopLog:i}=r,o=await Xl(e),a=await iy(t(o)),c=`http://localhost:${o}`;await Em(n(o,c)),console.log(`
|
|
1850
|
+
${s}`),console.log(` ${c}`),o!==e&&console.log(` (port ${e} was busy)`);let l=[],f=async()=>{console.log(`
|
|
1851
|
+
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await In(process.pid),process.exit(0)};return process.on("SIGINT",f),process.on("SIGTERM",f),{port:o,url:c,onCleanup(u){l.push(u)}}}import cP from"chokidar";var lP={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Yt(r){let{target:e,onChange:t,events:n="change",debounceMs:s=150}=r,i,o=cP.watch(e,lP),a=()=>{i&&clearTimeout(i),i=setTimeout(t,s)};return n==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}Re();async function cy(r,e,t,n){let s=process.cwd(),i=$i(process.pid),o=e.watch?new oy:void 0,a=new oy;a.setMaxListeners(0);let c=ge(e.mode),l=await ul(r);l.length&&console.log(`Replacing the running server for this bulb (pid ${l.map(P=>P.pid).join(", ")})`);let f=1;console.log(al(f)),console.log(`Loading ${ay.basename(r)}...`);let{html:u,bulb:d,serverExports:p}=await Wc(r,e.watch,e.trust,n,e.dir);pt(c,r,d.server);let y=e.trust?void 0:kr(d),{port:m,url:b,onCleanup:k}=await Po({portPreference:e.port,displayName:d.name,stopLog:i,makeServerOptions:P=>({getHtml:()=>u,basePath:s,fsBase:Ei(r,e.dir),port:P,reloadEmitter:o,messageEmitter:a,getServerExports:()=>p,getBulbBlocks:()=>({infer:d.infer,insight:d.insight,code:d.code,config:d.config,data:d.data}),saveInferenceResult:async(C,O)=>{let R=await $r.readFile(r,"utf-8");R=Mo(R,"data",C.join(Pp)),R=Mo(R,"insight",O),await $r.writeFile(r,R)},localOverride:n?{name:n.name,serveDir:n.serveDir}:void 0,trusted:e.trust,trustHint:t}),makeEntry:(P,C)=>({pid:process.pid,port:P,url:C,file:r,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,predicted:y})});e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(y?` trust: restricted \u2014 this bulb appears to use ${y}; re-run with --trust to enable it:
|
|
1846
1852
|
${t}
|
|
1847
1853
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
1848
1854
|
`),e.watch&&console.log(` Watching for changes...
|
|
1849
|
-
`);let x,T;if(e.watch&&o){let P=0,C=Promise.resolve();if(x=
|
|
1850
|
-
`),o.emit("reload")}})}}x&&k(x),T&&k(T),k(()=>$r.rm(
|
|
1851
|
-
`):await
|
|
1855
|
+
`);let x,T;if(e.watch&&o){let P=0,C=Promise.resolve();if(x=Yt({target:r,onChange:()=>{let O=++P;C=C.then(async()=>{if(O===P)try{console.log("Recompiling...");let R=await Wc(r,!0,e.trust,n,e.dir);u=R.html,p=R.serverExports,d=R.bulb,f++,console.log(al(f)),o.emit("reload")}catch(R){console.error("Compile error:",R)}})}}),n){let{name:O,serveDir:R}=n;T=Yt({target:R,events:"all",onChange:()=>{console.log(`Local package '${O}' changed. Browser reloading...
|
|
1856
|
+
`),o.emit("reload")}})}}x&&k(x),T&&k(T),k(()=>$r.rm(Hc(r),{force:!0})),e.open&&(l.some(P=>P.port===m)?console.log(` Reusing the open browser tab.
|
|
1857
|
+
`):await uP(b))}mt();import{readFileSync as uy,copyFileSync as dP,existsSync as pP}from"fs";import*as ne from"path";import{fileURLToPath as mP}from"url";import{EventEmitter as hP}from"events";import fy from"open";Re();var Zl=r=>`/agents/${r}/client.js`,fP=`
|
|
1852
1858
|
(() => {
|
|
1853
1859
|
const api = async (name, ...args) => {
|
|
1854
1860
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -1883,15 +1889,15 @@ Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await Nn(pr
|
|
|
1883
1889
|
es.onerror = () => { es.close(); };
|
|
1884
1890
|
}
|
|
1885
1891
|
})();
|
|
1886
|
-
`;function
|
|
1892
|
+
`;function ly(r){let{name:e,agent:t,styles:n,mountHtml:s,watch:i,theme:o}=r,a=Zl(t);return`<!DOCTYPE html>
|
|
1887
1893
|
<html>
|
|
1888
1894
|
<head>
|
|
1889
1895
|
<meta charset="utf-8">
|
|
1890
1896
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1891
|
-
<title>${
|
|
1892
|
-
${
|
|
1897
|
+
<title>${oi(e)} - typebulb</title>
|
|
1898
|
+
${ci(e,o)}
|
|
1893
1899
|
<style>
|
|
1894
|
-
${
|
|
1900
|
+
${ai}
|
|
1895
1901
|
</style>
|
|
1896
1902
|
<style>
|
|
1897
1903
|
${n}
|
|
@@ -1903,17 +1909,17 @@ ${s}
|
|
|
1903
1909
|
${i?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
|
|
1904
1910
|
|
|
1905
1911
|
<script>
|
|
1906
|
-
${
|
|
1912
|
+
${fP}
|
|
1907
1913
|
</script>
|
|
1908
1914
|
|
|
1909
1915
|
<script type="module" src="${a}"></script>
|
|
1910
1916
|
</body>
|
|
1911
|
-
</html>`}async function
|
|
1912
|
-
${n.url}`),r.open&&await
|
|
1913
|
-
`);let x=ne.join(u,t,"client"),T=ne.join(u,"core","client");async function P(){await(await import("esbuild")).build({entryPoints:[ne.join(x,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:ne.join(
|
|
1914
|
-
`),i.emit("reload")}catch(h){console.error("Mirror rebuild failed:",h instanceof Error?h.message:h)}finally{R=!1}}}})}r.open&&await
|
|
1915
|
-
`);let
|
|
1916
|
-
`)}catch(
|
|
1917
|
-
`),
|
|
1918
|
-
`),process.exit(1)}function
|
|
1919
|
-
${e}`),process.exit(1))}async function
|
|
1917
|
+
</html>`}async function dy(r){let e=process.cwd(),t=r.agentTarget;mg(t)||(console.error(`Unknown agent '${t}'. Known: ${Rr().join(", ")}.`),process.exit(1));let n=await ll(e,t);if(n){console.log(`Mirror '${t}' is already running for this project:
|
|
1918
|
+
${n.url}`),r.open&&await fy(n.url);return}let s=$i(process.pid),i=r.watch?new hP:void 0,o=ge(r.mode),a=await gg(t),c=a.displayName||`${t} mirror`;pt(o,ne.join(e,"mirror"));let l=ne.dirname(mP(import.meta.url)),f=ne.join(l,"agents",t),u=ne.join(l,"..","cli","agents"),d=ne.join(f,"styles.css"),p=ne.join(f,"index.html"),y=()=>ly({name:c,agent:t,styles:uy(d,"utf8"),mountHtml:uy(p,"utf8"),watch:r.watch}),{port:m,url:b,onCleanup:k}=await Po({portPreference:r.port,displayName:c,stopLog:s,makeServerOptions:O=>({getHtml:y,basePath:e,port:O,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${ne.posix.dirname(Zl(t))}/`,dir:f}}),makeEntry:(O,R)=>({pid:process.pid,port:O,url:R,file:`agent:${t}`,cwd:e,startedAt:Date.now(),trust:!0,agent:t})});r.watch&&console.log(` Watching for changes...
|
|
1919
|
+
`);let x=ne.join(u,t,"client"),T=ne.join(u,"core","client");async function P(){await(await import("esbuild")).build({entryPoints:[ne.join(x,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:ne.join(f,"client.js")});for(let R of["styles.css","index.html","typebulb.png","typebulb-inv.png"])dP(ne.join(T,R),ne.join(f,R))}let C;if(r.watch&&i){let O=pP(x),R=!1;C=Yt({target:O?u:f,events:"all",onChange:async()=>{if(!R){R=!0;try{O&&await P(),console.log(`Mirror rebuilt. Browser reloading...
|
|
1920
|
+
`),i.emit("reload")}catch(h){console.error("Mirror rebuild failed:",h instanceof Error?h.message:h)}finally{R=!1}}}})}r.open&&await fy(b),k(()=>a.shutdownSwitcher?.()),k(()=>a.shutdownComposer?.()),C&&k(C)}mt();import*as py from"path";async function my(r,e,t,n,s){let i=ge(t),o=!1,a=async()=>{let{bulb:c,config:l}=await xe(r);o||(pt(i,r,c.server),o=!0),await Cn(c.server,r,n,l.dependencies,s)};if(console.log(`Running ${py.basename(r)}...`),await a(),e){console.log(`Watching for changes...
|
|
1921
|
+
`);let c=0,l=Promise.resolve();Yt({target:r,onChange:()=>{let f=++c;l=l.then(async()=>{if(f===c)try{console.log("Re-running..."),await a()}catch(u){console.error("Error:",u)}})}})}}mt();import{Console as gP}from"node:console";Re();async function yy(r,e,t,n,s){SP();try{let p=Sr(await Y(),r)[0];p&&(Ii(p.pid,_e(p.pid).offset),console.error(`note: 'call' boots a fresh server.ts instance; the running server (${p.url}) is not contacted \u2014 state shared with it must live on disk.`))}catch{}let i=ge(t),{bulb:o,config:a}=await xe(r);o.server||Vn("This bulb has no **server.ts** block; nothing to call."),pt(i,r,o.server);let c;try{c=await Cn(o.server,r,n,a.dependencies,s)}catch(p){Vn(p instanceof Error?p.message:String(p))}let l=Ao(c,e.fn);if(!l){let p=[...Object.keys(c).filter(y=>typeof c[y]=="function"),...Object.keys(Eo)];Vn(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let f=await yP(e);if(To(l)){try{for await(let p of l(...f))await gy(JSON.stringify(p,by)+`
|
|
1922
|
+
`)}catch(p){Vn(p instanceof Error?p.stack??p.message:String(p))}return hy(0)}let u;try{u=await l(...f)}catch(p){Vn(p instanceof Error?p.stack??p.message:String(p))}let d=vP(u);d!==void 0&&await gy(d+`
|
|
1923
|
+
`),hy(0)}function hy(r){process.exitCode=r,setTimeout(()=>process.exit(r),2e3).unref?.()}async function yP(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await kP()),wP(e)}return bP(r.positional)}function bP(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function wP(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 vP(r){if(r!==void 0)return JSON.stringify(r,by,2)}function by(r,e){return typeof e=="bigint"?e.toString():e}function Vn(r){process.stderr.write(r+`
|
|
1924
|
+
`),process.exit(1)}function SP(){let r=new gP(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 gy(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function kP(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var eu="0.29.1";function wy(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
1925
|
+
${e}`),process.exit(1))}async function xP(){let r=gu(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${eu}`),process.exit(0)),r.help&&(yu(),process.exit(0)),Dg(),r.subcommand==="logs"){await Yg(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await Vg(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await zg(r.stopScope):await Gg(r.file||void 0);return}if(r.subcommand==="send"){await Xg(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await Kg(eu);return}if(r.subcommand==="models"){await Ug(r.mode);return}if(r.subcommand==="pull"){await qm(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="push"){await Km(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="agent"){await(r.agentTarget?dy(r):qg(eu));return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await Mg(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let c=await lm(process.cwd());c||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=c}else e=Vt.resolve(r.file);await vy.access(e).then(()=>!0,()=>!1)||(Rr().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:Vt.relative(process.cwd(),e)||Vt.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await Lg(e,s);return}let i=!r.noTrust&&Bt(e);i&&!r.trust&&console.error("trust: granted from memory (run `typebulb untrust` to revoke)"),r.trust=r.noTrust?!1:r.trust||i;let o;try{o=await xe(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 pu(r.local)}catch(c){console.error(c instanceof Error?c.message:String(c)),process.exit(1)}console.error(`replace: ${a.name} \u2192 ${Vt.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await $g(e,a);return}if(r.subcommand==="call"){wy(r.trust,s),await yy(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a,r.dir);return}if(o&&o.bulb.server&&(Qs(o.bulb)||r.server)){wy(r.trust,s),await my(e,r.watch,r.mode,a,r.dir);return}await cy(e,r,s,a)}xP().catch(r=>{console.error("Error:",r.message),process.exit(1)});
|