typebulb 0.31.1 → 0.31.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -1,91 +1,91 @@
|
|
|
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 By=Object.create;var _o=Object.defineProperty;var jy=Object.getOwnPropertyDescriptor;var Fy=Object.getOwnPropertyNames;var qy=Object.getPrototypeOf,Uy=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),cu=(r,e)=>{for(var t in e)_o(r,t,{get:e[t],enumerable:!0})},Jy=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fy(e))!Uy.call(r,s)&&s!==t&&_o(r,s,{get:()=>e[s],enumerable:!(n=jy(e,s))||n.enumerable});return r};var Ky=(r,e,t)=>(t=r!=null?By(qy(r)):{},Jy(e||!r||!r.__esModule?_o(t,"default",{value:r,enumerable:!0}):t,r));function vu(r){return Qe.find(e=>Pe[e].path===r)}function xu(r){return!!r?.startsWith("typebulb")}var Pe,Qe,Su,zn=A(()=>{Pe={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"}},Qe=["code","css","html","data","infer","insight","config","notes"];Su="typebulb/v1"});function $o(r){return/[:\n"']/.test(r)||r.startsWith(" ")||r.endsWith(" ")?`"${r.replace(/"/g,'\\"')}"`:r}function Lo(r){return r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1).replace(/\\"/g,'"'):r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}var Xn=A(()=>{});function fe(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=tb(n);if(!s)return null;let i=new Map,o=[],a=t;for(;t<e.length;){let l=e[t]?.trim()?.match(ku);if(l){let f=l[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let u=e[t]?.match(Qn);if(!u){o.push(`**${f}** has no code fence \u2014 block skipped`);continue}let d=u[1];t++;let p=[],y=Mo(d);for(;t<e.length&&!e[t]?.match(y);)p.push(e[t]),t++;let m=t<e.length;t++,o.push(...Zy(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 Zy(r,e,t){let n=[];for(let s=0;s<e.length;s++){let i=e[s]?.trim().match(ku);i&&Qy.has(i[1].trim())&&eb(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 eb(r,e){let t=e+1;for(;t<r.length&&r[t]?.trim()==="";)t++;return!!r[t]?.match(Qn)}function tb(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=Lo(i);break}}return!xu(e.format)||!e.name?null:e}function Eu(r){return fe(r)?.warnings??[]}function Au(r){let e=Object.fromEntries(Qe.map(t=>[t,r.files.get(Pe[t].path)||""]));return{name:r.frontmatter.name,...e}}var ku,Qn,Qy,Mo,Do=A(()=>{zn();Xn();ku=/^\*\*(.+)\*\*$/,Qn=/^(`{3,})(\w*)\s*$/,Qy=new Set(Qe.map(r=>Pe[r].path)),Mo=r=>new RegExp(`^${r}\\s*$`)});function Tu(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 Pu(r,e){let{path:t}=Pe[r],n=t.split(".").pop(),s=Tu(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(Qn);if(!a)continue;let c=
|
|
9
|
+
${s}`}function Ou(r){let e=Qe.filter(t=>r[t]).map(t=>Pu(t,r[t]));return["---",`format: ${Su}`,`name: ${$o(r.name)}`,"---","",...e].join(`
|
|
10
|
+
`)}function Bo(r,e,t){let{path:n}=Pe[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(Qn);if(!a)continue;let c=Mo(a[1]),l=o+1;for(;l<s.length&&!s[l]?.match(c);)l++;if(l>=s.length)return r;let f=Tu(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
|
|
15
|
+
${Pu(e,t)}
|
|
16
|
+
`}var _u=A(()=>{zn();Do();Xn()});function Lr(r){if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}function nb(r){return r.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"")}function jo(r){let e=Lr(r??"").description?.trim();if(!e)return rb;let t=nb(e);return(t.length>200?t.slice(0,197)+"...":t).replace(/\n/g," ")}var rb,Cu=A(()=>{rb="A Typebulb bulb."});var Ru=A(()=>{});function Fo(r,e,t){let s=new RegExp(e).exec(r.slice(t));return s?t+s.index:-1}var Nu=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 Iu=A(()=>{});function Zn(r,e){let t=new RegExp(e,"g"),n=r.match(t);return n?n.length:0}var $u=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=Fo(r,`<${e}[
|
|
17
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
|
|
19
|
-
`)}};jr.defaultYaml={explicit:!1,version:"1.2"};jr.defaultTags={"!!":"tag:yaml.org,2002:"};
|
|
20
|
-
`)?
|
|
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 qo=A(()=>{Nu();Iu();$u()});var Uo=A(()=>{qo()});var Jo=A(()=>{Uo()});var Lu=A(()=>{Jo()});var Mu=A(()=>{});var Du=A(()=>{Ru();qo();Uo();Lu();Jo();Mu()});var j=E(te=>{"use strict";var Ko=Symbol.for("yaml.alias"),Bu=Symbol.for("yaml.document"),es=Symbol.for("yaml.map"),ju=Symbol.for("yaml.pair"),Ho=Symbol.for("yaml.scalar"),ts=Symbol.for("yaml.seq"),Fe=Symbol.for("yaml.node.type"),ob=r=>!!r&&typeof r=="object"&&r[Fe]===Ko,ab=r=>!!r&&typeof r=="object"&&r[Fe]===Bu,cb=r=>!!r&&typeof r=="object"&&r[Fe]===es,lb=r=>!!r&&typeof r=="object"&&r[Fe]===ju,Fu=r=>!!r&&typeof r=="object"&&r[Fe]===Ho,ub=r=>!!r&&typeof r=="object"&&r[Fe]===ts;function qu(r){if(r&&typeof r=="object")switch(r[Fe]){case es:case ts:return!0}return!1}function db(r){if(r&&typeof r=="object")switch(r[Fe]){case Ko:case es:case Ho:case ts:return!0}return!1}var fb=r=>(Fu(r)||qu(r))&&!!r.anchor;te.ALIAS=Ko;te.DOC=Bu;te.MAP=es;te.NODE_TYPE=Fe;te.PAIR=ju;te.SCALAR=Ho;te.SEQ=ts;te.hasAnchor=fb;te.isAlias=ob;te.isCollection=qu;te.isDocument=ab;te.isMap=cb;te.isNode=db;te.isPair=lb;te.isScalar=Fu;te.isSeq=ub});var Br=E(Wo=>{"use strict";var Q=j(),ae=Symbol("break visit"),Uu=Symbol("skip children"),Oe=Symbol("remove node");function rs(r,e){let t=Ju(e);Q.isDocument(r)?Xt(null,r.contents,t,Object.freeze([r]))===Oe&&(r.contents=null):Xt(null,r,t,Object.freeze([]))}rs.BREAK=ae;rs.SKIP=Uu;rs.REMOVE=Oe;function Xt(r,e,t,n){let s=Ku(r,e,t,n);if(Q.isNode(s)||Q.isPair(s))return Hu(r,n,s),Xt(r,s,t,n);if(typeof s!="symbol"){if(Q.isCollection(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){let o=Xt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ae)return ae;o===Oe&&(e.items.splice(i,1),i-=1)}}}else if(Q.isPair(e)){n=Object.freeze(n.concat(e));let i=Xt("key",e.key,t,n);if(i===ae)return ae;i===Oe&&(e.key=null);let o=Xt("value",e.value,t,n);if(o===ae)return ae;o===Oe&&(e.value=null)}}return s}async function ns(r,e){let t=Ju(e);Q.isDocument(r)?await Qt(null,r.contents,t,Object.freeze([r]))===Oe&&(r.contents=null):await Qt(null,r,t,Object.freeze([]))}ns.BREAK=ae;ns.SKIP=Uu;ns.REMOVE=Oe;async function Qt(r,e,t,n){let s=await Ku(r,e,t,n);if(Q.isNode(s)||Q.isPair(s))return Hu(r,n,s),Qt(r,s,t,n);if(typeof s!="symbol"){if(Q.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===ae)return ae;o===Oe&&(e.items.splice(i,1),i-=1)}}}else if(Q.isPair(e)){n=Object.freeze(n.concat(e));let i=await Qt("key",e.key,t,n);if(i===ae)return ae;i===Oe&&(e.key=null);let o=await Qt("value",e.value,t,n);if(o===ae)return ae;o===Oe&&(e.value=null)}}return s}function Ju(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 Ku(r,e,t,n){if(typeof t=="function")return t(r,e,n);if(Q.isMap(e))return t.Map?.(r,e,n);if(Q.isSeq(e))return t.Seq?.(r,e,n);if(Q.isPair(e))return t.Pair?.(r,e,n);if(Q.isScalar(e))return t.Scalar?.(r,e,n);if(Q.isAlias(e))return t.Alias?.(r,e,n)}function Hu(r,e,t){let n=e[e.length-1];if(Q.isCollection(n))n.items[r]=t;else if(Q.isPair(n))r==="key"?n.key=t:n.value=t;else if(Q.isDocument(n))n.contents=t;else{let s=Q.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}Wo.visit=rs;Wo.visitAsync=ns});var Yo=E(Yu=>{"use strict";var Wu=j(),pb=Br(),mb={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},hb=r=>r.replace(/[!,[\]{}]/g,e=>mb[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+hb(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&&Wu.isNode(e.contents)){let i={};pb.visit(e.contents,(o,a)=>{Wu.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:"};Yu.Directives=jr});var ss=E(Fr=>{"use strict";var Vu=j(),gb=Br();function yb(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 Gu(r){let e=new Set;return gb.visit(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function zu(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function bb(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s??(s=Gu(r));let o=zu(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(Vu.isScalar(o.node)||Vu.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=yb;Fr.anchorNames=Gu;Fr.createNodeAnchors=bb;Fr.findNewAnchor=zu});var Vo=E(Xu=>{"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)}Xu.applyReviver=qr});var Ze=E(Zu=>{"use strict";var wb=j();function Qu(r,e,t){if(Array.isArray(r))return r.map((n,s)=>Qu(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!wb.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}Zu.toJS=Qu});var is=E(td=>{"use strict";var vb=Vo(),ed=j(),Sb=Ze(),Go=class{constructor(e){Object.defineProperty(this,ed.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(!ed.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=Sb.toJS(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?vb.applyReviver(i,{"":a},"",a):a}};td.NodeBase=Go});var Ur=E(rd=>{"use strict";var xb=ss(),kb=Br(),Zt=j(),Eb=is(),Ab=Ze(),zo=class extends Eb.NodeBase{constructor(e){super(Zt.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)=>{(Zt.isAlias(o)||Zt.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||(Ab.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(xb.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(Zt.isAlias(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(Zt.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(Zt.isPair(e)){let n=os(r,e.key,t),s=os(r,e.value,t);return Math.max(n,s)}return 1}rd.Alias=zo});var G=E(Xo=>{"use strict";var Tb=j(),Pb=is(),Ob=Ze(),_b=r=>!r||typeof r!="function"&&typeof r!="object",et=class extends Pb.NodeBase{constructor(e){super(Tb.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:Ob.toJS(this.value,e,t)}toString(){return String(this.value)}};et.BLOCK_FOLDED="BLOCK_FOLDED";et.BLOCK_LITERAL="BLOCK_LITERAL";et.PLAIN="PLAIN";et.QUOTE_DOUBLE="QUOTE_DOUBLE";et.QUOTE_SINGLE="QUOTE_SINGLE";Xo.Scalar=et;Xo.isScalarValue=_b});var Jr=E(sd=>{"use strict";var Cb=Ur(),kt=j(),nd=G(),Rb="tag:yaml.org,2002:";function Nb(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 Ib(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=Rb+e.slice(2));let l=Nb(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new nd.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 nd.Scalar(r);return e?f.tag=e:l.default||(f.tag=l.tag),c&&(c.node=f),f}sd.createNode=Ib});var cs=E(as=>{"use strict";var $b=Jr(),_e=j(),Lb=is();function Qo(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 $b.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 id=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,Zo=class extends Lb.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=>_e.isNode(n)||_e.isPair(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(id(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(_e.isCollection(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,Qo(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(_e.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&&_e.isScalar(i)?i.value:i:_e.isCollection(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!_e.isPair(t))return!1;let n=t.value;return n==null||e&&_e.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 _e.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(_e.isCollection(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,Qo(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};as.Collection=Zo;as.collectionFromPath=Qo;as.isEmptyPath=id});var Kr=E(ls=>{"use strict";var Mb=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function ea(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var Db=(r,e,t)=>r.endsWith(`
|
|
20
|
+
`)?ea(t,e):t.includes(`
|
|
21
21
|
`)?`
|
|
22
|
-
`+
|
|
23
|
-
`)t===
|
|
22
|
+
`+ea(t,e):(r.endsWith(" ")?"":" ")+t;ls.indentComment=ea;ls.lineComment=Db;ls.stringifyComment=Mb});var ad=E(Hr=>{"use strict";var Bb="flow",ta="block",us="quoted";function jb(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,x=-1;t===ta&&(m=od(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}x=m}if(T===`
|
|
23
|
+
`)t===ta&&(m=od(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!==" "&&(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>x+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 k=r.slice(0,l[0]);for(let T=0;T<l.length;++T){let P=l[T],
|
|
26
|
-
${e}${r.slice(0,
|
|
27
|
-
${e}${r.slice(P+1,
|
|
28
|
-
`);n=e,s=e+1,i=r[s]}return n}Hr.FOLD_BLOCK=
|
|
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>x+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 k=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?k=`
|
|
26
|
+
${e}${r.slice(0,C)}`:(t===us&&f[P]&&(k+=`${r[P]}\\`),k+=`
|
|
27
|
+
${e}${r.slice(P+1,C)}`)}return k}function od(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=ta;Hr.FOLD_FLOW=Bb;Hr.FOLD_QUOTED=us;Hr.foldFlowLines=jb});var Yr=E(cd=>{"use strict";var be=G(),tt=ad(),fs=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),ps=r=>/^(%|---|\.\.\.)/m.test(r);function Fb(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
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:
|
|
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:tt.foldFlowLines(o,i,tt.FOLD_QUOTED,fs(e,!1))}function ra(r,e){if(e.options.singleQuote===!1||e.implicitKey&&r.includes(`
|
|
33
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:
|
|
34
|
+
${t}`)+"'";return e.implicitKey?n:tt.foldFlowLines(n,t,tt.FOLD_FLOW,fs(e,!1))}function er(r,e){let{singleQuote:t}=e.options,n;if(t===!1)n=Wr;else{let s=r.includes('"'),i=r.includes("'");s&&!i?n=ra:i&&!s?n=Wr:n=t?ra:Wr}return n(r,e)}var na;try{na=new RegExp(`(^|(?<!
|
|
35
35
|
))
|
|
36
36
|
+(?!
|
|
37
|
-
|$)`,"g")}catch{
|
|
37
|
+
|$)`,"g")}catch{na=/\n+(?!\n|$)/g}function ds({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 er(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:!Fb(t,c,l.length);if(!t)return f?`|
|
|
38
38
|
`:`>
|
|
39
|
-
`;let u,d;for(d=t.length;d>0;--d){let
|
|
40
|
-
`&&
|
|
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
|
-
`)x=b;else break}let k=t.substring(0,x<b?x+1:b);k&&(t=t.substring(k.length),k=k.replace(/\n+/g,`$&${l}`));let P=(m?l?"2":"1":"")+u;if(r&&(P+=" "+a(r.replace(/ ?[\r\n]+/g," ")),s&&s()),!f){let
|
|
44
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),
|
|
42
|
+
`&&(p=p.slice(0,-1)),p=p.replace(na,`$&${l}`));let m=!1,b,x=-1;for(b=0;b<t.length;++b){let C=t[b];if(C===" ")m=!0;else if(C===`
|
|
43
|
+
`)x=b;else break}let k=t.substring(0,x<b?x+1:b);k&&(t=t.substring(k.length),k=k.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}`),_=!1,N=fs(n,!0);o!=="folded"&&e!==be.Scalar.BLOCK_FOLDED&&(N.onOverflow=()=>{_=!0});let h=tt.foldFlowLines(`${k}${C}${p}`,l,tt.FOLD_BLOCK,N);if(!_)return`>${P}
|
|
45
45
|
${l}${h}`}return t=t.replace(/\n+/g,`$&${l}`),`|${P}
|
|
46
|
-
${l}${k}${t}${p}`}function
|
|
47
|
-
`)||f&&/[[\]{},]/.test(i))return
|
|
48
|
-
`)?
|
|
49
|
-
`))return ds(r,e,t,n);if(ps(i)){if(c==="")return e.forceBlockIndent=!0,ds(r,e,t,n);if(a&&c===l)return
|
|
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
|
|
51
|
-
${e.indent}${a}`:a}
|
|
52
|
-
${a}:`):(b=`${b}:`,d&&(b+=Gr.lineComment(b,t.indent,l(d))));let x,k,T;
|
|
53
|
-
`:"",k){let N=l(k);
|
|
54
|
-
${Gr.indentComment(N,t.indent)}`}
|
|
55
|
-
`&&T&&(
|
|
56
|
-
|
|
57
|
-
`):
|
|
58
|
-
${t.indent}`}else if(!p&&
|
|
59
|
-
`),
|
|
60
|
-
${t.indent}`)}}else(
|
|
61
|
-
`)&&(
|
|
46
|
+
${l}${k}${t}${p}`}function qb(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 er(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||f||!i.includes(`
|
|
48
|
+
`)?er(i,e):ds(r,e,t,n);if(!a&&!f&&s!==be.Scalar.PLAIN&&i.includes(`
|
|
49
|
+
`))return ds(r,e,t,n);if(ps(i)){if(c==="")return e.forceBlockIndent=!0,ds(r,e,t,n);if(a&&c===l)return er(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 er(i,e)}return a?u:tt.foldFlowLines(u,c,tt.FOLD_FLOW,fs(e,!1))}function Ub(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?er(o.value,e):ds(o,e,t,n);case be.Scalar.QUOTE_DOUBLE:return Wr(o.value,e);case be.Scalar.QUOTE_SINGLE:return ra(o.value,e);case be.Scalar.PLAIN:return qb(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}cd.stringifyString=Ub});var Vr=E(sa=>{"use strict";var Jb=ss(),rt=j(),Kb=Kr(),Hb=Yr();function Wb(r,e){let t=Object.assign({blockQuote:!0,commentString:Kb.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 Yb(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(rt.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 Vb(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let s=[],i=(rt.isScalar(r)||rt.isCollection(r))&&r.anchor;i&&Jb.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 Gb(r,e,t,n){if(rt.isPair(r))return r.toString(e,t,n);if(rt.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=rt.isNode(r)?r:e.doc.createNode(r,{onTagObj:c=>s=c});s??(s=Yb(e.doc.schema.tags,i));let o=Vb(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):rt.isScalar(i)?Hb.stringifyString(i,e,t,n):i.toString(e,t,n);return o?rt.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
51
|
+
${e.indent}${a}`:a}sa.createStringifyContext=Wb;sa.stringify=Gb});var fd=E(dd=>{"use strict";var qe=j(),ld=G(),ud=Vr(),Gr=Kr();function zb({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=qe.isNode(r)&&r.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(qe.isCollection(r)||!qe.isNode(r)&&typeof r=="object"){let N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let p=!u&&(!r||d&&e==null&&!t.inFlow||qe.isCollection(r)||(qe.isScalar(r)?r.type===ld.Scalar.BLOCK_FOLDED||r.type===ld.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=ud.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 x,k,T;qe.isNode(e)?(x=!!e.spaceBefore,k=e.commentBefore,T=e.comment):(x=!1,k=null,T=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!d&&qe.isScalar(e)&&(t.indentAtStart=b.length+1),m=!1,!f&&c.length>=2&&!t.inFlow&&!p&&qe.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let P=!1,C=ud.stringify(e,t,()=>P=!0,()=>m=!0),_=" ";if(d||x||k){if(_=x?`
|
|
53
|
+
`:"",k){let N=l(k);_+=`
|
|
54
|
+
${Gr.indentComment(N,t.indent)}`}C===""&&!t.inFlow?_===`
|
|
55
|
+
`&&T&&(_=`
|
|
56
|
+
|
|
57
|
+
`):_+=`
|
|
58
|
+
${t.indent}`}else if(!p&&qe.isCollection(e)){let N=C[0],h=C.indexOf(`
|
|
59
|
+
`),v=h!==-1,I=t.inFlow??e.flow??e.items.length===0;if(v||!I){let L=!1;if(v&&(N==="&"||N==="!")){let R=C.indexOf(" ");N==="&"&&R!==-1&&R<h&&C[R+1]==="!"&&(R=C.indexOf(" ",R+1)),(R===-1||h<R)&&(L=!0)}L||(_=`
|
|
60
|
+
${t.indent}`)}}else(C===""||C[0]===`
|
|
61
|
+
`)&&(_="");return b+=_+C,t.inFlow?P&&n&&n():T&&!P?b+=Gr.lineComment(b,t.indent,l(T)):m&&s&&s(),b}dd.stringifyPair=zb});var oa=E(ia=>{"use strict";var pd=Gn("process");function Xb(r,...e){r==="debug"&&console.log(...e)}function Qb(r,e){(r==="debug"||r==="warn")&&(typeof pd.emitWarning=="function"?pd.emitWarning(e):console.warn(e))}ia.debug=Xb;ia.warn=Qb});var ys=E(gs=>{"use strict";var zr=j(),md=G(),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 md.Scalar(Symbol(ms)),{addToJSMap:hd}),stringify:()=>ms},Zb=(r,e)=>(hs.identify(e)||zr.isScalar(e)&&(!e.type||e.type===md.Scalar.PLAIN)&&hs.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===hs.tag&&t.default);function hd(r,e,t){if(t=r&&zr.isAlias(t)?t.resolve(r.doc):t,zr.isSeq(t))for(let n of t.items)aa(r,e,n);else if(Array.isArray(t))for(let n of t)aa(r,e,n);else aa(r,e,t)}function aa(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=hd;gs.isMergeKey=Zb;gs.merge=hs});var la=E(bd=>{"use strict";var ew=oa(),gd=ys(),tw=Vr(),yd=j(),ca=Ze();function rw(r,e,{key:t,value:n}){if(yd.isNode(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(gd.isMergeKey(r,t))gd.addMergeToJSMap(r,e,n);else{let s=ca.toJS(t,"",r);if(e instanceof Map)e.set(s,ca.toJS(n,s,r));else if(e instanceof Set)e.add(s);else{let i=nw(t,s,r),o=ca.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 nw(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(yd.isNode(r)&&t?.doc){let n=tw.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)+'..."'),ew.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)}bd.addPairToJSMap=rw});var nt=E(ua=>{"use strict";var wd=Jr(),sw=fd(),iw=la(),bs=j();function ow(r,e,t){let n=wd.createNode(r,void 0,t),s=wd.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 iw.addPairToJSMap(t,n,this)}toString(e,t,n){return e?.doc?sw.stringifyPair(this,e,t,n):JSON.stringify(this)}};ua.Pair=ws;ua.createPair=ow});var da=E(Sd=>{"use strict";var Et=j(),vd=Vr(),vs=Kr();function aw(r,e,t){return(e.inFlow??r.flow?lw:cw)(r,e,t)}function cw({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(Et.isNode(m))!u&&m.spaceBefore&&d.push(""),Ss(t,d,m.commentBefore,u),m.comment&&(b=m.comment);else if(Et.isPair(m)){let k=Et.isNode(m.key)?m.key:null;k&&(!u&&k.spaceBefore&&d.push(""),Ss(t,d,k.commentBefore,u))}u=!1;let x=vd.stringify(m,f,()=>b=null,()=>u=!0);b&&(x+=vs.lineComment(x,i,l(b))),u&&b&&(u=!1),d.push(n+x)}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
|
-
`+vs.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function
|
|
64
|
+
`+vs.indentComment(l(r),c),a&&a()):u&&o&&o(),p}function lw({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(Et.isNode(m))m.spaceBefore&&u.push(""),Ss(e,u,m.commentBefore,!1),m.comment&&(b=m.comment);else if(Et.isPair(m)){let k=Et.isNode(m.key)?m.key:null;k&&(k.spaceBefore&&u.push(""),Ss(e,u,k.commentBefore,!1),k.comment&&(l=!0));let T=Et.isNode(m.value)?m.value:null;T?(T.comment&&(b=T.comment),T.commentBefore&&(l=!0)):m.value==null&&k?.comment&&(b=k.comment)}b&&(l=!0);let x=vd.stringify(m,c,()=>b=null);y<r.length-1&&(x+=","),b&&(x+=vs.lineComment(x,n,a(b))),!l&&(u.length>f||x.includes(`
|
|
65
65
|
`))&&(l=!0),u.push(x),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`${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())}}
|
|
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())}}Sd.stringifyCollection=aw});var it=E(pa=>{"use strict";var uw=da(),dw=la(),fw=cs(),st=j(),xs=nt(),pw=G();function Xr(r,e){let t=st.isScalar(e)?e.value:e;for(let n of r)if(st.isPair(n)&&(n.key===e||n.key===t||st.isScalar(n.key)&&n.key.value===t))return n}var fa=class extends fw.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(st.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(xs.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;st.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new xs.Pair(e,e?.value):n=new xs.Pair(e.key,e.value);let s=Xr(this.items,n.key),i=this.schema?.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);st.isScalar(s.value)&&pw.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=Xr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let s=Xr(this.items,e)?.value;return(!t&&st.isScalar(s)?s.value:s)??void 0}has(e){return!!Xr(this.items,e)}set(e,t){this.add(new xs.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)dw.addPairToJSMap(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!st.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})),uw.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};pa.YAMLMap=fa;pa.findPair=Xr});var tr=E(kd=>{"use strict";var mw=j(),xd=it(),hw={collection:"map",default:!0,nodeClass:xd.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return mw.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>xd.YAMLMap.from(r,e,t)};kd.map=hw});var ot=E(Ed=>{"use strict";var gw=Jr(),yw=da(),bw=cs(),Es=j(),ww=G(),vw=Ze(),ma=class extends bw.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=ks(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=ks(e);if(typeof n!="number")return;let s=this.items[n];return!t&&Es.isScalar(s)?s.value:s}has(e){let t=ks(e);return typeof t=="number"&&t<this.items.length}set(e,t){let n=ks(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let s=this.items[n];Es.isScalar(s)&&ww.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(vw.toJS(i,String(s++),t));return n}toString(e,t,n){return e?yw.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(gw.createNode(a,void 0,n))}}return i}};function ks(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}Ed.YAMLSeq=ma});var rr=E(Td=>{"use strict";var Sw=j(),Ad=ot(),xw={collection:"seq",default:!0,nodeClass:Ad.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Sw.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Ad.YAMLSeq.from(r,e,t)};Td.seq=xw});var Qr=E(Pd=>{"use strict";var kw=Yr(),Ew={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)}};Pd.string=Ew});var As=E(Cd=>{"use strict";var Od=G(),_d={identify:r=>r==null,createNode:()=>new Od.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Od.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&_d.test.test(r)?r:e.options.nullStr};Cd.nullTag=_d});var ha=E(Nd=>{"use strict";var Aw=G(),Rd={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new Aw.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Rd.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};Nd.boolTag=Rd});var nr=E(Id=>{"use strict";function Tw({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}Id.stringifyNumber=Tw});var ya=E(Ts=>{"use strict";var Pw=G(),ga=nr(),Ow={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:ga.stringifyNumber},_w={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():ga.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 Pw.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:ga.stringifyNumber};Ts.float=Cw;Ts.floatExp=_w;Ts.floatNaN=Ow});var wa=E(Os=>{"use strict";var $d=nr(),Ps=r=>typeof r=="bigint"||Number.isInteger(r),ba=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function Ld(r,e,t){let{value:n}=r;return Ps(n)&&n>=0?t+n.toString(e):$d.stringifyNumber(r)}var Rw={identify:r=>Ps(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>ba(r,2,8,t),stringify:r=>Ld(r,8,"0o")},Nw={identify:Ps,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>ba(r,0,10,t),stringify:$d.stringifyNumber},Iw={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)=>ba(r,2,16,t),stringify:r=>Ld(r,16,"0x")};Os.int=Nw;Os.intHex=Iw;Os.intOct=Rw});var Dd=E(Md=>{"use strict";var $w=tr(),Lw=As(),Mw=rr(),Dw=Qr(),Bw=ha(),va=ya(),Sa=wa(),jw=[$w.map,Mw.seq,Dw.string,Lw.nullTag,Bw.boolTag,Sa.intOct,Sa.int,Sa.intHex,va.floatNaN,va.floatExp,va.float];Md.schema=jw});var Fd=E(jd=>{"use strict";var Fw=G(),qw=tr(),Uw=rr();function Bd(r){return typeof r=="bigint"||Number.isInteger(r)}var _s=({value:r})=>JSON.stringify(r),Jw=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:_s},{identify:r=>r==null,createNode:()=>new Fw.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:_s},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:_s},{identify:Bd,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})=>Bd(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:_s}],Kw={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Hw=[qw.map,Uw.seq].concat(Jw,Kw);jd.schema=Hw});var ka=E(qd=>{"use strict";var Zr=Gn("buffer"),xa=G(),Ww=Yr(),Yw={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=xa.Scalar.BLOCK_LITERAL),e!==xa.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===xa.Scalar.BLOCK_LITERAL?`
|
|
69
|
+
`:" ")}return Ww.stringifyString({comment:r,type:e,value:a},n,s,i)}};qd.binary=Yw});var Ns=E(Rs=>{"use strict";var Cs=j(),Ea=nt(),Vw=G(),Gw=ot();function Ud(r,e){if(Cs.isSeq(r))for(let t=0;t<r.items.length;++t){let n=r.items[t];if(!Cs.isPair(n)){if(Cs.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let s=n.items[0]||new Ea.Pair(new Vw.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 ka.Pair(n)}}else e("Expected a sequence for this tag");return r}function Ud(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:qd,createNode:Ud};Rs.createPairs=Ud;Rs.pairs=Gw;Rs.resolvePairs=qd});var Ta=E(Aa=>{"use strict";var Jd=j(),Ea=Qe(),en=st(),zw=it(),Kd=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(Jd.isPair(s)?(i=Ea.toJS(s.key,"",t),o=Ea.toJS(s.value,i,t)):i=Ea.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=Kd.createPairs(e,t,n),i=new this;return i.items=s.items,i}};Et.tag="tag:yaml.org,2002:omap";var Xw={collection:"seq",identify:r=>r instanceof Map,nodeClass:Et,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Kd.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Jd.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)};Aa.YAMLOMap=Et;Aa.omap=Xw});var Gd=E(Pa=>{"use strict";var Hd=G();function Wd({value:r,source:e},t){return e&&(r?Yd:Vd).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Yd={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 Hd.Scalar(!0),stringify:Wd},Vd={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 Hd.Scalar(!1),stringify:Wd};Pa.falseTag=Vd;Pa.trueTag=Yd});var zd=E(Is=>{"use strict";var Qw=G(),Oa=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:Oa.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():Oa.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 Qw.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:Oa.stringifyNumber};Is.float=tv;Is.floatExp=ev;Is.floatNaN=Zw});var Qd=E(rn=>{"use strict";var Xd=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 _a(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 Xd.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=>_a(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=>_a(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:Xd.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=>_a(r,16,"0x")};rn.int=sv;rn.intBin=rv;rn.intHex=iv;rn.intOct=nv});var Ra=E(Ca=>{"use strict";var Ds=j(),Ls=rt(),Ms=st(),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 Ia=E(Bs=>{"use strict";var av=rr();function Na(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 Zd(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})=>Na(r,t),stringify:Zd},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=>Na(r,!1),stringify:Zd},ef={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(ef.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=Na(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=ef});var nf=E(rf=>{"use strict";var uv=er(),dv=As(),fv=tr(),pv=Qr(),mv=xa(),tf=Gd(),$a=zd(),js=Qd(),hv=ys(),gv=Ta(),yv=Ns(),bv=Ra(),La=Ia(),wv=[uv.map,fv.seq,pv.string,dv.nullTag,tf.trueTag,tf.falseTag,js.intBin,js.intOct,js.int,js.intHex,$a.floatNaN,$a.floatExp,$a.float,mv.binary,hv.merge,gv.omap,yv.pairs,bv.set,La.intTime,La.floatTime,La.timestamp];rf.schema=wv});var mf=E(Ba=>{"use strict";var cf=er(),vv=As(),lf=tr(),Sv=Qr(),xv=ma(),Ma=ga(),Da=ba(),kv=Md(),Ev=jd(),uf=xa(),nn=ys(),df=Ta(),ff=Ns(),sf=nf(),pf=Ra(),Fs=Ia(),of=new Map([["core",kv.schema],["failsafe",[cf.map,lf.seq,Sv.string]],["json",Ev.schema],["yaml11",sf.schema],["yaml-1.1",sf.schema]]),af={binary:uf.binary,bool:xv.boolTag,float:Ma.float,floatExp:Ma.floatExp,floatNaN:Ma.floatNaN,floatTime:Fs.floatTime,int:Da.int,intHex:Da.intHex,intOct:Da.intOct,intTime:Fs.intTime,map:cf.map,merge:nn.merge,null:vv.nullTag,omap:df.omap,pairs:ff.pairs,seq:lf.seq,set:pf.set,timestamp:Fs.timestamp},Av={"tag:yaml.org,2002:binary":uf.binary,"tag:yaml.org,2002:merge":nn.merge,"tag:yaml.org,2002:omap":df.omap,"tag:yaml.org,2002:pairs":ff.pairs,"tag:yaml.org,2002:set":pf.set,"tag:yaml.org,2002:timestamp":Fs.timestamp};function Tv(r,e,t){let n=of.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(of.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"?af[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(af).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},[])}Ba.coreKnownTags=Av;Ba.getTags=Tv});var qa=E(hf=>{"use strict";var ja=j(),Pv=er(),Ov=tr(),_v=Qr(),qs=mf(),Cv=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,Fa=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,ja.MAP,{value:Pv.map}),Object.defineProperty(this,ja.SCALAR,{value:_v.string}),Object.defineProperty(this,ja.SEQ,{value:Ov.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Cv:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};hf.Schema=Fa});var yf=E(gf=>{"use strict";var Rv=j(),Ua=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=Ua.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=Ua.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(Ua.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]=Cs.isPair(n)?n:new Ea.Pair(n)}}else e("Expected a sequence for this tag");return r}function Jd(r,e,t){let{replacer:n}=t,s=new Gw.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(Ea.createPair(a,c,t))}return s}var zw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ud,createNode:Jd};Rs.createPairs=Jd;Rs.pairs=zw;Rs.resolvePairs=Ud});var Pa=E(Ta=>{"use strict";var Kd=j(),Aa=Ze(),en=it(),Xw=ot(),Hd=Ns(),At=class r extends Xw.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(Kd.isPair(s)?(i=Aa.toJS(s.key,"",t),o=Aa.toJS(s.value,i,t)):i=Aa.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=Hd.createPairs(e,t,n),i=new this;return i.items=s.items,i}};At.tag="tag:yaml.org,2002:omap";var Qw={collection:"seq",identify:r=>r instanceof Map,nodeClass:At,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Hd.resolvePairs(r,e),n=[];for(let{key:s}of t.items)Kd.isScalar(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new At,t)},createNode:(r,e,t)=>At.from(r,e,t)};Ta.YAMLOMap=At;Ta.omap=Qw});var zd=E(Oa=>{"use strict";var Wd=G();function Yd({value:r,source:e},t){return e&&(r?Vd:Gd).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Vd={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 Wd.Scalar(!0),stringify:Yd},Gd={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 Wd.Scalar(!1),stringify:Yd};Oa.falseTag=Gd;Oa.trueTag=Vd});var Xd=E(Is=>{"use strict";var Zw=G(),_a=nr(),ev={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:_a.stringifyNumber},tv={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():_a.stringifyNumber(r)}},rv={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 Zw.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:_a.stringifyNumber};Is.float=rv;Is.floatExp=tv;Is.floatNaN=ev});var Zd=E(rn=>{"use strict";var Qd=nr(),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 Ca(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 Qd.stringifyNumber(r)}var nv={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=>Ca(r,2,"0b")},sv={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=>Ca(r,8,"0")},iv={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:Qd.stringifyNumber},ov={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=>Ca(r,16,"0x")};rn.int=iv;rn.intBin=nv;rn.intHex=ov;rn.intOct=sv});var Na=E(Ra=>{"use strict";var Ds=j(),Ls=nt(),Ms=it(),Tt=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}};Tt.tag="tag:yaml.org,2002:set";var av={collection:"map",identify:r=>r instanceof Set,nodeClass:Tt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>Tt.from(r,e,t),resolve(r,e){if(Ds.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new Tt,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};Ra.YAMLSet=Tt;Ra.set=av});var $a=E(Bs=>{"use strict";var cv=nr();function Ia(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,s=o=>e?BigInt(o):Number(o),i=n.replace(/_/g,"").split(":").reduce((o,a)=>o*s(60)+s(a),s(0));return t==="-"?s(-1)*i:i}function ef(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return cv.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 lv={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})=>Ia(r,t),stringify:ef},uv={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=>Ia(r,!1),stringify:ef},tf={identify:r=>r instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(r){let e=r.match(tf.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,s,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,s,i||0,o||0,a||0,c),f=e[8];if(f&&f!=="Z"){let u=Ia(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=uv;Bs.intTime=lv;Bs.timestamp=tf});var sf=E(nf=>{"use strict";var dv=tr(),fv=As(),pv=rr(),mv=Qr(),hv=ka(),rf=zd(),La=Xd(),js=Zd(),gv=ys(),yv=Pa(),bv=Ns(),wv=Na(),Ma=$a(),vv=[dv.map,pv.seq,mv.string,fv.nullTag,rf.trueTag,rf.falseTag,js.intBin,js.intOct,js.int,js.intHex,La.floatNaN,La.floatExp,La.float,hv.binary,gv.merge,yv.omap,bv.pairs,wv.set,Ma.intTime,Ma.floatTime,Ma.timestamp];nf.schema=vv});var hf=E(ja=>{"use strict";var lf=tr(),Sv=As(),uf=rr(),xv=Qr(),kv=ha(),Da=ya(),Ba=wa(),Ev=Dd(),Av=Fd(),df=ka(),nn=ys(),ff=Pa(),pf=Ns(),of=sf(),mf=Na(),Fs=$a(),af=new Map([["core",Ev.schema],["failsafe",[lf.map,uf.seq,xv.string]],["json",Av.schema],["yaml11",of.schema],["yaml-1.1",of.schema]]),cf={binary:df.binary,bool:kv.boolTag,float:Da.float,floatExp:Da.floatExp,floatNaN:Da.floatNaN,floatTime:Fs.floatTime,int:Ba.int,intHex:Ba.intHex,intOct:Ba.intOct,intTime:Fs.intTime,map:lf.map,merge:nn.merge,null:Sv.nullTag,omap:ff.omap,pairs:pf.pairs,seq:uf.seq,set:mf.set,timestamp:Fs.timestamp},Tv={"tag:yaml.org,2002:binary":df.binary,"tag:yaml.org,2002:merge":nn.merge,"tag:yaml.org,2002:omap":ff.omap,"tag:yaml.org,2002:pairs":pf.pairs,"tag:yaml.org,2002:set":mf.set,"tag:yaml.org,2002:timestamp":Fs.timestamp};function Pv(r,e,t){let n=af.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(af.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(r))for(let i of r)s=s.concat(i);else typeof r=="function"&&(s=r(s.slice()));return t&&(s=s.concat(nn.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?cf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(cf).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}ja.coreKnownTags=Tv;ja.getTags=Pv});var Ua=E(gf=>{"use strict";var Fa=j(),Ov=tr(),_v=rr(),Cv=Qr(),qs=hf(),Rv=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,qa=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,Fa.MAP,{value:Ov.map}),Object.defineProperty(this,Fa.SCALAR,{value:Cv.string}),Object.defineProperty(this,Fa.SEQ,{value:_v.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Rv:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};gf.Schema=qa});var bf=E(yf=>{"use strict";var Nv=j(),Ja=Vr(),sn=Kr();function Iv(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=Ja.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(Nv.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=Ja.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(Ja.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
|
+
`}yf.stringifyDocument=Iv});var on=E(wf=>{"use strict";var $v=Ur(),sr=cs(),pe=j(),Lv=nt(),Mv=Ze(),Dv=Ua(),Bv=bf(),Ka=ss(),jv=Vo(),Fv=Jr(),Ha=Yo(),Wa=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 Ha.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){ir(this.contents)&&this.contents.add(e)}addIn(e,t){ir(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=Ka.anchorNames(this);e.anchor=!t||n.has(t)?Ka.findNewAnchor(t||"a",n):t}return new $v.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=k=>typeof k=="number"||k instanceof String||k instanceof Number,x=t.filter(b).map(String);x.length>0&&(t=t.concat(x)),s=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=Ka.createNodeAnchors(this,o||"a"),y={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},m=Fv.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 Lv.Pair(s,i)}delete(e){return ir(this.contents)?this.contents.delete(e):!1}deleteIn(e){return sr.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):ir(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 sr.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 sr.isEmptyPath(e)?this.contents!==void 0:pe.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=sr.collectionFromPath(this.schema,[e],t):ir(this.contents)&&this.contents.set(e,t)}setIn(e,t){sr.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=sr.collectionFromPath(this.schema,Array.from(e),t):ir(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 Ha.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 Ha.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 Dv.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=Mv.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"?jv.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 Bv.stringifyDocument(this,e)}};function ir(r){if(pe.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}wf.Document=Wa});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}},Ya=class extends an{constructor(e,t,n){super("YAMLParseError",e,t,n)}},Va=class extends an{constructor(e,t,n){super("YAMLWarning",e,t,n)}},qv=(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:k.comment=T.comment);let P=new
|
|
83
|
-
`+
|
|
84
|
-
`+N:h.comment=N,
|
|
85
|
-
`+
|
|
86
|
-
`+b.comment:l.comment=b.comment),l.range=[n.offset,m,b.offset]}else l.range=[n.offset,m,m];return l}
|
|
79
|
+
`}};cn.YAMLError=an;cn.YAMLParseError=Ya;cn.YAMLWarning=Va;cn.prettifyError=qv});var un=E(vf=>{"use strict";function Uv(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,x=null,k=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 v=h.source.substring(1)||" ";u?u+=d+v:u=v,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||x)&&(k=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":{x&&i(h,"MULTIPLE_TAGS","A node can have at most one tag"),x=h,C??(C=h.offset),l=!1,f=!1,y=!0;break}case t:(b||x)&&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 _=r[r.length-1],N=_?_.offset+_.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:x,newlineAfterProp:k,end:N,start:C??N}}vf.resolveProps=Uv});var Us=E(Sf=>{"use strict";function Ga(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(Ga(e.key)||Ga(e.value))return!0}return!1;default:return!0}}Sf.containsNewline=Ga});var za=E(xf=>{"use strict";var Jv=Us();function Kv(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&Jv.containsNewline(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}xf.flowIndentCheck=Kv});var Xa=E(Ef=>{"use strict";var kf=j();function Hv(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(i,o)=>i===o||kf.isScalar(i)&&kf.isScalar(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}Ef.mapIncludes=Hv});var Cf=E(_f=>{"use strict";var Af=nt(),Wv=it(),Tf=un(),Yv=Us(),Pf=za(),Vv=Xa(),Of="All mapping items must start at the same column";function Gv({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??Wv.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=Tf.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",Of)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=`
|
|
81
|
+
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||Yv.containsNewline(d))&&s(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==n.indent&&s(c,"BAD_INDENT",Of);t.atKey=!0;let x=m.end,k=d?r(t,d,m,s):e(t,x,u,null,m,s);t.schema.compat&&Pf.flowIndentCheck(n.indent,d,s),t.atKey=!1,Vv.mapIncludes(t,a.items,k)&&s(x,"DUPLICATE_KEY","Map keys must be unique");let T=Tf.resolveProps(p??[],{indicator:"map-value-ind",next:y,offset:k.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(k.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&&Pf.flowIndentCheck(n.indent,y,s),c=P.range[2];let C=new Af.Pair(k,P);t.options.keepSourceTokens&&(C.srcToken=f),a.items.push(C)}else{b&&s(k.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),T.comment&&(k.comment?k.comment+=`
|
|
82
|
+
`+T.comment:k.comment=T.comment);let P=new Af.Pair(k);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}_f.resolveBlockMap=Gv});var Nf=E(Rf=>{"use strict";var zv=ot(),Xv=un(),Qv=za();function Zv({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=i?.nodeClass??zv.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=Xv.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}Rf.resolveBlockSeq=Zv});var or=E(If=>{"use strict";function eS(r,e,t,n){let s="";if(r){let i=!1,o="";for(let a of r){let{source:c,type:l}=a;switch(l){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";s?s+=o+f:s=f,o="";break}case"newline":s&&(o+=c),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:s,offset:e}}If.resolveEnd=eS});var Df=E(Mf=>{"use strict";var tS=j(),rS=nt(),$f=it(),nS=ot(),sS=or(),Lf=un(),iS=Us(),oS=Xa(),Qa="Block collections are not allowed within flow collections",Za=r=>r&&(r.type==="block-map"||r.type==="block-seq");function aS({composeNode:r,composeEmptyNode:e},t,n,s,i){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?$f.YAMLMap:nS.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 x=n.items[b],{start:k,key:T,sep:P,value:C}=x,_=Lf.resolveProps(k,{flow:a,indicator:"explicit-key-ind",next:T??P?.[0],offset:u,onError:s,parentIndent:n.indent,startOnNewline:!1});if(!_.found){if(!_.anchor&&!_.tag&&!P&&!C){b===0&&_.comma?s(_.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):b<n.items.length-1&&s(_.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),_.comment&&(l.comment?l.comment+=`
|
|
83
|
+
`+_.comment:l.comment=_.comment),u=_.end;continue}!o&&t.options.strict&&iS.containsNewline(T)&&s(T,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(b===0)_.comma&&s(_.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(_.comma||s(_.start,"MISSING_CHAR",`Missing , between ${a} items`),_.comment){let N="";e:for(let h of k)switch(h.type){case"comma":case"space":break;case"comment":N=h.source.substring(1);break e;default:break e}if(N){let h=l.items[l.items.length-1];tS.isPair(h)&&(h=h.value??h.key),h.comment?h.comment+=`
|
|
84
|
+
`+N:h.comment=N,_.comment=_.comment.substring(N.length+1)}}if(!o&&!P&&!_.found){let N=C?r(t,C,_,s):e(t,_.end,P,null,_,s);l.items.push(N),u=N.range[2],Za(C)&&s(N.range,"BLOCK_IN_FLOW",Qa)}else{t.atKey=!0;let N=_.end,h=T?r(t,T,_,s):e(t,N,k,null,_,s);Za(T)&&s(h.range,"BLOCK_IN_FLOW",Qa),t.atKey=!1;let v=Lf.resolveProps(P??[],{flow:a,indicator:"map-value-ind",next:C,offset:h.range[2],onError:s,parentIndent:n.indent,startOnNewline:!1});if(v.found){if(!o&&!_.found&&t.options.strict){if(P)for(let R of P){if(R===v.found)break;if(R.type==="newline"){s(R,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}_.start<v.found.offset-1024&&s(v.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(v.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let I=C?r(t,C,v,s):v.found?e(t,v.end,P,null,v,s):null;I?Za(C)&&s(I.range,"BLOCK_IN_FLOW",Qa):v.comment&&(h.comment?h.comment+=`
|
|
85
|
+
`+v.comment:h.comment=v.comment);let L=new rS.Pair(h,I);if(t.options.keepSourceTokens&&(L.srcToken=x),o){let R=l;oS.mapIncludes(t,R.items,h)&&s(N,"DUPLICATE_KEY","Map keys must be unique"),R.items.push(L)}else{let R=new $f.YAMLMap(t.schema);R.flow=!0,R.items.push(L);let K=(I??h).range;R.range=[h.range[0],K[1],K[2]],l.items.push(R)}u=I?I.range[2]:v.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),x=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",x),p&&p.source.length!==1&&y.unshift(p)}if(y.length>0){let b=sS.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}Mf.resolveFlowCollection=aS});var jf=E(Bf=>{"use strict";var cS=j(),lS=G(),uS=it(),dS=ot(),fS=Cf(),pS=Nf(),mS=Df();function ec(r,e,t,n,s,i){let o=t.type==="block-map"?fS.resolveBlockMap(r,e,t,n,i):t.type==="block-seq"?pS.resolveBlockSeq(r,e,t,n,i):mS.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 hS(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===uS.YAMLMap.tagName&&a==="map"||o===dS.YAMLSeq.tagName&&a==="seq")return ec(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),ec(r,e,t,s,o)}let l=ec(r,e,t,s,o,c),f=c.resolve?.(l,d=>s(i,"TAG_RESOLVE_FAILED",d),e.options)??l,u=cS.isNode(f)?f:new lS.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Bf.composeCollection=hS});var rc=E(Ff=>{"use strict";var tc=G();function gS(r,e,t){let n=e.offset,s=yS(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?tc.Scalar.BLOCK_FOLDED:tc.Scalar.BLOCK_LITERAL,o=e.source?bS(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
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,x]=o[m];if(x===""||x==="\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+x.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,x]=o[m];l+=b.length+x.length+1;let k=x[x.length-1]==="\r";if(k&&(x=x.slice(0,-1)),x&&b.length<c){let P=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;t(l-x.length-(k?2:1),"BAD_INDENT",P),b=""}i===
|
|
88
|
+
`;for(let m=f;m<a;++m){let[b,x]=o[m];l+=b.length+x.length+1;let k=x[x.length-1]==="\r";if(k&&(x=x.slice(0,-1)),x&&b.length<c){let P=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;t(l-x.length-(k?2:1),"BAD_INDENT",P),b=""}i===tc.Scalar.BLOCK_LITERAL?(u+=d+b.slice(c)+x,d=`
|
|
89
89
|
`):b.length>c||x[0]===" "?(d===" "?d=`
|
|
90
90
|
`:!p&&d===`
|
|
91
91
|
`&&(d=`
|
|
@@ -98,46 +98,46 @@ ${l}
|
|
|
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 yS({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 bS(r){let e=r.split(/\n( *)/),t=e[0],n=t.match(/^( *)/),i=[n?.[1]?[n[1],t.slice(n[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)i.push([e[o],e[o+1]]);return i}Ff.resolveBlockScalar=gS});var sc=E(Uf=>{"use strict";var nc=G(),wS=or();function vS(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=nc.Scalar.PLAIN,c=SS(i,l);break;case"single-quoted-scalar":a=nc.Scalar.QUOTE_SINGLE,c=xS(i,l);break;case"double-quoted-scalar":a=nc.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=wS.resolveEnd(o,f,e,t);return{value:c,type:a,comment:u.comment,range:[n,f,u.offset]}}function SS(r,e){let t="";switch(r[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),qf(r)}function xS(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),qf(r.slice(1,-1)).replace(/''/g,"'")}function qf(r){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
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}=ES(r,n);t+=i,n=o}else if(s==="\\"){let i=r[++n],o=AS[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+=TS(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 ES(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 AS={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 TS(r,e,t,n){let s=r.substr(e,t),o=s.length===t&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;if(isNaN(o)){let a=r.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}Uf.resolveFlowScalar=vS});var Hf=E(Kf=>{"use strict";var Pt=j(),Jf=G(),PS=rc(),OS=sc();function _S(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?PS.resolveBlockScalar(r,e,n):OS.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[Pt.SCALAR]:c?l=CS(r.schema,s,c,t,n):e.type==="scalar"?l=RS(r,s,e,n):l=r.schema[Pt.SCALAR];let f;try{let u=l.resolve(s,d=>n(t??e,"TAG_RESOLVE_FAILED",d),r.options);f=Pt.isScalar(u)?u:new Jf.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);n(t??e,"TAG_RESOLVE_FAILED",d),f=new Jf.Scalar(s)}return f.range=a,f.source=s,i&&(f.type=i),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function CS(r,e,t,n,s){if(t==="!")return r[Pt.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[Pt.SCALAR])}function RS({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[Pt.SCALAR];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[Pt.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;i(s,"TAG_RESOLVE_FAILED",f,!0)}}return o}Kf.composeScalar=_S});var Yf=E(Wf=>{"use strict";function NS(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}Wf.emptyScalarPosition=NS});var zf=E(oc=>{"use strict";var IS=Ur(),$S=j(),LS=jf(),Vf=Hf(),MS=or(),DS=Yf(),BS={composeNode:Gf,composeEmptyNode:ic};function Gf(r,e,t,n){let s=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=t,l,f=!0;switch(e.type){case"alias":l=jS(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=Vf.composeScalar(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":l=LS.composeCollection(BS,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=ic(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&&(!$S.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 ic(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:DS.emptyScalarPosition(e,t,n),indent:-1,source:""},u=Vf.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 jS({options:r},{offset:e,source:t,end:n},s){let i=new IS.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=MS.resolveEnd(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}oc.composeEmptyNode=ic;oc.composeNode=Gf});var Zf=E(Qf=>{"use strict";var FS=on(),Xf=zf(),qS=or(),US=un();function JS(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new FS.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=US.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?Xf.composeNode(l,s,f,o):Xf.composeEmptyNode(l,f.end,n,null,f,o);let u=c.contents.range[2],d=qS.resolveEnd(i,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[t,u,d.offset],c}Qf.composeDoc=JS});var cc=E(rp=>{"use strict";var KS=Gn("process"),HS=Yo(),WS=on(),dn=ln(),ep=j(),YS=Zf(),VS=or();function fn(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 tp(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 ac=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,s,i)=>{let o=fn(t);i?this.warnings.push(new dn.YAMLWarning(o,n,s)):this.errors.push(new dn.YAMLParseError(o,n,s))},this.directives=new HS.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=tp(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(ep.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];ep.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 dn.YAMLParseError(fn(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:tp(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(KS.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,n,s)=>{let i=fn(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=YS.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 dn.YAMLParseError(fn(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 dn.YAMLParseError(fn(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=VS.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 dn.YAMLParseError(fn(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 WS.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}}};rp.Composer=ac});var ip=E(Js=>{"use strict";var GS=rc(),zS=sc(),XS=ln(),np=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 XS.YAMLParseError([a,a+1],i,o)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return zS.resolveFlowScalar(r,e,n);case"block-scalar":return GS.resolveBlockScalar({options:{strict:e}},r,n)}}return null}function ZS(r,e){let{implicitKey:t=!1,indent:n,inFlow:s=!1,offset:i=-1,type:o="PLAIN"}=e,a=np.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
125
|
`),f=a.substring(0,l),u=a.substring(l+1)+`
|
|
126
|
-
`,d=[{type:"block-scalar-header",offset:i,indent:n,source:f}];return
|
|
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
|
|
126
|
+
`,d=[{type:"block-scalar-header",offset:i,indent:n,source:f}];return sp(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 ex(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=np.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">":tx(r,c);break;case'"':lc(r,c,"double-quoted-scalar");break;case"'":lc(r,c,"single-quoted-scalar");break;default:lc(r,c,"scalar")}}function tx(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})}}}Js.createScalarToken=
|
|
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}];sp(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 sp(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 lc(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=ZS;Js.resolveAsScalar=QS;Js.setScalarValue=ex});var ap=E(op=>{"use strict";var rx=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}op.stringify=rx});var dp=E(up=>{"use strict";var uc=Symbol("break visit"),nx=Symbol("skip children"),cp=Symbol("remove item");function Ot(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),lp(Object.freeze([]),r,e)}Ot.BREAK=uc;Ot.SKIP=nx;Ot.REMOVE=cp;Ot.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};Ot.parentCollection=(r,e)=>{let t=Ot.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 lp(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=lp(Object.freeze(r.concat([[s,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===uc)return uc;a===cp&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&s==="key"&&(n=n(e,r))}}return typeof n=="function"?n(e,r):n}up.visit=Ot});var Ws=E(ce=>{"use strict";var dc=ip(),sx=ap(),ix=dp(),fc="\uFEFF",pc="",mc="",hc="",ox=r=>!!r&&"items"in r,ax=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar");function cx(r){switch(r){case fc:return"<BOM>";case pc:return"<DOC>";case mc:return"<FLOW_END>";case hc:return"<SCALAR>";default:return JSON.stringify(r)}}function lx(r){switch(r){case fc:return"byte-order-mark";case pc:return"doc-mode";case mc:return"flow-error-end";case hc: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}ce.createScalarToken=
|
|
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}ce.createScalarToken=dc.createScalarToken;ce.resolveAsScalar=dc.resolveAsScalar;ce.setScalarValue=dc.setScalarValue;ce.stringify=sx.stringify;ce.visit=ix.visit;ce.BOM=fc;ce.DOCUMENT=pc;ce.FLOW_END=mc;ce.SCALAR=hc;ce.isCollection=ox;ce.isScalar=ax;ce.prettyToken=cx;ce.tokenType=lx});var bc=E(pp=>{"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 fp=new Set("0123456789ABCDEFabcdef"),ux=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ys=new Set(",[]{}"),dx=new Set(` ,[]{}
|
|
135
|
+
\r `),gc=r=>!r||dx.has(r),yc=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(gc),"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(gc),"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===`
|
|
@@ -147,23 +147,23 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
147
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
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(
|
|
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(gc))+(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(ux.has(t))t=this.buffer[++e];else if(t==="%"&&fp.has(this.buffer[e+1])&&fp.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)}};pp.Lexer=yc});var vc=E(mp=>{"use strict";var wc=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}}}};mp.LineCounter=wc});var xc=E(wp=>{"use strict";var fx=Gn("process"),hp=Ws(),px=bc();function at(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function gp(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 bp(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 ar(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 yp(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!at(e.start,"explicit-key-ind")&&!at(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,bp(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 Sc=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 px.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,fx.env.LOG_TOKENS&&console.log("|",hp.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=hp.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"&&yp(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&&gp(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":{gp(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=ar(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(
|
|
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(at(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(bp(t.key)&&!at(t.sep,"newline")){let o=ar(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(at(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=ar(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]}):at(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&&!at(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||at(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=ar(s);yp(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=Vs(e),n=
|
|
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=ar(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=ar(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())}}};wp.Parser=Sc});var Ep=E(hn=>{"use strict";var vp=cc(),mx=on(),mn=ln(),hx=oa(),gx=j(),yx=vc(),Sp=xc();function xp(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new yx.LineCounter||null,prettyErrors:e}}function bx(r,e={}){let{lineCounter:t,prettyErrors:n}=xp(e),s=new Sp.Parser(t?.addNewLine),i=new vp.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 kp(r,e={}){let{lineCounter:t,prettyErrors:n}=xp(e),s=new Sp.Parser(t?.addNewLine),i=new vp.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 wx(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=kp(r,t);if(!s)return null;if(s.warnings.forEach(i=>hx.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 vx(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 gx.isDocument(r)&&!n?r.toString(t):new mx.Document(r,n,t).toString(t)}hn.parse=wx;hn.parseAllDocuments=bx;hn.parseDocument=kp;hn.stringify=vx});var Tp=E(F=>{"use strict";var Sx=cc(),xx=on(),kx=Ua(),kc=ln(),Ex=Ur(),ct=j(),Ax=nt(),Tx=G(),Px=it(),Ox=ot(),_x=Ws(),Cx=bc(),Rx=vc(),Nx=xc(),Gs=Ep(),Ap=Br();F.Composer=Sx.Composer;F.Document=xx.Document;F.Schema=kx.Schema;F.YAMLError=kc.YAMLError;F.YAMLParseError=kc.YAMLParseError;F.YAMLWarning=kc.YAMLWarning;F.Alias=Ex.Alias;F.isAlias=ct.isAlias;F.isCollection=ct.isCollection;F.isDocument=ct.isDocument;F.isMap=ct.isMap;F.isNode=ct.isNode;F.isPair=ct.isPair;F.isScalar=ct.isScalar;F.isSeq=ct.isSeq;F.Pair=Ax.Pair;F.Scalar=Tx.Scalar;F.YAMLMap=Px.YAMLMap;F.YAMLSeq=Ox.YAMLSeq;F.CST=_x;F.Lexer=Cx.Lexer;F.LineCounter=Rx.LineCounter;F.Parser=Nx.Parser;F.parse=Gs.parse;F.parseAllDocuments=Gs.parseAllDocuments;F.parseDocument=Gs.parseDocument;F.stringify=Gs.stringify;F.visit=Ap.visit;F.visitAsync=Ap.visitAsync});function $x(r){try{return JSON.parse(r.trim()),!0}catch{return!1}}function Lx(r){let e=r.trim();if(!e.startsWith("<"))return!1;let t=e.match(Ix);return t?Dr(e,t[1])!==null:!1}function Mx(r){let e=r.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=Pp.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function Op(r){return $x(r)||Lx(r)||Mx(r)}var Pp,Ix,Ec=A(()=>{Du();Pp=Ky(Tp(),1),Ix=/<([a-zA-Z_][\w.-]*)/});function Dx(r){if(!r?.trim())return[];let e=r.replace(/\r\n/g,`
|
|
157
|
+
`),t=e.trim();if(Op(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 zs(r){return
|
|
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 Dx(r).map(e=>e.text)}var _p,Cp=A(()=>{Ec();_p=`
|
|
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 Ue=A(()=>{zn();Do();_u();Cu();Ec();Cp();Xn()});function cr(r){return{...Au(r),server:r.files.get("server.ts")??""}}function Xs(r){return!!r.server&&!r.code}var gn=A(()=>{Ue();Ue()});function qx(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 Rp(r){let e=[];for(let s of Fx)for(let i of r.matchAll(s)){let o=qx(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 Np(r){return Rp(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 jx)l.targets.includes(t)&&l.pattern.test(a)&&s.push({type:l.type,severity:"error",message:Kx(l.type,c),lineNumber:c,lineContent:a})}return t==="client"&&n&&s.push(...Ux(i,n)),s}function Ux(r,e){let t=new Set(Object.keys(e));return Rp(r.join(`
|
|
166
|
+
`)).filter(({root:n})=>!t.has(n)).map(({root:n,lineIndex:s})=>({type:"UNDECLARED_IMPORT",severity:"error",message:Jx(n,s+1),lineNumber:s+1,lineContent:r[s]}))}function Jx(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 Kx(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
|
|
334
|
+
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var _t,Ct,jx,Fx,Qs=A(()=>{_t=["client"],Ct=["client","server"],jx=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:_t},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:Ct},{type:"JS_EXTENSION_IMPORT",pattern:/from\s+['"][^'"]*\/[^'"]*\.js['"]/,targets:_t},{type:"URL_IMPORT",pattern:/from\s+['"]https?:\/\//,targets:_t},{type:"VERSION_SPECIFIER_IMPORT",pattern:/from\s+['"][^'"]*@[\d^~]/,targets:_t},{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:_t},{type:"NAVIGATION",pattern:/window\.(location\.(reload|assign|replace)\s*\(|open\s*\()/,targets:_t},{type:"NAVIGATION",pattern:/window\.location(\.href)?\s*=[^=]/,targets:_t}],Fx=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});var Zp=A(()=>{});var de,xe,fr=A(()=>{de=class extends Error{constructor(e,t="unknown",n=!1){super(e),this.code=t,this.retryable=n}},xe=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 de(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 de(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,
|
|
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 de(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 de(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,Nc=A(()=>{fr();pi=class extends xe{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 de(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 pr,mi=A(()=>{fr();pr=class extends xe{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,Ic=A(()=>{mi();hi=class extends pr{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,$c=A(()=>{fr();gi=class extends xe{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 yi
|
|
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,Lc=A(()=>{fr();yi=class extends xe{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
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 de(`Prompt blocked: ${t}`)}}}});var bi,
|
|
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 de(`Prompt blocked: ${t}`)}}}});var bi,Mc=A(()=>{mi();bi=class extends pr{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 Lt(r){let e=mk.get(r);if(!e)throw new Error(`Unsupported protocol: ${r}`);return e}function hk(r,e){return r.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function Dc(r,e){let t=Lt(r.protocol),n=t.getPath(r.model,e.stream),s=hk(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 gk(r){return/prompt is too long|context[_ ](length|window)|maximum context|token count exceeds|too many tokens/i.test(r)}async function mr(r,e){let t=Lt(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||gk(s))&&(o="context_exceeded"),{code:o,message:s,retryable:i===429||i>=500}}var em,mk,Bc=A(()=>{Nc();Ic();$c();Lc();Mc();em=new bi,mk=new Map([["openai",new pi],["openrouter",new hi],["anthropic",new gi],["gemini",new yi],["ollama",em],["openai-compat",em]])});function tm(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 jc(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*rm(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=jc(s);u!==null&&u!=="done"&&(yield u)}return}t?.(),s+=n.decode(c,{stream:!0});let{pos:l,len:f}=tm(s);for(;l!==-1;){let u=s.slice(0,l);s=s.slice(l+f);let d=jc(u);if(d==="done")return;d!==null&&(yield d),{pos:l,len:f}=tm(s)}}}finally{i&&e?.removeEventListener("abort",i);try{await r.cancel()}catch{}}}async function Mt(r,e){if(!r.body)throw new Error("Response body is missing");let t="";for await(let n of Dt(r,e))n.kind==="text"&&(t+=n.text);return t}async function*Dt(r,e){let t=e??(r.headers.get("X-Provider-Protocol")||"openai"),n=Lt(t);if(!r.body)return;let s=r.body.getReader();for await(let i of rm(s)){let o=n.parseStreamChunk(i);o?.reasoning&&(yield{kind:"reasoning",text:o.reasoning}),o?.text&&(yield{kind:"text",text:o.text})}}var nm=A(()=>{Bc()});import{strToU8 as yk,strFromU8 as bk,deflateSync as wk,inflateSync as vk}from"fflate";function qc(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
|
|
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?"":Ce(JSON.stringify(r))}function
|
|
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":
|
|
366
|
+
`)}function An(r){try{return JSON.parse(r)}catch{return null}}function xk(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 kk(r){let e=xk(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 Ek(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 Ak(r){let e=null,t=0;for(;t<r.length;){let n=r[t];if(n==="{"||n==="["){let s=Ek(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 Uc(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 Sk){let c=a(t);if(c!==null){let l=An(c);if(l!==null)return{parsed:l,json:c,fixesApplied:[...e,o]}}}let i=Ak(r);return i!==null?{...i,fixesApplied:[...e,"extracted last JSON value"]}:{parsed:null,json:t,fixesApplied:e}}function Jc(r){try{let e={i:r.insight,d:r.data},t=JSON.stringify(e),n=wk(yk(t),{level:9}),s=Pk(n),i=`${sm}:${s}`;return i.length>Tk?"":"#"+Fc+i}catch{return""}}function Kc(r){try{let e=r.startsWith("#")?r.slice(1):r;if(!e.startsWith(Fc))return null;let t=e.slice(Fc.length),n=t.indexOf(":");if(n===-1||t.slice(0,n)!==sm)return null;let s=Ok(t.slice(n+1)),i=JSON.parse(bk(vk(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 Pk(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 Ok(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 Sk,Fc,sm,Tk,im=A(()=>{Sk=[["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",kk]];Fc="tb=",sm="1",Tk=6e4});var hr=A(()=>{Zp();fr();Bc();nm();im();mi();$c();Lc();Nc();Ic();Mc()});function yr(r){return(r.includes("://")?r:`http://${r}`).replace(/\/+$/,"")}function Hc(){return Pn}async function He(){let[r,e]=await Promise.all([am(),$k()]);return Ik([...Lk(e),...r],process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL)}function Ik(r,e,t){return!e||!t?r:r.map(n=>n.provider===e&&n.name===t?{...n,default:!0}:n)}async function om(){let r;try{r=await fetch(_k,{signal:AbortSignal.timeout(Rk)})}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 $k(){if(Tn&&Date.now()-Tn.fetchedAt<=Ck)return Tn.models;let r=await om()??await om();return r?(Tn={models:r,fetchedAt:Date.now()},Pn=null,r):Tn?.models??[]}async function am(){if(wi&&Date.now()-wi.fetchedAt<=Nk)return wi.models;let r=yr(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 Lk(r){let e=new Set(Object.entries(gr).filter(([,t])=>!!process.env[t]).map(([t])=>t));return r.filter(t=>e.has(t.provider))}function Wc(){return Object.values(gr).some(r=>!!process.env[r])}async function vi(){return Wc()||process.env.TB_AI_BASE_URL?!0:(await am()).length>0}function cm(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 gr,_k,Ck,Rk,Nk,Tn,wi,Pn,Bt=A(()=>{gr={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};_k="https://api.typebulb.com/api/models",Ck=1440*60*1e3,Rk=5e3,Nk=60*1e3,Tn=null,wi=null,Pn=null});function We(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=Lt(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${yr(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=gr[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 pt(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 Dc(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(()=>{hr();Bt()});import{realpathSync as jk}from"fs";import{join as Gc,resolve as Fk}from"path";import{homedir as qk}from"os";function Ai(){let r=process.env.TYPEBULB_SERVERS_DIR;return r?Gc(r,".."):Gc(qk(),".typebulb")}function Ve(){return process.env.TYPEBULB_SERVERS_DIR||Gc(Ai(),"servers")}function re(r){let e=Fk(r),t=e;try{t=jk.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function fm(r,e){let t=re(r),n=re(e);return t.startsWith(n.endsWith("/")?n:n+"/")?!t.includes("/node_modules/"):!1}var Ti=A(()=>{});import{readFileSync as Uk,writeFileSync as Jk,mkdirSync as Kk}from"fs";import{join as Hk}from"path";function pm(){return Hk(Ai(),"trust.json")}function zc(){try{let r=JSON.parse(Uk(pm(),"utf8"));return new Set(Array.isArray(r)?r:[])}catch{return new Set}}function Wk(r){Kk(Ai(),{recursive:!0}),Jk(pm(),JSON.stringify([...r]))}function jt(r){return zc().has(re(r))}function wr(r,e){let t=zc(),n=re(r);(e?t.has(n):!t.has(n))||(e?t.add(n):t.delete(n),Wk(t))}function Xc(){return[...zc()]}var Cn=A(()=>{Ti()});function Ce(r){return r.length>5e4?r.slice(0,5e4)+`
|
|
368
|
+
\u2026[${r.length-5e4} more characters truncated]`:r}function Ge(r){let e=r.replace(Yk,"").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 Yk,Pi,Oi=A(()=>{Yk=/\u001b\[[0-9;]*m/g;Pi=(r,e)=>``});import{existsSync as Vk,readdirSync as Gk,statSync as zk}from"fs";import{join as Xk}from"path";function _i(r){if(!Vk(r))return[];let e;try{e=Gk(r)}catch{return[]}let t=[];for(let n of e){if(!n.endsWith(".jsonl"))continue;let s=Xk(r,n);try{let i=zk(s);i.isFile()&&t.push({sessionId:n.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var Qc=A(()=>{});var vr,Zc=A(()=>{vr=class{ensureHarnessSupport(){}}});import{openSync as Qk,readSync as Zk,closeSync as e0,statSync as t0,readdirSync as r0,readFileSync as n0,existsSync as s0}from"fs";import{join as Nn}from"path";import{homedir as rl}from"os";function i0(r){return r.replace(/[^a-zA-Z0-9]/g,"-")}function Ci(r){let e=r?.type==="image"?r.source:void 0;return e?.type==="base64"&&e.data?Pi(e.data,e.media_type):""}function el(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?el(t.content):Ci(t)}).join(`
|
|
370
|
+
`):r==null?"":Ce(JSON.stringify(r))}function a0(r){let e=r.trim();return!!e&&ym.some(t=>t.test(e))}function c0(r){let e=r.trim();return e?ym.some(t=>{let n=t.exec(e);return!!n&&n.index===0}):!0}function u0(r){return r.replace(l0,"")}function d0(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 ht(r){let e=u0(r).trim();return e?d0(e)??(a0(e)?"":e):""}function tl(r){return r?.type==="text"&&typeof r.text=="string"?ht(r.text):""}function nl(r,e){if(typeof r=="string")return Ge(r);if(!r||typeof r!="object")return Ge(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=hm(t.file?.originalSize);return n?`image (${n})`:"image"}if(t.type==="pdf"){let n=hm(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":Ge(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"):Ge(e)}function Rn(r){return!!r.isSidechain||!!r.isMeta}function f0(r){let e;try{e=Qk(r,"r")}catch{return""}try{let n=65536;try{n=t0(r).size}catch{}let s=(l,f)=>{if(f<=0)return"";let u=Buffer.alloc(f),d=Zk(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
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=
|
|
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()&&
|
|
375
|
-
`),n=[];if(t.forEach((o,a)=>{let c=
|
|
376
|
-
`)}function
|
|
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=ht(u):Array.isArray(u)&&(d=u.map(tl).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{e0(e)}}function p0(r){let e;try{e=r0(gm)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let n=JSON.parse(n0(Nn(gm,t),"utf8"));if(n?.sessionId!==r)continue;return process.kill(n.pid,0),!0}catch{}return!1}var o0,mm,ym,l0,Ee,hm,gm,Sr,Ri=A(()=>{Oi();Qc();Zc();o0=Nn(rl(),".claude","projects"),mm=r=>Nn(o0,i0(r));ym=[/\[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];l0=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;Ee=(r,e,t=e+"s")=>`${r} ${r===1?e:t}`,hm=r=>typeof r!="number"?"":r<1024?`${r}B`:r<1048576?`${Math.round(r/1024)}KB`:`${(r/1048576).toFixed(1)}MB`;gm=Nn(rl(),".claude","sessions");Sr=class extends vr{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}detectsInstalled(){return s0(Nn(rl(),".claude"))}sessionsDir(e){return mm(e)}listSessionFiles(e){return _i(mm(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=ht(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=el(i.content);n.push({type:"tool_result",id:i.tool_use_id??"",content:o,isError:!!i.is_error,digest:nl(e.toolUseResult,o)})}else{let o=tl(i)||Ci(i);o&&n.push({type:"user",text:o})}return{events:n}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=ht(el(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=>!c0(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()&&ht(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 p0(e)}readPreview(e){return f0(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=ht(t);else if(Array.isArray(t)){let s=t;n=e.type==="user"?s.map(tl).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 bm}from"child_process";import{readdir as m0,readFile as vm,writeFile as Sm,unlink as sl,mkdir as h0}from"fs/promises";import{mkdirSync as xm,writeFileSync as Ni,appendFileSync as g0,readFileSync as il}from"fs";import*as he from"path";import{fileURLToPath as y0}from"url";function ol(r){return he.join(Ve(),`${r}.json`)}function $n(r){return he.join(Ve(),`${r}.log`)}function al(r){return he.join(Ve(),`${r}.wait.json`)}function km(r){try{let e=JSON.parse(il(al(r),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function cl(r,e=""){let t=km(r)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Ii(r,e,t=""){try{xm(Ve(),{recursive:!0});let n=km(r);n[t]=e,Ni(al(r),JSON.stringify({cursors:n}))}catch{}}function $i(r){let e=$n(r);try{xm(Ve(),{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(g0(e,c),s+=c.length,s>2*wm){let l=il(e),f=l.subarray(Math.max(0,l.length-wm));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 Em(r){try{Ni($n(r),"")}catch{}}function Re(r,e=0){try{let t=il($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 ll(r){return`\u2500\u2500 run ${r} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function w0(r){let e=b0.exec(r);return e?Number(e[1]):void 0}function Am(r,e){let t=r.split(`
|
|
375
|
+
`),n=[];if(t.forEach((o,a)=>{let c=w0(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 ul(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function Tm(r){await h0(Ve(),{recursive:!0}),await Sm(ol(r.pid),JSON.stringify(r))}async function Pm(r,e){let t=ol(r);try{let n=JSON.parse(await vm(t,"utf8"));if(n.denied===e)return;n.denied=e,await Sm(t,JSON.stringify(n))}catch{}}async function In(r){await sl(ol(r)).catch(()=>{}),await sl($n(r)).catch(()=>{}),await sl(al(r)).catch(()=>{})}async function z(r){let e;try{e=await m0(Ve())}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 vm(he.join(Ve(),s),"utf8"))}catch{await In(i);return}o&&typeof o.pid=="number"&&ul(o.pid)?t.push(o):await In(i)})),(r?t.filter(s=>s.agent==null&&fm(s.file,r)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function dl(r,e){let t=re(r);return(await z()).find(n=>n.cwd!=null&&re(n.cwd)===t&&(e?n.agent===e:n.agent!=null))}async function Ft(r){try{process.kill(r,"SIGTERM")}catch{}await In(r)}function xr(r,e){let t=re(e);return r.filter(n=>n.agent==null&&n.pid!==process.pid&&re(n.file)===t)}async function fl(r){let e=xr(await z(),r);for(let t of e)await Ft(t.pid);return e}function S0(r,e,t){(process.platform==="win32"?bm("cmd",["/c","start","","/b",r,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):bm(r,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function Om(){return he.join(he.dirname(y0(import.meta.url)),"index.js")}function x0(r,e={}){return{command:process.execPath,args:[Om(),...e.trust?["--trust"]:[],...e.dir?["--dir",e.dir]:[],...e.mode?["--mode",e.mode]:[],r,...e.open===!1?["--no-open"]:[]]}}function k0(r){return{command:process.execPath,args:[Om(),`agent:${r}`,"--no-open"]}}async function _m(r,e,t,n){let s=await r();if(s)return s;S0(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await v0(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),[s]=await fl(n),i={...e,dir:e.dir??s?.dir,mode:e.mode??s?.mode};return _m(async()=>xr(await z(),n)[0],x0(r,i),t,he.basename(r))}async function Cm(r,e=process.cwd()){return _m(()=>dl(e,r),k0(r),e,`the ${r} mirror`)}var wm,b0,v0,Ne=A(()=>{Ti();wm=1e6;b0=/^── run (\d+) ── /;v0=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 pl(r){return(Mi(r)??"bulb").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"bulb"}var ml=A(()=>{});import{readdirSync as E0,readFileSync as A0,statSync as T0}from"fs";import{join as Rm,basename as P0}from"path";function Nm(r,e,t){if(e>8)return t;let n;try{n=E0(r,{withFileTypes:!0})}catch{return t}for(let s of n)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;Nm(Rm(r,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(Rm(r,s.name));return t}function Di(r){return Nm(r,0,[]).map(e=>{let t=0;try{t=T0(e).mtimeMs}catch{}let n,s=!1;try{let i=A0(e,"utf8");n=Mi(i.slice(0,1024));let o=fe(i);s=!!o&&Xs(cr(o))}catch{}return{path:e,name:n??P0(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var Im=A(()=>{Ue();gn();ml()});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 O0}from"fs/promises";async function hl(r){try{let e=fe(await O0(r,"utf-8"));return e?kr(cr(e)):void 0}catch{return}}var $m=A(()=>{gn();Bi()});function gl(r){let e=fe(r);if(!e)return r;let t=e.files.get("code.tsx");if(!t)return r;let n=Np(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=vu(l);u&&(c[u]=f)}return c.config=JSON.stringify(i,null,2),Ou(c)}var Lm=A(()=>{Ue();Qs()});import{spawn as Mm}from"child_process";import{basename as _0}from"path";function C0(){return process.env.TYPEBULB_EDITOR||"code"}function N0(r,e,t){return t==null?[e]:R0.test(_0(r))?["-g",`${e}:${t}`]:[`+${t}`,e]}function I0(r,e){let t=C0();return{command:t,args:N0(t,r,e)}}function yl(r,e){let{command:t,args:n}=I0(r,e),s=process.platform==="win32"?Mm("cmd.exe",["/d","/s","/c",t,...n],{detached:!0,stdio:"ignore",windowsHide:!0}):Mm(t,n,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var R0,Dm=A(()=>{R0=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as $0,existsSync as L0}from"fs";import*as qt from"path";import{fileURLToPath as M0}from"url";function Bm(){let r=qt.dirname(M0(import.meta.url));for(;!L0(qt.join(r,"package.json"));){let e=qt.dirname(r);if(e===r)break;r=e}return r}function Ut(){return qt.join(Bm(),"README.md")}function Er(){return qt.join(Bm(),"description.md")}function D0(r){let e=$0(Er(),"utf8").trim().replace(/\s+/g," ");return`---
|
|
377
377
|
name: typebulb
|
|
378
378
|
description: ${JSON.stringify(e)}
|
|
379
379
|
version: ${r}
|
|
380
|
-
---`}function
|
|
380
|
+
---`}function B0(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 jm(r,e){return`${D0(e)}
|
|
381
381
|
|
|
382
|
-
${
|
|
382
|
+
${B0(e)}
|
|
383
383
|
|
|
384
384
|
${r.trim()}
|
|
385
|
-
`}var ji=A(()=>{});import{readFileSync as
|
|
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
|
|
385
|
+
`}var ji=A(()=>{});import{readFileSync as Fm,existsSync as j0}from"fs";import*as Ie from"path";function qm(r){return[...r?[`.env.${r}.local`,`.env.${r}`]:[],".env.local",".env"]}function ge(r,e=process.cwd()){let t={},n=[];for(let s of qm(r)){let i;try{i=Fm(Ie.resolve(e,s),"utf-8")}catch{continue}n.push(s);for(let[o,a]of Um(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:r,sources:t,loaded:n}}function*Um(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 qm()){let n;try{n=Fm(Ie.resolve(e,t),"utf-8")}catch{continue}for(let[s,i]of Um(n))if(s===r)return i}return process.env[r]}function F0(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 gt(r,e,t){let{sources:n,mode:s,loaded:i}=r,o=process.cwd(),a=Ie.dirname(e),c=`(mode: ${s??"none"})`,l=t?F0(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=Ie.resolve(a)!==Ie.resolve(o);if(u)for(let p of[".env.local",".env"])j0(Ie.join(a,p))&&console.log(`env: ${Ie.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 yt=A(()=>{});import*as $e from"fs/promises";import*as Ae from"path";function wl(r,e){ge(e);let t=process.env.TYPEBULB_ORIGIN||q0;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
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(
|
|
389
|
-
`),n=fe(t(r)),s=fe(t(e));return!n||!s?t(r)===t(e):n.frontmatter.name===s.frontmatter.name&&
|
|
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(bl(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 $e.readFile(r.dest,"utf-8")}catch{}if(i!==void 0){if(U0(i,s))return{kind:"up-to-date",dest:r.dest};if(!e.force){let{mtime:a}=await $e.stat(r.dest);return{kind:"conflict",dest:r.dest,localMtime:a,remoteLastModified:t.headers.get("last-modified")}}}await $e.mkdir(Ae.dirname(r.dest),{recursive:!0}),await $e.writeFile(r.dest,s);let o=new Date(t.headers.get("last-modified")??"");return isNaN(o.getTime())||await $e.utimes(r.dest,new Date,o),{kind:"written",dest:r.dest,created:i===void 0}}function U0(r,e){let t=i=>i.replace(/\r\n/g,`
|
|
389
|
+
`),n=fe(t(r)),s=fe(t(e));return!n||!s?t(r)===t(e):n.frontmatter.name===s.frontmatter.name&&Qe.every(i=>(n.files.get(Pe[i].path)||"")===(s.files.get(Pe[i].path)||""))}async function Jm(r,e){r||(console.error("Usage: typebulb pull <bulb url | typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1));let t=wl(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 q0,qi,bl,Ki=A(()=>{yt();Ue();q0="https://typebulb.com",qi=(r,e)=>Ae.join("typebulbs","u",r,`${e}.bulb.md`),bl=r=>`${r.origin}/u/${encodeURIComponent(r.userSlug)}/${encodeURIComponent(r.slug)}.md`});import*as Ar from"fs/promises";import*as Hm from"path";async function Hi(r,e){let t=await Ar.readFile(r.dest,"utf-8"),{mtime:n}=await Ar.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(bl(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:Km(o)};if(!i.ok)return{kind:"http-error",status:i.status,message:Km(o)};let a=JSON.parse(o);return await Ar.utimes(r.dest,new Date,new Date(a.updatedAt)),{kind:"pushed",created:a.created,serverStripped:a.serverStripped,updatedAt:a.updatedAt}}function Km(r){try{return JSON.parse(r).error||r}catch{return r}}async function Wm(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=wl(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=Hm.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 vl=A(()=>{Ki()});var Tr=A(()=>{Ne();Im();$m();ml();Lm();Dm();Cn();Bt();Bt();Si();ji();Ki();vl();yt()});import{copyFileSync as J0,existsSync as Ym,mkdirSync as Vm,rmSync as K0,writeFileSync as H0}from"fs";import{homedir as W0}from"os";import*as Le from"path";import{fileURLToPath as Y0}from"url";function Z0(){return Q0.replace('"__TB_DESCRIPTION_PATH__"',JSON.stringify(Er())).replace('"__TB_README_PATH__"',JSON.stringify(Ut()))}function Gm(){try{if(!Ym(Wi()))return}catch{return}try{let r=V0();Vm(Le.dirname(r),{recursive:!0}),H0(r,Z0()),K0(G0(),{force:!0})}catch{}try{let r=z0();if(!Ym(r))return;let e=X0();Vm(Le.dirname(e),{recursive:!0}),J0(r,e)}catch{}}var Wi,V0,G0,z0,X0,Q0,zm=A(()=>{Tr();Wi=()=>Le.join(W0(),".pi","agent"),V0=()=>Le.join(Wi(),"extensions","typebulb.ts"),G0=()=>Le.join(Wi(),"extensions","typebulb-wait.ts"),z0=()=>Le.join(Le.dirname(Y0(import.meta.url)),"agents","pi","matchu-patchu.ts"),X0=()=>Le.join(Wi(),"extensions","matchu-patchu.ts"),Q0=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,32 @@ 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 H,
|
|
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,Qm
|
|
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 H,bt=A(()=>{H=process.cwd()});import{spawn as Xm}from"child_process";import{StringDecoder as eE}from"string_decoder";function cE(r,e){let t=new eE("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 tE,rE,Qm,nE,sE,iE,oE,aE,Yi,Vi,Zm,eh=A(()=>{bt();tE=3e4,rE=5e3,Qm=2e3,nE=2e3,sE=12e4,iE=8e3,oE=15e3,aE=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;#d;#f;#y="";#A=1;#s=new Map;#v;#b;constructor(e,t,n=(s,i)=>Xm(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.#f="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.#f=`could not start pi: ${U(o)}`,this.#b();return}this.#e=i,this.#d=t,Yi.add(i),i.stdout&&cE(i.stdout,o=>this.#T(o)),i.stderr&&i.stderr.on("data",o=>{this.#y=(this.#y+o.toString()).slice(-nE)}),i.on("error",o=>this.#k(`could not start pi: ${o.message}`)),i.on("exit",o=>{this.#e===i&&this.#k(o?`pi exited (code ${o})${this.#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.#d=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.#d}get error(){return this.#f}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.#x({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.#x(i),{ok:!0}}async rpc(e){if(!aE.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.#d=s)}catch{}return{ok:!0,data:{...t.data??{},sessionFile:this.#d}}}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()+rE),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,Zm(Qm)])}try{e.stdin?.end()}catch{}if(await Promise.race([this.#v,Zm(Qm)]),e.exitCode===null&&!e.killed)if(process.platform==="win32"&&e.pid)try{Xm("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")}}#x(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"?iE:oE)})}#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.#f??"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)"))},tE);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
|
-
`)
|
|
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??sE),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}}#k(e){this.#f=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()}},Zm=r=>new Promise(e=>{setTimeout(e,r).unref?.()})});import{existsSync as th,readFileSync as lE,realpathSync as uE}from"fs";import{join as Jt,dirname as ih,resolve as dE}from"path";import{homedir as rh}from"os";function pE(r,e){let t=Jt(r,".pi");if(fE.some(s=>th(Jt(t,s))))return!0;let n=Jt(e,".agents","skills");for(let s=r;;){let i=Jt(s,".agents","skills");if(i!==n&&th(i))return!0;let o=ih(s);if(o===s)return!1;s=o}}function mE(r,e){for(let t=e;;){if(r[t]===!0||r[t]===!1)return!0;let n=ih(t);if(n===t)return!1;t=n}}function oh(r,e){try{let t=e?.agentDir??Jt(rh(),".pi","agent"),n=nh(e?.home??process.env.HOME??rh()),s=nh(dE(r));if(!pE(s,n))return null;let i=sh(Jt(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||mE(sh(Jt(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 fE,nh,sh,ah=A(()=>{fE=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],nh=r=>{try{return uE(r)}catch{return r}},sh=r=>{try{return JSON.parse(lE(r,"utf8"))}catch{return{}}}});import{statSync as hE,openSync as gE,readSync as yE,closeSync as bE,existsSync as lh}from"fs";import{join as Gi}from"path";import{homedir as Sl}from"os";import{execFile as wE}from"child_process";async function SE(r){let e=Gi(Sl(),".pi","agent","bin",process.platform==="win32"?"fd.exe":"fd");for(let t of["fd","fdfind",...lh(e)?[e]:[]]){let n=await new Promise(s=>{wE(t,["--base-directory",r,"--type","f","--follow","--hidden","--exclude",".git"],{maxBuffer:67108864},(i,o)=>s(i?null:o))});if(n!==null)return n.split(`
|
|
549
|
+
`).filter(Boolean).map(s=>s.replace(/\\/g,"/"))}return null}function xE(r){return`--${r.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function ch(r){return r.type==="message"?kE(r.message?.role):r.type==="custom_message"?r.display!==!1:!1}var vE,kE,Pr,xl=A(()=>{Oi();Qc();Zc();zm();eh();ah();vE=Gi(Sl(),".pi","agent","sessions");kE=r=>r==="user"||r==="assistant"||r==="toolResult"||r==="bashExecution";Pr=class extends vr{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return lh(Gi(Sl(),".pi","agent"))}ensureHarnessSupport(){Gm()}createDriver(e,t){let n=new Vi(e,t),s=oh(e);return s&&n.notice(s,"warning"),n}walkFiles(e){return SE(e)}sessionsDir(e){return Gi(vE,xE(e))}listSessionFiles(e){return _i(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 ch(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:Ge(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(`
|
|
550
|
+
`),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)ch(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=gE(e,"r")}catch{return""}try{let s=65536;try{s=hE(e).size}catch{}let i=(u,d)=>{let p=Buffer.alloc(d),y=yE(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
551
|
`))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{
|
|
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,M);if(g.partial=g.partial.slice(M+1),!q.trim())continue;let ue=r.parseEntry(q);if(!ue)continue;let ee=r.idOf(ue);ee&&(g.entries.set(ee,ue),!r.isSidechain(ue)&&r.isLeafType(ue)&&(
|
|
557
|
-
`).filter(Boolean).map(async
|
|
558
|
-
`)){if(!B.trim())continue;let $=r.parseEntry(B);if(!$)continue;let J=r.searchText($);J&&
|
|
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()&&(M=q.text.trim())}let B=M.length>
|
|
560
|
-
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=
|
|
561
|
-
${r}`;return
|
|
562
|
-
`)}function
|
|
552
|
+
`))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{bE(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(`
|
|
553
|
+
`):""}}});var zi,uh=A(()=>{zi=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});import{execFile as EE}from"child_process";import{promisify as AE}from"util";import{readFile as TE}from"fs/promises";import{resolve as dh,sep as PE}from"path";async function Me(r,e){let{stdout:t}=await OE("git",r,{cwd:e,maxBuffer:67108864});return t}async function Or(){if(Xi)return Xi;try{Xi=(await Me(["rev-parse","--show-toplevel"],H)).trim()}catch{}return Xi}function _E(r,e){let t=e===" "?r:e;return t==="?"?"U":t}async function ph(){let r=await Or();if(!r)return{repo:!1,root:"",files:[]};try{let e=await Me(["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:_E(i[0],i[1])}))}try{let s=await Me(["diff","--numstat","HEAD"],r),i=new Map;for(let o of s.split(`
|
|
554
|
+
`)){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 mh(r){let e=await Or();if(!e)return{ok:!1,error:"not a git repository"};try{if((await Me(["status","--porcelain","-z","--",r],e)).startsWith("??")){let s=dh(e,r);if(!s.startsWith(dh(e)+PE))return{ok:!1,error:"outside repository"};let i=await TE(s);return i.includes(0)?kl("Binary file (not shown)",!1):kl(i.toString("utf8"),!0)}let n;try{n=await Me(["diff","--no-color","--unified=999999","HEAD","--",r],e)}catch{n=await Me(["diff","--no-color","--unified=999999","--",r],e)}return kl(n,!1)}catch(t){return{ok:!1,error:U(t)}}}var OE,fh,Xi,kl,Qi=A(()=>{bt();OE=AE(EE),fh=2e6;kl=(r,e)=>({ok:!0,text:r.slice(0,fh),untracked:e,truncated:r.length>fh})});function Zi(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 El=A(()=>{});var eo,to,hh=A(()=>{eo=".typebulb/paste",to={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 CE,mkdirSync as RE,writeFileSync as NE,readFileSync as IE}from"fs";import{join as ro}from"path";function gh(){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 DE(r){return r.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function BE(r){let e=AbortSignal.timeout($E);for(let[t,n]of ME){let s=We(t,n);if(typeof s!="string"){try{let i=await pt(s,{messages:[{role:"user",content:`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
|
|
555
|
+
|
|
556
|
+
${r.slice(0,LE)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=DE(await Mt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function yh(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=ro(r,eo);try{RE(t,{recursive:!0})}catch(a){return{ok:!1,error:U(a)}}let n,s,i;if(e.kind==="image"){if(n=`img-${gh()}`,s=Object.keys(to).find(a=>to[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else n=await BE(e.data)??`paste-${gh()}`,s="md",i=e.data;let o=`${n}.${s}`;for(let a=2;CE(ro(t,o));a++)o=`${n}-${a}.${s}`;try{NE(ro(t,o),i)}catch(a){return{ok:!1,error:U(a)}}return{ok:!0,path:`${eo}/${o}`}}function bh(r,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),n=to[t];if(!n)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:n,base64:IE(ro(r,eo,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var $E,LE,ME,wh=A(()=>{hr();Tr();bt();hh();$E=4e3,LE=4e3,ME=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});import{existsSync as vh,openSync as jE,readSync as FE,closeSync as qE,statSync as _r,readdirSync as Sh,watchFile as UE,unwatchFile as xh,mkdirSync as JE,writeFileSync as KE,readFileSync as no,unlinkSync as HE,rmSync as WE}from"fs";import{stat as YE}from"fs/promises";import{dirname as VE,join as Kt,resolve as kh}from"path";function QE(r){if(!Number.isInteger(r))return!0;try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}function so(r){let e={cwd:H,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 w={d:r.createDriver(e.cwd,g),file:g};return t.add(w),e.file||(n=w),w}async function o(g){t.delete(g),n===g&&(n=void 0);try{await g.d.dispose()}catch(w){console.error("[composer] dispose:",U(w))}}function a(){let g=s();for(let w of[...t])w!==g&&(w.d.streaming||w.d.queue||w.d.error||o(w))}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(w=>w.file===n.file);g&&C(g)}}let l=g=>Kt(g,zE),f=(g,w)=>Kt(l(g),`${w}.lock`);function u(g,w){try{let S=f(g,w);if(Date.now()-_r(S).mtimeMs>=Eh)return!1;try{let O=parseInt(no(S,"utf8").trim(),10);if(O===process.pid||!QE(O))return!1}catch{}return!0}catch{return!1}}function d(g,w){if(w)try{JE(l(g),{recursive:!0}),KE(f(g,w),String(process.pid))}catch(S){console.error("[lock] claim failed:",U(S))}}function p(g){try{WE(Kt(g,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function y(g){let w=l(g);if(!vh(w))return;let S;try{S=Sh(w)}catch{return}let O=Date.now();for(let M of S){if(!M.endsWith(".lock"))continue;let B=Kt(w,M);try{let $=_r(B);O-$.mtimeMs>XE&&HE(B)}catch{}}}function m(g){try{return _r(g),!1}catch(w){return w.code==="ENOENT"}}function b(){let g=e;if(g.file&&!m(g.file)){d(g.cwd,g.sessionId);return}let w=x(g);w&&C(w)}function x(g){if(!g.everAttached)return k(g.cwd)??T(g.cwd,()=>!0)}function k(g){let w=l(g);if(!vh(w))return;let S;try{S=Sh(w)}catch{return}let O;for(let B of S)if(B.endsWith(".lock"))try{let $=_r(Kt(w,B));if(Date.now()-$.mtimeMs>=Eh||parseInt(no(Kt(w,B),"utf8").trim(),10)!==process.pid)continue;(!O||$.mtimeMs>O.mtime)&&(O={sessionId:B.slice(0,-5),mtime:$.mtimeMs})}catch{}if(!O)return;let M=r.listSessionFiles(g).find(B=>B.sessionId===O.sessionId);if(!(!M||m(M.file)))return M}function T(g,w){return r.listSessionFiles(g).sort((S,O)=>O.mtime-S.mtime).find(S=>!u(g,S.sessionId)&&w(S))}function P(g,w){let S=e;if(S.file)try{xh(S.file)}catch{}S.file=g,S.sessionId=w,S.partial="",S.offset=0,S.latest={in:0,out:0,cached:0,cacheCreate:0},S.latestModel=null,S.entries=new Map,S.chainLastId=void 0,S.buffer.push({type:"cleared"}),S.buffer.push({type:"session",sessionId:w})}function C(g){let w=e;n=void 0,P(g.file,g.sessionId),w.everAttached=!0,d(w.cwd,g.sessionId),N();try{xh(g.file)}catch{}UE(g.file,{interval:200},()=>N())}function _(){P(void 0,"")}function N(){let g=e;if(!g.file)return;let w;try{w=_r(g.file).size}catch{return}if(w<=g.offset)return;let S;try{S=jE(g.file,"r")}catch{return}try{let q=w-g.offset,ue=Buffer.alloc(q),ee=0;for(;ee<q;){let au=FE(S,ue,ee,q-ee,g.offset+ee);if(!au)break;ee+=au}g.offset+=ee,g.partial+=ue.subarray(0,ee).toString("utf8")}finally{qE(S)}let O,M;for(;(M=g.partial.indexOf(`
|
|
557
|
+
`))>=0;){let q=g.partial.slice(0,M);if(g.partial=g.partial.slice(M+1),!q.trim())continue;let ue=r.parseEntry(q);if(!ue)continue;let ee=r.idOf(ue);ee&&(g.entries.set(ee,ue),!r.isSidechain(ue)&&r.isLeafType(ue)&&(O=ee))}if(!O)return;let B=[],$=g.entries.get(O),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--)L(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(ee=>r.idOf(ee))),ue=h(g.entries);for(let ee=B.length-1;ee>=0;ee--)L(B[ee]),v(r.idOf(B[ee]),ue,q)}g.chainLastId=O}function h(g){let w=new Map;for(let S of g.values()){let O=r.parentOf(S);if(!O)continue;let M=w.get(O);M?M.push(S):w.set(O,[S])}return w}function v(g,w,S){if(!g)return;let O=w.get(g);if(!O)return;let M=O.filter(q=>!r.isSidechain(q));if(M.length<2)return;let B=M.filter(q=>!S.has(r.idOf(q)));if(!B.length)return;let $=[],J=0;for(let q of B){let ue=I(q,w);$.push(...ue.events),J+=ue.count}J>0&&e.buffer.push({type:"fork",atId:g,count:J,events:$})}function I(g,w){let S=[],O=[g];for(;O.length;){let $=O.pop();if(r.isSidechain($))continue;S.push($);let J=w.get(r.idOf($)??"");if(J)for(let q of J)O.push(q)}S.sort(($,J)=>(Date.parse(r.timestampOf($)??"")||0)-(Date.parse(r.timestampOf(J)??"")||0));let M=[];for(let $ of S)r.isRecoveryNoise($)||M.push(...r.apply($,e.sessionStartMs).events);return{count:M.reduce(($,J)=>$+(J.type==="user"||J.type==="assistant"?1:0),0),events:M}}function L(g){try{let{events:w,usage:S,model:O,cost:M}=r.apply(g,e.sessionStartMs);for(let B of w)e.buffer.push(B);w.some(B=>B.type==="assistant")&&s()?.d.clearCompletedDraft(),w.some(B=>B.type==="user")&&s()?.d.clearEcho(),O&&(e.latestModel=O),S&&(e.latest=S),(S||M)&&e.buffer.push({type:"usage",...e.latest,cost:M})}catch(w){console.error("[mirror] skipped malformed entry:",U(w))}}async function R(){return{cwd:e.cwd,pid:process.pid,composer:!!r.createDriver,elsewhere:await K()}}async function K(){if(r.listSessionFiles(e.cwd).length)return;let g=await Or();if(!g)return;let w=kh(g).toLowerCase();for(let S=kh(e.cwd);S.toLowerCase()!==w;){let O=VE(S);if(O===S)return;S=O;let M=r.listSessionFiles(S).length;if(M)return{dir:S,count:M}}}K().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 W=new zi;async function Be(g,w){W.accept(g,w)&&console.log(w)}function Z(){let g=r.sessionAlive(e.sessionId,e.cwd);if(g!==void 0)return g;if(!e.file)return!1;try{return Date.now()-_r(e.file).mtimeMs<1e4}catch{return!1}}function Y(){return r.chainWorking([...e.entries.values()])&&Z()}function je(){!r.createDriver||s()||e.latestModel||Y()||i(e.file)}async function Te(g){let w=e;b(),c(),je(),a();let S=s();for(let $ of t)$!==S&&$.d.dialog;let O=new Set([...t].filter($=>$.d.streaming&&$.file).map($=>$.file)),M=O.size?r.listSessionFiles(w.cwd).filter($=>O.has($.file)).map($=>$.sessionId):[],B=r.createDriver?{streaming:!!S?.d.streaming,draft:S?.d.draft??null,echo:S?.d.echo??null,status:S?.d.status??null,dialog:S?.d.dialog??null,queue:S?.d.queue??null,stats:S?.d.stats??null,model:S?.d.model??null,error:S?.d.error}:void 0;return{events:w.buffer.slice(g),cursor:w.buffer.length,working:!!S?.d.streaming||Y(),latestModel:w.latestModel,composer:B,busy:M}}async function nu(){b(),c();let g=s();if(g?.d.error&&!g.d.streaming&&(await o(g),g=void 0),!g){if(Y())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 ky(g,w){if(!r.createDriver)return{ok:!1,error:"not supported"};let S=String(g??"").trim();if(!S)return{ok:!1,error:"empty message"};let O=await nu();return O.ok?O.d.send(S,w):O}async function Ey(g,w){let S=s();return S?S.d.respondUi(String(g??""),w??{}):{ok:!1,error:"no dialog pending"}}async function Ay(g,w){if(!r.createDriver)return{ok:!1,error:"not supported"};if(!g||typeof g.type!="string")return{ok:!1,error:"bad command"};if(w?.spawn){let O=await nu();return O.ok?O.d.rpc(g):O}let S=s();return!S||S.d.error?{ok:!1,error:"not running"}:S.d.rpc(g)}async function Ty(){let g=s();if(g)try{await g.d.stop()}catch(w){console.error("[composer] stop:",U(w))}return{ok:!0}}async function Py(){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&&_(),i(void 0),a(),{ok:!0})):{ok:!1,error:"not supported"}}async function Oy(){if(!r.createDriver)return[];let g=await Me(["ls-files","--cached","--others","--exclude-standard"],e.cwd).catch(()=>null),w=g!==null?g.split(`
|
|
558
|
+
`).filter(Boolean):await r.walkFiles?.(e.cwd)??[];return(await Promise.all(w.map(async O=>{try{return{f:O,m:(await YE(Kt(e.cwd,O))).mtimeMs}}catch{return{f:O,m:0}}}))).sort((O,M)=>M.m-O.m).map(O=>O.f)}function _y(){for(let g of[...t])o(g)}async function Cy(g){return r.createDriver?yh(e.cwd,g):{ok:!1,error:"not supported"}}async function Ry(g){return bh(e.cwd,String(g??""))}async function Ny(){return r.listSessionFiles(e.cwd).sort((g,w)=>w.mtime-g.mtime).map(({sessionId:g,file:w,mtime:S})=>({sessionId:g,mtime:S,preview:r.readPreview(w)}))}let su=new Map;function Iy(g,w){let S=su.get(g);if(S&&S.mtime===w)return S.turns;let O=[],M="";try{M=no(g,"utf8")}catch{return[]}for(let B of M.split(`
|
|
559
|
+
`)){if(!B.trim())continue;let $=r.parseEntry(B);if(!$)continue;let J=r.searchText($);J&&O.push({text:J,lower:J.toLowerCase()})}return su.set(g,{mtime:w,turns:O}),O}async function $y(g){let w=g.toLowerCase(),S=[];for(let{sessionId:O,file:M,mtime:B}of r.listSessionFiles(e.cwd).sort(($,J)=>J.mtime-$.mtime)){let{hitCount:$,snippet:J}=Zi(Iy(M,B),w);if($&&(S.push({sessionId:O,mtime:B,preview:r.readPreview(M),hitCount:$,snippet:J}),S.length>=ZE))break}return S}let iu=800,ou=new Map;function Ly(g,w){let S=ou.get(g);if(S&&S.mtime===w)return S.text;let O="";try{O=no(g,"utf8")}catch{return""}let M="";for(let $ of O.split(`
|
|
560
|
+
`)){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()&&(M=q.text.trim())}let B=M.length>iu?M.slice(0,iu).trimEnd()+"\u2026":M;return ou.set(g,{mtime:w,text:B}),B}async function My(g){let w=r.listSessionFiles(e.cwd).find(S=>S.sessionId===g);return{text:w?Ly(w.file,w.mtime):""}}async function Dy(g){let w=e,S=r.listSessionFiles(w.cwd).find(O=>O.sessionId===g);return S?S.file===w.file?{ok:!0}:(C(S),c(),a(),{ok:!0}):{ok:!1,error:"session not found"}}return p(e.cwd),y(e.cwd),b(),{info:R,poll:Te,logEmbedStatus:Be,listSessions:Ny,searchSessions:$y,sessionPeek:My,attach:Dy,composerSend:ky,composerStop:Ty,composerNew:Py,composerFiles:Oy,composerUiRespond:Ey,composerRpc:Ay,composerPaste:Cy,composerPasteRead:Ry,shutdownComposer:_y}}var GE,zE,Eh,XE,ZE,Al=A(()=>{bt();uh();Qi();El();wh();GE=".typebulb",zE=`${GE}/locks`,Eh=5e3,XE=6e4;ZE=50});import{existsSync as _l,mkdirSync as eA,readFileSync as Ah,writeFileSync as tA}from"fs";import{join as Ht,isAbsolute as rA}from"path";async function Th(r,e){let t=rA(r)?r:Ht(H,r);return _l(t)?(yl(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function Ph(r){let e=H,t=gl(r),n=Ht(e,"typebulbs");eA(n,{recursive:!0});let s=pl(t),i=`${s}.bulb.md`;for(let l=2;_l(Ht(n,i))&&Ah(Ht(n,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=Ht(n,i);_l(o)||tA(o,t);let a=Ht("typebulbs",i),c=await Li(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function Oh(){return z(H)}async function _h(r){return await Ft(r),{ok:!0}}async function Ch(){return Di(H).filter(r=>!r.serverOnly).map(r=>({...r,trusted:jt(r.path)}))}async function Rh(r){let e=r.toLowerCase(),t=[];for(let n of Di(H).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=Ah(n.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
|
|
561
|
+
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=Zi(i,e);o&&t.push({path:n.path,hitCount:o,snippet:a})}return t}async function Nh(r,e){let t=H;e!=null&&wr(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 Ih(r){return{cap:await hl(r)}}async function $h(r,e){return wr(r,e),{ok:!0}}async function Lh(r,e){return Re(r,e)}async function jh(){return Ln&&Date.now()-Ln.fetchedAt<=sA?Ln.samples:(Tl??=iA().finally(()=>{Tl=null}),Tl)}async function iA(){try{let r=await fetch(`${nA}/api/scripts/u/samples?stubs`,{signal:AbortSignal.timeout(Dh)});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:jo(i.config)}));return Ln={samples:s,fetchedAt:Date.now()},s}catch{return Ln?.samples??[]}}async function Fh(r){return Cl.test(r)?Jh(Mh,"samples",r,!0):{ok:!1,error:"bad slug"}}async function qh(){let r=Rl();if(!r)return{bulbs:[]};let e=`${io()}
|
|
562
|
+
${r}`;return wt?.key===e&&Date.now()-wt.fetchedAt<=oA?{user:wt.user,bulbs:wt.bulbs}:(Pl??=aA(e,r).finally(()=>{Pl=null}),Pl)}async function Ol(r,e,t){let n=await fetch(`${r}${e}`,{headers:t,signal:AbortSignal.timeout(Dh)});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 aA(r,e){let t={Authorization:`Bearer ${e}`};try{let n=io(),s;try{s=await Ol(n,"/api/me",t)}catch{let a=new URL(n);n=`${a.protocol}//api.${a.host}`,s=await Ol(n,"/api/me",t)}let o=(await Ol(n,"/api/scripts/list",t)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:jo(a.config)}));return wt={key:r,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return wt?.key===r?{user:wt.user,bulbs:wt.bulbs}:{bulbs:[]}}}async function Uh(r,e,t=!1){return!Cl.test(e)||!Cl.test(r)?{ok:!1,error:"bad slug"}:Jh(io(),r,e,t)}async function Jh(r,e,t,n){let s=qi(e,t);try{let i=await Ji({origin:r,userSlug:e,slug:t,dest:Ht(H,s)},{force:n,token:Rl(),timeoutMs:Bh});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 Kh(r,e=!1){let t=Rl();if(!t)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let n=Ui(r,H,io()),s=await Hi(n,{token:t,force:e,timeoutMs:Bh});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 nA,Mh,sA,Dh,Bh,Ln,Tl,Cl,oA,wt,Pl,io,Rl,Nl=A(()=>{Tr();bt();El();Ue();nA="https://api.typebulb.com",Mh="https://typebulb.com",sA=3600*1e3,Dh=5e3,Bh=15e3,Ln=null,Tl=null;Cl=/^[a-z0-9][a-z0-9-]*$/,oA=300*1e3,wt=null,Pl=null,io=()=>Fi("TYPEBULB_ORIGIN",H)||Mh,Rl=()=>Fi("TYPEBULB_TOKEN",H)});import{readFileSync as Ll,writeFileSync as Wh,mkdirSync as cA,appendFileSync as Yh,rmSync as Hh}from"fs";import{join as co,dirname as lA}from"path";import{createServer as uA}from"http";function vt(r){try{return JSON.parse(Ll(r,"utf8"))}catch{return null}}function ao(r,e){cA(lA(r),{recursive:!0}),Wh(r,JSON.stringify(e,null,2)+`
|
|
563
|
+
`)}function Gh(r,e,t){let n=co(r,".gitignore"),s="";try{s=Ll(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
564
|
`)?`
|
|
564
|
-
`:"";try{
|
|
565
|
+
`:"";try{Yh(n,a+t+`
|
|
565
566
|
`+o.join(`
|
|
566
567
|
`)+`
|
|
567
|
-
`)}catch(c){console.error("[switcher] .gitignore update failed",U(c))}}function
|
|
568
|
+
`)}catch(c){console.error("[switcher] .gitignore update failed",U(c))}}function hA(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>mA&&(Bn="uncached")}function Xh(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 gA(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 Qh(r){let e;try{e=JSON.parse(r)}catch{return r}Dn=typeof e?.model=="string"?e.model:null,De&&(e.model=De),Yt&&(e.provider=zh(Yt));let t=/haiku/i.test(Dn||"");return jn!=null&&!t&&(e.reasoning={effort:Il[jn]}),delete e.thinking,e.output_config&&delete e.output_config.effort,gA(e),JSON.stringify(e)}function yA(){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
569
|
data: ${JSON.stringify(a)}
|
|
569
570
|
|
|
570
571
|
`}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 +573,11 @@ data: ${JSON.stringify(a)}
|
|
|
572
573
|
|
|
573
574
|
`)}default:return i}};return i=>{r+=i;let o="",a;for(;(a=r.indexOf(`
|
|
574
575
|
|
|
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
|
|
576
|
+
`))!==-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 bA(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 wA(r,e,t){if(!De){Mn(e,400,"invalid_request_error",pA);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(Ml,{method:"POST",headers:Xh(r,n),body:Qh(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?yA():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});hA(p);let y=f(p);y&&e.write(y)}else e.write(Buffer.from(d))}}catch{}finally{e.writableEnded||e.end()}}async function vA(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(!De||!n)return s();try{let i=await fetch(`${Ml}/count_tokens`,{method:"POST",headers:Xh(r,n),body:Qh(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function SA(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}bA(r).then(n=>{if(t.includes("count_tokens"))return vA(r,e,n);if(t.includes("/v1/messages"))return wA(r,e,n);Mn(e,404,"not_found_error",t)})}function xA(){return Cr&&Wt?Promise.resolve(Wt):new Promise((r,e)=>{let t=uA(SA);t.on("error",e),t.listen(0,"127.0.0.1",()=>{Cr=t,Wt=t.address().port,console.log(`[switcher] wire proxy listening on ${oo(Wt)}`),r(Wt)})})}function kA(){try{Cr?.close()}catch{}Cr=null,Wt=null}function EA(r,e){let t=lo(r),n=vt(t),s=n||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===oo(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=uo(r);if(!vt(i)){let a={};for(let c of Vh)a[c]=c in s.env?s.env[c]:null;ao(i,{managedBy:"agent-switcher",fileExisted:n!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=oo(e),s.env.ANTHROPIC_AUTH_TOKEN=fA,ao(t,s),Gh(r,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function AA(r,e,t){let n=uo(r),s=vt(n)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},ao(n,s)}function Zh(r){let e=lo(r),t=uo(r),n=vt(t),s=vt(e);if(s?.env){let i=n?.snapshot||{};for(let o of Vh){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{Hh(e,{force:!0})}catch{}else ao(e,s)}try{Hh(t,{force:!0})}catch{}}async function TA(){let r=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await He()).filter(n=>n.provider==="openrouter"&&!Dl(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:Hc()??void 0;return{hasKey:r,models:e,error:t}}async function PA(){if(Cr&&De)return{active:!0,managed:!0,model:De,port:Wt,provider:Yt,routedModel:Dn,caching:Bn,reasoning:jn,externalBaseUrl:null};let r=vt(lo(H))?.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 eg(r,e){let t=await xA();return De=r,Yt=e,EA(H,t),t}async function OA({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(Dl(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 eg(r,Bl[r]??null),Dn=null,Bn="unknown",AA(H,r,Yt)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${U(e)}`}}return{ok:!0}}async function _A({level:r}){return r!=null&&(!Number.isInteger(r)||r<0||r>=Il.length)?{ok:!1,error:`reasoning level must be 0\u2013${Il.length-1} or null`}:(jn=r,{ok:!0,level:r})}async function CA(){return Zh(H),De=null,Yt=null,Dn=null,Bn="unknown",{ok:!0}}async function RA({key:r}){let e=(r||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=H,n=co(t,".env"),s="";try{s=Ll(n,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))Wh(n,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
|
|
576
577
|
`)?`
|
|
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
|
|
578
|
+
`:"";Yh(n,i+`OPENROUTER_API_KEY=${e}
|
|
579
|
+
`)}}catch(i){return{ok:!1,error:U(i)}}return process.env.OPENROUTER_API_KEY=e,Gh(t,[".env"],"# secrets"),{ok:!0}}function NA(){if(!(!Cr&&!De)){try{Zh(H)}catch{}kA()}}function IA(r,e){return tg.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 $A(r){if(tg.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 LA(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=$l(e?.cache_read_input_tokens)||$l(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 MA({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(Dl(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:zh(a)}:i),u=await fetch(Ml,{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 x=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:IA(a.status,x),restriction:$A(x)}}let l=typeof c?.provider=="string"?c.provider:void 0,f=c?.content?.find?.(x=>x.type==="text")?.text??c?.content?.[0]?.text??"ok",u=$l(c?.usage?.cache_creation_input_tokens),{r:d,j:p}=await o(l),{works:y,read:m,note:b}=LA(d.ok,p?.usage,l);return y===!0&&l&&(Bl[r]=l,De===r&&(Yt=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 dA,Ml,fA,pA,Vh,mA,Il,lo,uo,oo,Dl,Cr,Wt,De,Yt,Dn,Bn,jn,Bl,$l,zh,tg,rg=A(()=>{Tr();bt();dA="https://openrouter.ai/api",Ml=`${dA}/v1/messages`,fA="typebulb-proxy-managed",pA="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.",Vh=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],mA=5e3,Il=["low","medium","high"],lo=r=>co(r,".claude","settings.local.json"),uo=r=>co(r,".claude",".cc-switcher.json"),oo=r=>`http://127.0.0.1:${r}`;Dl=r=>/^anthropic\//i.test(r)||/claude/i.test(r),Cr=null,Wt=null,De=null,Yt=null,Dn=null,Bn="unknown",jn=1,Bl={},$l=r=>typeof r=="number"?r:0,zh=r=>({order:[r],allow_fallbacks:!1});tg=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=vt(uo(H)),t=e?.active?.model;if(!t)return;let s=(vt(lo(H))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await eg(t,e.active.provider??Bl[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${oo(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",U(e))}})()});var sg={};cu(sg,{attach:()=>KA,blockToMarkdown:()=>Ci,breakout:()=>Ph,capText:()=>Ce,cleanUserText:()=>ht,clearSwitchModel:()=>CA,composerPasteRead:()=>HA,displayName:()=>DA,downloadSample:()=>Fh,firstLineDigest:()=>Ge,git:()=>Me,gitChangedFiles:()=>ph,gitDiff:()=>mh,info:()=>BA,isHiddenTurn:()=>Rn,launchBulb:()=>Nh,listBreakouts:()=>Oh,listBulbFiles:()=>Ch,listMyBulbs:()=>qh,listSamples:()=>jh,listSessions:()=>qA,listSwitchModels:()=>TA,logEmbedStatus:()=>FA,openFile:()=>Th,poll:()=>jA,predictTrustOf:()=>Ih,probeModel:()=>MA,pullRemoteBulb:()=>Uh,pushLocalBulb:()=>Kh,readBulbLog:()=>Lh,repoRoot:()=>Or,saveOpenRouterKey:()=>RA,searchBulbs:()=>Rh,searchSessions:()=>UA,sessionPeek:()=>JA,setBulbTrust:()=>$h,setReasoning:()=>_A,setSwitchModel:()=>OA,shutdownSwitcher:()=>NA,stopBreakout:()=>_h,switchState:()=>PA,toolResultDigest:()=>nl});var ng,DA,BA,jA,FA,qA,UA,JA,KA,HA,ig=A(()=>{Al();Ri();Nl();Qi();rg();Ri();Oi();ng=new Sr,DA=ng.displayName,{info:BA,poll:jA,logEmbedStatus:FA,listSessions:qA,searchSessions:UA,sessionPeek:JA,attach:KA,composerPasteRead:HA}=so(ng)});import{readFileSync as WA,writeFileSync as YA,mkdirSync as VA}from"fs";import{homedir as GA}from"os";import*as fo from"path";async function cg(){try{let r=await fetch(new URL("/api/tags",ag()).toString(),{signal:AbortSignal.timeout(zA)});return r.ok?((await r.json()).models??[]).map(t=>t.name).filter(t=>!!t):[]}catch{return[]}}function lg(r){let e;try{e=WA(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&&!jl(n)}}}catch{}return{json:void 0,unreadable:!0}}function jl(r){let e=r?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function XA(r){let e=jl(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 ug(){let{json:r,unreadable:e}=lg(og());return e?{installed:[],configured:null}:{installed:await cg(),configured:XA(r)}}async function dg(){let r=await cg();return r.length?QA(og(),r,ag()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function QA(r,e,t){let{json:n,unreadable:s}=lg(r);if(s)return{ok:!1,error:`could not parse ${r} \u2014 edit the ollama provider there yourself`};let i={...n??{},providers:{...jl(n)??{},ollama:{baseUrl:`${t}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{VA(fo.dirname(r),{recursive:!0}),YA(r,JSON.stringify(i,null,2)+`
|
|
580
|
+
`)}catch(o){return{ok:!1,error:`could not write ${r}: ${U(o)}`}}return{ok:!0,count:e.length}}var zA,og,ag,fg=A(()=>{bt();Tr();zA=1500,og=()=>fo.join(GA(),".pi","agent","models.json"),ag=()=>yr(process.env.OLLAMA_HOST??"http://localhost:11434")});var mg={};cu(mg,{attach:()=>oT,breakout:()=>Ph,composerFiles:()=>uT,composerNew:()=>lT,composerPaste:()=>pT,composerPasteRead:()=>mT,composerRpc:()=>fT,composerSend:()=>aT,composerStop:()=>cT,composerUiRespond:()=>dT,displayName:()=>ZA,downloadSample:()=>Fh,git:()=>Me,gitChangedFiles:()=>ph,gitDiff:()=>mh,info:()=>eT,launchBulb:()=>Nh,listBreakouts:()=>Oh,listBulbFiles:()=>Ch,listMyBulbs:()=>qh,listSamples:()=>jh,listSessions:()=>nT,logEmbedStatus:()=>rT,ollamaOffer:()=>ug,ollamaSync:()=>dg,openFile:()=>Th,poll:()=>tT,predictTrustOf:()=>Ih,pullRemoteBulb:()=>Uh,pushLocalBulb:()=>Kh,readBulbLog:()=>Lh,repoRoot:()=>Or,searchBulbs:()=>Rh,searchSessions:()=>sT,sessionPeek:()=>iT,setBulbTrust:()=>$h,shutdownComposer:()=>hT,stopBreakout:()=>_h});var pg,ZA,eT,tT,rT,nT,sT,iT,oT,aT,cT,lT,uT,dT,fT,pT,mT,hT,hg=A(()=>{Al();xl();Nl();Qi();fg();pg=new Pr,ZA=pg.displayName,{info:eT,poll:tT,logEmbedStatus:rT,listSessions:nT,searchSessions:sT,sessionPeek:iT,attach:oT,composerSend:aT,composerStop:cT,composerNew:lT,composerFiles:uT,composerUiRespond:dT,composerRpc:fT,composerPaste:pT,composerPasteRead:mT,shutdownComposer:hT}=so(pg)});import*as xy from"fs/promises";import*as Gt from"path";import*as yu from"path";import*as uu from"fs/promises";import{existsSync as zt,readFileSync as Hy}from"fs";import*as X from"path";import{pathToFileURL as Wy}from"url";import{resolve as Ro}from"resolve.exports";import{init as du,parse as fu}from"es-module-lexer";function pu(r,e){let t=X.join(r,"package.json");try{return JSON.parse(Hy(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}var Co=["browser","import","default"],lu=["node","import","default"];function mu(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:X.resolve(n)}}async function hu(r){let{name:e,dir:t}=r;if(!zt(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let n=pu(t,e),s=Yy(n,e),i=X.resolve(t,s);if(!zt(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=X.dirname(i),a=`/local/${e}/${X.basename(i)}`,c=Vy(n,t);return await Gy(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:c}}function Yy(r,e){if(r.exports!==void 0){let n;try{n=Ro(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=No(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 Vy(r,e){if(r.exports!==void 0)try{let n=Ro(r,".",{conditions:["types"]}),s=No(n);if(s){let i=X.resolve(e,s);if(zt(i))return i}}catch{}let t=r.types??r.typings;if(t){let n=X.resolve(e,t);if(zt(n))return n}}function No(r){if(typeof r=="string")return r;if(Array.isArray(r))return r.find(e=>typeof e=="string")}async function Gy(r,e,t){await du;let n=X.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 uu.readFile(o,"utf8")}catch{continue}let c,l;try{[c,,,l]=fu(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=zy(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 zy(r,e,t){let n=e.replace(/[?#].*$/,""),s=X.resolve(X.dirname(r),n),i=[s,s+".js",s+".mjs",X.join(s,"index.js"),X.join(s,"index.mjs")];for(let o of i)if(X.normalize(o).startsWith(t)&&zt(o))return o}function Xy(r,e,t){let n=pu(r,e),s;if(n.exports!==void 0)try{s=No(Ro(n,t,{conditions:lu}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${lu.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=X.resolve(r,s);if(!zt(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return Wy(i).href}async function gu(r,e){await du;let t;try{[t]=fu(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=Xy(e.dir,e.name,a);n+=r.slice(s,i.s)+c,s=i.e}return n+r.slice(s)}var Io=5e3;function bu(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||yu.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=Io;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=mu(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 wu(){console.log(`
|
|
580
581
|
typebulb - Local bulb runner for Typebulb
|
|
581
582
|
|
|
582
583
|
Usage:
|
|
@@ -726,11 +727,11 @@ Examples:
|
|
|
726
727
|
typebulb my-editor.bulb.md
|
|
727
728
|
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
728
729
|
typebulb .
|
|
729
|
-
`)}gn();import*as
|
|
730
|
+
`)}gn();import*as mt from"fs/promises";import*as ie from"path";import{pathToFileURL as Bk}from"url";import{transform as Bx}from"sucrase";function Ac(r,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:n}=Bx(r,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:n}}catch(n){return{code:"",error:String(n)}}}Qs();function Hx(r){return r.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
730
731
|
`)[0]}`).join(`
|
|
731
|
-
`)}function
|
|
732
|
-
${Kx(t)}`)}var ct="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Ac="https://data.jsdelivr.com/v1/package/npm/";function Ip(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=cr(t??s.version),this.subpath=cr(n??s.subpath)}static parse(e){let t=Ip(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=$p(t[1]??""),a=cr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=$p(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(ct).host,s=new URL(bn).host;if(t.host===n){let i=Ip(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,$p=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),cr(r.slice(e+1))]};async function le(r){try{return await r()}catch{return}}function Ct(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Tc(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(Ct(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(",")),`${ct}/${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),`${ct}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await le(()=>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 le(()=>this.http.getJson(`${Ac}${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:f,peerDependencies:u,peerDependenciesMeta:d}=n;return{name:e,version:t,dependencies:f,peerDependencies:u,peerDependenciesMeta:d}}let s=this.packageJson(new D(`${e}@${t}`)),i=await le(()=>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 Lp=r=>r.startsWith("@types/"),vn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!Lp(e)),Pc=r=>Object.keys(r?.dependencies||{}).filter(e=>!Lp(e)),Hx=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 Hx(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 Pc(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 xn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await le(()=>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 le(()=>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 le(()=>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 le(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as Wx,parse as Yx}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))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 Wx;let[s]=Yx(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)),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(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,f=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:x,isSharedDep:k}=n.get(y),T=a.has(y),P=p!==y,O=!(b||k)&&(T||!x),N=this.singletonDepsOf(m,o),h=P&&f.has(y);h&&u.add(y);let S=h?[...N,y]:N.length?N: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}/`,`${ct}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...vn(e.meta),...Pc(e.meta)])].filter(n=>t.has(n))}};lr.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as Mp,satisfies as Vx,maxSatisfying as Dp,major as Gx,valid as zx}from"semver";var Zs=class{cmp(e,t){return e===t?0:Mp(e,t)?1:Mp(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Vx(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=Dp(e,n,{includePrerelease:!1});if(a)return a}return Dp(e,n,{includePrerelease:!0})??void 0}majorOf(e){return Gx(e)}isExactVersion(e){return zx(e)!==null}},Rt=new Zs;var Nt=class{constructor(e){this.store=e}async isNegative(e){let t=await le(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await le(()=>this.store.get(e)))?.attempts||0)+1;await le(()=>this.store.set(e,{until:Date.now()+Xx(n),attempts:n}))}async clearNegative(e){await le(()=>this.store.delete(e))}};function Xx(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}function Bp(r,e){let t=new wn(r,e),n=new Sn(t),s=new xn(r,t,Rt);return{packageService:new lr(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as Hp from"fs/promises";import*as Se from"path";import*as ut from"fs/promises";import*as Je from"path";import*as qp from"os";import*as Oc from"fs/promises";import*as jp from"crypto";function ve(r){return jp.createHash("sha1").update(r).digest("hex")}async function Ue(r){try{return JSON.parse(await Oc.readFile(r,"utf8"))}catch{return}}async function ei(r){try{return await Oc.readFile(r,"utf8")}catch{return}}var Fp=1,lt=Je.join(qp.homedir(),".typebulb","cache"),kn=Je.join(lt,"packages"),En=Je.join(lt,"proxy"),ti=Je.join(lt,"dts"),Qx=Je.join(lt,"emit"),_c;function V(){return _c||(_c=Zx()),_c}function ri(r,e){return Je.join(Qx,ve(r),e)}async function Zx(){await ut.mkdir(lt,{recursive:!0});let r=Je.join(lt,"version.json");if((await Ue(r))?.version===Fp)return;let t=await ut.readdir(lt).catch(()=>[]);await Promise.all(t.map(n=>ut.rm(Je.join(lt,n),{recursive:!0,force:!0}))),await ut.writeFile(r,JSON.stringify({version:Fp})+`
|
|
733
|
-
`,"utf8")}import*as
|
|
732
|
+
`)}function Ip(r,e){let t=yn(r,{target:"client",dependencies:e}).filter(n=>n.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
733
|
+
${Hx(t)}`)}var lt="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Tc="https://data.jsdelivr.com/v1/package/npm/";function $p(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=$p(e||"");if(!t.length)return new r({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=Lp(t[1]??""),a=lr(t.slice(2).join("/"));return new r({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Lp(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(lt).host,s=new URL(bn).host;if(t.host===n){let i=$p(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,Lp=r=>{let e=r.indexOf("@");return e<0?[r,void 0]:[r.slice(0,e),lr(r.slice(e+1))]};async function le(r){try{return await r()}catch{return}}function Rt(r){let e=r||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Pc(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(Rt(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(",")),`${lt}/${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),`${lt}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let n=await le(()=>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 le(()=>this.http.getJson(`${Tc}${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:f,peerDependencies:u,peerDependenciesMeta:d}=n;return{name:e,version:t,dependencies:f,peerDependencies:u,peerDependenciesMeta:d}}let s=this.packageJson(new D(`${e}@${t}`)),i=await le(()=>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 Mp=r=>r.startsWith("@types/"),vn=r=>Object.keys(r?.peerDependencies||{}).filter(e=>!Mp(e)),Oc=r=>Object.keys(r?.dependencies||{}).filter(e=>!Mp(e)),Wx=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 Wx(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 Oc(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 xn=class{constructor(e,t,n){this.cache=e,this.cdn=t,this.semver=n}async learnExactVersion(e){let t=await le(()=>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 le(()=>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 le(()=>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 le(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?n.withVersion(o).format():e,root:s,range:i,pinned:o}}};import{init as Yx,parse as Vx}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 Yx;let[s]=Vx(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)),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(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,f=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:x,isSharedDep:k}=n.get(y),T=a.has(y),P=p!==y,_=!(b||k)&&(T||!x),N=this.singletonDepsOf(m,o),h=P&&f.has(y);h&&u.add(y);let v=h?[...N,y]:N.length?N:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:_,external:v})]),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}/`,`${lt}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...vn(e.meta),...Oc(e.meta)])].filter(n=>t.has(n))}};ur.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g];import{gt as Dp,satisfies as Gx,maxSatisfying as Bp,major as zx,valid as Xx}from"semver";var Zs=class{cmp(e,t){return e===t?0:Dp(e,t)?1:Dp(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!Gx(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=Bp(e,n,{includePrerelease:!1});if(a)return a}return Bp(e,n,{includePrerelease:!0})??void 0}majorOf(e){return zx(e)}isExactVersion(e){return Xx(e)!==null}},Nt=new Zs;var It=class{constructor(e){this.store=e}async isNegative(e){let t=await le(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let n=((await le(()=>this.store.get(e)))?.attempts||0)+1;await le(()=>this.store.set(e,{until:Date.now()+Qx(n),attempts:n}))}async clearNegative(e){await le(()=>this.store.delete(e))}};function Qx(r){return Math.min(9e5*Math.pow(2,Math.max(0,r-1)),864e5)}function jp(r,e){let t=new wn(r,e),n=new Sn(t),s=new xn(r,t,Nt);return{packageService:new ur(s,t,n),versionResolver:s,cdnClient:t,peerResolver:n}}import*as Wp from"fs/promises";import*as Se from"path";import*as dt from"fs/promises";import*as Ke from"path";import*as Up from"os";import*as _c from"fs/promises";import*as Fp from"crypto";function ve(r){return Fp.createHash("sha1").update(r).digest("hex")}async function Je(r){try{return JSON.parse(await _c.readFile(r,"utf8"))}catch{return}}async function ei(r){try{return await _c.readFile(r,"utf8")}catch{return}}var qp=1,ut=Ke.join(Up.homedir(),".typebulb","cache"),kn=Ke.join(ut,"packages"),En=Ke.join(ut,"proxy"),ti=Ke.join(ut,"dts"),Zx=Ke.join(ut,"emit"),Cc;function V(){return Cc||(Cc=ek()),Cc}function ri(r,e){return Ke.join(Zx,ve(r),e)}async function ek(){await dt.mkdir(ut,{recursive:!0});let r=Ke.join(ut,"version.json");if((await Je(r))?.version===qp)return;let t=await dt.readdir(ut).catch(()=>[]);await Promise.all(t.map(n=>dt.rm(Ke.join(ut,n),{recursive:!0,force:!0}))),await dt.writeFile(r,JSON.stringify({version:qp})+`
|
|
734
|
+
`,"utf8")}import*as ft from"fs/promises";import*as Jp from"path";async function me(r,e){await ft.mkdir(Jp.dirname(r),{recursive:!0});let t=`${r}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await ft.writeFile(t,e,"utf8"),await ft.rename(t,r).catch(async n=>{throw await ft.rm(t,{force:!0}).catch(()=>{}),n})}var dr=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 Rc=Se.join(kn,"indexes"),Kp=Se.join(kn,"pinned"),tk=Se.join(kn,"meta"),rk=Se.join(kn,"negative.json"),si=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new It(new dr(rk));async getPinnedExact(e,t){let n=`${e}@${t}`;if(this.pinnedMem.has(n))return this.pinnedMem.get(n);await V();let s=await ei(Se.join(Kp,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 V(),await me(Se.join(Kp,ve(s)+".txt"),n)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await V();let t=await Je(Se.join(Rc,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 V(),await me(Se.join(Rc,ni(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await Wp.rm(Se.join(Rc,ni(e)+".json"),{force:!0})}async isNegative(e){return await V(),this.negativeCache.isNegative(e)}async recordNegative(e){await V(),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 V();let s=await Je(Hp(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 V(),await me(Hp(e,t),JSON.stringify(o))}};function Hp(r,e){return Se.join(tk,ni(r),encodeURIComponent(e)+".json")}function ni(r){return r.replace(/\//g,"__")}var Yp={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 nk=new si,{packageService:ii,versionResolver:Vp,cdnClient:Gp,peerResolver:XC}=jp(nk,Yp);var zp=`
|
|
734
735
|
(() => {
|
|
735
736
|
// Embedded (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
|
|
736
737
|
// bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
|
|
@@ -1219,18 +1220,18 @@ ${Kx(t)}`)}var ct="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Ac="https:
|
|
|
1219
1220
|
};
|
|
1220
1221
|
}
|
|
1221
1222
|
})();
|
|
1222
|
-
`;var
|
|
1223
|
+
`;var $t=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; }
|
|
1223
1224
|
canvas { max-width: 100%; }
|
|
1224
1225
|
body { margin: 0; display: flow-root; font-family: system-ui, -apple-system, sans-serif; }
|
|
1225
1226
|
html[data-theme="dark"] { color-scheme: dark; }
|
|
1226
1227
|
html[data-theme="light"] { color-scheme: light; }`;function ci(r,e){return` <script>
|
|
1227
1228
|
(function() {
|
|
1228
1229
|
try {
|
|
1229
|
-
var KEY = ${
|
|
1230
|
+
var KEY = ${$t(JSON.stringify("tb-theme:"+r))};
|
|
1230
1231
|
var doc = document.documentElement;
|
|
1231
1232
|
var mq = window.matchMedia('(prefers-color-scheme: dark)');
|
|
1232
1233
|
var os = function() { return mq.matches ? 'dark' : 'light'; };
|
|
1233
|
-
var FORCED = ${
|
|
1234
|
+
var FORCED = ${$t(JSON.stringify(e??null))};
|
|
1234
1235
|
var stored = function() {
|
|
1235
1236
|
try { var v = localStorage.getItem(KEY); return (v === 'dark' || v === 'light') ? v : undefined; }
|
|
1236
1237
|
catch (e) { return undefined; }
|
|
@@ -1258,8 +1259,8 @@ ${Kx(t)}`)}var ct="https://esm.sh",bn="https://cdn.jsdelivr.net/npm/",Ac="https:
|
|
|
1258
1259
|
});
|
|
1259
1260
|
} catch (e) {}
|
|
1260
1261
|
})();
|
|
1261
|
-
</script>`}function
|
|
1262
|
-
html, body { height: 100%; }`,p={imports:
|
|
1262
|
+
</script>`}function Xp(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?"":`
|
|
1263
|
+
html, body { height: 100%; }`,p={imports:ik(a.imports)};return`<!DOCTYPE html>
|
|
1263
1264
|
<html>
|
|
1264
1265
|
<head>
|
|
1265
1266
|
<meta charset="utf-8">
|
|
@@ -1279,23 +1280,23 @@ ${n}
|
|
|
1279
1280
|
<body>
|
|
1280
1281
|
${u}
|
|
1281
1282
|
|
|
1282
|
-
${i.length>0?`<script>window.__TB_DATA__ = ${
|
|
1283
|
-
${o?`<script>window.__TB_INSIGHT__ = ${
|
|
1284
|
-
${f?`<script>window.__TB_DIR__ = ${
|
|
1283
|
+
${i.length>0?`<script>window.__TB_DATA__ = ${$t(JSON.stringify(i))};</script>`:""}
|
|
1284
|
+
${o?`<script>window.__TB_INSIGHT__ = ${$t(JSON.stringify(o))};</script>`:""}
|
|
1285
|
+
${f?`<script>window.__TB_DIR__ = ${$t(JSON.stringify(f))};</script>`:""}
|
|
1285
1286
|
|
|
1286
1287
|
<script>
|
|
1287
|
-
${
|
|
1288
|
+
${zp}
|
|
1288
1289
|
</script>
|
|
1289
1290
|
|
|
1290
|
-
${
|
|
1291
|
+
${sk}
|
|
1291
1292
|
|
|
1292
1293
|
<script type="module">
|
|
1293
1294
|
globalThis.__tbEntryRan = true; /* import graph resolved \u2014 the load-failure backstop's signal (imports hoist above this line) */
|
|
1294
1295
|
await globalThis.__tbBoot; /* #tb= fragment restore, set by the shim when present (TB-Inference.md) */
|
|
1295
|
-
${
|
|
1296
|
+
${$t(t)}
|
|
1296
1297
|
</script>
|
|
1297
1298
|
</body>
|
|
1298
|
-
</html>`}var
|
|
1299
|
+
</html>`}var sk=`<script>
|
|
1299
1300
|
(function () {
|
|
1300
1301
|
var framed = window.parent !== window;
|
|
1301
1302
|
var post = function (m) { try { parent.postMessage(m, '*'); } catch (e) {} }; /* framed only */
|
|
@@ -1391,8 +1392,8 @@ ${It(t)}
|
|
|
1391
1392
|
}
|
|
1392
1393
|
});
|
|
1393
1394
|
})();
|
|
1394
|
-
</script>`;function
|
|
1395
|
-
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");
|
|
1395
|
+
</script>`;function ik(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 Qp,readFileSync as ok}from"fs";import{execFile as ak}from"child_process";import{promisify as ck}from"util";import{satisfies as lk}from"semver";var uk=ck(ak),dk=/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+(@[a-zA-Z0-9.^~*x-]+)?$/i;async function di(r,e,t,n){let i=r.map(l=>fk(l,t)).filter(l=>!pk(l,e));if(i.length===0)return;let o=i.filter(l=>!dk.test(l));if(o.length)throw new Error(`Refusing to install npm spec(s) with unsupported characters: ${o.join(", ")}
|
|
1396
|
+
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");Qp(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 uk("npm",["install",...c,...i],{cwd:e,shell:!0})}function fk(r,e){if(!e||D.parse(r).version)return r;let t=e[r];return t?`${r}@${t}`:r}function pk(r,e){let{name:t,version:n}=D.parse(r),s=li.join(e,"node_modules",t);if(!Qp(s))return!1;if(!n)return!0;try{let i=JSON.parse(ok(li.join(s,"package.json"),"utf-8")).version;return lk(i,n)}catch{return!1}}function fi(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(D.rootOf(s))}return[...e]}hr();Si();Bt();import*as br from"fs/promises";import*as Ye from"path";function xi(r,e,t=e){let n=Ye.resolve(e,r),s=Ye.normalize(t),i=Ye.normalize(n);if(i!==s&&!i.startsWith(s+Ye.sep))throw new Error("Path traversal detected - access denied");return n}async function On(r,e,t){return br.readFile(xi(r,e,t))}async function ki(r,e,t,n){let s=xi(r,t,n);await br.mkdir(Ye.dirname(s),{recursive:!0}),await br.writeFile(s,typeof e=="string"?e:Buffer.from(e))}async function lm(r){let e=We(r.provider,r.model);if(typeof e=="string")throw new Error(e);let t=await pt(e,r);if(!t.ok){let n=await mr(t,e.protocol);throw new Error(n.message)}return{response:t,protocol:e.protocol}}async function Mk(r){let{response:e,protocol:t}=await lm(r);return{text:await Mt(e,t)}}async function*Dk(r){let{response:e,protocol:t}=await lm(r);yield*Dt(e,t)}function um(r,e=process.cwd()){let t=Object.assign(Mk,{stream:Dk}),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 ki(s,i,r,e),!0)};globalThis.tb=Object.freeze({ai:t,fs:n,dir:r,models:()=>He(),hasOwnKeys:vi,mode:"local"})}async function dm(r){let t=(await mt.readdir(r)).find(n=>n.endsWith(".bulb.md"));return t?ie.join(r,t):null}function Ei(r,e){let t=ie.resolve(r),n=ie.join(ie.dirname(t),ie.basename(t).replace(/\.bulb\.md$/,""));return e?ie.join(n,e):n}async function ke(r){let e=await mt.readFile(r,"utf-8"),t=fe(e);if(!t)throw new Error("Invalid .bulb.md file format");let n=cr(t);return{bulb:n,config:Lr(n.config),warnings:Eu(e)}}function Yc(r){let e=ie.basename(r).replace(/\.bulb\.md$/i,"");return ie.join(ie.dirname(r),".typebulb",`${e}.server.mjs`)}async function _n(r,e,t,n,s){let i=Ac(r,{serverOnly:!0});if(i.error)throw new Error(`Server compilation error: ${i.error}`);let o=i.code;t&&(o=await gu(o,t));let a=ie.join(ie.dirname(e),".typebulb");await mt.mkdir(a,{recursive:!0});let c=fi(o);c.length>0&&await di(c,a,n);let l=Yc(e);return await mt.writeFile(l,o,"utf-8"),um(Ei(e,s)),await import(`${Bk(l).href}?t=${Date.now()}`)}async function Vc(r,e,t,n,s){let{bulb:i,config:o}=await ke(r),a=zs(i.data);Ip(i.code,o.dependencies??{});let c=Ac(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=Xp({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 _n(i.server,r,n,o.dependencies,s)),{html:f,bulb:i,serverExports:u}}gn();Cn();Ri();xl();var po={claude:{adapter:()=>new Sr,server:()=>Promise.resolve().then(()=>(ig(),sg))},pi:{adapter:()=>new Pr,server:()=>Promise.resolve().then(()=>(hg(),mg))}};function gg(r){return r in po}function Rr(){return Object.keys(po)}function yg(){return Object.fromEntries(Object.entries(po).map(([r,e])=>[r,e.adapter]))}function bg(r){return po[r].server()}import*as xt from"path";import{spawn as FT,execSync as qT}from"child_process";import{createRequire as UT}from"module";import{existsSync as JT}from"fs";import*as oe from"fs/promises";import*as ne from"path";var Fl=[{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"}],ql=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function Ul(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 gT=`
|
|
1396
1397
|
/**
|
|
1397
1398
|
* Get raw data chunk from the Data tab.
|
|
1398
1399
|
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
@@ -1403,7 +1404,7 @@ ${It(t)}
|
|
|
1403
1404
|
* @param index - Chunk index (0-based)
|
|
1404
1405
|
* @throws If chunk is not valid JSON/JSON-ish
|
|
1405
1406
|
*/
|
|
1406
|
-
json<T = unknown>(index: number): T;`,
|
|
1407
|
+
json<T = unknown>(index: number): T;`,yT=`
|
|
1407
1408
|
/**
|
|
1408
1409
|
* Get the insight data produced by the inference layer.
|
|
1409
1410
|
*
|
|
@@ -1412,7 +1413,7 @@ ${It(t)}
|
|
|
1412
1413
|
*
|
|
1413
1414
|
* @returns The parsed insight JSON, or undefined if no insight is available
|
|
1414
1415
|
*/
|
|
1415
|
-
insight<T = unknown>(): T | undefined;`,
|
|
1416
|
+
insight<T = unknown>(): T | undefined;`,wg=`options: {
|
|
1416
1417
|
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
1417
1418
|
system?: string;
|
|
1418
1419
|
/** 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. */
|
|
@@ -1423,12 +1424,12 @@ ${It(t)}
|
|
|
1423
1424
|
webSearch?: boolean;
|
|
1424
1425
|
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
1425
1426
|
signal?: AbortSignal;
|
|
1426
|
-
}`,
|
|
1427
|
+
}`,vg=`
|
|
1427
1428
|
/** A single streamed delta from \`tb.ai.stream()\`. Discriminated by \`kind\`. */
|
|
1428
1429
|
type AiChunk =
|
|
1429
1430
|
| { kind: "text"; text: string }
|
|
1430
1431
|
| { kind: "reasoning"; text: string };
|
|
1431
|
-
`,
|
|
1432
|
+
`,Sg=`
|
|
1432
1433
|
/**
|
|
1433
1434
|
* General-purpose AI call. \`tb.ai(opts)\` resolves with the full text; \`tb.ai.stream(opts)\`
|
|
1434
1435
|
* returns an async iterable of {@link AiChunk} deltas you consume with \`for await\`.
|
|
@@ -1437,7 +1438,7 @@ type AiChunk =
|
|
|
1437
1438
|
* @throws On rate limit, network error, or provider error
|
|
1438
1439
|
*/
|
|
1439
1440
|
ai: {
|
|
1440
|
-
(${
|
|
1441
|
+
(${wg}): Promise<{ text: string }>;
|
|
1441
1442
|
/**
|
|
1442
1443
|
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
1443
1444
|
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
@@ -1451,8 +1452,8 @@ type AiChunk =
|
|
|
1451
1452
|
* if (c.kind === "text") answer += c.text;
|
|
1452
1453
|
* }
|
|
1453
1454
|
*/
|
|
1454
|
-
stream(${
|
|
1455
|
-
};`,
|
|
1455
|
+
stream(${wg}): AsyncIterable<AiChunk>;
|
|
1456
|
+
};`,xg=`
|
|
1456
1457
|
/**
|
|
1457
1458
|
* Returns AI models available to the current user.
|
|
1458
1459
|
* Models are filtered by the user's configured API keys.
|
|
@@ -1476,7 +1477,7 @@ type AiChunk =
|
|
|
1476
1477
|
* making many AI calls should check this and show a "use your own keys"
|
|
1477
1478
|
* notice instead of running.
|
|
1478
1479
|
*/
|
|
1479
|
-
hasOwnKeys(): Promise<boolean>;`,
|
|
1480
|
+
hasOwnKeys(): Promise<boolean>;`,bT="\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;",kg=`
|
|
1480
1481
|
/**
|
|
1481
1482
|
* The mode this bulb is running in.
|
|
1482
1483
|
*
|
|
@@ -1486,7 +1487,7 @@ type AiChunk =
|
|
|
1486
1487
|
* - \`'embedded'\` \u2014 Running as a bulb embedded inside another bulb (sandboxed,
|
|
1487
1488
|
* client-only: AI, filesystem, and server RPC are unavailable)
|
|
1488
1489
|
*/
|
|
1489
|
-
mode: 'local' | 'editor' | 'published' | 'embedded';`,
|
|
1490
|
+
mode: 'local' | 'editor' | 'published' | 'embedded';`,Eg=`
|
|
1490
1491
|
/**
|
|
1491
1492
|
* Local filesystem access (CLI only).
|
|
1492
1493
|
*
|
|
@@ -1503,7 +1504,7 @@ type AiChunk =
|
|
|
1503
1504
|
readBytes(path: string): Promise<Uint8Array>;
|
|
1504
1505
|
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
1505
1506
|
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
1506
|
-
};`,
|
|
1507
|
+
};`,Ag=`
|
|
1507
1508
|
/**
|
|
1508
1509
|
* The bulb's folder \u2014 absolute path to \`<bulb-dir>/<filename-stem>/\`
|
|
1509
1510
|
* (or its subfolder when the run is scoped with \`--dir\`).
|
|
@@ -1512,7 +1513,7 @@ type AiChunk =
|
|
|
1512
1513
|
* \`tb.fs\` already resolves relative paths against it, so bulb code writing
|
|
1513
1514
|
* its own files never needs it. CLI only \u2014 throws in editor/published/embedded mode.
|
|
1514
1515
|
*/
|
|
1515
|
-
readonly dir: string;`,
|
|
1516
|
+
readonly dir: string;`,wT=`
|
|
1516
1517
|
/**
|
|
1517
1518
|
* Async value inspector for tensor-like objects.
|
|
1518
1519
|
*
|
|
@@ -1579,39 +1580,39 @@ type AiChunk =
|
|
|
1579
1580
|
*
|
|
1580
1581
|
* @returns The full canonical URL
|
|
1581
1582
|
*/
|
|
1582
|
-
url(): Promise<string>;`,
|
|
1583
|
+
url(): Promise<string>;`,vT="\n /**\n * Subscribe to a value pushed from the terminal via `typebulb send <file> [message]`.\n *\n * The dual of `tb.server.log` (data out): a value sent *in* from the CLI, no `--trust` required.\n * Use it to start expensive work on demand instead of on load \u2014 e.g. `tb.onMessage(() => start())`\n * \u2014 so hot reloads don't re-trigger it while you edit, and an agent kicks off one run when ready.\n *\n * The message is the JSON-parsed value of what `send` was given (or the raw string if it isn't\n * JSON; `undefined` for a bare `typebulb send <file>`). A non-`undefined` return value (awaited)\n * becomes the reply `send --wait` prints on stdout \u2014 JSON-serializable, at most one handler\n * replying \u2014 the structured read-back for self-tests. Returns an unsubscribe function. Inert in\n * an embedded bulb (no sender) \u2014 the handler is registered but never fires.\n *\n * @param handler - Called with each pushed message; may return a JSON-serializable reply.\n * @returns An unsubscribe function.\n */\n onMessage(handler: (message: any) => unknown): () => void;",ST="\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>>;",Jl=`${vg}
|
|
1583
1584
|
/**
|
|
1584
1585
|
* Typebulb utilities namespace.
|
|
1585
1586
|
* Type \`tb.\` to discover available helpers.
|
|
1586
1587
|
*/
|
|
1587
|
-
declare const tb: {${
|
|
1588
|
+
declare const tb: {${gT}${wT}${yT}${ST}${vT}${Sg}${Eg}${Ag}${xg}${bT}${kg}
|
|
1588
1589
|
};
|
|
1589
|
-
`,
|
|
1590
|
+
`,Kl=`${vg}
|
|
1590
1591
|
/**
|
|
1591
1592
|
* Typebulb utilities namespace (server-side).
|
|
1592
1593
|
* Type \`tb.\` to discover available helpers.
|
|
1593
1594
|
*/
|
|
1594
|
-
declare const tb: {${
|
|
1595
|
+
declare const tb: {${Sg}${Eg}${Ag}${xg}${kg}
|
|
1595
1596
|
};
|
|
1596
|
-
`;import
|
|
1597
|
+
`;import AT from"p-limit";import{resolve as Pg}from"resolve.exports";var ze={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},Fn=["index.d.ts","index.d.mts"],Hl=/\.d\.(ts|mts|cts)$/i;function mo(r){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(r)||/[?&]dts(?:[&#]|$)/i.test(r)}function Tg(r){return[`${r}.d.ts`,`${r}.d.mts`]}function St(r){if(!r||r==="./"||r==="/")return[...Fn];let e=r.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=Tg(e),n=e.endsWith("/")?e:`${e}/`;return t.push(...Tg(`${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(xT(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function xT(r){return r===408||r===429||r>=500&&r<600}var ho=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)||mo(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 D({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 D({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=Rt(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([...Fn],t);if(!Hl.test(o)){let a=await this.tryUntilSuccess(St(o),t);if(a)return a}return t(o)}let s=St(e.path),i=n?.subpath?[...s,...Fn]:[...Fn,...s];return this.tryUntilSuccess(i,t)}toResolutionResult(e){return{kind:Hl.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let n=t||".",s=e;try{let i=this.extractPathFromResult(Pg(s,n,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(Pg(s,n,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=D.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 D(i).format(),a=new D({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=Pc(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(St(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=Rt(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 kT}from"fflate";var go=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=kT(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 yo=class{constructor(e,t,n=new go){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=Nt.majorOf(n),o=e.filter(a=>Nt.majorOf(a)===i);if(o.length)return o.sort((a,c)=>Nt.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=St(e);return t!==e&&n.push(`${e}.d.ts`,`${e}/index.d.ts`),n}async fetchFromVersionedRoot(e,t){let n=new D(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 D(t).format():t.name}}}async resolve(e){let t=D.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 bo=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(`
|
|
1597
1598
|
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
1598
|
-
`),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
|
|
1599
|
-
`);await this.prefetchBareDeps(y,l,d,p,s);let m=c.format(),b=e===m?[e]:[e,m],x=b.some(k=>this.ambientlyDeclares(i,k));return x?this.markFileAmbient(d,f):p.push(...b.map(k=>({module:k,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:x}}};import*as Ir from"path";var
|
|
1600
|
-
`,"utf8"),await oe.writeFile(ne.join(e,"code.tsx"),r.code,"utf8"),await oe.writeFile(ne.join(e,"tb.d.ts"),
|
|
1601
|
-
`,"utf8"),{dir:e}}function
|
|
1602
|
-
`))console.log(`${e} ${n}`);return r.length>0}function
|
|
1599
|
+
`),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 Og="file:///node_modules",wo=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${Og}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let n=Rt(t);return`${Og}/${this.epochDir()}/${e}/${n}`}};import{LRUCache as ET}from"lru-cache";function _g(r){let e=new ET({ttl:ze.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 bo,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=_g(e.cache),this.typescriptProvider=new ho(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new yo(e.cdnClient,e.cache),this.virtualFs=new wo}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 D(n).subpath===new D(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>ze.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,ze.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=mo(c)?[c]:St(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 D(e).name!==new D(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,ze.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=AT(ze.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,n,s,ze.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,ze.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 D(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 D(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(k=>k.content).join(`
|
|
1600
|
+
`);await this.prefetchBareDeps(y,l,d,p,s);let m=c.format(),b=e===m?[e]:[e,m],x=b.some(k=>this.ambientlyDeclares(i,k));return x?this.markFileAmbient(d,f):p.push(...b.map(k=>({module:k,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:x}}};import*as Ir from"path";var TT=Ir.join(ti,"pkg"),PT=Ir.join(ti,"files"),OT=Ir.join(ti,"negative.json"),So=class{pkgMem=new Map;fileMem=new Map;negativeCache=new It(new dr(OT));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await V();let t=await Je(Cg(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 vo(async()=>{await V(),await me(Cg(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await V();let t=await ei(Rg(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await vo(async()=>{await V(),await me(Rg(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await vo(async()=>{await V(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return vo(()=>this.negativeCache.clearNegative(e))}};async function vo(r){try{await r()}catch{}}function Cg(r){return Ir.join(TT,ve(r)+".json")}function Rg(r){return Ir.join(PT,ve(r)+".txt")}var Wl;function _T(){return Wl||(Wl=new qn({cache:new So,cdnClient:Gp,packageService:ii,versionResolver:Vp})),Wl}var Ng="file:///node_modules/";async function Ig(r){let e=ri(r.emitKey,"typecheck");await V(),await oe.rm(e,{recursive:!0,force:!0}),await oe.mkdir(e,{recursive:!0});let t=IT(r.jsxImportSource,r.dependencies),n=await _T().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=xo(u.path);if(!d||o.has(d))continue;o.add(d);let p=ne.join(e,"node_modules",d);await oe.mkdir(ne.dirname(p),{recursive:!0}),await oe.writeFile(p,u.content,"utf8")}let a={};for(let f of i)for(let u of f.shims){let d=xo(u.path);d&&(a[u.module]=[`./node_modules/${d}`])}for(let f of i){if(f.ambient)continue;let u=xo(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=xo(u.path);d&&c.add(`node_modules/${d}`)}if(r.local){delete a[r.local.name];let f=await $T(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=CT(r.jsxImportSource,a,[...c]);return await oe.writeFile(ne.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
1601
|
+
`,"utf8"),await oe.writeFile(ne.join(e,"code.tsx"),r.code,"utf8"),await oe.writeFile(ne.join(e,"tb.d.ts"),Jl,"utf8"),{dir:e}}var Yl={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function CT(r,e,t=[]){return{compilerOptions:{...Yl,lib:RT([...Fl,...ql]),jsx:"react-jsx",jsxImportSource:r??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function RT(r){return Ul(r).map(e=>NT(e.name))}function NT(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 IT(r,e){let t=r??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function xo(r){if(!r.startsWith(Ng))return;let e=r.slice(Ng.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function $T(r,e){if(!r.typesAbs)return;let t=ne.dirname(r.typesAbs),n=ne.join(e,"node_modules",r.name);for(let s of await LT(t)){let i=ne.join(n,ne.relative(t,s));await oe.mkdir(ne.dirname(i),{recursive:!0}),await oe.copyFile(s,i)}return ne.basename(r.typesAbs)}async function LT(r){let e=[];async function t(n){let s=await oe.readdir(n,{withFileTypes:!0});for(let i of s){let o=ne.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 Xe from"path";import{existsSync as MT}from"fs";var DT="^22";async function $g(r){let e=ri(r.emitKey,"typecheck-server");await V(),await ye.rm(e,{recursive:!0,force:!0}),await ye.mkdir(e,{recursive:!0});let t=Xe.join(r.bulbDir,".typebulb"),n=fi(r.server).filter(o=>o!==r.local?.name);await di([`@types/node@${DT}`,...n],t,r.dependencies,{ignoreScripts:!0});let s=Xe.join(t,"node_modules"),i=Xe.join(e,"node_modules");return await jT(s,i),await ye.writeFile(Xe.join(e,"server.ts"),r.server,"utf8"),await ye.writeFile(Xe.join(e,"tb.d.ts"),Kl,"utf8"),await ye.writeFile(Xe.join(e,"tsconfig.json"),JSON.stringify(BT(r.local),null,2)+`
|
|
1602
|
+
`,"utf8"),{dir:e}}function BT(r){let e={...Yl,lib:["ES2023"],types:["node"]};if(r?.typesAbs){let t=i=>i.replace(/\\/g,"/"),n=t(Xe.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 jT(r,e){if(!MT(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)}Qs();async function Mg(r,e){let{bulb:t,config:n,warnings:s}=await ke(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=Lg(yn(t.code,{target:"client",dependencies:n.dependencies??{}}),"client")||i),t.server&&(i=Lg(yn(t.server,{target:"server"}),"server")||i);let o=WT([process.cwd(),xt.dirname(r)]);if(!o){let l=xt.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 Ig({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 $g({server:t.server,bulbDir:xt.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 KT(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 Lg(r,e){for(let t of r)for(let n of t.message.split(`
|
|
1603
|
+
`))console.log(`${e} ${n}`);return r.length>0}function KT(r,e){return new Promise(t=>{let n=FT(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 HT=UT(import.meta.url);function WT(r){let e=n=>{try{let s=HT.resolve("typescript/package.json",{paths:n}),i=xt.join(xt.dirname(s),"lib","tsc.js");return JT(i)?i:void 0}catch{return}},t=e(r);if(t)return t;try{let n=qT("npm root -g",{encoding:"utf8"}).trim();return e([n])}catch{return}}Bi();Cn();async function Dg(r,e){let{bulb:t}=await ke(r),n=kr(t);if(jt(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.)")}Cn();import*as Un from"path";async function Bg(r,e){if(!r){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let n=Xc();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)),wr(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}`)}Ne();import*as Ug from"readline";var Jn=yg();function jg(){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 Fg(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 Vl(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 Jg(r){let e=Fg(process.cwd());if("ambiguous"in e){let t=await YT(r,e.ambiguous);return t?qg(r,t):VT(r,e.ambiguous)}return qg(r,e.name)}async function qg(r,e){let t,n;try{t=await Cm(e)}catch(f){n=f instanceof Error?f.message:String(f)}let{lit:s,litLink:i,brand:o}=Vl(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(Er())}`,` ${s(Ut())}`],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(`
|
|
1603
1604
|
`)+`
|
|
1604
|
-
`)}async function
|
|
1605
|
+
`)}async function YT(r,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:n}=Vl(!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(`
|
|
1605
1606
|
`)+`
|
|
1606
|
-
`);let i=
|
|
1607
|
+
`);let i=Ug.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 VT(r,e){let{lit:t,brand:n}=Vl(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(`
|
|
1607
1608
|
`)+`
|
|
1608
|
-
`)}
|
|
1609
|
-
`+e)}function
|
|
1609
|
+
`)}yt();Bt();async function Kg(r){ge(r);let e=await He();if(e.length>0){console.log(cm(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!Wc()){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(gr))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 Hg from"fs/promises";async function Wg(r){let e=Ut(),t;try{t=await Hg.readFile(e,"utf8")}catch{console.error(`Could not read the bundled README (expected at ${e}).`),process.exit(1)}process.stdout.write(jm(t,r))}Ti();import*as Yg from"path";Ne();function GT(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&&re(o.cwd)===re(t));return n&&i.find(o=>o.agent===n)||i[0]}return r.find(i=>re(i.file)===re(e))}var Hn=r=>r.agent??Yg.basename(r.file);function Vg(r,e){for(let t of r)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"}${t.dir?` --dir ${t.dir}`:""} ${t.file}`)}function Gl(r,e){if(!r.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Vg(r,t=>console.log(t)),console.log(`
|
|
1610
|
+
`+e)}function zl(r,e,t,n,s){let i=GT(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>\`):`),Vg(r,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Gg(r,e){if(!r){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),Gl(await z(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=zl(await z(),r,"logs",process.cwd(),Kn());if(e.clear){Em(t.pid),console.log(`Cleared log for ${Hn(t)} (pid ${t.pid}).`);return}let n=Re(t.pid),s=n.text;if(e.run!==void 0&&(s=Am(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(`
|
|
1610
1611
|
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
1611
1612
|
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
1612
1613
|
`)&&process.stdout.write(`
|
|
1613
|
-
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=Re(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
|
|
1614
|
-
`);m=k.pop()??"";for(let T of k)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(!
|
|
1614
|
+
`),e.follow&&e.run===void 0){let i=n.offset,o=setInterval(()=>{let c=Re(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 zT=r=>new Promise(e=>setTimeout(e,r));async function zg(r,e){if(!r){Gl(await z(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=zl(await z(),r,"wait",process.cwd(),Kn()),n=t.agent!=null,i=process.env.TYPEBULB_WAIT_SHIM==="1",o=e.timeoutSec??1800,a=e.match??"",c=Re(t.pid).offset,l=cl(t.pid,a)??(a?cl(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 x=Re(t.pid,f);if(f=x.offset,x.text){m+=x.text;let k=m.split(`
|
|
1615
|
+
`);m=k.pop()??"";for(let T of k)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(!ul(t.pid)){y||(console.error(`server ${Hn(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await zT(400)}Ii(t.pid,f,a),process.exit(b)}async function Xg(r){if(!r){Gl(await z(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=zl(await z(),r,"stop",process.cwd(),Kn());await Ft(e.pid),console.log(`Stopped ${Hn(e)} (pid ${e.pid}, ${e.url}).`)}async function Qg(r){let e=process.cwd(),t=r==="agent"?Kn():void 0,n=r==="global"?await z():r==="bulbs"?await z(e):(await z()).filter(i=>i.agent!=null&&i.cwd!=null&&re(i.cwd)===re(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=>Ft(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)}`)}Ne();import*as Zg from"path";async function ey(r,e,t=0){let n=e!==void 0&&e.startsWith("tb:");n&&t<=0&&(t=Io);let s=Zg.resolve(r),i=xr(await z(),s)[0];i||(console.error(`No running server for '${r}'. Start it first: npx typebulb ${r}`),process.exit(1));let o=async d=>{let p=await fetch(`${i.url}/__send${d>0?`?reply=${d}`:""}`,{method:"POST",headers:{"Content-Type":"text/plain"},body:e??""});return p.ok||(console.error(`send failed: HTTP ${p.status} from ${i.url}/__send`),process.exit(1)),await p.json().catch(()=>({}))},a={};try{let d=Date.now()+t;do{if(a=await o(t>0?Math.max(d-Date.now(),1e3):0),(a.clients??0)>0||Date.now()>=d)break;await new Promise(p=>setTimeout(p,150))}while(!0)}catch(d){console.error(`send failed: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}let c=a.clients??0,l=`${c} page${c===1?"":"s"}`;if(c===0){t>0?console.error(`No page connected after ${t/1e3}s \u2014 is the bulb open?`):console.error("Sent, but no page is connected yet \u2014 open the bulb and retry."),n&&process.exit(1);return}console.error(`Sent to ${l}.`);let f=a.results??[],u=a.errors??[];for(let d of u)console.error(`handler error: ${d}`);if(u.length&&process.exit(1),f.length>1&&(console.error(`${f.length} replies from ${l} \u2014 one reply owns stdout: at most one tb.onMessage handler, in one page, may return a value.`),process.exit(1)),f.length===1){let d;try{d=JSON.parse(f[0])}catch{d=void 0}console.log(typeof d=="string"?d:f[0])}else a.timedOut&&(n&&(console.error(`No reply to '${e}' within ${t/1e3}s \u2014 reload the page and retry.`),process.exit(1)),console.error(`(no reply within ${t/1e3}s \u2014 a slow handler's return needs a larger --wait=ms)`))}Ki();vl();yt();import*as $r from"fs/promises";import*as ly from"path";import{EventEmitter as cy}from"events";Ue();Bi();import fP from"open";hr();Ue();import{Hono as rP}from"hono";import{serve as nP}from"@hono/node-server";import{streamSSE as sP}from"hono/streaming";import*as sy from"fs/promises";import*as iy from"path";import*as Xl 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([Xl.readFile(n),Xl.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await V();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 ty=`
|
|
1615
1616
|
const CSS = '\\n' +
|
|
1616
1617
|
/* The agent mirror's token set, verbatim (agents/core/client/styles.css) \u2014 one system across CLI
|
|
1617
1618
|
chrome: app chrome sits on --panel, content wells paint --veil, grays ride one neutral tint.
|
|
@@ -1915,17 +1916,17 @@ export function runInference(ctx) {
|
|
|
1915
1916
|
showConfirm();
|
|
1916
1917
|
document.body.appendChild(host);
|
|
1917
1918
|
}
|
|
1918
|
-
`;Ne();
|
|
1919
|
-
${d}`:"";return h.text(`Forbidden: this capability requires --trust.${R}`,403)}await
|
|
1920
|
-
`+Z.slice(-4e3)),new de("LLM output is not valid JSON","parse_error",!0);Y.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",Y.fixesApplied.join(", "));let
|
|
1919
|
+
`;Ne();Bt();Si();hr();import{stream as XT}from"hono/streaming";var QT="X-TB-Stream";function Yn(r){return r instanceof de?{message:r.message,code:r.code,retryable:r.retryable}:{message:r instanceof Error?r.message:"Unknown error",code:"unknown",retryable:!1}}function Eo(r,e){return r.header("Content-Type","application/x-ndjson; charset=utf-8"),r.header("Cache-Control","no-cache"),r.header(QT,"1"),XT(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 Ao={log:(...r)=>console.log(...r)};function To(r,e){let t=r?.[e]??(Object.hasOwn(Ao,e)?Ao[e]:void 0);return typeof t=="function"?t:void 0}function Po(r){return r.constructor?.name==="AsyncGeneratorFunction"}var ZT=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,eP=/[?&]target=/,tP=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function ry(r,e=""){return ZT.test(r)?!0:tP.test(r)&&eP.test(e)}var oy="127.0.0.1",iP=new Set(["localhost","127.0.0.1","::1"]);function oP(r){if(r)try{return new URL(r.includes("://")?r:`http://${r}`).hostname}catch{return}}function aP(r){let e=oP(r);return!!e&&iP.has(e)}function cP(r,e){if(!e)return!1;try{return new URL(r).host===e}catch{return!1}}function Ql(r){return r instanceof Error?r.message:"Unknown error"}async function ay(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 rP;m.use("*",async(h,v)=>{if(!aP(h.req.header("host")))return h.text("Forbidden: untrusted Host",403);await v()}),m.use("*",async(h,v)=>{await v(),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"]],x=async(h,v)=>{if(!u){let I=new URL(h.req.url).pathname,L=b.find(([K])=>K.endsWith("/*")?I.startsWith(K.slice(0,-2)):I===K)?.[1]??"server-side code (server.ts)";Pm(process.pid,L);let R=d?`
|
|
1920
|
+
${d}`:"";return h.text(`Forbidden: this capability requires --trust.${R}`,403)}await v()},k=async(h,v)=>{let I=h.req.header("sec-fetch-site");if(I){if(I!=="same-origin")return h.text(`Forbidden: ${I} request`,403)}else{let L=h.req.header("origin");if(L&&!cP(L,h.req.header("host")))return h.text("Forbidden: cross-origin request",403)}await v()};for(let[h]of b)m.use(h,x),m.use(h,k);if(m.use("/__log",k),m.post("/__log",async h=>{try{let{args:v}=await h.req.json();console.log(...v||[])}catch{}return h.json({ok:!0})}),o){let h=0,v=new Map;m.use("/__send",k),m.post("/__send",async I=>{let L="";try{L=await I.req.text()}catch{}let R=Number(I.req.query("reply"))||0,K=o.listenerCount("message");if(R<=0||K===0)return o.emit("message",{payload:L}),I.json({clients:K});let W=++h,Be=await new Promise(Z=>{let Y={expected:K,received:0,results:[],errors:[],finish:Te=>{clearTimeout(je),v.delete(W),Z({results:Y.results,errors:Y.errors,timedOut:Te})}},je=setTimeout(()=>Y.finish(!0),R);v.set(W,Y),o.emit("message",{id:W,payload:L})});return I.json({clients:K,...Be})}),m.use("/__send-reply",k),m.post("/__send-reply",async I=>{try{let{id:L,results:R,errors:K}=await I.req.json(),W=v.get(L);W&&(W.results.push(...R??[]),W.errors.push(...K??[]),++W.received>=W.expected&&W.finish(!1))}catch{}return I.json({ok:!0})})}m.get("/",h=>h.html(e())),m.post("/__fs/read",async h=>{try{let{path:v}=await h.req.json(),I=await On(v,y,t);return new Response(new Uint8Array(I),{headers:{"Content-Type":"application/octet-stream"}})}catch(v){let I=Ql(v);return h.json({error:I},400)}}),m.post("/__fs/write",async h=>{try{let v=h.req.query("path");return v?(await ki(v,new Uint8Array(await h.req.arrayBuffer()),y,t),h.json({success:!0})):h.json({error:"Missing path"},400)}catch(v){let I=Ql(v);return h.json({error:I},400)}}),m.post("/__api/:name",async h=>{try{let v=h.req.param("name"),I=To(a?.(),v);if(!I)return h.json({error:`API function '${v}' not found`},404);let{args:L}=await h.req.json();if(Po(I))return Eo(h,I(...L||[]));let R=await I(...L||[]);return h.json({result:R})}catch(v){let I=Ql(v);return h.json({error:I},500)}}),m.post("/__ai",async h=>{try{let{messages:v,system:I,effort:L,provider:R,model:K,webSearch:W,stream:Be}=await h.req.json();if(!v||!Array.isArray(v)||v.length===0)return h.json({message:"messages array is required",code:"unknown",retryable:!1},400);let Z=We(R,K);if(typeof Z=="string")return h.json({message:Z,code:"unknown",retryable:!1},400);let Y=await pt(Z,{messages:v,system:I,effort:L,webSearch:W,signal:h.req.raw.signal});if(!Y.ok){let Te=await mr(Y,Z.protocol);return h.json(Te,Y.status)}if(Be)return Eo(h,Dt(Y,Z.protocol));let je=await Mt(Y,Z.protocol);return je||console.warn("[tb.ai] Empty response from provider"),h.json({text:je})}catch(v){return h.json(Yn(v),500)}}),m.post("/__infer",async h=>{try{let{data:v}=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 L=We();if(typeof L=="string")return h.json({message:L,code:"unknown",retryable:!1},400);let R=Array.isArray(v)?v.map(String):[],K=qc(I,R),W=await pt(L,{messages:[{role:"user",content:K}],signal:h.req.raw.signal});if(!W.ok){let Z=await mr(W,L.protocol);return h.json(Z,W.status)}let Be=(async function*(){let Z="";for await(let Te of Dt(W,L.protocol))Te.kind!=="text"||!Te.text||(Z+=Te.text,yield{kind:"delta",text:Te.text});let Y=Uc(Z);if(Y.parsed===null)throw console.warn(`[tb.infer] output not valid JSON after sanitize; raw output (last 4000 chars):
|
|
1921
|
+
`+Z.slice(-4e3)),new de("LLM output is not valid JSON","parse_error",!0);Y.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",Y.fixesApplied.join(", "));let je={insight:Y.parsed,insightJson:Y.json,data:R};yield{kind:"complete",...je,fixesApplied:Y.fixesApplied,hash:Jc(je)}})();return Eo(h,Be)}catch(v){return h.json(Yn(v),500)}});let T=async h=>{let{hash:v}=await h.req.json().catch(()=>({}));return typeof v=="string"?Kc(v):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 v=await T(h);return v?(await l(v.data,v.insightJson),h.json({ok:!0})):h.json({message:"No decodable #tb= fragment to save.",code:"unknown",retryable:!1},400)}catch(v){return h.json(Yn(v),500)}}),m.get("/__infer-info",h=>{let v=c?.(),I=Lr(v?.config??"").inference,L=zs(v?.data??""),R=We();return typeof R=="string"?h.json({error:R,inference:I,data:L}):h.json({provider:R.protocol,model:R.model,inference:I,data:L})}),m.use("/__infer-decode",k),m.post("/__infer-decode",async h=>h.json(await T(h)??{error:"invalid fragment"})),m.get("/__infer-ui.js",h=>h.body(ty,200,{"Content-Type":"text/javascript; charset=utf-8"})),m.get("/__models",async h=>{try{let v=await He();return h.json(v)}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 v=new URL(h.req.url),L=(v.pathname+v.search).slice(7),R=L.lastIndexOf("https://");return R===-1?h.text("Invalid proxy URL",400):_(h,L.slice(R))}),f&&ny(m,`/local/${f.name}/`,f.serveDir),p&&ny(m,p.mount,p.dir);async function _(h,v){let I;try{I=new URL(v)}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 L=await C.get(v);if(L)return new Response(L.body,{status:200,headers:Zl(L.contentType,L.cacheControl)});try{let R=await fetch(v,{headers:{Accept:h.req.header("Accept")||"*/*"},redirect:"follow"});if(!R.ok)return h.text(`Upstream ${R.status}`,R.status);let K=R.headers.get("Content-Type")||void 0,W=R.headers.get("Cache-Control")||void 0;if(R.body){let[Be,Z]=R.body.tee();return(async()=>{try{let Y=await new Response(Z).arrayBuffer();await C.set(v,{body:Buffer.from(Y),contentType:K,cacheControl:W})}catch{}})(),new Response(Be,{status:R.status,headers:Zl(K,W)})}return new Response(null,{status:R.status,headers:Zl(K,W)})}catch(R){return h.text(`Proxy fetch failed: ${R instanceof Error?R.message:R}`,502)}}(i||o)&&m.get("/__reload",h=>sP(h,async v=>{let I=()=>{v.writeSSE({event:"reload",data:""})},L=R=>{v.writeSSE({event:"message",data:JSON.stringify(R)})};for(i?.on("reload",I),o?.on("message",L),v.onAbort(()=>{i?.removeListener("reload",I),o?.removeListener("message",L)});!v.aborted;)await v.sleep(3e4)})),m.notFound(async h=>{if(h.req.method!=="GET")return h.text("Not Found",404);let v=new URL(h.req.url);return ry(v.pathname,v.search)?_(h,"https://esm.sh"+v.pathname+v.search):h.text("Not Found",404)});let N=nP({fetch:m.fetch,port:s,hostname:oy});return{port:s,close:()=>N.close()}}function Zl(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 ny(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=xi(i,t),a=await sy.readFile(o);return new Response(a,{headers:{"Content-Type":lP(o)}})}catch{return n.text("Not Found",404)}})}function lP(r){switch(iy.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 eu(r){let e=await import("net");return new Promise(t=>{let n=e.createServer();n.listen(r,oy,()=>{let s=n.address(),i=typeof s=="object"&&s?s.port:r;n.close(()=>t(i))}),n.on("error",()=>{t(eu(r+1))})})}Ne();async function Oo(r){let{portPreference:e,makeServerOptions:t,makeEntry:n,displayName:s,stopLog:i}=r,o=await eu(e),a=await ay(t(o)),c=`http://localhost:${o}`;await Tm(n(o,c)),console.log(`
|
|
1921
1922
|
${s}`),console.log(` ${c}`),o!==e&&console.log(` (port ${e} was busy)`);let l=[],f=async()=>{console.log(`
|
|
1922
|
-
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
|
|
1923
|
+
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 uP from"chokidar";var dP={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Vt(r){let{target:e,onChange:t,events:n="change",debounceMs:s=150}=r,i,o=uP.watch(e,dP),a=()=>{i&&clearTimeout(i),i=setTimeout(t,s)};return n==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}Ne();async function uy(r,e,t,n){let s=process.cwd(),i=$i(process.pid),o=e.watch?new cy:void 0,a=new cy;a.setMaxListeners(0);let c=ge(e.mode),l=await fl(r);l.length&&console.log(`Replacing the running server for this bulb (pid ${l.map(P=>P.pid).join(", ")})`);let f=1;console.log(ll(f)),console.log(`Loading ${ly.basename(r)}...`);let{html:u,bulb:d,serverExports:p}=await Vc(r,e.watch,e.trust,n,e.dir);gt(c,r,d.server);let y=e.trust?void 0:kr(d),{port:m,url:b,onCleanup:x}=await Oo({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,_)=>{let N=await $r.readFile(r,"utf-8");N=Bo(N,"data",C.join(_p)),N=Bo(N,"insight",_),await $r.writeFile(r,N)},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,dir:e.dir,mode:e.mode,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:
|
|
1923
1924
|
${t}
|
|
1924
1925
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
1925
1926
|
`),e.watch&&console.log(` Watching for changes...
|
|
1926
|
-
`);let k,T;if(e.watch&&o){let P=0,
|
|
1927
|
-
`),o.emit("reload")}})}}k&&x(k),T&&x(T),x(()=>$r.rm(
|
|
1928
|
-
`):await
|
|
1927
|
+
`);let k,T;if(e.watch&&o){let P=0,C=Promise.resolve();if(k=Vt({target:r,onChange:()=>{let _=++P;C=C.then(async()=>{if(_===P)try{console.log("Recompiling...");let N=await Vc(r,!0,e.trust,n,e.dir);u=N.html,p=N.serverExports,d=N.bulb,f++,console.log(ll(f)),o.emit("reload")}catch(N){console.error("Compile error:",N)}})}}),n){let{name:_,serveDir:N}=n;T=Vt({target:N,events:"all",onChange:()=>{console.log(`Local package '${_}' changed. Browser reloading...
|
|
1928
|
+
`),o.emit("reload")}})}}k&&x(k),T&&x(T),x(()=>$r.rm(Yc(r),{force:!0})),e.open&&(l.some(P=>P.port===m)?console.log(` Reusing the open browser tab.
|
|
1929
|
+
`):await fP(b))}yt();import{readFileSync as fy,copyFileSync as mP,existsSync as hP}from"fs";import*as se from"path";import{fileURLToPath as gP}from"url";import{EventEmitter as yP}from"events";import py from"open";Ne();var tu=r=>`/agents/${r}/client.js`,pP=`
|
|
1929
1930
|
(() => {
|
|
1930
1931
|
const api = async (name, ...args) => {
|
|
1931
1932
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -1960,7 +1961,7 @@ Shutting down...`),a.close();for(let u of l)try{await u()}catch{}i(),await In(pr
|
|
|
1960
1961
|
es.onerror = () => { es.close(); };
|
|
1961
1962
|
}
|
|
1962
1963
|
})();
|
|
1963
|
-
`;function
|
|
1964
|
+
`;function dy(r){let{name:e,agent:t,styles:n,mountHtml:s,watch:i,theme:o}=r,a=tu(t);return`<!DOCTYPE html>
|
|
1964
1965
|
<html>
|
|
1965
1966
|
<head>
|
|
1966
1967
|
<meta charset="utf-8">
|
|
@@ -1980,17 +1981,17 @@ ${s}
|
|
|
1980
1981
|
${i?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
|
|
1981
1982
|
|
|
1982
1983
|
<script>
|
|
1983
|
-
${
|
|
1984
|
+
${pP}
|
|
1984
1985
|
</script>
|
|
1985
1986
|
|
|
1986
1987
|
<script type="module" src="${a}"></script>
|
|
1987
1988
|
</body>
|
|
1988
|
-
</html>`}async function
|
|
1989
|
-
${n.url}`),r.open&&await
|
|
1990
|
-
`);let k=se.join(u,t,"client"),T=se.join(u,"core","client");async function P(){await(await import("esbuild")).build({entryPoints:[se.join(k,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:se.join(f,"client.js")});for(let N of["styles.css","index.html","typebulb.png","typebulb-inv.png"])
|
|
1991
|
-
`),i.emit("reload")}catch(h){console.error("Mirror rebuild failed:",h instanceof Error?h.message:h)}finally{N=!1}}}})}r.open&&await
|
|
1992
|
-
`);let c=0,l=Promise.resolve();
|
|
1993
|
-
`)}catch(p){Vn(p instanceof Error?p.stack??p.message:String(p))}return
|
|
1994
|
-
`),
|
|
1995
|
-
`),process.exit(1)}function
|
|
1996
|
-
${e}`),process.exit(1))}async function
|
|
1989
|
+
</html>`}async function my(r){let e=process.cwd(),t=r.agentTarget;gg(t)||(console.error(`Unknown agent '${t}'. Known: ${Rr().join(", ")}.`),process.exit(1));let n=await dl(e,t);if(n){console.log(`Mirror '${t}' is already running for this project:
|
|
1990
|
+
${n.url}`),r.open&&await py(n.url);return}let s=$i(process.pid),i=r.watch?new yP:void 0,o=ge(r.mode),a=await bg(t),c=a.displayName||`${t} mirror`;gt(o,se.join(e,"mirror"));let l=se.dirname(gP(import.meta.url)),f=se.join(l,"agents",t),u=se.join(l,"..","cli","agents"),d=se.join(f,"styles.css"),p=se.join(f,"index.html"),y=()=>dy({name:c,agent:t,styles:fy(d,"utf8"),mountHtml:fy(p,"utf8"),watch:r.watch}),{port:m,url:b,onCleanup:x}=await Oo({portPreference:r.port,displayName:c,stopLog:s,makeServerOptions:_=>({getHtml:y,basePath:e,port:_,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${se.posix.dirname(tu(t))}/`,dir:f}}),makeEntry:(_,N)=>({pid:process.pid,port:_,url:N,file:`agent:${t}`,cwd:e,startedAt:Date.now(),trust:!0,agent:t})});r.watch&&console.log(` Watching for changes...
|
|
1991
|
+
`);let k=se.join(u,t,"client"),T=se.join(u,"core","client");async function P(){await(await import("esbuild")).build({entryPoints:[se.join(k,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:se.join(f,"client.js")});for(let N of["styles.css","index.html","typebulb.png","typebulb-inv.png"])mP(se.join(T,N),se.join(f,N))}let C;if(r.watch&&i){let _=hP(k),N=!1;C=Vt({target:_?u:f,events:"all",onChange:async()=>{if(!N){N=!0;try{_&&await P(),console.log(`Mirror rebuilt. Browser reloading...
|
|
1992
|
+
`),i.emit("reload")}catch(h){console.error("Mirror rebuild failed:",h instanceof Error?h.message:h)}finally{N=!1}}}})}r.open&&await py(b),x(()=>a.shutdownSwitcher?.()),x(()=>a.shutdownComposer?.()),C&&x(C)}yt();import*as hy from"path";async function gy(r,e,t,n,s){let i=ge(t),o=!1,a=async()=>{let{bulb:c,config:l}=await ke(r);o||(gt(i,r,c.server),o=!0),await _n(c.server,r,n,l.dependencies,s)};if(console.log(`Running ${hy.basename(r)}...`),await a(),e){console.log(`Watching for changes...
|
|
1993
|
+
`);let c=0,l=Promise.resolve();Vt({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)}})}})}}yt();import{Console as bP}from"node:console";Ne();async function wy(r,e,t,n,s){kP();try{let p=xr(await z(),r)[0];p&&(Ii(p.pid,Re(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 ke(r);o.server||Vn("This bulb has no **server.ts** block; nothing to call."),gt(i,r,o.server);let c;try{c=await _n(o.server,r,n,a.dependencies,s)}catch(p){Vn(p instanceof Error?p.message:String(p))}let l=To(c,e.fn);if(!l){let p=[...Object.keys(c).filter(y=>typeof c[y]=="function"),...Object.keys(Ao)];Vn(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let f=await wP(e);if(Po(l)){try{for await(let p of l(...f))await by(JSON.stringify(p,vy)+`
|
|
1994
|
+
`)}catch(p){Vn(p instanceof Error?p.stack??p.message:String(p))}return yy(0)}let u;try{u=await l(...f)}catch(p){Vn(p instanceof Error?p.stack??p.message:String(p))}let d=xP(u);d!==void 0&&await by(d+`
|
|
1995
|
+
`),yy(0)}function yy(r){process.exitCode=r,setTimeout(()=>process.exit(r),2e3).unref?.()}async function wP(r){if(r.hasArgsFlag){let e=r.argsJson??"";return e==="-"&&(e=await EP()),SP(e)}return vP(r.positional)}function vP(r){return r.map(e=>{try{return JSON.parse(e)}catch{return e}})}function SP(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 xP(r){if(r!==void 0)return JSON.stringify(r,vy,2)}function vy(r,e){return typeof e=="bigint"?e.toString():e}function Vn(r){process.stderr.write(r+`
|
|
1996
|
+
`),process.exit(1)}function kP(){let r=new bP(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 by(r){return new Promise((e,t)=>{process.stdout.write(r,n=>n?t(n):e())})}async function EP(){let r=[];for await(let e of process.stdin)r.push(e);return Buffer.concat(r).toString("utf-8")}var ru="0.31.2";function Sy(r,e){r||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
1997
|
+
${e}`),process.exit(1))}async function AP(){let r=bu(process.argv.slice(2));if(r.version&&(console.log(`typebulb ${ru}`),process.exit(0)),r.help&&(wu(),process.exit(0)),jg(),r.subcommand==="logs"){await Gg(r.file||void 0,{follow:r.follow,clear:r.clear,run:r.run,lines:r.lines});return}if(r.subcommand==="wait"){await zg(r.file||void 0,{match:r.match,timeoutSec:r.timeoutSec});return}if(r.subcommand==="stop"){r.stopScope?await Qg(r.stopScope):await Xg(r.file||void 0);return}if(r.subcommand==="send"){await ey(r.file,r.sendMessage,r.sendWaitMs??0);return}if(r.subcommand==="skill"){await Wg(ru);return}if(r.subcommand==="models"){await Kg(r.mode);return}if(r.subcommand==="pull"){await Jm(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="push"){await Wm(r.file||void 0,{force:r.force,mode:r.mode});return}if(r.subcommand==="agent"){await(r.agentTarget?my(r):Jg(ru));return}if(r.subcommand==="trust"||r.subcommand==="untrust"){await Bg(r.file||void 0,r.subcommand==="trust");return}let e;if(!r.file||r.file==="."){let c=await dm(process.cwd());c||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=c}else e=Gt.resolve(r.file);await xy.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:Gt.relative(process.cwd(),e)||Gt.basename(e),s=`npx typebulb --trust ${n.includes(" ")?`"${n}"`:n}`;if(r.subcommand==="predict"){await Dg(e,s);return}let i=!r.noTrust&&jt(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 ke(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 hu(r.local)}catch(c){console.error(c instanceof Error?c.message:String(c)),process.exit(1)}console.error(`replace: ${a.name} \u2192 ${Gt.relative(process.cwd(),a.dir)||"."}`)}if(r.subcommand==="check"){await Mg(e,a);return}if(r.subcommand==="call"){Sy(r.trust,s),await wy(e,{fn:r.fn,positional:r.callArgs,argsJson:r.argsJson,hasArgsFlag:r.hasArgsFlag},r.mode,a,r.dir);return}if(o&&o.bulb.server&&(Xs(o.bulb)||r.server)){Sy(r.trust,s),await gy(e,r.watch,r.mode,a,r.dir);return}await uy(e,r,s,a)}AP().catch(r=>{console.error("Error:",r.message),process.exit(1)});
|